text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Remove unused traits in Article Get Most Recent Integration Test
<?php namespace RCatlin\Blog\Test\Integration\Controller\Api; use League\FactoryMuffin\Facade as FactoryMuffin; use RCatlin\Blog\Entity; use RCatlin\Blog\Test\Integration\AbstractIntegrationTest; use RCatlin\Blog\Test\LoadsFactoryMuffinFactories; use RCatlin\Blog\Test\ReadsResponseContent; class ArticleControllerGetMostRecentTest extends AbstractIntegrationTest { use LoadsFactoryMuffinFactories; use ReadsResponseContent; public function testGetMostRecent() { /** @var Entity\Article $article0 */ $article0 = FactoryMuffin::create(Entity\Article::class, [ 'active' => true, 'createdAt' => 'dateTimeBetween|-3 days;-2 days', 'tagCount' => 0, ]); /** @var Entity\Article $article1 */ $article1 = FactoryMuffin::create(Entity\Article::class, [ 'active' => true, 'createdAt' => 'dateTimeBetween|-1 day;now', 'tagCount' => 0, ]); $response = $this->client->get('/api/articles/mostrecent'); $this->assertSame(200, $response->getStatusCode()); $content = json_decode($this->readResponse($response), true); $this->assertSame($article1->getId(), $content['result']['data']['id']); } }
<?php namespace RCatlin\Blog\Test\Integration\Controller\Api; use League\FactoryMuffin\Facade as FactoryMuffin; use RCatlin\Blog\Entity; use RCatlin\Blog\Test\CreatesGuzzleStream; use RCatlin\Blog\Test\HasFaker; use RCatlin\Blog\Test\Integration\AbstractIntegrationTest; use RCatlin\Blog\Test\LoadsFactoryMuffinFactories; use RCatlin\Blog\Test\ReadsResponseContent; class ArticleControllerGetMostRecentTest extends AbstractIntegrationTest { use CreatesGuzzleStream; use HasFaker; use LoadsFactoryMuffinFactories; use ReadsResponseContent; public function testGetMostRecent() { /** @var Entity\Article $article0 */ $article0 = FactoryMuffin::create(Entity\Article::class, [ 'active' => true, 'createdAt' => 'dateTimeBetween|-3 days;-2 days', 'tagCount' => 0, ]); /** @var Entity\Article $article1 */ $article1 = FactoryMuffin::create(Entity\Article::class, [ 'active' => true, 'createdAt' => 'dateTimeBetween|-1 day;now', 'tagCount' => 0, ]); $response = $this->client->get('/api/articles/mostrecent'); $this->assertSame(200, $response->getStatusCode()); $content = json_decode($this->readResponse($response), true); $this->assertSame($article1->getId(), $content['result']['data']['id']); } }
application: Add error() function to Output class
<?php /** * Output library * @author M2Mobi, Heinz Wiesinger */ class Output { /** * Constructor */ public function __construct() { } /** * Destructor */ public function __destruct() { } /** * Print given message immediatly * @param String $msg Message to print * @return void */ public static function cli_print($msg) { require_once("class.m2datetime.inc.php"); echo M2DateTime::get_datetime() . ": " . $msg; } /** * Print status information ([ok] or [failed]) * @param String $msg Message to print * @return void */ public static function cli_print_status($bool) { require_once("class.m2datetime.inc.php"); if ($bool === TRUE) { echo "[ok]\n"; } else { echo "[failed]\n"; } } /** * Print given message immediatly * @param String $msg Message to print * @return void */ public static function cli_println($msg) { require_once("class.m2datetime.inc.php"); echo M2DateTime::get_datetime() . ": " . $msg . "\n"; } /** * Trigger a PHP error * @param String $info The error string that should be printed * @return void */ public static function error($info) { if (isset($_GET['controller']) && isset($_GET['method'])) { trigger_error($_GET['controller'] . "/" . $_GET['method'] . ": " . $info); } else { trigger_error($info); } } } ?>
<?php /** * Output library * @author M2Mobi, Heinz Wiesinger */ class Output { /** * Constructor */ public function __construct() { } /** * Destructor */ public function __destruct() { } /** * Print given message immediatly * @param String $msg Message to print * @return void */ public static function cli_print($msg) { require_once("class.m2datetime.inc.php"); echo M2DateTime::get_datetime() . ": " . $msg; } /** * Print status information ([ok] or [failed]) * @param String $msg Message to print * @return void */ public static function cli_print_status($bool) { require_once("class.m2datetime.inc.php"); if ($bool === TRUE) { echo "[ok]\n"; } else { echo "[failed]\n"; } } /** * Print given message immediatly * @param String $msg Message to print * @return void */ public static function cli_println($msg) { require_once("class.m2datetime.inc.php"); echo M2DateTime::get_datetime() . ": " . $msg . "\n"; } } ?>
Use Force Segment write key
import React from 'react' import ReactDOM from 'react-dom/server' import request from 'superagent' import { DisplayPanel } from '@artsy/reaction-force/dist/Components/Publishing/Display/DisplayPanel' import { ServerStyleSheet } from 'styled-components' import { DisplayQuery } from 'client/apps/display/query' const { API_URL, NODE_ENV, SEGMENT_WRITE_KEY_FORCE, WEBFONT_URL } = process.env export const display = (req, res, next) => { res.setHeader('X-Frame-Options', '*') request .post(API_URL + '/graphql') .set('Accept', 'application/json') .query({ query: DisplayQuery }) .end((err, response) => { if (err) { return next(err) } const display = response.body.data.display let css = '' let body = '' if (display) { const DisplayPanelComponent = React.createFactory(DisplayPanel) const sheet = new ServerStyleSheet() body = ReactDOM.renderToString( sheet.collectStyles( DisplayPanelComponent({ unit: display.panel, campaign: display }) ) ) css = sheet.getStyleTags() } res.locals.sd.CAMPAIGN = display res.render('index', { css, body, fallback: !display, nodeEnv: NODE_ENV, segmentWriteKey: SEGMENT_WRITE_KEY_FORCE, webfontUrl: WEBFONT_URL }) }) }
import React from 'react' import ReactDOM from 'react-dom/server' import request from 'superagent' import { DisplayPanel } from '@artsy/reaction-force/dist/Components/Publishing/Display/DisplayPanel' import { ServerStyleSheet } from 'styled-components' import { DisplayQuery } from 'client/apps/display/query' const { API_URL, NODE_ENV, SEGMENT_WRITE_KEY_MICROGRAVITY, WEBFONT_URL } = process.env export const display = (req, res, next) => { res.setHeader('X-Frame-Options', '*') request .post(API_URL + '/graphql') .set('Accept', 'application/json') .query({ query: DisplayQuery }) .end((err, response) => { if (err) { return next(err) } const display = response.body.data.display let css = '' let body = '' if (display) { const DisplayPanelComponent = React.createFactory(DisplayPanel) const sheet = new ServerStyleSheet() body = ReactDOM.renderToString( sheet.collectStyles( DisplayPanelComponent({ unit: display.panel, campaign: display }) ) ) css = sheet.getStyleTags() } res.locals.sd.CAMPAIGN = display res.render('index', { css, body, fallback: !display, nodeEnv: NODE_ENV, segmentWriteKey: SEGMENT_WRITE_KEY_MICROGRAVITY, webfontUrl: WEBFONT_URL }) }) }
Support configuring SOCKS proxy in the example
#!/usr/bin/env python3 import traceback from telethon_examples.interactive_telegram_client \ import InteractiveTelegramClient 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() kwargs = {} if settings.get('socks_proxy'): import socks # $ pip install pysocks host, port = settings['socks_proxy'].split(':') kwargs = dict(proxy=(socks.SOCKS5, host, int(port))) 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']), **kwargs) print('Initialization done!') try: client.run() except Exception as e: print('Unexpected error ({}): {} at\n{}'.format( type(e), e, traceback.format_exc())) finally: client.disconnect() print('Thanks for trying the interactive example! Exiting...')
#!/usr/bin/env python3 import traceback from telethon_examples.interactive_telegram_client \ import InteractiveTelegramClient 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: client.disconnect() print('Thanks for trying the interactive example! Exiting...')
Fix quoting for MANIFEST.MF Import-Package
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.jar.Attributes; import java.util.jar.Manifest; /** * Used by re-version.sh. Not included in normal compile so it doesn't accidentally end up in artifacts. * Need it to be a java class to handle weird manifest lines */ public class ManifestReversion { public static void main(String[] args) throws Exception { String filename = args[0]; String version = args[1] .replaceFirst("^v", ""); Manifest manifest; try (InputStream input = new FileInputStream(filename)) { manifest = new Manifest(input); } final Attributes attributes = manifest.getMainAttributes(); attributes.putValue("Liquibase-Version", version); final String bundleVersion = attributes.getValue("Bundle-Version"); if (bundleVersion != null) { attributes.putValue("Bundle-Version", version); } final String importPackage = attributes.getValue("Import-Package"); if (importPackage != null) { attributes.putValue("Import-Package", importPackage.replaceAll("version=\"\\[0\\.0,1\\)\"", "version=\"[" + version + ",1)\"")); } final String exportPackage = attributes.getValue("Export-Package"); if (exportPackage != null) { attributes.putValue("Export-Package", exportPackage.replaceAll(";version=\"0\\.0\\.0\"", ";version=\"" + version + "\"")); } try (OutputStream out = new FileOutputStream(filename)) { manifest.write(out); } } }
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.jar.Attributes; import java.util.jar.Manifest; /** * Used by re-version.sh. Not included in normal compile so it doesn't accidentally end up in artifacts. * Need it to be a java class to handle weird manifest lines */ public class ManifestReversion { public static void main(String[] args) throws Exception { String filename = args[0]; String version = args[1] .replaceFirst("^v", ""); Manifest manifest; try (InputStream input = new FileInputStream(filename)) { manifest = new Manifest(input); } final Attributes attributes = manifest.getMainAttributes(); attributes.putValue("Liquibase-Version", version); final String bundleVersion = attributes.getValue("Bundle-Version"); if (bundleVersion != null) { attributes.putValue("Bundle-Version", version); } final String importPackage = attributes.getValue("Import-Package"); if (importPackage != null) { attributes.putValue("Import-Package", importPackage.replaceAll("version=\"\\[0\\.0,1\\)\"", "version=\"[" + version + ",1)")); } final String exportPackage = attributes.getValue("Export-Package"); if (exportPackage != null) { attributes.putValue("Export-Package", exportPackage.replaceAll(";version=\"0\\.0\\.0\"", ";version=\"" + version + "\"")); } try (OutputStream out = new FileOutputStream(filename)) { manifest.write(out); } } }
Add IPv6 to trusted proxies list
<?php namespace Strimoid\Providers; use Carbon\Carbon; use GuzzleHttp\Client; use Illuminate\Pagination\Paginator; use Illuminate\Support\ServiceProvider; use Pdp\Parser; use Pdp\PublicSuffixListManager; use Strimoid\Helpers\OEmbed; class AppServiceProvider extends ServiceProvider { public function boot() { if ($this->app->environment('local')) { $this->app->register('Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider'); $this->app->register('Barryvdh\Debugbar\ServiceProvider'); } $dsn = config('services.raven.dsn'); if (!empty($dsn)) { $this->app->register(\Jenssegers\Raven\RavenServiceProvider::class); } $locale = config('app.locale'); Carbon::setLocale($locale); Paginator::$defaultView = 'pagination::bootstrap-4'; Paginator::$defaultSimpleView = 'pagination::simple-bootstrap-4'; \Request::setTrustedProxies(['172.16.0.0/16', 'fd00::/8']); } public function register() { $this->app->bind('guzzle', function () { return new Client([ 'connect_timeout' => 3, 'timeout' => 10, ]); }); $this->app->bind('pdp', function () { $pslManager = new PublicSuffixListManager(); $parser = new Parser($pslManager->getList()); return $parser; }); $this->app->bind('oembed', function () { return new OEmbed(); }); } }
<?php namespace Strimoid\Providers; use Carbon\Carbon; use GuzzleHttp\Client; use Illuminate\Pagination\Paginator; use Illuminate\Support\ServiceProvider; use Pdp\Parser; use Pdp\PublicSuffixListManager; use Strimoid\Helpers\OEmbed; class AppServiceProvider extends ServiceProvider { public function boot() { if ($this->app->environment('local')) { $this->app->register('Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider'); $this->app->register('Barryvdh\Debugbar\ServiceProvider'); } $dsn = config('services.raven.dsn'); if (!empty($dsn)) { $this->app->register(\Jenssegers\Raven\RavenServiceProvider::class); } $locale = config('app.locale'); Carbon::setLocale($locale); Paginator::$defaultView = 'pagination::bootstrap-4'; Paginator::$defaultSimpleView = 'pagination::simple-bootstrap-4'; \Request::setTrustedProxies(['172.16.0.0/16']); } public function register() { $this->app->bind('guzzle', function () { return new Client([ 'connect_timeout' => 3, 'timeout' => 10, ]); }); $this->app->bind('pdp', function () { $pslManager = new PublicSuffixListManager(); $parser = new Parser($pslManager->getList()); return $parser; }); $this->app->bind('oembed', function () { return new OEmbed(); }); } }
Fix issue with deletewatcher causing application crash
import BaseWatcher from './BaseWatcher'; class DeleteWatcher extends BaseWatcher { constructor(bot) { super(bot); } /** * The method this watcher should listen on. * * @type {string[]} */ method = [ 'messageDelete', 'messageDeleteBulk' ]; shouldRun(method, message) { if (!super.shouldRun(method, message)) { return false; } // don't log deletion of bot messages if (message.author && message.author.bot) { return false; } return true; } action(method, message) { // check if we're getting a collection of messages or not if (method === 'messageDeleteBulk') { message.forEach((value) => { this.logMessage(value) }); } else { this.logMessage(message); } } logMessage(message) { let messageToSend = ''; if (message.author) { messageToSend = `**User:** ${message.author} (${message.author.username}#${message.author.discriminator})\n**Action:** message removed\n**Channel:** ${message.channel}\n**Message:**\`\`\`${message.cleanContent}\`\`\``; } else { messageToSend = `**User:** Unknown\n**Action:** message removed\n**Channel:** ${message.channel}\n**Message:**\`\`\`${message.cleanContent}\`\`\``; } this.sendMessageToModeratorLogsChannel(messageToSend); } } export default DeleteWatcher;
import BaseWatcher from './BaseWatcher'; class DeleteWatcher extends BaseWatcher { constructor(bot) { super(bot); } /** * The method this watcher should listen on. * * @type {string[]} */ method = [ 'messageDelete', 'messageDeleteBulk' ]; shouldRun(method, message) { if (!super.shouldRun(method, message)) { return false; } // don't log deletion of bot messages if (message.author.bot) { return false; } return true; } action(method, message) { // check if we're getting a collection of messages or not if (method === 'messageDeleteBulk') { message.forEach((value) => { this.logMessage(value) }); } else { this.logMessage(message); } } logMessage(message) { const messageToSend = `**User:** ${message.author} (${message.author.username}#${message.author.discriminator})\n**Action:** message removed\n**Channel:** ${message.channel}\n**Message:**\`\`\`${message.cleanContent}\`\`\``; this.sendMessageToModeratorLogsChannel(messageToSend); } } export default DeleteWatcher;
Allow to configure user class
<?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'])); } if(isset($config['user_class'])) { $container->setParameter('doctrine_user.user_object.class', $config['user_class']); } } /** * 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 \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'; } }
Throw exception if class is not found rather than returning null
<?php namespace AppBundle\API; use Symfony\Component\Config\Definition\Exception\Exception; use Symfony\Component\HttpFoundation\ParameterBag; use Symfony\Component\HttpFoundation\Session\SessionInterface; class Webservice { const ERROR_NOT_LOGGED_IN = "Error. Not logged in."; private $DB; public function __construct(\AppBundle\DB $DB) { $this->DB = $DB; } /** * @param ParameterBag $query * @param SessionInterface $session * @return array result */ public function execute(ParameterBag $query, SessionInterface $session = null){ return array(); } /** * @param $namespace string * @param $classname string * @throws Exception * @return Webservice */ public function factory($namespace, $classname) { $serviceNamespace = '\\AppBundle\\API\\' . ucfirst($namespace); $class = $serviceNamespace . '\\' . ucfirst($classname); if (!class_exists($class)) { throw new Exception("Could not find class: ".$namespace."\\".$class); } return new $class($this->DB); } /** * @param $query ParameterBag * @return \PDO db connection */ protected function getDbFromQuery($query){ if (! $query->has('dbversion')){ throw new Exception('No valid dbversion provided'); } return $this->DB->getDbForVersion($query->get('dbversion')); } }
<?php namespace AppBundle\API; use Symfony\Component\Config\Definition\Exception\Exception; use Symfony\Component\HttpFoundation\ParameterBag; use Symfony\Component\HttpFoundation\Session\SessionInterface; class Webservice { const ERROR_NOT_LOGGED_IN = "Error. Not logged in."; private $DB; public function __construct(\AppBundle\DB $DB) { $this->DB = $DB; } /** * @param ParameterBag $query * @param SessionInterface $session * @return array result */ public function execute(ParameterBag $query, SessionInterface $session = null){ return array(); } /** * @param $namespace string * @param $classname string * @return Webservice|null */ public function factory($namespace, $classname) { $serviceNamespace = '\\AppBundle\\API\\' . ucfirst($namespace); $class = $serviceNamespace . '\\' . ucfirst($classname); if (!class_exists($class)) { return null; } return new $class($this->DB); } /** * @param $query ParameterBag * @return \PDO db connection */ protected function getDbFromQuery($query){ if (! $query->has('dbversion')){ throw new Exception('No valid dbversion provided'); } return $this->DB->getDbForVersion($query->get('dbversion')); } }
Fix comment incorrectly indicating an unexpected method parameter.
<?php abstract class SQLayerTable { /** @property *str* table name **/ protected $tableName; /** @property *obj* SQLayerDbo **/ protected $dbo; /** @method get record from key * @param *int* integer key * @return *arr* assoc (or false) **/ public function recFromKey($key) { /** compose sql **/ $sql = 'SELECT * FROM "'.$this->tableName.'" WHERE "key" = '.$key.';'; /** return the first record (or false) **/ if ($recs = $this->dbo->fetchRecs($sql)) { foreach ($recs as $rec) { return $rec; } } else { return false; } } /** @method get record from key * @param void * @return *arr* array of assocs (or false) **/ public function allRecs() { /** compose sql **/ $sql = 'SELECT * FROM "'.$this->tableName.'";'; /** return the array of recs (or false) **/ if ($recs = $this->dbo->fetchRecs($sql)) { return $recs; } else { return false; } } }
<?php abstract class SQLayerTable { /** @property *str* table name **/ protected $tableName; /** @property *obj* SQLayerDbo **/ protected $dbo; /** @method get record from key * @param *int* integer key * @return *arr* assoc (or false) **/ public function recFromKey($key) { /** compose sql **/ $sql = 'SELECT * FROM "'.$this->tableName.'" WHERE "key" = '.$key.';'; /** return the first record (or false) **/ if ($recs = $this->dbo->fetchRecs($sql)) { foreach ($recs as $rec) { return $rec; } } else { return false; } } /** @method get record from key * @param *int* integer key * @return *arr* array of assocs (or false) **/ public function allRecs() { /** compose sql **/ $sql = 'SELECT * FROM "'.$this->tableName.'";'; /** return the array of recs (or false) **/ if ($recs = $this->dbo->fetchRecs($sql)) { return $recs; } else { return false; } } }
Change the id strategy, using random strings instead of counters
<?php namespace Goetas\Twital\EventSubscriber; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Goetas\Twital\EventDispatcher\TemplateEvent; use Goetas\Twital\Twital; /** * * @author Asmir Mustafic <[email protected]> * */ class IDNodeSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents() { return array( 'compiler.post_load' => array( array( 'addAttribute' ) ), 'compiler.pre_dump' => array( array( 'removeAttribute' ) ) ); } public function addAttribute(TemplateEvent $event) { $doc = $event->getTemplate()->getDocument(); $xp = new \DOMXPath($doc); $nodes = $xp->query("//*[@*[namespace-uri()='".Twital::NS."']]"); foreach ($nodes as $node) { $node->setAttributeNS(Twital::NS, '__internal-id__', microtime(1).mt_rand()); } } public function removeAttribute(TemplateEvent $event) { $doc = $event->getTemplate()->getDocument(); $xp = new \DOMXPath($doc); $xp->registerNamespace('twital', Twital::NS); $attributes = $xp->query("//@twital:__internal-id__"); foreach ($attributes as $attribute) { $attribute->ownerElement->removeAttributeNode($attribute); } } }
<?php namespace Goetas\Twital\EventSubscriber; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Goetas\Twital\EventDispatcher\TemplateEvent; use Goetas\Twital\Twital; /** * * @author Asmir Mustafic <[email protected]> * */ class IDNodeSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents() { return array( 'compiler.post_load' => array( array( 'addAttribute' ) ), 'compiler.pre_dump' => array( array( 'removeAttribute' ) ) ); } public function addAttribute(TemplateEvent $event) { $doc = $event->getTemplate()->getDocument(); $xp = new \DOMXPath($doc); $nodes = $xp->query("//*[@*[namespace-uri()='".Twital::NS."']]"); $cnt = 0; foreach ($nodes as $node) { $node->setAttributeNS(Twital::NS, '__internal-id__', ++$cnt); } } public function removeAttribute(TemplateEvent $event) { $doc = $event->getTemplate()->getDocument(); $xp = new \DOMXPath($doc); $xp->registerNamespace('twital', Twital::NS); $attributes = $xp->query("//@twital:__internal-id__"); foreach ($attributes as $attribute) { $attribute->ownerElement->removeAttributeNode($attribute); } } }
Add email to send objects during registration
'use strict'; export default class UserService { static get $inject(){ return ['$http', '$window','API_URL']; } constructor($http,$window,API_URL) { this.$http = $http; this.$window = $window; this.API_URL = API_URL; } static get name(){ return 'UserService'; } register(user, pass, email) { return this.$http.post(`${ this.API_URL }/user/signup`, { username: user, password: pass, email: email }); } login(user, pass) { return this.$http.post(`${ this.API_URL }/user/login`, { username: user, password: pass }); } logout(){ this.$window.localStorage.removeItem('jwtToken'); } getCurrentUser() { let token = this.$window.localStorage['jwtToken']; if (!token) return {}; let base64Url = token.split('.')[1]; let base64 = base64Url.replace('-', '+').replace('_', '/'); return JSON.parse(this.$window.atob(base64)).user; } isAuthenticated() { return !!this.$window.localStorage['jwtToken']; } }
'use strict'; export default class UserService { static get $inject(){ return ['$http', '$window','API_URL']; } constructor($http,$window,API_URL) { this.$http = $http; this.$window = $window; this.API_URL = API_URL; } static get name(){ return 'UserService'; } register(user, pass) { return this.$http.post(`${ this.API_URL }/user/signup`, { username: user, password: pass }); } login(user, pass) { return this.$http.post(`${ this.API_URL }/user/login`, { username: user, password: pass }); } logout(){ this.$window.localStorage.removeItem('jwtToken'); } getCurrentUser() { let token = this.$window.localStorage['jwtToken']; if (!token) return {}; let base64Url = token.split('.')[1]; let base64 = base64Url.replace('-', '+').replace('_', '/'); return JSON.parse(this.$window.atob(base64)).user; } isAuthenticated() { return !!this.$window.localStorage['jwtToken']; } }
Set hmm detail state to null on GET_HMM.REQUESTED
/** * * * @copyright 2017 Government of Canada * @license MIT * @author igboyes * */ import { WS_UPDATE_STATUS, FIND_HMMS, GET_HMM } from "../actionTypes"; const initialState = { list: null, detail: null, process: null }; const hmmsReducer = (state = initialState, action) => { switch (action.type) { case WS_UPDATE_STATUS: if (action.data.id === "hmm_install") { return { ...state, process: action.data.process, ready: action.data.ready, size: action.data.download_size }; } return state; case FIND_HMMS.SUCCEEDED: return { ...state, fileExists: action.data.file_exists, list: action.data.documents, page: action.data.page, pageCount: action.data.page_count, totalCount: action.data.total_count }; case GET_HMM.REQUESTED: return {...state, detail: null}; case GET_HMM.SUCCEEDED: return {...state, detail: action.data}; default: return state; } }; export default hmmsReducer;
/** * * * @copyright 2017 Government of Canada * @license MIT * @author igboyes * */ import { WS_UPDATE_STATUS, FIND_HMMS, GET_HMM } from "../actionTypes"; const initialState = { list: null, detail: null, process: null }; const hmmsReducer = (state = initialState, action) => { switch (action.type) { case WS_UPDATE_STATUS: if (action.data.id === "hmm_install") { return { ...state, process: action.data.process, ready: action.data.ready, size: action.data.download_size }; } return state; case FIND_HMMS.SUCCEEDED: return { ...state, fileExists: action.data.file_exists, list: action.data.documents, page: action.data.page, pageCount: action.data.page_count, totalCount: action.data.total_count }; case GET_HMM.SUCCEEDED: return {...state, detail: action.data}; default: return state; } }; export default hmmsReducer;
Set default fetch mode to fetch_obj
<?php /* * This file is a part of the ChZ-PHP package. * * (c) François LASSERRE <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Engine; use \PDO as PDO; use \PDOException as PDOException; class Db extends PDO { const FETCH_ASSOC = PDO::FETCH_ASSOC; const FETCH_NUM = PDO::FETCH_NUM; const FETCH_OBJ = PDO::FETCH_OBJ; const FETCH_BOTH = PDO::FETCH_BOTH; const PARAM_INT = PDO::PARAM_INT; const PARAM_STR = PDO::PARAM_STR; private static $instance; public function __construct() { if (!isset(self::$instance)) { try { self::$instance = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_NAME, DB_USER, DB_PASS, array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES '.DB_ENCODING, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); } catch (PDOException $e) { die('Connection error: '.$e->getMessage()); } } return self::$instance; } public static function getInstance() { if (!isset(self::$instance)) { new Db(); } return self::$instance; } }
<?php /* * This file is a part of the ChZ-PHP package. * * (c) François LASSERRE <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Engine; use \PDO as PDO; use \PDOException as PDOException; class Db extends PDO { const FETCH_ASSOC = PDO::FETCH_ASSOC; const FETCH_NUM = PDO::FETCH_NUM; const FETCH_OBJ = PDO::FETCH_OBJ; const FETCH_BOTH = PDO::FETCH_BOTH; const PARAM_INT = PDO::PARAM_INT; const PARAM_STR = PDO::PARAM_STR; private static $instance; public function __construct() { if (!isset(self::$instance)) { try { self::$instance = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_NAME, DB_USER, DB_PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES '.DB_ENCODING, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); } catch (PDOException $e) { die('Connection error: '.$e->getMessage()); } } return self::$instance; } public static function getInstance() { if (!isset(self::$instance)) { new Db(); } return self::$instance; } }
Set dev port back to 3000
module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), bower: { install: { options: { targetDir: './lib/ui', layout: 'byComponent', install: true, verbose: false, cleanTargetDir: true, cleanBowerDir: true, bowerOptions: {} } } }, jasmine_node: { all: 'spec/server/' }, jasmine: { }, express: { options: { }, dev: { options: { script: 'src/server/app.js', port: 3000 } } }, watch: { express: { files: [ 'src/server/**/*.js' ], tasks: [ 'express:dev' ], options: { spawn: false } } } }); grunt.loadNpmTasks('grunt-bower-task'); grunt.loadNpmTasks('grunt-jasmine-node'); grunt.loadNpmTasks('grunt-contrib-jasmine'); grunt.loadNpmTasks('grunt-express-server'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['jasmine_node']); grunt.registerTask('run', ['express:dev', 'watch']); };
module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), bower: { install: { options: { targetDir: './lib/ui', layout: 'byComponent', install: true, verbose: false, cleanTargetDir: true, cleanBowerDir: true, bowerOptions: {} } } }, jasmine_node: { all: 'spec/server/' }, jasmine: { }, express: { options: { }, dev: { options: { script: 'src/server/app.js', port: 1234 } } }, watch: { express: { files: [ 'src/server/**/*.js' ], tasks: [ 'express:dev' ], options: { spawn: false } } } }); grunt.loadNpmTasks('grunt-bower-task'); grunt.loadNpmTasks('grunt-jasmine-node'); grunt.loadNpmTasks('grunt-contrib-jasmine'); grunt.loadNpmTasks('grunt-express-server'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['jasmine_node']); grunt.registerTask('run', ['express:dev', 'watch']); };
Drop username as it will be used/available in meta
<?php namespace Bolt\Extension\Bolt\Members\Storage\Schema\Table; use Bolt\Storage\Database\Schema\Table\BaseTable; /** * Account table. * * @author Gawain Lynch <[email protected]> */ class Account extends BaseTable { /** * @inheritDoc */ protected function addColumns() { $this->table->addColumn('guid', 'guid', []); $this->table->addColumn('email', 'string', ['length' => 128]); $this->table->addColumn('displayname', 'string', ['length' => 32, 'notnull' => false]); $this->table->addColumn('enabled', 'boolean', ['default' => 0]); $this->table->addColumn('roles', 'json_array', ['length' => 1024, 'notnull' => false]); $this->table->addColumn('lastseen', 'datetime', ['default' => '']); $this->table->addColumn('lastip', 'string', ['length' => 32, 'notnull' => false]); } /** * @inheritDoc */ protected function addIndexes() { $this->table->addUniqueIndex(['email']); $this->table->addIndex(['enabled']); } /** * @inheritDoc */ protected function setPrimaryKey() { $this->table->setPrimaryKey(['guid']); } }
<?php namespace Bolt\Extension\Bolt\Members\Storage\Schema\Table; use Bolt\Storage\Database\Schema\Table\BaseTable; /** * Account table. * * @author Gawain Lynch <[email protected]> */ class Account extends BaseTable { /** * @inheritDoc */ protected function addColumns() { $this->table->addColumn('guid', 'guid', []); $this->table->addColumn('username', 'string', ['length' => 32]); $this->table->addColumn('email', 'string', ['length' => 128]); $this->table->addColumn('lastseen', 'datetime', ['default' => '1900-01-01 00:00:00']); $this->table->addColumn('lastip', 'string', ['length' => 32, 'notnull' => false, 'default' => '']); $this->table->addColumn('displayname', 'string', ['length' => 32, 'notnull' => false]); $this->table->addColumn('enabled', 'boolean', ['default' => 0]); $this->table->addColumn('roles', 'json_array', ['length' => 1024, 'default' => '']); } /** * @inheritDoc */ protected function addIndexes() { $this->table->addUniqueIndex(['username']); $this->table->addUniqueIndex(['email']); $this->table->addIndex(['enabled']); } /** * @inheritDoc */ protected function setPrimaryKey() { $this->table->setPrimaryKey(['guid']); } }
Adjust permission check order logic
<?php namespace LaravelDoctrine\ACL\Permissions; use LaravelDoctrine\ACL\Contracts\HasPermissions as HasPermissionsContract; use LaravelDoctrine\ACL\Contracts\HasRoles as HasRolesHasRoles; use LaravelDoctrine\ACL\Contracts\Permission as PermissionContract; trait HasPermissions { /** * @param PermissionContract|string $name * * @return bool */ public function hasPermissionTo($name) { if ($this instanceof HasPermissionsContract) { foreach ($this->getPermissions() as $permission) { if ($this->getPermissionName($permission) === $name) { return true; } } } if ($this instanceof HasRolesHasRoles) { foreach ($this->getRoles() as $role) { if ($role->hasPermissionTo($name)) { return true; } } } return false; } /** * @param PermissionContract|string $permission * * @return string */ protected function getPermissionName($permission) { return $permission instanceof PermissionContract ? $permission->getName() : $permission; } }
<?php namespace LaravelDoctrine\ACL\Permissions; use LaravelDoctrine\ACL\Contracts\HasPermissions as HasPermissionsContract; use LaravelDoctrine\ACL\Contracts\HasRoles as HasRolesHasRoles; use LaravelDoctrine\ACL\Contracts\Permission as PermissionContract; trait HasPermissions { /** * @param PermissionContract|string $name * * @return bool */ public function hasPermissionTo($name) { if ($this instanceof HasRolesHasRoles) { foreach ($this->getRoles() as $role) { if ($role->hasPermissionTo($name)) { return true; } } } if ($this instanceof HasPermissionsContract) { foreach ($this->getPermissions() as $permission) { if ($this->getPermissionName($permission) === $name) { return true; } } } return false; } /** * @param PermissionContract|string $permission * * @return string */ protected function getPermissionName($permission) { return $permission instanceof PermissionContract ? $permission->getName() : $permission; } }
Allow main handlers to be called without callbacks
var Observable = require('../utils').Observable, errors = require('../errors'); module.exports = Observable.extend({ constructor: function MailHandler(transport, render) { this.transport = transport; this.render = render; }, isEnabled: function () { return !!this.transport; }, forgotPassword: function (to, context, fn) { var _this = this; this.render('reset_email.txt', context, function (err, body) { if (err) { return fn(err); } _this.sendMail({ from: "JSBin <[email protected]>", to: to, subject: 'JSBin Password Reset', text: body }, fn); }); }, errorReport: function (to, context, fn) { var _this = this; this.render('error_email.txt', context, function (err, body) { if (err) { return fn(err); } _this.sendMail({ from: "JSBin <[email protected]>", to: to, subject: 'JSBin Internal Server Error', text: body }, fn); }); }, sendMail: function (options, fn) { var error = new errors.MailerError('Mail Transport is not configured'); if (!this.transport) { return fn(error); } this.transport.sendMail(options, function (err) { if (typeof fn === 'function') { fn(err ? error : null); } }); } });
var Observable = require('../utils').Observable, errors = require('../errors'); module.exports = Observable.extend({ constructor: function MailHandler(transport, render) { this.transport = transport; this.render = render; }, isEnabled: function () { return !!this.transport; }, forgotPassword: function (to, context, fn) { var _this = this; this.render('reset_email.txt', context, function (err, body) { if (err) { return fn(err); } _this.sendMail({ from: "JSBin <[email protected]>", to: to, subject: 'JSBin Password Reset', text: body }, fn); }); }, errorReport: function (to, context, fn) { var _this = this; this.render('error_email.txt', context, function (err, body) { if (err) { return fn(err); } _this.sendMail({ from: "JSBin <[email protected]>", to: to, subject: 'JSBin Internal Server Error', text: body }, fn); }); }, sendMail: function (options, fn) { var error = new errors.MailerError('Mail Transport is not configured'); if (!this.transport) { return fn(error); } this.transport.sendMail(options, function (err) { fn(err ? error : null); }); } });
Fix stop stream even if there is no more positions in the stream Add a control stream to signal when to stop taking values from the position stream. This change is due takeWhile evaluates the condition after receiving the next value and in this case there is not guarantee of receiving an extra position.
'use strict'; /* global cordova */ define(function(require, exports) { var Bacon = require('./ext/Bacon'); var location = require('./location'); var positionStream = location.streamMultiplePositions(); var PositionRecorder = function() { var recordingFlag = false; var positions = []; var recording; var control; var stream; /** * Return the status of the recorder * @returns {Boolean} true if recording, false if it not recording. */ var isRecording = function() { return recordingFlag; }; /** * Start to record positions * @returns a copy of the stream */ var startRecording = function() { control = new Bacon.Bus(); stream = new Bacon.Bus(); recordingFlag = true; positionStream .takeUntil(control) //.doLog() .onValue(function(position) { positions.push(position); stream.push(position); }); return stream; }; /** * Stop recording positions */ var stopRecording = function() { control.push(new Bacon.End()); recordingFlag = false; }; /** * Get a list of positions recorded * @returns {Array} list of positions recorded */ var getRecordedPositions = function() { return positions; }; return { startRecording: startRecording, stopRecording: stopRecording, isRecording: isRecording, getRecordedPositions: getRecordedPositions }; }; return PositionRecorder; });
'use strict'; /* global cordova */ define(function(require, exports) { var Bacon = require('./ext/Bacon'); var location = require('./location'); var positionStream = location.streamMultiplePositions(); var PositionRecorder = function() { var recordingFlag = false; var positions = []; /** * Return the status of the recorder * @returns {Boolean} true if recording, false if it not recording. */ var isRecording = function() { return recordingFlag; }; /** * Start to record positions * @returns a copy of the stream */ var startRecording = function() { var stream = new Bacon.Bus(); recordingFlag = true; positionStream .takeWhile(isRecording) //.doLog() .onValue(function(position) { positions.push(position); stream.push(position); }); return stream; }; /** * Stop recording positions */ var stopRecording = function() { recordingFlag = false; }; /** * Get a list of positions recorded * @returns {Array} list of positions recorded */ var getRecordedPositions = function() { return positions; }; return { startRecording: startRecording, stopRecording: stopRecording, isRecording: isRecording, getRecordedPositions: getRecordedPositions }; }; return PositionRecorder; });
TEST reduce number of iterations for stopwatch test
# -*- encoding: utf-8 -*- """Created on Dec 16, 2014. @author: Katharina Eggensperger @projekt: AutoML2015 """ from __future__ import print_function import time import unittest from autosklearn.util import StopWatch class Test(unittest.TestCase): _multiprocess_can_split_ = True def test_stopwatch_overhead(self): # CPU overhead start = time.clock() watch = StopWatch() for i in range(1, 1000): watch.start_task('task_%d' % i) watch.stop_task('task_%d' % i) stop = time.clock() dur = stop - start cpu_overhead = dur - watch.cpu_sum() self.assertLess(cpu_overhead, 1.5) # Wall Overhead start = time.time() watch = StopWatch() for i in range(1, 1000): watch.start_task('task_%d' % i) watch.stop_task('task_%d' % i) stop = time.time() dur = stop - start wall_overhead = dur - watch.wall_sum() self.assertLess(wall_overhead, 2) self.assertLess(cpu_overhead, 2*wall_overhead) if __name__ == '__main__': # import sys;sys.argv = ['', 'Test.testName'] unittest.main()
# -*- encoding: utf-8 -*- """Created on Dec 16, 2014. @author: Katharina Eggensperger @projekt: AutoML2015 """ from __future__ import print_function import time import unittest from autosklearn.util import StopWatch class Test(unittest.TestCase): _multiprocess_can_split_ = True def test_stopwatch_overhead(self): # CPU overhead start = time.clock() watch = StopWatch() for i in range(1, 100000): watch.start_task('task_%d' % i) watch.stop_task('task_%d' % i) stop = time.clock() dur = stop - start cpu_overhead = dur - watch.cpu_sum() self.assertLess(cpu_overhead, 1.5) # Wall Overhead start = time.time() watch = StopWatch() for i in range(1, 100000): watch.start_task('task_%d' % i) watch.stop_task('task_%d' % i) stop = time.time() dur = stop - start wall_overhead = dur - watch.wall_sum() self.assertLess(wall_overhead, 2) self.assertLess(cpu_overhead, 2*wall_overhead) if __name__ == '__main__': # import sys;sys.argv = ['', 'Test.testName'] unittest.main()
Make it so that Struct Pointer return values work.
var FFI = require("./ffi"), util = require("util"); // CIF proves a JS interface for the libffi "callback info" (CIF) structure var CIF = module.exports = function(rtype, types) { this._returnType = rtype; this._types = types; if (!FFI.isValidReturnType(this._returnType)) { throw new Error("Invalid Return Type"); } this._argtypesptr = new FFI.Pointer(types.length * FFI.Bindings.FFI_TYPE_SIZE); this._rtypeptr = FFI.ffiTypeFor(this._returnType); var tptr = this._argtypesptr.seek(0); for (var i = 0, len = types.length; i < len; i++) { var typeName = types[i]; if (FFI.isValidParamType(typeName)) { tptr.putPointer(FFI.ffiTypeFor(typeName), true); } else { throw new Error("Invalid Type: " + types[i]); } } this._cifptr = FFI.Bindings.prepCif(types.length, this._rtypeptr, this._argtypesptr); }; CIF.prototype.getArgTypesPointer = function() { return this._argtypesptr; } CIF.prototype.getReturnTypePointer = function() { return this._rtypeptr; } CIF.prototype.getPointer = function() { return this._cifptr; }
var FFI = require("./ffi"), util = require("util"); // CIF proves a JS interface for the libffi "callback info" (CIF) structure var CIF = module.exports = function(rtype, types) { this._returnType = rtype; this._types = types; if (!FFI.isValidReturnType(this._returnType)) { throw new Error("Invalid Return Type"); } this._argtypesptr = new FFI.Pointer(types.length * FFI.Bindings.FFI_TYPE_SIZE); this._rtypeptr = FFI.Bindings.FFI_TYPES[this._returnType]; var tptr = this._argtypesptr.seek(0); for (var i = 0, len = types.length; i < len; i++) { var typeName = types[i]; if (FFI.isValidParamType(typeName)) { tptr.putPointer(FFI.ffiTypeFor(typeName), true); } else { throw new Error("Invalid Type: " + types[i]); } } this._cifptr = FFI.Bindings.prepCif(types.length, this._rtypeptr, this._argtypesptr); }; CIF.prototype.getArgTypesPointer = function() { return this._argtypesptr; } CIF.prototype.getReturnTypePointer = function() { return this._rtypeptr; } CIF.prototype.getPointer = function() { return this._cifptr; }
GEN-63: Use pandoc's multiline_tables extension to build table
/* * Created brightSPARK Labs * www.brightsparklabs.com */ 'use strict'; // ----------------------------------------------------------------------------- // MODULES // ----------------------------------------------------------------------------- var es = require('event-stream'); var execSync = require('execSync'); var gutil = require('gulp-util'); var moment = require('moment'); // ----------------------------------------------------------------------------- // EXPORTS // ----------------------------------------------------------------------------- module.exports = function() { // format to pass to 'git log' var headerFormat = "\\newpage%n%n\ -------------------------------------------------------------------%n\ **Document Control**%n\ --------------------- --------------------------------------------%n\ Last Modified On: %ci%n%n\ Last Modified By: %cn%n%n\ Generated On: <%%= date %%>%n%n\ Generated From: <%%= file.relative %%>%n%n\ Version Identifier: %h%n%n\ --------------------------------------------------------------------%n\ %n\\newpage%n%n" var gitCommand = 'git --no-pager log -n1 --pretty=tformat:\'' + headerFormat +'\''; return es.map(function(file, cb){ var headerText = execSync.exec(gitCommand + ' ' + file.path).stdout; headerText = headerText || ''; var data = { date : moment().utc().format(), file : file }; file.contents = Buffer.concat([ new Buffer(gutil.template(headerText, data)), file.contents ]); cb(null, file); }); };
/* * Created brightSPARK Labs * www.brightsparklabs.com */ 'use strict'; // ----------------------------------------------------------------------------- // MODULES // ----------------------------------------------------------------------------- var es = require('event-stream'); var execSync = require('execSync'); var gutil = require('gulp-util'); var moment = require('moment'); // ----------------------------------------------------------------------------- // EXPORTS // ----------------------------------------------------------------------------- module.exports = function() { // format to pass to 'git log' var headerFormat = "\\newpage%n%n\ |**Document Control**|%n\ |-:|-%n\ |Last Modified On:|%cI%n\ |Last Modified By:|%cn%n\ |Generated On:| <%%= date %%>%n\ |Generated From:| <%%= file.relative %%>%n\ |Version Identifier:|%h%n\ %n\\newpage%n%n" var gitCommand = 'git --no-pager log -n1 --pretty=tformat:\'' + headerFormat +'\''; return es.map(function(file, cb){ var headerText = execSync.exec(gitCommand + ' ' + file.path).stdout; headerText = headerText || ''; var data = { date : moment().utc().format(), file : file }; file.contents = Buffer.concat([ new Buffer(gutil.template(headerText, data)), file.contents ]); cb(null, file); }); };
Remove PHP template engine from 'modules' project.
<?php namespace @@namespace@@\Modules\Frontend; use Phalcon\DiInterface; use Phalcon\Loader; use Phalcon\Mvc\View; use Phalcon\Mvc\ModuleDefinitionInterface; class Module implements ModuleDefinitionInterface { /** * Registers an autoloader related to the module * * @param DiInterface $di */ public function registerAutoloaders(DiInterface $di = null) { $loader = new Loader(); $loader->registerNamespaces([ '@@namespace@@\Modules\Frontend\Controllers' => __DIR__ . '/controllers/', '@@namespace@@\Modules\Frontend\Models' => __DIR__ . '/models/', ]); $loader->register(); } /** * Registers services related to the module * * @param DiInterface $di */ public function registerServices(DiInterface $di) { /** * Setting up the view component */ $di->set('view', function () { $view = new View(); $view->setDI($this); $view->setViewsDir(__DIR__ . '/views/'); $view->registerEngines([ '.volt' => 'voltShared' ]); return $view; }); } }
<?php namespace @@namespace@@\Modules\Frontend; use Phalcon\DiInterface; use Phalcon\Loader; use Phalcon\Mvc\View; use Phalcon\Mvc\ModuleDefinitionInterface; class Module implements ModuleDefinitionInterface { /** * Registers an autoloader related to the module * * @param DiInterface $di */ public function registerAutoloaders(DiInterface $di = null) { $loader = new Loader(); $loader->registerNamespaces([ '@@namespace@@\Modules\Frontend\Controllers' => __DIR__ . '/controllers/', '@@namespace@@\Modules\Frontend\Models' => __DIR__ . '/models/', ]); $loader->register(); } /** * Registers services related to the module * * @param DiInterface $di */ public function registerServices(DiInterface $di) { /** * Setting up the view component */ $di->set('view', function () { $view = new View(); $view->setDI($this); $view->setViewsDir(__DIR__ . '/views/'); $view->registerEngines([ '.volt' => 'voltShared', '.phtml' => 'Phalcon\Mvc\View\Engine\Php' ]); return $view; }); } }
Revert "Resolve src/ folder too" This reverts commit 39cd9a4eecb0e1eaef08127551d752963f345a0b.
const fs = require('fs'); const path = require('path'); // eslint-disable-next-line import/no-extraneous-dependencies const webpack = require('webpack'); const nodeModules = {}; // This is to filter out node_modules as we don't want them // to be made part of any bundles. fs.readdirSync('node_modules') .filter((x) => { return ['.bin'].indexOf(x) === -1; }) .forEach((mod) => { nodeModules[mod] = `commonjs ${mod}`; }); module.exports = { entry: './src/main.js', target: 'node', output: { path: path.join(__dirname, 'dist'), filename: 'addons-linter.js', libraryTarget: 'commonjs2', }, module: { rules: [ { use: 'babel-loader', // babel options are in .babelrc exclude: /(node_modules|bower_components)/, test: /\.js$/, }, { use: 'raw-loader', exclude: /(node_modules|bower_components)/, test: /\.txt$/, }, ], }, externals: nodeModules, plugins: [ new webpack.BannerPlugin( { banner: 'require("source-map-support").install();', raw: true, entryOnly: false, } ), ], resolve: { extensions: ['.js', '.json'], modules: [ 'node_modules', ], }, devtool: 'sourcemap', };
const fs = require('fs'); const path = require('path'); // eslint-disable-next-line import/no-extraneous-dependencies const webpack = require('webpack'); const nodeModules = {}; // This is to filter out node_modules as we don't want them // to be made part of any bundles. fs.readdirSync('node_modules') .filter((x) => { return ['.bin'].indexOf(x) === -1; }) .forEach((mod) => { nodeModules[mod] = `commonjs ${mod}`; }); module.exports = { entry: './src/main.js', target: 'node', output: { path: path.join(__dirname, 'dist'), filename: 'addons-linter.js', libraryTarget: 'commonjs2', }, module: { rules: [ { use: 'babel-loader', // babel options are in .babelrc exclude: /(node_modules|bower_components)/, test: /\.js$/, }, { use: 'raw-loader', exclude: /(node_modules|bower_components)/, test: /\.txt$/, }, ], }, externals: nodeModules, plugins: [ new webpack.BannerPlugin( { banner: 'require("source-map-support").install();', raw: true, entryOnly: false, } ), ], resolve: { extensions: ['.js', '.json'], modules: [ path.join(__dirname, 'src'), path.resolve(__dirname, 'node_modules'), ], }, devtool: 'sourcemap', };
Add attrs and typing to deps
import re from setuptools import find_packages, setup with open('netsgiro/__init__.py') as fh: metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", fh.read())) with open('README.rst') as fh: long_description = fh.read() setup( name='netsgiro', version=metadata['version'], description='File parsers for Nets AvtaleGiro and OCR Giro', long_description=long_description, url='https://github.com/otovo/python-netsgiro', author='Otovo AS', license='Apache License, Version 2.0', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], keywords='avtalegiro ocr giro', packages=find_packages(exclude=['tests', 'tests.*']), install_requires=[ 'attrs', 'typing', # Needed for Python 3.4 ], extras_require={ 'dev': [ 'check-manifest', 'flake8', 'flake8-import-order', 'mypy', 'pytest', 'pytest-xdist', 'tox', ], }, )
import re from setuptools import find_packages, setup with open('netsgiro/__init__.py') as fh: metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", fh.read())) with open('README.rst') as fh: long_description = fh.read() setup( name='netsgiro', version=metadata['version'], description='File parsers for Nets AvtaleGiro and OCR Giro', long_description=long_description, url='https://github.com/otovo/python-netsgiro', author='Otovo AS', license='Apache License, Version 2.0', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], keywords='avtalegiro ocr giro', packages=find_packages(exclude=['tests', 'tests.*']), install_requires=[ ], extras_require={ 'dev': [ 'check-manifest', 'flake8', 'flake8-import-order', 'mypy', 'pytest', 'pytest-xdist', 'tox', ], }, )
Improve geo ip string decoding
<?php // JUser/View/Helper/UserWithIp.php namespace JUser\View\Helper; use Zend\View\Helper\AbstractHelper; class UserWithIp extends AbstractHelper { public function __invoke($username, $ipAddress) { $geo = $this->view->geoip($ipAddress); $place = ''; if ($geo&&$geo->getCity()) { $place .= $this->view->escapeHtml(mb_convert_encoding($geo->getCity(), "UTF-8", "ISO-8859-1")).", "; } if ($geo&&$geo->getCountryName()) { $place .= $this->view->escapeHtml(mb_convert_encoding($geo->getCountryName(), "UTF-8", "ISO-8859-1")); } //if they didn't pass us a user name print the place and/or ipAddress if (is_null($username) || 0 == strlen($username)) { if ('' === $place) { return $ipAddress; } else { $return = '<span data-toggle="tooltip" title="%s">%s</span>'; return sprintf($return, $ipAddress, $place); } } //otherwise return the username with a tooltip if ('' === $place) { $tooltip = $ipAddress; } else { $tooltip = $place. ' ('.$ipAddress.')'; } $return = '<span data-toggle="tooltip" title="%s">%s</span>'; return sprintf($return, $tooltip, $username); } }
<?php // JUser/View/Helper/UserWithIp.php namespace JUser\View\Helper; use Zend\View\Helper\AbstractHelper; class UserWithIp extends AbstractHelper { public function __invoke($username, $ipAddress) { $geo = $this->view->geoip($ipAddress); $place = ''; if ($geo&&$geo->getCity()) { $place .= $this->view->escapeHtml(mb_convert_encoding($geo->getCity(), "UTF-8", "auto")).", "; } if ($geo&&$geo->getCountryName()) { $place .= $this->view->escapeHtml(mb_convert_encoding($geo->getCountryName(), "UTF-8", "auto")); } //if they didn't pass us a user name print the place and/or ipAddress if (is_null($username) || 0 == strlen($username)) { if ('' === $place) { return $ipAddress; } else { $return = '<span data-toggle="tooltip" title="%s">%s</span>'; return sprintf($return, $ipAddress, $place); } } //otherwise return the username with a tooltip if ('' === $place) { $tooltip = $ipAddress; } else { $tooltip = $place. ' ('.$ipAddress.')'; } $return = '<span data-toggle="tooltip" title="%s">%s</span>'; return sprintf($return, $tooltip, $username); } }
Add tra and some rewording for plugin info for plugin edit window git-svn-id: 9bac41f8ebc9458fc3e28d41abfab39641e8bd1c@30965 b456876b-0849-0410-b77d-98878d47e9d5
<?php // (c) Copyright 2002-2010 by authors of the Tiki Wiki/CMS/Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ // this script may only be included - so it's better to die if called directly. if (strpos($_SERVER["SCRIPT_NAME"],basename(__FILE__)) !== false) { header("location: index.php"); die; } function wikiplugin_userlink_info() { return array( 'name' => tra('Userlink function'), 'documentation' => tra('PluginUserlink'), 'description' => tra('Makes a link to the user information page'), 'prefs' => array('wikiplugin_userlink'), 'params' => array( 'user' => array( 'required' => false, 'name' => tra('User account name'), 'description' => tra('User account name (which can be an email address)'), 'filter' => 'xss', ), ), ); } function wikiplugin_userlink($data, $params) { global $smarty; $path = 'lib/smarty_tiki/modifier.userlink.php'; include_once($path); $func = 'smarty_modifier_userlink'; $content = $func($params['user'], '', '', $data); return '~np~'.$content.'~/np~'; }
<?php // (c) Copyright 2002-2010 by authors of the Tiki Wiki/CMS/Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ // this script may only be included - so it's better to die if called directly. if (strpos($_SERVER["SCRIPT_NAME"],basename(__FILE__)) !== false) { header("location: index.php"); die; } function wikiplugin_userlink_info() { return array( 'name' => tra('Userlink function'), 'documentation' => 'PluginUserlink', 'description' => tra('Makes a link to the user information page'), 'prefs' => array('wikiplugin_userlink'), 'params' => array( 'user' => array( 'required' => false, 'name' => tra('User account name'), 'description' => 'User account name (could be email)', 'filter' => 'xss', ), ), ); } function wikiplugin_userlink($data, $params) { global $smarty; $path = 'lib/smarty_tiki/modifier.userlink.php'; include_once($path); $func = 'smarty_modifier_userlink'; $content = $func($params["user"], '', '', $data); return '~np~'.$content.'~/np~'; }
Revert "missing formatExport and ClearFilters formatters"
/** * Bootstrap Table Portuguese Portugal Translation * Author: Burnspirit<[email protected]> */ (function ($) { 'use strict'; $.fn.bootstrapTable.locales['pt-PT'] = { formatLoadingMessage: function () { return 'A carregar, por favor aguarde...'; }, formatRecordsPerPage: function (pageNumber) { return pageNumber + ' registos por p&aacute;gina'; }, formatShowingRows: function (pageFrom, pageTo, totalRows) { return 'A mostrar ' + pageFrom + ' at&eacute; ' + pageTo + ' de ' + totalRows + ' linhas'; }, formatSearch: function () { return 'Pesquisa'; }, formatNoMatches: function () { return 'Nenhum registo encontrado'; }, formatPaginationSwitch: function () { return 'Esconder/Mostrar pagina&ccedil&atilde;o'; }, formatRefresh: function () { return 'Atualizar'; }, formatToggle: function () { return 'Alternar'; }, formatColumns: function () { return 'Colunas'; }, formatAllRows: function () { return 'Tudo'; } }; $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['pt-PT']); })(jQuery);
/** * Bootstrap Table Portuguese Portugal Translation * Author: Burnspirit<[email protected]> */ (function ($) { 'use strict'; $.fn.bootstrapTable.locales['pt-PT'] = { formatLoadingMessage: function () { return 'A carregar, por favor aguarde...'; }, formatRecordsPerPage: function (pageNumber) { return pageNumber + ' registos por p&aacute;gina'; }, formatShowingRows: function (pageFrom, pageTo, totalRows) { return 'A mostrar ' + pageFrom + ' at&eacute; ' + pageTo + ' de ' + totalRows + ' linhas'; }, formatSearch: function () { return 'Pesquisa'; }, formatNoMatches: function () { return 'Nenhum registo encontrado'; }, formatPaginationSwitch: function () { return 'Esconder/Mostrar pagina&ccedil&atilde;o'; }, formatRefresh: function () { return 'Atualizar'; }, formatToggle: function () { return 'Alternar'; }, formatColumns: function () { return 'Colunas'; }, formatAllRows: function () { return 'Tudo'; }, formatExport: function () { return 'Exportar dados'; }, formatClearFilters: function () { return 'Remover filtros'; } }; $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['pt-PT']); })(jQuery);
Allow user selection at section level
//----------------------------------------------------------------------------// // // // V e r t e x V i e w // // // // Copyright (C) Herve Bitteur 2000-2009. All rights reserved. // // This software is released under the GNU General Public License. // // Please contact [email protected] to report bugs & suggestions. // //----------------------------------------------------------------------------// // package omr.graph; import java.awt.*; /** * Interface <code>VertexView</code> defines the interface needed to handle the * rendering of a vertex. * * @author Herv&eacute; Bitteur * @version $Id$ */ public interface VertexView { //~ Methods ---------------------------------------------------------------- //--------------// // getRectangle // //--------------// /** * Return the display rectangle used by the rendering of the vertex * * @return the bounding rectangle in the display space */ Rectangle getRectangle (); //--------// // render // //--------// /** * Render the vertex * * @param g the graphics context * @param drawBorders should vertex borders be drawn * * @return true if actually rendered, i.e. is displayed */ boolean render (Graphics g, boolean drawBorders); }
//----------------------------------------------------------------------------// // // // V e r t e x V i e w // // // // Copyright (C) Herve Bitteur 2000-2009. All rights reserved. // // This software is released under the GNU General Public License. // // Please contact [email protected] to report bugs & suggestions. // //----------------------------------------------------------------------------// // package omr.graph; import java.awt.*; /** * Interface <code>VertexView</code> defines the interface needed to handle the * rendering of a vertex. * * @author Herv&eacute; Bitteur * @version $Id$ */ public interface VertexView { //~ Methods ---------------------------------------------------------------- //--------------// // getRectangle // //--------------// /** * Return the display rectangle used by the rendering of the vertex * * @return the bounding rectangle in the display space */ Rectangle getRectangle (); //--------// // render // //--------// /** * Render the vertex * * @param g the graphics context * * @param drawBorders should vertex borders be drawn * @return true if actually rendered, i.e. is displayed */ boolean render (Graphics g, boolean drawBorders); }
Use tagged service IDs sorter to sort tagged services.
<?php /** * @author Igor Nikolaev <[email protected]> * @copyright Copyright (c) 2015, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\AdminBundle\DependencyInjection\Compiler; use Darvin\Utils\DependencyInjection\TaggedServiceIdsSorter; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; /** * Menu compiler pass */ class MenuPass implements CompilerPassInterface { const TAG_MENU_ITEM = 'darvin_admin.menu_item'; /** * {@inheritdoc} */ public function process(ContainerBuilder $container) { $menu = $container->getDefinition('darvin_admin.menu'); $menuItems = $container->findTaggedServiceIds(self::TAG_MENU_ITEM); if (empty($menuItems)) { return; } $sorter = new TaggedServiceIdsSorter(); $sorter->sort($menuItems); foreach ($menuItems as $id => $attr) { $menu->addMethodCall('addItem', array( $attr[0]['group'], new Reference($id), )); } } }
<?php /** * @author Igor Nikolaev <[email protected]> * @copyright Copyright (c) 2015, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\AdminBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; /** * Menu compiler pass */ class MenuPass implements CompilerPassInterface { const TAG_MENU_ITEM = 'darvin_admin.menu_item'; /** * {@inheritdoc} */ public function process(ContainerBuilder $container) { $menu = $container->getDefinition('darvin_admin.menu'); $menuItems = $container->findTaggedServiceIds(self::TAG_MENU_ITEM); uasort($menuItems, function (array $a, array $b) { if ($a[0]['position'] === $b[0]['position']) { return 0; } return $a[0]['position'] > $b[0]['position'] ? 1 : -1; }); foreach ($menuItems as $id => $attr) { $menu->addMethodCall('addItem', array( $attr[0]['group'], new Reference($id), )); } } }
Use zoom-in cursor in digital browser
<?php use_helper('Javascript') ?> <div class="row"> <div class="span6"> <h1><?php echo __('Media') ?></h1> </div> <?php if (null !== $facet = $pager->getFacet('mediaTypeId')): ?> <div class="span6"> <div class="btn-group top-options"> <?php foreach ($facet['terms'] as $item): ?> <button type="button" class="btn"><?php echo $item['term'] ?></button> <?php endforeach; ?> </div> </div> <?php endif; ?> </div> <div class="row"> <div class="span12"> <div class="section masonry"> <?php foreach ($pager->getResults() as $hit): ?> <?php $doc = build_i18n_doc($hit) ?> <div class="brick"> <div class="preview zoom"> <?php echo link_to(image_tag($doc['digitalObject']['thumbnail_FullPath']), array('module' => 'informationobject', 'slug' => $doc['slug'])) ?> </div> <div class="details"> <?php echo $doc[$sf_user->getCulture()]['title'] ?> </div> </div> <?php endforeach; ?> </div> <div class="section"> <?php echo get_partial('default/pager', array('pager' => $pager)) ?> </div> </div> </div>
<?php use_helper('Javascript') ?> <div class="row"> <div class="span6"> <h1><?php echo __('Media') ?></h1> </div> <?php if (null !== $facet = $pager->getFacet('mediaTypeId')): ?> <div class="span6"> <div class="btn-group top-options"> <?php foreach ($facet['terms'] as $item): ?> <button type="button" class="btn"><?php echo $item['term'] ?></button> <?php endforeach; ?> </div> </div> <?php endif; ?> </div> <div class="row"> <div class="span12"> <div class="section masonry"> <?php foreach ($pager->getResults() as $hit): ?> <?php $doc = build_i18n_doc($hit) ?> <div class="brick"> <div class="preview"> <?php echo link_to(image_tag($doc['digitalObject']['thumbnail_FullPath']), array('module' => 'informationobject', 'slug' => $doc['slug'])) ?> </div> <div class="details"> <?php echo $doc[$sf_user->getCulture()]['title'] ?> </div> </div> <?php endforeach; ?> </div> <div class="section"> <?php echo get_partial('default/pager', array('pager' => $pager)) ?> </div> </div> </div>
Fix error in console need to check type before call hasOwnProperty Look at this https://i.imgur.com/v2lpTuk.png
/* eslint-env browser */ ;(function() { try { const onMessage = ({ data }) => { if (!data.wappalyzer) { return } const { technologies } = data.wappalyzer || {} removeEventListener('message', onMessage) postMessage({ wappalyzer: { js: technologies.reduce((technologies, { name, chains }) => { chains.forEach((chain) => { const value = chain .split('.') .reduce( (value, method) => value && value instanceof Object && value.hasOwnProperty(method) ? value[method] : undefined, window ) if (value !== undefined) { technologies.push({ name, chain, value: typeof value === 'string' || typeof value === 'number' ? value : !!value }) } }) return technologies }, []) } }) } addEventListener('message', onMessage) } catch (e) { // Fail quietly } })()
/* eslint-env browser */ ;(function() { try { const onMessage = ({ data }) => { if (!data.wappalyzer) { return } const { technologies } = data.wappalyzer || {} removeEventListener('message', onMessage) postMessage({ wappalyzer: { js: technologies.reduce((technologies, { name, chains }) => { chains.forEach((chain) => { const value = chain .split('.') .reduce( (value, method) => value && value.hasOwnProperty(method) ? value[method] : undefined, window ) if (value !== undefined) { technologies.push({ name, chain, value: typeof value === 'string' || typeof value === 'number' ? value : !!value }) } }) return technologies }, []) } }) } addEventListener('message', onMessage) } catch (e) { // Fail quietly } })()
Remove urbansimd from excluded packages.
from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name='urbansim', version='0.2dev', description='Tool for modeling metropolitan real estate markets', author='Synthicity', author_email='[email protected]', license='AGPL', url='https://github.com/synthicity/urbansim', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 2.7', 'License :: OSI Approved :: GNU Affero General Public License v3' ], packages=find_packages(exclude=['*.tests']), package_data={'urbansim.urbansim': ['templates/*.template']}, install_requires=[ 'Django>=1.6.2', 'jinja2>=2.7.2', 'numpy>=1.8.0', 'pandas>=0.13.1', 'patsy>=0.2.1', 'pyyaml>=3.10', 'scipy>=0.13.3', 'shapely>=1.3.0', 'simplejson>=3.3.3', 'statsmodels>=0.5.0', 'tables>=3.1.0' ], entry_points={ 'console_scripts': [ 'urbansim_compile = urbansim.urbansim.compilecli:main', 'urbansim_serve = urbansim.server.servecli:main' ] } )
from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name='urbansim', version='0.2dev', description='Tool for modeling metropolitan real estate markets', author='Synthicity', author_email='[email protected]', license='AGPL', url='https://github.com/synthicity/urbansim', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 2.7', 'License :: OSI Approved :: GNU Affero General Public License v3' ], packages=find_packages(exclude=['urbansimd', '*.tests']), package_data={'urbansim.urbansim': ['templates/*.template']}, install_requires=[ 'Django>=1.6.2', 'jinja2>=2.7.2', 'numpy>=1.8.0', 'pandas>=0.13.1', 'patsy>=0.2.1', 'pyyaml>=3.10', 'scipy>=0.13.3', 'shapely>=1.3.0', 'simplejson>=3.3.3', 'statsmodels>=0.5.0', 'tables>=3.1.0' ], entry_points={ 'console_scripts': [ 'urbansim_compile = urbansim.urbansim.compilecli:main', 'urbansim_serve = urbansim.server.servecli:main' ] } )
Add key prop to card.
import React, { Component } from 'react'; import Registry from '../utils/Registry'; import BaseComponent from './BaseComponent'; import {omit, pick} from 'lodash'; const CARD_REGIONS = ['header', 'subheader', 'topmatter', 'subheader2', 'topmatter2', 'footer', 'footerHeader', 'footerSubheader', 'bottommatter', 'footerSubheader2', 'bottommatter2']; export default class Card extends Component { render() { let props = this.props; let style = props.style || {}; let regions = {}; let classNames = (props.cardClasses || []).join(' ') || ''; CARD_REGIONS.forEach(region => { if (props[region]) { regions[region] = ( <div className={"card-" + region}> <span className={"card-" + region + "-inner"}>{props[region]}</span> </div> ) } }); return ( <div className={'card card-' + props.cardStyle + ' ' + classNames} style={style}> <div className="card-header"> {regions.header} {regions.subheader} {regions.topmatter} {regions.subheader2} {regions.topmatter2} </div> <div className="card-content"> {props.children} </div> <div className="card-footer"> {regions.footerHeader} {regions.footerSubheader} {regions.bottommatter} {regions.footerSubheader2} {regions.bottommatter2} </div> </div> ) } } Registry.set('Card', Card);
import React, { Component } from 'react'; import Registry from '../utils/Registry'; import BaseComponent from './BaseComponent'; import {omit, pick} from 'lodash'; const CARD_REGIONS = ['header', 'subheader', 'topmatter', 'subheader2', 'topmatter2', 'footer', 'footerHeader', 'footerSubheader', 'bottommatter', 'footerSubheader2', 'bottommatter2']; export default class Card extends Component { render() { let props = this.props; let style = props.style || {}; let regions = {}; let classNames = (props.cardClasses || []).join(' ') || ''; CARD_REGIONS.forEach(region => { if (props[region]) { regions[region] = ( <div className={"card-" + region}> <span>{props[region]}</span> </div> ) } }); return ( <div className={'card card-' + props.cardStyle + ' ' + classNames} style={style}> <div className="card-header"> {regions.header} {regions.subheader} {regions.topmatter} {regions.subheader2} {regions.topmatter2} </div> <div className="card-content"> {props.children} </div> <div className="card-footer"> {regions.footerHeader} {regions.footerSubheader} {regions.bottommatter} {regions.footerSubheader2} {regions.bottommatter2} </div>; </div> ) } }
Remove persistence type from fixtures.
package com.novoda.downloadmanager; import android.content.Context; class FilePersistenceFixtures { private FilePersistenceResult filePersistenceResult = FilePersistenceResult.SUCCESS; private boolean writeResult = true; private long currentSize = 100; static FilePersistenceFixtures aFilePersistence() { return new FilePersistenceFixtures(); } FilePersistenceFixtures withFilePersistenceResult(FilePersistenceResult filePersistenceResult) { this.filePersistenceResult = filePersistenceResult; return this; } FilePersistenceFixtures withWriteResult(boolean writeResult) { this.writeResult = writeResult; return this; } FilePersistenceFixtures withCurrentSize(long currentSize) { this.currentSize = currentSize; return this; } FilePersistence build() { return new FilePersistence() { @Override public void initialiseWith(Context context, StorageRequirementRule storageRequirementRule) { } @Override public FilePersistenceResult create(FilePath absoluteFilePath, FileSize fileSize) { return filePersistenceResult; } @Override public boolean write(byte[] buffer, int offset, int numberOfBytesToWrite) { return writeResult; } @Override public void delete(FilePath absoluteFilePath) { // do nothing. } @Override public long getCurrentSize(FilePath filePath) { return currentSize; } @Override public void close() { // do nothing. } }; } }
package com.novoda.downloadmanager; import android.content.Context; class FilePersistenceFixtures { private FilePersistenceResult filePersistenceResult = FilePersistenceResult.SUCCESS; private boolean writeResult = true; private long currentSize = 100; private FilePersistenceType filePersistenceType = FilePersistenceType.PATH; static FilePersistenceFixtures aFilePersistence() { return new FilePersistenceFixtures(); } FilePersistenceFixtures withFilePersistenceResult(FilePersistenceResult filePersistenceResult) { this.filePersistenceResult = filePersistenceResult; return this; } FilePersistenceFixtures withWriteResult(boolean writeResult) { this.writeResult = writeResult; return this; } FilePersistenceFixtures withCurrentSize(long currentSize) { this.currentSize = currentSize; return this; } FilePersistenceFixtures withFilePersistenceType(FilePersistenceType filePersistenceType) { this.filePersistenceType = filePersistenceType; return this; } FilePersistence build() { return new FilePersistence() { @Override public void initialiseWith(Context context, StorageRequirementRule storageRequirementRule) { } @Override public FilePersistenceResult create(FilePath absoluteFilePath, FileSize fileSize) { return filePersistenceResult; } @Override public boolean write(byte[] buffer, int offset, int numberOfBytesToWrite) { return writeResult; } @Override public void delete(FilePath absoluteFilePath) { // do nothing. } @Override public long getCurrentSize(FilePath filePath) { return currentSize; } @Override public void close() { // do nothing. } }; } }
Remove placeholder from initial state
export default { creatorIsOpen: false, title: '', description: '', creationStatus: { failed: false, fields: [] }, datasets: { name: 'datasets', selected: null, data: [], loading: false, loaded: false, child: { name: 'visualisations', selected: null, data: [], loading: false, loaded: false, child: { name: 'locations', selected: null, data: [], loading: false, loaded: false, child: { name: 'models', selected: null, data: [], loading: false, loaded: false, child: { name: 'scenarios', selected: null, data: [], loading: false, loaded: false, child: { name: 'categories', selected: null, data: [], loading: false, loaded: false, child: { name: 'subcategories', selected: null, data: [], loading: false, loaded: false, child: { name: 'indicators', selected: null, data: [], loading: false, loaded: false, child: { name: 'years', selected: null, data: [], loading: false, loaded: false, child: { name: 'timeseries', selected: null, data: [], loading: false, loaded: false } } } } } } } } } } };
export default { creatorIsOpen: false, title: '', description: '', placeholder: '', creationStatus: { failed: false, fields: [] }, datasets: { name: 'datasets', selected: null, data: [], loading: false, loaded: false, child: { name: 'visualisations', selected: null, data: [], loading: false, loaded: false, child: { name: 'locations', selected: null, data: [], loading: false, loaded: false, child: { name: 'models', selected: null, data: [], loading: false, loaded: false, child: { name: 'scenarios', selected: null, data: [], loading: false, loaded: false, child: { name: 'categories', selected: null, data: [], loading: false, loaded: false, child: { name: 'subcategories', selected: null, data: [], loading: false, loaded: false, child: { name: 'indicators', selected: null, data: [], loading: false, loaded: false, child: { name: 'years', selected: null, data: [], loading: false, loaded: false, child: { name: 'timeseries', selected: null, data: [], loading: false, loaded: false } } } } } } } } } } };
Support for extra parameters in extractors
# -*- coding: utf-8 -*- from __future__ import ( print_function, unicode_literals, division, absolute_import) from six.moves import range from monkeylearn.utils import SleepRequestsMixin, MonkeyLearnResponse, HandleErrorsMixin from monkeylearn.settings import DEFAULT_BASE_ENDPOINT, DEFAULT_BATCH_SIZE class Extraction(SleepRequestsMixin, HandleErrorsMixin): def __init__(self, token, base_endpoint=DEFAULT_BASE_ENDPOINT): self.token = token self.endpoint = base_endpoint + 'extractors/' def extract(self, module_id, text_list, batch_size=DEFAULT_BATCH_SIZE, sleep_if_throttled=True): text_list = list(text_list) self.check_batch_limits(text_list, batch_size) url = self.endpoint + module_id + '/extract/' res = [] responses = [] for i in range(0, len(text_list), batch_size): data = { 'text_list': text_list[i:i+batch_size] } if kwargs is not None: for key, value in kwargs.iteritems(): data[key] = value response = self.make_request(url, 'POST', data, sleep_if_throttled) self.handle_errors(response) responses.append(response) res.extend(response.json()['result']) return MonkeyLearnResponse(res, responses)
# -*- coding: utf-8 -*- from __future__ import ( print_function, unicode_literals, division, absolute_import) from six.moves import range from monkeylearn.utils import SleepRequestsMixin, MonkeyLearnResponse, HandleErrorsMixin from monkeylearn.settings import DEFAULT_BASE_ENDPOINT, DEFAULT_BATCH_SIZE class Extraction(SleepRequestsMixin, HandleErrorsMixin): def __init__(self, token, base_endpoint=DEFAULT_BASE_ENDPOINT): self.token = token self.endpoint = base_endpoint + 'extractors/' def extract(self, module_id, text_list, batch_size=DEFAULT_BATCH_SIZE, sleep_if_throttled=True): text_list = list(text_list) self.check_batch_limits(text_list, batch_size) url = self.endpoint + module_id + '/extract/' res = [] responses = [] for i in range(0, len(text_list), batch_size): data = { 'text_list': text_list[i:i+batch_size] } response = self.make_request(url, 'POST', data, sleep_if_throttled) self.handle_errors(response) responses.append(response) res.extend(response.json()['result']) return MonkeyLearnResponse(res, responses)
Add minimal shutdown signal handling
<?php declare(ticks = 1); namespace Aerys\Watch; use Aerys\Server, Aerys\BinOptions, Aerys\Bootstrapper; class DebugWatcher { public function watch(BinOptions $binOptions) { list($reactor, $server, $hosts) = (new Bootstrapper)->boot($binOptions); register_shutdown_function(function() use ($server) { $this->shutdown($server); }); $server->start($hosts); foreach ($hosts->getBindableAddresses() as $addr) { $addr = substr(str_replace('0.0.0.0', '*', $addr), 6); printf("Listening for HTTP traffic on %s ...\n", $addr); } if (extension_loaded('pcntl')) { $f = function() use ($server) { $server->stop()->onComplete(function(){ exit; }); }; pcntl_signal(SIGINT, $f); pcntl_signal(SIGTERM, $f); } $reactor->run(); } private function shutdown(Server $server) { if (!$err = error_get_last()) { return; } switch ($err['type']) { case E_ERROR: case E_PARSE: case E_USER_ERROR: case E_CORE_ERROR: case E_CORE_WARNING: case E_COMPILE_ERROR: case E_COMPILE_WARNING: extract($err); printf("%s in %s on line %d\n", $message, $file, $line); $server->stop()->onComplete(function() { exit; }); break; } } }
<?php namespace Aerys\Watch; use Aerys\Server, Aerys\BinOptions, Aerys\Bootstrapper; class DebugWatcher { public function watch(BinOptions $binOptions) { list($reactor, $server, $hosts) = (new Bootstrapper)->boot($binOptions); register_shutdown_function(function() use ($server) { $this->shutdown($server); }); $server->start($hosts); foreach ($hosts->getBindableAddresses() as $addr) { $addr = substr(str_replace('0.0.0.0', '*', $addr), 6); printf("Listening for HTTP traffic on %s ...\n", $addr); } $reactor->run(); } private function shutdown(Server $server) { if (!$err = error_get_last()) { return; } switch ($err['type']) { case E_ERROR: case E_PARSE: case E_USER_ERROR: case E_CORE_ERROR: case E_CORE_WARNING: case E_COMPILE_ERROR: case E_COMPILE_WARNING: extract($err); printf("%s in %s on line %d\n", $message, $file, $line); $server->stop()->onComplete(function() { exit; }); break; } } }
Fix error when loading without auth config
var _ = require('lodash'); var crc = require('crc'); // Base structure for a configuration module.exports = function(options) { options = _.defaults(options, { // Port for running the webserver 'port': 3000, // Root folder 'root': process.cwd(), // Workspace id 'id': null, // Secret identifier for the workspace 'secret': null, // Events reporting 'reporting': { 'timeout': 180 * 1e3 }, // Authentication settings 'auth': {}, // Hooks 'hooks': { 'users.auth': function(data) { if (!data.email || !data.token) throw "Need 'token' and 'email' for auth hook"; var userId = data.email; var token = data.token; if (_.size(options.auth.users) > 0) { if (!options.auth.users[userId] || token != options.auth.users[userId]) throw "Invalid user"; } return { 'id': userId, 'name': userId, 'token': data.token, 'email': data.email }; }, } }); // Unique id for workspace options.id = options.id || crc.hex32(crc.crc32(options.root)) return options; };
var _ = require('lodash'); var crc = require('crc'); // Base structure for a configuration module.exports = function(options) { options = _.defaults(options, { // Port for running the webserver 'port': 3000, // Root folder 'root': process.cwd(), // Workspace id 'id': null, // Secret identifier for the workspace 'secret': null, // Events reporting 'reporting': { 'timeout': 180 * 1e3 }, // Hooks 'hooks': { 'users.auth': function(data) { if (!data.email || !data.token) throw "Need 'token' and 'email' for auth hook"; var userId = data.email; var token = data.token; if (_.size(options.auth.users) > 0) { if (!options.auth.users[userId] || token != options.auth.users[userId]) throw "Invalid user"; } return { 'id': userId, 'name': userId, 'token': data.token, 'email': data.email }; }, } }); // Unique id for workspace options.id = options.id || crc.hex32(crc.crc32(options.root)) return options; };
Set name as mandatory element for reset form creation
<?php namespace GoalioForgotPassword\Form; use Laminas\Form\Form; use Laminas\Form\Element; use GoalioForgotPassword\Options\ForgotOptionsInterface; class Reset extends Form { /** * @var ForgotOptionsInterface */ protected $forgotOptions; public function __construct($name, ForgotOptionsInterface $forgotOptions) { $this->setForgotOptions($forgotOptions); parent::__construct($name); $this->add(array( 'name' => 'newCredential', 'options' => array( 'label' => 'New Password', ), 'attributes' => array( 'type' => 'password', ), )); $this->add(array( 'name' => 'newCredentialVerify', 'options' => array( 'label' => 'Verify New Password', ), 'attributes' => array( 'type' => 'password', ), )); $submitElement = new Element\Button('submit'); $submitElement ->setLabel('Set new password') ->setAttributes(array( 'type' => 'submit', )); $this->add($submitElement, array( 'priority' => -100, )); } public function setForgotOptions(ForgotOptionsInterface $forgotOptions) { $this->forgotOptions = $forgotOptions; return $this; } public function getForgotOptions() { return $this->forgotOptions; } }
<?php namespace GoalioForgotPassword\Form; use Laminas\Form\Form; use Laminas\Form\Element; use GoalioForgotPassword\Options\ForgotOptionsInterface; class Reset extends Form { /** * @var ForgotOptionsInterface */ protected $forgotOptions; public function __construct($name = null, ForgotOptionsInterface $forgotOptions) { $this->setForgotOptions($forgotOptions); parent::__construct($name); $this->add(array( 'name' => 'newCredential', 'options' => array( 'label' => 'New Password', ), 'attributes' => array( 'type' => 'password', ), )); $this->add(array( 'name' => 'newCredentialVerify', 'options' => array( 'label' => 'Verify New Password', ), 'attributes' => array( 'type' => 'password', ), )); $submitElement = new Element\Button('submit'); $submitElement ->setLabel('Set new password') ->setAttributes(array( 'type' => 'submit', )); $this->add($submitElement, array( 'priority' => -100, )); } public function setForgotOptions(ForgotOptionsInterface $forgotOptions) { $this->forgotOptions = $forgotOptions; return $this; } public function getForgotOptions() { return $this->forgotOptions; } }
Fix: Reset GIDs works even if user has no pub_key
#!/usr/bin/env python # -*- coding:utf-8 -*- import types from sfa.storage.model import * from sfa.storage.alchemy import * from sfa.trust.gid import create_uuid from sfa.trust.hierarchy import Hierarchy from sfa.util.xrn import Xrn from sfa.trust.certificate import Certificate, Keypair, convert_public_key def fix_users(): s=global_dbsession hierarchy = Hierarchy() users = s.query(RegRecord).filter_by(type="user") for record in users: record.gid = "" if not record.gid: uuid = create_uuid() pkey = Keypair(create=True) pub_key=getattr(record,'reg_keys',None) print pub_key if len(pub_key) > 0: # use only first key in record if pub_key and isinstance(pub_key, types.ListType): pub_key = pub_key[0] pub_key = pub_key.key pkey = convert_public_key(pub_key) urn = Xrn (xrn=record.hrn, type='user').get_urn() email=getattr(record,'email',None) gid_object = hierarchy.create_gid(urn, uuid, pkey, email = email) gid = gid_object.save_to_string(save_parents=True) record.gid = gid s.commit() if __name__ == '__main__': fix_users()
#!/usr/bin/env python # -*- coding:utf-8 -*- import types from sfa.storage.model import * from sfa.storage.alchemy import * from sfa.trust.gid import create_uuid from sfa.trust.hierarchy import Hierarchy from sfa.util.xrn import Xrn from sfa.trust.certificate import Certificate, Keypair, convert_public_key def fix_users(): s=global_dbsession hierarchy = Hierarchy() users = s.query(RegRecord).filter_by(type="user") for record in users: record.gid = "" if not record.gid: uuid = create_uuid() pkey = Keypair(create=True) pub_key=getattr(record,'reg_keys',None) if pub_key is not None: # use only first key in record if pub_key and isinstance(pub_key, types.ListType): pub_key = pub_key[0] pub_key = pub_key.key pkey = convert_public_key(pub_key) urn = Xrn (xrn=record.hrn, type='user').get_urn() email=getattr(record,'email',None) gid_object = hierarchy.create_gid(urn, uuid, pkey, email = email) gid = gid_object.save_to_string(save_parents=True) record.gid = gid s.commit() if __name__ == '__main__': fix_users()
Add 2 form configuration (coosos_tag_auto_complete, coosos_tag_persist_new)
<?php namespace Coosos\TagBundle\Form\Type; use Coosos\TagBundle\Form\DataTransformer\TagsTransformer; use Doctrine\Common\Persistence\ObjectManager; use Symfony\Bridge\Doctrine\Form\DataTransformer\CollectionToArrayTransformer; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormView; use Symfony\Component\OptionsResolver\OptionsResolver; class TagsType extends AbstractType { /** * @var ObjectManager */ private $manager; /** * TagsType constructor. * @param ObjectManager $manager */ public function __construct(ObjectManager $manager) { $this->manager = $manager; } public function buildView(FormView $view, FormInterface $form, array $options) { $view->vars = array_merge($view->vars, $options); } /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->addModelTransformer(new CollectionToArrayTransformer(), true) ->addModelTransformer(new TagsTransformer($this->manager), true); } /** * @param OptionsResolver $resolver */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ "required" => false, "coosos_tag_auto_complete" => true, "coosos_tag_persist_new" => true, ]); } /** * @return string */ public function getParent(): string { return TextType::class; } }
<?php namespace Coosos\TagBundle\Form\Type; use Coosos\TagBundle\Form\DataTransformer\TagsTransformer; use Doctrine\Common\Persistence\ObjectManager; use Symfony\Bridge\Doctrine\Form\DataTransformer\CollectionToArrayTransformer; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class TagsType extends AbstractType { /** * @var ObjectManager */ private $manager; /** * TagsType constructor. * @param ObjectManager $manager */ public function __construct(ObjectManager $manager) { $this->manager = $manager; } /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->addModelTransformer(new CollectionToArrayTransformer(), true) ->addModelTransformer(new TagsTransformer($this->manager), true); } /** * @param OptionsResolver $resolver */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ "required" => false, ]); } /** * @return string */ public function getParent(): string { return TextType::class; } }
Add method to get lists vendors
<?php /** * Vendor Class * * Manage vendor and can automatically detect vendor. * * @package Core */ class Vendor { private $vendors = array(); public function __construct() { if (ENVIRONMENT == 'testing' || ENVIRONMENT == 'development') { $dirs = scandir(BASE_PATH); $length = count($dirs); $arr = array(); for ($i = 0 ; $i < count($dirs) ; $i++) { if ($dirs[$i] != '.' && $dirs[$i] != '..' && $dirs[$i] != '.git' && is_dir($dirs[$i])) { $arr[] = $dirs[$i]; } } $config =& loadClass('Config', 'Core'); $config->save('Vendor', $arr); $this->vendors = $arr; } } public function lists() { return $this->vendors; } } ?>
<?php /** * Vendor Class * * Manage vendor and can automatically detect vendor. * * @package Core */ class Vendor { public function __construct() { if (ENVIRONMENT == 'testing' || ENVIRONMENT == 'development') { $dirs = scandir(BASE_PATH); $length = count($dirs); $arr = array(); for ($i = 0 ; $i < count($dirs) ; $i++) { if ($dirs[$i] != '.' && $dirs[$i] != '..' && $dirs[$i] != '.git' && is_dir($dirs[$i])) { $arr[] = $dirs[$i]; } } $config =& loadClass('Config', 'Core'); $config->save('Vendor', $arr); } } } ?>
Change the types according to the names in the README
var replaceAll = function( occurrences ) { var configs = this; return { from: function( target ) { return { to: function( replacement ) { var template; var index = -1; if ( configs.ignoringCase ) { template = occurrences.toLowerCase(); while(( index = target .toLowerCase() .indexOf( template, index === -1 ? 0 : index + replacement.length ) ) !== -1 ) { target = target .substring( 0, index ) + replacement + target.substring( index + replacement.length ); } return target; } return target.split( occurrences ).join( replacement ); } }; }, ignoringCase: function() { return replaceAll.call({ ignoringCase: true }, occurrences ); } }; }; module.exports = { all: replaceAll };
var replaceAll = function( oldToken ) { var configs = this; return { from: function( string ) { return { to: function( newToken ) { var template; var index = -1; if ( configs.ignoringCase ) { template = oldToken.toLowerCase(); while(( index = string .toLowerCase() .indexOf( template, index === -1 ? 0 : index + newToken.length ) ) !== -1 ) { string = string .substring( 0, index ) + newToken + string.substring( index + newToken.length ); } return string; } return string.split( oldToken ).join( newToken ); } }; }, ignoringCase: function() { return replaceAll.call({ ignoringCase: true }, oldToken ); } }; }; module.exports = { all: replaceAll };
Add 'ujson' requirement for tests & aiohttp
# -*- coding: utf-8 -*- from __future__ import unicode_literals import codecs from setuptools import setup, find_packages setup( name='venom', version='1.0.0a1', packages=find_packages(exclude=['*tests*']), url='https://github.com/biosustain/venom', license='MIT', author='Lars Schöning', author_email='[email protected]', description='Venom is an upcoming RPC framework for Python', long_description=codecs.open('README.rst', encoding='utf-8').read(), test_suite='nose.collector', tests_require=[ 'aiohttp', 'ujson', 'nose' ], install_requires=[], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules' ], zip_safe=False, extras_require={ 'docs': ['sphinx'], 'aiohttp': ['aiohttp', 'ujson'], 'grpc': ['grpcio'], 'zmq': ['pyzmq'], } )
# -*- coding: utf-8 -*- from __future__ import unicode_literals import codecs from setuptools import setup, find_packages setup( name='Venom', version='1.0.0a1', packages=find_packages(exclude=['*tests*']), url='https://github.com/biosustain/venom', license='MIT', author='Lars Schöning', author_email='[email protected]', description='Venom is an upcoming RPC framework for Python', long_description=codecs.open('README.rst', encoding='utf-8').read(), test_suite='nose.collector', tests_require=[ 'aiohttp', 'nose' ], install_requires=[ ], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules' ], zip_safe=False, extras_require={ 'docs': ['sphinx'], 'aiohttp': ['aiohttp'], 'grpc': ['grpcio'], 'zmq': ['pyzmq'], } )
Use hot loading for css
'use-strict'; var path = require('path'); var webpack = require('webpack'); module.exports = { context: __dirname, entry: { app: [ 'webpack-hot-middleware/client', 'babel-polyfill', './js/index' ], style: [ 'webpack-hot-middleware/client', './css/index.scss' ] }, output: { path: path.join(__dirname, 'assets', 'js'), filename: '[name].bundle.js', publicPath: '/assets/js/' }, module: { preLoaders: [{ loader: 'eslint', test: /\.jsx?$/, exclude: /node_modules/ }], loaders: [{ loader: 'babel', test: /\.jsx?$/, exclude: /node_modules/ }, { loaders: ['style', 'css?sourceMap', 'sass?sourceMap'], test: /\.scss$/ }] }, resolve: { extensions: ['', '.js', '.jsx'], modulesDirectories: ['node_modules'] }, debug: true, devtool: 'eval', plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new webpack.DefinePlugin({ __DEVELOPMENT__: true, 'process.env': { 'NODE_ENV': JSON.stringify('development') } }) ] };
'use-strict'; var path = require('path'); var webpack = require('webpack'); module.exports = { context: __dirname, entry: { app: [ 'webpack-hot-middleware/client', 'babel-polyfill', './js/index' ], style: './css/index.scss' }, output: { path: path.join(__dirname, 'assets', 'js'), filename: '[name].bundle.js', publicPath: '/assets/js/' }, module: { preLoaders: [{ loader: 'eslint', test: /\.jsx?$/, exclude: /node_modules/ }], loaders: [{ loader: 'babel', test: /\.jsx?$/, exclude: /node_modules/ }, { loaders: ['style', 'css?sourceMap', 'sass?sourceMap'], test: /\.scss$/ }] }, resolve: { extensions: ['', '.js', '.jsx'], modulesDirectories: ['node_modules'] }, debug: true, devtool: 'eval', plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new webpack.DefinePlugin({ __DEVELOPMENT__: true, 'process.env': { 'NODE_ENV': JSON.stringify('development') } }) ] };
Fix typos in `Krang.deepExtend` function.
Krang.deepExtend = function(destination, source) { for (var property in source) { var type = typeof source[property], deep = true; if (source[property] === null || type !== 'object') deep = false; if (Object.isElement(source[property])) deep = false; if (source[property] && source[property].constructor && source[property].constructor !== Object) { deep = false; } if (deep) { destination[property] = destination[property] || {}; arguments.callee(destination[property], source[property]); } else { destination[property] = source[property]; } } return destination; }; Krang.Mixin = {}; Krang.Mixin.Configurable = { setOptions: function(options) { this.options = {}; var constructor = this.constructor; if (constructor.superclass) { // Build the inheritance chain. var chain = [], klass = constructor; while (klass = klass.superclass) chain.push(klass); chain = chain.reverse(); for (var i = 0, l = chain.length; i < l; i++) Krang.deepExtend(this.options, chain[i].DEFAULT_OPTIONS || {}); } Krang.deepExtend(this.options, constructor.DEFAULT_OPTIONS || {}); return Krang.deepExtend(this.options, options || {}); } };
Krang.deepExtend = function(destination, source) { for (var property in source) { var type = typeof source[property], deep = true; if (source[property] === null || type !== 'object') deep = false; if (Object.isElement(source[propety])) deep = false; if (source[property] && source[property].constructor && source[property].constructor !== Object) { deep = false; } if (deep) { destination[property] = destination[property] || {}; arguments.callee(destination[property], source[property]); } else { destination[property] = source[property]; } } return destination; }; Krang.Mixin = {}; Krang.Mixin.Configurable = { setOptions: function(options) { this.options = {}; var constructor = this.constructor; if (constructor.superclass) { // Build the inheritance chain. var chain = [], klass = constructor; while (klass = klass.superclass) chain.push(klass); chain = chain.reverse(); for (var i = 0, l = chain.length; i < l; i++) Krang.deepExtend(this.options, chain[i].DEFAULT_OPTIONS || {}); } Krang.deepExtend(this.options, constructor.DEFAULT_OPTIONS); return Krang.deepExtend(this.options, options || {}); } };
Fix check for valid date to avoid displaying invalid dates
//noinspection JSUnusedAssignment dashlight.widgets = (function (module) { module.build_status = (function () { var build = function (content) { var text; var textDuration; var minutes; text = content.branch + " build" + " is " + content.state; if (content.startTime.isValid()) { text = text + "; started at " + content.startTime.format("DD MMM YYYY HH:mm:ss"); } if (!!content.finishTime.isValid()) { minutes = content.duration.minutes(); textDuration = content.duration.seconds() + "s"; if (minutes > 0) { textDuration = minutes + "m:" + textDuration; } text = text + "; finished at " + content.finishTime.format("DD MMM YYYY HH:mm:ss") + " (" + textDuration + ")"; } return $("<div></div>").text(text); }; return { build: build } }()); return module; }(dashlight.widgets || {}));
//noinspection JSUnusedAssignment dashlight.widgets = (function (module) { module.build_status = (function () { var build = function (content) { var text; var textDuration; var minutes; text = content.branch + " build" + " is " + content.state; if (!!content.startTime) { text = text + "; started at " + content.startTime.format("DD MMM YYYY HH:mm:ss"); } if (!!content.finishTime) { minutes = content.duration.minutes(); textDuration = content.duration.seconds() + "s"; if (minutes > 0) { textDuration = minutes + "m:" + textDuration; } text = text + "; finished at " + content.finishTime.format("DD MMM YYYY HH:mm:ss") + " (" + textDuration + ")"; } return $("<div></div>").text(text); }; return { build: build } }()); return module; }(dashlight.widgets || {}));
Change round:start to +5 days
<?php namespace OpenDominion\Console\Commands; use Carbon\Carbon; use Illuminate\Console\Command; use OpenDominion\Models\Round; use OpenDominion\Models\RoundLeague; class RoundStartCommand extends Command { protected $signature = 'round:start'; protected $description = 'Starts a new round (dev only)'; public function __construct() { parent::__construct(); // } public function handle() { $this->output->writeln('<info>Attempting to start a new round</info>'); $standardRoundLeague = RoundLeague::where('key', 'standard') ->firstOrFail(); $lastRound = Round::where('round_league_id', $standardRoundLeague->id) ->orderBy('number', 'desc') ->firstOrFail(); if ($lastRound->isActive()) { $this->output->writeln("<error>Did not create a new round because round {$lastRound->number} in {$standardRoundLeague->description} is still active!</error>"); return false; } $newRound = Round::create([ 'round_league_id' => $standardRoundLeague->id, 'number' => ($lastRound->number + 1), 'name' => 'Development Round', 'start_date' => new Carbon('+5 days midnight'), 'end_date' => new Carbon('+55 days midnight'), ]); $this->output->writeln("<info>Round {$newRound->number} created successfully</info>"); } }
<?php namespace OpenDominion\Console\Commands; use Carbon\Carbon; use Illuminate\Console\Command; use OpenDominion\Models\Round; use OpenDominion\Models\RoundLeague; class RoundStartCommand extends Command { protected $signature = 'round:start'; protected $description = 'Starts a new round (dev only)'; public function __construct() { parent::__construct(); // } public function handle() { $this->output->writeln('<info>Attempting to start a new round</info>'); $standardRoundLeague = RoundLeague::where('key', 'standard') ->firstOrFail(); $lastRound = Round::where('round_league_id', $standardRoundLeague->id) ->orderBy('number', 'desc') ->firstOrFail(); if ($lastRound->isActive()) { $this->output->writeln("<error>Did not create a new round because round {$lastRound->number} in {$standardRoundLeague->description} is still active!</error>"); return false; } $newRound = Round::create([ 'round_league_id' => $standardRoundLeague->id, 'number' => ($lastRound->number + 1), 'name' => 'Development Round', 'start_date' => new Carbon('tomorrow midnight'), 'end_date' => new Carbon('+51 days midnight'), ]); $this->output->writeln("<info>Round {$newRound->number} created successfully</info>"); } }
Set default creation date for new episode
<?php /** * episode actions. * * @package sflimetracker * @subpackage episode */ class episodeActions extends sfActions { public function executeAdd($request) { $this->form=new EpisodeForm(); if ($request->isMethod('post')) { $this->form->bind($request->getPostParameters()); if($this->form->isValid()) { $episode=$this->form->save(); // redirect to default feed $this->redirect('episode/view?episode_id='.$episode->getId()); } else return; } $this->form->setDefaults(Array( 'podcast_id'=>$request->getParameter('podcast_id'), 'created_at'=>time() ),Array()); } public function executeView($request) { $id=$request->getParameter('id'); $this->episode=$episode=EpisodePeer::retrieveByPK($id); $this->forward404Unless($episode); $this->podcast=$podcast=$episode->getPodcast(); $this->forward404Unless($podcast); $this->torrents=$torrents=$episode->getTorrentsJoinFeed(); $this->feeds=$feeds=$podcast->getFeeds(); $has_feeds=Array(); foreach($torrents as $torrent) { $has_feeds[]=$torrent->getFeed(); } $this->missing_feeds=array_diff($feeds,$has_feeds); $this->form=new EpisodeForm($episode); } }
<?php /** * episode actions. * * @package sflimetracker * @subpackage episode */ class episodeActions extends sfActions { public function executeAdd($request) { $this->form=new EpisodeForm(); if ($request->isMethod('post')) { $this->form->bind($request->getPostParameters()); if($this->form->isValid()) { $episode=$this->form->save(); // redirect to default feed $this->redirect('episode/view?episode_id='.$episode->getId()); } else return; } $this->form->setDefaults(Array( 'podcast_id'=>$request->getParameter('podcast_id') ),Array()); } public function executeView($request) { $id=$request->getParameter('id'); $this->episode=$episode=EpisodePeer::retrieveByPK($id); $this->forward404Unless($episode); $this->podcast=$podcast=$episode->getPodcast(); $this->forward404Unless($podcast); $this->torrents=$torrents=$episode->getTorrentsJoinFeed(); $this->feeds=$feeds=$podcast->getFeeds(); $has_feeds=Array(); foreach($torrents as $torrent) { $has_feeds[]=$torrent->getFeed(); } $this->missing_feeds=array_diff($feeds,$has_feeds); $this->form=new EpisodeForm($episode); } }
Add logic check to only throw DelayException if required
<?php namespace Smartbox\Integration\FrameworkBundle\Core\Processors\ControlFlow; use Smartbox\CoreBundle\Type\SerializableArray; use Smartbox\Integration\FrameworkBundle\Core\Exchange; use Smartbox\Integration\FrameworkBundle\Core\Processors\Exceptions\DelayException; use Smartbox\Integration\FrameworkBundle\Core\Processors\Exceptions\ThrottledException; use Smartbox\Integration\FrameworkBundle\Core\Processors\Exceptions\ThrottlingLimitReachedException; use Smartbox\Integration\FrameworkBundle\Core\Processors\Processor; class DelayInterceptor extends Processor { protected $delayPeriod = 0; /** * @return bool */ public function isRuntimeBreakpoint() { return $this->runtimeBreakpoint; } /** * @param bool $runtimeBreakpoint */ public function setRuntimeBreakpoint($runtimeBreakpoint) { $this->runtimeBreakpoint = $runtimeBreakpoint; } /** * @return int */ public function getDelayPeriod() { return $this->delayPeriod; } /** * @param int $periodMs */ public function setDelayPeriod(int $delayPeriod) { $this->delayPeriod = $delayPeriod; } /** * @param Exchange $exchange * @param SerializableArray $processingContext * * @throws ThrottlingLimitReachedException * @throws ThrottledException */ protected function doProcess(Exchange $exchange, SerializableArray $processingContext) { if ($this->delayPeriod > 0 || $exchange->getIn()->getHeader('delay') > 0) { throw new DelayException(); } } }
<?php namespace Smartbox\Integration\FrameworkBundle\Core\Processors\ControlFlow; use Smartbox\CoreBundle\Type\SerializableArray; use Smartbox\Integration\FrameworkBundle\Core\Exchange; use Smartbox\Integration\FrameworkBundle\Core\Processors\Exceptions\DelayException; use Smartbox\Integration\FrameworkBundle\Core\Processors\Exceptions\ThrottledException; use Smartbox\Integration\FrameworkBundle\Core\Processors\Exceptions\ThrottlingLimitReachedException; use Smartbox\Integration\FrameworkBundle\Core\Processors\Processor; class DelayInterceptor extends Processor { protected $delayPeriod = 0; /** * @return bool */ public function isRuntimeBreakpoint() { return $this->runtimeBreakpoint; } /** * @param bool $runtimeBreakpoint */ public function setRuntimeBreakpoint($runtimeBreakpoint) { $this->runtimeBreakpoint = $runtimeBreakpoint; } /** * @return int */ public function getDelayPeriod() { return $this->delayPeriod; } /** * @param int $periodMs */ public function setDelayPeriod(int $delayPeriod) { $this->delayPeriod = $delayPeriod; } /** * @param Exchange $exchange * @param SerializableArray $processingContext * * @throws ThrottlingLimitReachedException * @throws ThrottledException */ protected function doProcess(Exchange $exchange, SerializableArray $processingContext) { throw new DelayException(); } }
Set default duration for events to 1 hour. Signed-off-by: François de Metz <[email protected]>
var icalendar = require('icalendar'); var _ = require('underscore'); exports.generateIcal = function(currentUser, boards, params) { var ical = new icalendar.iCalendar(); boards.each(function(board) { board.cards().each(function(card) { // no arm, no chocolate if (!card.get('badges').due) return; if (params && params.only_me == 'true' && !_(card.get('idMembers')).include(currentUser.id)) { return; } var event = new icalendar.VEvent(card.id); event.setSummary(card.get('name')); event.setDescription(card.get('desc')); event.setDate(card.get('badges').due, 60*60); event.addProperty('ATTACH', card.get('url')); event.addProperty('URL', card.get('url')); if (params && params.alarm != '-1') { comp = event.addComponent('VALARM'); comp.addProperty('ACTION', 'DISPLAY'); comp.addProperty('DESCRIPTION', 'Generated by trello calendar'); comp.addProperty('TRIGGER', params.alarm); } ical.addComponent(event); }); }); return ical; }
var icalendar = require('icalendar'); var _ = require('underscore'); exports.generateIcal = function(currentUser, boards, params) { var ical = new icalendar.iCalendar(); boards.each(function(board) { board.cards().each(function(card) { // no arm, no chocolate if (!card.get('badges').due) return; if (params && params.only_me == 'true' && !_(card.get('idMembers')).include(currentUser.id)) { return; } var event = new icalendar.VEvent(card.id); event.setSummary(card.get('name')); event.setDescription(card.get('desc')); event.setDate(card.get('badges').due); event.addProperty('ATTACH', card.get('url')); event.addProperty('URL', card.get('url')); if (params && params.alarm != '-1') { comp = event.addComponent('VALARM'); comp.addProperty('ACTION', 'DISPLAY'); comp.addProperty('DESCRIPTION', 'Generated by trello calendar'); comp.addProperty('TRIGGER', params.alarm); } ical.addComponent(event); }); }); return ical; }
Fix indeterminate ordering issue for extensions The original code used set() to dedupe enabled extensions. This resulted in an arbitrary ordering of the values. The expected result was a deterministic ordering of loaded extensions that matches the order given by the whitelist. This removes the set() usage to preserve order. Existing users subject to the arbitrary ordering should be unaffected as their builds must already be tolerant to ordering changes to have worked thus far.
"""Tools for loading and validating extensions.""" from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import pkg_resources import semver class MissingDependency(Exception): """No dependency found.""" class InvalidDependency(Exception): """Found dependency but with the wrong version.""" def load_extensions(whitelist=()): """Get an iterable of extensions in order.""" whitelist = ('core',) + tuple(whitelist) extensions = pkg_resources.iter_entry_points('rpmvenv.extensions') extensions = ( extension for extension in extensions if extension.name in whitelist ) extensions = tuple(set(extensions)) extensions = sorted(extensions, key=lambda ext: whitelist.index(ext.name)) return tuple(extension.load() for extension in extensions) def validate_extensions(extensions): """Process the extension dependencies.""" ext_map = dict( (ext.name, ext) for ext in extensions ) for ext in extensions: for dependency, versions in ext.requirements.items(): ext_dependency = ext_map.get(dependency, None) if not ext_dependency: raise MissingDependency( '{0} is required by {1} but is not loaded.'.format( ext.name, dependency, ) ) for version in versions: if not semver.match(ext.version, version): raise InvalidDependency( '{0}-{1} required by {2} but found {0}-{3}.'.format( dependency, version, ext.name, ext.version, ) ) return extensions
"""Tools for loading and validating extensions.""" from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import pkg_resources import semver class MissingDependency(Exception): """No dependency found.""" class InvalidDependency(Exception): """Found dependency but with the wrong version.""" def load_extensions(whitelist=()): """Get an iterable of extensions in order.""" whitelist = tuple(set(('core',) + tuple(whitelist))) extensions = pkg_resources.iter_entry_points('rpmvenv.extensions') extensions = ( extension for extension in extensions if extension.name in whitelist ) extensions = tuple(set(extensions)) extensions = sorted(extensions, key=lambda ext: whitelist.index(ext.name)) return tuple(extension.load() for extension in extensions) def validate_extensions(extensions): """Process the extension dependencies.""" ext_map = dict( (ext.name, ext) for ext in extensions ) for ext in extensions: for dependency, versions in ext.requirements.items(): ext_dependency = ext_map.get(dependency, None) if not ext_dependency: raise MissingDependency( '{0} is required by {1} but is not loaded.'.format( ext.name, dependency, ) ) for version in versions: if not semver.match(ext.version, version): raise InvalidDependency( '{0}-{1} required by {2} but found {0}-{3}.'.format( dependency, version, ext.name, ext.version, ) ) return extensions
Resolve linting errors after upgrades
module.exports = { extends: ["matrix-org"], plugins: [ "babel", ], env: { browser: true, node: true, }, rules: { "no-var": ["warn"], "prefer-rest-params": ["warn"], "prefer-spread": ["warn"], "one-var": ["warn"], "padded-blocks": ["warn"], "no-extend-native": ["warn"], "camelcase": ["warn"], "no-multi-spaces": ["error", { "ignoreEOLComments": true }], "space-before-function-paren": ["error", { "anonymous": "never", "named": "never", "asyncArrow": "always", }], "arrow-parens": "off", "prefer-promise-reject-errors": "off", "quotes": "off", "indent": "off", "no-constant-condition": "off", "no-async-promise-executor": "off", // We use a `logger` intermediary module "no-console": "error", }, overrides: [{ "files": ["src/**/*.ts"], "extends": ["matrix-org/ts"], "rules": { // We're okay being explicit at the moment "@typescript-eslint/no-empty-interface": "off", // While we're converting to ts we make heavy use of this "@typescript-eslint/no-explicit-any": "off", "quotes": "off", }, }], };
module.exports = { extends: ["matrix-org"], plugins: [ "babel", ], env: { browser: true, node: true, }, rules: { "no-var": ["warn"], "prefer-rest-params": ["warn"], "prefer-spread": ["warn"], "one-var": ["warn"], "padded-blocks": ["warn"], "no-extend-native": ["warn"], "camelcase": ["warn"], "no-multi-spaces": ["error", { "ignoreEOLComments": true }], "space-before-function-paren": ["error", { "anonymous": "never", "named": "never", "asyncArrow": "always", }], "arrow-parens": "off", "prefer-promise-reject-errors": "off", "quotes": "off", "indent": "off", "no-constant-condition": "off", "no-async-promise-executor": "off", // We use a `logger` intermediary module "no-console": "error", }, overrides: [{ "files": ["src/**/*.ts"], "extends": ["matrix-org/ts"], "rules": { // While we're converting to ts we make heavy use of this "@typescript-eslint/no-explicit-any": "off", "quotes": "off", }, }], };
Fix typo, add beacon service bean
package com.aemreunal.config.controller; /* *************************** * Copyright (c) 2014 * * * * This code belongs to: * * * * @author Ahmet Emre Ünal * * S001974 * * * * [email protected] * * [email protected] * * * * aemreunal.com * *************************** */ import java.nio.charset.Charset; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import com.aemreunal.controller.BeaconController; import com.aemreunal.service.BeaconService; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.aemreunal" }) //@ContextConfiguration(classes = { CoreTestConfig.class }) public class BeaconControllerTestConfig { public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); @Bean public BeaconController beaconController() { return new BeaconController(); } @Bean public BeaconService beaconService() { return new BeaconService(); } }
package com.aemreunal.config.controller; /* *************************** * Copyright (c) 2014 * * * * This code belongs to: * * * * @author Ahmet Emre Ünal * * S001974 * * * * [email protected] * * [email protected] * * * * aemreunal.com * *************************** */ import java.nio.charset.Charset; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import com.aemreunal.controller.BeaconController; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.aemreunal" }) //@ContextConfiguration(classes = { CoreTestConfig.class }) public class BeaconControllerTestConfig { public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); @Bean public BeaconController projectController() { return new BeaconController(); } }
Fix the make_fragments_QB3_cluster.pl install path.
#!/usr/bin/env python2 from setuptools import setup, find_packages # Uploading to PyPI # ================= # The first time only: # $ python setup.py register -r pypi # # Every version bump: # $ git tag <version>; git push --tags # $ python setup.py sdist upload -r pypi version = '0.4.0' setup( name='klab', version=version, author='Kortemme Lab, UCSF', author_email='[email protected]', url='https://github.com/Kortemme-Lab/klab', download_url='https://github.com/Kortemme-Lab/klab/tarball/'+version, license='MIT', description="A collection of utilities used by our lab for computational biophysics", long_description=open('README.rst').read(), keywords=['utilities', 'library', 'biophysics'], classifiers=[ "Intended Audience :: Science/Research", "Topic :: Scientific/Engineering :: Bio-Informatics", "Development Status :: 3 - Alpha", 'Programming Language :: Python :: 2', ], packages=find_packages(), package_data={ 'klab.bio.fragments': [ 'make_fragments_QB3_cluster.pl', ], }, install_requires=[], entry_points={ 'console_scripts': [ 'klab_generate_fragments=klab.bio.fragments.generate_fragments:main', ], }, )
#!/usr/bin/env python2 from setuptools import setup, find_packages # Uploading to PyPI # ================= # The first time only: # $ python setup.py register -r pypi # # Every version bump: # $ git tag <version>; git push --tags # $ python setup.py sdist upload -r pypi version = '0.4.0' setup( name='klab', version=version, author='Kortemme Lab, UCSF', author_email='[email protected]', url='https://github.com/Kortemme-Lab/klab', download_url='https://github.com/Kortemme-Lab/klab/tarball/'+version, license='MIT', description="A collection of utilities used by our lab for computational biophysics", long_description=open('README.rst').read(), keywords=['utilities', 'library', 'biophysics'], classifiers=[ "Intended Audience :: Science/Research", "Topic :: Scientific/Engineering :: Bio-Informatics", "Development Status :: 3 - Alpha", 'Programming Language :: Python :: 2', ], packages=find_packages(), package_data={ 'klab.bio.fragments': [ 'make_fragments_RAP_cluster.pl', ], }, install_requires=[], entry_points={ 'console_scripts': [ 'klab_generate_fragments=klab.bio.fragments.generate_fragments:main', ], }, )
Fix zoom interpretation in helper
var path = require('path'), assert = require('assert'), fs = require('fs'); var carto = require('../lib/carto'); var tree = require('../lib/carto').tree; var helper = require('./support/helper'); function cleanupItem(key, value) { if (key === 'rules') return; else if (key === 'ruleIndex') return; else if (key === 'elements') return value.map(function(item) { return item.value; }); else if (key === 'filters') { var arr = []; for (var id in value.filters) arr.push(id + value.filters[id].val); if (arr.length) return arr; } else if (key === 'attachment' && value === '__default__') return; else if (key === 'zoom') { if (value != tree.Zoom.all) return (new tree.Zoom()).setZoom(value).toString(); } else return value; } describe('Specificity', function() { helper.files('specificity', 'mss', function(file) { it('should handle spec correctly in ' + file, function(done) { helper.file(file, function(content) { var tree = (new carto.Parser({ paths: [ path.dirname(file) ], filename: file })).parse(content); var mss = tree.toList({}); mss = helper.makePlain(mss, cleanupItem); helper.compareToFile(mss, file, helper.resultFile(file)); done(); }); }); }); });
var path = require('path'), assert = require('assert'), fs = require('fs'); var carto = require('../lib/carto'); var tree = require('../lib/carto').tree; var helper = require('./support/helper'); function cleanupItem(key, value) { if (key === 'rules') return; else if (key === 'ruleIndex') return; else if (key === 'elements') return value.map(function(item) { return item.value; }); else if (key === 'filters') { var arr = []; for (var id in value.filters) arr.push(id + value.filters[id].val); if (arr.length) return arr; } else if (key === 'attachment' && value === '__default__') return; else if (key === 'zoom') { if (value != tree.Zoom.all) return tree.Zoom.toString(value); } else return value; } describe('Specificity', function() { helper.files('specificity', 'mss', function(file) { it('should handle spec correctly in ' + file, function(done) { helper.file(file, function(content) { var tree = (new carto.Parser({ paths: [ path.dirname(file) ], filename: file })).parse(content); var mss = tree.toList({}); mss = helper.makePlain(mss, cleanupItem); helper.compareToFile(mss, file, helper.resultFile(file)); done(); }); }); }); });
Use the new PingPongModule Repository class
<?php namespace Modules\Media\Image; use Illuminate\Contracts\Config\Repository; use Pingpong\Modules\Repository as Module; class ThumbnailsManager { /** * @var Module */ private $module; /** * @var Repository */ private $config; /** * @param Repository $config * @param Module $module */ public function __construct(Repository $config, Module $module) { $this->module = $module; $this->config = $config; } /** * Return all thumbnails for all modules * @return array */ public function all() { $thumbnails = []; foreach ($this->module->enabled() as $enabledModule) { $configuration = $this->config->get(strtolower($enabledModule) . '::thumbnails'); $thumbnails = array_merge($thumbnails, $configuration); } return $thumbnails; } /** * Find the filters for the given thumbnail * @param $thumbnail */ public function find($thumbnail) { foreach ($this->all() as $thumbName => $filters) { if ($thumbName == $thumbnail) { return $filters; } } } }
<?php namespace Modules\Media\Image; use Illuminate\Contracts\Config\Repository; use Pingpong\Modules\Module; class ThumbnailsManager { /** * @var Module */ private $module; /** * @var Repository */ private $config; /** * @param Repository $config * @param Module $module */ public function __construct(Repository $config, Module $module) { $this->module = $module; $this->config = $config; } /** * Return all thumbnails for all modules * @return array */ public function all() { $thumbnails = []; foreach ($this->module->enabled() as $enabledModule) { $configuration = $this->config->get(strtolower($enabledModule) . '::thumbnails'); $thumbnails = array_merge($thumbnails, $configuration); } return $thumbnails; } /** * Find the filters for the given thumbnail * @param $thumbnail */ public function find($thumbnail) { foreach ($this->all() as $thumbName => $filters) { if ($thumbName == $thumbnail) { return $filters; } } } }
Add explicit dependency on Mercurial.
# coding=utf-8 # pylint: disable=missing-docstring # # 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 https://mozilla.org/MPL/2.0/. from setuptools import setup if __name__ == "__main__": setup(name="funfuzz", version="0.3.0", entry_points={ "console_scripts": ["funfuzz = funfuzz.bot:main"] }, packages=[ "funfuzz", "funfuzz.autobisectjs", "funfuzz.js", "funfuzz.util", "funfuzz.util.tooltool", ], package_data={"funfuzz": [ "autobisectjs/*", "js/*", "js/jsfunfuzz/*", "js/shared/*", "util/*", "util/tooltool/*", ]}, package_dir={"": "src"}, install_requires=[ "FuzzManager>=0.1.1", "lithium-reducer>=0.2.0", "mercurial>=4.3.3", ], zip_safe=False)
# coding=utf-8 # pylint: disable=missing-docstring # # 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 https://mozilla.org/MPL/2.0/. from setuptools import setup if __name__ == "__main__": setup(name="funfuzz", version="0.3.0", entry_points={ "console_scripts": ["funfuzz = funfuzz.bot:main"] }, packages=[ "funfuzz", "funfuzz.autobisectjs", "funfuzz.js", "funfuzz.util", "funfuzz.util.tooltool", ], package_data={"funfuzz": [ "autobisectjs/*", "js/*", "js/jsfunfuzz/*", "js/shared/*", "util/*", "util/tooltool/*", ]}, package_dir={"": "src"}, install_requires=[ "FuzzManager>=0.1.1", "lithium-reducer>=0.2.0", ], zip_safe=False)
Update playground sizes to be more representitive of real-world usage
'use strict'; import React, { Component } from 'react'; import Pic from '../lib/index.js'; export default class Playground extends Component { render() { return ( <html> <head> <meta charSet='UTF-8' /> <title>react-pic</title> </head> <body> <div id="root"> <Pic alt='heart' images={[ { width: 40, url: 'http://placehold.it/40?text=♥' }, { width: 200, url: 'http://placehold.it/200?text=♥' }, { width: 400, url: 'http://placehold.it/400?text=♥' }, { width: 600, url: 'http://placehold.it/600?text=♥' }, { width: 800, url: 'http://placehold.it/800?text=♥' } ]} /> </div> <script src='//localhost:8080/build/react-pic.js' /> </body> </html> ); } }
'use strict'; import React, { Component } from 'react'; import Pic from '../lib/index.js'; export default class Playground extends Component { render() { return ( <html> <head> <meta charSet='UTF-8' /> <title>react-pic</title> </head> <body> <div id="root"> <Pic alt='heart' images={[ { width: 290, url: 'http://placehold.it/290?text=♥' }, { width: 300, url: 'http://placehold.it/300?text=♥' }, { width: 353, url: 'http://placehold.it/353?text=♥' }, { width: 367, url: 'http://placehold.it/367?text=♥' }, { width: 630, url: 'http://placehold.it/630?text=♥' } ]} /> </div> <script src='//localhost:8080/build/react-pic.js' /> </body> </html> ); } }
Concatenate all subdirs, not just mixins
module.exports = function(grunt) { grunt.initConfig({ concat: { dist: { src: ['lib/osteo.js', 'lib/*.js', 'lib/**/*.js'], dest: 'osteo.js' } }, jshint: { options: { jshintrc: true }, beforeconcat: ['lib/**/*.js'], afterconcat: ['osteo.js'] }, uglify: { options: { report: 'min' }, dist: { src: 'osteo.js', dest: 'osteo.min.js' } }, mocha: { src: 'test/test.html', options: { bail: true, log: true, run: true, timeout: 1000, mocha: { ignoreLeaks: true } } }, watch: { files: ['lib/**/*.js'], tasks: ['concat', 'jshint'] } }); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-mocha'); grunt.registerTask('test', ['concat', 'mocha']); grunt.registerTask('default', ['test']); grunt.registerTask('release', ['concat', 'mocha', 'uglify']); };
module.exports = function(grunt) { grunt.initConfig({ concat: { dist: { src: ['lib/osteo.js', 'lib/*.js', 'lib/mixins/*.js'], dest: 'osteo.js' } }, jshint: { options: { jshintrc: true }, beforeconcat: ['lib/**/*.js'], afterconcat: ['osteo.js'] }, uglify: { options: { report: 'min' }, dist: { src: 'osteo.js', dest: 'osteo.min.js' } }, mocha: { src: 'test/test.html', options: { bail: true, log: true, run: true, timeout: 1000, mocha: { ignoreLeaks: true } } }, watch: { files: ['lib/**/*.js'], tasks: ['concat', 'jshint'] } }); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-mocha'); grunt.registerTask('test', ['concat', 'mocha']); grunt.registerTask('default', ['test']); grunt.registerTask('release', ['concat', 'mocha', 'uglify']); };
Fix history file parser to allow nonexistent file.
/* * Copyright (C) 2015 Archie L. Cobbs. All rights reserved. */ package org.jsimpledb.cli.cmd; import java.io.File; import java.util.EnumSet; import java.util.Map; import org.jsimpledb.SessionMode; import org.jsimpledb.cli.CliSession; import org.jsimpledb.parse.Parser; import org.jsimpledb.util.ParseContext; public class SetHistoryFileCommand extends AbstractCommand { public SetHistoryFileCommand() { super("set-history-file file.txt:file"); } @Override public String getHelpSummary() { return "Configures the history file used for command line tab-completion."; } @Override protected Parser<?> getParser(String typeName) { return "file".equals(typeName) ? new OutputFileParser() : super.getParser(typeName); } @Override public EnumSet<SessionMode> getSessionModes() { return EnumSet.allOf(SessionMode.class); } @Override public CliSession.Action getAction(CliSession session, ParseContext ctx, boolean complete, Map<String, Object> params) { final File file = (File)params.get("file.txt"); return new CliSession.TransactionalAction() { @Override public void run(CliSession session) throws Exception { session.getConsole().setHistoryFile(file); session.getWriter().println("Updated history file to " + file); } }; } }
/* * Copyright (C) 2015 Archie L. Cobbs. All rights reserved. */ package org.jsimpledb.cli.cmd; import java.io.File; import java.util.EnumSet; import java.util.Map; import org.jsimpledb.SessionMode; import org.jsimpledb.cli.CliSession; import org.jsimpledb.parse.Parser; import org.jsimpledb.util.ParseContext; public class SetHistoryFileCommand extends AbstractCommand { public SetHistoryFileCommand() { super("set-history-file file.txt:file"); } @Override public String getHelpSummary() { return "Configures the history file used for command line tab-completion."; } @Override protected Parser<?> getParser(String typeName) { return "file".equals(typeName) ? new InputFileParser() : super.getParser(typeName); } @Override public EnumSet<SessionMode> getSessionModes() { return EnumSet.allOf(SessionMode.class); } @Override public CliSession.Action getAction(CliSession session, ParseContext ctx, boolean complete, Map<String, Object> params) { final File file = (File)params.get("file.txt"); return new CliSession.TransactionalAction() { @Override public void run(CliSession session) throws Exception { session.getConsole().setHistoryFile(file); session.getWriter().println("Updated history file to " + file); } }; } }
Fix in app initialization for generators
from __future__ import unicode_literals import importlib from goerr import err from django.apps import AppConfig from chartflo.engine import ChartFlo GENERATORS = {} cf = ChartFlo() def load_generator(modname, subgenerator=None): try: path = modname + ".chartflo" if subgenerator is not None: path = path + "." + subgenerator mod = importlib.import_module(path) generator = getattr(mod, "run") return generator except ImportError as e: if "No module named" not in str(e): err.new(e) return None except Exception as e: err.new(e, load_generator, "Error loading module") class ChartfloConfig(AppConfig): name = 'chartflo' verbose_name = "Chartflo" def ready(self): """ Load generators and initialize class instance """ global GENERATORS, cf from django.conf import settings apps = settings.INSTALLED_APPS generators = {} for app in apps: try: res = load_generator(app) if res is not None: generators[app] = res except Exception as e: err.new(e, self.ready, "Can not initialize Chartflo generators") GENERATORS = generators if err.exists: err.trace()
from __future__ import unicode_literals import importlib from goerr import err from django.apps import AppConfig GENERATORS = {} cf = None def load_generator(modname, subgenerator=None): try: path = modname + ".chartflo" if subgenerator is not None: path = path + "." + subgenerator mod = importlib.import_module(path) generator = getattr(mod, "run") return generator except ImportError as e: if "No module named" not in str(e): err.new(e) return None except Exception as e: err.new(e, load_generator, "Error loading module") class ChartfloConfig(AppConfig): name = 'chartflo' verbose_name = "Chartflo" def ready(self): """ Load generators and initialize class instance """ global GENERATORS, cf from django.conf import settings apps = settings.INSTALLED_APPS generators = {} for app in apps: try: res = load_generator(app) if res is not None: generators[app] = res except Exception as e: err.new(e) GENERATORS = generators # Initialize class instance from chartflo.engine import ChartFlo cf = ChartFlo() if err.exists: err.trace()
Add environment variable for ability to set the output directory
#!/usr/bin/env python3 import configargparse from goodline_iptv.importer import do_import if __name__ == '__main__': parser = configargparse.ArgParser() parser.add_argument('-o', '--out-dir', required=True, env_var='OUTDIR', help='Output directory') parser.add_argument('-e', '--encoding', default='cp1251', env_var='ENCODING', help='Source JTV teleguide encoding') parser.add_argument('-t', '--timezone', default='+0700', env_var='TIMEZONE', help='Source JTV teleguide timezone') parser.add_argument('-u', '--udpxy', env_var='UDPXY_ADDR', help='Address of the udproxy service, if available') parser.add_argument('-v', '--verbosity', default=0, env_var='VERBOSITY', type=int, choices=range(0, 4), help='Verbosity level') args = parser.parse_args() do_import(args.verbosity, args.out_dir, args.encoding, args.timezone, args.udpxy)
#!/usr/bin/env python3 import configargparse from goodline_iptv.importer import do_import if __name__ == '__main__': parser = configargparse.ArgParser() parser.add_argument('-o', '--out-dir', required=True, help='Output directory') parser.add_argument('-e', '--encoding', default='cp1251', env_var='ENCODING', help='Source JTV teleguide encoding') parser.add_argument('-t', '--timezone', default='+0700', env_var='TIMEZONE', help='Source JTV teleguide timezone') parser.add_argument('-u', '--udpxy', env_var='UDPXY_ADDR', help='Address of the udproxy service, if available') parser.add_argument('-v', '--verbosity', default=0, env_var='VERBOSITY', type=int, choices=range(0, 4), help='Verbosity level') args = parser.parse_args() do_import(args.verbosity, args.out_dir, args.encoding, args.timezone, args.udpxy)
Save note on Enter key press, autofocus the input field
// @flow import type { TodoItem } from "./model/TodoItem"; import React from "react"; import ContentAdd from "material-ui/svg-icons/content/add"; import TextField from "material-ui/TextField"; import Paper from "material-ui/Paper"; import FloatingActionButton from "material-ui/FloatingActionButton"; import logo from "./logo.svg"; import TodoList from "./TodoListContainer"; import TodoToolbar from "./TodoToolbarContainer"; import "./App.css"; type Props = { items: Array<TodoItem>, addTodo: (text: string) => void }; const App = ({ items, addTodo }: Props) => { let inputTextField; const addItem = () => { const input = inputTextField.input; if (input.value) { addTodo(input.value); input.value = ""; } }; return ( <div className="App"> <TodoToolbar /> <TodoList items={items} /> <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "32px" }} > <TextField ref={node => (inputTextField = node)} onKeyPress={ev => { if (ev.key === "Enter") { addItem() } }} autoFocus={true} hintText="Enter you note" style={{ flex: 1, margin: "0 16px" }} /> <FloatingActionButton onClick={addItem}> <ContentAdd /> </FloatingActionButton> </div> </div> ); }; export default App;
// @flow import type { TodoItem } from "./model/TodoItem"; import React from "react"; import ContentAdd from "material-ui/svg-icons/content/add"; import TextField from "material-ui/TextField"; import Paper from "material-ui/Paper"; import FloatingActionButton from "material-ui/FloatingActionButton"; import logo from "./logo.svg"; import TodoList from "./TodoListContainer"; import TodoToolbar from "./TodoToolbarContainer"; import "./App.css"; type Props = { items: Array<TodoItem>, addTodo: (text: string) => void }; const App = ({ items, addTodo }: Props) => { let inputTextField; const addItem = () => { const input = inputTextField.input; if (input.value) { addTodo(input.value); input.value = ""; } }; return ( <div className="App"> <TodoToolbar /> <TodoList items={items} /> <div style={{ display: "flex", justifyContent: 'space-between', alignItems: "center", padding: '32px' }} > <TextField ref={node => (inputTextField = node)} hintText="Enter you note" style={{ flex: 1, margin: '0 16px' }} /> <FloatingActionButton onClick={addItem} > <ContentAdd /> </FloatingActionButton> </div> </div> ); }; export default App;
Fix CLI project name s/node-push-to-deploy/push-to-deploy
var fs = require("fs"); var http = require("http"); var nopt = require("nopt"); var main = require("./main"); var yaml = require("js-yaml"); var configs, options; function help() { var out = [ "Usage: push-to-deploy [-p port] config-file1 [config-file2 ...]", "", "General options:", " -h, --help # Print options and usage.", " -p, --port # Set listening port (default 8000).", "" ]; console.log(out.join("\n")); } options = nopt({ port: String }, { h: "--help", p: "--port" }); configs = options.argv.remain; module.exports = function() { if (options.help) { help(); process.exit(0); } if (!configs.length) { console.error("Missing config file.\n"); help(); process.exit(1); } try { configs = configs.map(function(config) { if (/yml$/i.test(config)) { return yaml.safeLoad(fs.readFileSync(config, "utf8")); } else if (/json$/i.test(config)) { return JSON.parse(fs.readFileSync(config, "utf8")); } else { throw new Error("Unsupported extension `" + config + "`. Supported JSON or YAML."); } }); } catch(error) { console.error(error, error.stack); process.exit(1); } main(configs, options); };
var fs = require("fs"); var http = require("http"); var nopt = require("nopt"); var main = require("./main"); var yaml = require("js-yaml"); var configs, options; function help() { var out = [ "Usage: node-push-to-deploy [-p port] config-file1 [config-file2 ...]", "", "General options:", " -h, --help # Print options and usage.", " -p, --port # Set listening port (default 8000).", "" ]; console.log(out.join("\n")); } options = nopt({ port: String }, { h: "--help", p: "--port" }); configs = options.argv.remain; module.exports = function() { if (options.help) { help(); process.exit(0); } if (!configs.length) { console.error("Missing config file.\n"); help(); process.exit(1); } try { configs = configs.map(function(config) { if (/yml$/i.test(config)) { return yaml.safeLoad(fs.readFileSync(config, "utf8")); } else if (/json$/i.test(config)) { return JSON.parse(fs.readFileSync(config, "utf8")); } else { throw new Error("Unsupported extension `" + config + "`. Supported JSON or YAML."); } }); } catch(error) { console.error(error, error.stack); process.exit(1); } main(configs, options); };
Fix plot title not showing up
from __future__ import (absolute_import, division, print_function, unicode_literals) from copy import deepcopy from ..utils.exceptions import GgplotError class labs(object): """ General class for all label adding classes """ labels = {} def __init__(self, *args, **kwargs): if args and not isinstance(args, dict): raise GgplotError( "'labs' excepts either a dictionary as", "an argument or keyword arguments") self.labels = args else: self.labels = kwargs def __radd__(self, gg): gg = deepcopy(gg) gg.labels.update(self.labels) return gg class xlab(labs): """ Create x-axis label """ def __init__(self, xlab): if xlab is None: raise GgplotError("Arguments to", self.__class__.__name__, "cannot be None") self.labels = {'x': xlab} class ylab(labs): """ Create y-axis label """ def __init__(self, ylab): if ylab is None: raise GgplotError("Arguments to", self.__class__.__name__, "cannot be None") self.labels = {'y': ylab} class ggtitle(labs): """ Create plot title """ def __init__(self, title): if title is None: raise GgplotError("Arguments to", self.__class__.__name__, "cannot be None") self.labels = {'title': title}
from __future__ import (absolute_import, division, print_function, unicode_literals) from copy import deepcopy from ..utils.exceptions import GgplotError class labs(object): """ General class for all label adding classes """ labels = {} def __init__(self, *args, **kwargs): if args and not isinstance(args, dict): raise GgplotError( "'labs' excepts either a dictionary as", "an argument or keyword arguments") self.labels = args else: self.labels = kwargs def __radd__(self, gg): gg = deepcopy(gg) gg.labels.update(self.labels) return gg class xlab(labs): """ Create x-axis label """ def __init__(self, xlab): if xlab is None: raise GgplotError("Arguments to", self.__class__.__name__, "cannot be None") self.labels = {'x': xlab} class ylab(labs): """ Create y-axis label """ def __init__(self, ylab): if ylab is None: raise GgplotError("Arguments to", self.__class__.__name__, "cannot be None") self.labels = {'y': ylab} class ggtitle(labs): """ Create plot title """ def __init__(self, title): if title is None: raise GgplotError("Arguments to", self.__class__.__name__, "cannot be None") self.label = {'title': title}
Fix warning for foreign key detection
<?php /** * PHP version 7.1 * * This source file is subject to the license that is bundled with this package in the file LICENSE. */ namespace ComPHPPuebla\Fixtures\Processors; class ForeignKeyProcessor implements Processor { /** @var array */ protected $references; public function __construct() { $this->references = []; } public function process(array $row): array { $processedRows = []; foreach ($row as $column => $value) { if (null === $value) { $processedRows[$column] = $value; continue; } $processedRows[$column] = $this->parseKeyIfNeeded($value); } return $processedRows; } public function postProcessing(string $key, int $id): void { $this->addReference($key, $id); } private function addReference(string $key, int $id) { $this->references[$key] = $id; } /** * @return mixed */ private function parseKeyIfNeeded(string $value) { if ($this->isAReference($value) && $this->referenceExistsFor($value)) { return $this->references[substr($value, 1)]; } return $value; } private function isAReference(string $value): bool { if (empty($value)) { return false; } return '@' === $value[0]; } private function referenceExistsFor(string $value): bool { return isset($this->references[substr($value, 1)]); } }
<?php /** * PHP version 7.1 * * This source file is subject to the license that is bundled with this package in the file LICENSE. */ namespace ComPHPPuebla\Fixtures\Processors; class ForeignKeyProcessor implements Processor { /** @var array */ protected $references; public function __construct() { $this->references = []; } public function process(array $row): array { $processedRows = []; foreach ($row as $column => $value) { if (null === $value) { $processedRows[$column] = $value; continue; } $processedRows[$column] = $this->parseKeyIfNeeded($value); } return $processedRows; } public function postProcessing(string $key, int $id): void { $this->addReference($key, $id); } private function addReference(string $key, int $id) { $this->references[$key] = $id; } /** * @return mixed */ private function parseKeyIfNeeded(string $value) { if ($this->isAReference($value) && $this->referenceExistsFor($value)) { return $this->references[substr($value, 1)]; } return $value; } private function isAReference(string $value): bool { return '@' === $value[0]; } private function referenceExistsFor(string $value): bool { return isset($this->references[substr($value, 1)]); } }
:bug: Remove parameter left over from version of common terms search
function build(searchTerm) { return { index: 'profiles', type: 'gps', body: { size: 30, query: { bool: { should: [ { match_phrase: { name: { query: searchTerm, boost: 2, slop: 1 } } }, { match_phrase: { alternativeName: { query: searchTerm, boost: 2, slop: 1 } } }, { common: { name: { query: searchTerm, cutoff_frequency: 0.0001 } } }, { common: { alternativeName: { query: searchTerm, cutoff_frequency: 0.0001 } } }, { nested: { path: 'doctors', query: { bool: { should: [ { match_phrase: { 'doctors.name': { query: searchTerm, boost: 2, slop: 1 } } }, { match: { 'doctors.name': { query: searchTerm } } } ] } }, } }] } }, } }; } module.exports = { build, };
function build(searchTerm) { return { index: 'profiles', type: 'gps', body: { size: 30, query: { bool: { should: [ { match_phrase: { name: { query: searchTerm, boost: 2, slop: 1 } } }, { match_phrase: { alternativeName: { query: searchTerm, boost: 2, slop: 1 } } }, { common: { name: { query: searchTerm, cutoff_frequency: 0.0001 } } }, { common: { alternativeName: { query: searchTerm, cutoff_frequency: 0.0001 } } }, { nested: { path: 'doctors', query: { bool: { should: [ { match_phrase: { 'doctors.name': { query: searchTerm, boost: 2, slop: 1 } } }, { match: { 'doctors.name': { query: searchTerm, cutoff_frequency: 0.0001 } } } ] } }, } }] } }, } }; } module.exports = { build, };
Add 'smif version' to label
import React, { Component } from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { Link, Router } from 'react-router-dom' import { fetchSmifDetails } from '../actions/actions.js' class Footer extends Component { constructor(props) { super(props) } componentDidMount() { const { dispatch } = this.props dispatch(fetchSmifDetails()) } renderLoading() { return ( <div className="alert alert-primary"> Loading... </div> ) } renderError() { return ( <div className="alert alert-danger"> Error </div> ) } renderFooter(version) { return ( <div className="container"> <div className="row"> <div className="col"> smif version: <span className="badge badge-dark">{version}</span> </div> </div> </div> ) } render() { const {isFetching, smif} = this.props if (isFetching) { return this.renderLoading() } else { return this.renderFooter(smif.version) } } } Footer.propTypes = { smif: PropTypes.object.isRequired } function mapStateToProps(state) { const { smif } = state return { smif: state.smif.item, isFetching: (state.smif.isFetching) } } export default connect(mapStateToProps)(Footer)
import React, { Component } from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { Link, Router } from 'react-router-dom' import { fetchSmifDetails } from '../actions/actions.js' class Footer extends Component { constructor(props) { super(props) } componentDidMount() { const { dispatch } = this.props dispatch(fetchSmifDetails()) } renderLoading() { return ( <div className="alert alert-primary"> Loading... </div> ) } renderError() { return ( <div className="alert alert-danger"> Error </div> ) } renderFooter(version) { return ( <div className="container"> <div className="row justify-content-md-center"> <div className="col-md-auto"> <span className="badge badge-dark">{version}</span> </div> </div> </div> ) } render() { const {isFetching, smif} = this.props if (isFetching) { return this.renderLoading() } else { return this.renderFooter(smif.version) } } } Footer.propTypes = { smif: PropTypes.object.isRequired } function mapStateToProps(state) { const { smif } = state return { smif: state.smif.item, isFetching: (state.smif.isFetching) } } export default connect(mapStateToProps)(Footer)
Switch from watch to watchCollection for bodyclass directive
define([ 'angular', 'app', 'lodash' ], function (angular, app, _) { 'use strict'; angular .module('grafana.directives') .directive('bodyClass', function() { return { link: function($scope, elem) { var lastPulldownVal; var lastHideControlsVal; $scope.$watchCollection('dashboard.pulldowns', function() { if (!$scope.dashboard) { return; } var panel = _.find($scope.dashboard.pulldowns, function(pulldown) { return pulldown.enable; }); var panelEnabled = panel ? panel.enable : false; if (lastPulldownVal !== panelEnabled) { elem.toggleClass('submenu-controls-visible', panelEnabled); lastPulldownVal = panelEnabled; } }); $scope.$watch('dashboard.hideControls', function() { if (!$scope.dashboard) { return; } var hideControls = $scope.dashboard.hideControls || $scope.playlist_active; if (lastHideControlsVal !== hideControls) { elem.toggleClass('hide-controls', hideControls); lastHideControlsVal = hideControls; } }); $scope.$watch('playlist_active', function() { elem.toggleClass('hide-controls', $scope.playlist_active === true); elem.toggleClass('playlist-active', $scope.playlist_active === true); }); } }; }); });
define([ 'angular', 'app', 'lodash' ], function (angular, app, _) { 'use strict'; angular .module('grafana.directives') .directive('bodyClass', function() { return { link: function($scope, elem) { var lastPulldownVal; var lastHideControlsVal; $scope.$watch('dashboard.pulldowns', function() { if (!$scope.dashboard) { return; } var panel = _.find($scope.dashboard.pulldowns, function(pulldown) { return pulldown.enable; }); var panelEnabled = panel ? panel.enable : false; if (lastPulldownVal !== panelEnabled) { elem.toggleClass('submenu-controls-visible', panelEnabled); lastPulldownVal = panelEnabled; } }, true); $scope.$watch('dashboard.hideControls', function() { if (!$scope.dashboard) { return; } var hideControls = $scope.dashboard.hideControls || $scope.playlist_active; if (lastHideControlsVal !== hideControls) { elem.toggleClass('hide-controls', hideControls); lastHideControlsVal = hideControls; } }); $scope.$watch('playlist_active', function() { elem.toggleClass('hide-controls', $scope.playlist_active === true); elem.toggleClass('playlist-active', $scope.playlist_active === true); }); } }; }); });
Package settings now read from package file in parent folder
var through = require('through2') var gutil = require('gulp-util') var superagent = require('superagent') var extend = require('extend') var pkg = require('../package.json') var PluginError = gutil.PluginError var defaultConfig = extend({ port: 23956 }, pkg.notifyDte || {}); function gulpVSDTE(config) { var options = extend({}, defaultConfig, config || {}); var files = [] var endpoint = 'http://localhost:' + options.port + '/project/files' return through.obj(function (file, enc, cb) { // Record the path for sending to EnvDTE files.push(file.path) // Spit the file back into the pipeline without modification this.push(file) cb() }, function (cb) { superagent.put(endpoint) .send(JSON.stringify(files)) .set('Content-Type', 'application/json') .end(function (err, res) { if (err) gutil.log(err) else gutil.log(res.text) cb() }) }) } module.exports = gulpVSDTE;
var through = require('through2') var gutil = require('gulp-util') var superagent = require('superagent') var extend = require('extend') var PluginError = gutil.PluginError var defaultConfig = { port: 23956 } function gulpVSDTE(config) { var options = extend({}, defaultConfig, config || {}); var files = [] var endpoint = 'http://localhost:' + options.port + '/project/files' return through.obj(function (file, enc, cb) { // Record the path for sending to EnvDTE files.push(file.path) // Spit the file back into the pipeline without modification this.push(file) cb() }, function (cb) { superagent.put(endpoint) .send(JSON.stringify(files)) .set('Content-Type', 'application/json') .end(function (err, res) { if (err) gutil.log(err) else gutil.log(res.text) cb() }) }) } module.exports = gulpVSDTE;
Remove unused import and fix typo
from django.core.exceptions import ObjectDoesNotExist from django.core.management.base import BaseCommand from subscriptions.models import Subscription class Command(BaseCommand): help = ("Active subscription holders need to be informed via audio file " "about the new missed call service.") def handle(self, *args, **options): self.stdout.write("Processing active subscriptions ...") count = 0 try: active_subscriptions_list = list( Subscription.objects.filter(active=True)) except ObjectDoesNotExist: self.stdout.write("No active subscriptions found") if len(active_subscriptions_list) > 0: for active_subscription in active_subscriptions_list: # Add audio file to subscription meta_data. Not sure how we'll # handle translations here. if (active_subscription.metadata is not None and "welcome_message" not in active_subscription.metadata): active_subscription["audio_file_url"] = "audio_file_url" count += 1 if count > 0: self.stdout.write( "Update {} subscriptions with voice notes".format(count)) else: self.stdout.write( "No subscriptions updated with audio file notes")
from django.core.exceptions import ObjectDoesNotExist from django.core.management.base import BaseCommand, CommandError from subscriptions.models import Subscription class Command(BaseCommand): help = ("Active subscription holders need to be informed via audio file " "about the new missed call service.") def handle(self, *args, **options): self.stdout.write("Processing active subscriptions ...") count = 0 try: active_subscriptions_list = list( Subscription.objects.filter(active=True)) except ObjectDoesNotExist: self.stdout.write("No active subscriptions found") if len(active_subscriptions_list) > 0: for active_subscription in active_subscriptions_list: # Add audio file to subscription meta_data. Not sure how we'll # handle translations here. if (active_subscription.metadata is not None and "welcome_message" not in active_subscription.metadata): active_subscription["audo_file_url"] = "audio_file_url" count += 1 if count > 0: self.stdout.write( "Update {} subscriptions with voice notes".format(count)) else: self.stdout.write( "No subscriptions updated with audio file notes")
Make sure karma can access jquery-ui
var webpack = require('webpack'); // TODO: use BowerWebpackPlugin // var BowerWebpackPlugin = require('bower-webpack-plugin'); var webpackCommon = require('./webpack.common.config.js'); // Put in separate file? var webpackTestConfig = { devtool: 'inline-source-map', plugins: [ new webpack.ResolverPlugin( new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('bower.json', ['main']) ), new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery', 'window.$': 'jquery' }), ], resolve: webpackCommon.resolve, externals: {'jquery': 'jQuery', 'jquery-ui': 'jQuery.ui'}, module: { loaders: [ // Assume test files are ES6 {test: /\.test\.js$/, loader: 'babel-loader'}, ] } }; module.exports = function (config) { config.set({ browsers: ['PhantomJS'], frameworks: ['mocha', 'sinon'], files: [ 'website/static/vendor/bower_components/jquery/dist/jquery.js', 'website/static/vendor/bower_components/jquery-ui/ui/jquery-ui.js', // Only need to target one file, which will load all files in tests/ that // match *.test.js 'website/static/js/tests/tests.webpack.js', ], reporters: ['spec'], preprocessors: { // add webpack as preprocessor 'website/static/js/tests/tests.webpack.js': ['webpack', 'sourcemap'], }, webpack: webpackTestConfig, webpackServer: { noInfo: true // don't spam the console } }); };
var webpack = require('webpack'); // TODO: use BowerWebpackPlugin // var BowerWebpackPlugin = require('bower-webpack-plugin'); var webpackCommon = require('./webpack.common.config.js'); // Put in separate file? var webpackTestConfig = { devtool: 'inline-source-map', plugins: [ new webpack.ResolverPlugin( new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('bower.json', ['main']) ), new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery', 'window.$': 'jquery' }), ], resolve: webpackCommon.resolve, module: { loaders: [ // Assume test files are ES6 {test: /\.test\.js$/, loader: 'babel-loader'}, ] } }; module.exports = function (config) { config.set({ browsers: ['PhantomJS'], frameworks: ['mocha', 'sinon'], files: [ // Only need to target one file, which will load all files in tests/ that // match *.test.js 'website/static/js/tests/tests.webpack.js', ], reporters: ['spec'], preprocessors: { // add webpack as preprocessor 'website/static/js/tests/tests.webpack.js': ['webpack', 'sourcemap'], }, webpack: webpackTestConfig, webpackServer: { noInfo: true // don't spam the console } }); };
Add AuthenticationMiddleware to tests (for 1.7)
#!/usr/bin/env python import sys from os.path import abspath, dirname from django.conf import settings import django sys.path.insert(0, abspath(dirname(__file__))) if not settings.configured: settings.configure( INSTALLED_APPS=( 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.auth', 'django.contrib.admin', 'email_log', 'email_log.tests', ), DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, EMAIL_LOG_BACKEND = 'django.core.mail.backends.locmem.EmailBackend', MIDDLEWARE_CLASSES=( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ), ROOT_URLCONF='email_log.tests.urls', ) def runtests(): if hasattr(django, 'setup'): django.setup() try: from django.test.runner import DiscoverRunner runner_class = DiscoverRunner test_args = ['email_log.tests'] except ImportError: from django.test.simple import DjangoTestSuiteRunner runner_class = DjangoTestSuiteRunner test_args = ['tests'] failures = runner_class(failfast=False).run_tests(test_args) sys.exit(failures) if __name__ == "__main__": runtests()
#!/usr/bin/env python import sys from os.path import abspath, dirname from django.conf import settings import django sys.path.insert(0, abspath(dirname(__file__))) if not settings.configured: settings.configure( INSTALLED_APPS=( 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.auth', 'django.contrib.admin', 'email_log', 'email_log.tests', ), DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, EMAIL_LOG_BACKEND = 'django.core.mail.backends.locmem.EmailBackend', ROOT_URLCONF='email_log.tests.urls', ) def runtests(): if hasattr(django, 'setup'): django.setup() try: from django.test.runner import DiscoverRunner runner_class = DiscoverRunner test_args = ['email_log.tests'] except ImportError: from django.test.simple import DjangoTestSuiteRunner runner_class = DjangoTestSuiteRunner test_args = ['tests'] failures = runner_class(failfast=False).run_tests(test_args) sys.exit(failures) if __name__ == "__main__": runtests()
Delete init vertices from the polygon entity.
define( [ 'polygonjs/Entity', 'polygonjs/geom/Vector3' ], function (Entity, Vector3) { "use strict"; var Polygon = function (opts) { opts = opts || {}; Entity.call(this, opts); this.type = 'polygon'; this.vertices = opts.vertices || []; this.normal = opts.normal || Vector3.ONE; // this.initVertices(); }; Polygon.create = function (opts) { return new Polygon(opts); }; Polygon.prototype = Object.create(Entity.prototype); // Polygon.prototype.update = function (delta) { // var vertices = this.vertices, // worldVertices = this.worldVertices, // vertex, worldVertex, // i = vertices.length, // transform = this.getWorldTransform(); // // Apply world transformation // while (--i >= 0) { // vertex = vertices[i]; // worldVertices[i] = transform.multiplyVector(vertex); // TODO: slow! // } // }; // Polygon.prototype.draw = function (camera, surface) { // // ... // }; return Polygon; } );
define( [ 'polygonjs/Entity', 'polygonjs/geom/Vector3' ], function (Entity, Vector3) { "use strict"; var Polygon = function (opts) { opts = opts || {}; Entity.call(this, opts); this.type = 'polygon'; this.vertices = opts.vertices || []; this.normal = opts.normal || Vector3.ONE; // this.initVertices(); }; Polygon.create = function (opts) { return new Polygon(opts); }; Polygon.prototype = Object.create(Entity.prototype); // Polygon.prototype.initVertices = function () { // this.worldVertices = []; // this.viewVertices = []; // this.screenVertices = []; // var i = this.vertices.length; // while (--i >= 0) { // // this.worldVertices.push(Vector3.create(0, 0, 0)); // // this.viewVertices.push(Vector3.create(0, 0, 0)); // // this.screenVertices.push(Vector3.create(0, 0, 0)); // } // }; // Polygon.prototype.update = function (delta) { // var vertices = this.vertices, // worldVertices = this.worldVertices, // vertex, worldVertex, // i = vertices.length, // transform = this.getWorldTransform(); // // Apply world transformation // while (--i >= 0) { // vertex = vertices[i]; // worldVertices[i] = transform.multiplyVector(vertex); // TODO: slow! // } // }; // Polygon.prototype.draw = function (camera, surface) { // // ... // }; return Polygon; } );
Make the suggestion colorbox a square (increased the height)
/* * Author: Pierre-Henry Soria <[email protected]> * Copyright: (c) 2015-2020, Pierre-Henry Soria. All Rights Reserved. * License: GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. */ var $suggestionBox = (function () { $.get(pH7Url.base + 'ph7cms-helper/main/suggestionbox', function (oData) { $.colorbox({ width: '240px', height: '240px', speed: 500, scrolling: false, html: $(oData).find('#box_block') }) }) }); var $amendBoxBgColor = (function () { var aHexColors = [ '#ffffff', '#eceff1', '#ffdcd8', '#d1dce5', '#f9fbe7', '#ffe0b2', '#ffecb3', '#fff9c4', '#ffccbc', '#e0f7fa', '#fce4ec', '#b2dfdb' ]; var sRandomHexColor = aHexColors[Math.floor((Math.random() * aHexColors.length))]; $('#cboxContent').css('background-color', sRandomHexColor + ' !important') }); $(document).ready(function () { $suggestionBox(); $amendBoxBgColor(); });
/* * Author: Pierre-Henry Soria <[email protected]> * Copyright: (c) 2015-2019, Pierre-Henry Soria. All Rights Reserved. * License: GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. */ var $suggestionBox = (function () { $.get(pH7Url.base + 'ph7cms-helper/main/suggestionbox', function (oData) { $.colorbox({ width: '240px', height: '235px', speed: 500, scrolling: false, html: $(oData).find('#box_block') }) }) }); var $amendBoxBgColor = (function () { var aHexColors = [ '#ffffff', '#eceff1', '#ffdcd8', '#d1dce5', '#f9fbe7', '#ffe0b2', '#ffecb3', '#fff9c4', '#ffccbc', '#e0f7fa', '#fce4ec', '#b2dfdb' ]; var sRandomHexColor = aHexColors[Math.floor((Math.random() * aHexColors.length))]; $('#cboxContent').css('background-color', sRandomHexColor + ' !important') }); $(document).ready(function () { $suggestionBox(); $amendBoxBgColor(); });
Add trim and emptytonull middleware to global.
<?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { /** * The application's global HTTP middleware stack. * * These middleware are run during every request to your application. * * @var array */ protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \App\Http\Middleware\Trim::class, \App\Http\Middleware\EmptyToNull::class, ]; /** * The application's route middleware groups. * * @var array */ protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, ], 'api' => [ 'throttle:60,1', ], ]; /** * The application's route middleware. * * These middleware may be assigned to groups or used individually. * * @var array */ protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'safetext' => \App\Http\Middleware\SafeText::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, ]; }
<?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { /** * The application's global HTTP middleware stack. * * These middleware are run during every request to your application. * * @var array */ protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, ]; /** * The application's route middleware groups. * * @var array */ protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, ], 'api' => [ 'throttle:60,1', ], ]; /** * The application's route middleware. * * These middleware may be assigned to groups or used individually. * * @var array */ protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'safetext' => \App\Http\Middleware\SafeText::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'trim' => \App\Http\Middleware\TrimInput::class, ]; }
Add integrator property for Operations
import hoomd.integrate class Operations: def __init__(self, simulation=None): self.simulation = simulation self._compute = list() self._auto_schedule = False self._scheduled = False def add(self, op): if isinstance(op, hoomd.integrate._integrator): self._integrator = op else: raise ValueError("Operation is not of the correct type to add to" " Operations.") @property def _operations(self): op = list() if hasattr(self, '_integrator'): op.append(self._integrator) return op @property def _sys_init(self): if self.simulation is None or self.simulation.state is None: return False else: return True def schedule(self): if not self._sys_init: raise RuntimeError("System not initialized yet") sim = self.simulation for op in self._operations: new_objs = op.attach(sim) if isinstance(op, hoomd.integrate._integrator): sim._cpp_sys.setIntegrator(op._cpp_obj) if new_objs is not None: self._compute.extend(new_objs) self._scheduled = True def _store_reader(self, reader): # TODO pass @property def scheduled(self): return self._scheduled @property def integrator(self): try: return self._integrator except AttributeError: return None
import hoomd.integrate class Operations: def __init__(self, simulation=None): self.simulation = simulation self._compute = list() self._auto_schedule = False self._scheduled = False def add(self, op): if isinstance(op, hoomd.integrate._integrator): self._integrator = op else: raise ValueError("Operation is not of the correct type to add to" " Operations.") @property def _operations(self): op = list() if hasattr(self, '_integrator'): op.append(self._integrator) return op @property def _sys_init(self): if self.simulation is None or self.simulation.state is None: return False else: return True def schedule(self): if not self._sys_init: raise RuntimeError("System not initialized yet") sim = self.simulation for op in self._operations: new_objs = op.attach(sim) if isinstance(op, hoomd.integrate._integrator): sim._cpp_sys.setIntegrator(op._cpp_obj) if new_objs is not None: self._compute.extend(new_objs) self._scheduled = True def _store_reader(self, reader): # TODO pass @property def scheduled(self): return self._scheduled
Fix for ignoring BPMN validation - JBPM-4000
package org.jbpm.migration; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; /** Convenience class for making the error handling within the parsing and validation processes a little more verbose. */ abstract class ErrorCollector<T extends Exception> { private final List<T> warningList = new ArrayList<T>(); private final List<T> errorList = new ArrayList<T>(); private final List<T> fatalList = new ArrayList<T>(); public void warning(final T ex) { warningList.add(ex); } public void error(final T ex) { errorList.add(ex); } public void fatalError(final T ex) { fatalList.add(ex); } public boolean didErrorOccur() { // checking warnings might be too restrictive return !warningList.isEmpty() || !errorList.isEmpty() ||!fatalList.isEmpty(); } public List<T> getWarningList() { return warningList; } public List<T> getErrorList() { return errorList; } public List<T> getFatalList() { return fatalList; } public void logErrors(final Logger logger) { for (final T ex : warningList) { logger.warn("==>", ex); } for (final T ex : errorList) { logger.error("==>", ex); } for (final T ex : fatalList) { logger.fatal("==>", ex); } } }
package org.jbpm.migration; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; /** Convenience class for making the error handling within the parsing and validation processes a little more verbose. */ abstract class ErrorCollector<T extends Exception> { private final List<T> warningList = new ArrayList<T>(); private final List<T> errorList = new ArrayList<T>(); private final List<T> fatalList = new ArrayList<T>(); public void warning(final T ex) { warningList.add(ex); } public void error(final T ex) { errorList.add(ex); } public void fatalError(final T ex) { fatalList.add(ex); } public boolean didErrorOccur() { return !warningList.isEmpty() && !errorList.isEmpty() && !fatalList.isEmpty(); } public List<T> getWarningList() { return warningList; } public List<T> getErrorList() { return errorList; } public List<T> getFatalList() { return fatalList; } public void logErrors(final Logger logger) { for (final T ex : warningList) { logger.warn("==>", ex); } for (final T ex : errorList) { logger.error("==>", ex); } for (final T ex : fatalList) { logger.fatal("==>", ex); } } }
Add is_done=True to get_all_expired filter.
from django.db import models from celery.registry import tasks from datetime import datetime, timedelta __all__ = ["TaskManager", "PeriodicTaskManager"] class TaskManager(models.Manager): def get_task(self, task_id): task, created = self.get_or_create(task_id=task_id) return task def is_done(self, task_id): return self.get_task(task_id).is_done def get_all_expired(self): return self.filter(date_done__lt=datetime.now() - timedelta(days=5), is_done=True) def delete_expired(self): self.get_all_expired().delete() def mark_as_done(self, task_id): task, created = self.get_or_create(task_id=task_id, defaults={ "is_done": True}) if not created: task.is_done = True task.save() class PeriodicTaskManager(models.Manager): def get_waiting_tasks(self): periodic_tasks = tasks.get_all_periodic() waiting = [] for task_name, task in periodic_tasks.items(): task_meta, created = self.get_or_create(name=task_name) # task_run.every must be a timedelta object. run_at = task_meta.last_run_at + task.run_every if datetime.now() > run_at: waiting.append(task_meta) return waiting
from django.db import models from celery.registry import tasks from datetime import datetime, timedelta __all__ = ["TaskManager", "PeriodicTaskManager"] class TaskManager(models.Manager): def get_task(self, task_id): task, created = self.get_or_create(task_id=task_id) return task def is_done(self, task_id): return self.get_task(task_id).is_done def get_all_expired(self): return self.filter(date_done__lt=datetime.now() - timedelta(days=5)) def delete_expired(self): self.get_all_expired().delete() def mark_as_done(self, task_id): task, created = self.get_or_create(task_id=task_id, defaults={ "is_done": True}) if not created: task.is_done = True task.save() class PeriodicTaskManager(models.Manager): def get_waiting_tasks(self): periodic_tasks = tasks.get_all_periodic() waiting = [] for task_name, task in periodic_tasks.items(): task_meta, created = self.get_or_create(name=task_name) # task_run.every must be a timedelta object. run_at = task_meta.last_run_at + task.run_every if datetime.now() > run_at: waiting.append(task_meta) return waiting
Fix open in new window URL
import React from 'react' import { NavLink } from 'react-router-dom' import EditTools from './EditTools' import PreviewTools from './PreviewTools' import styles from './Toolbar.styl' export default ({ params, project, layout, theme, onLayoutChanged, onThemeChanged }) => { const { username, owner, project: projectName, mode } = params const linkBase = ['', username, owner, projectName].join('/').replace('//', '/') return ( <div className={styles.container}> <nav role="navigation" className={styles.nav}> <NavLink to={linkBase + '/edit'} className={styles.navLink} activeClassName={styles.active}> <img src="/public/img/toolbar/edit.png" /> Edit </NavLink> <NavLink to={linkBase + '/preview'} className={styles.navLink} activeClassName={styles.active} > <img src="/public/img/toolbar/preview.png" /> Preview </NavLink> </nav> {mode === 'edit' && <EditTools />} {mode === 'preview' && <PreviewTools href={`/preview/${owner || username}/${projectName}`} layout={layout} theme={theme} onLayoutChanged={onLayoutChanged} onThemeChanged={onThemeChanged} />} </div> ) }
import React from 'react' import { NavLink } from 'react-router-dom' import EditTools from './EditTools' import PreviewTools from './PreviewTools' import styles from './Toolbar.styl' export default ({ params, project, layout, theme, onLayoutChanged, onThemeChanged }) => { const { username, owner, project: projectName, mode } = params const linkBase = ['', username, owner, projectName].join('/').replace('//', '/') return ( <div className={styles.container}> <nav role="navigation" className={styles.nav}> <NavLink to={linkBase + '/edit'} className={styles.navLink} activeClassName={styles.active}> <img src="/public/img/toolbar/edit.png" /> Edit </NavLink> <NavLink to={linkBase + '/preview'} className={styles.navLink} activeClassName={styles.active} > <img src="/public/img/toolbar/preview.png" /> Preview </NavLink> </nav> {mode === 'edit' && <EditTools />} {mode === 'preview' && <PreviewTools href={`/preview/${username}/${projectName}`} layout={layout} theme={theme} onLayoutChanged={onLayoutChanged} onThemeChanged={onThemeChanged} />} </div> ) }
Move blanket into bower's devDependencies.
/* globals module */ var EOL = require('os').EOL; module.exports = { normalizeEntityName: function() {}, afterInstall: function() { return this.addBowerPackageToProject('blanket', '~1.1.5', {saveDev: true}) // Modify tests/index.html to include the blanket options after the application .then(function() { return this.insertIntoFile( 'tests/index.html', ' <script src="assets/blanket-options.js"></script>', { after: '<script src="assets/' + this.project.config().modulePrefix + '.js"></script>' + EOL } ); }.bind(this)) // Modify tests/index.html to include the blanket loader after the blanket options .then(function() { return this.insertIntoFile( 'tests/index.html', ' <script src="assets/blanket-loader.js"></script>', { after: '<script src="assets/blanket-options.js"></script>' + EOL } ); }.bind(this)) // modify the blanket reporter styles so it's not covered by the ember testing container .then(function() { return this.insertIntoFile( 'tests/index.html', ' <style>#blanket-main { position: relative; z-index: 99999; }</style>', { after: '<link rel="stylesheet" href="assets/test-support.css">' + EOL } ); }.bind(this)); } };
/* globals module */ var EOL = require('os').EOL; module.exports = { normalizeEntityName: function() {}, afterInstall: function() { return this.addBowerPackageToProject('blanket', '~1.1.5') // Modify tests/index.html to include the blanket options after the application .then(function() { return this.insertIntoFile( 'tests/index.html', ' <script src="assets/blanket-options.js"></script>', { after: '<script src="assets/' + this.project.config().modulePrefix + '.js"></script>' + EOL } ); }.bind(this)) // Modify tests/index.html to include the blanket loader after the blanket options .then(function() { return this.insertIntoFile( 'tests/index.html', ' <script src="assets/blanket-loader.js"></script>', { after: '<script src="assets/blanket-options.js"></script>' + EOL } ); }.bind(this)) // modify the blanket reporter styles so it's not covered by the ember testing container .then(function() { return this.insertIntoFile( 'tests/index.html', ' <style>#blanket-main { position: relative; z-index: 99999; }</style>', { after: '<link rel="stylesheet" href="assets/test-support.css">' + EOL } ); }.bind(this)); } };
Use 'number' input to use the width: 80px CSS rule Auditors: eater, cbhl
(function(Perseus) { var InputInteger = Perseus.Widget.extend({ initialize: function() { this.$input = $("<input type='number'>"); }, render: function() { this.$el.empty(); this.$el.append(this.$input); return $.when(this); }, focus: function() { this.$input.focus(); }, toJSON: function() { return { value: this.$input.val() }; }, set: function(options) { this.$input.val(options.value); }, simpleValidate: function(rubric) { return InputInteger.validate(this.toJSON(), rubric); } }); _.extend(InputInteger, { validate: function(state, rubric) { // For now, rubric is just like {value: "17"} // TODO(alpert): Smarter checking if (state.value === "") { return { type: "invalid", message: null }; } else if (state.value === rubric.value) { return { type: "points", earned: 1, total: 1, message: null }; } else { return { type: "points", earned: 0, total: 1, message: "Consider writing in the right answer, silly." }; } } }); Perseus.Widgets.register("input-integer", InputInteger); })(Perseus);
(function(Perseus) { var InputInteger = Perseus.Widget.extend({ initialize: function() { this.$input = $("<input>"); }, render: function() { this.$el.empty(); this.$el.append(this.$input); return $.when(this); }, focus: function() { this.$input.focus(); }, toJSON: function() { return { value: this.$input.val() }; }, set: function(options) { this.$input.val(options.value); }, simpleValidate: function(rubric) { return InputInteger.validate(this.toJSON(), rubric); } }); _.extend(InputInteger, { validate: function(state, rubric) { // For now, rubric is just like {value: "17"} // TODO(alpert): Smarter checking if (state.value === "") { return { type: "invalid", message: null }; } else if (state.value === rubric.value) { return { type: "points", earned: 1, total: 1, message: null }; } else { return { type: "points", earned: 0, total: 1, message: "Consider writing in the right answer, silly." }; } } }); Perseus.Widgets.register("input-integer", InputInteger); })(Perseus);
Fix bug in service insights
/* eslint-disable class-methods-use-this */ /* * Copyright 2019 Expedia Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import store from '../../../serviceInsights/stores/serviceInsightsStore'; export class ServiceInsightsTabStateStore { search = null; isAvailable = false; hasValidSearch = false; init(search) { this.search = search; // is Service Insights enabled in the appliation config? const enableServiceInsights = (window.haystackUiConfig && window.haystackUiConfig.enableServiceInsights) || false; // If user is directly accessing URL, show this feature const isAccessingServiceInsights = this.search.tabId === 'serviceInsights'; // has required minimal search terms this.hasValidSearch = !!(search.serviceName || search.traceId); this.isAvailable = enableServiceInsights && (this.hasValidSearch || isAccessingServiceInsights); } fetch() { // Copy `hasValidSearch` so serviceInsight reactJS component can leverage store.hasValidSearch = this.hasValidSearch; return store; } } export default new ServiceInsightsTabStateStore();
/* eslint-disable class-methods-use-this */ /* * Copyright 2019 Expedia Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import store from '../../../serviceInsights/stores/serviceInsightsStore'; export class ServiceInsightsTabStateStore { search = null; isAvailable = false; hasValidSearch = false; init(search) { this.search = search; // is Service Insights enabled in the appliation config? const enableServiceInsights = (window.haystackUiConfig && window.haystackUiConfig.enableServiceInsights) || false; // If user is directly accessing URL, show this feature const isAccessingServiceInsights = this.search.tabId === 'serviceInsights'; // has required minimal search terms this.hasValidSearch = !!(search.serviceName || search.traceId); this.isAvailable = enableServiceInsights && (this.hasValidSearch || isAccessingServiceInsights); } fetch() { return store; } } export default new ServiceInsightsTabStateStore();
Add 'cache' & ''thumbs' file system management
<?php namespace Bolt\Provider; use Bolt\Filesystem\Adapter\Local; use Bolt\Filesystem\Filesystem; use Bolt\Filesystem\Manager; use Bolt\Filesystem\Plugin; use Silex\Application; use Silex\ServiceProviderInterface; /** * @author Carson Full <[email protected]> */ class FilesystemServiceProvider implements ServiceProviderInterface { public function register(Application $app) { $app['filesystem'] = $app->share( function ($app) { $manager = new Manager( [ 'root' => new Filesystem(new Local($app['resources']->getPath('root'))), 'app' => new Filesystem(new Local($app['resources']->getPath('app'))), 'default' => new Filesystem(new Local($app['resources']->getPath('files'))), 'files' => new Filesystem(new Local($app['resources']->getPath('files'))), 'config' => new Filesystem(new Local($app['resources']->getPath('config'))), 'theme' => new Filesystem(new Local($app['resources']->getPath('themebase'))), 'extensions' => new Filesystem(new Local($app['resources']->getPath('extensions'))), 'cache' => new Filesystem(new Local($app['resources']->getPath('cache'))), 'thumbs' => new Filesystem(new Local($app['resources']->getPath('web/thumbs'))), ], [ new Plugin\PublicUrl($app), new Plugin\Authorized($app), new Plugin\ThumbnailUrl($app), ] ); return $manager; } ); } public function boot(Application $app) { } }
<?php namespace Bolt\Provider; use Bolt\Filesystem\Adapter\Local; use Bolt\Filesystem\Filesystem; use Bolt\Filesystem\Manager; use Bolt\Filesystem\Plugin; use Silex\Application; use Silex\ServiceProviderInterface; /** * @author Carson Full <[email protected]> */ class FilesystemServiceProvider implements ServiceProviderInterface { public function register(Application $app) { $app['filesystem'] = $app->share( function ($app) { $manager = new Manager( [ 'root' => new Filesystem(new Local($app['resources']->getPath('root'))), 'app' => new Filesystem(new Local($app['resources']->getPath('app'))), 'default' => new Filesystem(new Local($app['resources']->getPath('files'))), 'files' => new Filesystem(new Local($app['resources']->getPath('files'))), 'config' => new Filesystem(new Local($app['resources']->getPath('config'))), 'theme' => new Filesystem(new Local($app['resources']->getPath('themebase'))), 'extensions' => new Filesystem(new Local($app['resources']->getPath('extensions'))), ], [ new Plugin\PublicUrl($app), new Plugin\Authorized($app), new Plugin\ThumbnailUrl($app), ] ); return $manager; } ); } public function boot(Application $app) { } }
Change test name to be more descriptive Also better conforms to the naming conventions for other tests in this module.
from web_test_base import * class TestIATIStandard(WebTestBase): """ TODO: Add tests to assert that: - the number of activities and publishers roughly matches those displayed on the Registry - a key string appears on the homepage """ requests_to_load = { 'IATI Standard Homepage - no www': { 'url': 'http://iatistandard.org' }, 'IATI Standard Homepage - with www': { 'url': 'http://www.iatistandard.org' } } def test_contains_links(self, loaded_request): """ Test that each page contains links to the defined URLs. """ result = utility.get_links_from_page(loaded_request) # Selection of header links assert "/en/news/" in result assert "/en/about/" in result assert "/en/iati-standard/" in result assert "/en/using-data/" in result # Selection of footer links assert "/en/contact/" in result assert "/en/terms-and-conditions/" in result assert "/en/privacy-policy/" in result def test_contains_newsletter_signup_form(self, loaded_request): """ Tests to confirm that there is always a form to subscribe to the newsletter within the footer. """ xpath = '//*[@id="mc-embedded-subscribe-form"]' result = utility.locate_xpath_result(loaded_request, xpath) assert len(result) == 1
from web_test_base import * class TestIATIStandard(WebTestBase): """ TODO: Add tests to assert that: - the number of activities and publishers roughly matches those displayed on the Registry - a key string appears on the homepage """ requests_to_load = { 'IATI Standard Homepage - no www': { 'url': 'http://iatistandard.org' }, 'IATI Standard Homepage - with www': { 'url': 'http://www.iatistandard.org' } } def test_contains_links(self, loaded_request): """ Test that each page contains links to the defined URLs. """ result = utility.get_links_from_page(loaded_request) # Selection of header links assert "/en/news/" in result assert "/en/about/" in result assert "/en/iati-standard/" in result assert "/en/using-data/" in result # Selection of footer links assert "/en/contact/" in result assert "/en/terms-and-conditions/" in result assert "/en/privacy-policy/" in result def test_newsletter_signup_form(self, loaded_request): """ Tests to confirm that there is always a form to subscribe to the newsletter within the footer. """ xpath = '//*[@id="mc-embedded-subscribe-form"]' result = utility.locate_xpath_result(loaded_request, xpath) assert len(result) == 1
Update websocket url to use dynamic host rather than fixed
import { browserHistory } from 'react-router'; const instanceID = Math.floor(Math.random() * 10000) + 1; export const eventTypes = { shownNotification: "SHOWN_NOTIFICATION", shownWarning: "SHOWN_WARNING", changedRoute: "CHANGED_ROUTE", appInitialised: "APP_INITIALISED", requestSent: "REQUEST_SENT", requestReceived: "REQUEST_RECEIVED" } browserHistory.listen(location => { log.add(eventTypes.changedRoute, {...location}) }); const socket = new WebSocket(`ws://${window.location.host}/florence/websocket`); socket.onopen = () => { log.add(eventTypes.appInitialised); } export default class log { static add(eventType, payload) { const event = { type: eventType, location: location.href, instanceID, clientTimestamp: new Date().toISOString(), payload: payload || null } // console.log(event); // Socket isn't open yet but something has been loged, wait until it is open to send it if (socket.readyState === 0) { socket.onopen = () => { socket.send(`event:${JSON.stringify(event)}`); } return; } socket.send(`event:${JSON.stringify(event)}`); // Send across with a top level type because other data, not just events, will be sent too e.g. /* { type: "LOG_EVENT", payload: { event } } */ } }
import { browserHistory } from 'react-router'; const instanceID = Math.floor(Math.random() * 10000) + 1; export const eventTypes = { shownNotification: "SHOWN_NOTIFICATION", shownWarning: "SHOWN_WARNING", changedRoute: "CHANGED_ROUTE", appInitialised: "APP_INITIALISED", requestSent: "REQUEST_SENT", requestReceived: "REQUEST_RECEIVED" } browserHistory.listen(location => { log.add(eventTypes.changedRoute, {...location}) }); const socket = new WebSocket('ws://localhost:8081/florence/websocket'); socket.onopen = () => { log.add(eventTypes.appInitialised); } export default class log { static add(eventType, payload) { const event = { type: eventType, location: location.href, instanceID, clientTimestamp: new Date().toISOString(), payload: payload || null } // console.log(event); // Socket isn't open yet but something has been loged, wait until it is open to send it if (socket.readyState === 0) { socket.onopen = () => { socket.send(`event:${JSON.stringify(event)}`); } return; } socket.send(`event:${JSON.stringify(event)}`); // Send across with a top level type because other data, not just events, will be sent too e.g. /* { type: "LOG_EVENT", payload: { event } } */ } }
Fix exception caused by calling validateLayoutProperty without passing a style
'use strict'; var validate = require('./validate'); var ValidationError = require('../error/validation_error'); module.exports = function validateLayoutProperty(options) { var key = options.key; var style = options.style; var styleSpec = options.styleSpec; var value = options.value; var propertyKey = options.objectKey; var layerSpec = styleSpec['layout_' + options.layerType]; if (options.valueSpec || layerSpec[propertyKey]) { var errors = []; if (options.layerType === 'symbol') { if (propertyKey === 'icon-image' && style && !style.sprite) { errors.push(new ValidationError(key, value, 'use of "icon-image" requires a style "sprite" property')); } else if (propertyKey === 'text-field' && style && !style.glyphs) { errors.push(new ValidationError(key, value, 'use of "text-field" requires a style "glyphs" property')); } } return errors.concat(validate({ key: options.key, value: value, valueSpec: options.valueSpec || layerSpec[propertyKey], style: style, styleSpec: styleSpec })); } else { return [new ValidationError(key, value, 'unknown property "%s"', propertyKey)]; } };
'use strict'; var validate = require('./validate'); var ValidationError = require('../error/validation_error'); module.exports = function validateLayoutProperty(options) { var key = options.key; var style = options.style; var styleSpec = options.styleSpec; var value = options.value; var propertyKey = options.objectKey; var layerSpec = styleSpec['layout_' + options.layerType]; if (options.valueSpec || layerSpec[propertyKey]) { var errors = []; if (options.layerType === 'symbol') { if (propertyKey === 'icon-image' && !style.sprite) { errors.push(new ValidationError(key, value, 'use of "icon-image" requires a style "sprite" property')); } else if (propertyKey === 'text-field' && !style.glyphs) { errors.push(new ValidationError(key, value, 'use of "text-field" requires a style "glyphs" property')); } } return errors.concat(validate({ key: options.key, value: value, valueSpec: options.valueSpec || layerSpec[propertyKey], style: style, styleSpec: styleSpec })); } else { return [new ValidationError(key, value, 'unknown property "%s"', propertyKey)]; } };
Raise version for release due to font licensing issues resolution
from setuptools import setup, find_packages import sys, os here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.rst')).read() except IOError: README = '' version = "0.0.2" setup(name='backlash', version=version, description="Standalone WebOb port of the Werkzeug Debugger with Python3 support meant to replace WebError in future TurboGears2", long_description=README, classifiers=['Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.2', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware', 'Topic :: Internet :: WWW/HTTP :: WSGI'], keywords='wsgi', author='Alessandro Molina', author_email='[email protected]', url='https://github.com/TurboGears/backlash', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ "WebOb" # -*- Extra requirements: -*- ], entry_points=""" # -*- Entry points: -*- """, )
from setuptools import setup, find_packages import sys, os here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.rst')).read() except IOError: README = '' version = "0.0.1a2" setup(name='backlash', version=version, description="Standalone WebOb port of the Werkzeug Debugger with Python3 support meant to replace WebError in future TurboGears2", long_description=README, classifiers=['Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware', 'Topic :: Internet :: WWW/HTTP :: WSGI'], keywords='wsgi', author='Alessandro Molina', author_email='[email protected]', url='https://github.com/TurboGears/backlash', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ "WebOb" # -*- Extra requirements: -*- ], entry_points=""" # -*- Entry points: -*- """, )
Add stubs for handling requests to server.
import json import threading import socket import SocketServer from orderbook import asks, bids class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): try: while True: data = self.request.recv(1024) if data: response = handle_data(data) cur_thread = threading.current_thread() response = "\n{}: {}".format(cur_thread.name, data) self.request.sendall(response) except socket.error: # Surpress errno 13 Broken Pipe pass class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass def create_server(host="localhost", port=0): server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler) server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() return server def handle_data(data): data = json.loads(data) if data['type'] == 'ask': handle_ask(data) elif data['type'] == 'bid': handle_bid(data) elif data['type'] == 'greeting': handle_greeting(data) def handle_ask(ask): asks.append(ask) def handle_bid(bid): bids.append(bid) def handle_greeting(greeting): pass
import json import threading import socket import SocketServer from orderbook import match_bid, offers, asks messages = [] class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): try: while True: data = self.request.recv(1024) if data: data = json.loads(data) messages.append(data) print "MESSAGES: {}".format(messages) if data['type'] == 'bid': response = handle_bid(data) elif data['type'] == 'ask': response = handle_asks(data) cur_thread = threading.current_thread() response = "\n{}: {}".format(cur_thread.name, data) self.request.sendall(response) except socket.error: # Surpress errno 13 Broken Pipe pass class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass def create_server(host="localhost", port=0): server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler) server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() return server def handle_ask(ask): asks.append(ask) def handle_bid(bid): bids.append(bid)
Fix KoboS3Storage deprecated bucket and acl arguments
# coding: utf-8 from django.conf import settings as django_settings from django.core.files.storage import FileSystemStorage from storages.backends.s3boto3 import S3Boto3Storage def get_kobocat_storage(): """ Return an instance of a storage object depending on the setting `KOBOCAT_DEFAULT_FILE_STORAGE` value """ if ( django_settings.KOBOCAT_DEFAULT_FILE_STORAGE == 'storages.backends.s3boto3.S3Boto3Storage' ): return KobocatS3Boto3Storage() else: return KobocatFileSystemStorage() class KobocatFileSystemStorage(FileSystemStorage): def __init__( self, location=None, base_url=None, file_permissions_mode=None, directory_permissions_mode=None, ): location = ( django_settings.KOBOCAT_MEDIA_PATH if not location else location ) super().__init__( location=location, base_url=base_url, file_permissions_mode=file_permissions_mode, directory_permissions_mode=directory_permissions_mode, ) class KobocatS3Boto3Storage(S3Boto3Storage): def __init__(self, acl=None, bucket=None, **settings): if acl: settings['default_acl'] = acl settings['bucket_name'] = django_settings.KOBOCAT_AWS_STORAGE_BUCKET_NAME super().__init__(**settings)
# coding: utf-8 from django.conf import settings as django_settings from django.core.files.storage import FileSystemStorage from storages.backends.s3boto3 import S3Boto3Storage def get_kobocat_storage(): """ Return an instance of a storage object depending on the setting `KOBOCAT_DEFAULT_FILE_STORAGE` value """ if ( django_settings.KOBOCAT_DEFAULT_FILE_STORAGE == 'storages.backends.s3boto3.S3Boto3Storage' ): return KobocatS3Boto3Storage() else: return KobocatFileSystemStorage() class KobocatFileSystemStorage(FileSystemStorage): def __init__( self, location=None, base_url=None, file_permissions_mode=None, directory_permissions_mode=None, ): location = ( django_settings.KOBOCAT_MEDIA_PATH if not location else location ) super().__init__( location=location, base_url=base_url, file_permissions_mode=file_permissions_mode, directory_permissions_mode=directory_permissions_mode, ) class KobocatS3Boto3Storage(S3Boto3Storage): def __init__(self, acl=None, bucket=None, **settings): bucket = django_settings.KOBOCAT_AWS_STORAGE_BUCKET_NAME super().__init__(acl=None, bucket=bucket, **settings)
Fix wrong varname in provider class.
<?php namespace Rych\Silex\Provider; use Silex\Application; use Silex\ServiceProviderInterface; use Rych\Plates\Extension\RoutingExtension; use Rych\Plates\Extension\SecurityExtension; class PlatesServiceProvider implements ServiceProviderInterface { public function register(Application $app) { $app['plates.path'] = null; $app['plates.folders'] = array (); $app['plates.engine'] = $app->share(function ($app) { $engine = new \Plates\Engine($app['plates.path']); foreach ($app['plates.folders'] as $name => $path) { $engine->addFolder($name, $path); } if (isset($app['url_generator'])) { $engine->loadExtension(new RoutingExtension($app['url_generator'])); } if (isset($app['security'])) { $engine->loadExtension(new SecurityExtension($app['security'])); } return $engine; }); $app['plates'] = $app->share(function ($app) { $plates = new \Plates\Template($app['plates.engine']); $plates->app = $app; return $plates; }); } public function boot(Application $app) { } }
<?php namespace Rych\Silex\Provider; use Silex\Application; use Silex\ServiceProviderInterface; use Rych\Plates\Extension\RoutingExtension; use Rych\Plates\Extension\SecurityExtension; class PlatesServiceProvider implements ServiceProviderInterface { public function register(Application $app) { $app['plates.path'] = null; $app['plates.folders'] = array (); $app['plates.engine'] = $app->share(function ($app) { $engine = new \Plates\Engine($app['plates.path']); foreach ($app['plates.folders'] as $name => $path) { $engine->addFolder($name, $path); } if (isset($app['url_generator'])) { $plates->loadExtension(new RoutingExtension($app['url_generator'])); } if (isset($app['security'])) { $plates->loadExtension(new SecurityExtension($app['security'])); } return $engine; }); $app['plates'] = $app->share(function ($app) { $plates = new \Plates\Template($app['plates.engine']); $plates->app = $app; return $plates; }); } public function boot(Application $app) { } }
BAP-11412: Implement enable/disable operations - CS Fix
<?php namespace Oro\Bundle\TranslationBundle\Helper; use Oro\Bundle\ConfigBundle\Config\ConfigManager; use Oro\Bundle\LocaleBundle\DependencyInjection\Configuration; use Oro\Bundle\TranslationBundle\Entity\Language; class LanguageHelper { /** @var ConfigManager */ protected $configManager; /** * @param ConfigManager $configManager */ public function __construct(ConfigManager $configManager) { $this->configManager = $configManager; } /** * @param Language $language */ public function updateSystemConfiguration(Language $language) { $languages = $this->configManager->get($this->getConfigurationName(), true); if ($language->isEnabled()) { if (!in_array($language->getCode(), $languages, true)) { $languages[] = $language->getCode(); } } else { if (false !== ($index = array_search($language->getCode(), $languages, true))) { unset($languages[$index]); } } $this->configManager->set($this->getConfigurationName(), $languages); $this->configManager->flush(); } /** * @return string */ protected function getConfigurationName() { return Configuration::getConfigKeyByName(Configuration::LANGUAGES); } }
<?php namespace Oro\Bundle\TranslationBundle\Helper; use Oro\Bundle\ConfigBundle\Config\ConfigManager; use Oro\Bundle\LocaleBundle\DependencyInjection\Configuration; use Oro\Bundle\TranslationBundle\Entity\Language; class LanguageHelper { /** @var ConfigManager */ protected $configManager; /** * @param ConfigManager $configManager */ public function __construct(ConfigManager $configManager) { $this->configManager = $configManager; } /** * @param Language $language */ public function updateSystemConfiguration(Language $language) { $languages = $this->configManager->get($this->getConfigurationName(), true); if ($language->isEnabled()) { if(!in_array($language->getCode(), $languages, true)){ $languages[] = $language->getCode(); } } else { if (false !== ($index = array_search($language->getCode(), $languages, true))) { unset($languages[$index]); } } $this->configManager->set($this->getConfigurationName(), $languages); $this->configManager->flush(); } /** * @return string */ protected function getConfigurationName() { return Configuration::getConfigKeyByName(Configuration::LANGUAGES); } }
Change mapping to avoid warning
from django.conf import settings from django.contrib.auth.models import User from django.db import models class UserMetadata(models.Model): user = models.OneToOneField( User, related_name="metadata", on_delete=models.CASCADE ) tos_version = models.IntegerField(default=0) tos_accepted = models.DateTimeField(default=None, null=True,) privacy_policy_version = models.IntegerField(default=0) privacy_policy_accepted = models.DateTimeField(default=None, null=True,) colorscheme = models.CharField(default="dark-yellow-green.theme", max_length=255,) @property def tos_up_to_date(self): return self.tos_version == settings.TOS_VERSION @property def privacy_policy_up_to_date(self): return self.privacy_policy_version == settings.PRIVACY_POLICY_VERSION @classmethod def get_for_user(cls, user): meta, created = UserMetadata.objects.get_or_create(user=user) return meta def save(self, *args, **kwargs): super().save(*args, **kwargs) from . import TaskStore if self.tos_up_to_date and self.privacy_policy_up_to_date: store = TaskStore.get_for_user(self.user) store.taskd_account.resume() def __str__(self): return self.user.username class Meta: app_label = "taskmanager"
from django.conf import settings from django.contrib.auth.models import User from django.db import models class UserMetadata(models.Model): user = models.ForeignKey( User, related_name="metadata", unique=True, on_delete=models.CASCADE ) tos_version = models.IntegerField(default=0) tos_accepted = models.DateTimeField(default=None, null=True,) privacy_policy_version = models.IntegerField(default=0) privacy_policy_accepted = models.DateTimeField(default=None, null=True,) colorscheme = models.CharField(default="dark-yellow-green.theme", max_length=255,) @property def tos_up_to_date(self): return self.tos_version == settings.TOS_VERSION @property def privacy_policy_up_to_date(self): return self.privacy_policy_version == settings.PRIVACY_POLICY_VERSION @classmethod def get_for_user(cls, user): meta, created = UserMetadata.objects.get_or_create(user=user) return meta def save(self, *args, **kwargs): super().save(*args, **kwargs) from . import TaskStore if self.tos_up_to_date and self.privacy_policy_up_to_date: store = TaskStore.get_for_user(self.user) store.taskd_account.resume() def __str__(self): return self.user.username class Meta: app_label = "taskmanager"
Validate that score doesn't already exist for a round when submitting the form
from flask.ext.wtf import Form from wtforms import SelectField, BooleanField, IntegerField, TextField, \ validators from models import RobotScore class TeamForm(Form): number = IntegerField("Number", [validators.Required(), validators.NumberRange(min=1, max=99999)]) name = TextField("Name", [validators.Required(), validators.Length(min=1, max=50)]) affiliation = TextField("Affiliation", [validators.Length(min=1, max=200)]) city = TextField("City", [validators.Length(min=1, max=50)]) state = TextField("State", [validators.Length(min=2, max=2)]) # TODO add validation class ScoreForm(Form): team_id = SelectField(u'Team', coerce=int) round_number = SelectField(u'Round', choices=[(1, '1'), (2, '2'), (3, '3')], coerce=int) tree_branch_is_closer = BooleanField(u'Is tree branch closer to mat than power lines', default=False) tree_branch_is_intact = BooleanField(u'Is tree branch model intact', default=False) cargo_plane_location = SelectField(u'Cargo plane location', choices=[('0', 'None'), ('1', 'Yellow only'), ('2', 'Light blue')]) def __init__(self, *args, **kwargs): Form.__init__(self, *args, **kwargs) self.score = None def validate(self): rv = Form.validate(self) if not rv: return False score = RobotScore.query.filter_by(round_number=self.round_number.data).first() if score is not None: self.round_number.errors.append("Score already exists for this round") return False self.score = score return True
from flask.ext.wtf import Form from wtforms import SelectField, BooleanField, IntegerField, TextField, \ validators class TeamForm(Form): number = IntegerField("Number", [validators.Required(), validators.NumberRange(min=1, max=99999)]) name = TextField("Name", [validators.Required(), validators.Length(min=1, max=50)]) affiliation = TextField("Affiliation", [validators.Length(min=1, max=200)]) city = TextField("City", [validators.Length(min=1, max=50)]) state = TextField("State", [validators.Length(min=2, max=2)]) # TODO add validation class ScoreForm(Form): team_id = SelectField(u'Team', coerce=int) round_number = SelectField(u'Round', choices=[(1, '1'), (2, '2'), (3, '3')], coerce=int) tree_branch_is_closer = BooleanField(u'Is tree branch closer to mat than power lines', default=False) tree_branch_is_intact = BooleanField(u'Is tree branch model intact', default=False) cargo_plane_location = SelectField(u'Cargo plane location', choices=[('0', 'None'), ('1', 'Yellow only'), ('2', 'Light blue')])
Add conf file to installation script
#! /usr/bin/env python3 # -*- coding: utf-8 -*- from setuptools import setup from dlstats import version import os setup(name='dlstats', version=version.version, description='A python module that provides an interface between statistics providers and pandas.', author='Widukind team', author_email='[email protected]', url='https://github.com/Widukind', package_dir={'dlstats': 'dlstats', 'dlstats.fetchers': 'dlstats/fetchers'}, packages=['dlstats', 'dlstats.fetchers'], data_files=[('/usr/local/bin',['dlstats/dlstats_server.py']), ('/etc/systemd/system',['os_specific/dlstats.service']), ('/etc/',['config/dlstats'])], install_requires=[ 'requests>=2.4.3', 'pymongo>=2.7.2', 'pandas>=0.12', 'docopt>=0.6.0', 'voluptuous>=0.8', 'xlrd>=0.8', 'configobj>=5.0', 'elasticsearch>=1.0.0,<2.0.0' ] ) with open('/etc/systemd/system/dlstats.service'): os.chmod('/etc/systemd/system/dlstats.service', 0o755) with open('/usr/local/bin/dlstats_server.py'): os.chmod('/usr/local/bin/dlstats_server.py', 0o755) with open('/etc/dlstats'): os.chmod('/etc/dlstats', 0o755)
#! /usr/bin/env python3 # -*- coding: utf-8 -*- from setuptools import setup from dlstats import version import os setup(name='dlstats', version=version.version, description='A python module that provides an interface between statistics providers and pandas.', author='Widukind team', author_email='[email protected]', url='https://github.com/Widukind', package_dir={'dlstats': 'dlstats', 'dlstats.fetchers': 'dlstats/fetchers'}, packages=['dlstats', 'dlstats.fetchers'], data_files=[('/usr/local/bin',['dlstats/dlstats_server.py']), ('/etc/systemd/system',['os_specific/dlstats.service'])], install_requires=[ 'requests>=2.4.3', 'pymongo>=2.7.2', 'pandas>=0.12', 'docopt>=0.6.0', 'voluptuous>=0.8', 'xlrd>=0.8', 'configobj>=5.0', 'elasticsearch>=1.0.0,<2.0.0' ] ) with open('/etc/systemd/system/dlstats.service'): os.chmod('/etc/systemd/system/dlstats.service', 0o755) with open('/usr/local/bin/dlstats_server.py'): os.chmod('/usr/local/bin/dlstats_server.py', 0o755)
Add a note on env configuration
module.exports = function(scope, argv) { return { install: function (done) { scope.applyConfig({ create: { Image: "niallo/strider:latest", Env: { /* https://github.com/Strider-CD/strider#configuring */ } }, start: { PublishAllPorts: !!argv.publish } }, function (err) { if (err) throw err; scope.inspectContainer(function (err, data) { if (err) throw err; else { var ip = data.NetworkSettings.IPAddress; done(null, JSON.stringify({ ip_address: ip, ports: data.NetworkSettings.Ports, app: { url: "http://"+ip+":3000", email: "[email protected]", password: "dontlook" }, ssh: { port: 22, username: "strider", password: "str!der", notes: "Root access is prohibited by default through ssh. To get root access login as strider and su to root." } }, null, 2)) } }); }); } } }
module.exports = function(scope, argv) { return { install: function (done) { scope.applyConfig({ create: { Image: "niallo/strider:latest", }, start: { PublishAllPorts: !!argv.publish } }, function (err) { if (err) throw err; scope.inspectContainer(function (err, data) { if (err) throw err; else { var ip = data.NetworkSettings.IPAddress; done(null, JSON.stringify({ ip_address: ip, ports: data.NetworkSettings.Ports, app: { url: "http://"+ip+":3000", email: "[email protected]", password: "dontlook" }, ssh: { port: 22, username: "strider", password: "str!der", notes: "Root access is prohibited by default through ssh. To get root access login as strider and su to root." } }, null, 2)) } }); }); } } }
Fix for incoming PM matches always being null.
package mnm.mods.tabbychat.filters; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import mnm.mods.tabbychat.TabbyChat; import mnm.mods.tabbychat.api.Channel; import mnm.mods.tabbychat.api.TabbyAPI; import mnm.mods.tabbychat.api.filters.Filter; import mnm.mods.tabbychat.api.filters.FilterEvent; import mnm.mods.tabbychat.util.MessagePatterns; /** * Base class for filters that just need to set the */ public class MessageFilter extends TabFilter { @Override public Pattern getPattern() { try { // Quickly update the pattern MessagePatterns messege = TabbyChat.getInstance().serverSettings.messegePattern.getValue(); String pattern = String.format("(?:%s|%s)", messege.getOutgoing(), messege.getIncoming()); setPattern(pattern); } catch (PatternSyntaxException e) { TabbyChat.getLogger().error(e); } return super.getPattern(); } @Override public void action(Filter filter, FilterEvent event) { // 0 = whole message, 1 = outgoing recipient, 2 = incoming recipient String player = event.matcher.group(1); // For when it's an incoming message. if (player == null) { player = event.matcher.group(2); } Channel dest = TabbyAPI.getAPI().getChat().getChannel(player); if (dest.getPrefix().isEmpty()) { dest.setPrefix("/msg " + player); } event.channels.add(dest); } }
package mnm.mods.tabbychat.filters; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import mnm.mods.tabbychat.TabbyChat; import mnm.mods.tabbychat.api.Channel; import mnm.mods.tabbychat.api.TabbyAPI; import mnm.mods.tabbychat.api.filters.Filter; import mnm.mods.tabbychat.api.filters.FilterEvent; import mnm.mods.tabbychat.util.MessagePatterns; /** * Base class for filters that just need to set the */ public class MessageFilter extends TabFilter { @Override public Pattern getPattern() { try { // Quickly update the pattern MessagePatterns messege = TabbyChat.getInstance().serverSettings.messegePattern.getValue(); String pattern = String.format("(?:%s|%s)", messege.getOutgoing(), messege.getIncoming()); setPattern(pattern); } catch (PatternSyntaxException e) { TabbyChat.getLogger().error(e); } return super.getPattern(); } @Override public void action(Filter filter, FilterEvent event) { String player = event.matcher.group(1); Channel dest = TabbyAPI.getAPI().getChat().getChannel(player); if (dest.getPrefix().isEmpty()) { dest.setPrefix("/msg " + player); } event.channels.add(dest); } }
Make 'Router created' message translatable Change-Id: If0e246157a72fd1cabdbbde77e0c057d9d611eaa
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012, Nachi Ueno, NTT MCL, Inc. # All rights reserved. """ Views for managing Quantum Routers. """ import logging from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from horizon import forms from horizon import exceptions from horizon import messages from openstack_dashboard import api LOG = logging.getLogger(__name__) class CreateForm(forms.SelfHandlingForm): name = forms.CharField(max_length="255", label=_("Router Name")) failure_url = 'horizon:project:routers:index' def __init__(self, request, *args, **kwargs): super(CreateForm, self).__init__(request, *args, **kwargs) def handle(self, request, data): try: router = api.quantum.router_create(request, name=data['name']) message = _('Router %s was successfully created.') % data['name'] messages.success(request, message) return router except: msg = _('Failed to create router "%s".') % data['name'] LOG.info(msg) redirect = reverse(self.failure_url) exceptions.handle(request, msg, redirect=redirect) return False
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012, Nachi Ueno, NTT MCL, Inc. # All rights reserved. """ Views for managing Quantum Routers. """ import logging from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from horizon import forms from horizon import exceptions from horizon import messages from openstack_dashboard import api LOG = logging.getLogger(__name__) class CreateForm(forms.SelfHandlingForm): name = forms.CharField(max_length="255", label=_("Router Name")) failure_url = 'horizon:project:routers:index' def __init__(self, request, *args, **kwargs): super(CreateForm, self).__init__(request, *args, **kwargs) def handle(self, request, data): try: router = api.quantum.router_create(request, name=data['name']) message = 'Router created "%s"' % data['name'] messages.success(request, message) return router except: msg = _('Failed to create router "%s".') % data['name'] LOG.info(msg) redirect = reverse(self.failure_url) exceptions.handle(request, msg, redirect=redirect) return False