text,positive,negative Increase log verbosity on exception,"from bs4 import BeautifulSoup import logging from jetcomcrawl import browser import jetcomcrawl.libs.queue class Worker(object): def __init__(self): self.queue_categories = jetcomcrawl.libs.queue.Queue('queue_categories') self.queue_items = jetcomcrawl.libs.queue.Queue('queue_items') def work(self): '''Keeps running indefinitely, retrieving jobs from sqs''' while True: # TODO: Handle no items left in queue data = self.queue_categories.retrieve() cid = data['cid'] page = data['page'] logging.info('Finding products for category {}, page {}'.format(cid, page)) html = browser.get('https://jet.com/search/results?category={}&page={}'.format(cid, page)) try: soup = BeautifulSoup(html.text, 'html.parser') results = [] for item in soup.find('div', {'class': 'products'}).findAll('div', {'class': 'product mobile'}): url = item.a['href'] uid = url.split('/')[-1] results.append({'uid': uid, 'url': url}) except: logging.info(html.text) raise logging.info('{} products found for category {}, page {}, inserting into sqs'.format(len(results), cid, page)) self.queue_items.insert_bulk(results) self.queue_categories.remove_processed() ","from bs4 import BeautifulSoup import logging from jetcomcrawl import browser import jetcomcrawl.libs.queue class Worker(object): def __init__(self): self.queue_categories = jetcomcrawl.libs.queue.Queue('queue_categories') self.queue_items = jetcomcrawl.libs.queue.Queue('queue_items') def work(self): '''Keeps running indefinitely, retrieving jobs from sqs''' while True: # TODO: Handle no items left in queue data = self.queue_categories.retrieve() cid = data['cid'] page = data['page'] logging.info('Finding products for category {}, page {}'.format(cid, page)) html = browser.get('https://jet.com/search/results?category={}&page={}'.format(cid, page)) soup = BeautifulSoup(html.text, 'html.parser') results = [] for item in soup.find('div', {'class': 'products'}).findAll('div', {'class': 'product mobile'}): url = item.a['href'] uid = url.split('/')[-1] results.append({'uid': uid, 'url': url}) logging.info('{} products found for category {}, page {}, inserting into sqs'.format(len(results), cid, page)) self.queue_items.insert_bulk(results) self.queue_categories.remove_processed() " Update format type in View Index User,"<?php use yii\helpers\Html; use yii\grid\GridView; /* @var $this yii\web\View */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'Users'; $this->params['breadcrumbs'][] = $this->title; ?> <div class=""user-index""> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a('Create User', ['create'], ['class' => 'btn btn-success']) ?> </p> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'columns' => [ 'user_id', 'user_name', 'user_email:email', 'user_birthday', ['class' => 'yii\grid\ActionColumn'], array( 'format' => 'html', 'attribute' => 'user_name', 'value'=>function($data){ return $data->user_name; } ) ] ]); ?> </div> ","<?php use yii\helpers\Html; use yii\grid\GridView; /* @var $this yii\web\View */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'Users'; $this->params['breadcrumbs'][] = $this->title; ?> <div class=""user-index""> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a('Create User', ['create'], ['class' => 'btn btn-success']) ?> </p> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'columns' => [ 'user_id', 'user_name', 'user_email:email', 'user_birthday', ['class' => 'yii\grid\ActionColumn'], array( 'format' => 'image', 'attribute' => 'user_name', 'value'=>function($data){ return $data->user_name; } ) ] ]); ?> </div> " Test the replacement method too,"<?php namespace tests\Http\Discovery; use Http\Discovery\Exception\NotFoundException; use Http\Discovery\Psr17FactoryDiscovery; use PHPUnit\Framework\TestCase; use Psr\Http\Message\RequestFactoryInterface; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ServerRequestFactoryInterface; use Psr\Http\Message\StreamFactoryInterface; use Psr\Http\Message\UploadedFileFactoryInterface; use Psr\Http\Message\UriFactoryInterface; class Psr17FactoryDiscoveryTest extends TestCase { /** * @dataProvider getFactories */ public function testFind($method, $interface) { $callable = [Psr17FactoryDiscovery::class, $method]; $client = $callable(); $this->assertInstanceOf($interface, $client); } /** * @group NothingInstalled * @dataProvider getFactories */ public function testNotFound($method) { $callable = [Psr17FactoryDiscovery::class, $method]; $this->expectException(NotFoundException::class); $callable(); } public function getFactories() { yield ['findRequestFactory', RequestFactoryInterface::class]; yield ['findResponseFactory', ResponseFactoryInterface::class]; yield ['findServerRequestFactory', ServerRequestFactoryInterface::class]; yield ['findStreamFactory', StreamFactoryInterface::class]; yield ['findUploadedFileFactory', UploadedFileFactoryInterface::class]; yield ['findUriFactory', UriFactoryInterface::class]; yield ['findUrlFactory', UriFactoryInterface::class]; } } ","<?php namespace tests\Http\Discovery; use Http\Discovery\Exception\NotFoundException; use Http\Discovery\Psr17FactoryDiscovery; use PHPUnit\Framework\TestCase; use Psr\Http\Message\RequestFactoryInterface; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ServerRequestFactoryInterface; use Psr\Http\Message\StreamFactoryInterface; use Psr\Http\Message\UploadedFileFactoryInterface; use Psr\Http\Message\UriFactoryInterface; class Psr17FactoryDiscoveryTest extends TestCase { /** * @dataProvider getFactories */ public function testFind($method, $interface) { $callable = [Psr17FactoryDiscovery::class, $method]; $client = $callable(); $this->assertInstanceOf($interface, $client); } /** * @group NothingInstalled * @dataProvider getFactories */ public function testNotFound($method) { $callable = [Psr17FactoryDiscovery::class, $method]; $this->expectException(NotFoundException::class); $callable(); } public function getFactories() { yield ['findRequestFactory', RequestFactoryInterface::class]; yield ['findResponseFactory', ResponseFactoryInterface::class]; yield ['findServerRequestFactory', ServerRequestFactoryInterface::class]; yield ['findStreamFactory', StreamFactoryInterface::class]; yield ['findUploadedFileFactory', UploadedFileFactoryInterface::class]; yield ['findUrlFactory', UriFactoryInterface::class]; } } " Change to react from react-with-addons,"var path = require(""path""); module.exports = { cache: true, entry: ""./js/main.js"", devtool: ""#source-map"", output: { path: path.resolve(""./build""), filename: ""bundle.js"", sourceMapFilename: ""[file].map"", publicPath: ""/build/"", stats: { colors: true }, }, module: { noParse: [/node_modules\/react/, /node_modules\/jquery/, /bower_components\/MathJax/, /bower_components\/KAS/, /node_modules\/underscore/], loaders: [ { //tell webpack to use jsx-loader for all *.jsx files test: /\.js$/, loader: ""regenerator-loader"" }, { //tell webpack to use jsx-loader for all *.jsx files test: /\.js$/, loader: ""jsx-loader?insertPragma=React.DOM&harmony&stripTypes"" } ], }, resolve: { alias: { ""react"": path.resolve(""node_modules/react/dist/react.js""), ""underscore"": path.resolve(""node_modules/underscore/underscore-min.js""), ""jquery"": path.resolve(""node_modules/jquery/dist/jquery.min.js""), ""katex"": path.resolve(""bower_components/katex/build/katex.min.js""), }, extensions: ["""", "".js"", "".jsx""] } } ","var path = require(""path""); module.exports = { cache: true, entry: ""./js/main.js"", devtool: ""#source-map"", output: { path: path.resolve(""./build""), filename: ""bundle.js"", sourceMapFilename: ""[file].map"", publicPath: ""/build/"", stats: { colors: true }, }, module: { noParse: [/node_modules\/react/, /node_modules\/jquery/, /bower_components\/MathJax/, /bower_components\/KAS/, /node_modules\/underscore/], loaders: [ { //tell webpack to use jsx-loader for all *.jsx files test: /\.js$/, loader: ""regenerator-loader"" }, { //tell webpack to use jsx-loader for all *.jsx files test: /\.js$/, loader: ""jsx-loader?insertPragma=React.DOM&harmony&stripTypes"" } ], }, resolve: { alias: { ""react"": path.resolve(""node_modules/react/dist/react-with-addons.js""), ""underscore"": path.resolve(""node_modules/underscore/underscore-min.js""), ""jquery"": path.resolve(""node_modules/jquery/dist/jquery.min.js""), ""katex"": path.resolve(""bower_components/katex/build/katex.min.js""), }, extensions: ["""", "".js"", "".jsx""] } } " Change config path to public path,"<?php /* * This file is part of the Laravel Facebook Account-Kit package. * * (c) Ibraheem Adeniyi <ibonly01@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Ibonly\FacebookAccountKit; use Illuminate\Support\ServiceProvider; class FacebookAccountKitServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Publishes all the config file this package needs to function */ public function boot() { $config = realpath(__DIR__ . '/../resources/config/facebookAccountKit.php'); $js = realpath(__DIR__ . '/../resources/config/accountkit.js'); $this->publishes([ $config => config_path('AccountKit.php') ], 'config'); $this->publishes([ $js => public_path('public/js/accountkit.js') ], 'public'); } /** * Register the application services. */ public function register() { $this->app->singleton('AccountKit', function() { return new FacebookAccountKit; }); } /** * Get the services provided by the provider * @return array */ public function provides() { return ['AccountKit']; } } ","<?php /* * This file is part of the Laravel Facebook Account-Kit package. * * (c) Ibraheem Adeniyi <ibonly01@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Ibonly\FacebookAccountKit; use Illuminate\Support\ServiceProvider; class FacebookAccountKitServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Publishes all the config file this package needs to function */ public function boot() { $config = realpath(__DIR__ . '/../resources/config/facebookAccountKit.php'); $js = realpath(__DIR__ . '/../resources/config/accountkit.js'); $this->publishes([ $config => config_path('AccountKit.php') ], 'config'); $this->publishes([ $js => config_path('accountkit.js') ], 'public/js/'); } /** * Register the application services. */ public function register() { $this->app->singleton('AccountKit', function() { return new FacebookAccountKit; }); } /** * Get the services provided by the provider * @return array */ public function provides() { return ['AccountKit']; } } " Allow to set link target (_self to change current window's location),"require(['gitbook'], function(gitbook) { gitbook.events.bind('start', function(e, config) { var opts = config.toolbar; if (!opts || !opts.buttons) return; var buttons = opts.buttons.slice(0); buttons.reverse(); buttons.forEach(function(button) { gitbook.toolbar.createButton({ icon: button.icon || ""fa fa-external-link"", label: button.label || ""Link"", position: 'right', onClick: function(e) { e.preventDefault(); var mapping = { ""{{title}}"": encodeURIComponent(document.title), ""{{url}}"": encodeURIComponent(location.href) }; var re = RegExp(Object.keys(mapping).join(""|""), ""g""); var url = button.url.replace(re, function(matched) { return mapping[matched]; }); if (button.target == ""_self"") { window.location = url; } else { window.open(url, button.target || ""_blank""); } } }); }); }); }); ","require(['gitbook'], function(gitbook) { gitbook.events.bind('start', function(e, config) { var opts = config.toolbar; if (!opts || !opts.buttons) return; var buttons = opts.buttons.slice(0); buttons.reverse(); buttons.forEach(function(button) { gitbook.toolbar.createButton({ icon: button.icon || ""fa fa-external-link"", label: button.label || ""Link"", position: 'right', onClick: function(e) { e.preventDefault(); var mapping = { ""{{title}}"": encodeURIComponent(document.title), ""{{url}}"": encodeURIComponent(location.href) }; var re = RegExp(Object.keys(mapping).join(""|""), ""g""); window.open(button.url.replace(re, function(matched) { return mapping[matched]; })); } }); }); }); }); " Add optional importUrl to Shapefile signature,"L.Shapefile =L.GeoJSON.extend({ initialize: function (file, options, importUrl) { if(typeof cw !== 'undefined'){ if (typeof importUrl === 'undefined') { importUrl = 'shp.js'; } this.worker = cw(function(data,cb){ importScripts(importUrl); shp(data).then(cb); }); } L.GeoJSON.prototype.initialize.call(this,{features:[]},options); this.addFileData(file); }, addFileData:function(file){ var self = this; self.fire('data:loading'); if(typeof file !== 'string' && !('byteLength' in file)){ var data = self.addData(file); self.fire('data:loaded'); return data; } if(self.worker){ self.worker.data(cw.makeUrl(file)).then(function(data){ self.addData(data); self.fire('data:loaded'); self.worker.close(); }); }else{ shp(file).then(function(data){ self.addData(data); self.fire('data:loaded'); }); } return this; } }); L.shapefile= function(a,b,c){ return new L.Shapefile(a,b,c); } ","L.Shapefile =L.GeoJSON.extend({ initialize: function (file, options) { if(typeof cw !== 'undefined'){ this.worker = cw(function(data,cb){ importScripts('shp.js'); shp(data).then(cb); }); } L.GeoJSON.prototype.initialize.call(this,{features:[]},options); this.addFileData(file); }, addFileData:function(file){ var self = this; self.fire('data:loading'); if(typeof file !== 'string' && !('byteLength' in file)){ var data = self.addData(file); self.fire('data:loaded'); return data; } if(self.worker){ self.worker.data(cw.makeUrl(file)).then(function(data){ self.addData(data); self.fire('data:loaded'); self.worker.close(); }); }else{ shp(file).then(function(data){ self.addData(data); self.fire('data:loaded'); }); } return this; } }); L.shapefile= function(a,b){ return new L.Shapefile(a,b); } " "Correct a straggling CLI format string after ref selector changes Summary: Ref T13589. This is missing a ""%s"" conversion. Test Plan: Will view a commit with a diff. Maniphest Tasks: T13589 Differential Revision: https://secure.phabricator.com/D21512","<?php final class DiffusionGitRawDiffQuery extends DiffusionRawDiffQuery { protected function newQueryFuture() { $drequest = $this->getRequest(); $repository = $drequest->getRepository(); $commit = $this->getAnchorCommit(); $options = array( '-M', '-C', '--no-ext-diff', '--no-color', '--src-prefix=a/', '--dst-prefix=b/', '-U'.(int)$this->getLinesOfContext(), ); $against = $this->getAgainstCommit(); if ($against === null) { // Check if this is the root commit by seeing if it has parents, since // `git diff X^ X` does not work if ""X"" is the initial commit. list($parents) = $repository->execxLocalCommand( 'log -n 1 %s %s --', '--format=%P', gitsprintf('%s', $commit)); if (strlen(trim($parents))) { $against = $commit.'^'; } else { $against = ArcanistGitAPI::GIT_MAGIC_ROOT_COMMIT; } } $path = $drequest->getPath(); if (!strlen($path)) { $path = '.'; } return $repository->getLocalCommandFuture( 'diff %Ls %s %s -- %s', $options, gitsprintf('%s', $against), gitsprintf('%s', $commit), $path); } } ","<?php final class DiffusionGitRawDiffQuery extends DiffusionRawDiffQuery { protected function newQueryFuture() { $drequest = $this->getRequest(); $repository = $drequest->getRepository(); $commit = $this->getAnchorCommit(); $options = array( '-M', '-C', '--no-ext-diff', '--no-color', '--src-prefix=a/', '--dst-prefix=b/', '-U'.(int)$this->getLinesOfContext(), ); $against = $this->getAgainstCommit(); if ($against === null) { // Check if this is the root commit by seeing if it has parents, since // `git diff X^ X` does not work if ""X"" is the initial commit. list($parents) = $repository->execxLocalCommand( 'log -n 1 %s --', '--format=%P', gitsprintf('%s', $commit)); if (strlen(trim($parents))) { $against = $commit.'^'; } else { $against = ArcanistGitAPI::GIT_MAGIC_ROOT_COMMIT; } } $path = $drequest->getPath(); if (!strlen($path)) { $path = '.'; } return $repository->getLocalCommandFuture( 'diff %Ls %s %s -- %s', $options, gitsprintf('%s', $against), gitsprintf('%s', $commit), $path); } } " Print stacktrace when security exception thrown,"package org.example; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import java.security.AccessControlContext; import java.security.AccessController; import java.security.AllPermission; import java.security.CodeSource; import java.security.Permissions; import java.security.Policy; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.security.ProtectionDomain; import java.security.cert.Certificate; public class Sandbox { public void runNashornScriptInSandbox(String source) throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName(""nashorn""); Object result = sandbox(() -> { return engine.eval(source); }); System.out.println(String.format(""result is '%s'"", result)); } private Object sandbox(PrivilegedExceptionAction<Object> action) throws PrivilegedActionException { Policy.setPolicy(new java.security.Policy() { @Override public java.security.PermissionCollection getPermissions(ProtectionDomain domain) { Permissions permissions = new Permissions(); permissions.add(new AllPermission()); return permissions; } }); System.setSecurityManager(new SecurityManager()); ProtectionDomain domain = new ProtectionDomain(new CodeSource(null, (Certificate[]) null), new Permissions()); final AccessControlContext context = new AccessControlContext(new ProtectionDomain[]{domain}); try { return AccessController.doPrivileged(action, context); } finally { try { System.setSecurityManager(null); } catch (SecurityException e) { e.printStackTrace(); throw e; } } } } ","package org.example; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import java.security.AccessControlContext; import java.security.AccessController; import java.security.AllPermission; import java.security.CodeSource; import java.security.Permissions; import java.security.Policy; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.security.ProtectionDomain; import java.security.cert.Certificate; public class Sandbox { public void runNashornScriptInSandbox(String source) throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName(""nashorn""); Object result = sandbox(() -> { return engine.eval(source); }); System.out.println(String.format(""result is '%s'"", result)); } private Object sandbox(PrivilegedExceptionAction<Object> action) throws PrivilegedActionException { Policy.setPolicy(new java.security.Policy() { @Override public java.security.PermissionCollection getPermissions(ProtectionDomain domain) { Permissions permissions = new Permissions(); permissions.add(new AllPermission()); return permissions; } }); System.setSecurityManager(new SecurityManager()); ProtectionDomain domain = new ProtectionDomain(new CodeSource(null, (Certificate[]) null), new Permissions()); final AccessControlContext context = new AccessControlContext(new ProtectionDomain[]{domain}); try { return AccessController.doPrivileged(action, context); } finally { System.setSecurityManager(null); } } } " Allow linking to own page when link is in content,"<?php class Kwc_Basic_LinkTag_Intern_Form extends Kwc_Abstract_Form { public function __construct($name, $class, $id = null) { parent::__construct($name, $class, $id); $this->add(new Kwf_Form_Field_PageSelect('target', trlKwf('Target'))) ->setControllerUrl(Kwc_Admin::getInstance($class)->getControllerUrl('Pages')) ->setWidth(233) ->setAllowBlank(false); $this->add(new Kwf_Form_Field_Select('anchor', trlKwf('Anchor'))) ->setValues(Kwc_Admin::getInstance($class)->getControllerUrl('Anchors') . '/json-data') ->setShowNoSelection(true); } public function prepareSave($parentRow, $postData) { if ($parentRow) { // Limit 1 weil alle komponenten die hier zurück kommen, dieselbe url // haben und es wird ja überprüft ob zu sich selbst gelinkt wird $data = Kwf_Component_Data_Root::getInstance()->getComponentByDbId( $parentRow->component_id, array('limit' => 1, 'ignoreVisible' => true) ); if (isset($postData[$this->fields['target']->getFieldName()]) && $data && $data->isPage && $data->getPage() && $data->getPage()->dbId == $postData[$this->fields['target']->getFieldName()] ) { throw new Kwf_ClientException(trlKwf('Link cannot link to itself')); } } parent::prepareSave($parentRow, $postData); } } ","<?php class Kwc_Basic_LinkTag_Intern_Form extends Kwc_Abstract_Form { public function __construct($name, $class, $id = null) { parent::__construct($name, $class, $id); $this->add(new Kwf_Form_Field_PageSelect('target', trlKwf('Target'))) ->setControllerUrl(Kwc_Admin::getInstance($class)->getControllerUrl('Pages')) ->setWidth(233) ->setAllowBlank(false); $this->add(new Kwf_Form_Field_Select('anchor', trlKwf('Anchor'))) ->setValues(Kwc_Admin::getInstance($class)->getControllerUrl('Anchors') . '/json-data') ->setShowNoSelection(true); } public function prepareSave($parentRow, $postData) { if ($parentRow) { // Limit 1 weil alle komponenten die hier zurück kommen, dieselbe url // haben und es wird ja überprüft ob zu sich selbst gelinkt wird $data = Kwf_Component_Data_Root::getInstance()->getComponentByDbId( $parentRow->component_id, array('limit' => 1) ); if (isset($postData[$this->fields['target']->getFieldName()]) && $data && $data->getPage() && $data->getPage()->dbId == $postData[$this->fields['target']->getFieldName()]) { throw new Kwf_ClientException(trlKwf('Link cannot link to itself')); } } parent::prepareSave($parentRow, $postData); } } " Remove innerHTML from the code,"window.addEventListener('click', function(event) { var target = event.target; if (target.id == 'forcarProxy' || target.id == 'listaSites') { self.port.emit('daNovoProxy', target.toString()); } if (target.id == 'verSites') { self.port.emit('openTabSites', target.toString()); } if (target.id == 'mensagem') { self.port.emit('openTabLink', target.toString()); } }, false); self.on('message', function(data){ if(data.hasOwnProperty('host') && data.hasOwnProperty('port')) { document.getElementById(""proxyaddr"").firstChild.nodeValue = data.host + ':' + data.port; } if(data.hasOwnProperty('version')) { document.getElementById(""ahoy-version"").firstChild.nodeValue = data.version; } }) self.port.on('currentURL', function( currentURL, blockedSites ) { var cleanURL = currentURL.replace(/.*?:\/\/www.|.*?:\/\//g,"""").replace(/\//g,""""); if ( blockedSites.indexOf(cleanURL) != -1 ) { document.getElementById('status-inactivo').style.display = ""none""; document.getElementById('status-activo').style.display = """"; } else { document.getElementById('status-inactivo').style.display = """"; document.getElementById('status-activo').style.display = ""none""; } });","window.addEventListener('click', function(event) { var target = event.target; if (target.id == 'forcarProxy' || target.id == 'listaSites') { self.port.emit('daNovoProxy', target.toString()); } if (target.id == 'verSites') { self.port.emit('openTabSites', target.toString()); } if (target.id == 'mensagem') { self.port.emit('openTabLink', target.toString()); } }, false); self.on('message', function(data){ if(data.hasOwnProperty('host') && data.hasOwnProperty('port')) { document.getElementById(""proxyaddr"").innerHTML = data.host + ':' + data.port; } if(data.hasOwnProperty('version')) { document.getElementById(""ahoy-version"").innerHTML = data.version; } }) self.port.on('currentURL', function( currentURL, blockedSites ) { var cleanURL = currentURL.replace(/.*?:\/\/www.|.*?:\/\//g,"""").replace(/\//g,""""); if ( blockedSites.indexOf(cleanURL) != -1 ) { document.getElementById('status-inactivo').style.display = ""none""; document.getElementById('status-activo').style.display = """"; } else { document.getElementById('status-inactivo').style.display = """"; document.getElementById('status-activo').style.display = ""none""; } });" Call function with full path and leading backslash,"<?php namespace Politix\PolitikportalBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; // use Politix\PolitikportalBundle\Model; class SourcesController extends Controller { public function indexAction($name) { $out['items'] = $this->getSource('tagesschau'); $out['name'] = $name; return $this->render('PolitikportalBundle:Default:items.html.twig', $out); } function getSourceAction($source) { $out['source'] = $source; $sql = 'SELECT * FROM rss_items WHERE source LIKE ""' . $source . '"" ORDER BY pubDate DESC LIMIT 0,10'; $out['items'] = $this->getDB($sql); return $this->render('PolitikportalBundle:Default:items.html.twig', $out); } function getSourcesAction() { require ('/var/www/vhosts/politikportal.eu/subdomains/new/httpdocs/politix/src/Politix/PolitikportalBundle/Model/SourceModel.php'); $db = new \Politix\PolitikportalBundle\Model\SourceModel(); $out['sources'] = $db->getSources; return $this->render('PolitikportalBundle:Default:sources.html.twig', $out); } function getDB($sql) { $conn = $this->container->get('database_connection'); return $conn->query($sql); } } ","<?php namespace Politix\PolitikportalBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Politix\PolitikportalBundle\Model; class SourcesController extends Controller { public function indexAction($name) { $out['items'] = $this->getSource('tagesschau'); $out['name'] = $name; return $this->render('PolitikportalBundle:Default:items.html.twig', $out); } function getSourceAction($source) { $out['source'] = $source; $sql = 'SELECT * FROM rss_items WHERE source LIKE ""' . $source . '"" ORDER BY pubDate DESC LIMIT 0,10'; $out['items'] = $this->getDB($sql); return $this->render('PolitikportalBundle:Default:items.html.twig', $out); } function getSourcesAction() { require ('/var/www/vhosts/politikportal.eu/subdomains/new/httpdocs/politix/src/Politix/PolitikportalBundle/Model/SourceModel.php'); $db = new Politix\PolitikportalBundle\Model\SourceModel(); $out['sources'] = $db->getSources; return $this->render('PolitikportalBundle:Default:sources.html.twig', $out); } function getDB($sql) { $conn = $this->container->get('database_connection'); return $conn->query($sql); } } " "Increase the required version of requests. Versions of the requests library prior to 2.20.0 have a known security vulnerability (CVE-2018-18074).","import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.version_info <= (2, 4): error = 'Requires Python Version 2.5 or above... exiting.' print >> sys.stderr, error sys.exit(1) requirements = [ 'requests>=2.20.0,<3.0', ] setup(name='googlemaps', version='3.0.2', description='Python client library for Google Maps API Web Services', scripts=[], url='https://github.com/googlemaps/google-maps-services-python', packages=['googlemaps'], license='Apache 2.0', platforms='Posix; MacOS X; Windows', setup_requires=requirements, install_requires=requirements, test_suite='googlemaps.test', classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Internet', ] ) ","import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.version_info <= (2, 4): error = 'Requires Python Version 2.5 or above... exiting.' print >> sys.stderr, error sys.exit(1) requirements = [ 'requests>=2.11.1,<3.0', ] setup(name='googlemaps', version='3.0.2', description='Python client library for Google Maps API Web Services', scripts=[], url='https://github.com/googlemaps/google-maps-services-python', packages=['googlemaps'], license='Apache 2.0', platforms='Posix; MacOS X; Windows', setup_requires=requirements, install_requires=requirements, test_suite='googlemaps.test', classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Internet', ] ) " Remove deprecated notes from PropTypes helper,"(function() { window.shared || (window.shared = {}); // Allow a prop to be null, if the prop type explicitly allows this. // Then fall back to another validator if a value is passed. var nullable = function(validator) { return function(props, propName, componentName) { if (props[propName] === null) return null; return validator(props, propName, componentName); }; }; var PropTypes = window.shared.PropTypes = { nullable: nullable, // UI actions, stepping stone to Flux actions: React.PropTypes.shape({ onColumnClicked: React.PropTypes.func.isRequired, onClickSaveNotes: React.PropTypes.func.isRequired, onClickSaveService: React.PropTypes.func.isRequired, onClickDiscontinueService: React.PropTypes.func.isRequired }), requests: React.PropTypes.shape({ saveNotes: nullable(React.PropTypes.string).isRequired }), api: React.PropTypes.shape({ saveNotes: React.PropTypes.func.isRequired }), // The feed of all notes and data entered in Student Insights for // a student. feed: React.PropTypes.shape({ event_notes: React.PropTypes.array.isRequired, services: React.PropTypes.shape({ active: React.PropTypes.array.isRequired, discontinued: React.PropTypes.array.isRequired }), deprecated: React.PropTypes.shape({ interventions: React.PropTypes.array.isRequired }) }) }; })(); ","(function() { window.shared || (window.shared = {}); // Allow a prop to be null, if the prop type explicitly allows this. // Then fall back to another validator if a value is passed. var nullable = function(validator) { return function(props, propName, componentName) { if (props[propName] === null) return null; return validator(props, propName, componentName); }; }; var PropTypes = window.shared.PropTypes = { nullable: nullable, // UI actions, stepping stone to Flux actions: React.PropTypes.shape({ onColumnClicked: React.PropTypes.func.isRequired, onClickSaveNotes: React.PropTypes.func.isRequired, onClickSaveService: React.PropTypes.func.isRequired, onClickDiscontinueService: React.PropTypes.func.isRequired }), requests: React.PropTypes.shape({ saveNotes: nullable(React.PropTypes.string).isRequired }), api: React.PropTypes.shape({ saveNotes: React.PropTypes.func.isRequired }), // The feed of all notes and data entered in Student Insights for // a student. feed: React.PropTypes.shape({ event_notes: React.PropTypes.array.isRequired, services: React.PropTypes.shape({ active: React.PropTypes.array.isRequired, discontinued: React.PropTypes.array.isRequired }), deprecated: React.PropTypes.shape({ notes: React.PropTypes.array.isRequired, interventions: React.PropTypes.array.isRequired }) }) }; })();" "Revert ""support for preact 7"" This reverts commit 3d72ee045e2d89ba591f02d08c292afcdd393989.","import splat from ""./splat""; import formatDeclarations from ""./formatDeclarations""; export default function createRenderer(backend) { let globalSpec = 0; const specs = Object.create(null); return function render(rules) { let currentSpec = -1; const className = splat(rules).map((rule) => { let ruleSpec = -1; const ruleSpecs = specs[rule.id] || (specs[rule.id] = []); for (let i = 0; i < ruleSpecs.length; i++) { if (ruleSpecs[i] > currentSpec) { ruleSpec = ruleSpecs[i]; break; } } if (ruleSpec < 0) { formatDeclarations(`.${rule.class}__${globalSpec}`, rule.declarations, backend); ruleSpecs.push(globalSpec); ruleSpec = globalSpec; globalSpec += 1; } currentSpec = ruleSpec; return `${rule.class}__${ruleSpec}`; }).join("" ""); return { toString () { return className; }, _rules: rules, }; }; } ","import splat from ""./splat""; import formatDeclarations from ""./formatDeclarations""; export default function createRenderer(backend) { let globalSpec = 0; const specs = Object.create(null); return function render(rules) { let currentSpec = -1; const classNames = splat(rules).map((rule) => { let ruleSpec = -1; const ruleSpecs = specs[rule.id] || (specs[rule.id] = []); for (let i = 0; i < ruleSpecs.length; i++) { if (ruleSpecs[i] > currentSpec) { ruleSpec = ruleSpecs[i]; break; } } if (ruleSpec < 0) { formatDeclarations(`.${rule.class}__${globalSpec}`, rule.declarations, backend); ruleSpecs.push(globalSpec); ruleSpec = globalSpec; globalSpec += 1; } currentSpec = ruleSpec; return `${rule.class}__${ruleSpec}`; }); const renderer = {}; Object.defineProperties(renderer, { toString: { value() { return classNames.join("" ""); }, }, _rules: { value: rules }, }); classNames.forEach((className) => renderer[className] = true); return renderer; }; } " Change a way to add constants into twig globals,"<?php /* * 이 컨트롤러를 상속받아 구현하는 컨트롤러는 Twig 템플릿 엔진을 기본으로 로드함 */ class MY_Controller extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library('twig'); $this->load->helper('url'); // Twig 관련 글로벌 설정은 이곳 또는 application/libraries/Twig.php 에 작성 $this->twig->addGlobal('session', $_SESSION); // 사용자 정의 상수를 Twig global로 등록 $defined_constants = get_defined_constants(true)['user']; foreach ($defined_constants as $constant => $value) { $this->twig->addGlobal($constant, $value); } if ($this->accountlib->is_login() === false) { redirect('/account/login'); } elseif ($this->accountlib->is_auth() === false) { redirect('/account/not_authenticated'); } } } if (!class_exists('API_Controller')) { require_once APPPATH . 'core/API_Controller.php'; } ","<?php /* * 이 컨트롤러를 상속받아 구현하는 컨트롤러는 Twig 템플릿 엔진을 기본으로 로드함 */ class MY_Controller extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library('twig'); $this->load->helper('url'); // Twig 관련 글로벌 설정은 이곳 또는 application/libraries/Twig.php 에 작성 $this->twig->addGlobal('session', $_SESSION); // 아래 상수들은 constants.php와 동기화 필요 $this->twig->addGlobal('USER_TYPE_ARTIST', USER_TYPE_ARTIST); $this->twig->addGlobal('USER_TYPE_PLACE_OWNER', USER_TYPE_PLACE_OWNER); $this->twig->addGlobal('TYPE_ARTWORKS', TYPE_ARTWORKS); $this->twig->addGlobal('TYPE_PLACES', TYPE_PLACES); if ($this->accountlib->is_login() === false) { redirect('/account/login'); } elseif ($this->accountlib->is_auth() === false) { redirect('/account/not_authenticated'); } } } if (!class_exists('API_Controller')) { require_once APPPATH . 'core/API_Controller.php'; } " Add support for testing URL redirects.,"<?php /* * Bear CMS addon for Bear Framework * https://bearcms.com/ * Copyright (c) Amplilabs Ltd. * Free to use under the MIT license. */ namespace BearCMS\Internal; use BearFramework\App; /** * @internal * @codeCoverageIgnore */ class Settings { /** * * @param App $app * @param \BearCMS $bearCMS * @param App\Request $request * @return App\Response|null */ public static function handleRedirectRequest(App $app, \BearCMS $bearCMS, App\Request $request): ?App\Response { $settings = $bearCMS->data->settings->get(); $path = strtolower($request->path->get()); $testURL = $request->query->getValue('test-url-redirect'); if ($testURL !== null && $bearCMS->currentUser->exists()) { $location = $testURL; } else { $redirects = $settings->redirects; $location = null; if (isset($redirects[$path])) { $location = $redirects[$path]; } elseif (isset($redirects[$path . '/'])) { $location = $redirects[$path . '/']; } } if ($location !== null) { if (strpos($location, '://') === false) { $location = '/' . ltrim($location, '/'); $location = $app->urls->get($location); } return new App\Response\PermanentRedirect($location); } return null; } } ","<?php /* * Bear CMS addon for Bear Framework * https://bearcms.com/ * Copyright (c) Amplilabs Ltd. * Free to use under the MIT license. */ namespace BearCMS\Internal; use BearFramework\App; /** * @internal * @codeCoverageIgnore */ class Settings { /** * * @param App $app * @param \BearCMS $bearCMS * @param App\Request $request * @return App\Response|null */ public static function handleRedirectRequest(App $app, \BearCMS $bearCMS, App\Request $request): ?App\Response { $settings = $bearCMS->data->settings->get(); $path = strtolower($request->path->get()); $redirects = $settings->redirects; $location = null; if (isset($redirects[$path])) { $location = $redirects[$path]; } elseif (isset($redirects[$path . '/'])) { $location = $redirects[$path . '/']; } if ($location !== null) { $location = '/' . ltrim($location, '/'); if (strpos($location, '://') === false) { $location = $app->urls->get($location); } return new App\Response\PermanentRedirect($location); } return null; } } " Update path fonts gulp task,"// imports var gulp = require('gulp'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var uglify = require('gulp-uglify'); var buffer = require('vinyl-buffer'); // build src gulp.task('browserify', function(cb){ return browserify('./src/app.js', { debug: true }) .bundle() .pipe(source('bundle.js')) .pipe(gulp.dest('./www/')); cb(); }); // build in release mode gulp.task('browserify:release', function(cb){ return browserify('./src/app.js') .bundle() .pipe(source('bundle.js')) .pipe(buffer()) .pipe(uglify()) .pipe(gulp.dest('./www/')); cb(); }); // copy fonts gulp.task('fonts', function(cb){ return gulp.src('node_modules/ionic-npm/fonts/**') .pipe(gulp.dest('./www/fonts/')); cb(); }); // copy assets gulp.task('assets', function(cb){ return gulp.src('./assets/**') .pipe(gulp.dest('./www/')); cb(); }); // copy templates gulp.task('templates', function(cb){ return gulp.src('./src/**/*.html') .pipe(gulp.dest('./www/')); cb(); }); ","// imports var gulp = require('gulp'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var uglify = require('gulp-uglify'); var buffer = require('vinyl-buffer'); // build src gulp.task('browserify', function(cb){ return browserify('./src/app.js', { debug: true }) .bundle() .pipe(source('bundle.js')) .pipe(gulp.dest('./www/')); cb(); }); // build in release mode gulp.task('browserify:release', function(cb){ return browserify('./src/app.js') .bundle() .pipe(source('bundle.js')) .pipe(buffer()) .pipe(uglify()) .pipe(gulp.dest('./www/')); cb(); }); // copy fonts gulp.task('fonts', function(cb){ return gulp.src('node_modules/ionic-framework/release/fonts/**') .pipe(gulp.dest('./www/fonts/')); cb(); }); // copy assets gulp.task('assets', function(cb){ return gulp.src('./assets/**') .pipe(gulp.dest('./www/')); cb(); }); // copy templates gulp.task('templates', function(cb){ return gulp.src('./src/**/*.html') .pipe(gulp.dest('./www/')); cb(); });" Update dependency to Core v26,"# -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name = ""OpenFisca-Country-Template"", version = ""3.6.0"", author = ""OpenFisca Team"", author_email = ""contact@openfisca.org"", classifiers=[ ""Development Status :: 5 - Production/Stable"", ""License :: OSI Approved :: GNU Affero General Public License v3"", ""Operating System :: POSIX"", ""Programming Language :: Python"", ""Topic :: Scientific/Engineering :: Information Analysis"", ], description = ""OpenFisca tax and benefit system for Country-Template"", keywords = ""benefit microsimulation social tax"", license =""http://www.fsf.org/licensing/licenses/agpl-3.0.html"", url = ""https://github.com/openfisca/country-template"", include_package_data = True, # Will read MANIFEST.in data_files = [ (""share/openfisca/openfisca-country-template"", [""CHANGELOG.md"", ""LICENSE"", ""README.md""]), ], install_requires = [ ""OpenFisca-Core[web-api] >= 26.0, < 27.0"", ], extras_require = { ""dev"": [ ""autopep8 == 1.4.0"", ""flake8 >= 3.5.0, < 3.6.0"", ""flake8-print"", ""pycodestyle >= 2.3.0, < 2.4.0"", # To avoid incompatibility with flake ] }, packages=find_packages(), ) ","# -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name = ""OpenFisca-Country-Template"", version = ""3.6.0"", author = ""OpenFisca Team"", author_email = ""contact@openfisca.org"", classifiers=[ ""Development Status :: 5 - Production/Stable"", ""License :: OSI Approved :: GNU Affero General Public License v3"", ""Operating System :: POSIX"", ""Programming Language :: Python"", ""Topic :: Scientific/Engineering :: Information Analysis"", ], description = ""OpenFisca tax and benefit system for Country-Template"", keywords = ""benefit microsimulation social tax"", license =""http://www.fsf.org/licensing/licenses/agpl-3.0.html"", url = ""https://github.com/openfisca/country-template"", include_package_data = True, # Will read MANIFEST.in data_files = [ (""share/openfisca/openfisca-country-template"", [""CHANGELOG.md"", ""LICENSE"", ""README.md""]), ], install_requires = [ ""OpenFisca-Core[web-api] >= 25.0, < 26.0"", ], extras_require = { ""dev"": [ ""autopep8 == 1.4.0"", ""flake8 >= 3.5.0, < 3.6.0"", ""flake8-print"", ""pycodestyle >= 2.3.0, < 2.4.0"", # To avoid incompatibility with flake ] }, packages=find_packages(), ) " Remove unneeded exception signature from unit test.,"package com.fasterxml.jackson.databind.deser; import javax.measure.Measure; import java.util.List; import com.fasterxml.jackson.databind.BaseMapTest; import com.fasterxml.jackson.databind.ObjectMapper; public class TestNoClassDefFoundDeserializer extends BaseMapTest { public static class Parent { public List<Child> child; } public static class Child { public Measure measure; } public void testClassIsMissing() { boolean missing = false; try { Class.forName(""javax.measure.Measure""); } catch (ClassNotFoundException ex) { missing = true; } assertTrue(""javax.measure.Measure is not in classpath"", missing); } public void testDeserialize() throws Exception { ObjectMapper m = new ObjectMapper(); Parent result = m.readValue("" { } "", Parent.class); assertNotNull(result); } public void testUseMissingClass() throws Exception { boolean missing = false; try { ObjectMapper m = new ObjectMapper(); m.readValue("" { \""child\"" : [{}] } "", Parent.class); } catch (NoClassDefFoundError ex) { missing = true; } assertTrue(""cannot instantiate a missing class"", missing); } } ","package com.fasterxml.jackson.databind.deser; import javax.measure.Measure; import java.util.List; import com.fasterxml.jackson.databind.BaseMapTest; import com.fasterxml.jackson.databind.ObjectMapper; public class TestNoClassDefFoundDeserializer extends BaseMapTest { public static class Parent { public List<Child> child; } public static class Child { public Measure measure; } public void testClassIsMissing() throws ClassNotFoundException { boolean missing = false; try { Class.forName(""javax.measure.Measure""); } catch (ClassNotFoundException ex) { missing = true; } assertTrue(""javax.measure.Measure is not in classpath"", missing); } public void testDeserialize() throws Exception { ObjectMapper m = new ObjectMapper(); Parent result = m.readValue("" { } "", Parent.class); assertNotNull(result); } public void testUseMissingClass() throws Exception { boolean missing = false; try { ObjectMapper m = new ObjectMapper(); m.readValue("" { \""child\"" : [{}] } "", Parent.class); } catch (NoClassDefFoundError ex) { missing = true; } assertTrue(""cannot instantiate a missing class"", missing); } } " Add TODO for handling failed signup,"import React, { Component } from 'react'; import { Field, reduxForm } from 'redux-form'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import { registerUser } from '../../../../redux/actions'; import styles from './styles.css'; class SignupPage extends Component { constructor() { super(); this._submit = this._submit.bind(this); } _submit(data) { const { dispatch, history } = this.props; dispatch(registerUser(data)) .then(() => { // TODO: don't redirect if there was an error signing up for account history.push('/login'); }); } render() { const { handleSubmit, signUpError } = this.props; return ( <div className=""signup""> <div className=""signup__form""> <form onSubmit={ handleSubmit(this._submit) }> <p className=""signup__label"">Email</p> <Field className=""signup__input"" name=""email"" component=""input"" type=""text"" /> <p className=""signup__label"">Password</p> <Field className=""signup__input"" name=""password"" component=""input"" type=""password"" /> <button type=""submit"" className=""signup__submit"">Create</button> { signUpError && <p className=""signup__error"">{ signUpError }</p> } </form> </div> </div> ); } } export default withRouter(connect( ({ root }) => ({ signUpError: root.signUpError }) )(reduxForm({ form: 'signup' })(SignupPage))); ","import React, { Component } from 'react'; import { Field, reduxForm } from 'redux-form'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import { registerUser } from '../../../../redux/actions'; import styles from './styles.css'; class SignupPage extends Component { constructor() { super(); this._submit = this._submit.bind(this); } _submit(data) { const { dispatch, history } = this.props; dispatch(registerUser(data)) .then(() => { history.push('/login'); }); } render() { const { handleSubmit, signUpError } = this.props; return ( <div className=""signup""> <div className=""signup__form""> <form onSubmit={ handleSubmit(this._submit) }> <p className=""signup__label"">Email</p> <Field className=""signup__input"" name=""email"" component=""input"" type=""text"" /> <p className=""signup__label"">Password</p> <Field className=""signup__input"" name=""password"" component=""input"" type=""password"" /> <button type=""submit"" className=""signup__submit"">Create</button> { signUpError && <p className=""signup__error"">{ signUpError }</p> } </form> </div> </div> ); } } export default withRouter(connect( ({ root }) => ({ signUpError: root.signUpError }) )(reduxForm({ form: 'signup' })(SignupPage))); " Set log level. PhantomJS off.,"var istanbul = require('browserify-istanbul'); var isparta = require('isparta'); module.exports = function (config) { 'use strict'; config.set({ browsers: [ //'PhantomJS', 'Chrome', 'Firefox', 'Safari', 'Opera' ], reporters: ['progress', 'notify', 'coverage'], frameworks: ['browserify', 'mocha', 'chai-sinon', 'sinon'], // list of files / patterns to load in the browser files: ['./tests/spec/**/*.js'], preprocessors: { './tests/spec/**/*.js': ['browserify'] }, client: { mocha: {reporter: 'html'} // change Karma's debug.html to the mocha web reporter }, browserify: { debug: true, transform: [ //'babelify', istanbul({ instrumenter: isparta, ignore: ['**/node_modules/**', '**/test/**'], }) ], configure: function (bundle) { bundle.on('bundled', function (error) { if (error != null) console.error(error.message); }); } }, notifyReporter: { reportEachFailure: true, reportSuccess: true }, logLevel: 'LOG_INFO', }); }; ","var istanbul = require('browserify-istanbul'); var isparta = require('isparta'); module.exports = function (config) { 'use strict'; config.set({ browsers: [ 'Chrome', 'Firefox', 'Safari', 'Opera' ], reporters: ['progress', 'notify', 'coverage'], frameworks: ['browserify', 'mocha', 'chai-sinon', 'sinon'], // list of files / patterns to load in the browser files: ['./tests/spec/**/*.js'], preprocessors: { './tests/spec/**/*.js': ['browserify'] }, client: { mocha: {reporter: 'html'} // change Karma's debug.html to the mocha web reporter }, browserify: { debug: true, transform: [ //'babelify', istanbul({ instrumenter: isparta, ignore: ['**/node_modules/**', '**/test/**'], }) ], configure: function (bundle) { bundle.on('bundled', function (error) { if (error != null) console.error(error.message); }); } }, notifyReporter: { reportEachFailure: true, reportSuccess: true } }); }; " Fix some sorting thing for isort,"""""""This module contains utilities to support API links."""""" from django.utils import six from dynamic_rest.conf import settings from dynamic_rest.routers import DynamicRouter def merge_link_object(serializer, data, instance): """"""Add a 'links' attribute to the data that maps field names to URLs. NOTE: This is the format that Ember Data supports, but alternative implementations are possible to support other formats. """""" link_object = {} if not getattr(instance, 'pk', None): # If instance doesn't have a `pk` field, we'll assume it doesn't # have a canonical resource URL to hang a link off of. # This generally only affectes Ephemeral Objects. return data link_fields = serializer.get_link_fields() for name, field in six.iteritems(link_fields): # For included fields, omit link if there's no data. if name in data and not data[name]: continue link = getattr(field, 'link', None) if link is None: base_url = '' if settings.ENABLE_HOST_RELATIVE_LINKS: # if the resource isn't registered, this will default back to # using resource-relative urls for links. base_url = DynamicRouter.get_canonical_path( serializer.get_resource_key(), instance.pk ) or '' link = '%s%s/' % (base_url, name) # Default to DREST-generated relation endpoints. elif callable(link): link = link(name, field, data, instance) link_object[name] = link if link_object: data['links'] = link_object return data ","""""""This module contains utilities to support API links."""""" from django.utils import six from dynamic_rest.conf import settings from .routers import DynamicRouter def merge_link_object(serializer, data, instance): """"""Add a 'links' attribute to the data that maps field names to URLs. NOTE: This is the format that Ember Data supports, but alternative implementations are possible to support other formats. """""" link_object = {} if not getattr(instance, 'pk', None): # If instance doesn't have a `pk` field, we'll assume it doesn't # have a canonical resource URL to hang a link off of. # This generally only affectes Ephemeral Objects. return data link_fields = serializer.get_link_fields() for name, field in six.iteritems(link_fields): # For included fields, omit link if there's no data. if name in data and not data[name]: continue link = getattr(field, 'link', None) if link is None: base_url = '' if settings.ENABLE_HOST_RELATIVE_LINKS: # if the resource isn't registered, this will default back to # using resource-relative urls for links. base_url = DynamicRouter.get_canonical_path( serializer.get_resource_key(), instance.pk ) or '' link = '%s%s/' % (base_url, name) # Default to DREST-generated relation endpoints. elif callable(link): link = link(name, field, data, instance) link_object[name] = link if link_object: data['links'] = link_object return data " Fix the option name for Tableau server version,"from luigi_td.targets.result import ResultTarget import urllib import logging logger = logging.getLogger('luigi-interface') class TableauServerResultTarget(ResultTarget): # required server = None username = None password = None datasource = None # optional ssl = 'true' ssl_verify = 'true' server_version = None site = None project = None mode = 'replace' def get_result_url(self): reqs = {} for name in ['server', 'username', 'password', 'datasource']: if getattr(self, name) is None: raise TypeError('missing option ""{0}"" for {1}'.format(name, self)) reqs[name] = urllib.quote(getattr(self, name)) params = { 'ssl': self.ssl, 'ssl_verify': self.ssl_verify, 'server_version': self.server_version, 'site': self.site, 'project': self.project, 'mode': self.mode, } reqs['params'] = urllib.urlencode([(key, params[key]) for key in params if params[key] is not None]) return ""tableau://{username}:{password}@{server}/{datasource}?{params}"".format(**reqs) class TableauOnlineResultTarget(TableauServerResultTarget): server = 'online.tableausoftware.com' server_version = 'online' ","from luigi_td.targets.result import ResultTarget import urllib import logging logger = logging.getLogger('luigi-interface') class TableauServerResultTarget(ResultTarget): # required server = None username = None password = None datasource = None # optional ssl = 'true' ssl_verify = 'true' version = None site = None project = None mode = 'replace' def get_result_url(self): reqs = {} for name in ['server', 'username', 'password', 'datasource']: if getattr(self, name) is None: raise TypeError('missing option ""{0}"" for {1}'.format(name, self)) reqs[name] = urllib.quote(getattr(self, name)) params = { 'ssl': self.ssl, 'ssl_verify': self.ssl_verify, 'version': self.version, 'site': self.site, 'project': self.project, 'mode': self.mode, } reqs['params'] = urllib.urlencode([(key, params[key]) for key in params if params[key] is not None]) return ""tableau://{username}:{password}@{server}/{datasource}?{params}"".format(**reqs) class TableauOnlineResultTarget(TableauServerResultTarget): server = 'online.tableausoftware.com' version = 'online' " "CRM-2945: Prepare demo - fix cs build","<?php namespace Oro\Bundle\IntegrationBundle\Exception; class SoapConnectionException extends TransportException { /** * @param string $response * @param \Exception $exception * @param string $request * @param string $headers * * @return static */ public static function createFromResponse($response, \Exception $exception = null, $request = '', $headers = '') { $exceptionMessage = ''; $exceptionCode = 0; $code = 'unknown'; if (null !== $exception) { $exceptionMessage = $exception->getMessage(); $exceptionCode = $exception->getCode(); } if (!empty($headers['code'])) { $code = $headers['code']; } $message = PHP_EOL; $message .= str_pad('[message]', 20, ' ', STR_PAD_RIGHT) . $exceptionMessage . PHP_EOL; $message .= str_pad('[request]', 20, ' ', STR_PAD_RIGHT) . $request . PHP_EOL; $message .= str_pad('[response]', 20, ' ', STR_PAD_RIGHT) . $response . PHP_EOL; $message .= str_pad('[code]', 20, ' ', STR_PAD_RIGHT) . $code . PHP_EOL; $message .= PHP_EOL; $newException = new static($message, $exceptionCode, $exception); if ($exception instanceof \SoapFault) { $newException->setFaultCode($exception->faultcode); } return $newException; } } ","<?php namespace Oro\Bundle\IntegrationBundle\Exception; class SoapConnectionException extends TransportException { /** * @param string $response * @param \Exception $exception * @param string $request * @param string $headers * * @return static */ public static function createFromResponse($response, \Exception $exception = null, $request = '', $headers = '') { $exceptionMessage = null !== $exception ? $exception->getMessage() : ''; $exceptionCode = null !== $exception ? $exception->getCode() : 0; $code = !empty($headers['code']) ? $headers['code'] : 'unknown'; $message = PHP_EOL; $message .= str_pad('[message]', 20, ' ', STR_PAD_RIGHT) . $exceptionMessage . PHP_EOL; $message .= str_pad('[request]', 20, ' ', STR_PAD_RIGHT) . $request . PHP_EOL; $message .= str_pad('[response]', 20, ' ', STR_PAD_RIGHT) . $response . PHP_EOL; $message .= str_pad('[code]', 20, ' ', STR_PAD_RIGHT) . $code . PHP_EOL; $message .= PHP_EOL; $newException = new static($message, $exceptionCode, $exception); if ($exception instanceof \SoapFault) { $newException->setFaultCode($exception->faultcode); } return $newException; } } " ZON-3409: Update to version with celery.,"from setuptools import setup, find_packages setup( name='zeit.content.gallery', version='2.7.4.dev0', author='gocept, Zeit Online', author_email='zon-backend@zeit.de', url='http://www.zeit.de/', description=""vivi Content-Type Portraitbox"", packages=find_packages('src'), package_dir={'': 'src'}, include_package_data=True, zip_safe=False, license='BSD', namespace_packages=['zeit', 'zeit.content'], install_requires=[ 'cssselect', 'Pillow', 'gocept.form', 'setuptools', 'zeit.cms >= 3.0.dev0', 'zeit.connector>=2.4.0.dev0', 'zeit.imp>=0.15.0.dev0', 'zeit.content.image', 'zeit.push>=1.7.0.dev0', 'zeit.wysiwyg', 'zope.app.appsetup', 'zope.app.testing', 'zope.component', 'zope.formlib', 'zope.interface', 'zope.publisher', 'zope.security', 'zope.testing', ], entry_points={ 'fanstatic.libraries': [ 'zeit_content_gallery=zeit.content.gallery.browser.resources:lib', ], }, ) ","from setuptools import setup, find_packages setup( name='zeit.content.gallery', version='2.7.4.dev0', author='gocept, Zeit Online', author_email='zon-backend@zeit.de', url='http://www.zeit.de/', description=""vivi Content-Type Portraitbox"", packages=find_packages('src'), package_dir={'': 'src'}, include_package_data=True, zip_safe=False, license='BSD', namespace_packages=['zeit', 'zeit.content'], install_requires=[ 'cssselect', 'Pillow', 'gocept.form', 'setuptools', 'zeit.cms>=2.92.1.dev0', 'zeit.connector>=2.4.0.dev0', 'zeit.imp>=0.15.0.dev0', 'zeit.content.image', 'zeit.push>=1.7.0.dev0', 'zeit.wysiwyg', 'zope.app.appsetup', 'zope.app.testing', 'zope.component', 'zope.formlib', 'zope.interface', 'zope.publisher', 'zope.security', 'zope.testing', ], entry_points={ 'fanstatic.libraries': [ 'zeit_content_gallery=zeit.content.gallery.browser.resources:lib', ], }, ) " Remove no longer needed package_data,"#!/usr/bin/env python from setuptools import setup, find_packages __about__ = {} with open(""warehouse/__about__.py"") as fp: exec(fp, None, __about__) setup( name=__about__[""__title__""], version=__about__[""__version__""], description=__about__[""__summary__""], long_description=open(""README.rst"").read(), url=__about__[""__uri__""], license=__about__[""__license__""], author=__about__[""__author__""], author_email=__about__[""__email__""], install_requires=[ ""Flask"", ""Flask-SQLAlchemy"", ""Flask-Script"", ""boto"", ""eventlet"", ""progress"", ""psycopg2"", ""python-s3file>=1.1"", ""requests"", ""schema"", ""xmlrpc2"", ], extras_require={ ""tests"": [ ""pylint"", ], }, packages=find_packages(exclude=[""tests""]), package_data={ ""warehouse"": [ ""simple/templates/*.html"", ""synchronize/*.crt"", ], }, include_package_data=True, entry_points={ ""console_scripts"": [ ""warehouse = warehouse.__main__:main"", ], }, classifiers=[ ""License :: OSI Approved :: BSD License"", ""Operating System :: POSIX"", ""Programming Language :: Python :: 2.7"", ""Programming Language :: Python :: Implementation :: CPython"", ""Programming Language :: Python :: Implementation :: PyPy"", ], zip_safe=False, ) ","#!/usr/bin/env python from setuptools import setup, find_packages __about__ = {} with open(""warehouse/__about__.py"") as fp: exec(fp, None, __about__) setup( name=__about__[""__title__""], version=__about__[""__version__""], description=__about__[""__summary__""], long_description=open(""README.rst"").read(), url=__about__[""__uri__""], license=__about__[""__license__""], author=__about__[""__author__""], author_email=__about__[""__email__""], install_requires=[ ""Flask"", ""Flask-SQLAlchemy"", ""Flask-Script"", ""boto"", ""eventlet"", ""progress"", ""psycopg2"", ""python-s3file>=1.1"", ""requests"", ""schema"", ""xmlrpc2"", ], extras_require={ ""tests"": [ ""pylint"", ], }, packages=find_packages(exclude=[""tests""]), package_data={ """": [""LICENSE""], ""warehouse"": [ ""simple/templates/*.html"", ""synchronize/*.crt"", ], }, include_package_data=True, entry_points={ ""console_scripts"": [ ""warehouse = warehouse.__main__:main"", ], }, classifiers=[ ""License :: OSI Approved :: BSD License"", ""Operating System :: POSIX"", ""Programming Language :: Python :: 2.7"", ""Programming Language :: Python :: Implementation :: CPython"", ""Programming Language :: Python :: Implementation :: PyPy"", ], zip_safe=False, ) " Change to dist dir before uploading to lose the absolute path.,"import tempfile import tee from os.path import split from process import Process from chdir import ChdirStack from exit import err_exit class SCP(object): """"""Secure copy and FTP abstraction."""""" def __init__(self, process=None): self.process = process or Process() self.dirstack = ChdirStack() def run_scp(self, distfile, location): if not self.process.quiet: print 'scp-ing to %(location)s' % locals() rc = self.process.os_system( 'scp ""%(distfile)s"" ""%(location)s""' % locals()) if rc != 0: err_exit('scp failed') return rc def run_sftp(self, distfile, location): if not self.process.quiet: print 'sftp-ing to %(location)s' % locals() dir, distfile = split(distfile) self.dirstack.push(dir) try: with tempfile.NamedTemporaryFile(prefix='sftp-') as file: file.write('put ""%(distfile)s""\n' % locals()) file.write('bye\n') file.flush() cmdfile = file.name rc, lines = self.process.popen( 'sftp -b ""%(cmdfile)s"" ""%(location)s""' % locals(), echo=tee.StartsWith('Uploading')) if rc != 0: err_exit('sftp failed') return rc finally: self.dirstack.pop() ","import tempfile import tee from process import Process from exit import err_exit class SCP(object): """"""Secure copy and FTP abstraction."""""" def __init__(self, process=None): self.process = process or Process() def run_scp(self, distfile, location): if not self.process.quiet: print 'scp-ing to %(location)s' % locals() rc = self.process.os_system( 'scp ""%(distfile)s"" ""%(location)s""' % locals()) if rc != 0: err_exit('scp failed') return rc def run_sftp(self, distfile, location): if not self.process.quiet: print 'sftp-ing to %(location)s' % locals() with tempfile.NamedTemporaryFile(prefix='sftp-') as file: file.write('put ""%(distfile)s""\n' % locals()) file.write('quit\n') file.flush() cmdfile = file.name rc, lines = self.process.popen( 'sftp -b ""%(cmdfile)s"" ""%(location)s""' % locals(), echo=tee.StartsWith('Uploading')) if rc != 0: err_exit('sftp failed') return rc " Rename edit task descriptor set address method to set deadline,"package seedu.address.logic.parser; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.logic.parser.CliSyntax.PREFIX_DEADLINE; import static seedu.address.logic.parser.CliSyntax.PREFIX_TIMEINTERVAL_END; import static seedu.address.logic.parser.CliSyntax.PREFIX_TIMEINTERVAL_START; import seedu.address.logic.commands.Command; import seedu.address.logic.commands.IncorrectCommand; import seedu.address.logic.commands.ListCommand; public class ListCommandParser { /** * Parses the given {@code String} of arguments in the context of the * FindCommand and returns an FindCommand object for execution. */ public Command parse(String args) { try { ArgumentTokenizer argsTokenizer = new ArgumentTokenizer(PREFIX_DEADLINE, PREFIX_TIMEINTERVAL_START, PREFIX_TIMEINTERVAL_END); argsTokenizer.tokenize(args); if (args.trim().contains(PREFIX_TIMEINTERVAL_START.getPrefix()) && args.trim().contains(PREFIX_TIMEINTERVAL_END.getPrefix())) { return new ListCommand(argsTokenizer.getValue(PREFIX_TIMEINTERVAL_START).get(), argsTokenizer.getValue(PREFIX_TIMEINTERVAL_END).get()); } else if (args.trim().contains(PREFIX_DEADLINE.getPrefix())) { return new ListCommand(argsTokenizer.getValue(PREFIX_DEADLINE).get()); } } catch (Exception e) { e.printStackTrace(); return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListCommand.MESSAGE_USAGE)); } return new ListCommand(); } } ","package seedu.address.logic.parser; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.logic.parser.CliSyntax.PREFIX_DEADLINE; import java.util.Date; import java.util.List; import seedu.address.logic.commands.Command; import seedu.address.logic.commands.IncorrectCommand; import seedu.address.logic.commands.ListCommand; public class ListCommandParser { /** * Parses the given {@code String} of arguments in the context of the * FindCommand and returns an FindCommand object for execution. */ public Command parse(String args) { try { if (!args.isEmpty() && args.contains(""by "")) { ArgumentTokenizer argsTokenizer = new ArgumentTokenizer(PREFIX_DEADLINE); argsTokenizer.tokenize(args); List<Date> endDateList = new DateTimeParser().parse( argsTokenizer.getValue(PREFIX_DEADLINE).get()).get(0).getDates(); List<Date> startDateList = new DateTimeParser().parse(""now"").get(0).getDates(); return new ListCommand(startDateList.get(0), endDateList.get(0)); } } catch (Exception e) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListCommand.MESSAGE_USAGE)); } return new ListCommand(); } } " Fix lowercase weekday in own availability,"import ActionTypes from '../constants/ActionTypes'; import BaseStore from './BaseStore'; class AvailabilityStore extends BaseStore { setInitial() { this._availability = {'static': [], 'dynamic': []} } _registerToActions(action) { super._registerToActions(action); switch (action.type) { case ActionTypes.EDIT_AVAILABILITY: this.availability = action.availability; this.emitChange(); break; case ActionTypes.REQUEST_LOGIN_USER_SUCCESS: case ActionTypes.REQUEST_AUTOLOGIN_SUCCESS: this.availability = action.response.user.availability ? action.response.user.availability : this._availability; console.log(this.ownAvailability); this.emitChange(); break; case ActionTypes.REQUEST_REGISTER_USER_SUCCESS: this.availability = action.availability; this.emitChange(); break; default: break; } } get ownAvailability() { return this._availability; } set availability(availability) { this._availability = availability; } } export default new AvailabilityStore(); ","import ActionTypes from '../constants/ActionTypes'; import BaseStore from './BaseStore'; class AvailabilityStore extends BaseStore { setInitial() { this._availability = {'static': [], 'dynamic': []} } _registerToActions(action) { super._registerToActions(action); switch (action.type) { case ActionTypes.EDIT_AVAILABILITY: this.availability = action.availability; this.emitChange(); break; case ActionTypes.REQUEST_LOGIN_USER_SUCCESS: case ActionTypes.REQUEST_AUTOLOGIN_SUCCESS: this.availability = action.response.user.availability ? action.response.user.availability : this._availability; console.log(this.ownAvailability); this.emitChange(); break; case ActionTypes.REQUEST_REGISTER_USER_SUCCESS: this.availability = action.availability; this.emitChange(); break; default: break; } } get ownAvailability() { return this._availability; } set availability(availability) { availability.dynamic.forEach((dynamicCase) => { dynamicCase.weekday = dynamicCase.weekday.toLowerCase(); }); this._availability = availability; } } export default new AvailabilityStore(); " Fix to append when document body is ready,"(function () { var _console = window.console; var _methods = { log: window.console.log, error: window.console.error, info: window.console.info, debug: window.console.debug, clear: window.console.clear, }; function append (message) { if (document.body) { document.body.append(message); } else { setTimeout(append, 100, message); } } function clear () { if (document.body) { document.body.innerHtml = null; } _methods.clear.call(_console); }; function message (text, color, $message) { $message = document.createElement('span'); $message.style.color = color || '#000000'; $message.innerText = text; return $message; } function write (key, color) { return function () { Function.prototype.apply.call(_methods[key], _console, arguments); append(message(Array.prototype.slice.call(arguments).join(' '), color)); }; } window.console.clear = clear; window.console.error = write('error', '#ff0000'); window.console.log = write('log'); window.console.info = write('info'); window.console.debug = write('debug'); function errorHandler (e) { e.preventDefault(); console.error(e.message); return true; } if (window.attachEvent) { window.attachEvent('onerror', errorHandler); } else { window.addEventListener('error', errorHandler, true); } }) (); ","(function () { var _console = window.console; var _methods = { log: window.console.log, error: window.console.error, info: window.console.info, debug: window.console.debug, clear: window.console.clear, }; var $body = document.body; function append (message) { $body.append(message); } function clear () { $body.innerHtml = """"; _methods.clear.call(_console); }; function message (text, color, $message) { $message = document.createElement('span'); $message.style.color = color || '#000000'; $message.innerText = text; return $message; } function write (key, color) { return function () { Function.prototype.apply.call(_methods[key], _console, arguments); append(message(Array.prototype.slice.call(arguments).join(' '), color)); }; } window.console.clear = clear; window.console.error = write('error', '#ff0000'); window.console.log = write('log'); window.console.info = write('info'); window.console.debug = write('debug'); function errorHandler (e) { e.preventDefault(); console.error(e.message); return true; } if (window.attachEvent) { window.attachEvent('onerror', errorHandler); } else { window.addEventListener('error', errorHandler, true); } }) (); " Use template for namespaced version,"(function() { if(typeof(this.PHP_JS) === ""undefined""){ // This references at top of namespace allows PHP_JS class to // be included directly inside an object (unusual use) var PHP_JS = function(cfgObj) { if(!(this instanceof PHP_JS)) { // Allow invokation without ""new"" return new PHP_JS(cfgObj); } this.window = cfgObj && cfgObj.window ? cfgObj.window : window; // Allow user to pass in window, e.g., if in context // without access to window but need to pass in, like // a Mozilla JavaScript module }; } var php_js_shared = {}; // Private static holder across all instances; we usually use // instance variables, but this is necessary for a very few // like require_once()/include_once() PHP_JS.prototype = { //#FUNCTIONS_HERE# }; // end PHP_JS.prototype this.PHP_JS = PHP_JS; // User must instantiate (don't need ""new"" to do it, though slightly // faster if do use ""new"") // use in own code like: var $P = PHP_JS(); // If you place this namespace in a context like a JavaScript module // (e.g., for a Firefox extension) without access to the global // window object, you could instantiate in code which did have // access to ""window"" like this: var $P = PHP_JS({window:window}); }()); ","(function() { if(typeof(this.PHP_JS) === ""undefined""){ // This references at top of namespace allows PHP_JS class to // be included directly inside an object (unusual use) var PHP_JS = function(cfgObj) { if(!(this instanceof PHP_JS)) { // Allow invokation without ""new"" return new PHP_JS(cfgObj); } this.window = cfgObj && cfgObj.window ? cfgObj.window : window; // Allow user to pass in window, e.g., if in context // without access to window but need to pass in, like // a Mozilla JavaScript module }; } var php_js_shared = {}; // Private static holder across all instances; we usually use // instance variables, but this is necessary for a very few // like require_once()/include_once() PHP_JS.prototype = { //#FUNCTIONS_HERE# }; // end PHP_JS.prototype this.PHP_JS = PHP_JS; // User must instantiate (don't need ""new"" to do it, though slightly // faster if do use ""new"") // use in own code like: var $P = PHP_JS(); // If you place this namespace in a context like a JavaScript module // (e.g., for a Firefox extension) without access to the global // window object, you could instantiate in code which did have // access to ""window"" like this: var $P = PHP_JS({window:window}); }()); // Kevin, I moved invocation parentheses inside the other parentheses for // the sake of jslint; otherwise, no difference" INC-7: Fix Java 8 javadoc errors,"/* * Created by brightSPARK Labs * www.brightsparklabs.com */ package com.brightsparklabs.asanti.validator; import com.brightsparklabs.assam.data.AsnData; import com.brightsparklabs.assam.validator.Validator; /** * Static utility methods pertaining to {@link Validator} instances. * * @author brightSPARK Labs */ public class Validators { // ------------------------------------------------------------------------- // CLASS VARIABLES // ------------------------------------------------------------------------- /** the default validator */ private static Validator instance; // ------------------------------------------------------------------------- // CONSTRUCTION // ------------------------------------------------------------------------- /** * Private constructor. */ private Validators() { // static utility class should never be instantiated throw new AssertionError(); } // ------------------------------------------------------------------------- // PUBLIC METHODS // ------------------------------------------------------------------------- /** * Returns the default validator which validates {@link AsnData} against its corresponding * schema. * * @return the default validator */ public static Validator getDefault() { /* * NOTE: Not thread safe, but unlikely this method will actually be called. Generally a * custom validator will be used. */ if (instance == null) { instance = ValidatorImpl.builder().build(); } return instance; } /** * Returns a builder for creating a Validator which which validates {@link AsnData} against its * corresponding schema as well as any custom validation rules. * * @return the default validator */ public static ValidatorImpl.Builder newCustomValidatorBuilder() { return ValidatorImpl.builder(); } } ","/* * Created by brightSPARK Labs * www.brightsparklabs.com */ package com.brightsparklabs.asanti.validator; import com.brightsparklabs.assam.validator.Validator; /** * Static utility methods pertaining to {@link Validator} instances. * * @author brightSPARK Labs */ public class Validators { // ------------------------------------------------------------------------- // CLASS VARIABLES // ------------------------------------------------------------------------- /** the default validator */ private static Validator instance; // ------------------------------------------------------------------------- // CONSTRUCTION // ------------------------------------------------------------------------- /** * Private constructor. */ private Validators() { // static utility class should never be instantiated throw new AssertionError(); } // ------------------------------------------------------------------------- // PUBLIC METHODS // ------------------------------------------------------------------------- /** * Returns the default validator which validates @link{AsnData} against its corresponding * schema. * * @return the default validator */ public static Validator getDefault() { /* * NOTE: Not thread safe, but unlikely this method will actually be called. Generally a * custom validator will be used. */ if (instance == null) { instance = ValidatorImpl.builder().build(); } return instance; } /** * Returns a builder for creating a Validator which which validates {@AsnData} against its * corresponding schema as well as any custom validation rules. * * @return the default validator */ public static ValidatorImpl.Builder newCustomValidatorBuilder() { return ValidatorImpl.builder(); } } " Add case for select-multiple inputs,"import React from 'react'; export default function(WrappedComponent) { const Field = React.createClass({ getInitialState() { return { value: """", message: """", valid: true }; }, componentDidMount() { this.validators = this.validators || []; let validators = this.props.validators; if (validators && validators.constructor === Array) { this.validators = this.validators.concat(validators); } }, validate() { for (let validator of this.validators) { let result = validator(this.state.value); if (result !== true) { this.setState({valid: false, message: result}); return false; } } this.setState({valid: true, message: """"}); return true; }, handleChange(event) { return new Promise((resolve) => { switch (event.target.type) { case ""checkbox"": this.setState({value: event.target.checked}, resolve); break; case ""select-multiple"": this.setState({ value: Array.from(event.target.selectedOptions).map((option) => { return option.value; }) }, resolve); break; default: this.setState({value: event.target.value}, resolve); break; } }); }, render() { return ( <WrappedComponent handleChange={this.handleChange} message={this.state.message} validate={this.validate}/> ); } }); return Field; } ","import React from 'react'; import classNames from 'classnames'; export default function(WrappedComponent) { const Field = React.createClass({ getInitialState() { return { value: """", message: """", valid: true }; }, componentDidMount() { this.validators = this.validators || []; let validators = this.props.validators; if (validators && validators.constructor === Array) { this.validators = this.validators.concat(validators); } }, validate() { for (let validator of this.validators) { let result = validator(this.state.value); if (result !== true) { this.setState({valid: false, message: result}); return false; } } this.setState({valid: true, message: """"}); return true; }, handleChange(event) { return new Promise((resolve) => { switch (event.target.type) { case ""checkbox"": this.setState({value: event.target.checked}, resolve); break; default: this.setState({value: event.target.value}, resolve); break; } }); }, render() { return ( <WrappedComponent handleChange={this.handleChange} message={this.state.message} validate={this.validate}/> ); } }); return Field; } " Add double quotes for MAC address,"{ ""inbound"": [ { ""cookie"": 1, ""match"": { ""tcp_dst"": 4321 }, ""action"": { ""fwd"": 0 } }, { ""cookie"": 2, ""match"": { ""tcp_dst"": 4322 }, ""action"": { ""fwd"": 1 } }, { ""cookie"": 3, ""match"": { ""eth_src"": ""08:00:27:89:3b:9f"" }, ""action"": { ""drop"": 0 } } ] }","{ ""inbound"": [ { ""cookie"": 1, ""match"": { ""tcp_dst"": 4321 }, ""action"": { ""fwd"": 0 } }, { ""cookie"": 2, ""match"": { ""tcp_dst"": 4322 }, ""action"": { ""fwd"": 1 } }, { ""cookie"": 3, ""match"": { ""eth_src"": '08:00:27:89:3b:9f' }, ""action"": { ""drop"": 0 } } ] }" Set input type to phone for phone.,"# -*- coding:utf-8 -*- from django import forms from django.utils.translation import ugettext as _ from .models import Item, Group, Profile, Area class SearchForm(forms.Form): area = forms.ModelChoiceField(label=_('Area'), queryset=Area.objects.all(), required=False) group = forms.ModelChoiceField(label=_('Group'), queryset=Group.objects.all(), required=False) q = forms.CharField(required=False, label=_('Query'),) def filter_by(self): # TODO search using more than one field # TODO split query string and make seaprate search by words filters = {} if self.cleaned_data['group']: filters['group'] = self.cleaned_data['group'] if self.cleaned_data['area']: filters['area'] = self.cleaned_data['area'] filters['description__icontains'] = self.cleaned_data['q'] return filters class ItemForm(forms.ModelForm): class Meta: model = Item fields = ( 'area', 'group', 'title', 'description', 'price', 'is_active' ) class PhoneWidget(forms.TextInput): input_type = 'phone' class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'phone', ) widgets = { 'phone': PhoneWidget } ","# -*- coding:utf-8 -*- from django import forms from django.utils.translation import ugettext as _ from .models import Item, Group, Profile, Area class SearchForm(forms.Form): area = forms.ModelChoiceField(label=_('Area'), queryset=Area.objects.all(), required=False) group = forms.ModelChoiceField(label=_('Group'), queryset=Group.objects.all(), required=False) q = forms.CharField(required=False, label=_('Query'),) def filter_by(self): # TODO search using more than one field # TODO split query string and make seaprate search by words filters = {} if self.cleaned_data['group']: filters['group'] = self.cleaned_data['group'] if self.cleaned_data['area']: filters['area'] = self.cleaned_data['area'] filters['description__icontains'] = self.cleaned_data['q'] return filters class ItemForm(forms.ModelForm): class Meta: model = Item fields = ( 'area', 'group', 'title', 'description', 'price', 'is_active' ) class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'phone', ) " Revert the change to show cluster list even if you only have one,"<?php # $Id: get_ganglia.php 2510 2011-03-15 01:12:34Z vvuksan $ # Retrieves and parses the XML output from gmond. Results stored # in global variables: $clusters, $hosts, $hosts_down, $metrics. # Assumes you have already called get_context.php. # if (! Gmetad($conf['ganglia_ip'], $conf['ganglia_port']) ) { print ""<H4>There was an error collecting ganglia data "". ""(${conf['ganglia_ip']}:${conf['ganglia_port']}): $error</H4>\n""; exit; } # If we have no child data sources, assume something is wrong. if (!count($grid) and !count($cluster)) { print ""<H4>Ganglia cannot find a data source. Is gmond running?</H4>""; exit; } # If we only have one cluster source, suppress MetaCluster output. if (count($grid) <= 2 and $context==""meta"") { # Lets look for one cluster (the other is our grid). foreach($grid as $source) if (isset($source['CLUSTER']) and $source['CLUSTER']) { $standalone = 1; $context = ""cluster""; # Need to refresh data with new context. Gmetad($conf['ganglia_ip'], $conf['ganglia_port']); $clustername = $source['NAME']; } } ?> ","<?php # $Id: get_ganglia.php 2510 2011-03-15 01:12:34Z vvuksan $ # Retrieves and parses the XML output from gmond. Results stored # in global variables: $clusters, $hosts, $hosts_down, $metrics. # Assumes you have already called get_context.php. # if (! Gmetad($conf['ganglia_ip'], $conf['ganglia_port']) ) { print ""<H4>There was an error collecting ganglia data "". ""(${conf['ganglia_ip']}:${conf['ganglia_port']}): $error</H4>\n""; exit; } # If we have no child data sources, assume something is wrong. if (!count($grid) and !count($cluster)) { print ""<H4>Ganglia cannot find a data source. Is gmond running?</H4>""; exit; } # If we only have one cluster source, suppress MetaCluster output. #if (count($grid) <= 2 and $context==""meta"") # { # # Lets look for one cluster (the other is our grid). # foreach($grid as $source) # if (isset($source['CLUSTER']) and $source['CLUSTER']) # { # $standalone = 1; # $context = ""cluster""; # # Need to refresh data with new context. # Gmetad($conf['ganglia_ip'], $conf['ganglia_port']); # $clustername = $source['NAME']; # } # } ?> " "Add a zero-width word boundary to the start to make it faster ""\b"" checks only edge of the words, so it will make the regex faster since it's gonna skip the other locations.","/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // @flow /** * Takes a string and returns the string with public URLs removed. * It doesn't remove the URLs like `chrome://..` because they are internal URLs * and they shouldn't be removed. */ export function removeURLs( string: string, removeExtensions: boolean = true ): string { const rmExtensions = removeExtensions ? '|moz-extension:' : ''; const regExp = new RegExp( '\\b((?:https?:|ftp:|file:/?' + rmExtensions + ')//)[^\\s/$.?#][^\\s)]*', // ^ ^ ^ // | | Matches any characters except // | | whitespaces and ')' character. // | | Other characters are allowed now // | Matches any character except whitespace // | and '/', '$', '.', '?' or '#' characters // | because this is start of the URL // Matches 'http', 'https', 'ftp', 'file' and optionally 'moz-extension' protocols. // The colons are repeated here but it was necessary because file protocol can be either // 'file://' or 'file:///' and we need to check that inside the first group. 'gi' ); return string.replace(regExp, '$1<URL>'); } ","/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // @flow /** * Takes a string and returns the string with public URLs removed. * It doesn't remove the URLs like `chrome://..` because they are internal URLs * and they shouldn't be removed. */ export function removeURLs( string: string, removeExtensions: boolean = true ): string { const rmExtensions = removeExtensions ? '|moz-extension:' : ''; const regExp = new RegExp( '((?:https?:|ftp:|file:/?' + rmExtensions + ')//)[^\\s/$.?#][^\\s)]*', // ^ ^ ^ // | | Matches any characters except // | | whitespaces and ')' character. // | | Other characters are allowed now // | Matches any character except whitespace // | and '/', '$', '.', '?' or '#' characters // | because this is start of the URL // Matches 'http', 'https', 'ftp', 'file' and optionally 'moz-extension' protocols. // The colons are repeated here but it was necessary because file protocol can be either // 'file://' or 'file:///' and we need to check that inside the first group. 'gi' ); return string.replace(regExp, '$1<URL>'); } " Clear scope product name value,"'use strict'; var app = angular.module('ProductsApp'); app.controller('editmodeController', ['$scope', function($scope) { var ctrl = this; ctrl.enterEvent = function(event) { if (event.which === 13){ $scope.$parent.product.editMode = false; } }; }]); app.controller('ProductCtrl', [ '$scope', 'Product', ($scope, Product) => { $scope.products = Product.query( () => { let genId = () => { let pIds = []; for (var i = 0; i < $scope.products.length; i++) pIds.push($scope.products[i].id); return Math.max.apply(null, pIds)+1; }; $scope.insert = function(name) { $scope.products.push( { id: $scope.products.length > 0 ? genId() : 1, name: name } ); $scope.name = """"; }; $scope.updateProduct = (name, $index) => { $scope.products[$index].name = name; }; }); $scope.showPrompt = false; $scope.editMode = false; $scope.saveProducts = () => { Product.save($scope.products); }; $scope.delete = function(index) { $scope.products.splice(index, 1); }; $scope.edit=function(producto){ producto.editMode = true; }; }]);","'use strict'; var app = angular.module('ProductsApp'); app.controller('editmodeController', ['$scope', function($scope) { var ctrl = this; ctrl.enterEvent = function(event) { if (event.which === 13){ $scope.$parent.product.editMode = false; } }; }]); app.controller('ProductCtrl', [ '$scope', 'Product', ($scope, Product) => { $scope.products = Product.query( () => { let genId = () => { let pIds = []; for (var i = 0; i < $scope.products.length; i++) pIds.push($scope.products[i].id); return Math.max.apply(null, pIds)+1; }; $scope.insert = function(name) { $scope.products.push( { id: $scope.products.length > 0 ? genId() : 1, name: name } ); }; $scope.updateProduct = (name, $index) => { $scope.products[$index].name = name; }; }); $scope.showPrompt = false; $scope.editMode = false; $scope.saveProducts = () => { Product.save($scope.products); }; $scope.delete = function(index) { $scope.products.splice(index, 1); }; $scope.edit=function(producto){ producto.editMode = true; }; }]);" "Fix compatibility with svgr and images #971","import React from 'react'; import { Image, requireNativeComponent } from 'react-native'; import { meetOrSliceTypes, alignEnum } from '../lib/extract/extractViewBox'; import extractProps, { propsAndStyles } from '../lib/extract/extractProps'; import Shape from './Shape'; const spacesRegExp = /\s+/; export default class SvgImage extends Shape { static displayName = 'Image'; static defaultProps = { x: 0, y: 0, width: 0, height: 0, preserveAspectRatio: 'xMidYMid meet', }; render() { const { props } = this; const { preserveAspectRatio, x, y, width, height, xlinkHref, href = xlinkHref, } = props; const modes = preserveAspectRatio.trim().split(spacesRegExp); return ( <RNSVGImage ref={this.refMethod} {...extractProps({ ...propsAndStyles(props), x: null, y: null }, this)} x={x} y={y} width={width} height={height} meetOrSlice={meetOrSliceTypes[modes[1]] || 0} align={alignEnum[modes[0]] || 'xMidYMid'} src={Image.resolveAssetSource( typeof href === 'string' ? { uri: href } : href, )} /> ); } } const RNSVGImage = requireNativeComponent('RNSVGImage'); ","import React from 'react'; import { Image, requireNativeComponent } from 'react-native'; import { meetOrSliceTypes, alignEnum } from '../lib/extract/extractViewBox'; import extractProps, { propsAndStyles } from '../lib/extract/extractProps'; import Shape from './Shape'; const spacesRegExp = /\s+/; export default class SvgImage extends Shape { static displayName = 'Image'; static defaultProps = { x: 0, y: 0, width: 0, height: 0, preserveAspectRatio: 'xMidYMid meet', }; render() { const { props } = this; const { preserveAspectRatio, x, y, width, height, xlinkHref, href = xlinkHref, } = props; const modes = preserveAspectRatio.trim().split(spacesRegExp); return ( <RNSVGImage ref={this.refMethod} {...extractProps({ ...propsAndStyles(props), x: null, y: null }, this)} x={x} y={y} width={width} height={height} meetOrSlice={meetOrSliceTypes[modes[1]] || 0} align={alignEnum[modes[0]] || 'xMidYMid'} src={Image.resolveAssetSource(href)} /> ); } } const RNSVGImage = requireNativeComponent('RNSVGImage'); " Change Tweet upper length limit,"from datetime import date import calendar def get_time_index(update): if ""warning"" in update: return 7 if ""pollution"" in update: return 8 elif ""today"" in update: return 0 elif ""this morning"" in update: return 1 elif ""this lunchtime"" in update: return 2 elif ""this afternoon"" in update: return 3 elif ""this evening"" in update: return 4 elif ""tonight"" in update: return 5 elif "" day"" in update: return 6 else: raise Exception(""time not set: {}"".format(update)) def sort_by_time(updates): timed_updates = {} for update in updates: timed_updates[update] = get_time_index(update) for update in sorted(timed_updates, key=timed_updates.get): yield update def fit_into_tweets(updates): dayname = calendar.day_name[date.today().weekday()] alerts = [] alert = dayname + "": "" addToAlert = True i = 1 for update in updates: if (len(alert) + len(update) < 280): alert += update + "" "" addToAlert = True else: alerts.append(alert.rstrip()) i += 1 alert = dayname + "": "" + update + "" "" if addToAlert or len(alerts) < i: alerts.append(alert.rstrip()) return alerts ","from datetime import date import calendar def get_time_index(update): if ""warning"" in update: return 7 if ""pollution"" in update: return 8 elif ""today"" in update: return 0 elif ""this morning"" in update: return 1 elif ""this lunchtime"" in update: return 2 elif ""this afternoon"" in update: return 3 elif ""this evening"" in update: return 4 elif ""tonight"" in update: return 5 elif "" day"" in update: return 6 else: raise Exception(""time not set: {}"".format(update)) def sort_by_time(updates): timed_updates = {} for update in updates: timed_updates[update] = get_time_index(update) for update in sorted(timed_updates, key=timed_updates.get): yield update def fit_into_tweets(updates): dayname = calendar.day_name[date.today().weekday()] alerts = [] alert = dayname + "": "" addToAlert = True i = 1 for update in updates: if (len(alert) + len(update) < 140): alert += update + "" "" addToAlert = True else: alerts.append(alert.rstrip()) i += 1 alert = dayname + "": "" + update + "" "" if addToAlert or len(alerts) < i: alerts.append(alert.rstrip()) return alerts " Fix long description content type,"import codecs from os import path from textwrap import dedent from setuptools import setup here = path.abspath(path.dirname(__file__)) with codecs.open(path.join(here, ""README.rst""), encoding='utf-8') as f: long_description = f.read() setup( name='python-jsonstore', use_scm_version=True, description="""", long_description=long_description, long_description_content_type='text/x-rst', author=""Oliver Bristow"", author_email='github+pypi@oliverbristow.co.uk', license='MIT', classifiers=dedent("""""" Development Status :: 5 - Production/Stable Intended Audience :: Developers License :: OSI Approved :: MIT License Operating System :: OS Independent Programming Language :: Python :: 2 Programming Language :: Python :: 2.7 Programming Language :: Python :: 3 Programming Language :: Python :: 3.3 Programming Language :: Python :: 3.4 Programming Language :: Python :: 3.5 Programming Language :: Python :: 3.6 Programming Language :: Python :: 3.7 Programming Language :: Python :: Implementation :: CPython Programming Language :: Python :: Implementation :: PyPy Topic :: Database Topic :: Software Development """""").strip().split('\n'), keywords='json key value store', url='https://github.com/Code0x58/python-jsonstore/', py_modules=dedent("""""" jsonstore """""").strip().split('\n'), setup_requires=[""setuptools_scm"", ""wheel""], ) ","import codecs from os import path from textwrap import dedent from setuptools import setup here = path.abspath(path.dirname(__file__)) with codecs.open(path.join(here, ""README.rst""), encoding='utf-8') as f: long_description = f.read() setup( name='python-jsonstore', use_scm_version=True, description="""", long_description=long_description, long_description_content_type='text/markdown', author=""Oliver Bristow"", author_email='github+pypi@oliverbristow.co.uk', license='MIT', classifiers=dedent("""""" Development Status :: 5 - Production/Stable Intended Audience :: Developers License :: OSI Approved :: MIT License Operating System :: OS Independent Programming Language :: Python :: 2 Programming Language :: Python :: 2.7 Programming Language :: Python :: 3 Programming Language :: Python :: 3.3 Programming Language :: Python :: 3.4 Programming Language :: Python :: 3.5 Programming Language :: Python :: 3.6 Programming Language :: Python :: 3.7 Programming Language :: Python :: Implementation :: CPython Programming Language :: Python :: Implementation :: PyPy Topic :: Database Topic :: Software Development """""").strip().split('\n'), keywords='json key value store', url='https://github.com/Code0x58/python-jsonstore/', py_modules=dedent("""""" jsonstore """""").strip().split('\n'), setup_requires=[""setuptools_scm"", ""wheel""], ) " "Add simple ""yo"" bot command","import os import json import asyncio from butterfield.utils import at_bot from aiodocker import Docker from aiocore import Service WEB_ROOT = os.environ.get(""MOXIE_WEB_URL"", ""http://localhost:8888"") @asyncio.coroutine def events(bot): docker = Docker() events = docker.events events.saferun() stream = events.listen() while True: el = yield from stream.get() yield from bot.post(""#cron"", ""`{}`"".format(str(el))) @asyncio.coroutine @at_bot def run(bot, message: ""message""): runner = Service.resolve(""moxie.cores.run.RunService"") text = message.get(""text"", """") if text == """": yield from bot.post(message['channel'], ""Invalid request"") cmd, arg = text.split("" "", 1) if cmd == ""run"": job = arg yield from bot.post( message['channel'], ""Doing bringup of {}"".format(job)) try: yield from runner.run(job) except ValueError as e: yield from bot.post( message['channel'], ""Gah, {job} failed - {e}"".format(e=e, job=job) ) return yield from bot.post(message['channel'], ""Job {job} online - {webroot}/container/{job}/"".format( webroot=WEB_ROOT, job=job)) elif cmd == ""yo"": yield from bot.post( message['channel'], ""Yo {}"".format(message['user'])) ","import os import json import asyncio from butterfield.utils import at_bot from aiodocker import Docker from aiocore import Service WEB_ROOT = os.environ.get(""MOXIE_WEB_URL"", ""http://localhost:8888"") @asyncio.coroutine def events(bot): docker = Docker() events = docker.events events.saferun() stream = events.listen() while True: el = yield from stream.get() yield from bot.post(""#cron"", ""`{}`"".format(str(el))) @asyncio.coroutine @at_bot def run(bot, message: ""message""): runner = Service.resolve(""moxie.cores.run.RunService"") text = message.get(""text"", """") if text == """": yield from bot.post(message['channel'], ""Invalid request"") cmd, arg = text.split("" "", 1) if cmd == ""run"": job = arg yield from bot.post( message['channel'], ""Doing bringup of {}"".format(job)) try: yield from runner.run(job) except ValueError as e: yield from bot.post( message['channel'], ""Gah, {job} failed - {e}"".format(e=e, job=job) ) return yield from bot.post(message['channel'], ""Job {job} online - {webroot}/container/{job}/"".format( webroot=WEB_ROOT, job=job)) " Remove uneeded app store modification since there is app emulation.,"<?php /** * @loadSharedFixture * @group 54 */ class SPM_ShopyMind_Test_Lib_ShopymindClient_Callback_Get_Products extends EcomDev_PHPUnit_Test_Case { protected function tearDown() { parent::tearDown(); Mage::unregister('_resource_singleton/catalog/product_flat'); } public function testCanGetRandomProducts() { $products = ShopymindClient_Callback::getProducts('store-1', false, false, true, 1); $this->assertRegExp('#catalog/product/view/id/[1-2]/#', $products[0]['product_link']); } public function testIfAStoreHasNoProductsNothingIsReturned() { $products = ShopymindClient_Callback::getProducts('store-2', false, false, true, 1); $this->assertEmpty($products); } public function testCanGetRandomProductsIfNoStoreIsDefined() { $products = ShopymindClient_Callback::getProducts(null, false, false, true, 1); $this->assertRegExp('#catalog/product/view/id/[1-2]/#', $products[0]['product_link']); } public function testCanGetRandomProductsInSpecificsProductsIds() { $products = ShopymindClient_Callback::getProducts(null, false, array(1), true, 1); $this->assertRegExp('#catalog/product/view/id/1/#', $products[0]['product_link']); } } ","<?php /** * @loadSharedFixture * @group 54 */ class SPM_ShopyMind_Test_Lib_ShopymindClient_Callback_Get_Products extends EcomDev_PHPUnit_Test_Case { protected function tearDown() { parent::tearDown(); Mage::unregister('_resource_singleton/catalog/product_flat'); } public function testCanGetRandomProducts() { Mage::app()->setCurrentStore(1); $products = ShopymindClient_Callback::getProducts('store-1', false, false, true, 1); $this->assertRegExp('#catalog/product/view/id/[1-2]/#', $products[0]['product_link']); Mage::app()->setCurrentStore(0); } public function testIfAStoreHasNoProductsNothingIsReturned() { $products = ShopymindClient_Callback::getProducts('store-2', false, false, true, 1); $this->assertEmpty($products); } public function testCanGetRandomProductsIfNoStoreIsDefined() { $products = ShopymindClient_Callback::getProducts(null, false, false, true, 1); $this->assertRegExp('#catalog/product/view/id/[1-2]/#', $products[0]['product_link']); } public function testCanGetRandomProductsInSpecificsProductsIds() { $products = ShopymindClient_Callback::getProducts(null, false, array(1), true, 1); $this->assertRegExp('#catalog/product/view/id/1/#', $products[0]['product_link']); } } " "Fix check for generator ipc response Since we're actually using an for..of loop it doesn't matter that there's a 'next()' function on the object. What really matters is a function for the iterator symbol.","const { ipcMain } = require('electron'); function isPromise(object) { return object.then && typeof(object.then) === 'function'; } function isGenerator(object) { return object[Symbol.iterator] && typeof(object[Symbol.iterator]) === 'function'; } class IPCHandler { handle(event, funct, binding = this) { const localFunc = funct.bind(binding); ipcMain.on(event, (ev, ...args) => { const localFuncResult = localFunc(...args); if(isPromise(localFuncResult)) { localFuncResult.then((...result) => { ev.sender.send(event, ...result); }); } else if(isGenerator(localFuncResult)) { for(let result of localFuncResult) { ev.sender.send(event, result); } } else { ev.sender.send(event, localFuncResult); } }); } handleSync(event, funct, binding = this) { const localFunc = funct.bind(binding); ipcMain.on(event, (ev, ...args) => { const localFuncResult = localFunc(...args); if(isPromise(localFuncResult)) { localFuncResult.then((result) => { ev.returnValue = result; }); } else { ev.returnValue = localFuncResult; } }); } provide(event, func) { const localFunc = func.bind(this); ipcMain.on(event, localFunc); } } module.exports = IPCHandler; ","const { ipcMain } = require('electron'); function isPromise(object) { return object.then && typeof(object.then) === 'function'; } function isGenerator(object) { return object.next && typeof(object.next) === 'function'; } class IPCHandler { handle(event, funct, binding = this) { const localFunc = funct.bind(binding); ipcMain.on(event, (ev, ...args) => { const localFuncResult = localFunc(...args); if(isPromise(localFuncResult)) { localFuncResult.then((...result) => { ev.sender.send(event, ...result); }); } else if(isGenerator(localFuncResult)) { for(let result of localFuncResult) { ev.sender.send(event, result); } } else { ev.sender.send(event, localFuncResult); } }); } handleSync(event, funct, binding = this) { const localFunc = funct.bind(binding); ipcMain.on(event, (ev, ...args) => { const localFuncResult = localFunc(...args); if(isPromise(localFuncResult)) { localFuncResult.then((result) => { ev.returnValue = result; }); } else { ev.returnValue = localFuncResult; } }); } provide(event, func) { const localFunc = func.bind(this); ipcMain.on(event, localFunc); } } module.exports = IPCHandler; " Rename click handler function so it’s more explicit what it does,"import React from 'react'; import { Link } from 'react-router'; import './Menu.css'; import User from './User'; import language from '../language/language'; const menuLanguage = language.components.menu; let Menu = React.createClass ({ getInitialState() { return { showUser: false }; }, toggleUser(e) { e.preventDefault(e); if (!this.state.showUser) { this.setState({showUser : true}); } else { this.setState({showUser : false}); } }, render() { const { user } = this.props; let userElement; userElement = ( <User user={user} /> ); return ( <div> <ul> <li> <Link to=""recent-tracks"" className=""Menu__item""> {menuLanguage.recentTracks} </Link> </li> <li> <Link to=""top-artists"" className=""Menu__item""> {menuLanguage.topArtists} </Link> </li> <li> <Link className=""Menu__item"" onClick={this.toggleUser}> {menuLanguage.userInfo} </Link> </li> </ul> {this.state.showUser ? userElement : null} </div> ); } }); export default Menu; ","import React from 'react'; import { Link } from 'react-router'; import './Menu.css'; import User from './User'; import language from '../language/language'; const menuLanguage = language.components.menu; let Menu = React.createClass ({ getInitialState() { return { showUser: false }; }, onClick(e) { e.preventDefault(e); if (!this.state.showUser) { this.setState({showUser : true}); } else { this.setState({showUser : false}); } }, render() { const { user } = this.props; let userElement; userElement = ( <User user={user} /> ); return ( <div> <ul> <li> <Link to=""recent-tracks"" className=""Menu__item""> {menuLanguage.recentTracks} </Link> </li> <li> <Link to=""top-artists"" className=""Menu__item""> {menuLanguage.topArtists} </Link> </li> <li> <Link className=""Menu__item"" onClick={this.onClick}> {menuLanguage.userInfo} </Link> </li> </ul> {this.state.showUser ? userElement : null} </div> ); } }); export default Menu; " Hide columns not needed in add locale view,"$(function() { // Show only locales available for the selected project var projectLocales = $('#server').data('project-locales'); $(projectLocales).each(function() { $('.menu').find('.language.' + this).parents('li').addClass('limited').show(); }); $('.menu:visible input[type=search]').trigger(""keyup""); // Request new locale $('.locale .menu li').click(function (e) { if ($('.locale .menu .search-wrapper > a').is('.back')) { e.preventDefault(); var locale = $(this).find('.language').attr('class').split(' ')[1], project = $('#server').data('project'); Pontoon.requestLocale(locale, project); } }); // Switch between available locales and locales to request $('.locale .menu .search-wrapper > a').click(function (e) { e.preventDefault(); var menu = $(this).parents('.menu'); menu.find('.sort .progress, .latest').toggle(); $(this).toggleClass('back') .find('span').toggleClass('fa-plus-square fa-chevron-left'); if ($(this).is('.back')) { menu.find('li').addClass('limited').show(); $(projectLocales).each(function() { menu.find('.language.' + this).parents('li').removeClass('limited').hide(); }); } else { menu.find('li').removeClass('limited').hide(); $(projectLocales).each(function() { menu.find('.language.' + this).parents('li').addClass('limited').show(); }); } $('.menu:visible input[type=search]').trigger(""keyup"").focus(); }); }); ","$(function() { // Show only locales available for the selected project var projectLocales = $('#server').data('project-locales'); $(projectLocales).each(function() { $('.menu').find('.language.' + this).parents('li').addClass('limited').show(); }); $('.menu:visible input[type=search]').trigger(""keyup""); // Request new locale $('.locale .menu li').click(function (e) { if ($('.locale .menu .search-wrapper > a').is('.back')) { e.preventDefault(); var locale = $(this).find('.language').attr('class').split(' ')[1], project = $('#server').data('project'); Pontoon.requestLocale(locale, project); } }); // Switch between available locales and locales to request $('.locale .menu .search-wrapper > a').click(function (e) { e.preventDefault(); var menu = $(this).parents('.menu'); menu.find('.sort span:eq(2)').toggle(); $(this).toggleClass('back') .find('span').toggleClass('fa-plus-square fa-chevron-left'); if ($(this).is('.back')) { menu.find('li').addClass('limited').show(); $(projectLocales).each(function() { menu.find('.language.' + this).parents('li').removeClass('limited').hide(); }); } else { menu.find('li').removeClass('limited').hide(); $(projectLocales).each(function() { menu.find('.language.' + this).parents('li').addClass('limited').show(); }); } $('.menu:visible input[type=search]').trigger(""keyup"").focus(); }); }); " Add function based queries for publications,"const DB = require('./db'); class Boost extends DB { constructor(config) { super(config); this.model = config.model; this.resolveQuery(); } db() { return this.model; } data() { return this.data; } watch() { this.model.changes().then(changes => { changes.each((error, doc) => { if (error) { // console.log(error); } this.incoming(); }); }).error(function(error) { console.log(error); }); } resolveQuery() { let ret; let query = this.query; if (typeof query == 'function') { query = query.bind(this); ret = query(); if (typeof ret.then == 'function') { ret = query; } else { ret = ret.run(); } } else { ret = this.model.filter(this.query).run(); } this.data = ret; } } module.exports = Boost; ","const DB = require('./db'); class Boost extends DB { constructor(config) { super(config); this.model = config.model; } db() { return this.model; } data() { return this.model.filter(this.query).run(); } watch() { this.model.changes().then(changes => { changes.each((error, doc) => { if (error) { // console.log(error); } this.incoming(); // let change_type; // if (doc.isSaved() === false) { // // console.log('document deleted'); // change_type = 'delete'; // } else if (doc.getOldValue() === null) { // // console.log('new document'); // change_type = 'insert'; // } else { // // console.log('document update'); // change_type = 'update'; // } // // // console.log(change_type); // this.socket.emit('update', change_type, doc); }); }).error(function(error) { console.log(error); }); } } module.exports = Boost; " "Update the irclib dependency to version 0.4.8. Add an explicit url in dependency_links for irclib's SourceForge download page. The url currently in PyPI is stale, so the download fails. It looks like the upstream package is now called ""irc"", so investigate porting cobe to that in the future. Fixes #3: ""Depends on outdated irclib?""","#!/usr/bin/env python # Require setuptools. See http://pypi.python.org/pypi/setuptools for # installation instructions, or run the ez_setup script found at # http://peak.telecommunity.com/dist/ez_setup.py from setuptools import setup, find_packages setup( name = ""cobe"", version = ""2.0.2"", author = ""Peter Teichman"", author_email = ""peter@teichman.org"", url = ""http://wiki.github.com/pteichman/cobe/"", description = ""Markov chain based text generator library and chatbot"", packages = [""cobe""], test_suite = ""tests"", setup_requires = [ ""nose==1.1.2"", ""coverage==3.5"" ], install_requires = [ ""PyStemmer==1.2.0"", ""argparse==1.2.1"", ""python-irclib==0.4.8"" ], classifiers = [ ""Development Status :: 5 - Production/Stable"", ""Environment :: Console"", ""Intended Audience :: Developers"", ""Intended Audience :: End Users/Desktop"", ""License :: OSI Approved :: MIT License"", ""Operating System :: OS Independent"", ""Programming Language :: Python"", ""Topic :: Scientific/Engineering :: Artificial Intelligence"" ], entry_points = { ""console_scripts"" : [ ""cobe = cobe.control:main"" ] } ) ","#!/usr/bin/env python # Require setuptools. See http://pypi.python.org/pypi/setuptools for # installation instructions, or run the ez_setup script found at # http://peak.telecommunity.com/dist/ez_setup.py from setuptools import setup, find_packages setup( name = ""cobe"", version = ""2.0.2"", author = ""Peter Teichman"", author_email = ""peter@teichman.org"", url = ""http://wiki.github.com/pteichman/cobe/"", description = ""Markov chain based text generator library and chatbot"", packages = [""cobe""], test_suite = ""tests"", setup_requires = [ ""nose==1.1.2"", ""coverage==3.5"" ], install_requires = [ ""PyStemmer==1.2.0"", ""argparse==1.2.1"", ""python-irclib==0.4.6"" ], classifiers = [ ""Development Status :: 5 - Production/Stable"", ""Environment :: Console"", ""Intended Audience :: Developers"", ""Intended Audience :: End Users/Desktop"", ""License :: OSI Approved :: MIT License"", ""Operating System :: OS Independent"", ""Programming Language :: Python"", ""Topic :: Scientific/Engineering :: Artificial Intelligence"" ], entry_points = { ""console_scripts"" : [ ""cobe = cobe.control:main"" ] } ) " Use exact device pixel ratio no bigger than 3,"(function () { function initTwinklingStars(devicePixelRatio) { particlesJS('stars', { particles: { number: { value: 180, density: { enable: true, value_area: 600 } }, color: { value: '#ffffff' }, shape: { type: 'circle' }, opacity: { value: 1, random: true, anim: { enable: true, speed: 3, opacity_min: 0 } }, size: { value: 1.5 / devicePixelRatio, random: true, anim: { enable: true, speed: 1, size_min: 0.5 / devicePixelRatio, sync: false } }, line_linked: { enable: false }, move: { enable: true, speed: 50, direction: 'none', random: true, straight: true, out_mode: 'bounce' } }, retina_detect: true }); } window.onload = function () { initTwinklingStars(Math.min(window.devicePixelRatio, 3) || 1); document.body.className = ''; } window.onresize = function () { clearTimeout(window.onResizeEnd); window.onResizeEnd = setTimeout(initTwinklingStars, 250); } window.ontouchmove = function () { return false; } window.onorientationchange = function () { document.body.scrollTop = 0; } }()); ","(function () { function initTwinklingStars(devicePixelRatio) { particlesJS('stars', { particles: { number: { value: 180, density: { enable: true, value_area: 600 } }, color: { value: '#ffffff' }, shape: { type: 'circle' }, opacity: { value: 1, random: true, anim: { enable: true, speed: 3, opacity_min: 0 } }, size: { value: 1.5 / devicePixelRatio, random: true, anim: { enable: true, speed: 1, size_min: 0.5 / devicePixelRatio, sync: false } }, line_linked: { enable: false }, move: { enable: true, speed: 50, direction: 'none', random: true, straight: true, out_mode: 'bounce' } }, retina_detect: true }); } window.onload = function () { initTwinklingStars(window.devicePixelRatio / 1.5 || 1); document.body.className = ''; } window.onresize = function () { clearTimeout(window.onResizeEnd); window.onResizeEnd = setTimeout(initTwinklingStars, 250); } window.ontouchmove = function () { return false; } window.onorientationchange = function () { document.body.scrollTop = 0; } }()); " Use 'true' while filtering a boolean as opposed to 'True',"import re from distutils.util import strtobool from django.db.models import BooleanField, FieldDoesNotExist from django.db.models.fields.related import ManyToManyField from rest_framework import filters class JSONAPIFilterBackend(filters.DjangoFilterBackend): def filter_queryset(self, request, queryset, view): filter_class = self.get_filter_class(view, queryset) primary_key = queryset.model._meta.pk.name query_params = {} for param, value in request.query_params.iteritems(): match = re.search(r'^filter\[(\w+)\]$', param) if match: field_name = match.group(1) try: name, extra = field_name.split('__') except ValueError: name = field_name extra = None if name not in view.filter_fields.keys(): return queryset.none() if len(field_name) > 1 and field_name[:2] == 'id': query_params['{0}__{1}'.format(primary_key, extra)] = value if hasattr(queryset.model, field_name)\ and isinstance(getattr(queryset.model, field_name).field, ManyToManyField): value = value.split(',') # Allow 'true' or 'false' as values for boolean fields try: if isinstance(queryset.model._meta.get_field(field_name), BooleanField): value = bool(strtobool(value)) except FieldDoesNotExist: pass query_params[field_name] = value if filter_class: return filter_class(query_params, queryset=queryset).qs return queryset ","import re from django.db.models.fields.related import ManyToManyField from rest_framework import filters class JSONAPIFilterBackend(filters.DjangoFilterBackend): def filter_queryset(self, request, queryset, view): filter_class = self.get_filter_class(view, queryset) primary_key = queryset.model._meta.pk.name query_params = {} for param, value in request.query_params.iteritems(): match = re.search(r'^filter\[(\w+)\]$', param) if match: field_name = match.group(1) try: name, extra = field_name.split('__') except ValueError: name = field_name extra = None if name not in view.filter_fields.keys(): return queryset.none() if len(field_name) > 1 and field_name[:2] == 'id': query_params['{0}__{1}'.format(primary_key, extra)] = value if hasattr(queryset.model, field_name)\ and isinstance(getattr(queryset.model, field_name).field, ManyToManyField): value = value.split(',') query_params[field_name] = value if filter_class: return filter_class(query_params, queryset=queryset).qs return queryset " Add returns to test class properties,"# Licensed under a 3-clause BSD style license - see LICENSE.rst # Tests of NDDataBase from __future__ import (absolute_import, division, print_function, unicode_literals) from ..nddatabase import NDDataBase from ...tests.helper import pytest class MinimalSubclass(NDDataBase): def __init__(self): super(MinimalSubclass, self).__init__() @property def data(self): return None @property def mask(self): return super(MinimalSubclass, self).mask @property def unit(self): return super(MinimalSubclass, self).unit @property def wcs(self): return super(MinimalSubclass, self).wcs @property def meta(self): return super(MinimalSubclass, self).meta class MinimalUncertainty(object): """""" Define the minimum attributes acceptable as an uncertainty object. """""" def __init__(self, value): self._uncertainty = value @property def uncertainty_type(self): return ""totally and completely fake"" def test_nddatabase_subclass(): a = MinimalSubclass() assert a.meta is None assert a.data is None assert a.mask is None assert a.unit is None assert a.wcs is None good_uncertainty = MinimalUncertainty(5) a.uncertainty = good_uncertainty assert a.uncertainty is good_uncertainty bad_uncertainty = 5 with pytest.raises(TypeError): a.uncertainty = bad_uncertainty ","# Licensed under a 3-clause BSD style license - see LICENSE.rst # Tests of NDDataBase from __future__ import (absolute_import, division, print_function, unicode_literals) from ..nddatabase import NDDataBase from ...tests.helper import pytest class MinimalSubclass(NDDataBase): def __init__(self): super(MinimalSubclass, self).__init__() @property def data(self): return None @property def mask(self): super(MinimalSubclass, self).mask @property def unit(self): super(MinimalSubclass, self).unit @property def wcs(self): super(MinimalSubclass, self).wcs @property def meta(self): super(MinimalSubclass, self).meta class MinimalUncertainty(object): """""" Define the minimum attributes acceptable as an uncertainty object. """""" def __init__(self, value): self._uncertainty = value @property def uncertainty_type(self): return ""totally and completely fake"" def test_nddatabase_subclass(): a = MinimalSubclass() assert a.meta is None assert a.data is None assert a.mask is None assert a.unit is None assert a.wcs is None good_uncertainty = MinimalUncertainty(5) a.uncertainty = good_uncertainty assert a.uncertainty is good_uncertainty bad_uncertainty = 5 with pytest.raises(TypeError): a.uncertainty = bad_uncertainty " "Add perma-link to each scheduled maintenance PR #2912 adds scheduled maintenance ID to overview HTML. This patch introduces permanent link and icon image by the ID.","<div class=""timeline schedule""> <div class=""panel panel-default""> <div class=""panel-heading""> <strong>{{ trans('cachet.incidents.scheduled') }}</strong> </div> <div class=""list-group""> @foreach($scheduled_maintenance as $schedule) <div class=""list-group-item"" id=""scheduled-{{ $schedule->id }}""> <strong>{{ $schedule->name }}</strong> <small class=""date""><abbr class=""timeago"" data-toggle=""tooltip"" data-placement=""right"" title=""{{ $schedule->scheduled_at_formatted }}"" data-timeago=""{{ $schedule->scheduled_at_iso }}""></abbr></small> <div class=""pull-right""><a href=""#scheduled-{{ $schedule->id }}""><i class=""ion ion-link""></i></a></div> <div class=""markdown-body""> {!! $schedule->formatted_message !!} </div> @if($schedule->components->count() > 0) <hr> @foreach($schedule->components as $affected_component) <span class=""label label-primary"">{{ $affected_component->component->name }}</span> @endforeach @endif </div> @endforeach </div> </div> </div> ","<div class=""timeline schedule""> <div class=""panel panel-default""> <div class=""panel-heading""> <strong>{{ trans('cachet.incidents.scheduled') }}</strong> </div> <div class=""list-group""> @foreach($scheduled_maintenance as $schedule) <div class=""list-group-item"" id=""scheduled-{{ $schedule->id }}""> <strong>{{ $schedule->name }}</strong> <small class=""date""><abbr class=""timeago"" data-toggle=""tooltip"" data-placement=""right"" title=""{{ $schedule->scheduled_at_formatted }}"" data-timeago=""{{ $schedule->scheduled_at_iso }}""></abbr></small> <div class=""markdown-body""> {!! $schedule->formatted_message !!} </div> @if($schedule->components->count() > 0) <hr> @foreach($schedule->components as $affected_component) <span class=""label label-primary"">{{ $affected_component->component->name }}</span> @endforeach @endif </div> @endforeach </div> </div> </div> " Fix redirect loop when no content,"/** * Main controller for Ghost frontend */ /*global require, module */ var Ghost = require('../../ghost'), api = require('../api'), ghost = new Ghost(), frontendControllers; frontendControllers = { 'homepage': function (req, res) { // Parse the page number var pageParam = req.params.page !== undefined ? parseInt(req.params.page, 10) : 1; // No negative pages if (pageParam < 1) { return res.redirect(""/page/1/""); } api.posts.browse({page: pageParam}).then(function (page) { var maxPage = page.pages; // A bit of a hack for situations with no content. if (maxPage === 0) { maxPage = 1; page.pages = 1; } // If page is greater than number of pages we have, redirect to last page if (pageParam > maxPage) { return res.redirect(""/page/"" + maxPage + ""/""); } // Render the page of posts ghost.doFilter('prePostsRender', page.posts, function (posts) { res.render('index', {posts: posts, pagination: {page: page.page, prev: page.prev, next: page.next, limit: page.limit, total: page.total, pages: page.pages}}); }); }); }, 'single': function (req, res) { api.posts.read({'slug': req.params.slug}).then(function (post) { ghost.doFilter('prePostsRender', post.toJSON(), function (post) { res.render('post', {post: post}); }); }); } }; module.exports = frontendControllers;","/** * Main controller for Ghost frontend */ /*global require, module */ var Ghost = require('../../ghost'), api = require('../api'), ghost = new Ghost(), frontendControllers; frontendControllers = { 'homepage': function (req, res) { // Parse the page number var pageParam = req.params.page !== undefined ? parseInt(req.params.page, 10) : 1; // No negative pages if (pageParam < 1) { return res.redirect(""/page/1/""); } api.posts.browse({page: pageParam}).then(function (page) { // If page is greater than number of pages we have, redirect to last page if (pageParam > page.pages) { return res.redirect(""/page/"" + (page.pages) + ""/""); } // Render the page of posts ghost.doFilter('prePostsRender', page.posts, function (posts) { res.render('index', {posts: posts, pagination: {page: page.page, prev: page.prev, next: page.next, limit: page.limit, total: page.total, pages: page.pages}}); }); }); }, 'single': function (req, res) { api.posts.read({'slug': req.params.slug}).then(function (post) { ghost.doFilter('prePostsRender', post.toJSON(), function (post) { res.render('post', {post: post}); }); }); } }; module.exports = frontendControllers;" Use full path of meteor-async-await module to register plugin.,"exports.getDefaults = function getDefaults(features) { var options = { compact: false, sourceMap: ""inline"", externalHelpers: true, ast: false, // ""Loose"" mode gets us faster and more IE-compatible transpilations of: // classes, computed properties, modules, for-of, and template literals. // Basically all the transformers that support ""loose"". // http://babeljs.io/docs/usage/loose/ loose: [""all""], whitelist: [ ""es3.propertyLiterals"", ""es3.memberExpressionLiterals"", ""es6.arrowFunctions"", ""es6.templateLiterals"", ""es6.classes"", ""es6.constants"", ""es6.blockScoping"", ""es6.properties.shorthand"", ""es6.properties.computed"", ""es6.parameters"", ""es6.spread"", ""es7.objectRestSpread"", ""es6.destructuring"", ""es7.trailingFunctionCommas"", ""flow"" ] }; if (features) { if (features.meteorAsyncAwait) { var plugins = options.plugins || []; plugins.push(require.resolve(""meteor-async-await"")); options.plugins = plugins; options.whitelist.push(""es7.asyncFunctions""); } if (features.modules) { options.loose.push(""es6.modules""); options.whitelist.push(""es6.modules""); } } return options; }; ","exports.getDefaults = function getDefaults(features) { var options = { compact: false, sourceMap: ""inline"", externalHelpers: true, ast: false, // ""Loose"" mode gets us faster and more IE-compatible transpilations of: // classes, computed properties, modules, for-of, and template literals. // Basically all the transformers that support ""loose"". // http://babeljs.io/docs/usage/loose/ loose: [""all""], whitelist: [ ""es3.propertyLiterals"", ""es3.memberExpressionLiterals"", ""es6.arrowFunctions"", ""es6.templateLiterals"", ""es6.classes"", ""es6.constants"", ""es6.blockScoping"", ""es6.properties.shorthand"", ""es6.properties.computed"", ""es6.parameters"", ""es6.spread"", ""es7.objectRestSpread"", ""es6.destructuring"", ""es7.trailingFunctionCommas"", ""flow"" ] }; if (features) { if (features.meteorAsyncAwait) { var plugins = options.plugins || []; plugins.push(""meteor-async-await""); options.plugins = plugins; options.whitelist.push(""es7.asyncFunctions""); } if (features.modules) { options.loose.push(""es6.modules""); options.whitelist.push(""es6.modules""); } } return options; }; " Add test for default allowHeaders,"var request = require('supertest'); var express = require('express'); var ach = require('../index.js'); describe(""using ach"", function() { describe(""with defaults"", function() { var app = express(); app.use(ach()); app.get('/', function(req, res) { res.send(200); }); describe('requests with no Origin', function() { it('should not receive Access-Control headers', function(done) { request(app) .get('/') .expect(200) .end(function(err, res) { if (err) throw err; Object.keys(res.header).forEach(function(header) { if (/^access\-control/.test(header)) { throw new Error ( header + ' header present for originless request'); } }); done(); }); }); }); describe('requests with Origin set', function() { it('should receive a wildcard Access-Control-Allow-Origin', function(done) { request(app) .get('/') .set('Origin', 'http://example.com') .expect(200) .expect('Access-Control-Allow-Origin', '*') .end(function(err, res) { if (err) throw err; done(); }); }); }); describe('requests with Origin set', function() { it('should receive the default Access-Control-Allow-Headers', function(done) { request(app) .get('/') .set('Origin', 'http://example.com') .expect(200) .expect('Access-Control-Allow-Headers', 'X-Requested-With') .end(function(err, res) { if (err) throw err; done(); }); }); }); }); }); ","var request = require('supertest'); var express = require('express'); var ach = require('../index.js'); describe(""using ach"", function() { describe(""with defaults"", function() { var app = express(); app.use(ach()); app.get('/', function(req, res) { res.send(200); }); describe('requests with no Origin', function() { it('should not receive Access-Control headers', function(done) { request(app) .get('/') .expect(200) .end(function(err, res) { if (err) throw err; Object.keys(res.header).forEach(function(header) { if (/^access\-control/.test(header)) { throw new Error ( header + ' header present for originless request'); } }); done(); }); }); }); describe('requests with Origin set', function() { it('should receive a wildcard Access-Control-Allow-Origin', function(done) { request(app) .get('/') .set('Origin','http://example.com') .expect(200) .expect('Access-Control-Allow-Origin','*') .end(function(err, res) { if (err) throw err; done(); }); }); }); }); }); " Fix object notation in service,"angular.module('atlasApp').service('MapsService', function( $scope, $http, LocationProvider, BusInfoProvider ) { return { /** * Initializes the Google Maps canvas */ initMap: function () { console.log('Initializing'); var mapOptions = { zoom: 15, center: $scope.mapCenter, mapTypeId: google.maps.MapTypeId.ROADMAP, disableDefaultUI: true, }; var mapCanvas = document.getElementById('map-canvas'); $scope.map = new google.maps.Map( mapCanvas, mapOptions ); $scope.locationProvider = new LocationProvider($scope.map); // Instantiating the Bus Info Provider with a map. $scope.busInfoProvider = new BusInfoProvider($scope.map); }; plotMarker: function(lat, lng, name) { var position = new google.maps.LatLng(lat, lng); $scope.marker = new google.maps.Marker({ position: position, map: $scope.map, title: name }); $scope.map.setCenter(position); }; /** * Resizes the view to fit within the bounds of the screen. */ resizeView: function() { var newHeight = $(window).height() - $('div.navbar').height() - 90 - $('#toolbar').height(); $('#map-canvas').css({height: newHeight}); }; clearMap: function() {}; }; });","angular.module('atlasApp').service('MapsService', function( $scope, $http, LocationProvider, BusInfoProvider ) { return { /** * Initializes the Google Maps canvas */ this.initMap = function () { console.log('Initializing'); var mapOptions = { zoom: 15, center: $scope.mapCenter, mapTypeId: google.maps.MapTypeId.ROADMAP, disableDefaultUI: true, }; var mapCanvas = document.getElementById('map-canvas'); $scope.map = new google.maps.Map( mapCanvas, mapOptions ); $scope.locationProvider = new LocationProvider($scope.map); // Instantiating the Bus Info Provider with a map. $scope.busInfoProvider = new BusInfoProvider($scope.map); }; this.plotMarker = function(lat, lng, name) { var position = new google.maps.LatLng(lat, lng); $scope.marker = new google.maps.Marker({ position: position, map: $scope.map, title: name }); $scope.map.setCenter(position); }; /** * Resizes the view to fit within the bounds of the screen. */ this.resizeView = function() { var newHeight = $(window).height() - $('div.navbar').height() - 90 - $('#toolbar').height(); $('#map-canvas').css({height: newHeight}); }; this.clearMap = function() {}; }; });" Fix missing username in initial login session,"/* eslint-disable no-param-reassign */ import Vue from 'vue'; export default { namespaced: true, state: { username: null, }, mutations: { setUsername(state, username) { state.username = username; }, }, actions: { status({ commit }) { return Vue.http.get('api/session').then( (response) => { commit('setUsername', (response.body && response.body.username) ? response.body.username : null); return response.status; }, (response) => { commit('setUsername', null); return response.status; }, ); }, login({ commit }, { username, password }) { return Vue.http.post('api/session', { username, password }).then( (response) => { commit('setUsername', response.body.username); return true; }, () => false, ); }, logout({ commit }) { return Vue.http.delete('api/session').then( () => { commit('setUsername', null); return true; }, () => false, ); }, }, }; ","/* eslint-disable no-param-reassign */ import Vue from 'vue'; export default { namespaced: true, state: { username: null, }, mutations: { setUsername(state, username) { state.username = username; }, }, actions: { status({ commit }) { return Vue.http.get('api/session').then( (response) => { commit('setUsername', (response.body && response.body.username) ? response.body.username : null); return response.status; }, (response) => { commit('setUsername', null); return response.status; }, ); }, login({ commit }, { username, password }) { return Vue.http.post('api/session', { username, password }).then( (response) => { commit('setUsername', response.username); return true; }, () => false, ); }, logout({ commit }) { return Vue.http.delete('api/session').then( () => { commit('setUsername', null); return true; }, () => false, ); }, }, }; " Fix type hint of connection interface,"<?php namespace BinSoul\Net\Mqtt; /** * Represents the connection of a MQTT client. */ interface Connection { /** * @return int */ public function getProtocol(); /** * @return string */ public function getClientID(); /** * @return bool */ public function isCleanSession(); /** * @return string */ public function getUsername(); /** * @return string */ public function getPassword(); /** * @return Message|null */ public function getWill(); /** * @return int */ public function getKeepAlive(); /** * Returns a new connection with the given protocol. * * @param int $protocol * * @return self */ public function withProtocol($protocol); /** * Returns a new connection with the given client id. * * @param string $clientID * * @return self */ public function withClientID($clientID); /** * Returns a new connection with the given credentials. * * @param string $username * @param string $password * * @return self */ public function withCredentials($username, $password); /** * Returns a new connection with the given will. * * @param Message $will * * @return self */ public function withWill(Message $will); /** * Returns a new connection with the given keep alive timeout. * * @param int $timeout * * @return self */ public function withKeepAlive($timeout); } ","<?php namespace BinSoul\Net\Mqtt; /** * Represents the connection of a MQTT client. */ interface Connection { /** * @return int */ public function getProtocol(); /** * @return int */ public function getClientID(); /** * @return bool */ public function isCleanSession(); /** * @return string */ public function getUsername(); /** * @return string */ public function getPassword(); /** * @return Message|null */ public function getWill(); /** * @return int */ public function getKeepAlive(); /** * Returns a new connection with the given protocol. * * @param int $protocol * * @return self */ public function withProtocol($protocol); /** * Returns a new connection with the given client id. * * @param string $clientID * * @return self */ public function withClientID($clientID); /** * Returns a new connection with the given credentials. * * @param string $username * @param string $password * * @return self */ public function withCredentials($username, $password); /** * Returns a new connection with the given will. * * @param Message $will * * @return self */ public function withWill(Message $will); /** * Returns a new connection with the given keep alive timeout. * * @param int $timeout * * @return self */ public function withKeepAlive($timeout); } " Update to use my own client_id,"spade.require('sproutcore'); spade.require('sproutcore-touch'); // Create application namespace var SproutGram = SC.Application.create(); SproutGram.PhotoModel = SC.Object.extend({ standard_res: null, username: null }); SproutGram.photosController = SC.ArrayProxy.create({ content: [] }); SproutGram.PhotosView = SC.CollectionView.extend({ contentBinding: 'SproutGram.photosController' }); $(document).ready(function() { $.ajax({ url:'https://api.instagram.com/v1/media/popular?client_id=92cf548d90fa4b98b4a5cdc5f9f70999', dataType: ""jsonp"", success:function(response){ var images = response.data; for (var i=0, l=25; i<l; i++) { var image = images[i]; var userComments = []; image.comments.data.forEach(function(comment) { userComments.push({ text: comment.text, commenter: comment.from.username }) }); SproutGram.photosController.pushObject(SproutGram.PhotoModel.create({ standard_res: image.images.standard_resolution.url, username: image.user.username, comments: userComments, title: (image.caption)? image.caption.text : ""No title"", itemIndex: i })); } } }) }); ","spade.require('sproutcore'); spade.require('sproutcore-touch'); // Create application namespace var SproutGram = SC.Application.create(); SproutGram.PhotoModel = SC.Object.extend({ standard_res: null, username: null }); SproutGram.photosController = SC.ArrayProxy.create({ content: [] }); SproutGram.PhotosView = SC.CollectionView.extend({ contentBinding: 'SproutGram.photosController' }); $(document).ready(function() { $.ajax({ url:'https://api.instagram.com/v1/media/popular?access_token=6668562.f59def8.29acda9c153b49448c0948359f774626', dataType: ""jsonp"", success:function(response){ var images = response.data; for (var i=0, l=25; i<l; i++) { var image = images[i]; var userComments = []; image.comments.data.forEach(function(comment) { userComments.push({ text: comment.text, commenter: comment.from.username }) }); SproutGram.photosController.pushObject(SproutGram.PhotoModel.create({ standard_res: image.images.standard_resolution.url, username: image.user.username, comments: userComments, title: (image.caption)? image.caption.text : ""No title"", itemIndex: i })); } } }) }); " "Set default invalid/unset line to -1, to reduce confusion with 0 being interpreted as the first line.","package io.collap.bryg.compiler.ast; import io.collap.bryg.compiler.context.Context; import java.io.PrintStream; public abstract class Node { protected Context context; /** * A line of -1 indicates that the line has not been set! */ private int line = -1; protected Node (Context context) { this.context = context; } /** * IMPORTANT NOTE: All (named) variables *must* be resolved in the Node constructors. Using any ""current"" Scope in the `compile` * method yields undefined behaviour! The root scope can be used to allocate space for anonymous temporal variables. */ public abstract void compile (); public void print (PrintStream out, int depth) { /* Print line number with indent. */ String lineStr; if (line > 0) { lineStr = line + "": ""; }else { lineStr = "" ""; } for (int i = lineStr.length (); i < 7; ++i) { out.print (' '); } out.print (lineStr); /* Print depth node indent. */ for (int i = 0; i < depth; ++i) { out.print ("" ""); } /* Print class name. */ out.println (getClass ().getSimpleName ()); } public int getLine () { return line; } protected void setLine (int line) { this.line = line; } } ","package io.collap.bryg.compiler.ast; import io.collap.bryg.compiler.context.Context; import java.io.PrintStream; public abstract class Node { protected Context context; private int line = 0; protected Node (Context context) { this.context = context; } /** * IMPORTANT NOTE: All (named) variables *must* be resolved in the Node constructors. Using any ""current"" Scope in the `compile` * method yields undefined behaviour! The root scope can be used to allocate space for anonymous temporal variables. */ public abstract void compile (); public void print (PrintStream out, int depth) { /* Print line number with indent. */ String lineStr; if (line > 0) { lineStr = line + "": ""; }else { lineStr = "" ""; } for (int i = lineStr.length (); i < 7; ++i) { out.print (' '); } out.print (lineStr); /* Print depth node indent. */ for (int i = 0; i < depth; ++i) { out.print ("" ""); } /* Print class name. */ out.println (getClass ().getSimpleName ()); } public int getLine () { return line; } protected void setLine (int line) { this.line = line; } } " BLD: Use more sensible versioning towards first release,"import os import subprocess from distutils.core import setup try: if os.path.exists("".git""): s = subprocess.Popen([""git"", ""rev-parse"", ""HEAD""], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out = s.communicate()[0] GIT_REVISION = out.strip() else: GIT_REVISION = ""unknown"" except WindowsError: GIT_REVISION = ""unknown"" FULL_VERSION = '0.1.0-dev' if ""dev"" in FULL_VERSION: RELEASED = False VERSION = FULL_VERSION + '-' + GIT_REVISION[:7] else: RELEASED = True VERSION = FULL_VERSION def generate_version_py(filename): cnt = """"""\ # This file was autogenerated version = '%s' git_revision = '%s' """""" cnt = cnt % (VERSION, GIT_REVISION) f = open(filename, ""w"") try: f.write(cnt) finally: f.close() if __name__ == '__main__': generate_version_py(""sahgutils/__dev_version.py"") setup( name='SAHGutils', version=VERSION, author='Scott Sinclair', author_email='scott.sinclair.za@gmail.com', packages=['sahgutils', 'sahgutils.io'], license='LICENSE.txt', description='Useful tools for data analysis and plots.', long_description=open('README.txt').read(), ) ","import os import subprocess from distutils.core import setup try: if os.path.exists("".git""): s = subprocess.Popen([""git"", ""rev-parse"", ""HEAD""], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out = s.communicate()[0] GIT_REVISION = out.strip() else: GIT_REVISION = ""unknown"" except WindowsError: GIT_REVISION = ""unknown"" FULL_VERSION = '0.0.1-dev' if ""dev"" in FULL_VERSION: RELEASED = False VERSION = FULL_VERSION + '-' + GIT_REVISION[:7] else: RELEASED = True VERSION = FULL_VERSION def generate_version_py(filename): cnt = """"""\ # This file was autogenerated version = '%s' git_revision = '%s' """""" cnt = cnt % (VERSION, GIT_REVISION) f = open(filename, ""w"") try: f.write(cnt) finally: f.close() if __name__ == '__main__': generate_version_py(""sahgutils/__dev_version.py"") setup( name='SAHGutils', version=VERSION, author='Scott Sinclair', author_email='scott.sinclair.za@gmail.com', packages=['sahgutils', 'sahgutils.io'], license='LICENSE.txt', description='Useful tools for data analysis and plots.', long_description=open('README.txt').read(), ) " Remove underscore _ from private members (was old Pear coding conventions for PHP4+) + update phpdoc type names,"<?php /** * @title Entity Class * * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2013-2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Framework / Mvc / Model / Engine * @version 1.0 */ namespace PH7\Framework\Mvc\Model\Engine; defined('PH7') or exit('Restricted access'); abstract class Entity { /** * @var int */ private $iId; /** * Get the primary key. * * @return int */ public function getKeyId() { $this->checkKeyId(); return $this->iId; } /** * Set the primary key. * * @param int $iId * * @return void */ public function setKeyId($iId) { $this->iId = (int)$iId; } /** * Check if the $_iId attribute is not empty, otherwise we set the last insert ID. * * @see Db::lastInsertId() * * @return void */ protected function checkKeyId() { if (empty($this->iId)) { $this->setKeyId(Db::getInstance()->lastInsertId()); } } } ","<?php /** * @title Entity Class * * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2013-2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Framework / Mvc / Model / Engine * @version 1.0 */ namespace PH7\Framework\Mvc\Model\Engine; defined('PH7') or exit('Restricted access'); abstract class Entity { /** * @var integer */ private $_iId; /** * Get the primary key. * * @return integer */ public function getKeyId() { $this->checkKeyId(); return $this->_iId; } /** * Set the primary key. * * @param integer $iId * * @return void */ public function setKeyId($iId) { $this->_iId = (int)$iId; } /** * Check if the $_iId attribute is not empty, otherwise we set the last insert ID. * * @see Db::lastInsertId() * * @return void */ protected function checkKeyId() { if (empty($this->_iId)) { $this->setKeyId(Db::getInstance()->lastInsertId()); } } } " "fedimg: Fix the script function args Signed-off-by: Sayan Chowdhury <5f0367a2b3b757615b57f51d912cf16f2c0ad827@gmail.com>","#!/bin/env python # -*- coding: utf8 -*- """""" Triggers an upload process with the specified raw.xz URL. """""" import argparse import logging import logging.config import multiprocessing.pool import fedmsg.config import fedimg.uploader logging.config.dictConfig(fedmsg.config.load_config()['logging']) log = logging.getLogger('fedmsg') def trigger_upload(url, compose_id, push_notifications): upload_pool = multiprocessing.pool.ThreadPool(processes=4) fedimg.uploader.upload(upload_pool, [url], compose_id=compose_id, push_notifications=push_notifications) def get_args(): parser = argparse.ArgumentParser( description=""Trigger a manual upload process with the "" ""specified raw.xz URL"") parser.add_argument( ""-u"", ""--url"", type=str, help="".raw.xz URL"", required=True) parser.add_argument( ""-c"", ""--compose-id"", type=str, help=""compose id of the .raw.xz file"", required=True) parser.add_argument( ""-p"", ""--push-notifications"", help=""Bool to check if we need to push fedmsg notifications"", action=""store_true"", required=False) args = parser.parse_args() return args.url, args.compose_id, args.push_notifications def main(): url, compose_id, push_notifications = get_args() trigger_upload(url, compose_id, push_notifications) if __name__ == '__main__': main() ","#!/bin/env python # -*- coding: utf8 -*- """""" Triggers an upload process with the specified raw.xz URL. """""" import argparse import logging import logging.config import multiprocessing.pool import fedmsg.config import fedimg.uploader logging.config.dictConfig(fedmsg.config.load_config()['logging']) log = logging.getLogger('fedmsg') def trigger_upload(compose_id, url, push_notifications): upload_pool = multiprocessing.pool.ThreadPool(processes=4) fedimg.uploader.upload(upload_pool, [url], compose_id=compose_id, push_notifications=push_notifications) def get_args(): parser = argparse.ArgumentParser( description=""Trigger a manual upload process with the "" ""specified raw.xz URL"") parser.add_argument( ""-u"", ""--url"", type=str, help="".raw.xz URL"", required=True) parser.add_argument( ""-c"", ""--compose-id"", type=str, help=""compose id of the .raw.xz file"", required=True) parser.add_argument( ""-p"", ""--push-notifications"", help=""Bool to check if we need to push fedmsg notifications"", action=""store_true"", required=False) args = parser.parse_args() return args.url, args.compose_id, args.push_notifications def main(): url, compose_id, push_notifications = get_args() trigger_upload(url, compose_id, push_notifications) if __name__ == '__main__': main() " Comment out javaValidateObj on phone number,"/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ package: 'foam.nanos.auth', name: 'Phone', documentation: 'Phone number information.', messages: [ { name: 'INVALID_NUMBER', message: 'Invalid phone number.' } ], constants: [ { name: 'PHONE_REGEX', factory: function() { return /([+]?\d{1,2}[\.\-\s]?)?(\d{3}[.-]?){2}\d{4}/g; } } ], properties: [ { class: 'PhoneNumber', name: 'number', label: '', required: true, validateObj: function (number) { if ( ! this.PHONE_REGEX.test(number) ) { return this.INVALID_NUMBER; } }, preSet: function(o, n) { return n.replace(/[- )(]/g, ''); }, // javaValidateObj: ` // String number = ((Phone) obj).getNumber(); // if ( ! Phone.PHONE_REGEX.matcher(number).matches() ) { // throw new IllegalStateException(Phone.INVALID_NUMBER); // } // ` }, { class: 'Boolean', name: 'verified', permissionRequired: true } ] }); ","/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ package: 'foam.nanos.auth', name: 'Phone', documentation: 'Phone number information.', messages: [ { name: 'INVALID_NUMBER', message: 'Invalid phone number.' } ], constants: [ { name: 'PHONE_REGEX', factory: function() { return /([+]?\d{1,2}[\.\-\s]?)?(\d{3}[.-]?){2}\d{4}/g; } } ], properties: [ { class: 'PhoneNumber', name: 'number', label: '', required: true, validateObj: function (number) { if ( ! this.PHONE_REGEX.test(number) ) { return this.INVALID_NUMBER; } }, preSet: function(o, n) { return n.replace(/[- )(]/g, ''); }, javaValidateObj: ` String number = ((Phone) obj).getNumber(); if ( ! Phone.PHONE_REGEX.matcher(number).matches() ) { throw new IllegalStateException(Phone.INVALID_NUMBER); } ` }, { class: 'Boolean', name: 'verified', permissionRequired: true } ] }); " "Change onAnimating/ed to individual ref Also switch zIndex to elevation on android because there’s nasty bug, https://github.com/gitim/react-native-sortable-list/issues/2. Only showed up when android back through shared elements to shared elements (changed grid to go to grid instead of details)","import React from 'react'; import {StyleSheet, Text, View, Platform} from 'react-native'; import {SharedElementMotion} from 'navigation-react-native'; export default (props) => ( <SharedElementMotion elementStyle={(name, data) => data} style={styles.motion} onAnimating={(name, ref) => {ref.setNativeProps({style:{opacity: 0}})}} onAnimated={(name, ref) => {ref.setNativeProps({style:{opacity: 1}})}} {...props}> {({x, y, w, h, fontSize, fontColor}, name, {color}) => ( !name.startsWith('text') ? <View style={{ position: 'absolute', left: x, top: y, width: w, height: h, backgroundColor: color, }}> </View> : <Text style={{ position: 'absolute', left: x, top: y, width: w, height: h, fontSize, textAlign: 'center', fontWeight: 'bold', color: fontColor, ...Platform.select({ ios: { zIndex: 1, }, android: { elevation: 1, }, }), }}> {color} </Text> )} </SharedElementMotion> ); const styles = StyleSheet.create({ motion: { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, backgroundColor: 'transparent', }, }); ","import React from 'react'; import {StyleSheet, Text, View} from 'react-native'; import {SharedElementMotion} from 'navigation-react-native'; export default (props) => ( <SharedElementMotion elementStyle={(name, data) => data} style={styles.motion} onAnimating={(name, oldRef, mountedRef, oldData, mountedData) => { mountedData.hide && mountedRef.setNativeProps({style:{opacity: 0}}) }} onAnimated={(name, oldRef, mountedRef) => {mountedRef.setNativeProps({style:{opacity: 1}})}} {...props}> {({x, y, w, h, fontSize, fontColor}, name, {color}) => ( !name.startsWith('text') ? <View style={{ position: 'absolute', left: x, top: y, width: w, height: h, backgroundColor: color, }}> </View> : <Text style={{ position: 'absolute', left: x, top: y, width: w, height: h, fontSize, textAlign: 'center', fontWeight: 'bold', color: fontColor, zIndex: 1, }}> {color} </Text> )} </SharedElementMotion> ); const styles = StyleSheet.create({ motion: { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, backgroundColor: 'transparent', }, }); " Fix the bug : the running of two processes are not synchronous,"package cn.six.uav.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; /** * Created by songzhw on 2016/3/10. */ public class CommandRunner { private List<String> outputs; public int run(List<String> cmds) throws Exception { outputs = new ArrayList<>(); ProcessBuilder procBuilder = new ProcessBuilder(cmds) .redirectErrorStream(true); final Process proc = procBuilder.start(); new Thread(new Runnable() { @Override public void run() { String line; outputs.clear(); try { InputStream is = proc.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); while( (line = reader.readLine()) != null){ outputs.add(line); } for(String aline : outputs){ System.out.println(""szw line = ""+aline); } } catch (IOException e) { e.printStackTrace(); } } }) .start(); return proc.waitFor(); } } ","package cn.six.uav.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; /** * Created by songzhw on 2016/3/10. */ public class CommandRunner { private List<String> outputs; public void run(List<String> cmds) throws Exception { outputs = new ArrayList<>(); ProcessBuilder procBuilder = new ProcessBuilder(cmds) .redirectErrorStream(true); final Process proc = procBuilder.start(); new Thread(new Runnable() { @Override public void run() { String line; outputs.clear(); try { InputStream is = proc.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); while( (line = reader.readLine()) != null){ outputs.add(line); } for(String aline : outputs){ System.out.println(""szw line = ""+aline); } } catch (IOException e) { e.printStackTrace(); } } }) .start(); } } " Tweak difficulty - adjust drink + food decrements,"export default { gameWidth: 1080, gameHeight: 1613, images: { 'background-game': './assets/images/background-game.png', 'background-landing': './assets/images/background-landing.png', 'background-face': './assets/images/ui/background-face.png', 'background-game-over': './assets/images/ui/background-face-game-over.png', 'score-bar': './assets/images/ui/score-bar.png', frame: './assets/images/ui/frame.png', 'food-bar': './assets/images/ui/food-bar.png', 'drinks-bar': './assets/images/ui/drinks-bar.png', 'black-background': './assets/images/ui/black-background.png', spit: './assets/images/player/spit.png' }, rules: { drinkDecrementPerTimeUnit: 2, drinkDecrementTimeMilliSeconds: 500, drinkMinimumAmount: -250, drinkMaximumAmount: 250, foodDecrementPerMove: 4, foodMinimumAmount: -250, foodMaximumAmount: 250, playerInitialMoveSpeed: 500, playerMaxDragMultiplier: 0.4, playerYPosition: 860, minimumSpawnTime: 1200, maximumSpawnTime: 2500, }, gravity: 400, player: { mouthOffset: 180 } }; ","export default { gameWidth: 1080, gameHeight: 1613, images: { 'background-game': './assets/images/background-game.png', 'background-landing': './assets/images/background-landing.png', 'background-face': './assets/images/ui/background-face.png', 'background-game-over': './assets/images/ui/background-face-game-over.png', 'score-bar': './assets/images/ui/score-bar.png', frame: './assets/images/ui/frame.png', 'food-bar': './assets/images/ui/food-bar.png', 'drinks-bar': './assets/images/ui/drinks-bar.png', 'black-background': './assets/images/ui/black-background.png', spit: './assets/images/player/spit.png' }, rules: { drinkDecrementPerTimeUnit: 4, drinkDecrementTimeMilliSeconds: 1000, drinkMinimumAmount: -250, drinkMaximumAmount: 250, foodDecrementPerMove: 2, foodMinimumAmount: -250, foodMaximumAmount: 250, playerInitialMoveSpeed: 500, playerMaxDragMultiplier: 0.4, playerYPosition: 860, minimumSpawnTime: 1200, maximumSpawnTime: 2500, }, gravity: 400, player: { mouthOffset: 180 } }; " Make sure that a filetime error doesn't crash the site,"<?php namespace Common\Core\Header; use DateTimeImmutable; final class Asset { /** @var string */ private $file; /** @var Priority */ private $priority; /** @var bool */ private $addTimestamp; /** @var DateTimeImmutable */ private $createdOn; public function __construct(string $file, bool $addTimestamp = false, Priority $priority = null) { $this->file = $file; $this->addTimestamp = $addTimestamp; $this->priority = $priority ?? Priority::standard(); $this->createdOn = new DateTimeImmutable(); } public function compare(Asset $asset): int { $comparison = $this->priority->compare($asset->priority); if ($comparison === 0) { $comparison = $this->createdOn <=> $asset->createdOn; } return $comparison; } public function getFile(): string { return $this->file; } public function getPriority(): Priority { return $this->priority; } public function forCacheUrl(string $cacheUrl): self { $cacheAsset = clone $this; $cacheAsset->file = $cacheUrl; return $cacheAsset; } public function __toString(): string { if (!$this->addTimestamp) { return $this->file; } // check if we need to use a ? or & $separator = mb_strpos($this->file, '?') === false ? '?' : '&'; return $this->file . $separator . 'm=' . @filemtime(__DIR__ . '/../../../../' . $this->file); } } ","<?php namespace Common\Core\Header; use DateTimeImmutable; final class Asset { /** @var string */ private $file; /** @var Priority */ private $priority; /** @var bool */ private $addTimestamp; /** @var DateTimeImmutable */ private $createdOn; public function __construct(string $file, bool $addTimestamp = false, Priority $priority = null) { $this->file = $file; $this->addTimestamp = $addTimestamp; $this->priority = $priority ?? Priority::standard(); $this->createdOn = new DateTimeImmutable(); } public function compare(Asset $asset): int { $comparison = $this->priority->compare($asset->priority); if ($comparison === 0) { $comparison = $this->createdOn <=> $asset->createdOn; } return $comparison; } public function getFile(): string { return $this->file; } public function getPriority(): Priority { return $this->priority; } public function forCacheUrl(string $cacheUrl): self { $cacheAsset = clone $this; $cacheAsset->file = $cacheUrl; return $cacheAsset; } public function __toString(): string { if (!$this->addTimestamp) { return $this->file; } // check if we need to use a ? or & $separator = mb_strpos($this->file, '?') === false ? '?' : '&'; return $this->file . $separator . 'm=' . filemtime(__DIR__ . '/../../../../' . $this->file); } } " Unify strings in Go with variants,"/* Language: Go Author: Stephan Kountso aka StepLg <steplg@gmail.com> Contributors: Evgeny Stepanischev <imbolk@gmail.com> Description: Google go language (golang). For info about language see http://golang.org/ Category: system */ function(hljs) { var GO_KEYWORDS = { keyword: 'break default func interface select case map struct chan else goto package switch ' + 'const fallthrough if range type continue for import return var go defer ' + 'bool byte complex64 complex128 float32 float64 int8 int16 int32 int64 string uint8 ' + 'uint16 uint32 uint64 int uint uintptr rune', literal: 'true false iota nil', built_in: 'append cap close complex copy imag len make new panic print println real recover delete' }; return { aliases: ['golang'], keywords: GO_KEYWORDS, illegal: '</', contains: [ hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE, { className: 'string', variants: [ hljs.QUOTE_STRING_MODE, {begin: '\'', end: '[^\\\\]\''}, {begin: '`', end: '`'}, ] }, { className: 'number', variants: [ {begin: hljs.C_NUMBER_RE + '[dflsi]', relevance: 1}, hljs.C_NUMBER_MODE ] }, { begin: /:=/ // relevance booster } ] }; } ","/* Language: Go Author: Stephan Kountso aka StepLg <steplg@gmail.com> Contributors: Evgeny Stepanischev <imbolk@gmail.com> Description: Google go language (golang). For info about language see http://golang.org/ Category: system */ function(hljs) { var GO_KEYWORDS = { keyword: 'break default func interface select case map struct chan else goto package switch ' + 'const fallthrough if range type continue for import return var go defer ' + 'bool byte complex64 complex128 float32 float64 int8 int16 int32 int64 string uint8 ' + 'uint16 uint32 uint64 int uint uintptr rune', literal: 'true false iota nil', built_in: 'append cap close complex copy imag len make new panic print println real recover delete' }; return { aliases: ['golang'], keywords: GO_KEYWORDS, illegal: '</', contains: [ hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE, hljs.QUOTE_STRING_MODE, { className: 'string', begin: '\'', end: '[^\\\\]\'' }, { className: 'string', begin: '`', end: '`' }, { className: 'number', variants: [ {begin: hljs.C_NUMBER_RE + '[dflsi]', relevance: 1}, hljs.C_NUMBER_MODE ] }, { begin: /:=/ // relevance booster } ] }; } " Set root url to search," const {BrowserRouter, Route} = require('react-router-dom'); const h = require('react-hyperscript'); const ReactGA = require('react-ga'); const _ = require('lodash'); const Features = require('./features'); ReactGA.initialize('UA-43341809-7'); const Analytics = (props) => { ReactGA.set({ page: props.location.pathname + props.location.search }); ReactGA.pageview(props.location.pathname + props.location.search); return null; }; module.exports = () => { return h(BrowserRouter, [ h('div', [ { path: '*', render: props => h(Analytics, props) }, { path: '/', render: props => h(Features.Search, props) }, { path: '/search', render: props => h(Features.Search, props) }, { path: '/view', render: props => h(Features.View, props) }, { path: '/paint', render: props => h(Features.Paint, props) }, { path: '/edit', render: props => { const editProps = _.assign({}, props, { admin: true }); return h(Features.View, editProps); } } ].map( spec => h(Route, _.assign({ exact: true }, spec)) )) ]); };"," const {BrowserRouter, Route} = require('react-router-dom'); const h = require('react-hyperscript'); const ReactGA = require('react-ga'); const _ = require('lodash'); const Features = require('./features'); ReactGA.initialize('UA-43341809-7'); const Analytics = (props) => { ReactGA.set({ page: props.location.pathname + props.location.search }); ReactGA.pageview(props.location.pathname + props.location.search); return null; }; module.exports = () => { return h(BrowserRouter, [ h('div', [ { path: '*', render: props => h(Analytics, props) }, { path: '/', render: props => h(Features.Entry, props) }, { path: '/search', render: props => h(Features.Search, props) }, { path: '/view', render: props => h(Features.View, props) }, { path: '/paint', render: props => h(Features.Paint, props) }, { path: '/edit', render: props => { const editProps = _.assign({}, props, { admin: true }); return h(Features.View, editProps); } } ].map( spec => h(Route, _.assign({ exact: true }, spec)) )) ]); };" Add support for MongoDB 2.4.1.,"var mongoose = require('mongoose'); var config = require('config'); var semver = require('semver'); // configure mongodb mongoose.connect(config.mongodb.connectionString || 'mongodb://' + config.mongodb.user + ':' + config.mongodb.password + '@' + config.mongodb.server +'/' + config.mongodb.database); mongoose.connection.on('error', function (err) { console.error('MongoDB error: ' + err.message); console.error('Make sure a mongoDB server is running and accessible by this application'); process.exit(1); }); mongoose.connection.on('open', function (err) { mongoose.connection.db.admin().serverStatus(function(err, data) { if (err) { if (err.name === ""MongoError"" && (err.errmsg === 'need to login' || err.errmsg === 'unauthorized')) { console.log('Forcing MongoDB authentication'); mongoose.connection.db.authenticate(config.mongodb.user, config.mongodb.password, function(err) { if (!err) return; console.error(err); process.exit(1); }); return; } else { console.error(err); process.exit(1); } } if (!semver.satisfies(data.version, '>=2.1.0')) { console.error('Error: Uptime requires MongoDB v2.1 minimum. The current MongoDB server uses only '+ data.version); process.exit(1); } }); }); module.exports = mongoose; ","var mongoose = require('mongoose'); var config = require('config'); var semver = require('semver'); // configure mongodb mongoose.connect(config.mongodb.connectionString || 'mongodb://' + config.mongodb.user + ':' + config.mongodb.password + '@' + config.mongodb.server +'/' + config.mongodb.database); mongoose.connection.on('error', function (err) { console.error('MongoDB error: ' + err.message); console.error('Make sure a mongoDB server is running and accessible by this application'); process.exit(1); }); mongoose.connection.on('open', function (err) { mongoose.connection.db.admin().serverStatus(function(err, data) { if (err) { if (err.name === ""MongoError"" && err.errmsg === 'need to login') { console.log('Forcing MongoDB authentication'); mongoose.connection.db.authenticate(config.mongodb.user, config.mongodb.password, function(err) { if (!err) return; console.error(err); process.exit(1); }); return; } else { console.error(err); process.exit(1); } } if (!semver.satisfies(data.version, '>=2.1.0')) { console.error('Error: Uptime requires MongoDB v2.1 minimum. The current MongoDB server uses only '+ data.version); process.exit(1); } }); }); module.exports = mongoose;" "Fix a bug when a command like ""/list-players"" is miss-spelled and ""/leave"" is executed cause of its alias ""/l"". And add some aliases.","package client.command; public enum Commands { Username(new String[]{""/username"", ""/name"", ""/u"", ""/n""}, Username.class), Team(new String[]{""/team"", ""/t""}, Team.class), Contract(new String[]{""/put-contract"", ""/contract""}, Contract.class), Create(new String[]{""/create"", ""/c""}, Create.class), Join(new String[]{""/join"", ""/j""}, Join.class), ListPlayers(new String[]{""/list-players"", ""/players""}, ListPlayers.class), ListChannel(new String[]{""/list-channels"", ""/channels""}, ListChannel.class), Leave(new String[]{""/leave"", ""/l""}, Leave.class), ShowCards(new String[]{""/show-cards"", ""/cards""}, ShowCards.class), ShowTable(new String[]{""/show-table"", ""/table""}, ShowTable.class), PlayCard(new String[]{""/play"", ""/p""}, PlayCard.class), ShowContract(new String[]{""/show-contract""}, ShowContract.class); private String[] aliases; private Class command; Commands(String[] aliases, Class command) { this.aliases = aliases; this.command = command; } public static Class from(String text) throws Exception { for (Commands command : Commands.values()) { for (String alias : command.getAliases()) { if (text.split(""\\s+"")[0].equals(alias)) { return command.getCommand(); } } } throw new Exception(); } public String[] getAliases() { return this.aliases; } public Class getCommand() { return this.command; } } ","package client.command; public enum Commands { Username(new String[]{""/username"", ""/name"", ""/u""}, Username.class), Team(new String[]{""/team"", ""/t""}, Team.class), Contract(new String[]{""/contract""}, Contract.class), Create(new String[]{""/create"", ""/c""}, Create.class), Join(new String[]{""/join"", ""/j""}, Join.class), ListPlayers(new String[]{""/list-players""}, ListPlayers.class), ListChannel(new String[]{""/list-channel""}, ListChannel.class), Leave(new String[]{""/leave"", ""/l""}, Leave.class), ShowCards(new String[]{""/show-cards""}, ShowCards.class), ShowTable(new String[]{""/show-table""}, ShowTable.class), PlayCard(new String[]{""/play""}, PlayCard.class), ShowContract(new String[]{""/show-contract""}, ShowContract.class); private String[] aliases; private Class command; Commands(String[] aliases, Class command) { this.aliases = aliases; this.command = command; } public static Class from(String text) throws Exception { for (Commands command : Commands.values()) { for (String alias : command.getAliases()) { if (text.startsWith(alias + ' ')) { return command.getCommand(); } } } throw new Exception(); } public String[] getAliases() { return this.aliases; } public Class getCommand() { return this.command; } } " Rename Object to BaseObject in YII 2.0.13,"<?php namespace yii\materialicons\base; use yii\base\BaseObject; use yii\materialicons\component\Icon; use yii\materialicons\component\Stack; /** * Class MaterialIcons * @package yii\materialicons\base */ abstract class MaterialIcons extends BaseObject { /** * @param string $name * @param array $options * @return Icon */ public static function icon($name, $options = []) { return new Icon($name, $options); } /** * @param array $options * @return Stack */ public static function stack($options = []) { return new Stack($options); } /** * Size values * @see rmrevin\yii\fontawesome\component\Icon::size */ const SIZE_LARGE = 'lg'; const SIZE_2X = '2x'; const SIZE_3X = '3x'; const SIZE_4X = '4x'; const SIZE_5X = '5x'; /** * Rotate values * @see rmrevin\yii\fontawesome\component\Icon::rotate */ const ROTATE_90 = '90'; const ROTATE_180 = '180'; const ROTATE_270 = '270'; /** * Flip values * @see rmrevin\yii\fontawesome\component\Icon::flip */ const FLIP_HORIZONTAL = 'horizontal'; const FLIP_VERTICAL = 'vertical'; } ","<?php namespace yii\materialicons\base; use yii\base\Object; use yii\materialicons\component\Icon; use yii\materialicons\component\Stack; /** * Class MaterialIcons * @package yii\materialicons\base */ abstract class MaterialIcons extends Object { /** * @param string $name * @param array $options * @return Icon */ public static function icon($name, $options = []) { return new Icon($name, $options); } /** * @param array $options * @return Stack */ public static function stack($options = []) { return new Stack($options); } /** * Size values * @see rmrevin\yii\fontawesome\component\Icon::size */ const SIZE_LARGE = 'lg'; const SIZE_2X = '2x'; const SIZE_3X = '3x'; const SIZE_4X = '4x'; const SIZE_5X = '5x'; /** * Rotate values * @see rmrevin\yii\fontawesome\component\Icon::rotate */ const ROTATE_90 = '90'; const ROTATE_180 = '180'; const ROTATE_270 = '270'; /** * Flip values * @see rmrevin\yii\fontawesome\component\Icon::flip */ const FLIP_HORIZONTAL = 'horizontal'; const FLIP_VERTICAL = 'vertical'; }" Change button text and other stuff,"var fipsData; google.load('visualization', '1', {packages:['table']}); $(function() { $.ajax({ url: '/data/fipsData.json', dataType: 'json', success: function(data) { fipsData = data; } }); $('#collapse-data-more').on('shown.bs.collapse', function () { generateChart(); $('#tableToggle').html('Hide this data'); }); $('#collapse-data-more').on('hidden.bs.collapse', function () { $('#tableToggle').html('Learn More About This Data'); }); }); function generateChart() { if (!fipsData) { //Wait for fips data to load setTimeout(generateChart, 1000); } else { var data = new google.visualization.DataTable(); data.addColumn('string', 'State'); data.addColumn('string', 'County'); data.addColumn('number', 'Count'); var rows = []; var keys = vehicleCounts.keys(); for (var i in keys) { var key = keys[i]; var count = vehicleCounts.get(key.replace(/^0*/, '')); var fips = fipsData[''+key]; if (fips) { rows.push([fips.State, fips.County, count]); } else { console.log('Unknown fips: ' + fips); } } data.addRows(rows); var table = new google.visualization.Table(document.getElementById('dataTable')); table.draw(data, {showRowNumber: false, sort: 'enable', sortColumn: 2, sortAscending: false}); } } ","var fipsData; google.load('visualization', '1', {packages:['table']}); $(function() { $.ajax({ url: '/data/fipsData.json', dataType: 'json', success: function(data) { fipsData = data; } }); $('#collapse-data-more').on('shown.bs.collapse', function () { generateChart(); }); }); function generateChart() { if (!fipsData) { //Wait for fips data to load setTimeout(generateChart, 1000); } else { var data = new google.visualization.DataTable(); data.addColumn('string', 'State'); data.addColumn('string', 'County'); data.addColumn('number', 'Count'); var rows = []; var keys = vehicleCounts.keys(); for (var i in keys) { var key = keys[i]; var count = vehicleCounts.get(key.replace(/^0*/, '')); var fips = fipsData[''+key]; if (fips) { rows.push([fips.State, fips.County, count]); } else { console.log('Unknown fips: ' + fips); } } data.addRows(rows); var table = new google.visualization.Table(document.getElementById('dataTable')); table.draw(data, {showRowNumber: false, sort: 'enable', sortColumn: 2, sortAscending: false}); } } " Use default controls if no controls configured,"angular.module('anol.map') .provider('ControlsService', [function() { var _controls; this.setControls = function(controls) { _controls = controls; }; this.$get = [function() { // and this is the service part var Controls = function(controls) { this.controls = controls || ol.control.defaults(); this.map = undefined; }; Controls.prototype.registerMap = function(map) { this.map = map; }; Controls.prototype.addControl = function(control) { if(this.map !== undefined) { this.map.addControl(control); } this.controls.push(control); }; Controls.prototype.addControls = function(controls) { var self = this; if(this.map !== undefined) { angular.forEach(controls, function(control) { self.map.addControl(control); }); } this.controls = this.controls.concat(controls); }; return new Controls(_controls); }]; }]); ","angular.module('anol.map') .provider('ControlsService', [function() { var _controls = []; this.setControls = function(controls) { _controls = controls; }; this.$get = [function() { // and this is the service part var Controls = function(controls) { this.controls = controls; this.map = undefined; }; Controls.prototype.registerMap = function(map) { this.map = map; }; Controls.prototype.addControl = function(control) { if(this.map !== undefined) { this.map.addControl(control); } this.controls.push(control); }; Controls.prototype.addControls = function(controls) { var self = this; if(this.map !== undefined) { angular.forEach(controls, function(control) { self.map.addControl(control); }); } this.controls = this.controls.concat(controls); }; return new Controls(_controls); }]; }]); " Clean up a little and don't store a final reference to the builder.,"// // SamsoN - utilities for playn clients and servers // Copyright (c) 2014, Cupric - All rights reserved. // http://github.com/cupric/samson/blob/master/LICENSE package samson; import java.util.List; import java.util.Map; import com.google.common.collect.Lists; import org.lwjgl.opengl.Display; /** * Notifier for debugging notifications. Issues a log message printout via an Interval. */ public class JavaNotifications extends Notifications { @Override public void cancelAll () { for (Interval interval : _scheduled) { interval.cancel(); } _scheduled.clear(); } @Override protected Handle schedule (long when, Builder builder) { final String message = builder._message; final Map<String, String> data = builder._data; final Interval interval = new Interval() { @Override public void expired () { dispatch(data, Display.isActive()); _scheduled.remove(this); } }; interval.schedule(Math.max(0, when - System.currentTimeMillis())); _scheduled.add(interval); return new Handle() { @Override public void cancel() { interval.cancel(); _scheduled.remove(interval); } }; } protected List<Interval> _scheduled = Lists.newArrayList(); } ","// // SamsoN - utilities for playn clients and servers // Copyright (c) 2014, Cupric - All rights reserved. // http://github.com/cupric/samson/blob/master/LICENSE package samson; import java.util.List; import com.google.common.collect.Lists; import org.lwjgl.opengl.Display; /** * Notifier for debugging notifications. Issues a log message printout via an Interval. */ public class JavaNotifications extends Notifications { @Override public void cancelAll () { for (Interval interval : _scheduled) { interval.cancel(); } _scheduled.clear(); } @Override protected Handle schedule (long when, final Builder builder) { final Interval interval = new Interval(Interval.PLAYN) { @Override public void expired () { dispatch(builder._data, Display.isActive()); _scheduled.remove(this); } }; interval.schedule(Math.max(0, when - System.currentTimeMillis())); _scheduled.add(interval); return new Handle() { @Override public void cancel() { interval.cancel(); _scheduled.remove(interval); } }; } protected List<Interval> _scheduled = Lists.newArrayList(); } " Change default path for the config json,"<?php namespace Stirling\Core; use InvalidArgumentException; class Config { protected static $instance; private $properties; /** * Config constructor. * @param string $configPath */ private function __construct($configPath) { $this->properties = Array(""git"" => null, ""name"" => null, ""version"" => null); if (file_exists($configPath)) { $json = json_decode(file_get_contents($configPath), true); if ($json != null) { $this->properties = array_merge($this->properties, $json); } } } public static function instance($configPath = ""./resources/default.json"") { if (self::$instance == null) { self::$instance = new Config($configPath); } return self::$instance; } public function __get($name) { if (key_exists($name, $this->properties)) { return $this->properties[$name]; } else { throw new InvalidArgumentException(""Property '"" . $name . ""' does not exist""); } } public function getConfigMap() { $temp = $this->properties; unset($temp[""version""]); unset($temp[""name""]); unset($temp[""git""]); return $temp; } } ","<?php namespace Stirling\Core; use InvalidArgumentException; class Config { protected static $instance; private $properties; /** * Config constructor. * @param string $configPath */ private function __construct($configPath) { $this->properties = Array(""git"" => null, ""name"" => null, ""version"" => null); if (file_exists($configPath)) { $json = json_decode(file_get_contents($configPath), true); if ($json != null) { $this->properties = array_merge($this->properties, $json); } } } public static function instance($configPath = ""./default.json"") { if (self::$instance == null) { self::$instance = new Config($configPath); } return self::$instance; } public function __get($name) { if (key_exists($name, $this->properties)) { return $this->properties[$name]; } else { throw new InvalidArgumentException(""Property '"" . $name . ""' does not exist""); } } public function getConfigMap() { $temp = $this->properties; unset($temp[""version""]); unset($temp[""name""]); unset($temp[""git""]); return $temp; } } " Add myself as a maintainer & update the url,"#!/usr/bin/env python import os from setuptools import find_packages, setup def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read() setup( name=""django-anonymizer"", version='0.5.0.13-bw', packages=find_packages(exclude=['*.tests']), include_package_data=True, author=""Luke Plant"", author_email=""L.Plant.98@cantab.net"", maintainer=""David Stensland"", maintainer_email=""anonymizer@terite.com"", url=""https://github.com/betterworks/django-anonymizer"", description=""App to anonymize data in Django models."", long_description=(read('README.rst') + ""\n\n"" + read('CHANGES.rst')), license=""MIT"", keywords=""django data database anonymize private"", classifiers=[ ""Development Status :: 4 - Beta"", ""Environment :: Web Environment"", ""Environment :: Console"", ""Intended Audience :: Developers"", ""License :: OSI Approved :: MIT License"", ""Operating System :: OS Independent"", ""Programming Language :: Python"", ""Programming Language :: Python :: 2.7"", ""Programming Language :: Python :: 3"", ""Programming Language :: Python :: 3.4"", ""Programming Language :: Python :: 3.5"", ""Framework :: Django"", ""Topic :: Software Development :: Testing"", ""Topic :: Database"" ], install_requires=[ 'faker >= 0.0.4-bw', 'django >= 1.8.0', 'six >= 1.10.0'], ) ","#!/usr/bin/env python import os from setuptools import find_packages, setup def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read() setup( name=""django-anonymizer"", version='0.5.0.13-bw', packages=find_packages(exclude=['*.tests']), include_package_data=True, author=""Luke Plant"", author_email=""L.Plant.98@cantab.net"", url=""https://bitbucket.org/spookylukey/django-anonymizer/"", description=""App to anonymize data in Django models."", long_description=(read('README.rst') + ""\n\n"" + read('CHANGES.rst')), license=""MIT"", keywords=""django data database anonymize private"", classifiers=[ ""Development Status :: 4 - Beta"", ""Environment :: Web Environment"", ""Environment :: Console"", ""Intended Audience :: Developers"", ""License :: OSI Approved :: MIT License"", ""Operating System :: OS Independent"", ""Programming Language :: Python"", ""Programming Language :: Python :: 2.7"", ""Programming Language :: Python :: 3"", ""Programming Language :: Python :: 3.4"", ""Programming Language :: Python :: 3.5"", ""Framework :: Django"", ""Topic :: Software Development :: Testing"", ""Topic :: Database"" ], install_requires=[ 'faker >= 0.0.4-bw', 'django >= 1.8.0', 'six >= 1.10.0'], ) " Improve documentation and clean up,"<?php namespace Elchristo\Calendar\Converter; use Elchristo\Calendar\Exception\RuntimeException; use Elchristo\Calendar\Model\Event\CalendarEventInterface; /** * Factory to build events which can be converted into various output formats */ class ConvertibleEventFactory { private $registeredConverters = []; /** * @param array $registeredConverters Declared converters in configuration */ public function __construct(array $registeredConverters = []) { $this->registeredConverters = $registeredConverters; } /** * Build instance of event converter (""default"" if not found) * * @param CalendarEventInterface $event Calendar event to convert * @param string $format Output format * @return ConvertibleEventInterface */ public function build(CalendarEventInterface $event, $format) { $key = \get_class($event); $name = \ucfirst($format); try { $eventClass = (isset($this->registeredConverters[$name]) && isset($this->registeredConverters[$name][$key])) ? $this->registeredConverters[$name][$key] : __NAMESPACE__ . ""\\"" . $name . ""\Event\Default{$name}Event""; return new $eventClass($event); } catch (\Exception $e) { throw new RuntimeException(""Impossible to build converter for calendar event of type {$event->getType()}."", $e->getCode(), $e); } } } ","<?php namespace Elchristo\Calendar\Converter; use Elchristo\Calendar\Exception\RuntimeException; use Elchristo\Calendar\Model\Event\CalendarEventInterface; /** * Factory to build convertible events */ class ConvertibleEventFactory { const DEFAULT_NAMESPACE_PREFIX = __NAMESPACE__ . '\\'; private $registeredConverters = []; /** * @param array $registeredConverters Declared converters in configuration */ public function __construct(array $registeredConverters = []) { $this->registeredConverters = $registeredConverters; } /** * Build instance of convertable event (default event if not found) * * @param CalendarEventInterface $event Calendar event to convert * @param string $format Output format */ public function build(CalendarEventInterface $event, $format) { $key = \get_class($event); $name = \ucfirst($format); try { if (isset($this->registeredConverters[$name]) && \array_key_exists($key, $this->registeredConverters[$name])) { $eventClass = $this->registeredConverters[$name][$key]; return new $eventClass($event); } $defaultEventClass = self::DEFAULT_NAMESPACE_PREFIX . ""{$name}\Event\Default{$name}Event""; return new $defaultEventClass($event); } catch (\Exception $e) { throw new RuntimeException(""Impossible to build event of type {$event->getType()}."", $e->getCode(), $e); } } } " Use the phase from the pre-FT'd file for the test FT,"# -*- coding: utf-8 -*- """""" Created on Mon Sep 30 20:22:29 2013 @author: chris Test script for the pytnt project """""" import unittest import numpy as np from numpy.testing import assert_allclose from processTNT import TNTfile class TestLoadFile(unittest.TestCase): """"""Tests that pytnt can load files"""""" def test_load_time_domain(self): ref1 = TNTfile(""testdata/LiCl_ref1.tnt"") def test_load_freq_domain(self): ref1 = TNTfile(""testdata/LiCl_ref1-ftp.tnt"") def test_load_fails(self): with self.assertRaises(AssertionError): zero = TNTfile(""/dev/zero"") class TestFourierTransform(unittest.TestCase): """"""Test that the Fourier Transform is done correctly Makes sure that the reference frequency is taken into account properly """""" def test_ref1(self): time_domain = TNTfile(""testdata/LiCl_ref1.tnt"") freq_domain = TNTfile(""testdata/LiCl_ref1-ftp.tnt"") lb = freq_domain.TMG2['linebrd'][0, 0] ph0 = freq_domain.TMG2['cumm_0_phase'][0, 0] my_ft = time_domain.LBfft(lb, 1, phase=np.deg2rad(ph0)) assert_allclose(freq_domain.DATA, my_ft) if __name__ == '__main__': unittest.main()","# -*- coding: utf-8 -*- """""" Created on Mon Sep 30 20:22:29 2013 @author: chris Test script for the pytnt project """""" import unittest from numpy.testing import assert_allclose from processTNT import TNTfile class TestLoadFile(unittest.TestCase): """"""Tests that pytnt can load files"""""" def test_load_time_domain(self): ref1 = TNTfile(""testdata/LiCl_ref1.tnt"") def test_load_freq_domain(self): ref1 = TNTfile(""testdata/LiCl_ref1-ftp.tnt"") def test_load_fails(self): with self.assertRaises(AssertionError): zero = TNTfile(""/dev/zero"") class TestFourierTransform(unittest.TestCase): """"""Test that the Fourier Transform is done correctly Makes sure that the reference frequency is taken into account properly """""" def test_ref1(self): time_domain = TNTfile(""testdata/LiCl_ref1.tnt"") freq_domain = TNTfile(""testdata/LiCl_ref1-ftp.tnt"") lb = freq_domain.TMG2['linebrd'][0, 0] my_ft = time_domain.LBfft(lb, 1) assert_allclose(freq_domain.DATA, my_ft) if __name__ == '__main__': unittest.main()" Set default login mechanism to LDAP,"class Authenticate extends React.Component { constructor(props) { super(props) this.state = { mechanism: ""ldap"" }; this.handleChange = this.handleChange.bind(this); this.handleAuthenticated = this.handleAuthenticated.bind(this); } handleChange(event) { console.log(event.target.value) this.setState({mechanism: event.target.value}) } handleAuthenticated() { rootPage.changeToMainPage.call(rootPage, ""secret"") } render() { let mechanism = (<AuthenticateToken onAuthenticated={this.handleAuthenticated} />) if (this.state.mechanism === ""ldap"") { mechanism = (<AuthenticateLdap onAuthenticated={this.handleAuthenticated} />) } return ( <section className=""container"" id=""authenticate""> <h5 className=""title"">Authenticate</h5> <label>Authentication mechanism</label> <select onChange={this.handleChange} value={this.state.mechanism}> <option value=""token"">Token</option> <option value=""ldap"">LDAP</option> </select> {mechanism} </section> ) } }","class Authenticate extends React.Component { constructor(props) { super(props) this.state = { mechanism: ""token"" }; this.handleChange = this.handleChange.bind(this); this.handleAuthenticated = this.handleAuthenticated.bind(this); } handleChange(event) { console.log(event.target.value) this.setState({mechanism: event.target.value}) } handleAuthenticated() { rootPage.changeToMainPage.call(rootPage, ""secret"") } render() { let mechanism = (<AuthenticateToken onAuthenticated={this.handleAuthenticated} />) if (this.state.mechanism === ""ldap"") { mechanism = (<AuthenticateLdap onAuthenticated={this.handleAuthenticated} />) } return ( <section className=""container"" id=""authenticate""> <h5 className=""title"">Authenticate</h5> <label>Authentication mechanism</label> <select onChange={this.handleChange} value={this.state.mechanism}> <option value=""token"">Token</option> <option value=""ldap"">LDAP</option> </select> {mechanism} </section> ) } }" Change the search field resolving logic,"<?php namespace AstritZeqiri\LaravelSearchable\Traits; use AstritZeqiri\LaravelSearchable\Search; use AstritZeqiri\LaravelSearchable\Exceptions\SearchException; trait Searchable { /** * Search on multiple database fields on eloquent models. * * @param Illuminate\Database\Eloquent\Builder $query * @param string $search * @param array|string $fields * @param boolean $exact * * @throws SearchException [if the search fields are not set on the model or they are not given on the method] * @return Illuminate\Database\Eloquent\Builder */ public function scopeSearch($query, $search = """", $fields = [], $exact = false) { if (! $search) { return $query; } $fields = $this->resolveSearchFields($fields); if (empty($fields)) { throw SearchException::searchOnOrFieldsNotFound(); } return (new Search($query)) ->className(static::class) ->searchFor($search) ->onFields($fields) ->exactSearch($exact) ->build(); } /** * Resolve the fields that should be searched on. * The fields are given as an array or declared * on the model as $searchOn property. * * @param array|string $fields * * @return array */ private function resolveSearchFields($fields = []) { if (is_array($fields)) { return $fields; } if (is_string($fields)) { return [$fields]; } if (property_exists(static::class, 'searchOn')) { return is_array(static::$searchOn) ? static::$searchOn : [static::$searchOn]; } return []; } } ","<?php namespace AstritZeqiri\LaravelSearchable\Traits; use AstritZeqiri\LaravelSearchable\Search; use AstritZeqiri\LaravelSearchable\Exceptions\SearchException; trait Searchable { /** * Search on multiple database fields on eloquent models. * * @param Illuminate\Database\Eloquent\Builder $query * @param string $search * @param array $fields * @param boolean $exact * * @throws SearchException [if the search fields are not set on the model or they are not given on the method] * @return Illuminate\Database\Eloquent\Builder */ public function scopeSearch($query, $search = """", $fields = [], $exact = false) { if (! $search) { return $query; } if (! $fields && ! property_exists(static::class, 'searchOn')) { throw SearchException::searchOnOrFieldsNotFound(); } $fields = $fields ?: static::$searchOn; if (! is_array($fields)) { $fields = [$fields]; } if (empty($fields)) { return $query; } return (new Search($query)) ->className(static::class) ->searchFor($search) ->onFields($fields) ->exactSearch($exact) ->build(); } } " Use view class directly in routing,"define([ 'zepto', 'backbone', 'collections/items', 'collections/users', 'collections/likes', 'views/create_item_page', 'views/show_item_page', 'views/search_form_page', 'views/search_results_page' ], function( $, Backbone, itemCollection, userCollection, likeCollection, CreateItemPageView, ShowItemPageView, SearchFormPageView, SearchResultsPageView){ var Router = Backbone.Router.extend({ routes: { '' : CreateItemPageView, 'item/:itemId' : ShowItemPageView, 'search_form' : SearchFormPageView, 'search?*query' : SearchResultsPageView, 'search' : SearchResultsPageView }, initialize: function(){ Backbone.history.on('route', function(router, viewClass, params){ if(this.view){ this.view.close(); } this.view = new viewClass({params: params}); $('#container').html(this.view.el); }, this); // Internally handle anchor clicks if route is defined $(document).delegate('a', 'click', function(e){ var route = e.target.getAttribute('href').replace(/^\//, ''); Backbone.history.navigate(route, {trigger: true}); return false; }); } }); return Router; }); ","define([ 'zepto', 'backbone', 'collections/items', 'collections/users', 'collections/likes', 'views/create_item_page', 'views/show_item_page', 'views/search_form_page', 'views/search_results_page' ], function( $, Backbone, itemCollection, userCollection, likeCollection, CreateItemPageView, ShowItemPageView, SearchFormPageView, SearchResultsPageView){ var views = { CreateItemPageView: CreateItemPageView, ShowItemPageView: ShowItemPageView, SearchFormPageView: SearchFormPageView, SearchResultsPageView: SearchResultsPageView, }, Router = Backbone.Router.extend({ routes: { '': 'CreateItemPageView', 'item/:itemId': 'ShowItemPageView', 'search_form': 'SearchFormPageView', 'search?*query': 'SearchResultsPageView', 'search': 'SearchResultsPageView' }, initialize: function(){ Backbone.history.on('route', function(router, viewName, params){ if(this.view){ this.view.close(); } this.view = new views[viewName]({params: params}); $('#container').html(this.view.el); }, this); // Internally handle anchor clicks if route is defined $(document).delegate('a', 'click', function(e){ var route = e.target.getAttribute('href').replace(/^\//, ''); Backbone.history.navigate(route, {trigger: true}); return false; }); } }); return Router; }); " "Change logging setup for Process() Also fix usage of badly named .proc variable.","import subprocess as sub import logbook class Process(object): """""" Helper class for running processes """""" def __init__(self, cmd): self.cmd = cmd self.popen = None self.success = None self.log = logbook.Logger(self.cmd) def setup(self): """""" Setup the Popen object used in execution """""" self.log.debug('Spawning process handler') self.popen = sub.Popen( self.cmd.split(), stdout=sub.PIPE, stderr=sub.PIPE, ) def run(self): self.log.debug('Executing') while not self.popen.poll(): # TODO: Gracefully handle stderr as well line = self.popen.stdout.readline() if not line: break self.log.info(line.decode('utf-8').rstrip()) exit = self.popen.wait() self.log.debug('Exitcode {0}'.format(exit)) self.success = exit == 0 if not self.success: self.log.error(self.popen.stderr.read()) ","import subprocess as sub import logbook class Process(object): """""" Helper class for running processes """""" def __init__(self, cmd): self.cmd = cmd self.proc = None self.success = None self.log = logbook.Logger(self.__class__.__name__) def setup(self): """""" Setup the Popen object used in execution """""" self.log.info('Spawning handler for {0}...'.format(self.cmd)) self.popen = sub.Popen( self.cmd.split(), stdout=sub.PIPE, stderr=sub.PIPE, ) def run(self): self.log.info('Executing {0}'.format(self.cmd)) while not self.popen.poll(): # TODO: Gracefully handle stderr as well line = self.popen.stdout.readline() if not line: break self.log.info(line.decode('utf-8').rstrip()) exit = self.popen.wait() self.log.info('Exitcode {0}'.format(exit)) self.success = exit == 0 if not self.success: self.log.error(self.popen.stderr.read()) " "Update service provider Applications , JwtAuth","<?php namespace Applications; use ReflectionClass; use Illuminate\Foundation\AliasLoader; use Illuminate\Support\ServiceProvider; class ApplicationsServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { // Find path to the package $applicationFileName = with(new ReflectionClass('Applications\ApplicationsServiceProvider'))->getFileName(); $applicationPath = dirname($applicationFileName); $this->loadViewsFrom($applicationPath . '/../views', 'applications'); include $applicationPath . '/../routes.php'; } /** * Register the service provider. * * @return void */ public function register() { $this->app->register(\Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class); $this->app->register(\Dingo\Api\Provider\LaravelServiceProvider::class); $this->app->register(\Barryvdh\Cors\ServiceProvider::class); $this->app->register(\JwtAuth\JwtAuthServiceProvider::class); $loader = AliasLoader::getInstance(); $loader->alias('JWTAuth', \Tymon\JWTAuth\Facades\JWTAuth::class); $loader->alias('JWTFactory', \Tymon\JWTAuth\Facades\JWTFactory::class); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return []; } } ","<?php namespace Applications; use ReflectionClass; use Illuminate\Foundation\AliasLoader; use Illuminate\Support\ServiceProvider; class ApplicationsServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { // Find path to the package $applicationsFileName = with(new ReflectionClass('Applications\ApplicationsServiceProvider'))->getFileName(); $applicationsPath = dirname($applicationsFileName); $this->loadViewsFrom($applicationsPath . '/../views', 'applications'); include $applicationsPath . '/../routes.php'; } /** * Register the service provider. * * @return void */ public function register() { $this->app->register(\Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class); $this->app->register(\Dingo\Api\Provider\LaravelServiceProvider::class); $this->app->register(\Barryvdh\Cors\ServiceProvider::class); $loader = AliasLoader::getInstance(); $loader->alias('JWTAuth', \Tymon\JWTAuth\Facades\JWTAuth::class); $loader->alias('JWTFactory', \Tymon\JWTAuth\Facades\JWTFactory::class); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return []; } } " "Replace '.' with '-' in Appveyor links They apparently replace both '.' and '_' in URLs. Fixes #1220.","import Component from '@ember/component'; import { computed } from '@ember/object'; import { alias } from '@ember/object/computed'; export default Component.extend({ tagName: 'span', classNames: ['badge'], id: alias('badge.attributes.id'), repository: alias('badge.attributes.repository'), imageUrl: computed('badge.attributes.id', function() { let id = this.get('badge.attributes.id'); let branch = this.get('branch'); if (id !== undefined && id !== null) { return `https://ci.appveyor.com/api/projects/status/${id}/branch/${branch}?svg=true`; } else { let service = this.get('service'); let repository = this.get('repository'); return `https://ci.appveyor.com/api/projects/status/${service}/${repository}?svg=true&branch=${branch}`; } }), branch: computed('badge.attributes.branch', function() { return this.get('badge.attributes.branch') || 'master'; }), projectName: computed('badge.attributes.project_name', function() { return this.get('badge.attributes.project_name') || this.get('badge.attributes.repository').replace(/[_.]/g, '-'); }), service: computed('badge.attributes.service', function() { return this.get('badge.attributes.service') || 'github'; }), text: computed('badge', function() { return `Appveyor build status for the ${ this.get('branch') } branch`; }) }); ","import Component from '@ember/component'; import { computed } from '@ember/object'; import { alias } from '@ember/object/computed'; export default Component.extend({ tagName: 'span', classNames: ['badge'], id: alias('badge.attributes.id'), repository: alias('badge.attributes.repository'), imageUrl: computed('badge.attributes.id', function() { let id = this.get('badge.attributes.id'); let branch = this.get('branch'); if (id !== undefined && id !== null) { return `https://ci.appveyor.com/api/projects/status/${id}/branch/${branch}?svg=true`; } else { let service = this.get('service'); let repository = this.get('repository'); return `https://ci.appveyor.com/api/projects/status/${service}/${repository}?svg=true&branch=${branch}`; } }), branch: computed('badge.attributes.branch', function() { return this.get('badge.attributes.branch') || 'master'; }), projectName: computed('badge.attributes.project_name', function() { return this.get('badge.attributes.project_name') || this.get('badge.attributes.repository').replace(/_/g, '-'); }), service: computed('badge.attributes.service', function() { return this.get('badge.attributes.service') || 'github'; }), text: computed('badge', function() { return `Appveyor build status for the ${ this.get('branch') } branch`; }) }); " "Fix jscs violations, happening on travis","module.exports = { extractId: function(href) { return href.replace(/^[a-z-]+:\/+?[^\/]+/, '') // Remove protocol & domain .replace(/[\?\&]livereload=\w+/, '') // Remove LiveReload cachebuster .replace(/^\//, '') // Remove root / .replace(/\.[a-zA-Z]+$/, '') // Remove simple extension .replace(/[^\.\w-]+/g, '-') // Replace illegal characters .replace(/\./g, ':'); // Replace dots with colons(for valid id) }, addDataAttr: function(options, tag) { for (var opt in tag.dataset) { if (tag.dataset.hasOwnProperty(opt)) { if (opt === ""env"" || opt === ""dumpLineNumbers"" || opt === ""rootpath"" || opt === ""errorReporting"") { options[opt] = tag.dataset[opt]; } else { try { options[opt] = JSON.parse(tag.dataset[opt]); } catch(_) {} } } } } }; ","module.exports = { extractId: function(href) { return href.replace(/^[a-z-]+:\/+?[^\/]+/, '' ) // Remove protocol & domain .replace(/[\?\&]livereload=\w+/, '' ) // Remove LiveReload cachebuster .replace(/^\//, '' ) // Remove root / .replace(/\.[a-zA-Z]+$/, '' ) // Remove simple extension .replace(/[^\.\w-]+/g, '-') // Replace illegal characters .replace(/\./g, ':'); // Replace dots with colons(for valid id) }, addDataAttr: function(options, tag) { for (var opt in tag.dataset) { if (tag.dataset.hasOwnProperty(opt)) { if (opt === ""env"" || opt === ""dumpLineNumbers"" || opt === ""rootpath"" || opt === ""errorReporting"") { options[opt] = tag.dataset[opt]; } else { try { options[opt] = JSON.parse(tag.dataset[opt]); } catch(_) {} } } } } }; " Remove raw results from IPWhois object.,""""""" Views for the rdap_explorer project, query app. """""" import ipwhois from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.views.decorators.cache import cache_page from django.views.decorators.csrf import csrf_protect from json import dumps from .forms import QueryForm def index(request): if request.method == 'POST': form = QueryForm(request.POST) if form.is_valid(): return HttpResponseRedirect(reverse( 'query:results', args=(form['query'].value(),) )) else: form = QueryForm() return render(request, 'query/index.html', { 'title': 'Query', 'form': form }) @cache_page(86400) @csrf_protect def results(request, query): error = None result = {} form = QueryForm(initial={""query"": query}) try: ip = ipwhois.IPWhois(query) result = ip.lookup_rdap(retry_count=1, depth=2) title = ip.address_str except (ValueError, ipwhois.exceptions.IPDefinedError) as e: error = e title = 'Error' return render(request, 'query/index.html', { 'title': title, 'error': error, 'form': form, 'result': dumps(result) }) ",""""""" Views for the rdap_explorer project, query app. """""" import ipwhois from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.views.decorators.cache import cache_page from django.views.decorators.csrf import csrf_protect from json import dumps from .forms import QueryForm def index(request): if request.method == 'POST': form = QueryForm(request.POST) if form.is_valid(): return HttpResponseRedirect(reverse( 'query:results', args=(form['query'].value(),) )) else: form = QueryForm() return render(request, 'query/index.html', { 'title': 'Query', 'form': form }) @cache_page(86400) @csrf_protect def results(request, query): error = None result = {} form = QueryForm(initial={""query"": query}) try: ip = ipwhois.IPWhois(query) result = ip.lookup_rdap(retry_count=1, depth=2, inc_raw=True) title = ip.address_str except (ValueError, ipwhois.exceptions.IPDefinedError) as e: error = e title = 'Error' return render(request, 'query/index.html', { 'title': title, 'error': error, 'form': form, 'result': dumps(result) }) " Update the version number after last change,"#!/usr/bin/env python # -*- coding: UTF-8 -*- # (c) 2014 Rajat Agarwal from setuptools import setup, find_packages import sqoot # Work around mbcs bug in distutils. # http://bugs.python.org/issue10945 import codecs try: codecs.lookup('mbcs') except LookupError: ascii = codecs.lookup('ascii') func = lambda name, enc=ascii: {True: enc}.get(name=='mbcs') codecs.register(func) setup( name='sqoot', version='20140923', author='Rajat Agarwal', author_email='rajatagarwal@alumni.purdue.edu', url='https://github.com/ragarwal6397', description='Sqoot wrapper library', long_description=open('./README.txt', 'r').read(), download_url='https://github.com/ragarwal6397/sqoot/tarball/master', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'License :: OSI Approved :: MIT License', ], packages=find_packages(), install_requires=[ 'requests>=2.1', ], license='MIT License', keywords='sqoot api', include_package_data=True, zip_safe=True, ) ","#!/usr/bin/env python # -*- coding: UTF-8 -*- # (c) 2014 Rajat Agarwal from setuptools import setup, find_packages import sqoot # Work around mbcs bug in distutils. # http://bugs.python.org/issue10945 import codecs try: codecs.lookup('mbcs') except LookupError: ascii = codecs.lookup('ascii') func = lambda name, enc=ascii: {True: enc}.get(name=='mbcs') codecs.register(func) setup( name='sqoot', version='20140727', author='Rajat Agarwal', author_email='rajatagarwal@alumni.purdue.edu', url='https://github.com/ragarwal6397', description='Sqoot wrapper library', long_description=open('./README.txt', 'r').read(), download_url='https://github.com/ragarwal6397/sqoot/tarball/master', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'License :: OSI Approved :: MIT License', ], packages=find_packages(), install_requires=[ 'requests>=2.1', ], license='MIT License', keywords='sqoot api', include_package_data=True, zip_safe=True, ) " "Remove symfony-yaml repo link, it's been merged into skeleton-v1","<?php Git::$repositories['Gatekeeper'] = [ 'remote' => 'git@github.com:JarvusInnovations/Gatekeeper.git', 'originBranch' => 'master', 'workingBranch' => 'instances/' . Site::getConfig('primary_hostname'), 'localOnly' => true, 'trees' => [ 'dwoo-plugins', 'event-handlers', 'html-templates', 'php-classes', 'php-config' => [ 'exclude' => '#^/Git\\.config\\.php$#' // don't sync this file ], 'php-migrations', 'phpunit-tests', 'sencha-workspace/pages', 'site-root' => [ 'exclude' => [ '#^/css(/|$)#', // don't sync /css, this directory is generated by /sass/compile '#^/js/pages(/|$)#' // don't sync /js/pages, this directory is generated by /sencha-cmd/pages-build ] ] ] ]; Git::$repositories['jarvus-highlighter'] = [ 'remote' => ""https://github.com/JarvusInnovations/jarvus-highlighter.git"", 'originBranch' => 'master', 'workingBranch' => 'master', 'trees' => [ ""sencha-workspace/packages/jarvus-highlighter"" => '.' ] ];","<?php Git::$repositories['Gatekeeper'] = [ 'remote' => 'git@github.com:JarvusInnovations/Gatekeeper.git', 'originBranch' => 'master', 'workingBranch' => 'instances/' . Site::getConfig('primary_hostname'), 'localOnly' => true, 'trees' => [ 'dwoo-plugins', 'event-handlers', 'html-templates', 'php-classes', 'php-config' => [ 'exclude' => '#^/Git\\.config\\.php$#' // don't sync this file ], 'php-migrations', 'phpunit-tests', 'sencha-workspace/pages', 'site-root' => [ 'exclude' => [ '#^/css(/|$)#', // don't sync /css, this directory is generated by /sass/compile '#^/js/pages(/|$)#' // don't sync /js/pages, this directory is generated by /sencha-cmd/pages-build ] ] ] ]; Git::$repositories['symfony-yaml'] = [ 'remote' => 'https://github.com/symfony/Yaml.git', 'originBranch' => 'master', 'workingBranch' => 'master', 'trees' => [ 'php-classes/Symfony/Component/Yaml' => [ 'path' => '.', 'exclude' => [ '#\\.gitignore$#', '#^/Tests#', '#\\.md$#', '#composer\\.json#', '#phpunit\\.xml\\.dist#' ] ] ] ]; Git::$repositories['jarvus-highlighter'] = [ 'remote' => ""https://github.com/JarvusInnovations/jarvus-highlighter.git"", 'originBranch' => 'master', 'workingBranch' => 'master', 'trees' => [ ""sencha-workspace/packages/jarvus-highlighter"" => '.' ] ];" Add accounting group to apidocs,"API_GROUPS = { 'authentication': ['/api-auth/', '/api/auth-valimo/',], 'user': ['/api/users/', '/api/user-invitations/', '/api/user-counters/',], 'organization': [ '/api/customers/', '/api/customer-permissions-log/', '/api/customer-permissions-reviews/', '/api/customer-permissions/', ], 'marketplace': [ '/api/marketplace-bookings/', '/api/marketplace-cart-items/', '/api/marketplace-categories/', '/api/marketplace-category-component-usages/', '/api/marketplace-checklists-categories/', '/api/marketplace-checklists/', '/api/marketplace-component-usages/', '/api/marketplace-offering-files/', '/api/marketplace-offerings/', '/api/marketplace-order-items/', '/api/marketplace-orders/', '/api/marketplace-plans/', '/api/marketplace-plugins/', '/api/marketplace-public-api/', '/api/marketplace-resource-offerings/', '/api/marketplace-resources/', '/api/marketplace-screenshots/', '/api/marketplace-service-providers/', ], 'reporting': [ '/api/support-feedback-average-report/', '/api/support-feedback-report/', ], 'accounting': ['/api/invoices/', '/api/invoice-items/',], } ","API_GROUPS = { 'authentication': ['/api-auth/', '/api/auth-valimo/',], 'user': ['/api/users/', '/api/user-invitations/', '/api/user-counters/',], 'organization': [ '/api/customers/', '/api/customer-permissions-log/', '/api/customer-permissions-reviews/', '/api/customer-permissions/', ], 'marketplace': [ '/api/marketplace-bookings/', '/api/marketplace-cart-items/', '/api/marketplace-categories/', '/api/marketplace-category-component-usages/', '/api/marketplace-checklists-categories/', '/api/marketplace-checklists/', '/api/marketplace-component-usages/', '/api/marketplace-offering-files/', '/api/marketplace-offerings/', '/api/marketplace-order-items/', '/api/marketplace-orders/', '/api/marketplace-plans/', '/api/marketplace-plugins/', '/api/marketplace-public-api/', '/api/marketplace-resource-offerings/', '/api/marketplace-resources/', '/api/marketplace-screenshots/', '/api/marketplace-service-providers/', ], 'reporting': [ '/api/support-feedback-average-report/', '/api/support-feedback-report/', ], } " Fix token refresh for spotify credentials,"from flask_login import UserMixin import spotify import spotipy import db_utils import application as app class User(UserMixin): ''' User class for Flask-Login ''' def __init__(self, user_id, username=None): self.id = int(user_id) self.username = username self._spotify = None @property def spotify(self): oa_client = spotify.sp_oauth # Fetch credentials from database if not self._spotify: self._spotify = db_utils.spotify_creds_for_user(app.engine, self.id) # No credentials exist for user if self._spotify is None: return None # Refresh tokens if nescessary if oa_client.is_token_expired(self._spotify): print(""Spotify token expired for {}."".format(self.username)) self._spotify = oa_client.refresh_access_token( self._spotify.get('refresh_token')) # Save/return new credentials if possible if self._spotify: db_utils.spotify_credentials_upsert(app.engine, self.id, self._spotify) return spotipy.Spotify(auth=self._spotify['access_token']) class Playlist(object): ''' Playlist object representation ''' def __init__(self, playlist_id, title=None, duration=0, count=0): self.id = playlist_id self.title = title self.duration = duration self.count = count ","from flask_login import UserMixin import spotify import spotipy import db_utils import application as app class User(UserMixin): ''' User class for Flask-Login ''' def __init__(self, user_id, username=None): self.id = int(user_id) self.username = username self._spotify = None @property def spotify(self): oa_client = spotify.sp_oauth # Fetch credentials from database if not self._spotify: self._spotify = db_utils.spotify_creds_for_user(app.engine, self.id) # No credentials exist for user if self._spotify is None: return None # Refresh tokens if nescessary if oa_client.is_token_expired(self._spotify): self._spotify = oa_client.refresh_access_token(self._spotify) # Save/return new credentials if possible if self._spotify: db_utils.spotify_credentials_upsert(app.engine, self.id, self._spotify) return spotipy.Spotify(auth=self._spotify['access_token']) class Playlist(object): ''' Playlist object representation ''' def __init__(self, playlist_id, title=None, duration=0, count=0): self.id = playlist_id self.title = title self.duration = duration self.count = count " Add UTM mark to Evil Martian link,"import React, { Component } from ""react"" import styles from ""./index.css"" import logo from ""./evilmartians.svg"" export default class Footer extends Component { render() { return ( <footer className={ styles.root } role=""contentinfo""> <div className={ styles.inner }> <div className={ styles.info }> <p className={ styles.license }> { ""Distributed under the MIT License."" } </p> <p className={ styles.issue }>{ ""Found an issue?"" } <a className={ styles.report } href=""https://github.com/postcss/postcss.org/issues"" > { ""Report it!"" } </a> </p> </div> <div className={ styles.logo }> <a className={ styles.logoLink } href={ ""https://evilmartians.com/"" + ""?utm_source=postcss&utm_campaign=homepage"" } > <img alt=""Evil Martians"" className={ styles.logoInner } src={ logo } /> </a> </div> </div> </footer> ) } } ","import React, { Component } from ""react"" import styles from ""./index.css"" import logo from ""./evilmartians.svg"" export default class Footer extends Component { render() { return ( <footer className={ styles.root } role=""contentinfo""> <div className={ styles.inner }> <div className={ styles.info }> <p className={ styles.license }> { ""Distributed under the MIT License."" } </p> <p className={ styles.issue }>{ ""Found an issue?"" } <a className={ styles.report } href=""https://github.com/postcss/postcss.org/issues"" > { ""Report it!"" } </a> </p> </div> <div className={ styles.logo }> <a className={ styles.logoLink } href=""https://evilmartians.com/"" > <img alt=""Evil Martians"" className={ styles.logoInner } src={ logo } /> </a> </div> </div> </footer> ) } } " Use preg_quote() for escaping horizontal rule markers.,"<?php namespace FluxBB\Markdown\Extension\Core; use FluxBB\Markdown\Common\Text; use FluxBB\Markdown\Extension\ExtensionInterface; use FluxBB\Markdown\Renderer\RendererAwareInterface; use FluxBB\Markdown\Renderer\RendererAwareTrait; use FluxBB\Markdown\Markdown; /** * Converts horizontal rules * * Original source code from Markdown.pl * * > Copyright (c) 2004 John Gruber * > <http://daringfireball.net/projects/markdown/> * * @author Kazuyuki Hayashi <hayashi@valnur.net> */ class HorizontalRuleExtension implements ExtensionInterface, RendererAwareInterface { use RendererAwareTrait; /** * {@inheritdoc} */ public function register(Markdown $markdown) { $markdown->on('block', array($this, 'processHorizontalRule'), 20); } /** * @param Text $text */ public function processHorizontalRule(Text $text) { $marks = array('*', '-', '_'); foreach ($marks as $mark) { $text->replace( '/^[ ]{0,2}([ ]?' . preg_quote($mark, '/') . '[ ]?){3,}[ \t]*$/m', $this->getRenderer()->renderHorizontalRule() . ""\n\n"" ); } } /** * {@inheritdoc} */ public function getName() { return 'hr'; } } ","<?php namespace FluxBB\Markdown\Extension\Core; use FluxBB\Markdown\Common\Text; use FluxBB\Markdown\Extension\ExtensionInterface; use FluxBB\Markdown\Renderer\RendererAwareInterface; use FluxBB\Markdown\Renderer\RendererAwareTrait; use FluxBB\Markdown\Markdown; /** * Converts horizontal rules * * Original source code from Markdown.pl * * > Copyright (c) 2004 John Gruber * > <http://daringfireball.net/projects/markdown/> * * @author Kazuyuki Hayashi <hayashi@valnur.net> */ class HorizontalRuleExtension implements ExtensionInterface, RendererAwareInterface { use RendererAwareTrait; /** * {@inheritdoc} */ public function register(Markdown $markdown) { $markdown->on('block', array($this, 'processHorizontalRule'), 20); } /** * @param Text $text */ public function processHorizontalRule(Text $text) { $marks = array('\*', '-', '_'); foreach ($marks as $mark) { $text->replace( '/^[ ]{0,2}([ ]?' . $mark . '[ ]?){3,}[ \t]*$/m', $this->getRenderer()->renderHorizontalRule() . ""\n\n"" ); } } /** * {@inheritdoc} */ public function getName() { return 'hr'; } } " Allow any number of tests being reported,"package test.projects; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertLinesMatch; import com.github.sormuras.bach.Bach; import com.github.sormuras.bach.Logbook; import com.github.sormuras.bach.Options; import java.nio.file.Path; import org.junit.jupiter.api.Test; class StreamingEventsTests { @Test void build() { var name = ""StreamingEvents""; var root = Path.of(""test.projects"", name); var bach = Bach.of( Logbook.ofErrorPrinter(), Options.ofCommandLineArguments( """""" --chroot %s --verbose --limit-tools javac,jar,test,junit build """""" .formatted(root))); assertEquals(0, bach.run(), bach.logbook().toString()); assertLinesMatch( """""" >> BACH'S INITIALIZATION >> Work on project StreamingEvents 0 >> INFO + BUILD >> Ran \\d+ tests Build end. Bach run took .+ Logbook written to .+ """""" .lines(), bach.logbook().lines()); } } ","package test.projects; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertLinesMatch; import com.github.sormuras.bach.Bach; import com.github.sormuras.bach.Logbook; import com.github.sormuras.bach.Options; import java.nio.file.Path; import org.junit.jupiter.api.Test; class StreamingEventsTests { @Test void build() { var name = ""StreamingEvents""; var root = Path.of(""test.projects"", name); var bach = Bach.of( Logbook.ofErrorPrinter(), Options.ofCommandLineArguments( """""" --chroot %s --verbose --limit-tools javac,jar,test,junit build """""" .formatted(root))); assertEquals(0, bach.run(), bach.logbook().toString()); assertLinesMatch( """""" >> BACH'S INITIALIZATION >> Work on project StreamingEvents 0 >> INFO + BUILD >> Ran 2 tests Build end. Bach run took .+ Logbook written to .+ """""" .lines(), bach.logbook().lines()); } } " Fix for duplicated event triggered when using ajax.,"/** * @copyright Copyright (c) 2014 2amigOS! Consulting Group LLC * @link http://2amigos.us * @license http://www.opensource.org/licenses/bsd-license.php New BSD License */ if (typeof dosamigos == ""undefined"" || !dosamigos) { var dosamigos = {}; } dosamigos.toggleColumn = (function ($) { var pub = { onText: 'On', offText: 'Off', onTitle: 'On', offTitle: 'Off', registerHandler: function (grid, selector, cb) { $(document).off('click.toggleColumn', selector,); $(document).on('click.toggleColumn', selector, function (e) { e.preventDefault(); var $self = $(this); var url = $self.attr('href'); $.ajax({ url: url, dataType: 'json', success: function (data) { $self .html(data.value ? pub.onText : pub.offText) .attr('title', data.value ? pub.onTitle : pub.offTitle); $.isFunction(cb) && cb(true, data); }, error: function (xhr) { $.isFunction(cb) && cb(false, xhr); } }); return false; }); } }; return pub; })(jQuery);","/** * @copyright Copyright (c) 2014 2amigOS! Consulting Group LLC * @link http://2amigos.us * @license http://www.opensource.org/licenses/bsd-license.php New BSD License */ if (typeof dosamigos == ""undefined"" || !dosamigos) { var dosamigos = {}; } dosamigos.toggleColumn = (function ($) { var pub = { onText: 'On', offText: 'Off', onTitle: 'On', offTitle: 'Off', registerHandler: function (grid, selector, cb) { $(document).on('click.toggleColumn', selector, function (e) { e.preventDefault(); var $self = $(this); var url = $self.attr('href'); $.ajax({ url: url, dataType: 'json', success: function (data) { $self .html(data.value ? pub.onText : pub.offText) .attr('title', data.value ? pub.onTitle : pub.offTitle); $.isFunction(cb) && cb(true, data); }, error: function (xhr) { $.isFunction(cb) && cb(false, xhr); } }); return false; }); } }; return pub; })(jQuery);" Correct bind provider mock in tests,"import unittest from mock import patch, Mock, MagicMock import os import sys from bind.provider import Provider class TestBindProvider(unittest.TestCase): @patch('subprocess.check_output') @patch('bind.provider.unit_get') def test_first_setup(self, ugm, spcom): ugm.return_value = '10.0.0.1' bp = Provider('example.com') parser = MagicMock() bp.first_setup(parser) ugm.assert_called_once_with('public-address') parser.dict_to_zone.assert_called_with({'rr': 'A', 'alias': 'ns', 'addr': '10.0.0.1', 'ttl': 300}) @patch('bind.provider.ZoneParser.dict_to_zone') @patch('bind.provider.ZoneParser.save') def test_add_record(self, zps, zpm): bp = Provider('example.com') bp.reload_config = Mock() bp.add_record({'rr': 'A', 'alias': 'foo', 'addr': '127.0.0.1'}) zps.assert_called_once_with() zpm.assert_called_once_with({'alias': 'foo', 'addr': '127.0.0.1', 'rr': 'A'}) bp.reload_config.assert_called_once_with() ","import unittest from mock import patch, Mock, MagicMock import os import sys from bind.provider import Provider class TestBindProvider(unittest.TestCase): @patch('subprocess.check_output') @patch('bind.provider.unit_get') def test_first_setup(self, ugm, spcom): spcom.return_value = '10.0.0.1' bp = Provider('example.com') parser = MagicMock() bp.first_setup(parser) ugm.assert_called_once_with('public-address') parser.dict_to_zone.assert_called_with({'rr': 'A', 'alias': 'ns', 'addr': '10.0.0.1', 'ttl': 300}) @patch('bind.provider.ZoneParser.dict_to_zone') @patch('bind.provider.ZoneParser.save') def test_add_record(self, zps, zpm): bp = Provider('example.com') bp.reload_config = Mock() bp.add_record({'rr': 'A', 'alias': 'foo', 'addr': '127.0.0.1'}) zps.assert_called_once_with() zpm.assert_called_once_with({'alias': 'foo', 'addr': '127.0.0.1', 'rr': 'A'}) bp.reload_config.assert_called_once_with() " Add tree to fix formio-util dependency.,"var fs = require('fs'); module.exports = function (app) { app.config([ 'formioComponentsProvider', function(formioComponentsProvider) { formioComponentsProvider.register('datagrid', { title: 'Data Grid', template: 'formio/components/datagrid.html', settings: { input: true, tree: true, components: [], tableView: true, label: '', key: 'datagrid', protected: false, persistent: true } }); } ]); app.controller('formioDataGrid', [ '$scope', function($scope) { $scope.data[$scope.component.key] = $scope.data[$scope.component.key] || [{}]; $scope.addRow = function() { $scope.data[$scope.component.key].push({}); }; $scope.removeRow = function(index) { $scope.data[$scope.component.key].splice(index, 1); }; } ]); app.run([ '$templateCache', 'FormioUtils', function($templateCache, FormioUtils) { $templateCache.put('formio/components/datagrid.html', FormioUtils.fieldWrap( fs.readFileSync(__dirname + '/../templates/components/datagrid.html', 'utf8') )); } ]); }; ","var fs = require('fs'); module.exports = function (app) { app.config([ 'formioComponentsProvider', function(formioComponentsProvider) { formioComponentsProvider.register('datagrid', { title: 'Data Grid', template: 'formio/components/datagrid.html', settings: { input: true, components: [], tableView: true, label: '', key: 'datagrid', protected: false, persistent: true } }); } ]); app.controller('formioDataGrid', [ '$scope', function($scope) { $scope.data[$scope.component.key] = $scope.data[$scope.component.key] || [{}]; $scope.addRow = function() { $scope.data[$scope.component.key].push({}); }; $scope.removeRow = function(index) { $scope.data[$scope.component.key].splice(index, 1); }; } ]); app.run([ '$templateCache', 'FormioUtils', function($templateCache, FormioUtils) { $templateCache.put('formio/components/datagrid.html', FormioUtils.fieldWrap( fs.readFileSync(__dirname + '/../templates/components/datagrid.html', 'utf8') )); } ]); }; " Revert previous change to auth timestamp.,"import tornado.web import tornado.escape import json import time import os import settings as global_settings from lib.handlers.base import BaseHandler class EmbedTerminalHandler(BaseHandler): @tornado.web.authenticated def get(self): if not self.get_secure_cookie('gateone_ssl'): self.set_secure_cookie('gateone_ssl','accepted') self.redirect(global_settings.GATEONE_STATIC_URL+'/static/accept_certificate.html') else: secret = global_settings.TERMINAL_SECRET authobj = { 'api_key': global_settings.TERMINAL_API_KEY, 'upn': self.get_current_user(), 'timestamp': str(int(time.time() * 1000)), 'signature': """", 'signature_method': 'HMAC-SHA1', 'api_version': '1.0' } authobj['signature'] = self.create_signature(secret, authobj['api_key'], authobj['upn'], authobj['timestamp']) ctx = { 'authobj': authobj, 'gateone_url': global_settings.GATEONE_URL, 'gateone_origins_url': global_settings.GATEONE_ORIGINS_URL } self.write(ctx) @tornado.web.authenticated def create_signature(self, secret, *parts): import hmac, hashlib hash = hmac.new(secret, digestmod=hashlib.sha1) for part in parts: hash.update(str(part)) return hash.hexdigest() ","import tornado.web import tornado.escape import json import time import os import settings as global_settings from lib.handlers.base import BaseHandler class EmbedTerminalHandler(BaseHandler): @tornado.web.authenticated def get(self): if not self.get_secure_cookie('gateone_ssl'): self.set_secure_cookie('gateone_ssl','accepted') self.redirect(global_settings.GATEONE_STATIC_URL+'/static/accept_certificate.html') else: secret = global_settings.TERMINAL_SECRET authobj = { 'api_key': global_settings.TERMINAL_API_KEY, 'upn': self.get_current_user(), 'timestamp': str(int(time.time())), 'signature': """", 'signature_method': 'HMAC-SHA1', 'api_version': '1.0' } authobj['signature'] = self.create_signature(secret, authobj['api_key'], authobj['upn'], authobj['timestamp']) ctx = { 'authobj': authobj, 'gateone_url': global_settings.GATEONE_URL, 'gateone_origins_url': global_settings.GATEONE_ORIGINS_URL } self.write(ctx) @tornado.web.authenticated def create_signature(self, secret, *parts): import hmac, hashlib hash = hmac.new(secret, digestmod=hashlib.sha1) for part in parts: hash.update(str(part)) return hash.hexdigest() " "Resolve Doctrine proxies to real entity names in order to generate proper identifiers for model. | Q | A | ------------- | --- | Bug fix? | no | New feature? | yes | BC breaks? | no | Deprecations? | no | Tests pass? | yes | License | MIT","<?php namespace Spy\Timeline\ResolveComponent; use Doctrine\Common\Util\ClassUtils; use Spy\Timeline\Exception\ResolveComponentDataException; use Spy\Timeline\ResolveComponent\ValueObject\ResolveComponentModelIdentifier; use Spy\Timeline\ResolveComponent\ValueObject\ResolvedComponentData; /** * Basic implementation of a component data resolver. * * When no object is given we use the given model and identifier and data=null as ResolvedComponentData arguments * * When an object is given * - the model string is extracted by using get_class on the model * - The identifier is extracted by using the getId method on the model * * When not able to resolve the component data an * Spy\Timeline\Exception\ResolveComponentDataException exception is thrown. */ class BasicComponentDataResolver implements ComponentDataResolverInterface { /** * {@inheritdoc} */ public function resolveComponentData(ResolveComponentModelIdentifier $resolve) { $model = $resolve->getModel(); $identifier = $resolve->getIdentifier(); $data = null; if (is_object($model)) { $data = $model; $modelClass = ClassUtils::getRealClass(get_class($model)); if (!method_exists($model, 'getId')) { throw new ResolveComponentDataException('Model must have a getId method'); } $identifier = $model->getId(); $model = $modelClass; } return new ResolvedComponentData($model, $identifier, $data); } } ","<?php namespace Spy\Timeline\ResolveComponent; use Spy\Timeline\Exception\ResolveComponentDataException; use Spy\Timeline\ResolveComponent\ValueObject\ResolveComponentModelIdentifier; use Spy\Timeline\ResolveComponent\ValueObject\ResolvedComponentData; /** * Basic implementation of a component data resolver. * * When no object is given we use the given model and identifier and data=null as ResolvedComponentData arguments * * When an object is given * - the model string is extracted by using get_class on the model * - The identifier is extracted by using the getId method on the model * * When not able to resolve the component data an * Spy\Timeline\Exception\ResolveComponentDataException exception is thrown. */ class BasicComponentDataResolver implements ComponentDataResolverInterface { /** * {@inheritdoc} */ public function resolveComponentData(ResolveComponentModelIdentifier $resolve) { $model = $resolve->getModel(); $identifier = $resolve->getIdentifier(); $data = null; if (is_object($model)) { $data = $model; $modelClass = get_class($model); if (!method_exists($model, 'getId')) { throw new ResolveComponentDataException('Model must have a getId method'); } $identifier = $model->getId(); $model = $modelClass; } return new ResolvedComponentData($model, $identifier, $data); } } " Remove mcrypt constant from the bundle boot,"<?php /** * LICENSE: This file is subject to the terms and conditions defined in * file 'LICENSE', which is part of this source code package. * * @copyright 2016 Copyright(c) - All rights reserved. */ namespace Rafrsr\DoctrineExtraBundle; use Rafrsr\Crypto\Crypto; use Symfony\Component\HttpKernel\Bundle\Bundle; use Symfony\Component\HttpKernel\Kernel; use Rafrsr\DoctrineExtraBundle\DBAL\Types\Encryptor; /** * Class RafrsrDoctrineExtraBundle */ class RafrsrDoctrineExtraBundle extends Bundle { /** * @var Kernel */ protected static $kernel; public function __construct(Kernel $kernel) { self::$kernel = $kernel; } /** * @return Kernel */ public static function getKernel() { return self::$kernel; } /** * Boots the Bundle. */ public function boot() { if ($this->container->hasParameter('rafrsr.doctrine.encryptor')) { $encryptor = $this->container->getParameter('rafrsr.doctrine.encryptor'); } else { $encryptor = null; } if ($this->container->hasParameter('rafrsr.doctrine.secret')) { $secret = $this->container->getParameter('rafrsr.doctrine.secret'); } else { $secret = $this->container->getParameter('secret'); } Encryptor::set(Crypto::build($secret, $encryptor)); } } ","<?php /** * LICENSE: This file is subject to the terms and conditions defined in * file 'LICENSE', which is part of this source code package. * * @copyright 2016 Copyright(c) - All rights reserved. */ namespace Rafrsr\DoctrineExtraBundle; use Rafrsr\Crypto\Crypto; use Symfony\Component\HttpKernel\Bundle\Bundle; use Symfony\Component\HttpKernel\Kernel; use Rafrsr\DoctrineExtraBundle\DBAL\Types\Encryptor; /** * Class RafrsrDoctrineExtraBundle */ class RafrsrDoctrineExtraBundle extends Bundle { /** * @var Kernel */ protected static $kernel; public function __construct(Kernel $kernel) { self::$kernel = $kernel; } /** * @return Kernel */ public static function getKernel() { return self::$kernel; } /** * Boots the Bundle. */ public function boot() { if ($this->container->hasParameter('rafrsr.doctrine.encryptor')) { $encryptor = $this->container->getParameter('rafrsr.doctrine.encryptor'); } else { $encryptor = MCRYPT_RIJNDAEL_256; } if ($this->container->hasParameter('rafrsr.doctrine.secret')) { $secret = $this->container->getParameter('rafrsr.doctrine.secret'); } else { $secret = $this->container->getParameter('secret'); } Encryptor::set(Crypto::build($secret, $encryptor)); } }" Remove Underscore as it's not longer a dependency,"module.exports = function(config){ config.set({ basePath : 'client', files : [ 'components/angular/angular.js', 'components/angular-cookies/angular-cookies.js', 'components/angular-mocks/angular-mocks.js', 'components/angular-ui-router/release/angular-ui-router.js', 'js/**/*.js', 'tests/unit/**/*.js' ], /*exclude : [ 'app/lib/angular/angular-loader.js', 'app/lib/angular/*.min.js', 'app/lib/angular/angular-scenario.js' ],*/ autoWatch : true, frameworks: ['mocha', 'chai'], browsers : ['Chrome'], plugins : [ 'karma-junit-reporter', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-mocha', 'karma-chai' ], junitReporter : { outputFile: 'test_out/unit.xml', suite: 'unit' } }) };","module.exports = function(config){ config.set({ basePath : 'client', files : [ 'components/angular/angular.js', 'components/angular-cookies/angular-cookies.js', 'components/angular-mocks/angular-mocks.js', 'components/angular-ui-router/release/angular-ui-router.js', 'components/underscore/underscore.js', 'js/**/*.js', 'tests/unit/**/*.js' ], /*exclude : [ 'app/lib/angular/angular-loader.js', 'app/lib/angular/*.min.js', 'app/lib/angular/angular-scenario.js' ],*/ autoWatch : true, frameworks: ['mocha', 'chai'], browsers : ['Chrome'], plugins : [ 'karma-junit-reporter', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-mocha', 'karma-chai' ], junitReporter : { outputFile: 'test_out/unit.xml', suite: 'unit' } }) };" Fix reference to old controller name,"<?php namespace App\Http\Controllers; use App\Http\Requests\LoginRequest; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Foundation\Auth\AuthenticatesUsers; class LoginController extends Controller { use AuthenticatesUsers; protected $lockoutTime = 60 * 60 * 3; protected $maxLoginAttempts = 5; public function index() { // if the user is already logged in then redirect to index if (\Auth::check()) return \Redirect::action('HomeController@index'); return view('login'); } public function login(LoginRequest $request) { if (\Auth::check()) return \Redirect::action('HomeController@index'); if ($this->hasTooManyLoginAttempts($request)) { $this->fireLockoutEvent($request); return \Redirect::action('LoginController@index') ->withErrors(['lockout' => 'You have been locked out. Try again in 3 hours.']); } $username = \Input::get('username'); $password = \Input::get('password'); if (\Auth::attempt(['name' => $username, 'password' => $password]) == false) { $this->incrementLoginAttempts($request); return \Redirect::action('LoginController@index') ->withErrors(['login' => 'You have given invalid credentials. Please try again.']); } $this->clearLoginAttempts($request); return \Redirect::intended(); } public function logout() { \Auth::logout(); return \Redirect::action('LoginController@login'); } } ","<?php namespace App\Http\Controllers; use App\Http\Requests\LoginRequest; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Foundation\Auth\AuthenticatesUsers; class LoginController extends Controller { use AuthenticatesUsers; protected $lockoutTime = 60 * 60 * 3; protected $maxLoginAttempts = 5; public function index() { // if the user is already logged in then redirect to index if (\Auth::check()) return \Redirect::action('MangaController@index'); return view('login'); } public function login(LoginRequest $request) { if (\Auth::check()) return \Redirect::action('MangaController@index'); if ($this->hasTooManyLoginAttempts($request)) { $this->fireLockoutEvent($request); return \Redirect::action('LoginController@index') ->withErrors(['lockout' => 'You have been locked out. Try again in 3 hours.']); } $username = \Input::get('username'); $password = \Input::get('password'); if (\Auth::attempt(['name' => $username, 'password' => $password]) == false) { $this->incrementLoginAttempts($request); return \Redirect::action('LoginController@index') ->withErrors(['login' => 'You have given invalid credentials. Please try again.']); } $this->clearLoginAttempts($request); return \Redirect::intended(); } public function logout() { \Auth::logout(); return \Redirect::action('LoginController@login'); } } " "Fix pyreq test on Windows Signed-off-by: Uilian Ries <d4bad57018205bdda203549c36d3feb0bfe416a7@gmail.com>","import unittest from conans.test.utils.tools import TestClient from cpt.test.test_client.tools import get_patched_multipackager class PythonRequiresTest(unittest.TestCase): def test_python_requires(self): base_conanfile = """"""from conans import ConanFile myvar = 123 def myfunct(): return 234 class Pkg(ConanFile): pass """""" conanfile = """"""from conans import ConanFile class Pkg(ConanFile): name = ""pyreq"" version = ""1.0.0"" python_requires = ""pyreq_base/0.1@user/channel"" def build(self): v = self.python_requires[""pyreq_base""].module.myvar f = self.python_requires[""pyreq_base""].module.myfunct() self.output.info(""%s,%s"" % (v, f)) """""" client = TestClient() client.save({""conanfile_base.py"": base_conanfile}) client.run(""export conanfile_base.py pyreq_base/0.1@user/channel"") client.save({""conanfile.py"": conanfile}) mulitpackager = get_patched_multipackager(client, username=""user"", channel=""testing"", exclude_vcvars_precommand=True) mulitpackager.add({}, {}) mulitpackager.run() self.assertIn(""pyreq/1.0.0@user/"", client.out) self.assertIn("": 123,234"", client.out) ","import unittest from conans.test.utils.tools import TestClient from cpt.test.test_client.tools import get_patched_multipackager class PythonRequiresTest(unittest.TestCase): def test_python_requires(self): base_conanfile = """"""from conans import ConanFile myvar = 123 def myfunct(): return 234 class Pkg(ConanFile): pass """""" conanfile = """"""from conans import ConanFile class Pkg(ConanFile): name = ""pyreq"" version = ""1.0.0"" python_requires = ""pyreq_base/0.1@user/channel"" def build(self): v = self.python_requires[""pyreq_base""].module.myvar f = self.python_requires[""pyreq_base""].module.myfunct() self.output.info(""%s,%s"" % (v, f)) """""" client = TestClient() client.save({""conanfile_base.py"": base_conanfile}) client.run(""export conanfile_base.py pyreq_base/0.1@user/channel"") client.save({""conanfile.py"": conanfile}) mulitpackager = get_patched_multipackager(client, username=""user"", channel=""testing"", exclude_vcvars_precommand=True) mulitpackager.add({}, {}) mulitpackager.run() self.assertIn(""pyreq/1.0.0@user/testing: 123,234"", client.out) " Add banner to CSS files,"/*global module:false*/ module.exports = function(grunt) { // Project configuration. grunt.initConfig({ // Metadata. pkg: grunt.file.readJSON('package.json'), banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today(""yyyy-mm-dd"") %>\n' + '<%= pkg.homepage ? ""* "" + pkg.homepage + ""\\n"" : """" %>' + '* Copyright (c) <%= grunt.template.today(""yyyy"") %> <%= pkg.author.name %>;' + ' Licensed <%= _.pluck(pkg.licenses, ""type"").join("", "") %> */\n', // Task configuration. uglify: { options: { banner: '<%= banner %>' }, dist: { files: { 'dist/ng-mobile-menu.min.js' : ['src/ng-mobile-menu.js'] } } }, less: { dist: { options: { compress: true, banner: '<%= banner %>' }, files: { ""dist/ng-mobile-menu.min.css"" : ""src/ng-mobile-menu.less"" } } } }); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-less'); // Default task. grunt.registerTask('default', ['uglify', 'less']); }; ","/*global module:false*/ module.exports = function(grunt) { // Project configuration. grunt.initConfig({ // Metadata. pkg: grunt.file.readJSON('package.json'), banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today(""yyyy-mm-dd"") %>\n' + '<%= pkg.homepage ? ""* "" + pkg.homepage + ""\\n"" : """" %>' + '* Copyright (c) <%= grunt.template.today(""yyyy"") %> <%= pkg.author.name %>;' + ' Licensed <%= _.pluck(pkg.licenses, ""type"").join("", "") %> */\n', // Task configuration. uglify: { options: { banner: '<%= banner %>' }, dist: { files: { 'dist/ng-mobile-menu.min.js' : ['src/ng-mobile-menu.js'] } } }, less: { dist: { options: { compress: true }, files: { ""dist/ng-mobile-menu.min.css"" : ""src/ng-mobile-menu.less"" } } } }); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-less'); // Default task. grunt.registerTask('default', ['uglify', 'less']); }; " Support pdo key in container,"<?php namespace Inspector; use Inspector\Inspection\InspectionInterface; use ReflectionClass; class Inspector implements InspectorInterface { private $inspections = array(); private $container; public function __construct($container) { $this->container = $container; } public function addInspection(InspectionInterface $inspection) { $this->inspections[] = $inspection; } public function getInspections() { return $this->inspections; } public function runInspection(InspectionInterface $inspection) { $className = $inspection->getClassName(); $methodName = $inspection->getMethodName(); $reflector = new ReflectionClass($className); $method = $reflector->getConstructor(); $arguments = array(); // Inject requested constructor arguments if ($method) { foreach ($method->getParameters() as $p) { if ($p->getName() == 'db') { $arguments[] = $this->container['db']; } if ($p->getName() == 'pdo') { $arguments[] = $this->container['pdo']; } } } $instance = $reflector->newInstanceArgs($arguments); foreach ($reflector->getMethods() as $method) { if ($method->getName()==$methodName) { if ($method->isPublic()) { $instance->$methodName($inspection); } } } } public function run() { foreach ($this->inspections as $inspection) { $this->runInspection($inspection); } } } ","<?php namespace Inspector; use Inspector\Inspection\InspectionInterface; use ReflectionClass; class Inspector implements InspectorInterface { private $inspections = array(); private $container; public function __construct($container) { $this->container = $container; } public function addInspection(InspectionInterface $inspection) { $this->inspections[] = $inspection; } public function getInspections() { return $this->inspections; } public function runInspection(InspectionInterface $inspection) { $className = $inspection->getClassName(); $methodName = $inspection->getMethodName(); $reflector = new ReflectionClass($className); $method = $reflector->getConstructor(); $arguments = array(); // Inject requested constructor arguments if ($method) { foreach ($method->getParameters() as $p) { if ($p->getName() == 'db') { $arguments[] = $this->container['db']; } } } $instance = $reflector->newInstanceArgs($arguments); foreach ($reflector->getMethods() as $method) { if ($method->getName()==$methodName) { if ($method->isPublic()) { $instance->$methodName($inspection); } } } } public function run() { foreach ($this->inspections as $inspection) { $this->runInspection($inspection); } } } " Increment version in preperation for release of version 1.3.0,"try: # Try using ez_setup to install setuptools if not already installed. from ez_setup import use_setuptools use_setuptools() except ImportError: # Ignore import error and assume Python 3 which already has setuptools. pass from setuptools import setup DESC = ('This Python library for Raspberry Pi makes it easy to leverage the ' 'complex functionality of the Texas Instruments INA219 ' 'sensor to measure voltage, current and power.') classifiers = ['Development Status :: 4 - Beta', 'Operating System :: POSIX :: Linux', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Topic :: System :: Hardware :: Hardware Drivers'] # Define required packages. requires = ['Adafruit_GPIO', 'mock'] def read_long_description(): try: import pypandoc return pypandoc.convert('README.md', 'rst') except(IOError, ImportError): return """" setup(name='pi-ina219', version='1.3.0', author='Chris Borrill', author_email='chris.borrill@gmail.com', description=DESC, long_description=read_long_description(), license='MIT', url='https://github.com/chrisb2/pi_ina219/', classifiers=classifiers, keywords='ina219 raspberrypi', install_requires=requires, test_suite='tests', py_modules=['ina219']) ","try: # Try using ez_setup to install setuptools if not already installed. from ez_setup import use_setuptools use_setuptools() except ImportError: # Ignore import error and assume Python 3 which already has setuptools. pass from setuptools import setup DESC = ('This Python library for Raspberry Pi makes it easy to leverage the ' 'complex functionality of the Texas Instruments INA219 ' 'sensor to measure voltage, current and power.') classifiers = ['Development Status :: 4 - Beta', 'Operating System :: POSIX :: Linux', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Topic :: System :: Hardware :: Hardware Drivers'] # Define required packages. requires = ['Adafruit_GPIO', 'mock'] def read_long_description(): try: import pypandoc return pypandoc.convert('README.md', 'rst') except(IOError, ImportError): return """" setup(name='pi-ina219', version='1.2.0', author='Chris Borrill', author_email='chris.borrill@gmail.com', description=DESC, long_description=read_long_description(), license='MIT', url='https://github.com/chrisb2/pi_ina219/', classifiers=classifiers, keywords='ina219 raspberrypi', install_requires=requires, test_suite='tests', py_modules=['ina219']) " Clean up how timelines respond to tweets,"YUI.add(""model-timeline-base"", function(Y) { ""use strict""; var models = Y.namespace(""Falco.Models""), TimelineBase; TimelineBase = Y.Base.create(""timeline"", Y.Model, [], { initializer : function(config) { var tweets; if(!config) { config = {}; } tweets = new models.Tweets({ items : config.tweets || [] }); this.set(""tweets"", tweets); this._handles = [ tweets.after([ ""more"", ""add"" ], this._tweetAdd, this) ]; this.publish(""tweets"", { preventable : false }); }, destructor : function() { new Y.EventTarget(this._handles).detach(); this._handles = null; this.get(""tweets"").destroy(); }, // Override .toJSON() to make sure tweets are included toJSON : function() { var json = TimelineBase.superclass.toJSON.apply(this); json.tweets = json.tweets.toJSON(); return json; }, _tweetAdd : function(e) { // Don't notify for tweets from cache // TODO: is this ever hit? if(e.cached) { debugger; return; } this.fire(""tweets"", { count : e.model ? 1 : (e.parsed || e.models).length }); } }); models.TimelineBase = TimelineBase; }, ""@VERSION@"", { requires : [ // YUI ""base-build"", ""model"", // Models ""model-list-tweets"" ] }); ","YUI.add(""model-timeline-base"", function(Y) { ""use strict""; var models = Y.namespace(""Falco.Models""), TimelineBase; TimelineBase = Y.Base.create(""timeline"", Y.Model, [], { initializer : function(config) { var tweets; config || (config = {}); tweets = new models.Tweets({ items : config.tweets || [] }); this.set(""tweets"", tweets); this._handles = [ tweets.after([ ""more"", ""add"" ], this._tweetAdd, this) ]; this.publish(""tweets"", { preventable : false }); }, destructor : function() { new Y.EventTarget(this._handles).detach(); this._handles = null; this.get(""tweets"").destroy(); }, // Override .toJSON() to make sure tweets are included toJSON : function() { var json = TimelineBase.superclass.toJSON.apply(this); json.tweets = json.tweets.toJSON(); return json; }, _tweetAdd : function(e) { var count = 1; // Don't notify for tweets from cache if(e.cached) { return; } if(e.parsed || e.models) { count = (e.parsed || e.models).length; } this.fire(""tweets"", { count : count }); } }); models.TimelineBase = TimelineBase; }, ""@VERSION@"", { requires : [ // YUI ""base-build"", ""model"", // Models ""model-list-tweets"" ] }); " [n/a] Fix type hinting return for setMetadata method,"<?php namespace Kerox\Messenger\Model; use Kerox\Messenger\Helper\ValidatorTrait; class ThreadControl implements \JsonSerializable { use ValidatorTrait; /** * @var int */ protected $recipientId; /** * @var null|int */ protected $targetAppId; /** * @var null|string */ protected $metadata; /** * PassThreadControl constructor. * * @param int $recipientId * @param int|null $targetAppId */ public function __construct(int $recipientId, int $targetAppId = null) { $this->recipientId = $recipientId; $this->targetAppId = $targetAppId; } /** * @param string $metadata */ public function setMetadata(string $metadata) { $this->isValidString($metadata, 1000); $this->metadata = $metadata; } /** * @return array */ public function jsonSerialize(): array { $json = [ 'recipient' => [ 'id' => $this->recipientId ], 'target_app_id' => $this->targetAppId, 'metadata' => $this->metadata, ]; return array_filter($json); } } ","<?php namespace Kerox\Messenger\Model; use Kerox\Messenger\Helper\ValidatorTrait; class ThreadControl implements \JsonSerializable { use ValidatorTrait; /** * @var int */ protected $recipientId; /** * @var null|int */ protected $targetAppId; /** * @var null|string */ protected $metadata; /** * PassThreadControl constructor. * * @param int $recipientId * @param int|null $targetAppId */ public function __construct(int $recipientId, int $targetAppId = null) { $this->recipientId = $recipientId; $this->targetAppId = $targetAppId; } /** * @param string $metadata */ public function setMetadata(string $metadata): void { $this->isValidString($metadata, 1000); $this->metadata = $metadata; } /** * @return array */ public function jsonSerialize(): array { $json = [ 'recipient' => [ 'id' => $this->recipientId ], 'target_app_id' => $this->targetAppId, 'metadata' => $this->metadata, ]; return array_filter($json); } } " "Remove @emails from non-generated files (91/n) Summary: Context - [[quip](https://fb.quip.com/1T2uAglapSkF)] We are updating the oncall annotation format of all javascript files from `emails oncall+my_oncall_shortname` to `oncall my_oncall_shortname`. NOTE: There are other linter errors in some of these files that have not been introduced by this change, they are not being fixed here since they are non-trivial fixes (eg. moving a file to a different path). To ensure we don't break anything, we are making this update with the following steps: 1. Add 'oncall' annotation format to JSCodegenModule and its generated files 2. Add new linter rule to add the annotation to existing non-codegen files 3. Add the new annotation to existing non-codegen files - D37541172 4. Update www oncall extraction logic and VS Code templates to use the new format - D37862548 5. Remove 'emails' annotation from JSCodegenModule and its generated files - D37963776 6. **(This diff)** Remove old annotation format from existing non-codegen files 7. Consolidate linters rule to ask user to add new annotation to new files drop-conflicts ignore-nocommit Differential Revision: D38292971 fbshipit-source-id: 716de2affb520ae5e33aa9e1a051499c272bcc88","/** * (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary. * * @flow strict-local * @format * @oncall ads_integration_management */ 'use strict'; const MAX_ASCII_CHARACTER = 127; /** * Serializes strings with non-ASCII characters to their Unicode escape * sequences (eg. \u2022), to avoid hitting this lint rule: * ""Source code should only include printable US-ASCII bytes"" */ const NonASCIIStringSnapshotSerializer = { test(val: mixed): boolean { if (typeof val !== 'string') { return false; } for (let i = 0; i < val.length; i++) { if (val.charCodeAt(i) > MAX_ASCII_CHARACTER) { return true; } } return false; }, print: (val: string): string => { return ( '""' + val .split('') .map((char) => { const code = char.charCodeAt(0); return code > MAX_ASCII_CHARACTER ? '\\u' + code.toString(16).padStart(4, '0') : char; }) .join('') // Keep the same behaviour as Jest's regular string snapshot // serialization, which escapes double quotes. .replace(/""/g, '\\""') + '""' ); }, }; module.exports = NonASCIIStringSnapshotSerializer; ","/** * (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary. * * @emails oncall+ads_integration_management * @flow strict-local * @format * @oncall ads_integration_management */ 'use strict'; const MAX_ASCII_CHARACTER = 127; /** * Serializes strings with non-ASCII characters to their Unicode escape * sequences (eg. \u2022), to avoid hitting this lint rule: * ""Source code should only include printable US-ASCII bytes"" */ const NonASCIIStringSnapshotSerializer = { test(val: mixed): boolean { if (typeof val !== 'string') { return false; } for (let i = 0; i < val.length; i++) { if (val.charCodeAt(i) > MAX_ASCII_CHARACTER) { return true; } } return false; }, print: (val: string): string => { return ( '""' + val .split('') .map((char) => { const code = char.charCodeAt(0); return code > MAX_ASCII_CHARACTER ? '\\u' + code.toString(16).padStart(4, '0') : char; }) .join('') // Keep the same behaviour as Jest's regular string snapshot // serialization, which escapes double quotes. .replace(/""/g, '\\""') + '""' ); }, }; module.exports = NonASCIIStringSnapshotSerializer; " Remove print statements from daemon,"#!/usr/bin/env python #Script adapted from example by Sander Marechal, released into public domain #Taken from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ import sys, time from daemon import Daemon from web_frontend import settings class MyDaemon(Daemon): def run(self): while True: min_repeat_time = settings.MIN_CONDOR_Q_POLL_TIME * 60 start_time = time.time() import background_run finish_time = time.time() difference = finish_time - start_time if difference < min_repeat_time: time.sleep(min_repeat_time - difference) if __name__ == ""__main__"": daemon = MyDaemon('/tmp/helper_daemon.pid') if len(sys.argv) == 2: if 'start' == sys.argv[1]: daemon.start() elif 'stop' == sys.argv[1]: daemon.stop() elif 'restart' == sys.argv[1]: daemon.restart() else: print ""Unknown command"" sys.exit(2) sys.exit(0) else: print ""usage: %s start|stop|restart"" % sys.argv[0] sys.exit(2) ","#!/usr/bin/env python #Script adapted from example by Sander Marechal, released into public domain #Taken from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ import sys, time from daemon import Daemon from web_frontend import settings class MyDaemon(Daemon): def run(self): while True: min_repeat_time = settings.MIN_CONDOR_Q_POLL_TIME * 60 start_time = time.time() import background_run finish_time = time.time() difference = finish_time - start_time print 'Took ' + str(difference) + ' seconds' if difference < min_repeat_time: print 'Sleeping for ' + str(min_repeat_time - difference) + ' seconds' time.sleep(min_repeat_time - difference) if __name__ == ""__main__"": daemon = MyDaemon('/tmp/helper_daemon.pid') if len(sys.argv) == 2: if 'start' == sys.argv[1]: daemon.start() elif 'stop' == sys.argv[1]: daemon.stop() elif 'restart' == sys.argv[1]: daemon.restart() else: print ""Unknown command"" sys.exit(2) sys.exit(0) else: print ""usage: %s start|stop|restart"" % sys.argv[0] sys.exit(2) " Update success callbacks for BookmarkFactory,"//factory is like the model - it access the backend and returns the data to the controller (function(){ 'use strict'; angular .module('shareMark') .factory('BookmarkFactory', BookmarkFactory); function BookmarkFactory($http){ return { getBookmarks: getBookmarks, getBookmark: getBookmark, createBookmark: createBookmark, updateBookmark: updateBookmark } function getBookmark(id){ return $http.get('bookmarks/' + id) .then(function(response){ return response.data; }); } function getBookmarks(){ return $http.get('/bookmarks') .then(function(response){ return response.data; }) }//end getBookmarks function createBookmark(bookmark){ const request = { method: ""post"", url: '/bookmarks', headers: { 'Content-Type': 'application/json' }, data: { bookmark: bookmark } } return $http(request) .then(function(response){ return response.data; }) } function updateBookmark(bookmark){ debugger }//end updateBookmark }//end BookmarkFactory }()); ","//factory is like the model - it access the backend and returns the data to the controller (function(){ 'use strict'; angular .module('shareMark') .factory('BookmarkFactory', BookmarkFactory); function BookmarkFactory($http){ return { // NOTE: callable methods getBookmarks: getBookmarks, getBookmark: getBookmark, createBookmark: createBookmark, updateBookmark: updateBookmark } function getBookmark(id){ return $http.get('bookmarks/' + id) .then(successResponse) // .then(function(response){ // return response.data; // }); } function getBookmarks(){ //returns our json file via active model serializer return $http.get('/bookmarks') //ajax returns a promise .then(successResponse) .catch(errorResponse); // debugger }//end getBookmarks function createBookmark(bookmark){ var req = { method: ""post"", url: '/bookmarks', headers: { 'Content-Type': 'application/json' // ""Content-Type"": ""application/json; charset = utf-8;"" }, data: { bookmark: bookmark } } return $http(req) .catch(errorResponse); }//end createBookmark function updateBookmark(bookmark){ debugger }//end updateBookmark function successResponse(response){ return response.data; } function errorResponse(error){ return error.data; } }//end BookmarkFactory }()); " Make so that grunt test is more human readable and in travis use grunt travis that do coveralls,"'use strict'; module.exports = function(grunt) { // Load tasks grunt.loadNpmTasks('grunt-wiredep'); grunt.loadNpmTasks('grunt-jslint'); grunt.loadNpmTasks('grunt-jscoverage'); grunt.loadNpmTasks('grunt-mocha-test'); grunt.loadNpmTasks('grunt-coveralls'); grunt.initConfig({ wiredep: { task: { src: ['public/index.html'] } }, jslint: { server: { src: 'api/**/*.js', directives: { node: true, white: true }, options: { failOnError: false } } }, jscoverage: { src: { expand: true, cwd: 'api/', src: ['**/*.js'], dest: 'api-cov', ext: '.js' } }, mochaTest: { travis: { options: { reporter: 'mocha-lcov-reporter', captureFile: 'api-cov/output/mocha-lcov-reporter.out', quiet: false }, src: ['test/**/*.js'] }, test: { src: ['test/**/*.js'] } }, coveralls: { options: { force: false }, test: { src: 'api-cov/output/mocha-lcov-reporter.out' } } }); // Register tasks grunt.registerTask('default', ['wiredep']); grunt.registerTask('test', ['jslint', 'jscoverage', 'mochaTest:test']); grunt.registerTask('travis', ['jslint', 'jscoverage', 'mochaTest:travis', 'coveralls']); };","'use strict'; module.exports = function(grunt) { // Load tasks grunt.loadNpmTasks('grunt-wiredep'); grunt.loadNpmTasks('grunt-jslint'); grunt.loadNpmTasks('grunt-jscoverage'); grunt.loadNpmTasks('grunt-mocha-test'); grunt.loadNpmTasks('grunt-coveralls'); grunt.initConfig({ wiredep: { task: { src: ['public/index.html'] } }, jslint: { server: { src: 'api/**/*.js', directives: { node: true, white: true }, options: { failOnError: false } } }, jscoverage: { src: { expand: true, cwd: 'api/', src: ['**/*.js'], dest: 'api-cov', ext: '.js' } }, mochaTest: { test: { options: { reporter: 'mocha-lcov-reporter', captureFile: 'api-cov/output/mocha-lcov-reporter.out', quiet: false }, src: ['test/**/*.js'] } }, coveralls: { options: { force: false }, test: { src: 'api-cov/output/mocha-lcov-reporter.out' } } }); // Register tasks grunt.registerTask('default', ['wiredep']); grunt.registerTask('test', ['jslint', 'jscoverage', 'mochaTest']); grunt.registerTask('travis', ['test', 'coveralls']); };" Add linear layout manager to recycler view,"package com.akexorcist.mvpsimple.module.feed; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.akexorcist.mvpsimple.R; public class FeedActivity extends AppCompatActivity implements FeedContractor.View { private FeedContractor.Presenter feedPresenter; private RecyclerView rvPostList; private FeedAdapter feedAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(com.akexorcist.mvpsimple.R.layout.activity_feed); bindView(); setupView(); createPresenter(); } private void bindView() { rvPostList = (RecyclerView) findViewById(R.id.rv_post_list); } private void setupView() { feedAdapter = new FeedAdapter(); rvPostList.setAdapter(feedAdapter); rvPostList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); } private void createPresenter() { FeedPresenter.createPresenter(this); } @Override protected void onResume() { super.onResume(); feedPresenter.start(); } @Override public void updatePostList() { feedAdapter.setPostItemList(feedPresenter.getPostList().getItemList()); } @Override public void showLoading() { } @Override public void hideLoading() { } @Override public void setPresenter(FeedContractor.Presenter presenter) { this.feedPresenter = presenter; } } ","package com.akexorcist.mvpsimple.module.feed; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import com.akexorcist.mvpsimple.R; public class FeedActivity extends AppCompatActivity implements FeedContractor.View { private FeedContractor.Presenter feedPresenter; private RecyclerView rvPostList; private FeedAdapter feedAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(com.akexorcist.mvpsimple.R.layout.activity_feed); bindView(); setupView(); createPresenter(); } private void bindView() { rvPostList = (RecyclerView) findViewById(R.id.rv_post_list); } private void setupView() { feedAdapter = new FeedAdapter(); rvPostList.setAdapter(feedAdapter); } private void createPresenter() { FeedPresenter.createPresenter(this); } @Override protected void onResume() { super.onResume(); feedPresenter.start(); } @Override public void updatePostList() { feedAdapter.setPostItemList(feedPresenter.getPostList().getItemList()); } @Override public void showLoading() { } @Override public void hideLoading() { } @Override public void setPresenter(FeedContractor.Presenter presenter) { this.feedPresenter = presenter; } } " Print the scenario when running 262-style tests.,"#!/usr/bin/env python3 import json import sys PREFIXES = [ [""FAIL"", ""PASS""], [""EXPECTED FAIL"", ""UNEXPECTED PASS""], ] def parse_expected_failures(): expected_failures = set() with open(""expected-failures.txt"", ""r"") as fp: for line in fp: line = line.strip() if not line: continue if line.startswith(""#""): continue expected_failures.add(line) return expected_failures def main(filename): expected_failures = parse_expected_failures() with open(filename, ""r"") as fp: results = json.load(fp) unexpected_results = [] for test in results: expected_failure = test[""file""] in expected_failures actual_result = test[""result""][""pass""] print(""{} {} ({})"".format(PREFIXES[expected_failure][actual_result], test[""file""], test[""scenario""])) if actual_result == expected_failure: if not actual_result: print(test[""rawResult""][""stderr""]) print(test[""rawResult""][""stdout""]) print(test[""result""][""message""]) unexpected_results.append(test) if unexpected_results: print(""{} unexpected results:"".format(len(unexpected_results))) for unexpected in unexpected_results: print(""- {}"".format(unexpected[""file""])) return False print(""All results as expected."") return True if __name__ == ""__main__"": sys.exit(0 if main(sys.argv[1]) else 1) ","#!/usr/bin/env python3 import json import sys PREFIXES = [ [""FAIL"", ""PASS""], [""EXPECTED FAIL"", ""UNEXPECTED PASS""], ] def parse_expected_failures(): expected_failures = set() with open(""expected-failures.txt"", ""r"") as fp: for line in fp: line = line.strip() if not line: continue if line.startswith(""#""): continue expected_failures.add(line) return expected_failures def main(filename): expected_failures = parse_expected_failures() with open(filename, ""r"") as fp: results = json.load(fp) unexpected_results = [] for test in results: expected_failure = test[""file""] in expected_failures actual_result = test[""result""][""pass""] print(""{} {}"".format(PREFIXES[expected_failure][actual_result], test[""file""])) if actual_result == expected_failure: if not actual_result: print(test[""rawResult""][""stderr""]) print(test[""rawResult""][""stdout""]) print(test[""result""][""message""]) unexpected_results.append(test) if unexpected_results: print(""{} unexpected results:"".format(len(unexpected_results))) for unexpected in unexpected_results: print(""- {}"".format(unexpected[""file""])) return False print(""All results as expected."") return True if __name__ == ""__main__"": sys.exit(0 if main(sys.argv[1]) else 1) " Fix authentication from cookied token.,"import hashlib import datetime from flask_login import UserMixin, AnonymousUserMixin import mediacloud as mcapi from app.core import db, mc # User class class User(UserMixin): def __init__(self, name, userid, active=True): self.name = name self.id = userid self.active = active self.created = datetime.datetime.now() def is_active(self): return self.active def is_anonymous(self): return False def is_authenticated(self): return True @classmethod def get(cls, userid): try: return User.cached[userid] except KeyError: return None User.cached = {} def authenticate_user_key(username, key): user_mc = mcapi.MediaCloud(key) if user_mc.verifyAuthToken(): user = User(username, key) User.cached[user.id] = user return user return AnonymousUserMixin() def authenticate_user(username, password): try: key = mc.userAuthToken(username, password) user = User(username, key) User.cached[user.id] = user return user except Exception: return AnonymousUserMixin() ","import hashlib import datetime from flask_login import UserMixin, AnonymousUserMixin import mediacloud as mcapi from app.core import db, mc # User class class User(UserMixin): def __init__(self, name, userid, active=True): self.name = name self.id = userid self.active = active self.created = datetime.datetime.now() def is_active(self): return self.active def is_anonymous(self): return False def is_authenticated(self): return True @classmethod def get(cls, userid): try: return User.cached[userid] except KeyError: return None User.cached = {} def authenticate_user_key(username, key): user_mc = mcapi.MediaCloud(key) if user_mc.verifyUserAuthToken(): user = User(username, key) User.cached[user.id] = user return user return AnonymousUserMixin() def authenticate_user(username, password): try: key = mc.userAuthToken(username, password) user = User(username, key) User.cached[user.id] = user return user except Exception: return AnonymousUserMixin() " [Admin] Improve the UI of cancelling and completing an order,"(function($) { $.fn.extend({ requireConfirmation: function() { return this.each(function() { return $(this).on('click', function(event) { event.preventDefault(); var actionButton = $(this); if (actionButton.is('a')) { $('#confirmation-button').attr('href', actionButton.attr('href')); } if (actionButton.is('button')) { $('#confirmation-button').on('click', function(event) { event.preventDefault(); return actionButton.closest('form').submit(); }); } return $('#confirmation-modal').modal('show'); }); }); } }); $(document).ready(function() { $('#sidebar') .first() .sidebar('attach events', '#sidebar-toggle', 'show') ; $('.ui.checkbox').checkbox(); $('.ui.accordion').accordion(); $('.link.ui.dropdown').dropdown({action: 'hide'}); $('.button.ui.dropdown').dropdown({action: 'hide'}); $('.menu .item').tab(); $('.form button').on('click', function() { return $(this).closest('form').addClass('loading'); }); $('.message .close').on('click', function() { return $(this).closest('.message').transition('fade'); }); $('.loadable.button').on('click', function() { return $(this).addClass('loading'); }); $('[data-requires-confirmation]').requireConfirmation(); $('.special.cards .image').dimmer({ on: 'hover' }); }); })(jQuery); ","(function($) { $.fn.extend({ requireConfirmation: function() { return this.each(function() { return $(this).on('click', function(event) { event.preventDefault(); var actionButton = $(this); if (actionButton.is('a')) { $('#confirmation-button').attr('href', actionButton.attr('href')); } if (actionButton.is('button')) { $('#confirmation-button').on('click', function(event) { event.preventDefault(); return actionButton.closest('form').submit(); }); } return $('#confirmation-modal').modal('show'); }); }); } }); $(document).ready(function() { $('#sidebar') .first() .sidebar('attach events', '#sidebar-toggle', 'show') ; $('.ui.checkbox').checkbox(); $('.ui.accordion').accordion(); $('.link.ui.dropdown').dropdown({action: 'hide'}); $('.button.ui.dropdown').dropdown({action: 'hide'}); $('.menu .item').tab(); $('.form button').on('click', function() { return $(this).closest('form').addClass('loading'); }); $('.message .close').on('click', function() { return $(this).closest('.message').transition('fade'); }); $('[data-requires-confirmation]').requireConfirmation(); $('.special.cards .image').dimmer({ on: 'hover' }); }); })(jQuery); " Disable buttons when no items,"const {h, app} = hyperapp /** @jsx h */ /* * To Do List with additional 'delete item' * feature that takes number of list item and * removes it from the list */ app({ state: { items: [""garden"", ""bathe"", ""cry""], item: """", deleteIndex: 0, }, view: (state, actions) => ( <main> <ol> {state.items.map(item => <li>{item}</li>)} </ol> <input type=""text"" placeholder=""Add New Item..."" onblur={e => actions.setItem(e.target.value)} value="""" /> <button onclick={actions.addItem}>Add Item</button> <br /> <input type=""text"" placeholder=""Delete Item Number..."" onblur={e => actions.setDelete(e.target.value)} value="""" /> <button onclick={actions.deleteItem} disabled={state.items.length <= 0}> Delete Item </button> <br /> <button onclick={actions.clearList} disabled={state.items.length <= 0}> Clear List </button> </main> ), actions: { addItem: state => ({ items: [...state.items, state.item] }), clearList: state => ({ items: [] }), setItem: (state, actions, value) => ({ item: value }), setDelete: (state, actions, value) => ({ deleteIndex: value }), deleteItem: state => ({ items: state.items.filter((_, i) => i != state.deleteIndex - 1 )}), } })","const {h, app} = hyperapp /** @jsx h */ /* * To Do List with additional 'delete item' * feature that takes number of list item and * removes it from the list */ app({ state: { items: [""garden"", ""bathe"", ""cry""], item: """", deleteIndex: 0, }, view: (state, actions) => ( <main> <ol> {state.items.map(item => <li>{item}</li>)} </ol> <input type=""text"" placeholder=""Add New Item..."" onblur={e => actions.setItem(e.target.value)} value="""" /> <button onclick={actions.addItem}>Add Item</button> <br /> <input type=""text"" placeholder=""Delete Item Number..."" onblur={e => actions.setDelete(e.target.value)} value="""" /> <button onclick={actions.deleteItem}>Delete Item</button> <br /> <button onclick={actions.clearList}>Clear List</button> </main> ), actions: { addItem: state => ({ items: [...state.items, state.item] }), clearList: state => ({ items: [] }), setItem: (state, actions, value) => ({ item: value }), setDelete: (state, actions, value) => ({ deleteIndex: value }), deleteItem: state => ({ items: state.items.filter((_, i) => i != state.deleteIndex - 1 )}), } })" "Check accepted uploads List-Id, otherwise we get false +ves from bugs-dist Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk>","# -*- coding: utf-8 -*- from DebianChangesBot import MailParser from DebianChangesBot.messages import AcceptedUploadMessage class AcceptedUploadParser(MailParser): @staticmethod def parse(headers, body): if headers.get('List-Id', '') != '<debian-devel-changes.lists.debian.org>': return msg = AcceptedUploadMessage() mapping = { 'Source': 'package', 'Version': 'version', 'Distribution': 'distribution', 'Urgency': 'urgency', 'Changed-By': 'by', 'Closes': 'closes', } for line in body: for field, target in mapping.iteritems(): if line.startswith('%s: ' % field): val = line[len(field) + 2:] setattr(msg, target, val) del mapping[field] break # If we have found all the field, stop looking if len(mapping) == 0: break try: if msg.closes: msg.closes = [int(x) for x in msg.closes.split(' ')] except ValueError: return return msg ","# -*- coding: utf-8 -*- from DebianChangesBot import MailParser from DebianChangesBot.messages import AcceptedUploadMessage class AcceptedUploadParser(MailParser): @staticmethod def parse(headers, body): msg = AcceptedUploadMessage() mapping = { 'Source': 'package', 'Version': 'version', 'Distribution': 'distribution', 'Urgency': 'urgency', 'Changed-By': 'by', 'Closes': 'closes', } for line in body: for field, target in mapping.iteritems(): if line.startswith('%s: ' % field): val = line[len(field) + 2:] setattr(msg, target, val) del mapping[field] break # If we have found all the field, stop looking if len(mapping) == 0: break try: if msg.closes: msg.closes = [int(x) for x in msg.closes.split(' ')] except ValueError: return return msg " Hide admin menu if not authorized,"'use strict'; angular.module('adminApp') .directive('topMenu', ['$location', 'Menu', 'Auth', function ($location, Menu, Auth) { return { restrict: 'A', transclude: true, controller: function ($scope) { $scope.user = Auth.getUser(); $scope.menuItems = []; function setUpMenu() { if (Auth.isLoggedIn()) { $scope.menuItems = Menu.get(); } else { $scope.menuItems = []; } } Auth.subscribe($scope, function () { $scope.user = Auth.getUser(); setUpMenu(); }); $scope.signOutBtn = function () { Auth.signOut(function (err, res) { if (err) { $scope.error = {error: true, message: err.message}; } else { $location.path('/signIn'); } }); }; $scope.menuItems = Menu.get(); $scope.select = function (path) { angular.forEach($scope.menuItems, function (menuItem) { menuItem.selected = menuItem.link === path; angular.forEach(menuItem.nestedMenu, function (nestedMenuItem) { nestedMenuItem.selected = false; if (nestedMenuItem.link === path) { nestedMenuItem.selected = menuItem.selected = true; } }); }); }; setUpMenu(); $scope.select($location.path()); }, templateUrl: '/views/admin/topMenu.html' }; }]); ","'use strict'; angular.module('adminApp') .directive('topMenu', ['$location', 'Menu', 'Auth', function ($location, Menu, Auth) { return { restrict: 'A', transclude: true, controller: function ($scope) { $scope.user = Auth.getUser(); Auth.subscribe($scope, function () { $scope.user = Auth.getUser(); }); $scope.signOutBtn = function () { Auth.signOut(function (err, res) { if (err) { $scope.error = {error: true, message: err.message}; } else { $location.path('/signIn'); } }); }; var menuItems = $scope.menuItems = Menu.get(); $scope.select = function (path) { angular.forEach(menuItems, function (menuItem) { menuItem.selected = menuItem.link === path; angular.forEach(menuItem.nestedMenu, function (nestedMenuItem) { nestedMenuItem.selected = false; if (nestedMenuItem.link === path) { nestedMenuItem.selected = menuItem.selected = true; } }); }); }; $scope.select($location.path()); }, templateUrl: '/views/admin/topMenu.html' }; }]); " "Use strict equal for organizationId This solves the lint offence","(function () { 'use strict'; angular.module('exceptionless.validators') .directive('projectNameAvailableValidator', function($timeout, $q, projectService) { return { restrict: 'A', require: 'ngModel', scope: { organizationId: ""="" }, link: function(scope, element, attrs, ngModel) { ngModel.$asyncValidators.unique = function(name) { var deferred = $q.defer(); if (ngModel.$pristine) { $timeout(function() { deferred.resolve(true); }, 0); } else if (scope.organizationId === ""__newOrganization"") { deferred.resolve(true); } else { projectService.isNameAvailable(scope.organizationId, name).then(function(response) { if (response.status === 201) { deferred.reject(''); } else { deferred.resolve(true); } }, function() { deferred.reject('An error occurred while validating the project name.'); }); } return deferred.promise; }; scope.$watch(""organizationId"", function() { ngModel.$validate(); }); } }; }); }()); ","(function () { 'use strict'; angular.module('exceptionless.validators') .directive('projectNameAvailableValidator', function($timeout, $q, projectService) { return { restrict: 'A', require: 'ngModel', scope: { organizationId: ""="" }, link: function(scope, element, attrs, ngModel) { ngModel.$asyncValidators.unique = function(name) { var deferred = $q.defer(); if (ngModel.$pristine) { $timeout(function() { deferred.resolve(true); }, 0); } else if (scope.organizationId == ""__newOrganization"") { deferred.resolve(true); } else { projectService.isNameAvailable(scope.organizationId, name).then(function(response) { if (response.status === 201) { deferred.reject(''); } else { deferred.resolve(true); } }, function() { deferred.reject('An error occurred while validating the project name.'); }); } return deferred.promise; }; scope.$watch(""organizationId"", function() { ngModel.$validate(); }); } }; }); }()); " "Improve ISBN field in Book Type form - Add required, pattern (to allow only numbers and dashes in HTML5-supporting browsers) and title properties - Remove a bit of redundant code","from django import forms from django.forms import ModelForm from django.utils.translation import ugettext_lazy as _ from books.models import BookType from egielda import settings class BookForm(ModelForm): # Different max_length than in model (to allow dashes in ISBN) isbn = forms.CharField(max_length=20, label=_(""ISBN""), widget=forms.TextInput( attrs={'required': 'required', 'pattern': '[0-9-]+', 'title': 'ISBN number'})) class Meta: model = BookType fields = ['isbn', 'publisher', 'title', 'publication_year', 'price'] labels = { 'publisher': _(""Publisher""), 'title': _(""Title""), 'publication_year': _(""Publication year""), 'price': _(""Price (%s)"") % getattr(settings, 'CURRENCY', 'USD'), } widgets = { 'publisher': forms.TextInput(attrs={'required': 'required'}), 'title': forms.TextInput(attrs={'required': 'required'}), 'publication_year': forms.NumberInput(attrs={'required': 'required', 'min': '1900', 'max': '2100'}), 'price': forms.NumberInput(attrs={'required': 'required', 'max': '999.99'}), } def clean_isbn(self): data = self.cleaned_data['isbn'] data = ''.join(filter(lambda x: x.isdigit(), data)) return data","from django import forms from django.forms import ModelForm from django.utils.translation import ugettext_lazy as _ from books.models import BookType from egielda import settings class BookForm(ModelForm): # Different max_length than in model (to allow dividers in ISBN number) isbn = forms.CharField(max_length=20, label=_(""ISBN"")) class Meta: model = BookType fields = ['isbn', 'publisher', 'title', 'publication_year', 'price'] labels = { 'isbn': _(""ISBN""), 'publisher': _(""Publisher""), 'title': _(""Title""), 'publication_year': _(""Publication year""), 'price': _(""Price (%s)"") % getattr(settings, 'CURRENCY', 'USD'), } widgets = { 'isbn': forms.TextInput(attrs={'required': 'required'}), 'publisher': forms.TextInput(attrs={'required': 'required'}), 'title': forms.TextInput(attrs={'required': 'required'}), 'publication_year': forms.NumberInput(attrs={'required': 'required', 'min': '1900', 'max': '2100'}), 'price': forms.NumberInput(attrs={'required': 'required', 'max': '999.99'}), } def clean_isbn(self): data = self.cleaned_data['isbn'] data = ''.join(filter(lambda x: x.isdigit(), data)) return data" "Allow messgae in preffered class sniff Signed-off-by: Tomas Votruba <5445cc846624f8e1309aa4cd2a2306f4bc110566@gmail.com>","<?php declare(strict_types=1); namespace Symplify\CodingStandard\Sniffs\Architecture; use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Sniffs\Sniff; use Symplify\TokenRunner\Analyzer\SnifferAnalyzer\Naming; use function Safe\sprintf; final class PreferredClassSniff implements Sniff { /** * @var string[] */ public $oldToPreferredClasses = []; /** * @var Naming */ private $naming; public function __construct(Naming $naming) { $this->naming = $naming; } /** * @return int[] */ public function register(): array { return [T_STRING]; } /** * @param int $position */ public function process(File $file, $position): void { if ($this->oldToPreferredClasses === []) { return; } $className = $this->naming->getClassName($file, $position); if (! isset($this->oldToPreferredClasses[$className])) { return; } $preferredClass = $this->oldToPreferredClasses[$className]; $file->addError($this->createMessage($className, $preferredClass), $position, self::class); } private function createMessage(string $className, string $preferredCase): string { // class if (class_exists($preferredCase)) { return sprintf('Instead of ""%s"" class, use ""%s""', $className, $preferredCase); } // advice return sprintf('You should not use ""%s"". Instead, %s', $className, lcfirst($preferredCase)); } } ","<?php declare(strict_types=1); namespace Symplify\CodingStandard\Sniffs\Architecture; use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Sniffs\Sniff; use Symplify\TokenRunner\Analyzer\SnifferAnalyzer\Naming; use function Safe\sprintf; final class PreferredClassSniff implements Sniff { /** * @var string[] */ public $oldToPreferredClasses = []; /** * @var Naming */ private $naming; public function __construct(Naming $naming) { $this->naming = $naming; } /** * @return int[] */ public function register(): array { return [T_STRING]; } /** * @param int $position */ public function process(File $file, $position): void { if ($this->oldToPreferredClasses === []) { return; } $className = $this->naming->getClassName($file, $position); if (! isset($this->oldToPreferredClasses[$className])) { return; } $preferredClass = $this->oldToPreferredClasses[$className]; $file->addError( sprintf('Instead of ""%s"" class, use ""%s""', $className, $preferredClass), $position, self::class ); } } " Refactor add cache clear commands compiler pass.,"<?php declare(strict_types=1); /** * @author Alexander Volodin <mr-stanlik@yandex.ru> * @copyright Copyright (c) 2020, 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; /** * Add commands to cache clearer compiler pass */ class AddCacheClearCommandsPass implements CompilerPassInterface { private const CLEARER = 'darvin_admin.cache.clearer'; /** * {@inheritDoc} */ public function process(ContainerBuilder $container): void { if (!$container->hasDefinition(self::CLEARER)) { return; } $clearer = $container->getDefinition(self::CLEARER); foreach ($container->getParameter('darvin_admin.cache.clear.sets') as $setName => $setAttr) { if (!$setAttr['enabled']) { continue; } foreach ($setAttr['commands'] as $commandAlias => $commandAttr) { if (!$commandAttr['enabled']) { continue; } $clearer->addMethodCall('addCommand', [ $setName, $commandAlias, new Reference($commandAttr['id']), $commandAttr['input'], ]); } } } } ","<?php /** * @author Alexander Volodin <mr-stanlik@yandex.ru> * @copyright Copyright (c) 2020, 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; /** * Add cache clear command compiler pass */ class AddCacheClearCommandsPass implements CompilerPassInterface { private const CACHE_CLEANER_ID = 'darvin_admin.cache.clearer'; /** * {@inheritdoc} */ public function process(ContainerBuilder $container) { if (!$container->hasDefinition(self::CACHE_CLEANER_ID)) { return; } $sets = $container->getParameter('darvin_admin.cache.clear.sets'); if (empty($sets)) { return; } $cacheClearerDefinition = $container->getDefinition(self::CACHE_CLEANER_ID); $definitions = []; foreach ($sets as $set => $commands) { foreach ($commands as $alias => $command) { $id = strpos($command['id'], '@') === 0 ? substr($command['id'], 1) : $command['id']; $cacheClearerDefinition->addMethodCall('addCommand', [ $set, $alias, new Reference($id), $command['input'], ]); } } $container->addDefinitions($definitions); } } " Add record details after upload,"import Ember from 'ember' import Authenticated from 'ember-simple-auth/mixins/authenticated-route-mixin' const { get, set } = Ember export default Ember.Route.extend(Authenticated, { pageTitle: 'Media', toggleDropzone () { $('body').toggleClass('dz-open') }, actions: { uploadImage (file) { const record = this.store.createRecord('file', { filename: get(file, 'name'), contentType: get(file, 'type'), length: get(file, 'size') }) $('body').removeClass('dz-open') var settings = { url: '/api/upload', headers: {} } file.read().then(url => { if (get(record, 'url') == null) { set(record, 'url', url) } }) this.get('session').authorize('authorizer:token', (headerName, headerValue) => { settings.headers[headerName] = headerValue file.upload(settings).then(response => { for (var property in response.body) { set(record, property, response.body[property]) } return record.save() }, () => { record.rollback() }) }) }, willTransition () { $('body').unbind('dragenter dragleave', this.toggleDropzone) }, didTransition () { $('body').on('dragenter dragleave', this.toggleDropzone) } }, model () { return this.store.findAll('file') } }) ","import Ember from 'ember' import Authenticated from 'ember-simple-auth/mixins/authenticated-route-mixin' const { get, set } = Ember export default Ember.Route.extend(Authenticated, { pageTitle: 'Media', toggleDropzone () { $('body').toggleClass('dz-open') }, actions: { uploadImage (file) { const record = this.store.createRecord('file', { filename: get(file, 'name'), contentType: get(file, 'type'), length: get(file, 'size') }) $('body').removeClass('dz-open') var settings = { url: '/api/upload', headers: {} } file.read().then(url => { if (get(record, 'url') == null) { set(record, 'url', url) } }) this.get('session').authorize('authorizer:token', (headerName, headerValue) => { settings.headers[headerName] = headerValue file.upload(settings).then(response => { //set(record, 'url', response.headers.Location) console.log(response) return record.save() }, () => { record.rollback() }) }) }, willTransition () { $('body').unbind('dragenter dragleave', this.toggleDropzone) }, didTransition () { $('body').on('dragenter dragleave', this.toggleDropzone) } }, model () { return this.store.findAll('file') } }) " Use the extract-text-webpack-plugin in scss,"const path = require('path'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const NODE_ENV = process.env.NODE_ENV; module.exports = { mode: NODE_ENV || 'production', entry: { 'app': './src/js/app.js', 'train-number-calc': './src/js/train-number-calc.js', '404': './src/js/404.js', }, output: { path: path.resolve(__dirname, './dist'), filename: '[name].js', publicPath: 'dist', }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', }, { test: /\.js$/, loader: 'babel-loader', }, { test: /\.css$/, use: ['style-loader', 'css-loader'], }, { test: /\.scss$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: ['css-loader', 'sass-loader'], }), }, ], }, resolve: { extensions: ['.js', '.vue'], alias: { vue$: 'vue/dist/vue.esm.js', }, }, devServer: { contentBase: path.resolve(__dirname, './'), port: 8888, inline: true, watchContentBase: true, }, }; ","const path = require('path'); const NODE_ENV = process.env.NODE_ENV; module.exports = { mode: NODE_ENV || 'production', entry: { 'app': './src/js/app.js', 'train-number-calc': './src/js/train-number-calc.js', '404': './src/js/404.js', }, output: { path: path.resolve(__dirname, './dist'), filename: '[name].js', publicPath: 'dist', }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', }, { test: /\.js$/, loader: 'babel-loader', }, { test: /\.css$/, use: ['style-loader', 'css-loader'], }, { test: /\.scss$/, use: [ 'style-loader', 'css-loader', 'sass-loader', ], }, ], }, resolve: { extensions: ['.js', '.vue'], alias: { vue$: 'vue/dist/vue.esm.js', }, }, devServer: { contentBase: path.resolve(__dirname, './'), port: 8888, inline: true, watchContentBase: true, }, }; " Return empty link if no foreign object,"<?php namespace Oro\Bundle\DataGridBundle\Extension\Formatter\Property; use Symfony\Component\Routing\RouterInterface; use Oro\Bundle\DataGridBundle\Datasource\ResultRecordInterface; use Oro\Bundle\UIBundle\Twig\Environment; class LinkProperty extends UrlProperty { const TEMPLATE = 'OroDataGridBundle:Extension:Formatter/Property/linkProperty.html.twig'; /** * @var Environment */ protected $twig; /** * @param RouterInterface $router * @param Environment $twig */ public function __construct(RouterInterface $router, Environment $twig) { $this->router = $router; $this->twig = $twig; } /** * {@inheritdoc} */ public function getRawValue(ResultRecordInterface $record) { $label = null; try { $label = $record->getValue($this->getOr(self::DATA_NAME_KEY) ?: $this->get(self::NAME_KEY)); // if the foreign object doesn't exist there is no link possible if (!$label) return """"; } catch (\LogicException $e) { } return $this->twig ->loadTemplate(self::TEMPLATE) ->render( [ 'url' => parent::getRawValue($record), 'label' => $label ] ); } } ","<?php namespace Oro\Bundle\DataGridBundle\Extension\Formatter\Property; use Symfony\Component\Routing\RouterInterface; use Oro\Bundle\DataGridBundle\Datasource\ResultRecordInterface; use Oro\Bundle\UIBundle\Twig\Environment; class LinkProperty extends UrlProperty { const TEMPLATE = 'OroDataGridBundle:Extension:Formatter/Property/linkProperty.html.twig'; /** * @var Environment */ protected $twig; /** * @param RouterInterface $router * @param Environment $twig */ public function __construct(RouterInterface $router, Environment $twig) { $this->router = $router; $this->twig = $twig; } /** * {@inheritdoc} */ public function getRawValue(ResultRecordInterface $record) { $label = null; try { $label = $record->getValue($this->getOr(self::DATA_NAME_KEY) ?: $this->get(self::NAME_KEY)); } catch (\LogicException $e) { } return $this->twig ->loadTemplate(self::TEMPLATE) ->render( [ 'url' => parent::getRawValue($record), 'label' => $label ] ); } } " Fix for broken unit test,"/** * Author: Jeff Whelpley * Date: 1/21/15 * * Testing out batter */ var name = 'lib/batter'; var taste = require('taste'); var batter = taste.target(name); describe('UNIT ' + name, function () { describe('getOptions()', function () { it('should set defaults', function () { var opts = { rootDir: 'foo', targetDir: 'blah', require: 'choo' }; var expected = { rootDir: 'foo', targetDir: 'blah', tasksets: { default: ['lint', 'test'] }, require: 'choo', unitTestCode: 'test/unit/**/*.js', unitTargetCode: 'lib/**/*.js', testDir: 'test' }; taste.addCommandLineArgs(expected); var actual = batter.getOptions(opts); actual.should.deep.equal(expected); }); }); describe('getPlugins()', function () { it('should return batter by default', function () { var rootDir = __dirname.replace('/test' + taste.delim + 'unit', ''); var opts = { rootDir: 'blah' }; var expected = [ { rootDir: rootDir }, { rootDir: 'blah' } ]; var actual = batter.getPlugins(opts); actual.should.deep.equal(expected); }); }); });","/** * Author: Jeff Whelpley * Date: 1/21/15 * * Testing out batter */ var name = 'lib/batter'; var taste = require('taste'); var batter = taste.target(name); describe('UNIT ' + name, function () { describe('getOptions()', function () { it('should set defaults', function () { var opts = { rootDir: 'foo', targetDir: 'blah', require: 'choo' }; var expected = { rootDir: 'foo', targetDir: 'blah', require: 'choo', unitTestCode: 'test/unit/**/*.js', unitTargetCode: 'lib/**/*.js', testDir: 'test' }; taste.addCommandLineArgs(expected); var actual = batter.getOptions(opts); actual.should.deep.equal(expected); }); }); describe('getPlugins()', function () { it('should return batter by default', function () { var rootDir = __dirname.replace('/test' + taste.delim + 'unit', ''); var opts = { rootDir: 'blah' }; var expected = [ { rootDir: rootDir }, { rootDir: 'blah' } ]; var actual = batter.getPlugins(opts); actual.should.deep.equal(expected); }); }); });" Use SQLite in an attempt to speed up the tests.,"# -*- coding: utf-8 -*- from .base import Base as Settings class Testing(Settings): # Database Configuration. # -------------------------------------------------------------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } # django-celery. # -------------------------------------------------------------------------- Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery'] BROKER_URL = 'django://' # django-haystack. # -------------------------------------------------------------------------- HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } # Media Storage Configuration. # -------------------------------------------------------------------------- # Amazon Web Services AWS_STORAGE_BUCKET_NAME = 'test-bucket' # django-s3-folder-storage DEFAULT_S3_PATH = 'media' STATIC_S3_PATH = 'static' CDN_DOMAIN = 'cdn.example.net' MEDIA_URL = 'https://%s/%s/' % (CDN_DOMAIN, DEFAULT_S3_PATH) STATIC_URL = 'https://%s/%s/' % (CDN_DOMAIN, STATIC_S3_PATH) # Authentication Configuration. # -------------------------------------------------------------------------- HELLO_BASE_CLIENT_ID = 'client-id' HELLO_BASE_CLIENT_SECRET = 'client-secret' OAUTH_AUTHORIZATION_URL = 'https://testserver/oauth/authorize/' OAUTH_TOKEN_URL = 'https://testserver/oauth/token/' ","# -*- coding: utf-8 -*- from .base import Base as Settings class Testing(Settings): # Database Configuration. # -------------------------------------------------------------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test', } } # django-celery. # -------------------------------------------------------------------------- Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery'] BROKER_URL = 'django://' # django-haystack. # -------------------------------------------------------------------------- HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } # Media Storage Configuration. # -------------------------------------------------------------------------- # Amazon Web Services AWS_STORAGE_BUCKET_NAME = 'test-bucket' # django-s3-folder-storage DEFAULT_S3_PATH = 'media' STATIC_S3_PATH = 'static' CDN_DOMAIN = 'cdn.example.net' MEDIA_URL = 'https://%s/%s/' % (CDN_DOMAIN, DEFAULT_S3_PATH) STATIC_URL = 'https://%s/%s/' % (CDN_DOMAIN, STATIC_S3_PATH) # Authentication Configuration. # -------------------------------------------------------------------------- HELLO_BASE_CLIENT_ID = 'client-id' HELLO_BASE_CLIENT_SECRET = 'client-secret' OAUTH_AUTHORIZATION_URL = 'https://testserver/oauth/authorize/' OAUTH_TOKEN_URL = 'https://testserver/oauth/token/' " Set the first item of the select-box selected by default,"/** * @see https://vuejs.org/v2/guide/components.html#Form-Input-Components-using-Custom-Events */ var typesSelectbox = { template: '<select v-bind:value=""value"" v-on:change=""updateValue($event.target.value)"" v-model=""selected"">' + '<option v-for=""type in types"" :value=""type.formType"">' + '{{ type.formType }}' + '</option>' + '</select>' , props: ['value'], data: function () { return { selected: this.value, types: [] } }, mounted: function() { this.getExtraFormTypes(); }, methods: { updateValue: function (selectedExtraFormType) { this.$emit('input', selectedExtraFormType); }, /** * Get the form types */ getExtraFormTypes: function() { this.$http .get('/extra-form-types.json') .then( function(response) { return response.json(); }, function (response) { console.log(response.status + ' ' + response.statusText); }) .then(function (jsonTypes) { this.types = jsonTypes; if (this.selected === 'initial') { this.selected = Object.keys(this.types)[0]; } this.$emit('input', this.selected) }) ; } } };","/** * @see https://vuejs.org/v2/guide/components.html#Form-Input-Components-using-Custom-Events */ var typesSelectbox = { template: '<select v-bind:value=""value"" v-on:change=""updateValue($event.target.value)"" v-model=""selected"">' + '<option v-for=""type in types"" :value=""type.formType"">' + '{{ type.formType }}' + '</option>' + '</select>' , props: ['value'], data: function () { return { selected: this.value, types: [] } }, mounted: function() { this.getExtraFormTypes(); }, methods: { updateValue: function (selectedExtraFormType) { this.$emit('input', selectedExtraFormType); }, /** * Get the form types */ getExtraFormTypes: function() { this.$http .get('/extra-form-types.json') .then( function(response) { return response.json(); }, function (response) { console.log(response.status + ' ' + response.statusText); }) .then(function (jsonTypes) { this.types = jsonTypes; if (this.selected === 'initial') { this.selected = Object.keys(this.types)[8]; } this.$emit('input', this.selected) }) ; } } };" Correct test to match the inverse test.,"import unittest from calexicon.calendars.tests.test_calendar import JulianGregorianConversion from calexicon.fn import julian_to_gregorian, gregorian_to_julian from calexicon.fn import julian_to_julian_day_number, julian_day_number_to_julian class TestJulianConversion(JulianGregorianConversion): def setUp(self): pass def Julian_to_Gregorian_conversion(self, julian_args, gregorian_args): result = julian_to_gregorian(*julian_args) self.assertEqual( result, gregorian_args, ) def Gregorian_to_Julian_conversion(self, julian_args, gregorian_args): result = gregorian_to_julian(*gregorian_args) self.assertEqual( result, julian_args, ) class TestJulianNumberConversion(unittest.TestCase): def test_number_to_julian_date(self): self.assertEqual(julian_to_julian_day_number(-4713, 1, 1), 0) self.assertEqual(julian_to_julian_day_number(-4712, 1, 1), 365) def test_julian_date_to_number(self): self.assertEqual(julian_day_number_to_julian(0), (-4713, 1, 1)) ","import unittest from calexicon.calendars.tests.test_calendar import JulianGregorianConversion from calexicon.fn import julian_to_gregorian, gregorian_to_julian from calexicon.fn import julian_to_julian_day_number, julian_day_number_to_julian class TestJulianConversion(JulianGregorianConversion): def setUp(self): pass def Julian_to_Gregorian_conversion(self, julian_args, gregorian_args): result = julian_to_gregorian(*julian_args) self.assertEqual( result, gregorian_args, ) def Gregorian_to_Julian_conversion(self, julian_args, gregorian_args): result = gregorian_to_julian(*gregorian_args) self.assertEqual( result, julian_args, ) class TestJulianNumberConversion(unittest.TestCase): def test_number_to_julian_date(self): self.assertEqual(julian_to_julian_day_number(-4713, 1, 1), 0) self.assertEqual(julian_to_julian_day_number(-4712, 1, 1), 365) def test_julian_date_to_number(self): self.assertEqual(julian_day_number_to_julian(1), (-4713, 1, 1)) " "Rename fetchPage to fetchPageContent, since it returns the content of the page.","/* eslint no-console: 0 */ 'use strict'; const phantom = require('phantom'); function* blockResourceLoading(page) { yield page.property('onResourceRequested', function(requestData, request) { var BLOCKED_RESOURCES = [ /\.gif/gi, /\.png/gi, /\.css/gi, /^((?!(feuseradmin\.js|tinymce|jquery-)).)*\.js.*/gi ]; var is_blacklisted_resource = BLOCKED_RESOURCES.some(function(r) { return r.test(requestData['url']); }); if (is_blacklisted_resource) { request.abort(); } }); } function* fetchPageContent(url, instance) { let is_local_instance = false; if (!instance) { instance = yield * initPhantomInstance(); is_local_instance = true; } const page = yield instance.createPage(); yield * blockResourceLoading(page); yield page.open(url); let html = yield page.property('content'); yield page.close(); if (is_local_instance) { instance.exit(); } return html; } function* initPhantomInstance() { return yield phantom.create(); } module.exports = { blockResourceLoading: blockResourceLoading, fetchPageContent: fetchPageContent, initPhantomInstance: initPhantomInstance }; ","/* eslint no-console: 0 */ 'use strict'; const phantom = require('phantom'); function* blockResourceLoading(page) { yield page.property('onResourceRequested', function(requestData, request) { var BLOCKED_RESOURCES = [ /\.gif/gi, /\.png/gi, /\.css/gi, /^((?!(feuseradmin\.js|tinymce|jquery-)).)*\.js.*/gi ]; var is_blacklisted_resource = BLOCKED_RESOURCES.some(function(r) { return r.test(requestData['url']); }); if (is_blacklisted_resource) { request.abort(); } }); } function* fetchPage(url, instance) { let is_local_instance = false; if (!instance) { instance = yield * initPhantomInstance(); is_local_instance = true; } const page = yield instance.createPage(); yield * blockResourceLoading(page); yield page.open(url); let html = yield page.property('content'); yield page.close(); if (is_local_instance) { instance.exit(); } return html; } function* initPhantomInstance() { return yield phantom.create(); } module.exports = { blockResourceLoading: blockResourceLoading, fetchPage: fetchPage, initPhantomInstance: initPhantomInstance }; " Fix send count and add debug logging,"import logging from promgen.models import Project, Service logger = logging.getLogger(__name__) class SenderBase(object): def send(self, data): sent = 0 for alert in data['alerts']: if 'project' in alert['labels']: logger.debug('Checking for projects') for project in Project.objects.filter(name=alert['labels']['project']): logger.debug('Checking %s', project) for sender in project.sender.all(): logger.debug('Sending to %s', sender) if self._send(sender.value, alert, data): sent += 1 if 'service' in alert['labels']: logger.debug('Checking for service') for service in Service.objects.filter(name=alert['labels']['service']): logger.debug('Checking %s', service) for sender in service.sender.all(): logger.debug('Sending to %s', sender) if self._send(sender.value, alert, data): sent += 1 if sent == 0: logger.debug('No senders configured for project or service %s', alert['labels']['project']) return sent def test(self, target, alert): logger.debug('Sending test message to %s', target) self._send(target, alert, {'externalURL': ''}) ","import logging from promgen.models import Project, Service logger = logging.getLogger(__name__) class SenderBase(object): def send(self, data): for alert in data['alerts']: if 'project' in alert['labels']: sent = 0 for project in Project.objects.filter(name=alert['labels']['project']): for sender in project.sender.all(): if self._send(sender.value, alert, data): sent += 1 if 'service' in alert['labels']: for service in Service.objects.filter(name=alert['labels']['service']): for sender in service.sender.all(): if self._send(sender.value, alert, data): sent += 1 if sent == 0: logger.debug('No senders configured for project or service %s', alert['labels']['project']) return sent def test(self, target, alert): logger.debug('Sending test message to %s', target) self._send(target, alert, {'externalURL': ''}) " "Allow different DB password for private instance Now the private instance password can be set with the MYSQL_PASSWORD_PRIVATE or MYSQL_PASSWORD_PVT environment variables. If neither of those are set, it defaults to the same password as the public database (MYSQL_PASSWORD environment variable).","import Knex from 'knex'; import dotenv from 'dotenv'; dotenv.config() const dbs = { get public() { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get#smart_self-overwriting_lazy_getters delete this.public; return this.public = Knex({ client: 'mysql2', useNullAsDefault: true, connection: { host : process.env.MYSQL_HOST || '127.0.0.1', user : process.env.MYSQL_USER || '', password : process.env.MYSQL_PASSWORD || '', database : process.env.MYSQL_DATABASE || 'testldapi' }, }); }, get private() { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get#smart_self-overwriting_lazy_getters delete this.private; return this.private = Knex({ client: 'mysql2', useNullAsDefault: true, connection: { host : process.env.MYSQL_HOST || '127.0.0.1', user : process.env.MYSQL_USER || '', password : process.env.MYSQL_PASSWORD_PRIVATE || process.env.MYSQL_PASSWORD_PVT || process.env.MYSQL_PASSWORD || '', database : process.env.MYSQL_DATABASE_PRIVATE || process.env.MYSQL_DATABASE_PVT || (process.env.MYSQL_DATABASE ? `${process.env.MYSQL_DATABASE}pvt` : 'testldapi') }, }); } } export { dbs }; ","import Knex from 'knex'; import dotenv from 'dotenv'; dotenv.config() const dbs = { get public() { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get#smart_self-overwriting_lazy_getters delete this.public; return this.public = Knex({ client: 'mysql2', useNullAsDefault: true, connection: { host : process.env.MYSQL_HOST || '127.0.0.1', user : process.env.MYSQL_USER || '', password : process.env.MYSQL_PASSWORD || '', database : process.env.MYSQL_DATABASE || 'testldapi' }, }); }, get private() { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get#smart_self-overwriting_lazy_getters delete this.private; return this.private = Knex({ client: 'mysql2', useNullAsDefault: true, connection: { host : process.env.MYSQL_HOST || '127.0.0.1', user : process.env.MYSQL_USER || '', password : process.env.MYSQL_PASSWORD || '', database : process.env.MYSQL_DATABASE_PRIVATE || process.env.MYSQL_DATABASE_PVT || (process.env.MYSQL_DATABASE ? `${process.env.MYSQL_DATABASE}pvt` : 'testldapi') }, }); } } export { dbs }; " "Change data parser, need to add unix timestamp support","package com.kilfat.web.model.deserializer; import com.fasterxml.jackson.databind.JsonNode; import com.kilfat.config.ServiceConstants; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DeserializerHelper { private static final SimpleDateFormat dateFormat = new SimpleDateFormat(ServiceConstants.DATE_FORMAT); public static JsonNode getFieldNode(JsonNode node, String field) { if (node.get(field) != null) { return node.get(field); } return null; } public static String getField(JsonNode node, String field) { if (node.get(field) != null) { return node.get(field).textValue(); } return """"; } public static Integer getIntegerField(JsonNode node, String field) { if (node.get(field) != null) { return node.get(field).intValue(); } return null; } public static Long getLongField(JsonNode node, String field) { if (node.get(field) != null) { return node.get(field).longValue(); } return null; } public static Date getDateField(JsonNode node, String field) { long date; if (node.get(field) == null || node.get(field).isLong() == false) { return null; } date = node.get(field).asLong(); try { return dateFormat.parse(date*1000L); } catch (ParseException e) { throw new RuntimeException(e); } } } ","package com.kilfat.web.model.deserializer; import com.fasterxml.jackson.databind.JsonNode; import com.kilfat.config.ServiceConstants; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DeserializerHelper { private static final SimpleDateFormat dateFormat = new SimpleDateFormat(ServiceConstants.DATE_FORMAT); public static JsonNode getFieldNode(JsonNode node, String field) { if (node.get(field) != null) { return node.get(field); } return null; } public static String getField(JsonNode node, String field) { if (node.get(field) != null) { return node.get(field).textValue(); } return """"; } public static Integer getIntegerField(JsonNode node, String field) { if (node.get(field) != null) { return node.get(field).intValue(); } return null; } public static Long getLongField(JsonNode node, String field) { if (node.get(field) != null) { return node.get(field).longValue(); } return null; } public static Date getDateField(JsonNode node, String field) { String dateAsString; if (node.get(field) == null) { return null; } dateAsString = node.get(field).textValue(); try { return dateFormat.parse(dateAsString); } catch (ParseException e) { throw new RuntimeException(e); } } } " Add case reference for planning permissions,"<?php class PlanningApplication extends Module { const MAX_DISTANCE = 1; // In Km public $url = ""https://data.bathhacked.org/resource/uyh5-eygi.json""; function getData() { $aps = json_decode($this->fetch()); $relevant = array(); foreach($aps as $ap) { if(!property_exists($ap, 'locationtext')) { continue; } preg_match(Module::POSTCODE_REGEX, $ap->locationtext, $matches); // If we find the planning permission if(isset($matches[0])) { $apl = $this->getPostCodeLocation($matches[0]); // If we can convert it to a location if($apl) { $distance = $this->distance($apl[1], $apl[0], self::$postCodeLoc[1], self::$postCodeLoc[0], ""K""); // Add only planning applications in our area if($distance < self::MAX_DISTANCE) { $relevant[] = array( 'casedate' => $ap->casedate, 'casetext' => $ap->casetext, 'locationtext' => $ap->locationtext, 'banesstatus' => $ap->banesstatus, 'casereference' => $ap->casereference ); } } } } return $relevant; } } ?>","<?php class PlanningApplication extends Module { const MAX_DISTANCE = 1; // In Km public $url = ""https://data.bathhacked.org/resource/uyh5-eygi.json""; function getData() { $aps = json_decode($this->fetch()); $relevant = array(); foreach($aps as $ap) { if(!property_exists($ap, 'locationtext')) { continue; } preg_match(Module::POSTCODE_REGEX, $ap->locationtext, $matches); // If we find the planning permission if(isset($matches[0])) { $apl = $this->getPostCodeLocation($matches[0]); // If we can convert it to a location if($apl) { $distance = $this->distance($apl[1], $apl[0], self::$postCodeLoc[1], self::$postCodeLoc[0], ""K""); // Add only planning applications in our area if($distance < self::MAX_DISTANCE) { $relevant[] = array( 'casedate' => $ap->casedate, 'casetext' => $ap->casetext, 'locationtext' => $ap->locationtext, 'banesstatus' => $ap->banesstatus ); } } } } return $relevant; } } ?>" Remove unused group counts variable,"from collections import defaultdict import numpy as np from tmhmm.model import parse from tmhmm.hmm import viterbi, forward, backward __all__ = ['predict'] GROUP_NAMES = ('i', 'm', 'o') def predict(sequence, header, model_or_filelike, compute_posterior=True): if isinstance(model_or_filelike, tuple): model = model_or_filelike else: _, model = parse(open(model_or_filelike)) _, path = viterbi(sequence, *model) if compute_posterior: forward_table, constants = forward(sequence, *model) backward_table = backward(sequence, constants, *model) posterior = forward_table * backward_table _, _, _, char_map, label_map, name_map = model observations = len(sequence) states = len(name_map) table = np.zeros(shape=(observations, 3)) for i in range(observations): group_probs = defaultdict(float) for j in range(states): group = label_map[j].lower() group_probs[group] += posterior[i, j] for k, group in enumerate(GROUP_NAMES): table[i, k] = group_probs[group] return path, table/table.sum(axis=1, keepdims=True) return path ","from collections import Counter, defaultdict import numpy as np from tmhmm.model import parse from tmhmm.hmm import viterbi, forward, backward __all__ = ['predict'] GROUP_NAMES = ('i', 'm', 'o') def predict(sequence, header, model_or_filelike, compute_posterior=True): if isinstance(model_or_filelike, tuple): model = model_or_filelike else: _, model = parse(open(model_or_filelike)) _, path = viterbi(sequence, *model) if compute_posterior: forward_table, constants = forward(sequence, *model) backward_table = backward(sequence, constants, *model) posterior = forward_table * backward_table _, _, _, char_map, label_map, name_map = model observations = len(sequence) states = len(name_map) # just counts how many states there are per label group_counts = Counter(label_map.values()) table = np.zeros(shape=(observations, 3)) for i in range(observations): group_probs = defaultdict(float) for j in range(states): group = label_map[j].lower() group_probs[group] += posterior[i, j] for k, group in enumerate(GROUP_NAMES): table[i, k] = group_probs[group] return path, table/table.sum(axis=1, keepdims=True) return path " Add agency chain to Booking,"# Python 2 and 3 from __future__ import unicode_literals from gapipy.resources.checkin import Checkin from ..base import Resource from .agency_chain import AgencyChain from .document import Invoice, Document from .override import Override from .service import Service from .transaction import Payment, Refund class Booking(Resource): _resource_name = 'bookings' _is_parent_resource = True _as_is_fields = ['id', 'href', 'external_id', 'currency'] _price_fields = [ 'amount_owing', 'amount_paid', 'amount_pending', 'commission', 'tax_on_commission', ] _date_fields = [ 'date_closed', 'date_of_first_travel', 'date_of_last_travel', 'balance_due_date', ] _date_time_fields_utc = ['date_created', ] _resource_fields = [ ('agency', 'Agency'), ('agency_chain', AgencyChain), ('agent', 'Agent'), ('associated_agency', 'Agency'), ] @property def _resource_collection_fields(self): return [ ('services', Service), ('invoices', Invoice), ('payments', Payment), ('refunds', Refund), ('documents', Document), ('overrides', Override), ('checkins', Checkin), ] ","# Python 2 and 3 from __future__ import unicode_literals from gapipy.resources.checkin import Checkin from ..base import Resource from .transaction import Payment, Refund from .document import Invoice, Document from .override import Override from .service import Service class Booking(Resource): _resource_name = 'bookings' _is_parent_resource = True _as_is_fields = ['id', 'href', 'external_id', 'currency'] _price_fields = [ 'amount_owing', 'amount_paid', 'amount_pending', 'commission', 'tax_on_commission', ] _date_fields = [ 'date_closed', 'date_of_first_travel', 'date_of_last_travel', 'balance_due_date', ] _date_time_fields_utc = ['date_created', ] _resource_fields = [ ('agent', 'Agent'), ('agency', 'Agency'), ('associated_agency', 'Agency'), ] @property def _resource_collection_fields(self): return [ ('services', Service), ('invoices', Invoice), ('payments', Payment), ('refunds', Refund), ('documents', Document), ('overrides', Override), ('checkins', Checkin), ] " Fix the tags loading more than 5 tags.,"<?php if($_SERVER['REQUEST_METHOD'] == 'POST' && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') { require_once 'db-connect.inc.php'; $db = ConnectDb(); $stmt = $db->prepare(""SELECT NoteTags FROM note WHERE NoteComplete = 0"" ); $stmt->execute(); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); $result = ''; $tagList = array(); $checkbox = array(); foreach($rows as $item) { $tags = unserialize($item['NoteTags']); if(sizeof($tags) > 0 && $tags !== '') { foreach($tags as $tag) { if(!in_array($tag, $tagList)) { $tagList[] = $tag; // limit the pre-loaded tags to 5. if(5 >= count($tagList)) { $checkbox[] = '<div class=""checkbox""> <label> <input type=""checkbox"" name=""new-tag"" data-tag=""' . $tag . '"" value=""' . $tag . '""> ' . $tag . ' </label> </div>'; } } } } } foreach($checkbox as $tag) { echo $tag; } // change this to return JSON which can then be decoded server-side and will also populate an option box to pick which tag to show. } else { echo 'No direct access'; } ?>","<?php if($_SERVER['REQUEST_METHOD'] == 'POST' && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') { require_once 'db-connect.inc.php'; $db = ConnectDb(); $stmt = $db->prepare(""SELECT NoteTags FROM note WHERE NoteComplete = 0"" ); $stmt->execute(); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); $result = ''; $tagList = array(); $checkbox = array(); foreach($rows as $item) { $tags = unserialize($item['NoteTags']); if(sizeof($tags) > 0 && $tags !== '') { foreach($tags as $tag) { if(!in_array($tag, $tagList)) { $checkbox[] = '<div class=""checkbox""> <label> <input type=""checkbox"" name=""new-tag"" data-tag=""' . $tag . '"" value=""' . $tag . '""> ' . $tag . ' </label> </div>'; // limit the pre-loaded tags to 5. if(5 >= count($tagList)) { $tagList[] = $tag; } } } } } foreach($checkbox as $tag) { echo $tag; } // change this to return JSON which can then be decoded server-side and will also populate an option box to pick which tag to show. } else { echo 'No direct access'; } ?>" Fix for close always current modal,"Extension = window.Extension || {}; Extension.LayoutView = Marionette.LayoutView.extend({ /** * Removed default action on hash links * in order not to trigger router methods */ preventHashChange: function(event) { var $target = $(event.currentTarget); if (_.string.startsWith($target.attr('href'), '#')) { event.preventDefault(); } }, /** * Open a view in a modal * * Attach a view to modal region * and trigger modal initialization */ openModal: function(modalView, options) { var self = this; this.modal.show(modalView); $.magnificPopup.open(_.defaults({}, options, { items: { src: this.modal.$el, type: 'inline' }, /*modal: true,*/ midClick: true, callbacks: { open: function() { self.modal.$el.on(""click"", "".mfp-close, .mfp-inline-close"", function() { App.layout.closeModal(); }); self.modal.$el.on(""click"", ""a[href]"", function(event) { self.preventHashChange(event); }); }, close: function() { self.modal.currentView.destroy(); } } })); }, /** * Close current modal * * A modal view class can be passed to prevent closing the wrong modal */ closeModal: function(modalViewClass) { if (!modalViewClass || this.modal.currentView instanceof modalViewClass) { $.magnificPopup.close(); } } }); ","Extension = window.Extension || {}; Extension.LayoutView = Marionette.LayoutView.extend({ /** * Removed default action on hash links * in order not to trigger router methods */ preventHashChange: function(event) { var $target = $(event.currentTarget); if (_.string.startsWith($target.attr('href'), '#')) { event.preventDefault(); } }, /** * Open a view in a modal * * Attach a view to modal region * and trigger modal initialization */ openModal: function(modalView, options) { var self = this; this.modal.show(modalView); $.magnificPopup.open(_.defaults({}, options, { items: { src: this.modal.$el, type: 'inline' }, /*modal: true,*/ midClick: true, callbacks: { open: function() { self.modal.$el.on(""click"", "".mfp-close, .mfp-inline-close"", function() { App.layout.closeModal(); }); self.modal.$el.on(""click"", ""a[href]"", function(event) { self.preventHashChange(event); }); }, close: function() { modalView.destroy(); } } })); }, /** * Close current modal * * A modal view class can be passed to prevent closing the wrong modal */ closeModal: function(modalViewClass) { if (!modalViewClass || this.modal.currentView instanceof modalViewClass) { $.magnificPopup.close(); } } });" "Remove '@Override', to fix compile on JDK 1.5.","/* // Licensed to Julian Hyde under one or more contributor license // agreements. See the NOTICE file distributed with this work for // additional information regarding copyright ownership. // // Julian Hyde licenses this file to you under the Modified BSD License // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/BSD-3-Clause */ package sqlline; import java.sql.*; import sun.misc.*; /** * A signal handler for SqlLine which interprets Ctrl+C as a request to cancel * the currently executing query. Adapted from <a * href=""http://www.smotricz.com/kabutz/Issue043.html"">TJSN</a>. */ class SunSignalHandler implements SqlLineSignalHandler, SignalHandler { private DispatchCallback dispatchCallback; SunSignalHandler() { Signal.handle(new Signal(""INT""), this); } public void setCallback(DispatchCallback dispatchCallback) { this.dispatchCallback = dispatchCallback; } public void handle(Signal sig) { try { synchronized (this) { if (dispatchCallback != null) { dispatchCallback.forceKillSqlQuery(); dispatchCallback.setToCancel(); } } } catch (SQLException ex) { throw new RuntimeException(ex); } } } ","/* // Licensed to Julian Hyde under one or more contributor license // agreements. See the NOTICE file distributed with this work for // additional information regarding copyright ownership. // // Julian Hyde licenses this file to you under the Modified BSD License // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/BSD-3-Clause */ package sqlline; import java.sql.*; import sun.misc.*; /** * A signal handler for SqlLine which interprets Ctrl+C as a request to cancel * the currently executing query. Adapted from <a * href=""http://www.smotricz.com/kabutz/Issue043.html"">TJSN</a>. */ class SunSignalHandler implements SqlLineSignalHandler, SignalHandler { private DispatchCallback dispatchCallback; SunSignalHandler() { Signal.handle(new Signal(""INT""), this); } @Override public void setCallback(DispatchCallback dispatchCallback) { this.dispatchCallback = dispatchCallback; } @Override public void handle(Signal sig) { try { synchronized (this) { if (dispatchCallback != null) { dispatchCallback.forceKillSqlQuery(); dispatchCallback.setToCancel(); } } } catch (SQLException ex) { throw new RuntimeException(ex); } } } " "Set log level to info, fixed bug with map object","import logging import numpy as np import settings from models import Robby def evolve(): population = np.array([Robby() for i in range(0, settings.POPULATION)]) for gen in range(0, settings.GENERATIONS): for individual in population: individual.live() new_population = list() while len(new_population)<settings.POPULATION: father, mother = np.random.choice( population, size=2, p=get_relative_probabilities(population)) child1, child2 = father.mate(mother) new_population.append(child1) new_population.append(child2) population = new_population logging.info(""Generation {}: {}"".format( gen, max([r.get_fitness() for r in population]))) def get_relative_probabilities(population): pop_fitness = [r.get_fitness() for r in population] min_fitness = min(pop_fitness) max_fitness = max(pop_fitness) normalized = list( map( lambda x: normalize(x, min_fitness, max_fitness), pop_fitness ) ) total = sum(normalized) return list(map(lambda x: x/total, normalized)) def normalize(x, minf, maxf): return (x - minf) / (maxf - minf) if __name__=='__main__': logging.basicConfig(level=20) evolve() ","import logging import numpy as np import settings from models import Robby def evolve(): population = np.array([Robby() for i in range(0, settings.POPULATION)]) for gen in range(0, settings.GENERATIONS): for individual in population: individual.live() new_population = list() while len(new_population)<settings.POPULATION: father, mother = np.random.choice( population, size=2, p=get_relative_probabilities(population)) child1, child2 = father.mate(mother) new_population.append(child1) new_population.append(child2) population = new_population logging.info(""Generation {}: {}"".format( gen, max([r.get_fitness() for r in population]))) def get_relative_probabilities(population): pop_fitness = [r.get_fitness() for r in population] min_fitness = min(pop_fitness) max_fitness = max(pop_fitness) normalized = map(lambda x: normalize(x, min_fitness, max_fitness), pop_fitness) total = sum(normalized) return map(lambda x: x/total, normalized) def normalize(x, minf, maxf): return (x - minf) / (maxf - minf) if __name__=='__main__': logging.basicConfig(level=1) evolve() " Update vigenereDicitonaryHacker: fixed error reported in forum,"# Vigenère Cipher Dictionary Hacker # https://www.nostarch.com/crackingcodes/ (BSD Licensed) import detectEnglish, vigenereCipher, pyperclip def main(): ciphertext = """"""Tzx isnz eccjxkg nfq lol mys bbqq I lxcz."""""" hackedMessage = hackVigenereDictionary(ciphertext) if hackedMessage != None: print('Copying hacked message to clipboard:') print(hackedMessage) pyperclip.copy(hackedMessage) else: print('Failed to hack encryption.') def hackVigenereDictionary(ciphertext): fo = open('dictionary.txt') words = fo.readlines() fo.close() for word in words: word = word.strip() # Remove the newline at the end. decryptedText = vigenereCipher.decryptMessage(word, ciphertext) if detectEnglish.isEnglish(decryptedText, wordPercentage=40): # Check with user to see if the decrypted key has been found: print() print('Possible encryption break:') print('Key ' + str(word) + ': ' + decryptedText[:100]) print() print('Enter D for done, or just press Enter to continue breaking:') response = input('> ') if response.upper().startswith('D'): return decryptedText if __name__ == '__main__': main() ","# Vigenère Cipher Dictionary Hacker # https://www.nostarch.com/crackingcodes/ (BSD Licensed) import detectEnglish, vigenereCipher, pyperclip def main(): ciphertext = """"""Tzx isnz eccjxkg nfq lol mys bbqq I lxcz."""""" hackedMessage = hackVigenereDictionary(ciphertext) if hackedMessage != None: print('Copying hacked message to clipboard:') print(hackedMessage) pyperclip.copy(hackedMessage) else: print('Failed to hack encryption.') def hackVigenereDictionary(ciphertext): fo = open('dictionary.txt') words = fo.readlines() fo.close() for word in lines: word = word.strip() # Remove the newline at the end. decryptedText = vigenereCipher.decryptMessage(word, ciphertext) if detectEnglish.isEnglish(decryptedText, wordPercentage=40): # Check with user to see if the decrypted key has been found: print() print('Possible encryption break:') print('Key ' + str(word) + ': ' + decryptedText[:100]) print() print('Enter D for done, or just press Enter to continue breaking:') response = input('> ') if response.upper().startswith('D'): return decryptedText if __name__ == '__main__': main() " "Create a clone. This allows multiple values to be set, and it doesn't conflict with the global object.","(function(fs, path){ 'use strict'; // Resources global.__objectCache = {}; // Module module.exports = exports = { __objectCache: global.__objectCache, read: function(fileName){ fileName = path.resolve(fileName); var fileDataRaw = null, fileData = null; // Try searching cache: if (typeof this.__objectCache[fileName] !== 'undefined') { return JSON.parse(JSON.stringify(this.__objectCache[fileName])); } // Try reading file: try { fileDataRaw = fs.readFileSync(fileName); } catch (e) { throw {'type':'read', 'original':e}; } // Try parsing file data: try { fileData = JSON.parse(fileDataRaw); this.__objectCache[fileName] = fileData; } catch (e) { throw {'type':'parse', 'original':e}; } return fileData; }, purge: function(fileName){ fileName = path.resolve(fileName); if (typeof fileName !== 'undefined') { // Purge specific cache: this.__objectCache[fileName] = undefined; } else { // Purge all cache: for (var id in this.__objectCache) { this.__objectCache[id] = undefined; } } return true; } }; })(require('fs'), require('path')); ","(function(fs, path){ 'use strict'; // Resources global.__objectCache = {}; // Module module.exports = exports = { __objectCache: global.__objectCache, read: function(fileName){ fileName = path.resolve(fileName); var fileDataRaw = null, fileData = null; // Try searching cache: if (typeof this.__objectCache[fileName] !== 'undefined') { return this.__objectCache[fileName]; } // Try reading file: try { fileDataRaw = fs.readFileSync(fileName); } catch (e) { throw {'type':'read', 'original':e}; } // Try parsing file data: try { fileData = JSON.parse(fileDataRaw); this.__objectCache[fileName] = fileData; } catch (e) { throw {'type':'parse', 'original':e}; } return fileData; }, purge: function(fileName){ fileName = path.resolve(fileName); if (typeof fileName !== 'undefined') { // Purge specific cache: this.__objectCache[fileName] = undefined; } else { // Purge all cache: for (var id in this.__objectCache) { this.__objectCache[id] = undefined; } } return true; } }; })(require('fs'), require('path')); " Create the file if it doesn't exist,"<?php namespace Typidesign\Translations\Console\Commands; class AddTranslations extends AbstractTranslations { /** * The name and signature of the console command. */ protected $signature = 'translations:add {path : The file or directory containing the json encoded translations you want to merge.} {--force : Overwrite existing translations.}'; /** * The console command description. */ protected $description = 'Add translations strings found in a file or directory.'; /** * Execute the console command. */ public function handle() { foreach ($this->getFiles() as $file) { $targetDirectory = resource_path('lang'); $mainFile = $targetDirectory.'/'.$file->getBasename(); if ($this->files->missing($targetDirectory)) { $this->files->makeDirectory($targetDirectory); } if ($this->files->missing($mainFile)) { $this->files->copy($file->getPathname(), $mainFile); $this->info($mainFile.' created.'); continue; } $existingTranslations = $this->getTranslations($mainFile); $newTranslations = $this->getTranslations($file); if ($this->option('force')) { $translations = array_merge($existingTranslations, $newTranslations); } else { $translations = $existingTranslations + $newTranslations; } ksort($translations, SORT_STRING | SORT_FLAG_CASE); $this->put($mainFile, $translations); $this->info(count($translations) - count($existingTranslations).' translations added in '.$mainFile.'.'); } } } ","<?php namespace Typidesign\Translations\Console\Commands; class AddTranslations extends AbstractTranslations { /** * The name and signature of the console command. */ protected $signature = 'translations:add {path : The file or directory containing the json encoded translations you want to merge.} {--force : Overwrite existing translations.}'; /** * The console command description. */ protected $description = 'Add translations strings found in a file or directory.'; /** * Execute the console command. */ public function handle() { foreach ($this->getFiles() as $file) { $mainFile = resource_path('lang/'.basename($file)); $existingTranslations = $this->getTranslations($mainFile); $newTranslations = $this->getTranslations($file); if ($this->option('force')) { $translations = array_merge($existingTranslations, $newTranslations); } else { $translations = $existingTranslations + $newTranslations; } ksort($translations, SORT_STRING | SORT_FLAG_CASE); $this->put($mainFile, $translations); $this->info(count($translations) - count($existingTranslations).' translations added in '.$mainFile.'.'); } } } " Change order of test declarations,"module.exports = function( grunt ) { ""use strict""; grunt.initConfig({ bump: { options: { files: [ ""package.json"" ], // Commit commit: true, commitMessage: ""Release v%VERSION%"", commitFiles: [ ""package.json"" ], // Tag createTag: true, tagName: ""%VERSION%"", tagMessage: ""Version %VERSION%"", // Push push: true, pushTo: ""origin"" } }, jshint: { options: { jshintrc: "".jshintrc"" }, all: [ ""Gruntfile.js"", ""tasks/*.js"", ""test/*.js"" ] }, jscs: { src: ""<%= jshint.all %>"" }, nodeunit: { methods: ""test/methods.js"", enmasse: ""test/enmasse.js"" } }); // Load grunt tasks from NPM packages require( ""load-grunt-tasks"" )( grunt ); grunt.loadTasks( ""tasks"" ); grunt.registerTask( ""default"", [ ""jshint"", ""jscs"", ""nodeunit"" ] ); }; ","module.exports = function( grunt ) { ""use strict""; grunt.initConfig({ bump: { options: { files: [ ""package.json"" ], // Commit commit: true, commitMessage: ""Release v%VERSION%"", commitFiles: [ ""package.json"" ], // Tag createTag: true, tagName: ""%VERSION%"", tagMessage: ""Version %VERSION%"", // Push push: true, pushTo: ""origin"" } }, jshint: { options: { jshintrc: "".jshintrc"" }, all: [ ""Gruntfile.js"", ""tasks/*.js"", ""test/*.js"" ] }, jscs: { src: ""<%= jshint.all %>"" }, nodeunit: { enmasse: ""test/enmasse.js"", methods: ""test/methods.js"" } }); // Load grunt tasks from NPM packages require( ""load-grunt-tasks"" )( grunt ); grunt.loadTasks( ""tasks"" ); grunt.registerTask( ""default"", [ ""jshint"", ""jscs"", ""nodeunit"" ] ); }; " Fix assign member to the team,"import Ember from 'ember'; const { Route, RSVP } = Ember; export default Route.extend({ deactivate() { this.store.peekAll('team-member').forEach((team) => { if (team.get('isNew')) { this.store.deleteRecord(team); } }); }, actions: { assignMember(member) { const flashMessages = Ember.get(this, 'flashMessages'); return member.save().then(() => { flashMessages.success(member.get('name')+' has been assigned to the team'); }).catch(() => { member.rollback(); flashMessages.danger('Unable to assign member to the team'); }); }, removeMember(member) { const flashMessages = Ember.get(this, 'flashMessages'); return member.destroyRecord().then(() => { flashMessages.success(member.get('name')+' has been removed from the team'); }).catch(() => { member.rollback(); flashMessages.danger('Unable to remove member from the team'); }); } }, model: function (params) { const store = this.store; const teamId = params.id; const tournament = this.modelFor('tournament'); return RSVP.hash({ team: store.find('team', teamId), matches: store.query('match', {tournamentId: tournament.get('id'), teamId}), teamMembers: store.query('team-member', {teamId}) }).then((hash) => { hash.team.set('teamMembers', hash.teamMembers); return hash; }); } }); ","import Ember from 'ember'; const { Route, RSVP } = Ember; export default Route.extend({ deactivate() { this.store.peekAll('team-member').forEach((team) => { if (team.get('isNew')) { this.store.deleteRecord(team); } }); }, actions: { assignMember(member) { const flashMessages = Ember.get(this, 'flashMessages'); return member.save().then(() => { this.currentModel.get('teamMembers').addObject(member); flashMessages.success(member.get('name')+' has been assigned to the team'); }).catch(() => { member.rollback(); flashMessages.danger('Unable to assign member to the team'); }); }, removeMember(member) { const flashMessages = Ember.get(this, 'flashMessages'); return member.destroyRecord().then(() => { flashMessages.success(member.get('name')+' has been removed from the team'); }).catch(() => { member.rollback(); flashMessages.danger('Unable to remove member from the team'); }); } }, model: function (params) { const store = this.store; const teamId = params.id; const tournament = this.modelFor('tournament'); return RSVP.hash({ team: store.find('team', teamId), matches: store.query('match', {tournamentId: tournament.get('id'), teamId}), teamMembers: store.query('team-member', {teamId}) }).then((hash) => { hash.team.set('teamMembers', hash.teamMembers); return hash; }); } }); " Fix error determining current version in other working directories.,"from __future__ import absolute_import __author__ = 'katharine' import os import subprocess from pebble_tool.exceptions import MissingSDK from pebble_tool.util import get_persist_dir def sdk_path(): path = os.getenv('PEBBLE_SDK_PATH', None) or os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..')) if not os.path.exists(path): raise MissingSDK(""SDK unavailable; can't run this command."") return path def sdk_version(): try: from . import version return version.version_string except ImportError: here = os.path.dirname(__file__) try: return subprocess.check_output([""git"", ""describe""], cwd=here, stderr=subprocess.STDOUT).strip() except subprocess.CalledProcessError as e: if e.returncode == 128: try: return 'g{}'.format(subprocess.check_output([""git"", ""rev-parse"", ""--short"", ""HEAD""], cwd=here, stderr=subprocess.STDOUT)).strip() except subprocess.CalledProcessError as e: pass return 'unknown' def get_sdk_persist_dir(platform): dir = os.path.join(get_persist_dir(), sdk_version(), platform) if not os.path.exists(dir): os.makedirs(dir) return dir def add_arm_tools_to_path(self, args): os.environ['PATH'] += "":{}"".format(os.path.join(self.sdk_path(args), ""arm-cs-tools"", ""bin""))","from __future__ import absolute_import __author__ = 'katharine' import os import subprocess from pebble_tool.exceptions import MissingSDK from pebble_tool.util import get_persist_dir def sdk_path(): path = os.getenv('PEBBLE_SDK_PATH', None) or os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..')) if not os.path.exists(path): raise MissingSDK(""SDK unavailable; can't run this command."") return path def sdk_version(): try: from . import version return version.version_string except ImportError: try: return subprocess.check_output([""git"", ""describe""], stderr=subprocess.STDOUT).strip() except subprocess.CalledProcessError as e: if e.returncode == 128: return 'g{}'.format(subprocess.check_output([""git"", ""rev-parse"", ""--short"", ""HEAD""], stderr=subprocess.STDOUT)).strip() else: return 'unknown' def get_sdk_persist_dir(platform): dir = os.path.join(get_persist_dir(), sdk_version(), platform) if not os.path.exists(dir): os.makedirs(dir) return dir def add_arm_tools_to_path(self, args): os.environ['PATH'] += "":{}"".format(os.path.join(self.sdk_path(args), ""arm-cs-tools"", ""bin""))" Mark updates pending at boot so initial render is performed,"'use strict'; var postal = require('postal'); var raf = require('raf'); var FluzoStore = require('fluzo-store')(postal); var fluzo_channel = postal.channel('fluzo'); var render_pending = true; var render_suscriptions = []; var updating = false; var Fluzo = { Store: FluzoStore, action: FluzoStore.action, clearRenderRequests: function () { render_pending = false; }, requestRender: function () { render_pending = true; }, onRender: function (cb) { render_suscriptions.push(cb); var index = render_suscriptions.length - 1; return function () { render_suscriptions.splice(index, 1); }; }, renderIfRequested: function (delta) { if (render_pending) { var now = Date.now(); render_suscriptions.forEach(function (cb) { cb(now, delta); }); this.clearRenderRequests(); } }, startUpdating: function () { if (!updating) { updating = true; (function tick(delta) { if (updating) { raf(tick); } Fluzo.renderIfRequested(delta); })(0); } }, stopUpdating: function () { updating = false; } }; fluzo_channel.subscribe('store.changed.*', Fluzo.requestRender); module.exports = Fluzo; ","'use strict'; var postal = require('postal'); var raf = require('raf'); var FluzoStore = require('fluzo-store')(postal); var fluzo_channel = postal.channel('fluzo'); var render_pending = false; var render_suscriptions = []; var updating = false; var Fluzo = { Store: FluzoStore, action: FluzoStore.action, clearRenderRequests: function () { render_pending = false; }, requestRender: function () { render_pending = true; }, onRender: function (cb) { render_suscriptions.push(cb); var index = render_suscriptions.length - 1; return function () { render_suscriptions.splice(index, 1); }; }, renderIfRequested: function (delta) { if (render_pending) { var now = Date.now(); render_suscriptions.forEach(function (cb) { cb(now, delta); }); this.clearRenderRequests(); } }, startUpdating: function () { if (!updating) { updating = true; (function tick(delta) { if (updating) { raf(tick); } Fluzo.renderIfRequested(delta); })(0); } }, stopUpdating: function () { updating = false; } }; fluzo_channel.subscribe('store.changed.*', Fluzo.requestRender); module.exports = Fluzo; " Allow empty commit messages if explictly specified.,"from types import SimpleNamespace class ChangeTemplate(SimpleNamespace): # orig_hash do_commit = True msg = None datetime = None author = None class RewriteMixin(): ChangeTemplate = ChangeTemplate def rewrite_active_branch(self, base_commit, commit_chain): branch_name = self.get_current_branch_name() # Detach HEAD to base commit. self.checkout_ref(base_commit) # Apply each commit to HEAD in order. try: for commit in commit_chain: self.git( ""cherry-pick"", ""--allow-empty"", ""--allow-empty-message"", ""--no-commit"", commit.orig_hash ) # If squashing one commit into the next, do_commit should be # False so that it's changes are included in the next commit. if commit.do_commit: self.git( ""commit"", ""--author"", commit.author, ""--date"", commit.datetime, ""-F"", ""-"", stdin=commit.msg ) self.git(""branch"", ""-f"", branch_name, ""HEAD"") except Exception as e: raise e finally: # Whether on success or failure, always re-checkout the branch. On success, # this will be the re-written branch. On failure, this will be the original # branch (since re-defining the branch ref is the last step). self.git(""checkout"", branch_name) ","from types import SimpleNamespace class ChangeTemplate(SimpleNamespace): # orig_hash do_commit = True msg = None datetime = None author = None class RewriteMixin(): ChangeTemplate = ChangeTemplate def rewrite_active_branch(self, base_commit, commit_chain): branch_name = self.get_current_branch_name() # Detach HEAD to base commit. self.checkout_ref(base_commit) # Apply each commit to HEAD in order. try: for commit in commit_chain: self.git( ""cherry-pick"", ""--allow-empty"", ""--no-commit"", commit.orig_hash ) # If squashing one commit into the next, do_commit should be # False so that it's changes are included in the next commit. if commit.do_commit: self.git( ""commit"", ""--author"", commit.author, ""--date"", commit.datetime, ""-F"", ""-"", stdin=commit.msg ) self.git(""branch"", ""-f"", branch_name, ""HEAD"") except Exception as e: raise e finally: # Whether on success or failure, always re-checkout the branch. On success, # this will be the re-written branch. On failure, this will be the original # branch (since re-defining the branch ref is the last step). self.git(""checkout"", branch_name) " Add module as unit test dependency,"const path = require(""path""); module.exports = function(config) { config.set({ frameworks: [""jasmine""], proxies: { '/lib/css/': '/base/lib/css' }, files: [ { pattern: ""./src/**/*.js"", type: ""module"" }, { pattern: ""./node_modules/@browser-modules/typescript.dictionary/lib/dictionary.js"", type: ""module"" }, { pattern: ""./test/**/*.js"", type: ""module"" }, { pattern: ""./lib/css/*.css"", type: 'css'} ], preprocessors: { ""src/**/!(*.test).js"": [""karma-coverage-istanbul-instrumenter""] }, reporters: [""spec"",""junit"", ""coverage-istanbul""], junitReporter: { outputDir: './output', outputFile: undefined, suite: '', useBrowserName: false, nameFormatter: undefined, classNameFormatter: undefined, properties: {}, xmlVersion: null }, coverageIstanbulInstrumenter: { esModules: true }, coverageIstanbulReporter: { reports: [""html"", ""text"", ""lcovonly""], dir: path.join(__dirname, ""coverage""), skipFilesWithNoCoverage: true }, browsers: [""ChromeHeadless""], singleRun: true }); }; ","const path = require(""path""); module.exports = function(config) { config.set({ frameworks: [""jasmine""], proxies: { '/lib/css/': '/base/lib/css' }, files: [ { pattern: ""./src/**/*.js"", type: ""module"" }, { pattern: ""./test/**/*.js"", type: ""module"" }, { pattern: ""./lib/css/*.css"", type: 'css'} ], preprocessors: { ""src/**/!(*.test).js"": [""karma-coverage-istanbul-instrumenter""] }, reporters: [""spec"",""junit"", ""coverage-istanbul""], junitReporter: { outputDir: './output', outputFile: undefined, suite: '', useBrowserName: false, nameFormatter: undefined, classNameFormatter: undefined, properties: {}, xmlVersion: null }, coverageIstanbulInstrumenter: { esModules: true }, coverageIstanbulReporter: { reports: [""html"", ""text"", ""lcovonly""], dir: path.join(__dirname, ""coverage""), skipFilesWithNoCoverage: true }, browsers: [""ChromeHeadless""], singleRun: true }); }; " Add dev suffix to development DB name,"'use strict'; module.exports = { development: { client: 'pg', connection: { database: 'sg_db_dev', user: 'postgres', password: 'postgres', charset: 'utf8' }, migrations: { directory: __dirname + '/db/migrations' }, seeds: { directory: __dirname + '/db/seeds/development' } }, test: { client: 'pg', connection: { database: 'sg_db_test', user: 'postgres', password: 'postgres', charset: 'utf8' }, migrations: { directory: __dirname + '/db/migrations' }, seeds: { directory: __dirname + '/db/seeds/test' } }, production: { client: 'pg', connection: process.env.DATABASE_URL, pool: { min: 2, max: 10 }, migrations: { directory: __dirname + '/db/migrations' }, seeds: { directory: __dirname + '/db/seeds/production' } } };","'use strict'; module.exports = { development: { client: 'pg', connection: { database: 'sg_db', user: 'postgres', password: 'postgres', charset: 'utf8' }, migrations: { directory: __dirname + '/db/migrations' }, seeds: { directory: __dirname + '/db/seeds/development' } }, test: { client: 'pg', connection: { database: 'sg_db_test', user: 'postgres', password: 'postgres', charset: 'utf8' }, migrations: { directory: __dirname + '/db/migrations' }, seeds: { directory: __dirname + '/db/seeds/test' } }, production: { client: 'pg', connection: process.env.DATABASE_URL, pool: { min: 2, max: 10 }, migrations: { directory: __dirname + '/db/migrations' }, seeds: { directory: __dirname + '/db/seeds/production' } } };" Add missing test for Left::ap,"<?php namespace PhpFp\Either\Test; use PhpFp\Either\Either; use PhpFp\Either\Constructor\{Left, Right}; class ApTest extends \PHPUnit_Framework_TestCase { public function testApParameterCount() { $count = (new \ReflectionMethod('PhpFp\Either\Constructor\Left::ap')) ->getNumberOfParameters(); $this->assertEquals($count, 1, 'Left::ap takes one parameter.' ); $count = (new \ReflectionMethod('PhpFp\Either\Constructor\Right::ap')) ->getNumberOfParameters(); $this->assertEquals($count, 1, 'Right::ap takes one parameter.' ); } public function testAp() { $addTwo = Either::of( function ($x) { return $x + 2; } ); $id = function ($x) { return $x; }; $a = Either::of(5); $b = new Left(4); $this->assertEquals( $addTwo ->ap($a) ->either($id, $id), 7, 'Applies to a Right.' ); $this->assertEquals( $addTwo->ap($b)->either($id, $id), 4, 'Applies to a Left.' ); $subOne = new Left( function ($x) { return $x - 1; } ); $this->assertEquals( $subOne->ap($a)->either($id, $id), 5, 'Does not apply to a Right.' ); $this->assertEquals( $subOne->ap($b)->either($id, $id), 4, 'Does not apply to a Left.' ); } } ","<?php namespace PhpFp\Either\Test; use PhpFp\Either\Either; use PhpFp\Either\Constructor\{Left, Right}; class ApTest extends \PHPUnit_Framework_TestCase { public function testApParameterCount() { $count = (new \ReflectionMethod('PhpFp\Either\Constructor\Left::ap')) ->getNumberOfParameters(); $this->assertEquals($count, 1, 'Left::ap takes one parameter.' ); $count = (new \ReflectionMethod('PhpFp\Either\Constructor\Right::ap')) ->getNumberOfParameters(); $this->assertEquals($count, 1, 'Right::ap takes one parameter.' ); } public function testAp() { $addTwo = Either::of( function ($x) { return $x + 2; } ); $id = function ($x) { return $x; }; $a = Either::of(5); $b = new Left(4); $this->assertEquals( $addTwo ->ap($a) ->either($id, $id), 7, 'Applies to a Right.' ); $this->assertEquals( $addTwo->ap($b)->either($id, $id), 4, 'Applies to a Left.' ); } } " Refactor: Change order of 'makeDrinks' function in order to have a better readability,"public class Logic { public final static String STICK = ""0""; public final static String MESSAGE_CODE = ""M""; public String makeDrink(Drink drink, int nbOfSugars, double amount) { if(amount >= drink.getPrice()) { return parseToDrinkMakerProtocol(drink, nbOfSugars); } return ""Need "" + String.valueOf(drink.getPrice() - amount); } public String parseToCustomer(String commandFromDrinkMaker) { String[] commands = commandFromDrinkMaker.split("":""); if(commands.length == 2 && MESSAGE_CODE.equals(commands[0])) { return commands[1]; } return """"; } public String parseToDrinkMakerProtocol(Drink drink, int nbOfSugars) { return drink.getCode() + "":"" + sugarCode(nbOfSugars) + "":"" + stickCode(nbOfSugars); } private String sugarCode(int nbOfSugars) { return hasSugars(nbOfSugars)? String.valueOf(nbOfSugars) : """"; } private String stickCode(int nbOfSugars) { return hasSugars(nbOfSugars)? STICK : """"; } private boolean hasSugars(int nbOfSugars) { return nbOfSugars > 0; } } ","public class Logic { public final static String STICK = ""0""; public final static String MESSAGE_CODE = ""M""; public String parseToCustomer(String commandFromDrinkMaker) { String[] commands = commandFromDrinkMaker.split("":""); if(commands.length == 2 && MESSAGE_CODE.equals(commands[0])) { return commands[1]; } return """"; } public String parseToDrinkMakerProtocol(Drink drink, int nbOfSugars) { return drink.getCode() + "":"" + sugarCode(nbOfSugars) + "":"" + stickCode(nbOfSugars); } private String sugarCode(int nbOfSugars) { return hasSugars(nbOfSugars)? String.valueOf(nbOfSugars) : """"; } private String stickCode(int nbOfSugars) { return hasSugars(nbOfSugars)? STICK : """"; } private boolean hasSugars(int nbOfSugars) { return nbOfSugars > 0; } public String makeDrink(Drink drink, int nbOfSugars, double amountOfMoneyGiven) { if(amountOfMoneyGiven >= drink.getPrice()) { return parseToDrinkMakerProtocol(drink, nbOfSugars); } return ""Need "" + String.valueOf(drink.getPrice() - amountOfMoneyGiven); } } " Fix remove last element from select box,"$.fn.productAutocomplete = function (options) { 'use strict' // Default options options = options || {} var multiple = typeof (options.multiple) !== 'undefined' ? options.multiple : true function formatProduct (product) { return Select2.util.escapeMarkup(product.name) } function formatProductList(products) { var formatted_data = $.map(products, function (obj) { var item = { id: obj.id, text: obj.name } return item }); return formatted_data } this.select2({ multiple: true, minimumInputLength: 3, ajax: { url: Spree.routes.products_api, dataType: 'json', data: function (params) { return { q: { name_or_master_sku_cont: params.term }, m: 'OR', token: Spree.api_key } }, processResults: function(data) { var products = data.products ? data.products : [] var results = formatProductList(products) return { results: results } } }, templateSelection: function(data, container) { return data.text } }).on(""select2:unselect"", function (e) { if($(this).select2('data').length == 0) { $('<input>').attr({ type: 'hidden', name: this.name, value: '', id: this.id }).appendTo('form.edit_promotion') } }).on('select2:select', function(e) { $('input#'+this.id).remove() }) } $(document).ready(function () { $('.product_picker').productAutocomplete() }) ","$.fn.productAutocomplete = function (options) { 'use strict' // Default options options = options || {} var multiple = typeof (options.multiple) !== 'undefined' ? options.multiple : true function formatProduct (product) { return Select2.util.escapeMarkup(product.name) } function formatProductList(products) { var formatted_data = $.map(products, function (obj) { var item = { id: obj.id, text: obj.name } return item }); return formatted_data } this.select2({ multiple: true, minimumInputLength: 3, ajax: { url: Spree.routes.products_api, dataType: 'json', data: function (params) { var query = { q: { name_or_master_sku_cont: params.term }, m: 'OR', token: Spree.api_key } return query; }, processResults: function(data) { var products = data.products ? data.products : [] var results = formatProductList(products) return { results: results } } }, templateSelection: function(data, container) { return data.text } }) } $(document).ready(function () { $('.product_picker').productAutocomplete() }) " Use real children for scrollview,"'use strict'; angular.module('integrationApp') .directive('faScrollView', function (famous) { return { template: '<div></div>', restrict: 'E', transclude: true, link: function postLink(scope, element, attrs) { }, compile: function(tElem, tAttrs, transclude){ return { pre: function(scope, element, attrs){ var ScrollView = famous[""famous/views/scrollview""]; var ViewSequence = famous['famous/core/viewsequence']; var Surface = famous['famous/core/surface']; var surfaces = new ViewSequence(); for(var i = 0; i < 50; i++) { surfaces.push(new Surface({content: 'Item ' + i, size:[100, 20]})); } var _children = []; console.log(""surfaces"", surfaces) scope.view = new ScrollView({ itemSpacing: 1 }); window.Engine.pipe(scope.view); scope.$on('registerChild', function(evt, data){ if(evt.targetScope.$id != scope.$id){ console.log(""scroll view registered"", data); _children.push(data.view); scope.view.sequenceFrom(_children); evt.stopPropagation(); }; }); scope.modifier = {}; }, post: function(scope, element, attrs){ transclude(scope, function(clone) { element.find('div').append(clone); }); scope.$emit('registerChild', {view: scope.view, mod: scope.modifier}); } }; }, scope: {} }; }); ","'use strict'; angular.module('integrationApp') .directive('faScrollView', function (famous) { return { template: '<div></div>', restrict: 'E', transclude: true, link: function postLink(scope, element, attrs) { }, compile: function(tElem, tAttrs, transclude){ return { pre: function(scope, element, attrs){ var ScrollView = famous[""famous/views/scrollview""]; var ViewSequence = famous['famous/core/viewsequence']; var Surface = famous['famous/core/surface']; var surfaces = new ViewSequence(); for(var i = 0; i < 50; i++) { surfaces.push(new Surface({content: 'Item ' + i, size:[100, 20]})); } console.log(""surfaces"", surfaces) scope.view = new ScrollView({ itemSpacing: 1 }); scope.view.sequenceFrom(surfaces); window.Engine.pipe(scope.view); scope.$on('registerChild', function(evt, data){ if(evt.targetScope.$id != scope.$id){ console.log(""scroll view registered"", data); evt.stopPropagation(); }; }); scope.modifier = {}; }, post: function(scope, element, attrs){ transclude(scope, function(clone) { element.find('div').append(clone); }); scope.$emit('registerChild', {view: scope.view, mod: scope.modifier}); } }; }, scope: {} }; }); " "Change Choose Document form element to not required PW: made this change so I could use this form field in the tree view","<?php namespace CftfBundle\Form\Type; use Doctrine\ORM\EntityRepository; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class LsDocListType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('lsDoc', EntityType::class, [ 'label' => 'Choose Document', 'choice_label' => 'title', 'required' => false, 'multiple' => false, 'class' => 'CftfBundle\Entity\LsDoc', 'query_builder' => function (EntityRepository $er) { return $er->createQueryBuilder('d') ->orderBy('d.title', 'ASC'); } ]) ; } /** * @param OptionsResolver $resolver */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'ajax' => false, ]); } } ","<?php namespace CftfBundle\Form\Type; use Doctrine\ORM\EntityRepository; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class LsDocListType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('lsDoc', EntityType::class, [ 'label' => 'Choose Document', 'choice_label' => 'title', 'required' => true, 'multiple' => false, 'class' => 'CftfBundle\Entity\LsDoc', 'query_builder' => function (EntityRepository $er) { return $er->createQueryBuilder('d') ->orderBy('d.title', 'ASC'); } ]) ; } /** * @param OptionsResolver $resolver */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'ajax' => false, ]); } } " Update with unauthorised redirect on 403.,"var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); var jwt = require('jsonwebtoken'); var config = require('../config.js'); var User = require('../models/user.js'); router.use(function(req, res, next) { var token = req.body.token || req.query.token || req.headers['x-access-token']; if(token) { jwt.verify(token, 'supersecret', function(err, decoded) { if(err) { return res.json({ success: false, message: 'Failed to authenticate' }); } else { req.decoded = decoded; next(); } }); } else { return res.render('unauthorised', { success: false, message: 'No token provided' }) } }); /* GET users listing. */ router.get('/', function(req, res, next) { User.find({}, function(err, users) { res.json(users); }); }); module.exports = router; ","var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); var jwt = require('jsonwebtoken'); var config = require('../config.js'); var User = require('../models/user.js'); router.use(function(req, res, next) { var token = req.body.token || req.query.token || req.headers['x-access-token']; if(token) { jwt.verify(token, 'supersecret', function(err, decoded) { if(err) { return res.json({ success: false, message: 'Failed to authenticate' }); } else { req.decoded = decoded; next(); } }); } else { return res.status(403).send({ success: false, message: 'No token provided' }); } }); /* GET users listing. */ router.get('/', function(req, res, next) { User.find({}, function(err, users) { res.json(users); }); }); module.exports = router; " Change name of results array.,"# -*- coding: utf-8 -*- # paramrunner.py # Run findparams on linde model and save results import helpers import findparams import tables import numpy as np savedir = ""/home/ith/results/"" savefile = ""linde-params.hf5"" WMAP5PIVOT = np.array([5.25e-60]) lindefx = {""vars"":[""mass"",""lambda""], ""values"": [np.linspace(4.9e-8,6e-8), np.linspace(5e-14, 1.6e-13)], ""pivotk"":WMAP5PIVOT, ""pot"": ""linde"", ""ystart"": np.array([25.0, -1.0, 0.0, 1.0, 0, 1.0, 0])} def run_and_save_model(sf=None, fx=None, sd=None): """"""Run linde model and save results."""""" if sf is None: sf = savefile if sd is None: sd = savedir helpers.ensurepath(sd) if fx is None: fx = lindefx results = findparams.param_vs_spectrum(fx) try: rfile = tables.openFile(sd + sf, ""w"") rfile.createArray(rfile.root, ""params_results"", results, ""Model parameter search results"") print ""Results saved in %s"" % str(sd + sf) finally: rfile.close() if __name__ == ""__main__"": run_linde_model()","# -*- coding: utf-8 -*- # paramrunner.py # Run findparams on linde model and save results import helpers import findparams import tables import numpy as np savedir = ""/home/ith/results/"" savefile = ""linde-params.hf5"" WMAP5PIVOT = np.array([5.25e-60]) lindefx = {""vars"":[""mass"",""lambda""], ""values"": [np.linspace(4.9e-8,6e-8), np.linspace(5e-14, 1.6e-13)], ""pivotk"":WMAP5PIVOT, ""pot"": ""linde"", ""ystart"": np.array([25.0, -1.0, 0.0, 1.0, 0, 1.0, 0])} def run_and_save_model(sf=None, fx=None, sd=None): """"""Run linde model and save results."""""" if sf is None: sf = savefile if sd is None: sd = savedir helpers.ensurepath(sd) if fx is None: fx = lindefx results = findparams.param_vs_spectrum(fx) try: rfile = tables.openFile(sd + sf, ""w"") rfile.createArray(rfile.root, ""params-results"", results, ""Model parameter search results"") print ""Results saved in %s"" % str(sd + sf) finally: rfile.close() if __name__ == ""__main__"": run_linde_model()" "Allow for the addition of admin assets I think the `BuildClientView` event should ultimately be split into two separate events for the forum/admin clients, but this is fine for now.","<?php namespace Flarum\Events; use Flarum\Support\ClientAction; use Flarum\Support\ClientView; use Flarum\Forum\Actions\ClientAction as ForumClientAction; use Flarum\Admin\Actions\ClientAction as AdminClientAction; class BuildClientView { /** * @var ClientAction */ public $action; /** * @var ClientView */ public $view; /** * @var array */ public $keys; /** * @param ClientAction $action * @param ClientView $view * @param array $keys */ public function __construct($action, $view, &$keys) { $this->action = $action; $this->view = $view; $this->keys = &$keys; } public function forumAssets($files) { if ($this->action instanceof ForumClientAction) { $this->view->getAssets()->addFiles((array) $files); } } public function forumBootstrapper($bootstrapper) { if ($this->action instanceof ForumClientAction) { $this->view->addBootstrapper($bootstrapper); } } public function forumTranslations(array $keys) { if ($this->action instanceof ForumClientAction) { foreach ($keys as $key) { $this->keys[] = $key; } } } public function adminAssets($files) { if ($this->action instanceof AdminClientAction) { $this->view->getAssets()->addFiles((array) $files); } } public function adminBootstrapper($bootstrapper) { if ($this->action instanceof AdminClientAction) { $this->view->addBootstrapper($bootstrapper); } } } ","<?php namespace Flarum\Events; use Flarum\Support\ClientAction; use Flarum\Support\ClientView; use Flarum\Forum\Actions\ClientAction as ForumClientAction; class BuildClientView { /** * @var ClientAction */ public $action; /** * @var ClientView */ public $view; /** * @var array */ public $keys; /** * @param ClientAction $action * @param ClientView $view * @param array $keys */ public function __construct($action, $view, &$keys) { $this->action = $action; $this->view = $view; $this->keys = &$keys; } public function forumAssets($files) { if ($this->action instanceof ForumClientAction) { $this->view->getAssets()->addFiles((array) $files); } } public function forumBootstrapper($bootstrapper) { if ($this->action instanceof ForumClientAction) { $this->view->addBootstrapper($bootstrapper); } } public function forumTranslations(array $keys) { if ($this->action instanceof ForumClientAction) { foreach ($keys as $key) { $this->keys[] = $key; } } }} " Add search functionality to global settings,"(function(cloudStack) { cloudStack.sections['global-settings'] = { title: 'Global Settings', id: 'global-settings', listView: { label: 'Global Settings', actions: { edit: { label: 'Change value', action: function(args) { var name = args.data.jsonObj.name; var value = args.data.value; $.ajax({ url: createURL( 'updateConfiguration&name=' + name + '&value=' + value ), dataType: 'json', async: true, success: function(json) { var item = json.updateconfigurationresponse.configuration; args.response.success({data: item}); }, error: function(json) { args.response.error({ message: $.parseJSON(json.responseText).updateconfigurationresponse.errortext }); } }); } } }, fields: { name: { label: 'Name', id: true }, description: { label: 'Description' }, value: { label: 'Value', editable: true } }, dataProvider: function(args) { var data = { page: args.page, pagesize: pageSize }; if (args.filterBy.search.value) { data.name = args.filterBy.search.value; } $.ajax({ url: createURL('listConfigurations'), data: data, dataType: ""json"", async: true, success: function(json) { var items = json.listconfigurationsresponse.configuration; args.response.success({ data: items }); } }); } } }; })(cloudStack); ","(function(cloudStack) { cloudStack.sections['global-settings'] = { title: 'Global Settings', id: 'global-settings', listView: { label: 'Global Settings', actions: { edit: { label: 'Change value', action: function(args) { var name = args.data.jsonObj.name; var value = args.data.value; $.ajax({ url: createURL( 'updateConfiguration&name=' + name + '&value=' + value ), dataType: 'json', async: true, success: function(json) { var item = json.updateconfigurationresponse.configuration; args.response.success({data: item}); }, error: function(json) { args.response.error({ message: $.parseJSON(json.responseText).updateconfigurationresponse.errortext }); } }); } } }, fields: { name: { label: 'Name', id: true }, description: { label: 'Description' }, value: { label: 'Value', editable: true } }, dataProvider: function(args) { $.ajax({ url: createURL(""listConfigurations&page="" + args.page + ""&pagesize="" + pageSize), dataType: ""json"", async: true, success: function(json) { var items = json.listconfigurationsresponse.configuration; args.response.success({ data: items }); } }); } } }; })(cloudStack); " Remove imports from stupid C module.,"import sys, os from setuptools import setup from pymantic import version setup(name='pymantic', version=version, description=""Semantic Web and RDF library for Python"", long_description="""""""""""", classifiers=['Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Text Processing :: Markup', ], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='RDF N3 Turtle Semantics Web3.0', author='Gavin Carothers, Nick Pilon', author_email='gavin@carothers.name, npilon@gmail.com', url='http://github.com/oreillymedia/pymantic', license='BSD', packages=['pymantic'], include_package_data=True, zip_safe=False, test_suite='nose.collector', install_requires=[ 'httplib2', 'lxml', 'mock_http', 'pytz', 'simplejson', 'lepl' ], entry_points="""""" # -*- Entry points: -*- """""", scripts = [ 'pymantic/scripts/named_graph_to_nquads', ], ) ","import sys, os try: import Cython except ImportError: pass from setuptools import setup from pymantic import version import setupinfo setup(name='pymantic', version=version, description=""Semantic Web and RDF library for Python"", long_description="""""""""""", classifiers=['Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Text Processing :: Markup', ], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='RDF N3 Turtle Semantics Web3.0', author='Gavin Carothers, Nick Pilon', author_email='gavin@carothers.name, npilon@gmail.com', url='http://github.com/oreillymedia/pymantic', license='BSD', packages=['pymantic'], include_package_data=True, zip_safe=False, test_suite='nose.collector', install_requires=[ 'httplib2', 'lxml', 'mock_http', 'pytz', 'simplejson', 'lepl' ], entry_points="""""" # -*- Entry points: -*- """""", scripts = [ 'pymantic/scripts/named_graph_to_nquads', ], #Ignoring unfinished C module #ext_modules = setupinfo.ext_modules(), #**setupinfo.extra_setup_args() ) " "Add capbility to render value as return on standard js render signature. Fix cs and doc blocks.","<?php namespace Yajra\Datatables\Html; use Illuminate\Support\Fluent; /** * Class Column * * @package Yajra\Datatables\Html * @see https://datatables.net/reference/option/ for possible columns option */ class Column extends Fluent { /** * @param array $attributes */ public function __construct($attributes = []) { $attributes['orderable'] = isset($attributes['orderable']) ? $attributes['orderable'] : true; $attributes['searchable'] = isset($attributes['searchable']) ? $attributes['searchable'] : true; // Allow methods override attribute value foreach ($attributes as $attribute => $value) { $method = 'parse' . ucfirst(strtolower($attribute)); if (method_exists($this, $method)) { $attributes[$attribute] = $this->$method($value); } } parent::__construct($attributes); } /** * Parse render attribute. * * @param \Closure|string $value * @return string|null */ public function parseRender($value) { $view = app('view'); if (is_callable($value)) { return value($value); } elseif ($view->exists($value)) { return $view->make($value)->render(); } return $value ? $this->parseRenderAsString($value) : null; } /** * Display render value as is. * * @param string $value * @return string */ private function parseRenderAsString($value) { return ""function(data,type,full,meta){return $value;}""; } } ","<?php namespace Yajra\Datatables\Html; use Illuminate\Support\Fluent; /** * Class Column * * @package Yajra\Datatables\Html * @see https://datatables.net/reference/option/ for possible columns option */ class Column extends Fluent { /** * @param array $attributes */ public function __construct($attributes = []) { $attributes['orderable'] = isset($attributes['orderable']) ? $attributes['orderable'] : true; $attributes['searchable'] = isset($attributes['searchable']) ? $attributes['searchable'] : true; // Allow methods override attribute value foreach($attributes as $attribute => $value) { $method = 'parse' . ucfirst(strtolower($attribute)); if(method_exists($this, $method)) { $attributes[$attribute] = $this->$method($value); } } parent::__construct($attributes); } /** * Parse Render * * @param $value * * @return string */ public function parseRender($value) { $value = $value ?: $this->config->get('datatables.render_template', 'datatables::action'); if(is_callable($value)) { $value = value($value); } else { $value = view($value)->render(); } $value = preg_replace(""/\r|\n/"", ' ', $value); return $value ?: null; } } " Add comments in Service functions,"(function ($) { 'use strict'; /** * Panda Base Events Service * @type {void|Object|*} */ Panda.Events = $.extend(Panda.Events || {}, { /** * Initialize the Panda Events Library */ init: function () { // Register global events Panda.Events.Library.init(); }, /** * Add an event listener using jQuery's 'on' * * @param {object|string} listener * @param {string} event * @param {string} context * @param {function} callback */ on: function (listener, event, context, callback) { $(listener).on(event, context, function () { if (typeof callback === 'function') { callback.apply(this, Array.prototype.slice.call(arguments)); } }); }, /** * Add an event listener using jQuery's 'one' * * @param {object|string} listener * @param {string} event * @param {string} context * @param {function} callback */ one: function (listener, event, context, callback) { $(listener).one(event, context, function () { if (typeof callback === 'function') { callback.apply(this, Array.prototype.slice.call(arguments)); } }); }, /** * Remove an event listener. * * @param {object|string} listener * @param {string} event * @param {string} context */ off: function (listener, event, context) { $(listener).off(event, context); }, /** * Trigger a specific event * * @param {object|string} listener * @param {string} event * @param {function} callback */ dispatch: function (listener, event, callback) { $(listener).trigger(event, callback); } }); })(jQuery); ","(function ($) { 'use strict'; /** * Panda Base Events Service * @type {void|Object|*} */ Panda.Events = $.extend(Panda.Events || {}, { init: function () { // Register global events Panda.Events.Library.init(); }, on: function (listener, event, context, callback) { $(listener).on(event, context, function () { if (typeof callback === 'function') { callback.apply(this, Array.prototype.slice.call(arguments)); } }); }, one: function (listener, event, context, callback) { $(listener).one(event, context, function () { if (typeof callback === 'function') { callback.apply(this, Array.prototype.slice.call(arguments)); } }); }, off: function (listener, event, context) { $(listener).off(event, context); }, dispatch: function (listener, event, callback) { $(listener).trigger(event, callback); } }); })(jQuery); " Add OpenLattice User Role role as clarification for default permissions,"import React, { PropTypes } from 'react'; import Immutable from 'immutable'; import { Table } from 'react-bootstrap'; import { AUTHENTICATED_USER } from '../../../utils/Consts/UserRoleConsts'; import styles from '../styles.module.css'; export default class RolePermissionsTable extends React.Component { static propTypes = { rolePermissions: PropTypes.instanceOf(Immutable.Map).isRequired, headers: PropTypes.array.isRequired } getRows = () => { const { rolePermissions } = this.props; const rows = []; if (rolePermissions) { rolePermissions.keySeq().forEach((role) => { let permissionsStr = rolePermissions.get(role).join(', '); let roleStr = role; if (role === AUTHENTICATED_USER) { roleStr = 'OpenLattice User Role - Default for all users*'; permissionsStr = 'None'; } rows.push( <tr className={`${styles.mainRow} roleRow`} key={role}> <td>{roleStr}</td> <td>{permissionsStr}</td> </tr> ); }); } return rows; } render() { const headers = []; this.props.headers.forEach((header) => { headers.push(<th key={header}>{header}</th>); }); return ( <Table bordered responsive className={styles.table}> <thead> <tr> {headers} </tr> </thead> <tbody> {this.getRows()} </tbody> </Table> ); } } ","import React, { PropTypes } from 'react'; import Immutable from 'immutable'; import { Table } from 'react-bootstrap'; import { AUTHENTICATED_USER } from '../../../utils/Consts/UserRoleConsts'; import styles from '../styles.module.css'; export default class RolePermissionsTable extends React.Component { static propTypes = { rolePermissions: PropTypes.instanceOf(Immutable.Map).isRequired, headers: PropTypes.array.isRequired } getRows = () => { const { rolePermissions } = this.props; const rows = []; if (rolePermissions) { rolePermissions.keySeq().forEach((role) => { let permissionsStr = rolePermissions.get(role).join(', '); let roleStr = role; if (role === AUTHENTICATED_USER) { roleStr = 'Default for all users*'; permissionsStr = 'None'; } rows.push( <tr className={`${styles.mainRow} roleRow`} key={role}> <td>{roleStr}</td> <td>{permissionsStr}</td> </tr> ); }); } return rows; } render() { const headers = []; this.props.headers.forEach((header) => { headers.push(<th key={header}>{header}</th>); }); return ( <Table bordered responsive className={styles.table}> <thead> <tr> {headers} </tr> </thead> <tbody> {this.getRows()} </tbody> </Table> ); } } " Ch09: Create and redirect to Tag in tag_create().,"from django.shortcuts import ( get_object_or_404, redirect, render) from .forms import TagForm from .models import Startup, Tag def startup_detail(request, slug): startup = get_object_or_404( Startup, slug__iexact=slug) return render( request, 'organizer/startup_detail.html', {'startup': startup}) def startup_list(request): return render( request, 'organizer/startup_list.html', {'startup_list': Startup.objects.all()}) def tag_create(request): if request.method == 'POST': form = TagForm(request.POST) if form.is_valid(): new_tag = form.save() return redirect(new_tag) else: # empty data or invalid data # show bound HTML form (with errors) pass else: # request.method != 'POST' # show unbound HTML form pass def tag_detail(request, slug): tag = get_object_or_404( Tag, slug__iexact=slug) return render( request, 'organizer/tag_detail.html', {'tag': tag}) def tag_list(request): return render( request, 'organizer/tag_list.html', {'tag_list': Tag.objects.all()}) ","from django.shortcuts import ( get_object_or_404, render) from .forms import TagForm from .models import Startup, Tag def startup_detail(request, slug): startup = get_object_or_404( Startup, slug__iexact=slug) return render( request, 'organizer/startup_detail.html', {'startup': startup}) def startup_list(request): return render( request, 'organizer/startup_list.html', {'startup_list': Startup.objects.all()}) def tag_create(request): if request.method == 'POST': form = TagForm(request.POST) if form.is_valid(): # create new object from data # show webpage for new object pass else: # empty data or invalid data # show bound HTML form (with errors) pass else: # request.method != 'POST' # show unbound HTML form pass def tag_detail(request, slug): tag = get_object_or_404( Tag, slug__iexact=slug) return render( request, 'organizer/tag_detail.html', {'tag': tag}) def tag_list(request): return render( request, 'organizer/tag_list.html', {'tag_list': Tag.objects.all()}) " "Check the existence of the images_path ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' BEG TRACEBACK Traceback (most recent call last): File ""/opt/xos/observer/event_loop.py"", line 349, in sync failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion) File ""/opt/xos/observer/openstacksyncstep.py"", line 14, in __call__ return self.call(**args) File ""/opt/xos/observer/syncstep.py"", line 97, in call pending = self.fetch_pending(deletion) File ""/opt/xos/observer/steps/sync_images.py"", line 22, in fetch_pending for f in os.listdir(images_path): OSError: [Errno 2] No such file or directory: '/opt/xos/images' ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' END TRACEBACK Signed-off-by: S.Çağlar Onur <acf5ae661bb0a9f738c88a741b1d35ac69ab5408@10ur.org>","import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} if os.path.exists(images_path): for f in os.listdir(images_path): filename = os.path.join(images_path, f) if os.path.isfile(filename): available_images[f] = filename images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ""."".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save() ","import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} for f in os.listdir(images_path): if os.path.isfile(os.path.join(images_path ,f)): available_images[f] = os.path.join(images_path ,f) images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ""."".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save() " Move requirements read code info function,"import re from setuptools import setup, find_packages # Dynamically calculate the version version = __import__('device_inventory').get_version() # Collect installation requirements def read_requirements(path): with open(path) as reqf: dep_re = re.compile(r'^([^\s#]+)') return [m.group(0) for m in (dep_re.match(l) for l in reqf) if m] inst_reqs = read_requirements('requirements.txt') setup( name=""device-inventory"", version=version, packages=find_packages(), license='AGPLv3 License', description=('The Device Inventory is a tool to help the inventory ' 'of computers. It retrieves details of the hardware ' 'information and, optionally, runs some health and ' 'benchmark tests.'), scripts=['scripts/device-inventory', 'scripts/di-stress-test'], package_data={'device_inventory': [ 'config.ini', 'config_logging.json', 'data/*' ]}, url='https://github.com/eReuse/device-inventory', author='eReuse team', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Information Technology', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: GNU Affero General Public License v3', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Topic :: System :: Logging', 'Topic :: Utilities', ], install_requires=inst_reqs, ) ","from setuptools import setup, find_packages # Dynamically calculate the version version = __import__('device_inventory').get_version() # Collect installation requirements with open('requirements.txt') as reqf: import re dep_re = re.compile(r'^([^\s#]+)') inst_reqs = [m.group(0) for m in [dep_re.match(l) for l in reqf] if m] setup( name=""device-inventory"", version=version, packages=find_packages(), license='AGPLv3 License', description=('The Device Inventory is a tool to help the inventory ' 'of computers. It retrieves details of the hardware ' 'information and, optionally, runs some health and ' 'benchmark tests.'), scripts=['scripts/device-inventory', 'scripts/di-stress-test'], package_data={'device_inventory': [ 'config.ini', 'config_logging.json', 'data/*' ]}, url='https://github.com/eReuse/device-inventory', author='eReuse team', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Information Technology', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: GNU Affero General Public License v3', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Topic :: System :: Logging', 'Topic :: Utilities', ], install_requires=inst_reqs, ) " Use service base get method,"define([ 'service/serviceBase' ], function(ServiceBase) { 'use strict'; // Override in configuration.properties with `web.ui` prefix var DEFAULTS = { 'vertex.loadRelatedMaxBeforePrompt': 50, 'vertex.loadRelatedMaxForceSearch': 250, 'ontology.iri.artifactHasEntity': 'http://lumify.io/dev#rawHasEntity', 'properties.multivalue.defaultVisibleCount': 2, 'map.provider': 'google', 'map.provider.osm.url': 'https://a.tile.openstreetmap.org/${z}/${x}/${y}.png,' + 'https://b.tile.openstreetmap.org/${z}/${x}/${y}.png,' + 'https://c.tile.openstreetmap.org/${z}/${x}/${y}.png' }; // Coerce all values to strings since that's what they will be from // server _.keys(DEFAULTS).forEach(function(key) { DEFAULTS[key] = '' + DEFAULTS[key]; }); function ConfigService() { ServiceBase.call(this); return this; } ConfigService.prototype = Object.create(ServiceBase.prototype); ConfigService.prototype.getProperties = function(refresh) { if (!refresh && this.cachedProperties) { return this.cachedProperties; } this.cachedProperties = this._ajaxGet({ url: 'configuration' }) .then(this.applyDefaults); return this.cachedProperties; }; ConfigService.prototype.applyDefaults = function(properties) { return _.extend({}, DEFAULTS, properties); }; return ConfigService; }); ","define([ 'service/serviceBase' ], function(ServiceBase) { 'use strict'; // Override in configuration.properties with `web.ui` prefix var DEFAULTS = { 'vertex.loadRelatedMaxBeforePrompt': 50, 'vertex.loadRelatedMaxForceSearch': 250, 'ontology.iri.artifactHasEntity': 'http://lumify.io/dev#rawHasEntity', 'properties.multivalue.defaultVisibleCount': 2, 'map.provider': 'google', 'map.provider.osm.url': 'https://a.tile.openstreetmap.org/${z}/${x}/${y}.png,' + 'https://b.tile.openstreetmap.org/${z}/${x}/${y}.png,' + 'https://c.tile.openstreetmap.org/${z}/${x}/${y}.png' }; // Coerce all values to strings since that's what they will be from // server _.keys(DEFAULTS).forEach(function(key) { DEFAULTS[key] = '' + DEFAULTS[key]; }); function ConfigService() { ServiceBase.call(this); return this; } ConfigService.prototype = Object.create(ServiceBase.prototype); ConfigService.prototype.getProperties = function(refresh) { if (!refresh && this.cachedProperties) return this.cachedProperties; return (this.cachedProperties = $.get('configuration').then(this.applyDefaults)); }; ConfigService.prototype.applyDefaults = function(properties) { return _.extend({}, DEFAULTS, properties); }; return ConfigService; }); " "Include LengthValidator in list of exporeted objects Signed-off-by: Branko Vukelic <26059cc39872530f89fec69552bb1050e1cc2caa@outernet.is>",""""""" .. module:: bottle_utils.form :synopsis: Form processing and validation library .. moduleauthor:: Outernet Inc <hello@outernet.is> """""" from .exceptions import ValidationError from .fields import (DormantField, Field, StringField, PasswordField, HiddenField, EmailField, TextAreaField, DateField, FileField, IntegerField, FloatField, BooleanField, SelectField) from .forms import Form from .validators import (Validator, Required, DateValidator, InRangeValidator, LengthValidator) __all__ = ['ValidationError', 'DormantField', 'Field', 'StringField', 'PasswordField', 'HiddenField', 'EmailField', 'TextAreaField', 'DateField', 'FileField', 'IntegerField', 'FloatField', 'BooleanField', 'SelectField', 'Form', 'Validator', 'Required', 'DateValidator', 'InRangeValidator'] ",""""""" .. module:: bottle_utils.form :synopsis: Form processing and validation library .. moduleauthor:: Outernet Inc <hello@outernet.is> """""" from .exceptions import ValidationError from .fields import (DormantField, Field, StringField, PasswordField, HiddenField, EmailField, TextAreaField, DateField, FileField, IntegerField, FloatField, BooleanField, SelectField) from .forms import Form from .validators import Validator, Required, DateValidator, InRangeValidator __all__ = ['ValidationError', 'DormantField', 'Field', 'StringField', 'PasswordField', 'HiddenField', 'EmailField', 'TextAreaField', 'DateField', 'FileField', 'IntegerField', 'FloatField', 'BooleanField', 'SelectField', 'Form', 'Validator', 'Required', 'DateValidator', 'InRangeValidator'] " Add rules for validating property schema _type and units.,"var _ = require('lodash'); module.exports = function(model) { 'use strict'; let propertyTypes = [ 'number', 'string', 'histogram', 'composition' ]; let propertyUnits = [ 'mm', 'm', 'c', 'f' ]; return { mustExist: mustExist, mustNotExist: mustNotExist, isValidPropertyType: isValidPropertyType, isValidUnit: isValidUnit }; // mustExist looks up an entry in the named table by id. If // the entry doesn't exist it returns an error. function mustExist(what, modelName, done) { model[modelName].get(what).then(function(value) { let error = null; if (!value) { error = { rule: 'mustExist', actual: what, expected: 'did not find ' + what + ' in model' }; } done(error); }); } // mustNotExist looks up an entry in the named table by the named // index. If the entry exists it returns an error. function mustNotExist(what, spec, done) { let pieces = spec.split(':'), modelName = pieces[0], modelIndex = pieces[1]; model[modelName].get(what, modelIndex).then(function(value) { let error = null; if (value) { // found a match, when we shouldn't have error = { rule: 'mustNotExist', actual: what, expected: `found ${what} in model` }; } done(error); }); } function isValidPropertyType(what, _ignore) { let invalid = { rule: 'isValidPropertyType', actual: what, expected: `type to be one of ${propertyTypes}` }; return _.indexOf(propertyTypes, what) === -1 ? invalid : null; } function isValidUnit(what, _ignore) { let invalid = { rule: 'isValidUnit', actual: what, expected: `units to be one of ${propertyUnits}` }; return _.indexOf(propertyUnits, what) === -1 ? invalid : null; } }; ","module.exports = function(model) { return { mustExist: mustExist, mustNotExist: mustNotExist }; function mustExist(what, modelName, done) { 'use strict'; model[modelName].get(what).then(function(value) { let error = null; if (!value) { error = { rule: 'mustExist', actual: what, expected: 'did not find ' + what + ' in model' }; } done(error); }); } function mustNotExist(what, spec, done) { 'use strict'; let pieces = spec.split(':'), modelName = pieces[0], modelIndex = pieces[1]; model[modelName].get(what, modelIndex).then(function(value) { let error = null; if (value) { // found a match, when we shouldn't have error = { rule: 'mustNotExist', actual: what, expected: `found ${what} in model` }; } done(error); }); } }; " Make extractor repo recurse in case of list or array.,"package com.pholser.junit.quickcheck.internal.extractors; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Map; import org.javaruntype.type.Types; import com.pholser.junit.quickcheck.RandomValueExtractor; import com.pholser.junit.quickcheck.RegisterableRandomValueExtractor; public class ExtractorRepository { private final Map<Type, RandomValueExtractor<?>> extractors = new HashMap<Type, RandomValueExtractor<?>>(); public ExtractorRepository add(Iterable<RegisterableRandomValueExtractor<?>> source) { for (RegisterableRandomValueExtractor<?> each : source) registerTypes(each); return this; } private void registerTypes(RegisterableRandomValueExtractor<?> extractor) { for (Class<?> each : extractor.types()) extractors.put(each, extractor); } public RandomValueExtractor<?> extractorFor(Type type) { org.javaruntype.type.Type<?> typeToken = Types.forJavaLangReflectType(type); if (typeToken.isArray()) { Class<?> componentType = typeToken.getComponentClass(); return new ArrayExtractor(componentType, extractorFor(componentType)); } else if (List.class.equals(typeToken.getRawClass())) { Class<?> componentType = typeToken.getTypeParameters().get(0).getType().getRawClass(); return new ListExtractor(extractorFor(componentType)); } return extractors.get(type); } } ","package com.pholser.junit.quickcheck.internal.extractors; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Map; import org.javaruntype.type.Types; import com.pholser.junit.quickcheck.RandomValueExtractor; import com.pholser.junit.quickcheck.RegisterableRandomValueExtractor; public class ExtractorRepository { private final Map<Type, RandomValueExtractor<?>> extractors = new HashMap<Type, RandomValueExtractor<?>>(); public ExtractorRepository add(Iterable<RegisterableRandomValueExtractor<?>> source) { for (RegisterableRandomValueExtractor<?> each : source) registerTypes(each); return this; } private void registerTypes(RegisterableRandomValueExtractor<?> extractor) { for (Class<?> each : extractor.types()) extractors.put(each, extractor); } public RandomValueExtractor<?> extractorFor(Type type) { org.javaruntype.type.Type<?> typeToken = Types.forJavaLangReflectType(type); if (typeToken.isArray()) { Class<?> componentType = typeToken.getComponentClass(); return new ArrayExtractor(componentType, extractors.get(componentType)); } else if (List.class.equals(typeToken.getRawClass())) { Class<?> componentType = typeToken.getTypeParameters().get(0).getType().getRawClass(); return new ListExtractor(extractors.get(componentType)); } return extractors.get(type); } } " Clean initial route from extra 'title' field,"// index.android.js // Flow import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Navigator } from 'react-native'; import Splash from './scenes/splash'; import Login from './scenes/login'; import Register from './scenes/register'; import Overview from './scenes/overview.android'; export default class FlowApp extends Component { render() { return ( <Navigator initialRoute={{ name: 'splash' }} configureScene={(route) => route.sceneConfig || Navigator.SceneConfigs.FloatFromBottomAndroid} renderScene={(route, navigator) => { switch (route.name) { case 'splash': return <Splash navigator={navigator} />; case 'login': return <Login {...route.passProps} />; case 'register': return <Register {...route.passProps} />; case 'overview': return <Overview navigator={navigator} {...route.passProps} />; default: return <Text>Bad route name given!</Text> } }} /> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('FlowApp', () => FlowApp); ","// index.android.js // Flow import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Navigator } from 'react-native'; import Splash from './scenes/splash'; import Login from './scenes/login'; import Register from './scenes/register'; import Overview from './scenes/overview.android'; export default class FlowApp extends Component { render() { return ( <Navigator initialRoute={{ title: 'Flow', name: 'splash' }} configureScene={(route) => route.sceneConfig || Navigator.SceneConfigs.FloatFromBottomAndroid} renderScene={(route, navigator) => { switch (route.name) { case 'splash': return <Splash navigator={navigator} />; case 'login': return <Login {...route.passProps} />; case 'register': return <Register {...route.passProps} />; case 'overview': return <Overview navigator={navigator} {...route.passProps} />; default: return <Text>Bad route name given!</Text> } }} /> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('FlowApp', () => FlowApp); " Increase interval to 5 seconds,"(function() { ""use strict""; var lastKeys = """"; function fetchRedlines() { var baseUrl = $('#baseUrl').val(); var artworkUrl = $('#artworkUrl').val(); $.get(baseUrl + 'index').done(function(keys) { if (lastKeys === keys) { return; } lastKeys = keys; var items = []; var requests = $.map(keys.split('\n'), function(key) { return $.get(baseUrl + key).done(function(data) { var json = JSON.parse(data); var feedback = $('<div/>').text(json.feedback).addClass('feedback'); var artwork = $('<div/>').append($('<img/>').attr('src', artworkUrl)) .append($('<img/>').attr('src', json.image).addClass('redline')) .addClass('drawing'); var item = $('<div/>').append(feedback) .append(artwork) .attr('id', key); items.push(item); }).fail(function() { console.log('Failed to fetch data for key ' + key); }); }); $.when.apply($, requests).done(function () { $('#items').empty(); $.each(items, function(i, item) { $('#items').append(item); }); $('#submissions').text(items.length); }); }).fail(function() { console.log('Failed to fetch index file'); }); } $(function() { fetchRedlines(); setInterval(fetchRedlines, 5000); }); })(); ","(function() { ""use strict""; var lastKeys = """"; function fetchRedlines() { var baseUrl = $('#baseUrl').val(); var artworkUrl = $('#artworkUrl').val(); $.get(baseUrl + 'index').done(function(keys) { if (lastKeys === keys) { return; } lastKeys = keys; var items = []; var requests = $.map(keys.split('\n'), function(key) { return $.get(baseUrl + key).done(function(data) { var json = JSON.parse(data); var feedback = $('<div/>').text(json.feedback).addClass('feedback'); var artwork = $('<div/>').append($('<img/>').attr('src', artworkUrl)) .append($('<img/>').attr('src', json.image).addClass('redline')) .addClass('drawing'); var item = $('<div/>').append(feedback) .append(artwork) .attr('id', key); items.push(item); }).fail(function() { console.log('Failed to fetch data for key ' + key); }); }); $.when.apply($, requests).done(function () { $('#items').empty(); $.each(items, function(i, item) { $('#items').append(item); }); $('#submissions').text(items.length); }); }).fail(function() { console.log('Failed to fetch index file'); }); } $(function() { fetchRedlines(); setInterval(fetchRedlines, 1000); }); })(); " Remove arrow function to remain compatible with older Node versions,"""use strict""; var MetafileMatcher = require('./metafile-matcher'); // Not needed in Node 4.0+ if (!Object.assign) Object.assign = require('object-assign'); class MetalsmithMetafiles { constructor(options) { options = options || {}; this._initMatcherOptions(options); this._initMatchers(); } _initMatcherOptions(options) { this._matcherOptions = []; var parserOptions = Object.assign({'.json': true}, options.parsers); for (var extension in parserOptions) { var enabled = parserOptions[extension]; if (enabled) { this._matcherOptions.push( Object.assign({}, options, {""extension"": extension}) ); } } } _initMatchers() { this._matchers = this._matcherOptions.map(function(options) { return new MetafileMatcher(options); }); } // Main interface parseMetafiles(files) { filesLoop: for (var path in files) { for (var matcher of this._matchers) { var metafile = matcher.metafile(path, files[path]); if (!metafile.isMetafile) continue; if (!files[metafile.mainFile]) continue; Object.assign(files[metafile.mainFile], metafile.metadata); if (matcher.deleteMetaFiles) delete files[metafile.path]; continue filesLoop; } } } } module.exports = MetalsmithMetafiles; ","""use strict""; var MetafileMatcher = require('./metafile-matcher'); // Not needed in Node 4.0+ if (!Object.assign) Object.assign = require('object-assign'); class MetalsmithMetafiles { constructor(options) { options = options || {}; this._initMatcherOptions(options); this._initMatchers(); } _initMatcherOptions(options) { this._matcherOptions = []; var parserOptions = Object.assign({'.json': true}, options.parsers); for (var extension in parserOptions) { var enabled = parserOptions[extension]; if (enabled) { this._matcherOptions.push( Object.assign({}, options, {""extension"": extension}) ); } } } _initMatchers() { this._matchers = this._matcherOptions.map((options) => new MetafileMatcher(options)); } // Main interface parseMetafiles(files) { filesLoop: for (var path in files) { for (var matcher of this._matchers) { var metafile = matcher.metafile(path, files[path]); if (!metafile.isMetafile) continue; if (!files[metafile.mainFile]) continue; Object.assign(files[metafile.mainFile], metafile.metadata); if (matcher.deleteMetaFiles) delete files[metafile.path]; continue filesLoop; } } } } module.exports = MetalsmithMetafiles; " Make keyup function a bit more consistant,"// JavaScript Document // Scripts written by YOURNAME @ YOURCOMPANY var overlays = document.querySelectorAll(""[data-overlay]""), overlay_closer = document.querySelector("".overlay-closer""); // listen for clicks on the overlay closer overlay_closer.addEventListener(""click"", function (e) { e.preventDefault(); close_overlay_closer(); }); // listen for esc key press document.addEventListener(""keyup"", function(e) { if (e.keyCode === 27) close_overlay_closer(); }); // function to close the overlay closer function close_overlay_closer() { // make sure the overlay closer exists if ((typeof overlay_closer === ""object"")) { overlay_closer.classList.remove(""is-active""); overlay_closer.setAttribute(""aria-hidden"", ""true""); // make sure overlays exist if ((typeof overlays === ""object"")) { for (var i = 0; i < overlays.length; i++) { if (overlays[i].hasAttribute(""aria-hidden"")) { // mark the overlay as hidden overlays[i].setAttribute(""aria-hidden"", ""true""); } else { // focus the overlay overlays[i].focus(); } // mark the overlay as inactive overlays[i].classList.remove(""is-active""); } } } } ","// JavaScript Document // Scripts written by YOURNAME @ YOURCOMPANY var overlays = document.querySelectorAll(""[data-overlay]""), overlay_closer = document.querySelector("".overlay-closer""); // listen for clicks on the overlay closer overlay_closer.addEventListener(""click"", function (e) { e.preventDefault(); close_overlay_closer(); }); // listen for esc key press document.onkeyup = function(e) { if (e.keyCode === 27) { close_overlay_closer(); } }; // function to close the overlay closer function close_overlay_closer() { // make sure the overlay closer exists if ((typeof overlay_closer === ""object"")) { overlay_closer.classList.remove(""is-active""); overlay_closer.setAttribute(""aria-hidden"", ""true""); // make sure overlays exist if ((typeof overlays === ""object"")) { for (var i = 0; i < overlays.length; i++) { if (overlays[i].hasAttribute(""aria-hidden"")) { // mark the overlay as hidden overlays[i].setAttribute(""aria-hidden"", ""true""); } else { // focus the overlay overlays[i].focus(); } // mark the overlay as inactive overlays[i].classList.remove(""is-active""); } } } } " BAP-10985: Update the rules displaying autocomplete result for business unit owner field,"<?php namespace Oro\Bundle\OrganizationBundle\Form\Transformer; use Doctrine\Common\Collections\Collection; use Oro\Bundle\OrganizationBundle\Entity\BusinessUnit; use Oro\Bundle\OrganizationBundle\Entity\Manager\BusinessUnitManager; use Symfony\Component\Form\DataTransformerInterface; class BusinessUnitTreeTransformer implements DataTransformerInterface { /** @var BusinessUnitManager */ protected $manager; /** @var BusinessUnit */ protected $entity; public function __construct($manager) { $this->manager = $manager; } /** * {@inheritdoc} */ public function reverseTransform($value) { if (null == $value) { return 0; } elseif (is_array($value)) { foreach ($value as &$val) { if ($val === '') { $val = 0; } } return $this->manager->getBusinessUnitRepo()->findBy(['id' => $value]); } return $this->manager->getBusinessUnitRepo()->find($value); } /** * {@inheritdoc} */ public function transform($value) { if (null == $value) { return 0; } if (is_array($value) || (is_object($value) && ($value instanceof Collection))) { $result = []; foreach ($value as $object) { $result[] = $object->getId(); } } elseif (is_object($value)) { $result = $value->getId(); } else { $result = $value; } return $result; } } ","<?php namespace Oro\Bundle\OrganizationBundle\Form\Transformer; use Doctrine\Common\Collections\Collection; use Oro\Bundle\OrganizationBundle\Entity\BusinessUnit; use Oro\Bundle\OrganizationBundle\Entity\Manager\BusinessUnitManager; use Symfony\Component\Form\DataTransformerInterface; class BusinessUnitTreeTransformer implements DataTransformerInterface { /** @var BusinessUnitManager */ protected $manager; /** @var BusinessUnit */ protected $entity; public function __construct($manager) { $this->manager = $manager; } /** * {@inheritdoc} */ public function reverseTransform($value) { if (null == $value) { return 0; } elseif (is_array($value)) { foreach($value as &$val) { if ($val === """") { $val = 0; } } return $this->manager->getBusinessUnitRepo()->findBy(['id' => $value]); } return $this->manager->getBusinessUnitRepo()->find($value); } /** * {@inheritdoc} */ public function transform($value) { if (null == $value) { return 0; } if (is_array($value) || (is_object($value) && ($value instanceof Collection))) { $result = []; foreach ($value as $object) { $result[] = $object->getId(); } } elseif (is_object($value)) { $result = $value->getId(); } else { $result = $value; } return $result; } } " Unify numbers in Go with variants,"/* Language: Go Author: Stephan Kountso aka StepLg <steplg@gmail.com> Contributors: Evgeny Stepanischev <imbolk@gmail.com> Description: Google go language (golang). For info about language see http://golang.org/ Category: system */ function(hljs) { var GO_KEYWORDS = { keyword: 'break default func interface select case map struct chan else goto package switch ' + 'const fallthrough if range type continue for import return var go defer ' + 'bool byte complex64 complex128 float32 float64 int8 int16 int32 int64 string uint8 ' + 'uint16 uint32 uint64 int uint uintptr rune', literal: 'true false iota nil', built_in: 'append cap close complex copy imag len make new panic print println real recover delete' }; return { aliases: ['golang'], keywords: GO_KEYWORDS, illegal: '</', contains: [ hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE, hljs.QUOTE_STRING_MODE, { className: 'string', begin: '\'', end: '[^\\\\]\'' }, { className: 'string', begin: '`', end: '`' }, { className: 'number', variants: [ {begin: hljs.C_NUMBER_RE + '[dflsi]', relevance: 1}, hljs.C_NUMBER_MODE ] }, { begin: /:=/ // relevance booster } ] }; } ","/* Language: Go Author: Stephan Kountso aka StepLg <steplg@gmail.com> Contributors: Evgeny Stepanischev <imbolk@gmail.com> Description: Google go language (golang). For info about language see http://golang.org/ Category: system */ function(hljs) { var GO_KEYWORDS = { keyword: 'break default func interface select case map struct chan else goto package switch ' + 'const fallthrough if range type continue for import return var go defer ' + 'bool byte complex64 complex128 float32 float64 int8 int16 int32 int64 string uint8 ' + 'uint16 uint32 uint64 int uint uintptr rune', literal: 'true false iota nil', built_in: 'append cap close complex copy imag len make new panic print println real recover delete' }; return { aliases: ['golang'], keywords: GO_KEYWORDS, illegal: '</', contains: [ hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE, hljs.QUOTE_STRING_MODE, { className: 'string', begin: '\'', end: '[^\\\\]\'' }, { className: 'string', begin: '`', end: '`' }, { className: 'number', begin: hljs.C_NUMBER_RE + '[dflsi]?', relevance: 0 }, hljs.C_NUMBER_MODE, { begin: /:=/ // relevance booster } ] }; } " Make sure points in checksum are consistent,"import hashlib import autopep8 def is_grade(cell): """"""Returns True if the cell is a grade cell."""""" if 'nbgrader' not in cell.metadata: return False return cell.metadata['nbgrader'].get('grade', False) def is_solution(cell): """"""Returns True if the cell is a solution cell."""""" if 'nbgrader' not in cell.metadata: return False return cell.metadata['nbgrader'].get('solution', False) def determine_grade(cell): if not is_grade(cell): raise ValueError(""cell is not a grade cell"") max_points = float(cell.metadata['nbgrader']['points']) if cell.cell_type == 'code': for output in cell.outputs: if output.output_type == 'error': return 0, max_points return max_points, max_points else: return None, max_points def compute_checksum(cell): m = hashlib.md5() # fix minor whitespace issues that might have been added and then # add cell contents m.update(autopep8.fix_code(cell.source).rstrip()) # include number of points that the cell is worth if 'points' in cell.metadata.nbgrader: m.update(str(float(cell.metadata.nbgrader['points']))) # include the grade_id if 'grade_id' in cell.metadata.nbgrader: m.update(cell.metadata.nbgrader['grade_id']) return m.hexdigest() ","import hashlib import autopep8 def is_grade(cell): """"""Returns True if the cell is a grade cell."""""" if 'nbgrader' not in cell.metadata: return False return cell.metadata['nbgrader'].get('grade', False) def is_solution(cell): """"""Returns True if the cell is a solution cell."""""" if 'nbgrader' not in cell.metadata: return False return cell.metadata['nbgrader'].get('solution', False) def determine_grade(cell): if not is_grade(cell): raise ValueError(""cell is not a grade cell"") max_points = float(cell.metadata['nbgrader']['points']) if cell.cell_type == 'code': for output in cell.outputs: if output.output_type == 'error': return 0, max_points return max_points, max_points else: return None, max_points def compute_checksum(cell): m = hashlib.md5() # fix minor whitespace issues that might have been added and then # add cell contents m.update(autopep8.fix_code(cell.source).rstrip()) # include number of points that the cell is worth if 'points' in cell.metadata.nbgrader: m.update(cell.metadata.nbgrader['points']) # include the grade_id if 'grade_id' in cell.metadata.nbgrader: m.update(cell.metadata.nbgrader['grade_id']) return m.hexdigest() " "Change init event to service:running service:running is the best one to ensure BrowserSync has fully loaded. It is triggered after any initialization function and DNS lookup.","/* * grunt-browser-sync * https://github.com/shakyshane/grunt-browser-sync * * Copyright (c) 2013 Shane Osbourne * Licensed under the MIT license. */ 'use strict'; module.exports = function (grunt) { grunt.registerMultiTask(""browserSync"", ""Keep your browsers in sync"", function () { var done = this.async(); var options = this.options(); var patterns; if (this.data && this.data.bsFiles && this.data.bsFiles.src) { patterns = this.data.bsFiles.src; if (typeof patterns === ""string"") { patterns = [patterns]; } } if (!patterns) { if (this.data.src) { patterns = this.data.src; if (typeof this.data.src === ""string"") { patterns = [this.data.src]; } } } if (!patterns) { if (this.filesSrc.length) { patterns = this.filesSrc; } } var browserSync = require(""browser-sync""); browserSync.init(patterns, options); //noinspection JSUnresolvedVariable if (options.watchTask || options.watchtask || options.background) { // Wait until browserSync fully initializes browserSync.emitter.on('service:running', function() { done(); // Allow Watch task to run after }); } }); }; ","/* * grunt-browser-sync * https://github.com/shakyshane/grunt-browser-sync * * Copyright (c) 2013 Shane Osbourne * Licensed under the MIT license. */ 'use strict'; module.exports = function (grunt) { grunt.registerMultiTask(""browserSync"", ""Keep your browsers in sync"", function () { var done = this.async(); var options = this.options(); var patterns; if (this.data && this.data.bsFiles && this.data.bsFiles.src) { patterns = this.data.bsFiles.src; if (typeof patterns === ""string"") { patterns = [patterns]; } } if (!patterns) { if (this.data.src) { patterns = this.data.src; if (typeof this.data.src === ""string"") { patterns = [this.data.src]; } } } if (!patterns) { if (this.filesSrc.length) { patterns = this.filesSrc; } } var browserSync = require(""browser-sync""); browserSync.init(patterns, options); //noinspection JSUnresolvedVariable if (options.watchTask || options.watchtask || options.background) { // Wait until browserSync fully initializes browserSync.emitter.on('init', function() { done(); // Allow Watch task to run after }); } }); }; " Rename modes param to playmodes and use get_arr directly,"<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace App\Http\Controllers\InterOp; use App\Http\Controllers\Controller; use App\Models\User; class UserGroupsController extends Controller { public function update() { [$user, $group] = $this->getUserAndGroupModels(); $modes = get_arr(request()->input('playmodes'), 'get_string'); $user->addOrUpdateGroup($group, $modes); return response(null, 204); } public function destroy() { [$user, $group] = $this->getUserAndGroupModels(); $user->removeFromGroup($group); return response(null, 204); } public function setDefault() { [$user, $group] = $this->getUserAndGroupModels(); $user->setDefaultGroup($group); return response(null, 204); } private function getUserAndGroupModels() { $params = get_params(request()->all(), null, [ 'group_id:int', 'user_id:int', ]); $group = app('groups')->byId($params['group_id'] ?? null); abort_if($group === null, 404, 'Group not found'); return [ User::findOrFail($params['user_id'] ?? null), $group, ]; } } ","<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace App\Http\Controllers\InterOp; use App\Http\Controllers\Controller; use App\Models\User; class UserGroupsController extends Controller { public function update() { [$user, $group] = $this->getUserAndGroupModels(); $modes = get_param_value(request()->input('modes'), 'string[]'); $user->addOrUpdateGroup($group, $modes); return response(null, 204); } public function destroy() { [$user, $group] = $this->getUserAndGroupModels(); $user->removeFromGroup($group); return response(null, 204); } public function setDefault() { [$user, $group] = $this->getUserAndGroupModels(); $user->setDefaultGroup($group); return response(null, 204); } private function getUserAndGroupModels() { $params = get_params(request()->all(), null, [ 'group_id:int', 'user_id:int', ]); $group = app('groups')->byId($params['group_id'] ?? null); abort_if($group === null, 404, 'Group not found'); return [ User::findOrFail($params['user_id'] ?? null), $group, ]; } } " Add links to harvester dump sites,"module.exports = function (creep) { if(creep.memory.currentTarget) { creep.memory.currentTarget = Game.getObjectById(creep.memory.currentTarget.id); } // Aquire target if(!creep.memory.currentTarget || !creep.memory.currentTarget.structureType || creep.memory.currentTarget.energy === creep.memory.currentTarget.energyCapacity) { creep.memory.currentTarget = creep.pos.findClosest(FIND_MY_SPAWNS, { filter: function(spawn) { return (spawn.energy < spawn.energyCapacity); }, algorithm: ""astar"" }); if(!creep.memory.currentTarget) { creep.memory.currentTarget = creep.pos.findClosest(FIND_MY_STRUCTURES, { filter: function(structure) { return (structure.structureType === STRUCTURE_EXTENSION || structure.structureType === STRUCTURE_LINK) && (structure.energy < structure.energyCapacity); }, algorithm: ""astar"" }); } } // Execute on target if(creep.memory.currentTarget) { if(creep.pos.isNearTo(creep.memory.currentTarget.pos.x, creep.memory.currentTarget.pos.y)) { creep.transferEnergy(Game.getObjectById(creep.memory.currentTarget.id)); } else { creep.advMove(creep.memory.currentTarget); } } }; ","module.exports = function (creep) { if(creep.memory.currentTarget) { creep.memory.currentTarget = Game.getObjectById(creep.memory.currentTarget.id); } // Aquire target if(!creep.memory.currentTarget || !creep.memory.currentTarget.structureType || creep.memory.currentTarget.energy === creep.memory.currentTarget.energyCapacity) { creep.memory.currentTarget = creep.pos.findClosest(FIND_MY_SPAWNS, { filter: function(spawn) { return (spawn.energy < spawn.energyCapacity); }, algorithm: ""astar"" }); if(!creep.memory.currentTarget) { creep.memory.currentTarget = creep.pos.findClosest(FIND_MY_STRUCTURES, { filter: function(structure) { return (structure.structureType === STRUCTURE_EXTENSION) && (structure.energy < structure.energyCapacity); }, algorithm: ""astar"" }); } } // Execute on target if(creep.memory.currentTarget) { if(creep.pos.isNearTo(creep.memory.currentTarget.pos.x, creep.memory.currentTarget.pos.y)) { creep.transferEnergy(Game.getObjectById(creep.memory.currentTarget.id)); } else { creep.advMove(creep.memory.currentTarget); } } }; " Add telephone property to organization type,"<?php namespace JsonLd\ContextTypes; class Organization extends Thing { /** * Property structure * * @var array */ private $extendedStructure = [ 'address' => PostalAddress::class, 'logo' => ImageObject::class, 'contactPoint' => ContactPoint::class, 'email' => null, 'telephone' => null, ]; /** * Organization constructor. Merges extendedStructure up * * @param array $attributes * @param array $extendedStructure */ public function __construct(array $attributes, array $extendedStructure = []) { parent::__construct( $attributes, array_merge($this->structure, $this->extendedStructure, $extendedStructure) ); } /** * Set the contactPoints * * @param array $items * * @return array */ protected function setContactPointAttribute($items) { if (is_array($items) === false) { return $items; } //Check if it is an array with one dimension if (is_array(reset($items)) === false) { return $this->getNestedContext(ContactPoint::class, $items); } //Process multi dimensional array return array_map(function ($item) { return $this->getNestedContext(ContactPoint::class, $item); }, $items); } } ","<?php namespace JsonLd\ContextTypes; class Organization extends Thing { /** * Property structure * * @var array */ private $extendedStructure = [ 'address' => PostalAddress::class, 'logo' => ImageObject::class, 'contactPoint' => ContactPoint::class, 'email' => null, ]; /** * Organization constructor. Merges extendedStructure up * * @param array $attributes * @param array $extendedStructure */ public function __construct(array $attributes, array $extendedStructure = []) { parent::__construct( $attributes, array_merge($this->structure, $this->extendedStructure, $extendedStructure) ); } /** * Set the contactPoints * * @param array $items * * @return array */ protected function setContactPointAttribute($items) { if (is_array($items) === false) { return $items; } //Check if it is an array with one dimension if (is_array(reset($items)) === false) { return $this->getNestedContext(ContactPoint::class, $items); } //Process multi dimensional array return array_map(function ($item) { return $this->getNestedContext(ContactPoint::class, $item); }, $items); } } " Change property visibility so it can be used by subclasses,"<?php class JsonView extends ApiView { /** @var array */ protected $string_fields; public function render($content) { $this->setHeader('Content-Type', 'application/json; charset=utf8'); return parent::render($content); } /** * Function to build output, can be used by JSON and JSONP */ public function buildOutput($content) { $content = $this->addCount($content); // need to work out which fields should have been numbers // Don't use JSON_NUMERIC_CHECK because it eats things (e.g. talk stubs) // Specify a list of fields to NOT convert to numbers $this->string_fields = array(""stub"", ""track_name"", ""comment""); $output = $this->numericCheck($content); $retval = json_encode($output); return $retval; } protected function numericCheck($data) { if (! is_array($data)) { return $this->scalarNumericCheck('', $data); } $output = array(); foreach ($data as $key => $value) { // recurse as needed if (is_array($value)) { $output[$key] = $this->numericCheck($value); } else { $output[$key] = $this->scalarNumericCheck($key, $value); } } return $output; } protected function scalarNumericCheck($key, $value) { if (is_numeric($value) && ! in_array($key, $this->string_fields)) { return (float) $value; } return $value; } } ","<?php class JsonView extends ApiView { /** @var array */ private $string_fields; public function render($content) { $this->setHeader('Content-Type', 'application/json; charset=utf8'); return parent::render($content); } /** * Function to build output, can be used by JSON and JSONP */ public function buildOutput($content) { $content = $this->addCount($content); // need to work out which fields should have been numbers // Don't use JSON_NUMERIC_CHECK because it eats things (e.g. talk stubs) // Specify a list of fields to NOT convert to numbers $this->string_fields = array(""stub"", ""track_name"", ""comment""); $output = $this->numericCheck($content); $retval = json_encode($output); return $retval; } protected function numericCheck($data) { if (! is_array($data)) { return $this->scalarNumericCheck('', $data); } $output = array(); foreach ($data as $key => $value) { // recurse as needed if (is_array($value)) { $output[$key] = $this->numericCheck($value); } else { $output[$key] = $this->scalarNumericCheck($key, $value); } } return $output; } protected function scalarNumericCheck($key, $value) { if (is_numeric($value) && ! in_array($key, $this->string_fields)) { return (float) $value; } return $value; } } " Use method reference instead of lambda,"/** * */ package ca.eandb.jmist.framework.geometry.mesh; import java.util.stream.StreamSupport; import ca.eandb.jmist.framework.BoundingBoxBuilder3; import ca.eandb.jmist.math.Box3; import ca.eandb.jmist.math.Sphere; /** * @author bwkimmel * */ public final class MeshUtil { private MeshUtil() {} public static Mesh triangulate(Mesh mesh) { return mesh.getMaxFaceVertexCount() == 3 ? mesh : new TriangulatedMesh(mesh); } public static Sphere getBoundingSphere(Mesh mesh) { return getBoundingSphere(mesh.getVertices()); } public static Sphere getBoundingSphere(Mesh.Face face) { return getBoundingSphere(face.getVertices()); } private static Sphere getBoundingSphere(Iterable<Mesh.Vertex> vertices) { return Sphere.smallestContaining(() -> StreamSupport.stream(vertices.spliterator(), false) .map(Mesh.Vertex::getPosition) .iterator()); } public static Box3 getBoundingBox(Mesh mesh) { return getBoundingBox(mesh.getVertices()); } public static Box3 getBoundingBox(Mesh.Face face) { return getBoundingBox(face.getVertices()); } private static Box3 getBoundingBox(Iterable<Mesh.Vertex> vertices) { BoundingBoxBuilder3 builder = new BoundingBoxBuilder3(); for (Mesh.Vertex vertex : vertices) { builder.add(vertex.getPosition()); } return builder.getBoundingBox(); } } ","/** * */ package ca.eandb.jmist.framework.geometry.mesh; import java.util.stream.StreamSupport; import ca.eandb.jmist.framework.BoundingBoxBuilder3; import ca.eandb.jmist.math.Box3; import ca.eandb.jmist.math.Sphere; /** * @author bwkimmel * */ public final class MeshUtil { private MeshUtil() {} public static Mesh triangulate(Mesh mesh) { return mesh.getMaxFaceVertexCount() == 3 ? mesh : new TriangulatedMesh(mesh); } public static Sphere getBoundingSphere(Mesh mesh) { return getBoundingSphere(mesh.getVertices()); } public static Sphere getBoundingSphere(Mesh.Face face) { return getBoundingSphere(face.getVertices()); } private static Sphere getBoundingSphere(Iterable<Mesh.Vertex> vertices) { return Sphere.smallestContaining(() -> StreamSupport.stream(vertices.spliterator(), false) .map(v -> v.getPosition()) .iterator()); } public static Box3 getBoundingBox(Mesh mesh) { return getBoundingBox(mesh.getVertices()); } public static Box3 getBoundingBox(Mesh.Face face) { return getBoundingBox(face.getVertices()); } private static Box3 getBoundingBox(Iterable<Mesh.Vertex> vertices) { BoundingBoxBuilder3 builder = new BoundingBoxBuilder3(); for (Mesh.Vertex vertex : vertices) { builder.add(vertex.getPosition()); } return builder.getBoundingBox(); } } " Include new numberOfDecimals function into the main build,"""use strict""; module.exports = { makeRandomAlphanumericalString: require(""./source/make-random-alphanumerical-string""), addOneTimeListener: require(""./source/add-one-time-listener""), noConcurrentCalls: require(""./source/no-concurrent-calls""), curriedDemethodify: require(""./source/curried-demethodify""), repeatAsyncUntil: require(""./source/repeat-async-until""), numberOfDecimals: require(""./source/number-of-decimals""), createErrorType: require(""./source/create-error-type""), looselyMatches: require(""./source/loosely-matches""), tryOrCrash: require(""./source/try-or-crash""), sequentially: require(""./source/sequentially""), demethodify: require(""./source/demethodify""), factorify: require(""./source/factorify""), methodify: require(""./source/methodify""), toAsync: require(""./source/to-async""), delayed: require(""./source/delayed""), compact: require(""./source/compact""), assert: require(""./source/assert""), delay: require(""./source/delay"") }; ","""use strict""; module.exports = { makeRandomAlphanumericalString: require(""./source/make-random-alphanumerical-string""), addOneTimeListener: require(""./source/add-one-time-listener""), noConcurrentCalls: require(""./source/no-concurrent-calls""), curriedDemethodify: require(""./source/curried-demethodify""), repeatAsyncUntil: require(""./source/repeat-async-until""), createErrorType: require(""./source/create-error-type""), looselyMatches: require(""./source/loosely-matches""), tryOrCrash: require(""./source/try-or-crash""), sequentially: require(""./source/sequentially""), demethodify: require(""./source/demethodify""), factorify: require(""./source/factorify""), methodify: require(""./source/methodify""), toAsync: require(""./source/to-async""), delayed: require(""./source/delayed""), compact: require(""./source/compact""), assert: require(""./source/assert""), delay: require(""./source/delay"") }; " Update gruntfile tasks for changes to source.,"module.exports = function(grunt) { 'use strict'; var host = grunt.option('host') || 'localhost'; grunt.loadNpmTasks('grunt-contrib'); grunt.loadNpmTasks('grunt-karma'); grunt.initConfig({ concat: { all: { files: { 'dist/skate.js': [ 'src/skate.js' ] } } }, connect: { docs: { options: { keepalive: true, hostname: host, open: 'http://' + host + ':8000/docs' } } }, karma: { all: { options: { browsers: ['PhantomJS'], files: [ 'src/skate.js', 'tests/skate.js' ], frameworks: ['mocha', 'sinon-chai'], singleRun: true } } }, uglify: { all: { files: { 'dist/skate.min.js': 'dist/skate.js' } } }, watch: { test: { files: ['src/*.js'], tasks: ['dist'] } } }); grunt.registerTask('build', 'Runs the tests and builds the dist.', ['test']); grunt.registerTask('dist', 'Builds the dist.', ['concat', 'uglify']); grunt.registerTask('docs', 'Runs the docs server.', ['connect:docs']) grunt.registerTask('test', 'Runs the tests.', ['dist', 'karma']); }; ","module.exports = function(grunt) { 'use strict'; var host = grunt.option('host') || 'localhost'; grunt.loadNpmTasks('grunt-contrib'); grunt.loadNpmTasks('grunt-karma'); grunt.initConfig({ concat: { all: { files: { 'dist/skate.js': [ 'src/skate.js' ] } } }, connect: { docs: { options: { keepalive: true, hostname: host, open: 'http://' + host + ':8000/docs' } } }, karma: { all: { options: { browsers: ['PhantomJS'], files: [ 'dist/skate.js', 'tests/skate.js' ], frameworks: ['mocha', 'sinon-chai'], singleRun: true } } }, uglify: { all: { files: { 'dist/skate.min.js': 'dist/skate.js' } } }, watch: { test: { files: ['src/*.js'], tasks: ['dist'] } } }); grunt.registerTask('build', 'Runs the tests and builds the dist.', ['test']); grunt.registerTask('dist', 'Builds the dist.', ['concat', 'uglify']); grunt.registerTask('docs', 'Runs the docs server.', ['connect:docs']) grunt.registerTask('test', 'Runs the tests.', ['dist', 'karma']); }; " Switch import from ugettext to gettext,"from django.core.paginator import InvalidPage, Paginator from django.http import Http404 from django.utils.translation import gettext as _ from haystack.forms import FacetedSearchForm from haystack.query import SearchQuerySet from haystack.views import FacetedSearchView class SearchView(FacetedSearchView): template = 'search/search.htm' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form_class = FacetedSearchForm self.searchqueryset = SearchQuerySet() def build_page(self): page = self.request.resolver_match.kwargs.get('page') or self.request.GET.get('page') or 1 try: page_number = int(page) except ValueError: if page == 'last': page_number = paginator.num_pages else: raise Http404(_(""Page is not 'last', nor can it be converted to an int."")) paginator = Paginator(self.results, self.results_per_page) try: page = paginator.page(page_number) except InvalidPage: raise Http404(_('Invalid page (%(page_number)s)') % { 'page_number': page_number }) return (paginator, page) def extra_context(self): context = super().extra_context() context.update({'is_paginated': bool(self.query)}) return context ","from django.core.paginator import InvalidPage, Paginator from django.http import Http404 from django.utils.translation import ugettext as _ from haystack.forms import FacetedSearchForm from haystack.query import SearchQuerySet from haystack.views import FacetedSearchView class SearchView(FacetedSearchView): template = 'search/search.htm' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form_class = FacetedSearchForm self.searchqueryset = SearchQuerySet() def build_page(self): page = self.request.resolver_match.kwargs.get('page') or self.request.GET.get('page') or 1 try: page_number = int(page) except ValueError: if page == 'last': page_number = paginator.num_pages else: raise Http404(_(""Page is not 'last', nor can it be converted to an int."")) paginator = Paginator(self.results, self.results_per_page) try: page = paginator.page(page_number) except InvalidPage: raise Http404(_('Invalid page (%(page_number)s)') % { 'page_number': page_number }) return (paginator, page) def extra_context(self): context = super().extra_context() context.update({'is_paginated': bool(self.query)}) return context " Fix (Feedback): Change style to lanscape phone,"<?php namespace AppBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\Extension\Core\Type\TextareaType; use Symfony\Component\Form\Extension\Core\Type\EmailType; class FeedbackType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name', TextType::class, array( 'attr' => array( 'class' => ''), )) ->add('email', EmailType::class, array( 'attr' => array( 'class' => ''), )) ->add('object', TextType::class, array( 'attr' => array( 'class' => ''), )) ->add('message', TextareaType::class, array( 'attr' => array( 'class' => 'materialize-textarea'), )) ; } public function setDefaultOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'error_bubbling' => true )); } public function getName() { return 'feedback_form'; } } ","<?php namespace AppBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\Extension\Core\Type\TextareaType; use Symfony\Component\Form\Extension\Core\Type\EmailType; use Symfony\Component\Validator\Constraints\Email; use Symfony\Component\Validator\Constraints\NotBlank; class FeedbackType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name', TextType::class, array( 'attr' => array( 'class' => ''), )) ->add('email', EmailType::class, array( 'attr' => array( 'class' => ''), )) ->add('object', TextType::class, array( 'attr' => array( 'class' => ''), )) ->add('message', TextareaType::class, array( 'attr' => array( 'class' => 'materialize-textarea'), )) ; } public function setDefaultOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'error_bubbling' => true )); } public function getName() { return 'feedback_form'; } } " Include one tank on player 1 on game creation,"import Queue import json import EBQP from . import world from . import types from . import consts class GameRequestHandler: def __init__(self): self.world = None self.responses = { EBQP.new: self.respond_new, } def process(self, request): request_pieces = request.split(EBQP.packet_delimiter, 1) command = request_pieces[0] params = request_pieces[1].strip() if len(request_pieces) > 1 else '' try: json_args = json.loads(params) except Exception as e: return ""process:failure:bad json"" if command in self.responses: return self.responses[command](json_args) else: return ""process:failure:unsupported command"" def respond_new(self, args): if 'uid1' not in args or 'uid2' not in args: return 'new:failure:missing uid' uid1 = args['uid1'] uid2 = args['uid2'] self.world = world.World([uid1, uid2]) self.world.add_unit(uid1, types.new_unit('Tank', consts.RED)) self.responses = { EBQP.view: self.respond_view, EBQP.move: self.respond_move, } return 'new:success' def respond_view(self, args): return 'view:success:%s' % self.world.to_json() #TODO def respond_move(self, args): return 'move:failure:unimplemented' ","import Queue import json import EBQP from . import world class GameRequestHandler: def __init__(self): self.world = None self.responses = { EBQP.new: self.respond_new, } def process(self, request): request_pieces = request.split(EBQP.packet_delimiter, 1) command = request_pieces[0] params = request_pieces[1].strip() if len(request_pieces) > 1 else '' try: json_args = json.loads(params) except Exception as e: return ""process:failure:bad json"" if command in self.responses: return self.responses[command](json_args) else: return ""process:failure:unsupported command"" def respond_new(self, args): if 'uid1' not in args or 'uid2' not in args: return 'new:failure:missing uid' uid1 = args['uid1'] uid2 = args['uid2'] self.world = world.World([uid1, uid2]) self.responses = { EBQP.view: self.respond_view, EBQP.move: self.respond_move, } return 'new:success' def respond_view(self, args): return 'view:success:%s' % self.world.to_json() #TODO def respond_move(self, args): return 'move:failure:unimplemented' " "Fix popup & encode URI components URL encode `var data` to prevent issues with titles containing an `&`, sql injection etc. Alternative method to prevent CMS popup with changed fields.","(function ($) { $.entwine('ss', function ($) { $('.ss-seo-editor .ss-gridfield-item input, .ss-seo-editor .ss-gridfield-item textarea').entwine({ onchange: function () { // kill the popup for form changes $('.cms-edit-form').removeClass('changed'); var $this = $(this); var id = $this.closest('tr').attr('data-id'); var url = $this.closest('.ss-gridfield').attr('data-url') + ""/update/"" + id; var data = encodeURIComponent($this.attr('name')) + '=' + encodeURIComponent($(this).val()); statusMessage('Saving changes', 'good'); $.post( url, data, function (data, textStatus) { statusMessage(data.message, data.type); $this.closest('td').removeClass(); if (data.errors.length) { $this.closest('td').addClass('seo-editor-error'); data.errors.forEach(function(error) { $this.closest('td').addClass(error) }); } else { $this.closest('td').addClass('seo-editor-valid'); } }, 'json' ); } }); }); }(jQuery)); ","(function ($) { $.entwine('ss', function ($) { $('.ss-seo-editor .ss-gridfield-item input, .ss-seo-editor .ss-gridfield-item textarea').entwine({ onchange: function () { // kill the popup for form changes window.onbeforeunload = null; var $this = $(this); var id = $this.closest('tr').attr('data-id'); var url = $this.closest('.ss-gridfield').attr('data-url') + ""/update/"" + id; var data = $this.attr('name') + '=' + $(this).val(); statusMessage('Saving changes', 'good'); $.post( url, data, function (data, textStatus) { statusMessage(data.message, data.type); $this.closest('td').removeClass(); if (data.errors.length) { $this.closest('td').addClass('seo-editor-error'); data.errors.forEach(function(error) { $this.closest('td').addClass(error) }); } else { $this.closest('td').addClass('seo-editor-valid'); } }, 'json' ); } }); }); }(jQuery));" Fix test: JSX pragma is deprecated in React 0.12,"'use strict' var React = require('react-tools/build/modules/React'); var statusForm = React.createClass({ render: function(){ return <form class=""form-horizontal"" role=""form""> <div class=""form-group""> <label for=""brand-lead"" class=""col-sm-4 control-label"">Brand lead:</label> <div class=""col-sm-8""> <input class=""form-control"" placeholder=""brand lead"" type=""text"" id=""brand-lead"" ref=""brandLead"" data-state=""brandLead"" /> </div> </div> <div class=""form-group""> <label for=""status-text"" class=""col-sm-4 control-label"">Status:</label> <div class=""col-sm-8""> <textarea id=""status-text"" class=""form-control"" rows=""40"" ref=""statusText"" data-state=""statusText""/> </div> </div> <input class=""btn btn-success"" type=""submit"" value=""Save status""/> </form> } }); module.exports = statusForm; ","/** @jsx React.DOM */ 'use strict' var React = require('react-tools/build/modules/React'); var statusForm = React.createClass({ render: function(){ return <form class=""form-horizontal"" role=""form""> <div class=""form-group""> <label for=""brand-lead"" class=""col-sm-4 control-label"">Brand lead:</label> <div class=""col-sm-8""> <input class=""form-control"" placeholder=""brand lead"" type=""text"" id=""brand-lead"" ref=""brandLead"" data-state=""brandLead"" /> </div> </div> <div class=""form-group""> <label for=""status-text"" class=""col-sm-4 control-label"">Status:</label> <div class=""col-sm-8""> <textarea id=""status-text"" class=""form-control"" rows=""40"" ref=""statusText"" data-state=""statusText""/> </div> </div> <input class=""btn btn-success"" type=""submit"" value=""Save status""/> </form> } }); module.exports = statusForm;" Fix source for join column,"<?php /* * This file is part of the DataGridBundle. * * (c) Abhoryo <abhoryo@free.fr> * (c) Stanislav Turza * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace APY\DataGridBundle\Grid\Column; class JoinColumn extends TextColumn { protected $joinColumns = array(); protected $dataJunction = self::DATA_DISJUNCTION; public function __initialize(array $params) { parent::__initialize($params); $this->setJoinColumns($this->getParam('columns', array())); $this->setSeparator($this->getParam('separator', ' ')); $this->setVisibleForSource(true); $this->setIsManualField(true); } public function setJoinColumns(array $columns) { $this->joinColumns = $columns; } public function getJoinColumns() { return $this->joinColumns; } public function getFilters($source) { $filters = array(); // Apply same filters on each column foreach ($this->joinColumns as $columnName) { $tempFilters = parent::getFilters($source); foreach ($tempFilters as $filter) { $filter->setColumnName($columnName); } $filters = array_merge($filters, $tempFilters); } return $filters; } public function getType() { return 'join'; } } ","<?php /* * This file is part of the DataGridBundle. * * (c) Abhoryo <abhoryo@free.fr> * (c) Stanislav Turza * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace APY\DataGridBundle\Grid\Column; class JoinColumn extends TextColumn { protected $joinColumns = array(); protected $dataJunction = self::DATA_DISJUNCTION; public function __initialize(array $params) { parent::__initialize($params); $this->setJoinColumns($this->getParam('columns', array())); $this->setSeparator($this->getParam('separator', ' ')); $this->setIsManualField(true); } public function setJoinColumns(array $columns) { $this->joinColumns = $columns; } public function getJoinColumns() { return $this->joinColumns; } public function getFilters($source) { $filters = array(); // Apply same filters on each column foreach ($this->joinColumns as $columnName) { $tempFilters = parent::getFilters($source); foreach ($tempFilters as $filter) { $filter->setColumnName($columnName); } $filters = array_merge($filters, $tempFilters); } return $filters; } public function getType() { return 'join'; } } " Add faceting test to Group index,"from algoliasearch_django import AlgoliaIndex class ChartIndex(AlgoliaIndex): fields = [ 'title', 'arrangers' ] settings = { 'searchableAttributes': [ 'title', 'arrangers', ] } class GroupIndex(AlgoliaIndex): should_index = 'is_active' fields = [ 'name', 'get_kind_display', 'get_gender_display', 'code', 'image', 'bhs_id', ] settings = { 'searchableAttributes': [ 'name', 'code', 'bhs_id', 'get_kind_display', ], 'attributesForFaceting': [ 'get_kind_display', ] } class PersonIndex(AlgoliaIndex): fields = [ 'first_name', 'middle_name', 'last_name', 'nick_name', 'get_gender_display', 'get_part_display', 'email', 'image', 'bhs_id', 'full_name', 'common_name', ] settings = { 'searchableAttributes': [ 'bhs_id,full_name', 'get_gender_display', 'get_part_display', 'email', ] } ","from algoliasearch_django import AlgoliaIndex class ChartIndex(AlgoliaIndex): fields = [ 'title', 'arrangers' ] settings = { 'searchableAttributes': [ 'title', 'arrangers', ] } class GroupIndex(AlgoliaIndex): should_index = 'is_active' fields = [ 'name', 'get_kind_display', 'get_gender_display', 'code', 'image', 'bhs_id', ] settings = { 'searchableAttributes': [ 'name', 'code', 'bhs_id', 'get_kind_display', ] } class PersonIndex(AlgoliaIndex): fields = [ 'first_name', 'middle_name', 'last_name', 'nick_name', 'get_gender_display', 'get_part_display', 'email', 'image', 'bhs_id', 'full_name', 'common_name', ] settings = { 'searchableAttributes': [ 'bhs_id,full_name', 'get_gender_display', 'get_part_display', 'email', ] } " Fix macroable conflict with dynamic relationships,"<?php declare(strict_types=1); namespace Rinvex\Support\Traits; use Error; use Exception; use BadMethodCallException; use Illuminate\Support\Traits\Macroable as BaseMacroable; trait Macroable { use BaseMacroable { BaseMacroable::__call as macroableCall; BaseMacroable::__callStatic as macroableCallStatic; } /** * Handle dynamic method calls into the model. * * @param string $method * @param array $parameters * * @return mixed */ public function __call($method, $parameters) { if (in_array($method, ['increment', 'decrement'])) { return $this->{$method}(...$parameters); } try { if ($resolver = (static::$relationResolvers[get_class($this)][$method] ?? null)) { return $resolver($this); } return $this->forwardCallTo($this->newQuery(), $method, $parameters); } catch (Error | BadMethodCallException $e) { if ($method !== 'macroableCall') { return $this->macroableCall($method, $parameters); } } } /** * Handle dynamic static method calls into the method. * * @param string $method * @param array $parameters * * @return mixed */ public static function __callStatic($method, $parameters) { try { return (new static())->{$method}(...$parameters); } catch (Exception $e) { if ($method !== 'macroableCallStatic') { return (new static())::macroableCallStatic($method, $parameters); } } } } ","<?php declare(strict_types=1); namespace Rinvex\Support\Traits; use Error; use Exception; use BadMethodCallException; use Illuminate\Support\Traits\Macroable as BaseMacroable; trait Macroable { use BaseMacroable { BaseMacroable::__call as macroableCall; BaseMacroable::__callStatic as macroableCallStatic; } /** * Handle dynamic method calls into the model. * * @param string $method * @param array $parameters * * @return mixed */ public function __call($method, $parameters) { if (in_array($method, ['increment', 'decrement'])) { return $this->{$method}(...$parameters); } try { return $this->forwardCallTo($this->newQuery(), $method, $parameters); } catch (Error | BadMethodCallException $e) { if ($method !== 'macroableCall') { return $this->macroableCall($method, $parameters); } } } /** * Handle dynamic static method calls into the method. * * @param string $method * @param array $parameters * * @return mixed */ public static function __callStatic($method, $parameters) { try { return (new static())->{$method}(...$parameters); } catch (Exception $e) { if ($method !== 'macroableCallStatic') { return (new static())::macroableCallStatic($method, $parameters); } } } } " Add currency handling and custom points!,"exports.names = ['settings', 'set']; exports.hidden = true; exports.enabled = true; exports.matchStart = true; exports.handler = function (data) { if (bot.hasPermission(bot.getUser(data.user.id), 'queue-order')) { var input = data.message.split(' '); // Settings to support direct access to supported = ['activeDJTimeoutMins', 'minActiveDJQueueLength', 'maxSongLengthSecs', 'chatRandomnessPercentage', 'quietMode', 'upvoteSongs', 'verboseLogging', 'welcomeUsers' ]; var settings = []; var chatMessage = """"; if (input.length < 3) { for (var key in config) { if (config.hasOwnProperty(key) && _.contains(supported, key)) { chatMessage += key + ': ' + config[key] + ', '; } } bot.sendChat('Current settings: ' + chatMessage); } else { var key = input[1]; var value = _.rest(input, 2).join(' '); if (_.contains(supported, key)) { config[key] = value; bot.sendChat('/me set: ' + key + ' = ' + value); } else { bot.sendChat('/me unknown setting: ' + key); } } } }; ","exports.names = ['settings', 'set']; exports.hidden = true; exports.enabled = true; exports.matchStart = true; exports.handler = function (data) { if (bot.hasPermission(bot.getUser(data.user.id), 'queue-order')) { var input = data.message.split(' '); // Settings to support direct access to supported = ['activeDJTimeoutMins', 'maxSongLengthSecs', 'prohibitMehInLine', 'quietMode', 'upvoteSongs', 'verboseLogging', 'welcomeUsers' ]; var settings = []; var chatMessage = """"; if (input.length < 3) { for (var key in config) { if (config.hasOwnProperty(key) && _.contains(supported, key)) { chatMessage += key + ': ' + config[key] + ', '; } } bot.sendChat('Current settings: ' + chatMessage); } else { var key = input[1]; var value = _.rest(input, 2).join(' '); if (_.contains(supported, key)) { config[key] = value; bot.sendChat('/me set: ' + key + ' = ' + value); } else { bot.sendChat('/me unknown setting: ' + key); } } } }; " Remove comment from check nslookup,"# -*- coding: utf-8 -*- import logging from util import full_stack from util import check_nslookup from util import get_credentials_for from dbaas_dnsapi.models import DatabaseInfraDNSList from dbaas_credentials.models import CredentialType from ..base import BaseStep from ....exceptions.error_codes import DBAAS_0005 LOG = logging.getLogger(__name__) class CheckDns(BaseStep): def __unicode__(self): return ""Waiting dns propagation..."" def do(self, workflow_dict): try: if not 'databaseinfra' in workflow_dict: return False dns_credentials = get_credentials_for(environment=workflow_dict['environment'], credential_type=CredentialType.DNSAPI) dns_list = DatabaseInfraDNSList.objects.filter(databaseinfra=workflow_dict['databaseinfra'].id) for dns in dns_list: LOG.info(""Checking dns %s on %s"" % (dns.dns, dns_credentials.project)) check_nslookup(dns.dns, dns_credentials.project) return True except Exception: traceback = full_stack() workflow_dict['exceptions']['error_codes'].append(DBAAS_0005) workflow_dict['exceptions']['traceback'].append(traceback) return False def undo(self, workflow_dict): LOG.info(""Nothing to do here..."") return True ","# -*- coding: utf-8 -*- import logging from util import full_stack from util import check_nslookup from util import get_credentials_for from dbaas_dnsapi.models import DatabaseInfraDNSList from dbaas_credentials.models import CredentialType from ..base import BaseStep from ....exceptions.error_codes import DBAAS_0005 LOG = logging.getLogger(__name__) class CheckDns(BaseStep): def __unicode__(self): return ""Waiting dns propagation..."" def do(self, workflow_dict): try: if not 'databaseinfra' in workflow_dict: return False dns_credentials = get_credentials_for(environment=workflow_dict['environment'], credential_type=CredentialType.DNSAPI) dns_list = DatabaseInfraDNSList.objects.filter(databaseinfra=workflow_dict['databaseinfra'].id) for dns in dns_list: LOG.info(""Checking dns %s on %s"" % (dns.dns, dns_credentials.project)) #check_nslookup(dns.dns, dns_credentials.project) return True except Exception: traceback = full_stack() workflow_dict['exceptions']['error_codes'].append(DBAAS_0005) workflow_dict['exceptions']['traceback'].append(traceback) return False def undo(self, workflow_dict): LOG.info(""Nothing to do here..."") return True " Make tests pass on python3,"from __future__ import absolute_import, unicode_literals from unittest import skipUnless from prometheus_client import Counter from prometheus_client import CollectorRegistry, generate_latest try: from prometheus_client.twisted import MetricsResource from twisted.trial.unittest import TestCase from twisted.web.server import Site from twisted.web.resource import Resource from twisted.internet import reactor from twisted.web.client import Agent from twisted.web.client import readBody HAVE_TWISTED = True except ImportError: from unittest import TestCase HAVE_TWISTED = False class MetricsResourceTest(TestCase): @skipUnless(HAVE_TWISTED, ""Don't have twisted installed."") def setUp(self): self.registry = CollectorRegistry() def test_reports_metrics(self): """""" ``MetricsResource`` serves the metrics from the provided registry. """""" c = Counter('cc', 'A counter', registry=self.registry) c.inc() root = Resource() root.putChild(b'metrics', MetricsResource(registry=self.registry)) server = reactor.listenTCP(0, Site(root)) self.addCleanup(server.stopListening) agent = Agent(reactor) port = server.getHost().port url = ""http://localhost:{port}/metrics"".format(port=port) d = agent.request(b""GET"", url.encode(""ascii"")) d.addCallback(readBody) d.addCallback(self.assertEqual, generate_latest(self.registry)) return d ","from __future__ import absolute_import, unicode_literals from unittest import skipUnless from prometheus_client import Counter from prometheus_client import CollectorRegistry, generate_latest try: from prometheus_client.twisted import MetricsResource from twisted.trial.unittest import TestCase from twisted.web.server import Site from twisted.web.resource import Resource from twisted.internet import reactor from twisted.web.client import Agent from twisted.web.client import readBody HAVE_TWISTED = True except ImportError: from unittest import TestCase HAVE_TWISTED = False class MetricsResourceTest(TestCase): @skipUnless(HAVE_TWISTED, ""Don't have twisted installed."") def setUp(self): self.registry = CollectorRegistry() def test_reports_metrics(self): """""" ``MetricsResource`` serves the metrics from the provided registry. """""" c = Counter('cc', 'A counter', registry=self.registry) c.inc() root = Resource() root.putChild(b'metrics', MetricsResource(registry=self.registry)) server = reactor.listenTCP(0, Site(root)) self.addCleanup(server.stopListening) agent = Agent(reactor) port = server.getHost().port url = u""http://localhost:{port}/metrics"".format(port=port) d = agent.request(b""GET"", url.encode(""ascii"")) d.addCallback(readBody) d.addCallback(self.assertEqual, generate_latest(self.registry)) return d " Add Gauge component to src/index,"module.exports = { BarChart: require('./components/BarChart'), Button: require('./components/Button'), ButtonGroup: require('./components/ButtonGroup'), Calendar: require('./components/Calendar'), Column: require('./components/grid/Column'), DatePicker: require('./components/DatePicker'), DatePickerFullScreen: require('./components/DatePickerFullScreen'), DateRangePicker: require('./components/DateRangePicker'), DateTimePicker: require('./components/DateTimePicker'), DisplayInput: require('./components/DisplayInput'), DonutChart: require('./components/DonutChart'), Drawer: require('./components/Drawer'), FileUpload: require('./components/FileUpload'), Gauge: require('./components/Gauge'), Icon: require('./components/Icon'), Loader: require('./components/Loader'), Modal: require('./components/Modal'), PageIndicator: require('./components/PageIndicator'), ProgressBar: require('./components/ProgressBar'), RadioButton: require('./components/RadioButton'), RajaIcon: require('./components/RajaIcon'), Row: require('./components/grid/Row'), RangeSelector: require('./components/RangeSelector'), SearchInput: require('./components/SearchInput'), Select: require('./components/Select'), SelectFullScreen: require('./components/SelectFullScreen'), SimpleInput: require('./components/SimpleInput'), SimpleSelect: require('./components/SimpleSelect'), Spin: require('./components/Spin'), TimeBasedLineChart: require('./components/TimeBasedLineChart'), ToggleSwitch: require('./components/ToggleSwitch'), Tooltip: require('./components/Tooltip'), TypeAhead: require('./components/TypeAhead'), AppConstants: require('./constants/App'), Styles: require('./constants/Style') }; ","module.exports = { BarChart: require('./components/BarChart'), Button: require('./components/Button'), ButtonGroup: require('./components/ButtonGroup'), Calendar: require('./components/Calendar'), Column: require('./components/grid/Column'), DatePicker: require('./components/DatePicker'), DatePickerFullScreen: require('./components/DatePickerFullScreen'), DateRangePicker: require('./components/DateRangePicker'), DateTimePicker: require('./components/DateTimePicker'), DisplayInput: require('./components/DisplayInput'), DonutChart: require('./components/DonutChart'), Drawer: require('./components/Drawer'), FileUpload: require('./components/FileUpload'), Icon: require('./components/Icon'), Loader: require('./components/Loader'), Modal: require('./components/Modal'), PageIndicator: require('./components/PageIndicator'), ProgressBar: require('./components/ProgressBar'), RadioButton: require('./components/RadioButton'), RajaIcon: require('./components/RajaIcon'), Row: require('./components/grid/Row'), RangeSelector: require('./components/RangeSelector'), SearchInput: require('./components/SearchInput'), Select: require('./components/Select'), SelectFullScreen: require('./components/SelectFullScreen'), SimpleInput: require('./components/SimpleInput'), SimpleSelect: require('./components/SimpleSelect'), Spin: require('./components/Spin'), TimeBasedLineChart: require('./components/TimeBasedLineChart'), ToggleSwitch: require('./components/ToggleSwitch'), Tooltip: require('./components/Tooltip'), TypeAhead: require('./components/TypeAhead'), AppConstants: require('./constants/App'), Styles: require('./constants/Style') }; " Throw Invalid Argument Exception when no args passed through to push and unshift,"<?php namespace Stack; use Symfony\Component\HttpKernel\HttpKernelInterface; class Builder { private $specs; public function __construct() { $this->specs = new \SplStack(); } public function unshift(/*$kernelClass, $args...*/) { if (func_num_args() > 0) { $spec = func_get_args(); $this->specs->unshift($spec); } else { throw new \InvalidArgumentException(""Missing argument(s) when calling unshift""); } return $this; } public function push(/*$kernelClass, $args...*/) { if (func_num_args() > 0) { $spec = func_get_args(); $this->specs->push($spec); } else { throw new \InvalidArgumentException(""Missing argument(s) when calling push""); } return $this; } public function resolve(HttpKernelInterface $app) { $middlewares = array($app); foreach ($this->specs as $spec) { $args = $spec; $firstArg = array_shift($args); if (is_callable($firstArg)) { $app = $firstArg($app); } else { $kernelClass = $firstArg; array_unshift($args, $app); $reflection = new \ReflectionClass($kernelClass); $app = $reflection->newInstanceArgs($args); } array_unshift($middlewares, $app); } return new StackedHttpKernel($app, $middlewares); } } ","<?php namespace Stack; use Symfony\Component\HttpKernel\HttpKernelInterface; class Builder { private $specs; public function __construct() { $this->specs = new \SplStack(); } public function unshift(/*$kernelClass, $args...*/) { if (func_num_args() > 0) { $spec = func_get_args(); $this->specs->unshift($spec); } return $this; } public function push(/*$kernelClass, $args...*/) { if (func_num_args() > 0) { $spec = func_get_args(); $this->specs->push($spec); } return $this; } public function resolve(HttpKernelInterface $app) { $middlewares = array($app); foreach ($this->specs as $spec) { $args = $spec; $firstArg = array_shift($args); if (is_callable($firstArg)) { $app = $firstArg($app); } else { $kernelClass = $firstArg; array_unshift($args, $app); $reflection = new \ReflectionClass($kernelClass); $app = $reflection->newInstanceArgs($args); } array_unshift($middlewares, $app); } return new StackedHttpKernel($app, $middlewares); } } " Fix installation on systems where locales are not properly configured,"import codecs from distutils.core import setup def read(fname): ''' Read a file from the directory where setup.py resides ''' with codecs.open(fname, encoding='utf-8') as rfh: return rfh.read() try: description = read('README.txt') except: description = read('README.md') setup( name='python-ldap-test', version='0.2.2', author='Adrian Gruntkowski', author_email='adrian.gruntkowski@gmail.com', packages=['ldap_test', 'ldap_test.test'], url='https://github.com/zoldar/python-ldap-test/', license='LICENSE.txt', description=('Tool for testing code speaking with LDAP server. Allows to easily' ' configure and run an embedded, in-memory LDAP server. Uses' ' UnboundID LDAP SDK through Py4J.'), keywords=['testing', 'tests', 'test', 'ldap'], long_description=description, install_requires=[ ""py4j >= 0.10.2.1"", ], package_data={ '': ['*.txt'], 'ldap_test': ['*.jar'], }, options={ 'bdist_rpm': { 'build_requires':[ 'python', 'python-setuptools', 'py4j', ], 'requires':[ 'python', 'py4j', ], }, }, ) ","from distutils.core import setup from setuptools.command.install import install try: description = open('README.txt').read() except: description = open('README.md').read() setup( name='python-ldap-test', version='0.2.2', author='Adrian Gruntkowski', author_email='adrian.gruntkowski@gmail.com', packages=['ldap_test', 'ldap_test.test'], url='https://github.com/zoldar/python-ldap-test/', license='LICENSE.txt', description=('Tool for testing code speaking with LDAP server. Allows to easily' ' configure and run an embedded, in-memory LDAP server. Uses' ' UnboundID LDAP SDK through Py4J.'), keywords = ['testing', 'tests', 'test', 'ldap'], long_description=description, install_requires=[ ""py4j >= 0.10.2.1"", ], package_data={ '': ['*.txt'], 'ldap_test': ['*.jar'], }, options={ 'bdist_rpm': { 'build_requires':[ 'python', 'python-setuptools', 'py4j', ], 'requires':[ 'python', 'py4j', ], }, }, ) " "Add ""ably"" in comment as a broadcast connection https://github.com/laravel/laravel/pull/5531","<?php return [ /* |-------------------------------------------------------------------------- | Default Broadcaster |-------------------------------------------------------------------------- | | This option controls the default broadcaster that will be used by the | framework when an event needs to be broadcast. You may set this to | any of the connections defined in the ""connections"" array below. | | Supported: ""pusher"", ""ably"", ""redis"", ""log"", ""null"" | */ 'default' => env('BROADCAST_DRIVER', 'null'), /* |-------------------------------------------------------------------------- | Broadcast Connections |-------------------------------------------------------------------------- | | Here you may define all of the broadcast connections that will be used | to broadcast events to other systems or over websockets. Samples of | each available type of connection are provided inside this array. | */ 'connections' => [ 'pusher' => [ 'driver' => 'pusher', 'key' => env('PUSHER_APP_KEY'), 'secret' => env('PUSHER_APP_SECRET'), 'app_id' => env('PUSHER_APP_ID'), 'options' => [ 'cluster' => env('PUSHER_APP_CLUSTER'), 'encrypted' => true, ], ], 'redis' => [ 'driver' => 'redis', 'connection' => 'default', ], 'log' => [ 'driver' => 'log', ], 'null' => [ 'driver' => 'null', ], ], ]; ","<?php return [ /* |-------------------------------------------------------------------------- | Default Broadcaster |-------------------------------------------------------------------------- | | This option controls the default broadcaster that will be used by the | framework when an event needs to be broadcast. You may set this to | any of the connections defined in the ""connections"" array below. | | Supported: ""pusher"", ""redis"", ""log"", ""null"" | */ 'default' => env('BROADCAST_DRIVER', 'null'), /* |-------------------------------------------------------------------------- | Broadcast Connections |-------------------------------------------------------------------------- | | Here you may define all of the broadcast connections that will be used | to broadcast events to other systems or over websockets. Samples of | each available type of connection are provided inside this array. | */ 'connections' => [ 'pusher' => [ 'driver' => 'pusher', 'key' => env('PUSHER_APP_KEY'), 'secret' => env('PUSHER_APP_SECRET'), 'app_id' => env('PUSHER_APP_ID'), 'options' => [ 'cluster' => env('PUSHER_APP_CLUSTER'), 'encrypted' => true, ], ], 'redis' => [ 'driver' => 'redis', 'connection' => 'default', ], 'log' => [ 'driver' => 'log', ], 'null' => [ 'driver' => 'null', ], ], ]; " feat(form): Change color of mode button checkboxes to green,"import React, {PropTypes, Component} from 'react' import { getModeIcon } from '../../util/itinerary' export default class ModeButton extends Component { static propTypes = { active: PropTypes.bool, label: PropTypes.string, mode: PropTypes.string, icons: PropTypes.object, onClick: PropTypes.func } render () { const {active, icons, label, mode, onClick} = this.props const buttonColor = active ? '#000' : '#bbb' return ( <div className='mode-button-container'> <button className='mode-button' onClick={onClick} title={mode} style={{ borderColor: buttonColor }} > <div className='mode-icon' style={{ fill: buttonColor }}> {getModeIcon(mode, icons)} </div> </button> <div className='mode-label' style={{ color: buttonColor }}>{label}</div> {active && <div> <div className='mode-check' style={{ color: 'white' }}><i className='fa fa-circle' /></div> <div className='mode-check' style={{ color: 'green' }}><i className='fa fa-check-circle' /></div> </div>} </div> ) } } ","import React, {PropTypes, Component} from 'react' import { getModeIcon } from '../../util/itinerary' export default class ModeButton extends Component { static propTypes = { active: PropTypes.bool, label: PropTypes.string, mode: PropTypes.string, icons: PropTypes.object, onClick: PropTypes.func } render () { const {active, icons, label, mode, onClick} = this.props const buttonColor = active ? '#000' : '#bbb' return ( <div className='mode-button-container'> <button className='mode-button' onClick={onClick} title={mode} style={{ borderColor: buttonColor }} > <div className='mode-icon' style={{ fill: buttonColor }}> {getModeIcon(mode, icons)} </div> </button> <div className='mode-label' style={{ color: buttonColor }}>{label}</div> {active && <div> <div className='mode-check' style={{ color: 'white' }}><i className='fa fa-circle' /></div> <div className='mode-check' style={{ color: 'red' }}><i className='fa fa-check-circle' /></div> </div>} </div> ) } } " Update because CakePHP version changed,"<?php /** * Class UnitsController * Actions related to dealing with units * @author Stuart Chalk <schalk@unf.edu> * */ class UnitsController extends AppController { public $uses=['Unit']; /** * beforeFilter function */ public function beforeFilter() { parent::beforeFilter(); $this->Auth->allow(); } /** * List the quantities * @param $qid - quantityID */ public function index($qid="""",$format="""") { if($qid=="""") { $data=$this->Unit->find('list',['fields'=>['id','name'],'order'=>['name']]); } else { $data=$this->Unit->find('list',['fields'=>['id','name'],'conditions'=>['quantity_id'=>$qid],'order'=>['name']]); } if($format==""json"") { echo json_encode($data); exit; } $this->set('data',$data); } /** * Regex test function */ public function regex() { $s=""05 Nov 2007 17:38:45""; $r=""/^([0-9]{1,2}) ([a-zA-Z]{3}) ([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/""; preg_match($r,$s,$m); debug($m);exit; } }","<?php /** * Class UnitsController * Actions related to dealing with units * @author Stuart Chalk <schalk@unf.edu> * */ class UnitsController extends AppController { public $uses=['Unit']; /** * beforeFilter function */ public function beforeFilter() { parent::beforeFilter(); $this->Auth->allow(); } /** * List the quantities * @param $qid - quantityID */ public function index($qid="""",$format="""") { if($qid=="""") { $data=$this->Unit->find('list',['fields'=>['id','name'],'order'=>['name']]); } else { $data=$this->Unit->find('list',['fields'=>['id','name'],'conditions'=>['quantity_id'=>$qid],'order'=>['name']]); } //echo ""<pre>"";print_r($data);echo ""</pre>"";exit; if($format==""json"") { echo json_encode($data); exit; } $this->set('data',$data); } /** * Regex test function */ public function regex() { $s=""05 Nov 2007 17:38:45""; $r=""/^([0-9]{1,2}) ([a-zA-Z]{3}) ([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/""; preg_match($r,$s,$m); debug($m);exit; } /** * JSON test function */ public function jsona() { $data=file_get_contents(WWW_ROOT.'/scidata_spectrum.txt'); echo ""<pre>"";json_decode(""["".$data.""]"");echo ""</pre>"";exit; } }" Move fields to top and give explicit name to id,"package com.alexstyl.specialdates.events; import android.support.annotation.ColorRes; import android.support.annotation.StringRes; import com.alexstyl.specialdates.R; import java.util.HashMap; import java.util.Map; public enum EventType { BIRTHDAY(EventColumns.TYPE_BIRTHDAY, R.string.birthday, R.color.birthday_red), NAMEDAY(EventColumns.TYPE_NAMEDAY, R.string.nameday, R.color.nameday_blue); private static final Map<Integer, EventType> map; private final int eventTypeId; private final int eventNameRes; private final int eventColorRes; static { map = new HashMap<>(); for (EventType eventType : values()) { map.put(eventType.eventTypeId, eventType); } } public static EventType fromId(@EventTypeId int eventTypeId) { if (map.containsKey(eventTypeId)) { return map.get(eventTypeId); } throw new IllegalArgumentException(""No event type with eventTypeId "" + eventTypeId); } EventType(@EventTypeId int eventTypeId, @StringRes int nameResId, @ColorRes int colorResId) { this.eventTypeId = eventTypeId; this.eventNameRes = nameResId; this.eventColorRes = colorResId; } @StringRes public int nameRes() { return eventNameRes; } @ColorRes public int getColorRes() { return eventColorRes; } } ","package com.alexstyl.specialdates.events; import android.support.annotation.ColorRes; import android.support.annotation.StringRes; import com.alexstyl.specialdates.R; import java.util.HashMap; import java.util.Map; public enum EventType { BIRTHDAY(EventColumns.TYPE_BIRTHDAY, R.string.birthday, R.color.birthday_red), NAMEDAY(EventColumns.TYPE_NAMEDAY, R.string.nameday, R.color.nameday_blue); private static final Map<Integer, EventType> map; static { map = new HashMap<>(); for (EventType eventType : values()) { map.put(eventType.id, eventType); } } private final int id; private final int eventNameRes; private final int eventColorRes; EventType(@EventTypeId int id, @StringRes int nameResId, @ColorRes int colorResId) { this.id = id; this.eventNameRes = nameResId; this.eventColorRes = colorResId; } @StringRes public int nameRes() { return eventNameRes; } @ColorRes public int getColorRes() { return eventColorRes; } public static EventType fromId(@EventTypeId int eventTypeId) { if (map.containsKey(eventTypeId)) { return map.get(eventTypeId); } throw new IllegalArgumentException(""No event type with id "" + eventTypeId); } } " Use doc instead of conditions,"/*! * Mongoose findOrCreate Plugin * Copyright(c) 2012 Nicholas Penree <nick@penree.com> * MIT Licensed */ function findOrCreatePlugin(schema, options) { schema.statics.findOrCreate = function findOrCreate(conditions, doc, options, callback) { if (arguments.length < 4) { if (typeof options === 'function') { // Scenario: findOrCreate(conditions, doc, callback) callback = options; options = {}; } else if (typeof doc === 'function') { // Scenario: findOrCreate(conditions, callback); callback = doc; doc = {}; options = {}; } } var self = this; this.findOne(conditions, function(err, result) { if(err || result) { if(options && options.upsert && !err) { self.update(conditions, doc, function(err, count){ self.findOne(conditions, function(err, result) { callback(err, result, false); }); }) } else { callback(err, result, false) } } else { for (var key in conditions) { doc[key] = conditions[key]; } var obj = new self(doc) obj.save(function(err) { callback(err, obj, true); }); } }) } } /** * Expose `findOrCreatePlugin`. */ module.exports = findOrCreatePlugin;","/*! * Mongoose findOrCreate Plugin * Copyright(c) 2012 Nicholas Penree <nick@penree.com> * MIT Licensed */ function findOrCreatePlugin(schema, options) { schema.statics.findOrCreate = function findOrCreate(conditions, doc, options, callback) { if (arguments.length < 4) { if (typeof options === 'function') { // Scenario: findOrCreate(conditions, doc, callback) callback = options; options = {}; } else if (typeof doc === 'function') { // Scenario: findOrCreate(conditions, callback); callback = doc; doc = {}; options = {}; } } var self = this; this.findOne(conditions, function(err, result) { if(err || result) { if(options && options.upsert && !err) { self.update(conditions, doc, function(err, count){ self.findOne(conditions, function(err, result) { callback(err, result, false); }); }) } else { callback(err, result, false) } } else { for (var key in conditions) { doc[key] = conditions[key]; } var obj = new self(conditions) obj.save(function(err) { callback(err, obj, true); }); } }) } } /** * Expose `findOrCreatePlugin`. */ module.exports = findOrCreatePlugin;" Correct template format of Textarea,"(function() { 'use strict'; angular .module('app') .directive('propText', TextDirective); TextDirective.$inject = ['$parse']; function TextDirective($parse) { var directive = { require : 'ngModel', restrict : 'E', template : templateFunction, link : linkFunction, }; return directive; function templateFunction($element, $attrs) { /* jshint -W043 */ return '<textarea id=""property-{{model.name}}""\ class=""form-control"" \ ng-change=""doChange()"" \ ng-model=""value"" \ ng-keydown=""onKeydown($event)""></textarea> \ <small></small>'; } function linkFunction($scope, $element, $attrs, $ctrl) { var model = $parse($attrs.ngModel)($scope); var change = $parse($attrs.ngChange)($scope); $scope.model = model; $scope.value = model.value; $scope.doChange = function() { model.value = $scope.value; change(); }; $scope.onKeydown = function(e) { if (e.ctrlKey && e.keyCode == 90) { e.preventDefault(); } return false; }; } } })();","(function() { 'use strict'; angular .module('app') .directive('propText', TextDirective); TextDirective.$inject = ['$parse']; function TextDirective($parse) { var directive = { require : 'ngModel', restrict : 'E', template : templateFunction, link : linkFunction, }; return directive; function templateFunction($element, $attrs) { /* jshint -W043 */ return '<textarea id=""property-{{model.name}}""\ class=""form-control"" \ ng-change=""doChange()"" \ ng-model=""value"" \ ng-keydown=""onKeydown($event)""><small></small>'; } function linkFunction($scope, $element, $attrs, $ctrl) { var model = $parse($attrs.ngModel)($scope); var change = $parse($attrs.ngChange)($scope); $scope.model = model; $scope.value = model.value; $scope.doChange = function() { model.value = $scope.value; change(); }; $scope.onKeydown = function(e) { if (e.ctrlKey && e.keyCode == 90) { e.preventDefault(); } return false; }; } } })();" Disable specific JSCS rules where necessary,"'use strict'; var walk = require('walk'), path = require('path'), fs = require('fs'); class FileSystemSourceRepository { // Awaiting resolution of https://github.com/jscs-dev/node-jscs/issues/1890 // jscs:disable disallowAnonymousFunctions constructor (configuration) { this.exclude = configuration.exclude; this.include = ['.js']; this.sources = null; } // Awaiting resolution of https://github.com/jscs-dev/node-jscs/issues/1890 // jscs:disable disallowAnonymousFunctions getAll () { if (this.sources === null) { this.sources = []; walk.walkSync('.', { filters: this.exclude, listeners: { file: appendSourceFile.bind(this) } }); } return this.sources; } } function appendSourceFile (root, stats, next) { /*jshint validthis:true */ var filePath = path.join(root, stats.name); if (this.include.indexOf(path.extname(stats.name)) !== -1) { this.sources.push({ getLines: function getLines () { return fs.readFileSync(this.location, 'utf8'); }, location: filePath }); } next(); } module.exports = FileSystemSourceRepository; ","'use strict'; var walk = require('walk'), path = require('path'), fs = require('fs'); class FileSystemSourceRepository { // Awaiting resolution of https://github.com/jscs-dev/node-jscs/issues/1890 // jscs:disable constructor (configuration) { this.exclude = configuration.exclude; this.include = ['.js']; this.sources = null; } // Awaiting resolution of https://github.com/jscs-dev/node-jscs/issues/1890 // jscs:disable getAll () { if (this.sources === null) { this.sources = []; walk.walkSync('.', { filters: this.exclude, listeners: { file: appendSourceFile.bind(this) } }); } return this.sources; } } function appendSourceFile (root, stats, next) { /*jshint validthis:true */ var filePath = path.join(root, stats.name); if (this.include.indexOf(path.extname(stats.name)) !== -1) { this.sources.push({ getLines: function getLines () { return fs.readFileSync(this.location, 'utf8'); }, location: filePath }); } next(); } module.exports = FileSystemSourceRepository; " "Add better enumeration for Notification The previous 'Kind' enumeration for Notification were using a home-made-cooked way of dealing with enumeration. The code were got from an article from the http://sametmax.com/ website (great website by the way). This new version uses the python 3.4 enumeration module, but as this module had been introduced in Python 3.4, it means that the Python 3.3 compatibility is broken.","from enum import Enum, unique class ENotifer(object): def notify(self, notification): notification.notifier = notification.notifier or self for listener in self._eternal_listener + self.listeners: listener.notifyChanged(notification) @unique class Kind(Enum): ADD = 0 ADD_MANY = 1 MOVE = 2 REMOVE = 3 REMOVE_MANY = 4 SET = 5 UNSET = 6 class Notification(object): def __init__(self, notifier=None, kind=None, old=None, new=None, feature=None): self.notifier = notifier self.kind = kind self.old = old self.new = new self.feature = feature def __repr__(self): return ('[{0}] old={1} new={2} obj={3} #{4}' .format(self.kind.name, self.old, self.new, self.notifier, self.feature)) class EObserver(object): def __init__(self, notifier=None, notifyChanged=None): if notifier: notifier.listeners.append(self) if notifyChanged: self.notifyChanged = notifyChanged def observe(self, notifier): notifier.listeners.append(self) def notifyChanged(self, notification): pass "," class ENotifer(object): def notify(self, notification): notification.notifier = notification.notifier or self for listener in self._eternal_listener + self.listeners: listener.notifyChanged(notification) def enum(enumName, *listValueNames): """"""Clever implementation of an enum like in python Shameless copy from: http://sametmax.com/faire-des-enums-en-python/ """""" listValueNumbers = range(len(listValueNames)) dictAttrib = dict(zip(listValueNames, listValueNumbers)) dictReverse = dict(zip(listValueNumbers, listValueNames)) dictAttrib[""dictReverse""] = dictReverse mainType = type(enumName, (), dictAttrib) return mainType Kind = enum('Kind', 'ADD', 'ADD_MANY', 'MOVE', 'REMOVE', 'REMOVE_MANY', 'SET', 'UNSET') class Notification(object): def __init__(self, notifier=None, kind=None, old=None, new=None, feature=None): self.notifier = notifier self.kind = kind self.old = old self.new = new self.feature = feature def __repr__(self): return ('[{0}] old={1} new={2} obj={3} #{4}' .format(Kind.dictReverse[self.kind], self.old, self.new, self.notifier, self.feature)) class EObserver(object): def __init__(self, notifier=None, notifyChanged=None): if notifier: notifier.listeners.append(self) if notifyChanged: self.notifyChanged = notifyChanged def observe(self, notifier): notifier.listeners.append(self) def notifyChanged(self, notification): pass " Add phpdoc for magic item() method,"<?php namespace Nodes\Api\Routing; use Dingo\Api\Routing\Helpers as DingoRoutingHelpers; /** * Class Helpers * * @trait * @package Nodes\Api\Routing * * @property \Illuminate\Database\Eloquent\Model $user * @property \Nodes\Api\Auth\Auth $auth * @property \Nodes\Api\Http\Response\Factory $response * @method Response item() item($item, $transformer, array $parameters = [], Closure $after = null) Bind an item to a transformer and start building a response */ trait Helpers { use DingoRoutingHelpers; /** * Get the authenticated user * * @author Morten Rugaard <moru@nodes.dk> * * @access protected * @return \Illuminate\Database\Eloquent\Model */ protected function user() { return app('api.auth')->user(); } /** * Get the auth instance * * @author Morten Rugaard <moru@nodes.dk> * * @access public * @return \Nodes\Api\Auth\Auth */ protected function auth() { return app('api.auth'); } /** * Get the response factory instance * * @author Morten Rugaard <moru@nodes.dk> * * @access protected * @return \Nodes\Api\Http\Response\Factory */ protected function response() { return app('api.http.response'); } } ","<?php namespace Nodes\Api\Routing; use Dingo\Api\Routing\Helpers as DingoRoutingHelpers; /** * Class Helpers * * @trait * @package Nodes\Api\Routing * * @property \Illuminate\Database\Eloquent\Model $user * @property \Nodes\Api\Auth\Auth $auth * @property \Nodes\Api\Http\Response\Factory $response */ trait Helpers { use DingoRoutingHelpers; /** * Get the authenticated user * * @author Morten Rugaard <moru@nodes.dk> * * @access protected * @return \Illuminate\Database\Eloquent\Model */ protected function user() { return app('api.auth')->user(); } /** * Get the auth instance * * @author Morten Rugaard <moru@nodes.dk> * * @access public * @return \Nodes\Api\Auth\Auth */ protected function auth() { return app('api.auth'); } /** * Get the response factory instance * * @author Morten Rugaard <moru@nodes.dk> * * @access protected * @return \Nodes\Api\Http\Response\Factory */ protected function response() { return app('api.http.response'); } }" Switch to file-based sourcemaps for msal.js and msal.min.js,"var path = require(""path""); var webpack = require(""webpack""); var UglifyJsPlugin = require('uglifyjs-webpack-plugin'); var package = require('./package'); var ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin'); var PATHS = { entryPoint: path.resolve(__dirname, 'src/index.ts'), bundles: path.resolve(__dirname, 'dist'), } module.exports = { mode: ""production"", entry: { 'msal': [PATHS.entryPoint], 'msal.min': [PATHS.entryPoint] }, output: { path: PATHS.bundles, filename: '[name].js', libraryTarget: 'umd', library: 'Msal', umdNamedDefine: true }, resolve: { extensions: ['.ts', '.tsx', '.js'] }, devtool: 'source-map', plugins: [ new ForkTsCheckerWebpackPlugin(), new webpack.BannerPlugin({ banner: `/*! ${package.name} v${package.version} ${new Date().toISOString().split('T')[0]} */\n'use strict';`, raw: true }) ], optimization: { minimize: true, minimizer: [new UglifyJsPlugin({ include: /\.min\.js$/, sourceMap: true })] }, module: { rules: [{ test: /\.(ts|tsx|js)?$/, use: { loader: 'ts-loader', options: { transpileOnly: true, } } }] } } ","var path = require(""path""); var webpack = require(""webpack""); var UglifyJsPlugin = require('uglifyjs-webpack-plugin'); var package = require('./package'); var ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin'); var PATHS = { entryPoint: path.resolve(__dirname, 'src/index.ts'), bundles: path.resolve(__dirname, 'dist'), } module.exports = { mode: ""production"", entry: { 'msal': [PATHS.entryPoint], 'msal.min': [PATHS.entryPoint] }, output: { path: PATHS.bundles, filename: '[name].js', libraryTarget: 'umd', library: 'Msal', umdNamedDefine: true }, resolve: { extensions: ['.ts', '.tsx', '.js'] }, devtool: 'inline-source-map', plugins: [ new ForkTsCheckerWebpackPlugin(), new webpack.BannerPlugin({ banner: `/*! ${package.name} v${package.version} ${new Date().toISOString().split('T')[0]} */\n'use strict';`, raw: true }) ], optimization: { minimize: true, minimizer: [new UglifyJsPlugin({ include: /\.min\.js$/ })] }, module: { rules: [{ test: /\.(ts|tsx|js)?$/, use: { loader: 'ts-loader', options: { transpileOnly: true, } } }] } }" Upgrade to spring boot 2 and java 9,"package se.jaitco.queueticketapi.service; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import se.jaitco.queueticketapi.model.Roles; import se.jaitco.queueticketapi.model.User; import java.util.Arrays; import java.util.Optional; @Slf4j @Component public class UserService { public Optional<User> getUser(String username) { Optional<User> user = Optional.empty(); if (""Aschan"".equals(username)) { User aschan = User.builder() .username(""Aschan"") .password(""{noop}Fotboll"") .grantedRoles(Arrays.asList(Roles.CUSTOMER, Roles.ADMIN)) .build(); user = Optional.of(aschan); } else if (""Lmar"".equals(username)) { User lmar = User.builder() .username(""Lmar"") .password(""{noop}Book"") .grantedRoles(Arrays.asList(Roles.ADMIN)) .build(); user = Optional.of(lmar); } return user; } } ","package se.jaitco.queueticketapi.service; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import se.jaitco.queueticketapi.model.Roles; import se.jaitco.queueticketapi.model.User; import java.util.Arrays; import java.util.Optional; @Slf4j @Component public class UserService { public Optional<User> getUser(String username) { Optional<User> user = Optional.empty(); if (""Aschan"".equals(username)) { User aschan = User.builder() .username(""Aschan"") .password(""Fotboll"") .grantedRoles(Arrays.asList(Roles.CUSTOMER, Roles.ADMIN)) .build(); user = Optional.of(aschan); } else if (""Lmar"".equals(username)) { User lmar = User.builder() .username(""Lmar"") .password(""Book"") .grantedRoles(Arrays.asList(Roles.ADMIN)) .build(); user = Optional.of(lmar); } return user; } } " Return lastInsertId of user creation,"<?php namespace ZerobRSS\Dao; use \Doctrine\DBAL\Connection as Db; class Users { /** @var Db */ private $db; public function __construct(Db $db) { $this->db = $db; } public function getUser($value, $column = 'id') { return $this->db->createQueryBuilder() ->select('*') ->from('users') ->where($column.' = :value') ->setParameter(':value', $value) ->execute(); } public function update($id, $values) { // Prepare update query $query = $this->db->createQueryBuilder() ->update('users') ->where('id = :id') ->setParameter(':id', $id); // Append parameters to update to the query foreach ($values as $key => $value) { $query = $query->set($key, ':'.$key)->setParameter(':'.$key, $value); } return $query->execute(); } public function create($values) { // Prepare insert query $query = $this->db->createQueryBuilder() ->insert('users'); // Append parameters to insert to the query foreach ($values as $key => $value) { $query = $query->setValue($key, ':'.$key)->setParameter(':'.$key, $value); } $query->execute(); // @TODO: Check if this works in MariaDB return $this->db->lastInsertId('users_id_seq'); } } ","<?php namespace ZerobRSS\Dao; use \Doctrine\DBAL\Connection as Db; class Users { /** @var Db */ private $db; public function __construct(Db $db) { $this->db = $db; } public function getUser($value, $column = 'id') { return $this->db->createQueryBuilder() ->select('*') ->from('users') ->where($column.' = :value') ->setParameter(':value', $value) ->execute(); } public function update($id, $values) { // Prepare update query $query = $this->db->createQueryBuilder() ->update('users') ->where('id = :id') ->setParameter(':id', $id); // Append parameters to update to the query foreach ($values as $key => $value) { $query = $query->set($key, ':'.$key)->setParameter(':'.$key, $value); } return $query->execute(); } public function create($values) { // Prepare insert query $query = $this->db->createQueryBuilder() ->insert('users'); // Append parameters to insert to the query foreach ($values as $key => $value) { $query = $query->setValue($key, ':'.$key)->setParameter(':'.$key, $value); } return $query->execute(); } } " Add construct and make bots attribute protected,"<?php include_once 'models/curl.php'; include_once 'models/grader/serializer.php'; include_once 'models/grader/bot.php'; class Grader { public $registeredBots; protected $game; protected $users; protected $bots = []; public function __construct( $users, $game ) { $this->users = $users; foreach ( $users as $user ) { $this->bots[] = new GraderBot( $user ); } $this->game = $game; } public function initiate() { $this->registeredBots = []; foreach ( $this->bots as $bot ) { try { $bot->sendInitiateRequest(); $this->registeredBots[] = $bot; } catch ( GraderBotException $e ) { } } } public function createGame() { $this->game->users = $this->users; $this->game->save(); foreach ( $this->registeredBots as $bot ) { $bot->sendGameRequest( $this->game ); } } public function nextRound() { $round = $this->game->getCurrentRound(); foreach ( $this->registeredBots as $bot ) { $bot->sendRoundRequest( $round ); } } } ?> ","<?php include_once 'models/curl.php'; include_once 'models/grader/serializer.php'; include_once 'models/grader/bot.php'; class Grader { public $bots; public $registeredBots; protected $game; public function initiate() { $this->registeredBots = []; foreach ( $this->bots as $bot ) { try { $bot->sendInitiateRequest(); $this->registeredBots[] = $bot; } catch ( GraderBotException $e ) { } } } public function createGame() { foreach ( $this->bots as $bot ) { $bot->sendGameRequest( $this->game ); } } public function nextRound() { $round = $this->game->getCurrentRound(); foreach ( $this->bots as $bot ) { $bot->sendRoundRequest( $round ); } } } ?> " Include sublime-keymap files in JSON format tests.,"from __future__ import absolute_import import fnmatch import os import unittest from . import validate_json_format class TestSettings(unittest.TestCase): def _get_json_files(self, file_pattern, folder='.'): for root, dirnames, filenames in os.walk(folder): for filename in fnmatch.filter(filenames, file_pattern): yield os.path.join(root, filename) for dirname in [d for d in dirnames if d not in ('.git', '.tox', '.idea')]: for f in self._get_json_files( file_pattern, os.path.join(root, dirname)): yield f def test_json_settings(self): """"""Test each JSON file."""""" file_patterns = ( '*.sublime-commands', '*.sublime-keymap', '*.sublime-menu', '*.sublime-settings' ) for file_pattern in file_patterns: for f in self._get_json_files(file_pattern): print(f) self.assertFalse( validate_json_format.CheckJsonFormat( False, True).check_format(f), ""%s does not comform to expected format!"" % f) ","from __future__ import absolute_import import fnmatch import os import unittest from . import validate_json_format class TestSettings(unittest.TestCase): def _get_json_files(self, file_pattern, folder='.'): for root, dirnames, filenames in os.walk(folder): for filename in fnmatch.filter(filenames, file_pattern): yield os.path.join(root, filename) for dirname in [d for d in dirnames if d not in ('.git', '.tox', '.idea')]: for f in self._get_json_files( file_pattern, os.path.join(root, dirname)): yield f def test_json_settings(self): """"""Test each JSON file."""""" file_patterns = ( '*.sublime-settings', '*.sublime-commands', '*.sublime-menu' ) for file_pattern in file_patterns: for f in self._get_json_files(file_pattern): print(f) self.assertFalse( validate_json_format.CheckJsonFormat( False, True).check_format(f), ""%s does not comform to expected format!"" % f) " Add synchronization of note position after dragdrop between tabs,"define([ 'backbone', 'models/noteModel', 'underscore', 'jquery', 'text!templates/noteTemplate.html', 'jquery.extensions' ], function (Backbone, model, _, $, template) { 'use strict'; var NoteView = Backbone.View.extend({ template: _.template(template), events: { 'click': 'click', 'click button.close': 'close' }, initialize: function () { this.listenTo(this.model, 'destroy', this.remove); }, render: function () { var $el = this.$el, model = this.model; $el. html(this.template(this.model.attributes)). addClass('note'). children('.head').drags({ handle:$el, ondragstop: function (e) { model.save('offset', $(e.target).offset()); } }).end(). offset(this.model.get('offset')); return this; }, click: function (e) { e.stopPropagation(); e.preventDefault(); }, close: function () { this.model.destroy(); } }); return NoteView; }); ","define([ 'backbone', 'models/noteModel', 'underscore', 'jquery', 'text!templates/noteTemplate.html', 'jquery.extensions' ], function (Backbone, model, _, $, template) { 'use strict'; var NoteView = Backbone.View.extend({ template: _.template(template), events: { 'click': 'click', 'click button.close': 'close' }, initialize: function () { this.listenTo(this.model, 'destroy', this.remove); }, render: function () { var $el = this.$el; this.$el. html(this.template(this.model.attributes)). addClass('note'). children('.head').drags({handle:$el}).end(). offset(this.model.get('offset')); return this; }, click: function (e) { e.stopPropagation(); e.preventDefault(); }, close: function () { this.model.destroy(); } }); return NoteView; }); " Return 400 response on login fail,"<?php namespace OpenCFP\Controller; use Silex\Application; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class SecurityController { public function indexAction(Request $req, Application $app) { $template = $app['twig']->loadTemplate('login.twig'); return $template->render(array()); } public function processAction(Request $req, Application $app) { $template = $app['twig']->loadTemplate('login.twig'); $template_data = array(); $code = 200; try { $page = new \OpenCFP\Login($app['sentry']); if ($page->authenticate($req->get('email'), $req->get('passwd'))) { return $app->redirect($app['url'] . '/dashboard'); } $template_data = array( 'user' => $app['sentry']->getUser(), 'email' => $req->get('email'), 'errorMessage' => $page->getAuthenticationMessage() ); $code = 400; } catch (Exception $e) { $template_data = array( 'user' => $app['sentry']->getUser(), 'email' => $req->get('email'), 'errorMessage' => $e->getMessage() ); $code = 400; } return new Response($template->render($template_data), $code); } public function outAction(Request $req, Application $app) { $app['sentry']->logout(); return $app->redirect($app['url'] . '/'); } } ","<?php namespace OpenCFP\Controller; use Silex\Application; use Symfony\Component\HttpFoundation\Request; class SecurityController { public function indexAction(Request $req, Application $app) { $template = $app['twig']->loadTemplate('login.twig'); return $template->render(array()); } public function processAction(Request $req, Application $app) { $template = $app['twig']->loadTemplate('login.twig'); $template_data = array(); try { $page = new \OpenCFP\Login($app['sentry']); if ($page->authenticate($req->get('email'), $req->get('passwd'))) { return $app->redirect($app['url'] . '/dashboard'); } $template_data = array( 'user' => $app['sentry']->getUser(), 'email' => $req->get('email'), 'errorMessage' => $page->getAuthenticationMessage() ); } catch (Exception $e) { $template_data = array( 'user' => $app['sentry']->getUser(), 'email' => $req->get('email'), 'errorMessage' => $e->getMessage() ); } return $template->render($template_data); } public function outAction(Request $req, Application $app) { $app['sentry']->logout(); return $app->redirect($app['url'] . '/'); } } " Fix migration for new tenants,"# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2020-02-12 09:25 from __future__ import unicode_literals from django.db import migrations, connection from bluebottle.clients import properties from bluebottle.clients.models import Client from bluebottle.clients.utils import LocalTenant from django.contrib.auth.models import Permission, Group def remove_anonymous_permissions(apps, schema_editor): permissions = ( ('assignments', 'api_read_assignment'), ('events', 'api_read_event'), ('activities', 'api_read_activity'), ('funding', 'api_read_funding'), ) tenant = Client.objects.get(schema_name=connection.tenant.schema_name) with LocalTenant(tenant): if properties.CLOSED_SITE: anonymous = Group.objects.get(name='Anonymous') for (app, codename) in permissions: try: permission = Permission.objects.get( content_type__app_label=app, codename=codename ) anonymous.permissions.remove(permission) except Permission.DoesNotExist: pass anonymous.save() class Migration(migrations.Migration): dependencies = [ ('activities', '0017_auto_20200205_1054'), ] operations = [ migrations.RunPython(remove_anonymous_permissions) ] ","# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2020-02-12 09:25 from __future__ import unicode_literals from django.db import migrations, connection from bluebottle.clients import properties from bluebottle.clients.models import Client from bluebottle.clients.utils import LocalTenant from django.contrib.auth.models import Permission, Group def remove_anonymous_permissions(apps, schema_editor): permissions = ( ('assignments', 'api_read_assignment'), ('events', 'api_read_event'), ('activities', 'api_read_activity'), ('funding', 'api_read_funding'), ) tenant = Client.objects.get(schema_name=connection.tenant.schema_name) with LocalTenant(tenant): if properties.CLOSED_SITE: anonymous = Group.objects.get(name='Anonymous') for (app, codename) in permissions: permission = Permission.objects.get( content_type__app_label=app, codename=codename ) anonymous.permissions.remove(permission) anonymous.save() class Migration(migrations.Migration): dependencies = [ ('activities', '0017_auto_20200205_1054'), ] operations = [ migrations.RunPython(remove_anonymous_permissions) ] " Fix double sprintf in exception,"<?php declare(strict_types=1); namespace GrumPHP\Locator; use GrumPHP\Exception\ExecutableNotFoundException; use GrumPHP\Util\Paths; use Symfony\Component\Process\ExecutableFinder; class ExternalCommand { /** * @var list<string> */ private $suffixes = ['', '.phar']; /** * @var string */ protected $binDir; /** * @var ExecutableFinder */ protected $executableFinder; public function __construct(string $binDir, ExecutableFinder $executableFinder) { $this->binDir = rtrim($binDir, '/\\'); $this->executableFinder = $executableFinder; } public static function loadWithPaths(Paths $paths, ExecutableFinder $executableFinder): self { return new self( $paths->getBinDir(), $executableFinder ); } public function locate(string $command): string { foreach ($this->suffixes as $suffix) { $cmdName = $command . $suffix; // Search executable: $executable = $this->executableFinder->find($cmdName, null, [$this->binDir]); if ($executable) { return $executable; } } throw ExecutableNotFoundException::forCommand($command); } } ","<?php declare(strict_types=1); namespace GrumPHP\Locator; use GrumPHP\Exception\ExecutableNotFoundException; use GrumPHP\Util\Paths; use Symfony\Component\Process\ExecutableFinder; class ExternalCommand { /** * @var list<string> */ private $suffixes = ['', '.phar']; /** * @var string */ protected $binDir; /** * @var ExecutableFinder */ protected $executableFinder; public function __construct(string $binDir, ExecutableFinder $executableFinder) { $this->binDir = rtrim($binDir, '/\\'); $this->executableFinder = $executableFinder; } public static function loadWithPaths(Paths $paths, ExecutableFinder $executableFinder): self { return new self( $paths->getBinDir(), $executableFinder ); } public function locate(string $command): string { foreach ($this->suffixes as $suffix) { $cmdName = $command . $suffix; // Search executable: $executable = $this->executableFinder->find($cmdName, null, [$this->binDir]); if ($executable) { return $executable; } } throw ExecutableNotFoundException::forCommand( sprintf('The executable for ""%s"" could not be found.', $command) ); } } " Use constant in test ...,"<?php class ImageInfoTest extends TestCaseBase { const TEST_IMAGE_URL = 'http://www.mixdecultura.ro/wp-content/uploads/2013/03/galicia-locuinte-celtice.jpg'; const TEST_IMAGE_WIDTH = 600; const TEST_IMAGE_HEIGHT = 408; const TEST_IMAGE_SIZE = 244800; const TEST_IMAGE_MIME = 'image/jpeg'; public function testOne() { $info = Embed\ImageInfo\Curl::getImageInfo([ 'value' => self::TEST_IMAGE_URL, ]); $this->assertEquals($info, [ 'width' => self::TEST_IMAGE_WIDTH, 'height' => self::TEST_IMAGE_HEIGHT, 'size' => self::TEST_IMAGE_SIZE, 'mime' => self::TEST_IMAGE_MIME, ]); } public function testGuzzle() { $info = Embed\ImageInfo\Guzzle5::getImagesInfo([[ 'value' => self::TEST_IMAGE_URL, ]], [ 'client' => new \GuzzleHttp\Client(), ]); $this->assertEquals($info[0], [ 'width' => self::TEST_IMAGE_WIDTH, 'height' => self::TEST_IMAGE_HEIGHT, 'size' => self::TEST_IMAGE_SIZE, 'mime' => self::TEST_IMAGE_MIME, 'value' => self::TEST_IMAGE_URL, ]); } } ","<?php class ImageInfoTest extends TestCaseBase { const TEST_IMAGE_URL = 'http://www.mixdecultura.ro/wp-content/uploads/2013/03/galicia-locuinte-celtice.jpg'; const TEST_IMAGE_WIDTH = 600; const TEST_IMAGE_HEIGHT = 408; const TEST_IMAGE_SIZE = 244800; const TEST_IMAGE_MIME = 'image/jpeg'; public function testOne() { $info = Embed\ImageInfo\Curl::getImageInfo([ 'value' => self::TEST_IMAGE_URL, ]); $this->assertEquals($info, [ 'width' => self::TEST_IMAGE_WIDTH, 'height' => self::TEST_IMAGE_HEIGHT, 'size' => self::TEST_IMAGE_SIZE, 'mime' => self::TEST_IMAGE_MIME, ]); } public function testGuzzle() { $info = Embed\ImageInfo\Guzzle5::getImagesInfo([[ 'value' => 'http://www.mixdecultura.ro/wp-content/uploads/2013/03/galicia-locuinte-celtice.jpg', ]], [ 'client' => new \GuzzleHttp\Client(), ]); $this->assertEquals($info[0], [ 'width' => self::TEST_IMAGE_WIDTH, 'height' => self::TEST_IMAGE_HEIGHT, 'size' => self::TEST_IMAGE_SIZE, 'mime' => self::TEST_IMAGE_MIME, 'value' => self::TEST_IMAGE_URL, ]); } } " Fix release version to 0.4.2,"import setuptools with open(""README.md"", ""r"") as fh: long_description = fh.read() setuptools.setup( name='scholarly', version='0.4.2', author='Steven A. Cholewiak, Panos Ipeirotis, Victor Silva', author_email='steven@cholewiak.com, panos@stern.nyu.edu, vsilva@ualberta.ca', description='Simple access to Google Scholar authors and citations', long_description=long_description, long_description_content_type=""text/markdown"", license='Unlicense', url='https://github.com/scholarly-python-package/scholarly', packages=setuptools.find_packages(), keywords=['Google Scholar', 'academics', 'citations'], classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules'], install_requires=['arrow', 'beautifulsoup4', 'bibtexparser', 'requests[security]', 'requests[socks]', 'stem', 'fake_useragent', 'PySocks', 'selenium', 'python-dotenv', 'free-proxy', ], test_suite=""test_module.py"" ) ","import setuptools with open(""README.md"", ""r"") as fh: long_description = fh.read() setuptools.setup( name='scholarly', version='0.4.1', author='Steven A. Cholewiak, Panos Ipeirotis, Victor Silva', author_email='steven@cholewiak.com, panos@stern.nyu.edu, vsilva@ualberta.ca', description='Simple access to Google Scholar authors and citations', long_description=long_description, long_description_content_type=""text/markdown"", license='Unlicense', url='https://github.com/scholarly-python-package/scholarly', packages=setuptools.find_packages(), keywords=['Google Scholar', 'academics', 'citations'], classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules'], install_requires=['arrow', 'beautifulsoup4', 'bibtexparser', 'requests[security]', 'requests[socks]', 'stem', 'fake_useragent', 'PySocks', 'selenium', 'python-dotenv', 'free-proxy', ], test_suite=""test_module.py"" ) " Fix typo in class declaration,"import React, { PureComponent } from ""react""; import PropTypes from ""prop-types""; import styled from ""styled-components""; import { NonIdealState } from ""@blueprintjs/core""; import Entries from ""../../shared/components/Entries.js""; const BUTTERCUP_LOGO = require(""../../../resources/buttercup-standalone.png""); const Container = styled.div` flex: 1; `; const EntryShape = PropTypes.shape({ id: PropTypes.string.isRequired, title: PropTypes.string.isRequired, url: PropTypes.string }); class SearchResults extends PureComponent { static propTypes = { entries: PropTypes.arrayOf(EntryShape), sourcesUnlocked: PropTypes.number.isRequired, onSelectEntry: PropTypes.func.isRequired }; render() { return ( <Container> <Choose> <When condition={this.props.entries.length > 0}> <Entries autoLoginEnabled={false} entries={this.props.entries} onSelectEntry={this.props.onSelectEntry} sourcesUnlocked={this.props.sourcesUnlocked} /> </When> <Otherwise> <NonIdealState title=""Welcome to Buttercup"" description=""Use the search bar to find entries in your unlocked vaults."" icon={<img src={BUTTERCUP_LOGO} width=""64"" />} /> </Otherwise> </Choose> </Container> ); } } export default SearchResults; ","import React, { Pureomponent } from ""react""; import PropTypes from ""prop-types""; import styled from ""styled-components""; import { NonIdealState } from ""@blueprintjs/core""; import Entries from ""../../shared/components/Entries.js""; const BUTTERCUP_LOGO = require(""../../../resources/buttercup-standalone.png""); const Container = styled.div` flex: 1; `; const EntryShape = PropTypes.shape({ id: PropTypes.string.isRequired, title: PropTypes.string.isRequired, url: PropTypes.string }); class SearchResults extends Pureomponent { static propTypes = { entries: PropTypes.arrayOf(EntryShape), sourcesUnlocked: PropTypes.number.isRequired, onSelectEntry: PropTypes.func.isRequired }; render() { return ( <Container> <Choose> <When condition={this.props.entries.length > 0}> <Entries autoLoginEnabled={false} entries={this.props.entries} onSelectEntry={this.props.onSelectEntry} sourcesUnlocked={this.props.sourcesUnlocked} /> </When> <Otherwise> <NonIdealState title=""Welcome to Buttercup"" description=""Use the search bar to find entries in your unlocked vaults."" icon={<img src={BUTTERCUP_LOGO} width=""64"" />} /> </Otherwise> </Choose> </Container> ); } } export default SearchResults; " Add ids to the markup,"(function(global) { 'use strict'; (function(id) { var i, j; var tab = document.getElementById(id); var thead = tab.querySelector('thead'); var tbody = tab.querySelector('tbody'); var tr, th, td; // tr = document.createElement('tr'); // th = document.createElement('td'); // tr.appendChild(th); // for (i = 0; i < 30; i++) { // th = document.createElement('th'); // th.textContent = i + 1; // tr.appendChild(th); // } // thead.appendChild(tr); for (i = 0; i < 3; i++) { tr = document.createElement('tr'); tr.id = ""row-"" + i; // th = document.createElement('th'); // th.textContent = i + 1; // tr.appendChild(th); for (j = 0; j < 30; j++) { td = document.createElement('td'); td.textContent = 0; td.id = ""cell-"" + (i * 30 + j); tr.appendChild(td); } tbody.appendChild(tr); } })('rams'); })(this) ","(function(global) { 'use strict'; (function(id) { var i, j; var tab = document.getElementById(id); var thead = tab.querySelector('thead'); var tbody = tab.querySelector('tbody'); var tr, th, td; // tr = document.createElement('tr'); // th = document.createElement('td'); // tr.appendChild(th); // for (i = 0; i < 30; i++) { // th = document.createElement('th'); // th.textContent = i + 1; // tr.appendChild(th); // } // thead.appendChild(tr); for (i = 0; i < 3; i++) { tr = document.createElement('tr'); // th = document.createElement('th'); // th.textContent = i + 1; // tr.appendChild(th); for (j = 0; j < 30; j++) { td = document.createElement('td'); td.textContent = 0; tr.appendChild(td); } tbody.appendChild(tr); } })('rams'); })(this) " Add one more case for testing mockMethod on object/class,"<?php namespace MockaTests\Mocka; use \Mocka\Mocka; class ClassTraitTest extends \PHPUnit_Framework_TestCase { public function testMockClass() { $mocka = new Mocka(); $mockClass = $mocka->mockClass('\MockaMocks\AbstractClass'); $this->assertInstanceOf('\\Mocka\\ClassMock', $mockClass); } public function testMockInterface() { $mocka = new Mocka(); $mockClass = $mocka->mockInterface('\MockaMocks\InterfaceMock'); $this->assertInstanceOf('\\Mocka\\ClassMock', $mockClass); } public function testCallMockedMethod() { $mocka = new Mocka(); $mockClass = $mocka->mockClass('\MockaMocks\AbstractClass'); /** @var \MockaMocks\AbstractClass|\Mocka\ClassTrait $object */ $object = $mockClass->newInstance(); $this->assertNull($object->foo()); $this->assertSame('bar', $object->bar()); $mockClass->mockMethod('foo')->set(function () { return 'foo'; }); $this->assertSame('foo', $object->foo()); $object->mockMethod('foo')->set(function () { return 'bar'; }); $this->assertSame('bar', $object->foo()); $objectAnother = $mockClass->newInstance(); $this->assertSame('foo', $objectAnother->foo()); $mockClass->mockMethod('foo')->set(function () { return 'zoo'; }); $this->assertSame('bar', $object->foo()); } } ","<?php namespace MockaTests\Mocka; use \Mocka\Mocka; class ClassTraitTest extends \PHPUnit_Framework_TestCase { public function testMockClass() { $mocka = new Mocka(); $mockClass = $mocka->mockClass('\MockaMocks\AbstractClass'); $this->assertInstanceOf('\\Mocka\\ClassMock', $mockClass); } public function testMockInterface() { $mocka = new Mocka(); $mockClass = $mocka->mockInterface('\MockaMocks\InterfaceMock'); $this->assertInstanceOf('\\Mocka\\ClassMock', $mockClass); } public function testCallMockedMethod() { $mocka = new Mocka(); $mockClass = $mocka->mockClass('\MockaMocks\AbstractClass'); /** @var \MockaMocks\AbstractClass|\Mocka\ClassTrait $object */ $object = $mockClass->newInstance(); $this->assertNull($object->foo()); $this->assertSame('bar', $object->bar()); $mockClass->mockMethod('foo')->set(function () { return 'foo'; }); $this->assertSame('foo', $object->foo()); $object->mockMethod('foo')->set(function () { return 'bar'; }); $this->assertSame('bar', $object->foo()); $objectAnother = $mockClass->newInstance(); $this->assertSame('foo', $objectAnother->foo()); } } " Update to new stats format,"'use strict' var influx = require('influx') var _ = require('lodash') var defaults = { plugin: 'influx-stats-store', enabled: true, log_input: false, log_output: false, influx: { host:'localhost', port:'8086', username:'stats', password:'stats', database:'seneca_stats' } } module.exports = function (opts) { var seneca = this var extend = seneca.util.deepextend opts = extend(defaults, opts) seneca.add({role: 'stats', cmd: 'store'}, handle_storage) function handle_storage (msg, done) { this.prior(msg, function (err, data) { if (!opts.enabled) { return done(null, data) } if (opts.log_input) { console.log(JSON.stringify(data, null, 2)) } var client = influx(opts.influx) var series = {} _.each(data.stats, (stat) => { var id = stat.stat series[id] = series[id] || [] series[id].push([stat.values, stat.tags]) }) if (opts.log_output) { console.log(JSON.stringify(series, null, 2)) } client.writeSeries(series, (err) => { if (err) { seneca.log.error(err) opts.enabled = false } done(null, data) }) }) } return opts.plugin } ","'use strict' var influx = require('influx') var _ = require('lodash') var defaults = { plugin: 'influx-stats-store', enabled: true, log_input: false, log_output: false, influx: { host:'localhost', port:'8086', username:'stats', password:'stats', database:'seneca_stats' } } module.exports = function (opts) { var seneca = this var extend = seneca.util.deepextend opts = extend(defaults, opts) seneca.add({role: 'stats', cmd: 'store'}, handleStorage) function handleStorage (msg, done) { this.prior(msg, function (err, data) { if (!opts.enabled) { return done(null, data) } if (opts.log_input) { console.log(JSON.stringify(data, null, 2)) } var client = influx(opts.influx) var series = {} _.each(data.metrics, (stat) => { var id = stat.metric series[id] = series[id] || [] series[id].push([stat.values, stat.tags]) }) if (opts.log_output) { console.log(JSON.stringify(series, null, 2)) } client.writeSeries(series, (err) => { if (err) { seneca.log.error(err) opts.enabled = false } done(null, data) }) }) } return opts.plugin } " "Fix dataProvider - it was never called It's a bit hacky, I will try to think about a better solution. Until than it's better to have the bug fixed...","<?php namespace PhpRQ; use Nette\Utils\Finder; /** * @author Jakub Chábek <jakub.chabek@heureka.cz> */ class TestRunner { /** * @var ClientProvider */ private $provider; public function __construct(ClientProvider $provider) { $this->provider = $provider; } public function run() { foreach (Finder::findFiles('*Test.php')->from(__DIR__) as $fileInfo) { /** @var \SplFileInfo $fileInfo*/ $baseName = $fileInfo->getBasename('.php'); if ($baseName === 'PhpRQTest') { continue; } $className = 'PhpRQ\\' . $baseName; $reflection = new \ReflectionClass($className); if (!$reflection->isInstantiable()) { continue; } foreach ($reflection->getMethods() as $method) { if (!$method->isPublic() || strpos($methodName = $method->getName(), 'test') === false) { continue; } $phpdoc = $method->getDocComment(); if ($phpdoc !== false && ($providerPos = strpos($phpdoc, '@dataProvider')) !== false) { $providerMethodPos = $providerPos + 14; $providerMethodLen = strpos($phpdoc, ""\n"", $providerMethodPos) - $providerMethodPos; $providerMethod = substr($phpdoc, $providerMethodPos, $providerMethodLen); $testCase = new $className($this->provider->getRedisClient()); foreach ($testCase->$providerMethod() as $args) { $testCase = new $className($this->provider->getRedisClient()); call_user_func_array([$testCase, $methodName], (array)$args); } } else { $testCase = new $className($this->provider->getRedisClient()); $testCase->$methodName(); } } } } } ","<?php namespace PhpRQ; use Nette\Utils\Finder; /** * @author Jakub Chábek <jakub.chabek@heureka.cz> */ class TestRunner { /** * @var ClientProvider */ private $provider; public function __construct(ClientProvider $provider) { $this->provider = $provider; } public function run() { foreach (Finder::findFiles('*Test.php')->from(__DIR__) as $fileInfo) { /** @var \SplFileInfo $fileInfo*/ $baseName = $fileInfo->getBasename('.php'); if ($baseName === 'PhpRQTest') { continue; } $className = 'PhpRQ\\' . $baseName; $reflection = new \ReflectionClass($className); if (!$reflection->isInstantiable()) { continue; } foreach ($reflection->getMethods() as $method) { if (!$method->isPublic() || strpos($methodName = $method->getName(), 'test') === false) { continue; } $testCase = new $className($this->provider->getRedisClient()); $testCase->$methodName(); } } } } " Add plenty of link usability to motion card.,"import React from 'react'; import { Link } from 'react-router-dom'; function voteValueDescription(value) { switch (value) { case 1: return 'kyllä'; case 0: return 'tyhjä'; case -1: return 'ei'; } return 'whatever'; } export default function MotionCard({_case, totalCount, userVote}) { const userVoteSummary = (userVote !== undefined ? 'Äänestit ' + voteValueDescription(userVote).toUpperCase() : 'Äänestä'); return (<article className=""ba mb3 b--black-10 bg-white shadow-4""> <Link to={`/motion/${_case.issue_id}`} className=""db pv3 ph3 no-underline black dim"" href=""#0""> <div className=""flex flex-column flex-row-ns""> <div className=""pr3 w-40""> <img src=""http://lorempixel.com/800/600/city"" className=""db"" alt=""Motion image thumbnail."" /> </div> <div className=""w-60 pl3""> <h3 className=""f5 gray mv0"">{_case.number}/{totalCount}</h3> <h1 className=""f4 dark-gray mv2 ttu"">{_case.title}</h1> <div className=""f6 link dim br1 ph3 pt2 pb1 mb2 dib white bg-red"" href=""#0"">{userVoteSummary}</div> </div> </div> </Link> </article>); } ","import React from 'react'; import { Link } from 'react-router-dom'; function voteValueDescription(value) { switch (value) { case 1: return 'kyllä'; case 0: return 'tyhjä'; case -1: return 'ei'; } return 'whatever'; } export default function MotionCard({_case, totalCount, userVote}) { const userVoteSummary = (userVote !== undefined ? 'Äänestit ' + voteValueDescription(userVote).toUpperCase() : 'Äänestä'); return (<article className=""ba mb3 b--black-10 bg-white shadow-4""> <a className=""db pv3 ph3 no-underline black dim"" href=""#0""> <div className=""flex flex-column flex-row-ns""> <div className=""pr3 w-40""> <img src=""http://lorempixel.com/800/600/city"" className=""db"" alt=""Motion image thumbnail."" /> </div> <div className=""w-60 pl3""> <h3 className=""f5 gray mv0"">{_case.number}/{totalCount}</h3> <h1 className=""f4 dark-gray mv2 ttu"">{_case.title}</h1> <Link to={`/motion/${_case.issue_id}`} className=""f6 link dim br1 ph3 pt2 pb1 mb2 dib white bg-red"" href=""#0"">{userVoteSummary}</Link> </div> </div> </a> </article>); } " Change status method to pass object instead of nesting it,"'use strict'; // Create, restore, list, and get status of koast DB backups // /** * @module koastAdminApp.service/koastBackup */ angular.module('koastAdminApp.sections.backup.backup-service', []) .service('backup', function (api, constants) { var service = { //make create backup request //where name is the name of the backup and type is what kind of backup it will be createBackup: function (name, collections, type) { return api.callMethod('backup', 'start', { collections: collections, type: type, name: name, opts: { name: name, bucket: constants.awsBucket } }); }, //ask for the status of a particular inprogress backup //where id is the id from the backup receipt status: function (id) { return api.callMethod('backup', 'stat', id); }, //get a list of backups list: function () { return api.callMethod('backup', 'list'); }, //restore the db using the selected backup //where id is the id of the backup restoreBackup: function (id) { return api.callMethod('backup', 'restore', { id: id }); } }; return service; });","'use strict'; // Create, restore, list, and get status of koast DB backups // /** * @module koastAdminApp.service/koastBackup */ angular.module('koastAdminApp.sections.backup.backup-service', []) .service('backup', function (api, constants) { var service = { //make create backup request //where name is the name of the backup and type is what kind of backup it will be createBackup: function (name, collections, type) { return api.callMethod('backup', 'create', { collections: collections, type: type, name: name, opts: { bucket: constants.awsBucket } }); }, //ask for the status of a particular inprogress backup //where id is the id from the backup receipt status: function (id) { return api.callMethod('backup', 'stat', { id: id }); }, //get a list of backups list: function () { return api.callMethod('backup', 'list'); }, //restore the db using the selected backup //where id is the id of the backup restoreBackup: function (id) { return api.callMethod('backup', 'restore', { id: id }); } }; return service; }); " Test change to see if BOM task is really necessary,"// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. module.exports = function (grunt) { var config = require(""./config.js""); grunt.file.preserveBOM = true; // Helper function to load the config file function loadConfig(path) { var glob = require('glob'); var object = {}; var key; glob.sync('*', {cwd: path}).forEach(function(option) { key = option.replace(/\.js$/,''); object[key] = require(path + option); }); return object; } // Load task options var gruntConfig = loadConfig('./tasks/options/'); // Package data gruntConfig.pkg = grunt.file.readJSON(""package.json""); // Project config grunt.initConfig(gruntConfig); // Load all grunt-tasks in package.json require(""load-grunt-tasks"")(grunt); // Register external tasks grunt.loadTasks(""tasks/""); // Task alias's grunt.registerTask(""default"", [""clean"", ""less"", ""concat"", ""copy"", ""replace""]); grunt.registerTask(""css"", [""less""]); grunt.registerTask(""base"", [""clean:base"", ""concat:baseDesktop"", ""concat:basePhone"", ""concat:baseStringsDesktop"", ""concat:baseStringsPhone"", ""replace""]); grunt.registerTask(""ui"", [""clean:ui"", ""concat:uiDesktop"", ""concat:uiPhone"", ""concat:uiStringsDesktop"", ""concat:uiStringsPhone"", ""replace"", ""less""]); }","// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. module.exports = function (grunt) { var config = require(""./config.js""); // Helper function to load the config file function loadConfig(path) { var glob = require('glob'); var object = {}; var key; glob.sync('*', {cwd: path}).forEach(function(option) { key = option.replace(/\.js$/,''); object[key] = require(path + option); }); return object; } // Load task options var gruntConfig = loadConfig('./tasks/options/'); // Package data gruntConfig.pkg = grunt.file.readJSON(""package.json""); // Project config grunt.initConfig(gruntConfig); // Load all grunt-tasks in package.json require(""load-grunt-tasks"")(grunt); // Register external tasks grunt.loadTasks(""tasks/""); // Task alias's grunt.registerTask(""default"", [""clean"", ""less"", ""concat"", ""copy"", ""replace"", ""bom""]); grunt.registerTask(""css"", [""less"", ""bom""]); grunt.registerTask(""base"", [""clean:base"", ""concat:baseDesktop"", ""concat:basePhone"", ""concat:baseStringsDesktop"", ""concat:baseStringsPhone"", ""replace"", ""bom""]); grunt.registerTask(""ui"", [""clean:ui"", ""concat:uiDesktop"", ""concat:uiPhone"", ""concat:uiStringsDesktop"", ""concat:uiStringsPhone"", ""replace"", ""less"", ""bom""]); }" Add last exception message to Interrupted message,"<?php declare(strict_types=1); namespace Asynchronicity\Polling; use Exception; final class Poller { /** * Invoke the provided callable until it doesn't throw an exception anymore, or a timeout occurs. The poller will wait before invoking the * callable again. * * @param callable $probe * @param Timeout $timeout */ public function poll(callable $probe, Timeout $timeout): void { $timeout->start(); $lastException = null; while (true) { try { $returnValue = $probe(); if ($returnValue !== null) { throw IncorrectUsage::theProbeShouldNotReturnAnything(); } // the probe was successful, so we can return now return; } catch (IncorrectUsage $exception) { throw $exception; } catch (Exception $exception) { // the probe was unsuccessful, we remember the last exception $lastException = $exception; } if ($timeout->hasTimedOut()) { throw new Interrupted( 'A timeout has occurred. Last exception: ' . $lastException->getMessage(), 0, $lastException ); } // we wait before trying again $timeout->wait(); } } } ","<?php declare(strict_types=1); namespace Asynchronicity\Polling; use Exception; final class Poller { /** * Invoke the provided callable until it doesn't throw an exception anymore, or a timeout occurs. The poller will wait before invoking the * callable again. * * @param callable $probe * @param Timeout $timeout */ public function poll(callable $probe, Timeout $timeout): void { $timeout->start(); $lastException = null; while (true) { try { $returnValue = $probe(); if ($returnValue !== null) { throw IncorrectUsage::theProbeShouldNotReturnAnything(); } // the probe was successful, so we can return now return; } catch (IncorrectUsage $exception) { throw $exception; } catch (Exception $exception) { // the probe was unsuccessful, we remember the last exception $lastException = $exception; } if ($timeout->hasTimedOut()) { throw new Interrupted('A timeout has occurred', 0, $lastException); } // we wait before trying again $timeout->wait(); } } } " Use KDatabaseBehavior::factory() to create the sluggable behavior.,"<?php /** * @version $Id$ * @category Nooku * @package Nooku_Server * @subpackage Newsfeeds * @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net). * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Newsfeeds Database Table Class * * @author Babs Gsgens <http://nooku.assembla.com/profile/babsgosgens> * @category Nooku * @package Nooku_Server * @subpackage Newsfeeds */ class ComNewsfeedsDatabaseTableNewsfeeds extends KDatabaseTableDefault { public function _initialize(KConfig $config) { $sluggable = KDatabaseBehavior::factory('sluggable', array('columns' => array('name'))); $config->append(array( 'identity_column' => 'id', 'base' => 'newsfeeds', 'name' => 'newsfeeds', 'behaviors' => array('lockable', 'orderable', $sluggable), 'column_map' => array( 'enabled' => 'published', 'locked_on' => 'checked_out_time', 'locked_by' => 'checked_out', 'slug' => 'alias' ) )); parent::_initialize($config); } } ","<?php /** * @version $Id$ * @category Nooku * @package Nooku_Server * @subpackage Newsfeeds * @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net). * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Newsfeeds Database Table Class * * @author Babs Gsgens <http://nooku.assembla.com/profile/babsgosgens> * @category Nooku * @package Nooku_Server * @subpackage Newsfeeds */ class ComNewsfeedsDatabaseTableNewsfeeds extends KDatabaseTableDefault { public function _initialize(KConfig $config) { $sluggable = KFactory::get('lib.koowa.database.behavior.sluggable', array('columns' => array('name')) ); $config->append(array( 'identity_column' => 'id', 'base' => 'newsfeeds', 'name' => 'newsfeeds', 'behaviors' => array('lockable', 'orderable', $sluggable), 'column_map' => array( 'enabled' => 'published', 'locked_on' => 'checked_out_time', 'locked_by' => 'checked_out', 'slug' => 'alias' ) )); parent::_initialize($config); } } " Add classifier for Python 3.6,"import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-pgallery', version=__import__('pgallery').__version__, description='Photo gallery app for PostgreSQL and Django.', long_description=read('README.rst'), author='Zbigniew Siciarz', author_email='zbigniew@siciarz.net', url='https://github.com/zsiciarz/django-pgallery', download_url='https://pypi.python.org/pypi/django-pgallery', license='MIT', install_requires=[ 'Django>=1.9', 'Pillow', 'psycopg2>=2.5', 'django-markitup>=2.0', 'django-model-utils>=2.0', ], packages=find_packages(exclude=['tests']), include_package_data=True, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Utilities', ], ) ","import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-pgallery', version=__import__('pgallery').__version__, description='Photo gallery app for PostgreSQL and Django.', long_description=read('README.rst'), author='Zbigniew Siciarz', author_email='zbigniew@siciarz.net', url='https://github.com/zsiciarz/django-pgallery', download_url='https://pypi.python.org/pypi/django-pgallery', license='MIT', install_requires=[ 'Django>=1.9', 'Pillow', 'psycopg2>=2.5', 'django-markitup>=2.0', 'django-model-utils>=2.0', ], packages=find_packages(exclude=['tests']), include_package_data=True, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Utilities', ], ) " Fix user satisfaction bar charts tests following removal of the matrix,"define([ 'common/views/visualisations/bar-chart/user-satisfaction', 'common/views/visualisations/bar-chart/bar-chart', 'extensions/collections/collection', 'backbone' ], function (UserSatisfaction, BarChart, Collection, Backbone) { describe('UserSatisfaction Bar Chart', function () { var graph; beforeEach(function () { spyOn(UserSatisfaction.prototype, 'render'); graph = new UserSatisfaction({ collection: new Collection([], { format: 'integer' }) }); }); describe('initialize()', function () { it('calls render() on a reset of the collection data', function () { expect(UserSatisfaction.prototype.render).not.toHaveBeenCalled(); graph.collection.reset(); expect(UserSatisfaction.prototype.render).toHaveBeenCalled(); }); }); describe('components()', function () { beforeEach(function () { spyOn(BarChart.prototype, 'components').andReturn({ hover: { view: {} }, xaxis: { view: Backbone.View } }); }); it('removes the hover component from the BarChart', function () { expect(graph.components().hover).toBeUndefined(); }); it('removes the yaxis component from the BarChart', function () { expect(graph.components().yaxis).toBeUndefined(); }); it('sets the xasis to not useEllipses', function () { expect(graph.components().xaxis.view.prototype.useEllipses).toEqual(false); }); }); }); }); ","define([ 'common/views/visualisations/bar-chart/user-satisfaction', 'common/views/visualisations/bar-chart/bar-chart', 'common/collections/journey', 'extensions/collections/collection', 'backbone' ], function (UserSatisfaction, BarChart, JourneyCollection, Collection, Backbone) { describe('UserSatisfaction Bar Chart', function () { var graph; beforeEach(function () { spyOn(UserSatisfaction.prototype, 'render'); graph = new UserSatisfaction({ collection: new Collection([ { values: new Collection([]) } ], { format: 'integer' }) }); }); describe('initialize()', function () { it('calls render() on a reset of the collection data', function () { expect(UserSatisfaction.prototype.render).not.toHaveBeenCalled(); graph.collection.at(0).get('values').reset(); expect(UserSatisfaction.prototype.render).toHaveBeenCalled(); }); }); describe('components()', function () { beforeEach(function () { spyOn(BarChart.prototype, 'components').andReturn({ hover: { view: {} }, xaxis: { view: Backbone.View } }); }); it('removes the hover component from the BarChart', function () { expect(graph.components().hover).toBeUndefined(); }); it('removes the yaxis component from the BarChart', function () { expect(graph.components().yaxis).toBeUndefined(); }); it('sets the xasis to not useEllipses', function () { expect(graph.components().xaxis.view.prototype.useEllipses).toEqual(false); }); }); }); }); " Adjust order of dependency set in DEVELOP mode,"package com.github.blindpirate.gogradle.core.mode; import com.github.blindpirate.gogradle.core.dependency.GolangDependencySet; import static com.github.blindpirate.gogradle.core.dependency.GolangDependencySet.merge; public enum BuildMode { DEVELOP { @Override public GolangDependencySet determine(GolangDependencySet declaredDependencies, GolangDependencySet vendorDependencies, GolangDependencySet lockedDependencies) { return merge(declaredDependencies, lockedDependencies, vendorDependencies); } }, REPRODUCIBLE { @Override public GolangDependencySet determine(GolangDependencySet declaredDependencies, GolangDependencySet vendorDependencies, GolangDependencySet lockedDependencies) { return merge(vendorDependencies, lockedDependencies, declaredDependencies); } }; public abstract GolangDependencySet determine( GolangDependencySet declaredDependencies, GolangDependencySet vendorDependencies, GolangDependencySet lockedDependencies); } ","package com.github.blindpirate.gogradle.core.mode; import com.github.blindpirate.gogradle.core.dependency.GolangDependencySet; import static com.github.blindpirate.gogradle.core.dependency.GolangDependencySet.merge; public enum BuildMode { DEVELOP { @Override public GolangDependencySet determine(GolangDependencySet declaredDependencies, GolangDependencySet vendorDependencies, GolangDependencySet lockedDependencies) { return merge(declaredDependencies, vendorDependencies, lockedDependencies); } }, REPRODUCIBLE { @Override public GolangDependencySet determine(GolangDependencySet declaredDependencies, GolangDependencySet vendorDependencies, GolangDependencySet lockedDependencies) { return merge(vendorDependencies, lockedDependencies, declaredDependencies); } }; public abstract GolangDependencySet determine( GolangDependencySet declaredDependencies, GolangDependencySet vendorDependencies, GolangDependencySet lockedDependencies); } " Adjust get one user api," import * as types from '../constants/ActionTypes'; import fetch from 'isomorphic-fetch'; import Config from '../config'; export function receiveAccountSuccess(data) { return { type: types.RECIEVE_ACCOUNT_SUCCESS, account: data }; } function receiveAccountFailure(err) { console.log(err); } function setToken(token) { window.localStorage.QustomPortalTK = token; return { type: types.SET_TOKEN, token }; } export function verifyToken(token) { return (dispatch) => fetch(`${Config.baseURL}/api/v1/mgnt/users/me`, { method: 'GET', credentials: 'same-origin', headers: { Accept: 'application/json', 'Content-Type': 'application/json', authorization: token } }) .then(response => response.json()) .then(data => { if (data.hasOwnProperty('accountid') && data.accountid) { dispatch(setToken(token)); dispatch(receiveAccountSuccess(data)); } else { // token no used: token expired / user doesn't have a account dispatch(receiveAccountFailure(data)); } }) .catch(err => receiveAccountFailure(err.responseJSON)); } "," import * as types from '../constants/ActionTypes'; import fetch from 'isomorphic-fetch'; import Config from '../config'; export function receiveAccountSuccess(data) { return { type: types.RECIEVE_ACCOUNT_SUCCESS, account: data }; } function receiveAccountFailure(err) { console.log(err); } function setToken(token) { window.localStorage.QustomPortalTK = token; return { type: types.SET_TOKEN, token }; } export function verifyToken(token) { return (dispatch) => fetch(`${Config.baseURL}/api/v1/mgnt/users/`, { method: 'GET', credentials: 'same-origin', headers: { Accept: 'application/json', 'Content-Type': 'application/json', authorization: token } }) .then(response => response.json()) .then(data => { if (data.hasOwnProperty('accountid') && data.accountid) { dispatch(setToken(token)); dispatch(receiveAccountSuccess(data)); } else { // token no used: token expired / user doesn't have a account dispatch(receiveAccountFailure(data)); } }) .catch(err => receiveAccountFailure(err.responseJSON)); } " "Change text on leave modal cancel button issue #3106","var LeaveEditorController = Ember.Controller.extend({ args: Ember.computed.alias('model'), actions: { confirmAccept: function () { var args = this.get('args'), editorController, model, transition; if (Ember.isArray(args)) { editorController = args[0]; transition = args[1]; model = editorController.get('model'); } if (!transition || !editorController) { this.notifications.showError('Sorry, there was an error in the application. Please let the Ghost team know what happened.'); return true; } // definitely want to clear the data store and post of any unsaved, client-generated tags model.updateTags(); if (model.get('isNew')) { // the user doesn't want to save the new, unsaved post, so delete it. model.deleteRecord(); } else { // roll back changes on model props model.rollback(); } // setting isDirty to false here allows willTransition on the editor route to succeed editorController.set('isDirty', false); // since the transition is now certain to complete, we can unset window.onbeforeunload here window.onbeforeunload = null; transition.retry(); }, confirmReject: function () { } }, confirm: { accept: { text: 'Leave', buttonClass: 'button-delete' }, reject: { text: 'Stay', buttonClass: 'button' } } }); export default LeaveEditorController; ","var LeaveEditorController = Ember.Controller.extend({ args: Ember.computed.alias('model'), actions: { confirmAccept: function () { var args = this.get('args'), editorController, model, transition; if (Ember.isArray(args)) { editorController = args[0]; transition = args[1]; model = editorController.get('model'); } if (!transition || !editorController) { this.notifications.showError('Sorry, there was an error in the application. Please let the Ghost team know what happened.'); return true; } // definitely want to clear the data store and post of any unsaved, client-generated tags model.updateTags(); if (model.get('isNew')) { // the user doesn't want to save the new, unsaved post, so delete it. model.deleteRecord(); } else { // roll back changes on model props model.rollback(); } // setting isDirty to false here allows willTransition on the editor route to succeed editorController.set('isDirty', false); // since the transition is now certain to complete, we can unset window.onbeforeunload here window.onbeforeunload = null; transition.retry(); }, confirmReject: function () { } }, confirm: { accept: { text: 'Leave', buttonClass: 'button-delete' }, reject: { text: 'Cancel', buttonClass: 'button' } } }); export default LeaveEditorController; " Change TextArea overwrite props order,"import React, { Component } from 'react'; import PropTypes from 'prop-types'; import idgen from './idgen'; import Icon from './Icon'; import cx from 'classnames'; class Textarea extends Component { componentDidUpdate() { M.textareaAutoResize(this._textarea); } renderIcon(icon) { return <Icon className=""material-icons prefix"">{icon}</Icon>; } render() { const { className, iconClassName, icon, label, id, onChange, ...other } = this.props; const computedId = id || idgen(); return ( <div className=""input-field""> {icon && this.renderIcon(icon, iconClassName)} <textarea {...other} ref={input => { this._textarea = input; }} onChange={onChange} id={computedId} className={cx('materialize-textarea', className)} /> <label htmlFor={computedId}>{label}</label> </div> ); } } Textarea.propTypes = { /* * render icon next to input */ icon: PropTypes.string, /* * icon classname */ iconClassName: PropTypes.string, /* * textarea label */ label: PropTypes.string, /* * onChange callback */ onChange: PropTypes.func, /* * override id * @default idgen() */ id: PropTypes.string, /* * disabled input */ disabled: PropTypes.bool, /* * predefined value */ value: PropTypes.string, className: PropTypes.string }; export default Textarea; ","import React, { Component } from 'react'; import PropTypes from 'prop-types'; import idgen from './idgen'; import Icon from './Icon'; import cx from 'classnames'; class Textarea extends Component { componentDidUpdate() { M.textareaAutoResize(this._textarea); } renderIcon(icon) { return <Icon className=""material-icons prefix"">{icon}</Icon>; } render() { const { className, iconClassName, icon, label, id, onChange, ...other } = this.props; const computedId = id || idgen(); return ( <div className=""input-field""> {icon && this.renderIcon(icon, iconClassName)} <textarea ref={input => { this._textarea = input; }} onChange={onChange} id={computedId} className={cx('materialize-textarea', className)} {...other} /> <label htmlFor={computedId}>{label}</label> </div> ); } } Textarea.propTypes = { /* * render icon next to input */ icon: PropTypes.string, /* * icon classname */ iconClassName: PropTypes.string, /* * textarea label */ label: PropTypes.string, /* * onChange callback */ onChange: PropTypes.func, /* * override id * @default idgen() */ id: PropTypes.string, /* * disabled input */ disabled: PropTypes.bool, /* * predefined value */ value: PropTypes.string, className: PropTypes.string }; export default Textarea; " Implement with trait in controller,"<?php /** * @author kylekatarnls */ trait Jade { protected $jade; protected $jade_view_path; public function settings(array $options = array()) { if(isset($options['view_path'])) { $this->jade_view_path = $options['view_path']; unset($options['view_path']); } else { $this->jade_view_path = APPPATH . 'views'; } if(isset($options['cache'])) { if($options['cache'] === TRUE) { $options['cache'] = APPPATH . 'cache/jade'; } if(! file_exists($options['cache']) && ! mkdir($options['cache'], 0777, TRUE)) { throw new Exception(""Cache folder does not exists and cannot be created."", 1); } } $this->jade = new Jade\Jade($options); return $this; } public function view($view, array $data = array(), $return = false) { if(! $this->jade) { $this->settings(); } $view = $this->jade_view_path . DIRECTORY_SEPARATOR . $view . '.jade'; $data = array_merge($this->load->get_vars(), $data); if($return) { return $this->jade->render($view, $data); } else { echo $this->jade->render($view, $data); return $this; } } } ","<?php /** * @author kylekatarnls */ class Jade { protected $CI; protected $jade; protected $view_path; public function __construct(array $options = array()) { if(isset($options['view_path'])) { $this->view_path = $options['view_path']; unset($options['view_path']); } else { $this->view_path = APPPATH . 'views'; } if(isset($options['cache'])) { if($options['cache'] === TRUE) { $options['cache'] = __DIR__ . '/../cache/jade'; } if(! file_exists($options['cache']) && ! mkdir($options['cache'], 0777, TRUE)) { throw new Exception(""Cache folder does not exists and cannot be created."", 1); } } $this->CI =& get_instance(); $this->jade = new Jade\Jade($options); } public function view($view, array $data = array(), $return = false) { $view = $this->view_path . DIRECTORY_SEPARATOR . $view . '.jade'; $data = array_merge($this->CI->load->get_vars(), $data); if($return) { return $this->jade->render($view, $data); } else { echo $this->jade->render($view, $data); } } } " Delete docs on task completion,"from custom.uth.utils import create_case, match_case, attach_images_to_case, submit_error_case from custom.uth.models import SonositeUpload, VscanUpload from celery.task import task import io def get_files_from_doc(doc): files = {} for f in doc._attachments.keys(): files[f] = io.BytesIO(doc.fetch_attachment(f)) return files @task def async_create_case(upload_id): upload_doc = SonositeUpload.get(upload_id) files = get_files_from_doc(upload_doc) create_case(upload_doc.related_case_id, files) upload_doc.delete() @task def async_find_and_attach(upload_id): case = None try: upload_doc = VscanUpload.get(upload_id) files = get_files_from_doc(upload_doc) case = match_case( upload_doc.scanner_serial, upload_doc.scan_id, ) if case: files = {} for f in upload_doc._attachments.keys(): files[f] = io.BytesIO(upload_doc.fetch_attachment(f)) attach_images_to_case(case._id, files) else: return -1 upload_doc.delete() except: # mark the case as having errored (if we know what it is) # but reraise the error since we don't want to hide it if case: submit_error_case(case._id) raise ","from custom.uth.utils import create_case, match_case, attach_images_to_case, submit_error_case from custom.uth.models import SonositeUpload, VscanUpload from celery.task import task import io def get_files_from_doc(doc): files = {} for f in doc._attachments.keys(): files[f] = io.BytesIO(doc.fetch_attachment(f)) return files @task def async_create_case(upload_id): upload_doc = SonositeUpload.get(upload_id) files = get_files_from_doc(upload_doc) create_case(upload_doc.related_case_id, files) # TODO delete doc if processing is successful @task def async_find_and_attach(upload_id): try: upload_doc = VscanUpload.get(upload_id) files = get_files_from_doc(upload_doc) case = match_case( upload_doc.scanner_serial, upload_doc.scan_id, # upload_doc.date ) if case: files = {} for f in upload_doc._attachments.keys(): files[f] = io.BytesIO(upload_doc.fetch_attachment(f)) attach_images_to_case(case._id, files) else: return -1 # TODO delete doc if successful except: # mark the case as having errored (if we know what it is) # but reraise the error since we don't want to hide it if case: submit_error_case(case._id) raise " BiGCZ: Clear results from map on datacatalog cleanup,"""use strict""; var App = require('../app'), router = require('../router').router, coreUtils = require('../core/utils'), models = require('./models'), views = require('./views'); var DataCatalogController = { dataCatalogPrepare: function() { if (!App.map.get('areaOfInterest')) { router.navigate('', { trigger: true }); return false; } }, dataCatalog: function() { App.map.setDataCatalogSize(); App.state.set({ 'active_page': coreUtils.dataCatalogPageTitle, }); var form = new models.SearchForm(); var catalogs = new models.Catalogs([ new models.Catalog({ id: 'cinergi', name: 'CINERGI', active: true, results: new models.Results(null, { catalog: 'cinergi' }), }), new models.Catalog({ id: 'hydroshare', name: 'HydroShare', results: new models.Results(null, { catalog: 'hydroshare' }), }), new models.Catalog({ id: 'cuahsi', name: 'WDC', description: 'Optional catalog description here...', results: new models.Results(null, { catalog: 'cuahsi' }), }) ]); var view = new views.DataCatalogWindow({ model: form, collection: catalogs }); App.rootView.sidebarRegion.show(view); }, dataCatalogCleanUp: function() { App.map.set({ dataCatalogResults: null, dataCatalogActiveResult: null, }); } }; module.exports = { DataCatalogController: DataCatalogController, }; ","""use strict""; var App = require('../app'), router = require('../router').router, coreUtils = require('../core/utils'), models = require('./models'), views = require('./views'); var DataCatalogController = { dataCatalogPrepare: function() { if (!App.map.get('areaOfInterest')) { router.navigate('', { trigger: true }); return false; } }, dataCatalog: function() { App.map.setDataCatalogSize(); App.state.set({ 'active_page': coreUtils.dataCatalogPageTitle, }); var form = new models.SearchForm(); var catalogs = new models.Catalogs([ new models.Catalog({ id: 'cinergi', name: 'CINERGI', active: true, results: new models.Results(null, { catalog: 'cinergi' }), }), new models.Catalog({ id: 'hydroshare', name: 'HydroShare', results: new models.Results(null, { catalog: 'hydroshare' }), }), new models.Catalog({ id: 'cuahsi', name: 'WDC', description: 'Optional catalog description here...', results: new models.Results(null, { catalog: 'cuahsi' }), }) ]); var view = new views.DataCatalogWindow({ model: form, collection: catalogs }); App.rootView.sidebarRegion.show(view); } }; module.exports = { DataCatalogController: DataCatalogController, }; " "[Menu] Fix nested menus that can't be clicked issue This fixes a regression that was introduced in https://github.com/callemall/material-ui/pull/3360. The previous `click-awayable` mixin listened on `mouseup` and `touchend` events and the new `ClickAwayListener` was implemented to use `mousedown` and `touchstart` events. This commit changes the events to mimick the behavior from the original mixin. Resolves #3818","import React from 'react'; import ReactDOM from 'react-dom'; import events from '../utils/events'; const isDescendant = (el, target) => { if (target !== null) { return el === target || isDescendant(el, target.parentNode); } return false; }; const clickAwayEvents = ['mouseup', 'touchend']; const bind = (callback) => clickAwayEvents.forEach((event) => events.on(document, event, callback)); const unbind = (callback) => clickAwayEvents.forEach((event) => events.off(document, event, callback)); export default class ClickAwayListener extends React.Component { static propTypes = { children: React.PropTypes.node, onClickAway: React.PropTypes.any, }; componentDidMount() { if (this.props.onClickAway) { bind(this.handleClickAway); } } componentDidUpdate(prevProps) { if (prevProps.onClickAway !== this.props.onClickAway) { unbind(this.handleClickAway); if (this.props.onClickAway) { bind(this.handleClickAway); } } } componentWillUnmount() { unbind(this.handleClickAway); } handleClickAway = (event) => { if (event.defaultPrevented) { return; } const el = ReactDOM.findDOMNode(this); if (document.documentElement.contains(event.target) && !isDescendant(el, event.target)) { this.props.onClickAway(event); } }; render() { return this.props.children; } } ","import React from 'react'; import ReactDOM from 'react-dom'; import events from '../utils/events'; const isDescendant = (el, target) => { if (target !== null) { return el === target || isDescendant(el, target.parentNode); } return false; }; const clickAwayEvents = ['mousedown', 'touchstart']; const bind = (callback) => clickAwayEvents.forEach((event) => events.on(document, event, callback)); const unbind = (callback) => clickAwayEvents.forEach((event) => events.off(document, event, callback)); export default class ClickAwayListener extends React.Component { static propTypes = { children: React.PropTypes.node, onClickAway: React.PropTypes.any, }; componentDidMount() { if (this.props.onClickAway) { bind(this.handleClickAway); } } componentDidUpdate(prevProps) { if (prevProps.onClickAway !== this.props.onClickAway) { unbind(this.handleClickAway); if (this.props.onClickAway) { bind(this.handleClickAway); } } } componentWillUnmount() { unbind(this.handleClickAway); } handleClickAway = (event) => { if (event.defaultPrevented) { return; } const el = ReactDOM.findDOMNode(this); if (document.documentElement.contains(event.target) && !isDescendant(el, event.target)) { this.props.onClickAway(event); } }; render() { return this.props.children; } } " Move fallback URL pattern to the end of the list so it gets matched last.,"#!/usr/bin/python # -*- coding: utf-8 -*- from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.views.static import serve urlpatterns = [ url(r'^', include('django.contrib.auth.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^web/', include('campus02.web.urls', namespace='web')), ] if settings.DEBUG: import debug_toolbar urlpatterns.append( url( r'^__debug__/', include(debug_toolbar.urls) ) ) urlpatterns.append( url( r'^media/(?P<path>.*)$', serve, { 'document_root': settings.MEDIA_ROOT, } ) ) urlpatterns.append( url( r'^static/(?P<path>.*)$', serve, { 'document_root': settings.STATIC_ROOT, } ), ) urlpatterns.append( url(r'^', include('campus02.base.urls', namespace='base')) ) ","#!/usr/bin/python # -*- coding: utf-8 -*- from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.views.static import serve urlpatterns = [ url(r'^', include('django.contrib.auth.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^web/', include('campus02.web.urls', namespace='web')), url(r'^', include('campus02.base.urls', namespace='base')), ] if settings.DEBUG: import debug_toolbar urlpatterns.append( url( r'^__debug__/', include(debug_toolbar.urls) ) ) urlpatterns.append( url( r'^media/(?P<path>.*)$', serve, { 'document_root': settings.MEDIA_ROOT, } ) ) urlpatterns.append( url( r'^static/(?P<path>.*)$', serve, { 'document_root': settings.STATIC_ROOT, } ), ) " "Support creating a next page, retrieve only the current page, and delete the current page and move to the next one. Switch to requests library for PUT and DELETE methods.","#!/usr/bin/env python import datetime import logging import requests class HarManager(object): def __init__(self, args): self._logger = logging.getLogger('kcaa.proxy_util') self.pageref = 1 proxy_root = 'http://{}/proxy/{}'.format(args.proxy_controller, args.proxy.partition(':')[2]) self._proxy_har = '{}/har'.format(proxy_root) self._proxy_har_pageref = '{}/har/pageRef'.format(proxy_root) def get_next_page(self): start = datetime.datetime.now() next_pageref = self.pageref + 1 rp = requests.put(self._proxy_har_pageref, data={'pageRef': next_pageref}) rp.raise_for_status() rg = requests.get('{}?pageRef={}'.format(self._proxy_har, self.pageref)) rg.raise_for_status() rd = requests.delete('{}/{}'.format(self._proxy_har_pageref, self.pageref)) rd.raise_for_status() self.pageref = next_pageref end = datetime.datetime.now() # No Content-Length header? content_size = len(rg.text) self._logger.debug('Poke HAR ({:.1f} KiB) in {:.2f} seconds.'.format( (1.0 / 1024) * content_size, (end - start).total_seconds())) # HAR content should always be encoded in UTF-8, according to the spec. return rg.json(encoding='utf8') ","#!/usr/bin/env python import datetime import json import logging import urllib2 class HarManager(object): def __init__(self, args): self._logger = logging.getLogger('kcaa.proxy_util') self.pageref = 1 proxy_root = 'http://{}/proxy/{}'.format(args.proxy_controller, args.proxy.partition(':')[2]) self.har = '{}/har'.format(proxy_root) self.har_pageref = '{}/har/pageref' def _get(self, url): try: return urllib2.urlopen(url) except urllib2.URLError as e: self._logger.error('Proxy error: {}'.format(e)) return None def get_next_page(self): # TODO: Create the next page start = datetime.datetime.now() # TODO: Retrieve only the current page data = self._get(self.har) # TODO: Delete the current page and move to the next one if not data: return None end = datetime.datetime.now() content = data.read() # No Content-Length header? content_size = len(content) self._logger.debug('Poke HAR ({:.1f} KiB) in {:.2f} seconds.'.format( (1.0 / 1024) * content_size, (end - start).total_seconds())) # HAR content should always be encoded in UTF-8, according to the spec. return json.loads(content, encoding='utf8') " Add registration link and 2020 logo,"$(document).ready(function() { $('#navbar_replacement').replaceWith('\ <div class=""navbar navbar-inverse navbar-static-top"">\ <div class=""container"">\ <div class=""navbar-header"">\ <button type=""button"" class=""navbar-toggle"" data-toggle=""collapse"" data-target="".navbar-collapse"">\ <span class=""icon-bar""></span>\ <span class=""icon-bar""></span>\ <span class=""icon-bar""></span>\ </button>\ <a class=""navbar-brand"" href=""index.html""><img class=""img-responsive"" style=""width:280px;max-width:100%"" src=""assets/img/NoCaSS2020_transparent.png"" alt=""NoCaSS 2020""></a>\ </div>\ <div class=""navbar-collapse collapse"">\ <ul class=""nav navbar-nav navbar-right"">\ <li><a href=""https://twitter.com/intent/follow?screen_name=nocass_official"">Follow @nocass_official</a></li>\ <li><a href=""index.html"">Home</a></li>\ <li><a href=""about.html"">About</a></li>\ <li><a href=""programme.html"">Programme</a></li>\ <li><a href=""venue.html"">Venue</a></li>\ <li><a href=""registration2.html"">Registration</a></li>\ <li><a href=""sponsors.html"">Sponsorship</a></li>\ </ul>\ </div><!--/.nav-collapse -->\ </div>\ </div>\ '); }) ","$(document).ready(function() { $('#navbar_replacement').replaceWith('\ <div class=""navbar navbar-inverse navbar-static-top"">\ <div class=""container"">\ <div class=""navbar-header"">\ <button type=""button"" class=""navbar-toggle"" data-toggle=""collapse"" data-target="".navbar-collapse"">\ <span class=""icon-bar""></span>\ <span class=""icon-bar""></span>\ <span class=""icon-bar""></span>\ </button>\ <a class=""navbar-brand"" href=""index.html""><img class=""img-responsive"" style=""width:280px;max-width:100%"" src=""assets/img/Horizontal_header_generic.svg"" alt=""NoCaSS 2020""></a>\ </div>\ <div class=""navbar-collapse collapse"">\ <ul class=""nav navbar-nav navbar-right"">\ <li><a href=""https://twitter.com/intent/follow?screen_name=nocass_official"">Follow @nocass_official</a></li>\ <li><a href=""index.html"">Home</a></li>\ <li><a href=""about.html"">About</a></li>\ <li><a href=""programme.html"">Programme</a></li>\ <li><a href=""venue.html"">Venue</a></li>\ <li><a href=""#"">Registration</a></li>\ <li><a href=""sponsors.html"">Sponsorship</a></li>\ </ul>\ </div><!--/.nav-collapse -->\ </div>\ </div>\ '); }) " "Fix - removed private access modifier from Enum constructor It is already private by spec.","package com.maxmind.geoip2.model; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; /** * This class provides the GeoIP2 Connection-Type model. */ public class ConnectionTypeResponse extends AbstractResponse { /** * The enumerated values that connection-type may take. */ public enum ConnectionType { DIALUP(""Dialup""), CABLE_DSL(""Cable/DSL""), CORPORATE(""Corporate""), CELLULAR( ""Cellular""); private final String name; ConnectionType(String name) { this.name = name; } /* * (non-Javadoc) * * @see java.lang.Enum#toString() */ @JsonValue @Override public String toString() { return this.name; } } private final ConnectionType connectionType; private final String ipAddress; ConnectionTypeResponse() { this(null, null); } public ConnectionTypeResponse( @JsonProperty(""connection_type"") ConnectionType connectionType, @JsonProperty(""ip_address"") String ipAddress ) { this.connectionType = connectionType; this.ipAddress = ipAddress; } /** * @return The connection type of the IP address. */ @JsonProperty(""connection_type"") public ConnectionType getConnectionType() { return this.connectionType; } /** * @return The IP address that the data in the model is for. */ @JsonProperty(""ip_address"") public String getIpAddress() { return this.ipAddress; } } ","package com.maxmind.geoip2.model; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; /** * This class provides the GeoIP2 Connection-Type model. */ public class ConnectionTypeResponse extends AbstractResponse { /** * The enumerated values that connection-type may take. */ public enum ConnectionType { DIALUP(""Dialup""), CABLE_DSL(""Cable/DSL""), CORPORATE(""Corporate""), CELLULAR( ""Cellular""); private final String name; private ConnectionType(String name) { this.name = name; } /* * (non-Javadoc) * * @see java.lang.Enum#toString() */ @JsonValue @Override public String toString() { return this.name; } } private final ConnectionType connectionType; private final String ipAddress; ConnectionTypeResponse() { this(null, null); } public ConnectionTypeResponse( @JsonProperty(""connection_type"") ConnectionType connectionType, @JsonProperty(""ip_address"") String ipAddress ) { this.connectionType = connectionType; this.ipAddress = ipAddress; } /** * @return The connection type of the IP address. */ @JsonProperty(""connection_type"") public ConnectionType getConnectionType() { return this.connectionType; } /** * @return The IP address that the data in the model is for. */ @JsonProperty(""ip_address"") public String getIpAddress() { return this.ipAddress; } } " Fix typo in 8ball response,"import random from plugin import CommandPlugin, PluginException class Ball8(CommandPlugin): """""" 8ball command (by javipepe :)) """""" def __init__(self, bot): CommandPlugin.__init__(self, bot) self.triggers = ['8ball'] self.short_help = 'Ask me a question' self.help = 'Ask me a question, I\'ll decide what the answer should be. Based on https://en.wikipedia.org/wiki/Magic_8-Ball' self.help_example = ['!8ball Is linux better than windows?'] # ^ obviously yes. def on_command(self, event, response): args = event['text'] if not args or not args[-1:].__contains__('?'): raise PluginException('Invalid argument! Ask me a question!') else: possible_answers = ['It is certain', 'It is decidedly so', 'Without a doubt', 'Yes, definitely', 'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good', 'Yes', 'Signs point to yes', 'Reply hazy try again', 'Ask again later', 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again', 'Don\'t count on it', 'My reply is no', 'My sources say no', 'Outlook not so good', 'Very doubtful'] response['text'] = ':8ball: says *_%s_*!' % random.choice(possible_answers) self.bot.sc.api_call('chat.postMessage', **response) ","import random from plugin import CommandPlugin, PluginException class Ball8(CommandPlugin): """""" 8ball command (by javipepe :)) """""" def __init__(self, bot): CommandPlugin.__init__(self, bot) self.triggers = ['8ball'] self.short_help = 'Ask me a question' self.help = 'Ask me a question, I\'ll decide what the answer should be. Based on https://en.wikipedia.org/wiki/Magic_8-Ball' self.help_example = ['!8ball Is linux better than windows?'] # ^ obviously yes. def on_command(self, event, response): args = event['text'] if not args or not args[-1:].__contains__('?'): raise PluginException('Invalid argument! Ask me a question!') else: possible_answers = ['It is certain', 'It is decidedly so', 'Without a doubt', 'Yes, definitely', 'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good', 'Yes', 'Signs point to yes', 'Reply hazy try again', 'Ask again later', 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again', 'Do\'t count on it', 'My reply is no', 'My sources say no', 'Outlook not so good', 'Very doubtful'] response['text'] = ':8ball: says *_%s_*!' % random.choice(possible_answers) self.bot.sc.api_call('chat.postMessage', **response) " Fix error when import lamvery in function,"# -*- coding: utf-8 -*- import os import sys import re import shlex import subprocess ENV_PATTERN = re.compile('^(?P<name>[^\s]+)\s*=\s*(?P<value>.+)$') def previous_alias(alias): return '{}-pre'.format(alias) def parse_env_args(env): if not isinstance(env, list): return None ret = {} for e in env: matches = ENV_PATTERN.match(e) if matches is None: raise Exception( 'The format of ""env"" option must be ""NAME=VALUE"": {}'.format(e)) name = matches.group('name') value = matches.group('value') k, v = shlex.split('{} {}'.format(name, value)) ret[k] = v return ret def run_commands(commands, working_dir=os.getcwd()): cwd = os.getcwd() os.chdir(working_dir) for c in commands: try: subprocess.check_output( c, stderr=subprocess.STDOUT, shell=True) except subprocess.CalledProcessError as e: os.chdir(cwd) raise Exception(e.output) os.chdir(cwd) def confirm_overwrite(path): ret = True if os.path.exists(path): print('Overwrite {}? [y/n]: '.format(path)) y_n = sys.stdin.readline() if not y_n.startswith('y'): ret = False return ret ","# -*- coding: utf-8 -*- import os import sys import re import shlex import subprocess from termcolor import cprint ENV_PATTERN = re.compile('^(?P<name>[^\s]+)\s*=\s*(?P<value>.+)$') def previous_alias(alias): return '{}-pre'.format(alias) def parse_env_args(env): if not isinstance(env, list): return None ret = {} for e in env: matches = ENV_PATTERN.match(e) if matches is None: raise Exception( 'The format of ""env"" option must be ""NAME=VALUE"": {}'.format(e)) name = matches.group('name') value = matches.group('value') k, v = shlex.split('{} {}'.format(name, value)) ret[k] = v return ret def run_commands(commands, working_dir=os.getcwd()): cwd = os.getcwd() os.chdir(working_dir) for c in commands: try: subprocess.check_output( c, stderr=subprocess.STDOUT, shell=True) except subprocess.CalledProcessError as e: os.chdir(cwd) raise Exception(e.output) os.chdir(cwd) def confirm_overwrite(path): ret = True if os.path.exists(path): cprint('Overwrite {}? [y/n]: '.format(path), 'yellow', file=sys.stderr, end="""") y_n = sys.stdin.readline() if not y_n.startswith('y'): ret = False return ret " Add log line for susbcription stats email recipients,"const logger = require('logger'); const mailService = require('services/mailService'); const DEFAULT_TEMPLATE = 'forest-change-notification'; const TEMPLATE_MAP = { 'viirs-active-fires': 'forest-fires-notification-viirs', 'imazon-alerts': 'forest-change-imazon-alerts', story: 'stories-alerts', 'forma-alerts': 'forest-change-notification', forma250GFW: 'forest-change-notification', 'terrai-alerts': 'forest-change-notification', 'glad-alerts': 'forest-change-notification-glads', 'monthly-summary': 'monthly-summary', }; class EmailPublisher { static async publish(subscription, results, layer) { logger.info('Publishing email with results', results); let template = TEMPLATE_MAP[layer.slug] || DEFAULT_TEMPLATE; const language = subscription.language.toLowerCase().replace(/_/g, '-'); template = `${template}-${language}`; logger.info('MAIL TEMPLATE', template); const recipients = [{ address: { email: subscription.resource.content } }]; mailService.sendMail(template, results, recipients); } static sendStats(emails, stats) { logger.info('Publishing email with stats', stats); const template = 'subscriptions-stats'; logger.info('MAIL TEMPLATE', template); const recipients = emails.map((el) => ({ address: { email: el } })); logger.info('Subscription stats email recipients', emails); mailService.sendMail(template, stats, recipients); } } module.exports = EmailPublisher; ","const logger = require('logger'); const mailService = require('services/mailService'); const DEFAULT_TEMPLATE = 'forest-change-notification'; const TEMPLATE_MAP = { 'viirs-active-fires': 'forest-fires-notification-viirs', 'imazon-alerts': 'forest-change-imazon-alerts', story: 'stories-alerts', 'forma-alerts': 'forest-change-notification', forma250GFW: 'forest-change-notification', 'terrai-alerts': 'forest-change-notification', 'glad-alerts': 'forest-change-notification-glads', 'monthly-summary': 'monthly-summary', }; class EmailPublisher { static async publish(subscription, results, layer) { logger.info('Publishing email with results', results); let template = TEMPLATE_MAP[layer.slug] || DEFAULT_TEMPLATE; const language = subscription.language.toLowerCase().replace(/_/g, '-'); template = `${template}-${language}`; logger.info('MAIL TEMPLATE', template); const recipients = [{ address: { email: subscription.resource.content } }]; mailService.sendMail(template, results, recipients); } static sendStats(emails, stats) { logger.info('Publishing email with stats', stats); const template = 'subscriptions-stats'; logger.info('MAIL TEMPLATE', template); const recipients = emails.map((el) => ({ address: { email: el } })); mailService.sendMail(template, stats, recipients); } } module.exports = EmailPublisher; " Fix formula as requested in review,"'use strict'; import NearestNeighborIndexProcessor from './NearestNeighborIndexProcessor'; class FixationsDataProcessor { constructor() { this.fixationsData = []; this.nniProcessor = new NearestNeighborIndexProcessor(); } getScreenResolution(fileContentsAsArray) { let firstLine = fileContentsAsArray[0]; let resolution = firstLine.split(' '); return { width: parseInt(resolution[0]), height: parseInt(resolution[1]) } } process(fileContentsAsArray) { fileContentsAsArray.splice(0, 1); for(let c in fileContentsAsArray) { let lineItems = fileContentsAsArray[c].split(' '); this.addItemToMinute([lineItems[1], lineItems[2]], this.getMinuteFromTimestamp(parseInt(lineItems[0]))); } for(let i in this.fixationsData) { this.fixationsData[i]['nni'] = this.nniProcessor.calculate(this.fixationsData[i].points); } return this.fixationsData; } addItemToMinute(point, minute) { if(this.fixationsData[minute] === undefined) { this.fixationsData[minute] = { points: [point] } } else { this.fixationsData[minute].points.push(point); } } getMinuteFromTimestamp(timestamp) { let minute = Math.floor(timestamp / 1000 / 60); return minute; } } export default FixationsDataProcessor ","'use strict'; import NearestNeighborIndexProcessor from './NearestNeighborIndexProcessor'; class FixationsDataProcessor { constructor() { this.fixationsData = []; this.nniProcessor = new NearestNeighborIndexProcessor(); } getScreenResolution(fileContentsAsArray) { let firstLine = fileContentsAsArray[0]; let resolution = firstLine.split(' '); return { width: parseInt(resolution[0]), height: parseInt(resolution[1]) } } process(fileContentsAsArray) { fileContentsAsArray.splice(0, 1); for(let c in fileContentsAsArray) { let lineItems = fileContentsAsArray[c].split(' '); this.addItemToMinute([lineItems[1], lineItems[2]], this.getMinuteFromTimestamp(parseInt(lineItems[0]))); } for(let i in this.fixationsData) { this.fixationsData[i]['nni'] = this.nniProcessor.calculate(this.fixationsData[i].points); } return this.fixationsData; } addItemToMinute(point, minute) { if(this.fixationsData[minute] === undefined) { this.fixationsData[minute] = { points: [point] } } else { this.fixationsData[minute].points.push(point); } } getMinuteFromTimestamp(timestamp) { let minute = Math.floor(timestamp * 1.67 * 0.00001); return minute; } } export default FixationsDataProcessor " Fix API root for latest Workspace.,"angular.module('<%= appname %>', ['ngResource']) .service('TodosSvc', function ($resource) { var Todo = $resource('http://localhost:3000/api/todos/:todoId', { todoId: '@id' }); var todos = { items: [] }; todos.addItem = addItem; function addItem(name) { var item = new Todo({ name: name }); item.$save(function () { todos.items.push(item); }); } todos.removeItem = removeItem; function removeItem(index) { var todo = todos.items[index]; todo.$delete(); todos.items.splice(index, 1); } todos.items = Todo.query(); return todos; }) .controller('TodosCtrl', function ($scope, TodosSvc) { $scope.items = TodosSvc.items; $scope.name = ''; $scope.add = function () { TodosSvc.addItem($scope.name); $scope.name = ''; }; $scope.cancel = function (index) { TodosSvc.removeItem(index); }; $scope.complete = function (index) { TodosSvc.removeItem(index); }; }); document.addEventListener(window.cordova ? 'deviceready' : 'DOMContentLoaded', function () { console.log('BACN v<%= version %> Loaded.'); angular.bootstrap(document, ['<%= appname %>']); }, false); ","angular.module('<%= appname %>', ['ngResource']) .service('TodosSvc', function ($resource) { var Todo = $resource('http://localhost:3000/todos/:todoId', { todoId: '@id' }); var todos = { items: [] }; todos.addItem = addItem; function addItem(name) { var item = new Todo({ name: name }); item.$save(function () { todos.items.push(item); }); } todos.removeItem = removeItem; function removeItem(index) { var todo = todos.items[index]; todo.$delete(); todos.items.splice(index, 1); } todos.items = Todo.query(); return todos; }) .controller('TodosCtrl', function ($scope, TodosSvc) { $scope.items = TodosSvc.items; $scope.name = ''; $scope.add = function () { TodosSvc.addItem($scope.name); $scope.name = ''; }; $scope.cancel = function (index) { TodosSvc.removeItem(index); }; $scope.complete = function (index) { TodosSvc.removeItem(index); }; }); document.addEventListener(window.cordova ? 'deviceready' : 'DOMContentLoaded', function () { console.log('BACN v<%= version %> Loaded.'); angular.bootstrap(document, ['<%= appname %>']); }, false); " Allow data to be sent on job run queue.,"'use strict'; import DrushIORun from '../run/client'; let apiClient; class DrushIORuns { constructor(client, project, job) { apiClient = client; this.project = project; this.job = job; } create(params = {}, wait = false) { return new Promise((resolve, reject) => { apiClient.post(`/projects/${this.project.identifier}/jobs/${this.job.identifier}/runs`, params).then((response) => { let intervalTimer; if (wait) { intervalTimer = setInterval(() => { apiClient.get(`/projects/${this.project.identifier}/jobs/${this.job.identifier}/runs/${response.body.id}`).then((res) => { if (['error', 'complete'].indexOf(res.body.status) >= 0) { clearInterval(intervalTimer); resolve(new DrushIORun(apiClient, this.project, this.job, res.body.id, res.body)) } }).catch((err) => { clearInterval(intervalTimer); reject(err); }); }, 5000); } else { resolve(new DrushIORun(apiClient, this.project, this.job, response.body.id, response.body)); } }).catch((err) => { reject(err); }); }); } } export default DrushIORuns; ","'use strict'; import DrushIORun from '../run/client'; let apiClient; class DrushIORuns { constructor(client, project, job) { apiClient = client; this.project = project; this.job = job; } create(params = {}, wait = false) { return new Promise((resolve, reject) => { apiClient.post(`/projects/${this.project.identifier}/jobs/${this.job.identifier}/runs`).then((response) => { let intervalTimer; if (wait) { intervalTimer = setInterval(() => { apiClient.get(`/projects/${this.project.identifier}/jobs/${this.job.identifier}/runs/${response.body.id}`).then((res) => { if (['error', 'complete'].indexOf(res.body.status) >= 0) { clearInterval(intervalTimer); resolve(new DrushIORun(apiClient, this.project, this.job, res.body.id, res.body)) } }).catch((err) => { clearInterval(intervalTimer); reject(err); }); }, 5000); } else { resolve(new DrushIORun(apiClient, this.project, this.job, response.body.id, response.body)); } }).catch((err) => { reject(err); }); }); } } export default DrushIORuns; " feat: Configure symfony serializer to preserve empty objects,"<?php namespace CQRSFactory; use CQRS\Serializer\SerializerInterface; use CQRS\Serializer\SymfonySerializer; use CQRSFactory\Exception\DomainException; use Psr\Container\ContainerInterface; use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer; use Symfony\Component\Serializer\SerializerInterface as SymfonySerializerInterface; /** * @phpstan-type SerializerConfig array{ * class: class-string<SerializerInterface>, * instance?: class-string|object, * format?: string, * context?: array * } * @phpstan-extends AbstractFactory<SerializerInterface> */ class SerializerFactory extends AbstractFactory { protected function createWithConfig(ContainerInterface $container, string $configKey): SerializerInterface { /** @var SerializerConfig $config */ $config = $this->retrieveConfig($container, $configKey, 'serializer'); if ($config['class'] === SymfonySerializer::class) { $instance = $this->retrieveService( $container, $config, 'instance', SymfonySerializerInterface::class ); $format = $config['format'] ?? 'json'; $context = $config['context'] ?? []; return new SymfonySerializer($instance, $format, $context); } return new $config['class']; } /** * @phpstan-return SerializerConfig */ protected function getDefaultConfig(): array { return [ 'class' => SymfonySerializer::class, 'instance' => SymfonySerializerInterface::class, 'context' => [ AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS => true, ], ]; } } ","<?php namespace CQRSFactory; use CQRS\Serializer\SerializerInterface; use CQRS\Serializer\SymfonySerializer; use CQRSFactory\Exception\DomainException; use Psr\Container\ContainerInterface; use Symfony\Component\Serializer\SerializerInterface as SymfonySerializerInterface; /** * @phpstan-type SerializerConfig array{ * class: class-string<SerializerInterface>, * instance?: class-string|object, * format?: string, * context?: array * } * @phpstan-extends AbstractFactory<SerializerInterface> */ class SerializerFactory extends AbstractFactory { protected function createWithConfig(ContainerInterface $container, string $configKey): SerializerInterface { /** @var SerializerConfig $config */ $config = $this->retrieveConfig($container, $configKey, 'serializer'); if ($config['class'] === SymfonySerializer::class) { $instance = $this->retrieveService( $container, $config, 'instance', SymfonySerializerInterface::class ); $format = $config['format'] ?? 'json'; $context = $config['context'] ?? []; return new SymfonySerializer($instance, $format, $context); } return new $config['class']; } /** * @phpstan-return SerializerConfig */ protected function getDefaultConfig(): array { return [ 'class' => SymfonySerializer::class, 'instance' => SymfonySerializerInterface::class, ]; } } " Add dominion state metadata to Bugsnag,"<?php namespace OpenDominion\Http\Middleware; use Bugsnag; use Closure; use Illuminate\Database\Eloquent\ModelNotFoundException; use OpenDominion\Services\Dominion\SelectorService; class ShareSelectedDominion { /** @var SelectorService */ protected $dominionSelectorService; /** * ShareSelectedDominion constructor. * * @param SelectorService $dominionSelectorService */ public function __construct(SelectorService $dominionSelectorService) { $this->dominionSelectorService = $dominionSelectorService; } public function handle($request, Closure $next) { if (starts_with($request->path(), 'nova')) { return $next($request); } if ($this->dominionSelectorService->hasUserSelectedDominion()) { try { $dominion = $this->dominionSelectorService->getUserSelectedDominion(); } catch (ModelNotFoundException $e) { $this->dominionSelectorService->unsetUserSelectedDominion(); $request->session()->flash('alert-danger', 'The database has been reset for development purposes since your last visit. Please re-register a new account. You can use the same credentials you\'ve used before.'); return redirect()->route('home'); } // Add dominion context to Bugsnag Bugsnag::registerCallback(function (Bugsnag\Report $report) use ($dominion) { /** @noinspection NullPointerExceptionInspection */ $report->setMetaData([ 'dominion' => array_except($dominion->toArray(), ['race', 'realm']), ]); }); view()->share('selectedDominion', $dominion); } return $next($request); } } ","<?php namespace OpenDominion\Http\Middleware; use Closure; use Illuminate\Database\Eloquent\ModelNotFoundException; use OpenDominion\Services\Dominion\SelectorService; class ShareSelectedDominion { /** @var SelectorService */ protected $dominionSelectorService; /** * ShareSelectedDominion constructor. * * @param SelectorService $dominionSelectorService */ public function __construct(SelectorService $dominionSelectorService) { $this->dominionSelectorService = $dominionSelectorService; } public function handle($request, Closure $next) { if (starts_with($request->path(), 'nova')) { return $next($request); } if ($this->dominionSelectorService->hasUserSelectedDominion()) { try { $dominion = $this->dominionSelectorService->getUserSelectedDominion(); } catch (ModelNotFoundException $e) { $this->dominionSelectorService->unsetUserSelectedDominion(); $request->session()->flash('alert-danger', 'The database has been reset for development purposes since your last visit. Please re-register a new account. You can use the same credentials you\'ve used before.'); return redirect()->route('home'); } view()->share('selectedDominion', $dominion); } return $next($request); } } " Use the slash module to support windows pathes,"import slash from 'slash'; export default function() { class BabelRootImportHelper { root = global.rootPath || process.cwd() transformRelativeToRootPath(importPath, rootPathSuffix, rootPathPrefix) { let withoutRootPathPrefix = ''; if (this.hasRootPathPrefixInString(importPath, rootPathPrefix)) { if (importPath.substring(0, 1) === '/') { withoutRootPathPrefix = importPath.substring(1, importPath.length); } else { withoutRootPathPrefix = importPath.substring(2, importPath.length); } return `${slash(this.root)}${rootPathSuffix ? rootPathSuffix : ''}/${withoutRootPathPrefix}`; } if (typeof importPath === 'string') { return importPath; } throw new Error('ERROR: No path passed'); } hasRootPathPrefixInString(importPath, rootPathPrefix = '~') { let containsRootPathPrefix = false; if (typeof importPath === 'string') { if (importPath.substring(0, 1) === rootPathPrefix) { containsRootPathPrefix = true; } const firstTwoCharactersOfString = importPath.substring(0, 2); if (firstTwoCharactersOfString === `${rootPathPrefix}/`) { containsRootPathPrefix = true; } } return containsRootPathPrefix; } } return new BabelRootImportHelper(); } ","export default function() { class BabelRootImportHelper { root = global.rootPath || process.cwd() transformRelativeToRootPath(importPath, rootPathSuffix, rootPathPrefix) { let withoutRootPathPrefix = ''; if (this.hasRootPathPrefixInString(importPath, rootPathPrefix)) { if (importPath.substring(0, 1) === '/') { withoutRootPathPrefix = importPath.substring(1, importPath.length); } else { withoutRootPathPrefix = importPath.substring(2, importPath.length); } return `${this.root}${rootPathSuffix ? rootPathSuffix : ''}/${withoutRootPathPrefix}`; } if (typeof importPath === 'string') { return importPath; } throw new Error('ERROR: No path passed'); } hasRootPathPrefixInString(importPath, rootPathPrefix = '~') { let containsRootPathPrefix = false; if (typeof importPath === 'string') { if (importPath.substring(0, 1) === rootPathPrefix) { containsRootPathPrefix = true; } const firstTwoCharactersOfString = importPath.substring(0, 2); if (firstTwoCharactersOfString === `${rootPathPrefix}/`) { containsRootPathPrefix = true; } } return containsRootPathPrefix; } } return new BabelRootImportHelper(); } " Fix tests failing on cypress 3.1.0,"describe('Import JSON', () => { it('should work properly', () => { cy.loginVisit('/') cy.fixture('import.json').then(IMPORT_API => { // Click [Import JSON] button cy.get('.j-buttons__wrapper > a[href=""/new""] + div > button') .click() // Prepare file upload const file = JSON.stringify(IMPORT_API, null, 2) const fileArray = file.split('\n') const fileObject = new File(fileArray, 'import.json', { type: 'application/json' }) const dropEvent = { dataTransfer: { files: [ fileObject ] } } // Execute File upload cy.get('.uploader') .trigger('drop', dropEvent).then(() => { // Wait until editor appears, indicating successful upload cy.get('#gw-json-editor') // Confirm upload cy.get('.j-confirmation-container > .j-confirmation__buttons-group > .j-button--primary') .click({ force: true }) .get('.j-confirmation__buttons-group > .j-button--primary') .click() // Validate that imported api endpoint is created cy.loginVisit('/') cy.get('.j-search-bar__input', { timeout: 100000 }) .type(IMPORT_API.name) .get('.j-table__tbody') .contains(IMPORT_API.name) }) }) }) }) ","describe('Import JSON', () => { it('should work properly', () => { cy.loginVisit('/') cy.fixture('import.json').then(IMPORT_API => { // Click [Import JSON] button cy.get('.j-buttons__wrapper > a[href=""/new""] + div > button') .click() // Prepare file upload const file = JSON.stringify(IMPORT_API, null, 2) const fileArray = file.split('\n') const fileObject = new File(fileArray, 'import.json', { type: 'application/json' }) const dropEvent = { dataTransfer: { files: [ fileObject ] } } // Execute File upload cy.get('.uploader') .trigger('drop', dropEvent).then(() => { // Confirm upload cy.get('.j-confirmation-container > .j-confirmation__buttons-group > .j-button--primary') .click({ force: true }) .get('.j-confirmation__buttons-group > .j-button--primary') .click() // Validate that imported api endpoint is created cy.loginVisit('/') cy.get('.j-search-bar__input', { timeout: 100000 }) .type(IMPORT_API.name) .get('.j-table__tbody') .contains(IMPORT_API.name) }) }) }) }) " "Change precedence of fillStyle's parameters User provided `style` overrides should take precedence over color.","import React from 'react'; export default class SparklinesLine extends React.Component { static propTypes = { color: React.PropTypes.string, style: React.PropTypes.object }; static defaultProps = { style: {} }; render() { const { points, width, height, margin, color, style } = this.props; const linePoints = points .map((p) => [p.x, p.y]) .reduce((a, b) => a.concat(b)); const closePolyPoints = [ points[points.length - 1].x, height - margin, margin, height - margin, margin, points[0].y ]; const fillPoints = linePoints.concat(closePolyPoints); const lineStyle = { stroke: color || style.stroke || 'slategray', strokeWidth: style.strokeWidth || '1', strokeLinejoin: style.strokeLinejoin || 'round', strokeLinecap: style.strokeLinecap || 'round', fill: 'none' }; const fillStyle = { stroke: style.stroke || 'none', strokeWidth: '0', fillOpacity: style.fillOpacity || '.1', fill: style.fill || color || 'slategray' }; return ( <g> <polyline points={fillPoints.join(' ')} style={fillStyle} /> <polyline points={linePoints.join(' ')} style={lineStyle} /> </g> ) } } ","import React from 'react'; export default class SparklinesLine extends React.Component { static propTypes = { color: React.PropTypes.string, style: React.PropTypes.object }; static defaultProps = { style: {} }; render() { const { points, width, height, margin, color, style } = this.props; const linePoints = points .map((p) => [p.x, p.y]) .reduce((a, b) => a.concat(b)); const closePolyPoints = [ points[points.length - 1].x, height - margin, margin, height - margin, margin, points[0].y ]; const fillPoints = linePoints.concat(closePolyPoints); const lineStyle = { stroke: color || style.stroke || 'slategray', strokeWidth: style.strokeWidth || '1', strokeLinejoin: style.strokeLinejoin || 'round', strokeLinecap: style.strokeLinecap || 'round', fill: 'none' }; const fillStyle = { stroke: style.stroke || 'none', strokeWidth: '0', fillOpacity: style.fillOpacity || '.1', fill: color || style.fill || 'slategray' }; return ( <g> <polyline points={fillPoints.join(' ')} style={fillStyle} /> <polyline points={linePoints.join(' ')} style={lineStyle} /> </g> ) } } " "[IMP] Set Picking Type in Create [IMP] Flake8","# Copyright 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' @api.model def _get_default_picking_type(self): return self.env['stock.picking.type'].search([ ('code', '=', 'stock_request_order'), ('warehouse_id.company_id', 'in', [self.env.context.get('company_id', self.env.user.company_id.id), False])], limit=1).id picking_type_id = fields.Many2one( 'stock.picking.type', 'Operation Type', default=_get_default_picking_type, required=True) @api.onchange('warehouse_id') def onchange_warehouse_picking_id(self): if self.warehouse_id: picking_type_id = self.env['stock.picking.type'].\ search([('code', '=', 'stock_request_order'), ('warehouse_id', '=', self.warehouse_id.id)], limit=1) if picking_type_id: self._origin.write({'picking_type_id': picking_type_id.id}) @api.model def create(self, vals): if vals.get('warehouse_id', False): picking_type_id = self.env['stock.picking.type'].\ search([('code', '=', 'stock_request_order'), ('warehouse_id', '=', vals['warehouse_id'])], limit=1) if picking_type_id: vals.update({'picking_type_id': picking_type_id.id}) return super().create(vals) ","# Copyright 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' @api.model def _get_default_picking_type(self): return self.env['stock.picking.type'].search([ ('code', '=', 'stock_request_order'), ('warehouse_id.company_id', 'in', [self.env.context.get('company_id', self.env.user.company_id.id), False])], limit=1).id picking_type_id = fields.Many2one( 'stock.picking.type', 'Operation Type', default=_get_default_picking_type, required=True) @api.onchange('warehouse_id') def onchange_warehouse_picking_id(self): if self.warehouse_id: picking_type_id = self.env['stock.picking.type'].\ search([('code', '=', 'stock_request_order'), ('warehouse_id', '=', self.warehouse_id.id)], limit=1) if picking_type_id: self._origin.write({'picking_type_id': picking_type_id.id}) " Add results from load more to matches prop,"import { connect } from 'react-redux'; import Matches from '../components/Matches.jsx'; import { unmountMatch, removeMatch, incrementOffset, addMatches } from '../actions/index.js'; import request from 'then-request'; const mapStateToProps = (state) => ( { matches: state.matches.values, offset: state.matches.offset, self: state.profile, } ); const mapDispatchToProps = (dispatch) => ( { onConnectClick: (id) => { dispatch(unmountMatch(id)); setTimeout( () => { dispatch(removeMatch(id)); }, 120 ); }, onHideClick: (id) => { dispatch(unmountMatch(id)); setTimeout( () => { dispatch(removeMatch(id)); }, 120 ); }, onLoadMoreClick: (self, offset) => { //use the offset to get additional matches from db, then request('GET', '/api/matches', { qs: { self, offset, }, }) .done((matches) => { if (matches.statusCode === 200) { dispatch(addMatches(JSON.parse(matches.body))); dispatch(incrementOffset(20)); } else { // TODO: handle error } }); }, } ); export default connect(mapStateToProps, mapDispatchToProps)(Matches); ","import { connect } from 'react-redux'; import Matches from '../components/Matches.jsx'; import { unmountMatch, removeMatch, incrementOffset, addMatches } from '../actions/index.js'; import request from 'then-request'; const mapStateToProps = (state) => ( { matches: state.matches.values, offset: state.matches.offset, self: state.profile, } ); const mapDispatchToProps = (dispatch) => ( { onConnectClick: (id) => { dispatch(unmountMatch(id)); setTimeout( () => { dispatch(removeMatch(id)); }, 120 ); }, onHideClick: (id) => { dispatch(unmountMatch(id)); setTimeout( () => { dispatch(removeMatch(id)); }, 120 ); }, onLoadMoreClick: (self, offset) => { //use the offset to get additional matches from db, then request('GET', '/api/matches', { qs: { self, offset, }, }) .done((matches) => { dispatch(addMatches([{firstName: 'Velvet', lastName: 'Underground', languages: { canTeach: [['English', 'native']], willLearn: [['German', 'advanced']] }, description: 'hi there', photoUrl: 'http://watchmojo.com/uploads/blipthumbs/M-RR-Top10-Velvet-Underground-Songs-480p30_480.jpg'}])); dispatch(incrementOffset(20)); }); }, } ); export default connect(mapStateToProps, mapDispatchToProps)(Matches); " Allow any pymongo 2.x version,"from setuptools import setup, find_packages version = '1.3.5' setup(name='switchboard', version=version, description=""Feature flipper for Pyramid, Pylons, or TurboGears apps."", # http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=[ ""Programming Language :: Python"", ""Topic :: Software Development :: Libraries :: Python Modules"", ], keywords='switches feature flipper pyramid pylons turbogears', author='Kyle Adams', author_email='kadams54@users.noreply.github.com', url='https://github.com/switchboardpy/switchboard/', download_url='https://github.com/switchboardpy/switchboard/releases', license='Apache License', packages=find_packages(exclude=['ez_setup']), include_package_data=True, install_requires=[ 'pymongo >= 2.3, < 3', 'blinker >= 1.2', 'WebOb >= 0.9', 'Mako >= 0.9', 'bottle == 0.12.8', ], zip_safe=False, tests_require=[ 'nose', 'mock', 'paste', 'selenium', 'splinter', ], test_suite='nose.collector', ) ","from setuptools import setup, find_packages version = '1.3.5' setup(name='switchboard', version=version, description=""Feature flipper for Pyramid, Pylons, or TurboGears apps."", # http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=[ ""Programming Language :: Python"", ""Topic :: Software Development :: Libraries :: Python Modules"", ], keywords='switches feature flipper pyramid pylons turbogears', author='Kyle Adams', author_email='kadams54@users.noreply.github.com', url='https://github.com/switchboardpy/switchboard/', download_url='https://github.com/switchboardpy/switchboard/releases', license='Apache License', packages=find_packages(exclude=['ez_setup']), include_package_data=True, install_requires=[ 'pymongo == 2.3', 'blinker >= 1.2', 'WebOb >= 0.9', 'Mako >= 0.9', 'bottle == 0.12.8', ], zip_safe=False, tests_require=[ 'nose', 'mock', 'paste', 'selenium', 'splinter', ], test_suite='nose.collector', ) " Add response limit parameter to the request,"define(['app'], function(app) { return ['$scope', '$timeout', '$http', function($scope, $timeout, $http) { $scope.authors = []; $scope.search = { author: """", limit: 10 }; $scope.listBooks = function (id, event) { console.log(""Go to books of author id "" + id); }; $scope.$watch('search.author', function() { $timeout.cancel($scope.timeout); $scope.timeout = $timeout(function() { if ($scope.search.author) { $http.post('/api/author/search', $scope.search) .success(function(data, status) { $scope.status = status; $scope.authors = data; }) .error(function(data, status) { $scope.authors = []; }); } }, 2000); }); }]; }); ","define(['app'], function(app) { return ['$scope', '$timeout', '$http', function($scope, $timeout, $http) { $scope.authors = []; $scope.search = { author: """" }; $scope.listBooks = function (id, event) { console.log(""Go to books of author id "" + id); }; $scope.$watch('search.author', function() { $timeout.cancel($scope.timeout); $scope.timeout = $timeout(function() { if ($scope.search.author) { $http.post('/api/author/search', { ""author"": $scope.search.author }) .success(function(data, status) { $scope.status = status; $scope.authors = data; }) .error(function(data, status) { $scope.authors = []; }); } }, 2000); }); }]; }); " Set default log level to INFO,"from __future__ import absolute_import from ddsc_incron.celery import celery # Note that logging to a single file from multiple processes is NOT supported. # See: http://docs.python.org/2/howto/logging-cookbook.html # #logging-to-a-single-file-from-multiple-processes # This very much applies to ddsc-incron! # TODO: Consider ConcurrentLogHandler on pypi when this bug is solved? # https://bugzilla.redhat.com/show_bug.cgi?id=858912 BROKER_URL = celery.conf['BROKER_URL'] LOGGING = { 'version': 1, 'formatters': { 'verbose': { 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'verbose', 'level': 'DEBUG', }, 'null': { 'class': 'logging.NullHandler', }, 'rmq': { 'class': 'ddsc_logging.handlers.DDSCHandler', 'level': 'INFO', 'broker_url': BROKER_URL, }, }, 'loggers': { '': { 'handlers': ['null'], 'level': 'INFO', }, }, } try: # Allow each environment to override these settings. from ddsc_incron.localsettings import * # NOQA except ImportError: pass ","from __future__ import absolute_import from ddsc_incron.celery import celery # Note that logging to a single file from multiple processes is NOT supported. # See: http://docs.python.org/2/howto/logging-cookbook.html # #logging-to-a-single-file-from-multiple-processes # This very much applies to ddsc-incron! # TODO: Consider ConcurrentLogHandler on pypi when this bug is solved? # https://bugzilla.redhat.com/show_bug.cgi?id=858912 BROKER_URL = celery.conf['BROKER_URL'] LOGGING = { 'version': 1, 'formatters': { 'verbose': { 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'verbose', 'level': 'DEBUG', }, 'null': { 'class': 'logging.NullHandler', }, 'rmq': { 'class': 'ddsc_logging.handlers.DDSCHandler', 'formatter': 'verbose', 'level': 'DEBUG', 'broker_url': BROKER_URL, }, }, 'loggers': { '': { 'handlers': ['null'], 'level': 'DEBUG', }, }, } try: # Allow each environment to override these settings. from ddsc_incron.localsettings import * # NOQA except ImportError: pass " Replace form type names with FQCN.,"<?php /** * @author Igor Nikolaev <igor.sv.n@gmail.com> * @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\UserBundle\Configuration; use Darvin\ConfigBundle\Configuration\AbstractConfiguration; use Darvin\ConfigBundle\Parameter\ParameterModel; /** * Configuration * * @method array getNotificationEmails() */ class Configuration extends AbstractConfiguration { /** * {@inheritdoc} */ public function getModel() { return array( new ParameterModel('notification_emails', ParameterModel::TYPE_ARRAY, array(), array( 'form' => array( 'options' => array( 'type' => 'Symfony\\Component\\Form\\Extension\\Core\\Type\\EmailType', 'allow_add' => true, 'allow_delete' => true, ), ), )), ); } /** * {@inheritdoc} */ public function getName() { return 'darvin_user'; } } ","<?php /** * @author Igor Nikolaev <igor.sv.n@gmail.com> * @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\UserBundle\Configuration; use Darvin\ConfigBundle\Configuration\AbstractConfiguration; use Darvin\ConfigBundle\Parameter\ParameterModel; /** * Configuration * * @method array getNotificationEmails() */ class Configuration extends AbstractConfiguration { /** * {@inheritdoc} */ public function getModel() { return array( new ParameterModel('notification_emails', ParameterModel::TYPE_ARRAY, array(), array( 'form' => array( 'options' => array( 'type' => 'email', 'allow_add' => true, 'allow_delete' => true, ), ), )), ); } /** * {@inheritdoc} */ public function getName() { return 'darvin_user'; } } " Fix para modelo de posicioanmento autal,"angular.module('sislegisapp').factory('ReuniaoResource', function($resource, BACKEND) { return $resource(BACKEND + '/reuniaos/:ReuniaoId', { ReuniaoId : '@id' }, { 'queryAll' : { method : 'GET', isArray : true }, 'query' : { method : 'GET', isArray : false }, 'buscarReuniaoPorData' : { url : BACKEND + ""/reuniaos/findByData"", method : 'GET', isArray : true, transformResponse: function(data){ var jsonParse = JSON.parse(data); jsonParse.forEach(function(item, index){ if(item.posicionamentoPreliminar==true){ jsonParse[index].posicionamento.nome = 'Previamente ' + item.posicionamentoAtual.posicionamento.nome; } }); return jsonParse; } }, 'update' : { method : 'PUT' } }); }); ","angular.module('sislegisapp').factory('ReuniaoResource', function($resource, BACKEND) { return $resource(BACKEND + '/reuniaos/:ReuniaoId', { ReuniaoId : '@id' }, { 'queryAll' : { method : 'GET', isArray : true }, 'query' : { method : 'GET', isArray : false }, 'buscarReuniaoPorData' : { url : BACKEND + ""/reuniaos/findByData"", method : 'GET', isArray : true, transformResponse: function(data){ var jsonParse = JSON.parse(data); jsonParse.forEach(function(item, index){ if(item.posicionamentoPreliminar){ jsonParse[index].posicionamento.nome = 'Previamente ' + item.posicionamento.nome; } }); return jsonParse; } }, 'update' : { method : 'PUT' } }); }); " Fix lookup to pass in correct column number,"var fizz_source_map = new sourceMap.SourceMapConsumer(fizzbuzz_map); var test_source_map = new sourceMap.SourceMapConsumer(test_map); var catch_source_map = new sourceMap.SourceMapConsumer(catch_map); var body = document.body; function parseStackTrace(err) { var info; var source_map; if(err.mode === 'trycatch') { info = parseTryCatchStackTrace(err); source_map = catch_source_map; } else { info = err.stack; source_map = test_source_map; if(/fizzbuzz/.test(info.filename)) { source_map = fizz_source_map; } } var orig = source_map.originalPositionFor({ line: info.line, column: info.column }); orig.mode = err.mode; body.innerHTML += '<div class=""error""><pre>' + JSON.stringify(orig, null, 4); } function parseTryCatchStackTrace(err) { var lines = err.stack.split('\n'), stack; stack = lines[1].split(':').reverse().splice(0, 2); return { column: stack[0], line: stack[1] }; } window.onerror = function(msg, filename, lineno, colno, err) { var error = { err: err, stack: { message: msg, line: lineno, column: colno, filename: filename }, mode: 'onerror' }; parseStackTrace(error); };","var fizz_source_map = new sourceMap.SourceMapConsumer(fizzbuzz_map); var test_source_map = new sourceMap.SourceMapConsumer(test_map); var catch_source_map = new sourceMap.SourceMapConsumer(catch_map); var body = document.body; function parseStackTrace(err) { var info; var source_map; if(err.mode === 'trycatch') { info = parseTryCatchStackTrace(err); source_map = catch_source_map; } else { info = err.stack; source_map = test_source_map; if(/fizzbuzz/.test(info.filename)) { source_map = fizz_source_map; } } var orig = source_map.originalPositionFor({ line: info.line, column: info.column }); orig.mode = err.mode; body.innerHTML += '<div class=""error""><pre>' + JSON.stringify(orig, null, 4); } function parseTryCatchStackTrace(err) { var lines = err.stack.split('\n'), stack; stack = lines[1].split(':').reverse().splice(0, 2); return { column: 0, line: stack[1] }; } window.onerror = function(msg, filename, lineno, colno, err) { var error = { err: err, stack: { message: msg, line: lineno, column: colno, filename: filename }, mode: 'onerror' }; parseStackTrace(error); };" Update mm control for new style,"wax = wax || {}; wax.mm = wax.mm || {}; wax.mm.interaction = function() { var dirty = false, _grid; function grid() { var zoomLayer = map.getLayerAt(0) .levels[Math.round(map.getZoom())]; if (!dirty && _grid !== undefined && _grid.length) { return _grid; } else { _grid = (function(t) { var o = []; for (var key in t) { if (t[key].parentNode === zoomLayer) { var offset = wax.u.offset(t[key]); o.push([ offset.top, offset.left, t[key] ]); } } return o; })(map.getLayerAt(0).tiles); return _grid; } } function attach(x) { if (!arguments.length) return map; map = x; function setdirty() { dirty = true; } var clearingEvents = ['zoomed', 'panned', 'centered', 'extentset', 'resized', 'drawn']; for (var i = 0; i < clearingEvents.length; i++) { map.addCallback(clearingEvents[i], setdirty); } } return wax.interaction() .attach(attach) .parent(function() { return map.parent; }) .grid(grid); }; ","wax = wax || {}; wax.mm = wax.mm || {}; wax.mm.interaction = function() { var dirty = false, _grid; function grid() { var zoomLayer = map.getLayerAt(0) .levels[Math.round(map.getZoom())]; if (!dirty && _grid !== undefined && _grid.length) { return _grid; } else { _grid = (function(t) { var o = []; for (var key in t) { if (t[key].parentNode === zoomLayer) { var offset = wax.u.offset(t[key]); o.push([ offset.top, offset.left, t[key] ]); } } return o; })(map.getLayerAt(0).tiles); return _grid; } } function attach(x) { if (!arguments.length) return map; map = x; function setdirty() { dirty = true; } var clearingEvents = ['zoomed', 'panned', 'centered', 'extentset', 'resized', 'drawn']; for (var i = 0; i < clearingEvents.length; i++) { map.addCallback(clearingEvents[i], setdirty); } } return wax.interaction() .attach(attach) .grid(grid); }; " Set correct filesystem mount point / namespace if plugin is called,"<?php namespace Bolt\Filesystem\Plugin; use Bolt\Filesystem\Filesystem; use Bolt\Filesystem\FilesystemInterface; use Bolt\Filesystem\PluginInterface; use Bolt\Filesystem\MountPointAwareInterface; use Silex\Application; abstract class AdapterPlugin implements PluginInterface { /** @var FilesystemInterface */ protected $filesystem; /** @var string */ protected $namespace; /** @var Application */ protected $app; public function __construct(Application $app, $namespace = 'files') { $this->app = $app; $this->namespace = $namespace === 'default' ? 'files' : $namespace; } public function setFilesystem(FilesystemInterface $filesystem) { $this->filesystem = $filesystem; if ($this->filesystem instanceof MountPointAwareInterface) { $this->namespace = $this->filesystem->getMountPoint(); } } public function getDefault() { return false; } public function handle() { $args = func_get_args(); $method = 'get' . $this->adapterType() . ucfirst($this->getMethod()); if (method_exists($this, $method)) { return call_user_func_array([$this, $method], $args); } return $this->getDefault(); } protected function adapterType() { if ($this->filesystem instanceof Filesystem) { $reflect = new \ReflectionClass($this->filesystem->getAdapter()); return $reflect->getShortName(); } return 'Unknown'; } } ","<?php namespace Bolt\Filesystem\Plugin; use Bolt\Filesystem\Filesystem; use Bolt\Filesystem\FilesystemInterface; use Bolt\Filesystem\PluginInterface; use Silex\Application; abstract class AdapterPlugin implements PluginInterface { /** @var FilesystemInterface */ protected $filesystem; /** @var string */ protected $namespace; /** @var Application */ protected $app; public function __construct(Application $app, $namespace = 'files') { $this->app = $app; $this->namespace = $namespace === 'default' ? 'files' : $namespace; } public function setFilesystem(FilesystemInterface $filesystem) { $this->filesystem = $filesystem; } public function getDefault() { return false; } public function handle() { $args = func_get_args(); $method = 'get' . $this->adapterType() . ucfirst($this->getMethod()); if (method_exists($this, $method)) { return call_user_func_array([$this, $method], $args); } return $this->getDefault(); } protected function adapterType() { if ($this->filesystem instanceof Filesystem) { $reflect = new \ReflectionClass($this->filesystem->getAdapter()); return $reflect->getShortName(); } return 'Unknown'; } } " Change variable names to reduce confusion,"from exceptions import AssertionError from django.core.exceptions import ValidationError from django.test import TestCase from django.test.client import Client from cyder.core.ctnr.models import Ctnr class CyTestMixin(object): """""" Mixin for all tests. """""" def _pre_setup(self): super(TestCase, self)._pre_setup() # Add ctnrs to session. session = self.client.session session['ctnr'] = Ctnr.objects.get(id=2) session['ctnrs'] = list(Ctnr.objects.all()) session.save() def assertObjectsConflict(self, obj_create_list): pairs = [(a,b) for a in obj_create_list for b in obj_create_list if a != b] for first, second in pairs: x = first() try: second() except ValidationError: pass else: raise AssertionError( ""'{}' and '{}' do not conflict"".format(first.name, second.name)) x.delete() def assertObjectsDontConflict(self, obj_create_list): pairs = [(a,b) for a in obj_create_list for b in obj_create_list if a != b] for first, second in pairs: x = first() y = second() y.delete() x.delete() class TestCase(TestCase, CyTestMixin): """""" Base class for all tests. """""" client_class = Client fixtures = ['core/users'] ","from exceptions import AssertionError from django.core.exceptions import ValidationError from django.test import TestCase from django.test.client import Client from cyder.core.ctnr.models import Ctnr class CyTestMixin(object): """""" Mixin for all tests. """""" def _pre_setup(self): super(TestCase, self)._pre_setup() # Add ctnrs to session. session = self.client.session session['ctnr'] = Ctnr.objects.get(id=2) session['ctnrs'] = list(Ctnr.objects.all()) session.save() def assertObjectsConflict(self, obj_create_list): pairs = [(x,y) for x in obj_create_list for y in obj_create_list if x != y] for first, second in pairs: x = first() try: second() except ValidationError: pass else: raise AssertionError( ""'{}' and '{}' do not conflict"".format(first.name, second.name)) x.delete() def assertObjectsDontConflict(self, obj_create_list): pairs = [(x,y) for x in obj_create_list for y in obj_create_list if x != y] for first, second in pairs: x = first() y = second() y.delete() x.delete() class TestCase(TestCase, CyTestMixin): """""" Base class for all tests. """""" client_class = Client fixtures = ['core/users'] " Make blog posts table more responsive,"import {personEntityName} from ""./person"" export const blogPostEntityName = ""blogPosts""; export default (nga) => { const personEntity = nga.entity(personEntityName); const entity = nga.entity(blogPostEntityName); entity.listView().fields([ nga.field(""title"") .isDetailLink(true), nga.field(""author"", ""reference"") .targetEntity(personEntity) .targetField(nga.field(""name"")), nga.field(""readers"", ""reference_many"") .targetEntity(personEntity) .targetField(nga.field(""name"")) .cssClasses(""hidden-xs hidden-sm"") ]); entity.creationView().fields([ nga.field(""title"") .validation({required: true}), nga.field(""content"", ""wysiwyg""), nga.field(""author"", ""reference"") .targetEntity(personEntity) .targetField(nga.field(""name"")) .sortField(""name"") .sortDir(""DESC"") .validation({required: true}) .remoteComplete(true, { refreshDelay: 200, searchQuery(search){ return {search} } }), nga.field(""readers"", ""reference_many"") .targetEntity(personEntity) .targetField(nga.field(""name"")) .sortField(""name"") .sortDir(""DESC"") .remoteComplete(true, { refreshDelay: 200, searchQuery(name){ return {name} } }) ]); entity.editionView().fields(entity.creationView().fields()); return entity; }","import {personEntityName} from ""./person"" export const blogPostEntityName = ""blogPosts""; export default (nga) => { const personEntity = nga.entity(personEntityName); const entity = nga.entity(blogPostEntityName); entity.listView().fields([ nga.field(""title"") .isDetailLink(true), nga.field(""author"", ""reference"") .targetEntity(personEntity) .targetField(nga.field(""name"")), nga.field(""readers"", ""reference_many"") .targetEntity(personEntity) .targetField(nga.field(""name"")) ]); entity.creationView().fields([ nga.field(""title"") .validation({required: true}), nga.field(""content"", ""wysiwyg""), nga.field(""author"", ""reference"") .targetEntity(personEntity) .targetField(nga.field(""name"")) .sortField(""name"") .sortDir(""DESC"") .validation({required: true}) .remoteComplete(true, { refreshDelay: 200, searchQuery(search){ return {search} } }), nga.field(""readers"", ""reference_many"") .targetEntity(personEntity) .targetField(nga.field(""name"")) .sortField(""name"") .sortDir(""DESC"") .remoteComplete(true, { refreshDelay: 200, searchQuery(name){ return {name} } }) ]); entity.editionView().fields(entity.creationView().fields()); return entity; }" "Set sails.js migration property to 'alter' We want Sails.js to try to perform migration automatically","/** * Default model configuration * (sails.config.models) * * Unless you override them, the following properties will be included * in each of your models. * * For more info on Sails models, see: * http://sailsjs.org/#!/documentation/concepts/ORM */ module.exports.models = { /*************************************************************************** * * * Your app's default connection. i.e. the name of one of your app's * * connections (see `config/connections.js`) * * * ***************************************************************************/ // connection: 'localDiskDb', /*************************************************************************** * * * How and whether Sails will attempt to automatically rebuild the * * tables/collections/etc. in your schema. * * * * See http://sailsjs.org/#!/documentation/concepts/ORM/model-settings.html * * * ***************************************************************************/ migrate: 'alter' }; ","/** * Default model configuration * (sails.config.models) * * Unless you override them, the following properties will be included * in each of your models. * * For more info on Sails models, see: * http://sailsjs.org/#!/documentation/concepts/ORM */ module.exports.models = { /*************************************************************************** * * * Your app's default connection. i.e. the name of one of your app's * * connections (see `config/connections.js`) * * * ***************************************************************************/ // connection: 'localDiskDb', /*************************************************************************** * * * How and whether Sails will attempt to automatically rebuild the * * tables/collections/etc. in your schema. * * * * See http://sailsjs.org/#!/documentation/concepts/ORM/model-settings.html * * * ***************************************************************************/ // migrate: 'alter' }; " Drop old MySQL versions support that doesn't support json columns,"<?php declare(strict_types=1); use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAttributesTable extends Migration { /** * Run the migrations. * * @return void */ public function up(): void { Schema::create(config('rinvex.attributes.tables.attributes'), function (Blueprint $table) { // Columns $table->increments('id'); $table->string('slug'); $table->json('name'); $table->json('description')->nullable(); $table->mediumInteger('sort_order')->unsigned()->default(0); $table->string('group')->nullable(); $table->string('type'); $table->boolean('is_required')->default(false); $table->boolean('is_collection')->default(false); $table->text('default')->nullable(); $table->timestamps(); // Indexes $table->unique('slug'); }); } /** * Reverse the migrations. * * @return void */ public function down(): void { Schema::dropIfExists(config('rinvex.attributes.tables.attributes')); } } ","<?php declare(strict_types=1); use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAttributesTable extends Migration { /** * Run the migrations. * * @return void */ public function up(): void { Schema::create(config('rinvex.attributes.tables.attributes'), function (Blueprint $table) { // Columns $table->increments('id'); $table->string('slug'); $table->{$this->jsonable()}('name'); $table->{$this->jsonable()}('description')->nullable(); $table->mediumInteger('sort_order')->unsigned()->default(0); $table->string('group')->nullable(); $table->string('type'); $table->boolean('is_required')->default(false); $table->boolean('is_collection')->default(false); $table->text('default')->nullable(); $table->timestamps(); // Indexes $table->unique('slug'); }); } /** * Reverse the migrations. * * @return void */ public function down(): void { Schema::dropIfExists(config('rinvex.attributes.tables.attributes')); } /** * Get jsonable column data type. * * @return string */ protected function jsonable(): string { $driverName = DB::connection()->getPdo()->getAttribute(PDO::ATTR_DRIVER_NAME); $dbVersion = DB::connection()->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION); $isOldVersion = version_compare($dbVersion, '5.7.8', 'lt'); return $driverName === 'mysql' && $isOldVersion ? 'text' : 'json'; } } " Create recorder file if not exist,"from Measurement import Measurement class Recorder(object): def __init__(self, recorderType): self.recorderType = recorderType def record(self, measure: Measurement): None class PrintRecorder(Recorder): def __init__(self, config): Recorder.__init__(self, 'file') self.format = config['format'] def record(self, measure: Measurement): line = self.format.format( device_id=measure.device_id, celsius=measure.get_celsius(), fahrenheit=measure.get_fahrenheit(), timestamp=measure.timestamp) print(line, end='\n') class FileRecorder(Recorder): def __init__(self, config): Recorder.__init__(self, 'file') self.format = config['format'] self.container = config['container'] self.extension = config['extension'] def record(self, measure: Measurement): log_entry = self.format.format( device_id=measure.device_id, celsius=measure.get_celsius(), fahrenheit=measure.get_fahrenheit(), timestamp=measure.timestamp) file_path = self.container + measure.device_id.split('/')[-1] + self.extension f = open(file_path, 'w+') f.writelines([log_entry])","from Measurement import Measurement class Recorder(object): def __init__(self, recorderType): self.recorderType = recorderType def record(self, measure: Measurement): None class PrintRecorder(Recorder): def __init__(self, config): Recorder.__init__(self, 'file') self.format = config['format'] def record(self, measure: Measurement): line = self.format.format( device_id=measure.device_id, celsius=measure.get_celsius(), fahrenheit=measure.get_fahrenheit(), timestamp=measure.timestamp) print(line, end='\n') class FileRecorder(Recorder): def __init__(self, config): Recorder.__init__(self, 'file') self.format = config['format'] self.container = config['container'] self.extension = config['extension'] def record(self, measure: Measurement): log_entry = self.format.format( device_id=measure.device_id, celsius=measure.get_celsius(), fahrenheit=measure.get_fahrenheit(), timestamp=measure.timestamp) file_path = self.container + measure.device_id.split('/')[-1] + self.extension f = open(file_path, 'w') f.writelines([log_entry])" Add publish command to gruntfile,"/*global exports:true, require:true */ module.exports = exports = function(grunt) { 'use strict'; grunt.initConfig({ casper: { }, coffee: { compile: { files: { 'dist/wai.js': 'src/*.coffee' } } }, coffeelint: { options: { }, source: ['src/*.coffee'] }, shell: { publishDocs: { options: { stdout: true }, command: 'rake publish ALLOW_DIRTY=true' } }, uglify: { wai: { files: { 'dist/wai.min.js': ['dist/wai.js'] } } }, watch: { build: { files: ['src/*.coffee'], tasks: ['build'] }, grunt: { files: [ 'Gruntfile.js' ] } } }); require('load-grunt-tasks')(grunt); grunt.registerTask('default', ['build', 'watch']); grunt.registerTask('build', ['coffee', 'uglify']); grunt.registerTask('publish', ['shell']); // grunt.registerTask('server', function() { // grunt.log.writeln('Starting web server at test/server.coffee'); // require('./test/server.coffee').listen(8181); // }); grunt.registerTask('test', ['build', 'coffeelint']); }; ","/*global exports:true, require:true */ module.exports = exports = function(grunt) { 'use strict'; grunt.initConfig({ casper: { }, coffee: { compile: { files: { 'dist/wai.js': 'src/*.coffee' } } }, coffeelint: { options: { }, source: ['src/*.coffee'] }, shell: { listFolders: { options: { stdout: true }, command: 'rake publish ALLOW_DIRTY=true' } }, uglify: { wai: { files: { 'dist/wai.min.js': ['dist/wai.js'] } } }, watch: { build: { files: ['src/*.coffee'], tasks: ['build'] }, grunt: { files: [ 'Gruntfile.js' ] } } }); require('load-grunt-tasks')(grunt); grunt.registerTask('default', ['build', 'watch']); grunt.registerTask('build', ['coffee', 'uglify']); // grunt.registerTask('publish', ['shell']); // grunt.registerTask('server', function() { // grunt.log.writeln('Starting web server at test/server.coffee'); // require('./test/server.coffee').listen(8181); // }); grunt.registerTask('test', ['build', 'coffeelint']); }; " Add tests around ObjectType Meta,"from collections import OrderedDict from unittest import TestCase from graphql.type.definition import GraphQLField, GraphQLObjectType from graphql.type.scalars import GraphQLString from polygraph.types.definitions import PolygraphNonNull from polygraph.types.fields import String, Int from polygraph.types.object_type import ObjectType from polygraph.types.tests.helpers import graphql_objects_equal class ObjectTypeTest(TestCase): def test_simple_object_type(self): class HelloWorldObject(ObjectType): """""" This is a test object """""" first = String(description=""First violin"", nullable=True) second = String(description=""Second fiddle"", nullable=False) third = String(deprecation_reason=""Third is dead"") hello_world = HelloWorldObject() expected = GraphQLObjectType( name=""HelloWorldObject"", description=""This is a test object"", fields=OrderedDict({ ""first"": GraphQLField(GraphQLString, None, None, None, ""First violin""), ""second"": GraphQLField( PolygraphNonNull(GraphQLString), None, None, None, ""Second fiddle""), ""third"": GraphQLField( PolygraphNonNull(GraphQLString), None, None, ""Third is dead"", None), }) ) actual = hello_world.build_definition() self.assertTrue(graphql_objects_equal(expected, actual)) def test_object_type_meta(self): class MetaObject(ObjectType): """""" This docstring is _not_ the description """""" count = Int() class Meta: name = ""Meta"" description = ""Actual meta description is here"" meta = MetaObject() self.assertEqual(meta.description, ""Actual meta description is here"") self.assertEqual(meta.name, ""Meta"") ","from collections import OrderedDict from unittest import TestCase from graphql.type.definition import GraphQLField, GraphQLObjectType from graphql.type.scalars import GraphQLString from polygraph.types.definitions import PolygraphNonNull from polygraph.types.fields import String from polygraph.types.object_type import ObjectType from polygraph.types.tests.helpers import graphql_objects_equal class HelloWorldObject(ObjectType): """""" This is a test object """""" first = String(description=""First violin"", nullable=True) second = String(description=""Second fiddle"", nullable=False) third = String(deprecation_reason=""Third is dead"") class ObjectTypeTest(TestCase): def test_simple_object_type(self): hello_world = HelloWorldObject() expected = GraphQLObjectType( name=""HelloWorldObject"", description=""This is a test object"", fields=OrderedDict({ ""first"": GraphQLField(GraphQLString, None, None, None, ""First violin""), ""second"": GraphQLField( PolygraphNonNull(GraphQLString), None, None, None, ""Second fiddle""), ""third"": GraphQLField( PolygraphNonNull(GraphQLString), None, None, ""Third is dead"", None), }) ) actual = hello_world.build_definition() self.assertTrue(graphql_objects_equal(expected, actual)) " Allow us to limit the amount of returned results,"<?php namespace MindOfMicah\LaravelDatatables; use Illuminate\Http\JsonResponse; class Datatable { protected $model; protected $columns; public function __construct($a) { $this->a = $a; } public function asJsonResponse() { $data = []; $total = $amount_displayed = 0; if ($this->model) { $model_name = $this->model; if ($this->columns) { } $sql = $model_name::query()->select($this->columns ?: '*'); $total = ($sql->count()); $models = $sql->take($this->a->input('length'))->get(); $data = $models->toArray(); $total = $total; $amount_displayed = count($models); } $data = ([ 'aaData'=>$data, 'iTotalRecords'=>$total, 'iTotalDisplayRecords'=>$amount_displayed ]); return new JsonResponse($data, 200); } public function forEloquentModel($model) { $this->model = $model; return $this; } public function pluckColumns($argument1) { $this->columns[] = $argument1; return $this; } } ","<?php namespace MindOfMicah\LaravelDatatables; use Illuminate\Http\JsonResponse; class Datatable { protected $model; protected $columns; public function __construct($a) { $this->a = $a; } public function asJsonResponse() { $data = []; $total = $amount_displayed = 0; if ($this->model) { $model_name = $this->model; if ($this->columns) { } $models = $model_name::select($this->columns?:'*')->get(); $data = $models->toArray(); $total = count($models); $amount_displayed = count($models); } $data = ([ 'aaData'=>$data, 'iTotalRecords'=>$total, 'iTotalDisplayRecords'=>$amount_displayed ]); return new JsonResponse($data, 200); } public function forEloquentModel($model) { $this->model = $model; return $this; } public function pluckColumns($argument1) { $this->columns[] = $argument1; return $this; } } " Add function to list donors and total donations.,"# Charles Robison # 2016.10.16 # Mailroom Lab #!/usr/bin/env python donors = { 'Smith':[100, 125, 100], 'Galloway':[50], 'Williams':[22, 43, 40, 3.25], 'Cruz':[101], 'Maples':[1.50, 225] } donations = {} for k, v in donors.items(): donations[k] = sum(v) def print_report(): print(""This will print a report"") for i in donations: print(i, donations[i]) def send_thanks(): print(""This will write a thank you note"") # here is where triple quoted strings can be helpful msg = """""" What would you like to do? To send a thank you: type ""s"" To print a report: type ""p"" To exit: type ""x"" """""" def main(): """""" run the main interactive loop """""" response = '' # keep asking until the users responds with an 'x' while True: # make sure there is a break if you have infinite loop! print(msg) response = input(""==> "").strip() # strip() in case there are any spaces if response == 'p': print_report() elif response == 's': send_thanks() elif response == 'x': break else: print('please type ""s"", ""p"", or ""x""') if __name__ == ""__main__"": main()","# Charles Robison # 2016.10.16 # Mailroom Lab #!/usr/bin/env python donors = { 'Smith':[100, 125, 100], 'Galloway':[50], 'Williams':[22, 43, 40, 3.25], 'Cruz':[101], 'Maples':[1.50, 225] } def print_report(): print(""This will print a report"") for i in donors.values(): print(sum(i)) def send_thanks(): print(""This will write a thank you note"") # here is where triple quoted strings can be helpful msg = """""" What would you like to do? To send a thank you: type ""s"" To print a report: type ""p"" To exit: type ""x"" """""" def main(): """""" run the main interactive loop """""" response = '' # keep asking until the users responds with an 'x' while True: # make sure there is a break if you have infinite loop! print(msg) response = input(""==> "").strip() # strip() in case there are any spaces if response == 'p': print_report() elif response == 's': send_thanks() elif response == 'x': break else: print('please type ""s"", ""p"", or ""x""') if __name__ == ""__main__"": main()" Add system status to /status endpoint,"<?php /* * This file is part of Cachet. * * (c) Alt Three Services Limited * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace CachetHQ\Cachet\Http\Controllers\Api; use CachetHQ\Cachet\Integrations\Contracts\System; use CachetHQ\Cachet\Integrations\Releases; /** * This is the general api controller. * * @author James Brooks <james@bluebaytravel.co.uk> */ class GeneralController extends AbstractApiController { /** * Ping endpoint allows API consumers to check the version. * * @return \Illuminate\Http\JsonResponse */ public function ping() { return $this->item('Pong!'); } /** * Endpoint to show the Cachet version. * * @return \Illuminate\Http\JsonResponse */ public function version() { $latest = app(Releases::class)->latest(); return $this->setMetaData([ 'on_latest' => version_compare(CACHET_VERSION, $latest['tag_name']) === 1, 'latest' => $latest, ])->item(CACHET_VERSION); } /** * Get the system status message. * * @return \Illuminate\Http\JsonResponse */ public function status() { $system = app()->make(System::class)->getStatus(); return $this->item([ 'status' => $system['system_status'], 'message' => $system['system_message'] ]); } } ","<?php /* * This file is part of Cachet. * * (c) Alt Three Services Limited * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace CachetHQ\Cachet\Http\Controllers\Api; use CachetHQ\Cachet\Integrations\Contracts\System; use CachetHQ\Cachet\Integrations\Releases; /** * This is the general api controller. * * @author James Brooks <james@bluebaytravel.co.uk> */ class GeneralController extends AbstractApiController { /** * Ping endpoint allows API consumers to check the version. * * @return \Illuminate\Http\JsonResponse */ public function ping() { return $this->item('Pong!'); } /** * Endpoint to show the Cachet version. * * @return \Illuminate\Http\JsonResponse */ public function version() { $latest = app(Releases::class)->latest(); return $this->setMetaData([ 'on_latest' => version_compare(CACHET_VERSION, $latest['tag_name']) === 1, 'latest' => $latest, ])->item(CACHET_VERSION); } /** * Get the system status message. * * @return \Illuminate\Http\JsonResponse */ public function status() { $system = app()->make(System::class)->getStatus(); return $this->item($system['system_message']); } } " Update WebsocketHandler and WebsocketSession behavior,"package io.scalecube.gateway.websocket; import io.scalecube.gateway.clientsdk.ClientMessage; import io.scalecube.gateway.clientsdk.ClientSettings; import io.scalecube.gateway.clientsdk.codec.WebsocketGatewayMessageCodec; import io.scalecube.gateway.clientsdk.websocket.WebsocketClientTransport; import io.scalecube.services.codec.DataCodec; import java.time.Duration; import reactor.core.publisher.Mono; import reactor.ipc.netty.resources.LoopResources; public class WebsocketClientTransportTest { public static void main(String[] args) throws InterruptedException { String contentType = ""application/json""; ClientSettings settings = ClientSettings.builder().contentType(contentType).host(""localhost"").port(7070).build(); LoopResources loopResources = LoopResources.create(""worker""); WebsocketClientTransport transport = new WebsocketClientTransport( settings, new WebsocketGatewayMessageCodec(DataCodec.getInstance(contentType)), loopResources); ClientMessage request = ClientMessage.builder().qualifier(""/greeting/one"").header(""sid"", ""1"").build(); Mono.delay(Duration.ofSeconds(3)) .doOnTerminate( () -> { System.err.println(""closing ...""); transport.close().subscribe(); }) .subscribe(); transport.requestResponse(request).subscribe(System.out::println, System.err::println); Thread.currentThread().join(); } } ","package io.scalecube.gateway.websocket; import io.scalecube.gateway.clientsdk.ClientMessage; import io.scalecube.gateway.clientsdk.ClientSettings; import io.scalecube.gateway.clientsdk.codec.WebsocketGatewayMessageCodec; import io.scalecube.gateway.clientsdk.websocket.WebsocketClientTransport; import io.scalecube.services.codec.DataCodec; import java.time.Duration; import reactor.core.publisher.Mono; import reactor.ipc.netty.resources.LoopResources; public class WebsocketClientTransportTest { public static void main(String[] args) { String contentType = ""application/json""; ClientSettings settings = ClientSettings.builder().contentType(contentType).host(""localhost"").port(7070).build(); LoopResources loopResources = LoopResources.create(""worker""); WebsocketClientTransport transport = new WebsocketClientTransport( settings, new WebsocketGatewayMessageCodec(DataCodec.getInstance(contentType)), loopResources); ClientMessage request = ClientMessage.builder().qualifier(""/greeting/one"").build(); Mono.delay(Duration.ofSeconds(10)) .doOnTerminate( () -> { System.err.println(""closing ...""); transport.close().subscribe(); }) .subscribe(); ClientMessage block = transport.requestResponse(request).block(); System.out.println(block); } } " Format duration in downloaded list,"/** * View for viewing downloaded videos. */ export default class DownloadedList { /** * Default constructor for setting the values * * @param {HTMLElement} element - The HTML element to bind/adopt * @param {Array<Object>} [mediaItems=null] - The array containing media items */ constructor(element, mediaItems = null) { this.element = element; this.mediaItems = mediaItems; } /** * Render page. * * The cards should show the program name, episode number and * episode length. */ render() { let html = ` <section> <ul class=""listaus""> `; this.mediaItems.forEach((episode) => { html += ` <li> <span class=""lLeft""> <span class=""lTitle"">${episode.getTitle()}</span>`; if (episode.getDuration() !== ' ') { html += `<span class=""lDur"">Kesto ${episode.getDuration()} min</span>`; } html += `</span> <span class=""lRight""> <a href=""#download/${episode.getId()}/${episode.getMediaId()}""> <i class=""material-icons media-control-buttons arial-label=""Stream"">delete_forever</i> <i class=""material-icons media-control-buttons"" arial-label=""Stream"">play_circle_filled</i> </a> </span> </li> <hr> `; }); html += ` </ul> </section> `; this.element.innerHTML = html; } } ","/** * View for viewing downloaded videos. */ export default class DownloadedList { /** * Default constructor for setting the values * * @param {HTMLElement} element - The HTML element to bind/adopt * @param {Array<Object>} [mediaItems=null] - The array containing media items */ constructor(element, mediaItems = null) { this.element = element; this.mediaItems = mediaItems; } /** * Render page. * * The cards should show the program name, episode number and * episode length. */ render() { let html = ` <section> <ul class=""listaus""> `; this.mediaItems.forEach((episode) => { html += ` <li> <span class=""lLeft""> <span class=""lTitle"">${episode.getTitle()}</span>`; if (episode.getDuration() !== ' ') { html += `<span class=""lDur"">Kesto ${episode.getDuration()}min</span>`; } html += `</span> <span class=""lRight""> <a href=""#download/${episode.getId()}/${episode.getMediaId()}""> <i class=""material-icons media-control-buttons arial-label=""Stream"">delete_forever</i> <i class=""material-icons media-control-buttons"" arial-label=""Stream"">play_circle_filled</i> </a> </span> </li> <hr> `; }); html += ` </ul> </section> `; this.element.innerHTML = html; } } " Add non-breaking space and fix error,"from data_types.hook import Hook from data_types.repository import Repository from data_types.user import User from .base import EventBase class EventWatch(EventBase): def __init__(self, sdk): super(EventWatch, self).__init__(sdk) self.hook = None self.repository = None self.sender = None """""" WatchEvent Triggered when someone stars your repository. https://developer.github.com/v3/activity/events/types/#watchevent """""" async def process(self, payload, chat): """""" Processes Watch event :param payload: JSON object with payload :param chat: current chat object :return: """""" self.sdk.log(""Watch event payload taken {}"".format(payload)) try: self.repository = Repository(payload['repository']) self.sender = User(payload['sender']) except Exception as e: self.sdk.log('Cannot process WatchEvent payload because of {}'.format(e)) await self.send( chat['chat'], '⭐️ <a href=\""{}\"">{}</a> starred <a href=\""{}\"">{}</a> ★ {}'.format( self.sender.html_url, self.sender.login, self.repository.html_url, self.repository.full_name, self.repository.stargazers_count ), 'HTML' ) ","from data_types.hook import Hook from data_types.repository import Repository from data_types.user import User from .base import EventBase class EventWatch(EventBase): def __init__(self, sdk): super(EventWatch, self).__init__(sdk) self.hook = None self.repository = None self.sender = None """""" WatchEvent Triggered when someone stars your repository. https://developer.github.com/v3/activity/events/types/#watchevent """""" async def process(self, payload, chat): """""" Processes Watch event :param payload: JSON object with payload :param chat: current chat object :return: """""" self.sdk.log(""Watch event payload taken {}"".format(payload)) try: self.repository = Repository(payload['repository']) self.sender = User(payload['sender']) except Exception as e: self.sdk.log('Cannot process WatchEvent payload because of {}'.format(e)) await self.send( chat['chat'], '⭐️ <a href=\""{}\"">{}</a> starred <a href=\""{}\"">{}</a> ★ {}'.format( self.sender.html_url, self.sender.login, self.repository.html_url, self.repository.full_name, self.sender.repository.stargazers_count ), 'HTML' ) " Refactor importer slightly to avoid creation problems,"import requests import csv from models import Planet, SolarSystem from django.core.exceptions import ValidationError class ExoplanetsImporter: @staticmethod def run(filename = None): if filename!=None: csv_data = open(filename) else: csv_data = requests.get('http://exoplanets.org/exoplanets.csv') rows = csv.reader(csv_data) headers = {} got_headers = False for row in rows: if got_headers == 0: # Store headers colnum = 0 for col in row: headers[col] = colnum colnum += 1 got_headers = True else: # Find and store system data try: system, created = SolarSystem.objects.get_or_create(name = row[headers['STAR']]) system.temperature = row[headers['TEFF']] or None system.save() except ValidationError: print stardata raise # Find and store planet data try: planet, created = Planet.objects.get_or_create(name = row[headers['NAME']], solar_system = system) planet.radius = row[headers['R']] or None planet.semi_major_axis = row[headers['A']] planet.save() except ValidationError: print planetdata raise ","import requests import csv from models import Planet, SolarSystem from django.core.exceptions import ValidationError class ExoplanetsImporter: @staticmethod def run(filename = None): if filename!=None: csv_data = open(filename) else: csv_data = requests.get('http://exoplanets.org/exoplanets.csv') rows = csv.reader(csv_data) headers = {} got_headers = False for row in rows: if got_headers == 0: # Store headers colnum = 0 for col in row: headers[col] = colnum colnum += 1 got_headers = True else: # Find and store system data stardata = { 'name': row[headers['STAR']], 'temperature': row[headers['TEFF']] or None } try: system, created = SolarSystem.objects.get_or_create(**stardata) except ValidationError: print stardata raise # Find and store planet data planetdata = { 'name': row[headers['NAME']], 'radius': row[headers['R']] or None, #'temperature': row[headers['NAME']], 'semi_major_axis': row[headers['A']], 'solar_system': system } try: planet, created = Planet.objects.get_or_create(**planetdata) except ValidationError: print planetdata raise " Add errorMessage notifcation from backend,"import WebSocketClient from 'websocket.js'; import config from '../config'; import createQueryString from './createQueryString'; import { addNotification } from 'app/actions/NotificationActions'; import { User } from 'app/actions/ActionTypes'; export default function createWebSocketMiddleware() { let socket = null; return store => { const makeSocket = jwt => { if (socket || !jwt) return; const qs = createQueryString({ jwt }); socket = new WebSocketClient(`${config.wsServerUrl}/${qs}`); socket.onmessage = event => { const { type, payload, meta } = JSON.parse(event.data); store.dispatch({ type, payload, meta }); if (meta.errorMessage) { store.dispatch(addNotification({ message: meta.errorMessage })); } }; socket.onopen = () => { store.dispatch({ type: 'WS_CONNECTED' }); }; socket.onclose = () => { store.dispatch({ type: 'WS_CLOSED' }); }; socket.onerror = () => { store.dispatch({ type: 'WS_ERROR' }); }; }; return next => action => { if (action.type === 'REHYDRATED') { makeSocket(store.getState().auth.token); return next(action); } if (action.type === User.LOGIN.SUCCESS) { makeSocket(action.payload.token); return next(action); } if (action.type === User.LOGOUT) { if (socket) { socket.close(); } socket = null; return next(action); } return next(action); }; }; } ","import WebSocketClient from 'websocket.js'; import config from '../config'; import createQueryString from './createQueryString'; import { User } from 'app/actions/ActionTypes'; export default function createWebSocketMiddleware() { let socket = null; return store => { const makeSocket = jwt => { if (socket || !jwt) return; const qs = createQueryString({ jwt }); socket = new WebSocketClient(`${config.wsServerUrl}/${qs}`); socket.onmessage = event => { const { type, payload, meta } = JSON.parse(event.data); store.dispatch({ type, payload, meta }); }; socket.onopen = () => { store.dispatch({ type: 'WS_CONNECTED' }); }; socket.onclose = () => { store.dispatch({ type: 'WS_CLOSED' }); }; socket.onerror = () => { store.dispatch({ type: 'WS_ERROR' }); }; }; return next => action => { if (action.type === 'REHYDRATED') { makeSocket(store.getState().auth.token); return next(action); } if (action.type === User.LOGIN.SUCCESS) { makeSocket(action.payload.token); return next(action); } if (action.type === User.LOGOUT) { if (socket) { socket.close(); } socket = null; return next(action); } return next(action); }; }; } " "Use requiresAtLeastOneElement() instead of cannotBeEmpty() Symfony deprecation https://github.com/symfony/symfony/blob/3.4/src/Symfony/Component/Config/Definition/Builder/ArrayNodeDefinition.php#L428","<?php namespace OpenClassrooms\Bundle\OneSkyBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * @author Romain Kuzniak <romain.kuzniak@openclassrooms.com> */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('openclassrooms_onesky'); $rootNode->children() ->scalarNode('api_key')->isRequired()->cannotBeEmpty()->end() ->scalarNode('api_secret')->isRequired()->cannotBeEmpty()->end() ->scalarNode('project_id')->isRequired()->cannotBeEmpty()->end() ->scalarNode('file_format')->cannotBeEmpty()->defaultValue('xliff')->end() ->scalarNode('source_locale')->cannotBeEmpty()->defaultValue('en')->end() ->arrayNode('locales')->requiresAtLeastOneElement()->cannotBeEmpty()->prototype('scalar')->end()->end() ->arrayNode('file_paths')->requiresAtLeastOneElement()->cannotBeEmpty()->prototype('scalar')->end()->end() ->scalarNode('keep_all_strings')->cannotBeEmpty()->defaultValue(true)->end() ->end(); return $treeBuilder; } } ","<?php namespace OpenClassrooms\Bundle\OneSkyBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * @author Romain Kuzniak <romain.kuzniak@openclassrooms.com> */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('openclassrooms_onesky'); $rootNode->children() ->scalarNode('api_key')->isRequired()->cannotBeEmpty()->end() ->scalarNode('api_secret')->isRequired()->cannotBeEmpty()->end() ->scalarNode('project_id')->isRequired()->cannotBeEmpty()->end() ->scalarNode('file_format')->cannotBeEmpty()->defaultValue('xliff')->end() ->scalarNode('source_locale')->cannotBeEmpty()->defaultValue('en')->end() ->arrayNode('locales')->isRequired()->cannotBeEmpty()->prototype('scalar')->end()->end() ->arrayNode('file_paths')->isRequired()->cannotBeEmpty()->prototype('scalar')->end()->end() ->scalarNode('keep_all_strings')->cannotBeEmpty()->defaultValue(true)->end() ->end(); return $treeBuilder; } } " Update memory object when adding a class,"(function () { var cogClass = function () {}; cogClass.prototype.exec = function (params, request, response) { var oops = this.utils.apiError; var sys = this.sys; if (params.classid) { sys.db.run('INSERT OR REPLACE INTO classes VALUES (?,?,?)',[params.classid,params.groupid,params.name],function(err){ if (err) {return oops(response,err,'classes/addclass(1)')}; sendClasses(); }) } else { var db = this.sys.db; sys.db.run('INSERT INTO classes VALUES (NULL,?,?)',[params.groupid,params.name],function(err){ if (err) {return oops(response,err,'classes/addclass(2)')}; sys.membershipKeys[this.lastID] = {}; sendClasses(); }); } function sendClasses () { sys.db.all('SELECT classID,classes.name,ruleGroupID,ruleGroups.name AS ruleGroupName FROM classes JOIN ruleGroups USING(ruleGroupID) ORDER BY classes.name;',function(err,rows){ if (err||!rows) {return oops(response,err,'classes/addclass(3)')}; response.writeHead(200, {'Content-Type': 'application/json'}); response.end(JSON.stringify(rows)); }); } } exports.cogClass = cogClass; })(); ","(function () { var cogClass = function () {}; cogClass.prototype.exec = function (params, request, response) { var oops = this.utils.apiError; if (params.classid) { var db = this.sys.db; db.run('INSERT OR REPLACE INTO classes VALUES (?,?,?)',[params.classid,params.groupid,params.name],function(err){ if (err) {return oops(response,err,'classes/addclass(1)')}; sendClasses(); }) } else { var db = this.sys.db; db.run('INSERT INTO classes VALUES (NULL,?,?)',[params.groupid,params.name],function(err){ if (err) {return oops(response,err,'classes/addclass(2)')}; sendClasses(); }); } function sendClasses () { db.all('SELECT classID,classes.name,ruleGroupID,ruleGroups.name AS ruleGroupName FROM classes JOIN ruleGroups USING(ruleGroupID) ORDER BY classes.name;',function(err,rows){ if (err||!rows) {return oops(response,err,'classes/addclass(3)')}; response.writeHead(200, {'Content-Type': 'application/json'}); response.end(JSON.stringify(rows)); }); } } exports.cogClass = cogClass; })(); " "Docs: Update mixup between rules in docstring example `requirePaddingNewLinesBeforeExport` was mentioned instead of `disallowPaddingNewLinesBeforeExport`. Closes gh-1317","/** * Disallows newline before module.exports * * Type: `Boolean` * * Value: `true` * * #### Example * * ```js * ""disallowPaddingNewLinesBeforeExport"": true * ``` * * ##### Valid * * ```js * var a = 2; * module.exports = a; * ``` * * ##### Invalid * * ```js * var a = 2; * * module.exports = a; * ``` */ var assert = require('assert'); module.exports = function() {}; module.exports.prototype = { configure: function(value) { assert( value === true, this.getOptionName() + ' option requires a true value or should be removed' ); }, getOptionName: function() { return 'disallowPaddingNewLinesBeforeExport'; }, check: function(file, errors) { file.iterateNodesByType('AssignmentExpression', function(node) { var left = node.left; if (!( left.object && left.object.name === 'module' && left.property && left.property.name === 'exports')) { return; } var firstToken = file.getFirstNodeToken(node); var prevToken = file.getPrevToken(firstToken, {includeComments: true}); errors.assert.linesBetween({ atMost: 1, token: prevToken, nextToken: firstToken, message: 'Unexpected extra newline before export' }); }); } }; ","/** * Disallows newline before module.exports * * Type: `Boolean` * * Value: `true` * * #### Example * * ```js * ""requirePaddingNewLinesBeforeExport"": true * ``` * * ##### Valid * * ```js * var a = 2; * module.exports = a; * ``` * * ##### Invalid * * ```js * var a = 2; * * module.exports = a; * ``` */ var assert = require('assert'); module.exports = function() {}; module.exports.prototype = { configure: function(value) { assert( value === true, this.getOptionName() + ' option requires a true value or should be removed' ); }, getOptionName: function() { return 'disallowPaddingNewLinesBeforeExport'; }, check: function(file, errors) { file.iterateNodesByType('AssignmentExpression', function(node) { var left = node.left; if (!( left.object && left.object.name === 'module' && left.property && left.property.name === 'exports')) { return; } var firstToken = file.getFirstNodeToken(node); var prevToken = file.getPrevToken(firstToken, {includeComments: true}); errors.assert.linesBetween({ atMost: 1, token: prevToken, nextToken: firstToken, message: 'Unexpected extra newline before export' }); }); } }; " Use hash_equals for constant-time string comparison,"<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Crypt; /** * Tools for cryptography */ class Utils { /** * Compare two strings to avoid timing attacks * * C function memcmp() internally used by PHP, exits as soon as a difference * is found in the two buffers. That makes possible of leaking * timing information useful to an attacker attempting to iteratively guess * the unknown string (e.g. password). * The length will leak. * * @param string $expected * @param string $actual * @return bool */ public static function compareStrings($expected, $actual) { $expected = (string) $expected; $actual = (string) $actual; if (function_exists('hash_equals')) { return hash_equals($expected, $actual); } $lenExpected = strlen($expected); $lenActual = strlen($actual); $len = min($lenExpected, $lenActual); $result = 0; for ($i = 0; $i < $len; $i++) { $result |= ord($expected[$i]) ^ ord($actual[$i]); } $result |= $lenExpected ^ $lenActual; return ($result === 0); } } ","<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Crypt; /** * Tools for cryptography */ class Utils { /** * Compare two strings to avoid timing attacks * * C function memcmp() internally used by PHP, exits as soon as a difference * is found in the two buffers. That makes possible of leaking * timing information useful to an attacker attempting to iteratively guess * the unknown string (e.g. password). * * @param string $expected * @param string $actual * @return bool */ public static function compareStrings($expected, $actual) { $expected = (string) $expected; $actual = (string) $actual; $lenExpected = strlen($expected); $lenActual = strlen($actual); $len = min($lenExpected, $lenActual); $result = 0; for ($i = 0; $i < $len; $i++) { $result |= ord($expected[$i]) ^ ord($actual[$i]); } $result |= $lenExpected ^ $lenActual; return ($result === 0); } } " Make prcheck pass without needing cond deps,"import threading # noqa from typing import Callable, Optional # noqa import watchdog.observers # pylint: disable=import-error from watchdog import events # pylint: disable=import-error from chalice.cli.filewatch import FileWatcher, WorkerProcess class WatchdogWorkerProcess(WorkerProcess): """"""Worker that runs the chalice dev server."""""" def _start_file_watcher(self, project_dir): # type: (str) -> None restart_callback = WatchdogRestarter(self._restart_event) watcher = WatchdogFileWatcher() watcher.watch_for_file_changes( project_dir, restart_callback) class WatchdogFileWatcher(FileWatcher): def watch_for_file_changes(self, root_dir, callback): # type: (str, Callable[[], None]) -> None observer = watchdog.observers.Observer() observer.schedule(callback, root_dir, recursive=True) observer.start() class WatchdogRestarter(events.FileSystemEventHandler): def __init__(self, restart_event): # type: (threading.Event) -> None # The reason we're using threading self.restart_event = restart_event def on_any_event(self, event): # type: (events.FileSystemEvent) -> None # If we modify a file we'll get a FileModifiedEvent # as well as a DirectoryModifiedEvent. # We only care about reloading is a file is modified. if event.is_directory: return self() def __call__(self): # type: () -> None self.restart_event.set() ","import threading # noqa from typing import Callable, Optional # noqa import watchdog.observers from watchdog.events import FileSystemEventHandler from watchdog.events import FileSystemEvent # noqa from chalice.cli.filewatch import FileWatcher, WorkerProcess class WatchdogWorkerProcess(WorkerProcess): """"""Worker that runs the chalice dev server."""""" def _start_file_watcher(self, project_dir): # type: (str) -> None restart_callback = WatchdogRestarter(self._restart_event) watcher = WatchdogFileWatcher() watcher.watch_for_file_changes( project_dir, restart_callback) class WatchdogFileWatcher(FileWatcher): def watch_for_file_changes(self, root_dir, callback): # type: (str, Callable[[], None]) -> None observer = watchdog.observers.Observer() observer.schedule(callback, root_dir, recursive=True) observer.start() class WatchdogRestarter(FileSystemEventHandler): def __init__(self, restart_event): # type: (threading.Event) -> None # The reason we're using threading self.restart_event = restart_event def on_any_event(self, event): # type: (FileSystemEvent) -> None # If we modify a file we'll get a FileModifiedEvent # as well as a DirectoryModifiedEvent. # We only care about reloading is a file is modified. if event.is_directory: return self() def __call__(self): # type: () -> None self.restart_event.set() " Check to make sure haunt hasn't started before starting it.,"/** * Event.js * * @description :: TODO: You might write a short summary of how this model works and what it represents here. * @docs :: http://sailsjs.org/#!documentation/models */ module.exports = { autoWatch: false, autosubscribe: [], attributes: { room: {model: 'room', required: true}, container: {type: 'string', required: true}, card: {type: 'string', required: true}, game: {model: 'game', required: true} }, afterDestroy: function (events, cb) { _.each(events, function(event) { for (var stat in Event.cards[event.card].effect) { if (stat === 'relics') { Event.count({card: {'contains': 'relic'}, game: event.game}) .then(function(numRelics) { sails.log.info('relics remaining: ' + numRelics); if (numRelics == 0 && event.game.haunt == undefined) { Game.startHaunt(event.game); } }) .catch(function(err) { sails.log.error(err); }); } } }); cb(); }, cards: sails.config.gameconfig.cards }; ","/** * Event.js * * @description :: TODO: You might write a short summary of how this model works and what it represents here. * @docs :: http://sailsjs.org/#!documentation/models */ module.exports = { autoWatch: false, autosubscribe: [], attributes: { room: {model: 'room', required: true}, container: {type: 'string', required: true}, card: {type: 'string', required: true}, game: {model: 'game', required: true} }, afterDestroy: function (events, cb) { _.each(events, function(event) { for (var stat in Event.cards[event.card].effect) { if (stat === 'relics') { Event.count({card: {'contains': 'relic'}, game: event.game}) .then(function(numRelics) { sails.log.info('relics remaining: ' + numRelics); if (numRelics == 0) { Game.startHaunt(event.game); } }) .catch(function(err) { sails.log.error(err); }); } } }); cb(); }, cards: sails.config.gameconfig.cards }; " Clean up Webpack Dev Server Logs,"const path = require('path'); const webpack = require('webpack'); const buildEntryPoint = entryPoint => { return [ 'react-hot-loader/patch', 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', entryPoint ]; }; const plugins = [ new webpack.optimize.CommonsChunkPlugin({ name: 'commons', filename: 'common.js' }), new webpack.HotModuleReplacementPlugin() ]; module.exports = { entry: { app: buildEntryPoint('./src') }, output: { path: path.join(__dirname, 'dev'), publicPath: '/', filename: '[name].js' }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel', include: path.join(__dirname, 'src') }, { test: /\.css$/, loader: 'style!css' } ] }, resolve: { root: [ path.resolve(__dirname, 'src') ], extensions: ['', '.js', '.jsx'], }, plugins: plugins, devServer: { historyApiFallback: true, contentBase: path.resolve(__dirname, 'dev'), hot: true, inline: true, stats: { assets: true, colors: true, version: false, hash: false, timings: true, chunks: false, chunkModules: false }, port: 3000 }, devtool: 'source-map' }; ","const path = require('path'); const webpack = require('webpack'); const buildEntryPoint = entryPoint => { return [ 'react-hot-loader/patch', 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', entryPoint ]; }; const plugins = [ new webpack.optimize.CommonsChunkPlugin({ name: 'commons', filename: 'common.js' }), new webpack.HotModuleReplacementPlugin() ]; module.exports = { entry: { app: buildEntryPoint('./src') }, output: { path: path.join(__dirname, 'dev'), publicPath: '/', filename: '[name].js' }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel', include: path.join(__dirname, 'src') }, { test: /\.css$/, loader: 'style!css' } ] }, resolve: { root: [ path.resolve(__dirname, 'src') ], extensions: ['', '.js', '.jsx'], }, plugins: plugins, devServer: { historyApiFallback: true, contentBase: path.resolve(__dirname, 'dev'), hot: true, inline: true, stats: { colors: true }, port: 3000 }, devtool: 'source-map' }; " "Return animation, new default easing","import React from 'react'; import PropTypes from 'prop-types'; import { Animated, AppState, Easing, View, ViewPropTypes } from 'react-native'; import CircularProgress from './CircularProgress'; const AnimatedProgress = Animated.createAnimatedComponent(CircularProgress); export default class AnimatedCircularProgress extends React.PureComponent { constructor(props) { super(props); this.state = { fillAnimation: new Animated.Value(props.prefill) } } componentDidMount() { this.animate(); } componentDidUpdate(prevProps) { if (prevProps.fill !== this.props.fill) { this.animate(); } } animate(toVal, dur, ease) { const toValue = toVal || this.props.fill; const duration = dur || this.props.duration; const easing = ease || this.props.easing; return Animated.timing(this.state.fillAnimation, { toValue, easing, duration, }).start(this.props.onAnimationComplete); } render() { const { fill, prefill, ...other } = this.props; return ( <AnimatedProgress {...other} fill={this.state.fillAnimation} /> ); } } AnimatedCircularProgress.propTypes = { ...CircularProgress.propTypes, prefill: PropTypes.number, duration: PropTypes.number, easing: PropTypes.func, onAnimationComplete: PropTypes.func, }; AnimatedCircularProgress.defaultProps = { duration: 500, easing: Easing.out(Easing.ease), prefill: 0, }; ","import React from 'react'; import PropTypes from 'prop-types'; import { Animated, AppState, Easing, View, ViewPropTypes } from 'react-native'; import CircularProgress from './CircularProgress'; const AnimatedProgress = Animated.createAnimatedComponent(CircularProgress); export default class AnimatedCircularProgress extends React.PureComponent { constructor(props) { super(props); this.state = { fillAnimation: new Animated.Value(props.prefill) } } componentDidMount() { this.animate(); } componentDidUpdate(prevProps) { if (prevProps.fill !== this.props.fill) { this.animate(); } } animate(toVal, dur, ease) { const toValue = toVal || this.props.fill; const duration = dur || this.props.duration; const easing = ease || this.props.easing; Animated.timing(this.state.fillAnimation, { toValue, easing, duration, }).start(this.props.onAnimationComplete); } render() { const { fill, prefill, ...other } = this.props; return ( <AnimatedProgress {...other} fill={this.state.fillAnimation} /> ); } } AnimatedCircularProgress.propTypes = { ...CircularProgress.propTypes, prefill: PropTypes.number, duration: PropTypes.number, easing: PropTypes.func, onAnimationComplete: PropTypes.func, }; AnimatedCircularProgress.defaultProps = { duration: 500, easing: Easing.elastic(1), prefill: 0, }; " ENN: Make watermark more resilient to err on import.,"from __future__ import (absolute_import, division, print_function, unicode_literals) from collections import OrderedDict import importlib import sys import six def watermark(): """""" Give the version of each of the dependencies -- useful for bug reports. Returns ------- result : dict mapping the name of each package to its version string or, if an optional dependency is not installed, None """""" packages = ['six', 'numpy', 'scipy', 'matplotlib', 'pandas', 'pims', 'pyyaml', 'metadatastore', 'filestore', 'channelarchiver', 'bubblegum'] result = OrderedDict() for package_name in packages: try: package = importlib.import_module(package_name) version = package.__version__ except ImportError: result[package_name] = None except Exception as err: version = ""FAILED TO DETECT: {0}"".format(err) result[package_name] = version # enaml provides its version differently try: import enaml from enaml.version import version_info version = _make_version_string(version_info) except ImportError: version = None except Exception as err: version = ""FAILED TO DETECT: {0}"".format(err) result['enaml'] = version # ...as does Python version_info = sys.version_info result['python'] = _make_version_string(version_info) return result def _make_version_string(version_info): version_string = '.'.join(map(str, [version_info[0], version_info[1], version_info[2]])) return version_string ","from __future__ import (absolute_import, division, print_function, unicode_literals) from collections import OrderedDict import importlib import sys import six def watermark(): """""" Give the version of each of the dependencies -- useful for bug reports. Returns ------- result : dict mapping the name of each package to its version string or, if an optional dependency is not installed, None """""" packages = ['six', 'numpy', 'scipy', 'matplotlib', 'pandas', 'pims', 'pyyaml', 'metadatastore', 'filestore', 'channelarchiver', 'bubblegum'] result = OrderedDict() for package_name in packages: try: package = importlib.import_module(package_name) except ImportError: result[package_name] = None else: try: version = package.__version__ except AttributeError as err: version = ""FAILED TO DETECT: {0}"".format(err) result[package_name] = version # enaml provides its version differently try: import enaml except ImportError: result['enaml'] = None else: from enaml.version import version_info result['enaml'] = _make_version_string(version_info) # ...as does Python version_info = sys.version_info result['python'] = _make_version_string(version_info) return result def _make_version_string(version_info): version_string = '.'.join(map(str, [version_info[0], version_info[1], version_info[2]])) return version_string " "Resolve `SyntaxWarning: ""is"" with a literal`","# coding: utf-8 from collections import OrderedDict def _convert_sheets_to_lists(content): cols = OrderedDict() if not content or len(content) == 0: return [], None if isinstance(content[0], list): cols.update(OrderedDict.fromkeys(content[0])) for row in content: if isinstance(row, dict): cols.update(OrderedDict.fromkeys(row.keys())) cols = cols.keys() out_content = [] _valid = False for row in content: out_row = [] for col in cols: _val = row.get(col, '') if _val is None: _val = '' out_row.append(_val) if len(out_row) > 0: _valid = True out_content.append(out_row) return cols, out_content if _valid else None def ss_structure_to_mdtable(content): """""" receives a dict or OrderedDict with arrays of arrays representing a spreadsheet, and returns a markdown document with tables """""" import tabulate out_sheets = OrderedDict() output = [] def cell_to_str(cell): return '' if cell is None else str(cell) for (sheet_name, contents) in content.items(): out_sheets[sheet_name] = output (headers, content) = _convert_sheets_to_lists(contents) if content: output.append('#{}'.format(sheet_name)) output.append(tabulate.tabulate(content, headers=headers, tablefmt=""orgtbl"")) return '\n\n'.join(output) ","# coding: utf-8 from collections import OrderedDict def _convert_sheets_to_lists(content): cols = OrderedDict() if not content or len(content) is 0: return [], None if isinstance(content[0], list): cols.update(OrderedDict.fromkeys(content[0])) for row in content: if isinstance(row, dict): cols.update(OrderedDict.fromkeys(row.keys())) cols = cols.keys() out_content = [] _valid = False for row in content: out_row = [] for col in cols: _val = row.get(col, '') if _val is None: _val = '' out_row.append(_val) if len(out_row) > 0: _valid = True out_content.append(out_row) return cols, out_content if _valid else None def ss_structure_to_mdtable(content): """""" receives a dict or OrderedDict with arrays of arrays representing a spreadsheet, and returns a markdown document with tables """""" import tabulate out_sheets = OrderedDict() output = [] def cell_to_str(cell): return '' if cell is None else str(cell) for (sheet_name, contents) in content.items(): out_sheets[sheet_name] = output (headers, content) = _convert_sheets_to_lists(contents) if content: output.append('#{}'.format(sheet_name)) output.append(tabulate.tabulate(content, headers=headers, tablefmt=""orgtbl"")) return '\n\n'.join(output) " Add redirect to /admin/ on Admin app w/ empty URL,"from django.conf.urls import include, url, patterns from django.contrib import admin from django.views.generic import RedirectView from settings import ADMIN_BASE from . import views base_pattern = '^{}'.format(ADMIN_BASE) urlpatterns = [ ### ADMIN ### url(base_pattern, include(patterns('', url(r'^$', views.home, name='home'), url(r'^django_admin/', include(admin.site.urls)), url(r'^spam/', include('admin.spam.urls', namespace='spam')), url(r'^auth/', include('admin.common_auth.urls', namespace='auth')), url(r'^prereg/', include('admin.pre_reg.urls', namespace='pre_reg')), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.password_reset_confirm_custom, name='password_reset_confirm'), url(r'^reset/done/$', views.password_reset_done, name='password_reset_complete'), ) ) ), url(r'^$', RedirectView.as_view(url='/admin/')), ] ","from django.conf.urls import include, url, patterns from django.contrib import admin from settings import ADMIN_BASE from . import views base_pattern = '^{}'.format(ADMIN_BASE) urlpatterns = [ ### ADMIN ### url(base_pattern, include(patterns('', url(r'^$', views.home, name='home'), url(r'^django_admin/', include(admin.site.urls)), url(r'^spam/', include('admin.spam.urls', namespace='spam')), url(r'^auth/', include('admin.common_auth.urls', namespace='auth')), url(r'^prereg/', include('admin.pre_reg.urls', namespace='pre_reg')), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.password_reset_confirm_custom, name='password_reset_confirm'), url(r'^reset/done/$', views.password_reset_done, name='password_reset_complete'), ) ) ) ] " Refresh all views when invoking move action,"package com.yuyakaido.android.cardstackview.internal; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import com.yuyakaido.android.cardstackview.CardStackLayoutManager; public class CardStackDataObserver extends RecyclerView.AdapterDataObserver { private final RecyclerView recyclerView; public CardStackDataObserver(RecyclerView recyclerView) { this.recyclerView = recyclerView; } @Override public void onChanged() { CardStackLayoutManager manager = getCardStackLayoutManager(); manager.setTopPosition(0); } @Override public void onItemRangeChanged(int positionStart, int itemCount) { // Do nothing } @Override public void onItemRangeChanged(int positionStart, int itemCount, @Nullable Object payload) { // Do nothing } @Override public void onItemRangeInserted(int positionStart, int itemCount) { // Do nothing } @Override public void onItemRangeRemoved(int positionStart, int itemCount) { CardStackLayoutManager manager = getCardStackLayoutManager(); if (positionStart == 0) { manager.setTopPosition(0); } manager.removeAllViews(); } @Override public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) { CardStackLayoutManager manager = getCardStackLayoutManager(); manager.removeAllViews(); } private CardStackLayoutManager getCardStackLayoutManager() { RecyclerView.LayoutManager manager = recyclerView.getLayoutManager(); if (manager instanceof CardStackLayoutManager) { return (CardStackLayoutManager) manager; } throw new IllegalStateException(""CardStackView must be set CardStackLayoutManager.""); } } ","package com.yuyakaido.android.cardstackview.internal; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import com.yuyakaido.android.cardstackview.CardStackLayoutManager; public class CardStackDataObserver extends RecyclerView.AdapterDataObserver { private final RecyclerView recyclerView; public CardStackDataObserver(RecyclerView recyclerView) { this.recyclerView = recyclerView; } @Override public void onChanged() { CardStackLayoutManager manager = getCardStackLayoutManager(); manager.setTopPosition(0); } @Override public void onItemRangeChanged(int positionStart, int itemCount) { // Do nothing } @Override public void onItemRangeChanged(int positionStart, int itemCount, @Nullable Object payload) { // Do nothing } @Override public void onItemRangeInserted(int positionStart, int itemCount) { // Do nothing } @Override public void onItemRangeRemoved(int positionStart, int itemCount) { CardStackLayoutManager manager = getCardStackLayoutManager(); if (positionStart == 0) { manager.setTopPosition(0); } manager.removeAllViews(); } @Override public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) { // Do nothing } private CardStackLayoutManager getCardStackLayoutManager() { RecyclerView.LayoutManager manager = recyclerView.getLayoutManager(); if (manager instanceof CardStackLayoutManager) { return (CardStackLayoutManager) manager; } throw new IllegalStateException(""CardStackView must be set CardStackLayoutManager.""); } } " Add TransactionId to responses. Fix error_no and error_desc variables,"<?php require_once('../../lib/merchant.php'); require_once('initialize_gateway.php'); try { $response = $gateway->authenticate( array( 'transaction_id' => $_SESSION['transaction_id'], 'payload' => $_POST['PaRes'] )); if ( $response->success() ) { ?> <table border=""1"" cellspacing=""4"" cellpadding=""4""> <thead> <tr> <th>PAResStatus</th> <th>SignatureVerification</th> <th>TransactionId</th> <th>EciFlag</th> <th>Xid</th> <th>Cavv</th> <th>ErrorNo</th> <th>ErrorDesc</th> </tr> </thead> <tbody> <tr> <td><?php echo $response->pares_status ?></td> <td><?php echo $response->signature_verification ?></td> <td><?php echo $_SESSION['transaction_id'] ?></td> <td><?php echo $response->eci_flag ?></td> <td><?php echo $response->xid ?></td> <td><?php echo $response->cavv ?></td> <td><?php echo $response->error_no ?></td> <td<?php echo $response->error_desc ?></td> </tr> </tbody> </table> <?php } else { echo ""<p>{$response->message()}</p>""; } } catch (Exception $exc) { echo $exc->getMessage(); } ?> <p><a href=""index.php"">Return to test page</a></p> ","<?php require_once('../../lib/merchant.php'); require_once('initialize_gateway.php'); try { $response = $gateway->authenticate( array( 'transaction_id' => $_SESSION['transaction_id'], 'payload' => $_POST['PaRes'] )); if ( $response->success() ) { ?> <table border=""1"" cellspacing=""4"" cellpadding=""4""> <thead> <tr> <th>PAResStatus</th> <th>SignatureVerification</th> <th>EciFlag</th> <th>Xid</th> <th>Cavv</th> <th>ErrorNo</th> <th>ErrorDesc</th> </tr> </thead> <tbody> <tr> <td><?php echo $response->pares_status ?></td> <td><?php echo $response->signature_verification ?></td> <td><?php echo $response->eci_flag ?></td> <td><?php echo $response->xid ?></td> <td><?php echo $response->Cavv ?></td> <td><?php echo $response->ErrorNo ?></td> <td<?php echo $response->ErrorDesc ?></td> </tr> </tbody> </table> <?php } else { echo ""<p>{$response->message()}</p>""; } } catch (Exception $exc) { echo $exc->getMessage(); } ?> <p><a href=""index.php"">Return to test page</a></p> " Use `internetarchive.search()` function rather than `internetarchive.Search` class.,"""""""Search the Internet Archive using the Archive.org Advanced Search API <https://archive.org/advancedsearch.php#raw>. usage: ia search [--help] <query>... [options...] options: -h, --help -p, --parameters=<key:value>... Parameters to send with your query. -s, --sort=<field:order>... Sort search results by specified fields. <order> can be either ""asc"" for ascending and ""desc"" for descending. -f, --field=<field>... Metadata fields to return. """""" from docopt import docopt import sys from internetarchive import search # main() #_________________________________________________________________________________________ def main(argv): args = docopt(__doc__, argv=argv) params = dict(p.split(':') for p in args['--parameters']) if args['--sort']: for i, field in enumerate(args['--sort']): key = 'sort[{0}]'.format(i) params[key] = field.strip().replace(':', ' ') fields = ['identifier'] + args['--field'] query = ' '.join(args['<query>']) search_resp = search(query, fields=fields, params=params) for result in search_resp.results(): output = '\t'.join([result[f] for f in fields]).encode('utf-8') sys.stdout.write(output + '\n') sys.exit(0) ","""""""Search the Internet Archive using the Archive.org Advanced Search API <https://archive.org/advancedsearch.php#raw>. usage: ia search [--help] <query>... [options...] options: -h, --help -p, --parameters=<key:value>... Parameters to send with your query. -s, --sort=<field:order>... Sort search results by specified fields. <order> can be either ""asc"" for ascending and ""desc"" for descending. -f, --field=<field>... Metadata fields to return. """""" from docopt import docopt import sys import internetarchive # main() #_________________________________________________________________________________________ def main(argv): args = docopt(__doc__, argv=argv) params = dict(p.split(':') for p in args['--parameters']) if args['--sort']: for i, field in enumerate(args['--sort']): key = 'sort[{0}]'.format(i) params[key] = field.strip().replace(':', ' ') fields = ['identifier'] + args['--field'] query = ' '.join(args['<query>']) search = internetarchive.Search(query, fields=fields, params=params) for result in search.results: output = '\t'.join([result[f] for f in fields]).encode('utf-8') sys.stdout.write(output + '\n') sys.exit(0) " "Return mailbox object, not name, for getMailboxes()","<?php namespace Ddeboer\Imap; /** * A connection to an IMAP server that is authenticated for a user */ class Connection { protected $server; protected $resource; protected $mailboxes; protected $mailboxNames; public function __construct($resource, $server) { if (!is_resource($resource)) { throw new \InvalidArgumentException('$resource must be a resource'); } $this->resource = $resource; $this->server = $server; } /** * Get a list of mailboxes (also known as folders) * * @return array */ public function getMailboxes() { if (null === $this->mailboxes) { foreach ($this->getMailboxNames() as $mailboxName) { $this->mailboxes[] = $this->getMailbox($mailboxName); } } return $this->mailboxes; } public function getMailbox($name) { return new Mailbox($this->server . $name, $this->resource); } /** * Count number of messages not in any mailbox * * @return int */ public function count() { return \imap_num_msg($this->resource); } protected function getMailboxNames() { if (null === $this->mailboxNames) { $mailboxes = \imap_getmailboxes($this->resource, $this->server, '*'); foreach ($mailboxes as $mailbox) { $this->mailboxNames[] = str_replace($this->server, '', $mailbox->name); } } return $this->mailboxNames; } }","<?php namespace Ddeboer\Imap; /** * A connection to an IMAP server that is authenticated for a user */ class Connection { protected $server; protected $resource; protected $mailboxes; public function __construct($resource, $server) { if (!is_resource($resource)) { throw new \InvalidArgumentException('$resource must be a resource'); } $this->resource = $resource; $this->server = $server; } /** * Get a list of mailboxes * * @return array */ public function getMailboxes() { if (null === $this->mailboxes) { $mailboxes = \imap_getmailboxes($this->resource, $this->server, '*'); foreach ($mailboxes as $mailbox) { $this->mailboxes[] = str_replace($this->server, '', $mailbox->name); } } return $this->mailboxes; } public function getMailbox($name) { foreach ($this->getMailboxes() as $mailbox) { if (strcasecmp($name, $mailbox) === 0) { if (false === \imap_reopen($this->resource, $this->server . $mailbox)) { throw new \Exception('Could not open mailbox ' . $mailbox); } return new Mailbox($mailbox, $this->resource); } } throw new \InvalidArgumentException('Mailbox ' . $name . ' not found'); } public function count() { return \imap_num_msg($this->resource); } }" Fix message sorting in renderer having issues with varying message key lengths,"var STATE = (function(){ var FILE; var MSGS; var selectedChannel; return { uploadFile: function(file){ FILE = file; MSGS = null; }, getChannelList: function(){ var channels = FILE.getChannels(); return Object.keys(channels).map(key => ({ // reserve.txt id: key, name: channels[key].name, server: FILE.getServer(channels[key].server), msgcount: FILE.getMessageCount(key) })); }, getChannelName: function(channel){ return FILE.getChannelById(channel).name; }, getUserName: function(user){ return FILE.getUserById(user).name; }, selectChannel: function(channel){ selectedChannel = channel; MSGS = Object.keys(FILE.getMessages(channel)).sort((key1, key2) => { if (key1.length === key2.length){ return key1 > key2 ? 1 : key1 < key2 ? -1 : 0; } else{ return key1.length > key2.length ? 1 : -1; } }); }, getMessageList: function(startIndex, count){ if (!MSGS){ return []; } var messages = FILE.getMessages(selectedChannel); return MSGS.slice(startIndex, !count ? undefined : startIndex+count).map(key => { var message = messages[key]; return { // reserve.txt user: FILE.getUser(message.u), timestamp: message.t, contents: message.m }; }); }, getMessageCount: function(){ return MSGS ? MSGS.length : 0; } }; })(); ","var STATE = (function(){ var FILE; var MSGS; var selectedChannel; return { uploadFile: function(file){ FILE = file; MSGS = null; }, getChannelList: function(){ var channels = FILE.getChannels(); return Object.keys(channels).map(key => ({ // reserve.txt id: key, name: channels[key].name, server: FILE.getServer(channels[key].server), msgcount: FILE.getMessageCount(key) })); }, getChannelName: function(channel){ return FILE.getChannelById(channel).name; }, getUserName: function(user){ return FILE.getUserById(user).name; }, selectChannel: function(channel){ selectedChannel = channel; MSGS = Object.keys(FILE.getMessages(channel)).sort(); }, getMessageList: function(startIndex, count){ if (!MSGS){ return []; } var messages = FILE.getMessages(selectedChannel); return MSGS.slice(startIndex, !count ? undefined : startIndex+count).map(key => { var message = messages[key]; return { // reserve.txt user: FILE.getUser(message.u), timestamp: message.t, contents: message.m }; }); }, getMessageCount: function(){ return MSGS ? MSGS.length : 0; } }; })(); " Update orderedmultidict dependency to 0.7.3 and newer.,"import os import re import sys from sys import version_info from os.path import dirname, join as pjoin from setuptools import setup, find_packages with open(pjoin(dirname(__file__), 'furl', '__init__.py')) as fd: VERSION = re.compile( r"".*__version__ = '(.*?)'"", re.S).match(fd.read()).group(1) if sys.argv[-1] == 'publish': """""" Publish to PyPi. """""" os.system('python setup.py sdist upload') sys.exit() long_description = ( 'Information and documentation at https://github.com/gruns/furl.') setup(name='furl', version=VERSION, author='Arthur Grunseid', author_email='grunseid@gmail.com', url='https://github.com/gruns/furl', license='Unlicense', description='URL manipulation made simple.', long_description=long_description, packages=find_packages(), include_package_data=True, platforms=['any'], classifiers=['Topic :: Internet', 'Natural Language :: English', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: Freely Distributable', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], install_requires=['orderedmultidict >= 0.7.3'], test_suite='tests', tests_require=[] if version_info[0:2] >= [2, 7] else ['unittest2'], ) ","import os import re import sys from sys import version_info from os.path import dirname, join as pjoin from setuptools import setup, find_packages with open(pjoin(dirname(__file__), 'furl', '__init__.py')) as fd: VERSION = re.compile( r"".*__version__ = '(.*?)'"", re.S).match(fd.read()).group(1) if sys.argv[-1] == 'publish': """""" Publish to PyPi. """""" os.system('python setup.py sdist upload') sys.exit() long_description = ( 'Information and documentation at https://github.com/gruns/furl.') setup(name='furl', version=VERSION, author='Arthur Grunseid', author_email='grunseid@gmail.com', url='https://github.com/gruns/furl', license='Unlicense', description='URL manipulation made simple.', long_description=long_description, packages=find_packages(), include_package_data=True, platforms=['any'], classifiers=['Topic :: Internet', 'Natural Language :: English', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: Freely Distributable', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], install_requires=['orderedmultidict >= 0.7.2'], test_suite='tests', tests_require=[] if version_info[0:2] >= [2, 7] else ['unittest2'], ) " Add easy access to close and sync methods of nc files,""""""" easync.py - easier access to netCDF4 files """""" import netCDF4 class EasyGroup(object): def __repr__(self): return ""EasyNC: %s %s"" % (self._filename,self.group.path) def __str__(self): return self.__repr__() def __init__(self,group,filename): self._filename = filename self.group = group self.groups = group.groups self.variables = group.variables self.dimensions = group.dimensions for gname in group.groups.keys(): if hasattr(self,gname): print self,""already has an attribute"",gname,""skipping"" continue self.__setattr__(gname,EasyGroup(group.groups[gname],self._filename)) for vname in group.variables.keys(): if hasattr(self,vname): print self,""already has an attribute"",vname,""skipping"" continue self.__setattr__(vname,group.variables[vname]) for dname in group.dimensions.keys(): dimname = ""dim_"" + dname if hasattr(self,dimname): print self,""already has an attribute"",dimname,""skipping"" continue self.__setattr__(dimname,group.dimensions[dname]) def EasyNetCDF4(*args,**kwargs): nc = netCDF4.Dataset(*args,**kwargs) if len(args) > 0: fn = args[0] else: fn = kwargs['filename'] enc = EasyGroup(nc,fn) enc.close = nc.close enc.sync = nc.sync return enc",""""""" easync.py - easier access to netCDF4 files """""" import netCDF4 class EasyGroup(object): def __repr__(self): return ""EasyNC: %s %s"" % (self._filename,self.group.path) def __str__(self): return self.__repr__() def __init__(self,group,filename): self._filename = filename self.group = group self.groups = group.groups self.variables = group.variables self.dimensions = group.dimensions for gname in group.groups.keys(): if hasattr(self,gname): print self,""already has an attribute"",gname,""skipping"" continue self.__setattr__(gname,EasyGroup(group.groups[gname],self._filename)) for vname in group.variables.keys(): if hasattr(self,vname): print self,""already has an attribute"",vname,""skipping"" continue self.__setattr__(vname,group.variables[vname]) for dname in group.dimensions.keys(): dimname = ""dim_"" + dname if hasattr(self,dimname): print self,""already has an attribute"",dimname,""skipping"" continue self.__setattr__(dimname,group.dimensions[dname]) def EasyNetCDF4(*args,**kwargs): nc = netCDF4.Dataset(*args,**kwargs) if len(args) > 0: fn = args[0] else: fn = kwargs['filename'] return EasyGroup(nc,fn)" Rename recursive method to snake_case,"<?php if (!function_exists('load_directory')) { /** * Load all files in directory * * @author Morten Rugaard <moru@nodes.dk> * * @access public * @param string $path Path to directory (must contain trailing slash) * @param boolean $recursive Load recursively * @return boolean */ function load_directory($path, $recursive = true) { // Make sure directory exists if (!file_exists($path)) { return false; } // Scan directory $directory = scandir($path); $directory = array_slice($directory, 2); // No files found in directory if (empty($directory)) { return false; } // Parse directory foreach ($directory as $item) { // If item is a directory and recursive is false. // We'll simply skip the directory and move on. if (is_dir($path . $item) && !$recursive) { continue; } if (is_dir($path . $item)) { // Load directory load_directory($path . $item . '/'); } else { // Load file include_once ($path . $item); } } return true; } }","<?php if (!function_exists('load_directory')) { /** * Load all files in directory * * @author Morten Rugaard <moru@nodes.dk> * * @access public * @param string $path Path to directory (must contain trailing slash) * @param boolean $recursive Load recursively * @return boolean */ function load_directory($path, $recursive = true) { // Make sure directory exists if (!file_exists($path)) { return false; } // Scan directory $directory = scandir($path); $directory = array_slice($directory, 2); // No files found in directory if (empty($directory)) { return false; } // Parse directory foreach ($directory as $item) { // If item is a directory and recursive is false. // We'll simply skip the directory and move on. if (is_dir($path . $item) && !$recursive) { continue; } if (is_dir($path . $item)) { // Load directory loadDirectory($path . $item . '/'); } else { // Load file include_once ($path . $item); } } return true; } }" Fix usage of Nock in unit tests - much cleaner now,"var config = require('./config'); var should = require('should'); var nock = require('nock'); var up = require('../index')(config); nock.disableNetConnect(); var baseApi = nock('https://jawbone.com:443'); describe('up', function(){ describe('.moves', function(){ describe('.get()', function(){ it('should call correct url', function(done){ var api = baseApi.matchHeader('Accept', 'application/json') .get('/nudge/api/v.1.1/users/@me/moves?') .reply(200, 'OK!'); up.moves.get({}, function(err, body) { (err === null).should.be.true; body.should.equal('OK!'); api.done(); done(); }); }); }); describe('.get({ xid: 123 })', function(){ it('should return correct url', function(done){ var api = baseApi.matchHeader('Accept', 'application/json') .get('/nudge/api/v.1.1/moves/123') .reply(200, 'OK!'); up.moves.get({ xid: 123 }, function(err, body) { (err === null).should.be.true; body.should.equal('OK!'); api.done(); done(); }); }); }); }); }); ","var config = require('./config'); var should = require('should'); var nock = require('nock'); var up = require('../index')(config); var baseApi = nock('https://jawbone.com:443'); describe('up', function(){ describe('.moves', function(){ describe('.get()', function(){ it('should call correct url', function(done){ var api = baseApi.matchHeader('Accept', 'application/json') .get('/nudge/api/v.1.1/users/@me/moves?') .reply(200, 'OK!'); up.moves.get({}, function(err, body) { (err === null).should.be.true; body.should.equal('OK!'); api.isDone().should.be.true; api.pendingMocks().should.be.empty; done(); }); }); }); describe('.get({ xid: 123 })', function(){ it('should return correct url', function(done){ var api = baseApi.matchHeader('Accept', 'application/json') .get('/nudge/api/v.1.1/moves/123') .reply(200, 'OK!'); up.moves.get({ xid: 123 }, function(err, body) { (err === null).should.be.true; body.should.equal('OK!'); api.isDone().should.be.true; api.pendingMocks().should.be.empty; done(); }); }); }); }); });" Change initial default showResult value to 'NO DATA' message,"import React from 'react'; import GithubAPI from '../../api/githubAPI'; class HomePage extends React.Component { constructor(props, context) { super(props, context); this.state = { showResult: ""NO DATA - Click button above to fetch data."" }; this.invokeGitHubAPI = this.invokeGitHubAPI.bind(this); } invokeGitHubAPI(){ GithubAPI.testOctokat().then(testResult => { let parsedTestResult = testResult.pushedAt.toTimeString(); console.log(testResult); console.log(parsedTestResult); this.setState({showResult: parsedTestResult}); }).catch(error => { throw(error); }); } render() { return ( <div> <h1>GitHub Status API GUI</h1> <h3>Open browser console to see JSON data returned from GitHub API</h3> <div className=""row""> <div className=""col-sm-3""> <button type=""button"" className=""btn btn-primary"" onClick={this.invokeGitHubAPI}>Test GitHub API Call</button> </div> </div> <div className=""row""> <div className=""col-sm-6""> <span>{this.state.showResult}</span> </div> </div> </div> ); } } export default HomePage; ","import React from 'react'; import GithubAPI from '../../api/githubAPI'; class HomePage extends React.Component { constructor(props, context) { super(props, context); this.state = { showResult: ""l"" }; this.invokeGitHubAPI = this.invokeGitHubAPI.bind(this); } invokeGitHubAPI(){ GithubAPI.testOctokat().then(testResult => { let parsedTestResult = testResult.pushedAt.toTimeString(); console.log(testResult); console.log(parsedTestResult); this.setState({showResult: parsedTestResult}); }).catch(error => { throw(error); }); } render() { return ( <div> <h1>GitHub Status API GUI</h1> <h3>Open browser console to see JSON data returned from GitHub API</h3> <div className=""row""> <div className=""col-sm-3""> <button type=""button"" className=""btn btn-primary"" onClick={this.invokeGitHubAPI}>Test GitHub API Call</button> </div> </div> <div className=""row""> <div className=""col-sm-6""> <span>{this.state.showResult}</span> </div> </div> </div> ); } } export default HomePage; " Make Grunt use the correct paths for sassing.,"module.exports = function(grunt) { // 1. All configuration goes here grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), /* concat: { dist: { src: [ 'javascripts/app.js', 'javascripts/foundation.min.js' ], dest: 'javascripts/app.min.js', } } */ /* uglify: { build: { src: 'javascripts/app.js', dest: 'javascripts/app.min.js' } }, */ watch: { scripts: { files: ['js/*.js', 'sass/*.scss'], tasks: ['sass'], options: { spawn: false, }, } }, sass: { dist: { options: { style: 'compressed', loadPath: [ 'node_modules/bootstrap-sass/vendor/assets/stylesheets/', 'node_modules/font-awesome/scss/' ] }, files: { 'css/app.css': 'sass/app.scss' } } } }); // 3. Where we tell Grunt we plan to use this plug-in. //grunt.loadNpmTasks('grunt-contrib-concat'); //grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-sass'); // grunt.loadNpmTasks('grunt-sass'); // 4. Where we tell Grunt what to do when we type ""grunt"" into the terminal. grunt.registerTask('default', ['sass']); };","module.exports = function(grunt) { // 1. All configuration goes here grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), /* concat: { dist: { src: [ 'javascripts/app.js', 'javascripts/foundation.min.js' ], dest: 'javascripts/app.min.js', } } */ /* uglify: { build: { src: 'javascripts/app.js', dest: 'javascripts/app.min.js' } }, */ watch: { scripts: { files: ['js/*.js', 'sass/*.scss'], tasks: ['sass'], options: { spawn: false, }, } }, sass: { dist: { options: { style: 'compressed' }, files: { 'css/app.css': 'sass/app.scss' } } } }); // 3. Where we tell Grunt we plan to use this plug-in. //grunt.loadNpmTasks('grunt-contrib-concat'); //grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-sass'); // grunt.loadNpmTasks('grunt-sass'); // 4. Where we tell Grunt what to do when we type ""grunt"" into the terminal. grunt.registerTask('default', ['sass']); };" Move Guzzle 3.9 providers to a compat() function,"<?php namespace Bolt\Provider; use Guzzle\Service\Builder\ServiceBuilder; use Guzzle\Service\Client as ServiceClient; use GuzzleHttp\Client; use Silex\Application; use Silex\ServiceProviderInterface; class GuzzleServiceProvider implements ServiceProviderInterface { public function register(Application $app) { $app['guzzle.base_url'] = '/'; if (!isset($app['guzzle.plugins'])) { $app['guzzle.plugins'] = array(); } /** @deprecated */ if (version_compare(PHP_VERSION, '5.4.0', '<')) { return $this->compat($app); } } /** * PHP 5.3 compatibility services * * @deprecated * * @param Application $app */ private function compat(Application $app) { // Register a Guzzle ServiceBuilder $app['guzzle'] = $app->share( function () use ($app) { if (!isset($app['guzzle.services'])) { $builder = new ServiceBuilder(array()); } else { $builder = ServiceBuilder::factory($app['guzzle.services']); } return $builder; } ); // Register a simple Guzzle Client object (requires absolute URLs when guzzle.base_url is unset) $app['guzzle.client'] = $app->share( function () use ($app) { $client = new ServiceClient($app['guzzle.base_url']); foreach ($app['guzzle.plugins'] as $plugin) { $client->addSubscriber($plugin); } return $client; } ); } public function boot(Application $app) { } } ","<?php namespace Bolt\Provider; use Guzzle\Service\Builder\ServiceBuilder; use Guzzle\Service\Client; use Silex\Application; use Silex\ServiceProviderInterface; class GuzzleServiceProvider implements ServiceProviderInterface { public function register(Application $app) { $app['guzzle.base_url'] = '/'; if (!isset($app['guzzle.plugins'])) { $app['guzzle.plugins'] = array(); } // Register a Guzzle ServiceBuilder $app['guzzle'] = $app->share( function () use ($app) { if (!isset($app['guzzle.services'])) { $builder = new ServiceBuilder(array()); } else { $builder = ServiceBuilder::factory($app['guzzle.services']); } return $builder; } ); // Register a simple Guzzle Client object (requires absolute URLs when guzzle.base_url is unset) $app['guzzle.client'] = $app->share( function () use ($app) { $client = new Client($app['guzzle.base_url']); foreach ($app['guzzle.plugins'] as $plugin) { $client->addSubscriber($plugin); } return $client; } ); } public function boot(Application $app) { } } " "Set the payout status to created BEFORE we call out to dorado. This way we do not override that status that dorado set. BB-9471 #resolve","import json import requests from django.core.exceptions import ImproperlyConfigured from django.db import connection from requests.exceptions import MissingSchema from bluebottle.clients import properties class PayoutValidationError(Exception): pass class PayoutCreationError(Exception): pass class DoradoPayoutAdapter(object): def __init__(self, project): self.settings = getattr(properties, 'PAYOUT_SERVICE', None) self.project = project self.tenant = connection.tenant def trigger_payout(self): # Send the signal to Dorado data = { 'project_id': self.project.id, 'tenant': self.tenant.schema_name } try: self.project.payout_status = 'created' self.project.save() response = requests.post(self.settings['url'], data) response.raise_for_status() except requests.HTTPError: try: raise PayoutValidationError(json.loads(response.content)) except ValueError: raise PayoutCreationError(response.content) except MissingSchema: raise ImproperlyConfigured(""Incorrect Payout URL"") except IOError, e: raise PayoutCreationError(unicode(e)) except TypeError: raise ImproperlyConfigured(""Invalid Payout settings"") ","import json import requests from django.core.exceptions import ImproperlyConfigured from django.db import connection from requests.exceptions import MissingSchema from bluebottle.clients import properties class PayoutValidationError(Exception): pass class PayoutCreationError(Exception): pass class DoradoPayoutAdapter(object): def __init__(self, project): self.settings = getattr(properties, 'PAYOUT_SERVICE', None) self.project = project self.tenant = connection.tenant def trigger_payout(self): # Send the signal to Dorado data = { 'project_id': self.project.id, 'tenant': self.tenant.schema_name } try: response = requests.post(self.settings['url'], data) response.raise_for_status() self.project.payout_status = 'created' self.project.save() except requests.HTTPError: try: raise PayoutValidationError(json.loads(response.content)) except ValueError: raise PayoutCreationError(response.content) except MissingSchema: raise ImproperlyConfigured(""Incorrect Payout URL"") except IOError, e: raise PayoutCreationError(unicode(e)) except TypeError: raise ImproperlyConfigured(""Invalid Payout settings"") " Fix JS bug on thumbnail," $(document).ready(function() { // Init action when user select sildeshow to see $('.slideshow-item').on('click', function(event) { // Cancel event global.cancelEvent(event); // Select new slideshow item $('.slideshow-item').removeClass('activ'); $(this).addClass('activ'); // Extract slideshow identifier and display slideshow var slideshowId = String($(this).attr('data-slideshow-id')); displaySlideshow(slideshowId); }); // Select first slideshow per default if ($('.slideshow-item').length > 0) $('.slideshow-item')[0].click(); }); /** * Allows to display slideshow using Ajax. * @param event Click event to prevent. * @param slideshowItem Slideshow item that have been selected. */ function displaySlideshow(slideshowId) { // Load slideshow content and display it var ajaxBaseUrl = global.basePath + '/ajax/slideshow/' + slideshowId; $.ajax({ url: ajaxBaseUrl, timeout: 10000, success: function(msg) { // Add new content and initialize it (carousel + slideshow) $('#section-content').html(msg); initAjaxSlideshow(); initThumbnailAction(); }, error: function(msg) { alert(""Impossible de charger le diaporama""); } }); } /** * Allows to initialize action when user click on thumbnails. */ function initThumbnailAction() { $('.thumbnail-item').on('click', function() { var index = $(this).attr('data-index'); $('#picture-list').slick('slickGoTo', index); }); } "," $(document).ready(function() { // Init action when user select sildeshow to see $('.slideshow-item').on('click', function(event) { // Cancel event global.cancelEvent(event); // Select new slideshow item $('.slideshow-item').removeClass('activ'); $(this).addClass('activ'); // Extract slideshow identifier and display slideshow var slideshowId = String($(this).attr('data-slideshow-id')); displaySlideshow(slideshowId); }); // Select first slideshow per default if ($('.slideshow-item').length > 0) $('.slideshow-item')[0].click(); }); /** * Allows to display slideshow using Ajax. * @param event Click event to prevent. * @param slideshowItem Slideshow item that have been selected. */ function displaySlideshow(slideshowId) { // Load slideshow content and display it var ajaxBaseUrl = global.basePath + '/ajax/slideshow/' + slideshowId; $.ajax({ url: ajaxBaseUrl, timeout: 10000, success: function(msg) { // Add new content and initialize it (carousel + slideshow) $('#section-content').html(msg); initAjaxSlideshow(); initThumbnailAction(); }, error: function(msg) { alert(""Impossible de charger le diaporama""); } }); } /** * Allows to initialize action when user click on thumbnails. */ function initThumbnailAction() { $('.thumbnail-item').on('click', function() { var index = $(this).attr('data-index'); $('#picture-list').slickGoTo(index); }); } " Add a back to overview button,"import React, { Component } from 'react'; import { Link } from 'react-router'; import './BookDetails.scss'; export default class BookDetails extends Component { render() { const { title, coverUrl } = this.props.book; return ( <div className=""book-details""> <Link to=""/""> <i className=""fa fa-chevron-left"" /> Back to Overview </Link> <div className=""book-details__cover""> <img alt={title} src={coverUrl} className=""book-details__cover__image"" /> </div> <div className=""book-details__info""> <h1 className=""book-details__info__title"">Moby Dick</h1> <h2 className=""book-details__info__author"">Herman Melville</h2> <h4 className=""book-details__info__meta"">Published by Project Gutenberg</h4> <p className=""book-details__info__description""> Nulla facilisi. Donec eros erat, molestie et dignissim in, pulvinar facilisis risus. Ut at nisl vitae odio malesuada ultrices vitae sit amet est. Cras feugiat neque sit amet elementum accumsan. Vestibulum pharetra a neque nec congue. Maecenas vel sollicitudin tortor, nec mattis mi. Praesent dui lorem, faucibus vitae purus semper, rhoncus tincidunt magna. </p> <p className=""book-details__info__subjects""></p> </div> </div> ); } } ","import React, { Component } from 'react'; import './BookDetails.scss'; export default class BookDetails extends Component { render() { const { title, coverUrl } = this.props.book; return ( <div className=""book-details""> <div className=""book-details__cover""> <img alt={title} src={coverUrl} className=""book-details__cover__image"" /> </div> <div className=""book-details__info""> <h1 className=""book-details__info__title"">Moby Dick</h1> <h2 className=""book-details__info__author"">Herman Melville</h2> <h4 className=""book-details__info__meta"">Published by Project Gutenberg</h4> <p className=""book-details__info__description""> Nulla facilisi. Donec eros erat, molestie et dignissim in, pulvinar facilisis risus. Ut at nisl vitae odio malesuada ultrices vitae sit amet est. Cras feugiat neque sit amet elementum accumsan. Vestibulum pharetra a neque nec congue. Maecenas vel sollicitudin tortor, nec mattis mi. Praesent dui lorem, faucibus vitae purus semper, rhoncus tincidunt magna. </p> <p className=""book-details__info__subjects""></p> </div> </div> ); } } " Index aggregated task data using permutation hash,"<?php /* This file contains a set of functions that are common to all tools of besearcher. Author: Fernando Bevilacqua <fernando.bevilacqua@his.se> */ function aggredateTaskInfos($theTaskJsonFiles) { $aInfos = array(); foreach($theTaskJsonFiles as $aFile) { $aInfo = json_decode(file_get_contents($aFile), true); $aPermutation = $aInfo['permutation']; // TODO: get progress and result data from log file $aInfos[$aPermutation] = array( 'commit' => $aInfo['hash'], 'permutation' => $aPermutation, 'date' => date('d-m-Y H:i:s', $aInfo['time']), 'params' => $aInfo['params'], 'cmd' => $aInfo['cmd'], 'progress' => 0, 'results' => array(), 'raw' => $aInfo ); } return $aInfos; } function findTasksInfos($theDataDir) { $aData = array(); $aTasks = scandir($theDataDir); foreach($aTasks as $aItem) { $aPath = $theDataDir . DIRECTORY_SEPARATOR . $aItem; if($aItem[0] != '.' && is_dir($aPath)) { $aFiles = glob($aPath . DIRECTORY_SEPARATOR . '*.json'); $aData[$aItem] = aggredateTaskInfos($aFiles); } } return $aData; } ?> ","<?php /* This file contains a set of functions that are common to all tools of besearcher. Author: Fernando Bevilacqua <fernando.bevilacqua@his.se> */ function aggredateTaskInfos($theTaskJsonFiles) { $aInfos = array(); foreach($theTaskJsonFiles as $aFile) { $aInfo = json_decode(file_get_contents($aFile), true); // TODO: get progress and result data from log file $aInfos[] = array( 'commit' => $aInfo['hash'], 'permutation' => $aInfo['permutation'], 'date' => date('d-m-Y H:i:s', $aInfo['time']), 'params' => $aInfo['params'], 'cmd' => $aInfo['cmd'], 'progress' => 0, 'results' => array(), 'raw' => $aInfo ); } return $aInfos; } function findTasksInfos($theDataDir) { $aData = array(); $aTasks = scandir($theDataDir); foreach($aTasks as $aItem) { $aPath = $theDataDir . DIRECTORY_SEPARATOR . $aItem; if($aItem[0] != '.' && is_dir($aPath)) { $aFiles = glob($aPath . DIRECTORY_SEPARATOR . '*.json'); $aData[$aItem] = aggredateTaskInfos($aFiles); } } return $aData; } ?> " Update database backends analyzer to target 1.5,"import ast from .base import BaseAnalyzer, Result class DB_BackendsVisitor(ast.NodeVisitor): def __init__(self): self.found = [] removed_items = { 'django.db.backends.postgresql': 'django.db.backends.postgresql_psycopg2', } def visit_Str(self, node): if node.s in self.removed_items.keys(): self.found.append((node.s, node)) class DB_BackendsAnalyzer(BaseAnalyzer): def analyze_file(self, filepath, code): if not isinstance(code, ast.AST): return visitor = DB_BackendsVisitor() visitor.visit(code) for name, node in visitor.found: propose = visitor.removed_items[name] result = Result( description = ( '%r database backend has beed deprecated in Django 1.3 ' 'and removed in 1.4. Use %r instead.' % (name, propose) ), path = filepath, line = node.lineno) lines = self.get_file_lines(filepath, node.lineno, node.lineno) for lineno, important, text in lines: result.source.add_line(lineno, text, important) result.solution.add_line(lineno, text.replace(name, propose), important) yield result ","import ast from .base import BaseAnalyzer, Result class DB_BackendsVisitor(ast.NodeVisitor): def __init__(self): self.found = [] deprecated_items = { 'django.db.backends.postgresql': 'django.db.backends.postgresql_psycopg2', } def visit_Str(self, node): if node.s in self.deprecated_items.keys(): self.found.append((node.s, node)) class DB_BackendsAnalyzer(BaseAnalyzer): def analyze_file(self, filepath, code): if not isinstance(code, ast.AST): return visitor = DB_BackendsVisitor() visitor.visit(code) for name, node in visitor.found: propose = visitor.deprecated_items[name] result = Result( description = ( '%r backend is deprecated, use %r instead' % (name, propose) ), path = filepath, line = node.lineno) lines = self.get_file_lines(filepath, node.lineno, node.lineno) for lineno, important, text in lines: result.source.add_line(lineno, text, important) result.solution.add_line(lineno, text.replace(name, propose), important) yield result " Add native dns module to webpack externals,"const { resolve } = require('path') module.exports = { mode: 'production', entry: './dist.browser/browser/index.js', module: { rules: [ { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/, }, { test: /\.js$/, loader: 'file-replace-loader', options: { condition: 'always', replacement(resourcePath) { const mapping = { [resolve('./dist.browser/lib/logging.js')]: resolve( './dist.browser/browser/logging.js' ), [resolve('./dist.browser/lib/net/peer/libp2pnode.js')]: resolve( './dist.browser/browser/libp2pnode.js' ), } return mapping[resourcePath] }, async: true, }, }, ], }, resolve: { extensions: ['.tsx', '.ts', '.js'], }, output: { filename: 'bundle.js', path: resolve(__dirname, 'dist'), library: 'ethereumjs', }, node: { dgram: 'empty', // used by: rlpxpeer via ethereumjs-devp2p net: 'empty', // used by: rlpxpeer fs: 'empty', // used by: FullSynchronizer via @ethereumjs/vm }, performance: { hints: false, // suppress maxAssetSize warnings etc.. }, externals: ['dns'], } ","const { resolve } = require('path') module.exports = { mode: 'production', entry: './dist.browser/browser/index.js', module: { rules: [ { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/, }, { test: /\.js$/, loader: 'file-replace-loader', options: { condition: 'always', replacement(resourcePath) { const mapping = { [resolve('./dist.browser/lib/logging.js')]: resolve( './dist.browser/browser/logging.js' ), [resolve('./dist.browser/lib/net/peer/libp2pnode.js')]: resolve( './dist.browser/browser/libp2pnode.js' ), } return mapping[resourcePath] }, async: true, }, }, ], }, resolve: { extensions: ['.tsx', '.ts', '.js'], }, output: { filename: 'bundle.js', path: resolve(__dirname, 'dist'), library: 'ethereumjs', }, node: { dgram: 'empty', // used by: rlpxpeer via ethereumjs-devp2p net: 'empty', // used by: rlpxpeer fs: 'empty', // used by: FullSynchronizer via @ethereumjs/vm }, performance: { hints: false, // suppress maxAssetSize warnings etc.. }, } " Add param for confirm field on register test func,"import bookmarks import unittest class FlaskrTestCase(unittest.TestCase): def setUp(self): self.app = bookmarks.app.test_client() # with bookmarks.app.app_context(): bookmarks.database.init_db() def tearDown(self): # with bookmarks.app.app_context(): bookmarks.database.db_session.remove() bookmarks.database.Base.metadata.drop_all( bind=bookmarks.database.engine) def test_empty_db(self): rv = self.app.get('/') assert b'There aren\'t any bookmarks yet.' in rv.data def register(self, username, name, email, password, confirm=None): return self.app.post('/register_user/', data=dict( username=username, name=name, email=email, password=password, confirm=confirm ), follow_redirects=True) def login(self, username, password): return self.app.post('/login', data=dict( username=username, password=password, confirm=password ), follow_redirects=True) def logout(self): return self.app.get('/logout', follow_redirects=True) def test_register(self): username = 'byanofsky' name = 'Brandon Yanofsky' email = 'byanofsky@me.com' password = 'Brandon123' rv = self.register(username, name, email, password) # print(rv.data) assert (b'Successfully registered ' in rv.data) if __name__ == '__main__': unittest.main() ","import bookmarks import unittest class FlaskrTestCase(unittest.TestCase): def setUp(self): self.app = bookmarks.app.test_client() # with bookmarks.app.app_context(): bookmarks.database.init_db() def tearDown(self): # with bookmarks.app.app_context(): bookmarks.database.db_session.remove() bookmarks.database.Base.metadata.drop_all( bind=bookmarks.database.engine) def test_empty_db(self): rv = self.app.get('/') assert b'There aren\'t any bookmarks yet.' in rv.data def register(self, username, name, email, password): return self.app.post('/register_user/', data=dict( username=username, name=name, email=email, password=password, confirm=password ), follow_redirects=True) def login(self, username, password): return self.app.post('/login', data=dict( username=username, password=password, confirm=password ), follow_redirects=True) def logout(self): return self.app.get('/logout', follow_redirects=True) def test_register(self): username = 'byanofsky' name = 'Brandon Yanofsky' email = 'byanofsky@me.com' password = 'Brandon123' rv = self.register(username, name, email, password) # print(rv.data) assert (b'Successfully registered ' in rv.data) if __name__ == '__main__': unittest.main() " "Add lint and reformat target. This is part of the ground work to have a consistent style to the template JSON documents. Two targets are defined. * Lint - verify all JSON templates follow the approved style. * Reformat - modify all JSON templates to follow the approved style. The lint target will be used to gate the build in a future commit. If a PR does not meet the approved style it will fail the build The reformat target is for developers. Developers should execute this target before sending a PR to match the approved style.","var grunt = require('grunt'); require('load-grunt-tasks')(grunt); var files = ['test/*.js']; var templates = ['**/*.json']; grunt.initConfig({ mochacli: { options: { reporter: 'spec', bail: false }, all: files }, jshint: { files: files, options: { jshintrc: '.jshintrc' } }, jscs: { files: { src: files }, options: { config: '.jscsrc', esnext: true } }, jsbeautifier: { test: { files: { src: files }, options: { mode: 'VERIFY_ONLY', config: '.beautifyrc' } }, lint: { files: { src: templates }, options: { mode: 'VERIFY_ONLY', config: '.beautifyrc' } }, reformat: { files: { src: templates }, options: { mode: 'VERIFY_AND_WRITE', config: '.beautifyrc' } }, write: { files: { src: files }, options: { config: '.beautifyrc' } } } }); grunt.registerTask('test', ['jshint', 'jscs', 'jsbeautifier:test', 'jsbeautifier:write', 'mochacli']); ","var grunt = require('grunt'); require('load-grunt-tasks')(grunt); var files = ['test/*.js']; grunt.initConfig({ mochacli: { options: { reporter: 'spec', bail: false }, all: files }, jshint: { files: files, options: { jshintrc: '.jshintrc' } }, jscs: { files: { src: files }, options: { config: '.jscsrc', esnext: true } }, jsbeautifier: { test: { files: { src: files }, options: { mode: 'VERIFY_ONLY', config: '.beautifyrc' } }, write: { files: { src: files }, options: { config: '.beautifyrc' } } } }); grunt.registerTask('test', ['jshint', 'jscs', 'jsbeautifier', 'mochacli']); " Add UT on standard family unit,"<?php namespace Akeneo\Bundle\MeasureBundle\Tests\Unit\Manager; use Akeneo\Bundle\MeasureBundle\Manager\MeasureManager; class MeasureManagerTest extends \PHPUnit_Framework_TestCase { public function setUp() { $this->measureManager = new MeasureManager; $this->measureManager->setMeasureConfig( array( 'WEIGHT' => array( 'standard' => 'KILOGRAM', 'units' => array( 'KILOGRAM' => array('symbol' => 'kg'), 'GRAM' => array('symbol' => 'g') ) ) ) ); } public function testGetUnitForFamily() { $this->assertEquals( array( 'KILOGRAM' => 'kg', 'GRAM' => 'g', ), $this->measureManager->getUnitSymbolsForFamily('WEIGHT') ); } public function testInvalidFamilyWhenGettingUnitForFamily() { try { $this->measureManager->getUnitSymbolsForFamily('LENGTH'); } catch (\InvalidArgumentException $e) { $this->assertEquals('Undefined measure family ""LENGTH""', $e->getMessage()); return; } $this->fail('An InvalidArgumentException has not been raised.'); } public function testGetStandardUnitForFamily() { $this->assertEquals( 'KILOGRAM', $this->measureManager->getStandardUnitForFamily('WEIGHT') ); } } ","<?php namespace Akeneo\Bundle\MeasureBundle\Tests\Unit\Manager; use Akeneo\Bundle\MeasureBundle\Manager\MeasureManager; class MeasureManagerTest extends \PHPUnit_Framework_TestCase { public function setUp() { $this->measureManager = new MeasureManager; $this->measureManager->setMeasureConfig( array( 'WEIGHT' => array( 'units' => array( 'KILOGRAM' => array('symbol' => 'kg'), 'GRAM' => array('symbol' => 'g') ) ) ) ); } public function testGetUnitForFamily() { $this->assertEquals( array( 'KILOGRAM' => 'kg', 'GRAM' => 'g', ), $this->measureManager->getUnitSymbolsForFamily('WEIGHT') ); } public function testInvalidFamilyWhenGettingUnitForFamily() { try { $this->measureManager->getUnitSymbolsForFamily('LENGTH'); } catch (\InvalidArgumentException $e) { $this->assertEquals('Undefined measure family ""LENGTH""', $e->getMessage()); return; } $this->fail('An InvalidArgumentException has not been raised.'); } } " Update rest api url config error message,"import json from django.core.exceptions import ImproperlyConfigured from ..compat import NoReverseMatch, render, render_to_string, reverse def render_embed(nodes=None, request=None): context = {} if nodes is None: try: prefix = request.build_absolute_uri(""/"").rstrip(""/"") context.update( { ""cms_url"": prefix + reverse(""admin:djedi:cms""), ""exclude_json_nodes"": True, } ) output = render(request, ""djedi/cms/embed.html"", context) except NoReverseMatch: raise ImproperlyConfigured( ""Could not find djedi in your url conf, "" ""enable django admin or include "" ""djedi.urls within the admin namespace."" ) else: context.update( { ""cms_url"": reverse(""admin:djedi:cms""), ""exclude_json_nodes"": False, ""json_nodes"": json.dumps(nodes).replace(""</"", ""\\x3C/""), } ) output = render_to_string(""djedi/cms/embed.html"", context) return output ","import json from django.core.exceptions import ImproperlyConfigured from ..compat import NoReverseMatch, render, render_to_string, reverse def render_embed(nodes=None, request=None): context = {} if nodes is None: try: prefix = request.build_absolute_uri(""/"").rstrip(""/"") context.update( { ""cms_url"": prefix + reverse(""admin:djedi:cms""), ""exclude_json_nodes"": True, } ) output = render(request, ""djedi/cms/embed.html"", context) except NoReverseMatch: raise ImproperlyConfigured( ""Could not find djedi in your url conf, "" ""include djedi.rest.urls within the djedi namespace."" ) else: context.update( { ""cms_url"": reverse(""admin:djedi:cms""), ""exclude_json_nodes"": False, ""json_nodes"": json.dumps(nodes).replace(""</"", ""\\x3C/""), } ) output = render_to_string(""djedi/cms/embed.html"", context) return output " Fix missing comma in tabular data preview,"chorus.dialogs.TabularDataPreview = chorus.dialogs.Base.extend({ constructorName: ""TabularDataPreview"", templateName: 'tabular_data_preview', title: function() {return t(""dataset.data_preview_title"", {name: this.model.get(""objectName"")}); }, events: { ""click button.cancel"": ""cancelTask"" }, subviews: { '.results_console': 'resultsConsole' }, setup: function() { _.bindAll(this, 'title'); this.resultsConsole = new chorus.views.ResultsConsole({ footerSize: _.bind(this.footerSize, this), showDownloadDialog: true, tabularData: this.model, enableResize: true, enableExpander: true }); this.closePreviewHandle = chorus.PageEvents.subscribe(""action:closePreview"", this.closeModal, this); this.modalClosedHandle = chorus.PageEvents.subscribe(""modal:closed"", this.cancelTask, this); }, footerSize: function() { return this.$('.modal_controls').outerHeight(true); }, postRender: function() { this.task = this.model.preview(); this.resultsConsole.execute(this.task); }, cancelTask: function(e) { this.task && this.task.cancel(); chorus.PageEvents.unsubscribe(this.modalClosedHandle); }, close: function() { chorus.PageEvents.unsubscribe(this.closePreviewHandle); } }); ","chorus.dialogs.TabularDataPreview = chorus.dialogs.Base.extend({ constructorName: ""TabularDataPreview"", templateName: 'tabular_data_preview', title: function() {return t(""dataset.data_preview_title"", {name: this.model.get(""objectName"")}); }, events: { ""click button.cancel"": ""cancelTask"" }, subviews: { '.results_console': 'resultsConsole' }, setup: function() { _.bindAll(this, 'title'); this.resultsConsole = new chorus.views.ResultsConsole({ footerSize: _.bind(this.footerSize, this), showDownloadDialog: true, tabularData: this.model enableResize: true, enableExpander: true }); this.closePreviewHandle = chorus.PageEvents.subscribe(""action:closePreview"", this.closeModal, this); this.modalClosedHandle = chorus.PageEvents.subscribe(""modal:closed"", this.cancelTask, this); }, footerSize: function() { return this.$('.modal_controls').outerHeight(true); }, postRender: function() { this.task = this.model.preview(); this.resultsConsole.execute(this.task); }, cancelTask: function(e) { this.task && this.task.cancel(); chorus.PageEvents.unsubscribe(this.modalClosedHandle); }, close: function() { chorus.PageEvents.unsubscribe(this.closePreviewHandle); } }); " Convert `PlantsViewPage` to an a stateless component,"import PlantList from './plantList'; import PlantListAddBox from './plantListAddBox'; import PlantView from './plantView'; import React from 'react'; const plantsViewPage = props => { let plantView; if (props.selectedPlantName) { plantView = ( <PlantView plantName={props.selectedPlantName} editing={props.editing} onEdit={props.onEdit} /> ); } return ( <div id=""content"" className=""plantsViewPage""> <PlantListAddBox onAdd={props.onAddPlant} /> <PlantList plants={props.plants} filterString={props.filterString} sortType={props.sortType} /> {plantView} </div> ); }; plantsViewPage.propTypes = { editing: React.PropTypes.bool.isRequired, filter: React.PropTypes.func.isRequired, onAddPlant: React.PropTypes.func.isRequired, onEdit: React.PropTypes.func.isRequired, plants: React.PropTypes.object.isRequired, selectedPlantName: React.PropTypes.string, sort: React.PropTypes.func.isRequired }; export default plantsViewPage;","import PlantList from './plantList'; import PlantListAddBox from './plantListAddBox'; import PlantView from './plantView'; import React from 'react'; export default class PlantsViewPage extends React.Component { static get propTypes() { return { editing: React.PropTypes.bool.isRequired, filter: React.PropTypes.func.isRequired, onAddPlant: React.PropTypes.func.isRequired, onEdit: React.PropTypes.func.isRequired, plants: React.PropTypes.object.isRequired, selectedPlantName: React.PropTypes.string, sort: React.PropTypes.func.isRequired }; } render() { let plantView; if (this.props.selectedPlantName) { plantView = ( <PlantView plantName={this.props.selectedPlantName} editing={this.props.editing} onEdit={this.props.onEdit} /> ); } return ( <div id=""content"" className=""plantsViewPage""> <PlantListAddBox onAdd={this.props.onAddPlant} /> <PlantList plants={this.props.plants} filterString={this.props.filterString} sortType={this.props.sortType} /> {plantView} </div> ); } }" Add --seed option for running seeds,"<?php namespace Abhijitghogre\LaravelDbClearCommand\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; class RefreshDatabase extends Command { /** * The console command name. * * @var string */ protected $name = 'db:clear {--seed : Seed the database after clearing}'; /** * The console command description. * * @var string */ protected $description = 'Drop all database tables and rerun the migrations.'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function fire() { $tables = []; DB::statement('SET FOREIGN_KEY_CHECKS=0'); foreach (DB::select('SHOW TABLES') as $k => $v) { $tables[] = array_values((array) $v)[0]; } foreach ($tables as $table) { Schema::drop($table); echo ""Table "" . $table . "" has been dropped."" . PHP_EOL; } $this->call('migrate'); if ($this->option('seed')) { $this->call('db:seed'); } } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return [ ]; } /** * Get the console command options. * * @return array */ protected function getOptions() { return [ ]; } } ","<?php namespace Abhijitghogre\LaravelDbClearCommand\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; class RefreshDatabase extends Command { /** * The console command name. * * @var string */ protected $name = 'db:clear'; /** * The console command description. * * @var string */ protected $description = 'Drop all database tables and rerun the migrations.'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function fire() { $tables = []; DB::statement('SET FOREIGN_KEY_CHECKS=0'); foreach (DB::select('SHOW TABLES') as $k => $v) { $tables[] = array_values((array)$v)[0]; } foreach ($tables as $table) { Schema::drop($table); echo ""Table "" . $table . "" has been dropped."" . PHP_EOL; } $this->call('migrate'); } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return [ ]; } /** * Get the console command options. * * @return array */ protected function getOptions() { return [ ]; } } " Use ES5 function syntax in script,"@extends('layouts.main') @section('title') Payment @endsection @section('breadcrumb') <ol class=""breadcrumb""> <li><a href=""/shop"">Shop</a></li> <li><a href=""/cart"">Cart</a></li> <li><a href=""/checkout"">Checkout</a></li> <li class=""active"">Pay</li> </ol> @endsection @section('content') <h1>Pay</h1> <h2>Order Details</h2> @include('orders._summary') <form action="""" id=""pay-now-form"" class=""row""> <div class=""col-sm-12 col-md-4 col-lg-3""> <button type=""submit"" class=""btn btn-success btn-lg btn-block"">Pay now</button> </div> </form> @stop @section('scripts') <script> (function() { const stripe = Stripe('{{ config('services.stripe.publishable') }}'); const sessionId = '{{ $session_id }}'; document.querySelector('#pay-now-form').addEventListener('submit', function(e) { e && e.preventDefault(); stripe.redirectToCheckout({ sessionId }).then(function (result) { if (result.error && result.error.message) { alert(result.error.message); } }); }); })(); </script> @stop ","@extends('layouts.main') @section('title') Payment @endsection @section('breadcrumb') <ol class=""breadcrumb""> <li><a href=""/shop"">Shop</a></li> <li><a href=""/cart"">Cart</a></li> <li><a href=""/checkout"">Checkout</a></li> <li class=""active"">Pay</li> </ol> @endsection @section('content') <h1>Pay</h1> <h2>Order Details</h2> @include('orders._summary') <form action="""" id=""pay-now-form"" class=""row""> <div class=""col-sm-12 col-md-4 col-lg-3""> <button type=""submit"" class=""btn btn-success btn-lg btn-block"">Pay now</button> </div> </form> @stop @section('scripts') <script> (function() { const stripe = Stripe('{{ config('services.stripe.publishable') }}'); const sessionId = '{{ $session_id }}'; document.querySelector('#pay-now-form').addEventListener('submit', e => { e && e.preventDefault(); stripe.redirectToCheckout({ sessionId }).then(function (result) { if (result.error && result.error.message) { alert(result.error.message); } }); }); })(); </script> @stop " Add persian_arabic_analyzer for title and content,"<?php return [ 'index' => 'sites', 'body' => [ 'settings' => [ 'number_of_shards' => 10, 'number_of_replicas' => 0, 'analysis' => [ 'char_filter' => [ 'persian_arabic_chars' => [ 'type' => 'mapping', 'mappings' => [ 'ك=>ک', 'ي=>ی', 'ؤ=>و', 'ئ=>ی', 'أ=>ا', 'ِ=>', 'ُ=>', 'َ=>', 'آ=>ا', '=> ' ] ] ], 'analyzer' => [ 'persian_arabic_analyzer' => [ 'type' => 'custom', 'tokenizer' => 'standard', 'char_filter' => ['persian_arabic_chars'] ] ] ] ], 'mapping' => [ 'default' => [ 'properties' => [ 'title' => [ 'type' => 'string', 'index' => 'analyzed', 'analyzer' => 'persian_arabic_analyzer' ], 'content' => [ 'type' => 'string', 'index' => 'analyzed', 'analyzer' => 'persian_arabic_analyzer' ], 'hash_id' => ['type' => 'string', 'index' => 'not_analyzed'], 'original' => [ 'type' => 'object', 'properties' => [ 'title' => ['type' => 'string', 'index' => 'not_analyzed'], 'content' => ['type' => 'string', 'index' => 'not_analyzed'], 'url' => ['type' => 'string', 'index' => 'not_analyzed'], 'date' => ['type' => 'date', 'format' => 'date_time_no_millis'] ] ] ] ] ] ] ];","<?php return [ 'index' => 'sites', 'body' => [ 'mapping' => [ 'default' => [ 'properties' => [ 'title' => ['type' => 'string'], 'content' => ['type' => 'string'], 'hash_id' => ['type' => 'string', 'index' => 'not_analyzed'], 'original' => [ 'type' => 'object', 'properties' => [ 'title' => ['type' => 'string', 'index' => 'not_analyzed'], 'content' => ['type' => 'string', 'index' => 'not_analyzed'], 'url' => ['type' => 'string', 'index' => 'not_analyzed'], 'date' => ['type' => 'date', 'format' => 'date_time_no_millis'] ] ] ] ] ] ] ];" "Update sorl-thumbnail requirement from <12.5,>=12.4.1 to >=12.4.1,<12.7 Updates the requirements on [sorl-thumbnail](https://github.com/jazzband/sorl-thumbnail) to permit the latest version. - [Release notes](https://github.com/jazzband/sorl-thumbnail/releases) - [Changelog](https://github.com/jazzband/sorl-thumbnail/blob/master/CHANGES.rst) - [Commits](https://github.com/jazzband/sorl-thumbnail/compare/12.4.1...12.6.2) Signed-off-by: dependabot-preview[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com>","#!/usr/bin/env python import os from setuptools import find_packages, setup setup( name='django-oscar-stores', version=""2.0"", url='https://github.com/django-oscar/django-oscar-stores', author=""David Winterbottom"", author_email=""david.winterbottom@gmail.com"", description=""An extension for Oscar to include stores"", long_description=open( os.path.join(os.path.dirname(__file__), 'README.rst')).read(), keywords=""django, oscar, e-commerce"", license='BSD', platforms=['linux'], packages=find_packages(exclude=[""sandbox*"", ""tests*""]), include_package_data=True, install_requires=[ 'django-oscar>=2.0,<2.1', 'requests>=1.1', 'sorl-thumbnail>=12.4.1,<12.7', ], # See http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: 1.11', 'Framework :: Django :: 2.2', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ]) ","#!/usr/bin/env python import os from setuptools import find_packages, setup setup( name='django-oscar-stores', version=""2.0"", url='https://github.com/django-oscar/django-oscar-stores', author=""David Winterbottom"", author_email=""david.winterbottom@gmail.com"", description=""An extension for Oscar to include stores"", long_description=open( os.path.join(os.path.dirname(__file__), 'README.rst')).read(), keywords=""django, oscar, e-commerce"", license='BSD', platforms=['linux'], packages=find_packages(exclude=[""sandbox*"", ""tests*""]), include_package_data=True, install_requires=[ 'django-oscar>=2.0,<2.1', 'requests>=1.1', 'sorl-thumbnail>=12.4.1,<12.5', ], # See http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: 1.11', 'Framework :: Django :: 2.2', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ]) " Update to AceQL HTTP Main 8.0 - new try,"/* * This file is part of AceQL HTTP. * AceQL HTTP: SQL Over HTTP * Copyright (C) 2021, KawanSoft SAS * (http://www.kawansoft.com). All rights reserved. * * AceQL HTTP is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * AceQL HTTP is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA * * Any modifications to this file must keep this entire header * intact. */ package com.kawansoft.app.version; /** * Contains the package Version info */ public class GuiVersionConstants { public static final String VERSION = ""v8.0""; public static final String DATE = ""01-Sep-2021""; } // End ","/* * This file is part of AceQL HTTP. * AceQL HTTP: SQL Over HTTP * Copyright (C) 2021, KawanSoft SAS * (http://www.kawansoft.com). All rights reserved. * * AceQL HTTP is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * AceQL HTTP is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA * * Any modifications to this file must keep this entire header * intact. */ package com.kawansoft.app.version; /** * Contains the package Version info */ public class GuiVersionConstants { public static final String VERSION = ""v8.0""; public static final String DATE = ""01-Sep-2021""; } // End " "Add default prefix (for tables) of """" for upgraders","<?PHP // $Id$ // This file is generally only included from admin/index.php // It defines default values for any important configuration variables $defaults = array ( ""theme"" => ""standard"", ""lang"" => ""en"", ""langdir"" => ""LTR"", ""locale"" => ""en"", ""auth"" => ""email"", ""smtphosts"" => """", ""smtpuser"" => """", ""smtppass"" => """", ""gdversion"" => 1, ""longtimenosee"" => 100, ""zip"" => ""/usr/bin/zip"", ""unzip"" => ""/usr/bin/unzip"", ""slasharguments"" => 1, ""htmleditor"" => true, ""proxyhost"" => """", ""proxyport"" => """", ""maxeditingtime"" => 1800, ""changepassword"" => true, ""country"" => """", ""prefix"" => """", ""guestloginbutton"" => 1, ""debug"" => 7 ); ?> ","<?PHP // $Id$ // This file is generally only included from admin/index.php // It defines default values for any important configuration variables $defaults = array ( ""theme"" => ""standard"", ""lang"" => ""en"", ""langdir"" => ""LTR"", ""locale"" => ""en"", ""auth"" => ""email"", ""smtphosts"" => """", ""smtpuser"" => """", ""smtppass"" => """", ""gdversion"" => 1, ""longtimenosee"" => 100, ""zip"" => ""/usr/bin/zip"", ""unzip"" => ""/usr/bin/unzip"", ""slasharguments"" => 1, ""htmleditor"" => true, ""proxyhost"" => """", ""proxyport"" => """", ""maxeditingtime"" => 1800, ""changepassword"" => true, ""country"" => """", ""guestloginbutton"" => 1, ""debug"" => 7 ); ?> " Make fancy things like scrolling menus work in the demo.,"// // Triple Play - utilities for use in PlayN-based games // Copyright (c) 2011-2014, Three Rings Design, Inc. - All rights reserved. // http://github.com/threerings/tripleplay/blob/master/LICENSE package tripleplay.demo; import java.util.Arrays; import playn.core.Game; import playn.core.PlayN; import playn.core.util.Clock; import tripleplay.game.ScreenStack; public class TripleDemo extends Game.Default { /** Args from the Java bootstrap class. */ public static String[] mainArgs = {}; public static final int UPDATE_RATE = 25; public TripleDemo () { super(UPDATE_RATE); } @Override public void init () { _screens.push(new DemoMenuScreen(_screens)); // propagate events so that things like buttons inside a scroller work if (!Arrays.asList(mainArgs).contains(""--no-propagate"")) { PlayN.setPropagateEvents(true); } } @Override public void update (int delta) { _clock.update(delta); _screens.update(delta); } @Override public void paint (float alpha) { _clock.paint(alpha); _screens.paint(_clock); } protected final Clock.Source _clock = new Clock.Source(UPDATE_RATE); protected final ScreenStack _screens = new ScreenStack() { @Override protected void handleError (RuntimeException error) { PlayN.log().warn(""Screen failure"", error); } @Override protected Transition defaultPushTransition () { return slide(); } @Override protected Transition defaultPopTransition () { return slide().right(); } }; } ","// // Triple Play - utilities for use in PlayN-based games // Copyright (c) 2011-2014, Three Rings Design, Inc. - All rights reserved. // http://github.com/threerings/tripleplay/blob/master/LICENSE package tripleplay.demo; import playn.core.Game; import playn.core.PlayN; import playn.core.util.Clock; import tripleplay.game.ScreenStack; public class TripleDemo extends Game.Default { /** Args from the Java bootstrap class. */ public static String[] mainArgs = {}; public static final int UPDATE_RATE = 25; public TripleDemo () { super(UPDATE_RATE); } @Override public void init () { _screens.push(new DemoMenuScreen(_screens)); } @Override public void update (int delta) { _clock.update(delta); _screens.update(delta); } @Override public void paint (float alpha) { _clock.paint(alpha); _screens.paint(_clock); } protected final Clock.Source _clock = new Clock.Source(UPDATE_RATE); protected final ScreenStack _screens = new ScreenStack() { @Override protected void handleError (RuntimeException error) { PlayN.log().warn(""Screen failure"", error); } @Override protected Transition defaultPushTransition () { return slide(); } @Override protected Transition defaultPopTransition () { return slide().right(); } }; } " Fix test for wheel in Xenial and Trusty,"import pytest import os SECUREDROP_TARGET_PLATFORM = os.environ.get(""SECUREDROP_TARGET_PLATFORM"", ""trusty"") testinfra_hosts = [ ""docker://{}-sd-app"".format(SECUREDROP_TARGET_PLATFORM) ] def test_pip_wheel_installed(Command): """""" Ensure `wheel` is installed via pip, for packaging Python dependencies into a Debian package. """""" c = Command(""pip list installed"") assert ""wheel"" in c.stdout assert c.rc == 0 def test_sass_gem_installed(Command): """""" Ensure the `sass` Ruby gem is installed, for compiling SASS to CSS. """""" c = Command(""gem list"") assert ""sass (3.4.23)"" in c.stdout assert c.rc == 0 def test_pip_dependencies_installed(Command): """""" Ensure the development pip dependencies are installed """""" c = Command(""pip list installed"") assert ""Flask-Babel"" in c.stdout assert c.rc == 0 @pytest.mark.xfail(reason=""This check conflicts with the concept of pegging"" ""dependencies"") def test_build_all_packages_updated(Command): """""" Ensure a dist-upgrade has already been run, by checking that no packages are eligible for upgrade currently. This will ensure that all upgrades, security and otherwise, have been applied to the VM used to build packages. """""" c = Command('aptitude --simulate -y dist-upgrade') assert c.rc == 0 assert ""No packages will be installed, upgraded, or removed."" in c.stdout ","import pytest import os SECUREDROP_TARGET_PLATFORM = os.environ.get(""SECUREDROP_TARGET_PLATFORM"", ""trusty"") testinfra_hosts = [ ""docker://{}-sd-app"".format(SECUREDROP_TARGET_PLATFORM) ] def test_pip_wheel_installed(Command): """""" Ensure `wheel` is installed via pip, for packaging Python dependencies into a Debian package. """""" c = Command(""pip freeze"") assert ""wheel==0.24.0"" in c.stdout assert c.rc == 0 def test_sass_gem_installed(Command): """""" Ensure the `sass` Ruby gem is installed, for compiling SASS to CSS. """""" c = Command(""gem list"") assert ""sass (3.4.23)"" in c.stdout assert c.rc == 0 def test_pip_dependencies_installed(Command): """""" Ensure the development pip dependencies are installed """""" c = Command(""pip list installed"") assert ""Flask-Babel"" in c.stdout assert c.rc == 0 @pytest.mark.xfail(reason=""This check conflicts with the concept of pegging"" ""dependencies"") def test_build_all_packages_updated(Command): """""" Ensure a dist-upgrade has already been run, by checking that no packages are eligible for upgrade currently. This will ensure that all upgrades, security and otherwise, have been applied to the VM used to build packages. """""" c = Command('aptitude --simulate -y dist-upgrade') assert c.rc == 0 assert ""No packages will be installed, upgraded, or removed."" in c.stdout " "Fix a now, incorrect unit test","<?php namespace allejo\stakx\tests; use allejo\stakx\Engines\MarkdownEngine; class MarkdownEngineTest extends \PHPUnit_Stakx_TestCase { /** @var MarkdownEngine */ private $mdEngine; public function setUp () { parent::setUp(); $this->mdEngine = MarkdownEngine::instance(); } public function testHeaderIdAttr () { $content = '# Hello World'; $expected = '<h1 id=""hello-world"">Hello World</h1>'; $compiled = $this->mdEngine->parse($content); $this->assertEquals($expected, $compiled); } public function testCodeBlockWithLanguage () { $codeBlock = <<<CODE ```php <?php echo ""hello world""; ``` CODE; $compiled = $this->mdEngine->parse($codeBlock); $this->assertContains('<code class=""hljs language-php"">', $compiled); } public function testCodeBlockWithNoLanguage () { $codeBlock = <<<CODE ``` Plain text! ``` CODE; $compiled = $this->mdEngine->parse($codeBlock); $this->assertContains('<code>', $compiled); $this->assertNotContains('language-', $compiled); } public function testCodeBlockWithUnsupportedLanguage () { $this->setExpectedException(\PHPUnit_Framework_Error_Warning::class); $codeBlock = <<<CODE ```toast toast(""some made up""); ``` CODE; $this->mdEngine->parse($codeBlock); } }","<?php namespace allejo\stakx\tests; use allejo\stakx\Engines\MarkdownEngine; class MarkdownEngineTest extends \PHPUnit_Stakx_TestCase { /** @var MarkdownEngine */ private $mdEngine; public function setUp () { parent::setUp(); $this->mdEngine = MarkdownEngine::instance(); } public function testHeaderIdAttr () { $content = '# Hello World'; $expected = '<h1 id=""hello-world"">Hello World</h1>'; $compiled = $this->mdEngine->parse($content); $this->assertEquals($expected, $compiled); } public function testCodeBlockWithLanguage () { $codeBlock = <<<CODE ```php <?php echo ""hello world""; ``` CODE; $compiled = $this->mdEngine->parse($codeBlock); $this->assertContains('<code class=""language-php"">', $compiled); } public function testCodeBlockWithNoLanguage () { $codeBlock = <<<CODE ``` Plain text! ``` CODE; $compiled = $this->mdEngine->parse($codeBlock); $this->assertContains('<code>', $compiled); $this->assertNotContains('language-', $compiled); } public function testCodeBlockWithUnsupportedLanguage () { $this->setExpectedException(\PHPUnit_Framework_Error_Warning::class); $codeBlock = <<<CODE ```toast toast(""some made up""); ``` CODE; $this->mdEngine->parse($codeBlock); } }" Use Iterator to iterate through records,"from django.contrib import admin from .models import Record from .tasks import send_personnel_code class RecordAdmin(admin.ModelAdmin): list_display = [ ""id"", ""identity"", ""write_to"", ""created_at"", ""updated_at""] list_filter = [""write_to"", ""created_at""] search_fields = [""identity"", ""write_to""] actions = [""resend_personnel_code""] def resend_personnel_code(self, request, queryset): created = 0 skipped = 0 for record in queryset.iterator(): if record.write_to != ""personnel_code"": skipped += 1 continue send_personnel_code.apply_async(kwargs={ ""identity"": str(record.identity), ""personnel_code"": record.id}) created += 1 if created == 1: created_text = ""%s Record was"" % created else: created_text = ""%s Records were"" % created if skipped == 1: skipped_text = ""%s Record was"" % skipped else: skipped_text = ""%s Records were"" % skipped self.message_user( request, ""%s successfully changed. %s skipped because they are "" ""not a HCW."" % (created_text, skipped_text)) resend_personnel_code.short_description = ""Send code by SMS (personnel ""\ ""code only)"" admin.site.register(Record, RecordAdmin) ","from django.contrib import admin from .models import Record from .tasks import send_personnel_code class RecordAdmin(admin.ModelAdmin): list_display = [ ""id"", ""identity"", ""write_to"", ""created_at"", ""updated_at""] list_filter = [""write_to"", ""created_at""] search_fields = [""identity"", ""write_to""] actions = [""resend_personnel_code""] def resend_personnel_code(self, request, queryset): created = 0 skipped = 0 for record in queryset: if record.write_to != ""personnel_code"": skipped += 1 continue send_personnel_code.apply_async(kwargs={ ""identity"": str(record.identity), ""personnel_code"": record.id}) created += 1 if created == 1: created_text = ""%s Record was"" % created else: created_text = ""%s Records were"" % created if skipped == 1: skipped_text = ""%s Record was"" % skipped else: skipped_text = ""%s Records were"" % skipped self.message_user( request, ""%s successfully changed. %s skipped because they are "" ""not a HCW."" % (created_text, skipped_text)) resend_personnel_code.short_description = ""Send code by SMS (personnel ""\ ""code only)"" admin.site.register(Record, RecordAdmin) " Swap out native factory.Factory with Django specific factory .... now all factory() calls actually save versus ... before nasty assumption,"# making a bet that factory_boy will pan out as we get more data import factory from supplements.models import Ingredient, Measurement, IngredientComposition, Supplement DEFAULT_INGREDIENT_NAME = 'Leucine' DEFAULT_INGREDIENT_HL_MINUTE = 50 DEFAULT_MEASUREMENT_NAME = 'milligram' DEFAULT_MEASUREMENT_SHORT_NAME = 'mg' DEFAULT_SUPPLEMENT_NAME = 'BCAA' class IngredientFactory(factory.DjangoModelFactory): class Meta: model = Ingredient name = DEFAULT_INGREDIENT_NAME half_life_minutes = DEFAULT_INGREDIENT_HL_MINUTE class MeasurementFactory(factory.DjangoModelFactory): class Meta: model = Measurement name = DEFAULT_MEASUREMENT_NAME class IngredientCompositionFactory(factory.DjangoModelFactory): class Meta: model = IngredientComposition ingredient = factory.SubFactory(IngredientFactory) measurement_unit = factory.SubFactory(MeasurementFactory) class SupplementFactory(factory.DjangoModelFactory): class Meta: model = Supplement name = DEFAULT_SUPPLEMENT_NAME @factory.post_generation def ingredient_composition(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return if extracted: # A list of groups were passed in, use them for group in extracted: self.ingredient_composition.add(group) ","# making a bet that factory_boy will pan out as we get more data import factory from supplements.models import Ingredient, Measurement, IngredientComposition, Supplement DEFAULT_INGREDIENT_NAME = 'Leucine' DEFAULT_INGREDIENT_HL_MINUTE = 50 DEFAULT_MEASUREMENT_NAME = 'milligram' DEFAULT_MEASUREMENT_SHORT_NAME = 'mg' DEFAULT_SUPPLEMENT_NAME = 'BCAA' class IngredientFactory(factory.Factory): class Meta: model = Ingredient name = DEFAULT_INGREDIENT_NAME half_life_minutes = DEFAULT_INGREDIENT_HL_MINUTE class MeasurementFactory(factory.Factory): class Meta: model = Measurement name = DEFAULT_MEASUREMENT_NAME class IngredientCompositionFactory(factory.Factory): class Meta: model = IngredientComposition ingredient = factory.SubFactory(IngredientFactory) measurement_unit = factory.SubFactory(MeasurementFactory) class SupplementFactory(factory.Factory): class Meta: model = Supplement name = DEFAULT_SUPPLEMENT_NAME @factory.post_generation def ingredient_composition(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return if extracted: # A list of groups were passed in, use them for group in extracted: print (group) self.ingredient_composition.add(group) " Refactor oembed manual include for clarity,"""use strict""; var readFile = require(""fs-readfile-promise""); var components = require(""server-components""); var domino = require(""domino""); var moment = require(""moment""); var _ = require(""lodash""); var getOembed = require(""../get-oembed""); function includeOembed(item) { if (item.oembed) { return getOembed(item.oembed.root_url, item.oembed.item_url, 350).then((oembed) => { return _.merge(item, { description: oembed.html }); }); } else { return item; } } var ManualSource = components.newElement(); ManualSource.createdCallback = function () { var icon = this.getAttribute(""icon""); var sourceName = this.getAttribute(""source""); return readFile(`data/${sourceName}.json`, 'utf8').then((rawJson) => { var json = JSON.parse(rawJson); return Promise.all(json.map(includeOembed)); }).then((loadedItems) => { this.dispatchEvent(new domino.impl.CustomEvent('items-ready', { items: loadedItems.map((item) => { return { icon: icon, title: item.title, url: item.url, timestamp: moment(item.date, ""YYYY/MM/DD"").unix(), description: item.description, location: item.location, }}), bubbles: true })); }); }; components.registerElement(""manual-source"", { prototype: ManualSource }); ","""use strict""; var readFile = require(""fs-readfile-promise""); var components = require(""server-components""); var domino = require(""domino""); var moment = require(""moment""); var _ = require(""lodash""); var getOembed = require(""../get-oembed""); var ManualSource = components.newElement(); ManualSource.createdCallback = function () { var icon = this.getAttribute(""icon""); var sourceName = this.getAttribute(""source""); return readFile(`data/${sourceName}.json`, 'utf8').then((rawJson) => { var json = JSON.parse(rawJson); return Promise.all(json.map((item) => { if (item.oembed) { return getOembed(item.oembed.root_url, item.oembed.item_url, 250).then((oembed) => { var newItem = _.merge(item, { description: oembed.html }); console.log(item, newItem); return newItem; }); } else { return item; } })) }).then((loadedItems) => { this.dispatchEvent(new domino.impl.CustomEvent('items-ready', { items: loadedItems.map((item) => { return { icon: icon, title: item.title, url: item.url, timestamp: moment(item.date, ""YYYY/MM/DD"").unix(), description: item.description, location: item.location, }}), bubbles: true })); }); }; components.registerElement(""manual-source"", { prototype: ManualSource }); " "Fix invalid view include path Related to https://github.com/timegridio/timegrid/issues/139","@extends('beautymail::templates.minty') @section('content') @include('beautymail::templates.minty.contentStart') <tr> <td class=""title""> {{ trans('emails.user.appointment-validation.hello-title') }} </td> </tr> <tr> <td width=""100%"" height=""10""></td> </tr> <tr> <td class=""paragraph""> {{ trans('emails.user.appointment-validation.hello-paragraph') }} </td> </tr> <tr> <td width=""100%"" height=""25""></td> </tr> <tr> <td class=""title""> {{ trans('emails.user.appointment-validation.appointment-title') }} </td> </tr> <tr> <td width=""100%"" height=""10""></td> </tr> <tr> <td class=""paragraph""> @include('emails.guest.appointment-validation._appointment', compact('appointment')) </td> </tr> <tr> <td width=""100%"" height=""25""></td> </tr> <tr> <td> @include('beautymail::templates.minty.button', ['text' => trans('emails.user.appointment-validation.button'), 'link' => route('user.agenda')]) </td> </tr> <tr> <td width=""100%"" height=""25""></td> </tr> @include('beautymail::templates.minty.contentEnd') @stop","@extends('beautymail::templates.minty') @section('content') @include('beautymail::templates.minty.contentStart') <tr> <td class=""title""> {{ trans('emails.user.appointment-validation.hello-title') }} </td> </tr> <tr> <td width=""100%"" height=""10""></td> </tr> <tr> <td class=""paragraph""> {{ trans('emails.user.appointment-validation.hello-paragraph') }} </td> </tr> <tr> <td width=""100%"" height=""25""></td> </tr> <tr> <td class=""title""> {{ trans('emails.user.appointment-validation.appointment-title') }} </td> </tr> <tr> <td width=""100%"" height=""10""></td> </tr> <tr> <td class=""paragraph""> @include('emails.manager.appointment-validation._appointment', compact('appointment')) </td> </tr> <tr> <td width=""100%"" height=""25""></td> </tr> <tr> <td> @include('beautymail::templates.minty.button', ['text' => trans('emails.user.appointment-validation.button'), 'link' => route('user.agenda')]) </td> </tr> <tr> <td width=""100%"" height=""25""></td> </tr> @include('beautymail::templates.minty.contentEnd') @stop" Compress data API responses with gzip if supported by client,"<?php namespace DrupalReleaseDate\Controllers; use Silex\Application; use Silex\ControllerProviderInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class DataControllerProvider implements ControllerProviderInterface { public function connect(Application $app) { $controllers = $app['controllers_factory']; $controllers->get('/samples.json', 'DrupalReleaseDate\Controllers\Data::samples'); $controllers->get('/changes.json', 'DrupalReleaseDate\Controllers\Data::changes'); $controllers->get('/estimates.json', 'DrupalReleaseDate\Controllers\Data::estimates'); $controllers->get('/distribution.json', 'DrupalReleaseDate\Controllers\Data::distribution'); $controllers ->after(function (Request $request, Response $response) { // Respond as JSONP if necessary if (($response instanceof JsonResponse) && $request->get('callback') !== null) { $response->setCallBack($request->get('callback')); } $response->headers->set('Access-Control-Allow-Origin', '*'); // Allow caching for one hour. $response->setMaxAge(3600); $response->setSharedMaxAge(3600); }) ->after(function (Request $request, Response $response) { // Compress the response if supported by client. $response->setVary('Accept-Encoding'); if (strpos($request->headers->get('Accept-Encoding'), 'gzip') !== false) { $response->setContent(gzencode($response->getContent())); $response->headers->set('Content-Encoding', 'gzip'); } }, Application::LATE_EVENT); return $controllers; } } ","<?php namespace DrupalReleaseDate\Controllers; use Silex\Application; use Silex\ControllerProviderInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class DataControllerProvider implements ControllerProviderInterface { public function connect(Application $app) { $controllers = $app['controllers_factory']; $controllers->get('/samples.json', 'DrupalReleaseDate\Controllers\Data::samples'); $controllers->get('/changes.json', 'DrupalReleaseDate\Controllers\Data::changes'); $controllers->get('/estimates.json', 'DrupalReleaseDate\Controllers\Data::estimates'); $controllers->get('/distribution.json', 'DrupalReleaseDate\Controllers\Data::distribution'); $controllers->after( function (Request $request, Response $response) { // Respond as JSONP if necessary if (($response instanceof JsonResponse) && $request->get('callback') !== null) { $response->setCallBack($request->get('callback')); } $response->headers->set('Access-Control-Allow-Origin', '*'); // Allow caching for one hour. $response->setMaxAge(3600); $response->setSharedMaxAge(3600); } ); return $controllers; } } " Sort yml items to get same results for regendoc runs,"# content of conftest.py import pytest def pytest_collect_file(parent, path): if path.ext == "".yml"" and path.basename.startswith(""test""): return YamlFile(path, parent) class YamlFile(pytest.File): def collect(self): import yaml # we need a yaml parser, e.g. PyYAML raw = yaml.safe_load(self.fspath.open()) for name, spec in sorted(raw.items()): yield YamlItem(name, self, spec) class YamlItem(pytest.Item): def __init__(self, name, parent, spec): super(YamlItem, self).__init__(name, parent) self.spec = spec def runtest(self): for name, value in sorted(self.spec.items()): # some custom test execution (dumb example follows) if name != value: raise YamlException(self, name, value) def repr_failure(self, excinfo): """""" called when self.runtest() raises an exception. """""" if isinstance(excinfo.value, YamlException): return ""\n"".join([ ""usecase execution failed"", "" spec failed: %r: %r"" % excinfo.value.args[1:3], "" no further details known at this point."" ]) def reportinfo(self): return self.fspath, 0, ""usecase: %s"" % self.name class YamlException(Exception): """""" custom exception for error reporting. """""" ","# content of conftest.py import pytest def pytest_collect_file(parent, path): if path.ext == "".yml"" and path.basename.startswith(""test""): return YamlFile(path, parent) class YamlFile(pytest.File): def collect(self): import yaml # we need a yaml parser, e.g. PyYAML raw = yaml.safe_load(self.fspath.open()) for name, spec in raw.items(): yield YamlItem(name, self, spec) class YamlItem(pytest.Item): def __init__(self, name, parent, spec): super(YamlItem, self).__init__(name, parent) self.spec = spec def runtest(self): for name, value in self.spec.items(): # some custom test execution (dumb example follows) if name != value: raise YamlException(self, name, value) def repr_failure(self, excinfo): """""" called when self.runtest() raises an exception. """""" if isinstance(excinfo.value, YamlException): return ""\n"".join([ ""usecase execution failed"", "" spec failed: %r: %r"" % excinfo.value.args[1:3], "" no further details known at this point."" ]) def reportinfo(self): return self.fspath, 0, ""usecase: %s"" % self.name class YamlException(Exception): """""" custom exception for error reporting. """""" " Add dates to test OAI harvester,"from __future__ import unicode_literals import httpretty from scrapi.base import OAIHarvester from scrapi.linter import RawDocument from .utils import TEST_OAI_DOC class TestHarvester(OAIHarvester): base_url = '' long_name = 'Test' short_name = 'test' url = 'test' property_list = ['type', 'source', 'publisher', 'format', 'date'] @httpretty.activate def harvest(self, start_date='2015-03-14', end_date='2015-03-16'): request_url = 'http://validAI.edu/?from={}&to={}'.format(start_date, end_date) httpretty.register_uri(httpretty.GET, request_url, body=TEST_OAI_DOC, content_type=""application/XML"") records = self.get_records(request_url, start_date, end_date) return [RawDocument({ 'doc': str(TEST_OAI_DOC), 'source': 'crossref', 'filetype': 'XML', 'docID': ""1"" }) for record in records] class TestOAIHarvester(object): def setup_method(self, method): self.harvester = TestHarvester() def test_normalize(self): results = [ self.harvester.normalize(record) for record in self.harvester.harvest() ] for res in results: assert res['title'] == 'Test' ","from __future__ import unicode_literals import httpretty from scrapi.base import OAIHarvester from scrapi.linter import RawDocument from .utils import TEST_OAI_DOC class TestHarvester(OAIHarvester): base_url = '' long_name = 'Test' short_name = 'test' url = 'test' property_list = ['type', 'source', 'publisher', 'format', 'date'] @httpretty.activate def harvest(self, days_back=1): start_date = '2015-03-14' end_date = '2015-03-16' request_url = 'http://validAI.edu/?from={}&to={}'.format(start_date, end_date) httpretty.register_uri(httpretty.GET, request_url, body=TEST_OAI_DOC, content_type=""application/XML"") records = self.get_records(request_url, start_date, end_date) return [RawDocument({ 'doc': str(TEST_OAI_DOC), 'source': 'crossref', 'filetype': 'XML', 'docID': ""1"" }) for record in records] class TestOAIHarvester(object): def setup_method(self, method): self.harvester = TestHarvester() def test_normalize(self): results = [ self.harvester.normalize(record) for record in self.harvester.harvest() ] for res in results: assert res['title'] == 'Test' " Fix channel filtering to work properly,"#!/usr/bin/env python import os import yaml class ChannelFilter(object): def __init__(self, path=None): if path is None: path = os.path.join(os.path.dirname(__file__), 'channels.yaml') with open(path) as f: self.config = yaml.load(f) print(self.config) @property def firehose_channel(self): return self.config['firehose-channel'] @property def default_channel(self): return self.config['default-channel'] def all_channels(self): channels = [self.default_channel, self.firehose_channel] + list(self.config['channels']) return list(set(channels)) def channels_for(self, projects): """""" :param project: Get all channels to spam for given projects :type project: list """""" channels = set() for channel in self.config['channels']: for project in projects: if project in self.config['channels'][channel]: channels.add(channel) break if not channels: channels.add(self.default_channel) channels.add(self.firehose_channel) return channels ","#!/usr/bin/env python import os import yaml class ChannelFilter(object): def __init__(self, path=None): if path is None: path = os.path.join(os.path.dirname(__file__), 'channels.yaml') with open(path) as f: self.config = yaml.load(f) print(self.config) @property def firehose_channel(self): return self.config['firehose-channel'] @property def default_channel(self): return self.config['default-channel'] def all_channels(self): channels = [self.default_channel, self.firehose_channel] + list(self.config['channels']) return list(set(channels)) def channels_for(self, project): """""" :param project: Get all channels to spam for the given project :type project: basestring """""" channels = set() for channel in self.config['channels']: if project in self.config['channels'][channel]: channels.add(channel) continue if not channels: channels.add(self.default_channel) channels.add(self.firehose_channel) print(channels) return channels " Add more msgs for staff/user/new view,"from django.shortcuts import get_object_or_404, render, redirect from django.shortcuts import render from apps.staff.forms import NewUserForm from django.contrib.auth.models import User from django.contrib import messages def admin_view(request): return render(request, 'staff/base.jinja', {}) def users_new_view(request): if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] if User.objects.filter(email=email).exists(): messages.add_message(request, messages.ERROR, 'Username with\ that email already exists') else: User.objects.create_user( username = form.cleaned_data['username'], email = email, password = form.cleaned_data['password'], last_name = form.cleaned_data['last_name'], first_name = form.cleaned_data['first_name'] ) # messages = ""User created"" messages.add_message(request, messages.SUCCESS, 'User create!.') else: form = NewUserForm() messages.add_message(request, messages.INFO, 'This is a message!.') return render(request, 'staff/users/new.jinja', { 'form': form, }) ","from django.shortcuts import get_object_or_404, render, redirect from django.shortcuts import render from apps.staff.forms import NewUserForm from django.contrib.auth.models import User from django.contrib import messages def admin_view(request): return render(request, 'staff/base.jinja', {}) def users_new_view(request): if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] if User.objects.filter(email=email).exists(): # messages = ""User with that email already exists"" pass else: User.objects.create_user( username = form.cleaned_data['username'], email = email, password = form.cleaned_data['password'], last_name = form.cleaned_data['last_name'], first_name = form.cleaned_data['first_name'] ) # messages = ""User created"" else: form = NewUserForm() messages.add_message(request, messages.INFO, 'This is a message!.') return render(request, 'users/new.html', { 'form': form, # 'messages': messages }) " Remove commented-out line in testcase,"from mpi4py import MPI import mpiunittest as unittest class GReqCtx(object): source = 1 tag = 7 completed = False free_called = False def query(self, status): status.Set_source(self.source) status.Set_tag(self.tag) def free(self): self.free_called = True def cancel(self, completed): if completed is not self.completed: raise MPI.Exception(MPI.ERR_PENDING) class TestGrequest(unittest.TestCase): def testAll(self): ctx = GReqCtx() greq = MPI.Grequest.Start(ctx.query, ctx.free, ctx.cancel) self.assertFalse(greq.Test()) self.assertFalse(ctx.free_called) greq.Cancel() greq.Complete() ctx.completed = True greq.Cancel() status = MPI.Status() self.assertTrue(greq.Test(status)) self.assertEqual(status.Get_source(), ctx.source) self.assertEqual(status.Get_tag(), ctx.tag) greq.Wait() self.assertTrue(ctx.free_called) if MPI.Get_version() < (2, 0): del GReqCtx del TestGrequest if __name__ == '__main__': unittest.main() ","from mpi4py import MPI import mpiunittest as unittest class GReqCtx(object): source = 1 tag = 7 completed = False free_called = False def query(self, status): status.Set_source(self.source) status.Set_tag(self.tag) def free(self): self.free_called = True def cancel(self, completed): if completed is not self.completed: #raise AssertionError() raise MPI.Exception(MPI.ERR_PENDING) class TestGrequest(unittest.TestCase): def testAll(self): ctx = GReqCtx() greq = MPI.Grequest.Start(ctx.query, ctx.free, ctx.cancel) self.assertFalse(greq.Test()) self.assertFalse(ctx.free_called) greq.Cancel() greq.Complete() ctx.completed = True greq.Cancel() status = MPI.Status() self.assertTrue(greq.Test(status)) self.assertEqual(status.Get_source(), ctx.source) self.assertEqual(status.Get_tag(), ctx.tag) greq.Wait() self.assertTrue(ctx.free_called) if MPI.Get_version() < (2, 0): del GReqCtx del TestGrequest if __name__ == '__main__': unittest.main() " Fix auth redirect for non-rooted applications,"<?php namespace Beskhue\CookieTokenAuth\Controller\Component; use Cake\Controller\Component; use Cake\Routing\Router; /** * Redirect component. */ class RedirectComponent extends Component { public $components = ['Auth']; /** * Initialize properties. * * @param array $config The config data. * @return void */ public function initialize(array $config) { $this->controller = $this->_registry->getController(); } /** * Redirect the client to the cookie authentication page. * If a url is given, set Auth to return to that url after authentication. * * @param string $url The url to return the client to after authentication. */ public function redirectToAuthenticationPage($url = null) { if ($url) { $this->Auth->redirectUrl($url); } else { $this->Auth->redirectUrl($this->request->here(false)); } $this->controller->redirect(Router::url([ 'plugin' => 'Beskhue/CookieTokenAuth', 'controller' => 'CookieTokenAuth', '_base' => false ])); } /** * Redirect the client back to where they were before they were * sent to the cookie authentication page, or to the page specified * when calling the redirectToAuthenticationPage method. */ public function redirectBack() { $this->controller->redirect($this->Auth->redirectUrl()); } } ","<?php namespace Beskhue\CookieTokenAuth\Controller\Component; use Cake\Controller\Component; use Cake\Routing\Router; /** * Redirect component. */ class RedirectComponent extends Component { public $components = ['Auth']; /** * Initialize properties. * * @param array $config The config data. * @return void */ public function initialize(array $config) { $this->controller = $this->_registry->getController(); } /** * Redirect the client to the cookie authentication page. * If a url is given, set Auth to return to that url after authentication. * * @param string $url The url to return the client to after authentication. */ public function redirectToAuthenticationPage($url = null) { if ($url) { $this->Auth->redirectUrl($url); } else { $this->Auth->redirectUrl($this->request->here(false)); } $this->controller->redirect(Router::url([ 'plugin' => 'Beskhue/CookieTokenAuth', 'controller' => 'CookieTokenAuth' ])); } /** * Redirect the client back to where they were before they were * sent to the cookie authentication page, or to the page specified * when calling the redirectToAuthenticationPage method. */ public function redirectBack() { $this->controller->redirect($this->Auth->redirectUrl()); } } " Remove inline serving from webpack dev server,"const path = require('path'); const webpack = require('webpack'); module.exports = { entry: { home: path.join(__dirname, 'app/src/home'), }, module: { loaders: [ { test: /\.sass$/, loaders: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'], }, { test: /\.js$/, loader: 'babel-loader', exclude: 'node_modules', query: { presets: ['es2015'] }, }, { test: /\.(ttf|woff|woff2)$/, loader: 'file', query: { name: 'fonts/[name].[ext]' }, }, { test: /\.png$/, loader: 'file', }, { test: /\.html$/, loader: 'file-loader?name=[name].[ext]!extract-loader!html-loader', }, ], }, output: { path: path.join(__dirname, 'app/build'), publicPath: '/', filename: '[name].js', }, plugins: [ new webpack.optimize.UglifyJsPlugin({ minimize: true, compress: { warnings: false } }), ], // -------------------------------------------------------------------------- devServer: { contentBase: path.join(__dirname, 'app/build'), }, }; ","const path = require('path'); const webpack = require('webpack'); module.exports = { entry: { home: path.join(__dirname, 'app/src/home'), }, module: { loaders: [ { test: /\.sass$/, loaders: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'], }, { test: /\.js$/, loader: 'babel-loader', exclude: 'node_modules', query: { presets: ['es2015'] }, }, { test: /\.(ttf|woff|woff2)$/, loader: 'file', query: { name: 'fonts/[name].[ext]' }, }, { test: /\.png$/, loader: 'file', }, { test: /\.html$/, loader: 'file-loader?name=[name].[ext]!extract-loader!html-loader', }, ], }, output: { path: path.join(__dirname, 'app/build'), publicPath: '/', filename: '[name].js', }, plugins: [ new webpack.optimize.UglifyJsPlugin({ minimize: true, compress: { warnings: false } }), ], // -------------------------------------------------------------------------- devServer: { contentBase: path.join(__dirname, 'app/build'), inline: true, }, }; " Change left-right for test CI,"'use strict'; var MAX = 1000; function Node( number ){ this.number = 0; this.parent = null; this.left = null; this.right = null; this.depth = 0; if( number === undefined ){ this.number = Math.floor((Math.random() * MAX) + 1); } else{ this.number = number; } } function Tree(){ this.list = []; this.root = null; } Tree.prototype.insert = function( number ){ var node = new Node( number ); if( this.root === null || this.root === undefined ){ this.root = node; } else{ var parentNode = this.root; while( true ){ if( parentNode.number < node.number ){ if( parentNode.left === null ){ parentNode.left = node; node.parent = parentNode; node.depth = parentNode.depth + 1; break; } else{ parentNode = parentNode.left; } } else{ if( parentNode.right === null ){ parentNode.right = node; node.parent = parentNode; node.depth = parentNode.depth + 1; break; } else{ parentNode = parentNode.right; } } } } this.list.push( node ); }; /* // TODO Tree.prototype.delete = function( node ) { }; */ ","'use strict'; var MAX = 1000; function Node( number ){ this.number = 0; this.parent = null; this.left = null; this.right = null; this.depth = 0; if( number === undefined ){ this.number = Math.floor((Math.random() * MAX) + 1); } else{ this.number = number; } } function Tree(){ this.list = []; this.root = null; } Tree.prototype.insert = function( number ){ var node = new Node( number ); if( this.root === null || this.root === undefined ){ this.root = node; } else{ var parentNode = this.root; while( true ){ if( parentNode.number > node.number ){ if( parentNode.left === null ){ parentNode.left = node; node.parent = parentNode; node.depth = parentNode.depth + 1; break; } else{ parentNode = parentNode.left; } } else{ if( parentNode.right === null ){ parentNode.right = node; node.parent = parentNode; node.depth = parentNode.depth + 1; break; } else{ parentNode = parentNode.right; } } } } this.list.push( node ); }; /* // TODO Tree.prototype.delete = function( node ) { }; */ " "Remove unused method; suppress unchecked cast warnings git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@1836 0d517254-b314-0410-acde-c619094fa49f","package edu.northwestern.bioinformatics.studycalendar.dao; import edu.northwestern.bioinformatics.studycalendar.domain.Role; import edu.northwestern.bioinformatics.studycalendar.domain.StudySubjectAssignment; import edu.northwestern.bioinformatics.studycalendar.domain.User; import edu.nwu.bioinformatics.commons.CollectionUtils; import java.util.List; import java.io.Serializable; public class UserDao extends StudyCalendarMutableDomainObjectDao<User> implements Serializable { @Override public Class<User> domainClass() { return User.class; } @SuppressWarnings({ ""unchecked"" }) public List<User> getAll() { return getHibernateTemplate().find(""from User order by name""); } @SuppressWarnings({ ""unchecked"" }) public User getByName(String name) { return (User) CollectionUtils.firstElement(getHibernateTemplate().find(""from User where name = ?"", name)); } @SuppressWarnings({ ""unchecked"" }) public List<StudySubjectAssignment> getAssignments(User user) { return (List<StudySubjectAssignment>) getHibernateTemplate().find( ""from StudySubjectAssignment a where a.subjectCoordinator = ? "", user); } public List<User> getAllSubjectCoordinators() { return getByRole(Role.SUBJECT_COORDINATOR); } @SuppressWarnings({ ""unchecked"" }) public List<User> getByRole(Role role) { return getHibernateTemplate() .find(""select u from User u join u.userRoles r where r.role = ? order by u.name"", role); } } ","package edu.northwestern.bioinformatics.studycalendar.dao; import edu.northwestern.bioinformatics.studycalendar.domain.*; import edu.northwestern.bioinformatics.studycalendar.StudyCalendarError; import edu.nwu.bioinformatics.commons.CollectionUtils; import java.util.List; import java.io.Serializable; public class UserDao extends StudyCalendarMutableDomainObjectDao<User> implements Serializable { @Override public Class<User> domainClass() { return User.class; } public List<User> getAll() { return getHibernateTemplate().find(""from User order by name""); } public User getByName(String name) { List<User> results = getHibernateTemplate().find(""from User where name = ?"", name); if (results.size() == 0) { return null; } return results.get(0); } public List getByCsmUserId(Long csmUserId) { List<User> results = getHibernateTemplate().find(""from User where csm_user_id = ?"", csmUserId); return results; } public List<StudySubjectAssignment> getAssignments(User user) { List<StudySubjectAssignment> results = getHibernateTemplate().find( ""from StudySubjectAssignment a where a.subjectCoordinator = ? "", user); return results; } public List<User> getAllSubjectCoordinators() { return getByRole(Role.SUBJECT_COORDINATOR); } public List<User> getByRole(Role role) { return getHibernateTemplate() .find(""select u from User u join u.userRoles r where r.role = ? order by u.name"", role); } } " Test changes in develop branch,"<?php /* DEVELOPMENT BRANCH */ /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/ZendSkeletonModule for the canonical source repository * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Angrybirds; use Zend\ModuleManager\Feature\AutoloaderProviderInterface; use Zend\ModuleManager\Feature\ConfigProviderInterface; class Module implements AutoloaderProviderInterface, ConfigProviderInterface { public function getAutoloaderConfig() { return array( 'Zend\Loader\ClassMapAutoloader' => array( __DIR__ . '/autoload_classmap.php', ), 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( // if we're in a namespace deeper than one level we need to fix the \ in the path __NAMESPACE__ => __DIR__ . '/src/' . str_replace('\\', '/' , __NAMESPACE__), ), ), ); } public function getConfig() { return include __DIR__ . '/config/module.config.php'; } /*public function onBootstrap($e) { // You may not need to do this if you're doing it elsewhere in your // application $eventManager = $e->getApplication()->getEventManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); }*/ } ","<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/ZendSkeletonModule for the canonical source repository * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Angrybirds; use Zend\ModuleManager\Feature\AutoloaderProviderInterface; use Zend\ModuleManager\Feature\ConfigProviderInterface; class Module implements AutoloaderProviderInterface, ConfigProviderInterface { public function getAutoloaderConfig() { return array( 'Zend\Loader\ClassMapAutoloader' => array( __DIR__ . '/autoload_classmap.php', ), 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( // if we're in a namespace deeper than one level we need to fix the \ in the path __NAMESPACE__ => __DIR__ . '/src/' . str_replace('\\', '/' , __NAMESPACE__), ), ), ); } public function getConfig() { return include __DIR__ . '/config/module.config.php'; } /*public function onBootstrap($e) { // You may not need to do this if you're doing it elsewhere in your // application $eventManager = $e->getApplication()->getEventManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); }*/ } " Fix models section always being active,"<section class=""sidebar""> <ul class=""sidebar-menu""> @foreach ($menu as $menuItem) <li class=""{{ ($menuItem['route'] == Route::currentRouteName()) ? 'active' : '' }}""> <a href=""{{ URL::route($menuItem['route']) }}""> {!! $menuItem['icon'] !!} <span> {{ $menuItem['title'] }} </span> </a> </li> @endforeach <li class=""treeview {{ isset($model) ? 'active' : '' }}""> <a href=""#""> <i class=""fa fa-th""></i> <span>Models</span> <i class=""fa fa-angle-left pull-right""></i> </a> <ul class=""treeview-menu""> @foreach ($models as $model) @if ( ! $model->hidden) <li class=""{{ ('admin.model.all' == Route::currentRouteName() && Route::current()->getParameter('slug') == $model->route) ? 'active' : '' }}""> <a href=""{{ route('admin.model.all', ['slug' => $model->route]) }}""> <i class=""fa fa-angle-right""></i> <span>{{ $model->title }}</span> </a> </li> @endif @endforeach </ul> </li> </ul> </section> <!-- /.sidebar -->","<section class=""sidebar""> <ul class=""sidebar-menu""> @foreach ($menu as $menuItem) <li class=""{{ ($menuItem['route'] == Route::currentRouteName()) ? 'active' : '' }}""> <a href=""{{ URL::route($menuItem['route']) }}""> {!! $menuItem['icon'] !!} <span> {{ $menuItem['title'] }} </span> </a> </li> @endforeach <li class=""treeview active""> <a href=""#""> <i class=""fa fa-th""></i> <span>Models</span> <i class=""fa fa-angle-left pull-right""></i> </a> <ul class=""treeview-menu""> @foreach ($models as $model) @if ( ! $model->hidden) <li class=""{{ ('admin.model.all' == Route::currentRouteName() && Route::current()->getParameter('slug') == $model->route) ? 'active' : '' }}""> <a href=""{{ route('admin.model.all', ['slug' => $model->route]) }}""> <i class=""fa fa-angle-right""></i> {{ $model->title }} </a> </li> @endif @endforeach </ul> </li> </ul> </section> <!-- /.sidebar -->" Fix when depth becomes zero.,"<?php namespace Yajra\CMS\Presenters; use Laracasts\Presenter\Presenter; use Yajra\CMS\Contracts\UrlGenerator; class MenuPresenter extends Presenter { /** * Link href target window. * * @return string */ public function target() { return $this->entity->target == 0 ? '_self' : '_blank'; } /** * Indented title against depth. * * @param int $start * @param string $symbol * @return string */ public function indentedTitle($start = 1, $symbol = '— ') { $depth = $this->entity->depth ?? 1; return str_repeat($symbol, $depth - $start) . ' ' . $this->entity->title; } /** * Generate menu url depending on type the menu. * * @return string */ public function url() { /** @var \Yajra\CMS\Repositories\Extension\Repository $repository */ $repository = app('extensions'); /** @var \Yajra\CMS\Entities\Extension $extension */ $extension = $repository->findOrFail($this->entity->extension_id); $class = $extension->param('class'); if (class_exists($class)) { $entity = app($class)->findOrNew($this->entity->param('id')); if ($entity instanceof UrlGenerator) { return $entity->getUrl($extension->param('data')); } } return $this->entity->url; } } ","<?php namespace Yajra\CMS\Presenters; use Laracasts\Presenter\Presenter; use Yajra\CMS\Contracts\UrlGenerator; class MenuPresenter extends Presenter { /** * Link href target window. * * @return string */ public function target() { return $this->entity->target == 0 ? '_self' : '_blank'; } /** * Indented title against depth. * * @param int $start * @param string $symbol * @return string */ public function indentedTitle($start = 1, $symbol = '— ') { return str_repeat($symbol, $this->entity->depth - $start) . ' ' . $this->entity->title; } /** * Generate menu url depending on type the menu. * * @return string */ public function url() { /** @var \Yajra\CMS\Repositories\Extension\Repository $repository */ $repository = app('extensions'); /** @var \Yajra\CMS\Entities\Extension $extension */ $extension = $repository->findOrFail($this->entity->extension_id); $class = $extension->param('class'); if (class_exists($class)) { $entity = app($class)->findOrNew($this->entity->param('id')); if ($entity instanceof UrlGenerator) { return $entity->getUrl($extension->param('data')); } } return $this->entity->url; } } " Add smarter default behaviour for validateOptions.,"var Generator = require('generate-js'), Joi = require('joi'), async = require('async'); var EndPoint = Generator.generate(function EndPoint(options) { var _ = this; options.validateOptions = options.validateOptions || { abortEarly: false, stripUnknown: true }; _.defineProperties(options); _.debug = false; }); EndPoint.Joi = Joi; EndPoint.definePrototype({ incomingSchema: Joi.object(), outgoingSchema: Joi.object(), run: function run(data, done) { var _ = this; function validateIncoming(next) { _.debug && console.log(""validateIncoming"", data); Joi.validate(data, _.incomingSchema, _.validateOptions, next); } function runIncoming(data, next) { _.debug && console.log(""runIncoming"", data); _.incoming(data, next); } function validateOutgoing(data, next) { console.log(""validateOutgoing"", data); Joi.validate(data, _.outgoingSchema, _.validateOptions, next); } function runOutgoing(data, next) { _.debug && console.log(""runOutgoing"", data); _.outgoing(data, next); } async.waterfall([ validateIncoming, runIncoming, validateOutgoing, runOutgoing ], done); }, incoming: function incoming(data, done) { var _ = this; done(null, data); }, outgoing: function outgoing(data, done) { var _ = this; done(null, data); } }); module.exports = EndPoint; ","var Generator = require('generate-js'), Joi = require('joi'), async = require('async'); var EndPoint = Generator.generate(function EndPoint(options) { var _ = this; _.defineProperties(options); _.debug = false; }); EndPoint.Joi = Joi; EndPoint.definePrototype({ incomingSchema: Joi.object(), outgoingSchema: Joi.object(), run: function run(data, done) { var _ = this; function validateIncoming(next) { _.debug && console.log(""validateIncoming"", data); Joi.validate(data, _.incomingSchema, _.validateOptions, next); } function runIncoming(data, next) { _.debug && console.log(""runIncoming"", data); _.incoming(data, next); } function validateOutgoing(data, next) { console.log(""validateOutgoing"", data); Joi.validate(data, _.outgoingSchema, _.validateOptions, next); } function runOutgoing(data, next) { _.debug && console.log(""runOutgoing"", data); _.outgoing(data, next); } async.waterfall([ validateIncoming, runIncoming, validateOutgoing, runOutgoing ], done); }, incoming: function incoming(data, done) { var _ = this; done(null, data); }, outgoing: function outgoing(data, done) { var _ = this; done(null, data); } }); module.exports = EndPoint; " Add a basic initial git setup on the new project,"'use strict'; var yeoman = require('yeoman-generator'); var prompts = require('./prompts'); var _ = require('lodash'); module.exports = yeoman.Base.extend({ initializing: function() { this.appName = this.fs.readJSON(this.destinationPath('package.json')).name; }, prompting: prompts, writing: function () { if (this.envFile) { this.fs.write(this.destinationPath('.env'), this.envFile); } else { this.fs.copyTpl( this.templatePath('.env'), this.destinationPath('.env'), { appName: _.snakeCase(this.appName) } ); } }, install: function () { this.spawnCommand('git', [ 'init' ]) .on('exit', () => { this.spawnCommand('git', [ 'add', '.' ]) .on('exit', () => { this.spawnCommand('git', [ 'commit', '-m', 'Initial commit' ]); }); }); this.npmInstall(); this.spawnCommand('gem', [ 'install', 'bundler', '--conservative' ]) .on('exit', (code) => { if (!code) { this.spawnCommand('ruby', [ this.destinationPath('bin', 'bundle'), 'install' ]) .on('exit', (code) => { if (!code) { this.spawnCommand('ruby', [ this.destinationPath('bin', 'rails'), 'db:setup' ]); this.spawnCommand('ruby', [ this.destinationPath('bin', 'rails'), 'log:clear', 'tmp:clear' ]); } }); } }); } }); ","'use strict'; var yeoman = require('yeoman-generator'); var prompts = require('./prompts'); var _ = require('lodash'); module.exports = yeoman.Base.extend({ initializing: function() { this.appName = this.fs.readJSON(this.destinationPath('package.json')).name; }, prompting: prompts, writing: function () { if (this.envFile) { this.fs.write(this.destinationPath('.env'), this.envFile); } else { this.fs.copyTpl( this.templatePath('.env'), this.destinationPath('.env'), { appName: _.snakeCase(this.appName) } ); } }, install: function () { this.npmInstall(); this.spawnCommand('gem', [ 'install', 'bundler', '--conservative' ]) .on('exit', (code) => { if (!code) { this.spawnCommand('ruby', [ this.destinationPath('bin', 'bundle'), 'install' ]) .on('exit', (code) => { if (!code) { this.spawnCommand('ruby', [ this.destinationPath('bin', 'rails'), 'db:setup' ]); this.spawnCommand('ruby', [ this.destinationPath('bin', 'rails'), 'log:clear', 'tmp:clear' ]); } }); } }); } }); " Make TPC check work on chrome again,"// buffer-tpc-check.js // (c) 2013 Sunil Sadasivan // Check if third party cookies are disabled // ;(function () { ;(function check() { //if the 3rd party cookies check is done, remove the iframe if((self.port) || (xt && xt.options)) { bufferpm.bind(""buffer_3pc_done"", function(){ elem = document.getElementById('buffer_tpc_check'); if(elem) { elem.parentNode.removeChild(elem); } return false; }); //if the 3rd party cookies check is disabled, store it bufferpm.bind(""buffer_3pc_disabled"", function(){ if(xt && xt.options) { xt.options['buffer.op.tpc-disabled'] = true; } self.port.emit('buffer_tpc_disabled'); return false; }); var iframe = document.createElement('iframe'); iframe.id = 'buffer_tpc_check'; iframe.src = 'https://d3ijcis4e2ziok.cloudfront.net/tpc-check.html'; //iframe.src = 'http://local.bufferapp.com/js/tpc-check.html'; iframe.style.display=""none""; document.body.appendChild(iframe); } else { setTimeout(check, 50); } }()); }()); ","// buffer-tpc-check.js // (c) 2013 Sunil Sadasivan // Check if third party cookies are disabled // ;(function () { ;(function check() { //if the 3rd party cookies check is done, remove the iframe if(self.port) { bufferpm.bind(""buffer_3pc_done"", function(){ elem = document.getElementById('buffer_tpc_check'); if(elem) { elem.parentNode.removeChild(elem); } return false; }); //if the 3rd party cookies check is disabled, store it bufferpm.bind(""buffer_3pc_disabled"", function(){ if(xt && xt.options) { xt.options['buffer.op.tpc-disabled'] = true; } self.port.emit('buffer_tpc_disabled'); return false; }); var iframe = document.createElement('iframe'); iframe.id = 'buffer_tpc_check'; iframe.src = 'https://d3ijcis4e2ziok.cloudfront.net/tpc-check.html'; //iframe.src = 'http://local.bufferapp.com/js/tpc-check.html'; iframe.style.display=""none""; document.body.appendChild(iframe); } else { setTimeout(check, 50); } }()); }()); " Add test when error is unknown,"require('rootpath')(); const Hapi = require('hapi'); const { describe, it, expect, sinon, before, after, beforeEach, afterEach } = require('tests/helper'); const route = require('app/features/events'); const eventHandler = require('app/features/events/eventHandler'); describe('Unit | Route | Event Index ', function() { let server; beforeEach(() => { server = require('server').BootStrapTestHelper('events'); }); afterEach(() => { server.stop(); }); describe('Server', () => { it('should have an object, version, and name attribute', () => { // then expect(route.register.attributes).to.exist; expect(route.register.attributes).to.be.an('object'); expect(route.register.attributes.name).to.equal('events-api'); expect(route.register.attributes).to.have.property('version'); }); }); describe('Route POST /api/events', () => { before(() => { sinon.stub(eventHandler, 'create').callsFake((request, reply) => reply('ok')); }); after(() => { eventHandler.create.restore(); }); it('should exist', () => { // when return server.inject({ method: 'POST', url: '/api/events', payload: { host: {}, event: {} } }).then((res) => { // then expect(res.statusCode).to.equal(200); }); }); }); });","require('rootpath')(); const Hapi = require('hapi'); const { describe, it, expect, sinon, before, after, beforeEach, afterEach } = require('tests/helper'); const route = require('app/features/events'); const eventHandler = require('app/features/events/eventHandler'); describe('Unit | Route | Event Index ', function() { let server; beforeEach(() => { server = require('server').BootStrapTestHelper('events'); }); afterEach(() => { server.stop(); }); describe('Server', () => { it('should have an object, version, and name attribute', () => { // then expect(route.register.attributes).to.exist; expect(route.register.attributes).to.be.an('object'); expect(route.register.attributes.name).to.equal('events-api'); expect(route.register.attributes).to.have.property('version'); }); }); describe('Route POST /api/events', () => { before(() => { sinon.stub(eventHandler, 'create').callsFake((request, reply) => reply('ok')); }); after(() => { eventHandler.create.restore(); }); it('should exist', () => { // when return server.inject({ method: 'POST', url: '/api/events', payload: { username: 'Flo' } }).then((res) => { // then expect(res.statusCode).to.equal(200); }); }); }); });" Create variable with all js files,"module.exports = function (grunt) { 'use strict'; var jsFiles = [ 'Gruntfile.js', 'generators/**/*.js' ]; grunt.initConfig({ jshint: { files: jsFiles, options: { jshintrc: '.jshintrc' } }, bump: { options: { files: ['package.json'], commit: false, createTag: false, push: false } }, watch: { options: { spawn: false }, scripts: { files: jsFiles, tasks: ['jshint'] } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-bump'); grunt.registerTask('test', ['jshint']); grunt.registerTask('default', ['watch']); }; ","module.exports = function (grunt) { 'use strict'; grunt.initConfig({ jshint: { files: [ 'Gruntfile.js', 'generators/**/*.js' ], options: { jshintrc: '.jshintrc' } }, bump: { options: { files: ['package.json'], commit: false, createTag: false, push: false } }, watch: { options: { spawn: false }, scripts: { files: [ 'generators/**/*.js', 'Gruntfile.js' ], tasks: ['jshint'] } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-bump'); grunt.registerTask('test', ['jshint']); grunt.registerTask('default', ['watch']); }; " "Fix merge conflict & add 3rd paramater for map function; false for directory, true for file","var fs = require('fs'); module.exports = function requireAll(options) { if (typeof options === 'string') { options = { dirname: options, filter: /(.+)\.js(on)?$/, excludeDirs: /^\.(git|svn)$/, params: params }; } var files = fs.readdirSync(options.dirname); var modules = {}; var resolve = options.resolve || identity; var map = options.map || identity; var mapSubDirectoryNames = typeof options.mapSubDirectoryNames === ""undefined"" ? true : options.mapSubDirectoryNames function excludeDirectory(dirname) { return options.excludeDirs && dirname.match(options.excludeDirs); } files.forEach(function (file) { var filepath = options.dirname + '/' + file; if (fs.statSync(filepath).isDirectory()) { if (excludeDirectory(file)) return; if (mapSubDirectoryNames){ file = map(file, filepath, false); } modules[file] = requireAll({ dirname: filepath, filter: options.filter, excludeDirs: options.excludeDirs, resolve: resolve, map: map }); } else { var match = file.match(options.filter); if (!match) return; if(!options.params) { modules[map(match[1], filepath, true)] = resolve(require(filepath)); } else { modules[map(match[1], filepath, true)] = resolve(require(filepath))(params); } } }); return modules; }; function identity(val) { return val; } ","var fs = require('fs'); module.exports = function requireAll(options) { if (typeof options === 'string') { options = { dirname: options, filter: /(.+)\.js(on)?$/, excludeDirs: /^\.(git|svn)$/, params: params }; } var files = fs.readdirSync(options.dirname); var modules = {}; var resolve = options.resolve || identity; var map = options.map || identity; var mapSubDirectoryNames = typeof options.mapSubDirectoryNames === ""undefined"" ? true : options.mapSubDirectoryNames function excludeDirectory(dirname) { return options.excludeDirs && dirname.match(options.excludeDirs); } files.forEach(function (file) { var filepath = options.dirname + '/' + file; if (fs.statSync(filepath).isDirectory()) { if (excludeDirectory(file)) return; if (mapSubDirectoryNames){ file = map(file, filepath); } modules[file] = requireAll({ dirname: filepath, filter: options.filter, excludeDirs: options.excludeDirs, resolve: resolve, map: map }); } else { var match = file.match(options.filter); if (!match) return; if(!options.params) { modules[match[1]] = resolve(require(filepath)); } else { modules[match[1]] = resolve(require(filepath))(params); } } }); return modules; }; function identity(val) { return val; } " "Move is_sticky field into post's advanced options For #13","# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.contrib import admin from adminsortable.admin import SortableAdmin from glitter import block_admin from glitter.admin import GlitterAdminMixin, GlitterPagePublishedFilter from .models import Category, LatestNewsBlock, Post @admin.register(Category) class CategoryAdmin(SortableAdmin): prepopulated_fields = { 'slug': ('title',) } @admin.register(Post) class PostAdmin(GlitterAdminMixin, admin.ModelAdmin): date_hierarchy = 'date' list_display = ('title', 'date', 'category', 'is_published', 'is_sticky') list_filter = (GlitterPagePublishedFilter, 'date', 'category') prepopulated_fields = { 'slug': ('title',) } def get_fieldsets(self, request, obj=None): advanced_options = ['published', 'is_sticky', 'slug'] if getattr(settings, 'GLITTER_NEWS_TAGS', False): advanced_options.append('tags') fieldsets = ( ('Post', { 'fields': ('title', 'category', 'author', 'date', 'image', 'summary', 'tags') }), ('Advanced options', { 'fields': advanced_options }), ) return fieldsets block_admin.site.register(LatestNewsBlock) block_admin.site.register_block(LatestNewsBlock, 'App Blocks') ","# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.contrib import admin from adminsortable.admin import SortableAdmin from glitter import block_admin from glitter.admin import GlitterAdminMixin, GlitterPagePublishedFilter from .models import Category, LatestNewsBlock, Post @admin.register(Category) class CategoryAdmin(SortableAdmin): prepopulated_fields = { 'slug': ('title',) } @admin.register(Post) class PostAdmin(GlitterAdminMixin, admin.ModelAdmin): date_hierarchy = 'date' list_display = ('title', 'date', 'category', 'is_sticky', 'is_published') list_filter = (GlitterPagePublishedFilter, 'date', 'category') prepopulated_fields = { 'slug': ('title',) } def get_fieldsets(self, request, obj=None): advanced_options = ['published', 'slug'] if getattr(settings, 'GLITTER_NEWS_TAGS', False): advanced_options.append('tags') fieldsets = ( ('Post', { 'fields': ( 'title', 'category', 'is_sticky', 'author', 'date', 'image', 'summary', 'tags', ) }), ('Advanced options', { 'fields': advanced_options }), ) return fieldsets block_admin.site.register(LatestNewsBlock) block_admin.site.register_block(LatestNewsBlock, 'App Blocks') " "Allow to manually set size. Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>","<?php namespace Orchestra\Avatar\Handlers; use Illuminate\Support\Arr; use Orchestra\Avatar\Handler; use Orchestra\Avatar\HandlerInterface; class Gravatar extends Handler implements HandlerInterface { /** * Service URL. */ const URL = 'http://www.gravatar.com/avatar'; /** * {@inheritdoc} */ protected $name = 'gravatar'; /** * {@inheritdoc} */ public function render() { $url = sprintf( '%s/%s?s=%d', static::URL, $this->getGravatarIdentifier(), $this->getGravatarSize() ); if (! is_null($default = Arr::get($this->config, 'gravatar.default'))) { $url .= ""&d="".urlencode($default); } return $url; } /** * Get Gravatar identifier. * * @return string */ protected function getGravatarIdentifier() { return md5(strtolower(trim($this->getIdentifier()))); } /** * Get Gravatar size. * * @return mixed */ protected function getGravatarSize() { $size = $this->getSize(); return Arr::get($this->config, ""sizes.{$size}"", (is_int($size) ? $size : 'small')); } } ","<?php namespace Orchestra\Avatar\Handlers; use Illuminate\Support\Arr; use Orchestra\Avatar\Handler; use Orchestra\Avatar\HandlerInterface; class Gravatar extends Handler implements HandlerInterface { /** * Service URL. */ const URL = 'http://www.gravatar.com/avatar'; /** * {@inheritdoc} */ protected $name = 'gravatar'; /** * {@inheritdoc} */ public function render() { $url = sprintf( '%s/%s?s=%d', static::URL, $this->getGravatarIdentifier(), $this->getGravatarSize() ); if (! is_null($default = Arr::get($this->config, 'gravatar.default'))) { $url .= ""&d="".urlencode($default); } return $url; } /** * Get Gravatar identifier. * * @return string */ protected function getGravatarIdentifier() { return md5(strtolower(trim($this->getIdentifier()))); } /** * Get Gravatar size. * * @return mixed */ protected function getGravatarSize() { $size = $this->getSize(); return Arr::get($this->config, ""sizes.{$size}"", 'small'); } } " Rename descriptors -> rval to avoid confusion,""""""" Basic molecular features. """""" __author__ = ""Steven Kearnes"" __copyright__ = ""Copyright 2014, Stanford University"" __license__ = ""BSD 3-clause"" from rdkit.Chem import Descriptors from pande_gas.features import Featurizer class MolecularWeight(Featurizer): """""" Molecular weight. """""" name = ['mw', 'molecular_weight'] def _featurize(self, mol): """""" Calculate molecular weight. Parameters ---------- mol : RDKit Mol Molecule. """""" wt = Descriptors.ExactMolWt(mol) wt = [wt] return wt class SimpleDescriptors(Featurizer): """""" RDKit descriptors. See http://rdkit.org/docs/GettingStartedInPython.html #list-of-available-descriptors. """""" name = 'descriptors' def __init__(self): self.descriptors = [] self.functions = [] for descriptor, function in Descriptors.descList: self.descriptors.append(descriptor) self.functions.append(function) def _featurize(self, mol): """""" Calculate RDKit descriptors. Parameters ---------- mol : RDKit Mol Molecule. """""" rval = [] for function in self.functions: rval.append(function(mol)) return rval ",""""""" Basic molecular features. """""" __author__ = ""Steven Kearnes"" __copyright__ = ""Copyright 2014, Stanford University"" __license__ = ""BSD 3-clause"" from rdkit.Chem import Descriptors from pande_gas.features import Featurizer class MolecularWeight(Featurizer): """""" Molecular weight. """""" name = ['mw', 'molecular_weight'] def _featurize(self, mol): """""" Calculate molecular weight. Parameters ---------- mol : RDKit Mol Molecule. """""" wt = Descriptors.ExactMolWt(mol) wt = [wt] return wt class SimpleDescriptors(Featurizer): """""" RDKit descriptors. See http://rdkit.org/docs/GettingStartedInPython.html #list-of-available-descriptors. """""" name = 'descriptors' def __init__(self): self.descriptors = [] self.functions = [] for descriptor, function in Descriptors.descList: self.descriptors.append(descriptor) self.functions.append(function) def _featurize(self, mol): """""" Calculate RDKit descriptors. Parameters ---------- mol : RDKit Mol Molecule. """""" descriptors = [] for function in self.functions: descriptors.append(function(mol)) return descriptors " Add class names to views when a require path is available,";(function(Agent){ var patchViewChanges = _.debounce(function(view, prop, action, difference, oldValue) { Agent.lazyWorker.push({ context: Agent, args: [view], callback: function(view) { Agent.sendAppComponentReport('view:change', { cid: view.cid, data: Agent.serializeView(view) }); } }); }, 200); // @private Agent.patchBackboneView = function(BackboneView) { debug.log('Backbone.View detected'); Agent.patchBackboneComponent(BackboneView, function(view) { // on new instance Agent.lazyWorker.push({ context: Agent, args: [view], callback: function(view) { // registra il nuovo componente dell'app var data = Agent.serializeView(view) Agent.registerAppComponent('View', view, data); Agent.sendAppComponentReport('view:change', { data: data, cid: view.cid }); } }); // set class name if we can if (view._requirePath) { view._className = _.last(view._requirePath.split('/')); } // Patcha i metodi del componente dell'app Agent.patchAppComponentTrigger(view, 'view'); Agent.onDefined(view, 'ui', function() { Agent.onChange(view.ui, _.partial(patchViewChanges, view)); patchViewChanges(view); }); Agent.onDefined(view, '_events', function() { Agent.onChange(view._events, _.partial(patchViewChanges, view)); patchViewChanges(view); }); }); }; }(Agent)); ",";(function(Agent){ var patchViewChanges = _.debounce(function(view, prop, action, difference, oldValue) { Agent.lazyWorker.push({ context: Agent, args: [view], callback: function(view) { Agent.sendAppComponentReport('view:change', { cid: view.cid, data: Agent.serializeView(view) }); } }); }, 200); // @private Agent.patchBackboneView = function(BackboneView) { debug.log('Backbone.View detected'); Agent.patchBackboneComponent(BackboneView, function(view) { // on new instance Agent.lazyWorker.push({ context: Agent, args: [view], callback: function(view) { // registra il nuovo componente dell'app var data = Agent.serializeView(view) Agent.registerAppComponent('View', view, data); Agent.sendAppComponentReport('view:change', { data: data, cid: view.cid }); } }); // Patcha i metodi del componente dell'app Agent.patchAppComponentTrigger(view, 'view'); Agent.onDefined(view, 'ui', function() { Agent.onChange(view.ui, _.partial(patchViewChanges, view)); patchViewChanges(view); }); Agent.onDefined(view, '_events', function() { Agent.onChange(view._events, _.partial(patchViewChanges, view)); patchViewChanges(view); }); }); }; }(Agent)); " Use a more obvious check for transitions,"import React from 'react'; import Relay from 'react-relay'; import Container from './Container'; import RouteAggregator from './RouteAggregator'; export default class RootComponent extends React.Component { static displayName = 'ReactRouterRelay.RootComponent'; static propTypes = { location: React.PropTypes.object.isRequired, }; static childContextTypes = { routeAggregator: React.PropTypes.instanceOf(RouteAggregator).isRequired, }; constructor(props, context) { super(props, context); this._routeAggregator = new RouteAggregator(); this._routeAggregator.updateRoute(props); } getChildContext() { return { routeAggregator: this._routeAggregator, }; } componentWillReceiveProps(nextProps) { if (nextProps.location === this.props.location) { return; } this._routeAggregator.updateRoute(nextProps); } renderLoading = () => { this._routeAggregator.setLoading(); return this.renderComponent(); }; renderFetched = (data) => { this._routeAggregator.setFetched(data); return this.renderComponent(); }; renderFailure = (error, retry) => { this._routeAggregator.setFailure(error, retry); return this.renderComponent(); }; renderComponent() { return <Container {...this.props} />; } render() { return ( <Relay.RootContainer Component={this._routeAggregator} route={this._routeAggregator.route} renderLoading={this.renderLoading} renderFetched={this.renderFetched} renderFailure={this.renderFailure} /> ); } } ","import React from 'react'; import Relay from 'react-relay'; import Container from './Container'; import RouteAggregator from './RouteAggregator'; export default class RootComponent extends React.Component { static displayName = 'ReactRouterRelay.RootComponent'; static propTypes = { routes: React.PropTypes.array.isRequired, }; static childContextTypes = { routeAggregator: React.PropTypes.instanceOf(RouteAggregator).isRequired, }; constructor(props, context) { super(props, context); this._routeAggregator = new RouteAggregator(); this._routeAggregator.updateRoute(props); } getChildContext() { return { routeAggregator: this._routeAggregator, }; } componentWillReceiveProps(nextProps) { if (nextProps.routes === this.props.routes) { return; } this._routeAggregator.updateRoute(nextProps); } renderLoading = () => { this._routeAggregator.setLoading(); return this.renderComponent(); }; renderFetched = (data) => { this._routeAggregator.setFetched(data); return this.renderComponent(); }; renderFailure = (error, retry) => { this._routeAggregator.setFailure(error, retry); return this.renderComponent(); }; renderComponent() { return <Container {...this.props} />; } render() { return ( <Relay.RootContainer Component={this._routeAggregator} route={this._routeAggregator.route} renderLoading={this.renderLoading} renderFetched={this.renderFetched} renderFailure={this.renderFailure} /> ); } } " Add an example of TreeBuilder.buildRawHtml(),"class View { static render(state){ return TreeBuilder.build(h => h(""div"", {} , h(""button"", {}, ""OK"") , h(""input"", { type: ""checkbox"" }) , h(""a"", { href: ""#"" }, ""link "" + state.val) , h(""button"", { onclick: ()=>{ __p.onclick_reloadLibs(); } } , ""reload libs"" ) , TreeBuilder.buildRawHtml('aa <em>em</em> bb <span onclick=""alert(123)"">click</span>') ) ); } } class Page { constructor(){ this.state = {}; } getTitle(){ return ""sinatra-skelton""; } onclick_reloadLibs(){ __g.api_v2(""get"", ""/api/reload_libs"", {}, (result)=>{ __g.unguard(); }, (errors)=>{ __g.unguard(); __g.printApiErrors(errors); alert(""Check console.""); }); } init(){ puts(""init""); __g.api_v2(""get"", ""/api/sample"", { fooBar: 123, b: { c: 456 } }, (result)=>{ __g.unguard(); puts(result); Object.assign(this.state, result); this.render(); }, (errors)=>{ __g.unguard(); __g.printApiErrors(errors); alert(""Check console.""); }); } render(){ $(""#tree_builder_container"") .empty() .append(View.render({ val: 234 })); } } __g.ready(new Page()); ","class View { static render(state){ return TreeBuilder.build(h => h(""div"", {} , h(""button"", {}, ""OK"") , h(""input"", { type: ""checkbox"" }) , h(""a"", { href: ""#"" }, ""link "" + state.val) , h(""button"", { onclick: ()=>{ __p.onclick_reloadLibs(); } } , ""reload libs"" ) ) ); } } class Page { constructor(){ this.state = {}; } getTitle(){ return ""sinatra-skelton""; } onclick_reloadLibs(){ __g.api_v2(""get"", ""/api/reload_libs"", {}, (result)=>{ __g.unguard(); }, (errors)=>{ __g.unguard(); __g.printApiErrors(errors); alert(""Check console.""); }); } init(){ puts(""init""); __g.api_v2(""get"", ""/api/sample"", { fooBar: 123, b: { c: 456 } }, (result)=>{ __g.unguard(); puts(result); Object.assign(this.state, result); this.render(); }, (errors)=>{ __g.unguard(); __g.printApiErrors(errors); alert(""Check console.""); }); } render(){ $(""#tree_builder_container"") .empty() .append(View.render({ val: 234 })); } } __g.ready(new Page()); " "Add scienceos init to command line interface This shouldn't really be there but is currently necessary so that references work before the simulation starts (this is for people entering their homes).","package uk.ac.eeci; import io.improbable.scienceos.Conductor; import io.improbable.scienceos.Reference; import io.improbable.scienceos.WorkerPool; import org.apache.commons.cli.*; public class CommandLineInterface { private String inputFilePath; private String outputFilePath; public static void main(String ... args) { Options options = new Options(); Option input = new Option(""i"", ""input"", true, ""file path to scenario db""); input.setRequired(true); options.addOption(input); Option output = new Option(""o"", ""output"", true, ""file path for output db""); output.setRequired(true); options.addOption(output); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp(""energy-agents"", options); System.exit(1); return; } CommandLineInterface cli = new CommandLineInterface(); cli.inputFilePath = cmd.getOptionValue(""input""); cli.outputFilePath = cmd.getOptionValue(""output""); cli.run(); } private void run() { Reference.pool = new WorkerPool(4); // FIXME shouldnt be here Reference.pool.setCurrentExecutor(Reference.pool.main); // FIXME shouldnt be here CitySimulation citySimulation = ScenarioBuilder.readScenario(this.inputFilePath, this.outputFilePath); new Conductor(citySimulation).run(); } } ","package uk.ac.eeci; import io.improbable.scienceos.Conductor; import org.apache.commons.cli.*; public class CommandLineInterface { private String inputFilePath; private String outputFilePath; public static void main(String ... args) { Options options = new Options(); Option input = new Option(""i"", ""input"", true, ""file path to scenario db""); input.setRequired(true); options.addOption(input); Option output = new Option(""o"", ""output"", true, ""file path for output db""); output.setRequired(true); options.addOption(output); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp(""energy-agents"", options); System.exit(1); return; } CommandLineInterface cli = new CommandLineInterface(); cli.inputFilePath = cmd.getOptionValue(""input""); cli.outputFilePath = cmd.getOptionValue(""output""); cli.run(); } private void run() { CitySimulation citySimulation = ScenarioBuilder.readScenario(this.inputFilePath, this.outputFilePath); new Conductor(citySimulation).run(); } } " "Update google-cloud-bigquery to get changes to DEFAULT_RETRY. Change-Id: Id24ae732121556ad2df9c1ca465400a43429a0e6","# Copyright 2017 Verily Life Sciences Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the ""License""); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """"""Package configuration."""""" from setuptools import find_packages from setuptools import setup REQUIRED_PACKAGES = ['pandas', 'google-api-core==1.1.2', 'google-auth==1.4.1', 'google-cloud-bigquery==1.6.0', 'google-cloud-storage==1.10.0', 'pysqlite>=2.8.3', 'ddt', 'typing'] setup( name='analysis-py-utils', version='0.4.0', license='Apache 2.0', author='Verily Life Sciences', url='https://github.com/verilylifesciences/analysis-py-utils', install_requires=REQUIRED_PACKAGES, packages=find_packages(), include_package_data=True, description='Python utilities for data analysis.', requires=[]) ","# Copyright 2017 Verily Life Sciences Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the ""License""); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """"""Package configuration."""""" from setuptools import find_packages from setuptools import setup REQUIRED_PACKAGES = ['pandas', 'google-api-core==1.1.2', 'google-auth==1.4.1', 'google-cloud-bigquery==1.5.0', 'google-cloud-storage==1.10.0', 'pysqlite>=2.8.3', 'ddt', 'typing'] setup( name='analysis-py-utils', version='0.4.0', license='Apache 2.0', author='Verily Life Sciences', url='https://github.com/verilylifesciences/analysis-py-utils', install_requires=REQUIRED_PACKAGES, packages=find_packages(), include_package_data=True, description='Python utilities for data analysis.', requires=[]) " Add a constant for default JavaFX style (Modena at this time) for FXMLStylesheet,"package moe.tristan.easyfxml.api; import moe.tristan.easyfxml.util.Resources; import moe.tristan.easyfxml.util.Stages; import io.vavr.control.Try; import javafx.stage.Stage; import java.net.URI; import java.net.URL; import java.nio.file.Path; /** * Represents a stylesheet a supplier of Path. What this means is that any protocol is acceptable. Whether it is local * file-based or remote URI-based. * * @see Stages#setStylesheet(Stage, FxmlStylesheet) */ public interface FxmlStylesheet { FxmlStylesheet DEFAULT_JAVAFX_STYLE = () -> null; /** * @return the CSS file that composes the stylesheet as a {@link Path}. See {@link * Resources#getResourcePath(String)} */ Path getPath(); /** * This method is a sample implementation that should work in almost all general cases. * <p> * An {@link java.io.IOException} can be thrown in very rare cases. * <p> * If you encounter them, post an issue with system details. * * @return the CSS file in external form (i.e. with the file:/, http:/...) protocol info before it. * @see Resources#getResourceURL(String) * @see URL#toExternalForm() */ default String getExternalForm() { return Try.of(this::getPath) .map(Path::toUri) .mapTry(URI::toURL) .map(URL::toExternalForm) .get(); } } ","package moe.tristan.easyfxml.api; import moe.tristan.easyfxml.util.Resources; import moe.tristan.easyfxml.util.Stages; import io.vavr.control.Try; import javafx.stage.Stage; import java.net.URI; import java.net.URL; import java.nio.file.Path; /** * Represents a stylesheet a supplier of Path. What this means is that any protocol is acceptable. Whether it is local * file-based or remote URI-based. * * @see Stages#setStylesheet(Stage, FxmlStylesheet) */ public interface FxmlStylesheet { /** * @return the CSS file that composes the stylesheet as a {@link Path}. See {@link * Resources#getResourcePath(String)} */ Path getPath(); /** * This method is a sample implementation that should work in almost all general cases. * <p> * An {@link java.io.IOException} can be thrown in very rare cases. * <p> * If you encounter them, post an issue with system details. * * @return the CSS file in external form (i.e. with the file:/, http:/...) protocol info before it. * @see Resources#getResourceURL(String) * @see URL#toExternalForm() */ default String getExternalForm() { return Try.of(this::getPath) .map(Path::toUri) .mapTry(URI::toURL) .map(URL::toExternalForm) .get(); } } " Change includeNeighborhood default value to 0,"from .location_schema import Location from marshmallow import Schema, fields, post_dump from .location_api_url import LocationUrl class LocationByPointQueryString(Schema): point = fields.Str() includeEntityTypes = fields.Str() includeNeighborhood = fields.Int( default=0 ) include = fields.Str( default='ciso2' ) o = fields.Str() key = fields.Str( required=True, error_messages={'required': 'Please provide a key'} ) class Meta: fields = ('point', 'includeEntityTypes', 'includeNeighborhood', 'include', 'o', 'key') ordered = True @post_dump def build_query_string(self, data): queryValues = [] for key, value in data.items(): if not key == 'point': queryValues.append('{0}={1}'.format(key, value)) queryString = '&'.join(queryValues) return '{0}?{1}'.format(data['point'], queryString) class LocationByPointSchema(Location, Schema): queryParameters = fields.Nested( LocationByPointQueryString ) class Meta: fields = ('version', 'restApi', 'resourcePath', 'queryParameters') ordered = True class LocationByPointUrl(LocationUrl): def __init__(self, data, protocol): schema = LocationByPointSchema() super().__init__(data, protocol, schema) @property def query(self): return self._schema_dict['queryParameters'] ","from .location_schema import Location from marshmallow import Schema, fields, post_dump from .location_api_url import LocationUrl class LocationByPointQueryString(Schema): point = fields.Str() includeEntityTypes = fields.Str() includeNeighborhood = fields.Int( default=1 ) include = fields.Str( default='ciso2' ) o = fields.Str() key = fields.Str( required=True, error_messages={'required': 'Please provide a key'} ) class Meta: fields = ('point', 'includeEntityTypes', 'includeNeighborhood', 'include', 'o', 'key') ordered = True @post_dump def build_query_string(self, data): queryValues = [] for key, value in data.items(): if not key == 'point': queryValues.append('{0}={1}'.format(key, value)) queryString = '&'.join(queryValues) return '{0}?{1}'.format(data['point'], queryString) class LocationByPointSchema(Location, Schema): queryParameters = fields.Nested( LocationByPointQueryString ) class Meta: fields = ('version', 'restApi', 'resourcePath', 'queryParameters') ordered = True class LocationByPointUrl(LocationUrl): def __init__(self, data, protocol): schema = LocationByPointSchema() super().__init__(data, protocol, schema) @property def query(self): return self._schema_dict['queryParameters'] " Add assertion that request base URL is set to the prefix,"<?php namespace CHH\Test; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use CHH\UrlMap; use Stack\CallableHttpKernel; class UrlMapTest extends \PHPUnit_Framework_TestCase { function test() { $app = new CallableHttpKernel(function(Request $req) { return new Response(""Fallback!""); }); $urlMap = new UrlMap($app); $urlMap->setMap(array( '/foo' => new CallableHttpKernel(function(Request $req) { return new Response('foo'); }) )); $req = Request::create('/foo'); $resp = $urlMap->handle($req); $this->assertEquals('foo', $resp->getContent()); } function testOverridesPathInfo() { $test = $this; $app = new CallableHttpKernel(function(Request $req) { return new Response(""Fallback!""); }); $urlMap = new UrlMap($app); $urlMap->setMap(array( '/foo' => new CallableHttpKernel(function(Request $req) use ($test) { $test->assertEquals('/', $req->getPathinfo()); $test->assertEquals('/foo', $req->attributes->get(UrlMap::ATTR_PREFIX)); $test->assertEquals('/foo', $req->getBaseUrl()); return new Response(""Hello World""); }) )); $resp = $urlMap->handle(Request::create('/foo?bar=baz')); $this->assertEquals('Hello World', $resp->getContent()); } } ","<?php namespace CHH\Test; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use CHH\UrlMap; use Stack\CallableHttpKernel; class UrlMapTest extends \PHPUnit_Framework_TestCase { function test() { $app = new CallableHttpKernel(function(Request $req) { return new Response(""Fallback!""); }); $urlMap = new UrlMap($app); $urlMap->setMap(array( '/foo' => new CallableHttpKernel(function(Request $req) { return new Response('foo'); }) )); $req = Request::create('/foo'); $resp = $urlMap->handle($req); $this->assertEquals('foo', $resp->getContent()); } function testOverridesPathInfo() { $test = $this; $app = new CallableHttpKernel(function(Request $req) { return new Response(""Fallback!""); }); $urlMap = new UrlMap($app); $urlMap->setMap(array( '/foo' => new CallableHttpKernel(function(Request $req) use ($test) { $test->assertEquals('/', $req->getPathinfo()); $test->assertEquals('/foo', $req->attributes->get(UrlMap::ATTR_PREFIX)); return new Response(""Hello World""); }) )); $resp = $urlMap->handle(Request::create('/foo?bar=baz')); $this->assertEquals('Hello World', $resp->getContent()); } } " "Fix the import of MigrationExecutor to be lazy. MigrationExecutor checks at import time whether apps are all loaded. This doesn't work as they are usually not if your app is imported by adding it to INSTALLED_APPS. Importing the MigrationExecutor locally solves this problem as ExportMigration is only called once the django_prometheus app is signaled that it's ready.","from django.db import connections from django.db.backends.dummy.base import DatabaseWrapper from prometheus_client import Gauge unapplied_migrations = Gauge( 'django_migrations_unapplied_total', 'Count of unapplied migrations by database connection', ['connection']) applied_migrations = Gauge( 'django_migrations_applied_total', 'Count of applied migrations by database connection', ['connection']) def ExportMigrationsForDatabase(alias, executor): plan = executor.migration_plan(executor.loader.graph.leaf_nodes()) unapplied_migrations.labels(alias).set(len(plan)) applied_migrations.labels(alias).set(len( executor.loader.applied_migrations)) def ExportMigrations(): """"""Exports counts of unapplied migrations. This is meant to be called during app startup, ideally by django_prometheus.apps.AppConfig. """""" # Import MigrationExecutor lazily. MigrationExecutor checks at # import time that the apps are ready, and they are not when # django_prometheus is imported. ExportMigrations() should be # called in AppConfig.ready(), which signals that all apps are # ready. from django.db.migrations.executor import MigrationExecutor if 'default' in connections and ( type(connections['default']) == DatabaseWrapper): # This is the case where DATABASES = {} in the configuration, # i.e. the user is not using any databases. Django ""helpfully"" # adds a dummy database and then throws when you try to # actually use it. So we don't do anything, because trying to # export stats would crash the app on startup. return for alias in connections.databases: executor = MigrationExecutor(connections[alias]) ExportMigrationsForDatabase(alias, executor) ","from django.db import connections from django.db.backends.dummy.base import DatabaseWrapper from django.db.migrations.executor import MigrationExecutor from prometheus_client import Gauge unapplied_migrations = Gauge( 'django_migrations_unapplied_total', 'Count of unapplied migrations by database connection', ['connection']) applied_migrations = Gauge( 'django_migrations_applied_total', 'Count of applied migrations by database connection', ['connection']) def ExportMigrationsForDatabase(alias, executor): plan = executor.migration_plan(executor.loader.graph.leaf_nodes()) unapplied_migrations.labels(alias).set(len(plan)) applied_migrations.labels(alias).set(len( executor.loader.applied_migrations)) def ExportMigrations(): """"""Exports counts of unapplied migrations. This is meant to be called during app startup, ideally by django_prometheus.apps.AppConfig. """""" if 'default' in connections and ( type(connections['default']) == DatabaseWrapper): # This is the case where DATABASES = {} in the configuration, # i.e. the user is not using any databases. Django ""helpfully"" # adds a dummy database and then throws when you try to # actually use it. So we don't do anything, because trying to # export stats would crash the app on startup. return for alias in connections.databases: executor = MigrationExecutor(connections[alias]) ExportMigrationsForDatabase(alias, executor) " Set up storybook to output an async webpack config,"import { NormalModuleReplacementPlugin } from 'webpack' import merge from 'webpack-merge' import path from 'path' import initConf from '../build' export default async () => merge( await initConf({ context: path.resolve(__dirname, '..'), mode: 'development', injectStyles: true, }), { plugins: [ // Set up mock for WebExt APIs. Idea from: // https://github.com/aeksco/react-typescript-web-extension-starter/blob/f62486ec8518eb5cf78687a2e658505fd528dc8a/.storybook/webpack.config.js new NormalModuleReplacementPlugin( /webextension-polyfill-ts/, (resource) => { const absMockPath = path.resolve( __dirname, 'mocks/webextension-polyfill-ts.js', ) resource.request = path.relative( resource.context, absMockPath, ) }, ), ], }, ) ","import { NormalModuleReplacementPlugin } from 'webpack' import merge from 'webpack-merge' import path from 'path' import initConf from '../build' export default merge( initConf({ context: path.resolve(__dirname, '..'), mode: 'development', injectStyles: true, }), { plugins: [ // Set up mock for WebExt APIs. Idea from: // https://github.com/aeksco/react-typescript-web-extension-starter/blob/f62486ec8518eb5cf78687a2e658505fd528dc8a/.storybook/webpack.config.js new NormalModuleReplacementPlugin( /webextension-polyfill-ts/, resource => { const absMockPath = path.resolve( __dirname, 'mocks/webextension-polyfill-ts.js', ) resource.request = path.relative( resource.context, absMockPath, ) }, ), ], }, ) " Add autofocus on field search,"<body> <div class=""container""> {err} <div class=""panel panel-default""> <div class=""panel-body""> <h1>Check In</h1> <form method=""get""> <div class=""form-group""> <input type=""text"" class=""form-control"" name=""search"" placeholder=""หมายเลขประจำตัว, ชื่อ, นามสกุล, ชื่อเล่น"" autofocus> </div> <button type=""submit"" class=""btn btn-default"">Submit</button> </form> </div> </div> <div class=""panel panel-default""> <div class=""table-responsive""> <table class=""table""> <thead> <tr> <th>ID</th> <th>ชื่อ - นามสกุล</th> <th>ชื่อเล่น</th> <th>โรงเรียน</th> <th>Action</th> </tr> </thead> <tbody> {attendees} </tbody> </table> </div> </div> </div> </body>","<body> <div class=""container""> {err} <div class=""panel panel-default""> <div class=""panel-body""> <h1>Check In</h1> <form method=""get""> <div class=""form-group""> <input type=""text"" class=""form-control"" name=""search"" placeholder=""หมายเลขประจำตัว, ชื่อ, นามสกุล, ชื่อเล่น""> </div> <button type=""submit"" class=""btn btn-default"">Submit</button> </form> </div> </div> <div class=""panel panel-default""> <div class=""table-responsive""> <table class=""table""> <thead> <tr> <th>ID</th> <th>ชื่อ - นามสกุล</th> <th>ชื่อเล่น</th> <th>โรงเรียน</th> <th>Action</th> </tr> </thead> <tbody> {attendees} </tbody> </table> </div> </div> </div> </body>" Add auth and contentypes django apps on tests to prevent RuntimeError on Django 1.9,"import django from django.conf import settings if not settings.configured: settings.configure( DEBUG=True, INSTALLED_APPS=( 'django.contrib.auth', 'django.contrib.contenttypes', 'mailviews', 'mailviews.tests', ), DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, }, ROOT_URLCONF='mailviews.tests.urls', STATIC_URL='/static/', LOGGING={ 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, }, 'loggers': { '': { 'handler': ['console'], 'level': 'DEBUG', }, }, }, ) if hasattr(django, 'setup'): django.setup() from mailviews.tests.tests import * # NOQA if __name__ == '__main__': from mailviews.tests.__main__ import __main__ __main__() ","import django from django.conf import settings if not settings.configured: settings.configure( DEBUG=True, INSTALLED_APPS=( 'mailviews', 'mailviews.tests', ), DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, }, ROOT_URLCONF='mailviews.tests.urls', STATIC_URL='/static/', LOGGING={ 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, }, 'loggers': { '': { 'handler': ['console'], 'level': 'DEBUG', }, }, }, ) if hasattr(django, 'setup'): django.setup() from mailviews.tests.tests import * # NOQA if __name__ == '__main__': from mailviews.tests.__main__ import __main__ __main__() " Include OSM search result type in details object,"/** * L.Control.GeoSearch - search for an address and zoom to it's location * L.GeoSearch.Provider.OpenStreetMap uses openstreetmap geocoding service * https://github.com/smeijer/L.GeoSearch */ L.GeoSearch.Provider.OpenStreetMap = L.Class.extend({ options: {}, initialize: function(options) { options = L.Util.setOptions(this, options); }, GetServiceUrl: function (qry) { var parameters = L.Util.extend({ q: qry, format: 'json' }, this.options); return location.protocol + '//nominatim.openstreetmap.org/search' + L.Util.getParamString(parameters); }, ParseJSON: function (data) { var results = []; for (var i = 0; i < data.length; i++) { var boundingBox = data[i].boundingbox, northEastLatLng = new L.LatLng( boundingBox[1], boundingBox[3] ), southWestLatLng = new L.LatLng( boundingBox[0], boundingBox[2] ); if (data[i].address) data[i].address.type = data[i].type; results.push(new L.GeoSearch.Result( data[i].lon, data[i].lat, data[i].display_name, new L.LatLngBounds([ northEastLatLng, southWestLatLng ]), data[i].address )); } return results; } }); ","/** * L.Control.GeoSearch - search for an address and zoom to it's location * L.GeoSearch.Provider.OpenStreetMap uses openstreetmap geocoding service * https://github.com/smeijer/L.GeoSearch */ L.GeoSearch.Provider.OpenStreetMap = L.Class.extend({ options: {}, initialize: function(options) { options = L.Util.setOptions(this, options); }, GetServiceUrl: function (qry) { var parameters = L.Util.extend({ q: qry, format: 'json' }, this.options); return location.protocol + '//nominatim.openstreetmap.org/search' + L.Util.getParamString(parameters); }, ParseJSON: function (data) { var results = []; for (var i = 0; i < data.length; i++) { var boundingBox = data[i].boundingbox, northEastLatLng = new L.LatLng( boundingBox[1], boundingBox[3] ), southWestLatLng = new L.LatLng( boundingBox[0], boundingBox[2] ); results.push(new L.GeoSearch.Result( data[i].lon, data[i].lat, data[i].display_name, new L.LatLngBounds([ northEastLatLng, southWestLatLng ]), data[i].address )); } return results; } }); " Update unit test to match the change within KeyBoard Manager.,"describe('Keyboard module', function() { describe('KeyboardManger', function() { // Inject the Keyboard module for this test beforeEach(module('Keyboard')); var keyboardManager; beforeEach(inject(function(KeyboardManager) { keyboardManager = KeyboardManager; })); it('should be injected', function() { expect(keyboardManager).toBeDefined(); }); describe('.init', function() { it('should initialize $document to be binded with \'keydown\' event', function() { keyboardManager.init(); var keyTriggered = 0; var callback = function(key, e) { keyTriggered = key; }; keyboardManager.keyEventHandlers = [callback]; var e = $.Event('keydown'); // click left e.which = 37; angular.element(window.document).triggerHandler(e); expect(keyTriggered).toEqual('left'); }); }); beforeEach(function() { keyboardManager.init(); }); describe('.on', function() { it('should add new callback function into keyEventHandlers', function() { var callback = function(key, e) { console.log(key); }; keyboardManager.on(callback); expect(keyboardManager.keyEventHandlers).toEqual([callback]); }); }); describe('._handleKeyEvent', function() { it('should call all callback functions for a key event', function() { var keyTriggered = 0; var callback = function(key, e) { keyTriggered = key; }; keyboardManager.keyEventHandlers = [callback]; keyboardManager._handleKeyEvent('left'); expect(keyTriggered).toEqual('left'); }); }); }); }); ","describe('Keyboard module', function() { describe('KeyboardManger', function() { // Inject the Keyboard module for this test beforeEach(module('Keyboard')); var keyboardManager; beforeEach(inject(function(KeyboardManager) { keyboardManager = KeyboardManager; })); it('should be injected', function() { expect(keyboardManager).toBeDefined(); }); describe('.on', function() { it('should add new callback function into keyEventHandlers', function() { var callback = function(key, e) { console.log(key); }; keyboardManager.on(callback); expect(keyboardManager.keyEventHandlers).toEqual([callback]); }); }); describe('._handleKeyEvent', function() { it('should call all callback functions for a key event', function() { var keyTriggered = 0; var callback = function(key, e) { keyTriggered = key; }; keyboardManager.keyEventHandlers = [callback]; keyboardManager._handleKeyEvent('left'); expect(keyTriggered).toEqual('left'); }); }); describe('.init', function() { it('should initialize $document to be binded with \'keydown\' event', function() { keyboardManager.init(); var keyTriggered = 0; var callback = function(key, e) { keyTriggered = key; }; keyboardManager.keyEventHandlers = [callback]; var e = $.Event('keydown'); // click left e.which = 37; angular.element(window.document).triggerHandler(e); expect(keyTriggered).toEqual('left'); }); }); }); }); " Add ID of authorized user on facebook auth request,"<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Request; use Illuminate\Contracts\Auth\Guard; use Facebook\FacebookSession; use Illuminate\Support\Facades\Session; // add other classes you plan to use, e.g.: // use Facebook\FacebookRequest; // use Facebook\GraphUser; // use Facebook\FacebookRequestException; /** * Class FacebookController * * @package App\Http\Controllers\Auth */ class FacebookController extends Controller { public function token(Guard $auth) { try { $accessToken = $auth->facebookAuth(Input::get('code')); return response()->json([ 'user' => [ 'name' => Auth::user()->name, 'facebookId' => Auth::user()->facebookId, 'id' => Auth::user()->id ], 'token_type' => 'bearer', 'access_token' => $accessToken ]); } catch(\Exception $e) { Log::error( ""Exception occured, code: "" . $e->getCode() . "" with message: "" . $e->getMessage() ); } return response('Bad request.', 400); } } ","<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Request; use Illuminate\Contracts\Auth\Guard; use Facebook\FacebookSession; use Illuminate\Support\Facades\Session; // add other classes you plan to use, e.g.: // use Facebook\FacebookRequest; // use Facebook\GraphUser; // use Facebook\FacebookRequestException; /** * Class FacebookController * * @package App\Http\Controllers\Auth */ class FacebookController extends Controller { public function token(Guard $auth) { try { $accessToken = $auth->facebookAuth(Input::get('code')); return response()->json([ 'user' => [ 'name' => Auth::user()->name, 'id' => Auth::user()->facebookId ], 'token_type' => 'bearer', 'access_token' => $accessToken ]); } catch(\Exception $e) { Log::error( ""Exception occured, code: "" . $e->getCode() . "" with message: "" . $e->getMessage() ); } return response('Bad request.', 400); } } " Add bundle name in dev mode,"const merge = require('webpack-merge') const webpack = require('webpack') const WebpackAssetsManifest = require('webpack-assets-manifest') const WEBPACK_DEV_SERVER = 'http://localhost:8080' module.exports = function () { process.env.NODE_ENV = 'development' return merge(require('./config.base.js'), { mode: 'development', watch: true, output: { filename: 'js/main.js', chunkFilename: 'js/[name].bundle.js', publicPath: WEBPACK_DEV_SERVER + '/assets/module/web/' }, module: { rules: [ { test: /\.(sass|scss|css)$/, use: [ 'vue-style-loader', 'css-loader', 'sass-loader' ] } ] }, plugins: [ new webpack.HotModuleReplacementPlugin(), new WebpackAssetsManifest({ output: 'assets.json', writeToDisk: true, publicPath: true, assets: { 'webpack-hot-reload': WEBPACK_DEV_SERVER + '/webpack-dev-server.js' } }) ], devtool: '#cheap-module-eval-source-map', devServer: { contentBase: false, hot: true, headers: { 'Access-Control-Allow-Origin': '*' } } }) } ","const merge = require('webpack-merge') const webpack = require('webpack') const WebpackAssetsManifest = require('webpack-assets-manifest') const WEBPACK_DEV_SERVER = 'http://localhost:8080' module.exports = function () { process.env.NODE_ENV = 'development' return merge(require('./config.base.js'), { mode: 'development', watch: true, output: { filename: 'js/main.js', publicPath: WEBPACK_DEV_SERVER + '/assets/module/web/' }, module: { rules: [ { test: /\.(sass|scss|css)$/, use: [ 'vue-style-loader', 'css-loader', 'sass-loader' ] } ] }, plugins: [ new webpack.HotModuleReplacementPlugin(), new WebpackAssetsManifest({ output: 'assets.json', writeToDisk: true, publicPath: true, assets: { 'webpack-hot-reload': WEBPACK_DEV_SERVER + '/webpack-dev-server.js' } }) ], devtool: '#cheap-module-eval-source-map', devServer: { contentBase: false, hot: true, headers: { 'Access-Control-Allow-Origin': '*' } } }) } " Change Constants type for doubling_time and relative_contact_rate from int to float,"""""""Defaults."""""" from .utils import RateLos class Regions: """"""Arbitrary number of counties."""""" def __init__(self, **kwargs): population = 0 for key, value in kwargs.items(): setattr(self, key, value) population += value self.population = population class Constants: def __init__( self, *, current_hospitalized: int, doubling_time: float, known_infected: int, relative_contact_rate: float, region: Regions, hospitalized: RateLos, icu: RateLos, ventilated: RateLos, as_date: bool = False, market_share: float = 1.0, max_y_axis: int = None, n_days: int = 60, recovery_days: int = 14, ): self.region = region self.current_hospitalized = current_hospitalized self.known_infected = known_infected self.doubling_time = doubling_time self.relative_contact_rate = relative_contact_rate self.hospitalized = hospitalized self.icu = icu self.ventilated = ventilated self.as_date = as_date self.market_share = market_share self.max_y_axis = max_y_axis self.n_days = n_days self.recovery_days = recovery_days def __repr__(self) -> str: return f""Constants(population_default: {self.region.population}, known_infected: {self.known_infected})"" ","""""""Defaults."""""" from .utils import RateLos class Regions: """"""Arbitrary number of counties."""""" def __init__(self, **kwargs): population = 0 for key, value in kwargs.items(): setattr(self, key, value) population += value self.population = population class Constants: def __init__( self, *, current_hospitalized: int, doubling_time: int, known_infected: int, relative_contact_rate: int, region: Regions, hospitalized: RateLos, icu: RateLos, ventilated: RateLos, as_date: bool = False, market_share: float = 1.0, max_y_axis: int = None, n_days: int = 60, recovery_days: int = 14, ): self.region = region self.current_hospitalized = current_hospitalized self.known_infected = known_infected self.doubling_time = doubling_time self.relative_contact_rate = relative_contact_rate self.hospitalized = hospitalized self.icu = icu self.ventilated = ventilated self.as_date = as_date self.market_share = market_share self.max_y_axis = max_y_axis self.n_days = n_days self.recovery_days = recovery_days def __repr__(self) -> str: return f""Constants(population_default: {self.region.population}, known_infected: {self.known_infected})"" " "Support SNI in the example client Fixes: gh-36","import socket, ssl import h11 class MyHttpClient: def __init__(self, host, port): self.sock = socket.create_connection((host, port)) if port == 443: ctx = ssl.create_default_context() self.sock = ctx.wrap_socket(self.sock, server_hostname=host) self.conn = h11.Connection(our_role=h11.CLIENT) def send(self, *events): for event in events: data = self.conn.send(event) if data is None: # event was a ConnectionClosed(), meaning that we won't be # sending any more data: self.sock.shutdown(socket.SHUT_WR) else: self.sock.sendall(data) # max_bytes_per_recv intentionally set low for pedagogical purposes def next_event(self, max_bytes_per_recv=200): while True: # If we already have a complete event buffered internally, just # return that. Otherwise, read some data, add it to the internal # buffer, and then try again. event = self.conn.next_event() if event is h11.NEED_DATA: self.conn.receive_data(self.sock.recv(max_bytes_per_recv)) continue return event ","import socket, ssl import h11 class MyHttpClient: def __init__(self, host, port): self.sock = socket.create_connection((host, port)) if port == 443: self.sock = ssl.wrap_socket(self.sock) self.conn = h11.Connection(our_role=h11.CLIENT) def send(self, *events): for event in events: data = self.conn.send(event) if data is None: # event was a ConnectionClosed(), meaning that we won't be # sending any more data: self.sock.shutdown(socket.SHUT_WR) else: self.sock.sendall(data) # max_bytes_per_recv intentionally set low for pedagogical purposes def next_event(self, max_bytes_per_recv=200): while True: # If we already have a complete event buffered internally, just # return that. Otherwise, read some data, add it to the internal # buffer, and then try again. event = self.conn.next_event() if event is h11.NEED_DATA: self.conn.receive_data(self.sock.recv(max_bytes_per_recv)) continue return event " Remove some artist code in Badge component,"import { h, Component } from 'preact'; import style from './style'; import Icon from '../Icon'; export default class Badge extends Component { render() { const { event, small } = this.props; if (!event) { return; } if (event.cancelled) { return ( <span class={`${style.badge} ${small ? style.badgeSmall : {}} ${style.badgeCancelled}`}> <Icon name=""close"" /> Cancelled </span> ); } if (event.reason.attendance) { if (event.reason.attendance === 'im_going') { return ( <span class={`${style.badge} ${small ? style.badgeSmall : {}} ${style.badgeGoing}`}> <Icon name=""check"" /> Going </span> ); } else if (event.reason.attendance === 'i_might_go') { return ( <span class={`${style.badge} ${small ? style.badgeSmall : {}} ${style.badgeMaybe}`}> <Icon name=""bookmark"" /> Maybe </span> ); } } else if (event.type && event.type === 'festival') { return ( <span class={`${style.badge} ${small ? style.badgeSmall : {}} ${style.badgeFestival}`}> <Icon name=""star"" /> Festival </span> ); } return; } } ","import { h, Component } from 'preact'; import style from './style'; import Icon from '../Icon'; export default class Badge extends Component { render() { const { artist, event, small } = this.props; if (!event && !artist) { return; } if (artist && artist.onTourUntil) { return ( <span class={`${style.badge} ${small ? style.badgeSmall : {}} ${style.badgeOnTour}`}> <Icon name=""calendar"" /> On tour </span> ); } if (event.cancelled) { return ( <span class={`${style.badge} ${small ? style.badgeSmall : {}} ${style.badgeCancelled}`}> <Icon name=""close"" /> Cancelled </span> ); } if (event.reason.attendance) { if (event.reason.attendance === 'im_going') { return ( <span class={`${style.badge} ${small ? style.badgeSmall : {}} ${style.badgeGoing}`}> <Icon name=""check"" /> Going </span> ); } else if (event.reason.attendance === 'i_might_go') { return ( <span class={`${style.badge} ${small ? style.badgeSmall : {}} ${style.badgeMaybe}`}> <Icon name=""bookmark"" /> Maybe </span> ); } } else if (event.type && event.type === 'festival') { return ( <span class={`${style.badge} ${small ? style.badgeSmall : {}} ${style.badgeFestival}`}> <Icon name=""star"" /> Festival </span> ); } return; } } " Fix bug in EdgeDescriptor setting.," from binary_descriptor import BinaryDescriptor import amitgroup as ag import amitgroup.features # TODO: This is temporarily moved #@BinaryDescriptor.register('edges') class EdgeDescriptor(BinaryDescriptor): """""" Binary descriptor based on edges. The parameters are similar to :func:`amitgroup.features.bedges`. Parameters ---------- polarity_sensitive : bool If True, the polarity of the edges will matter. If False, then the direction of edges will not matter. k : int See :func:`amitgroup.features.bedges`. radius : int Radius of edge spreading. See :func:`amitgroup.features.bedges`. min_contrast : float See :func:`amitgroup.features.bedges`. """""" def __init__(self, polarity_sensitive=True, k=5, radius=1, min_contrast=0.1): self.settings = {} # Change this self.settings['contrast_insensitive'] = not polarity_sensitive self.settings['k'] = k self.settings['radius'] = radius self.settings['min_contrast'] = min_contrast self.settings.update(settings) def extract_features(self, img): #return ag.features.bedges_from_image(img, **self.settings) return ag.features.bedges(img, **self.settings) def save_to_dict(self): return self.settings @classmethod def load_from_dict(cls, d): return cls(d) EdgeDescriptor = BinaryDescriptor.register('edges')(EdgeDescriptor) "," from binary_descriptor import BinaryDescriptor import amitgroup as ag import amitgroup.features # TODO: This is temporarily moved #@BinaryDescriptor.register('edges') class EdgeDescriptor(BinaryDescriptor): """""" Binary descriptor based on edges. The parameters are similar to :func:`amitgroup.features.bedges`. Parameters ---------- polarity_sensitive : bool If True, the polarity of the edges will matter. If False, then the direction of edges will not matter. k : int See :func:`amitgroup.features.bedges`. radius : int Radius of edge spreading. See :func:`amitgroup.features.bedges`. min_contrast : float See :func:`amitgroup.features.bedges`. """""" def __init__(self, polarity_sensitive=True, k=5, radius=1, min_contrast=0.1): self.settings = {} # Change this self.settings['contrast_insensitive'] = polarity_sensitive self.settings['k'] = k self.settings['radius'] = radius self.settings['min_contrast'] = min_contrast self.settings.update(settings) def extract_features(self, img): #return ag.features.bedges_from_image(img, **self.settings) return ag.features.bedges(img, **self.settings) def save_to_dict(self): return self.settings @classmethod def load_from_dict(cls, d): return cls(d) EdgeDescriptor = BinaryDescriptor.register('edges')(EdgeDescriptor) " Fix test for auth tokens store,"from test.base import ApiTestCase from zou.app.stores import auth_tokens_store class CommandsTestCase(ApiTestCase): def setUp(self): super(CommandsTestCase, self).setUp() self.store = auth_tokens_store self.store.clear() def tearDown(self): self.store.clear() def test_get_and_add(self): self.assertIsNone(self.store.get(""key-1"")) self.store.add(""key-1"", ""true"") self.assertEquals(self.store.get(""key-1""), ""true"") def test_delete(self): self.store.add(""key-1"", ""true"") self.store.delete(""key-1"") self.assertIsNone(self.store.get(""key-1"")) def test_is_revoked(self): self.assertTrue(self.store.is_revoked({""jti"": ""key-1""})) self.store.add(""key-1"", ""true"") self.assertTrue(self.store.is_revoked({""jti"": ""key-1""})) self.store.add(""key-1"", ""false"") self.assertFalse(self.store.is_revoked({""jti"": ""key-1""})) def test_keys(self): self.store.add(""key-1"", ""true"") self.store.add(""key-2"", ""true"") self.assertTrue(""key-1"" in self.store.keys()) self.assertTrue(""key-2"" in self.store.keys()) ","from test.base import ApiTestCase from zou.app.stores import auth_tokens_store class CommandsTestCase(ApiTestCase): def setUp(self): super(CommandsTestCase, self).setUp() self.store = auth_tokens_store self.store.clear() def tearDown(self): self.store.clear() def test_get_and_add(self): self.assertIsNone(self.store.get(""key-1"")) self.store.add(""key-1"", ""true"") self.assertEquals(self.store.get(""key-1""), ""true"") def test_delete(self): self.store.add(""key-1"", ""true"") self.store.delete(""key-1"") self.assertIsNone(self.store.get(""key-1"")) def test_is_revoked(self): self.assertTrue(self.store.is_revoked({""jti"": ""key-1""})) self.store.add(""key-1"", ""true"") self.assertTrue(self.store.is_revoked({""jti"": ""key-1""})) self.store.add(""key-1"", ""false"") self.assertFalse(self.store.is_revoked({""jti"": ""key-1""})) def test_keys(self): self.store.add(""key-1"", ""true"") self.store.add(""key-2"", ""true"") self.assertEquals( self.store.keys(), [""key-1"", ""key-2""] ) " Fix ESLint's whims about indentation,"// @flow export default [`# Getting the first 3 Pipelines of an Organization query FirstThreePipelinesQuery { organization(slug: $organizationSlug) { id name pipelines(first: 3) { edges { node { name description repository { url } } } } } }`, `# Listing the teams within your organization query FirstThreeTeamsQuery { organization(slug: $organizationSlug) { teams(first: 3) { edges { node { name members(first: 10) { edges { node { role user { name } } } } } } } } }`, `# Creating an Agent Registration Token mutation CreateAgentToken { agentTokenCreate(input: { organizationID: $organizationId, description: ""My New Agent Registration Token"" }) { agentTokenEdge { node { id description token } } } }`, `# Revoking an Agent Registration Token mutation RevokeAgentToken { agentTokenRevoke(input: { id: $agentTokenId, reason: ""I accidently commited it to source control 😬"" }) { agentToken { id description revokedAt revokedBy { name } } } }` ]; ","// @flow export default [`# Getting the first 3 Pipelines of an Organization query FirstThreePipelinesQuery { organization(slug: $organizationSlug) { id name pipelines(first: 3) { edges { node { name description repository { url } } } } } }`, `# Listing the teams within your organization query FirstThreeTeamsQuery { organization(slug: $organizationSlug) { teams(first: 3) { edges { node { name members(first: 10) { edges { node { role user { name } } } } } } } } }`, `# Creating an Agent Registration Token mutation CreateAgentToken { agentTokenCreate(input: { organizationID: $organizationId, description: ""My New Agent Registration Token"" }) { agentTokenEdge { node { id description token } } } }`, `# Revoking an Agent Registration Token mutation RevokeAgentToken { agentTokenRevoke(input: { id: $agentTokenId, reason: ""I accidently commited it to source control 😬"" }) { agentToken { id description revokedAt revokedBy { name } } } }` ]; " "Fix active theme selector. Add validation to API. Closes #3226 - Remove dependent property from the computed content property that is used to build the active theme selector. - Add validation to the Settings model so that it rejects attempts to set an activeTheme that is not installed.","var SettingsGeneralController = Ember.ObjectController.extend({ isDatedPermalinks: function (key, value) { // setter if (arguments.length > 1) { this.set('permalinks', value ? '/:year/:month/:day/:slug/' : '/:slug/'); } // getter var slugForm = this.get('permalinks'); return slugForm !== '/:slug/'; }.property('permalinks'), themes: function () { return this.get('availableThemes').reduce(function (themes, t) { var theme = {}; theme.name = t.name; theme.label = t.package ? t.package.name + ' - ' + t.package.version : t.name; theme.package = t.package; theme.active = !!t.active; themes.push(theme); return themes; }, []); }.property().readOnly(), actions: { save: function () { var self = this; return this.get('model').save().then(function (model) { self.notifications.closePassive(); self.notifications.showSuccess('Settings successfully saved.'); return model; }).catch(function (errors) { self.notifications.closePassive(); self.notifications.showErrors(errors); }); }, } }); export default SettingsGeneralController; ","var SettingsGeneralController = Ember.ObjectController.extend({ isDatedPermalinks: function (key, value) { // setter if (arguments.length > 1) { this.set('permalinks', value ? '/:year/:month/:day/:slug/' : '/:slug/'); } // getter var slugForm = this.get('permalinks'); return slugForm !== '/:slug/'; }.property('permalinks'), themes: function () { return this.get('availableThemes').reduce(function (themes, t) { var theme = {}; theme.name = t.name; theme.label = t.package ? t.package.name + ' - ' + t.package.version : t.name; theme.package = t.package; theme.active = !!t.active; themes.push(theme); return themes; }, []); }.property('availableThemes').readOnly(), actions: { save: function () { var self = this; return this.get('model').save().then(function (model) { self.notifications.closePassive(); self.notifications.showSuccess('Settings successfully saved.'); return model; }).catch(function (errors) { self.notifications.closePassive(); self.notifications.showErrors(errors); }); }, } }); export default SettingsGeneralController; " Make end date not required.,"<?php namespace app\models; use Yii; /** * This is the model class for table ""History"". * * @property integer $counterId * @property string $startDate * @property string $endDate * * @property Counters $counter */ class History extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'History'; } /** * @inheritdoc */ public function rules() { return [ [['counterId', 'startDate'], 'required'], [['startDate', 'endDate'], 'string'], [['counterId'], 'integer'], [['counterId', 'startDate', 'endDate'], 'unique', 'targetAttribute' => ['counterId', 'startDate', 'endDate'], 'message' => 'The combination of Counter ID, Start Date and End Date has already been taken.'] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'counterId' => 'Counter ID', 'startDate' => 'Start Date', 'endDate' => 'End Date', ]; } /** * @return \yii\db\ActiveQuery */ public function getCounter() { return $this->hasOne(Counter::className(), ['counterId' => 'counterId']); } } ","<?php namespace app\models; use Yii; /** * This is the model class for table ""History"". * * @property integer $counterId * @property string $startDate * @property string $endDate * * @property Counters $counter */ class History extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'History'; } /** * @inheritdoc */ public function rules() { return [ [['counterId', 'startDate', 'endDate'], 'required'], [['startDate', 'endDate'], 'string'], [['counterId'], 'integer'], [['counterId', 'startDate', 'endDate'], 'unique', 'targetAttribute' => ['counterId', 'startDate', 'endDate'], 'message' => 'The combination of Counter ID, Start Date and End Date has already been taken.'] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'counterId' => 'Counter ID', 'startDate' => 'Start Date', 'endDate' => 'End Date', ]; } /** * @return \yii\db\ActiveQuery */ public function getCounter() { return $this->hasOne(Counter::className(), ['counterId' => 'counterId']); } } " Improve PSR test to produce useful output,"<?php namespace phpSmug\Tests; /** * @class * Test properties of our codebase rather than the actual code. */ class PsrComplianceTest extends \PHPUnit_Framework_TestCase { /** * @test */ public function testPSR() { // If we can't find the command-line tool, we mark the test as skipped // so it shows as a warning to the developer rather than passing silently. if (!file_exists('vendor/bin/php-cs-fixer')) { $this->markTestSkipped( 'Needs linter to check PSR compliance' ); } // Run linter in dry-run mode so it changes nothing. exec( escapeshellcmd('vendor/bin/php-cs-fixer fix --diff -v --dry-run .'), $output, $return_var ); // If we've got output, pop its first item (""Fixed all files..."") // shift off the last two lines, and trim whitespace from the rest. if ($output) { array_pop($output); array_shift($output); array_shift($output); $output = array_map('trim', $output); } // Check shell return code: if nonzero, report the output as a failure. $this->assertEquals( 0, $return_var, ""PSR linter reported errors in: \n\t"".implode(""\n\t"", $output) ); } } ","<?php namespace phpSmug\Tests; /** * @class * Test properties of our codebase rather than the actual code. */ class PsrComplianceTest extends \PHPUnit_Framework_TestCase { /** * @test */ public function testPSR() { // If we can't find the command-line tool, we mark the test as skipped // so it shows as a warning to the developer rather than passing silently. if (!file_exists('vendor/bin/php-cs-fixer')) { $this->markTestSkipped( 'Needs linter to check PSR compliance' ); } // Let's check all PSR compliance for our code and tests. // Add any other pass you want to test to this array. foreach (array('lib/', 'examples/', 'test/') as $path) { // Run linter in dry-run mode so it changes nothing. exec( escapeshellcmd('vendor/bin/php-cs-fixer fix --dry-run '.$_SERVER['PWD'].""/$path""), $output, $return_var ); // If we've got output, pop its first item (""Fixed all files..."") // and trim whitespace from the rest so the below makes sense. if ($output) { array_pop($output); $output = array_map('trim', $output); } // Check shell return code: if nonzero, report the output as a failure. $this->assertEquals( 0, $return_var, ""PSR linter reported errors in $path: \n\t"".implode(""\n\t"", $output) ); } } } " Add icon to primary stage,"/* *\ ** SICU Stress Measurement System ** ** Project P04 | C380 Team A ** ** EBME 380: Biomedical Engineering Design Experience ** ** Case Western Reserve University ** ** 2016 Fall Semester ** \* */ package edu.cwru.sicu_sms; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.stage.Stage; /** * The main stage of the front-end program for interfacing with the electronic system. * * @since September 27, 2016 * @author Ted Frohlich <ttf10@case.edu> * @author Abby Walker <amw138@case.edu> */ public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load( getClass().getResource(""sicu_sms.fxml"") ); primaryStage.getIcons().add(new Image( ""http://s3.amazonaws.com/libapps/customers/558/images/CWRU_Logo.jpg"")); primaryStage.setTitle(""SICU Stress Measurement System""); primaryStage.setScene(new Scene(root)); primaryStage.setMaximized(true); primaryStage.show(); } public static void main(String[] args) { launch(args); } } ","/* *\ ** SICU Stress Measurement System ** ** Project P04 | C380 Team A ** ** EBME 380: Biomedical Engineering Design Experience ** ** Case Western Reserve University ** ** 2016 Fall Semester ** \* */ package edu.cwru.sicu_sms; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; /** * The main stage of the front-end program for interfacing with the electronic system. * * @since September 27, 2016 * @author Ted Frohlich <ttf10@case.edu> * @author Abby Walker <amw138@case.edu> */ public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load( getClass().getResource(""sicu_sms.fxml"") ); primaryStage.setTitle(""SICU Stress Measurement System""); primaryStage.setScene(new Scene(root)); primaryStage.setMaximized(true); primaryStage.show(); } public static void main(String[] args) { launch(args); } } " Remove duplicated split call from EmploymentParser.,"from typing import Tuple from linkedin_scraper.parsers.base import BaseParser class EmploymentParser(BaseParser): def __init__(self): self.professions_list = self.get_lines_from_datafile( 'professions_list.txt') def parse(self, item: str) -> Tuple[str, str]: """""" Parse LinkedIn employment string into position and company. :param item: employment string :return: position, company """""" if ' at ' in item: # Simplest case, standard LinkedIn format <position> at <company> return tuple(item.split(' at ', maxsplit=1)) words = item.split() for index, word in enumerate(reversed(words)): normalized_word = word.strip(',.-').lower() if normalized_word in self.professions_list: founded_profession_index = len(words) - index break else: # We don't know which is which so return whole string as a position return item, '' # We found profession name in employment string, everything # after it is company name return (' '.join(words[:founded_profession_index]).rstrip(',.- '), ' '.join(words[founded_profession_index:]).lstrip(',.- ')) ","from typing import Tuple from linkedin_scraper.parsers.base import BaseParser class EmploymentParser(BaseParser): def __init__(self): self.professions_list = self.get_lines_from_datafile( 'professions_list.txt') def parse(self, item: str) -> Tuple[str, str]: """""" Parse LinkedIn employment string into position and company. :param item: employment string :return: position, company """""" if ' at ' in item: # Simplest case, standard LinkedIn format <position> at <company> return tuple(item.split(' at ', maxsplit=1)) words = item.split() for index, word in enumerate(reversed(item.split())): normalized_word = word.strip(',.-').lower() if normalized_word in self.professions_list: founded_profession_index = len(words) - index break else: # We don't know which is which so return whole string as a position return item, '' # We found profession name in employment string, everything # after it is company name return (' '.join(words[:founded_profession_index]).rstrip(',.- '), ' '.join(words[founded_profession_index:]).lstrip(',.- ')) " Fix anonymous class exposing functionality," module.exports = { onLoad: function(callback) { if (typeof callback !== 'function') { throw new Error('""onLoad"" must have a callback function'); } withLiveReactload(function(lrload) { var winOnload = window.onload; if (!winOnload || !winOnload.__is_livereactload) { window.onload = function() { // initial load event callback(lrload.state); lrload.winloadDone = true; if (typeof winOnload === 'function' && !winOnload.__is_livereactload) { winOnload(); } } } window.onload.__is_livereactload = true; if (lrload.winloadDone) { // reload event callback(lrload.state) } }) }, setState: function(state) { withLiveReactload(function(lrload) { lrload.state = state; }) }, expose: function(cls, id) { withLiveReactload(function(lrload) { if (lrload.makeHot) { lrload.makeHot({exports: cls}, 'CUSTOM_' + id); } }) } } function withLiveReactload(cb) { if (typeof window !== 'undefined') { var lrload = window.__livereactload; if (lrload) { cb(lrload); } } } "," module.exports = { onLoad: function(callback) { if (typeof callback !== 'function') { throw new Error('""onLoad"" must have a callback function'); } withLiveReactload(function(lrload) { var winOnload = window.onload; if (!winOnload || !winOnload.__is_livereactload) { window.onload = function() { // initial load event callback(lrload.state); lrload.winloadDone = true; if (typeof winOnload === 'function' && !winOnload.__is_livereactload) { winOnload(); } } } window.onload.__is_livereactload = true; if (lrload.winloadDone) { // reload event callback(lrload.state) } }) }, setState: function(state) { withLiveReactload(function(lrload) { lrload.state = state; }) }, expose: function(cls, id) { withLiveReactload(function(lrload) { if (lrload.makeHot) { lrload.makeHot(cls, 'CUSTOM_' + id); } }) } } function withLiveReactload(cb) { if (typeof window !== 'undefined') { var lrload = window.__livereactload; if (lrload) { cb(lrload); } } } " "Check that python-sqlite2 is installed git-svn-id: ad91b9aa7ba7638d69f912c9f5d012e3326e9f74@147 3942dd89-8c5d-46d7-aeed-044bccf3e60c","import sys, os.path has_sqlite = True try: from pysqlite2 import dbapi2 as sqlite except: has_sqlite = False class Statistics: def __init__(self): self.total = 0 self.passed = 0 self.failed = 0 def register(self, manager, parser): manager.register(instance=self, event='input', keyword='stats', callback=self.input, order=65535) manager.register(instance=self, event='exit', keyword='stats', callback=self.exit) def init(self, con): create = """""" CREATE TABLE IF NOT EXISTS statistics ( timestamp TIMESTAMP, feed varchar(255), success integer, failure integer );"""""" cur = con.cursor() cur.execute(create) con.commit() def input(self, feed): if not has_sqlite: raise Exception('module statistics requires python-sqlite2 (Sqlite v3) library.') self.total = len(feed.entries) def exit(self, feed): self.passed = len(feed.entries) self.failed = self.total - self.passed dbname = os.path.join(sys.path[0], feed.manager.configname+"".db"") con = sqlite.connect(dbname) self.init(con) cur = con.cursor() cur.execute(""insert into statistics (timestamp, feed, success, failure) values (date('now'), '%s', %d, %d);"" % (feed.name, self.passed, self.failed)) con.commit() con.close() ","from pysqlite2 import dbapi2 as sqlite import sys, os.path class Statistics: def __init__(self): self.total = 0 self.passed = 0 self.failed = 0 def register(self, manager, parser): manager.register(instance=self, event='input', keyword='stats', callback=self.input, order=65535) manager.register(instance=self, event='exit', keyword='stats', callback=self.exit) def init(self, con): create = """""" CREATE TABLE IF NOT EXISTS statistics ( timestamp TIMESTAMP, feed varchar(255), success integer, failure integer );"""""" cur = con.cursor() cur.execute(create) con.commit() def input(self, feed): self.total = len(feed.entries) def exit(self, feed): self.passed = len(feed.entries) self.failed = self.total - self.passed dbname = os.path.join(sys.path[0], feed.manager.configname+"".db"") con = sqlite.connect(dbname) self.init(con) cur = con.cursor() cur.execute(""insert into statistics (timestamp, feed, success, failure) values (date('now'), '%s', %d, %d);"" % (feed.name, self.passed, self.failed)) con.commit() con.close() " Allow function declaration name to be an Identifier node,"'use strict'; var Node = require('./Node'); var ok = require('assert').ok; class FunctionDeclaration extends Node { constructor(def) { super('FunctionDeclaration'); this.name = def.name; this.params = def.params; this.body = this.makeContainer(def.body); } generateCode(codegen) { var name = this.name; var params = this.params; var body = this.body; var statement = this.statement; if (name != null) { ok(typeof name === 'string' || name.type === 'Identifier', 'Function name should be a string or Identifier'); } if (name) { codegen.write('function '); codegen.generateCode(name); codegen.write('('); } else { codegen.write('function('); } if (params && params.length) { for (let i=0, paramsLen = params.length; i<paramsLen; i++) { if (i !== 0) { codegen.write(', '); } var param = params[i]; if (typeof param === 'string') { codegen.write(param); } else { if (param.type !== 'Identifier') { throw new Error('Illegal param: ' + param); } codegen.generateCode(param); } } } codegen.write(') '); var oldInFunction = codegen.inFunction; codegen.inFunction = true; codegen.generateBlock(body); codegen.inFunction = oldInFunction; if (statement) { codegen.write('\n'); } } isCompoundExpression() { return true; } } module.exports = FunctionDeclaration;","'use strict'; var Node = require('./Node'); var ok = require('assert').ok; class FunctionDeclaration extends Node { constructor(def) { super('FunctionDeclaration'); this.name = def.name; this.params = def.params; this.body = this.makeContainer(def.body); } generateCode(codegen) { var name = this.name; var params = this.params; var body = this.body; var statement = this.statement; if (name != null) { ok(typeof name === 'string', 'Function name should be a string'); } codegen.write('function' + (name ? ' ' + name : '') + '('); if (params && params.length) { for (let i=0, paramsLen = params.length; i<paramsLen; i++) { if (i !== 0) { codegen.write(', '); } var param = params[i]; if (typeof param === 'string') { codegen.write(param); } else { if (param.type !== 'Identifier') { throw new Error('Illegal param: ' + param); } codegen.generateCode(param); } } } codegen.write(') '); var oldInFunction = codegen.inFunction; codegen.inFunction = true; codegen.generateBlock(body); codegen.inFunction = oldInFunction; if (statement) { codegen.write('\n'); } } isCompoundExpression() { return true; } } module.exports = FunctionDeclaration;" "Add _fields cache Change _update to _apply and add option for non-required fields"," from collections import defaultdict from inspect import classify_class_attrs from django.forms import ValidationError from django.utils.functional import cached_property from .fields import field from .utils import DictObject class DataView(object): def __init__(self, obj=None, **kwargs): if obj is None: obj = DictObject() self._obj = obj self._kwargs = kwargs @cached_property def _fields(self): return { name: prop for name, kind, cls, prop in classify_class_attrs(self.__class__) if isinstance(prop, field) } @cached_property def _field_names(self): return tuple(self._fields.keys()) def _reduce(self): ''' Reduce our instance to its serialisable state. Returns a dict. ''' return { name: getattr(self, name) for name in self._field_names } def _apply(self, data, update=False): ''' Update an instance from supplied data. If update is False, all fields not tagged as ._required=False MUST be supplied in the data dict. ''' errors = defaultdict(list) for name in self._field_names: try: setattr(self, name, data[name]) except KeyError: if self.update: pass if getattr(self._fields[name], '_required', True): errors[name].append( ValidationError('This field is required') ) except ValidationError as e: errors[name].append(e.message) self._errors = dict(errors) if errors: raise ValidationError(self._errors) return self._obj "," from collections import defaultdict from inspect import classify_class_attrs from django.forms import ValidationError from django.utils.functional import cached_property from .fields import field from .utils import DictObject class DataView(object): def __init__(self, obj=None, **kwargs): if obj is None: obj = DictObject() self._obj = obj self._kwargs = kwargs @cached_property def _field_names(self): return tuple( name for name, kind, cls, prop in classify_class_attrs(self.__class__) if isinstance(prop, field) ) def _reduce(self): ''' Reduce our instance to its serialisable state. Returns a dict. ''' return { name: getattr(self, name) for name in self._field_names } def _update(self, data): ''' Update an instance from supplied data. ''' errors = defaultdict(list) for name in self._field_names: if name in data: try: setattr(self, name, data[name]) except ValidationError as e: errors[name].append(e.message) self._errors = dict(errors) if errors: raise ValidationError(self._errors) return self._obj " Fix bug with scrollbar in TB10,"package gui.sub_controllers; import gui.GraphDrawer; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.scene.control.ScrollBar; /** * Created by TUDelft SID on 29-5-2017. */ public class PanningController { private ScrollBar scrollbar; private GraphDrawer drawer; public PanningController(ScrollBar scrollBar, GraphDrawer drawer) { this.scrollbar = scrollBar; this.drawer = drawer; initialize(); } public void initialize() { scrollbar.setMax(drawer.getZoomLevel()); scrollbar.setVisibleAmount(drawer.getZoomLevel()); scrollbar.valueProperty().addListener(new ChangeListener<Number>() { public void changed(ObservableValue<? extends Number> ov, Number old_val, Number new_val) { System.out.println(""delta: "" + (new_val.doubleValue() - old_val.doubleValue())); } }); } public void setScrollbarSize(double factor) { setScrollbarSize(factor, (int) (scrollbar.getMax() / 2)); } public void setScrollbarSize(double factor, int column) { double max = scrollbar.getMax(); double amount = scrollbar.getVisibleAmount(); if ((factor < 1 && amount < 1) || (factor > 1 && amount >= max)) { return; } amount = scrollbar.getVisibleAmount() * factor; scrollbar.setValue(column); scrollbar.setVisibleAmount(amount); System.out.println(amount); } } ","package gui.sub_controllers; import gui.GraphDrawer; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.scene.control.ScrollBar; /** * Created by TUDelft SID on 29-5-2017. */ public class PanningController { private ScrollBar scrollbar; private GraphDrawer drawer; public PanningController(ScrollBar scrollBar, GraphDrawer drawer) { this.scrollbar = scrollBar; this.drawer = drawer; initialize(); } public void initialize() { scrollbar.setMax(drawer.getRadius()); scrollbar.setVisibleAmount(drawer.getRadius()); scrollbar.valueProperty().addListener(new ChangeListener<Number>() { public void changed(ObservableValue<? extends Number> ov, Number old_val, Number new_val) { System.out.println(""delta: "" + (new_val.doubleValue() - old_val.doubleValue())); } }); } public void setScrollbarSize(double factor) { setScrollbarSize(factor, (int) (scrollbar.getMax() / 2)); } public void setScrollbarSize(double factor, int column) { double max = scrollbar.getMax(); double amount = scrollbar.getVisibleAmount(); if ((factor < 1 && amount < 1) || (factor > 1 && amount >= max)) { return; } amount = scrollbar.getVisibleAmount() * factor; scrollbar.setValue(column); scrollbar.setVisibleAmount(amount); System.out.println(amount); } } " Fix CD fail lambda python,"# Invoked by: CloudWatch Events # Returns: Error or status message # # Triggered periodically to check if the CD CodePipeline has failed, and # publishes a notification import boto3 import traceback import json import os from datetime import datetime, timedelta code_pipeline = boto3.client('codepipeline') sns = boto3.client('sns') def post_notification(action_state): topic_arn = os.environ['CODEPIPELINE_FAILURES_TOPIC_ARN'] message = json.dumps(action_state) sns.publish(TopicArn=topic_arn, Message=message) def lambda_handler(event, context): try: print('Checking pipeline state...') pipeline_name = os.environ['PIPELINE_NAME'] pipeline_state = code_pipeline.get_pipeline_state(name=pipeline_name) for stage_state in pipeline_state['stageStates']: for action_state in stage_state['actionStates']: if 'latestExecution' in action_state: execution = action_state['latestExecution'] timezone = execution['lastStatusChange'].tzinfo period_start = datetime.now(timezone) - timedelta(seconds=60) if execution['lastStatusChange'] > period_start: if execution['status'] == 'Failed': post_notification(action_state) return '...Done' except Exception as e: print('Function failed due to exception.') print(e) traceback.print_exc() ","# Invoked by: CloudWatch Events # Returns: Error or status message # # Triggered periodically to check if the CD CodePipeline has failed, and # publishes a notification import boto3 import traceback import json import os from datetime import datetime, timedelta code_pipeline = boto3.client('codepipeline') sns = boto3.client('sns') def post_notification(action_state): topic_arn = os.environ['CODEPIPELINE_FAILURES_TOPIC_ARN'] message = json.dumps(action_state) sns.publish(TopicArn=topic_arn, Message=message) def lambda_handler(event, context): try: print('Checking pipeline state...') period_start = datetime.now() - timedelta(seconds=60) pipeline_name = os.environ['PIPELINE_NAME'] pipeline_state = code_pipeline.get_pipeline_state(name=pipeline_name) for stage_state in pipeline_state['stageStates']: for action_state in stage_state['actionStates']: exec = action_state['latestExecution'] if execution['lastStatusChange'] > period_start: if execution['status'] == 'Failed': post_notification(action_state) return '...Done' except Exception as e: print('Function failed due to exception.') print(e) traceback.print_exc() put_job_failure(job, 'Function exception: ' + str(e)) " "Allow ""Authorization"" header to be used, in the CORS preflight request","<?php namespace Silktide\LazyBoy\Provider; use Pimple\Container; use Pimple\ServiceProviderInterface; use Silex\Application; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; /** * Enables application to handles CORS requests * * TODO: Review security implications */ class CorsServiceProvider implements ServiceProviderInterface { public function register(Container $app) { if ($app instanceof Application) { //handling CORS preflight request $app->before(function (Request $request) { if ($request->getMethod() === ""OPTIONS"") { $response = new Response(); $response->headers->set(""Access-Control-Allow-Origin"",""*""); $response->headers->set(""Access-Control-Allow-Methods"",""GET,POST,PUT,DELETE,OPTIONS""); $response->headers->set(""Access-Control-Allow-Headers"",""Content-Type,Authorization""); $response->setStatusCode(200); $response->send(); exit(); } }, Application::EARLY_EVENT); //handling CORS response with right headers $app->after(function (Request $request, Response $response) { $response->headers->set(""Access-Control-Allow-Origin"",""*""); $response->headers->set(""Access-Control-Allow-Methods"",""GET,POST,PUT,DELETE,OPTIONS""); }); } } } ","<?php /** * Silktide Nibbler. Copyright 2013-2014 Silktide Ltd. All Rights Reserved. */ namespace Silktide\LazyBoy\Provider; use Pimple\Container; use Pimple\ServiceProviderInterface; use Silex\Application; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; /** * Enables application to handles CORS requests * * TODO: Review security implications */ class CorsServiceProvider implements ServiceProviderInterface { public function register(Container $app) { if ($app instanceof Application) { //handling CORS preflight request $app->before(function (Request $request) { if ($request->getMethod() === ""OPTIONS"") { $response = new Response(); $response->headers->set(""Access-Control-Allow-Origin"",""*""); $response->headers->set(""Access-Control-Allow-Methods"",""GET,POST,PUT,DELETE,OPTIONS""); $response->headers->set(""Access-Control-Allow-Headers"",""Content-Type""); $response->setStatusCode(200); $response->send(); exit(); } }, Application::EARLY_EVENT); //handling CORS response with right headers $app->after(function (Request $request, Response $response) { $response->headers->set(""Access-Control-Allow-Origin"",""*""); $response->headers->set(""Access-Control-Allow-Methods"",""GET,POST,PUT,DELETE,OPTIONS""); }); } } } " Comment too-verbose JSON structure logging,"var fs = require(""fs""); var PEG = require(""pegjs""); var parser = PEG.buildParser(fs.readFileSync(""parser.pegjs"", ""utf8"")); var tunes = fs.readFileSync(""test/tunes.txt"", ""utf8"").split(""\n\n""); var mistakes = 0; tunes.forEach(function(p) { try { var parsed = parser.parse(p + ""\n""); console.log(""\x1B[0;32m:)\x1B[0m "" + parsed.header.title) //console.log(JSON.stringify(parsed, null, 2)) } catch (error) { console.log(""\x1B[0;31m\nSyntax Error:""); console.log(error.message); console.log(""line: "" + error.line); console.log(""column: "" + error.column); var debugLine = Array(error.column).join(""-"") + ""^""; var debugMargin = Array(error.line.toString().length + 2).join(""-""); var i; var lines = p.split(""\n""); for (i = 0; i < error.line; i++) console.log((i + 1) + "" "" + lines[i]); console.log(debugMargin + debugLine) for (i = error.line + 1; i < lines.length; i++) console.log(i + "" "" + lines[i]); mistakes += 1; } }); process.exit(mistakes.length); ","var fs = require(""fs""); var PEG = require(""pegjs""); var parser = PEG.buildParser(fs.readFileSync(""parser.pegjs"", ""utf8"")); var tunes = fs.readFileSync(""test/tunes.txt"", ""utf8"").split(""\n\n""); var mistakes = 0; tunes.forEach(function(p) { try { var parsed = parser.parse(p + ""\n""); console.log(""\x1B[0;32m:)\x1B[0m "" + parsed.header.title) console.log(JSON.stringify(parsed, null, 2)) } catch (error) { console.log(""\x1B[0;31m\nSyntax Error:""); console.log(error.message); console.log(""line: "" + error.line); console.log(""column: "" + error.column); var debugLine = Array(error.column).join(""-"") + ""^""; var debugMargin = Array(error.line.toString().length + 2).join(""-""); var i; var lines = p.split(""\n""); for (i = 0; i < error.line; i++) console.log((i + 1) + "" "" + lines[i]); console.log(debugMargin + debugLine) for (i = error.line + 1; i < lines.length; i++) console.log(i + "" "" + lines[i]); mistakes += 1; } }); process.exit(mistakes.length); " "Exclude noisy ""repairCost"" meta field","package roycurtis.signshopexport.json; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; /** Exclusions class for blacklisting objects and fields in Gson */ public class Exclusions implements ExclusionStrategy { @Override public boolean shouldSkipField(FieldAttributes f) { String name = f.getName(); return // Ignore dynamic CraftBukkit handle field name.equalsIgnoreCase(""handle"") // Ignore book page contents || name.equalsIgnoreCase(""pages"") // Ignore unsupported tags || name.equalsIgnoreCase(""unhandledTags"") // Ignore redundant data object || name.equalsIgnoreCase(""data"") // Ignore hide flags || name.equalsIgnoreCase(""hideFlag"") // Ignore repair costs || name.equalsIgnoreCase(""repairCost"") // Ignore skull profiles || name.equalsIgnoreCase(""profile"") // Ignore shield patterns || name.equalsIgnoreCase(""blockEntityTag""); } @Override public boolean shouldSkipClass(Class<?> clazz) { String name = clazz.getSimpleName(); if ( name.equalsIgnoreCase(""ItemStack"") ) if ( clazz.getTypeName().startsWith(""net.minecraft.server"") ) return true; return name.equalsIgnoreCase(""ChatComponentText""); } }","package roycurtis.signshopexport.json; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; /** Exclusions class for blacklisting objects and fields in Gson */ public class Exclusions implements ExclusionStrategy { @Override public boolean shouldSkipField(FieldAttributes f) { String name = f.getName(); return // Ignore dynamic CraftBukkit handle field name.equalsIgnoreCase(""handle"") // Ignore book page contents || name.equalsIgnoreCase(""pages"") // Ignore unsupported tags || name.equalsIgnoreCase(""unhandledTags"") // Ignore redundant data object || name.equalsIgnoreCase(""data"") // Ignore hide flags || name.equalsIgnoreCase(""hideFlag"") // Ignore skull profiles || name.equalsIgnoreCase(""profile"") // Ignore shield patterns || name.equalsIgnoreCase(""blockEntityTag""); } @Override public boolean shouldSkipClass(Class<?> clazz) { String name = clazz.getSimpleName(); if ( name.equalsIgnoreCase(""ItemStack"") ) if ( clazz.getTypeName().startsWith(""net.minecraft.server"") ) return true; return name.equalsIgnoreCase(""ChatComponentText""); } }" Fix ip -> target bug,"<?php namespace CascadeEnergy\ServiceDiscovery\Consul; use CascadeEnergy\ServiceDiscovery\ServiceDiscoveryClientInterface; class ConsulDns implements ServiceDiscoveryClientInterface { private $lookupService; public function __construct(callable $lookupService = null) { $this->lookupService = $lookupService; if (is_null($lookupService)) { $this->lookupService = ""dns_get_record""; } } public function getServiceAddress($serviceName, $version = null) { $dnsEntry = ""$serviceName.service.consul""; if (!empty($version)) { $dnsEntry = ""$version.$dnsEntry""; } $resultList = call_user_func($this->lookupService, $dnsEntry, DNS_SRV); if (empty($resultList)) { return false; } $ipAddress = ''; $port = '80'; foreach ($resultList as $result) { if (isset($result['target'])) { $ipAddress = $result['target']; } if (isset($result['port'])) { $port = $result['port']; } } return ""$ipAddress:$port""; } } ","<?php namespace CascadeEnergy\ServiceDiscovery\Consul; use CascadeEnergy\ServiceDiscovery\ServiceDiscoveryClientInterface; class ConsulDns implements ServiceDiscoveryClientInterface { private $lookupService; public function __construct(callable $lookupService = null) { $this->lookupService = $lookupService; if (is_null($lookupService)) { $this->lookupService = ""dns_get_record""; } } public function getServiceAddress($serviceName, $version = null) { $dnsEntry = ""$serviceName.service.consul""; if (!empty($version)) { $dnsEntry = ""$version.$dnsEntry""; } $resultList = call_user_func($this->lookupService, $dnsEntry, DNS_SRV); if (empty($resultList)) { return false; } $ipAddress = ''; $port = '80'; foreach ($resultList as $result) { if (isset($result['host'])) { $ipAddress = $result['host']; } if (isset($result['port'])) { $port = $result['port']; } } return ""$ipAddress:$port""; } } " Use the Symfony Filesystem to test symlinks,"<?php /* * This file is part of Contao Manager. * * (c) Contao Association * * @license LGPL-3.0-or-later */ namespace Contao\ManagerApi\IntegrityCheck; use Contao\ManagerApi\ApiKernel; use Contao\ManagerApi\I18n\Translator; use Crell\ApiProblem\ApiProblem; use Symfony\Component\Filesystem\Filesystem; class SymlinkCheck extends AbstractIntegrityCheck { /** * @var ApiKernel */ private $kernel; /** * Constructor. * * @param ApiKernel $kernel * @param Translator $translator */ public function __construct(ApiKernel $kernel, Translator $translator) { parent::__construct($translator); $this->kernel = $kernel; } public function run() { if (($error = $this->canCreateSymlinks()) === null) { return null; } return (new ApiProblem( $this->trans('symlink.title'), 'https://php.net/symlink' ))->setDetail($error); } private function canCreateSymlinks() { if (!function_exists('symlink')) { return ''; } try { $filesystem = new Filesystem(); $tempname = tempnam(sys_get_temp_dir(), ''); $filesystem->remove($tempname); $filesystem->symlink($this->kernel->getProjectDir(), $tempname); $filesystem->remove($tempname); } catch (\Exception $e) { return $e->getMessage(); } return null; } } ","<?php /* * This file is part of Contao Manager. * * (c) Contao Association * * @license LGPL-3.0-or-later */ namespace Contao\ManagerApi\IntegrityCheck; use Contao\ManagerApi\I18n\Translator; use Contao\ManagerApi\System\ServerInfo; use Crell\ApiProblem\ApiProblem; class SymlinkCheck extends AbstractIntegrityCheck { /** * @var ServerInfo */ private $serverInfo; /** * Constructor. */ public function __construct(ServerInfo $serverInfo, Translator $translator) { parent::__construct($translator); $this->serverInfo = $serverInfo; } public function run() { // Skip symlink check on Windows for now if ($this->serverInfo->getPlatform() === ServerInfo::PLATFORM_WINDOWS) { return null; } if ($this->canCreateSymlinks()) { return null; } return new ApiProblem( $this->trans('symlink.title'), 'https://php.net/symlink' ); } private function canCreateSymlinks() { if (!function_exists('symlink')) { return false; } $tmpfile = tempnam(sys_get_temp_dir(), ''); @unlink($tmpfile); $result = @symlink(__FILE__, $tmpfile); @unlink($tmpfile); return true === $result; } } " Set window.location.href so that it is picked up on componentDidMount.,"'use strict'; jest.autoMockOff(); jest.mock('jquery'); // Fixes https://github.com/facebook/jest/issues/78 jest.dontMock('react'); jest.dontMock('underscore'); describe(""Server rendering"", function () { var React; var App; var document; var home_url = ""http://localhost/""; var home = { ""@id"": ""/"", ""@type"": [""portal""], ""portal_title"": ""ENCODE"", ""title"": ""Home"" }; beforeEach(function () { require('../../libs/react-patches'); React = require('react'); App = require('..'); var server_app = <App context={home} href={home_url} />; var markup = '<!DOCTYPE html>\n' + React.renderToString(server_app); var parser = new DOMParser(); document = parser.parseFromString(markup, 'text/html'); window.location.href = home_url; }); it(""renders the application to html"", function () { expect(document.title).toBe(home.portal_title); }); it(""react render http-equiv correctly"", function () { var meta_http_equiv = document.querySelectorAll('meta[http-equiv]'); expect(meta_http_equiv.length).not.toBe(0); }); it(""mounts the application over the rendered html"", function () { var props = App.getRenderedProps(document); var app = React.render(<App {...props} />, document); expect(app.getDOMNode()).toBe(document.documentElement); }); }); ","'use strict'; jest.autoMockOff(); jest.mock('jquery'); // Fixes https://github.com/facebook/jest/issues/78 jest.dontMock('react'); jest.dontMock('underscore'); describe(""Server rendering"", function () { var React; var App; var document; var home_url = ""http://localhost/""; var home = { ""@id"": ""/"", ""@type"": [""portal""], ""portal_title"": ""ENCODE"", ""title"": ""Home"" }; beforeEach(function () { require('../../libs/react-patches'); React = require('react'); App = require('..'); var server_app = <App context={home} href={home_url} />; var markup = '<!DOCTYPE html>\n' + React.renderToString(server_app); var parser = new DOMParser(); document = parser.parseFromString(markup, 'text/html'); }); it(""renders the application to html"", function () { expect(document.title).toBe(home.portal_title); }); it(""react render http-equiv correctly"", function () { var meta_http_equiv = document.querySelectorAll('meta[http-equiv]'); expect(meta_http_equiv.length).not.toBe(0); }); it(""mounts the application over the rendered html"", function () { var props = App.getRenderedProps(document); var app = React.render(<App {...props} />, document); expect(app.getDOMNode()).toBe(document.documentElement); }); }); " "Create ""Register configurations"" method and move config codes","<?php namespace Juy\ActiveMenu; use Illuminate\Support\ServiceProvider as IlluminateServiceProvider; class ServiceProvider extends IlluminateServiceProvider { /** * Indicates if loading of the provider is deferred * * @var bool */ protected $defer = false; /** * Register the application services * * @return void */ public function register() { $this->app->singleton('active', function($app) { return new Active($app['router']->current()->getName()); }); } /** * Perform post-registration booting of services * * @return void */ public function boot() { // Add custom blade directive @ifActiveUrl \Blade::directive('ifActiveRoute', function($expression) { return ""<?php if (Active::route({$expression})): ?>""; }); // Register configurations $this->registerConfigurations(); } /** * Register configurations * * @return void */ protected function registerConfigurations() { // Default package configuration $this->mergeConfigFrom( __DIR__ . '/../config/activemenu.php', 'activemenu' ); // Publish the config file $this->publishes([ __DIR__ . '/../config/activemenu.php' => config_path('activemenu.php') ], 'config'); } } ","<?php namespace Juy\ActiveMenu; use Illuminate\Support\ServiceProvider as IlluminateServiceProvider; class ServiceProvider extends IlluminateServiceProvider { /** * Indicates if loading of the provider is deferred * * @var bool */ protected $defer = false; /** * Register the application services * * @return void */ public function register() { // Default package configuration $this->mergeConfigFrom( __DIR__ . '/../config/activemenu.php', 'activemenu' ); $this->app->singleton('active', function($app) { return new Active($app['router']->current()->getName()); }); } /** * Perform post-registration booting of services * * @return void */ public function boot() { // Add custom blade directive @ifActiveUrl \Blade::directive('ifActiveRoute', function($expression) { return ""<?php if (Active::route({$expression})): ?>""; }); // Publish the config file $this->publishConfig(); } /** * Publish the config file */ protected function publishConfig() { $this->publishes([ __DIR__ . '/../config/activemenu.php' => config_path('activemenu.php') ], 'config'); } } " Update sampledata generator to allow component resources,"""""""Module for factories for tesing resources application."""""" import random from factory import DjangoModelFactory, Faker, post_generation from factory.faker import faker from resources.models import ( Resource, ResourceComponent, ) class ResourceFactory(DjangoModelFactory): """"""Factory for generating resources."""""" name = Faker('sentence') description = Faker('paragraph', nb_sentences=5) class Meta: """"""Metadata for class."""""" model = Resource @post_generation def create_components(self, create, extracted, **kwargs): """"""Create components for resource."""""" FAKER = faker.Faker() number_of_components = random.randint(1, 9) for i in range(number_of_components): component_name = FAKER.sentence() component_type = random.choice(list(ResourceComponent.COMPONENT_TYPE_DATA)) resource_count = Resource.objects.count() if component_type == ResourceComponent.TYPE_WEBSITE: ResourceComponent.objects.create( name=component_name, resource=self, component_url=FAKER.url(), ) elif component_type == ResourceComponent.TYPE_RESOURCE and resource_count >= 2: resources = list(Resource.objects.exclude(pk=self.pk)) resource_component = resources[random.randint(0, len(resources) - 1)] ResourceComponent.objects.create( name=resource_component.name, resource=self, component_resource=resource_component, ) # TODO: Implement all types of components else: ResourceComponent.objects.create( name=component_name, resource=self, component_url=FAKER.url(), ) ","""""""Module for factories for tesing resources application."""""" import random from factory import DjangoModelFactory, Faker, post_generation from factory.faker import faker from resources.models import ( Resource, ResourceComponent, ) class ResourceFactory(DjangoModelFactory): """"""Factory for generating resources."""""" name = Faker('sentence') description = Faker('paragraph', nb_sentences=5) class Meta: """"""Metadata for class."""""" model = Resource @post_generation def create_components(self, create, extracted, **kwargs): """"""Create components for resource."""""" FAKER = faker.Faker() number_of_components = random.randint(0, 9) for i in range(number_of_components): component_name = FAKER.sentence() component_type = random.choice(list(ResourceComponent.COMPONENT_TYPE_DATA)) if component_type == ResourceComponent.TYPE_WEBSITE: ResourceComponent.objects.create( name=component_name, resource=self, component_url=FAKER.url(), ) # TODO: Implement all types of components else: ResourceComponent.objects.create( name=component_name, resource=self, component_url=FAKER.url(), ) " "Fix access to one exam page now is only for logged users","<?php namespace Egzaminer\Exam; use Exception; use Egzaminer\Question\Questions; use Egzaminer\Question\Answers; use Egzaminer\Controller as Controller; class Exam extends Controller { public function showAction($id) { $testInfo = (new ExamModel())->getInfo($id); if (false === $testInfo) { throw new Exception('Exam not exists!'); } $questions = (new Questions())->getByExamId($id); $answers = (new Answers())->getAnswersByQuestions($questions); // if form was send if (!empty($_POST)) { $stats = (new ExamStat())->getStats($testInfo, $questions, $_POST); $this->data['test-check'] = [ 'test' => $testInfo, 'questions' => $questions, 'answers' => $answers, 'stats' => $stats, ]; $template = 'test-check'; } else { $this->data['test'] = [ 'title' => $testInfo['title'], 'questions' => $questions, 'answers' => $answers, ]; $template = 'test'; } $this->render($template, $testInfo['title']); } } ","<?php namespace Egzaminer\Exam; use Exception; use Egzaminer\Question\Questions; use Egzaminer\Question\Answers; use Egzaminer\Admin\Dashboard as Controller; class Exam extends Controller { public function showAction($id) { $testInfo = (new ExamModel())->getInfo($id); if (false === $testInfo) { throw new Exception('Exam not exists!'); } $questions = (new Questions())->getByExamId($id); $answers = (new Answers())->getAnswersByQuestions($questions); // if form was send if (!empty($_POST)) { $stats = (new ExamStat())->getStats($testInfo, $questions, $_POST); $this->data['test-check'] = [ 'test' => $testInfo, 'questions' => $questions, 'answers' => $answers, 'stats' => $stats, ]; $template = 'test-check'; } else { $this->data['test'] = [ 'title' => $testInfo['title'], 'questions' => $questions, 'answers' => $answers, ]; $template = 'test'; } $this->render($template, $testInfo['title']); } } " Hide variants select input when product has no variants,"from django import forms from django.utils.translation import pgettext_lazy from ..cart.forms import AddToCartForm from ..product.models import GenericProduct class GenericProductForm(AddToCartForm): base_variant = forms.CharField(widget=forms.HiddenInput()) variant = forms.ChoiceField(required=False) def __init__(self, *args, **kwargs): super(GenericProductForm, self).__init__(*args, **kwargs) self.fields['base_variant'].initial = self.product.base_variant.pk variants = self.product.variants.all().exclude( pk=self.product.base_variant.pk) self.fields['variant'].choices = [(v.pk, v) for v in variants] if not self.product.has_variants(): self.fields['variant'].widget = forms.HiddenInput() def get_variant(self, cleaned_data): pk = cleaned_data.get('variant') or cleaned_data.get('base_variant') variant = self.product.variants.get(pk=pk) return variant class ProductVariantInline(forms.models.BaseInlineFormSet): error_no_items = pgettext_lazy('Product admin error', 'You have to create at least one variant') def clean(self): count = 0 for form in self.forms: if form.cleaned_data: count += 1 if count < 1: raise forms.ValidationError(self.error_no_items) class ImageInline(ProductVariantInline): error_no_items = pgettext_lazy('Product admin error', 'You have to add at least one image') def get_form_class_for_product(product): if isinstance(product, GenericProduct): return GenericProductForm raise NotImplementedError ","from django import forms from django.utils.translation import pgettext_lazy from ..cart.forms import AddToCartForm from ..product.models import GenericProduct class GenericProductForm(AddToCartForm): variant = forms.ChoiceField() def __init__(self, *args, **kwargs): super(GenericProductForm, self).__init__(*args, **kwargs) variants = self.product.variants.all() if self.product.has_variants(): variants = variants.exclude(pk=self.product.base_variant.pk) variant_choices = [(v.pk, v) for v in variants] self.fields['variant'].choices = variant_choices def get_variant(self, cleaned_data): pk = cleaned_data['variant'] return self.product.variants.get(pk=pk) class ProductVariantInline(forms.models.BaseInlineFormSet): error_no_items = pgettext_lazy('Product admin error', 'You have to create at least one variant') def clean(self): count = 0 for form in self.forms: if form.cleaned_data: count += 1 if count < 1: raise forms.ValidationError(self.error_no_items) class ImageInline(ProductVariantInline): error_no_items = pgettext_lazy('Product admin error', 'You have to add at least one image') def get_form_class_for_product(product): if isinstance(product, GenericProduct): return GenericProductForm raise NotImplementedError " "Fix regexp to test regexps in tools. Without this commit we've got `{ test: /\.json$/, loader: 'react-hot!json' }` and it should be just as `{ test: /\.json$/, loader: 'json' }`","import _ from 'lodash'; import webpack from 'webpack'; function addWebpackDevServerScripts(entries, webpackDevServerAddress) { let clientScript = `webpack-dev-server/client?${webpackDevServerAddress}`; let webpackScripts = ['webpack/hot/dev-server', clientScript]; return _.mapValues(entries, entry => webpackScripts.concat(entry)); } export default (config, options) => { if (options.development && options.docs) { let webpackDevServerAddress = `http://localhost:${options.port}`; config = _.extend({}, config, { entry: addWebpackDevServerScripts(config.entry, webpackDevServerAddress), output: _.extend({}, config.output, { publicPath: `${webpackDevServerAddress}/assets/` }), module: _.extend({}, config.module, { loaders: config.module.loaders.map(value => { if (/\.js\/$/.test(value.test.toString())) { return _.extend({}, value, { loader: 'react-hot!' + value.loader }); } else { return value; } }) }), // Remove extract text plugin from dev workflow so hot reload works on css. plugins: config.plugins.concat([ new webpack.NoErrorsPlugin() ]) }); return config; } return config; }; ","import _ from 'lodash'; import webpack from 'webpack'; function addWebpackDevServerScripts(entries, webpackDevServerAddress) { let clientScript = `webpack-dev-server/client?${webpackDevServerAddress}`; let webpackScripts = ['webpack/hot/dev-server', clientScript]; return _.mapValues(entries, entry => webpackScripts.concat(entry)); } export default (config, options) => { if (options.development && options.docs) { let webpackDevServerAddress = `http://localhost:${options.port}`; config = _.extend({}, config, { entry: addWebpackDevServerScripts(config.entry, webpackDevServerAddress), output: _.extend({}, config.output, { publicPath: `${webpackDevServerAddress}/assets/` }), module: _.extend({}, config.module, { loaders: config.module.loaders.map(value => { if (/js/.test(value.test.toString())) { return _.extend({}, value, { loader: 'react-hot!' + value.loader }); } else { return value; } }) }), // Remove extract text plugin from dev workflow so hot reload works on css. plugins: config.plugins.concat([ new webpack.NoErrorsPlugin() ]) }); return config; } return config; }; " Fix array-style access of non-arrays,"<?php /** * */ namespace Mvc5\Test\Config; use Mvc5\Overload; use Mvc5\Test\Test\TestCase; class OverloadTest extends TestCase { /** * */ function test_get_not_overloaded() { $model = new Overload; $model->get('foo')['bar'] = 'baz'; $this->assertNull($model->get('foo')['bar'] ?? null); $model['foo']['bar'] = 'baz'; $this->assertEquals('baz', $model->get('foo')['bar']); } /** * */ function test_overload_offset_get() { $model = new Overload; $model['foo']['bar'] = 'baz'; $this->assertEquals('baz', $model['foo']['bar']); } /** * */ function test_overload_offset_get_config_object() { $model = new Overload(new Overload); $model['foo']['bar'] = 'baz'; $this->assertEquals('baz', $model['foo']['bar']); } /** * */ function test_overload_get_property() { $model = new Overload; $model->foo['bar'] = 'baz'; $this->assertEquals('baz', $model->foo['bar']); } /** * */ function test_overload_get_property_with_config_object() { $model = new Overload(new Overload); $model->foo['bar'] = 'baz'; $this->assertEquals('baz', $model->foo['bar']); } } ","<?php /** * */ namespace Mvc5\Test\Config; use Mvc5\Overload; use Mvc5\Test\Test\TestCase; class OverloadTest extends TestCase { /** * */ function test_get_not_overloaded() { $model = new Overload; $model->get('foo')['bar'] = 'baz'; $this->assertNull($model->get('foo')['bar']); $model['foo']['bar'] = 'baz'; $this->assertEquals('baz', $model->get('foo')['bar']); } /** * */ function test_overload_offset_get() { $model = new Overload; $model['foo']['bar'] = 'baz'; $this->assertEquals('baz', $model['foo']['bar']); } /** * */ function test_overload_offset_get_config_object() { $model = new Overload(new Overload); $model['foo']['bar'] = 'baz'; $this->assertEquals('baz', $model['foo']['bar']); } /** * */ function test_overload_get_property() { $model = new Overload; $model->foo['bar'] = 'baz'; $this->assertEquals('baz', $model->foo['bar']); } /** * */ function test_overload_get_property_with_config_object() { $model = new Overload(new Overload); $model->foo['bar'] = 'baz'; $this->assertEquals('baz', $model->foo['bar']); } } " Fix blueprints to include perfect-scrollbar,"module.exports = { afterInstall: function () { const packagesToRemove = [ 'ember-frost-button', 'ember-frost-checkbox', 'ember-frost-css-core', 'ember-frost-icons', 'ember-frost-link', 'ember-frost-loading', 'ember-frost-password', 'ember-frost-select', 'ember-frost-text', 'ember-frost-textarea', 'ember-frost-theme' ].map((packageName) => { return {name: packageName} }) return this.removePackagesFromProject(packagesToRemove) .then(() => { return this.addBowerPackagesToProject([ {name: 'lodash', target: '^4.10.0'}, {name: 'perfect-scrollbar', target: '>=0.6.7 <2.0.0'} ]) }) .then(() => { return this.addAddonsToProject({ packages: [ {name: 'ember-computed-decorators', target: '>=0.2.2 <2.0.0'}, {name: 'ember-lodash', target: '>=0.0.6 <2.0.0'}, {name: 'ember-one-way-controls', target: '>=0.5.3 <2.0.0'} ] }) }) }, normalizeEntityName: function () { // this prevents an error when the entityName is // not specified (since that doesn't actually matter // to us } } ","module.exports = { afterInstall: function () { const packagesToRemove = [ 'ember-frost-button', 'ember-frost-checkbox', 'ember-frost-css-core', 'ember-frost-icons', 'ember-frost-link', 'ember-frost-loading', 'ember-frost-password', 'ember-frost-select', 'ember-frost-text', 'ember-frost-textarea', 'ember-frost-theme' ].map((packageName) => { return {name: packageName} }) return this.removePackagesFromProject(packagesToRemove) .then(() => { return this.addBowerPackagesToProject([ {name: 'lodash', target: '^4.10.0'} ]) }) .then(() => { return this.addAddonsToProject({ packages: [ {name: 'ember-computed-decorators', target: '>=0.2.2 <2.0.0'}, {name: 'ember-lodash', target: '>=0.0.6 <2.0.0'}, {name: 'ember-one-way-controls', target: '>=0.5.3 <2.0.0'} ] }) }) }, normalizeEntityName: function () { // this prevents an error when the entityName is // not specified (since that doesn't actually matter // to us } } " Update broadcast command to use the user's own channel instead of the global channel due to an over whelming number of notifications,"<?php namespace Kregel\Radio\Commands; use App\Models\User; use Doctrine\Instantiator\Exception\InvalidArgumentException; use Illuminate\Console\Command; use Illuminate\Contracts\Bus\SelfHandling; use Illuminate\Database\Eloquent\Model; use \Kregel\Radio\Models\Notification; use Kregel\Radio\Models\Channel; class Broadcast extends Command implements SelfHandling { protected $signature = 'radio:broadcast'; /** * Execute the console command. * * @return mixed */ public function fire() { $this->info('Firing up'); $global = Channel::where('type', 'global')->first(); $title = $this->ask('What is the title of this broadcast?'); $message = $this->ask('What is your message to your users?'); if(empty($message) || empty($title)) { $this->error('You must fillout both the title and the message.'); return; } $this->info('Making your notification, please know if you have a lot of users this may take a while...'); foreach($global->users as $user) Notification::create([ 'channel_id' => $user->channel->id, 'user_id' => $user->id, 'is_unread' => true, 'name' => $title, 'description' => $message, 'type' => 'general' ]); $this->info('Completed!'); } } ","<?php namespace Kregel\Radio\Commands; use App\Models\User; use Doctrine\Instantiator\Exception\InvalidArgumentException; use Illuminate\Console\Command; use Illuminate\Contracts\Bus\SelfHandling; use Illuminate\Database\Eloquent\Model; use \Kregel\Radio\Models\Notification; use Kregel\Radio\Models\Channel; class Broadcast extends Command implements SelfHandling { protected $signature = 'radio:broadcast'; /** * Execute the console command. * * @return mixed */ public function fire() { $this->info('Firing up'); $global = Channel::where('type', 'global')->first(); $title = $this->ask('What is the title of this broadcast?'); $message = $this->ask('What is your message to your users?'); if(empty($message) || empty($title)) { $this->error('You must fillout both the title and the message.'); return; } $this->info('Making your notification, please know if you have a lot of users this may take a while...'); foreach($global->users as $user) Notification::create([ 'channel_id' => $global->id, 'user_id' => $user->id, 'is_unread' => true, 'name' => $title, 'description' => $message, 'type' => 'general' ]); $this->info('Completed!'); } }" Add testing for the WebAuthn implementation,""""""" This test file tests the lib.tokens.webauthntoken, along with lib.tokens.webauthn. This depends on lib.tokenclass """""" import unittest from copy import copy from privacyidea.lib.tokens import webauthn from privacyidea.lib.tokens.webauthn import COSEALGORITHM from .base import MyTestCase from privacyidea.lib.tokens.webauthntoken import WebAuthnTokenClass, WEBAUTHNACTION from privacyidea.lib.token import init_token from privacyidea.lib.policy import set_policy, SCOPE class WebAuthnTokenTestCase(MyTestCase): RP_ID = 'example.com' RP_NAME = 'ACME' def test_00_users(self): self.setUp_user_realms() set_policy(name=""WebAuthn"", scope=SCOPE.ENROLL, action=WEBAUTHNACTION.RELYING_PARTY_NAME+""=""+self.RP_NAME+"","" +WEBAUTHNACTION.RELYING_PARTY_ID+""=""+self.RP_ID) def test_01_create_token(self): pin = ""1234"" # # Init step 1 # token = init_token({'type': 'webauthn', 'pin': pin}) serial = token.token.serial self.assertEqual(token.type, ""webauthn"") self.assertEqual(WebAuthnTokenClass.get_class_prefix(), ""WAN"") self.assertEqual(WebAuthnTokenClass.get_class_info().get('type'), ""webauthn"") self.assertEqual(WebAuthnTokenClass.get_class_info('type'), ""webauthn"") ",""""""" This test file tests the lib.tokens.webauthntoken, along with lib.tokens.webauthn. This depends on lib.tokenclass """""" from .base import MyTestCase from privacyidea.lib.tokens.webauthntoken import WebAuthnTokenClass, WEBAUTHNACTION from privacyidea.lib.token import init_token from privacyidea.lib.policy import set_policy, SCOPE RP_ID = 'example.com' RP_NAME = 'ACME' class WebAuthnTokenTestCase(MyTestCase): def test_00_users(self): self.setUp_user_realms() set_policy(name=""WebAuthn"", scope=SCOPE.ENROLL, action=WEBAUTHNACTION.RELYING_PARTY_NAME+""=""+RP_NAME+"","" +WEBAUTHNACTION.RELYING_PARTY_ID+""=""+RP_ID) def test_01_create_token(self): pin = ""1234"" # # Init step 1 # token = init_token({'type': 'webauthn', 'pin': pin}) serial = token.token.serial self.assertEqual(token.type, ""webauthn"") self.assertEqual(WebAuthnTokenClass.get_class_prefix(), ""WAN"") self.assertEqual(WebAuthnTokenClass.get_class_info().get('type'), ""webauthn"") self.assertEqual(WebAuthnTokenClass.get_class_info('type'), ""webauthn"") " Update fullcalendar test with Heroku addresses,"$(document).ready(function() { // page is now ready, initialize the calendar... $('#calendar').fullCalendar({ // put your options and callbacks here events: { url: 'http://abeweb.herokuapp.com/calendarRead', type: 'POST', data: { custom_attribute: 'acbd' }, error: function() { alert('There was an error while fetching events!'); } } }) }); function saveEventUpdate(event) { url = 'http://abeweb.herokuapp.com/calendarUpdate' // Create a copy of the event object data = $.extend({}, event); // Replace string date with timestamp (ms since epoch) data.start = data.start.valueOf(); if(data.end != undefined){ data.end = event.end.valueOf(); } data.custom_attribute = 'abcd'; var ret_id = ''; var jqxhr = $.post( url, data, function(responseData) { // Executed on successful update to backend // Newly added event if(event.id == undefined) { // Get event ID from insert response obj = jQuery.parseJSON(responseData); ret_id = obj.id; event.id = ret_id; // Render the event on the calendar $('#calendar').fullCalendar('renderEvent', event, true); } }) .fail(function() { alert( ""Error sending update AJAX"" ); }) } ","$(document).ready(function() { // page is now ready, initialize the calendar... $('#calendar').fullCalendar({ // put your options and callbacks here events: { url: 'http://localhost:3000/calendarRead', type: 'POST', data: { custom_attribute: 'acbd' }, error: function() { alert('There was an error while fetching events!'); } } }) }); function saveEventUpdate(event) { url = 'https://abeweb.herokuapp.com/' // Create a copy of the event object data = $.extend({}, event); // Replace string date with timestamp (ms since epoch) data.start = data.start.valueOf(); if(data.end != undefined){ data.end = event.end.valueOf(); } data.custom_attribute = 'abcd'; var ret_id = ''; var jqxhr = $.post( url, data, function(responseData) { // Executed on successful update to backend // Newly added event if(event.id == undefined) { // Get event ID from insert response obj = jQuery.parseJSON(responseData); ret_id = obj.id; event.id = ret_id; // Render the event on the calendar $('#calendar').fullCalendar('renderEvent', event, true); } }) .fail(function() { alert( ""Error sending update AJAX"" ); }) } " Use token instead of getToken,"<?php namespace AdamWathan\Form; use AdamWathan\Form\ErrorStore\IlluminateErrorStore; use AdamWathan\Form\OldInput\IlluminateOldInputProvider; use Illuminate\Support\ServiceProvider; class FormServiceProvider extends ServiceProvider { protected $defer = false; public function register() { $this->registerErrorStore(); $this->registerOldInput(); $this->registerFormBuilder(); } protected function registerErrorStore() { $this->app->singleton('adamwathan.form.errorstore', function ($app) { return new IlluminateErrorStore($app['session.store']); }); } protected function registerOldInput() { $this->app->singleton('adamwathan.form.oldinput', function ($app) { return new IlluminateOldInputProvider($app['session.store']); }); } protected function registerFormBuilder() { $this->app->singleton('adamwathan.form', function ($app) { $formBuilder = new FormBuilder; $formBuilder->setErrorStore($app['adamwathan.form.errorstore']); $formBuilder->setOldInputProvider($app['adamwathan.form.oldinput']); $formBuilder->setToken($app['session.store']->token()); return $formBuilder; }); } public function provides() { return ['adamwathan.form']; } } ","<?php namespace AdamWathan\Form; use AdamWathan\Form\ErrorStore\IlluminateErrorStore; use AdamWathan\Form\OldInput\IlluminateOldInputProvider; use Illuminate\Support\ServiceProvider; class FormServiceProvider extends ServiceProvider { protected $defer = false; public function register() { $this->registerErrorStore(); $this->registerOldInput(); $this->registerFormBuilder(); } protected function registerErrorStore() { $this->app->singleton('adamwathan.form.errorstore', function ($app) { return new IlluminateErrorStore($app['session.store']); }); } protected function registerOldInput() { $this->app->singleton('adamwathan.form.oldinput', function ($app) { return new IlluminateOldInputProvider($app['session.store']); }); } protected function registerFormBuilder() { $this->app->singleton('adamwathan.form', function ($app) { $formBuilder = new FormBuilder; $formBuilder->setErrorStore($app['adamwathan.form.errorstore']); $formBuilder->setOldInputProvider($app['adamwathan.form.oldinput']); $formBuilder->setToken($app['session.store']->getToken()); return $formBuilder; }); } public function provides() { return ['adamwathan.form']; } } " Make jshint happy with Promise,"'use strict'; var BPromise = require('bluebird'); var request = BPromise.promisify(require('request')); var JXT = require('jxt').createRegistry(); JXT.use(require('./lib/xrd')); module.exports = function (opts, cb) { if (typeof opts === 'string') { opts = {host: opts}; } var config = { ssl: true, json: true, xrd: true }; for (var prop in opts) { config[prop] = opts[prop]; } var scheme = config.ssl ? 'https://' : 'http://'; var getJSON = new BPromise(function (resolve, reject) { request(scheme + config.host + '/.well-known/host-meta.json').spread(function (req, body) { resolve(JSON.parse(body)); }).catch(reject); }); var getXRD = new BPromise(function (resolve, reject) { request(scheme + config.host + '/.well-known/host-meta').spread(function (req, body) { var xrd = JXT.parse(body); resolve(xrd.toJSON()); }).catch(reject); }); return new BPromise(function (resolve, reject) { BPromise.some([getJSON, getXRD], 1).spread(resolve).catch(function () { reject('no-host-meta'); }); }).nodeify(cb); }; ","'use strict'; var Promise = require('bluebird'); var request = Promise.promisify(require('request')); var JXT = require('jxt').createRegistry(); JXT.use(require('./lib/xrd')); module.exports = function (opts, cb) { if (typeof opts === 'string') { opts = {host: opts}; } var config = { ssl: true, json: true, xrd: true }; for (var prop in opts) { config[prop] = opts[prop]; } var scheme = config.ssl ? 'https://' : 'http://'; var getJSON = new Promise(function (resolve, reject) { request(scheme + config.host + '/.well-known/host-meta.json').spread(function (req, body) { resolve(JSON.parse(body)); }).catch(reject); }); var getXRD = new Promise(function (resolve, reject) { request(scheme + config.host + '/.well-known/host-meta').spread(function (req, body) { var xrd = JXT.parse(body); resolve(xrd.toJSON()); }).catch(reject); }); return new Promise(function (resolve, reject) { Promise.some([getJSON, getXRD], 1).spread(resolve).catch(function () { reject('no-host-meta'); }); }).nodeify(cb); }; " Modify Post route to allow for SEO slug suffix.,"<?php require_once(dirname(__FILE__) . '/vendor/autoload.php'); session_start(); spl_autoload_register(function($class) { $parts = explode(""_"", $class); $classSlashSeparated = implode('/', $parts); $pathToFile = ""code/$classSlashSeparated.php""; $fullPathToFile = dirname(__FILE__) . '/' . $pathToFile; if (file_exists($fullPathToFile)) { include $fullPathToFile; } }); try { Toro::serve(array( ""/"" => ""Controller_Index"", ""/available"" => ""Controller_Available"", ""/login"" => ""Controller_Login"", ""/logout"" => ""Controller_Logout"", ""/posts"" => ""Controller_PostList"", ""/posts/new"" => ""Controller_PostNew"", ""/posts/:number/edit"" => ""Controller_PostEdit"", ""/posts/:number/notify-comment"" => ""Controller_PostCommentNotify"", ""/posts/(:number)(/:alpha)?"" => ""Controller_Post"", ""/profile"" => ""Controller_Profile"", ""/user/:number/upvote"" => ""Controller_UserUpvote"", ""/:string/posts"" => ""Controller_UserPosts"", ""/(.*)"" => ""Controller_UserProfile"", ""/map"" => ""Controller_Map"", ""/map/users"" => ""Controller_MapUsers"", )); } catch (Exception $e) { mail(""kalen@magemail.co"", ""MageHero Error"", $e->getTraceAsString()); die(""Uh-oh. Something's not right. Heroes have been deployed to fix it.""); } ","<?php require_once(dirname(__FILE__) . '/vendor/autoload.php'); session_start(); spl_autoload_register(function($class) { $parts = explode(""_"", $class); $classSlashSeparated = implode('/', $parts); $pathToFile = ""code/$classSlashSeparated.php""; $fullPathToFile = dirname(__FILE__) . '/' . $pathToFile; if (file_exists($fullPathToFile)) { include $fullPathToFile; } }); try { Toro::serve(array( ""/"" => ""Controller_Index"", ""/available"" => ""Controller_Available"", ""/login"" => ""Controller_Login"", ""/logout"" => ""Controller_Logout"", ""/posts"" => ""Controller_PostList"", ""/posts/new"" => ""Controller_PostNew"", ""/posts/:number"" => ""Controller_Post"", ""/posts/:number/edit"" => ""Controller_PostEdit"", ""/posts/:number/notify-comment"" => ""Controller_PostCommentNotify"", ""/profile"" => ""Controller_Profile"", ""/user/:number/upvote"" => ""Controller_UserUpvote"", ""/:string/posts"" => ""Controller_UserPosts"", ""/(.*)"" => ""Controller_UserProfile"", ""/map"" => ""Controller_Map"", ""/map/users"" => ""Controller_MapUsers"", )); } catch (Exception $e) { mail(""kalen@magemail.co"", ""MageHero Error"", $e->getTraceAsString()); die(""Uh-oh. Something's not right. Heroes have been deployed to fix it.""); } " Change timestamp format (important for hourly backups).,"from django.core.management.base import BaseCommand from django.core.management import call_command from django.conf import settings from django.utils import timezone import logging import os from danceschool.core.constants import getConstant # Define logger for this file logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Perform a backup of the site database, using configuration options from site settings.' def handle(self, *args, **options): backup_folder = getattr(settings,'BACKUP_LOCATION','/backup') if not os.path.isdir(backup_folder): logger.error( 'Backup failed because destination folder does not exist; ' + 'BACKUP_LOCATION must be updated in project settings.py.' ) return None backup_loc = os.path.join(backup_folder,'%s%s.json' % (getConstant('backups__filePrefix'), timezone.now().strftime('%Y%m%d%H%M%S'))) if not getConstant('backups__enableDataBackups'): logger.info('Aborting backup because backups are not enabled in global settings.') return None logger.info('Beginning JSON backup to file %s.' % backup_loc) with open(backup_loc,'w') as f: try: call_command('dumpdata',indent=1,format='json',natural_foreign=True,stdout=f) logger.info('Backup completed.') except: logger.error('Backup to file %s failed.' % backup_loc) ","from django.core.management.base import BaseCommand from django.core.management import call_command from django.conf import settings from django.utils import timezone import logging import os from danceschool.core.constants import getConstant # Define logger for this file logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Perform a backup of the site database, using configuration options from site settings.' def handle(self, *args, **options): backup_folder = getattr(settings,'BACKUP_LOCATION','/backup') if not os.path.isdir(backup_folder): logger.error( 'Backup failed because destination folder does not exist; ' + 'BACKUP_LOCATION must be updated in project settings.py.' ) return None backup_loc = os.path.join(backup_folder,'%s%s.json' % (getConstant('backups__filePrefix'), timezone.now().strftime('%Y%m%d'))) if not getConstant('backups__enableDataBackups'): logger.info('Aborting backup because backups are not enabled in global settings.') return None logger.info('Beginning JSON backup to file %s.' % backup_loc) with open(backup_loc,'w') as f: try: call_command('dumpdata',indent=1,format='json',natural_foreign=True,stdout=f) logger.info('Backup completed.') except: logger.error('Backup to file %s failed.' % backup_loc) " Return empty array if none found,"<?php namespace Modules\Media\Image; use Illuminate\Contracts\Config\Repository; class ThumbnailsManager { /** * @var Module */ private $module; /** * @var Repository */ private $config; /** * @param Repository $config */ public function __construct(Repository $config) { $this->module = app('modules'); $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('asgard.' . $enabledModule->getName()) . '.thumbnails'); if (!is_null($configuration)) { $thumbnails = array_merge($thumbnails, $configuration); } } return $thumbnails; } /** * Find the filters for the given thumbnail * @param $thumbnail * @return array */ public function find($thumbnail) { foreach ($this->all() as $thumbName => $filters) { if ($thumbName == $thumbnail) { return $filters; } } return []; } } ","<?php namespace Modules\Media\Image; use Illuminate\Contracts\Config\Repository; class ThumbnailsManager { /** * @var Module */ private $module; /** * @var Repository */ private $config; /** * @param Repository $config */ public function __construct(Repository $config) { $this->module = app('modules'); $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('asgard.' . $enabledModule->getName()) . '.thumbnails'); if (!is_null($configuration)) { $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; } } } } " Enforce that our Including Hyperlink includes," from marshmallow_jsonapi.fields import HyperlinkRelated from marshmallow_jsonapi.utils import get_value_or_raise class IncludingHyperlinkRelated(HyperlinkRelated): def __init__(self, nestedObj, *args, **kwargs): if callable(nestedObj): nestedObj = nestedObj(many=False) self.nestedObj = nestedObj kwargs['type_'] = "" "" kwargs['include_data'] = True super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs) def add_resource_linkage(self, value): def render(item): attributes = self._extract_attributes(item) type_ = attributes.pop('type', self.type_) return {'type': type_, 'id': get_value_or_raise(self.id_field, item), 'attributes': attributes} if self.many: included_data = [render(each) for each in value] else: included_data = render(value) return included_data def _extract_attributes(self, value): sub = self.nestedObj.dump(value).data try: return sub[""data""][""attributes""] except (KeyError, TypeError): # we are a classic type pass return sub "," from marshmallow_jsonapi.fields import HyperlinkRelated from marshmallow_jsonapi.utils import get_value_or_raise class IncludingHyperlinkRelated(HyperlinkRelated): def __init__(self, nestedObj, *args, **kwargs): if callable(nestedObj): nestedObj = nestedObj(many=False) self.nestedObj = nestedObj super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs) def add_resource_linkage(self, value): def render(item): attributes = self._extract_attributes(item) type_ = attributes.pop('type', self.type_) return {'type': type_, 'id': get_value_or_raise(self.id_field, item), 'attributes': attributes} if self.many: included_data = [render(each) for each in value] else: included_data = render(value) return included_data def _extract_attributes(self, value): sub = self.nestedObj.dump(value).data try: return sub[""data""][""attributes""] except (KeyError, TypeError): # we are a classic type pass return sub " Handle None returned from poll(),""""""" Primary entrypoint for applications wishing to implement Python Kafka Streams """""" import logging import confluent_kafka as kafka log = logging.getLogger(__name__) class KafkaStream(object): """""" Encapsulates stream graph processing units """""" def __init__(self, topology, kafka_config): self.topology = topology self.kafka_config = kafka_config self.consumer = None def start(self): """""" Begin streaming the data across the topology """""" self.consumer = kafka.Consumer({'bootstrap.servers': self.kafka_config.BOOTSTRAP_SERVERS, 'group.id': 'test'}) #, 'group.id': 'testgroup', #'default.topic.config': {'auto.offset.reset': 'smallest'}}) log.debug('Subscribing to topics %s', self.topology.kafka_topics) self.consumer.subscribe(self.topology.kafka_topics) log.debug('Subscribed to topics') self.run() def run(self): running = True while running: msg = self.consumer.poll() if msg is None: continue elif not msg.error(): print('Received message: %s' % msg.value().decode('utf-8')) elif msg.error().code() != kafka.KafkaError._PARTITION_EOF: print(msg.error()) running = False self.consumer.close() ",""""""" Primary entrypoint for applications wishing to implement Python Kafka Streams """""" import logging import confluent_kafka as kafka log = logging.getLogger(__name__) class KafkaStream(object): """""" Encapsulates stream graph processing units """""" def __init__(self, topology, kafka_config): self.topology = topology self.kafka_config = kafka_config self.consumer = None def start(self): """""" Begin streaming the data across the topology """""" self.consumer = kafka.Consumer({'bootstrap.servers': self.kafka_config.BOOTSTRAP_SERVERS, 'group.id': 'test'}) #, 'group.id': 'testgroup', #'default.topic.config': {'auto.offset.reset': 'smallest'}}) log.debug('Subscribing to topics %s', self.topology.kafka_topics) self.consumer.subscribe(self.topology.kafka_topics) log.debug('Subscribed to topics') self.run() def run(self): running = True while running: msg = self.consumer.poll() if not msg.error(): print('Received message: %s' % msg.value().decode('utf-8')) elif msg.error().code() != kafka.KafkaError._PARTITION_EOF: print(msg.error()) running = False self.consumer.close() " setup.py: Fix the creation of parser cache directory,"import os.path from distutils.command import build class build(build.build): def _compile_parsers(self): import parsing import edgedb import edgedb.server.main edgedb.server.main.init_import_system() import edgedb.lang.edgeql.parser.grammar.single as edgeql_spec import edgedb.lang.edgeql.parser.grammar.block as edgeql_spec2 import edgedb.server.pgsql.parser.pgsql as pgsql_spec import edgedb.lang.schema.parser.grammar.declarations as schema_spec import edgedb.lang.graphql.parser.grammar.document as graphql_spec base_path = os.path.dirname( os.path.dirname(os.path.dirname(__file__))) for spec in (edgeql_spec, edgeql_spec2, pgsql_spec, schema_spec, graphql_spec): subpath = os.path.dirname(spec.__file__)[len(base_path) + 1:] cache_dir = os.path.join(self.build_lib, subpath) os.makedirs(cache_dir, exist_ok=True) cache = os.path.join( cache_dir, spec.__name__.rpartition('.')[2] + '.pickle') parsing.Spec(spec, pickleFile=cache, verbose=True) def run(self, *args, **kwargs): super().run(*args, **kwargs) self._compile_parsers() ","import os.path from distutils.command import build class build(build.build): def _compile_parsers(self): import parsing import edgedb import edgedb.server.main edgedb.server.main.init_import_system() import edgedb.lang.edgeql.parser.grammar.single as edgeql_spec import edgedb.lang.edgeql.parser.grammar.block as edgeql_spec2 import edgedb.server.pgsql.parser.pgsql as pgsql_spec import edgedb.lang.schema.parser.grammar.declarations as schema_spec import edgedb.lang.graphql.parser.grammar.document as graphql_spec base_path = os.path.dirname( os.path.dirname(os.path.dirname(__file__))) for spec in (edgeql_spec, edgeql_spec2, pgsql_spec, schema_spec, graphql_spec): subpath = os.path.dirname(spec.__file__)[len(base_path) + 1:] cache_dir = os.path.join(self.build_lib, subpath) os.makedirs(cache_dir) cache = os.path.join( cache_dir, spec.__name__.rpartition('.')[2] + '.pickle') parsing.Spec(spec, pickleFile=cache, verbose=True) def run(self, *args, **kwargs): super().run(*args, **kwargs) self._compile_parsers() " Remove amount of round trip to the server,"liveblogSyndication .directive('lbIncomingSyndication', ['$routeParams', 'IncomingSyndicationActions', 'IncomingSyndicationReducers', 'Store', function($routeParams, IncomingSyndicationActions, IncomingSyndicationReducers, Store) { return { templateUrl: 'scripts/liveblog-syndication/views/incoming-syndication.html', scope: { lbPostsOnPostSelected: '=', openPanel: '=', syndId: '=' }, link: function(scope) { scope.blogId = $routeParams._id; scope.store = new Store(IncomingSyndicationReducers, { posts: {}, syndication: {} }); scope.store.connect(function(state) { scope.posts = state.posts; scope.syndication = state.syndication; }); scope.goBack = function() { scope.openPanel('ingest', null); }; IncomingSyndicationActions .getPosts(scope.blogId, scope.syndId); IncomingSyndicationActions .getSyndication(scope.syndId); // On incoming post, we reload all the posts. // Not very fast, but easy to setup scope.$on('posts', function(e, data) { if (data.posts[0].syndication_in) IncomingSyndicationActions .getPosts(scope.blogId, scope.syndId); }); scope.$on('$destroy', scope.store.destroy); } }; }]); ","liveblogSyndication .directive('lbIncomingSyndication', ['$routeParams', 'IncomingSyndicationActions', 'IncomingSyndicationReducers', 'Store', function($routeParams, IncomingSyndicationActions, IncomingSyndicationReducers, Store) { return { templateUrl: 'scripts/liveblog-syndication/views/incoming-syndication.html', scope: { lbPostsOnPostSelected: '=', openPanel: '=', syndId: '=' }, link: function(scope) { scope.blogId = $routeParams._id; scope.store = new Store(IncomingSyndicationReducers, { posts: {}, syndication: {} }); scope.store.connect(function(state) { scope.posts = state.posts; scope.syndication = state.syndication; }); scope.goBack = function() { scope.openPanel('ingest', null); }; IncomingSyndicationActions .getPosts(scope.blogId, scope.syndId); IncomingSyndicationActions .getSyndication(scope.syndId); // On incoming post, we reload all the posts. // Not very fast, but easy to setup scope.$on('posts', function() { IncomingSyndicationActions .getPosts(scope.blogId, scope.syndId); }); scope.$on('$destroy', scope.store.destroy); } }; }]); " Fix null Edinburgh journey code or destination,"from django.contrib.gis.geos import Point from busstops.models import Service from ...models import Vehicle, VehicleLocation, VehicleJourney from ..import_live_vehicles import ImportLiveVehiclesCommand class Command(ImportLiveVehiclesCommand): url = 'http://tfeapp.com/live/vehicles.php' source_name = 'TfE' services = Service.objects.filter(operator__in=('LOTH', 'EDTR', 'ECBU', 'NELB'), current=True) def get_journey(self, item): journey = VehicleJourney( code=item['journey_id'] or '', destination=item['destination'] or '' ) vehicle_defaults = {} try: journey.service = self.services.get(line_name=item['service_name']) vehicle_defaults['operator'] = journey.service.operator.first() except (Service.DoesNotExist, Service.MultipleObjectsReturned) as e: if item['service_name'] not in {'ET1', 'MA1', '3BBT'}: print(e, item['service_name']) vehicle_code = item['vehicle_id'] if vehicle_code.isdigit(): vehicle_defaults['fleet_number'] = vehicle_code journey.vehicle, vehicle_created = Vehicle.objects.update_or_create( vehicle_defaults, source=self.source, code=vehicle_code ) return journey, vehicle_created def create_vehicle_location(self, item): return VehicleLocation( latlong=Point(item['longitude'], item['latitude']), heading=item['heading'] ) ","from django.contrib.gis.geos import Point from busstops.models import Service from ...models import Vehicle, VehicleLocation, VehicleJourney from ..import_live_vehicles import ImportLiveVehiclesCommand class Command(ImportLiveVehiclesCommand): url = 'http://tfeapp.com/live/vehicles.php' source_name = 'TfE' services = Service.objects.filter(operator__in=('LOTH', 'EDTR', 'ECBU', 'NELB'), current=True) def get_journey(self, item): journey = VehicleJourney( code=item['journey_id'], destination=item['destination'] ) vehicle_defaults = {} try: journey.service = self.services.get(line_name=item['service_name']) vehicle_defaults['operator'] = journey.service.operator.first() except (Service.DoesNotExist, Service.MultipleObjectsReturned) as e: if item['service_name'] not in {'ET1', 'MA1', '3BBT'}: print(e, item['service_name']) vehicle_code = item['vehicle_id'] if vehicle_code.isdigit(): vehicle_defaults['fleet_number'] = vehicle_code journey.vehicle, vehicle_created = Vehicle.objects.update_or_create( vehicle_defaults, source=self.source, code=vehicle_code ) return journey, vehicle_created def create_vehicle_location(self, item): return VehicleLocation( latlong=Point(item['longitude'], item['latitude']), heading=item['heading'] ) " Remove unused callback params from create() destroy(),";(function(exports) { function Entities(coquette, game) { this.c = coquette; this.game = game; this._entities = []; }; Entities.prototype = { update: function(interval) { var entities = this.all(); for (var i = 0, len = entities.length; i < len; i++) { if (entities[i].update !== undefined) { entities[i].update(interval); } } }, all: function(Constructor) { if (Constructor === undefined) { return this._entities.slice(); // return shallow copy of array } else { var entities = []; for (var i = 0; i < this._entities.length; i++) { if (this._entities[i] instanceof Constructor) { entities.push(this._entities[i]); } } return entities; } }, create: function(Constructor, settings) { var entity = new Constructor(this.game, settings || {}); this.c.collider.createEntity(entity); this._entities.push(entity); return entity; }, destroy: function(entity) { for(var i = 0; i < this._entities.length; i++) { if(this._entities[i] === entity) { this.c.collider.destroyEntity(entity); this._entities.splice(i, 1); break; } } } }; exports.Entities = Entities; })(typeof exports === 'undefined' ? this.Coquette : exports); ",";(function(exports) { function Entities(coquette, game) { this.c = coquette; this.game = game; this._entities = []; }; Entities.prototype = { update: function(interval) { var entities = this.all(); for (var i = 0, len = entities.length; i < len; i++) { if (entities[i].update !== undefined) { entities[i].update(interval); } } }, all: function(Constructor) { if (Constructor === undefined) { return this._entities.slice(); // return shallow copy of array } else { var entities = []; for (var i = 0; i < this._entities.length; i++) { if (this._entities[i] instanceof Constructor) { entities.push(this._entities[i]); } } return entities; } }, create: function(Constructor, settings, callback) { var entity = new Constructor(this.game, settings || {}); this.c.collider.createEntity(entity); this._entities.push(entity); return entity; }, destroy: function(entity, callback) { for(var i = 0; i < this._entities.length; i++) { if(this._entities[i] === entity) { this.c.collider.destroyEntity(entity); this._entities.splice(i, 1); break; } } } }; exports.Entities = Entities; })(typeof exports === 'undefined' ? this.Coquette : exports); " Test spoof emails in travis,"<?php namespace Egulias\EmailValidator\Tests\EmailValidator\Validation; use Egulias\EmailValidator\EmailLexer; use Egulias\EmailValidator\Validation\SpoofCheckValidation; use PHPUnit\Framework\TestCase; class SpoofCheckValidationTest extends TestCase { /** * @dataProvider validUTF8EmailsProvider */ public function testUTF8EmailAreValid($email) { $validation = new SpoofCheckValidation(); $this->assertTrue($validation->isValid($email, new EmailLexer())); } public function testEmailWithSpoofsIsInvalid() { $validation = new SpoofCheckValidation(); $this->assertFalse($validation->isValid(""Кириллица"".""latin漢字"".""ひらがな"".""カタカナ"", new EmailLexer())); } public function validUTF8EmailsProvider() { return [ // Cyrillic ['Кириллица@Кириллица'], // Latin + Han + Hiragana + Katakana [""latin漢字"".""ひらがな"".""カタカナ"".""@example.com""], // Latin + Han + Hangul [""latin"".""漢字"".""조선말"".""@example.com""], // Latin + Han + Bopomofo [""latin"".""漢字"".""ㄅㄆㄇㄈ"".""@example.com""] ]; } } ","<?php namespace Egulias\EmailValidator\Tests\EmailValidator\Validation; use Egulias\EmailValidator\EmailLexer; use Egulias\EmailValidator\Validation\SpoofCheckValidation; use PHPUnit\Framework\TestCase; class SpoofCheckValidationTest extends TestCase { /** * @dataProvider validUTF8EmailsProvider */ public function testUTF8EmailAreValid($email) { $this->markTestSkipped(""Skipped for Travis CI since it is failing on this test for unknown reasons.""); $validation = new SpoofCheckValidation(); $this->assertTrue($validation->isValid($email, new EmailLexer())); } public function testEmailWithSpoofsIsInvalid() { $validation = new SpoofCheckValidation(); $this->assertFalse($validation->isValid(""Кириллица"".""latin漢字"".""ひらがな"".""カタカナ"", new EmailLexer())); } public function validUTF8EmailsProvider() { return [ // Cyrillic ['Кириллица@Кириллица'], // Latin + Han + Hiragana + Katakana [""latin漢字"".""ひらがな"".""カタカナ"".""@example.com""], // Latin + Han + Hangul [""latin"".""漢字"".""조선말"".""@example.com""], // Latin + Han + Bopomofo [""latin"".""漢字"".""ㄅㄆㄇㄈ"".""@example.com""] ]; } } " Call one player menu instead of going straight to the game,"function MainMenu(options) { 'use strict'; var menu; menu = { title: { text: 'Yet Another Pong Clone', font: 'bold 65px Monaco, Courier New, monospace', colour: '#FFFFFF' }, items: [ { text: '1P', font: 'bold 45px Monaco, Courier New, monospace', colour: '#FFFFFF', newScreen: OnePlayerMenu({ width: options.width, height: options.height, baseSpeed: options.baseSpeed, callback: options.callback }) }, { text: '2P', font: 'bold 45px Monaco, Courier New, monospace', colour: '#FFFFFF', newScreen: new Game({ width: options.width, height: options.height, baseSpeed: 5, twoPlayer: true, players : {} }) }, { text: 'Settings', font: 'bold 45px Monaco, Courier New, monospace', colour: '#FFFFFF', newScreen: {} } ], selected: { font: 'bold 55px Monaco, Courier New, monospace', colour: '#FFCC33' }, x: 0, y: 0, width: options.width || 1280, height: options.height || 640, backgroundColour: '#000000', itemSeparator: 100, callback: options.callback || function() {} }; return new Menu(menu); }; ","function MainMenu(options) { 'use strict'; var menu; menu = { title: { text: 'Yet Another Pong Clone', font: 'bold 65px Monaco, Courier New, monospace', colour: '#FFFFFF' }, items: [ { text: '1P', font: 'bold 45px Monaco, Courier New, monospace', colour: '#FFFFFF', newScreen: new Game({ width: options.width, height: options.height, baseSpeed: 5, twoPlayer: false, players : {} }) }, { text: '2P', font: 'bold 45px Monaco, Courier New, monospace', colour: '#FFFFFF', newScreen: new Game({ width: options.width, height: options.height, baseSpeed: 5, twoPlayer: true, players : {} }) }, { text: 'Settings', font: 'bold 45px Monaco, Courier New, monospace', colour: '#FFFFFF', newScreen: {} } ], selected: { font: 'bold 55px Monaco, Courier New, monospace', colour: '#FFCC33' }, x: 0, y: 0, width: options.width || 1280, height: options.height || 640, backgroundColour: '#000000', itemSeparator: 100, callback: options.callback || function() {} }; return new Menu(menu); }; " "Use SpooledTemp, not NamedTemp file","import json import re import base64 import hashlib from pymisp.tools import stix misperrors = {'error': 'Error'} userConfig = {} inputSource = ['file'] moduleinfo = {'version': '0.2', 'author': 'Hannah Ward', 'description': 'Import some stix stuff', 'module-type': ['import']} moduleconfig = [] def handler(q=False): # Just in case we have no data if q is False: return False # The return value r = {'results': []} # Load up that JSON q = json.loads(q) # It's b64 encoded, so decode that stuff package = base64.b64decode(q.get(""data"")).decode('utf-8') # If something really weird happened if not package: return json.dumps({""success"": 0}) pkg = stix.load_stix(package) for attrib in pkg.attributes: r[""results""].append({ ""values"" : [attrib.value] , ""types"": [attrib.type], ""categories"": [attrib.category]}) return r def introspection(): modulesetup = {} try: userConfig modulesetup['userConfig'] = userConfig except NameError: pass try: inputSource modulesetup['inputSource'] = inputSource except NameError: pass return modulesetup def version(): moduleinfo['config'] = moduleconfig return moduleinfo ","import json import re import base64 import hashlib import tempfile import os from pymisp.tools import stix misperrors = {'error': 'Error'} userConfig = {} inputSource = ['file'] moduleinfo = {'version': '0.2', 'author': 'Hannah Ward', 'description': 'Import some stix stuff', 'module-type': ['import']} moduleconfig = [] def handler(q=False): # Just in case we have no data if q is False: return False # The return value r = {'results': []} # Load up that JSON q = json.loads(q) # It's b64 encoded, so decode that stuff package = base64.b64decode(q.get(""data"")).decode('utf-8') # If something really weird happened if not package: return json.dumps({""success"": 0}) tfile = tempfile.NamedTemporaryFile(mode=""w"", prefix=""STIX"", delete=False) tfile.write(package) tfile.close() pkg = stix.load_stix(tfile.name) for attrib in pkg.attributes: r[""results""].append({ ""values"" : [attrib.value] , ""types"": [attrib.type], ""categories"": [attrib.category]}) os.unlink(tfile.name) return r def introspection(): modulesetup = {} try: userConfig modulesetup['userConfig'] = userConfig except NameError: pass try: inputSource modulesetup['inputSource'] = inputSource except NameError: pass return modulesetup def version(): moduleinfo['config'] = moduleconfig return moduleinfo " Make the firefox comment slightly more verbose,"@extends('layout') @section('content') @include('partials.standardHeader') <section class=""section home""> <div class=""container""> <div class=""column is-half is-offset-one-quarter""> <div class=""box""> <form action=""/upload"" class=""dropzone"" id=""that-zone""> <div class=""dz-message needsclick""> <h2>Drop files here or click to upload</h2> <br> <span class=""note needsclick""> Max: 50Mb </span> </div> {{ csrf_field() }} </form> </div> <form action=""{{ url('/zip/' . Session::get('hash')) }}"" method=""POST"" id=""form""> {{ csrf_field() }} <div class=""control password-conrol is-grouped has-addons""> <input type=""password"" name=""password"" class=""input is-large is-expanded"" placeholder=""Password""> {{-- Firefox is a bit wee so we can't use damn buttons with icons, instead we have to use something else like a div --}} <div class=""button is-primary is-large"" onclick=""document.querySelector('#form').submit()""> <span>Zip up</span> <span class=""icon is-small""> <i class=""fa fa-file-archive-o""></i> </span> </div> </div> </form> </div> </div> </section> @stop ","@extends('layout') @section('content') @include('partials.standardHeader') <section class=""section home""> <div class=""container""> <div class=""column is-half is-offset-one-quarter""> <div class=""box""> <form action=""/upload"" class=""dropzone"" id=""that-zone""> <div class=""dz-message needsclick""> <h2>Drop files here or click to upload</h2> <br> <span class=""note needsclick""> Max: 50Mb </span> </div> {{ csrf_field() }} </form> </div> <form action=""{{ url('/zip/' . Session::get('hash')) }}"" method=""POST"" id=""form""> {{ csrf_field() }} <div class=""control password-conrol is-grouped has-addons""> <input type=""password"" name=""password"" class=""input is-large is-expanded"" placeholder=""Password""> {{-- Firefox is a bit wee so we can't use damn buttons with icons --}} <div class=""button is-primary is-large"" onclick=""document.querySelector('#form').submit()""> <span>Zip up</span> <span class=""icon is-small""> <i class=""fa fa-file-archive-o""></i> </span> </div> </div> </form> </div> </div> </section> @stop " Fix growing coord list through reference,"import defaults from ""lodash/defaults""; import shuffle from ""lodash/shuffle""; class LocationGrid { constructor(config) { const settings = defaults({}, config, { x: {}, y: {}, initial: [] }); settings.x = defaults(settings.x, { start: 0, steps: 0, stepSize: 1, avoid: [] }); settings.y = defaults(settings.y, { start: 0, steps: 0, stepSize: 1, avoid: [] }); const xs = this.coordList(settings.x); const ys = this.coordList(settings.y); const coords = settings.initial; for (let y of ys) { for (let x of xs) { coords.push({ x, y }); } } this.freeCoords = shuffle(coords); } coordList(listSettings) { const avoid = typeof listSettings.avoid === ""function"" ? listSettings.avoid() : listSettings.avoid; const start = typeof listSettings.start === ""function"" ? listSettings.start() : listSettings.start; return Array(listSettings.steps) .fill() .map((v, i) => start + i * listSettings.stepSize) .filter((v, i) => !avoid.includes(i)); } getLocation() { return this.freeCoords.pop(); } } export default LocationGrid; ","import defaults from ""lodash/defaults""; import shuffle from ""lodash/shuffle""; class LocationGrid { constructor(settings) { settings = defaults(settings, { x: {}, y: {}, initial: [] }); settings.x = defaults(settings.x, { start: 0, steps: 0, stepSize: 1, avoid: [] }); settings.y = defaults(settings.y, { start: 0, steps: 0, stepSize: 1, avoid: [] }); const xs = this.coordList(settings.x); const ys = this.coordList(settings.y); const coords = settings.initial; for (let y of ys) { for (let x of xs) { coords.push({ x, y }); } } this.freeCoords = shuffle(coords); } coordList(listSettings) { const avoid = typeof listSettings.avoid === ""function"" ? listSettings.avoid() : listSettings.avoid; const start = typeof listSettings.start === ""function"" ? listSettings.start() : listSettings.start; return Array(listSettings.steps) .fill() .map((v, i) => start + i * listSettings.stepSize) .filter((v, i) => !avoid.includes(i)); } getLocation() { return this.freeCoords.pop(); } } export default LocationGrid; " Make the PEP pass the actual SP to the PDP in case of a trusted proxy.,"<?php class EngineBlock_Corto_Filter_Command_PolicyDecisionPoint extends EngineBlock_Corto_Filter_Command_Abstract { /** * This command may modify the response attributes * * @return array */ public function getResponseAttributes() { return $this->_responseAttributes; } public function execute() { $serviceProvider = EngineBlock_SamlHelper::findRequesterServiceProvider( $this->_serviceProvider, $this->_request, $this->_server->getRepository() ); if (!$serviceProvider) { $serviceProvider = $this->_serviceProvider; } if (!$serviceProvider->policyEnforcementDecisionRequired) { return; } EngineBlock_ApplicationSingleton::getLog()->debug( ""Policy Enforcement Point consult"" ); $validator = $this->_getValidator(); $hasAccess = $validator->hasAccess( $this->_collabPersonId, $this->_identityProvider->entityId, $serviceProvider->entityId, $this->_responseAttributes ); if ($hasAccess) { return; } $message = ""Policy Decision Point: access denied.""; if ($validator->getMessage()) { $message = $validator->getMessage(); } EngineBlock_ApplicationSingleton::getLog()->debug( ""Policy Enforcement Point access denied: "" . $message ); throw new EngineBlock_Corto_Exception_PEPNoAccess($message); } /** * @return EngineBlock_PolicyDecisionPoint_PepValidator */ protected function _getValidator() { return new EngineBlock_PolicyDecisionPoint_PepValidator(); } } ","<?php class EngineBlock_Corto_Filter_Command_PolicyDecisionPoint extends EngineBlock_Corto_Filter_Command_Abstract { /** * This command may modify the response attributes * * @return array */ public function getResponseAttributes() { return $this->_responseAttributes; } public function execute() { if (!$this->_serviceProvider->policyEnforcementDecisionRequired) { return; } EngineBlock_ApplicationSingleton::getLog()->debug( ""Policy Enforcement Point consult"" ); $validator = $this->_getValidator(); $hasAccess = $validator->hasAccess( $this->_collabPersonId, $this->_identityProvider->entityId, $this->_serviceProvider->entityId, $this->_responseAttributes ); if ($hasAccess) { return; } $message = ""Policy Decision Point: access denied.""; if ($validator->getMessage()) { $message = $validator->getMessage(); } EngineBlock_ApplicationSingleton::getLog()->debug( ""Policy Enforcement Point access denied: "" . $message ); throw new EngineBlock_Corto_Exception_PEPNoAccess($message); } /** * @return EngineBlock_PolicyDecisionPoint_PepValidator */ protected function _getValidator() { return new EngineBlock_PolicyDecisionPoint_PepValidator(); } } " Rename test method for clarity,"<?php namespace ArrayHelpers; use PHPUnit\Framework\TestCase; class ArrayHasTest extends TestCase { public function testWillReturnFalseIfNotAvailable() { $data = []; $key = 'foo'; $this->assertFalse( Arr::has($data, $key) ); } public function testWillReturnTrueIfAvailable() { $data = [ 'foo' => 'fighters', 'bar' => 'tenders', ]; $this->assertTrue( Arr::has($data, 'foo') ); } public function testWillReturnTrueIfFoundUsingDotNotation() { $data = [ 'i' => [ ""can't"" => [ 'get' => [ 'no' => 'satisfaction', ], ], ], ]; $key = ""i.can't.get.no""; $this->assertTrue( Arr::has($data, $key) ); } } ","<?php namespace ArrayHelpers; use PHPUnit\Framework\TestCase; class ArrayHasTest extends TestCase { public function testWillReturnFalseIfNotAvailable() { $data = []; $key = 'foo'; $this->assertFalse( Arr::has($data, $key) ); } public function testWillReturnTrueIfAvailable() { $data = [ 'foo' => 'fighters', 'bar' => 'tenders', ]; $this->assertTrue( Arr::has($data, 'foo') ); } public function testWillFindUsingDotNotation() { $data = [ 'i' => [ ""can't"" => [ 'get' => [ 'no' => 'satisfaction', ], ], ], ]; $key = ""i.can't.get.no""; $this->assertTrue( Arr::has($data, $key) ); } } " Make driver object filename case-insensitive,"class ObjectLocator { constructor(fs, objectName) { this.fs = fs; this.objectName = objectName; this.objects = []; this.objectDirectoryName = ""objects""; } run() { this.loadAllObjects(this.objectName); return this.objects; } loadAllObjects(dependencyName) { let fileData = this.fs.readFileSync(process.cwd() + `/${this.objectDirectoryName}/${dependencyName.toLowerCase()}.json`); let fileJson = {}; if (fileData != null || fileData.toString().length == 0) { fileJson = JSON.parse(fileData); } if (fileJson != null && fileJson != {}) { if (fileJson.dependencies == null) { throw new Error(`Json for the file ${dependencyName} must have a dependency array, if none provide a blank array`); } let dependencies = fileJson.dependencies; if (Array.isArray(dependencies)) { dependencies.forEach((dependency) => { if (this.objects.find(x => x.name == dependency) == null) { this.loadAllObjects(dependency); } }); } else { throw new Error(`Dependencies must be an array! object ${dependencyName} file dependencies is not an array`); } this.objects.push({ name: dependencyName, metadata: { fields: fileJson.fields, dependencies: fileJson.dependencies } }) } } } module.exports = ObjectLocator; ","class ObjectLocator { constructor(fs, objectName) { this.fs = fs; this.objectName = objectName; this.objects = []; this.objectDirectoryName = ""objects""; } run() { this.loadAllObjects(this.objectName); return this.objects; } loadAllObjects(dependencyName) { let fileData = this.fs.readFileSync(process.cwd() + `/${this.objectDirectoryName}/${dependencyName}.json`); let fileJson = {}; if (fileData != null || fileData.toString().length == 0) { fileJson = JSON.parse(fileData); } if (fileJson != null && fileJson != {}) { if (fileJson.dependencies == null) { throw new Error(`Json for the file ${dependencyName} must have a dependency array, if none provide a blank array`); } let dependencies = fileJson.dependencies; if (Array.isArray(dependencies)) { dependencies.forEach((dependency) => { if (this.objects.find(x => x.name == dependency) == null) { this.loadAllObjects(dependency); } }); } else { throw new Error(`Dependencies must be an array! object ${dependencyName} file dependencies is not an array`); } this.objects.push({ name: dependencyName, metadata: { fields: fileJson.fields, dependencies: fileJson.dependencies } }) } } } module.exports = ObjectLocator; " Fix sign up to use new load system,"<?php namespace Page; class SignUp { public function index() { if ($this->input->hasPost('username')) { $this->addUser(); } $this->load->storeView('SignUp'); $this->load->layout('Fresh'); } public function addUser() { $username = $this->input->post('username'); $password = $this->input->post('password'); $rpassword = $this->input->post('rpassword'); $this->load->library('Validation'); if ($password !== $rpassword) { $this->message->error('Your retype password is not match with the password you entered.'); } if (!$this->validation->username($username)) { $this->message->error('Your username is not valid, only use alphabet (a-z), number (0-9),'. ' and symbol (_.-). The character length must between 5-16 characters'); } if (!$this->validation->password($password)) { $this->message->error('Your password is not valid, only use alphabet (a-z), number (0-9),'. ' and symbol (@#!$*&~;:,?_.-). The character length must between 5-16 characters'); } if ($this->message->count('error') > 0) { return; } $this->message->success('Your account has been created successfully.'. ' Enter with your username and password', true); $this->router->redirect('user/signin'); } } ?> ","<?php namespace Page; class SignUp { public function index() { if ($this->input->hasPost('username')) { $this->addUser(); } $this->load->storeView('SignUp'); $this->load->layout('Fresh'); } public function addUser() { $username = $this->input->post('username'); $password = $this->input->post('password'); $rpassword = $this->input->post('rpassword'); $msg = $this->load->library('Message'); $valid = $this->load->library('Validation'); if ($password !== $rpassword) { $msg->error('Your retype password is not match with the password you entered.'); } if (!$valid->username($username)) { $msg->error('Your username is not valid, only use alphabet (a-z), number (0-9),'. ' and symbol (_.-). The character length must between 5-16 characters'); } if (!$valid->password($password)) { $msg->error('Your password is not valid, only use alphabet (a-z), number (0-9),'. ' and symbol (@#!$*&~;:,?_.-). The character length must between 5-16 characters'); } if ($msg->count('error') > 0) { return; } $msg->success('Your account has been created successfully.'. ' Enter with your username and password', true); $this->router->redirect('user/signin'); } } ?> " Add time unit to DELAY.,"package com.novoda.downloadmanager; import java.util.Timer; import java.util.TimerTask; class CallbackThrottleByTime implements CallbackThrottle { private static final long DELAY_IN_MILLIS = 0; private DownloadBatchStatus downloadBatchStatus; private Timer timer; private TimerTask timerTask; private final long periodInMillis; private DownloadBatchCallback callback; CallbackThrottleByTime(long periodInMillis) { this.periodInMillis = periodInMillis; } @Override public void setCallback(final DownloadBatchCallback callback) { this.callback = callback; timerTask = new TimerTask() { @Override public void run() { callback.onUpdate(downloadBatchStatus); } }; } @Override public void update(DownloadBatchStatus downloadBatchStatus) { if (timerTask == null) { return; } this.downloadBatchStatus = downloadBatchStatus; startUpdateIfNecessary(); } private void startUpdateIfNecessary() { if (timer == null) { timer = new Timer(); timer.scheduleAtFixedRate(timerTask, DELAY_IN_MILLIS, periodInMillis); } } @Override public void stopUpdates() { if (callback != null) { callback.onUpdate(downloadBatchStatus); } if (timer != null) { timer.cancel(); timer = null; } } } ","package com.novoda.downloadmanager; import java.util.Timer; import java.util.TimerTask; class CallbackThrottleByTime implements CallbackThrottle { private final long periodInMillis; private static final long DELAY = 0; private DownloadBatchStatus downloadBatchStatus; private Timer timer; private TimerTask timerTask; private DownloadBatchCallback callback; CallbackThrottleByTime(long periodInMillis) { this.periodInMillis = periodInMillis; } @Override public void setCallback(final DownloadBatchCallback callback) { this.callback = callback; timerTask = new TimerTask() { @Override public void run() { callback.onUpdate(downloadBatchStatus); } }; } @Override public void update(DownloadBatchStatus downloadBatchStatus) { if (timerTask == null) { return; } this.downloadBatchStatus = downloadBatchStatus; startUpdateIfNecessary(); } private void startUpdateIfNecessary() { if (timer == null) { timer = new Timer(); timer.scheduleAtFixedRate(timerTask, DELAY, periodInMillis); } } @Override public void stopUpdates() { if (callback != null) { callback.onUpdate(downloadBatchStatus); } if (timer != null) { timer.cancel(); timer = null; } } } " Hide the ''load more'' button while loading.,"'use strict'; // Initiate masonry & infinite scroll on relevant pages $(function() { var $container = $('#masonry-container'); $container.imagesLoaded(function(){ $container.masonry({ itemSelector: '.box', }); }); $container.infinitescroll({ navSelector : '#page-nav', // selector for the paged navigation nextSelector : '#page-nav a', // selector for the NEXT link (to page 2) itemSelector : '.box', // selector for all items you'll retrieve loading: { finishedMsg: 'Ikke flere resultater...', img: '/images/loading.gif', msgText: 'Henter flere resultater...', speed: 0, }, animate:false }, // trigger Masonry as a callback function( newElements ) { // hide new items while they are loading var $newElems = $( newElements ).css({ opacity: 0 }); // ensure that images load before adding to masonry layout $newElems.imagesLoaded(function(){ // show elems now they're ready $newElems.animate({ opacity: 1 }); $container.masonry( 'appended', $newElems, true ); $('#more').show(); }); } ); $(window).unbind('.infscr'); $(""#more"").click(function(){ $('#more').hide(); var $container = $('#masonry-container'); $container.infinitescroll('retrieve'); return false; }); }); ","'use strict'; // Initiate masonry & infinite scroll on relevant pages $(function() { var $container = $('#masonry-container'); $container.imagesLoaded(function(){ $container.masonry({ itemSelector: '.box', }); }); $container.infinitescroll({ navSelector : '#page-nav', // selector for the paged navigation nextSelector : '#page-nav a', // selector for the NEXT link (to page 2) itemSelector : '.box', // selector for all items you'll retrieve loading: { finishedMsg: 'Ikke flere resultater...', img: '/images/loading.gif', msgText: 'Henter flere resultater...', speed: 0, }, animate:false }, // trigger Masonry as a callback function( newElements ) { // hide new items while they are loading var $newElems = $( newElements ).css({ opacity: 0 }); // ensure that images load before adding to masonry layout $newElems.imagesLoaded(function(){ // show elems now they're ready $newElems.animate({ opacity: 1 }); $container.masonry( 'appended', $newElems, true ); }); } ); $(window).unbind('.infscr'); $(""#more"").click(function(){ var $container = $('#masonry-container'); $container.infinitescroll('retrieve'); return false; }); }); " Update query for selecting most-expensive tags on dashboard to query by space_id instead of user_id,"<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; use DB; class DashboardController extends Controller { public function __invoke() { $user = Auth::user(); $space_id = session('space')->id; $totalSpendings = $user ->spendings() ->whereRaw('MONTH(happened_on) = ?', [date('m')]) ->sum('amount'); $recentSpendings = $user ->spendings() ->orderBy('created_at', 'DESC') ->limit(3) ->get(); $mostExpensiveTags = DB::select(' SELECT tags.name AS name, SUM(spendings.amount) AS amount FROM tags LEFT OUTER JOIN spendings ON tags.id = spendings.tag_id WHERE tags.space_id = ? AND MONTH(happened_on) = ? GROUP BY tags.id HAVING SUM(spendings.amount) > 0 ORDER BY SUM(spendings.amount) DESC LIMIT 3; ', [$space_id, date('m')]); return view('dashboard', [ 'currency' => $user->currency, 'month' => date('n'), 'totalSpendings' => $totalSpendings, 'recentSpendings' => $recentSpendings, 'mostExpensiveTags' => $mostExpensiveTags, 'earningsCount' => $user->earnings->count(), 'spendingsCount' => $user->spendings->count() ]); } } ","<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; use DB; class DashboardController extends Controller { public function __invoke() { $user = Auth::user(); $totalSpendings = $user ->spendings() ->whereRaw('MONTH(happened_on) = ?', [date('m')]) ->sum('amount'); $recentSpendings = $user ->spendings() ->orderBy('created_at', 'DESC') ->limit(3) ->get(); $mostExpensiveTags = DB::select(' SELECT tags.name AS name, SUM(spendings.amount) AS amount FROM tags LEFT OUTER JOIN spendings ON tags.id = spendings.tag_id WHERE tags.user_id = ? AND MONTH(happened_on) = ? GROUP BY tags.id HAVING SUM(spendings.amount) > 0 ORDER BY SUM(spendings.amount) DESC LIMIT 3; ', [$user->id, date('m')]); return view('dashboard', [ 'currency' => $user->currency, 'month' => date('n'), 'totalSpendings' => $totalSpendings, 'recentSpendings' => $recentSpendings, 'mostExpensiveTags' => $mostExpensiveTags, 'earningsCount' => $user->earnings->count(), 'spendingsCount' => $user->spendings->count() ]); } } " "Fix incorrect default message for exception ctor PHP8.1+ complains about Exception not accepting `null` as the message argument for an `Exception` constructor. This fixes it.","<?php namespace React\Promise\Internal; use Exception; use LogicException; use React\Promise\PromiseAdapter\CallbackPromiseAdapter; use React\Promise\PromiseTest\PromiseRejectedTestTrait; use React\Promise\PromiseTest\PromiseSettledTestTrait; use React\Promise\TestCase; class RejectedPromiseTest extends TestCase { use PromiseSettledTestTrait, PromiseRejectedTestTrait; public function getPromiseTestAdapter(callable $canceller = null) { $promise = null; return new CallbackPromiseAdapter([ 'promise' => function () use (&$promise) { if (!$promise) { throw new LogicException('RejectedPromise must be rejected before obtaining the promise'); } return $promise; }, 'resolve' => function () { throw new LogicException('You cannot call resolve() for React\Promise\RejectedPromise'); }, 'reject' => function ($reason = null) use (&$promise) { if (!$promise) { $promise = new RejectedPromise($reason); } }, 'settle' => function ($reason = """") use (&$promise) { if (!$promise) { if (!$reason instanceof Exception) { $reason = new Exception($reason); } $promise = new RejectedPromise($reason); } }, ]); } } ","<?php namespace React\Promise\Internal; use Exception; use LogicException; use React\Promise\PromiseAdapter\CallbackPromiseAdapter; use React\Promise\PromiseTest\PromiseRejectedTestTrait; use React\Promise\PromiseTest\PromiseSettledTestTrait; use React\Promise\TestCase; class RejectedPromiseTest extends TestCase { use PromiseSettledTestTrait, PromiseRejectedTestTrait; public function getPromiseTestAdapter(callable $canceller = null) { $promise = null; return new CallbackPromiseAdapter([ 'promise' => function () use (&$promise) { if (!$promise) { throw new LogicException('RejectedPromise must be rejected before obtaining the promise'); } return $promise; }, 'resolve' => function () { throw new LogicException('You cannot call resolve() for React\Promise\RejectedPromise'); }, 'reject' => function ($reason = null) use (&$promise) { if (!$promise) { $promise = new RejectedPromise($reason); } }, 'settle' => function ($reason = null) use (&$promise) { if (!$promise) { if (!$reason instanceof Exception) { $reason = new Exception($reason); } $promise = new RejectedPromise($reason); } }, ]); } } " Change the way regexps are evaluated (fix bug that occured after re-sorting),"<?php namespace Hicoria\Xpay; use Nette\Object; class XpaySmsDispatcher extends Object { /** * @var IMessageProcessor[] */ private $processors = []; public function register($regex, IMessageProcessor $processor) { $this->processors[] = $processor; } public function sortByPriority() { usort($this->processors, function($a, $b) { return $b->getPriority() - $a->getPriority(); }); } public function process(XpayMessageEntity $paymentEntity) { foreach($this->getProcessors() as $processor) { $success = preg_match( ""~"" . preg_replace(""/~/"", ""\\~"", $processor->getResponse()) . ""~i"", trim($paymentEntity->getModified()), $matches); // continue for both, error and no match if(!$success) continue; // drop first element - we want matches in parentheses array_shift($matches); $processor->process($paymentEntity, $matches); $processor->getResponse()->sendResponse(); break; } return true; } /** * @return \Hicoria\Xpay\IMessageProcessor[] */ public function getProcessors() { return $this->processors; } }","<?php namespace Hicoria\Xpay; use Nette\Object; class XpaySmsDispatcher extends Object { /** * @var IMessageProcessor[] */ private $processors; public function register($regex, IMessageProcessor $processor) { $this->processors[$regex] = $processor; } public function sortByPriority() { usort($this->processors, function($a, $b) { return $b->getPriority() - $a->getPriority(); }); } public function process(XpayMessageEntity $paymentEntity) { foreach($this->getProcessors() as $regexp => $processor) { $success = preg_match( ""~"" . preg_replace(""/~/"", ""\\~"", $regexp) . ""~i"", trim($paymentEntity->getModified()), $matches); // continue for both, error and no match if(!$success) continue; // drop first element - we want matches in parentheses array_shift($matches); $processor->process($paymentEntity, $matches); $processor->getResponse()->sendResponse(); break; } return true; } /** * @return \Hicoria\Xpay\IMessageProcessor[] */ public function getProcessors() { return $this->processors; } }" Move function metadata logic to setMetadata function,"var Matcher = require('minimatch').Minimatch; /** * Sets the given metadata on the file object * * @param file {Object} * @param metadata {Object} * @private */ function setMetadata(file, global, rule) { if (typeof rule.metadata === 'function') { rule = Object.assign({}, rule, { metadata: rule.metadata(file, global) }); } Object.keys(rule.metadata).forEach(function (key) { if (rule.preserve && key in file) { return; } file[key] = rule.metadata[key]; }); } /** * Sets some metadata on each file depending a pattern * * @param rules {Array} array of rules to set the metadata, each item of * the array should be a literal object containing a `pattern` entry (String) * and a `metadata` entry (Object) * * @return {Function} */ module.exports = function (rules) { var rules = rules || [], matchers = []; rules.forEach(function (rule) { matchers.push({ matcher: new Matcher(rule.pattern), metadata: rule.metadata, preserve: rule.preserve, }); }); return function (files, metalsmith, done) { var globalMetadata = metalsmith.metadata(); Object.keys(files).forEach(function (file) { var fileObject = files[file]; matchers.forEach(function (rule) { if ( rule.matcher.match(file) ) { setMetadata(fileObject, globalMetadata, rule); } }); }); done(); }; }; ","var Matcher = require('minimatch').Minimatch; /** * Sets the given metadata on the file object * * @param file {Object} * @param metadata {Object} * @private */ function setMetadata(file, rule) { Object.keys(rule.metadata).forEach(function (key) { if (rule.preserve && key in file) { return; } file[key] = rule.metadata[key]; }); } /** * Sets some metadata on each file depending a pattern * * @param rules {Array} array of rules to set the metadata, each item of * the array should be a literal object containing a `pattern` entry (String) * and a `metadata` entry (Object) * * @return {Function} */ module.exports = function (rules) { var rules = rules || [], matchers = []; rules.forEach(function (rule) { matchers.push({ matcher: new Matcher(rule.pattern), metadata: rule.metadata, preserve: rule.preserve, }); }); return function (files, metalsmith, done) { var globalMetadata = metalsmith.metadata(); Object.keys(files).forEach(function (file) { var fileObject = files[file]; matchers.forEach(function (rule) { if ( rule.matcher.match(file) ) { if (typeof rule.metadata === 'function') { rule = Object.assign({}, rule, { metadata: rule.metadata(fileObject, globalMetadata) }); } setMetadata(fileObject, rule); } }); }); done(); }; }; " Add redirect to login endpoint if 401 received,"function redirectLogin() { window.location.href = '/log_in'; } function likeComment(event, commentId) { console.log(forumId); console.log(commentId); $.ajax({ 'url': '/forums/' + forumId + '/comments/' + commentId + ""/like"", 'type': 'PUT', 'success': function(res) { console.log(res); $(event.target).children('p').text(res.likes.length); $(event.target).siblings('i').children('p').text(res.dislikes.length); }, 'error': function(err) { if (err) { // window.location.href = '/log_in'; console.log(err); } }, 'dataType': 'json' }) } function dislikeComment(event, commentId) { console.log(forumId); console.log(commentId); $.ajax({ 'url': '/forums/' + forumId + '/comments/' + commentId + ""/dislike"", 'type': 'PUT', 'success': function(res) { $(event.target).children('p').text(res.dislikes.length); $(event.target).siblings('i').children('p').text(res.likes.length); }, 'error': function(err) { if (err) { // window.location.href = '/log_in'; console.log(err); } }, 'dataType': 'json' }) } ","function likeComment(event, commentId) { console.log(forumId); console.log(commentId); $.ajax({ 'url': '/forums/' + forumId + '/comments/' + commentId + ""/like"", 'type': 'PUT', 'success': function(res) { console.log(res); $(event.target).children('p').text(res.likes.length); $(event.target).siblings('i').children('p').text(res.dislikes.length); }, 'error': function(err) { if (err) { // window.location.href = '/log_in'; console.log(err); } }, 'dataType': 'json' }) } function dislikeComment(event, commentId) { console.log(forumId); console.log(commentId); $.ajax({ 'url': '/forums/' + forumId + '/comments/' + commentId + ""/dislike"", 'type': 'PUT', 'success': function(res) { $(event.target).children('p').text(res.dislikes.length); $(event.target).siblings('i').children('p').text(res.likes.length); }, 'error': function(err) { if (err) { // window.location.href = '/log_in'; console.log(err); } }, 'dataType': 'json' }) } " Add field `active` for Barman,"const { DataTypes, Model } = require('sequelize'); /** * This class represents a barman. */ class Barman extends Model { /** * Initialization function. * * @param sequelize * @returns {Model} */ static init(sequelize) { return super.init({ id: { type: DataTypes.INTEGER, primaryKey: true }, firstName: { type: DataTypes.STRING, allowNull: false }, lastName: { type: DataTypes.STRING, allowNull: false }, nickname: { type: DataTypes.STRING, allowNull: false }, facebook: { type: DataTypes.STRING }, dateOfBirth: { type: DataTypes.DATEONLY, allowNull: false }, flow: { type: DataTypes.TEXT }, active: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true } }, { sequelize, // Do not delete row, even when the user delete is account paranoid: true }); } /** * Set associations for the model. * * @param models */ static associate(models) { this.belongsToMany(models.Kommission, { through: models.KommissionWrapper }); this.belongsToMany(models.Role, { through: models.RoleWrapper }); this.belongsToMany(models.Service, { through: models.ServiceWrapper }); this.hasOne(Barman, { as: 'godFather' }); this.hasOne(models.ConnectionInformation, { as: 'connection' }); } } module.exports = { Barman }; ","const { DataTypes, Model } = require('sequelize'); /** * This class represents a barman. */ class Barman extends Model { /** * Initialization function. * * @param sequelize * @returns {Model} */ static init(sequelize) { return super.init({ id: { type: DataTypes.INTEGER, primaryKey: true }, firstName: { type: DataTypes.STRING, allowNull: false }, lastName: { type: DataTypes.STRING, allowNull: false }, nickname: { type: DataTypes.STRING, allowNull: false }, facebook: { type: DataTypes.STRING }, dateOfBirth: { type: DataTypes.DATEONLY, allowNull: false }, flow: { type: DataTypes.TEXT }, }, { sequelize, // Do not delete row, even when the user delete is account paranoid: true }); } /** * Set associations for the model. * * @param models */ static associate(models) { this.belongsToMany(models.Kommission, { through: models.KommissionWrapper }); this.belongsToMany(models.Role, { through: models.RoleWrapper }); this.belongsToMany(models.Service, { through: models.ServiceWrapper }); this.hasOne(Barman, { as: 'godFather' }); this.hasOne(models.ConnectionInformation, { as: 'connection' }); } } module.exports = { Barman }; " Enable backup restore and destroy actions.,"import openstackBackupsService from './openstack-backups-service'; import openstackBackupsList from './openstack-backups-list'; import backupSnapshotsList from './backup-snapshots-list'; export default module => { module.service('openstackBackupsService', openstackBackupsService); module.directive('openstackBackupsList', openstackBackupsList); module.directive('backupSnapshotsList', backupSnapshotsList); module.config(actionConfig); module.config(tabsConfig); }; // @ngInject function actionConfig(ActionConfigurationProvider, DEFAULT_EDIT_ACTION) { ActionConfigurationProvider.register('OpenStackTenant.Backup', { order: [ 'edit', 'restore', 'destroy', ], options: { edit: angular.merge({}, DEFAULT_EDIT_ACTION, { successMessage: 'Backup has been updated', fields: { kept_until: { help_text: 'Guaranteed time of backup retention. If null - keep forever.', label: 'Kept until', required: false, type: 'datetime' } } }) } }); } // @ngInject function tabsConfig(ResourceTabsConfigurationProvider, DEFAULT_RESOURCE_TABS) { ResourceTabsConfigurationProvider.register('OpenStackTenant.Backup', { order: [ ...DEFAULT_RESOURCE_TABS.order, 'snapshots', ], options: angular.merge({}, DEFAULT_RESOURCE_TABS.options, { snapshots: { heading: 'Snapshots', component: 'backupSnapshotsList' }, }) }); } ","import openstackBackupsService from './openstack-backups-service'; import openstackBackupsList from './openstack-backups-list'; import backupSnapshotsList from './backup-snapshots-list'; export default module => { module.service('openstackBackupsService', openstackBackupsService); module.directive('openstackBackupsList', openstackBackupsList); module.directive('backupSnapshotsList', backupSnapshotsList); module.config(actionConfig); module.config(tabsConfig); }; // @ngInject function actionConfig(ActionConfigurationProvider, DEFAULT_EDIT_ACTION) { ActionConfigurationProvider.register('OpenStackTenant.Backup', { order: [ 'edit' ], options: { edit: angular.merge({}, DEFAULT_EDIT_ACTION, { successMessage: 'Backup has been updated', fields: { kept_until: { help_text: 'Guaranteed time of backup retention. If null - keep forever.', label: 'Kept until', required: false, type: 'datetime' } } }) } }); } // @ngInject function tabsConfig(ResourceTabsConfigurationProvider, DEFAULT_RESOURCE_TABS) { ResourceTabsConfigurationProvider.register('OpenStackTenant.Backup', { order: [ ...DEFAULT_RESOURCE_TABS.order, 'snapshots', ], options: angular.merge({}, DEFAULT_RESOURCE_TABS.options, { snapshots: { heading: 'Snapshots', component: 'backupSnapshotsList' }, }) }); } " "Use minZoom on Map instead of zoom This prevents the component from rendering a thousand times.","import React from 'react' import PropTypes from 'prop-types' import { Map, TileLayer, GeoJSON } from 'react-leaflet' class CenteredMap extends React.PureComponent { static propTypes = { vectors: PropTypes.object.isRequired, className: PropTypes.string, frozen: PropTypes.bool, lat: PropTypes.number, lon: PropTypes.number, zoom: PropTypes.number } static defaultProps = { frozen: false, lat: 47, lon: 1, zoom: 5 } componentDidMount() { if (this.vectors) { this.setState({ bounds: this.vectors.leafletElement.getBounds() }) } } render() { const { vectors, className, frozen, lat, lon, zoom } = this.props const { bounds } = this.state return ( <Map className={className} center={[lat, lon]} bounds={bounds} minZoom={zoom} dragging={!frozen} scrollWheelZoom={false} doubleClickZoom={false} zoomControl={!frozen} > <TileLayer attribution='© Contributeurs <a href=""http://osm.org/copyright"">OpenStreetMap</a>' url='https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png' /> <GeoJSON color='blue' fillOpacity={0.1} weight={2} ref={vectors => { this.vectors = vectors }} data={vectors} /> </Map> ) } } export default CenteredMap ","import React from 'react' import PropTypes from 'prop-types' import { Map, TileLayer, GeoJSON } from 'react-leaflet' class CenteredMap extends React.PureComponent { static propTypes = { vectors: PropTypes.object.isRequired, className: PropTypes.string, frozen: PropTypes.bool, lat: PropTypes.number, lon: PropTypes.number, zoom: PropTypes.number } static defaultProps = { frozen: false, lat: 47, lon: 1, zoom: 5 } componentDidMount() { if (this.vectors) { this.setState({ bounds: this.vectors.leafletElement.getBounds() }) } } render() { const { vectors, className, frozen, lat, lon, zoom } = this.props const { bounds } = this.state return ( <Map className={className} center={[lat, lon]} bounds={bounds} zoom={zoom} dragging={!frozen} scrollWheelZoom={false} doubleClickZoom={false} zoomControl={!frozen} > <TileLayer attribution='© Contributeurs <a href=""http://osm.org/copyright"">OpenStreetMap</a>' url='https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png' /> <GeoJSON color='blue' fillOpacity={0.1} weight={2} ref={vectors => { this.vectors = vectors }} data={vectors} /> </Map> ) } } export default CenteredMap " "Add a comma here to help out people who modify this file. See https://bugzilla.redhat.com/show_bug.cgi?id=1184523","# Setup fedmsg logging. # See the following for constraints on this format https://bit.ly/Xn1WDn bare_format = ""[%(asctime)s][%(name)10s %(levelname)7s] %(message)s"" config = dict( logging=dict( version=1, formatters=dict( bare={ ""datefmt"": ""%Y-%m-%d %H:%M:%S"", ""format"": bare_format }, ), handlers=dict( console={ ""class"": ""logging.StreamHandler"", ""formatter"": ""bare"", ""level"": ""INFO"", ""stream"": ""ext://sys.stdout"", }, ), loggers=dict( fedmsg={ ""level"": ""INFO"", ""propagate"": False, ""handlers"": [""console""], }, moksha={ ""level"": ""INFO"", ""propagate"": False, ""handlers"": [""console""], }, ), ), ) ","# Setup fedmsg logging. # See the following for constraints on this format https://bit.ly/Xn1WDn bare_format = ""[%(asctime)s][%(name)10s %(levelname)7s] %(message)s"" config = dict( logging=dict( version=1, formatters=dict( bare={ ""datefmt"": ""%Y-%m-%d %H:%M:%S"", ""format"": bare_format }, ), handlers=dict( console={ ""class"": ""logging.StreamHandler"", ""formatter"": ""bare"", ""level"": ""INFO"", ""stream"": ""ext://sys.stdout"", } ), loggers=dict( fedmsg={ ""level"": ""INFO"", ""propagate"": False, ""handlers"": [""console""], }, moksha={ ""level"": ""INFO"", ""propagate"": False, ""handlers"": [""console""], }, ), ), ) " Include documentation and license in package,"from setuptools import setup, find_packages version = '0.2.1' README = open(""README.rst"", ""rt"").read() setup(name='corneti.recipes.codeintel', version=version, description=""A Sublime Text 2 / SublimeCodeIntel auto-completion data generator for buildout"", long_description=README, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Framework :: Buildout', 'Framework :: Buildout :: Recipe', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Text Editors' ], keywords='sublimetext sublimecodeintel editor buildout recipe', author='Fabio Corneti', author_email='info@corneti.com', url='https://github.com/fabiocorneti/corneti.recipes.codeintel', license='MIT', packages=find_packages(exclude=['ez_setup']), namespace_packages=['corneti', 'corneti.recipes'], include_package_data=True, zip_safe=False, install_requires=['setuptools', 'zc.buildout', 'zc.recipe.egg'], entry_points={'zc.buildout': ['default = corneti.recipes.codeintel:CodeintelRecipe']}, ) ","from setuptools import setup, find_packages version = '0.2' README = open(""README.rst"", ""rt"").read() setup(name='corneti.recipes.codeintel', version=version, description=""A Sublime Text 2 / SublimeCodeIntel auto-completion data generator for buildout"", long_description=README, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Framework :: Buildout', 'Framework :: Buildout :: Recipe', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Text Editors' ], keywords='sublimetext sublimecodeintel editor buildout recipe', author='Fabio Corneti', author_email='info@corneti.com', url='https://github.com/fabiocorneti/corneti.recipes.codeintel', license='MIT', packages=find_packages(exclude=['ez_setup']), namespace_packages=['corneti', 'corneti.recipes'], include_package_data=True, zip_safe=False, install_requires=['setuptools', 'zc.buildout', 'zc.recipe.egg'], entry_points={'zc.buildout': ['default = corneti.recipes.codeintel:CodeintelRecipe']}, ) " Throw error when site key is not defined,"'use strict'; angular.module('noCAPTCHA', []) .provider('noCAPTCHA', function NoCaptchaProvider() { var siteKey, theme; this.setSiteKey = function(_siteKey){ siteKey = _siteKey; }; this.setTheme = function(_theme){ theme = _theme; }; this.$get = [function NoCaptchaFactory() { return { theme: theme, siteKey: siteKey } }]; }) .directive('noCaptcha', ['noCAPTCHA', function(noCaptcha){ return { restrict:'EA', scope: { gRecaptchaResponse:'=', siteKey:'@', theme:'@' }, replace: true, link: function(scope, element){ var widgetId, grecaptchaCreateParameters; grecaptchaCreateParameters = { sitekey: scope.siteKey || noCaptcha.siteKey, theme: scope.theme || noCaptcha.theme, callback: function(r){ scope.$apply(function(){ scope.gRecaptchaResponse = r; }); } }; if(!grecaptchaCreateParameters.siteKey){ return throw 'Site Key is required'; } grecaptcha.render( element[0], grecaptchaCreateParameters ); scope.$on('$destroy', function(){ grecaptcha.reset(widgetId); }); } }; }]); ","'use strict'; angular.module('noCAPTCHA', []) .provider('noCAPTCHA', function NoCaptchaProvider() { var siteKey, theme; this.setSiteKey = function(_siteKey){ siteKey = _siteKey; }; this.setTheme = function(_theme){ theme = _theme; }; this.$get = [function NoCaptchaFactory() { return { theme: theme, siteKey: siteKey } }]; }) .directive('noCaptcha', ['noCAPTCHA', function(noCaptcha){ return { restrict:'EA', scope: { gRecaptchaResponse:'=', siteKey:'@', theme:'@' }, replace: true, link: function(scope, element){ var widgetId, grecaptchaCreateParameters; grecaptchaCreateParameters = { sitekey: scope.siteKey || noCaptcha.siteKey, theme: scope.theme || noCaptcha.theme, callback: function(r){ scope.$apply(function(){ scope.gRecaptchaResponse = r; }); } }; grecaptcha.render( element[0], grecaptchaCreateParameters ); scope.$on('$destroy', function(){ grecaptcha.reset(widgetId); }); } }; }]); " "Return array, change param name","<?php namespace Coosos\TagBundle\Controller; use Coosos\TagBundle\Entity\Tag; use Coosos\TagBundle\Repository\TagRepository; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; /** * Class TagController * @package Coosos\TagBundle\Controller * @Route(""/tag"") */ class TagController extends Controller { /** * @Route(""/tag-list"", name=""coosos_tag_tag_tagList"") * @Method(""GET"") * @param Request $request * @return Response */ public function tagListAction(Request $request) { $searchTag = ($request->query->has(""term"")) ? $request->query->get(""term"") : null; $categoryTag = ($request->query->has(""category"")) ? $request->query->get(""category"") : ""default""; $em = $this->getDoctrine()->getManager(); /** @var TagRepository $repository */ $repository = $em->getRepository(""CoososTagBundle:Tag""); $results = $repository->getTagList($searchTag, $categoryTag, 5); $tags = []; /** @var Tag $result */ foreach ($results as $result) { $tags[] = $result->getName(); } return new JsonResponse($tags, 200); } } ","<?php namespace Coosos\TagBundle\Controller; use Coosos\TagBundle\Entity\Tag; use Coosos\TagBundle\Repository\TagRepository; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; /** * Class TagController * @package Coosos\TagBundle\Controller * @Route(""/tag"") */ class TagController extends Controller { /** * @Route(""/tag-list"", name=""coosos_tag_tag_tagList"") * @Method(""GET"") * @param Request $request * @return Response */ public function tagListAction(Request $request) { $searchTag = ($request->query->has(""tag"")) ? $request->query->get(""tag"") : null; $categoryTag = ($request->query->has(""category"")) ? $request->query->get(""category"") : null; $em = $this->getDoctrine()->getManager(); /** @var TagRepository $repository */ $repository = $em->getRepository(""CoososTagBundle:Tag""); $results = $repository->getTagList($searchTag, $categoryTag, 5); $tags = []; /** @var Tag $result */ foreach ($results as $result) { $tags[] = $result->getName(); } return new JsonResponse(json_encode($tags), 200); } } " Change name of file on the filesystem.,"<?php namespace Zf2FileUploader\Resource\Persister\Image; use Zend\Filter\File\Rename; use Zf2FileUploader\Options\ImageResourceOptionsInterface; use Zf2FileUploader\Resource\ImageResourceInterface; use Zf2FileUploader\Resource\Persister\AbstractFilesystemPersister; use Zf2FileUploader\Resource\Persister\ImagePersisterInterface; class FilesystemPersister extends AbstractFilesystemPersister implements ImagePersisterInterface { /** * @var ImageResourceOptionsInterface */ protected $options; /** * @var \Callable */ protected $revertClb = null; public function __construct(ImageResourceOptionsInterface $options) { $this->options = $options; } /** * @param ImageResourceInterface $resource * @return boolean */ public function persist(ImageResourceInterface $resource) { $ext = $resource->getExt(); $baseName = $resource->getToken().($ext ? '.'.$ext : ''); $target = realpath($this->options->getImagePersistentPath()).'/'.$baseName; $moveUploadedFilter = new Rename(array( 'target' => $target, 'overwrite' => false, 'randomize' => false, )); $moveUploadedFilter->filter($resource->getPath()); $resource->setPath($target); $resource->setHttpPath($this->options->getImageHttpPath().'/'.$baseName); $this->setCallbacks(null, function () use ($target) { if (file_exists($target)) { unlink($target); } }); return file_exists($target); } }","<?php namespace Zf2FileUploader\Resource\Persister\Image; use Zend\Filter\File\Rename; use Zf2FileUploader\Options\ImageResourceOptionsInterface; use Zf2FileUploader\Resource\ImageResourceInterface; use Zf2FileUploader\Resource\Persister\AbstractFilesystemPersister; use Zf2FileUploader\Resource\Persister\ImagePersisterInterface; class FilesystemPersister extends AbstractFilesystemPersister implements ImagePersisterInterface { /** * @var ImageResourceOptionsInterface */ protected $options; /** * @var \Callable */ protected $revertClb = null; public function __construct(ImageResourceOptionsInterface $options) { $this->options = $options; } /** * @param ImageResourceInterface $resource * @return boolean */ public function persist(ImageResourceInterface $resource) { $ext = $resource->getExt(); $baseName = uniqid().($ext ? '.'.$ext : ''); $target = realpath($this->options->getImagePersistentPath()).'/'.$baseName; $moveUploadedFilter = new Rename(array( 'target' => $target, 'overwrite' => false, 'randomize' => false, )); $moveUploadedFilter->filter($resource->getPath()); $resource->setPath($target); $resource->setHttpPath($this->options->getImageHttpPath().'/'.$baseName); $this->setCallbacks(null, function () use ($target) { if (file_exists($target)) { unlink($target); } }); return file_exists($target); } }" Add support for single row checking,"#!/usr/bin/env python3 # -*- coding: utf8 -*- """""" Usage: exgrep TERM [options] EXCEL_FILE... Options: TERM The term to grep for. Can be any valid (python) regular expression. EXCEL_FILE The list of files to search through -c COL Only search in the column specified by COL. -r ROW Only search in the row specified by ROW -o Only output the matched part """""" import re from docopt import docopt import xlrd __author__ = 'peter' def main(): args = docopt(__doc__) p = re.compile(args['TERM'], re.UNICODE) for f in args['EXCEL_FILE']: workbook = xlrd.open_workbook(f) sheet = workbook.sheet_by_index(0) if args['-c']: check_row(args, p, sheet, int(args['-c'])) continue for rownum in range(sheet.nrows): check_row(args, p, sheet, rownum) def check_row(args, p, sheet, rownum): """""" Check a row for the presence of pattern p. """""" for idx, v in enumerate(sheet.row_values(rownum)): if args['-c'] and idx != int(args['-c']): continue s = p.search(str(v)) if s: if args['-o']: print(s.group(0)) else: print(sheet.row_values(rownum)) if __name__ == '__main__': main()","#!/usr/bin/env python3 # -*- coding: utf8 -*- """""" Usage: exgrep TERM [options] EXCEL_FILE... Options: TERM The term to grep for. Can be any valid (python) regular expression. EXCEL_FILE The list of files to search through -c COL Only search in the column specified by COL. -o Only output the matched part """""" import re from docopt import docopt import xlrd __author__ = 'peter' def main(): args = docopt(__doc__) p = re.compile(args['TERM'], re.UNICODE) for f in args['EXCEL_FILE']: workbook = xlrd.open_workbook(f) sheet = workbook.sheet_by_index(0) for rownum in range(sheet.nrows): for idx, v in enumerate(sheet.row_values(rownum)): if args['-c'] and idx != int(args['-c']): continue s = p.search(str(v)) if s: if args['-o']: print(s.group(0)) else: print(sheet.row_values(rownum)) if __name__ == '__main__': main()" Use logging. Remove hardcoded settings,"from control_milight.utils import process_automatic_trigger from django.conf import settings from django.core.management.base import BaseCommand, CommandError import serial import time import logging logger = logging.getLogger(""%s.%s"" % (""homecontroller"", __name__)) class Command(BaseCommand): args = '' help = 'Listen for 433MHz radio messages' def handle(self, *args, **options): s = serial.Serial(settings.ARDUINO_433, 9600) ITEM_MAP = settings.ARDUINO_433_ITEM_MAP sent_event_map = {} while True: line = s.readline() if line.startswith(""Received ""): id = line.split("" "")[1] if id in self.ITEM_MAP: item_name = self.ITEM_MAP[id] if item_name in sent_event_map: if sent_event_map[item_name] > time.time() - 5: continue logger.info(""Processing trigger %s (%s)"", item_name, id) process_automatic_trigger(item_name) sent_event_map[item_name] = time.time() else: logger.warn(""Unknown ID: %s"", id) ","from control_milight.utils import process_automatic_trigger from django.conf import settings from django.core.management.base import BaseCommand, CommandError import serial import time class Command(BaseCommand): args = '' help = 'Listen for 433MHz radio messages' ITEM_MAP = { ""5236713"": ""kitchen"", ""7697747"": ""hall"", ""1328959"": ""front-door"", ""247615"": ""unused-magnetic-switch"", ""8981913"": ""table"", } def handle(self, *args, **options): s = serial.Serial(settings.ARDUINO_433, 9600) sent_event_map = {} while True: line = s.readline() print ""- %s"" % line if line.startswith(""Received ""): id = line.split("" "")[1] if id in self.ITEM_MAP: item_name = self.ITEM_MAP[id] if item_name in sent_event_map: if sent_event_map[item_name] > time.time() - 5: print ""Too recent event: %s"" % item_name continue process_automatic_trigger(item_name) sent_event_map[item_name] = time.time() else: print ""Unknown id: %s"" % id " Update user object on `earn` events.,"export default function notificationsPlugin () { const currentNotifications = Symbol('Notifications') return (mp) => { mp[currentNotifications] = [] function onNotify (notif) { mp[currentNotifications].push(notif) mp.emit('notify', mp.wrapNotification(notif)) } function onEarn (ref) { const me = mp.me() if (me) Object.assign(me, ref) mp.emit('earn', { xp: ref.xp, pp: ref.pp, level: ref.level }) } function onSub (sub) { const me = mp.me() if (me) me.sub = sub mp.emit('sub', sub) } mp.on('connected', (user) => { mp[currentNotifications] = (user && user.notifications) || [] mp.ws.on('notify', onNotify) mp.ws.on('earn', onEarn) mp.ws.on('sub', onSub) }) Object.assign(mp, { notifications: () => mp[currentNotifications].map(mp.wrapNotification), getNotifications: () => mp.getMe() .then((me) => me.notifications || []) .tap((notifs) => { mp[currentNotifications] = notifs }) .map(mp.wrapNotification), acknowledgeNotification: (id) => mp.del(`notifications/${id}`).tap(() => { // Remove the notification from the local notifications list. mp[currentNotifications] = mp[currentNotifications] .filter((notif) => notif.id !== Number(id)) }) }) } } ","export default function notificationsPlugin () { const currentNotifications = Symbol('Notifications') return (mp) => { mp[currentNotifications] = [] function onNotify (notif) { mp[currentNotifications].push(notif) mp.emit('notify', mp.wrapNotification(notif)) } function onEarn (ref) { mp.emit('earn', { xp: ref.xp, pp: ref.pp, level: ref.level }) } function onSub (sub) { const me = mp.me() if (me) me.sub = sub mp.emit('sub', sub) } mp.on('connected', (user) => { mp[currentNotifications] = (user && user.notifications) || [] mp.ws.on('notify', onNotify) mp.ws.on('earn', onEarn) mp.ws.on('sub', onSub) }) Object.assign(mp, { notifications: () => mp[currentNotifications].map(mp.wrapNotification), getNotifications: () => mp.getMe() .then((me) => me.notifications || []) .tap((notifs) => { mp[currentNotifications] = notifs }) .map(mp.wrapNotification), acknowledgeNotification: (id) => mp.del(`notifications/${id}`).tap(() => { // Remove the notification from the local notifications list. mp[currentNotifications] = mp[currentNotifications] .filter((notif) => notif.id !== Number(id)) }) }) } } " Add docstrings to output models,"import hashlib class Store(object): """""" Record for stores. id -- integer name -- string location -- ZipcodeRecord """""" def __init__(self): self.id = None self.name = None self.location = None def __repr__(self): return ""%s,%s,%s"" % (self.name, self.location.zipcode, self.location.coords) class Customer(object): """""" Record for customers. id -- integer name -- string location -- ZipcodeRecord """""" def __init__(self): self.id = None self.name = None self.location = None def __repr__(self): return ""(%s, %s, %s)"" % \ (self.id, self.name, self.location.zipcode) class Transaction(object): """""" Record for transactions store -- Store customer -- Customer trans_time -- transaction time in days since start of simulation. int or long purchased_items -- list of products purchased trans_count -- hidden transaction id """""" def __init__(self, customer=None, trans_time=None, purchased_items=None, store=None, trans_count=None): self.store = store self.customer = customer self.trans_time = trans_time self.purchased_items = purchased_items self.trans_count = trans_count def transaction_id(self): """""" Compute transaction id as a hash of the transaction. Returns a string """""" return hashlib.md5(repr(self)).hexdigest() def __repr__(self): return ""(%s, %s, %s, %s)"" % (self.store.id, self.customer.id, self.trans_time, self.trans_count) ","import hashlib class Store(object): def __init__(self): self.id = None self.name = None self.location = None def __repr__(self): return ""%s,%s,%s"" % (self.name, self.location.zipcode, self.location.coords) class Customer(object): def __init__(self): self.id = None self.name = None self.location = None def __repr__(self): return ""(%s, %s, %s)"" % \ (self.id, self.name, self.location.zipcode) class Transaction(object): def __init__(self, customer=None, trans_time=None, purchased_items=None, store=None, trans_count=None): self.store = store self.customer = customer self.trans_time = trans_time self.purchased_items = purchased_items self.trans_count = trans_count def transaction_id(self): return hashlib.md5(repr(self)).hexdigest() def __repr__(self): return ""(%s, %s, %s, %s)"" % (self.store.id, self.customer.id, self.trans_time, self.trans_count) " Remove user from count query to show likes count for all users for obj,"from django.contrib.auth.decorators import login_required from django.contrib.contenttypes.models import ContentType from django.http import HttpResponse from django.utils import simplejson as json from django.shortcuts import get_object_or_404, redirect from django.views.decorators.http import require_POST from phileo.models import Like from phileo.signals import object_liked, object_unliked @require_POST @login_required def like_toggle(request, content_type_id, object_id): content_type = get_object_or_404(ContentType, pk=content_type_id) like, created = Like.objects.get_or_create( sender = request.user, receiver_content_type = content_type, receiver_object_id = object_id ) if created: object_liked.send(sender=Like, like=like) else: like.delete() object_unliked.send( sender=Like, object=content_type.get_object_for_this_type( pk=object_id ) ) if request.is_ajax(): return HttpResponse(json.dumps({ ""likes_count"": Like.objects.filter( receiver_content_type = content_type, receiver_object_id = object_id ).count() }), mimetype=""application/json"") return redirect(request.META[""HTTP_REFERER""]) ","from django.contrib.auth.decorators import login_required from django.contrib.contenttypes.models import ContentType from django.http import HttpResponse from django.utils import simplejson as json from django.shortcuts import get_object_or_404, redirect from django.views.decorators.http import require_POST from phileo.models import Like from phileo.signals import object_liked, object_unliked @require_POST @login_required def like_toggle(request, content_type_id, object_id): content_type = get_object_or_404(ContentType, pk=content_type_id) like, created = Like.objects.get_or_create( sender = request.user, receiver_content_type = content_type, receiver_object_id = object_id ) if created: object_liked.send(sender=Like, like=like) else: like.delete() object_unliked.send( sender=Like, object=content_type.get_object_for_this_type( pk=object_id ) ) if request.is_ajax(): return HttpResponse(json.dumps({ ""likes_count"": Like.objects.filter( sender = request.user, receiver_content_type = content_type, receiver_object_id = object_id ).count() }), mimetype=""application/json"") return redirect(request.META[""HTTP_REFERER""]) " Fix login error in Django 1.8.,"from django.contrib.admin.sites import AdminSite from django.contrib.admin.forms import AdminAuthenticationForm from django import forms from django.utils.translation import ugettext_lazy as _ from django.contrib.auth import authenticate __author__ = 'weijia' ERROR_MESSAGE = _(""Please enter the correct username and password "" ""for a staff account. Note that both fields are case-sensitive."") class UserAdminAuthenticationForm(AdminAuthenticationForm): """""" Same as Django's AdminAuthenticationForm but allows to login any user who is not staff. """""" def clean(self): try: return super(UserAdminAuthenticationForm, self).clean() except: username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') message = ERROR_MESSAGE if username and password: try: self.user_cache = authenticate(username=username, password=password) except: # The following is for userena as it uses different param self.user_cache = authenticate(identification=username, password=password) if self.user_cache is None: raise forms.ValidationError(message) elif not self.user_cache.is_active: raise forms.ValidationError(message) self.check_for_test_cookie() return self.cleaned_data # For Django 1.8 def confirm_login_allowed(self, user): if not user.is_active: raise forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', params={'username': self.username_field.verbose_name} ) class UserAdmin(AdminSite): # Anything we wish to add or override login_form = UserAdminAuthenticationForm def has_permission(self, request): return request.user.is_active ","__author__ = 'weijia' from django.contrib.admin.sites import AdminSite from django.contrib.admin.forms import AdminAuthenticationForm from django import forms from django.utils.translation import ugettext_lazy as _ from django.contrib.auth import authenticate ERROR_MESSAGE = _(""Please enter the correct username and password "" ""for a staff account. Note that both fields are case-sensitive."") class UserAdminAuthenticationForm(AdminAuthenticationForm): """""" Same as Django's AdminAuthenticationForm but allows to login any user who is not staff. """""" def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') message = ERROR_MESSAGE if username and password: try: self.user_cache = authenticate(username=username, password=password) except: # The following is for userena as it uses different param self.user_cache = authenticate(identification=username, password=password) if self.user_cache is None: raise forms.ValidationError(message) elif not self.user_cache.is_active: raise forms.ValidationError(message) self.check_for_test_cookie() return self.cleaned_data class UserAdmin(AdminSite): # Anything we wish to add or override login_form = UserAdminAuthenticationForm def has_permission(self, request): return request.user.is_active " "Remove Python 2.5 from trove classifiers Despite the fact that Django 1.4 supports Python 2.5, we cannot test for it on Travis-CI. Will need to update the PyPi release to v0.4 to fix completely.","# coding: utf-8 from setuptools import setup import os version = __import__('timezone_utils').VERSION setup( name='django-timezone-utils', version=version, description='', long_description=open( os.path.join( os.path.dirname(__file__), ""README.rst"" ) ).read(), author=""Michael Barr"", author_email=""micbarr+developer@gmail.com"", license=""MIT"", packages=['timezone_utils'], install_requires=[ 'pytz', 'django>=1.4,<1.8' ], zip_safe=False, platforms='any', include_package_data=True, classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Database', 'Topic :: Software Development :: Libraries', ], url='http://github.com/michaeljohnbarr/django-timezone-utils/', ) ","# coding: utf-8 from setuptools import setup import os version = __import__('timezone_utils').VERSION setup( name='django-timezone-utils', version=version, description='', long_description=open( os.path.join( os.path.dirname(__file__), ""README.rst"" ) ).read(), author=""Michael Barr"", author_email=""micbarr+developer@gmail.com"", license=""MIT"", packages=['timezone_utils'], install_requires=[ 'pytz', 'django>=1.4,<1.8' ], zip_safe=False, platforms='any', include_package_data=True, classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Database', 'Topic :: Software Development :: Libraries', ], url='http://github.com/michaeljohnbarr/django-timezone-utils/', ) " "Revert ""Fixed bad owner/user config, causing pastes to fail with 'Please tell me who you are'"" This reverts commit b0396671c6aad090e6b9b5bc9d6b6886b9f0d4e3. The owner.* configuration is custom-made by phorkie. If we use user.*, anonymous commits automatically get the user.* settings which we do not want. Resolves: https://github.com/cweiske/phorkie/issues/27","<?php namespace phorkie; class Repository_Setup { protected $repo; public function __construct(Repository $repo) { $this->repo = $repo; } /** * Should be called right after a repository has been created, * either by ""git init"" or ""git clone"". * Takes care of removing hook example files and creating * the git daemon export file * * @return void */ public function afterInit() { foreach (glob($this->repo->gitDir . '/hooks/*') as $hookfile) { unlink($hookfile); } touch($this->repo->gitDir . '/git-daemon-export-ok'); $vc = $this->repo->getVc(); file_put_contents( $this->repo->gitDir . '/hooks/post-update', <<<CDE #!/bin/sh # Hook script to prepare a packed repository for use over dumb transports. exec git update-server-info CDE ); chmod($this->repo->gitDir . '/hooks/post-update', 0755); //keep track of owner $vc->getCommand('config') ->addArgument('owner.name') ->addArgument($_SESSION['name']) ->execute(); $vc->getCommand('config') ->addArgument('owner.email') ->addArgument($_SESSION['email']) ->execute(); } } ?> ","<?php namespace phorkie; class Repository_Setup { protected $repo; public function __construct(Repository $repo) { $this->repo = $repo; } /** * Should be called right after a repository has been created, * either by ""git init"" or ""git clone"". * Takes care of removing hook example files and creating * the git daemon export file * * @return void */ public function afterInit() { foreach (glob($this->repo->gitDir . '/hooks/*') as $hookfile) { unlink($hookfile); } touch($this->repo->gitDir . '/git-daemon-export-ok'); $vc = $this->repo->getVc(); file_put_contents( $this->repo->gitDir . '/hooks/post-update', <<<CDE #!/bin/sh # Hook script to prepare a packed repository for use over dumb transports. exec git update-server-info CDE ); chmod($this->repo->gitDir . '/hooks/post-update', 0755); //keep track of owner $vc->getCommand('config') ->addArgument('user.name') ->addArgument($_SESSION['name']) ->execute(); $vc->getCommand('config') ->addArgument('user.email') ->addArgument($_SESSION['email']) ->execute(); } } ?> " "Enable strict mode after setting default preferences values. Technically this is already our first strict mode violation - reading the preferences will require reading data from the disk and we are on the main thread here. However currently the following code requires that those values exist so we initialize strict mode a little later. Instead we could move the default values into code (constants) and avoid needing to read the file here. We will have to keep them in sync though (code and xml).","/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus; import android.app.Application; import android.os.StrictMode; import android.preference.PreferenceManager; import org.mozilla.focus.search.SearchEngineManager; import org.mozilla.focus.telemetry.TelemetryWrapper; import org.mozilla.focus.utils.AdjustHelper; import org.mozilla.focus.utils.AppConstants; public class FocusApplication extends Application { @Override public void onCreate() { super.onCreate(); PreferenceManager.setDefaultValues(this, R.xml.settings, false); enableStrictMode(); SearchEngineManager.getInstance().init(this); TelemetryWrapper.init(this); AdjustHelper.setupAdjustIfNeeded(this); } private void enableStrictMode() { if (AppConstants.isReleaseBuild()) { return; } StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyDeath() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectAll() .penaltyDeath() .build()); } } ","/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus; import android.app.Application; import android.os.StrictMode; import android.preference.PreferenceManager; import org.mozilla.focus.search.SearchEngineManager; import org.mozilla.focus.telemetry.TelemetryWrapper; import org.mozilla.focus.utils.AdjustHelper; import org.mozilla.focus.utils.AppConstants; public class FocusApplication extends Application { @Override public void onCreate() { super.onCreate(); enableStrictMode(); PreferenceManager.setDefaultValues(this, R.xml.settings, false); SearchEngineManager.getInstance().init(this); TelemetryWrapper.init(this); AdjustHelper.setupAdjustIfNeeded(this); } private void enableStrictMode() { if (AppConstants.isReleaseBuild()) { return; } StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyDeath() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectAll() .penaltyDeath() .build()); } } " Add passes to Grizzly's lazyOp,"""""""Summary """""" from weld.weldobject import * def to_weld_type(weld_type, dim): """"""Summary Args: weld_type (TYPE): Description dim (TYPE): Description Returns: TYPE: Description """""" for i in xrange(dim): weld_type = WeldVec(weld_type) return weld_type class LazyOpResult: """"""Wrapper class around as yet un-evaluated Weld computation results Attributes: dim (int): Dimensionality of the output expr (WeldObject / Numpy.ndarray): The expression that needs to be evaluated weld_type (WeldType): Type of the output object """""" def __init__(self, expr, weld_type, dim): """"""Summary Args: expr (TYPE): Description weld_type (TYPE): Description dim (TYPE): Description """""" self.expr = expr self.weld_type = weld_type self.dim = dim def evaluate(self, verbose=True, decode=True, passes=None): """"""Summary Args: verbose (bool, optional): Description decode (bool, optional): Description Returns: TYPE: Description """""" if isinstance(self.expr, WeldObject): return self.expr.evaluate( to_weld_type( self.weld_type, self.dim), verbose, decode, passes=passes) return self.expr ","""""""Summary """""" from weld.weldobject import * def to_weld_type(weld_type, dim): """"""Summary Args: weld_type (TYPE): Description dim (TYPE): Description Returns: TYPE: Description """""" for i in xrange(dim): weld_type = WeldVec(weld_type) return weld_type class LazyOpResult: """"""Wrapper class around as yet un-evaluated Weld computation results Attributes: dim (int): Dimensionality of the output expr (WeldObject / Numpy.ndarray): The expression that needs to be evaluated weld_type (WeldType): Type of the output object """""" def __init__(self, expr, weld_type, dim): """"""Summary Args: expr (TYPE): Description weld_type (TYPE): Description dim (TYPE): Description """""" self.expr = expr self.weld_type = weld_type self.dim = dim def evaluate(self, verbose=True, decode=True): """"""Summary Args: verbose (bool, optional): Description decode (bool, optional): Description Returns: TYPE: Description """""" if isinstance(self.expr, WeldObject): return self.expr.evaluate( to_weld_type( self.weld_type, self.dim), verbose, decode) return self.expr " Fix Fatal error: Can't use function return value,"<?php namespace Aedart\Scaffold\Cache; use Aedart\Scaffold\Containers\IoC; use Aedart\Scaffold\Contracts\Builders\IndexBuilder; use Illuminate\Contracts\Cache\Repository; /** * Cache Helper * * @author Alin Eugen Deac <aedart@gmail.com> * @package Aedart\Scaffold\Cache */ class CacheHelper { /** * Default cache directory */ const DEFAULT_CACHE_DIRECTORY = '.scaffold/cache/'; /** * @var Repository */ static protected $cache; /** * Register the cache directory * * @param string $directory */ static public function setCacheDirectory($directory) { $ioc = IoC::getInstance(); $config = $ioc->make('config'); $config->set('cacheDir', $directory); $ioc->container()['config'] = $config; } /** * Returns a cache repository instance * * @return Repository */ static public function make() { if(!isset(self::$cache)){ $ioc = IoC::getInstance(); $repository = $ioc->make(Repository::class); self::$cache = $repository; } return self::$cache; } /** * Destroy the cache instance inside this helper */ static public function destroy() { self::$cache = null; } }","<?php namespace Aedart\Scaffold\Cache; use Aedart\Scaffold\Containers\IoC; use Aedart\Scaffold\Contracts\Builders\IndexBuilder; use Illuminate\Contracts\Cache\Repository; /** * Cache Helper * * @author Alin Eugen Deac <aedart@gmail.com> * @package Aedart\Scaffold\Cache */ class CacheHelper { /** * Default cache directory */ const DEFAULT_CACHE_DIRECTORY = IndexBuilder::DEFAULT_SCAFFOLD_INDEX_DIRECTORY . 'cache/'; /** * @var Repository */ static protected $cache; /** * Register the cache directory * * @param string $directory */ static public function setCacheDirectory($directory) { $ioc = IoC::getInstance(); $config = $ioc->make('config'); $config->set('cacheDir', $directory); $ioc->container()['config'] = $config; } /** * Returns a cache repository instance * * @return Repository */ static public function make() { if(!isset(self::$cache)){ $ioc = IoC::getInstance(); $repository = $ioc->make(Repository::class); self::$cache = $repository; } return self::$cache; } /** * Destroy the cache instance inside this helper */ static public function destroy() { self::$cache = null; } }" "Add parse_off stub and change docstring I follow the TomDoc format for docstrings.","class HalfedgeMesh: def __init__(self, filename=None): """"""Make an empty halfedge mesh."""""" self.vertices = [] self.halfedges = [] self.facets = [] def parse_off(self, filename): """"""Parses OFF files and returns a set of vertices, halfedges, and facets. """""" pass def get_halfedge(self, u, v): """"""Retrieve halfedge with starting vertex u and target vertex v u - starting vertex v - target vertex Returns a halfedge """""" pass class Vertex: def __init__(self, x, y, z, index): """"""Create a vertex with given index at given point. x - x-coordinate of the point y - y-coordinate of the point z - z-coordinate of the point index - integer id of this vertex """""" pass def halfedges(self): """"""Return a list of halfedges targeting to this vertex."""""" pass class Facet: def __init__(self, index): """"""Create a facet with the given index."""""" pass def halfedges(self): """"""Return halfedges going ccw around this facet."""""" pass class Halfedge: def __init__(self, index): """"""Create a halfedge with given index."""""" pass def opposite(self): """"""Return the opposite halfedge."""""" pass def next(self): """"""Return the opposite halfedge."""""" pass def prev(self): """"""Return the opposite halfedge."""""" pass def vertex(self): """"""Return the target vertex."""""" pass def facet(self): """"""Return the incident facet."""""" pass if __name__ == '__main__': m = HalfedgeMesh() ","class HalfedgeMesh: def __init__(self, filename=None): """"""Make an empty halfedge mesh."""""" self.vertices = [] self.halfedges = [] self.facets = [] def read_off(self, filename): class Vertex: def __init__(self, x, y, z, index): """"""Create a vertex with given index at given point. Args: x: x-coordinate of the point y: y-coordinate of the point z: z-coordinate of the point index: integer id of this vertex """""" pass def halfedges(self): """"""Return a list of halfedges targeting to this vertex."""""" pass class Facet: def __init__(self, index): """"""Create a facet with the given index."""""" pass def halfedges(self): """"""Return halfedges going ccw around this facet."""""" pass class Halfedge: def __init__(self, index): """"""Create a halfedge with given index."""""" pass def opposite(self): """"""Return the opposite halfedge."""""" pass def next(self): """"""Return the opposite halfedge."""""" pass def prev(self): """"""Return the opposite halfedge."""""" pass def vertex(self): """"""Return the target vertex."""""" pass def facet(self): """"""Return the incident facet."""""" pass if __name__ == '__main__': m = HalfedgeMesh() " Improve error handling on service component.,"/** * Main script. * * This component provides a main script that handles HTTP requests using the * Express framework. * * This package provides a default service component which eliminates the * boilerplate typically used in most applications. It is expected that most * applications will take advantage of this capability. However, the main * script will preferrentially load an app-specific component, accomodating * applications that need to override the standard boilerplate. * * Once the service is created.... */ exports = module.exports = function(IoC, logger) { return IoC.create('app/service') .catch(function(err) { // No application-specific service component is provided. Create the // default service component, which eliminates boilerplate in the // application itself. if (err.code == 'IMPLEMENTATION_NOT_FOUND' && err.interface == 'app/service') { return IoC.create('./service'); } throw err; }) .then(function(service) { return IoC.create('./gateway') .then(function(gateways) { // TODO: Implement a way to return the annotations, so those // can be used to drive service discovery. gateways.forEach(function(gateway, i) { // Dispatch requests to the service, which in this case is an // Express app. gateway.listen(function(err) { // TODO: log it // TODO: service discovery announce }); gateway.on('request', service); }); }); }); }; exports['@implements'] = 'http://i.bixbyjs.org/main'; exports['@require'] = [ '!container', 'http://i.bixbyjs.org/Logger' ]; ","/** * Main script. * * This component provides a main script that handles HTTP requests using the * Express framework. * * This package provides a default service component which eliminates the * boilerplate typically used in most applications. It is expected that most * applications will take advantage of this capability. However, the main * script will preferrentially load an app-specific component, accomodating * applications that need to override the standard boilerplate. * * Once the service is created.... */ exports = module.exports = function(IoC, logger) { return IoC.create('app/service') .catch(function(err) { // TODO: Check that the error is failure to create app/service return IoC.create('./service'); throw err; }) .then(function(service) { return IoC.create('./gateway') .then(function(gateways) { // TODO: Implement a way to return the annotations, so those // can be used to drive service discovery. gateways.forEach(function(gateway, i) { // Dispatch requests to the service, which in this case is an // Express app. gateway.listen(function(err) { // TODO: log it // TODO: service discovery announce }); gateway.on('request', service); }); }); }); }; exports['@implements'] = 'http://i.bixbyjs.org/main'; exports['@require'] = [ '!container', 'http://i.bixbyjs.org/Logger' ]; " Throw exception on assert failure,"<?php declare(strict_types = 1); namespace ASN1\Type; use ASN1\Component\Identifier; use ASN1\Component\Length; use ASN1\Exception\DecodeException; use ASN1\Feature\ElementBase; /** * Base class for primitive strings. */ abstract class PrimitiveString extends StringType { use PrimitiveType; /** * * @see \ASN1\Element::_encodedContentDER() * @return string */ protected function _encodedContentDER(): string { return $this->_string; } /** * * {@inheritdoc} * @see \ASN1\Element::_decodeFromDER() * @return self */ protected static function _decodeFromDER(Identifier $identifier, string $data, int &$offset): ElementBase { $idx = $offset; if (!$identifier->isPrimitive()) { throw new DecodeException(""DER encoded string must be primitive.""); } $length = Length::expectFromDER($data, $idx)->intLength(); $str = $length ? substr($data, $idx, $length) : """"; // substr should never return false, since length is // checked by Length::expectFromDER. assert(is_string($str), new DecodeException(""substr"")); $offset = $idx + $length; try { return new static($str); } catch (\InvalidArgumentException $e) { throw new DecodeException($e->getMessage(), 0, $e); } } } ","<?php declare(strict_types = 1); namespace ASN1\Type; use ASN1\Component\Identifier; use ASN1\Component\Length; use ASN1\Exception\DecodeException; use ASN1\Feature\ElementBase; /** * Base class for primitive strings. */ abstract class PrimitiveString extends StringType { use PrimitiveType; /** * * @see \ASN1\Element::_encodedContentDER() * @return string */ protected function _encodedContentDER(): string { return $this->_string; } /** * * {@inheritdoc} * @see \ASN1\Element::_decodeFromDER() * @return self */ protected static function _decodeFromDER(Identifier $identifier, string $data, int &$offset): ElementBase { $idx = $offset; if (!$identifier->isPrimitive()) { throw new DecodeException(""DER encoded string must be primitive.""); } $length = Length::expectFromDER($data, $idx)->intLength(); $str = $length ? substr($data, $idx, $length) : """"; // substr should never return false, since length is // checked by Length::expectFromDER. assert(is_string($str), ""substr""); $offset = $idx + $length; try { return new static($str); } catch (\InvalidArgumentException $e) { throw new DecodeException($e->getMessage(), 0, $e); } } } " Add API token on registration,"<?php namespace App\Http\Controllers; use Auth; use Illuminate\Http\Request; use Illuminate\Support\Facades\Redirect; use SocialAuth; use SocialNorm\Exceptions\ApplicationRejectedException; use SocialNorm\Exceptions\InvalidAuthorizationCodeException; use Toastr; class LoginController extends Controller { public function showLogin() { return view('login'); } public function authorizeUser() { return SocialAuth::authorize('github'); } public function loginUser(Request $request) { try { SocialAuth::login('github', function ($user, $details) { $user->email = $details->email; $user->name = $details->full_name; $user->token = $details->access_token; $user->github_username = $details->nickname; $user->api_token = str_random(60); $user->save(); }); } catch (ApplicationRejectedException $e) { return redirect('login'); } catch (InvalidAuthorizationCodeException $e) { return redirect('login'); } $request->session()->regenerate(); // Current user is now available via Auth facade $user = Auth::user(); Toastr::success(trans('alerts.loggedin'), trans('alerts.success')); return redirect('dashboard'); } public function logoutUser() { Auth::logout(); return redirect(''); } } ","<?php namespace App\Http\Controllers; use Auth; use Illuminate\Http\Request; use Illuminate\Support\Facades\Redirect; use SocialAuth; use SocialNorm\Exceptions\ApplicationRejectedException; use SocialNorm\Exceptions\InvalidAuthorizationCodeException; use Toastr; class LoginController extends Controller { public function showLogin() { return view('login'); } public function authorizeUser() { return SocialAuth::authorize('github'); } public function loginUser(Request $request) { try { SocialAuth::login('github', function ($user, $details) { $user->email = $details->email; $user->name = $details->full_name; $user->token = $details->access_token; $user->github_username = $details->nickname; $user->save(); }); } catch (ApplicationRejectedException $e) { return redirect('login'); } catch (InvalidAuthorizationCodeException $e) { return redirect('login'); } $request->session()->regenerate(); // Current user is now available via Auth facade $user = Auth::user(); Toastr::success(trans('alerts.loggedin'), trans('alerts.success')); return redirect('dashboard'); } public function logoutUser() { Auth::logout(); return redirect(''); } } " Fix count() method that might not return a relevant result,"<?php namespace BenTools\ETL\Iterator; use FilterIterator; use SplFileObject; class CsvFileIterator extends FilterIterator implements \Countable { private $nbLines; private $file; /** * CsvFileIterator constructor. * * @param $filename * @param string $delimiter * @param string $enclosure */ public function __construct(SplFileObject $file, $delimiter = ',', $enclosure = '""', $escapeString = '\\') { $this->file = $file; $this->file->setCsvControl($delimiter, $enclosure, $escapeString); $this->file->setFlags(SplFileObject::READ_CSV); parent::__construct($this->file); } /** * @inheritDoc */ public function accept() { $current = $this->getInnerIterator()->current(); return !empty(array_filter( $current, function ($cell) { return null !== $cell; } )); } /** * @inheritdoc */ public function count() { if (null === $this->nbLines) { $this->rewind(); $this->nbLines = count(iterator_to_array($this)); } return $this->nbLines; } } ","<?php namespace BenTools\ETL\Iterator; use FilterIterator; use SplFileObject; class CsvFileIterator extends FilterIterator implements \Countable { private $nbLines; private $file; /** * CsvFileIterator constructor. * * @param $filename * @param string $delimiter * @param string $enclosure */ public function __construct(SplFileObject $file, $delimiter = ',', $enclosure = '""', $escapeString = '\\') { $this->file = $file; $this->file->setCsvControl($delimiter, $enclosure, $escapeString); $this->file->setFlags(SplFileObject::READ_CSV); parent::__construct($this->file); } /** * @inheritDoc */ public function accept() { $current = $this->getInnerIterator()->current(); return !empty(array_filter( $current, function ($cell) { return null !== $cell; } )); } /** * @inheritdoc */ public function count() { if (null === $this->nbLines) { $flags = $this->file->getFlags(); $current = $this->file->key(); $this->file->setFlags(null); $this->file->seek(PHP_INT_MAX); $this->nbLines = $this->file->key() + 1; $this->file->seek($current); $this->file->setFlags($flags); } return $this->nbLines; } } " Rename and add missing modifier,"package org.yoooo.se1; import java.util.Scanner; public class Application { public void run(String[] args) { } public SimpleDirectedWeightGraph<String, Integer> getGraph() { return null; } private static Application sInstance = new Application(); public static Application getInstance() { return sInstance; } private Application() { } /** * Parses string and generates graph from the string as specified in feature 1. The string * should only contain lowercase letters and spaces. * * @param string string from input file * @return graph created from string */ private SimpleDirectedWeightGraph<String, Integer> stringToGraph(String string) { Scanner scanner = new Scanner(string); SimpleDirectedWeightGraph<String, Integer> graph = new SimpleDirectedWeightGraph<>( new EdgeFactory<String, Integer>() { private int mNext; @Override public Integer createEdge(String source, String target) { return mNext++; } }); if (!scanner.hasNext()) { return graph; } String prev = scanner.next(); graph.addVertex(prev); while (scanner.hasNext()) { String vertex = scanner.next(); graph.addVertex(vertex); Integer edge = graph.getEdge(prev, vertex); if (edge != null) { graph.setEdgeWeight(edge, graph.getEdgeWeight(edge) + 1); } else { graph.addEdge(prev, vertex); } } return graph; } } ","package org.yoooo.se1; import java.util.Scanner; public class Application { public void run(String[] args) { } public SimpleDirectedWeightGraph<String, Integer> getGraph() { return null; } private static Application sInstance = new Application(); public static Application getInstance() { return sInstance; } private Application() { } /** * Parses string and generates graph from the string as specified in feature 1. The string * should only contain lowercase letters and spaces. * * @param string string from input file * @return graph created from string */ private SimpleDirectedWeightGraph<String, Integer> stringToGraph(String string) { Scanner scanner = new Scanner(string); SimpleDirectedWeightGraph<String, Integer> graph = new SimpleDirectedWeightGraph<>( new EdgeFactory<String, Integer>() { int next; @Override public Integer createEdge(String source, String target) { return next++; } }); if (!scanner.hasNext()) { return graph; } String prev = scanner.next(); graph.addVertex(prev); while (scanner.hasNext()) { String vertex = scanner.next(); graph.addVertex(vertex); Integer edge = graph.getEdge(prev, vertex); if (edge != null) { graph.setEdgeWeight(edge, graph.getEdgeWeight(edge) + 1); } else { graph.addEdge(prev, vertex); } } return graph; } } " Fix import with links in embedded collections of maps,"package com.orientechnologies.orient.core.db.tool.importer; import com.orientechnologies.orient.core.db.record.OIdentifiable; /** Created by tglman on 28/07/17. */ public abstract class OAbstractCollectionConverter<T> implements OValuesConverter<T> { private final OConverterData converterData; protected OAbstractCollectionConverter(OConverterData converterData) { this.converterData = converterData; } public interface ResultCallback { void add(Object item); } protected boolean convertSingleValue(final Object item, ResultCallback result, boolean updated) { if (item == null) return false; if (item instanceof OIdentifiable) { final OValuesConverter<OIdentifiable> converter = (OValuesConverter<OIdentifiable>) OImportConvertersFactory.INSTANCE.getConverter(item, converterData); final OIdentifiable newValue = converter.convert((OIdentifiable) item); // this code intentionally uses == instead of equals, in such case we may distinguish rids // which already contained in // document and RID which is used to indicate broken record if (newValue != OImportConvertersFactory.BROKEN_LINK) result.add(newValue); if (!newValue.equals(item)) updated = true; } else { final OValuesConverter valuesConverter = OImportConvertersFactory.INSTANCE.getConverter(item, converterData); if (valuesConverter == null) result.add(item); else { final Object newValue = valuesConverter.convert(item); if (newValue != item) updated = true; result.add(newValue); } } return updated; } } ","package com.orientechnologies.orient.core.db.tool.importer; import com.orientechnologies.orient.core.db.record.OIdentifiable; /** Created by tglman on 28/07/17. */ public abstract class OAbstractCollectionConverter<T> implements OValuesConverter<T> { private final OConverterData converterData; protected OAbstractCollectionConverter(OConverterData converterData) { this.converterData = converterData; } public interface ResultCallback { void add(Object item); } protected boolean convertSingleValue(final Object item, ResultCallback result, boolean updated) { if (item == null) return false; if (item instanceof OIdentifiable) { final OValuesConverter<OIdentifiable> converter = (OValuesConverter<OIdentifiable>) OImportConvertersFactory.INSTANCE.getConverter(item, converterData); final OIdentifiable newValue = converter.convert((OIdentifiable) item); // this code intentionally uses == instead of equals, in such case we may distinguish rids // which already contained in // document and RID which is used to indicate broken record if (newValue != OImportConvertersFactory.BROKEN_LINK) result.add(newValue); if (!newValue.equals(item)) updated = true; } else { final OValuesConverter valuesConverter = OImportConvertersFactory.INSTANCE.getConverter(item.getClass(), converterData); if (valuesConverter == null) result.add(item); else { final Object newValue = valuesConverter.convert(item); if (newValue != item) updated = true; result.add(newValue); } } return updated; } } " Use user em in list users command,"<?php namespace AppBundle\Command; use AppBundle\Service\DBVersion; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class ListUserCommand extends ContainerAwareCommand { protected function configure() { $this // the name of the command (the part after ""bin/console"") ->setName('app:list-user') // the short description shown while running ""php bin/console list"" ->setDescription('Lists existing users.') // the full command description shown when running the command with // the ""--help"" option ->setHelp(""This command allows you to list all existing users..."") ->addOption('connection', 'c', InputOption::VALUE_REQUIRED, 'The database version') ; } protected function execute(InputInterface $input, OutputInterface $output) { $em = $this->getContainer()->get(DBVersion::class)->getUserEntityManager(); $users = $em->getRepository('AppBundle:FennecUser')->findAll(); $table = new Table($output); $table->setHeaders(['user_id', 'firstName', 'lastName', 'username']); foreach($users as $user){ $table->addRow([$user->getId(), $user->getFirstName(), $user->getLastName(), $user->getUsername()]); } $table->render(); } }","<?php namespace AppBundle\Command; use AppBundle\Service\DBVersion; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class ListUserCommand extends ContainerAwareCommand { protected function configure() { $this // the name of the command (the part after ""bin/console"") ->setName('app:list-user') // the short description shown while running ""php bin/console list"" ->setDescription('Lists existing users.') // the full command description shown when running the command with // the ""--help"" option ->setHelp(""This command allows you to list all existing users..."") ->addOption('connection', 'c', InputOption::VALUE_REQUIRED, 'The database version') ; } protected function execute(InputInterface $input, OutputInterface $output) { $connection_name = $input->getOption('connection'); if($connection_name == null) { $connection_name = $this->getContainer()->get('doctrine')->getDefaultConnectionName(); } $em = $this->getContainer()->get(DBVersion::class)->getEntityManager(); $users = $em->getRepository('AppBundle:FennecUser')->findAll(); $table = new Table($output); $table->setHeaders(['user_id', 'firstName', 'lastName', 'username']); foreach($users as $user){ $table->addRow([$user->getId(), $user->getFirstName(), $user->getLastName(), $user->getUsername()]); } $table->render(); } }" Clean up the management command stub in preparation of further development.,"import os import xlrd from django.core.management.base import BaseCommand, CommandError from olcc.models import Product class Command(BaseCommand): """""" :todo: Use optparse to add a --quiet option to supress all output except errors. :todo: Write a separate management command to fetch the latest price document. """""" args = ""<filename>"" help = ""Parses an excel document of OLCC price data."" def handle(self, *args, **options): try: filename = args[0] if not filename: # Get latest file and hash for update # ... pass self.stdout.write(""Importing from \""%s\""...\n"" % filename) # Import workbook wb = xlrd.open_workbook(filename) self.stdout.write(""Sheet Names:\n%s\n"" % wb.sheet_names()) # Get the first sheet sheet = wb.sheet_by_index(0) # Loop over worksheet for rownum in range(sheet.nrows): values = sheet.row_values(rownum) if len(values) > 0: try: # TODO: Updating products Product.from_row(values) except IndexError: pass except IOError as (errno, strerror): raise CommandError(""%s"" % strerror) except IndexError: raise CommandError(""You must specify a filename!"") ","import os import xlrd from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): """""" """""" args = ""<filename>"" help = ""Parses an excel document of OLCC price data."" def handle(self, *args, **options): try: filename = args[0] if not filename: # Get latest file and hash for update # ... pass self.stdout.write(""Importing from \""%s\""...\n"" % filename) # Import workbook wb = xlrd.open_workbook(filename); self.stdout.write(""Sheet Names:\n%s\n"" % wb.sheet_names()) # Get the first sheet sheet = wb.sheet_by_index(0) # Loop over worksheet #[u'Report Date: ', '', 40863.0, '', '', ''] #['', '', '', '', '', ''] #[u'Item Code', u'Item Status', u'Description', u'Size', u'Bottles per Case', u'Bottle Price'] #[u'0102B', u'@', u'GLENFIDDICH SNOW PHOENIX', u'750 ML', 6.0, 92.950000000000003] for rownum in range(sheet.nrows): print sheet.row_values(rownum) except IOError as (errno, strerror): raise CommandError(""%s"" % strerror) except IndexError: raise CommandError(""You must specify a filename!"") " "Fix CSP header, but Firefox doen't work","<?php /** * CSP * * @author Kenji Suzuki <https://github.com/kenjis> * @license MIT License * @copyright 2014 Kenji Suzuki * @link https://github.com/kenjis/php-csp-nonce-source */ class Csp { private static $nonce; private static function generateNonce() { $length = 16; $bytes = ''; if (function_exists('openssl_random_pseudo_bytes')) { $bytes = openssl_random_pseudo_bytes($length, $usable); if ($usable === false) { // weak } } else { throw new Exception('Can\'t use openssl_random_pseudo_bytes'); } static::$nonce = base64_encode($bytes); } public static function setHeader() { if (static::$nonce === null) { static::generateNonce(); } header(""Content-Security-Policy: script-src 'unsafe-inline' 'nonce-"" . static::$nonce . ""'""); } public static function getNonce() { if (static::$nonce === null) { static::generateNonce(); } return static::$nonce; } } ","<?php /** * CSP * * @author Kenji Suzuki <https://github.com/kenjis> * @license MIT License * @copyright 2014 Kenji Suzuki * @link https://github.com/kenjis/php-csp-nonce-source */ class Csp { private static $nonce; private static function generateNonce() { $length = 16; $bytes = ''; if (function_exists('openssl_random_pseudo_bytes')) { $bytes = openssl_random_pseudo_bytes($length, $usable); if ($usable === false) { // weak } } else { throw new Exception('Can\'t use openssl_random_pseudo_bytes'); } static::$nonce = base64_encode($bytes); } public static function setHeader() { if (static::$nonce === null) { static::generateNonce(); } header(""Content-Security-Policy: unsafe-inline; script-src 'nonce-"" . static::$nonce . ""'""); } public static function getNonce() { if (static::$nonce === null) { static::generateNonce(); } return static::$nonce; } } " Fix SQL for team filter,"<?php namespace App\Nova\Filters; use App\Team; use Illuminate\Http\Request; use Laravel\Nova\Filters\Filter; class UserTeam extends Filter { /** * The filter's component. * * @var string */ public $component = 'select-filter'; /** * Apply the filter to the given query. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Database\Eloquent\Builder $query * @param mixed $value * @return \Illuminate\Database\Eloquent\Builder */ public function apply(Request $request, $query, $value) { return $query->whereHas('teams', function ($query) use ($value) { $query->where('teams.id', '=', $value); }); } /** * Get the filter's available options. * * @param \Illuminate\Http\Request $request * @return array */ public function options(Request $request) { $teams = []; if ($request->user()->can('read-teams')) { $teams = Team::where('attendable', 1) ->when($request->user()->cant('read-teams-hidden'), function ($query) { $query->where('visible', 1); })->get() ->mapWithKeys(function ($item) { return [$item['name'] => $item['id']]; })->toArray(); } return $teams; } } ","<?php namespace App\Nova\Filters; use App\Team; use Illuminate\Http\Request; use Laravel\Nova\Filters\Filter; class UserTeam extends Filter { /** * The filter's component. * * @var string */ public $component = 'select-filter'; /** * Apply the filter to the given query. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Database\Eloquent\Builder $query * @param mixed $value * @return \Illuminate\Database\Eloquent\Builder */ public function apply(Request $request, $query, $value) { return $query->whereHas('teams', function ($query) use ($value) { $query->where('id', '=', $value); }); } /** * Get the filter's available options. * * @param \Illuminate\Http\Request $request * @return array */ public function options(Request $request) { $teams = []; if ($request->user()->can('read-teams')) { $teams = Team::where('attendable', 1) ->when($request->user()->cant('read-teams-hidden'), function ($query) { $query->where('visible', 1); })->get() ->mapWithKeys(function ($item) { return [$item['name'] => $item['id']]; })->toArray(); } return $teams; } } " "Make sure we're not grabbing any prototype props Probably unnecessary, but let's be safe","'use strict'; var trackStar = (function(){ function TrackStar() { var integrations = {}; if(!(this instanceof TrackStar)){ return new TrackStar(); } this.getIntegrations = function() { return integrations; }; this.integrate = function(integrationsObj) { if (Object.prototype.toString.call(integrationsObj) !== '[object Object]') { throw new Error('trackStar requires an Object of integrations'); } for(var key in integrationsObj){ if (integrationsObj.hasOwnProperty[key]){ var val = integrationsObj[key]; if (integrations.hasOwnProperty(key)) { integrations[key] = integrations[key].concat(val); } else { integrations[key] = [].concat(val); } } } return this; }; // Start testing API this.wipeClean = TrackStar; // End testing API return this; } function sendFunction (context, functionName, opts) { var integrations = context.getIntegrations(); for (var key in integrations){ if(integrations.hasOwnProperty(key)){ _integrationsMasterList[key][functionName](opts); } } } TrackStar.prototype.trackPageView = function() { sendFunction(this, 'trackPageView'); }; TrackStar.prototype.trackConversion = function(){ sendFunction(this, 'trackConversion'); }; TrackStar.prototype.trackAction = function(opts){ sendFunction(this, 'trackAction', opts); }; return window.trackStar = TrackStar(); }()); ","'use strict'; var trackStar = (function(){ function TrackStar() { var integrations = {}; if(!(this instanceof TrackStar)){ return new TrackStar(); } this.getIntegrations = function() { return integrations; }; this.integrate = function(integrationsObj) { if (Object.prototype.toString.call(integrationsObj) !== '[object Object]') { throw new Error('trackStar requires an Object of integrations'); } for(var key in integrationsObj){ var val = integrationsObj[key]; if (integrations.hasOwnProperty(key)) { integrations[key] = integrations[key].concat(val); } else { integrations[key] = [].concat(val); } } return this; }; // Start testing API this.wipeClean = TrackStar; // End testing API return this; } function sendFunction (context, functionName, opts) { var integrations = context.getIntegrations(); for (var key in integrations){ _integrationsMasterList[key][functionName](opts); }; } TrackStar.prototype.trackPageView = function() { sendFunction(this, 'trackPageView'); }; TrackStar.prototype.trackConversion = function(){ sendFunction(this, 'trackConversion'); }; TrackStar.prototype.trackAction = function(opts){ sendFunction(this, 'trackAction', opts); }; return window.trackStar = TrackStar(); }()); " "engine: Use proper method to mark net changes as saved The patch reduces the need for updating the entire VdsDynamic data by using a designated method for saving the dirty-network indicator of the host. Change-Id: Ib4c54214a275a1653c46bca7c95ff847975dd7d4 Signed-off-by: Moti Asayag <da1debb83a8e12b6e8822edf2c275f55cc51b720@redhat.com>","package org.ovirt.engine.core.bll.network.host; import org.ovirt.engine.core.bll.VdsCommand; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.action.VdsActionParameters; import org.ovirt.engine.core.common.vdscommands.VDSCommandType; import org.ovirt.engine.core.common.vdscommands.VDSReturnValue; import org.ovirt.engine.core.common.vdscommands.VdsIdVDSCommandParametersBase; @SuppressWarnings(""serial"") public class CommitNetworkChangesCommand<T extends VdsActionParameters> extends VdsCommand<T> { public CommitNetworkChangesCommand(T param) { super(param); } @Override protected void executeCommand() { VDSReturnValue retVal = runVdsCommand(VDSCommandType.SetSafeNetworkConfig, new VdsIdVDSCommandParametersBase(getParameters().getVdsId())); getDbFacade().getVdsDynamicDao().updateNetConfigDirty(getParameters().getVdsId(), false); setSucceeded(retVal.getSucceeded()); } @Override protected boolean canDoAction() { return true; } @Override public AuditLogType getAuditLogTypeValue() { return getSucceeded() ? AuditLogType.NETWORK_COMMINT_NETWORK_CHANGES : AuditLogType.NETWORK_COMMINT_NETWORK_CHANGES_FAILED; } } ","package org.ovirt.engine.core.bll.network.host; import org.ovirt.engine.core.bll.Backend; import org.ovirt.engine.core.bll.VdsCommand; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.action.VdsActionParameters; import org.ovirt.engine.core.common.vdscommands.VDSCommandType; import org.ovirt.engine.core.common.vdscommands.VDSReturnValue; import org.ovirt.engine.core.common.vdscommands.VdsIdVDSCommandParametersBase; @SuppressWarnings(""serial"") public class CommitNetworkChangesCommand<T extends VdsActionParameters> extends VdsCommand<T> { public CommitNetworkChangesCommand(T param) { super(param); } @Override protected void executeCommand() { VDSReturnValue retVal = Backend .getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.SetSafeNetworkConfig, new VdsIdVDSCommandParametersBase(getParameters().getVdsId())); getVds().setNetConfigDirty(false); getDbFacade().getVdsDynamicDao().update(getVds().getDynamicData()); setSucceeded(retVal.getSucceeded()); } @Override protected boolean canDoAction() { return true; } @Override public AuditLogType getAuditLogTypeValue() { return getSucceeded() ? AuditLogType.NETWORK_COMMINT_NETWORK_CHANGES : AuditLogType.NETWORK_COMMINT_NETWORK_CHANGES_FAILED; } } " Fix wrong oauthId when creating users.,"""use strict""; const passport = require('passport'); const BdApiStrategy = require('passport-bdapi').Strategy; module.exports = (config, app, passport, models) => { passport.use(new BdApiStrategy({ apiURL: config.apiUrl, clientID: config.clientId, clientSecret: config.clientSecret, callbackURL: config.callbackUrl }, (accessToken, refreshToken, profile, done) => { models.User.findOne({oauthId: `cf-${profile.user_id}`}, (err, user) => { if (user) { user.username = profile.username; user.save(err => done(err, user)); } else { models.User.create({ oauthId: `cf-${profile.user_id}`, username: profile.username }) .then(user => done(null, user)) .then(null, err => done(err, null)); } }); })); app.get('/auth/craftenforum', passport.authenticate('oauth2', {scope: 'read'}) ); app.get('/auth/craftenforum/callback', passport.authenticate('oauth2', {failureRedirect: '/'}), (req, res) => res.redirect('/') ); };","""use strict""; const passport = require('passport'); const BdApiStrategy = require('passport-bdapi').Strategy; module.exports = (config, app, passport, models) => { passport.use(new BdApiStrategy({ apiURL: config.apiUrl, clientID: config.clientId, clientSecret: config.clientSecret, callbackURL: config.callbackUrl }, (accessToken, refreshToken, profile, done) => { models.User.findOne({oauthId: `cf-${profile.user_id}`}, (err, user) => { if (user) { user.username = profile.username; user.save(err => done(err, user)); } else { models.User.create({ oauthId: ""cf-#{profile.user_id}"", username: profile.username }) .then(user => done(null, user)) .then(null, err => done(err, null)); } }); })); app.get('/auth/craftenforum', passport.authenticate('oauth2', {scope: 'read'}) ); app.get('/auth/craftenforum/callback', passport.authenticate('oauth2', {failureRedirect: '/'}), (req, res) => res.redirect('/') ); };" Add ngModel scope watchers and update the model and settings,"angular.module('angular-fullcalendar',[]) .value('CALENDAR_DEFAULTS',{ locale:'en' }) .directive('fc',['CALENDAR_DEFAULTS',fcDirectiveFn]); function fcDirectiveFn(CALENDAR_DEFAULTS) { return { restrict : 'A', scope : { eventSource : '=ngModel',options : '=fcOptions' }, link:function (scope, elm) { var calendar; init(); scope.$watch('eventSource', watchDirective,true); scope.$watch('options',watchDirective,true); scope.$on('$destroy', function () { destroy();}); function init() { if (!calendar) { calendar = $(elm).html(''); } calendar.fullCalendar(getOptions(scope.options)); } function destroy() { if(calendar && calendar.fullCalendar){ calendar.fullCalendar('destroy'); } } function getOptions(options) { return angular.extend(CALENDAR_DEFAULTS,{ events:scope.eventSource },options); } function watchDirective(newOptions,oldOptions) { if (newOptions !== oldOptions) { destroy(); init(); } else if ((newOptions && angular.isUndefined(calendar))) { init(); } } } }; } ","angular.module('angular-fullcalendar',[]) .value('CALENDAR_DEFAULTS',{ locale:'en' }) .directive('fc',['CALENDAR_DEFAULTS',fcDirectiveFn]); function fcDirectiveFn(CALENDAR_DEFAULTS) { return { restrict : 'A', scope : { eventSource : '=ngModel', options : '=fcOptions' }, link:function (scope, elm) { var calendar; init(); scope.$watch('options', function(newOptions,oldOptions) { if (newOptions !== oldOptions) { destroy(); init(); } else if ((newOptions && angular.isUndefined(calendar))) { init(); } },true); scope.$on('$destroy', function () { destroy(); }); function init() { if (!calendar) { calendar = $(elm).html(''); } calendar.fullCalendar(getOptions(scope.options)); } function destroy() { if(calendar && calendar.fullCalendar){ calendar.fullCalendar('destroy'); } } function getOptions(options) { return angular.extend(CALENDAR_DEFAULTS,{ events:scope.eventSource },options); } } }; } " Fix jinja loader on Py3,"""""""Genshi template loader that supports dotted names."""""" from os.path import exists, getmtime from jinja2.exceptions import TemplateNotFound from jinja2.loaders import FileSystemLoader from tg import config class JinjaTemplateLoader(FileSystemLoader): """"""Jinja template loader supporting dotted filenames. Based on Genshi Loader """""" template_extension = '.jinja' def get_source(self, environment, template): # Check if dottedname if not template.endswith(self.template_extension): # Get the actual filename from dotted finder finder = config['tg.app_globals'].dotted_filename_finder template = finder.get_dotted_filename( template_name=template, template_extension=self.template_extension) else: return FileSystemLoader.get_source(self, environment, template) # Check if the template exists if not exists(template): raise TemplateNotFound(template) # Get modification time mtime = getmtime(template) # Read the source fd = open(template, 'rb') try: source = fd.read().decode('utf-8') finally: fd.close() return source, template, lambda: mtime == getmtime(template) ","""""""Genshi template loader that supports dotted names."""""" from os.path import exists, getmtime from jinja2.exceptions import TemplateNotFound from jinja2.loaders import FileSystemLoader from tg import config class JinjaTemplateLoader(FileSystemLoader): """"""Jinja template loader supporting dotted filenames. Based on Genshi Loader """""" template_extension = '.jinja' def get_source(self, environment, template): # Check if dottedname if not template.endswith(self.template_extension): # Get the actual filename from dotted finder finder = config['pylons.app_globals'].dotted_filename_finder template = finder.get_dotted_filename( template_name=template, template_extension=self.template_extension) else: return FileSystemLoader.get_source(self, environment, template) # Check if the template exists if not exists(template): raise TemplateNotFound(template) # Get modification time mtime = getmtime(template) # Read the source fd = file(template) try: source = fd.read().decode('utf-8') finally: fd.close() return source, template, lambda: mtime == getmtime(template) " Fix lead save add mobile field,"<?php namespace App\Http\Controllers\Lead; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use App\Http\Controllers\MainController; use App\Models\Lead; class LeadSaveController extends MainController { /** * @param Request $request * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector */ public function save(Request $request) { if (empty($request->id)) { $lead = new Lead(); $lead->seller_id = Auth::user()->id; $lead->created_at = now(); } else { $lead = Lead::find($request->id); } $lead->company_id = Auth::user()->company_id; $lead->name = $request->name; $lead->business_name = $request->business_name; $lead->phone = $request->phone; $lead->mobile = $request->mobile; $lead->email = $request->email; $lead->country_id = $request->country_id; $lead->website = $request->website; $lead->notes = $request->notes; $lead->linkedin = $request->linkedin; $lead->facebook = $request->facebook; $lead->instagram = $request->instagram; $lead->twitter = $request->twitter; $lead->youtube = $request->youtube; $lead->tiktok = $request->tiktok; $lead->updated_at = now(); $lead->save(); return redirect('/lead'); } } ","<?php namespace App\Http\Controllers\Lead; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use App\Http\Controllers\MainController; use App\Models\Lead; class LeadSaveController extends MainController { /** * @param Request $request * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector */ public function save(Request $request) { if (empty($request->id)) { $lead = new Lead(); $lead->seller_id = Auth::user()->id; $lead->created_at = now(); } else { $lead = Lead::find($request->id); } $lead->company_id = Auth::user()->company_id; $lead->first_name = $request->first_name; $lead->last_name = $request->last_name; $lead->phone = $request->phone; $lead->email = $request->email; $lead->country_id = $request->country_id; $lead->website = $request->website; $lead->notes = $request->notes; $lead->linkedin = $request->linkedin; $lead->facebook = $request->facebook; $lead->instagram = $request->instagram; $lead->twitter = $request->twitter; $lead->youtube = $request->youtube; $lead->tiktok = $request->tiktok; $lead->updated_at = now(); $lead->save(); return redirect('/lead'); } } " common: Allow to register unnamed django views,"# Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from django.conf.urls import url class UrlsIndex(object): """""" Simple helper class for centralizing url patterns of a Django web application. Derived classes should override the 'scope' class attribute otherwise all declared patterns will be grouped under the default one. """""" urlpatterns = {} scope = 'default' @classmethod def add_url_pattern(cls, url_pattern, view, view_name): """""" Class method that adds an url pattern to the current scope. Args: url_pattern: regex describing a Django url view: function implementing the Django view view_name: name of the view used to reverse the url """""" if cls.scope not in cls.urlpatterns: cls.urlpatterns[cls.scope] = [] if view_name: cls.urlpatterns[cls.scope].append(url(url_pattern, view, name=view_name)) else: cls.urlpatterns[cls.scope].append(url(url_pattern, view)) @classmethod def get_url_patterns(cls): """""" Class method that returns the list of url pattern associated to the current scope. Returns: The list of url patterns associated to the current scope """""" return cls.urlpatterns[cls.scope] ","# Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from django.conf.urls import url class UrlsIndex(object): """""" Simple helper class for centralizing url patterns of a Django web application. Derived classes should override the 'scope' class attribute otherwise all declared patterns will be grouped under the default one. """""" urlpatterns = {} scope = 'default' @classmethod def add_url_pattern(cls, url_pattern, view, view_name): """""" Class method that adds an url pattern to the current scope. Args: url_pattern: regex describing a Django url view: function implementing the Django view view_name: name of the view used to reverse the url """""" if cls.scope not in cls.urlpatterns: cls.urlpatterns[cls.scope] = [] cls.urlpatterns[cls.scope].append(url(url_pattern, view, name=view_name)) @classmethod def get_url_patterns(cls): """""" Class method that returns the list of url pattern associated to the current scope. Returns: The list of url patterns associated to the current scope """""" return cls.urlpatterns[cls.scope] " Use fluent interface for DRYer code.,"<?php /** * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since 3.3.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ namespace App; use Cake\Error\Middleware\ErrorHandlerMiddleware; use Cake\Http\BaseApplication; use Cake\Routing\Middleware\AssetMiddleware; use Cake\Routing\Middleware\RoutingMiddleware; /** * Application setup class. * * This defines the bootstrapping logic, and middleware layers you * want to use in your application. */ class Application extends BaseApplication { /** * Setup the middleware your application will use. * * @param \Cake\Http\MiddlewareStack $middleware The middleware stack to setup. * @return \Cake\Http\MiddlewareStack The updated middleware. */ public function middleware($middleware) { $middleware // Catch any exceptions in the lower layers, // and make an error page/response ->push(new ErrorHandlerMiddleware(); // Handle plugin/theme assets like CakePHP normally does. ->push(new AssetMiddleware()) // Apply routing ->push(new RoutingMiddleware()); return $middleware; } } ","<?php /** * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since 3.3.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ namespace App; use Cake\Error\Middleware\ErrorHandlerMiddleware; use Cake\Http\BaseApplication; use Cake\Routing\Middleware\AssetMiddleware; use Cake\Routing\Middleware\RoutingMiddleware; /** * Application setup class. * * This defines the bootstrapping logic, and middleware layers you * want to use in your application. */ class Application extends BaseApplication { /** * Setup the middleware your application will use. * * @param \Cake\Http\MiddlewareStack $middleware The middleware stack to setup. * @return \Cake\Http\MiddlewareStack The updated middleware. */ public function middleware($middleware) { // Catch any exceptions in the lower layers, // and make an error page/response $middleware->push(new ErrorHandlerMiddleware()); // Handle plugin/theme assets like CakePHP normally does. $middleware->push(new AssetMiddleware()); // Apply routing $middleware->push(new RoutingMiddleware()); return $middleware; } } " Remove footer print and make file PEP8 compliant,"from flask.ext.login import current_user from viaduct.models.page import Page, PageRevision from viaduct import db from flask import render_template class PageAPI: @staticmethod def remove_page(path): page = Page.query.filter(Page.path == path).first() if not page: return False for rev in page.revisions.all(): db.session.delete(rev) for perm in page.permissions.all(): db.session.delete(perm) db.session.commit() db.session.delete(page) db.session.commit() return True @staticmethod def get_footer(): footer = Page.query.filter(Page.path == 'footer').first() if not footer: footer = Page('footer') if footer.revisions.count() > 0: revision = footer.revisions.order_by(PageRevision.id.desc()).\ first() exists = True else: revision = PageRevision(footer, current_user, '', '<b> No footer found </b>' '', True) exists = False return render_template('page/get_footer.htm', footer_revision=revision, footer=footer, exists=exists) ","from flask.ext.login import current_user from viaduct.models.page import Page, PagePermission, PageRevision from viaduct import db from flask import request, url_for, render_template from viaduct.models.group import Group class PageAPI: @staticmethod def remove_page(path): page = Page.query.filter(Page.path==path).first() if not page: return False for rev in page.revisions.all(): db.session.delete(rev) for perm in page.permissions.all(): db.session.delete(perm) db.session.commit() db.session.delete(page) db.session.commit() return True @staticmethod def get_footer(): footer = Page.query.filter(Page.path == 'footer').first() if not footer: footer = Page('footer') if footer.revisions.count() > 0: revision = footer.revisions.order_by(PageRevision.id.desc()).first() exists = True else: revision = PageRevision(footer, current_user, '', '<b> No footer found </b>' '', True) exists = False print vars(footer) return render_template('page/get_footer.htm', footer_revision=revision, footer=footer, exists=exists)" Use indirect class alias registration to fix PHP 5.6 behavior,"<?php namespace AmpProject\CompatibilityFix; use AmpProject\CompatibilityFix; /** * Backwards compatibility fix for classes that were moved. * * @package ampproject/amp-toolbox */ final class MovedClasses implements CompatibilityFix { /** * Mapping of aliases to be registered. * * @var array<string, string> Associative array of class alias mappings. */ const ALIASES = [ // v0.9.0 - moving HTML-based utility into a separate `Html` subnamespace. 'AmpProject\AtRule' => 'AmpProject\Html\AtRule', 'AmpProject\Attribute' => 'AmpProject\Html\Attribute', 'AmpProject\LengthUnit' => 'AmpProject\Html\LengthUnit', 'AmpProject\RequestDestination' => 'AmpProject\Html\RequestDestination', 'AmpProject\Role' => 'AmpProject\Html\Role', 'AmpProject\Tag' => 'AmpProject\Html\Tag', // v0.9.0 - Extracting `Encoding` out of `Dom\Document`, as it is turned into AMP value object. 'AmpProject\Dom\Document\Encoding' => 'AmpProject\Encoding', ]; /** * Register the compatibility fix. * * @return void */ public static function register() { spl_autoload_register( static function ($oldClassName) { if (! array_key_exists($oldClassName, self::ALIASES)) { return false; } class_alias(self::ALIASES[$oldClassName], $oldClassName, true); return true; } ); } } ","<?php namespace AmpProject\CompatibilityFix; use AmpProject\CompatibilityFix; /** * Backwards compatibility fix for classes that were moved. * * @package ampproject/amp-toolbox */ final class MovedClasses implements CompatibilityFix { /** * Mapping of aliases to be registered. * * @var array<string, string> Associative array of class alias mappings. */ const ALIASES = [ // v0.9.0 - moving HTML-based utility into a separate `Html` subnamespace. 'AmpProject\AtRule' => 'AmpProject\Html\AtRule', 'AmpProject\Attribute' => 'AmpProject\Html\Attribute', 'AmpProject\LengthUnit' => 'AmpProject\Html\LengthUnit', 'AmpProject\RequestDestination' => 'AmpProject\Html\RequestDestination', 'AmpProject\Role' => 'AmpProject\Html\Role', 'AmpProject\Tag' => 'AmpProject\Html\Tag', // v0.9.0 - Extracting `Encoding` out of `Dom\Document`, as it is turned into AMP value object. 'AmpProject\Dom\Document\Encoding' => 'AmpProject\Encoding', ]; /** * Register the compatibility fix. * * @return void */ public static function register() { foreach (self::ALIASES as $old => $new) { if (class_exists($old)) { continue; } class_alias($new, $old, true); } } } " Fix variable names in Related,"from .exceptions import ApiError # ----------------------------------------------------------------------------- class Related(object): def __init__(self, item_class=None, **kwargs): self._item_class = item_class self._resolvers = kwargs def resolve_related(self, data): for field_name, resolver in self._resolvers.items(): value = data.get(field_name, None) if value is None: # If this field were required or non-nullable, the deserializer # would already have raised an exception. continue try: resolved = self.resolve_field(value, resolver) except ApiError as e: pointer = '/data/{}'.format(field_name) raise e.update({'source': {'pointer': pointer}}) data[field_name] = resolved if self._item_class: return self._item_class(**data) return data def resolve_field(self, value, resolver): # marshmallow always uses lists here. many = isinstance(value, list) if many and not value: # As a tiny optimization, there's no need to resolve an empty list. return value if isinstance(resolver, Related): resolve_item = resolver.resolve_related else: resolve_item = resolver().resolve_related_item if many: return [resolve_item(item) for item in value] return resolve_item(value) ","from .exceptions import ApiError # ----------------------------------------------------------------------------- class Related(object): def __init__(self, item_class=None, **kwargs): self._item_class = item_class self._view_classes = kwargs def resolve_related(self, data): for field_name, view_class in self._view_classes.items(): value = data.get(field_name, None) if value is None: # If this field were required or non-nullable, the deserializer # would already have raised an exception. continue try: resolved = self.resolve_field(value, view_class) except ApiError as e: pointer = '/data/{}'.format(field_name) raise e.update({'source': {'pointer': pointer}}) data[field_name] = resolved if self._item_class: return self._item_class(**data) return data def resolve_field(self, value, view_class): # marshmallow always uses lists here. many = isinstance(value, list) if many and not value: # As a tiny optimization, there's no need to resolve an empty list. return value if isinstance(view_class, Related): # This is not actually a view class. resolver = view_class.resolve_related else: resolver = view_class().resolve_related_item if many: return [resolver(item) for item in value] return resolver(value) " Move pyclamav import inside of clean method on RWValidatedFileField so that it doesn't get imported by streamscript or unless as needed for field validation,"from django.forms import forms from south.modelsinspector import add_introspection_rules from validatedfile.fields import ValidatedFileField class RWValidatedFileField(ValidatedFileField): """""" Same as FileField, but you can specify: * content_types - list containing allowed content_types. Example: ['application/pdf', 'image/jpeg'] """""" def __init__(self, content_types=None, **kwargs): if content_types: self.content_types = content_types super(RWValidatedFileField, self).__init__(**kwargs) def clean(self, *args, **kwargs): # ValidatedFileField.clean will check the MIME type from the # http headers and by peeking in the file data = super(RWValidatedFileField, self).clean(*args, **kwargs) file = data.file # next scan with pyclamav tmpfile = file.file.name import pyclamav has_virus, virus_name = pyclamav.scanfile(tmpfile) if has_virus: fn = file.name raise forms.ValidationError( 'The file %s you uploaded appears to contain a virus or be' 'malware (%s).' % (fn, virus_name) ) return data add_introspection_rules([], [""^roundware\.rw\.fields\.RWValidatedFileField""]) ","from django.forms import forms from south.modelsinspector import add_introspection_rules from validatedfile.fields import ValidatedFileField import pyclamav class RWValidatedFileField(ValidatedFileField): """""" Same as FileField, but you can specify: * content_types - list containing allowed content_types. Example: ['application/pdf', 'image/jpeg'] """""" def __init__(self, content_types=None, **kwargs): if content_types: self.content_types = content_types super(RWValidatedFileField, self).__init__(**kwargs) def clean(self, *args, **kwargs): # ValidatedFileField.clean will check the MIME type from the # http headers and by peeking in the file data = super(RWValidatedFileField, self).clean(*args, **kwargs) file = data.file # next scan with pyclamav tmpfile = file.file.name has_virus, virus_name = pyclamav.scanfile(tmpfile) if has_virus: fn = file.name raise forms.ValidationError( 'The file %s you uploaded appears to contain a virus or be' 'malware (%s).' % (fn, virus_name) ) return data add_introspection_rules([], [""^roundware\.rw\.fields\.RWValidatedFileField""]) " Fix encoding of callsign and player name in URL,"'use strict'; var _ = require('lodash'); var XpItem = require('../models/xpItem'); module.exports = { set: function (exportString) { document.location.hash = exportString; }, get: function () { var hash = document.location.hash; var exportString = hash.replace('#', ''); return exportString; }, clear: function () { document.location.hash = ''; }, generateExportString: function (build) { var itemExports = _.map(build.xpHistory, function (xpItem) { return xpItem.exportString(); }); // add callsign and playername as first items itemExports.unshift(window.encodeURIComponent(build.callsign)); itemExports.unshift(window.encodeURIComponent(build.playerName)); var exportString = '/v1/' + itemExports.join(','); return exportString; }, parseExportStringToHistory: function (exportString) { var splitParts = exportString.split('/'); var items = splitParts[2]; var splitItems = items.split(','); var playerName = window.decodeURIComponent(splitItems.shift()); var callsign = window.decodeURIComponent(splitItems.shift()); var xpHistory = _.map(splitItems, function (stringItem) { var xpItem = new XpItem(); xpItem.parseExportString(stringItem); return xpItem; }); return { xpHistory: xpHistory, callsign: callsign, playerName: playerName }; } }; ","'use strict'; var _ = require('lodash'); var XpItem = require('../models/xpItem'); module.exports = { set: function (exportString) { document.location.hash = exportString; }, get: function () { var hash = document.location.hash; var exportString = hash.replace('#', ''); return exportString; }, clear: function () { document.location.hash = ''; }, generateExportString: function (build) { var itemExports = _.map(build.xpHistory, function (xpItem) { return xpItem.exportString(); }); // add callsign and playername as first items itemExports.unshift(build.callsign); itemExports.unshift(build.playerName); var exportString = '/v1/' + itemExports.join(','); return exportString; }, parseExportStringToHistory: function (exportString) { var splitParts = exportString.split('/'); var items = splitParts[2]; var splitItems = items.split(','); var playerName = splitItems.shift(); var callsign = splitItems.shift(); var xpHistory = _.map(splitItems, function (stringItem) { var xpItem = new XpItem(); xpItem.parseExportString(stringItem); return xpItem; }); return { xpHistory: xpHistory, callsign: callsign, playerName: playerName }; } }; " Change commit to apply (SharedPreferences),"package hrv.band.aurora.view.fragment; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import hrv.band.aurora.R; /** * Created by Julian on 15.11.2016. */ public class DisclaimerDialogFragment extends DialogFragment { public static final String DISCLAIMER_AGREEMENT = ""DisclaimerAgreementAccepted""; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.disclaimer) .setMessage(R.string.disclaimerText) .setPositiveButton(R.string.agree, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()); SharedPreferences.Editor prefsEditor = mPrefs.edit(); prefsEditor.putBoolean(DISCLAIMER_AGREEMENT, true); prefsEditor.apply(); } }) .setNegativeButton(R.string.disagree, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { System.exit(0); } }); return builder.create(); } } ","package hrv.band.aurora.view.fragment; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import hrv.band.aurora.R; /** * Created by Julian on 15.11.2016. */ public class DisclaimerDialogFragment extends DialogFragment { public static final String DISCLAIMER_AGREEMENT = ""DisclaimerAgreementAccepted""; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.disclaimer) .setMessage(R.string.disclaimerText) .setPositiveButton(R.string.agree, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()); SharedPreferences.Editor prefsEditor = mPrefs.edit(); prefsEditor.putBoolean(DISCLAIMER_AGREEMENT, true); prefsEditor.commit(); } }) .setNegativeButton(R.string.disagree, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { System.exit(0); } }); return builder.create(); } } " Add test for (unimplemented) /rpc route,"import chai, {expect} from 'chai'; import createApp from '../../src/app'; import dbFixtures from '../utils/dbFixtures'; describe('App', function() { before(async function() { this.timeout(60000); await dbFixtures.setup(); }); after(async function() { await dbFixtures.teardown(); }); it('factory (createApp) should be a function', function() { expect(createApp).to.exist .and.to.be.a('function'); }); describe('instance', function() { let app; before(function() { app = createApp({connectionString: dbFixtures.connectionString, schema: 'public'}); }); it('should respond to HTTP requests', async function() { await chai.request(app) .get('/'); }); it('should respond with success to ""GET /""', async function() { const res = await chai.request(app) .get('/'); res.should.have.status(200); }); describe('/rpc', function() { // TODO: implement rpc routes. In the mean time let's check that they're reserved. it('should not allow requests while feature is not implemented', async function() { await chai.request(app) .get('/rpc') .should.eventually.be.rejected; await chai.request(app) .get('/rpc/whatever') .should.eventually.be.rejected; }); }); }); describe('instance with bad connection string', function() { let app; before(function() { app = createApp({connectionString: 'postgres://nosuchhost', schema: 'public'}); }); it('should respond to GET / with failure', function() { return chai.request(app) .get('/') .should.eventually.be.rejected; }); }); }); ","import chai, {expect} from 'chai'; import createApp from '../../src/app'; import dbFixtures from '../utils/dbFixtures'; describe('App', function() { before(async function() { this.timeout(60000); await dbFixtures.setup(); }); after(async function() { await dbFixtures.teardown(); }); it('factory (createApp) should be a function', function() { expect(createApp).to.exist .and.to.be.a('function'); }); describe('instance', function() { let app; before(function() { app = createApp({connectionString: dbFixtures.connectionString, schema: 'public'}); }); it('should respond to HTTP requests', async function() { await chai.request(app) .get('/'); }); it('should respond with success to ""GET /""', async function() { const res = await chai.request(app) .get('/'); res.should.have.status(200); }); }); describe('instance with bad connection string', function() { let app; before(function() { app = createApp({connectionString: 'postgres://nosuchhost', schema: 'public'}); }); it('should respond to GET / with failure', function() { return chai.request(app) .get('/') .should.eventually.be.rejected; }); }); }); " Use BaseModel.create to create a test user,"from tests.app_tests import BaseTestCase from app.mod_auth.models import * from app.mod_auth.views import user_is_logged_in from flask import url_for USERNAME = 'username' PASSWORD = 'password' INVALID_USERNAME = 'wrong_username' INVALID_PASSWORD = 'wrong_password' class TestAuth(BaseTestCase): def setUp(self): super().setUp() User.create(username=USERNAME, password=PASSWORD) def login(self, username, password): return self.client.post(url_for('auth.login'), data=dict( username=username, password=password ), follow_redirects=True) def logout(self): return self.client.get(url_for('auth.logout', follow_redirects=True)) def test_login(self): with self.client: self.login(INVALID_USERNAME, PASSWORD) self.assertFalse(user_is_logged_in()) self.login(USERNAME, INVALID_PASSWORD) self.assertFalse(user_is_logged_in()) self.login(INVALID_USERNAME, INVALID_PASSWORD) self.assertFalse(user_is_logged_in()) self.login(USERNAME, PASSWORD) self.assertTrue(user_is_logged_in()) def test_logout(self): with self.client: self.login(USERNAME, PASSWORD) self.assertTrue(user_is_logged_in()) self.logout() self.assertFalse(user_is_logged_in()) ","from tests.app_tests import BaseTestCase from app.mod_auth.models import * from app.mod_auth.views import user_is_logged_in from flask import url_for USERNAME = 'username' PASSWORD = 'password' INVALID_USERNAME = 'wrong_username' INVALID_PASSWORD = 'wrong_password' class TestAuth(BaseTestCase): def setUp(self): super().setUp() user = User(username=USERNAME, password=PASSWORD) db.session.add(user) db.session.commit() def login(self, username, password): return self.client.post(url_for('auth.login'), data=dict( username=username, password=password ), follow_redirects=True) def logout(self): return self.client.get(url_for('auth.logout', follow_redirects=True)) def test_login(self): with self.client: self.login(INVALID_USERNAME, PASSWORD) self.assertFalse(user_is_logged_in()) self.login(USERNAME, INVALID_PASSWORD) self.assertFalse(user_is_logged_in()) self.login(INVALID_USERNAME, INVALID_PASSWORD) self.assertFalse(user_is_logged_in()) self.login(USERNAME, PASSWORD) self.assertTrue(user_is_logged_in()) def test_logout(self): with self.client: self.login(USERNAME, PASSWORD) self.assertTrue(user_is_logged_in()) self.logout() self.assertFalse(user_is_logged_in()) " Remove anonymous flag to force user to enter name,"(function() { // Creates an iframe with an embedded HipChat conversation window. // // Options: // url - The url to the room to embed; required // el - The container in which to insert the HipChat panel; required // timezone - The timezone to use in the embedded room; required // width - The width of the iframe; defaults to 100% // height - The height of the iframe; defaults to 400px var parametize = function(params) { var key, toks = []; for (key in params) { toks.push(key + '=' + params[key]); } return toks.join('&'); }; return this.HipChat = function(options) { if (options && options.url && options.el && options.timezone) { var el = document.querySelector(options.el); if (!el) return; var params = { timezone: options.timezone, minimal: true }; var url = options.url + (options.url.indexOf('?') > 0 ? '&' : '?') + parametize(params); if (url.indexOf('https://') !== 0) { url = 'https://' + url; } var w = options.width || '100%'; var h = options.height || 600; el.innerHTML = '<iframe src=""' + url + '"" frameborder=""' + 0 + '"" width=""' + w + '"" height=""' + h + '""></iframe>'; } }; })(); ","(function() { // Creates an iframe with an embedded HipChat conversation window. // // Options: // url - The url to the room to embed; required // el - The container in which to insert the HipChat panel; required // timezone - The timezone to use in the embedded room; required // width - The width of the iframe; defaults to 100% // height - The height of the iframe; defaults to 400px var parametize = function(params) { var key, toks = []; for (key in params) { toks.push(key + '=' + params[key]); } return toks.join('&'); }; return this.HipChat = function(options) { if (options && options.url && options.el && options.timezone) { var el = document.querySelector(options.el); if (!el) return; var params = { anonymous: false, timezone: options.timezone, minimal: true }; var url = options.url + (options.url.indexOf('?') > 0 ? '&' : '?') + parametize(params); if (url.indexOf('https://') !== 0) { url = 'https://' + url; } var w = options.width || '100%'; var h = options.height || 600; el.innerHTML = '<iframe src=""' + url + '"" frameborder=""' + 0 + '"" width=""' + w + '"" height=""' + h + '""></iframe>'; } }; })(); " Set instance config null by default,"<?php return array( 'table' => '', 'instance' => '', 'create' => function($system, $resource, $entity, $type) { $company_id = null; $representative_id = null; // Not the best code in the world. $class = explode('\\', get_class($this->resource)); switch(end($class)) { case 'Erp': $erp_id = $resource->id; break; case 'Company': $company_id = $resource->id; $erp_id = $resource->erp->id; break; case 'Representative': $representative_id = $resource->id; $company_id = $resource->company->id; $erp_id = $resource->company->erp->id; break; } return array( 'erp_id' => $erp_id, 'company_id' => $company_id, 'representative_id' => $representative_id, 'entity' => $entity, 'type' => $type, 'class' => get_class($system), 'status' => 'processing', ); }, );","<?php return array( 'table' => '', 'instance' => 'Algorit\Synchronizer\Storage\SyncInterface', 'create' => function($system, $resource, $entity, $type) { $company_id = null; $representative_id = null; // Not the best code in the world. $class = explode('\\', get_class($this->resource)); switch(end($class)) { case 'Erp': $erp_id = $resource->id; break; case 'Company': $company_id = $resource->id; $erp_id = $resource->erp->id; break; case 'Representative': $representative_id = $resource->id; $company_id = $resource->company->id; $erp_id = $resource->company->erp->id; break; } return array( 'erp_id' => $erp_id, 'company_id' => $company_id, 'representative_id' => $representative_id, 'entity' => $entity, 'type' => $type, 'class' => get_class($system), 'status' => 'processing', ); }, );" Fix countdown time sudden change during board updates,"package xyz.upperlevel.uppercore.task; import lombok.Getter; import org.bukkit.scheduler.BukkitRunnable; import xyz.upperlevel.uppercore.Uppercore; import java.text.SimpleDateFormat; import java.util.Date; import java.util.function.Consumer; public abstract class Countdown extends BukkitRunnable { @Getter private final long startAt, repeatEach; @Getter private long currentTick; public Countdown(long startAt, long repeatEach) { this.startAt = startAt; this.repeatEach = repeatEach; } public void start() { currentTick = startAt + repeatEach; runTaskTimer(Uppercore.plugin(), 0, repeatEach); } public long getTime() { return currentTick / repeatEach; } protected abstract void onTick(long time); protected abstract void onEnd(); @Override public void run() { currentTick -= repeatEach; if (currentTick == 0) { onEnd(); super.cancel(); } else { onTick(currentTick / repeatEach); } } public String toString(String pattern) { return new SimpleDateFormat(pattern).format(new Date(currentTick * 50)); } public static Countdown create(long startAt, long repeatEach, Consumer<Long> onTick, Runnable onEnd) { return new Countdown(startAt, repeatEach) { @Override protected void onTick(long tick) { onTick.accept(tick); } @Override protected void onEnd() { onEnd.run(); } }; } } ","package xyz.upperlevel.uppercore.task; import lombok.Getter; import org.bukkit.scheduler.BukkitRunnable; import xyz.upperlevel.uppercore.Uppercore; import java.text.SimpleDateFormat; import java.util.Date; import java.util.function.Consumer; public abstract class Countdown extends BukkitRunnable { @Getter private final long startAt, repeatEach; @Getter private long currentTick; public Countdown(long startAt, long repeatEach) { this.startAt = startAt; this.repeatEach = repeatEach; } public void start() { currentTick = startAt; runTaskTimer(Uppercore.plugin(), 0, repeatEach); } public long getTime() { return currentTick / repeatEach; } protected abstract void onTick(long time); protected abstract void onEnd(); @Override public void run() { onTick(currentTick / repeatEach); if (currentTick > 0) currentTick -= repeatEach; else { onEnd(); super.cancel(); } } public String toString(String pattern) { return new SimpleDateFormat(pattern).format(new Date(currentTick * 50)); } public static Countdown create(long startAt, long repeatEach, Consumer<Long> onTick, Runnable onEnd) { return new Countdown(startAt, repeatEach) { @Override protected void onTick(long tick) { onTick.accept(tick); } @Override protected void onEnd() { onEnd.run(); } }; } } " Allow passing of constructor arguments on make method helper.,"<?php namespace Yajra\DataTables\Html; use BadMethodCallException; use Yajra\DataTables\Contracts\DataTableHtmlBuilder; /** * @mixin Builder */ abstract class DataTableHtml implements DataTableHtmlBuilder { /** * @var \Yajra\DataTables\Html\Builder */ protected $htmlBuilder; /** * @return \Yajra\DataTables\Html\Builder */ public static function make() { if (func_get_args()) { return (new static(...func_get_args()))->handle(); } return app(static::class)->handle(); } /** * @param string $name * @param mixed $arguments * @return mixed * @throws \Exception */ public function __call($name, $arguments) { if (method_exists($this->getHtmlBuilder(), $name)) { return $this->getHtmlBuilder()->{$name}(...$arguments); } throw new BadMethodCallException(""Method {$name} does not exists""); } /** * @return \Yajra\DataTables\Html\Builder */ protected function getHtmlBuilder() { if ($this->htmlBuilder) { return $this->htmlBuilder; } return $this->htmlBuilder = app(Builder::class); } /** * @param mixed $builder * @return static */ public function setHtmlBuilder($builder) { $this->htmlBuilder = $builder; return $this; } } ","<?php namespace Yajra\DataTables\Html; use BadMethodCallException; use Yajra\DataTables\Contracts\DataTableHtmlBuilder; /** * @mixin Builder */ abstract class DataTableHtml implements DataTableHtmlBuilder { /** * @var \Yajra\DataTables\Html\Builder */ protected $htmlBuilder; /** * @return \Yajra\DataTables\Html\Builder */ public static function make() { return app(static::class)->handle(); } /** * @param string $name * @param mixed $arguments * @return mixed * @throws \Exception */ public function __call($name, $arguments) { if (method_exists($this->getHtmlBuilder(), $name)) { return $this->getHtmlBuilder()->{$name}(...$arguments); } throw new BadMethodCallException(""Method {$name} does not exists""); } /** * @return \Yajra\DataTables\Html\Builder */ protected function getHtmlBuilder() { if ($this->htmlBuilder) { return $this->htmlBuilder; } return $this->htmlBuilder = app(Builder::class); } /** * @param mixed $builder * @return static */ public function setHtmlBuilder($builder) { $this->htmlBuilder = $builder; return $this; } } " Fix parser test compile errors,"package schema import ""testing"" func TestParse(t *testing.T) { text := ` package users from locale import Location // this is a comment // This is also a comment // This is one too type User { // version comment version 1 { required string uuid required string username optional uint8 age } // 11/15/14 version 2 { optional Location location } } ` pkgList := NewPackageList() config := Config{} // create parser parser := NewParser(pkgList, config) pkg, err := parser.Parse(""TestParse"", text) t.Logf(""%#v\n"", pkg) t.Log(err) } func BenchmarkParse(b *testing.B) { text := ` package users from locale import Location // This is one too type User { // version comment version 1 { required string uuid required string username optional uint8 age } // 11/15/14 version 2 { optional Location location } } ` pkgList := NewPackageList() config := Config{} // create parser parser := NewParser(pkgList, config) for i := 0; i < b.N; i++ { parser.Parse(""TestParse"", text) } // t.Logf(""%#v\n"", pkg) // t.Log(err) } ","package schema import ""testing"" func TestParse(t *testing.T) { text := ` package users from locale import Location // this is a comment // This is also a comment // This is one too type User { // version comment version 1 { required string uuid required string username optional uint8 age } // 11/15/14 version 2 { optional Location location } } ` pkgList := NewPackageList() config := Config{} // create parser parser := NewParser(pkgList, config) pkg, err := parser.Parse(""TestParse"", text) // t.Logf(""%#v\n"", pkg) // t.Log(err) } func BenchmarkParse(b *testing.B) { text := ` package users from locale import Location // This is one too type User { // version comment version 1 { required string uuid required string username optional uint8 age } // 11/15/14 version 2 { optional Location location } } ` pkgList := NewPackageList() config := Config{} // create parser parser := NewParser(pkgList, config) for i := 0; i < b.N; i++ { parser.Parse(""TestParse"", text) } // t.Logf(""%#v\n"", pkg) // t.Log(err) } " "Add jshint and grunt-complexity to the test task Signed-off-by: Henrique Vicente <d390f26e2f50ad5716a9c69c58de1f5df9730e3b@gmail.com>","/* * grunt-config-options * https://github.com/henvic/grunt-cli-config * * Copyright (c) 2014 Henrique Vicente * Licensed under the MIT license. */ 'use strict'; module.exports = function exports(grunt) { grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', '<%= nodeunit.tests %>' ], options: { jshintrc: '.jshintrc' } }, nodeunit: { tests: ['test/*_test.js'] }, complexity: { generic: { src: ['Gruntfile.js', 'tasks/config_options.js'], options: { breakOnErrors: true, errorsOnly: false, cyclomatic: 3, halstead: 8, maintainability: 70, hideComplexFunctions: false } } } }); grunt.loadTasks('tasks'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.loadNpmTasks('grunt-complexity'); grunt.registerTask('test', ['jshint', 'nodeunit', 'complexity']); grunt.registerTask('default', ['test']); }; ","/* * grunt-config-options * https://github.com/henvic/grunt-cli-config * * Copyright (c) 2014 Henrique Vicente * Licensed under the MIT license. */ 'use strict'; module.exports = function exports(grunt) { grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', '<%= nodeunit.tests %>' ], options: { jshintrc: '.jshintrc' } }, nodeunit: { tests: ['test/*_test.js'] }, complexity: { generic: { src: ['Gruntfile.js', 'tasks/config_options.js'], options: { breakOnErrors: true, errorsOnly: false, cyclomatic: 3, halstead: 8, maintainability: 70, hideComplexFunctions: false } } } }); grunt.loadTasks('tasks'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.loadNpmTasks('grunt-complexity'); grunt.registerTask('test', ['nodeunit']); grunt.registerTask('default', ['jshint', 'test', 'complexity']); }; " Add explanation for background component,"var classnames = require('classnames'); var React = require('react/addons'); module.exports = React.createClass({ displayName: 'BackgroundPanel', propTypes: { backgroundSize: React.PropTypes.oneOf(['contain', 'auto']), backgroundRepeat: React.PropTypes.oneOf(['no-repeat']), backgroundPosition: React.PropTypes.string, backgroundImage: React.PropTypes.string.isRequired, opacity: React.PropTypes.number, }, getDefaultProps: function () { return { backgroundSize: 'auto', backgroundRepeat: 'no-repeat', backgroundPosition: ""50% 50%"", opacity: 1, }; }, render: function () { // would normally use a ::before pseudo element // http://stackoverflow.com/a/13509036 // 'react way' described here: // http://stackoverflow.com/a/28269950 var before = <span style={{ content: """", position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, zIndex: 1, backgroundImage: this.props.backgroundImage, opacity: this.props.opacity, backgroundPosition: this.props.backgroundPosition, backgroundSize: this.props.backgroundSize, backgroundRepeat: this.props.backgroundRepeat, }}/> return <div style={{ width: ""100%"", minHeight: ""auto"", height: ""auto"", }}> {before} {this.props.children} </div> } }); ","var classnames = require('classnames'); var React = require('react/addons'); module.exports = React.createClass({ displayName: 'BackgroundPanel', propTypes: { backgroundSize: React.PropTypes.oneOf(['contain', 'auto']), backgroundRepeat: React.PropTypes.oneOf(['no-repeat']), backgroundPosition: React.PropTypes.string, backgroundImage: React.PropTypes.string.isRequired, opacity: React.PropTypes.number, }, getDefaultProps: function () { return { backgroundSize: 'auto', backgroundRepeat: 'no-repeat', backgroundPosition: ""50% 50%"", opacity: 1, }; }, render: function () { var before = <span style={{ content: """", position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, zIndex: 1, backgroundImage: this.props.backgroundImage, opacity: this.props.opacity, backgroundPosition: this.props.backgroundPosition, backgroundSize: this.props.backgroundSize, backgroundRepeat: this.props.backgroundRepeat, }}/> return <div style={{ width: ""100%"", minHeight: ""auto"", height: ""auto"", }}> {before} {this.props.children} </div> } }); " Return office data in json form.,"<?php use LinusShops\CanadaPost\Services\GetNearestPostOffice; /** * Index Controller * */ class Linus_CanadaPost_OfficeController extends Mage_Core_Controller_Front_Action { /** * Get the list of nearest post offices */ public function nearestAction() { $common = Mage::helper('linus_common/request'); //Require: Postal code $postalCode = $this->getRequest()->get('postal_code'); $city = $this->getRequest()->get('city'); $province = $this->getRequest()->get('province'); if (in_array(null, array($postalCode, $city, $province))) { $msg = ''; if ($postalCode == null) { $msg .= 'postal code '; } if ($city == null) { $msg .= 'city '; } if ($province == null) { $msg .= 'province '; } $common->sendResponseJson(array(), 'Missing required fields: '.$msg); return; } $offices = Mage::helper('linus_canadapost')->getNearbyPostOffices( $postalCode, $city, $province ); $common->sendResponseJson($offices); } } ","<?php use LinusShops\CanadaPost\Services\GetNearestPostOffice; /** * Index Controller * */ class Linus_CanadaPost_OfficeController extends Mage_Core_Controller_Front_Action { /** * Get the list of nearest post offices */ public function nearestAction() { $common = Mage::helper('linus_common/request'); //Require: Postal code $postalCode = $this->getRequest()->get('postal_code'); $city = $this->getRequest()->get('city'); $province = $this->getRequest()->get('province'); if (in_array(null, array($postalCode, $city, $province))) { $msg = ''; if ($postalCode == null) { $msg .= 'postal code '; } if ($city == null) { $msg .= 'city '; } if ($province == null) { $msg .= 'province '; } $common->sendResponseJson(array(), 'Missing required fields: '.$msg); return; } $offices = Mage::helper('linus_canadapost')->getNearbyPostOffices( $postalCode, $city, $province ); } } " Add Changhong to list of manufacturers,"<?php namespace WhichBrowser\Data; Manufacturers::$GENERIC = [ 'LG Electronics' => 'LG', 'LGE' => 'LG', 'TOSHIBA' => 'Toshiba', 'SAMSUNG' => 'Samsung', 'SHARP' => 'Sharp', 'SONY' => 'Sony', ]; Manufacturers::$TELEVISION = [ 'BANGOLUFSEN' => 'Bang & Olufsen', 'CHANGHONG' => 'Changhong', 'changhong' => 'Changhong', 'HYUNDAI' => 'Hyundai', 'inverto' => 'Inverto', 'LOEWE' => 'Loewe', 'MEDION' => 'Medion', 'Sagemcom_Broadband_SAS' => 'Sagemcom', 'SERAPHIC' => 'Seraphic', 'selevision' => 'Selevision', 'smart' => 'Smart', 'Sky_worth' => 'Skyworth', 'TELEFUNKEN' => 'Telefunken', 'THOM' => 'Thomson', 'THOMSON' => 'Thomson', 'tv2n' => 'TV2N', 'VESTEL' => 'Vestel' ]; ","<?php namespace WhichBrowser\Data; Manufacturers::$GENERIC = [ 'LG Electronics' => 'LG', 'LGE' => 'LG', 'TOSHIBA' => 'Toshiba', 'SAMSUNG' => 'Samsung', 'SHARP' => 'Sharp', 'SONY' => 'Sony', ]; Manufacturers::$TELEVISION = [ 'BANGOLUFSEN' => 'Bang & Olufsen', 'CHANGHONG' => 'Changhong', 'HYUNDAI' => 'Hyundai', 'inverto' => 'Inverto', 'LOEWE' => 'Loewe', 'MEDION' => 'Medion', 'Sagemcom_Broadband_SAS' => 'Sagemcom', 'SERAPHIC' => 'Seraphic', 'selevision' => 'Selevision', 'smart' => 'Smart', 'Sky_worth' => 'Skyworth', 'TELEFUNKEN' => 'Telefunken', 'THOM' => 'Thomson', 'THOMSON' => 'Thomson', 'tv2n' => 'TV2N', 'VESTEL' => 'Vestel' ]; " Allow partial definition of the configuration,"<?php namespace photon\auth; use \photon\config\Container as Conf; class MongoDBBackend { private static $defaultConfig = array( 'user_class' => '\photon\auth\MongoDBUser', 'user_id' => 'login', 'user_password' => 'password', ); /** * Load the user from the database * * @param $user_id The unique user id */ public static function loadUser($user_id) { if ($user_id === null) { return false; } try { $user_id = trim($user_id); $config = Conf::f('auth_mongodb', self::$defaultConfig); $config = array_merge($config, self::$defaultConfig); $class = $config['user_class']; $user = new $class(array($config['user_id'] => $user_id)); } catch(\Exception $e) { return false; } return $user; } /** * Authenticate a existing user * * @param $user_id The unique user id * @return object The user object, * false if the user do not exists or the password is invalid */ public static function authenticate($auth) { $config = Conf::f('auth_mongodb', self::$defaultConfig); $config = array_merge($config, self::$defaultConfig); $user = self::loadUser($auth[$config['user_id']]); if (false === $user) { return false; } if ($user->verifyPassword($auth[$config['user_password']]) === false) { return false; } return $user; } } ","<?php namespace photon\auth; use \photon\config\Container as Conf; class MongoDBBackend { private static $defaultConfig = array( 'user_class' => '\photon\auth\MongoDBUser', 'user_id' => 'login', 'user_password' => 'password', ); /** * Load the user from the database * * @param $user_id The unique user id */ public static function loadUser($user_id) { if ($user_id === null) { return false; } try { $user_id = trim($user_id); $config = Conf::f('auth_mongodb', self::$defaultConfig); $class = $config['user_class']; $user = new $class(array($config['user_id'] => $user_id)); } catch(\Exception $e) { return false; } return $user; } /** * Authenticate a existing user * * @param $user_id The unique user id * @return object The user object, * false if the user do not exists or the password is invalid */ public static function authenticate($auth) { $config = Conf::f('auth_mongodb', self::$defaultConfig); $user = self::loadUser($auth[$config['user_id']]); if (false === $user) { return false; } if ($user->verifyPassword($auth[$config['user_password']]) === false) { return false; } return $user; } } " Check return value of read operation,"package org.helioviewer.jhv.view.jp2view.io; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; import javax.annotation.Nonnull; public class ByteChannelInputStream extends InputStream { private final ByteBuffer buf = ByteBuffer.allocateDirect(512 * 1024); private final ByteChannel chan; public ByteChannelInputStream(ByteChannel _chan) { chan = _chan; } @Override public int read() throws IOException { ensure(1); return (buf.get() + 256) & 0xFF; } @Override public int read(@Nonnull byte[] bytes, int off, int len) throws IOException { ensure(len); buf.get(bytes, off, len); return len; } @Override public int read(@Nonnull byte[] b) throws IOException { return read(b, 0, b.length); } private void ensure(int len) throws IOException { if (buf.remaining() < len) { buf.compact(); buf.flip(); int n; do { buf.position(buf.limit()); buf.limit(buf.capacity()); n = chan.read(buf); buf.flip(); } while (n >= 0 && buf.remaining() < len); } } } ","package org.helioviewer.jhv.view.jp2view.io; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; import javax.annotation.Nonnull; public class ByteChannelInputStream extends InputStream { private final ByteBuffer buf = ByteBuffer.allocateDirect(512 * 1024); private final ByteChannel chan; public ByteChannelInputStream(ByteChannel _chan) { chan = _chan; } @Override public int read() throws IOException { ensure(1); return (buf.get() + 256) & 0xFF; } @Override public int read(@Nonnull byte[] bytes, int off, int len) throws IOException { ensure(len); buf.get(bytes, off, len); return len; } @Override public int read(@Nonnull byte[] b) throws IOException { return read(b, 0, b.length); } private void ensure(int len) throws IOException { if (buf.remaining() < len) { buf.compact(); buf.flip(); do { buf.position(buf.limit()); buf.limit(buf.capacity()); chan.read(buf); buf.flip(); } while (buf.remaining() < len); } } } " Update parameters for deleting projects,"<?php namespace AppBundle\API\Delete; use AppBundle\AppBundle; use AppBundle\Entity\WebuserData; use AppBundle\Entity\FennecUser; use AppBundle\Service\DBVersion; /** * Web Service. * Delete Project with given internal_ids from the database (user has to be logged in and owner) */ class Projects { const ERROR_NOT_LOGGED_IN = ""Error. You are not logged in.""; private $manager; /** * Projects constructor. * @param $dbversion */ public function __construct(DBVersion $dbversion) { $this->manager = $dbversion->getEntityManager(); } /** * @inheritdoc * <code> * array('dbversion'=>$dbversion, 'ids'=>array($id1, $id2)); * </code> * @returns array $result * <code> * array(array('project_id','import_date','OTUs','sample size')); * </code> */ public function execute(FennecUser $user = null, $projectId) { $result = array('deletedProjects' => 0); if ($user === null) { $result['error'] = Projects::ERROR_NOT_LOGGED_IN; } else { $projects = $this->manager->getRepository(WebuserData::class)->findOneBy(array('webuser' => $user, 'webuserDataId' => $projectId)); $this->manager->remove($projects); $this->manager->flush(); $result['deletedProjects'] = 1; } return $result; } } ","<?php namespace AppBundle\API\Delete; use AppBundle\AppBundle; use AppBundle\Entity\WebuserData; use AppBundle\Entity\FennecUser; use AppBundle\Service\DBVersion; /** * Web Service. * Delete Project with given internal_ids from the database (user has to be logged in and owner) */ class Projects { const ERROR_NOT_LOGGED_IN = ""Error. You are not logged in.""; private $manager; /** * Projects constructor. * @param $dbversion */ public function __construct(DBVersion $dbversion) { $this->manager = $dbversion->getEntityManager(); } /** * @inheritdoc * <code> * array('dbversion'=>$dbversion, 'ids'=>array($id1, $id2)); * </code> * @returns array $result * <code> * array(array('project_id','import_date','OTUs','sample size')); * </code> */ public function execute(FennecUser $user = null) { $projectId = $_REQUEST['ids']; $result = array('deletedProjects' => 0); if ($user === null) { $result['error'] = Projects::ERROR_NOT_LOGGED_IN; } else { $projects = $this->manager->getRepository(WebuserData::class)->findOneBy(array('webuser' => $user, 'webuserDataId' => $projectId)); $this->manager->remove($projects); $this->manager->flush(); $result['deletedProjects'] = 1; } return $result; } } " Fix CLI api (was missing entrypoint hook),"from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from algorithm import Algorithm def main(): Server().main() class Server(object): def __init__(self, argv=None): self.argv = argv def get_algorithm(self): return Algorithm('aspen.algorithms.server') def get_website(self): """"""Return a website object. Useful in testing. """""" algorithm = self.get_algorithm() algorithm.run(argv=self.argv, _through='get_website_from_argv') return algorithm.state['website'] def main(self, argv=None): """"""http://aspen.io/cli/ """""" try: argv = argv if argv is not None else self.argv algorithm = self.get_algorithm() algorithm.run(argv=argv) except (SystemExit, KeyboardInterrupt): # Under some (most?) network engines, a SIGINT will be trapped by the # SIGINT signal handler above. However, gevent does ""something"" with # signals and our signal handler never fires. However, we *do* get a # KeyboardInterrupt here in that case. *shrug* # # See: https://github.com/gittip/aspen-python/issues/196 pass except: import aspen, traceback aspen.log_dammit(""Oh no! Aspen crashed!"") aspen.log_dammit(traceback.format_exc()) if __name__ == '__main__': main() ","from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from algorithm import Algorithm class Server(object): def __init__(self, argv=None): self.argv = argv def get_algorithm(self): return Algorithm('aspen.algorithms.server') def get_website(self): """"""Return a website object. Useful in testing. """""" algorithm = self.get_algorithm() algorithm.run(argv=self.argv, _through='get_website_from_argv') return algorithm.state['website'] def main(self, argv=None): """"""http://aspen.io/cli/ """""" try: argv = argv if argv is not None else self.argv algorithm = self.get_algorithm() algorithm.run(argv=argv) except (SystemExit, KeyboardInterrupt): # Under some (most?) network engines, a SIGINT will be trapped by the # SIGINT signal handler above. However, gevent does ""something"" with # signals and our signal handler never fires. However, we *do* get a # KeyboardInterrupt here in that case. *shrug* # # See: https://github.com/gittip/aspen-python/issues/196 pass except: import aspen, traceback aspen.log_dammit(""Oh no! Aspen crashed!"") aspen.log_dammit(traceback.format_exc()) if __name__ == '__main__': Server().main() " Make use of node path utils when processing the jst names for jst grunt task,"require('js-yaml'); var path = require('path'); module.exports = function (grunt) { grunt.loadNpmTasks('grunt-contrib-jst'); grunt.loadNpmTasks('grunt-mocha-test'); grunt.loadNpmTasks('grunt-karma'); grunt.initConfig({ paths: require('js_paths.yml'), mochaTest: { jsbox_apps: { src: ['<%= paths.tests.jsbox_apps.spec %>'], } }, jst: { options: { processName: function(filename) { var dir = path.dirname(filename); dir = path.relative('go/base/static/templates', dir); var parts = dir.split('/'); parts.push(path.basename(filename, '.jst')); // process the template names the arb Django Pipelines way return parts.join('_'); } }, templates: { files: { ""<%= paths.client.templates.dest %>"": [ ""<%= paths.client.templates.src %>"" ] } }, }, karma: { dev: { singleRun: true, reporters: ['dots'], configFile: 'karma.conf.js' } } }); grunt.registerTask('test:jsbox_apps', [ 'mochaTest:jsbox_apps' ]); grunt.registerTask('test:client', [ 'jst:templates', 'karma:dev' ]); grunt.registerTask('test', [ 'test:jsbox_apps', 'test:client' ]); grunt.registerTask('default', [ 'test' ]); }; ","require('js-yaml'); module.exports = function (grunt) { grunt.loadNpmTasks('grunt-contrib-jst'); grunt.loadNpmTasks('grunt-mocha-test'); grunt.loadNpmTasks('grunt-karma'); grunt.initConfig({ paths: require('js_paths.yml'), mochaTest: { jsbox_apps: { src: ['<%= paths.tests.jsbox_apps.spec %>'], } }, jst: { options: { processName: function(filename) { // process the template names the arb Django Pipelines way return filename .replace('go/base/static/templates/', '') .replace(/\..+$/, '') .split('/') .join('_'); } }, templates: { files: { ""<%= paths.client.templates.dest %>"": [ ""<%= paths.client.templates.src %>"" ] } }, }, karma: { dev: { singleRun: true, reporters: ['dots'], configFile: 'karma.conf.js' } } }); grunt.registerTask('test:jsbox_apps', [ 'mochaTest:jsbox_apps' ]); grunt.registerTask('test:client', [ 'jst:templates', 'karma:dev' ]); grunt.registerTask('test', [ 'test:jsbox_apps', 'test:client' ]); grunt.registerTask('default', [ 'test' ]); }; " Use ORM alias for embedded classes,"package de.espend.idea.php.annotation.doctrine.action; import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.jetbrains.php.codeInsight.PhpCodeInsightUtil; import com.jetbrains.php.lang.psi.elements.PhpClass; import com.jetbrains.php.lang.psi.elements.PhpPsiElement; import de.espend.idea.php.annotation.doctrine.util.DoctrineUtil; import de.espend.idea.php.annotation.util.PhpDocUtil; import de.espend.idea.php.annotation.util.PhpElementsUtil; import org.jetbrains.annotations.NotNull; /** * @author Daniel Espendiller <daniel@espendiller.net> */ public class DoctrineEmbeddedClassAnnotationGenerateAction extends DoctrineClassGeneratorAction { @NotNull @Override protected String supportedClass() { return ""Doctrine\\ORM\\Mapping\\Embedded""; } protected void execute(@NotNull Editor editor, @NotNull PhpClass phpClass, @NotNull PsiFile psiFile) { // insert ORM alias PhpPsiElement scopeForUseOperator = PhpCodeInsightUtil.findScopeForUseOperator(phpClass.getFirstChild()); if(scopeForUseOperator != null) { PhpElementsUtil.insertUseIfNecessary(scopeForUseOperator, DoctrineUtil.DOCTRINE_ORM_MAPPING, ""ORM""); PsiDocumentManager.getInstance(psiFile.getProject()).doPostponedOperationsAndUnblockDocument(editor.getDocument()); } PhpDocUtil.addClassEmbeddedDocs(phpClass, editor.getDocument(), psiFile); } } ","package de.espend.idea.php.annotation.doctrine.action; import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.jetbrains.php.codeInsight.PhpCodeInsightUtil; import com.jetbrains.php.lang.psi.elements.PhpClass; import com.jetbrains.php.lang.psi.elements.PhpPsiElement; import de.espend.idea.php.annotation.doctrine.util.DoctrineUtil; import de.espend.idea.php.annotation.util.PhpDocUtil; import de.espend.idea.php.annotation.util.PhpElementsUtil; import org.jetbrains.annotations.NotNull; /** * @author Daniel Espendiller <daniel@espendiller.net> */ public class DoctrineEmbeddedClassAnnotationGenerateAction extends DoctrineClassGeneratorAction { @NotNull @Override protected String supportedClass() { return ""Doctrine\\ORM\\Mapping\\Embedded""; } protected void execute(@NotNull Editor editor, @NotNull PhpClass phpClass, @NotNull PsiFile psiFile) { // insert ORM alias PhpPsiElement scopeForUseOperator = PhpCodeInsightUtil.findScopeForUseOperator(phpClass.getFirstChild()); if(scopeForUseOperator != null) { PhpElementsUtil.insertUseIfNecessary(scopeForUseOperator, DoctrineUtil.DOCTRINE_ORM_MAPPING, ""Embedded""); PsiDocumentManager.getInstance(psiFile.getProject()).doPostponedOperationsAndUnblockDocument(editor.getDocument()); } PhpDocUtil.addClassEmbeddedDocs(phpClass, editor.getDocument(), psiFile); } } " "TST: Enable running tests from inside a container by setting an env var for the path to the test volume data on the host",""""""" Utilities for dockorm tests. """""" # encoding: utf-8 from __future__ import unicode_literals from os import getenv from os.path import ( dirname, join, ) from six import iteritems from ..container import ( Container, scalar, ) TEST_ORG = 'dockorm_testing' TEST_TAG = 'test' def assert_in_logs(container, line): """""" Assert that the given lines are in the container's logs. """""" logs = scalar(container.logs(all=True)) validate_dict(logs, {'Logs': line}) def dockerfile_root(path): """""" Path to a directory Dockerfile for testing. """""" return join( dirname(__file__), 'dockerfiles', path, ) def make_container(image, **kwargs): return Container( image=image, build_path=dockerfile_root(image), organization=TEST_ORG, tag=TEST_TAG, **kwargs ) def volume(path): """""" Path to a file relative to the test volumes directory. """""" return join( getenv('DOCKORM_TESTS_DIR') or dirname(__file__), 'volumes', path, ) def validate_dict(to_test, expected): """""" Recursively validate a dictionary of expectations against another input. Like TestCase.assertDictContainsSubset, but recursive. """""" for key, value in iteritems(expected): if isinstance(value, dict): validate_dict(to_test[key], value) else: assert to_test[key] == value ",""""""" Utilities for dockorm tests. """""" # encoding: utf-8 from __future__ import unicode_literals from os.path import ( dirname, join, ) from six import iteritems from ..container import ( Container, scalar, ) TEST_ORG = 'dockorm_testing' TEST_TAG = 'test' def assert_in_logs(container, line): """""" Assert that the given lines are in the container's logs. """""" logs = scalar(container.logs(all=True)) validate_dict(logs, {'Logs': line}) def dockerfile_root(path): """""" Path to a directory Dockerfile for testing. """""" return join( dirname(__file__), 'dockerfiles', path, ) def make_container(image, **kwargs): return Container( image=image, build_path=dockerfile_root(image), organization=TEST_ORG, tag=TEST_TAG, **kwargs ) def volume(path): """""" Path to a file relative to the test volumes directory. """""" return join( dirname(__file__), 'volumes', path, ) def validate_dict(to_test, expected): """""" Recursively validate a dictionary of expectations against another input. Like TestCase.assertDictContainsSubset, but recursive. """""" for key, value in iteritems(expected): if isinstance(value, dict): validate_dict(to_test[key], value) else: assert to_test[key] == value " "Revert ""Fix to improperly disabled docs"" This reverts commit 8bc704f6272ccfebd48f7282e02420a56d8e934d.","#!/usr/bin/env python from ez_setup import use_setuptools use_setuptools() from setuptools import setup import re main_py = open('flatcat/__init__.py').read() metadata = dict(re.findall(""__([a-z]+)__ = '([^']+)'"", main_py)) requires = [ 'morfessor', ] setup(name='Morfessor FlatCat', version=metadata['version'], author=metadata['author'], author_email='morfessor@cis.hut.fi', url='http://www.cis.hut.fi/projects/morpho/', description='Morfessor FlatCat', packages=['flatcat', 'flatcat.tests'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Scientific/Engineering', ], license=""BSD"", scripts=['scripts/flatcat', 'scripts/flatcat-train', 'scripts/flatcat-segment', 'scripts/flatcat-diagnostics', 'scripts/flatcat-reformat' ], install_requires=requires, extras_require={ 'docs': [l.strip() for l in open('docs/build_requirements.txt')] } ) ","#!/usr/bin/env python from ez_setup import use_setuptools use_setuptools() from setuptools import setup import re main_py = open('flatcat/__init__.py').read() metadata = dict(re.findall(""__([a-z]+)__ = '([^']+)'"", main_py)) requires = [ 'morfessor', ] setup(name='Morfessor FlatCat', version=metadata['version'], author=metadata['author'], author_email='morfessor@cis.hut.fi', url='http://www.cis.hut.fi/projects/morpho/', description='Morfessor FlatCat', packages=['flatcat', 'flatcat.tests'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Scientific/Engineering', ], license=""BSD"", scripts=['scripts/flatcat', 'scripts/flatcat-train', 'scripts/flatcat-segment', 'scripts/flatcat-diagnostics', 'scripts/flatcat-reformat' ], install_requires=requires, #extras_require={ # 'docs': [l.strip() for l in open('docs/build_requirements.txt')] #} ) " "Revert ""fixed the issue of a client throwing exception - log to stderr and return gracefully"" This reverts commit 4cecd6558ec9457d0c3e933023a8a1f77714eee5.","import logging import sys class SentryHandler(logging.Handler): def emit(self, record): from sentry.client.models import get_client from sentry.client.middleware import SentryLogMiddleware # Fetch the request from a threadlocal variable, if available request = getattr(SentryLogMiddleware.thread, 'request', None) # Avoid typical config issues by overriding loggers behavior if record.name == 'sentry.errors': print >> sys.stderr, ""Recursive log message sent to SentryHandler"" print >> sys.stderr, record.message return get_client().create_from_record(record, request=request) try: import logbook except ImportError: pass else: class SentryLogbookHandler(logbook.Handler): def emit(self, record): from sentry.client.models import get_client # Avoid typical config issues by overriding loggers behavior if record.name == 'sentry.errors': print >> sys.stderr, ""Recursive log message sent to SentryHandler"" print >> sys.stderr, record.message return kwargs = dict( message=record.message, level=record.level, logger=record.channel, data=record.extra, ) client = get_client() if record.exc_info: return client.create_from_exception(record.exc_info, **kwargs) return client.create_from_text(**kwargs) ","import logging import sys class SentryHandler(logging.Handler): def emit(self, record): from sentry.client.models import get_client from sentry.client.middleware import SentryLogMiddleware # Fetch the request from a threadlocal variable, if available request = getattr(SentryLogMiddleware.thread, 'request', None) # Avoid typical config issues by overriding loggers behavior if record.name == 'sentry.errors': print >> sys.stderr, ""Recursive log message sent to SentryHandler"" print >> sys.stderr, record.message return try: get_client().create_from_record(record, request=request) except Exception, e: print >> sys.stderr, ""SentryHandler failure to create log record"" print >> sys.stderr, record.message try: import logbook except ImportError: pass else: class SentryLogbookHandler(logbook.Handler): def emit(self, record): from sentry.client.models import get_client # Avoid typical config issues by overriding loggers behavior if record.name == 'sentry.errors': print >> sys.stderr, ""Recursive log message sent to SentryHandler"" print >> sys.stderr, record.message return kwargs = dict( message=record.message, level=record.level, logger=record.channel, data=record.extra, ) client = get_client() if record.exc_info: return client.create_from_exception(record.exc_info, **kwargs) return client.create_from_text(**kwargs) " Handle members with duplicate email addresses,"from __future__ import absolute_import from django import forms from django.db import transaction, IntegrityError from sentry.models import ( AuditLogEntry, AuditLogEntryEvent, OrganizationMember, OrganizationMemberType ) class InviteOrganizationMemberForm(forms.ModelForm): class Meta: fields = ('email',) model = OrganizationMember def save(self, actor, organization, ip_address): om = super(InviteOrganizationMemberForm, self).save(commit=False) om.organization = organization om.type = OrganizationMemberType.MEMBER try: existing = OrganizationMember.objects.filter( organization=organization, user__email__iexact=om.email, )[0] except IndexError: pass else: return existing, False sid = transaction.savepoint(using='default') try: om.save() except IntegrityError: transaction.savepoint_rollback(sid, using='default') return OrganizationMember.objects.get( email__iexact=om.email, organization=organization, ), False transaction.savepoint_commit(sid, using='default') AuditLogEntry.objects.create( organization=organization, actor=actor, ip_address=ip_address, target_object=om.id, event=AuditLogEntryEvent.MEMBER_INVITE, data=om.get_audit_log_data(), ) om.send_invite_email() return om, True ","from __future__ import absolute_import from django import forms from django.db import transaction, IntegrityError from sentry.models import ( AuditLogEntry, AuditLogEntryEvent, OrganizationMember, OrganizationMemberType ) class InviteOrganizationMemberForm(forms.ModelForm): class Meta: fields = ('email',) model = OrganizationMember def save(self, actor, organization, ip_address): om = super(InviteOrganizationMemberForm, self).save(commit=False) om.organization = organization om.type = OrganizationMemberType.MEMBER try: existing = OrganizationMember.objects.get( organization=organization, user__email__iexact=om.email, ) except OrganizationMember.DoesNotExist: pass else: return existing, False sid = transaction.savepoint(using='default') try: om.save() except IntegrityError: transaction.savepoint_rollback(sid, using='default') return OrganizationMember.objects.get( email__iexact=om.email, organization=organization, ), False transaction.savepoint_commit(sid, using='default') AuditLogEntry.objects.create( organization=organization, actor=actor, ip_address=ip_address, target_object=om.id, event=AuditLogEntryEvent.MEMBER_INVITE, data=om.get_audit_log_data(), ) om.send_invite_email() return om, True " Fix misleading message about pylockfile.,"try: import lockfile except ImportError: lockfile = None import threading import logging log = logging.getLogger(__name__) NO_PYLOCKFILE_MESSAGE = ""pylockfile module not found, skipping experimental lockfile handling."" class LockManager(): def __init__(self, lockfile=lockfile): if not lockfile: log.info(NO_PYLOCKFILE_MESSAGE) self.job_locks = dict({}) self.job_locks_lock = threading.Lock() self.lockfile = lockfile def get_lock(self, path): """""" Get a job lock corresponding to the path - assumes parent directory exists but the file itself does not. """""" if self.lockfile: return self.lockfile.LockFile(path) else: with self.job_locks_lock: if path not in self.job_locks: lock = threading.Lock() self.job_locks[path] = lock else: lock = self.job_locks[path] return lock def free_lock(self, path): # Not needed with pylockfile # Not currently be called, will result in tiny memory leak if # pylockfile is unavailable - so if you process millions of jobs # install pylockfile. if not self.lockfile: with self.job_locks_lock: if path in self.job_locks: del self.job_locks[path] ","try: import lockfile except ImportError: lockfile = None import threading import logging log = logging.getLogger(__name__) NO_PYLOCKFILE_MESSAGE = ""pylockfile module not found, expect suboptimal Pulsar lock handling."" class LockManager(): def __init__(self, lockfile=lockfile): if not lockfile: log.info(NO_PYLOCKFILE_MESSAGE) self.job_locks = dict({}) self.job_locks_lock = threading.Lock() self.lockfile = lockfile def get_lock(self, path): """""" Get a job lock corresponding to the path - assumes parent directory exists but the file itself does not. """""" if self.lockfile: return self.lockfile.LockFile(path) else: with self.job_locks_lock: if path not in self.job_locks: lock = threading.Lock() self.job_locks[path] = lock else: lock = self.job_locks[path] return lock def free_lock(self, path): # Not needed with pylockfile # Not currently be called, will result in tiny memory leak if # pylockfile is unavailable - so if you process millions of jobs # install pylockfile. if not self.lockfile: with self.job_locks_lock: if path in self.job_locks: del self.job_locks[path] " Include shub.image in package tarball,"from __future__ import absolute_import from setuptools import setup, find_packages setup( name='shub', version='2.4.2', packages=find_packages(exclude=('tests', 'tests.*')), url='http://doc.scrapinghub.com/shub.html', description='Scrapinghub Command Line Client', long_description=open('README.rst').read(), author='Scrapinghub', author_email='info@scrapinghub.com', maintainer='Scrapinghub', maintainer_email='info@scrapinghub.com', license='BSD', entry_points={ 'console_scripts': ['shub = shub.tool:cli'] }, include_package_data=True, zip_safe=False, install_requires=['click', 'pip', 'requests', 'PyYAML', 'scrapinghub', 'six', 'docker-py', 'retrying'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Operating System :: OS Independent', 'Environment :: Console', 'Topic :: Internet :: WWW/HTTP', ], ) ","from __future__ import absolute_import from setuptools import setup setup( name='shub', version='2.4.2', packages=['shub'], url='http://doc.scrapinghub.com/shub.html', description='Scrapinghub Command Line Client', long_description=open('README.rst').read(), author='Scrapinghub', author_email='info@scrapinghub.com', maintainer='Scrapinghub', maintainer_email='info@scrapinghub.com', license='BSD', entry_points={ 'console_scripts': ['shub = shub.tool:cli'] }, include_package_data=True, zip_safe=False, install_requires=['click', 'pip', 'requests', 'PyYAML', 'scrapinghub', 'six', 'docker-py', 'retrying'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Operating System :: OS Independent', 'Environment :: Console', 'Topic :: Internet :: WWW/HTTP', ], ) " Use PkgResources helper to load response templates.,"import re from twisted.web.template import Element, renderer, XMLFile from twisted.python.filepath import FilePath from vumi.utils import PkgResources MXIT_RESOURCES = PkgResources(__name__) class ResponseParser(object): HEADER_PATTERN = r'^(.*)[\r\n]{1,2}\d?' ITEM_PATTERN = r'^(\d+)\. (.+)$' def __init__(self, content): header_match = re.match(self.HEADER_PATTERN, content) if header_match: [self.header] = header_match.groups() self.items = re.findall(self.ITEM_PATTERN, content, re.MULTILINE) else: self.header = content self.items = [] @classmethod def parse(cls, content): p = cls(content) return p.header, p.items class MxitResponse(Element): loader = XMLFile(FilePath(MXIT_RESOURCES.path('templates/response.xml'))) def __init__(self, message, loader=None): self.header, self.items = ResponseParser.parse(message['content']) super(MxitResponse, self).__init__(loader or self.loader) @renderer def render_header(self, request, tag): return tag(self.header) @renderer def render_body(self, request, tag): if not self.items: return '' return tag @renderer def render_item(self, request, tag): for index, text in self.items: yield tag.clone().fillSlots(index=str(index), text=text) ","import re from twisted.web.template import Element, renderer, XMLFile from twisted.python.filepath import FilePath class ResponseParser(object): HEADER_PATTERN = r'^(.*)[\r\n]{1,2}\d?' ITEM_PATTERN = r'^(\d+)\. (.+)$' def __init__(self, content): header_match = re.match(self.HEADER_PATTERN, content) if header_match: [self.header] = header_match.groups() self.items = re.findall(self.ITEM_PATTERN, content, re.MULTILINE) else: self.header = content self.items = [] @classmethod def parse(cls, content): p = cls(content) return p.header, p.items class MxitResponse(Element): loader = XMLFile( FilePath('vumi/transports/mxit/templates/response.xml')) def __init__(self, message, loader=None): self.header, self.items = ResponseParser.parse(message['content']) super(MxitResponse, self).__init__(loader or self.loader) @renderer def render_header(self, request, tag): return tag(self.header) @renderer def render_body(self, request, tag): if not self.items: return '' return tag @renderer def render_item(self, request, tag): for index, text in self.items: yield tag.clone().fillSlots(index=str(index), text=text) " Add concentration in the name,"'use strict'; // convert an experiment, an array of spectra, to a chart var types=require('./types.js'); module.exports=function (experiments, channels, index) { var channels = channels || 'RGBWT' if (! Array.isArray(experiments)) experiments=[experiments]; var chart = { type: ""chart"", value: { title: ""Open Spectrophotometer results"", ""axis"": [ { ""label"": ""nM"" }, { ""label"": ""Y axis"" } ], ""data"": [] } } var counter=0; for (var i = 0; i < experiments.length; i++) { if ((index === undefined) || (index === i)) { var experiment=experiments[i]; for (var key in experiment) { if (channels.indexOf(key)>-1) { var data=experiment[key]; chart.value.data.push({ ""x"":data.x, ""y"":data.y, ""label"":(++counter)+"". ""+types[key].label+(data.name ? ': '+data.name : '')+ (data.concentration ? ' ('+data.name+"")"" : '') , xAxis: 0, yAxis: 1, lineWidth: 2, color: 'red' }); } } } } return chart; } ","'use strict'; // convert an experiment, an array of spectra, to a chart var types=require('./types.js'); module.exports=function (experiments, channels, index) { var channels = channels || 'RGBWT' if (! Array.isArray(experiments)) experiments=[experiments]; var chart = { type: ""chart"", value: { title: ""Open Spectrophotometer results"", ""axis"": [ { ""label"": ""nM"" }, { ""label"": ""Y axis"" } ], ""data"": [] } } var counter=0; for (var i = 0; i < experiments.length; i++) { if ((index === undefined) || (index === i)) { var experiment=experiments[i]; for (var key in experiment) { if (channels.indexOf(key)>-1) { var data=experiment[key]; chart.value.data.push({ ""x"":data.x, ""y"":data.y, ""label"":(++counter)+"". ""+types[key].label+(data.name ? ': '+data.name : ''), xAxis: 0, yAxis: 1, lineWidth: 2, color: 'red' }); } } } } return chart; } " Fix static and private combination,"<?php /** * Part of CodeIgniter Simple and Secure Twig * * @author Kenji Suzuki <https://github.com/kenjis> * @license MIT License * @copyright 2015 Kenji Suzuki * @link https://github.com/kenjis/codeigniter-ss-twig */ $installer = new Installer(); $installer->install(); class Installer { public static function install() { self::copy('vendor/kenjis/codeigniter-ss-twig/libraries/Twig.php', 'application/libraries/Twig.php'); } private static function copy($src, $dst) { $success = copy($src, $dst); if ($success) { echo 'copied: ' . $dst . PHP_EOL; } } /** * Recursive Copy * * @param string $src * @param string $dst */ private static function recursiveCopy($src, $dst) { @mkdir($dst, 0755); $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($src, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST ); foreach ($iterator as $file) { if ($file->isDir()) { @mkdir($dst . '/' . $iterator->getSubPathName()); } else { $success = copy($file, $dst . '/' . $iterator->getSubPathName()); if ($success) { echo 'copied: ' . $dst . '/' . $iterator->getSubPathName() . PHP_EOL; } } } } } ","<?php /** * Part of CodeIgniter Simple and Secure Twig * * @author Kenji Suzuki <https://github.com/kenjis> * @license MIT License * @copyright 2015 Kenji Suzuki * @link https://github.com/kenjis/codeigniter-ss-twig */ $installer = new Installer(); $installer->install(); class Installer { public static function install() { static::copy('vendor/kenjis/codeigniter-ss-twig/libraries/Twig.php', 'application/libraries/Twig.php'); } private static function copy($src, $dst) { $success = copy($src, $dst); if ($success) { echo 'copied: ' . $dst . PHP_EOL; } } /** * Recursive Copy * * @param string $src * @param string $dst */ private static function recursiveCopy($src, $dst) { @mkdir($dst, 0755); $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($src, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST ); foreach ($iterator as $file) { if ($file->isDir()) { @mkdir($dst . '/' . $iterator->getSubPathName()); } else { $success = copy($file, $dst . '/' . $iterator->getSubPathName()); if ($success) { echo 'copied: ' . $dst . '/' . $iterator->getSubPathName() . PHP_EOL; } } } } } " FIx house meeting schema spring evals,"from flask import Blueprint from flask import render_template from flask import request spring_evals_bp = Blueprint('spring_evals_bp', __name__) @spring_evals_bp.route('/spring_evals/') def display_spring_evals(): # get user data user_name = request.headers.get('x-webauth-user') members = [ { 'name': ""Liam Middlebrook"", 'committee_meetings': 24, 'house_meetings_missed': [{'date': ""aprial fools fayas ads"", 'reason': ""I was playing videogames""}], 'major_project': 'open_container', 'major_project_passed': True, 'comments': ""please don't fail me"", 'result': 'Pending' }, { 'name': ""Julien Eid"", 'committee_meetings': 69, 'house_meetings_missed': [], 'major_project': 'wii-u shit', 'major_project_passed': True, 'comments': ""imdabes"", 'result': 'Passed' } ] # return names in 'first last (username)' format return render_template('spring_evals.html', username = user_name, members = members) ","from flask import Blueprint from flask import render_template from flask import request spring_evals_bp = Blueprint('spring_evals_bp', __name__) @spring_evals_bp.route('/spring_evals/') def display_spring_evals(): # get user data user_name = request.headers.get('x-webauth-user') members = [ { 'name': ""Liam Middlebrook"", 'committee_meetings': 24, 'house_meetings_missed': 0, 'house_meetings_comments': """", 'major_project': 'open_container', 'major_project_passed': True, 'comments': ""please don't fail me"", 'result': 'Pending' }, { 'name': ""Julien Eid"", 'committee_meetings': 69, 'house_meetings_missed': 0, 'house_meetings_comments': """", 'major_project': 'wii-u shit', 'major_project_passed': True, 'comments': ""imdabes"", 'result': 'Passed' }, { 'name': ""James Forcier"", 'committee_meetings': 3, 'house_meetings_missed': 5, 'house_meetings_comments': """", 'major_project': 'Bobby Junior', 'major_project_passed': False, 'comments': ""Jazzazazazazzz"", 'result': 'Failed' } ] # return names in 'first last (username)' format return render_template('spring_evals.html', username = user_name, members = members) " Allow customization of retrofit after client is created,"/** * * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * */ package com.microsoft.rest; import com.microsoft.rest.serializer.AzureJacksonUtils; import com.squareup.okhttp.OkHttpClient; import retrofit.Retrofit; import java.net.CookieManager; import java.net.CookiePolicy; import java.util.concurrent.Executor; import java.util.concurrent.Executors; /** * ServiceClient is the abstraction for accessing REST operations and their payload data types. */ public abstract class AzureServiceClient extends ServiceClient { /** * Initializes a new instance of the ServiceClient class. */ protected AzureServiceClient() { this(new OkHttpClient(), new Retrofit.Builder()); CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); this.client.setCookieHandler(cookieManager); Executor executor = Executors.newCachedThreadPool(); this.retrofitBuilder = this.retrofitBuilder .addConverterFactory(new AzureJacksonUtils().getConverterFactory()) .callbackExecutor(executor); } /** * Initializes a new instance of the ServiceClient class. * * @param client the OkHttpClient instance to use * @param retrofitBuilder the builder to build up a rest adapter */ protected AzureServiceClient(OkHttpClient client, Retrofit.Builder retrofitBuilder) { super(client, retrofitBuilder); } } ","/** * * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * */ package com.microsoft.rest; import com.microsoft.rest.retry.RetryHandler; import com.microsoft.rest.serializer.AzureJacksonUtils; import com.microsoft.rest.serializer.JacksonUtils; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.OkHttpClient; import retrofit.JacksonConverterFactory; import retrofit.Retrofit; import java.net.CookieManager; import java.net.CookiePolicy; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; /** * ServiceClient is the abstraction for accessing REST operations and their payload data types. */ public abstract class AzureServiceClient extends ServiceClient { /** * Initializes a new instance of the ServiceClient class. */ protected AzureServiceClient() { this(new OkHttpClient(), new Retrofit.Builder()); CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); this.client.setCookieHandler(cookieManager); Executor executor = Executors.newCachedThreadPool(); this.retrofitBuilder = this.retrofitBuilder .addConverterFactory(new AzureJacksonUtils().getConverterFactory()) .callbackExecutor(executor); } /** * Initializes a new instance of the ServiceClient class. * * @param client the OkHttpClient instance to use * @param retrofitBuilder the builder to build up a rest adapter */ protected AzureServiceClient(OkHttpClient client, Retrofit.Builder retrofitBuilder) { super(client, retrofitBuilder); } } " Remove else in batch method,"var vow = require('vow'); var ApiMethod = require('../lib/api-method'); var ApiError = require('../lib/api-error'); /** * @typedef {Object} BatchApiMethod * @property {String} method Method name. * @property {Object} params Method params. * * @example * { * method: 'hello', * params: {name: 'Master'} * } */ module.exports = new ApiMethod('baby-loris-api-batch') .setDescription('Executes a set of methods') .setOption('hiddenOnDocPage', true) .addParam({ // Methods are passed as an array of BatchApiMethod objects. name: 'methods', type: 'Array', description: 'Set of methods with a data', required: true }) .setAction(function (params, api) { return vow.allResolved(params.methods.map(function (method) { return api.exec(method.method, method.params); })).then(function (response) { return response.map(function (promise) { var data = promise.valueOf(); if (promise.isFulfilled()) { return { data: data }; } return { error: { type: data.type || ApiError.INTERNAL_ERROR, message: data.message } }; }); }); }); ","var vow = require('vow'); var ApiMethod = require('../lib/api-method'); var ApiError = require('../lib/api-error'); /** * @typedef {Object} BatchApiMethod * @property {String} method Method name. * @property {Object} params Method params. * * @example * { * method: 'hello', * params: {name: 'Master'} * } */ module.exports = new ApiMethod('baby-loris-api-batch') .setDescription('Executes a set of methods') .setOption('hiddenOnDocPage', true) .addParam({ // Methods are passed as an array of BatchApiMethod objects. name: 'methods', type: 'Array', description: 'Set of methods with a data', required: true }) .setAction(function (params, api) { return vow.allResolved(params.methods.map(function (method) { return api.exec(method.method, method.params); })).then(function (response) { return response.map(function (promise) { var data = promise.valueOf(); if (promise.isFulfilled()) { return { data: data }; } else { return { error: { type: data.type || ApiError.INTERNAL_ERROR, message: data.message } }; } }); }); }); " Remove the $queryKey param and associated parsing,"<?php namespace Rogue\Services; use Illuminate\Support\Facades\Log; use Softonic\GraphQL\ClientBuilder; class GraphQL { /** * Build a new GraphQL client. */ public function __construct() { $this->client = ClientBuilder::build(config('services.graphql.url')); } /** * Run a GraphQL query using the client and return the data result. * * @param $query String * @param $variables Array * @return array|null */ public function query($query, $variables) { // Use try/catch to avoid any GraphQL related errors breaking the application. try { $response = $this->client->query($query, $variables); } catch (\Exception $exception) { Log::error( 'GraphQL request failed. Variables: '.json_encode($variables).' Exception: '.$exception->getMessage() ); return null; } return $response ? $response->getData() : null; } /** * Query for a CampaignWebsite by campaignId field. * * @param $campaignId String * @return array|null */ public function getCampaignWebsiteByCampaignId($campaignId) { $query = ' query GetCampaignWebsiteByCampaignId($campaignId: String!) { campaignWebsiteByCampaignId(campaignId: $campaignId) { title slug } }'; $variables = [ 'campaignId' => $campaignId, ]; return $this->query($query, $variables, 'campaignWebsiteByCampaignId'); } } ","<?php namespace Rogue\Services; use Illuminate\Support\Facades\Log; use Softonic\GraphQL\ClientBuilder; class GraphQL { /** * Build a new GraphQL client. */ public function __construct() { $this->client = ClientBuilder::build(config('services.graphql.url')); } /** * Run a GraphQL query using the client * and parse the data result into a convenient format. * * @param $query String * @param $variables Array * @param $queryKey String * @return array|null */ public function query($query, $variables, $queryKey) { // Use try/catch to avoid any GraphQL related errors breaking the application. try { $response = $this->client->query($query, $variables); } catch (\Exception $exception) { Log::error( 'GraphQL request failed. Variables: '.json_encode($variables).' Exception: '.$exception->getMessage() ); return null; } return $response ? array_get($response->getData(), $queryKey) : null; } /** * Query for a CampaignWebsite by campaignId field. * * @param $campaignId String * @return array|null */ public function getCampaignWebsiteByCampaignId($campaignId) { $query = ' query GetCampaignWebsiteByCampaignId($campaignId: String!) { campaignWebsiteByCampaignId(campaignId: $campaignId) { title slug } }'; $variables = [ 'campaignId' => $campaignId, ]; return $this->query($query, $variables, 'campaignWebsiteByCampaignId'); } } " admin_programme: Fix form to reflect model change,"# -*- coding: utf-8 -*- from django import forms from uni_form.helper import FormHelper from uni_form.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.ext_programme.models import ProgrammeEvent class ProgrammeEventForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProgrammeEventForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'', 'title', 'description', 'start', 'end', 'presenters', 'presenters_titles', 'icon_original', 'email', 'home_url', 'twitter_url', 'github_url', 'facebook_url', 'linkedin_url', 'wiki_url', ButtonHolder ( Submit('submit', u'Tallenna') ) ) ) class Meta: model = ProgrammeEvent exclude = ('event','icon_small',) ","# -*- coding: utf-8 -*- from django import forms from uni_form.helper import FormHelper from uni_form.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.ext_programme.models import ProgrammeEvent class ProgrammeEventForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProgrammeEventForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'', 'title', 'description', 'presenters', 'presenters_titles', 'icon_original', 'email', 'home_url', 'twitter_url', 'github_url', 'facebook_url', 'linkedin_url', 'wiki_url', ButtonHolder ( Submit('submit', u'Tallenna') ) ) ) class Meta: model = ProgrammeEvent exclude = ('event',) " Use es6 syntax in node,"/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-power-select', included(appOrAddon) { let app = appOrAddon.app || appOrAddon; if (!app.__emberPowerSelectIncludedInvoked) { app.__emberPowerSelectIncludedInvoked = true; let options = typeof app.options === 'object' ? app.options : {}; let addonConfig = options['ember-power-select'] || {}; // Since ember-power-select styles already `@import` styles of ember-basic-dropdown, // this flag tells to ember-basic-dropdown to skip importing its styles provided // we're using a theme (or the default styles) if (addonConfig.theme !== false) { app.__skipEmberBasicDropdownStyles = true; } this._super.included.apply(this, arguments); // Don't include the precompiled css file if the user uses ember-cli-sass if (!app.registry.availablePlugins['ember-cli-sass']) { if (addonConfig.theme) { app.import(`vendor/ember-power-select-${addonConfig.theme}.css`); } else if (addonConfig.theme !== false) { app.import('vendor/ember-power-select.css'); } } } }, contentFor(type, config) { let emberBasicDropdown = this.addons.find((a) => a.name === 'ember-basic-dropdown'); return emberBasicDropdown.contentFor(type, config); } }; ","/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-power-select', included: function(appOrAddon) { var app = appOrAddon.app || appOrAddon; if (!app.__emberPowerSelectIncludedInvoked) { app.__emberPowerSelectIncludedInvoked = true; var options = typeof app.options === 'object' ? app.options : {}; var addonConfig = options['ember-power-select'] || {}; // Since ember-power-select styles already `@import` styles of ember-basic-dropdown, // this flag tells to ember-basic-dropdown to skip importing its styles provided // we're using a theme (or the default styles) if (addonConfig.theme !== false) { app.__skipEmberBasicDropdownStyles = true; } this._super.included.apply(this, arguments); // Don't include the precompiled css file if the user uses ember-cli-sass if (!app.registry.availablePlugins['ember-cli-sass']) { if (addonConfig.theme) { app.import('vendor/ember-power-select-'+addonConfig.theme+'.css'); } else if (addonConfig.theme !== false) { app.import('vendor/ember-power-select.css'); } } } }, contentFor: function(type, config) { var emberBasicDropdown = this.addons.filter(function(addon) { return addon.name === 'ember-basic-dropdown'; })[0] return emberBasicDropdown.contentFor(type, config); } }; " Use promises and log an error,"angular.module('geojsonApp',[]) .controller('MainCtrl', ['$http', function($http) { var self = this; self.items = []; self.queryItems = []; self.item = {}; self.query = {}; self.currentTab = 'home'; var resetItemModel = function() { self.item={}; self.item.location={}; self.item.location.coordinates=[]; }; resetItemModel(); var fetchItems = function() { return $http.get('/api/item') .then( function(response){ self.items = response.data; }, function(errResponse) { console.error('Error while fetching items'); } ); }; fetchItems(); self.add = function() { self.item.location.type = ""Point""; $http.post('/api/item', self.item) .then(fetchItems) .then( function(response) { resetItemModel(); self.currentTab = 'items'; }); }; self.inquire = function() { console.log(self.query); $http.post('/api/query', self.query) .then( function(response) { self.queryItems = response.data; self.currentTab = 'query'; }); }; self.delete = function(id) { $http.delete('/api/item/' + id) .then(fetchItems) .then( function(response) { self.currentTab = 'items'; }, function(error) { console.log(""Error deleting item""); }); }; }]); ","angular.module('geojsonApp',[]) .controller('MainCtrl', ['$http', function($http) { var self = this; self.items = []; self.queryItems = []; self.item = {}; self.query = {}; self.currentTab = 'home'; var resetItemModel = function() { self.item={}; self.item.location={}; self.item.location.coordinates=[]; }; resetItemModel(); var fetchItems = function() { return $http.get('/api/item') .then( function(response){ self.items = response.data; }, function(errResponse) { console.error('Error while fetching items'); } ); }; fetchItems(); self.add = function() { self.item.location.type = ""Point""; $http.post('/api/item', self.item) .then(fetchItems) .then( function(response) { resetItemModel(); self.currentTab = 'items'; }); }; self.inquire = function() { console.log(self.query); $http.post('/api/query', self.query) .then( function(response) { self.queryItems = response.data; self.currentTab = 'query'; }); }; self.delete = function(id) { $http.delete('/api/item/' + id); fetchItems(); self.currentTab = 'items'; }; }]); " Support multiple subscribers in g.Live.,"/** * Keep live updates from service. * @constructor */ g.live = function() { var socket; /** * Open the websocket connection. */ var open = function() { if (g.isEncrypted()) { socket = new WebSocket('wss://' + g.getHost() + '/api/live'); } else { socket = new WebSocket('ws://' + g.getHost() + '/api/live'); } socket.onclose = onclose; socket.onmessage = onmessage; }; /** * onmessage callback. * @param {!MessageEvent} event */ var onmessage = function(event) { var data = JSON.parse(event.data); if (subscriptions.hasOwnProperty(data.type)) { subscriptions[data.type].forEach(function(collection) { console.log(data, ""to"", collection); collection.log(data); }); } }; /** * Use as onclose callback from websocket, will try to reconnect after * two and a half second. * @param {!CloseEvent} event */ var onclose = function(event) { setTimeout(function() { open(); }, 2500); }; // Open the connection right away. open(); /** * @type {Object.<string, g.Collection>} */ var subscriptions = {}; /** * Subscribe a collection. * @param {!string} id The type id to subscribe to. * @param {!g.Collection} collection The collection to update. */ this.subscribe = function(id, collection) { if (subscriptions.hasOwnProperty(id)) { subscriptions[id].push(collection); } else { subscriptions[id] = [collection]; } }; return this; }; ","/** * Keep live updates from service. * @constructor */ g.live = function() { var socket; /** * Open the websocket connection. */ var open = function() { if (g.isEncrypted()) { socket = new WebSocket('wss://' + g.getHost() + '/api/live'); } else { socket = new WebSocket('ws://' + g.getHost() + '/api/live'); } socket.onclose = onclose; socket.onmessage = onmessage; }; /** * onmessage callback. * @param {!MessageEvent} event */ var onmessage = function(event) { var data = JSON.parse(event.data); if (subscriptions.hasOwnProperty(data.type)) { subscriptions[data.type].log(data); } }; /** * Use as onclose callback from websocket, will try to reconnect after * two and a half second. * @param {!CloseEvent} event */ var onclose = function(event) { setTimeout(function() { open(); }, 2500); }; // Open the connection right away. open(); /** * @type {Object.<string, g.Collection>} */ var subscriptions = {}; /** * Subscribe a collection. * @param {!string} id The type id to subscribe to. * @param {!g.Collection} collection The collection to update. */ this.subscribe = function(id, collection) { subscriptions[id] = collection; }; return this; }; " :white_check_mark: Include more unit test to validate template parse with nested template tags,"/* * templateSpec.js * * Distributed under terms of the MIT license. */ /* global describe, it, expect */ var requirejs = require(""requirejs""); requirejs.config({ baseUrl: __dirname + ""/../src/"", nodeRequire: require }); describe(""Setup"", function() { it(""require"", function() { expect(require).not.toBe(null); var css = requirejs(""css_parser""); expect(css).not.toBe(null); expect(requirejs(""vue"")).not.toBe(null); }); }); describe(""Parser Templates"", function() { var parser = requirejs(""template_parser""); it(""Simple br"", function() { var template = ""<templete>"" + ""<br/></template>""; var result = parser.extractTemplate(template); expect(result).toMatch(""<br/>""); }); it(""Multiline"", function() { var template = ""<template>\n"" + "" <input/> <label>Test</label>\n"" + "" </template>""; var result = parser.extractTemplate(template); var expected = ""'' + \n"" + ""' <input/> <label>Test</label>' + \n"" + ""' ' + ''""; expect(result.length).toBe(expected.length); expect(true).toBe(result === expected); }); it(""Multi tamplate tags"", function () { var template = ""<template><template><span/></template></template>"" ; var result = parser.extractTemplate(template); var expected = ""'<template><span/></template>' + ''""; expect(result).toEqual(expected); }); }); /* vim: set tabstop=4 softtabstop=4 shiftwidth=4 expandtab : */ ","/* * templateSpec.js * * Distributed under terms of the MIT license. */ /* global describe, it, expect */ var requirejs = require(""requirejs""); requirejs.config({ baseUrl: __dirname + ""/../src/"", nodeRequire: require }); describe(""Setup"", function() { it(""require"", function() { expect(require).not.toBe(null); var css = requirejs(""css_parser""); expect(css).not.toBe(null); expect(requirejs(""vue"")).not.toBe(null); }); }); describe(""Parser Templates"", function() { var parser = requirejs(""template_parser""); it(""Simple br"", function() { var template = ""<templete>"" + ""<br/></template>""; var result = parser.extractTemplate(template); expect(result).toMatch(""<br/>""); }); it(""Multiline"", function() { var template = ""<template>\n"" + "" <input/> <label>Test</label>\n"" + "" </template>""; var result = parser.extractTemplate(template); var expected = ""'' + \n"" + ""' <input/> <label>Test</label>' + \n"" + ""' ' + ''""; expect(result.length).toBe(expected.length); expect(true).toBe(result === expected); }); }); /* vim: set tabstop=4 softtabstop=4 shiftwidth=4 expandtab : */ " "Fix immediate call to NS.loc Localisation must load after Overture does, so this will not work. Must delay calls to localise until later.","// -------------------------------------------------------------------------- \\ // File: SearchTextView.js \\ // Module: ControlViews \\ // Requires: TextView.js \\ // Author: Neil Jenkins \\ // License: © 2010-2015 FastMail Pty Ltd. MIT Licensed. \\ // -------------------------------------------------------------------------- \\ ""use strict""; ( function ( NS ) { var ClearSearchButtonView = new NS.Class({ Extends: NS.ButtonView, type: 'v-ClearSearchButton', positioning: 'absolute', shortcut: 'ctrl-/' }); NS.ClearSearchButtonView = ClearSearchButtonView; var SearchTextView = NS.Class({ Extends: NS.TextView, type: 'v-SearchText', icon: null, draw: function ( layer, Element, el ) { var children = SearchTextView.parent.draw.call( this, layer, Element, el ); children.push( this.get( 'icon' ), Element.when( this, 'value' ).show([ new NS.ClearSearchButtonView({ label: NS.loc( 'Clear Search' ), target: this, method: 'reset' }) ]).end() ); return children; }, reset: function () { this.set( 'value', '' ) .blur(); } }); NS.SearchTextView = SearchTextView; }( O ) ); ","// -------------------------------------------------------------------------- \\ // File: SearchTextView.js \\ // Module: ControlViews \\ // Requires: TextView.js \\ // Author: Neil Jenkins \\ // License: © 2010-2015 FastMail Pty Ltd. MIT Licensed. \\ // -------------------------------------------------------------------------- \\ ""use strict""; ( function ( NS ) { var ClearSearchButtonView = new NS.Class({ Extends: NS.ButtonView, type: 'v-ClearSearchButton', positioning: 'absolute', label: NS.loc( 'Clear Search' ), shortcut: 'ctrl-/' }); NS.ClearSearchButtonView = ClearSearchButtonView; var SearchTextView = NS.Class({ Extends: NS.TextView, type: 'v-SearchText', icon: null, draw: function ( layer, Element, el ) { var children = SearchTextView.parent.draw.call( this, layer, Element, el ); children.push( this.get( 'icon' ), Element.when( this, 'value' ).show([ new NS.ClearSearchButtonView({ target: this, method: 'reset' }) ]).end() ); return children; }, reset: function () { this.set( 'value', '' ) .blur(); } }); NS.SearchTextView = SearchTextView; }( O ) ); " Update community to use new lib namespace,"import sys from lib.core import Tokenizer from lib.utilities import url_to_json def run(project_id, repo_path, cursor, **options): t_sub = options.get('sub') t_star = options.get('star') t_forks = options.get('forks') cursor.execute(''' SELECT url FROM projects WHERE id = {0} '''.format(project_id)) record = cursor.fetchone() tokenizer = Tokenizer() full_url = tokenizer.tokenize(record[0].rstrip()) json_response = url_to_json(full_url) subscribers_count = json_response['subscribers_count'] stargazers_count = json_response['stargazers_count'] forks = json_response['forks'] result = False if ( (subscribers_count >= t_sub and stargazers_count >= t_star) or (stargazers_count >= t_star and forks >= t_forks) or (subscribers_count >= t_sub and forks >= t_forks) ): result = True return ( result, { 'sub': subscribers_count, 'star': stargazers_count, 'forks': forks } ) if __name__ == '__main__': print('Attribute plugins are not meant to be executed directly.') sys.exit(1) ","import sys from core import Tokenizer from utilities import url_to_json def run(project_id, repo_path, cursor, **options): t_sub = options.get('sub') t_star = options.get('star') t_forks = options.get('forks') cursor.execute(''' SELECT url FROM projects WHERE id = {0} '''.format(project_id)) record = cursor.fetchone() tokenizer = Tokenizer() full_url = tokenizer.tokenize(record[0].rstrip()) json_response = url_to_json(full_url) subscribers_count = json_response['subscribers_count'] stargazers_count = json_response['stargazers_count'] forks = json_response['forks'] result = False if ( (subscribers_count >= t_sub and stargazers_count >= t_star) or (stargazers_count >= t_star and forks >= t_forks) or (subscribers_count >= t_sub and forks >= t_forks) ): result = True return ( result, { 'sub': subscribers_count, 'star': stargazers_count, 'forks': forks } ) if __name__ == '__main__': print('Attribute plugins are not meant to be executed directly.') sys.exit(1) " Fix service provider when initializing notification library,"<?php namespace Krucas\Notification; use Illuminate\Support\ServiceProvider; class NotificationServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('edvinaskrucas/notification'); } /** * Register the service provider. * * @return void */ public function register() { $this->app['config']->package('edvinaskrucas/notification', __DIR__.'/../config'); $this->app['notification'] = $this->app->share(function ($app) { $config = $app['config']; $notification = new Notification( $config->get('notification::default_container'), $config->get('notification::default_types'), $config->get('notification::default_format'), $config->get('notification::default_formats') ); return $notification; }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array(); } } ","<?php namespace Krucas\Notification; use Illuminate\Support\ServiceProvider; class NotificationServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('edvinaskrucas/notification'); } /** * Register the service provider. * * @return void */ public function register() { $this->app['config']->package('edvinaskrucas/notification', __DIR__.'/../config'); $this->app['notification'] = $this->app->share(function ($app) { $config = $app['config']; $notification = new Notification( $config->get('notification::default_container'), $config->get('notification::default_format'), $config->get('notification::default_formats'), $config->get('notification::default_types') ); return $notification; }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array(); } } " Add limit_choices_to to CustomLink.content_type field,"# Generated by Django 2.2 on 2019-04-15 19:28 from django.db import migrations, models import django.db.models.deletion import extras.models class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ('extras', '0021_add_color_comments_changelog_to_tag'), ] operations = [ migrations.CreateModel( name='CustomLink', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False)), ('name', models.CharField(max_length=100, unique=True)), ('text', models.CharField(max_length=200)), ('url', models.CharField(max_length=200)), ('weight', models.PositiveSmallIntegerField(default=100)), ('group_name', models.CharField(blank=True, max_length=50)), ('button_class', models.CharField(default='default', max_length=30)), ('new_window', models.BooleanField()), ('content_type', models.ForeignKey(limit_choices_to=extras.models.get_custom_link_models, on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')), ], options={ 'ordering': ['group_name', 'weight', 'name'], }, ), ] ","# Generated by Django 2.2 on 2019-04-15 19:28 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ('extras', '0021_add_color_comments_changelog_to_tag'), ] operations = [ migrations.CreateModel( name='CustomLink', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False)), ('name', models.CharField(max_length=100, unique=True)), ('text', models.CharField(max_length=200)), ('url', models.CharField(max_length=200)), ('weight', models.PositiveSmallIntegerField(default=100)), ('group_name', models.CharField(blank=True, max_length=50)), ('button_class', models.CharField(default='default', max_length=30)), ('new_window', models.BooleanField()), ('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')), ], options={ 'ordering': ['group_name', 'weight', 'name'], }, ), ] " Add Referer to proxy server.,"""use strict""; const webpack = require(""webpack""); const path = require(""path""); const ExtractTextPlugin = require(""extract-text-webpack-plugin""); module.exports = { context: path.resolve(""./src""), entry: { vendor: [ ""jquery"" ], nm: [ ""./nm/index.js"", ""./nm/resource/index.less"" ] }, output: { path: path.resolve(""./assets""), publicPath: ""/assets"", filename: ""[name]/bundle.js"" }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: ""babel-loader"" }, { test: /\.less$/, loader: ExtractTextPlugin.extract(""style-loader"", ""css-loader!less-loader"") } ] }, plugins: [ new webpack.ProvidePlugin({ ""$"": ""jquery"", ""jQuery"": ""jquery"" }), new webpack.optimize.CommonsChunkPlugin({ name: ""vendor"", filename: ""vendor.js"", minChunks: Infinity }), new ExtractTextPlugin(""./[name]/resource/bundle.css"") ], devServer: { proxy: { ""/api/*"": { target: ""http://music.163.com/"", host: ""music.163.com"", secure: false, headers: { ""Referer"": ""http://music.163.com"" } } } } }; ","""use strict""; const webpack = require(""webpack""); const path = require(""path""); const ExtractTextPlugin = require(""extract-text-webpack-plugin""); module.exports = { context: path.resolve(""./src""), entry: { vendor: [ ""jquery"" ], nm: [ ""./nm/index.js"", ""./nm/resource/index.less"" ] }, output: { path: path.resolve(""./assets""), publicPath: ""/assets"", filename: ""[name]/bundle.js"" }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: ""babel-loader"" }, { test: /\.less$/, loader: ExtractTextPlugin.extract(""style-loader"", ""css-loader!less-loader"") } ] }, plugins: [ new webpack.ProvidePlugin({ ""$"": ""jquery"", ""jQuery"": ""jquery"" }), new webpack.optimize.CommonsChunkPlugin({ name: ""vendor"", filename: ""vendor.js"", minChunks: Infinity }), new ExtractTextPlugin(""./[name]/resource/bundle.css"") ], devServer: { proxy: { ""/api/*"": { target: ""http://music.163.com/"", host: ""music.163.com"", secure: false } } } }; " Fix async loading from subdirectory,"var path = require('path'); var webpack = require('webpack'); var _ = require('lodash'); module.exports = function(options) { var config = { entry: [ './src/js/main.js' ], output: { path: path.join(__dirname, 'build'), filename: 'app.js', publicPath: '' }, plugins: [ new webpack.optimize.UglifyJsPlugin(), new webpack.optimize.DedupePlugin() ], resolve: { extensions: ['', '.js'] }, module: { loaders: [ { test: /\.js$/, loaders: ['babel?stage=0'], include: path.join(__dirname, 'src/js') }, ] }, }; if (options.environment === 'dev') { config.devtool = 'source-map'; Array.prototype.unshift.call( config.entry, 'webpack-dev-server/client?http://0.0.0.0:8000', 'webpack/hot/only-dev-server' ); config.plugins = [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ]; config.module.loaders[0].loaders.unshift('react-hot'); } config.module.loaders.unshift({ test: require.resolve(""react""), loader: ""expose?React"" }); return config; }; ","var path = require('path'); var webpack = require('webpack'); var _ = require('lodash'); module.exports = function(options) { var config = { entry: [ './src/js/main.js' ], output: { path: path.join(__dirname, 'build'), filename: 'app.js', publicPath: '/' }, plugins: [ new webpack.optimize.UglifyJsPlugin(), new webpack.optimize.DedupePlugin() ], resolve: { extensions: ['', '.js'] }, module: { loaders: [ { test: /\.js$/, loaders: ['babel?stage=0'], include: path.join(__dirname, 'src/js') }, ] }, }; if (options.environment === 'dev') { config.devtool = 'source-map'; Array.prototype.unshift.call( config.entry, 'webpack-dev-server/client?http://0.0.0.0:8000', 'webpack/hot/only-dev-server' ); config.plugins = [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ]; config.module.loaders[0].loaders.unshift('react-hot'); } config.module.loaders.unshift({ test: require.resolve(""react""), loader: ""expose?React"" }); return config; }; " refactor: Move initialisations inside main to avoid running them if not necessary,"#! /usr/bin/env python import os from slackclient import SlackClient import pyrebase import linkatos.firebase as fb import linkatos.activities as activities # Main if __name__ == '__main__': # starterbot environment variables BOT_ID = os.environ.get(""BOT_ID"") SLACK_BOT_TOKEN = os.environ.get(""SLACK_BOT_TOKEN"") # instantiate Slack clients slack_client = SlackClient(SLACK_BOT_TOKEN) # firebase environment variables FB_API_KEY = os.environ.get(""FB_API_KEY"") FB_USER = os.environ.get(""FB_USER"") FB_PASS = os.environ.get(""FB_PASS"") fb_credentials = {'username': FB_USER, 'password': FB_PASS} # initialise firebase project_name = 'coses-acbe6' firebase = fb.initialise(FB_API_KEY, project_name) # verify linkatos connection if slack_client.rtm_connect(): parsed_url_message = {} expecting_url = True expecting_reaction = False while True: # note that url is returned to keep it over several cylcles in # whilst we wait for an answer (expecting_url, expecting_reaction, parsed_url_message) = \ activities.event_consumer( expecting_url, expecting_reaction, parsed_url_message, slack_client, fb_credentials, firebase) else: print(""Connection failed. Invalid Slack token or bot ID?"") ","#! /usr/bin/env python import os from slackclient import SlackClient import pyrebase import linkatos.firebase as fb import linkatos.activities as activities # starterbot environment variables BOT_ID = os.environ.get(""BOT_ID"") SLACK_BOT_TOKEN = os.environ.get(""SLACK_BOT_TOKEN"") # instantiate Slack clients slack_client = SlackClient(SLACK_BOT_TOKEN) # firebase environment variables FB_API_KEY = os.environ.get(""FB_API_KEY"") FB_USER = os.environ.get(""FB_USER"") FB_PASS = os.environ.get(""FB_PASS"") fb_credentials = {'username': FB_USER, 'password': FB_PASS} # initialise firebase project_name = 'coses-acbe6' firebase = fb.initialise(FB_API_KEY, project_name) # Main if __name__ == '__main__': # verify linkatos connection if slack_client.rtm_connect(): parsed_url_message = {} expecting_url = True expecting_reaction = False while True: # note that url is returned to keep it over several cylcles in # whilst we wait for an answer (expecting_url, expecting_reaction, parsed_url_message) = \ activities.event_consumer( expecting_url, expecting_reaction, parsed_url_message, slack_client, fb_credentials, firebase) else: print(""Connection failed. Invalid Slack token or bot ID?"") " Create sourceMap for minified js,"module.exports = function (grunt) { // 1. All configuration goes here grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { igv: { src: [ 'js/**/*.js', 'vendor/inflate.js', 'vendor/zlib_and_gzip.min.js' ], dest: 'dist/igv-all.js' } }, uglify: { options: { mangle: false, sourceMap: true }, igv: { src: 'dist/igv-all.js', dest: 'dist/igv-all.min.js' } } }); // 3. Where we tell Grunt we plan to use this plug-in. grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-cssmin'); // 4. Where we tell Grunt what to do when we type ""grunt"" into the terminal. //grunt.registerTask('default', ['concat:igvexp', 'uglify:igvexp']); grunt.registerTask('default', ['concat:igv', 'uglify:igv']); }; ","module.exports = function (grunt) { // 1. All configuration goes here grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { igv: { src: [ 'js/**/*.js', 'vendor/inflate.js', 'vendor/zlib_and_gzip.min.js' ], dest: 'dist/igv-all.js' } }, uglify: { options: { mangle: false }, igv: { src: 'dist/igv-all.js', dest: 'dist/igv-all.min.js' } } }); // 3. Where we tell Grunt we plan to use this plug-in. grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-cssmin'); // 4. Where we tell Grunt what to do when we type ""grunt"" into the terminal. //grunt.registerTask('default', ['concat:igvexp', 'uglify:igvexp']); grunt.registerTask('default', ['concat:igv', 'uglify:igv']); }; " Fix name of spell checker.,"import traceback from routes import Mapper import ppp_core import example_ppp_module as flower import ppp_questionparsing_grammatical as qp_grammatical import ppp_cas import ppp_spell_checker #import ppp_nlp_ml_standalone class Application: def __init__(self): self.mapper = Mapper() self.mapper.connect('core', '/core/', app=ppp_core.app) self.mapper.connect('qp_grammatical', '/qp_grammatical/', app=qp_grammatical.app) self.mapper.connect('flower', '/flower/', app=flower.app) self.mapper.connect('cas', '/cas/', app=ppp_cas.app) self.mapper.connect('spellcheck', '/spell_checker/', app=ppp_spell_checker.app) #self.mapper.connect('nlp_ml_standalone', '/nlp_ml_standalone/', app=ppp_nlp_ml_standalone.app) def __call__(self, environ, start_response): match = self.mapper.routematch(environ=environ) app = match[0]['app'] if match else self.not_found try: return app(environ, start_response) except KeyboardInterrupt: raise except Exception as e: traceback.print_exc(e) def not_found(self, environ, start_response): headers = [('Content-Type', 'text/plain')] start_response('404 Not Found', headers) return [b'Not found.'] app = Application() ","import traceback from routes import Mapper import ppp_core import example_ppp_module as flower import ppp_questionparsing_grammatical as qp_grammatical import ppp_cas #import ppp_nlp_ml_standalone class Application: def __init__(self): self.mapper = Mapper() self.mapper.connect('core', '/core/', app=ppp_core.app) self.mapper.connect('qp_grammatical', '/qp_grammatical/', app=qp_grammatical.app) self.mapper.connect('flower', '/flower/', app=flower.app) self.mapper.connect('cas', '/cas/', app=ppp_cas.app) self.mapper.connect('spellcheck', '/spell_checker/', app=ppp_cas.app) #self.mapper.connect('nlp_ml_standalone', '/nlp_ml_standalone/', app=ppp_nlp_ml_standalone.app) def __call__(self, environ, start_response): match = self.mapper.routematch(environ=environ) app = match[0]['app'] if match else self.not_found try: return app(environ, start_response) except KeyboardInterrupt: raise except Exception as e: traceback.print_exc(e) def not_found(self, environ, start_response): headers = [('Content-Type', 'text/plain')] start_response('404 Not Found', headers) return [b'Not found.'] app = Application() " "Update gzip output for Python 3.8.2 Python 3.8.2 includes a fix for https://bugs.python.org/issue39389. Previously, the extra flags byte was always set to 0x02, claiming maximum compression. It now reflects the actual compression setting. Since our default is neither fastest or maximum, the expected test output is 0x00 for the extra flags byte.","from datetime import datetime import pytest from pytz import UTC from ichnaea.exceptions import GZIPDecodeError from ichnaea import util class TestUtil(object): gzip_foo = ( b""\x1f\x8b\x08\x00\xed\x7f\x9aU\x00\xffK"" b""\xcb\xcf\x07\x00!es\x8c\x03\x00\x00\x00"" ) def test_utcnow(self): now = util.utcnow() assert isinstance(now, datetime) assert now.tzinfo == UTC def test_encode_gzip(self): data = util.encode_gzip(b""foo"") # Test around the 4-byte timestamp assert data[:4] == self.gzip_foo[:4] assert data[8:] == self.gzip_foo[8:] def test_decode_gzip(self): data = util.decode_gzip(self.gzip_foo) assert data == b""foo"" def test_roundtrip_gzip(self): data = util.decode_gzip(util.encode_gzip(b""foo"")) assert data == b""foo"" def test_decode_gzip_error(self): with pytest.raises(GZIPDecodeError): util.decode_gzip(self.gzip_foo[:1]) with pytest.raises(GZIPDecodeError): util.decode_gzip(self.gzip_foo[:5]) ","from datetime import datetime import pytest from pytz import UTC from ichnaea.exceptions import GZIPDecodeError from ichnaea import util class TestUtil(object): gzip_foo = ( b""\x1f\x8b\x08\x00\xed\x7f\x9aU\x02\xffK"" b""\xcb\xcf\x07\x00!es\x8c\x03\x00\x00\x00"" ) def test_utcnow(self): now = util.utcnow() assert isinstance(now, datetime) assert now.tzinfo == UTC def test_encode_gzip(self): data = util.encode_gzip(b""foo"") # Test around the 4-byte timestamp assert data[:4] == self.gzip_foo[:4] assert data[8:] == self.gzip_foo[8:] def test_decode_gzip(self): data = util.decode_gzip(self.gzip_foo) assert data == b""foo"" def test_roundtrip_gzip(self): data = util.decode_gzip(util.encode_gzip(b""foo"")) assert data == b""foo"" def test_decode_gzip_error(self): with pytest.raises(GZIPDecodeError): util.decode_gzip(self.gzip_foo[:1]) with pytest.raises(GZIPDecodeError): util.decode_gzip(self.gzip_foo[:5]) " Add comment for updated Pandas requirement,"import os.path # Install setuptools if not installed. try: import setuptools except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages # read README as the long description readme = 'README' if os.path.exists('README') else 'README.md' with open(readme, 'r') as f: long_description = f.read() setup( name='spandex', version='0.1dev', description='Spatial Analysis and Data Exploration', long_description=long_description, author='Synthicity', author_email='ejanowicz@synthicity.com', url='https://github.com/synthicity/spandex', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 2.7', ], packages=find_packages(exclude=['*.tests']), install_requires=[ 'GeoAlchemy2>=0.2.1', # Bug fix for schemas other than public. 'pandas>=0.15.0', # pandas.Index.difference. 'psycopg2>=2.5', # connection and cursor context managers. 'six>=1.4', # Mapping for urllib. 'SQLAlchemy>=0.8' # GeoAlchemy2 support. ], extras_require={ 'prj': ['GDAL>=1.7'], # Python 3 support. 'rastertoolz': ['numpy>=1.8.0', 'rasterio>=0.12', 'rasterstats>=0.4', 'shapely>=1.3.2'] } ) ","import os.path # Install setuptools if not installed. try: import setuptools except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages # read README as the long description readme = 'README' if os.path.exists('README') else 'README.md' with open(readme, 'r') as f: long_description = f.read() setup( name='spandex', version='0.1dev', description='Spatial Analysis and Data Exploration', long_description=long_description, author='Synthicity', author_email='ejanowicz@synthicity.com', url='https://github.com/synthicity/spandex', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 2.7', ], packages=find_packages(exclude=['*.tests']), install_requires=[ 'GeoAlchemy2>=0.2.1', # Bug fix for schemas other than public. 'pandas>=0.15.0', 'psycopg2>=2.5', # connection and cursor context managers. 'six>=1.4', # Mapping for urllib. 'SQLAlchemy>=0.8' # GeoAlchemy2 support. ], extras_require={ 'prj': ['GDAL>=1.7'], # Python 3 support. 'rastertoolz': ['numpy>=1.8.0', 'rasterio>=0.12', 'rasterstats>=0.4', 'shapely>=1.3.2'] } ) " Add UTF-8 charset to the db connection,"<?php /** * This helper package makes a database connection for package Kola\PotatoOrm\Model. * * @package Kola\PotatoOrm\Helper\DbConn * @author Kolawole ERINOSO <kola.erinoso@gmail.com> * @license MIT <https://opensource.org/licenses/MIT> */ namespace Kola\PotatoOrm\Helper; use Kola\PotatoOrm\Exception\UnsuccessfulDbConnException as ConnEx; use \PDO; final class DbConn extends PDO implements DbConnInterface { /** * Override the parent class PDO constructor to prevent instantiation-argument requirement */ public function __construct() { } /** * Make a database connection * * @return PDO|string */ public static function connect() { self::loadDotenv(); try { $dbConn = new PDO(getenv('DB_ENGINE') . ':host=' . getenv('DB_HOST') . ';dbname=' . getenv('DB_DATABASE') . ';charset=utf8mb4', getenv('DB_USERNAME'), getenv('DB_PASSWORD'), [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_PERSISTENT => false]); } catch (ConnEx $e) { return $e->message(); } return $dbConn; } /** * Load Dotenv to grant getenv() access to environment variables in .env file */ private static function loadDotenv() { $dotenv = new \Dotenv\Dotenv($_SERVER['DOCUMENT_ROOT']); $dotenv->load(); } } ","<?php /** * This helper package makes a database connection for package Kola\PotatoOrm\Model. * * @package Kola\PotatoOrm\Helper\DbConn * @author Kolawole ERINOSO <kola.erinoso@gmail.com> * @license MIT <https://opensource.org/licenses/MIT> */ namespace Kola\PotatoOrm\Helper; use Kola\PotatoOrm\Exception\UnsuccessfulDbConnException as ConnEx; use \PDO; final class DbConn extends PDO implements DbConnInterface { /** * Override the parent class PDO constructor to prevent instantiation-argument requirement */ public function __construct() { } /** * Make a database connection * * @return PDO|string */ public static function connect() { self::loadDotenv(); try { $dbConn = new PDO(getenv('DB_ENGINE') . ':host=' . getenv('DB_HOST') . ';dbname=' . getenv('DB_DATABASE'), getenv('DB_USERNAME'), getenv('DB_PASSWORD')); $dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (ConnEx $e) { return $e->message(); } return $dbConn; } /** * Load Dotenv to grant getenv() access to environment variables in .env file */ private static function loadDotenv() { $dotenv = new \Dotenv\Dotenv($_SERVER['DOCUMENT_ROOT']); $dotenv->load(); } } " Add naming suffix option for SQS backends,"from .base import BackendFactory, Backend from ..queue.sqs import SQSQueue class SQSBackendFactory(BackendFactory): def __init__(self, sqs_connection_thunk, visibility_timeout=30, wait_time=10, name_suffix=None): """"""To allow backends to be initialized lazily, this factory requires a thunk (parameter-less closure) which returns an initialized SQS connection. This thunk is called as late as possible to initialize the connection and perform operations against the SQS API. We do this so that backends can be made available at import time without requiring a connection to be created at import time as well."""""" self.sqs_connection_thunk = sqs_connection_thunk self.visibility_timeout = visibility_timeout self.wait_time = wait_time # SQS makes it impossible to separate your queues by environment, so it can # be useful to include something to make your names unique. Typically you # will just pass your environment here. self.name_suffix = name_suffix def _create_backend_for_group(self, group): formatted_name = group if self.name_suffix: formatted_name += '_{}'.format(self.name_suffix) error_queue = SQSQueue(self.sqs_connection_thunk, self._queue_name('{}_error'.format(formatted_name)), self.visibility_timeout, self.wait_time) queue = SQSQueue(self.sqs_connection_thunk, self._queue_name(formatted_name), self.visibility_timeout, self.wait_time, redrive_queue=error_queue) return SQSBackend(group, queue, error_queue) class SQSBackend(Backend): pass ","from .base import BackendFactory, Backend from ..queue.sqs import SQSQueue class SQSBackendFactory(BackendFactory): def __init__(self, sqs_connection_thunk, visibility_timeout=30, wait_time=10): """"""To allow backends to be initialized lazily, this factory requires a thunk (parameter-less closure) which returns an initialized SQS connection. This thunk is called as late as possible to initialize the connection and perform operations against the SQS API. We do this so that backends can be made available at import time without requiring a connection to be created at import time as well."""""" self.sqs_connection_thunk = sqs_connection_thunk self.visibility_timeout = visibility_timeout self.wait_time = wait_time def _create_backend_for_group(self, group): error_queue = SQSQueue(self.sqs_connection_thunk, self._queue_name('{}_error'.format(group)), self.visibility_timeout, self.wait_time) queue = SQSQueue(self.sqs_connection_thunk, self._queue_name(group), self.visibility_timeout, self.wait_time, redrive_queue=error_queue) return SQSBackend(group, queue, error_queue) class SQSBackend(Backend): pass " "Make trailing slash on login view non-optional This was causing the UI tests to fail","from django.conf.urls import include from django.conf.urls import url from django.contrib.auth.views import login from django.views.generic.base import TemplateView from views import (RegistrationView, ActivationView, LoginForm, PasswordResetView) urlpatterns = [ url(r'^login/$', login, {'authentication_form': LoginForm}, name='login'), url(r'^activation-complete/$', TemplateView.as_view(template_name='registration/activation_complete.html'), # NOQA name='registration_activation_complete'), # Activation keys get matched by \w+ instead of the more specific # [a-fA-F0-9]{40} because a bad activation key should still get # to the view; that way it can return a sensible ""invalid key"" # message instead of a confusing 404. url(r'^activate/(?P<activation_key>\w+)/$', ActivationView.as_view(), name='registration_activate'), url(r'^register/$', RegistrationView.as_view(), name='registration_register'), url(r'^register/complete/$', TemplateView.as_view(template_name='registration/registration_complete.html'), # NOQA name='registration_complete'), url(r'^register/closed/$', TemplateView.as_view(template_name='registration/registration_closed.html'), # NOQA name='registration_disallowed'), url(r'password/reset/$', PasswordResetView.as_view(), name='auth_password_reset'), url(r'', include('registration.auth_urls')), ] ","from django.conf.urls import include from django.conf.urls import url from django.contrib.auth.views import login from django.views.generic.base import TemplateView from views import (RegistrationView, ActivationView, LoginForm, PasswordResetView) urlpatterns = [ url(r'^login/?$', login, {'authentication_form': LoginForm}, name='login'), url(r'^activation-complete/$', TemplateView.as_view(template_name='registration/activation_complete.html'), # NOQA name='registration_activation_complete'), # Activation keys get matched by \w+ instead of the more specific # [a-fA-F0-9]{40} because a bad activation key should still get # to the view; that way it can return a sensible ""invalid key"" # message instead of a confusing 404. url(r'^activate/(?P<activation_key>\w+)/$', ActivationView.as_view(), name='registration_activate'), url(r'^register/$', RegistrationView.as_view(), name='registration_register'), url(r'^register/complete/$', TemplateView.as_view(template_name='registration/registration_complete.html'), # NOQA name='registration_complete'), url(r'^register/closed/$', TemplateView.as_view(template_name='registration/registration_closed.html'), # NOQA name='registration_disallowed'), url(r'password/reset/$', PasswordResetView.as_view(), name='auth_password_reset'), url(r'', include('registration.auth_urls')), ] " Update console logs for cli script,"//------------------------------------------------------------------------------- // Common Modules //------------------------------------------------------------------------------- var bugpackApi = require(""bugpack""); var path = require('path'); //------------------------------------------------------------------------------- // Script //------------------------------------------------------------------------------- bugpackApi.loadContext(module, function(error, bugpack) { if (!error) { bugpack.loadExport(""buganno.AnnotationParserProcess"", function(error) { if (!error) { var BugUnitCli = bugpack.require('bugunit.BugUnitCli'); var targetModulePath = process.argv[2]; if (!targetModulePath) { throw new Error(""Must specify the module to install and test""); } targetModulePath = path.resolve(targetModulePath); //TODO BRN: Add ability to target specific test OR a test suite. BugUnitCli.start(targetModulePath, function(error) { if (error) { console.log(error.message); console.log(error.stack); process.exit(1); } }); } else { console.error(error.message); console.error(error.stack); process.exit(1); } }); } else { console.error(error.message); console.error(error.stack); process.exit(1); } }); ","//------------------------------------------------------------------------------- // Common Modules //------------------------------------------------------------------------------- var bugpackApi = require(""bugpack""); var path = require('path'); //------------------------------------------------------------------------------- // Script //------------------------------------------------------------------------------- bugpackApi.loadContext(module, function(error, bugpack) { if (!error) { bugpack.loadExport(""buganno.AnnotationParserProcess"", function(error) { if (!error) { var BugUnitCli = bugpack.require('bugunit.BugUnitCli'); var targetModulePath = process.argv[2]; if (!targetModulePath) { throw new Error(""Must specify the module to install and test""); } targetModulePath = path.resolve(targetModulePath); //TODO BRN: Add ability to target specific test OR a test suite. BugUnitCli.start(targetModulePath, function(error) { if (error) { console.log(error); console.log(error.stack); process.exit(1); } }); } else { console.error(error); process.exit(1); } }); } else { console.error(error); process.exit(1); } }); " Fix safari not showing login screen when server down,"define( [ 'service/serviceBase' ], function (ServiceBase) { 'use strict'; function UserService() { ServiceBase.call(this); return this; } UserService.prototype = Object.create(ServiceBase.prototype); UserService.prototype.isLoginRequired = function() { return this._ajaxGet({ url:'user/me' }); }; UserService.prototype.login = function(username, password) { return this._ajaxPost({ url:'login', data: { username: username, password: password } }); }; UserService.prototype.logout = function() { try { this.disconnect(); } catch(e) { console.log('Unable to disconnect socket', e); } return this._ajaxPost({ url:'logout' }); }; UserService.prototype.getOnline = function() { var self = this; var result = {}; return $.when( this._ajaxGet({ url: 'user/me' }), this.getCurrentUsers() ).then(function(userResponse, usersResponse) { var user = userResponse[0], users = usersResponse[0].users; return { user: user, users: users }; }); }; UserService.prototype.getCurrentUsers = function() { return this._ajaxGet({ url: '/user/' }); }; return UserService; }); ","define( [ 'service/serviceBase' ], function (ServiceBase) { 'use strict'; function UserService() { ServiceBase.call(this); return this; } UserService.prototype = Object.create(ServiceBase.prototype); UserService.prototype.isLoginRequired = function() { return this._ajaxGet({ url:'user/me' }); }; UserService.prototype.login = function(username, password) { return this._ajaxPost({ url:'login', data: { username: username, password: password } }); }; UserService.prototype.logout = function() { this.disconnect(); return this._ajaxPost({ url:'logout' }); }; UserService.prototype.getOnline = function() { var self = this; var result = {}; return $.when( this._ajaxGet({ url: 'user/me' }), this.getCurrentUsers() ).then(function(userResponse, usersResponse) { var user = userResponse[0], users = usersResponse[0].users; return { user: user, users: users }; }); }; UserService.prototype.getCurrentUsers = function() { return this._ajaxGet({ url: '/user/' }); }; return UserService; }); " Fix weird docsite chapter ordering,"import React from 'react' import Link from 'gatsby-link' import { getModuleName } from '../components/Headers' import { startCase, kebabCase, flatMap, last } from 'lodash' import { Paper, Menu, MenuItem, Divider } from 'material-ui' const modules = require('../docs').children export default ({ order }) => { return ( <Paper style={{ minWidth: '10em', justifyContent: 'space-between' }} zDepth={2}> <Menu desktop> <LinkItem link=""/docs/getting-started""> Getting Started </LinkItem> <LinkItem link=""/docs/cli-tool""> CLI Tool </LinkItem> <LinkItem link=""/docs/app-configuration""> App Configuration </LinkItem> <LinkItem link=""/docs/environmental-variables""> Environmental Variables </LinkItem> <Divider /> { modules.map(({ id, name }) => <LinkItem key={id} link={`/modules/${kebabCase(name)}`}> {getModuleName(name)} </LinkItem> ) } </Menu> </Paper> ) } function LinkItem({ link, children }) { return ( <MenuItem> <Link to={link}> {children} </Link> </MenuItem> ) } function getPageName(path) { const components = path.split('/') return startCase(components[components.length - 2]) } ","import React from 'react' import Link from 'gatsby-link' import { getModuleName } from '../components/Headers' import { startCase, kebabCase, flatMap, last } from 'lodash' import { Paper, Menu, MenuItem, Divider } from 'material-ui' const modules = require('../docs').children export default ({ pages }) => { return ( <Paper style={{ minWidth: '10em', justifyContent: 'space-between' }} zDepth={2}> <Menu desktop> { flatMap(pages, ({ id, path }) => path.startsWith('/docs') ? [ <MenuItem key={id}> <Link to={path}> {getPageName(path)} </Link> </MenuItem> ] : [] ) } <Divider /> { modules.map(({ id, name }) => <MenuItem key={id}> <Link to={`/modules/${kebabCase(name)}`}> {getModuleName(name)} </Link> </MenuItem> ) } </Menu> </Paper> ) } function getPageName(path) { const components = path.split('/') return startCase(components[components.length - 2]) } " Add possibility of using apis with dashes without any workarounds,"from types import ModuleType from .resource import Resource class SelfWrapper(ModuleType): def __init__(self, self_module, baked_args={}): for attr in [""__builtins__"", ""__doc__"", ""__name__"", ""__package__""]: setattr(self, attr, getattr(self_module, attr, None)) self.__path__ = [] self.self_module = self_module self.env = globals() def __setattr__(self, name, value): if hasattr(self, ""env""): self.env[name] = value ModuleType.__setattr__(self, name, value) def __getattr__(self, name): if name == ""env"": raise AttributeError if name not in self.env: host, prefix = self._parse_name(name) self.env[name] = Resource() self.env[name].config.host = host self.env[name].config.prefix = prefix return self.env[name] def _parse_name(self, name): name = name.replace('___', '-') parts = name.split('__') host = parts[0].replace('_', '.') prefix = '/' if len(parts) > 1: prefix = '/' + parts[1].replace('_', '/') + '/' return host, prefix ","from types import ModuleType from .resource import Resource class SelfWrapper(ModuleType): def __init__(self, self_module, baked_args={}): for attr in [""__builtins__"", ""__doc__"", ""__name__"", ""__package__""]: setattr(self, attr, getattr(self_module, attr, None)) self.__path__ = [] self.self_module = self_module self.env = globals() def __setattr__(self, name, value): if hasattr(self, ""env""): self.env[name] = value ModuleType.__setattr__(self, name, value) def __getattr__(self, name): if name == ""env"": raise AttributeError if name not in self.env: host, prefix = self._parse_name(name) self.env[name] = Resource() self.env[name].config.host = host self.env[name].config.prefix = prefix return self.env[name] def _parse_name(self, name): parts = name.split('__') host = parts[0].replace('_', '.') prefix = '/' if len(parts) > 1: prefix = '/' + parts[1].replace('_', '/') + '/' return host, prefix " Add cursor according to read only state,"/** * https://github.com/Taranys/simplerating */ angular.module('SimpleRating', []) .directive('simpleRating', function () { return { restrict: 'A', template: '<ul style=""padding: 0"">' + '<li ng-repeat=""star in stars"" style=""color: #FFD700"" ng-style=""getCursor()"" class=""glyphicon"" ng-class=""getStarClass($index)"" ng-click=""click($index)""></li>' + '</ul>', scope: { rating: ""="", ratingMax: ""="", readOnly: ""="" }, link: function ($scope) { $scope.getStarClass = function (index) { return ($scope.rating >= index) ? 'glyphicon-star' : 'glyphicon-star-empty'; }; $scope.getCursor = function() { return { cursor : ($scope.readOnly?'not-allowed':'pointer') }; }; $scope.$watch('rating', function () { $scope.stars = []; for (var i = 0; i < $scope.ratingMax; i++) { $scope.stars.push({}); } }); $scope.click = function (starRating) { if (!$scope.readOnly) { $scope.rating = starRating; } }; } }; });","/** * https://github.com/Taranys/simplerating */ angular.module('SimpleRating', []) .directive('simpleRating', function () { return { restrict: 'A', template: '<ul style=""padding: 0"">' + '<li ng-repeat=""star in stars"" style=""color: #FFD700; cursor: pointer"" class=""glyphicon"" ng-class=""getStarClass($index)"" ng-click=""click($index)""></li>' + '</ul>', scope: { rating: ""="", ratingMax: ""="", readOnly: ""="" }, link: function ($scope) { $scope.getStarClass = function (index) { return ($scope.rating >= index) ? 'glyphicon-star' : 'glyphicon-star-empty'; }; $scope.$watch('rating', function () { $scope.stars = []; for (var i = 0; i < $scope.ratingMax; i++) { $scope.stars.push({}); } }); $scope.click = function (starRating) { if (!$scope.readOnly) { $scope.rating = starRating; } }; } }; });" "Use 3 rows by default in test svn changeset:16411/svn branch:6.5","package com.vaadin.tests.components.textarea; import java.util.LinkedHashMap; import com.vaadin.tests.components.abstractfield.AbstractTextFieldTest; import com.vaadin.ui.TextArea; public class TextAreaTest extends AbstractTextFieldTest<TextArea> { private Command<TextArea, Boolean> wordwrapCommand = new Command<TextArea, Boolean>() { public void execute(TextArea c, Boolean value, Object data) { c.setWordwrap(value); } }; private Command<TextArea, Integer> rowsCommand = new Command<TextArea, Integer>() { public void execute(TextArea c, Integer value, Object data) { c.setRows(value); } }; @Override protected Class<TextArea> getTestClass() { return TextArea.class; } @Override protected void createActions() { super.createActions(); createWordwrapAction(CATEGORY_FEATURES); createRowsAction(CATEGORY_FEATURES); } private void createRowsAction(String category) { LinkedHashMap<String, Integer> options = createIntegerOptions(20); createSelectAction(""Rows"", category, options, ""3"", rowsCommand); } private void createWordwrapAction(String category) { createBooleanAction(""Wordwrap"", category, false, wordwrapCommand); } } ","package com.vaadin.tests.components.textarea; import java.util.LinkedHashMap; import com.vaadin.tests.components.abstractfield.AbstractTextFieldTest; import com.vaadin.ui.TextArea; public class TextAreaTest extends AbstractTextFieldTest<TextArea> { private Command<TextArea, Boolean> wordwrapCommand = new Command<TextArea, Boolean>() { public void execute(TextArea c, Boolean value, Object data) { c.setWordwrap(value); } }; private Command<TextArea, Integer> rowsCommand = new Command<TextArea, Integer>() { public void execute(TextArea c, Integer value, Object data) { c.setRows(value); } }; @Override protected Class<TextArea> getTestClass() { return TextArea.class; } @Override protected void createActions() { super.createActions(); createWordwrapAction(CATEGORY_STATE); createRowsAction(CATEGORY_STATE); } private void createRowsAction(String category) { LinkedHashMap<String, Integer> options = createIntegerOptions(20); createSelectAction(""Rows"", category, options, ""0"", rowsCommand); } private void createWordwrapAction(String category) { createBooleanAction(""Wordwrap"", category, false, wordwrapCommand); } } " Set atom target for webpack,"var webpack = require('webpack') module.exports = { contentBase: './dist/', cache: true, inline: true, target: 'atom', entry: { app: ['webpack/hot/dev-server', './js/entry.js'] }, devtool: '#source-map', output: { path: './public/built', filename: 'bundle.js', publicPath: 'http://localhost:8080/built/', sourceMapFilename: '[file].map', stats: { colors: true } }, module: { noParse: [], loaders: [ { test: /\.js?$/, exclude: [ /node_modules/, /bower_components/, /\.min.js$/ ], loader: 'babel', query: { presets: ['react', 'es2015'] } }, { test: /\.less$/, loader: 'style-loader!css-loader!less-loader' }, { test: /\.css$/, loader: 'style-loader!css-loader' } ] }, resolve: { alias: { // The with-addons is only needed for perseus :( // example: 'react': path.resolve('node_modules/react/dist/react-with-addons.js'), }, extensions: ['', '.js', '.jsx'] }, plugins: [ new webpack.HotModuleReplacementPlugin() ], devServer: { contentBase: './public', publicPath: 'http://localhost:8080/built/' } } ","var webpack = require('webpack') module.exports = { contentBase: './dist/', cache: true, inline: true, entry: { app: ['webpack/hot/dev-server', './js/entry.js'] }, devtool: '#source-map', output: { path: './public/built', filename: 'bundle.js', publicPath: 'http://localhost:8080/built/', sourceMapFilename: '[file].map', stats: { colors: true } }, module: { noParse: [], loaders: [ { test: /\.js?$/, exclude: [ /node_modules/, /bower_components/, /\.min.js$/ ], loader: 'babel', query: { presets: ['react', 'es2015'] } }, { test: /\.less$/, loader: 'style-loader!css-loader!less-loader' }, { test: /\.css$/, loader: 'style-loader!css-loader' } ] }, resolve: { alias: { // The with-addons is only needed for perseus :( // example: 'react': path.resolve('node_modules/react/dist/react-with-addons.js'), }, extensions: ['', '.js', '.jsx'] }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.IgnorePlugin(new RegExp('^(fs|ipc)$')) ], devServer: { contentBase: './public', publicPath: 'http://localhost:8080/built/' } } " Fix the event handler input->button,"// Set up a collection to contain player information. On the server, // it is backed by a MongoDB collection named ""players"". Players = new Meteor.Collection(""players""); if (Meteor.isClient) { Template.leaderboard.players = function () { return Players.find({}, {sort: {score: -1, name: 1}}); }; Template.leaderboard.selected_name = function () { var player = Players.findOne(Session.get(""selected_player"")); return player && player.name; }; Template.player.selected = function () { return Session.equals(""selected_player"", this._id) ? ""selected"" : ''; }; Template.leaderboard.events({ 'click button.inc': function () { Players.update(Session.get(""selected_player""), {$inc: {score: 5}}); } }); Template.player.events({ 'click': function () { Session.set(""selected_player"", this._id); } }); } // On server startup, create some players if the database is empty. if (Meteor.isServer) { Meteor.startup(function () { if (Players.find().count() === 0) { var names = [""Ada Lovelace"", ""Grace Hopper"", ""Marie Curie"", ""Carl Friedrich Gauss"", ""Nikola Tesla"", ""Claude Shannon""]; for (var i = 0; i < names.length; i++) Players.insert({name: names[i], score: Math.floor(Random.fraction()*10)*5}); } }); } ","// Set up a collection to contain player information. On the server, // it is backed by a MongoDB collection named ""players"". Players = new Meteor.Collection(""players""); if (Meteor.isClient) { Template.leaderboard.players = function () { return Players.find({}, {sort: {score: -1, name: 1}}); }; Template.leaderboard.selected_name = function () { var player = Players.findOne(Session.get(""selected_player"")); return player && player.name; }; Template.player.selected = function () { return Session.equals(""selected_player"", this._id) ? ""selected"" : ''; }; Template.leaderboard.events({ 'click input.inc': function () { Players.update(Session.get(""selected_player""), {$inc: {score: 5}}); } }); Template.player.events({ 'click': function () { Session.set(""selected_player"", this._id); } }); } // On server startup, create some players if the database is empty. if (Meteor.isServer) { Meteor.startup(function () { if (Players.find().count() === 0) { var names = [""Ada Lovelace"", ""Grace Hopper"", ""Marie Curie"", ""Carl Friedrich Gauss"", ""Nikola Tesla"", ""Claude Shannon""]; for (var i = 0; i < names.length; i++) Players.insert({name: names[i], score: Math.floor(Random.fraction()*10)*5}); } }); } " Make use of slots to reduce in-memory size,"# # Jasy - JavaScript Tooling Refined # Copyright 2010 Sebastian Werner # class MetaData: """""" Data structure to hold all dependency information Hint: Must be a clean data class without links to other systems for optiomal cachability using Pickle """""" __slots__ = [""provides"", ""requires"", ""optionals"", ""breaks"", ""assets""] def __init__(self, tree): self.provides = set() self.requires = set() self.optionals = set() self.breaks = set() self.assets = set() self.__inspect(tree) def __inspect(self, node): """""" The internal inspection routine """""" # Parse comments try: comments = node.comments except AttributeError: comments = None if comments: for comment in comments: commentTags = comment.getTags() if commentTags: if ""provide"" in commentTags: self.provides.update(set(commentTags[""provide""])) if ""require"" in commentTags: self.requires.update(set(commentTags[""require""])) if ""optional"" in commentTags: self.optionals.update(set(commentTags[""optional""])) if ""break"" in commentTags: self.breaks.update(set(commentTags[""break""])) if ""asset"" in commentTags: self.assets.update(set(commentTags[""asset""])) # Process children for child in node: self.__inspect(child) ","# # Jasy - JavaScript Tooling Refined # Copyright 2010 Sebastian Werner # class MetaData: """""" Data structure to hold all dependency information Hint: Must be a clean data class without links to other systems for optiomal cachability using Pickle """""" def __init__(self, tree): self.provides = set() self.requires = set() self.optionals = set() self.breaks = set() self.assets = set() self.__inspect(tree) def __inspect(self, node): """""" The internal inspection routine """""" # Parse comments try: comments = node.comments except AttributeError: comments = None if comments: for comment in comments: commentTags = comment.getTags() if commentTags: if ""provide"" in commentTags: self.provides.update(set(commentTags[""provide""])) if ""require"" in commentTags: self.requires.update(set(commentTags[""require""])) if ""optional"" in commentTags: self.optionals.update(set(commentTags[""optional""])) if ""break"" in commentTags: self.breaks.update(set(commentTags[""break""])) if ""asset"" in commentTags: self.assets.update(set(commentTags[""asset""])) # Process children for child in node: self.__inspect(child) " Add test on render method,"import re from django.conf import settings from django.test import TestCase from localized_fields.value import LocalizedValue from localized_fields.widgets import LocalizedFieldWidget class LocalizedFieldWidgetTestCase(TestCase): """"""Tests the workings of the :see:LocalizedFieldWidget class."""""" @staticmethod def test_widget_creation(): """"""Tests whether a widget is created for every language correctly."""""" widget = LocalizedFieldWidget() assert len(widget.widgets) == len(settings.LANGUAGES) @staticmethod def test_decompress(): """"""Tests whether a :see:LocalizedValue instance can correctly be ""decompressed"" over the available widgets."""""" localized_value = LocalizedValue() for lang_code, lang_name in settings.LANGUAGES: localized_value.set(lang_code, lang_name) widget = LocalizedFieldWidget() decompressed_values = widget.decompress(localized_value) for (lang_code, _), value in zip(settings.LANGUAGES, decompressed_values): assert localized_value.get(lang_code) == value @staticmethod def test_decompress_none(): """"""Tests whether the :see:LocalizedFieldWidget correctly handles :see:None."""""" widget = LocalizedFieldWidget() decompressed_values = widget.decompress(None) for _, value in zip(settings.LANGUAGES, decompressed_values): assert not value @staticmethod def test_render(): """"""Tests whether the :see:LocalizedFieldWidget correctly render."""""" widget = LocalizedFieldWidget() output = widget.render(name='title', value=None) assert bool(re.search('<label (.|\n|\t)*>\w+<\/label>', output)) ","from django.conf import settings from django.test import TestCase from localized_fields.value import LocalizedValue from localized_fields.widgets import LocalizedFieldWidget class LocalizedFieldWidgetTestCase(TestCase): """"""Tests the workings of the :see:LocalizedFieldWidget class."""""" @staticmethod def test_widget_creation(): """"""Tests whether a widget is created for every language correctly."""""" widget = LocalizedFieldWidget() assert len(widget.widgets) == len(settings.LANGUAGES) @staticmethod def test_decompress(): """"""Tests whether a :see:LocalizedValue instance can correctly be ""decompressed"" over the available widgets."""""" localized_value = LocalizedValue() for lang_code, lang_name in settings.LANGUAGES: localized_value.set(lang_code, lang_name) widget = LocalizedFieldWidget() decompressed_values = widget.decompress(localized_value) for (lang_code, _), value in zip(settings.LANGUAGES, decompressed_values): assert localized_value.get(lang_code) == value @staticmethod def test_decompress_none(): """"""Tests whether the :see:LocalizedFieldWidget correctly handles :see:None."""""" widget = LocalizedFieldWidget() decompressed_values = widget.decompress(None) for _, value in zip(settings.LANGUAGES, decompressed_values): assert not value " Update QR Code on textbox keyup,"document.addEventListener(""DOMContentLoaded"", function () { var qr_cellsize = 8; var qr_margin = 2 * qr_cellsize; var qr_levels = [""M"", ""L""]; var createImage = function(payload) { for (var levelIndex in qr_levels) { for (var typeNum = 1; typeNum <= 10; typeNum++) { try { var qr = qrcode(typeNum, qr_levels[levelIndex]); qr.addData(payload); qr.make(); return qr.createImgTag(qr_cellsize, qr_margin); } catch(e) { if (strStartsWith(e.message, ""code length overflow"")) { // ignore and try to use bigger QR code format } else { throw e; } } } } }; var updateImage = function() { payload = document.getElementById(""textbox"").value; document.getElementById(""insert-qrcode-here"").innerHTML = createImage(payload) || ""Error. URL too long?""; }; var strStartsWith = function(string, prefix) { return !string.indexOf(prefix); }; document.getElementById(""close"").onclick = function() { window.close(); }; document.getElementById(""textbox"").onchange = function() { updateImage(); }; document.getElementById(""textbox"").onkeyup = function() { updateImage(); }; document.getElementById(""textbox"").onclick = function() { this.select(); }; chrome.tabs.getSelected(null, function(tab) { document.getElementById(""textbox"").value = tab.url; document.getElementById(""textbox"").select(); updateImage(); }); }); ","document.addEventListener(""DOMContentLoaded"", function () { var qr_cellsize = 8; var qr_margin = 2 * qr_cellsize; var qr_levels = [""M"", ""L""]; var createImage = function(payload) { for (var levelIndex in qr_levels) { for (var typeNum = 1; typeNum <= 10; typeNum++) { try { var qr = qrcode(typeNum, qr_levels[levelIndex]); qr.addData(payload); qr.make(); return qr.createImgTag(qr_cellsize, qr_margin); } catch(e) { if (strStartsWith(e.message, ""code length overflow"")) { // ignore and try to use bigger QR code format } else { throw e; } } } } }; var updateImage = function() { payload = document.getElementById(""textbox"").value; document.getElementById(""insert-qrcode-here"").innerHTML = createImage(payload) || ""Error. URL too long?""; }; var strStartsWith = function(string, prefix) { return !string.indexOf(prefix); }; document.getElementById(""close"").onclick = function() { window.close(); }; document.getElementById(""textbox"").onchange = function() { updateImage(); }; document.getElementById(""textbox"").onclick = function() { this.select(); }; chrome.tabs.getSelected(null, function(tab) { document.getElementById(""textbox"").value = tab.url; document.getElementById(""textbox"").select(); updateImage(); }); }); " Support -'s in github repo and owner name,"from django.conf.urls import url from metaci.repository import views as repository_views urlpatterns = [ url( r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/branch/(?P<branch>.*)$', repository_views.branch_detail, name='branch_detail', ), url( r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/commit/(?P<sha>\w+)$', repository_views.commit_detail, name='commit_detail', ), url( r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/branches', repository_views.repo_branches, name='repo_branches', ), url( r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/plans', repository_views.repo_plans, name='repo_plans', ), url( r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/orgs', repository_views.repo_orgs, name='repo_orgs', ), url( r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/*$', repository_views.repo_detail, name='repo_detail', ), url( r'webhook/github/push$', repository_views.github_push_webhook, name='github_push_webhook', ), url( r'$', repository_views.repo_list, name='repo_list', ), ] ","from django.conf.urls import url from metaci.repository import views as repository_views urlpatterns = [ url( r'(?P<owner>\w+)/(?P<name>[^/].*)/branch/(?P<branch>.*)$', repository_views.branch_detail, name='branch_detail', ), url( r'(?P<owner>\w+)/(?P<name>[^/].*)/commit/(?P<sha>\w+)$', repository_views.commit_detail, name='commit_detail', ), url( r'(?P<owner>\w+)/(?P<name>[^/].*)/branches', repository_views.repo_branches, name='repo_branches', ), url( r'(?P<owner>\w+)/(?P<name>[^/].*)/plans', repository_views.repo_plans, name='repo_plans', ), url( r'(?P<owner>\w+)/(?P<name>[^/].*)/orgs', repository_views.repo_orgs, name='repo_orgs', ), url( r'(?P<owner>\w+)/(?P<name>[^/].*)/*$', repository_views.repo_detail, name='repo_detail', ), url( r'webhook/github/push$', repository_views.github_push_webhook, name='github_push_webhook', ), url( r'$', repository_views.repo_list, name='repo_list', ), ] " Remove closures from Expression language,"<?php namespace Heyday\CacheInclude; use Symfony\Component\ExpressionLanguage\ExpressionLanguage as SymfonyExpressionLanguage; /** * Class ExpressionLanguage * @package Heyday\CacheInclude */ class ExpressionLanguage extends SymfonyExpressionLanguage implements \Serializable { protected function registerFunctions() { parent::registerFunctions(); $this->register( 'list', function ($arg) { return sprintf('%s::get()', $arg); }, function (array $variables, $value) { return \DataList::create($value); } ); $this->register( 'instanceof', function ($arg0, $arg1) { return sprintf('%s instanceof %s', $arg0, $arg1); }, function (array $variables, $arg0, $arg1) { return $arg0 instanceof $arg1; } ); } /** * @return null */ public function serialize() { return null; } /** * @param string $serialized */ public function unserialize($serialized) { $this->__construct(); } } ","<?php namespace Heyday\CacheInclude; use Symfony\Component\ExpressionLanguage\ExpressionLanguage as SymfonyExpressionLanguage; /** * Class ExpressionLanguage * @package Heyday\CacheInclude */ class ExpressionLanguage extends SymfonyExpressionLanguage { protected function registerFunctions() { parent::registerFunctions(); $this->register( 'list', array($this, 'listCompiler'), array($this, 'listEvaluator') ); $this->register( 'instanceof', array($this, 'instanceofCompiler'), array($this, 'instanceofEvaluator') ); } /** * @param $arg * @return string */ public function listCompiler($arg) { return sprintf('%s::get()', $arg); } /** * @param array $variables * @param $value * @return static */ public function listEvaluator(array $variables, $value) { return \DataList::create($value); } /** * @param $arg0 * @param $arg1 * @return string */ public function instanceofCompiler($arg0, $arg1) { return sprintf('%s instanceof %s', $arg0, $arg1); } /** * @param array $variables * @param $arg0 * @param $arg1 * @return bool */ public function instanceofEvaluator(array $variables, $arg0, $arg1) { return $arg0 instanceof $arg1; } }" Add missing import in unit test file.,"package es.tid.ps.mobility.jobs; import static org.junit.Assert.assertEquals; import org.junit.Test; import es.tid.ps.mobility.data.BaseProtocol.Date; import es.tid.ps.mobility.data.BaseProtocol.Time; import es.tid.ps.mobility.data.MxCdrUtil; import es.tid.ps.mobility.parser.CdrParser; /** * * @author sortega */ public class CdrParserTest { @Test public void testParse() throws Exception { CdrParser parser = new CdrParser(""33F430521676F4|2221436242|"" + ""33F430521676F4|0442224173253|2|01/01/2010|02:00:01|2891|RMITERR""); assertEquals(MxCdrUtil.create(2221436242L, 0x521676f4, Date.newBuilder() .setDay(1) .setMonth(1) .setYear(10) .setWeekDay(5) .build(), Time.newBuilder() .setHour(2) .setMinute(0) .setSeconds(1) .build()), parser.parse()); } } ","package es.tid.ps.mobility.jobs; import static org.junit.Assert.assertEquals; import org.junit.Test; import es.tid.ps.mobility.data.BaseProtocol.Date; import es.tid.ps.mobility.data.BaseProtocol.Time; import es.tid.ps.mobility.data.MxCdrUtil; /** * * @author sortega */ public class CdrParserTest { @Test public void testParse() throws Exception { CdrParser parser = new CdrParser(""33F430521676F4|2221436242|"" + ""33F430521676F4|0442224173253|2|01/01/2010|02:00:01|2891|RMITERR""); assertEquals(MxCdrUtil.create(2221436242L, 0x521676f4, Date.newBuilder() .setDay(1) .setMonth(1) .setYear(10) .setWeekDay(5) .build(), Time.newBuilder() .setHour(2) .setMinute(0) .setSeconds(1) .build()), parser.parse()); } } " Update to follow Airbnb style standards,"import Ember from 'ember'; export default Ember.Component.extend({ showSettings: false, showLayer : true, didReceiveAttrs() { this._super(...arguments); if(this.get('layer').component === 'layer-title'){ this.set('showLayer', false); }else{ this.set('showLayer', true); } }, theme: Ember.computed('themes', 'layer.settings.properties.themeId', function(){ return this.get('themes').filter((item)=>{ return item.id === this.get('layer.settings.properties.themeId'); })[0]; }), lastIndex: Ember.computed('layers',function (){ return this.get('layers').length-1; }), actions: { showSettings (){ this.set('showSettings', true); }, moveBefore(index){ let layers = this.get('layers'); let removed = layers.objectAt(index); layers.insertAt(index-1, removed); layers.removeAt(index+1); }, moveAfter(index){ let layers = this.get('layers'); let removed = layers.objectAt(index); layers.insertAt(index+2, removed); layers.removeAt(index); } } }); ","import Ember from 'ember'; export default Ember.Component.extend({ showSettings: false, showLayer : true, didReceiveAttrs() { this._super(...arguments); if(this.get(""layer"").component === ""layer-title""){ this.set('showLayer', false); }else{ this.set('showLayer', true); } }, theme: Ember.computed('themes', 'layer.settings.properties.themeId', function(){ return this.get('themes').filter((item)=>{ return item.id === this.get('layer.settings.properties.themeId'); })[0]; }), lastIndex: Ember.computed('layers',function (){ return this.get('layers').length-1; }), actions: { showSettings (){ this.set('showSettings', true); }, moveBefore(index){ let layers = this.get('layers'); let removed = layers.objectAt(index); layers.insertAt(index-1, removed); layers.removeAt(index+1); }, moveAfter(index){ let layers = this.get('layers'); let removed = layers.objectAt(index); layers.insertAt(index+2, removed); layers.removeAt(index); } } }); " Fix serialization bug in CSVKitWriter that was breaking 4 tests.,"#!/usr/bin/env python from csvkit.unicsv import UnicodeCSVReader, UnicodeCSVWriter class CSVKitReader(UnicodeCSVReader): """""" A unicode-aware CSV reader with some additional features. """""" pass class CSVKitWriter(UnicodeCSVWriter): """""" A unicode-aware CSV writer with some additional features. """""" def __init__(self, f, encoding='utf-8', line_numbers=False, **kwargs): self.row_count = 0 self.line_numbers = line_numbers UnicodeCSVWriter.__init__(self, f, encoding, lineterminator='\n', **kwargs) def _append_line_number(self, row): if self.row_count == 0: row.insert(0, 'line_number') else: row.insert(0, self.row_count) self.row_count += 1 def writerow(self, row): if self.line_numbers: row = list(row) self._append_line_number(row) # Convert embedded Mac line endings to unix style line endings so they get quoted row = [i.replace('\r', '\n') if isinstance(i, basestring) else i for i in row] UnicodeCSVWriter.writerow(self, row) def writerows(self, rows): for row in rows: self.writerow(row) ","#!/usr/bin/env python from csvkit.unicsv import UnicodeCSVReader, UnicodeCSVWriter class CSVKitReader(UnicodeCSVReader): """""" A unicode-aware CSV reader with some additional features. """""" pass class CSVKitWriter(UnicodeCSVWriter): """""" A unicode-aware CSV writer with some additional features. """""" def __init__(self, f, encoding='utf-8', line_numbers=False, **kwargs): self.row_count = 0 self.line_numbers = line_numbers UnicodeCSVWriter.__init__(self, f, encoding, lineterminator='\n', **kwargs) def _append_line_number(self, row): if self.row_count == 0: row.insert(0, 'line_number') else: row.insert(0, self.row_count) self.row_count += 1 def writerow(self, row): if self.line_numbers: row = list(row) self._append_line_number(row) # Convert embedded Mac line endings to unix style line endings so they get quoted row = [i.replace('\r', '\n') for i in row] UnicodeCSVWriter.writerow(self, row) def writerows(self, rows): for row in rows: self.writerow(row) " Fix CPP problem on Linux,"''' Functions dealing with the compilation of code. ''' from .exceptions import ValidatorBrokenException import logging logger = logging.getLogger('opensubmitexec') GCC = ['gcc', '-o', '{output}', '{inputs}'] GPP = ['g++', '-pthread', '-o', '{output}', '{inputs}'] def compiler_cmdline(compiler=GCC, output=None, inputs=None): cmdline = [] for element in compiler: if element == '{output}': if output: cmdline.append(output) else: logger.error('Compiler output name is needed, but not given.') raise ValidatorBrokenException(""You need to declare the output name for this compiler."") elif element == '{inputs}': if inputs: for fname in inputs: if compiler in [GCC, GPP] and fname.endswith('.h'): logger.debug('Omitting {0} in the compiler call.'.format(fname)) else: cmdline.append(fname) else: logger.error('Input file names for compiler are not given.') raise ValidatorBrokenException('You need to declare input files for this compiler.') else: cmdline.append(element) return cmdline[0], cmdline[1:] ","''' Functions dealing with the compilation of code. ''' from .exceptions import ValidatorBrokenException import logging logger = logging.getLogger('opensubmitexec') GCC = ['gcc', '-o', '{output}', '{inputs}'] GPP = ['g++', '-o', '{output}', '{inputs}'] def compiler_cmdline(compiler=GCC, output=None, inputs=None): cmdline = [] for element in compiler: if element == '{output}': if output: cmdline.append(output) else: logger.error('Compiler output name is needed, but not given.') raise ValidatorBrokenException(""You need to declare the output name for this compiler."") elif element == '{inputs}': if inputs: for fname in inputs: if compiler in [GCC, GPP] and fname.endswith('.h'): logger.debug('Omitting {0} in the compiler call.'.format(fname)) else: cmdline.append(fname) else: logger.error('Input file names for compiler are not given.') raise ValidatorBrokenException('You need to declare input files for this compiler.') else: cmdline.append(element) return cmdline[0], cmdline[1:] " Fix getAll returning an empty collection,"define(function (require) { ""use strict""; var React = require('react/addons'), Router = require('react-router'), stores = require('stores'), ResourceRequest = require('./ResourceRequest.react'), RouteHandler = Router.RouteHandler; return React.createClass({ mixins: [Router.State], render: function () { var requests = stores.ResourceRequestStore.fetchWhere({ 'status__name': 'pending' }), statuses = stores.StatusStore.getAll(); if (!requests || !statuses) return <div className=""loading""></div>; var resourceRequestRows = requests.map(function (request) { return ( <ResourceRequest key={request.id} request={request}/> ) }); if (!resourceRequestRows[0]) { return ( <div> <h3>No resource requests</h3> </div> ); } return ( <div className=""resource-master""> <h1>Resource Requests</h1> <ul className=""requests""> <li> <h3>User</h3> <h3>Request</h3> <h3>Description</h3> </li> {resourceRequestRows} </ul> <RouteHandler /> </div> ); } }); }); ","define(function (require) { ""use strict""; var React = require('react/addons'), Router = require('react-router'), stores = require('stores'), ResourceRequest = require('./ResourceRequest.react'), RouteHandler = Router.RouteHandler; return React.createClass({ mixins: [Router.State], render: function () { var requests = stores.ResourceRequestStore.fetchWhere({ 'status__name': 'pending' }), statuses = stores.StatusStore.getAll(); if (!requests || !statuses) return <div className=""loading""></div>; requests = stores.ResourceRequestStore.getAll(); var resourceRequestRows = requests.map(function (request) { return ( <ResourceRequest key={request.id} request={request}/> ) }); if (!resourceRequestRows[0]) { return ( <div> <h3>No resource requests</h3> </div> ); } return ( <div className=""resource-master""> <h1>Resource Requests</h1> <ul className=""requests""> <li> <h3>User</h3> <h3>Request</h3> <h3>Description</h3> </li> {resourceRequestRows} </ul> <RouteHandler /> </div> ); } }); }); " Remove gis dependency in admin,"from django.conf.urls import patterns, include, url from django.views.generic import TemplateView from . import resources, views # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'project.views.home', name='home'), # url(r'^project/', include('project.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), url(r'^$', TemplateView.as_view(template_name='index.html'), name='home'), url(r'^ratings/$', resources.RatingListView.as_view(), name='rating_list'), url(r'^ratings/(?P<id>\d+)$', resources.RatingInstanceView.as_view(), name='rating_instance'), url(r'^survey_session$', resources.SurveySessionView.as_view(), name='survey_session_instance'), url(r'^survey_sessions/$', resources.SurveySessionListView.as_view(), name='survey_session_list'), url(r'^block_ratings/$', resources.BlockRatingListView.as_view(), name='block_rating_list'), url(r'^data/?$', views.csv_data, name='data_csv_list'), ) ","from django.conf.urls import patterns, include, url from django.views.generic import TemplateView from . import resources, views # Uncomment the next two lines to enable the admin: from django.contrib.gis import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'project.views.home', name='home'), # url(r'^project/', include('project.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), url(r'^$', TemplateView.as_view(template_name='index.html'), name='home'), url(r'^ratings/$', resources.RatingListView.as_view(), name='rating_list'), url(r'^ratings/(?P<id>\d+)$', resources.RatingInstanceView.as_view(), name='rating_instance'), url(r'^survey_session$', resources.SurveySessionView.as_view(), name='survey_session_instance'), url(r'^survey_sessions/$', resources.SurveySessionListView.as_view(), name='survey_session_list'), url(r'^block_ratings/$', resources.BlockRatingListView.as_view(), name='block_rating_list'), url(r'^data/?$', views.csv_data, name='data_csv_list'), ) " Enforce that defaultProps sit next to statics,"module.exports = { 'root': true, 'parser': 'babel-eslint', 'extends': [ 'airbnb', 'plugin:import/errors' ], 'rules': { 'space-before-function-paren': 0, 'comma-dangle': [2, 'never'], 'one-var': 0, 'one-var-declaration-per-line': 0, 'prefer-arrow-callback': 0, 'strict': 0, 'no-use-before-define': [2, {'functions': false}], 'no-underscore-dangle': 0, 'react/wrap-multilines': 0, 'react/prefer-stateless-function': 0, 'react/jsx-first-prop-new-line': 0, 'react/jsx-no-bind': 0, 'react/sort-comp': [2, { order: [ 'displayName', 'propTypes', 'mixins', 'statics', 'getDefaultProps', 'defaultProps', 'getInitialState', 'constructor', 'render', '/^_render.+$/', // any auxiliary _render methods 'componentWillMount', 'componentDidMount', 'componentWillReceiveProps', 'shouldComponentUpdate', 'componentWillUpdate', 'componentDidUpdate', 'componentWillUnmount', '/^on[A-Z].+$/', // event handlers 'everything-else', '/^_.+$/' // private methods ] }] } } ","module.exports = { 'root': true, 'parser': 'babel-eslint', 'extends': [ 'airbnb', 'plugin:import/errors' ], 'rules': { 'space-before-function-paren': 0, 'comma-dangle': [2, 'never'], 'one-var': 0, 'one-var-declaration-per-line': 0, 'prefer-arrow-callback': 0, 'strict': 0, 'no-use-before-define': [2, {'functions': false}], 'no-underscore-dangle': 0, 'react/wrap-multilines': 0, 'react/prefer-stateless-function': 0, 'react/jsx-first-prop-new-line': 0, 'react/jsx-no-bind': 0, 'react/sort-comp': [2, { order: [ 'displayName', 'propTypes', 'mixins', 'statics', 'getDefaultProps', 'getInitialState', 'constructor', 'render', '/^_render.+$/', // any auxiliary _render methods 'componentWillMount', 'componentDidMount', 'componentWillReceiveProps', 'shouldComponentUpdate', 'componentWillUpdate', 'componentDidUpdate', 'componentWillUnmount', '/^on[A-Z].+$/', // event handlers 'everything-else', '/^_.+$/' // private methods ] }] } } " Fix bug. Remove console logs.,"/** * Created by tshen on 16/7/15. */ 'use strict' import {NativeModules} from 'react-native'; const NativeSimpleFetch = NativeModules.SimpleFetch; const fetch = function (url, options) { const params = { url: url, method: options.method ? options.method.toUpperCase() : 'GET', headers: options.headers, timeout: 10000, body: options.body, gzipRequest: true }; return NativeSimpleFetch.sendRequest(params).then((res)=> { const status = parseInt(res[0]); const body = res[1]; return { ok: statusCode >= 200 && statusCode <= 300, status: status, json: ()=> { return new Promise((resolve, reject)=> { try { let obj = JSON.parse(body); resolve(obj); } catch (e) { if (typeof body === 'string') { resolve(body); } else { reject(e); } } }); } }; }); }; module.exports = { fetch };","/** * Created by tshen on 16/7/15. */ 'use strict' import {NativeModules} from 'react-native'; const NativeSimpleFetch = NativeModules.SimpleFetch; const fetch = function (url, options) { const params = { url: url, method: options.method ? options.method.toUpperCase() : 'GET', headers: options.headers, timeout: 10000, body: options.body, gzipRequest: true }; console.log(params); return NativeSimpleFetch.sendRequest(params).then((res)=> { console.log(res); const statusCode = parseInt(res[0]); const body = res[1]; return { ok: statusCode >= 200 && statusCode <= 300, status: statusCode, json: ()=> { return new Promise((resolve, reject)=> { try { let obj = JSON.parse(body); resolve(obj); } catch (e) { if (typeof body === 'string') { resolve(body); } else { reject(e); } } }); } }; }, (err)=> { console.log(err); return err; }); }; module.exports = { fetch };" "Drop features removed in Django 2.0 Field.rel and Field.remote_field.to are removed https://docs.djangoproject.com/en/dev/releases/2.0/#features-removed-in-2-0","# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-01-29 16:12 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('contenttypes', '0002_remove_content_type_name'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Like', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('receiver_object_id', models.PositiveIntegerField()), ('timestamp', models.DateTimeField(default=django.utils.timezone.now)), ('receiver_content_type', models.ForeignKey('contenttypes.ContentType', on_delete=django.db.models.deletion.CASCADE)), ('sender', models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=django.db.models.deletion.CASCADE, related_name='liking')), ], ), migrations.AlterUniqueTogether( name='like', unique_together=set([('sender', 'receiver_content_type', 'receiver_object_id')]), ), ] ","# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-01-29 16:12 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('contenttypes', '0002_remove_content_type_name'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Like', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('receiver_object_id', models.PositiveIntegerField()), ('timestamp', models.DateTimeField(default=django.utils.timezone.now)), ('receiver_content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')), ('sender', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='liking', to=settings.AUTH_USER_MODEL)), ], ), migrations.AlterUniqueTogether( name='like', unique_together=set([('sender', 'receiver_content_type', 'receiver_object_id')]), ), ] " Add support for emails notifications,"<?php namespace App\Controllers; use App\Entities\Lead; class LeadController extends BaseController { /** * Validations rules to $_POST data * @var [array] */ protected $rules = [ 'required' => [ ['name'], ['email'], ], 'lengthMin' => [ ['name', 3], ], 'email' => 'email', ]; /** * Input labels * @var array */ protected $labels = [ 'name' => 'Name', 'email' => 'Email', ]; public function store($request, $response) { $lead = new Lead(); $lead->name = $request->getParam('name'); $lead->email = $request->getParam('email'); $lead->date = date('Y-m-d H:i:s'); if (!$lead->isRegistered($lead->email)) { $lead->save(); } sendEmail($lead->email, $lead->name, getenv('LEAD_EMAIL_SUBJECT'), 'lead', $lead); sendEmail(getenv('ADMIN_EMAIL'), 'Edwin Ramírez', getenv('LEAD_EMAIL_SUBJECT'), 'admin', $lead); return $response->withRedirect('/thanks', 301); } } ","<?php namespace App\Controllers; use App\Entities\Lead; use Core\Controllers\EmailController as Email; use Symfony\Component\VarDumper\Dumper\DataDumperInterface; class LeadController extends BaseController { /** * Validations rules to $_POST data * @var [array] */ protected $rules = [ 'required' => [ ['name'], ['email'], ], 'lengthMin' => [ ['name', 3], ], 'email' => 'email', ]; /** * Input labels * @var array */ protected $labels = [ 'name' => 'Name', 'email' => 'Email', ]; public function store($request, $response) { //$errors = $this->validate($_POST, $this->rules, $this->labels); /* if ($errors) { return view('home.twig', compact('errors')); }*/ $lead = new Lead(); $lead->name = $request->getParam('name'); $lead->email = $request->getParam('email'); $lead->date = date('Y-m-d H:i:s'); if (!$lead->isRegistered($lead->email)) { $lead->save(); } return $response->withRedirect('/thanks', 301); } /** * Route params example * if the path has parameters, the $ response parameter is required as the first method argument * @param $response * @param $name */ public function search($response, $name) { dd($name); } } " Remove merges from the log.,"#! /usr/bin/env python import argparse import csv import git if __name__ == '__main__': parser = argparse.ArgumentParser(description='Extract git history information.') parser.add_argument('-f', '--from', dest='from_', help='from revno') parser.add_argument('-t', '--to', help='to revno') parser.add_argument('-l', '--limit', help='max number of commits') parser.add_argument('-p', '--project', help='project directory') parser.add_argument('-c', '--csv', help='csv file name') args = parser.parse_args() if not args.csv or not args.project: parser.print_help() exit(1) with open(args.csv, 'w') as csvfile: csvwriter = csv.writer(csvfile, delimiter=',', quotechar='""', doublequote=True) repo = git.Repo(args.project) if args.limit: iter_ = repo.iter_commits(args.from_, max_count=args.limit, no_merges=True) else: iter_ = repo.iter_commits(args.from_, no_merges=True) for commit in iter_: if commit.hexsha == args.to: break summary = commit.summary.encode('utf-8') message = commit.message.encode('utf-8') stats = commit.stats.total csvwriter.writerow((summary, message, commit.hexsha, stats['files'], stats['lines'], stats['insertions'], stats['deletions'])) ","#! /usr/bin/env python import argparse import csv import git if __name__ == '__main__': parser = argparse.ArgumentParser(description='Extract git history information.') parser.add_argument('-f', '--from', dest='from_', help='from revno') parser.add_argument('-t', '--to', help='to revno') parser.add_argument('-l', '--limit', help='max number of commits') parser.add_argument('-p', '--project', help='project directory') parser.add_argument('-c', '--csv', help='csv file name') args = parser.parse_args() if not args.csv or not args.project: parser.print_help() exit(1) with open(args.csv, 'w') as csvfile: csvwriter = csv.writer(csvfile, delimiter='\t', quotechar='|') repo = git.Repo(args.project) if args.limit: iter_ = repo.iter_commits(args.from_, max_count=args.limit) else: iter_ = repo.iter_commits(args.from_) for commit in iter_: if commit.hexsha == args.to: break summary = commit.summary.encode('utf-8') message = commit.message.encode('utf-8') stats = commit.stats.total csvwriter.writerow((summary, message, stats['files'], stats['lines'], stats['insertions'], stats['deletions'])) " Substitute a more realistic jurisdiction_id,"from pupa.scrape import Jurisdiction from .people import PersonScraper class Example(Jurisdiction): jurisdiction_id = 'ocd-jurisdiction/country:us/state:ex/place:example' def get_metadata(self): return { 'name': 'Example', 'legislature_name': 'Example Legislature', 'legislature_url': 'http://example.com', 'terms': [{ 'name': '2013-2014', 'sessions': ['2013'], 'start_year': 2013, 'end_year': 2014 }], 'provides': ['people'], 'parties': [ {'name': 'Independent' }, {'name': 'Green' }, {'name': 'Bull-Moose'} ], 'session_details': { '2013': {'_scraped_name': '2013'} }, 'feature_flags': [], } def get_scraper(self, term, session, scraper_type): if scraper_type == 'people': return PersonScraper def scrape_session_list(self): return ['2013'] ","from pupa.scrape import Jurisdiction from .people import PersonScraper class Example(Jurisdiction): jurisdiction_id = 'ex' def get_metadata(self): return { 'name': 'Example', 'legislature_name': 'Example Legislature', 'legislature_url': 'http://example.com', 'terms': [{ 'name': '2013-2014', 'sessions': ['2013'], 'start_year': 2013, 'end_year': 2014 }], 'provides': ['people'], 'parties': [ {'name': 'Independent' }, {'name': 'Green' }, {'name': 'Bull-Moose'} ], 'session_details': { '2013': {'_scraped_name': '2013'} }, 'feature_flags': [], } def get_scraper(self, term, session, scraper_type): if scraper_type == 'people': return PersonScraper def scrape_session_list(self): return ['2013'] " "Create and set model association objects in the initialize method, instead of in the parse method.","define([ 'underscore', 'backbone', 'models/profile', 'models/address', 'collections/item' ], function (_, Backbone, Profile, Address, ItemCollection) { 'use strict'; var ResumeModel = Backbone.Model.extend({ defaults: { name: '' }, hasOne: ['profile', 'address'], hasMany: ['items'], initialize: function(attributes, options) { var options = { resumeId: this.id }; this.set('address', new Address(attributes.address, options)); this.set('profile', new Profile(attributes.profile, options)); this.set('items', new ItemCollection(attributes.items, options)); }, parse: function(response) { if (response.resume) { return response.resume; } else { return response; } }, toJSON: function() { var json = JSON.parse(JSON.stringify(this.attributes)); // has one associations _.each(this.hasOne, function(assoc) { json[assoc + '_id'] = this.get(assoc).id; delete json[assoc]; }, this); // has many associations _.each(this.hasMany, function(assoc) { var singular = assoc.substring(0, assoc.length - 1); json[singular + '_ids'] = this.get(assoc).map(function(item) { return item.id; }); delete json[assoc]; }, this); return { resume: json }; } }); return ResumeModel; }); ","define([ 'underscore', 'backbone', 'models/profile', 'models/address', 'collections/item' ], function (_, Backbone, Profile, Address, ItemCollection) { 'use strict'; var ResumeModel = Backbone.Model.extend({ defaults: { name: '' }, hasOne: ['profile', 'address'], hasMany: ['items'], parse: function(response) { var r; if (response.resume) { r = response.resume; } else { r = response; } var options = { resumeId: this.id }; r.address = new Address(r.address, options); r.profile = new Profile(r.profile, options); r.items = new ItemCollection(r.items, options); return r; }, toJSON: function() { var json = JSON.parse(JSON.stringify(this.attributes)); // has one associations _.each(this.hasOne, function(assoc) { json[assoc + '_id'] = this.get(assoc).id; delete json[assoc]; }, this); // has many associations _.each(this.hasMany, function(assoc) { var singular = assoc.substring(0, assoc.length - 1); json[singular + '_ids'] = this.get(assoc).map(function(item) { return item.id; }); delete json[assoc]; }, this); return { resume: json }; } }); return ResumeModel; }); " Add errors attribute with setter/getter,"__version__ = (2014, 10, 0) def get_version(): """""" :rtype: str """""" return '.'.join(str(i) for i in __version__) class Gignore(object): BASE_URL = 'https://raw.githubusercontent.com/github/gitignore/master/' name = None file_content = None valid = True errors = [] def get_base_url(self): """""" :rtype: str """""" return self.BASE_URL def set_name(self, name): """""" :type name: str """""" self.name = name def get_name(self): """""" :rtype: str """""" return self.name def set_file_content(self, file_content): """""" :type file_content: str """""" self.file_content = file_content def get_file_content(self): """""" :rtype: str """""" return self.file_content def is_valid(self): """""" :rtype: bool """""" return self.valid def set_valid(self, valid): """""" :type valid: bool """""" self.valid = valid def add_error(self, error_message): """""" :type error_message: str """""" self.errors.append(error_message) def get_errors(self): """""" :rtype: list of str """""" return self.errors ","__version__ = (2014, 10, 0) def get_version(): """""" :rtype: str """""" return '.'.join(str(i) for i in __version__) class Gignore(object): BASE_URL = 'https://raw.githubusercontent.com/github/gitignore/master/' name = None file_content = None valid = True def get_base_url(self): """""" :rtype: str """""" return self.BASE_URL def set_name(self, name): """""" :type name: str """""" self.name = name def get_name(self): """""" :rtype: str """""" return self.name def set_file_content(self, file_content): """""" :type file_content: str """""" self.file_content = file_content def get_file_content(self): """""" :rtype: str """""" return self.file_content def is_valid(self): """""" :rtype: bool """""" return self.valid def set_valid(self, valid): """""" :type valid: bool """""" self.valid = valid " Add null in invalid path test,"//@@author A0162266E package guitests; import java.io.File; import java.io.IOException; import org.junit.Test; import werkbook.task.logic.commands.SaveCommand; public class SaveCommandTest extends TaskListGuiTest { @Test public void save_invalidPath_failure() { commandBox.runCommand(""save \""\0\""""); assertResultMessage(SaveCommand.MESSAGE_INVALID_PATH); } @Test public void save_nonExistentFolder_failure() { commandBox.runCommand(""save src\\test\\data\\sandbox\\some_folder""); assertResultMessage(SaveCommand.MESSAGE_FOLDER_NOT_EXIST); } @Test public void save_notDirectory_failure() { File newFile = new File(""src\\test\\data\\sandbox\\newFile""); try { newFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } commandBox.runCommand(""save src\\test\\data\\sandbox\\newFile""); assertResultMessage(SaveCommand.MESSAGE_NOT_A_DIRECTORY); } @Test public void save_validDirectory_success() { File newFolder = new File(""src\\test\\data\\sandbox\\newFolder""); newFolder.mkdir(); commandBox.runCommand(""save src\\test\\data\\sandbox\\newFolder""); assertResultMessage(SaveCommand.MESSAGE_SUCCESS); } } ","//@@author A0162266E package guitests; import java.io.File; import java.io.IOException; import org.junit.Test; import werkbook.task.logic.commands.SaveCommand; public class SaveCommandTest extends TaskListGuiTest { @Test public void save_invalidPath_failure() { commandBox.runCommand(""save \""\"" ""); assertResultMessage(SaveCommand.MESSAGE_INVALID_PATH); } @Test public void save_nonExistentFolder_failure() { commandBox.runCommand(""save src\\test\\data\\sandbox\\some_folder""); assertResultMessage(SaveCommand.MESSAGE_FOLDER_NOT_EXIST); } @Test public void save_notDirectory_failure() { File newFile = new File(""src\\test\\data\\sandbox\\newFile""); try { newFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } commandBox.runCommand(""save src\\test\\data\\sandbox\\newFile""); assertResultMessage(SaveCommand.MESSAGE_NOT_A_DIRECTORY); } @Test public void save_validDirectory_success() { File newFolder = new File(""src\\test\\data\\sandbox\\newFolder""); newFolder.mkdir(); commandBox.runCommand(""save src\\test\\data\\sandbox\\newFolder""); assertResultMessage(SaveCommand.MESSAGE_SUCCESS); } } " Remove unnesearry log when testing for timestamp,"<?php namespace Craft; use Carbon\Carbon; class FeedMeDateHelper { // Public Methods // ========================================================================= public static function parseString($date) { $parsedDate = null; if (is_array($date)) { return $date; } try { $timestamp = FeedMeDateHelper::isTimestamp($date); if ($timestamp) { $date = '@' . $date; } $dt = Carbon::parse($date); if ($dt) { $dateTimeString = $dt->toDateTimeString(); $parsedDate = DateTime::createFromString($dateTimeString, craft()->timezone); } } catch (\Exception $e) { FeedMePlugin::log('Date parse error: ' . $date . ' - ' . $e->getMessage(), LogLevel::Error, true); } return $parsedDate; } public static function isTimestamp($string) { try { new DateTime('@' . $string); } catch(\Exception $e) { return false; } return true; } }","<?php namespace Craft; use Carbon\Carbon; class FeedMeDateHelper { // Public Methods // ========================================================================= public static function parseString($date) { $parsedDate = null; if (is_array($date)) { return $date; } try { $timestamp = FeedMeDateHelper::isTimestamp($date); if ($timestamp) { $date = '@' . $date; } $dt = Carbon::parse($date); if ($dt) { $dateTimeString = $dt->toDateTimeString(); $parsedDate = DateTime::createFromString($dateTimeString, craft()->timezone); } } catch (\Exception $e) { FeedMePlugin::log('Date parse error: ' . $date . ' - ' . $e->getMessage(), LogLevel::Error, true); } return $parsedDate; } public static function isTimestamp($string) { try { new DateTime('@' . $string); } catch(\Exception $e) { FeedMePlugin::log('Date parse error: ' . $string . ' - ' . $e->getMessage(), LogLevel::Error, true); return false; } return true; } }" Add note about python 3 support,"#!/usr/bin/env python from distutils.core import setup import os from setuptools import find_packages name = 'Mikko Korpela' # I might be just a little bit too much afraid of those bots.. address = name.lower().replace(' ', '.')+chr(64)+'gmail.com' setup(name='robotframework-pabot', version='0.39', description='Parallel test runner for Robot Framework', long_description='A parallel executor for Robot Framework tests.' 'With Pabot you can split one execution into multiple and save test execution time.', author=name, author_email=address, url='https://github.com/mkorpela/pabot', download_url='https://pypi.python.org/pypi/robotframework-pabot', packages=find_packages(), classifiers=[ 'Intended Audience :: Developers', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Testing', 'License :: OSI Approved :: Apache Software License', 'Development Status :: 5 - Production/Stable', 'Framework :: Robot Framework' ], scripts=[os.path.join('scripts', 'pabot'), os.path.join('scripts', 'pabot.bat')], license='Apache License, Version 2.0', install_requires=['robotframework', 'robotremoteserver>=1.1']) ","#!/usr/bin/env python from distutils.core import setup import os from setuptools import find_packages name = 'Mikko Korpela' # I might be just a little bit too much afraid of those bots.. address = name.lower().replace(' ', '.')+chr(64)+'gmail.com' setup(name='robotframework-pabot', version='0.39', description='Parallel test runner for Robot Framework', long_description='A parallel executor for Robot Framework tests.' 'With Pabot you can split one execution into multiple and save test execution time.', author=name, author_email=address, url='https://github.com/mkorpela/pabot', download_url='https://pypi.python.org/pypi/robotframework-pabot', packages=find_packages(), classifiers=[ 'Intended Audience :: Developers', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Testing', 'License :: OSI Approved :: Apache Software License', 'Development Status :: 5 - Production/Stable', 'Framework :: Robot Framework' ], scripts=[os.path.join('scripts', 'pabot'), os.path.join('scripts', 'pabot.bat')], license='Apache License, Version 2.0', install_requires=['robotframework', 'robotremoteserver>=1.1']) " Fix cuboid regions not extending all the way to negative infinity,"package in.twizmwaz.cardinal.module.modules.regions.parsers; import in.twizmwaz.cardinal.module.modules.regions.RegionParser; import in.twizmwaz.cardinal.util.NumUtils; import org.bukkit.util.Vector; import org.jdom2.Element; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CuboidParser extends RegionParser { private final Vector min, max; public CuboidParser(Element element) { super(element.getAttributeValue(""name"")); List<String> values = new ArrayList<>(); values.addAll(Arrays.asList(element.getAttributeValue(""min"").contains("","") ? element.getAttributeValue(""min"").trim().split("","") : element.getAttributeValue(""min"").trim().split("" ""))); values.addAll(Arrays.asList(element.getAttributeValue(""max"").trim().replaceAll("" "", "","").split("",""))); for (String string : values) { values.set(values.indexOf(string), string.trim()); } this.min = new Vector(NumUtils.parseDouble(values.get(0)), NumUtils.parseDouble(values.get(1)), NumUtils.parseDouble(values.get(2))); this.max = new Vector(NumUtils.parseDouble(values.get(3)), NumUtils.parseDouble(values.get(4)), NumUtils.parseDouble(values.get(5))); } public Vector getMin() { return min; } public Vector getMax() { return max; } } ","package in.twizmwaz.cardinal.module.modules.regions.parsers; import in.twizmwaz.cardinal.module.modules.regions.RegionParser; import org.bukkit.util.Vector; import org.jdom2.Element; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CuboidParser extends RegionParser { private final Vector min, max; public CuboidParser(Element element) { super(element.getAttributeValue(""name"")); List<String> values = new ArrayList<>(); values.addAll(Arrays.asList(element.getAttributeValue(""min"").contains("","") ? element.getAttributeValue(""min"").trim().split("","") : element.getAttributeValue(""min"").trim().split("" ""))); values.addAll(Arrays.asList(element.getAttributeValue(""max"").trim().replaceAll("" "", "","").split("",""))); for (String string : values) { values.set(values.indexOf(string), string.trim()); if (string.equalsIgnoreCase(""oo"")) values.set(values.indexOf(string), ""256""); if (string.equalsIgnoreCase(""-oo"")) values.set(values.indexOf(string), ""0""); } this.min = new Vector(Double.parseDouble(values.get(0)), Double.parseDouble(values.get(1)), Double.parseDouble(values.get(2))); this.max = new Vector(Double.parseDouble(values.get(3)), Double.parseDouble(values.get(4)), Double.parseDouble(values.get(5))); } public Vector getMin() { return min; } public Vector getMax() { return max; } } " "Remove lucene query parser lib Originally added for an experiment to parse lucene query_string queries, this lib is not currently used. Removeing from the autoloader sequence, but leaving the lib and grammar file in case I want to revisit the experiment later.","(function() { ""use strict""; head.js(""js/vendor/json2.js"") .js(""js/vendor/jsonlint.js"") .js(""http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"",""js/vendor/angular.min.js"", function() { head.js(""js/vendor/angular-sanitize.min.js"",""js/vendor/ng-bootstrap/ui-bootstrap-custom-tpls-0.1.0-SNAPSHOT.min.js"",""js/vendor/select2/select2.min.js"",""js/vendor/select2/angular-ui.min.js"", ""js/app.js"", function() { head.js(""js/controllers/DropdownCtrl.js"") .js(""js/controllers/AnalyzerCtrl.js"") .js(""js/controllers/TokenizerCtrl.js"") .js(""js/controllers/NavbarCtrl.js"") .js(""js/controllers/AdhocCtrl.js"") .js(""js/controllers/QueryInput.js"") .js(""js/controllers/QueryOutput.js"") .js(""js/directives/modal.js"") .js(""js/directives/rawerror.js"") .js(""js/filters/jsonlint.js""); }); }); }).call(this); ","(function() { ""use strict""; head.js(""js/vendor/json2.js"") .js(""js/vendor/jsonlint.js"") .js(""js/vendor/lucene/lucene-query-parser.js"") .js(""http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"",""js/vendor/angular.min.js"", function() { head.js(""js/vendor/angular-sanitize.min.js"",""js/vendor/ng-bootstrap/ui-bootstrap-custom-tpls-0.1.0-SNAPSHOT.min.js"",""js/vendor/select2/select2.min.js"",""js/vendor/select2/angular-ui.min.js"", ""js/app.js"", function() { head.js(""js/controllers/DropdownCtrl.js"") .js(""js/controllers/AnalyzerCtrl.js"") .js(""js/controllers/TokenizerCtrl.js"") .js(""js/controllers/NavbarCtrl.js"") .js(""js/controllers/AdhocCtrl.js"") .js(""js/controllers/QueryInput.js"") .js(""js/controllers/QueryOutput.js"") .js(""js/directives/modal.js"") .js(""js/directives/rawerror.js"") .js(""js/filters/jsonlint.js""); }); }); }).call(this); " Test set model helper method.,"<?php namespace Test\Unit; use Test\TestCase; use \Mockery as m; use Taskforcedev\CrudApi\Helpers\CrudApi; class CrudApiHelperTest extends TestCase { public function testGetRelatedFieldForUserId() { $crudApi = new CrudApi(['namespace' => null]); $related_field = $crudApi->getRelatedField('user_id'); $this->assertEquals('user', $related_field); } public function testGetRelatedFieldForOrganisationId() { $crudApi = new CrudApi(['namespace' => null]); $related_field = $crudApi->getRelatedField('organisation_id'); $this->assertEquals('organisation', $related_field); } public function testGetModelDisplayNameWithoutAnInstance() { $options = [ 'namespace' => null, 'model' => 'User' ]; $crudApi = new CrudApi($options); $display = $crudApi->getModelDisplayName(); $this->assertEquals('User', $display); } public function testAuthorUserModelBinding() { $crudApi = new CrudApi(['namespace' => 'Test\\Models\\', 'model' => 'Post']); $related_field = $crudApi->getRelatedField('author_id'); $this->assertEquals('author', $related_field); $relation = $crudApi->getRelatedModel($related_field); $class = get_class($relation); $this->assertEquals('Test\\Models\\User', $class); } public function testSetModelHelper() { $options = ['namespace' => null]; $crudApi = new CrudApi($options); $crudApi->setModelHelper('test'); $this->assertEquals('test', $crudApi->modelHelper); } }","<?php namespace Test\Unit; use Test\TestCase; use Taskforcedev\CrudApi\Helpers\CrudApi; class CrudApiHelperTest extends TestCase { public function testGetRelatedFieldForUserId() { $crudApi = new CrudApi(['namespace' => null]); $related_field = $crudApi->getRelatedField('user_id'); $this->assertEquals('user', $related_field); } public function testGetRelatedFieldForOrganisationId() { $crudApi = new CrudApi(['namespace' => null]); $related_field = $crudApi->getRelatedField('organisation_id'); $this->assertEquals('organisation', $related_field); } public function testGetModelDisplayNameWithoutAnInstance() { $options = [ 'namespace' => null, 'model' => 'User' ]; $crudApi = new CrudApi($options); $display = $crudApi->getModelDisplayName(); $this->assertEquals('User', $display); } public function testAuthorUserModelBinding() { $crudApi = new CrudApi(['namespace' => 'Test\\Models\\', 'model' => 'Post']); $related_field = $crudApi->getRelatedField('author_id'); $this->assertEquals('author', $related_field); $relation = $crudApi->getRelatedModel($related_field); $class = get_class($relation); $this->assertEquals('Test\\Models\\User', $class); } }" Allow passing in a title,"#! /usr/bin/env node var opts = require('optimist').argv var through = require('through2'); function indexhtmlify(opts) { opts = opts || {} var s = through(function onwrite(chunk, enc, cb) { s.push(chunk) cb() }, function onend(cb) { s.push('</script>\n') s.push('</html>\n') cb() }) s.push('<!DOCTYPE html>\n') s.push('<html>\n') s.push('<head>\n') s.push('<title>' + (opts.title || '---') + '</title>\n') s.push('<meta content=""width=device-width, initial-scale=1.0, ' + 'maximum-scale=1.0, user-scalable=0"" name=""viewport"" />\n') s.push('<meta charset=utf-8></head>\n') if (opts.style) { s.push('<style>\n') s.push(require('fs').readFileSync(opts.style, 'utf8')) s.push('</style>\n') } s.push('<body></body>\n') s.push('<script language=javascript>\n') return s } module.exports = indexhtmlify if (require.main === module) { if(process.stdin.isTTY) { console.error('USAGE: browserify client.js | indexhtmlify ' + '--style style.css > index.html') process.exit(1) } process.stdin .pipe(indexhtmlify(opts)) .pipe(process.stdout) } ","#! /usr/bin/env node var opts = require('optimist').argv var through = require('through2'); function indexhtmlify(opts) { var s = through(function onwrite(chunk, enc, cb) { s.push(chunk) cb() }, function onend(cb) { s.push('</script>\n') s.push('</html>\n') cb() }) s.push('<!DOCTYPE html>\n') s.push('<html>\n') s.push('<head>\n') s.push('<title>---</title>\n') s.push('<meta content=""width=device-width, initial-scale=1.0, ' + 'maximum-scale=1.0, user-scalable=0"" name=""viewport"" />\n') s.push('<meta charset=utf-8></head>\n') if (opts.style) { s.push('<style>\n') s.push(require('fs').readFileSync(opts.style, 'utf8')) s.push('</style>\n') } s.push('<body></body>\n') s.push('<script language=javascript>\n') return s } module.exports = indexhtmlify if (require.main === module) { if(process.stdin.isTTY) { console.error('USAGE: browserify client.js | indexhtmlify ' + '--style style.css > index.html') process.exit(1) } process.stdin .pipe(indexhtmlify(opts)) .pipe(process.stdout) } " Make consturctor compatible with php 5.4,"<?php namespace HelloFresh\Reagieren\MessageBroker\Composite; use Collections\ArrayList; use Collections\Dictionary; use Collections\MapInterface; use Collections\VectorInterface; use HelloFresh\Reagieren\CompositeProducerInterface; use HelloFresh\Reagieren\ProducerInterface; class Producer implements CompositeProducerInterface { /** * @var VectorInterface */ private $producers; /** * Composite Producer Constructor * * @param array $producers */ public function __construct() { $this->producers = new ArrayList(func_get_args()); } /** * {@inheritdoc} */ public function produce($payload, $configs = []) { $configs = new Dictionary($configs); $this->producers->each(function (ProducerInterface $producer) use ($payload, $configs) { /** @var MapInterface $brokerConfigs */ $brokerConfigs = $configs->get($producer->getName()); try { $topic = $brokerConfigs->get('topic'); } catch (\OutOfBoundsException $e) { throw new \InvalidArgumentException('You should configure the topic/exchange that you want to produce to'); } $producer->produce($topic, $payload, $brokerConfigs); }); } } ","<?php namespace HelloFresh\Reagieren\MessageBroker\Composite; use Collections\ArrayList; use Collections\Dictionary; use Collections\MapInterface; use Collections\VectorInterface; use HelloFresh\Reagieren\CompositeProducerInterface; use HelloFresh\Reagieren\ProducerInterface; class Producer implements CompositeProducerInterface { /** * @var VectorInterface */ private $producers; /** * Composite Producer Constructor * * @param array $producers */ public function __construct(...$producers) { $this->producers = new ArrayList($producers); } /** * {@inheritdoc} */ public function produce($payload, $configs = []) { $configs = new Dictionary($configs); $this->producers->each(function (ProducerInterface $producer) use ($payload, $configs) { /** @var MapInterface $brokerConfigs */ $brokerConfigs = $configs->get($producer->getName()); try { $topic = $brokerConfigs->get('topic'); } catch (\OutOfBoundsException $e) { throw new \InvalidArgumentException('You should configure the topic/exchange that you want to produce to'); } $producer->produce($topic, $payload, $brokerConfigs); }); } } " Change button class for new post controls location,"import { extend } from 'flarum/extend'; import app from 'flarum/app'; import Button from 'flarum/components/Button'; import CommentPost from 'flarum/components/CommentPost'; export default function() { extend(CommentPost.prototype, 'actionItems', function(items) { const post = this.props.post; if (post.isHidden() || !post.canLike()) return; let isLiked = app.session.user && post.likes().some(user => user === app.session.user); items.add('like', Button.component({ children: app.trans(isLiked ? 'likes.unlike_action' : 'likes.like_action'), className: 'Button Button--link', onclick: () => { isLiked = !isLiked; post.save({isLiked}); // We've saved the fact that we do or don't like the post, but in order // to provide instantaneous feedback to the user, we'll need to add or // remove the like from the relationship data manually. const data = post.data.relationships.likes.data; data.some((like, i) => { if (like.id === app.session.user.id()) { data.splice(i, 1); return true; } }); if (isLiked) { data.unshift({type: 'users', id: app.session.user.id()}); } } }) ); }); } ","import { extend } from 'flarum/extend'; import app from 'flarum/app'; import Button from 'flarum/components/Button'; import CommentPost from 'flarum/components/CommentPost'; export default function() { extend(CommentPost.prototype, 'actionItems', function(items) { const post = this.props.post; if (post.isHidden() || !post.canLike()) return; let isLiked = app.session.user && post.likes().some(user => user === app.session.user); items.add('like', Button.component({ children: app.trans(isLiked ? 'likes.unlike_action' : 'likes.like_action'), className: 'Button Button--text', onclick: () => { isLiked = !isLiked; post.save({isLiked}); // We've saved the fact that we do or don't like the post, but in order // to provide instantaneous feedback to the user, we'll need to add or // remove the like from the relationship data manually. const data = post.data.relationships.likes.data; data.some((like, i) => { if (like.id === app.session.user.id()) { data.splice(i, 1); return true; } }); if (isLiked) { data.unshift({type: 'users', id: app.session.user.id()}); } } }) ); }); } " Return attachment ID instead of URL,"/* * Adapted from: http://mikejolley.com/2012/12/using-the-new-wordpress-3-5-media-uploader-in-plugins/ */ jQuery(document).ready(function ($) { // Uploading files var file_frame; $('.custom-profile-picture-remove').on('click', function (event) { $('#user_meta_image').val(''); $('#submit').click(); }); $('.custom-profile-picture').on('click', function (event) { event.preventDefault(); // If the media frame already exists, reopen it. if (file_frame) { file_frame.open(); return; } // Create the media frame. file_frame = wp.media.frames.file_frame = wp.media({ title: $(this).data('uploader_title'), button: { text: $(this).data('uploader_button_text') }, multiple: false // Set to true to allow multiple files to be selected }); // When an image is selected, run a callback. file_frame.on('select', function () { // We set multiple to false so only get one image from the uploader attachment = file_frame.state().get('selection').first().toJSON(); // Do something with attachment.id and/or attachment.url here $('#user_meta_image').val(attachment.id); $('.current-profile-picture').attr('src', attachment.url); }); // Finally, open the modal file_frame.open(); }); });","/* * Adapted from: http://mikejolley.com/2012/12/using-the-new-wordpress-3-5-media-uploader-in-plugins/ */ jQuery(document).ready(function ($) { // Uploading files var file_frame; $('.custom-profile-picture-remove').on('click', function (event) { $('#user_meta_image').val(''); $('#submit').click(); }); $('.custom-profile-picture').on('click', function (event) { event.preventDefault(); // If the media frame already exists, reopen it. if (file_frame) { file_frame.open(); return; } // Create the media frame. file_frame = wp.media.frames.file_frame = wp.media({ title: $(this).data('uploader_title'), button: { text: $(this).data('uploader_button_text') }, multiple: false // Set to true to allow multiple files to be selected }); // When an image is selected, run a callback. file_frame.on('select', function () { // We set multiple to false so only get one image from the uploader attachment = file_frame.state().get('selection').first().toJSON(); // Do something with attachment.id and/or attachment.url here $('#user_meta_image').val(attachment.url); $('.current-profile-picture').attr('src', attachment.url); }); // Finally, open the modal file_frame.open(); }); });" "Add more structures to test_full() document Signed-off-by: Squareys <0f6a03d4883e012ba4cb2c581a68f35544703cd6@googlemail.com>","import os import unittest from pyddl import * from pyddl.enum import * __author__ = ""Jonathan Hale"" class DdlTextWriterTest(unittest.TestCase): def tearDown(self): try: os.remove(""test.oddl"") except FileNotFoundError: pass # test_empty failed? def test_empty(self): # create document document = DdlDocument() # write document DdlTextWriter(document).write(""test.oddl"") # check if file was created try: self.assertTrue(os.path.isfile(""test.oddl"")) except FileNotFoundError: self.fail(""DdlTextWriter did not create the specified file."") def test_full(self): # create document document = DdlDocument() document.add_structure(B""Human"", None, [DdlStructure(B""Name"", None, [DdlPrimitive(PrimitiveType.string, [""Peter""])]), DdlStructure(B""Age"", None, [DdlPrimitive(PrimitiveType.unsigned_int16, [21])])] ) document.add_structure(B""SomethingElse"", None, [DdlStructure(B""AnArray"", None, [DdlPrimitive(PrimitiveType.int32, range(1, 100))])] ) document.add_structure(B""MoreElse"", None, [DdlStructure(B""AnVectorArray"", None, [DdlPrimitive(PrimitiveType.int32, [(1, 2), (12, 42), (13, 31)], None, 2)])] ) # write document DdlTextWriter(document).write(""test.oddl"") if __name__ == ""__main__"": unittest.main() ","import os import unittest from pyddl import * from pyddl.enum import * __author__ = ""Jonathan Hale"" class DdlTextWriterTest(unittest.TestCase): def tearDown(self): try: os.remove(""test.oddl"") except FileNotFoundError: pass # test_empty failed? def test_empty(self): # create document document = DdlDocument() # write document DdlTextWriter(document).write(""test.oddl"") # check if file was created try: self.assertTrue(os.path.isfile(""test.oddl"")) except FileNotFoundError: self.fail(""DdlTextWriter did not create the specified file."") def test_full(self): # create document document = DdlDocument() document.add_structure(B""Human"", None, [DdlStructure(B""Name"", None, [DdlPrimitive(PrimitiveType.string, [""Peter""])]), DdlStructure(B""Age"", None, [DdlPrimitive(PrimitiveType.unsigned_int16, [21])])] ) # write document DdlTextWriter(document).write(""test.oddl"") if __name__ == ""__main__"": unittest.main() " Remove streed requirement from validation,"/** * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ /*global define*/ define( [], function () { 'use strict'; return { getRules: function () { return { 'firstname': { 'required': true }, 'lastname': { 'required': true }, 'postcode': { 'required': true }, 'city': { 'required': true }, 'country_id': { 'required': true } }; } }; } ); ","/** * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ /*global define*/ define( [], function () { 'use strict'; return { getRules: function () { return { 'firstname': { 'required': true }, 'lastname': { 'required': true }, 'street': { 'required': true }, 'postcode': { 'required': true }, 'city': { 'required': true }, 'country_id': { 'required': true } }; } }; } ); " "Animation: Attach Aside to element with ng-scope ngAnimate won't run correctly unless it's attached to an ng-scope. Previously I was attaching to body which isn't scoped.","/* global define */ (function() { 'use strict'; define(['lodash', 'moment'], function(_, moment) { var RequestController = function($log, $scope, ClusterResolver, RequestService, RequestTrackingService, $aside) { ClusterResolver.then(function() { var myAside = $aside({ 'title': 'Requested Tasks', 'template': 'views/request.html', 'animation': 'am-fade-and-slide-right', 'backdropAnimation': 'animation-fade', 'show': false, 'container': '.RequestManagement' }); myAside.$scope.empty = true; $scope.show = function() { RequestService.getList().then(function(response) { myAside.show(); response = _.map(response.reverse(), function(request) { /* jshint camelcase: false */ var time = request.state === 'complete' ? request.completed_at : request.requested_at; var headline = request.headline; var state = request.state; if (request.error) { headline += ' ' + request.error_message; state = 'error'; } return { headline: request.headline, state: state, time: moment(time).fromNow() }; }); myAside.$scope.tasks = response; myAside.$scope.empty = response.length === 0; }); }; }); }; return ['$log', '$scope', 'ClusterResolver', 'RequestService', 'RequestTrackingService', '$aside', RequestController]; }); })(); ","/* global define */ (function() { 'use strict'; define(['lodash', 'moment'], function(_, moment) { var RequestController = function($log, $scope, ClusterResolver, RequestService, RequestTrackingService, $aside) { ClusterResolver.then(function() { var myAside = $aside({ 'title': 'Requested Tasks', 'template': 'views/request.html', 'container': 'body', 'animation': 'am-fade-and-slide-left', 'backdropAnimation': 'animation-fade', 'show': false }); myAside.$scope.empty = true; $scope.show = function() { RequestService.getList().then(function(response) { myAside.show(); response = _.map(response.reverse(), function(request) { /* jshint camelcase: false */ var time = request.state === 'complete' ? request.completed_at : request.requested_at; var headline = request.headline; var state = request.state; if (request.error) { headline += ' ' + request.error_message; state = 'error'; } return { headline: request.headline, state: state, time: moment(time).fromNow() }; }); myAside.$scope.tasks = response; myAside.$scope.empty = response.length === 0; }); }; }); }; return ['$log', '$scope', 'ClusterResolver', 'RequestService', 'RequestTrackingService', '$aside', RequestController]; }); })(); " Fix creating the first address.,"/** * @fileOverview PocketCreateCtrl angular controller */ 'use strict'; define(['./module', 'darkwallet'], function (controllers, DarkWallet) { controllers.controller('PocketCreateCtrl', ['$scope', '$wallet', '$history', 'watch', '$tabs', 'modals', function($scope, $wallet, $history, watch, $tabs, modals) { /** * Scope variables */ $scope.newPocket = {}; /** * Create a pocket */ $scope.createPocket = function() { if ($scope.newPocket.name) { var identity = DarkWallet.getIdentity(); // Don't need the password for old style var askPassword = (identity.store.get('version') > 4) ? modals.password : function(title, cb) {cb();}; askPassword('Write your unlock password', function(password) { // create pocket identity.wallet.pockets.createPocket($scope.newPocket.name, password); var pocketIndex = identity.wallet.pockets.hdPockets.length-1; // initialize pocket on angular $wallet.initPocket(pocketIndex); // generate an address $wallet.generateAddress(pocketIndex, 0); // select the pocket $scope.selectPocket($scope.newPocket.name, pocketIndex); // reset pocket form $scope.newPocket = {name:''}; }); } else { // cancel $tabs.open(); } }; }]); }); ","/** * @fileOverview PocketCreateCtrl angular controller */ 'use strict'; define(['./module', 'darkwallet'], function (controllers, DarkWallet) { controllers.controller('PocketCreateCtrl', ['$scope', '$wallet', '$history', 'watch', '$tabs', 'modals', function($scope, $wallet, $history, watch, $tabs, modals) { /** * Scope variables */ $scope.newPocket = {}; /** * Create a pocket */ $scope.createPocket = function() { if ($scope.newPocket.name) { var identity = DarkWallet.getIdentity(); // Don't need the password for old style var askPassword = (identity.store.get('version') > 4) ? modals.password : function(title, cb) {cb();}; askPassword('Write your unlock password', function(password) { // create pocket identity.wallet.pockets.createPocket($scope.newPocket.name, password); var pocketIndex = identity.wallet.pockets.hdPockets.length-1; // initialize pocket on angular $wallet.initPocket(pocketIndex); // generate an address $wallet.generateAddress(pocketIndex*2, 0); // select the pocket $scope.selectPocket($scope.newPocket.name, pocketIndex); // reset pocket form $scope.newPocket = {name:''}; }); } else { // cancel $tabs.open(); } }; }]); }); " Remove TODO for done thing,"package edu.northwestern.bioinformatics.studycalendar.domain.delta; import edu.northwestern.bioinformatics.studycalendar.domain.PlanTreeInnerNode; import edu.northwestern.bioinformatics.studycalendar.domain.PlanTreeNode; import javax.persistence.Entity; import javax.persistence.DiscriminatorValue; import javax.persistence.Transient; import javax.persistence.Column; import java.util.Set; import org.hibernate.validator.NotNull; /** * @author Rhett Sutphin */ @Entity @DiscriminatorValue(""add"") public class Add extends Change { private Integer newChildId; private Integer index; @Override @Transient public ChangeAction getAction() { return ChangeAction.ADD; } ////// BEAN PROPERTIES @Column (name = ""new_value"") public Integer getNewChildId() { return newChildId; } public void setNewChildId(Integer newChildId) { this.newChildId = newChildId; } @Column (name = ""attribute"") public Integer getIndex() { return index; } public void setIndex(Integer index) { this.index = index; } @Override public String toString() { StringBuilder sb = new StringBuilder(getClass().getSimpleName()) .append(""[id="").append(getId()).append(""; child id "").append(getNewChildId()); if (getIndex() != null) { sb.append("" at index "").append(getIndex()); } return sb.append(']').toString(); } } ","package edu.northwestern.bioinformatics.studycalendar.domain.delta; import edu.northwestern.bioinformatics.studycalendar.domain.PlanTreeInnerNode; import edu.northwestern.bioinformatics.studycalendar.domain.PlanTreeNode; import javax.persistence.Entity; import javax.persistence.DiscriminatorValue; import javax.persistence.Transient; import javax.persistence.Column; import java.util.Set; import org.hibernate.validator.NotNull; /** * @author Rhett Sutphin */ @Entity // TODO @DiscriminatorValue(""add"") public class Add extends Change { private Integer newChildId; private Integer index; @Override @Transient public ChangeAction getAction() { return ChangeAction.ADD; } ////// BEAN PROPERTIES @Column (name = ""new_value"") public Integer getNewChildId() { return newChildId; } public void setNewChildId(Integer newChildId) { this.newChildId = newChildId; } @Column (name = ""attribute"") public Integer getIndex() { return index; } public void setIndex(Integer index) { this.index = index; } @Override public String toString() { StringBuilder sb = new StringBuilder(getClass().getSimpleName()) .append(""[id="").append(getId()).append(""; child id "").append(getNewChildId()); if (getIndex() != null) { sb.append("" at index "").append(getIndex()); } return sb.append(']').toString(); } } " Remove statement without side effect.,"import tablib from import_export import fields, resources, widgets from . import models CategoryResource = resources.modelresource_factory(models.Category) QuestionResource = resources.modelresource_factory(models.Question) class ChecklistResource(resources.ModelResource): questions = fields.Field(column_name='questions', widget=widgets.JSONWidget(),) category_data = fields.Field( column_name='category_data', widget=widgets.JSONWidget() ) def before_import_row(self, row, **kwargs): if row.get('category_data'): dataset = tablib.Dataset().load(row.get('category_data'), 'json') CategoryResource().import_data(dataset) def dehydrate_category_data(self, checklist): if checklist.category: dataset = CategoryResource().export( queryset=models.Category.objects.filter(pk=checklist.category.pk) ) return dataset.json def dehydrate_questions(self, checklist): dataset = QuestionResource().export(queryset=checklist.questions.all()) return dataset.json def save_m2m(self, instance, row, using_transactions, dry_run): super().save_m2m(instance, row, using_transactions, dry_run) if row.get('questions'): dataset = tablib.Dataset().load(row.get('questions'), 'json') QuestionResource().import_data(dataset) class Meta: exclude = ('created', 'modified', 'uuid', 'customers') ChecklistResource = resources.modelresource_factory(models.Checklist, ChecklistResource) ","import tablib from import_export import fields, resources, widgets from . import models CategoryResource = resources.modelresource_factory(models.Category) QuestionResource = resources.modelresource_factory(models.Question) class ChecklistResource(resources.ModelResource): questions = fields.Field(column_name='questions', widget=widgets.JSONWidget(),) category_data = fields.Field( column_name='category_data', widget=widgets.JSONWidget() ) def before_import_row(self, row, **kwargs): if row.get('category_data'): dataset = tablib.Dataset().load(row.get('category_data'), 'json') CategoryResource().import_data(dataset) def dehydrate_category_data(self, checklist): if checklist.category: dataset = CategoryResource().export( queryset=models.Category.objects.filter(pk=checklist.category.pk) ) return dataset.json def dehydrate_questions(self, checklist): dataset = QuestionResource().export(queryset=checklist.questions.all()) return dataset.json def save_m2m(self, instance, row, using_transactions, dry_run): super().save_m2m(instance, row, using_transactions, dry_run) if row.get('questions'): dataset = tablib.Dataset().load(row.get('questions'), 'json') result = QuestionResource().import_data(dataset) result class Meta: exclude = ('created', 'modified', 'uuid', 'customers') ChecklistResource = resources.modelresource_factory(models.Checklist, ChecklistResource) " web: Fix minification of javascript source file,"module.exports = function(grunt) { var dejsx = require('grunt-react').browserify; grunt.loadNpmTasks('grunt-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-browserify'); grunt.loadNpmTasks('grunt-react'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), browserify: { options: { transform: [dejsx], debug: true }, app: { src: 'src/main.js', dest: 'spreads.js' } }, uglify: { spreads: { files: { './spreads.min.js': ['./spreads.js'] } } }, watch: { grunt: { files: ['Gruntfile.js'] }, src: { files: ['src/**/*.js'], tasks: ['browserify'] }, sass: { files: 'scss/**/*.scss', tasks: ['sass'] } }, sass: { dist: { options: { outputStyle: 'compressed' }, files: { 'spreads.css': 'scss/app.scss' } } } }); grunt.registerTask('build', ['sass']); grunt.registerTask('default', ['build', 'browserify', 'uglify']); };","module.exports = function(grunt) { var dejsx = require('grunt-react').browserify; grunt.loadNpmTasks('grunt-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-browserify'); grunt.loadNpmTasks('grunt-react'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), browserify: { options: { transform: [dejsx], debug: true }, app: { src: 'src/main.js', dest: 'spreads.js' } }, uglify: { spreads: { options: { sourceMap: './spreads.min-map.js', sourceMapIn: './spreads.js' }, files: { './spreads.min.js': ['./spreads.js'] } } }, watch: { grunt: { files: ['Gruntfile.js'] }, src: { files: ['src/**/*.js'], tasks: ['browserify'] }, sass: { files: 'scss/**/*.scss', tasks: ['sass'] } }, sass: { dist: { options: { outputStyle: 'compressed' }, files: { 'spreads.css': 'scss/app.scss' } } } }); grunt.registerTask('build', ['sass']); grunt.registerTask('default', ['build', 'browserify', 'uglify']); };" Change the home list name.,"<!-- Sidebar --> <div class=""sidebar"" data-active-color=""gray"" data-active-color=""purple""> <div class=""sidebar-wrapper""> <div class=""logo""> <a href=""{{ url('/') }}"" class=""simple-text""> <strong>Stack</strong> <small>hub</small> </a> </div> <ul class=""nav""> <li {!! request()->route()->getName() == 'dashboard' ? 'class=""active""' : '' !!}> <a href=""{{ url('/home') }}""> <i class=""fa fa-dashboard""></i> <p>Início</p> </a> </li> <li {!! request()->route()->getName() == 'trends.stars' ? 'class=""active""' : '' !!}> <a href=""{{ url('/graphics/stars') }}""> <i class=""fa fa-star""></i> <p>Top 10 Stared</p> </a> </li> <li {!! request()->route()->getName() == 'trends.forks' ? 'class=""active""' : '' !!}> <a href=""{{ url('/graphics/forks') }}""> <i class=""fa fa-code-fork""></i> <p>Top 10 Forked</p> </a> </li> </ul> </div> </div> ","<!-- Sidebar --> <div class=""sidebar"" data-active-color=""gray"" data-active-color=""purple""> <div class=""sidebar-wrapper""> <div class=""logo""> <a href=""{{ url('/') }}"" class=""simple-text""> <strong>Stack</strong> <small>hub</small> </a> </div> <ul class=""nav""> <li {!! request()->route()->getName() == 'dashboard' ? 'class=""active""' : '' !!}> <a href=""{{ url('/home') }}""> <i class=""fa fa-dashboard""></i> <p>Dashboard</p> </a> </li> <li {!! request()->route()->getName() == 'trends.stars' ? 'class=""active""' : '' !!}> <a href=""{{ url('/graphics/stars') }}""> <i class=""fa fa-star""></i> <p>Top 10 Stared</p> </a> </li> <li {!! request()->route()->getName() == 'trends.forks' ? 'class=""active""' : '' !!}> <a href=""{{ url('/graphics/forks') }}""> <i class=""fa fa-code-fork""></i> <p>Top 10 Forked</p> </a> </li> </ul> </div> </div> " "Use unique binding_index for RouterL3AgentBinding This is because (router_id, binding_index) tuple is expected to be unique, as per db model. Closes-Bug: #1674434 Change-Id: I64fcee88f2ac942e6fa173644fbfb7655ea6041b","# Copyright (c) 2016 Intel Corporation. # # 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. from neutron.objects import l3agent from neutron.tests.unit.objects import test_base from neutron.tests.unit import testlib_api class RouterL3AgentBindingIfaceObjTestCase(test_base.BaseObjectIfaceTestCase): _test_class = l3agent.RouterL3AgentBinding class RouterL3AgentBindingDbObjTestCase(test_base.BaseDbObjectTestCase, testlib_api.SqlTestCase): _test_class = l3agent.RouterL3AgentBinding def setUp(self): super(RouterL3AgentBindingDbObjTestCase, self).setUp() self._create_test_router() def getter(): self._create_test_agent() return self._agent['id'] index = iter(range(1, len(self.objs) + 1)) self.update_obj_fields( {'router_id': self._router.id, 'binding_index': lambda: next(index), 'l3_agent_id': getter}) ","# Copyright (c) 2016 Intel Corporation. # # 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. from neutron.objects import l3agent from neutron.tests.unit.objects import test_base from neutron.tests.unit import testlib_api class RouterL3AgentBindingIfaceObjTestCase(test_base.BaseObjectIfaceTestCase): _test_class = l3agent.RouterL3AgentBinding class RouterL3AgentBindingDbObjTestCase(test_base.BaseDbObjectTestCase, testlib_api.SqlTestCase): _test_class = l3agent.RouterL3AgentBinding def setUp(self): super(RouterL3AgentBindingDbObjTestCase, self).setUp() self._create_test_router() def getter(): self._create_test_agent() return self._agent['id'] self.update_obj_fields( {'router_id': self._router.id, 'l3_agent_id': getter}) " Fix front-end dash removal method for signup ufid,"'use strict'; angular.module('users').controller('AuthenticationController', ['$scope', '$http', '$location', 'Authentication', function($scope, $http, $location, Authentication) { $scope.authentication = Authentication; // If user is signed in then redirect back home if ($scope.authentication.user) $location.path('/'); $scope.signup = function() { if ($scope.credentials) $scope.convertID(); $http.post('/auth/signup', $scope.credentials).success(function(response) { // If successful we assign the response to the global user model $scope.authentication.user = response; // And redirect to the index page $location.path('/'); }).error(function(response) { $scope.error = response.message; }); }; $scope.convertID = function() { var dashPos = $scope.credentials.ufid.indexOf('-'); if (dashPos !== -1) $scope.credentials.ufid = $scope.credentials.ufid.slice(0,dashPos) + $scope.credentials.ufid.slice(dashPos + 1); }; $scope.signin = function() { $http.post('/auth/signin', $scope.credentials).success(function(response) { // If successful we assign the response to the global user model $scope.authentication.user = response; // And redirect to the index page $location.path('/'); }).error(function(response) { $scope.error = response.message; }); }; } ]); ","'use strict'; angular.module('users').controller('AuthenticationController', ['$scope', '$http', '$location', 'Authentication', function($scope, $http, $location, Authentication) { $scope.authentication = Authentication; // If user is signed in then redirect back home if ($scope.authentication.user) $location.path('/'); $scope.signup = function() { if ($scope.credentials) $scope.convertID(); $http.post('/auth/signup', $scope.credentials).success(function(response) { // If successful we assign the response to the global user model $scope.authentication.user = response; // And redirect to the index page $location.path('/'); }).error(function(response) { $scope.error = response.message; }); }; $scope.convertID = function() { var dashPos = $scope.credentials.ufid.indexOf('-'); if (dashPos !== -1) $scope.credentials.ufid = $scope.credentials.ufid.slice(0,dashPos - 1) + $scope.credentials.slice(dashPos + 1); }; $scope.signin = function() { $http.post('/auth/signin', $scope.credentials).success(function(response) { // If successful we assign the response to the global user model $scope.authentication.user = response; // And redirect to the index page $location.path('/'); }).error(function(response) { $scope.error = response.message; }); }; } ]); " Store StyleBlock descendants to speed up containsOpenStyleBlock,"<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace App\Libraries\Markdown\StyleBlock; use League\CommonMark\Block\Element\AbstractBlock; use League\CommonMark\Cursor; class Element extends AbstractBlock { /** * @var string */ protected $class; /** * @var static[] */ protected $containedStyleBlocks; public function __construct(string $class) { $this->class = $class; $this->containedStyleBlocks = []; } public function getClass(): string { return $this->class; } public function canContain(AbstractBlock $block): bool { if ($block instanceof static) { $this->containedStyleBlocks[] = $block; } return true; } public function isCode(): bool { return false; } public function matchesNextLine(Cursor $cursor): bool { // Make sure the most nested open StyleBlock tries to handle this first if ($cursor->getLine() === '}}}' && !$this->containsOpenStyleBlock()) { $cursor->advanceToEnd(); return false; } return true; } private function containsOpenStyleBlock(): bool { // Assumes that these StyleBlocks are never removed from descendant tree foreach ($this->containedStyleBlocks as $styleBlock) { if ($styleBlock->isOpen()) { return true; } } return false; } } ","<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace App\Libraries\Markdown\StyleBlock; use League\CommonMark\Block\Element\AbstractBlock; use League\CommonMark\Cursor; class Element extends AbstractBlock { /** * @var string */ protected $class; public function __construct(string $class) { $this->class = $class; } public function getClass(): string { return $this->class; } public function canContain(AbstractBlock $block): bool { return true; } public function isCode(): bool { return false; } public function matchesNextLine(Cursor $cursor): bool { // Make sure the most nested open StyleBlock tries to handle this first if ($cursor->getLine() === '}}}' && !$this->containsOpenStyleBlock()) { $cursor->advanceToEnd(); return false; } return true; } private function containsOpenStyleBlock(): bool { $walker = $this->walker(); $walker->next(); while (($event = $walker->next()) !== null) { if (!$event->isEntering()) { continue; } $node = $event->getNode(); if ($node instanceof static && $node->isOpen()) { return true; } } return false; } } " Add CAS 3.0 specific endpoints,""""""" (2) CAS server URIs as described in the CAS protocol. """""" from django.conf.urls import patterns from django.conf.urls import url from mama_cas.views import LoginView from mama_cas.views import LogoutView from mama_cas.views import ValidateView from mama_cas.views import ServiceValidateView from mama_cas.views import ProxyValidateView from mama_cas.views import ProxyView from mama_cas.views import WarnView from mama_cas.views import SamlValidateView urlpatterns = patterns('', url(r'^login/?$', LoginView.as_view(), name='cas_login'), url(r'^logout/?$', LogoutView.as_view(), name='cas_logout'), url(r'^validate/?$', ValidateView.as_view(), name='cas_validate'), url(r'^serviceValidate/?$', ServiceValidateView.as_view(), name='cas_service_validate'), url(r'^proxyValidate/?$', ProxyValidateView.as_view(), name='cas_proxy_validate'), url(r'^proxy/?$', ProxyView.as_view(), name='cas_proxy'), url(r'^p3/serviceValidate/?$', ServiceValidateView.as_view(), name='cas_p3_service_validate'), url(r'^p3/proxyValidate/?$', ProxyValidateView.as_view(), name='cas_p3_proxy_validate'), url(r'^warn/?$', WarnView.as_view(), name='cas_warn'), url(r'^samlValidate/?$', SamlValidateView.as_view(), name='cas_saml_validate'), ) ",""""""" URLconf for CAS server URIs as described in the CAS protocol. """""" from django.conf.urls import patterns from django.conf.urls import url from mama_cas.views import LoginView from mama_cas.views import LogoutView from mama_cas.views import ValidateView from mama_cas.views import ServiceValidateView from mama_cas.views import ProxyValidateView from mama_cas.views import ProxyView from mama_cas.views import WarnView from mama_cas.views import SamlValidateView urlpatterns = patterns('', url(r'^login/?$', LoginView.as_view(), name='cas_login'), url(r'^logout/?$', LogoutView.as_view(), name='cas_logout'), url(r'^validate/?$', ValidateView.as_view(), name='cas_validate'), url(r'^serviceValidate/?$', ServiceValidateView.as_view(), name='cas_service_validate'), url(r'^proxyValidate/?$', ProxyValidateView.as_view(), name='cas_proxy_validate'), url(r'^proxy/?$', ProxyView.as_view(), name='cas_proxy'), url(r'^warn/?$', WarnView.as_view(), name='cas_warn'), url(r'^samlValidate/?$', SamlValidateView.as_view(), name='cas_saml_validate'), ) " Allow to set items in AST.,"from collections import OrderedDict, Mapping import json __all__ = ['AST'] class AST(Mapping): def __init__(self, **kwargs): self._elements = OrderedDict(**kwargs) def add(self, key, value): previous = self._elements.get(key, None) if previous is None: self._elements[key] = [value] else: previous.append(value) def update(self, *args, **kwargs): for dct in args: for k, v in dct: self.add(k, v) for k, v in kwargs.items(): self.add(k, v) @property def first(self): key = self.elements.keys[0] return self.elements[key] def __iter__(self): return iter(self._elements) def __contains__(self, key): return key in self._elements def __len__(self): return len(self._elements) def __getitem__(self, key): if key not in self._elements: self._elements[key] = list() return self._elements[key] def __setitem__(self, key, value): self._elements[key] = value def __getattr__(self, key): return self.__getitem__(key) if key in self._elements: return self.__getitem__(key) raise KeyError(key) @staticmethod def serializable(obj): if isinstance(obj, AST): return obj._elements return obj def __repr__(self): return self.serializable(self._elements) def __str__(self): return json.dumps(self._elements, indent=4, default=self.serializable) ","from collections import OrderedDict, Mapping import json class AST(Mapping): def __init__(self, **kwargs): self._elements = OrderedDict(**kwargs) def add(self, key, value): previous = self._elements.get(key, None) if previous is None: self._elements[key] = [value] else: previous.append(value) def update(self, *args, **kwargs): for dct in args: for k, v in dct: self.add(k, v) for k, v in kwargs.items(): self.add(k, v) @property def first(self): key = self.elements.keys[0] return self.elements[key] def __iter__(self): return iter(self._elements) def __contains__(self, key): return key in self._elements def __len__(self): return len(self._elements) def __getitem__(self, key): if key not in self._elements: self._elements[key] = list() return self._elements[key] def __getattr__(self, key): return self.__getitem__(key) if key in self._elements: return self.__getitem__(key) raise KeyError(key) @staticmethod def serializable(obj): if isinstance(obj, AST): return obj._elements return obj def __repr__(self): return self.serializable(self._elements) def __str__(self): return json.dumps(self._elements, indent=4, default=self.serializable) " "Set focus on input text + modic","<html> <head> <meta charset=""UTF-8""> <title>films</title> <link href=""css/cinema.css"" rel=""stylesheet"" type=""text/css""/> <script src=""https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js""></script> </head> <body> <?php include './header.php'; ?> <input id=""titre"" type=""search"" name=""titre"" placeholder=""titre"" onkeyup=""search(value)""> <div id=""result""></div> </body> <?php include './footer.php'; ?> <script> function search(value) { /*if(arguments.length == 0) { var value = $(""#titre"").val(); } else { value = arguments[0]; }*/ if(value === undefined) { var value = $(""#titre"").val(); } $.ajax( { url: ""search_result.php?titre="" + value, success: function(result) { $(""#result"").html(result); }, error: function() { $(""#result"").html(""<h1 style='color: red'>ERROR</h1>""); } } ); }; search(); $( ""#titre"" ).focus(); </script> </html>","<html> <head> <meta charset=""UTF-8""> <title>films</title> <script src=""https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js""></script> </head> <body> <?php include './header.php'; ?> <input id=""titre"" type=""search"" name=""titre"" placeholder=""titre""> <input id=""search"" type=""submit""> <div id=""result""></div> </body> <?php include './footer.php'; ?> <script> $(""#search"").click(function() { var value = $(""#titre"").val(); $.ajax( { url: ""search_result.php?titre="" + value, success: function(result) { $(""#result"").html(result); }, error: function() { $(""#result"").html(""<h1 style='color: red'>ERROR</h1>""); } } ); }); </script> </html>" "Add additional checks in unref() make sure no code calls unref() more than it should. Requires taking a wider lock, but this isn't performance critical code anyway","package com.litl.leveldb; import java.io.Closeable; import android.util.Log; abstract class NativeObject implements Closeable { private static final String TAG = NativeObject.class.getSimpleName(); protected long mPtr; private int mRefCount = 0; protected NativeObject() { // The Java wrapper counts as one reference, will // be released when closed ref(); } protected NativeObject(long ptr) { this(); if (ptr == 0) { throw new OutOfMemoryError(""Failed to allocate native object""); } mPtr = ptr; } synchronized protected long getPtr() { return mPtr; } protected void assertOpen(String message) { if (getPtr() == 0) { throw new IllegalStateException(message); } } synchronized void ref() { mRefCount++; } synchronized void unref() { if (mRefCount <= 0) { throw new IllegalStateException(""Reference count is already 0""); } mRefCount--; if (mRefCount == 0) { closeNativeObject(mPtr); mPtr = 0; } } protected abstract void closeNativeObject(long ptr); @Override public void close() { unref(); } @Override protected void finalize() throws Throwable { if (mPtr != 0) { Log.w(TAG, ""NativeObject "" + getClass().getSimpleName() + "" was finalized before native resource was closed, did you forget to call close()?""); } super.finalize(); } } ","package com.litl.leveldb; import java.io.Closeable; import java.util.concurrent.atomic.AtomicInteger; import android.util.Log; abstract class NativeObject implements Closeable { private static final String TAG = NativeObject.class.getSimpleName(); protected long mPtr; private AtomicInteger mRefCount = new AtomicInteger(); protected NativeObject() { // The Java wrapper counts as one reference, will // be released when closed ref(); } protected NativeObject(long ptr) { this(); if (ptr == 0) { throw new OutOfMemoryError(""Failed to allocate native object""); } mPtr = ptr; } protected long getPtr() { return mPtr; } protected void assertOpen(String message) { if (mPtr == 0) { throw new IllegalStateException(message); } } void ref() { mRefCount.incrementAndGet(); } void unref() { if (mRefCount.decrementAndGet() == 0) { closeNativeObject(mPtr); mPtr = 0; } } protected abstract void closeNativeObject(long ptr); @Override public void close() { unref(); } @Override protected void finalize() throws Throwable { if (mPtr != 0) { Log.w(TAG, ""NativeObject "" + getClass().getSimpleName() + "" was finalized before native resource was closed, did you forget to call close()?""); } super.finalize(); } } " "test: Add Python 2.7 to nox test environment It is needed for sanity checking the code against the current deployment environment. Signed-off-by: Nabarun Pal <46a782cbd1e9f752958998187886c2b51fda054c@gmail.com>","""""""Automation using nox. """""" import nox nox.options.sessions = [""dev""] nox.options.reuse_existing_virtualenvs = True nox.options.error_on_external_run = True @nox.session(python=""3.5"") def dev(session): session.install(""-r"", ""requirements.txt"") session.run(""python"", ""manage.py"", *session.posargs) @nox.session(python=[""2.7"", ""3.5"", ""3.6"", ""3.7"", ""3.8""]) def test(session): session.install(""-r"", ""requirements.txt"") session.install(""-r"", ""tools/requirements-test.txt"") session.run(""pytest"", ""--cov"", ""-v"", ""--tb=native"") session.run(""coverage"", ""report"", ""-m"") @nox.session(python=[""3.5"", ""3.6"", ""3.7"", ""3.8""]) def lint(session): session.install(""pre-commit"") session.run(""pre-commit"", ""run"", ""--all-files"") @nox.session(python=""3.5"") def docs(session): session.install(""-r"", ""tools/requirements-docs.txt"") def get_sphinx_build_command(kind): return [ ""sphinx-build"", ""-W"", ""-d"", ""docs/build/_doctrees/"" + kind, ""-b"", kind, ""docs/source"", ""docs/build/"" + kind, ] session.run(*get_sphinx_build_command(""html"")) ","""""""Automation using nox. """""" import nox nox.options.sessions = [""dev""] nox.options.reuse_existing_virtualenvs = True nox.options.error_on_external_run = True @nox.session(python=""3.5"") def dev(session): session.install(""-r"", ""requirements.txt"") session.run(""python"", ""manage.py"", *session.posargs) @nox.session(python=[""3.5"", ""3.6"", ""3.7"", ""3.8""]) def test(session): session.install(""-r"", ""requirements.txt"") session.install(""-r"", ""tools/requirements-test.txt"") session.run(""pytest"", ""--cov"", ""-v"", ""--tb=native"") session.run(""coverage"", ""report"", ""-m"") @nox.session(python=[""3.5"", ""3.6"", ""3.7"", ""3.8""]) def lint(session): session.install(""pre-commit"") session.run(""pre-commit"", ""run"", ""--all-files"") @nox.session(python=""3.5"") def docs(session): session.install(""-r"", ""tools/requirements-docs.txt"") def get_sphinx_build_command(kind): return [ ""sphinx-build"", ""-W"", ""-d"", ""docs/build/_doctrees/"" + kind, ""-b"", kind, ""docs/source"", ""docs/build/"" + kind, ] session.run(*get_sphinx_build_command(""html"")) " Remove Object.assign for testing compat,"// Written by Joshua Paul A. Chan (function() { ""use strict""; // Import variables if present (from env.js) (thanks @jvandemo) var env = {}; if(window){ env = window.__env; } // Initialize app angular.module('wr', ['ui.router', 'wr.controllers', 'wr.services', 'wr.directives', 'wr.components']) .constant('__env', env) .config(function($logProvider, $locationProvider, $stateProvider, $urlMatcherFactoryProvider, __env) { // enable/disable angular debug $logProvider.debugEnabled(__env.enableDebug); // FIXME locationProvider // $locationProvider.html5Mode(true); // make trailing slashes optional $urlMatcherFactoryProvider.strictMode(false); $stateProvider .state('convos', { url: ""/conversations"", templateUrl: ""client/app/templates/conversations.html"", deepStateRedirect: true }) .state('convos.convo', { url: ""/{convoId}"", views: { convo: { template: ""<convo/>"" } } }); }); // Initialize modules angular.module('wr.controllers', []); angular.module('wr.services', []); angular.module('wr.directives', []); angular.module('wr.components', []); }()); ","// Written by Joshua Paul A. Chan (function() { ""use strict""; // Import variables if present (from env.js) (thanks @jvandemo) var env = {}; if(window){ Object.assign(env, window.__env); } // Initialize app angular.module('wr', ['ui.router', 'wr.controllers', 'wr.services', 'wr.directives', 'wr.components']) .constant('__env', env) .config(function($logProvider, $locationProvider, $stateProvider, $urlMatcherFactoryProvider, __env) { // enable/disable angular debug $logProvider.debugEnabled(__env.enableDebug); // FIXME locationProvider // $locationProvider.html5Mode(true); // make trailing slashes optional $urlMatcherFactoryProvider.strictMode(false); $stateProvider .state('convos', { url: ""/conversations"", templateUrl: ""client/app/templates/conversations.html"", deepStateRedirect: true }) .state('convos.convo', { url: ""/{convoId}"", views: { convo: { template: ""<convo/>"" } } }); }); // Initialize modules angular.module('wr.controllers', []); angular.module('wr.services', []); angular.module('wr.directives', []); angular.module('wr.components', []); }()); " Add ability to click on listing cards,"import React from 'react'; import { Link } from 'react-router'; import { Card, Image, Icon } from 'semantic-ui-react'; import ListingDeleteModal from './ListingDeleteModal'; const getIconString = str => ( str === 'home improvement' ? 'home' : 'laptop' ); const Listing = ({ userId, listingId, title, createdAt, body, type, handleDelete, pathname, cutBody }) => <Card centered raised> <Link to={`/listings/${listingId}`} > <Card centered raised> <Card.Content> { pathname === '/dashboard' ? <ListingDeleteModal handleDelete={handleDelete} userId={userId} listingId={listingId} /> : null } <Image floated=""right""> <Icon name={getIconString(type)} size=""big"" /> </Image> <Card.Header> { title } </Card.Header> <Card.Meta> { createdAt } </Card.Meta> <Card.Description> { cutBody(body) } </Card.Description> </Card.Content> </Card> </Link> </Card>; Listing.propTypes = { title: React.PropTypes.string.isRequired, createdAt: React.PropTypes.string.isRequired, body: React.PropTypes.string.isRequired, type: React.PropTypes.string.isRequired, userId: React.PropTypes.number, listingId: React.PropTypes.number.isRequired, handleDelete: React.PropTypes.func, pathname: React.PropTypes.string.isRequired, }; export default Listing; ","import React from 'react'; import { Card, Image, Icon } from 'semantic-ui-react'; import ListingDeleteModal from './ListingDeleteModal'; const getIconString = str => ( str === 'home improvement' ? 'home' : 'laptop' ); const Listing = ({ userId, listingId, title, createdAt, body, type, handleDelete, pathname, cutBody }) => <Card centered raised> <Card.Content> { pathname === '/dashboard' ? <ListingDeleteModal handleDelete={handleDelete} userId={userId} listingId={listingId} /> : null } <Image floated=""right""> <Icon name={getIconString(type)} size=""big"" /> </Image> <Card.Header> { title } </Card.Header> <Card.Meta> { createdAt } </Card.Meta> <Card.Description> { cutBody(body) } </Card.Description> </Card.Content> </Card>; Listing.propTypes = { title: React.PropTypes.string.isRequired, createdAt: React.PropTypes.string.isRequired, body: React.PropTypes.string.isRequired, type: React.PropTypes.string.isRequired, userId: React.PropTypes.number, listingId: React.PropTypes.number.isRequired, handleDelete: React.PropTypes.func, pathname: React.PropTypes.string.isRequired, }; export default Listing; " Change env variables for node setup to single URI varieable,"from django.conf import settings from web3 import HTTPProvider, Web3 from web3.middleware import geth_poa_middleware from .utils import Singleton class Web3Service(metaclass=Singleton): """"""Creates a `web3` instance based on the given Provider."""""" def __init__(self, *args, **kwargs): """"""Initializes the `web3` object. Args: rpc_provider (HTTPProvider): Valid `web3` HTTPProvider instance (optional) """""" rpc_provider = kwargs.pop('rpc_provider', None) if not rpc_provider: timeout = getattr(settings, ""ETHEREUM_NODE_TIMEOUT"", 10) uri = settings.ETHEREUM_NODE_PORT rpc_provider = HTTPProvider( endpoint_uri=uri, request_kwargs={ ""timeout"": timeout } ) self.web3 = Web3(rpc_provider) # If running in a network with PoA consensus, inject the middleware if getattr(settings, ""ETHEREUM_GETH_POA"", False): self.web3.middleware_stack.inject(geth_poa_middleware, layer=0) super(Web3Service, self).__init__() ","from django.conf import settings from web3 import HTTPProvider, Web3 from web3.middleware import geth_poa_middleware from .utils import Singleton class Web3Service(metaclass=Singleton): """"""Creates a `web3` instance based on the given Provider."""""" def __init__(self, *args, **kwargs): """"""Initializes the `web3` object. Args: rpc_provider (HTTPProvider): Valid `web3` HTTPProvider instance (optional) """""" rpc_provider = kwargs.pop('rpc_provider', None) if not rpc_provider: timeout = getattr(settings, ""ETHEREUM_NODE_TIMEOUT"", 10) uri = ""{scheme}://{host}:{port}"".format( host=settings.ETHEREUM_NODE_HOST, port=settings.ETHEREUM_NODE_PORT, scheme=""https"" if settings.ETHEREUM_NODE_SSL else ""http"", ) rpc_provider = HTTPProvider( endpoint_uri=uri, request_kwargs={ ""timeout"": timeout } ) self.web3 = Web3(rpc_provider) # If running in a network with PoA consensus, inject the middleware if getattr(settings, ""ETHEREUM_GETH_POA"", False): self.web3.middleware_stack.inject(geth_poa_middleware, layer=0) super(Web3Service, self).__init__() " Fix windows phone API calls,"// cordova-plugin-spinnerdialog // Copyright © 2015 filfat Studios AB // Repo: https://github.com/filfat-Studios-AB/cordova-plugin-spinnerdialog /* global Windows, cordova */ var progressIndicator; cordova.commandProxy.add(""SpinnerDialog"",{ show: function (successCallback, errorCallback, data) { if (typeof Windows !== 'undefined' && typeof Windows.UI !== 'undefined' /* Check that we have a UI to work with */ && typeof Windows.UI.ViewManagement.StatusBar !== 'undefined' /* Check that we have the StatusBar to work with*/) { var data = data[0] || { title: undefined }; progressIndicator = Windows.UI.ViewManagement.StatusBar.ProgressIndicator || Windows.UI.ViewManagement.StatusBar.getForCurrentView().progressIndicator; if (data.title == null) data.title = undefined; progressIndicator.text = typeof data.title !== 'undefined' ? data.title : 'Loading...'; progressIndicator.showAsync(); } }, hide: function (successCallback, errorCallback, data) { if (typeof Windows !== 'undefined' && typeof Windows.UI !== 'undefined' /* Check that we have a UI to work with */ && typeof Windows.UI.ViewManagement.StatusBar !== 'undefined' /* Check that we have the StatusBar to work with*/) { progressIndicator.hideAsync(); } } }); ","// cordova-plugin-spinnerdialog // Copyright © 2015 filfat Studios AB // Repo: https://github.com/filfat-Studios-AB/cordova-plugin-spinnerdialog /* global Windows, cordova */ var progressIndicator; cordova.commandProxy.add(""SpinnerDialog"",{ show: function (successCallback, errorCallback, data) { if (typeof Windows !== 'undefined' && typeof Windows.UI !== 'undefined' /* Check that we have a UI to work with */ && typeof Windows.UI.ViewManagement.StatusBar !== 'undefined' /* Check that we have the StatusBar to work with*/) { var data = data[0]; progressIndicator = Windows.UI.ViewManagement.StatusBar.ProgressIndicator; if(data.title == null) data.title = undefined; progressIndicator.text = typeof data.title !== 'undefined' ? data.title : 'Loading...'; progressIndicator.showAsync(); } }, hide: function (successCallback, errorCallback, data) { if (typeof Windows !== 'undefined' && typeof Windows.UI !== 'undefined' /* Check that we have a UI to work with */ && typeof Windows.UI.ViewManagement.StatusBar !== 'undefined' /* Check that we have the StatusBar to work with*/) { progressIndicator.hideAsync(); } } }); " Fix value get - use offset,"# -*- coding: utf8 -*- from time import time __author__ = 'sergey' class CacheTTLseconds(object): """""" Simple cache storage { key (int | str) : [ timestamp (float), - then added, updated, set to 0 if expired values (int | str) - some data ], ... } """""" OFFSET_TIME = 0 OFFSET_VALUE = 1 _max_ttl = 300 _storage = None def __init__(self): self._storage = {} pass def __len__(self): return len(self._storage) def set_max_ttl(self, seconds): self._max_ttl = seconds return self def set(self, key, value): self._storage[ key ] = [time(), value] return self def get(self, key, default=None): # not setted val = self._storage.get(key, [0, default])[self.OFFSET_VALUE] now = time() # update time only if value was set if key in self._storage: self._storage[ key ][self.OFFSET_TIME] = now return val def unset(self, key): if key in self._storage: del self._storage[ key ] return self def clear(self): now = time() count = 0 for key, item in tuple(self._storage.items()): if now - item[self.OFFSET_TIME] > self._max_ttl: del self._storage[key] count += 1 return count ","# -*- coding: utf8 -*- from time import time __author__ = 'sergey' class CacheTTLseconds(object): """""" Simple cache storage { key (int | str) : [ timestamp (float), - then added, updated, set to 0 if expired values (int | str) - some data ], ... } """""" OFFSET_TIME = 0 OFFSET_VALUE = 1 _max_ttl = 300 _storage = None def __init__(self): self._storage = {} pass def __len__(self): return len(self._storage) def set_max_ttl(self, seconds): self._max_ttl = seconds return self def set(self, key, value): self._storage[ key ] = [time(), value] return self def get(self, key, default=None): # not setted val = self._storage.get(key, [0, default]) now = time() # update time only if value was set if key in self._storage: self._storage[ key ][self.OFFSET_TIME] = now return val def unset(self, key): if key in self._storage: del self._storage[ key ] return self def clear(self): now = time() count = 0 for key, item in tuple(self._storage.items()): if now - item[self.OFFSET_TIME] > self._max_ttl: del self._storage[key] count += 1 return count " Change artifact location to suite CircleCI,"module.exports = function(grunt) { grunt.loadNpmTasks(""grunt-mocha-test""); grunt.loadNpmTasks(""grunt-mocha-istanbul""); var testOutputLocation = process.env.CIRCLE_TEST_REPORTS || ""test_output""; var artifactsLocation = process.env.CIRCLE_ARTIFACTS || ""build_artifacts""; grunt.initConfig({ mochaTest: { test: { src: [""test/**/*.js""] }, ci: { src: [""test/**/*.js""], options: { reporter: ""xunit"", captureFile: testOutputLocation + ""/mocha/results.xml"", quiet: true } } }, mocha_istanbul: { coverage: { src: [""test/**/*.js""], options: { coverageFolder: artifactsLocation, check: { lines: 100, statements: 100, branches: 100, functions: 100 }, reportFormats: [""lcov""] } } } }); grunt.registerTask(""test"", [""mochaTest:test"", ""mocha_istanbul""]); grunt.registerTask(""ci-test"", [""mochaTest:ci"", ""mocha_istanbul""]); grunt.registerTask(""default"", ""test""); }; ","module.exports = function(grunt) { grunt.loadNpmTasks(""grunt-mocha-test""); grunt.loadNpmTasks(""grunt-mocha-istanbul""); var testOutputLocation = process.env.CIRCLE_TEST_REPORTS || ""test_output""; var artifactsLocation = process.env.CIRCLE_ARTIFACTS || ""build_artifacts""; grunt.initConfig({ mochaTest: { test: { src: [""test/**/*.js""] }, ci: { src: [""test/**/*.js""], options: { reporter: ""xunit"", captureFile: testOutputLocation + ""/mocha/results.xml"", quiet: true } } }, mocha_istanbul: { coverage: { src: [""test/**/*.js""], options: { coverageFolder: artifactsLocation + ""/coverage"", check: { lines: 100, statements: 100, branches: 100, functions: 100 }, reportFormats: [""lcov""] } } } }); grunt.registerTask(""test"", [""mochaTest:test"", ""mocha_istanbul""]); grunt.registerTask(""ci-test"", [""mochaTest:ci"", ""mocha_istanbul""]); grunt.registerTask(""default"", ""test""); }; " Add first stateless function component,"var React = require('react'); var PropTypes = require('prop-types'); function SelectLanguage(props) { var languages = ['All', 'JavaScript', 'Ruby', 'Java', 'CSS', 'Python']; return ( <ul className='languages'> {languages.map(function (lang){ return ( <li style={lang === props.selectedLanguage ? { color: '#d0021b'}: null} onClick={props.onSelect.bind(null, lang)} key={lang}> {lang} </li> ) }, this)} </ul> ) } SelectLanguage.propTypes = { selectedLanguage: PropTypes.string.isRequired, onSelect: PropTypes.func.isRequired, } class Popular extends React.Component { constructor (props) { super(props); this.state = { selectedLanguage: 'All' }; this.updateLanguage = this.updateLanguage.bind(this); } updateLanguage(lang) { this.setState(function() { return { selectedLanguage: lang } }); } render() { return ( <div> <SelectLanguage selectedLanguage={this.state.selectedLanguage} onSelect={this.updateLanguage} /> </div> ) } } module.exports = Popular;","var React = require('react'); class Popular extends React.Component { constructor (props) { super(props); this.state = { selectedLanguage: 'All' }; this.updateLanguage = this.updateLanguage.bind(this); } updateLanguage(lang) { this.setState(function() { return { selectedLanguage: lang } }); } render() { var languages = ['All', 'JavaScript', 'Ruby', 'Java', 'CSS', 'Python']; return ( <ul className='languages'> <p>Selected Language: {this.state.selectedLanguage}</p> {languages.map(function (lang){ return ( <li style={lang === this.state.selectedLanguage ? { color: '#d0021b'}: null} onClick={this.updateLanguage.bind(null, lang)} key={lang}> {lang} </li> ) }, this)} </ul> ) } } module.exports = Popular;" Fix bad usage of a reserved word,"from django.views.generic import ListView, CreateView from django.utils.timezone import now from timer.models import Timer, Location, Station, Moon, System from timer.forms import TimerForm class TimerCreateView(CreateView): model = Timer form_class = TimerForm class TimerListView(ListView): model = Timer template_name = 'timer/timer_list.html' def get_queryset(self): qs = super(TimerListView, self).get_queryset().select_related('location', 'station', 'moon', 'system') if int(self.request.GET.get('all', 0)) == 0: qs = qs.filter(expiration__gt=now()) typ = int(self.request.GET.get('type', 0)) if typ == 1: qs = [m for m in qs if m.location.get_type == 'Station'] if typ == 2: qs = [m for m in qs if m.location.get_type == 'System'] if typ == 3: qs = [m for m in qs if m.location.get_type == 'Moon'] return qs def get_context_data(self, **kwargs): ctx = super(TimerListView, self).get_context_data(**kwargs) ctx.update({ 'list_all': int(self.request.GET.get('all', 0)), 'list_type': int(self.request.GET.get('type', 0)), }) return ctx ","from django.views.generic import ListView, CreateView from django.utils.timezone import now from timer.models import Timer, Location, Station, Moon, System from timer.forms import TimerForm class TimerCreateView(CreateView): model = Timer form_class = TimerForm class TimerListView(ListView): model = Timer template_name = 'timer/timer_list.html' def get_queryset(self): qs = super(TimerListView, self).get_queryset().select_related('location', 'station', 'moon', 'system') if int(self.request.GET.get('all', 0)) == 0: qs = qs.filter(expiration__gt=now()) type = int(self.request.GET.get('type', 0)) if type == 1: qs = [m for m in qs if m.location.get_type == 'Station'] if type == 2: qs = [m for m in qs if m.location.get_type == 'System'] if type == 3: qs = [m for m in qs if m.location.get_type == 'Moon'] return qs def get_context_data(self, **kwargs): ctx = super(TimerListView, self).get_context_data(**kwargs) ctx.update({ 'list_all': int(self.request.GET.get('all', 0)), 'list_type': int(self.request.GET.get('type', 0)), }) return ctx" Adjust code style to reduce lines of code :bear:,"import datetime from django.utils.timezone import utc from .models import Ticket class TicketServices(): def edit_ticket_once(self, **kwargs): id_list = kwargs.get('id_list') edit_tags = kwargs.get('edit_tags') edit_requester = kwargs.get('edit_requester') edit_subject = kwargs.get('edit_subject') edit_due_at = kwargs.get('edit_due_at') edit_assignee = kwargs.get('edit_assignee') if edit_tags: Ticket.objects.filter(pk__in=id_list).update(tags=edit_tags) if edit_subject: Ticket.objects.filter(pk__in=id_list).update(subject=edit_subject) if edit_requester: Ticket.objects.filter(pk__in=id_list).update( requester=edit_requester ) if edit_due_at: Ticket.objects.filter(pk__in=id_list).update( due_at=datetime.datetime.strptime( edit_due_at, '%m/%d/%Y' ).replace(tzinfo=utc) ) if edit_assignee: Ticket.objects.filter(pk__in=id_list).update( assignee=edit_assignee ) ","import datetime from django.utils.timezone import utc from .models import Ticket class TicketServices(): def edit_ticket_once(self, **kwargs): id_list = kwargs.get('id_list') edit_tags = kwargs.get('edit_tags') edit_requester = kwargs.get('edit_requester') edit_subject = kwargs.get('edit_subject') edit_due_at = kwargs.get('edit_due_at') edit_assignee = kwargs.get('edit_assignee') if edit_tags: Ticket.objects.filter( pk__in=id_list ).update(tags=edit_tags) if edit_subject: Ticket.objects.filter( pk__in=id_list ).update(subject=edit_subject) if edit_requester: Ticket.objects.filter( pk__in=id_list ).update(requester=edit_requester) if edit_due_at: Ticket.objects.filter( pk__in=id_list ).update( due_at=datetime.datetime.strptime( edit_due_at, ""%m/%d/%Y"" ).replace(tzinfo=utc) ) if edit_assignee: Ticket.objects.filter( pk__in=id_list ).update(assignee=edit_assignee) " Correct function call to no longer pass one parameter to many,"<?php namespace Picqer\Financials\Exact\Query; class Resultset { protected $connection; protected $url; protected $class; protected $params; public function __construct($connection, $url, $class, $params) { $this->connection = $connection; $this->url = $url; $this->class = $class; $this->params = $params; } public function next() { $result = $this->connection->get($this->url, $this->params); $this->url = $this->connection->nextUrl; $this->params = null; return $this->collectionFromResult($result); } public function hasMore() { return $this->url !== null; } protected function collectionFromResult($result) { // If we have one result which is not an assoc array, make it the first element of an array for the // collectionFromResult function so we always return a collection from filter if ((bool) count(array_filter(array_keys($result), 'is_string'))) { $result = [ $result ]; } $class = $this->class; $collection = []; foreach ($result as $r) { $collection[] = new $class($this->connection, $r); } return $collection; } } ","<?php namespace Picqer\Financials\Exact\Query; class Resultset { protected $connection; protected $url; protected $class; protected $params; public function __construct($connection, $url, $class, $params) { $this->connection = $connection; $this->url = $url; $this->class = $class; $this->params = $params; } public function next() { $result = $this->connection->get($this->url, $this->params); $this->url = $this->connection->nextUrl; $this->params = null; return $this->collectionFromResult($result, $this->class); } public function hasMore() { return $this->url !== null; } protected function collectionFromResult($result) { // If we have one result which is not an assoc array, make it the first element of an array for the // collectionFromResult function so we always return a collection from filter if ((bool) count(array_filter(array_keys($result), 'is_string'))) { $result = [ $result ]; } $class = $this->class; $collection = []; foreach ($result as $r) { $collection[] = new $class($this->connection, $r); } return $collection; } } " Add 'nose' to required packages for testing.,"import os.path as op import re from setuptools import setup def read(name, only_open=False): f = open(op.join(op.dirname(__file__), name)) return f if only_open else f.read() ext_version = None with read('flask_json.py', only_open=True) as f: for line in f: if line.startswith('__version__'): ext_version, = re.findall(r""__version__\W*=\W*'([^']+)'"", line) break setup( name='Flask-JSON', version=ext_version, url='https://github.com/skozlovf/flask-json', license='BSD', author='Sergey Kozlov', author_email='skozlovf@gmail.com', description='Better JSON support for Flask', long_description=read('README.rst'), py_modules=['flask_json'], zip_safe=False, include_package_data=True, platforms='any', install_requires=['Flask>=0.10'], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], tests_require=['nose>=1.0'], test_suite='nose.collector' ) ","import os.path as op import re from setuptools import setup def read(name, only_open=False): f = open(op.join(op.dirname(__file__), name)) return f if only_open else f.read() ext_version = None with read('flask_json.py', only_open=True) as f: for line in f: if line.startswith('__version__'): ext_version, = re.findall(r""__version__\W*=\W*'([^']+)'"", line) break setup( name='Flask-JSON', version=ext_version, url='https://github.com/skozlovf/flask-json', license='BSD', author='Sergey Kozlov', author_email='skozlovf@gmail.com', description='Better JSON support for Flask', long_description=read('README.rst'), py_modules=['flask_json'], zip_safe=False, include_package_data=True, platforms='any', install_requires=['Flask>=0.10'], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], test_suite='nose.collector' ) " "Improve path resolution in mockserver, https://github.com/Starcounter/starcounter-include/pull/111#discussion_r215271675 https://github.com/Starcounter/starcounter-include/pull/111#discussion_r215273089","const connect = require('connect'); const fs = require('fs'); const path = require('path'); const servingDirectory = 'sc/'; connect().use('/sc/htmlmerger', function fooMiddleware(req, res, next) { // req.url starts with ""/foo"" const query = req._parsedUrl.query; const pairs = query.split('&'); let content = ''; // console.log('Merging ' + query); pairs.forEach((pair)=>{ // res.write(""Chunk""); const parts = pair.split('='); const appName = parts[0]; let fileName = parts[1]; content += `<imported-template-scope scope=""${appName}""><template><meta itemprop=""juicy-composition-scope"" content=""${appName}""/></template>`; if(fileName){ fileName = fileName.replace(/%2F/g, path.sep); if(fs.existsSync(path.resolve(servingDirectory, fileName))){ content += fs.readFileSync(servingDirectory + fileName, 'utf8'); } else { content += '<template>file does not exist, but you\'re just mocking, right?</template>'; } } content += `</imported-template-scope>`; }) res.setHeader('Content-Type', 'text/html'); setTimeout(()=>{ res.end(content) next(); }, 50); }).listen(9999, function() { console.log('Mocked SC Server running on 9999...'); }); ","const connect = require('connect'); const fs = require('fs'); const path = require('path'); const servingDirectory = 'sc/'; connect().use('/sc/htmlmerger', function fooMiddleware(req, res, next) { // req.url starts with ""/foo"" const query = req._parsedUrl.query; const pairs = query.split('&'); let content = ''; // console.log('Merging ' + query); pairs.forEach((pair)=>{ // res.write(""Chunk""); const parts = pair.split('='); const appName = parts[0]; let fileName = parts[1]; content += `<imported-template-scope scope=""${appName}""><template><meta itemprop=""juicy-composition-scope"" content=""${appName}""/></template>`; if(fileName){ fileName = fileName.replace('%2F','/'); if(fs.existsSync(servingDirectory + fileName)){ content += fs.readFileSync(servingDirectory + fileName, 'utf8'); } else { content += '<template>file does not exist, but you\'re just mocking, right?</template>'; } } content += `</imported-template-scope>`; }) res.setHeader('Content-Type', 'text/html'); setTimeout(()=>{ res.end(content) next(); }, 50); }).listen(9999, function() { console.log('Mocked SC Server running on 9999...'); }); " Add grunt-mdlint to CI tests,"module.exports = function (grunt) { require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); grunt.initConfig({ mdlint: { pass: ['README.md'], fail: ['test/fixtures/*.md'] }, simplemocha: { options: { globals: ['should'], timeout: 10000, ignoreLeaks: false, ui: 'bdd', reporter: 'spec' }, all: { src: ['test/integrationTests.js'] } }, jshint: { options: { bitwise: true, indent: 2, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, nonew: true, quotmark: 'single', sub: true, undef: true, unused: true, boss: true, trailing: true, eqnull: true, node: true, expr: true, evil: true, globals: { describe: true, it: true, before: true } }, files: { src: ['*.js', 'test/*.js', 'tasks/*.js'] } } }); grunt.registerTask('default', ['jshint', 'mdlint:pass', 'simplemocha']); grunt.loadTasks('tasks'); }; ","module.exports = function (grunt) { require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); grunt.initConfig({ mdlint: { pass: ['README.md'], fail: ['test/fixtures/*.md'] }, simplemocha: { options: { globals: ['should'], timeout: 10000, ignoreLeaks: false, ui: 'bdd', reporter: 'spec' }, all: { src: ['test/integrationTests.js'] } }, jshint: { options: { bitwise: true, indent: 2, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, nonew: true, quotmark: 'single', sub: true, undef: true, unused: true, boss: true, trailing: true, eqnull: true, node: true, expr: true, evil: true, globals: { describe: true, it: true, before: true } }, files: { src: ['*.js', 'test/*.js', 'tasks/*.js'] } } }); grunt.registerTask('default', ['jshint', 'simplemocha']); grunt.loadTasks('tasks'); }; " Update dynamic IFrame size support settings.,"<!-- <<< IFrame Resize Attributes --> <script src=""iframeResizer/iframeResizer.min.js""></script> <script type=""text/javascript""> iFrameResize({ log: false, // Enable console logging enablePublicMethods: true, // Enable methods within iframe hosted page heightCalculationMethod: 'grow', resizedCallback: function (messageData) { // Callback fn when resize is received $('p#callback').html( '<b>Frame ID:</b> ' + messageData.iframe.id + ' <b>Height:</b> ' + messageData.height + ' <b>Width:</b> ' + messageData.width + ' <b>Event type:</b> ' + messageData.type ); }, messageCallback: function (messageData) { // Callback fn when message is received $('p#callback').html( '<b>Frame ID:</b> ' + messageData.iframe.id + ' <b>Message:</b> ' + messageData.message ); alert(messageData.message); }, closedCallback: function (id) { // Callback fn when iFrame is closed $('p#callback').html( '<b>IFrame (</b>' + id + '<b>) removed from page.</b>' ); } }); </script> <!-- <<< IFrame Resize Attributes -->","<!-- <<< IFrame Resize Attributes --> <script src=""iframeResizer/iframeResizer.min.js""></script> <script type=""text/javascript""> iFrameResize({ log: false, // Enable console logging enablePublicMethods: true, // Enable methods within iframe hosted page heightCalculationMethod: 'max', resizedCallback: function (messageData) { // Callback fn when resize is received $('p#callback').html( '<b>Frame ID:</b> ' + messageData.iframe.id + ' <b>Height:</b> ' + messageData.height + ' <b>Width:</b> ' + messageData.width + ' <b>Event type:</b> ' + messageData.type ); }, messageCallback: function (messageData) { // Callback fn when message is received $('p#callback').html( '<b>Frame ID:</b> ' + messageData.iframe.id + ' <b>Message:</b> ' + messageData.message ); alert(messageData.message); }, closedCallback: function (id) { // Callback fn when iFrame is closed $('p#callback').html( '<b>IFrame (</b>' + id + '<b>) removed from page.</b>' ); } }); </script> <!-- <<< IFrame Resize Attributes -->" Add some stricter checks in singleLinePerSelector,"'use strict'; var helpers = require('../helpers'); module.exports = { name: 'singleLinePerSelector', nodeTypes: ['ruleset'], message: 'Each selector should be on its own line.', lint: function singleLinePerSelectorLinter (config, node) { var report = false; var results = []; var self = this; node.forEach('delimiter', function (element, index) { element = helpers.ensureObject(node.get(index + 1)); // Check if the delimiter is on the next line if (element.type !== 'space') { element = helpers.ensureObject(node.get(index - 1)); } switch (config.style) { case '18f': node.forEach('selector', function (selector) { selector = helpers.ensureObject(selector.first().first('ident')); selector = selector.content; if (selector && selector.length >= 5) { report = true; return; } }); break; default: report = true; break; } if (report && element.content.indexOf('\n') === -1) { results.push({ column: element.start.column, line: element.start.line, message: self.message }); } }); if (results.length) { return results; } } }; ","'use strict'; module.exports = { name: 'singleLinePerSelector', nodeTypes: ['ruleset'], message: 'Each selector should be on its own line.', lint: function singleLinePerSelectorLinter (config, node) { var report = false; var results = []; var self = this; node.forEach('delimiter', function (element, index) { element = node.get(index + 1); // Check if the delimiter is on the next line if (!element.is('space')) { element = node.get(index - 1); } switch (config.style) { case '18f': node.forEach('selector', function (selector) { selector = selector.first().first('ident').content; if (selector.length >= 5) { report = true; return; } }); break; default: report = true; break; } if (report && element.content.indexOf('\n') === -1) { results.push({ column: element.start.column, line: element.start.line, message: self.message }); } }); if (results.length) { return results; } } }; " Enable titleCollapse for section notes form,"/*jslint browser: true, undef: true, white: false, laxbreak: true *//*global Ext,Slate*/ Ext.define('SlateAdmin.view.progress.narratives.Manager',{ extend: 'Ext.Container', xtype: 'progress-narratives-manager', requires: [ 'SlateAdmin.view.progress.narratives.SectionsGrid', 'SlateAdmin.view.progress.narratives.StudentsGrid', 'SlateAdmin.view.progress.narratives.EditorForm', 'SlateAdmin.view.progress.narratives.SectionNotesForm' ], layout: 'border', componentCls: 'progress-narratives-manager', items: [{ region: 'west', weight: 100, split: true, xtype: 'progress-narratives-sectionsgrid' },{ region: 'center', xtype: 'progress-narratives-studentsgrid', disabled: true },{ region: 'east', split: true, weight: 100, flex: 1, xtype: 'progress-narratives-editorform', disabled: true },{ region: 'south', split: true, xtype: 'progress-narratives-sectionnotesform', collapsible :true, collapsed: true, titleCollapse: true, stateful: true, stateId: 'progress-narratives-sectionnotesform', disabled: true }] });","/*jslint browser: true, undef: true, white: false, laxbreak: true *//*global Ext,Slate*/ Ext.define('SlateAdmin.view.progress.narratives.Manager',{ extend: 'Ext.Container', xtype: 'progress-narratives-manager', requires: [ 'SlateAdmin.view.progress.narratives.SectionsGrid', 'SlateAdmin.view.progress.narratives.StudentsGrid', 'SlateAdmin.view.progress.narratives.EditorForm', 'SlateAdmin.view.progress.narratives.SectionNotesForm' ], layout: 'border', componentCls: 'progress-narratives-manager', items: [{ region: 'west', weight: 100, split: true, xtype: 'progress-narratives-sectionsgrid' },{ region: 'center', xtype: 'progress-narratives-studentsgrid', disabled: true },{ region: 'east', split: true, weight: 100, flex: 1, xtype: 'progress-narratives-editorform', disabled: true },{ region: 'south', split: true, xtype: 'progress-narratives-sectionnotesform', collapsible :true, collapsed: true, stateful: true, stateId: 'progress-narratives-sectionnotesform', disabled: true }] });" Set default selection to password,"package gui; import java.awt.GridLayout; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import controller.Controller; public class PasswordPane { public static String showUnlockWalletDialog() { JPanel userPanel = new JPanel(); userPanel.setLayout(new GridLayout(2,2)); //Labels for the textfield components JLabel passwordLbl = new JLabel(""Enter wallet password:""); JPasswordField passwordFld = new JPasswordField(); //Add the components to the JPanel userPanel.add(passwordLbl); userPanel.add(passwordFld); Object[] options = {""Unlock"", ""Unlock for 2 minutes"", ""Cancel""}; //As the JOptionPane accepts an object as the message //it allows us to use any component we like - in this case //a JPanel containing the dialog components we want int n = JOptionPane.showOptionDialog( null, userPanel, ""Unlock Wallet"", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, passwordFld ); if(n == JOptionPane.YES_OPTION) { Controller.getInstance().setSecondsToUnlock(-1); } else if (n == JOptionPane.NO_OPTION) { Controller.getInstance().setSecondsToUnlock(120); } else { return """"; } return new String(passwordFld.getPassword()); } } ","package gui; import java.awt.GridLayout; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import controller.Controller; public class PasswordPane { public static String showUnlockWalletDialog() { JPanel userPanel = new JPanel(); userPanel.setLayout(new GridLayout(2,2)); //Labels for the textfield components JLabel passwordLbl = new JLabel(""Enter wallet password:""); JPasswordField passwordFld = new JPasswordField(); //Add the components to the JPanel userPanel.add(passwordLbl); userPanel.add(passwordFld); Object[] options = {""Unlock"", ""Unlock for 2 minutes"", ""Cancel""}; //As the JOptionPane accepts an object as the message //it allows us to use any component we like - in this case //a JPanel containing the dialog components we want int n = JOptionPane.showOptionDialog( null, userPanel, ""Unlock Wallet"", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2] ); if(n == JOptionPane.YES_OPTION) { Controller.getInstance().setSecondsToUnlock(-1); } else if (n == JOptionPane.NO_OPTION) { Controller.getInstance().setSecondsToUnlock(120); } else { return """"; } return new String(passwordFld.getPassword()); } } " "Make a box a box * fix default name from ""folder"" to ""box""","/* * Wegas * http://wegas.albasim.ch * * Copyright (c) 2013-2018 School of Business and Engineering Vaud, Comem, MEI * Licensed under the MIT License */ /** * @fileOverview * @author Cyril Junod <cyril.junod at gmail.com> */ YUI.add('wegas-box', function(Y) { 'use strict'; /** * @name Y.Wegas.Box * @extends Y.Widget * @borrows Y.WidgetChild, Y.Wegas.Widget, Y.Wegas.Editable * @class Displays a box widget * @constructor * @description Display a simple box */ var Box = Y.Base.create( 'wegas-box', Y.Widget, [Y.WidgetChild, Y.Wegas.Widget, Y.Wegas.Editable], { /** @lends Y.Wegas.Box# */ CONTENT_TEMPLATE: null, getEditorLabel: function() { return Y.Wegas.Helper.stripHtml(this.get('name')); } }, { /** @lends Y.Wegas.Box */ EDITORNAME: 'Box', ATTRS: { name: { value: 'box', type: 'string', view: { label: 'Name' } } } } ); Y.Wegas.Box = Box; }); ","/* * Wegas * http://wegas.albasim.ch * * Copyright (c) 2013-2018 School of Business and Engineering Vaud, Comem, MEI * Licensed under the MIT License */ /** * @fileOverview * @author Cyril Junod <cyril.junod at gmail.com> */ YUI.add('wegas-box', function(Y) { 'use strict'; /** * @name Y.Wegas.Box * @extends Y.Widget * @borrows Y.WidgetChild, Y.Wegas.Widget, Y.Wegas.Editable * @class Displays a box widget * @constructor * @description Display a simple box */ var Box = Y.Base.create( 'wegas-box', Y.Widget, [Y.WidgetChild, Y.Wegas.Widget, Y.Wegas.Editable], { /** @lends Y.Wegas.Box# */ CONTENT_TEMPLATE: null, getEditorLabel: function() { return Y.Wegas.Helper.stripHtml(this.get('name')); } }, { /** @lends Y.Wegas.Box */ EDITORNAME: 'Box', ATTRS: { name: { value: 'folder', type: 'string', view: { label: 'Name' } } } } ); Y.Wegas.Box = Box; }); " Remove deprecated usage of tree builder where possible,"<?php /* * This file is part of JoliTypo - a project by JoliCode. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. */ namespace JoliTypo\Bridge\Symfony\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder('joli_typo'); $rootNode = $this->getRootNode($treeBuilder, 'joli_typo'); $rootNode ->fixXmlConfig('preset') ->children() ->arrayNode('presets') ->useAttributeAsKey('name') ->isRequired() ->prototype('array') ->children() ->scalarNode('locale')->end() ->arrayNode('fixers') ->prototype('scalar') ->end() ->end() ->end() ->end() ->end() ; return $treeBuilder; } private function getRootNode(TreeBuilder $treeBuilder, $name) { // BC layer for symfony/config 4.1 and older if (! \method_exists($treeBuilder, 'getRootNode')) { return $treeBuilder->root($name); } return $treeBuilder->getRootNode(); } } ","<?php /* * This file is part of JoliTypo - a project by JoliCode. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. */ namespace JoliTypo\Bridge\Symfony\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('joli_typo'); $rootNode ->fixXmlConfig('preset') ->children() ->arrayNode('presets') ->useAttributeAsKey('name') ->isRequired() ->prototype('array') ->children() ->scalarNode('locale')->end() ->arrayNode('fixers') ->prototype('scalar') ->end() ->end() ->end() ->end() ->end() ; return $treeBuilder; } } " Set servicejid setting on register,"# -*- coding: utf-8 -*- #from twisted.words.xish import domish from base import * import random import time import bnw_core.bnw_objects as objs def _(s,user): return s from uuid import uuid4 import re @check_arg(name=USER_RE) @defer.inlineCallbacks def cmd_register(request,name=""""): """""" Регистрация """""" if request.user: defer.returnValue( dict(ok=False, desc=u'You are already registered as %s' % (request.user['name'],), ) ) else: name=name.lower()[:128] if name=='anonymous': defer.returnValue( dict(ok=False,desc=u'You aren''t anonymous.') ) user=objs.User({ 'id': uuid4().hex, 'name': name, 'login_key': uuid4().hex, 'regdate': int(time.time()), 'jid': request.bare_jid, 'interface': 'redeye', 'settings.servicejid': request.to.split('/',1)[0], }) if not (yield objs.User.find_one({'name':name})): _ = yield user.save() defer.returnValue( dict(ok=True,desc='We registered you as %s.' % (name,)) ) else: defer.returnValue( dict(ok=True,desc='This username is already taken') ) ","# -*- coding: utf-8 -*- #from twisted.words.xish import domish from base import * import random import time import bnw_core.bnw_objects as objs def _(s,user): return s from uuid import uuid4 import re @check_arg(name=USER_RE) @defer.inlineCallbacks def cmd_register(request,name=""""): """""" Регистрация """""" if request.user: defer.returnValue( dict(ok=False, desc=u'You are already registered as %s' % (request.user['name'],), ) ) else: name=name.lower()[:128] if name=='anonymous': defer.returnValue( dict(ok=False,desc=u'You aren''t anonymous.') ) user=objs.User({ 'id': uuid4().hex, 'name': name, 'login_key': uuid4().hex, 'regdate': int(time.time()), 'jid': request.bare_jid, 'interface': 'redeye', }) if not (yield objs.User.find_one({'name':name})): _ = yield user.save() defer.returnValue( dict(ok=True,desc='We registered you as %s.' % (name,)) ) else: defer.returnValue( dict(ok=True,desc='This username is already taken') ) " Enforce requirement for build and reset arguments,"<?php namespace Dock\Cli; use Dock\Docker\Compose\Project; use Dock\Project\ProjectManager; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class ResetCommand extends Command { /** * @var ProjectManager */ private $projectManager; /** * @var Project */ private $project; /** * @param ProjectManager $projectManager * @param Project $project */ public function __construct(ProjectManager $projectManager, Project $project) { parent::__construct(); $this->projectManager = $projectManager; $this->project = $project; } /** * {@inheritdoc} */ protected function configure() { $this ->setName('reset') ->setDescription('Reset the containers of the project') ->addArgument('container', InputArgument::IS_ARRAY | InputArgument::REQUIRED, 'Component names') ; } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $containers = $input->getArgument('container'); $this->projectManager->reset($this->project, $containers); $output->writeln([ 'Container(s) successfully reset.', ]); } } ","<?php namespace Dock\Cli; use Dock\Docker\Compose\Project; use Dock\Project\ProjectManager; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class ResetCommand extends Command { /** * @var ProjectManager */ private $projectManager; /** * @var Project */ private $project; /** * @param ProjectManager $projectManager * @param Project $project */ public function __construct(ProjectManager $projectManager, Project $project) { parent::__construct(); $this->projectManager = $projectManager; $this->project = $project; } /** * {@inheritdoc} */ protected function configure() { $this ->setName('reset') ->setDescription('Reset the containers of the project') ->addArgument('container', InputArgument::IS_ARRAY, 'Component names') ; } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $containers = $input->getArgument('container'); $this->projectManager->reset($this->project, $containers); $output->writeln([ 'Container(s) successfully reset.', ]); } } " Select only unsubscribed contacts from mailjet on sync script,"from django.core.management.base import BaseCommand from django.db import DEFAULT_DB_ALIAS from optparse import make_option class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--connection', action='store', dest='connection', default=DEFAULT_DB_ALIAS, ), ) def handle(self, *args, **options): from courriers.backends import get_backend from courriers.models import NewsletterSubscriber self.connection = options.get('connection') backend_klass = get_backend() backend = backend_klass() unsubscribed_users = (NewsletterSubscriber.objects.using(self.connection) .filter(is_unsubscribed=True) .values_list('email', flat=True) .order_by('-unsubscribed_at')) mailjet_contacts = backend.mailjet_api.contact.list(unsub=1) mailjet_users = [contact['email'] for contact in mailjet_contacts['result']] diff = list(set(mailjet_users) - set(unsubscribed_users)) print ""%d contacts to unsubscribe"" % len(diff) for email in diff: backend.unregister(email) print ""Unsubscribe user: %s"" % email ","from django.core.management.base import BaseCommand from django.db import DEFAULT_DB_ALIAS from optparse import make_option class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--connection', action='store', dest='connection', default=DEFAULT_DB_ALIAS, ), ) def handle(self, *args, **options): from courriers.backends import get_backend from courriers.models import NewsletterSubscriber self.connection = options.get('connection') backend_klass = get_backend() backend = backend_klass() unsubscribed_users = (NewsletterSubscriber.objects.using(self.connection) .filter(is_unsubscribed=True) .values_list('email', flat=True) .order_by('-unsubscribed_at')) mailjet_contacts = backend.mailjet_api.contact.list() mailjet_users = [contact['email'] for contact in mailjet_contacts['result']] diff = list(set(unsubscribed_users) - set(mailjet_users)) print ""%d contacts to unsubscribe"" % len(diff) for email in diff: backend.unregister(email) print ""Unsubscribe user: %s"" % email " Make emit able to return an array of values," function Events() { var listeners = {} $.extend(this, { on: function(type, cb) { if (!$.isArray(listeners[type])) listeners[type] = [] if (listeners[type].indexOf(cb) < 0) listeners[type].push(cb) }, once: function(type, cb) { this.on(type, function observer() { this.off(type, observer) cb.apply(this, arguments) }) }, emit: function(type) { var result = [] if (!$.isArray(listeners[type])) listeners[type] = [] var args = Array.prototype.slice.call(arguments, 1) var cbs = listeners[type].slice() while (cbs.length > 0) { result.push(cbs.shift().apply(this, args)) } return result }, off: function(type, cb) { if (cb == undefined) throw new Error(""You cannot remove all listeners on an event"") if (!$.isFunction(cb)) throw new Error(""You must pass a listener to Event.off"") var index = listeners[type].indexOf(cb) if (index != undefined && index >= 0) { listeners[type].splice(index, 1); } }, }) } "," function Events() { var listeners = {} $.extend(this, { on: function(type, cb) { if (!$.isArray(listeners[type])) listeners[type] = [] if (listeners[type].indexOf(cb) < 0) listeners[type].push(cb) }, once: function(type, cb) { this.on(type, function observer() { this.off(type, observer) cb.apply(this, arguments) }) }, emit: function(type) { if (!$.isArray(listeners[type])) listeners[type] = [] var args = Array.prototype.slice.call(arguments, 1) var cbs = listeners[type].slice() while (cbs.length > 0) { cbs.shift().apply(this, args) } }, off: function(type, cb) { if (cb == undefined) throw new Error(""You cannot remove all listeners on an event"") if (!$.isFunction(cb)) throw new Error(""You must pass a listener to Event.off"") var index = listeners[type].indexOf(cb) if (index != undefined && index >= 0) { listeners[type].splice(index, 1); } }, }) } " Change name for release archives,"var eventStream = require('event-stream'), gulp = require('gulp'), chmod = require('gulp-chmod'), zip = require('gulp-zip'), tar = require('gulp-tar'), gzip = require('gulp-gzip'), rename = require('gulp-rename'); gulp.task('prepare-release', function() { var version = require('./package.json').version; return eventStream.merge( getSources() .pipe(zip('operator-status-plugin-' + version + '.zip')), getSources() .pipe(tar('operator-status-plugin-' + version + '.tar')) .pipe(gzip()) ) .pipe(chmod(0644)) .pipe(gulp.dest('release')); }); // Builds and packs plugins sources gulp.task('default', ['prepare-release'], function() { // The ""default"" task is just an alias for ""prepare-release"" task. }); /** * Returns files stream with the plugin sources. * * @returns {Object} Stream with VinylFS files. */ var getSources = function() { return gulp.src([ 'Controller/*', 'LICENSE', 'Plugin.php', 'README.md', 'routing.yml' ], {base: './'} ) .pipe(rename(function(path) { path.dirname = 'Mibew/Mibew/Plugin/OperatorStatus/' + path.dirname; })); }","var eventStream = require('event-stream'), gulp = require('gulp'), chmod = require('gulp-chmod'), zip = require('gulp-zip'), tar = require('gulp-tar'), gzip = require('gulp-gzip'), rename = require('gulp-rename'); gulp.task('prepare-release', function() { var version = require('./package.json').version; return eventStream.merge( getSources() .pipe(zip('mibew-operator-status-plugin-' + version + '.zip')), getSources() .pipe(tar('mibew-operator-status-plugin-' + version + '.tar')) .pipe(gzip()) ) .pipe(chmod(0644)) .pipe(gulp.dest('release')); }); // Builds and packs plugins sources gulp.task('default', ['prepare-release'], function() { // The ""default"" task is just an alias for ""prepare-release"" task. }); /** * Returns files stream with the plugin sources. * * @returns {Object} Stream with VinylFS files. */ var getSources = function() { return gulp.src([ 'Controller/*', 'LICENSE', 'Plugin.php', 'README.md', 'routing.yml' ], {base: './'} ) .pipe(rename(function(path) { path.dirname = 'Mibew/Mibew/Plugin/OperatorStatus/' + path.dirname; })); }" Create new container when not pulled from container,"<?php namespace League\Route\Strategy; use RuntimeException; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class RequestResponseStrategy extends AbstractStrategy implements StrategyInterface { /** * {@inheritdoc} */ public function dispatch($controller, array $vars) { $response = $this->invokeController($controller, [ $this->getRequest(), $this->getContainer()->get('Symfony\Component\HttpFoundation\Response'), $vars ]); if ($response instanceof Response) { return $response; } throw new RuntimeException( 'When using the Request -> Response Strategy your controller must ' . 'return an instance of [Symfony\Component\HttpFoundation\Response]' ); } /** * Get Request either from the container or else create it from globals * @return \Symfony\Component\HttpFoundation\Request */ protected function getRequest() { if ( $this->getContainer()->isRegistered('Symfony\Component\HttpFoundation\Request') || $this->getContainer()->isInServiceProvider('Symfony\Component\HttpFoundation\Request') ) { return $this->getContainer()->get('Symfony\Component\HttpFoundation\Request'); } return Request::createFromGlobals(); } } ","<?php namespace League\Route\Strategy; use RuntimeException; use Symfony\Component\HttpFoundation\Response; class RequestResponseStrategy extends AbstractStrategy implements StrategyInterface { /** * {@inheritdoc} */ public function dispatch($controller, array $vars) { $response = $this->invokeController($controller, [ $this->getRequest(), $this->getContainer()->get('Symfony\Component\HttpFoundation\Response'), $vars ]); if ($response instanceof Response) { return $response; } throw new RuntimeException( 'When using the Request -> Response Strategy your controller must ' . 'return an instance of [Symfony\Component\HttpFoundation\Response]' ); } /** * Get Request either from the container or else create it from globals * @return \Symfony\Component\HttpFoundation\Request */ protected function getRequest() { if ($this->getContainer()->isRegistered('Symfony\Component\HttpFoundation\Request') || $this->getContainer()->isInServiceProvider('Symfony\Component\HttpFoundation\Request') ) { return $this->getContainer()->get('Symfony\Component\HttpFoundation\Request'); } else { return $this->getContainer()->get('Symfony\Component\HttpFoundation\Request')->createFromGlobals(); } } } " antler: Use custom theme by default.,"from caribou.settings.setting_types import * from caribou.i18n import _ AntlerSettings = SettingsTopGroup( _(""Antler Preferences""), ""/org/gnome/antler/"", ""org.gnome.antler"", [SettingsGroup(""antler"", _(""Antler""), [ SettingsGroup(""appearance"", _(""Appearance""), [ StringSetting( ""keyboard_type"", _(""Keyboard Type""), ""touch"", _(""The keyboard geometry Caribou should use""), _(""The keyboard geometry determines the shape "" ""and complexity of the keyboard, it could range from "" ""a 'natural' look and feel good for composing simple "" ""text, to a fullscale keyboard.""), # Translators: Keyboard type (similar to touch/tactile device) allowed=[(('touch'), _('Touch')), # Translators: Keyboard type (conventional keyboard) (('fullscale'), _('Full scale')), # Translators: Keyboard type (scanned grid by rows/columns) (('scan'), _('Scan'))]), BooleanSetting(""use_system"", _(""Use System Theme""), False, _(""Use System Theme"")), FloatSetting(""min_alpha"", _(""Minimum Alpha""), 0.2, _(""Minimal opacity of keyboard""), min=0.0, max=1.0), FloatSetting(""max_alpha"", _(""Maximum Alpha""), 1.0, _(""Maximal opacity of keyboard""), min=0.0, max=1.0), IntegerSetting(""max_distance"", _(""Maximum Distance""), 100, _(""Maximum distance when keyboard is hidden""), min=0, max=1024) ]) ]) ]) ","from caribou.settings.setting_types import * from caribou.i18n import _ AntlerSettings = SettingsTopGroup( _(""Antler Preferences""), ""/org/gnome/antler/"", ""org.gnome.antler"", [SettingsGroup(""antler"", _(""Antler""), [ SettingsGroup(""appearance"", _(""Appearance""), [ StringSetting( ""keyboard_type"", _(""Keyboard Type""), ""touch"", _(""The keyboard geometry Caribou should use""), _(""The keyboard geometry determines the shape "" ""and complexity of the keyboard, it could range from "" ""a 'natural' look and feel good for composing simple "" ""text, to a fullscale keyboard.""), # Translators: Keyboard type (similar to touch/tactile device) allowed=[(('touch'), _('Touch')), # Translators: Keyboard type (conventional keyboard) (('fullscale'), _('Full scale')), # Translators: Keyboard type (scanned grid by rows/columns) (('scan'), _('Scan'))]), BooleanSetting(""use_system"", _(""Use System Theme""), True, _(""Use System Theme"")), FloatSetting(""min_alpha"", _(""Minimum Alpha""), 0.2, _(""Minimal opacity of keyboard""), min=0.0, max=1.0), FloatSetting(""max_alpha"", _(""Maximum Alpha""), 1.0, _(""Maximal opacity of keyboard""), min=0.0, max=1.0), IntegerSetting(""max_distance"", _(""Maximum Distance""), 100, _(""Maximum distance when keyboard is hidden""), min=0, max=1024) ]) ]) ]) " Update preprocessor for 4.x: New imports and make it more robust,"# -*- coding: utf-8 -*- """"""This preprocessor replaces Python code in markdowncell with the result stored in cell metadata """""" from nbconvert.preprocessors import * import re def get_variable( match, variables): try: x = variables[match] return x except KeyError: return """" class PyMarkdownPreprocessor(Preprocessor): def replace_variables(self,source,variables): """""" Replace {{variablename}} with stored value """""" try: replaced = re.sub(""{{(.*?)}}"", lambda m: get_variable(m.group(1),variables) , source) except TypeError: replaced = source return replaced def preprocess_cell(self, cell, resources, index): """""" Preprocess cell Parameters ---------- cell : NotebookNode cell Notebook cell being processed resources : dictionary Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine. cell_index : int Index of the cell being processed (see base.py) """""" if cell.cell_type == ""markdown"": if hasattr(cell['metadata'], 'variables'): variables = cell['metadata']['variables'] if len(variables) > 0: cell.source = self.replace_variables(cell.source, variables) return cell, resources ","""""""This preprocessor replaces Python code in markdowncell with the result stored in cell metadata """""" #----------------------------------------------------------------------------- # Copyright (c) 2014, Juergen Hasch # # Distributed under the terms of the Modified BSD License. # #----------------------------------------------------------------------------- from IPython.nbconvert.preprocessors import * import re class PyMarkdownPreprocessor(Preprocessor): def replace_variables(self,source,variables): """""" Replace {{variablename}} with stored value """""" try: replaced = re.sub(""{{(.*?)}}"", lambda m: variables[m.group(1)] , source) except TypeError: replaced = source return replaced def preprocess_cell(self, cell, resources, index): """""" Preprocess cell Parameters ---------- cell : NotebookNode cell Notebook cell being processed resources : dictionary Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine. cell_index : int Index of the cell being processed (see base.py) """""" if cell.cell_type == ""markdown"": if hasattr(cell['metadata'], 'variables'): variables = cell['metadata']['variables'] if len(variables) > 0: cell.source = self.replace_variables(cell.source, variables) return cell, resources " Remove check for versions < 1.7,"import os import django from django.conf import settings if not settings.configured: settings_dict = dict( INSTALLED_APPS=[ 'django.contrib.contenttypes', 'django.contrib.auth', 'bootstrap3', 'form_utils', ], DATABASES={ ""default"": { ""ENGINE"": ""django.db.backends.sqlite3"", } }, MEDIA_ROOT=os.path.join(os.path.dirname(__file__), 'media'), MEDIA_URL='/media/', STATIC_URL='/static/', MIDDLEWARE_CLASSES=[], BOOTSTRAP3={ 'form_renderers': { 'default': 'form_utils_bootstrap3.renderers.BetterFormRenderer' } } ) if django.VERSION >= (1, 8): settings_dict['TEMPLATES'] = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [] } ] settings.configure(**settings_dict) django.setup() ","import os import django from django.conf import settings if not settings.configured: settings_dict = dict( INSTALLED_APPS=[ 'django.contrib.contenttypes', 'django.contrib.auth', 'bootstrap3', 'form_utils', ], DATABASES={ ""default"": { ""ENGINE"": ""django.db.backends.sqlite3"", } }, MEDIA_ROOT=os.path.join(os.path.dirname(__file__), 'media'), MEDIA_URL='/media/', STATIC_URL='/static/', MIDDLEWARE_CLASSES=[], BOOTSTRAP3={ 'form_renderers': { 'default': 'form_utils_bootstrap3.renderers.BetterFormRenderer' } } ) if django.VERSION >= (1, 8): settings_dict['TEMPLATES'] = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [] } ] settings.configure(**settings_dict) if django.VERSION >= (1, 7): django.setup() " Change the default value for the chronicle option,"""""""Usage: chronicler [-c CHRONICLE] The Chronicler remembers… Options: -c, --chronicle CHRONICLE chronicle file to use [default: chronicle.hjson] """""" import docopt import hjson import jsonschema import chronicle def main(): options = docopt.docopt(__doc__) try: c = open(options['--chronicle']) except FileNotFoundError: print(""No chronicle to read."") exit(1) try: c = hjson.load(c) except hjson.HjsonDecodeError as e: print(""This chronicle can't be deciphered."") print(""L%d, C%d: %s"" % (e.lineno, e.colno, e.msg)) exit(1) try: jsonschema.validate(c, chronicle.schema) except jsonschema.ValidationError as e: print(""This chronicle can't be deciphered."") print(""%s: %s"" % (list(e.path), e.message)) exit(1) print(""Behold my story:"") played = 0 won = 0 for h in c: for a in h['against']: played += 1 if a['result']['victory'] == True: won += 1 print(""victories: %d/%d"" % (won, played)) if __name__ == '__main__': main() ","""""""Usage: chronicler [-c CHRONICLE] The Chronicler remembers… Options: -c, --chronicle CHRONICLE chronicle file to use [default: chronicle.txt] """""" import docopt import hjson import jsonschema import chronicle def main(): options = docopt.docopt(__doc__) try: c = open(options['--chronicle']) except FileNotFoundError: print(""No chronicle to read."") exit(1) try: c = hjson.load(c) except hjson.HjsonDecodeError as e: print(""This chronicle can't be deciphered."") print(""L%d, C%d: %s"" % (e.lineno, e.colno, e.msg)) exit(1) try: jsonschema.validate(c, chronicle.schema) except jsonschema.ValidationError as e: print(""This chronicle can't be deciphered."") print(""%s: %s"" % (list(e.path), e.message)) exit(1) print(""Behold my story:"") played = 0 won = 0 for h in c: for a in h['against']: played += 1 if a['result']['victory'] == True: won += 1 print(""victories: %d/%d"" % (won, played)) if __name__ == '__main__': main() " "Enable i18next Debugging For Tests Enable i18next's debugging output in the test environment to make diagnosing problems easier.","/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, defaultLocale: 'en', i18nextOptions: { ns: { namespaces: [ 'main' ], defaultNs: 'main' }, cookieName: 'locale', preload: [ 'en' ], lng: 'en', fallbackLng: 'en', getAsync: true, resGetPath: '/locales/__ns__/__lng__.json', debug: true }, APP: { } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; }; ","/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, defaultLocale: 'en', i18nextOptions: { ns: { namespaces: [ 'main' ], defaultNs: 'main' }, cookieName: 'locale', preload: [ 'en' ], lng: 'en', fallbackLng: 'en', getAsync: true, resGetPath: '/locales/__ns__/__lng__.json' }, APP: { } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; }; " Replace class with new name.,"<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\FrameworkBundle\Test; use Symfony\Bundle\FrameworkBundle\KernelBrowser; use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; /** * WebTestCase is the base class for functional tests. * * @author Fabien Potencier <fabien@symfony.com> */ abstract class WebTestCase extends KernelTestCase { /** * Creates a KernelBrowser. * * @param array $options An array of options to pass to the createKernel method * @param array $server An array of server parameters * * @return KernelBrowser A KernelBrowser instance */ protected static function createClient(array $options = [], array $server = []) { $kernel = static::bootKernel($options); try { $client = $kernel->getContainer()->get('test.client'); } catch (ServiceNotFoundException $e) { if (class_exists(KernelBrowser::class)) { throw new \LogicException('You cannot create the client used in functional tests if the ""framework.test"" config is not set to true.'); } throw new \LogicException('You cannot create the client used in functional tests if the BrowserKit component is not available. Try running ""composer require symfony/browser-kit""'); } $client->setServerParameters($server); return $client; } } ","<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\FrameworkBundle\Test; use Symfony\Bundle\FrameworkBundle\KernelBrowser; use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; /** * WebTestCase is the base class for functional tests. * * @author Fabien Potencier <fabien@symfony.com> */ abstract class WebTestCase extends KernelTestCase { /** * Creates a KernelBrowser. * * @param array $options An array of options to pass to the createKernel method * @param array $server An array of server parameters * * @return KernelBrowser A KernelBrowser instance */ protected static function createClient(array $options = [], array $server = []) { $kernel = static::bootKernel($options); try { $client = $kernel->getContainer()->get('test.client'); } catch (ServiceNotFoundException $e) { if (class_exists(Client::class)) { throw new \LogicException('You cannot create the client used in functional tests if the ""framework.test"" config is not set to true.'); } throw new \LogicException('You cannot create the client used in functional tests if the BrowserKit component is not available. Try running ""composer require symfony/browser-kit""'); } $client->setServerParameters($server); return $client; } } " Copy individual directories to prevent overwriting existing,"<?php namespace Phine\Console; use Symfony\Component\Console\Input\InputArgument; use Illuminate\Filesystem\Filesystem; class InitCommand extends Command { private $files; public function __construct($app) { $this->files = $app['files']; $this->base = getcwd(); parent::__construct(); } protected function configure() { $this->setName('init') ->setDescription('Initialize a new Phine project.') ->addArgument( 'name', InputArgument::OPTIONAL, 'Where should we initialize this project?' ); } protected function fire() { if ($base = $this->input->getArgument('name')) { $this->base .= '/' . $base; } // Copy the Phine project into the new site directory $copyFrom = __DIR__ . '/../../'; $this->files->copyDirectory($copyFrom . '/framework/', $this->base . '/framework/'); $this->files->copyDirectory($copyFrom . '/public/', $this->base . '/public/'); $this->files->copyDirectory($copyFrom . '/resources/', $this->base . '/resources/'); $this->files->copyDirectory($copyFrom . '/site/', $this->base . '/site/'); $this->files->copy ($copyFrom . '/.gitignore', $this->base . '/.gitignore'); $this->files->copy ($copyFrom . '/gulpfile.js', $this->base . '/gulpfile.js'); $this->files->copy ($copyFrom . '/package.json',$this->base . '/package.json'); $this->files->copy ($copyFrom . '/phine', $this->base . '/phine'); // Copy doesn't preserve phine executableness, put it back $this->files->chmod($this->base . '/phine', 0755); $this->info(""Phine initialized successfully!""); } }","<?php namespace Phine\Console; use Symfony\Component\Console\Input\InputArgument; use Illuminate\Filesystem\Filesystem; class InitCommand extends Command { private $files; public function __construct($app) { $this->files = $app['files']; $this->base = getcwd(); parent::__construct(); } protected function configure() { $this->setName('init') ->setDescription('Initialize a new Phine project.') ->addArgument( 'name', InputArgument::OPTIONAL, 'Where should we initialize this project?' ); } protected function fire() { if ($base = $this->input->getArgument('name')) { $this->base .= '/' . $base; } // Copy the Phine project into the new site directory $this->files->copyDirectory(__DIR__ . '/../../', $this->base); // If cloned from master, .git comes along, let's not. $this->files->deleteDirectory($this->base . '/.git', 0755); // Copy doesn't preserve phine executableness, put it back $this->files->chmod($this->base . '/phine', 0755); $this->info(""Phine {$this->base} initialized successfully!""); } }" Enable Featured Image Functionality on Home Page,"<?php /** * Home Page Template * Template Name: Home Page * */ get_header(); ?> <div class=""hero-header"" data-parallax=""scroll"" data-image-src=""<?php echo wp_get_attachment_url( get_post_thumbnail_id($post->ID)); ?>""> <div class=""hero-description row""> <div class=""hero-description-text""> <h2>Spreading the Gospel</h2> <h3>One Internet Connection At A Time</h3> </div> </div> </div> <div class=""hp-quick-links""> <?php // Display Quick Links if( have_rows('quick_links') ): echo '<div class=""row medium-up-3 large-up-4"" data-equalizer data-equalize-on=""medium"">'; // loop through the rows of data while ( have_rows('quick_links') ) : the_row(); echo '<div class=""column quick-link-container"" data-equalizer-watch>'; // display a sub field value echo '<h4>' . get_sub_field('quick_link_title') . '</h4>'; the_sub_field('quick_link_description'); echo '<a href=""' . get_sub_field('quick_link_page_link') . '"" class=""button expanded hollow"">View Page</a>'; echo '</div>'; endwhile; echo '</div>'; else : endif; ?> </div> <?php get_footer(); ?>","<?php /** * Home Page Template * Template Name: Home Page * */ get_header(); ?> <div class=""hero-header"" data-parallax=""scroll"" data-image-src=""http://localhost:8888/technet.ywammontana.org/wp-content/uploads/2016/05/photo-1448960968772-b63b3f40dfc1.jpeg""> <div class=""hero-description row""> <div class=""hero-description-text""> <h2>Spreading the Gospel</h2> <h3>One Internet Connection At A Time</h3> </div> </div> </div> <div class=""hp-quick-links""> <?php // Display Quick Links if( have_rows('quick_links') ): echo '<div class=""row medium-up-3 large-up-4"" data-equalizer data-equalize-on=""medium"">'; // loop through the rows of data while ( have_rows('quick_links') ) : the_row(); echo '<div class=""column quick-link-container"" data-equalizer-watch>'; // display a sub field value echo '<h4>' . get_sub_field('quick_link_title') . '</h4>'; the_sub_field('quick_link_description'); echo '<a href=""' . get_sub_field('quick_link_page_link') . '"" class=""button expanded hollow"">View Page</a>'; echo '</div>'; endwhile; echo '</div>'; else : endif; ?> </div> <?php get_footer(); ?>" Hide the label if asked to,"<?php namespace fieldwork\components; class TextField extends Field { const ON_ENTER_NEXT = 'next'; const ON_ENTER_SUBMIT = 'submit'; private $onEnter = '', $mask = null; public function getAttributes () { $att = array(); if (!empty($this->onEnter)) $att['data-input-action-on-enter'] = $this->onEnter; if ($this->mask !== null) $att['data-input-mask'] = $this->mask; return array_merge(parent::getAttributes(), $att); } public function onEnter ($action = '') { $this->onEnter = $action; return $this; } /** * Sets input mask for this field * * @param string $mask * * @return static */ public function setMask ($mask) { $this->mask = $mask; return $this; } public function getClasses () { return array_merge( parent::getClasses(), array('textfield', 'fieldwork-inputfield') ); } public function getHTML ($showLabel = true) { if ($showLabel) return sprintf(""<div class=\""input-field\""><input type='text' %s><label for=\""%s\"">%s</label></div>"", $this->getAttributesString(), $this->getId(), $this->label); else return sprintf(""<div class=\""input-field\""><input type='text' %s></div>"", $this->getAttributesString(), $this->getId()); } }","<?php namespace fieldwork\components; class TextField extends Field { const ON_ENTER_NEXT = 'next'; const ON_ENTER_SUBMIT = 'submit'; private $onEnter = '', $mask = null; public function getAttributes () { $att = array(); if (!empty($this->onEnter)) $att['data-input-action-on-enter'] = $this->onEnter; if ($this->mask !== null) $att['data-input-mask'] = $this->mask; return array_merge(parent::getAttributes(), $att); } public function onEnter ($action = '') { $this->onEnter = $action; return $this; } /** * Sets input mask for this field * * @param string $mask * * @return static */ public function setMask ($mask) { $this->mask = $mask; return $this; } public function getClasses () { return array_merge( parent::getClasses(), array('textfield', 'fieldwork-inputfield') ); } public function getHTML ($showLabel = true) { return sprintf(""<div class=\""input-field\""><input type='text' %s><label for=\""%s\"">%s</label></div>"", $this->getAttributesString(), $this->getId(), $this->label); } }" Add conditional blocks for avatars and post sidebar,"<article id=""post-<?php the_ID(); ?>"" <?php post_class(); ?>> <div class=""row""> <?php if (!is_author() && !is_single()): ?> <div class=""col-md-2 avatar-wrapper""> <?php keitaro_author_avatar(get_the_author_meta('ID')); ?> </div> <?php endif; ?> <div class=""col-md-8""> <?php get_template_part(SNIPPETS_DIR . '/header/entry-header'); if (is_archive() || is_home() || is_search()) : get_template_part(SNIPPETS_DIR . '/entry-excerpt'); else : get_template_part(SNIPPETS_DIR . '/entry-content'); endif; comments_template(); ?> </div> <?php if (is_single()): ?> <div class=""col-md-4""> <?php if (!is_search()): keitaro_child_pages_list(get_the_ID()); foreach (get_children(get_ancestors(get_the_ID())) as $page) : get_template_part(SNIPPETS_DIR . '/sidebars/icon-blocks'); endforeach; endif; get_template_part(SNIPPETS_DIR . '/entry-footer'); ?> </div> <?php endif; ?> </div> </article>","<article id=""post-<?php the_ID(); ?>"" <?php post_class(); ?>> <div class=""row""> <div class=""col-md-8""> <?php get_template_part(SNIPPETS_DIR . '/header/entry-header'); if (is_archive() || is_home() || is_search()) : get_template_part(SNIPPETS_DIR . '/entry-excerpt'); else : if ('' !== get_the_post_thumbnail()) : get_template_part(SNIPPETS_DIR . '/post-thumbnail'); endif; get_template_part(SNIPPETS_DIR . '/entry-content'); endif; comments_template(); ?> </div> <div class=""col-md-4""> <?php if (!is_search()): keitaro_child_pages_list(get_the_ID()); foreach (get_children(get_ancestors(get_the_ID())) as $page) : get_template_part(SNIPPETS_DIR . '/sidebars/icon-blocks'); endforeach; endif; get_template_part(SNIPPETS_DIR . '/entry-footer'); ?> </div> </div> </article> " Correct bug in updating Payload with new Request object,"<?php /* * Copyright (c) 2016 Refinery29, Inc. * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Refinery29\Piston\Middleware\Request; use League\Pipeline\StageInterface; use Refinery29\Piston\Middleware\GetOnlyStage; use Refinery29\Piston\Middleware\Payload; use Refinery29\Piston\Request; class IncludedResource implements StageInterface { use GetOnlyStage; /** * @param Payload $payload * * @throws \League\Route\Http\Exception\BadRequestException * * @return Payload */ public function process($payload) { /** @var Request $request */ $request = $payload->getRequest(); if (!isset($request->getQueryParams()['include'])) { return $payload; } $this->ensureGetOnlyRequest($request); $include = explode(',', $request->getQueryParams()['include']); if (!empty($include)) { foreach ((array) $include as $k => $resource) { if (strpos($resource, '.') !== false) { $resource = explode('.', $resource); $include[$k] = $resource; } } $payload = $payload->withRequest( $request->withIncludedResources($include) ); } return $payload; } } ","<?php /* * Copyright (c) 2016 Refinery29, Inc. * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Refinery29\Piston\Middleware\Request; use League\Pipeline\StageInterface; use Refinery29\Piston\Middleware\GetOnlyStage; use Refinery29\Piston\Middleware\Payload; use Refinery29\Piston\Request; class IncludedResource implements StageInterface { use GetOnlyStage; /** * @param Payload $payload * * @throws \League\Route\Http\Exception\BadRequestException * * @return Request */ public function process($payload) { /** @var Request $request */ $request = $payload->getRequest(); if (!isset($request->getQueryParams()['include'])) { return $payload; } $this->ensureGetOnlyRequest($request); $include = explode(',', $request->getQueryParams()['include']); if (!empty($include)) { foreach ((array) $include as $k => $resource) { if (strpos($resource, '.') !== false) { $resource = explode('.', $resource); $include[$k] = $resource; } } //$request->setIncludedResources($include); $payload->withRequest($request->withIncludedResources($include)); } return $payload; } } " Make ChooseLanguageScreen use data from Redux,"import React, { Component, PropTypes } from 'react'; import { StyleSheet, View } from 'react-native'; import { Card, Thumbnail, Container, Content, List } from 'native-base'; import { connect } from 'react-redux'; import chooseLanguageStyles from './chooseLanguageStyles'; import GlobalStyle from '../../common/globalStyle'; import CardHeader from '../../common/card-header/cardHeader'; import SingleRowListItem from '../../common/single-row-list-item/singleRowListItem'; // TODO Replace temporary placeholder image const LOGO_URL = 'https://facebook.github.io/react/img/logo_og.png'; class ChooseLanguageScreen extends Component { static navigationOptions = { title: 'Choose Language', }; // TODO Improve typechecking static propTypes = { languages: PropTypes.objectOf(PropTypes.any).isRequired, }; renderRow = lang => <SingleRowListItem text={lang.attributes.local_name} icon=""arrow-forward"" /> render() { return ( <Container> <Content contentContainerStyle={GlobalStyle.padder}> <View style={chooseLanguageStyles.logoContainer}> <Thumbnail style={StyleSheet.flatten(chooseLanguageStyles.logo)} source={{ uri: LOGO_URL }} /> </View> <Card> <CardHeader title=""Välj språk"" subtitle=""Språket som ska visas i appen"" icon=""globe"" /> <List dataArray={this.props.languages.languages.data} renderRow={this.renderRow} /> </Card> </Content> </Container> ); } } const mapStateToProps = state => ({ languages: state.languages }); export default connect(mapStateToProps)(ChooseLanguageScreen); ","import React, { Component } from 'react'; import { StyleSheet, View } from 'react-native'; import { Card, Thumbnail, Container, Content, List } from 'native-base'; import chooseLanguageStyles from './chooseLanguageStyles'; import GlobalStyle from '../../common/globalStyle'; import CardHeader from '../../common/card-header/cardHeader'; import SingleRowListItem from '../../common/single-row-list-item/singleRowListItem'; const LOGO_URL = 'https://facebook.github.io/react/img/logo_og.png'; // Temporary data. Will be handled in another way in the future. const LANGUAGES = ['Svenska', 'English', 'Español', 'Dansk', 'Norsk']; export default class ChooseLanguageScreen extends Component { static navigationOptions = { title: 'Choose Language', }; renderRow = language => <SingleRowListItem text={language} icon=""arrow-forward"" /> render() { return ( <Container> <Content contentContainerStyle={GlobalStyle.padder}> <View style={chooseLanguageStyles.logoContainer}> <Thumbnail style={StyleSheet.flatten(chooseLanguageStyles.logo)} source={{ uri: LOGO_URL }} /> </View> <Card> <CardHeader title=""Välj språk"" subtitle=""Språket som ska visas i appen"" icon=""globe"" /> <List dataArray={LANGUAGES} renderRow={this.renderRow} /> </Card> </Content> </Container> ); } } " Use the correct syntax when iterating a week's games.,"from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.all()[0]; for game in wk.game_set.all(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == ""BEN"": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 60 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): ret = [] return HttpResponse(json.dumps(ret), ""application/javascript"") ","from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.all()[0]; for game in wk.games_set(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == ""BEN"": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 60 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): ret = [] return HttpResponse(json.dumps(ret), ""application/javascript"") " Fix invalid whitespace on empty line,"<?php /** * This file is part of the Laravel Auditing package. * * @author Antério Vieira <anteriovieira@gmail.com> * @author Quetzy Garcia <quetzyg@altek.org> * @author Raphael França <raphaelfrancabsb@gmail.com> * @copyright 2015-2017 * * For the full copyright and license information, * please view the LICENSE.md file that was distributed * with this source code. */ namespace OwenIt\Auditing\Drivers; use Illuminate\Support\Facades\Config; use OwenIt\Auditing\Contracts\Auditable; use OwenIt\Auditing\Contracts\AuditDriver; class Database implements AuditDriver { /** * {@inheritdoc} */ public function audit(Auditable $model) { $class = Config::get('audit.implementation', \OwenIt\Auditing\Models\Audit::class); return $class::create($model->toAudit()); } /** * {@inheritdoc} */ public function prune(Auditable $model) { if (($threshold = $model->getAuditThreshold()) > 0) { $total = $model->audits()->count(); $forRemoval = ($total - $threshold); if ($forRemoval > 0) { $model->audits() ->orderBy('created_at', 'asc') ->limit($forRemoval) ->delete(); return true; } } return false; } } ","<?php /** * This file is part of the Laravel Auditing package. * * @author Antério Vieira <anteriovieira@gmail.com> * @author Quetzy Garcia <quetzyg@altek.org> * @author Raphael França <raphaelfrancabsb@gmail.com> * @copyright 2015-2017 * * For the full copyright and license information, * please view the LICENSE.md file that was distributed * with this source code. */ namespace OwenIt\Auditing\Drivers; use Illuminate\Support\Facades\Config; use OwenIt\Auditing\Contracts\Auditable; use OwenIt\Auditing\Contracts\AuditDriver; class Database implements AuditDriver { /** * {@inheritdoc} */ public function audit(Auditable $model) { $class = Config::get('audit.implementation', \OwenIt\Auditing\Models\Audit::class); return $class::create($model->toAudit()); } /** * {@inheritdoc} */ public function prune(Auditable $model) { if (($threshold = $model->getAuditThreshold()) > 0) { $total = $model->audits()->count(); $forRemoval = ($total - $threshold); if ($forRemoval > 0) { $model->audits() ->orderBy('created_at', 'asc') ->limit($forRemoval) ->delete(); return true; } } return false; } } " FORGE-1848: Fix CDI explosions. Weld doesn't like Anonmymous classes sometimes for some reason?,"package org.jboss.forge.addon.parser.java.beans; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import org.jboss.forge.addon.parser.java.facets.JavaSourceFacet; import org.jboss.forge.addon.parser.java.resources.JavaResource; import org.jboss.forge.addon.parser.java.resources.JavaResourceVisitor; import org.jboss.forge.addon.projects.Project; import org.jboss.forge.addon.resource.visit.VisitContext; import org.jboss.forge.roaster.model.source.JavaSource; /** * @author <a href=""mailto:lincolnbaxter@gmail.com"">Lincoln Baxter, III</a> */ public class ProjectOperations { public List<JavaResource> getProjectClasses(Project project) { final List<JavaResource> classes = new ArrayList<>(); if (project != null) { project.getFacet(JavaSourceFacet.class).visitJavaSources(new JavaClassSourceVisitor(classes)); } return classes; } private static class JavaClassSourceVisitor extends JavaResourceVisitor { private final List<JavaResource> classes; private JavaClassSourceVisitor(List<JavaResource> classes) { this.classes = classes; } @Override public void visit(VisitContext context, JavaResource resource) { try { JavaSource<?> javaType = resource.getJavaType(); if (javaType.isClass()) { classes.add(resource); } } catch (FileNotFoundException e) { // ignore } } } } ","package org.jboss.forge.addon.parser.java.beans; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import org.jboss.forge.addon.parser.java.facets.JavaSourceFacet; import org.jboss.forge.addon.parser.java.resources.JavaResource; import org.jboss.forge.addon.parser.java.resources.JavaResourceVisitor; import org.jboss.forge.addon.projects.Project; import org.jboss.forge.addon.resource.visit.VisitContext; import org.jboss.forge.roaster.model.source.JavaSource; public class ProjectOperations { public List<JavaResource> getProjectClasses(Project project) { final List<JavaResource> classes = new ArrayList<>(); if (project != null) { project.getFacet(JavaSourceFacet.class).visitJavaSources(new JavaResourceVisitor() { @Override public void visit(VisitContext context, JavaResource resource) { try { JavaSource<?> javaType = resource.getJavaType(); if (javaType.isClass()) { classes.add(resource); } } catch (FileNotFoundException e) { // ignore } } }); } return classes; } } " Update GLPI to 0.91 in unit tests,"<?php require_once('commonfunction.php'); include_once (GLPI_ROOT . ""/config/based_config.php""); include_once (GLPI_ROOT . ""/inc/dbmysql.class.php""); include_once (GLPI_CONFIG_DIR . ""/config_db.php""); class GLPIInstallTest extends PHPUnit_Framework_TestCase { /** * @test */ public function installDatabase() { $DBvars = get_class_vars('DB'); drop_database( $DBvars['dbuser'], $DBvars['dbhost'], $DBvars['dbdefault'], $DBvars['dbpassword'] ); $result = load_mysql_file( $DBvars['dbuser'], $DBvars['dbhost'], $DBvars['dbdefault'], $DBvars['dbpassword'], GLPI_ROOT .""/install/mysql/glpi-0.91-empty.sql"" ); $output = array(); $returncode = 0; exec( ""php -f "".GLPI_ROOT. ""/tools/cliupdate.php -- --upgrade"", $output, $returncode ); $this->assertEquals(0,$returncode, ""Error when update GLPI in CLI mode\n"". implode(""\n"",$output) ); $this->assertEquals( 0, $result['returncode'], ""Failed to install GLPI database:\n"". implode(""\n"", $result['output']) ); } } ","<?php require_once('commonfunction.php'); include_once (GLPI_ROOT . ""/config/based_config.php""); include_once (GLPI_ROOT . ""/inc/dbmysql.class.php""); include_once (GLPI_CONFIG_DIR . ""/config_db.php""); class GLPIInstallTest extends PHPUnit_Framework_TestCase { /** * @test */ public function installDatabase() { $DBvars = get_class_vars('DB'); drop_database( $DBvars['dbuser'], $DBvars['dbhost'], $DBvars['dbdefault'], $DBvars['dbpassword'] ); $result = load_mysql_file( $DBvars['dbuser'], $DBvars['dbhost'], $DBvars['dbdefault'], $DBvars['dbpassword'], GLPI_ROOT .""/install/mysql/glpi-0.90-empty.sql"" ); $output = array(); $returncode = 0; exec( ""php -f "".GLPI_ROOT. ""/tools/cliupdate.php -- --upgrade"", $output, $returncode ); $this->assertEquals(0,$returncode, ""Error when update GLPI in CLI mode\n"". implode(""\n"",$output) ); $this->assertEquals( 0, $result['returncode'], ""Failed to install GLPI database:\n"". implode(""\n"", $result['output']) ); } } " Improve output for Pairing lists,"import java.awt.Component; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; public class PairingListCellRenderer implements ListCellRenderer<Pairing> { @Override public Component getListCellRendererComponent(JList<? extends Pairing> list, Pairing value, int index, boolean isSelected, boolean cellHasFocus) { String latex = ""?""; if (value != null) { String type = value.getVariableExpression().getType().toString(); if (value.isPaired()) { //make a copy of the expression so that any selections can be removed, //otherwise the selected subexpression will show as highlighted in the pairings list. Expression copy = value.getPairedExpression().duplicate(); copy.deselectRecursive(); latex = String.format(""\\textrm{%s } %s \\leftarrow %s"", type, value.getVariableExpression().toLatex(), copy.toLatex()); } else { latex = String.format(""\\textrm{%s } %s \\textrm{ is unpaired}"", type, value.getVariableExpression().toLatex()); } if (isSelected) latex = String.format(""\\bgcolor{%s}{%s}"", LookAndFeel.SELECTED_LATEX_COLOR, latex); } return new JLabel(new ImageIcon(LatexHandler.latexToImage(latex))); } }","import java.awt.Component; import java.awt.image.BufferedImage; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; @SuppressWarnings(""unused"") public class PairingListCellRenderer implements ListCellRenderer<Pairing> { @Override public Component getListCellRendererComponent(JList<? extends Pairing> list, Pairing value, int index, boolean isSelected, boolean cellHasFocus) { String latex = ""?""; if (value != null) { String type = value.getVariableExpression().getType().toString(); if (value.isPaired()) { //make a copy of the expression so that any selections can be removed, //otherwise the selected subexpression will show as highlighted in the pairings list. Expression copy = value.getPairedExpression().duplicate(); copy.deselectRecursive(); latex = type + "" "" + value.getVariableExpression().toLatex() + "" \\leftarrow "" + copy.toLatex(); //latex = value.getVariableExpression().toLatex() + "" \\leftarrow "" + value.getPairedExpression().toLatex(); } else { latex = type + "" "" + value.getVariableExpression().toLatex() + "" \\textrm{ is unpaired}""; } if (isSelected) { latex = ""\\bgcolor{"" + LookAndFeel.SELECTED_LATEX_COLOR + ""}{"" + latex + ""}""; } } return new JLabel(new ImageIcon(LatexHandler.latexToImage(latex))); } }" Stop invoking get_model for each request,"from __future__ import absolute_import, unicode_literals from django.http import Http404 from django.utils.functional import cached_property from feincms import settings from feincms._internal import get_model from feincms.module.mixins import ContentView class Handler(ContentView): page_model_path = None context_object_name = 'feincms_page' @cached_property def page_model(self): model = self.page_model_path or settings.FEINCMS_DEFAULT_PAGE_MODEL return get_model(*model.split('.')) def get_object(self): path = None if self.args: path = self.args[0] return self.page_model._default_manager.for_request( self.request, raise404=True, best_match=True, path=path) def dispatch(self, request, *args, **kwargs): try: return super(Handler, self).dispatch(request, *args, **kwargs) except Http404 as e: if settings.FEINCMS_CMS_404_PAGE: try: request.original_path_info = request.path_info request.path_info = settings.FEINCMS_CMS_404_PAGE response = super(Handler, self).dispatch( request, *args, **kwargs) response.status_code = 404 return response except Http404: raise e else: raise ","from __future__ import absolute_import, unicode_literals from django.http import Http404 from feincms import settings from feincms._internal import get_model from feincms.module.mixins import ContentView class Handler(ContentView): page_model_path = 'page.Page' context_object_name = 'feincms_page' @property def page_model(self): if not hasattr(self, '_page_model'): self._page_model = get_model(*self.page_model_path.split('.')) if self._page_model is None: raise ImportError( ""Can't import model \""%s\"""" % self.page_model_path) return self._page_model def get_object(self): path = None if self.args: path = self.args[0] return self.page_model._default_manager.for_request( self.request, raise404=True, best_match=True, path=path) def dispatch(self, request, *args, **kwargs): try: return super(Handler, self).dispatch(request, *args, **kwargs) except Http404 as e: if settings.FEINCMS_CMS_404_PAGE: try: request.original_path_info = request.path_info request.path_info = settings.FEINCMS_CMS_404_PAGE response = super(Handler, self).dispatch( request, *args, **kwargs) response.status_code = 404 return response except Http404: raise e else: raise " Allow keys to be set (in anticipation of write commands). Better object __repr__() for spaces and tickets.,"from functools import wraps class AssemblaObject(object): """""" Proxies getitem calls (eg: `instance['id']`) to a dictionary `instance.data['id']`. """""" def __init__(self, data): self.data = data def __getitem__(self, key): return self.data[key] def __setitem__(self, key, value): self.data[key] = value def keys(self): return self.data.keys() def values(self): return self.data.values() def get(self, *args, **kwargs): return self.data.get(*args, **kwargs) def __repr__(self): if 'name' in self.data: return ""<%s: %s>"" % (type(self).__name__, self.data['name']) if ('number' in self.data) and ('summary' in self.data): return ""<%s: #%s - %s>"" % (type(self).__name__, self.data['number'], self.data['summary']) return super(AssemblaObject, self).__repr__() def assembla_filter(func): """""" Filters :data for the objects in it which possess attributes equal in name/value to a key/value in kwargs. Each key/value combination in kwargs is compared against the object, so multiple keyword arguments can be passed in to constrain the filtering. """""" @wraps(func) def wrapper(class_instance, **kwargs): results = func(class_instance) if not kwargs: return results else: return filter( # Find the objects who have an equal number of matching attr/value # combinations as `len(kwargs)` lambda obj: len(kwargs) == len( filter( lambda boolean: boolean, [obj.get(attr_name) == value for attr_name, value in kwargs.iteritems()] ) ), results ) return wrapper","from functools import wraps class AssemblaObject(object): """""" Proxies getitem calls (eg: `instance['id']`) to a dictionary `instance.data['id']`. """""" def __init__(self, data): self.data = data def __getitem__(self, key): return self.data[key] def keys(self): return self.data.keys() def values(self): return self.data.values() def get(self, *args, **kwargs): return self.data.get(*args, **kwargs) def assembla_filter(func): """""" Filters :data for the objects in it which possess attributes equal in name/value to a key/value in kwargs. Each key/value combination in kwargs is compared against the object, so multiple keyword arguments can be passed in to constrain the filtering. """""" @wraps(func) def wrapper(class_instance, **kwargs): results = func(class_instance) if not kwargs: return results else: return filter( # Find the objects who have an equal number of matching attr/value # combinations as `len(kwargs)` lambda obj: len(kwargs) == len( filter( lambda boolean: boolean, [obj.get(attr_name) == value for attr_name, value in kwargs.iteritems()] ) ), results ) return wrapper" Set template wildcard to *.mako,"#!/usr/bin/env python from setuptools import setup, find_packages import sys import os import glob setup(name = ""scilifelab"", version = ""0.2.2"", author = ""Science for Life Laboratory"", author_email = ""genomics_support@scilifelab.se"", description = ""Useful scripts for use at SciLifeLab"", license = ""MIT"", scripts = glob.glob('scripts/*.py') + glob.glob('scripts/bcbb_helpers/*.py') + ['scripts/pm'], install_requires = [ ""bcbio-nextgen >= 0.2"", ""drmaa >= 0.5"", ""sphinx >= 1.1.3"", ""couchdb >= 0.8"", ""reportlab >= 2.5"", ""cement >= 2.0.2"", ""mock"", ""PIL"", ""pyPdf"", ""logbook >= 0.4"", # pandas screws up installation; tries to look for local site # packages and not in virtualenv #""pandas >= 0.9"", ""biopython"", ""rst2pdf"", #""psutil"", ], test_suite = 'nose.collector', packages=find_packages(exclude=['tests']), package_data = {'scilifelab':[ 'data/grf/*', 'data/templates/*.mako', 'data/templates/rst/*', ]} ) os.system(""git rev-parse --short --verify HEAD > ~/.scilifelab_version"") ","#!/usr/bin/env python from setuptools import setup, find_packages import sys import os import glob setup(name = ""scilifelab"", version = ""0.2.2"", author = ""Science for Life Laboratory"", author_email = ""genomics_support@scilifelab.se"", description = ""Useful scripts for use at SciLifeLab"", license = ""MIT"", scripts = glob.glob('scripts/*.py') + glob.glob('scripts/bcbb_helpers/*.py') + ['scripts/pm'], install_requires = [ ""bcbio-nextgen >= 0.2"", ""drmaa >= 0.5"", ""sphinx >= 1.1.3"", ""couchdb >= 0.8"", ""reportlab >= 2.5"", ""cement >= 2.0.2"", ""mock"", ""PIL"", ""pyPdf"", ""logbook >= 0.4"", # pandas screws up installation; tries to look for local site # packages and not in virtualenv #""pandas >= 0.9"", ""biopython"", ""rst2pdf"", #""psutil"", ], test_suite = 'nose.collector', packages=find_packages(exclude=['tests']), package_data = {'scilifelab':[ 'data/grf/*', 'data/templates/*.*', 'data/templates/rst/*', ]} ) os.system(""git rev-parse --short --verify HEAD > ~/.scilifelab_version"") " Upgrade tangled 1.0a10 => 1.0a11,"from setuptools import setup, PEP420PackageFinder setup( name='tangled.web', version='1.0a11.dev0', description='RESTful Web Framework', long_description=open('README.rst').read(), url='http://tangledframework.org/', download_url='https://github.com/TangledWeb/tangled.web/tags', author='Wyatt Baldwin', author_email='self@wyattbaldwin.com', packages=PEP420PackageFinder.find(include=['tangled*']), include_package_data=True, install_requires=[ 'tangled>=1.0a11', 'MarkupSafe>=0.23', 'WebOb>=1.5.1', ], extras_require={ 'dev': [ 'tangled[dev]>=1.0a11', ], }, entry_points="""""" [tangled.scripts] serve = tangled.web.scripts.serve shell = tangled.web.scripts.shell show = tangled.web.scripts.show [tangled.scaffolds] basic = tangled.web.scaffolds:basic """""", classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], ) ","from setuptools import setup, PEP420PackageFinder setup( name='tangled.web', version='1.0a11.dev0', description='RESTful Web Framework', long_description=open('README.rst').read(), url='http://tangledframework.org/', download_url='https://github.com/TangledWeb/tangled.web/tags', author='Wyatt Baldwin', author_email='self@wyattbaldwin.com', packages=PEP420PackageFinder.find(include=['tangled*']), include_package_data=True, install_requires=[ 'tangled>=1.0a10', 'MarkupSafe>=0.23', 'WebOb>=1.5.1', ], extras_require={ 'dev': [ 'tangled[dev]>=1.0a10', ], }, entry_points="""""" [tangled.scripts] serve = tangled.web.scripts.serve shell = tangled.web.scripts.shell show = tangled.web.scripts.show [tangled.scaffolds] basic = tangled.web.scaffolds:basic """""", classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], ) " Fix bug in new URL endpoint,"from django.conf import settings from django.conf.urls import url from django.views.decorators.cache import cache_page import api.activity.views import api.sector.views app_name = 'api' urlpatterns = [ url(r'^$', api.activity.views.ActivityList.as_view(), name='activity-list'), url(r'^aggregations/', cache_page( settings.API_CACHE_SECONDS )(api.activity.views.ActivityAggregations.as_view()), name='activity-aggregations'), url(r'^(?P<pk>\d+)/$', api.activity.views.ActivityDetail.as_view(), name='activity-detail'), url(r'^(?P<iati_identifier>[\w-]+)/$', api.activity.views.ActivityDetailByIatiIdentifier.as_view(), name='activity-detail-by-iati-identifier'), url(r'^(?P<pk>\d+)/transactions/$', api.activity.views.ActivityTransactionList.as_view(), name='activity-transactions'), url(r'^(?P<iati_identifier>[\w-]+)/transactions/$', api.activity.views.ActivityTransactionListByIatiIdentifier.as_view(), name='activity-transactions-by-iati-identifier'), url(r'^(?P<pk>\d+)/transactions/(?P<id>[^@$&+,/:;=?]+)$', api.activity.views.ActivityTransactionDetail.as_view(), name='activity-transaction-detail'), ] ","from django.conf import settings from django.conf.urls import url from django.views.decorators.cache import cache_page import api.activity.views import api.sector.views app_name = 'api' urlpatterns = [ url(r'^$', api.activity.views.ActivityList.as_view(), name='activity-list'), url(r'^aggregations/', cache_page( settings.API_CACHE_SECONDS )(api.activity.views.ActivityAggregations.as_view()), name='activity-aggregations'), url(r'^(?P<pk>\d+)/$', api.activity.views.ActivityDetail.as_view(), name='activity-detail'), url(r'^(?P<iati_identifier>[\w-]+)/$', api.activity.views.ActivityDetailByIatiIdentifier.as_view(), name='activity-detail-by-iati-identifier'), url(r'^(?P<pk>\d+)/transactions/$', api.activity.views.ActivityTransactionList.as_view(), name='activity-transactions'), url(r'^(?P<iati_identifier>[\w-]+)/transactions$', api.activity.views.ActivityTransactionListByIatiIdentifier.as_view(), name='activity-transactions-by-iati-identifier'), url(r'^(?P<pk>\d+)/transactions/(?P<id>[^@$&+,/:;=?]+)$', api.activity.views.ActivityTransactionDetail.as_view(), name='activity-transaction-detail'), ] " Fix attributes manager test to fit the new model,"<?php namespace PhpAbac\Test\Manager; use PhpAbac\Abac; class AttributeManagerTest extends \PHPUnit_Framework_TestCase { /** @var \PhpAbac\Manager\AttributeManager **/ private $manager; public function setUp() { new Abac(new \PDO( 'mysql:host=' . $GLOBALS['MYSQL_DB_HOST'] . ';' . 'dbname=' . $GLOBALS['MYSQL_DB_DBNAME'], $GLOBALS['MYSQL_DB_USER'], $GLOBALS['MYSQL_DB_PASSWD'], [ \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION ] )); $this->manager = Abac::get('attribute-manager'); } public function tearDown() { Abac::clearContainer(); } public function testCreate() { $this->manager->create('test-attribute', 'abac_policy_rules', 'name', 'id'); $data = Abac::get('pdo-connection') ->query( 'SELECT * FROM abac_attributes_data ad ' . 'INNER JOIN abac_attributes a ON a.id = ad.id '. 'WHERE ad.name = ""JAPD""' ) ->fetchAll() ; $this->assertCount(1, $data); $this->assertEquals('JAPD', $data[0]['name']); $this->assertEquals('abac_test_user', $data[0]['table_name']); $this->assertEquals('has_done_japd', $data[0]['column_name']); $this->assertEquals('id', $data[0]['criteria_column']); } }","<?php namespace PhpAbac\Test\Manager; use PhpAbac\Abac; class AttributeManagerTest extends \PHPUnit_Framework_TestCase { /** @var \PhpAbac\Manager\AttributeManager **/ private $manager; public function setUp() { new Abac(new \PDO( 'mysql:host=' . $GLOBALS['MYSQL_DB_HOST'] . ';' . 'dbname=' . $GLOBALS['MYSQL_DB_DBNAME'], $GLOBALS['MYSQL_DB_USER'], $GLOBALS['MYSQL_DB_PASSWD'], [ \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION ] )); $this->manager = Abac::get('attribute-manager'); } public function tearDown() { Abac::clearContainer(); } public function testCreate() { $this->manager->create('test-attribute', 'abac_policy_rules', 'name', 'id'); $data = Abac::get('pdo-connection')->query('SELECT * FROM abac_attributes WHERE name = ""test-attribute""')->fetchAll(); $this->assertCount(1, $data); $this->assertEquals('test-attribute', $data[0]['name']); $this->assertEquals('abac_policy_rules', $data[0]['table_name']); $this->assertEquals('name', $data[0]['column_name']); $this->assertEquals('id', $data[0]['criteria_column']); } }" Add function to convert wkt point to coordinates.,"<?php /** * Implements convenient methods for conversion of JSON and WKT. */ function json_to_wkt($json) { $geometry = json_decode($json)->{""features""}[0]->{""geometry""}; $coordinates = $geometry->{""coordinates""}; $wkt = """"; if($geometry->{""type""} == ""Polygon"") { $wkt = ""POLYGON(""; foreach ($coordinates as $linearRing) { $wkt .= ""(""; foreach($linearRing as $point) { $wkt .= $point[0] . "" "" . $point[1] . "",""; } $wkt = substr($wkt, 0, -1) . ""),""; } } else if($geometry->{""type""} == ""MultiPolygon"") { $wkt = ""MULTIPOLYGON(""; foreach ($coordinates as $polygon) { $wkt .= ""(""; foreach ($polygon as $linearRing) { $wkt .= ""(""; foreach ($linearRing as $point) { $wkt .= $point[0] . "" "" . $point[1] . "",""; } $wkt = substr($wkt, 0, -1) . ""),""; } $wkt = substr($wkt, 0, -1) . ""),""; } } return substr($wkt, 0, -1) . "")""; } function point_to_coord($wkt) { $coord = explode(""("", $wkt)[1]; $coord = explode("")"", $coord)[0]; return explode("" "", $coord); } ?>","<?php /** * Implements convenient methods for conversion of JSON to and from WKT. */ function json_to_wkt($json) { $geometry = json_decode($json)->{""features""}[0]->{""geometry""}; $coordinates = $geometry->{""coordinates""}; $wkt = """"; if($geometry->{""type""} == ""Polygon"") { $wkt = ""POLYGON(""; foreach ($coordinates as $linearRing) { $wkt .= ""(""; foreach($linearRing as $point) { $wkt .= $point[0] . "" "" . $point[1] . "",""; } $wkt = substr($wkt, 0, -1) . ""),""; } } else if($geometry->{""type""} == ""MultiPolygon"") { $wkt = ""MULTIPOLYGON(""; foreach ($coordinates as $polygon) { $wkt .= ""(""; foreach ($polygon as $linearRing) { $wkt .= ""(""; foreach ($linearRing as $point) { $wkt .= $point[0] . "" "" . $point[1] . "",""; } $wkt = substr($wkt, 0, -1) . ""),""; } $wkt = substr($wkt, 0, -1) . ""),""; } } return substr($wkt, 0, -1) . "")""; } ?>" Disable stats after crash report until we find a alternative solution," from datetime import datetime from seven23.models.profile.models import Profile from rest_framework.authentication import TokenAuthentication # from seven23.models.stats.models import MonthlyActiveUser, DailyActiveUser def active_user_middleware(get_response): def middleware(request): user = request.user user_auth_tuple = TokenAuthentication().authenticate(request) if user_auth_tuple is not None: (user, token) = user_auth_tuple if user.is_authenticated and not user.is_superuser: # If user has no profile, we create on. if not hasattr(user, 'profile'): Profile.objects.create(user=user) now = datetime.now() last_api_call = user.profile.last_api_call udpate_user = False if now.year != last_api_call.year or now.month != last_api_call.month : # MonthlyActiveUser.objects.update_or_create(year=now.year, month=now.month) udpate_user = True if now.year != last_api_call.year or now.month != last_api_call.month or now.day != last_api_call.day : # DailyActiveUser.objects.update_or_create(year=now.year, month=now.month, day=now.day) udpate_user = True if udpate_user: user.profile.last_api_call = now user.save() # Perform actual request response = get_response(request) return response return middleware"," from datetime import datetime from seven23.models.profile.models import Profile from rest_framework.authentication import TokenAuthentication from seven23.models.stats.models import MonthlyActiveUser, DailyActiveUser def active_user_middleware(get_response): def middleware(request): user = request.user user_auth_tuple = TokenAuthentication().authenticate(request) if user_auth_tuple is not None: (user, token) = user_auth_tuple if user.is_authenticated and not user.is_superuser: # If user has no profile, we create on. if not hasattr(user, 'profile'): Profile.objects.create(user=user) now = datetime.now() last_api_call = user.profile.last_api_call udpate_user = False if now.year != last_api_call.year or now.month != last_api_call.month : MonthlyActiveUser.objects.update_or_create(year=now.year, month=now.month) udpate_user = True if now.year != last_api_call.year or now.month != last_api_call.month or now.day != last_api_call.day : DailyActiveUser.objects.update_or_create(year=now.year, month=now.month, day=now.day) udpate_user = True if udpate_user: user.profile.last_api_call = now user.save() # Perform actual request response = get_response(request) return response return middleware" Fix import order (some somewhat cyclic dependencies; should fix),"""""""This module has functions and classes useful for setting up simulations"""""" ######################################################################## # # # This test was written by Thomas Heavey in 2019. # # theavey@bu.edu thomasjheavey@gmail.com # # # # Copyright 2017-19 Thomas J. Heavey IV # # # # 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. # # # ######################################################################## from __future__ import absolute_import from .para_temp_setup import * from .sim_setup import * from .molecule import Molecule from .system import System from .simulation import Simulation, SimpleSimulation from .pt_simulation import PTSimulation ","""""""This module has functions and classes useful for setting up simulations"""""" ######################################################################## # # # This test was written by Thomas Heavey in 2019. # # theavey@bu.edu thomasjheavey@gmail.com # # # # Copyright 2017-19 Thomas J. Heavey IV # # # # 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. # # # ######################################################################## from __future__ import absolute_import from .para_temp_setup import * from .sim_setup import * from .simulation import Simulation, SimpleSimulation from .pt_simulation import PTSimulation from .molecule import Molecule from .system import System " BAP-1664: Fix not valid date from db,"<?php namespace Oro\Bundle\LocaleBundle\DoctrineExtensions\DBAL\Types; use Doctrine\DBAL\Platforms\AbstractPlatform; use Doctrine\DBAL\Types\ConversionException; use Doctrine\DBAL\Types\DateTimeType; class UTCDateTimeType extends DateTimeType { /** @var null| \DateTimeZone */ static private $utc = null; /** * {@inheritdoc} */ public function convertToDatabaseValue($value, AbstractPlatform $platform) { if ($value === null) { return null; } $value->setTimeZone((self::$utc) ? self::$utc : (self::$utc = new \DateTimeZone('UTC'))); return parent::convertToDatabaseValue($value, $platform); } /** * {@inheritdoc} */ public function convertToPHPValue($value, AbstractPlatform $platform) { if ($value === null) { return null; } $val = \DateTime::createFromFormat( $platform->getDateTimeFormatString(), $value, (self::$utc) ? self::$utc : (self::$utc = new \DateTimeZone('UTC')) ); if (!$val) { throw ConversionException::conversionFailed($value, $this->getName()); } $errors = $val->getLastErrors(); // date was parsed to completely not valid value if ($errors['warning_count'] > 0 && (int)$val->format('Y') < 0) { return null; } return $val; } } ","<?php namespace Oro\Bundle\LocaleBundle\DoctrineExtensions\DBAL\Types; use Doctrine\DBAL\Platforms\AbstractPlatform; use Doctrine\DBAL\Types\ConversionException; use Doctrine\DBAL\Types\DateTimeType; class UTCDateTimeType extends DateTimeType { /** @var null| \DateTimeZone */ static private $utc = null; /** * {@inheritdoc} */ public function convertToDatabaseValue($value, AbstractPlatform $platform) { if ($value === null) { return null; } $value->setTimeZone((self::$utc) ? self::$utc : (self::$utc = new \DateTimeZone('UTC'))); return parent::convertToDatabaseValue($value, $platform); } /** * {@inheritdoc} */ public function convertToPHPValue($value, AbstractPlatform $platform) { if ($value === null) { return null; } $val = \DateTime::createFromFormat( $platform->getDateTimeFormatString(), $value, (self::$utc) ? self::$utc : (self::$utc = new \DateTimeZone('UTC')) ); if (!$val) { throw ConversionException::conversionFailed($value, $this->getName()); } $errors = $val->getLastErrors(); if ($errors['warning_count'] > 0) { return null; } return $val; } } " Fix logic for displaying pending survey info,"<h2><span class=""label label-default"">Pending surveys</span></h2> <table class=""table table-striped table-hover""> <thead> <tr> <th>Survey ID</th> <th>Description</th> <th>Date Scheduled</th> <th>Test type</th> <th>Accession</th> <th>Survey Note</th> <th></th> </tr> </thead> <tbody> @foreach ($pendingSurveys as $pending) @unless (is_null($pending->machine)) <tr> <td><a href=""{{ route('surveys.edit', $pending->id)}}"">{{ $pending->id }}</a></td> <td><a href=""{{ route('machines.show', $pending->machine->id) }}"">{{ $pending->machine->description }}</a></td> <td>{{ $pending->test_date}}</td> <td>{{ $pending->type->test_type}}</td> <td>{{ $pending->accession }}</td> <td>{{ $pending->notes }}</td> <td><a href=""{{ route('surveys.edit', $pending->id) }}"" class=""btn btn-default btn-xs"" role=""button"" data-toggle=""tooltip"" title=""Modify this machine""> <span class=""glyphicon glyphicon-pencil"" aria-hidden=""true""></span></a> </td> </tr> @endunless @endforeach </tbody> </table> ","<h2><span class=""label label-default"">Pending surveys</span></h2> <table class=""table table-striped table-hover""> <thead> <tr> <th>Survey ID</th> <th>Description</th> <th>Date Scheduled</th> <th>Test type</th> <th>Accession</th> <th>Survey Note</th> <th></th> </tr> </thead> <tbody> @foreach ($pendingSurveys as $pending) @if (is_null($pending->machine)) { break; } @else { <tr> <td><a href=""{{ route('surveys.edit', $pending->id)}}"">{{ $pending->id }}</a></td> <td><a href=""{{ route('machines.show', $pending->machine->id) }}"">{{ $pending->machine->description }}</a></td> <td>{{ $pending->test_date}}</td> <td>{{ $pending->type->test_type}}</td> <td>{{ $pending->accession }}</td> <td>{{ $pending->notes }}</td> <td><a href=""{{ route('surveys.edit', $pending->id) }}"" class=""btn btn-default btn-xs"" role=""button"" data-toggle=""tooltip"" title=""Modify this machine""> <span class=""glyphicon glyphicon-pencil"" aria-hidden=""true""></span></a> </td> </tr> } @endif @endforeach </tbody> </table> " ":bug: Send a ping on worker init This fixes non-shared workers","'use babel' import {Disposable, CompositeDisposable} from 'sb-event-kit' import Communication from 'sb-communication' class Exchange { constructor(worker) { this.worker = worker this.port = worker.port || worker this.communication = new Communication() this.subscriptions = new CompositeDisposable() this.subscriptions.add(this.communication) const callback = message => { this.communication.parseMessage(message.data) } this.port.addEventListener('message', callback) this.subscriptions.add(new Disposable(() => { this.port.removeEventListener('message', callback) })) this.communication.onShouldSend(message => { this.port.postMessage(message) }) this.onRequest('ping', function(_, message) { message.response = 'pong' }) this.request('ping') } request(name, data = {}) { return this.communication.request(name, data) } onRequest(name, callback) { return this.communication.onRequest(name, callback) } terminate() { if (this.worker.terminate) { this.worker.terminate() } else { this.port.close() } this.dispose() } dispose() { this.subscriptions.dispose() } static create(filePath) { return new Exchange(new Worker(filePath)) } static createShared(filePath) { const worker = new SharedWorker(filePath) const exchange = new Exchange(worker) worker.port.start() return exchange } } module.exports = Exchange ","'use babel' import {Disposable, CompositeDisposable} from 'sb-event-kit' import Communication from 'sb-communication' class Exchange { constructor(worker) { this.worker = worker this.port = worker.port || worker this.communication = new Communication() this.subscriptions = new CompositeDisposable() this.subscriptions.add(this.communication) const callback = message => { this.communication.parseMessage(message.data) } this.port.addEventListener('message', callback) this.subscriptions.add(new Disposable(() => { this.port.removeEventListener('message', callback) })) this.communication.onShouldSend(message => { this.port.postMessage(message) }) this.onRequest('ping', function(_, message) { message.response = 'pong' }) } request(name, data = {}) { return this.communication.request(name, data) } onRequest(name, callback) { return this.communication.onRequest(name, callback) } terminate() { if (this.worker.terminate) { this.worker.terminate() } else { this.port.close() } this.dispose() } dispose() { this.subscriptions.dispose() } static create(filePath) { return new Exchange(new Worker(filePath)) } static createShared(filePath) { const worker = new SharedWorker(filePath) const exchange = new Exchange(worker) worker.port.start() return exchange } } module.exports = Exchange " Add 'Escalation' Queue Id (Valorant),"package no.stelar7.api.r4j.basic.constants.types.val; import no.stelar7.api.r4j.basic.constants.types.CodedEnum; import java.util.Optional; import java.util.stream.Stream; public enum GameQueueType implements CodedEnum<GameQueueType> { COMPETITIVE(""competitive""), DEATHMATCH(""deathmatch""), SPIKE_RUSH(""spikerush""), UNRATED(""unrated""), CUSTOM_GAME(""""), TOURNAMENT_MODE(""tournamentmode""), ONE_FOR_ALL(""onefa""), ESCALATION(""ggteam""), ; private final String queue; /** * Constructor for MapType * * @param code the mapId */ GameQueueType(final String code) { this.queue = code; } /** * Gets from code. * * @param mapId the map id * @return the from code */ public Optional<GameQueueType> getFromCode(final String mapId) { return Stream.of(GameQueueType.values()).filter(t -> t.queue.equals(mapId)).findFirst(); } @Override public String prettyName() { switch (this) { default: return ""This enum does not have a pretty name""; } } /** * Gets id. * * @return the id */ public String getId() { return this.queue; } /** * Used internaly in the api... * * @return the value */ public String getValue() { return getId(); } } ","package no.stelar7.api.r4j.basic.constants.types.val; import no.stelar7.api.r4j.basic.constants.types.CodedEnum; import java.util.Optional; import java.util.stream.Stream; public enum GameQueueType implements CodedEnum<GameQueueType> { COMPETITIVE(""competitive""), DEATHMATCH(""deathmatch""), SPIKE_RUSH(""spikerush""), UNRATED(""unrated""), CUSTOM_GAME(""""), TOURNAMENT_MODE(""tournamentmode""), ONE_FOR_ALL(""onefa""), ; private final String queue; /** * Constructor for MapType * * @param code the mapId */ GameQueueType(final String code) { this.queue = code; } /** * Gets from code. * * @param mapId the map id * @return the from code */ public Optional<GameQueueType> getFromCode(final String mapId) { return Stream.of(GameQueueType.values()).filter(t -> t.queue.equals(mapId)).findFirst(); } @Override public String prettyName() { switch (this) { default: return ""This enum does not have a pretty name""; } } /** * Gets id. * * @return the id */ public String getId() { return this.queue; } /** * Used internaly in the api... * * @return the value */ public String getValue() { return getId(); } } " Make sure dataset-list doesn't get shadowed.,"/** * Main, shows the start page and provides controllers for the header and the footer. * This the entry module which serves as an entry point so other modules only have to include a * single module. */ define( [ ""angular"", ""./dashboard-services"", ""./dashboard-controllers"" ], function (angular, services, controllers) { ""use strict""; var loginRoutes = angular.module(""dashboard.routes"", [""narthex.common""]); loginRoutes.config([""$routeProvider"", function ($routeProvider) { $routeProvider .when( ""/foo"", { templateUrl: ""/narthex/assets/templates/dashboard.html"", controller: controllers.DashboardCtrl } ).otherwise( { templateUrl: ""/narthex/assets/templates/notFound.html"" } ); }]); var narthexLogin = angular.module( ""narthex.dashboard"", [ ""ngCookies"", ""ngRoute"", ""ngStorage"", ""dashboard.routes"", ""dashboard.services"" ] ); narthexLogin.controller(""IndexCtrl"", controllers.IndexCtrl); return narthexLogin; } ); ","/** * Main, shows the start page and provides controllers for the header and the footer. * This the entry module which serves as an entry point so other modules only have to include a * single module. */ define( [ ""angular"", ""./dashboard-services"", ""./dashboard-controllers"" ], function (angular, services, controllers) { ""use strict""; var loginRoutes = angular.module(""dashboard.routes"", [""narthex.common""]); loginRoutes.config([""$routeProvider"", function ($routeProvider) { $routeProvider .when( ""/"", { templateUrl: ""/narthex/assets/templates/dashboard.html"", controller: controllers.DashboardCtrl } ).otherwise( { templateUrl: ""/narthex/assets/templates/notFound.html"" } ); }]); var narthexLogin = angular.module( ""narthex.dashboard"", [ ""ngCookies"", ""ngRoute"", ""ngStorage"", ""dashboard.routes"", ""dashboard.services"" ] ); narthexLogin.controller(""IndexCtrl"", controllers.IndexCtrl); return narthexLogin; } ); " Fix double indentation error in FFApi class,"from datetime import datetime from pprint import pformat from re import search as re_search from re import sub as re_sub class FFApi: def __init__(self, content): self.c = content def pull(self, *fields): c = self.c for f in fields: if isinstance(c, dict) and f in c.keys(): if f == fields[-1]: return c[f] c = c[f] def push(self, value, *fields): c = self.c for f in fields: if isinstance(c, dict) and f in c.keys(): if f == fields[-1]: c[f] = value c = c[f] def timestamp(self): if self.pull('state', 'lastchange') is not None: self.push(api_timestamp(), 'state', 'lastchange') def show(self): return pformat(self.c) def api_timestamp(dt=None): if not dt: dt = datetime.now() return dt.isoformat('T') def api_descr(rx, replace, text): match = ( False if not (rx and text) else re_search(rx, text) ) if match and replace: text = re_sub(rx, replace, text) return text ","from datetime import datetime from pprint import pformat from re import search as re_search from re import sub as re_sub class FFApi: def __init__(self, content): self.c = content def pull(self, *fields): c = self.c for f in fields: if isinstance(c, dict) and f in c.keys(): if f == fields[-1]: return c[f] c = c[f] def push(self, value, *fields): c = self.c for f in fields: if isinstance(c, dict) and f in c.keys(): if f == fields[-1]: c[f] = value c = c[f] def timestamp(self): if self.pull('state', 'lastchange') is not None: self.push(api_timestamp(), 'state', 'lastchange') def show(self): return pformat(self.c) def api_timestamp(dt=None): if not dt: dt = datetime.now() return dt.isoformat('T') def api_descr(rx, replace, text): match = ( False if not (rx and text) else re_search(rx, text) ) if match and replace: text = re_sub(rx, replace, text) return text " "Disable logging of groups without Turbase ID This is run each time someone loads the page which makes up a lot of duplicated messages in Sentry.","/* * Copyright (c) $year, Den Norske Turistforening (DNT) * * https://github.com/Turistforeningen/turadmin */ sentry = require('../lib/sentry'); module.exports = function (app, express, options) { ""use strict""; var api = options.api; return function (req, res, next) { var userGroups = []; if (req.session && req.session.user && (!!req.session.user.sherpa_id)) { api.getAssociationsFor({bruker_sherpa_id: req.session.user.sherpa_id}, function (err, statusCode, associations) { if (err) { throw err; } if (statusCode === 200) { for (var i = 0; i < associations.length; i++) { if (associations[i].object_id) { userGroups.push(associations[i]); } else { //sentry.captureMessage('Group ""' + associations[i].navn + '"" without Turbase ID!', { // level: 'warning', // extra: { // user: req.session.user, // group: associations[i] // } //}); } } req.userGroups = userGroups; next(); } else { sentry.captureMessage('Request to DNT API failed!', { extra: { statusCode: statusCode, errors: associations.errors } }); next(); } }); } else { // User is authenticated by other method than DNT Connect console.log('Not implemented.'); next(); } }; }; ","/* * Copyright (c) $year, Den Norske Turistforening (DNT) * * https://github.com/Turistforeningen/turadmin */ sentry = require('../lib/sentry'); module.exports = function (app, express, options) { ""use strict""; var api = options.api; return function (req, res, next) { var userGroups = []; if (req.session && req.session.user && (!!req.session.user.sherpa_id)) { api.getAssociationsFor({bruker_sherpa_id: req.session.user.sherpa_id}, function (err, statusCode, associations) { if (err) { throw err; } if (statusCode === 200) { for (var i = 0; i < associations.length; i++) { if (associations[i].object_id) { userGroups.push(associations[i]); } else { sentry.captureMessage('Group ""' + associations[i].navn + '"" without Turbase ID!', { level: 'warning', extra: { user: req.session.user, group: associations[i] } }); } } req.userGroups = userGroups; next(); } else { sentry.captureMessage('Request to DNT API failed!', { extra: { statusCode: statusCode, errors: associations.errors } }); next(); } }); } else { // User is authenticated by other method than DNT Connect console.log('Not implemented.'); next(); } }; }; " Add status endpoint to admin server,"# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.conf.urls import patterns, include, url from django.conf.urls.static import static urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.ADMIN_ENABLED: # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns += patterns( '', url(r'^status/', include('status.urls', namespace='status')), url(r'^admin/', include(admin.site.urls)), url(r'^admin/reports/', include('reports.urls', namespace='reports')), ) if settings.BACKEND_ENABLED: urlpatterns += patterns( '', url(r'^status/', include('status.urls', namespace='status')), url(r'^checker/api/v1/', include('checker.urls', namespace='checker')), url(r'^call_centre/api/v1/', include('call_centre.urls', namespace='call_centre')), url(r'^cla_provider/api/v1/', include('cla_provider.urls', namespace='cla_provider')), url(r'^oauth2/', include('cla_auth.urls', namespace='oauth2')), ) if settings.DEBUG: urlpatterns += patterns( '', url(r'^means_test/api/v1/', include('means_test_api.urls', namespace='means_test')), ) ","# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.conf.urls import patterns, include, url from django.conf.urls.static import static urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.ADMIN_ENABLED: # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns += patterns( '', url(r'^admin/', include(admin.site.urls)), url(r'^admin/reports/', include('reports.urls', namespace='reports')), ) if settings.BACKEND_ENABLED: urlpatterns += patterns( '', url(r'^status/', include('status.urls', namespace='status')), url(r'^checker/api/v1/', include('checker.urls', namespace='checker')), url(r'^call_centre/api/v1/', include('call_centre.urls', namespace='call_centre')), url(r'^cla_provider/api/v1/', include('cla_provider.urls', namespace='cla_provider')), url(r'^oauth2/', include('cla_auth.urls', namespace='oauth2')), ) if settings.DEBUG: urlpatterns += patterns( '', url(r'^means_test/api/v1/', include('means_test_api.urls', namespace='means_test')), ) " Remove no-longer needed wagtail 2.0 warning,"from wagtail.admin.edit_handlers import FieldPanel from wagtailgeowidget.widgets import ( GeoField, ) from wagtailgeowidget.app_settings import ( GEO_WIDGET_ZOOM ) class GeoPanel(FieldPanel): def __init__(self, *args, **kwargs): self.classname = kwargs.pop('classname', """") self.address_field = kwargs.pop('address_field', """") self.hide_latlng = kwargs.pop('hide_latlng', False) self.zoom = kwargs.pop('zoom', GEO_WIDGET_ZOOM) super().__init__(*args, **kwargs) def widget_overrides(self): field = self.model._meta.get_field(self.field_name) srid = getattr(field, 'srid', 4326) return { self.field_name: GeoField( address_field=self.address_field, hide_latlng=self.hide_latlng, zoom=self.zoom, srid=srid, id_prefix='id_', used_in='GeoPanel', ) } def clone(self): return self.__class__( field_name=self.field_name, classname=self.classname, address_field=self.address_field, hide_latlng=self.hide_latlng, zoom=self.zoom, ) ","import warnings import wagtail if wagtail.VERSION < (2, 0): warnings.warn(""GeoPanel only works in Wagtail 2+"", Warning) # NOQA warnings.warn(""Please import GeoPanel from wagtailgeowidget.legacy_edit_handlers instead"", Warning) # NOQA warnings.warn(""All support for Wagtail 1.13 and below will be droppen in April 2018"", Warning) # NOQA from wagtail.admin.edit_handlers import FieldPanel from wagtailgeowidget.widgets import ( GeoField, ) from wagtailgeowidget.app_settings import ( GEO_WIDGET_ZOOM ) class GeoPanel(FieldPanel): def __init__(self, *args, **kwargs): self.classname = kwargs.pop('classname', """") self.address_field = kwargs.pop('address_field', """") self.hide_latlng = kwargs.pop('hide_latlng', False) self.zoom = kwargs.pop('zoom', GEO_WIDGET_ZOOM) super().__init__(*args, **kwargs) def widget_overrides(self): field = self.model._meta.get_field(self.field_name) srid = getattr(field, 'srid', 4326) return { self.field_name: GeoField( address_field=self.address_field, hide_latlng=self.hide_latlng, zoom=self.zoom, srid=srid, id_prefix='id_', ) } def clone(self): return self.__class__( field_name=self.field_name, classname=self.classname, address_field=self.address_field, hide_latlng=self.hide_latlng, zoom=self.zoom, ) " "Make ""children"" an optional prop Fixes #5","import React, { Component, PropTypes } from 'react'; import Truncate from 'react-truncate'; class ShowMore extends Component { static defaultProps = { lines: 3, more: 'Show more', less: 'Show less', anchorClass: '' } static propTypes = { children: PropTypes.node, lines: PropTypes.number, more: PropTypes.node, less: PropTypes.node, anchorClass: PropTypes.string } state = { expanded: false, truncated: false } handleTruncate = truncated => { if (truncated !== this.state.truncated) { this.setState({ truncated }); } } toggleLines = event => { event.preventDefault(); this.setState({ expanded: !this.state.expanded }); } render() { const { children, more, less, lines, anchorClass } = this.props; const { expanded, truncated } = this.state; return ( <div> <Truncate lines={!expanded && lines} ellipsis={( <span>... <a href='#' className={anchorClass} onClick={this.toggleLines}>{more}</a></span> )} onTruncate={this.handleTruncate} > {children} </Truncate> {!truncated && expanded && ( <span> <a href='#' className={anchorClass} onClick={this.toggleLines}>{less}</a></span> )} </div> ); } } export default ShowMore; ","import React, { Component, PropTypes } from 'react'; import Truncate from 'react-truncate'; class ShowMore extends Component { static defaultProps = { lines: 3, more: 'Show more', less: 'Show less', anchorClass: '' } static propTypes = { children: PropTypes.node.isRequired, lines: PropTypes.number, more: PropTypes.node, less: PropTypes.node, anchorClass: PropTypes.string } state = { expanded: false, truncated: false } handleTruncate = truncated => { if (truncated !== this.state.truncated) { this.setState({ truncated }); } } toggleLines = event => { event.preventDefault(); this.setState({ expanded: !this.state.expanded }); } render() { const { children, more, less, lines, anchorClass } = this.props; const { expanded, truncated } = this.state; return ( <div> <Truncate lines={!expanded && lines} ellipsis={( <span>... <a href='#' className={anchorClass} onClick={this.toggleLines}>{more}</a></span> )} onTruncate={this.handleTruncate} > {children} </Truncate> {!truncated && expanded && ( <span> <a href='#' className={anchorClass} onClick={this.toggleLines}>{less}</a></span> )} </div> ); } } export default ShowMore; " Add chooseMostRecentDate helper and use it,"<?php namespace Northstar\Merge; use Northstar\Exceptions\NorthstarValidationException; class Merger { public function merge($field, $target, $duplicate) { $mergeMethod = 'merge'.studly_case($field); if (! method_exists($this, $mergeMethod)) { throw new NorthstarValidationException(['Unable to merge '.$field.' field. No merge instructions found.'], ['target' => $target, 'duplicate' => $duplicate]); } return $this->{$mergeMethod}($target, $duplicate); } public function mergeLastAuthenticatedAt($target, $duplicate) { return $this->chooseMostRecentDate('last_authenticated_at', $target, $duplicate); } public function mergeLastMessagedAt($target, $duplicate) { return $this->chooseMostRecentDate('last_messaged_at', $target, $duplicate); } public function mergeLastAccessedAt($target, $duplicate) { return $this->chooseMostRecentDate('last_accessed_at', $target, $duplicate); } public function mergeLanguage($target, $duplicate) { if ($target->last_accessed_at > $duplicate->last_accessed_at) { return $target->language; } return $duplicate->language; } public function chooseMostRecentDate($field, $target, $duplicate) { $targetValue = $target->{$field}; $duplicateValue = $duplicate->{$field}; return $targetValue > $duplicateValue ? $targetValue : $duplicateValue; } } ","<?php namespace Northstar\Merge; use Northstar\Exceptions\NorthstarValidationException; class Merger { public function merge($field, $target, $duplicate) { $mergeMethod = 'merge'.studly_case($field); if (! method_exists($this, $mergeMethod)) { throw new NorthstarValidationException(['Unable to merge '.$field.' field. No merge instructions found.'], ['target' => $target, 'duplicate' => $duplicate]); } return $this->{$mergeMethod}($target, $duplicate); } public function mergeLastAuthenticatedAt($target, $duplicate) { $targetValue = $target->last_authenticated_at; $duplicateValue = $duplicate->last_authenticated_at; return $targetValue > $duplicateValue ? $targetValue : $duplicateValue; } public function mergeLastMessagedAt($target, $duplicate) { $targetValue = $target->last_messaged_at; $duplicateValue = $duplicate->last_messaged_at; return $targetValue > $duplicateValue ? $targetValue : $duplicateValue; } public function mergeLastAccessedAt($target, $duplicate) { $targetValue = $target->last_accessed_at; $duplicateValue = $duplicate->last_accessed_at; return $targetValue > $duplicateValue ? $targetValue : $duplicateValue; } public function mergeLanguage($target, $duplicate) { if ($target->last_accessed_at > $duplicate->last_accessed_at) { return $target->language; } return $duplicate->language; } } " Remove reference to validate. Added verbose flag,"'use strict'; const glob = require('glob-all'); const fs = require('fs'); const mime = require('mime-types'); const globOpts = { nodir: true }; class Assets { constructor (serverless, options) { this.serverless = serverless; this.options = options; this.provider = this.serverless.getProvider('aws'); this.commands = { s3deploy: { lifecycleEvents: [ 'deploy' ], options: { verbose: { usage: ""Increase verbosity"", shortcut: 'v' } } } }; this.hooks = { 's3deploy:deploy': () => new Promise.resolve().then(this.deployS3.bind(this)) }; } deployS3() { const service = this.serverless.service; const config = service.custom.assets; // glob config.files.forEach((opt) => { let cfg = Object.assign({}, globOpts, {cwd: opt.source}); glob.sync(opt.globs, cfg).forEach((fn) => { const body = fs.readFileSync(opt.source + fn) const type = mime.lookup(fn); (!!this.options.verbose) && this.serverless.cli.log(""File: "", fn, type) this.provider.request('S3', 'putObject', { ACL: config.acl || 'public-read', Body: body, Bucket: config.bucket, Key: fn, ContentType: type }, this.options.stage, this.options.region); }); }); } } module.exports = Assets; ","'use strict'; const glob = require('glob-all'); const fs = require('fs'); const mime = require('mime-types'); const globOpts = { nodir: true }; class Assets { constructor (serverless, options) { this.serverless = serverless; this.options = options; this.provider = this.serverless.getProvider('aws'); Object.assign(this, validate) this.commands = { s3deploy: { lifecycleEvents: [ 'deploy' ] } }; this.hooks = { 's3deploy:deploy': () => new Promise.resolve() .then(this.deployS3.bind(this)) }; } deployS3() { const service = this.serverless.service; const config = service.custom.assets; // glob config.files.forEach((opt) => { let cfg = Object.assign({}, globOpts, {cwd: opt.source}); glob.sync(opt.globs, cfg).forEach((fn) => { const body = fs.readFileSync(opt.source + fn) const type = mime.lookup(fn); console.log(""File: "", fn, type) this.provider.request('S3', 'putObject', { ACL: config.acl || 'public-read', Body: body, Bucket: config.bucket, Key: fn, ContentType: type }, this.options.stage, this.options.region); }); }); } } module.exports = Assets; " Use synchronized block for getInstance,"package net.qbar.common.card; import java.util.Map; import com.google.common.collect.Maps; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; public class PunchedCardDataManager { private static volatile PunchedCardDataManager instance; public static PunchedCardDataManager getInstance() { if (instance == null) { synchronized (PunchedCardDataManager.class) { if (instance == null) { instance = new PunchedCardDataManager(); } } } return instance; } private Map<Short, PunchedCardData> datas; private PunchedCardDataManager() { datas = Maps.newHashMap(); } public PunchedCardData registerDataType(int id, IPunchedCard data) { if (this.datas.containsKey(id)) throw new IllegalArgumentException(""id already used""); PunchedCardData card = new PunchedCardData(id, data); this.datas.put(card.getId(), card); return card; } public PunchedCardData getCardData(ItemStack card) { NBTTagCompound tag = card.getTagCompound(); if (!tag.hasKey(""PunchedCardDataId"")) throw new IllegalArgumentException(""Invalid ItemStack""); short id = tag.getShort(""PunchedCardDataId""); if (!this.datas.containsKey(id)) throw new IllegalArgumentException(""No data found""); return this.datas.get(id); } } ","package net.qbar.common.card; import java.util.Map; import com.google.common.collect.Maps; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; public class PunchedCardDataManager { private static PunchedCardDataManager instance; public static PunchedCardDataManager getInstance() { if (instance == null) instance = new PunchedCardDataManager(); return instance; } private Map<Short, PunchedCardData> datas; private PunchedCardDataManager() { datas = Maps.newHashMap(); } public PunchedCardData registerDataType(int id, IPunchedCard data) { if (this.datas.containsKey(id)) throw new IllegalArgumentException(""id already used""); PunchedCardData card = new PunchedCardData(id, data); this.datas.put(card.getId(), card); return card; } public PunchedCardData getCardData(ItemStack card) { NBTTagCompound tag = card.getTagCompound(); if (!tag.hasKey(""PunchedCardDataId"")) throw new IllegalArgumentException(""Invalid ItemStack""); short id = tag.getShort(""PunchedCardDataId""); if (!this.datas.containsKey(id)) throw new IllegalArgumentException(""No data found""); return this.datas.get(id); } } " Fix recent changes page not working,"{{-- Copyright 2015-2017 ppy Pty. Ltd. This file is part of osu!web. osu!web is distributed with the hope of attracting more community contributions to the core ecosystem of osu!. osu!web is free software: you can redistribute it and/or modify it under the terms of the Affero GNU General Public License version 3 as published by the Free Software Foundation.i osu!web is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with osu!web. If not, see <http://www.gnu.org/licenses/>. --}} <a class="" changelog-stream {{ $featured ? 'changelog-stream--featured' : '' }} {{ $build !== null && $build->version === $stream->version ? 'changelog-stream--active' : '' }} changelog-stream--{{ str_slug($stream->updateStream->pretty_name) }} "" href={{ route('changelog', ['build' => $stream->version]) }} > <div class=""changelog-stream__content""> <span class=""changelog-stream__name"">{{ $stream->updateStream->pretty_name }}</span> <span class=""changelog-stream__build"">{{ $stream->version }}</span> <span class=""changelog-stream__users"">{{ trans_choice('changelog.users-online', $stream->users, ['users' => $stream->users]) }}</span> </div> <div class=""changelog-stream__indicator""></div> </a> ","{{-- Copyright 2015-2017 ppy Pty. Ltd. This file is part of osu!web. osu!web is distributed with the hope of attracting more community contributions to the core ecosystem of osu!. osu!web is free software: you can redistribute it and/or modify it under the terms of the Affero GNU General Public License version 3 as published by the Free Software Foundation.i osu!web is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with osu!web. If not, see <http://www.gnu.org/licenses/>. --}} <a class="" changelog-stream {{ $featured ? 'changelog-stream--featured' : '' }} {{ $build->version === $stream->version ? 'changelog-stream--active' : '' }} changelog-stream--{{ str_slug($stream->updateStream->pretty_name) }} "" href={{ route('changelog', ['build' => $stream->version]) }} > <div class=""changelog-stream__content""> <span class=""changelog-stream__name"">{{ $stream->updateStream->pretty_name }}</span> <span class=""changelog-stream__build"">{{ $stream->version }}</span> <span class=""changelog-stream__users"">{{ trans_choice('changelog.users-online', $stream->users, ['users' => $stream->users]) }}</span> </div> <div class=""changelog-stream__indicator""></div> </a> " Fix buglet in compact testing,"""""""Tests for the PythonPoint tool. """""" import os, sys, string from reportlab.test import unittest from reportlab.test.utils import makeSuiteForClasses, outputfile import reportlab class PythonPointTestCase(unittest.TestCase): ""Some very crude tests on PythonPoint."" def test0(self): ""Test if pythonpoint.pdf can be created from pythonpoint.xml."" join, dirname, isfile, abspath = os.path.join, os.path.dirname, os.path.isfile, os.path.abspath rlDir = abspath(dirname(reportlab.__file__)) from reportlab.tools.pythonpoint import pythonpoint from reportlab.lib.utils import isCompactDistro, open_for_read ppDir = dirname(pythonpoint.__file__) xml = join(ppDir, 'demos', 'pythonpoint.xml') datafilename = 'pythonpoint.pdf' outDir = outputfile('') if isCompactDistro(): cwd = None xml = open_for_read(xml) else: cwd = os.getcwd() os.chdir(join(ppDir, 'demos')) pdf = join(outDir, datafilename) if isfile(pdf): os.remove(pdf) pythonpoint.process(xml, outDir=outDir, verbose=0, datafilename=datafilename) if cwd: os.chdir(cwd) assert os.path.exists(pdf) def makeSuite(): return makeSuiteForClasses(PythonPointTestCase) #noruntests if __name__ == ""__main__"": unittest.TextTestRunner().run(makeSuite()) ","""""""Tests for the PythonPoint tool. """""" import os, sys, string from reportlab.test import unittest from reportlab.test.utils import makeSuiteForClasses, outputfile import reportlab class PythonPointTestCase(unittest.TestCase): ""Some very crude tests on PythonPoint."" def test0(self): ""Test if pythonpoint.pdf can be created from pythonpoint.xml."" join, dirname, isfile, abspath = os.path.join, os.path.dirname, os.path.isfile, os.path.abspath rlDir = abspath(dirname(reportlab.__file__)) from reportlab.tools.pythonpoint import pythonpoint from reportlab.lib.utils import isCompactDistro, open_for_read ppDir = dirname(pythonpoint.__file__) xml = join(ppDir, 'demos', 'pythonpoint.xml') datafilename = 'pythonpoint.pdf' outdir = outputfile('') if isCompactDistro(): cwd = None xml = open_for_read(xml) else: outDir = join(rlDir, 'test') cwd = os.getcwd() os.chdir(join(ppDir, 'demos')) pdf = join(outDir, datafilename) if isfile(pdf): os.remove(pdf) pythonpoint.process(xml, outDir=outDir, verbose=0, datafilename=datafilename) if cwd: os.chdir(cwd) assert os.path.exists(pdf) os.remove(pdf) def makeSuite(): return makeSuiteForClasses(PythonPointTestCase) #noruntests if __name__ == ""__main__"": unittest.TextTestRunner().run(makeSuite()) " Use subheaders in member list,"import { List } from 'material-ui/List'; import Subheader from 'material-ui/Subheader'; import React from 'react'; import { Link } from 'react-router'; import MemberItem from './MemberItem'; export default class GroupItem extends React.Component { static propTypes = { id: React.PropTypes.string, isAdmin: React.PropTypes.bool, isMember: React.PropTypes.bool, name: React.PropTypes.string, members: React.PropTypes.array, } renderHeader() { if (this.props.isAdmin) { return <Subheader style={{ textTransform: 'uppercase' }}><Link to={`/group/${this.props.id}`}>{this.props.name}</Link></Subheader>; } return <Subheader style={{ textTransform: 'uppercase' }}>{this.props.name}</Subheader>; } render() { const members = this.props.members.filter(member => member.user); if (!members.length) { return null; } return ( <List> {this.renderHeader()} {members.sort((a, b) => a.user.name > b.user.name).map(member => <MemberItem key={member.id} isMember={this.props.isMember} {...member} />)} </List> ); } } ","import { List } from 'material-ui/List'; import React from 'react'; import { Link } from 'react-router'; import MemberItem from './MemberItem'; export default class GroupItem extends React.Component { static propTypes = { id: React.PropTypes.string, isAdmin: React.PropTypes.bool, isMember: React.PropTypes.bool, name: React.PropTypes.string, members: React.PropTypes.array, } renderHeader() { if (this.props.isAdmin) { return <h2><Link to={`/group/${this.props.id}`}>{this.props.name}</Link></h2>; } return <h2>{this.props.name}</h2>; } render() { const members = this.props.members.filter(member => member.user); if (!members.length) { return null; } return ( <List> {this.renderHeader()} {members.sort((a, b) => a.user.name > b.user.name).map(member => <MemberItem key={member.id} isMember={this.props.isMember} {...member} />)} </List> ); } } " Change identifier of user id by return of method getAuthIdentifier(),"<?php namespace Laravel\Passport\Bridge; use RuntimeException; use Illuminate\Contracts\Hashing\Hasher; use League\OAuth2\Server\Entities\ClientEntityInterface; use League\OAuth2\Server\Repositories\UserRepositoryInterface; class UserRepository implements UserRepositoryInterface { /** * The hasher implementation. * * @var \Illuminate\Contracts\Hashing\Hasher */ protected $hasher; /** * Create a new repository instance. * * @param \Illuminate\Contracts\Hashing\Hasher $hasher * @return void */ public function __construct(Hasher $hasher) { $this->hasher = $hasher; } /** * {@inheritdoc} */ public function getUserEntityByUserCredentials($username, $password, $grantType, ClientEntityInterface $clientEntity) { if (is_null($model = config('auth.providers.users.model'))) { throw new RuntimeException('Unable to determine user model from configuration.'); } if (method_exists($model, 'findForPassport')) { $user = (new $model)->findForPassport($username); } else { $user = (new $model)->where('email', $username)->first(); } if (! $user || ! $this->hasher->check($password, $user->password)) { return; } return new User($user->getAuthIdentifier()); } } ","<?php namespace Laravel\Passport\Bridge; use RuntimeException; use Illuminate\Contracts\Hashing\Hasher; use League\OAuth2\Server\Entities\ClientEntityInterface; use League\OAuth2\Server\Repositories\UserRepositoryInterface; class UserRepository implements UserRepositoryInterface { /** * The hasher implementation. * * @var \Illuminate\Contracts\Hashing\Hasher */ protected $hasher; /** * Create a new repository instance. * * @param \Illuminate\Contracts\Hashing\Hasher $hasher * @return void */ public function __construct(Hasher $hasher) { $this->hasher = $hasher; } /** * {@inheritdoc} */ public function getUserEntityByUserCredentials($username, $password, $grantType, ClientEntityInterface $clientEntity) { if (is_null($model = config('auth.providers.users.model'))) { throw new RuntimeException('Unable to determine user model from configuration.'); } if (method_exists($model, 'findForPassport')) { $user = (new $model)->findForPassport($username); } else { $user = (new $model)->where('email', $username)->first(); } if (! $user || ! $this->hasher->check($password, $user->password)) { return; } return new User($user->id); } } " Address TODO comments in code,"import versioneer try: from setuptools import setup except ImportError as err: print(""Missing Python module requirement: setuptools."") raise err setup( name='tabpy-server', version=versioneer.get_version(), description='Web server Tableau uses to run Python scripts.', url='https://github.com/tableau/TabPy', author='Tableau', author_email='github@tableau.com', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Programming Language :: Python :: 3.5', ""Topic :: Scientific/Engineering"", ""Topic :: Scientific/Engineering :: Information Analysis"", ], packages=['tabpy_server', 'tabpy_server.common', 'tabpy_server.management', 'tabpy_server.psws', 'tabpy_server.static'], package_data={'tabpy_server.static': ['*.*'], 'tabpy_server': ['startup.*', 'state.ini']}, license='MIT', install_requires=[ 'backports_abc', 'cloudpickle', 'configparser', 'decorator', 'future', 'futures', 'genson', 'jsonschema>=2.3.0', 'mock', 'numpy', 'python-dateutil', 'pyOpenSSL', 'requests', 'singledispatch', 'simplejson', 'tornado==5.1.1', 'Tornado-JSON' ], cmdclass=versioneer.get_cmdclass(), ) ","import versioneer try: from setuptools import setup except ImportError as err: print(""Missing Python module requirement: setuptools."") raise err setup( name='tabpy-server', version=versioneer.get_version(), description='Web server Tableau uses to run Python scripts.', url='https://github.com/tableau/TabPy', author='Tableau', author_email='github@tableau.com', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Programming Language :: Python :: 3.5', ""Topic :: Scientific/Engineering"", ""Topic :: Scientific/Engineering :: Information Analysis"", ], packages=['tabpy_server', 'tabpy_server.common', 'tabpy_server.management', 'tabpy_server.psws', 'tabpy_server.static'], package_data={'tabpy_server.static': ['*.*'], 'tabpy_server': ['startup.*', 'state.ini']}, license='MIT', # TODO Add tabpy_tools dependency when published on github install_requires=[ 'backports_abc', 'cloudpickle', 'configparser', 'decorator', 'future', 'futures', 'genson', 'jsonschema>=2.3.0', 'mock', 'numpy', 'python-dateutil', 'pyOpenSSL', 'requests', 'singledispatch', 'simplejson', 'tornado==5.1.1', 'Tornado-JSON' ], cmdclass=versioneer.get_cmdclass(), ) " Remove compatibility tag for Python 2.6,"from setuptools import setup if __name__ == ""__main__"": with open('README.rst', 'r') as f: long_description = f.read() setup( classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], description=""werkzeug + twisted.web"", long_description=long_description, setup_requires=[""incremental""], use_incremental=True, install_requires=[ ""six"", ""Twisted>=13.2"", ""werkzeug"", ""incremental"", ], keywords=""twisted flask werkzeug web"", license=""MIT"", name=""klein"", packages=[""klein"", ""klein.test""], package_dir={"""": ""src""}, url=""https://github.com/twisted/klein"", maintainer='Amber Brown (HawkOwl)', maintainer_email='hawkowl@twistedmatrix.com', ) ","from setuptools import setup if __name__ == ""__main__"": with open('README.rst', 'r') as f: long_description = f.read() setup( classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], description=""werkzeug + twisted.web"", long_description=long_description, setup_requires=[""incremental""], use_incremental=True, install_requires=[ ""six"", ""Twisted>=13.2"", ""werkzeug"", ""incremental"", ], keywords=""twisted flask werkzeug web"", license=""MIT"", name=""klein"", packages=[""klein"", ""klein.test""], package_dir={"""": ""src""}, url=""https://github.com/twisted/klein"", maintainer='Amber Brown (HawkOwl)', maintainer_email='hawkowl@twistedmatrix.com', ) " Use default PK field name for Asset form field,"from django.core import validators from django.db.models import get_model from django.forms.fields import MultiValueField, CharField, IntegerField from .widgets import AssetWidget class AssetField(MultiValueField): _delimiter = ':' widget = AssetWidget pk_field_name = 'id' default_fields = { 'asset_pk': IntegerField, 'asset_type': CharField, } def __init__(self, *args, **kwargs): kwargs.pop('queryset', None) self.pk_field_name = kwargs.pop('to_field_name', self.pk_field_name) fields = ( self.default_fields['asset_pk'](), self.default_fields['asset_type'](), ) super(AssetField, self).__init__(fields, *args, **kwargs) def prepare_value(self, value): return super(AssetField, self).prepare_value(value) def to_python(self, value): if value in validators.EMPTY_VALUES: return None asset_pk, asset_type = value model = get_model('assets', asset_type) filters = { self.pk_field_name: value[0] } try: return model.objects.get(**filters) except model.DoesNotExist: return None def compress(self, data_list): return self.to_python(data_list) ","from django.core import validators from django.db.models import get_model from django.forms.fields import MultiValueField, CharField, IntegerField from .widgets import AssetWidget class AssetField(MultiValueField): _delimiter = ':' widget = AssetWidget default_fields = { 'asset_pk': IntegerField, 'asset_type': CharField, } def __init__(self, *args, **kwargs): kwargs.pop('queryset', None) self.pk_field_name = kwargs.pop('to_field_name') fields = ( self.default_fields['asset_pk'](), self.default_fields['asset_type'](), ) super(AssetField, self).__init__(fields, *args, **kwargs) def prepare_value(self, value): return super(AssetField, self).prepare_value(value) def to_python(self, value): if value in validators.EMPTY_VALUES: return None asset_pk, asset_type = value model = get_model('assets', asset_type) filters = { self.pk_field_name: value[0] } try: return model.objects.get(**filters) except model.DoesNotExist: return None def compress(self, data_list): return self.to_python(data_list) " "Fix recent migration for SQLite BadMethodCallException: SQLite doesn't support multiple calls to dropColumn / renameColumn in a single modification.","<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class MatchPageAndArticleSchema extends Migration { private $tables = [ 'generic_pages', 'press_releases', 'research_guides', 'educator_resources', 'digital_catalogs', 'printed_catalogs', ]; public function up() { foreach( $this->tables as $tableName ) { Schema::table($tableName, function (Blueprint $table) { $table->dropColumn('image_url'); $table->string('imgix_uuid')->nullable()->after('text'); }); Schema::table($tableName, function (Blueprint $table) { $table->renameColumn('text', 'copy'); }); } } public function down() { foreach( $this->tables as $tableName ) { Schema::table($tableName, function (Blueprint $table) { $table->dropColumn('imgix_uuid'); $table->string('image_url')->nullable()->after('copy'); }); Schema::table($tableName, function (Blueprint $table) { $table->renameColumn('copy', 'text'); }); } } } ","<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class MatchPageAndArticleSchema extends Migration { private $tables = [ 'generic_pages', 'press_releases', 'research_guides', 'educator_resources', 'digital_catalogs', 'printed_catalogs', ]; public function up() { foreach( $this->tables as $tableName ) { Schema::table($tableName, function (Blueprint $table) { $table->dropColumn('image_url'); $table->string('imgix_uuid')->nullable()->after('text'); $table->renameColumn('text', 'copy'); }); } } public function down() { foreach( $this->tables as $tableName ) { Schema::table($tableName, function (Blueprint $table) { $table->dropColumn('imgix_uuid'); $table->string('image_url')->nullable()->after('copy'); $table->renameColumn('copy', 'text'); }); } } } " Set CF_STACK environment variable in compile tests,"import os from build_pack_utils import BuildPack from common.integration import DirectoryHelper from common.integration import OptionsHelper class BaseCompileApp(object): def setUp(self): self.dh = DirectoryHelper() (self.build_dir, self.cache_dir, self.temp_dir) = self.dh.create_bp_env(self.app_name) self.bp = BuildPack({ 'BUILD_DIR': self.build_dir, 'CACHE_DIR': self.cache_dir, 'TMPDIR': self.temp_dir }, '.') if 'BP_DEBUG' in os.environ.keys(): self.bp._ctx['BP_DEBUG'] = True self.dh.copy_build_pack_to(self.bp.bp_dir) self.dh.register_to_delete(self.bp.bp_dir) self.opts = OptionsHelper(os.path.join(self.bp.bp_dir, 'defaults', 'options.json')) self.opts.set_download_url( 'http://localhost:5000/binaries/{STACK}') os.environ[""CF_STACK""] = ""cflinuxfs2"" def tearDown(self): self.dh.cleanup() del os.environ[""CF_STACK""] ","import os from build_pack_utils import BuildPack from common.integration import DirectoryHelper from common.integration import OptionsHelper class BaseCompileApp(object): def setUp(self): self.dh = DirectoryHelper() (self.build_dir, self.cache_dir, self.temp_dir) = self.dh.create_bp_env(self.app_name) self.bp = BuildPack({ 'BUILD_DIR': self.build_dir, 'CACHE_DIR': self.cache_dir, 'TMPDIR': self.temp_dir }, '.') if 'BP_DEBUG' in os.environ.keys(): self.bp._ctx['BP_DEBUG'] = True self.dh.copy_build_pack_to(self.bp.bp_dir) self.dh.register_to_delete(self.bp.bp_dir) self.opts = OptionsHelper(os.path.join(self.bp.bp_dir, 'defaults', 'options.json')) self.opts.set_download_url( 'http://localhost:5000/binaries/{STACK}') def tearDown(self): self.dh.cleanup() " Fix genre background image URI,"import React from 'react'; import { Tab } from 'semantic-ui-react'; import Img from 'react-image-smooth-loading'; import genreToIcon from './mapGenres'; import styles from './styles.scss'; const bannedGenres = [ 'seen live' ]; class GenresTab extends React.Component { constructor(props) { super(props); } onGenreClick (genreName) { this.props.history.push('/tag/' + genreName); } render () { let { genres } = this.props; return ( <Tab.Pane attached={false}> <div className={styles.genre_tab_container}> { typeof genres !== 'undefined' ? _.filter(genres, genre => !_.includes(bannedGenres, genre.name)).map((tag, i) => { return ( <div className={styles.genre_container} key={i} onClick={() => this.onGenreClick(tag.name)} > <div className={styles.genre_overlay}> <Img src={'https://picsum.photos/256?random=' + i} /> </div> <div className={styles.genre_name}> <div className={styles.svg_icon} dangerouslySetInnerHTML={{ __html: genreToIcon(tag.name) }} /> { tag.name } </div> </div> ); }) : null } </div> </Tab.Pane> ); } } export default GenresTab; ","import React from 'react'; import { Tab } from 'semantic-ui-react'; import Img from 'react-image-smooth-loading'; import genreToIcon from './mapGenres'; import styles from './styles.scss'; const bannedGenres = [ 'seen live' ]; class GenresTab extends React.Component { constructor(props) { super(props); } onGenreClick (genreName) { this.props.history.push('/tag/' + genreName); } render () { let { genres } = this.props; return ( <Tab.Pane attached={false}> <div className={styles.genre_tab_container}> { typeof genres !== 'undefined' ? _.filter(genres, genre => !_.includes(bannedGenres, genre.name)).map((tag, i) => { return ( <div className={styles.genre_container} key={i} onClick={() => this.onGenreClick(tag.name)} > <div className={styles.genre_overlay}> <Img src={'https://picsum.photos/256x256/?random&seed=' + i} /> </div> <div className={styles.genre_name}> <div className={styles.svg_icon} dangerouslySetInnerHTML={{ __html: genreToIcon(tag.name) }} /> { tag.name } </div> </div> ); }) : null } </div> </Tab.Pane> ); } } export default GenresTab; " "Add additional processing on text type modifiers - minLength cannot be higher than maxLength - minLength, maxLength and length cannot be negative - minLength defaults to 0","<?php namespace Good\Rolemodel\Schema; use Good\Rolemodel\SchemaVisitor; class TextMember extends PrimitiveMember { public function acceptSchemaVisitor(SchemaVisitor $visitor) { // visit this, there are no children to pass visitor on to $visitor->visitTextMember($this); } function getValidParameterTypeModifiers() { return array('minLength', 'maxLength', 'length');; } function getValidNonParameterTypeModifiers() { return array(); } function processTypeModifiers(array $typeModifiers) { if (array_key_exists('length', $typeModifiers)) { if (array_key_exists('minLength', $typeModifiers) || array_key_exists('maxLength', $typeModifiers)) { throw new \Exception(""The 'length' type modifier cannot be defined alongside 'minLength' or 'maxLength'.""); } if ($typeModifiers['length'] < 0) { throw new \Exception(""The length for a text must be positive""); } $typeModifiers['minLength'] = $typeModifiers['length']; $typeModifiers['maxLength'] = $typeModifiers['length']; unset($typeModifiers['length']); } if (array_key_exists('minLength', $typeModifiers) && array_key_exists('maxLength', $typeModifiers) && $typeModifiers['minLength'] > $typeModifiers['maxLength']) { throw new \Exception(""The minLength for a text cannot be higher than its maxLength""); } if ((array_key_exists('minLength', $typeModifiers) && $typeModifiers['minLength'] < 0) || (array_key_exists('maxLength', $typeModifiers) && $typeModifiers['maxLength'] < 0)) { throw new \Exception(""The minLength and maxLength for a text must be positive""); } return $typeModifiers; } function getDefaultTypeModifierValues() { return array('minLength' => 0); } } ?>","<?php namespace Good\Rolemodel\Schema; use Good\Rolemodel\SchemaVisitor; class TextMember extends PrimitiveMember { public function acceptSchemaVisitor(SchemaVisitor $visitor) { // visit this, there are no children to pass visitor on to $visitor->visitTextMember($this); } function getValidParameterTypeModifiers() { return array('minLength', 'maxLength', 'length');; } function getValidNonParameterTypeModifiers() { return array(); } function processTypeModifiers(array $typeModifiers) { if (array_key_exists('length', $typeModifiers)) { if (array_key_exists('minLength', $typeModifiers) || array_key_exists('maxLength', $typeModifiers)) { throw new \Exception(""The 'length' type modifier cannot be defined alongside 'minLength' or 'maxLength'.""); } $typeModifiers['minLength'] = $typeModifiers['length']; $typeModifiers['maxLength'] = $typeModifiers['length']; unset($typeModifiers['length']); } return $typeModifiers; } function getDefaultTypeModifierValues() { return array(); } } ?>" Fix issue list after change of authentication package,"Geolocation.latLng() Template.newIssue.events({ 'submit form': function(){ event.preventDefault(); var title = event.target.title.value; var description = event.target.description.value; var imageURL = Session.get('imageURL'); console.log(title, description); if (title && description && Geolocation.latLng()) { Issues.insert({ title: title, description: description, status: 'open', lat: Geolocation.latLng().lat, lng: Geolocation.latLng().lng, userID: Meteor.userId(), imageURL: imageURL, createdAt: new Date(), lastModified: new Date() }); Router.go('/issues-list'); } else { console.log(""form not valid""); } } }); Template.IssuesList.helpers({ title: function(){ return ""Status of Submitted"" }, issues: function (){ // Show newest tasks at the top return Issues.find({'userID': Meteor.userId()}, {sort: {createdAt: 1}}) } }); Template.task.helpers({ label_mapper: function(par){ var dict = {}; //Updates labels for submitted issues dict[""open""] = ""-warning""; dict[""rejected""] = ""-danger""; dict[""solved""] = ""-success""; dict[""pending""] = ""-info"" return dict[par] } });","Geolocation.latLng() Template.newIssue.events({ 'submit form': function(){ event.preventDefault(); var title = event.target.title.value; var description = event.target.description.value; var imageURL = Session.get('imageURL'); console.log(title, description); if (title && description && Geolocation.latLng()) { Issues.insert({ title: title, description: description, status: 'open', lat: Geolocation.latLng().lat, lng: Geolocation.latLng().lng, userID: Meteor.userId(), imageURL: imageURL, createdAt: new Date(), lastModified: new Date() }); Router.go('/issues-list'); } else { console.log(""form not valid""); } } }); Template.dashboard.helpers({ title: function(){ return ""Status of Submitted"" }, issues: function (){ // Show newest tasks at the top return Issues.find({'userID': this.userId}, {sort: {createdAt: 1}}) } }); Template.task.helpers({ label_mapper: function(par){ var dict = {}; //Updates labels for submitted issues dict[""open""] = ""-warning""; dict[""rejected""] = ""-danger""; dict[""solved""] = ""-success""; dict[""pending""] = ""-info"" return dict[par] } });" Update dendro tests and specify no periodic boundaries to be consistent w/ previous unit testing,"# Licensed under an MIT open source license - see LICENSE ''' Tests for Dendrogram statistics ''' import numpy as np import numpy.testing as npt from ..statistics import Dendrogram_Stats, DendroDistance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances min_deltas = np.logspace(-1.5, 0.5, 40) def test_DendroStat(): tester = Dendrogram_Stats(dataset1[""cube""], min_deltas=min_deltas) tester.run(periodic_bounds=False) npt.assert_allclose(tester.numfeatures, computed_data[""dendrogram_val""]) def test_DendroDistance(): tester_dist = \ DendroDistance(dataset1[""cube""], dataset2[""cube""], min_deltas=min_deltas, periodic_bounds=False).distance_metric() npt.assert_almost_equal(tester_dist.histogram_distance, computed_distances[""dendrohist_distance""]) npt.assert_almost_equal(tester_dist.num_distance, computed_distances[""dendronum_distance""]) ","# Licensed under an MIT open source license - see LICENSE ''' Tests for Dendrogram statistics ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import Dendrogram_Stats, DendroDistance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances class testDendrograms(TestCase): def setUp(self): self.min_deltas = np.logspace(-1.5, 0.5, 40) def test_DendroStat(self): self.tester = Dendrogram_Stats(dataset1[""cube""], min_deltas=self.min_deltas) self.tester.run() npt.assert_allclose(self.tester.numfeatures, computed_data[""dendrogram_val""]) def test_DendroDistance(self): self.tester_dist = \ DendroDistance(dataset1[""cube""], dataset2[""cube""], min_deltas=self.min_deltas).distance_metric() npt.assert_almost_equal(self.tester_dist.histogram_distance, computed_distances[""dendrohist_distance""]) npt.assert_almost_equal(self.tester_dist.num_distance, computed_distances[""dendronum_distance""]) " Fix wrong import of logger,"# Django settings for vpr project. from base import * DEBUG = True DEVELOPMENT = True TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { #'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. #'NAME': 'vpr.sqlite3', # Or path to database file if using sqlite3. 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'vpr_dev', # Or path to database file if using sqlite3. 'USER': 'vpr', # Not used with sqlite3. 'PASSWORD': 'vpr', # Not used with sqlite3. 'HOST': 'localhost', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '3306', # Set to empty string for default. Not used with sqlite3. } } # Make this unique, and don't share it with anybody. #SECRET_KEY = 'kw7#s$8t&6d9*7*$a$(gui0r1ze7f#u%(hua=^a3u66+vyj+9g' ROOT_URLCONF = 'vpr.urls.dev' INSTALLED_APPS += ( 'django_extensions', ) ","# Django settings for vpr project. from base import * from logger import * DEBUG = True DEVELOPMENT = True TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { #'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. #'NAME': 'vpr.sqlite3', # Or path to database file if using sqlite3. 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'vpr_dev', # Or path to database file if using sqlite3. 'USER': 'vpr', # Not used with sqlite3. 'PASSWORD': 'vpr', # Not used with sqlite3. 'HOST': 'localhost', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '3306', # Set to empty string for default. Not used with sqlite3. } } # Make this unique, and don't share it with anybody. #SECRET_KEY = 'kw7#s$8t&6d9*7*$a$(gui0r1ze7f#u%(hua=^a3u66+vyj+9g' ROOT_URLCONF = 'vpr.urls.dev' INSTALLED_APPS += ( 'django_extensions', ) " Make controller name configurable for resource routes,"<?php namespace Spark\Controller; class ControllerCollection extends \Silex\ControllerCollection { function draw(callable $callback) { if ($callback instanceof \Closure) { $callback = $callback->bindTo($this); } $callback($this); return $this; } function resources($resourceName, $options = []) { $controller = @$options['controller'] ?: $resourceName; $this->get(""/$resourceName"", ""$controller#index"") ->bind(""{$resourceName}_index""); $this->get(""/$resourceName/new"", ""$controller#new"") ->bind(""{$resourceName}_new""); $this->get(""/$resourceName/{id}"", ""$controller#show"") ->bind(""{$resourceName}_show""); $this->get(""/$resourceName/{id}/edit"", ""$controller#edit"") ->bind(""{$resourceName}_edit""); $this->post(""/$resourceName"", ""$controller#create"") ->bind(""{$resourceName}_create""); $this->put(""/$resourceName/{id}"", ""$controller#update"") ->bind(""{$resourceName}_update""); $this->delete(""/$resourceName/{id}"", ""$controller#destroy"") ->bind(""{$resourceName}_destroy""); } function resource($resourceName, $options = []) { $controller = @$options['controller'] ?: $resourceName; $this->get(""/$resourceName"", ""$controller#show""); $this->get(""/$resourceName/new"", ""$controller#new""); $this->get(""/$resourceName/edit"", ""$controller#edit""); $this->post(""/$resourceName"", ""$controller#create""); $this->put(""/$resourceName"", ""$controller#update""); $this->delete(""/$resourceName"", ""$controller#destroy""); } } ","<?php namespace Spark\Controller; class ControllerCollection extends \Silex\ControllerCollection { function draw(callable $callback) { $callback($this); return $this; } function resources($resourceName) { $this->get(""/$resourceName"", ""$resourceName#index"") ->bind(""{$resourceName}_index""); $this->get(""/$resourceName/new"", ""$resourceName#new"") ->bind(""{$resourceName}_new""); $this->get(""/$resourceName/{id}"", ""$resourceName#show"") ->bind(""{$resourceName}_show""); $this->get(""/$resourceName/{id}/edit"", ""$resourceName#edit"") ->bind(""{$resourceName}_edit""); $this->post(""/$resourceName"", ""$resourceName#create"") ->bind(""{$resourceName}_create""); $this->put(""/$resourceName/{id}"", ""$resourceName#update"") ->bind(""{$resourceName}_update""); $this->delete(""/$resourceName/{id}"", ""$resourceName#destroy"") ->bind(""{$resourceName}_destroy""); } function resource($resourceName) { $this->get(""/$resourceName"", ""$resourceName#show""); $this->get(""/$resourceName/new"", ""$resourceName#new""); $this->get(""/$resourceName/edit"", ""$resourceName#edit""); $this->post(""/$resourceName"", ""$resourceName#create""); $this->put(""/$resourceName"", ""$resourceName#update""); $this->delete(""/$resourceName"", ""$resourceName#destroy""); } } " Check if digest is in progress and apply callback on-infinite,"angular.module('ngNephila.components.infinitescroll', [ 'ngNephila.services.visibleInContainer' ]) .directive('infiniteScroll', [ '$window', '$rootScope', 'visibleInContainer', function($window, $rootScope, visibleInContainer) { return { restrict: 'E', scope: { onInfinite: '&', ngIf: '&', }, link: function(scope, elem, attrs) { var visible = false; var windowElement = angular.element($window); var container = null; var reached; var handler = function() { if (scope.ngIf() === false) { return; } reached = visibleInContainer(elem[0], container[0]); if (reached && !visible) { visible = true; if (scope.$$phase || $rootScope.$$phase) { scope.onInfinite(); } else { scope.$apply(scope.onInfinite); } } else if (!reached && visible) { visible = false; } }; var changeContainer = function(newContainer) { if (container != null) { container.unbind('scroll', handler); } container = newContainer; if (newContainer != null) { return container.bind('scroll', handler); } }; changeContainer(windowElement); handler(); } }; } ]);","angular.module('ngNephila.components.infinitescroll', [ 'ngNephila.services.visibleInContainer' ]) .directive('infiniteScroll', [ '$window', 'visibleInContainer', function($window, visibleInContainer) { return { restrict: 'E', scope: { onInfinite: '&', ngIf: '&', }, link: function(scope, elem, attrs) { var visible = false; var windowElement = angular.element($window); var container = null; var reached; var handler = function() { if (scope.ngIf() === false) { return; } reached = visibleInContainer(elem[0], container[0]); if (reached && !visible) { visible = true; scope.onInfinite(); } else if (!reached && visible) { visible = false; } }; var changeContainer = function(newContainer) { if (container != null) { container.unbind('scroll', handler); } container = newContainer; if (newContainer != null) { return container.bind('scroll', handler); } }; changeContainer(windowElement); handler(); } }; } ]);" Convert greeting bar to react-intl,"import React, { Component } from 'react'; import { FormattedMessage } from 'react-intl'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { Shimmer } from '../../common/shimmer/Shimmer'; export class GreetingBar extends Component { componentDidMount() {} render() { const { user } = this.props; if (!user) { return ( <div className=""col mb-1 mt-2""> <Shimmer height={38} /> </div> ); } return ( <> <div className=""col-md-auto mb-1 mt-2 lead""> <FormattedMessage id=""account.greeting"" />, {user.firstName} {user.lastName}! </div> <div className=""col mb-1 mt-2 text-md-right""> {user.email} {user.email && user.phoneNumber && <span className=""mx-1""> · </span>} <span className=""mr-2"">{user.phoneNumber} </span> <Link className=""btn btn-light"" to=""/contact-details""> <FormattedMessage id=""account.update.contact"" /> </Link> </div> </> ); } } const mapStateToProps = (state) => ({ user: state.login.user, }); const withRedux = connect(mapStateToProps); export default withRedux(GreetingBar); ","import React, { Component } from 'react'; import { Message } from 'retranslate'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { Shimmer } from '../../common/shimmer/Shimmer'; export class GreetingBar extends Component { componentDidMount() {} render() { const { user } = this.props; if (!user) { return ( <div className=""col mb-1 mt-2""> <Shimmer height={38} /> </div> ); } return ( <> <div className=""col-md-auto mb-1 mt-2 lead""> <Message>account.greeting</Message>, {user.firstName} {user.lastName}! </div> <div className=""col mb-1 mt-2 text-md-right""> {user.email} {user.email && user.phoneNumber && <span className=""mx-1""> · </span>} <span className=""mr-2"">{user.phoneNumber} </span> <Link className=""btn btn-light"" to=""/contact-details""> <Message>account.update.contact</Message> </Link> </div> </> ); } } const mapStateToProps = (state) => ({ user: state.login.user, }); const withRedux = connect(mapStateToProps); export default withRedux(GreetingBar); " Allow AJAX viewpress view function calls,"<?php use Carbon\Carbon; use EklundChristopher\ViewPress\Application; if (! function_exists('viewpress_view')) { /** * Render a view file. * * @param string $template * @param array $data [] * @return string */ function viewpress_view($template, array $data = []) { if (is_admin() and ! defined('DOING_AJAX') and ! DOING_AJAX) { return; } return Application::getInstance()->view($template, $data); } } if (! function_exists('viewpress_directive')) { /** * Register a Blade directive. * * @param string $name * @param callable $closure * @return void */ function viewpress_directive($name, callable $closure) { if (is_admin()) { return; } $compiler = Application::getInstance()->view->getEngineResolver()->resolve('blade')->getCompiler(); $compiler->directive($name, $closure); } } if (! function_exists('viewpress_timeago')) { /** * Display a more humanly readable date & time. * * @param string $date * @return string */ function viewpress_timeago($date) { $timestamp = strtotime($date); return Carbon::createFromTimestamp($timestamp)->diffForHumans(); } } ","<?php use Carbon\Carbon; use EklundChristopher\ViewPress\Application; if (! function_exists('viewpress_view')) { /** * Render a view file. * * @param string $template * @param array $data [] * @return string */ function viewpress_view($template, array $data = []) { if (is_admin()) { return; } return Application::getInstance()->view($template, $data); } } if (! function_exists('viewpress_directive')) { /** * Register a Blade directive. * * @param string $name * @param callable $closure * @return void */ function viewpress_directive($name, callable $closure) { if (is_admin()) { return; } $compiler = Application::getInstance()->view->getEngineResolver()->resolve('blade')->getCompiler(); $compiler->directive($name, $closure); } } if (! function_exists('viewpress_timeago')) { /** * Display a more humanly readable date & time. * * @param string $date * @return string */ function viewpress_timeago($date) { $timestamp = strtotime($date); return Carbon::createFromTimestamp($timestamp)->diffForHumans(); } } " Correct cycling bug when password is updated server side,"package fr.coding.tools; import android.webkit.HttpAuthHandler; import android.webkit.WebView; import java.util.Date; import java.util.List; import fr.coding.tools.model.HostAuth; import fr.coding.tools.model.SslByPass; /** * Created by Matthieu on 03/10/2015. */ public class AutoAuthSslWebView extends SslWebView { public CallbackResult<HostAuth, HostAuth> AuthAsked; protected List<HostAuth> allowedHosts; public void setAllowedHosts(List<HostAuth> hosts) { allowedHosts = hosts; } public List<HostAuth> getAllowedHosts() { return allowedHosts; } public long AutoTestedDate = 0; @Override public void onReceivedHttpAuthRequest(WebView webView, HttpAuthHandler handler, String host, String realm) { if ((allowedHosts != null)&&(AutoTestedDate < (new Date().getTime()-(15000)))) { for (HostAuth ha : allowedHosts) { if (host.equals(ha.Host)) { AutoTestedDate = new Date().getTime(); handler.proceed(ha.Login, ha.Password); return; } } } if (AuthAsked != null) { HostAuth hostAuth = new HostAuth(); hostAuth.Host = host; HostAuth ret = AuthAsked.onCallback(hostAuth); if (ret != null) { handler.proceed(ret.Login, ret.Password); return; } } super.onReceivedHttpAuthRequest(webView, handler, host, realm); } } ","package fr.coding.tools; import android.webkit.HttpAuthHandler; import android.webkit.WebView; import java.util.List; import fr.coding.tools.model.HostAuth; import fr.coding.tools.model.SslByPass; /** * Created by Matthieu on 03/10/2015. */ public class AutoAuthSslWebView extends SslWebView { public CallbackResult<HostAuth, HostAuth> AuthAsked; protected List<HostAuth> allowedHosts; public void setAllowedHosts(List<HostAuth> hosts) { allowedHosts = hosts; } public List<HostAuth> getAllowedHosts() { return allowedHosts; } @Override public void onReceivedHttpAuthRequest(WebView webView, HttpAuthHandler handler, String host, String realm) { if (allowedHosts != null) { for (HostAuth ha : allowedHosts) { if (host.equals(ha.Host)) { handler.proceed(ha.Login, ha.Password); return; } } } if (AuthAsked != null) { HostAuth hostAuth = new HostAuth(); hostAuth.Host = host; HostAuth ret = AuthAsked.onCallback(hostAuth); if (ret != null) { handler.proceed(ret.Login, ret.Password); return; } } super.onReceivedHttpAuthRequest(webView, handler, host, realm); } } " Add logging for processing skips.,"package uk.ac.ebi.quickgo.index.common.listener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; /** * Created 02/12/15 * @author Edd */ public class LogStepListener implements StepExecutionListener { // logger private static final Logger LOGGER = LoggerFactory.getLogger(LogStepListener.class); @Override public void beforeStep(StepExecution stepExecution) { LOGGER.info(""QuickGO indexing STEP '{}' starting."", stepExecution.getStepName()); } @Override public ExitStatus afterStep(StepExecution stepExecution) { LOGGER.info(""=====================================================""); LOGGER.info("" QuickGO Step Statistics ""); LOGGER.info(""Step name : {}"", stepExecution.getStepName()); LOGGER.info(""Exit status : {}"", stepExecution.getExitStatus().getExitCode()); LOGGER.info(""Read count : {}"", stepExecution.getReadCount()); LOGGER.info(""Write count : {}"", stepExecution.getWriteCount()); LOGGER.info(""Skip count : {} ({} read / {} processing /{} write)"", stepExecution.getSkipCount(), stepExecution.getReadSkipCount(), stepExecution.getProcessSkipCount(), stepExecution.getWriteSkipCount()); LOGGER.info(""=====================================================""); return stepExecution.getExitStatus(); } } ","package uk.ac.ebi.quickgo.index.common.listener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; /** * Created 02/12/15 * @author Edd */ public class LogStepListener implements StepExecutionListener { // logger private static final Logger LOGGER = LoggerFactory.getLogger(LogStepListener.class); @Override public void beforeStep(StepExecution stepExecution) { LOGGER.info(""QuickGO indexing STEP '{}' starting."", stepExecution.getStepName()); } @Override public ExitStatus afterStep(StepExecution stepExecution) { LOGGER.info(""=====================================================""); LOGGER.info("" QuickGO Step Statistics ""); LOGGER.info(""Step name : {}"", stepExecution.getStepName()); LOGGER.info(""Exit status : {}"", stepExecution.getExitStatus().getExitCode()); LOGGER.info(""Read count : {}"", stepExecution.getReadCount()); LOGGER.info(""Write count : {}"", stepExecution.getWriteCount()); LOGGER.info(""Skip count : {} ({} read / {} write)"", stepExecution.getSkipCount(), stepExecution .getReadSkipCount(), stepExecution.getWriteSkipCount()); LOGGER.info(""=====================================================""); return stepExecution.getExitStatus(); } } " SFX: Fix issue where sound effects could be loaded more than once,"var Sfx = { sounds: { }, preload: function() { this.load('pickup_donut'); this.load('pickup_veggie'); this.load('omnom'); this.load('burp'); this.load('running'); this.load('puke'); }, load: function(soundId) { if (typeof Sfx.sounds[soundId] != 'undefined') { return Sfx.sounds[soundId]; } console.info('[SFX] Loading sound effect', soundId); Sfx.sounds[soundId] = new Audio('assets/sfx/' + soundId + '.wav'); Sfx.sounds[soundId].load(); return Sfx.sounds[soundId]; }, play: function(soundId) { if (typeof Sfx.sounds[soundId] == 'undefined') { Sfx.load(soundId); } else { Sfx.sounds[soundId].load(); // call load() every time to fix Chrome issue where sound only plays first time } Sfx.sounds[soundId].play(); }, pickupDonut: function () { this.play('pickup_donut'); }, pickupVeggie: function () { this.play('pickup_veggie'); }, omNom: function() { this.play('omnom'); }, burp: function() { this.play('burp'); }, puke: function() { this.play('puke'); } };","var Sfx = { sounds: { }, preload: function() { this.load('pickup_donut'); this.load('pickup_veggie'); this.load('omnom'); this.load('burp'); this.load('running'); this.load('puke'); }, load: function(soundId) { console.info('[SFX] Loading sound effect', soundId); Sfx.sounds[soundId] = new Audio('assets/sfx/' + soundId + '.wav'); Sfx.sounds[soundId].load(); return Sfx.sounds[soundId]; }, play: function(soundId) { if (typeof Sfx.sounds[soundId] == 'undefined') { Sfx.load(soundId); } else { Sfx.sounds[soundId].load(); // call load() every time to fix Chrome issue where sound only plays first time } Sfx.sounds[soundId].play(); }, pickupDonut: function () { this.play('pickup_donut'); }, pickupVeggie: function () { this.play('pickup_veggie'); }, omNom: function() { this.play('omnom'); }, burp: function() { this.play('burp'); }, puke: function() { this.play('puke'); } };" Fix import and type file,"// @flow import React, {Component} from 'react' import {StyleSheet, Text, TouchableHighlight, View} from 'react-native' import commonStyles from '../../styles/common' export default class ExistingDeviceRender extends Component { render () { return ( <View style={[styles.container, {marginTop: 200, padding: 20, alignItems: 'stretch'}]}> <Text style={commonStyles.h1}>What type of device would you like to connect this device with?</Text> <View style={{flex: 1, flexDirection: 'row', marginTop: 40, justifyContent: 'space-between', alignItems: 'flex-start', paddingLeft: 40, paddingRight: 40}}> <TouchableHighlight onPress={() => this.props.onSubmitComputer()}> <View style={{flexDirection: 'column', alignItems: 'center'}}> <Text>[Desktop icon]</Text> <Text>Desktop Device ></Text> </View> </TouchableHighlight> <TouchableHighlight onPress={() => this.props.onSubmitPhone()}> <View style={{flexDirection: 'column', alignItems: 'center'}}> <Text>[Mobile icon]</Text> <Text>Mobile Device ></Text> </View> </TouchableHighlight> </View> </View> ) } } ExistingDeviceRender.propTypes = { onSubmitComputer: React.PropTypes.func.isRequired, onSubmitPhone: React.PropTypes.func.isRequired } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'flex-start' } }) ","import React, {Component} from 'react' import {StyleSheet, Text, TouchableHighlight, View} from 'react-native' import commonStyles from '../../../styles/common' export default class ExistingDeviceRender extends Component { render () { return ( <View style={[styles.container, {marginTop: 200, padding: 20, alignItems: 'stretch'}]}> <Text style={commonStyles.h1}>What type of device would you like to connect this device with?</Text> <View style={{flex: 1, flexDirection: 'row', marginTop: 40, justifyContent: 'space-between', alignItems: 'flex-start', paddingLeft: 40, paddingRight: 40}}> <TouchableHighlight onPress={() => this.props.onSubmitComputer()}> <View style={{flexDirection: 'column', alignItems: 'center'}}> <Text>[Desktop icon]</Text> <Text>Desktop Device ></Text> </View> </TouchableHighlight> <TouchableHighlight onPress={() => this.props.onSubmitPhone()}> <View style={{flexDirection: 'column', alignItems: 'center'}}> <Text>[Mobile icon]</Text> <Text>Mobile Device ></Text> </View> </TouchableHighlight> </View> </View> ) } } ExistingDeviceRender.propTypes = { onSubmitComputer: React.PropTypes.func.isRequired, onSubmitPhone: React.PropTypes.func.isRequired } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'flex-start' } }) " Fix page height issues for tutorial page,"import React from 'react' import '../styles/video.css' const Tutorial = props => <div className='container'> <div className='row' style={{ marginBottom: 0 }}> <div className='col s12 valign-wrapper' style={{ minHeight: 'calc(100vh - 64px)' }} > <div style={{ width: '100%' }}> <div className='video-container z-depth-1'> <iframe src='https://www.youtube.com/embed/WQt0GDsL8ZU?rel=0' width='853' height='480' frameBorder='0' allowFullScreen='allowfullscreen' title='tutorial-video' /> </div> <p style={{ marginTop: '20px' }}> If you have any problems using the MarCom Resource Center, please contact Jesse Weigel at{' '} <a href='mailto:jweigel@franciscan.edu'> jweigel@franciscan.edu </a>{' '} or <a href='tel:17402845305'> 740-284-5305</a>. </p> </div> </div> </div> </div> export default Tutorial ","import React from 'react' import '../styles/video.css' const Tutorial = props => <div className='container'> <div className='row'> <div className='col s12 valign-wrapper' style={{ minHeight: 'calc(100vh - 64px)' }} > <div> <div className='video-container z-depth-1'> <iframe src='https://www.youtube.com/embed/WQt0GDsL8ZU?rel=0' width='853' height='480' frameBorder='0' allowFullScreen='allowfullscreen' title='tutorial-video' /> </div> <p className='btm-margin-20'> If you have any problems using the MarCom Resource Center, please contact Jesse Weigel at{' '} <a href='mailto:jweigel@franciscan.edu'> jweigel@franciscan.edu </a>{' '} or <a href='tel:17402845305'> 740-284-5305</a>. </p> </div> </div> </div> </div> export default Tutorial " Define default getContent for actions.,"<?php namespace Dersam\RequestTracker; /** * * * @author Sam Schmidt <samuel@dersam.net> * @since 2016-02-09 */ abstract class Action { protected $endpoint; protected $lastValidationError; protected $requiredParameters = []; protected $parameters = []; public function set(string $fieldName, $value) { $this->parameters[$fieldName] = $value; return $this; } public function getEndpoint() : string { return $this->endpoint; } /** * @return mixed */ public function getLastValidationError() : string { return $this->lastValidationError; } public function validate() : boolean { $missing = array_diff_key( $this->requiredParameters, $this->parameters ); $valid = true; if (count($missing) > 0) { $valid = false; $e = 'Missing required fields: '; foreach ($missing as $key) { $e .= $key.' '; } $this->lastValidationError = $e; } return $valid; } public function getContent() { return $this->parameters; } abstract function processResponse(); } ","<?php namespace Dersam\RequestTracker; /** * * * @author Sam Schmidt <samuel@dersam.net> * @since 2016-02-09 */ abstract class Action { protected $endpoint; protected $lastValidationError; protected $requiredParameters = []; protected $parameters = []; public function set(string $fieldName, $value) { $this->parameters[$fieldName] = $value; return $this; } public function getEndpoint() : string { return $this->endpoint; } /** * @return mixed */ public function getLastValidationError() : string { return $this->lastValidationError; } public function validate() : boolean { $missing = array_diff_key( $this->requiredParameters, $this->parameters ); $valid = true; if (count($missing) > 0) { $valid = false; $e = 'Missing required fields: '; foreach ($missing as $key) { $e .= $key.' '; } $this->lastValidationError = $e; } return $valid; } abstract function processResponse(); } " Update confirm to be if,"$(document).ready(function() { $('#ballot_response').submit(function(event) { if(confirm(""Are you sure you want to submit your ballot?"")) { var sortableList = $(""#candidates""); var listElements = sortableList.children(); var listValues = []; for (var i = 0; i < listElements.length; i++) { listValues.push(listElements[i].id); } var formData = { 'ballot' : listValues, '_csrf' : $('input[name=_csrf]').val() }; var formsub = $.ajax({ type : 'POST', url : '/endpoints/process_ballot.php', data : formData, dataType : 'json', encode : true }); formsub.done(function(data) { if (data.success) { setTimeout(function() { window.location.href = ""/vote""; }, 100); } }); } event.preventDefault(); }); }); ","$(document).ready(function() { $('#ballot_response').submit(function(event) { confirm(""Are you sure you want to submit your ballot?""); var sortableList = $(""#candidates""); var listElements = sortableList.children(); var listValues = []; for (var i = 0; i < listElements.length; i++) { listValues.push(listElements[i].id); } var formData = { 'ballot' : listValues, '_csrf' : $('input[name=_csrf]').val() }; var formsub = $.ajax({ type : 'POST', url : '/endpoints/process_ballot.php', data : formData, dataType : 'json', encode : true }); formsub.done(function(data) { if (data.success) { setTimeout(function() { window.location.href = ""/vote""; }, 100); } }); event.preventDefault(); }); }); " Test 1st training loss improves over 0th validation.,"import theanets import util class TestTrainer(util.MNIST): def setUp(self): super(TestTrainer, self).setUp() self.exp = theanets.Experiment( theanets.Autoencoder, layers=(self.DIGIT_SIZE, 10, self.DIGIT_SIZE)) def assert_progress(self, algo, **kwargs): trainer = self.exp.itertrain(self.images, optimize=algo, **kwargs) train, valid = next(trainer) assert train['loss'] < valid['loss'] def test_sgd(self): self.assert_progress('sgd', learning_rate=1e-4) def test_nag(self): self.assert_progress('nag', learning_rate=1e-4) def test_rprop(self): self.assert_progress('rprop', learning_rate=1e-4) def test_rmsprop(self): self.assert_progress('rmsprop', learning_rate=1e-4) def test_adadelta(self): self.assert_progress('adadelta', learning_rate=1e-4) def test_cg(self): self.assert_progress('cg') def test_layerwise(self): self.exp = theanets.Experiment( theanets.Autoencoder, layers=(self.DIGIT_SIZE, 10, 10, self.DIGIT_SIZE)) self.assert_progress('layerwise') ","import theanets import util class TestTrainer(util.MNIST): def setUp(self): super(TestTrainer, self).setUp() self.exp = theanets.Experiment( theanets.Autoencoder, layers=(self.DIGIT_SIZE, 10, self.DIGIT_SIZE)) def assert_progress(self, algo, **kwargs): trainer = self.exp.itertrain(self.images, optimize=algo, **kwargs) t0, v0 = next(trainer) t1, v1 = next(trainer) t2, v2 = next(trainer) assert t2['loss'] < t0['loss'] def test_sgd(self): self.assert_progress('sgd', learning_rate=1e-4) def test_nag(self): self.assert_progress('nag', learning_rate=1e-4) def test_rprop(self): self.assert_progress('rprop', learning_rate=1e-4) def test_rmsprop(self): self.assert_progress('rmsprop', learning_rate=1e-4) def test_adadelta(self): self.assert_progress('adadelta', learning_rate=1e-4) def test_cg(self): self.assert_progress('cg') def test_layerwise(self): self.exp = theanets.Experiment( theanets.Autoencoder, layers=(self.DIGIT_SIZE, 10, 10, self.DIGIT_SIZE)) self.assert_progress('layerwise') " Add author and URL info to make mkrelease happy.,"import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.txt')).read() CHANGES = open(os.path.join(here, 'CHANGES.txt')).read() requires = [ 'pyramid', 'pyramid_zodbconn', 'pyramid_tm', 'pyramid_debugtoolbar', 'ZODB3', 'waitress', 'repoze.folder', 'zope.interface', 'requests', 'feedparser', 'WebHelpers', 'zc.queue', ] setup(name='push-hub', version='0.5', description='push-hub', long_description=README + '\n\n' + CHANGES, classifiers=[ ""Programming Language :: Python"", ""Framework :: Pylons"", ""Topic :: Internet :: WWW/HTTP"", ""Topic :: Internet :: WWW/HTTP :: WSGI :: Application"", ], author='Six Feet Up', author_email='info@sixfeetup.com', url='http://www.sixfeetup.com', keywords='web pylons pyramid', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires = requires, tests_require= requires, extras_require={'test': ['mock']}, test_suite=""pushhub"", entry_points = """"""\ [paste.app_factory] main = pushhub:main [console_scripts] process_subscriber_notices = pushhub.scripts:process_subscriber_notices """""", ) ","import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.txt')).read() CHANGES = open(os.path.join(here, 'CHANGES.txt')).read() requires = [ 'pyramid', 'pyramid_zodbconn', 'pyramid_tm', 'pyramid_debugtoolbar', 'ZODB3', 'waitress', 'repoze.folder', 'zope.interface', 'requests', 'feedparser', 'WebHelpers', 'zc.queue', ] setup(name='push-hub', version='0.5', description='push-hub', long_description=README + '\n\n' + CHANGES, classifiers=[ ""Programming Language :: Python"", ""Framework :: Pylons"", ""Topic :: Internet :: WWW/HTTP"", ""Topic :: Internet :: WWW/HTTP :: WSGI :: Application"", ], author='', author_email='', url='', keywords='web pylons pyramid', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires = requires, tests_require= requires, extras_require={'test': ['mock']}, test_suite=""pushhub"", entry_points = """"""\ [paste.app_factory] main = pushhub:main [console_scripts] process_subscriber_notices = pushhub.scripts:process_subscriber_notices """""", ) " Add extra space before and after dash matchers,"#!/usr/bin/env node 'use strict'; var stdin = process.openStdin(); var async = require('async'); var cheerio = require('cheerio'); var request = require('request'); main(); function main() { stdin.setEncoding('utf8'); stdin.on('data', function(data) { fetchTitles(JSON.parse(data)); }); } function fetchTitles(urls) { async.mapLimit(urls, 20, fetchTitle, function(err, d) { if(err) { return console.error(err); } console.log(JSON.stringify(d.filter(id), null, 4)); }); } function fetchTitle(d, cb) { if(!d) { return cb(); } request.get(d.url, { rejectUnauthorized: false, pool: { maxSockets: 1000 } }, function(err, res, body) { if(err) { console.error(d.url, err); return cb(); } var $ = cheerio.load(body); d.title = $('title').text().split('·')[0]. split(' - ')[0]. split(' — ')[0]. split('|')[0]. split('//')[0]. split('«')[0]. split(' : ')[0]. trim(); cb(null, d); }); } function id(a) {return a;} ","#!/usr/bin/env node 'use strict'; var stdin = process.openStdin(); var async = require('async'); var cheerio = require('cheerio'); var request = require('request'); main(); function main() { stdin.setEncoding('utf8'); stdin.on('data', function(data) { fetchTitles(JSON.parse(data)); }); } function fetchTitles(urls) { async.mapLimit(urls, 20, fetchTitle, function(err, d) { if(err) { return console.error(err); } console.log(JSON.stringify(d.filter(id), null, 4)); }); } function fetchTitle(d, cb) { if(!d) { return cb(); } request.get(d.url, { rejectUnauthorized: false, pool: { maxSockets: 1000 } }, function(err, res, body) { if(err) { console.error(d.url, err); return cb(); } var $ = cheerio.load(body); d.title = $('title').text().split('·')[0]. split('-')[0]. split('—')[0]. split('|')[0]. split('//')[0]. split('«')[0]. split(' : ')[0]. trim(); cb(null, d); }); } function id(a) {return a;} " Remove passing test that brokes on Jenkins build,"<?php namespace Tests; use App\User; use App\Company; use TestCase; use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; class CompanyEditFormTest extends TestCase { use DatabaseTransactions; /** * A basic test example. * * @return void */ public function testExample() { $this->assertTrue(true); } // public function test_edit_own_company() // { // //$this->withoutMiddleware(); // $user = factory(User::class, 'admin')->create(); // $company = factory(Company::class)->create(); // $user->companies()->save($company); // $this->actingAs($user) // ->seeInDatabase('companies', [ // 'id' => $company->id, // 'name' => $company->name, // ]) // ->visit('/company/'.$company->id.'/edit') // ->see($company->name) // ->type('Company New Name', 'name') // ->press('Save Edit') // ->seeInDatabase('companies', [ // 'id' => $company->id, // 'name' => 'Company New Name' // ]); // } } ","<?php namespace Tests; use App\User; use App\Company; use TestCase; use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; class CompanyEditFormTest extends TestCase { use DatabaseTransactions; /** * A basic test example. * * @return void */ public function testEdit() { //$this->withoutMiddleware(); $user = factory(User::class, 'owner')->create(); $company = factory(Company::class)->create(); $user->companies()->save($company); $this->actingAs($user) ->seeInDatabase('companies', [ 'id' => $company->id, 'name' => $company->name, ]) ->visit('/company/'.$company->id.'/edit') ->see($company->name) ->type('Company New Name', 'name') ->press('Save Edit') ->seeInDatabase('companies', [ 'id' => $company->id, 'name' => 'Company New Name' ]); } } " "Revert ""basic bolts check for reportedfailedexception"" This reverts commit e8d886485923b0f7a5101e55ded48103751f55a0.","package backtype.storm.topology; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.tuple.Tuple; import java.util.Map; import org.apache.log4j.Logger; public class BasicBoltExecutor implements IRichBolt { public static Logger LOG = Logger.getLogger(BasicBoltExecutor.class); private IBasicBolt _bolt; private transient BasicOutputCollector _collector; public BasicBoltExecutor(IBasicBolt bolt) { _bolt = bolt; } public void declareOutputFields(OutputFieldsDeclarer declarer) { _bolt.declareOutputFields(declarer); } public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { _bolt.prepare(stormConf, context); _collector = new BasicOutputCollector(collector); } public void execute(Tuple input) { _collector.setContext(input); try { _bolt.execute(input, _collector); _collector.getOutputter().ack(input); } catch(FailedException e) { LOG.warn(""Failed to process tuple"", e); _collector.getOutputter().fail(input); } } public void cleanup() { _bolt.cleanup(); } public Map<String, Object> getComponentConfiguration() { return _bolt.getComponentConfiguration(); } }","package backtype.storm.topology; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.tuple.Tuple; import java.util.Map; import org.apache.log4j.Logger; public class BasicBoltExecutor implements IRichBolt { public static Logger LOG = Logger.getLogger(BasicBoltExecutor.class); private IBasicBolt _bolt; private transient BasicOutputCollector _collector; public BasicBoltExecutor(IBasicBolt bolt) { _bolt = bolt; } public void declareOutputFields(OutputFieldsDeclarer declarer) { _bolt.declareOutputFields(declarer); } public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { _bolt.prepare(stormConf, context); _collector = new BasicOutputCollector(collector); } public void execute(Tuple input) { _collector.setContext(input); try { _bolt.execute(input, _collector); _collector.getOutputter().ack(input); } catch(FailedException e) { if(e instanceof ReportedFailedException) { _collector.reportError(e); } _collector.getOutputter().fail(input); } } public void cleanup() { _bolt.cleanup(); } public Map<String, Object> getComponentConfiguration() { return _bolt.getComponentConfiguration(); } }" Update URLs to match best practice of the resource name not being plural,"import express from 'express'; import bodyParser from 'body-parser'; import log from './log'; import database from './database'; import configureHelmet from './middleware/configure-helmet'; import requestLogger from './middleware/request-logger'; import userRoutes from './components/user/user-routes'; import postRoutes from './components/post/post-routes'; import notFoundRoute from './errors/not-found-routes'; function startServer() { database.sync() .then(() => { log.info('Connected to Database Successfully'); const app = express(); configureHelmet(app); app.use(requestLogger); app.use(bodyParser.json()); app.use('/v2.0/user', userRoutes); app.use('/v2.0/post', postRoutes); app.use(notFoundRoute); const port = process.env.PORT; app.listen(port, () => { log.info({ port }, 'CSBlogs API now running'); }); }) .catch(error => { if (error instanceof database.ConnectionError) { log.info('Connection to Database Failed', { host: process.env.CSBLOGS_DATABASE_HOST, port: process.env.CSBLOGS_DATABASE_PORT, name: process.env.CSBLOGS_DATABASE_NAME, username: process.env.CSBLOGS_DATABASE_USERNAME }); setTimeout(startServer, 1000); } }); } startServer(); ","import express from 'express'; import bodyParser from 'body-parser'; import log from './log'; import database from './database'; import configureHelmet from './middleware/configure-helmet'; import requestLogger from './middleware/request-logger'; import userRoutes from './components/user/user-routes'; import postRoutes from './components/post/post-routes'; import notFoundRoute from './errors/not-found-routes'; function startServer() { database.sync() .then(() => { log.info('Connected to Database Successfully'); const app = express(); configureHelmet(app); app.use(requestLogger); app.use(bodyParser.json()); app.use('/v2.0/users', userRoutes); app.use('/v2.0/posts', postRoutes); app.use(notFoundRoute); const port = process.env.PORT; app.listen(port, () => { log.info({ port }, 'CSBlogs API now running'); }); }) .catch(error => { if (error instanceof database.ConnectionError) { log.info('Connection to Database Failed', { host: process.env.CSBLOGS_DATABASE_HOST, port: process.env.CSBLOGS_DATABASE_PORT, name: process.env.CSBLOGS_DATABASE_NAME, username: process.env.CSBLOGS_DATABASE_USERNAME }); setTimeout(startServer, 1000); } }); } startServer(); " Fix an issue in python 2 for the scratch extension.,"import os import re from jinja2 import Template DEFAULT_TEMPLATE = os.path.join(os.path.dirname(__file__), 'extension.tpl.js') supported_modules = [ 'button', 'dynamixel', 'l0_dc_motor', 'l0_gpio', 'l0_servo', 'led', 'potard', ] def find_modules(state, type): return [ str(m['alias']) for m in state['modules'] if m['type'] == type ] def find_xl320(state, dxl): dxl = next(filter(lambda mod: mod['alias'] == dxl, state['modules'])) motors = [m for m in dxl if re.match(r'm[0-9]+', m)] return motors def generate_extension(name, robot, host, port, template=DEFAULT_TEMPLATE): context = {} context = { 'name': name, 'host': host, 'port': port, } context.update({ type: find_modules(robot._state, type) for type in supported_modules }) if context['dynamixel']: # TODO: This should be done for every dxl controller! context['xl_320'] = find_xl320(robot._state, context['dynamixel'][0]) with open(template) as f: tpl = Template(f.read()) ext = tpl.render(**context) return ext ","import os import re from jinja2 import Template DEFAULT_TEMPLATE = os.path.join(os.path.dirname(__file__), 'extension.tpl.js') supported_modules = [ 'button', 'dynamixel', 'l0_dc_motor', 'l0_gpio', 'l0_servo', 'led', 'potard', ] def find_modules(state, type): return [ m['alias'] for m in state['modules'] if m['type'] == type ] def find_xl320(state, dxl): dxl = next(filter(lambda mod: mod['alias'] == dxl, state['modules'])) motors = [m for m in dxl if re.match(r'm[0-9]+', m)] return motors def generate_extension(name, robot, host, port, template=DEFAULT_TEMPLATE): context = {} context = { 'name': name, 'host': host, 'port': port, } context.update({ type: find_modules(robot._state, type) for type in supported_modules }) if context['dynamixel']: # TODO: This should be done for every dxl controller! context['xl_320'] = find_xl320(robot._state, context['dynamixel'][0]) with open(template) as f: tpl = Template(f.read()) ext = tpl.render(**context) return ext " Clean up temporary directory after the test,"import collections import os import shutil import tempfile import time import unittest import mock from chainer import serializers from chainer import testing from chainer import training class TestTrainerElapsedTime(unittest.TestCase): def setUp(self): self.trainer = _get_mocked_trainer() def test_elapsed_time(self): with self.assertRaises(RuntimeError): self.trainer.elapsed_time self.trainer.run() self.assertGreater(self.trainer.elapsed_time, 0) def test_elapsed_time_serialization(self): self.trainer.run() serialized_time = self.trainer.elapsed_time tempdir = tempfile.mkdtemp() try: path = os.path.join(tempdir, 'trainer.npz') serializers.save_npz(path, self.trainer) trainer = _get_mocked_trainer((20, 'iteration')) serializers.load_npz(path, trainer) trainer.run() self.assertGreater(trainer.elapsed_time, serialized_time) finally: shutil.rmtree(tempdir) def _get_mocked_trainer(stop_trigger=(10, 'iteration')): updater = mock.Mock() updater.get_all_optimizers.return_value = {} updater.iteration = 0 def update(): updater.iteration += 1 updater.update = update return training.Trainer(updater, stop_trigger) testing.run_module(__name__, __file__) ","import collections import os import tempfile import time import unittest import mock from chainer import serializers from chainer import testing from chainer import training class TestTrainerElapsedTime(unittest.TestCase): def setUp(self): self.trainer = _get_mocked_trainer() def test_elapsed_time(self): with self.assertRaises(RuntimeError): self.trainer.elapsed_time self.trainer.run() self.assertGreater(self.trainer.elapsed_time, 0) def test_elapsed_time_serialization(self): self.trainer.run() serialized_time = self.trainer.elapsed_time tempdir = tempfile.mkdtemp() path = os.path.join(tempdir, 'trainer.npz') serializers.save_npz(path, self.trainer) trainer = _get_mocked_trainer((20, 'iteration')) serializers.load_npz(path, trainer) trainer.run() self.assertGreater(trainer.elapsed_time, serialized_time) def _get_mocked_trainer(stop_trigger=(10, 'iteration')): updater = mock.Mock() updater.get_all_optimizers.return_value = {} updater.iteration = 0 def update(): updater.iteration += 1 updater.update = update return training.Trainer(updater, stop_trigger) testing.run_module(__name__, __file__) " Send message to other API,"const models = require('../../models'); let Project = models.projects; module.exports = function(connection, done) { connection.createChannel(function(err, ch) { console.log(err); var ex = 'chiepherd.main'; ch.assertExchange(ex, 'topic'); ch.assertQueue('chiepherd.project.create', { exclusive: false }, function(err, q) { ch.bindQueue(q.queue, ex, ""chiepherd.project.create"") ch.consume(q.queue, function(msg) { // LOG console.log("" [%s]: %s"", msg.fields.routingKey, msg.content.toString()); let json = JSON.parse(msg.content.toString()); // Create project Project.create({ name: json.name, label: json.label, description: json.description }).then(function(project) { ch.sendToQueue(msg.properties.replyTo, new Buffer.from(JSON.stringify(project)), { correlationId: msg.properties.correlationId }); connection.createChannel(function(error, channel) { var ex = 'chiepherd.project.created'; channel.assertExchange(ex, 'fanout', { durable: false }); channel.publish(ex, '', new Buffer.from(JSON.stringify(project))); }); ch.ack(msg); }).catch(function(error) { ch.sendToQueue(msg.properties.replyTo, new Buffer.from(JSON.stringify(error)), { correlationId: msg.properties.correlationId }); ch.ack(msg); }); }, { noAck: false }); }); }); done(); } ","const models = require('../../models'); let Project = models.projects; module.exports = function(connection, done) { connection.createChannel(function(err, ch) { console.log(err); var ex = 'chiepherd.main'; ch.assertExchange(ex, 'topic'); ch.assertQueue('chiepherd.project.create', { exclusive: false }, function(err, q) { ch.bindQueue(q.queue, ex, ""chiepherd.project.create"") ch.consume(q.queue, function(msg) { // LOG console.log("" [%s]: %s"", msg.fields.routingKey, msg.content.toString()); let json = JSON.parse(msg.content.toString()); // Create project Project.create({ name: json.name, label: json.label, description: json.description }).then(function(project) { ch.sendToQueue(msg.properties.replyTo, new Buffer.from(JSON.stringify(project)), { correlationId: msg.properties.correlationId }); ch.ack(msg); }).catch(function(error) { ch.sendToQueue(msg.properties.replyTo, new Buffer.from(JSON.stringify(error)), { correlationId: msg.properties.correlationId }); ch.ack(msg); }); }, { noAck: false }); }); }); done(); } " Add control buttons to auth,"import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import jwtDecode from 'jwt-decode'; import styles from './styles.scss'; import Login from './Login'; import Signup from './Signup'; import Info from './Info'; import Controls from '../Controls'; import { addUser } from '../../actions/user'; const mapDispatchToProps = dispatch => ({ addUserFromToken: token => dispatch(addUser(jwtDecode(token))), }); class Auth extends Component { state = { isNewUser: false } toggleNewUser = () => { this.setState({ isNewUser: !this.state.isNewUser }); } render() { const { addUserFromToken } = this.props; const { isNewUser } = this.state; return ( <div className={styles.Auth}> <Controls /> <div className={[styles.AuthBox, isNewUser ? '' : styles.OldUser].join(' ')}> { isNewUser ? <Signup switchForm={this.toggleNewUser} addUser={addUserFromToken} /> : <Login switchForm={this.toggleNewUser} addUser={addUserFromToken} /> } <Info message={isNewUser ? 'Take a part in creating better video games!' : 'Welcome back!'} isNewUser={isNewUser} /> </div> </div> ); } } Auth.propTypes = { addUserFromToken: PropTypes.func.isRequired }; export default connect(null, mapDispatchToProps)(Auth); ","import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import jwtDecode from 'jwt-decode'; import styles from './styles.scss'; import Login from './Login'; import Signup from './Signup'; import Info from './Info'; import { addUser } from '../../actions/user'; const mapDispatchToProps = dispatch => ({ addUserFromToken: token => dispatch(addUser(jwtDecode(token))), }); class Auth extends Component { state = { isNewUser: false } toggleNewUser = () => { this.setState({ isNewUser: !this.state.isNewUser }); } render() { const { addUserFromToken } = this.props; const { isNewUser } = this.state; return ( <div className={styles.Auth}> <div className={[styles.AuthBox, isNewUser ? '' : styles.OldUser].join(' ')}> { isNewUser ? <Signup switchForm={this.toggleNewUser} addUser={addUserFromToken} /> : <Login switchForm={this.toggleNewUser} addUser={addUserFromToken} /> } <Info message={isNewUser ? 'Take a part in creating better video games!' : 'Welcome back!'} isNewUser={isNewUser} /> </div> </div> ); } } Auth.propTypes = { addUserFromToken: PropTypes.func.isRequired }; export default connect(null, mapDispatchToProps)(Auth); " Remove extra event handler methods from todo,"import React, { PropTypes } from 'react' class Todo extends React.Component { static propTypes = { todo: PropTypes.any.isRequired, deleteButtonVisible: PropTypes.bool, onCompleted: PropTypes.func.isRequired, onDelete: PropTypes.func.isRequired, onDeleteButtonVisibilityChanged: PropTypes.func.isRequired }; render () { const textStyle = this.props.todo.completed ? {'textDecoration': 'line-through'} : {} let deleteButtonClassName = 'delete-button close' if (!this.props.deleteButtonVisible) { deleteButtonClassName += ' delete-button-hidden' } return ( <tr className='todo' onMouseEnter={this.props.onDeleteButtonVisibilityChanged.bind(this, this.props.todo)} onMouseLeave={this.props.onDeleteButtonVisibilityChanged.bind(this, undefined)} > <td> <input type='checkbox' checked={this.props.todo.completed ? 'checked' : ''} onChange={() => { this.props.onCompleted(this.props.todo) } } /> </td> <td> <span style={textStyle}> {this.props.todo.text} </span> </td> <td> <button type='button' className={deleteButtonClassName} aria-label='Close' onClick={this.props.onDelete.bind(this, this.props.todo)}> <span aria-hidden='true'>×</span> </button> </td> </tr> ) } } export default Todo ","import React, { PropTypes } from 'react' class Todo extends React.Component { static propTypes = { todo: PropTypes.any.isRequired, deleteButtonVisible: PropTypes.bool, onCompleted: PropTypes.func.isRequired, onDelete: PropTypes.func.isRequired, onDeleteButtonVisibilityChanged: PropTypes.func.isRequired }; render () { const textStyle = this.props.todo.completed ? {'textDecoration': 'line-through'} : {} let deleteButtonClassName = 'delete-button close' if (!this.props.deleteButtonVisible) { deleteButtonClassName += ' delete-button-hidden' } return ( <tr className='todo' onMouseEnter={this.handleMouseEnter.bind(this)} onMouseLeave={this.handleMouseLeave.bind(this)} > <td> <input type='checkbox' checked={this.props.todo.completed ? 'checked' : ''} onChange={() => { this.props.onCompleted(this.props.todo) } } /> </td> <td> <span style={textStyle}> {this.props.todo.text} </span> </td> <td> <button type='button' className={deleteButtonClassName} aria-label='Close' onClick={this.handleDelete.bind(this)}> <span aria-hidden='true'>×</span> </button> </td> </tr> ) } handleMouseEnter (event) { this.props.onDeleteButtonVisibilityChanged(this.props.todo) } handleMouseLeave (event) { this.props.onDeleteButtonVisibilityChanged(undefined) } handleDelete () { this.props.onDelete(this.props.todo) } } export default Todo " Add semicolon in test file,"const { expect } = require('chai'); const cheerio = require('cheerio'); const request = require('supertest'); const app = require('../app'); describe('Pages', function() { let req; describe('/', function() { beforeEach(function() { req = request(app).get('/'); }); it('returns 200 OK', function(done) { req.expect(200, done); }); it('renders template', function (done) { req.expect('Content-Type', /text\/html/, done); }); it('has valid title', function (done) { req .expect((res) => { const content = res.text; const $ = cheerio.load(content); expect($('title').text()).to.eq('Slava Pavlutin'); }) .end(done); }); }); describe('/contact', function() { beforeEach(function() { req = request(app).get('/contact'); }); it('returns 200 OK', function (done) { req.expect(200, done); }); it('renders template', function (done) { req.expect('Content-Type', /text\/html/, done); }); it('has valid title', function (done) { req .expect((res) => { const content = res.text; const $ = cheerio.load(content); expect($('title').text()).to.eq('Slava Pavlutin | Contact'); }) .end(done); }); }); }); ","const { expect } = require('chai'); const cheerio = require('cheerio'); const request = require('supertest'); const app = require('../app'); describe('Pages', function() { let req; describe('/', function() { beforeEach(function() { req = request(app).get('/') }); it('returns 200 OK', function(done) { req.expect(200, done); }); it('renders template', function (done) { req.expect('Content-Type', /text\/html/, done); }); it('has valid title', function (done) { req .expect((res) => { const content = res.text; const $ = cheerio.load(content); expect($('title').text()).to.eq('Slava Pavlutin'); }) .end(done); }); }); describe('/contact', function() { beforeEach(function() { req = request(app).get('/contact'); }); it('returns 200 OK', function (done) { req.expect(200, done); }); it('renders template', function (done) { req.expect('Content-Type', /text\/html/, done); }); it('has valid title', function (done) { req .expect((res) => { const content = res.text; const $ = cheerio.load(content); expect($('title').text()).to.eq('Slava Pavlutin | Contact'); }) .end(done); }); }); }); " Set initial hash size (should be tuned more).,"package com.zaxxer.hikari.json.util; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; import com.zaxxer.hikari.json.JsonProperty; public final class Clazz { private final Class<?> actualClass; private final Map<Integer, Phield> fields; public Clazz(Class<?> clazz) { this.actualClass = clazz; this.fields = new HashMap<>((int)(actualClass.getDeclaredFields().length * 1.3)); } void parseFields() { for (Field field : actualClass.getDeclaredFields()) { if (!Modifier.isStatic(field.getModifiers())) { JsonProperty jsonProperty = field.getAnnotation(JsonProperty.class); boolean excluded = (jsonProperty != null && jsonProperty.exclude()); Phield phield = new Phield(field, excluded); if (jsonProperty != null) { fields.put(jsonProperty.name().hashCode(), phield); } else { fields.put(field.getName().hashCode(), phield); fields.put(field.getName().toLowerCase().hashCode(), phield); } } } } public Class<?> getActualClass() { return actualClass; } public Phield getPhield(final int hashCode) { return fields.get(hashCode); } @Override public String toString() { return ""Clazz ["" + actualClass.getCanonicalName() + ""]""; } public Object newInstance() throws InstantiationException, IllegalAccessException { return actualClass.newInstance(); } } ","package com.zaxxer.hikari.json.util; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; import com.zaxxer.hikari.json.JsonProperty; public final class Clazz { private final Class<?> actualClass; private final Map<Integer, Phield> fields; public Clazz(Class<?> clazz) { this.actualClass = clazz; this.fields = new HashMap<>(); } void parseFields() { for (Field field : actualClass.getDeclaredFields()) { if (!Modifier.isStatic(field.getModifiers())) { JsonProperty jsonProperty = field.getAnnotation(JsonProperty.class); boolean excluded = (jsonProperty != null && jsonProperty.exclude()); Phield phield = new Phield(field, excluded); if (jsonProperty != null) { fields.put(jsonProperty.name().hashCode(), phield); } else { fields.put(field.getName().hashCode(), phield); fields.put(field.getName().toLowerCase().hashCode(), phield); } } } } public Class<?> getActualClass() { return actualClass; } public Phield getPhield(final int hashCode) { return fields.get(hashCode); } @Override public String toString() { return ""Clazz ["" + actualClass.getCanonicalName() + ""]""; } public Object newInstance() throws InstantiationException, IllegalAccessException { return actualClass.newInstance(); } } " [fixed] Tag helper code should have used jqLite API.,"/* global angular */ (function() { angular.module(""googlechart"") .factory(""agcScriptTagHelper"", agcScriptTagHelperFactory); agcScriptTagHelperFactory.$inject = [""$q"", ""$document""]; function agcScriptTagHelperFactory($q, $document) { /** Add a script tag to the document's head section and return an angular * promise that resolves when the script has loaded. */ function agcScriptTagHelper(url) { var deferred = $q.defer(); var head = $document.find('head')[0]; var script = angular.element('<script></script>'); script.setAttribute('type', 'text/javascript'); script.src = url; if (script.addEventListener) { // Standard browsers (including IE9+) script.addEventListener('load', onLoad, false); script.onerror = onError; } else { // IE8 and below script.onreadystatechange = function () { if (script.readyState === 'loaded' || script.readyState === 'complete') { script.onreadystatechange = null; onLoad(); } }; } head.appendChild(script); function onLoad() { deferred.resolve(); } function onError() { deferred.reject(); } return deferred.promise; } return agcScriptTagHelper; } })(); ","/* global angular */ (function() { angular.module(""googlechart"") .factory(""agcScriptTagHelper"", agcScriptTagHelperFactory); agcScriptTagHelperFactory.$inject = [""$q"", ""$document""]; function agcScriptTagHelperFactory($q, $document) { /** Add a script tag to the document's head section and return an angular * promise that resolves when the script has loaded. */ function agcScriptTagHelper(url) { var deferred = $q.defer(); var head = $document.getElementsByTagName('head')[0]; var script = $document.createElement('script'); script.setAttribute('type', 'text/javascript'); script.src = url; if (script.addEventListener) { // Standard browsers (including IE9+) script.addEventListener('load', onLoad, false); script.onerror = onError; } else { // IE8 and below script.onreadystatechange = function () { if (script.readyState === 'loaded' || script.readyState === 'complete') { script.onreadystatechange = null; onLoad(); } }; } head.appendChild(script); function onLoad() { deferred.resolve(); } function onError() { deferred.reject(); } return deferred.promise; } return agcScriptTagHelper; } })(); " Make the filter() function always return a collection,"<?php namespace Picqer\Financials\Exact\Query; trait Findable { public function find($id) { $result = $this->connection()->get($this->url, [ '$filter' => $this->primaryKey . "" eq guid'$id'"" ]); return new self($this->connection(), $result); } public function filter($filter, $expand = '', $select = '') { $request = [ '$filter' => $filter ]; if (strlen($expand) > 0) { $request['$expand'] = $expand; } if (strlen($select) > 0) { $request['$select'] = $select; } $result = $this->connection()->get($this->url, $request); // If we have one result which is not an assoc array, make it the first element of an array for the // collectionFromResult function so we always return a collection from filter if ((bool) count(array_filter(array_keys($result), 'is_string'))) { $result = [ $result ]; } return $this->collectionFromResult($result); } public function get() { $result = $this->connection()->get($this->url); return $this->collectionFromResult($result); } public function collectionFromResult($result) { $collection = [ ]; foreach ($result as $r) { $collection[] = new self($this->connection(), $r); } return $collection; } }","<?php namespace Picqer\Financials\Exact\Query; trait Findable { public function find($id) { $result = $this->connection()->get($this->url, [ '$filter' => $this->primaryKey . "" eq guid'$id'"" ]); return new self($this->connection(), $result); } public function filter($filter, $expand = '', $select='') { $request = [ '$filter' => $filter ]; if (strlen($expand) > 0) { $request['$expand'] = $expand; } if (strlen($select) > 0) { $request['$select'] = $select; } $result = $this->connection()->get($this->url, $request); return new self($this->connection(), $result); } public function get() { $result = $this->connection()->get($this->url); return $this->collectionFromResult($result); } public function collectionFromResult($result) { $collection = []; foreach ($result as $r) { $collection[] = new self($this->connection(), $r); } return $collection; } }" Fix non-java find usages dialogs.,"package com.intellij.find.findUsages; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.usageView.UsageViewUtil; import javax.swing.*; /** * Created by IntelliJ IDEA. * User: max * Date: Feb 14, 2005 * Time: 5:40:05 PM * To change this template use File | Settings | File Templates. */ public class CommonFindUsagesDialog extends AbstractFindUsagesDialog { private PsiElement myPsiElement; public CommonFindUsagesDialog(PsiElement element, Project project, FindUsagesOptions findUsagesOptions, boolean toShowInNewTab, boolean mustOpenInNewTab, boolean isSingleFile) { super(project, findUsagesOptions, toShowInNewTab, mustOpenInNewTab, isSingleFile, FindUsagesUtil.isSearchForTextOccurencesAvailable(element, isSingleFile), !isSingleFile && !element.getManager().isInProject(element)); myPsiElement = element; init(); } protected JPanel createFindWhatPanel() { return null; } protected JComponent getPreferredFocusedControl() { return null; } public String getLabelText() { return StringUtil.capitalize(UsageViewUtil.getType(myPsiElement)) + "" "" + UsageViewUtil.getDescriptiveName(myPsiElement); } } ","package com.intellij.find.findUsages; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.usageView.UsageViewUtil; import javax.swing.*; /** * Created by IntelliJ IDEA. * User: max * Date: Feb 14, 2005 * Time: 5:40:05 PM * To change this template use File | Settings | File Templates. */ public class CommonFindUsagesDialog extends AbstractFindUsagesDialog { private PsiElement myPsiElement; public CommonFindUsagesDialog(PsiElement element, Project project, FindUsagesOptions findUsagesOptions, boolean toShowInNewTab, boolean mustOpenInNewTab, boolean isSingleFile) { super(project, findUsagesOptions, toShowInNewTab, mustOpenInNewTab, isSingleFile, FindUsagesUtil.isSearchForTextOccurencesAvailable(element, isSingleFile), !isSingleFile && !element.getManager().isInProject(element)); myPsiElement = element; } protected JPanel createFindWhatPanel() { return null; } protected JComponent getPreferredFocusedControl() { return null; } public String getLabelText() { return StringUtil.capitalize(UsageViewUtil.getType(myPsiElement)) + "" "" + UsageViewUtil.getDescriptiveName(myPsiElement); } } " Reduce polling access by exponential backoff like strategy,"(function(){ ""use strict""; var POLLING_INTERVAL = 3 * 1000; var POLLING_URL = ""/polling/alerts""; $(function(){ if($('#vue-notification').length === 0) return; var alert = new Vue({ el: ""#vue-notification"", data: { ""alerts"": [] }, created: function(){ var self = this; var currentInterval = POLLING_INTERVAL; var fetch = function(){ self.fetchAlertsData().then(function(alerts){ if(self.alerts.toString() == alerts.toString()) { currentInterval *= 1.1; } else { currentInterval = POLLING_INTERVAL; } self.alerts = alerts; setTimeout(fetch, currentInterval); })[""catch""](function(xhr){ if(xhr.status === 401) { // signed out } if(xhr.status === 0) { // server unreachable (maybe down) } }); }; fetch(); }, computed: { alertsCount: { $get: function(){ return this.alerts.length; } }, hasAlerts: { $get: function(){ return this.alertsCount > 0; } } }, methods: { fetchAlertsData: function() { return new Promise(function(resolve, reject) { $.getJSON(POLLING_URL, resolve).fail(reject); }); } } }); }); })(); ","(function(){ ""use strict""; var POLLING_INTERVAL = 3 * 1000; var POLLING_URL = ""/polling/alerts""; $(function(){ if($('#vue-notification').length === 0) return; var alert = new Vue({ el: ""#vue-notification"", data: { ""alerts"": [] }, created: function(){ var self = this; var fetch = function(){ self.fetchAlertsData().then(function(alerts){ self.alerts = alerts; })[""catch""](function(xhr){ if(xhr.status === 401) { clearInterval(timer); // signed out } if(xhr.status === 0) { clearInterval(timer); // server unreachable (maybe down) } }); }; fetch(); var timer = setInterval(fetch, POLLING_INTERVAL); }, computed: { alertsCount: { $get: function(){ return this.alerts.length; } }, hasAlerts: { $get: function(){ return this.alertsCount > 0; } } }, methods: { fetchAlertsData: function() { return new Promise(function(resolve, reject) { $.getJSON(POLLING_URL, resolve).fail(reject); }); } } }); }); })(); " Add a test about parsing $< and $> (that was failing before fix),"<?php use Manialib\Formatting\Converter\Html; use Manialib\Formatting\ManiaplanetString; class HtmlTest extends PHPUnit_Framework_TestCase { public function convertProvider() { return [ [ '$cfeg$fff๐u1 $666ツ', '<span style=""color:#cfe;"">g</span><span style=""color:#fff;"">๐u1 </span><span style=""color:#666;"">ツ</span>' ], [ 'a$>b', 'ab' ], [ 'foo$<$f20foo$>bar', 'foo<span style=""color:#f20;"">foo</span>bar' ] ]; } /** * @dataProvider convertProvider */ public function testConvert($input, $expected) { $this->assertEquals($expected, (new ManiaplanetString($input))->toHtml()); } /** * @dataProvider convertProvider */ public function testReuseConverter($input, $expected) { $converter = new Html(); $this->assertEquals( $converter->setInput(new ManiaplanetString($input))->getOutput(), $converter->setInput(new ManiaplanetString($input))->getOutput()); } public function nicknamesProvider() { return [ [''] ]; } /** * @dataProvider nicknamesProvider */ public function testNoErrors($input) { (new ManiaplanetString($input))->toHtml(); } } ","<?php use Manialib\Formatting\Converter\Html; use Manialib\Formatting\ManiaplanetString; class HtmlTest extends PHPUnit_Framework_TestCase { public function convertProvider() { return [ [ '$cfeg$fff๐u1 $666ツ', '<span style=""color:#cfe;"">g</span><span style=""color:#fff;"">๐u1 </span><span style=""color:#666;"">ツ</span>' ], ['a$>b', 'ab'] ]; } /** * @dataProvider convertProvider */ public function testConvert($input, $expected) { $this->assertEquals($expected, (new ManiaplanetString($input))->toHtml()); } /** * @dataProvider convertProvider */ public function testReuseConverter($input, $expected) { $converter = new Html(); $this->assertEquals( $converter->setInput(new ManiaplanetString($input))->getOutput(), $converter->setInput(new ManiaplanetString($input))->getOutput()); } public function nicknamesProvider() { return [ [''] ]; } /** * @dataProvider nicknamesProvider */ public function testNoErrors($input) { (new ManiaplanetString($input))->toHtml(); } } " Make test inner classes static,"package org.granchi.hollywood; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import static com.google.common.truth.Truth.assertThat; @RunWith(MockitoJUnitRunner.class) public class ModelTest { @Test public void testGetSubmodelsOfSameType() throws Exception { ParentModel model = new ParentModel(); assertThat(model.getSubmodelsOfType(ParentModel.class)).containsExactly(model); } @Test public void testGetSubmodelsOfParentType() throws Exception { ChildModel model = new ChildModel(); assertThat(model.getSubmodelsOfType(ParentModel.class)).containsExactly(model); } @Test public void testGetSubmodelsOfChildType() throws Exception { ParentModel model = new ParentModel(); assertThat(model.getSubmodelsOfType(ChildModel.class)).isEmpty(); } @Test public void testGetSubmodelsOfUnrelatedType() throws Exception { ParentModel model = new ParentModel(); assertThat(model.getSubmodelsOfType(OtherParentModel.class)).isEmpty(); } private static class ParentModel extends Model { @Override protected Model actUpon(Action action) { return null; } } private static class ChildModel extends ParentModel { @Override protected Model actUpon(Action action) { return null; } } public static class OtherParentModel extends Model { @Override protected Model actUpon(Action action) { return null; } } }","package org.granchi.hollywood; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import static com.google.common.truth.Truth.assertThat; @RunWith(MockitoJUnitRunner.class) public class ModelTest { @Test public void testGetSubmodelsOfSameType() throws Exception { ParentModel model = new ParentModel(); assertThat(model.getSubmodelsOfType(ParentModel.class)).containsExactly(model); } @Test public void testGetSubmodelsOfParentType() throws Exception { ChildModel model = new ChildModel(); assertThat(model.getSubmodelsOfType(ParentModel.class)).containsExactly(model); } @Test public void testGetSubmodelsOfChildType() throws Exception { ParentModel model = new ParentModel(); assertThat(model.getSubmodelsOfType(ChildModel.class)).isEmpty(); } @Test public void testGetSubmodelsOfUnrelatedType() throws Exception { ParentModel model = new ParentModel(); assertThat(model.getSubmodelsOfType(OtherParentModel.class)).isEmpty(); } private class ParentModel extends Model { @Override protected Model actUpon(Action action) { return null; } } private class ChildModel extends ParentModel { @Override protected Model actUpon(Action action) { return null; } } public class OtherParentModel extends Model { @Override protected Model actUpon(Action action) { return null; } } }" Fix for pagination only showing 30 results,"<?php namespace EdpGithub\ApiClient\Service; use EdpGithub\ApiClient\Model\Repo as RepoModel; class Repo extends AbstractService { // list of github allowed types for fetching repositories protected $allowedTypes = array( 'all', 'owner', 'public', 'private', 'member', ); public function listRepositories($username = null, $type = null) { $api = $this->getApiClient(); $params['access_token'] = $api->getOAuthToken(); //hotfix to display more then 30 results //@todo implement proper pagination $params['per_page'] = 100; if($type !== null) { if(!in_array($type, $this->allowedTypes)) { throw new Exception\DomainException(""Wrong type '$type' provided.""); } $params['type'] = $type; } if ($username == null) { $repos = $api->request('/user/repos', $params); } else { $repos = $this->getApiClient()->request('/users/' . $username . '/repos'); } return $this->hydrate($repos); } public function hydrate($repos) { $repoList = null; foreach($repos as $repo) { $repolist[] = new RepoModel($repo); } return $repolist; } } ","<?php namespace EdpGithub\ApiClient\Service; use EdpGithub\ApiClient\Model\Repo as RepoModel; class Repo extends AbstractService { // list of github allowed types for fetching repositories protected $allowedTypes = array( 'all', 'owner', 'public', 'private', 'member', ); public function listRepositories($username = null, $type = null) { $api = $this->getApiClient(); $params['access_token'] = $api->getOAuthToken(); if($type !== null) { if(!in_array($type, $this->allowedTypes)) { throw new Exception\DomainException(""Wrong type '$type' provided.""); } $params['type'] = $type; } if ($username == null) { $repos = $api->request('/user/repos', $params); } else { $repos = $this->getApiClient()->request('/users/' . $username . '/repos'); } return $this->hydrate($repos); } public function hydrate($repos) { $repoList = null; foreach($repos as $repo) { $repolist[] = new RepoModel($repo); } return $repolist; } } " Format parsed speed data for use in Chart.js,"import os import re import json class Parser(object): """"""Parse output from Speedtest CLI into JSON"""""" def parse_all(self): # needs: # labels (timestamps) # data (ping/dl/ul speed) records = [] labels = [] download_speeds = [] for file in os.listdir(""data""): if file.endswith("".speedtest.txt""): records.append(self.parse(""data/"" + file)) for record in records: labels.append(record[""timestamp""]) if record[""result""] == ""success"": download_speeds.append(record[""download""]) datasets = [{""label"":""Download Speeds"", ""data"":download_speeds}] summary = {} summary[""labels""] = labels summary[""datasets""] = datasets return json.dumps(summary) def parse(self, file): input = open(file, ""r"") data = input.read() input.close() timestamp = re.search(r'Speed Test Ran at: (.*)', data) ping = re.search(r'Ping: (.*)', data) download = re.search(r'Download: (.*) Mbit/s', data) upload = re.search(r'Upload: (.*)', data) record = {} if timestamp: record[""timestamp""] = timestamp.group(1) if ping: record[""result""] = ""success"" record[""ping""] = ping.group(1) record[""download""] = download.group(1) record[""upload""] = upload.group(1) else: record[""result""] = ""failure"" return record parser = Parser() print parser.parse_all() ","import os import re import json class Parser(object): """"""Parse output from Speedtest CLI into JSON"""""" def parse_all(self): records = [] for file in os.listdir(""data""): if file.endswith("".speedtest.txt""): records.append(self.parse(""data/"" + file)) return json.dumps(records) def parse(self, file): input = open(file, ""r"") data = input.read() input.close() timestamp = re.search(r'Speed Test Ran at: (.*)', data) ping = re.search(r'Ping: (.*)', data) download = re.search(r'Download: (.*)', data) upload = re.search(r'Upload: (.*)', data) record = {} if timestamp: record[""timestamp""] = timestamp.group(1) if ping: record[""result""] = ""success"" record[""ping""] = ping.group(1) record[""download""] = download.group(1) record[""upload""] = upload.group(1) else: record[""result""] = ""failure"" return record parser = Parser() print parser.parse_all() " Make unit test output neater.,"package org.kohsuke.github; import java.io.IOException; import org.junit.Test; /** * @author Martin van Zijl */ public class GHIssueEventTest extends AbstractGitHubApiTestBase { @Test public void testEventsForSingleIssue() throws Exception { GHRepository repo = getRepository(); GHIssue issue = repo.getIssue(1); System.out.println(""Single issue:""); for (GHIssueEvent event : issue.listEvents()) { System.out.println(event); } //TODO: Use the following... //GHIssueBuilder builder = repo.createIssue(""test from the api""); //GHIssue issue = builder.create(); } @Test public void testRepositoryEvents() throws Exception { GHRepository repo = getRepository(); PagedIterable<GHIssueEvent> list = repo.listIssueEvents(); System.out.println(""Repository (all):""); int i = 0; for (GHIssueEvent event : list.asList()) { System.out.println(event); if (i++ > 10) break; } } @Test public void testRepositorySingleEvent() throws Exception { GHRepository repo = getRepository(); GHIssueEvent event = repo.getIssueEvent(2615868520L); System.out.println(""Repository (single event):""); System.out.println(event); } protected GHRepository getRepository() throws IOException { return getRepository(gitHub); } private GHRepository getRepository(GitHub gitHub) throws IOException { return gitHub.getOrganization(""github-api-test-org"").getRepository(""github-api""); } } ","package org.kohsuke.github; import java.io.IOException; import org.junit.Test; /** * @author Martin van Zijl */ public class GHIssueEventTest extends AbstractGitHubApiTestBase { @Test public void testEventsForSingleIssue() throws Exception { GHRepository repo = getRepository(); GHIssue issue = repo.getIssue(1); for (GHIssueEvent event : issue.listEvents()) { System.out.println(event); } //TODO: Use the following... //GHIssueBuilder builder = repo.createIssue(""test from the api""); //GHIssue issue = builder.create(); } @Test public void testRepositoryEvents() throws Exception { GHRepository repo = getRepository(); PagedIterable<GHIssueEvent> list = repo.listIssueEvents(); for (GHIssueEvent event : list) { System.out.println(event); } } @Test public void testRepositorySingleEvent() throws Exception { GHRepository repo = getRepository(); GHIssueEvent event = repo.getIssueEvent(2615868520L); System.out.println(event); } protected GHRepository getRepository() throws IOException { return getRepository(gitHub); } private GHRepository getRepository(GitHub gitHub) throws IOException { return gitHub.getOrganization(""github-api-test-org"").getRepository(""github-api""); } } " Modify <button> format to 1 line,"import React from 'react'; import ClipboardJS from 'clipboard'; import 'balloon-css/balloon.css'; export default class CopyButton extends React.PureComponent { constructor(props) { super(props); this.copyBtnRef = React.createRef(); this.clipboardRef = React.createRef(); } static defaultProps = { content: '', }; state = { tooltipAttrs: {}, }; componentDidMount() { this.clipboardRef.current = new ClipboardJS(this.copyBtnRef.current, { text: () => this.props.content, }); this.clipboardRef.current.on('success', () => { const self = this; this.setState({ tooltipAttrs: { 'data-balloon': '複製成功!', 'data-balloon-visible': '', 'data-balloon-pos': 'up', }, }); setTimeout(function() { self.setState({ tooltipAttrs: {} }); }, 1000); }); } render() { const { tooltipAttrs } = this.state; return ( <button ref={this.copyBtnRef} className=""btn-copy"" {...tooltipAttrs}> 複製到剪貼簿 <style jsx>{` .btn-copy { margin-left: 10px; } `}</style> </button> ); } } ","import React from 'react'; import ClipboardJS from 'clipboard'; import 'balloon-css/balloon.css'; export default class CopyButton extends React.PureComponent { constructor(props) { super(props); this.copyBtnRef = React.createRef(); this.clipboardRef = React.createRef(); } static defaultProps = { content: '', }; state = { tooltipAttrs: {}, }; componentDidMount() { this.clipboardRef.current = new ClipboardJS(this.copyBtnRef.current, { text: () => this.props.content, }); this.clipboardRef.current.on('success', () => { const self = this; this.setState({ tooltipAttrs: { 'data-balloon': '複製成功!', 'data-balloon-visible': '', 'data-balloon-pos': 'up', }, }); setTimeout(function() { self.setState({ tooltipAttrs: {} }); }, 1000); }); } render() { const { tooltipAttrs } = this.state; return ( <button ref={this.copyBtnRef} className=""btn-copy"" {...tooltipAttrs} > 複製到剪貼簿 <style jsx>{` .btn-copy { margin-left: 10px; } `}</style> </button> ); } } " Fix another exception for ud when def isn't found,"""""""Looks up a term from urban dictionary @package ppbot @syntax ud <word> """""" import requests import json from modules import * class Urbandictionary(Module): def __init__(self, *args, **kwargs): """"""Constructor"""""" Module.__init__(self, kwargs=kwargs) self.url = ""http://www.urbandictionary.com/iphone/search/define?term=%s"" def _register_events(self): """"""Register module commands."""""" self.add_command('ud') def ud(self, event): """"""Action to react/respond to user calls."""""" if self.num_args >= 1: word = '%20'.join(event['args']) r = requests.get(self.url % (word)) ur = json.loads(r.text) try: definition = ur['list'][0] definition['definition'] = definition['definition'].replace(""\r"", "" "").replace(""\n"", "" "") definition['example'] = definition['example'].replace(""\r"", "" "").replace(""\n"", "" "") message = ""%(word)s (%(thumbs_up)d/%(thumbs_down)d): %(definition)s (ex: %(example)s)"" % (definition) self.msg(event['target'], message[:450]) except (IndexError, KeyError) as e: self.msg(event['target'], 'Could find word ""%s""' % ' '.join(event['args'])) else: self.syntax_message(event['nick'], '.ud <word>') ","""""""Looks up a term from urban dictionary @package ppbot @syntax ud <word> """""" import requests import json from modules import * class Urbandictionary(Module): def __init__(self, *args, **kwargs): """"""Constructor"""""" Module.__init__(self, kwargs=kwargs) self.url = ""http://www.urbandictionary.com/iphone/search/define?term=%s"" def _register_events(self): """"""Register module commands."""""" self.add_command('ud') def ud(self, event): """"""Action to react/respond to user calls."""""" if self.num_args >= 1: word = '%20'.join(event['args']) r = requests.get(self.url % (word)) ur = json.loads(r.text) try: definition = ur['list'][0] definition['definition'] = definition['definition'].replace(""\r"", "" "").replace(""\n"", "" "") definition['example'] = definition['example'].replace(""\r"", "" "").replace(""\n"", "" "") message = ""%(word)s (%(thumbs_up)d/%(thumbs_down)d): %(definition)s (ex: %(example)s)"" % (definition) self.msg(event['target'], message[:450]) except KeyError: self.msg(event['target'], 'Could find word ""%s""' % ' '.join(event['args'])) else: self.syntax_message(event['nick'], '.ud <word>') " Create story floating button is not shown if no contact is selected,"import React, { Component } from 'react' import CreateStoryButton from './CreateStoryButton' import Story from './Story' import reactCSS from 'reactcss' export default class StoryList extends Component { componentWillReceiveProps(props) { this.contents = null; if (props.selectedContactId.length) { if (props.stories.length > 0) { this.contents = props.stories.map(story => { return ( <Story key={story.id} id={story.id} title={story.title} text={story.text} handleDelete={() => { props.removeStory(props.selectedContactId, story.id) }} /> ) }) } else { this.contents = <h1 style={this.styles.title}>No stories found!</h1> } } } render() { this.styles = reactCSS({ default: { main: { padding: ""1em 2em 1em 2em"", width: ""100%"", height: ""100%"" }, title: { textAlign: ""center"", fontSize: ""24px"", fontStyle: ""normal"" } } }) return ( <div style={this.styles.main}> { this.contents } {this.props.selectedContactId.length ? <CreateStoryButton handleClick={() => { this.props.toggleStoryComposer() }} /> : null } </div> ) } }","import React, { Component } from 'react' import CreateStoryButton from './CreateStoryButton' import Story from './Story' import reactCSS from 'reactcss' export default class StoryList extends Component { componentWillReceiveProps(props) { this.contents = null; if (props.selectedContactId.length) { if (props.stories.length > 0) { this.contents = props.stories.map(story => { return ( <Story key={story.id} id={story.id} title={story.title} text={story.text} handleDelete={() => { props.removeStory(props.selectedContactId, story.id) }} /> ) }) } else { this.contents = <h1 style={this.styles.title}>No stories found!</h1> } } } render() { this.styles = reactCSS({ default: { main: { padding: ""1em 2em 1em 2em"", width: ""100%"", height: ""100%"" }, title: { textAlign: ""center"", fontSize: ""24px"", fontStyle: ""normal"" } } }) return ( <div style={this.styles.main}> { this.contents } <CreateStoryButton handleClick={() => { this.props.toggleStoryComposer() }} /> </div> ) } }" Fix method comment parameter signature.,"<?php namespace Orbt\ResourceMirror\Resource; /** * A collection of resource objects. */ class Collection implements \IteratorAggregate { /** * Resource collection array. * @var array */ protected $collection = array(); /** * {@inheritdoc} */ public function getIterator() { return new \ArrayIterator($this->collection); } /** * Adds a new resource. * * @param \Orbt\ResourceMirror\Resource\Resource $resource * Resource object. * @return static * This collection, for fluent interface. * * @throws \InvalidArgumentException * If the given object is not a resource object. */ public function add($resource) { if (!$resource instanceof Resource) { throw new \InvalidArgumentException('Resource has the wrong type.'); } $this->collection[] = $resource; return $this; } /** * Removes a resource. * * @param Resource $resource * Resource object to remove. * @return static * This collection, for fluent interface. */ public function remove($resource) { $keysToRemove = array_keys($this->collection, $resource, true); $this->collection = array_values(array_diff_key($this->collection, array_flip($keysToRemove))); return $this; } /** * Returns the collection. */ public function getAll() { return $this->collection; } } ","<?php namespace Orbt\ResourceMirror\Resource; /** * A collection of resource objects. */ class Collection implements \IteratorAggregate { /** * Resource collection array. * @var array */ protected $collection = array(); /** * {@inheritdoc} */ public function getIterator() { return new \ArrayIterator($this->collection); } /** * Adds a new resource. * * @param Resource $resource * Resource object. * @return static * This collection, for fluent interface. * * @throws \InvalidArgumentException * If the given object is not a resource object. */ public function add($resource) { if (!$resource instanceof Resource) { throw new \InvalidArgumentException('Resource has the wrong type.'); } $this->collection[] = $resource; return $this; } /** * Removes a resource. * * @param Resource $resource * Resource object to remove. * @return static * This collection, for fluent interface. */ public function remove($resource) { $keysToRemove = array_keys($this->collection, $resource, true); $this->collection = array_values(array_diff_key($this->collection, array_flip($keysToRemove))); return $this; } /** * Returns the collection. */ public function getAll() { return $this->collection; } } " "Update app list view for application status Add the application status, not just the judged status. This is important for the admin since they see unsubmitted applications. Signed-off-by: Marc Jones <bb1304e98184a66f7e15848bfbd0ff1c09583089@gmail.com> (cherry picked from commit 86195f70374a720e6f15e0ea8f0a965554b36296) Signed-off-by: Marc Jones <bb1304e98184a66f7e15848bfbd0ff1c09583089@gmail.com>","@extends('app') @section('content') <h1>All Applications</h1> <hr> <table class=""table table-hover""> <thead> <tr> <th>Name</th> <th>Applicant</th> <th>Status</th> <th>Judge Status</th> <th>Score</th> <th>Date Created</th> <th>Date Modified</th> </tr> </thead> <tbody> @foreach($applications as $application) <tr> <td> @if($application->status == 'new') <a href=""/applications/{{ $application->id }}"">{{ $application->name }}</a> @else <a href=""/applications/{{ $application->id }}/review"">{{ $application->name }}</a> @endif </td> <td>{{ $application->user->name }}</td> <td>{{ $application->status }}</td> <td>{{ $application->judge_status }}</td> <td>{{ $application->objective_score }} / {{ $application->subjective_score }} / {{ $application->total_score }}</td> <td>{{ $application->created_at->format('Y-m-d') }}</td> <td>{{ $application->updated_at->format('Y-m-d') }}</td> </tr> @endforeach </tbody> </table> @endsection ","@extends('app') @section('content') <h1>All Applications</h1> <hr> <table class=""table table-hover""> <thead> <tr> <th>Name</th> <th>Applicant</th> <th>Judge Status</th> <th>Score</th> <th>Date Created</th> <th>Date Modified</th> </tr> </thead> <tbody> @foreach($applications as $application) <tr> <td> @if($application->status == 'new') <a href=""/applications/{{ $application->id }}"">{{ $application->name }}</a> @else <a href=""/applications/{{ $application->id }}/review"">{{ $application->name }}</a> @endif </td> <td>{{ $application->user->name }}</td> <td>{{ $application->judge_status }}</td> <td>{{ $application->objective_score }} / {{ $application->subjective_score }} / {{ $application->total_score }}</td> <td>{{ $application->created_at->format('Y-m-d') }}</td> <td>{{ $application->updated_at->format('Y-m-d') }}</td> </tr> @endforeach </tbody> </table> @endsection " Fix registration of new member,"<?php namespace GeneaLabs\LaravelGovernor\Listeners; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Schema; use GeneaLabs\LaravelGovernor\Role; class CreatedListener { /** * @SuppressWarnings(PHPMD.StaticAccess) */ public function handle(string $event, array $models) { if (str_contains($event, ""Hyn\Tenancy\Models\Website"") || str_contains($event, ""Hyn\Tenancy\Models\Hostname"") ) { return; } collect($models) ->filter(function ($model) { return $model instanceof Model && get_class($model) === config('genealabs-laravel-governor.models.auth'); }) ->each(function ($model) { try { $model->roles()->syncWithoutDetaching('Member'); } catch (Exception $exception) { $roleClass = config(""genealabs-laravel-governor.models.role""); (new $roleClass)->firstOrCreate([ 'name' => 'Member', 'description' => 'Represents the baseline registered user. Customize permissions as best suits your site.', ]); $model->roles()->attach('Member'); } }); } } ","<?php namespace GeneaLabs\LaravelGovernor\Listeners; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Schema; use GeneaLabs\LaravelGovernor\Role; class CreatedListener { /** * @SuppressWarnings(PHPMD.StaticAccess) */ public function handle(string $event, array $models) { if (str_contains($event, ""Hyn\Tenancy\Models\Website"") || str_contains($event, ""Hyn\Tenancy\Models\Hostname"") ) { return; } collect($models) ->filter(function ($model) { return $model instanceof Model && get_class($model) === config('genealabs-laravel-governor.models.auth'); }) ->each(function ($model) { try { $model->roles()->attach('Member'); } catch (Exception $exception) { $roleClass = config(""genealabs-laravel-governor.models.role""); (new $roleClass)->firstOrCreate([ 'name' => 'Member', 'description' => 'Represents the baseline registered user. Customize permissions as best suits your site.', ]); $model->roles()->attach('Member'); } }); } } " Save selected workspace state into store,"import React, { PropTypes } from 'react' import { View, ListView, StyleSheet } from 'react-native' import { Actions } from 'react-native-router-flux' import WorkspaceRow from './WorkspaceRow' import store from '../store/store' const WorkspaceSelectionList = ({ onWorkspaceSelection }) => { const listData = [ {label:'Workspace 1'}, {label:'Workspace 2'}, {label:'Workspace 3'}, {label:'Workspace 4'}, ] const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}) const dataSource = ds.cloneWithRows(listData) contextTypes = { routes: PropTypes.object.isRequired, }; const onPress = (label) => { Actions.editQuery() onWorkspaceSelection(label); console.log(store.getState()) } return( <View style={styles.container}> <ListView dataSource={dataSource} renderRow={ (rowData) => <WorkspaceRow onPress={() => onPress(rowData.label)} {...rowData} />} /> </View> ) } WorkspaceSelectionList.propTypes = { // todos: PropTypes.arrayOf(PropTypes.shape({ // label: PropTypes.string.isRequired // }).isRequired).isRequired, onWorkspaceSelection: PropTypes.func.isRequired, routes: PropTypes.object, } const styles = StyleSheet.create({ listContent: { flex: 1, alignSelf: 'stretch' }, container: { flex: 1 } }); export default WorkspaceSelectionList ","import React, { PropTypes } from 'react' import { View, ListView, StyleSheet } from 'react-native' import { Actions } from 'react-native-router-flux' import WorkspaceRow from './WorkspaceRow' const WorkspaceSelectionList = ({ onWorkspaceSelection }) => { const listData = [ {label:'Workspace 1'}, {label:'Workspace 2'}, {label:'Workspace 3'}, {label:'Workspace 4'}, ] const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}) const dataSource = ds.cloneWithRows(listData) contextTypes = { routes: PropTypes.object.isRequired, }; const onPress = () => { console.log(""Test""); Actions.editQuery() onWorkspaceSelection(""default""); } return( <View style={styles.container}> <ListView dataSource={dataSource} renderRow={ (rowData) => <WorkspaceRow onPress={onPress} {...rowData} />} /> </View> ) } WorkspaceSelectionList.propTypes = { onWorkspaceSelection: PropTypes.func.isRequired, routes: PropTypes.object, } const styles = StyleSheet.create({ listContent: { flex: 1, alignSelf: 'stretch' }, container: { flex: 1 } }); export default WorkspaceSelectionList " Allow auditors to CR comments in context,"# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: anze@reciprocitylabs.com # Maintained By: anze@reciprocitylabs.com scope = ""Audit"" description = """""" The permissions required by an auditor to access relevant resources for the program being audited. """""" permissions = { ""read"": [ ""Audit"", ""Request"", ""ControlAssessment"", ""Issue"", ""DocumentationResponse"", ""InterviewResponse"", ""PopulationSampleResponse"", ""Meeting"", ""ObjectDocument"", ""ObjectPerson"", ""Relationship"", ""Document"", ""Meeting"", ""UserRole"", ""Comment"", ""Context"", ], ""create"": [ ""Request"", ""ControlAssessment"", ""Issue"", ""Relationship"", ""DocumentationResponse"", ""InterviewResponse"", ""PopulationSampleResponse"", ""Comment"", ], ""view_object_page"": [ ""__GGRC_ALL__"" ], ""update"": [ ""Request"", ""ControlAssessment"", ""Issue"", ""DocumentationResponse"", ""InterviewResponse"", ""PopulationSampleResponse"" ], ""delete"": [ ""Request"", ""ControlAssessment"", ""Issue"", ""DocumentationResponse"", ""InterviewResponse"", ""PopulationSampleResponse"", ], } ","# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: anze@reciprocitylabs.com # Maintained By: anze@reciprocitylabs.com scope = ""Audit"" description = """""" The permissions required by an auditor to access relevant resources for the program being audited. """""" permissions = { ""read"": [ ""Audit"", ""Request"", ""ControlAssessment"", ""Issue"", ""DocumentationResponse"", ""InterviewResponse"", ""PopulationSampleResponse"", ""Meeting"", ""ObjectDocument"", ""ObjectPerson"", ""Relationship"", ""Document"", ""Meeting"", ""UserRole"", ""Context"", ], ""create"": [ ""Request"", ""ControlAssessment"", ""Issue"", ""Relationship"", ""DocumentationResponse"", ""InterviewResponse"", ""PopulationSampleResponse"", ], ""view_object_page"": [ ""__GGRC_ALL__"" ], ""update"": [ ""Request"", ""ControlAssessment"", ""Issue"", ""DocumentationResponse"", ""InterviewResponse"", ""PopulationSampleResponse"" ], ""delete"": [ ""Request"", ""ControlAssessment"", ""Issue"", ""DocumentationResponse"", ""InterviewResponse"", ""PopulationSampleResponse"", ], } " Bring user profile defaults management command up to date,"from django.conf import settings from django.contrib.auth.models import User from django.core.management.base import NoArgsCommand, CommandError from optparse import make_option class Command(NoArgsCommand): help = ""Set the user profile settings of every user to the defaults"" option_list = NoArgsCommand.option_list + ( make_option('--update-anon-user', dest='update-anon-user', default=False, action='store_true', help='Update also the profile of the anonymous user'), ) def handle_noargs(self, **options): update_anon_user = 'update-anon-user' in options for u in User.objects.all(): # Ignore the anonymous user by default if u.id == settings.ANONYMOUS_USER_ID and not update_anon_user: continue up = u.userprofile # Expect user profiles to be there and add all default settings up.inverse_mouse_wheel = settings.PROFILE_DEFAULT_INVERSE_MOUSE_WHEEL up.independent_ontology_workspace_is_default = \ settings.PROFILE_INDEPENDENT_ONTOLOGY_WORKSPACE_IS_DEFAULT up.show_text_label_tool = settings.PROFILE_SHOW_TEXT_LABEL_TOOL up.show_tagging_tool = settings.PROFILE_SHOW_TAGGING_TOOL up.show_cropping_tool = settings.PROFILE_SHOW_CROPPING_TOOL up.show_segmentation_tool = settings.PROFILE_SHOW_SEGMENTATION_TOOL up.show_tracing_tool = settings.PROFILE_SHOW_TRACING_TOOL up.show_ontology_tool = settings.PROFILE_SHOW_ONTOLOGY_TOOL # Save the changes up.save() ","from django.conf import settings from django.contrib.auth.models import User from django.core.management.base import NoArgsCommand, CommandError from optparse import make_option class Command(NoArgsCommand): help = ""Set the user profile settings of every user to the defaults"" option_list = NoArgsCommand.option_list + ( make_option('--update-anon-user', dest='update-anon-user', default=False, action='store_true', help='Update also the profile of the anonymous user'), ) def handle_noargs(self, **options): update_anon_user = 'update-anon-user' in options for u in User.objects.all(): # Ignore the anonymous user by default if u.id == settings.ANONYMOUS_USER_ID and not update_anon_user: continue up = u.userprofile # Expect user profiles to be there and add all default settings up.inverse_mouse_wheel = settings.PROFILE_DEFAULT_INVERSE_MOUSE_WHEEL up.show_text_label_tool = settings.PROFILE_SHOW_TEXT_LABEL_TOOL up.show_tagging_tool = settings.PROFILE_SHOW_TAGGING_TOOL up.show_cropping_tool = settings.PROFILE_SHOW_CROPPING_TOOL up.show_segmentation_tool = settings.PROFILE_SHOW_SEGMENTATION_TOOL up.show_tracing_tool = settings.PROFILE_SHOW_TRACING_TOOL # Save the changes up.save() " Move editor-related setup into event handler so it only runs after the editor has been initialized,"(function(){ zeit.cms.declare_namespace('zeit.edit'); zeit.edit.FoldBlock = gocept.Class.extend({ construct: function(context) { var self = this; var id = context.getAttribute('href'); MochiKit.DOM.toggleElementClass('folded', id); sessionStorage['folding.' + id] = MochiKit.DOM.hasElementClass(id, 'folded')?'yes':''; }, // @staticmethod restore_folding: function() { forEach( $$('a[cms\:cp-module=""zeit.edit.FoldBlock""]'), function(action) { var id = action.getAttribute('href'); if (sessionStorage['folding.' + id]) { log(""Restore folding=on for"", id); MochiKit.DOM.addElementClass(id, 'folded'); } else { log(""Restore folding=off for"", id); MochiKit.DOM.removeElementClass(id, 'folded'); } }); } }); MochiKit.Signal.connect( window, 'cp-editor-loaded', function() { MochiKit.Signal.connect( zeit.edit.editor, 'after-reload', function() { zeit.edit.FoldBlock.prototype.restore_folding(); }); }); })();","(function(){ zeit.cms.declare_namespace('zeit.edit'); zeit.edit.FoldBlock = gocept.Class.extend({ construct: function(context) { var self = this; var id = context.getAttribute('href'); MochiKit.DOM.toggleElementClass('folded', id); sessionStorage['folding.' + id] = MochiKit.DOM.hasElementClass(id, 'folded')?'yes':''; }, // @staticmethod restore_folding: function() { forEach( $$('a[cms\:cp-module=""zeit.edit.FoldBlock""]'), function(action) { var id = action.getAttribute('href'); if (sessionStorage['folding.' + id]) { log(""Restore folding=on for"", id); MochiKit.DOM.addElementClass(id, 'folded'); } else { log(""Restore folding=off for"", id); MochiKit.DOM.removeElementClass(id, 'folded'); } }); } }); MochiKit.Signal.connect( zeit.edit.editor, 'after-reload', function() { zeit.edit.FoldBlock.prototype.restore_folding(); }); })();" "Allow post urls without slugs to be transformed * Modify for post_id -> post_ident in route dynamic segment","App.RawTransform = DS.Transform.extend({ deserialize: function(serialized) { return serialized; }, serialize: function(deserialized) { return deserialized; } }); App.ArrayTransform = App.RawTransform.extend({}); App.TimestampTransform = DS.NumberTransform.extend({}); App.ChoiceTransform = DS.StringTransform.extend(); App.TumblrStringTransform = DS.StringTransform.extend({ deserialize: function(serialized){ 'use strict'; var deserialized = this._super(serialized), self = this, router = this.container.lookup('router:main'), url; // return if null if (Ember.isNone(deserialized)) return null; // reformat tumblr urls appropriately return deserialized.replace(/href=""http:\/\/([^\.]*).tumblr.com\/([^""]*)""/g, function(orig, blog_name, path, idx, full){ if (!Em.isEmpty(path)){ path = /post\/(\d+)\/?(.*)?/.exec(path); var post_ident = path[1], post_slug = path[2]; url = router.router.recognizer.generate('single_post', { blog_name: blog_name, post_ident: post_ident, post_slug: post_slug }); } else { url = router.router.recognizer.generate('single_blog', {blog_name: blog_name}); } url = router.get('location').formatURL(url); if (url.charAt(0) !== '/') { url = '/' + url; } return 'href=""%@""'.fmt(url); }); } }); ","App.RawTransform = DS.Transform.extend({ deserialize: function(serialized) { return serialized; }, serialize: function(deserialized) { return deserialized; } }); App.ArrayTransform = App.RawTransform.extend({}); App.TimestampTransform = DS.NumberTransform.extend({}); App.ChoiceTransform = DS.StringTransform.extend(); App.TumblrStringTransform = DS.StringTransform.extend({ deserialize: function(serialized){ 'use strict'; var deserialized = this._super(serialized), self = this, router = this.container.lookup('router:main'), url; // return if null if (Ember.isNone(deserialized)) return null; // reformat tumblr urls appropriately return deserialized.replace(/href=""http:\/\/([^\.]*).tumblr.com\/([^""]*)""/g, function(orig, blog_name, path, idx, full){ if (!Em.isEmpty(path)){ path = /post\/(\d+)\/(.*)?/.exec(path); var post_ident = path[1], post_slug = path[2]; url = router.router.recognizer.generate('single_post', { blog_name: blog_name, post_id: post_ident, post_slug: post_slug }); } else { url = router.router.recognizer.generate('single_blog', {blog_name: blog_name}); } url = router.get('location').formatURL(url); if (url.charAt(0) !== '/') { url = '/' + url; } return 'href=""%@""'.fmt(url); }); } }); " "Update priority of Content-Type listener - Should happen between authorization (-600) and validation (-650)","<?php /** * @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause * @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com) */ namespace ZF\ContentNegotiation; use Zend\Mvc\MvcEvent; class Module { /** * {@inheritDoc} */ public function getAutoloaderConfig() { return array( 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/src/', ), ), ); } /** * {@inheritDoc} */ public function getConfig() { return include __DIR__ . '/config/module.config.php'; } /** * {@inheritDoc} */ public function onBootstrap($e) { $app = $e->getApplication(); $services = $app->getServiceManager(); $em = $app->getEventManager(); $em->attach(MvcEvent::EVENT_ROUTE, new ContentTypeListener(), -625); $sem = $em->getSharedManager(); $sem->attach( 'Zend\Stdlib\DispatchableInterface', MvcEvent::EVENT_DISPATCH, $services->get('ZF\ContentNegotiation\AcceptListener'), -10 ); $sem->attachAggregate($services->get('ZF\ContentNegotiation\AcceptFilterListener')); $sem->attachAggregate($services->get('ZF\ContentNegotiation\ContentTypeFilterListener')); } } ","<?php /** * @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause * @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com) */ namespace ZF\ContentNegotiation; use Zend\Mvc\MvcEvent; class Module { /** * {@inheritDoc} */ public function getAutoloaderConfig() { return array( 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/src/', ), ), ); } /** * {@inheritDoc} */ public function getConfig() { return include __DIR__ . '/config/module.config.php'; } /** * {@inheritDoc} */ public function onBootstrap($e) { $app = $e->getApplication(); $services = $app->getServiceManager(); $em = $app->getEventManager(); $em->attach(MvcEvent::EVENT_ROUTE, new ContentTypeListener(), -99); $sem = $em->getSharedManager(); $sem->attach( 'Zend\Stdlib\DispatchableInterface', MvcEvent::EVENT_DISPATCH, $services->get('ZF\ContentNegotiation\AcceptListener'), -10 ); $sem->attachAggregate($services->get('ZF\ContentNegotiation\AcceptFilterListener')); $sem->attachAggregate($services->get('ZF\ContentNegotiation\ContentTypeFilterListener')); } } " Fix the bug once and for all,"var addFollowers = require('./follow'); var checkAuth = require('./check_auth'); var checkPrivilege = require('./privilege_check'); var githubOAuth = require('./github_oauth'); var users = require('./db').get('users'); module.exports = function(app) { app.get('/me', checkAuth, function(req, res) { checkPrivilege(req.session.user.login, function(err, privilege) { users.find({ following: req.session.user.login }, function(err, following) { res.json({ privilege: privilege, following: following }); }); }); }); app.get('/user', checkAuth, function(req, res) { return res.json(req.session.user); }); app.post('/follow/:login', checkAuth, function(req, res) { checkPrivilege(req.session.user.login, function(err, privilege) { users.findOne({ login: req.session.user.login }, function(error, user) { var amount = privilege.count; if (user.following) { amount -= user.following.length; } addFollowers(req.session.user.login, amount, function(err, result) { res.json(result); }); }); }); }); githubOAuth.addRoutes(app, function(err, token, res, ignore, req) { if (token.error) { return res.send('There was an error logging in: ' + token.error_description); } req.session.token = token.access_token; res.redirect('/'); }); }; ","var addFollowers = require('./follow'); var checkAuth = require('./check_auth'); var checkPrivilege = require('./privilege_check'); var githubOAuth = require('./github_oauth'); var users = require('./db').get('users'); module.exports = function(app) { app.get('/me', checkAuth, function(req, res) { checkPrivilege(req.session.user.login, function(err, privilege) { users.find({ following: req.session.user.login }, function(err, following) { res.json({ privilege: privilege, following: following }); }); }); }); app.get('/user', checkAuth, function(req, res) { return res.json(req.session.user); }); app.post('/follow/:login', checkAuth, function(req, res) { checkPrivilege(req.session.user.login, function(err, privilege) { users.findOne({ login: req.session.user.login }, function(error, user) { var amount = privilege.following; if (user.following) { amount -= user.following.length; } addFollowers(req.session.user.login, amount, function(err, result) { res.json(result); }); }); }); }); githubOAuth.addRoutes(app, function(err, token, res, ignore, req) { if (token.error) { return res.send('There was an error logging in: ' + token.error_description); } req.session.token = token.access_token; res.redirect('/'); }); }; " Select recursive tests - karma,"const webpackConfig = require(""../webpack.config.js""); delete webpackConfig.entry; delete webpackConfig.output; webpackConfig.mode = ""development""; const browsers = [""FirefoxHeadless""]; if (process.env.CI) { browsers.push(""CustomChrome""); } module.exports = function (config) { config.set({ basePath: ""../"", frameworks: [""mocha"", ""chai"", ""sinon""], plugins: [ require(""karma-webpack""), require(""karma-chrome-launcher""), require(""karma-firefox-launcher""), require(""karma-mocha""), require(""karma-chai""), require(""karma-sinon""), require(""karma-spec-reporter"") ], files: [""test/web/**/*.spec.js""], exclude: [], preprocessors: { ""src/**/*.ts"": [""webpack""], ""test/web/**/*.spec.js"": [""webpack""] }, reporters: [""spec"", ""progress""], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: false, customLaunchers: { CustomChrome: { base: ""ChromeHeadless"", flags: [""--disable-web-security""], debug: true } }, browsers, webpack: webpackConfig, singleRun: true }); }; ","const webpackConfig = require(""../webpack.config.js""); delete webpackConfig.entry; delete webpackConfig.output; webpackConfig.mode = ""development""; const browsers = [""FirefoxHeadless""]; if (process.env.CI) { browsers.push(""CustomChrome""); } module.exports = function (config) { config.set({ basePath: ""../"", frameworks: [""mocha"", ""chai"", ""sinon""], plugins: [ require(""karma-webpack""), require(""karma-chrome-launcher""), require(""karma-firefox-launcher""), require(""karma-mocha""), require(""karma-chai""), require(""karma-sinon""), require(""karma-spec-reporter"") ], files: [""test/web/*.spec.js""], exclude: [], preprocessors: { ""src/**/*.ts"": [""webpack""], ""test/web/**/*.spec.js"": [""webpack""] }, reporters: [""spec"", ""progress""], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: false, customLaunchers: { CustomChrome: { base: ""ChromeHeadless"", flags: [""--disable-web-security""], debug: true } }, browsers, webpack: webpackConfig, singleRun: true }); }; " Fix issue where fonts aren't actually getting injected.,"import {SVGRenderer} from 'scratch-svg-renderer'; // Contains 'font-family', but doesn't only contain 'font-family=""none""' const HAS_FONT_REGEXP = 'font-family(?!=""none"")'; const getCostumeUrl = (function () { let cachedAssetId; let cachedUrl; return function (assetId, vm) { if (cachedAssetId === assetId) { return cachedUrl; } cachedAssetId = assetId; const storage = vm.runtime.storage; const asset = storage.get(assetId); // If the SVG refers to fonts, they must be inlined in order to display correctly in the img tag. // Avoid parsing the SVG when possible, since it's expensive. if (asset.assetType === storage.AssetType.ImageVector) { const svgString = vm.runtime.storage.get(assetId).decodeText(); if (svgString.match(HAS_FONT_REGEXP)) { const svgRenderer = new SVGRenderer(); svgRenderer.loadString(svgString); const svgText = svgRenderer.toString(true /* shouldInjectFonts */); cachedUrl = `data:image/svg+xml;utf8,${encodeURIComponent(svgText)}`; } else { cachedUrl = vm.runtime.storage.get(assetId).encodeDataURI(); } } else { cachedUrl = vm.runtime.storage.get(assetId).encodeDataURI(); } return cachedUrl; }; }()); export { getCostumeUrl as default, HAS_FONT_REGEXP }; ","import {SVGRenderer} from 'scratch-svg-renderer'; // Contains 'font-family', but doesn't only contain 'font-family=""none""' const HAS_FONT_REGEXP = 'font-family(?!=""none"")'; const getCostumeUrl = (function () { let cachedAssetId; let cachedUrl; return function (assetId, vm) { if (cachedAssetId === assetId) { return cachedUrl; } cachedAssetId = assetId; const storage = vm.runtime.storage; const asset = storage.get(assetId); // If the SVG refers to fonts, they must be inlined in order to display correctly in the img tag. // Avoid parsing the SVG when possible, since it's expensive. if (asset.assetType === storage.AssetType.ImageVector) { const svgString = vm.runtime.storage.get(assetId).decodeText(); if (svgString.match(HAS_FONT_REGEXP)) { const svgRenderer = new SVGRenderer(); svgRenderer.loadString(svgString); const svgText = svgRenderer.toString(true /* shouldInjectFonts */); cachedUrl = `data:image/svg+xml;utf8,${encodeURIComponent(svgText)}`; } cachedUrl = vm.runtime.storage.get(assetId).encodeDataURI(); } cachedUrl = vm.runtime.storage.get(assetId).encodeDataURI(); return cachedUrl; }; }()); export { getCostumeUrl as default, HAS_FONT_REGEXP }; " Return empty string if file extension don't match," 'use strict'; var path = require('path'); var fs = require('fs'); var through = require('through2'); var glob = require('glob'); module.exports = function() { var process = function(filename) { var replaceString = ''; if (fs.statSync(filename).isDirectory()) { // Ignore directories start with _ if (path.basename(filename).substring(0, 1) == '_') return ''; fs.readdirSync(filename).forEach(function (file) { replaceString += process(filename + path.sep + file); }); return replaceString; } else { if (filename.substr(-4).match(/sass|scss/i)) { return '@import ""' + filename + '"";\n' } else { return ''; } } } var transform = function(file, env, cb) { // find all instances matching var contents = file.contents.toString('utf-8'); var reg = /@import\s+\""([^\""]*\*[^\""]*)\"";/; var result; while((result = reg.exec(contents)) !== null) { var index = result.index; var sub = result[0]; var globName = result[1]; var files = glob.sync(file.base + globName); var replaceString = ''; files.forEach(function(filename){ replaceString += process(filename); }); contents = contents.replace(sub, replaceString); } file.contents = new Buffer(contents); cb(null, file); }; return through.obj(transform); }; "," 'use strict'; var path = require('path'); var fs = require('fs'); var through = require('through2'); var glob = require('glob'); module.exports = function() { var process = function(filename) { var replaceString = ''; if (fs.statSync(filename).isDirectory()) { // Ignore directories start with _ if (path.basename(filename).substring(0, 1) == '_') return ''; fs.readdirSync(filename).forEach(function (file) { replaceString += process(filename + path.sep + file); }); return replaceString; } else { if (filename.substr(-4).match(/sass|scss/i)) { return '@import ""' + filename + '"";\n' } } } var transform = function(file, env, cb) { // find all instances matching var contents = file.contents.toString('utf-8'); var reg = /@import\s+\""([^\""]*\*[^\""]*)\"";/; var result; while((result = reg.exec(contents)) !== null) { var index = result.index; var sub = result[0]; var globName = result[1]; var files = glob.sync(file.base + globName); var replaceString = ''; files.forEach(function(filename){ replaceString += process(filename); }); contents = contents.replace(sub, replaceString); } file.contents = new Buffer(contents); cb(null, file); }; return through.obj(transform); }; " Use addData() to append the app object to the plates engine,"<?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 \League\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'] = function ($app) { $plates = $app['plates.engine']; $plates->addData([ '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 \League\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 = $app['plates.engine']; $plates->app = $app; return $plates; }); } public function boot(Application $app) { } } " Handle cases where there are multiple values for a field.," from rest_framework import status from rest_framework.exceptions import APIException def json_api_exception_handler(exc, context): """""" Custom exception handler that returns errors object as an array """""" # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node ""title"" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, list): for reason in value: errors.append({'detail': reason, 'meta': {'field': key}}) else: errors.append({'detail': value, 'meta': {'field': key}}) elif isinstance(message, (list, tuple)): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') "," from rest_framework import status from rest_framework.exceptions import APIException def json_api_exception_handler(exc, context): """""" Custom exception handler that returns errors object as an array """""" # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node ""title"" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, list): value = value[0] errors.append({'detail': value, 'meta': {'field': key}}) elif isinstance(message, (list, tuple)): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') " Fix semicolon :/ in info_retriever,"# LING 573 Question Answering System # Code last updated 4/17/14 by Clara Gordon # This code implements an InfoRetriever for the question answering system. from pymur import * from general_classes import * class InfoRetriever: # builds a QueryEnvironment associated with the indexed document collection def __init__(self, index_path): # how to get this to link up to the doc collection? self.path_to_idx = index_path self.index = new Index(self.path_to_idx) self.query_env = QueryEnvironment() self.query_env.addIndex(self.path_to_idx) # creates a list of all the passages returned by all the queries generated by # the query-processing module def retrieve_passages(self, queries): passages = [] for query in queries: # second argument is the number of documents desired docs = self.query_env.runQuery(""#combine[passage50:25]("" + query + "")"", 20) for doc in docs: doc_num = doc.document begin = doc.begin end = doc.end doc_id = self.query_env.documents([doc_num])[0].metadata['docno'] # need this for output passage = Passage(self.index.document(doc_num, True)[begin, end], doc.score, doc_id) passages.append(passage) return passages ","# LING 573 Question Answering System # Code last updated 4/17/14 by Clara Gordon # This code implements an InfoRetriever for the question answering system. from pymur import * from general_classes import * class InfoRetriever: # builds a QueryEnvironment associated with the indexed document collection def __init__(self, index_path): # how to get this to link up to the doc collection? self.path_to_idx = index_path self.index = new Index(self.path_to_idx); self.query_env = QueryEnvironment() self.query_env.addIndex(self.path_to_idx) # creates a list of all the passages returned by all the queries generated by # the query-processing module def retrieve_passages(self, queries): passages = [] for query in queries: # second argument is the number of documents desired docs = self.query_env.runQuery(""#combine[passage50:25]("" + query + "")"", 20) for doc in docs: doc_num = doc.document begin = doc.begin end = doc.end doc_id = self.query_env.documents([doc_num])[0].metadata['docno'] # need this for output passage = Passage(self.index.document(doc_num, True)[begin, end], doc.score, doc_id) passages.append(passage) return passages " Reorder imports in alphabetical order,"from docker.errors import APIError from flask import request, jsonify, make_response from flask_restplus import Resource, fields, Namespace, Api from graphqlapi.exceptions import RequestException from graphqlapi.proxy import proxy_request def register_graphql(namespace: Namespace, api: Api): """"""Method used to register the GraphQL namespace and endpoint."""""" # Create expected headers and payload headers = api.parser() payload = api.model('Payload', {'query': fields.String( required=True, description='GraphQL query or mutation', example='{allIndicatorTypes{nodes{id,name}}}')}) @namespace.route('/graphql', endpoint='with-parser') @namespace.doc() class GraphQL(Resource): @namespace.expect(headers, payload, validate=True) def post(self): """""" Execute GraphQL queries and mutations Use this endpoint to send http request to the GraphQL API. """""" payload = request.json try: status, response = proxy_request(payload) return make_response(jsonify(response), status) except RequestException as ex: return ex.to_response() except APIError as apiError: return make_response(jsonify({'message': apiError.explanation}), apiError.status_code) ","from graphqlapi.proxy import proxy_request from graphqlapi.interceptor import RequestException from flask_restplus import Resource, fields, Namespace, Api from docker.errors import APIError from flask import request, jsonify, make_response def register_graphql(namespace: Namespace, api: Api): """"""Method used to register the GraphQL namespace and endpoint."""""" # Create expected headers and payload headers = api.parser() payload = api.model('Payload', {'query': fields.String( required=True, description='GraphQL query or mutation', example='{allIndicatorTypes{nodes{id,name}}}')}) @namespace.route('/graphql', endpoint='with-parser') @namespace.doc() class GraphQL(Resource): @namespace.expect(headers, payload, validate=True) def post(self): """""" Execute GraphQL queries and mutations Use this endpoint to send http request to the GraphQL API. """""" payload = request.json try: status, response = proxy_request(payload) return make_response(jsonify(response), status) except RequestException as ex: return ex.to_response() except APIError as apiError: return make_response(jsonify({'message': apiError.explanation}), apiError.status_code) " Fix test runner for trunk,"#!/usr/bin/env python import sys from os.path import abspath, dirname import django from django.conf import settings 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 except: from django.test.simple import DjangoTestSuiteRunner failures = DjangoTestSuiteRunner(failfast=False).run_tests(['tests']) else: failures = DiscoverRunner(failfast=False).run_tests( ['email_log.tests']) sys.exit(failures) if __name__ == ""__main__"": runtests() ","#!/usr/bin/env python import sys from os.path import abspath, dirname import django from django.conf import settings 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', SOUTH_MIGRATION_MODULES={ 'email_log': 'email_log.south_migrations', }, ) def runtests(): if hasattr(django, 'setup'): django.setup() from django.test.simple import DjangoTestSuiteRunner failures = DjangoTestSuiteRunner(failfast=False).run_tests(['tests']) sys.exit(failures) if __name__ == ""__main__"": runtests() " Create final willow-main.js under dist/,"var path = require('path'); var webpack = require('webpack'); // sass-loader needs this require('es6-promise').polyfill(); module.exports = { entry: [ 'webpack-hot-middleware/client', // WebpackDevServer host and port 'babel-polyfill', './ui/js/willow-main' ], output: { publicPath: '/', path: path.join(__dirname, '/dist/js'), filename: 'willow-main.js' }, resolve: { extensions: ['', '.jsx', '.js', '.json'], modulesDirectories: ['node_modules', 'ui/js'] }, module: { loaders: [ { loaders: [ 'react-hot', 'babel?' + JSON.stringify({ plugins: [['transform-runtime']], presets: ['stage-0', 'es2015', 'react'] }) ], // Skip any files outside of your project's `src` directory include: [ path.resolve(__dirname, ""ui""), ], // Only run `.js` and `.jsx` files through Babel test: /\.jsx?$/, }, { test: /\.scss$/, loader: 'style!css!sass' } ] }, devtool: 'source-map', debug: true, plugins: [ new webpack.HotModuleReplacementPlugin() ] }","var path = require('path'); var webpack = require('webpack'); // sass-loader needs this require('es6-promise').polyfill(); module.exports = { entry: [ 'webpack-hot-middleware/client', // WebpackDevServer host and port 'babel-polyfill', './ui/js/willow-main' ], output: { publicPath: '/', path: path.join(__dirname, '/ui'), filename: 'willow-main.js' }, resolve: { extensions: ['', '.jsx', '.js', '.json'], modulesDirectories: ['node_modules', 'ui/js'] }, module: { loaders: [ { loaders: [ 'react-hot', 'babel?' + JSON.stringify({ plugins: [['transform-runtime']], presets: ['stage-0', 'es2015', 'react'] }) ], // Skip any files outside of your project's `src` directory include: [ path.resolve(__dirname, ""ui""), ], // Only run `.js` and `.jsx` files through Babel test: /\.jsx?$/, }, { test: /\.scss$/, loader: 'style!css!sass' } ] }, devtool: 'source-map', debug: true, plugins: [ new webpack.HotModuleReplacementPlugin() ] }" Use store true in db creation script,"#!/usr/bin/env python3 from database import db from database import bdb from database import bdb_refseq from import_data import import_data import argparse def restet_relational_db(): print('Removing relational database...') db.reflect() db.drop_all() print('Removing relational database completed.') print('Recreating relational database...') db.create_all() print('Recreating relational database completed.') def reset_mappings_db(): print('Removing mappigns database...') bdb.reset() bdb_refseq.reset() print('Removing mapings database completed.') if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '-i', '--import_mappings', action='store_true', help='Should mappings be (re)imported' ) parser.add_argument( '-r', '--reload_relational', action='store_true', help='Should relational database be (re)imported' ) args = parser.parse_args() if args.import_mappings: reset_mappings_db() if args.reload_relational: restet_relational_db() if args.reload_relational or args.import_mappings: print('Importing data') import_data( import_mappings=args.import_mappings, reload_relational=args.reload_relational ) print('Importing completed') print('Done, all tasks completed.') else: print('This script should be run from command line') ","#!/usr/bin/env python3 from database import db from database import bdb from database import bdb_refseq from import_data import import_data import argparse def restet_relational_db(): print('Removing relational database...') db.reflect() db.drop_all() print('Removing relational database completed.') print('Recreating relational database...') db.create_all() print('Recreating relational database completed.') def reset_mappings_db(): print('Removing mappigns database...') bdb.reset() bdb_refseq.reset() print('Removing mapings database completed.') if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '-i', '--import_mappings', default=False, help='Should mappings be (re)imported' ) parser.add_argument( '-r', '--reload_relational', default=False, help='Should relational database be (re)imported' ) args = parser.parse_args() if args.import_mappings: reset_mappings_db() if args.reload_relational: restet_relational_db() if args.reload_relational or args.import_mappings: print('Importing data') import_data( import_mappings=args.import_mappings, reload_relational=args.reload_relational ) print('Importing completed') print('Done, all tasks completed.') else: print('This script should be run from command line') " Fix content localizator - able to return null values,"<?php namespace Milax\Mconsole\Processors; use Milax\Mconsole\Contracts\ContentLocalizator as Repository; use Milax\Mconsole\Models\Compiled; class ContentLocalizator implements Repository { public function localize($object, $lang = null) { $lang = is_null($lang) ? config('app.locale') : $lang; $attributes = $object->getAttributes(); $compiled = new Compiled; foreach ($attributes as $key => $value) { $hasLanguages = false; $value = $object->$key; switch (gettype($value)) { case 'array': if (array_has($value, $lang)) { $hasLanguages = true; } break; case 'string': $value = json_decode($value, true); if (json_last_error() === JSON_ERROR_NONE) { if (array_has($value, $lang)) { $hasLanguages = true; } } break; default: continue; } if ($hasLanguages) { if (!is_array($value[$lang]) && strlen($value[$lang]) == 0) { $compiled->$key = null; } else { $compiled->$key = $value[$lang]; } } } return $compiled; } } ","<?php namespace Milax\Mconsole\Processors; use Milax\Mconsole\Contracts\ContentLocalizator as Repository; use Milax\Mconsole\Models\Compiled; class ContentLocalizator implements Repository { public function localize($object, $lang = null) { $lang = is_null($lang) ? config('app.locale') : $lang; $attributes = $object->getAttributes(); $compiled = new Compiled; foreach ($attributes as $key => $value) { $hasLanguages = false; $value = $object->$key; switch (gettype($value)) { case 'array': if (isset($value[$lang])) { $hasLanguages = true; } break; case 'string': $value = json_decode($value, true); if (json_last_error() === JSON_ERROR_NONE) { if (isset($value[$lang])) { $hasLanguages = true; } } break; default: continue; } if ($hasLanguages) { if (!is_array($value[$lang]) && strlen($value[$lang]) == 0) { $compiled->$key = null; } else { $compiled->$key = $value[$lang]; } } } return $compiled; } } " Remove ternary to fix linting,"import React from 'react' import Placeholder from '../Placeholder' import {decrypt} from '../../utils/crypto' export default class EncryptedImage extends React.PureComponent { state = { src: '', status: 'fetching', error: null } componentDidMount() { this.fetchAndDecryptImage() } error(status, err) { this.setState({status: status, error: err}) console.error(err) } fetchAndDecryptImage() { fetch(this.props.src) .then((response) => { if (!response.ok) throw response.status this.setState({status: 'decrypting'}) response.arrayBuffer() .then((body) => { decrypt(body) .then((decrypted) => { this.setState({ src: `data:image/jpeg;base64,${btoa(decrypted)}`, status: 'ready' }) }) .catch((err) => { this.error('error:decrypting', err) }) }) }) .catch((err) => { this.error('error:fetching', err) }) } render() { if (this.state.status === 'ready') { return ( <img src={this.state.src} title={this.props.title} alt={this.props.title} /> ) } else { return ( <Placeholder status={this.state.status} title={this.props.title} error={this.state.error} /> ) } } } ","import React from 'react' import Placeholder from '../Placeholder' import {decrypt} from '../../utils/crypto' export default class EncryptedImage extends React.PureComponent { state = { src: '', status: 'fetching', error: null } componentDidMount() { this.fetchAndDecryptImage() } error(status, err) { this.setState({status: status, error: err}) console.error(err) } fetchAndDecryptImage() { fetch(this.props.src) .then((response) => { if (!response.ok) throw response.status this.setState({status: 'decrypting'}) response.arrayBuffer() .then((body) => { decrypt(body) .then((decrypted) => { this.setState({ src: `data:image/jpeg;base64,${btoa(decrypted)}`, status: 'ready' }) }) .catch((err) => { this.error('error:decrypting', err) }) }) }) .catch((err) => { this.error('error:fetching', err) }) } render() { return this.state.status === 'ready' ? ( <img src={this.state.src} title={this.props.title} alt={this.props.title} /> ) : ( <Placeholder status={this.state.status} title={this.props.title} error={this.state.error} /> ) } } " Improve detection of complete deployment,"<?php namespace Guttmann\NautCli\Service; use GuzzleHttp\Client; class DeployLogService { public function streamLog(Client $client, $streamLink) { /** @var \GuzzleHttp\Cookie\CookieJar $cookieJar */ $cookieJar = $client->getConfig('cookies'); $cookieStrings = []; foreach ($cookieJar->toArray() as $cookie) { $cookieStrings[] = $cookie['Name'] . '=' . $cookie['Value'] . ';'; } $context = stream_context_create([ 'http' => [ 'method' => 'GET', 'header' => 'Cookie: ' . implode(' ', $cookieStrings) . ""\r\n"" ] ]); $timeout = 30; $output = ''; while ($timeout > 0) { $lastOutput = $output; $output = file_get_contents($streamLink, 'r', $context); $printableOutput = str_replace($lastOutput, '', $output); if ($printableOutput === '') { $timeout -= 1; } else { $timeout = 30; } echo $printableOutput; if (preg_match('/deploy of "".*"" to "".*"" finished/i', $printableOutput) === 1) { return; } else { sleep(1); } } echo PHP_EOL . 'Streaming deploy log timed out. Maybe the deployment failed?' . PHP_EOL; exit(1); } } ","<?php namespace Guttmann\NautCli\Service; use GuzzleHttp\Client; class DeployLogService { public function streamLog(Client $client, $streamLink) { /** @var \GuzzleHttp\Cookie\CookieJar $cookieJar */ $cookieJar = $client->getConfig('cookies'); $cookieStrings = []; foreach ($cookieJar->toArray() as $cookie) { $cookieStrings[] = $cookie['Name'] . '=' . $cookie['Value'] . ';'; } $context = stream_context_create([ 'http' => [ 'method' => 'GET', 'header' => 'Cookie: ' . implode(' ', $cookieStrings) . ""\r\n"" ] ]); $timeout = 10; $output = ''; while ($timeout > 0) { $lastOutput = $output; $output = file_get_contents($streamLink, 'r', $context); $printableOutput = str_replace($lastOutput, '', $output); if ($printableOutput === '') { $timeout -= 1; } else { $timeout = 10; } echo $printableOutput; sleep(1); } echo PHP_EOL . 'No contact with stream for 10 seconds, assumed finished.' . PHP_EOL; } } " Add install of bower dependencies,"(function() { 'use strict'; var yeoman = require('yeoman-generator'), scaffold = {}; module.exports = yeoman.generators.Base.extend({ constructor: function() { yeoman.generators.Base.apply(this, arguments); this.option('skip-welcome'); this.argument('runType', { type: String, required: false }); scaffold = require('../../scaffold')(this); this.isBuild = typeof this.runType !== 'undefined' && this.runType.toLowerCase() === 'build'; }, initializing: function() { var message = 'Starting development mode. I will start a server with BrowserSync support. :)'; if (this.isBuild) { message = 'Starting build view. I will start a server with BrowserSync support. :)'; } if (!this.options['skip-welcome']) { scaffold.welcomeMessage(' Running project ', message); } }, install: function() { scaffold.log('Installing Bower dependencies...', 'yellow'); this.bowerInstall('', this.async); }, end: function() { if (this.isBuild) { this.spawnCommand('grunt', ['serve']); return false; } this.spawnCommand('grunt', ['default']); } }); })(); ","(function() { 'use strict'; var yeoman = require('yeoman-generator'), scaffold = {}; module.exports = yeoman.generators.Base.extend({ constructor: function() { yeoman.generators.Base.apply(this, arguments); this.option('skip-welcome'); this.argument('runType', { type: String, required: false }); scaffold = require('../../scaffold')(this); this.isBuild = typeof this.runType !== 'undefined' && this.runType.toLowerCase() === 'build'; }, initializing: function() { var message = 'Starting development mode. I will start a server with BrowserSync support. :)'; if (this.isBuild) { message = 'Starting build view. I will start a server with BrowserSync support. :)'; } if (!this.options['skip-welcome']) { scaffold.welcomeMessage(' Running project ', message); } }, install: function() { if (this.isBuild) { this.spawnCommand('grunt', ['serve']); return false; } this.spawnCommand('grunt', ['default']); } }); })(); " Add convenience function to read tempdir files.,"from mock import patch import pytest import os import shutil import tempfile class Directory: def __init__(self, directory): self.directory = directory def __getitem__(self, name): path = os.path.join(self.directory, name) assert not os.path.relpath(path, self.directory).startswith('..') return File(path) class File: def __init__(self, path): self.directory = os.path.dirname(path) self.path = path def fill(self, content): if not os.path.exists(self.directory): os.makedirs(self.directory) with open(self.path, 'w') as f: if isinstance(content, (list, tuple)): content = '\n'.join(content) f.write(content) def content(self): with open(self.path) as f: return f.read() @pytest.yield_fixture def tempdir(): """""" Returns an object for easy use of a temporary directory which is cleaned up afterwards. Use tempdir[filepath] to access files. Use .fill(lines) on the returned object to write content to the file. """""" directory = tempfile.mkdtemp() yield Directory(directory) shutil.rmtree(directory) @pytest.yield_fixture def ployconf(tempdir): """""" Returns a Configfile object which manages ploy.conf. """""" yield tempdir['etc/ploy.conf'] @pytest.yield_fixture def os_execvp_mock(): with patch(""os.execvp"") as os_execvp_mock: yield os_execvp_mock ","from mock import patch import pytest import os import shutil import tempfile class Directory: def __init__(self, directory): self.directory = directory def __getitem__(self, name): path = os.path.join(self.directory, name) assert not os.path.relpath(path, self.directory).startswith('..') return File(path) class File: def __init__(self, path): self.directory = os.path.dirname(path) self.path = path def fill(self, content): if not os.path.exists(self.directory): os.makedirs(self.directory) with open(self.path, 'w') as f: if isinstance(content, (list, tuple)): content = '\n'.join(content) f.write(content) @pytest.yield_fixture def tempdir(): """""" Returns an object for easy use of a temporary directory which is cleaned up afterwards. Use tempdir[filepath] to access files. Use .fill(lines) on the returned object to write content to the file. """""" directory = tempfile.mkdtemp() yield Directory(directory) shutil.rmtree(directory) @pytest.yield_fixture def ployconf(tempdir): """""" Returns a Configfile object which manages ploy.conf. """""" yield tempdir['etc/ploy.conf'] @pytest.yield_fixture def os_execvp_mock(): with patch(""os.execvp"") as os_execvp_mock: yield os_execvp_mock " "Use --path instead of --realpath Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>","<?php namespace Laravie\Authen\Tests; use Orchestra\Testbench\TestCase as BaseTestCase; abstract class TestCase extends BaseTestCase { /** * Setup the test environment. */ protected function setUp(): void { parent::setUp(); $this->withFactories(__DIR__.'/factories'); $this->loadMigrationsFrom([ '--database' => 'testing', '--path' => realpath(__DIR__.'/migrations'), ]); } /** * Get package providers. * * @param \Illuminate\Foundation\Application $app * * @return array */ protected function getPackageProviders($app) { return [ \Laravie\Authen\AuthenServiceProvider::class, \Laravie\Authen\Tests\Stubs\AuthServiceProvider::class, ]; } /** * Define environment setup. * * @param \Illuminate\Foundation\Application $app * * @return void */ protected function getEnvironmentSetUp($app) { $config = $app->make('config'); $config->set([ 'auth.providers.users' => [ 'driver' => 'authen', 'model' => \Laravie\Authen\Tests\Stubs\User::class, ], ]); } } ","<?php namespace Laravie\Authen\Tests; use Orchestra\Testbench\TestCase as BaseTestCase; abstract class TestCase extends BaseTestCase { /** * Setup the test environment. */ protected function setUp(): void { parent::setUp(); $this->withFactories(__DIR__.'/factories'); $this->loadMigrationsFrom([ '--database' => 'testing', '--realpath' => realpath(__DIR__.'/migrations'), ]); } /** * Get package providers. * * @param \Illuminate\Foundation\Application $app * * @return array */ protected function getPackageProviders($app) { return [ \Laravie\Authen\AuthenServiceProvider::class, \Laravie\Authen\Tests\Stubs\AuthServiceProvider::class, ]; } /** * Define environment setup. * * @param \Illuminate\Foundation\Application $app * * @return void */ protected function getEnvironmentSetUp($app) { $config = $app->make('config'); $config->set([ 'auth.providers.users' => [ 'driver' => 'authen', 'model' => \Laravie\Authen\Tests\Stubs\User::class, ], ]); } } " Edit intro evals data route,"from flask import Blueprint from flask import render_template from flask import request intro_evals_bp = Blueprint('intro_evals_bp', __name__) @intro_evals_bp.route('/intro_evals/') def display_intro_evals(): # get user data user_name = request.headers.get('x-webauth-user') members = [ { 'name': ""Liam Middlebrook"", 'packet_due': '2015-12-23', 'eval_date': '2016-02-13', 'signatures_missed': 3, 'committee_meetings': 24, 'committee_meetings_passed': False, 'house_meetings_missed': [{'date': ""aprial fools fayas ads"", 'reason': ""I was playing videogames""}], 'technical_seminars': [{'date': ""halloween"", 'name': 'how to play videogames with liam'}], 'social_events': """", 'freshmen_project': False, 'comments': ""please don't fail me"", 'result': 'Pending' } ] # return names in 'first last (username)' format return render_template('intro_evals.html', username = user_name, members = members) ","from flask import Blueprint from flask import render_template from flask import request intro_evals_bp = Blueprint('intro_evals_bp', __name__) @intro_evals_bp.route('/intro_evals/') def display_intro_evals(): # get user data user_name = request.headers.get('x-webauth-user') members = [ { 'name': ""Liam Middlebrook"", 'packet_due': '2015-12-23', 'eval_date': '2016-02-13', 'signatures_missed': 3, 'committee_meetings': 24, 'committee_meetings_passed': False, 'house_meetings_missed': 0, 'house_meetings_comments': """", 'technical_seminars': ""Seminar 1\nSeminar 2"", 'techincal_seminars_passed': True, 'social_events': """", 'freshmen_project': False, 'comments': ""please don't fail me"", 'result': 'Pending' } ] # return names in 'first last (username)' format return render_template('intro_evals.html', username = user_name, members = members) " Use dictionary get() method to access 'detail'," from rest_framework import status from rest_framework.exceptions import APIException def json_api_exception_handler(exc, context): """""" Custom exception handler that returns errors object as an array """""" from rest_framework.views import exception_handler response = exception_handler(exc, context) # Title removed to avoid clash with node ""title"" errors acceptable_members = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response is not None: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in acceptable_members: errors.append({key: value}) else: errors.append({'detail': {key: value}}) elif isinstance(message, list): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} # Return 401 instead of 403 during unauthorized requests without having user log in with Basic Auth if response is not None and response.data['errors'][0].get('detail') == ""Authentication credentials were not provided."": response.status_code = 401 return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') "," from rest_framework import status from rest_framework.exceptions import APIException def json_api_exception_handler(exc, context): """""" Custom exception handler that returns errors object as an array """""" from rest_framework.views import exception_handler response = exception_handler(exc, context) # Title removed to avoid clash with node ""title"" errors acceptable_members = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response is not None: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in acceptable_members: errors.append({key: value}) else: errors.append({'detail': {key: value}}) elif isinstance(message, list): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} # Return 401 instead of 403 during unauthorized requests without having user log in with Basic Auth if response is not None and response.data['errors'][0]['detail'] == ""Authentication credentials were not provided."": response.status_code = 401 return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') " Bugfix: Update exception when YAML couldn't be parsed,"<?php namespace Just\SonataThemeBundle\DependencyInjection; use RuntimeException; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; use Symfony\Component\Yaml\Exception\ParseException; use Symfony\Component\Yaml\Yaml; /** * This is the class that loads and manages your bundle configuration. * * @link http://symfony.com/doc/current/cookbook/bundles/extension.html */ class JustSonataThemeExtension extends Extension implements PrependExtensionInterface { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $this->processConfiguration($configuration, $configs); } /** * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container */ public function prepend(ContainerBuilder $container) { $bundles = $container->getParameter('kernel.bundles'); if (!array_key_exists('SonataAdminBundle', $bundles)) { throw new RuntimeException('SonataAdminBundle wasn\'t found, dit you registered it correctly?'); } try { $config = Yaml::parse(file_get_contents(__DIR__ . '/../Resources/config/theme.yml')); } catch (ParseException $e) { throw new RuntimeException(sprintf(""Unable to parse the YAML string: %s"", $e->getMessage())); } $container->prependExtensionConfig('sonata_admin', $config); } } ","<?php namespace Just\SonataThemeBundle\DependencyInjection; use RuntimeException; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; use Symfony\Component\Yaml\Exception\ParseException; use Symfony\Component\Yaml\Yaml; /** * This is the class that loads and manages your bundle configuration. * * @link http://symfony.com/doc/current/cookbook/bundles/extension.html */ class JustSonataThemeExtension extends Extension implements PrependExtensionInterface { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $this->processConfiguration($configuration, $configs); } /** * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container */ public function prepend(ContainerBuilder $container) { $bundles = $container->getParameter('kernel.bundles'); if (!array_key_exists('SonataAdminBundle', $bundles)) { throw new RuntimeException('SonataAdminBundle wasn\'t found, dit you registered it correctly?'); } try { $config = Yaml::parse(file_get_contents(__DIR__ . '/../Resources/config/theme.yml')); } catch (ParseException $e) { printf(""Unable to parse the YAML string: %s"", $e->getMessage()); } $container->prependExtensionConfig('sonata_admin', $config); } } " Use default text when no data exists for query,"var scripts = document.getElementsByTagName('script'), script = scripts[scripts.length - 1], report = JSON.parse(script.getAttribute('data-report')), type = script.getAttribute('data-type'); google.load('visualization', '1.0', {'packages':['corechart']}); google.setOnLoadCallback(drawChart); function drawChart() { if(report.length > 1) { var chart_height = (report.length - 1) * 20, reverse = type === 'week' ? true : false, wrapper = new google.visualization.ChartWrapper({ chartType: 'BarChart', dataTable: google.visualization.arrayToDataTable(report), options: { chartArea: { bottom: 50, height: chart_height, left: '10%', right: '10%', top: 50, width: '90%' }, height: chart_height + 100, legend: { alignment: 'center', position: 'top' }, reverseCategories: reverse }, containerId: 'chart' }); wrapper.draw(); } else if (report.length === 1) { var container = $('#chart'), text = $('<p>No data to display.</p>'); container.append(text); } } ","var scripts = document.getElementsByTagName('script'), script = scripts[scripts.length - 1], report = JSON.parse(script.getAttribute('data-report')), type = script.getAttribute('data-type'); google.load('visualization', '1.0', {'packages':['corechart']}); google.setOnLoadCallback(drawChart); function drawChart() { if(report.length > 1) { var chart_height = (report.length - 1) * 20, reverse = type === 'week' ? true : false, wrapper = new google.visualization.ChartWrapper({ chartType: 'BarChart', dataTable: google.visualization.arrayToDataTable(report), options: { chartArea: { bottom: 50, height: chart_height, left: '10%', right: '10%', top: 50, width: '90%' }, height: chart_height + 100, legend: { alignment: 'center', position: 'top' }, reverseCategories: reverse }, containerId: 'chart' }); wrapper.draw(); } else { container = $('#chart'); container.text(''); } } " Fix error message when svgexport is not installed,"var Promise = require('./promise'); var command = require('./command'); var fs = require('./fs'); var error = require('./error'); // Convert a svg file to a pmg function convertSVGToPNG(source, dest, options) { if (!command.isAvailable) return Promise.reject(new Error('Could not convert SVG in this platform')); if (!fs.existsSync(source)) return Promise.reject(new error.FileNotFoundError({ filename: source })); return command.spawn('svgexport', [source, dest]) .fail(function(err) { if (err.code == 'ENOENT') { err = error.RequireInstallError({ cmd: 'svgexport', install: 'Install it using: ""npm install svgexport -g""' }); } throw err; }) .then(function() { if (fs.existsSync(dest)) return; throw new Error('Error converting '+source+' into '+dest); }); } // Convert a svg buffer to a png file function convertSVGBufferToPNG(buf, dest) { // Create a temporary SVG file to convert return fs.tmpFile({ postfix: '.svg' }) .then(function(tmpSvg) { return fs.writeFile(tmpSvg, buf) .then(function() { return convertSVGToPNG(tmpSvg, dest); }); }); } module.exports = { convertSVGToPNG: convertSVGToPNG, convertSVGBufferToPNG: convertSVGBufferToPNG };","var Promise = require('./promise'); var command = require('./command'); var fs = require('./fs'); var error = require('./error'); // Convert a svg file to a pmg function convertSVGToPNG(source, dest, options) { if (!command.isAvailable) return Promise.reject(new Error('Could not convert SVG in this platform')); if (!fs.existsSync(source)) return Promise.reject(new error.FileNotFoundError({ filename: source })); return command.spawn('svgexport', [source, dest]) .fail(function(err) { if (err.code == 'ENOENT') { error.RequireInstallError({ cmd: 'svgexport', install: 'Install it using: ""npm install svgexport -g""' }); } throw err; }) .then(function() { if (fs.existsSync(dest)) return; throw new Error('Error converting '+source+' into '+dest); }); } // Convert a svg buffer to a png file function convertSVGBufferToPNG(buf, dest) { // Create a temporary SVG file to convert return fs.tmpFile({ postfix: '.svg' }) .then(function(tmpSvg) { return fs.writeFile(tmpSvg, buf) .then(function() { return convertSVGToPNG(tmpSvg, dest); }); }); } module.exports = { convertSVGToPNG: convertSVGToPNG, convertSVGBufferToPNG: convertSVGBufferToPNG };" Install no longer runs shim,"<?php namespace Vagrant\Shim\Command; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class InstallCommand extends Command { protected function configure() { $this ->setName('install') ->setDescription('Symlink vagrant-shim to a directory in $PATH') ->addArgument('path', InputArgument::OPTIONAL, '<comment>Default</comment>: <info>/usr/local/bin</info>') ; } protected function execute(InputInterface $input, OutputInterface $output) { $path = $input->getArgument('path') ?: '/usr/local/bin'; if ($this->manager->isInstalled()) { $output->write(sprintf('Uninstalling from <info>%s</info>...', join('</info>, <info>', $this->manager->getInstalledPaths()))); if ($this->manager->uninstall()) { $output->writeln('<comment>SUCCESS</comment>'); } else { $output->writeln('<error>FAILED</error>'); return 1; } } $output->write(sprintf('Installing to <info>%s</info>...', $path)); if ($this->manager->install($path)) { $output->writeln('<comment>SUCCESS</comment>'); } else { $output->writeln('<error>FAILED</error>'); return 1; } } } ","<?php namespace Vagrant\Shim\Command; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class InstallCommand extends Command { protected function configure() { $this ->setName('install') ->setDescription('Symlink vagrant-shim to a directory in $PATH') ->addArgument('path', InputArgument::OPTIONAL, '<comment>Default</comment>: <info>/usr/local/bin</info>') ; } protected function execute(InputInterface $input, OutputInterface $output) { $path = $input->getArgument('path') ?: '/usr/local/bin'; if ($this->manager->isInstalled()) { $output->write(sprintf('Uninstalling from <info>%s</info>...', join('</info>, <info>', $this->manager->getInstalledPaths()))); if ($this->manager->uninstall()) { $output->writeln('<comment>SUCCESS</comment>'); } else { $output->writeln('<error>FAILED</error>'); return 1; } } $output->write(sprintf('Installing to <info>%s</info>...', $path)); if ($this->manager->install($path)) { $output->writeln('<comment>SUCCESS</comment>'); } else { $output->writeln('<error>FAILED</error>'); return 1; } // Run ""shim"" $command = $this->getApplication()->find('shim'); $command->run(new ArrayInput(array('command' => 'shim')), $output); } } " "Fix selection of the submit button in the createNewPerson wdio test The test was failing because of not being able to find the button.","import Page from './page' const Page_URL = '/people/new' class CreatePerson extends Page { get form() { return browser.element('form') } get alertSuccess() { return browser.element('.alert-success') } get lastName() { return browser.element('#lastName') } get firstName() { return browser.element('#firstName') } get rolePrincipalButton() { return browser.element('#rolePrincipalButton') } get roleAdvisorButton() { return browser.element('#roleAdvisorButton') } get emailAddress() { return browser.element('#emailAddress') } get phoneNumber() { return browser.element('#phoneNumber') } get rank() { return browser.element('#rank') } get gender() { return browser.element('#gender') } get country() { return browser.element('#country') } get endOfTourDate() { return browser.element('#endOfTourDate') } get biography() { return browser.element('.biography .text-editor p') } get submitButton() { return browser.element('#formBottomSubmit') } open() { super.openAsSuperUser(Page_URL) } waitForAlertSuccessToLoad() { if(!this.alertSuccess.isVisible()) { this.alertSuccess.waitForExist() this.alertSuccess.waitForVisible() } } submitForm() { this.submitButton.click() } } export default new CreatePerson() ","import Page from './page' const Page_URL = '/people/new' class CreatePerson extends Page { get form() { return browser.element('form') } get alertSuccess() { return browser.element('.alert-success') } get lastName() { return browser.element('#lastName') } get firstName() { return browser.element('#firstName') } get rolePrincipalButton() { return browser.element('#rolePrincipalButton') } get roleAdvisorButton() { return browser.element('#roleAdvisorButton') } get emailAddress() { return browser.element('#emailAddress') } get phoneNumber() { return browser.element('#phoneNumber') } get rank() { return browser.element('#rank') } get gender() { return browser.element('#gender') } get country() { return browser.element('#country') } get endOfTourDate() { return browser.element('#endOfTourDate') } get biography() { return browser.element('.biography .text-editor p') } get submitButton() { return browser.element('form .form-top-submit > button[type=""submit""]') } open() { super.openAsSuperUser(Page_URL) } waitForAlertSuccessToLoad() { if(!this.alertSuccess.isVisible()) { this.alertSuccess.waitForExist() this.alertSuccess.waitForVisible() } } submitForm() { this.submitButton.click() } } export default new CreatePerson() " Fix proxy incorrectly proxying requests for files a level deeper than intended,"var path = require('path'); var fs = require('fs'); var mime = require('mime'); var pattern = function (file, included) { return {pattern: file, included: included, served: true, watched: false}; }; var framework = function (files) { files.push(pattern(path.join(__dirname, 'framework.js'), false)); files.push(pattern(path.join(__dirname, 'runner.js'), true)); }; var createProxyForDirectory = function (directory) { return function (request, response, next) { if (!request.url.startsWith('/base/')) { var filePath = path.join(directory, request.url); fs.exists(filePath, function (exists) { if (exists) { response.writeHead(200, { ""Content-Type"": mime.lookup(filePath) }); fs.createReadStream(filePath).pipe(response); } else { next(); } }); } else { next(); } } }; var proxyBowerComponentsMiddlewareFactory = function () { return createProxyForDirectory('bower_components'); }; var proxyNodeModulesMiddlewareFactory = function () { return createProxyForDirectory('node_modules'); }; framework.$inject = ['config.files']; module.exports = { 'framework:web-components': ['factory', framework], 'middleware:proxy-bower-components': ['factory', proxyBowerComponentsMiddlewareFactory], 'middleware:proxy-node-modules': ['factory', proxyNodeModulesMiddlewareFactory] };","var path = require('path'); var fs = require('fs'); var mime = require('mime'); var pattern = function (file, included) { return {pattern: file, included: included, served: true, watched: false}; }; var framework = function (files) { files.push(pattern(path.join(__dirname, 'framework.js'), false)); files.push(pattern(path.join(__dirname, 'runner.js'), true)); }; var createProxyForDirectory = function (directory) { return function (request, response, next) { var filePath = path.join(directory, request.url.replace('/base/', '')); fs.exists(filePath, function (exists) { if (exists) { response.writeHead(200, { ""Content-Type"": mime.lookup(filePath) }); fs.createReadStream(filePath).pipe(response); } else { next(); } }); } }; var proxyBowerComponentsMiddlewareFactory = function () { return createProxyForDirectory('bower_components'); }; var proxyNodeModulesMiddlewareFactory = function () { return createProxyForDirectory('node_modules'); }; framework.$inject = ['config.files']; module.exports = { 'framework:web-components': ['factory', framework], 'middleware:proxy-bower-components': ['factory', proxyBowerComponentsMiddlewareFactory], 'middleware:proxy-node-modules': ['factory', proxyNodeModulesMiddlewareFactory] };" Update deps and bump version. ANL-10319,"from setuptools import setup import io import os here = os.path.abspath(os.path.dirname(__file__)) def read(*filenames, **kwargs): encoding = kwargs.get('encoding', 'utf-8') sep = kwargs.get('sep', '\n') buf = [] for filename in filenames: with io.open(filename, encoding=encoding) as f: buf.append(f.read()) return sep.join(buf) long_description = read('README.md') setup( name='mongo-pool', version='0.5.0', url='http://github.com/ubervu/mongo-pool/', description='The tool that keeps all your mongos in one place', long_description=long_description, license='Apache Software License', author='UberVU', author_email=""development@ubervu.com"", install_requires=['pymongo>=3.6.1', 'six>=1.15.0'], packages=['mongo_pool'], include_package_data=True, platforms='any', test_suite='nose.collector', tests_require=['nose', 'mock'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Database', 'Topic :: Software Development :: Libraries :: Python Modules', ], extras_require={ 'testing': ['nose', 'mock'], } ) ","from setuptools import setup import io import os here = os.path.abspath(os.path.dirname(__file__)) def read(*filenames, **kwargs): encoding = kwargs.get('encoding', 'utf-8') sep = kwargs.get('sep', '\n') buf = [] for filename in filenames: with io.open(filename, encoding=encoding) as f: buf.append(f.read()) return sep.join(buf) long_description = read('README.md') setup( name='mongo-pool', version='0.4.2', url='http://github.com/ubervu/mongo-pool/', description='The tool that keeps all your mongos in one place', long_description=long_description, license='Apache Software License', author='UberVU', author_email=""development@ubervu.com"", install_requires=['pymongo>=3.0.3'], packages=['mongo_pool'], include_package_data=True, platforms='any', test_suite='nose.collector', tests_require=['nose', 'mock'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Database', 'Topic :: Software Development :: Libraries :: Python Modules', ], extras_require={ 'testing': ['nose'], } ) " Allow never version of fudge (1.0.3 and up),"import re from distribute_setup import use_setuptools use_setuptools() from setuptools import setup version = None for line in open('./soundcloud/__init__.py'): m = re.search('__version__\s*=\s*(.*)', line) if m: version = m.group(1).strip()[1:-1] # quotes break assert version setup( name='soundcloud', version=version, description='A friendly wrapper library for the Soundcloud API', author='Paul Osman', author_email='osman@soundcloud.com', url='https://github.com/soundcloud/soundcloud-python', license='BSD', packages=['soundcloud'], include_package_data=True, use_2to3=True, package_data={ '': ['README.rst'] }, install_requires=[ 'fudge>=1.0.3', 'requests>=0.14.0', 'simplejson>=2.0', ], tests_require=[ 'nose>=1.1.2', ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet', 'Topic :: Multimedia :: Sound/Audio', 'Topic :: Software Development :: Libraries :: Python Modules', ] ) ","import re from distribute_setup import use_setuptools use_setuptools() from setuptools import setup version = None for line in open('./soundcloud/__init__.py'): m = re.search('__version__\s*=\s*(.*)', line) if m: version = m.group(1).strip()[1:-1] # quotes break assert version setup( name='soundcloud', version=version, description='A friendly wrapper library for the Soundcloud API', author='Paul Osman', author_email='osman@soundcloud.com', url='https://github.com/soundcloud/soundcloud-python', license='BSD', packages=['soundcloud'], include_package_data=True, use_2to3=True, package_data={ '': ['README.rst'] }, install_requires=[ 'fudge==1.0.3', 'requests>=0.14.0', 'simplejson>=2.0', ], tests_require=[ 'nose>=1.1.2', ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet', 'Topic :: Multimedia :: Sound/Audio', 'Topic :: Software Development :: Libraries :: Python Modules', ] ) " Fix gui not updating the pocket name after rename;,"/** * @fileOverview PocketCreateCtrl angular controller */ define(['./module', 'darkwallet'], function (controllers, DarkWallet) { 'use strict'; controllers.controller('PocketCreateCtrl', ['$scope', function($scope) { /** * Scope variables */ $scope.newPocket = {}; $scope.creatingPocket = false; /** * Create a pocket */ $scope.createPocket = function() { if ($scope.creatingPocket && $scope.newPocket.name) { var identity = DarkWallet.getIdentity(); // create pocket identity.wallet.pockets.createPocket($scope.newPocket.name); var pocketIndex = identity.wallet.pockets.hdPockets.length-1; // initialize pocket on angular $scope.initPocket(pocketIndex); // generate an address $scope.generateAddress(pocketIndex*2, 0); // select the pocket $scope.selectPocket($scope.newPocket.name, pocketIndex); // reset pocket form $scope.newPocket = {name:''}; } $scope.creatingPocket = !$scope.creatingPocket; }; /** * Rename a pocket */ $scope.finalizeRenamePocket = function(pocket) { if (!pocket || !pocket.name) { // if empty just toggle visibility $scope.forms.pocketLabelForm.$show(); } else { var identity = DarkWallet.getIdentity(); identity.store.save(); $scope.pocket.name = pocket.name; } }; }]); }); ","/** * @fileOverview PocketCreateCtrl angular controller */ define(['./module', 'darkwallet'], function (controllers, DarkWallet) { 'use strict'; controllers.controller('PocketCreateCtrl', ['$scope', function($scope) { /** * Scope variables */ $scope.newPocket = {}; $scope.creatingPocket = false; /** * Create a pocket */ $scope.createPocket = function() { if ($scope.creatingPocket && $scope.newPocket.name) { var identity = DarkWallet.getIdentity(); // create pocket identity.wallet.pockets.createPocket($scope.newPocket.name); var pocketIndex = identity.wallet.pockets.hdPockets.length-1; // initialize pocket on angular $scope.initPocket(pocketIndex); // generate an address $scope.generateAddress(pocketIndex*2, 0); // select the pocket $scope.selectPocket($scope.newPocket.name, pocketIndex); // reset pocket form $scope.newPocket = {name:''}; } $scope.creatingPocket = !$scope.creatingPocket; }; /** * Rename a pocket */ $scope.finalizeRenamePocket = function(pocket) { if (!pocket || !pocket.name) { // if empty just toggle visibility $scope.forms.pocketLabelForm.$show(); } else { var identity = DarkWallet.getIdentity(); identity.store.save(); } }; }]); }); " Fix broken utils test with seed,"import sys import unittest import numpy as np import torch sys.path.append(""../metal"") from metal.utils import ( rargmax, hard_to_soft, recursive_merge_dicts ) class UtilsTest(unittest.TestCase): def test_rargmax(self): x = np.array([2, 1, 2]) np.random.seed(1) self.assertEqual(sorted(list(set(rargmax(x) for _ in range(10)))), [0, 2]) def test_hard_to_soft(self): x = torch.tensor([1,2,2,1]) target = torch.tensor([ [1, 0], [0, 1], [0, 1], [1, 0], ], dtype=torch.float) self.assertTrue(((hard_to_soft(x, 2) == target).sum() == 8)) def test_recursive_merge_dicts(self): x = { 'foo': {'Foo': {'FOO': 1}}, 'bar': 2, 'baz': 3, } y = { 'FOO': 4, 'bar': 5, } z = { 'foo': 6 } recursive_merge_dicts(x, y, verbose=False) self.assertEqual(x['bar'], 5) self.assertEqual(x['foo']['Foo']['FOO'], 4) with self.assertRaises(ValueError): recursive_merge_dicts(x, z, verbose=False) if __name__ == '__main__': unittest.main()","import sys import unittest import numpy as np import torch sys.path.append(""../metal"") from metal.utils import ( rargmax, hard_to_soft, recursive_merge_dicts ) class UtilsTest(unittest.TestCase): def test_rargmax(self): x = np.array([2, 1, 2]) self.assertEqual(sorted(list(set(rargmax(x) for _ in range(10)))), [0, 2]) def test_hard_to_soft(self): x = torch.tensor([1,2,2,1]) target = torch.tensor([ [1, 0], [0, 1], [0, 1], [1, 0], ], dtype=torch.float) self.assertTrue(((hard_to_soft(x, 2) == target).sum() == 8)) def test_recursive_merge_dicts(self): x = { 'foo': {'Foo': {'FOO': 1}}, 'bar': 2, 'baz': 3, } y = { 'FOO': 4, 'bar': 5, } z = { 'foo': 6 } recursive_merge_dicts(x, y, verbose=False) self.assertEqual(x['bar'], 5) self.assertEqual(x['foo']['Foo']['FOO'], 4) with self.assertRaises(ValueError): recursive_merge_dicts(x, z, verbose=False) if __name__ == '__main__': unittest.main()" Call fuelclient directly passing over the object,"from fuelclient.commands import base from fuelclient.commands import environment as env_commands from fuelclient.common import data_utils class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand): """"""Clone environment and translate settings to the given release."""""" columns = env_commands.EnvShow.columns def get_parser(self, prog_name): parser = super(EnvClone, self).get_parser(prog_name) parser.add_argument('name', type=str, help='Name of the new environment.') parser.add_argument('release', type=int, help='ID of the release of the new environment.') return parser def take_action(self, parsed_args): # TODO(akscram): While the clone procedure is not a part of # fuelclient.objects.Environment the connection # colled directly. new_env = self.client._entity_wrapper.connection.post_request( ""clusters/{0}/upgrade/clone"".format(parsed_args.id), { 'name': parsed_args.name, 'release_id': parsed_args.release, } ) new_env = data_utils.get_display_data_single(self.columns, new_env) return (self.columns, new_env) ","from fuelclient.commands import base from fuelclient.commands import environment as env_commands from fuelclient.common import data_utils class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand): """"""Clone environment and translate settings to the given release."""""" columns = env_commands.EnvShow.columns def get_parser(self, prog_name): parser = super(EnvClone, self).get_parser(prog_name) parser.add_argument('name', type=str, help='Name of the new environment.') parser.add_argument('release', type=int, help='ID of the release of the new environment.') return parser def take_action(self, parsed_args): new_env = self.client.connection.post_request( ""clusters/{0}/upgrade/clone"".format(parsed_args.id), { 'name': parsed_args.name, 'release_id': parsed_args.release, } ) new_env = data_utils.get_display_data_single(self.columns, new_env) return (self.columns, new_env) " FIX Return resolved module name rather than original class module name,"<?php namespace SilverLeague\Console\Command\Object; use SilverLeague\Console\Command\SilverStripeCommand; use SilverLeague\Console\Framework\Utility\ObjectUtilities; use SilverStripe\Core\Injector\Injector; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * Shows which Object is returned from the Injector * * @package silverstripe-console * @author Robbie Averill <robbie@averill.co.nz> */ class LookupCommand extends SilverStripeCommand { use ObjectUtilities; /** * {@inheritDoc} */ protected function configure() { $this ->setName('object:lookup') ->setDescription('Shows which Object is returned from the Injector') ->addArgument('object', InputArgument::REQUIRED, 'The Object to look up'); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $object = $input->getArgument('object'); $resolvedTo = get_class(Injector::inst()->get($object)); $output->writeln('<comment>' . $object . '</comment> resolves to <info>' . $resolvedTo . '</info>'); if ($module = $this->getModuleName($resolvedTo)) { $output->writeln('<info>Module:</info> <comment>' . $module . '</comment>'); } } } ","<?php namespace SilverLeague\Console\Command\Object; use SilverLeague\Console\Command\SilverStripeCommand; use SilverLeague\Console\Framework\Utility\ObjectUtilities; use SilverStripe\Core\Injector\Injector; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * Shows which Object is returned from the Injector * * @package silverstripe-console * @author Robbie Averill <robbie@averill.co.nz> */ class LookupCommand extends SilverStripeCommand { use ObjectUtilities; /** * {@inheritDoc} */ protected function configure() { $this ->setName('object:lookup') ->setDescription('Shows which Object is returned from the Injector') ->addArgument('object', InputArgument::REQUIRED, 'The Object to look up'); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $object = $input->getArgument('object'); $resolvedTo = get_class(Injector::inst()->get($object)); $output->writeln('<comment>' . $object . '</comment> resolves to <info>' . $resolvedTo . '</info>'); if ($module = $this->getModuleName($object)) { $output->writeln('<info>Module:</info> <comment>' . $module . '</comment>'); } } } " Add posts state and inject service to PostsCtrl.,"var app = angular.module('codeLinks', ['ui.router']); app.config([ '$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $stateProvider .state('home', { url: '/home', templateUrl: '/home.html', controller: 'MainCtrl' }) .state('posts', { url: '/posts/{id}', templateUrl: '/posts.html', controller: 'PostCtrl' }); $urlRouterProvider.otherwise('home'); } ]); app.factory('posts', [function() { var o = { posts: [] }; return o; }]); app.controller('MainCtrl', [ '$scope', 'posts', function($scope, posts) { $scope.test = 'Hello world!'; $scope.posts = posts.posts; $scope.addPost = function() { if (!$scope.title || $scope.title === '') { return; } $scope.posts.push({ title: $scope.title, link: $scope.link, upvotes: 0 }); $scope.title = ''; $scope.link = ''; }; $scope.incrementUpvotes = function(post) { post.upvotes += 1; }; } ]); app.controller('PostsCtrl', [ '$scope', '$stateParams', 'posts', function($scope, $stateParams, posts) { } ]);","var app = angular.module('codeLinks', ['ui.router']); app.config([ '$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $stateProvider.state('home', { url: '/home', templateUrl: '/home.html', controller: 'MainCtrl' }); $urlRouterProvider.otherwise('home'); } ]); app.factory('posts', [function() { var o = { posts: [] }; return o; }]); app.controller('MainCtrl', [ '$scope', 'posts', function($scope, posts) { $scope.test = 'Hello world!'; $scope.posts = posts.posts; $scope.addPost = function() { if (!$scope.title || $scope.title === '') { return; } $scope.posts.push({ title: $scope.title, link: $scope.link, upvotes: 0 }); $scope.title = ''; $scope.link = ''; }; $scope.incrementUpvotes = function(post) { post.upvotes += 1; }; } ]);" Expand range of wave sum simulator.,"/** Global variables for processing.js access **/ var waveSpeed = 3; var timestep = 0.3 var w = 0.3; var w2 = 0.45; var playing = false; /** Page setup **/ $(document).ready(function() { $(""#speed-slider"").slider({min: -5, max: 5, step: 0.1, slide: setAnimSpeed, value: timestep}); $(""#wave1-w-slider"").slider({min: 0, max: 1, step: 0.03, slide: setW1, value: w}); $(""#wave2-w-slider"").slider({min: 0, max: 1, step: 0.03, slide: setW2, value: w2}); $(""#play"").click(function() { var processing = Processing.getInstanceById(""wave-sum-sim""); if (playing) { processing.noLoop(); $(""#play"").html(""Play""); } else { processing.loop(); processing.draw(); $(""#play"").html(""Pause""); } playing = !playing; }); }); function setAnimSpeed(event, ui) { timestep = ui.value; } function setW1(event, ui) { w = ui.value; } function setW2(event, ui) { w2 = ui.value; }","/** Global variables for processing.js access **/ var waveSpeed = 3; var timestep = 0.3 var w = 0.3; var w2 = 0.45; var playing = false; /** Page setup **/ $(document).ready(function() { $(""#speed-slider"").slider({min: -5, max: 5, step: 0.1, slide: setAnimSpeed, value: timestep}); $(""#wave1-w-slider"").slider({min: 0, max: 0.6, step: 0.03, slide: setW1, value: w}); $(""#wave2-w-slider"").slider({min: 0, max: 0.6, step: 0.03, slide: setW2, value: w2}); $(""#play"").click(function() { var processing = Processing.getInstanceById(""wave-sum-sim""); if (playing) { processing.noLoop(); $(""#play"").html(""Play""); } else { processing.loop(); processing.draw(); $(""#play"").html(""Pause""); } playing = !playing; }); }); function setAnimSpeed(event, ui) { timestep = ui.value; } function setW1(event, ui) { w = ui.value; } function setW2(event, ui) { w2 = ui.value; }" Fix Python3 unicode test error,"from ansiblelint import AnsibleLintRule try: from types import StringTypes except ImportError: # Python3 removed types.StringTypes StringTypes = str, class NoFormattingInWhenRule(AnsibleLintRule): id = 'CINCH0001' shortdesc = 'No Jinja2 in when' description = '""when"" lines should not include Jinja2 variables' tags = ['deprecated'] def _is_valid(self, when): if not isinstance(when, StringTypes): return True return when.find('{{') == -1 and when.find('}}') == -1 def matchplay(self, file, play): errors = [] if isinstance(play, dict): if 'roles' not in play: return errors for role in play['roles']: if self.matchtask(file, role): errors.append(({'when': role}, 'role ""when"" clause has Jinja2 templates')) if isinstance(play, list): for play_item in play: sub_errors = self.matchplay(file, play_item) if sub_errors: errors = errors + sub_errors return errors def matchtask(self, file, task): return 'when' in task and not self._is_valid(task['when']) ","from ansiblelint import AnsibleLintRule class NoFormattingInWhenRule(AnsibleLintRule): id = 'CINCH0001' shortdesc = 'No Jinja2 in when' description = '""when"" lines should not include Jinja2 variables' tags = ['deprecated'] def _is_valid(self, when): if not isinstance(when, (str, unicode)): return True return when.find('{{') == -1 and when.find('}}') == -1 def matchplay(self, file, play): errors = [] if isinstance(play, dict): if 'roles' not in play: return errors for role in play['roles']: if self.matchtask(file, role): errors.append(({'when': role}, 'role ""when"" clause has Jinja2 templates')) if isinstance(play, list): for play_item in play: sub_errors = self.matchplay(file, play_item) if sub_errors: errors = errors + sub_errors return errors def matchtask(self, file, task): return 'when' in task and not self._is_valid(task['when']) " "Fix existing item recognition in ""Code"" widget.","import DashboardWidgetComponent from 'appkit/components/dashboard-widget'; var GithubTeamNotices = DashboardWidgetComponent.extend({ init: function() { this._super(); this.set(""contents"", []); }, actions: { receiveEvent: function(data) { var items = Ember.A(JSON.parse(data)); this.updatePullRequests(items.pull_requests); // eventually Issues too } }, updatePullRequests: function(items) { var contents = this.get(""contents""); if (!Ember.isEmpty(items)) { // Remove items that have disappeared. var itemsToRemove = []; contents.forEach(function(existingItem) { var isNotPresent = !items.findBy(""id"", existingItem.get(""id"")); if (isNotPresent) { itemsToRemove.pushObject(existingItem); } }); contents.removeObjects(itemsToRemove); // Process current items. items.forEach(function(item) { var existingItem = contents.findBy(""url"", item.id); if (Ember.isEmpty(existingItem)) { // Add new items. var newItem = contents.pushObject(Ember.Object.create(item)); newItem.set(""dashEventType"", ""Pull Request""); } else { // Update existing items. existingItem.setProperties(item); } }); } } }); export default GithubTeamNotices; ","import DashboardWidgetComponent from 'appkit/components/dashboard-widget'; var GithubTeamNotices = DashboardWidgetComponent.extend({ init: function() { this._super(); this.set(""contents"", []); }, actions: { receiveEvent: function(data) { var items = Ember.A(JSON.parse(data)); this.updatePullRequests(items.pull_requests); // eventually Issues too } }, updatePullRequests: function(items) { var contents = this.get(""contents""); if (!Ember.isEmpty(items)) { // Remove items that have disappeared. var itemsToRemove = []; contents.forEach(function(existingItem) { var isNotPresent = !items.findBy(""url"", existingItem.get(""url"")); if (isNotPresent) { itemsToRemove.pushObject(existingItem); } }); contents.removeObjects(itemsToRemove); // Process current items. items.forEach(function(item) { var existingItem = contents.findBy(""url"", item.url); if (Ember.isEmpty(existingItem)) { // Add new items. var newItem = contents.pushObject(Ember.Object.create(item)); newItem.set(""dashEventType"", ""Pull Request""); } else { // Update existing items. existingItem.setProperties(item); } }); } } }); export default GithubTeamNotices; " Check that regex matching template vars is not null,"JSONEditor.defaults.templates[""default""] = function() { return { compile: function(template) { var matches = template.match(/{{\s*([a-zA-Z0-9\-_\.]+)\s*}}/g); var l = matches && matches.length; // Shortcut if the template contains no variables if(!l) return function() { return template; }; // Pre-compute the search/replace functions // This drastically speeds up template execution var replacements = []; var get_replacement = function(i) { var p = matches[i].replace(/[{}\s]+/g,'').split('.'); var n = p.length; var func; if(n > 1) { var cur; func = function(vars) { cur = vars; for(i=0; i<n; i++) { cur = cur[p[i]]; if(!cur) break; } return cur; }; } else { p = p[0]; func = function(vars) { return vars[p]; }; } replacements.push({ s: matches[i], r: func }); }; for(var i=0; i<l; i++) { get_replacement(i); } // The compiled function return function(vars) { var ret = template+""""; var r; for(i=0; i<l; i++) { r = replacements[i]; ret = ret.replace(r.s, r.r(vars)); } return ret; }; } }; }; ","JSONEditor.defaults.templates[""default""] = function() { return { compile: function(template) { var matches = template.match(/{{\s*([a-zA-Z0-9\-_\.]+)\s*}}/g); var l = matches.length; // Shortcut if the template contains no variables if(!l) return function() { return template; }; // Pre-compute the search/replace functions // This drastically speeds up template execution var replacements = []; var get_replacement = function(i) { var p = matches[i].replace(/[{}\s]+/g,'').split('.'); var n = p.length; var func; if(n > 1) { var cur; func = function(vars) { cur = vars; for(i=0; i<n; i++) { cur = cur[p[i]]; if(!cur) break; } return cur; }; } else { p = p[0]; func = function(vars) { return vars[p]; }; } replacements.push({ s: matches[i], r: func }); }; for(var i=0; i<l; i++) { get_replacement(i); } // The compiled function return function(vars) { var ret = template+""""; var r; for(i=0; i<l; i++) { r = replacements[i]; ret = ret.replace(r.s, r.r(vars)); } return ret; }; } }; }; " Update wrong value of monthBeforeYear,"export default { today: 'วันนี้', now: 'ตอนนี้', backToToday: 'กลับไปยังวันนี้', ok: 'ตกลง', clear: 'ลบล้าง', month: 'เดือน', year: 'ปี', timeSelect: 'เลือกเวลา', dateSelect: 'เลือกวัน', monthSelect: 'เลือกเดือน', yearSelect: 'เลือกปี', decadeSelect: 'เลือกทศวรรษ', yearFormat: 'YYYY', dateFormat: 'D/M/YYYY', dayFormat: 'D', dateTimeFormat: 'D/M/YYYY HH:mm:ss', monthFormat: 'MMMM', monthBeforeYear: true, previousMonth: 'เดือนก่อนหน้า (PageUp)', nextMonth: 'เดือนถัดไป (PageDown)', previousYear: 'ปีก่อนหน้า (Control + left)', nextYear: 'ปีถัดไป (Control + right)', previousDecade: 'ทศวรรษก่อนหน้า', nextDecade: 'ทศวรรษถัดไป', previousCentury: 'ศตวรรษก่อนหน้า', nextCentury: 'ศตวรรษถัดไป', }; ","export default { today: 'วันนี้', now: 'ตอนนี้', backToToday: 'กลับไปยังวันนี้', ok: 'ตกลง', clear: 'ลบล้าง', month: 'เดือน', year: 'ปี', timeSelect: 'เลือกเวลา', dateSelect: 'เลือกวัน', monthSelect: 'เลือกเดือน', yearSelect: 'เลือกปี', decadeSelect: 'เลือกทศวรรษ', yearFormat: 'YYYY', dateFormat: 'D/M/YYYY', dayFormat: 'D', dateTimeFormat: 'D/M/YYYY HH:mm:ss', monthFormat: 'MMMM', monthBeforeYear: false, previousMonth: 'เดือนก่อนหน้า (PageUp)', nextMonth: 'เดือนถัดไป (PageDown)', previousYear: 'ปีก่อนหน้า (Control + left)', nextYear: 'ปีถัดไป (Control + right)', previousDecade: 'ทศวรรษก่อนหน้า', nextDecade: 'ทศวรรษถัดไป', previousCentury: 'ศตวรรษก่อนหน้า', nextCentury: 'ศตวรรษถัดไป', }; " Fix empty author assignment inline if,"package com.indeed.proctor.builder.maven; import com.indeed.proctor.builder.LocalProctorBuilder; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import java.io.File; import java.io.FileWriter; import java.io.Writer; @Mojo(name = ""generate-matrix"") public class BuilderMojo extends AbstractMojo { @Parameter(property = ""topDirectory"", defaultValue = ""${basedir}/src/main/proctor-data"") private File topDirectory; @Parameter(property = ""outputFile"", defaultValue = ""${project.build.directory}/proctor-test-matrix.json"") private File outputFile; @Parameter(property = ""author"", defaultValue = """") private String author; @Parameter(property = ""version"", defaultValue = ""-1"") private String version; @Override public final void execute() throws MojoExecutionException { if(!topDirectory.exists()) { return; } try { // try to make sure path exists outputFile.getParentFile().mkdirs(); Writer w = new FileWriter(outputFile); new LocalProctorBuilder(topDirectory, w, """".equals(author) ? null : author, version).execute(); w.close(); } catch (Exception e) { throw new MojoExecutionException(""Failure during builder execution"", e); } } } ","package com.indeed.proctor.builder.maven; import com.indeed.proctor.builder.LocalProctorBuilder; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import java.io.File; import java.io.FileWriter; import java.io.Writer; @Mojo(name = ""generate-matrix"") public class BuilderMojo extends AbstractMojo { @Parameter(property = ""topDirectory"", defaultValue = ""${basedir}/src/main/proctor-data"") private File topDirectory; @Parameter(property = ""outputFile"", defaultValue = ""${project.build.directory}/proctor-test-matrix.json"") private File outputFile; @Parameter(property = ""author"", defaultValue = """") private String author; @Parameter(property = ""version"", defaultValue = ""-1"") private String version; @Override public final void execute() throws MojoExecutionException { if(!topDirectory.exists()) { return; } try { // try to make sure path exists outputFile.getParentFile().mkdirs(); Writer w = new FileWriter(outputFile); new LocalProctorBuilder(topDirectory, w, """".equals(author) ? author : null, version).execute(); w.close(); } catch (Exception e) { throw new MojoExecutionException(""Failure during builder execution"", e); } } } " Add missed serial version UID,"package models; import models.enumeration.ResourceType; import play.db.ebean.Model; import javax.persistence.*; import java.util.List; @MappedSuperclass abstract public class UserAction extends Model { private static final long serialVersionUID = 7150871138735757127L; @Id public Long id; @ManyToOne public User user; @Enumerated(EnumType.STRING) public models.enumeration.ResourceType resourceType; public String resourceId; public static <T extends UserAction> List<T> findBy(Finder<Long, T> finder, ResourceType resourceType, String resourceId) { return finder.where() .eq(""resourceType"", resourceType) .eq(""resourceId"", resourceId).findList(); } public static <T extends UserAction> T findBy(Finder<Long, T> finder, User subject, ResourceType resourceType, String resourceId) { return finder.where() .eq(""user.id"", subject.id) .eq(""resourceType"", resourceType) .eq(""resourceId"", resourceId).findUnique(); } public static <T extends UserAction> List<T> findBy(Finder<Long, T> finder, User subject, ResourceType resourceType) { return finder.where() .eq(""user.id"", subject.id) .eq(""resourceType"", resourceType).findList(); } } ","package models; import models.enumeration.ResourceType; import play.db.ebean.Model; import javax.persistence.*; import java.util.List; @MappedSuperclass abstract public class UserAction extends Model { @Id public Long id; @ManyToOne public User user; @Enumerated(EnumType.STRING) public models.enumeration.ResourceType resourceType; public String resourceId; public static <T extends UserAction> List<T> findBy(Finder<Long, T> finder, ResourceType resourceType, String resourceId) { return finder.where() .eq(""resourceType"", resourceType) .eq(""resourceId"", resourceId).findList(); } public static <T extends UserAction> T findBy(Finder<Long, T> finder, User subject, ResourceType resourceType, String resourceId) { return finder.where() .eq(""user.id"", subject.id) .eq(""resourceType"", resourceType) .eq(""resourceId"", resourceId).findUnique(); } public static <T extends UserAction> List<T> findBy(Finder<Long, T> finder, User subject, ResourceType resourceType) { return finder.where() .eq(""user.id"", subject.id) .eq(""resourceType"", resourceType).findList(); } } " Add link to new meal form,"import React, { Component } from 'react' import { Link } from 'react-router-dom' import { connect } from 'react-redux' import { Menu } from 'semantic-ui-react' import { css } from 'glamor' class Nav extends Component { handleLogout = () => this.props.logout() render() { return ( <Menu secondary {...rules}> <Menu.Item name='home' as={Link} to=""/"" > Home </Menu.Item> { this.props.isAuthenticated ? <Menu.Menu position=""right""> <Menu.Item name='households' as={Link} to=""/households"" > Households </Menu.Item> <Menu.Item as={Link} to=""/households/new"" > New Household </Menu.Item> <Menu.Item as={Link} to=""/meals/new""> New Meal </Menu.Item> <Menu.Item as={Link} to=""/"" onClick={this.handleLogout}> Logout </Menu.Item> </Menu.Menu> : <Menu.Menu position=""right""> <Menu.Item as={Link} to=""/login""> Login </Menu.Item> <Menu.Item as={Link} to=""/signup""> Sign Up </Menu.Item> </Menu.Menu> } </Menu> ) } } export default connect(state => { return { isAuthenticated: state.auth.isAuthenticated } }, null)(Nav) let rules = css({ height: '60px' }) ","import React, { Component } from 'react' import { Link } from 'react-router-dom' import { connect } from 'react-redux' import { Menu } from 'semantic-ui-react' import { css } from 'glamor' class Nav extends Component { handleLogout = () => this.props.logout() render() { return ( <Menu secondary {...rules}> <Menu.Item name='home' as={Link} to=""/"" > Home </Menu.Item> { this.props.isAuthenticated ? <Menu.Menu position=""right""> <Menu.Item name='households' as={Link} to=""/households"" > Households </Menu.Item> <Menu.Item as={Link} to=""/households/new"" > New Household </Menu.Item> <Menu.Item as={Link} to=""/"" onClick={this.handleLogout}> Logout </Menu.Item> </Menu.Menu> : <Menu.Menu position=""right""> <Menu.Item as={Link} to=""/login""> Login </Menu.Item> <Menu.Item as={Link} to=""/signup""> Sign Up </Menu.Item> </Menu.Menu> } </Menu> ) } } export default connect(state => { return { isAuthenticated: state.auth.isAuthenticated } }, null)(Nav) let rules = css({ height: '60px' }) " Use select instead of React Dropdown.,"import React, { Component } from 'react' import { Col, Form, Row } from 'react-bootstrap' import Select from 'react-select' class DropdownOption extends Component { render() { const option = this.props.options[this.props.optionKey] const model = this.props.model const currentChoice = model[this.props.optionKey] return ( <Row className=""align-items-center pb-2"" key={this.props.index}> <Col sm={5}> <Form.Label htmlFor=""options-dropdown""> {option.title} </Form.Label> </Col> <Col sm={7}> <Select value={{value: currentChoice, label: currentChoice}} onChange={(choice) => { const value = choice.value let attrs = {} attrs[this.props.optionKey] = value this.props.onChange(attrs) }} options={option.choices.map((choice) => { return { value: choice, label: choice} })} /> </Col> </Row> ) } } export default DropdownOption ","import React, { Component } from 'react' import { Col, Dropdown, Form, Row } from 'react-bootstrap' class DropdownOption extends Component { render() { const option = this.props.options[this.props.optionKey] const model = this.props.model return ( <Row className=""align-items-center pb-2"" key={this.props.index}> <Col sm={5}> <Form.Label htmlFor=""options-dropdown""> {option.title} </Form.Label> </Col> <Col sm={7}> <Dropdown id=""options-dropdown"" onSelect={(value) => { let attrs = {} attrs[this.props.optionKey] = value this.props.onChange(attrs) }}> <Dropdown.Toggle variant=""secondary""> {model[this.props.optionKey]} </Dropdown.Toggle> <Dropdown.Menu> {option.choices.map((choice) => { return <Dropdown.Item key={choice} eventKey={choice}>{choice}</Dropdown.Item> })} </Dropdown.Menu> </Dropdown> </Col> </Row> ) } } export default DropdownOption " Change the background to reflect the color chosen,"from django import forms from django.conf import settings from django.utils.safestring import mark_safe class ColorPickerWidget(forms.TextInput): class Media: css = { ""all"": (""%s/%s"" % (settings.STATIC_URL, ""paintstore/css/colorpicker.css""),) } js = ( (""%s/%s"" % (settings.STATIC_URL, ""paintstore/jquery_1.7.2.js"")), (""%s/%s"" % (settings.STATIC_URL, ""paintstore/colorpicker.js"")) ) input_type = 'colorpicker' def render(self, name, value, attrs=None): script = u""""""<script type='text/javascript'> $(document).ready(function(){{ $('#{0}').ColorPicker({{ onSubmit: function(hsb, hex, rgb, el, parent) {{ $(el).val('#' + hex); $(el).ColorPickerHide(); $('#{0}').css('background-color', '#' + hex); }}, onBeforeShow: function () {{ $(this).ColorPickerSetColor(this.value); }} }}).bind('keyup', function(){{ $(this).ColorPickerSetColor(this.value.replace('#', '')); }}); $('#{0}').css('background-color', $('#{0}').val()); }}); </script> """""".format(u'id_'+name) super_render = super(ColorPickerWidget, self).render(name, value, attrs) return mark_safe(u""%s%s"" % (super_render, script)) ","from django import forms from django.conf import settings from django.utils.safestring import mark_safe class ColorPickerWidget(forms.TextInput): class Media: css = { ""all"": (""%s/%s"" % (settings.STATIC_URL, ""paintstore/css/colorpicker.css""),) } js = ( (""%s/%s"" % (settings.STATIC_URL, ""paintstore/jquery_1.7.2.js"")), (""%s/%s"" % (settings.STATIC_URL, ""paintstore/colorpicker.js"")) ) input_type = 'colorpicker' def render(self, name, value, attrs=None): script = u""""""<script type='text/javascript'> $(document).ready(function(){ $('#%s').ColorPicker({ onSubmit: function(hsb, hex, rgb, el, parent) { $(el).val('#' + hex); $(el).ColorPickerHide(); }, onBeforeShow: function () { $(this).ColorPickerSetColor(this.value); } }).bind('keyup', function(){ $(this).ColorPickerSetColor(this.value.replace('#', '')); }); }); </script> """""" % (""id_%s"" % name,) super_render = super(ColorPickerWidget, self).render(name, value, attrs) return mark_safe(u""%s%s"" % (super_render, script)) " "Fix infinite loop with missing symbol definition The local function _resolve_symbol is renamed for improved tracebacks.","import hc2002.plugin as plugin import hc2002.config as config plugin.register_for_resource(__name__, 'hc2002.resource.instance') _prefixes = ('availability-zone:', 'image:', 'kernel:', 'key:', 'load-balancers:', 'ramdisk:', 'security-groups:', 'spot-price:', 'subnet:') def apply(instance): def resolve_symbol(original_value): value = original_value visited = set() while isinstance(value, basestring) \ and value.startswith(prefix): value = value.format(region=config.region, **instance) if value in instance \ and value not in visited: visited.add(value) value = instance[value] else: if original_value == value: raise Exception(""Unable to resolve '%s'"" % value) else: raise Exception( ""While resolving '%s': unable to resolve '%s'"" % (original_value, value)) return value # Resolve symbols for prefix in _prefixes: key = prefix[:-1] if key not in instance: continue if isinstance(instance[key], basestring): instance[key] = resolve_symbol(instance[key]) elif isinstance(instance[key], list): instance[key] = map(resolve_symbol, instance[key]) # Drop resolvable symbols for key in instance.keys(): if key.startswith(_prefixes): del instance[key] ","import hc2002.plugin as plugin import hc2002.config as config plugin.register_for_resource(__name__, 'hc2002.resource.instance') _prefixes = ('availability-zone:', 'image:', 'kernel:', 'key:', 'load-balancers:', 'ramdisk:', 'security-groups:', 'spot-price:', 'subnet:') def apply(instance): def _resolve_symbol(value): visited = set() while isinstance(value, basestring) \ and value.startswith(prefix): value = value.format(region=config.region, **instance) if value in instance \ and value not in visited: visited.add(value) value = instance[value] return value # Resolve symbols for prefix in _prefixes: key = prefix[:-1] if key not in instance: continue if isinstance(instance[key], basestring): instance[key] = _resolve_symbol(instance[key]) elif isinstance(instance[key], list): instance[key] = map(_resolve_symbol, instance[key]) # Drop resolvable symbols for key in instance.keys(): if key.startswith(_prefixes): del instance[key] " Add a link to the name,"<?php if (!isset($_SESSION)) { session_start(); } ?> <!DOCTYPE html> <html lang=""en""> <head> <title> Sunrise Hospital </title> <link href=""assets/css/bootstrap.min.css"" rel=""stylesheet"" /> </head> <body> <div class=""container"" style=""padding-top: 10px;""> <nav class=""navbar navbar-static-top""> <a href=""index.php"" class=""navbar-brand""> Sunrise Hospital</a> <ul class=""nav nav-pills""> <li class=""nav-item""> <a href=""https://goo.gl/maps/PyT52gM87su"" target=""_blank""> Address: Plot no- 1, Opposite SBI, Sector 12, Kharghar, Navi Mumbai</a> </li> <li class=""nav-item""> <a class="""" href=""tel:+917709473553"">Ambulance Number: +91 7709473553</a> </li> <?php if (isset($_SESSION['username'])) { echo '<li class=""nav-item"" style=""align-items: right;""> <a class=""nav-link"" href=""logout.php"">Logout</a> </li>'; } ?> </ul> </nav> </div> ","<?php if (!isset($_SESSION)) { session_start(); } ?> <!DOCTYPE html> <html lang=""en""> <head> <title> Sunrise Hospital </title> <link href=""assets/css/bootstrap.min.css"" rel=""stylesheet"" /> </head> <body> <div class=""container"" style=""padding-top: 10px;""> <nav class=""navbar navbar-static-top""> <a class=""navbar-brand""> Sunrise Hospital</a> <ul class=""nav nav-pills""> <li class=""nav-item""> <a href=""https://goo.gl/maps/PyT52gM87su"" target=""_blank""> Address: Plot no- 1, Opposite SBI, Sector 12, Kharghar, Navi Mumbai</a> </li> <li class=""nav-item""> <a class="""" href=""tel:+917709473553"">Ambulance Number: +91 7709473553</a> </li> <?php if (isset($_SESSION['username'])) { echo '<li class=""nav-item"" style=""align-items: right;""> <a class=""nav-link"" href=""logout.php"">Logout</a> </li>'; } ?> </ul> </nav> </div> " "Exit if SPOTIFY_{USERNAME,PASSWORD} is not set","import sys import spytify from mopidy import settings from mopidy.backends.base import BaseBackend class SpotifyBackend(BaseBackend): def __init__(self, *args, **kwargs): super(SpotifyBackend, self).__init__(*args, **kwargs) self.spotify = spytify.Spytify(self.username, self.password) self._playlist_load_cache = None @property def username(self): username = settings.SPOTIFY_USERNAME.encode('utf-8') if not username: sys.exit('Setting SPOTIFY_USERNAME is not set.') return username @property def password(self): password = settings.SPOTIFY_PASSWORD.encode('utf-8') if not password: sys.exit('Setting SPOTIFY_PASSWORD is not set.') return password def playlist_load(self, name): if not self._playlist_load_cache: for playlist in self.spotify.stored_playlists: if playlist.name == name: tracks = [] for track in playlist.tracks: tracks.append(u'add %s\n' % track.file_id) self._playlist_load_cache = tracks break return self._playlist_load_cache def playlists_list(self): playlists = [] for playlist in self.spotify.stored_playlists: playlists.append(u'playlist: %s' % playlist.name.decode('utf-8')) return playlists def url_handlers(self): return [u'spotify:', u'http://open.spotify.com/'] ","import spytify from mopidy import settings from mopidy.backends.base import BaseBackend class SpotifyBackend(BaseBackend): def __init__(self, *args, **kwargs): super(SpotifyBackend, self).__init__(*args, **kwargs) self.spotify = spytify.Spytify( settings.SPOTIFY_USERNAME.encode('utf-8'), settings.SPOTIFY_PASSWORD.encode('utf-8')) self._playlist_load_cache = None def playlist_load(self, name): if not self._playlist_load_cache: for playlist in self.spotify.stored_playlists: if playlist.name == name: tracks = [] for track in playlist.tracks: tracks.append(u'add %s\n' % track.file_id) self._playlist_load_cache = tracks break return self._playlist_load_cache def playlists_list(self): playlists = [] for playlist in self.spotify.stored_playlists: playlists.append(u'playlist: %s' % playlist.name.decode('utf-8')) return playlists def url_handlers(self): return [u'spotify:', u'http://open.spotify.com/'] " Change 'success' and 'message' to lowercase,"import logging import smtplib from socket import error as socket_error from email.mime.text import MIMEText from pylons import config log = logging.getLogger(__name__) SMTP_SERVER = config.get('ckanext.requestdata.smtp.server', '') SMTP_USER = config.get('ckanext.requestdata.smtp.user', '') SMTP_PASSWORD = config.get('ckanext.requestdata.smtp.password', '') def send_email(content, to, from_, subject): '''Sends email :param content: The body content for the mail. :type string: :param to: To whom will be mail sent :type string: :param from_: The sender of mail. :type string: :rtype: string ''' msg = MIMEText(content,'plain','UTF-8') if isinstance(to, basestring): to = [to] msg['Subject'] = subject msg['From'] = from_ msg['To'] = ','.join(to) try: s = smtplib.SMTP(SMTP_SERVER) s.login(SMTP_USER, SMTP_PASSWORD) s.sendmail(from_, to, msg.as_string()) s.quit() response_dict = { 'success' : True, 'message' : 'Email message was successfully sent.' } return response_dict except socket_error: log.critical('Could not connect to email server. Have you configured the SMTP settings?') error_dict = { 'success': False, 'message' : 'An error occured while sending the email. Try again.' } return error_dict ","import logging import smtplib from socket import error as socket_error from email.mime.text import MIMEText from pylons import config log = logging.getLogger(__name__) SMTP_SERVER = config.get('ckanext.requestdata.smtp.server', '') SMTP_USER = config.get('ckanext.requestdata.smtp.user', '') SMTP_PASSWORD = config.get('ckanext.requestdata.smtp.password', '') def send_email(content, to, from_, subject): '''Sends email :param content: The body content for the mail. :type string: :param to: To whom will be mail sent :type string: :param from_: The sender of mail. :type string: :rtype: string ''' msg = MIMEText(content,'plain','UTF-8') if isinstance(to, basestring): to = [to] msg['Subject'] = subject msg['From'] = from_ msg['To'] = ','.join(to) try: s = smtplib.SMTP(SMTP_SERVER) s.login(SMTP_USER, SMTP_PASSWORD) s.sendmail(from_, to, msg.as_string()) s.quit() response_dict = { 'Success' : True, 'Message' : 'Email message was successfully sent.' } return response_dict except socket_error: log.critical('Could not connect to email server. Have you configured the SMTP settings?') error_dict = { 'Success': False, 'Message' : 'An error occured while sending the email. Try again.' } return error_dict" Insert custom commands through the getCommands() function.,"<?php /** * @version $Id$ * @category Nooku * @package Nooku_Server * @subpackage Sections * @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net). * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Sections Toolbar Class * * @author Stian Didriksen <http://nooku.assembla.com/profile/stiandidriksen> * @category Nooku * @package Nooku_Server * @subpackage Section */ class ComSectionsControllerToolbarSections extends ComDefaultControllerToolbarDefault { public function getCommands() { $this->addSeperator() ->addEnable(array('label' => 'publish')) ->addDisable(array('label' => 'unpublish')); return parent::getCommands(); } protected function _commandNew(KControllerToolbarCommand $command) { $option = $this->_identifier->package; $view = KInflector::singularize($this->_identifier->name); $command->append(array( 'attribs' => array( 'href' => JRoute::_('index.php?option=com_'.$option.'&view='.$view.'&scope=content' ) ) )); } }","<?php /** * @version $Id$ * @category Nooku * @package Nooku_Server * @subpackage Modules * @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net). * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Sections Toolbar Class * * @author Stian Didriksen <http://nooku.assembla.com/profile/stiandidriksen> * @category Nooku * @package Nooku_Server * @subpackage Modules */ class ComSectionsControllerToolbarSections extends ComDefaultControllerToolbarDefault { public function __construct(KConfig $config) { parent::__construct($config); $this->addSeperator() ->addEnable(array('label' => 'publish')) ->addDisable(array('label' => 'unpublish')); } protected function _commandNew(KControllerToolbarCommand $command) { $option = $this->_identifier->package; $view = KInflector::singularize($this->_identifier->name); $command->append(array( 'attribs' => array( 'href' => JRoute::_('index.php?option=com_'.$option.'&view='.$view.'&scope=content' ) ) )); } }" Fix annot read property '/' of undefined,"import SocketIONamespace from ""./namespace""; export default class SocketIOServer { constructor(io) { this._io = io; this._nsps = Object.create(null); this._sockets = this.of(""/""); } get rawServer() { return this._io; } // // Delegation methods // of(name, fn) { var nsp = this._nsps[name]; if (! nsp) { nsp = new SocketIONamespace(this._io.of(name, fn)); this._nsps[name] = nsp; } return nsp; } } // pass through methods [ ""serveClient"", ""set"", ""path"", ""adapter"", ""origins"", ""listen"", ""attach"", ""bind"", ""onconnection"", /* ""of"", */ ""close"" ].forEach(methodName => { SocketIOServer.prototype[methodName] = function (...args) { this._io[methodName](...args); return this; }; }); [ /* ""on"" */, ""to"", ""in"", ""use"", ""emit"", ""send"", ""write"", ""clients"", ""compress"", // mayajs-socketio-wrapper methods ""on"", ""off"", ""receive"", ""offReceive"" ].forEach(methodName => { SocketIOServer.prototype[methodName] = function (...args) { return this._sockets[methodName](...args); } }); ","import SocketIONamespace from ""./namespace""; export default class SocketIOServer { constructor(io) { this._io = io; this._sockets = this.of(""/""); this._nsps = Object.create(null); } get rawServer() { return this._io; } // // Delegation methods // of(name, fn) { var nsp = this._nsps[name]; if (! nsp) { nsp = new SocketIONamespace(this._io.of(name, fn)); this._nsps[name] = nsp; } return nsp; } } // pass through methods [ ""serveClient"", ""set"", ""path"", ""adapter"", ""origins"", ""listen"", ""attach"", ""bind"", ""onconnection"", /* ""of"", */ ""close"" ].forEach(methodName => { SocketIOServer.prototype[methodName] = function (...args) { this._io[methodName](...args); return this; }; }); [ /* ""on"" */, ""to"", ""in"", ""use"", ""emit"", ""send"", ""write"", ""clients"", ""compress"", // mayajs-socketio-wrapper methods ""on"", ""off"", ""receive"", ""offReceive"" ].forEach(methodName => { SocketIOServer.prototype[methodName] = function (...args) { return this._sockets[methodName](...args); } }); " Add a loading indicator on the auth page,"const React = require('react'); const Utils = require('../utils'); const AuthentificationPage = React.createClass({ getInitialState() { return { loading: false }; }, openAuthWindow() { this.setState({ loading: true }); Utils.Socket.emit('youtube/auth'); }, render() { if (this.state.loading) { return ( <div className=""text-page""> <div className=""jumbotron""> <h1 className=""display-3"">YouWatch</h1> <p className=""lead"">Please fulfill the informations on the other window</p> <p className=""lead""> <button className=""btn btn-primary btn-lg disabled""><i className=""fa fa-spinner fa-pulse"" /> Logging in...</button> </p> </div> </div> ); } return ( <div className=""text-page""> <div className=""jumbotron""> <h1 className=""display-3"">YouWatch</h1> <p className=""lead"">{'Let\'s connect to your YouTube Account'}</p> <p className=""lead""> <button className=""btn btn-primary btn-lg"" onClick={this.openAuthWindow}>Log in</button> </p> </div> </div> ); }, }); module.exports = AuthentificationPage; ","const React = require('react'); const Utils = require('../utils'); const AuthentificationPage = React.createClass({ getInitialState() { return { loading: false }; }, openAuthWindow() { this.setState({ loading: true }); Utils.Socket.emit('youtube/auth'); }, render() { if (this.state.loading) { return ( <div className=""text-page""> <div className=""jumbotron""> <h1 className=""display-3"">YouWatch</h1> <p className=""lead"">Please fulfill the informations on the other window</p> <p className=""lead""> <button className=""btn btn-primary btn-lg disabled"">Logging in...</button> </p> </div> </div> ); } return ( <div className=""text-page""> <div className=""jumbotron""> <h1 className=""display-3"">YouWatch</h1> <p className=""lead"">{'Let\'s connect to your YouTube Account'}</p> <p className=""lead""> <button className=""btn btn-primary btn-lg"" onClick={this.openAuthWindow}>Log in</button> </p> </div> </div> ); }, }); module.exports = AuthentificationPage; " "CRM-1051: Add a Reset workflow button that will erase the relation from specific entity view page - removed not used event triggering","define([ 'jquery', 'underscore', 'orotranslation/js/translator', 'oroui/js/modal', 'oronavigation/js/navigation', 'oroui/js/messenger' ], function($, _, __, Modal, Navigation, Messenger) { 'use strict'; var navigation = Navigation.getInstance(); /** * Reset button click handler * * @export oroworkflow/js/delete-handler * @class oroworkflow.WorkflowDeleteHandler */ return function() { var element = $(this); if (element.data('_in-progress')) { return; } element.data('_in-progress', true); var resetInProgress = function() { element.data('_in-progress', false); }; var confirmReset = new Modal({ title: __('Workflow reset'), content: __('Attention: This action will reset workflow data for this record.'), okText: __('Yes, Reset') }); confirmReset.on('ok', function() { $.ajax({ url: element.data('url'), type: 'DELETE', success: function(responce) { if (navigation) { navigation.loadPage(true); } else { window.location.reload(); } }, error: function() { Messenger.notificationFlashMessage('error', __('Cannot reset workflow item data.')); resetInProgress(); } }) }); confirmReset.on('cancel', function() { resetInProgress(); }); confirmReset.open(); } }); ","define([ 'jquery', 'underscore', 'orotranslation/js/translator', 'oroui/js/modal', 'oronavigation/js/navigation', 'oroui/js/messenger' ], function($, _, __, Modal, Navigation, Messenger) { 'use strict'; var navigation = Navigation.getInstance(); /** * Reset button click handler * * @export oroworkflow/js/delete-handler * @class oroworkflow.WorkflowDeleteHandler */ return function() { var element = $(this); if (element.data('_in-progress')) { return; } element.data('_in-progress', true); var resetInProgress = function() { element.data('_in-progress', false); }; var confirmReset = new Modal({ title: __('Workflow reset'), content: __('Attention: This action will reset workflow data for this record.'), okText: __('Yes, Reset') }); confirmReset.on('ok', function() { $.ajax({ url: element.data('url'), type: 'DELETE', success: function(responce) { if (navigation) { navigation.loadPage(true); } else { window.location.reload(); } element.trigger('reset_success', [responce]); }, error: function() { Messenger.notificationFlashMessage('error', __('Cannot reset workflow item data.')); resetInProgress(); } }) }); confirmReset.on('cancel', function() { resetInProgress(); }); confirmReset.open(); } }); " [MediaBundle] Remove non working method which causes issues,"<?php namespace Kunstmaan\MediaBundle\Repository; use Doctrine\ORM\EntityNotFoundException; use Doctrine\ORM\EntityRepository; use Kunstmaan\MediaBundle\Entity\Media; /** * MediaRepository */ class MediaRepository extends EntityRepository { /** * @param Media $media */ public function save(Media $media) { $em = $this->getEntityManager(); $em->persist($media); $em->flush(); } /** * @param Media $media */ public function delete(Media $media) { $em = $this->getEntityManager(); $media->setDeleted(true); $em->persist($media); $em->flush(); } /** * @param int $mediaId * * @return object * * @throws EntityNotFoundException */ public function getMedia($mediaId) { $media = $this->find($mediaId); if (!$media) { throw new EntityNotFoundException(); } return $media; } /** * Finds all Media that has their deleted flag set to 1 * and have their remove_from_file_system flag set to 0 * * @return object[] */ public function findAllDeleted() { return $this->findBy(['deleted' => true, 'removedFromFileSystem' => false]); } } ","<?php namespace Kunstmaan\MediaBundle\Repository; use Doctrine\ORM\EntityNotFoundException; use Doctrine\ORM\EntityRepository; use Kunstmaan\MediaBundle\Entity\Media; /** * MediaRepository */ class MediaRepository extends EntityRepository { /** * @param Media $media */ public function save(Media $media) { $em = $this->getEntityManager(); $em->persist($media); $em->flush(); } /** * @param Media $media */ public function delete(Media $media) { $em = $this->getEntityManager(); $media->setDeleted(true); $em->persist($media); $em->flush(); } /** * @param int $mediaId * * @return object * * @throws EntityNotFoundException */ public function getMedia($mediaId) { $media = $this->find($mediaId); if (!$media) { throw new EntityNotFoundException(); } return $media; } /** * @param int $pictureId * * @return object * * @throws EntityNotFoundException */ public function getPicture($pictureId) { $em = $this->getEntityManager(); $picture = $em->getRepository(\Kunstmaan\MediaBundle\Entity\Image::class)->find($pictureId); if (!$picture) { throw new EntityNotFoundException(); } return $picture; } /** * Finds all Media that has their deleted flag set to 1 * and have their remove_from_file_system flag set to 0 * * @return object[] */ public function findAllDeleted() { return $this->findBy(['deleted' => true, 'removedFromFileSystem' => false]); } } " Revise to anagram_lists and rename to sorted anagram dict class,"""""""Leetcode 49. Group Anagrams Medium URL: https://leetcode.com/problems/group-anagrams/ Given an array of strings, group anagrams together. Example: Input: [""eat"", ""tea"", ""tan"", ""ate"", ""nat"", ""bat""], Output: [ [""ate"",""eat"",""tea""], [""nat"",""tan""], [""bat""] ] Note: - All inputs will be in lowercase. - The order of your output does not matter. """""" class SolutionSortedAnagramDict(object): def groupAnagrams(self, strs): """""" :type strs: List[str] :rtype: List[List[str]] Output Limit Exceede. Time complexity: O(n*klogk), where - n is the length of strs, - k is the lenght of the longest string. Space complexity: O(n). """""" from collections import defaultdict # Store in a dict with sorted string->string list. anagram_lists = defaultdict(list) for s in strs: # Use sorted string as dict key. k = ''.join(sorted(s)) anagram_lists[k].append(s) return anagram_lists.values() def main(): # Output: # [ # [""ate"",""eat"",""tea""], # [""nat"",""tan""], # [""bat""] # ] strs = [""eat"", ""tea"", ""tan"", ""ate"", ""nat"", ""bat""] print SolutionSortedAnagramDict().groupAnagrams(strs) if __name__ == '__main__': main() ","""""""Leetcode 49. Group Anagrams Medium URL: https://leetcode.com/problems/group-anagrams/ Given an array of strings, group anagrams together. Example: Input: [""eat"", ""tea"", ""tan"", ""ate"", ""nat"", ""bat""], Output: [ [""ate"",""eat"",""tea""], [""nat"",""tan""], [""bat""] ] Note: - All inputs will be in lowercase. - The order of your output does not matter. """""" class SolutionSortedDict(object): def groupAnagrams(self, strs): """""" :type strs: List[str] :rtype: List[List[str]] Output Limit Exceede. Time complexity: O(n*klogk), where - n is the length of strs, - k is the lenght of the longest string. Space complexity: O(n). """""" from collections import defaultdict # Store in a dict with sorted string->string list. anagrams_d = defaultdict(list) for s in strs: # Use sorted string as dict key. k = ''.join(sorted(s)) anagrams_d[k].append(s) return anagrams_d.values() def main(): # Output: # [ # [""ate"",""eat"",""tea""], # [""nat"",""tan""], # [""bat""] # ] strs = [""eat"", ""tea"", ""tan"", ""ate"", ""nat"", ""bat""] print SolutionSortedDict().groupAnagrams(strs) if __name__ == '__main__': main() " "Remove shell console script from entry points Amends f06fecca161bca2360ce076e9cc15458cbda0de5","from setuptools import setup, PEP420PackageFinder setup( name='tangled', version='1.0a13.dev0', description='Tangled namespace and utilities', long_description=open('README.rst').read(), url='https://tangledframework.org/', download_url='https://github.com/TangledWeb/tangled/tags', author='Wyatt Baldwin', author_email='self@wyattbaldwin.com', packages=PEP420PackageFinder.find(include=['tangled*']), install_requires=[ 'runcommands>=1.0a27', ], extras_require={ 'dev': [ 'coverage>=4.4.2', 'flake8>=3.5.0', 'Sphinx>=1.6.5', 'sphinx_rtd_theme>=0.2.4', ], }, entry_points="""""" [console_scripts] tangled = tangled.__main__:main [tangled.scripts] release = tangled.scripts:ReleaseCommand scaffold = tangled.scripts:ScaffoldCommand """""", classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], ) ","from setuptools import setup, PEP420PackageFinder setup( name='tangled', version='1.0a13.dev0', description='Tangled namespace and utilities', long_description=open('README.rst').read(), url='https://tangledframework.org/', download_url='https://github.com/TangledWeb/tangled/tags', author='Wyatt Baldwin', author_email='self@wyattbaldwin.com', packages=PEP420PackageFinder.find(include=['tangled*']), install_requires=[ 'runcommands>=1.0a27', ], extras_require={ 'dev': [ 'coverage>=4.4.2', 'flake8>=3.5.0', 'Sphinx>=1.6.5', 'sphinx_rtd_theme>=0.2.4', ], }, entry_points="""""" [console_scripts] tangled = tangled.__main__:main [tangled.scripts] release = tangled.scripts:ReleaseCommand scaffold = tangled.scripts:ScaffoldCommand python = tangled.scripts:ShellCommand """""", classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], ) " "Change redirect after success login from projects to dashboard. – SAAS-125","'use strict'; (function() { angular.module('ncsaas') .controller('AuthController', ['$location', '$state', '$auth', 'authService', AuthController]); function AuthController($location, $state, $auth, authService) { var vm = this; vm.isSignupFormVisible = false; vm.signin = signin; vm.user = {}; vm.hasErrors = hasErrors; vm.getErrors = getErrors; vm.authenticate = authenticate; function signin() { authService.signin(vm.user.username, vm.user.password).then(success, error); function success() { $state.go('dashboard'); } function error(response) { vm.errors = response.data; } } function hasErrors() { return vm.errors; } function getErrors() { if (vm.errors !== undefined) { var prettyErrors = []; for (var key in vm.errors) { if (vm.errors.hasOwnProperty(key)) { if (Object.prototype.toString.call(vm.errors[key]) === '[object Array]') { prettyErrors.push(key + ': ' + vm.errors[key].join(', ')); } else { prettyErrors.push(key + ': ' + vm.errors[key]); } } } return prettyErrors; } else { return ''; } } function authenticate(provider) { $auth.authenticate(provider); } } })(); ","'use strict'; (function() { angular.module('ncsaas') .controller('AuthController', ['$location', '$auth', 'authService', AuthController]); function AuthController($location, $auth, authService) { var vm = this; vm.isSignupFormVisible = false; vm.signin = signin; vm.user = {}; vm.hasErrors = hasErrors; vm.getErrors = getErrors; vm.authenticate = authenticate; function signin() { authService.signin(vm.user.username, vm.user.password).then(success, error); function success() { $location.path('/projects/'); } function error(response) { vm.errors = response.data; } } function hasErrors() { return vm.errors; } function getErrors() { if (vm.errors !== undefined) { var prettyErrors = []; for (var key in vm.errors) { if (vm.errors.hasOwnProperty(key)) { if (Object.prototype.toString.call(vm.errors[key]) === '[object Array]') { prettyErrors.push(key + ': ' + vm.errors[key].join(', ')); } else { prettyErrors.push(key + ': ' + vm.errors[key]); } } } return prettyErrors; } else { return ''; } } function authenticate(provider) { $auth.authenticate(provider); } } })(); " Make dashboard route become admin's default,"from openedoo_project import db from openedoo.core.libs import Blueprint from .controllers.employee import EmployeeLogin, EmployeeLogout, AddEmployee, \ AssignEmployeeAsTeacher, EmployeeDashboard, EditEmployee, DeleteEmployee, \ SearchEmployee, AddSubject module_employee = Blueprint('module_employee', __name__, template_folder='templates', static_folder='static') module_employee.add_url_rule('/admin', view_func=EmployeeDashboard.as_view('dashboard')) module_employee.add_url_rule('/admin/login', view_func=EmployeeLogin.as_view('login')) module_employee.add_url_rule('/admin/logout', view_func=EmployeeLogout.as_view('logout')) module_employee.add_url_rule('/admin/add', view_func=AddEmployee.as_view('add')) module_employee.add_url_rule('/admin/edit', view_func=EditEmployee.as_view('edit')) assignEmployeeAsTeacherView = AssignEmployeeAsTeacher.as_view('assign') module_employee.add_url_rule('/admin/assign', view_func=assignEmployeeAsTeacherView) module_employee.add_url_rule('/admin/delete', view_func=DeleteEmployee.as_view('delete')) module_employee.add_url_rule('/search', view_func=SearchEmployee.as_view('search')) module_employee.add_url_rule('/admin/subject/add', view_func=AddSubject.as_view('add_subject')) ","from openedoo_project import db from openedoo.core.libs import Blueprint from .controllers.employee import EmployeeLogin, EmployeeLogout, AddEmployee, \ AssignEmployeeAsTeacher, EmployeeDashboard, EditEmployee, DeleteEmployee, \ SearchEmployee, AddSubject module_employee = Blueprint('module_employee', __name__, template_folder='templates', static_folder='static') module_employee.add_url_rule('/admin/dashboard', view_func=EmployeeDashboard.as_view('dashboard')) module_employee.add_url_rule('/admin/login', view_func=EmployeeLogin.as_view('login')) module_employee.add_url_rule('/admin/logout', view_func=EmployeeLogout.as_view('logout')) module_employee.add_url_rule('/admin/add', view_func=AddEmployee.as_view('add')) module_employee.add_url_rule('/admin/edit', view_func=EditEmployee.as_view('edit')) assignEmployeeAsTeacherView = AssignEmployeeAsTeacher.as_view('assign') module_employee.add_url_rule('/admin/assign', view_func=assignEmployeeAsTeacherView) module_employee.add_url_rule('/admin/delete', view_func=DeleteEmployee.as_view('delete')) module_employee.add_url_rule('/search', view_func=SearchEmployee.as_view('search')) module_employee.add_url_rule('/admin/subject/add', view_func=AddSubject.as_view('add_subject')) " Fix for queued job support,"<?php /** * If the queued jobs module is installed, this will be used for offline processing of Zip files. * * @author Mark Guinn <mark@adaircreative.com> * @date 05.09.2016 * @package shop_downloadable */ if (!interface_exists('QueuedJob')) { return; } class FilePrepQueuedJob extends AbstractQueuedJob implements QueuedJob { /** * The QueuedJob queue to use when processing updates * @config * @var int */ private static $reindex_queue = 2; // QueuedJob::QUEUED; /** * @param DownloadTempFile $object */ public function __construct($object = null) { if ($object) { $this->setObject($object); } } /** * Helper method */ public function triggerProcessing() { singleton('QueuedJobService')->queueJob($this); } /** * @return string */ public function getTitle() { /** @var DownloadTempFile $obj */ $obj = $this->getObject(); return ""Prep File For Download: "" . ($obj ? $obj->getFriendlyName() : '???'); } /** * Reprocess any needed fields */ public function process() { ini_set('memory_limit', '1G'); /** @var DownloadTempFile $obj */ $obj = $this->getObject(); $obj->process(); $this->isComplete = true; } } ","<?php /** * If the queued jobs module is installed, this will be used for offline processing of Zip files. * * @author Mark Guinn <mark@adaircreative.com> * @date 05.09.2016 * @package shop_downloadable */ if (!interface_exists('QueuedJob')) { return; } class FilePrepQueuedJob extends AbstractQueuedJob implements QueuedJob { /** * The QueuedJob queue to use when processing updates * @config * @var int */ private static $reindex_queue = 2; // QueuedJob::QUEUED; /** * @param DownloadTempFile $object */ public function __construct($object) { $this->setObject($object); } /** * Helper method */ public function triggerProcessing() { singleton('QueuedJobService')->queueJob($this); } /** * @return string */ public function getTitle() { /** @var DownloadTempFile $obj */ $obj = $this->getObject(); return ""Prep File For Download: "" . ($obj ? $obj->getFriendlyName() : '???'); } /** * Reprocess any needed fields */ public function process() { ini_set('memory_limit', '1G'); /** @var DownloadTempFile $obj */ $obj = $this->getObject(); $obj->process(); $this->isComplete = true; } } " Switch to using README.md for project description on pypi.,"from setuptools import setup from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='Flask-Babel', version='0.12.0', url='http://github.com/python-babel/flask-babel', license='BSD', author='Armin Ronacher', author_email='armin.ronacher@active-4.com', description='Adds i18n/l10n support to Flask applications', long_description=long_description, long_description_content_type='text/markdown', packages=['flask_babel'], zip_safe=False, platforms='any', install_requires=[ 'Flask', 'Babel>=2.3', 'Jinja2>=2.5' ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] ) ",""""""" Flask-Babel ----------- Adds i18n/l10n support to Flask applications with the help of the `Babel`_ library. Links ````` * `documentation <http://packages.python.org/Flask-Babel>`_ * `development version <http://github.com/mitsuhiko/flask-babel/zipball/master#egg=Flask-Babel-dev>`_ .. _Babel: http://babel.edgewall.org/ """""" from setuptools import setup setup( name='Flask-Babel', version='0.12.0', url='http://github.com/python-babel/flask-babel', license='BSD', author='Armin Ronacher', author_email='armin.ronacher@active-4.com', description='Adds i18n/l10n support to Flask applications', long_description=__doc__, packages=['flask_babel'], zip_safe=False, platforms='any', install_requires=[ 'Flask', 'Babel>=2.3', 'Jinja2>=2.5' ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] ) " Check when product doesn't have a price.,"package com.tacktic.inbudget; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Rectangle; import io.sphere.sdk.products.ProductProjection; import javax.money.MonetaryAmount; import static com.tacktic.inbudget.BaseScreen.*; import static java.util.Locale.ENGLISH; public class Item extends GameElement { private final String productId; private final Texture texture; private final Rectangle item; private final MonetaryAmount price; public Item(ProductProjection product, Resources resources) { String slug = product.getSlug().get(ENGLISH).orElse(""""); productId = product.getId(); texture = resources.itemImage(slug); item = new Rectangle(); item.width = texture.getWidth(); item.height = texture.getHeight(); item.x = MathUtils.random(VIEWPORT_MARGIN, VIEWPORT_WIDTH - item.width - VIEWPORT_MARGIN); item.y = VIEWPORT_HEIGHT; if (product.getMasterVariant().getPrices().isEmpty()) { throw new RuntimeException(""Product without prices "" + productId); } price = product.getMasterVariant().getPrices().get(0).getValue(); } @Override Texture texture() { return texture; } @Override Rectangle box() { return item; } public String productId() { return productId; } public String price() { String textValue = String.valueOf(price.getNumber().intValueExact()); return ""$"" + textValue; } public void playSound() { } } ","package com.tacktic.inbudget; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Rectangle; import io.sphere.sdk.products.ProductProjection; import javax.money.MonetaryAmount; import static com.tacktic.inbudget.BaseScreen.*; import static java.util.Locale.ENGLISH; public class Item extends GameElement { private final String productId; private final Texture texture; private final Rectangle item; private final MonetaryAmount price; public Item(ProductProjection product, Resources resources) { String slug = product.getSlug().get(ENGLISH).orElse(""""); productId = product.getId(); texture = resources.itemImage(slug); item = new Rectangle(); item.width = texture.getWidth(); item.height = texture.getHeight(); item.x = MathUtils.random(VIEWPORT_MARGIN, VIEWPORT_WIDTH - item.width - VIEWPORT_MARGIN); item.y = VIEWPORT_HEIGHT; price = product.getMasterVariant().getPrices().get(0).getValue(); } @Override Texture texture() { return texture; } @Override Rectangle box() { return item; } public String productId() { return productId; } public String price() { String textValue = String.valueOf(price.getNumber().intValueExact()); return ""$"" + textValue; } public void playSound() { } } " Add watch files in nodemon task,"var gulp = require('gulp'); var nodemon = require('gulp-nodemon'); var concat = require('gulp-concat'); var sass = require('gulp-sass'); var cssPath = [ './vendor/webuploader_fex/dist/webuploader.css', './assets/css/**/*' ]; var jsPath = [ './vendor/jquery/dist/jquery.js', './vendor/webuploader_fex/dist/webuploader.js', './assets/js/**/*' ]; gulp.task('css', function () { gulp.src(cssPath) .pipe(sass()) .pipe(concat('all.css')) .pipe(gulp.dest('./public/css')); }); gulp.task('js', function () { gulp.src(jsPath) .pipe(concat('all.js')) .pipe(gulp.dest('./public/js')); }); gulp.task('watch', function () { gulp.watch('assets/css/**/*', ['css']); gulp.watch('assets/js/**/*', ['js']); }); gulp.task('build', function () { gulp.start(['css', 'js']); }); gulp.task('nodemon', function () { nodemon({ script: './bin/www', ext: 'sass js', env: { 'NODE_ENV': 'development' }, watch: ['app.js', './routes', './bin'] }); }); gulp.task('default', function () { gulp.start('watch'); gulp.start('nodemon'); }); ","var gulp = require('gulp'); var nodemon = require('gulp-nodemon'); var concat = require('gulp-concat'); var sass = require('gulp-sass'); var cssPath = [ './vendor/webuploader_fex/dist/webuploader.css', './assets/css/**/*' ]; var jsPath = [ './vendor/jquery/dist/jquery.js', './vendor/webuploader_fex/dist/webuploader.js', './assets/js/**/*' ]; gulp.task('css', function () { gulp.src(cssPath) .pipe(sass()) .pipe(concat('all.css')) .pipe(gulp.dest('./public/css')); }); gulp.task('js', function () { gulp.src(jsPath) .pipe(concat('all.js')) .pipe(gulp.dest('./public/js')); }); gulp.task('watch', function () { gulp.watch('assets/css/**/*', ['css']); gulp.watch('assets/js/**/*', ['js']); }); gulp.task('build', function () { gulp.start(['css', 'js']); }); gulp.task('nodemon', function () { nodemon({ script: './bin/www', ext: 'sass js', env: { 'NODE_ENV': 'development' } }); }); gulp.task('default', function () { gulp.start('watch'); gulp.start('nodemon'); }); " Set created client to public,"<?php namespace Guzzle\ConfigOperationsBundle\DependencyInjection\CompilerPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; /** * Compiler pass that will add our definitions to Guzzle clients. * * @author Pierre Rolland <roll.pierre@gmail.com> */ class ClientCompilerPass implements CompilerPassInterface { /** * {@inheritdoc} */ public function process(ContainerBuilder $container) { $taggedServices = $container->findTaggedServiceIds( 'guzzle.client' ); $definitions = []; foreach ($taggedServices as $id => $tags) { foreach ($tags as $attributes) { $definitionId = sprintf('guzzle_client.%s', $attributes['alias']); if (!$container->has($definitionId)) { $definition = new Definition(); $definition->setClass('Guzzle\ConfigOperationsBundle\GuzzleClient'); $definition->setFactory([ new Reference('guzzle_config_operations.factory'), 'getClient' ]); $definition->setPublic(true); $definition->addArgument($id); $definitions[$definitionId] = $definition; } } } $container->addDefinitions($definitions); } } ","<?php namespace Guzzle\ConfigOperationsBundle\DependencyInjection\CompilerPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; /** * Compiler pass that will add our definitions to Guzzle clients. * * @author Pierre Rolland <roll.pierre@gmail.com> */ class ClientCompilerPass implements CompilerPassInterface { /** * {@inheritdoc} */ public function process(ContainerBuilder $container) { $taggedServices = $container->findTaggedServiceIds( 'guzzle.client' ); $definitions = []; foreach ($taggedServices as $id => $tags) { foreach ($tags as $attributes) { $definitionId = sprintf('guzzle_client.%s', $attributes['alias']); if (!$container->has($definitionId)) { $definition = new Definition(); $definition->setClass('Guzzle\ConfigOperationsBundle\GuzzleClient'); $definition->setFactory([ new Reference('guzzle_config_operations.factory'), 'getClient' ]); $definition->addArgument($id); $definitions[$definitionId] = $definition; } } } $container->addDefinitions($definitions); } } " Enforce URL ends with whats passed from json,"exports.generateDefaultStub = function (data) { angular .module(data['stub-options']['module_name'], [ 'ngMockE2E', 'app' ]) .run(function ($httpBackend) { var createStub = function (method, example, $httpBackend) { var httpMethod = method.toUpperCase(), url = new RegExp(example.request.url + '$'), res = example.response; $httpBackend ['when' + httpMethod](url) .respond(function (method, url) { return [res.status, res.body]; }); }, methodData, method; delete data['stub-options']; for (methodData in data) { var httpMethod = data[methodData].method, examples = data[methodData].examples; for (method in examples) { createStub( httpMethod, examples[method], $httpBackend ); } } }); }; ","exports.generateDefaultStub = function (data) { angular .module(data['stub-options']['module_name'], [ 'ngMockE2E', 'app' ]) .run(function ($httpBackend) { var createStub = function (method, example, $httpBackend) { var httpMethod = method.toUpperCase(), url = new RegExp(example.request.url), res = example.response; $httpBackend ['when' + httpMethod](url) .respond(function (method, url) { return [res.status, res.body]; }); }, methodData, method; delete data['stub-options']; for (methodData in data) { var httpMethod = data[methodData].method, examples = data[methodData].examples; for (method in examples) { createStub( httpMethod, examples[method], $httpBackend ); } } }); }; " "Fix imports that broke when running in strict mode The badly place semicolon triggered ""undefined variable"" errors.","var debug = require('debug')('metalsmith-copy'), path = require('path'), cloneDeep = require('lodash').cloneDeep, minimatch = require('minimatch'); module.exports = plugin; function plugin(options) { return function(files, metalsmith, done) { if (!options.directory && !options.extension && !options.transform) return done(new Error('metalsmith-copy: ""directory"" or ""extension"" option required')); var matcher = minimatch.Minimatch(options.pattern); Object.keys(files).forEach(function (file) { debug('checking file: ' + file); if (!matcher.match(file)) return; var newName = file; // transform filename if (options.transform) { newName = options.transform(file); } else { if (options.extension) { var currentExt = path.extname(file); newName = path.join(path.dirname(file), path.basename(file, currentExt) + options.extension); } if (options.directory) { newName = path.join(options.directory, path.basename(newName)); } } if (files[newName]) return done(new Error('metalsmith-copy: copying ' + file + ' to ' + newName + ' would overwrite file')); debug('copying file: ' + newName); files[newName] = cloneDeep(files[file], function(value) { if (value instanceof Buffer) { return new Buffer(value); } }); if (options.move) { delete files[file]; } }); done(); } } ","var debug = require('debug')('metalsmith-copy'), path = require('path'), cloneDeep = require('lodash').cloneDeep; minimatch = require('minimatch'); module.exports = plugin; function plugin(options) { return function(files, metalsmith, done) { if (!options.directory && !options.extension && !options.transform) return done(new Error('metalsmith-copy: ""directory"" or ""extension"" option required')); var matcher = minimatch.Minimatch(options.pattern); Object.keys(files).forEach(function (file) { debug('checking file: ' + file); if (!matcher.match(file)) return; var newName = file; // transform filename if (options.transform) { newName = options.transform(file); } else { if (options.extension) { var currentExt = path.extname(file); newName = path.join(path.dirname(file), path.basename(file, currentExt) + options.extension); } if (options.directory) { newName = path.join(options.directory, path.basename(newName)); } } if (files[newName]) return done(new Error('metalsmith-copy: copying ' + file + ' to ' + newName + ' would overwrite file')); debug('copying file: ' + newName); files[newName] = cloneDeep(files[file], function(value) { if (value instanceof Buffer) { return new Buffer(value); } }); if (options.move) { delete files[file]; } }); done(); } } " "Check for a fileversion region before copying them to the source region This is mainly for test fileversions that are created without regions by default"," def copy_files(src, target_node, parent=None, name=None): """"""Copy the files from src to the target node :param Folder src: The source to copy children from :param Node target_node: The node to copy files to :param Folder parent: The parent of to attach the clone of src to, if applicable """""" assert not parent or not parent.is_file, 'Parent must be a folder' cloned = src.clone() cloned.parent = parent cloned.target = target_node cloned.name = name or cloned.name cloned.copied_from = src cloned.save() if src.is_file and src.versions.exists(): fileversions = src.versions.select_related('region').order_by('-created') most_recent_fileversion = fileversions.first() if most_recent_fileversion.region and most_recent_fileversion.region != target_node.osfstorage_region: # add all original version except the most recent cloned.versions.add(*fileversions[1:]) # create a new most recent version and update the region before adding new_fileversion = most_recent_fileversion.clone() new_fileversion.region = target_node.osfstorage_region new_fileversion.save() cloned.versions.add(new_fileversion) else: cloned.versions.add(*src.versions.all()) if not src.is_file: for child in src.children: copy_files(child, target_node, parent=cloned) return cloned "," def copy_files(src, target_node, parent=None, name=None): """"""Copy the files from src to the target node :param Folder src: The source to copy children from :param Node target_node: The node to copy files to :param Folder parent: The parent of to attach the clone of src to, if applicable """""" assert not parent or not parent.is_file, 'Parent must be a folder' cloned = src.clone() cloned.parent = parent cloned.target = target_node cloned.name = name or cloned.name cloned.copied_from = src cloned.save() if src.is_file and src.versions.exists(): fileversions = src.versions.select_related('region').order_by('-created') most_recent_fileversion = fileversions.first() if most_recent_fileversion.region != target_node.osfstorage_region: # add all original version except the most recent cloned.versions.add(*fileversions[1:]) # create a new most recent version and update the region before adding new_fileversion = most_recent_fileversion.clone() new_fileversion.region = target_node.osfstorage_region new_fileversion.save() cloned.versions.add(new_fileversion) else: cloned.versions.add(*src.versions.all()) if not src.is_file: for child in src.children: copy_files(child, target_node, parent=cloned) return cloned " "Fix 'No Files Found"" showing when files are found","import Ember from 'ember'; export default Ember.Component.extend({ showSelect: false, noFileFound: true, //make computed property that observers the layers.[] and if change see if there is a file didRender() { console.log(this.get('layer.settings.values.downloadLink') , this.get('noFileFound')) if(!this.get('layer.settings.values.downloadLink')){ this.get('node.files').then((result)=>{ result.objectAt(0).get('files').then((files)=>{ console.log(""files.length"" , files.length); if(files.length === 0){ this.set('noFileFound', true); return false; }else{ this.set('noFileFound', false); } let fileDatesLinks = {} let fileModifiedDates = [] for(let i = 0; i < files.length; i++){ fileModifiedDates.push(files.objectAt(i).get('dateModified')); fileDatesLinks[files.objectAt(i).get('dateModified')] = files.objectAt(i).get('links').download; } let mostRecentDate = new Date(Math.max.apply(null,fileModifiedDates)); this.set('layer.settings.values.downloadLink' , fileDatesLinks[mostRecentDate]); }); }); }else{ this.set('noFileFound', false); } }, actions: { fileDetail(file) { this.set('showSelect', false); this.set('layer.settings.values.downloadLink' , file.data.links.download) }, showSelect(){ this.set('showSelect', true); }, hideSelect(){ this.set('showSelect', false); } } }); ","import Ember from 'ember'; export default Ember.Component.extend({ showSelect: false, noFileFound: true, didRender() { if(!this.get('layer.settings.values.downloadLink')){ this.get('node.files').then((result)=>{ result.objectAt(0).get('files').then((files)=>{ if(files.length === 0){ this.set('noFileFound', true); return false; }else{ this.set('noFileFound', false); } let fileDatesLinks = {} let fileModifiedDates = [] for(let i = 0; i < files.length; i++){ fileModifiedDates.push(files.objectAt(i).get('dateModified')); fileDatesLinks[files.objectAt(i).get('dateModified')] = files.objectAt(i).get('links').download; } let mostRecentDate = new Date(Math.max.apply(null,fileModifiedDates)); this.set('layer.settings.values.downloadLink' , fileDatesLinks[mostRecentDate]); }); }); } }, actions: { fileDetail(file) { this.set('showSelect', false); this.set('layer.settings.values.downloadLink' , file.data.links.download) }, showSelect(){ this.set('showSelect', true); }, hideSelect(){ this.set('showSelect', false); } } }); " "Add informative message on first run. Signed-off-by: François de Metz <5187da0b934cc25eb2201a3ec9206c24b13cb23b@2metz.fr>","#!/usr/bin/env node var argv = require('optimist').boolean('billable') .default('hours', 8) .argv , config = require('../config') , intervals = require('../intervals') ; function processTime(token) { if (!argv.date) { console.log('Usage: intervals --date 2011-03-13 --hours 8 [--billable]'); } else { console.log('add '+ argv.hours +' hours '+ (argv.billable ? 'billable' : 'non billable') +' for '+ argv.date); intervals.addTime({ time: argv.hours, date: argv.date, billable: argv.billable }, intervals.createClient(token), function(err, res) { if (err) throw err; if (res.status != 201) throw res.body; console.log('Success ! time added'); }); } } config.read(function(err, value) { if (err) { if (err.code == 'ENOENT') { process.stdout.write('Please enter your token (go to https://xx.timetask.com/account/api/ and generate a new one): '); intervals.readInput(function(input) { config.write({token: input}, function(err) { if (err) throw err; console.log('token saved in '+ config.path); processTime(input); }); }); } } else { processTime(value.token); } }); ","#!/usr/bin/env node var argv = require('optimist').boolean('billable') .default('hours', 8) .argv , config = require('../config') , intervals = require('../intervals') ; function processTime(token) { if (!argv.date) { console.log('Usage: intervals --date 2011-03-13 --hours 8 [--billable]'); } else { console.log('add '+ argv.hours +' hours '+ (argv.billable ? 'billable' : 'non billable') +' for '+ argv.date); intervals.addTime({ time: argv.hours, date: argv.date, billable: argv.billable }, intervals.createClient(token), function(err, res) { if (err) throw err; if (res.status != 201) throw res.body; console.log('Success ! time added'); }); } } config.read(function(err, value) { if (err) { if (err.code == 'ENOENT') { process.stdout.write('Please enter your token: '); intervals.readInput(function(input) { config.write({token: input}, function(err) { if (err) throw err; console.log('token saved in '+ config.path); processTime(input); }); }); } } else { processTime(value.token); } }); " Correct argument name in script to format reago input file,"#!/usr/bin/python # -*- coding: utf-8 -*- import sys import os import argparse import re reago_dir = '/tools/rna_manipulation/reago/reago/' def add_read_pair_num(input_filepath, output_filepath, read_pair_num): to_add = '.' + str(read_pair_num) with open(input_filepath,'r') as input_file: with open(output_filepath,'w') as output_file: for line in input_file: if line[0] == '>': split_line = line.split() seq_id = split_line[0] if seq_id.rfind(to_add) != (len(seq_id)-len(to_add)): split_line[0] = seq_id + to_add output_file.write(' '.join(split_line) + '\n') else: output_file.write(line) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--r1_sequence_file', required=True) parser.add_argument('--r2_sequence_file', required=True) args = parser.parse_args() add_read_pair_num(args.r1_sequence_file, args.r1_sequence_file, 1) add_read_pair_num(args.r2_sequence_file, args.r2_sequence_file, 2)","#!/usr/bin/python # -*- coding: utf-8 -*- import sys import os import argparse import re reago_dir = '/tools/rna_manipulation/reago/reago/' def add_read_pair_num(input_filepath, output_filepath, read_pair_num): to_add = '.' + str(read_pair_num) with open(input_filepath,'r') as input_file: with open(output_filepath,'w') as output_file: for line in input_file: if line[0] == '>': split_line = line.split() seq_id = split_line[0] if seq_id.rfind(to_add) != (len(seq_id)-len(to_add)): split_line[0] = seq_id + to_add output_file.write(' '.join(split_line) + '\n') else: output_file.write(line) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--r1_sequence_file', required=True) parser.add_argument('--r2_sequence_file', required=True) args = parser.parse_args() add_read_pair_num(args.r1_input_sequence_file, args.r1_input_sequence_file, 1) add_read_pair_num(args.r2_input_sequence_file, args.r2_input_sequence_file, 2)" Add user_id to returned transactions,"from django.db import models from django.db.models import Sum class User(models.Model): name = models.CharField(max_length=254, unique=True) create_date = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) mail_address = models.EmailField(null=True) @property def last_transaction(self): try: return self.transactions.last().create_date except AttributeError: return None @property def balance(self): return self.transactions.aggregate(sum=Sum('value'))['sum'] or 0 def to_full_dict(self): return {'id': self.id, 'name': self.name, 'mail_address': self.mail_address, 'balance': self.balance, 'last_transaction': self.last_transaction} def to_dict(self): return {'id': self.id, 'name': self.name, 'balance': self.balance, 'last_transaction': self.last_transaction} def __str__(self): return self.name class Transaction(models.Model): user = models.ForeignKey('User', related_name='transactions', on_delete=models.PROTECT, db_index=True) create_date = models.DateTimeField(auto_now_add=True) value = models.IntegerField() def to_dict(self): return {'id': self.id, 'create_date': self.create_date, 'value': self.value, 'user': self.user_id} class Meta: ordering = ('create_date',) ","from django.db import models from django.db.models import Sum class User(models.Model): name = models.CharField(max_length=254, unique=True) create_date = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) mail_address = models.EmailField(null=True) @property def last_transaction(self): try: return self.transactions.last().create_date except AttributeError: return None @property def balance(self): return self.transactions.aggregate(sum=Sum('value'))['sum'] or 0 def to_full_dict(self): return {'id': self.id, 'name': self.name, 'mail_address': self.mail_address, 'balance': self.balance, 'last_transaction': self.last_transaction} def to_dict(self): return {'id': self.id, 'name': self.name, 'balance': self.balance, 'last_transaction': self.last_transaction} def __str__(self): return self.name class Transaction(models.Model): user = models.ForeignKey('User', related_name='transactions', on_delete=models.PROTECT, db_index=True) create_date = models.DateTimeField(auto_now_add=True) value = models.IntegerField() def to_dict(self): return {'id': self.id, 'create_date': self.create_date, 'value': self.value} class Meta: ordering = ('create_date',) " Add xml header and post data as stream-like object just to be sure,"# coding=utf-8 from __future__ import unicode_literals from io import BytesIO from .marc import Record from .util import etree, parse_xml, show_diff class Bib(object): """""" An Alma Bib record """""" def __init__(self, alma, xml): self.alma = alma self.orig_xml = xml.encode('utf-8') self.init(xml) def init(self, xml): self.doc = parse_xml(xml) self.mms_id = self.doc.findtext('mms_id') self.marc_record = Record(self.doc.find('record')) self.linked_to_cz = self.doc.findtext('linked_record_id[@type=""CZ""]') or None def save(self, diff=False): # Save record back to Alma post_data = ('<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>'.encode('utf-8') + etree.tostring(self.doc, encoding='UTF-8')) if diff: show_diff(self.orig_xml, post_data) response = self.alma.put('/bibs/{}'.format(self.mms_id), data=BytesIO(post_data), headers={'Content-Type': 'application/xml'}) self.init(response) def dump(self, filename): # Dump record to file with open(filename, 'wb') as f: f.write(etree.tostring(self.doc, pretty_print=True)) ","# coding=utf-8 from __future__ import unicode_literals from .marc import Record from .util import etree, parse_xml, show_diff class Bib(object): """""" An Alma Bib record """""" def __init__(self, alma, xml): self.alma = alma self.orig_xml = xml.encode('utf-8') self.init(xml) def init(self, xml): self.doc = parse_xml(xml) self.mms_id = self.doc.findtext('mms_id') self.marc_record = Record(self.doc.find('record')) self.linked_to_cz = self.doc.findtext('linked_record_id[@type=""CZ""]') or None def save(self, diff=False): # Save record back to Alma post_data = etree.tostring(self.doc, encoding='UTF-8') if diff: show_diff(self.orig_xml, post_data) response = self.alma.put('/bibs/{}'.format(self.mms_id), data=post_data, headers={'Content-Type': 'application/xml'}) self.init(response) def dump(self, filename): # Dump record to file with open(filename, 'wb') as f: f.write(etree.tostring(self.doc, pretty_print=True)) " Add whitespace between title and text for search index.,"import re from django.test.client import RequestFactory from django.template import RequestContext from haystack import indexes from cms import models as cmsmodels rf = RequestFactory() HTML_TAG_RE = re.compile(r'<[^>]+>') def cleanup_content(s): """""" Removes HTML tags from data and replaces them with spaces. """""" return HTML_TAG_RE.subn('', s)[0] class PageIndex(indexes.SearchIndex, indexes.Indexable): """""" Since for now we only offer this site in one language, we can get around by not doing any language model hacks. """""" text = indexes.CharField(document=True) title = indexes.CharField() url = indexes.CharField() def get_model(self): return cmsmodels.Page def index_queryset(self, using=None): return self.get_model().objects.filter(published=True) def prepare(self, obj): self.prepared_data = super(PageIndex, self).prepare(obj) request = rf.get('/') request.session = {} text = u"""" # Let's extract the title context = RequestContext(request) for title in obj.title_set.all(): self.prepared_data['title'] = title.title for placeholder in obj.placeholders.all(): text += placeholder.render(context, None) self.prepared_data['text'] = cleanup_content( self.prepared_data['title'] + u' ' + text) self.prepared_data['url'] = obj.get_absolute_url() return self.prepared_data ","import re from django.test.client import RequestFactory from django.template import RequestContext from haystack import indexes from cms import models as cmsmodels rf = RequestFactory() HTML_TAG_RE = re.compile(r'<[^>]+>') def cleanup_content(s): """""" Removes HTML tags from data and replaces them with spaces. """""" return HTML_TAG_RE.subn('', s)[0] class PageIndex(indexes.SearchIndex, indexes.Indexable): """""" Since for now we only offer this site in one language, we can get around by not doing any language model hacks. """""" text = indexes.CharField(document=True) title = indexes.CharField() url = indexes.CharField() def get_model(self): return cmsmodels.Page def index_queryset(self, using=None): return self.get_model().objects.filter(published=True) def prepare(self, obj): self.prepared_data = super(PageIndex, self).prepare(obj) request = rf.get('/') request.session = {} text = u"""" # Let's extract the title context = RequestContext(request) for title in obj.title_set.all(): self.prepared_data['title'] = title.title for placeholder in obj.placeholders.all(): text += placeholder.render(context, None) self.prepared_data['text'] = cleanup_content( self.prepared_data['title'] + text) self.prepared_data['url'] = obj.get_absolute_url() return self.prepared_data " Remove unused var to fix lint error,"import React, { PropTypes } from 'react' import {LineChart} from 'react-d3-basic' class RoomChart extends React.Component { static propTypes = { data: PropTypes.object }; render () { const {data} = this.props let activity = [] if (data && data.activity) { activity = data.activity } const chartData = activity.map((chunk) => { return { timestamp: new Date(chunk[0] * 1000), messages: chunk[1] } }) const width = 550 return ( <LineChart data={chartData} width={width} height={300} margins={{ top: 25, bottom: 60, right: 25, left: 50 }} chartSeries={[ { field: 'messages', name: 'Messages', color: '#ff7600', style: { 'stroke-width': 2.5 } } ]} x={(d) => d.timestamp} xScale='time' innerTickSize={20} /> ) } } export default RoomChart ","import React, { PropTypes } from 'react' import {LineChart} from 'react-d3-basic' import classes from './RoomChart.scss' class RoomChart extends React.Component { static propTypes = { data: PropTypes.object }; render () { const {data} = this.props let activity = [] if (data && data.activity) { activity = data.activity } const chartData = activity.map((chunk) => { return { timestamp: new Date(chunk[0] * 1000), messages: chunk[1] } }) const width = 550 return ( <LineChart data={chartData} width={width} height={300} margins={{ top: 25, bottom: 60, right: 25, left: 50 }} chartSeries={[ { field: 'messages', name: 'Messages', color: '#ff7600', style: { 'stroke-width': 2.5 } } ]} x={(d) => d.timestamp} xScale='time' innerTickSize={20} /> ) } } export default RoomChart " Set static/docs as the default folder to generate the apidoc's files,"# Copyright 2015 Vinicius Chiele. All rights reserved. # # 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. try: import flask_script except ImportError: raise ImportError('Missing flask-script library (pip install flask-script)') import subprocess from flask_script import Command class GenerateApiDoc(Command): def __init__(self, input_path=None, output_path=None, template_path=None): super().__init__() self.input_path = input_path self.output_path = output_path or 'static/docs' self.template_path = template_path def run(self): cmd = ['apidoc'] if self.input_path: cmd.append('--input') cmd.append(self.input_path) if self.output_path: cmd.append('--output') cmd.append(self.output_path) if self.template_path: cmd.append('--template') cmd.append(self.template_path) return subprocess.call(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) ","# Copyright 2015 Vinicius Chiele. All rights reserved. # # 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. try: import flask_script except ImportError: raise ImportError('Missing flask-script library (pip install flask-script)') import subprocess from flask_script import Command class GenerateApiDoc(Command): def __init__(self, input_path=None, output_path=None, template_path=None): super().__init__() self.input_path = input_path self.output_path = output_path self.template_path = template_path def run(self): cmd = ['apidoc'] if self.input_path: cmd.append('--input') cmd.append(self.input_path) if self.output_path: cmd.append('--output') cmd.append(self.output_path) if self.template_path: cmd.append('--template') cmd.append(self.template_path) return subprocess.call(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) " Add output file type option,"import ast import click from graphing.graph import FunctionGrapher from parsing.parser import FileVisitor @click.command() @click.argument('code', type=click.File('rb')) @click.option('--printed', default=False, is_flag=True, help='Pretty prints the call tree for each class in the file') @click.option('--remove-builtins', default=False, is_flag=True, help='Removes builtin functions from call trees') @click.option('--output', help='Graphviz output file name') @click.option('--output-format', default='pdf', help='File type for graphviz output file') def cli(code, printed, remove_builtins, output, output_format): """""" Parses a file. codegrapher [file_name] """""" parsed_code = ast.parse(code.read(), filename='code.py') visitor = FileVisitor() visitor.visit(parsed_code) if printed: click.echo('Classes in file:') for class_object in visitor.classes: if remove_builtins: class_object.remove_builtins() click.echo('=' * 80) click.echo(class_object.name) click.echo(class_object.pprint()) click.echo('') if output: graph = FunctionGrapher() class_names = set(cls.name for cls in visitor.classes) for cls in visitor.classes: graph.add_dict_to_graph(class_names, cls.call_tree) graph.add_classes_to_graph(visitor.classes) graph.name = output graph.dot_file.format = output_format graph.render() ","import ast import click from graphing.graph import FunctionGrapher from parsing.parser import FileVisitor @click.command() @click.argument('code', type=click.File('rb')) @click.option('--printed', default=False, is_flag=True, help='Pretty prints the call tree for each class in the file') @click.option('--remove-builtins', default=False, is_flag=True, help='Removes builtin functions from call trees') @click.option('--output', help='Graphviz output file name') def cli(code, printed, remove_builtins, output): """""" Parses a file. codegrapher [file_name] """""" parsed_code = ast.parse(code.read(), filename='code.py') visitor = FileVisitor() visitor.visit(parsed_code) if printed: click.echo('Classes in file:') for class_object in visitor.classes: if remove_builtins: class_object.remove_builtins() click.echo('=' * 80) click.echo(class_object.name) click.echo(class_object.pprint()) click.echo('') if output: graph = FunctionGrapher() class_names = set(cls.name for cls in visitor.classes) for cls in visitor.classes: graph.add_dict_to_graph(class_names, cls.call_tree) graph.add_classes_to_graph(visitor.classes) graph.name = output graph.render() " Correct classifiers from the pypi trove entries,"from distutils.core import setup setup(name=""stellar-magnate"", version=""0.1"", description=""A space-themed commodity trading game"", long_description="""""" Stellar Magnate is a space-themed trading game in the spirit of Planetary Travel by Brian Winn. """""", author=""Toshio Kuratomi"", author_email=""toshio@fedoraproject.org"", maintainer=""Toshio Kuratomi"", maintainer_email=""toshio@fedoraproject.org"", url=""https://github.com/abadger/pubmarine"", license=""GNU Affero General Public License v3 or later (AGPLv3+)"", keywords='game trading', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console :: Curses', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Games/Entertainment', 'Topic :: Games/Entertainment :: Simulation', ], packages=['magnate', 'magnate.ui'], scripts=['bin/magnate'], install_requires=['pubmarine >= 0.3', 'urwid', 'straight.plugin'], ) ","from distutils.core import setup setup(name=""stellar-magnate"", version=""0.1"", description=""A space-themed commodity trading game"", long_description="""""" Stellar Magnate is a space-themed trading game in the spirit of Planetary Travel, a trading game for the Apple IIe by Brian Winn. """""", author=""Toshio Kuratomi"", author_email=""toshio@fedoraproject.org"", maintainer=""Toshio Kuratomi"", maintainer_email=""toshio@fedoraproject.org"", url=""https://github.com/abadger/pubmarine"", license=""GNU Affero General Public License v3+"", keywords='game trading', classifiers=[ 'Development Status :: 3 - Alpha', #'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', #'Topic :: Software Development :: Libraries :: Python Modules', ], packages=['magnate', 'magnate.ui'], scripts=['bin/magnate'], install_requires=['pubmarine >= 0.3', 'urwid', 'straight.plugin'], ) " Deal with transformer with retuns array,"<?php namespace Rezzza\Jobflow\Extension\ETL\Processor; use Knp\ETL\ContextInterface; use Knp\ETL\TransformerInterface; use Psr\Log\LoggerInterface; use Rezzza\Jobflow\Metadata\MetadataAccessor; use Rezzza\Jobflow\Processor\JobProcessor; use Rezzza\Jobflow\Scheduler\ExecutionContext; class TransformerProxy extends ETLProcessor implements TransformerInterface, JobProcessor { public function __construct(TransformerInterface $processor, MetadataAccessor $metadataAccessor, LoggerInterface $logger = null) { // Construct used for TypeHinting parent::__construct($processor, $metadataAccessor, $logger); } public function transform($data, ContextInterface $context) { return $this->processor->transform($data, $context); } public function execute(ExecutionContext $execution) { $data = $execution->read(); $this->debug(count($data) .' rows'); foreach ($data as $k => $result) { $value = $result->getValue(); $metadata = $result->getMetadata(); $context = $this->createContext($execution, $metadata); $transformedData = $this->transform($value, $context); if (is_array($transformedData)) { foreach ($transformedData as $d) { $this->writeData($value, $metadata, $execution, $d); } } else { $this->writeData($value, $metadata, $execution, $transformedData); } } $execution->valid(); } private function writeData($value, $metadata, $execution, $data) { $metadata = $this->metadataAccessor->createMetadata($value, $metadata); $execution->write($data, $metadata); } } ","<?php namespace Rezzza\Jobflow\Extension\ETL\Processor; use Knp\ETL\ContextInterface; use Knp\ETL\TransformerInterface; use Psr\Log\LoggerInterface; use Rezzza\Jobflow\Metadata\MetadataAccessor; use Rezzza\Jobflow\Processor\JobProcessor; use Rezzza\Jobflow\Scheduler\ExecutionContext; class TransformerProxy extends ETLProcessor implements TransformerInterface, JobProcessor { public function __construct(TransformerInterface $processor, MetadataAccessor $metadataAccessor, LoggerInterface $logger = null) { // Construct used for TypeHinting parent::__construct($processor, $metadataAccessor, $logger); } public function transform($data, ContextInterface $context) { return $this->processor->transform($data, $context); } public function execute(ExecutionContext $execution) { $data = $execution->read(); $this->debug(count($data) .' rows'); foreach ($data as $k => $result) { $value = $result->getValue(); $metadata = $result->getMetadata(); $context = $this->createContext($execution, $metadata); $transformedData = $this->transform($value, $context); $metadata = $this->metadataAccessor->createMetadata($value, $metadata); $execution->write($transformedData, $metadata); } $execution->valid(); } } " Mark batch syncs as such to help with caching,"<?php declare(strict_types=1); // phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter,SlevomatCodingStandard.Functions.UnusedParameter namespace App\Nova\Actions; use App\Jobs\PushToJedi; use Illuminate\Support\Str; use Illuminate\Bus\Queueable; use Laravel\Nova\Actions\Action; use Illuminate\Support\Collection; use Laravel\Nova\Fields\ActionFields; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; class SyncAccess extends Action { use InteractsWithQueue, Queueable, SerializesModels; /** * Perform the action on the given models. * * @param \Laravel\Nova\Fields\ActionFields $fields * @param \Illuminate\Support\Collection $models * * @return void * * @suppress PhanPossiblyNonClassMethodCall */ public function handle(ActionFields $fields, Collection $models): void { foreach ($models as $user) { if (Str::startsWith($user->uid, 'svc_')) { continue; } // I tried to make this class ShouldQueue so Nova would handle queueing // but was getting an exception. I think it's fine to run synchronously...? PushToJedi::dispatchNow( $user, self::class, request()->user()->id, count($models) === 1 ? 'manual' : 'manual_batch' ); } } /** * Get the fields available on the action. * * @return array<\Laravel\Nova\Fields\Field> */ public function fields(): array { return []; } } ","<?php declare(strict_types=1); // phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter,SlevomatCodingStandard.Functions.UnusedParameter namespace App\Nova\Actions; use App\Jobs\PushToJedi; use Illuminate\Support\Str; use Illuminate\Bus\Queueable; use Laravel\Nova\Actions\Action; use Illuminate\Support\Collection; use Laravel\Nova\Fields\ActionFields; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; class SyncAccess extends Action { use InteractsWithQueue, Queueable, SerializesModels; /** * Perform the action on the given models. * * @param \Laravel\Nova\Fields\ActionFields $fields * @param \Illuminate\Support\Collection $models * * @return void * * @suppress PhanPossiblyNonClassMethodCall */ public function handle(ActionFields $fields, Collection $models): void { foreach ($models as $user) { if (Str::startsWith($user->uid, 'svc_')) { continue; } // I tried to make this class ShouldQueue so Nova would handle queueing // but was getting an exception. I think it's fine to run synchronously...? PushToJedi::dispatchNow($user, self::class, request()->user()->id, 'manual'); } } /** * Get the fields available on the action. * * @return array<\Laravel\Nova\Fields\Field> */ public function fields(): array { return []; } } " Allow periods and dashes in profile page,""""""" URLConf for Django user profile management. Recommended usage is to use a call to ``include()`` in your project's root URLConf to include this URLConf for any URL beginning with '/profiles/'. If the default behavior of the profile views is acceptable to you, simply use a line like this in your root URLConf to set up the default URLs for profiles:: (r'^profiles/', include('profiles.urls')), But if you'd like to customize the behavior (e.g., by passing extra arguments to the various views) or split up the URLs, feel free to set up your own URL patterns for these views instead. If you do, it's a good idea to keep the name ``profiles_profile_detail`` for the pattern which points to the ``profile_detail`` view, since several views use ``reverse()`` with that name to generate a default post-submission redirect. If you don't use that name, remember to explicitly pass ``success_url`` to those views. """""" from django.conf.urls import * from profiles import views urlpatterns = patterns('', url(r'^create/$', views.create_profile, name='profiles_create_profile'), url(r'^edit/$', views.edit_profile, name='profiles_edit_profile'), url(r'^(?P<username>[\w-.]+)/$', views.profile_detail, name='profiles_profile_detail'), url(r'^$', views.ProfileListView.as_view(), name='profiles_profile_list'), ) ",""""""" URLConf for Django user profile management. Recommended usage is to use a call to ``include()`` in your project's root URLConf to include this URLConf for any URL beginning with '/profiles/'. If the default behavior of the profile views is acceptable to you, simply use a line like this in your root URLConf to set up the default URLs for profiles:: (r'^profiles/', include('profiles.urls')), But if you'd like to customize the behavior (e.g., by passing extra arguments to the various views) or split up the URLs, feel free to set up your own URL patterns for these views instead. If you do, it's a good idea to keep the name ``profiles_profile_detail`` for the pattern which points to the ``profile_detail`` view, since several views use ``reverse()`` with that name to generate a default post-submission redirect. If you don't use that name, remember to explicitly pass ``success_url`` to those views. """""" from django.conf.urls import * from profiles import views urlpatterns = patterns('', url(r'^create/$', views.create_profile, name='profiles_create_profile'), url(r'^edit/$', views.edit_profile, name='profiles_edit_profile'), url(r'^(?P<username>\w+)/$', views.profile_detail, name='profiles_profile_detail'), url(r'^$', views.ProfileListView.as_view(), name='profiles_profile_list'), ) " "Read the docs, setTo takes an array of addresses, which is the right way to do it, not implode it with commas.","<?php namespace BisonLab\SakonninBundle\Lib\Sakonnin; /* */ class MailForward { protected $container; protected $router; public function __construct($container, $options = array()) { $this->container = $container; } /* You may call this lazyness, jkust having an options array, but it's also * more future proof. */ public function execute($options = array()) { $message = $options['message']; $router = $this->getRouter(); $url = $router->generate('message_show', array('id' => $message->getId()), true); // Not gonna do html, yet at least.. // $body = '<a href=""' . $url . '"">Link to this message</a>' . ""\n\n""; $body = ""Link to this message: "" . $url . ""\n\n""; $body .= $message->getBody(); $mail = \Swift_Message::newInstance() ->setSubject($message->getSubject()) ->setFrom($message->getFrom()) ->setTo($options['attributes']) ->setBody($body, 'text/plain' ) ; $this->container->get('mailer')->send($mail); return true; } public function getRouter() { if (!$this->router) { $this->router = $this->container->get('router'); } return $this->router; } } ","<?php namespace BisonLab\SakonninBundle\Lib\Sakonnin; /* */ class MailForward { protected $container; protected $router; public function __construct($container, $options = array()) { $this->container = $container; } /* You may call this lazyness, jkust having an options array, but it's also * more future proof. */ public function execute($options = array()) { $message = $options['message']; $router = $this->getRouter(); $url = $router->generate('message_show', array('id' => $message->getId()), true); // Not gonna do html, yet at least.. // $body = '<a href=""' . $url . '"">Link to this message</a>' . ""\n\n""; $body = ""Link to this message: "" . $url . ""\n\n""; $body .= $message->getBody(); $mail = \Swift_Message::newInstance() ->setSubject($message->getSubject()) ->setFrom($message->getFrom()) ->setTo(implode("","", $options['attributes'])) ->setBody($body, 'text/plain' ) ; $this->container->get('mailer')->send($mail); return true; } public function getRouter() { if (!$this->router) { $this->router = $this->container->get('router'); } return $this->router; } } " "Add python-coveralls as a test dependency This is so that we can push our coverage stats to coverage.io.","#!/usr/bin/env python import os import sys from serfclient import __version__ try: from setuptools import setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest errno = pytest.main(self.test_args) sys.exit(errno) except ImportError: from distutils.core import setup PyTest = lambda x: x try: long_description = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() except: long_description = None setup( name='serfclient', version=__version__, description='Python client for the Serf orchestration tool', long_description=long_description, url='https://github.com/KushalP/serfclient-py', author='Kushal Pisavadia', author_email='kushal@violentlymild.com', maintainer='Kushal Pisavadia', maintainer_email='kushal@violentlymild.com', keywords=['Serf', 'orchestration', 'service discovery'], license='MIT', packages=['serfclient'], install_requires=['msgpack-python >= 0.4.0'], tests_require=['pytest >= 2.5.2', 'pytest-cov >= 1.6', 'python-coveralls >= 2.4.2'], cmdclass={'test': PyTest} ) ","#!/usr/bin/env python import os import sys from serfclient import __version__ try: from setuptools import setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest errno = pytest.main(self.test_args) sys.exit(errno) except ImportError: from distutils.core import setup PyTest = lambda x: x try: long_description = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() except: long_description = None setup( name='serfclient', version=__version__, description='Python client for the Serf orchestration tool', long_description=long_description, url='https://github.com/KushalP/serfclient-py', author='Kushal Pisavadia', author_email='kushal@violentlymild.com', maintainer='Kushal Pisavadia', maintainer_email='kushal@violentlymild.com', keywords=['Serf', 'orchestration', 'service discovery'], license='MIT', packages=['serfclient'], install_requires=['msgpack-python >= 0.4.0'], tests_require=['pytest >= 2.5.2', 'pytest-cov >= 1.6'], cmdclass={'test': PyTest} ) " Statistics: Adjust label angle to 30°,"/*globals $, Morris, gettext*/ $(function () { $("".chart"").css(""height"", ""250px""); new Morris.Area({ element: 'obd_chart', data: JSON.parse($(""#obd-data"").html()), xkey: 'date', ykeys: ['ordered', 'paid'], labels: [gettext('Placed orders'), gettext('Paid orders')], lineColors: ['#000099', '#009900'], smooth: false, resize: true, fillOpacity: 0.3, behaveLikeLine: true }); new Morris.Area({ element: 'rev_chart', data: JSON.parse($(""#rev-data"").html()), xkey: 'date', ykeys: ['revenue'], labels: [gettext('Total revenue')], smooth: false, resize: true, fillOpacity: 0.3, preUnits: $.trim($(""#currency"").html()) + ' ' }); new Morris.Bar({ element: 'obp_chart', data: JSON.parse($(""#obp-data"").html()), xkey: 'item', ykeys: ['ordered', 'paid'], labels: [gettext('Placed orders'), gettext('Paid orders')], barColors: ['#000099', '#009900'], resize: true, xLabelAngle: 30 }); }); ","/*globals $, Morris, gettext*/ $(function () { $("".chart"").css(""height"", ""250px""); new Morris.Area({ element: 'obd_chart', data: JSON.parse($(""#obd-data"").html()), xkey: 'date', ykeys: ['ordered', 'paid'], labels: [gettext('Placed orders'), gettext('Paid orders')], lineColors: ['#000099', '#009900'], smooth: false, resize: true, fillOpacity: 0.3, behaveLikeLine: true }); new Morris.Area({ element: 'rev_chart', data: JSON.parse($(""#rev-data"").html()), xkey: 'date', ykeys: ['revenue'], labels: [gettext('Total revenue')], smooth: false, resize: true, fillOpacity: 0.3, preUnits: $.trim($(""#currency"").html()) + ' ' }); new Morris.Bar({ element: 'obp_chart', data: JSON.parse($(""#obp-data"").html()), xkey: 'item', ykeys: ['ordered', 'paid'], labels: [gettext('Placed orders'), gettext('Paid orders')], barColors: ['#000099', '#009900'], resize: true, xLabelAngle: 60 }); });" Add better timeout killing to file conversion,"import os import tempfile import subprocess import logging try: TimeoutExpired = subprocess.TimeoutExpired HAS_TIMEOUT = True except AttributeError: TimeoutExpired = Exception HAS_TIMEOUT = False def convert_to_pdf(filepath, binary_name=None, construct_call=None, timeout=50): if binary_name is None and construct_call is None: return outpath = tempfile.mkdtemp() path, filename = os.path.split(filepath) name, extension = filename.rsplit('.', 1) output_file = os.path.join(outpath, '%s.pdf' % name) arguments = [ binary_name, ""--headless"", ""--convert-to"", ""pdf"", ""--outdir"", outpath, filepath ] if construct_call is not None: arguments, output_file = construct_call(filepath, outpath) # Set different HOME so libreoffice can write to it env = dict(os.environ) env.update({'HOME': outpath}) logging.info(""Running: %s"", ' '.join(arguments)) logging.info(""Env: %s"", env) try: p = subprocess.Popen( arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env ) kwargs = {} if HAS_TIMEOUT: kwargs['timeout'] = timeout out, err = p.communicate(**kwargs) p.wait() except TimeoutExpired: p.kill() out, err = p.communicate() finally: if p.returncode is None: p.kill() out, err = p.communicate() if p.returncode == 0: if os.path.exists(output_file): return output_file else: logging.error(""Error during Doc to PDF conversion: %s"", err) return None ","import os import tempfile import subprocess import logging def convert_to_pdf(filepath, binary_name=None, construct_call=None): if binary_name is None and construct_call is None: return outpath = tempfile.mkdtemp() path, filename = os.path.split(filepath) name, extension = filename.rsplit('.', 1) output_file = os.path.join(outpath, '%s.pdf' % name) arguments = [ binary_name, ""--headless"", ""--convert-to"", ""pdf"", ""--outdir"", outpath, filepath ] if construct_call is not None: arguments, output_file = construct_call(filepath, outpath) # Set different HOME so libreoffice can write to it env = dict(os.environ) env.update({'HOME': outpath}) logging.info(""Running: %s"", ' '.join(arguments)) logging.info(""Env: %s"", env) p = subprocess.Popen( arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env ) out, err = p.communicate() p.wait() if p.returncode == 0: if os.path.exists(output_file): return output_file else: logging.error(""Error during Doc to PDF conversion: %s"", err) return None " Use aside rather than div for element,"WebBlocks.Blocks.addBlock({ 'name': 'Message', 'test': function(element){ return $(element).hasClass('message'); }, 'definition': function(){ var COLOR_CLASSES = $.merge($.merge([],WebBlocks.Blocks.Color.COLORS),WebBlocks.Blocks.Color.FLAVORS); this.tag = 'aside'; this.initialize = function(){ this.addClass('message'); } this.attributes = { 'header': { 'set': function(value){ this.unsetHeader(); this.prepend('<header>'+value+'</header>'); }, 'unset': function(){ this.getHeader().remove(); }, 'get': function(){ return this.children('header'); } }, 'content': { 'set': function(value){ this.unsetContent(); this.append($(document.createElement('div')).html(value)); }, 'unset': function(){ this.getContent().remove(); }, 'get': function(){ return this.children(':not(header)'); } }, 'color': { 'set': function(value){ this.unsetColor(); this.addClass(value); return this; }, 'unset': function(){ // requires WebBlocks.Blocks.Color if(WebBlocks.Blocks.Color) this.removeClass(COLOR_CLASSES.join(' ')); }, 'get': function(){ var classes = [] $.each(this.attr('class').split(' '), function(){ if($.inArray(this.toString(), COLOR_CLASSES) >= 0) classes.push(this.toString()); }) return classes; } } } } });","WebBlocks.Blocks.addBlock({ 'name': 'Message', 'test': function(element){ return $(element).hasClass('message'); }, 'definition': function(){ var COLOR_CLASSES = $.merge($.merge([],WebBlocks.Blocks.Color.COLORS),WebBlocks.Blocks.Color.FLAVORS); this.initialize = function(){ this.addClass('message'); } this.attributes = { 'header': { 'set': function(value){ this.unsetHeader(); this.prepend('<header>'+value+'</header>'); }, 'unset': function(){ this.getHeader().remove(); }, 'get': function(){ return this.children('header'); } }, 'content': { 'set': function(value){ this.unsetContent(); this.append($(document.createElement('div')).html(value)); }, 'unset': function(){ this.getContent().remove(); }, 'get': function(){ return this.children(':not(header)'); } }, 'color': { 'set': function(value){ this.unsetColor(); this.addClass(value); return this; }, 'unset': function(){ // requires WebBlocks.Blocks.Color if(WebBlocks.Blocks.Color) this.removeClass(COLOR_CLASSES.join(' ')); }, 'get': function(){ var classes = [] $.each(this.attr('class').split(' '), function(){ if($.inArray(this.toString(), COLOR_CLASSES) >= 0) classes.push(this.toString()); }) return classes; } } } } });" Fix test runner to cope with django compressor,""""""" Standalone test runner for wardrounds plugin """""" import sys from opal.core import application class Application(application.OpalApplication): pass from django.conf import settings settings.configure(DEBUG=True, DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, OPAL_OPTIONS_MODULE = 'referral.tests.dummy_options_module', ROOT_URLCONF='referral.urls', STATIC_URL='/assets/', STATIC_ROOT='static', STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder',), INSTALLED_APPS=('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django.contrib.admin', 'compressor', 'opal', 'opal.tests', 'referral',)) from django.test.runner import DiscoverRunner test_runner = DiscoverRunner(verbosity=1) if len(sys.argv) == 2: failures = test_runner.run_tests([sys.argv[-1], ]) else: failures = test_runner.run_tests(['referral', ]) if failures: sys.exit(failures) ",""""""" Standalone test runner for wardrounds plugin """""" import sys from opal.core import application class Application(application.OpalApplication): pass from django.conf import settings settings.configure(DEBUG=True, DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, OPAL_OPTIONS_MODULE = 'referral.tests.dummy_options_module', ROOT_URLCONF='referral.urls', STATIC_URL='/assets/', INSTALLED_APPS=('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django.contrib.admin', 'opal', 'opal.tests', 'referral',)) from django.test.runner import DiscoverRunner test_runner = DiscoverRunner(verbosity=1) if len(sys.argv) == 2: failures = test_runner.run_tests([sys.argv[-1], ]) else: failures = test_runner.run_tests(['referral', ]) if failures: sys.exit(failures) " Change eslint formatter to HTML instead of checkstyle,"'use strict'; const path = require('path'); const nodeExternals = require('webpack-node-externals'); module.exports = { entry: { authorizer: './lambda_functions/authorizer/authorizer.js', 'get-session': './lambda_functions/get-session/getSession.js' }, target: 'node', module: { loaders: [ { enforce: ""pre"", test: /\.js$/, loader: ""eslint-loader"", exclude: /node_modules/ }, { test: /\.js$/, loader: 'babel-loader', include: __dirname, exclude: /node_modules/, query: { presets: ['es2015', 'stage-0'] } } ] }, babel: { presets: [""es2015""], env: { test: { plugins: [""istanbul""] } } }, eslint: { outputReport: { filePath: 'eslint.html', formatter: require('eslint/lib/formatters/html') } }, output: { libraryTarget: 'commonjs', path: path.join(__dirname, '.webpack'), filename: '[name].js' }, resolve: { root: path.resolve(__dirname), alias: { lib: 'lib' }, extensions: ['', '.js', '.jsx'] }, externals: [nodeExternals()] };","'use strict'; const path = require('path'); const nodeExternals = require('webpack-node-externals'); module.exports = { entry: { authorizer: './lambda_functions/authorizer/authorizer.js', 'get-session': './lambda_functions/get-session/getSession.js' }, target: 'node', module: { loaders: [ { enforce: ""pre"", test: /\.js$/, loader: ""eslint-loader"", exclude: /node_modules/ }, { test: /\.js$/, loader: 'babel-loader', include: __dirname, exclude: /node_modules/, query: { presets: ['es2015', 'stage-0'] } } ] }, babel: { presets: [""es2015""], env: { test: { plugins: [""istanbul""] } } }, eslint: { outputReport: { filePath: 'checkstyle.xml', formatter: require('eslint/lib/formatters/checkstyle') } }, output: { libraryTarget: 'commonjs', path: path.join(__dirname, '.webpack'), filename: '[name].js' }, resolve: { root: path.resolve(__dirname), alias: { lib: 'lib' }, extensions: ['', '.js', '.jsx'] }, externals: [nodeExternals()] };" Remove try/catch from event execution,"/* coveraje - a simple javascript code coverage tool. EventEmitter wrapper Copyright (c) 2011 Wolfgang Kluge (klugesoftware.de, gehirnwindung.de) */ (function () { ""use strict""; var EventEmitter = require(""events"").EventEmitter; function CoverajeEvent(wait) { var ev = new EventEmitter(); function emit(t) { return function () { var args = Array.prototype.slice.call(arguments, 0); ev.emit.apply(ev, [t].concat(args)); return this; }; } function on(t) { return function () { var args = Array.prototype.slice.call(arguments, 0); ev.on.apply(ev, [t].concat(args)); return this; }; } this.complete = emit(""_cj_complete""); this.error = emit(""_cj_error""); // don't use special ""error"" event this.start = emit(""_cj_start""); this.onComplete = on(""_cj_complete""); this.onError = on(""_cj_error""); this.onStart = on(""_cj_start""); return this; } if (typeof exports !== ""undefined"" && exports) { exports.CoverajeEvent = CoverajeEvent; } }());","/* coveraje - a simple javascript code coverage tool. EventEmitter wrapper Copyright (c) 2011 Wolfgang Kluge (klugesoftware.de, gehirnwindung.de) */ (function () { ""use strict""; var EventEmitter = require(""events"").EventEmitter; function CoverajeEvent(wait) { var ev = new EventEmitter(); function emit(t) { return function () { var args = Array.prototype.slice.call(arguments, 0); try { ev.emit.apply(ev, [t].concat(args)); } catch (ex) {} return this; }; } function on(t) { return function () { var args = Array.prototype.slice.call(arguments, 0); ev.on.apply(ev, [t].concat(args)); return this; }; } this.complete = emit(""_cj_complete""); this.error = emit(""_cj_error""); // don't use special ""error"" event this.start = emit(""_cj_start""); this.onComplete = on(""_cj_complete""); this.onError = on(""_cj_error""); this.onStart = on(""_cj_start""); return this; } if (typeof exports !== ""undefined"" && exports) { exports.CoverajeEvent = CoverajeEvent; } }());" Add missing test for to_float applied on a float (when pint is present).,"# -*- coding: utf-8 -*- """""" tests.test_unit ~~~~~~~~~~~~~~~ Module dedicated to testing the unit utility functions. :copyright: 2015 by Lantz Authors, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """""" from __future__ import (division, unicode_literals, print_function, absolute_import) from pytest import raises, yield_fixture, mark from lantz_core import unit from lantz_core.unit import (set_unit_registry, get_unit_registry, to_float, to_quantity) try: from pint import UnitRegistry except ImportError: pass @yield_fixture def teardown(): unit.UNIT_REGISTRY = None yield unit.UNIT_REGISTRY = None @mark.skipif(unit.UNIT_SUPPORT is False, reason=""Requires Pint"") def test_set_unit_registry(teardown): ureg = UnitRegistry() set_unit_registry(ureg) assert get_unit_registry() is ureg @mark.skipif(unit.UNIT_SUPPORT is False, reason=""Requires Pint"") def test_reset_unit_registry(teardown): ureg = UnitRegistry() set_unit_registry(ureg) with raises(ValueError): set_unit_registry(ureg) def test_converters(teardown): """"""Test to_quantity and to_float utility functions. """""" val = 1.0 assert to_float(val) == val assert to_float(to_quantity(val, 'A')) == val ","# -*- coding: utf-8 -*- """""" tests.test_unit ~~~~~~~~~~~~~~~ Module dedicated to testing the unit utility functions. :copyright: 2015 by Lantz Authors, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """""" from __future__ import (division, unicode_literals, print_function, absolute_import) from pytest import raises, yield_fixture, mark from lantz_core import unit from lantz_core.unit import (set_unit_registry, get_unit_registry, to_float, to_quantity) try: from pint import UnitRegistry except ImportError: pass @yield_fixture def teardown(): unit.UNIT_REGISTRY = None yield unit.UNIT_REGISTRY = None @mark.skipif(unit.UNIT_SUPPORT is False, reason=""Requires Pint"") def test_set_unit_registry(teardown): ureg = UnitRegistry() set_unit_registry(ureg) assert get_unit_registry() is ureg @mark.skipif(unit.UNIT_SUPPORT is False, reason=""Requires Pint"") def test_reset_unit_registry(teardown): ureg = UnitRegistry() set_unit_registry(ureg) with raises(ValueError): set_unit_registry(ureg) def test_converters(teardown): """"""Test to_quantity and to_float utility functions. """""" val = 1.0 assert to_float(to_quantity(val, 'A')) == val " Add environment variables to service schema,"/* eslint-disable no-unused-vars */ import React from 'react'; /* eslint-enable no-unused-vars */ import General from './service-schema/General'; import Optional from './service-schema/Optional'; let ServiceSchema = { type: 'object', properties: { General: General, 'Container Settings': { description: 'Configure your Docker Container', type: 'object', properties: { image: { description: 'name of your docker image', type: 'string', getter: function (service) { let container = service.getContainerSettings(); if (container && container.docker && container.docker.image) { return container.docker.image; } return null; } }, network: { title: 'Network', fieldType: 'select', options: [ 'Host', 'Bridged' ], getter: function (service) { let container = service.getContainerSettings(); if (container && container.docker && container.docker.network) { return container.docker.network.toLowerCase(); } return null; } } }, required: [] }, 'Optional': Optional, 'environmentVariables': { description: 'Variables exposed to your environment homie.', type: 'object', title: 'Environment Variables', properties: { ports: { description: 'ports for ships to dock', type: 'array', duplicable: true, getter: function (service) { return service.getCommand(); }, itemShape: { properties: { key: { type: 'string', getter: function (service) { return service.getCommand(); } }, value: { type: 'string', getter: function (service) { return service.getCommand(); } } } } } } } }, required: [ 'General' ] }; module.exports = ServiceSchema; ","/* eslint-disable no-unused-vars */ import React from 'react'; /* eslint-enable no-unused-vars */ import General from './service-schema/General'; import Optional from './service-schema/Optional'; let ServiceSchema = { type: 'object', properties: { General: General, 'Container Settings': { description: 'Configure your Docker Container', type: 'object', properties: { image: { description: 'name of your docker image', type: 'string', getter: function (service) { let container = service.getContainerSettings(); if (container && container.docker && container.docker.image) { return container.docker.image; } return null; } }, network: { title: 'Network', fieldType: 'select', options: [ 'Host', 'Bridged' ], getter: function (service) { let container = service.getContainerSettings(); if (container && container.docker && container.docker.network) { return container.docker.network.toLowerCase(); } return null; } } }, required: [] }, 'Optional': Optional }, required: [ 'General' ] }; module.exports = ServiceSchema; " Allow to close a tab after the task has been executed,"Ext.namespace('ui', 'ui.task'); // config - {prefix, ftype, fid, fpath, fname, lang, storeRecord} ui.task.ChangeFileOwner = function(config) { Ext.apply(this, config); var msg = Ext.MessageBox.wait(_('Saving data...')); XHR({ scope : this, params : { task : 'setFileOwner', fileIdDB : this.fileIdDB, newOwner : this.newOwner }, success : function(r) { var o = Ext.util.JSON.decode(r.responseText); // We reload 2 stores to reflect this change ui.cmp.WorkTreeGrid.getInstance().getRootNode().reload(function() { ui.cmp.PatchesTreeGrid.getInstance().getRootNode().reload(); }); // We reload the information Portlet to reflect this change ui.cmp.PortletInfo.getInstance().store.reload(); // Remove wait msg msg.hide(); if( Ext.isDefined(this.fromType) && this.fromType === 'tab') { Ext.getCmp('main-panel').remove(this.from.curTab); } this.from.close(); // Notify PhDOE.notify('info', _('Owner changed'), _('The owner for this file have been changed successfully !')); }, failure : function(r) { var o = Ext.util.JSON.decode(r.responseText); // Remove wait msg msg.hide(); PhDOE.winForbidden(o.type); if( Ext.isDefined(this.fromType) && this.fromType === 'tab') { Ext.getCmp('main-panel').remove(this.from.curTab); } this.from.close(); } }); };","Ext.namespace('ui', 'ui.task'); // config - {prefix, ftype, fid, fpath, fname, lang, storeRecord} ui.task.ChangeFileOwner = function(config) { Ext.apply(this, config); var msg = Ext.MessageBox.wait(_('Saving data...')); XHR({ scope : this, params : { task : 'setFileOwner', fileIdDB : this.fileIdDB, newOwner : this.newOwner }, success : function(r) { var o = Ext.util.JSON.decode(r.responseText); // We reload 2 stores to reflect this change ui.cmp.WorkTreeGrid.getInstance().getRootNode().reload(function() { ui.cmp.PatchesTreeGrid.getInstance().getRootNode().reload(); }); // We reload the information Portlet to reflect this change ui.cmp.PortletInfo.getInstance().store.reload(); // Remove wait msg msg.hide(); this.from.close(); // Notify PhDOE.notify('info', _('Owner changed'), _('The owner for this file have been changed successfully !')); }, failure : function(r) { var o = Ext.util.JSON.decode(r.responseText); // Remove wait msg msg.hide(); PhDOE.winForbidden(o.type); this.from.close(); } }); };" Use url when presenting the menu url.,"<?php namespace Yajra\CMS\Presenters; use Laracasts\Presenter\Presenter; use Yajra\CMS\Contracts\UrlGenerator; class MenuPresenter extends Presenter { /** * Link href target window. * * @return string */ public function target() { return $this->entity->target == 0 ? '_self' : '_blank'; } /** * Indented title against depth. * * @param int $start * @param string $symbol * @return string */ public function indentedTitle($start = 1, $symbol = '— ') { $repeat = $this->entity->depth - $start; return str_repeat($symbol, $repeat >=0 ? $repeat : 0) . ' ' . $this->entity->title; } /** * Generate menu url depending on type the menu. * * @return string */ public function url() { /** @var \Yajra\CMS\Repositories\Extension\Repository $repository */ $repository = app('extensions'); /** @var \Yajra\CMS\Entities\Extension $extension */ $extension = $repository->findOrFail($this->entity->extension_id); $class = $extension->param('class'); if (class_exists($class)) { $entity = app($class)->findOrNew($this->entity->param('id')); if ($entity instanceof UrlGenerator) { return $entity->getUrl($extension->param('data')); } } return url($this->entity->url); } } ","<?php namespace Yajra\CMS\Presenters; use Laracasts\Presenter\Presenter; use Yajra\CMS\Contracts\UrlGenerator; class MenuPresenter extends Presenter { /** * Link href target window. * * @return string */ public function target() { return $this->entity->target == 0 ? '_self' : '_blank'; } /** * Indented title against depth. * * @param int $start * @param string $symbol * @return string */ public function indentedTitle($start = 1, $symbol = '— ') { $repeat = $this->entity->depth - $start; return str_repeat($symbol, $repeat >=0 ? $repeat : 0) . ' ' . $this->entity->title; } /** * Generate menu url depending on type the menu. * * @return string */ public function url() { /** @var \Yajra\CMS\Repositories\Extension\Repository $repository */ $repository = app('extensions'); /** @var \Yajra\CMS\Entities\Extension $extension */ $extension = $repository->findOrFail($this->entity->extension_id); $class = $extension->param('class'); if (class_exists($class)) { $entity = app($class)->findOrNew($this->entity->param('id')); if ($entity instanceof UrlGenerator) { return $entity->getUrl($extension->param('data')); } } return $this->entity->url; } } " Fix push-master grunt task for angular project.,"module.exports = function() { return { _defaults: { bg: false }, /** * Clean the app distribution folder. */ app_clean: { execOpts: { cwd: '.' }, cmd: 'rm -Rf <%= distScriptsPath %>/*' }, /** * Copy app HTML template to distribution folder. */ copy_app_template: { execOpts: { cwd: '.' }, cmd: 'cp <%= appMainTemplate %> <%= distPath %>' }, /* * Push local (master) branch to remote master. Push to subtree remotes also. */ push_2_master: { execOpts: { cwd: '../../' }, cmd: [ 'git push origin master', 'git push bitbucket master', ].join(';') } }; }; ","module.exports = function() { return { _defaults: { bg: false }, /** * Clean the app distribution folder. */ app_clean: { execOpts: { cwd: '.' }, cmd: 'rm -Rf <%= distScriptsPath %>/*' }, /** * Copy app HTML template to distribution folder. */ copy_app_template: { execOpts: { cwd: '.' }, cmd: 'cp <%= appMainTemplate %> <%= distPath %>' }, /* * Push local (master) branch to remote master. Push to subtree remotes also. */ push_2_master: { execOpts: { cwd: '../../../' }, cmd: [ 'git push origin master', 'git push bitbucket master', ].join(';') } }; }; " Enable remote debugging when running app.,"module.exports = function(grunt) { grunt.initConfig({ nodewebkit: { options: { platforms: ['osx'], buildDir: './build', macIcns: './app/icon/logo.icns' }, src: ['./app/**/*'] }, browserSync: { bsFiles: { src : 'app/css/*.css' }, options: { server: { baseDir: ""./app"" } } }, shell: { runApp: { command: '/Applications/node-webkit.app/Contents/MacOS/node-webkit ./app --remote-debugging-port=9222' } } }); require('load-grunt-tasks')(grunt); grunt.registerTask('build', ['nodewebkit']); grunt.registerTask('server', ['browserSync']); grunt.registerTask('run', ['shell:runApp']); } ","module.exports = function(grunt) { grunt.initConfig({ nodewebkit: { options: { platforms: ['osx'], buildDir: './build', macIcns: './app/icon/logo.icns' }, src: ['./app/**/*'] }, browserSync: { bsFiles: { src : 'app/css/*.css' }, options: { server: { baseDir: ""./app"" } } }, shell: { runApp: { command: '/Applications/node-webkit.app/Contents/MacOS/node-webkit ./app' } } }); require('load-grunt-tasks')(grunt); grunt.registerTask('build', ['nodewebkit']); grunt.registerTask('server', ['browserSync']); grunt.registerTask('run', ['shell:runApp']); } " Check for eval match and exit right away. Fix not returning error messages.,"var format = require(""util"").format; var TennuEval = { requires: [""admin""], init: function(client, imports) { function handleEval(IRCMessage) { if (IRCMessage.message.search(/^\>\>/) === -1) { return; } return imports.admin.isAdmin(IRCMessage.hostmask) .then(function(result) { if (!result) { return adminFail(IRCMessage.nickname, IRCMessage.hostmask.hostname); } return (""<<"" + eval(IRCMessage.message.substr(2))).split('\n'); }) }; function adminFail(nickname, hostname) { return { intent: 'notice', query: true, message: ['Restricted access.', format('Logged: %s@%s.', nickname, hostname)] }; } return { handlers: { ""privmsg"": handleEval, } }; } }; module.exports = TennuEval;","var format = require(""util"").format; var TennuEval = { requires: [""admin""], init: function(client, imports) { function handleEval(IRCMessage) { return imports.admin.isAdmin(IRCMessage.hostmask) .then(function (result) { if(!result){ adminFail(IRCMessage.nickname, IRCMessage.hostmask.hostname); } if(IRCMessage.message.search(/^\>\>/) > -1){ return (""<<""+eval(IRCMessage.message.substr(2))).split('\n'); } }) }; function adminFail(nickname, hostname) { return { intent: 'notice', query: true, message: ['Restricted access.', format('Logged: %s@%s.', nickname, hostname)] }; } return { handlers: { ""privmsg"": handleEval, } }; } }; module.exports = TennuEval;" Increase waitForServerToGive200 timeout to 10s & add debug trace,"<?php namespace WireMock\Client; class HttpWait { public function waitForServerToGive200($url, $timeoutSecs = 10) { $debugTrace = array(); $startTime = microtime(true); $serverStarted = false; while (microtime(true) - $startTime < $timeoutSecs) { try { $headers = @get_headers($url, 1); } catch (\Exception $e) { $debugTrace[] = ""$url not yet up. Error getting headers: "" . $e->getMessage(); continue; } if (isset($headers) && isset($headers[0]) && $headers[0] === 'HTTP/1.1 200 OK') { $serverStarted = true; break; } else { if (!isset($headers)) { $debugTrace[] = ""$url not yet up. \$headers not set""; } else if (!isset($headers[0])) { $debugTrace[] = ""$url not yet up. \$headers[0] not set""; } else { $debugTrace[] = ""$url not yet up. \$headers[0] was ${headers[0]}""; } } usleep(100000); } if (!$serverStarted) { $time = microtime(true) - $startTime; $debugTrace[] = ""$url failed to come up after $time seconds""; echo implode(""\n"", $debugTrace) .""\n""; } return $serverStarted; } public function waitForServerToFailToRespond($url, $timeoutSecs = 5) { $startTime = microtime(true); $serverFailedToRespond = false; while (microtime(true) - $startTime < $timeoutSecs) { if (@get_headers($url, 1) === false) { $serverFailedToRespond = true; break; } } return $serverFailedToRespond; } } ","<?php namespace WireMock\Client; class HttpWait { public function waitForServerToGive200($url, $timeoutSecs = 5) { $startTime = microtime(true); $serverStarted = false; while (microtime(true) - $startTime < $timeoutSecs) { try { $headers = @get_headers($url, 1); } catch (\Exception $e) { continue; } if (isset($headers) && isset($headers[0]) && $headers[0] === 'HTTP/1.1 200 OK') { $serverStarted = true; break; } } return $serverStarted; } public function waitForServerToFailToRespond($url, $timeoutSecs = 5) { $startTime = microtime(true); $serverFailedToRespond = false; while (microtime(true) - $startTime < $timeoutSecs) { if (@get_headers($url, 1) === false) { $serverFailedToRespond = true; break; } } return $serverFailedToRespond; } } " "Refactor for common use between apps Conflicts: app/js/app.js app/js/controllers.js WTK: I removed everything except websocket.js (originally services.js) since we're splitting out the websocket code.","'use strict'; /* Services */ var websocket = angular.module('websocket', []); websocket. factory('websocket', ['$rootScope', function($rootScope) { var ws, make_message, parse_message, Service; ws = new window.WebSocket(""ws://automation.azurestandard.com:9000""); ws.onopen = function () { console.log(""Socket has been opened""); } ws.onerror = function (error) { console.log(""WebSocket Error "" + error); }; // Log messages from the server ws.onmessage = function (msg) { var parsed; parsed = parse_message(msg.data); //Call registered handlers then $rootScope.$apply(); }; make_message = function (topic, body) { return topic + "" "" + JSON.stringify(body); }; parse_message = function (msg) { var topic, body, parts; parts = msg.split("" "", 1); topic = parts[0]; body = JSON.parse(msg.substring(topic.length + 1)); return {""topic"": topic, ""body"": body}; }; // We return this object to anything injecting our service Service = { emit: function (topic, body) { this.send(make_message(topic,body)); }, register: function (topic, func) { }, make_message: make_message, send: ws.send } return Service; }]); ","'use strict'; /* Services */ // Demonstrate how to register services // In this case it is a simple value service. // angular.module('pickControl.services', [function () { // }]); angular.module('pickControl.services', []). factory('websocket', function() { var websocket, make_message, parse_message, con; make_message = function (topic, body) { return topic + "" "" + JSON.stringify(body); } parse_message = function (msg) { var topic, body, parts; parts = msg.split("" "", 1); topic = parts[0]; body = JSON.parse(msg.substring(topic.length + 1)); return {""topic"": topic, ""body"": body}; } con = new window.WebSocket(""ws://automation.azurestandard.com:9000/bin""); con.onerror = function (error) { console.log(""WebSocket Error "" + error); }; // Log messages from the server con.onmessage = function (msg) { var parsed; parsed = parse_message(msg.data); //Call registered handlers then $scope.$apply(); }; websocket = { emit: function (topic, body) { console.log(topic); console.log(body); }, register: function (topic, func) { }, send: function (msg) { }, make_message: function (topic, body) { }, } //factory function body that constructs websocket return websocket; }); " "Fix URL detection error for upper case in the installer Signed-off-by: Richard Lea <5e20e57f18b15612bae274c2aef7dc395ee6b2a1@zoho.com>","<?php $version = (float) substr(phpversion(), 0, 3); $rc_url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; $pos = strpos(strtolower($rc_url), 'chigi/install'); $chigi_root_url = substr(strtolower($rc_url), 0, $pos); define('CHIGI_ROOT_URL', $chigi_root_url . 'chigi/'); // 当前config.php文件的路径 $rc_dir = dirname(__FILE__); $rc_dir = str_replace('\\', '/', $rc_dir); $pos = strpos($rc_dir, 'Chigi/install'); $chigi_root_path = substr($rc_dir, 0, $pos); define('CHIGI_ROOT_PATH',$chigi_root_path . 'Chigi/'); if ($version >= 5.3) { //用户项目入口 define('APP_NAME', 'Installation'); define('APP_PATH', './'); //define('APP_DEBUG', true); //您可以注释掉这行,关闭调试模式 define('THINK_PATH', '../../Core/'); //定义正确的框架文件路径 if(!file_exists(THINK_PATH . 'ThinkPHP.php')){ exit(""未找到ThinkPHP内核位置,请在install/index.php中重新指定""); } require_once THINK_PATH . 'ThinkPHP.php'; } else { exit(""对不起,您的PHP版本略低,千木架构对PHP最低版本要求5.3""); } ?> ","<?php $version = (float) substr(phpversion(), 0, 3); $rc_url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; $pos = strpos($rc_url, 'chigi/install'); $chigi_root_url = substr($rc_url, 0, $pos); define('CHIGI_ROOT_URL', $chigi_root_url . 'chigi/'); // 当前config.php文件的路径 $rc_dir = dirname(__FILE__); $rc_dir = str_replace('\\', '/', $rc_dir); $pos = strpos($rc_dir, 'Chigi/install'); $chigi_root_path = substr($rc_dir, 0, $pos); define('CHIGI_ROOT_PATH',$chigi_root_path . 'Chigi/'); if ($version >= 5.3) { //用户项目入口 define('APP_NAME', 'Installation'); define('APP_PATH', './'); //define('APP_DEBUG', true); //您可以注释掉这行,关闭调试模式 define('THINK_PATH', '../../Core/'); //定义正确的框架文件路径 if(!file_exists(THINK_PATH . 'ThinkPHP.php')){ exit(""未找到ThinkPHP内核位置,请在install/index.php中重新指定""); } require_once THINK_PATH . 'ThinkPHP.php'; } else { exit(""对不起,您的PHP版本略低,千木架构对PHP最低版本要求5.3""); } ?> " Move setUp and tearDown methods into general FormTestCase class,"import unittest from app import create_app, db from app.utils.forms import RedirectForm class FormTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_ctx = self.app.app_context() self.app_ctx.push() db.create_all() def tearDown(self): db.session.remove() db.drop_all() self.app_ctx.pop() class TestRedirectForm(FormTestCase): def setUp(self): super().setUp() self.form = RedirectForm() def test_is_safe_url(self): with self.app.test_request_context(): self.assertFalse(self.form.is_safe_url('http://externalsite.com')) self.assertTrue(self.form.is_safe_url('http://' + self.app.config[ 'SERVER_NAME'])) self.assertTrue(self.form.is_safe_url('safe_internal_link')) def test_get_redirect_target(self): with self.app.test_request_context('/?next=http://externalsite.com'): self.assertIsNone(self.form.get_redirect_target()) with self.app.test_request_context('/?next=safe_internal_link'): self.assertEquals(self.form.get_redirect_target(), 'safe_internal_link') ","import unittest from app import create_app, db from app.utils.forms import RedirectForm class TestRedirectForm(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_ctx = self.app.app_context() self.redirect_form = RedirectForm() self.app_ctx.push() db.create_all() def tearDown(self): db.session.remove() db.drop_all() self.app_ctx.pop() def test_is_safe_url(self): with self.app.test_request_context(): self.assertFalse(self.redirect_form.is_safe_url('http://externalsite.com')) self.assertTrue(self.redirect_form.is_safe_url('http://' + self.app.config[ 'SERVER_NAME'])) self.assertTrue(self.redirect_form.is_safe_url('safe_internal_link')) def test_get_redirect_target(self): with self.app.test_request_context('/?next=http://externalsite.com'): self.assertIsNone(self.redirect_form.get_redirect_target()) with self.app.test_request_context('/?next=safe_internal_link'): self.assertEquals(self.redirect_form.get_redirect_target(), 'safe_internal_link') " Include integers and more by if.,"<?php /** * Hash class file */ namespace Graviton\DocumentBundle\Entity; /** * Special type for hash fields * * @author List of contributors <https://github.com/libgraviton/graviton/graphs/contributors> * @license http://opensource.org/licenses/gpl-license.php GNU Public License * @link http://swisscom.ch */ class Hash extends \ArrayObject implements \JsonSerializable { /** * Specify data which should be serialized to JSON * * @return object */ public function jsonSerialize() { return (object) $this->arrayFilterRecursive($this->getArrayCopy()); } /** * Clean up, remove empty positions of second level and above * * @param array $input to be cleaned up * @return array */ private function arrayFilterRecursive($input) { if (empty($input)) { return []; } foreach ($input as &$value) { if (is_array($value) || is_object($value)) { $value = $this->arrayFilterRecursive($value); } } return array_filter($input, [$this, 'cleanUpArray']); } /** * Remove NULL values or Empty array object * @param mixed $var object field value * @return bool */ private function cleanUpArray($var) { $empty = empty($var); if ($empty && ( is_int($var) || is_bool($var) || is_float($var) || is_integer($var)) ) { return true; } return !$empty; } } ","<?php /** * Hash class file */ namespace Graviton\DocumentBundle\Entity; /** * Special type for hash fields * * @author List of contributors <https://github.com/libgraviton/graviton/graphs/contributors> * @license http://opensource.org/licenses/gpl-license.php GNU Public License * @link http://swisscom.ch */ class Hash extends \ArrayObject implements \JsonSerializable { /** * Specify data which should be serialized to JSON * * @return object */ public function jsonSerialize() { return (object) $this->arrayFilterRecursive($this->getArrayCopy()); } /** * Clean up, remove empty positions of second level and above * * @param array $input to be cleaned up * @return array */ private function arrayFilterRecursive($input) { if (empty($input)) { return []; } foreach ($input as &$value) { if (is_array($value) || is_object($value)) { $value = $this->arrayFilterRecursive($value); } } return array_filter($input, [$this, 'cleanUpArray']); } /** * Remove NULL values or Empty array object * @param mixed $var object field value * @return bool */ private function cleanUpArray($var) { if ($var !== false) { return !empty($var); } return true; } } " Comment out the require for util that was used for showing an example custom config file,"const {Initializer, api} = require('actionhero'); const r = require('@lib/r'); // const util = require('util'); module.exports = class ApiInitializer extends Initializer { constructor() { super(); this.name = 'api-initializer'; } initialize() { api.mc = { r: r, directories: require('@dal/directories')(r), projects: require('@dal/projects')(r), datasets: require('@dal/datasets')(r), check: require('@dal/check')(r), processes: require('@dal/processes')(r), publishedDatasets: require('@dal/published-datasets')(r), samples: require('@dal/samples')(r), templates: require('@dal/templates')(r), files: require('@dal/files')(r), log: { debug: (msg, params) => api.log(msg, 'debug', params), info: (msg, params) => api.log(msg, 'info', params), notice: (msg, params) => api.log(msg, 'notice', params), warning: (msg, params) => api.log(msg, 'warning', params), error: (msg, params) => api.log(msg, 'error', params), critical: (msg, params) => api.log(msg, 'crit', params), alert: (msg, params) => api.log(msg, 'alert', params), emergency: (msg, params) => api.log(msg, 'emerg', params), } }; // api.mc.log.info(util.inspect(api.config.db, {showHidden: false, depth: null})); } };","const {Initializer, api} = require('actionhero'); const r = require('@lib/r'); const util = require('util'); module.exports = class ApiInitializer extends Initializer { constructor() { super(); this.name = 'api-initializer'; } initialize() { api.mc = { r: r, directories: require('@dal/directories')(r), projects: require('@dal/projects')(r), datasets: require('@dal/datasets')(r), check: require('@dal/check')(r), processes: require('@dal/processes')(r), publishedDatasets: require('@dal/published-datasets')(r), samples: require('@dal/samples')(r), templates: require('@dal/templates')(r), files: require('@dal/files')(r), log: { debug: (msg, params) => api.log(msg, 'debug', params), info: (msg, params) => api.log(msg, 'info', params), notice: (msg, params) => api.log(msg, 'notice', params), warning: (msg, params) => api.log(msg, 'warning', params), error: (msg, params) => api.log(msg, 'error', params), critical: (msg, params) => api.log(msg, 'crit', params), alert: (msg, params) => api.log(msg, 'alert', params), emergency: (msg, params) => api.log(msg, 'emerg', params), } }; // api.mc.log.info(util.inspect(api.config.db, {showHidden: false, depth: null})); } };" Reset char count on post,"$(() => { $('.js-character-count').each((i, el) => { const $el = $(el); const $target = $el.siblings($el.attr('data-target')); const max = $el.attr('data-max'); $target.on('keyup cc-reset', (ev) => { const $tgt = $(ev.target); const count = $tgt.val().length; const text = `${count} / ${max}`; if (count > max) { $el.removeClass('has-color-yellow-700').addClass('has-color-red-500'); const $button = $el.parents('form').find('input[type=""submit""]'); if ($button) { $button.attr('disabled', true).addClass('is-muted'); } } else if (count > 0.75 * max) { $el.removeClass('has-color-red-500').addClass('has-color-yellow-700'); const $button = $el.parents('form').find('input[type=""submit""]'); if ($button) { $button.attr('disabled', false).removeClass('is-muted'); } } else { $el.removeClass('has-color-red-500 has-color-yellow-700'); const $button = $el.parents('form').find('input[type=""submit""]'); if ($button) { $button.attr('disabled', false).removeClass('is-muted'); } } $el.text(text); }); $target.parents('form').on('ajax:success', ev => { $target.val('').trigger('cc-reset'); }); }); });","$(() => { $('.js-character-count').each((i, el) => { const $el = $(el); const $target = $el.siblings($el.attr('data-target')); const max = $el.attr('data-max'); $target.on('keyup', (ev) => { const $tgt = $(ev.target); const count = $tgt.val().length; const text = `${count} / ${max}`; if (count > max) { $el.removeClass('has-color-yellow-700').addClass('has-color-red-500'); const $button = $el.parents('form').find('input[type=""submit""]'); if ($button) { $button.attr('disabled', true).addClass('is-muted'); } } else if (count > 0.75 * max) { $el.removeClass('has-color-red-500').addClass('has-color-yellow-700'); const $button = $el.parents('form').find('input[type=""submit""]'); if ($button) { $button.attr('disabled', false).removeClass('is-muted'); } } else { $el.removeClass('has-color-red-500 has-color-yellow-700'); const $button = $el.parents('form').find('input[type=""submit""]'); if ($button) { $button.attr('disabled', false).removeClass('is-muted'); } } $el.text(text); }); }); });" Fix bug where devices didn't close if stayOpen was true,"// This source file is part of the Packet Guardian project. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. $.onReady(function() { var stayOpen = false; var reallyOpen = false; $("".device-header"").click(function(e) { if (!reallyOpen) { return; } var self = $(e.target); if (self.hasClass(""device-checkbox"")) { return; } if (self[0].tagName === 'A') { return; } while (!self.hasClass(""device-header"")) { self = $(self[0].parentNode); } var bodyNum = self.data(""deviceId""); expandBody(bodyNum); }); function expandBody(bodyNum) { var thebody = $(""#device-body-""+bodyNum); // Get the max-height value before setting it back to 0 var mh = thebody.style(""max-height""); if (!stayOpen) { // Close all $("".device-body"").style(""max-height"", ""0px""); } if (mh !== ""200px"") { thebody.style(""max-height"", ""200px""); } else { thebody.style(""max-height"", ""0px""); } } var preOpenID = location.hash.substring(1); if (preOpenID) { expandBody(preOpenID); } $("".device-header"").on(""mousedown"", function() { reallyOpen = true; }); $("".device-header"").on(""mousemove"", function() { reallyOpen = false; }); window.keepDevicesOpen = function(stay) { stayOpen = stay; }; }); ","// This source file is part of the Packet Guardian project. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. $.onReady(function() { var stayOpen = false; var reallyOpen = false; $("".device-header"").click(function(e) { if (!reallyOpen) { return; } var self = $(e.target); if (self.hasClass(""device-checkbox"")) { return; } while (!self.hasClass(""device-header"")) { self = $(self[0].parentNode); } var bodyNum = self.data(""deviceId""); expandBody(bodyNum); }); function expandBody(bodyNum) { var thebody = $(""#device-body-""+bodyNum); // Get the max-height value before setting it back to 0 var mh = thebody.style(""max-height""); if (!stayOpen) { $("".device-body"").style(""max-height"", ""0""); } if (mh !== ""200px"") { thebody.style(""max-height"", ""200px""); } } var preOpenID = location.hash.substring(1); if (preOpenID) { expandBody(preOpenID); } $("".device-header"").on(""mousedown"", function() { reallyOpen = true; }); $("".device-header"").on(""mousemove"", function() { reallyOpen = false; }); window.keepDevicesOpen = function(stay) { stayOpen = stay; }; }); " Fix forwarding positional args in Pipeline __call__,"class Pipeline(object): """"""Defines a pipeline for transforming sequence data."""""" def __init__(self, convert_token=None): if convert_token is None: self.convert_token = lambda x: x elif callable(convert_token): self.convert_token = convert_token else: raise ValueError(""Pipeline input convert_token {} is not None "" ""or callable"".format(convert_token)) self.pipes = [self] def __call__(self, x, *args): for pipe in self.pipes: x = pipe.call(x, *args) return x def call(self, x, *args): if isinstance(x, list): return [self(tok, *args) for tok in x] return self.convert_token(x, *args) def add_before(self, pipeline): """"""Add `pipeline` before this processing pipeline."""""" if not isinstance(pipeline, Pipeline): pipeline = Pipeline(pipeline) self.pipes = pipeline.pipes[:] + self.pipes[:] return self def add_after(self, pipeline): """"""Add `pipeline` after this processing pipeline."""""" if not isinstance(pipeline, Pipeline): pipeline = Pipeline(pipeline) self.pipes = self.pipes[:] + pipeline.pipes[:] return self ","class Pipeline(object): """"""Defines a pipeline for transforming sequence data."""""" def __init__(self, convert_token=None): if convert_token is None: self.convert_token = lambda x: x elif callable(convert_token): self.convert_token = convert_token else: raise ValueError(""Pipeline input convert_token {} is not None "" ""or callable"".format(convert_token)) self.pipes = [self] def __call__(self, x, *args): for pipe in self.pipes: x = pipe.call(x) return x def call(self, x, *args): if isinstance(x, list): return [self(tok, *args) for tok in x] return self.convert_token(x, *args) def add_before(self, pipeline): """"""Add `pipeline` before this processing pipeline."""""" if not isinstance(pipeline, Pipeline): pipeline = Pipeline(pipeline) self.pipes = pipeline.pipes[:] + self.pipes[:] return self def add_after(self, pipeline): """"""Add `pipeline` after this processing pipeline."""""" if not isinstance(pipeline, Pipeline): pipeline = Pipeline(pipeline) self.pipes = self.pipes[:] + pipeline.pipes[:] return self " Fix for refreshing the max amount of the knob when the max value its bound to is changed,"angular.module('ui.knob', []) .directive('knob', function () { return { restrict: 'EACM', template: function(elem, attrs){ return '<input value=""{{ knob }}"">'; }, replace: true, scope: true, link: function (scope, elem, attrs) { scope.knob = scope.$eval(attrs.knobData); var renderKnob = function(){ scope.knob = scope.$eval(attrs.knobData); var opts = {}; if(!angular.isUndefined(attrs.knobOptions)){ opts = scope.$eval(attrs.knobOptions); } if(!angular.isUndefined(attrs.knobMax)){ var max = scope.$eval(attrs.knobMax); if(!angular.isUndefined(max)){ opts.max = max; } } $elem = $(elem); $elem.val(scope.knob); $elem.change(); $elem.knob(opts); }; var updateMax = function updateMax() { var max = scope.$eval(attrs.knobMax); $elem.trigger('configure', { 'max': max }).trigger('change'); } scope.$watch(attrs.knobData, function () { renderKnob(); }); scope.$watch(attrs.knobMax, function() { updateMax(); }); scope.$watch(attrs.knobOptions, function () { renderKnob(); }, true); } }; });","angular.module('ui.knob', []) .directive('knob', function () { return { restrict: 'EACM', template: function(elem, attrs){ return '<input value=""{{ knob }}"">'; }, replace: true, scope: true, link: function (scope, elem, attrs) { scope.knob = scope.$eval(attrs.knobData); var renderKnob = function(){ scope.knob = scope.$eval(attrs.knobData); var opts = {}; if(!angular.isUndefined(attrs.knobOptions)){ opts = scope.$eval(attrs.knobOptions); } if(!angular.isUndefined(attrs.knobMax)){ var max = scope.$eval(attrs.knobMax); if(!angular.isUndefined(max)){ opts.max = max; } } $elem = $(elem); $elem.val(scope.knob); $elem.change(); $elem.knob(opts); }; scope.$watch(attrs.knobData, function () { renderKnob(); }); scope.$watch(attrs.knobOptions, function () { renderKnob(); }, true); } }; });" Update REACH reader to new API class path,"from indra.java_vm import autoclass, JavaException class ReachReader(object): """"""The ReachReaader wraps a singleton instance of the REACH reader. This allows calling the reader many times without having to wait for it to start up each time. Attributes ---------- api_ruler : org.clulab.reach.apis.ApiRuler An instance of the REACH ApiRuler class (java object). """""" def __init__(self): self.api_ruler = None def get_api_ruler(self): """"""Return the existing reader if it exists or launch a new one. Returns ------- api_ruler : org.clulab.reach.apis.ApiRuler An instance of the REACH ApiRuler class (java object). """""" if self.api_ruler is None: try: self.api_ruler =\ autoclass('org.clulab.reach.apis.ApiRuler') except JavaException: try: autoclass('java.lang.String') except JavaException: pass return None return self.api_ruler ","from indra.java_vm import autoclass, JavaException class ReachReader(object): """"""The ReachReaader wraps a singleton instance of the REACH reader. This allows calling the reader many times without having to wait for it to start up each time. Attributes ---------- api_ruler : edu.arizona.sista.reach.apis.ApiRuler An instance of the REACH ApiRuler class (java object). """""" def __init__(self): self.api_ruler = None def get_api_ruler(self): """"""Return the existing reader if it exists or launch a new one. Returns ------- api_ruler : edu.arizona.sista.reach.apis.ApiRuler An instance of the REACH ApiRuler class (java object). """""" if self.api_ruler is None: try: self.api_ruler =\ autoclass('edu.arizona.sista.reach.apis.ApiRuler') except JavaException: try: autoclass('java.lang.String') except JavaException: pass return None return self.api_ruler " "Convert severe ""Disabling economy until..."" to info","package xyz.upperlevel.uppercore.economy; import lombok.Getter; import net.milkbowl.vault.economy.Economy; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.plugin.RegisteredServiceProvider; import xyz.upperlevel.uppercore.Uppercore; import xyz.upperlevel.uppercore.util.PluginUtil; public class EconomyManager { @Getter private static boolean enabled = false; private static Economy economy; public static void enable() { Uppercore.logger().info(""Disabling economy until vault load""); enabled = false; PluginUtil.onPluginLoaded(""Vault"", p -> { RegisteredServiceProvider<Economy> rsp = Bukkit.getServicesManager().getRegistration(Economy.class); if (rsp == null) { Uppercore.logger().severe(""Cannot find any economy service, economy not supported""); enabled = false; return; } enabled = true; economy = rsp.getProvider(); }); } public static Economy getEconomy() { return enabled ? economy : null; } public static Balance get(OfflinePlayer player) { return economy == null ? null : new Balance(player); } public static String format(double v) { return economy.format(v); } } ","package xyz.upperlevel.uppercore.economy; import lombok.Getter; import net.milkbowl.vault.economy.Economy; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.plugin.RegisteredServiceProvider; import xyz.upperlevel.uppercore.Uppercore; import xyz.upperlevel.uppercore.util.PluginUtil; public class EconomyManager { @Getter private static boolean enabled = false; private static Economy economy; public static void enable() { Uppercore.logger().severe(""Disabling economy until vault load""); enabled = false; PluginUtil.onPluginLoaded(""Vault"", p -> { RegisteredServiceProvider<Economy> rsp = Bukkit.getServicesManager().getRegistration(Economy.class); if (rsp == null) { Uppercore.logger().severe(""Cannot find any economy service, economy not supported""); enabled = false; return; } enabled = true; economy = rsp.getProvider(); }); } public static Economy getEconomy() { return enabled ? economy : null; } public static Balance get(OfflinePlayer player) { return economy == null ? null : new Balance(player); } public static String format(double v) { return economy.format(v); } } " Exit process if BBC_SERVICES_URL is not set,"var EventSource = require(""eventsource""), EventEmitter = require(""events"").EventEmitter, utils = require(""radiodan-client"").utils, http = require(""./http-promise""), logger = utils.logger(__filename), bbcServicesURL = process.env.BBC_SERVICES_URL; if(typeof bbcServicesURL === ""undefined"") { logger.error(""BBC_SERVICES_API not found in ENV""); process.exit(); } module.exports = { create: create }; function create() { var instance = new EventEmitter; instance.store = {}; listenForEvents(); return instance; function listenForEvents() { var url = bbcServicesURL+""/stream"", es = new EventSource(url), firstError = true; logger.debug(""Connecting to"", url); es.onmessage = handleMessage; es.onerror = function() { // always fails on startup if(firstError) { firstError = false; } else { logger.warn(""EventSource error""); } }; } function handleMessage(msg) { var data = parseMessage(msg.data), store; if (data) { store = instance.store[data.service] = instance.store[data.service] || {}; store[data.topic] = data.data; instance.emit(data.service, data.topic, data.data); instance.emit(data.service+""/""+data.topic, data.data); } } function parseMessage(data) { try { return JSON.parse(data); } catch(err) { logger.warn(""Cannot parse"", err); return false; } } } ","var EventSource = require(""eventsource""), EventEmitter = require(""events"").EventEmitter, utils = require(""radiodan-client"").utils, http = require(""./http-promise""), bbcServicesURL = process.env.BBC_SERVICES_URL; module.exports = { create: create }; function create() { var instance = new EventEmitter, logger = utils.logger(__filename); instance.store = {}; listenForEvents(); return instance; function listenForEvents() { var url = bbcServicesURL+""/stream"", es = new EventSource(url), firstError = true; logger.debug(""Connecting to"", url); es.onmessage = handleMessage; es.onerror = function() { // always fails on startup if(firstError) { firstError = false; } else { logger.warn(""EventSource error""); } }; } function handleMessage(msg) { var data = parseMessage(msg.data), store; if (data) { store = instance.store[data.service] = instance.store[data.service] || {}; store[data.topic] = data.data; instance.emit(data.service, data.topic, data.data); instance.emit(data.service+""/""+data.topic, data.data); } } function parseMessage(data) { try { return JSON.parse(data); } catch(err) { logger.warn(""Cannot parse"", err); return false; } } } " Trim output of each line,"<?php namespace Tests\Concerns; use PHPUnit\Framework\Assert; class ArtisanResult { private $output; private $status; private $parameters; public function __construct($parameters, $output, $status) { $this->output = $output; $this->status = $status; $this->parameters = $parameters; } public function assertStatus($expected) { Assert::assertEquals($expected, $this->status); } public function assertStepOutput($expectedLines) { foreach ($this->stepLines() as $index => $actualLine) { Assert::assertEquals($expectedLines[$index], $actualLine); } } public function dump() { return tap($this, function () { dump(""Status: {$this->status}""); dump(""Output:\n{$this->output}""); }); } public function dumpIfFailed() { return $this->status === 0 ? $this : $this->dump(); } private function outputLines() { foreach (explode(""\n"", trim($this->output)) as $index => $actualLine) { yield $index => trim($actualLine); } } private function stepLines() { foreach ($this->outputLines() as $index => $actualLine) { if (substr($actualLine, 0, 1) !== ""["") { break; } yield $index => $actualLine; } } } ","<?php namespace Tests\Concerns; use PHPUnit\Framework\Assert; class ArtisanResult { private $output; private $status; private $parameters; public function __construct($parameters, $output, $status) { $this->output = $output; $this->status = $status; $this->parameters = $parameters; } public function assertStatus($expected) { Assert::assertEquals($expected, $this->status); } public function assertStepOutput($expectedLines) { foreach ($this->stepLines() as $index => $actualLine) { Assert::assertEquals($expectedLines[$index], $actualLine); } } public function dump() { return tap($this, function () { dump(""Status: {$this->status}""); dump(""Output:\n{$this->output}""); }); } public function dumpIfFailed() { return $this->status === 0 ? $this : $this->dump(); } private function outputLines() { foreach (explode(""\n"", $this->output) as $index => $actualLine) { yield $index => $actualLine; } } private function stepLines() { foreach ($this->outputLines() as $index => $actualLine) { if (substr($actualLine, 0, 1) !== ""["") { break; } yield $index => $actualLine; } } } " Enable disabling for inanimate enemy tanks,"import React from 'react'; import { TANK_RADIUS } from '../../simulation/constants'; class TankBody extends React.Component { constructor(props) { super(props); this.radius = props.radius || TANK_RADIUS; this.material = props.material || 'color: red;' this.socketControlsDisabled = props.socketControlsDisabled || false; } render () { return ( <a-sphere position='0 0 0' rotation={this.props.rotation} material={this.material} socket-controls={`simulationAttribute: tankRotation; `+ `characterId: ${this.props.characterId}; `+ `enabled: ${!this.socketControlsDisabled}`} radius={this.radius}> <a-torus position='0 0 0' rotation='90 0 0' material={this.material} radius={this.radius} radius-tubular={0.1}/> <a-sphere // Windows position={`0 0.6 ${0.4 - this.radius}`} radius='0.5' scale='2.5 1 1.5' material='color:black; opacity:0.4;'/> <a-sphere position={`${-(this.radius - 0.5)} 0.6 -1`} radius='0.4' material='color:black; opacity:0.4;'/> <a-sphere position={`${this.radius - 0.5} 0.6 -1`} radius='0.4' material='color:black; opacity:0.4;'/> {this.props.children} </a-sphere> ) } } module.exports = TankBody; ","import React from 'react'; import { TANK_RADIUS } from '../../simulation/constants'; class TankBody extends React.Component { constructor(props) { super(props); this.radius = props.radius || TANK_RADIUS; this.material = props.material || 'color: red;' } render () { return ( <a-sphere position='0 0 0' rotation={this.props.rotation} material={this.material} socket-controls={`simulationAttribute: tankRotation; characterId: ${this.props.characterId}`} radius={this.radius}> <a-torus position='0 0 0' rotation='90 0 0' material={this.material} radius={this.radius} radius-tubular={0.1}/> <a-sphere // Windows position={`0 0.6 ${0.4 - this.radius}`} radius='0.5' scale='2.5 1 1.5' material='color:black; opacity:0.4;'/> <a-sphere position={`${-(this.radius - 0.5)} 0.6 -1`} radius='0.4' material='color:black; opacity:0.4;'/> <a-sphere position={`${this.radius - 0.5} 0.6 -1`} radius='0.4' material='color:black; opacity:0.4;'/> {this.props.children} </a-sphere> ) } } module.exports = TankBody; " Fix the REST module name.,"import datetime import pytz from nose.tools import (assert_is_none) from qipipe.helpers.qiprofile_helper import QIProfile from qiprofile_rest.models import Project from test import project from test.helpers.logging_helper import logger SUBJECT = 'Breast099' """"""The test subject."""""" SESSION = 'Session01' """"""The test session."""""" class TestQIProfileHelper(object): """"""The Imaging Profile helper unit tests."""""" def setUp(self): if not Project.objects.filter(name=project()): Project(name=project()).save() self._db = QIProfile() self._clear() def tearDown(self): self._clear() def test_save_subject(self): self._db.save_subject(project(), SUBJECT) def test_save_session(self): date = datetime.datetime(2013, 7, 4, tzinfo=pytz.utc) self._db.save_session(project(), SUBJECT, SESSION, acquisition_date=date) date = datetime.datetime(2013, 7, 4, tzinfo=pytz.utc) self._db.save_session(project(), SUBJECT, SESSION, acquisition_date=date) def _clear(self): sbj = self._db.find_subject(project(), SUBJECT) if sbj: sbj.delete() if __name__ == ""__main__"": import nose nose.main(defaultTest=__name__) ","import datetime import pytz from nose.tools import (assert_is_none) from qipipe.helpers.qiprofile_helper import QIProfile from qiprofile.models import Project from test import project from test.helpers.logging_helper import logger SUBJECT = 'Breast099' """"""The test subject."""""" SESSION = 'Session01' """"""The test session."""""" class TestQIProfileHelper(object): """"""The Imaging Profile helper unit tests."""""" def setUp(self): if not Project.objects.filter(name=project()): Project(name=project()).save() self._db = QIProfile() self._clear() def tearDown(self): self._clear() def test_save_subject(self): self._db.save_subject(project(), SUBJECT) def test_save_session(self): date = datetime.datetime(2013, 7, 4, tzinfo=pytz.utc) self._db.save_session(project(), SUBJECT, SESSION, acquisition_date=date) date = datetime.datetime(2013, 7, 4, tzinfo=pytz.utc) self._db.save_session(project(), SUBJECT, SESSION, acquisition_date=date) def _clear(self): sbj = self._db.find_subject(project(), SUBJECT) if sbj: sbj.delete() if __name__ == ""__main__"": import nose nose.main(defaultTest=__name__) " Remove the SSL default since it requires certs,"import yaml _defaults = { ""bind_client"": [ ""tcp:6667:interface={::}"" ], ""bind_server"": [] } class Config(object): def __init__(self, configFileName): self._configData = {} self._readConfig(configFileName) for key, val in _defaults: if key not in self._configData: self._configData[key] = val def _readConfig(self, fileName): try: with open(fileName, 'r') as configFile: configData = yaml.safe_load(configFile) except Exception as e: raise ConfigReadError (e) for key, val in configData.iteritems(): if key != ""include"" and key not in self._configData: self._configData[key] = val if ""include"" in configData: for fileName in configData[""include""]: self._readConfig(fileName) def __len__(self): return len(self._configData) def __getitem__(self, key): return self._configData[key] def __setitem__(self, key, value): self._configData[key] = value def getWithDefault(self, key, defaultValue): try: return self._configData[key] except KeyError: return defaultValue class ConfigReadError(Exception): def __init__(self, desc): self.desc = desc def __str__(self): return ""Error reading configuration file: {}"".format(self.desc)","import yaml _defaults = { ""bind_client"": [ ""tcp:6667:interface={::}"", ""ssl:6697:interface={::}"" ], ""bind_server"": [] } class Config(object): def __init__(self, configFileName): self._configData = {} self._readConfig(configFileName) for key, val in _defaults: if key not in self._configData: self._configData[key] = val def _readConfig(self, fileName): try: with open(fileName, 'r') as configFile: configData = yaml.safe_load(configFile) except Exception as e: raise ConfigReadError (e) for key, val in configData.iteritems(): if key != ""include"" and key not in self._configData: self._configData[key] = val if ""include"" in configData: for fileName in configData[""include""]: self._readConfig(fileName) def __len__(self): return len(self._configData) def __getitem__(self, key): return self._configData[key] def __setitem__(self, key, value): self._configData[key] = value def getWithDefault(self, key, defaultValue): try: return self._configData[key] except KeyError: return defaultValue class ConfigReadError(Exception): def __init__(self, desc): self.desc = desc def __str__(self): return ""Error reading configuration file: {}"".format(self.desc)" Fix code quality issues introduced by web editor while correcting conflicts,"package seedu.address.model.util; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.model.AddressBook; import seedu.address.model.ReadOnlyAddressBook; import seedu.address.model.tag.UniqueTagList; import seedu.utask.model.task.Deadline; import seedu.utask.model.task.EventTask; import seedu.utask.model.task.Frequency; import seedu.utask.model.task.Name; import seedu.utask.model.task.Task; import seedu.utask.model.task.Timestamp; import seedu.utask.model.task.UniqueTaskList.DuplicateTaskException; public class SampleDataUtil { public static Task[] getSamplePersons() { try { return new Task[] { new EventTask(new Name(""My first task""), new Deadline(""010117""), new Timestamp(""0900 to 1000""), new Frequency(""-""), new UniqueTagList(""important"")) }; } catch (IllegalValueException e) { throw new AssertionError(""sample data cannot be invalid"", e); } } public static ReadOnlyAddressBook getSampleAddressBook() { try { AddressBook sampleAB = new AddressBook(); for (Task samplePerson : getSamplePersons()) { sampleAB.addPerson(samplePerson); } return sampleAB; } catch (DuplicateTaskException e) { throw new AssertionError(""sample data cannot contain duplicate persons"", e); } } } ","package seedu.address.model.util; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.model.AddressBook; import seedu.address.model.ReadOnlyAddressBook; import seedu.address.model.tag.UniqueTagList; import seedu.utask.model.task.Deadline; import seedu.utask.model.task.EventTask; import seedu.utask.model.task.Frequency; import seedu.utask.model.task.Name; import seedu.utask.model.task.Task; import seedu.utask.model.task.Timestamp; import seedu.utask.model.task.UniqueTaskList.DuplicateTaskException; public class SampleDataUtil { public static Task[] getSamplePersons() { try { return new Task[] { new EventTask(new Name(""My first task""), new Deadline(""010117""), new Timestamp(""0900 to 1000""), new Frequency(""-""), new UniqueTagList(""important"")) }; } catch (IllegalValueException e) { throw new AssertionError(""sample data cannot be invalid"", e); } } public static ReadOnlyAddressBook getSampleAddressBook() { try { AddressBook sampleAB = new AddressBook(); for (Task samplePerson : getSamplePersons()) { sampleAB.addPerson(samplePerson); } return sampleAB; } catch (DuplicateTaskException e) { throw new AssertionError(""sample data cannot contain duplicate persons"", e); } } } " "[bare-expo] Fix ios detox test hang Sometimes the iOS detox tests fail with error `Interaction cannot continue because the desired element was not found.` The `isVisible` check requires that at least %75 of the element is visible on the screen, which was not always the case.","import { by, device, element, expect as detoxExpect, waitFor } from 'detox'; import { getTextAsync, sleepAsync } from './Utils'; import { expectResults } from './utils/report'; let TESTS = [ 'Basic', // 'Asset', // 'FileSystem', // 'Font', 'Permissions', 'Blur', 'LinearGradient', 'Constants', // 'Contacts', 'Crypto', // 'GLView', 'Haptics', 'Localization', // 'SecureStore', // 'Segment', // 'SQLite', 'Random', 'Permissions', 'KeepAwake', 'FirebaseCore', 'FirebaseAnalytics', // 'Audio', 'HTML', ]; const MIN_TIME = 50000; describe('test-suite', () => { TESTS.map(testName => { it( `passes ${testName}`, async () => { await device.launchApp({ newInstance: true, url: `bareexpo://test-suite/select/${testName}`, }); await sleepAsync(100); await detoxExpect(element(by.id('test_suite_container'))).toExist(); await waitFor(element(by.id('test_suite_text_results'))) .toExist() .withTimeout(MIN_TIME); const input = await getTextAsync('test_suite_final_results'); expectResults({ testName, input, }); }, MIN_TIME * 1.5 ); }); }); ","import { by, device, element, expect as detoxExpect, waitFor } from 'detox'; import { getTextAsync, sleepAsync } from './Utils'; import { expectResults } from './utils/report'; let TESTS = [ 'Basic', // 'Asset', // 'FileSystem', // 'Font', 'Permissions', 'Blur', 'LinearGradient', 'Constants', // 'Contacts', 'Crypto', // 'GLView', 'Haptics', 'Localization', // 'SecureStore', // 'Segment', // 'SQLite', 'Random', 'Permissions', 'KeepAwake', 'FirebaseCore', 'FirebaseAnalytics', // 'Audio', 'HTML', ]; const MIN_TIME = 50000; describe('test-suite', () => { TESTS.map(testName => { it( `passes ${testName}`, async () => { await device.launchApp({ newInstance: true, url: `bareexpo://test-suite/select/${testName}`, }); await sleepAsync(100); await detoxExpect(element(by.id('test_suite_container'))).toBeVisible(); await waitFor(element(by.id('test_suite_text_results'))) .toBeVisible() .withTimeout(MIN_TIME); const input = await getTextAsync('test_suite_final_results'); expectResults({ testName, input, }); }, MIN_TIME * 1.5 ); }); }); " Enable the write of the offical README.md,"#! /bin/env php <?php // Load readme.md template $readme = file_get_contents(__DIR__ . '/README.template.md'); // Creating simple tags $readme = fillReadme($readme, 'creating-simple-tags'); file_put_contents(__DIR__ . '/../README.md', $readme); function fillReadme(&$file, $example) { $process = proc_open( 'php '.__DIR__.'/examples/' . $example . '.php', array( array(""pipe"",""r""), array(""pipe"",""w""), array(""pipe"",""w"") ), $pipes ); $phpOutput = stream_get_contents($pipes[1]); return str_replace( '{{'.$example.'}}', '`````php'. PHP_EOL. file_get_contents(__DIR__ . '/examples/' . $example . '.php'). '`````'. PHP_EOL. '`````jade'. PHP_EOL. file_get_contents(__DIR__ . '/examples/' . $example . '.jade'). '`````'. PHP_EOL. '`````html'. PHP_EOL. $phpOutput. PHP_EOL. '`````'. PHP_EOL, $file ); } ","#! /bin/env php <?php // Load readme.md template $readme = file_get_contents(__DIR__ . '/README.md'); // Creating simple tags $readme = fillReadme($readme, 'creating-simple-tags'); echo $readme; function fillReadme(&$file, $example) { $process = proc_open( 'php '.__DIR__.'/examples/' . $example . '.php', array( array(""pipe"",""r""), array(""pipe"",""w""), array(""pipe"",""w"") ), $pipes ); $phpOutput = stream_get_contents($pipes[1]); return str_replace( '{{'.$example.'}}', '`````php'. PHP_EOL. file_get_contents(__DIR__ . '/examples/' . $example . '.php'). '`````'. PHP_EOL. '`````jade'. PHP_EOL. file_get_contents(__DIR__ . '/examples/' . $example . '.jade'). '`````'. PHP_EOL. '`````html'. PHP_EOL. $phpOutput. PHP_EOL. '`````'. PHP_EOL, $file ); } " Change date display in email,"<?php class EmailSendGradesWorker extends SendGradesWorker { public function fire($job, $data){ $start_time = microtime(true); Log::info('Job started_EmailSendGradesWorker', array('start_time' => $start_time)); $report = new TextReportGeneratorWorker(); $this->userObject = User::find($data['user_id']); $report->setUser($this->userObject); $grades = $report->getNotSentGrades(); if($grades !== false){ $data = array( 'grades' => $grades ); Log::info(View::make('emails.grades', $data)->render()); if(!empty($data['grades'])){ Mail::send('emails.grades', $data, function($message) { $message->to($this->userObject->email)->subject('Oceny z DziennikLogin - ' . date('Y - m - d H:i')); }); //Mark grades as sent EmailSendStatus::where('user_id', '=', $this->userObject->id) ->whereIn('grade_id', $report->getNotSentGradesIds()) ->update(array('status' => '1')); Log::info('Email sent'); } } else { Log::info('No grades to send'); } //Delete the job $job->delete(); //Some logs Log::info('Job successful', array('time' => microtime(true), 'execution_time' => microtime(true) - $start_time)); } }","<?php class EmailSendGradesWorker extends SendGradesWorker { public function fire($job, $data){ $start_time = microtime(true); Log::info('Job started_EmailSendGradesWorker', array('start_time' => $start_time)); $report = new TextReportGeneratorWorker(); $this->userObject = User::find($data['user_id']); $report->setUser($this->userObject); $grades = $report->getNotSentGrades(); if($grades !== false){ $data = array( 'grades' => $grades ); Log::info(View::make('emails.grades', $data)->render()); if(!empty($data['grades'])){ Mail::send('emails.grades', $data, function($message) { $message->to($this->userObject->email)->subject('Oceny z DziennikLogin - ' . date('Y-m-d H:i')); }); //Mark grades as sent EmailSendStatus::where('user_id', '=', $this->userObject->id) ->whereIn('grade_id', $report->getNotSentGradesIds()) ->update(array('status' => '1')); Log::info('Email sent'); } } else { Log::info('No grades to send'); } //Delete the job $job->delete(); //Some logs Log::info('Job successful', array('time' => microtime(true), 'execution_time' => microtime(true) - $start_time)); } }" "Add hack to deal with PHP entry files In case we're using dev environment (or any other the prod one) we'll incorrect asset url. This hack tryies to deal with it in an ugly, but working way. TODO: deal with absolute URLs (or remove that option if it's never used).","<?php namespace Avalanche\Bundle\ImagineBundle\Imagine; use Symfony\Component\Routing\RouterInterface; class CachePathResolver { /** * @var string */ private $webRoot; /** * @var RouterInterface */ private $router; /** * Constructs cache path resolver with a given web root and cache prefix * * @param string $webRoot * @param RouterInterface $router */ public function __construct($webRoot, RouterInterface $router) { $this->webRoot = $webRoot; $this->router = $router; } /** * Gets filtered path for rendering in the browser * * @param string $path * @param string $filter * @param boolean $absolute * * @return mixed */ public function getBrowserPath($path, $filter, $absolute = false) { $realPath = realpath($this->webRoot . $path); $path = ltrim($path, '/'); $uri = $this->router->generate('_imagine_' . $filter, ['path' => $path], $absolute); $uri = str_replace(urlencode($path), urldecode($path), $uri); // TODO: find better way then this hack. if (preg_match('#^/\w+[.]php(/.*?)$#i', $uri, $m)) { $uri = $m[1]; } $cached = realpath($this->webRoot . $uri); if (file_exists($cached) && !is_dir($cached) && filemtime($realPath) > filemtime($cached)) { unlink($cached); } return $uri; } } ","<?php namespace Avalanche\Bundle\ImagineBundle\Imagine; use Symfony\Component\Routing\RouterInterface; class CachePathResolver { /** * @var string */ private $webRoot; /** * @var RouterInterface */ private $router; /** * Constructs cache path resolver with a given web root and cache prefix * * @param string $webRoot * @param RouterInterface $router */ public function __construct($webRoot, RouterInterface $router) { $this->webRoot = $webRoot; $this->router = $router; } /** * Gets filtered path for rendering in the browser * * @param string $path * @param string $filter * @param boolean $absolute * * @return mixed */ public function getBrowserPath($path, $filter, $absolute = false) { $realPath = realpath($this->webRoot . $path); $path = ltrim($path, '/'); $uri = $this->router->generate('_imagine_' . $filter, ['path' => $path], $absolute); $uri = str_replace(urlencode($path), urldecode($path), $uri); $cached = realpath($this->webRoot . $uri); if (file_exists($cached) && !is_dir($cached) && filemtime($realPath) > filemtime($cached)) { unlink($cached); } return $uri; } } " Replace initial D. and M. with similar-looking characters to get around archaic Twitter restriction.,"# encoding: utf-8 """"""Twitter delivery mechanism for botfriend."""""" import re import unicodedata from nose.tools import set_trace import tweepy from bot import Publisher class TwitterPublisher(Publisher): def __init__( self, bot, full_config, kwargs ): for key in ['consumer_key', 'consumer_secret', 'access_token', 'access_token_secret']: if not key in kwargs: raise ValueError( ""Missing required Twitter configuration key %s"" % key ) auth = tweepy.OAuthHandler(kwargs['consumer_key'], kwargs['consumer_secret']) auth.set_access_token(kwargs['access_token'], kwargs['access_token_secret']) self.api = tweepy.API(auth) def twitter_safe(self, content): return _twitter_safe(content) def publish(self, post, publication): content = self.twitter_safe(post.content) # TODO: update_with_media would go here if there were attachments # on the Post. try: response = self.api.update_status(content) publication.report_success() except tweepy.error.TweepError, e: publication.report_failure(e) def _twitter_safe(content): """"""Turn a string into something that won't get rejected by Twitter."""""" content = unicode(content) content = unicodedata.normalize('NFC', content) for bad, replace in ('D', u'𝙳'), ('M', u'𝙼'): if any(content.startswith(x) for x in (bad + ' ', bad + '.')): content = re.compile(""^%s"" % bad).sub(replace, content) content = content.encode(""utf8"") return content[:140] Publisher = TwitterPublisher ","""""""Twitter delivery mechanism for botfriend."""""" from nose.tools import set_trace import tweepy from bot import Publisher class TwitterPublisher(Publisher): def __init__( self, bot, full_config, kwargs ): for key in ['consumer_key', 'consumer_secret', 'access_token', 'access_token_secret']: if not key in kwargs: raise ValueError( ""Missing required Twitter configuration key %s"" % key ) auth = tweepy.OAuthHandler(kwargs['consumer_key'], kwargs['consumer_secret']) auth.set_access_token(kwargs['access_token'], kwargs['access_token_secret']) self.api = tweepy.API(auth) def twitter_safe(self, content): content = unicode(content) content = unicodedata.normalize('NFC', content) content = content.encode(""utf8"") # TODO: replace initial D., M. etc. return content[:140] def publish(self, post, publication): content = self.twitter_safe(post.content) # TODO: update_with_media would go here if there were attachments # on the Post. try: response = self.api.update_status(content) publication.report_success() except tweepy.error.TweepError, e: publication.report_failure(e) Publisher = TwitterPublisher " Support API keys on organization project list (fixes GH-1666),"from __future__ import absolute_import from rest_framework.response import Response from sentry.api.base import DocSection from sentry.api.bases.organization import OrganizationEndpoint from sentry.api.serializers import serialize from sentry.models import Project class OrganizationProjectsEndpoint(OrganizationEndpoint): doc_section = DocSection.ORGANIZATIONS def get(self, request, organization): """""" List an organization's projects Return a list of projects bound to a organization. {method} {path} """""" if request.auth and hasattr(request.auth, 'project'): team_list = [request.auth.project.team] project_list = [request.auth.project] else: team_list = list(request.access.teams) project_list = list(Project.objects.filter( team__in=team_list, ).order_by('name')) team_map = dict( (t.id, c) for (t, c) in zip(team_list, serialize(team_list, request.user)), ) context = [] for project, pdata in zip(project_list, serialize(project_list, request.user)): pdata['team'] = team_map[project.team_id] context.append(pdata) return Response(context) ","from __future__ import absolute_import from rest_framework.response import Response from sentry.api.base import DocSection from sentry.api.bases.organization import OrganizationEndpoint from sentry.api.serializers import serialize from sentry.models import Project, Team class OrganizationProjectsEndpoint(OrganizationEndpoint): doc_section = DocSection.ORGANIZATIONS def get(self, request, organization): """""" List an organization's projects Return a list of projects bound to a organization. {method} {path} """""" team_list = Team.objects.get_for_user( organization=organization, user=request.user, ) project_list = [] for team in team_list: project_list.extend(Project.objects.get_for_user( team=team, user=request.user, )) project_list.sort(key=lambda x: x.name) team_map = dict( (t.id, c) for (t, c) in zip(team_list, serialize(team_list, request.user)), ) context = [] for project, pdata in zip(project_list, serialize(project_list, request.user)): pdata['team'] = team_map[project.team_id] context.append(pdata) return Response(context) " "Set collection name to 'null' rather than a placeholder for inline results","// MapReduceOutput.java package com.mongodb; /** * Represents the result of a map/reduce operation * @author antoine */ public class MapReduceOutput { MapReduceOutput( DBCollection from , BasicDBObject raw ){ _raw = raw; if ( raw.containsKey( ""results"" ) ) { _coll = null; _collname = null; _resultSet = (Iterable<DBObject>) raw.get( ""results"" ); } else { _collname = raw.getString( ""result"" ); _coll = from._db.getCollection( _collname ); _resultSet = _coll.find(); } _counts = (BasicDBObject)raw.get( ""counts"" ); } /** * returns a cursor to the results of the operation * @return */ public Iterable<DBObject> results(){ return _resultSet; } /** * drops the collection that holds the results */ public void drop(){ if ( _coll != null) _coll.drop(); } /** * gets the collection that holds the results * (Will return null if results are Inline) * @return */ public DBCollection getOutputCollection(){ return _coll; } public BasicDBObject getRaw(){ return _raw; } public String toString(){ return _raw.toString(); } final BasicDBObject _raw; final String _collname; final Iterable<DBObject> _resultSet; final DBCollection _coll; final BasicDBObject _counts; } ","// MapReduceOutput.java package com.mongodb; /** * Represents the result of a map/reduce operation * @author antoine */ public class MapReduceOutput { MapReduceOutput( DBCollection from , BasicDBObject raw ){ _raw = raw; if ( raw.containsKey( ""results"" ) ) { _coll = null; _collname = ""<<INLINE>>""; _resultSet = (Iterable<DBObject>) raw.get( ""results"" ); } else { _collname = raw.getString( ""result"" ); _coll = from._db.getCollection( _collname ); _resultSet = _coll.find(); } _counts = (BasicDBObject)raw.get( ""counts"" ); } /** * returns a cursor to the results of the operation * @return */ public Iterable<DBObject> results(){ return _resultSet; } /** * drops the collection that holds the results */ public void drop(){ if ( _coll != null) _coll.drop(); } /** * gets the collection that holds the results * (Will return null if results are Inline) * @return */ public DBCollection getOutputCollection(){ return _coll; } public BasicDBObject getRaw(){ return _raw; } public String toString(){ return _raw.toString(); } final BasicDBObject _raw; final String _collname; final Iterable<DBObject> _resultSet; final DBCollection _coll; final BasicDBObject _counts; } " Fix tests according to the defaults,"var should = require(""should""); var rank = require(""../index.js"").rank; describe(""Rank calculation"", function() { var points = 72; var hours = 36; var gravity = 1.8; describe(""Calulate the rank for an element"", function() { var score; before(function(done) { score = rank.rank(points, hours, gravity); done(); }); it('is bigger than 0', function(done) { (score > 0).should.be.true; done(); }); it('is correct', function(done) { should.equal(0.1137595839488455, score); done(); }); }); describe(""Rank variation factor based on published time"", function() { var score; before(function(done) { score = rank.rank(points, hours, gravity); done(); }); it('decreases rank if it is older', function(done) { var older_hours = hours + 1; var older_score = rank.rank(points, older_hours, gravity); (score > older_score).should.be.true; done(); }); it('increases rank if it is fresh', function(done) { var earlier_hours = hours - 1; var earlier_score = rank.rank(points, earlier_hours, gravity); (score < earlier_score).should.be.true; done(); }); }); }); ","var should = require(""should""); var rank = require(""../index.js"").rank; describe(""Rank calculation"", function() { var points = 72; var hours = 36; var gravity = 1.8; describe(""Calulate the rank for an element"", function() { var score; before(function(done) { score = rank.rank(points, hours, gravity); done(); }); it('is bigger than 0', function(done) { (score > 0).should.be.true; done(); }); it('is correct', function(done) { should.equal(0.1032100580982522, score); done(); }); }); describe(""Rank variation factor based on published time"", function() { var score; before(function(done) { score = rank.rank(points, hours, gravity); done(); }); it('decreases rank if it is older', function(done) { var older_hours = hours + 1; var older_score = rank.rank(points, older_hours, gravity); (score > older_score).should.be.true; done(); }); it('increases rank if it is fresh', function(done) { var earlier_hours = hours - 1; var earlier_score = rank.rank(points, earlier_hours, gravity); (score < earlier_score).should.be.true; done(); }); }); }); " Add link and title in the bricks,"<?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> ","<?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""> <a href=""#""> <?php echo image_tag($doc['digitalObject']['thumbnail_FullPath']) ?> </a> </div> <div class=""details""> </div> </div> <?php endforeach; ?> </div> <div class=""section""> <?php echo get_partial('default/pager', array('pager' => $pager)) ?> </div> </div> </div> " Put all URLs to public,"import packageJson from './package.json'; module.exports = { backendRoot: 'https://obscure-woodland-71302.herokuapp.com/', /* flaskRoot: 'http://localhost:5000',*/ flaskRoot: 'http://catapp-staging.herokuapp.com/', /* graphQLRoot: (process.env.NODE_ENV !== 'production') ? '//localhost:5000/graphql' : '//catappdatabase.herokuapp.com/graphql', */ graphQLRoot: '//catappdatabase.herokuapp.com/graphql', newGraphQLRoot: '//catappdatabase2.herokuapp.com/graphql', whiteLabel: false, suBranding: false, appBar: true, version: packageJson.version, gaTrackingId: 'UA-109061730-1', apps: [ { title: 'Activity Maps', route: '/activityMaps', }, { title: 'AtoML', }, { title: 'CatKit Slab Generator', route: '/catKitDemo', }, { title: 'GraphiQL Console', route: '/graphQLConsole', }, { title: 'Pourbaix Diagrams', }, { title: 'Publications', route: '/publications', }, { title: 'Scaling Relations', }, { /* title: 'Upload Datasets',*/ /* route: '/upload',*/ /* }, {*/ title: 'Wyckoff Bulk Generator', route: '/bulkGenerator', }, { title: 'Your Next App ...', route: '/yourNextApp', }, ], }; ","import packageJson from './package.json'; module.exports = { backendRoot: 'https://obscure-woodland-71302.herokuapp.com/', flaskRoot: 'http://localhost:5000', /* flaskRoot: 'http://catapp-staging.herokuapp.com/',*/ /* graphQLRoot: (process.env.NODE_ENV !== 'production') ? '//localhost:5000/graphql' : '//catappdatabase.herokuapp.com/graphql', */ graphQLRoot: '//catappdatabase.herokuapp.com/graphql', newGraphQLRoot: '//catappdatabase2.herokuapp.com/graphql', whiteLabel: false, suBranding: false, appBar: true, version: packageJson.version, gaTrackingId: 'UA-109061730-1', apps: [ { title: 'Activity Maps', route: '/activityMaps', }, { title: 'AtoML', }, { title: 'CatKit Slab Generator', route: '/catKitDemo', }, { title: 'GraphiQL Console', route: '/graphQLConsole', }, { title: 'Pourbaix Diagrams', }, { title: 'Publications', route: '/publications', }, { title: 'Scaling Relations', }, { /* title: 'Upload Datasets',*/ /* route: '/upload',*/ /* }, {*/ title: 'Wyckoff Bulk Generator', route: '/bulkGenerator', }, { title: 'Your Next App ...', route: '/yourNextApp', }, ], }; " Remove bootswatchlet to improve load performance.,"// For any third party dependencies, like jQuery, place them in the lib folder. // Configure loading modules from the lib directory, // except for 'app' ones, which are in a sibling // directory. requirejs.config({ baseUrl: 'js', paths: { // the left side is the module ID, // the right side is the path to // the jQuery file, relative to baseUrl. // Also, the path should NOT include // the '.js' file extension. router: 'app/router', parts: 'app/parts', controllers: 'app/controllers', data: 'app/data', models: 'app/models', views: 'app/views', bootstrap: 'lib/bootstrap', twbs: 'lib/twbs', jquery: 'lib/jquery', Handlebars: 'lib/handlebars', text: 'lib/text', hbar: 'lib/hbars' }, shim: { bootstrap: { deps: ['jquery'] }, twbs: { deps: ['bootstrap'] }, Handlebars: { deps: ['bootstrap'], exports: 'Handlebars' }, 'jquery': { exports: '$' } }, hbars: { extension: '.hbar' // default = '.html' } }); // Start loading the main app file. Put all of // your application logic in there. require(['app/main'], function () { // You can put stuff in here too. }); ","// For any third party dependencies, like jQuery, place them in the lib folder. // Configure loading modules from the lib directory, // except for 'app' ones, which are in a sibling // directory. requirejs.config({ baseUrl: 'js', paths: { // the left side is the module ID, // the right side is the path to // the jQuery file, relative to baseUrl. // Also, the path should NOT include // the '.js' file extension. router: 'app/router', parts: 'app/parts', controllers: 'app/controllers', data: 'app/data', models: 'app/models', views: 'app/views', bootstrap: 'lib/bootstrap', twbs: 'lib/twbs', jquery: 'lib/jquery', Handlebars: 'lib/handlebars', text: 'lib/text', hbar: 'lib/hbars', bootswatchlet: 'lib/bootswatchlet' }, shim: { bootstrap: { deps: ['jquery'] }, twbs: { deps: ['bootstrap'] }, Handlebars: { deps: ['bootstrap'], exports: 'Handlebars' }, 'jquery': { exports: '$' }, bootswatchlet: { deps: ['twbs'] } }, hbars: { extension: '.hbar' // default = '.html' } }); // Start loading the main app file. Put all of // your application logic in there. require(['app/main'], function () { // You can put stuff in here too. }); " "Fix indenting. Create any schemas that were just loaded.","from django.core.management.commands import loaddata from django.core.management.base import CommandError from django.db import DatabaseError from optparse import make_option from ...models import Schema, template_schema class Command(loaddata.Command): option_list = loaddata.Command.option_list + ( make_option('--schema', action='store', dest='schema', help='Specify which schema to load schema-aware models to', default='__template__', ), ) def handle(self, *app_labels, **options): schema_name = options.get('schema') if schema_name == '__template__': # Hmm, we don't want to accidentally write data to this, so # we should raise an exception if we are going to be # writing any schema-aware objects. schema = None else: try: schema = Schema.objects.get(schema=options.get('schema')) except Schema.DoesNotExist: raise CommandError('No Schema found named ""%s""' % schema_name) schema.activate() super(Command, self).handle(*app_labels, **options) if schema: schema.deactivate() for schema in Schema.objects.all(): schema.create_schema() ","from django.core.management.commands import loaddata from django.core.management.base import CommandError from django.db import DatabaseError from optparse import make_option from ...models import Schema, template_schema class Command(loaddata.Command): option_list = loaddata.Command.option_list + ( make_option('--schema', action='store', dest='schema', help='Specify which schema to load schema-aware models to', default='__template__', ), ) def handle(self, *app_labels, **options): schema_name = options.get('schema') if schema_name == '__template__': # Hmm, we don't want to accidentally write data to this, so # we should raise an exception if we are going to be # writing any schema-aware objects. schema = None else: try: schema = Schema.objects.get(schema=options.get('schema')) except Schema.DoesNotExist: raise CommandError('No Schema found named ""%s""' % schema_name) schema.activate() super(Command, self).handle(*app_labels, **options) if schema: schema.deactivate() " Add alert for invalid creds,"angular.module('ccdb.login', ['ccdb.authentication.authentication', 'ccdb.authentication.user.authentication', 'ui.bootstrap']) .config(function ($routeProvider) { $routeProvider.when( '/login', { templateUrl: 'login/login.html', controller: 'LoginController', access: { requiredLogin: false } } ); }) .controller('LoginController', function($scope, $window, $location, $timeout, UserAuthentication, Authentication) { $scope.errorHandler = {}; $scope.reset = function () { $location.path('/reset'); }; $scope.login = function() { var username = $scope.user.username, password = $scope.user.password; if (username !== undefined && password !== undefined) { UserAuthentication.login(username, password).success(function(data) { if (data.status === 401) { alert('Invalid credentials'); return null; } Authentication.isLoggedIn = true; Authentication.user = data.user.username; Authentication.userRole = data.user.role; $window.sessionStorage.token = data.token; $window.sessionStorage.user = data.user.username; $window.sessionStorage.userRole = data.user.role; $location.path('/'); }).error(function(error) { $scope.errorHandler.message = (error) ? error.message : 'An error occurred'; }); } else { alert('Invalid credentials'); } }; } ); ","angular.module('ccdb.login', ['ccdb.authentication.authentication', 'ccdb.authentication.user.authentication', 'ui.bootstrap']) .config(function ($routeProvider) { $routeProvider.when( '/login', { templateUrl: 'login/login.html', controller: 'LoginController', access: { requiredLogin: false } } ); }) .controller('LoginController', function($scope, $window, $location, $timeout, UserAuthentication, Authentication) { $scope.errorHandler = {}; $scope.reset = function () { $location.path('/reset'); }; $scope.login = function() { var username = $scope.user.username, password = $scope.user.password; if (username !== undefined && password !== undefined) { UserAuthentication.login(username, password).success(function(data) { if (data.status === 401) return null; Authentication.isLoggedIn = true; Authentication.user = data.user.username; Authentication.userRole = data.user.role; $window.sessionStorage.token = data.token; $window.sessionStorage.user = data.user.username; $window.sessionStorage.userRole = data.user.role; $location.path('/'); }).error(function(error) { $scope.errorHandler.message = (error) ? error.message : 'An error occurred'; }); } else { alert('Invalid credentials'); } }; } ); " Fix converter instances cache and remove unnecessary constant,"<?php namespace Elchristo\Calendar\Converter; use Elchristo\Calendar\Exception\RuntimeException; use Elchristo\Calendar\Model\CalendarInterface; /** * Facade class to access converters and execute conversion process */ class Converter { /** @var array Cached converter instances */ private static $converters = []; /** * Convert events of given calendar into * * @param CalendarInterface $calendar Calendar to convert * @param string $name Converter name / format * @param array $options Additional options * * @return ConverterInterface * @throws RuntimeException */ public static function convert(CalendarInterface $calendar, $name, array $options = []) { $canonicalizeName = $this->canonicalizeName($name); if (isset(self::$converters[$canonicalizeName])) { $converter = self::$converters[$canonicalizeName]; } else { // TODO allow configured namespaces $className = __NAMESPACE__ . '\\' . \ucfirst($name) . '\\' . ucfirst($name); if (true !== \class_exists($className, true)) { throw new RuntimeException(\sprintf('Unknown converter with name ""%s"" resolving to %s.', $name, $className)); } $config = $calendar->getConfig(); $eventBuilder = new ConvertibleEventFactory($config->getRegisteredConverters()); $converter = new $className($eventBuilder); self::$converters[$canonicalizeName] = $converter; } return $converter->convert($calendar, $options); } private function canonicalizeName($name) { return \strtolower(\strtr($name, [ '-' => '', '_' => '', ' ' => '', '\\' => '', '/' => '' ])); } } ","<?php namespace Elchristo\Calendar\Converter; use Elchristo\Calendar\Exception\RuntimeException; use Elchristo\Calendar\Model\CalendarInterface; /** * Facade class to access converters and execute conversion process */ class Converter { const DEFAULT_CONVERTER_NAMESPACE = __NAMESPACE__ . '\\'; /** @var array Cached converter instances */ private static $converters = []; /** * Convert events of given calendar into * * @param CalendarInterface $calendar Calendar to convert * @param string $name Converter name / format * @param array $options Additional options * * @return ConverterInterface * @throws RuntimeException */ public static function convert(CalendarInterface $calendar, $name, array $options = []) { if (isset(self::$converters[$name])) { $converter = self::$converters[$name]; } else { // TODO allow configured namespaces $className = self::DEFAULT_CONVERTER_NAMESPACE . \ucfirst($name) . '\\' . ucfirst($name); if (true !== \class_exists($className, true)) { throw new RuntimeException(\sprintf('Unknown converter with name ""%s"" resolving to %s.', $name, $className)); } $config = $calendar->getConfig(); $eventBuilder = new ConvertibleEventFactory($config->getRegisteredConverters()); $converter = new $className($eventBuilder); } return $converter->convert($calendar, $options); } } " Switch UI tests back to google chrome.,"import pytest from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions import time from webdriver_manager.chrome import ChromeDriverManager @pytest.fixture(scope=""session"") def chromedriver(): try: options = Options() options.headless = True options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') options.add_argument(""--disable-gpu"") driver = webdriver.Chrome(ChromeDriverManager().install(), options=options) url = 'http://localhost:9000' driver.get(url + ""/gettingstarted"") WebDriverWait(driver, 30).until(expected_conditions.title_contains('Sign in')) #Login to Graylog uid_field = driver.find_element_by_name(""username"") uid_field.clear() uid_field.send_keys(""admin"") password_field = driver.find_element_by_name(""password"") password_field.clear() password_field.send_keys(""admin"") password_field.send_keys(Keys.RETURN) WebDriverWait(driver, 30).until(expected_conditions.title_contains('Getting started')) #Run tests yield driver finally: driver.quit() ","import pytest from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions import time from webdriver_manager.chrome import ChromeDriverManager from webdriver_manager.utils import ChromeType @pytest.fixture(scope=""session"") def chromedriver(): try: options = Options() options.headless = True options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') options.add_argument(""--disable-gpu"") driver = webdriver.Chrome(ChromeDriverManager(chrome_type=ChromeType.CHROMIUM).install(), options=options) url = 'http://localhost:9000' driver.get(url + ""/gettingstarted"") WebDriverWait(driver, 30).until(expected_conditions.title_contains('Sign in')) #Login to Graylog uid_field = driver.find_element_by_name(""username"") uid_field.clear() uid_field.send_keys(""admin"") password_field = driver.find_element_by_name(""password"") password_field.clear() password_field.send_keys(""admin"") password_field.send_keys(Keys.RETURN) WebDriverWait(driver, 30).until(expected_conditions.title_contains('Getting started')) #Run tests yield driver finally: driver.quit() " Split class loading code to compare static class & generated class,"package net.folab.fo.runtime; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import java.lang.reflect.Field; import net.folab.fo.runtime._fo._lang.Boolean; import net.folab.fo.runtime._fo._lang.Integer; import org.junit.Test; public class GeneratedCodeTest { private Class<?> genClass; public void setup(String className) throws ClassNotFoundException { ClassLoader classLoader = new ClassLoader(getClass().getClassLoader()) { }; genClass = classLoader.loadClass(className); } @Test public void test__() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, ClassNotFoundException { setup(""net.folab.fo.runtime._""); test(); } public void test() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { test(""_a"", Integer.valueOf(1)); test(""_b"", Integer.valueOf(2)); test(""_c"", Integer.valueOf(3)); test(""_d"", Integer.valueOf(4)); test(""_e"", Integer.valueOf(5)); test(""_f"", Boolean.FALSE); test(""_t"", Boolean.TRUE); test(""_nt"", Boolean.FALSE); } public <T extends Evaluable<T>> void test(String name, Evaluable<T> expected) throws NoSuchFieldException, IllegalAccessException { Field field = genClass.getField(name); @SuppressWarnings(""unchecked"") Evaluable<T> value = (Evaluable<T>) field.get(null); assertThat(value.evaluate(), is(expected)); } } ","package net.folab.fo.runtime; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import java.lang.reflect.Field; import net.folab.fo.runtime._fo._lang.Boolean; import net.folab.fo.runtime._fo._lang.Integer; import org.junit.Test; import org.junit.Before; public class GeneratedCodeTest { private Class<?> genClass; @Before public void setUp() throws ClassNotFoundException { genClass = Class.forName(""net.folab.fo.runtime._""); } @Test public void test() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { test(""_a"", Integer.valueOf(1)); test(""_b"", Integer.valueOf(2)); test(""_c"", Integer.valueOf(3)); test(""_d"", Integer.valueOf(4)); test(""_e"", Integer.valueOf(5)); test(""_f"", Boolean.FALSE); test(""_t"", Boolean.TRUE); test(""_nt"", Boolean.FALSE); } public <T extends Evaluable<T>> void test(String name, Evaluable<T> expected) throws NoSuchFieldException, IllegalAccessException { Field field = genClass.getField(name); @SuppressWarnings(""unchecked"") Evaluable<T> value = (Evaluable<T>) field.get(null); assertThat(value.evaluate(), is(expected)); } } " Handle FileNotFound and Permission errors gracefully,""""""" Log file parsers provided by Sentry Logs """""" import tailer # same functionality as UNIX tail in python from ..helpers import send_message try: (FileNotFoundError, PermissionError) except NameError: # Python 2.7 FileNotFoundError = IOError # pylint: disable=redefined-builtin PermissionError = IOError # pylint: disable=redefined-builtin class Parser(object): """"""Abstract base class for any parser"""""" def __init__(self, filepath): self.filepath = filepath self.logger = self.__doc__.strip() self.message = None self.extended_message = None self.params = None self.site = None def follow_tail(self): """""" Read (tail and follow) the log file, parse entries and send messages to Sentry using Raven. """""" try: logfile = open(self.filepath) except (FileNotFoundError, PermissionError) as err: exit(""Error: Can't read logfile %s (%s)"" % (self.filepath, err)) for line in tailer.follow(logfile): self.message = None self.extended_message = None self.params = None self.site = None self.parse(line) send_message(self.message, self.extended_message, self.params, self.site, self.logger) def parse(self, line): """""" Parse a line of a log file. Must be overridden by the subclass. The implementation must set these properties: - ``message`` (string) - ``extended_message`` (string) - ``params`` (list of string) - ``site`` (string) """""" raise NotImplementedError('parse() method must set: ' 'message, extended_message, params, site') ",""""""" Log file parsers provided by Sentry Logs """""" import tailer # same functionality as UNIX tail in python from ..helpers import send_message class Parser(object): """"""Abstract base class for any parser"""""" def __init__(self, filepath): self.filepath = filepath self.logger = self.__doc__.strip() self.message = None self.extended_message = None self.params = None self.site = None def follow_tail(self): """""" Read (tail and follow) the log file, parse entries and send messages to Sentry using Raven. """""" for line in tailer.follow(open(self.filepath)): self.message = None self.extended_message = None self.params = None self.site = None self.parse(line) send_message(self.message, self.extended_message, self.params, self.site, self.logger) def parse(self, line): """""" Parse a line of a log file. Must be overridden by the subclass. The implementation must set these properties: - ``message`` (string) - ``extended_message`` (string) - ``params`` (list of string) - ``site`` (string) """""" raise NotImplementedError('parse() method must set: ' 'message, extended_message, params, site') " Add limit_days query param to the get_job endpoint.," from notifications_python_client.base import BaseAPIClient from app.notify_client import _attach_current_user class JobApiClient(BaseAPIClient): def __init__(self, base_url=None, client_id=None, secret=None): super(self.__class__, self).__init__(base_url=base_url or 'base_url', client_id=client_id or 'client_id', secret=secret or 'secret') def init_app(self, app): self.base_url = app.config['API_HOST_NAME'] self.client_id = app.config['ADMIN_CLIENT_USER_NAME'] self.secret = app.config['ADMIN_CLIENT_SECRET'] def get_job(self, service_id, job_id=None, limit_days=None): if job_id: return self.get(url='/service/{}/job/{}'.format(service_id, job_id)) params = {} if limit_days is not None: params['limit_days'] = limit_days else: return self.get(url='/service/{}/job'.format(service_id), params=params) def create_job(self, job_id, service_id, template_id, original_file_name, notification_count): data = { ""id"": job_id, ""template"": template_id, ""original_file_name"": original_file_name, ""notification_count"": notification_count } _attach_current_user(data) resp = self.post(url='/service/{}/job'.format(service_id), data=data) return resp['data'] "," from notifications_python_client.base import BaseAPIClient from app.notify_client import _attach_current_user class JobApiClient(BaseAPIClient): def __init__(self, base_url=None, client_id=None, secret=None): super(self.__class__, self).__init__(base_url=base_url or 'base_url', client_id=client_id or 'client_id', secret=secret or 'secret') def init_app(self, app): self.base_url = app.config['API_HOST_NAME'] self.client_id = app.config['ADMIN_CLIENT_USER_NAME'] self.secret = app.config['ADMIN_CLIENT_SECRET'] def get_job(self, service_id, job_id=None): if job_id: return self.get(url='/service/{}/job/{}'.format(service_id, job_id)) else: return self.get(url='/service/{}/job'.format(service_id)) def create_job(self, job_id, service_id, template_id, original_file_name, notification_count): data = { ""id"": job_id, ""template"": template_id, ""original_file_name"": original_file_name, ""notification_count"": notification_count } _attach_current_user(data) resp = self.post(url='/service/{}/job'.format(service_id), data=data) return resp['data'] " Add parameter validation to contact form,"// Here be the site javascript! $(document).ready(function () { new WOW().init(); $('.preload-section').fadeOut(function() { $('.profile').fadeIn(); }); $("".button-collapse"").sideNav(); $('.scrollspy').scrollSpy(); $(""form"").submit(function (event) { event.preventDefault(); $(""#send-msg"").attr(""disabled"", true); $(""#fa-send"").toggleClass(""fa-envelope-o"").toggleClass(""fa-spinner"").toggleClass(""fa-spin""); var msg = $(""#message"").val(); var mail = $(""#email"").val(); var subject = $(""#subject"").val(); if (msg !== """" && mail !== """" && subject !== """") { var payload = {subject: subject, email: mail, message: msg}; // Send mail to the local python mail server $.ajax({ type: ""POST"", url: ""http://mattij.com:5000/sendmail"", crossDomain: true, data: payload, complete: function (data, status, req) { $(""#fa-send"").toggleClass(""fa-envelope-o"").toggleClass(""fa-spinner"").toggleClass(""fa-spin""); $(""#message"").val(""""); $(""#email"").val(""""); $(""#subject"").val(""""); $(""#send-msg"").attr(""disabled"", false); $('#modal1').openModal(); } }); } else { alert(""Congrats! Looks like you managed to bypass MaterializeCSS form validation. Please fill all the fields""); } }); });","// Here be the site javascript! $(document).ready(function () { new WOW().init(); $('.preload-section').fadeOut(function() { $('.profile').fadeIn(); }); $("".button-collapse"").sideNav(); $('.scrollspy').scrollSpy(); $(""form"").submit(function (event) { event.preventDefault(); $(""#send-msg"").attr(""disabled"", true); $(""#fa-send"").toggleClass(""fa-envelope-o"").toggleClass(""fa-spinner"").toggleClass(""fa-spin""); var msg = $(""#message"").val(); var mail = $(""#email"").val(); var subject = $(""#subject"").val(); var payload = {subject: subject, email: mail, message: msg}; // Send mail to the local python mail server $.ajax({ type: ""POST"", url: ""http://mattij.com:5000/sendmail"", crossDomain: true, data: payload, complete: function (data, status, req) { $(""#fa-send"").toggleClass(""fa-envelope-o"").toggleClass(""fa-spinner"").toggleClass(""fa-spin""); $(""#message"").val(""""); $(""#email"").val(""""); $(""#subject"").val(""""); $(""#send-msg"").attr(""disabled"", false); $('#modal1').openModal(); } }); }); });" "Add stripslashes to comment content Closes #24","<?php include_once($BASE_DIR . 'database/models.php'); function getComments($comments) { global $smarty; $smarty->assign(""comments"", $comments); $smarty->display('models/comments.tpl'); } class CommentsHandler { function post($modelId) { // TODO: xhr global $BASE_DIR; global $smarty; $memberId = getLoggedId(); if (!$memberId) { http_response_code(403); return; } if (isset($_POST['content']) && strlen($_POST['content']) > 0) insertComment($memberId, $modelId, htmlspecialchars(stripslashes($_POST['content']))); header('Location: ' . $_SERVER['HTTP_REFERER'] . '#tab_comments'); } function delete($modelId, $commentId) { global $BASE_DIR; global $smarty; $comment = getComment($commentId); if($comment == null) { http_response_code(404); return; } if (getLoggedId() != $comment['idmember']) { http_response_code(403); return; } deleteComment($modelId, $commentId); } } ","<?php include_once($BASE_DIR . 'database/models.php'); function getComments($comments) { global $smarty; $smarty->assign(""comments"", $comments); $smarty->display('models/comments.tpl'); } class CommentsHandler { function post($modelId) { // TODO: xhr global $BASE_DIR; global $smarty; $memberId = getLoggedId(); if (!$memberId) { http_response_code(403); return; } if (isset($_POST['content']) && strlen($_POST['content']) > 0) insertComment($memberId, $modelId, htmlspecialchars($_POST['content'])); header('Location: ' . $_SERVER['HTTP_REFERER'] . '#tab_comments'); } function delete($modelId, $commentId) { global $BASE_DIR; global $smarty; $comment = getComment($commentId); if($comment == null) { http_response_code(404); return; } if (getLoggedId() != $comment['idmember']) { http_response_code(403); return; } deleteComment($modelId, $commentId); } } " Reduce visibility of firebase analytics constructor,"package com.alexstyl.specialdates.analytics; import android.content.Context; import android.os.Bundle; import com.google.firebase.analytics.FirebaseAnalytics; import com.novoda.notils.logger.simple.Log; import java.util.Locale; public class Firebase implements Analytics { private static final Bundle NO_DATA = null; private final FirebaseAnalytics firebaseAnalytics; private static Firebase INSTANCE; public static Firebase get(Context context) { if (INSTANCE == null) { INSTANCE = new Firebase(FirebaseAnalytics.getInstance(context)); } return INSTANCE; } private Firebase(FirebaseAnalytics firebaseAnalytics) { this.firebaseAnalytics = firebaseAnalytics; } @Override public void trackAction(Action goToToday) { String actionName = goToToday.getName(); firebaseAnalytics.logEvent(actionName, NO_DATA); Log.d(""Tracking event:"" + actionName); } @Override public void trackAction(ActionWithParameters action) { String formattedAction = format(action); firebaseAnalytics.logEvent(formattedAction, NO_DATA); Log.d(""Tracking event:"" + formattedAction); } @Override public void trackScreen(Screen screen) { firebaseAnalytics.logEvent(""screen_view:"" + screen.screenName(), NO_DATA); Log.d(""Tracking screen_view:"" + screen); } private String format(ActionWithParameters action) { return String.format(Locale.US, ""%s:%s:%s"", action.getName(), action.getLabel(), action.getValue()); } } ","package com.alexstyl.specialdates.analytics; import android.content.Context; import android.os.Bundle; import com.google.firebase.analytics.FirebaseAnalytics; import com.novoda.notils.logger.simple.Log; import java.util.Locale; public class Firebase implements Analytics { private static final Bundle NO_DATA = null; private final FirebaseAnalytics firebaseAnalytics; private static Firebase INSTANCE; public static Firebase get(Context context) { if (INSTANCE == null) { INSTANCE = new Firebase(FirebaseAnalytics.getInstance(context)); } return INSTANCE; } public Firebase(FirebaseAnalytics firebaseAnalytics) { this.firebaseAnalytics = firebaseAnalytics; } @Override public void trackAction(Action goToToday) { String actionName = goToToday.getName(); firebaseAnalytics.logEvent(actionName, NO_DATA); Log.d(""Tracking event:"" + actionName); } @Override public void trackAction(ActionWithParameters action) { String formattedAction = format(action); firebaseAnalytics.logEvent(formattedAction, NO_DATA); Log.d(""Tracking event:"" + formattedAction); } @Override public void trackScreen(Screen screen) { firebaseAnalytics.logEvent(""screen_view:"" + screen.screenName(), NO_DATA); Log.d(""Tracking screen_view:"" + screen); } private String format(ActionWithParameters action) { return String.format(Locale.US, ""%s:%s:%s"", action.getName(), action.getLabel(), action.getValue()); } } " "Fix incorrectly named property ""data"" to be ""attributes""","<?php namespace Chrisgeary92\Pagespeed; class Response { /** * PageSpeed API response data * * @var array */ protected $attributes; /** * Create a new PageSpeed response * * @param array $attributes */ public function __construct(array $attributes) { $this->attributes = $attributes; } /** * Return API response from PageSpeed Service * * @return array */ public function getAttributes() { return $this->attributes; } /** * Allow public access of $attribute properties * * @param string $attribute * @return mixed */ public function __get($attribute) { if (array_key_exists($attribute, $this->attributes)) { return $this->attributes[$attribute]; } } /** * Convert $attributes to JSON if cast to a string * * @return string */ public function __toString() { return json_encode($this->attributes); } /** * Return only the $attributes for var_dump() * * @return array */ public function __debugInfo() { return $this->getAttributes(); } } ","<?php namespace Chrisgeary92\Pagespeed; class Response { /** * PageSpeed API response data * * @var array */ protected $attributes; /** * Create a new PageSpeed response * * @param array $attributes */ public function __construct(array $attributes) { $this->attributes = $attributes; } /** * Return API response from PageSpeed Service * * @return array */ public function getAttributes() { return $this->attributes; } /** * Allow public access of $attribute properties * * @param string $attribute * @return mixed */ public function __get($attribute) { if (array_key_exists($attribute, $this->attributes)) { return $this->attributes[$attribute]; } } /** * Convert $attributes to JSON if cast to a string * * @return string */ public function __toString() { return json_encode($this->data); } /** * Return only the $attributes for var_dump() * * @return array */ public function __debugInfo() { return $this->getAttributes(); } } " "Send modifier keys to VM but allow bubbling This allows the keys to be used for developer shortcuts, but also keeps the ""if any key pressed"" block working (and hacked key blocks).","const bindAll = require('lodash.bindall'); class VMManager { constructor (vm) { bindAll(this, [ 'attachKeyboardEvents', 'detachKeyboardEvents', 'onKeyDown', 'onKeyUp' ]); this.vm = vm; } attachKeyboardEvents () { // Feed keyboard events as VM I/O events. document.addEventListener('keydown', this.onKeyDown); document.addEventListener('keyup', this.onKeyUp); } detachKeyboardEvents () { document.removeEventListener('keydown', this.onKeyDown); document.removeEventListener('keyup', this.onKeyUp); } onKeyDown (e) { // Don't capture keys intended for Blockly inputs. if (e.target !== document && e.target !== document.body) return; this.vm.postIOData('keyboard', { keyCode: e.keyCode, isDown: true }); // Don't stop browser keyboard shortcuts if (e.metaKey || e.altKey || e.ctrlKey) return; e.preventDefault(); } onKeyUp (e) { // Always capture up events, // even those that have switched to other targets. this.vm.postIOData('keyboard', { keyCode: e.keyCode, isDown: false }); // E.g., prevent scroll. if (e.target !== document && e.target !== document.body) { e.preventDefault(); } } } module.exports = VMManager; ","const bindAll = require('lodash.bindall'); class VMManager { constructor (vm) { bindAll(this, [ 'attachKeyboardEvents', 'detachKeyboardEvents', 'onKeyDown', 'onKeyUp' ]); this.vm = vm; } attachKeyboardEvents () { // Feed keyboard events as VM I/O events. document.addEventListener('keydown', this.onKeyDown); document.addEventListener('keyup', this.onKeyUp); } detachKeyboardEvents () { document.removeEventListener('keydown', this.onKeyDown); document.removeEventListener('keyup', this.onKeyUp); } onKeyDown (e) { // Don't capture keys intended for Blockly inputs. if (e.target !== document && e.target !== document.body) return; // Don't capture browser keyboard shortcuts if (e.metaKey || e.altKey || e.ctrlKey) return; this.vm.postIOData('keyboard', { keyCode: e.keyCode, isDown: true }); e.preventDefault(); } onKeyUp (e) { // Always capture up events, // even those that have switched to other targets. this.vm.postIOData('keyboard', { keyCode: e.keyCode, isDown: false }); // E.g., prevent scroll. if (e.target !== document && e.target !== document.body) { e.preventDefault(); } } } module.exports = VMManager; " Enable searching by port in the Node > [Service] listing,"import Controller from '@ember/controller'; import { get, set } from '@ember/object'; import WithFiltering from 'consul-ui/mixins/with-filtering'; export default Controller.extend(WithFiltering, { queryParams: { s: { as: 'filter', replace: true, }, }, setProperties: function() { this._super(...arguments); set(this, 'selectedTab', 'health-checks'); }, filter: function(item, { s = '' }) { const term = s.toLowerCase(); return ( get(item, 'Service') .toLowerCase() .indexOf(term) !== -1 || get(item, 'Port') .toString() .toLowerCase() .indexOf(term) !== -1 ); }, actions: { sortChecksByImportance: function(a, b) { const statusA = get(a, 'Status'); const statusB = get(b, 'Status'); switch (statusA) { case 'passing': // a = passing // unless b is also passing then a is less important return statusB === 'passing' ? 0 : 1; case 'critical': // a = critical // unless b is also critical then a is more important return statusB === 'critical' ? 0 : -1; case 'warning': // a = warning switch (statusB) { // b is passing so a is more important case 'passing': return -1; // b is critical so a is less important case 'critical': return 1; // a and b are both warning, therefore equal default: return 0; } } return 0; }, }, }); ","import Controller from '@ember/controller'; import { get, set } from '@ember/object'; import WithFiltering from 'consul-ui/mixins/with-filtering'; export default Controller.extend(WithFiltering, { queryParams: { s: { as: 'filter', replace: true, }, }, setProperties: function() { this._super(...arguments); set(this, 'selectedTab', 'health-checks'); }, filter: function(item, { s = '' }) { return ( get(item, 'Service') .toLowerCase() .indexOf(s.toLowerCase()) !== -1 ); }, actions: { sortChecksByImportance: function(a, b) { const statusA = get(a, 'Status'); const statusB = get(b, 'Status'); switch (statusA) { case 'passing': // a = passing // unless b is also passing then a is less important return statusB === 'passing' ? 0 : 1; case 'critical': // a = critical // unless b is also critical then a is more important return statusB === 'critical' ? 0 : -1; case 'warning': // a = warning switch (statusB) { // b is passing so a is more important case 'passing': return -1; // b is critical so a is less important case 'critical': return 1; // a and b are both warning, therefore equal default: return 0; } } return 0; }, }, }); " Fix link to font in layout view,"<!DOCTYPE html> <html> <head> <title>Budget</title> <meta name=""viewport"" content=""width=device-width, initial-scale=1"" /> <link rel=""stylesheet"" href=""https://fonts.googleapis.com/css?family=Nunito+Sans:400,400i"" /> <link rel=""stylesheet"" href=""/style.css"" /> </head> <body> @if (Auth::check()) <div class=""navigation""> <ul> <li> <a href=""/dashboard"">Dashboard</a> </li> <li> <a href=""/reports"">Reports</a> </li> <li> <a href=""/budgets"">Budgets</a> </li> <li> <a href=""/tags"">Tags</a> </li> </ul> <ul> <li> <a href=""/settings"">Settings</a> </li> <li> <a href=""/logout"">Log out</a> </li> </ul> </div> @endif <div class=""body""> @yield('body') </div> </body> </html> ","<!DOCTYPE html> <html> <head> <title>Budget</title> <meta name=""viewport"" content=""width=device-width, initial-scale=1"" /> <link rel=""stylesheet"" href=""https://fonts.googleapis.com/css?family=Nunito:300,300i"" /> <link rel=""stylesheet"" href=""/style.css"" /> </head> <body> @if (Auth::check()) <div class=""navigation""> <ul> <li> <a href=""/dashboard"">Dashboard</a> </li> <li> <a href=""/reports"">Reports</a> </li> <li> <a href=""/budgets"">Budgets</a> </li> <li> <a href=""/tags"">Tags</a> </li> </ul> <ul> <li> <a href=""/settings"">Settings</a> </li> <li> <a href=""/logout"">Log out</a> </li> </ul> </div> @endif <div class=""body""> @yield('body') </div> </body> </html> " Fix load failure if not logged in.,"package com.gh4a.loader; import java.io.IOException; import org.eclipse.egit.github.core.RepositoryId; import org.eclipse.egit.github.core.client.RequestException; import org.eclipse.egit.github.core.service.CollaboratorService; import android.content.Context; import com.gh4a.Gh4Application; public class IsCollaboratorLoader extends BaseLoader<Boolean> { private String mRepoOwner; private String mRepoName; public IsCollaboratorLoader(Context context, String repoOwner, String repoName) { super(context); mRepoOwner = repoOwner; mRepoName = repoName; } @Override public Boolean doLoadInBackground() throws IOException { Gh4Application app = Gh4Application.get(); String login = app.getAuthLogin(); if (login == null) { return false; } CollaboratorService collabService = (CollaboratorService) app.getService(Gh4Application.COLLAB_SERVICE); try { RepositoryId repoId = new RepositoryId(mRepoOwner, mRepoName); return collabService.isCollaborator(repoId, login); } catch (RequestException e) { if (e.getStatus() == 403) { // the API returns 403 if the user doesn't have push access, // which in turn means he isn't a collaborator return false; } throw e; } } } ","package com.gh4a.loader; import java.io.IOException; import org.eclipse.egit.github.core.RepositoryId; import org.eclipse.egit.github.core.client.RequestException; import org.eclipse.egit.github.core.service.CollaboratorService; import android.content.Context; import com.gh4a.Gh4Application; public class IsCollaboratorLoader extends BaseLoader<Boolean> { private String mRepoOwner; private String mRepoName; public IsCollaboratorLoader(Context context, String repoOwner, String repoName) { super(context); mRepoOwner = repoOwner; mRepoName = repoName; } @Override public Boolean doLoadInBackground() throws IOException { Gh4Application app = Gh4Application.get(); CollaboratorService collabService = (CollaboratorService) app.getService(Gh4Application.COLLAB_SERVICE); try { RepositoryId repoId = new RepositoryId(mRepoOwner, mRepoName); return collabService.isCollaborator(repoId, app.getAuthLogin()); } catch (RequestException e) { if (e.getStatus() == 403) { // the API returns 403 if the user doesn't have push access, // which in turn means he isn't a collaborator return false; } throw e; } } } " "Update favicon based on UniqueFeed values, not Feed","from optparse import make_option from django.conf import settings from django.core.management.base import BaseCommand from django.db import connection from raven import Client from ...models import UniqueFeed, Favicon class Command(BaseCommand): """"""Fetches favicon updates and saves them if there are any"""""" option_list = BaseCommand.option_list + ( make_option( '--all', action='store_true', dest='all', default=False, help='Force update of all existing favicons', ), ) def handle(self, *args, **kwargs): links = UniqueFeed.objects.values_list('link', flat=True).distinct() for link in links: try: Favicon.objects.update_favicon(link, force_update=kwargs['all']) except Exception: if settings.DEBUG or not hasattr(settings, 'SENTRY_DSN'): raise else: client = Client(dsn=settings.SENTRY_DSN) client.captureException() connection.close() ","from optparse import make_option from django.conf import settings from django.core.management.base import BaseCommand from django.db import connection from raven import Client from ...models import Feed, Favicon class Command(BaseCommand): """"""Fetches favicon updates and saves them if there are any"""""" option_list = BaseCommand.option_list + ( make_option( '--all', action='store_true', dest='all', default=False, help='Force update of all existing favicons', ), ) def handle(self, *args, **kwargs): links = Feed.objects.values_list('link', flat=True).distinct() for link in links: try: Favicon.objects.update_favicon(link, force_update=kwargs['all']) except Exception: if settings.DEBUG or not hasattr(settings, 'SENTRY_DSN'): raise else: client = Client(dsn=settings.SENTRY_DSN) client.captureException() connection.close() " Secure content that must not be altered by grunt,"""use strict""; /*jshint node: true*/ /*eslint-env node*/ module.exports = function (grunt) { require(""time-grunt"")(grunt); // Since the tasks are split using load-grunt-config, a global object contains the configuration /*global configFile, configuration*/ var ConfigFile = require(""./make/configFile.js""); global.configFile = new ConfigFile(); global.configuration = Object.create(configFile.content); if (configFile.isNew()) { grunt.registerTask(""default"", function () { var done = this.async(); //eslint-disable-line no-invalid-this grunt.util.spawn({ cmd: ""node"", args: [""make/config""], opts: { stdio: ""inherit"" } }, function (error) { if (error) { done(); return; } grunt.util.spawn({ grunt: true, args: [""check"", ""jsdoc"", ""default""], opts: { stdio: ""inherit"" } }, done); }); }); return; } configFile.readSourceFiles(); // Amend the configuration with internal settings configuration.pkg = grunt.file.readJSON(""./package.json""); require(""load-grunt-config"")(grunt); grunt.task.loadTasks(""grunt/tasks""); }; ","""use strict""; /*jshint node: true*/ /*eslint-env node*/ module.exports = function (grunt) { require(""time-grunt"")(grunt); // Since the tasks are split using load-grunt-config, a global object contains the configuration /*global configFile, configuration*/ var ConfigFile = require(""./make/configFile.js""); global.configFile = new ConfigFile(); global.configuration = configFile.content; if (configFile.isNew()) { grunt.registerTask(""default"", function () { var done = this.async(); //eslint-disable-line no-invalid-this grunt.util.spawn({ cmd: ""node"", args: [""make/config""], opts: { stdio: ""inherit"" } }, function (error) { if (error) { done(); return; } grunt.util.spawn({ grunt: true, args: [""check"", ""jsdoc"", ""default""], opts: { stdio: ""inherit"" } }, done); }); }); return; } configFile.readSourceFiles(); // Amend the configuration with internal settings configuration.pkg = grunt.file.readJSON(""./package.json""); require(""load-grunt-config"")(grunt); grunt.task.loadTasks(""grunt/tasks""); }; " Fix links in public view,"@extends('layouts.master') @section('title') {{ $collection->name }} @parent @stop @section('main-navigation') <!-- Skip --> @stop @section('content') <div class=""container pt-5 mt-5""> <div class=""mb-5 pb-5 text-lg text-muted""> <p> Výber diel z <a href=""{{ config('app.url') }}"" class=""underline"">Webu <i class=""fa fa-search color""></i> umenia</a>. </p> <p class=""mt-3""> Inšpirované výstavou <a href=""https://medium.com/sng-online/vystava-sedmicky/home"" class=""underline"">Sedmičky v SNG</a>. </p> </div> <x-user-collections.share-form :collection=""$collection"" :items=""$items"" disabled /> <div class=""pb-5 my-5 text-center text-lg text-muted""> <p> Vytvor a zdieľaj vlastný výber výtvarných diel na <a href=""{{ config('app.url') }}"" class=""underline"">Webe umenia</a>. </p> <p class=""mt-3""> Tematické výbery kurátoriek a kurátorov Slovenskej národnej galérie nájdeš na výstave <a href=""https://medium.com/sng-online/vystava-sedmicky/home"" class=""underline"">Sedmičky</a>. </p> </div> </div> @endsection ","@extends('layouts.master') @section('title') {{ $collection->name }} @parent @stop @section('main-navigation') <!-- Skip --> @stop @section('content') <div class=""container pt-5 mt-5""> <div class=""mb-5 pb-5 text-lg text-muted""> <p> Výber diel z <a href=""#TODO"" class=""underline"">Webu <i class=""fa fa-search color""></i> umenia</a>. </p> <p class=""mt-3""> Inšpirované výstavou <a href=""#TODO"" class=""underline"">Sedmičky v SNG</a>. </p> </div> <x-user-collections.share-form :collection=""$collection"" :items=""$items"" disabled /> <div class=""pb-5 my-5 text-center text-lg text-muted""> <p> Vytvor a zdieľaj vlastný výber výtvarných diel na <a href=""#TODO"" class=""underline"">Webe umenia</a>. </p> <p class=""mt-3""> Tematické výbery kurátoriek a kurátorov Slovenskej národnej galérie nájdeš na výstave <a href=""#TODO"" class=""underline"">Sedmičky</a>. </p> </div> </div> @endsection " Add vat unique per comapny,"# Copyright (C) 2015 Forest and Biomass Romania # Copyright (C) 2020 NextERP Romania # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import _, api, models from odoo.exceptions import ValidationError class ResPartner(models.Model): _inherit = ""res.partner"" @api.model def _get_vat_nrc_constrain_domain(self): domain = [ (""company_id"", ""="", self.company_id.id if self.company_id else False), (""parent_id"", ""="", False), (""vat"", ""="", self.vat), ""|"", (""nrc"", ""="", self.nrc), (""nrc"", ""="", False), ] return domain @api.constrains(""vat"", ""nrc"") def _check_vat_nrc_unique(self): for record in self: if record.vat: domain = record._get_vat_nrc_constrain_domain() found = self.env[""res.partner""].search(domain) if len(found) > 1: raise ValidationError( _(""The VAT and NRC pair (%s, %s) must be unique ids=%s!"") % (record.vat, record.nrc, found.ids) ) ","# Copyright (C) 2015 Forest and Biomass Romania # Copyright (C) 2020 NextERP Romania # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import _, api, models from odoo.exceptions import ValidationError class ResPartner(models.Model): _inherit = ""res.partner"" @api.model def _get_vat_nrc_constrain_domain(self): domain = [ (""company_id"", ""="", self.company_id), (""parent_id"", ""="", False), (""vat"", ""="", self.vat), ""|"", (""nrc"", ""="", self.nrc), (""nrc"", ""="", False), ] return domain @api.constrains(""vat"", ""nrc"") def _check_vat_nrc_unique(self): for record in self: if record.vat: domain = record._get_vat_nrc_constrain_domain() found = self.env[""res.partner""].search(domain) if len(found) > 1: raise ValidationError( _(""The VAT and NRC pair (%s, %s) must be unique ids=%s!"") % (record.vat, record.nrc, found.ids) ) " Remove console.log when exporting txt file,"const wrap = require('word-wrap'); function msgText(msg, charasMap) { if (msg.type === 'narrator') { return wrap(msg.content, { width: 72, indent: '', cut: true }); } else if (msg.type === 'ooc') { return wrap(`(( OOC: ${msg.content} ))`, { width: 72, indent: '', cut: true }); } else if (msg.type === 'chara') { const chara = charasMap.get(msg.charaId); const indentedContent = wrap(msg.content, { width: 70, indent: ' ', cut: true }); return `${chara.name.toUpperCase()}:\n${indentedContent}`; } else if (msg.type === 'image') { return `--- IMAGE ---\n${msg.url}\n-------------`; } throw new Error(`Unexpected message type: ${msg.type}`); } module.exports = ({ generateTextFile({ title, desc = null, msgs, charasMap, includeOOC }, writeRaw) { // Make sure to only write windows-compatible newlines const write = str => writeRaw(str.replace(/\n/g, '\r\n')); // header format write(`${title}\n${desc || ''}\n----------\n\n`); // Write each message msgs.forEach(msg => { if (msg.type !== 'ooc' || includeOOC) { const msgBlock = msgText(msg, charasMap); write(msgBlock+'\n\n'); } }) }, }); ","const wrap = require('word-wrap'); function msgText(msg, charasMap) { if (msg.type === 'narrator') { return wrap(msg.content, { width: 72, indent: '', cut: true }); } else if (msg.type === 'ooc') { return wrap(`(( OOC: ${msg.content} ))`, { width: 72, indent: '', cut: true }); } else if (msg.type === 'chara') { const chara = charasMap.get(msg.charaId); const indentedContent = wrap(msg.content, { width: 70, indent: ' ', cut: true }); return `${chara.name.toUpperCase()}:\n${indentedContent}`; } else if (msg.type === 'image') { return `--- IMAGE ---\n${msg.url}\n-------------`; } throw new Error(`Unexpected message type: ${msg.type}`); } module.exports = ({ generateTextFile({ title, desc = null, msgs, charasMap, includeOOC }, writeRaw) { // Make sure to only write windows-compatible newlines const write = str => writeRaw(str.replace(/\n/g, '\r\n')); // header format write(`${title}\n${desc || ''}\n----------\n\n`); // Write each message msgs.forEach(msg => { console.log(msg) if (msg.type !== 'ooc' || includeOOC) { const msgBlock = msgText(msg, charasMap); write(msgBlock+'\n\n'); } }) }, }); " Exclude common unwanted package patterns,"from django_rocket import __version__, __author__, __email__, __license__ from setuptools import setup, find_packages README = open('README.rst').read() # Second paragraph has the short description description = README.split('\n')[1] setup( name='django-rocket', version=__version__, description=description, long_description=README, author=__author__, author_email=__email__, license=__license__, url='https://github.com/mariocesar/django-rocket', download_url='https://pypi.python.org/pypi/django-rocket', packages=find_packages(exclude=['tests', 'tests.*', 'example', 'docs', 'env']), install_requires=[ 'django>1.5,<1.7', 'wheel', ], extras_require={ 'Docs': [""sphinx"", ""sphinx_rtd_theme""], 'develop': [""coverage""], }, zip_safe=False, classifiers=[ 'Operating System :: OS Independent', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django' ] ) ","from django_rocket import __version__, __author__, __email__, __license__ from setuptools import setup, find_packages README = open('README.rst').read() # Second paragraph has the short description description = README.split('\n')[1] setup( name='django-rocket', version=__version__, description=description, long_description=README, author=__author__, author_email=__email__, license=__license__, url='https://github.com/mariocesar/django-rocket', download_url='https://pypi.python.org/pypi/django-rocket', packages=find_packages(exclude=['tests', 'tests.*']), install_requires=[ 'django>1.5,<1.7', 'wheel', ], extras_require={ 'Docs': [""sphinx"", ""sphinx_rtd_theme""], 'develop': [""coverage""], }, zip_safe=False, classifiers=[ 'Operating System :: OS Independent', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django' ] ) " "Change path instead of dbName for SQLite driver SQLite does not have `dbname` parameter (in fact, SQLite databases do not have names - it's always one database per 1 file). So, if useing sqlite, you should ``` doctrine: dbal: driver: pdo_sqlite path: ""%kernel.cache_dir%/__DBNAME__.db"" ``` Where dbName will be replaced with ENV_TEST_CHANNEL_READABLE.","<?php namespace Liuggio\Fastest\Doctrine\DBAL; use Doctrine\Bundle\DoctrineBundle\ConnectionFactory as BaseConnectionFactory; use Doctrine\Common\EventManager; use Doctrine\DBAL\Configuration; use Liuggio\Fastest\Process\EnvCommandCreator; /** * Creates a connection taking the db name from the env, this is great if you want to run parallel functional tests. */ class ConnectionFactory extends BaseConnectionFactory { /** * Create a connection by name. * * @param array $params * @param Configuration $config * @param EventManager $eventManager * @param array $mappingTypes * * @return \Doctrine\DBAL\Connection */ public function createConnection(array $params, Configuration $config = null, EventManager $eventManager = null, array $mappingTypes = array()) { $dbName = $this->getDbNameFromEnv($params['dbname']); if ($params['driver'] === 'pdo_sqlite') { $params['path'] = str_replace(""__DBNAME__"", $dbName, $params['path']); } else { $params['dbname'] = $dbName; } return parent::createConnection($params, $config, $eventManager, $mappingTypes); } private function getDbNameFromEnv($dbName) { if ($this->issetDbNameEnvValue()) { return $dbName.'_'.$this->getDbNameEnvValue(); } return $dbName; } private function issetDbNameEnvValue() { $dbName = $this->getDbNameEnvValue(); return (!empty($dbName)); } private function getDbNameEnvValue() { return getenv(EnvCommandCreator::ENV_TEST_CHANNEL_READABLE); } } ","<?php namespace Liuggio\Fastest\Doctrine\DBAL; use Doctrine\Bundle\DoctrineBundle\ConnectionFactory as BaseConnectionFactory; use Doctrine\Common\EventManager; use Doctrine\DBAL\Configuration; use Liuggio\Fastest\Process\EnvCommandCreator; /** * Creates a connection taking the db name from the env, this is great if you want to run parallel functional tests. */ class ConnectionFactory extends BaseConnectionFactory { /** * Create a connection by name. * * @param array $params * @param Configuration $config * @param EventManager $eventManager * @param array $mappingTypes * * @return \Doctrine\DBAL\Connection */ public function createConnection(array $params, Configuration $config = null, EventManager $eventManager = null, array $mappingTypes = array()) { $params['dbname'] = $this->getDbNameFromEnv($params['dbname']); return parent::createConnection($params, $config, $eventManager, $mappingTypes); } private function getDbNameFromEnv($dbName) { if ($this->issetDbNameEnvValue()) { return $dbName.'_'.$this->getDbNameEnvValue(); } return $dbName; } private function issetDbNameEnvValue() { $dbName = $this->getDbNameEnvValue(); return (!empty($dbName)); } private function getDbNameEnvValue() { return getenv(EnvCommandCreator::ENV_TEST_CHANNEL_READABLE); } } " Add more syntactic construct lexing.,"from pygments.token import Comment, Keyword, Literal, Operator, Text from pygments.lexer import RegexLexer class K3Lexer(RegexLexer): name = 'K3' aliases = ['k3'] filenames = ['*.k3'] keywords = { 'preprocessor': ""include"", ""declaration"": [ ""annotation"", ""declare"", ""feed"", ""provides"", ""requires"", ""source"", ""trigger"" ], ""type"": [""bool"", ""int"", ""real"", ""string"", ""option"", ""ind"", ""collection""], ""expression"": [ ""if"", ""then"", ""else"", ""let"", ""in"", ""case"", ""of"", ""bind"", ""as"", ""some"", ""none"", ""true"", ""false"" ] } tokens = { 'root': [ (r'//.*?$', Comment), (r'\b(' + r'|'.join(keywords[""preprocessor""]) + r')\s*\b(?!\.)', Keyword.Namespace), (r'\b(' + r'|'.join(keywords[""declaration""]) + r')\s*\b(?!\.)', Keyword.Declaration), (r'\b(' + r'|'.join(keywords[""type""]) + r')\s*\b(?!\.)', Keyword.Type), (r'\b(' + r'|'.join(keywords[""expression""]) + r')\s*\b(?!\.)', Keyword.Reserved), (r'[+\-*/<>=!&|\\():;,]+', Operator), (r'[0-9]+(\.[0-9]*)?', Literal.Number), (r'""[^""]*""', Literal.String), (r'\b([_a-zA-Z][_a-zA-Z0-9]*)\b', Text), (r'\s+', Text.Whitespace) ], } ","from pygments.token import Keyword, Text, Token from pygments.lexer import RegexLexer class K3Lexer(RegexLexer): name = 'K3' aliases = ['k3'] filenames = ['*.k3'] keywords = { 'preprocessor': ""include"", ""declaration"": [ ""annotation"", ""declare"", ""feed"", ""provides"", ""requires"", ""source"", ""trigger"" ], ""type"": [""bool"", ""int"", ""real"", ""string"", ""option"", ""ind"", ""collection""], ""expression"": [ ""if"", ""then"", ""else"", ""let"", ""in"", ""case"", ""of"", ""bind"", ""as"", ""some"", ""none"", ] } tokens = { 'root': [ (r'//.*?$', Token.Comment), (r'\b(' + r'|'.join(keywords[""preprocessor""]) + r')\s*\b(?!\.)', Keyword.Namespace), (r'\b(' + r'|'.join(keywords[""declaration""]) + r')\s*\b(?!\.)', Keyword.Declaration), (r'\b(' + r'|'.join(keywords[""type""]) + r')\s*\b(?!\.)', Keyword.Type), (r'\b(' + r'|'.join(keywords[""expression""]) + r')\s*\b(?!\.)', Keyword.Reserved), (r'.*\n', Text), ], } " Change test case with partial message in expectedExceptino annotation to use full expectedExceptionMessage one,"<?php /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\TestCase; class ExceptionMessageRegExpTest extends TestCase { /** * @expectedException \Exception * @expectedExceptionMessageRegExp /^A polymorphic \w+ message/ */ public function testRegexMessage() { throw new \Exception('A polymorphic exception message'); } /** * @expectedException \Exception * @expectedExceptionMessageRegExp /^a poly[a-z]+ [a-zA-Z0-9_]+ me(s){2}age$/i */ public function testRegexMessageExtreme() { throw new \Exception('A polymorphic exception message'); } /** * @runInSeparateProcess * @requires extension xdebug * @expectedException \Exception * @expectedExceptionMessageRegExp #Screaming preg_match# */ public function testMessageXdebugScreamCompatibility() { \ini_set('xdebug.scream', '1'); throw new \Exception('Screaming preg_match'); } /** * @expectedException \Exception * @expectedExceptionMessage A variadic exception message * @expectedExceptionMessageRegExp /^A variadic \w+ message/ */ public function testSimultaneousLiteralAndRegExpExceptionMessage() { throw new \Exception('A variadic exception message'); } } ","<?php /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\TestCase; class ExceptionMessageRegExpTest extends TestCase { /** * @expectedException \Exception * @expectedExceptionMessageRegExp /^A polymorphic \w+ message/ */ public function testRegexMessage() { throw new \Exception('A polymorphic exception message'); } /** * @expectedException \Exception * @expectedExceptionMessageRegExp /^a poly[a-z]+ [a-zA-Z0-9_]+ me(s){2}age$/i */ public function testRegexMessageExtreme() { throw new \Exception('A polymorphic exception message'); } /** * @runInSeparateProcess * @requires extension xdebug * @expectedException \Exception * @expectedExceptionMessageRegExp #Screaming preg_match# */ public function testMessageXdebugScreamCompatibility() { \ini_set('xdebug.scream', '1'); throw new \Exception('Screaming preg_match'); } /** * @expectedException \Exception variadic * @expectedExceptionMessageRegExp /^A variadic \w+ message/ */ public function testSimultaneousLiteralAndRegExpExceptionMessage() { throw new \Exception('A variadic exception message'); } } " Use passive flag on addEventListener,"""use strict""; const getActivities = wrapper => { return new Promise(resolve => { const observer = new MutationObserver(mutations => { for (let mutation of mutations) { for (let addedNode of mutation.addedNodes) { if (addedNode.classList && addedNode.classList.contains(""activities"")) { observer.disconnect(); resolve(addedNode); return; } } } }); observer.observe(wrapper, { childList: true, subtree: true }); }); }; const infiniteScroll = activities => { let htmlHeight = document.documentElement.scrollHeight; const observer = new MutationObserver(() => { htmlHeight = document.documentElement.scrollHeight; }); observer.observe(activities, { childList: true, attributes: true, characterData: false, subtree: true }); document.addEventListener(""scroll"", e => { if (e.pageY + window.innerHeight === htmlHeight) { const moreButton = activities.parentNode.querySelector("".more-button""); if (moreButton === null) { return; } moreButton.click(); } }, { passive: true }); }; const init = () => { const activities = document.querySelector("".activities""); if (activities !== null) { infiniteScroll(activities); return; } const wrapper = document.querySelector("".feedActivities""); if (wrapper === null) { return; } getActivities(wrapper).then(activities => infiniteScroll(activities)); }; document.addEventListener(""DOMContentLoaded"", init); ","""use strict""; const getActivities = wrapper => { return new Promise(resolve => { const observer = new MutationObserver(mutations => { for (let mutation of mutations) { for (let addedNode of mutation.addedNodes) { if (addedNode.classList && addedNode.classList.contains(""activities"")) { observer.disconnect(); resolve(addedNode); return; } } } }); observer.observe(wrapper, { childList: true, subtree: true }); }); }; const infiniteScroll = activities => { let htmlHeight = document.documentElement.scrollHeight; const observer = new MutationObserver(() => { htmlHeight = document.documentElement.scrollHeight; }); observer.observe(activities, { childList: true, attributes: true, characterData: false, subtree: true }); document.addEventListener(""scroll"", e => { if (e.pageY + window.innerHeight === htmlHeight) { const moreButton = activities.parentNode.querySelector("".more-button""); if (moreButton === null) { return; } moreButton.click(); } }); }; const init = () => { const activities = document.querySelector("".activities""); if (activities !== null) { infiniteScroll(activities); return; } const wrapper = document.querySelector("".feedActivities""); if (wrapper === null) { return; } getActivities(wrapper).then(activities => infiniteScroll(activities)); }; document.addEventListener(""DOMContentLoaded"", init); " Add some documentation to letters,"from dal import autocomplete from django import forms from django.contrib import admin from letters.models import Letter, Topic from prosopography.models import Person class PersonInlineForm(forms.ModelForm): """"""Configure inline admin form for :class:`prosopography.models.Person` """""" class Meta: model = Person.letters_to.through fields = ('__all__') widgets = { 'person': autocomplete.ModelSelect2( url='people:dal-autocomplete', attrs={ 'data-placeholder': 'Type to search...', 'data-minimum-input-length': 2, } ), } class PersonInline(admin.TabularInline): """""":class:`prosopography.models.Person` admin inline for M2M."""""" model = Person.letters_to.through form = PersonInlineForm class LetterAdmin(admin.ModelAdmin): """"""ModelAdmin for :class:`letters.models.Letter`"""""" model = Letter inlines = [PersonInline] fields = ('book', 'letter', 'topics', 'date', 'citations') search_fields = ('book', 'letter', 'letters_to__nomina') list_filter = ('book',) filter_horizontal = ('citations',) admin.site.register(Letter, LetterAdmin) admin.site.register(Topic) ","from dal import autocomplete from django import forms from django.contrib import admin from .models import Letter, Topic from prosopography.models import Person class PersonInlineForm(forms.ModelForm): class Meta: model = Person.letters_to.through fields = ('__all__') widgets = { 'person': autocomplete.ModelSelect2( url='people:dal-autocomplete', attrs={ 'data-placeholder': 'Type to search...', 'data-minimum-input-length': 2, } ), } class PersonInline(admin.TabularInline): model = Person.letters_to.through form = PersonInlineForm class LetterAdmin(admin.ModelAdmin): model = Letter inlines = [PersonInline] fields = ('book', 'letter', 'topics', 'date', 'citations') search_fields = ('book', 'letter', 'letters_to__nomina') list_filter = ('book',) filter_horizontal = ('citations',) admin.site.register(Letter, LetterAdmin) admin.site.register(Topic) " Add handler for 433 Nickname already in use,"import zirc import ssl import socket import utils import commands debug = False class Bot(zirc.Client): def __init__(self): self.connection = zirc.Socket(family=socket.AF_INET6, wrapper=ssl.wrap_socket) self.config = zirc.IRCConfig(host=""chat.freenode.net"", port=6697, nickname=""zIRCBot2"", ident=""zirc"", realname=""A zIRC bot"", channels=[""##wolfy1339"", ""##powder-bots""], sasl_user=""BigWolfy1339"", sasl_pass="""") self.connect(self.config) self.start() @staticmethod def on_ctcp(irc, raw): utils.print_(raw, flush=True) @classmethod def on_privmsg(self, event, irc, arguments): if "" "".join(arguments).startswith(""?""): utils.call_command(self, event, irc, arguments) @classmethod def on_all(self, event, irc): if debug: utils.print_(event.raw, flush=True) @classmethod def on_nicknameinuse(self, event, irc): irc.nick(bot.config['nickname'] + ""_"") Bot() ","import zirc import ssl import socket import utils import commands debug = False class Bot(zirc.Client): def __init__(self): self.connection = zirc.Socket(family=socket.AF_INET6, wrapper=ssl.wrap_socket) self.config = zirc.IRCConfig(host=""chat.freenode.net"", port=6697, nickname=""zIRCBot2"", ident=""zirc"", realname=""A zIRC bot"", channels=[""##wolfy1339"", ""##powder-bots""], sasl_user=""BigWolfy1339"", sasl_pass="""") self.connect(self.config) self.start() @staticmethod def on_ctcp(irc, raw): utils.print_(raw, flush=True) @classmethod def on_privmsg(self, event, irc, arguments): if "" "".join(arguments).startswith(""?""): utils.call_command(self, event, irc, arguments) @classmethod def on_all(self, event, irc): if debug: utils.print_(event.raw, flush=True) Bot() " Implement __unicode__ for entry objects,"# -*- coding: utf-8 -*- """"""Base class for all types of entries."""""" class BaseEntry(object): """"""Base class for all types of entries."""""" def format(self, **options): raise NotImplementedError() @property def entry_type(self): raise NotImplementedError() @property def entry_key(self): raise NotImplementedError() @property def fields(self): raise NotImplementedError() def aliases(self, format): raise NotImplementedError() def valid(self, format): raise NotImplementedError() def keys(self): raise NotImplementedError() def values(self): raise NotImplementedError() def __eq__(self, other): raise NotImplementedError() def __ne__(self, other): return not self == other def __contains__(self, item): raise NotImplementedError() def __getitem__(self, field): """"""Return the value for the given field."""""" raise NotImplementedError() def __iter__(self): for field in self.fields: yield (field, self[field]) def __len__(self): raise NotImplementedError() def __str__(self): return self.format() def __unicode__(self): return unicode(str(self)) def __repr__(self): raise NotImplementedError() ","# -*- coding: utf-8 -*- """"""Base class for all types of entries."""""" class BaseEntry(object): """"""Base class for all types of entries."""""" def format(self, **options): raise NotImplementedError() @property def entry_type(self): raise NotImplementedError() @property def entry_key(self): raise NotImplementedError() @property def fields(self): raise NotImplementedError() def aliases(self, format): raise NotImplementedError() def valid(self, format): raise NotImplementedError() def keys(self): raise NotImplementedError() def values(self): raise NotImplementedError() def __eq__(self, other): raise NotImplementedError() def __ne__(self, other): return not self == other def __contains__(self, item): raise NotImplementedError() def __getitem__(self, field): """"""Return the value for the given field."""""" raise NotImplementedError() def __iter__(self): for field in self.fields: yield (field, self[field]) def __len__(self): raise NotImplementedError() def __str__(self): return self.format() def __repr__(self): raise NotImplementedError() " Make collections link go to v2 route,"from django.conf import settings from django.conf.urls import include, url, patterns from django.conf.urls.static import static from settings import API_BASE from website.settings import DEV_MODE from . import views base_pattern = '^{}'.format(API_BASE) urlpatterns = [ ### API ### url(base_pattern, include(patterns('', url(r'^$', views.root, name='root'), url(r'^applications/', include('api.applications.urls', namespace='applications')), url(r'^nodes/', include('api.nodes.urls', namespace='nodes')), url(r'^users/', include('api.users.urls', namespace='users')), url(r'^files/', include('api.files.urls', namespace='files')), url(r'^docs/', include('rest_framework_swagger.urls')), )) ) ] if DEV_MODE: urlpatterns.extend([ url(r'^v2/collections/', include('api.collections.urls', namespace='collections')), ]) urlpatterns += static('/static/', document_root=settings.STATIC_ROOT) handler404 = views.error_404 ","from django.conf import settings from django.conf.urls import include, url, patterns from django.conf.urls.static import static from settings import API_BASE from website.settings import DEV_MODE from . import views base_pattern = '^{}'.format(API_BASE) urlpatterns = [ ### API ### url(base_pattern, include(patterns('', url(r'^$', views.root, name='root'), url(r'^applications/', include('api.applications.urls', namespace='applications')), url(r'^nodes/', include('api.nodes.urls', namespace='nodes')), url(r'^users/', include('api.users.urls', namespace='users')), url(r'^files/', include('api.files.urls', namespace='files')), url(r'^docs/', include('rest_framework_swagger.urls')), )) ) ] if DEV_MODE: urlpatterns.extend([ url(r'^collections/', include('api.collections.urls', namespace='collections')), ]) urlpatterns += static('/static/', document_root=settings.STATIC_ROOT) handler404 = views.error_404 " Remove init from scene definition,"define(function(require){ var scene = new THREE.Object3D(); var camera = new THREE.PerspectiveCamera(75, 16 / 9, 0.1, 5000); var loader = new THREE.JSONLoader(true); var origin = new THREE.Vector3(); var StarSystem = require(""component/starfield""); var starfield = StarSystem.create(33, 100); scene.add(starfield); camera.position.set(0, 3, 10); camera.lookAt(origin); var ship; loader.load(""models/spaceship-five.js"", function(geometry, materials){ materials[1].bumpMap.bumpScale = 0.0001; ship = new THREE.Object3D(); ship.add(new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials))); var tailLight = new THREE.PointLight(0xCCCCFF, 2, 3); tailLight.position.set(0, 0, 5.2); ship.add(tailLight); scene.add(ship); console.log(ship); }); var light = new THREE.PointLight(0xFFFFFF, 1, 100); light.position.set(10, 10, 10); scene.add(light); return { scene: scene, camera: camera, render: render }; function render(time){ ship.rotation.y += 0.01; } });","define(function(require){ var scene = new THREE.Object3D(); var camera = new THREE.PerspectiveCamera(75, 16 / 9, 0.1, 5000); var loader = new THREE.JSONLoader(true); var origin = new THREE.Vector3(); var StarSystem = require(""component/starfield""); var starfield = StarSystem.create(33, 100); scene.add(starfield); camera.position.set(0, 3, 10); camera.lookAt(origin); var ship; loader.load(""models/spaceship-five.js"", function(geometry, materials){ materials[1].bumpMap.bumpScale = 0.0001; ship = new THREE.Object3D(); ship.add(new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials))); var tailLight = new THREE.PointLight(0xCCCCFF, 2, 3); tailLight.position.set(0, 0, 5.2); ship.add(tailLight); scene.add(ship); console.log(ship); }); var light = new THREE.PointLight(0xFFFFFF, 1, 100); light.position.set(10, 10, 10); scene.add(light); return { scene: scene, camera: camera, render: render, init: init }; function render(time){ ship.rotation.y += 0.01; } });" "Add README.rst contents to PyPI page That is to say, what is visible at https://pypi.org/project/serenata-toolbox/","from setuptools import setup REPO_URL = 'http://github.com/okfn-brasil/serenata-toolbox' with open('README.rst') as fobj: long_description = fobj.read() setup( author='Serenata de Amor', author_email='contato@serenata.ai', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', 'Topic :: Utilities', ], description='Toolbox for Serenata de Amor project', zip_safe=False, install_requires=[ 'aiofiles', 'aiohttp', 'beautifulsoup4>=4.4', 'lxml>=3.6', 'pandas>=0.18', 'python-decouple>=3.1', 'tqdm' ], keywords='serenata de amor, data science, brazil, corruption', license='MIT', long_description=long_description, name='serenata-toolbox', packages=[ 'serenata_toolbox', 'serenata_toolbox.federal_senate', 'serenata_toolbox.chamber_of_deputies', 'serenata_toolbox.datasets' ], url=REPO_URL, python_requires='>=3.6', version='15.0.3', ) ","from setuptools import setup REPO_URL = 'http://github.com/okfn-brasil/serenata-toolbox' setup( author='Serenata de Amor', author_email='contato@serenata.ai', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', 'Topic :: Utilities', ], description='Toolbox for Serenata de Amor project', zip_safe=False, install_requires=[ 'aiofiles', 'aiohttp', 'beautifulsoup4>=4.4', 'lxml>=3.6', 'pandas>=0.18', 'python-decouple>=3.1', 'tqdm' ], keywords='serenata de amor, data science, brazil, corruption', license='MIT', long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL), name='serenata-toolbox', packages=[ 'serenata_toolbox', 'serenata_toolbox.federal_senate', 'serenata_toolbox.chamber_of_deputies', 'serenata_toolbox.datasets' ], url=REPO_URL, python_requires='>=3.6', version='15.0.2', ) " Fix absolute paths to sources by config params,"package com.crowdin.cli.commands.functionality; import com.crowdin.cli.properties.CliProperties; import com.crowdin.cli.properties.Params; import com.crowdin.cli.properties.PropertiesBean; import com.crowdin.cli.utils.file.FileReader; import org.apache.commons.lang3.StringUtils; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; public class PropertiesBuilder { private File configFile; private File identityFile; private Params params; public PropertiesBuilder(File configFile, File identityFile, Params params) { this.configFile = configFile; this.identityFile = identityFile; this.params = params; } public PropertiesBean build() { PropertiesBean pb = (!(Files.notExists(configFile.toPath()) && params != null)) ? CliProperties.buildFromMap(new FileReader().readCliConfig(configFile)) : new PropertiesBean(); if (identityFile != null) { CliProperties.populateWithCredentials(pb, new FileReader().readCliConfig(identityFile)); } if (params != null) { if (new File(params.getSourceParam()).isAbsolute()) { pb.setPreserveHierarchy(false); pb.setBasePath(configFile.toPath().getRoot().toString()); params.setSourceParam(StringUtils.removePattern(params.getSourceParam(), ""^([a-zA-Z]:)?[\\\\/]+"")); } CliProperties.populateWithParams(pb, params); } String basePathIfEmpty = new File(configFile.getAbsolutePath()).getParent(); return CliProperties.processProperties(pb, basePathIfEmpty); } } ","package com.crowdin.cli.commands.functionality; import com.crowdin.cli.properties.CliProperties; import com.crowdin.cli.properties.Params; import com.crowdin.cli.properties.PropertiesBean; import com.crowdin.cli.utils.file.FileReader; import java.io.File; import java.nio.file.Files; public class PropertiesBuilder { private File configFile; private File identityFile; private Params params; public PropertiesBuilder(File configFile, File identityFile, Params params) { this.configFile = configFile; this.identityFile = identityFile; this.params = params; } public PropertiesBean build() { PropertiesBean pb = (!(Files.notExists(configFile.toPath()) && params != null)) ? CliProperties.buildFromMap(new FileReader().readCliConfig(configFile)) : new PropertiesBean(); if (identityFile != null) { CliProperties.populateWithCredentials(pb, new FileReader().readCliConfig(identityFile)); } if (params != null) { CliProperties.populateWithParams(pb, params); } String basePathIfEmpty = (Files.exists(configFile.toPath()) && !(params != null && params.getBasePathParam() != null)) ? new File(configFile.getAbsolutePath()).getParent() : """"; return CliProperties.processProperties(pb, basePathIfEmpty); } } " Fix missing githubIssue field when the corresponding issue already existed.,"# -*- coding: utf-8 -*- from AbstractVisitor import AbstractVisitor from duralex.alinea_parser import * from github import Github class AddGitHubIssueVisitor(AbstractVisitor): def __init__(self, args): self.github = Github(args.github_token) self.repo = self.github.get_repo(args.github_repository) self.issues = list(self.repo.get_issues()) self.current_issue = -1 super(AddGitHubIssueVisitor, self).__init__() def visit_edit_node(self, node, post): if post: return if 'commitMessage' not in node: node['commitMessage'] = '(#' + str(self.current_issue) + ')' else: node['commitMessage'] = node['commitMessage'] + '\nGitHub: #' + str(self.current_issue) def visit_node(self, node): if 'type' in node and node['type'] == 'article': title = 'Article ' + str(node['order']) body = node['content'] found = False for issue in self.issues: if issue.title == title: found = True node['githubIssue'] = issue.html_url self.current_issue = issue.number if issue.body != body: issue.edit(title=title, body=body) if not found: issue = self.repo.create_issue(title=title, body=body) node['githubIssue'] = issue.html_url self.current_issue = issue.number super(AddGitHubIssueVisitor, self).visit_node(node) ","# -*- coding: utf-8 -*- from AbstractVisitor import AbstractVisitor from duralex.alinea_parser import * from github import Github class AddGitHubIssueVisitor(AbstractVisitor): def __init__(self, args): self.github = Github(args.github_token) self.repo = self.github.get_repo(args.github_repository) self.issues = list(self.repo.get_issues()) self.current_issue = -1 super(AddGitHubIssueVisitor, self).__init__() def visit_edit_node(self, node, post): if post: return if 'commitMessage' not in node: node['commitMessage'] = '(#' + str(self.current_issue) + ')' else: node['commitMessage'] = node['commitMessage'] + '\nGitHub: #' + str(self.current_issue) def visit_node(self, node): if 'type' in node and node['type'] == 'article': title = 'Article ' + str(node['order']) body = node['content'] found = False for issue in self.issues: if issue.title == title: found = True node['githubIssue'] = issue.html_url self.current_issue = issue.number if issue.body != body: issue.edit(title=title, body=body) if not found: issue = self.repo.create_issue(title=title, body=body) self.current_issue = issue.number super(AddGitHubIssueVisitor, self).visit_node(node) " Save option added to form builder,"<?php namespace AppBundle\Form\Type; /** * Created by PhpStorm. * User: kolbusz * Date: 08.03.15 * Time: 14:16 */ use \Symfony\Component\Form\AbstractType; use \Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class TaskType extends AbstractType{ private $mode = 'create'; public function __construct($mode = 'create'){ $this->mode = $mode; } public function buildForm(FormBuilderInterface $builder, array $options){ $builder->add('done', 'checkbox', ['required' => false]) ->add('priority', 'choice', ['choices' => [0,1,2,3]]) ->add('category', 'entity', ['class' => 'AppBundle:Category']) ->add('assignee', 'entity', ['class' => 'AppBundle:User']) ->add('save', 'submit'); if($this->mode == 'create'){ $builder->add('content', 'text') ->add('dueDate', 'date'); }else if($this->mode == 'edit'){ $builder->add('content', 'text', ['disabled' => true]) ->add('dueDate', 'date', ['disabled' => true]); } } public function setDefaultOptions(OptionsResolverInterface $resolver){ $resolver->setDefaults([ 'data_class' => 'AppBundle\Entity\Task', ]); } public function getName(){ return 'task'; } } ","<?php namespace AppBundle\Form\Type; /** * Created by PhpStorm. * User: kolbusz * Date: 08.03.15 * Time: 14:16 */ use \Symfony\Component\Form\AbstractType; use \Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class TaskType extends AbstractType{ private $mode = 'create'; public function __construct($mode = 'create'){ $this->mode = $mode; } public function buildForm(FormBuilderInterface $builder, array $options){ $builder->add('done', 'checkbox', ['required' => false]) ->add('priority', 'choice', ['choices' => [0,1,2,3]]) ->add('category', 'entity', ['class' => 'AppBundle:Category']) ->add('assignee', 'entity', ['class' => 'AppBundle:User']); if($this->mode == 'create'){ $builder->add('content', 'text') ->add('dueDate', 'date'); }else if($this->mode == 'edit'){ $builder->add('content', 'text', ['disabled' => true]) ->add('dueDate', 'date', ['disabled' => true]); } } public function setDefaultOptions(OptionsResolverInterface $resolver){ $resolver->setDefaults([ 'data_class' => 'AppBundle\Entity\Task', ]); } public function getName(){ return 'task'; } } " Add comment about Provider not being used in userland code,"<?php namespace Neos\Flow\Http; use Neos\Flow\Annotations as Flow; use Neos\Flow\Core\Bootstrap; use Psr\Http\Message\ServerRequestFactoryInterface; use Psr\Http\Message\ServerRequestInterface; /** * Central authority to get hold of the active HTTP request. * When no active HTTP request can be determined (for example in CLI context) a new instance is built using a ServerRequestFactoryInterface implementation * * Note: Naturally this class is not being used explicitly. But it is configured as factory for Psr\Http\Message\ServerRequestInterface instances * * @Flow\Scope(""singleton"") */ final class ActiveHttpRequestProvider { /** * @Flow\Inject * @var Bootstrap */ protected $bootstrap; /** * @Flow\Inject * @var BaseUriProvider */ protected $baseUriProvider; /** * @Flow\Inject * @var ServerRequestFactoryInterface */ protected $serverRequestFactory; /** * Returns the currently active HTTP request, if available. * If the HTTP request can't be determined, a new instance is created using an instance of ServerRequestFactoryInterface * * @return ServerRequestInterface */ public function getActiveHttpRequest(): ServerRequestInterface { $requestHandler = $this->bootstrap->getActiveRequestHandler(); if ($requestHandler instanceof HttpRequestHandlerInterface) { return $requestHandler->getHttpRequest(); } try { $baseUri = $this->baseUriProvider->getConfiguredBaseUriOrFallbackToCurrentRequest(); } catch (Exception $e) { $baseUri = 'http://localhost'; } return $this->serverRequestFactory->createServerRequest('GET', $baseUri); } } ","<?php namespace Neos\Flow\Http; use Neos\Flow\Annotations as Flow; use Neos\Flow\Core\Bootstrap; use Psr\Http\Message\ServerRequestFactoryInterface; use Psr\Http\Message\ServerRequestInterface; /** * Central authority to get hold of the active HTTP request. * When no active HTTP request can be determined (for example in CLI context) a new instance is built using a ServerRequestFactoryInterface implementation * * @Flow\Scope(""singleton"") */ final class ActiveHttpRequestProvider { /** * @Flow\Inject * @var Bootstrap */ protected $bootstrap; /** * @Flow\Inject * @var BaseUriProvider */ protected $baseUriProvider; /** * @Flow\Inject * @var ServerRequestFactoryInterface */ protected $serverRequestFactory; /** * Returns the currently active HTTP request, if available. * If the HTTP request can't be determined, a new instance is created using an instance of ServerRequestFactoryInterface * * @return ServerRequestInterface */ public function getActiveHttpRequest(): ServerRequestInterface { $requestHandler = $this->bootstrap->getActiveRequestHandler(); if ($requestHandler instanceof HttpRequestHandlerInterface) { return $requestHandler->getHttpRequest(); } try { $baseUri = $this->baseUriProvider->getConfiguredBaseUriOrFallbackToCurrentRequest(); } catch (Exception $e) { $baseUri = 'http://localhost'; } return $this->serverRequestFactory->createServerRequest('GET', $baseUri); } } " "Fix the array object test, since you cant access array data as property Array Data is only accessible via array-access.","<?php /* +--------------------------------------------------------------------------+ | Zephir Language | +--------------------------------------------------------------------------+ | Copyright (c) 2013-2015 Zephir Team and contributors | +--------------------------------------------------------------------------+ | This source file is subject the MIT license, that is bundled with | | this package in the file LICENSE, and is available through the | | world-wide-web at the following url: | | http://zephir-lang.com/license.html | | | | If you did not receive a copy of the MIT license and are unable | | to obtain it through the world-wide-web, please send a note to | | license@zephir-lang.com so we can mail you a copy immediately. | +--------------------------------------------------------------------------+ */ namespace Extension; use Test\ArrayObject; class ArrayObjectTest extends \PHPUnit_Framework_TestCase { public function testSetGet() { $t = new ArrayObject(); $this->assertInstanceOf('\ArrayObject', $t); $t->test_1 = 1; $this->assertEquals(1, $t->test_1); $t['test_2'] = 1; $this->assertEquals(1, $t['test_2']); } } ","<?php /* +--------------------------------------------------------------------------+ | Zephir Language | +--------------------------------------------------------------------------+ | Copyright (c) 2013-2015 Zephir Team and contributors | +--------------------------------------------------------------------------+ | This source file is subject the MIT license, that is bundled with | | this package in the file LICENSE, and is available through the | | world-wide-web at the following url: | | http://zephir-lang.com/license.html | | | | If you did not receive a copy of the MIT license and are unable | | to obtain it through the world-wide-web, please send a note to | | license@zephir-lang.com so we can mail you a copy immediately. | +--------------------------------------------------------------------------+ */ namespace Extension; use Test\ArrayObject; class ArrayObjectTest extends \PHPUnit_Framework_TestCase { public function testSetGet() { $t = new ArrayObject(); $this->assertInstanceOf('\ArrayObject', $t); $t->test_1 = 1; $this->assertEquals(1, $t->test_1); $t[""test_2""] = 1; $this->assertEquals(1, $t->test_2); } } " "Make Google Maps use the coordinates supplied by Wikipedia app Bug: T120275 Change-Id: I7eebb4c2b4e7164cb481ea23831296d4d50a426b","package org.wikipedia.util; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.location.Location; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import org.wikipedia.R; import org.wikipedia.WikipediaApp; import org.wikipedia.feed.announcement.GeoIPCookieUnmarshaller; public final class GeoUtil { public static void sendGeoIntent(@NonNull Activity activity, @NonNull Location location, @Nullable String placeName) { // Using geo:latitude,longitude doesn't give a point on the map, // hence using query String geoStr = ""geo:0,0?q="" + location.getLatitude() + "","" + location.getLongitude(); if (!TextUtils.isEmpty(placeName)) { geoStr += ""("" + Uri.encode(placeName) + "")""; } try { activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(geoStr))); } catch (ActivityNotFoundException e) { FeedbackUtil.showMessage(activity, R.string.error_no_maps_app); } } @Nullable public static String getGeoIPCountry() { try { return GeoIPCookieUnmarshaller.unmarshal(WikipediaApp.getInstance()).country(); } catch (IllegalArgumentException e) { // For our purposes, don't care about malformations in the GeoIP cookie for now. return null; } } private GeoUtil() { } } ","package org.wikipedia.util; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.location.Location; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import org.wikipedia.R; import org.wikipedia.WikipediaApp; import org.wikipedia.feed.announcement.GeoIPCookieUnmarshaller; public final class GeoUtil { public static void sendGeoIntent(@NonNull Activity activity, @NonNull Location location, @Nullable String placeName) { String geoStr = ""geo:""; geoStr += Double.toString(location.getLatitude()) + "","" + Double.toString(location.getLongitude()); if (!TextUtils.isEmpty(placeName)) { geoStr += ""?q="" + Uri.encode(placeName); } try { activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(geoStr))); } catch (ActivityNotFoundException e) { FeedbackUtil.showMessage(activity, R.string.error_no_maps_app); } } @Nullable public static String getGeoIPCountry() { try { return GeoIPCookieUnmarshaller.unmarshal(WikipediaApp.getInstance()).country(); } catch (IllegalArgumentException e) { // For our purposes, don't care about malformations in the GeoIP cookie for now. return null; } } private GeoUtil() { } } " Add log line for susbcription stats email recipients,"const logger = require('logger'); const mailService = require('services/mailService'); const DEFAULT_TEMPLATE = 'forest-change-notification'; const TEMPLATE_MAP = { 'viirs-active-fires': 'forest-fires-notification-viirs', 'imazon-alerts': 'forest-change-imazon-alerts', story: 'stories-alerts', 'forma-alerts': 'forest-change-notification', forma250GFW: 'forest-change-notification', 'terrai-alerts': 'forest-change-notification', 'glad-alerts': 'forest-change-notification-glads', 'monthly-summary': 'monthly-summary', }; class EmailPublisher { static async publish(subscription, results, layer) { logger.info('Publishing email with results', results); let template = TEMPLATE_MAP[layer.slug] || DEFAULT_TEMPLATE; const language = subscription.language.toLowerCase().replace(/_/g, '-'); template = `${template}-${language}`; logger.info('MAIL TEMPLATE', template); const recipients = [{ address: { email: subscription.resource.content } }]; mailService.sendMail(template, results, recipients); } static sendStats(emails, stats) { logger.info('Publishing email with stats', stats); const template = 'subscriptions-stats'; logger.info('MAIL TEMPLATE', template); const recipients = emails.map((el) => ({ address: { email: el } })); logger.info('Subscription stats email recipients', emails); mailService.sendMail(template, stats, recipients); } } module.exports = EmailPublisher; ","const logger = require('logger'); const mailService = require('services/mailService'); const DEFAULT_TEMPLATE = 'forest-change-notification'; const TEMPLATE_MAP = { 'viirs-active-fires': 'forest-fires-notification-viirs', 'imazon-alerts': 'forest-change-imazon-alerts', story: 'stories-alerts', 'forma-alerts': 'forest-change-notification', forma250GFW: 'forest-change-notification', 'terrai-alerts': 'forest-change-notification', 'glad-alerts': 'forest-change-notification-glads', 'monthly-summary': 'monthly-summary', }; class EmailPublisher { static async publish(subscription, results, layer) { logger.info('Publishing email with results', results); let template = TEMPLATE_MAP[layer.slug] || DEFAULT_TEMPLATE; const language = subscription.language.toLowerCase().replace(/_/g, '-'); template = `${template}-${language}`; logger.info('MAIL TEMPLATE', template); const recipients = [{ address: { email: subscription.resource.content } }]; mailService.sendMail(template, results, recipients); } static sendStats(emails, stats) { logger.info('Publishing email with stats', stats); const template = 'subscriptions-stats'; logger.info('MAIL TEMPLATE', template); const recipients = emails.map((el) => ({ address: { email: el } })); mailService.sendMail(template, stats, recipients); } } module.exports = EmailPublisher; " Use tagged service IDs sorter to sort tagged services.,"<?php /** * @author Igor Nikolaev <igor.sv.n@gmail.com> * @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\ConfigBundle\DependencyInjection\Compiler; use Darvin\Utils\DependencyInjection\TaggedServiceIdsSorter; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; /** * Configuration pool compiler pass */ class ConfigurationPoolPass implements CompilerPassInterface { const POOL_ID = 'darvin_config.configuration.pool'; const TAG_CONFIGURATION = 'darvin_config.configuration'; /** * {@inheritdoc} */ public function process(ContainerBuilder $container) { $configurationIds = $container->findTaggedServiceIds(self::TAG_CONFIGURATION); if (empty($configurationIds)) { return; } $taggedServiceIdsSorter = new TaggedServiceIdsSorter(); $taggedServiceIdsSorter->sort($configurationIds); $pool = $container->getDefinition(self::POOL_ID); $poolReference = new Reference(self::POOL_ID); foreach ($configurationIds as $id => $attr) { $configuration = $container->getDefinition($id); $configuration->addMethodCall('setConfigurationPool', array( $poolReference, )); $pool->addMethodCall('add', array( new Reference($id), )); } } } ","<?php /** * @author Igor Nikolaev <igor.sv.n@gmail.com> * @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\ConfigBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; /** * Configuration pool compiler pass */ class ConfigurationPoolPass implements CompilerPassInterface { const POOL_ID = 'darvin_config.configuration.pool'; const TAG_CONFIGURATION = 'darvin_config.configuration'; /** * {@inheritdoc} */ public function process(ContainerBuilder $container) { $configurationIds = $container->findTaggedServiceIds(self::TAG_CONFIGURATION); if (empty($configurationIds)) { return; } $pool = $container->getDefinition(self::POOL_ID); $poolReference = new Reference(self::POOL_ID); foreach ($configurationIds as $id => $attr) { $configuration = $container->getDefinition($id); $configuration->addMethodCall('setConfigurationPool', array( $poolReference, )); $pool->addMethodCall('add', array( new Reference($id), )); } } } " Add action to create folder in root,"define([ ""src/tree"" ], function(Tree) { var hr = codebox.require(""hr/hr""); var menu = codebox.require(""utils/menu""); var dialogs = codebox.require(""utils/dialogs""); var File = codebox.require(""models/file""); var Panel = hr.View.extend({ className: ""component-files-panel"", initialize: function(options) { Panel.__super__.initialize.apply(this, arguments); // Add files tree this.tree = new Tree({ model: codebox.root }); this.tree.appendTo(this); // Context menu menu.add(this.$el, this.getContextMenu.bind(this)); }, render: function() { this.tree.refresh(); return this.ready(); }, // Generate the context menu items getContextMenu: function() { var that = this; var items = [ { label: ""New File"", click: function() { return dialogs.prompt(""Create a new file"", ""untitled"") .then(function(n) { return File.create(""./"", n); }) .then(that.update.bind(that)); } }, { label: ""New Folder"", click: function() { return dialogs.prompt(""Create a new folder"", ""untitled"") .then(function(n) { return File.mkdir(""./"", n); }) .then(that.update.bind(that)); } } ]; return items; }, }); return Panel; });","define([ ""src/tree"" ], function(Tree) { var hr = codebox.require(""hr/hr""); var menu = codebox.require(""utils/menu""); var dialogs = codebox.require(""utils/dialogs""); var File = codebox.require(""models/file""); var Panel = hr.View.extend({ className: ""component-files-panel"", initialize: function(options) { Panel.__super__.initialize.apply(this, arguments); // Add files tree this.tree = new Tree({ model: codebox.root }); this.tree.appendTo(this); // Context menu menu.add(this.$el, this.getContextMenu.bind(this)); }, render: function() { this.tree.refresh(); return this.ready(); }, // Generate the context menu items getContextMenu: function() { var items = [ { label: ""New File"", click: function() { return dialogs.prompt(""Create a new file"", ""untitled"") .then(function(n) { return File.create(""./"", n); }); } }, { label: ""New Folder"", click: function() { } } ]; return items; }, }); return Panel; });" Replace missing function getOrignalMessageSpliter with getAllMessageSpliters in tunderbird email extractor because problem with php7.,"<?php namespace ActiveCollab\EmailReplyExtractor\Extractor; final class ThunderBirdMailExtractor extends Extractor { /** * Extract Reply from ThunderBird mail */ protected function processLines() { $splitters = $this->getAllMessageSplitters(); if (!empty($splitters)) { $this->stripOriginalMessage($splitters); } $this->body = implode(""\n"", $this->body); if (preg_match('/(.*)(On)(.*) wrote\:(.*)/mis', $this->body, $matches, PREG_OFFSET_CAPTURE)) { $match_index = $matches[1][0]; $this->body = trim($match_index); } $this->body = explode(""\n"", $this->body); $unwanted_text_patterns = $this->getUnwantedTextPatterns(); if (!empty($unwanted_text_patterns)) { $this->stripUnwantedText($unwanted_text_patterns); } $this->stripSignature(); $this->convertPlainTextQuotesToBlockquotes(); } /** * Return original message splitters * * @return array */ protected function getAllMessageSplitters() { return array_merge(parent::getAllMessageSplitters(), [ '/\-------------------------/is', ]); } }","<?php namespace ActiveCollab\EmailReplyExtractor\Extractor; final class ThunderBirdMailExtractor extends Extractor { /** * Extract Reply from ThunderBird mail */ protected function processLines() { $splitters = $this->getOriginalMessageSplitters(); if (!empty($splitters)) { $this->stripOriginalMessage($splitters); } $this->body = implode(""\n"", $this->body); if (preg_match('/(.*)(On)(.*) wrote\:(.*)/mis', $this->body, $matches, PREG_OFFSET_CAPTURE)) { $match_index = $matches[1][0]; $this->body = trim($match_index); } $this->body = explode(""\n"", $this->body); $unwanted_text_patterns = $this->getUnwantedTextPatterns(); if (!empty($unwanted_text_patterns)) { $this->stripUnwantedText($unwanted_text_patterns); } $this->stripSignature(); $this->convertPlainTextQuotesToBlockquotes(); } /** * Return original message splitters * * @return array */ protected function getOriginalMessageSplitters() { return array_merge(parent::getOriginalMessageSplitters(), [ '/\-------------------------/is', ]); } }" Add user tools closing by click,"var $ = require('jquery'); require('browsernizr/test/touchevents'); require('browsernizr'); var UserToolsUpdater = function($usertools) { this.$usertools = $usertools; }; UserToolsUpdater.prototype = { updateUserTools: function($usertools) { var $list = $('<ul>'); var user = $usertools.find('strong').first().text(); $('<li>') .addClass('user-tools-welcome-msg') .text(user).appendTo($list) .on('click', function() { if ($(document.documentElement).hasClass('touchevents')) { $list.toggleClass('opened'); } }); $usertools.find('a').each(function() { var $link = $(this); $('<li>').addClass('user-tools-link').html($link).appendTo($list); }); $usertools.empty().addClass('user-tools').append($list); $list.on('mouseenter', function() { $list.addClass('opened'); }).on('mouseleave', function() { $list.removeClass('opened'); }); }, run: function() { try { this.updateUserTools(this.$usertools); } catch (e) { console.error(e); } this.$usertools.addClass('initialized'); } }; $(document).ready(function() { $('#user-tools').each(function() { new UserToolsUpdater($(this)).run(); }); }); ","var $ = require('jquery'); var UserToolsUpdater = function($usertools) { this.$usertools = $usertools; }; UserToolsUpdater.prototype = { updateUserTools: function($usertools) { var $list = $('<ul>'); var user = $usertools.find('strong').first().text(); $('<li>').addClass('user-tools-welcome-msg').text(user).appendTo($list); $usertools.find('a').each(function() { var $link = $(this); $('<li>').addClass('user-tools-link').html($link).appendTo($list); }); $usertools.empty().addClass('user-tools').append($list); $list.on('mouseenter', function() { $list.addClass('opened'); }); $list.on('mouseleave', function() { $list.removeClass('opened'); }); }, run: function() { try { this.updateUserTools(this.$usertools); } catch (e) { console.error(e); } this.$usertools.addClass('initialized'); } }; $(document).ready(function() { $('#user-tools').each(function() { new UserToolsUpdater($(this)).run(); }); }); " Set q_ back to previous on exception in pre-pool block,"/** * @license * Copyright 2019 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ package foam.util.concurrent; import foam.core.Agency; import foam.core.ContextAgent; import foam.core.X; /** * An Aynchronous implementation of the AssemblyLine interface. * Uses the threadpool to avoid blocking the caller. **/ public class AsyncAssemblyLine extends SyncAssemblyLine { protected Agency pool_; protected X x_; public AsyncAssemblyLine(X x) { x_ = x; pool_ = (Agency) x.get(""threadPool""); } public void enqueue(Assembly job) { final Assembly previous; synchronized ( startLock_ ) { try { previous = q_; q_ = job; job.executeUnderLock(); job.startJob(); } catch (Throwable t) { q_ = previous; throw t; } } pool_.submit(x_, new ContextAgent() { public void execute(X x) { try { job.executeJob(); if ( previous != null ) previous.waitToComplete(); synchronized ( endLock_ ) { job.endJob(); job.complete(); } } finally { // Isn't required, but helps GC last entry. synchronized ( startLock_ ) { // If I'm still the only job in the queue, then remove me if ( q_ == job ) q_ = null; } } }}, ""SyncAssemblyLine""); } } ","/** * @license * Copyright 2019 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ package foam.util.concurrent; import foam.core.Agency; import foam.core.ContextAgent; import foam.core.X; /** * An Aynchronous implementation of the AssemblyLine interface. * Uses the threadpool to avoid blocking the caller. **/ public class AsyncAssemblyLine extends SyncAssemblyLine { protected Agency pool_; protected X x_; public AsyncAssemblyLine(X x) { x_ = x; pool_ = (Agency) x.get(""threadPool""); } public void enqueue(Assembly job) { final Assembly previous; synchronized ( startLock_ ) { try { previous = q_; q_ = job; job.executeUnderLock(); job.startJob(); } catch (Throwable t) { q_ = null; throw t; } } pool_.submit(x_, new ContextAgent() { public void execute(X x) { try { job.executeJob(); if ( previous != null ) previous.waitToComplete(); synchronized ( endLock_ ) { job.endJob(); job.complete(); } } finally { // Isn't required, but helps GC last entry. synchronized ( startLock_ ) { // If I'm still the only job in the queue, then remove me if ( q_ == job ) q_ = null; } } }}, ""SyncAssemblyLine""); } } " "Use 'sync' as queue name for Sync Queues, used while logging failed sync jobs when running from within another parent job","<?php namespace Illuminate\Queue\Jobs; use Illuminate\Container\Container; use Illuminate\Contracts\Queue\Job as JobContract; class SyncJob extends Job implements JobContract { /** * The class name of the job. * * @var string */ protected $job; /** * The queue message data. * * @var string */ protected $payload; /** * Create a new job instance. * * @param \Illuminate\Container\Container $container * @param string $payload * @param string $queue * @return void */ public function __construct(Container $container, $payload, $queue) { $this->queue = $queue; $this->payload = $payload; $this->container = $container; } /** * Get the raw body string for the job. * * @return string */ public function getRawBody() { return $this->payload; } /** * Release the job back into the queue. * * @param int $delay * @return void */ public function release($delay = 0) { parent::release($delay); } /** * Get the number of times the job has been attempted. * * @return int */ public function attempts() { return 1; } /** * Get the job identifier. * * @return string */ public function getJobId() { return ''; } /** * Get the name of the queue the job belongs to. * * @return string */ public function getQueue() { return 'sync'; } } ","<?php namespace Illuminate\Queue\Jobs; use Illuminate\Container\Container; use Illuminate\Contracts\Queue\Job as JobContract; class SyncJob extends Job implements JobContract { /** * The class name of the job. * * @var string */ protected $job; /** * The queue message data. * * @var string */ protected $payload; /** * Create a new job instance. * * @param \Illuminate\Container\Container $container * @param string $payload * @param string $queue * @return void */ public function __construct(Container $container, $payload, $queue) { $this->queue = $queue; $this->payload = $payload; $this->container = $container; } /** * Get the raw body string for the job. * * @return string */ public function getRawBody() { return $this->payload; } /** * Release the job back into the queue. * * @param int $delay * @return void */ public function release($delay = 0) { parent::release($delay); } /** * Get the number of times the job has been attempted. * * @return int */ public function attempts() { return 1; } /** * Get the job identifier. * * @return string */ public function getJobId() { return ''; } } " Include player position in `getCurrentState`,"var osa = require('osa2') function play(uri) { if (uri) return playTrack(uri) return osa(() => Application('Spotify').play())() } function playTrack(uri) { return osa((uri) => Application('Spotify').playTrack(uri))(uri) } function pause() { return osa(() => Application('Spotify').pause())() } function toggle() { return osa(() => Application('Spotify').playpause())() } function next() { return osa(() => Application('Spotify').nextTrack())() } function prev() { return osa(() => Application('Spotify').previousTrack())() } function getCurrentTrack() { return osa(() => { var track = Application('Spotify').currentTrack return { id: track.id(), name: track.name(), album: track.album(), artist: track.artist(), duration: track.duration(), artwork: track.artworkUrl(), popularity: track.popularity() } })() } function getPlayerState() { return osa(() => { var s = Application('Spotify') return { state: s.playerState(), volume: s.soundVolume(), position: s.playerPosition(), repeating: s.repeating(), shuffling: s.shuffling(), } })() } module.exports = { play, pause, toggle, next, prev, getCurrentTrack, getPlayerState } ","var osa = require('osa2') function play(uri) { if (uri) return playTrack(uri) return osa(() => Application('Spotify').play())() } function playTrack(uri) { return osa((uri) => Application('Spotify').playTrack(uri))(uri) } function pause() { return osa(() => Application('Spotify').pause())() } function toggle() { return osa(() => Application('Spotify').playpause())() } function next() { return osa(() => Application('Spotify').nextTrack())() } function prev() { return osa(() => Application('Spotify').previousTrack())() } function getCurrentTrack() { return osa(() => { var track = Application('Spotify').currentTrack return { id: track.id(), name: track.name(), album: track.album(), artist: track.artist(), duration: track.duration(), artwork: track.artworkUrl(), popularity: track.popularity() } })() } function getPlayerState() { return osa(() => { var s = Application('Spotify') return { state: s.playerState(), volume: s.soundVolume(), repeating: s.repeating(), shuffling: s.shuffling(), } })() } module.exports = { play, pause, toggle, next, prev, getCurrentTrack, getPlayerState } " Include participant in outgoing ack,"from yowsup.structs import ProtocolEntity, ProtocolTreeNode from .ack import AckProtocolEntity class OutgoingAckProtocolEntity(AckProtocolEntity): ''' <ack type=""{{delivery | read}}"" class=""{{message | receipt | ?}}"" id=""{{MESSAGE_ID}} to={{TO_JID}}""> </ack> <ack to=""{{GROUP_JID}}"" participant=""{{JID}}"" id=""{{MESSAGE_ID}}"" class=""receipt"" type=""{{read | }}""> </ack> ''' def __init__(self, _id, _class, _type, _to, _participant = None): super(OutgoingAckProtocolEntity, self).__init__(_id, _class) self.setOutgoingData(_type, _to, _participant) def setOutgoingData(self, _type, _to, _participant): self._type = _type self._to = _to self._participant = _participant def toProtocolTreeNode(self): node = super(OutgoingAckProtocolEntity, self).toProtocolTreeNode() if self._type: node.setAttribute(""type"", self._type) node.setAttribute(""to"", self._to) if self._participant: node.setAttribute(""participant"", self._participant) return node def __str__(self): out = super(OutgoingAckProtocolEntity, self).__str__() out += ""Type: %s\n"" % self._type out += ""To: %s\n"" % self._to if self._participant: out += ""Participant: %s\n"" % self._participant return out @staticmethod def fromProtocolTreeNode(node): entity = AckProtocolEntity.fromProtocolTreeNode(node) entity.__class__ = OutgoingAckProtocolEntity entity.setOutgoingData( node.getAttributeValue(""type""), node.getAttributeValue(""to""), node.getAttributeValue(""participant"") ) return entity ","from yowsup.structs import ProtocolEntity, ProtocolTreeNode from .ack import AckProtocolEntity class OutgoingAckProtocolEntity(AckProtocolEntity): ''' <ack type=""{{delivery | read}}"" class=""{{message | receipt | ?}}"" id=""{{MESSAGE_ID}} to={{TO_JID}}""> </ack> ''' def __init__(self, _id, _class, _type, _to): super(OutgoingAckProtocolEntity, self).__init__(_id, _class) self.setOutgoingData(_type, _to) def setOutgoingData(self, _type, _to): self._type = _type self._to = _to def toProtocolTreeNode(self): node = super(OutgoingAckProtocolEntity, self).toProtocolTreeNode() if self._type: node.setAttribute(""type"", self._type) node.setAttribute(""to"", self._to) return node def __str__(self): out = super(OutgoingAckProtocolEntity, self).__str__() out += ""Type: %s\n"" % self._type out += ""To: %s\n"" % self._to return out @staticmethod def fromProtocolTreeNode(node): entity = AckProtocolEntity.fromProtocolTreeNode(node) entity.__class__ = OutgoingAckProtocolEntity entity.setOutgoingData( node.getAttributeValue(""type""), node.getAttributeValue(""to"") ) return entity " Fix the loop on the home slider,"var LightSliderHomeInit = function() { // // Init // this.init(); }; LightSliderHomeInit.prototype.init = function() { var that = this; $('[data-slider-home]').lightSlider({ item: 1, slideMargin: 0, pager: false, loop: true, onAfterSlide: function(slider) { var $pages = slider.parents('.slider-home').find('.slider-home__pager li'); $pages.removeClass('active'); $($pages[slider.getCurrentSlideCount()-1]).addClass('active'); }, onSliderLoad: function(slider) { var $pages = slider.parents('.slider-home').find('.slider-home__pager li'); $pages.each(function(idx) { var that = $(this); that.click(function(e) { e.preventDefault(); $pages.removeClass('active'); that.addClass('active'); slider.goToSlide(idx+1); return false; }); }); } }); }; module.exports = LightSliderHomeInit; ","var LightSliderHomeInit = function() { // // Init // this.init(); }; LightSliderHomeInit.prototype.init = function() { var that = this; $('[data-slider-home]').lightSlider({ item: 1, slideMargin: 0, pager: false, loop: true, onAfterSlide: function(slider) { var $pages = slider.parents('.slider-home').find('.slider-home__pager li'); $pages.removeClass('active'); console.log(slider.getCurrentSlideCount()); $($pages[slider.getCurrentSlideCount()-1]).addClass('active'); }, onSliderLoad: function(slider) { var $pages = slider.parents('.slider-home').find('.slider-home__pager li'); $pages.each(function(idx) { var that = $(this); that.click(function(e) { e.preventDefault(); $pages.removeClass('active'); that.addClass('active'); slider.goToSlide(idx); return false; }); }); } }); }; module.exports = LightSliderHomeInit; " Fix default value of object factory defaultAttributes,"<?php namespace Knp\RadBundle\DataFixtures; use Doctrine\Common\DataFixtures\ReferenceRepository; use Doctrine\Common\Persistence\ObjectManager; class ObjectFactory { private $manager; private $className; private $defaultAttributes = array(); public function __construct( ReferenceRepository $referenceRepository, ReferenceManipulator $referenceManipulator, ObjectManager $manager, $className ) { $this->referenceRepository = $referenceRepository; $this->referenceManipulator = $referenceManipulator; $this->manager = $manager; $this->className = $className; } public function add(array $attributes = array()) { // We do not override $attributes because the reference manipulator will use the first element to generate the reference name $mergedAttributes = array_merge($this->defaultAttributes, $attributes); $object = new $this->className(); foreach ($mergedAttributes as $attribute => $value) { $object->{'set'.ucfirst($attribute)}($value); } $this->referenceRepository->addReference( $this->referenceManipulator->createReferenceName($this->className, $attributes), $object ); $this->manager->persist($object); return $this; } public function setDefaults(array $attributes = array()) { $this->defaultAttributes = $attributes; return $this; } } ","<?php namespace Knp\RadBundle\DataFixtures; use Doctrine\Common\DataFixtures\ReferenceRepository; use Doctrine\Common\Persistence\ObjectManager; class ObjectFactory { private $manager; private $className; private $defaultAttributes; public function __construct( ReferenceRepository $referenceRepository, ReferenceManipulator $referenceManipulator, ObjectManager $manager, $className ) { $this->referenceRepository = $referenceRepository; $this->referenceManipulator = $referenceManipulator; $this->manager = $manager; $this->className = $className; } public function add(array $attributes = array()) { // We do not override $attributes because the reference manipulator will use the first element to generate the reference name $mergedAttributes = array_merge($this->defaultAttributes, $attributes); $object = new $this->className(); foreach ($mergedAttributes as $attribute => $value) { $object->{'set'.ucfirst($attribute)}($value); } $this->referenceRepository->addReference( $this->referenceManipulator->createReferenceName($this->className, $attributes), $object ); $this->manager->persist($object); return $this; } public function setDefaults(array $attributes = array()) { $this->defaultAttributes = $attributes; return $this; } } " Increase headers background color opacity,"angular.module('soundmist').directive('player', function (Player) { return { restrict: 'E', scope: false, replace: false, templateUrl: 'directives/player/player.html', link: function (scope, element) { scope.Player = Player let slider = angular.element(document.querySelector('#progress'))[0] let blocking = false scope.$watch('Player.getActive()', function (track) { if (track == undefined) return scope.track = track // Use the high-res artwork instead of the downscaled one provided var url = scope.track.artwork_url if (url) { url = url.replace('large.jpg', 't500x500.jpg') } scope.wallpaper = { 'background': 'linear-gradient(rgba(255, 126, 0, 0.90),rgba(255, 119, 0, 0.95)), url(' + url + ')' } }) scope.$watch('Player.getProgress(track)', function (progress) { if (!blocking) scope.progress = progress * 1000 }) slider.addEventListener('mousedown', event => { blocking = true }) slider.addEventListener('mouseup', function (event) { if (blocking) { let x = event.pageX - this.offsetLeft let progress = x / slider.offsetWidth Player.setProgress(scope.track, progress) blocking = false } }) } } }) ","angular.module('soundmist').directive('player', function (Player) { return { restrict: 'E', scope: false, replace: false, templateUrl: 'directives/player/player.html', link: function (scope, element) { scope.Player = Player let slider = angular.element(document.querySelector('#progress'))[0] let blocking = false scope.$watch('Player.getActive()', function (track) { if (track == undefined) return scope.track = track // Use the high-res artwork instead of the downscaled one provided var url = scope.track.artwork_url if (url) { url = url.replace('large.jpg', 't500x500.jpg') } scope.wallpaper = { 'background': 'linear-gradient(rgba(255, 126, 0, 0.90),rgba(255, 119, 0, 0.75)), url(' + url + ')' } }) scope.$watch('Player.getProgress(track)', function (progress) { if (!blocking) scope.progress = progress * 1000 }) slider.addEventListener('mousedown', event => { blocking = true }) slider.addEventListener('mouseup', function (event) { if (blocking) { let x = event.pageX - this.offsetLeft let progress = x / slider.offsetWidth Player.setProgress(scope.track, progress) blocking = false } }) } } }) " Update to use new configuration methods.,"<?php /** * This file is part of the Miny framework. * (c) Dániel Buga <daniel@bugadani.hu> * * For licensing information see the LICENSE file. */ namespace Modules\ORM; use Miny\Application\BaseApplication; class Module extends \Miny\Modules\Module { public function defaultConfiguration() { return array( 'database_descriptor' => __NAMESPACE__ . '\\DatabaseDiscovery', 'table_name_format' => 'miny_%s' ); } public function init(BaseApplication $app) { $container = $app->getContainer(); $module = $this; $container->addAlias( '\\PDO', __NAMESPACE__ . '\\PDO' ); $container->addAlias( __NAMESPACE__ . '\\PDO', null, array( $this->getConfiguration('pdo:dsn'), $this->getConfiguration('pdo:username'), $this->getConfiguration('pdo:password'), $this->getConfiguration('pdo:options') ) ); $container->addCallback( __NAMESPACE__ . '\\DatabaseDiscovery', function (DatabaseDiscovery $discovery) use ($module) { $discovery->table_format = $module->getConfiguration('table_name_format'); } ); $container->addAlias( __NAMESPACE__ . '\\iDatabaseDescriptor', $module->getConfiguration('database_descriptor') ); } } ","<?php /** * This file is part of the Miny framework. * (c) Dániel Buga <daniel@bugadani.hu> * * For licensing information see the LICENSE file. */ namespace Modules\ORM; use Miny\Application\BaseApplication; class Module extends \Miny\Modules\Module { public function defaultConfiguration() { return array( 'orm' => array( 'database_descriptor' => __NAMESPACE__ . '\\DatabaseDiscovery', 'table_name_format' => 'miny_%s' ) ); } public function init(BaseApplication $app) { $container = $app->getContainer(); $parameters = $app->getParameterContainer(); $container->addAlias( '\\PDO', __NAMESPACE__ . '\\PDO' ); $container->addAlias( __NAMESPACE__ . '\\PDO', null, array( '@orm:pdo:dsn', '@orm:pdo:username', '@orm:pdo:password', '@orm:pdo:options' ) ); $container->addCallback( __NAMESPACE__ . '\\DatabaseDiscovery', function (DatabaseDiscovery $discovery) use ($parameters) { $discovery->table_format = $parameters['orm']['table_name_format']; } ); $container->addAlias(__NAMESPACE__ . '\\iDatabaseDescriptor', $parameters['orm']['database_descriptor']); } } " Add our own error class for invalid arguments,"(function (GoL) { var CT = { Dead: {}, Alive: {} }; function InvalidArgument(message) { this.prototype = Error.prototype; this.name = 'InvalidArgument'; this.message = message; this.toString = function () { return this.name + ': ' + this.message; }; }; function cellSymbolToObject(symbol) { switch (symbol) { case '.': return CT.Dead; case '*': return CT.Alive; default: throw new InvalidArgument('Unknown cell symbol in zero generation: ' + symbol); } } GoL.Support = { CellTypes: CT , parseCanvas: function (canvas) { if (!canvas || !canvas[0] || !canvas[0].getContext) { throw new InvalidArgument(""Not a canvas element""); } return canvas[0]; } , parseCellGrid: function (layout) { var rows = layout.trim().split(""\n"") , grid , gridWidth , gridIsSquare; if (rows.length < 1) { throw new InvalidArgument('Cell grid is too small'); } grid = _.map(rows, function (row) { return _.map(row.split(''), cellSymbolToObject) }); gridWidth = grid.length; gridIsSquare = _.all(grid, function (row) { return row.length === gridWidth }); if (!gridIsSquare) { throw new InvalidArgument('Cell grid is not a square'); } return grid; } }; })(GameOfLife); ","(function (GoL) { var CT = { Dead: {}, Alive: {} }; function cellSymbolToObject(symbol) { switch (symbol) { case '.': return CT.Dead; case '*': return CT.Alive; default: throw new Error('Invalid argument: unknown cell symbol in zero generation: ' + symbol); } } GoL.Support = { CellTypes: CT , parseCanvas: function (canvas) { if (!canvas || !canvas[0] || !canvas[0].getContext) { throw new Error(""Invalid argument: not a canvas element""); } return canvas[0]; } , parseCellGrid: function (layout) { var rows = layout.trim().split(""\n"") , grid , gridWidth , gridIsSquare; if (rows.length < 1) { throw new Error(""Invalid argument: cell grid is too small""); } grid = _.map(rows, function (row) { return _.map(row.split(''), cellSymbolToObject) }); gridWidth = grid.length; gridIsSquare = _.all(grid, function (row) { return row.length === gridWidth }); if (!gridIsSquare) { throw new Error('Invalid argument: cell grid is not a square'); } return grid; } }; })(GameOfLife); " Fix error on new user registration.,"from django import forms from registration.models import RegistrationProfile from registration.forms import RegistrationForm from pykeg.core.models import UserProfile class KegbotRegistrationForm(RegistrationForm): gender = forms.CharField() weight = forms.IntegerField() def save(self, profile_callback=None): new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'], password=self.cleaned_data['password1'], email=self.cleaned_data['email'], send_email=False, profile_callback=profile_callback) new_user.is_active = True new_user.save() new_profile, is_new = UserProfile.objects.get_or_create(user=new_user) new_profile.gender = self.cleaned_data['gender'] new_profile.weight = self.cleaned_data['weight'] new_profile.save() return new_user class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('gender', 'weight') ","from django import forms from registration.models import RegistrationProfile from registration.forms import RegistrationForm from pykeg.core.models import UserProfile class KegbotRegistrationForm(RegistrationForm): gender = forms.CharField() weight = forms.IntegerField() def save(self, profile_callback=None): new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'], password=self.cleaned_data['password1'], email=self.cleaned_data['email'], send_email=False, profile_callback=profile_callback) new_user.is_active = True new_user.save() new_profile = UserProfile.objects.create(user=new_user, gender=self.cleaned_data['gender'], weight=self.cleaned_data['weight']) new_profile.save() return new_user class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('gender', 'weight') " "Add @return to run method Signed-off-by: franckysolo <a6b137401235e3a76c6d3fec9a271303e5d76274@gmail.com>","<?php /** * Unitest (PHP Unit Test) * * @version 1.0.0 * @author franckysolo <franckysolo@gmail.com> */ namespace Unitest; /** * @category PHP Unit Test - Simple Unit Test for PHP * @version 1.0.0 * @author franckysolo <franckysolo@gmail.com> * @license http://creativecommons.org/licenses/by-sa/3.0/ CC BY-SA 3.0 * @package Unitest * @filesource Series.php */ class Series { /** * The array of test cases * * @var array */ protected $cases = array(); /** * * @param array $cases */ public function __construct(array $cases = array()) { $this->cases = $cases; } /** * Run all test cases * * @return Report */ public function run() { $report = new Report(); foreach ($this->cases as $case) { $result = $report->newResult($case); ob_start(); try { $unitest = new $case($result); // Init the test (config) $unitest->init(); // Run it $unitest->run(); } catch (\Exception $e) { $result->setException($e); } $result->setOutput(ob_get_clean()); } return $report; } } ","<?php /** * Unitest (PHP Unit Test) * * @version 1.0.0 * @author franckysolo <franckysolo@gmail.com> */ namespace Unitest; /** * @category PHP Unit Test - Simple Unit Test for PHP * @version 1.0.0 * @author franckysolo <franckysolo@gmail.com> * @license http://creativecommons.org/licenses/by-sa/3.0/ CC BY-SA 3.0 * @package Unitest * @filesource Series.php */ class Series { /** * The array of test cases * * @var array */ protected $cases = array(); /** * * @param array $cases */ public function __construct(array $cases = array()) { $this->cases = $cases; } /** * Run all test cases */ public function run() { $report = new Report(); foreach ($this->cases as $case) { $result = $report->newResult($case); ob_start(); try { $unitest = new $case($result); // Init the test (config) $unitest->init(); // Run it $unitest->run(); } catch (\Exception $e) { $result->setException($e); } $result->setOutput(ob_get_clean()); } return $report; } }" Remove dependency as plugin is configurable,"from setuptools import setup, find_packages __version__ = ""0.0.1"" description = ""A buildout recipe to create .deb packages"" setup( name='vdt.recipe.debian', version=__version__, description=description, long_description=description, classifiers=[ ""Framework :: Buildout"", ""Programming Language :: Python"", ""Programming Language :: Python :: 2.7"", ""Topic :: Software Development :: Libraries :: Python Modules"", ], keywords='', author='Martijn Jacobs', author_email='martijn@devopsconsulting.nl', url='https://github.com/devopsconsulting/vdt.recipe.debian', license='', # include all packages in the egg, except the test package. packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), # for avoiding conflict have one namespace for all apc related eggs. namespace_packages=['vdt', 'vdt.recipe'], # include non python files include_package_data=True, zip_safe=False, # specify dependencies install_requires=[ 'setuptools', 'zc.buildout', ], # mark test target to require extras. extras_require={ 'test': [ ] }, # generate scripts entry_points={ 'console_scripts': ['debianize = vdt.recipe.debian.debianize:debianize'], # noqs 'zc.buildout': ['default = vdt.recipe.debian.config:CreateConfig'] }, ) ","from setuptools import setup, find_packages __version__ = ""0.0.1"" description = ""A buildout recipe to create .deb packages"" setup( name='vdt.recipe.debian', version=__version__, description=description, long_description=description, classifiers=[ ""Framework :: Buildout"", ""Programming Language :: Python"", ""Programming Language :: Python :: 2.7"", ""Topic :: Software Development :: Libraries :: Python Modules"", ], keywords='', author='Martijn Jacobs', author_email='martijn@devopsconsulting.nl', url='https://github.com/devopsconsulting/vdt.recipe.debian', license='', # include all packages in the egg, except the test package. packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), # for avoiding conflict have one namespace for all apc related eggs. namespace_packages=['vdt', 'vdt.recipe'], # include non python files include_package_data=True, zip_safe=False, # specify dependencies install_requires=[ 'setuptools', 'zc.buildout', 'vdt.versionplugin.buildout>=0.0.2' ], # mark test target to require extras. extras_require={ 'test': [ ] }, # generate scripts entry_points={ 'console_scripts': ['debianize = vdt.recipe.debian.debianize:debianize'], # noqs 'zc.buildout': ['default = vdt.recipe.debian.config:CreateConfig'] }, ) " Fix BreadcrumbsView docs that still said DropdownMenuView,"/** * A Backbone view that renders breadcrumbs-type tiered navigation. * * Initialize the view by passing in the following attributes: * *~~~ javascript * var view = new BreadcrumbsView({ * el: $('selector for element that will contain breadcrumbs'), * model: new BreadcrumbsModel({ * breadcrumbs: [{url: '/', title: 'Overview'}] * }), * events: { * 'click nav.breadcrumbs a.nav-item': function (event) { * event.preventDefault(); * window.location = $(event.currentTarget).attr('href'); * } * } * }); *~~~ * @module BreadcrumbsView */ ;(function (define) { 'use strict'; define(['backbone', 'edx-ui-toolkit/js/utils/html-utils', 'text!./breadcrumbs.underscore'], function (Backbone, HtmlUtils, breadcrumbsTemplate) { var BreadcrumbsView = Backbone.View.extend({ initialize: function (options) { this.template = HtmlUtils.template(breadcrumbsTemplate); this.listenTo(this.model, 'change', this.render); this.render(); }, render: function () { var json = this.model.attributes; HtmlUtils.setHtml(this.$el, this.template(json)); return this; } }); return BreadcrumbsView; }); }).call( this, // Use the default 'define' function if available, else use 'RequireJS.define' typeof define === 'function' && define.amd ? define : RequireJS.define ); ","/** * A Backbone view that renders breadcrumbs-type tiered navigation. * * Initialize the view by passing in the following attributes: * *~~~ javascript * var view = new DropdownMenuView({ * el: $('selector for element that will contain breadcrumbs'), * model: new BreadcrumbsModel({ * breadcrumbs: [{url: '/', title: 'Overview'}] * }), * events: { * 'click nav.breadcrumbs a.nav-item': function (event) { * event.preventDefault(); * window.location = $(event.currentTarget).attr('href'); * } * } * }); *~~~ * @module BreadcrumbsView */ ;(function (define) { 'use strict'; define(['backbone', 'edx-ui-toolkit/js/utils/html-utils', 'text!./breadcrumbs.underscore'], function (Backbone, HtmlUtils, breadcrumbsTemplate) { var BreadcrumbsView = Backbone.View.extend({ initialize: function (options) { this.template = HtmlUtils.template(breadcrumbsTemplate); this.listenTo(this.model, 'change', this.render); this.render(); }, render: function () { var json = this.model.attributes; HtmlUtils.setHtml(this.$el, this.template(json)); return this; } }); return BreadcrumbsView; }); }).call( this, // Use the default 'define' function if available, else use 'RequireJS.define' typeof define === 'function' && define.amd ? define : RequireJS.define ); " Use getter to access instance values,"'use strict'; var bcrypt = require('bcrypt'); module.exports = function (sequelize, DataTypes) { var User = sequelize.define('User', { username: { type: DataTypes.STRING, unique: true }, password: DataTypes.STRING, isAdmin: { type: DataTypes.BOOLEAN, defaultValue: 0 } }, { classMethods: { encryptPassword: function (password, next) { var SALT_WORK_FACTOR = 10; bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) { if (err) { throw err; } bcrypt.hash(password, salt, function (err, hash) { if (err) { throw err; } return next(hash); }); }); } }, instanceMethods: { comparePassword: function (candidatePassword, callback) { bcrypt.compare(candidatePassword, this.getDataValue('password'), function (err, isMatch) { if (err) { return callback(err); } callback(null, isMatch); }); } } }); return User; }; ","'use strict'; var bcrypt = require('bcrypt'); module.exports = function (sequelize, DataTypes) { var User = sequelize.define('User', { username: { type: DataTypes.STRING, unique: true }, password: DataTypes.STRING, isAdmin: { type: DataTypes.BOOLEAN, defaultValue: 0 } }, { classMethods: { encryptPassword: function (password, next) { var SALT_WORK_FACTOR = 10; bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) { if (err) { throw err; } bcrypt.hash(password, salt, function (err, hash) { if (err) { throw err; } return next(hash); }); }); } }, instanceMethods: { comparePassword: function (candidatePassword, callback) { bcrypt.compare(candidatePassword, this.password, function (err, isMatch) { if (err) { return callback(err); } callback(null, isMatch); }); } } }); return User; }; " Return setUp and tearDown methods in proper order.,"<?php namespace Laracasts\Integrated; use Laracasts\Integrated\Str; use ReflectionClass; class AnnotationReader { /** * The object to reflect into. * * @var object */ protected $reference; /** * Create a new AnnotationReader instance. * * @param mixed $reference */ public function __construct($reference) { $this->reference = $reference; } /** * Get method names for the referenced object * which contain the given annotation. * * @param string $annotation * @return array */ public function having($annotation) { $methods = []; foreach ($this->reflectInto($this->reference) as $method) { if ($this->hasAnnotation($annotation, $method)) { $methods[] = $method->getName(); } } // We'll reverse the results to ensure that this package's // hooks are called *before* the user's. return array_reverse($methods); } /** * Reflect into the given object. * * @param object $object * @return ReflectionClass */ protected function reflectInto($object) { return (new ReflectionClass($object))->getMethods(); } /** * Search the docblock for the given annotation. * * @param string $annotation * @param \ReflectionMethod $method * @return boolean */ protected function hasAnnotation($annotation, \ReflectionMethod $method) { return Str::contains($method->getDocComment(), ""@{$annotation}""); } } ","<?php namespace Laracasts\Integrated; use Laracasts\Integrated\Str; use ReflectionClass; class AnnotationReader { /** * The object to reflect into. * * @var object */ protected $reference; /** * Create a new AnnotationReader instance. * * @param mixed $reference */ public function __construct($reference) { $this->reference = $reference; } /** * Get method names for the referenced object * which contain the given annotation. * * @param string $annotation * @return array */ public function having($annotation) { $methods = []; foreach ($this->reflectInto($this->reference) as $method) { if ($this->hasAnnotation($annotation, $method)) { $methods[] = $method->getName(); } } return $methods; } /** * Reflect into the given object. * * @param object $object * @return ReflectionClass */ protected function reflectInto($object) { return (new ReflectionClass($object))->getMethods(); } /** * Search the docblock for the given annotation. * * @param string $annotation * @param \ReflectionMethod $method * @return boolean */ protected function hasAnnotation($annotation, \ReflectionMethod $method) { return Str::contains($method->getDocComment(), ""@{$annotation}""); } } " "Fix for browser type checking when undefined or null When a browser called getType on an undefined or null value it returns “DOMWindow” instead of “[object Undefined]” (in some cases at least). Let’s treat undefined and null special and simply return them as “undefined” and “null”, respectively.","msngr.extend((function () { ""use strict""; return { utils: { getType: function (obj) { if (!msngr.utils.exists(obj)) { return """" + obj; } return Object.prototype.toString.call(obj); }, isNullOrUndefined: function (obj) { return (obj === undefined || obj === null); }, exists: function (obj) { return !this.isNullOrUndefined(obj); }, isString: function (str) { return (this.getType(str) === ""[object String]""); }, isDate: function (obj) { return (this.getType(obj) === ""[object Date]""); }, isArray: function (obj) { return (this.getType(obj) === ""[object Array]""); }, isNumber: function (obj) { return (this.getType(obj) === ""[object Number]""); }, isObject: function (obj) { return (this.getType(obj) === ""[object Object]""); }, isFunction: function (func) { return (this.getType(func) === ""[object Function]""); }, isEmptyString: function (str) { var isStr = this.isString(str); if (str === undefined || str === null || (isStr && str.toString().trim().length === 0)) { return true; } return false; }, hasWildCard: function (str) { return (str.indexOf(""*"") !== -1); } } }; }())); ","msngr.extend((function () { ""use strict""; return { utils: { getType: function (obj) { return Object.prototype.toString.call(obj); }, isNullOrUndefined: function (obj) { return (obj === undefined || obj === null); }, exists: function (obj) { return !this.isNullOrUndefined(obj); }, isString: function (str) { return (this.getType(str) === ""[object String]""); }, isDate: function (obj) { return (this.getType(obj) === ""[object Date]""); }, isArray: function (obj) { return (this.getType(obj) === ""[object Array]""); }, isNumber: function (obj) { return (this.getType(obj) === ""[object Number]""); }, isObject: function (obj) { return (this.getType(obj) === ""[object Object]""); }, isFunction: function (func) { return (this.getType(func) === ""[object Function]""); }, isEmptyString: function (str) { var isStr = this.isString(str); if (str === undefined || str === null || (isStr && str.toString().trim().length === 0)) { return true; } return false; }, hasWildCard: function (str) { return (str.indexOf(""*"") !== -1); } } }; }())); " Clear the city autocomplete when unselecting the country in countrycity widget,"$(document).ready(function() { // autocomplete widget javascript initialization for bootstrap=countrycity $('.autocomplete_light_widget[data-bootstrap=countrycity]').each(function() { var country_wrapper = $(this).prev(); var city_wrapper = $(this); function setup() { // get the related country deck var country_deck = country_wrapper.yourlabs_deck(); var country_select = country_deck.valueSelect; if (country_deck.payload.bootstrap == 'remote') { // instanciate a RemoteChannelDeck deck for this city var city_deck = city_wrapper.yourlabs_deck(RemoteChannelDeck); } else { // instanciate a deck for this city var city_deck = city_wrapper.yourlabs_deck(); } // set country_pk in city autocomplete data when a country is selected country_select.bind('change', function() { console.log($(this).val()); if ($(this).val()) { city_deck.autocomplete.innerContainer.html(''); city_deck.autocomplete.data['country__pk'] = $(this).val(); } else { city_deck.autocomplete.data['country_pk'] = ''; city_deck.valueSelect.find('option').remove(); city_deck.valueSelect.val(''); city_deck.deck.html(''); city_deck.updateDisplay(); } }); // set country_pk in city autocomplete data if a country is initially selected if (country_select.val()) city_deck.input.yourlabs_autocomplete().data['country__pk'] = country_select.val(); } // if the country deck is ready: setup the city deck, else wait for country deck to be ready country_wrapper.data('deckready', 0) ? setup() : country_wrapper.bind('deckready', setup); }); }); ","$(document).ready(function() { // autocomplete widget javascript initialization for bootstrap=countrycity $('.autocomplete_light_widget[data-bootstrap=countrycity]').each(function() { var country_wrapper = $(this).prev(); var city_wrapper = $(this); function setup() { // get the related country deck var country_deck = country_wrapper.yourlabs_deck(); var country_select = country_deck.valueSelect; if (country_deck.payload.bootstrap == 'remote') { // instanciate a RemoteChannelDeck deck for this city var city_deck = city_wrapper.yourlabs_deck(RemoteChannelDeck); } else { // instanciate a deck for this city var city_deck = city_wrapper.yourlabs_deck(); } // set country_pk in city autocomplete data when a country is selected country_select.bind('change', function() { city_deck.input.yourlabs_autocomplete().data['country__pk'] = $(this).val(); }); // set country_pk in city autocomplete data if a country is initially selected if (country_select.val()) city_deck.input.yourlabs_autocomplete().data['country__pk'] = country_select.val(); } // if the country deck is ready: setup the city deck, else wait for country deck to be ready country_wrapper.data('deckready', 0) ? setup() : country_wrapper.bind('deckready', setup); }); }); " Fix (Register controller): PHP code should follow PSR-1 basic coding standard,"<?php namespace AppBundle\Controller; use AppBundle\Entity\User; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use AppBundle\Form\Type\RegisterType; class RegistrationController extends Controller { /** * @Route(""/inscription"", name=""registration"") * @Method({""GET"",""POST""}) */ public function registrationAction(Request $request) { // Only for user not logged if($this->getUser()){ return $this->redirectToRoute('homepage'); } $user = new User(); $form = $this->createForm(RegisterType::class, $user); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()){ $wantNewsletter = isset($request->get('register')['newsletter']) ? true : false; $this->container->get('app.user')->create($user, $wantNewsletter); return $this->redirectToRoute('registration'); } return $this->render('registration.html.twig', array( 'form' => $form->createView() )); } /** * @Route(""/inscription/activation/{code}"", name=""registration.activation"", requirements={""code"": ""[a-z0-9]+""}) * @Method({""GET"") */ public function accountActivationAction(Request $request) { } } ","<?php namespace AppBundle\Controller; use AppBundle\Entity\User; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use AppBundle\Form\Type\RegisterType; class RegistrationController extends Controller { /** * @Route(""/inscription"", name=""registration"") * @Method({""GET"",""POST""}) */ public function registrationAction(Request $request) { // Only for user not logged if($this->getUser()){ return $this->redirectToRoute('homepage'); } $user = new User(); $form = $this->createForm(RegisterType::class, $user); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()){ $wantNewsletter = isset($request->get('register')['newsletter']) ? true : false; $this->container->get('app.user')->create($user, $wantNewsletter); //return $this->redirectToRoute('registration'); } return $this->render('registration.html.twig', array( 'form' => $form->createView() )); } /** * @Route(""/inscription/activation/{code}"", name=""registration.activation"", requirements={""code"": ""[a-z0-9]+""}) * @Method({""GET"",""POST""}) */ public function AccountActivationAction(Request $request) { } } " Fix PHPStan level 5 in xcodes package,"<?php declare(strict_types=1); namespace Greenter\Validator; use DOMDocument; use DOMElement; use DOMXPath; /** * Class XmlErrorCodeProvider. */ class XmlErrorCodeProvider implements ErrorCodeProviderInterface { private $xmlErrorFile; /** * XmlErrorCodeProvider constructor. */ public function __construct() { $this->xmlErrorFile = __DIR__.'/../data/CodeErrors.xml'; } /** * Get all codes and messages. * * @return array */ public function getAll(): ?array { $xpath = $this->getXpath(); $nodes = $xpath->query('/errors/error'); $items = []; foreach ($nodes as $node) { /** @var DOMElement $node */ $key = $node->getAttribute('code'); $items[$key] = $node->nodeValue; } return $items; } /** * Get Error Message by code. * * @param string $code * * @return string */ public function getValue(?string $code): ?string { $xpath = $this->getXpath(); $nodes = $xpath->query(""/errors/error[@code='$code']""); if ($nodes->length !== 1) { return ''; } return $nodes[0]->nodeValue; } private function getXpath(): DOMXPath { $doc = new DOMDocument(); $doc->load($this->xmlErrorFile); $xpath = new DOMXPath($doc); return $xpath; } } ","<?php declare(strict_types=1); namespace Greenter\Validator; use DOMDocument; use DOMXPath; /** * Class XmlErrorCodeProvider. */ class XmlErrorCodeProvider implements ErrorCodeProviderInterface { private $xmlErrorFile; /** * XmlErrorCodeProvider constructor. */ public function __construct() { $this->xmlErrorFile = __DIR__.'/../data/CodeErrors.xml'; } /** * Get all codes and messages. * * @return array */ public function getAll(): ?array { $xpath = $this->getXpath(); $nodes = $xpath->query('/errors/error'); $items = []; foreach ($nodes as $node) { /** @var $node \DOMElement */ $key = $node->getAttribute('code'); $items[$key] = $node->nodeValue; } return $items; } /** * Get Error Message by code. * * @param string $code * * @return string */ public function getValue(?string $code): ?string { $xpath = $this->getXpath(); $nodes = $xpath->query(""/errors/error[@code='$code']""); if ($nodes->length !== 1) { return ''; } return $nodes[0]->nodeValue; } private function getXpath(): ?DOMXPath { $doc = new DOMDocument(); $doc->load($this->xmlErrorFile); $xpath = new DOMXPath($doc); return $xpath; } } " Fix a race condition in clearTables,"const mysql = require(""mysql""); const { withPromiseLogging } = require(""../testing/logging""); // Run an array of functions returning Promises sequentially. // Function N+1 will be executed after function N resolves. // Rejects on the first error encountered. const sequencePromises = (promiseFns) => promiseFns.reduce((left, right) => left.then(right), Promise.resolve()); // Execute a single query on a mysql connection. // See https://github.com/mysqljs/mysql for details. const query = withPromiseLogging(""db:query"")( (sqlQuery) => new Promise((resolve, reject) => { const connection = mysql.createConnection({ host: ""db"", user: ""root"", password: ""password"", database: ""test_poradnia"", }); connection.connect((err) => { if (err) { reject(err); } }); connection.query(sqlQuery, (err, results, fields) => { if (err) { reject(err); } else { resolve(results); } }); connection.end(); }) ); // Clear all rows in tables provided. // The function is not aware of relations between tables. // If TableA references TableB, TableA should appear before TableB in the argument. const clearTables = (tables) => { // Create functions that will trigger queries, but do not execute them until scheduled. const lazyDeletes = tables.map((table) => (previousQueryResult) => query(`delete from ${table}`) ); // By convention, cypress plugins mustn't return `undefined`. // `null` is fine. return sequencePromises(lazyDeletes).then(() => null); }; module.exports = { query, clearTables }; ","const mysql = require(""mysql""); const { withPromiseLogging } = require(""../testing/logging""); // Run an array of functions returning Promises sequentially. // Function N+1 will be executed after function N resolves. // Rejects on the first error encountered. const sequencePromises = (promiseFns) => promiseFns.reduce((left, right) => left.then(right), Promise.resolve()); // Execute a single query on a mysql connection. // See https://github.com/mysqljs/mysql for details. const query = withPromiseLogging(""db:query"")( (sqlQuery) => new Promise((resolve, reject) => { const connection = mysql.createConnection({ host: ""db"", user: ""root"", password: ""password"", database: ""test_poradnia"", }); connection.connect((err) => { if (err) { reject(err); } }); connection.query(sqlQuery, (err, results, fields) => { if (err) { reject(err); } else { resolve(results); } }); connection.end(); }) ); // Clear all rows in tables provided. // The function is not aware of relations between tables. // If TableA references TableB, TableA should appear before TableB in the argument. const clearTables = (tables) => sequencePromises(tables.map((table) => query(`delete from ${table}`))).then( () => null ); module.exports = { query, clearTables }; " Fix for findById model method,"<?php /** * This file is part of Vegas package * * @author Slawomir Zytko <slawomir.zytko@gmail.com> * @copyright Amsterdam Standard Sp. Z o.o. * @homepage http://vegas-cmf.github.io * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Vegas\Db\Decorator; use Vegas\Db\Decorator\Helper\MappingHelperTrait; use Vegas\Db\Decorator\Helper\SlugTrait; use Vegas\Db\Decorator\Helper\WriteAttributesTrait; use Vegas\Db\MappingResolverTrait; /** * Class ModelAbstract * @package Vegas\Db\Decorator */ abstract class ModelAbstract extends \Phalcon\Mvc\Model { use MappingResolverTrait; use MappingHelperTrait; use SlugTrait; use WriteAttributesTrait; /** * Event fired when record is being created */ public function beforeCreate() { $this->created_at = time(); } /** * Event fired when record is being updated */ public function beforeUpdate() { $this->updated_at = time(); } /** * Finds record by its ID * * @param $id * @return \Phalcon\Mvc\Model\ResultsetInterface */ public function findById($id) { return parent::findFirst(array( ""conditions"" => ""id = ?1"", ""bind"" => array(1 => $id) )); } }","<?php /** * This file is part of Vegas package * * @author Slawomir Zytko <slawomir.zytko@gmail.com> * @copyright Amsterdam Standard Sp. Z o.o. * @homepage http://vegas-cmf.github.io * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Vegas\Db\Decorator; use Vegas\Db\Decorator\Helper\MappingHelperTrait; use Vegas\Db\Decorator\Helper\SlugTrait; use Vegas\Db\Decorator\Helper\WriteAttributesTrait; use Vegas\Db\MappingResolverTrait; /** * Class ModelAbstract * @package Vegas\Db\Decorator */ abstract class ModelAbstract extends \Phalcon\Mvc\Model { use MappingResolverTrait; use MappingHelperTrait; use SlugTrait; use WriteAttributesTrait; /** * Event fired when record is being created */ public function beforeCreate() { $this->created_at = time(); } /** * Event fired when record is being updated */ public function beforeUpdate() { $this->updated_at = time(); } /** * Finds record by its ID * * @param $id * @return \Phalcon\Mvc\Model\ResultsetInterface */ public function findById($id) { return parent::find(array( ""conditions"" => ""id = ?1"", ""bind"" => array(1 => $id) )); } }" "Allow hostnames to be used as ip_address Previously introduced change for monasca-persister had enforced the IPAddress as the only type one can configure influxdb.ip_address property with. Following change makes it possible to use also hostname. Using IPAdress is still possible. Change-Id: Ib0d7f19b3ac2dcb7c84923872d94f180cda58b2b","# (C) Copyright 2016-2017 Hewlett Packard Enterprise Development LP # Copyright 2017 FUJITSU LIMITED # # 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. from oslo_config import cfg influxdb_opts = [ cfg.StrOpt('database_name', help='database name where metrics are stored', default='mon'), cfg.HostAddressOpt('ip_address', help='Valid IP address or hostname ' 'to InfluxDB instance'), cfg.PortOpt('port', help='port to influxdb', default=8086), cfg.StrOpt('user', help='influxdb user ', default='mon_persister'), cfg.StrOpt('password', secret=True, help='influxdb password')] influxdb_group = cfg.OptGroup(name='influxdb', title='influxdb') def register_opts(conf): conf.register_group(influxdb_group) conf.register_opts(influxdb_opts, influxdb_group) def list_opts(): return influxdb_group, influxdb_opts ","# (C) Copyright 2016-2017 Hewlett Packard Enterprise Development LP # Copyright 2017 FUJITSU LIMITED # # 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. from oslo_config import cfg influxdb_opts = [ cfg.StrOpt('database_name', help='database name where metrics are stored', default='mon'), cfg.IPOpt('ip_address', help='ip address to influxdb'), cfg.PortOpt('port', help='port to influxdb', default=8086), cfg.StrOpt('user', help='influxdb user ', default='mon_persister'), cfg.StrOpt('password', secret=True, help='influxdb password')] influxdb_group = cfg.OptGroup(name='influxdb', title='influxdb') def register_opts(conf): conf.register_group(influxdb_group) conf.register_opts(influxdb_opts, influxdb_group) def list_opts(): return influxdb_group, influxdb_opts " "Remove unnecessary code from autloader Removed unnecessary code.","<?php /** * @file * @version 0.1 * @copyright 2017 CN-Consult GmbH * @author Yannick Lapp <yannick.lapp@cn-consult.eu> */ /** * Class Psr4Autoloader */ class Psr4Autoloader { private $prefixes = array(); /** * register all prefixes that are saved in the object */ public function register() { spl_autoload_register( function ($_class) { foreach ($this->prefixes as $prefix=>$baseDirectory) { // check whether class uses one of the namespace prefixes $len = strlen($prefix); if (strncmp($prefix, $_class, $len) === 0) { $relativeClass = substr($_class, $len); $file = $baseDirectory . str_replace('\\', '/', $relativeClass) . '.php'; if (file_exists($file)) require_once $file; } } } ); } /** * add a namespace to the list * * @param string $_prefix namespace prefix * @param string $_baseDir filepath prefix */ public function addNamespace($_prefix, $_baseDir) { if (isset($this->prefixes[$_prefix]) === false) { $this->prefixes[$_prefix] = $_baseDir; } } }","<?php /** * @file * @version 0.1 * @copyright 2017 CN-Consult GmbH * @author Yannick Lapp <yannick.lapp@cn-consult.eu> */ /** * Class Psr4Autoloader */ class Psr4Autoloader { private $prefixes = array(); /** * register all prefixes that are saved in the object */ public function register() { spl_autoload_register( function ($_class) { foreach ($this->prefixes as $prefix=>$baseDirectory) { // check whether class uses the namespace prefix $len = strlen($prefix); if (strncmp($prefix, $_class, $len) === 0) { $relativeClass = substr($_class, $len); $file = $baseDirectory . str_replace('\\', '/', $relativeClass) . '.php'; if (file_exists($file)) { require_once $file; } } } } ); } /** * add a namespace to the list * * @param string $_prefix namespace prefix * @param string $_baseDir filepath prefix */ public function addNamespace($_prefix, $_baseDir) { // initialize the namespace prefix array if (isset($this->prefixes[$_prefix]) === false) { $this->prefixes[$_prefix] = array(); } $this->prefixes[$_prefix] = $_baseDir; } }" Comment out @bubil 's menu-bar removal,"AV.VisualizationView = Backbone.View.extend({ el: '#visualization', // The rendering of the visualization will be slightly // different here, because there is no templating necessary: // The server gives back a page. render: function() { this.model.url = this.model.urlRoot + this.model.id + '/view?mode=heatmap&condensed=true'; var response = $.ajax({ url: this.model.url, type: ""GET"" }).done(_.bind(function(d) { //If the server returns an HTML document if (d[0] != 'R') { return d; } else { //Rendering setTimeout(function(){}, 1000); return this.render(); } }, this)); this.$el.attr('src', this.model.url).load(_.bind(function() { var iframe = this.$el.contents(); // iframe.find('.menubar').remove(); // iframe.find('.title-bar').remove(); }, this)); $('#basicModal').modal({ show: true }); } }); ","AV.VisualizationView = Backbone.View.extend({ el: '#visualization', // The rendering of the visualization will be slightly // different here, because there is no templating necessary: // The server gives back a page. render: function() { this.model.url = this.model.urlRoot + this.model.id + '/view?mode=heatmap&condensed=true'; var response = $.ajax({ url: this.model.url, type: ""GET"" }).done(_.bind(function(d) { console.log(d[0]); //If the server returns an HTML document if (d[0] != 'R') { return d; } else { //Rendering console.log(""Yo dawg, I heard you like recursion, so I put"" + "" recursion in your recursion so you can recur"" + "" while you recur""); setTimeout(function(){}, 1000); return this.render(); } }, this)); this.$el.attr('src', this.model.url).load(_.bind(function() { var iframe = this.$el.contents(); iframe.find('.menubar').remove(); iframe.find('.title-bar').remove(); }, this)); $('#basicModal').modal({ show: true }); } }); " Fix some urllib3 import issues,""""""" Resolves OpenSSL issues in some servers: https://lukasa.co.uk/2013/01/Choosing_SSL_Version_In_Requests/ https://github.com/kennethreitz/requests/pull/799 """""" from distutils.version import StrictVersion from requests.adapters import HTTPAdapter try: import requests.packages.urllib3 as urllib3 except ImportError: import urllib3 PoolManager = urllib3.poolmanager.PoolManager class SSLAdapter(HTTPAdapter): '''An HTTPS Transport Adapter that uses an arbitrary SSL version.''' def __init__(self, ssl_version=None, **kwargs): self.ssl_version = ssl_version super(SSLAdapter, self).__init__(**kwargs) def init_poolmanager(self, connections, maxsize, block=False): urllib_ver = urllib3.__version__.split('-')[0] if urllib3 and urllib_ver != 'dev' and \ StrictVersion(urllib_ver) <= StrictVersion('1.5'): self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block) else: self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, ssl_version=self.ssl_version) ",""""""" Resolves OpenSSL issues in some servers: https://lukasa.co.uk/2013/01/Choosing_SSL_Version_In_Requests/ https://github.com/kennethreitz/requests/pull/799 """""" from distutils.version import StrictVersion from requests.adapters import HTTPAdapter try: from requests.packages.urllib3.poolmanager import PoolManager except ImportError: import urllib3 from urllib3.poolmanager import PoolManager class SSLAdapter(HTTPAdapter): '''An HTTPS Transport Adapter that uses an arbitrary SSL version.''' def __init__(self, ssl_version=None, **kwargs): self.ssl_version = ssl_version super(SSLAdapter, self).__init__(**kwargs) def init_poolmanager(self, connections, maxsize, block=False): urllib_ver = urllib3.__version__ if urllib3 and StrictVersion(urllib_ver) <= StrictVersion('1.5'): self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block) else: self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, ssl_version=self.ssl_version) " Use toString() to print the error coming from the API request,"'use strict'; var request = require('request'); function removeEmptyItemFilter(item) { return item.length > 0; } function tasksFromTextToObject(text) { return text .replace(/([ \t]+)/gm, ' ') // Remove duplicate spaces .split('\n') // Create an array with the tasks .filter(removeEmptyItemFilter) // Remove empty element .map(function (line) { // Each task must be an object var fields = line.split(' '); return { name: fields[0], // The first element is the name of the app port: parseInt(fields[1], 10), // The second element is the port to use endpoints: fields.slice(2) // The following elements are the endpoints .filter(removeEmptyItemFilter) }; }); } function Marathon(marathonUrl) { this._marathonUrl = marathonUrl; return this; } Marathon.prototype.getTasks = function (callback) { function onResponse(error, response, body) { if (error) { return callback(new Error('Unable to get the tasks using the Marathon ' + 'API. ' + error.toString())); } var tasks = tasksFromTextToObject(body); return callback(null, tasks); } var options = { url: this._marathonUrl + '/v2/tasks', headers: { 'Accept': 'text/plain' } }; request.get(options, onResponse); }; module.exports = Marathon; ","'use strict'; var request = require('request'); function removeEmptyItemFilter(item) { return item.length > 0; } function tasksFromTextToObject(text) { return text .replace(/([ \t]+)/gm, ' ') // Remove duplicate spaces .split('\n') // Create an array with the tasks .filter(removeEmptyItemFilter) // Remove empty element .map(function (line) { // Each task must be an object var fields = line.split(' '); return { name: fields[0], // The first element is the name of the app port: parseInt(fields[1], 10), // The second element is the port to use endpoints: fields.slice(2) // The following elements are the endpoints .filter(removeEmptyItemFilter) }; }); } function Marathon(marathonUrl) { this._marathonUrl = marathonUrl; return this; } Marathon.prototype.getTasks = function (callback) { function onResponse(error, response, body) { if (error) { return callback(new Error('Unable to get the tasks using the Marathon ' + 'API. Error: ' + error.message)); } var tasks = tasksFromTextToObject(body); return callback(null, tasks); } var options = { url: this._marathonUrl + '/v2/tasks', headers: { 'Accept': 'text/plain' } }; request.get(options, onResponse); }; module.exports = Marathon; " Fix wrong type for debug,"<?php namespace App; use Matthias\SymfonyConsoleForm\Bundle\SymfonyConsoleFormBundle; use Symfony\Bundle\FrameworkBundle\FrameworkBundle; use Symfony\Bundle\TwigBundle\TwigBundle; use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpKernel\Kernel as SymfonyKernel; class Kernel extends SymfonyKernel { /** @var string */ private $vendorDirectory; public function __construct(string $environment, bool $debug, string $vendorDirectory) { parent::__construct($environment, $debug); $this->vendorDirectory = $vendorDirectory; } public function registerBundles(): array { return [ new FrameworkBundle(), new TwigBundle(), new SymfonyConsoleFormBundle(), ]; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__ . '/config.yml'); } public function getCacheDir(): string { return __DIR__ . '/cache'; } public function getLogDir(): string { return __DIR__ . '/logs'; } protected function buildContainer(): ContainerInterface { $container = parent::buildContainer(); $container->setParameter('vendor_directory', $this->vendorDirectory); return $container; } } ","<?php namespace App; use Matthias\SymfonyConsoleForm\Bundle\SymfonyConsoleFormBundle; use Symfony\Bundle\FrameworkBundle\FrameworkBundle; use Symfony\Bundle\TwigBundle\TwigBundle; use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpKernel\Kernel as SymfonyKernel; class Kernel extends SymfonyKernel { /** @var string */ private $vendorDirectory; public function __construct(string $environment, string $debug, string $vendorDirectory) { parent::__construct($environment, $debug); $this->vendorDirectory = $vendorDirectory; } public function registerBundles(): array { return [ new FrameworkBundle(), new TwigBundle(), new SymfonyConsoleFormBundle(), ]; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__ . '/config.yml'); } public function getCacheDir(): string { return __DIR__ . '/cache'; } public function getLogDir(): string { return __DIR__ . '/logs'; } protected function buildContainer(): ContainerInterface { $container = parent::buildContainer(); $container->setParameter('vendor_directory', $this->vendorDirectory); return $container; } } " Use usubscribe rather than popping the broadcaster,"import json import tornadoredis.pubsub import tornadoredis from .base_provider import BaseProvider class RedisSubProvider(BaseProvider): def __init__(self): self._subscriber = tornadoredis.pubsub.SockJSSubscriber(tornadoredis.Client()) def close(self, broadcaster): for channel in self._subscriber.subscribers: if broadcaster in self._subscriber.subscribers[channel]: self._subscriber.unsubscribe(channel, broadcaster) def get_channel(self, base_channel, **channel_filter): return self._construct_channel(base_channel, **channel_filter) def subscribe(self, channels, broadcaster): self._subscriber.subscribe(channels, broadcaster) def unsubscribe(self, channels, broadcaster): for channel in channels: if broadcaster in self._subscriber.subscribers[channel]: self._subscriber.subscribers[channel].pop(broadcaster) def publish(self, channel, data): if isinstance(data, dict): data = json.dumps(data) broadcasters = list(self._subscriber.subscribers[channel].keys()) if broadcasters: for bc in broadcasters: if not bc.session.is_closed: bc.broadcast(broadcasters, data) break ","import json import tornadoredis.pubsub import tornadoredis from .base_provider import BaseProvider class RedisSubProvider(BaseProvider): def __init__(self): self._subscriber = tornadoredis.pubsub.SockJSSubscriber(tornadoredis.Client()) def close(self, broadcaster): for channel in self._subscriber.subscribers: if broadcaster in self._subscriber.subscribers[channel]: self._subscriber.subscribers[channel].pop(broadcaster) def get_channel(self, base_channel, **channel_filter): return self._construct_channel(base_channel, **channel_filter) def subscribe(self, channels, broadcaster): self._subscriber.subscribe(channels, broadcaster) def unsubscribe(self, channels, broadcaster): for channel in channels: if broadcaster in self._subscriber.subscribers[channel]: self._subscriber.subscribers[channel].pop(broadcaster) def publish(self, channel, data): if isinstance(data, dict): data = json.dumps(data) broadcasters = list(self._subscriber.subscribers[channel].keys()) if broadcasters: for bc in broadcasters: if not bc.session.is_closed: bc.broadcast(broadcasters, data) break " Return a dictionary for transcription/translation services (instead of list),"# coding: utf-8 from collections import defaultdict, OrderedDict from django.db import models from rest_framework import serializers class BaseServiceSerializer(serializers.ModelSerializer): class Meta: fields = [ 'name', 'code', ] class BaseServiceLanguageM2MSerializer(serializers.ModelSerializer): region = serializers.SerializerMethodField() service = serializers.SerializerMethodField() language = serializers.SerializerMethodField() class Meta: fields = '__all__' def get_list_serializer_class(self): pass def get_region(self, through_instance): if through_instance.region: return through_instance.region.code return None def get_service(self, through_instance): return through_instance.service.code def get_language(self, through_instance): return through_instance.language.code class BaseServiceLanguageM2MListSerializer(serializers.ListSerializer): # Force `ListSerializer` to return a dict, not a list @property def data(self): ret = serializers.BaseSerializer.data.fget(self) return serializers.ReturnDict(ret, serializer=self) def to_representation(self, data): """""" Override `ListSerializer` behaviour to display services as a dictionary instead of a list """""" iterable = data.all() if isinstance(data, models.Manager) else data formatted_data = self._get_formatted_data(iterable) return formatted_data ","# coding: utf-8 from collections import defaultdict, OrderedDict from django.db import models from rest_framework import serializers class BaseServiceSerializer(serializers.ModelSerializer): class Meta: fields = [ 'name', 'code', ] class BaseServiceLanguageM2MSerializer(serializers.ModelSerializer): region = serializers.SerializerMethodField() service = serializers.SerializerMethodField() language = serializers.SerializerMethodField() class Meta: fields = '__all__' def get_list_serializer_class(self): pass def get_region(self, through_instance): if through_instance.region: return through_instance.region.code return None def get_service(self, through_instance): return through_instance.service.code def get_language(self, through_instance): return through_instance.language.code class BaseServiceLanguageM2MListSerializer(serializers.ListSerializer): def to_representation(self, data): """""" Override `ListSerializer` behaviour to display services as a dictionary instead of a list """""" iterable = data.all() if isinstance(data, models.Manager) else data formatted_data = self._get_formatted_data(iterable) representation = [] for service_code, service in formatted_data.items(): representation.append({service_code: service}) return representation " Update includes; set encoding for file.,"# -*- coding: utf-8 -*- import csv import collections import sys import re import os import binascii def parameters_from_args(defaults_tuple=None, sys_args): """"""Provided a set of tuples for default values, return a list of mapped variables."""""" defaults = collections.OrderedDict(defaults_tuple) if defaults_tuple is not None: args = len(sys_args) - 1 for i, key in enumerate(defaults.keys()): idx = i + 1 if idx <= args: defaults[key] = sys_args[idx] return defaults def msg(output_msg, mtype='message', exception=None): if mtype == 'error': arcpy_messages = arcpy.GetMessages() tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] if config.mode == 'script': if exception: # print the raw exception print exception # Arcpy and Python stuff, hopefully also helpful err_msg = ""ArcPy Error: {msg_text}\nPython Error: ${tbinfo}"".format( msg_text=arcpy_messages, tbinfo=tbinfo) else: arcpy.AddMessage(output_msg) if exception: arcpy.AddError(exception) arcpy.AddError(arcpy_messages) arcpy.AddMessage(""Python Error: ${tbinfo}"".format(tbinfo=tbinfo)) elif config.mode == 'script': print output_msg else: if mtype == 'message': arcpy.AddMessage(output_msg) elif mtype == 'warning': arcpy.AddWarning(output_msg) ","import sys import collections def parameters_from_args(defaults_tuple=None, sys_args): """"""Provided a set of tuples for default values, return a list of mapped variables."""""" defaults = collections.OrderedDict(defaults_tuple) if defaults_tuple is not None: args = len(sys_args) - 1 for i, key in enumerate(defaults.keys()): idx = i + 1 if idx <= args: defaults[key] = sys_args[idx] return defaults def msg(output_msg, mtype='message', exception=None): if mtype == 'error': arcpy_messages = arcpy.GetMessages() tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] if config.mode == 'script': if exception: # print the raw exception print exception # Arcpy and Python stuff, hopefully also helpful err_msg = ""ArcPy Error: {msg_text}\nPython Error: ${tbinfo}"".format( msg_text=arcpy_messages, tbinfo=tbinfo) else: arcpy.AddMessage(output_msg) if exception: arcpy.AddError(exception) arcpy.AddError(arcpy_messages) arcpy.AddMessage(""Python Error: ${tbinfo}"".format(tbinfo=tbinfo)) elif config.mode == 'script': print output_msg else: if mtype == 'message': arcpy.AddMessage(output_msg) elif mtype == 'warning': arcpy.AddWarning(output_msg) " "Bump tensorflow from 2.5.1 to 2.5.2 Bumps [tensorflow](https://github.com/tensorflow/tensorflow) from 2.5.1 to 2.5.2. - [Release notes](https://github.com/tensorflow/tensorflow/releases) - [Changelog](https://github.com/tensorflow/tensorflow/blob/master/RELEASE.md) - [Commits](https://github.com/tensorflow/tensorflow/compare/v2.5.1...v2.5.2) --- updated-dependencies: - dependency-name: tensorflow dependency-type: direct:production ... Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@github.com>","import setuptools setuptools.setup( python_requires='<3.8', entry_points={ ""console_scripts"": [ ""microscopeimagequality=microscopeimagequality.application:command"" ] }, install_requires=[ ""click"", ""matplotlib"", ""nose"", ""numpy<1.19.0,>=1.16.0"", ""Pillow"", ""scikit-image"", ""scipy"", ""six"", ""tensorflow==2.5.2"", ""imagecodecs"", ], test_requires=[""pytest""], name=""microscopeimagequality"", package_data={ ""microscopeimagequality"": [ ""data/"" ] }, classifiers=[ 'License :: OSI Approved :: Apache Software License', 'Intended Audience :: Science/Research', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering'], description=""Microscope Image Quality Classification"", url='https://github.com/google/microscopeimagequality', author='Samuel Yang', author_email='samuely@google.com', license='Apache 2.0', packages=setuptools.find_packages( exclude=[ ""tests"" ] ), version=""0.1.0dev5"" ) ","import setuptools setuptools.setup( python_requires='<3.8', entry_points={ ""console_scripts"": [ ""microscopeimagequality=microscopeimagequality.application:command"" ] }, install_requires=[ ""click"", ""matplotlib"", ""nose"", ""numpy<1.19.0,>=1.16.0"", ""Pillow"", ""scikit-image"", ""scipy"", ""six"", ""tensorflow==2.5.1"", ""imagecodecs"", ], test_requires=[""pytest""], name=""microscopeimagequality"", package_data={ ""microscopeimagequality"": [ ""data/"" ] }, classifiers=[ 'License :: OSI Approved :: Apache Software License', 'Intended Audience :: Science/Research', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering'], description=""Microscope Image Quality Classification"", url='https://github.com/google/microscopeimagequality', author='Samuel Yang', author_email='samuely@google.com', license='Apache 2.0', packages=setuptools.find_packages( exclude=[ ""tests"" ] ), version=""0.1.0dev5"" ) " Bump version (0.6 -> 0.7),"from setuptools import setup entry_points = { 'console_scripts': [ 'whatportis=whatportis.cli:run', ] } readme = open('README.rst').read() setup( name=""whatportis"", version=""0.7"", url='http://github.com/ncrocfer/whatportis', author='Nicolas Crocfer', author_email='ncrocfer@gmail.com', description=""A command to search port names and numbers"", long_description=readme, packages=['whatportis'], include_package_data=True, install_requires=[ ""simplejson"", ""tinydb"", ""requests"", ""prettytable"", ""click"" ], extras_require={ ""dev"": [ ""pytest"", ""tox"" ], ""server"": [ ""flask"" ] }, entry_points=entry_points, classifiers=( 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Natural Language :: English', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4' ), ) ","from setuptools import setup entry_points = { 'console_scripts': [ 'whatportis=whatportis.cli:run', ] } readme = open('README.rst').read() setup( name=""whatportis"", version=""0.6"", url='http://github.com/ncrocfer/whatportis', author='Nicolas Crocfer', author_email='ncrocfer@gmail.com', description=""A command to search port names and numbers"", long_description=readme, packages=['whatportis'], include_package_data=True, install_requires=[ ""simplejson"", ""tinydb"", ""requests"", ""prettytable"", ""click"" ], extras_require={ ""dev"": [ ""pytest"", ""tox"" ], ""server"": [ ""flask"" ] }, entry_points=entry_points, classifiers=( 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Natural Language :: English', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4' ), ) " "Use config to cache from composer.json Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>","<?php namespace Orchestra\Config\Console; use Symfony\Component\Finder\Finder; use Illuminate\Contracts\Console\Kernel; use Illuminate\Foundation\Console\ConfigCacheCommand as BaseCommand; class ConfigCacheCommand extends BaseCommand { /** * Boot a fresh copy of the application configuration. * * @return array */ protected function getFreshConfiguration() { $app = require $this->laravel->bootstrapPath('app.php'); $app->make(Kernel::class)->bootstrap(); $config = $app->make('config'); $files = \array_merge( $this->configToCache(), $this->getConfigurationFiles() ); foreach ($files as $file) { $config[$file]; } return $config->all(); } /** * Get all of the configuration files for the application. * * @return array */ protected function getConfigurationFiles() { $files = []; $path = $this->laravel->configPath(); $found = Finder::create()->files()->name('*.php')->depth('== 0')->in($path); foreach ($found as $file) { $files[] = \basename($file->getRealPath(), '.php'); } return $files; } /** * Get all of the package names that should be ignored. * * @return array */ protected function configToCache() { if (! file_exists($this->laravel->basePath('composer.json')) { return []; } return json_decode(file_get_contents( $this->laravel->basePath('composer.json') ), true)['extra']['config-cache'] ?? []; } } ","<?php namespace Orchestra\Config\Console; use Symfony\Component\Finder\Finder; use Illuminate\Contracts\Console\Kernel; use Illuminate\Foundation\Console\ConfigCacheCommand as BaseCommand; class ConfigCacheCommand extends BaseCommand { /** * Boot a fresh copy of the application configuration. * * @return array */ protected function getFreshConfiguration() { $app = require $this->laravel->basePath().'/bootstrap/app.php'; $app->make(Kernel::class)->bootstrap(); $config = $app->make('config'); $files = \array_merge( $config->get('compile.config', []), $this->getConfigurationFiles() ); foreach ($files as $file) { $config[$file]; } return $config->all(); } /** * Get all of the configuration files for the application. * * @return array */ protected function getConfigurationFiles() { $files = []; $path = $this->laravel->configPath(); $found = Finder::create()->files()->name('*.php')->depth('== 0')->in($path); foreach ($found as $file) { $files[] = \basename($file->getRealPath(), '.php'); } return $files; } } " "Fix keycloak auth filter not excluded all websocket request Signed-off-by: Sun Seng David Tan <a9f1581903e4bd3aaa1590f4fc9da1fa6887498b@redhat.com>","package com.redhat.che.keycloak.server; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class KeycloakAuthenticationFilter extends org.keycloak.adapters.servlet.KeycloakOIDCFilter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; String auth = request.getHeader(""Authorization""); if(auth == null ){ System.out.println(""No auth header for "" + request.getRequestURI()); } if(auth != null && auth.equals(""Internal"")){ chain.doFilter(req, res); } else if (request.getRequestURI().endsWith(""/ws"") || request.getRequestURI().endsWith(""/eventbus"") || request.getScheme().equals(""ws"") || req.getScheme().equals(""wss"") || request.getRequestURI().contains(""/websocket/"")) { System.out.println(""Skipping "" + request.getRequestURI()); chain.doFilter(req, res); } else { super.doFilter(req, res, chain); System.out.println(request.getRequestURL() + "" status : "" + ((HttpServletResponse) res).getStatus()); } } }","package com.redhat.che.keycloak.server; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class KeycloakAuthenticationFilter extends org.keycloak.adapters.servlet.KeycloakOIDCFilter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; String auth = request.getHeader(""Authorization""); if(auth == null ){ System.out.println(""No auth header for "" + request.getRequestURI()); } if(auth != null && auth.equals(""Internal"")){ chain.doFilter(req, res); }else if (request.getRequestURI().endsWith(""/ws"") || request.getRequestURI().endsWith(""/eventbus"") || request.getScheme().equals(""ws"") || req.getScheme().equals(""wss"")) { System.out.println(""Skipping "" + request.getRequestURI()); chain.doFilter(req, res); } else { super.doFilter(req, res, chain); System.out.println(request.getRequestURL() + "" status : "" + ((HttpServletResponse) res).getStatus()); } } }" Fix links in tags page,"import React from 'react'; import PropTypes from 'proptypes'; import graphql from 'graphql'; import Link from '../components/Link'; class TagRoute extends React.Component { static propTypes = { data: PropTypes.object, pathContext: PropTypes.object } render() { const posts = this.props.data.allMarkdownRemark.edges; const postLinks = posts.map(post => { return ( <li key={post.node.fields.path}> <Link to={post.node.fields.path}> {post.node.frontmatter.title} </Link> </li> ); }); return ( <div> <h2> {this.props.data.allMarkdownRemark.totalCount} posts tagged with “{this.props.pathContext.tag}” </h2> <ul> {postLinks} </ul> <p> <Link to=""/tags/"">Browse all tags</Link> </p> </div> ); } } export default TagRoute; export const pageQuery = graphql` query TagPage($tag: String) { allMarkdownRemark( limit: 1000 sort: { fields: [frontmatter___date], order: DESC } filter: { frontmatter: { tags: { in: [$tag] }, draft: { ne: true } } } ) { totalCount edges { node { fields { path } frontmatter { title } } } } } `; ","import React from 'react'; import PropTypes from 'proptypes'; import graphql from 'graphql'; import Link from '../components/Link'; class TagRoute extends React.Component { static propTypes = { data: PropTypes.object, pathContext: PropTypes.object } render() { const posts = this.props.data.allMarkdownRemark.edges; const postLinks = posts.map(post => { return ( <li key={post.node.fields.slug}> <Link to={post.node.fields.slug}> {post.node.frontmatter.title} </Link> </li> ); }); return ( <div> <h2> {this.props.data.allMarkdownRemark.totalCount} posts tagged with “{this.props.pathContext.tag}” </h2> <ul> {postLinks} </ul> <p> <Link to=""/tags/"">Browse all tags</Link> </p> </div> ); } } export default TagRoute; export const pageQuery = graphql` query TagPage($tag: String) { allMarkdownRemark( limit: 1000 sort: { fields: [frontmatter___date], order: DESC } filter: { frontmatter: { tags: { in: [$tag] }, draft: { ne: true } } } ) { totalCount edges { node { fields { slug } frontmatter { title } } } } } `; " Update tests to include PHP 5.5 style Class::class calls,"<?php namespace Chrisgeary92\Pagespeed\Test; use Chrisgeary92\Pagespeed\Service; use Chrisgeary92\Pagespeed\PagespeedException; class ServiceTest extends \PHPUnit_Framework_TestCase { /** @test */ public function it_is_initializable() { $service = new Service(); $this->assertInstanceOf(Service::class, $service); } /** @test */ public function it_can_merge_url_with_optional_query_arguments() { $service = new Service(); $return = $service->getArguments('https://google.com', [ 'strategy' => 'desktop', 'screenshot' => true ]); $this->assertArrayHasKey('url', $return); $this->assertArrayHasKey('strategy', $return); $this->assertArrayHasKey('screenshot', $return); } /** @test */ public function it_can_successfully_test_a_public_webpage() { $url = 'https://github.com/chrisgeary92/pagespeed'; $service = new Service(); $response = $service->runPagespeed($url); $this->assertEquals($url, $response['id']); $this->assertEquals(200, $response['responseCode']); } /** @test */ public function it_throws_exceptions_for_failed_pagespeed_checks() { $this->expectException(PagespeedException::class); $service = new Service(); $response = $service->runPagespeed('test'); } } ","<?php namespace Chrisgeary92\Pagespeed\Test; use Chrisgeary92\Pagespeed\Service; class ServiceTest extends \PHPUnit_Framework_TestCase { /** @test */ public function it_is_initializable() { $service = new Service(); $this->assertInstanceOf('Chrisgeary92\Pagespeed\Service', $service); } /** @test */ public function it_can_merge_url_with_optional_query_arguments() { $service = new Service(); $return = $service->getArguments('https://google.com', [ 'strategy' => 'desktop', 'screenshot' => true ]); $this->assertArrayHasKey('url', $return); $this->assertArrayHasKey('strategy', $return); $this->assertArrayHasKey('screenshot', $return); } /** @test */ public function it_can_successfully_test_a_public_webpage() { $url = 'https://github.com/chrisgeary92/pagespeed'; $service = new Service(); $response = $service->runPagespeed($url); $this->assertEquals($url, $response['id']); $this->assertEquals(200, $response['responseCode']); } /** @test */ public function it_throws_exceptions_for_failed_pagespeed_checks() { $this->expectException('Chrisgeary92\Pagespeed\PagespeedException'); $service = new Service(); $response = $service->runPagespeed('test'); } } " Swap order of implode() args to fix deprecation warning on PHP 7.4,"<?php namespace WireMock\Integration; use WireMock\Client\WireMock; require_once 'MappingsAssertionFunctions.php'; require_once 'TestClient.php'; abstract class WireMockIntegrationTest extends \PHPUnit_Framework_TestCase { /** @var WireMock */ protected static $_wireMock; /** @var TestClient */ protected $_testClient; public static function setUpBeforeClass() { self::runCmd('./../wiremock/start.sh'); self::$_wireMock = WireMock::create(); assertThat(self::$_wireMock->isAlive(), is(true)); } public static function tearDownAfterClass() { self::runCmd('./../wiremock/stop.sh'); } protected static function runCmd($cmd) { $result = 0; $output = array(); $redirect = EXEC_BLOCKS_ON_OUTPUT ? '> /dev/null' : ''; exec(""($cmd) $redirect 2>&1 &"", $output, $result); $output = array_map(function ($line) { return ""\n$line""; }, $output); echo implode(""\n"", $output); assertThat($result, is(0)); } public function setUp() { $this->_testClient = new TestClient(); self::$_wireMock->reset(); } public function clearMappings() { exec('rm -f ../wiremock/1/mappings/*'); } } ","<?php namespace WireMock\Integration; use WireMock\Client\WireMock; require_once 'MappingsAssertionFunctions.php'; require_once 'TestClient.php'; abstract class WireMockIntegrationTest extends \PHPUnit_Framework_TestCase { /** @var WireMock */ protected static $_wireMock; /** @var TestClient */ protected $_testClient; public static function setUpBeforeClass() { self::runCmd('./../wiremock/start.sh'); self::$_wireMock = WireMock::create(); assertThat(self::$_wireMock->isAlive(), is(true)); } public static function tearDownAfterClass() { self::runCmd('./../wiremock/stop.sh'); } protected static function runCmd($cmd) { $result = 0; $output = array(); $redirect = EXEC_BLOCKS_ON_OUTPUT ? '> /dev/null' : ''; exec(""($cmd) $redirect 2>&1 &"", $output, $result); $output = array_map(function ($line) { return ""\n$line""; }, $output); echo implode($output, ""\n""); assertThat($result, is(0)); } public function setUp() { $this->_testClient = new TestClient(); self::$_wireMock->reset(); } public function clearMappings() { exec('rm -f ../wiremock/1/mappings/*'); } } " Configure loader to store assets in clear names instead of hash," 'use strict'; var path = require('path'); var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var ExtractTextPlugin = require(""extract-text-webpack-plugin""); module.exports = { entry: { 'vendor': ['angular','angular-animate','angular-aria','angular-messages','angular-material','angular-material-icons','@uirouter/angularjs'], 'app': path.resolve(__dirname,'src/app.js') }, output: { path: path.resolve(__dirname,'dist'), filename: 'scripts/[name].js' }, module: { loaders: [ { test: /\.js$/, exclude: /(node_modules,libs)/, loader: 'babel-loader', // 'babel-loader' is also a legal name to reference query: { presets: ['es2015'] } }, { test: /\.html$/, loader: 'html-loader' }, // Extract css files { test: /\.(png|svg)$/, loader: ""file-loader?name=./images/[name].[ext]"" }, { test: /\.css$/, loader: ExtractTextPlugin.extract({ fallback: ""style-loader"", use: ""css-loader"" }) } ] }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: ['app', 'vendor'] }), new HtmlWebpackPlugin({ template: path.resolve(__dirname,'src/index.html') }), new ExtractTextPlugin(""styles/[name].css""), ] };"," 'use strict'; var path = require('path'); var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var ExtractTextPlugin = require(""extract-text-webpack-plugin""); module.exports = { entry: { 'vendor': ['angular','angular-animate','angular-aria','angular-messages','angular-material','angular-material-icons','@uirouter/angularjs'], 'app': path.resolve(__dirname,'src/app.js') }, output: { path: path.resolve(__dirname,'dist'), filename: 'scripts/[name].js' }, module: { loaders: [ { test: /\.js$/, exclude: /(node_modules,libs)/, loader: 'babel-loader', // 'babel-loader' is also a legal name to reference query: { presets: ['es2015'] } }, { test: /\.html$/, loader: 'html-loader' }, // Extract css files { test: /\.png$/, loader: 'file-loader' }, { test: /\.css$/, loader: ExtractTextPlugin.extract({ fallback: ""style-loader"", use: ""css-loader"" }) } ] }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: ['app', 'vendor'] }), new HtmlWebpackPlugin({ template: path.resolve(__dirname,'src/index.html') }), new ExtractTextPlugin(""styles/[name].css""), ] };" Fix typo in content type,"<?php namespace OParl\Website\Api\Controllers; use function Swagger\scan; /** * @SWG\Swagger( * schemes={""https""}, * host=""dev.oparl.org"", * basePath=""/api/"", * @SWG\Info( * title=""OParl Developer Platform API"", * description=""Meta information concerning the OParl ecosystem"", * version=""0"", * @SWG\License( * name=""CC-4.0-BY"", * url=""https://creativecommons.org/licenses/by/4.0/"" * ) * ), * produces={ ""application/json"" } * ) */ class ApiController { /** * Return the dynamically updated swagger.json for the meta endpoints. * * @return \Symfony\Component\HttpFoundation\Response */ public function swaggerJson() { $swagger = scan(base_path('lib/Api/Controllers')); return response($swagger, 200, [ 'Content-Type' => 'application/json', 'Access-Control-Allow-Origin' => '*', ]); } /** * Index page for the api. * * @return \Symfony\Component\HttpFoundation\Response */ public function index() { return view('api.index'); } } ","<?php namespace OParl\Website\Api\Controllers; use function Swagger\scan; /** * @SWG\Swagger( * schemes={""https""}, * host=""dev.oparl.org"", * basePath=""/api/"", * @SWG\Info( * title=""OParl Developer Platform API"", * description=""Meta information concerning the OParl ecosystem"", * version=""0"", * @SWG\License( * name=""CC-4.0-BY"", * url=""https://creativecommons.org/licenses/by/4.0/"" * ) * ), * produces={ ""application/json"" } * ) */ class ApiController { /** * Return the dynamically updated swagger.json for the meta endpoints. * * @return \Symfony\Component\HttpFoundation\Response */ public function swaggerJson() { $swagger = scan(base_path('lib/Api/Controllers')); return response($swagger, 200, [ 'Content-Tyype' => 'application/json', 'Access-Control-Allow-Origin' => '*', ]); } /** * Index page for the api. * * @return \Symfony\Component\HttpFoundation\Response */ public function index() { return view('api.index'); } } " Remove platform/login from web command,"<?php namespace Platformsh\Cli\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class WebCommand extends UrlCommandBase { protected function configure() { parent::configure(); $this ->setName('web') ->setDescription('Open the Platform.sh Web UI'); $this->addProjectOption() ->addEnvironmentOption(); } protected function execute(InputInterface $input, OutputInterface $output) { // Attempt to select the appropriate project and environment. try { $this->validateInput($input); } catch (\Exception $e) { // Ignore errors. } $project = $this->hasSelectedProject() ? $this->getSelectedProject() : false; $url = 'https://accounts.platform.sh/'; if ($project) { $url = $project->getLink('#ui'); if ($this->hasSelectedEnvironment()) { $environment = $this->getSelectedEnvironment(); $url .= '/environments/' . $environment['id']; } } $this->openUrl($url, $input, $output); } } ","<?php namespace Platformsh\Cli\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class WebCommand extends UrlCommandBase { protected function configure() { parent::configure(); $this ->setName('web') ->setDescription('Open the Platform.sh Web UI'); $this->addProjectOption() ->addEnvironmentOption(); } protected function execute(InputInterface $input, OutputInterface $output) { // Attempt to select the appropriate project and environment. try { $this->validateInput($input); } catch (\Exception $e) { // Ignore errors. } $project = $this->hasSelectedProject() ? $this->getSelectedProject() : false; $url = 'https://accounts.platform.sh/platform/login'; if ($project) { $url = $project->getLink('#ui'); if ($this->hasSelectedEnvironment()) { $environment = $this->getSelectedEnvironment(); $url .= '/environments/' . $environment['id']; } } $this->openUrl($url, $input, $output); } } " "Support either global or local locale The global locale should be set by using `Globalize.locale()` prior to the rendering. A local locale should be set via a property `locale` in the React component.","var Globalize = require(""globalize""); var mixins = {}; Object.getOwnPropertyNames(Globalize).forEach(function(fn) { if (fn.indexOf(""format"") === 0) { var fnString = Globalize[fn].toString(); var argString = fnString.substr(fnString.indexOf(""("")+1, fnString.indexOf("")"")-(fnString.indexOf(""("")+1)).trim(); var argArray = argString.split("", ""); (function(currentFn, currentArgs) { var formatter = function(nextProps) { var instance = Globalize; var componentProps = nextProps || this.props; var propArgs = currentArgs.map(function(element) { return componentProps[element.replace(/(\s\/\*|\*\/)/,"""").trim()]; }); if (componentProps[""locale""]) { instance = Globalize(componentProps[""locale""]); } this.setState({ formattedValue: instance[currentFn].apply(instance, propArgs) }); }; mixins[currentFn] = { componentWillMount: formatter, componentWillReceiveProps: formatter }; })(fn, argArray); } }); module.exports = mixins; ","var Globalize = require(""globalize""); var mixins = {}; Object.getOwnPropertyNames(Globalize).forEach(function(fn) { if (fn.indexOf(""format"") === 0) { var fnString = Globalize[fn].toString(); var argString = fnString.substr(fnString.indexOf(""("")+1, fnString.indexOf("")"")-(fnString.indexOf(""("")+1)).trim(); var argArray = argString.split("", ""); (function(currentFn, currentArgs) { var formatter = function(nextProps) { var componentProps = nextProps || this.props; var propArgs = currentArgs.map(function(element) { return componentProps[element.replace(/(\s\/\*|\*\/)/,"""").trim()]; }); Globalize.locale( componentProps[""locale""] ); this.setState({ formattedValue: Globalize[currentFn].apply(Globalize, propArgs) }); }; mixins[currentFn] = { componentWillMount: formatter, componentWillReceiveProps: formatter }; })(fn, argArray); } }); module.exports = mixins; " Add fix for context data refs issue in nested components,"'use strict'; const _ = require('lodash'); module.exports = function(fractal){ function RenderExtension() { this.tags = ['render']; this.parse = function (parser, nodes) { var tok = parser.nextToken(); var args = parser.parseSignature(null, true); parser.advanceAfterBlockEnd(tok.value); return new nodes.CallExtensionAsync(this, 'run', args); }; this.run = function () { const source = fractal.components; const args = Array.from(arguments); const rootContext = args[0].ctx; const callback = args.pop(); args.shift(); const handle = args[0]; let context = args[1]; const merge = args[2] || false; const entity = source.find(handle); if (!entity) { throw new Error(`Could not render component '${handle}' - component not found.`); } const defaultContext = entity.isComponent ? entity.variants().default().context : entity.context; if (!context) { context = defaultContext; } else if (merge) { context = _.defaultsDeep(context, defaultContext); } source.resolve(context).then(context => { // fix env for rendered components let env = JSON.parse(JSON.stringify(rootContext._env)); context._env = env; entity.render(context).then(html => { callback(null, html); }).catch(err => { callback(err); }); }); }; }; return new RenderExtension(); }; ","'use strict'; const _ = require('lodash'); module.exports = function(fractal){ function RenderExtension() { this.tags = ['render']; this.parse = function (parser, nodes) { var tok = parser.nextToken(); var args = parser.parseSignature(null, true); parser.advanceAfterBlockEnd(tok.value); return new nodes.CallExtensionAsync(this, 'run', args); }; this.run = function () { const source = fractal.components; const args = Array.from(arguments); const rootContext = args[0].ctx; const callback = args.pop(); args.shift(); const handle = args[0]; let context = args[1]; const merge = args[2] || false; const entity = source.find(handle); if (!entity) { throw new Error(`Could not render component '${handle}' - component not found.`); } const defaultContext = entity.isComponent ? entity.variants().default().context : entity.context; if (!context) { context = defaultContext; } else if (merge) { context = _.defaultsDeep(context, defaultContext); } // fix env for rendered components let env = JSON.parse(JSON.stringify(rootContext._env)); context._env = env; entity.render(context).then(html => { callback(null, html); }).catch(err => { callback(err); }); }; }; return new RenderExtension(); }; " Add button for creating earning to earnings' index view,"@extends('layout') @section('title', __('general.earnings')) @section('body') <div class=""wrapper my-3""> <div class=""row""> <div class=""row__column row__column--middle""> <h2>{{ __('general.earnings') }}</h2> </div> <div class=""row__column row__column--compact row__column--middle""> <a href=""/earnings/create"" class=""button"">Create Earning</a> </div> </div> <div class=""box mt-3""> @if (count($earnings)) @foreach ($earnings as $earning) <div class=""box__section row""> <div class=""row__column""> <div class=""color-dark"">{{ $earning->description }}</div> <div class=""mt-1"" style=""font-size: 14px; font-weight: 600;"">{{ $earning->formatted_happened_on }}</div> </div> <div class=""row__column row__column--middle color-dark"">{!! $currency !!} {{ $earning->formatted_amount }}</div> <div class=""row__column row__column--middle row__column--compact""> <form method=""POST"" action=""/earnings/{{ $earning->id }}""> {{ method_field('DELETE') }} {{ csrf_field() }} <button class=""button link""> <i class=""far fa-trash-alt""></i> </button> </form> </div> </div> @endforeach @else <div class=""box__section text-center"">You don't have any earnings</div> @endif </div> </div> @endsection ","@extends('layout') @section('title', __('general.earnings')) @section('body') <div class=""wrapper my-3""> <h2>{{ __('general.earnings') }}</h2> <div class=""box mt-3""> @if (count($earnings)) @foreach ($earnings as $earning) <div class=""box__section row""> <div class=""row__column""> <div class=""color-dark"">{{ $earning->description }}</div> <div class=""mt-1"" style=""font-size: 14px; font-weight: 600;"">{{ $earning->formatted_happened_on }}</div> </div> <div class=""row__column row__column--middle color-dark"">{!! $currency !!} {{ $earning->formatted_amount }}</div> <div class=""row__column row__column--middle row__column--compact""> <form method=""POST"" action=""/earnings/{{ $earning->id }}""> {{ method_field('DELETE') }} {{ csrf_field() }} <button class=""button link""> <i class=""far fa-trash-alt""></i> </button> </form> </div> </div> @endforeach @else <div class=""box__section text-center"">You don't have any earnings</div> @endif </div> </div> @endsection " Hide data from assessment info,"var _ = require('lodash'), assessmentData = require('./assessments'), http = require(""q-io/http""); var routes = {}; routes.publish = function (router) { router.get('/assess/:assessmentId', function (request, response) { var assessmentId = request.params.assessmentId; var assessment = _.cloneDeep(assessmentData.get(assessmentId)); delete assessment.className; delete assessment.tests; delete assessment.tips; delete assessment.guides; response.send(assessment); }); router.post('/assess/:assessmentId', function (request, response) { var assessmentId = request.params.assessmentId; var assessment = assessmentData.get(assessmentId); var submittedCode = request.body.code; var options = { url: 'http://localhost:5020/v1/', method: 'POST', body: [ JSON.stringify({ assessment: { title: assessment.title, className: assessment.className, tests: assessment.tests }, code: submittedCode }) ] }; http.request(http.normalizeRequest(options)) .then(function (submissionResponse) { submissionResponse.body.read().then(function (body) { response .status(submissionResponse.status) .send(body); }); }); }); }; module.exports = routes;","var _ = require('lodash'), assessmentData = require('./assessments'), http = require(""q-io/http""); var routes = {}; routes.publish = function (router) { router.get('/assess/:assessmentId', function (request, response) { var assessmentId = request.params.assessmentId; var assessment = assessmentData.get(assessmentId); response.send(assessment); }); router.post('/assess/:assessmentId', function (request, response) { var assessmentId = request.params.assessmentId; var assessment = assessmentData.get(assessmentId); var submittedCode = request.body.code; var options = { url: 'http://localhost:5020/v1/', method: 'POST', body: [ JSON.stringify({ assessment: { title: assessment.title, className: assessment.className, tests: assessment.tests }, code: submittedCode }) ] }; http.request(http.normalizeRequest(options)) .then(function (submissionResponse) { submissionResponse.body.read().then(function (body) { response .status(submissionResponse.status) .send(body); }); }); }); }; module.exports = routes;" Add improvement for code coverage by using yet unmerged PR to karma-remap-istanbul repo,"// Karma configuration file, see link for more information // https://karma-runner.github.io/0.13/config/configuration-file.html module.exports = function (config) { var configuration = { basePath: '', frameworks: ['jasmine', 'angular-cli'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-remap-istanbul'), require('angular-cli/plugins/karma') ], files: [ {pattern: './src/test.ts', watched: false} ], preprocessors: { './src/test.ts': ['angular-cli'] }, remapIstanbulReporter: { reports: { html: 'coverage', lcovonly: './coverage/coverage.lcov' }, remapOptions: { exclude: /(util|test|polyfills).ts$/ } }, angularCli: { config: './angular-cli.json', environment: 'dev' }, reporters: ['progress', 'karma-remap-istanbul'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, // browser for travis-ci customLaunchers: { Chrome_travis_ci: { base: 'Chrome', flags: ['--no-sandbox'] } } }; if (process.env.TRAVIS) { configuration.browsers = ['Chrome_travis_ci']; } config.set(configuration); }; ","// Karma configuration file, see link for more information // https://karma-runner.github.io/0.13/config/configuration-file.html module.exports = function (config) { var configuration = { basePath: '', frameworks: ['jasmine', 'angular-cli'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-remap-istanbul'), require('angular-cli/plugins/karma') ], files: [ {pattern: './src/test.ts', watched: false} ], preprocessors: { './src/test.ts': ['angular-cli'] }, remapIstanbulReporter: { reports: { html: 'coverage', lcovonly: './coverage/coverage.lcov' } }, angularCli: { config: './angular-cli.json', environment: 'dev' }, reporters: ['progress', 'karma-remap-istanbul'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, // browser for travis-ci customLaunchers: { Chrome_travis_ci: { base: 'Chrome', flags: ['--no-sandbox'] } } }; if (process.env.TRAVIS) { configuration.browsers = ['Chrome_travis_ci']; } config.set(configuration); }; " Use passed directory in mako engine.,"#!/usr/bin/env python """"""Provide the mako templating engine."""""" from __future__ import print_function from mako.template import Template from mako.lookup import TemplateLookup from . import Engine class MakoEngine(Engine): """"""Mako templating engine."""""" handle = 'mako' def __init__(self, template, dirname=None, tolerant=False, **kwargs): """"""Initialize mako template."""""" super(MakoEngine, self).__init__(**kwargs) directories = [dirname] if dirname is not None else ['.'] lookup = TemplateLookup(directories=directories) default_filters = ['filter_undefined'] if tolerant else None encoding_errors = 'replace' if tolerant else 'strict' imports = ['def filter_undefined(value):\n' ' if value is UNDEFINED:\n' ' return \'<UNDEFINED>\'\n' ' return value\n'] self.template = Template(template, default_filters=default_filters, encoding_errors=encoding_errors, imports=imports, lookup=lookup, strict_undefined=not tolerant, ) def apply(self, mapping): """"""Apply a mapping of name-value-pairs to a template."""""" return self.template.render(**mapping) ","#!/usr/bin/env python """"""Provide the mako templating engine."""""" from __future__ import print_function from mako.template import Template from mako.lookup import TemplateLookup from . import Engine class MakoEngine(Engine): """"""Mako templating engine."""""" handle = 'mako' def __init__(self, template, tolerant=False, **kwargs): """"""Initialize mako template."""""" super(MakoEngine, self).__init__(**kwargs) default_filters = ['filter_undefined'] if tolerant else None encoding_errors = 'replace' if tolerant else 'strict' imports = ['def filter_undefined(value):\n' ' if value is UNDEFINED:\n' ' return \'<UNDEFINED>\'\n' ' return value\n'] lookup = TemplateLookup(directories=['.']) self.template = Template(template, default_filters=default_filters, encoding_errors=encoding_errors, imports=imports, lookup=lookup, strict_undefined=not tolerant, ) def apply(self, mapping): """"""Apply a mapping of name-value-pairs to a template."""""" return self.template.render(**mapping) " Move main() into _main() to make testing easier,"import argparse import os import sys from urllib.parse import urlparse from .v5_client import LuminosoClient, get_token_filename from .v5_constants import URL_BASE def _main(argv): default_domain_base = urlparse(URL_BASE).netloc default_token_filename = get_token_filename() parser = argparse.ArgumentParser( description='Save a token for the Luminoso Daylight API.', ) parser.add_argument('token', help='API token (see ""Settings - Tokens"" in the UI)') parser.add_argument('domain', default=default_domain_base, help=f'API domain, default {default_domain_base}', nargs='?') parser.add_argument('-f', '--token_file', default=default_token_filename, help=(f'File in which to store the token, default' f' {default_token_filename}')) args = parser.parse_args(argv) # Make this as friendly as possible: turn any of ""daylight.luminoso.com"", # ""daylight.luminoso.com/api/v5"", or ""http://daylight.luminoso.com/"", into # just the domain domain = args.domain if '://' in domain: domain = urlparse(domain).netloc else: domain = domain.split('/')[0] LuminosoClient.save_token(args.token, domain=domain, token_file=args.token_file) def main(): """""" The setuptools entry point. """""" _main(sys.argv[1:]) ","import argparse import os import sys from urllib.parse import urlparse from .v5_client import LuminosoClient, get_token_filename from .v5_constants import URL_BASE def main(): default_domain_base = urlparse(URL_BASE).netloc default_token_filename = get_token_filename() parser = argparse.ArgumentParser( description='Save a token for the Luminoso Daylight API.', ) parser.add_argument('token', help='API token (see ""Settings - Tokens"" in the UI)') parser.add_argument('domain', default=default_domain_base, help=f'API domain, default {default_domain_base}', nargs='?') parser.add_argument('-f', '--token_file', default=default_token_filename, help=(f'File in which to store the token, default' f' {default_token_filename}')) args = parser.parse_args() # Make this as friendly as possible: turn any of ""daylight.luminoso.com"", # ""daylight.luminoso.com/api/v5"", or ""http://daylight.luminoso.com/"", into # just the domain domain = args.domain if '://' in domain: domain = urlparse(domain).netloc else: domain = domain.split('/')[0] LuminosoClient.save_token(args.token, domain=domain, token_file=args.token_file) " Fix dollar sign issue in angular injection,"'use strict'; var through = require('through') , loader = require('./loader') , async = require('async'); function angularify() { var buf = ''; return through(function(chunk) { buf += chunk.toString(); }, function () { var rexSingle = new RegExp(/require\('angula[^']+'\)[,;]/g) , rexDouble = new RegExp(/require\(""angula[^']+""\)[,;]/g) // , rexModule = new RegExp(/\(.*?\)/) , requires = [] , self = this; requires = requires.concat(buf.match(rexSingle)); requires = requires.concat(buf.match(rexDouble)); async.eachSeries(requires, function (req, callback) { if (req === null) { return callback(); } var modVer = req .replace('require(', '') .replace(/\)[,;]/, '') .replace(/\'|\""/g, '') .split('@'); loader.getModule(modVer[0], modVer[1], function (err, module) { module += 'module.exports = window.angular'; // JavaScript String.replace gives unexpected result with $ chars // replace these temporarily... module = module.replace(/\$/g, '_DOLLARBANG_'); // Insert angular buf = buf.replace(req, module); // Now insert the $ chars again... buf = buf.replace(/_DOLLARBANG_/g, '$'); callback(); }); }, function (err) { if (err) { throw err; } self.queue(buf); self.queue(null); }); }); } module.exports = angularify; ","'use strict'; var through = require('through') , loader = require('./loader') , async = require('async'); function angularify() { var buf = ''; return through(function(chunk) { buf += chunk.toString(); }, function () { var rexSingle = new RegExp(/require\('angula[^']+'\)[,;]/g) , rexDouble = new RegExp(/require\(""angula[^']+""\)[,;]/g) // , rexModule = new RegExp(/\(.*?\)/) , requires = [] , self = this; requires = requires.concat(buf.match(rexSingle)); requires = requires.concat(buf.match(rexDouble)); async.eachSeries(requires, function (req, callback) { if (req === null) { return callback(); } var modVer = req .replace('require(', '') .replace(/\)[,;]/, '') .replace(/\'|\""/g, '') .split('@'); loader.getModule(modVer[0], modVer[1], function (err, module) { // JavaScript String.replace gives unexpected result with $ chars // replace these temporarily... module = module.replace(/\$/g, '_'); // Insert angular buf = buf.replace(req, module); // Now insert the $ chars again... buf = buf.replace(/_/, '$'); callback(); }); }, function (err) { if (err) { throw err; } self.queue(buf); self.queue(null); }); }); } module.exports = angularify; " "Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command.","import os from celery.loaders.djangoapp import Loader as DjangoLoader from celery.loaders.default import Loader as DefaultLoader from django.conf import settings from django.core.management import setup_environ """""" .. class:: Loader The current loader class. """""" Loader = DefaultLoader if settings.configured: Loader = DjangoLoader else: try: # A settings module may be defined, but Django didn't attempt to # load it yet. As an alternative to calling the private _setup(), # we could also check whether DJANGO_SETTINGS_MODULE is set. settings._setup() except ImportError: if not callable(getattr(os, ""fork"", None)): # Platform doesn't support fork() # XXX On systems without fork, multiprocessing seems to be launching # the processes in some other way which does not copy the memory # of the parent process. This means that any configured env might # be lost. This is a hack to make it work on Windows. # A better way might be to use os.environ to set the currently # used configuration method so to propogate it to the ""child"" # processes. But this has to be experimented with. # [asksol/heyman] try: settings_mod = os.environ.get(""DJANGO_SETTINGS_MODULE"", ""settings"") project_settings = __import__(settings_mod, {}, {}, ['']) setup_environ(project_settings) Loader = DjangoLoader except ImportError: pass else: Loader = DjangoLoader """""" .. data:: current_loader The current loader instance. """""" current_loader = Loader() """""" .. data:: settings The global settings object. """""" settings = current_loader.conf ","import os from celery.loaders.djangoapp import Loader as DjangoLoader from celery.loaders.default import Loader as DefaultLoader from django.conf import settings from django.core.management import setup_environ """""" .. class:: Loader The current loader class. """""" Loader = DefaultLoader if settings.configured: Loader = DjangoLoader else: if not callable(getattr(os, ""fork"", None)): # Platform doesn't support fork() # XXX On systems without fork, multiprocessing seems to be launching # the processes in some other way which does not copy the memory # of the parent process. This means that any configured env might # be lost. This is a hack to make it work on Windows. # A better way might be to use os.environ to set the currently # used configuration method so to propogate it to the ""child"" # processes. But this has to be experimented with. # [asksol/heyman] try: settings_mod = os.environ.get(""DJANGO_SETTINGS_MODULE"", ""settings"") project_settings = __import__(settings_mod, {}, {}, ['']) setup_environ(project_settings) Loader = DjangoLoader except ImportError: pass """""" .. data:: current_loader The current loader instance. """""" current_loader = Loader() """""" .. data:: settings The global settings object. """""" settings = current_loader.conf " "Make sure we install the csv file, still.","#!/usr/bin/python from setuptools import setup setup(name='libhxl', version='2.7.1', description='Python support for the Humanitarian Exchange Language (HXL).', author='David Megginson', author_email='contact@megginson.com', url='http://hxlproject.org', install_requires=['python-dateutil', 'xlrd', 'requests', 'unidecode'], packages=['hxl'], package_data={'hxl': ['*.csv']}, include_package_data=True, test_suite='tests', entry_points={ 'console_scripts': [ 'hxladd = hxl.scripts:hxladd', 'hxlappend = hxl.scripts:hxlappend', 'hxlclean = hxl.scripts:hxlclean', 'hxlcount = hxl.scripts:hxlcount', 'hxlcut = hxl.scripts:hxlcut', 'hxldedup = hxl.scripts:hxldedup', 'hxlmerge = hxl.scripts:hxlmerge', 'hxlrename = hxl.scripts:hxlrename', 'hxlreplace = hxl.scripts:hxlreplace', 'hxlselect = hxl.scripts:hxlselect', 'hxlsort = hxl.scripts:hxlsort', 'hxltag = hxl.scripts:hxltag', 'hxlvalidate = hxl.scripts:hxlvalidate' ] } ) ","#!/usr/bin/python from setuptools import setup setup(name='libhxl', version='2.7', description='Python support for the Humanitarian Exchange Language (HXL).', author='David Megginson', author_email='contact@megginson.com', url='http://hxlproject.org', install_requires=['python-dateutil', 'xlrd', 'requests', 'unidecode'], packages=['hxl'], test_suite='tests', entry_points={ 'console_scripts': [ 'hxladd = hxl.scripts:hxladd', 'hxlappend = hxl.scripts:hxlappend', 'hxlclean = hxl.scripts:hxlclean', 'hxlcount = hxl.scripts:hxlcount', 'hxlcut = hxl.scripts:hxlcut', 'hxldedup = hxl.scripts:hxldedup', 'hxlmerge = hxl.scripts:hxlmerge', 'hxlrename = hxl.scripts:hxlrename', 'hxlreplace = hxl.scripts:hxlreplace', 'hxlselect = hxl.scripts:hxlselect', 'hxlsort = hxl.scripts:hxlsort', 'hxltag = hxl.scripts:hxltag', 'hxlvalidate = hxl.scripts:hxlvalidate' ] } ) " "Throw NPE instead of ServiceRuntimeException, more fitting","package fi.nls.oskari.mybatis; import org.apache.ibatis.mapping.Environment; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.apache.ibatis.transaction.TransactionFactory; import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; import javax.sql.DataSource; public class MyBatisHelper { public static SqlSessionFactory initMyBatis(DataSource ds, Class<?>... mappers) { return build(getConfig(ds, mappers)); } public static Configuration getConfig(DataSource ds, Class<?>... mappers) { if (ds == null) { throw new NullPointerException(""Tried initializing MyBatis without a datasource""); } final TransactionFactory transactionFactory = new JdbcTransactionFactory(); final Environment environment = new Environment(""development"", transactionFactory, ds); final Configuration configuration = new Configuration(environment); configuration.setLazyLoadingEnabled(true); addMappers(configuration, mappers); return configuration; } public static void addAliases(Configuration config, Class<?>... aliases) { for (Class<?> alias : aliases) { config.getTypeAliasRegistry().registerAlias(alias); } } public static void addMappers(Configuration config, Class<?>... mappers) { for (Class<?> mapper : mappers) { config.addMapper(mapper); } } public static SqlSessionFactory build(Configuration config) { return new SqlSessionFactoryBuilder().build(config); } } ","package fi.nls.oskari.mybatis; import fi.nls.oskari.service.ServiceRuntimeException; import org.apache.ibatis.mapping.Environment; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.apache.ibatis.transaction.TransactionFactory; import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; import javax.sql.DataSource; public class MyBatisHelper { public static SqlSessionFactory initMyBatis(DataSource ds, Class<?>... mappers) { return build(getConfig(ds, mappers)); } public static Configuration getConfig(DataSource ds, Class<?>... mappers) { if(ds == null) { throw new ServiceRuntimeException(""Tried initializing MyBatis without a datasource""); } final TransactionFactory transactionFactory = new JdbcTransactionFactory(); final Environment environment = new Environment(""development"", transactionFactory, ds); final Configuration configuration = new Configuration(environment); configuration.setLazyLoadingEnabled(true); addMappers(configuration, mappers); return configuration; } public static void addAliases(Configuration config, Class<?>... aliases) { for (Class<?> alias : aliases) { config.getTypeAliasRegistry().registerAlias(alias); } } public static void addMappers(Configuration config, Class<?>... mappers) { for (Class<?> mapper : mappers) { config.addMapper(mapper); } } public static SqlSessionFactory build(Configuration config) { return new SqlSessionFactoryBuilder().build(config); } } " Add Github+LinkedIn to Hacker Data export,""""""" Generates a CSV containing approved hackers' resumes """""" from hackfsu_com.views.generic import StreamedCsvView from hackfsu_com.util import acl, files from django.conf import settings from api.models import Hackathon, HackerInfo, UserInfo class ResumeLinksCsv(StreamedCsvView): access_manager = acl.AccessManager(acl_accept=[acl.group_organizer]) file_name = 'HackFSU Approved Hackers\' Submitted Resumes.csv' @staticmethod def row_generator(request): h = Hackathon.objects.current() yield ['Approved Hackers\' Submitted Resumes'] yield [ 'First Name', 'Last Name', 'Email', 'School', 'Github', 'LinkedIn', 'Attended', 'Resume File Name', 'Resume URL' ] for hacker in HackerInfo.objects.filter( hackathon=h, approved=True ): user_info = UserInfo.objects.get(user=hacker.user) row = [ hacker.user.first_name, hacker.user.last_name, hacker.user.email, str(hacker.school), user_info.github, user_info.linkedin, hacker.attendee_status.checked_in_at is not None ] if len(hacker.resume_file_name) > 0: row.extend([ hacker.resume_file_name.split('/')[-1], settings.URL_BASE + files.get_url(hacker.resume_file_name) ]) yield row ",""""""" Generates a CSV containing approved hackers' resumes """""" from hackfsu_com.views.generic import StreamedCsvView from hackfsu_com.util import acl, files from django.conf import settings from api.models import Hackathon, HackerInfo class ResumeLinksCsv(StreamedCsvView): access_manager = acl.AccessManager(acl_accept=[acl.group_organizer]) file_name = 'HackFSU Approved Hackers\' Submitted Resumes.csv' @staticmethod def row_generator(request): h = Hackathon.objects.current() yield ['Approved Hackers\' Submitted Resumes'] yield [ 'First Name', 'Last Name', 'Email', 'School', 'Attended', 'Resume File Name', 'Resume URL' ] for hacker in HackerInfo.objects.filter( hackathon=h, approved=True ): row = [ hacker.user.first_name, hacker.user.last_name, hacker.user.email, str(hacker.school), hacker.attendee_status.checked_in_at is not None ] if len(hacker.resume_file_name) > 0: row.extend([ hacker.resume_file_name.split('/')[-1], settings.URL_BASE + files.get_url(hacker.resume_file_name) ]) yield row " Update tests to import see,"#!/usr/bin/env python # encoding: utf-8 """""" Unit tests for see.py """""" from __future__ import print_function, unicode_literals try: import unittest2 as unittest except ImportError: import unittest import os import sys sys.path.insert(0, os.path.dirname(__file__)) import see class TestSee(unittest.TestCase): def test_line_width(self): # Arrange default_width = 1 max_width = 1 # Act width = see.line_width(default_width, max_width) # Assert self.assertIsInstance(width, int) self.assertEqual(width, 1) def test_regex_filter(self): # Arrange names = [""george"", ""helen""] pat = ""or*"" # Act out = see.regex_filter(names, pat) # Assert self.assertIsInstance(out, tuple) self.assertEqual(out, (""george"",)) def test_fn_filter(self): # Arrange names = [""george"", ""helen""] pat = ""*or*"" # Act out = see.fn_filter(names, pat) # Assert self.assertIsInstance(out, tuple) self.assertEqual(out, (""george"",)) def test_see_with_no_args(self): # Act out = see.see() # Assert self.assertIsInstance(out, see._SeeOutput) if __name__ == '__main__': unittest.main() # End of file ","#!/usr/bin/env python # encoding: utf-8 """""" Unit tests for see.py """""" from __future__ import print_function, unicode_literals try: import unittest2 as unittest except ImportError: import unittest import see class TestSee(unittest.TestCase): def test_line_width(self): # Arrange default_width = 1 max_width = 1 # Act width = see.line_width(default_width, max_width) # Assert self.assertIsInstance(width, int) self.assertEqual(width, 1) def test_regex_filter(self): # Arrange names = [""george"", ""helen""] pat = ""or*"" # Act out = see.regex_filter(names, pat) # Assert self.assertIsInstance(out, tuple) self.assertEqual(out, (""george"",)) def test_fn_filter(self): # Arrange names = [""george"", ""helen""] pat = ""*or*"" # Act out = see.fn_filter(names, pat) # Assert self.assertIsInstance(out, tuple) self.assertEqual(out, (""george"",)) def test_see_with_no_args(self): # Act out = see.see() # Assert self.assertIsInstance(out, see._SeeOutput) if __name__ == '__main__': unittest.main() # End of file " Delete tag only on success,"define('app/views/delete_tag', [ 'ember', 'jquery' ], /** * * Delete tag view * * @returns Class */ function() { return Ember.View.extend({ tagName: false, didInsertElement: function(e){ $(""a.tagButton"").button(); }, deleteTag: function() { var tag = this.tag; var machine = Mist.machine; log(""tag to delete: "" + tag); var payload = { 'tag': tag.toString() }; machine.set('pendingDeleteTag', true); $.ajax({ url: 'backends/' + machine.backend.id + '/machines/' + machine.id + '/metadata', type: 'DELETE', contentType: 'application/json', data: JSON.stringify(payload), success: function(data) { info('Successfully deleted tag from machine', machine.name); machine.tags.removeObject(this.tag.toString()); machine.set('pendingDeleteTag', false); }, error: function(jqXHR, textstate, errorThrown) { Mist.notificationController.notify('Error while deleting tag from machine ' + machine.name); error(textstate, errorThrown, 'while deleting tag from machine machine', machine.name); machine.set('pendingDeleteTag', false); } }); } }); } ); ","define('app/views/delete_tag', [ 'ember', 'jquery' ], /** * * Delete tag view * * @returns Class */ function() { return Ember.View.extend({ tagName: false, didInsertElement: function(e){ $(""a.tagButton"").button(); }, deleteTag: function() { var tag = this.tag; var machine = Mist.machine; machine.tags.removeObject(this.tag.toString()); log(""tag to delete: "" + tag); var payload = { 'tag': tag.toString() }; machine.set('pendingDeleteTag', true); $.ajax({ url: 'backends/' + machine.backend.id + '/machines/' + machine.id + '/metadata', type: 'DELETE', contentType: 'application/json', data: JSON.stringify(payload), success: function(data) { info('Successfully deleted tag from machine', machine.name); machine.set('pendingDeleteTag', false); }, error: function(jqXHR, textstate, errorThrown) { Mist.notificationController.notify('Error while deleting tag from machine ' + machine.name); error(textstate, errorThrown, 'while deleting tag from machine machine', machine.name); machine.tags.addObject(tag.toString()); machine.set('pendingDeleteTag', false); } }); } }); } ); " Fix blocks and use ViewData,"<?php namespace Enhavo\Bundle\SliderBundle\Block; use Doctrine\ORM\EntityRepository; use Enhavo\Bundle\AppBundle\View\ViewData; use Enhavo\Bundle\BlockBundle\Model\BlockInterface; use Enhavo\Bundle\SliderBundle\Entity\SliderBlock; use Enhavo\Bundle\SliderBundle\Factory\SliderBlockFactory; use Enhavo\Bundle\SliderBundle\Form\Type\SliderBlockType as SliderBlockFormType; use Enhavo\Bundle\BlockBundle\Block\AbstractBlockType; use Symfony\Component\OptionsResolver\OptionsResolver; class SliderBlockType extends AbstractBlockType { /** @var EntityRepository */ private $repository; public function createViewData(BlockInterface $block, ViewData $viewData, $resource, array $options) { $viewData['slides'] = $this->repository->findAll(); } public function configureOptions(OptionsResolver $optionsResolver) { $optionsResolver->setDefaults([ 'model' => SliderBlock::class, 'form' => SliderBlockFormType::class, 'factory' => SliderBlockFactory::class, 'template' => 'theme/block/slider.html.twig', 'label' => 'Slider', 'translation_domain' => 'EnhavoSliderBundle', 'groups' => ['default', 'content'] ]); } public static function getName(): ?string { return 'slider'; } } ","<?php namespace Enhavo\Bundle\SliderBundle\Block; use Doctrine\ORM\EntityRepository; use Enhavo\Bundle\BlockBundle\Model\BlockInterface; use Enhavo\Bundle\SliderBundle\Entity\SliderBlock; use Enhavo\Bundle\SliderBundle\Factory\SliderBlockFactory; use Enhavo\Bundle\SliderBundle\Form\Type\SliderBlockType as SliderBlockFormType; use Enhavo\Bundle\BlockBundle\Block\AbstractBlockType; use Symfony\Component\OptionsResolver\OptionsResolver; class SliderBlockType extends AbstractBlockType { /** @var EntityRepository */ private $repository; public function createViewData(BlockInterface $block, $resource, array $options) { $data = parent::createViewData($block, $resource, $options); $data['slides'] = $this->repository->findAll(); return $data; } public function configureOptions(OptionsResolver $optionsResolver) { $optionsResolver->setDefaults([ 'model' => SliderBlock::class, 'form' => SliderBlockFormType::class, 'factory' => SliderBlockFactory::class, 'template' => 'theme/block/slider.html.twig', 'label' => 'Slider', 'translation_domain' => 'EnhavoSliderBundle', 'groups' => ['default', 'content'] ]); } public static function getName(): ?string { return 'slider'; } } " Use full module path for entry point,"# coding=utf-8 from setuptools import setup, find_packages setup( name=""git-up"", version=""1.3.0"", packages=find_packages(exclude=[""tests""]), scripts=['PyGitUp/gitup.py'], install_requires=['GitPython==1.0.0', 'colorama==0.3.3', 'termcolor==1.1.0', 'docopt==0.6.2', 'six==1.9.0'], # Tests test_suite=""nose.collector"", tests_require='nose', # Executable entry_points={ 'console_scripts': [ 'git-up = PyGitUp.gitup:run' ] }, # Additional data package_data={ 'PyGitUp': ['check-bundler.rb'], '': ['README.rst', 'LICENCE'] }, zip_safe=False, # Metadata author=""Markus Siemens"", author_email=""markus@m-siemens.de"", description=""A python implementation of 'git up'"", license=""MIT"", keywords=""git git-up"", url=""https://github.com/msiemens/PyGitUp"", classifiers=[ ""Development Status :: 5 - Production/Stable"", ""Environment :: Console"", ""Intended Audience :: Developers"", ""License :: OSI Approved :: MIT License"", ""Topic :: Software Development :: Version Control"", ""Topic :: Utilities"" ], long_description=open('README.rst').read() ) ","# coding=utf-8 from setuptools import setup, find_packages setup( name=""git-up"", version=""1.3.0"", packages=find_packages(exclude=[""tests""]), scripts=['PyGitUp/gitup.py'], install_requires=['GitPython==1.0.0', 'colorama==0.3.3', 'termcolor==1.1.0', 'docopt==0.6.2', 'six==1.9.0'], # Tests test_suite=""nose.collector"", tests_require='nose', # Executable entry_points={ 'console_scripts': [ 'git-up = gitup:run' ] }, # Additional data package_data={ 'PyGitUp': ['check-bundler.rb'], '': ['README.rst', 'LICENCE'] }, zip_safe=False, # Metadata author=""Markus Siemens"", author_email=""markus@m-siemens.de"", description=""A python implementation of 'git up'"", license=""MIT"", keywords=""git git-up"", url=""https://github.com/msiemens/PyGitUp"", classifiers=[ ""Development Status :: 5 - Production/Stable"", ""Environment :: Console"", ""Intended Audience :: Developers"", ""License :: OSI Approved :: MIT License"", ""Topic :: Software Development :: Version Control"", ""Topic :: Utilities"" ], long_description=open('README.rst').read() ) " Fix up some tabs & spaces inconsistencies,"module.exports = function(grunt) { grunt.initConfig({ bower: { main: { rjsConfig: 'js/main.js' } }, jshint: { files: ['Gruntfile.js', 'js/**/*.js', 'specs/**/*.js'], options: { ignores: ['js/vendor/*.js'] } }, jasmine: { src: ['js/**/*.js'], options: { specs: ['specs/**/*.spec.js'], template: require('grunt-template-jasmine-requirejs'), templateOptions: { requireConfigFile: 'js/main.js', requireConfig: { baseUrl: 'js' } } } }, watch: { files: ['Gruntfile.js', 'js/**/*.js', 'specs/**/*.js'], tasks: ['jshint', 'jasmine'] } }); grunt.loadNpmTasks('grunt-bower-requirejs'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-jasmine'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('travis', ['jshint', 'jasmine']); grunt.registerTask('default', ['jshint', 'jasmine', 'watch']); };","module.exports = function(grunt) { grunt.initConfig({ bower: { main: { rjsConfig: 'js/main.js' } }, jshint: { files: ['Gruntfile.js', 'js/**/*.js', 'specs/**/*.js'], options: { ignores: ['js/vendor/*.js'] } }, jasmine: { src: ['js/**/*.js'], options: { specs: ['specs/**/*.spec.js'], template: require('grunt-template-jasmine-requirejs'), templateOptions: { requireConfigFile: 'js/main.js', requireConfig: { baseUrl: 'js' } } } }, watch: { files: ['Gruntfile.js', 'js/**/*.js', 'specs/**/*.js'], tasks: ['jshint', 'jasmine'] } }); grunt.loadNpmTasks('grunt-bower-requirejs'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-jasmine'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('travis', ['jshint', 'jasmine']); grunt.registerTask('default', ['jshint', 'jasmine', 'watch']); };" Increase the @office limit to 15 minutes instead of 10,"const _ = require('lodash'); const members = require('../lib/members'); const get_presence_device = require('../lib/presence'); const createMention = username => `@${username}`; module.exports = robot => { robot.hear(/@kontoret|@office/i, msg => { members() .then(members => { Promise.all( members.map(member => Promise.all( member.wifi_devices.map(device_mac => get_presence_device(device_mac).then(presence_device => { if ( presence_device === undefined || Math.abs( (new Date().getTime() - presence_device.info.last_seen.toDate().getTime()) / 1000 ) > 60 * 15 ) { return false; } return member.slack; }) ) ) ) ).then(members_queried => { const membersAtOffice = _.uniq( members_queried .reduce((a, b) => a.concat(b)) .filter(member_device => member_device !== false) ); if (membersAtOffice.length === 0) { msg.send( 'Nobody at the office at the moment :slightly_frowning_face:' ); return; } msg.send( membersAtOffice.map(member => createMention(member)).join(', ') ); }); }) .catch(error => msg.send(error.message)); }); }; ","const _ = require('lodash'); const members = require('../lib/members'); const get_presence_device = require('../lib/presence'); const createMention = username => `@${username}`; module.exports = robot => { robot.hear(/@kontoret|@office/i, msg => { members() .then(members => { Promise.all( members.map(member => Promise.all( member.wifi_devices.map(device_mac => get_presence_device(device_mac).then(presence_device => { if ( presence_device === undefined || Math.abs( (new Date().getTime() - presence_device.info.last_seen.toDate().getTime()) / 1000 ) > 60 * 10 ) { return false; } return member.slack; }) ) ) ) ).then(members_queried => { const membersAtOffice = _.uniq( members_queried .reduce((a, b) => a.concat(b)) .filter(member_device => member_device !== false) ); if (membersAtOffice.length === 0) { msg.send( 'Nobody at the office at the moment :slightly_frowning_face:' ); return; } msg.send( membersAtOffice.map(member => createMention(member)).join(', ') ); }); }) .catch(error => msg.send(error.message)); }); }; " ISDOT-98: Configure Campaign entity merge option&mass action for grid,"<?php namespace Oro\Bundle\EntityMergeBundle\Validator\Constraints; use Symfony\Component\Validator\Constraint; use Oro\Bundle\EntityMergeBundle\Data\EntityData; use Oro\Bundle\EntityMergeBundle\Exception\InvalidArgumentException; class SourceEntityValidator extends DoctrineHelperValidator { /** * {@inheritdoc} */ public function validate($value, Constraint $constraint) { if (!$value instanceof EntityData) { throw new InvalidArgumentException( sprintf( 'Oro\Bundle\EntityMergeBundle\Data\EntityData supported only, %s given', is_object($value) ? get_class($value) : gettype($value) ) ); } /* @var EntityData $value */ $entities = $value->getEntities(); $fields = $value->getFields(); foreach ($fields as $field) { $sourceEntity = $field->getSourceEntity(); if (!is_object($sourceEntity)) { continue; } foreach ($entities as $entity) { if ($this->doctrineHelper->isEntityEqual($entity, $sourceEntity)) { break 2; } } $this->context->addViolation( /* @var SourceEntity $constraint */ $constraint->message, ['{{ limit }}' => $field->getFieldName()] ); } } } ","<?php namespace Oro\Bundle\EntityMergeBundle\Validator\Constraints; use Symfony\Component\Validator\Constraint; use Oro\Bundle\EntityMergeBundle\Data\EntityData; use Oro\Bundle\EntityMergeBundle\Exception\InvalidArgumentException; class SourceEntityValidator extends DoctrineHelperValidator { /** * {@inheritdoc} */ public function validate($value, Constraint $constraint) { if (!$value instanceof EntityData) { throw new InvalidArgumentException( sprintf( 'Oro\Bundle\EntityMergeBundle\Data\EntityData supported only, %s given', is_object($value) ? get_class($value) : gettype($value) ) ); } /* @var EntityData $value */ $entities = $value->getEntities(); $fields = $value->getFields(); foreach ($fields as $field) { $sourceEntity = $field->getSourceEntity(); foreach ($entities as $entity) { if ($this->doctrineHelper->isEntityEqual($entity, $sourceEntity)) { break 2; } } $this->context->addViolation( /* @var SourceEntity $constraint */ $constraint->message, ['{{ limit }}' => $field->getFieldName()] ); } } } " "Disable test that fails on bot I will look at it. rdar://35264910","# TestPOUnwrapping.py # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https://swift.org/LICENSE.txt for license information # See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors # # ------------------------------------------------------------------------------ """"""Test that we can correctly handle a nested generic type."""""" import lldbsuite.test.lldbrepl as lldbrepl import lldbsuite.test.decorators as decorators class REPLBasicTestCase(lldbrepl.REPLTest): mydir = lldbrepl.REPLTest.compute_mydir(__file__) @decorators.expectedFailureAll( oslist=[ ""macosx"", ""linux""], bugnumber=""rdar://35264910"") def doTest(self): self.command( '''class Foo<T,U> { var t: T? var u: U? init() { t = nil; u = nil } init(_ x: T, _ y: U) { t = x; u = y } };(Foo<String,Double>(),Foo<Double,String>(3.14,""hello""))''', patterns=[ r'\$R0: \(Foo<String, Double>, Foo<Double, String>\) = {', r'0 = {', r't = nil', r'u = nil', r'1 = {', r't = 3\.14[0-9]+', 'u = ""hello""']) ","# TestPOUnwrapping.py # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https://swift.org/LICENSE.txt for license information # See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors # # ------------------------------------------------------------------------------ """"""Test that we can correctly handle a nested generic type."""""" import lldbsuite.test.lldbrepl as lldbrepl import lldbsuite.test.decorators as decorators class REPLBasicTestCase(lldbrepl.REPLTest): mydir = lldbrepl.REPLTest.compute_mydir(__file__) def doTest(self): self.command( '''class Foo<T,U> { var t: T? var u: U? init() { t = nil; u = nil } init(_ x: T, _ y: U) { t = x; u = y } };(Foo<String,Double>(),Foo<Double,String>(3.14,""hello""))''', patterns=[ r'\$R0: \(Foo<String, Double>, Foo<Double, String>\) = {', r'0 = {', r't = nil', r'u = nil', r'1 = {', r't = 3\.14[0-9]+', 'u = ""hello""']) " Fix unit tests skip symlink tests on windows,"<?php namespace PharIo\Phive; use PharIo\FileSystem\Filename; use PHPUnit\Framework\TestCase; /** * @covers \PharIo\Phive\SymlinkPharActivator */ class SymlinkPharActivatorTest extends TestCase { public function setUp() { if (0 === stripos(PHP_OS, 'win')) { $this->markTestSkipped('PHP does not support symlinks on Windows.'); } $this->deleteTestSymlink(); } public function tearDown() { $this->deleteTestSymlink(); } public function testActivateCreatesExpectedSymlink() { $targetPhar = new Filename(__DIR__ .'/fixtures/some.phar'); $symlinkFilename = new Filename(__DIR__ . '/symlink'); $activator = new SymlinkPharActivator(); $activator->activate($targetPhar, $symlinkFilename); $this->assertTrue(is_link($symlinkFilename->asString())); } public function testActiveReturnsExpectedFilename() { $targetPhar = new Filename(__DIR__ .'/fixtures/some.phar'); $symlinkFilename = new Filename(__DIR__ . '/symlink'); $activator = new SymlinkPharActivator(); $actual = $activator->activate($targetPhar, $symlinkFilename); $this->assertEquals($symlinkFilename ,$actual); } private function deleteTestSymlink() { $filename = __DIR__ . '/symlink'; if (!file_exists($filename)) { return; } unlink($filename); } } ","<?php namespace PharIo\Phive; use PharIo\FileSystem\Filename; use PHPUnit\Framework\TestCase; /** * @covers \PharIo\Phive\SymlinkPharActivator */ class SymlinkPharActivatorTest extends TestCase { public function setUp() { $this->deleteTestSymlink(); } public function tearDown() { $this->deleteTestSymlink(); } public function testActivateCreatesExpectedSymlink() { $targetPhar = new Filename(__DIR__ .'/fixtures/some.phar'); $symlinkFilename = new Filename(__DIR__ . '/symlink'); $activator = new SymlinkPharActivator(); $activator->activate($targetPhar, $symlinkFilename); $this->assertTrue(is_link($symlinkFilename->asString())); } public function testActiveReturnsExpectedFilename() { $targetPhar = new Filename(__DIR__ .'/fixtures/some.phar'); $symlinkFilename = new Filename(__DIR__ . '/symlink'); $activator = new SymlinkPharActivator(); $actual = $activator->activate($targetPhar, $symlinkFilename); $this->assertEquals($symlinkFilename ,$actual); } private function deleteTestSymlink() { $filename = __DIR__ . '/symlink'; if (!file_exists($filename)) { return; } unlink($filename); } } " Make the starting text more sane,"// ==UserScript== // @name SmartyFace // @description Text Prediction on facepunch // @author benjojo // @namespace http://facepunch.com // @include http://facepunch.com/* // @include http://www.facepunch.com/* // @include https://facepunch.com/* // @include https://www.facepunch.com/* // @version 1 // ==/UserScript== var endPoint = ""http://text.nsa.me.uk/pose""; function findTextBoxes (argument) { var boxes = $('textarea'); var parent = boxes[2].parentNode; $(parent).prepend(""<i id=\""SmartyFace\"" style=\""pointer-events:none; color: #CCC;position: absolute;font: 13px Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif;padding: 0 1px 0 1px;\"">Type Reply Here</i>""); var textarea = boxes[2]; $(boxes[2]).keypress(function(a) { var text = $(textarea).val(); $.post( endPoint, { post: text }) .done(function( data ) { $('#SmartyFace').html($(textarea).val()+data); }); // $('#SmartyFace').html($(textarea).val()); }); } findTextBoxes();","// ==UserScript== // @name SmartyFace // @description Text Prediction on facepunch // @author benjojo // @namespace http://facepunch.com // @include http://facepunch.com/* // @include http://www.facepunch.com/* // @include https://facepunch.com/* // @include https://www.facepunch.com/* // @version 1 // ==/UserScript== var endPoint = ""http://text.nsa.me.uk/pose""; function findTextBoxes (argument) { var boxes = $('textarea'); var parent = boxes[2].parentNode; $(parent).prepend(""<i id=\""SmartyFace\"" style=\""pointer-events:none; color: #CCC;position: absolute;font: 13px Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif;padding: 0 1px 0 1px;\"">This is a test wow. such test</i>""); var textarea = boxes[2]; $(boxes[2]).keypress(function(a) { var text = $(textarea).val(); $.post( endPoint, { post: text }) .done(function( data ) { $('#SmartyFace').html($(textarea).val()+data); }); // $('#SmartyFace').html($(textarea).val()); }); } findTextBoxes();" Fix gaia-reader bug where wrong storageRootDirectory config key was being used in file GETs.,"/* @flow */ import express from 'express' import expressWinston from 'express-winston' import logger from 'winston' import cors from 'cors' import Path from 'path' import { GaiaDiskReader } from './server' export function makeHttpServer(config: Object) { const app = express() const server = new GaiaDiskReader(config) app.config = config app.use(expressWinston.logger({ transports: logger.loggers.default.transports })) app.use(cors()) app.get(/\/([a-zA-Z0-9]+)\/(.+)/, (req: express.request, res: express.response) => { let filename = req.params[1] if (filename.endsWith('/')) { filename = filename.substring(0, filename.length - 1) } const address = req.params[0] return server.handleGet(address, filename) .then((fileInfo) => { const exists = fileInfo.exists const contentType = fileInfo.contentType if (!exists) { return res.status(404).send('File not found') } const opts = { root: config.diskSettings.storageRootDirectory, headers: { 'content-type': contentType } } const path = Path.join(address, filename) return res.sendFile(path, opts) }) .catch((err) => { logger.error(err) return res.status(400).send('Could not return file') }) }) return app } ","/* @flow */ import express from 'express' import expressWinston from 'express-winston' import logger from 'winston' import cors from 'cors' import Path from 'path' import { GaiaDiskReader } from './server' export function makeHttpServer(config: Object) { const app = express() const server = new GaiaDiskReader(config) app.config = config app.use(expressWinston.logger({ transports: logger.loggers.default.transports })) app.use(cors()) app.get(/\/([a-zA-Z0-9]+)\/(.+)/, (req: express.request, res: express.response) => { let filename = req.params[1] if (filename.endsWith('/')) { filename = filename.substring(0, filename.length - 1) } const address = req.params[0] return server.handleGet(address, filename) .then((fileInfo) => { const exists = fileInfo.exists const contentType = fileInfo.contentType if (!exists) { return res.status(404).send('File not found') } const opts = { root: config.storageRootDirectory, headers: { 'content-type': contentType } } const path = Path.join(address, filename) return res.sendFile(path, opts) }) .catch((err) => { logger.error(err) return res.status(400).send('Could not return file') }) }) return app } " Add attribution to slugify function.,"from been.core import DirectorySource, source_registry from hashlib import sha1 import re import unicodedata import time import markdown # slugify from Django source (BSD license) def slugify(value): value = unicodedata.normalize('NFKD', unicode(value)).encode('ascii', 'ignore') value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) return re.sub('[-\s]+', '-', value) class MarkdownDirectory(DirectorySource): kind = 'markdown' def process_event(self, event): md = markdown.Markdown(extensions=['meta']) html = md.convert(event['content']) event['title'] = ' '.join(md.Meta.get('title', [event['filename']])) event['slug'] = '-'.join(md.Meta.get('slug', [slugify(event['title'])])) event['summary'] = ' '.join(md.Meta.get('summary', [event['content'][:100]])) if md.Meta.get('published'): # Parse time, then convert struct_time (local) -> epoch (GMT) -> struct_time (GMT) event['timestamp'] = time.gmtime(time.mktime(time.strptime(' '.join(md.Meta.get('published')), '%Y-%m-%d %H:%M:%S'))) event['_id'] = sha1(event['full_path'].encode('utf-8')).hexdigest() if time.gmtime() < event['timestamp']: return None else: return event source_registry.add(MarkdownDirectory) ","from been.core import DirectorySource, source_registry from hashlib import sha1 import re import unicodedata import time import markdown def slugify(value): value = unicodedata.normalize('NFKD', unicode(value)).encode('ascii', 'ignore') value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) return re.sub('[-\s]+', '-', value) class MarkdownDirectory(DirectorySource): kind = 'markdown' def process_event(self, event): md = markdown.Markdown(extensions=['meta']) html = md.convert(event['content']) event['title'] = ' '.join(md.Meta.get('title', [event['filename']])) event['slug'] = '-'.join(md.Meta.get('slug', [slugify(event['title'])])) event['summary'] = ' '.join(md.Meta.get('summary', [event['content'][:100]])) if md.Meta.get('published'): # Parse time, then convert struct_time (local) -> epoch (GMT) -> struct_time (GMT) event['timestamp'] = time.gmtime(time.mktime(time.strptime(' '.join(md.Meta.get('published')), '%Y-%m-%d %H:%M:%S'))) event['_id'] = sha1(event['full_path'].encode('utf-8')).hexdigest() if time.gmtime() < event['timestamp']: return None else: return event source_registry.add(MarkdownDirectory) " "Use international MSISDN format according to SMPP protocol spec: 4.2.6.1.1","import logging logger = logging.getLogger(__name__) def strspn(source, allowed): newchrs = [] for c in source: if c in allowed: newchrs.append(c) return u''.join(newchrs) def check_cell_phone_number(number): cleaned_number = strspn(number, u'0123456789') #if not u'+' in cleaned_number[:1]: # cleaned_number = u'+%s' % cleaned_number return int(cleaned_number) def truncate_sms(text, max_length=160): if len(text) <= max_length: return text else: logger.error(""Trying to send an SMS that is too long: %s"", text) return text[:max_length-3] + '...' def parse_sms(content): content = content.upper().strip() from smsgateway.backends.base import hook for keyword, subkeywords in hook.iteritems(): if content[:len(keyword)] == unicode(keyword): remainder = content[len(keyword):].strip() if '*' in subkeywords: parts = remainder.split(u' ') subkeyword = parts[0].strip() if subkeyword in subkeywords: return [keyword] + parts return keyword, remainder else: for subkeyword in subkeywords: if remainder[:len(subkeyword)] == unicode(subkeyword): subremainder = remainder[len(subkeyword):].strip() return [keyword, subkeyword] + subremainder.split() return None ","import logging logger = logging.getLogger(__name__) def strspn(source, allowed): newchrs = [] for c in source: if c in allowed: newchrs.append(c) return u''.join(newchrs) def check_cell_phone_number(number): cleaned_number = strspn(number, u'+0123456789') if not u'+' in cleaned_number[:1]: cleaned_number = u'+%s' % cleaned_number return cleaned_number def truncate_sms(text, max_length=160): if len(text) <= max_length: return text else: logger.error(""Trying to send an SMS that is too long: %s"", text) return text[:max_length-3] + '...' def parse_sms(content): content = content.upper().strip() from smsgateway.backends.base import hook for keyword, subkeywords in hook.iteritems(): if content[:len(keyword)] == unicode(keyword): remainder = content[len(keyword):].strip() if '*' in subkeywords: parts = remainder.split(u' ') subkeyword = parts[0].strip() if subkeyword in subkeywords: return [keyword] + parts return keyword, remainder else: for subkeyword in subkeywords: if remainder[:len(subkeyword)] == unicode(subkeyword): subremainder = remainder[len(subkeyword):].strip() return [keyword, subkeyword] + subremainder.split() return None " "Undo ctor changes to derived class of AbstractModelCollection These will be moved to a different branch","<?php /** * Container for multiple TwitterRequestTokenModel objects, also handles * collection metadata such as pagination */ class TwitterRequestTokenModelCollection extends AbstractModelCollection { /** * Take arrays of data and create a collection of models; store metadata * * @param array $data * @param int $total */ public function __construct(array $data, $total = 0) { $this->total = $total; // hydrate the model objects foreach ($data as $item) { $this->list[] = new TwitterRequestTokenModel($item); } } /** * Present this collection ready for the output handlers * * This creates the expected output structure, converting each resource * to it's presentable representation and adding the meta fields for totals * and pagination * * @param Request $request * @param bool $verbose * * @return array */ public function getOutputView(Request $request, $verbose = false) { // handle the collection first $retval = array(); $retval['twitter_request_tokens'] = array(); foreach ($this->list as $item) { $retval['twitter_request_tokens'][] = $item->getOutputView($request, $verbose); } // add other fields $retval['meta'] = $this->addPaginationLinks($request); return $retval; } } ","<?php /** * Container for multiple TwitterRequestTokenModel objects, also handles * collection metadata such as pagination */ class TwitterRequestTokenModelCollection extends AbstractModelCollection { /** @var int */ protected $total; /** @var array */ protected $list; /** * Take arrays of data and create a collection of models; store metadata * * @param array $data * @param int $total */ public function __construct(array $data, $total = 0) { $this->total = $total; $this->list = []; // hydrate the model objects foreach ($data as $item) { $this->list[] = new TwitterRequestTokenModel($item); } } /** * Present this collection ready for the output handlers * * This creates the expected output structure, converting each resource * to it's presentable representation and adding the meta fields for totals * and pagination * * @param Request $request * @param bool $verbose * * @return array */ public function getOutputView(Request $request, $verbose = false) { // handle the collection first $retval = array(); $retval['twitter_request_tokens'] = array(); foreach ($this->list as $item) { $retval['twitter_request_tokens'][] = $item->getOutputView($request, $verbose); } // add other fields $retval['meta'] = $this->addPaginationLinks($request); return $retval; } } " Cover wildcard definitions for the compiled container,"<?php namespace DI\Test\IntegrationTest\Definitions; use DI\Annotation\Inject; use DI\ContainerBuilder; use DI\Test\IntegrationTest\BaseContainerTest; use DI\Test\IntegrationTest\Fixtures\Implementation1; use DI\Test\IntegrationTest\Fixtures\Interface1; /** * Test definitions using wildcards. */ class WildcardDefinitionsTest extends BaseContainerTest { /** * @dataProvider provideContainer */ public function test_wildcards(ContainerBuilder $builder) { $builder->addDefinitions([ 'foo*' => 'bar', 'DI\Test\IntegrationTest\*\Interface*' => \DI\create('DI\Test\IntegrationTest\*\Implementation*'), ]); $container = $builder->build(); $this->assertEquals('bar', $container->get('foo1')); $object = $container->get(Interface1::class); $this->assertInstanceOf(Implementation1::class, $object); } /** * @dataProvider provideContainer */ public function test_wildcards_as_dependency(ContainerBuilder $builder) { $builder->useAnnotations(true); $builder->addDefinitions([ 'DI\Test\IntegrationTest\*\Interface*' => \DI\create('DI\Test\IntegrationTest\*\Implementation*'), ]); $container = $builder->build(); /** @var WildcardDefinitionsTestFixture $object */ $object = $container->get(WildcardDefinitionsTestFixture::class); $this->assertInstanceOf(Implementation1::class, $object->dependency); } } class WildcardDefinitionsTestFixture { /** * @Inject * @var Interface1 */ public $dependency; } ","<?php namespace DI\Test\IntegrationTest\Definitions; use DI\Annotation\Inject; use DI\ContainerBuilder; use DI\Test\IntegrationTest\Fixtures\Implementation1; use DI\Test\IntegrationTest\Fixtures\Interface1; /** * Test definitions using wildcards. */ class WildcardDefinitionsTest extends \PHPUnit_Framework_TestCase { public function test_wildcards() { $builder = new ContainerBuilder(); $builder->addDefinitions([ 'foo*' => 'bar', 'DI\Test\IntegrationTest\*\Interface*' => \DI\create('DI\Test\IntegrationTest\*\Implementation*'), ]); $container = $builder->build(); $this->assertEquals('bar', $container->get('foo1')); $object = $container->get(Interface1::class); $this->assertInstanceOf(Implementation1::class, $object); } public function test_wildcards_as_dependency() { $builder = new ContainerBuilder(); $builder->useAnnotations(true); $builder->addDefinitions([ 'DI\Test\IntegrationTest\*\Interface*' => \DI\create('DI\Test\IntegrationTest\*\Implementation*'), ]); $container = $builder->build(); /** @var WildcardDefinitionsTestFixture $object */ $object = $container->get(WildcardDefinitionsTestFixture::class); $this->assertInstanceOf(Implementation1::class, $object->dependency); } } class WildcardDefinitionsTestFixture { /** * @Inject * @var Interface1 */ public $dependency; } " Fix typo in HTML normalization,"<?php /** * @copyright 2018 Vladimir Jimenez * @license https://github.com/stakx-io/stakx/blob/master/LICENSE.md MIT */ namespace allejo\stakx\Utilities; abstract class HtmlUtils { public static function htmlXPath(\DOMDocument &$DOMDocument, $html, $xpathQuery) { $html = self::normalizeHTML($html); libxml_use_internal_errors(true); $DOMDocument->loadHTML($html); $xmlErrors = libxml_get_errors(); /** @var \LibXMLError $error */ foreach ($xmlErrors as $error) { // http://www.xmlsoft.org/html/libxml-xmlerror.html#xmlParserErrors if ($error->code === 801) { continue; } @trigger_error($error->message, E_USER_WARNING); } libxml_clear_errors(); $xpath = new \DOMXPath($DOMDocument); return $xpath->query($xpathQuery); } private static function normalizeHTML($html) { if (strpos($html, '<body>') === false || strpos($html, '</body>') === false) { return sprintf('<body>%s</body>', $html); } return $html; } } ","<?php /** * @copyright 2018 Vladimir Jimenez * @license https://github.com/stakx-io/stakx/blob/master/LICENSE.md MIT */ namespace allejo\stakx\Utilities; abstract class HtmlUtils { public static function htmlXPath(\DOMDocument &$DOMDocument, $html, $xpathQuery) { $html = self::normalizeHTML($html); libxml_use_internal_errors(true); $DOMDocument->loadHTML($html); $xmlErrors = libxml_get_errors(); /** @var \LibXMLError $error */ foreach ($xmlErrors as $error) { // http://www.xmlsoft.org/html/libxml-xmlerror.html#xmlParserErrors if ($error->code === 801) { continue; } @trigger_error($error->message, E_USER_WARNING); } libxml_clear_errors(); $xpath = new \DOMXPath($DOMDocument); return $xpath->query($xpathQuery); } private static function normalizeHTML($html) { if (strpos($html, '<body>' === false) || strpos($html, '</body>') === false) { return sprintf('<body>%s</body>', $html); } return $html; } } " Add is_active and default args to AnalyzeJudgingContext,"from accelerator.tests.factories import ( CriterionFactory, CriterionOptionSpecFactory, ) from accelerator.tests.contexts.judge_feedback_context import ( JudgeFeedbackContext, ) from accelerator.models import ( JUDGING_FEEDBACK_STATUS_COMPLETE, JudgeApplicationFeedback, ) class AnalyzeJudgingContext(JudgeFeedbackContext): def __init__(self, type=""reads"", name=""reads"", read_count=1, options=[""""], is_active=True): super().__init__(is_active=is_active) self.read_count = read_count self.options = options self.feedback.feedback_status = JUDGING_FEEDBACK_STATUS_COMPLETE self.feedback.save() self.add_application() # Add unread app self.criterion = CriterionFactory(type=type, name=name, judging_round=self.judging_round) self.option_specs = [CriterionOptionSpecFactory( criterion=self.criterion, count=read_count, option=option) for option in options] def needed_reads(self): return (self.read_count * len(self.applications) - self.feedback_count()) def feedback_count(self): counts = [JudgeApplicationFeedback.objects.filter( application=app, feedback_status=JUDGING_FEEDBACK_STATUS_COMPLETE).count() for app in self.applications] return sum([min(self.read_count, count) for count in counts]) ","from accelerator.tests.factories import ( CriterionFactory, CriterionOptionSpecFactory, ) from accelerator.tests.contexts.judge_feedback_context import ( JudgeFeedbackContext, ) from accelerator.models import ( JUDGING_FEEDBACK_STATUS_COMPLETE, JudgeApplicationFeedback, ) class AnalyzeJudgingContext(JudgeFeedbackContext): def __init__(self, type, name, read_count, options): super().__init__() self.read_count = read_count self.options = options self.feedback.feedback_status = JUDGING_FEEDBACK_STATUS_COMPLETE self.feedback.save() self.add_application() # Add unread app self.criterion = CriterionFactory(type=type, name=name, judging_round=self.judging_round) self.option_specs = [CriterionOptionSpecFactory( criterion=self.criterion, count=read_count, option=option) for option in options] def needed_reads(self): return (self.read_count * len(self.applications) - self.feedback_count()) def feedback_count(self): counts = [JudgeApplicationFeedback.objects.filter( application=app, feedback_status=JUDGING_FEEDBACK_STATUS_COMPLETE).count() for app in self.applications] return sum([min(self.read_count, count) for count in counts]) " Update AJAX fn to ES6,"import axios from 'axios' let links const AJAX = async ({ url, resource, id, method = 'GET', data = {}, params = {}, headers = {}, }) => { try { const basepath = window.basepath || '' let response url = `${basepath}${url}` if (!links) { const linksRes = (response = await axios({ url: `${basepath}/chronograf/v1`, method: 'GET', })) links = linksRes.data } if (resource) { url = id ? `${basepath}${links[resource]}/${id}` : `${basepath}${links[resource]}` } response = await axios({ url, method, data, params, headers, }) const {auth} = links return { ...response, auth: {links: auth}, logoutLink: links.logout, } } catch (error) { const {response} = error const {auth} = links throw {...response, auth: {links: auth}, logoutLink: links.logout} // eslint-disable-line no-throw-literal } } export const get = async url => { try { return await AJAX({ method: 'GET', url, }) } catch (error) { console.error(error) throw error } } export default AJAX ","import axios from 'axios' let links export default async function AJAX({ url, resource, id, method = 'GET', data = {}, params = {}, headers = {}, }) { try { const basepath = window.basepath || '' let response url = `${basepath}${url}` if (!links) { const linksRes = (response = await axios({ url: `${basepath}/chronograf/v1`, method: 'GET', })) links = linksRes.data } if (resource) { url = id ? `${basepath}${links[resource]}/${id}` : `${basepath}${links[resource]}` } response = await axios({ url, method, data, params, headers, }) const {auth} = links return { ...response, auth: {links: auth}, logoutLink: links.logout, } } catch (error) { const {response} = error const {auth} = links throw {...response, auth: {links: auth}, logoutLink: links.logout} // eslint-disable-line no-throw-literal } } export const get = async url => { try { return await AJAX({ method: 'GET', url, }) } catch (error) { console.error(error) throw error } } " Sort photos by title by default,"package com.castelijns.mmdemo.photos; import com.castelijns.mmdemo.models.Photo; import java.util.Collection; import java.util.Collections; import java.util.List; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; public class PhotosPresenter implements PhotosContract.Presenter { private PhotosContract.View view; private PhotosRepo repo; PhotosPresenter(PhotosContract.View view) { this.view = view; repo = PhotosRepo.getInstance(); } @Override public void start() { repo.getAllPhotos() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<List<Photo>>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(List<Photo> photos) { Collections.sort(photos); view.showPhotos(photos); } @Override public void onError(Throwable e) { } @Override public void onComplete() { } }); } @Override public void stop() { } } ","package com.castelijns.mmdemo.photos; import com.castelijns.mmdemo.models.Photo; import java.util.List; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; public class PhotosPresenter implements PhotosContract.Presenter { private PhotosContract.View view; private PhotosRepo repo; PhotosPresenter(PhotosContract.View view) { this.view = view; repo = PhotosRepo.getInstance(); } @Override public void start() { repo.getAllPhotos() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<List<Photo>>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(List<Photo> photos) { view.showPhotos(photos); } @Override public void onError(Throwable e) { } @Override public void onComplete() { } }); } @Override public void stop() { } } " Adjust tests to new changes,"import test from ""ava""; import {runKaba} from ""./lib/runner""; /** * @typedef {{ * status: number, * dir?: string, * args?: string[], * match?: RegExp, * noMatch?: RegExp, * }} FixtureConfig */ /* eslint-disable camelcase */ /** @var {Object<string,FixtureConfig>} fixtureTests */ let fixtureTests = { js: { status: 0, }, scss_fail_on_error: { status: 1, args: [""--silent""], noMatch: /Found \d+ Stylelint issues:/, }, scss_fail_on_error_lint: { status: 1, dir: ""scss_fail_on_error"", match: /Found \d+ Stylelint issues:/, }, scss: { status: 0, }, ts: { status: 0, }, }; /* eslint-enable camelcase */ Object.keys(fixtureTests).forEach(key => { test(`File: ${key}`, t => { let expected = fixtureTests[key]; let result = runKaba(expected.dir || key, expected.args || []); let stdout = null !== result.stdout ? result.stdout.toString() : """"; t.is(result.status, expected.status); if (undefined !== expected.match) { t.truthy(expected.match.test(stdout)); } if (undefined !== expected.noMatch) { t.falsy(expected.noMatch.test(stdout)); } }); }); ","import test from ""ava""; import {runKaba} from ""./lib/runner""; /** * @typedef {{ * status: number, * dir?: string, * args?: string[], * match?: RegExp, * noMatch?: RegExp, * }} FixtureConfig */ /* eslint-disable camelcase */ /** @var {Object<string,FixtureConfig>} fixtureTests */ let fixtureTests = { js: { status: 0, }, scss_fail_on_error: { status: 1, noMatch: /Found \d+ Stylelint issues:/, }, scss_fail_on_error_lint: { status: 1, dir: ""scss_fail_on_error"", args: [""--lint""], match: /Found \d+ Stylelint issues:/, }, scss: { status: 0, }, ts: { status: 0, }, }; /* eslint-enable camelcase */ Object.keys(fixtureTests).forEach(key => { test(`File: ${key}`, t => { let expected = fixtureTests[key]; let result = runKaba(expected.dir || key, expected.args || []); let stdout = null !== result.stdout ? result.stdout.toString() : """"; t.is(result.status, expected.status); if (undefined !== expected.match) { t.truthy(expected.match.test(stdout)); } if (undefined !== expected.noMatch) { t.falsy(expected.noMatch.test(stdout)); } }); }); " Set default theme based on users system theme,"import Vue from 'vue'; import FileInfoModal from './components/file-info-modal.vue'; const app = new Vue({ el: '#app', components: { FileInfoModal }, data: () => ({ theme: 'light', menuOpen: false, }), computed: { darkMode() { return this.theme === 'dark'; }, lightMode() { return this.theme === 'light'; } }, methods: { showFileInfo(filePath) { this.$refs.fileInfoModal.show(filePath); }, toggleTheme() { this.theme = this.lightMode ? 'dark' : 'light'; }, }, created: function () { this.theme = localStorage.theme || (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'); }, mounted: function() { window.addEventListener('keyup', e => e.key === '/' && this.$refs.searchInput.focus()); window.addEventListener('scroll', function() { if (window.scrollY > 10) { this.$refs.scrollToTop.classList.remove('hidden'); } else { this.$refs.scrollToTop.classList.add('hidden'); } }.bind(this)); }, watch: { theme: value => localStorage.setItem('theme', value), } }); let hljs = require('highlight.js'); hljs.initHighlightingOnLoad(); ","import Vue from 'vue'; import FileInfoModal from './components/file-info-modal.vue'; const app = new Vue({ el: '#app', components: { FileInfoModal }, data: () => ({ theme: 'light', menuOpen: false, }), computed: { darkMode() { return this.theme === 'dark'; }, lightMode() { return this.theme === 'light'; } }, methods: { showFileInfo(filePath) { this.$refs.fileInfoModal.show(filePath); }, toggleTheme() { this.theme = this.lightMode ? 'dark' : 'light'; }, }, created: function () { this.theme = localStorage.getItem('theme') || 'light'; }, mounted: function() { window.addEventListener('keyup', e => e.key === '/' && this.$refs.searchInput.focus()); window.addEventListener('scroll', function() { if (window.scrollY > 10) { this.$refs.scrollToTop.classList.remove('hidden'); } else { this.$refs.scrollToTop.classList.add('hidden'); } }.bind(this)); }, watch: { theme: value => localStorage.setItem('theme', value), } }); let hljs = require('highlight.js'); hljs.initHighlightingOnLoad(); " Send json content-type to Jenkins,"#!/usr/bin/env python import os import sys import hashlib # Add the lib directory to the path for Lambda to load our libs sys.path.append(os.path.join(os.path.dirname(__file__), 'lib')) import requests # NOQA import hmac # NOQA def verify_signature(secret, signature, payload): computed_hash = hmac.new(str(secret), payload, hashlib.sha1) computed_signature = '='.join(['sha1', computed_hash.hexdigest()]) return hmac.compare_digest(computed_signature, str(signature)) def lambda_handler(event, context): print 'Webhook received' verified = verify_signature(event['secret'], event['x_hub_signature'], event['payload']) print 'Signature verified: ' + str(verified) if verified: response = requests.post(event['jenkins_url'], headers={ 'Content-Type': 'application/json', 'X-GitHub-Delivery': event['x_github_delivery'], 'X-GitHub-Event': event['x_github_event'], 'X-Hub-Signature': event['x_hub_signature'] }, data=event['payload']) response.raise_for_status() else: raise requests.HTTPError('400 Client Error: Bad Request') if __name__ == ""__main__"": pass ","#!/usr/bin/env python import os import sys import hashlib # Add the lib directory to the path for Lambda to load our libs sys.path.append(os.path.join(os.path.dirname(__file__), 'lib')) import requests # NOQA import hmac # NOQA def verify_signature(secret, signature, payload): computed_hash = hmac.new(str(secret), payload, hashlib.sha1) computed_signature = '='.join(['sha1', computed_hash.hexdigest()]) return hmac.compare_digest(computed_signature, str(signature)) def lambda_handler(event, context): print 'Webhook received' verified = verify_signature(event['secret'], event['x_hub_signature'], event['payload']) print 'Signature verified: ' + str(verified) if verified: response = requests.post(event['jenkins_url'], headers={ 'X-GitHub-Delivery': event['x_github_delivery'], 'X-GitHub-Event': event['x_github_event'], 'X-Hub-Signature': event['x_hub_signature'] }, json=event['payload']) response.raise_for_status() else: raise requests.HTTPError('400 Client Error: Bad Request') if __name__ == ""__main__"": pass " "Fix place of broadcasting of 'user logged in' event - It was called only for standard authentication","angular.module('codebrag.auth') .factory('authService', function($http, httpRequestsBuffer, $q, $rootScope) { var authService = { loggedInUser: undefined, login: function(user) { var loginRequest = $http.post('rest/users', user, {bypassQueue: true}); return loginRequest.then(function(response) { authService.loggedInUser = response.data; httpRequestsBuffer.retryAllRequest(); }); }, logout: function() { var logoutRequest = $http.get('rest/users/logout'); return logoutRequest.then(function() { authService.loggedInUser = undefined; }) }, isAuthenticated: function() { return !angular.isUndefined(authService.loggedInUser); }, isNotAuthenticated: function() { return !authService.isAuthenticated(); }, requestCurrentUser: function() { if (authService.isAuthenticated()) { return $q.when(authService.loggedInUser); } return $http.get('rest/users').then(function(response) { authService.loggedInUser = response.data; $rootScope.$broadcast(""codebrag:loggedIn""); return $q.when(authService.loggedInUser); }); } }; return authService; });","angular.module('codebrag.auth') .factory('authService', function($http, httpRequestsBuffer, $q, $rootScope) { var authService = { loggedInUser: undefined, login: function(user) { var loginRequest = $http.post('rest/users', user, {bypassQueue: true}); return loginRequest.then(function(response) { authService.loggedInUser = response.data; $rootScope.$broadcast(""codebrag:loggedIn""); httpRequestsBuffer.retryAllRequest(); }); }, logout: function() { var logoutRequest = $http.get('rest/users/logout'); return logoutRequest.then(function() { authService.loggedInUser = undefined; }) }, isAuthenticated: function() { return !angular.isUndefined(authService.loggedInUser); }, isNotAuthenticated: function() { return !authService.isAuthenticated(); }, requestCurrentUser: function() { if (authService.isAuthenticated()) { return $q.when(authService.loggedInUser); } return $http.get('rest/users').then(function(response) { authService.loggedInUser = response.data; return $q.when(authService.loggedInUser); }); } }; return authService; });" Allow using subst variables in layer attributes,"Ext.define('App.model.Query', { extend: 'Ext.data.Model', config: { fields: [ { name: 'detail', mapping: 'properties', convert: function(value, record) { var detail = [], attributes = record.raw.attributes; detail.push('<table class=""detail"">'); for (var k in attributes) { if (attributes.hasOwnProperty(k) && attributes[k]) { detail = detail.concat([ '<tr>', '<th>', OpenLayers.i18n(k), '</th>', '<td>', OpenLayers.String.format(attributes[k], App), '</td>', '</tr>' ]); } } detail.push('</table>'); return detail.join(''); } }, {name: 'type'} ] } }); Ext.create('Ext.data.Store', { storeId: 'queryStore', model: 'App.model.Query', grouper: { groupFn: function(record) { return OpenLayers.i18n(record.get('type')); } } }); ","Ext.define('App.model.Query', { extend: 'Ext.data.Model', config: { fields: [ { name: 'detail', mapping: 'properties', convert: function(value, record) { var detail = [], attributes = record.raw.attributes; detail.push('<table class=""detail"">'); for (var k in attributes) { if (attributes.hasOwnProperty(k) && attributes[k]) { detail = detail.concat([ '<tr>', '<th>', OpenLayers.i18n(k), '</th>', '<td>', attributes[k], '</td>', '</tr>' ]); } } detail.push('</table>'); return detail.join(''); } }, {name: 'type'} ] } }); Ext.create('Ext.data.Store', { storeId: 'queryStore', model: 'App.model.Query', grouper: { groupFn: function(record) { return OpenLayers.i18n(record.get('type')); } } }); " HotFix: Package data locations have changed for rst templates apparently,"#!/usr/bin/env python from setuptools import setup, find_packages import sys import os import glob setup(name = ""scilifelab"", version = ""0.2.2"", author = ""Science for Life Laboratory"", author_email = ""genomics_support@scilifelab.se"", description = ""Useful scripts for use at SciLifeLab"", license = ""MIT"", scripts = glob.glob('scripts/*.py') + glob.glob('scripts/bcbb_helpers/*.py') + ['scripts/pm'], install_requires = [ ""bcbio-nextgen >= 0.2"", ""drmaa >= 0.5"", ""sphinx >= 1.1.3"", ""couchdb >= 0.8"", ""reportlab >= 2.5"", ""cement >= 2.0.2"", ""mock"", ""PIL"", ""pyPdf"", ""logbook >= 0.4"", # pandas screws up installation; tries to look for local site # packages and not in virtualenv #""pandas >= 0.9"", ""biopython"", ""rst2pdf"", #""psutil"", ], test_suite = 'nose.collector', packages=find_packages(exclude=['tests']), package_data = {'scilifelab':[ 'data/grf/*', 'data/templates/rst/*', ]} ) os.system(""git rev-parse --short --verify HEAD > ~/.scilifelab_version"") ","#!/usr/bin/env python from setuptools import setup, find_packages import sys import os import glob setup(name = ""scilifelab"", version = ""0.2.2"", author = ""Science for Life Laboratory"", author_email = ""genomics_support@scilifelab.se"", description = ""Useful scripts for use at SciLifeLab"", license = ""MIT"", scripts = glob.glob('scripts/*.py') + glob.glob('scripts/bcbb_helpers/*.py') + ['scripts/pm'], install_requires = [ ""bcbio-nextgen >= 0.2"", ""drmaa >= 0.5"", ""sphinx >= 1.1.3"", ""couchdb >= 0.8"", ""reportlab >= 2.5"", ""cement >= 2.0.2"", ""mock"", ""PIL"", ""pyPdf"", ""logbook >= 0.4"", # pandas screws up installation; tries to look for local site # packages and not in virtualenv #""pandas >= 0.9"", ""biopython"", ""rst2pdf"", #""psutil"", ], test_suite = 'nose.collector', packages=find_packages(exclude=['tests']), package_data = {'scilifelab':[ 'data/grf/*', 'data/templates/*', ]} ) os.system(""git rev-parse --short --verify HEAD > ~/.scilifelab_version"") " "Fix ""Looks good"" unit test.","var React = require(""react""); var renderToDOMNode = require(""../render-to-dom-node.js""); var ReagicEditor = require(""./reagic-editor.js""); class EditorExample extends ReagicEditor { renderEditor(){ return <input onChange={() => this.onChange()} ref=""input""></input> } readData(value){ var newData = React.findDOMNode(this.refs.input).value; return newData; } } describe(""ReagicEditor"", function(){ var data, domNode, onChange, schema; beforeEach(function(){ data = ""hi""; schema = { title: ""Greeting"", validators: [ function(value){ return value !== """"; } ] }; this.renderDomNodeWithData = function(data){ return renderToDOMNode( <EditorExample data={data} schema={schema} onChange={function(){ onChange.apply(this, arguments); }}/> ); } domNode = this.renderDomNodeWithData(data); }); it(""Renders the label with the field title"", function(){ expect(domNode.querySelector(""label"").innerHTML).toContain(schema.title); }); it(""Correctly shows that a field without any validators is valid"", function(){ expect(domNode.querySelector(""label"").innerHTML).toContain(""✔""); }); it(""Shows 'Fix this' in indicator if a value isn't valid"", function(){ domNode = this.renderDomNodeWithData(""""); expect(domNode.querySelector(""label"").innerHTML).toContain(""Fix this""); }); }) ","var React = require(""react""); var renderToDOMNode = require(""../render-to-dom-node.js""); var ReagicEditor = require(""./reagic-editor.js""); class EditorExample extends ReagicEditor { renderEditor(){ return <input onChange={() => this.onChange()} ref=""input""></input> } readData(value){ var newData = React.findDOMNode(this.refs.input).value; return newData; } } describe(""ReagicEditor"", function(){ var data, domNode, onChange, schema; beforeEach(function(){ data = ""hi""; schema = { title: ""Greeting"", validators: [ function(value){ return value !== """"; } ] }; this.renderDomNodeWithData = function(data){ return renderToDOMNode( <EditorExample data={data} schema={schema} onChange={function(){ onChange.apply(this, arguments); }}/> ); } domNode = this.renderDomNodeWithData(data); }); it(""Renders the label with the field title"", function(){ expect(domNode.querySelector(""label"").innerHTML).toContain(schema.title); }); it(""Correctly shows that a field without any validators is valid"", function(){ expect(domNode.querySelector(""label"").innerHTML).toContain(""Looks good""); }); it(""Shows 'Fix this' in indicator if a value isn't valid"", function(){ domNode = this.renderDomNodeWithData(""""); expect(domNode.querySelector(""label"").innerHTML).toContain(""Fix this""); }); }) " Set the permission of the file logs for daily and single to be 02770,"<?php return [ /* |-------------------------------------------------------------------------- | Default Log Channel |-------------------------------------------------------------------------- | | This option defines the default log channel that gets used when writing | messages to the logs. The name specified in this option should match | one of the channels defined in the ""channels"" configuration array. | */ 'default' => env('LOG_CHANNEL', 'stack'), /* |-------------------------------------------------------------------------- | Log Channels |-------------------------------------------------------------------------- | | Here you may configure the log channels for your application. Out of | the box, Laravel uses the Monolog PHP logging library. This gives | you a variety of powerful log handlers / formatters to utilize. | | Available Drivers: ""single"", ""daily"", ""slack"", ""syslog"", | ""errorlog"", ""custom"", ""stack"" | */ 'channels' => [ 'stack' => [ 'driver' => 'stack', 'channels' => ['single'], ], 'single' => [ 'driver' => 'single', 'path' => storage_path('logs/laravel.log'), 'level' => 'debug', 'permission' => 02770, ], 'daily' => [ 'driver' => 'daily', 'path' => storage_path('logs/laravel.log'), 'level' => 'debug', 'days' => 7, 'permission' => 02770, ], 'syslog' => [ 'driver' => 'syslog', 'level' => 'debug', ], 'errorlog' => [ 'driver' => 'errorlog', 'level' => 'debug', ], ], ]; ","<?php return [ /* |-------------------------------------------------------------------------- | Default Log Channel |-------------------------------------------------------------------------- | | This option defines the default log channel that gets used when writing | messages to the logs. The name specified in this option should match | one of the channels defined in the ""channels"" configuration array. | */ 'default' => env('LOG_CHANNEL', 'stack'), /* |-------------------------------------------------------------------------- | Log Channels |-------------------------------------------------------------------------- | | Here you may configure the log channels for your application. Out of | the box, Laravel uses the Monolog PHP logging library. This gives | you a variety of powerful log handlers / formatters to utilize. | | Available Drivers: ""single"", ""daily"", ""slack"", ""syslog"", | ""errorlog"", ""custom"", ""stack"" | */ 'channels' => [ 'stack' => [ 'driver' => 'stack', 'channels' => ['single'], ], 'single' => [ 'driver' => 'single', 'path' => storage_path('logs/laravel.log'), 'level' => 'debug', ], 'daily' => [ 'driver' => 'daily', 'path' => storage_path('logs/laravel.log'), 'level' => 'debug', 'days' => 7, ], 'syslog' => [ 'driver' => 'syslog', 'level' => 'debug', ], 'errorlog' => [ 'driver' => 'errorlog', 'level' => 'debug', ], ], ]; " Add semicolons and blocks to mock Writable Stream.,"/*! * YUI Onyx * Copyright 2011 Yahoo! Inc. * Licensed under the BSD license. */ /** * Returns a Vows topic function, which will return * a MockWritableStream, a fake Writable Stream. * * Implements writeHead, like a http.ServerResponse. * Only the (status, headers) signature is implemented. * * Verify with these instance variables: * * - $store: Written data, from write * - $status: HTTP status code, from writeHead * - $headers: HTTP header object, from writeHead * * @return {Function} Vows topic function */ module.exports = function () { return function () { function MockWritableStream () { this.$store = """"; } var proto = MockWritableStream.prototype; proto.writeHead = function (status, /* msg, */ headers) { this.$status = status; this.$headers = headers; }; proto.end = function (input) { if (input) { this.write(input); } this.$end = true; }; proto.write = function (input) { if (this.$end) { throw new Error(""Unable to write: closed.""); } if (Buffer.isBuffer(input)) { this.$store += input.toString(""utf8""); } else { this.$store += input; } }; return new MockWritableStream(); }; }; ","/*! * YUI Onyx * Copyright 2011 Yahoo! Inc. * Licensed under the BSD license. */ /** * Returns a Vows topic function, which will return * a MockWritableStream, a fake Writable Stream. * * Implements writeHead, like a http.ServerResponse. * Only the (status, headers) signature is implemented. * * Verify with these instance variables: * * - $store: Written data, from write * - $status: HTTP status code, from writeHead * - $headers: HTTP header object, from writeHead * * @return {Function} Vows topic function */ module.exports = function () { return function () { function MockWritableStream () { this.$store = """"; } var proto = MockWritableStream.prototype; proto.writeHead = function (status, /* msg, */ headers) { this.$status = status; this.$headers = headers; }; proto.end = function (input) { if (input) this.write(input); this.$end = true; }; proto.write = function (input) { if (this.$end) throw new Error(""Unable to write: closed.""); if (Buffer.isBuffer(input)) { this.$store += input.toString(""utf8""); } else { this.$store += input; } }; return new MockWritableStream; } } " "Enable to specify a string for the trigger label as a substring of the node label. For example a node label with ""WinXP Acceptance London"" and 'Restricted node Label = London'","package org.jvnet.hudson.plugins.triggers.startup; import hudson.model.Node; import java.io.Serializable; /** * @author Gregory Boissinot */ public class HudsonStartupService implements Serializable { public boolean has2Schedule(HudsonStartupTrigger startupTrigger, Node jobNode) { if (startupTrigger == null) { throw new NullPointerException(""A startupTrigger object has to be set.""); } if (jobNode == null) { throw new NullPointerException(""A node object has to be set.""); } String triggerLabel = startupTrigger.getLabel(); return has2Schedule(triggerLabel, jobNode); } private boolean has2Schedule(String triggerLabel, Node jobNode) { String jobNodeName = jobNode.getNodeName(); if (triggerLabel == null) { //Jobs on master has to schedule return isMaster(jobNodeName); } if (triggerLabel.equalsIgnoreCase(""master"")) { //User set 'master' string, Jobs on master has to schedule return isMaster(jobNodeName); } if (triggerLabel.equalsIgnoreCase(jobNodeName)) { //Match exactly node name return true; } String labelString = jobNode.getLabelString(); if (labelString == null) { return false; } if (triggerLabel.equalsIgnoreCase(labelString)) { //Match node label return true; } return labelString.contains(triggerLabel); } private boolean isMaster(String nodeName) { //Master node name is """", slave node name is never empty return nodeName.equals(""""); } } ","package org.jvnet.hudson.plugins.triggers.startup; import hudson.model.Node; import java.io.Serializable; /** * @author Gregory Boissinot */ public class HudsonStartupService implements Serializable { public boolean has2Schedule(HudsonStartupTrigger startupTrigger, Node jobNode) { if (startupTrigger == null) { throw new NullPointerException(""A startupTrigger object has to be set.""); } if (jobNode == null) { throw new NullPointerException(""A node object has to be set.""); } String triggerLabel = startupTrigger.getLabel(); return has2Schedule(triggerLabel, jobNode); } private boolean has2Schedule(String triggerLabel, Node jobNode) { String jobNodeName = jobNode.getNodeName(); if (triggerLabel == null) { //Jobs on master has to schedule return isMaster(jobNodeName); } if (triggerLabel.equalsIgnoreCase(""master"")) { //User set 'master' string, Jobs on master has to schedule return isMaster(jobNodeName); } if (triggerLabel.equalsIgnoreCase(jobNodeName)) { //Match exactly node name return true; } return triggerLabel.equalsIgnoreCase(jobNode.getLabelString()); //Match node label } private boolean isMaster(String nodeName) { //Master node name is """", slave node name is never empty return nodeName.equals(""""); } } " Add hack for broken timezone support in dayone,"""""""Common services code"""""" AVAILABLE_SERVICES = ['habit_list', 'idonethis', 'nikeplus'] def get_service_module(service_name): """"""Import given service from dayonetools.services package"""""" import importlib services_pkg = 'dayonetools.services' module = '%s.%s' % (services_pkg, service_name) return importlib.import_module(module) def convert_to_dayone_date_string(day_str): """""" Convert given date in 'yyyy-mm-dd' format into dayone accepted format of iso8601 The timestamp will match midnight but year, month, and day will be replaced with given arguments. """""" year, month, day = day_str.split('-') from datetime import datetime now = datetime.utcnow() # FIXME: The current version of day one does not support timezone data # correctly. So, if we enter midnight here then every entry is off by a # day. # Don't know the hour, minute, etc. so just assume midnight date = now.replace(year=int(year), month=int(month), day=int(day), minute=00, hour=10, second=0, microsecond=0) iso_string = date.isoformat() # Very specific format for dayone, if the 'Z' is not in the # correct positions the entries will not show up in dayone at all. return iso_string + 'Z' # Make all services available from this level for service_name in AVAILABLE_SERVICES: service = get_service_module(service_name) ","""""""Common services code"""""" AVAILABLE_SERVICES = ['habit_list', 'idonethis', 'nikeplus'] def get_service_module(service_name): """"""Import given service from dayonetools.services package"""""" import importlib services_pkg = 'dayonetools.services' module = '%s.%s' % (services_pkg, service_name) return importlib.import_module(module) def convert_to_dayone_date_string(day_str): """""" Convert given date in 'yyyy-mm-dd' format into dayone accepted format of iso8601 The timestamp will match midnight but year, month, and day will be replaced with given arguments. """""" year, month, day = day_str.split('-') from datetime import datetime now = datetime.utcnow() # Don't know the hour, minute, etc. so just assume midnight date = now.replace(year=int(year), month=int(month), day=int(day), minute=0, hour=0, second=0, microsecond=0) iso_string = date.isoformat() # Very specific format for dayone, if the 'Z' is not in the # correct positions the entries will not show up in dayone at all. return iso_string + 'Z' # Make all services available from this level for service_name in AVAILABLE_SERVICES: service = get_service_module(service_name) " Return the state object if the key is not specified,"import _ from 'lodash'; import events from 'events'; class ImmutableStore extends events.EventEmitter { state = {}; constructor(state = {}) { super(); this.state = state; } get(key, defaultValue) { return (key === undefined) ? this.state : _.get(this.state, key, defaultValue); } set(key, value) { const prevValue = this.get(key); if (typeof value === 'object' && _.isEqual(value, prevValue)) { return this.state; } if (value === prevValue) { return this.state; } this.state = _.merge({}, this.state, _.set({}, key, value)); this.emit('change', this.state); return this.state; } unset(key) { let state = _.extend({}, this.state); _.unset(state, key); this.state = state; this.emit('change', this.state); return this.state; } replace(key, value) { const prevValue = this.get(key); if (typeof value === 'object' && _.isEqual(value, prevValue)) { return this.state; } if (value === prevValue) { return this.state; } this.unset(key); this.set(key, value); return this.state; } clear() { this.state = {}; this.emit('change', this.state); return this.state; } } export default ImmutableStore; ","import _ from 'lodash'; import events from 'events'; class ImmutableStore extends events.EventEmitter { state = {}; constructor(state = {}) { super(); this.state = state; } get(key, defaultValue) { return _.get(this.state, key, defaultValue); } set(key, value) { const prevValue = this.get(key); if (typeof value === 'object' && _.isEqual(value, prevValue)) { return this.state; } if (value === prevValue) { return this.state; } this.state = _.merge({}, this.state, _.set({}, key, value)); this.emit('change', this.state); return this.state; } unset(key) { let state = _.extend({}, this.state); _.unset(state, key); this.state = state; this.emit('change', this.state); return this.state; } replace(key, value) { const prevValue = this.get(key); if (typeof value === 'object' && _.isEqual(value, prevValue)) { return this.state; } if (value === prevValue) { return this.state; } this.unset(key); this.set(key, value); return this.state; } clear() { this.state = {}; this.emit('change', this.state); return this.state; } } export default ImmutableStore; " Refactor generation of posts into method,"import React, { Component } from 'react'; import { connect } from 'react-redux'; import { fetchPosts } from '../actions'; import Post from '../components/Post'; // Smart component class PostsContainer extends Component { componentWillMount() { const { fetchPosts } = this.props; fetchPosts(); } buildPosts(posts) { return posts.map(post => <Post post={post} key={post.id} /> ); } render() { const { posts } = this.props; return ( <div className=""article-listing""> {this.buildPosts(posts)} <nav> <ul className=""pager""> <li><a href=""#"">Older</a></li> <li className=""disabled""><a href=""#"">Newer</a></li> </ul> </nav> </div> ); } } function mapStateToProps(state) { return { posts: state.posts.posts, pageNum: state.posts.pageNum }; } export default connect( mapStateToProps, { fetchPosts } )(PostsContainer);","import React, { Component } from 'react'; import { connect } from 'react-redux'; import { fetchPosts } from '../actions'; import Post from '../components/Post'; // Smart component class PostsContainer extends Component { componentWillMount() { const { fetchPosts } = this.props; fetchPosts(); } buildPosts(posts) { } render() { const { posts } = this.props; return ( <div className=""article-listing""> {posts.map(post => <Post post={post} key={post.id} />)} {this.buildPosts(posts)} <nav> <ul className=""pager""> <li><a href=""#"">Older</a></li> <li className=""disabled""><a href=""#"">Newer</a></li> </ul> </nav> </div> ); } } function mapStateToProps(state) { return { posts: state.posts.posts, pageNum: state.posts.pageNum }; } export default connect( mapStateToProps, { fetchPosts } )(PostsContainer);" Change occurrence of person to tasks in deleteCommand class,"package seedu.address.logic.commands; import seedu.address.commons.core.Messages; import seedu.address.commons.core.UnmodifiableObservableList; import seedu.address.model.person.ReadOnlyPerson; import seedu.address.model.person.UniquePersonList.TaskNotFoundException; /** * Deletes a task identified using it's last displayed index from the task manager. */ public class DeleteCommand extends Command { public static final String COMMAND_WORD = ""delete""; public static final String MESSAGE_USAGE = COMMAND_WORD + "": Deletes the task identified by the index number used in the last task listing.\n"" + ""Parameters: INDEX (must be a positive integer)\n"" + ""Example: "" + COMMAND_WORD + "" 1""; public static final String MESSAGE_DELETE_TASK_SUCCESS = ""Deleted Task: %1$s""; public final int targetIndex; public DeleteCommand(int targetIndex) { this.targetIndex = targetIndex; } @Override public CommandResult execute() { UnmodifiableObservableList<ReadOnlyPerson> lastShownList = model.getFilteredPersonList(); if (lastShownList.size() < targetIndex) { indicateAttemptToExecuteIncorrectCommand(); return new CommandResult(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); } ReadOnlyPerson taskToDelete = lastShownList.get(targetIndex - 1); try { model.deleteTask(taskToDelete); } catch (TaskNotFoundException pnfe) { assert false : ""The target task cannot be missing""; } return new CommandResult(String.format(MESSAGE_DELETE_TASK_SUCCESS, taskToDelete)); } } ","package seedu.address.logic.commands; import seedu.address.commons.core.Messages; import seedu.address.commons.core.UnmodifiableObservableList; import seedu.address.model.person.ReadOnlyPerson; import seedu.address.model.person.UniquePersonList.PersonNotFoundException; /** * Deletes a person identified using it's last displayed index from the address book. */ public class DeleteCommand extends Command { public static final String COMMAND_WORD = ""delete""; public static final String MESSAGE_USAGE = COMMAND_WORD + "": Deletes the person identified by the index number used in the last person listing.\n"" + ""Parameters: INDEX (must be a positive integer)\n"" + ""Example: "" + COMMAND_WORD + "" 1""; public static final String MESSAGE_DELETE_PERSON_SUCCESS = ""Deleted Person: %1$s""; public final int targetIndex; public DeleteCommand(int targetIndex) { this.targetIndex = targetIndex; } @Override public CommandResult execute() { UnmodifiableObservableList<ReadOnlyPerson> lastShownList = model.getFilteredPersonList(); if (lastShownList.size() < targetIndex) { indicateAttemptToExecuteIncorrectCommand(); return new CommandResult(Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX); } ReadOnlyPerson personToDelete = lastShownList.get(targetIndex - 1); try { model.deletePerson(personToDelete); } catch (PersonNotFoundException pnfe) { assert false : ""The target person cannot be missing""; } return new CommandResult(String.format(MESSAGE_DELETE_PERSON_SUCCESS, personToDelete)); } } " "Include task fields into taskcard - index,task,tag,due,priority","package seedu.address.ui; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import seedu.address.model.task.ReadOnlyTask; public class TaskCard extends UiPart{ private static final String FXML = ""TaskListCard.fxml""; @FXML private HBox cardPane; @FXML private Label detail; @FXML private Label id; @FXML private Label dbd; @FXML private Label dbt; @FXML private Label priority; @FXML private Label tags; private ReadOnlyTask task; private int displayedIndex; public TaskCard(){ } public static TaskCard load(ReadOnlyTask task, int displayedIndex){ TaskCard card = new TaskCard(); card.task = task; card.displayedIndex = displayedIndex; return UiPartLoader.loadUiPart(card); } @FXML public void initialize() { detail.setText(task.getDetail().details); id.setText(displayedIndex + "". ""); dbd.setText(task.getDueByDate().getFriendlyString()); dbt.setText(task.getDueByTime().getFriendlyString()); priority.setText(task.getPriority().value); tags.setText(task.tagsString()); tags.setTextFill(Color.GOLD); } public HBox getLayout() { return cardPane; } @Override public void setNode(Node node) { cardPane = (HBox)node; } @Override public String getFxmlPath() { return FXML; } } ","package seedu.address.ui; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import seedu.address.model.task.ReadOnlyTask; public class TaskCard extends UiPart{ private static final String FXML = ""TaskListCard.fxml""; @FXML private HBox cardPane; @FXML private Label detail; @FXML private Label id; @FXML private Label dbd; @FXML private Label dbt; @FXML private Label priority; @FXML private Label tags; private ReadOnlyTask task; private int displayedIndex; public TaskCard(){ } public static TaskCard load(ReadOnlyTask task, int displayedIndex){ TaskCard card = new TaskCard(); card.task = task; card.displayedIndex = displayedIndex; return UiPartLoader.loadUiPart(card); } @FXML public void initialize() { detail.setText(task.getDetail().details); id.setText(displayedIndex + "". ""); dbd.setText(task.getDueByDate().getFriendlyString()); dbt.setText(task.getDueByTime().getFriendlyString()); priority.setText(task.getPriority().value); tags.setText(task.tagsString()); } public HBox getLayout() { return cardPane; } @Override public void setNode(Node node) { cardPane = (HBox)node; } @Override public String getFxmlPath() { return FXML; } } " Move fields to top and give explicit name to id,"package com.alexstyl.specialdates.events; import android.support.annotation.ColorRes; import android.support.annotation.StringRes; import com.alexstyl.specialdates.R; import java.util.HashMap; import java.util.Map; public enum EventType { BIRTHDAY(EventColumns.TYPE_BIRTHDAY, R.string.birthday, R.color.birthday_red), NAMEDAY(EventColumns.TYPE_NAMEDAY, R.string.nameday, R.color.nameday_blue); private static final Map<Integer, EventType> map; private final int eventTypeId; private final int eventNameRes; private final int eventColorRes; static { map = new HashMap<>(); for (EventType eventType : values()) { map.put(eventType.eventTypeId, eventType); } } public static EventType fromId(@EventTypeId int eventTypeId) { if (map.containsKey(eventTypeId)) { return map.get(eventTypeId); } throw new IllegalArgumentException(""No event type with eventTypeId "" + eventTypeId); } EventType(@EventTypeId int eventTypeId, @StringRes int nameResId, @ColorRes int colorResId) { this.eventTypeId = eventTypeId; this.eventNameRes = nameResId; this.eventColorRes = colorResId; } @StringRes public int nameRes() { return eventNameRes; } @ColorRes public int getColorRes() { return eventColorRes; } } ","package com.alexstyl.specialdates.events; import android.support.annotation.ColorRes; import android.support.annotation.StringRes; import com.alexstyl.specialdates.R; import java.util.HashMap; import java.util.Map; public enum EventType { BIRTHDAY(EventColumns.TYPE_BIRTHDAY, R.string.birthday, R.color.birthday_red), NAMEDAY(EventColumns.TYPE_NAMEDAY, R.string.nameday, R.color.nameday_blue); private static final Map<Integer, EventType> map; static { map = new HashMap<>(); for (EventType eventType : values()) { map.put(eventType.id, eventType); } } private final int id; private final int eventNameRes; private final int eventColorRes; EventType(@EventTypeId int id, @StringRes int nameResId, @ColorRes int colorResId) { this.id = id; this.eventNameRes = nameResId; this.eventColorRes = colorResId; } @StringRes public int nameRes() { return eventNameRes; } @ColorRes public int getColorRes() { return eventColorRes; } public static EventType fromId(@EventTypeId int eventTypeId) { if (map.containsKey(eventTypeId)) { return map.get(eventTypeId); } throw new IllegalArgumentException(""No event type with id "" + eventTypeId); } } " Set platform instead of statuses when creating or updating entity type.,"<?php namespace Botamp\Botamp\ApiResource; class EntityType extends AbstractApiResource { private $configHelper; public function __construct(\Botamp\Botamp\Helper\ConfigHelper $configHelper) { parent::__construct($configHelper); $this->configHelper = $configHelper; } public function createOrUpdate() { try { $entityType = $this->botamp->entityTypes->get('order'); $this->update($entityType); } catch (\Botamp\Exceptions\NotFound $e) { $this->create(); } $this->configHelper->setEntityTypeCreated(); } private function create() { $this->botamp->entityTypes->create([ 'name' => 'order', 'singular_label' => 'Order', 'plural_label' => 'Orders', 'platform' => 'magento' ]); } private function update($entityType) { $entityTypeAttributes = $entityType->getBody()['data']['attributes']; if ($entityTypeAttributes['platform'] !== 'magento') { $entityTypeAttributes['platform'] = 'magento'; $entityTypeId = $entityType->getBody()['data']['id']; $this->botamp->entityTypes->update($entityTypeId, $entityTypeAttributes); } } public function created() { return $this->configHelper->entityTypeCreated(); } } ","<?php namespace Botamp\Botamp\ApiResource; class EntityType extends AbstractApiResource { private $magentoOrderStatuses = []; private $configHelper; public function __construct(\Botamp\Botamp\Helper\ConfigHelper $configHelper) { parent::__construct($configHelper); $this->magentoOrderStatuses = [ 'processing', 'pending_payment', 'payment_review', 'new', 'holded', 'complete', 'closed', 'canceled' ]; $this->configHelper = $configHelper; } public function createOrUpdate() { try { $entityType = $this->botamp->entityTypes->get('order'); $this->update($entityType); } catch (\Botamp\Exceptions\NotFound $e) { $this->create(); } $this->configHelper->setEntityTypeCreated(); } private function create() { $this->botamp->entityTypes->create([ 'name' => 'order', 'singular_label' => 'Order', 'plural_label' => 'Orders', 'statuses' => $this->magentoOrderStatuses ]); } private function update($entityType) { $entityTypeAttributes = $entityType->getBody()['data']['attributes']; if ($entityTypeAttributes['statuses'] !== $this->magentoOrderStatuses) { $entityTypeAttributes['statuses'] = $this->magentoOrderStatuses; $entityTypeId = $entityType->getBody()['data']['id']; $this->botamp->entityTypes->update($entityTypeId, $entityTypeAttributes); } } public function created() { return $this->configHelper->entityTypeCreated(); } } " Update Service Provider to 5.4,"<?php namespace Jp\Twilio; use Illuminate\Support\ServiceProvider; class TwilioServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Register the service provider. * * @return void */ public function register() { // Register manager for usage with the Facade. $this->app->singleton('twilio', function () { $config = \Config::get('twilio'); if (!array($config)) { throw new \Exception('Twilio: Invalid configuration.'); } return new Twilio($config); }); // $this->app['twilio'] = $this->app->share(function($app) // { // $config = \Config::get('services.twilio'); // if (!array($config)) { // throw new \Exception('Twilio: Invalid configuration.'); // } // return new Twilio($config); // }); // // Register Twilio Test SMS Command // $this->app['twilio.sms'] = $this->app->share(function($app) { // return new Commands\TwilioSmsCommand(); // }); // // Register Twilio Test Call Command // $this->app['twilio.call'] = $this->app->share(function($app) { // return new Commands\TwilioCallCommand(); // }); // $this->commands( // 'twilio.sms', // 'twilio.call' // ); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('twilio'); } } ","<?php namespace Jp\Twilio; use Illuminate\Support\ServiceProvider; class TwilioServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Register the service provider. * * @return void */ public function register() { $this->app['twilio'] = $this->app->share(function($app) { $config = \Config::get('services.twilio'); if (!array($config)) { throw new \Exception('Twilio: Invalid configuration.'); } return new Twilio($config); }); // Register Twilio Test SMS Command $this->app['twilio.sms'] = $this->app->share(function($app) { return new Commands\TwilioSmsCommand(); }); // Register Twilio Test Call Command $this->app['twilio.call'] = $this->app->share(function($app) { return new Commands\TwilioCallCommand(); }); $this->commands( 'twilio.sms', 'twilio.call' ); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('twilio'); } } " HEXDEV-150: Update description of intercept term.,"package hex.schemas; import hex.tree.SharedTreeModel; import water.api.API; import water.api.ModelOutputSchema; import water.api.ModelSchema; import water.api.TwoDimTableBase; public class SharedTreeModelV3<M extends SharedTreeModel<M, P, O>, S extends SharedTreeModelV3<M, S, P, PS, O, OS>, P extends SharedTreeModel.SharedTreeParameters, PS extends SharedTreeV3.SharedTreeParametersV3<P, PS>, O extends SharedTreeModel.SharedTreeOutput, OS extends SharedTreeModelV3.SharedTreeModelOutputV3<O,OS>> extends ModelSchema<M, S, P, PS, O, OS> { public static class SharedTreeModelOutputV3<O extends SharedTreeModel.SharedTreeOutput, SO extends SharedTreeModelOutputV3<O,SO>> extends ModelOutputSchema<O, SO> { @API(help=""Variable Importances"", direction=API.Direction.OUTPUT) TwoDimTableBase variable_importances; @API(help=""The Intercept term, the initial model function value to which trees make adjustments"", direction=API.Direction.OUTPUT) double initF; } } ","package hex.schemas; import hex.tree.SharedTreeModel; import water.api.API; import water.api.ModelOutputSchema; import water.api.ModelSchema; import water.api.TwoDimTableBase; public class SharedTreeModelV3<M extends SharedTreeModel<M, P, O>, S extends SharedTreeModelV3<M, S, P, PS, O, OS>, P extends SharedTreeModel.SharedTreeParameters, PS extends SharedTreeV3.SharedTreeParametersV3<P, PS>, O extends SharedTreeModel.SharedTreeOutput, OS extends SharedTreeModelV3.SharedTreeModelOutputV3<O,OS>> extends ModelSchema<M, S, P, PS, O, OS> { public static class SharedTreeModelOutputV3<O extends SharedTreeModel.SharedTreeOutput, SO extends SharedTreeModelOutputV3<O,SO>> extends ModelOutputSchema<O, SO> { @API(help=""Variable Importances"", direction=API.Direction.OUTPUT) TwoDimTableBase variable_importances; @API(help=""The Intercept term, the initial predicted value to which trees make adjustments"", direction=API.Direction.OUTPUT) double initF; } } " Add filters controller missing definition,"'use strict'; var angular , DashboardController , FiltersController , ChartController; angular.module('wharf', ['ui.router', 'wharf.controllers']); angular.module('wharf').config(function($stateProvider, $urlRouterProvider) { $stateProvider.state('dashboard', { abstract: true, url: '/dashboard', template: '<ui-view/>' }).state('dashboard.details', { url: '/details', views: { '': { templateUrl: '/js/templates/dashboard.html', controller: 'DashboardController as dashboardController' }, 'filters@dashboard.details': { templateUrl: '/js/templates/dashboard/_filters.html', controller: 'FiltersController as filtersController' }, 'chart@dashboard.details': { templateUrl: '/js/templates/dashboard/_chart.html', controller: 'ChartController as chartController' } } }); $urlRouterProvider.otherwise('/'); }); angular.module('wharf.controllers', []); angular.module('wharf.controllers').controller('DashboardController', DashboardController); angular.module('wharf.controllers').controller('FiltersController', FiltersController); angular.module('wharf.controllers').controller('ChartController', ChartController); ","'use strict'; var angular , DashboardController , ChartController; angular.module('wharf', ['ui.router', 'wharf.controllers']); angular.module('wharf').config(function($stateProvider, $urlRouterProvider) { $stateProvider.state('dashboard', { abstract: true, url: '/dashboard', template: '<ui-view/>' }).state('dashboard.details', { url: '/details', views: { '': { templateUrl: '/js/templates/dashboard.html', controller: 'DashboardController as dashboardController' }, 'filters@dashboard.details': { templateUrl: '/js/templates/dashboard/_filters.html', controller: 'FiltersController as filtersController' }, 'chart@dashboard.details': { templateUrl: '/js/templates/dashboard/_chart.html', controller: 'ChartController as chartController' } } }); $urlRouterProvider.otherwise('/'); }); angular.module('wharf.controllers', []); angular.module('wharf.controllers').controller('DashboardController', DashboardController); angular.module('wharf.controllers').controller('FiltersController', FiltersController); angular.module('wharf.controllers').controller('ChartController', ChartController); " Fix the stupid flashing interval bug.,"index = 0; var masterInterval; slogans = [ ""when mission critical just doesn't make any sense."", ""when you just don't need multi-master replication."", ""when those other databases are just too relational."", ""when you're not quite sure what web scale means."", ""when determinism really isn't your thing."", ""when JSON is holding you back."", ""when you want to take a chance."", ""when persistence means turning fsync on."" ]; function fade_change(element, text) { var op = 1; var timer = setInterval(function () { if (op <= 0.1){ clearInterval(timer); element.innerHTML = text; element.style.opacity = 0; fade_in(element); } element.style.opacity = op; op -= op * 0.1; }, 50); } function fade_in(element) { var op = 0; var timer = setInterval(function () { if (op >= 1.0){ clearInterval(timer); element.style.opacity = 1.0; } element.style.opacity = op; op += 0.05; }, 50); } function change_text() { index++; change_me = document.getElementById(""changing_text""); fade_change(change_me, slogans[index % slogans.length]); } start_change = function() { masterInterval = window.setInterval(change_text, 6000); } stop_change = function() { window.clearInterval(masterInterval); } window.onload = function() { start_change(); }; window.addEventListener('blur', stop_change); window.addEventListener('focus', start_change); ","index = 0; slogans = [ ""when mission critical just doesn't make any sense."", ""when you just don't need multi-master replication."", ""when those other databases are just too relational."", ""when you're not quite sure what web scale means."", ""when determinism really isn't your thing."", ""when JSON is holding you back."", ""when you want to take a chance."", ""when persistence means turning fsync on."" ]; function fade_change(element, text) { var op = 1; var timer = setInterval(function () { if (op <= 0.1){ clearInterval(timer); element.innerHTML = text; element.style.opacity = 0; fade_in(element); } element.style.opacity = op; op -= op * 0.1; }, 50); } function fade_in(element) { var op = 0; var timer = setInterval(function () { if (op >= 1.0){ clearInterval(timer); element.style.opacity = 1.0; } element.style.opacity = op; op += 0.05; }, 50); } function change_text() { index++; change_me = document.getElementById(""changing_text""); fade_change(change_me, slogans[index % slogans.length]); } window.onload = function() { setInterval(change_text, 6000); }; " Increase version due to change in streamed apps management,"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.3"" 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='amol@turbogears.org', 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.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='amol@turbogears.org', 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: -*- """""", ) " Fix typo in mapping array key.,"<?php namespace Borfast\Socializr; class Profile { public $provider; public $id; public $email; public $name; public $first_name; public $middle_name; public $last_name; public $username; public $link; public $raw_response; public $avatar; /** * Create a new Profile object based on an array of attributes and a mapping * from those attributes to the Profile object's attributes. * The $mapping array should have this format (example for Facebook): * $mapping = [ * 'id' => 'id', * 'email' => 'email', * 'name' => 'name', * 'first_name' => 'first_name', * 'middle_name' => 'middle_name', * 'last_name' => 'last_name', * 'username' => 'username', * 'link' => 'link' * ]; * The keys are the name of the Profile object attributes, while the values * are the key of that attribute in the $attributes array. Like so: * ['profile_object_attribute' => 'key_in_attributes_array'] * * @author Raúl Santos */ public static function create(array $mapping, array $attributes) { $profile = new Profile; foreach ($mapping as $key => $name) { $profile->$key = (isset($attributes[$name])) ? $attributes[$name] : null; } return $profile; } } ","<?php namespace Borfast\Socializr; class Profile { public $provider; public $id; public $email; public $name; public $first_name; public $middle_name; public $last_name; public $username; public $link; public $raw_response; public $avatar; /** * Create a new Profile object based on an array of attributes and a mapping * from those attributes to the Profile object's attributes. * The $mapping array should have this format: * $mapping = [ * 'id' => 'id', * 'email' => 'email', * 'name' => 'name', * 'first_name' => 'firs_name', * 'middle_name' => 'middle_name', * 'last_name' => 'last_name', * 'username' => 'username', * 'link' => 'link' * ]; * The keys are the name of the Profile object attributes, while the values * are the key of that attribute in the $attributes array. Like so: * ['profile_object_attribute' => 'key_in_attributes_array'] * * @author Raúl Santos */ public static function create(array $mapping, array $attributes) { $profile = new Profile; foreach ($mapping as $key => $name) { $profile->$key = (isset($attributes[$name])) ? $attributes[$name] : null; } return $profile; } } " Add count of how many messages have been ignored to rate limiter,"package io.tetrapod.core.utils; /** * A rate gauge that keeps a history of event times */ public class RateLimiter { protected final long[] samples; protected int cur = -1; protected int len; protected int perMillis; // If we're currently limiting, how many have been ignored during this period of limiting. protected int ignoredCount; public RateLimiter(int max, int perMillis) { this.samples = new long[max]; this.perMillis = perMillis; this.ignoredCount = 0; } public synchronized void mark() { cur = (cur + 1) % samples.length; samples[cur] = System.currentTimeMillis(); len = Math.min(len + 1, samples.length); } public synchronized Long getLastValue() { if (len > 0) { return samples[cur]; } else { return null; } } public synchronized Long getOldestValue() { if (len > 0) { if (len < samples.length) { return samples[0]; } else { return samples[(cur + 1) % samples.length]; } } else { return null; } } public synchronized int getLength() { return len; } public synchronized boolean shouldLimit() { if (len >= samples.length) { if ((getLastValue() - getOldestValue()) < perMillis) { ignoredCount++; return true; } else { ignoredCount = 0; return false; } } else { ignoredCount = 0; return false; } } public synchronized int getIgnoreCount() { return ignoredCount; } } ","package io.tetrapod.core.utils; /** * A rate gauge that keeps a history of event times */ public class RateLimiter { protected final long[] samples; protected int cur = -1; protected int len; protected int perMillis; public RateLimiter(int max, int perMillis) { this.samples = new long[max]; this.perMillis = perMillis; } public synchronized void mark() { cur = (cur + 1) % samples.length; samples[cur] = System.currentTimeMillis(); len = Math.min(len + 1, samples.length); } public synchronized Long getLastValue() { if (len > 0) { return samples[cur]; } else { return null; } } public synchronized Long getOldestValue() { if (len > 0) { if (len < samples.length) { return samples[0]; } else { return samples[(cur + 1) % samples.length]; } } else { return null; } } public synchronized int getLength() { return len; } public synchronized boolean shouldLimit() { if (len >= samples.length) { return (getLastValue() - getOldestValue()) < perMillis; } else { return false; } } } " "Use id, do not assemble it manually","var MutationTable = function () { var element var mutations function detailFormatter(index, row_data, element) { var mutation_id = row_data._id var mutation = mutations[mutation_id] return nunjucks.render( 'row_details.njk', {mutation: mutation} ) } function getMutationRow(mutation_id) { return $('#' + mutation_id) } var publicSpace = { init: function(table_element, mutations_list) { mutations = {} for(var i = 0; i < mutations_list.length; i++) { var mutation = mutations_list[i] mutations[mutation.pos + mutation.alt] = mutation } element = table_element element.bootstrapTable({ detailFormatter: detailFormatter, onClickRow: function(row_data){ publicSpace.expandRow(row_data._id) } }) if(window.location.hash) { publicSpace.expandRow(window.location.hash.substring(1)) } }, expandRow: function(mutation_id) { element.bootstrapTable( 'expandRow', getMutationRow(mutation_id).data('index') ) } } return publicSpace } ","var MutationTable = function () { var element var mutations function detailFormatter(index, row_data, element) { var mutation_id = row_data._id var mutation = mutations[mutation_id] return nunjucks.render( 'row_details.njk', {mutation: mutation} ) } function getMutationRow(mutation_id) { return $('#' + mutation_id) } var publicSpace = { init: function(table_element, mutations_list) { mutations = {} for(var i = 0; i < mutations_list.length; i++) { var mutation = mutations_list[i] mutations[mutation.pos + mutation.alt] = mutation } element = table_element element.bootstrapTable({ detailFormatter: detailFormatter, onClickRow: function(row_data){ publicSpace.expandRow(row_data[0] + row_data[2]) } }) if(window.location.hash) { publicSpace.expandRow(window.location.hash.substring(1)) } }, expandRow: function(mutation_id) { element.bootstrapTable( 'expandRow', getMutationRow(mutation_id).data('index') ) } } return publicSpace } " Test recommendation via article class,"#!/usr/bin/env python # -*- coding: utf-8 -*- from django.test import TestCase from opps.articles.models import Article, Post class ArticleModelTest(TestCase): fixtures = ['tests/initial_data.json'] def setUp(self): self.article = Article.objects.get(id=1) def test_child_class(self): self.assertTrue(self.article.child_class) self.assertEqual(self.article.child_class, 'Post') def test_get_absolute_url(self): self.assertEqual(self.article.get_absolute_url(), u'/channel-01/test-post-application') self.assertEqual(self.article.get_absolute_url(), ""/{0}/{1}"".format(self.article.channel.long_slug, self.article.slug)) def test_recommendation(self): self.assertEqual([], self.article.recommendation()) class PostModelTest(TestCase): fixtures = ['tests/initial_data.json'] def setUp(self): self.post = Post.objects.get(id=1) def test_basic_post_exist(self): post = Post.objects.all() self.assertTrue(post) self.assertTrue(post[0], self.post) self.assertEqual(len(post), 1) self.assertEqual(post[0].slug, u'test-post-application') self.assertEqual(post[0].title, u'test post application') self.assertTrue(post[0].short_url) ","#!/usr/bin/env python # -*- coding: utf-8 -*- from django.test import TestCase from opps.articles.models import Article, Post class ArticleModelTest(TestCase): fixtures = ['tests/initial_data.json'] def setUp(self): self.article = Article.objects.get(id=1) def test_child_class(self): self.assertTrue(self.article.child_class) self.assertEqual(self.article.child_class, 'Post') def test_get_absolute_url(self): self.assertEqual(self.article.get_absolute_url(), u'/channel-01/test-post-application') self.assertEqual(self.article.get_absolute_url(), ""/{0}/{1}"".format(self.article.channel.long_slug, self.article.slug)) class PostModelTest(TestCase): fixtures = ['tests/initial_data.json'] def setUp(self): self.post = Post.objects.get(id=1) def test_basic_post_exist(self): post = Post.objects.all() self.assertTrue(post) self.assertTrue(post[0], self.post) self.assertEqual(len(post), 1) self.assertEqual(post[0].slug, u'test-post-application') self.assertEqual(post[0].title, u'test post application') self.assertTrue(post[0].short_url) " Use appropriate key if isMultiple is true,"<?php namespace Nails\GeoIp\Settings; use Nails\GeoIp\Service\Driver; use Nails\Common\Helper\Form; use Nails\Common\Interfaces; use Nails\Common\Service\FormValidation; use Nails\Components\Setting; use Nails\GeoIp\Constants; use Nails\Factory; /** * Class General * * @package Nails\GeoIp\Settings */ class General implements Interfaces\Component\Settings { /** * @inheritDoc */ public function getLabel(): string { return 'Geo-IP'; } // -------------------------------------------------------------------------- /** * @inheritDoc */ public function getPermissions(): array { return []; } // -------------------------------------------------------------------------- /** * @inheritDoc */ public function get(): array { /** @var Driver $oDriverService */ $oDriverService = Factory::service('Driver', Constants::MODULE_SLUG); /** @var Setting $oDriver */ $oDriver = Factory::factory('ComponentSetting'); $oDriver ->setKey($oDriverService->isMultiple() ? $oDriverService->getSettingKey() . '[]' : $oDriverService->getSettingKey() ) ->setType($oDriverService->isMultiple() ? Form::FIELD_DROPDOWN_MULTIPLE : Form::FIELD_DROPDOWN ) ->setLabel('Driver') ->setFieldset('Driver') ->setClass('select2') ->setOptions(['' => 'No Driver Selected'] + $oDriverService->getAllFlat()) ->setValidation([ FormValidation::RULE_REQUIRED, ]); return [ $oDriver, ]; } } ","<?php namespace Nails\GeoIp\Settings; use Nails\GeoIp\Service\Driver; use Nails\Common\Helper\Form; use Nails\Common\Interfaces; use Nails\Common\Service\FormValidation; use Nails\Components\Setting; use Nails\GeoIp\Constants; use Nails\Factory; /** * Class General * * @package Nails\GeoIp\Settings */ class General implements Interfaces\Component\Settings { /** * @inheritDoc */ public function getLabel(): string { return 'Geo-IP'; } // -------------------------------------------------------------------------- /** * @inheritDoc */ public function getPermissions(): array { return []; } // -------------------------------------------------------------------------- /** * @inheritDoc */ public function get(): array { /** @var Driver $oDriverService */ $oDriverService = Factory::service('Driver', Constants::MODULE_SLUG); /** @var Setting $oDriver */ $oDriver = Factory::factory('ComponentSetting'); $oDriver ->setKey($oDriverService->getSettingKey()) ->setType($oDriverService->isMultiple() ? Form::FIELD_DROPDOWN_MULTIPLE : Form::FIELD_DROPDOWN ) ->setLabel('Driver') ->setFieldset('Driver') ->setClass('select2') ->setOptions(['' => 'No Driver Selected'] + $oDriverService->getAllFlat()) ->setValidation([ FormValidation::RULE_REQUIRED, ]); return [ $oDriver, ]; } } " Fix migrations (filename default value),"# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings import django.utils.timezone import user_clipboard.models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Clipboard', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('file', models.FileField(max_length=128, upload_to=user_clipboard.models.new_file_upload_to)), ('filename', models.CharField(default='', max_length=256, editable=False)), ('is_image', models.BooleanField(default=False, db_index=True, editable=False)), ('date_created', models.DateTimeField(default=django.utils.timezone.now, editable=False, db_index=True)), ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)), ], options={ 'verbose_name': 'Clipboard Item', 'verbose_name_plural': 'Clipboard', }, ), ] ","# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings import django.utils.timezone import user_clipboard.models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Clipboard', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('file', models.FileField(max_length=128, upload_to=user_clipboard.models.new_file_upload_to)), ('filename', models.CharField(default=b'', max_length=256, editable=False)), ('is_image', models.BooleanField(default=False, db_index=True, editable=False)), ('date_created', models.DateTimeField(default=django.utils.timezone.now, editable=False, db_index=True)), ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)), ], options={ 'verbose_name': 'Clipboard Item', 'verbose_name_plural': 'Clipboard', }, ), ] " Add a check for AzureAdapter existance,"<?php namespace BsbFlysystem\Adapter\Factory; use BsbFlysystem\Exception\RequirementsException; use WindowsAzure\Common\ServicesBuilder; use League\Flysystem\Azure\AzureAdapter as Adapter; use UnexpectedValueException; use Zend\ServiceManager\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; class AzureAdapterFactory extends AbstractAdapterFactory implements FactoryInterface { /** * @inheritdoc */ public function doCreateService(ServiceLocatorInterface $serviceLocator) { if (!class_exists('League\Flysystem\Azure\AzureAdapter')) { throw new RequirementsException( ['league/flysystem-azure'], 'Azure' ); } $endpoint = sprintf( 'DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s', $this->options['account-name'], $this->options['account-key'] ); $blobRestProxy = ServicesBuilder::getInstance()->createBlobService($endpoint); $adapter = new Adapter($blobRestProxy, $this->options['container']); return $adapter; } /** * @inheritdoc */ protected function validateConfig() { if (!isset($this->options['account-name'])) { throw new UnexpectedValueException(""Missing 'account-name' as option""); } if (!isset($this->options['account-key'])) { throw new UnexpectedValueException(""Missing 'account-key' as option""); } if (!isset($this->options['container'])) { throw new UnexpectedValueException(""Missing 'container' as option""); } } } ","<?php namespace BsbFlysystem\Adapter\Factory; use WindowsAzure\Common\ServicesBuilder; use League\Flysystem\Azure\AzureAdapter as Adapter; use UnexpectedValueException; use Zend\ServiceManager\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; class AzureAdapterFactory extends AbstractAdapterFactory implements FactoryInterface { /** * @inheritdoc */ public function doCreateService(ServiceLocatorInterface $serviceLocator) { $endpoint = sprintf( 'DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s', $this->options['account-name'], $this->options['account-key'] ); $blobRestProxy = ServicesBuilder::getInstance()->createBlobService($endpoint); $adapter = new Adapter($blobRestProxy, $this->options['container']); return $adapter; } /** * @inheritdoc */ protected function validateConfig() { if (!isset($this->options['account-name'])) { throw new UnexpectedValueException(""Missing 'account-name' as option""); } if (!isset($this->options['account-key'])) { throw new UnexpectedValueException(""Missing 'account-key' as option""); } if (!isset($this->options['container'])) { throw new UnexpectedValueException(""Missing 'container' as option""); } } } " Order blobs in the playlist API by lowest position first,"from django.http import JsonResponse from django.views.generic import ListView from .models import Blob class PodcastBlobList(ListView): model = Blob def get_queryset(self): qs = super(PodcastBlobList, self).get_queryset() qs = qs.filter(content_type__app_label=self.kwargs['app_label'], content_type__model=self.kwargs['model'], object_id=self.kwargs['id']) qs = qs.order_by('position') qs = qs.select_related('content_type').prefetch_related('content_object') return qs def get_blob_data(self, blob): return { 'id': blob.pk, 'podcast': blob.content_object.get_blobs_url(), 'title': blob.content_object.title, 'image': blob.content_object.image.url if blob.content_object.image else None, 'url': blob.link, } def get_context_data(self, **kwargs): kwargs['blob_list'] = [self.get_blob_data(blob) for blob in self.object_list] return super(PodcastBlobList, self).get_context_data(**kwargs) def render_to_response(self, context, **response_kwargs): return JsonResponse(context['blob_list'], safe=False) ","from django.http import JsonResponse from django.views.generic import ListView from .models import Blob class PodcastBlobList(ListView): model = Blob def get_queryset(self): qs = super(PodcastBlobList, self).get_queryset() qs = qs.filter(content_type__app_label=self.kwargs['app_label'], content_type__model=self.kwargs['model'], object_id=self.kwargs['id']) qs = qs.order_by('-position') qs = qs.select_related('content_type').prefetch_related('content_object') return qs def get_blob_data(self, blob): return { 'id': blob.pk, 'podcast': blob.content_object.get_blobs_url(), 'title': blob.content_object.title, 'image': blob.content_object.image.url if blob.content_object.image else None, 'url': blob.link, } def get_context_data(self, **kwargs): kwargs['blob_list'] = [self.get_blob_data(blob) for blob in self.object_list] return super(PodcastBlobList, self).get_context_data(**kwargs) def render_to_response(self, context, **response_kwargs): return JsonResponse(context['blob_list'], safe=False) " Update unit tests with new query helper names,"# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> import unittest import mock from ggrc.converters import query_helper class TestQueryHelper(unittest.TestCase): def test_expression_keys(self): """""" test expression keys function Make sure it works with: empty query simple query complex query invalid complex query """""" # pylint: disable=protected-access # needed for testing protected function inside the query helper query = mock.MagicMock() helper = query_helper.QueryHelper(query) expressions = [ (set(), {}), (set([""key_1""]), { ""left"": ""key_1"", ""op"": {""name"": ""=""}, ""right"": """", }), (set([""key_1"", ""key_2""]), { ""left"": { ""left"": ""key_2"", ""op"": {""name"": ""=""}, ""right"": """", }, ""op"": {""name"": ""AND""}, ""right"": { ""left"": ""key_1"", ""op"": {""name"": ""!=""}, ""right"": """", }, }), (set(), { ""left"": { ""left"": ""5"", ""op"": {""name"": ""=""}, ""right"": """", }, ""op"": {""name"": ""=""}, ""right"": { ""left"": ""key_1"", ""op"": {""name"": ""!=""}, ""right"": """", }, }), ] for expected_result, expression in expressions: self.assertEqual(expected_result, helper._expression_keys(expression)) ","# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> import unittest import mock from ggrc.converters import query_helper class TestQueryHelper(unittest.TestCase): def test_expression_keys(self): """""" test expression keys function Make sure it works with: empty query simple query complex query invalid complex query """""" query = mock.MagicMock() helper = query_helper.QueryHelper(query) expressions = [ (set(), {}), (set([""key_1""]), { ""left"": ""key_1"", ""op"": {""name"": ""=""}, ""right"": """", }), (set([""key_1"", ""key_2""]), { ""left"": { ""left"": ""key_2"", ""op"": {""name"": ""=""}, ""right"": """", }, ""op"": {""name"": ""AND""}, ""right"": { ""left"": ""key_1"", ""op"": {""name"": ""!=""}, ""right"": """", }, }), (set(), { ""left"": { ""left"": ""5"", ""op"": {""name"": ""=""}, ""right"": """", }, ""op"": {""name"": ""=""}, ""right"": { ""left"": ""key_1"", ""op"": {""name"": ""!=""}, ""right"": """", }, }), ] for expected_result, expression in expressions: self.assertEqual(expected_result, helper.expression_keys(expression)) " Fix error from removed api after upgrading jquery," define([], function() { 'use strict'; return withAsyncQueue; function withAsyncQueue() { this.before('initialize', function() { var self = this, deferreds = {}, stacks = {}; this.setupAsyncQueue = function(name) { var stack = stacks[name] = [], objectData; self[name + 'Ready'] = function(callback) { if (callback) { // Legacy non-promise if (objectData) { callback.call(self, objectData); } else { stack.push(callback); } } else { return deferreds[name] || (deferreds[name] = $.Deferred()); } }; self[name + 'IsReady'] = function() { if (deferreds[name]) { return deferreds[name].state() == 'resolved'; } return objectData !== undefined; }; self[name + 'MarkReady'] = function(data) { if (!data) throw ""No object passed to "" + name + ""MarkReady""; if (deferreds[name]) { deferreds[name].resolve(data); } else { deferreds[name] = $.Deferred(); deferreds[name].resolve(data); } objectData = data; stack.forEach(function(c) { c.call(self, objectData); }); stack.length = 0; }; self[name + 'Unload'] = function() { deferreds[name] = null; objectData = null; }; }; }); } }); "," define([], function() { 'use strict'; return withAsyncQueue; function withAsyncQueue() { this.before('initialize', function() { var self = this, deferreds = {}, stacks = {}; this.setupAsyncQueue = function(name) { var stack = stacks[name] = [], objectData; self[name + 'Ready'] = function(callback) { if (callback) { // Legacy non-promise if (objectData) { callback.call(self, objectData); } else { stack.push(callback); } } else { return deferreds[name] || (deferreds[name] = $.Deferred()); } }; self[name + 'IsReady'] = function() { if (deferreds[name]) { return deferreds[name].isResolved(); } return objectData !== undefined; }; self[name + 'MarkReady'] = function(data) { if (!data) throw ""No object passed to "" + name + ""MarkReady""; if (deferreds[name]) { deferreds[name].resolve(data); } else { deferreds[name] = $.Deferred(); deferreds[name].resolve(data); } objectData = data; stack.forEach(function(c) { c.call(self, objectData); }); stack.length = 0; }; self[name + 'Unload'] = function() { deferreds[name] = null; objectData = null; }; }; }); } }); " Use latest version of pcpp that's actually on pypi,"from setuptools import setup setup(name='fortdepend', version='0.1.0', description='Automatically generate Fortran dependencies', author='Peter Hill', author_email='peter@fusionplasma.co.uk', url='https://github.com/ZedThree/fort_depend.py/', download_url='https://github.com/ZedThree/fort_depend.py/tarball/0.1.0', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Fortran', ], packages=['fortdepend'], install_requires=[ 'colorama >= 0.3.9', 'pcpp >= 1.1.0' ], extras_requires={ 'tests': ['pytest >= 3.3.0'], 'docs': [ 'sphinx >= 1.4', 'sphinx-argparse >= 0.2.3' ], }, keywords=['build', 'dependencies', 'fortran'], entry_points={ 'console_scripts': [ 'fortdepend = fortdepend.__main__:main', ], }, ) ","from setuptools import setup setup(name='fortdepend', version='0.1.0', description='Automatically generate Fortran dependencies', author='Peter Hill', author_email='peter@fusionplasma.co.uk', url='https://github.com/ZedThree/fort_depend.py/', download_url='https://github.com/ZedThree/fort_depend.py/tarball/0.1.0', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Fortran', ], packages=['fortdepend'], install_requires=[ 'colorama >= 0.3.9', 'pcpp >= 1.1.1' ], extras_requires={ 'tests': ['pytest >= 3.3.0'], 'docs': [ 'sphinx >= 1.4', 'sphinx-argparse >= 0.2.3' ], }, keywords=['build', 'dependencies', 'fortran'], entry_points={ 'console_scripts': [ 'fortdepend = fortdepend.__main__:main', ], }, ) " Refactor compiler pass classes for consistency.,"<?php /** * @author Igor Nikolaev <igor.sv.n@gmail.com> * @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; /** * Add dashboard widgets compiler pass */ class AddDashboardWidgetsPass implements CompilerPassInterface { const DASHBOARD_ID = 'darvin_admin.dashboard.dashboard'; const TAG_DASHBOARD_WIDGET = 'darvin_admin.dashboard_widget'; /** * {@inheritdoc} */ public function process(ContainerBuilder $container) { if (!$container->hasDefinition(self::DASHBOARD_ID)) { return; } $widgetIds = $container->findTaggedServiceIds(self::TAG_DASHBOARD_WIDGET); if (empty($widgetIds)) { return; } $sorter = new TaggedServiceIdsSorter(); $sorter->sort($widgetIds); $dashboardDefinition = $container->getDefinition(self::DASHBOARD_ID); foreach ($widgetIds as $id => $attr) { $dashboardDefinition->addMethodCall('addWidget', array( new Reference($id), )); } } } ","<?php /** * @author Igor Nikolaev <igor.sv.n@gmail.com> * @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; /** * Add dashboard widgets compiler pass */ class AddDashboardWidgetsPass implements CompilerPassInterface { const DASHBOARD_ID = 'darvin_admin.dashboard.dashboard'; const TAG_DASHBOARD_WIDGET = 'darvin_admin.dashboard_widget'; /** * {@inheritdoc} */ public function process(ContainerBuilder $container) { if (!$container->hasDefinition(self::DASHBOARD_ID)) { return; } $widgetIds = $container->findTaggedServiceIds(self::TAG_DASHBOARD_WIDGET); if (empty($widgetIds)) { return; } $taggedServiceIdsSorter = new TaggedServiceIdsSorter(); $taggedServiceIdsSorter->sort($widgetIds); $dashboardDefinition = $container->getDefinition(self::DASHBOARD_ID); foreach ($widgetIds as $id => $attr) { $dashboardDefinition->addMethodCall('addWidget', array( new Reference($id), )); } } } " "Fix duplicates in asset import It relied on the unique constraint from the database, but it doesn't apply if parent_id is null. So it checks the existence of the asset before inserting it.","from zou.app.resources.source.csv.base import BaseCsvImportResource from zou.app.project import project_info, asset_info from zou.app.models.entity import Entity from sqlalchemy.exc import IntegrityError class AssetsCsvImportResource(BaseCsvImportResource): def prepare_import(self): self.projects = {} self.entity_types = {} def import_row(self, row): name = row[""Name""] project_name = row[""Project""] entity_type_name = row[""Category""] description = row[""Description""] self.add_to_cache_if_absent( self.projects, project_info.get_or_create, project_name ) project_id = self.get_id_from_cache(self.projects, project_name) self.add_to_cache_if_absent( self.entity_types, asset_info.get_or_create_type, entity_type_name ) entity_type_id = self.get_id_from_cache( self.entity_types, entity_type_name ) try: entity = Entity.get_by( name=name, project_id=project_id, entity_type_id=entity_type_id ) if entity is None: entity = Entity.create( name=name, description=description, project_id=project_id, entity_type_id=entity_type_id ) except IntegrityError: pass return entity ","from zou.app.resources.source.csv.base import BaseCsvImportResource from zou.app.project import project_info, asset_info from zou.app.models.entity import Entity from sqlalchemy.exc import IntegrityError class AssetsCsvImportResource(BaseCsvImportResource): def prepare_import(self): self.projects = {} self.entity_types = {} def import_row(self, row): name = row[""Name""] project_name = row[""Project""] entity_type_name = row[""Category""] description = row[""Description""] self.add_to_cache_if_absent( self.projects, project_info.get_or_create, project_name ) project_id = self.get_id_from_cache(self.projects, project_name) self.add_to_cache_if_absent( self.entity_types, asset_info.get_or_create_type, entity_type_name ) entity_type_id = self.get_id_from_cache( self.entity_types, entity_type_name ) try: entity = Entity.create( name=name, description=description, project_id=project_id, entity_type_id=entity_type_id ) except IntegrityError: entity = Entity.get_by( name=name, project_id=project_id, entity_type_id=entity_type_id ) return entity " Change to simple string manipulation,"<?php namespace Tighten\TLint\Formatters; use PhpParser\Node; use PhpParser\Lexer; use PhpParser\Parser; use PhpParser\NodeTraverser; use PhpParser\Node\Expr\New_; use PhpParser\Node\Stmt\Class_; use PhpParser\Node\Stmt\Return_; use Tighten\TLint\BaseFormatter; use PhpParser\PrettyPrinter\Standard; use PhpParser\NodeVisitor\CloningVisitor; use Tighten\TLint\Linters\Concerns\LintsMigrations; class UseAnonymousMigrations extends BaseFormatter { use LintsMigrations; public const description = 'Prefer anonymous class migrations.'; public function format(Parser $parser, Lexer $lexer) { $traverser = new NodeTraverser; $traverser->addVisitor(new CloningVisitor); $className = null; array_map(function (Node $node) use (&$className) { if ( $node instanceof Class_ && $node->extends->toString() === 'Migration' && $node->name ) { $className = $node->name->toString(); } }, $traverser->traverse($parser->parse($this->code))); if ($className) { $this->code = str_replace(""class {$className}"", 'return new class', $this->code); $this->code = $this->str_lreplace('}', '};', $this->code); } return $this->code; } public function str_lreplace($search, $replace, $subject) { $pos = strrpos($subject, $search); if ($pos !== false) { $subject = substr_replace($subject, $replace, $pos, strlen($search)); } return $subject; } } ","<?php namespace Tighten\TLint\Formatters; use PhpParser\Node; use PhpParser\Lexer; use PhpParser\Parser; use PhpParser\NodeTraverser; use PhpParser\Node\Expr\New_; use PhpParser\Node\Stmt\Class_; use PhpParser\Node\Stmt\Return_; use Tighten\TLint\BaseFormatter; use PhpParser\PrettyPrinter\Standard; use PhpParser\NodeVisitor\CloningVisitor; use Tighten\TLint\Linters\Concerns\LintsMigrations; class UseAnonymousMigrations extends BaseFormatter { use LintsMigrations; public const description = 'Prefer anonymous class migrations.'; public function format(Parser $parser, Lexer $lexer) { $traverser = new NodeTraverser; $traverser->addVisitor(new CloningVisitor); $originalStatements = $parser->parse($this->code); $tokens = $lexer->getTokens(); $statements = array_map(function (Node $node) { if ( $node instanceof Class_ && $node->extends->toString() === 'Migration' && $node->name ) { return new Return_(new New_($node)); } return $node; }, $traverser->traverse($originalStatements)); return (new Standard)->printFormatPreserving($statements, $originalStatements, $tokens); } } " Use aggregate Max to fetch new order value.,"from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.db import models from django.db.models import Max class OrderedModel(models.Model): """""" An abstract model that allows objects to be ordered relative to each other. Provides an ``order`` field. """""" order = models.PositiveIntegerField(editable=False, db_index=True) class Meta: abstract = True ordering = ('order',) def save(self, *args, **kwargs): if not self.id: c = self.__class__.objects.all().aggregate(Max('order')).get('order__max') self.order = c and c + 1 or 0 super(OrderedModel, self).save(*args, **kwargs) def _move(self, up, qs=None): if qs is None: qs = self.__class__._default_manager if up: qs = qs.order_by('-order').filter(order__lt=self.order) else: qs = qs.filter(order__gt=self.order) try: replacement = qs[0] except IndexError: # already first/last return self.order, replacement.order = replacement.order, self.order self.save() replacement.save() def move(self, direction, qs=None): self._move(direction == 'up', qs) def move_down(self): """""" Move this object down one position. """""" return self._move(up=False) def move_up(self): """""" Move this object up one position. """""" return self._move(up=True) ","from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.db import models class OrderedModel(models.Model): """""" An abstract model that allows objects to be ordered relative to each other. Provides an ``order`` field. """""" order = models.PositiveIntegerField(editable=False, db_index=True) class Meta: abstract = True ordering = ('order',) def save(self, *args, **kwargs): if not self.id: qs = self.__class__.objects.order_by('-order') try: self.order = qs[0].order + 1 except IndexError: self.order = 0 super(OrderedModel, self).save(*args, **kwargs) def _move(self, up, qs=None): if qs is None: qs = self.__class__._default_manager if up: qs = qs.order_by('-order').filter(order__lt=self.order) else: qs = qs.filter(order__gt=self.order) try: replacement = qs[0] except IndexError: # already first/last return self.order, replacement.order = replacement.order, self.order self.save() replacement.save() def move(self, direction, qs=None): self._move(direction == 'up', qs) def move_down(self): """""" Move this object down one position. """""" return self._move(up=False) def move_up(self): """""" Move this object up one position. """""" return self._move(up=True) " Add more visual aid to marking tasks,"package seedu.watodo.ui; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Region; import seedu.watodo.model.task.ReadOnlyTask; //@@author A0139845R-reused public class TaskCard extends UiPart<Region> { private static final String FXML = ""TaskListCard.fxml""; @FXML private HBox cardPane; @FXML private Label description; @FXML private Label status; @FXML private Label id; @FXML private Label startDate; @FXML private Label endDate; @FXML private FlowPane tags; public TaskCard(ReadOnlyTask task, int displayedIndex) { super(FXML); description.setText(task.getDescription().fullDescription); id.setText(displayedIndex + "". ""); if (task.getStartDate() != null) { startDate.setText(""Start Task From "" + task.getStartDate()); } else { startDate.setText(""""); } if (task.getEndDate() != null) { endDate.setText(""Do Task By "" + task.getEndDate()); } else { endDate.setText(""""); } status.setText(task.getStatus().toString()); if (task.getStatus().toString().equals(""Done"")) { cardPane.setStyle(""-fx-background-color: #2bba36;""); } initTags(task); } private void initTags(ReadOnlyTask person) { person.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName))); } } ","package seedu.watodo.ui; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Region; import seedu.watodo.model.task.ReadOnlyTask; //@@author A0139845R-reused public class TaskCard extends UiPart<Region> { private static final String FXML = ""TaskListCard.fxml""; @FXML private HBox cardPane; @FXML private Label description; @FXML private Label status; @FXML private Label id; @FXML private Label startDate; @FXML private Label endDate; @FXML private FlowPane tags; public TaskCard(ReadOnlyTask task, int displayedIndex) { super(FXML); description.setText(task.getDescription().fullDescription); id.setText(displayedIndex + "". ""); if (task.getStartDate() != null) { startDate.setText(""Start Task From "" + task.getStartDate()); } else { startDate.setText(""""); } if (task.getEndDate() != null) { endDate.setText(""Do Task By "" + task.getEndDate()); } else { endDate.setText(""""); } status.setText(task.getStatus().toString()); initTags(task); } private void initTags(ReadOnlyTask person) { person.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName))); } } " Implement AJAX for showing comments.,"$(document).ready(function() { $(""body"").on(""click"", ""#signup"", function(event){ event.preventDefault(); var $target = $(event.target); $.ajax({ type: ""GET"", url: ""/signup"", }).done(function(response){ $("".container"").replaceWith(response); }); }); $(""body"").on(""click"", ""#login"", function(event){ event.preventDefault(); var $target = $(event.target); $.ajax({ type: ""GET"", url: ""/"", }).done(function(response){ $("".container"").replaceWith(response); }); }); $("".edit_comment_link"").click(function(event){ var $this = $(this); event.preventDefault(); $this.hide(); $this.siblings("".edit_form_div"").css('display','block'); }); $("".add_comment_button"").click(function(event){ event.preventDefault(); var $target = $(event.target); $target.hide(); $("".comment_form"").css('display','block'); }); $('#comment_block').on('submit', '.comment_form form', function(event) { event.preventDefault(); var $form = $(this); $.ajax({ type: ""POST"", url: $form.attr('action'), data: $form.serialize() }).done(function(response){ $('.userComments').add(response, function(){ $('.userComments').css('display', 'block'); }); }); }); }); ","$(document).ready(function() { $(""body"").on(""click"", ""#signup"", function(event){ event.preventDefault(); var $target = $(event.target); $.ajax({ type: ""GET"", url: ""/signup"", }).done(function(response){ $("".container"").replaceWith(response); }); }); $(""body"").on(""click"", ""#login"", function(event){ event.preventDefault(); var $target = $(event.target); $.ajax({ type: ""GET"", url: ""/"", }).done(function(response){ $("".container"").replaceWith(response); }); }); $("".edit_comment_link"").click(function(event){ var $this = $(this); event.preventDefault(); $this.hide(); $this.siblings("".edit_form_div"").css('display','block'); }); $("".add_comment_button"").click(function(event){ event.preventDefault(); var $target = $(event.target); $target.hide(); $("".comment_form"").css('display','block'); }); $('#comment_block').on('submit', '.comment_form form', function(event) { event.preventDefault(); var $form = $(this); console.log($form); $.ajax({ type: ""POST"", url: $form.attr('action'), data: $form.serialize() }).done(function(response){ console.log(response); $('.userComments').append(response); }); }); }); " Add config property to grunt config,"/* jshint node:true */ ""use strict""; module.exports = function (grunt) { // Show elapsed time at the end require(""time-grunt"")(grunt); // Load all grunt tasks require(""load-grunt-tasks"")(grunt); // Project configuration. grunt.initConfig({ config: { main: ""object-event"", global: ""objectEvent"" }, nodeunit: { files: [""test/bootstrap.js""] }, jshint: { options: { jshintrc: "".jshintrc"", reporter: require(""jshint-stylish"") }, gruntfile: { src: ""Gruntfile.js"" }, lib: { src: [""<%= config.main %>.js"", ""lib/*.js""] }, test: { src: [""test/**/*.js""] } }, watch: { gruntfile: { files: ""<%= jshint.gruntfile.src %>"", tasks: [""jshint:gruntfile""] }, lib: { files: ""<%= jshint.lib.src %>"", tasks: [""jshint:lib"", ""nodeunit""] }, test: { files: ""<%= jshint.test.src %>"", tasks: [""jshint:test"", ""nodeunit""] } } }); // Default task. grunt.registerTask(""test"", [""jshint"", ""nodeunit""]); }; ","/* jshint node:true */ ""use strict""; module.exports = function (grunt) { // Show elapsed time at the end require(""time-grunt"")(grunt); // Load all grunt tasks require(""load-grunt-tasks"")(grunt); // Project configuration. grunt.initConfig({ nodeunit: { files: [""test/bootstrap.js""] }, jshint: { options: { jshintrc: "".jshintrc"", reporter: require(""jshint-stylish"") }, gruntfile: { src: ""Gruntfile.js"" }, lib: { src: [""object-event.js"", ""lib/*.js""] }, test: { src: [""test/**/*.js""] } }, watch: { gruntfile: { files: ""<%= jshint.gruntfile.src %>"", tasks: [""jshint:gruntfile""] }, lib: { files: ""<%= jshint.lib.src %>"", tasks: [""jshint:lib"", ""nodeunit""] }, test: { files: ""<%= jshint.test.src %>"", tasks: [""jshint:test"", ""nodeunit""] } } }); // Default task. grunt.registerTask(""test"", [""jshint"", ""nodeunit""]); }; " "Allow the upload function to acces not only formData, but also the raw files","import AddBlock from './addBlock'; export default function(config) { return function(e){ const {props, selection, files, editorState, onChange} = e; // Get upload function from config or editor props const upload = config.upload || props.upload; if (upload) { //this.setState({fileDrag: false, uploading: true}); console.log('Starting upload'); var formData = new FormData(); var data = { files: [] }; for (var key in files) { formData.append('files', files[key]); data.files.push(files[key]); } data.formData = data; upload(data, (files, tag)=> { console.log('Upload done'); // Success, tag can be function that returns editorState or a tag-type (default: image) var newEditorState = editorState(); files.forEach(function (x) { newEditorState = typeof tag === 'function' ? tag(x) : AddBlock(newEditorState, selection, tag || 'image', x); }); onChange(newEditorState); }, (err)=> { // Failed console.error(err) //this.setState({uploading: false, uploadError: err}); }, (percent)=> { // Progress //this.setState({percent: percent !== 100 ? percent : null}); console.log(percent) }); return true; } } }","import AddBlock from './addBlock'; export default function(config) { return function(e){ const {props, selection, files, editorState, onChange} = e; // Get upload function from config or editor props const upload = config.upload || props.upload; if (upload) { //this.setState({fileDrag: false, uploading: true}); console.log('Starting upload'); var data = new FormData(); for (var key in files) { data.append('files', files[key]); } upload(data, (files, tag)=> { console.log('Upload done'); // Success, tag can be function that returns editorState or a tag-type (default: image) var newEditorState = editorState(); files.forEach(function (x) { newEditorState = typeof tag === 'function' ? tag(x) : AddBlock(newEditorState, selection, tag || 'image', x); }); onChange(newEditorState); }, (err)=> { // Failed console.error(err) //this.setState({uploading: false, uploadError: err}); }, (percent)=> { // Progress //this.setState({percent: percent !== 100 ? percent : null}); console.log(percent) }); return true; } } }" Deal with document in node,"/*globals process, require*/ define([ '../ThirdParty/Uri', './defaultValue', './defined', './DeveloperError' ], function( Uri, defaultValue, defined, DeveloperError) { 'use strict'; /** * Given a relative Uri and a base Uri, returns the absolute Uri of the relative Uri. * @exports getAbsoluteUri * * @param {String} relative The relative Uri. * @param {String} [base] The base Uri. * @returns {String} The absolute Uri of the given relative Uri. * * @example * //absolute Uri will be ""https://test.com/awesome.png""; * var absoluteUri = Cesium.getAbsoluteUri('awesome.png', 'https://test.com'); */ function getAbsoluteUri(relative, base) { if (typeof process === 'object' && Object.prototype.toString.call(process) === '[object process]') { // Running node return getAbsoluteUri._implementation(relative, base, {baseURI: 'http://localhost/', location: {href: ''}}) } else { return getAbsoluteUri._implementation(relative, base, document); } } getAbsoluteUri._implementation = function(relative, base, documentObject) { //>>includeStart('debug', pragmas.debug); if (!defined(relative)) { throw new DeveloperError('relative uri is required.'); } //>>includeEnd('debug'); base = defaultValue(base, defaultValue(documentObject.baseURI, documentObject.location.href)); var baseUri = new Uri(base); var relativeUri = new Uri(relative); return relativeUri.resolve(baseUri).toString(); }; return getAbsoluteUri; }); ","define([ '../ThirdParty/Uri', './defaultValue', './defined', './DeveloperError' ], function( Uri, defaultValue, defined, DeveloperError) { 'use strict'; /** * Given a relative Uri and a base Uri, returns the absolute Uri of the relative Uri. * @exports getAbsoluteUri * * @param {String} relative The relative Uri. * @param {String} [base] The base Uri. * @returns {String} The absolute Uri of the given relative Uri. * * @example * //absolute Uri will be ""https://test.com/awesome.png""; * var absoluteUri = Cesium.getAbsoluteUri('awesome.png', 'https://test.com'); */ function getAbsoluteUri(relative, base) { return getAbsoluteUri._implementation(relative, base, document); } getAbsoluteUri._implementation = function(relative, base, documentObject) { //>>includeStart('debug', pragmas.debug); if (!defined(relative)) { throw new DeveloperError('relative uri is required.'); } //>>includeEnd('debug'); base = defaultValue(base, defaultValue(documentObject.baseURI, documentObject.location.href)); var baseUri = new Uri(base); var relativeUri = new Uri(relative); return relativeUri.resolve(baseUri).toString(); }; return getAbsoluteUri; }); " Make sure interval gets canceled,"import React, { Component } from 'react'; import CarouselA from './CarouselA'; import CarouselB from './CarouselB'; import styles from './HeroCarousel.styl' class HeroCarousel extends Component { constructor () { super(); this.state = { count: 0 }; } componentDidMount () { this.swapper = setInterval(::this.swap, 7500); } componentWillUnmount () { clearInterval(this.swapper); } swap () { this.setState({count: this.state.count + 1}); } swapHero () { clearInterval(this.swapper); this.setState({count: this.state.count + 1}); } render () { const showA = this.state.count % 2 === 0; if (this.props.username) return <span></span>; return ( <div style={{position: 'relative'}}> <CarouselA swapHero={::this.swapHero} oauthUrl={this.props.oauthUrl} style={{ opacity: showA ? 1 : 0, pointerEvents: showA ? 'all' : 'none' }} /> <CarouselB swapHero={::this.swapHero} oauthUrl={this.props.oauthUrl} style={{ opacity: showA ? 0 : 1, pointerEvents: showA ? 'none' : 'all' }} /> </div> ) } } export default HeroCarousel; ","import React, { Component } from 'react'; import CarouselA from './CarouselA'; import CarouselB from './CarouselB'; import styles from './HeroCarousel.styl' class HeroCarousel extends Component { constructor () { super(); this.state = { count: 0 }; } componentDidMount () { this.swapper = setInterval(::this.swap, 7500); } swap () { this.setState({count: this.state.count + 1}); } swapHero () { clearInterval(this.swapper); this.setState({count: this.state.count + 1}); } render () { const showA = this.state.count % 2 === 0; if (this.props.username) return <span></span>; return ( <div style={{position: 'relative'}}> <CarouselA swapHero={::this.swapHero} oauthUrl={this.props.oauthUrl} style={{ opacity: showA ? 1 : 0, pointerEvents: showA ? 'all' : 'none' }} /> <CarouselB swapHero={::this.swapHero} oauthUrl={this.props.oauthUrl} style={{ opacity: showA ? 0 : 1, pointerEvents: showA ? 'none' : 'all' }} /> </div> ) } } export default HeroCarousel; " Correct was->were in plural version of error message,"<?php /* * This file is part of PhpSpec, A php toolset to drive emergent * design by specification. * * (c) Marcello Duarte <marcello.duarte@gmail.com> * (c) Konstantin Kudryashov <ever.zet@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PhpSpec\Process\Prerequisites; use PhpSpec\Process\Context\ExecutionContextInterface; final class SuitePrerequisites implements SuitePrerequisitesInterface { /** * @var ExecutionContextInterface */ private $executionContext; /** * @param ExecutionContextInterface $executionContext */ public function __construct(ExecutionContextInterface $executionContext) { $this->executionContext = $executionContext; } /** * @throws PrerequisiteFailedException */ public function guardPrerequisites() { $undefinedTypes = array(); foreach ($this->executionContext->getGeneratedTypes() as $type) { if (!class_exists($type) && !interface_exists($type)) { $undefinedTypes[] = $type; } } if ($undefinedTypes) { throw new PrerequisiteFailedException(sprintf( ""The type%s %s %s generated but could not be loaded. Do you need to configure an autoloader?\n"", count($undefinedTypes) > 1 ? 's' : '', join(', ', $undefinedTypes), count($undefinedTypes) > 1 ? 'were' : 'was' )); } } } ","<?php /* * This file is part of PhpSpec, A php toolset to drive emergent * design by specification. * * (c) Marcello Duarte <marcello.duarte@gmail.com> * (c) Konstantin Kudryashov <ever.zet@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PhpSpec\Process\Prerequisites; use PhpSpec\Process\Context\ExecutionContextInterface; final class SuitePrerequisites implements SuitePrerequisitesInterface { /** * @var ExecutionContextInterface */ private $executionContext; /** * @param ExecutionContextInterface $executionContext */ public function __construct(ExecutionContextInterface $executionContext) { $this->executionContext = $executionContext; } /** * @throws PrerequisiteFailedException */ public function guardPrerequisites() { $undefinedTypes = array(); foreach ($this->executionContext->getGeneratedTypes() as $type) { if (!class_exists($type) && !interface_exists($type)) { $undefinedTypes[] = $type; } } if ($undefinedTypes) { throw new PrerequisiteFailedException(sprintf( ""The type%s %s was generated but could not be loaded. Do you need to configure an autoloader?\n"", count($undefinedTypes) > 1 ? 's' : '', join(', ', $undefinedTypes) )); } } } " "Increase current time widget update freq. to 4 Hz [rev: Matthew Gordon] Previous update frequency of 1 Hz would result in inconsistent updating if a time format which displays seconds was passed to the widget.","/* * Copyright 2017 Hewlett Packard Enterprise Development Company, L.P. * Licensed under the MIT License (the ""License""); you may not use this file except in compliance with the License. */ define([ 'underscore', './widget', 'text!find/idol/templates/page/dashboards/widgets/current-time-widget.html', 'moment-timezone-with-data' ], function(_, Widget, template, moment) { 'use strict'; return Widget.extend({ currentTimeTemplate: _.template(template), initialize: function(options) { Widget.prototype.initialize.apply(this, arguments); this.dateFormat = this.widgetSettings.dateFormat || 'll'; this.timeFormat = this.widgetSettings.timeFormat || 'HH:mm z'; this.timeZone = this.widgetSettings.timeZone || moment.tz.guess(); }, render: function() { Widget.prototype.render.apply(this); this.$content.html(this.currentTimeTemplate()); this.$time = this.$('.current-time'); this.$day = this.$('.day'); this.$date = this.$('.date'); this.updateTime(); setInterval(this.updateTime.bind(this), 250); }, updateTime: function() { const time = moment().tz(this.timeZone); this.$time.text(time.format(this.timeFormat)); this.$day.text(time.format('dddd')); this.$date.text(time.format(this.dateFormat)); } }); }); ","/* * Copyright 2017 Hewlett Packard Enterprise Development Company, L.P. * Licensed under the MIT License (the ""License""); you may not use this file except in compliance with the License. */ define([ 'underscore', './widget', 'text!find/idol/templates/page/dashboards/widgets/current-time-widget.html', 'moment-timezone-with-data' ], function(_, Widget, template, moment) { 'use strict'; return Widget.extend({ currentTimeTemplate: _.template(template), initialize: function(options) { Widget.prototype.initialize.apply(this, arguments); this.dateFormat = this.widgetSettings.dateFormat || 'll'; this.timeFormat = this.widgetSettings.timeFormat || 'HH:mm z'; this.timeZone = this.widgetSettings.timeZone || moment.tz.guess(); }, render: function() { Widget.prototype.render.apply(this); this.$content.html(this.currentTimeTemplate()); this.$time = this.$('.current-time'); this.$day = this.$('.day'); this.$date = this.$('.date'); this.updateTime(); setInterval(this.updateTime.bind(this), 1000); }, updateTime: function() { const time = moment().tz(this.timeZone); this.$time.text(time.format(this.timeFormat)); this.$day.text(time.format('dddd')); this.$date.text(time.format(this.dateFormat)); } }); }); " "Change to V2 spec of param meta data Had to switch to ElementTree to get attribute support","import xml.etree.ElementTree as ET import codecs def indent(elem, level=0): i = ""\n"" + level*"" "" if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + "" "" if not elem.tail or not elem.tail.strip(): elem.tail = i for elem in elem: indent(elem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i class XMLOutput(): def __init__(self, groups): xml_parameters = ET.Element(""parameters"") xml_version = ET.SubElement(xml_parameters, ""version"") xml_version.text = ""2"" for group in groups: xml_group = ET.SubElement(xml_parameters, ""group"") xml_group.attrib[""name""] = group.GetName() for param in group.GetParams(): xml_param = ET.SubElement(xml_group, ""parameter"") for code in param.GetFieldCodes(): value = param.GetFieldValue(code) if code == ""code"": xml_param.attrib[""name""] = value elif code == ""default"": xml_param.attrib[""default""] = value elif code == ""type"": xml_param.attrib[""type""] = value else: xml_field = ET.SubElement(xml_param, code) xml_field.text = value indent(xml_parameters) self.xml_document = ET.ElementTree(xml_parameters) def Save(self, filename): with codecs.open(filename, 'w', 'utf-8') as f: self.xml_document.write(f) ","from xml.dom.minidom import getDOMImplementation import codecs class XMLOutput(): def __init__(self, groups): impl = getDOMImplementation() xml_document = impl.createDocument(None, ""parameters"", None) xml_parameters = xml_document.documentElement xml_version = xml_document.createElement(""version"") xml_parameters.appendChild(xml_version) xml_version_value = xml_document.createTextNode(""1"") xml_version.appendChild(xml_version_value) for group in groups: xml_group = xml_document.createElement(""group"") xml_group.setAttribute(""name"", group.GetName()) xml_parameters.appendChild(xml_group) for param in group.GetParams(): xml_param = xml_document.createElement(""parameter"") xml_group.appendChild(xml_param) for code in param.GetFieldCodes(): value = param.GetFieldValue(code) xml_field = xml_document.createElement(code) xml_param.appendChild(xml_field) xml_value = xml_document.createTextNode(value) xml_field.appendChild(xml_value) self.xml_document = xml_document def Save(self, filename): with codecs.open(filename, 'w', 'utf-8') as f: self.xml_document.writexml(f, indent="" "", addindent="" "", newl=""\n"") " Use points from json directly,"angular.module(""personaApp"") .controller('quizController', ['$http', function($http){ var quiz = this; quiz.started = false; quiz.questionNumber = 0; quiz.gender = """"; quiz.questions = []; quiz.answers = []; $http.get('/assets/quizData.json').success(function(data){ quiz.questions = data; console.log(""Successfully loaded "" + quiz.questions.length + "" questions""); }); quiz.isStarted = function(){ return quiz.started; }; quiz.isGenderPage = function(){ return quiz.isStarted() && quiz.questionNumber == 0; } quiz.setGender = function(gender) { quiz.gender = gender; } quiz.setAnswer = function(number) { var n = quiz.questions[quiz.questionNumber-1].points[number]; quiz.answers.push(n); } quiz.start = function() { quiz.started = true; }; quiz.showNextQuestion = function() { if(!quiz.gender){ alert(""Pilih cowo apa cewe dulu""); return; } quiz.questionNumber++; if(quiz.questionNumber > quiz.questions.length){ var str = ""Selamat anda sudah selesai! Pilihan anda:\n""; for(var answer in quiz.answers){ str += quiz.answers[answer] + ""\n""; } alert(str); } }; }]);","angular.module(""personaApp"") .controller('quizController', ['$http', function($http){ var quiz = this; quiz.started = false; quiz.questionNumber = 0; quiz.gender = """"; quiz.questions = []; quiz.answers = []; $http.get('/assets/quizData.json').success(function(data){ quiz.questions = data; console.log(""Successfully loaded "" + quiz.questions.length + "" questions""); }); quiz.isStarted = function(){ return quiz.started; }; quiz.isGenderPage = function(){ return quiz.isStarted() && quiz.questionNumber == 0; } quiz.setGender = function(gender) { quiz.gender = gender; } quiz.setAnswer = function(number) { quiz.answers.push(number); } quiz.start = function() { quiz.started = true; }; quiz.showNextQuestion = function() { if(!quiz.gender){ alert(""Pilih cowo apa cewe dulu""); return; } quiz.questionNumber++; if(quiz.questionNumber > quiz.questions.length){ var str = ""Selamat anda sudah selesai! Pilihan anda:\n""; for(var answer in quiz.answers){ str += quiz.answers[answer] + ""\n""; } alert(str); } }; }]);" "Revert ""Added autoPanMapOnSelection to recenter the map by clicking a feature within the grid"" This reverts commit c5270d13ab270e97610fe9c3c87573177f0261a1.","/** * The grid in which summits are displayed * @extends Ext.grid.Panel */ Ext.define('GX.view.summit.Grid' ,{ extend: 'Ext.grid.Panel', alias : 'widget.summitgrid', requires: [ 'GeoExt.selection.FeatureModel', 'GeoExt.grid.column.Symbolizer', 'Ext.grid.plugin.CellEditing', 'Ext.form.field.Number' ], initComponent: function() { Ext.apply(this, { border: true, columns: [ {header: '', dataIndex: 'symbolizer', xtype: 'gx_symbolizercolumn', width: 30}, {header: 'ID', dataIndex: 'fid', width: 40}, {header: 'Name', dataIndex: 'name', flex: 3}, {header: 'Elevation', dataIndex: 'elevation', width: 60, editor: {xtype: 'numberfield'} }, {header: 'Title', dataIndex: 'title', flex: 4}, {header: 'Position', dataIndex: 'position', flex: 4} ], flex: 1, title : 'Summits Grid', store: 'Summits', selType: 'featuremodel', plugins: [ Ext.create('Ext.grid.plugin.CellEditing', { clicksToEdit: 2 }) ] }); this.callParent(arguments); // store singleton selection model instance GX.view.summit.Grid.selectionModel = this.getSelectionModel(); } }); ","/** * The grid in which summits are displayed * @extends Ext.grid.Panel */ Ext.define('GX.view.summit.Grid' ,{ extend: 'Ext.grid.Panel', alias : 'widget.summitgrid', requires: [ 'GeoExt.selection.FeatureModel', 'GeoExt.grid.column.Symbolizer', 'Ext.grid.plugin.CellEditing', 'Ext.form.field.Number' ], initComponent: function() { Ext.apply(this, { border: true, columns: [ {header: '', dataIndex: 'symbolizer', xtype: 'gx_symbolizercolumn', width: 30}, {header: 'ID', dataIndex: 'fid', width: 40}, {header: 'Name', dataIndex: 'name', flex: 3}, {header: 'Elevation', dataIndex: 'elevation', width: 60, editor: {xtype: 'numberfield'} }, {header: 'Title', dataIndex: 'title', flex: 4}, {header: 'Position', dataIndex: 'position', flex: 4} ], flex: 1, title : 'Summits Grid', store: 'Summits', selType: 'featuremodel', plugins: [ Ext.create('Ext.grid.plugin.CellEditing', { clicksToEdit: 2 }) ] }); this.getSelectionModel().autoPanMapOnSelection = true; this.callParent(arguments); // store singleton selection model instance GX.view.summit.Grid.selectionModel = this.getSelectionModel(); } }); " Test for environment variable existence,"import configobj import validate import os def _get_filename(): """"""Return the configuration file path."""""" appname = 'dlstats' if os.name == 'posix': if ""HOME"" in os.environ: if os.path.isfile(os.environ[""HOME""]+'/.'+appname): return os.environ[""HOME""]+'/.'+appname if os.path.isfile('/etc/'+appname): return '/etc/'+appname else: raise FileNotFoundError('No configuration file found.') elif os.name == 'mac': return (""%s/Library/Application Support/%s"" % (os.environ[""HOME""], appname)) elif os.name == 'nt': return (""%s\Application Data\%s"" % (os.environ[""HOMEPATH""], appname)) else: raise UnsupportedOSError(os.name) configuration_filename = _get_filename() _configspec = """""" [General] logging_directory = string() socket_directory = string() [MongoDB] host = ip_addr() port = integer() max_pool_size = integer() socketTimeoutMS = integer() connectTimeoutMS = integer() waitQueueTimeout = integer() waitQueueMultiple = integer() auto_start_request = boolean() use_greenlets = boolean() [ElasticSearch] host = integer() port = integer() [Fetchers] [[Eurostat]] url_table_of_contents = string()"""""" configuration = configobj.ConfigObj(configuration_filename, configspec=_configspec.split('\n')) validator = validate.Validator() configuration.validate(validator) configuration = configuration.dict() ","import configobj import validate import os def _get_filename(): """"""Return the configuration file path."""""" appname = 'dlstats' if os.name == 'posix': if os.path.isfile(os.environ[""HOME""]+'/.'+appname): return os.environ[""HOME""]+'/.'+appname elif os.path.isfile('/etc/'+appname): return '/etc/'+appname else: raise FileNotFoundError('No configuration file found.') elif os.name == 'mac': return (""%s/Library/Application Support/%s"" % (os.environ[""HOME""], appname)) elif os.name == 'nt': return (""%s\Application Data\%s"" % (os.environ[""HOMEPATH""], appname)) else: raise UnsupportedOSError(os.name) configuration_filename = _get_filename() _configspec = """""" [General] logging_directory = string() socket_directory = string() [MongoDB] host = ip_addr() port = integer() max_pool_size = integer() socketTimeoutMS = integer() connectTimeoutMS = integer() waitQueueTimeout = integer() waitQueueMultiple = integer() auto_start_request = boolean() use_greenlets = boolean() [ElasticSearch] host = integer() port = integer() [Fetchers] [[Eurostat]] url_table_of_contents = string()"""""" configuration = configobj.ConfigObj(configuration_filename, configspec=_configspec.split('\n')) validator = validate.Validator() configuration.validate(validator) configuration = configuration.dict() " Return as array; start of finding shell fraction," import numpy as np class Bubble2D(object): """""" Class for candidate bubble portions from 2D planes. """""" def __init__(self, props): super(Bubble2D, self).__init__() self._y = props[0] self._x = props[1] self._major = props[2] self._minor = props[3] self._pa = props[4] @property def params(self): return np.array([self._y, self._x, self._major, self._minor, self._pa]) @property def area(self): return np.pi * self.major * self.minor @property def pa(self): return self._pa @property def major(self): return self._major @property def minor(self): return self._minor def profile_lines(self, array, **kwargs): ''' Calculate radial profile lines of the 2D bubbles. ''' from basics.profile import azimuthal_profiles return azimuthal_profiles(array, self.params, **kwargs) def find_shell_fraction(self, array, frac_thresh=0.05, grad_thresh=1, **kwargs): ''' Find the fraction of the bubble edge associated with a shell. ''' shell_frac = 0 for prof in self.profiles_lines(array, **kwargs): pass def as_mask(self): ''' Return a boolean mask of the 2D region. ''' raise NotImplementedError() def find_shape(self): ''' Expand/contract to match the contours in the data. ''' raise NotImplementedError() "," import numpy as np class Bubble2D(object): """""" Class for candidate bubble portions from 2D planes. """""" def __init__(self, props): super(Bubble2D, self).__init__() self._y = props[0] self._x = props[1] self._major = props[2] self._minor = props[3] self._pa = props[4] @property def params(self): return [self._y, self._x, self._major, self._minor, self._pa] @property def area(self): return np.pi * self.major * self.minor @property def pa(self): return self._pa @property def major(self): return self._major @property def minor(self): return self._minor def profiles_lines(self, array, **kwargs): ''' Calculate radial profile lines of the 2D bubbles. ''' from basics.profile import azimuthal_profiles return azimuthal_profiles(array, self.params, **kwargs) def as_mask(self): ''' Return a boolean mask of the 2D region. ''' raise NotImplementedError() def find_shape(self): ''' Expand/contract to match the contours in the data. ''' raise NotImplementedError() " Fix config loader (bug in commit:5bdf6e47 / commit:eefe7561),"# -*- coding: utf-8 -*- # Copyright (c) 2014 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. """""" pycroft ~~~~~~~~~~~~~~ This package contains everything. :copyright: (c) 2011 by AG DSN. """""" import json, collections, pkgutil class Config(object): def __init__(self): self._config_data = None self._package = ""pycroft"" self._resource = ""config.json"" def load(self): data = None try: data = pkgutil.get_data(self._package, self._resource) except IOError: data = pkgutil.get_data(self._package, self._resource+"".default"") if data is None: raise Exception( ""Could not load config file {1} "" ""from package {0}"".format(self._package, self._resource) ) self._config_data = json.loads(data) if not isinstance(self._config_data, collections.Mapping): raise Exception(""Config must be a JSON object!"") def __getitem__(self, key): if self._config_data is None: self.load() return self._config_data[key] def __setitem__(self, key, value): raise Exception(""It is not possible to set configuration entries!"") config = Config() ","# -*- coding: utf-8 -*- # Copyright (c) 2014 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. """""" pycroft ~~~~~~~~~~~~~~ This package contains everything. :copyright: (c) 2011 by AG DSN. """""" import json, collections, pkgutil class Config(object): def __init__(self): self._config_data = None self._package = ""pycroft"" self._resource = ""config.json"" def load(self): data = (pkgutil.get_data(self._package, self._resource) or pkgutil.get_data(self._package, self._resource+"".default"")) if data is None: raise Exception( ""Could not load config file {1} "" ""from package {0}"".format(self._package, self._resource) ) self._config_data = json.loads(data) if not isinstance(self._config_data, collections.Mapping): raise Exception(""Config must be a JSON object!"") def __getitem__(self, key): if self._config_data is None: self.load() return self._config_data[key] def __setitem__(self, key, value): raise Exception(""It is not possible to set configuration entries!"") config = Config() " Trim strings before sending them to the channel,"'use strict'; var request = require( 'request' ), cheerio = require( 'cheerio' ), urlChecker = { bot : false, setup : function( bot ){ var _this = this, channel; _this.bot = bot; for( channel in _this.bot.opt.channels ){ if( _this.bot.opt.channels.hasOwnProperty( channel ) ){ bot.addListener( 'message' + this.bot.opt.channels[ channel ], _this.handleMessage ); } } }, handleMessage : function( from, text, message ){ var url, urlRegex = /(https?:\/\/[^\s]+)/g; url = text.match( urlRegex ); if( url !== null ){ request( url[ 0 ], function( error, response, html ){ var $ = cheerio.load( html ), pageTitle; if( error ){ console.log( error ); } pageTitle = $( 'title' ).text(); urlChecker.sendMessage( message.args[ 0 ], pageTitle ); }); } }, sendMessage : function( channel, message ){ this.bot.say( channel, message.trim() ); } }; module.exports = urlChecker; ","'use strict'; var request = require( 'request' ), cheerio = require( 'cheerio' ), urlChecker = { bot : false, setup : function( bot ){ var _this = this, channel; _this.bot = bot; for( channel in _this.bot.opt.channels ){ if( _this.bot.opt.channels.hasOwnProperty( channel ) ){ bot.addListener( 'message' + this.bot.opt.channels[ channel ], _this.handleMessage ); } } }, handleMessage : function( from, text, message ){ var url, urlRegex = /(https?:\/\/[^\s]+)/g; url = text.match( urlRegex ); if( url !== null ){ request( url[ 0 ], function( error, response, html ){ var $ = cheerio.load( html ), pageTitle; if( error ){ console.log( error ); } pageTitle = $( 'title' ).text(); urlChecker.sendMessage( message.args[ 0 ], pageTitle ); }); } }, sendMessage : function( channel, message ){ this.bot.say( channel, message ); } }; module.exports = urlChecker; " Refactor checkAuth function to account for change on server,"var api = require('./api'); module.exports = { login(username, password, callback) { api.login(username, password) .then((response) => { if(response.status === 400){ if(callback) { callback(false); } } else if (response.status === 200) { console.log(""$$$$$$$$"", document.cookie); response.json() .then(function(body) { localStorage.token = true; if(callback) { callback(true); } }); } }) .catch((err) => { console.error('Error with login' + err); }); }, logout(callback) { delete localStorage.token; api.logout() .then(() => { if (callback) { callback(); } }); }, loggedIn() { return !!localStorage.token }, checkForSession(next) { delete localStorage.token; api.checkForSession() .then((response) => { if(response.status === 200) { response.json().then((data) => { if(data.user) { localStorage.token = true; } next(data.user); }); } }) .catch((err) => { console.error('Error checking session', err); next(false); }); // send api request to protected route // if response.status === 401, i don't have access // return false; // else, // localStorage.token = true; // it will return userID / login data } }","var api = require('./api'); module.exports = { login(username, password, callback) { api.login(username, password) .then((response) => { if(response.status === 400){ if(callback) { callback(false); } } else if (response.status === 200) { console.log(""$$$$$$$$"", document.cookie); response.json() .then(function(body) { localStorage.token = true; if(callback) { callback(true); } }); } }) .catch((err) => { console.error('Error with login' + err); }); }, logout(callback) { delete localStorage.token; api.logout() .then(() => { if (callback) { callback(); } }); }, loggedIn() { return !!localStorage.token }, checkForSession(next) { delete localStorage.token; api.checkForSession() .then((response) => { if(response.status === 200) { response.json().then((data) => { if(data) { localStorage.token = true; } next(data); }); } }) .catch((err) => { console.error('Error checking session', err); next(false); }); // send api request to protected route // if response.status === 401, i don't have access // return false; // else, // localStorage.token = true; // it will return userID / login data } }" Set default values for data fields,"var os = require ('os'); var request = require ('request'); var HONEYBADGER_API_KEY = process.env.HONEYBADGER_API_KEY; exports.notify = function(data) { console.log(""Exception: "" + data.message); var requestOptions = { url:'https://api.honeybadger.io/v1/notices', headers:{ 'content-type':'application/json', 'X-API-Key':HONEYBADGER_API_KEY, 'Accept':'application/json' }, json:exports.errorPackage(data) }; request.post( requestOptions, function(e,r,body) { console.log('POST to honeybadger, status=' + r.statusCode + ' message=' + data.message); } ); } exports.errorPackage = function (data) { return { ""error"": { ""backtrace"": [ { ""file"": ""node"", ""method"": ""runtime_error"", ""number"": ""1"" } ], ""class"": ""RuntimeError"", ""message"": data.message || 'Default message' }, ""request"":{ ""url"": data.url || 'http://localhost', ""component"":""component"", ""action"":""action"", ""params"":{""_method"":""post""}, ""controller"":""worker"", ""session"":{} }, ""notifier"": { ""name"": ""Node Honeybadger Notifier"", ""url"": ""github/something"", ""version"": ""1.3.0"" }, ""server"": { ""hostname"": os.hostname() } } } ","var os = require ('os'); var request = require ('request'); var HONEYBADGER_API_KEY = process.env.HONEYBADGER_API_KEY; exports.notify = function(data) { console.log(""Exception: "" + data.message); var requestOptions = { url:'https://api.honeybadger.io/v1/notices', headers:{ 'content-type':'application/json', 'X-API-Key':HONEYBADGER_API_KEY, 'Accept':'application/json' }, json:exports.errorPackage(data) }; request.post( requestOptions, function(e,r,body) { console.log('POST to honeybadger, status=' + r.statusCode + ' message=' + data.message); } ); } exports.errorPackage = function (data) { return { ""error"": { ""backtrace"": [ { ""file"": ""node"", ""method"": ""runtime_error"", ""number"": ""1"" } ], ""class"": ""RuntimeError"", ""message"": data.message }, ""request"":{ ""url"": data.url, ""component"":""component"", ""action"":""action"", ""params"":{""_method"":""post""}, ""controller"":""worker"", ""session"":{} }, ""notifier"": { ""name"": ""Node Honeybadger Notifier"", ""url"": ""github/something"", ""version"": ""1.3.0"" }, ""server"": { ""hostname"": os.hostname() } } } " Disable reordering when add is disabled,"<div class=""portlet portlet-sortable light bordered"" :id=""guid""> <div class=""portlet-title""> <div class=""caption font-green-sharp""> <i class=""icon-speech font-green-sharp""></i> <span class=""caption-subject""> @{{panel.libelle}}</span> </div> <div class=""actions""> @if (!isset($disableAdd) || !$disableAdd) <button type=""button"" class=""btn btn-circle red-sunglo "" v-on:click='remove()'> <i class=""fa fa-close""></i> Supprimer </button> <button type=""button"" class=""btn btn-circle btn-default"" v-on:click='duplicate()'> <i class=""fa fa-clone""></i> Dupliquer </button> @endif <button type=""button"" class=""btn btn-circle btn-default"" v-on:click='reset()' > <i class=""fa fa-eraser""></i> Reset </button> @if (!isset($disableAdd) || !$disableAdd) <button type=""button"" class=""btn btn-circle btn-icon-only btn-default btn-draggable ""> <i class=""fa fa-arrows""></i> </button> @endif <button type=""button"" class=""btn btn-circle btn-icon-only btn-default fullscreen""> </button> </div> </div> <div class=""portlet-body""> <div class=""templatable"" v-html=""panel.pivot.html"" :class=""panel.css_class""> </div> </div> </div>","<div class=""portlet portlet-sortable light bordered"" :id=""guid""> <div class=""portlet-title""> <div class=""caption font-green-sharp""> <i class=""icon-speech font-green-sharp""></i> <span class=""caption-subject""> @{{panel.libelle}}</span> </div> <div class=""actions""> @if (!isset($disableAdd) || !$disableAdd) <button type=""button"" class=""btn btn-circle red-sunglo "" v-on:click='remove()'> <i class=""fa fa-close""></i> Supprimer </button> <button type=""button"" class=""btn btn-circle btn-default"" v-on:click='duplicate()'> <i class=""fa fa-clone""></i> Dupliquer </button> @endif <button type=""button"" class=""btn btn-circle btn-default"" v-on:click='reset()' > <i class=""fa fa-eraser""></i> Reset </button> <button type=""button"" class=""btn btn-circle btn-icon-only btn-default btn-draggable ""> <i class=""fa fa-arrows""></i> </button> <button type=""button"" class=""btn btn-circle btn-icon-only btn-default fullscreen""> </button> </div> </div> <div class=""portlet-body""> <div class=""templatable"" v-html=""panel.pivot.html"" :class=""panel.css_class""> </div> </div> </div>" Add publishes for future migrations,"<?php /** * @author Ben Rowe <ben.rowe.83@gmail.com> * @license http://www.opensource.org/licenses/mit-license.html MIT License */ namespace Benrowe\Laravel\Config; use Illuminate\Support\ServiceProvider; /** * Service Provider for Config * * @package Benrowe\Laravel\Config; */ class ServiceProvider extends ServiceProvider { protected $defer = false; /** * Boot the configuration component * * @return nil */ public function boot() { # publish necessary files $this->publishes([ __DIR__ . '/../config/config.php' => config_path('config.php'), ], 'config'); $this->publishes([ __DIR__.'/../migrations/' => database_path('migrations'), ], 'migrations'); } /** * Register an instance of the component * * @return void */ public function register() { $this->app->singleton('config', function () { return new Config(); }); } /** * Define the services this provider will build & provide * * @return array */ public function provides() { return [ 'Benrowe\Laravel\Config\Config', 'config' ]; } /** * Get the configuration destination path * * @return string */ protected function getConfigPath() { return ; } } ","<?php /** * @author Ben Rowe <ben.rowe.83@gmail.com> * @license http://www.opensource.org/licenses/mit-license.html MIT License */ namespace Benrowe\Laravel\Config; use Illuminate\Support\ServiceProvider; /** * Service Provider for Config * * @package Benrowe\Laravel\Config; */ class ServiceProvider extends ServiceProvider { protected $defer = false; /** * Boot the configuration component * * @return nil */ public function boot() { $configPath = __DIR__ . '/../config/config.php'; $this->publishes([ $configPath => $this->getConfigPath(), ], 'config'); } /** * Register an instance of the component * * @return void */ public function register() { $this->app->singleton('config', function () { return new Config(); }); } /** * Define the services this provider will build & provide * * @return array */ public function provides() { return [ 'Benrowe\Laravel\Config\Config', 'config' ]; } /** * Get the configuration destination path * * @return string */ protected function getConfigPath() { return config_path('config.php'); } } " "Set priority on incoming nodes starting opacity. Similar to 1740afee36da67cfbee9d36703f9e93f9735ecde","var partialRight = require('./partial-right') , d3 = require('d3') , DnD = require('./dnd') module.exports = function (tree) { var dnd = new DnD(tree) , listener = d3.behavior.drag() listener.on('dragstart', dnd.start) .on('drag', dnd.drag) .on('dragend', dnd.end) return function (selection, transformStyle, cssClasses) { var transitions = tree.el.select('.tree').classed('transitions') , enter = selection.enter() .append('li') .attr('class', 'node ' + (cssClasses || '') + (transitions ? ' transitioning-node' : '')) .classed('selected', function (d) { return d.selected }) .on('click', partialRight(tree._onSelect.bind(tree), tree.options)) .call(listener) .style(tree.prefix + 'transform', transformStyle) .call(tree.options.contents, tree, transitions) if (transitions) { enter.style('opacity', 1e-6, 'important') tree._forceRedraw() // Force a redraw so we see the updates transitioning d3.timer(function () { // Remove transitioning-node once the transitions have ended selection.classed('transitioning-node', false) return true // run once }, tree.transitionTimeout) } return selection } } ","var partialRight = require('./partial-right') , d3 = require('d3') , DnD = require('./dnd') module.exports = function (tree) { var dnd = new DnD(tree) , listener = d3.behavior.drag() listener.on('dragstart', dnd.start) .on('drag', dnd.drag) .on('dragend', dnd.end) return function (selection, transformStyle, cssClasses) { var transitions = tree.el.select('.tree').classed('transitions') , enter = selection.enter() .append('li') .attr('class', 'node ' + (cssClasses || '') + (transitions ? ' transitioning-node' : '')) .classed('selected', function (d) { return d.selected }) .on('click', partialRight(tree._onSelect.bind(tree), tree.options)) .call(listener) .style(tree.prefix + 'transform', transformStyle) .call(tree.options.contents, tree, transitions) if (transitions) { enter.style('opacity', 1e-6) tree._forceRedraw() // Force a redraw so we see the updates transitioning d3.timer(function () { // Remove transitioning-node once the transitions have ended selection.classed('transitioning-node', false) return true // run once }, tree.transitionTimeout) } return selection } } " Add a missing next parameter.,"/*! * Ext JS Connect 0.0.1 * Copyright(c) 2010 Ext JS, Inc. * MIT Licensed */ var child_process = require('child_process'), sys = require('sys'); module.exports = { handle: function (err, req, res, next) { var writeHead = res.writeHead, write = res.write, end = res.end; res.writeHead = function (code, headers) { var type = headers[""Content-Type""], accept = req.headers[""accept-encoding""]; if (!(code === 200 && accept && accept.indexOf('gzip') >= 0 && type && (/(text|javascript)/).test(type))) { res.writeHead = writeHead; res.writeHead(code, headers); return; } headers[""Content-Encoding""] = ""gzip""; delete headers[""Content-Length""]; var gzip = child_process.spawn(""gzip"", [""-9""]); res.write = function (chunk, encoding) { gzip.stdin.write(chunk, encoding); }; res.end = function (chunk, encoding) { if (chunk) { res.write(chunk, encoding); } gzip.stdin.end(); }; gzip.stdout.addListener('data', function (chunk) { write.call(res, chunk); }); gzip.addListener(""exit"", function (code) { res.write = write; res.end = end; res.end(); }); res.writeHead = writeHead; res.writeHead(code, headers); }; next(); } };","/*! * Ext JS Connect 0.0.1 * Copyright(c) 2010 Ext JS, Inc. * MIT Licensed */ var child_process = require('child_process'), sys = require('sys'); module.exports = { handle: function (err, req, res) { var writeHead = res.writeHead, write = res.write, end = res.end; res.writeHead = function (code, headers) { var type = headers[""Content-Type""], accept = req.headers[""accept-encoding""]; if (!(code === 200 && accept && accept.indexOf('gzip') >= 0 && type && (/(text|javascript)/).test(type))) { res.writeHead = writeHead; res.writeHead(code, headers); return; } headers[""Content-Encoding""] = ""gzip""; delete headers[""Content-Length""]; var gzip = child_process.spawn(""gzip"", [""-9""]); res.write = function (chunk, encoding) { gzip.stdin.write(chunk, encoding); }; res.end = function (chunk, encoding) { if (chunk) { res.write(chunk, encoding); } gzip.stdin.end(); }; gzip.stdout.addListener('data', function (chunk) { write.call(res, chunk); }); gzip.addListener(""exit"", function (code) { res.write = write; res.end = end; res.end(); }); res.writeHead = writeHead; res.writeHead(code, headers); }; next(); } };" Allow entry of usernames in email field.,"from django import forms from django.contrib.auth import authenticate from django.contrib.auth.forms import AuthenticationForm as Form from django.utils.translation import ugettext_lazy as _ class AuthenticationForm(Form): """"""Authenticate a ``User`` by email and password."""""" def __init__(self, *args, **kwargs): super(AuthenticationForm, self).__init__(*args, **kwargs) del(self.fields['username']) self.fields.insert(0, 'email', forms.CharField(label=_(u""Email""))) def clean(self): email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') if email and password: self.user_cache = authenticate(username=email, password=password) if self.user_cache is None: raise forms.ValidationError(_(""Please enter a correct email "" ""and password. Note that the "" ""password is case-sensitive."")) elif not self.user_cache.is_active: raise forms.ValidationError(_(""This account is inactive."")) if self.request: if not self.request.session.test_cookie_worked(): raise forms.ValidationError(_(""Your Web browser doesn't "" ""appear to have cookies "" ""enabled. Cookies are required "" ""for logging in."")) return self.cleaned_data ","from django import forms from django.contrib.auth import authenticate from django.contrib.auth.forms import AuthenticationForm as Form from django.utils.translation import ugettext_lazy as _ class AuthenticationForm(Form): """"""Authenticate a ``User`` by email and password."""""" def __init__(self, *args, **kwargs): super(AuthenticationForm, self).__init__(*args, **kwargs) del(self.fields['username']) self.fields.insert(0, 'email', forms.EmailField(label=_(u""Email""))) def clean(self): email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') if email and password: self.user_cache = authenticate(username=email, password=password) if self.user_cache is None: raise forms.ValidationError(_(""Please enter a correct email "" ""and password. Note that the "" ""password is case-sensitive."")) elif not self.user_cache.is_active: raise forms.ValidationError(_(""This account is inactive."")) if self.request: if not self.request.session.test_cookie_worked(): raise forms.ValidationError(_(""Your Web browser doesn't "" ""appear to have cookies "" ""enabled. Cookies are required "" ""for logging in."")) return self.cleaned_data " "Fix button class on upload modal no issue - this makes sure that the cancel button on the upload modal gets the correct class","import ModalDialog from 'ghost/components/gh-modal-dialog'; import upload from 'ghost/assets/lib/uploader'; var UploadModal = ModalDialog.extend({ layoutName: 'components/gh-modal-dialog', didInsertElement: function () { this._super(); upload.call(this.$('.js-drop-zone'), {fileStorage: this.get('config.fileStorage')}); }, confirm: { reject: { func: function () { // The function called on rejection return true; }, buttonClass: 'btn btn-default', text: 'Cancel' // The reject button text }, accept: { buttonClass: 'btn btn-blue right', text: 'Save', // The accept button texttext: 'Save' func: function () { var imageType = 'model.' + this.get('imageType'); if (this.$('.js-upload-url').val()) { this.set(imageType, this.$('.js-upload-url').val()); } else { this.set(imageType, this.$('.js-upload-target').attr('src')); } return true; } } }, actions: { closeModal: function () { this.sendAction(); }, confirm: function (type) { var func = this.get('confirm.' + type + '.func'); if (typeof func === 'function') { func.apply(this); } this.sendAction(); this.sendAction('confirm' + type); } } }); export default UploadModal; ","import ModalDialog from 'ghost/components/gh-modal-dialog'; import upload from 'ghost/assets/lib/uploader'; var UploadModal = ModalDialog.extend({ layoutName: 'components/gh-modal-dialog', didInsertElement: function () { this._super(); upload.call(this.$('.js-drop-zone'), {fileStorage: this.get('config.fileStorage')}); }, confirm: { reject: { func: function () { // The function called on rejection return true; }, buttonClass: true, text: 'Cancel' // The reject button text }, accept: { buttonClass: 'btn btn-blue right', text: 'Save', // The accept button texttext: 'Save' func: function () { var imageType = 'model.' + this.get('imageType'); if (this.$('.js-upload-url').val()) { this.set(imageType, this.$('.js-upload-url').val()); } else { this.set(imageType, this.$('.js-upload-target').attr('src')); } return true; } } }, actions: { closeModal: function () { this.sendAction(); }, confirm: function (type) { var func = this.get('confirm.' + type + '.func'); if (typeof func === 'function') { func.apply(this); } this.sendAction(); this.sendAction('confirm' + type); } } }); export default UploadModal; " Fix mistake in web test case initilization,"<?php namespace Ivory\LuceneSearchBundle\Tests\Emulation; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase; use Symfony\Component\HttpKernel\Util\Filesystem; /** * Web test case * * @author GeLo <geloen.eric@gmail.com> */ class WebTestCase extends BaseWebTestCase { /** * @var boolean TRUE if the web test case has been initialized else FALSE */ protected static $initialize = array(); /** * Remove emulation cache & logs directories */ protected static function initialize($environment) { if(!isset(self::$initialize[$environment]) || (isset(self::$initialize[$environment]) && !self::$initialize[$environment])) { $filesystem = new Filesystem(); $filesystem->remove(__DIR__.'/cache/'.$environment); $filesystem->remove(__DIR__.'/logs'); self::$initialize[$environment] = true; } } /** *@override */ protected static function getKernelClass() { $kernelClass = 'AppKernel'; require_once __DIR__.DIRECTORY_SEPARATOR.$kernelClass.'.php'; return $kernelClass; } /** * Gets the kernel container * * @return Symfony\Component\DependencyInjection\ContainerInterface */ public static function createContainer(array $options = array('environment' => 'default')) { self::initialize($options['environment']); $kernel = self::createKernel($options); $kernel->boot(); return $kernel->getContainer(); } } ","<?php namespace Ivory\LuceneSearchBundle\Tests\Emulation; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase; use Symfony\Component\HttpKernel\Util\Filesystem; /** * Web test case * * @author GeLo <geloen.eric@gmail.com> */ class WebTestCase extends BaseWebTestCase { /** * @var boolean TRUE if the web test case has been initialized else FALSE */ protected static $initialize = array(); /** * Remove emulation cache & logs directories */ protected static function initialize($environment) { if(!isset(self::$initialize[$environment]) || (isset(self::$initialize[$environment]) && self::$initialize[$environment])) { $filesystem = new Filesystem(); $filesystem->remove(__DIR__.'/cache/'.$environment); $filesystem->remove(__DIR__.'/logs'); self::$initialize[$environment] = true; } } /** *@override */ protected static function getKernelClass() { $kernelClass = 'AppKernel'; require_once __DIR__.DIRECTORY_SEPARATOR.$kernelClass.'.php'; return $kernelClass; } /** * Gets the kernel container * * @return Symfony\Component\DependencyInjection\ContainerInterface */ public static function createContainer(array $options = array('environment' => 'default')) { self::initialize($options['environment']); $kernel = self::createKernel($options); $kernel->boot(); return $kernel->getContainer(); } } " Optimize backend button click function,"define('app/views/backend_button', ['ember'], /** * Backend Button View * * @returns Class */ function() { return Ember.View.extend({ template: Ember.Handlebars.compile(""{{title}}""), tagName: 'a', attributeBindings: ['data-role', 'data-theme', 'data-inline', 'data-role', 'data-icon'], didInsertElement: function() { if ('button' in $(""#""+this.elementId)) { Ember.run.next(this, function() { $(""#""+this.elementId).button(); $('#backend-buttons').controlgroup('refresh'); }); } else { Ember.run.later(this, function() { this.didInsertElement(); }, 100); } }, click: function() { var backend = this.backend; $('#monitoring-message').hide(); $('#backend-delete-confirm').hide(); Mist.backendEditController.set('backend', backend); $('#backend-toggle option[value=1]')[0].selected = backend.enabled; $('#backend-toggle').slider('refresh'); $(""#edit-backend"").popup('option', 'positionTo', '#' + this.elementId).popup('open', {transition: 'pop'}); } }); } ); ","define('app/views/backend_button', ['ember'], /** * Backend Button View * * @returns Class */ function() { return Ember.View.extend({ template: Ember.Handlebars.compile(""{{title}}""), tagName: 'a', attributeBindings: ['data-role', 'data-theme', 'data-inline', 'data-role', 'data-icon'], didInsertElement: function() { if ('button' in $(""#""+this.elementId)) { Ember.run.next(this, function() { $(""#""+this.elementId).button(); $('#backend-buttons').controlgroup('refresh'); }); } else { Ember.run.later(this, function() { this.didInsertElement(); }, 100); } }, click: function() { var backend = this.backend; Mist.backendEditController.set('backend', backend); $('select.ui-slider-switch option[value=1]')[0].selected = backend.enabled; $('select.ui-slider-switch').slider('refresh'); $(""#edit-backend"").popup('option', 'positionTo', '#' + this.elementId).popup('open', {transition: 'pop'}); } }); } ); " Connect to 3 peers in Managertest,"<?php namespace BitWasp\Bitcoin\Tests\Networking\P2P; use BitWasp\Bitcoin\Bitcoin; use BitWasp\Bitcoin\Networking\Peer\Locator; use BitWasp\Bitcoin\Tests\Networking\AbstractTestCase; use React\Promise\Deferred; class ManagerTest extends AbstractTestCase { public function testManager() { $loop = new \React\EventLoop\StreamSelectLoop(); $factory = new \BitWasp\Bitcoin\Networking\Factory($loop); $peerFactory = $factory->getPeerFactory($factory->getDns()); $connector = $peerFactory->getConnector(); $locator = $peerFactory->getLocator($connector); $manager = $peerFactory->getManager($locator); $deferred = new Deferred(); $locator->queryDnsSeeds()->then(function () use ($manager, $deferred) { $manager->connectToPeers(3)->then(function () use ($deferred) { $deferred->resolve(); }, function () use ($deferred) { $deferred->reject(); }); }); $worked = false; $deferred->promise() ->then(function () use (&$worked) { $worked = true; }, function () use (&$worked) { $worked = false; }) ->always(function () use ($loop) { $loop->stop(); }); $loop->run(); $this->assertTrue($worked); } } ","<?php namespace BitWasp\Bitcoin\Tests\Networking\P2P; use BitWasp\Bitcoin\Bitcoin; use BitWasp\Bitcoin\Networking\Peer\Locator; use BitWasp\Bitcoin\Tests\Networking\AbstractTestCase; use React\Promise\Deferred; class ManagerTest extends AbstractTestCase { public function testManager() { $loop = new \React\EventLoop\StreamSelectLoop(); $factory = new \BitWasp\Bitcoin\Networking\Factory($loop); $peerFactory = $factory->getPeerFactory($factory->getDns()); $connector = $peerFactory->getConnector(); $locator = $peerFactory->getLocator($connector); $manager = $peerFactory->getManager($locator); $deferred = new Deferred(); $locator->queryDnsSeeds()->then(function () use ($manager, $deferred) { $manager->connectToPeers(1)->then(function () use ($deferred) { $deferred->resolve(); }, function () use ($deferred) { $deferred->reject(); }); }); $worked = false; $deferred->promise() ->then(function () use (&$worked) { $worked = true; }, function () use (&$worked) { $worked = false; }) ->always(function () use ($loop) { $loop->stop(); }); $loop->run(); $this->assertTrue($worked); } } " Support all Enumerables in proxy,"<?php namespace Illuminate\Support; /** * @mixin \Illuminate\Support\Enumerable */ class HigherOrderCollectionProxy { /** * The collection being operated on. * * @var \Illuminate\Support\Enumerable */ protected $collection; /** * The method being proxied. * * @var string */ protected $method; /** * Create a new proxy instance. * * @param \Illuminate\Support\Enumerable $collection * @param string $method * @return void */ public function __construct(Enumerable $collection, $method) { $this->method = $method; $this->collection = $collection; } /** * Proxy accessing an attribute onto the collection items. * * @param string $key * @return mixed */ public function __get($key) { return $this->collection->{$this->method}(function ($value) use ($key) { return is_array($value) ? $value[$key] : $value->{$key}; }); } /** * Proxy a method call onto the collection items. * * @param string $method * @param array $parameters * @return mixed */ public function __call($method, $parameters) { return $this->collection->{$this->method}(function ($value) use ($method, $parameters) { return $value->{$method}(...$parameters); }); } } ","<?php namespace Illuminate\Support; /** * @mixin \Illuminate\Support\Collection */ class HigherOrderCollectionProxy { /** * The collection being operated on. * * @var \Illuminate\Support\Collection */ protected $collection; /** * The method being proxied. * * @var string */ protected $method; /** * Create a new proxy instance. * * @param \Illuminate\Support\Collection $collection * @param string $method * @return void */ public function __construct(Collection $collection, $method) { $this->method = $method; $this->collection = $collection; } /** * Proxy accessing an attribute onto the collection items. * * @param string $key * @return mixed */ public function __get($key) { return $this->collection->{$this->method}(function ($value) use ($key) { return is_array($value) ? $value[$key] : $value->{$key}; }); } /** * Proxy a method call onto the collection items. * * @param string $method * @param array $parameters * @return mixed */ public function __call($method, $parameters) { return $this->collection->{$this->method}(function ($value) use ($method, $parameters) { return $value->{$method}(...$parameters); }); } } " Allow author_id on public API,"import BlogPost from '../database/models/blog-post'; import log from '../log'; const PUBLIC_API_ATTRIBUTES = [ 'id', 'title', 'link', 'description', 'date_updated', 'date_published', 'author_id' ]; const DEFAULT_ORDER = [ ['date_published', 'DESC'] ]; export function getAll() { return new Promise((resolve, reject) => { BlogPost.findAll({ attributes: PUBLIC_API_ATTRIBUTES, order: DEFAULT_ORDER, raw: true }) .then(resolve) .catch(error => { log.error({ error }, 'Error getting list of all posts'); reject(error); }); }); } export function getById(id) { return new Promise((resolve, reject) => { BlogPost.findOne({ attributes: PUBLIC_API_ATTRIBUTES, where: { id }, raw: true }) .then(resolve) .catch(error => { log.error({ error }, 'Error getting blog post by id'); reject(error); }); }); } export function getPage(pageNumber, pageSize) { return new Promise((resolve, reject) => { BlogPost.findAll({ attributes: PUBLIC_API_ATTRIBUTES, order: DEFAULT_ORDER, offset: pageNumber * pageSize, limit: pageSize, raw: true }) .then(resolve) .catch(error => { log.error({ error }, 'Error getting page of posts'); reject(error); }); }); } ","import BlogPost from '../database/models/blog-post'; import log from '../log'; const PUBLIC_API_ATTRIBUTES = [ 'id', 'title', 'link', 'description', 'date_updated', 'date_published' ]; const DEFAULT_ORDER = [ ['date_published', 'DESC'] ]; export function getAll() { return new Promise((resolve, reject) => { BlogPost.findAll({ attributes: PUBLIC_API_ATTRIBUTES, order: DEFAULT_ORDER, raw: true }) .then(resolve) .catch(error => { log.error({ error }, 'Error getting list of all posts'); reject(error); }); }); } export function getById(id) { return new Promise((resolve, reject) => { BlogPost.findOne({ attributes: PUBLIC_API_ATTRIBUTES, where: { id }, raw: true }) .then(resolve) .catch(error => { log.error({ error }, 'Error getting blog post by id'); reject(error); }); }); } export function getPage(pageNumber, pageSize) { return new Promise((resolve, reject) => { BlogPost.findAll({ attributes: PUBLIC_API_ATTRIBUTES, order: DEFAULT_ORDER, offset: pageNumber * pageSize, limit: pageSize, raw: true }) .then(resolve) .catch(error => { log.error({ error }, 'Error getting page of posts'); reject(error); }); }); } " Remove unnecessary check for error,"var fs = require('fs') , findExec = require('find-exec') , child_process = require('child_process') , players = [ 'mplayer', 'afplay', 'mpg123', 'mpg321', 'play' ] function Play(opts){ opts = opts || {} this.players = opts.players || players this.player = opts.player || findExec(this.players) var exec = child_process.exec this.play = function(what, next){ next = next || function(){} if (!what) return next(new Error(""No audio file specified"")); try { if (!fs.statSync(what).isFile()){ return next(new Error(what + "" is not a file"")); } } catch (err){ return next(new Error(""File doesn't exist: "" + what)); } if (!this.player){ return next(new Error(""Couldn't find a suitable audio player"")) } exec(this.player + ' ' + what, function(err, stdout, stderr){ return next(err); }) } this.test = function(next) { this.play('./assets/test.mp3', next) } } module.exports = function(opts){ return new Play(opts) } ","var fs = require('fs') , findExec = require('find-exec') , child_process = require('child_process') , players = [ 'mplayer', 'afplay', 'mpg123', 'mpg321', 'play' ] function Play(opts){ opts = opts || {} this.players = opts.players || players this.player = opts.player || findExec(this.players) var exec = child_process.exec this.play = function(what, next){ next = next || function(){} if (!what) return next(new Error(""No audio file specified"")); try { if (!fs.statSync(what).isFile()){ return next(new Error(what + "" is not a file"")); } } catch (err){ return next(new Error(""File doesn't exist: "" + what)); } if (!this.player){ return next(new Error(""Couldn't find a suitable audio player"")) } exec(this.player + ' ' + what, function(err, stdout, stderr){ if (err) return next(err) return next(); }) } this.test = function(next) { this.play('./assets/test.mp3', next) } } module.exports = function(opts){ return new Play(opts) } " Set default 32 bit cipher,"<?php namespace CodeZero\Encrypter; use Illuminate\Contracts\Encryption\DecryptException as IlluminateDecryptException; use Illuminate\Contracts\Encryption\Encrypter as IlluminateEncrypter; use Illuminate\Encryption\Encrypter as DefaultIlluminateEncrypter; class DefaultEncrypter implements Encrypter { /** * Laravel's Encrypter * * @var IlluminateEncrypter */ private $encrypter; /** * Create a new instance of LaravelEncrypter * * @param string $key * @param IlluminateEncrypter $encrypter */ public function __construct($key, IlluminateEncrypter $encrypter = null) { $this->encrypter = $encrypter ?: new DefaultIlluminateEncrypter(md5($key), 'AES-256-CBC'); } /** * Encrypt a string * * @param string $string * * @return string */ public function encrypt($string) { return $this->encrypter->encrypt($string); } /** * Decrypt an encrypted string * * @param string $payload * * @return string * @throws DecryptException */ public function decrypt($payload) { try { $decrypted = $this->encrypter->decrypt($payload); } catch (IlluminateDecryptException $exception) { throw new DecryptException('Decryption failed.', 0, $exception); } return $decrypted; } } ","<?php namespace CodeZero\Encrypter; use Illuminate\Contracts\Encryption\DecryptException as IlluminateDecryptException; use Illuminate\Contracts\Encryption\Encrypter as IlluminateEncrypter; use Illuminate\Encryption\Encrypter as DefaultIlluminateEncrypter; class DefaultEncrypter implements Encrypter { /** * Laravel's Encrypter * * @var IlluminateEncrypter */ private $encrypter; /** * Create a new instance of LaravelEncrypter * * @param string $key * @param IlluminateEncrypter $encrypter */ public function __construct($key, IlluminateEncrypter $encrypter = null) { $this->encrypter = $encrypter ?: new DefaultIlluminateEncrypter(md5($key)); } /** * Encrypt a string * * @param string $string * * @return string */ public function encrypt($string) { return $this->encrypter->encrypt($string); } /** * Decrypt an encrypted string * * @param string $payload * * @return string * @throws DecryptException */ public function decrypt($payload) { try { $decrypted = $this->encrypter->decrypt($payload); } catch (IlluminateDecryptException $exception) { throw new DecryptException('Decryption failed.', 0, $exception); } return $decrypted; } } " Add back navigation to commit history activity.,"package com.gh4a.activities; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v7.app.ActionBar; import com.gh4a.BaseActivity; import com.gh4a.Constants; import com.gh4a.R; import com.gh4a.fragment.CommitListFragment; import com.gh4a.utils.IntentUtils; public class CommitHistoryActivity extends BaseActivity { private String mRepoOwner; private String mRepoName; private String mRef; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (hasErrorView()) { return; } setContentView(R.layout.generic_list); Bundle extras = getIntent().getExtras(); String filePath = extras.getString(Constants.Object.PATH); mRepoOwner = extras.getString(Constants.Repository.OWNER); mRepoName = extras.getString(Constants.Repository.NAME); mRef = extras.getString(Constants.Object.REF); if (savedInstanceState == null) { CommitListFragment fragment = CommitListFragment.newInstance(mRepoOwner, mRepoName, mRef, filePath); FragmentManager fm = getSupportFragmentManager(); fm.beginTransaction().add(R.id.content_container, fragment).commit(); } ActionBar actionBar = getSupportActionBar(); actionBar.setTitle(R.string.history); actionBar.setSubtitle(filePath); actionBar.setDisplayHomeAsUpEnabled(true); } @Override protected Intent navigateUp() { return IntentUtils.getRepoActivityIntent(this, mRepoOwner, mRepoName, mRef); } }","package com.gh4a.activities; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v7.app.ActionBar; import com.gh4a.BaseActivity; import com.gh4a.Constants; import com.gh4a.R; import com.gh4a.fragment.CommitListFragment; public class CommitHistoryActivity extends BaseActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (hasErrorView()) { return; } setContentView(R.layout.generic_list); Bundle extras = getIntent().getExtras(); String filePath = extras.getString(Constants.Object.PATH); if (savedInstanceState == null) { CommitListFragment fragment = CommitListFragment.newInstance( extras.getString(Constants.Repository.OWNER), extras.getString(Constants.Repository.NAME), extras.getString(Constants.Object.REF), filePath); FragmentManager fm = getSupportFragmentManager(); fm.beginTransaction().add(R.id.content_container, fragment).commit(); } ActionBar actionBar = getSupportActionBar(); actionBar.setTitle(R.string.history); actionBar.setSubtitle(filePath); } }" Modify signup to hit signup api endpoint.,"angular.module('MovnThereUI').factory('AuthFactory', function($http, $window, ServerUrl) { 'use strict'; var login = function(credentials) { return $http .post(ServerUrl + 'login', credentials) .success(function(response) { $window.sessionStorage.setItem('movnThereUI.user', response.token); $http.defaults.headers.common['Authorization'] = 'Token token=' + $window.sessionStorage.getItem('movnThereUIUI.user'); }); }; var signup = function(credentials) { var params = { user: credentials }; return $http .post(ServerUrl + 'signup', params) .success(function(response) { $window.sessionStorage.setItem('movnThereUI.user', response.token); $http.defaults.headers.common['Authorization'] = 'Token token=' + $window.sessionStorage.getItem('movnThereUI.user'); }); }; var logout = function(credentials) { return $http .post(ServerUrl + '/logout') .success(function(response) { $window.sessionStorage.removeItem('movnThereUI.user'); }); }; var isAuthenticated = function() { return !!$window.sessionStorage.getItem('movnThereUI.user'); }; return { login: login, signup: signup, logout: logout, isAuthenticated: isAuthenticated }; }); ","angular.module('MovnThereUI').factory('AuthFactory', function($http, $window, ServerUrl) { 'use strict'; var login = function(credentials) { return $http .post(ServerUrl + 'login', credentials) .success(function(response) { $window.sessionStorage.setItem('movnThereUI.user', response.token); $http.defaults.headers.common['Authorization'] = 'Token token=' + $window.sessionStorage.getItem('movnThereUIUI.user'); }); }; var signup = function(credentials) { var params = { user: credentials }; return $http .post(ServerUrl + 'users', params) .success(function(response) { $window.sessionStorage.setItem('movnThereUI.user', response.token); $http.defaults.headers.common['Authorization'] = 'Token token=' + $window.sessionStorage.getItem('movnThereUI.user'); }); }; var logout = function(credentials) { return $http .post(ServerUrl + '/logout') .success(function(response) { $window.sessionStorage.removeItem('movnThereUI.user'); }); }; var isAuthenticated = function() { return !!$window.sessionStorage.getItem('movnThereUI.user'); }; return { login: login, signup: signup, logout: logout, isAuthenticated: isAuthenticated }; }); " Fix issue with wrong data in response,"/*! * apiai * Copyright(c) 2015 http://api.ai/ * Apache 2.0 Licensed */ 'use strict'; var Request = require('./request').Request; var util = require('util'); var ServerError = require('./exceptions').ServerError; exports.JSONApiRequest = module.exports.JSONApiRequest = JSONApiRequest; util.inherits(JSONApiRequest, Request); function JSONApiRequest () { JSONApiRequest.super_.apply(this, arguments); } JSONApiRequest.prototype._handleResponse = function(response) { var self = this; var body = ''; var buffers = []; var bufferLength = 0; response.on('data', function(chunk) { bufferLength += chunk.length; buffers.push(chunk); }); response.on('end', function() { if (bufferLength) { body = Buffer.concat(buffers, bufferLength).toString('utf8'); } buffers = []; bufferLength = 0; if (response.statusCode >= 200 && response.statusCode <= 299) { try { var json_body = JSON.parse(body); self.emit('response', json_body); } catch (error) { // JSON.parse can throw only one exception, SyntaxError // All another exceptions throwing from user function, // because it just rethrowing for better error handling. if (error instanceof SyntaxError) { self.emit('error', error); } else { throw error; } } } else { var error = new ServerError(response.statusCode, body, 'Wrong response status code.'); self.emit('error', error); } }); }; ","/*! * apiai * Copyright(c) 2015 http://api.ai/ * Apache 2.0 Licensed */ 'use strict'; var Request = require('./request').Request; var util = require('util'); var ServerError = require('./exceptions').ServerError; exports.JSONApiRequest = module.exports.JSONApiRequest = JSONApiRequest; util.inherits(JSONApiRequest, Request); function JSONApiRequest () { JSONApiRequest.super_.apply(this, arguments); } JSONApiRequest.prototype._handleResponse = function(response) { var self = this; var body = ''; response.on('data', function(chunk) { body += chunk; }); response.on('end', function() { if (response.statusCode >= 200 && response.statusCode <= 299) { try { var json_body = JSON.parse(body); self.emit('response', json_body); } catch (error) { // JSON.parse can throw only one exception, SyntaxError // All another exceptions throwing from user function, // because it just rethrowing for better error handling. if (error instanceof SyntaxError) { self.emit('error', error); } else { throw error; } } } else { var error = new ServerError(response.statusCode, body, 'Wrong response status code.'); self.emit('error', error); } }); }; " Add className to proptypes of textarea component,"import React, { Component } from 'react'; import PropTypes from 'prop-types'; import idgen from './idgen'; import Icon from './Icon'; import cx from 'classnames'; class Textarea extends Component { componentDidUpdate() { M.textareaAutoResize(this._textarea); } renderIcon(icon) { return <Icon className=""material-icons prefix"">{icon}</Icon>; } render() { const { className, iconClassName, icon, label, id, onChange, ...other } = this.props; const computedId = id || idgen(); return ( <div className=""input-field""> {icon && this.renderIcon(icon, iconClassName)} <textarea ref={input => { this._textarea = input; }} onChange={onChange} id={computedId} className={cx('materialize-textarea', className)} {...other} /> <label htmlFor={computedId}>{label}</label> </div> ); } } Textarea.propTypes = { /* * render icon next to input */ icon: PropTypes.string, /* * icon classname */ iconClassName: PropTypes.string, /* * textarea label */ label: PropTypes.string, /* * onChange callback */ onChange: PropTypes.func, /* * override id * @default idgen() */ id: PropTypes.string, /* * disabled input */ disabled: PropTypes.bool, /* * predefined value */ value: PropTypes.string, className: PropTypes.string }; export default Textarea; ","import React, { Component } from 'react'; import PropTypes from 'prop-types'; import idgen from './idgen'; import Icon from './Icon'; import cx from 'classnames'; class Textarea extends Component { componentDidUpdate() { M.textareaAutoResize(this._textarea); } renderIcon(icon) { return <Icon className=""material-icons prefix"">{icon}</Icon>; } render() { const { className, iconClassName, icon, label, id, onChange, ...other } = this.props; const computedId = id || idgen(); return ( <div className=""input-field""> {icon && this.renderIcon(icon, iconClassName)} <textarea ref={input => { this._textarea = input; }} onChange={onChange} id={computedId} className={cx('materialize-textarea', className)} {...other} /> <label htmlFor={computedId}>{label}</label> </div> ); } } Textarea.propTypes = { /* * render icon next to input */ icon: PropTypes.string, /* * icon classname */ iconClassName: PropTypes.string, /* * textarea label */ label: PropTypes.string, /* * onChange callback */ onChange: PropTypes.func, /* * override id * @default idgen() */ id: PropTypes.string, /* * disabled input */ disabled: PropTypes.bool, /* * predefined value */ value: PropTypes.string }; export default Textarea; " Use destructuring to remove noise,"import { h, Component } from 'preact' import { bind } from './util' export default class extends Component { constructor() { super() this.state.show = false } linkState(key) { return e => this.setState({ [key]: e.target.value }) } @bind toggleShow() { this.setState({ show: !this.state.show }) } clearState() { this.setState({ appName: '', username: '', password: '', show: false }) } @bind handleSubmit(e) { const { appName, username, password } = this.state e.preventDefault() this.props.add(appName, username, password) this.clearState() } render(_, { show, appName, username, password }) { return ( <section> <div style={{display: show ? 'block' : 'none'}}> <form onSubmit={this.handleSubmit}> <input name='appName' placeholder='Enter app name' value={appName} onInput={this.linkState('appName')} /> <input name='username' placeholder='Enter app username' value={username} onInput={this.linkState('username')} /> <input name='password' placeholder='Enter app password' value={password} onInput={this.linkState('password')} /> <button type='submit'>Save</button> </form> </div> <button onClick={this.toggleShow}>Add new app</button> </section> ) } } ","import { h, Component } from 'preact' import { bind } from './util' export default class extends Component { constructor() { super() this.state.show = false } linkState(key) { return e => this.setState({ [key]: e.target.value }) } @bind toggleShow() { this.setState({ show: !this.state.show }) } clearState() { this.setState({ appName: '', username: '', password: '', show: false }) } @bind handleSubmit(e) { e.preventDefault() this.props.add(this.state.appName, this.state.username, this.state.password) this.clearState() } render(_, { show, appName, username, password }) { return ( <section> <div style={{display: show ? 'block' : 'none'}}> <form onSubmit={this.handleSubmit}> <input name='appName' placeholder='Enter app name' value={appName} onInput={this.linkState('appName')} /> <input name='username' placeholder='Enter app username' value={username} onInput={this.linkState('username')} /> <input name='password' placeholder='Enter app password' value={password} onInput={this.linkState('password')} /> <button type='submit'>Save</button> </form> </div> <button onClick={this.toggleShow}>Add new app</button> </section> ) } } " Add js for aria-labelledby in conversations,"// @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-v3-or-Later app.views.ConversationsForm = Backbone.View.extend({ events: { ""keydown textarea#conversation_text"" : ""keyDown"", }, initialize: function(opts) { this.contacts = _.has(opts, ""contacts"") ? opts.contacts : null; this.prefill = []; if (_.has(opts, ""prefillName"") && _.has(opts, ""prefillValue"")) { this.prefill = [{name : opts.prefillName, value : opts.prefillValue}]; } this.autocompleteInput = $(""#contact_autocomplete""); this.prepareAutocomplete(this.contacts); }, prepareAutocomplete: function(data){ this.autocompleteInput.autoSuggest(data, { selectedItemProp: ""name"", searchObjProps: ""name"", asHtmlID: ""contact_ids"", retrieveLimit: 10, minChars: 1, keyDelay: 0, startText: '', emptyText: Diaspora.I18n.t(""no_results""), preFill: this.prefill }).focus(); $(""#contact_ids"").attr(""aria-labelledby"", ""toLabel""); }, keyDown : function(evt) { if( evt.keyCode === 13 && evt.ctrlKey ) { $(evt.target).parents(""form"").submit(); } } }); // @license-end ","// @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-v3-or-Later app.views.ConversationsForm = Backbone.View.extend({ events: { ""keydown textarea#conversation_text"" : ""keyDown"", }, initialize: function(opts) { this.contacts = _.has(opts, ""contacts"") ? opts.contacts : null; this.prefill = []; if (_.has(opts, ""prefillName"") && _.has(opts, ""prefillValue"")) { this.prefill = [{name : opts.prefillName, value : opts.prefillValue}]; } this.autocompleteInput = $(""#contact_autocomplete""); this.prepareAutocomplete(this.contacts); }, prepareAutocomplete: function(data){ this.autocompleteInput.autoSuggest(data, { selectedItemProp: ""name"", searchObjProps: ""name"", asHtmlID: ""contact_ids"", retrieveLimit: 10, minChars: 1, keyDelay: 0, startText: '', emptyText: Diaspora.I18n.t(""no_results""), preFill: this.prefill }).focus(); }, keyDown : function(evt) { if( evt.keyCode === 13 && evt.ctrlKey ) { $(evt.target).parents(""form"").submit(); } } }); // @license-end " Fix cprint: use stderr not stdout,"from __future__ import print_function import sys import string import json from colors import * def is_posix_filename(name, extra_chars=""""): CHARS = string.letters + string.digits + ""._-"" + extra_chars return all(c in CHARS for c in name) def cprint(color, msg, file=sys.stderr, end='\n'): if type(msg) is unicode: data = msg elif type(msg) is str: data = msg.__str__() print(color + data + RESET, file=file, end=end) def _assert(condition, msg): if condition: return cprint(LRED, msg) sys.exit(1) def to_unicode(obj, encoding='utf-8'): assert isinstance(obj, basestring), type(obj) if isinstance(obj, unicode): return obj for encoding in ['utf-8', 'latin1']: try: obj = unicode(obj, encoding) return obj except UnicodeDecodeError: pass assert False, ""tst: non-recognized encoding"" def data2json(data): def date_handler(obj): if hasattr(obj, 'isoformat'): return obj.isoformat() elif hasattr(obj, 'email'): return obj.email() return obj return json.dumps( data, default=date_handler, indent=2, separators=(',', ': '), sort_keys=True, ensure_ascii=False) ","from __future__ import print_function import sys import string import json from colors import * def is_posix_filename(name, extra_chars=""""): CHARS = string.letters + string.digits + ""._-"" + extra_chars return all(c in CHARS for c in name) def cprint(color, msg, file=sys.stdout, end='\n'): if type(msg) is unicode: data = msg elif type(msg) is str: data = msg.__str__() print(color + data + RESET, file=file, end=end) def _assert(condition, msg): if condition: return cprint(LRED, msg) sys.exit(1) def to_unicode(obj, encoding='utf-8'): assert isinstance(obj, basestring), type(obj) if isinstance(obj, unicode): return obj for encoding in ['utf-8', 'latin1']: try: obj = unicode(obj, encoding) return obj except UnicodeDecodeError: pass assert False, ""tst: non-recognized encoding"" def data2json(data): def date_handler(obj): if hasattr(obj, 'isoformat'): return obj.isoformat() elif hasattr(obj, 'email'): return obj.email() return obj return json.dumps( data, default=date_handler, indent=2, separators=(',', ': '), sort_keys=True, ensure_ascii=False) " Fix write program telecommand part size,"import struct from telecommand import Telecommand class EraseBootTableEntry(Telecommand): def apid(self): return 0xB0 def payload(self): mask = 0 for e in self._entries: mask |= 1 << e return [mask] def __init__(self, entries): self._entries = entries class WriteProgramPart(Telecommand): MAX_PART_SIZE = Telecommand.MAX_PAYLOAD_SIZE - 5 def apid(self): return 0xB1 def payload(self): mask = 0 for e in self._entries: mask |= 1 << e return list(struct.pack('<BI', mask, self._offset)) + list(self._content) def __init__(self, entries, offset, content): self._offset = offset self._content = content self._entries = entries class FinalizeProgramEntry(Telecommand): def apid(self): return 0xB2 def payload(self): mask = 0 for e in self._entries: mask |= 1 << e return list(struct.pack('<BIH', mask, self._length, self._expected_crc)) + list(self._name) def __init__(self, entries, length, expected_crc, name): self._entries = entries self._length = length self._expected_crc = expected_crc self._name = name ","import struct from telecommand import Telecommand class EraseBootTableEntry(Telecommand): def apid(self): return 0xB0 def payload(self): mask = 0 for e in self._entries: mask |= 1 << e return [mask] def __init__(self, entries): self._entries = entries class WriteProgramPart(Telecommand): MAX_PART_SIZE = Telecommand.MAX_PAYLOAD_SIZE - 3 def apid(self): return 0xB1 def payload(self): mask = 0 for e in self._entries: mask |= 1 << e return list(struct.pack('<BI', mask, self._offset)) + list(self._content) def __init__(self, entries, offset, content): self._offset = offset self._content = content self._entries = entries class FinalizeProgramEntry(Telecommand): def apid(self): return 0xB2 def payload(self): mask = 0 for e in self._entries: mask |= 1 << e return list(struct.pack('<BIH', mask, self._length, self._expected_crc)) + list(self._name) def __init__(self, entries, length, expected_crc, name): self._entries = entries self._length = length self._expected_crc = expected_crc self._name = name " "[IMP] Set Picking Type in Create [IMP] Flake8","# Copyright 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' @api.model def _get_default_picking_type(self): return self.env['stock.picking.type'].search([ ('code', '=', 'stock_request_order'), ('warehouse_id.company_id', 'in', [self.env.context.get('company_id', self.env.user.company_id.id), False])], limit=1).id picking_type_id = fields.Many2one( 'stock.picking.type', 'Operation Type', default=_get_default_picking_type, required=True) @api.onchange('warehouse_id') def onchange_warehouse_picking_id(self): if self.warehouse_id: picking_type_id = self.env['stock.picking.type'].\ search([('code', '=', 'stock_request_order'), ('warehouse_id', '=', self.warehouse_id.id)], limit=1) if picking_type_id: self._origin.write({'picking_type_id': picking_type_id.id}) @api.model def create(self, vals): if vals.get('warehouse_id', False): picking_type_id = self.env['stock.picking.type'].\ search([('code', '=', 'stock_request_order'), ('warehouse_id', '=', vals['warehouse_id'])], limit=1) if picking_type_id: vals.update({'picking_type_id': picking_type_id.id}) return super().create(vals) ","# Copyright 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' @api.model def _get_default_picking_type(self): return self.env['stock.picking.type'].search([ ('code', '=', 'stock_request_order'), ('warehouse_id.company_id', 'in', [self.env.context.get('company_id', self.env.user.company_id.id), False])], limit=1).id picking_type_id = fields.Many2one( 'stock.picking.type', 'Operation Type', default=_get_default_picking_type, required=True) @api.onchange('warehouse_id') def onchange_warehouse_picking_id(self): if self.warehouse_id: picking_type_id = self.env['stock.picking.type'].\ search([('code', '=', 'stock_request_order'), ('warehouse_id', '=', self.warehouse_id.id)], limit=1) if picking_type_id: self._origin.write({'picking_type_id': picking_type_id.id}) " "Use chrome headless as travis can't display chrome Travis failed the build as chrome couldn't launch OHM-1059","'use strict' // Karma configuration // http://karma-runner.github.io/0.10/config/configuration-file.html module.exports = function (config) { config.set({ // base path, that will be used to resolve files and exclude basePath: '', // testing framework to use (jasmine/mocha/qunit/...) frameworks: ['mocha', 'sinon-chai', 'dirty-chai'], // list of files / patterns to load in the browser files: [ 'node_modules/angular/angular.js', 'node_modules/angular-mocks/angular-mocks.js', 'node_modules/moment/moment.js', 'dist/bundle.js', { pattern: 'dist/bundle.js.map', included: false, watched: false }, 'dist/index.html', { pattern: 'dist/fonts/*', watched: false, included: false, served: true, nocache: false }, 'test/spec/controllers/*.js' ], proxies: { '/fonts/': 'http://localhost:8090/base/dist/fonts/' }, reporters: ['mocha'], // list of files / patterns to exclude exclude: [], // web server port port: 8090, mochaReporter: { showDiff: true, output: 'autowatch' }, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: ['ChromeHeadless'] }) } ","'use strict' // Karma configuration // http://karma-runner.github.io/0.10/config/configuration-file.html module.exports = function (config) { config.set({ // base path, that will be used to resolve files and exclude basePath: '', // testing framework to use (jasmine/mocha/qunit/...) frameworks: ['mocha', 'sinon-chai', 'dirty-chai'], // list of files / patterns to load in the browser files: [ 'node_modules/angular/angular.js', 'node_modules/angular-mocks/angular-mocks.js', 'node_modules/moment/moment.js', 'dist/bundle.js', { pattern: 'dist/bundle.js.map', included: false, watched: false }, 'dist/index.html', { pattern: 'dist/fonts/*', watched: false, included: false, served: true, nocache: false }, 'test/spec/controllers/*.js' ], proxies: { '/fonts/': 'http://localhost:8090/base/dist/fonts/' }, reporters: ['mocha'], // list of files / patterns to exclude exclude: [], // web server port port: 8090, mochaReporter: { showDiff: true, output: 'autowatch' }, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: ['Chrome'] }) } " Fix example code broken by After lib API changes,"<?php // 101_parallel_async_requests.php require __DIR__ . '/../vendor/autoload.php'; (new Alert\ReactorFactory)->select()->run(function($reactor) { $client = new Artax\Client($reactor); $startTime = microtime(true); $promises = []; foreach (range('a', 'z') as $alpha) { $uri = 'http://www.bing.com/search?q=' . $alpha; $promise = $client->request($uri); $promise->onResolve(function($error, $result) use ($reactor, $uri) { if ($error) { echo $error->getMessage(), ""\n""; } else { printf( ""HTTP/%s %d %s | %s\n"", $result->getProtocol(), $result->getStatus(), $result->getReason(), $uri ); } }); $promises[$alpha] = $promise; } After\some($promises)->onResolve(function() use ($reactor, $startTime) { printf(""26 parallel HTTP requests completed in %s seconds\n"", microtime(true) - $startTime); $reactor->stop(); }); }); ","<?php // 101_parallel_async_requests.php require __DIR__ . '/../vendor/autoload.php'; (new Alert\ReactorFactory)->select()->run(function($reactor) { $client = new Artax\Client($reactor); $startTime = microtime(true); $promises = []; foreach (range('a', 'z') as $alpha) { $uri = 'http://www.bing.com/search?q=' . $alpha; $promise = $client->request($uri); $promise->onResolution(function($error, $result) use ($reactor, $uri) { if ($error) { echo $error->getMessage(), ""\n""; } else { printf( ""HTTP/%s %d %s | %s\n"", $result->getProtocol(), $result->getStatus(), $result->getReason(), $uri ); } }); $promises[$alpha] = $promise; } After\some($promises)->onResolution(function() use ($reactor, $startTime) { printf(""26 parallel HTTP requests completed in %s seconds\n"", microtime(true) - $startTime); $reactor->stop(); }); }); " Update keys to match warnings,"// @flow import React, { Component } from 'react'; import { Link } from 'react-router'; import { Text } from 'react-dom'; import _ from 'underscore'; import styles from './Window2.css'; import ALL_DATA from '../fixtures/alldata.js'; const ALL_DATA_BY_ID = _.indexBy(ALL_DATA, 'id'); class Window2 extends Component { render() { function linkify(text){ let i=0; return ( <div className=""fullText""> { text.split(' ').map( function(word){ i++; if (word.indexOf('<Link>') > -1) { const [,url,text]= word.split('|'); return <Link key={i} to={url}>{text}</Link> } else { return word+' ' } } ) } </div> ); } const fullText = linkify(ALL_DATA_BY_ID[this.props.params.id].fullText); const { currentSearch, updateSearch } = this.props; return ( <div className=""window2""> <div className=""row""> <p>Window2</p> {fullText} </div> </div> ); } } export default Window2; ","// @flow import React, { Component } from 'react'; import { Link } from 'react-router'; import { Text } from 'react-dom'; import _ from 'underscore'; import styles from './Window2.css'; import ALL_DATA from '../fixtures/alldata.js'; const ALL_DATA_BY_ID = _.indexBy(ALL_DATA, 'id'); class Window2 extends Component { render() { function linkify(text){ return ( <div className=""fullText""> { text.split(' ').map( function(word){ if (word.indexOf('<Link>') > -1) { const [,url,text]= word.split('|'); return <Link to={url}>{text}</Link> } else { return word+' ' } } ) } </div> ); } const fullText = linkify(ALL_DATA_BY_ID[this.props.params.id].fullText); const { currentSearch, updateSearch } = this.props; return ( <div className=""window2""> <div className=""row""> <p>Window2</p> {fullText} </div> </div> ); } } export default Window2; " Fix linter error caused by in-range update to eslint,"'use strict'; /* global window:false */ const Bluefox = require('bluefox'); const log = require('../../../../lib/logger')({hostname: 'content', MODULE: 'wait/content/index'}); const trackRunResultEvents = require('./trackRunResultEvents'); const registerRunnerModule = require('../../../content-register'); registerRunnerModule('wait', async ({eventEmitter, getModule}) => { const runResultModule = await getModule('runResult'); const bluefox = new Bluefox(); const wait = bluefox.target(window); eventEmitter.on('tabs.initializedTabContent', () => { const drain = trackRunResultEvents(runResultModule, bluefox); eventEmitter.on('tabs.beforeContentUnload', () => { try { log.debug('Creating run result events...'); drain(); } catch (err) { log.error({err}, 'Error while creating runResult events'); } }); }); return { scriptValue: metadata => { if (typeof metadata.waitBeginTime === 'number') { return wait.overrideStartTime(metadata.waitBeginTime); } if (typeof metadata.runBeginTime === 'number') { return wait.overrideStartTime(metadata.runBeginTime); } return wait; }, }; }); ","'use strict'; /* global window:false, performance:false */ const Bluefox = require('bluefox'); const log = require('../../../../lib/logger')({hostname: 'content', MODULE: 'wait/content/index'}); const trackRunResultEvents = require('./trackRunResultEvents'); const registerRunnerModule = require('../../../content-register'); registerRunnerModule('wait', async ({eventEmitter, getModule}) => { const runResultModule = await getModule('runResult'); const bluefox = new Bluefox(); const wait = bluefox.target(window); eventEmitter.on('tabs.initializedTabContent', () => { const drain = trackRunResultEvents(runResultModule, bluefox); eventEmitter.on('tabs.beforeContentUnload', () => { try { log.debug('Creating run result events...'); drain(); } catch (err) { log.error({err}, 'Error while creating runResult events'); } }); }); return { scriptValue: metadata => { if (typeof metadata.waitBeginTime === 'number') { return wait.overrideStartTime(metadata.waitBeginTime); } if (typeof metadata.runBeginTime === 'number') { return wait.overrideStartTime(metadata.runBeginTime); } return wait; }, }; }); " Implement note delete api endpoint,"<?php namespace App\Http\Controllers; use App\Models\Note; use Illuminate\Support\Facades\Request; use Symfony\Component\HttpFoundation\Response; class NoteController extends Controller { /** * List all notes */ public function index() { $notes = Note::with([ 'user', 'tags', ])->get(); return $notes; } public function show(int $id) { return (new Note())->find($id); } /** * Create a new note * @param Request $request * @return string */ public function store(Request $request) { return 'Implement creation of note.'; } /** * Update a note * @param Request $request * @param int $id * @return string */ public function update(Request $request, int $id) { return 'Implement update of note.'; } /** * Delete a note * @param int $id * @return string */ public function destroy(int $id) { $note = Note::find($id); if ($note === null) { $statusCode = Response::HTTP_NOT_FOUND; } else { $note->delete(); $statusCode = Response::HTTP_NO_CONTENT; } return response('', $statusCode); } /** * Shows most recent note */ public function latest() { $note = Note::with([ 'user', 'tags', ]) ->orderBy('updated_at', 'DESC') ->first(); return $note; } } ","<?php namespace App\Http\Controllers; use App\Models\Note; use Illuminate\Support\Facades\Request; class NoteController extends Controller { /** * List all notes */ public function index() { $notes = Note::with([ 'user', 'tags', ])->get(); return $notes; } public function show(int $id) { return (new Note())->find($id); } /** * Create a new note * @param Request $request * @return string */ public function store(Request $request) { return 'Implement creation of note.'; } /** * Update a note * @param Request $request * @param int $id * @return string */ public function update(Request $request, int $id) { return 'Implement update of note.'; } /** * Delete a note * @param int $id * @return string */ public function destroy(int $id) { return 'Implement delete of note.'; } /** * Shows most recent note */ public function latest() { $note = Note::with([ 'user', 'tags', ]) ->orderBy('updated_at', 'DESC') ->first(); return $note; } } " Remove redundant newline from Colorbox init JS.,"$(document).ready(function () { $.colorbox.settings = $.extend({}, $.colorbox.settings, { maxWidth: '90%', opacity: 0.7, scrolling: false }); var translatable = [ 'current', 'previous', 'next', 'close', 'xhrError', 'imgError', 'slideshowStart', 'slideshowStop' ]; var locale = {}; for (var i = 0; i < translatable.length; i++) { locale[translatable[i]] = Translator.trans('colorbox.' + translatable[i]); } var init; (init = function (context) { $(context) .on('click', 'a.colorbox_ajax[href]', function (e) { e.preventDefault(); var $link = $(this); var url = $link.attr('href'); if (!url || '#' === url) { return; } $.colorbox($.extend({}, locale, { href: url, title: $link.attr('title') })); }) .find('.colorbox').colorbox(locale); })('body'); $(document).on('searchComplete', function (e, results) { init(results); }); }); ","$(document).ready(function () { $.colorbox.settings = $.extend({}, $.colorbox.settings, { maxWidth: '90%', opacity: 0.7, scrolling: false }); var translatable = [ 'current', 'previous', 'next', 'close', 'xhrError', 'imgError', 'slideshowStart', 'slideshowStop' ]; var locale = {}; for (var i = 0; i < translatable.length; i++) { locale[translatable[i]] = Translator.trans('colorbox.' + translatable[i]); } var init; (init = function (context) { $(context) .on('click', 'a.colorbox_ajax[href]', function (e) { e.preventDefault(); var $link = $(this); var url = $link.attr('href'); if (!url || '#' === url) { return; } $.colorbox($.extend({}, locale, { href: url, title: $link.attr('title') })); }) .find('.colorbox').colorbox(locale); })('body'); $(document).on('searchComplete', function (e, results) { init(results); }); }); " LightDisplay: Rename `pins` option to `segments`,"module.exports = (five) => { const Animation = require('./animation')(five) const Segment = require('./segment')(five) class LightDisplay { constructor (options) { if (Array.isArray(options)) { options = { segments: options } } this.segments = options.segments.map((segmentOptions) => new Segment(segmentOptions)) } on () { this.start({ name: '__constant__' }) } off () { return this.stop() .then(() => { this.segments.forEach((segment) => segment.off()) }) } start (options) { if (typeof options === 'string') { options = { name: options } } return this.off() .then(() => { options = Object.assign({ segments: this.segments }, options) return Animation.get(options) }) .then((animation) => { this.currentAnimation = animation animation.start() }) } stop () { if (!this.currentAnimation) { return Promise.resolve() } return this.currentAnimation.stop() .then(() => { this.currentAnimation = null }) } } Object.assign(LightDisplay, { Animation, Segment }) return LightDisplay } ","module.exports = (five) => { const Animation = require('./animation')(five) const Segment = require('./segment')(five) class LightDisplay { constructor (options) { if (Array.isArray(options)) { options = { pins: options } } this.segments = options.pins.map((pin) => new Segment(pin)) } on () { this.start({ name: '__constant__' }) } off () { return this.stop() .then(() => { this.segments.forEach((segment) => segment.off()) }) } start (options) { if (typeof options === 'string') { options = { name: options } } return this.off() .then(() => { options = Object.assign({ segments: this.segments }, options) return Animation.get(options) }) .then((animation) => { this.currentAnimation = animation animation.start() }) } stop () { if (!this.currentAnimation) { return Promise.resolve() } return this.currentAnimation.stop() .then(() => { this.currentAnimation = null }) } } Object.assign(LightDisplay, { Animation, Segment }) return LightDisplay } " Change total_score in Employee Serializer,"from .models import Employee from rest_framework import serializers class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee depth = 1 fields = ('pk', 'username', 'email', 'first_name', 'last_name', 'avatar', 'role', 'skype_id', 'last_month_score', 'current_month_score', 'level', 'score', 'categories', 'is_active', 'last_login') class EmployeeListSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'username', 'email', 'first_name', 'last_name', 'level', 'avatar', 'score')","from .models import Employee from rest_framework import serializers class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee depth = 1 fields = ('pk', 'username', 'email', 'first_name', 'last_name', 'avatar', 'role', 'skype_id', 'last_month_score', 'current_month_score', 'level', 'score', 'categories', 'is_active', 'last_login') class EmployeeListSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'username', 'email', 'first_name', 'last_name', 'level', 'avatar', 'total_score')" Add new css class to new WP 3.5 controls," <!-- Content upload <?php echo $id ?> --> <div id=""<?php echo $id ?>_content"" class=""<?php echo $group ? 'smallbox' : 'stuffbox' ?>""> <h3> <label for=""<?php echo $id ?>""><?php echo $title ?></label> </h3> <div class=""inside upload""> <div class=""upload_image_via_wp""> <input type=""text"" name=""<?php echo $id ?>"" id=""<?php echo $id ?>"" value=""<?php echo $val ?>"" readonly=""readonly"" /> <?php if (current_user_can('upload_files')) : ?> <div id=""wp-<?php echo $id ?>-editor-tools"" class=""wp-editor-tools customized hide-if-no-js""> <?php do_action('media_buttons', $id) ?> </div> <?php else: ?> <?php _e('It seems you are not able to upload files.') ?> <?php endif ?> </div> <?php if (!empty($val)): ?> <br class=""clear""/> <div class=""upload_image_result""> <a href=""<?php echo $val ?>"" target=""_blank""> <img src=""<?php echo $val ?>"" alt="""" /> </a> <a href=""<?php echo $val ?>"" target=""_blank""> <?php _e('See image in its real sizes.') ?> </a> </div> <?php endif ?> <p><?php echo $description ?></p> </div> </div> <!-- /Content upload <?php echo $id ?> -->"," <!-- Content upload <?php echo $id ?> --> <div id=""<?php echo $id ?>_content"" class=""<?php echo $group ? 'smallbox' : 'stuffbox' ?>""> <h3> <label for=""<?php echo $id ?>""><?php echo $title ?></label> </h3> <div class=""inside upload""> <div class=""upload_image_via_wp""> <input type=""text"" name=""<?php echo $id ?>"" id=""<?php echo $id ?>"" value=""<?php echo $val ?>"" readonly=""readonly"" /> <?php if (current_user_can('upload_files')) : ?> <div id=""wp-<?php echo $id ?>-editor-tools"" class=""wp-editor-tools hide-if-no-js""> <?php do_action('media_buttons', $id) ?> </div> <?php else: ?> <?php _e('It seems you are not able to upload files.') ?> <?php endif ?> </div> <?php if (!empty($val)): ?> <br class=""clear""/> <div class=""upload_image_result""> <a href=""<?php echo $val ?>"" target=""_blank""> <img src=""<?php echo $val ?>"" alt="""" /> </a> <a href=""<?php echo $val ?>"" target=""_blank""> <?php _e('See image in its real sizes.') ?> </a> </div> <?php endif ?> <p><?php echo $description ?></p> </div> </div> <!-- /Content upload <?php echo $id ?> -->" Make test case base compatible with Python 3," ''' PEXPECT LICENSE This license is approved by the OSI and FSF as GPL-compatible. http://opensource.org/licenses/isc-license.txt Copyright (c) 2012, Noah Spurrier <noah@noah.org> PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES. THE SOFTWARE IS PROVIDED ""AS IS"" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ''' from __future__ import print_function import unittest import sys import os class PexpectTestCase(unittest.TestCase): def setUp(self): self.PYTHONBIN = sys.executable self.original_path = os.getcwd() newpath = os.path.join (os.environ['PROJECT_PEXPECT_HOME'], 'tests') os.chdir (newpath) print('\n', self.id(), end='') unittest.TestCase.setUp(self) def tearDown(self): os.chdir (self.original_path) "," ''' PEXPECT LICENSE This license is approved by the OSI and FSF as GPL-compatible. http://opensource.org/licenses/isc-license.txt Copyright (c) 2012, Noah Spurrier <noah@noah.org> PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES. THE SOFTWARE IS PROVIDED ""AS IS"" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ''' import unittest import sys import os class PexpectTestCase(unittest.TestCase): def setUp(self): self.PYTHONBIN = sys.executable self.original_path = os.getcwd() newpath = os.path.join (os.environ['PROJECT_PEXPECT_HOME'], 'tests') os.chdir (newpath) print '\n', self.id(), unittest.TestCase.setUp(self) def tearDown(self): os.chdir (self.original_path) " Fix modding v2 activation link in admin view,"{{-- Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. See the LICENCE file in the repository root for full licence text. --}} @extends('master', ['titlePrepend' => trans('layout.header.admin.beatmapset')]) @section('content') @include('admin/_header') <div class=""osu-page osu-page--admin""> <h1>{{ $beatmapset->title }} - {{ $beatmapset->artist }}</h1> <ul> <li>{{ trans('admin.beatmapsets.show.discussion._') }}: @if ($beatmapset->discussion_enabled) {{ trans('admin.beatmapsets.show.discussion.active') }} @else {{ trans('admin.beatmapsets.show.discussion.inactive') }} / <a href=""{{ route('admin.beatmapsets.update', [ $beatmapset->getKey(), 'beatmapset[discussion_enabled]' => true, ]) }}"" data-method=""PUT"" data-confirm=""{{ trans('admin.beatmapsets.show.discussion.activate_confirm') }}"" >{{ trans('admin.beatmapsets.show.discussion.activate') }}</a> @endif </li> <li><a href=""{{ route('admin.beatmapsets.covers', $beatmapset->beatmapset_id) }}"">{{ trans('admin.beatmapsets.show.covers') }}</a></li> </ul> </div> @endsection ","{{-- Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. See the LICENCE file in the repository root for full licence text. --}} @extends('master', ['titlePrepend' => trans('layout.header.admin.beatmapset')]) @section('content') @include('admin/_header') <div class=""osu-page osu-page--admin""> <h1>{{ $beatmapset->title }} - {{ $beatmapset->artist }}</h1> <ul> <li>{{ trans('admin.beatmapsets.show.discussion._') }}: @if ($beatmapset->discussion_enabled) {{ trans('admin.beatmapsets.show.discussion.active') }} @else {{ trans('admin.beatmapsets.show.discussion.inactive') }} / <a href=""{{ route('admin.beatmapsets.update', [ 'beatmapsets' => $beatmapset->getKey(), 'beatmapset[discussion_enabled]=1' ]) }}"" data-method=""PUT"" data-confirm=""{{ trans('admin.beatmapsets.show.discussion.activate_confirm') }}"" >{{ trans('admin.beatmapsets.show.discussion.activate') }}</a> @endif </li> <li><a href=""{{ route('admin.beatmapsets.covers', $beatmapset->beatmapset_id) }}"">{{ trans('admin.beatmapsets.show.covers') }}</a></li> </ul> </div> @endsection " Fix typo in array access,"<?php namespace EventDispatcher\EventManager; use Zend\EventManager\EventManagerInterface; use Zend\ServiceManager\ServiceLocatorInterface; use Zend\Mvc\MvcEvent; class Dispatcher { protected $config = array(); protected $sm; public function __construct(array $config, ServiceLocatorInterface $sm) { $this->config = $config; $this->sm = $sm; } public function attachListeners(EventManagerInterface $eventManager) { $events = array( 'bootstrap', 'dispatch', 'dispatch.error', 'finish', 'render', 'render.error', 'route' ); foreach ($events as $event) { if (isset($this->config[$event]) && count($this->config[$event]) > 0) { $this->attachFor($eventManager, $event); } } } protected function attachFor(EventManagerInterface $eventManager, $eventName) { foreach ($this->config[$eventName] as $serviceName => $priority) { if (is_numeric($serviceName)) { // not an associative array $serviceName = $priority; $priority = 1; } $sm = $this->sm; $eventManager->attach($eventName, function ($event) use ($sm, $serviceName) { $listener = $sm->get($serviceName); return $listener->onEvent($event); }, $priority); } } } ","<?php namespace EventDispatcher\EventManager; use Zend\EventManager\EventManagerInterface; use Zend\ServiceManager\ServiceLocatorInterface; use Zend\Mvc\MvcEvent; class Dispatcher { protected $config = array(); protected $sm; public function __construct(array $config, ServiceLocatorInterface $sm) { $this->config = $config; $this->sm = $sm; } public function attachListeners(EventManagerInterface $eventManager) { $events = array( 'bootstrap', 'dispatch', 'dispatch.error', 'finish', 'render', 'render.error', 'route' ); foreach ($events as $event) { if (isset($this->config($event)) && count($this->config[$event]) > 0) { $this->attachFor($eventManager, $event); } } } protected function attachFor(EventManagerInterface $eventManager, $eventName) { foreach ($this->config[$eventName] as $serviceName => $priority) { if (is_numeric($serviceName)) { // not an associative array $serviceName = $priority; $priority = 1; } $sm = $this->sm; $eventManager->attach($eventName, function ($event) use ($sm, $serviceName) { $listener = $sm->get($serviceName); return $listener->onEvent($event); }, $priority); } } } " "Change metric type to int32 This was done as we may now send a -1 to indicate that we could not obtain response timing from request.","#!/usr/bin/env python from maas_common import (status_ok, status_err, metric, get_keystone_client, get_auth_ref) from requests import Session from requests import exceptions as exc def check(auth_ref): keystone = get_keystone_client(auth_ref) tenant_id = keystone.tenant_id auth_token = keystone.auth_token registry_endpoint = 'http://127.0.0.1:9191' api_status = 1 milliseconds = 0 s = Session() s.headers.update( {'Content-type': 'application/json', 'x-auth-token': auth_token}) try: # /images returns a list of public, non-deleted images r = s.get('%s/images' % registry_endpoint, verify=False, timeout=10) except (exc.ConnectionError, exc.HTTPError, exc.Timeout): api_status = 0 milliseconds = -1 except Exception as e: status_err(str(e)) else: milliseconds = r.elapsed.total_seconds() * 1000 if not r.ok: api_status = 0 status_ok() metric('glance_registry_local_status', 'uint32', api_status) metric('glance_registry_local_response_time', 'int32', milliseconds) def main(): auth_ref = get_auth_ref() check(auth_ref) if __name__ == ""__main__"": main() ","#!/usr/bin/env python from maas_common import (status_ok, status_err, metric, get_keystone_client, get_auth_ref) from requests import Session from requests import exceptions as exc def check(auth_ref): keystone = get_keystone_client(auth_ref) tenant_id = keystone.tenant_id auth_token = keystone.auth_token registry_endpoint = 'http://127.0.0.1:9191' api_status = 1 milliseconds = 0 s = Session() s.headers.update( {'Content-type': 'application/json', 'x-auth-token': auth_token}) try: # /images returns a list of public, non-deleted images r = s.get('%s/images' % registry_endpoint, verify=False, timeout=10) except (exc.ConnectionError, exc.HTTPError, exc.Timeout): api_status = 0 milliseconds = -1 except Exception as e: status_err(str(e)) else: milliseconds = r.elapsed.total_seconds() * 1000 if not r.ok: api_status = 0 status_ok() metric('glance_registry_local_status', 'uint32', api_status) metric('glance_registry_local_response_time', 'uint32', milliseconds) def main(): auth_ref = get_auth_ref() check(auth_ref) if __name__ == ""__main__"": main() " Add redirect to login page for when cookie is not found on logout,"/** * Created by Omnius on 6/26/16. */ 'use strict'; const retrieveFromToken = require(process.cwd() + '/server/helpers/hkdfTokenGenerator').retrieveFromToken; module.exports = () => { return (request, reply) => { const server = request.server; const redis = request.redis; const dao = server.methods.dao; const userCredentialDao = dao.userCredentialDao; const cookieSession = request.state['Hawk-Session-Token']; if (!(cookieSession && cookieSession.hawkSessionToken)) { server.log([], 'session cookie not found'); return reply.redirect('/login'); } const ikm = cookieSession.hawkSessionToken; const info = request.info.host + '/hawkSessionToken'; const salt = ''; const length = 2 * 32; server.log('ikm: ' + ikm + ' info: ' + info + ' salt: ' + salt + ' length: ' + length); retrieveFromToken(ikm, info, salt, length, (sessionId) => { userCredentialDao.deleteUserCredential(redis, sessionId, (err) => { if (err) { server.log(['error', 'database', 'delete'], err); } return reply.redirect('/login') .unstate('Hawk-Session-Token'); }); }); }; }; ","/** * Created by Omnius on 6/26/16. */ 'use strict'; const retrieveFromToken = require(process.cwd() + '/server/helpers/hkdfTokenGenerator').retrieveFromToken; module.exports = () => { return (request, reply) => { const server = request.server; const redis = request.redis; const dao = server.methods.dao; const userCredentialDao = dao.userCredentialDao; const cookieSession = request.state['Hawk-Session-Token']; const ikm = cookieSession.hawkSessionToken; const info = request.info.host + '/hawkSessionToken'; const salt = ''; const length = 2 * 32; server.log('ikm: ' + ikm + ' info: ' + info + ' salt: ' + salt + ' length: ' + length); retrieveFromToken(ikm, info, salt, length, (sessionId) => { userCredentialDao.deleteUserCredential(redis, sessionId, (err) => { if (err) { server.log(err); } return reply.redirect('/') .unstate('Hawk-Session-Token') .header('X-Permitted-Cross-Domain-Policies', 'master-only'); }); }); }; }; " Make ignore_errors False by default,"import contextlib import shutil import tempfile import numpy from chainer.utils import walker_alias # NOQA # import class and function from chainer.utils.conv import get_conv_outsize # NOQA from chainer.utils.conv import get_deconv_outsize # NOQA from chainer.utils.experimental import experimental # NOQA from chainer.utils.walker_alias import WalkerAlias # NOQA def force_array(x, dtype=None): # numpy returns a float value (scalar) when a return value of an operator # is a 0-dimension array. # We need to convert such a value to a 0-dimension array because `Function` # object needs to return an `numpy.ndarray`. if numpy.isscalar(x): if dtype is None: return numpy.array(x) else: return numpy.array(x, dtype) else: if dtype is None: return x else: return x.astype(dtype, copy=False) def force_type(dtype, value): if numpy.isscalar(value): return dtype.type(value) elif value.dtype != dtype: return value.astype(dtype, copy=False) else: return value @contextlib.contextmanager def tempdir(**kwargs): # A context manager that defines a lifetime of a temporary directory. ignore_errors = kwargs.pop('ignore_errors', False) temp_dir = tempfile.mkdtemp(**kwargs) try: yield temp_dir finally: shutil.rmtree(temp_dir, ignore_errors=ignore_errors) ","import contextlib import shutil import tempfile import numpy from chainer.utils import walker_alias # NOQA # import class and function from chainer.utils.conv import get_conv_outsize # NOQA from chainer.utils.conv import get_deconv_outsize # NOQA from chainer.utils.experimental import experimental # NOQA from chainer.utils.walker_alias import WalkerAlias # NOQA def force_array(x, dtype=None): # numpy returns a float value (scalar) when a return value of an operator # is a 0-dimension array. # We need to convert such a value to a 0-dimension array because `Function` # object needs to return an `numpy.ndarray`. if numpy.isscalar(x): if dtype is None: return numpy.array(x) else: return numpy.array(x, dtype) else: if dtype is None: return x else: return x.astype(dtype, copy=False) def force_type(dtype, value): if numpy.isscalar(value): return dtype.type(value) elif value.dtype != dtype: return value.astype(dtype, copy=False) else: return value @contextlib.contextmanager def tempdir(**kwargs): # A context manager that defines a lifetime of a temporary directory. temp_dir = tempfile.mkdtemp(**kwargs) try: yield temp_dir finally: shutil.rmtree(temp_dir, ignore_errors=True) " Remove loading of css files,"var ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { context: __dirname + '/app', entry: ['./app.jsx'], output: { filename: 'molten.js', path: './dist', publicPath: 'assets' }, module: { loaders: [ { test: /\.jsx?$/, exclude: /(node_modules|bower_components)/, loader: 'babel' }, { test: /\.less$/, loader: ExtractTextPlugin.extract( // activate source maps via loader query 'css?sourceMap!' + 'less?sourceMap' ) }, { test: /\.png$/, loader: 'url-loader?limit=100000&mimetype=image/png' } ] }, resolve: { alias: { react: __dirname + '/node_modules/react', 'react/addons': __dirname + '/node_modules/react/addons' }, root: __dirname + '/app', extensions: ['', '.js', '.jsx'], modulesDirectories: ['node_modules'] }, devtool: 'source-map', devServer: { headers: { 'Access-Control-Allow-Origin': '*' } }, plugins: [ // extract inline css into separate 'styles.css' new ExtractTextPlugin('styles.css') ] }; ","var ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { context: __dirname + '/app', entry: ['./app.jsx'], output: { filename: 'molten.js', path: './dist', publicPath: 'assets' }, module: { loaders: [ { test: /\.jsx?$/, exclude: /(node_modules|bower_components)/, loader: 'babel' }, { test: /\.css$/, loader: 'style-loader!css-loader' }, { test: /\.less$/, loader: ExtractTextPlugin.extract( // activate source maps via loader query 'css?sourceMap!' + 'less?sourceMap' ) }, { test: /\.png$/, loader: 'url-loader?limit=100000&mimetype=image/png' } ] }, resolve: { alias: { react: __dirname + '/node_modules/react', 'react/addons': __dirname + '/node_modules/react/addons' }, root: __dirname + '/app', extensions: ['', '.js', '.jsx'], modulesDirectories: ['node_modules'] }, devtool: 'source-map', devServer: { headers: { 'Access-Control-Allow-Origin': '*' } }, plugins: [ // extract inline css into separate 'styles.css' new ExtractTextPlugin('styles.css') ] }; " Add support for reading snapshots for auditor reader,"# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> scope = ""System Implied"" description = """""" A user with Auditor role for a program audit will also have this role in the default object context so that the auditor will have access to the objects required to perform the audit. """""" permissions = { ""read"": [ ""Snapshot"", ""Categorization"", ""Category"", ""ControlCategory"", ""ControlAssertion"", ""Control"", ""Assessment"", ""Issue"", ""ControlControl"", ""DataAsset"", ""AccessGroup"", ""Directive"", ""Contract"", ""Policy"", ""Regulation"", ""Standard"", ""Document"", ""Facility"", ""Help"", ""Market"", ""Objective"", ""ObjectDocument"", ""ObjectPerson"", ""Option"", ""OrgGroup"", ""Vendor"", ""PopulationSample"", ""Product"", ""Project"", ""Relationship"", ""Section"", ""Clause"", ""SystemOrProcess"", ""System"", ""Process"", ""SystemControl"", ""SystemSystem"", ""ObjectOwner"", ""Person"", ""Program"", ""Role"", ""Context"", { ""type"": ""BackgroundTask"", ""terms"": { ""property_name"": ""modified_by"", ""value"": ""$current_user"" }, ""condition"": ""is"" }, ], ""create"": [], ""view_object_page"": [], ""update"": [], ""delete"": [] } ","# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> scope = ""System Implied"" description = """""" A user with Auditor role for a program audit will also have this role in the default object context so that the auditor will have access to the objects required to perform the audit. """""" permissions = { ""read"": [ ""Categorization"", ""Category"", ""ControlCategory"", ""ControlAssertion"", ""Control"", ""Assessment"", ""Issue"", ""ControlControl"", ""DataAsset"", ""AccessGroup"", ""Directive"", ""Contract"", ""Policy"", ""Regulation"", ""Standard"", ""Document"", ""Facility"", ""Help"", ""Market"", ""Objective"", ""ObjectDocument"", ""ObjectPerson"", ""Option"", ""OrgGroup"", ""Vendor"", ""PopulationSample"", ""Product"", ""Project"", ""Relationship"", ""Section"", ""Clause"", ""SystemOrProcess"", ""System"", ""Process"", ""SystemControl"", ""SystemSystem"", ""ObjectOwner"", ""Person"", ""Program"", ""Role"", ""Context"", { ""type"": ""BackgroundTask"", ""terms"": { ""property_name"": ""modified_by"", ""value"": ""$current_user"" }, ""condition"": ""is"" }, ], ""create"": [], ""view_object_page"": [], ""update"": [], ""delete"": [] } " Enable the new Chrome fix in the demo,"<player-demo> <player-splash show={!app.route.link}></player-splash> <player-video if={app.route.link}></player-video> <script> var self = this; function updateRoute(grouping, group, link) { app.route.grouping = grouping; app.route.group = group; app.route.link = link; self.update(); if (!app.route.link) { if (window.player) window.player.destruct(); window.player = null; } else { var linkObj = Link.findBySlug(grouping, group, link); window.player = new Player({ url: linkObj.url, element: $('#video-stream'), ignoreAudio: false, showVideoEvents: false, chromeDOMFixInterval: 60 }); } } // catch updates to the route once the app has booted riot.route(updateRoute); // set the initial route on app boot (if # url is // already present - riot doesn't do this automatically) // wait a small amount of time so components are rendered // (if a link is part of the URL, the video element needs // to be present before processing) setTimeout(function() { riot.route.exec(updateRoute); }, 100); </script> </player-demo> ","<player-demo> <player-splash show={!app.route.link}></player-splash> <player-video if={app.route.link}></player-video> <script> var self = this; function updateRoute(grouping, group, link) { app.route.grouping = grouping; app.route.group = group; app.route.link = link; self.update(); if (!app.route.link) { if (window.player) window.player.destruct(); window.player = null; } else { var linkObj = Link.findBySlug(grouping, group, link); window.player = new Player({ url: linkObj.url, element: $('#video-stream'), ignoreAudio: false, showVideoEvents: false }); } } // catch updates to the route once the app has booted riot.route(updateRoute); // set the initial route on app boot (if # url is // already present - riot doesn't do this automatically) // wait a small amount of time so components are rendered // (if a link is part of the URL, the video element needs // to be present before processing) setTimeout(function() { riot.route.exec(updateRoute); }, 100); </script> </player-demo> " Check in Chai assertions that they have been given TestMongo,"import isEqual from 'lodash/isEqual' import { collectionAttachedSchema } from '../schemaHelper' const collectionLabel = collection => collection._name ? `collection named ""${collection._name}""` : '#{this}' const assetTestMongo = (collection, chai) => { chai.assert( collection.constructor && collection.constructor.name === 'TestMongo', 'expected an instance of TestMongo', 'expected not an instance of TestMongo', ) } export const plugin = (chai) => { const Assertion = chai.Assertion Assertion.addProperty('schema', function schemaProperty() { const collection = this._obj assetTestMongo(collection, this) const label = collectionLabel(collection) this.assert( collectionAttachedSchema(collection), `expected ${label} to have an attached schema`, `expected ${label} to not have an attached schema`, ) }) Assertion.addMethod('index', function indexMethod(fields) { const collection = this._obj assetTestMongo(collection, this) const label = collectionLabel(collection) const matchingIndex = collection.indexes.find((idx) => { const keys = Object.entries(idx.keys) return fields.every((f, i) => typeof f === 'string' ? f === keys[i][0] : isEqual(Object.entries(f)[0], keys[i])) }) this.assert( matchingIndex, `expected ${label} to have an index #{exp} from #{act}`, `expected ${label} to not have an index #{exp}`, fields, collection.indexes.map(idx => idx.keys), ) }) } ","import isEqual from 'lodash/isEqual' import { collectionAttachedSchema } from '../schemaHelper' const collectionLabel = collection => collection._name ? `collection named ""${collection._name}""` : '#{this}' function assetTestMongo() { const collection = this._obj this.assert( collection.constructor && collection.constructor.name === 'TestMongo', 'expected an instance of TestMongo', 'expected not an instance of TestMongo', ) } export const plugin = (chai) => { const Assertion = chai.Assertion Assertion.addProperty('schema', function schemaProperty() { assetTestMongo() const collection = this._obj const label = collectionLabel(collection) this.assert( collectionAttachedSchema(collection), `expected ${label} to have an attached schema`, `expected ${label} to not have an attached schema`, ) }) Assertion.addMethod('index', function indexMethod(fields) { assetTestMongo() const collection = this._obj const label = collectionLabel(collection) const matchingIndex = collection.indexes.find((idx) => { const keys = Object.entries(idx.keys) return fields.every((f, i) => typeof f === 'string' ? f === keys[i][0] : isEqual(Object.entries(f)[0], keys[i])) }) this.assert( matchingIndex, `expected ${label} to have an index #{exp} from #{act}`, `expected ${label} to not have an index #{exp}`, fields, collection.indexes.map(idx => idx.keys), ) }) } " Remove imaginary event server CLI options,"import click import sys @click.command() @click.option('--acme', help='The address for the ACME Directory Resource', default='https://acme-v01.api.letsencrypt.org/directory', show_default=True) @click.option('--email', help=(""Email address for Let's Encrypt certificate registration "" ""and recovery contact""), required=True) @click.option('--storage-dir', help='Path to directory for storing certificates') @click.option('--marathon', default='http://marathon.mesos:8080', help='The address for the Marathon HTTP API', show_default=True) @click.option('--poll', help=(""Periodically check Marathon's state every _n_ seconds "" ""[default: disabled]""), type=int) @click.option('--logfile', help='Where to log output to [default: stdout]', type=click.File('a'), default=sys.stdout) @click.option('--debug', help='Log debug output', is_flag=True) def main(acme, email, storage_dir, # ACME/certificates marathon, poll, # Marathon logfile, debug): # Logging """""" A tool to automatically request, renew and distribute Let's Encrypt certificates for apps running on Seed Stack. """""" ","import click import sys @click.command() @click.option('--acme', help='The address for the ACME Directory Resource', default='https://acme-v01.api.letsencrypt.org/directory', show_default=True) @click.option('--email', help=(""Email address for Let's Encrypt certificate registration "" ""and recovery contact""), required=True) @click.option('--storage-dir', help='Path to directory for storing certificates') @click.option('--marathon', default='http://marathon.mesos:8080', help='The address for the Marathon HTTP API', show_default=True) @click.option('--listen', help=(""The address of the interface and port to bind to to "" ""receive Marathon's event stream""), default='0.0.0.0:7000', show_default=True) @click.option('--advertise', default='http://marathon-acme.marathon.mesos', help=('The address to advertise to Marathon when registering ' 'for the event stream'), show_default=True) @click.option('--poll', help=(""Periodically check Marathon's state every _n_ seconds "" ""[default: disabled]""), type=int) @click.option('--logfile', help='Where to log output to [default: stdout]', type=click.File('a'), default=sys.stdout) @click.option('--debug', help='Log debug output', is_flag=True) def main(acme, email, storage_dir, # ACME marathon, listen, advertise, poll, # Marathon logfile, debug): # Logging """""" A tool to automatically request, renew and distribute Let's Encrypt certificates for apps running on Seed Stack. """""" " Add example for download icon,"import React from 'react'; import Icon from 'src/Icon'; function BasicIconsSet() { return ( <div> <Icon type=""add"" /> <Icon type=""edit"" /> <Icon type=""duplicate"" /> <Icon type=""copypaste"" /> <Icon type=""tickets"" /> <Icon type=""trashcan"" /> <Icon type=""drag"" /> <Icon type=""success"" /> <Icon type=""error"" /> <Icon type=""delete"" /> <Icon type=""header-next"" /> <Icon type=""header-prev"" /> <Icon type=""fold"" /> <Icon type=""unfold"" /> <Icon type=""next"" /> <Icon type=""prev"" /> <Icon type=""folder"" /> <Icon type=""loading"" spinning /> <Icon type=""lock"" /> <Icon type=""unlock"" /> <Icon type=""radio-empty"" /> <Icon type=""radio-half"" /> <Icon type=""radio-selected"" /> <Icon type=""picture"" /> <Icon type=""printer"" /> <Icon type=""pause"" /> <Icon type=""play"" /> <Icon type=""search"" /> <Icon type=""download"" /> </div> ); } export default BasicIconsSet; ","import React from 'react'; import Icon from 'src/Icon'; function BasicIconsSet() { return ( <div> <Icon type=""add"" /> <Icon type=""edit"" /> <Icon type=""duplicate"" /> <Icon type=""copypaste"" /> <Icon type=""tickets"" /> <Icon type=""trashcan"" /> <Icon type=""drag"" /> <Icon type=""success"" /> <Icon type=""error"" /> <Icon type=""delete"" /> <Icon type=""header-next"" /> <Icon type=""header-prev"" /> <Icon type=""fold"" /> <Icon type=""unfold"" /> <Icon type=""next"" /> <Icon type=""prev"" /> <Icon type=""folder"" /> <Icon type=""loading"" spinning /> <Icon type=""lock"" /> <Icon type=""unlock"" /> <Icon type=""radio-empty"" /> <Icon type=""radio-half"" /> <Icon type=""radio-selected"" /> <Icon type=""picture"" /> <Icon type=""printer"" /> <Icon type=""pause"" /> <Icon type=""play"" /> <Icon type=""search"" /> </div> ); } export default BasicIconsSet; " Add API client to global envar,"# -*- coding: utf8 -*- """"""Jinja globals module for pybossa-discourse."""""" from flask import Markup, request from . import discourse_client class DiscourseGlobals(object): """"""A class to implement Discourse Global variables."""""" def __init__(self, app): self.url = app.config['DISCOURSE_URL'] self.api = discourse_client app.jinja_env.globals.update(discourse=self) def comments(self): """"""Return an HTML snippet used to embed Discourse comments."""""" return Markup("""""" <div id=""discourse-comments""></div> <script type=""text/javascript""> DiscourseEmbed = {{ discourseUrl: '{0}/', discourseEmbedUrl: '{1}' }}; window.onload = function() {{ let d = document.createElement('script'), head = document.getElementsByTagName('head')[0], body = document.getElementsByTagName('body')[0]; d.type = 'text/javascript'; d.async = true; d.src = '{0}/javascripts/embed.js'; (head || body).appendChild(d); }} </script> """""").format(self.url, request.base_url) def notifications(self): """"""Return a count of unread notifications for the current user."""""" notifications = discourse_client.user_notifications() if not notifications: return 0 return sum([1 for n in notifications['notifications'] if not n['read']]) ","# -*- coding: utf8 -*- """"""Jinja globals module for pybossa-discourse."""""" from flask import Markup, request from . import discourse_client class DiscourseGlobals(object): """"""A class to implement Discourse Global variables."""""" def __init__(self, app): self.url = app.config['DISCOURSE_URL'] app.jinja_env.globals.update(discourse=self) def comments(self): """"""Return an HTML snippet used to embed Discourse comments."""""" return Markup("""""" <div id=""discourse-comments""></div> <script type=""text/javascript""> DiscourseEmbed = {{ discourseUrl: '{0}/', discourseEmbedUrl: '{1}' }}; window.onload = function() {{ let d = document.createElement('script'), head = document.getElementsByTagName('head')[0], body = document.getElementsByTagName('body')[0]; d.type = 'text/javascript'; d.async = true; d.src = '{0}/javascripts/embed.js'; (head || body).appendChild(d); }} </script> """""").format(self.url, request.base_url) def notifications(self): """"""Return a count of unread notifications for the current user."""""" notifications = discourse_client.user_notifications() if not notifications: return 0 return sum([1 for n in notifications['notifications'] if not n['read']]) " Revert webpack entry point change,"const { resolve } = require('path') module.exports = { mode: 'production', entry: './dist.browser/browser/index.js', module: { rules: [ { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/ }, { test: /\.js$/, loader: 'file-replace-loader', options: { condition: 'always', replacement (resourcePath) { const mapping = { [resolve('./dist.browser/lib/logging.js')]: resolve( './browser/logging.js' ), [resolve('./dist.browser/lib/net/peer/libp2pnode.js')]: resolve( './browser/libp2pnode.js' ) } return mapping[resourcePath] }, async: true } } ] }, resolve: { extensions: ['.tsx', '.ts', '.js'] }, output: { filename: 'bundle.js', path: resolve(__dirname, 'dist'), library: 'ethereumjs' } } ","const { resolve } = require('path') module.exports = { mode: 'production', entry: './dist.browser/index.js', module: { rules: [ { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/ }, { test: /\.js$/, loader: 'file-replace-loader', options: { condition: 'always', replacement (resourcePath) { const mapping = { [resolve('./dist.browser/lib/logging.js')]: resolve( './browser/logging.js' ), [resolve('./dist.browser/lib/net/peer/libp2pnode.js')]: resolve( './browser/libp2pnode.js' ) } return mapping[resourcePath] }, async: true } } ] }, resolve: { extensions: ['.tsx', '.ts', '.js'] }, output: { filename: 'bundle.js', path: resolve(__dirname, 'dist'), library: 'ethereumjs' } } " Fix condition whether pushState exists or not,"var ContribBox = React.createClass({ render: function() { return <div />; } }); var SearchBox = React.createClass({ getInitialState: function () { console.log(this.props); return { user: this.props.user || '' }; }, handleSubmit: function() { }, submit: function(e) { var uri = '/' + this.state.user; e.preventDefault(); var ps = window.history.pushState ? 1 : 0; [function(){location.replace(uri)},function(){window.history.pushState(null,null,uri)}][ps](); this.handleSubmit(); }, updateUser: function(e) { this.setState({ user: e.target.value }); }, render: function() { return ( <form className=""ui"" onSubmit={this.submit}> <div className=""ui action center aligned input""> <input type=""text"" placeholder=""나무위키 아이디 입력"" defaultValue={this.props.user} onChange={this.updateUser} /> <button className=""ui teal button"">조회</button> </div> </form> ); } }); ","var ContribBox = React.createClass({ render: function() { return <div />; } }); var SearchBox = React.createClass({ getInitialState: function () { console.log(this.props); return { user: this.props.user || '' }; }, submit: function(e) { var uri = '/' + this.state.user; e.preventDefault(); var ps = window.history.pushState | 1 || 0; [function(){location.replace(uri)},function(){window.history.pushState(null,null,uri)}][ps](); }, updateUser: function(e) { this.setState({ user: e.target.value }); }, render: function() { return ( <form className=""ui"" onSubmit={this.submit}> <div className=""ui action center aligned input""> <input type=""text"" placeholder=""나무위키 아이디 입력"" defaultValue={this.props.user} onChange={this.updateUser} /> <button className=""ui teal button"">조회</button> </div> </form> ); } }); " Make the URL formatter friendlier.,"(function (doc) { ""use strict""; var REGEX_URL = /^(https?):\/\/(?:gist|raw\.)?github(?:usercontent)?\.com\/([^\/]+\/[^\/]+\/[^\/]+|[0-9A-Za-z-]+\/[0-9a-f]+\/raw)\/(.+)/i; var devEl = doc.getElementById('url-dev'), prodEl = doc.getElementById('url-prod'), urlEl = doc.getElementById('url'); urlEl.addEventListener('input', function () { var url = urlEl.value.trim(); if (REGEX_URL.test(url)) { urlEl.classList.remove('invalid'); urlEl.classList.add('valid'); devEl.value = encodeURI(url.replace(REGEX_URL, '$1://rawgit.com/$2/$3')); prodEl.value = encodeURI(url.replace(REGEX_URL, '$1://cdn.rawgit.com/$2/$3')); } else { urlEl.classList.remove('valid'); if (url.length) { urlEl.classList.add('invalid'); } else { urlEl.classList.remove('invalid'); } devEl.value = ''; prodEl.value = ''; } }, false); devEl.addEventListener('focus', onFocus); prodEl.addEventListener('focus', onFocus); function onFocus(e) { setTimeout(function () { e.target.select(); }, 1); } }(document)); ","(function (doc) { ""use strict""; var REGEX_URL = /^(https?):\/\/(?:gist|raw)\.github(?:usercontent)?\.com\/([^\/]+\/[^\/]+\/[^\/]+|[0-9A-Za-z-]+\/[0-9a-f]+\/raw)\//i; var devEl = doc.getElementById('url-dev'), prodEl = doc.getElementById('url-prod'), urlEl = doc.getElementById('url'); urlEl.addEventListener('input', function () { var url = urlEl.value.trim(); if (REGEX_URL.test(url)) { urlEl.classList.remove('invalid'); urlEl.classList.add('valid'); devEl.value = encodeURI(url.replace(REGEX_URL, '$1://rawgit.com/$2/')); prodEl.value = encodeURI(url.replace(REGEX_URL, '$1://cdn.rawgit.com/$2/')); } else { urlEl.classList.remove('valid'); if (url.length) { urlEl.classList.add('invalid'); } else { urlEl.classList.remove('invalid'); } devEl.value = ''; prodEl.value = ''; } }, false); devEl.addEventListener('focus', onFocus); prodEl.addEventListener('focus', onFocus); function onFocus(e) { setTimeout(function () { e.target.select(); }, 1); } }(document)); " "restapi: Use StringBuilder for String concatenation Change-Id: Iee94056b785ef76cffafd4b2d07ae001dfab7674 Signed-off-by: Ori Liel <4fcecd40a9c0dad06aec9ecf8a7829d6470e6321@redhat.com>","package org.ovirt.engine.api.restapi.utils; import org.ovirt.engine.core.compat.Guid; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class GuidUtils { private static final String MD5_SECURITY_ALGORITHM = ""MD5""; public static Guid asGuid(String id) { try { return new Guid(id); }catch (IllegalArgumentException e) { throw new MalformedIdException(e); } } /** * There are some business entities in the API, which are not regarded as business entities in the engine, and * therefore they don't have IDs. The API generates uniqute GUIDs for them, according to their attributes. This * method accepts one or more string attributes, concatenates them, and using Md5 hash to generate a unique Guid for * them. * * @param args * one or more strings, guid will be generated from them * @return unique Guid generated from the given strings. */ public static Guid generateGuidUsingMd5(String... args) { StringBuilder builder = new StringBuilder(); for (String arg : args) { builder.append(arg); } byte[] hash; try { hash = MessageDigest.getInstance(MD5_SECURITY_ALGORITHM).digest(builder.toString().getBytes()); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); // never happens, MD5 algorithm exists } return new Guid(hash, true); } } ","package org.ovirt.engine.api.restapi.utils; import org.ovirt.engine.core.compat.Guid; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class GuidUtils { private static final String MD5_SECURITY_ALGORITHM = ""MD5""; public static Guid asGuid(String id) { try { return new Guid(id); }catch (IllegalArgumentException e) { throw new MalformedIdException(e); } } /** * There are some business entities in the API, which are not regarded as business entities in the engine, and * therefore they don't have IDs. The API generates uniqute GUIDs for them, according to their attributes. This * method accepts one or more string attributes, concatenates them, and using Md5 hash to generate a unique Guid for * them. * * @param args * one or more strings, guid will be generated from them * @return unique Guid generated from the given strings. */ public static Guid generateGuidUsingMd5(String... args) { String id = """"; for (String arg : args) { id = id + arg; } byte[] hash; try { hash = MessageDigest.getInstance(MD5_SECURITY_ALGORITHM).digest(id.getBytes()); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); // never happens, MD5 algorithm exists } return new Guid(hash, true); } } " Add tinyurl.com as a minifier,"# -*- coding: utf-8 -*- # # This file is part of tofbot, a friendly IRC bot. # You may redistribute it under the Simplified BSD License. # If we meet some day, and you think this stuff is worth it, # you can buy us a beer in return. # # Copyright (c) 2012 Etienne Millon <etienne.millon@gmail.com> from BeautifulSoup import BeautifulSoup import requests import re from toflib import Plugin DOMAINS = [ ""t.co/"" , ""tinyurl.com/"" ] VIDEO_DOMAINS = [ ""youtube"" , ""youtu.be"" ] def is_mini(url): for d in DOMAINS: if d in url: return True return False def is_video(url): for d in VIDEO_DOMAINS: if d in url: return True return False def urlExpand(url): r = requests.get(url) return r.url def getTitle(url): r = requests.get(url) c = r.content s = BeautifulSoup(c) t = s.html.head.title.string return ''.join(t.split(""\n"")).strip() class PluginExpand(Plugin): def on_url(self, url): if is_mini(url): try: exp = urlExpand(url) self.say(exp) except: pass if is_video(url): try: t = getTitle(url) self.say(t) except: pass ","# -*- coding: utf-8 -*- # # This file is part of tofbot, a friendly IRC bot. # You may redistribute it under the Simplified BSD License. # If we meet some day, and you think this stuff is worth it, # you can buy us a beer in return. # # Copyright (c) 2012 Etienne Millon <etienne.millon@gmail.com> from BeautifulSoup import BeautifulSoup import requests import re from toflib import Plugin DOMAINS = [ ""t.co/"" ] VIDEO_DOMAINS = [ ""youtube"" , ""youtu.be"" ] def is_mini(url): for d in DOMAINS: if d in url: return True return False def is_video(url): for d in VIDEO_DOMAINS: if d in url: return True return False def urlExpand(url): r = requests.get(url) return r.url def getTitle(url): r = requests.get(url) c = r.content s = BeautifulSoup(c) t = s.html.head.title.string return ''.join(t.split(""\n"")).strip() class PluginExpand(Plugin): def on_url(self, url): if is_mini(url): try: exp = urlExpand(url) self.say(exp) except: pass if is_video(url): try: t = getTitle(url) self.say(t) except: pass " Use array_key_exists for choice existence tests,"<?php namespace Jsor\StringFormatter\FieldDescriptor; use Jsor\StringFormatter\FormatContext; final class ChoiceFieldDescriptor implements FieldDescriptorInterface { private $descriptor; private $choices; private $defaultValueTranslator; public function __construct( FieldDescriptorInterface $descriptor, $choices, $defaultValueTranslator = null ) { $this->descriptor = $descriptor; $this->choices = $choices; $this->defaultValueTranslator = $defaultValueTranslator; } public function getCharacter() { return $this->descriptor->getCharacter(); } public function getValue(FormatContext $context) { $value = $this->descriptor->getValue($context); $choices = $this->getChoices($value); if (array_key_exists($value, $choices)) { return $choices[$value]; } if (is_callable($this->defaultValueTranslator)) { return call_user_func($this->defaultValueTranslator, $value); } return $value; } public function getReplacement($value, FormatContext $context) { return $this->descriptor->getReplacement($value, $context); } private function getChoices($value) { $choices = $this->choices; if (is_callable($choices)) { $choices = call_user_func($choices, $value); } return $choices; } } ","<?php namespace Jsor\StringFormatter\FieldDescriptor; use Jsor\StringFormatter\FormatContext; final class ChoiceFieldDescriptor implements FieldDescriptorInterface { private $descriptor; private $choices; private $defaultValueTranslator; public function __construct( FieldDescriptorInterface $descriptor, $choices, $defaultValueTranslator = null ) { $this->descriptor = $descriptor; $this->choices = $choices; $this->defaultValueTranslator = $defaultValueTranslator; } public function getCharacter() { return $this->descriptor->getCharacter(); } public function getValue(FormatContext $context) { $value = $this->descriptor->getValue($context); $choices = $this->getChoices($value); if (isset($choices[$value])) { return $choices[$value]; } if (is_callable($this->defaultValueTranslator)) { return call_user_func($this->defaultValueTranslator, $value); } return $value; } public function getReplacement($value, FormatContext $context) { return $this->descriptor->getReplacement($value, $context); } private function getChoices($value) { $choices = $this->choices; if (is_callable($choices)) { $choices = call_user_func($choices, $value); } return $choices; } } " Fix bot infinte image loop,"from modules.module_base import ModuleBase from tools.nsfw import Nsfw class ModuleNSFW(ModuleBase): def __init__(self, bot): ModuleBase.__init__(self, bot) self.name = ""NSFW"" self.nsfw = Nsfw(self.logger) def notify_command(self, message_id, from_attr, date, chat, commandName, commandStr): if commandName == ""bonjour"": if commandStr == """": text = ""Bonjours : %s"" % "", "".join(self.nsfw.bonjours) self.bot.sendMessage(text, chat[""id""]) return parserResult = self.nsfw.parse(commandStr) for key in parserResult.unknown(): self.bot.sendMessage(""bonjour %s not found"" % key, chat[""id""]) for key in parserResult.known(): result = self.nsfw.image(key, parserResult.mode(), ""out.jpg"") if result.ok(): self.bot.sendPhoto(chat[""id""], ""out.jpg"", result.message()) break; else: self.bot.sendMessage(result.message(), chat[""id""]) def get_commands(self): return [ (""bonjour"", ""Bonjour. Keywords: <%s> <last/random>"" % ""/"".join(self.nsfw.bonjours)), ] ","from modules.module_base import ModuleBase from tools.nsfw import Nsfw class ModuleNSFW(ModuleBase): def __init__(self, bot): ModuleBase.__init__(self, bot) self.name = ""NSFW"" self.nsfw = Nsfw(self.logger) def notify_command(self, message_id, from_attr, date, chat, commandName, commandStr): if commandName == ""bonjour"": if commandStr == """": text = ""Bonjours : %s"" % "", "".join(self.nsfw.bonjours) self.bot.sendMessage(text, chat[""id""]) return parserResult = self.nsfw.parse(commandStr) for key in parserResult.unknown(): self.bot.sendMessage(""bonjour %s not found"" % key, chat[""id""]) for key in parserResult.known(): result = self.nsfw.image(key, parserResult.mode(), ""out.jpg"") if result.ok(): self.bot.sendPhoto(chat[""id""], ""out.jpg"", result.message()) else: self.bot.sendMessage(result.message(), chat[""id""]) def get_commands(self): return [ (""bonjour"", ""Bonjour. Keywords: <%s> <last/random>"" % ""/"".join(self.nsfw.bonjours)), ] " "Add dc terms subject keywords https://www.dublincore.org/specifications/dublin-core/dcmi-terms/#http://purl.org/dc/elements/1.1/subject","<?php declare(strict_types = 1); namespace Embed\Detectors; class Keywords extends Detector { public function detect(): array { $tags = []; $metas = $this->extractor->getMetas(); $ld = $this->extractor->getLinkedData(); $types = [ 'keywords', 'og:video:tag', 'og:article:tag', 'og:video:tag', 'og:book:tag', 'lp.article:section', 'dcterms.subject', ]; foreach ($types as $type) { $value = $metas->strAll($type); if ($value) { $tags = array_merge($tags, self::toArray($value)); } } $value = $ld->strAll('keywords'); if ($value) { $tags = array_merge($tags, self::toArray($value)); } $tags = array_map('mb_strtolower', $tags); $tags = array_unique($tags); $tags = array_filter($tags); $tags = array_values($tags); return $tags; } private static function toArray(array $keywords): array { $all = []; foreach ($keywords as $keyword) { $tags = explode(',', $keyword); $tags = array_map('trim', $tags); $tags = array_filter( $tags, fn ($value) => !empty($value) && substr($value, -3) !== '...' ); $all = array_merge($all, $tags); } return $all; } } ","<?php declare(strict_types = 1); namespace Embed\Detectors; class Keywords extends Detector { public function detect(): array { $tags = []; $metas = $this->extractor->getMetas(); $ld = $this->extractor->getLinkedData(); $types = [ 'keywords', 'og:video:tag', 'og:article:tag', 'og:video:tag', 'og:book:tag', 'lp.article:section', ]; foreach ($types as $type) { $value = $metas->strAll($type); if ($value) { $tags = array_merge($tags, self::toArray($value)); } } $value = $ld->strAll('keywords'); if ($value) { $tags = array_merge($tags, self::toArray($value)); } $tags = array_map('mb_strtolower', $tags); $tags = array_unique($tags); $tags = array_filter($tags); $tags = array_values($tags); return $tags; } private static function toArray(array $keywords): array { $all = []; foreach ($keywords as $keyword) { $tags = explode(',', $keyword); $tags = array_map('trim', $tags); $tags = array_filter( $tags, fn ($value) => !empty($value) && substr($value, -3) !== '...' ); $all = array_merge($all, $tags); } return $all; } } " Update vigenereDicitonaryHacker: added full path to dictionary file,"# Vigenère Cipher Dictionary Hacker # https://www.nostarch.com/crackingcodes/ (BSD Licensed) from books.CrackingCodesWithPython.pyperclip import copy from books.CrackingCodesWithPython.Chapter11.detectEnglish import isEnglish from books.CrackingCodesWithPython.Chapter18.vigenereCipher import decryptMessage DICTIONARY_FILE = ""/home/jose/PycharmProjects/python-tutorials/books/CrackingCodesWithPython/Chapter11/dictionary.txt"" def main(): ciphertext = """"""Tzx isnz eccjxkg nfq lol mys bbqq I lxcz."""""" hackedMessage = hackVigenereDictionary(ciphertext) if not hackedMessage: print('Copying hacked message to clipboard:') print(hackedMessage) copy(hackedMessage) else: print('Failed to hack encryption.') def hackVigenereDictionary(ciphertext): fo = open(DICTIONARY_FILE) words = fo.readlines() fo.close() for word in words: word = word.strip() # Remove the newline at the end. decryptedText = decryptMessage(word, ciphertext) if isEnglish(decryptedText, wordPercentage=40): # Check with user to see if the decrypted key has been found: print() print('Possible encryption break:') print('Key ' + str(word) + ': ' + decryptedText[:100]) print() print('Enter D for done, or just press Enter to continue breaking:') response = input('> ') if response.upper().startswith('D'): return decryptedText if __name__ == '__main__': main() ","# Vigenère Cipher Dictionary Hacker # https://www.nostarch.com/crackingcodes/ (BSD Licensed) from books.CrackingCodesWithPython.pyperclip import copy from books.CrackingCodesWithPython.Chapter11.detectEnglish import isEnglish from books.CrackingCodesWithPython.Chapter18.vigenereCipher import decryptMessage def main(): ciphertext = """"""Tzx isnz eccjxkg nfq lol mys bbqq I lxcz."""""" hackedMessage = hackVigenereDictionary(ciphertext) if not hackedMessage: print('Copying hacked message to clipboard:') print(hackedMessage) copy(hackedMessage) else: print('Failed to hack encryption.') def hackVigenereDictionary(ciphertext): fo = open('dictionary.txt') words = fo.readlines() fo.close() for word in words: word = word.strip() # Remove the newline at the end. decryptedText = decryptMessage(word, ciphertext) if isEnglish(decryptedText, wordPercentage=40): # Check with user to see if the decrypted key has been found: print() print('Possible encryption break:') print('Key ' + str(word) + ': ' + decryptedText[:100]) print() print('Enter D for done, or just press Enter to continue breaking:') response = input('> ') if response.upper().startswith('D'): return decryptedText if __name__ == '__main__': main() " Check for null before calling toString,"package lt.nsg.jdbcglass.resultset; import org.slf4j.Logger; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class ResultSetLogger { public void logResultSetRow(Logger log, ResultSet resultSet) throws SQLException { final List<ResultSetColumn> columns = getResultSetColumns(resultSet); final String message = createLogMessage(columns); log.info("" {}"", message); } private String createLogMessage(List<ResultSetColumn> columns) { if (columns.size() == 0) { return ""{}""; } StringBuilder sb = new StringBuilder(); sb.append(""{""); for (ResultSetColumn column : columns) { sb.append(column.getFormattedStringValue()).append("",""); } sb.replace(sb.length() - 1, sb.length(), ""}""); return sb.toString(); } private List<ResultSetColumn> getResultSetColumns(ResultSet resultSet) throws SQLException { final ResultSetMetaData md = resultSet.getMetaData(); final int columnCount = md.getColumnCount(); final ArrayList<ResultSetColumn> columns = new ArrayList<>(); for (int i = 1; i <= columnCount; i++) { final String column = safeToString(resultSet.getObject(i)); columns.add(new ResultSetColumn(column)); } return columns; } private static String safeToString(Object o) throws SQLException { if (o == null) { return ""null""; } return o.toString(); } } ","package lt.nsg.jdbcglass.resultset; import org.slf4j.Logger; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class ResultSetLogger { public void logResultSetRow(Logger log, ResultSet resultSet) throws SQLException { final List<ResultSetColumn> columns = getResultSetColumns(resultSet); final String message = createLogMessage(columns); log.info("" {}"", message); } private String createLogMessage(List<ResultSetColumn> columns) { if (columns.size() == 0) { return ""{}""; } StringBuilder sb = new StringBuilder(); sb.append(""{""); for (ResultSetColumn column : columns) { sb.append(column.getFormattedStringValue()).append("",""); } sb.replace(sb.length() - 1, sb.length(), ""}""); return sb.toString(); } private List<ResultSetColumn> getResultSetColumns(ResultSet resultSet) throws SQLException { final ResultSetMetaData md = resultSet.getMetaData(); final int columnCount = md.getColumnCount(); final ArrayList<ResultSetColumn> columns = new ArrayList<>(); for (int i = 1; i <= columnCount; i++) { final String column = resultSet.getObject(i).toString(); columns.add(new ResultSetColumn(column)); } return columns; } } " Add a hack to auto-inject new deps,"from urllib.parse import urljoin from urllib.request import urlopen from urllib.error import URLError import sys ENORMOUS_INJECTION_HACK = False GITHUB_USERS = [('Polymer', '0.5.2')] def resolve_missing_user(user, branch, package): assets = [""{}.html"".format(package), ""{}.css"".format(package), ""{}.js"".format(package)] base_url = ""https://raw.githubusercontent.com/{user}/{package}/{branch}/"".format(**locals()) matched_assets = [] for asset in assets: asset_url = urljoin(base_url, asset) try: with urlopen(asset_url): pass matched_assets.append(asset) except URLError: pass if matched_assets: print("" Matched."") data = {'base': base_url, 'assets': {a: a for a in matched_assets}} if ENORMOUS_INJECTION_HACK: target = open('webshack/standard_packages.yaml', 'a') else: target = sys.stdout print('---') print('{}:'.format(package), file=target) print(' base: {}'.format(base_url), file=target) print(' assets:', file=target) for asset in matched_assets: print(' {0}: {0}'.format(asset), file=target) if not ENORMOUS_INJECTION_HACK: print('---') return True return False def resolve_missing(package): print('Trying to resolve missing package from GitHub repositories...') for user, branch in GITHUB_USERS: print(' {}...'.format(user)) if resolve_missing_user(user, branch, package): return ","from urllib.parse import urljoin from urllib.request import urlopen from urllib.error import URLError import sys GITHUB_USERS = [('Polymer', '0.5.2')] def resolve_missing_user(user, branch, package): assets = [""{}.html"".format(package), ""{}.css"".format(package), ""{}.js"".format(package)] base_url = ""https://raw.githubusercontent.com/{user}/{package}/{branch}/"".format(**locals()) matched_assets = [] for asset in assets: asset_url = urljoin(base_url, asset) try: with urlopen(asset_url): pass matched_assets.append(asset) except URLError: pass if matched_assets: print("" Matched."") data = {'base': base_url, 'assets': {a: a for a in matched_assets}} print('---') print('{}:'.format(package)) print(' base: {}'.format(base_url)) print(' assets:') for asset in matched_assets: print(' {0}: {0}'.format(asset)) print('---') return True return False def resolve_missing(package): print('Trying to resolve missing package from GitHub repositories...') for user, branch in GITHUB_USERS: print(' {}...'.format(user)) if resolve_missing_user(user, branch, package): return " "Put ""init"" as the topmost item in the sort again","package org.badvision.outlaweditor.data; import java.util.List; import org.badvision.outlaweditor.Application; import org.badvision.outlaweditor.data.xml.Global; import org.badvision.outlaweditor.data.xml.NamedEntity; public class DataUtilities { public static void ensureGlobalExists() { if (Application.gameData.getGlobal() == null) { Application.gameData.setGlobal(new Global()); } } public static void sortNamedEntities(List<? extends NamedEntity> entities) { if (entities == null) { return; } entities.sort((a,b)->{ String nameA = a == null ? """" : nullSafe(a.getName()); String nameB = b == null ? """" : nullSafe(b.getName()); if (nameA.equalsIgnoreCase(""init"")) return -1; if (nameB.equalsIgnoreCase(""init"")) return 1; return nameA.compareTo(nameB); }); } public static String nullSafe(String str) { if (str == null) return """"; return str; } public static String uppercaseFirst(String str) { StringBuilder b = new StringBuilder(str); int i = 0; do { b.replace(i, i + 1, b.substring(i, i + 1).toUpperCase()); i = b.indexOf("" "", i) + 1; } while (i > 0 && i < b.length()); return b.toString(); } } ","package org.badvision.outlaweditor.data; import java.util.List; import org.badvision.outlaweditor.Application; import org.badvision.outlaweditor.data.xml.Global; import org.badvision.outlaweditor.data.xml.NamedEntity; public class DataUtilities { public static void ensureGlobalExists() { if (Application.gameData.getGlobal() == null) { Application.gameData.setGlobal(new Global()); } } public static void sortNamedEntities(List<? extends NamedEntity> entities) { if (entities == null) { return; } entities.sort((a,b)->{ String nameA = a == null ? """" : nullSafe(a.getName()); String nameB = b == null ? """" : nullSafe(b.getName()); return nameA.compareTo(nameB); }); } public static String nullSafe(String str) { if (str == null) return """"; return str; } public static String uppercaseFirst(String str) { StringBuilder b = new StringBuilder(str); int i = 0; do { b.replace(i, i + 1, b.substring(i, i + 1).toUpperCase()); i = b.indexOf("" "", i) + 1; } while (i > 0 && i < b.length()); return b.toString(); } } " Fix crash when adding new group names,"package com.example.android.groupschedulecoordinator; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.view.View; import android.widget.EditText; import android.widget.Toast; import java.util.ArrayList; public class ActivityCreateGroup extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_group); } public void createGroup(View v) { EditText text = (EditText) findViewById(R.id.tbGroupName); String groupName = text.getText().toString(); if(groupName.isEmpty()) { android.content.Context context = getApplicationContext(); CharSequence warning = ""Please enter a valid group name.""; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, warning, duration); toast.show(); } else { Intent intent = new Intent(ActivityCreateGroup.this, MainActivity.class); Bundle extras = getIntent().getExtras(); ArrayList<String> group_list = extras.getStringArrayList(""groupList""); if(group_list == null) { group_list = new ArrayList<>(); } group_list.add(groupName); //intent.putExtra(""groupName"", groupName); intent.putStringArrayListExtra(""groupList"", group_list); startActivity(intent); } } } ","package com.example.android.groupschedulecoordinator; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.view.View; import android.widget.EditText; import android.widget.Toast; import java.util.ArrayList; public class ActivityCreateGroup extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_group); } public void createGroup(View v) { EditText text = (EditText) findViewById(R.id.tbGroupName); String groupName = text.getText().toString(); if(groupName.isEmpty()) { android.content.Context context = getApplicationContext(); CharSequence warning = ""Please enter a valid group name.""; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, warning, duration); toast.show(); } else { Intent intent = new Intent(ActivityCreateGroup.this, MainActivity.class); Bundle extras = getIntent().getExtras(); ArrayList<String> group_list = extras.getStringArrayList(""groupList""); group_list.add(groupName); //intent.putExtra(""groupName"", groupName); intent.putStringArrayListExtra(""groupList"", group_list); startActivity(intent); } } } " "CRM-442: Add imap related fields to User view and edit pages - remove not needed id field","<?php namespace Oro\Bundle\ImapBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class ConfigurationType extends AbstractType { const NAME = 'oro_imap_configuration'; /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('host', 'text', array('required' => true)) ->add('port', 'text', array('required' => true)) ->add( 'ssl', 'choice', array( 'choices' => array('ssl', 'tsl'), 'empty_data' => null, 'empty_value' => '', 'required' => false ) ) ->add('user', 'text', array('required' => true)) ->add('password', 'password', array('required' => true)); } /** * {@inheritdoc} */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults( array( 'data_class' => 'Oro\\Bundle\\ImapBundle\\Entity\\ImapEmailOrigin' ) ); } /** * {@inheritdoc} */ public function getName() { return self::NAME; } } ","<?php namespace Oro\Bundle\ImapBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class ConfigurationType extends AbstractType { const NAME = 'oro_imap_configuration'; /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('id', 'hidden') ->add('host', 'text', array('required' => true)) ->add('port', 'text', array('required' => true)) ->add( 'ssl', 'choice', array( 'choices' => array('ssl', 'tsl'), 'empty_data' => null, 'empty_value' => '', 'required' => false ) ) ->add('user', 'text', array('required' => true)) ->add('password', 'password', array('required' => true)); } /** * {@inheritdoc} */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults( array( 'data_class' => 'Oro\\Bundle\\ImapBundle\\Entity\\ImapEmailOrigin' ) ); } /** * {@inheritdoc} */ public function getName() { return self::NAME; } } " Fix: Use Twig_Filter instead of Twig_Function in twig extension,"<?php namespace Demontpx\UserBundle\Twig; use Demontpx\UserBundle\Entity\User; use Demontpx\UserBundle\Service\Gravatar; /** * Class GravatarExtension * * @author Bert Hekman <demontpx@gmail.com> * @copyright 2017 Bert Hekman */ class GravatarExtension extends \Twig_Extension { /** @var Gravatar */ private $gravatar; public function __construct(Gravatar $gravatar) { $this->gravatar = $gravatar; } public function getFunctions() { return [ new \Twig_Function('gravatar', [$this->gravatar, 'getUrl'], ['is_safe' => ['html']]), new \Twig_Function('user_gravatar', [$this, 'getUserGravatarUrl'], ['is_safe' => ['html']]), ]; } public function getFilters() { return [ new \Twig_Filter('gravatar', [$this->gravatar, 'getUrl'], ['is_safe' => ['html']]), new \Twig_Filter('user_gravatar', [$this, 'getUserGravatarUrl'], ['is_safe' => ['html']]), ]; } public function getUserGravatarUrl(User $user, $size = null, $rating = null, $default = null, $forceDefault = null) { return $this->gravatar->getUrl($user->getEmail(), $size, $rating, $default, $forceDefault); } } ","<?php namespace Demontpx\UserBundle\Twig; use Demontpx\UserBundle\Entity\User; use Demontpx\UserBundle\Service\Gravatar; /** * Class GravatarExtension * * @author Bert Hekman <demontpx@gmail.com> * @copyright 2017 Bert Hekman */ class GravatarExtension extends \Twig_Extension { /** @var Gravatar */ private $gravatar; public function __construct(Gravatar $gravatar) { $this->gravatar = $gravatar; } public function getFunctions() { return [ new \Twig_Function('gravatar', [$this->gravatar, 'getUrl'], ['is_safe' => ['html']]), new \Twig_Function('user_gravatar', [$this, 'getUserGravatarUrl'], ['is_safe' => ['html']]), ]; } public function getFilters() { return [ new \Twig_Function('gravatar', [$this->gravatar, 'getUrl'], ['is_safe' => ['html']]), new \Twig_Function('user_gravatar', [$this, 'getUserGravatarUrl'], ['is_safe' => ['html']]), ]; } public function getUserGravatarUrl(User $user, $size = null, $rating = null, $default = null, $forceDefault = null) { return $this->gravatar->getUrl($user->getEmail(), $size, $rating, $default, $forceDefault); } } " "Fix public_key default value in lexik_paybox.parameters parameter The parameter lexik_paybox.public_key seems to never been used in services, default value is now defined before parameter registration for parameter lexik_paybox.parameters","<?php namespace Lexik\Bundle\PayboxBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class LexikPayboxExtension extends Extension { /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); if (null === $config['parameters']['public_key']) { $config['parameters']['public_key'] = __DIR__ . '/../Resources/config/paybox_public_key.pem'; } $container->setParameter('lexik_paybox.servers', $config['servers']); $container->setParameter('lexik_paybox.parameters', $config['parameters']); $container->setParameter('lexik_paybox.transport.class', $config['transport']); $container->setParameter('lexik_paybox.public_key', $config['parameters']['public_key']); } } ","<?php namespace Lexik\Bundle\PayboxBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class LexikPayboxExtension extends Extension { /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); $container->setParameter('lexik_paybox.servers', $config['servers']); $container->setParameter('lexik_paybox.parameters', $config['parameters']); $container->setParameter('lexik_paybox.transport.class', $config['transport']); if (null === $config['parameters']['public_key']) { $config['parameters']['public_key'] = __DIR__ . '/../Resources/config/paybox_public_key.pem'; } $container->setParameter('lexik_paybox.public_key', $config['parameters']['public_key']); } } " Increment slide number for slide titles when adding new ones,"define([ ""backbone"", ""underscore"", ""jquery"", ""text!/src/html/templates/presentation.html"" ], function (Backbone, _, $, presentationTemplate) { var slideCounter = 1; return Backbone.View.extend({ id: ""presentation"", tagName: ""section"", template: _.template(presentationTemplate), events: { ""click #addslide"": ""addSlide"", ""click #editslide"": ""editSlide"", ""click #removeslide"": ""removeSlide"" }, render: function () { this.$el.html(this.template({ slides: this.collection.toJSON() })); return this; }, addSlide: function () { this.collection.create({ title: ""Slide "" + slideCounter }); slideCounter++; this.render(); }, editSlide: function (event) { window.location.href = ""#editslide/"" + $(event.currentTarget).parent().attr(""id""); }, removeSlide: function (event) { var view = this; var slideId = $(event.currentTarget).parent().attr(""id""); var slide = this.collection.find(function (model) { return model.get(""id"") === slideId; }); slide.destroy({ success: function () { view.collection.remove(slideId); view.render(); } }); } }); });","define([ ""backbone"", ""underscore"", ""jquery"", ""text!/src/html/templates/presentation.html"" ], function (Backbone, _, $, presentationTemplate) { return Backbone.View.extend({ id: ""presentation"", tagName: ""section"", template: _.template(presentationTemplate), events: { ""click #addslide"": ""addSlide"", ""click #editslide"": ""editSlide"", ""click #removeslide"": ""removeSlide"" }, render: function () { this.$el.html(this.template({ slides: this.collection.toJSON() })); return this; }, addSlide: function () { this.collection.create({}); this.render(); }, editSlide: function (event) { window.location.href = ""#editslide/"" + $(event.currentTarget).parent().attr(""id""); }, removeSlide: function (event) { var view = this; var slideId = $(event.currentTarget).parent().attr(""id""); var slide = this.collection.find(function (model) { return model.get(""id"") === slideId; }); slide.destroy({ success: function () { view.collection.remove(slideId); view.render(); } }); } }); });" Use 'spec' reporter for Mocha tests results,"module.exports = function(grunt) { 'use strict'; grunt.loadNpmTasks('grunt-coffeelint'); grunt.loadNpmTasks('grunt-contrib-coffee'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-simple-mocha'); grunt.initConfig({ coffee: { test: { expand: true, cwd: 'test', src: ['*.coffee'], dest: 'test', ext: '.compiled.js' } }, coffeelint: { options: { 'no_trailing_whitespace': { 'level': 'error' } }, test: ['test/test*.coffee'] }, jshint: { options: { jshintrc: '.jshintrc' }, gruntfile: 'Gruntfile.js', src: ['src/*.js'] }, simplemocha: { options: { ignoreLeaks: false, ui: 'bdd', reporter: 'spec' }, test: { src: 'test/test*.js' } } }); grunt.registerTask('check_codestyle', ['jshint', 'coffeelint']); grunt.registerTask('run_tests', ['coffee', 'simplemocha']); grunt.registerTask('test', ['check_codestyle', 'run_tests']); grunt.registerTask('default', 'test'); }; ","module.exports = function(grunt) { 'use strict'; grunt.loadNpmTasks('grunt-coffeelint'); grunt.loadNpmTasks('grunt-contrib-coffee'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-simple-mocha'); grunt.initConfig({ coffee: { test: { expand: true, cwd: 'test', src: ['*.coffee'], dest: 'test', ext: '.compiled.js' } }, coffeelint: { options: { 'no_trailing_whitespace': { 'level': 'error' } }, test: ['test/test*.coffee'] }, jshint: { options: { jshintrc: '.jshintrc' }, gruntfile: 'Gruntfile.js', src: ['src/*.js'] }, simplemocha: { options: { ignoreLeaks: false, ui: 'bdd', reporter: 'dot' }, test: { src: 'test/test*.js' } } }); grunt.registerTask('check_codestyle', ['jshint', 'coffeelint']); grunt.registerTask('run_tests', ['coffee', 'simplemocha']); grunt.registerTask('test', ['check_codestyle', 'run_tests']); grunt.registerTask('default', 'test'); }; " Use full-size image instead of the default one.,"var hoverZoomPlugins = hoverZoomPlugins || []; hoverZoomPlugins.push({ name:'Instagram', prepareImgLinks:function (callback) { $('body').on('mouseenter', 'a[href*=""?taken-by""]', function () { var link = $(this); if (link.hasClass('hoverZoomLink')) return; if (link.find('span.coreSpriteSidecarIconLarge').length === 0) { link.data().hoverZoomSrc = [link.prop('href').replace(/[?]taken-by=.*$/, 'media?size=l')]; link.addClass('hoverZoomLink'); hoverZoom.displayPicFromElement(link); } else { hoverZoom.prepareFromDocument(link, link.attr('href'), function(doc) { var img = []; doc.querySelectorAll('script').forEach(script => { var body = script.innerHTML; if (!body.startsWith('window._sharedData')) return; var json = JSON.parse(body.slice(20, -1)); var edges = json.entry_data.PostPage[""0""].graphql.shortcode_media.edge_sidecar_to_children.edges; edges.forEach(edge => img.push([edge.node.display_url])); }); return img.length > 0 ? img : false; }); } }); } }); ","var hoverZoomPlugins = hoverZoomPlugins || []; hoverZoomPlugins.push({ name:'Instagram', prepareImgLinks:function (callback) { $('body').on('mouseenter', 'a[href*=""?taken-by""]', function () { var link = $(this); if (link.hasClass('hoverZoomLink')) return; if (link.find('span.coreSpriteSidecarIconLarge').length === 0) { link.data().hoverZoomSrc = [link.find('img').attr('src')]; link.addClass('hoverZoomLink'); hoverZoom.displayPicFromElement(link); } else { hoverZoom.prepareFromDocument(link, link.attr('href'), function(doc) { var img = []; doc.querySelectorAll('script').forEach(script => { var body = script.innerHTML; if (!body.startsWith('window._sharedData')) return; var json = JSON.parse(body.slice(20, -1)); var edges = json.entry_data.PostPage[""0""].graphql.shortcode_media.edge_sidecar_to_children.edges; edges.forEach(edge => img.push([edge.node.display_url])); }); return img.length > 0 ? img : false; }); } }); } }); " Fix keys error and remove `set`,"'use strict'; var Cesium = require('cesium'); var fsExtra = require('fs-extra'); var nconf = require('nconf'); var Promise = require('bluebird'); var defined = Cesium.defined; nconf.env('__') .file({ file: 'config.json' }) .defaults({ port: 5000, listenPath: '/' }) .required([ 'secret', 'repositories' ]); var Settings = {}; Settings.loadRepositoriesSettings = function() { return fsExtra.readJson('config.json') .then(function(configJson) { if (!configJson.hasOwnProperty('repositories')) { return Promise.reject('config.json needs a `repositories` field'); } configJson.repositories.keys.forEach(function(name) { if (!defined(name.gitHubToken)) { return Promise.reject('Repository ' + name + ' must have a `gitHubToken`'); } Settings._repositories.push(name); }); }); }; Settings.get = function(repositoryName, key) { return nconf.get(['repositories', repositoryName, key].join(':')); }; Object.defineProperties(Settings, { port: { get: function() { return parseInt(nconf.get('port')); } }, listenPath: { get: function() { return nconf.get('listenPath'); } }, repositories: { get: function() { return Settings._repositories; } } }); module.exports = Settings; ","'use strict'; var Cesium = require('cesium'); var fsExtra = require('fs-extra'); var nconf = require('nconf'); var Promise = require('bluebird'); var defined = Cesium.defined; nconf.env('__') .file({ file: 'config.json' }) .defaults({ port: 5000, listenPath: '/' }) .required([ 'secret', 'repositories' ]); var Settings = {}; Settings.loadRepositoriesSettings = function() { return fsExtra.readJson('config.json') .then(function(configJson) { configJson.keys.forEach(function(name) { if (!defined(name.gitHubToken)) { return Promise.reject('Repository ' + name + ' must have a `gitHubToken`'); } Settings._repositories.push(name); }); }); }; Settings.set = function(repositoryName, key, value) { nconf.set(['repositories', repositoryName, key].join(':'), value); }; Settings.get = function(repositoryName, key) { return nconf.get(['repositories', repositoryName, key].join(':')); }; Object.defineProperties(Settings, { port: { get: function() { return parseInt(nconf.get('port')); } }, listenPath: { get: function() { return nconf.get('listenPath'); } }, repositories: { get: function() { return Settings._repositories; } } }); module.exports = Settings; " Use correct dict for the type sizes," from .base import SimSootExpr from archinfo import ArchSoot import logging l = logging.getLogger(""angr.engines.soot.expressions.cast"") class SimSootExpr_Cast(SimSootExpr): def __init__(self, expr, state): super(SimSootExpr_Cast, self).__init__(expr, state) def _execute(self): if self.expr.cast_type in ['double', 'float']: l.error('Casting of double and float types not supported.') return # get value local = self._translate_value(self.expr.value) value_uncasted = self.state.memory.load(local) # lookup the type size and extract value value_size = ArchSoot.sizeof[self.expr.cast_type] value_extracted = value_uncasted.reversed.get_bytes(index=0, size=value_size/8).reversed # determine size of Soot bitvector and resize bitvector # Note: smaller types than int's are stored in a 32-bit BV value_soot_size = value_size if value_size >= 32 else 32 if self.expr.cast_type in ['char', 'boolean']: # unsigned extend value_casted = value_extracted.zero_extend(value_soot_size-value_size) else: # signed extend value_casted = value_extracted.sign_extend(value_soot_size-value_size) self.expr = value_casted "," from .base import SimSootExpr from archinfo import ArchSoot import logging l = logging.getLogger(""angr.engines.soot.expressions.cast"") class SimSootExpr_Cast(SimSootExpr): def __init__(self, expr, state): super(SimSootExpr_Cast, self).__init__(expr, state) def _execute(self): if self.expr.cast_type in ['double', 'float']: l.error('Casting of double and float types not supported.') return # get value local = self._translate_value(self.expr.value) value_uncasted = self.state.memory.load(local) # lookup the type size and extract value value_size = ArchSoot.primitive_types[self.expr.cast_type] value_extracted = value_uncasted.reversed.get_bytes(index=0, size=value_size/8).reversed # determine size of Soot bitvector and resize bitvector # Note: smaller types than int's are stored in a 32-bit BV value_soot_size = value_size if value_size >= 32 else 32 if self.expr.cast_type in ['char', 'boolean']: # unsigned extend value_casted = value_extracted.zero_extend(value_soot_size-value_size) else: # signed extend value_casted = value_extracted.sign_extend(value_soot_size-value_size) self.expr = value_casted " Fix replacement c3 by billboard,"jQuery(function ($) { let url = ""daily_reports_chart.json""; let certname = $(""#dailyReportsChart"").data(""certname""); let days = parseInt($(""#dailyReportsChart"").data(""days"")); let defaultJSON = [] for (let index = days-1; index >= 0; index--) { defaultJSON.push({ day: moment().startOf('day').subtract(index, 'days').format('YYYY-MM-DD'), unchanged: 0, changed: 0, failed: 0 }) } let chart = bb.generate({ bindto: ""#dailyReportsChart"", data: { type: ""bar"", json: defaultJSON, keys: { x: ""day"", value: [""failed"", ""changed"", ""unchanged""], }, groups: [[""failed"", ""changed"", ""unchanged""]], colors: { // Must match CSS colors failed: ""#AA4643"", changed: ""#4572A7"", unchanged: ""#89A54E"", }, }, size: { height: 160, }, axis: { x: { type: ""category"", }, }, }); if (typeof certname !== typeof undefined && certname !== false) { // truncate /node/certname from URL, to determine path to json url = window.location.href.replace(/\/node\/[^/]+$/, """") + ""/daily_reports_chart.json?certname="" + certname } $.getJSON(url, function(data) { chart.load({json: data.result}) }); }) ","jQuery(function ($) { function generateChart(el) { var url = ""daily_reports_chart.json""; var certname = $(el).attr('data-certname'); if (typeof certname !== typeof undefined && certname !== false) { // truncate /node/certname from URL, to determine path to json url = window.location.href.replace(/\/node\/[^/]+$/,'') + ""/daily_reports_chart.json?certname="" + certname; } d3.json(url, function(data) { var chart = c3.generate({ bindto: '#dailyReportsChart', data: { type: 'bar', json: data['result'], keys: { x: 'day', value: ['failed', 'changed', 'unchanged'], }, groups: [ ['failed', 'changed', 'unchanged'] ], colors: { // Must match CSS colors 'failed':'#AA4643', 'changed':'#4572A7', 'unchanged':'#89A54E', } }, size: { height: 160 }, axis: { x: { type: 'category' } } }); }); } generateChart($(""#dailyReportsChart"")); }); " "Remove unused test code in test_util.py This doesn't seem to do anything Change-Id: Ieba6b5f7229680146f9b3f2ae2f3f2d2b1354376","# Copyright 2013 OpenStack LLC. # All Rights Reserved. # # 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 cStringIO import sys import unittest2 from ceilometerclient.common import utils class UtilsTest(unittest2.TestCase): def test_prettytable(self): class Struct: def __init__(self, **entries): self.__dict__.update(entries) # test that the prettytable output is wellformatted (left-aligned) saved_stdout = sys.stdout try: sys.stdout = output_dict = cStringIO.StringIO() utils.print_dict({'K': 'k', 'Key': 'Value'}) finally: sys.stdout = saved_stdout self.assertEqual(output_dict.getvalue(), '''\ +----------+-------+ | Property | Value | +----------+-------+ | K | k | | Key | Value | +----------+-------+ ''') ","# Copyright 2013 OpenStack LLC. # All Rights Reserved. # # 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 cStringIO import sys import unittest2 from ceilometerclient.common import utils class UtilsTest(unittest2.TestCase): def test_prettytable(self): class Struct: def __init__(self, **entries): self.__dict__.update(entries) # test that the prettytable output is wellformatted (left-aligned) columns = ['ID', 'Name'] val = ['Name1', 'another', 'veeeery long'] images = [Struct(**{'id': i ** 16, 'name': val[i]}) for i in range(len(val))] saved_stdout = sys.stdout try: sys.stdout = output_dict = cStringIO.StringIO() utils.print_dict({'K': 'k', 'Key': 'Value'}) finally: sys.stdout = saved_stdout self.assertEqual(output_dict.getvalue(), '''\ +----------+-------+ | Property | Value | +----------+-------+ | K | k | | Key | Value | +----------+-------+ ''') " Add nicer style for editor,"'use strict'; angular .module('flashcardModule.directives') .directive('markdownEditor', function() { var converter = new Showdown.converter(); var previewTemplate = '<div ng-hide=""isEditMode"" ng-dblclick=""toEditMode()"" class=""preview""></div>'; var editorTemplate = '<textarea ng-show=""isEditMode"" class=""editor input-block-level""></textarea>'; return { restrict: 'E', scope: { text: '=text' }, compile: function(tElement, tAttrs, transclude) { tElement.html(editorTemplate); tElement.append(previewTemplate); return function(scope, iElement, iAttrs, controller) { scope.isEditMode = false; if (scope.text) { var htmlText = converter.makeHtml(scope.text); iElement.find('div').html(htmlText); } scope.toEditMode = function() { iElement.find('textarea').html(scope.text); scope.isEditMode = true; } } } }; });","'use strict'; angular .module('flashcardModule.directives') .directive('markdownEditor', function() { var converter = new Showdown.converter(); var previewTemplate = '<div ng-hide=""isEditMode"" ng-dblclick=""toEditMode()"" class=""preview""></div>'; var editorTemplate = '<textarea ng-show=""isEditMode"" class=""editor""></textarea>'; return { restrict: 'E', scope: { text: '=text' }, compile: function(tElement, tAttrs, transclude) { tElement.html(editorTemplate); tElement.append(previewTemplate); return function(scope, iElement, iAttrs, controller) { scope.isEditMode = false; if (scope.text) { var htmlText = converter.makeHtml(scope.text); iElement.find('div').html(htmlText); } scope.toEditMode = function() { iElement.find('textarea').html(scope.text); scope.isEditMode = true; } } } }; });" "Fix DeprecationWarnings for serializer context * Pass a context containing a request to every serializer Conflicts: pages/tests/test_serializers.py","from rest_framework.reverse import reverse from user_management.models.tests.utils import APIRequestTestCase from .. import serializers from . import factories from pages.utils import build_url class PageSerializerTest(APIRequestTestCase): def setUp(self): self.request = self.create_request() self.context = {'request': self.request} def expected_data(self, page): expected = { 'id': page.pk, 'url': page.get_absolute_url(self.request), 'name': page.name, 'slug': page.slug, 'regions': page.rendered_regions(), } return expected def test_serialize(self): page = factories.PageFactory.create() serializer = serializers.PageSerializer(page, context=self.context) self.assertEqual(serializer.data, self.expected_data(page)) class GroupTest(APIRequestTestCase): def setUp(self): self.request = self.create_request() self.context = {'request': self.request} def expected_data(self, group): slug = group.slug return { 'url': group.get_absolute_url(self.request), 'slug': slug, 'links': { 'pages': build_url( reverse('pages:page-list', request=self.request), {'group': slug}, ), }, } def test_serialize(self): group = factories.GroupFactory.create() serializer = serializers.GroupSerializer(group, context=self.context) self.assertEqual(serializer.data, self.expected_data(group)) ","from mock import patch from django.test import TestCase from rest_framework.reverse import reverse from .. import serializers from . import factories from pages.utils import build_url class PageSerializerTest(TestCase): def expected_data(self, page): expected = { 'id': page.pk, 'url': page.get_absolute_url(), 'name': page.name, 'slug': page.slug, 'regions': page.rendered_regions(), } return expected def test_serialize(self): page = factories.PageFactory.create() serializer = serializers.PageSerializer(page) self.assertEqual(serializer.data, self.expected_data(page)) class GroupTest(TestCase): url_path = 'pages.models.Group.get_absolute_url' mocked_url = '/mocked_url' def expected_data(self, group): slug = group.slug return { 'url': self.mocked_url, 'slug': slug, 'links': { 'pages': build_url(reverse('pages:page-list'), {'group': slug}), }, } @patch(url_path) def test_serialize(self, group_url): group_url.return_value = self.mocked_url group = factories.GroupFactory.create() serializer = serializers.GroupSerializer(group) self.assertEqual(serializer.data, self.expected_data(group)) " Use the init command to setup functionnal tests,"<?php namespace Liip\RMT\Tests\Functional; class RMTFunctionalTestBase extends \PHPUnit_Framework_TestCase { protected $tempDir; protected function setUp() { // Create a temp folder $this->tempDir = tempnam(sys_get_temp_dir(),''); if (file_exists($this->tempDir)) { unlink($this->tempDir); } mkdir($this->tempDir); chdir($this->tempDir); // Create the executable task inside $rmtDir = realpath(__DIR__.'/../../../../../'); exec(""php $rmtDir/command.php init --generator=basic-increment --persister=vcs-tag --vcs=git""); } protected function createJsonConfig($generator, $persister, $otherConfig=array()) { $allConfig = array_merge($otherConfig, array( 'version-persister'=>$persister, 'version-generator'=>$generator )); file_put_contents('rmt.json', json_encode($allConfig)); } protected function tearDown() { exec('rm -rf '.$this->tempDir); } protected function initGit() { exec('git init'); exec('git add *'); exec('git commit -m ""First commit""'); } protected function manualDebug() { echo ""\n\nMANUAL DEBUG Go to:\n > cd "".$this->tempDir.""\n\n""; exit(); } } ","<?php namespace Liip\RMT\Tests\Functional; class RMTFunctionalTestBase extends \PHPUnit_Framework_TestCase { protected $tempDir; protected function setUp() { // Create a temp folder $this->tempDir = tempnam(sys_get_temp_dir(),''); if (file_exists($this->tempDir)) { unlink($this->tempDir); } mkdir($this->tempDir); chdir($this->tempDir); // Create the executable task inside $rmtDir = realpath(__DIR__.'/../../../../../'); file_put_contents('RMT', <<<EOF #!/usr/bin/env php <?php define('RMT_ROOT_DIR', __DIR__); ?> <?php require '$rmtDir/command.php'; ?> EOF ); exec('chmod +x RMT'); } protected function createJsonConfig($generator, $persister, $otherConfig=array()) { $allConfig = array_merge($otherConfig, array( 'version-persister'=>$persister, 'version-generator'=>$generator )); file_put_contents('rmt.json', json_encode($allConfig)); } protected function tearDown() { exec('rm -rf '.$this->tempDir); } protected function initGit() { exec('git init'); exec('git add *'); exec('git commit -m ""First commit""'); } protected function manualDebug() { echo ""\n\nMANUAL DEBUG Go to:\n > cd "".$this->tempDir.""\n\n""; exit(); } } " Use a different way to trigger the BC layer,"<?php declare(strict_types=1); namespace Paraunit\Process; use Paraunit\Configuration\EnvVariables; use Paraunit\Configuration\PHPUnitConfig; use Paraunit\Configuration\TempFilenameFactory; use Symfony\Component\Console\Helper\ProcessHelper; use Symfony\Component\Process\Process; use Symfony\Component\Process\ProcessUtils; class ProcessFactory implements ProcessFactoryInterface { /** @var CommandLine */ private $cliCommand; /** @var string[] */ private $baseCommandLine; /** @var string[] */ private $environmentVariables; public function __construct( CommandLine $cliCommand, PHPUnitConfig $phpunitConfig, TempFilenameFactory $tempFilenameFactory ) { $this->cliCommand = $cliCommand; $this->baseCommandLine = array_merge($this->cliCommand->getExecutable(), $this->cliCommand->getOptions($phpunitConfig)); $this->environmentVariables = [ EnvVariables::LOG_DIR => $tempFilenameFactory->getPathForLog(), ]; } public function create(string $testFilePath): AbstractParaunitProcess { $process = new Process( array_merge($this->baseCommandLine, [$testFilePath], $this->cliCommand->getSpecificOptions($testFilePath)), null, $this->environmentVariables ); if (method_exists(ProcessUtils::class, 'escapeArgument')) { // Symfony 3.4 BC layer $process->inheritEnvironmentVariables(); } return new SymfonyProcessWrapper($process, $testFilePath); } } ","<?php declare(strict_types=1); namespace Paraunit\Process; use Paraunit\Configuration\EnvVariables; use Paraunit\Configuration\PHPUnitConfig; use Paraunit\Configuration\TempFilenameFactory; use Symfony\Component\Process\Process; class ProcessFactory implements ProcessFactoryInterface { /** @var CommandLine */ private $cliCommand; /** @var string[] */ private $baseCommandLine; /** @var string[] */ private $environmentVariables; public function __construct( CommandLine $cliCommand, PHPUnitConfig $phpunitConfig, TempFilenameFactory $tempFilenameFactory ) { $this->cliCommand = $cliCommand; $this->baseCommandLine = array_merge($this->cliCommand->getExecutable(), $this->cliCommand->getOptions($phpunitConfig)); $this->environmentVariables = [ EnvVariables::LOG_DIR => $tempFilenameFactory->getPathForLog(), ]; } public function create(string $testFilePath): AbstractParaunitProcess { $process = new Process( array_merge($this->baseCommandLine, [$testFilePath], $this->cliCommand->getSpecificOptions($testFilePath)), null, $this->environmentVariables ); if (class_exists(\Symfony\Component\Process\ProcessBuilder::class)) { // Symfony 3.4 BC layer $process->inheritEnvironmentVariables(); } return new SymfonyProcessWrapper($process, $testFilePath); } } " "Add ability to convert to/from an array This is needed as an easy way to serialize an interpolator for sending/receiving over HTTP","class Interpolator: def __init__(self): self.data = [] def addIndexValue(self, index, value): self.data.append((index, value)) def valueAtIndex(self, target_index): if target_index < self.data[0][0]: return None elif self.data[-1][0] < target_index: return None else: start = None end = None for (index, value) in self.data: if index == target_index: return value else: if index <= target_index: start = (index, value) elif target_index < index: end = (index, value) break index_delta = end[0] - start[0] percent = (target_index - start[0]) / index_delta value_delta = end[1] - start[1] return start[1] + value_delta * percent def to_array(self): result = [] for (index, value) in self.data: result.append(index) result.append(value) return result def from_array(self, array): self.data = [] for i in range(0, len(array), 2): self.addIndexValue(array[i], array[i + 1]) if __name__ == ""__main__"": pass ","class Interpolator: def __init__(self): self.data = [] def addIndexValue(self, index, value): self.data.append((index, value)) def valueAtIndex(self, target_index): if target_index < self.data[0][0]: return None elif self.data[-1][0] < target_index: return None else: start = None end = None for (index, value) in self.data: if index == target_index: return value else: if index <= target_index: start = (index, value) elif target_index < index: end = (index, value) break index_delta = end[0] - start[0] percent = (target_index - start[0]) / index_delta value_delta = end[1] - start[1] return start[1] + value_delta * percent if __name__ == ""__main__"": pass " Add method to get instance.,"<?php namespace Taskforcedev\CrudApi\Helpers; /** * Class Model * * @package Taskforcedev\CrudApi\Helpers */ class Model { public $crudApi; /** * Model constructor. * * @param CrudApi $crudApi */ public function __construct(CrudApi $crudApi) { $this->crudApi = $crudApi; } /** * Get a model from the currently set namespace and model. * * If the model does not exist from the base namespace it will also * look in the namespace\Models as a secondary convention. * * @return false|string */ public function getModel() { if ($this->crudApi->model === null) { return false; } // If namespace is not detected or set then set to the laravel default of App. if ($this->crudApi->namespace === null) { $this->crudApi->setNamespace('App'); } $fqModel = $this->crudApi->namespace . $this->crudApi->model; if (!class_exists($fqModel)) { $fqModel = $this->namespace . 'Models\\'.$this->model; if (!class_exists($fqModel)) { return false; } } return $fqModel; } public function instance() { if ($this->crudApi->instance === null) { $fq = $this->getModel(); $instance = new $fq; $this->crudApi->setInstance($instance); } return $this->crudApi->instance; } }","<?php namespace Taskforcedev\CrudApi\Helpers; /** * Class Model * * @package Taskforcedev\CrudApi\Helpers */ class Model { public $crudApi; /** * Model constructor. * * @param CrudApi $crudApi */ public function __construct(CrudApi $crudApi) { $this->crudApi = $crudApi; } /** * Get a model from the currently set namespace and model. * * If the model does not exist from the base namespace it will also * look in the namespace\Models as a secondary convention. * * @return false|string */ public function getModel() { if ($this->crudApi->model === null) { return false; } // If namespace is not detected or set then set to the laravel default of App. if ($this->crudApi->namespace === null) { $this->crudApi->setNamespace('App'); } $fqModel = $this->crudApi->namespace . $this->crudApi->model; if (!class_exists($fqModel)) { $fqModel = $this->namespace . 'Models\\'.$this->model; if (!class_exists($fqModel)) { return false; } } return $fqModel; } }" "Fix a bad call when prefilling ApplicationSearch from `?projects=some_slug` Summary: Fixes T10299. Test Plan: - Visited `/maniphest/?projects=x` locally, where `x` is some valid project slug. - Before patch: Fatal on `requireViewer()` call. - After patch: Works correctly, filling the correct project into parameters. Reviewers: chad Reviewed By: chad Maniphest Tasks: T10299 Differential Revision: https://secure.phabricator.com/D15214","<?php final class PhabricatorProjectSearchField extends PhabricatorSearchTokenizerField { protected function getDefaultValue() { return array(); } protected function newDatasource() { return new PhabricatorProjectLogicalDatasource(); } protected function getValueFromRequest(AphrontRequest $request, $key) { $list = $this->getListFromRequest($request, $key); $phids = array(); $slugs = array(); $project_type = PhabricatorProjectProjectPHIDType::TYPECONST; foreach ($list as $item) { $type = phid_get_type($item); if ($type == $project_type) { $phids[] = $item; } else { if (PhabricatorTypeaheadDatasource::isFunctionToken($item)) { // If this is a function, pass it through unchanged; we'll evaluate // it later. $phids[] = $item; } else { $slugs[] = $item; } } } if ($slugs) { $projects = id(new PhabricatorProjectQuery()) ->setViewer($this->getViewer()) ->withSlugs($slugs) ->execute(); foreach ($projects as $project) { $phids[] = $project->getPHID(); } $phids = array_unique($phids); } return $phids; } protected function newConduitParameterType() { return new ConduitProjectListParameterType(); } } ","<?php final class PhabricatorProjectSearchField extends PhabricatorSearchTokenizerField { protected function getDefaultValue() { return array(); } protected function newDatasource() { return new PhabricatorProjectLogicalDatasource(); } protected function getValueFromRequest(AphrontRequest $request, $key) { $list = $this->getListFromRequest($request, $key); $phids = array(); $slugs = array(); $project_type = PhabricatorProjectProjectPHIDType::TYPECONST; foreach ($list as $item) { $type = phid_get_type($item); if ($type == $project_type) { $phids[] = $item; } else { if (PhabricatorTypeaheadDatasource::isFunctionToken($item)) { // If this is a function, pass it through unchanged; we'll evaluate // it later. $phids[] = $item; } else { $slugs[] = $item; } } } if ($slugs) { $projects = id(new PhabricatorProjectQuery()) ->setViewer($this->requireViewer()) ->withSlugs($slugs) ->execute(); foreach ($projects as $project) { $phids[] = $project->getPHID(); } $phids = array_unique($phids); } return $phids; } protected function newConduitParameterType() { return new ConduitProjectListParameterType(); } } " Fix CC field on acknowledgement email,"<?php declare(strict_types=1); namespace App\Mail; use App\Models\DocuSignEnvelope; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Symfony\Component\Mime\Email; class MembershipAgreementDocuSignEnvelopeReceived extends Mailable implements ShouldQueue { use Queueable; use SerializesModels; public DocuSignEnvelope $envelope; /** * Create a new message instance. */ public function __construct(DocuSignEnvelope $envelope) { $this->envelope = $envelope; } /** * Build the message. */ public function build(): self { return $this->from('noreply@my.robojackets.org', 'RoboJackets') ->to($this->envelope->signedBy->gt_email, $this->envelope->signedBy->name) ->cc('Membership Agreement Archives', config('services.membership_agreement_archive_email')) ->subject('Membership agreement signed') ->text('mail.agreement.docusignenvelopereceived') ->withSymfonyMessage(static function (Email $email): void { $email->replyTo('RoboJackets <hello@robojackets.org>'); }) ->tag('agreement-docusign-received') ->metadata('envelope-id', strval($this->envelope->id)); } } ","<?php declare(strict_types=1); namespace App\Mail; use App\Models\DocuSignEnvelope; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Symfony\Component\Mime\Email; class MembershipAgreementDocuSignEnvelopeReceived extends Mailable implements ShouldQueue { use Queueable; use SerializesModels; public DocuSignEnvelope $envelope; /** * Create a new message instance. */ public function __construct(DocuSignEnvelope $envelope) { $this->envelope = $envelope; } /** * Build the message. */ public function build(): self { return $this->from('noreply@my.robojackets.org', 'RoboJackets') ->to($this->envelope->signedBy->gt_email, $this->envelope->signedBy->name) ->cc('Membership Agreement Archives <'.config('services.membership_agreement_archive_email').'>') ->subject('Membership agreement signed') ->text('mail.agreement.docusignenvelopereceived') ->withSymfonyMessage(static function (Email $email): void { $email->replyTo('RoboJackets <hello@robojackets.org>'); }) ->tag('agreement-docusign-received') ->metadata('envelope-id', strval($this->envelope->id)); } } " Order tags in the menu in alphabetical order,"package models; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.persistence.*; import play.db.ebean.Model; import play.db.ebean.Model.Finder; @Entity public class Tag extends Model { @Id public Integer id; public String title; public boolean use_student_display; @OneToOne(mappedBy=""tag"") public TaskList task_list; public static Finder<Integer, Tag> find = new Finder( Integer.class, Tag.class ); public static Tag create(String title) { Tag result = new Tag(); result.title = title; result.save(); return result; } public static Map<String, List<Tag>> getWithPrefixes() { Map<String, List<Tag>> result = new TreeMap<String, List<Tag>>(); for (Tag t : find.order(""title ASC"").findList()) { String[] splits = t.title.split("":""); String prefix = t.title; if (splits.length > 1) { prefix = splits[0]; } List<Tag> cur_list = result.get(splits[0]); if (cur_list == null) { cur_list = new ArrayList<Tag>(); } cur_list.add(t); result.put(splits[0], cur_list); } return result; } } ","package models; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.*; import play.db.ebean.Model; import play.db.ebean.Model.Finder; @Entity public class Tag extends Model { @Id public Integer id; public String title; public boolean use_student_display; @OneToOne(mappedBy=""tag"") public TaskList task_list; public static Finder<Integer, Tag> find = new Finder( Integer.class, Tag.class ); public static Tag create(String title) { Tag result = new Tag(); result.title = title; result.save(); return result; } public static Map<String, List<Tag>> getWithPrefixes() { Map<String, List<Tag>> result = new HashMap<String, List<Tag>>(); for (Tag t : find.order(""title ASC"").findList()) { String[] splits = t.title.split("":""); String prefix = t.title; if (splits.length > 1) { prefix = splits[0]; } List<Tag> cur_list = result.get(splits[0]); if (cur_list == null) { cur_list = new ArrayList<Tag>(); } cur_list.add(t); result.put(splits[0], cur_list); } return result; } } " Use a simple counter rather than appending booleans to a list and counting them.,"""""""Tests for refleaks."""""" import itertools from cherrypy._cpcompat import HTTPConnection, HTTPSConnection, ntob import threading import cherrypy data = object() from cherrypy.test import helper class ReferenceTests(helper.CPWebCase): @staticmethod def setup_server(): class Root: @cherrypy.expose def index(self, *args, **kwargs): cherrypy.request.thing = data return ""Hello world!"" cherrypy.tree.mount(Root()) def test_threadlocal_garbage(self): success = itertools.count() def getpage(): host = '%s:%s' % (self.interface(), self.PORT) if self.scheme == 'https': c = HTTPSConnection(host) else: c = HTTPConnection(host) try: c.putrequest('GET', '/') c.endheaders() response = c.getresponse() body = response.read() self.assertEqual(response.status, 200) self.assertEqual(body, ntob(""Hello world!"")) finally: c.close() next(success) ITERATIONS = 25 ts = [] for _ in range(ITERATIONS): t = threading.Thread(target=getpage) ts.append(t) t.start() for t in ts: t.join() self.assertEqual(next(success), ITERATIONS) ","""""""Tests for refleaks."""""" from cherrypy._cpcompat import HTTPConnection, HTTPSConnection, ntob import threading import cherrypy data = object() from cherrypy.test import helper class ReferenceTests(helper.CPWebCase): @staticmethod def setup_server(): class Root: @cherrypy.expose def index(self, *args, **kwargs): cherrypy.request.thing = data return ""Hello world!"" cherrypy.tree.mount(Root()) def test_threadlocal_garbage(self): success = [] def getpage(): host = '%s:%s' % (self.interface(), self.PORT) if self.scheme == 'https': c = HTTPSConnection(host) else: c = HTTPConnection(host) try: c.putrequest('GET', '/') c.endheaders() response = c.getresponse() body = response.read() self.assertEqual(response.status, 200) self.assertEqual(body, ntob(""Hello world!"")) finally: c.close() success.append(True) ITERATIONS = 25 ts = [] for _ in range(ITERATIONS): t = threading.Thread(target=getpage) ts.append(t) t.start() for t in ts: t.join() self.assertEqual(len(success), ITERATIONS) " "Remove LiveWindow call from CommandBasedRobot LiveWindow is automatically updated regardless of mode as part of 2018 WPILib IterativeRobot changes, so calling LiveWindow.run() manually is unnecessary.","from wpilib import TimedRobot from wpilib.command import Scheduler class CommandBasedRobot(TimedRobot): ''' The base class for a Command-Based Robot. To use, instantiate commands and trigger them. ''' def startCompetition(self): """"""Initalizes the scheduler before starting robotInit()"""""" self.scheduler = Scheduler.getInstance() super().startCompetition() def commandPeriodic(self): ''' Run the scheduler regularly. If an error occurs during a competition, prevent it from crashing the program. ''' try: self.scheduler.run() except Exception as error: if not self.ds.isFMSAttached(): raise '''Just to be safe, stop all running commands.''' self.scheduler.removeAll() self.handleCrash(error) autonomousPeriodic = commandPeriodic teleopPeriodic = commandPeriodic disabledPeriodic = commandPeriodic # testPeriodic deliberately omitted def handleCrash(self, error): ''' Called if an exception is raised in the Scheduler during a competition. Writes an error message to the driver station by default. If you want more complex behavior, override this method in your robot class. ''' self.ds.reportError(str(error), printTrace=True) ","import hal from wpilib.timedrobot import TimedRobot from wpilib.command.scheduler import Scheduler from wpilib.livewindow import LiveWindow class CommandBasedRobot(TimedRobot): ''' The base class for a Command-Based Robot. To use, instantiate commands and trigger them. ''' def startCompetition(self): """"""Initalizes the scheduler before starting robotInit()"""""" self.scheduler = Scheduler.getInstance() super().startCompetition() def commandPeriodic(self): ''' Run the scheduler regularly. If an error occurs during a competition, prevent it from crashing the program. ''' try: self.scheduler.run() except Exception as error: if not self.ds.isFMSAttached(): raise '''Just to be safe, stop all running commands.''' self.scheduler.removeAll() self.handleCrash(error) autonomousPeriodic = commandPeriodic teleopPeriodic = commandPeriodic disabledPeriodic = commandPeriodic def testPeriodic(self): ''' Test mode will not run normal commands, but motors can be controlled and sensors viewed with the SmartDashboard. ''' LiveWindow.run() def handleCrash(self, error): ''' Called if an exception is raised in the Scheduler during a competition. Writes an error message to the driver station by default. If you want more complex behavior, override this method in your robot class. ''' self.ds.reportError(str(error), printTrace=True) " Remove PaginatorAdapterInterface since it does not make sense to put it on the adapter for Pagerfanta.,"<?php namespace FOS\ElasticaBundle\Paginator; use Pagerfanta\Adapter\AdapterInterface; class FantaPaginatorAdapter implements AdapterInterface { private $adapter; /** * @param \FOS\ElasticaBundle\Paginator\PaginatorAdapterInterface $adapter */ public function __construct(PaginatorAdapterInterface $adapter) { $this->adapter = $adapter; } /** * Returns the number of results. * * @return integer The number of results. */ public function getNbResults() { return $this->adapter->getTotalHits(); } /** * Returns Facets. * * @return mixed */ public function getFacets() { return $this->adapter->getFacets(); } /** * Returns Aggregations. * * @return mixed * * @api */ public function getAggregations() { return $this->adapter->getAggregations(); } /** * Returns a slice of the results. * * @param integer $offset The offset. * @param integer $length The length. * * @return array|\Traversable The slice. */ public function getSlice($offset, $length) { return $this->adapter->getResults($offset, $length)->toArray(); } } ","<?php namespace FOS\ElasticaBundle\Paginator; use Pagerfanta\Adapter\AdapterInterface; class FantaPaginatorAdapter implements AdapterInterface, PaginatorAdapterInterface { private $adapter; /** * @param \FOS\ElasticaBundle\Paginator\PaginatorAdapterInterface $adapter */ public function __construct(PaginatorAdapterInterface $adapter) { $this->adapter = $adapter; } /** * Returns the number of results. * * @return integer The number of results. */ public function getNbResults() { return $this->adapter->getTotalHits(); } /** * Returns Facets. * * @return mixed */ public function getFacets() { return $this->adapter->getFacets(); } /** * Returns Aggregations. * * @return mixed * * @api */ public function getAggregations() { return $this->adapter->getAggregations(); } /** * Returns a slice of the results. * * @param integer $offset The offset. * @param integer $length The length. * * @return array|\Traversable The slice. */ public function getSlice($offset, $length) { return $this->adapter->getResults($offset, $length)->toArray(); } } " Remove anchor from start of code block regex.,"<?php namespace FluxBB\CommonMark\Parser\Block; use FluxBB\CommonMark\Common\Text; use FluxBB\CommonMark\Node\CodeBlock; use FluxBB\CommonMark\Node\Container; use FluxBB\CommonMark\Parser\AbstractBlockParser; class CodeBlockParser extends AbstractBlockParser { /** * Parse the given content. * * Any newly created nodes should be pushed to the stack. Any remaining content should be passed to the next parser * in the chain. * * @param Text $content * @param Container $target * @return void */ public function parseBlock(Text $content, Container $target) { $content->handle( '{ (?: # Ensure blank line before (or beginning of subject) \A\s*\n?| \n\s*\n ) [ ]{4} # four leading spaces .+ (?: # optionally more spaces (?: # blank lines in between are okay \n[ ]* )* \n [ ]{4} .+ )* $ }mx', function (Text $code) use ($target) { // Remove leading blank lines $code->replace('/^(\s*\n)*/', ''); // Remove indent $code->replace('/^[ ]{1,4}/m', ''); $code->append(""\n""); $target->acceptCodeBlock(new CodeBlock($code)); }, function(Text $part) use ($target) { $this->next->parseBlock($part, $target); } ); } } ","<?php namespace FluxBB\CommonMark\Parser\Block; use FluxBB\CommonMark\Common\Text; use FluxBB\CommonMark\Node\CodeBlock; use FluxBB\CommonMark\Node\Container; use FluxBB\CommonMark\Parser\AbstractBlockParser; class CodeBlockParser extends AbstractBlockParser { /** * Parse the given content. * * Any newly created nodes should be pushed to the stack. Any remaining content should be passed to the next parser * in the chain. * * @param Text $content * @param Container $target * @return void */ public function parseBlock(Text $content, Container $target) { $content->handle( '{ ^ (?: # Ensure blank line before (or beginning of subject) \A\s*\n?| \n\s*\n ) [ ]{4} # four leading spaces .+ (?: # optionally more spaces (?: # blank lines in between are okay \n[ ]* )* \n [ ]{4} .+ )* $ }mx', function (Text $code) use ($target) { // Remove leading blank lines $code->replace('/^(\s*\n)*/', ''); // Remove indent $code->replace('/^[ ]{1,4}/m', ''); $code->append(""\n""); $target->acceptCodeBlock(new CodeBlock($code)); }, function(Text $part) use ($target) { $this->next->parseBlock($part, $target); } ); } } " "Use custom column names for some attributes in queryable tests (shouldn't affect the tests, which is the point)","/** * Dependencies */ var Waterline = require('waterline'); module.exports = Waterline.Collection.extend({ tableName: 'userTable2', identity: 'user', datastore: 'queryable', primaryKey: 'id', fetchRecordsOnUpdate: true, fetchRecordsOnDestroy: false, fetchRecordsOnCreate: true, fetchRecordsOnCreateEach: true, attributes: { // Primary Key id: { type: 'number', autoMigrations: { columnType: 'integer', autoIncrement: true, unique: true } }, first_name: { type: 'string', columnName: 'fName', autoMigrations: { columnType: 'varchar' } }, last_name: { type: 'string', columnName: 'lName', autoMigrations: { columnType: 'varchar' } }, type: { type: 'string', columnName: 't', autoMigrations: { columnType: 'varchar' } }, age: { type: 'number', columnName: 'a', autoMigrations: { columnType: 'integer' } }, email: { type: 'string', autoMigrations: { columnType: 'varchar' } }, // Timestamps updatedAt: { type: 'number', autoUpdatedAt: true, autoMigrations: { columnType: 'bigint' } }, createdAt: { type: 'number', autoCreatedAt: true, autoMigrations: { columnType: 'bigint' } } } }); ","/** * Dependencies */ var Waterline = require('waterline'); module.exports = Waterline.Collection.extend({ tableName: 'userTable2', identity: 'user', datastore: 'queryable', primaryKey: 'id', fetchRecordsOnUpdate: true, fetchRecordsOnDestroy: false, fetchRecordsOnCreate: true, fetchRecordsOnCreateEach: true, attributes: { // Primary Key id: { type: 'number', autoMigrations: { columnType: 'integer', autoIncrement: true, unique: true } }, first_name: { type: 'string', columnName: 'fName', autoMigrations: { columnType: 'varchar' } }, last_name: { type: 'string', autoMigrations: { columnType: 'varchar' } }, type: { type: 'string', autoMigrations: { columnType: 'varchar' } }, age: { type: 'number', autoMigrations: { columnType: 'integer' } }, email: { type: 'string', autoMigrations: { columnType: 'varchar' } }, // Timestamps updatedAt: { type: 'number', autoUpdatedAt: true, autoMigrations: { columnType: 'bigint' } }, createdAt: { type: 'number', autoCreatedAt: true, autoMigrations: { columnType: 'bigint' } } } }); " Set perks on form save.,"from django import forms from django.utils.translation import ugettext_lazy as _, ugettext as __ from .models import Funding from .widgets import PerksAmountWidget class FundingForm(forms.Form): required_css_class = 'required' amount = forms.DecimalField(label=_(""Amount""), decimal_places=2, widget=PerksAmountWidget()) name = forms.CharField(label=_(""Name""), required=False, help_text=_(""Optional name for public list of contributors"")) email = forms.EmailField(label=_(""Contact e-mail""), help_text=_(""We'll use it to contact you about your perks and fundraiser status and payment updates.<br/> "" ""Won't be publicised.""), required=False) def __init__(self, offer, *args, **kwargs): self.offer = offer super(FundingForm, self).__init__(*args, **kwargs) self.fields['amount'].widget.form_instance = self def clean_amount(self): if self.cleaned_data['amount'] <= 0: raise forms.ValidationError(__(""Enter positive amount."")) return self.cleaned_data['amount'] def clean(self): if not self.offer.is_current(): raise forms.ValidationError(__(""This offer is out of date."")) return self.cleaned_data def save(self): funding = Funding.objects.create( offer=self.offer, name=self.cleaned_data['name'], email=self.cleaned_data['email'], amount=self.cleaned_data['amount'], ) funding.perks = funding.offer.get_perks(funding.amount) return funding ","from django import forms from django.utils.translation import ugettext_lazy as _, ugettext as __ from .models import Funding from .widgets import PerksAmountWidget class FundingForm(forms.Form): required_css_class = 'required' amount = forms.DecimalField(label=_(""Amount""), decimal_places=2, widget=PerksAmountWidget()) name = forms.CharField(label=_(""Name""), required=False, help_text=_(""Optional name for public list of contributors"")) email = forms.EmailField(label=_(""Contact e-mail""), help_text=_(""We'll use it to contact you about your perks and fundraiser status and payment updates.<br/> "" ""Won't be publicised.""), required=False) def __init__(self, offer, *args, **kwargs): self.offer = offer super(FundingForm, self).__init__(*args, **kwargs) self.fields['amount'].widget.form_instance = self def clean_amount(self): if self.cleaned_data['amount'] <= 0: raise forms.ValidationError(__(""Enter positive amount."")) return self.cleaned_data['amount'] def clean(self): if not self.offer.is_current(): raise forms.ValidationError(__(""This offer is out of date."")) return self.cleaned_data def save(self): return Funding.objects.create( offer=self.offer, name=self.cleaned_data['name'], email=self.cleaned_data['email'], amount=self.cleaned_data['amount'], ) " Fix symlink creation for the examples,"'use strict'; module.exports = function (gulp, $) { gulp.task('scripts:setup', function () { return gulp.src('source') .pipe($.symlink('examples/source')); }); gulp.task('jscs', function () { return gulp.src([ 'source/**/*.js', 'examples/js/*.js' ]) .pipe($.jscs()); }); gulp.task('jshint', function () { return gulp.src([ 'source/**/*.js', 'examples/js/*.js' ]) .pipe($.jshint()) .pipe($.jshint.reporter('jshint-stylish')) .pipe($.jshint.reporter('fail')); }); gulp.task('concat', function () { return gulp.src([ 'source/**/*.js', '!**/*.spec.js' ]) .pipe($.concat('angular-ui-tree.js')) .pipe(gulp.dest('dist')); }); gulp.task('uglify', ['concat'], function () { return gulp.src('dist/angular-ui-tree.js') .pipe($.uglify({ preserveComments: 'some' })) .pipe($.rename('angular-ui-tree.min.js')) .pipe(gulp.dest('dist')); }); gulp.task('karma', function () { var server = new $.karma.Server({ configFile: __dirname + '/../karma.conf.js', singleRun: true }, function (err) { process.exit(err ? 1 : 0); }); return server.start(); }); }; ","'use strict'; module.exports = function (gulp, $) { gulp.task('scripts:setup', function () { return gulp.src('source') .pipe($.symlink('examples/source', { force: true })); }); gulp.task('jscs', function () { return gulp.src([ 'source/**/*.js', 'examples/js/*.js' ]) .pipe($.jscs()); }); gulp.task('jshint', function () { return gulp.src([ 'source/**/*.js', 'examples/js/*.js' ]) .pipe($.jshint()) .pipe($.jshint.reporter('jshint-stylish')) .pipe($.jshint.reporter('fail')); }); gulp.task('concat', function () { return gulp.src([ 'source/**/*.js', '!**/*.spec.js' ]) .pipe($.concat('angular-ui-tree.js')) .pipe(gulp.dest('dist')); }); gulp.task('uglify', ['concat'], function () { return gulp.src('dist/angular-ui-tree.js') .pipe($.uglify({ preserveComments: 'some' })) .pipe($.rename('angular-ui-tree.min.js')) .pipe(gulp.dest('dist')); }); gulp.task('karma', function () { var server = new $.karma.Server({ configFile: __dirname + '/../karma.conf.js', singleRun: true }, function (err) { process.exit(err ? 1 : 0); }); return server.start(); }); }; " Replace hard-coded English at top of settings menu,"@extends('layout') @section('body') <div class=""wrapper my-3""> <div class=""row""> <div class=""row__column mr-3"" style=""max-width: 300px;""> <div class=""box""> <div class=""box__section box__section--header"">{{ __('pages.settings') }}</div> <ul class=""box__section""> <li><a href=""/settings/profile""><i class=""fas fa-user fa-sm""></i> {{ __('general.profile') }}</a></li> <li><a href=""/settings/account""><i class=""fas fa-lock fa-sm""></i> {{ __('general.account') }}</a></li> <li><a href=""/settings/preferences""><i class=""fas fa-sliders-h fa-sm""></i> {{ __('general.preferences') }}</a></li> <li><a href=""/settings/spaces""><i class=""fas fa-rocket fa-sm""></i> {{ __('models.spaces') }}</a></li> </ul> </div> </div> <div class=""row__column""> @yield('settings_title') <form method=""POST"" action=""/settings"" enctype=""multipart/form-data""> {{ csrf_field() }} @yield('settings_body') </form> </div> </div> </div> @endsection ","@extends('layout') @section('body') <div class=""wrapper my-3""> <div class=""row""> <div class=""row__column mr-3"" style=""max-width: 300px;""> <div class=""box""> <div class=""box__section box__section--header"">Settings</div> <ul class=""box__section""> <li><a href=""/settings/profile""><i class=""fas fa-user fa-sm""></i> {{ __('general.profile') }}</a></li> <li><a href=""/settings/account""><i class=""fas fa-lock fa-sm""></i> {{ __('general.account') }}</a></li> <li><a href=""/settings/preferences""><i class=""fas fa-sliders-h fa-sm""></i> {{ __('general.preferences') }}</a></li> <li><a href=""/settings/spaces""><i class=""fas fa-rocket fa-sm""></i> {{ __('models.spaces') }}</a></li> </ul> </div> </div> <div class=""row__column""> @yield('settings_title') <form method=""POST"" action=""/settings"" enctype=""multipart/form-data""> {{ csrf_field() }} @yield('settings_body') </form> </div> </div> </div> @endsection " Change foreign_key for interes area,"module.exports = function(sequelize, DataTypes) { return sequelize.define('interesPoint', { id: { type: DataTypes.BIGINT, field: 'id', autoIncrement: true, primaryKey: true }, interesArea_fk: { type: DataTypes.BIGINT, field: 'interesArea_fk', notNull: true, references: { model: 'interesareas', key: 'id' } }, longitude: { type: DataTypes.DOUBLE, field: 'longitude', notNull: true }, latitude: { type: DataTypes.DOUBLE, field: 'latitude', notNull: true } } ); }; ","module.exports = function(sequelize, DataTypes) { return sequelize.define('interesPoint', { id: { type: DataTypes.BIGINT, field: 'id', autoIncrement: true, primaryKey: true }, interesArea_fk: { type: DataTypes.BIGINT, field: 'interesArea_fk', notNull: true, references: { model: 'interesAreas', key: 'id' } }, longitude: { type: DataTypes.DOUBLE, field: 'longitude', notNull: true }, latitude: { type: DataTypes.DOUBLE, field: 'latitude', notNull: true } } ); }; " Add test for relative path and renderString,"(function() { var expect, Environment, Loader, templatesPath; if(typeof require != 'undefined') { expect = require('expect.js'); Environment = require('../src/environment').Environment; Loader = require('../src/node-loaders').FileSystemLoader; templatesPath = 'tests/templates'; } else { expect = window.expect; Environment = nunjucks.Environment; Loader = nunjucks.WebLoader; templatesPath = '../templates'; } describe('api', function() { it('should always force compilation of parent template', function() { var env = new Environment(new Loader(templatesPath)); var parent = env.getTemplate('base.html'); var child = env.getTemplate('base-inherit.html'); expect(child.render()).to.be('Foo*Bar*BazFizzle'); }); it('should handle correctly relative paths', function() { var env = new Environment(new Loader(templatesPath)); var child1 = env.getTemplate('relative/test1.html'); var child2 = env.getTemplate('relative/test2.html'); expect(child1.render()).to.be('FooTest1BazFizzle'); expect(child2.render()).to.be('FooTest2BazFizzle'); }); it('should handle correctly relative paths in renderString', function() { var env = new Environment(new Loader(templatesPath)); expect(env.renderString('{% extends ""./relative/test1.html"" %}{% block block1 %}Test3{% endblock %}')).to.be('FooTest3BazFizzle'); }); }); })(); ","(function() { var expect, Environment, Loader, templatesPath; if(typeof require != 'undefined') { expect = require('expect.js'); Environment = require('../src/environment').Environment; Loader = require('../src/node-loaders').FileSystemLoader; templatesPath = 'tests/templates'; } else { expect = window.expect; Environment = nunjucks.Environment; Loader = nunjucks.WebLoader; templatesPath = '../templates'; } describe('api', function() { it('should always force compilation of parent template', function() { var env = new Environment(new Loader(templatesPath)); var parent = env.getTemplate('base.html'); var child = env.getTemplate('base-inherit.html'); expect(child.render()).to.be('Foo*Bar*BazFizzle'); }); it('should handle correctly relative paths', function() { var env = new Environment(new Loader(templatesPath)); var child1 = env.getTemplate('relative/test1.html'); var child2 = env.getTemplate('relative/test2.html'); expect(child1.render()).to.be('FooTest1BazFizzle'); expect(child2.render()).to.be('FooTest2BazFizzle'); }); }); })(); " Remove unwanted prints in management command,"from django.core.management.base import BaseCommand from django.utils import timezone from salt_observer.models import Minion from . import ApiCommand import json class Command(ApiCommand, BaseCommand): help = 'Fetch and save new data from all servers' def save_packages(self, api): packages = api.get_server_module_data('pkg.list_pkgs') upgrades = api.get_server_module_data('pkg.list_upgrades') for minion_fqdn, minion_packages in packages.items(): minion = Minion.objects.filter(fqdn=minion_fqdn).first() minion_data = json.loads(minion.data) minion_package_data = {} for minion_package_name, minion_package_version in minion_packages.items(): if type(upgrades.get(minion_fqdn, {})) != dict: del upgrades[minion_fqdn] minion_package_data.update({ minion_package_name: { 'version': minion_package_version, 'latest_version': upgrades.get(minion_fqdn, {}).get(minion_package_name, '') } }) minion_data['packages'] = minion_package_data minion.data = json.dumps(minion_data) minion.save() def handle(self, *args, **kwargs): api = super().handle(*args, **kwargs) self.save_packages(api) api.logout() ","from django.core.management.base import BaseCommand from django.utils import timezone from salt_observer.models import Minion from . import ApiCommand import json class Command(ApiCommand, BaseCommand): help = 'Fetch and save new data from all servers' def save_packages(self, api): print('Fetching packages ...') packages = api.get_server_module_data('pkg.list_pkgs') print('Fetching upgrades ...') upgrades = api.get_server_module_data('pkg.list_upgrades') for minion_fqdn, minion_packages in packages.items(): print('Handling {}'.format(minion_fqdn)) minion = Minion.objects.filter(fqdn=minion_fqdn).first() minion_data = json.loads(minion.data) minion_package_data = {} for minion_package_name, minion_package_version in minion_packages.items(): if type(upgrades.get(minion_fqdn, {})) != dict: del upgrades[minion_fqdn] minion_package_data.update({ minion_package_name: { 'version': minion_package_version, 'latest_version': upgrades.get(minion_fqdn, {}).get(minion_package_name, '') } }) minion_data['packages'] = minion_package_data minion.data = json.dumps(minion_data) minion.save() def handle(self, *args, **kwargs): api = super().handle(*args, **kwargs) self.save_packages(api) api.logout() " Move csv in a module,"let csv = (function () { let buildHeader = function (line) { return ""<thead><tr><th scope=\""col\""><button>"" + line.slice(0, -1).split("","").join(""</button></th><th scope=\""col\""><button>"") + ""</button></th></tr></thead>"" }; let buildAsHtml = function (lines) { let output = [buildHeader(lines[0])]; for (let i = 1; i < lines.length; i++) output.push(""<tr><td>"" + lines[i].slice(0, -1).split("","").join(""</td><td>"") + ""</td></tr>""); return ""<table>"" + output.join("""") + ""</table>""; }; return { buildAsHtml: buildAsHtml }; })(); function readSingleFile(e) { let file = e.target.files[0]; if (!file) { return; } let reader = new FileReader(); reader.onload = function(e) { let contents = e.target.result; displayContents(contents); $('#play-input').disabled = false; }; reader.readAsText(file); } function TestCall(event, other) { console.log(event); console.log(other); } function displayContents(contents) { var div = document.getElementById('file-content'); div.innerHTML = csv.buildAsHtml(contents.split(""\n"")); var ths = document.getElementsByTagName(""th""); console.log(""ths "" + ths); for (var i = 0; i < ths.length; i++) { ths[i].onclick = TestCall } // var element = $('#content'); // element.innerHTML = contents; }","function readSingleFile(e) { var file = e.target.files[0]; if (!file) { return; } var reader = new FileReader(); reader.onload = function(e) { var contents = e.target.result; displayContents(contents); $('#play-input').disabled = false; }; reader.readAsText(file); } function TestCall(event, other) { console.log(event); console.log(other); } function displayContents(contents) { var lines = contents.split(""\n""), output = [], i; output.push(""<thead><tr><th scope=\""col\""><button>"" + lines[0].slice(0, -1).split("","").join(""</button></th><th scope=\""col\""><button>"") + ""</button></th></tr></thead>""); for (i = 1; i < lines.length; i++) output.push(""<tr><td>"" + lines[i].slice(0, -1).split("","").join(""</td><td>"") + ""</td></tr>""); output = ""<table>"" + output.join("""") + ""</table>""; var div = document.getElementById('file-content'); div.innerHTML = output; var ths = document.getElementsByTagName(""th""); console.log(""ths "" + ths); for (var i = 0; i < ths.length; i++) { ths[i].onclick = TestCall } // var element = $('#content'); // element.innerHTML = contents; }" "Fix issue with lightbox resizing. Fixes #34","function calcMaxHeight(parent) { var winHeight = window.innerHeight; var padding = parseInt(parent.css('padding-top')) + parseInt(parent.css('margin-top')); return (winHeight * .95) - (2 * padding) - 1; } function calcMaxWidth(parent) { var winWidth = window.innerWidth; var padding = parseInt(parent.css('padding-left')) + parseInt(parent.css('margin-left')); return (winWidth * .95) - (2 * padding) - 1; } function resizeImg(img) { img.removeAttr('style'); var parent = img.parent(); var maxHeight = calcMaxHeight(parent); var maxWidth = calcMaxWidth(parent); if (maxWidth / img.width() < maxHeight / img.height()) { img.css('max-width', maxWidth + 'px'); } else { img.css('max-height', maxHeight + 'px'); } } $(document).ready(function() { $('.gallery__item').css('cursor', 'pointer'); $('.gallery__item').click(function() { var thumb = $(this).find('img'); var fullImg = $('<img />').attr('src', thumb.data('full-size')); $.featherlight(fullImg, { beforeOpen: function() { $('.featherlight-inner').removeClass('gallery__img'); }, onResize: function() { var img = $('.featherlight-inner'); resizeImg(img); } }); }); }); ","function resizeWhich(img) { img.removeAttr('style'); if (window.innerWidth / img.width() < window.innerHeight / img.height()) { return 'width'; console.log('Set width to 100%') } else { return 'height'; console.log('Set height to 100%') } } $(document).ready(function() { $('.gallery__item').css('cursor', 'pointer'); $('.gallery__item').click(function() { var thumb = $(this).find('img'); var fullImg = $('<img />').attr('src', thumb.data('full-size')); $.featherlight(fullImg, { onResize: function() { var img = $('.featherlight-inner').removeClass('gallery__img'); var prop = resizeWhich(img); var winHeight = window.innerHeight; var winWidth = window.innerWidth; var parent = img.parent(); var padding = parseInt(parent.css('padding-top')); if (prop === 'height') { var newHeight = (winHeight * .95) - 2 * padding - 1; img.css('max-height', newHeight + 'px'); } else { var newWidth = (winWidth * .95) - 2 * padding - 1; img.css('max-width', newWidth + 'px'); } } }); }); }); " Use imported class name instead of FQN,"<?php namespace Tests\Firebase\Database\Reference; use Firebase\Database\Reference\Validator; use Firebase\Exception\InvalidArgumentException; use GuzzleHttp\Psr7\Uri; use Psr\Http\Message\UriInterface; use Tests\FirebaseTestCase; class ValidatorTest extends FirebaseTestCase { /** * @var UriInterface */ private $uri; /** * @var Validator */ private $validator; protected function setUp() { parent::setUp(); $this->uri = new Uri('http://domain.tld'); $this->validator = new Validator(); } public function testValidateDepth() { $uri = $this->uri->withPath(str_pad('', (Validator::MAX_DEPTH + 1) * 2, 'x/')); $this->expectException(InvalidArgumentException::class); $this->validator->validateUri($uri); } public function testValidateKeySize() { $uri = $this->uri->withPath(str_pad('', Validator::MAX_KEY_SIZE + 1, 'x')); $this->expectException(InvalidArgumentException::class); $this->validator->validateUri($uri); } public function testValidateChars() { $invalid = str_shuffle(Validator::INVALID_KEY_CHARS)[0]; $uri = $this->uri->withPath($invalid); $this->expectException(InvalidArgumentException::class); $this->validator->validateUri($uri); } } ","<?php namespace Tests\Firebase\Database\Reference; use Firebase\Database\Reference\Validator; use Firebase\Exception\InvalidArgumentException; use GuzzleHttp\Psr7\Uri; use Psr\Http\Message\UriInterface; use Tests\FirebaseTestCase; class ValidatorTest extends FirebaseTestCase { /** * @var UriInterface */ private $uri; /** * @var Validator */ private $validator; protected function setUp() { parent::setUp(); $this->uri = new Uri('http://domain.tld'); $this->validator = new Validator(); } public function testValidateDepth() { $uri = $this->uri->withPath(str_pad('', (\Firebase\Database\Reference\Validator::MAX_DEPTH + 1) * 2, 'x/')); $this->expectException(InvalidArgumentException::class); $this->validator->validateUri($uri); } public function testValidateKeySize() { $uri = $this->uri->withPath(str_pad('', \Firebase\Database\Reference\Validator::MAX_KEY_SIZE + 1, 'x')); $this->expectException(InvalidArgumentException::class); $this->validator->validateUri($uri); } public function testValidateChars() { $invalid = str_shuffle(\Firebase\Database\Reference\Validator::INVALID_KEY_CHARS)[0]; $uri = $this->uri->withPath($invalid); $this->expectException(InvalidArgumentException::class); $this->validator->validateUri($uri); } } " Convert from jquery to vanilla JS,"@extends('components.content-area') @section('content') @include('components.page-title', ['title' => $page['title']]) <div class=""content""> {!! $page['content']['main'] !!} <table class=""table-stack"" aria-label=""Example table with fake contact information""> <thead> <tr> <th scope=""col"">First Name</th> <th scope=""col"">Last Name</th> <th scope=""col"">Email</th> </tr> </thead> <tbody> @for ($i = 0; $i < 10; $i++) <tr valign=""top""> <td>{{ $faker->firstName }}</td> <td>{{ $faker->lastName }}</td> <td>{{ $faker->email }}</td> </tr> @endfor </tbody> </table> <a class=""button"" onclick=""document.querySelector('pre.table-stack').classList.toggle('hidden');"">See Table Code</a> <pre class=""table-stack hidden"" style=""background: #EAEAEA; margin-bottom: 10px; overflow: scroll;""> {!! htmlspecialchars(' <table class=""table-stack"" aria-label=""Example table""> <thead> <tr> <th scope=""col""></th> <th scope=""col""></th> <th scope=""col""></th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> </tr> </tbody> </table> ') !!} </pre> </div> @endsection ","@extends('components.content-area') @section('content') @include('components.page-title', ['title' => $page['title']]) <div class=""content""> {!! $page['content']['main'] !!} <table class=""table-stack"" aria-label=""Example table with fake contact information""> <thead> <tr> <th scope=""col"">First Name</th> <th scope=""col"">Last Name</th> <th scope=""col"">Email</th> </tr> </thead> <tbody> @for ($i = 0; $i < 10; $i++) <tr valign=""top""> <td>{{ $faker->firstName }}</td> <td>{{ $faker->lastName }}</td> <td>{{ $faker->email }}</td> </tr> @endfor </tbody> </table> <a class=""button"" onclick=""$('pre.table-stack').toggleClass('hidden');"">See Table Code</a> <pre class=""table-stack hidden"" style=""background: #EAEAEA; margin-bottom: 10px; overflow: scroll;""> {!! htmlspecialchars(' <table class=""table-stack"" aria-label=""Example table""> <thead> <tr> <th scope=""col""></th> <th scope=""col""></th> <th scope=""col""></th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> </tr> </tbody> </table> ') !!} </pre> </div> @endsection " Add TODO to fix bug at later date,"class LocalNodeMiddleware(object): """""" Ensures a Node that represents the local server always exists. No other suitable hook for code that's run once and can access the server's host name was found. A migration was not suitable for the second reason. """""" def __init__(self): self.local_node_created = False def process_request(self, request): if not self.local_node_created: from dashboard.models import Node nodes = Node.objects.filter(local=True) host = ""http://"" + request.get_host() if host[-1] != ""/"": host += ""/"" service = host + ""service/"" if len(nodes) == 0: node = Node(name=""Local"", website_url=host, service_url=service, local=True) node.save() elif len(nodes) == 1: node = nodes[0] node.host = host node.service = service # TODO: Fix bug that prevents this from actually saving node.save() else: raise RuntimeError(""More than one local node found in Nodes table. Please fix before continuing."") self.local_node_created = True return None ","class LocalNodeMiddleware(object): """""" Ensures a Node that represents the local server always exists. No other suitable hook for code that's run once and can access the server's host name was found. A migration was not suitable for the second reason. """""" def __init__(self): self.local_node_created = False def process_request(self, request): if not self.local_node_created: from dashboard.models import Node nodes = Node.objects.filter(local=True) host = ""http://"" + request.get_host() if host[-1] != ""/"": host += ""/"" service = host + ""service/"" if len(nodes) == 0: node = Node(name=""Local"", website_url=host, service_url=service, local=True) node.save() elif len(nodes) == 1: node = nodes[0] node.host = host node.service = service node.save() else: raise RuntimeError(""More than one local node found in Nodes table. Please fix before continuing."") self.local_node_created = True return None " Use MorphMap when there's no instance,"<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. declare(strict_types=1); namespace App\Libraries\User; use App\Libraries\MorphMap; use App\Models\Beatmap; use App\Models\Score; use App\Models\ScorePin; class ScorePins { const REQUEST_ATTRIBUTE_KEY_PREFIX = 'current_user_score_pins:'; public function isPinned(Score\Best\Model $best): bool { $type = $best->getMorphClass(); $key = static::REQUEST_ATTRIBUTE_KEY_PREFIX.$type; $pins = request()->attributes->get($key); if ($pins === null) { $user = auth()->user(); $pins = $user === null ? [] : $user->scorePins() ->select('score_id') ->where(['score_type' => $type]) ->get() ->keyBy(fn (ScorePin $p) => $p->score_id); request()->attributes->set($key, $pins); } return isset($pins[$best->getKey()]); } public function reset(): void { foreach (Beatmap::MODES as $mode => $modeInt) { $type = MorphMap::getType(Score\Best\Model::getClassByString($mode)); request()->attributes->remove(static::REQUEST_ATTRIBUTE_KEY_PREFIX.$type); } } } ","<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. declare(strict_types=1); namespace App\Libraries\User; use App\Models\Beatmap; use App\Models\Score; use App\Models\ScorePin; class ScorePins { const REQUEST_ATTRIBUTE_KEY_PREFIX = 'current_user_score_pins:'; public function isPinned(Score\Best\Model $best): bool { $type = $best->getMorphClass(); $key = static::REQUEST_ATTRIBUTE_KEY_PREFIX.$type; $pins = request()->attributes->get($key); if ($pins === null) { $user = auth()->user(); $pins = $user === null ? [] : $user->scorePins() ->select('score_id') ->where(['score_type' => $type]) ->get() ->keyBy(fn (ScorePin $p) => $p->score_id); request()->attributes->set($key, $pins); } return isset($pins[$best->getKey()]); } public function reset(): void { foreach (Beatmap::MODES as $mode => $modeInt) { $class = Score\Best\Model::getClassByString($mode); $type = (new $class())->getMorphClass(); request()->attributes->remove(static::REQUEST_ATTRIBUTE_KEY_PREFIX.$type); } } } " Use time inestad of unix timestamp in screenshot file name,"<?php namespace Lmc\Steward\Test; use Nette\Utils\Strings; /** * Listener to take screenshot on each error or failure */ class ErrorScreenshotListener extends \PHPUnit_Framework_BaseTestListener { public function addError(\PHPUnit_Framework_Test $test, \Exception $e, $time) { $this->takeScreenshot($test, $e, $time); } public function addFailure(\PHPUnit_Framework_Test $test, \PHPUnit_Framework_AssertionFailedError $e, $time) { $this->takeScreenshot($test, $e, $time); } /** * Take screenshot and save it * @param PHPUnit_Framework_Test|LmcTestCase $test * @param Exception $e * @param $time */ private function takeScreenshot(\PHPUnit_Framework_Test $test, \Exception $e, $time) { if (!$test instanceof AbstractTestCase) { throw new \InvalidArgumentException('Test case must be descendant of Lmc\Steward\Test\AbstractTestCase'); } $test->log('Taking screenshot because: ' . $e->getMessage()); if (!$test->wd instanceof \RemoteWebDriver) { $test->log(""No webdriver, no screenshot.""); } $test->wd->takeScreenshot( __DIR__ . '/../../logs/' . Strings::webalize(get_class($test)) . '-' . Strings::webalize($test->getName()) . '-' . date('Y-m-d-H-i-s') . '.png' ); } } ","<?php namespace Lmc\Steward\Test; use Nette\Utils\Strings; /** * Listener to take screenshot on each error or failure */ class ErrorScreenshotListener extends \PHPUnit_Framework_BaseTestListener { public function addError(\PHPUnit_Framework_Test $test, \Exception $e, $time) { $this->takeScreenshot($test, $e, $time); } public function addFailure(\PHPUnit_Framework_Test $test, \PHPUnit_Framework_AssertionFailedError $e, $time) { $this->takeScreenshot($test, $e, $time); } /** * Take screenshot and save it * @param PHPUnit_Framework_Test|LmcTestCase $test * @param Exception $e * @param $time */ private function takeScreenshot(\PHPUnit_Framework_Test $test, \Exception $e, $time) { if (!$test instanceof AbstractTestCase) { throw new \InvalidArgumentException('Test case must be descendant of Lmc\Steward\Test\AbstractTestCase'); } $test->log('Taking screenshot because: ' . $e->getMessage()); if (!$test->wd instanceof \RemoteWebDriver) { $test->log(""No webdriver, no screenshot.""); } $test->wd->takeScreenshot( __DIR__ . '/../../logs/' . Strings::webalize(get_class($test)) . '-' . Strings::webalize($test->getName()) . '-' . time() . '.png' ); } } " "Add dashboard sort clauses: first name and id I have seen the dashboard sorting be inconsistent. Last name then first name then id should produce a consistent and predictable sort order.","# -*- coding: utf-8 -*- from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic.base import TemplateView from django.views.generic.detail import DetailView from babybuddy.mixins import PermissionRequired403Mixin from core.models import Child class Dashboard(LoginRequiredMixin, TemplateView): # TODO: Use .card-deck in this template once BS4 is finalized. template_name = 'dashboard/dashboard.html' # Show the overall dashboard or a child dashboard if one Child instance. def get(self, request, *args, **kwargs): children = Child.objects.count() if children == 0: return HttpResponseRedirect(reverse('babybuddy:welcome')) elif children == 1: return HttpResponseRedirect( reverse( 'dashboard:dashboard-child', args={Child.objects.first().slug} ) ) return super(Dashboard, self).get(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(Dashboard, self).get_context_data(**kwargs) context['objects'] = Child.objects.all() \ .order_by('last_name', 'first_name', 'id') return context class ChildDashboard(PermissionRequired403Mixin, DetailView): model = Child permission_required = ('core.view_child',) raise_exception = True template_name = 'dashboard/child.html' ","# -*- coding: utf-8 -*- from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic.base import TemplateView from django.views.generic.detail import DetailView from babybuddy.mixins import PermissionRequired403Mixin from core.models import Child class Dashboard(LoginRequiredMixin, TemplateView): # TODO: Use .card-deck in this template once BS4 is finalized. template_name = 'dashboard/dashboard.html' # Show the overall dashboard or a child dashboard if one Child instance. def get(self, request, *args, **kwargs): children = Child.objects.count() if children == 0: return HttpResponseRedirect(reverse('babybuddy:welcome')) elif children == 1: return HttpResponseRedirect( reverse( 'dashboard:dashboard-child', args={Child.objects.first().slug} ) ) return super(Dashboard, self).get(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(Dashboard, self).get_context_data(**kwargs) context['objects'] = Child.objects.all().order_by('last_name') return context class ChildDashboard(PermissionRequired403Mixin, DetailView): model = Child permission_required = ('core.view_child',) raise_exception = True template_name = 'dashboard/child.html' " Add a content type description to keep twine happy.,"#!/usr/bin/env python import io from setuptools import setup, Extension with io.open('README.rst', encoding='utf8') as readme: long_description = readme.read() setup( name=""pyspamsum"", version=""1.0.5"", description=""A Python wrapper for Andrew Tridgell's spamsum algorithm"", long_description=long_description, long_description_content_type='text/x-rst', author=""Russell Keith-Magee"", author_email=""russell@keith-magee.com"", url='http://github.com/freakboy3742/pyspamsum/', license=""New BSD"", classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Topic :: Text Processing', 'Topic :: Utilities', ], ext_modules=[ Extension( ""spamsum"", [ ""pyspamsum.c"", ""spamsum.c"", ""edit_dist.c"", ] ) ], test_suite='tests', ) ","#!/usr/bin/env python import io from setuptools import setup, Extension with io.open('README.rst', encoding='utf8') as readme: long_description = readme.read() setup( name=""pyspamsum"", version=""1.0.5"", description=""A Python wrapper for Andrew Tridgell's spamsum algorithm"", long_description=long_description, author=""Russell Keith-Magee"", author_email=""russell@keith-magee.com"", url='http://github.com/freakboy3742/pyspamsum/', license=""New BSD"", classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Topic :: Text Processing', 'Topic :: Utilities', ], ext_modules=[ Extension( ""spamsum"", [ ""pyspamsum.c"", ""spamsum.c"", ""edit_dist.c"", ] ) ], test_suite='tests', ) " LT-275: Fix bug with loading measurement flow,"import { Template } from 'meteor/templating'; import { Blaze } from 'meteor/blaze'; import { OHIF } from 'meteor/ohif:core'; const toolMap = { bidirectional: 'targets' }; OHIF.measurements.toggleLabelButton = options => { const removeButtonView = () => { if (!options.instance.buttonView) { return; } Blaze.remove(options.instance.buttonView); options.instance.buttonView = null; }; if (options.instance.buttonView) { removeButtonView(); } const tool = toolMap[options.toolData.toolType]; const toolCollection = options.measurementApi[tool]; const measurement = toolCollection.findOne(options.toolData._id); const data = { measurement, tool, position: options.position, threeColumns: true, hideCommon: true, toolType: options.toolData.toolType, doneCallback(location, description) { options.callback(options, location, description); toolCollection.update(measurement._id, { $set: { location, description } }); removeButtonView(); } }; const view = Blaze.renderWithData(Template.measureFlow, data, options.element); options.instance.buttonView = view; }; ","import { Template } from 'meteor/templating'; import { Blaze } from 'meteor/blaze'; import { OHIF } from 'meteor/ohif:core'; const toolMap = { bidirectional: 'targets' }; OHIF.measurements.toggleLabelButton = options => { const removeButtonView = () => { if (!options.instance.buttonView) { return; } Blaze.remove(options.instance.buttonView); options.instance.buttonView = null; }; if (options.instance.buttonView) { removeButtonView(); } const tool = toolMap[options.toolData.toolType]; const toolCollection = options.measurementApi[tool]; const measurement = toolCollection.findOne(options.toolData.id); const data = { measurement, tool, position: options.position, threeColumns: true, hideCommon: true, toolType: options.toolData.toolType, doneCallback(location, description) { options.callback(options, location, description); toolCollection.update(measurement._id, { $set: { location, description } }); removeButtonView(); } }; const view = Blaze.renderWithData(Template.measureFlow, data, options.element); options.instance.buttonView = view; }; " Add a blank line helper on markdown formatter,"<?php /* * This file is part of the WizadDoctrineDocBundle. * * (c) William POTTIER <developer@william-pottier.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Wizad\DoctrineDocBundle\Formatter; class MarkdownFormatter { private $buffer; public function __construct() { } public function dump($file) { file_put_contents($file, $this->buffer); } /* * Advanced styling */ public function addTitle($title) { $this->writeln(PHP_EOL . $title . PHP_EOL . '===================='); } public function addSection($title) { $this->writeln(PHP_EOL . $title . PHP_EOL . '--------------------'); } public function addParagraph($text) { $this->writeln(PHP_EOL . $text . PHP_EOL); } public function addLink($url, $text = null) { if (!$text) { $this->write(sprintf('[[%s]]', $url)); } else { $this->write(sprintf('[%s](%s)', $text, $url)); } } public function addBlankLine() { $this->write(PHP_EOL . PHP_EOL); } /* * RAW manipulation */ protected function writeln($line) { $this->write($line . PHP_EOL); } protected function write($text) { $this->buffer .= $text; } }","<?php /* * This file is part of the WizadDoctrineDocBundle. * * (c) William POTTIER <developer@william-pottier.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Wizad\DoctrineDocBundle\Formatter; class MarkdownFormatter { private $buffer; public function __construct() { } public function dump($file) { file_put_contents($file, $this->buffer); } /* * Advanced styling */ public function addTitle($title) { $this->writeln(PHP_EOL . $title . PHP_EOL . '===================='); } public function addSection($title) { $this->writeln(PHP_EOL . $title . PHP_EOL . '--------------------'); } public function addParagraph($text) { $this->writeln(PHP_EOL . $text . PHP_EOL); } public function addLink($url, $text = null) { if (!$text) { $this->write(sprintf('[[%s]]', $url)); } else { $this->write(sprintf('[%s](%s)', $text, $url)); } } /* * RAW manipulation */ protected function writeln($line) { $this->write($line . PHP_EOL); } protected function write($text) { $this->buffer .= $text; } }" Exit process with -1 when error occurs,"var path = require('path'); var Q = require('q'); var _ = require('lodash'); var fs = require('fs'); var utils = require('./utils'); var generate = require(""../lib/generate""); var parse = require(""../lib/parse""); var generators = require(""../lib/generate"").generators; var buildCommand = function(command) { return command .option('-o, --output <directory>', 'Path to output directory, defaults to ./_book') .option('-f, --format <name>', 'Change generation format, defaults to site, availables are: '+_.keys(generators).join("", "")) .option('--config <config file>', 'Configuration file to use, defualt to book.json') }; var makeBuildFunc = function(converter) { return function(dir, options) { dir = dir || process.cwd(); outputDir = options.output; console.log('Starting build ...'); return converter( _.extend({}, options || {}, { input: dir, output: outputDir, generator: options.format, configFile: options.config }) ) .then(function(output) { console.log(""Successfuly built !""); return output; }, utils.logError) .fail(function() { process.exit(-1); }); }; }; module.exports = { folder: makeBuildFunc(generate.folder), file: makeBuildFunc(generate.file), command: buildCommand }; ","var path = require('path'); var Q = require('q'); var _ = require('lodash'); var fs = require('fs'); var utils = require('./utils'); var generate = require(""../lib/generate""); var parse = require(""../lib/parse""); var generators = require(""../lib/generate"").generators; var buildCommand = function(command) { return command .option('-o, --output <directory>', 'Path to output directory, defaults to ./_book') .option('-f, --format <name>', 'Change generation format, defaults to site, availables are: '+_.keys(generators).join("", "")) .option('--config <config file>', 'Configuration file to use, defualt to book.json') }; var makeBuildFunc = function(converter) { return function(dir, options) { dir = dir || process.cwd(); outputDir = options.output; console.log('Starting build ...'); return converter( _.extend({}, options || {}, { input: dir, output: outputDir, generator: options.format, configFile: options.config }) ) .then(function(output) { console.log(""Successfuly built !""); return output; }, utils.logError); }; }; module.exports = { folder: makeBuildFunc(generate.folder), file: makeBuildFunc(generate.file), command: buildCommand }; " Add `columns` to the ignore list,"var postcss = require('postcss'), extend = require('extend'); module.exports = postcss.plugin('postcss-default-unit', function (opts) { opts = opts || {}; opts.unit = opts.unit || 'px'; opts.ignore = extend({ 'columns': true, 'column-count': true, 'fill-opacity': true, 'font-weight': true, 'line-height': true, 'opacity': true, 'orphans': true, 'widows': true, 'z-index': true, 'zoom': true, 'flex': true, 'order': true, 'flex-grow': true, 'flex-shrink': true }, opts.ignore); function transformDecl(decl) { if (!opts.ignore[decl.prop] && !/\w\(.*\)/.test(decl.value)) { decl.value = decl.value.replace(/\d+(\s|\/|$)/g, function(match){ return parseInt(match) === 0 ? match : match.replace(/\d+/, '$&' + opts.unit); }); } } function transformRule(rule) { if (rule.name === 'media') { rule.params = rule.params.replace(/(height|width|resolution)\s*:\s*\d+\)/g, function(match){ return match.replace(/\d+/, '$&' + opts.unit); }); } } function defaultUnit(style) { style.eachDecl(transformDecl); style.eachAtRule(transformRule); } return defaultUnit; }); ","var postcss = require('postcss'), extend = require('extend'); module.exports = postcss.plugin('postcss-default-unit', function (opts) { opts = opts || {}; opts.unit = opts.unit || 'px'; opts.ignore = extend({ 'column-count': true, 'fill-opacity': true, 'font-weight': true, 'line-height': true, 'opacity': true, 'orphans': true, 'widows': true, 'z-index': true, 'zoom': true, 'flex': true, 'order': true, 'flex-grow': true, 'flex-shrink': true }, opts.ignore); function transformDecl(decl) { if (!opts.ignore[decl.prop] && !/\w\(.*\)/.test(decl.value)) { decl.value = decl.value.replace(/\d+(\s|\/|$)/g, function(match){ return parseInt(match) === 0 ? match : match.replace(/\d+/, '$&' + opts.unit); }); } } function transformRule(rule) { if (rule.name === 'media') { rule.params = rule.params.replace(/(height|width|resolution)\s*:\s*\d+\)/g, function(match){ return match.replace(/\d+/, '$&' + opts.unit); }); } } function defaultUnit(style) { style.eachDecl(transformDecl); style.eachAtRule(transformRule); } return defaultUnit; }); " Set equal height on cards in contacts,"@if (!$hideTitle && !empty($postTitle)) @typography([ 'id' => 'mod-text-' . $ID .'-label', 'element' => 'h4', 'variant' => 'h2', 'classList' => ['module-title'] ]) {!! $postTitle !!} @endtypography @endif <div class=""o-grid"" aria-labelledby={{'mod-text-' . $ID .'-label'}}> @foreach ($contacts as $contact) <div class=""o-grid-12 {{apply_filters('Municipio/Controller/Archive/GridColumnClass', $columns)}}""> @card([ 'collapsible' => $contact['hasBody'], 'attributeList' => [ 'itemscope' => '', 'itemtype' => 'http://schema.org/Person' ], 'classList' => [ 'c-card--square-image', 'u-height--100' ], 'context' => 'module.contacts.card' ]) @if($showImages) <div class=""c-card__image""> <div class=""c-card__image-background"" alt=""{{ $contact['full_name'] }}"" style=""{{ $contact['image']['inlineStyle'] }}""></div> </div> @endif <div class=""c-card__body u-padding--0""> @include('partials.information') </div> @endcard </div> @endforeach </div>","@if (!$hideTitle && !empty($postTitle)) @typography([ 'id' => 'mod-text-' . $ID .'-label', 'element' => 'h4', 'variant' => 'h2', 'classList' => ['module-title'] ]) {!! $postTitle !!} @endtypography @endif <div class=""o-grid"" aria-labelledby={{'mod-text-' . $ID .'-label'}}> @foreach ($contacts as $contact) <div class=""o-grid-12 {{apply_filters('Municipio/Controller/Archive/GridColumnClass', $columns)}}""> @card([ 'collapsible' => $contact['hasBody'], 'attributeList' => [ 'itemscope' => '', 'itemtype' => 'http://schema.org/Person' ], 'classList' => [ 'c-card--square-image' ], 'context' => 'module.contacts.card' ]) @if($showImages) <div class=""c-card__image""> <div class=""c-card__image-background"" alt=""{{ $contact['full_name'] }}"" style=""{{ $contact['image']['inlineStyle'] }}""></div> </div> @endif <div class=""c-card__body u-padding--0""> @include('partials.information') </div> @endcard </div> @endforeach </div>" "Use better css selector naming. Fixes https://github.com/maximveksler/EatWell/pull/2#discussion_r60944809","import React from 'react' import RestaurantModel from './RestaurantModel' class Restaurant extends React.Component { constructor(props) { super(props) this.displayName = ""Restaurant"" } render() { // helper for code simplicity. var model = this.props.model // Controller calculats food icon for HTML View presentation. var foodTypeImage = """"; if (model.foodType === ""Burger"") { foodTypeImage = ""assets/img/Burger.png"" } else { foodTypeImage = ""http://placeponi.es/48/48"" } // Prepare rating JSX var ratings = []; for (var i=0; i < model.rating; i++) { ratings.push(<span className=""glyphicon glyphicon-star"" key={i}/>); } return ( <li className=""media"" onClick={this.props.onClick}> <div className=""media-left""> <img className=""media-object"" src={foodTypeImage} /> </div> <div className={""media-body"" + (this.props.selected ? "" selected-restaurant-row"" : """")}> <h4 className=""media-heading"">{model.name}</h4> <p> Rating: {ratings} </p> </div> </li> ) } } Restaurant.propTypes = { model: React.PropTypes.instanceOf(RestaurantModel) } Restaurant.defaultProps = { restaurant : new RestaurantModel(""NameOfPlace"", ""Burger"", 2, ""Dubnov 7, Tel Aviv-Yafo, Israel"") } export default Restaurant ","import React from 'react' import RestaurantModel from './RestaurantModel' class Restaurant extends React.Component { constructor(props) { super(props) this.displayName = ""Restaurant"" } render() { // helper for code simplicity. var model = this.props.model // Controller calculats food icon for HTML View presentation. var foodTypeImage = """"; if (model.foodType === ""Burger"") { foodTypeImage = ""assets/img/Burger.png"" } else { foodTypeImage = ""http://placeponi.es/48/48"" } // Prepare rating JSX var ratings = []; for (var i=0; i < model.rating; i++) { ratings.push(<span className=""glyphicon glyphicon-star"" key={i}/>); } return ( <li className=""media"" onClick={this.props.onClick}> <div className=""media-left""> <img className=""media-object"" src={foodTypeImage} /> </div> <div className={""media-body"" + (this.props.selected ? "" selected"" : """")}> <h4 className=""media-heading"">{model.name}</h4> <p> Rating: {ratings} </p> </div> </li> ) } } Restaurant.propTypes = { model: React.PropTypes.instanceOf(RestaurantModel) } Restaurant.defaultProps = { restaurant : new RestaurantModel(""NameOfPlace"", ""Burger"", 2, ""Dubnov 7, Tel Aviv-Yafo, Israel"") } export default Restaurant " Add a test case for robots.txt,"'use strict'; // mocha defines to avoid JSHint breakage /* global describe, it, before, beforeEach, after, afterEach */ var preq = require('preq'); var assert = require('../../utils/assert.js'); var server = require('../../utils/server.js'); describe('express app', function() { this.timeout(20000); before(function () { return server.start(); }); it('should get robots.txt', function() { return preq.get({ uri: server.config.uri + 'robots.txt' }).then(function(res) { assert.deepEqual(res.status, 200); assert.deepEqual(res.headers['disallow'], '/'); }); }); it('should get static content gzipped', function() { return preq.get({ uri: server.config.uri + 'static/index.html', headers: { 'accept-encoding': 'gzip, deflate' } }).then(function(res) { // check that the response is gzip-ed assert.deepEqual(res.headers['content-encoding'], 'gzip', 'Expected gzipped contents!'); }); }); it('should get static content uncompressed', function() { return preq.get({ uri: server.config.uri + 'static/index.html', headers: { 'accept-encoding': '' } }).then(function(res) { // check that the response is gzip-ed assert.deepEqual(res.headers['content-encoding'], undefined, 'Did not expect gzipped contents!'); }); }); }); ","'use strict'; // mocha defines to avoid JSHint breakage /* global describe, it, before, beforeEach, after, afterEach */ var preq = require('preq'); var assert = require('../../utils/assert.js'); var server = require('../../utils/server.js'); describe('express app', function() { this.timeout(20000); before(function () { return server.start(); }); it('should get static content gzipped', function() { return preq.get({ uri: server.config.uri + 'static/index.html', headers: { 'accept-encoding': 'gzip, deflate' } }).then(function(res) { // check that the response is gzip-ed assert.deepEqual(res.headers['content-encoding'], 'gzip', 'Expected gzipped contents!'); }); }); it('should get static content uncompressed', function() { return preq.get({ uri: server.config.uri + 'static/index.html', headers: { 'accept-encoding': '' } }).then(function(res) { // check that the response is gzip-ed assert.deepEqual(res.headers['content-encoding'], undefined, 'Did not expect gzipped contents!'); }); }); }); " Fix scrollSpy bug preventing original scroll to happen if a hash is present,"$(function() { var $documentNav = $('.document-nav'); if($documentNav.length) { var targets = [] , $window = $(window) , changeHash = false; $documentNav.find('a').each(function() { targets.push( $($(this).attr('href')) ) }); function setActive(hash) { var $current = $documentNav.find('[href='+hash+']') , $parent = $current.closest('li') , $parentParent = $parent.parent().closest('li'); $documentNav.find('.current, .active').removeClass('current active') $current.addClass('current') if($parentParent.length) { $parentParent.addClass('active') } else { $parent.addClass('active') } if(history.pushState) { history.pushState(null, null, hash); } else { location.hash = hash; } } // Scroll, update menu // =================== $window.on('scroll', function() { var scrollTop = $window.scrollTop(); console.log ('scroll', scrollTop); $.each( targets, function($index, $el) { var sectionBottom = (targets[$index+1] && targets[$index+1].offset().top - 1) || $window.height() if ($el.length && scrollTop - sectionBottom < -48) { setActive('#'+$el.attr('id')) return false; } }); }); } }); ","$(function() { var $documentNav = $('.document-nav'); if($documentNav.length) { var targets = [] , $window = $(window); $documentNav.find('a').each(function() { targets.push( $($(this).attr('href')) ) }); function setActive($current) { var $parent = $current.closest('li') , $parentParent = $parent.parent().closest('li'); $documentNav.find('.current, .active').removeClass('current active') $current.addClass('current') if($parentParent.length) { $parentParent.addClass('active') } else { $parent.addClass('active') } } // HASH change, update menu // ======================== $window.on('hashchange', function() { setTimeout(function() { setActive($documentNav.find('[href='+location.hash+']')) }, 1); }); // Scroll, update menu // =================== $window.on('scroll', function() { var scrollTop = $window.scrollTop(); $.each( targets, function($index, $el) { var sectionBottom = (targets[$index+1] && targets[$index+1].offset().top - 1) || $window.height() if ($el.length && scrollTop - sectionBottom < -48) { setActive($documentNav.find('[href=#'+$el.attr('id')+']')) return false; } }); }); } }); " "Attach mouse coordinate update to ""mousemove"" event","var GameInputFactory = function (canvas) { var pressedKeys = {}; var mousePos = {}; function setKey(event, status) { var code = event.keyCode; var key; switch(code) { case 32: key = 'SPACE'; break; case 37: key = 'LEFT'; break; case 38: key = 'UP'; break; case 39: key = 'RIGHT'; break; case 40: key = 'DOWN'; break; default: // Convert ASCII codes to letters key = String.fromCharCode(event.keyCode); } pressedKeys[key] = status; } document.addEventListener('keydown', function(e) { setKey(e, true); }); document.addEventListener('keyup', function(e) { setKey(e, false); }); canvas.addEventListener('mousemove', function (e) { // Scale position to game coordinate system mousePos.x = e.offsetX / e.target.width * GameState.WIDTH; mousePos.y = e.offsetY / e.target.height * GameState.HEIGHT; }); canvas.addEventListener('mousedown', function(e) { pressedKeys['MOUSE'] = true; }); canvas.addEventListener('mouseup', function(e) { pressedKeys['MOUSE'] = false; }); window.addEventListener('blur', function() { pressedKeys = {}; }); function isDown(key) { return pressedKeys[key]; } function getMousePos() { return mousePos; } return { isDown: isDown, getMousePos: getMousePos }; }; ","var GameInputFactory = function (canvas) { var pressedKeys = {}; var mousePos = {}; function setKey(event, status) { var code = event.keyCode; var key; switch(code) { case 32: key = 'SPACE'; break; case 37: key = 'LEFT'; break; case 38: key = 'UP'; break; case 39: key = 'RIGHT'; break; case 40: key = 'DOWN'; break; default: // Convert ASCII codes to letters key = String.fromCharCode(event.keyCode); } pressedKeys[key] = status; } document.addEventListener('keydown', function(e) { setKey(e, true); }); document.addEventListener('keyup', function(e) { setKey(e, false); }); canvas.addEventListener('mousedown', function(e) { // Scale position to game coordinate system mousePos.x = e.offsetX / e.target.width * GameState.WIDTH; mousePos.y = e.offsetY / e.target.height * GameState.HEIGHT; pressedKeys['MOUSE'] = true; }); canvas.addEventListener('mouseup', function(e) { pressedKeys['MOUSE'] = false; }); window.addEventListener('blur', function() { pressedKeys = {}; }); function isDown(key) { return pressedKeys[key]; } function getMousePos() { return mousePos; } return { isDown: isDown, getMousePos: getMousePos }; }; " "Move execution code to main() Signed-off-by: Zoran Zaric <d7dacae2c968388960bf8970080a980ed5c5dcb7@zoranzaric.de>","#!/usr/bin/env python import sys, os MAX_PACKSIZE = 1024*1024*1024 def usage(): sys.stderr.write(""usage: kurt.py <path>\n"") def get_files(path): files = os.listdir(path) for file in sorted(files): file_path = os.path.join(path, file) file_stats = os.stat(file_path) yield (file_path, file_stats.st_size) def get_packs(path): singles = [] packsize = 0 paths = [] for path, size in get_files(path): if packsize + size <= MAX_PACKSIZE: paths.append(path) packsize += size elif size > MAX_PACKSIZE: singles.append(([path], size)) else: yield (paths, packsize) packsize = 0 paths = [] for single in singles: yield single singles = [] if len(paths) > 0: yield (paths, packsize) def main(): if len(sys.argv) != 2: usage() sys.exit(1) path = sys.argv[1] #TODO check if path exists for index, pack in enumerate(get_packs(path)): paths, packsize = pack print ""Pack %d (%dB)"" % (index, packsize) for path in paths: print "" %s"" % path if __name__ == ""__main__"": main() ","#!/usr/bin/env python import sys, os MAX_PACKSIZE = 1024*1024*1024 def usage(): sys.stderr.write(""usage: kurt.py <path>\n"") def get_files(path): files = os.listdir(path) for file in sorted(files): file_path = os.path.join(path, file) file_stats = os.stat(file_path) yield (file_path, file_stats.st_size) def get_packs(path): singles = [] packsize = 0 paths = [] for path, size in get_files(path): if packsize + size <= MAX_PACKSIZE: paths.append(path) packsize += size elif size > MAX_PACKSIZE: singles.append(([path], size)) else: yield (paths, packsize) packsize = 0 paths = [] for single in singles: yield single singles = [] if len(paths) > 0: yield (paths, packsize) if len(sys.argv) != 2: usage() sys.exit(1) path = sys.argv[1] #TODO check if path exists for index, pack in enumerate(get_packs(path)): paths, packsize = pack print ""Pack %d (%dB)"" % (index, packsize) for path in paths: print "" %s"" % path " Fix parsing of css result line number,"<?php namespace SimplyTestable\WebClientBundle\Services\TaskOutput\ResultParser; use SimplyTestable\WebClientBundle\Model\TaskOutput\Result; use SimplyTestable\WebClientBundle\Model\TaskOutput\CssTextFileMessage; use SimplyTestable\WebClientBundle\Entity\Task\Output; class CssValidationResultParser extends ResultParser { /** * @return Result */ public function getResult() { $result = new Result(); $rawOutputArray = json_decode($this->getOutput()->getContent()); if (count($rawOutputArray) === 0) { return $result; } foreach ($rawOutputArray as $rawMessageObject) { $result->addMessage($this->getMessageFromOutput($rawMessageObject)); } return $result; } /** * * @param \stdClass $rawMessageObject * @return \SimplyTestable\WebClientBundle\Model\TaskOutput\CssTextFileMessage */ private function getMessageFromOutput(\stdClass $rawMessageObject) { $propertyToMethodMap = array( 'context' => 'setContext', 'line_number' => 'setLineNumber', 'message' => 'setMessage', 'ref' => 'setRef' ); $message = new CssTextFileMessage(); $message->setType($rawMessageObject->type); foreach ($propertyToMethodMap as $property => $methodName) { if (isset($rawMessageObject->$property)) { $message->$methodName($rawMessageObject->$property); } } return $message; } }","<?php namespace SimplyTestable\WebClientBundle\Services\TaskOutput\ResultParser; use SimplyTestable\WebClientBundle\Model\TaskOutput\Result; use SimplyTestable\WebClientBundle\Model\TaskOutput\CssTextFileMessage; use SimplyTestable\WebClientBundle\Entity\Task\Output; class CssValidationResultParser extends ResultParser { /** * @return Result */ public function getResult() { $result = new Result(); $rawOutputArray = json_decode($this->getOutput()->getContent()); if (count($rawOutputArray) === 0) { return $result; } foreach ($rawOutputArray as $rawMessageObject) { $result->addMessage($this->getMessageFromOutput($rawMessageObject)); } return $result; } /** * * @param \stdClass $rawMessageObject * @return \SimplyTestable\WebClientBundle\Model\TaskOutput\CssTextFileMessage */ private function getMessageFromOutput(\stdClass $rawMessageObject) { $propertyToMethodMap = array( 'context' => 'setContext', 'lineNumber' => 'setLineNumber', 'message' => 'setMessage', 'ref' => 'setRef' ); $message = new CssTextFileMessage(); $message->setType($rawMessageObject->type); foreach ($propertyToMethodMap as $property => $methodName) { if (isset($rawMessageObject->$property)) { $message->$methodName($rawMessageObject->$property); } } return $message; } }" Improve wallet check in state transitions,"function AppRun(AppConstants, $rootScope, $timeout, Wallet, Alert, $transitions) { 'ngInject'; const publicStates = [ ""app.home"", ""app.login"", ""app.signup"", ""app.faq"", ""app.trezor"", ""app.offlineTransactionHome"", ""app.offlineTransactionCreate"", ""app.offlineTransactionSend"" ]; // Change page title based on state $transitions.onSuccess({ to: true }, (transition) => { $rootScope.setPageTitle(transition.router.globals.current.title); // Enable tooltips globally $timeout( function() { $('[data-toggle=""tooltip""]').tooltip() }); }); // Check if a wallet is loaded before accessing private states $transitions.onStart({ to: (state) => { for (let i = 0; i < publicStates.length; i++) { if (publicStates[i] === state.name) return false; } return true; } }, (transition) => { if (!Wallet.current) { Alert.noWalletLoaded(); return transition.router.stateService.target('app.home'); } }); // Helper method for setting the page's title $rootScope.setPageTitle = (title) => { $rootScope.pageTitle = ''; if (title) { $rootScope.pageTitle += title; $rootScope.pageTitle += ' \u2014 '; } $rootScope.pageTitle += AppConstants.appName; }; } export default AppRun; ","function AppRun(AppConstants, $rootScope, $timeout, Wallet, Alert, $transitions) { 'ngInject'; // Change page title based on state $transitions.onSuccess({ to: true }, (transition) => { $rootScope.setPageTitle(transition.router.globals.current.title); // Enable tooltips globally $timeout( function() { $('[data-toggle=""tooltip""]').tooltip() }); }); // Check if a wallet is loaded before accessing private states $transitions.onStart({ to: (state) => { return (state.name !== 'app.home') && (state.name !== 'app.login') && (state.name !== 'app.signup') && (state.name !== 'app.faq') && (state.name !== 'app.trezor'); } }, (transition) => { if (!Wallet.current) { Alert.noWalletLoaded(); return transition.router.stateService.target('app.home'); } }); // Helper method for setting the page's title $rootScope.setPageTitle = (title) => { $rootScope.pageTitle = ''; if (title) { $rootScope.pageTitle += title; $rootScope.pageTitle += ' \u2014 '; } $rootScope.pageTitle += AppConstants.appName; }; } export default AppRun; " Update our container test case,"# This file is part of Moksha. # Copyright (C) 2008-2009 Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from tw.api import Widget from moksha.widgets.container import MokshaContainer class TestContainer: def setUp(self): self.w = MokshaContainer('test') def test_render_widget(self): assert 'Moksha Container' in self.w() def test_widget_content(self): """""" Ensure we can render a container with another widget """""" class MyWidget(Widget): template = """""" Hello World! """""" assert 'Hello World!' in self.w(content=MyWidget('mywidget')) def test_container_classes(self): rendered = self.w(**dict(skin3=True, stikynote=True, draggable=True, resizable=True)) assert 'class=""containerPlus draggable resizable""' in rendered, rendered ","# This file is part of Moksha. # Copyright (C) 2008-2009 Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from tw.api import Widget from moksha.widgets.container import MokshaContainer class TestContainer: def setUp(self): self.w = MokshaContainer('test') def test_render_widget(self): assert '<div id=""test"" ' in self.w() def test_widget_content(self): """""" Ensure we can render a container with another widget """""" class MyWidget(Widget): template = """""" Hello World! """""" assert 'Hello World!' in self.w(content=MyWidget('mywidget')) def test_container_classes(self): rendered = self.w(**dict(skin3=True, stikynote=True, draggable=True, resizable=True)) assert 'class=""containerPlus draggable resizable""' in rendered, rendered " "Revert ""added link to error fix"" This reverts commit 0086364d111a76710ddf05a056b8d369fada1162.","//$(document).ready(function(){ var ready = function(){ $(""#what"").on('click', function(e){ e.preventDefault(); $('html, body').stop().animate({ scrollTop: $("".block-2"").offset().top }, 1000); }); $(""#how"").on('click', function(e){ e.preventDefault(); $('html, body').stop().animate({ scrollTop: $("".block-3"").offset().top }, 1000); }); $(""#signup"").on('click', function(e){ e.preventDefault(); $('html, body').stop().animate({ scrollTop: $("".block-4"").offset().top }, 1000); }); $(window).scroll(function(){ var docScroll = $(window).scrollTop(), almostBottom = $("".block-4"").offset().top - 100; if(docScroll >= almostBottom) { $("".back-to-top"").fadeIn(200); } else { $("".back-to-top"").fadeOut(200); } }); $("".back-to-top"").on('click', function(e){ e.preventDefault(); $('html, body').stop().animate({ scrollTop: 0 }, 1000); }); }; $(document).ready(ready); $(document).on('turbolinks:load', ready); ","//$(document).ready(function(){ var ready = function(){ $(""#what"").on('click', function(e){ e.preventDefault(); $('html, body').stop().animate({ scrollTop: $("".block-2"").offset().top }, 1000); }); $(""#how"").on('click', function(e){ e.preventDefault(); $('html, body').stop().animate({ scrollTop: $("".block-3"").offset().top }, 1000); }); $(""#signup"").on('click', function(e){ e.preventDefault(); $('html, body').stop().animate({ scrollTop: $("".block-4"").offset().top }, 1000); }); $(window).scroll(function(){ var docScroll = $(window).scrollTop(), almostBottom = $("".block-4"").offset().top - 100; if(docScroll >= almostBottom) { $("".back-to-top"").fadeIn(200); } else { $("".back-to-top"").fadeOut(200); } }); $("".back-to-top"").on('click', function(e){ e.preventDefault(); $('html, body').stop().animate({ scrollTop: 0 }, 1000); }); }; // http://stackoverflow.com/questions/17600093/rails-javascript-not-loading-after-clicking-through-link-to-helper#17600195 $(document).ready(ready); $(document).on('turbolinks:load', ready); " Fix recursive call for sortNum filter," 'use strict'; /** * @ngdoc filter * @name SubSnoopApp.filter:sortnum * @function * @description * # sortnum * Filter in the SubSnoopApp. */ angular.module('SubSnoopApp') .filter('sortNum', ['$filter', function ($filter) { var sort = function(num1, num2, a, b, reverse, secondary) { var val1, val2; if (!(secondary)) { secondary = 'alpha'; } if (reverse) { val1 = 1; val2 = -1; } else { val1 = -1; val2 = 1; } if (num1 < num2) { return val1; } else if (num1 > num2) { return val2; } else { if (secondary === 'alpha') { if (typeof a !== 'string' && typeof b !== 'string') { a = a.subreddit; b = b.subreddit; } return $filter('sortAlpha')(a, b); } else if (secondary === 'date') { num1 = moment(a.created_utc*1000); num2 = moment(b.created_utc*1000); return sort(num1, num2, a, b, true, 'alpha'); } } } return function (num1, num2, a, b, reverse, secondary) { return sort(num1, num2, a, b, reverse, secondary); }; }]);"," 'use strict'; /** * @ngdoc filter * @name SubSnoopApp.filter:sortnum * @function * @description * # sortnum * Filter in the SubSnoopApp. */ angular.module('SubSnoopApp') .filter('sortNum', ['$filter', function ($filter) { return function (num1, num2, a, b, reverse, secondary) { var val1, val2; if (!(secondary)) { secondary = 'alpha'; } if (reverse) { val1 = 1; val2 = -1; } else { val1 = -1; val2 = 1; } if (num1 < num2) { return val1; } else if (num1 > num2) { return val2; } else { if (secondary === 'alpha') { if (typeof a !== 'string' && typeof b !== 'string') { a = a.subreddit; b = b.subreddit; } return $filter('sortAlpha')(a, b); } else if (secondary === 'date') { num1 = moment(a.created_utc*1000); num2 = moment(b.created_utc*1000); return sort(num1, num2, a, b, true, 'alpha'); } } }; }]);" Fix a derp on argparse,"__author__ = 'admiral0' from . import * from .Exceptions import JsonNotValid import argparse import os.path as path def is_mod_repo(x): if path.isdir(x): return x raise argparse.ArgumentTypeError(x + ' is not a Directory') def validate(args): try: repo = ModRepository(args.mod_repo) for m in repo.list_mods().values(): try: Mod(m) except JsonNotValid as e: print(str(e)) except JsonNotValid as e: print(str(e)) def list_mods(args): repo = ModManager(args.mod_repo) for mod in repo.mods.values(): print(mod.slug + ' ') print(','.join(mod.data['versions'].keys())) actions = { 'validate': validate, 'list': list_mods } parser = argparse.ArgumentParser(description='TechnicAntani ModRepo Tools') parser.add_argument('mod_repo', metavar='ModRepoPath', type=is_mod_repo, help='The path to Mod Repo directory', default='.') parser.add_argument('-a', dest='action', type=str, default='validate', choices=actions.keys(), help='Action to perform') def init(): args = parser.parse_args() actions[args.action](args)","__author__ = 'admiral0' from . import * from .Exceptions import JsonNotValid import argparse import os.path as path def is_mod_repo(x): if path.isdir(x): return x raise argparse.ArgumentTypeError(x + ' is not a Directory') def validate(args): try: repo = ModRepository(args.mod_repo) for m in repo.list_mods().values(): try: Mod(m) except JsonNotValid as e: print(str(e)) except JsonNotValid as e: print(str(e)) def list_mods(args): repo = ModManager(args.mod_repo) for mod in repo.mods.values(): print(mod.slug + ' ') print(','.join(mod.data['versions'].keys())) actions = { 'validate': validate, 'list': list_mods } parser = argparse.ArgumentParser(description='TechnicAntani ModRepo Tools') parser.add_argument('mod_repo', metavar='ModRepoPath', type=is_mod_repo, help='The path to Mod Repo directory', default='.') parser.add_argument('-a', dest='action', type=str, default='validate', choices=[actions.keys()], help='Action to perform') def init(): args = parser.parse_args() actions[args.action](args)" Fix generic message command to use new conversation methods.,"<?php /** * This file is part of the TelegramBot package. * * (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Longman\TelegramBot\Commands\SystemCommands; use Longman\TelegramBot\Conversation; use Longman\TelegramBot\Request; use Longman\TelegramBot\Commands\SystemCommand; /** * Generic message command */ class GenericmessageCommand extends SystemCommand { /**#@+ * {@inheritdoc} */ protected $name = 'Genericmessage'; protected $description = 'Handle generic message'; protected $version = '1.0.2'; protected $need_mysql = true; /**#@-*/ /** * Execution if MySQL is required but not available * * @return boolean */ public function executeNoDB() { //Do nothing return Request::emptyResponse(); } /** * Execute command * * @return boolean */ public function execute() { //If a conversation is busy, execute the conversation command after handling the message $conversation = new Conversation( $this->getMessage()->getChat()->getId(), $this->getMessage()->getFrom()->getId() ); //Fetch conversation command if it exists and execute it if ($conversation->exists() && ($command = $conversation->getCommand())) { return $this->telegram->executeCommand($command, $this->update); } return Request::emptyResponse(); } } ","<?php /** * This file is part of the TelegramBot package. * * (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Longman\TelegramBot\Commands\SystemCommands; use Longman\TelegramBot\Conversation; use Longman\TelegramBot\Request; use Longman\TelegramBot\Commands\SystemCommand; /** * Generic message command */ class GenericmessageCommand extends SystemCommand { /**#@+ * {@inheritdoc} */ protected $name = 'Genericmessage'; protected $description = 'Handle generic message'; protected $version = '1.0.1'; protected $need_mysql = true; /**#@-*/ /** * Execution if MySQL is required but not available * * @return boolean */ public function executeNoDB() { //Do nothing return Request::emptyResponse(); } /** * Execute command * * @return boolean */ public function execute() { //System command, fetch command to execute if conversation exist $message = $this->getMessage(); $chat_id = $message->getChat()->getId(); $user_id = $message->getFrom()->getId(); //Fetch Conversation if exist $command = (new Conversation($user_id, $chat_id))->getConversationCommand(); if (! is_null($command)) { return $this->telegram->executeCommand($command, $this->update); } return Request::emptyResponse(); } } " Use str instead of repr,"class Database(object): def __init__(self, channels): self.userdb = {} for i in channels: self.userdb[i] = {} def removeEntry(self, event, nick): try: del self.userdb[event.target][nick] except KeyError: for i in self.userdb[event.target].values(): if i['host'] == event.source.host: del self.userdb[event.target][i['hostmask'].split(""!"")[0]] break def addEntry(self, channel, nick, hostmask, host, account): self.userdb[channel][nick] = { 'hostmask': hostmask, 'host': host, 'account': account } def __getitem__(self, key): return self.userdb[key] def __delitem__(self, key): del self.userdb[key] def __setitem__(self, key, value): self.userdb[key] = value def __str__(self): return str(self.userdb) def get(self, key, default=None): try: return self.userdb[key] except KeyError: return default def keys(self): return self.userdb.keys() def values(self): return self.userdb.values() ","class Database(object): def __init__(self, channels): self.userdb = {} for i in channels: self.userdb[i] = {} def removeEntry(self, event, nick): try: del self.userdb[event.target][nick] except KeyError: for i in self.userdb[event.target].values(): if i['host'] == event.source.host: del self.userdb[event.target][i['hostmask'].split(""!"")[0]] break def addEntry(self, channel, nick, hostmask, host, account): self.userdb[channel][nick] = { 'hostmask': hostmask, 'host': host, 'account': account } def __getitem__(self, key): return self.userdb[key] def __delitem__(self, key): del self.userdb[key] def __setitem__(self, key, value): self.userdb[key] = value def __str__(self): return repr(self.userdb) def get(self, key, default=None): try: return self.userdb[key] except KeyError: return default def keys(self): return self.userdb.keys() def values(self): return self.userdb.values() " Add comment explaining weird map behavior,"import Polymer from '../../polymer'; require('../../components/ha-label-badge'); /* Leaflet clones this element before adding it to the map. This messes up our Poylmer object and we lose the reference to the `hass` object. That's why we refer here to window.hass instead of the hass property. */ export default new Polymer({ is: 'ha-entity-marker', properties: { hass: { type: Object, }, entityId: { type: String, value: '', reflectToAttribute: true, }, state: { type: Object, computed: 'computeState(entityId)', }, icon: { type: Object, computed: 'computeIcon(state)', }, image: { type: Object, computed: 'computeImage(state)', }, value: { type: String, computed: 'computeValue(state)', }, }, listeners: { tap: 'badgeTap', }, badgeTap(ev) { ev.stopPropagation(); if (this.entityId) { this.async(() => window.hass.moreInfoActions.selectEntity(this.entityId), 1); } }, computeState(entityId) { return entityId && window.hass.reactor.evaluate(window.hass.entityGetters.byId(entityId)); }, computeIcon(state) { return !state && 'home'; }, computeImage(state) { return state && state.attributes.entity_picture; }, computeValue(state) { return state && state.entityDisplay.split(' ').map(part => part.substr(0, 1)).join(''); }, }); ","import Polymer from '../../polymer'; require('../../components/ha-label-badge'); export default new Polymer({ is: 'ha-entity-marker', properties: { hass: { type: Object, }, entityId: { type: String, value: '', reflectToAttribute: true, }, state: { type: Object, computed: 'computeState(entityId)', }, icon: { type: Object, computed: 'computeIcon(state)', }, image: { type: Object, computed: 'computeImage(state)', }, value: { type: String, computed: 'computeValue(state)', }, }, listeners: { tap: 'badgeTap', }, badgeTap(ev) { ev.stopPropagation(); if (this.entityId) { this.async(() => window.hass.moreInfoActions.selectEntity(this.entityId), 1); } }, computeState(entityId) { return entityId && window.hass.reactor.evaluate(window.hass.entityGetters.byId(entityId)); }, computeIcon(state) { return !state && 'home'; }, computeImage(state) { return state && state.attributes.entity_picture; }, computeValue(state) { return state && state.entityDisplay.split(' ').map(part => part.substr(0, 1)).join(''); }, }); " "Revert ""Add a babel task to watch which works"" This reverts commit 9b22494b461448d9e75e153610c1629d8e455074.","module.exports = function(grunt) { grunt.initConfig({ pkgFile: 'package.json', clean: ['build'], babel: { options: { sourceMap: false }, dist: { src: 'index.js', dest: 'build/index.js' } }, watch: { dist: { files: 'index.js', task: ['babel:dist'] } }, eslint: { options: { parser: 'babel-eslint' }, target: ['index.js'] }, contributors: { options: { commitMessage: 'update contributors' } }, bump: { options: { commitMessage: 'v%VERSION%', pushTo: 'upstream' } } }); require('load-grunt-tasks')(grunt); grunt.registerTask('default', ['build']); grunt.registerTask('build', 'Build wdio-sync', function() { grunt.task.run([ 'eslint', 'clean', 'babel' ]); }); grunt.registerTask('release', 'Bump and tag version', function(type) { grunt.task.run([ 'build', 'contributors', 'bump:' + (type || 'patch') ]); }); }; ","module.exports = function(grunt) { grunt.initConfig({ pkgFile: 'package.json', clean: ['build'], babel: { options: { sourceMap: false }, dist: { files: [{ expand: true, cwd: './lib', src: 'index.js', dest: 'build/index.js', ext: '.js' }] } }, watch: { dist: { files: 'index.js', task: ['babel:dist'] } }, eslint: { options: { parser: 'babel-eslint' }, target: ['index.js'] }, contributors: { options: { commitMessage: 'update contributors' } }, bump: { options: { commitMessage: 'v%VERSION%', pushTo: 'upstream' } } }); require('load-grunt-tasks')(grunt); grunt.registerTask('default', ['build']); grunt.registerTask('build', 'Build wdio-sync', function() { grunt.task.run([ 'eslint', 'clean', 'babel' ]); }); grunt.registerTask('release', 'Bump and tag version', function(type) { grunt.task.run([ 'build', 'contributors', 'bump:' + (type || 'patch') ]); }); }; " "Bring back dependency for web-security services to MDS schema browser Change-Id: I71f289f9201bfad22d67e7d77d6b7065b53436a3","(function () { 'use strict'; var mds = angular.module('mds', [ 'motech-dashboard', 'mds.services', 'webSecurity.services', 'mds.controllers', 'mds.directives', 'mds.utils', 'ui.directives']); $.ajax({ url: '../mds/available/mdsTabs', success: function(data) { mds.constant('AVAILABLE_TABS', data); }, async: false }); mds.run(function ($rootScope, AVAILABLE_TABS) { $rootScope.AVAILABLE_TABS = AVAILABLE_TABS; }); mds.config(function ($routeProvider, AVAILABLE_TABS) { $routeProvider .when('/mds/dataBrowser/:entityId', { templateUrl: '../mds/resources/partials/dataBrowser.html', controller: 'MdsDataBrowserCtrl' }) .when('/mds/dataBrowser/:entityId/:moduleName', { templateUrl: '../mds/resources/partials/dataBrowser.html', controller: 'MdsDataBrowserCtrl' }) .when('/mds/dataBrowser/:entityId/:instanceId/:moduleName', { templateUrl: '../mds/resources/partials/dataBrowser.html', controller: 'MdsDataBrowserCtrl' }); angular.forEach(AVAILABLE_TABS, function (tab) { $routeProvider.when( '/mds/{0}'.format(tab), { templateUrl: '../mds/resources/partials/{0}.html'.format(tab), controller: 'Mds{0}Ctrl'.format(tab.capitalize()) } ); }); }); }()); ","(function () { 'use strict'; var mds = angular.module('mds', [ 'motech-dashboard', 'mds.services', 'mds.controllers', 'mds.directives', 'mds.utils', 'ui.directives']); $.ajax({ url: '../mds/available/mdsTabs', success: function(data) { mds.constant('AVAILABLE_TABS', data); }, async: false }); mds.run(function ($rootScope, AVAILABLE_TABS) { $rootScope.AVAILABLE_TABS = AVAILABLE_TABS; }); mds.config(function ($routeProvider, AVAILABLE_TABS) { $routeProvider .when('/mds/dataBrowser/:entityId', { templateUrl: '../mds/resources/partials/dataBrowser.html', controller: 'MdsDataBrowserCtrl' }) .when('/mds/dataBrowser/:entityId/:moduleName', { templateUrl: '../mds/resources/partials/dataBrowser.html', controller: 'MdsDataBrowserCtrl' }) .when('/mds/dataBrowser/:entityId/:instanceId/:moduleName', { templateUrl: '../mds/resources/partials/dataBrowser.html', controller: 'MdsDataBrowserCtrl' }); angular.forEach(AVAILABLE_TABS, function (tab) { $routeProvider.when( '/mds/{0}'.format(tab), { templateUrl: '../mds/resources/partials/{0}.html'.format(tab), controller: 'Mds{0}Ctrl'.format(tab.capitalize()) } ); }); }); }()); " Fix typo causing no name to be serialized for article categories,"<?php namespace rmatil\CmsBundle\Mapper; use rmatil\CmsBundle\Entity\ArticleCategory; use rmatil\CmsBundle\Exception\MapperException; use rmatil\CmsBundle\Model\ArticleCategoryDTO; class ArticleCategoryMapper extends AbstractMapper { public function entityToDto($articleCategory) { if (null === $articleCategory) { return null; } if ( ! ($articleCategory instanceof ArticleCategory)) { throw new MapperException(sprintf('Required object of type ""%s"" but got ""%s""', ArticleCategory::class, get_class($articleCategory))); } $articleCategoryDto = new ArticleCategoryDTO(); $articleCategoryDto->setId($articleCategory->getId()); $articleCategoryDto->setName($articleCategory->getName()); return $articleCategoryDto; } public function dtoToEntity($articleCategoryDto) { if (null === $articleCategoryDto) { return null; } if ( ! ($articleCategoryDto instanceof ArticleCategoryDTO)) { throw new MapperException(sprintf('Required object of type ""%s"" but got ""%s""', ArticleCategoryDTO::class, get_class($articleCategoryDto))); } $articleCategory = new ArticleCategory(); $articleCategory->setId($articleCategoryDto->getId()); $articleCategory->setName($articleCategoryDto->getName()); return $articleCategory; } } ","<?php namespace rmatil\CmsBundle\Mapper; use rmatil\CmsBundle\Entity\ArticleCategory; use rmatil\CmsBundle\Exception\MapperException; use rmatil\CmsBundle\Model\ArticleCategoryDTO; class ArticleCategoryMapper extends AbstractMapper { public function entityToDto($articleCategory) { if (null === $articleCategory) { return null; } if ( ! ($articleCategory instanceof ArticleCategory)) { throw new MapperException(sprintf('Required object of type ""%s"" but got ""%s""', ArticleCategory::class, get_class($articleCategory))); } $articleCategoryDto = new ArticleCategoryDTO(); $articleCategoryDto->setId($articleCategory->getId()); $articleCategoryDto->setName($articleCategoryDto->getName()); return $articleCategoryDto; } public function dtoToEntity($articleCategoryDto) { if (null === $articleCategoryDto) { return null; } if ( ! ($articleCategoryDto instanceof ArticleCategoryDTO)) { throw new MapperException(sprintf('Required object of type ""%s"" but got ""%s""', ArticleCategoryDTO::class, get_class($articleCategoryDto))); } $articleCategory = new ArticleCategory(); $articleCategory->setId($articleCategoryDto->getId()); $articleCategory->setName($articleCategoryDto->getName()); return $articleCategory; } } " Fix single-argument invocations that were parsing as arrays spuriously.,"var Replayer = function(obj) { this.record = []; var self = this; for (var k in obj) { if (typeof obj[k] === 'function') { // Close on k. (function () { var fnName = k; self[fnName] = function() { var args = Array.prototype.slice.call(arguments); self.record.push([ fnName, args ]); var result; if (args.length == 1) { result = obj[fnName].call(obj, args[0]); } else { result = obj[fnName].call(obj, args); } return result === obj ? self : result; }; })(); } } }; Replayer.prototype.replay = function(newSelf) { var results = []; for (var idx in this.record) { var curMethod = this.record[idx][0]; var curArgs = this.record[idx][1]; var curResult; if (curArgs.length == 1) { curResult = newSelf[curMethod].call(newSelf, curArgs[0]); } else { curResult = newSelf[curMethod].call(newSelf, curArgs); } results.push(curResult); } return results; }; module.exports.watch = function(obj) { return new Replayer(obj); }; ","var Replayer = function(obj) { this.record = []; var self = this; for (var k in obj) { if (typeof obj[k] === 'function') { // Close on k. (function () { var fnName = k; self[fnName] = function() { var args = Array.prototype.slice.call(arguments); self.record.push([ fnName, args ]); var result = obj[fnName].call(obj, args); console.log('Recording ' + fnName + ': result = ' + JSON.stringify(result)); return result === obj ? self : result; }; })(); } } }; Replayer.prototype.replay = function(newSelf) { var results = []; for (var idx in this.record) { var curMethod = this.record[idx][0]; var curArgs = this.record[idx][1]; var curResult = newSelf[curMethod].call(newSelf, curArgs); console.log('Replaying ' + curMethod + ': result = ' + JSON.stringify(curResult)); results.push(curResult); } return results; }; module.exports.watch = function(obj) { return new Replayer(obj); }; " Implement simple throttling for preview iframe refreshes.,"(function(window, $) { var document = window.document; var iframe_name = 'live_preview'; // Name (and id) to give to the preview iframe var preview_url = 'preview'; // Relative url to send the POST data to var keypress_delay = 400; // Number of milliseconds to wait before acting on keypress var latest_keypress = new Date(); $(document).ready(function() { var initial_url = $('.viewsitelink').attr('href'); var preview = '<div id=""preview_container""><iframe src=""' + initial_url + '"" id=""' + iframe_name + '"" name=""' + iframe_name + '""></iframe></div>'; var form = $('#cmspage_form'); // Insert the iframe into the document: $('#id_content').after(preview); // Set the main form's target to the preview iframe, and POST to our // preview url to update the iframe's content. $('#id_content').keyup(function(e) { var timestamp = new Date(); latest_keypress = timestamp; setTimeout(function() { // If no keypresses have occurred since this one, refresh the // iframe using the main form's data: var another_key_was_pressed = (latest_keypress > timestamp); if (!another_key_was_pressed) { form.attr('target', iframe_name) .attr('action', preview_url) .submit() .attr('target', '') // Reset target and action after submitting .attr('action', ''); } }, keypress_delay); }); }) }(window, django.jQuery)); ","(function(window, $) { var document = window.document; var preview_iframe; var iframe_name = 'live_preview'; // Name (and id) to give to the preview iframe var preview_url = 'preview'; // Relative url to send the POST data to var keypress_delay = 200; $(document).ready(function() { var initial_url = $('.viewsitelink').attr('href'); var preview = '<div id=""preview_container""><iframe src=""' + initial_url + '"" id=""' + iframe_name + '"" name=""' + iframe_name + '""></iframe></div>'; var form = $('#cmspage_form'); // Insert the iframe into the document: $('#id_content').after(preview); preview_iframe = $('#live_preview'); // Set the main form's target to the preview iframe, and POST to our // preview url to update the iframe's content. // TODO: throttle updates $('#id_content').keyup(function(e) { setTimeout(function() { form.attr('target', iframe_name) .attr('action', preview_url) .submit() .attr('target', '') // Reset target and action after submitting .attr('action', ''); }, keypress_delay); }); }) }(window, django.jQuery)); " "Add label to be translated for form For the moment the form is not translated.","<?php namespace Lexik\Bundle\TranslationBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; /** * TransUnit form type. * * @author Cédric Girard <c.girard@lexik.fr> */ class TransUnitType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('key', 'text', array( 'label' => 'translations.key', )); $builder->add('domain', 'choice', array( 'label' => 'translations.domain', 'choices' => array_combine($options['domains'], $options['domains']), )); $builder->add('translations', 'collection', array( 'type' => 'lxk_translation', 'label' => 'translations.page_title', 'required' => false, 'options' => array( 'data_class' => $options['translation_class'], ) )); } /** * {@inheritdoc} */ public function setDefaultOptions(OptionsResolverInterface $resolver) { parent::setDefaultOptions($resolver); $resolver->setDefaults(array( 'data_class' => null, 'domains' => array('messages'), 'translation_class' => null, )); } /** * {@inheritdoc} */ public function getName() { return 'trans_unit'; } } ","<?php namespace Lexik\Bundle\TranslationBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; /** * TransUnit form type. * * @author Cédric Girard <c.girard@lexik.fr> */ class TransUnitType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('key'); $builder->add('domain', 'choice', array( 'choices' => array_combine($options['domains'], $options['domains']), )); $builder->add('translations', 'collection', array( 'type' => new TranslationType(), 'required' => false, 'options' => array( 'data_class' => $options['translation_class'], ) )); } /** * {@inheritdoc} */ public function setDefaultOptions(OptionsResolverInterface $resolver) { parent::setDefaultOptions($resolver); $resolver->setDefaults(array( 'data_class' => null, 'domains' => array('messages'), 'translation_class' => null, )); } /** * {@inheritdoc} */ public function getName() { return 'trans_unit'; } }" Create a new image element instead of changing the image src. This is a potential fix to a memory issue in Chromium.,"$(function() { var $body = $('body'), $caption = $('#caption'), $img = $('#main-image'); var getImage = (function() { var index = 0, images = [], lastCall = Date.now(), WAIT_TIME = 1800000; // 30 minutes function updateImages() { $.getJSON('media') .done(function(data) { index = 0; images = data; lastCall = Date.now(); }) .fail(function(err) { console.log(err); }); } updateImages(); setInterval(updateImages, WAIT_TIME); return function getImage() { var image; if (images.length) { image = images[index]; index = (index + 1) % images.length; } return image; }; })(); function changeImage() { var caption, duration = 5000, image = getImage(); if (image) { caption = image.caption || ''; duration = image.duration || duration; $body.fadeOut(250, function() { $caption.text(caption); $('img').remove(); var img = $('<img id=""main-image"" class=""main-image"">'); img.attr('src', 'img/' + image.filename); img.one('load', function() { $body.fadeIn(250); }); img.prependTo('body'); /* $img.one('load', function() { $body.fadeIn(250); }).attr('src', 'img/' + image.filename); */ }); } setTimeout(changeImage, duration); } changeImage(); });","$(function() { var $body = $('body'), $caption = $('#caption'), $img = $('#main-image'); var getImage = (function() { var index = 0, images = [], lastCall = Date.now(), WAIT_TIME = 1800000; // 30 minutes function updateImages() { $.getJSON('media') .done(function(data) { index = 0; images = data; lastCall = Date.now(); }) .fail(function(err) { console.log(err); }); } updateImages(); setInterval(updateImages, WAIT_TIME); return function getImage() { var image; if (images.length) { image = images[index]; index = (index + 1) % images.length; } return image; }; })(); function changeImage() { var caption, duration = 5000, image = getImage(); if (image) { caption = image.caption || ''; duration = image.duration || duration; $body.fadeOut(250, function() { $caption.text(caption); $img.one('load', function() { $body.fadeIn(250); }).attr('src', 'img/' + image.filename); }); } setTimeout(changeImage, duration); } changeImage(); });" Set number of gallery images per page to 54,"<?php namespace App\FrontModule\Presenters; use App\Model\Entities; use App\Model\Repositories; final class GalleryPresenter extends SingleUserContentPresenter { /** @var Repositories\ImageRepository @inject */ public $imageRepository; /** @var Entities\ImageEntity[] */ private $images; /** * @param string $tagSlug */ public function actionDefault($tagSlug) { $this->images = $this->runActionDefault($this->imageRepository, $tagSlug, 54); } public function renderDefault() { parent::runRenderDefault(); $this->template->images = $this->images; $this->template->uploadDir = $this->context->parameters['uploadDir']; } /** * @param int $imageId */ public function handleActivate($imageId) { $image = $this->getItem($imageId, $this->imageRepository); if (!$image) { $this->throw404(); } $this->imageRepository->activate($image); $this->flashWithRedirect($this->translator->translate('locale.item.activated')); } /** * @param int $imageId */ public function handleDelete($imageId) { $image = $this->getItem($imageId, $this->imageRepository); if (!$image) { $this->throw404(); } $this->imageRepository->delete($image); $this->flashWithRedirect($this->translator->translate('locale.item.deleted')); } } ","<?php namespace App\FrontModule\Presenters; use App\Model\Entities; use App\Model\Repositories; final class GalleryPresenter extends SingleUserContentPresenter { /** @var Repositories\ImageRepository @inject */ public $imageRepository; /** @var Entities\ImageEntity[] */ private $images; /** * @param string $tagSlug */ public function actionDefault($tagSlug) { $this->images = $this->runActionDefault($this->imageRepository, $tagSlug, 50); } public function renderDefault() { parent::runRenderDefault(); $this->template->images = $this->images; $this->template->uploadDir = $this->context->parameters['uploadDir']; } /** * @param int $imageId */ public function handleActivate($imageId) { $image = $this->getItem($imageId, $this->imageRepository); if (!$image) { $this->throw404(); } $this->imageRepository->activate($image); $this->flashWithRedirect($this->translator->translate('locale.item.activated')); } /** * @param int $imageId */ public function handleDelete($imageId) { $image = $this->getItem($imageId, $this->imageRepository); if (!$image) { $this->throw404(); } $this->imageRepository->delete($image); $this->flashWithRedirect($this->translator->translate('locale.item.deleted')); } } " "Fix Editor Save Button not allowing unpublish Closes #2918","/* global console */ var EditorControllerMixin = Ember.Mixin.create({ //## Computed post properties isPublished: Ember.computed.equal('status', 'published'), isDraft: Ember.computed.equal('status', 'draft'), /** * By default, a post will not change its publish state. * Only with a user-set value (via setSaveType action) * can the post's status change. */ willPublish: function (key, value) { if (arguments.length > 1) { return value; } return this.get('isPublished'); }.property('isPublished'), actions: { save: function () { var status = this.get('willPublish') ? 'published' : 'draft', self = this; this.set('status', status); this.get('model').save().then(function () { console.log('saved'); self.notifications.showSuccess('Post status saved as <strong>' + self.get('status') + '</strong>.'); }, this.notifications.showErrors); }, setSaveType: function (newType) { if (newType === 'publish') { this.set('willPublish', true); } else if (newType === 'draft') { this.set('willPublish', false); } else { console.warn('Received invalid save type; ignoring.'); } } } }); export default EditorControllerMixin; ","/* global console */ var EditorControllerMixin = Ember.Mixin.create({ //## Computed post properties isPublished: Ember.computed.equal('status', 'published'), isDraft: Ember.computed.equal('status', 'draft'), /** * By default, a post will not change its publish state. * Only with a user-set value (via setSaveType action) * can the post's status change. */ willPublish: function (key, val) { if (val) { return val; } return this.get('isPublished'); }.property('isPublished'), actions: { save: function () { var status = this.get('willPublish') ? 'published' : 'draft', self = this; this.set('status', status); this.get('model').save().then(function () { console.log('saved'); self.notifications.showSuccess('Post status saved as <strong>' + self.get('status') + '</strong>.'); }, this.notifications.showErrors); }, setSaveType: function (newType) { if (newType === 'publish') { this.set('willPublish', true); } else if (newType === 'draft') { this.set('willPublish', false); } else { console.warn('Received invalid save type; ignoring.'); } } } }); export default EditorControllerMixin; " "Remove ReportingZones from model object. Signed-off-by: Jon Seymour <44f878afe53efc66b76772bd845eb65944ed8232@ninjablocks.com>","package model import ""time"" type TimeSeriesPayload struct { Thing string `json:""thing""` ThingType string `json:""thingType""` Promoted bool `json:""promoted""` Device string `json:""device""` Channel string `json:""channel""` Schema string `json:""schema""` Event string `json:""event""` Points []TimeSeriesDatapoint `json:""points""` Time string `json:""time""` TimeZone string `json:""timeZone""` TimeOffset int `json:""timeOffset""` Site string `json:""site""` UserOverride string `json:""_""` NodeOverride string `json:""_""` } type TimeSeriesDatapoint struct { Path string `json:""path""` Value interface{} `json:""value""` Type string `json:""type""` } func (p *TimeSeriesPayload) GetTime() (time.Time, error) { return time.Parse(time.RFC3339, p.Time) } func (p *TimeSeriesPayload) GetPath(path string) interface{} { for _, point := range p.Points { if point.Path == path { return point.Value } } return nil } ","package model import ""time"" type TimeSeriesPayload struct { Thing string `json:""thing""` ThingType string `json:""thingType""` Promoted bool `json:""promoted""` Device string `json:""device""` Channel string `json:""channel""` Schema string `json:""schema""` Event string `json:""event""` Points []TimeSeriesDatapoint `json:""points""` Time string `json:""time""` TimeZone string `json:""timeZone""` TimeOffset int `json:""timeOffset""` Site string `json:""site""` ReportingZones map[string]string `json:""zones""` UserOverride string `json:""_""` NodeOverride string `json:""_""` } type TimeSeriesDatapoint struct { Path string `json:""path""` Value interface{} `json:""value""` Type string `json:""type""` } func (p *TimeSeriesPayload) GetTime() (time.Time, error) { return time.Parse(time.RFC3339, p.Time) } func (p *TimeSeriesPayload) GetPath(path string) interface{} { for _, point := range p.Points { if point.Path == path { return point.Value } } return nil } " Fix for verify headers being incorrect.,"<?php // Elevate API Client namespace ElevateAPI; use GuzzleHttp\Client as GuzzleClient; use GuzzleHttp\Exception\GuzzleException; use ElevateAPI\Query\QueryAbstract; class Client { protected $_client; protected $_parameters; protected $_auth_key; protected $_security = 'key'; // Constructor for the client class. public function __construct($base_url, $auth_key, $security = 'key') { $this->_client = new GuzzleClient(['base_uri' => $base_url]); $this->_client->setDefaultOption('verify', false); $this->_auth_key = $auth_key; $this->_security = $security; } public function get(QueryAbstract $query) { $parameters = $query->parameters; // Merge Parameters with the auth. $parameters['auth'] = $query->authSecurityString($this->_security, $this->_auth_key); // grab the endpoint from the query class. $endpoint = 'solar.qll_web.' . $query->query; try { $response = $this->_client->request('GET', $endpoint, ['query' => $parameters]); } catch(GuzzleException $e) { throw $e; } // We need to check to see if the content type is text/xml, but for right now this will work fine. if($response->getStatusCode() == '200') { $xml = $response->getBody()->getContents(); return new \SimpleXMLElement($xml); } } }","<?php // Elevate API Client namespace ElevateAPI; use GuzzleHttp\Client as GuzzleClient; use GuzzleHttp\Exception\GuzzleException; use ElevateAPI\Query\QueryAbstract; class Client { protected $_client; protected $_parameters; protected $_auth_key; protected $_security = 'key'; // Constructor for the client class. public function __construct($base_url, $auth_key, $security = 'key') { $this->_client = new GuzzleClient(['base_uri' => $base_url]); $this->_auth_key = $auth_key; $this->_security = $security; } public function get(QueryAbstract $query) { $parameters = $query->parameters; // Merge Parameters with the auth. $parameters['auth'] = $query->authSecurityString($this->_security, $this->_auth_key); // grab the endpoint from the query class. $endpoint = 'solar.qll_web.' . $query->query; try { $response = $this->_client->request('GET', $endpoint, ['query' => $parameters]); } catch(GuzzleException $e) { throw $e; } // We need to check to see if the content type is text/xml, but for right now this will work fine. if($response->getStatusCode() == '200') { $xml = $response->getBody()->getContents(); return new \SimpleXMLElement($xml); } } }" "Fix a couple of tests Fix a couple of tests that were broken by commit 7e068a3."," import json import ckanapi import unittest import paste.fixture def wsgi_app(environ, start_response): status = '200 OK' headers = [('Content-type', 'application/json')] path = environ['PATH_INFO'] if path == '/api/action/hello_world': response = {'success': True, 'result': 'how are you?'} elif path == '/api/action/invalid': response = {'success': False, 'error': {'__type': 'Validation Error'}} elif path == '/api/action/echo': response = {'success': True, 'result': json.loads(environ['wsgi.input'].read())['message']} start_response(status, headers) return [json.dumps(response)] class TestTestAPPCKAN(unittest.TestCase): def setUp(self): self.test_app = paste.fixture.TestApp(wsgi_app) self.ckan = ckanapi.TestAppCKAN(self.test_app) def test_simple(self): self.assertEquals( self.ckan.action.hello_world(), 'how are you?') def test_invalid(self): self.assertRaises( ckanapi.ValidationError, self.ckan.action.invalid) def test_data(self): self.assertEquals( self.ckan.action.echo(message='for you'), 'for you') if __name__ == '__main__': unittest.main() "," import json import ckanapi import unittest import paste.fixture def wsgi_app(environ, start_response): status = '200 OK' headers = [('Content-type', 'application/json')] path = environ['PATH_INFO'] if path == '/api/action/hello_world': response = {'success': True, 'result': 'how are you?'} elif path == '/api/action/invalid': response = {'success': False, 'error': {'__type': 'Validation Error'}} elif path == '/api/action/echo': response = {'success': True, 'result': json.loads(environ['wsgi.input'].read())['message']} start_response(status, headers) return [json.dumps(response)] class TestTestAPPCKAN(unittest.TestCase): def setUp(self): self.test_app = paste.fixture.TestApp(wsgi_app) self.ckan = ckanapi.TestAppCKAN(self.test_app) def test_simple(self): self.assertEquals( self.ckan.action.hello_world()['result'], 'how are you?') def test_invalid(self): self.assertRaises( ckanapi.ValidationError, self.ckan.action.invalid) def test_data(self): self.assertEquals( self.ckan.action.echo(message='for you')['result'], 'for you') if __name__ == '__main__': unittest.main() " Use ActiveRecord field 'default' config,"<?php namespace Emergence\People; use HandleBehavior; class Invitation extends \ActiveRecord { public static $tableName = 'invitations'; public static $singularNoun = 'invitation'; public static $pluralNoun = 'invitations'; public static $fields = [ 'RecipientID' => [ 'type' => 'uint', 'index' => true ], 'Handle' => [ 'unique' => true ], 'Status' => [ 'type' => 'enum', 'values' => ['Pending', 'Used', 'Revoked'], 'default' => 'Pending' ], 'Expires' => [ 'type' => 'timestamp', 'default' => null ], 'Used' => [ 'type' => 'timestamp', 'default' => null ] ]; public static $relationships = [ 'Recipient' => [ 'type' => 'one-one', 'class' => Person::class ] ]; public function save($deep = true) { // set handle if (!$this->Handle) { $this->Handle = HandleBehavior::generateRandomHandle($this); } // call parent parent::save($deep); } }","<?php namespace Emergence\People; use HandleBehavior; class Invitation extends \ActiveRecord { public static $tableName = 'invitations'; public static $singularNoun = 'invitation'; public static $pluralNoun = 'invitations'; public static $fields = [ 'RecipientID' => [ 'type' => 'uint', 'index' => true ], 'Handle' => [ 'unique' => true ], 'Status' => [ 'type' => 'enum', 'values' => ['Pending', 'Used', 'Revoked'], 'default' => 'Pending' ], 'Expires' => [ 'type' => 'timestamp', 'notnull' => false ], 'Used' => [ 'type' => 'timestamp', 'notnull' => false ] ]; public static $relationships = [ 'Recipient' => [ 'type' => 'one-one', 'class' => Person::class ] ]; public function save($deep = true) { // set handle if (!$this->Handle) { $this->Handle = HandleBehavior::generateRandomHandle($this); } // call parent parent::save($deep); } }" Use behavior instead mixin to Polymer 1.x compatibility,"const createPolobxBehavior = function(stores) { let appState = {}; Object.keys(stores).forEach( key => { const store = mobx.observable(stores[key].store); const actions = stores[key].actions; appState[key] = { store, actions }; }); function dispatch({store, action, payload}) { if (appState[store] && appState[store].actions && appState[store].actions[action]) { const storeAction = appState[store].actions[action]; mobx.action(storeAction.bind(appState[store], [payload]))(); return appState[store]; } console.warn(`No action ""${action}"" for ""${store}"" store`); }; mobx.useStrict(true); return { created() { this._appState = appState; this.dispatch = dispatch; } attached() { const properties = this.constructor.config.properties; if (properties) { for (let property in properties) { const statePath = properties[property].statePath; if (statePath && this._appState[statePath.store]) { mobx.autorun(() => { const store = this._appState[statePath.store].store; this[property] = store[statePath.path]; }); } } } } }; }; ","const createPolobxMixin = function(stores) { let appState = {}; Object.keys(stores).forEach( key => { const store = mobx.observable(stores[key].store); const actions = stores[key].actions; appState[key] = { store, actions }; }); function dispatch({store, action, payload}) { if (appState[store] && appState[store].actions && appState[store].actions[action]) { const storeAction = appState[store].actions[action]; mobx.action(storeAction.bind(appState[store], [payload]))(); return appState[store]; } console.warn(`No action ""${action}"" for ""${store}"" store`); }; mobx.useStrict(true); return subclass => class extends subclass { constructor() { super(); this._appState = appState; this.dispatch = dispatch; } connectedCallback() { super.connectedCallback(); const properties = this.constructor.config.properties; if (properties) { for (let property in properties) { const statePath = properties[property].statePath; if (statePath && this._appState[statePath.store]) { mobx.autorun(() => { const store = this._appState[statePath.store].store; this[property] = store[statePath.path]; }); } } } } }; }; " "Use an Unicode object format string when building HTML for the admin, since the arguments can be Unicode as well. Fixes #2. Translated labels are now displayed correctly.","from django import template from django.conf import settings from django.core.urlresolvers import reverse from django.contrib.admin import site from ..admin import AdminViews register = template.Library() @register.simple_tag def get_admin_views(app_name): output = [] STATIC_URL = settings.STATIC_URL for k, v in site._registry.items(): if app_name.lower() not in str(k._meta): continue if isinstance(v, AdminViews): for type, name, link in v.output_urls: if type == 'url': img_url = ""%sadmin_views/icons/link.png"" % STATIC_URL alt_text = ""Link to '%s'"" % name else: img_url = ""%sadmin_views/icons/view.png"" % STATIC_URL alt_text = ""Custom admin view '%s'"" % name output.append( u""""""<tr> <th scope=""row""> <img src=""%s"" alt=""%s"" /> <a href=""%s"">%s</a></th> <td> </td> <td> </td> </tr> """""" % (img_url, alt_text, link, name) ) return """".join(output) ","from django import template from django.conf import settings from django.core.urlresolvers import reverse from django.contrib.admin import site from ..admin import AdminViews register = template.Library() @register.simple_tag def get_admin_views(app_name): output = [] STATIC_URL = settings.STATIC_URL for k, v in site._registry.items(): if app_name.lower() not in str(k._meta): continue if isinstance(v, AdminViews): for type, name, link in v.output_urls: if type == 'url': img_url = ""%sadmin_views/icons/link.png"" % STATIC_URL alt_text = ""Link to '%s'"" % name else: img_url = ""%sadmin_views/icons/view.png"" % STATIC_URL alt_text = ""Custom admin view '%s'"" % name output.append( """"""<tr> <th scope=""row""> <img src=""%s"" alt=""%s"" /> <a href=""%s"">%s</a></th> <td> </td> <td> </td> </tr> """""" % (img_url, alt_text, link, name) ) return """".join(output) " Add is_label_name field to Feature model,"from django.db import models from django.utils import timezone class Dataset(models.Model): name = models.CharField(max_length=100, default='') description = models.CharField(max_length=500, default='') source = models.FileField(upload_to='data_sources') created_at = models.DateTimeField('created at', default=timezone.now()) def __unicode__(self): return self.name class Label(models.Model): label = models.CharField(max_length=100, default='unlabeled') def __unicode__(self): return self.label class Instance(models.Model): dataset = models.ForeignKey(Dataset, related_name='instances') label = models.ForeignKey(Label, default=0, related_name='instances') name = models.CharField(max_length=100, default='unnamed') def __unicode__(self): return self.name class Feature(models.Model): datasets = models.ManyToManyField(Dataset, related_name='features') instances = models.ManyToManyField( Instance, null=True, related_name='features') name = models.CharField(max_length=100, unique=True) is_label_name = models.BooleanField(default=False) def __unicode__(self): return self.name class Value(models.Model): feature = models.ForeignKey(Feature, related_name='values') instance = models.ForeignKey(Instance, related_name='values') value = models.FloatField() def __unicode__(self): return unicode(self.value) ","from django.db import models from django.utils import timezone class Dataset(models.Model): name = models.CharField(max_length=100, default='') description = models.CharField(max_length=500, default='') source = models.FileField(upload_to='data_sources') created_at = models.DateTimeField('created at', default=timezone.now()) def __unicode__(self): return self.name class Label(models.Model): label = models.CharField(max_length=100, default='unlabeled') def __unicode__(self): return self.label class Instance(models.Model): dataset = models.ForeignKey(Dataset, related_name='instances') label = models.ForeignKey(Label, default=0, related_name='instances') name = models.CharField(max_length=100, default='unnamed') def __unicode__(self): return self.name class Feature(models.Model): datasets = models.ManyToManyField(Dataset, related_name='features') instances = models.ManyToManyField( Instance, null=True, related_name='features') name = models.CharField(max_length=100, unique=True) def __unicode__(self): return self.name class Value(models.Model): feature = models.ForeignKey(Feature, related_name='values') instance = models.ForeignKey(Instance, related_name='values') value = models.FloatField() def __unicode__(self): return unicode(self.value) " Add ebi_metagenomics as package script,"from setuptools import find_packages, setup setup( name=""ebisearch"", version=""0.0.1"", author=""Berenice Batut"", author_email=""berenice.batut@gmail.com"", description=(""A Python library for interacting with EBI Search's API""), license=""MIT"", keywords=""api api-client ebi"", url=""https://github.com/bebatut/ebisearch"", packages=find_packages(), entry_points={ 'console_scripts': [ 'ebisearch = ebisearch.__main__:main' ] }, scripts=['ebi_metagenomics'], classifiers=[ ""Development Status :: 2 - Pre-Alpha"", ""Environment :: Web Environment"", ""License :: OSI Approved :: MIT License"", ""Programming Language :: Python :: 3"", ""Intended Audience :: Developers"", ""Operating System :: OS Independent"", ""Topic :: Scientific/Engineering"", ""Programming Language :: Python :: 2"", ""Programming Language :: Python :: 2.7"", ""Programming Language :: Python :: 3"", ""Programming Language :: Python :: 3.3"", ""Programming Language :: Python :: 3.4"", ""Programming Language :: Python :: 3.5"", ""Programming Language :: Python :: 3.6"" ], extras_require={ 'testing': [""pytest""], }, setup_requires=['pytest-runner'], tests_require=['pytest'], install_requires=['requests', 'Click', 'flake8', 'pprint'] ) ","from setuptools import find_packages, setup setup( name=""ebisearch"", version=""0.0.1"", author=""Berenice Batut"", author_email=""berenice.batut@gmail.com"", description=(""A Python library for interacting with EBI Search's API""), license=""MIT"", keywords=""api api-client ebi"", url=""https://github.com/bebatut/ebisearch"", packages=find_packages(), entry_points={ 'console_scripts': [ 'ebisearch = ebisearch.__main__:main' ] }, classifiers=[ ""Development Status :: 2 - Pre-Alpha"", ""Environment :: Web Environment"", ""License :: OSI Approved :: MIT License"", ""Programming Language :: Python :: 3"", ""Intended Audience :: Developers"", ""Operating System :: OS Independent"", ""Topic :: Scientific/Engineering"", ""Programming Language :: Python :: 2"", ""Programming Language :: Python :: 2.7"", ""Programming Language :: Python :: 3"", ""Programming Language :: Python :: 3.3"", ""Programming Language :: Python :: 3.4"", ""Programming Language :: Python :: 3.5"", ""Programming Language :: Python :: 3.6"" ], extras_require={ 'testing': [""pytest""], }, setup_requires=['pytest-runner'], tests_require=['pytest'], install_requires=['requests', 'Click', 'flake8', 'pprint'] ) " Make sure embed response never matches a request,"<?php class CM_Http_Response_Page_Embed extends CM_Http_Response_Page { /** @var string|null */ private $_title; /** * @throws CM_Exception_Invalid * @return string */ public function getTitle() { if (null === $this->_title) { throw new CM_Exception_Invalid('Unprocessed page has no title'); } return $this->_title; } /** * @param CM_Page_Abstract $page * @return string */ protected function _renderPage(CM_Page_Abstract $page) { $renderAdapterLayout = new CM_RenderAdapter_Layout($this->getRender(), $page); $this->_title = $renderAdapterLayout->fetchTitle(); return $renderAdapterLayout->fetchPage(); } protected function _process() { $this->_processContentOrRedirect(); } public static function createFromRequest(CM_Http_Request_Abstract $request, CM_Site_Abstract $site, CM_Service_Manager $serviceManager) { return null; } /** * @param CM_Http_Request_Abstract $request * @param CM_Site_Abstract $site * @param CM_Service_Manager $serviceManager * @return CM_Http_Response_Page_Embed */ public static function createEmbedResponseFromRequest(CM_Http_Request_Abstract $request, CM_Site_Abstract $site, CM_Service_Manager $serviceManager) { $request = clone $request; $request->popPathLanguage(); return new self($request, $site, $serviceManager); } } ","<?php class CM_Http_Response_Page_Embed extends CM_Http_Response_Page { /** @var string|null */ private $_title; /** * @throws CM_Exception_Invalid * @return string */ public function getTitle() { if (null === $this->_title) { throw new CM_Exception_Invalid('Unprocessed page has no title'); } return $this->_title; } /** * @param CM_Page_Abstract $page * @return string */ protected function _renderPage(CM_Page_Abstract $page) { $renderAdapterLayout = new CM_RenderAdapter_Layout($this->getRender(), $page); $this->_title = $renderAdapterLayout->fetchTitle(); return $renderAdapterLayout->fetchPage(); } protected function _process() { $this->_processContentOrRedirect(); } /** * @param CM_Http_Request_Abstract $request * @param CM_Site_Abstract $site * @param CM_Service_Manager $serviceManager * @return CM_Http_Response_Page_Embed */ public static function createEmbedResponseFromRequest(CM_Http_Request_Abstract $request, CM_Site_Abstract $site, CM_Service_Manager $serviceManager) { $request = clone $request; $request->popPathLanguage(); return new self($request, $site, $serviceManager); } } " "Fix ambiguous URI parsing in Youtube Remarkup rule Summary: Fixes T12867. Also: - Simplify the code a little. - Stop mutating this on text/mobile -- there's no inherent value in the ""youtu.be"" link so I think this just changes the text the user wrote unnecessarily. Test Plan: {F5013804} Reviewers: chad Reviewed By: chad Maniphest Tasks: T12867 Differential Revision: https://secure.phabricator.com/D18149","<?php final class PhabricatorYoutubeRemarkupRule extends PhutilRemarkupRule { public function getPriority() { return 350.0; } public function apply($text) { try { $uri = new PhutilURI($text); } catch (Exception $ex) { return $text; } $domain = $uri->getDomain(); if (!preg_match('/(^|\.)youtube\.com\z/', $domain)) { return $text; } $params = $uri->getQueryParams(); $v_param = idx($params, 'v'); if (!strlen($v_param)) { return $text; } $text_mode = $this->getEngine()->isTextMode(); $mail_mode = $this->getEngine()->isHTMLMailMode(); if ($text_mode || $mail_mode) { return $text; } $youtube_src = 'https://www.youtube.com/embed/'.$v_param; $iframe = $this->newTag( 'div', array( 'class' => 'embedded-youtube-video', ), $this->newTag( 'iframe', array( 'width' => '650', 'height' => '400', 'style' => 'margin: 1em auto; border: 0px;', 'src' => $youtube_src, 'frameborder' => 0, ), '')); return $this->getEngine()->storeText($iframe); } } ","<?php final class PhabricatorYoutubeRemarkupRule extends PhutilRemarkupRule { private $uri; public function getPriority() { return 350.0; } public function apply($text) { $this->uri = new PhutilURI($text); if ($this->uri->getDomain() && preg_match('/(^|\.)youtube\.com$/', $this->uri->getDomain()) && idx($this->uri->getQueryParams(), 'v')) { return $this->markupYoutubeLink(); } return $text; } public function markupYoutubeLink() { $v = idx($this->uri->getQueryParams(), 'v'); $text_mode = $this->getEngine()->isTextMode(); $mail_mode = $this->getEngine()->isHTMLMailMode(); if ($text_mode || $mail_mode) { return $this->getEngine()->storeText('http://youtu.be/'.$v); } $youtube_src = 'https://www.youtube.com/embed/'.$v; $iframe = $this->newTag( 'div', array( 'class' => 'embedded-youtube-video', ), $this->newTag( 'iframe', array( 'width' => '650', 'height' => '400', 'style' => 'margin: 1em auto; border: 0px;', 'src' => $youtube_src, 'frameborder' => 0, ), '')); return $this->getEngine()->storeText($iframe); } } " Fix mimetype detection on symlink," import os import hashlib import magic from base64 import b64encode, b64decode from datetime import datetime from .settings import inventory from .encryption import random_key, copy_and_encrypt, decrypt_blob hashing = hashlib.sha256 def add_file(filepath, *, key=None): ""Import a file into Dis."" # Resolve symlinks realpath = os.path.realpath(filepath) if not os.path.isfile(filepath): raise FileNotFoundError if key is None: key = random_key() file_hash = hashing() file_hash.update(open(filepath, 'rb').read()) id_ = copy_and_encrypt(filepath, key) meta = { 'key': b64encode(key), 'hash': 'sha256-' + file_hash.hexdigest(), 'size': os.path.getsize(realpath), 'timestamp': datetime.now(), 'id': id_, 'info': { 'type': magic.from_file(realpath).decode(), 'mimetype': magic.from_file(realpath, mime=True).decode(), 'filename': os.path.basename(filepath), 'path': filepath, } } inventory.save_record(meta) return meta def get_content(id_, *, offset=0, length=None): key = b64decode(inventory.get_record(id_)['key']) return decrypt_blob(id_, key, offset=offset, length=length) "," import os import hashlib import magic from base64 import b64encode, b64decode from datetime import datetime from .settings import inventory from .encryption import random_key, copy_and_encrypt, decrypt_blob hashing = hashlib.sha256 def add_file(filepath, *, key=None): ""Import a file into Dis."" if not os.path.isfile(filepath): raise FileNotFoundError if key is None: key = random_key() file_hash = hashing() file_hash.update(open(filepath, 'rb').read()) id_ = copy_and_encrypt(filepath, key) meta = { 'key': b64encode(key), 'hash': 'sha256-' + file_hash.hexdigest(), 'size': os.path.getsize(filepath), 'timestamp': datetime.now(), 'id': id_, 'info': { 'type': magic.from_file(filepath).decode(), 'mimetype': magic.from_file(filepath, mime=True).decode(), 'filename': os.path.basename(filepath), 'path': filepath, } } inventory.save_record(meta) return meta def get_content(id_, *, offset=0, length=None): key = b64decode(inventory.get_record(id_)['key']) return decrypt_blob(id_, key, offset=offset, length=length) " Check if putting/getting was actually successful.,"#!/usr/bin/env python # coding=utf8 try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from .. import KeyValueStore class MemcacheStore(KeyValueStore): def __contains__(self, key): try: return key in self.mc except TypeError: raise IOError('memcache implementation does not support '\ '__contains__') def __init__(self, mc): self.mc = mc def _delete(self, key): if not self.mc.delete(key): raise IOError('Error deleting key') def _get(self, key): rv = self.mc.get(key) if None == rv: raise KeyError(key) return rv def _get_file(self, key, file): file.write(self._get(key)) def _open(self, key): return StringIO(self._get(key)) def _put(self, key, data): if not self.mc.set(key, data): if len(data) >= 1024 * 1023: raise IOError('Failed to store data, probably too large. '\ 'memcached limit is 1M') raise IOError('Failed to store data') return key def _put_file(self, key, file): return self._put(key, file.read()) def keys(self): raise IOError('Memcache does not support listing keys.') def iter_keys(self): raise IOError('Memcache does not support key iteration.') ","#!/usr/bin/env python # coding=utf8 try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from .. import KeyValueStore class MemcacheStore(KeyValueStore): def __contains__(self, key): try: return key in self.mc except TypeError: raise IOError('memcache implementation does not support '\ '__contains__') def __init__(self, mc): self.mc = mc def _delete(self, key): self.mc.delete(key) def _get(self, key): rv = self.mc.get(key) if None == rv: raise KeyError(key) return rv def _get_file(self, key, file): file.write(self._get(key)) def _open(self, key): return StringIO(self._get(key)) def _put(self, key, data): self.mc.set(key, data) return key def _put_file(self, key, file): self.mc.set(key, file.read()) return key def keys(self): raise IOError('Memcache does not support listing keys.') def iter_keys(self): raise IOError('Memcache does not support key iteration.') " Fix issue for root pages,"<?php namespace Anomaly\PagesModule\Page\Form; use Anomaly\PagesModule\Page\Contract\PageInterface; use Anomaly\PreferencesModule\Preference\Contract\PreferenceRepositoryInterface; use Illuminate\Foundation\Bus\DispatchesJobs; class PageFormFields { use DispatchesJobs; /** * Handle the page fields. * * @param PageFormBuilder $builder * @param PreferenceRepositoryInterface $preferences */ public function handle(PageFormBuilder $builder, PreferenceRepositoryInterface $preferences) { $parent = $builder->getParent(); /* @var PageInterface $entry */ if (!$parent && $entry = $builder->getFormEntry()) { $parent = $entry->getParent(); } $builder->setFields( [ '*', 'parent' => [ 'config' => [ 'mode' => 'lookup', 'default_value' => $parent ? $parent->getId() : null, ], ], 'publish_at' => [ 'config' => [ 'default_value' => 'now', 'timezone' => config('app.timezone'), ], ], ] ); if ($parent && $translations = $parent->getTranslations()) { $builder->setFields( array_merge( $builder->getFields(), $translations->map( function ($translation) { return [ 'field' => 'slug', 'locale' => $translation->locale, 'config' => [ 'prefix' => $translation->path, ], ]; } )->all() ) ); } } } ","<?php namespace Anomaly\PagesModule\Page\Form; use Anomaly\PagesModule\Page\Contract\PageInterface; use Anomaly\PreferencesModule\Preference\Contract\PreferenceRepositoryInterface; use Illuminate\Foundation\Bus\DispatchesJobs; class PageFormFields { use DispatchesJobs; /** * Handle the page fields. * * @param PageFormBuilder $builder * @param PreferenceRepositoryInterface $preferences */ public function handle(PageFormBuilder $builder, PreferenceRepositoryInterface $preferences) { $parent = $builder->getParent(); /* @var PageInterface $entry */ if (!$parent && $entry = $builder->getFormEntry()) { $parent = $entry->getParent(); } $translations = $parent->getTranslations(); $slugs = $translations->map( function ($translation) { return [ 'field' => 'slug', 'locale' => $translation->locale, 'config' => [ 'prefix' => $translation->path, ], ]; } )->all(); $builder->setFields( array_merge([ '*', 'parent' => [ 'config' => [ 'mode' => 'lookup', 'default_value' => $parent ? $parent->getId() : null, ], ], 'publish_at' => [ 'config' => [ 'default_value' => 'now', 'timezone' => config('app.timezone'), ], ], ], $slugs) ); } } " Fix another failing unit test (from metrics work).,"from os.path import exists, join import shutil import tempfile import time from lwr.managers.queued import QueueManager from lwr.managers.stateful import StatefulManagerProxy from lwr.tools.authorization import get_authorizer from .test_utils import TestDependencyManager from galaxy.util.bunch import Bunch from galaxy.jobs.metrics import NULL_JOB_INSTRUMENTER def test_persistence(): """""" Tests persistence of a managers jobs. """""" staging_directory = tempfile.mkdtemp() try: app = Bunch(staging_directory=staging_directory, persistence_directory=staging_directory, authorizer=get_authorizer(None), dependency_manager=TestDependencyManager(), job_metrics=Bunch(default_job_instrumenter=NULL_JOB_INSTRUMENTER), ) assert not exists(join(staging_directory, ""queued_jobs"")) queue1 = StatefulManagerProxy(QueueManager('test', app, num_concurrent_jobs=0)) job_id = queue1.setup_job('4', 'tool1', '1.0.0') touch_file = join(staging_directory, 'ran') queue1.launch(job_id, 'touch %s' % touch_file) time.sleep(.4) assert (not(exists(touch_file))) queue1.shutdown() queue2 = StatefulManagerProxy(QueueManager('test', app, num_concurrent_jobs=1)) time.sleep(1) assert exists(touch_file) finally: shutil.rmtree(staging_directory) try: queue2.shutdown() except: pass ","from os.path import exists, join import shutil import tempfile import time from lwr.managers.queued import QueueManager from lwr.managers.stateful import StatefulManagerProxy from lwr.tools.authorization import get_authorizer from .test_utils import TestDependencyManager from galaxy.util.bunch import Bunch def test_persistence(): """""" Tests persistence of a managers jobs. """""" staging_directory = tempfile.mkdtemp() try: app = Bunch(staging_directory=staging_directory, persistence_directory=staging_directory, authorizer=get_authorizer(None), dependency_manager=TestDependencyManager(), ) assert not exists(join(staging_directory, ""queued_jobs"")) queue1 = StatefulManagerProxy(QueueManager('test', app, num_concurrent_jobs=0)) job_id = queue1.setup_job('4', 'tool1', '1.0.0') touch_file = join(staging_directory, 'ran') queue1.launch(job_id, 'touch %s' % touch_file) time.sleep(.4) assert (not(exists(touch_file))) queue1.shutdown() queue2 = StatefulManagerProxy(QueueManager('test', app, num_concurrent_jobs=1)) time.sleep(1) assert exists(touch_file) finally: shutil.rmtree(staging_directory) try: queue2.shutdown() except: pass " Fix typo in options serializer.,"from rest_framework import serializers def validate_options(options, attributes): fields = {} for name, option in options.items(): field_type = option.get('type', '') if field_type == 'string': field = serializers.CharField() elif field_type == 'integer': field = serializers.IntegerField() elif field_type == 'money': field = serializers.IntegerField() elif field_type == 'boolean': field = serializers.BooleanField() else: field = serializers.CharField() default_value = option.get('default') if default_value: field.default = default_value if 'min' in option: field.min_value = option.get('min') if 'max' in option: field.max_value = option.get('max') if 'choices' in option: field.choices = option.get('choices') field.required = option.get('required', False) field.label = option.get('label') field.help_text = option.get('help_text') fields[name] = field serializer_class = type(b'AttributesSerializer', (serializers.Serializer,), fields) serializer = serializer_class(data=attributes) serializer.is_valid(raise_exception=True) ","from rest_framework import serializers def validate_options(options, attributes): fields = {} for name, option in options.items(): field_type = option.get('type', '') if field_type == 'string': field = serializers.CharField() elif field_type == 'integer': field = serializers.IntegerField() elif field_type == 'money': field = serializers.IntegerField() elif field_type == 'boolean': field = serializers.BooleanField() else: field = serializers.CharField() default_value = option.get('default') if default_value: field.default = default_value if 'min' in option: field.min_value = option.get('min') if 'max' in option: field.max_value = option.get('max') if 'choices' in option: fields.choices = option.get('choices') field.required = option.get('required', False) field.label = option.get('label') field.help_text = option.get('help_text') fields[name] = field serializer_class = type(b'AttributesSerializer', (serializers.Serializer,), fields) serializer = serializer_class(data=attributes) serializer.is_valid(raise_exception=True) " Add authentication otpion to mongodb,"# -*- coding: utf-8 -*- """""" pymongo library automatically tries to reconnect if connection has been lost """""" from intelmq.lib.bot import Bot try: import pymongo except ImportError: pymongo = None class MongoDBOutputBot(Bot): def init(self): if pymongo is None: self.logger.error('Could not import pymongo. Please install it.') self.stop() self.connect() def connect(self): self.logger.debug('Connecting to mongodb server.') try: self.client = pymongo.MongoClient(self.parameters.host, int(self.parameters.port)) except pymongo.errors.ConnectionFailure: raise ValueError('Connection to mongodb server failed.') else: db = self.client[self.parameters.database] if self.parameters.db_user and self.parameters.db_pass: try: db.authenticate(name=self.parameters.db_user, password=self.parameters.db_pass) except pymongo.errors.OperationFailure: raise ValueError('Authentication to {} failed'.format(self.parameters.database)) self.collection = db[self.parameters.collection] self.logger.info('Successfully connected to mongodb server.') def process(self): event = self.receive_message() try: self.collection.insert(event.to_dict(hierarchical=self.parameters.hierarchical_output)) except pymongo.errors.AutoReconnect: self.logger.error('Connection Lost. Connecting again.') self.connect() else: self.acknowledge_message() def shutdown(self): self.client.close() BOT = MongoDBOutputBot ","# -*- coding: utf-8 -*- """""" pymongo library automatically tries to reconnect if connection has been lost """""" from intelmq.lib.bot import Bot try: import pymongo except ImportError: pymongo = None class MongoDBOutputBot(Bot): def init(self): if pymongo is None: self.logger.error('Could not import pymongo. Please install it.') self.stop() self.connect() def connect(self): self.logger.debug('Connecting to mongodb server.') try: self.client = pymongo.MongoClient(self.parameters.host, int(self.parameters.port)) except pymongo.errors.ConnectionFailure: raise ValueError('Connection to mongodb server failed.') else: db = self.client[self.parameters.database] self.collection = db[self.parameters.collection] self.logger.info('Successfully connected to mongodb server.') def process(self): event = self.receive_message() try: self.collection.insert(event.to_dict(hierarchical=self.parameters.hierarchical_output)) except pymongo.errors.AutoReconnect: self.logger.error('Connection Lost. Connecting again.') self.connect() else: self.acknowledge_message() def shutdown(self): self.client.close() BOT = MongoDBOutputBot " "Return country name, not object","<?php namespace DougSisk\CountryState; use Phine\Country\Loader\Loader; class CountryState { protected $countries; protected $loader; protected $states = []; public function __construct() { $this->loader = new Loader; if ($countries = config('countrystate.limitCountries')) { foreach ($countries as $code) { $this->countries[$code] = $this->loader->loadCountry($code)->getShortName(); } } else { $countries = $this->loader->loadCountries(); foreach ($countries as $country) { $this->countries[$country->getAlpha2Code()] = $country->getShortName(); } } if ($preLoad = config('countrystate.preloadCountryStates')) { foreach ($preLoad as $country) { $this->addCountryStates($country); } } } public function getCountries() { return $this->countries; } public function getStates($country) { return $this->findCountryStates($country); } protected function findCountryStates($country) { if (!array_key_exists($country, $this->states)) { $this->addCountryStates($country); } return $this->states[$country]; } protected function addCountryStates($country) { $this->states[$country] = []; $states = $this->loader->loadSubdivisions($country); foreach ($states as $code => $subdivision) { $code = preg_replace(""/([A-Z]{2}-)/"", '', $code); $this->states[$country][$code] = $subdivision->getName(); } } } ","<?php namespace DougSisk\CountryState; use Phine\Country\Loader\Loader; class CountryState { protected $countries; protected $loader; protected $states = []; public function __construct() { $this->loader = new Loader; if ($countries = config('countrystate.limitCountries')) { foreach ($countries as $code) { $this->countries[$code] = $this->loader->loadCountry($code); } } else { $this->countries = $this->loader->loadCountries(); } if ($preLoad = config('countrystate.preloadCountryStates')) { foreach ($preLoad as $country) { $this->addCountryStates($country); } } } public function getCountries() { return $this->countries; } public function getStates($country) { return $this->findCountryStates($country); } protected function findCountryStates($country) { if (!array_key_exists($country, $this->states)) { $this->addCountryStates($country); } return $this->states[$country]; } protected function addCountryStates($country) { $this->states[$country] = []; $states = $this->loader->loadSubdivisions($country); foreach ($states as $code => $subdivision) { $code = preg_replace(""/([A-Z]{2}-)/"", '', $code); $this->states[$country][$code] = $subdivision->getName(); } } } " "Add support for using a function `extversion` can be a a dict with a `function` key -- e.g.: setup( ... setup_requires='setuptools_extversion', extversion={'function': 'my_package.version:get_package_version'}, )",""""""" setuptools_extversion Allows getting distribution version from external sources (e.g.: shell command, Python function) """""" import pkg_resources import subprocess VERSION_PROVIDER_KEY = 'extversion' def version_calc(dist, attr, value): """""" Handler for parameter to setup(extversion=value) """""" if attr == VERSION_PROVIDER_KEY: if callable(value): extversion = value elif hasattr(value, 'get'): if value.get('command'): extversion = command(value.get('command'), shell=True) if value.get('function'): extversion = function(value.get('function')) else: raise Exception('Unknown type for %s = %r' % (attr, value)) dist.metadata.version = extversion(dist) class command(object): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __call__(self, distribution): return subprocess.check_output(*self.args, **self.kwargs).strip() class function(object): def __init__(self, func, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs def __call__(self, *args, **kwargs): if isinstance(self.func, basestring): ep = pkg_resources.EntryPoint.parse('x=' + self.func) self.func = ep.load(False) args = list(self.args + args) kwargs = dict(self.kwargs) kwargs.update(kwargs) return self.func(*args, **kwargs) ",""""""" setuptools_extversion Allows getting distribution version from external sources (e.g.: shell command, Python function) """""" import subprocess VERSION_PROVIDER_KEY = 'extversion' def version_calc(dist, attr, value): """""" Handler for parameter to setup(extversion=value) """""" if attr == VERSION_PROVIDER_KEY: if callable(value): extversion = value elif hasattr(value, 'get'): if value.get('command'): extversion = command(value.get('command'), shell=True) else: raise Exception('Unknown type for %s = %r' % (attr, value)) dist.metadata.version = extversion(dist) class command(object): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __call__(self, distribution): return subprocess.check_output(*self.args, **self.kwargs).strip() class function(object): def __init__(self, func, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs def __call__(self, *args, **kwargs): if isinstance(self.func, basestring): ep = pkg_resources.EntryPoint.parse('x=' + self.func) self.func = ep.load(False) args = list(self.args + args) kwargs = dict(self.kwargs) kwargs.update(kwargs) return self.func(*args, **kwargs) " Correct filename argument in constructor,"/* *\ ** SICU Stress Measurement System ** ** Project P04 | C380 Team A ** ** EBME 380: Biomedical Engineering Design Experience ** ** Case Western Reserve University ** ** 2016 Fall Semester ** \* */ package edu.cwru.sicu_sms.util; import jssc.SerialPortEvent; /** * This class is used to configure and manage the serial port for receiving EKG channel data. * * @since December 12, 2016 * @author Ted Frohlich <ttf10@case.edu> * @author Abby Walker <amw138@case.edu> */ public class EKGSerialPort extends AbstractSerialPort { public EKGSerialPort() { super(""util/EKGSerialPort.properties""); } @Override public void serialEvent(SerialPortEvent serialPortEvent) { // TODO } } ","/* *\ ** SICU Stress Measurement System ** ** Project P04 | C380 Team A ** ** EBME 380: Biomedical Engineering Design Experience ** ** Case Western Reserve University ** ** 2016 Fall Semester ** \* */ package edu.cwru.sicu_sms.util; import jssc.SerialPortEvent; /** * This class is used to configure and manage the serial port for receiving EKG channel data. * * @since December 12, 2016 * @author Ted Frohlich <ttf10@case.edu> * @author Abby Walker <amw138@case.edu> */ public class EKGSerialPort extends AbstractSerialPort { public EKGSerialPort() { super(""src/main/resources/util/EKGSerialPort.properties""); } @Override public void serialEvent(SerialPortEvent serialPortEvent) { // TODO } } " Fix test for generic plugins,"import pytest from detectem.core import MATCHERS from detectem.plugin import load_plugins, GenericPlugin from tests import create_pm from .utils import create_har_entry class TestGenericPlugin: @pytest.fixture def plugins(self): return load_plugins() def test_generic_plugin(self): class MyGenericPlugin(GenericPlugin): pass x = MyGenericPlugin() with pytest.raises(NotImplementedError): x.get_information(entry=None) assert x.ptype == 'generic' @pytest.mark.parametrize( 'plugin_name,matcher_type,har_content,name', [( 'wordpress_generic', 'url', 'http://domain.tld/wp-content/plugins/example/', 'example', )] ) def test_real_generic_plugin( self, plugin_name, matcher_type, har_content, name, plugins ): plugin = plugins.get(plugin_name) har_entry = create_har_entry(matcher_type, value=har_content) # Verify presence using matcher class matchers = plugin.get_matchers(matcher_type) matcher_instance = MATCHERS[matcher_type] assert matcher_instance.get_info( har_entry, *matchers, ) == create_pm(presence=True) assert plugin.get_information(har_entry)['name'] == name ","import pytest from detectem.core import MATCHERS from detectem.plugin import load_plugins, GenericPlugin from .utils import create_har_entry class TestGenericPlugin(object): @pytest.fixture def plugins(self): return load_plugins() def test_generic_plugin(self): class MyGenericPlugin(GenericPlugin): pass x = MyGenericPlugin() with pytest.raises(NotImplementedError): x.get_information(entry=None) assert x.ptype == 'generic' @pytest.mark.parametrize('plugin_name,indicator,name', [ ( 'wordpress_generic', {'url': 'http://domain.tld/wp-content/plugins/example/'}, 'example', ) ]) def test_real_generic_plugin(self, plugin_name, indicator, name, plugins): plugin = plugins.get(plugin_name) matcher_type = [k for k in indicator.keys()][0] har_entry = create_har_entry(indicator, matcher_type) matchers_in_plugin = plugin._get_matchers(matcher_type, 'indicators') # Call presence method in related matcher class matcher_instance = MATCHERS[matcher_type] assert matcher_instance.check_presence(har_entry, *matchers_in_plugin) assert plugin.get_information(har_entry)['name'] == name " "Fix typo error. Typo on copyright comment.","<?php /** * This file is part of the Bruery Platform. * * (c) Viktore Zara <viktore.zara@gmail.com> * (c) Mell Zamora <mellzamora@outlook.com> * * Copyright (c) 2016. For the full copyright and license information, please view the LICENSE file that was distributed with this source code. */ namespace Bruery\UserBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; class TemplateCompilerPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { $definition = $container->getDefinition('bruery_core.template_loader'); $templates = $container->getParameter('bruery_user.templates'); $bunldeTemplates = []; foreach($templates as $key => $templates) { if(is_array($templates)) { foreach ($templates as $id=>$template) { $bunldeTemplates[sprintf('bruery_user.template.%s.%s', $key, $id)] = $template; } } else { $bunldeTemplates[sprintf('bruery_user.template.%s', $key)] = $templates; } } $definition->addMethodCall('setTemplates', array($bunldeTemplates)); } } ","<?php /** * This file is part of the Bruery Platform. * * (c) Viktore Zara <viktore.zara@gmail.com> * (c) Mell Zamora <mellzamora@outlook.com> * * Copyright (c) 2016. For the full copyright and license information, please view the LICENSE file that was distributed with this source code. */ */ namespace Bruery\UserBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; class TemplateCompilerPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { $definition = $container->getDefinition('bruery_core.template_loader'); $templates = $container->getParameter('bruery_user.templates'); $bunldeTemplates = []; foreach($templates as $key => $templates) { if(is_array($templates)) { foreach ($templates as $id=>$template) { $bunldeTemplates[sprintf('bruery_user.template.%s.%s', $key, $id)] = $template; } } else { $bunldeTemplates[sprintf('bruery_user.template.%s', $key)] = $templates; } } $definition->addMethodCall('setTemplates', array($bunldeTemplates)); } } " Add classifiers to indicate that the package works with python 3.,"from setuptools import setup import sys version = '2.0.0' if sys.version_info >= (3,): python_dateutils_version = 'python-dateutil>=2.0' else: python_dateutils_version = 'python-dateutil<2.0' setup(name='pyactiveresource', version=version, description='ActiveResource for Python', author='Shopify', author_email='developers@shopify.com', url='https://github.com/Shopify/pyactiveresource/', packages=['pyactiveresource', 'pyactiveresource/testing'], license='MIT License', test_suite='test', install_requires=[ 'six', ], tests_require=[ python_dateutils_version, 'PyYAML', ], platforms=['any'], classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules'] ) ","from setuptools import setup import sys version = '2.0.0' if sys.version_info >= (3,): python_dateutils_version = 'python-dateutil>=2.0' else: python_dateutils_version = 'python-dateutil<2.0' setup(name='pyactiveresource', version=version, description='ActiveResource for Python', author='Shopify', author_email='developers@shopify.com', url='https://github.com/Shopify/pyactiveresource/', packages=['pyactiveresource', 'pyactiveresource/testing'], license='MIT License', test_suite='test', install_requires=[ 'six', ], tests_require=[ python_dateutils_version, 'PyYAML', ], platforms=['any'], classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules'] ) " Update user api to real functionaliy,"/* global console, MashupPlatform */ var UserAPI = (function () { ""use strict""; var url = ""https://account.lab.fiware.org/user""; /***************************************************************** * C O N S T R U C T O R * *****************************************************************/ function UserAPI () { } /******************************************************************/ /* P R I V A T E F U N C T I O N S */ /******************************************************************/ function getUser(success, error) { MashupPlatform.http.makeRequest(url, { method: 'GET', requestHeaders: { ""X-FI-WARE-OAuth-Token"": ""true"", //""X-FI-WARE-OAuth-Header-Name"": ""X-Auth-Token"" ""x-fi-ware-oauth-get-parameter"": ""access_token"" }, onSuccess: success, onError: error }); } function test(success, error) { } /******************************************************************/ /* P U B L I C F U N C T I O N S */ /******************************************************************/ UserAPI.prototype = { getUser: function (accessToken, success, error) { getUser(accessToken, success, error); }, test: function (success, error) { test(success, error); } }; return UserAPI; })();","/* global console, MashupPlatform */ var UserAPI = (function () { ""use strict""; var url = ""https://account.lab.fiware.org/user""; /***************************************************************** * C O N S T R U C T O R * *****************************************************************/ function UserAPI () { } /******************************************************************/ /* P R I V A T E F U N C T I O N S */ /******************************************************************/ function getUser(accessToken, success, error) { MashupPlatform.http.makeRequest(url + ""/?access_token="" + accessToken, { method: 'GET', requestHeaders: { ""X-FI-WARE-OAuth-Token"": ""true"", ""X-FI-WARE-OAuth-Header-Name"": ""X-Auth-Token"" }, onSuccess: success, onError: error }); } function test(success, error) { } /******************************************************************/ /* P U B L I C F U N C T I O N S */ /******************************************************************/ UserAPI.prototype = { getUser: function (accessToken, success, error) { getUser(accessToken, success, error); }, test: function (success, error) { test(success, error); } }; return UserAPI; })();" Add test store unicode object,"from .base import IntegrationTest, AsyncUnitTestCase class BasicKVTests(IntegrationTest, AsyncUnitTestCase): def test_no_returnbody(self): async def go(): bucket = self.client.bucket(self.bucket_name) o = await bucket.new(self.key_name, ""bar"") await o.store(return_body=False) self.assertEqual(o.vclock, None) self.loop.run_until_complete(go()) def test_is_alive(self): self.assertTrue(self.client.is_alive()) def test_store_and_get(self): async def go(): bucket = self.client.bucket(self.bucket_name) rand = self.randint() obj = await bucket.new('foo', rand) await obj.store() obj = await bucket.get('foo') self.assertTrue(obj.exists) self.assertEqual(obj.bucket.name, self.bucket_name) self.assertEqual(obj.key, 'foo') self.assertEqual(obj.data, rand) obj2 = await bucket.new('baz', rand, 'application/json') obj2.charset = 'UTF-8' await obj2.store() obj2 = await bucket.get('baz') self.assertEqual(obj2.data, rand) self.loop.run_until_complete(go()) def test_store_object_with_unicode(self): async def go(): bucket = self.client.bucket(self.bucket_name) data = {'føø': u'éå'} obj = await bucket.new('foo', data) await obj.store() obj = await bucket.get('foo') self.assertEqual(obj.data, data) self.loop.run_until_complete(go()) ","from .base import IntegrationTest, AsyncUnitTestCase class BasicKVTests(IntegrationTest, AsyncUnitTestCase): def test_no_returnbody(self): async def go(): bucket = self.client.bucket(self.bucket_name) o = await bucket.new(self.key_name, ""bar"") await o.store(return_body=False) self.assertEqual(o.vclock, None) self.loop.run_until_complete(go()) def test_is_alive(self): self.assertTrue(self.client.is_alive()) def test_store_and_get(self): async def go(): bucket = self.client.bucket(self.bucket_name) rand = self.randint() obj = await bucket.new('foo', rand) await obj.store() obj = await bucket.get('foo') self.assertTrue(obj.exists) self.assertEqual(obj.bucket.name, self.bucket_name) self.assertEqual(obj.key, 'foo') self.assertEqual(obj.data, rand) obj2 = await bucket.new('baz', rand, 'application/json') obj2.charset = 'UTF-8' await obj2.store() obj2 = await bucket.get('baz') self.assertEqual(obj2.data, rand) self.loop.run_until_complete(go()) " Move date/time to the first csv column.,"import csv import sys import threading from time import sleep from datetime import datetime import msgpack import zmq context = zmq.Context() socket = context.socket(zmq.SUB) socket.setsockopt(zmq.SUBSCRIBE, b'') socket.bind(""tcp://*:4200"") terminate = threading.Event() def go(): global terminate writer = None firsttime = True with open('ani.csv', 'w', newline='') as csvfile: while not terminate.is_set(): try: msg = socket.recv(flags=zmq.NOBLOCK) except zmq.Again as e: # No message received continue orig, msgpackdata = msg.split(b' ', 1) unpacked = msgpack.unpackb(msgpackdata, encoding='utf-8') if not isinstance(unpacked, dict): print(""Message garbled: {}"", unpacked) continue if firsttime: headers = ['datetime'] + list(unpacked.keys()) writer = csv.DictWriter(csvfile, fieldnames=headers) writer.writeheader() firsttime = False unpacked.update({'datetime': str(datetime.now())}) writer.writerow(unpacked) print(msgpackdata, unpacked) anithread = threading.Thread(target=go) anithread.start() while True: try: sleep(1) except KeyboardInterrupt: terminate.set() anithread.join() break ","import csv import sys import threading from time import sleep from datetime import datetime import msgpack import zmq context = zmq.Context() socket = context.socket(zmq.SUB) socket.setsockopt(zmq.SUBSCRIBE, b'') socket.bind(""tcp://*:4200"") terminate = threading.Event() def go(): global terminate writer = None firsttime = True with open('ani.csv', 'w', newline='') as csvfile: while not terminate.is_set(): try: msg = socket.recv(flags=zmq.NOBLOCK) except zmq.Again as e: # No message received continue orig, msgpackdata = msg.split(b' ', 1) unpacked = msgpack.unpackb(msgpackdata, encoding='utf-8') if not isinstance(unpacked, dict): print(""Message garbled: {}"", unpacked) continue unpacked.update({'datetime': str(datetime.now())}) if firsttime: writer = csv.DictWriter(csvfile, fieldnames=list(unpacked.keys())) writer.writeheader() firsttime = False writer.writerow(unpacked) print(msgpackdata, unpacked) anithread = threading.Thread(target=go) anithread.start() while True: try: sleep(1) except KeyboardInterrupt: terminate.set() anithread.join() break " FEAT(Resolvers): Add a new settings allowing to set manually the language code of the url resolve when calling the resolver,"# -*- coding:utf-8 -*- # Standard library imports from __future__ import unicode_literals import uuid import requests from django.core.exceptions import ImproperlyConfigured from django.utils import translation import slumber from .conf import settings as local_settings from .encoding import prefix_kwargs from .utils import get_api_url from .constants import RESOLVE_API_VIEW_URL def resolve_url(site_id, view_name, args=None, kwargs=None, language=None): if site_id not in local_settings.SITES: raise ImproperlyConfigured(""[Cross site] Configuration error: The given site identifier is not configured in the settings"") site_conf = local_settings.SITES[site_id] language = translation.get_language() if language is None else language resolve_args = {'view_name': view_name, 'args': args, 'language': language} if kwargs: kwargs_prefix = uuid.uuid4() resolve_args[""kwargs_prefix""] = kwargs_prefix prefixed_kwargs = prefix_kwargs(kwargs_prefix, kwargs) resolve_args.update(prefixed_kwargs) api_url = get_api_url(site_conf[""scheme""], site_conf[""domain""]) session = requests.Session() session.verify = local_settings.VERIFY_SSL_CERT api = slumber.API(api_url, session=session, auth=local_settings.API_AUTH_CREDENTIALS) resolver = RESOLVE_API_VIEW_URL.replace('/', '') url = getattr(api, resolver).get(**resolve_args)['url'] return url ","# -*- coding:utf-8 -*- # Standard library imports from __future__ import unicode_literals import uuid import requests from django.core.exceptions import ImproperlyConfigured from django.utils import translation import slumber from .conf import settings as local_settings from .encoding import prefix_kwargs from .utils import get_api_url from .constants import RESOLVE_API_VIEW_URL def resolve_url(site_id, view_name, args=None, kwargs=None): if site_id not in local_settings.SITES: raise ImproperlyConfigured(""[Cross site] Configuration error: The given site identifier is not configured in the settings"") site_conf = local_settings.SITES[site_id] language = translation.get_language() resolve_args = {'view_name': view_name, 'args': args, 'language': language} if kwargs: kwargs_prefix = uuid.uuid4() resolve_args[""kwargs_prefix""] = kwargs_prefix prefixed_kwargs = prefix_kwargs(kwargs_prefix, kwargs) resolve_args.update(prefixed_kwargs) api_url = get_api_url(site_conf[""scheme""], site_conf[""domain""]) session = requests.Session() session.verify = local_settings.VERIFY_SSL_CERT api = slumber.API(api_url, session=session, auth=local_settings.API_AUTH_CREDENTIALS) resolver = RESOLVE_API_VIEW_URL.replace('/', '') url = getattr(api, resolver).get(**resolve_args)['url'] return url " "Add a check to see if we're using the same noun or verb, and lookup a new one if true."," var butter = (function($){ var verbs = null; var nouns = null; var lastVerb = null; var lastNoun = null; /** * SHOW ME WHAT YOU GOT */ function onPurposeRequest() { $('#verb').html(getVerbFromDictionary()); $('#noun').html(getNounFromDictionary()); } function init() { $('#purpose').on('click', onPurposeRequest); } function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } //Recursion for kicks. function getKindaRandomVerbIndex() { var v = getRandomInt(0, verbs.length-1); if (v == lastVerb) { v = getKindaRandomVerbIndex(); } lastVerb = v; return v; } function getKindaRandomNounIndex() { var n = getRandomInt(0, nouns.length-1); if (n == lastNoun) { n = getKindaRandomNounIndex(); } lastNoun = n; return n; } function getVerbFromDictionary() { var v = 'pass'; if (verbs != null) { v = verbs[getKindaRandomVerbIndex()]; } return v; } function getNounFromDictionary() { var n = 'butter'; if (nouns != null) { n = nouns[getKindaRandomNounIndex()]; } return n; } function loadData() { $.getJSON('words.json', function(data) { verbs = data.verbs; nouns = data.nouns; }); } /** * fire the plasma cannon */ (function __init(){ $(document).ready(init); //Load files loadData(); })(); })(jQuery);"," var butter = (function($){ var verbs = null; var nouns = null; /** * SHOW ME WHAT YOU GOT */ function onPurposeRequest() { $('#verb').html(getVerbFromDictionary()); $('#noun').html(getNounFromDictionary()); } function init() { $('#purpose').on('click', onPurposeRequest); } function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function getVerbFromDictionary() { var v = 'pass'; if (verbs != null) { v = verbs[getRandomInt(0, verbs.length-1)]; } return v; } function getNounFromDictionary() { var n = 'butter'; if (nouns != null) { n = nouns[getRandomInt(0, verbs.length-1)]; } return n; } function loadData() { $.getJSON('words.json', function(data) { verbs = data.verbs; nouns = data.nouns; }); } /** * fire the plasma cannon */ (function __init(){ $(document).ready(init); //Load files loadData(); })(); })(jQuery);" Fix mdui_description 'nl' always having 'en' value.,"<?php use OpenConext\Component\EngineBlockMetadata\Entity\AbstractRole; class EngineBlock_Corto_Mapper_Metadata_Entity_SsoDescriptor_UiInfo_Description { /** * @var AbstractRole */ private $_entity; public function __construct(AbstractRole $entity) { $this->_entity = $entity; } public function mapTo(array $rootElement) { $descriptions = array(); if (!empty($this->_entity->descriptionNl)) { $descriptions['nl'] = $this->_entity->descriptionNl; } if (!empty($this->_entity->descriptionEn)) { $descriptions['en'] = $this->_entity->descriptionEn; } if (empty($descriptions)) { return $rootElement; } if (!isset($rootElement['md:Extensions'])) { $rootElement['md:Extensions'] = array(); } if (!isset($rootElement['md:Extensions']['mdui:UIInfo'])) { $rootElement['md:Extensions']['mdui:UIInfo'] = array(0=>array()); } foreach($descriptions as $languageCode => $value) { if(empty($value)) { continue; } $rootElement['md:Extensions']['mdui:UIInfo'][0]['mdui:Description'][] = array( EngineBlock_Corto_XmlToArray::ATTRIBUTE_PFX . 'xml:lang' => $languageCode, EngineBlock_Corto_XmlToArray::VALUE_PFX => $value ); } return $rootElement; } } ","<?php use OpenConext\Component\EngineBlockMetadata\Entity\AbstractRole; class EngineBlock_Corto_Mapper_Metadata_Entity_SsoDescriptor_UiInfo_Description { /** * @var AbstractRole */ private $_entity; public function __construct(AbstractRole $entity) { $this->_entity = $entity; } public function mapTo(array $rootElement) { $descriptions = array(); if (!empty($this->_entity->descriptionEn)) { $descriptions['nl'] = $this->_entity->descriptionEn; } if (!empty($this->_entity->descriptionNl)) { $descriptions['en'] = $this->_entity->descriptionEn; } if (empty($descriptions)) { return $rootElement; } if (!isset($rootElement['md:Extensions'])) { $rootElement['md:Extensions'] = array(); } if (!isset($rootElement['md:Extensions']['mdui:UIInfo'])) { $rootElement['md:Extensions']['mdui:UIInfo'] = array(0=>array()); } foreach($descriptions as $languageCode => $value) { if(empty($value)) { continue; } $rootElement['md:Extensions']['mdui:UIInfo'][0]['mdui:Description'][] = array( EngineBlock_Corto_XmlToArray::ATTRIBUTE_PFX . 'xml:lang' => $languageCode, EngineBlock_Corto_XmlToArray::VALUE_PFX => $value ); } return $rootElement; } } " Simplify validate method in FormField.,"from django.db import models from django import forms from django.utils.translation import ugettext_lazy as _ from .backends import detect_backend, UnknownIdException, \ UnknownBackendException __all__ = ('EmbedVideoField', 'EmbedVideoFormField') class EmbedVideoField(models.URLField): """""" Model field for embeded video. Descendant of :py:class:`django.db.models.URLField`. """""" def formfield(self, **kwargs): defaults = {'form_class': EmbedVideoFormField} defaults.update(kwargs) return super(EmbedVideoField, self).formfield(**defaults) def south_field_triple(self): from south.modelsinspector import introspector cls_name = '%s.%s' % ( self.__class__.__module__, self.__class__.__name__ ) args, kwargs = introspector(self) return (cls_name, args, kwargs) class EmbedVideoFormField(forms.URLField): """""" Form field for embeded video. Descendant of :py:class:`django.forms.URLField` """""" def validate(self, url): # if empty url is not allowed throws an exception super(EmbedVideoFormField, self).validate(url) if not url: return try: detect_backend(url) except UnknownBackendException: raise forms.ValidationError(_(u'URL could not be recognized.')) except UnknownIdException: raise forms.ValidationError(_(u'ID of this video could not be \ recognized.')) return url ","from django.db import models from django import forms from django.utils.translation import ugettext_lazy as _ from .backends import detect_backend, UnknownIdException, \ UnknownBackendException __all__ = ('EmbedVideoField', 'EmbedVideoFormField') class EmbedVideoField(models.URLField): """""" Model field for embeded video. Descendant of :py:class:`django.db.models.URLField`. """""" def formfield(self, **kwargs): defaults = {'form_class': EmbedVideoFormField} defaults.update(kwargs) return super(EmbedVideoField, self).formfield(**defaults) def south_field_triple(self): from south.modelsinspector import introspector cls_name = '%s.%s' % ( self.__class__.__module__, self.__class__.__name__ ) args, kwargs = introspector(self) return (cls_name, args, kwargs) class EmbedVideoFormField(forms.URLField): """""" Form field for embeded video. Descendant of :py:class:`django.forms.URLField` """""" def validate(self, url): super(EmbedVideoFormField, self).validate(url) if url: try: detect_backend(url) except UnknownBackendException: raise forms.ValidationError(_(u'URL could not be recognized.')) except UnknownIdException: raise forms.ValidationError(_(u'ID of this video could not be \ recognized.')) return url " Make argument types more specific.,"<?php namespace Sil\SilAuth\auth; use Psr\Log\LoggerInterface; use Sil\Idp\IdBroker\Client\IdBrokerClient; class IdBroker { /** @var IdBrokerClient */ protected $client; /** @var LoggerInterface */ protected $logger; /** * * @param string $baseUri The base of the API's URL. * Example: 'https://api.example.com/'. * @param string $accessToken Your authorization access (bearer) token. * @param LoggerInterface $logger */ public function __construct( string $baseUri, string $accessToken, LoggerInterface $logger ) { $this->logger = $logger; $this->client = new IdBrokerClient($baseUri, $accessToken); } /** * Attempt to authenticate with the given username and password, returning * the attributes for that user if the credentials were acceptable (or null * if they were not acceptable, since there is no authenticated user in that * situation). * * @param string $username The username. * @param string $password The password. * @return array|null The user's attributes (if successful), otherwise null. */ public function getAuthenticatedUser(string $username, string $password) { $result = $this->client->authenticate([ 'username' => $username, 'password' => $password, ]); $statusCode = $result['statusCode'] ?? null; if (intval($statusCode) === 200) { unset($result['statusCode']); return $result; } return null; } } ","<?php namespace Sil\SilAuth\auth; use Psr\Log\LoggerInterface; use Sil\Idp\IdBroker\Client\IdBrokerClient; class IdBroker { /** @var IdBrokerClient */ protected $client; /** @var LoggerInterface */ protected $logger; /** * * @param string $baseUri The base of the API's URL. * Example: 'https://api.example.com/'. * @param string $accessToken Your authorization access (bearer) token. * @param LoggerInterface $logger */ public function __construct($baseUri, $accessToken, LoggerInterface $logger) { $this->logger = $logger; $this->client = new IdBrokerClient($baseUri, $accessToken); } /** * Attempt to authenticate with the given username and password, returning * the attributes for that user if the credentials were acceptable (or null * if they were not acceptable, since there is no authenticated user in that * situation). * * @param string $username The username. * @param string $password The password. * @return array|null The user's attributes (if successful), otherwise null. */ public function getAuthenticatedUser(string $username, string $password) { $result = $this->client->authenticate([ 'username' => $username, 'password' => $password, ]); $statusCode = $result['statusCode'] ?? null; if (intval($statusCode) === 200) { unset($result['statusCode']); return $result; } return null; } } " Disable steps that are not needed in Highcharts Editor,"angular.module('yds').directive('ydsWorkbenchNew', ['$ocLazyLoad', '$timeout', '$window', 'Data', 'Basket', 'Workbench', function ($ocLazyLoad, $timeout, $window, Data, Basket, Workbench) { return { restrict: 'E', scope: { lang: '@', userId: '@' }, templateUrl: ((typeof Drupal != 'undefined') ? Drupal.settings.basePath + Drupal.settings.yds_project.modulePath + '/' : '') + 'templates/workbench-new.html', link: function (scope, element) { scope.ydsAlert = """"; var editorContainer = angular.element(element[0].querySelector('.highcharts-editor-container')); //if userId is undefined or empty, stop the execution of the directive if (_.isUndefined(scope.userId) || scope.userId.trim().length == 0) { scope.ydsAlert = ""The YDS component is not properly configured."" + ""Please check the corresponding documentation section""; return false; } //check if the language attr is defined, else assign default value if (_.isUndefined(scope.lang) || scope.lang.trim() == """") scope.lang = ""en""; var editorOptions = { features: ""import templates customize export"" }; // Load the required CSS & JS files for the Editor $ocLazyLoad.load([ ""css/highcharts-editor.min.css"", ""lib/highcharts-editor.js"" ]).then(function () { // Start the Highcharts Editor highed.ready(function () { highed.Editor(editorContainer[0], editorOptions); }); }); } } } ]); ","angular.module('yds').directive('ydsWorkbenchNew', ['$ocLazyLoad', '$timeout', '$window', 'Data', 'Basket', 'Workbench', function ($ocLazyLoad, $timeout, $window, Data, Basket, Workbench) { return { restrict: 'E', scope: { lang: '@', userId: '@' }, templateUrl: ((typeof Drupal != 'undefined') ? Drupal.settings.basePath + Drupal.settings.yds_project.modulePath + '/' : '') + 'templates/workbench-new.html', link: function (scope, element) { scope.ydsAlert = """"; var editorContainer = angular.element(element[0].querySelector('.highcharts-editor-container')); //if userId is undefined or empty, stop the execution of the directive if (_.isUndefined(scope.userId) || scope.userId.trim().length == 0) { scope.ydsAlert = ""The YDS component is not properly configured."" + ""Please check the corresponding documentation section""; return false; } //check if the language attr is defined, else assign default value if (_.isUndefined(scope.lang) || scope.lang.trim() == """") scope.lang = ""en""; // Load the required CSS & JS files for the Editor $ocLazyLoad.load([ ""css/highcharts-editor.min.css"", ""lib/highcharts-editor.js"" ]).then(function () { // Start the Highcharts Editor highed.ready(function () { highed.Editor(editorContainer[0]); }); }); } } } ]); " Update redirect URI for custom provider.,"<?php use Illuminate\Database\Seeder; use Northstar\Models\Client; use Northstar\Auth\Scope; class ClientTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('clients')->delete(); // For easy testing, we'll seed one client with all scopes... Client::create([ 'title' => 'Trusted Test Client', 'description' => 'This is an example OAuth client seeded with your local Northstar installation. It was automatically given all scopes that were defined when it was created.', 'client_id' => 'trusted-test-client', 'client_secret' => 'secret1', 'redirect_uri' => [ 'http://northstar.dev:8000', 'http://dev.dosomething.org:8888/openid-connect/northstar', ], 'allowed_grants' => ['authorization_code', 'password', 'client_credentials'], 'scope' => collect(Scope::all())->keys()->toArray(), ]); // ..and one with limited scopes. Client::create([ 'title' => 'Untrusted Test Client', 'description' => 'This is an example OAuth client seeded with your local Northstar installation. It is only given the user scope, and can be used to simulate untrusted clients (for example, the mobile app).', 'client_id' => 'untrusted-test-client', 'client_secret' => 'secret2', 'allowed_grants' => ['password'], 'scope' => ['user'], ]); } } ","<?php use Illuminate\Database\Seeder; use Northstar\Models\Client; use Northstar\Auth\Scope; class ClientTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('clients')->delete(); // For easy testing, we'll seed one client with all scopes... Client::create([ 'title' => 'Trusted Test Client', 'description' => 'This is an example OAuth client seeded with your local Northstar installation. It was automatically given all scopes that were defined when it was created.', 'client_id' => 'trusted-test-client', 'client_secret' => 'secret1', 'redirect_uri' => [ 'http://northstar.dev:8000', 'http://dev.dosomething.org:8888/openid-connect/generic', ], 'allowed_grants' => ['authorization_code', 'password', 'client_credentials'], 'scope' => collect(Scope::all())->keys()->toArray(), ]); // ..and one with limited scopes. Client::create([ 'title' => 'Untrusted Test Client', 'description' => 'This is an example OAuth client seeded with your local Northstar installation. It is only given the user scope, and can be used to simulate untrusted clients (for example, the mobile app).', 'client_id' => 'untrusted-test-client', 'client_secret' => 'secret2', 'allowed_grants' => ['password'], 'scope' => ['user'], ]); } } " Test equals overridden on NamedVehicleMessage.,"package com.openxc.messages; import java.util.HashMap; import junit.framework.TestCase; import org.junit.Test; import org.junit.Before; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import android.os.Parcel; @Config(emulateSdk = 18, manifest = Config.NONE) @RunWith(RobolectricTestRunner.class) public class NamedVehicleMessageTest extends TestCase { NamedVehicleMessage message; HashMap<String, Object> data; @Before public void setup() { data = new HashMap<String, Object>(); data.put(""value"", Double.valueOf(42)); message = new NamedVehicleMessage(""foo"", data); } @Test public void testName() { assertEquals(""foo"", message.getName()); } @Test public void testExtractsNameFromValues() { data.put(""name"", ""bar""); message = new NamedVehicleMessage(data); assertEquals(""bar"", message.getName()); assertFalse(message.contains(""name"")); } @Test public void sameEquals() { assertEquals(message, message); } @Test public void sameNameAndValueEquals() { NamedVehicleMessage anotherMessage = new NamedVehicleMessage(""foo"", data); assertEquals(message, anotherMessage); } @Test public void testWriteAndReadFromParcel() { Parcel parcel = Parcel.obtain(); message.writeToParcel(parcel, 0); // Reset parcel for reading parcel.setDataPosition(0); VehicleMessage createdFromParcel = VehicleMessage.CREATOR.createFromParcel(parcel); assertTrue(message instanceof NamedVehicleMessage); assertEquals(message, createdFromParcel); } } ","package com.openxc.messages; import java.util.HashMap; import junit.framework.TestCase; import org.junit.Test; import org.junit.Before; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import android.os.Parcel; @Config(emulateSdk = 18, manifest = Config.NONE) @RunWith(RobolectricTestRunner.class) public class NamedVehicleMessageTest extends TestCase { NamedVehicleMessage message; HashMap<String, Object> data; @Before public void setup() { data = new HashMap<String, Object>(); data.put(""value"", Double.valueOf(42)); message = new NamedVehicleMessage(""foo"", data); } @Test public void testName() { assertEquals(""foo"", message.getName()); } @Test public void testExtractsNameFromValues() { data.put(""name"", ""bar""); message = new NamedVehicleMessage(data); assertEquals(""bar"", message.getName()); assertFalse(message.contains(""name"")); } @Test public void testWriteAndReadFromParcel() { Parcel parcel = Parcel.obtain(); message.writeToParcel(parcel, 0); // Reset parcel for reading parcel.setDataPosition(0); VehicleMessage createdFromParcel = VehicleMessage.CREATOR.createFromParcel(parcel); assertTrue(message instanceof NamedVehicleMessage); assertEquals(message, createdFromParcel); } } " Sort lessons by name when retrieving from db,"package se.kits.gakusei.content.repository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import se.kits.gakusei.content.model.Lesson; import se.kits.gakusei.content.model.Nugget; import java.util.List; public interface LessonRepository extends CrudRepository<Lesson, Long> { Lesson findByName(String name); List<Nugget> findNuggetsByTwoFactTypes( @Param(""lessonName"") String lessonName, @Param(""factType1"") String questionType, @Param(""factType2"") String answerType); List<Nugget> findNuggetsBySuccessrate( @Param(""username"") String username, @Param(""lessonName"") String lessonName, @Param(""factType1"") String questionType, @Param(""factType2"") String answerType); List<Nugget> findUnansweredNuggets( @Param(""username"") String username, @Param(""lessonName"") String lessonName, @Param(""factType1"") String questionType, @Param(""factType2"") String answerType); @Query(""select l from Lesson l where not l.description = 'quiz' order by l.name"") List<Lesson> findVocabularyLessons(); @Query(""select l from Lesson l where l.description = 'quiz' order by l.name"") List<Lesson> findQuizLessons(); } ","package se.kits.gakusei.content.repository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import se.kits.gakusei.content.model.Lesson; import se.kits.gakusei.content.model.Nugget; import java.util.List; public interface LessonRepository extends CrudRepository<Lesson, Long> { Lesson findByName(String name); List<Nugget> findNuggetsByTwoFactTypes( @Param(""lessonName"") String lessonName, @Param(""factType1"") String questionType, @Param(""factType2"") String answerType); List<Nugget> findNuggetsBySuccessrate( @Param(""username"") String username, @Param(""lessonName"") String lessonName, @Param(""factType1"") String questionType, @Param(""factType2"") String answerType); List<Nugget> findUnansweredNuggets( @Param(""username"") String username, @Param(""lessonName"") String lessonName, @Param(""factType1"") String questionType, @Param(""factType2"") String answerType); @Query(""select l from Lesson l where not l.description = 'quiz'"") List<Lesson> findVocabularyLessons(); @Query(""select l from Lesson l where l.description = 'quiz'"") List<Lesson> findQuizLessons(); } " Add better connection management ...,"#!/usr/bin/python # -*- coding: <encoding name> -*- import os import sys import time import re import MySQLdb from MySQLdb import cursors class mysql: cn = None host = None port = None user = None passw = None connected = False def __init__(self, host, user, passw, db, port=3306): self.port = port self.host = host self.user = user self.passw = passw self.db = db if not self.connect(): self.connected = False def connect(self): """""" connect to the mysql db """""" try: if self.connected: return True else: self.cn = MySQLdb.connect( host=self.host, user=self.user, passwd=self.passw, db=self.db, port=self.port) self.connected = True return True except: self.connected = False return False def querySelect(self, query): """""" do the select query and return the result as an array of dictionaries """""" if not self.connected: self.connect() data = [] cur = self.cn.cursor(cursors.DictCursor) try: cur.execute(query) except: return False data = cur.fetchall() cur.close() return data ","#!/usr/bin/python # -*- coding: <encoding name> -*- import os import sys import time import re import MySQLdb from MySQLdb import cursors class mysql: cn = None host = None port = None user = None passw = None def __init__(self, host, user, passw, db, port=3306): self.port = port self.host = host self.user = user self.passw = passw self.db = db if not self.connect(): return False def connect(self): """""" connect to the mysql db """""" try: self.cn = MySQLdb.connect( host=self.host, user=self.user, passwd=self.passw, db=self.db, port=self.port) return True except: return False def querySelect(self, query): """""" do the select query and return the result as an array of dictionaries """""" data = [] cur = self.cn.cursor(cursors.DictCursor) try: cur.execute(query) except: return False data = cur.fetchall() cur.close() return data " Swap public and static for consistency,"package yokohama.unit.position; import java.nio.file.Path; import java.util.Optional; import lombok.Value; @Value public class Span { private final Optional<Path> sourcePath; private final Position start; private final Position end; public String getFileName() { if (!sourcePath.isPresent()) return ""?""; Path path = sourcePath.get(); int nameCount = path.getNameCount(); if (nameCount == 0) return ""?""; String fileName = path.getName(nameCount -1).toString(); return fileName.equals("""") ? ""?"" : fileName; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(sourcePath.isPresent() ? sourcePath.get().toString() : ""?""); sb.append("":""); sb.append(start.toString()); if (!end.isDummy()) { sb.append(""-""); sb.append(end.toString()); } return sb.toString(); } public static Span of(Path path) { return new Span(Optional.of(path), Position.dummyPos(), Position.dummyPos()); } public static Span of(Path path, Position start) { return new Span(Optional.of(path), start, Position.dummyPos()); } public static Span of(Path path, Position start, Position end) { return new Span(Optional.of(path), start, end); } private static Span dummySpan = new Span( Optional.empty(), Position.dummyPos(), Position.dummyPos()); public static Span dummySpan() { return dummySpan; } } ","package yokohama.unit.position; import java.nio.file.Path; import java.util.Optional; import lombok.Value; @Value public class Span { private final Optional<Path> sourcePath; private final Position start; private final Position end; public String getFileName() { if (!sourcePath.isPresent()) return ""?""; Path path = sourcePath.get(); int nameCount = path.getNameCount(); if (nameCount == 0) return ""?""; String fileName = path.getName(nameCount -1).toString(); return fileName.equals("""") ? ""?"" : fileName; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(sourcePath.isPresent() ? sourcePath.get().toString() : ""?""); sb.append("":""); sb.append(start.toString()); if (!end.isDummy()) { sb.append(""-""); sb.append(end.toString()); } return sb.toString(); } public static Span of(Path path) { return new Span(Optional.of(path), Position.dummyPos(), Position.dummyPos()); } public static Span of(Path path, Position start) { return new Span(Optional.of(path), start, Position.dummyPos()); } static public Span of(Path path, Position start, Position end) { return new Span(Optional.of(path), start, end); } private static Span dummySpan = new Span( Optional.empty(), Position.dummyPos(), Position.dummyPos()); public static Span dummySpan() { return dummySpan; } } " Rename the DB from mydb to rose,"var debug = require('debug')('rose'); var mongoose = require('mongoose'); var mongoURI = process.env.MONGOLAB_URI || 'mongodb://localhost/rose'; debug('Connecting to MongoDB at ' + mongoURI + '...'); mongoose.connect(mongoURI); var featureSchema = new mongoose.Schema({ name: { type: String, required: true }, examples: { type: [{ technology: { type: String, required: true }, snippets: { type: [String], required: true } }], required: true } }); featureSchema.statics.search = function (query) { return this.find({ $or: [ { name: new RegExp(query, 'i') }, { examples: { $elemMatch: { $or: [ { technology: new RegExp(query, 'i') }, { snippets: new RegExp(query, 'i') } ] }}}, ]}) .lean() .select('-__v -_id -examples._id') .exec(); }; module.exports = mongoose.model('Feature', featureSchema); ","var debug = require('debug')('rose'); var mongoose = require('mongoose'); var mongoURI = process.env.MONGOLAB_URI || 'mongodb://localhost/mydb'; debug('Connecting to MongoDB at ' + mongoURI + '...'); mongoose.connect(mongoURI); var featureSchema = new mongoose.Schema({ name: { type: String, required: true }, examples: { type: [{ technology: { type: String, required: true }, snippets: { type: [String], required: true } }], required: true } }); featureSchema.statics.search = function (query) { return this.find({ $or: [ { name: new RegExp(query, 'i') }, { examples: { $elemMatch: { $or: [ { technology: new RegExp(query, 'i') }, { snippets: new RegExp(query, 'i') } ] }}}, ]}) .lean() .select('-__v -_id -examples._id') .exec(); }; module.exports = mongoose.model('Feature', featureSchema); " Make generating php doc work again,"<?php namespace Bolt\Storage\Entity; use Bolt\Storage\ContentLegacyService; /** * Entity for Content. * * @method integer getId() * @method string getSlug() * @method integer getOwnerid() * @method string getStatus() * @method array getTemplatefields() * @method setId(integer $id) * @method setSlug(string $slug) * @method setOwnerid(integer $ownerid) * @method setStatus(string $status) * @method getTemplatefields(array $templatefields) */ class Content extends Entity { protected $_contenttype; protected $_legacy; protected $id; protected $slug; protected $datecreated; protected $datechanged; protected $datepublish = null; protected $datedepublish = null; protected $ownerid; protected $status; protected $templatefields; public function getDatecreated() { if (!$this->datecreated) { return new \DateTime(); } return $this->datecreated; } public function getDatechanged() { if (!$this->datechanged) { return new \DateTime(); } return $this->datechanged; } public function getContenttype() { return $this->_contenttype; } public function setContenttype($value) { $this->_contenttype = $value; } public function setLegacyService(ContentLegacyService $service) { $this->_legacy = $service; $this->_legacy->initialize($this); } } ","<?php namespace Bolt\Storage\Entity; use Bolt\Storage\ContentLegacyService; /** * Entity for Content. * * @method integer getId() * @method string getSlug() * @method integer getOwnerid() * @method string getStatus() * @method array getTemplatefields() * @method setId(integer $id) * @method setSlug(string $slug) * @method setOwnerid(integer $ownerid) * @method setStatus(string $status) * @method getTemplatefields(array $templatefields) */ class Content extends Entity { protected $_contenttype; protected $_legacy; protected $id; protected $slug; protected $datecreated; protected $datechanged; protected $datepublish = null; protected $datedepublish = null; protected $ownerid; protected $status; protected $templatefields; public function getDatecreated() { if (!$this->datecreated) { return new \DateTime(); } return $this->datecreated; } public function getDatechanged() { if (!$this->datechanged) { return new \DateTime(); } return $this->datechanged; } public function getContenttype() { return $this->_contenttype; } public function setContenttype($value) { $this->_contenttype = $value; } public function setLegacyService(ContentLegacyService $service) { $this->_legacy = $service; $this->_legacy->initialize($this); } } " Update 'last_accessed_at' fallback to be clearer.,"<table id=""user-table"" class=""table""> <thead> <tr class=""row table-header""> <th class=""table-cell"">Name</th> <th class=""table-cell"">Contact Methods</th> <th class=""table-cell"">Last Visited</th> </tr> </thead> <tbody> @forelse($users as $user) <tr class=""table-row""> <td class=""table-cell""><a href=""{{ route('users.show', [$user->id]) }}"">{{ $user->display_name }}</a></td> <td class=""table-cell""> <code>{{ $user->email_preview }}</code> @if ($user->email_preview && $user->mobile_preview) <span class=""footnote""> and </span> @endif <code>{{ $user->mobile_preview }}</code> </td> <td class=""table-cell footnote""> {{ $user->last_accessed_at ? $user->last_accessed_at->diffForHumans() : 'N/A' }} </td> </tr> @empty @endforelse </tbody> </table> ","<table id=""user-table"" class=""table""> <thead> <tr class=""row table-header""> <th class=""table-cell"">Name</th> <th class=""table-cell"">Contact Methods</th> <th class=""table-cell"">Last Visited</th> </tr> </thead> <tbody> @forelse($users as $user) <tr class=""table-row""> <td class=""table-cell""><a href=""{{ route('users.show', [$user->id]) }}"">{{ $user->display_name }}</a></td> <td class=""table-cell""> <code>{{ $user->email_preview }}</code> @if ($user->email_preview && $user->mobile_preview) <span class=""footnote""> and </span> @endif <code>{{ $user->mobile_preview }}</code> </td> <td class=""table-cell footnote""> {{ $user->last_accessed_at ? $user->last_accessed_at->diffForHumans() : 'more than 2 years ago' }} </td> </tr> @empty @endforelse </tbody> </table> " Remove tests for storage adapter methods being removed.,"from unittest import TestCase from chatterbot.storage import StorageAdapter class StorageAdapterTestCase(TestCase): """""" This test case is for the StorageAdapter base class. Although this class is not intended for direct use, this test case ensures that exceptions requiring basic functionality are triggered when needed. """""" def setUp(self): super(StorageAdapterTestCase, self).setUp() self.adapter = StorageAdapter() def test_count(self): with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError): self.adapter.count() def test_filter(self): with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError): self.adapter.filter() def test_remove(self): with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError): self.adapter.remove('') def test_create(self): with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError): self.adapter.create() def test_update(self): with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError): self.adapter.update('') def test_get_random(self): with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError): self.adapter.get_random() def test_drop(self): with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError): self.adapter.drop() ","from unittest import TestCase from chatterbot.storage import StorageAdapter class StorageAdapterTestCase(TestCase): """""" This test case is for the StorageAdapter base class. Although this class is not intended for direct use, this test case ensures that exceptions requiring basic functionality are triggered when needed. """""" def setUp(self): super(StorageAdapterTestCase, self).setUp() self.adapter = StorageAdapter() def test_count(self): with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError): self.adapter.count() def test_find(self): with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError): self.adapter.find('') def test_filter(self): with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError): self.adapter.filter() def test_remove(self): with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError): self.adapter.remove('') def test_create(self): with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError): self.adapter.create() def test_update(self): with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError): self.adapter.update('') def test_get_random(self): with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError): self.adapter.get_random() def test_get_response_statements(self): with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError): self.adapter.get_response_statements() def test_drop(self): with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError): self.adapter.drop() " Use VARCHAR instead of LOB,"package org.fedoraproject.javadeptools.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity @Table public class ManifestEntry { @Id @GeneratedValue(generator = ""gen"") @GenericGenerator(name = ""gen"", strategy = ""increment"") private Long id; @ManyToOne @JoinColumn(name = ""fileArtifactId"", nullable = false) private FileArtifact fileArtifact; public ManifestEntry() { } public ManifestEntry(String key, String value) { this.key = key; this.value = value; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public FileArtifact getFileArtifact() { return fileArtifact; } public void setFileArtifact(FileArtifact fileArtifact) { this.fileArtifact = fileArtifact; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } private String key; @Column(columnDefinition = ""VARCHAR"") private String value; } ","package org.fedoraproject.javadeptools.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity @Table public class ManifestEntry { @Id @GeneratedValue(generator = ""gen"") @GenericGenerator(name = ""gen"", strategy = ""increment"") private Long id; @ManyToOne @JoinColumn(name = ""fileArtifactId"", nullable = false) private FileArtifact fileArtifact; public ManifestEntry() { } public ManifestEntry(String key, String value) { this.key = key; this.value = value; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public FileArtifact getFileArtifact() { return fileArtifact; } public void setFileArtifact(FileArtifact fileArtifact) { this.fileArtifact = fileArtifact; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } private String key; @Lob private String value; } " Add new script for running IGMF analysis.,"#!/usr/bin/env python from setuptools import setup, find_packages import os import sys from haloanalysis.version import get_git_version setup(name='haloanalysis', version=get_git_version(), license='BSD', packages=find_packages(exclude='tests'), include_package_data = True, classifiers=[ 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: Scientific/Engineering :: Astronomy', 'Development Status :: 4 - Beta', ], entry_points={'console_scripts': [ 'run-region-analysis = haloanalysis.scripts.region_analysis:main', 'run-halo-analysis = haloanalysis.scripts.halo_analysis:main', 'haloanalysis-aggregate = haloanalysis.scripts.aggregate:main', 'haloanalysis-stack = haloanalysis.scripts.stack:main', 'haloanalysis-fit-igmf = haloanalysis.scripts.fit_igmf:main', 'haloanalysis-make-html-table = haloanalysis.scripts.make_html_table:main', ]}, install_requires=['numpy >= 1.6.1', 'matplotlib >= 1.4.0', 'scipy >= 0.14', 'astropy >= 1.0', 'pyyaml', 'healpy', 'wcsaxes']) ","#!/usr/bin/env python from setuptools import setup, find_packages import os import sys from haloanalysis.version import get_git_version setup(name='haloanalysis', version=get_git_version(), license='BSD', packages=find_packages(exclude='tests'), include_package_data = True, classifiers=[ 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: Scientific/Engineering :: Astronomy', 'Development Status :: 4 - Beta', ], entry_points= {'console_scripts': [ 'run-region-analysis = haloanalysis.scripts.region_analysis:main', 'run-halo-analysis = haloanalysis.scripts.halo_analysis:main', 'haloanalysis-aggregate = haloanalysis.scripts.aggregate:main', 'haloanalysis-stack = haloanalysis.scripts.stack:main', 'haloanalysis-make-html-table = haloanalysis.scripts.make_html_table:main', ]}, install_requires=['numpy >= 1.6.1', 'matplotlib >= 1.4.0', 'scipy >= 0.14', 'astropy >= 1.0', 'pyyaml', 'healpy', 'wcsaxes']) " Add description to Poste in PostFixtures,"<?php /* Alexandre Couedelo @ 2015-02-17 20:15:24 Importé depuis Emagine/incipio */ namespace mgate\PersonneBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use mgate\PersonneBundle\Entity\Poste; class LoadPosteData implements FixtureInterface { /** * {@inheritDoc} */ public function load(ObjectManager $manager) { $postes = array( //Bureau ""Président"", ""Président par procuration"", ""Vice-président"", ""Trésorier"", ""Suiveur Manager Qualité"", ""Secrétaire général"", //ca ""Manager Qualité-Tréso"", ""Vice-Trésorier"", ""Binome Qualité"", ""Respo. Communication"", ""Respo. SI"", ""Respo. Dev'Co"", //Membre ""membre"", ""Intervenant"", ""Chef de Projet"", ); foreach($postes as $poste){ $p = new Poste(); $p->setIntitule($poste); $p->setDescription(""a completer""); $manager->persist($p); } $manager->flush(); } } ","<?php /* Alexandre Couedelo @ 2015-02-17 20:15:24 Importé depuis Emagine/incipio */ namespace mgate\PersonneBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use mgate\PersonneBundle\Entity\Poste; class LoadPosteData implements FixtureInterface { /** * {@inheritDoc} */ public function load(ObjectManager $manager) { $postes = array( //Bureau ""Président"", ""Vice-président"", ""Trésorier"", ""Suiveur Manager Qualité"", ""Secrétaire général"", //ca ""Manager Qualité-Tréso"", ""Vice-Trésorier"", ""Binome Qualité"", ""Respo. Communication"", ""Respo. SI"", ""Respo. Dev'Co"", //Membre ""membre"", ""Intervenant"", ""Chef de Projet"", ); foreach($postes as $poste){ $p = new Poste(); $p->setIntitule($poste); $manager->persist($p); } $manager->flush(); } } " Set focus to the first failed validation field.,"package com.strohwitwer.awesomevalidation.validator; import android.app.Activity; import android.widget.EditText; import com.strohwitwer.awesomevalidation.ValidationHolder; import com.strohwitwer.awesomevalidation.utils.ValidationCallback; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; public abstract class Validator { protected ArrayList<ValidationHolder> mValidationHolderList; public Validator() { mValidationHolderList = new ArrayList<ValidationHolder>(); } public void set(EditText editText, String regex, String errMsg) { Pattern pattern = Pattern.compile(regex); ValidationHolder validationHolder = new ValidationHolder(editText, pattern, errMsg); mValidationHolderList.add(validationHolder); } public void set(Activity activity, int viewId, String regex, int errMsgId) { EditText editText = (EditText) activity.findViewById(viewId); String errMsg = activity.getResources().getString(errMsgId); set(editText, regex, errMsg); } protected boolean checkFields(ValidationCallback callback) { boolean result = true; boolean hasFailed = false; for (ValidationHolder validationHolder : mValidationHolderList) { Matcher matcher = validationHolder.getPattern().matcher(validationHolder.getText()); if (!matcher.matches()) { callback.execute(validationHolder, matcher); if (!hasFailed) { EditText editText = validationHolder.getEditText(); editText.requestFocus(); editText.setSelection(editText.getText().length()); hasFailed = true; } result = false; } } return result; } public abstract boolean trigger(); public abstract void halt(); }","package com.strohwitwer.awesomevalidation.validator; import android.app.Activity; import android.widget.EditText; import com.strohwitwer.awesomevalidation.ValidationHolder; import com.strohwitwer.awesomevalidation.utils.ValidationCallback; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; public abstract class Validator { protected ArrayList<ValidationHolder> mValidationHolderList; public Validator() { mValidationHolderList = new ArrayList<ValidationHolder>(); } public void set(EditText editText, String regex, String errMsg) { Pattern pattern = Pattern.compile(regex); ValidationHolder validationHolder = new ValidationHolder(editText, pattern, errMsg); mValidationHolderList.add(validationHolder); } public void set(Activity activity, int viewId, String regex, int errMsgId) { EditText editText = (EditText) activity.findViewById(viewId); String errMsg = activity.getResources().getString(errMsgId); set(editText, regex, errMsg); } protected boolean checkFields(ValidationCallback callback) { boolean result = true; for (ValidationHolder validationHolder : mValidationHolderList) { Matcher matcher = validationHolder.getPattern().matcher(validationHolder.getText()); if (!matcher.matches()) { callback.execute(validationHolder, matcher); result = false; } } return result; } public abstract boolean trigger(); public abstract void halt(); }" Support multiple Flask apps on the same Aggregator instance,"import json from flask import request, Response from werkzeug.exceptions import BadRequest from werkzeug.test import EnvironBuilder class Aggregator(object): def __init__(self, app=None, endpoint=None): self.url_map = {} self.endpoint = endpoint or ""/aggregate"" if app: self.init_app(app) def init_app(self, app): app.add_url_rule(self.endpoint, view_func=self.post, methods=[""POST""], defaults={""app"": app}) def get_response(self, app, route): query_string = """" if '?' in route: route, query_string = route.split('?', 1) builder = EnvironBuilder(path=route, query_string=query_string) app.request_context(builder.get_environ()).push() return app.dispatch_request() def post(self, app): try: data = request.data.decode('utf-8') routes = json.loads(data) if not isinstance(routes, list): raise TypeError except (ValueError, TypeError) as e: raise BadRequest(""Can't get requests list."") def __generate(): data = None for route in routes: yield data + ', ' if data else '{' response = self.get_response(app, route) json_response = json.dumps(response) data = '""{}"": {}'.format(route, json_response) yield data + '}' return Response(__generate(), mimetype='application/json') ","import json from flask import request, Response from werkzeug.exceptions import BadRequest from werkzeug.test import EnvironBuilder class Aggregator(object): def __init__(self, app=None, endpoint=None): self.url_map = {} self.endpoint = endpoint or ""/aggregate"" if app: self.init_app(app) def init_app(self, app): self.app = app self.app.add_url_rule(self.endpoint, view_func=self.post, methods=[""POST""]) def get_response(self, route): query_string = """" if '?' in route: route, query_string = route.split('?', 1) builder = EnvironBuilder(path=route, query_string=query_string) self.app.request_context(builder.get_environ()).push() return self.app.dispatch_request() def post(self): try: data = request.data.decode('utf-8') routes = json.loads(data) if not isinstance(routes, list): raise TypeError except (ValueError, TypeError) as e: raise BadRequest(""Can't get requests list."") def __generate(): data = None for route in routes: yield data + ', ' if data else '{' response = self.get_response(route) json_response = json.dumps(response) data = '""{}"": {}'.format(route, json_response) yield data + '}' return Response(__generate(), mimetype='application/json') " Fix infrastructure spelling and clean up deprecated code,"const express = require('express'); const path = require('path'); const app = express(); app.use(express.static('./build')); app.get('/', function (req, res) { res.sendFile(path.join(__dirname, './build', 'index.html')); }); app.get('/infrastructure', function(req, res) { res.status(200).send({ regions : [ { name : ""east-1"", environments : [ { status : 'green', instanceCount : 12, trafficWeight: 0.3 } ] } ] }) }); app.get('/load', function(req, res) { res.status(200).send({ regions : [ { name : ""east-1"", environments : [ { errRate : 0.1, replicationLag : 0.7 } ] } ] }) }); app.listen(9000);","const express = require('express'); const path = require('path'); const app = express(); app.use(express.static('./build')); app.get('/', function (req, res) { res.sendFile(path.join(__dirname, './build', 'index.html')); }); app.get('/infrastucture', function(req, res) { res.send(200, { regions : [ { name : ""east-1"", environments : [ { status : 'green', instanceCount : 12, trafficWeight: 0.3 } ] } ] }) }); app.get('/load', function(req, res) { res.send(200, { regions : [ { name : ""east-1"", environments : [ { errRate : 0.1, replicationLag : 0.7 } ] } ] }) }); app.listen(9000);" Improve status and toasts in header.,"import { HeaderService } from ""./header.service.js""; export class HeaderTemplate { static update(render) { const start = Date.now(); /* eslint-disable indent */ render` <nav class=""flex flex-row bt bb mh5 center shadow-2""> <div class=""flex flex-wrap flex-row justify-around items-center min-w-70 logo""> <span class=""b""> <a href=""https://github.com/albertosantini/node-conpa"">ConPA 5</a> Asset Allocation App </span> </div> <div class=""flex flex-wrap flex-row items-center min-w-30 f7""> <div> <toasts></toasts> <div>${{ any: HeaderService.getStatus().then(({ namespace: status }) => { const end = Date.now(); return `${status.message} (${end - start}ms)`; }), placeholder: ""Loading..."" }}</div> </div> </div> </nav> `; /* eslint-enable indent */ } } ","import { HeaderService } from ""./header.service.js""; export class HeaderTemplate { static update(render) { const start = Date.now(); /* eslint-disable indent */ render` <nav class=""flex flex-row bt bb mw9 center shadow-2""> <div class=""flex flex-wrap flex-row justify-around items-center min-w-70 logo""> <span class=""b""> <a href=""https://github.com/albertosantini/node-conpa"">ConPA 5</a> Asset Allocation App </span> </div> <div class=""flex flex-wrap flex-row items-center min-w-30> <span class=""f7""> <toasts></toasts> <div>${{ any: HeaderService.getStatus().then(({ namespace: status }) => { const end = Date.now(); return `${status.message} (${end - start}ms)`; }), placeholder: ""Loading..."" }}</div> </span> </div> </nav> `; /* eslint-enable indent */ } } " Exclude testing files from deploy,"module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), sass: { options: { includePaths: ['app/bower_components/foundation/scss'] }, dist: { options: { outputStyle: 'default' }, files: { 'app/app.css': 'scss/app.scss' } } }, watch: { grunt: { files: ['Gruntfile.js'] }, sass: { files: 'scss/**/*.scss', tasks: ['sass'] } }, clean: ['../solartime-pages/'], copy: { main: { files: [ {expand: true, cwd: 'app/', src: ['**','!**/*_test.js','!index-async.html'], dest: '../solartime-pages/'} ] } }, }); grunt.loadNpmTasks('grunt-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.registerTask('build', ['sass']); grunt.registerTask('publish',['clean', 'copy']); grunt.registerTask('default', ['build','watch']); } ","module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), sass: { options: { includePaths: ['app/bower_components/foundation/scss'] }, dist: { options: { outputStyle: 'default' }, files: { 'app/app.css': 'scss/app.scss' } } }, watch: { grunt: { files: ['Gruntfile.js'] }, sass: { files: 'scss/**/*.scss', tasks: ['sass'] } }, clean: ['../solartime-pages/'], copy: { main: { files: [ {expand: true, cwd: 'app/', src: ['**'], dest: '../solartime-pages/'} ] } }, }); grunt.loadNpmTasks('grunt-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.registerTask('build', ['sass']); grunt.registerTask('publish',['clean', 'copy']); grunt.registerTask('default', ['build','watch']); } " Call backend view on delete account frontend,"import React, { Component } from 'react'; import {Button} from 'react-bootstrap'; import * as config from '../../config'; import axios from 'axios'; axios.defaults.withCredentials = true; class DeleteAccountForm extends Component { constructor(props) { super(props); this.state = { displayDeleteAccountMessage: false }; } handleDeleteAccountButton = () => { this.setState({displayDeleteAccountMessage: true}); } static get contextTypes() { return { router: React.PropTypes.object.isRequired, }; } handleDeleteAccountConfirmation = () => { axios.delete(config.backendUrl + '/delete_user') .then(res => { this.context.router.history.push('/'); }) .catch(error => { console.log(error); }) } handleDeleteAccountChangemind = () => { this.setState({displayDeleteAccountMessage: false}); } render() { return ( <div> <Button type=""submit"" bsStyle=""danger"" id=""delete-account"" onClick={this.handleDeleteAccountButton} > Delete account </Button> {this.state.displayDeleteAccountMessage ? <div className=""delete-account-confirmation""><b>We hate to see you leaving. Are you sure? <a onClick={this.handleDeleteAccountConfirmation}>Yes</a> <a onClick={this.handleDeleteAccountChangemind}>No</a></b></div> : null} </div> ); } } export default DeleteAccountForm; ","import React, { Component } from 'react'; import {Button} from 'react-bootstrap'; class DeleteAccountForm extends Component { constructor(props) { super(props); this.state = { displayDeleteAccountMessage: false }; } handleDeleteAccountButton = () => { this.setState({displayDeleteAccountMessage: true}); } handleDeleteAccountConfirmation = () => { console.log('Account deleted'); } handleDeleteAccountChangemind = () => { this.setState({displayDeleteAccountMessage: false}); } render() { return ( <div> <Button type=""submit"" bsStyle=""danger"" id=""delete-account"" onClick={this.handleDeleteAccountButton} > Delete account </Button> {this.state.displayDeleteAccountMessage ? <div className=""delete-account-confirmation""><b>We hate to see you leaving. Are you sure? <a onClick={this.handleDeleteAccountConfirmation}>Yes</a> <a onClick={this.handleDeleteAccountChangemind}>No</a></b></div> : null} </div> ); } } export default DeleteAccountForm; " Test (basics): Require target being in the tracked pool,"/** * Basics */ describe('Basics', () => { beforeEach(beforeEachHook); afterEach(afterEachHook); /** * Absolute tracking */ it('absolute tracking', async () => { let times = 0; let poolCopy; const targetOne = createTarget({ marginLeft: '-30px' }); const targetTwo = createTarget({ marginTop: '30px' }); const targetThree = createTarget({ marginTop: '-30px' }); new Tracker({ targets: document.getElementsByClassName('target'), snapshots: [ { callback({ DOMElement, pool }) { animate(DOMElement); times++; poolCopy = pool; } } ] }); await scroll(0, 10); expect(times).to.equal(1); expect(poolCopy).to.include(targetTwo); }); /** * Relative tracking */ it('relative tracking', async () => { let times = 0; let poolCopy; const targetOne = createTarget({ left: '-20px' }, bounds); const targetTwo = createTarget({ top: '-20px' }, bounds); const targetThree = createTarget({}, bounds); new Tracker({ targets: document.getElementsByClassName('target'), bounds, snapshots: [ { callback({ DOMElement, pool }) { animate(DOMElement); times++; poolCopy = pool; } } ] }); await scroll(0, 10); expect(times).to.equal(1); expect(poolCopy).to.include(targetThree); }); }); ","/** * Basics */ describe('Basics', () => { beforeEach(beforeEachHook); afterEach(afterEachHook); /** * Absolute tracking */ it('absolute tracking', async () => { let times = 0; const targetOne = createTarget({ marginLeft: '-30px' }); const targetTwo = createTarget({ marginTop: '30px' }); const targetThree = createTarget({ marginTop: '-30px' }); new Tracker({ targets: document.getElementsByClassName('target'), snapshots: [ { callback({ DOMElement }) { animate(DOMElement); times++; } } ] }); await scroll(0, 10); expect(times).to.equal(1); }); /** * Relative tracking */ it('relative tracking', async () => { let times = 0; let poolCopy; const targetOne = createTarget({ left: '-20px' }, bounds); const targetTwo = createTarget({ top: '-20px' }, bounds); const targetThree = createTarget({}, bounds); new Tracker({ targets: document.getElementsByClassName('target'), bounds, snapshots: [ { callback({ DOMElement, pool }) { animate(DOMElement); times++; poolCopy = pool; } } ] }); await scroll(0, 10); expect(times).to.equal(1); expect(poolCopy).to.include(targetThree); }); }); " Test Activity: Restore the full test with sample db since it causes SIGSEGV :-(,"package com.bitgrind.android; import java.util.Arrays; import jsqlite.Callback; import jsqlite.Exception; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.util.Log; public class SpatialiteTestActivity extends Activity { private static final String TAG = SpatialiteTestActivity.class.getName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); jsqlite.Database db = new jsqlite.Database(); try { db.open(Environment.getExternalStorageDirectory() + ""/spatialite_test.db"", jsqlite.Constants.SQLITE_OPEN_READONLY); Callback cb = new Callback() { @Override public void columns(String[] coldata) { Log.v(TAG, ""Columns: "" + Arrays.toString(coldata)); } @Override public void types(String[] types) { Log.v(TAG, ""Types: "" + Arrays.toString(types)); } @Override public boolean newrow(String[] rowdata) { Log.v(TAG, ""Row: "" + Arrays.toString(rowdata)); // Careful (from parent javadoc): // ""If true is returned the running SQLite query is aborted."" return false; } }; db.exec(""SELECT name, peoples, AsText(GaiaGeometry) from Towns where peoples > 350000 order by peoples DESC;"", cb); } catch (Exception e) { e.printStackTrace(); } } } ","package com.bitgrind.android; import java.util.Arrays; import jsqlite.Callback; import jsqlite.Exception; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.util.Log; public class SpatialiteTestActivity extends Activity { private static final String TAG = SpatialiteTestActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); jsqlite.Database db = new jsqlite.Database(); try { db.open(Environment.getExternalStorageDirectory() + ""/spatialite-test.db"", jsqlite.Constants.SQLITE_OPEN_CREATE); Callback cb = new Callback() { @Override public void columns(String[] coldata) { Log.v(TAG, ""Columns: "" + Arrays.toString(coldata)); } @Override public void types(String[] types) { Log.v(TAG, ""Types: "" + Arrays.toString(types)); } @Override public boolean newrow(String[] rowdata) { Log.v(TAG, ""Row: "" + Arrays.toString(rowdata)); // Careful (from parent javadoc): // ""If true is returned the running SQLite query is aborted."" return false; } }; db.exec(""SELECT spatialite_version();"", cb); } catch (Exception e) { Log.e(TAG, ""Exception caught"", e); } } } " Add action for possible future content,"<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Application\Controller; use Zend\Mvc\Controller\AbstractActionController; use Zend\View\Model\ViewModel; class IndexController extends AbstractActionController { public function indexAction() { $this->layout('layout/layout_home'); return new ViewModel(); } public function registerAction() { return new ViewModel(); } public function venueAction() { return new ViewModel(); } public function privacyAction() { return new ViewModel(); } public function diversityAction() { return new ViewModel(); } public function conductAction() { return new ViewModel(); } public function expectAction() { return new ViewModel(); } public function aboutAction() { return new ViewModel(); } public function eventsAction() { return new ViewModel(); } public function unconAction() { return new ViewModel(); } public function sitemapAction() { $this->layout('layout/xml'); } } ","<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Application\Controller; use Zend\Mvc\Controller\AbstractActionController; use Zend\View\Model\ViewModel; class IndexController extends AbstractActionController { public function indexAction() { $this->layout('layout/layout_home'); return new ViewModel(); } public function registerAction() { return new ViewModel(); } public function venueAction() { return new ViewModel(); } public function privacyAction() { return new ViewModel(); } public function diversityAction() { return new ViewModel(); } public function conductAction() { return new ViewModel(); } public function aboutAction() { return new ViewModel(); } public function eventsAction() { return new ViewModel(); } public function unconAction() { return new ViewModel(); } public function sitemapAction() { $this->layout('layout/xml'); } } " "Fix tests, broken by making slowfs a script In the tests we must run the script using python so we run with the correct python from .tox/<env>/bin/python.","import logging import os import signal import subprocess import time import pytest log = logging.getLogger(""test"") logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(levelname)s [%(name)s] %(message)s') @pytest.fixture def basedir(tmpdir): # 1. Create real file system with a special __ready__ file. realfs = tmpdir.mkdir(""realfs"") realfs.join(""__ready__"").write("""") # 2. Create slowfs mountpoint slowfs = tmpdir.mkdir(""slowfs"") # 3. Start slowfs log.debug(""Starting slowfs..."") cmd = [""python"", ""slowfs"", str(realfs), str(slowfs)] if os.environ.get(""DEBUG""): cmd.append(""--debug"") p = subprocess.Popen(cmd) try: # 4. Wait until __ready__ is visible via slowfs... log.debug(""Waiting until mount is ready..."") ready = slowfs.join(""__ready__"") for i in range(10): time.sleep(0.1) log.debug(""Checking mount..."") if ready.exists(): log.debug(""Mount is ready"") break else: raise RuntimeError(""Timeout waiting for slowfs mount %r"" % slowfs) # 4. We are ready for the test yield tmpdir finally: # 5. Interrupt slowfs, unmounting log.debug(""Stopping slowfs..."") p.send_signal(signal.SIGINT) p.wait() log.debug(""Stopped"") ","import logging import os import signal import subprocess import time import pytest log = logging.getLogger(""test"") logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(levelname)s [%(name)s] %(message)s') @pytest.fixture def basedir(tmpdir): # 1. Create real file system with a special __ready__ file. realfs = tmpdir.mkdir(""realfs"") realfs.join(""__ready__"").write("""") # 2. Create slowfs mountpoint slowfs = tmpdir.mkdir(""slowfs"") # 3. Start slowfs log.debug(""Starting slowfs..."") cmd = [""./slowfs"", str(realfs), str(slowfs)] if os.environ.get(""DEBUG""): cmd.append(""--debug"") p = subprocess.Popen(cmd) try: # 4. Wait until __ready__ is visible via slowfs... log.debug(""Waiting until mount is ready..."") ready = slowfs.join(""__ready__"") for i in range(10): time.sleep(0.1) log.debug(""Checking mount..."") if ready.exists(): log.debug(""Mount is ready"") break else: raise RuntimeError(""Timeout waiting for slowfs mount %r"" % slowfs) # 4. We are ready for the test yield tmpdir finally: # 5. Interrupt slowfs, unmounting log.debug(""Stopping slowfs..."") p.send_signal(signal.SIGINT) p.wait() log.debug(""Stopped"") " Add UI mock for application dropdown,"// React and reactstrap import React, { Component } from 'react'; import { Collapse, Navbar, NavbarToggler, NavbarBrand, Nav, NavItem, NavLink, Dropdown, DropdownItem, DropdownToggle, DropdownMenu } from 'reactstrap'; // Stylesheets & images import './../App.css'; import 'bootstrap/dist/css/bootstrap.css'; class NavBar extends Component { constructor(props) { super(props); this.state = { isOpen: false, dropdownOpen: false }; } toggle = () => { this.setState({ isOpen: !this.state.isOpen }); } dropdownToggle = () => { this.setState({ dropdownOpen: !this.state.dropdownOpen }); } render() { return ( <Navbar color=""primary"" dark expand=""md""> <NavbarBrand href=""#/"">CentralConfig</NavbarBrand> <Nav navbar> <Dropdown nav isOpen={this.state.dropdownOpen} toggle={this.dropdownToggle}> <DropdownToggle nav caret> Application </DropdownToggle> <DropdownMenu> <DropdownItem>App 1</DropdownItem> <DropdownItem>App 2</DropdownItem> <DropdownItem divider /> <DropdownItem>All applications</DropdownItem> </DropdownMenu> </Dropdown> </Nav> <Collapse isOpen={this.state.isOpen} navbar> <Nav className=""ml-auto"" navbar> <NavItem> <NavLink href=""https://github.com/cagedtornado/centralconfig"">Help</NavLink> </NavItem> </Nav> </Collapse> <NavbarToggler onClick={this.toggle} /> </Navbar> ); } } export default NavBar;","// React and reactstrap import React, { Component } from 'react'; import { Collapse, Navbar, NavbarToggler, NavbarBrand, Nav, NavItem, NavLink, } from 'reactstrap'; // Stylesheets & images import './../App.css'; import 'bootstrap/dist/css/bootstrap.css'; class NavBar extends Component { constructor(props) { super(props); this.state = { isOpen: false, }; } toggle = () => { this.setState({ isOpen: !this.state.isOpen }); } render() { return ( <Navbar color=""primary"" dark expand=""md""> <NavbarBrand href=""#/"">CentralConfig</NavbarBrand> <NavbarToggler onClick={this.toggle} /> <Collapse isOpen={this.state.isOpen} navbar> <Nav className=""ml-auto"" navbar> <NavItem> <NavLink href=""#/settings"">Settings</NavLink> </NavItem> <NavItem> <NavLink href=""https://github.com/cagedtornado/centralconfig"">Help</NavLink> </NavItem> </Nav> </Collapse> </Navbar> ); } } export default NavBar;" "Make it look nicer, possibly micro seconds faster","from django.views import generic from gallery.models import GalleryImage from gallery import queries from .models import Arc, Issue class IndexView(generic.ListView): model = Arc template_name = ""comics/index.html"" context_object_name = ""arcs"" class IssueView(generic.DetailView): model = Issue template_name = ""comics/issue.html"" def get_queryset(self): query_set = super().get_queryset().filter(arc__slug=self.kwargs.get(""arc_slug"")) return query_set class ComicPageView(generic.DetailView): model = GalleryImage template_name = ""comics/comic_page.html"" def __init__(self): super().__init__() self.issue = None def get_queryset(self): # Find Issue, then get gallery self.issue = Issue.objects.filter(arc__slug=self.kwargs.get(""arc_slug"")).get( slug=self.kwargs.get(""issue_slug"") ) query_set = super().get_queryset().filter(gallery__id=self.issue.gallery.id) return query_set def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context[""issue""] = self.issue # Set in get_queryset() gallery = self.issue.gallery sort_order = self.object.sort_order context[""next""] = queries.get_next_image(gallery, sort_order) context[""previous""] = queries.get_previous_image(gallery, sort_order) return context ","from django.views import generic from gallery.models import GalleryImage from gallery import queries from .models import Arc, Issue class IndexView(generic.ListView): model = Arc template_name = ""comics/index.html"" context_object_name = ""arcs"" class IssueView(generic.DetailView): model = Issue template_name = ""comics/issue.html"" def get_queryset(self): query_set = super().get_queryset().filter(arc__slug=self.kwargs.get(""arc_slug"")) return query_set class ComicPageView(generic.DetailView): model = GalleryImage template_name = ""comics/comic_page.html"" def __init__(self): super().__init__() self.issue = None def get_queryset(self): # Find Issue, then get gallery self.issue = Issue.objects.filter(arc__slug=self.kwargs.get(""arc_slug"")).get( slug=self.kwargs.get(""issue_slug"") ) query_set = super().get_queryset().filter(gallery__id=self.issue.gallery.id) return query_set def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context[""issue""] = self.issue # Set in get_queryset() context[""next""] = queries.get_next_image( self.issue.gallery, self.object.sort_order ) context[""previous""] = queries.get_previous_image( self.issue.gallery, self.object.sort_order ) return context " "Change extraction of status for AUTH_ERROR Based on this merged fix on AOR: https://github.com/marmelab/admin-on-rest/pull/1409/files#diff-c3ae69f3d76aad8177df8dd3a54c9476","import storage from './storage'; export const authClient = (loginApiUrl, noAccessPage = '/login') => { return (type, params) => { if (type === 'AUTH_LOGIN') { const request = new Request(loginApiUrl, { method: 'POST', body: JSON.stringify(params), headers: new Headers({ 'Content-Type': 'application/json' }), }); return fetch(request) .then(response => { if (response.status < 200 || response.status >= 300) { throw new Error(response.statusText); } return response.json(); }) .then(({ ttl, ...data }) => { storage.save('lbtoken', data, ttl); }); } if (type === 'AUTH_LOGOUT') { storage.remove('lbtoken'); return Promise.resolve(); } if (type === 'AUTH_ERROR') { const status = params.message.status; if (status === 401 || status === 403) { storage.remove('lbtoken'); return Promise.reject(); } return Promise.resolve(); } if (type === 'AUTH_CHECK') { const token = storage.load('lbtoken'); if (token && token.id) { return Promise.resolve(); } else { storage.remove('lbtoken'); return Promise.reject({ redirectTo: noAccessPage }); } } return Promise.reject('Unkown method'); }; }; ","import storage from './storage'; export const authClient = (loginApiUrl, noAccessPage = '/login') => { return (type, params) => { if (type === 'AUTH_LOGIN') { const request = new Request(loginApiUrl, { method: 'POST', body: JSON.stringify(params), headers: new Headers({ 'Content-Type': 'application/json' }), }); return fetch(request) .then(response => { if (response.status < 200 || response.status >= 300) { throw new Error(response.statusText); } return response.json(); }) .then(({ ttl, ...data }) => { storage.save('lbtoken', data, ttl); }); } if (type === 'AUTH_LOGOUT') { storage.remove('lbtoken'); return Promise.resolve(); } if (type === 'AUTH_ERROR') { const { status } = params; if (status === 401 || status === 403) { storage.remove('lbtoken'); return Promise.reject(); } return Promise.resolve(); } if (type === 'AUTH_CHECK') { const token = storage.load('lbtoken'); if (token && token.id) { return Promise.resolve(); } else { storage.remove('lbtoken'); return Promise.reject({ redirectTo: noAccessPage }); } } return Promise.reject('Unkown method'); }; };" Set DS default timeouts - don’t use inifnite values,"package com.github.endoscope.basic.ds; import javax.sql.DataSource; import com.github.endoscope.storage.jdbc.DataSourceProvider; import org.apache.commons.dbcp2.BasicDataSource; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import static org.slf4j.LoggerFactory.getLogger; public class BasicDataSourceProvider implements DataSourceProvider { private static final Logger log = getLogger(BasicDataSourceProvider.class); public DataSource create(String initParam){ if( StringUtils.isNotBlank(initParam) && initParam.startsWith(""jdbc:postgresql"") ){ log.info(""Detected jdbc:postgresql storage param for Endoscope - initializing BasicDataSource""); try{ BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(""org.postgresql.Driver""); //DEBUG: loglevel=2 //INFO: loglevel=1 //dataSource.setUrl(initParam + ""&loglevel=1""); dataSource.setUrl(initParam); //We save statistics every 15min or even less often //There is no reason to keep connection open for so long unused dataSource.setMinEvictableIdleTimeMillis(55000); dataSource.setTimeBetweenEvictionRunsMillis(60000); dataSource.setMaxWaitMillis(60 * 60 * 1000);//1h dataSource.setDefaultQueryTimeout( 15 * 60 * 1000);//15min return dataSource; }catch(Exception e){ log.info(""Failed to create custom Endoscope DataSource"", e); } } return null; } } ","package com.github.endoscope.basic.ds; import com.github.endoscope.storage.jdbc.DataSourceProvider; import org.apache.commons.dbcp2.BasicDataSource; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import javax.sql.DataSource; import static org.slf4j.LoggerFactory.getLogger; public class BasicDataSourceProvider implements DataSourceProvider { private static final Logger log = getLogger(BasicDataSourceProvider.class); public DataSource create(String initParam){ if( StringUtils.isNotBlank(initParam) && initParam.startsWith(""jdbc:postgresql"") ){ log.info(""Detected jdbc:postgresql storage param for Endoscope - initializing BasicDataSource""); try{ BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(""org.postgresql.Driver""); //DEBUG: loglevel=2 //INFO: loglevel=1 //dataSource.setUrl(initParam + ""&loglevel=1""); dataSource.setUrl(initParam); //We save statistics every 15min or even less often //There is no reason to keep connection open for so long unused dataSource.setMinEvictableIdleTimeMillis(55000); dataSource.setTimeBetweenEvictionRunsMillis(60000); return dataSource; }catch(Exception e){ log.info(""Failed to create custom Endoscope DataSource"", e); } } return null; } } " Fix error route no match,"/** * requires rcmApi from core */ angular.module('rcmAdminApi', []) .factory( 'rcmAdminApiUrlService', [ function () { /** * url map for APIs - These are parsed using the rcmApi service (core) * NOTE: these are named like {leastSpecific}{moreSpecific}{mostSpecific} for consistency and order * * @type {object} */ var urlMap = { countries: '/api/admin/country', languages: '/api/admin/language', pageTypes: '/api/admin/pagetypes', /* Current site */ siteCurrent: '/api/admin/manage-sites/current', /* Default site configuration */ siteDefault: '/api/admin/manage-sites/default', sites: '/api/admin/manage-sites', site: '/api/admin/manage-sites/{siteId}', siteCopy: '/api/admin/site-copy', sitePages: '/api/admin/sites/{siteId}/pages', sitePage: '/api/admin/sites/{siteId}/pages/{pageId}', sitePageCopy: '/api/admin/sites/{siteId}/page-copy/{pageId}', themes: '/api/admin/theme' }; return urlMap; } ] ); rcm.addAngularModule('rcmAdminApi'); ","/** * requires rcmApi from core */ angular.module('rcmAdminApi', []) .factory( 'rcmAdminApiUrlService', [ function () { /** * url map for APIs - These are parsed using the rcmApi service (core) * NOTE: these are named like {leastSpecific}{moreSpecific}{mostSpecific} for consistency and order * * @type {object} */ var urlMap = { countries: '/api/admin/country', languages: '/api/admin/language', pageTypes: '/api/admin/pagetypes', /* Current site */ siteCurrent: '/api/admin/manage-sites/current', /* Default site configuration */ siteDefault: '/api/admin/manage-sites/default', sites: '/api/admin/manage-sites?page_size=-1', site: '/api/admin/manage-sites/{siteId}', siteCopy: '/api/admin/site-copy', sitePages: '/api/admin/sites/{siteId}/pages', sitePage: '/api/admin/sites/{siteId}/pages/{pageId}', sitePageCopy: '/api/admin/sites/{siteId}/page-copy/{pageId}', themes: '/api/admin/theme' }; return urlMap; } ] ); rcm.addAngularModule('rcmAdminApi'); " TypeSafety: Support non-zero-indexed arrays in ensure(). Improve phrasing of Exception messages,"<?php namespace Kaloa\Util\TypeSafety; use IllegalArgumentException; trait TypeSafetyTrait { /** * @param string $types * @param array $args */ private function ensure($types, array $args) { if (!is_string($types)) { throw new IllegalArgumentException('Type list must be of type string'); } $cnt = count($args); if (strlen($types) !== $cnt) { throw new IllegalArgumentException('Type list length does not match argument count'); } $i = 0; foreach ($args as $arg) { switch ($types[$i]) { case 'b': if (!is_bool($arg)) { throw new IllegalArgumentException('bool expected'); } break; case 'f': if (!is_float($arg)) { throw new IllegalArgumentException('float expected'); } break; case 'i': if (!is_int($arg)) { throw new IllegalArgumentException('int expected'); } break; case 'r': if (!is_resource($arg)) { throw new IllegalArgumentException('resource expected'); } break; case 's': if (!is_string($arg)) { throw new IllegalArgumentException('string expected'); } break; case '-': /* skip */ break; default: throw new IllegalArgumentException('Unknown type at offset ' . $i . '. One of [bfirs-] expected'); break; } $i++; } } } ","<?php namespace Kaloa\Util\TypeSafety; use IllegalArgumentException; trait TypeSafetyTrait { /** * @param string $types * @param array $args */ private function ensure($types, array $args) { if (!is_string($types)) { throw new IllegalArgumentException('string expected'); } $cnt = count($args); if (strlen($types) !== $cnt) { throw new IllegalArgumentException('type count does not match argument count'); } for ($i = 0; $i < $cnt; $i++) { switch ($types[$i]) { case 'b': if (!is_bool($args[$i])) { throw new IllegalArgumentException('bool expected'); } break; case 'f': if (!is_float($args[$i])) { throw new IllegalArgumentException('float expected'); } break; case 'i': if (!is_int($args[$i])) { throw new IllegalArgumentException('int expected'); } break; case 'r': if (!is_resource($args[$i])) { throw new IllegalArgumentException('resource expected'); } break; case 's': if (!is_string($args[$i])) { throw new IllegalArgumentException('string expected'); } break; case '-': /* skip */ break; default: throw new IllegalArgumentException('Unknown type at offset ' . $i . '. One of [bfirs-] expected'); break; } } } } " Fix Splash width to 800 px.,"mol.modules.map.splash = function(mol) { mol.map.splash = {}; mol.map.splash.SplashEngine = mol.mvp.Engine.extend( { init: function(proxy, bus) { this.proxy = proxy; this.bus = bus; }, /** * Starts the MenuEngine. Note that the container parameter is * ignored. */ start: function() { this.display = new mol.map.splash.splashDisplay(); this.initDialog(); }, initDialog: function() { this.display.dialog( { autoOpen: true, width: 800, height: 500, dialogClass: ""mol-splash"", modal: true } ); $(this.display).width('98%'); } } ); mol.map.splash.splashDisplay = mol.mvp.View.extend( { init: function() { var html = '' + '<iframe class=""mol-splash iframe_content"" src=""https://docs.google.com/document/pub?id=1vrttRdCz4YReWFq5qQmm4K6WmyWayiouEYrYtPrAyvY&embedded=true""></iframe>'; this._super(html); this.iframe_content = $(this).find('.iframe_content'); } } ); }; ","mol.modules.map.splash = function(mol) { mol.map.splash = {}; mol.map.splash.SplashEngine = mol.mvp.Engine.extend( { init: function(proxy, bus) { this.proxy = proxy; this.bus = bus; }, /** * Starts the MenuEngine. Note that the container parameter is * ignored. */ start: function() { this.display = new mol.map.splash.splashDisplay(); this.initDialog(); }, initDialog: function() { this.display.dialog( { autoOpen: true, width: ""80%"", height: 500, dialogClass: ""mol-splash"", modal: true } ); $(this.display).width('98%'); } } ); mol.map.splash.splashDisplay = mol.mvp.View.extend( { init: function() { var html = '' + '<iframe class=""mol-splash iframe_content"" src=""https://docs.google.com/document/pub?id=1vrttRdCz4YReWFq5qQmm4K6WmyWayiouEYrYtPrAyvY&embedded=true""></iframe>'; this._super(html); this.iframe_content = $(this).find('.iframe_content'); } } ); }; " "Fix tests to use httpbin.org, return always 200","import unittest import http.client import time class TestStringMethods(unittest.TestCase): def test_404NoConfig(self): connRouter = http.client.HTTPConnection(""localhost"", 8666) connConfig = http.client.HTTPConnection(""localhost"", 8888) connRouter.request(""GET"", ""/httpbin"") response = connRouter.getresponse() data = response.read() connRouter.close() self.assertEqual(response.status, 404) def test_200WithConfig(self): connConfig = http.client.HTTPConnection(""localhost"", 8888) connConfig.request(""GET"",""/configure?location=/httpbin&upstream=http://httpbin.org/anything&ttl=10"") response = connConfig.getresponse() data = response.read() connConfig.close() self.assertEqual(response.status, 200) connRouter = http.client.HTTPConnection(""localhost"", 8666) connRouter.request(""GET"", ""/httpbin"") response = connRouter.getresponse() data = response.read() self.assertEqual(response.status, 200) connRouter.close() connConfig2 = http.client.HTTPConnection(""localhost"", 8888) connConfig2.request(""DELETE"",""/configure?location=/httpbin"") response2 = connConfig2.getresponse() data = response2.read() self.assertEqual(response2.status, 200) connConfig2.close() time.sleep(20) if __name__ == '__main__': unittest.main() ","import unittest import http.client import time class TestStringMethods(unittest.TestCase): def test_404NoConfig(self): connRouter = http.client.HTTPConnection(""localhost"", 8666) connConfig = http.client.HTTPConnection(""localhost"", 8888) connRouter.request(""GET"", ""/google"") response = connRouter.getresponse() connRouter.close() self.assertEqual(response.status, 404) def test_200WithConfig(self): connConfig = http.client.HTTPConnection(""localhost"", 8888) connConfig.request(""GET"",""/configure?location=/google&upstream=http://www.google.com/&ttl=10"") response = connConfig.getresponse() data = response.read() connConfig.close() self.assertEqual(response.status, 200) connRouter = http.client.HTTPConnection(""localhost"", 8666) connRouter.request(""GET"", ""/google"") response = connRouter.getresponse() data = response.read() self.assertEqual(response.status, 302) connRouter.close() connConfig2 = http.client.HTTPConnection(""localhost"", 8888) connConfig2.request(""DELETE"",""/configure?location=/google"") response2 = connConfig2.getresponse() data = response2.read() self.assertEqual(response2.status, 200) connConfig2.close() time.sleep(20) if __name__ == '__main__': unittest.main() " Check if maxResults is defined,"'use strict'; module.exports = bestResults; /* we have 2 criteria to find the best results 1. best match per zone based on the bestOf parameter 2. maxResults : maximal number of results */ function bestResults(results, bestOf, maxResults, minSimilarity) { var newResults = []; // in order to find the bestOf we will sort by similarity and take all of them for which there is nothing in a range // of the bestOf range results.sort(function (a, b) { return b.similarity - a.similarity; }); if (minSimilarity) { for (var i = 0; i < results.length; i++) { if (results[i].similarity < minSimilarity) { results = results.slice(0, i); break; } } } if (bestOf) { for (var i = 0; i < results.length; i++) { for (var j = 0; j < newResults.length; j++) { if (Math.abs(newResults[j].msem - results[i].msem) < (bestOf / (results[i].charge || 1))) { break; } } if (j == newResults.length) { newResults.push(results[i]); } } } else { newResults=results.slice(0); } if (maxResults) { newResults = newResults.slice(0, maxResults); } return newResults; }; ","'use strict'; module.exports = bestResults; /* we have 2 criteria to find the best results 1. best match per zone based on the bestOf parameter 2. maxResults : maximal number of results */ function bestResults(results, bestOf, maxResults, minSimilarity) { var newResults = []; // in order to find the bestOf we will sort by similarity and take all of them for which there is nothing in a range // of the bestOf range results.sort(function (a, b) { return b.similarity - a.similarity; }); if (minSimilarity) { for (var i = 0; i < results.length; i++) { if (results[i].similarity < minSimilarity) { results = results.slice(0, i); break; } } } if (bestOf) { for (var i = 0; i < results.length && newResults.length < maxResults; i++) { for (var j = 0; j < newResults.length; j++) { if (Math.abs(newResults[j].msem - results[i].msem) < (bestOf / (results[i].charge || 1))) { break; } } if (j == newResults.length) { newResults.push(results[i]); } } } else { newResults = results.slice(0, maxResults); } return newResults; }; " Add pinentry mode loopback to gpg command,"<?php /* * This file is part of the DB Backup utility. * * (c) Tom Adam <tomadam@instantiate.co.uk> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Instantiate\DatabaseBackup\FileEncrypter; use Instantiate\DatabaseBackup\Util\Process; class GpgFileEncrypter extends AbstractFileEncrypter { /** * @param string $inputFile * @param string $outputFile */ protected function encryptFile($inputFile, $outputFile) { Process::exec( 'gpg2 -v --encrypt {sign} --recipient {recipient} --batch --pinentry-mode loopback --yes {passphrase} --output {output_file} {input_file}', [ '{sign}' => $this->config['sign'] ? '--sign' : '', '{recipient}' => $this->config['recipient'], '{passphrase}' => $this->config['sign'] && $this->config['key_file'] ? '--passphrase-file '.$this->config['key_file'] : '', '{input_file}' => $inputFile, '{output_file}' => $outputFile, ], [], $this->logger ); } protected function getEncryptedFilename($inputFile) { return $inputFile.'.gpg'; } } ","<?php /* * This file is part of the DB Backup utility. * * (c) Tom Adam <tomadam@instantiate.co.uk> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Instantiate\DatabaseBackup\FileEncrypter; use Instantiate\DatabaseBackup\Util\Process; class GpgFileEncrypter extends AbstractFileEncrypter { /** * @param string $inputFile * @param string $outputFile */ protected function encryptFile($inputFile, $outputFile) { Process::exec( 'gpg2 -v --encrypt {sign} --recipient {recipient} --batch --yes {passphrase} --output {output_file} {input_file}', [ '{sign}' => $this->config['sign'] ? '--sign' : '', '{recipient}' => $this->config['recipient'], '{passphrase}' => $this->config['sign'] && $this->config['key_file'] ? '--passphrase-file '.$this->config['key_file'] : '', '{input_file}' => $inputFile, '{output_file}' => $outputFile, ], [], $this->logger ); } protected function getEncryptedFilename($inputFile) { return $inputFile.'.gpg'; } } " "Remove webpack configuration for externalising react Since already we use the `@apollo/client/core` import, `react` won't be included in the build. Closes https://github.com/ember-graphql/ember-apollo-client/issues/389","'use strict'; module.exports = { name: require('./package').name, options: { autoImport: { webpack: { module: { rules: [ /* fixes issue with graphql-js's mjs entry */ /* see: https://github.com/graphql/graphql-js/issues/1272#issuecomment-393903706 */ { test: /\.mjs$/, include: /node_modules\/graphql/, type: 'javascript/auto', }, ], }, }, }, }, included(app) { this._super.included.apply(this, arguments); this.app = app; }, getOptions() { const hostOptions = (this.parent && this.parent.options) || (this.app && this.app.options) || {}; return ( hostOptions.emberApolloClient || { keepGraphqlFileExtension: true, } ); }, setupPreprocessorRegistry(type, registry) { const options = this.getOptions(); if (type === 'parent') { registry.add('js', { name: require('./package').name, ext: 'graphql', toTree(tree) { const GraphQLFilter = require('broccoli-graphql-filter'); return new GraphQLFilter(tree, { keepExtension: options.keepGraphqlFileExtension, }); }, }); } }, }; ","'use strict'; module.exports = { name: require('./package').name, options: { autoImport: { webpack: { module: { rules: [ /* fixes issue with graphql-js's mjs entry */ /* see: https://github.com/graphql/graphql-js/issues/1272#issuecomment-393903706 */ { test: /\.mjs$/, include: /node_modules\/graphql/, type: 'javascript/auto', }, ], }, externals: { react: 'react', }, }, }, }, included(app) { this._super.included.apply(this, arguments); this.app = app; }, getOptions() { const hostOptions = (this.parent && this.parent.options) || (this.app && this.app.options) || {}; return ( hostOptions.emberApolloClient || { keepGraphqlFileExtension: true, } ); }, setupPreprocessorRegistry(type, registry) { const options = this.getOptions(); if (type === 'parent') { registry.add('js', { name: require('./package').name, ext: 'graphql', toTree(tree) { const GraphQLFilter = require('broccoli-graphql-filter'); return new GraphQLFilter(tree, { keepExtension: options.keepGraphqlFileExtension, }); }, }); } }, }; " Install dependencies at the end of the setup,"'use strict'; var yeoman = require('yeoman-generator'), utils = require('../../utils'); var LogGenerator = yeoman.generators.Base.extend({ prompts: require('./prompts'), dirs: require('./dirs'), srcFiles: require('./src-files'), projectFiles: require('./project-files'), prompting: function () { var done = this.async(); utils.banner(); this.prompt(this.prompts, function (props) { this.config.set(props); done(); }.bind(this)); }, writing: { app: function () { this._copyDirs(); this.fs.copyTpl( this.templatePath('_package.json'), this.destinationPath('package.json'), this.config.getAll() ); }, code: function () { this._copyFiles(this.srcFiles.files(this)); }, projectFiles: function () { this._copyFiles(this.projectFiles); } }, _copyDirs: function () { this.dirs.forEach(function (dir) { this.dest.mkdir(dir); }.bind(this)); }, _copyFiles: function (files) { files.forEach(function (file) { this.fs.copyTpl( this.templatePath(file.src), this.destinationPath(file.dst), {} ); }.bind(this)); }, end: function () { this.installDependencies(); } }); module.exports = LogGenerator; ","'use strict'; var yeoman = require('yeoman-generator'), utils = require('../../utils'); var LogGenerator = yeoman.generators.Base.extend({ prompts: require('./prompts'), dirs: require('./dirs'), srcFiles: require('./src-files'), projectFiles: require('./project-files'), prompting: function () { var done = this.async(); utils.banner(); this.prompt(this.prompts, function (props) { this.config.set(props); done(); }.bind(this)); }, writing: { app: function () { this._copyDirs(); this.fs.copyTpl( this.templatePath('_package.json'), this.destinationPath('package.json'), this.config.getAll() ); }, code: function () { this._copyFiles(this.srcFiles.files(this)); }, projectFiles: function () { this._copyFiles(this.projectFiles); } }, _copyDirs: function () { this.dirs.forEach(function (dir) { this.dest.mkdir(dir); }.bind(this)); }, _copyFiles: function (files) { files.forEach(function (file) { this.fs.copyTpl( this.templatePath(file.src), this.destinationPath(file.dst), {} ); }.bind(this)); } // end: function() { // this.installDependencies(); // } }); module.exports = LogGenerator; " Remove ':memory:' as that is default,"#!/usr/bin/env python import sys import django from django.conf import settings def main(): import warnings warnings.filterwarnings('error', category=DeprecationWarning) if not settings.configured: # Dynamically configure the Django settings with the minimum necessary to # get Django running tests settings.configure( INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.sessions', 'parse_push', ], DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, DEBUG=True, # ROOT_URLCONF='testproject.urls', ) # Compatibility with Django 1.7's stricter initialization if hasattr(django, 'setup'): django.setup() from django.test.utils import get_runner test_runner = get_runner(settings)(verbosity=2, interactive=True) if '--failfast' in sys.argv: test_runner.failfast = True failures = test_runner.run_tests(['parse_push']) sys.exit(failures) if __name__ == '__main__': main()","#!/usr/bin/env python import os import sys import django from django.conf import settings def main(): import warnings warnings.filterwarnings('error', category=DeprecationWarning) if not settings.configured: # Dynamically configure the Django settings with the minimum necessary to # get Django running tests settings.configure( INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.sessions', 'parse_push', ], # Django still complains? :( DATABASE_ENGINE='django.db.backends.sqlite3', DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:' } }, # MEDIA_PATH='/media/', # ROOT_URLCONF='parse_push.tests.urls', # DEBUG=True, # TEMPLATE_DEBUG=True, ) # Compatibility with Django 1.7's stricter initialization if hasattr(django, 'setup'): django.setup() from django.test.utils import get_runner test_runner = get_runner(settings)(verbosity=2, interactive=True) if '--failfast' in sys.argv: test_runner.failfast = True failures = test_runner.run_tests(['parse_push']) sys.exit(failures) if __name__ == '__main__': main()" Remove test for null result,"package com.deuteriumlabs.dendrite.unittest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Ignore; import org.junit.Test; import com.deuteriumlabs.dendrite.model.StoryPage; public class StoryPageTest { final static String IMPLEMENT_ME = ""Not implemented yet""; final static String NOT_WRITTEN = ""This page has not been written yet.""; @Test public void testDefaultConstructor() { final StoryPage storyPage = new StoryPage(); assertNull(storyPage.getBeginning()); assertNull(storyPage.getAncestry()); assertNull(storyPage.getAuthorId()); assertNull(storyPage.getAuthorName()); assertNull(storyPage.getBeginning()); assertNull(storyPage.getFormerlyLovingUsers()); assertNull(storyPage.getId()); assertNull(storyPage.getLovingUsers()); assertNull(storyPage.getParent()); assertTrue(storyPage.getTags().isEmpty()); assertEquals(storyPage.getLongSummary(), NOT_WRITTEN); } @Ignore(IMPLEMENT_ME) @Test public void testConstructorWithEntity() { fail(IMPLEMENT_ME); } @Ignore(IMPLEMENT_ME) @Test public void testCreate() { fail(IMPLEMENT_ME); } @Ignore(IMPLEMENT_ME) @Test public void testGetAncestry() { fail(IMPLEMENT_ME); } }","package com.deuteriumlabs.dendrite.unittest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Ignore; import org.junit.Test; import com.deuteriumlabs.dendrite.model.PageId; import com.deuteriumlabs.dendrite.model.StoryPage; public class StoryPageTest { final static String IMPLEMENT_ME = ""Not implemented yet""; final static String NOT_WRITTEN = ""This page has not been written yet.""; @Test public void testDefaultConstructor() { final StoryPage storyPage = new StoryPage(); assertNull(storyPage.getBeginning()); assertNull(storyPage.getAncestry()); assertNull(storyPage.getAuthorId()); assertNull(storyPage.getAuthorName()); assertNull(storyPage.getBeginning()); assertNull(storyPage.getFormerlyLovingUsers()); assertNull(storyPage.getId()); assertNull(storyPage.getLovingUsers()); assertNull(storyPage.getParent()); assertTrue(storyPage.getTags().isEmpty()); assertEquals(storyPage.getLongSummary(), NOT_WRITTEN); } @Ignore(IMPLEMENT_ME) @Test public void testConstructorWithEntity() { fail(IMPLEMENT_ME); } @Ignore(IMPLEMENT_ME) @Test public void testCreate() { fail(IMPLEMENT_ME); } @Test public void testGetAncestry() { final StoryPage storyPage = new StoryPage(); assertNull(storyPage.getAncestry()); } }" "Add plug-in summary for osc doc Stevedore Sphinx extension handles this comment. http://docs.openstack.org/developer/python-openstackclient/plugin-commands.html Change-Id: Id6339d11b900a644647c8c25bbd630ef52a60aab","# 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. """"""OpenStackClient plugin for Key Manager service."""""" from barbicanclient import client DEFAULT_API_VERSION = '1' API_VERSION_OPTION = 'os_key_manager_api_version' API_NAME = 'key_manager' API_VERSIONS = { '1': 'barbicanclient.client.Client', } def make_client(instance): """"""Returns a Barbican service client."""""" return client.Client(session=instance.session, region_name=instance._region_name) def build_option_parser(parser): """"""Hook to add global options."""""" parser.add_argument('--os-key-manager-api-version', metavar='<key-manager-api-version>', default=client.env( 'OS_KEY_MANAGER_API_VERSION', default=DEFAULT_API_VERSION), help=('Barbican API version, default=' + DEFAULT_API_VERSION + ' (Env: OS_KEY_MANAGER_API_VERSION)')) return parser ","# 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. from barbicanclient import client DEFAULT_API_VERSION = '1' API_VERSION_OPTION = 'os_key_manager_api_version' API_NAME = 'key_manager' API_VERSIONS = { '1': 'barbicanclient.client.Client', } def make_client(instance): """"""Returns a Barbican service client."""""" return client.Client(session=instance.session, region_name=instance._region_name) def build_option_parser(parser): """"""Hook to add global options."""""" parser.add_argument('--os-key-manager-api-version', metavar='<key-manager-api-version>', default=client.env( 'OS_KEY_MANAGER_API_VERSION', default=DEFAULT_API_VERSION), help=('Barbican API version, default=' + DEFAULT_API_VERSION + ' (Env: OS_KEY_MANAGER_API_VERSION)')) return parser " "Check interfaces, and abstract classes","<?php namespace Tests; use PHPUnit\Framework\TestCase; use App\Contracts\SortingAlgorithm; use App\Contracts\ProvidesFeedback; class AlgorithmTest extends TestCase { /** * List of algorithms to test * * @var array */ private $algorithms = [ \App\Algorithms\BubbleSort::class, \App\Algorithms\MergeSort::class, \App\Algorithms\SelectionSort::class, \App\Algorithms\InsertionSort::class, \App\Algorithms\QuickSort::class, ]; /** * Generate numbers to sort. */ public function __construct() { $this->numbers = $this->sorted = range(1, 100); shuffle($this->numbers); } /** * Test each algorithm */ public function testAlgorithms() { foreach ($this->algorithms as $algorithm) { $sorter = new $algorithm($this->numbers); // Assert it can really sort $this->assertAlgorithmCanSort($sorter); // The original still must be shufled! $this->assertNotEquals($this->numbers, $this->sorted); // Check if it implements and extends the neccessary interfaces and classes $this->assertInstanceOf(\App\Contracts\ProvidesFeedback::class, $sorter); $this->assertInstanceOf(\App\Sorter::class, $sorter); } } /** * Check if given algorithm can sort * * @param SortingAlgorithm $algorithm */ private function assertAlgorithmCanSort(SortingAlgorithm $algorithm) { $actual = $algorithm->sort(); $this->assertEquals($this->sorted, $actual); } } ","<?php namespace Tests; use PHPUnit\Framework\TestCase; use App\Contracts\SortingAlgorithm; class AlgorithmTest extends TestCase { /** * List of algorithms to test * * @var array */ private $algorithms = [ \App\Algorithms\BubbleSort::class, \App\Algorithms\MergeSort::class, \App\Algorithms\SelectionSort::class, \App\Algorithms\InsertionSort::class, \App\Algorithms\QuickSort::class, ]; /** * Generate numbers to sort. */ public function __construct() { $this->numbers = $this->sorted = range(1, 100); shuffle($this->numbers); } /** * Test each algorithm */ public function testAlgorithms() { foreach ($this->algorithms as $algorithm) { // Assert it can really sort $this->assertAlgorithmCanSort(new $algorithm($this->numbers)); // The original still must be shufled! $this->assertNotEquals($this->numbers, $this->sorted); } } /** * Check if given algorithm can sort * * @param SortingAlgorithm $algorithm */ private function assertAlgorithmCanSort(SortingAlgorithm $algorithm) { $actual = $algorithm->sort(); $this->assertEquals($this->sorted, $actual); } }" Fix exception message due to wrong rebase,"<?php namespace Marmelab\Multifetch; use KzykHys\Parallel\Parallel; class Multifetcher { public function fetch(array $parameters, $renderer, $parallelize = false) { if (isset($parameters['_parallel'])) { $parallelize = (bool) $parameters['_parallel']; unset($parameters['_parallel']); } if ($parallelize && !class_exists('\KzykHys\Parallel\Parallel')) { throw new \RuntimeException( '""kzykhys/parallel"" library is required to execute requests in parallel. To install it, run ""composer require kzykhys/parallel 0.1""' ); } $requests = array(); foreach ($parameters as $resource => $url) { $requests[$resource] = function () use ($resource, $url, $renderer) { $response = $renderer($url); $headers = array(); foreach ($response->headers->all() as $name => $value) { $headers[] = array('name' => $name, 'value' => current($value)); } return array( 'code' => $response->getStatusCode(), 'headers' => $headers, 'body' => $response->getContent(), ); }; } if ($parallelize) { $parallel = new Parallel(); return $parallel->values($requests); } foreach ($requests as $resource => $callback) { $responses[$resource] = $callback(); } return $responses; } } ","<?php namespace Marmelab\Multifetch; use KzykHys\Parallel\Parallel; class Multifetcher { public function fetch(array $parameters, $renderer, $parallelize = false) { if (isset($parameters['_parallel'])) { $parallelize = (bool) $parameters['_parallel']; unset($parameters['_parallel']); } if ($parallelize && !class_exists('\KzykHys\Parallel\Parallel')) { throw new \RuntimeException( '""kzykhys/parallel"" library is required. To install it, run ""composer require kzykhys/parallel 0.1""' ); } $requests = array(); foreach ($parameters as $resource => $url) { $requests[$resource] = function () use ($resource, $url, $renderer) { $response = $renderer($url); $headers = array(); foreach ($response->headers->all() as $name => $value) { $headers[] = array('name' => $name, 'value' => current($value)); } return array( 'code' => $response->getStatusCode(), 'headers' => $headers, 'body' => $response->getContent(), ); }; } if ($parallelize) { $parallel = new Parallel(); return $parallel->values($requests); } foreach ($requests as $resource => $callback) { $responses[$resource] = $callback(); } return $responses; } } " Fix naming in test case,"<?php namespace OpenCFP\Tests\Domain\Services; use OpenCFP\Domain\Services\ResetEmailer; class EmailerTest extends \PHPUnit_Framework_TestCase { private $swift_mailer; private $template; private $config_email; private $config_title; private $user_id; private $user_email; private $reset_code; private $mailer; public function setUp() { $this->swift_mailer = \Mockery::mock('mailer')->shouldReceive('send')->once() ->with(\Mockery::on($this->validateEmail()))->getMock(); $this->template = \Mockery::mock('template')->shouldIgnoreMissing(); $this->config_email = 'admin@example.com'; $this->config_title = 'Reset'; $this->user_email = 'user@example.com'; $this->user_id = 123; $this->reset_code = '987abc'; $this->mailer = new ResetEmailer($this->swift_mailer, $this->template, $this->config_email, $this->config_title); } public function tearDown() { \Mockery::close(); } /** @test */ public function it_sends_the_expected_email() { $this->mailer->send($this->user_id, $this->user_email, $this->reset_code); } private function validateEmail() { return function ($message) { return $message->getTo() === array($this->user_email => null); }; } } ","<?php namespace OpenCFP\Tests\Domain\Services; use OpenCFP\Domain\Services\ResetEmailer; class EmailerTest extends \PHPUnit_Framework_TestCase { private $mailer; private $template; private $config_email; private $config_title; private $user_id; private $user_email; private $reset_code; public function setUp() { $this->mailer = \Mockery::mock('mailer')->shouldReceive('send')->once() ->with(\Mockery::on($this->validateEmail()))->getMock(); $this->template = \Mockery::mock('template')->shouldIgnoreMissing(); $this->config_email = 'admin@example.com'; $this->config_title = 'Reset'; $this->user_email = 'user@example.com'; $this->user_id = 123; $this->reset_code = '987abc'; $this->mailer = new ResetEmailer($this->mailer, $this->template, $this->config_email, $this->config_title); } public function tearDown() { \Mockery::close(); } /** @test */ public function it_sends_the_expected_email() { $this->mailer->send($this->user_id, $this->user_email, $this->reset_code); } private function validateEmail() { return function ($message) { return $message->getTo() === array($this->user_email => null); }; } } " "[TASK] Adjust a comment to HTTP foundation Change-Id: I92e60d98528c1fd0cbdf0eeb08466e77014bc780 Related: #35243 Releases: 1.1 Original-Commit-Hash: 0914e9da46c731746fc71a871c363cc00be16e62","<?php namespace TYPO3\Fluid\ViewHelpers; /* * * This script belongs to the FLOW3 package ""Fluid"". * * * * It is free software; you can redistribute it and/or modify it under * * the terms of the GNU Lesser General Public License, either version 3 * * of the License, or (at your option) any later version. * * * * The TYPO3 project - inspiring people to share! * * */ /** * View helper which creates a <base href=""...""></base> tag. The Base URI * is taken from the current request. * In FLOW3, you should always include this ViewHelper to make the links work. * * = Examples = * * <code title=""Example""> * <f:base /> * </code> * <output> * <base href=""http://yourdomain.tld/"" /> * (depending on your domain) * </output> * * @api */ class BaseViewHelper extends \TYPO3\Fluid\Core\ViewHelper\AbstractViewHelper { /** * Render the ""Base"" tag by outputting $httpRequest->getBaseUri() * * @return string ""base""-Tag. * @api */ public function render() { return '<base href=""' . $this->controllerContext->getRequest()->getHttpRequest()->getBaseUri() . '"" />'; } } ?> ","<?php namespace TYPO3\Fluid\ViewHelpers; /* * * This script belongs to the FLOW3 package ""Fluid"". * * * * It is free software; you can redistribute it and/or modify it under * * the terms of the GNU Lesser General Public License, either version 3 * * of the License, or (at your option) any later version. * * * * The TYPO3 project - inspiring people to share! * * */ /** * View helper which creates a <base href=""...""></base> tag. The Base URI * is taken from the current request. * In FLOW3, you should always include this ViewHelper to make the links work. * * = Examples = * * <code title=""Example""> * <f:base /> * </code> * <output> * <base href=""http://yourdomain.tld/"" /> * (depending on your domain) * </output> * * @api */ class BaseViewHelper extends \TYPO3\Fluid\Core\ViewHelper\AbstractViewHelper { /** * Render the ""Base"" tag by outputting $request->getBaseUri() * * @return string ""base""-Tag. * @api */ public function render() { return '<base href=""' . $this->controllerContext->getRequest()->getHttpRequest()->getBaseUri() . '"" />'; } } ?> " Set registration open by default,"from firecares.settings.base import * # noqa INSTALLED_APPS += ('debug_toolbar', 'fixture_magic', 'django_extensions') # noqa MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware', ) # noqa # The Django Debug Toolbar will only be shown to these client IPs. INTERNAL_IPS = ( '127.0.0.1', ) DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, 'SHOW_TEMPLATE_CONTEXT': True, 'HIDE_DJANGO_SQL': False, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'magic' } } LOGGING['loggers'] = { # noqa 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, 'osgeo_importer': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, }, } def show_toolbar(request): return False DEBUG_TOOLBAR_CONFIG = { ""SHOW_TOOLBAR_CALLBACK"": show_toolbar, } # EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' CELERY_ALWAYS_EAGER = True REGISTRATION_OPEN = True try: from local_settings import * # noqa except ImportError: pass ","from firecares.settings.base import * # noqa INSTALLED_APPS += ('debug_toolbar', 'fixture_magic', 'django_extensions') # noqa MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware', ) # noqa # The Django Debug Toolbar will only be shown to these client IPs. INTERNAL_IPS = ( '127.0.0.1', ) DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, 'SHOW_TEMPLATE_CONTEXT': True, 'HIDE_DJANGO_SQL': False, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'magic' } } LOGGING['loggers'] = { # noqa 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, 'osgeo_importer': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, }, } def show_toolbar(request): return False DEBUG_TOOLBAR_CONFIG = { ""SHOW_TOOLBAR_CALLBACK"": show_toolbar, } # EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' CELERY_ALWAYS_EAGER = True try: from local_settings import * # noqa except ImportError: pass " Fix checking if an element is attached to the document,"var _ = require('_'), _cache = require('./cache'), _nodeNameCache = _cache(); module.exports = { isAttached: function(elem) { return (elem && elem !== document ? elem.parentNode : false); }, isHtml: function(text) { if (!_.isString(text)) { return false; } text = _.string.trim(text); return (text.charAt(0) === '<' && text.charAt(text.length - 1) === '>' && text.length >= 3); }, normalNodeName: function(elem) { var nodeName = elem.nodeName; return _nodeNameCache.getOrSet(nodeName, function() { return nodeName.toLowerCase(); }); }, isNodeName: function(elem, name) { var nodeName = _nodeNameCache.getOrSet(elem.nodeName, function() { return elem.nodeName.toLowerCase(); }), compareName = _nodeNameCache.getOrSet(name, function() { return name.toLowerCase(); }); return nodeName === compareName; }, merge: function(first, second) { var length = second.length, idx = 0, i = first.length; // Go through each element in the // second array and add it to the // first for (; idx < length; idx++) { first[i++] = second[idx]; } first.length = i; return first; } }; ","var _ = require('_'), _cache = require('./cache'), _nodeNameCache = _cache(); module.exports = { isAttached: function(elem) { return (elem.ownerDocument === document); }, isHtml: function(text) { if (!_.isString(text)) { return false; } text = _.string.trim(text); return (text.charAt(0) === '<' && text.charAt(text.length - 1) === '>' && text.length >= 3); }, normalNodeName: function(elem) { var nodeName = elem.nodeName; return _nodeNameCache.getOrSet(nodeName, function() { return nodeName.toLowerCase(); }); }, isNodeName: function(elem, name) { var nodeName = _nodeNameCache.getOrSet(elem.nodeName, function() { return elem.nodeName.toLowerCase(); }), compareName = _nodeNameCache.getOrSet(name, function() { return name.toLowerCase(); }); return nodeName === compareName; }, merge: function(first, second) { var length = second.length, idx = 0, i = first.length; // Go through each element in the // second array and add it to the // first for (; idx < length; idx++) { first[i++] = second[idx]; } first.length = i; return first; } }; " Fix test that took the spacing into account,"<?php namespace Backend\Modules\ContentBlocks\Tests\Action; use Common\WebTestCase; class AddTest extends WebTestCase { public function testAuthenticationIsNeeded(): void { $client = static::createClient(); $this->logout($client); $client->setMaxRedirects(1); $client->request('GET', '/private/en/content_blocks/index'); // we should get redirected to authentication with a reference to blog index in our url self::assertStringEndsWith( '/private/en/authentication?querystring=%2Fprivate%2Fen%2Fcontent_blocks%2Findex', $client->getHistory()->current()->getUri() ); } public function testFormIsDisplayed(): void { $client = static::createClient(); $this->login($client); $client->request('GET', '/private/en/content_blocks/add'); self::assertContains( 'Title<abbr data-toggle=""tooltip"" aria-label=""Required field"" title=""Required field"">*</abbr>', $client->getResponse()->getContent() ); self::assertContains( 'Visible on site', $client->getResponse()->getContent() ); self::assertContains( 'Add content block', $client->getResponse()->getContent() ); } } ","<?php namespace Backend\Modules\ContentBlocks\Tests\Action; use Common\WebTestCase; class AddTest extends WebTestCase { public function testAuthenticationIsNeeded(): void { $client = static::createClient(); $this->logout($client); $client->setMaxRedirects(1); $client->request('GET', '/private/en/content_blocks/index'); // we should get redirected to authentication with a reference to blog index in our url self::assertStringEndsWith( '/private/en/authentication?querystring=%2Fprivate%2Fen%2Fcontent_blocks%2Findex', $client->getHistory()->current()->getUri() ); } public function testFormIsDisplayed(): void { $client = static::createClient(); $this->login($client); $client->request('GET', '/private/en/content_blocks/add'); self::assertContains( 'Title <abbr data-toggle=""tooltip"" aria-label=""Required field"" title=""Required field"">*</abbr>', $client->getResponse()->getContent() ); self::assertContains( 'Visible on site', $client->getResponse()->getContent() ); self::assertContains( 'Add content block', $client->getResponse()->getContent() ); } } " Remove dropbox & kindle sharing flags,"package org.hogel.command.job; import com.google.inject.Inject; import org.hogel.bookscan.BookscanClient; import org.hogel.bookscan.OptimizeOption; import org.hogel.bookscan.model.Book; import org.hogel.config.Config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; public class OptimizeAllJob extends AbstractJob { private static final Logger LOG = LoggerFactory.getLogger(OptimizeAllJob.class); @Inject Config config; @Inject BookscanClient bookscanClient; @Override public void run() throws Exception { List<Book> books = bookscanClient .fetchBooks() .timeout(config.getTimeout()) .get(); // TODO: load optimize option from config file OptimizeOption option = new OptimizeOption(); option.addFlag(OptimizeOption.Flag.COVER); option.addFlag(OptimizeOption.Flag.BOLD); option.addFlag(OptimizeOption.Flag.WHITE); option.addType(OptimizeOption.Type.KINDLEP); long wait = config.getWait(); for (Book book : books) { LOG.info(""Optimize: {}"", book.getFilename()); bookscanClient .requestBookOptimize(book, option) .timeout(config.getTimeout()) .get(); Thread.sleep(wait); } } } ","package org.hogel.command.job; import com.google.inject.Inject; import org.hogel.bookscan.BookscanClient; import org.hogel.bookscan.OptimizeOption; import org.hogel.bookscan.model.Book; import org.hogel.config.Config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; public class OptimizeAllJob extends AbstractJob { private static final Logger LOG = LoggerFactory.getLogger(OptimizeAllJob.class); @Inject Config config; @Inject BookscanClient bookscanClient; @Override public void run() throws Exception { List<Book> books = bookscanClient .fetchBooks() .timeout(config.getTimeout()) .get(); // TODO: load optimize option from config file OptimizeOption option = new OptimizeOption(); option.addFlag(OptimizeOption.Flag.COVER); option.addFlag(OptimizeOption.Flag.BOLD); option.addFlag(OptimizeOption.Flag.KINDLE); option.addFlag(OptimizeOption.Flag.DROPBOX); option.addFlag(OptimizeOption.Flag.WHITE); option.addType(OptimizeOption.Type.KINDLEP); long wait = config.getWait(); for (Book book : books) { LOG.info(""Optimize: {}"", book.getFilename()); bookscanClient .requestBookOptimize(book, option) .timeout(config.getTimeout()) .get(); Thread.sleep(wait); } } } " Configure django correctly when we setup our env,"#!/usr/bin/env python import multiprocessing import optparse from django.conf import settings as django_settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module from hurricane.utils import run_until_stopped class ApplicationManager(object): @run_until_stopped def run(self): parser = optparse.OptionParser() parser.add_option('--settings', dest='settings') options, args = parser.parse_args() if not options.settings: raise ImproperlyConfigured(""You didn't provide a settings module."") settings = import_module(options.settings) django_settings.configure(settings) self.producer_queue = multiprocessing.Queue() for producer in settings.PRODUCERS: ProducerClass = import_module(producer).Producer producer = ProducerClass(settings, self.producer_queue) multiprocessing.Process(target=producer.run).start() self.receiver_queues = [] for consumer in settings.CONSUMERS: ConsumerClass = import_module(consumer).Consumer recv_queue = multiprocessing.Queue() consumer = ConsumerClass(settings, recv_queue) self.receiver_queues.append(recv_queue) multiprocessing.Process(target=consumer.run).start() while True: item = self.producer_queue.get() for recv_queue in self.receiver_queues: recv_queue.put(item) if __name__ == '__main__': app = ApplicationManager() app.run() ","#!/usr/bin/env python import multiprocessing import optparse from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module from hurricane.utils import run_until_stopped class ApplicationManager(object): @run_until_stopped def run(self): parser = optparse.OptionParser() parser.add_option('--settings', dest='settings') options, args = parser.parse_args() if not options.settings: raise ImproperlyConfigured(""You didn't provide a settings module."") settings = import_module(options.settings) self.producer_queue = multiprocessing.Queue() for producer in settings.PRODUCERS: ProducerClass = import_module(producer).Producer producer = ProducerClass(settings, self.producer_queue) multiprocessing.Process(target=producer.run).start() self.receiver_queues = [] for consumer in settings.CONSUMERS: ConsumerClass = import_module(consumer).Consumer recv_queue = multiprocessing.Queue() consumer = ConsumerClass(settings, recv_queue) self.receiver_queues.append(recv_queue) multiprocessing.Process(target=consumer.run).start() while True: item = self.producer_queue.get() for recv_queue in self.receiver_queues: recv_queue.put(item) if __name__ == '__main__': app = ApplicationManager() app.run() " Send old stringified actions with sendAction,"import Ember from 'ember'; export default Ember.Component.extend({ classNameBindings: ['isActive'], isActive: false, selectedClass: 'active', list: Ember.computed({ get() { if (this.attrs.list && this.attrs.list.value) { return this.attrs.list.value; } else { return null; } } }), didReceiveAttrs () { if (this.attrs.item && this.attrs.item.value) { this.set('itemData', this.attrs.item.value); } if(this.get('list')) { if(this.get('list').selectedClass) { this.set('selectedClass', this.get('list').selectedClass); } this.get('list').send('registerItem', this); } }, activate() { if(!this.get('isActive')) { this.set('isActive', this.get('selectedClass')); } }, deactivate() { if(this.get('isActive')) { this.set('isActive', false); } }, selectItem() { if (this.get('list')) { this.get('list').send(""itemSelected"", this); } }, onSelectAction() { let onSelect = this.attrs['on-select']; if (onSelect) { if (typeof onSelect === 'string') { this.sendAction(onSelect, this.get('itemData')); } else { onSelect(this.get('itemData')); } } }, click() { this.selectItem(); this.onSelectAction(); } }); ","import Ember from 'ember'; export default Ember.Component.extend({ classNameBindings: ['isActive'], isActive: false, selectedClass: 'active', list: Ember.computed({ get() { if (this.attrs.list && this.attrs.list.value) { return this.attrs.list.value; } else { return null; } } }), didReceiveAttrs () { if (this.attrs.item && this.attrs.item.value) { this.set('itemData', this.attrs.item.value); } if(this.get('list')) { if(this.get('list').selectedClass) { this.set('selectedClass', this.get('list').selectedClass); } this.get('list').send('registerItem', this); } }, activate() { if(!this.get('isActive')) { this.set('isActive', this.get('selectedClass')); } }, deactivate() { if(this.get('isActive')) { this.set('isActive', false); } }, selectItem() { if (this.get('list')) { this.get('list').send(""itemSelected"", this); } }, onSelectAction() { if (this.attrs['on-select']) { this.attrs['on-select'](this.get('itemData')); } }, click() { this.selectItem(); this.onSelectAction(); } }); " tests: Update tests to use pytest instead of nose,"import pytest from ckanapi import ValidationError from ckan.tests import helpers, factories from ckantoolkit import config @pytest.mark.ckan_config(""ckan.plugins"", ""stadtzhtheme"") @pytest.mark.usefixtures(""clean_db"", ""with_plugins"") class TestValidation(object): def test_invalid_url(self): """"""Test that an invalid resource url is caught by our validator. """""" print(config.get('ckan.plugins')) try: dataset = factories.Dataset() helpers.call_action( 'resource_download_permalink', {}, package_id=dataset['name'], name='Test-File', url='https://example.com]' ) except ValidationError as e: assert e.error_dict['url'] == [u'Bitte eine valide URL angeben'] else: raise AssertionError('ValidationError not raised') def test_invalid_url_for_upload_resource_type(self): """"""Test that the resource url is not validated if the url_type is 'upload'. """""" try: dataset = factories.Dataset() helpers.call_action( 'resource_create', package_id=dataset['name'], name='Test-File', url='https://example.com]', url_type='upload' ) except ValidationError: raise AssertionError('ValidationError raised erroneously') ","import nose from ckanapi import TestAppCKAN, ValidationError from ckan.tests import helpers, factories eq_ = nose.tools.eq_ assert_true = nose.tools.assert_true class TestValidation(helpers.FunctionalTestBase): def test_invalid_url(self): """"""Test that an invalid resource url is caught by our validator. """""" factories.Sysadmin(apikey=""my-test-key"") app = self._get_test_app() demo = TestAppCKAN(app, apikey=""my-test-key"") try: dataset = factories.Dataset() demo.action.resource_create( package_id=dataset['name'], name='Test-File', url='https://example.com]' ) except ValidationError as e: eq_( e.error_dict['url'], [u'Bitte eine valide URL angeben'] ) else: raise AssertionError('ValidationError not raised') def test_invalid_url_for_upload_resource_type(self): """"""Test that the resource url is not validated if the url_type is 'upload'. """""" factories.Sysadmin(apikey=""my-test-key"") app = self._get_test_app() demo = TestAppCKAN(app, apikey=""my-test-key"") try: dataset = factories.Dataset() demo.action.resource_create( package_id=dataset['name'], name='Test-File', url='https://example.com]', url_type='upload' ) except ValidationError: raise AssertionError('ValidationError raised erroneously') " Fix typo from authors field,"# -*- coding: utf-8 -*- from setuptools import setup, find_packages import sys, os version = '0.1.9.dev' setup(name='testdroid', version=version, description=""Testdroid API client for Python"", long_description=""""""\ Testdroid API client for Python"""""", classifiers=['Operating System :: OS Independent', 'Topic :: Software Development', 'Intended Audience :: Developers'], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='testdroid rest api client', author='Henri Kivelä <henri.kivela@bitbar.com>, Sakari Rautiainen <sakari.rautiainen@bitbar.com>, Teppo Malinen <teppo.malinen@bitbar.com>, Jarno Tuovinen <jarno.tuovinen@bitbar.com>', author_email='info@bitbar.com', url='http://www.testdroid.com', license='Apache License v2.0', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=True, install_requires=[ 'requests', 'pillow', ], entry_points = { 'console_scripts': [ 'testdroid = testdroid:main', ], }, ) ","# -*- coding: utf-8 -*- from setuptools import setup, find_packages import sys, os version = '0.1.9.dev' setup(name='testdroid', version=version, description=""Testdroid API client for Python"", long_description=""""""\ Testdroid API client for Python"""""", classifiers=['Operating System :: OS Independent', 'Topic :: Software Development', 'Intended Audience :: Developers'], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='testdroid rest api client', author='Henri Kivelä <henri.kivela@bitbar.com>, Sakari Rautiainen <sakari.rautiainen@bitbar.com>, Teppo Malinen <teppo.malinen@bitbar.com, Jarno Tuovinen <jarno.tuovinen@bitbar.com>', author_email='info@bitbar.com', url='http://www.testdroid.com', license='Apache License v2.0', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=True, install_requires=[ 'requests', 'pillow', ], entry_points = { 'console_scripts': [ 'testdroid = testdroid:main', ], }, ) " "Tweak logic used by UI to detect language Chromium and WebKit based browsers have the window.navigator.languages attribute, which is an ordered array of preferred languages as configured in the browser’s settings. Although changing the language in Chrome results in an Accept-Language header being added to requests, window.navigator.language still returns the language specified by the OS. I’ve tested this with Firefox, Chrome, IE 11, and Edge. Connect #5360","/* jshint ignore:start */ var sprintf = require('sprintf-js').sprintf; /** * @ngdoc method * @name function:i18n#N_ * @methodOf function:N_ * @description this function marks the translatable string with N_ * for 'grunt nggettext_extract' * */ export function N_(s) { return s; } export default angular.module('I18N', []) .factory('I18NInit', ['$window', 'gettextCatalog', function ($window, gettextCatalog) { return function() { var langInfo = ($window.navigator.languages || [])[0] || $window.navigator.language || $window.navigator.userLanguage; var langUrl = langInfo.replace('-', '_'); //gettextCatalog.debug = true; gettextCatalog.setCurrentLanguage(langInfo); gettextCatalog.loadRemote('/static/languages/' + langUrl + '.json'); }; }]) .factory('i18n', ['gettextCatalog', function (gettextCatalog) { return { _: function (s) { return gettextCatalog.getString (s); }, N_: N_, sprintf: sprintf, hasTranslation: function () { return gettextCatalog.strings[gettextCatalog.currentLanguage] !== undefined; } }; }]); ","/* jshint ignore:start */ var sprintf = require('sprintf-js').sprintf; /** * @ngdoc method * @name function:i18n#N_ * @methodOf function:N_ * @description this function marks the translatable string with N_ * for 'grunt nggettext_extract' * */ export function N_(s) { return s; } export default angular.module('I18N', []) .factory('I18NInit', ['$window', 'gettextCatalog', function ($window, gettextCatalog) { return function() { var langInfo = $window.navigator.language || $window.navigator.userLanguage; var langUrl = langInfo.replace('-', '_'); //gettextCatalog.debug = true; gettextCatalog.setCurrentLanguage(langInfo); gettextCatalog.loadRemote('/static/languages/' + langUrl + '.json'); }; }]) .factory('i18n', ['gettextCatalog', function (gettextCatalog) { return { _: function (s) { return gettextCatalog.getString (s); }, N_: N_, sprintf: sprintf, hasTranslation: function () { return gettextCatalog.strings[gettextCatalog.currentLanguage] !== undefined; } }; }]); " Fix a minor typo in package name,"from distutils.core import setup import glob datas = [ ""locale/"" + l.rsplit('/')[-1]+""/LC_MESSAGES/*.*"" for l in glob.glob(""pages/locale/*"")] datas.extend([ 'templates/admin/pages/page/*.html', 'templates/pages/*.html', 'fixtures/*.json' ] ) setup( name='django-page-cms', version=__import__('pages').__version__, description='A tree based Django CMS application', author='Batiste Bieler', author_email='batiste.bieler@gmail.com', url='http://code.google.com/p/django-page-cms/', requires=('html5lib (>=0.10)', 'tagging (>=0.2.1)', 'django_mptt (>=0.2.1)', ), packages=[ 'pages', 'pages.admin', 'pages.templatetags', #'example', ], package_dir={'pages': 'pages', 'pages.locale': 'locale', 'pages.templates': 'templates'}, package_data={'pages': datas}, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', 'Programming Language :: Python :: 2.3', 'Programming Language :: JavaScript', 'Topic :: Internet :: WWW/HTTP :: Site Management', ] ) ","from distutils.core import setup import glob datas = [ ""locale/"" + l.rsplit('/')[-1]+""/LC_MESSAGES/*.*"" for l in glob.glob(""pages/locale/*"")] datas.extend([ 'templates/admin/pages/page/*.html', 'templates/pages/*.html', 'fixtures/*.json' ] ) setup( name='django-page-cms', version=__import__('pages').__version__, description='A tree based Django CMS application', author='Batiste Bieler', author_email='batiste.bieler@gmail.com', url='http://code.google.com/p/django-page-cms/', requires=('html5lib (>=0.10)', 'tagging (>=0.2.1)', 'mptt (>=0.2.1)', ), packages=[ 'pages', 'pages.admin', 'pages.templatetags', #'example', ], package_dir={'pages': 'pages', 'pages.locale': 'locale', 'pages.templates': 'templates'}, package_data={'pages': datas}, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', 'Programming Language :: Python :: 2.3', 'Programming Language :: JavaScript', 'Topic :: Internet :: WWW/HTTP :: Site Management', ] ) " Make it work with new tg Jinja quickstart,"from setuptools import setup, find_packages import os version = '0.5.1' here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.txt')).read() CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read() except IOError: README = CHANGES = '' setup(name='tgext.admin', version=version, description=""Admin Controller add-on for basic TG identity model."", long_description=README + ""\n"" + CHANGES, # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=[ ""Programming Language :: Python"", ""Topic :: Software Development :: Libraries :: Python Modules"", ], keywords='turbogears2.extension, TG2, TG, sprox, Rest, internet, admin', author='Christopher Perkins', author_email='chris@percious.com', url='tgtools.googlecode.com', license='MIT', packages=find_packages(exclude=['ez_setup']), namespace_packages=['tgext'], include_package_data=True, zip_safe=True, install_requires=[ 'setuptools', 'tgext.crud>=0.5.1', # -*- Extra requirements: -*- ], entry_points="""""" # -*- Entry points: -*- """""", ) ","from setuptools import setup, find_packages import os version = '0.5.1' here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.txt')).read() CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read() except IOError: README = CHANGES = '' setup(name='tgext.admin', version=version, description=""Admin Controller add-on for basic TG identity model."", long_description=README + ""\n"" + CHANGES, # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=[ ""Programming Language :: Python"", ""Topic :: Software Development :: Libraries :: Python Modules"", ], keywords='turbogears2.extension, TG2, TG, sprox, Rest, internet, admin', author='Christopher Perkins', author_email='chris@percious.com', url='tgtools.googlecode.com', license='MIT', packages=find_packages(exclude=['ez_setup']), namespace_packages=['tgext'], include_package_data=True, zip_safe=True, install_requires=[ 'setuptools', 'tgext.crud>=0.4', # -*- Extra requirements: -*- ], entry_points="""""" # -*- Entry points: -*- """""", ) " "Fix bug TypeError, not exist values (json) is dict None","#!/usr/bin/env python # -*- coding: utf-8 -* import json from django import forms from django.template.loader import render_to_string from .models import Field, FieldOption class JSONField(forms.TextInput): model = Field def render(self, name, value, attrs=None): elements = [] try: values = json.loads(value) except TypeError: values = {} objs = self.model.objects.filter( application__contains=self.attrs.get('_model', None)) for obj in objs: o = {} o['name'] = obj.name o['slug'] = obj.slug element_attr = {} element_attr['name'] = obj.name element_attr['slug'] = obj.slug """""" element_attr['value'] = '1' element_attr['obj_value'] = values.get(obj.slug, '') """""" if obj.type in [""checkbox"", ""radiobox""]: obj_value = [] fo = FieldOption.objects.filter(field=obj) for i in fo: key = ""{}_{}"".format(obj.slug, i.option.slug) obj_value.append(values.get(key, '')) element_attr['list'] = zip(fo, obj_value) o['element'] = render_to_string( ""admin/opps/fields/json_{}.html"".format(obj.type), dictionary=element_attr ) elements.append(o) return render_to_string( ""admin/opps/fields/json.html"", {""elements"": elements, ""name"": name, ""value"": value}) ","#!/usr/bin/env python # -*- coding: utf-8 -* import json from django import forms from django.template.loader import render_to_string from .models import Field, Option, FieldOption class JSONField(forms.TextInput): model = Field def render(self, name, value, attrs=None): elements = [] values = json.loads(value) objs = self.model.objects.all() for obj in objs: o = {} o['name'] = obj.name o['slug'] = obj.slug element_attr = {} element_attr['name'] = obj.name element_attr['slug'] = obj.slug """""" element_attr['value'] = '1' element_attr['obj_value'] = values.get(obj.slug, '') """""" if obj.type in [""checkbox"", ""radiobox""]: obj_value = [] fo = FieldOption.objects.filter(field=obj) for i in fo: key = ""{}_{}"".format(obj.slug, i.option.slug) obj_value.append(values.get(key, '')) element_attr['list'] = zip(fo, obj_value) o['element'] = render_to_string( ""admin/opps/fields/json_{}.html"".format(obj.type), dictionary=element_attr ) elements.append(o) return render_to_string( ""admin/opps/fields/json.html"", {""elements"": elements, ""name"": name, ""value"": value}) " Reduce who to follow image size,"<div class=""bg-white p-3 mb-3""> <h5>Who to follow</h5> @if (count($follow_suggestions)) @foreach ($follow_suggestions as $follow_suggestion) <div class=""media""> <a href=""{{ url('/' . $follow_suggestion->username) }}""> <img class=""d-flex align-self-start rounded-circle mr-3"" src=""{{ $follow_suggestion->photo($follow_suggestion->id) }}"" style=""max-width: 32px; max-height: 32px;"" alt=""User photo""> </a> <div class=""media-body truncate""> <h6 class=""mt-0 mb-1""> <a class=""text-primary-hover"" href=""{{ url('/' . $follow_suggestion->username) }}"" style=""color: #555;""> {{ $follow_suggestion->name }} </a> @if ($follow_suggestion->verified > 0) <i class=""fa fa-check-circle text-primary""></i> @endif <span class=""text-muted"" style=""font-size: 13px; font-weight: 400;"" title=""{{ $follow_suggestion->username }}"">{{ '@' . $follow_suggestion->username }}</span> </h6> <user-follow :original-following=""false"" :user-id=""{{ $follow_suggestion->id }}"" :current-user-id=""{{ Auth::id() }}""></user-follow> </div> </div> <hr class=""mt-2 mb-2""> @endforeach <a href=""#"">Search by interests</a> @else No suggestions. @endif </div> ","<div class=""bg-white p-3 mb-3""> <h5>Who to follow</h5> @if (count($follow_suggestions)) @foreach ($follow_suggestions as $follow_suggestion) <div class=""media""> <a href=""{{ url('/' . $follow_suggestion->username) }}""> <img class=""d-flex align-self-start rounded-circle mr-3"" src=""{{ $follow_suggestion->photo($follow_suggestion->id) }}"" style=""max-width: 48px; max-height: 48px;"" alt=""User photo""> </a> <div class=""media-body truncate""> <h6 class=""mt-0 mb-1""> <a class=""text-primary-hover"" href=""{{ url('/' . $follow_suggestion->username) }}"" style=""color: #555;""> {{ $follow_suggestion->name }} </a> @if ($follow_suggestion->verified > 0) <i class=""fa fa-check-circle text-primary""></i> @endif <span class=""text-muted"" style=""font-size: 13px; font-weight: 400;"">{{ '@' . $follow_suggestion->username }}</span> </h6> <user-follow :original-following=""false"" :user-id=""{{ $follow_suggestion->id }}"" :current-user-id=""{{ Auth::id() }}""></user-follow> </div> </div> <hr class=""mt-2 mb-2""> @endforeach <a href=""#"">Search by interests</a> @else No suggestions. @endif </div> " Fix coverage and threshold checking,"const webpack = require('webpack'); module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine'], preprocessors: { 'src/**/testception.js': ['coverage'], 'src/**/testception-spec.js': ['webpack'] }, files: ['src/testception-spec.js'], webpack: { module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel' }, { test: /testception\.js$/, include: /src/, loader: 'isparta' } ] } }, reporters: ['progress', 'coverage'], coverageReporter: { dir: 'coverage', subdir: '.', reporters: [ { type: 'html' }, { type: 'text-summary' } ], check: { each: { statements: 100, branches: 100, functions: 100, lines: 100 } } }, port: 8080, runnerPort: 9100, colors: true, logLevel: config.LOG_INFO, autoWatch: false, browsers: ['PhantomJS'], captureTimeout: 5000, singleRun: true }); }; ","const webpack = require('webpack'); module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine'], preprocessors: { 'src/**/*.js': ['webpack', 'coverage', 'sourcemap'], 'test/spec/**/*.js': ['webpack', 'sourcemap'] }, files: ['src/testception-spec.js'], webpack: { module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel' // 'babel-loader' is also a legal name to reference }, { test: /^(?!.*spec\.js?$).*\.js?$/, include: /src\//, loader: 'isparta' } ] }, devtool: 'inline-source-map' }, reporters: ['progress', 'coverage'], coverageReporter: { dir: 'coverage', subdir: '.', reporters: [ { type: 'html' }, { type: 'text-summary' } ] }, port: 8080, runnerPort: 9100, colors: true, logLevel: config.LOG_INFO, autoWatch: false, browsers: ['PhantomJS'], captureTimeout: 5000, singleRun: true }); }; " Remove import of tag trait,"<?php namespace SlmMail\Mail\Message\Provider; use SlmMail\Mail\Message\ProvidesOptions; use Zend\Mail\Message; class Mailgun extends Message { use ProvidesOptions; const TAG_LIMIT = 3; /** * @var array */ protected $tags = array(); /** * Get all tags for this message * * @return array */ public function getTags() { return $this->tags; } /** * Set all tags for this message * * @param array $tags * @return self */ public function setTags(array $tags) { if (count($tags) > self::TAG_LIMIT) { throw new Exception\InvalidArgumentException(sprintf( 'Mailgun only allows up to %s tags', self::TAG_LIMIT )); } $this->tags = $tags; return $this; } /** * Add a tag to this message * * @param string $tag * @return self */ public function addTag($tag) { if (count($this->tags)+1 > self::TAG_LIMIT) { throw new Exception\InvalidArgumentException(sprintf( 'Mailgun only allows up to %s tags', self::TAG_LIMIT )); } $this->tags[] = (string) $tag; return $this; } } ","<?php namespace SlmMail\Mail\Message\Provider; use SlmMail\Mail\Message\ProvidesOptions; use SlmMail\Mail\Message\ProvidesTags; use Zend\Mail\Message; class Mailgun extends Message { use ProvidesOptions; const TAG_LIMIT = 3; /** * @var array */ protected $tags = array(); /** * Get all tags for this message * * @return array */ public function getTags() { return $this->tags; } /** * Set all tags for this message * * @param array $tags * @return self */ public function setTags(array $tags) { if (count($tags) > self::TAG_LIMIT) { throw new Exception\InvalidArgumentException(sprintf( 'Mailgun only allows up to %s tags', self::TAG_LIMIT )); } $this->tags = $tags; return $this; } /** * Add a tag to this message * * @param string $tag * @return self */ public function addTag($tag) { if (count($this->tags)+1 > self::TAG_LIMIT) { throw new Exception\InvalidArgumentException(sprintf( 'Mailgun only allows up to %s tags', self::TAG_LIMIT )); } $this->tags[] = (string) $tag; return $this; } } " "Make loop stopable, some fixes.","import time class Application(object): def __init__(self, startup_args={}): self._state = None self._states = {} self._mspf = None # ms per frame self._running = False @property def running(self): return self._running @property def state(self): if self._state: return self._state.__class__.__name__ else: raise AttributeError(""There is no available state."") @state.setter def state(self, name): if name in self._states: self._state = self._states[name] else: raise KeyError(""No such state: '{0}'."".format(name)) def register_state(self, state): """"""Add new state and initiate it with owner."""""" name = state.__name__ self._states[name] = state(self) if len(self._states) == 1: self._state = self._states[name] def stop(self): self._running = False def loop(self): if self._state: self._running = True else: raise AttributeError(""There is no avalable state."") while self._running: start_time = time.perf_counter() self._state.events() self._state.update() self._state.render() finish_time = time.perf_counter() delta = finish_time - start_time if delta <= self._mspf: time.sleep((self._mspf - delta) / 1000.0) else: pass # Log FPS drawdowns. ","import time class Application(object): def __init__(self, startup_args={}): self._state = None self._states = {} self._mspf = None # ms per frame @property def state(self): return self._state @state.setter def state(self, name): if name in self._states: self._state = self._states[name] else: raise KeyError(""No such state: '{0}'."".format(name)) def register_state(self, state): """"""Add new state and initiate it with owner."""""" name = state.__name__ self._states[name] = state(self) if len(self._states) == 1: self._state = self._states[name] def loop(self): while True: start_time = time.perf_counter() self._state.events() self._state.update() self._state.render() finish_time = time.perf_counter() delta = finish_time - start_time if delta <= self._mspf: time.sleep((self._mspf - delta) / 1000.0) else: pass # Log FPS drawdowns. " Fix bug with Query Scope predictor.,"package lucene4ir.predictor.pre; import lucene4ir.predictor.PreQPPredictor; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Term; import org.apache.lucene.search.*; import java.io.IOException; import java.util.HashSet; import java.util.Set; /** * Created by Harry Scells on 28/8/17. */ public class QSQPPredictor extends PreQPPredictor { public QSQPPredictor(IndexReader ir) { super(ir); } public String name() { return ""QueryScope""; } @Override public double scoreQuery(String qno, Query q) { // Number of documents containing at least one of the query terms. Set<Integer> Nq = new HashSet<>(); IndexSearcher searcher = new IndexSearcher(reader); String[] termTuples = q.toString().split("" ""); for (String termTuple : termTuples) { String[] terms = termTuple.split("":""); if (terms.length == 2) { String term = terms[1]; try { // Add the docs that contain this term to the set Nq. TermQuery query = new TermQuery(new Term(""all"", term)); TopDocs docs = searcher.search(query, reader.numDocs()); for (ScoreDoc scoreDoc : docs.scoreDocs) { Nq.add(scoreDoc.doc); } } catch (IOException e) { e.printStackTrace(); System.exit(1); } } } return -Math.log((1.0 + Nq.size()) / (1.0 + reader.numDocs())); } } ","package lucene4ir.predictor.pre; import lucene4ir.predictor.PreQPPredictor; import org.apache.lucene.index.IndexReader; import org.apache.lucene.search.Query; import java.io.IOException; /** * Created by Harry Scells on 28/8/17. */ public class QSQPPredictor extends PreQPPredictor { public QSQPPredictor(IndexReader ir) { super(ir); } public String name() { return ""QueryScope""; } @Override public double scoreQuery(String qno, Query q) { // Number of documents containing at least one of the query terms. double Nq = Double.POSITIVE_INFINITY; String[] termTuples = q.toString().split("" ""); for (String termTuple : termTuples) { String[] terms = termTuple.split("":""); if (terms.length == 2) { String term = terms[1]; try { double df = getDF(term); // What is the smallest possible df? if (df < Nq && df > 0) { Nq = df; } } catch (IOException e) { e.printStackTrace(); } } } return -Math.log((1 + Nq) / (1 + reader.numDocs())); } } " Add babel preset on serverBuild,"const TerserJsPlugin = require('terser-webpack-plugin'); const commonModule = { exclude: /(node_modules)/, use: { loader: ""babel-loader"", options: { presets: [""@babel/preset-env""], plugins: [ ""@babel/plugin-transform-modules-commonjs"", ""@babel/plugin-transform-runtime"" ] } } }; const serverBuild = { mode: 'production', entry: './src/twig.js', target: 'node', node: false, output: { path: __dirname, filename: 'twig.js', library: 'Twig', libraryTarget: 'umd' }, module: { rules: [commonModule], }, optimization: { minimize: false } }; const clientBuild = { mode: 'production', entry: './src/twig.js', target: 'web', node: { __dirname: false, __filename: false }, module: { rules: [commonModule] }, output: { path: __dirname, filename: 'twig.min.js', library: 'Twig', libraryTarget: 'umd' }, optimization: { minimize: true, minimizer: [new TerserJsPlugin({ include: /\.min\.js$/ })] } }; module.exports = [serverBuild, clientBuild]; ","const TerserJsPlugin = require('terser-webpack-plugin'); const serverBuild = { mode: 'production', entry: './src/twig.js', target: 'node', node: false, output: { path: __dirname, filename: 'twig.js', library: 'Twig', libraryTarget: 'umd' }, optimization: { minimize: false } }; const clientBuild = { mode: 'production', entry: './src/twig.js', target: 'web', node: { __dirname: false, __filename: false }, module: { rules: [ { exclude: /(node_modules)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'], plugins: [ '@babel/plugin-transform-modules-commonjs', '@babel/plugin-transform-runtime' ] } } } ] }, output: { path: __dirname, filename: 'twig.min.js', library: 'Twig', libraryTarget: 'umd' }, optimization: { minimize: true, minimizer: [new TerserJsPlugin({ include: /\.min\.js$/ })] } }; module.exports = [serverBuild, clientBuild]; " Use 2 spaces indents in Yaml file,"<?php namespace Craft; use Symfony\Component\Yaml\Yaml; /** * Schematic Data Model. * * Encapsulates data that has been exported via schematic. * * @author Itmundi * @copyright Copyright (c) 2015, Itmundi * @license MIT * * @link http://www.itmundi.nl */ class Schematic_DataModel extends BaseModel { /** * Define attributes. * * @inheritdoc */ protected function defineAttributes() { return array( 'assets' => AttributeType::Mixed, 'fields' => AttributeType::Mixed, 'globals' => AttributeType::Mixed, 'plugins' => AttributeType::Mixed, 'sections' => AttributeType::Mixed, 'userGroups' => AttributeType::Mixed, 'pluginData' => array(AttributeType::Mixed, 'default' => array()), ); } /** * Populate data model from yaml. * * @param string $yaml * * @return Schematic_DataModel */ public static function fromYaml($yaml) { $data = Yaml::parse($yaml); return $data === null ? null : new static($data); } /** * Populate yaml from data model. * * @param array $data * * @return Schematic_DataModel */ public static function toYaml(array $data) { $data = $data === null ? null : new static($data); return Yaml::dump($data->attributes, 12, 2); } } ","<?php namespace Craft; use Symfony\Component\Yaml\Yaml; /** * Schematic Data Model. * * Encapsulates data that has been exported via schematic. * * @author Itmundi * @copyright Copyright (c) 2015, Itmundi * @license MIT * * @link http://www.itmundi.nl */ class Schematic_DataModel extends BaseModel { /** * Define attributes. * * @inheritdoc */ protected function defineAttributes() { return array( 'assets' => AttributeType::Mixed, 'fields' => AttributeType::Mixed, 'globals' => AttributeType::Mixed, 'plugins' => AttributeType::Mixed, 'sections' => AttributeType::Mixed, 'userGroups' => AttributeType::Mixed, 'pluginData' => array(AttributeType::Mixed, 'default' => array()), ); } /** * Populate data model from yaml. * * @param string $yaml * * @return Schematic_DataModel */ public static function fromYaml($yaml) { $data = Yaml::parse($yaml); return $data === null ? null : new static($data); } /** * Populate yaml from data model. * * @param array $data * * @return Schematic_DataModel */ public static function toYaml(array $data) { $data = $data === null ? null : new static($data); return Yaml::dump($data->attributes, 12); } } " Add sample urls to json.dump,"import os, os.path import random import string import json import cherrypy from . import get_pic class StringGenerator(object): @cherrypy.expose def index(self): return """"""<html> <head> <link href=""/static/css/style.css"" rel=""stylesheet""> </head> <body> wrong page </body> </html>"""""" @cherrypy.expose def get_picture(self, url=""""): return get_pic.base64_picture(url) @cherrypy.expose def search(self, query): return json.dumps({""book"": {""title"":""Gs"", ""author"":""Bash Gs"", ""url"":""https://chitanka.info/text/1""}, ""recommended"":[{""title"":""Gs1"", ""author"":""Bash Gs1"", ""url"":""https://chitanka.info/text/2""}, {""title"":""Gs2"", ""author"":""Bash Gs2"", ""url"":""https://chitanka.info/text/3""}]}) @cherrypy.expose def display(self): return cherrypy.session['mystring'] def main(): conf = { '/': { 'tools.staticdir.on': True, 'tools.staticdir.dir': os.path.join( os.path.abspath(os.path.dirname(os.path.realpath(__file__))), 'web' ) }, } cherrypy.quickstart(StringGenerator(), '/', conf) if __name__ == '__main__': main() ","import os, os.path import random import string import json import cherrypy from . import get_pic class StringGenerator(object): @cherrypy.expose def index(self): return """"""<html> <head> <link href=""/static/css/style.css"" rel=""stylesheet""> </head> <body> wrong page </body> </html>"""""" @cherrypy.expose def get_picture(self, url=""""): return get_pic.base64_picture(url) @cherrypy.expose def search(self, query): return json.dumps({""book"": {""title"":""Gs"", ""author"":""Bash Gs""}, ""recommended"":[{""title"":""Gs1"", ""author"":""Bash Gs1""}, {""title"":""Gs2"", ""author"":""Bash Gs2""}]}) @cherrypy.expose def display(self): return cherrypy.session['mystring'] def main(): conf = { '/': { 'tools.staticdir.on': True, 'tools.staticdir.dir': os.path.join( os.path.abspath(os.path.dirname(os.path.realpath(__file__))), 'web' ) }, } cherrypy.quickstart(StringGenerator(), '/', conf) if __name__ == '__main__': main() " Add tables package to run pvlib modelchain with default parameters,"import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=""feedinlib"", version=""0.1.0rc2"", description=""Creating time series from pv or wind power plants."", url=""http://github.com/oemof/feedinlib"", author=""oemof developer group"", author_email=""windpowerlib@rl-institut.de"", license=""MIT"", packages=[""feedinlib""], long_description=read(""README.rst""), long_description_content_type=""text/x-rst"", zip_safe=False, install_requires=[ ""cdsapi >= 0.1.4"", ""geopandas"", ""numpy >= 1.7.0"", ""oedialect >= 0.0.6.dev0"", ""open_FRED-cli"", ""pandas >= 0.13.1"", ""pvlib >= 0.7.0"", ""tables"", ""windpowerlib >= 0.2.0"", ""xarray >= 0.12.0"", ""tables"" ], extras_require={ ""dev"": [ ""jupyter"", ""nbformat"", ""punch.py"", ""pytest"", ""sphinx_rtd_theme"", ], ""examples"": [""jupyter""], }, ) ","import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=""feedinlib"", version=""0.1.0rc2"", description=""Creating time series from pv or wind power plants."", url=""http://github.com/oemof/feedinlib"", author=""oemof developer group"", author_email=""windpowerlib@rl-institut.de"", license=""MIT"", packages=[""feedinlib""], long_description=read(""README.rst""), long_description_content_type=""text/x-rst"", zip_safe=False, install_requires=[ ""cdsapi >= 0.1.4"", ""geopandas"", ""numpy >= 1.7.0"", ""oedialect >= 0.0.6.dev0"", ""open_FRED-cli"", ""pandas >= 0.13.1"", ""pvlib >= 0.7.0"", ""tables"", ""windpowerlib >= 0.2.0"", ""xarray >= 0.12.0"", ], extras_require={ ""dev"": [ ""jupyter"", ""nbformat"", ""punch.py"", ""pytest"", ""sphinx_rtd_theme"", ], ""examples"": [""jupyter""], }, ) " Add variable for dynamic URL for acceptance tests,"var baseURL = 'localhost:8080'; //var baseURL = 'http://mayhem-ecse428.rhcloud.com'; exports.config = { /** * language of your feature files * options: french, spanish, norwegian, polish, german, russian */ language: 'english', /** * set selenium host and port */ selenium: { host: '127.0.0.1', port: 4444 }, /** * webdriverio options * * - logLevel: stdout log level * Options: *verbose* | *silent* | *command* | *data* | *result* * * - coloredLogs: Enables colors for log output * default: true * * - singleton: Set to true if you always want to reuse the same remote * default: false * * - waitforTimeout: Default timeout for all waitForXXX commands * default: 500 */ options: { logLevel: 'silent' }, /** * desired capabilities */ capabilities: { browserName: 'chrome' }, /** * location of feature files */ featureFiles: [ 'test-cucumber/features/**/*.feature' ], /** * environment variables * * - baseUrl: sets base url for `Given I open the site ""/some/url.html""` */ env: { baseUrl: baseURL }, /** * mocha options * @see http://mochajs.org/ */ mochaOpts: { reporter: 'spec', timeout: 10000, require: 'chai' } }; ","exports.config = { /** * language of your feature files * options: french, spanish, norwegian, polish, german, russian */ language: 'english', /** * set selenium host and port */ selenium: { host: '127.0.0.1', port: 4444 }, /** * webdriverio options * * - logLevel: stdout log level * Options: *verbose* | *silent* | *command* | *data* | *result* * * - coloredLogs: Enables colors for log output * default: true * * - singleton: Set to true if you always want to reuse the same remote * default: false * * - waitforTimeout: Default timeout for all waitForXXX commands * default: 500 */ options: { logLevel: 'silent' }, /** * desired capabilities */ capabilities: { browserName: 'chrome' }, /** * location of feature files */ featureFiles: [ 'test-cucumber/features/**/*.feature' ], /** * environment variables * * - baseUrl: sets base url for `Given I open the site ""/some/url.html""` */ env: { baseUrl: 'localhost:8080' }, /** * mocha options * @see http://mochajs.org/ */ mochaOpts: { reporter: 'spec', timeout: 10000, require: 'chai' } }; " Switch statement tests for constants rather than string literals.,"import { SELECT_ORGANISATION, DESELECT_ORGANISATION, ADD_ORGANISATION, DELETE_ORGANISATION, EDIT_ORGANISATION } from '../constants/ActionTypes.js' const initalState = [ { name: 'JavaScript 101', selected: false, id: 1 } ]; export default function organisations ( state = initalState, action ) { switch (action.type) { case SELECT_ORGANISATION: return state.map(org => { if (org.id === action.id) { return Object.assign({}, org, {selected: true}) } return org }) case DESELECT_ORGANISATION: return state.map(org => { if (org.id === action.id) { return Object.assign({}, org, {selected: false}) } return org }) case ADD_ORGANISATION: return state.concat([{ name: action.name, selected: false, id: state.reduce((maxId, todo) => Math.max(maxId, todo.id), 0) +1 }]) case EDIT_ORGANISATION: return state.map(org => { if (org.id === action.id) { return Object.assign({}, org, {name: action.name}) } return org; }) case DELETE_ORGANISATION: return state.filter(org => { if (org.id !== action.id) return org; }) default: return state; } } ","const initalState = [ { name: 'JavaScript 101', selected: false, id: 1 } ]; export default function organisations ( state = initalState, action ) { switch (action.type) { case 'SELECT_ORGANISATION': return state.map(org => { if (org.id === action.id) { return Object.assign({}, org, {selected: true}) } return org }) case 'DESELECT_ORGANISATION': return state.map(org => { if (org.id === action.id) { return Object.assign({}, org, {selected: false}) } return org }) case 'ADD_ORGANISATION': return state.concat([{ name: action.name, selected: false, id: state.reduce((maxId, todo) => Math.max(maxId, todo.id), 0) +1 }]) case 'EDIT_ORGANISATION': return state.map(org => { if (org.id === action.id) { return Object.assign({}, org, {name: action.name}) } return org; }) case 'DELETE_ORGANISATION': return state.filter(org => { if (org.id !== action.id) return org; }) default: return state; } } " Reset message input after sending a message.,"import React from 'react'; import { connect } from 'react-redux'; import config from '../config' import actions from '../actions'; class Messenger extends React.Component { sendMessage() { const message = this.messageInput.value; this.props.sendMessage(this.props.chatId, message); this.messageInput.value = ''; } render() { let messengerAttachmentClass = `c-messenger__attachment ${ this.props.showAttachment ? 'state-active' : '' }`; let inputHeight = { height: `${ this.props.messengerHeight }px` }; return ( <article className=""c-messenger"" style={ inputHeight }> <button className={ messengerAttachmentClass } onClick={ this.props.toggleAttachment }> <i className=""icon-add-circle-outline""></i> </button> <textarea ref={ input => this.messageInput = input } style={ inputHeight } placeholder=""Share knowledge"" onKeyUp={ this.props.keyUpInteraction } ></textarea> <button className=""c-messenger__submit"" onClick={ () => this.sendMessage() }> <i className=""icon-send""></i> </button> </article> ); } } const mapStateToProps = (state, ownProps) => state[config.stateName]; const mapDispatchToProps = (dispatch, ownProps) => { return { sendMessage: (chatId, message) => dispatch(actions.chats.sendMessage(chatId, message)), }; }; const MessengerConnect = connect(mapStateToProps, mapDispatchToProps)(Messenger); export default MessengerConnect; ","import React from 'react'; import { connect } from 'react-redux'; import config from '../config' import actions from '../actions'; class Messenger extends React.Component { sendMessage() { const message = this.messageInput.value; this.props.sendMessage(this.props.chatId, message); } render() { let messengerAttachmentClass = `c-messenger__attachment ${ this.props.showAttachment ? 'state-active' : '' }`; let inputHeight = { height: `${ this.props.messengerHeight }px` }; return ( <article className=""c-messenger"" style={ inputHeight }> <button className={ messengerAttachmentClass } onClick={ this.props.toggleAttachment }> <i className=""icon-add-circle-outline""></i> </button> <textarea ref={ input => this.messageInput = input } style={ inputHeight } placeholder=""Share knowledge"" onKeyUp={ this.props.keyUpInteraction } ></textarea> <button className=""c-messenger__submit"" onClick={ () => this.sendMessage() }> <i className=""icon-send""></i> </button> </article> ); } } const mapStateToProps = (state, ownProps) => state[config.stateName]; const mapDispatchToProps = (dispatch, ownProps) => { return { sendMessage: (chatId, message) => dispatch(actions.chats.sendMessage(chatId, message)), }; }; const MessengerConnect = connect(mapStateToProps, mapDispatchToProps)(Messenger); export default MessengerConnect; " CHange number step on input area.,"import React, { Component } from 'react'; import TextField from 'material-ui/TextField'; import Card, { CardActions, CardContent } from 'material-ui/Card'; import Button from 'material-ui/Button'; import TaxCalculator from '../libs/TaxCalculator'; class TextFields extends Component { state = { income: 0, expenses: 0 }; calculate() { const { income, expenses } = this.state; const taxInfo = TaxCalculator.getTaxInfo(income, expenses); this.props.handleUpdate(taxInfo); } render() { return ( <Card> <CardContent> <div> <TextField label=""Income"" type=""number"" value={this.state.income} onChange={event => this.setState({ income: event.target.value })} inputProps={{ step: '10000' }} margin=""normal"" style={{ width: '100%' }} /> </div> <div> <TextField label=""Expenses"" type=""number"" value={this.state.expenses} onChange={event => this.setState({ expenses: event.target.value })} inputProps={{ step: '10000' }} margin=""normal"" style={{ width: '100%' }} /> </div> </CardContent> <CardActions> <Button onClick={() => this.calculate()}>Calculate</Button> </CardActions> </Card> ); } } export default TextFields; ","import React, { Component } from 'react'; import TextField from 'material-ui/TextField'; import Card, { CardActions, CardContent } from 'material-ui/Card'; import Button from 'material-ui/Button'; import TaxCalculator from '../libs/TaxCalculator'; class TextFields extends Component { state = { income: 0, expenses: 0 }; calculate() { const { income, expenses } = this.state; const taxInfo = TaxCalculator.getTaxInfo(income, expenses); this.props.handleUpdate(taxInfo); } render() { return ( <Card> <CardContent> <div> <TextField label=""Income"" type=""number"" value={this.state.income} onChange={event => this.setState({ income: event.target.value })} margin=""normal"" style={{ width: '100%' }} /> </div> <div> <TextField label=""Expenses"" type=""number"" value={this.state.expenses} onChange={event => this.setState({ expenses: event.target.value })} margin=""normal"" style={{ width: '100%' }} /> </div> </CardContent> <CardActions> <Button onClick={() => this.calculate()}>Calculate</Button> </CardActions> </Card> ); } } export default TextFields; " [NodeBundle] Set correct typehints on methods and properties,"<?php namespace Kunstmaan\NodeBundle\Event; use Kunstmaan\AdminBundle\Event\BcEvent; use Kunstmaan\NodeBundle\Entity\HasNodeInterface; use Kunstmaan\NodeBundle\Entity\Node; use Kunstmaan\NodeBundle\Entity\NodeTranslation; use Symfony\Component\HttpFoundation\Request; final class SlugSecurityEvent extends BcEvent { /** @var Node|null */ private $node; /** @var NodeTranslation|null */ private $nodeTranslation; /** @var HasNodeInterface|null */ private $entity; /** @var Request|null */ private $request; /** * @return Node|null */ public function getNode() { return $this->node; } /** * @param Node $node */ public function setNode($node) { $this->node = $node; return $this; } /** * @return NodeTranslation|null */ public function getNodeTranslation() { return $this->nodeTranslation; } /** * @param NodeTranslation $nodeTranslation */ public function setNodeTranslation($nodeTranslation) { $this->nodeTranslation = $nodeTranslation; return $this; } /** * @return HasNodeInterface|null */ public function getEntity() { return $this->entity; } /** * @param HasNodeInterface $entity */ public function setEntity($entity) { $this->entity = $entity; return $this; } /** * @return Request|null */ public function getRequest() { return $this->request; } /** * @param Request $request */ public function setRequest($request) { $this->request = $request; return $this; } } ","<?php namespace Kunstmaan\NodeBundle\Event; use Kunstmaan\AdminBundle\Event\BcEvent; final class SlugSecurityEvent extends BcEvent { private $node; private $nodeTranslation; private $entity; private $request; /** * @return mixed */ public function getNode() { return $this->node; } /** * @param mixed $node */ public function setNode($node) { $this->node = $node; return $this; } /** * @return mixed */ public function getNodeTranslation() { return $this->nodeTranslation; } /** * @param mixed $nodeTranslation */ public function setNodeTranslation($nodeTranslation) { $this->nodeTranslation = $nodeTranslation; return $this; } /** * @return mixed */ public function getEntity() { return $this->entity; } /** * @param mixed $entity */ public function setEntity($entity) { $this->entity = $entity; return $this; } /** * @return mixed */ public function getRequest() { return $this->request; } /** * @param mixed $request */ public function setRequest($request) { $this->request = $request; return $this; } } " Fix null pointer in time chart,"package com.platypii.baseline.views.charts; import com.platypii.baseline.events.ChartFocusEvent; import com.platypii.baseline.measurements.MLocation; import android.content.Context; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import java.util.Collections; import org.greenrobot.eventbus.EventBus; public class TimeChartTouchable extends TimeChart { public TimeChartTouchable(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onTouchEvent(MotionEvent event) { super.onTouchEvent(event); if (event.getAction() == MotionEvent.ACTION_MOVE) { final long millis = (long) plot.getXinverse(0, event.getX()); // Find nearest data point final MLocation closest = findClosest(millis); // Emit chart focus event EventBus.getDefault().post(new ChartFocusEvent(closest)); } return true; // if the event was handled } // Avoid creating new object just to binary search private final MLocation touchLocation = new MLocation(); /** * Performs a binary search for the nearest data point */ @Nullable private MLocation findClosest(long millis) { if (trackData != null && !trackData.isEmpty()) { touchLocation.millis = millis; int closest_index = Collections.binarySearch(trackData, touchLocation); if (closest_index < 0) closest_index = -closest_index; if (closest_index == trackData.size()) closest_index--; return trackData.get(closest_index); } else { return null; } } } ","package com.platypii.baseline.views.charts; import com.platypii.baseline.events.ChartFocusEvent; import com.platypii.baseline.measurements.MLocation; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import java.util.Collections; import org.greenrobot.eventbus.EventBus; public class TimeChartTouchable extends TimeChart { public TimeChartTouchable(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onTouchEvent(MotionEvent event) { super.onTouchEvent(event); if (event.getAction() == MotionEvent.ACTION_MOVE) { final long millis = (long) plot.getXinverse(0, event.getX()); // Find nearest data point final MLocation closest = findClosest(millis); // Emit chart focus event EventBus.getDefault().post(new ChartFocusEvent(closest)); } return true; // if the event was handled } // Avoid creating new object just to binary search private final MLocation touchLocation = new MLocation(); /** * Performs a binary search for the nearest data point */ private MLocation findClosest(long millis) { touchLocation.millis = millis; int closest_index = Collections.binarySearch(trackData, touchLocation); if (closest_index < 0) closest_index = -closest_index; if (closest_index == trackData.size()) closest_index--; return trackData.get(closest_index); } } " Send demo turn over websocket.,"import json import tornado.ioloop import tornado.web from tornado.websocket import WebSocketHandler from tornado import template class MainHandler(tornado.web.RequestHandler): DEMO_TURN = { 'player_id': 'abc', 'player_turn': 1, 'card': { 'id': 'card_1', 'name': 'Card Name', 'image': None, 'description': 'This is a card', 'attributes': { 'power': 9001, 'strength': 100, 'speed': 50, 'agility': 20, 'smell': 4 } } } def get(self): self.write(application.template_loader.load(""index.html"").generate(turn=self.DEMO_TURN)) class SocketHandler(WebSocketHandler): def open(self): print(""WebSocket opened"") def on_message(self, message): self.write_message(json.dumps(self.DEMO_TURN)) def on_close(self): print(""WebSocket closed"") application = tornado.web.Application([ (r""/"", MainHandler), (r""/sockets"", SocketHandler), (r""/content/(.*)"", tornado.web.StaticFileHandler, {""path"": ""static""}) #(r""/"", MainHandler), ]) if __name__ == ""__main__"": application.listen(8888) application.template_loader = template.Loader(""templates"") tornado.ioloop.IOLoop.current().start()","import tornado.ioloop import tornado.web from tornado.websocket import WebSocketHandler from tornado import template class MainHandler(tornado.web.RequestHandler): DEMO_TURN = { 'player_id': 'abc', 'player_turn': 1, 'card': { 'id': 'card_1', 'name': 'Card Name', 'image': None, 'description': 'This is a card', 'attributes': { 'power': 9001, 'strength': 100, 'speed': 50, 'agility': 20, 'smell': 4 } } } def get(self): self.write(application.template_loader.load(""index.html"").generate(turn=self.DEMO_TURN)) class SocketHandler(WebSocketHandler): def open(self): print(""WebSocket opened"") def on_message(self, message): self.write_message(u""You said: "" + message) def on_close(self): print(""WebSocket closed"") application = tornado.web.Application([ (r""/"", MainHandler), (r""/sockets"", SocketHandler), (r""/content/(.*)"", tornado.web.StaticFileHandler, {""path"": ""static""}) #(r""/"", MainHandler), ]) if __name__ == ""__main__"": application.listen(8888) application.template_loader = template.Loader(""templates"") tornado.ioloop.IOLoop.current().start()" Set workers to use m1.small instances.,"package JpAws; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.RunInstancesRequest; import datameer.awstasks.aws.ec2.InstanceGroupImpl; import java.io.IOException; import java.util.concurrent.TimeUnit; /** * This class is used for spawning groups of workers. * @author charlesmunger */ public class WorkerMachines extends Ec2Machine { private String masterDomainName; /** * This creates a new workerMachines object, which is a local interface for managing groups of * workers. * @param masterDomainName Specifies the hostname of the Master, for the workers to connect * to. */ public WorkerMachines(String masterDomainName) { this.masterDomainName = masterDomainName; } @Override public String[] start(int numWorkers) throws IOException { AmazonEC2 ec2 = new AmazonEC2Client(PregelAuthenticator.get()); instanceGroup = new InstanceGroupImpl(ec2); RunInstancesRequest launchConfiguration = new RunInstancesRequest(Machine.AMIID, numWorkers, numWorkers) .withKeyName(PregelAuthenticator.get().getPrivateKeyName()) .withInstanceType(""m1.small"") .withSecurityGroupIds(Ec2Machine.SECURITY_GROUP); System.out.println(launchConfiguration.toString()); instanceGroup.launch(launchConfiguration, TimeUnit.MINUTES, 5); WorkerThread runWorker = new WorkerThread(instanceGroup, masterDomainName); runWorker.start(); return null; } } ","package JpAws; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.RunInstancesRequest; import datameer.awstasks.aws.ec2.InstanceGroupImpl; import java.io.IOException; import java.util.concurrent.TimeUnit; /** * This class is used for spawning groups of workers. * @author charlesmunger */ public class WorkerMachines extends Ec2Machine { private String masterDomainName; /** * This creates a new workerMachines object, which is a local interface for managing groups of * workers. * @param masterDomainName Specifies the hostname of the Master, for the workers to connect * to. */ public WorkerMachines(String masterDomainName) { this.masterDomainName = masterDomainName; } @Override public String[] start(int numWorkers) throws IOException { AmazonEC2 ec2 = new AmazonEC2Client(PregelAuthenticator.get()); instanceGroup = new InstanceGroupImpl(ec2); RunInstancesRequest launchConfiguration = new RunInstancesRequest(Machine.AMIID, numWorkers, numWorkers) .withKeyName(PregelAuthenticator.get().getPrivateKeyName()) .withInstanceType(""t1.micro"") .withSecurityGroupIds(Ec2Machine.SECURITY_GROUP); System.out.println(launchConfiguration.toString()); instanceGroup.launch(launchConfiguration, TimeUnit.MINUTES, 5); WorkerThread runWorker = new WorkerThread(instanceGroup, masterDomainName); runWorker.start(); return null; } } " Clear current suite on config change.,"import { Action } from '../actions/nightwatch' const initialState = {} export default function nightwatch(state = initialState, action) { switch (action.type) { case Action.SET_NIGHTWATCH_EXECUTABLE: { return { ...state, executablePath: action.payload.executablePath } } case Action.SET_NIGHTWATCH_CONFIG: { return { ...state, configPath: action.payload.configPath, suitesRoot: action.payload.suitesRoot, environments: action.payload.environments, currentEnvironment: action.payload.currentEnvironment, currentSuite: null } } case Action.SET_CURRENT_SUITE: { return { ...state, currentSuite: action.payload.currentSuite } } case Action.CLEAR_CURRENT_SUITE: { return { ...state, currentSuite: null } } case Action.SET_CURRENT_ENVIRONMENT: { return { ...state, currentEnvironment: action.payload.currentEnvironment } } default: { return state } } } ","import { Action } from '../actions/nightwatch' const initialState = {} export default function nightwatch(state = initialState, action) { switch (action.type) { case Action.SET_NIGHTWATCH_EXECUTABLE: { return { ...state, executablePath: action.payload.executablePath } } case Action.SET_NIGHTWATCH_CONFIG: { return { ...state, configPath: action.payload.configPath, suitesRoot: action.payload.suitesRoot, environments: action.payload.environments, currentEnvironment: action.payload.currentEnvironment } } case Action.SET_CURRENT_SUITE: { return { ...state, currentSuite: action.payload.currentSuite } } case Action.CLEAR_CURRENT_SUITE: { return { ...state, currentSuite: null } } case Action.SET_CURRENT_ENVIRONMENT: { return { ...state, currentEnvironment: action.payload.currentEnvironment } } default: { return state } } } " "Remove compile step from watch Potentially causing infinite loop re-compile","module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), banner: '/*! <%= pkg.name %> <%= pkg.version %> | Copyright <%= grunt.template.today(""yyyy"") %> <%= pkg.author.name %> | <%= pkg.licenses[0].type %> License */\n', concat: { options: { stripBanners: { block: true }, banner: '<%= banner %>' }, dist: { src: [ 'fileHash.js' ], dest: 'fileHash.js' } }, jshint: { files: [ 'fileHash.js' ] }, nodeunit: { files: [ 'test/test-*.js' ], }, watch: { files: [ 'fileHash.js', 'test/*.js' ], tasks: [ 'test' ] } }); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.registerTask('test', [ 'jshint', 'nodeunit' ]); grunt.registerTask('compile', [ 'concat' ]); grunt.registerTask('release', [ 'test', 'compile' ]); grunt.registerTask('dev', [ 'watch' ]); grunt.registerTask('default', [ 'dev' ]); }; ","module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), banner: '/*! <%= pkg.name %> <%= pkg.version %> | Copyright <%= grunt.template.today(""yyyy"") %> <%= pkg.author.name %> | <%= pkg.licenses[0].type %> License */\n', concat: { options: { stripBanners: { block: true }, banner: '<%= banner %>' }, dist: { src: [ 'fileHash.js' ], dest: 'fileHash.js' } }, jshint: { files: [ 'fileHash.js' ] }, nodeunit: { files: [ 'test/test-*.js' ], }, watch: { files: [ 'fileHash.js', 'test/*.js' ], tasks: [ 'release' ] } }); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.registerTask('test', [ 'jshint', 'nodeunit' ]); grunt.registerTask('compile', [ 'concat' ]); grunt.registerTask('release', [ 'test', 'compile' ]); grunt.registerTask('dev', [ 'watch' ]); grunt.registerTask('default', [ 'dev' ]); }; " Fix broken content from PhJS,"# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. from subprocess import check_output, CalledProcessError from urllib import unquote def application(env, start_response): status = ""200 OK"" response = """" qs = env.get(""QUERY_STRING"", None) if not qs or not qs.startswith(""_escaped_fragment_=""): status = ""500 Internal Server Error"" else: url = ""http://platformio.org/#!"" + unquote(qs[19:]) try: response = get_webcontent(url) if ""404 Not Found"" in response: status = ""404 Not Found"" except Exception: status = ""500 Internal Server Error"" start_response(status, [(""Content-Type"", ""text/html""), (""Content-Length"", str(len(response)))]) return response def get_webcontent(url): retrynums = 0 while retrynums < 5: try: response = check_output([ ""phantomjs"", ""--disk-cache=true"", ""--load-images=false"", ""crawler.js"", url ]) if 'ng-view=' not in response: raise CalledProcessError() return response except CalledProcessError: retrynums += 1 raise Exception(""Could not retrieve content from %s"" % url) ","# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. from subprocess import check_output, CalledProcessError from urllib import unquote def application(env, start_response): status = ""200 OK"" response = """" qs = env.get(""QUERY_STRING"", None) if not qs or not qs.startswith(""_escaped_fragment_=""): status = ""500 Internal Server Error"" else: url = ""http://platformio.org/#!"" + unquote(qs[19:]) try: response = get_webcontent(url) if ""404 Not Found"" in response: status = ""404 Not Found"" except Exception: status = ""500 Internal Server Error"" start_response(status, [(""Content-Type"", ""text/html""), (""Content-Length"", str(len(response)))]) return response def get_webcontent(url): retrynums = 0 while retrynums < 5: try: response = check_output([ ""phantomjs"", ""--disk-cache=true"", ""--load-images=false"", ""crawler.js"", url ]) if 'class=""ng-scope""' not in response: raise CalledProcessError() return response except CalledProcessError: retrynums += 1 raise Exception(""Could not retrieve content from %s"" % url) " Allow messages to come in through GET,"import webapp2 from google.appengine.api import channel from google.appengine.api import users open_channels = set() class ChannelDidConnect(webapp2.RequestHandler): def post(self): print ""Got connection"" open_channels.add(self.request.get(""from"")) class ChannelDisconnect(webapp2.RequestHandler): def post(self): print ""Got disconnection"" channelId = self.request.get(""from"") if channelId in open_channels: open_channels.remove(channelId) class ChannelRequest(webapp2.RequestHandler): def get(self): user = users.get_current_user() if not user: self.response.write({""token"": """"}) return token = channel.create_channel(user.user_id()) self.response.write( ""{\""token\"": \""%s\""}"" % token ) class Message(webapp2.RequestHandler): def post(self): self.handleRequest() def get(self): self.handleRequest() def handleRequest(self): print open_channels for channelId in open_channels: channel.send_message(channelId, ""message=%s&author=%s"" % (self.request.params[""message""], self.request.params[""author""])) app = webapp2.WSGIApplication([ ('/api/channel', ChannelRequest), ('/api/message', Message), ('/_ah/channel/connected/', ChannelDidConnect), ('/_ah/channel/disconnected/', ChannelDisconnect), ]) ","import webapp2 from google.appengine.api import channel from google.appengine.api import users open_channels = set() class ChannelDidConnect(webapp2.RequestHandler): def post(self): print ""Got connection"" open_channels.add(self.request.get(""from"")) class ChannelDisconnect(webapp2.RequestHandler): def post(self): print ""Got disconnection"" channelId = self.request.get(""from"") if channelId in open_channels: open_channels.remove(channelId) class ChannelRequest(webapp2.RequestHandler): def get(self): user = users.get_current_user() if not user: self.response.write({""token"": """"}) return token = channel.create_channel(user.user_id()) self.response.write( ""{\""token\"": \""%s\""}"" % token ) class Message(webapp2.RequestHandler): def post(self): # Only accept messages from logged in users user = users.get_current_user() if not user: return print open_channels for channelId in open_channels: channel.send_message(channelId, ""message=%s&author=%s"" % (self.request.POST[""message""], self.request.POST[""author""])) app = webapp2.WSGIApplication([ ('/api/channel', ChannelRequest), ('/api/message', Message), ('/_ah/channel/connected/', ChannelDidConnect), ('/_ah/channel/disconnected/', ChannelDisconnect), ]) " Fix AccordionWrapper initialization by passing initial 'accordion' and 'onChange' props to the container constructor.,"// @flow import React, { Component } from 'react'; import type { ElementProps } from 'react'; import { Provider, Subscribe } from 'unstated'; import AccordionContainer from '../AccordionContainer/AccordionContainer'; import Accordion from './accordion'; type AccordionWrapperProps = ElementProps<'div'> & { accordion: boolean, onChange: Function, }; const defaultProps: AccordionWrapperProps = { accordion: true, onChange: () => {}, className: 'accordion', children: null, }; class AccordionWrapper extends Component<AccordionWrapperProps> { accordionStore = new AccordionContainer({ accordion: this.props.accordion, onChange: this.props.onChange, }); static defaultProps = defaultProps; componentDidMount() { this.accordionStore.setAccordion(this.props.accordion); this.accordionStore.setOnChange(this.props.onChange); } componentDidUpdate() { this.accordionStore.setAccordion(this.props.accordion); this.accordionStore.setOnChange(this.props.onChange); } render() { const { accordion, onChange, ...rest } = this.props; return ( <Provider inject={[this.accordionStore]}> <Subscribe to={[AccordionContainer]}> {accordionStore => ( <Accordion accordion={accordionStore.state.accordion} {...rest} /> )} </Subscribe> </Provider> ); } } export default AccordionWrapper; ","// @flow import React, { Component } from 'react'; import type { ElementProps } from 'react'; import { Provider, Subscribe } from 'unstated'; import AccordionContainer from '../AccordionContainer/AccordionContainer'; import Accordion from './accordion'; type AccordionWrapperProps = ElementProps<'div'> & { accordion: boolean, onChange: Function, }; const defaultProps: AccordionWrapperProps = { accordion: true, onChange: () => {}, className: 'accordion', children: null, }; class AccordionWrapper extends Component<AccordionWrapperProps> { accordionStore = new AccordionContainer(); static defaultProps = defaultProps; componentDidMount() { this.accordionStore.setAccordion(this.props.accordion); this.accordionStore.setOnChange(this.props.onChange); } componentDidUpdate() { this.accordionStore.setAccordion(this.props.accordion); this.accordionStore.setOnChange(this.props.onChange); } render() { const { accordion, onChange, ...rest } = this.props; return ( <Provider inject={[this.accordionStore]}> <Subscribe to={[AccordionContainer]}> {accordionStore => ( <Accordion accordion={accordionStore.state.accordion} {...rest} /> )} </Subscribe> </Provider> ); } } export default AccordionWrapper; " "Remove duplicate key from mandragora config Looks like this was just an accident.","var mandragora = require(""mandragora-bucket/index.js""), gulp = require(""gulp""), less = require(""gulp-less""); mandragora(gulp, { paths: { bower: [ ""bower_components/purescript-*/src/**/*.purs"", ""bower_components/purescript-*/purescript-*/src/**/*.purs"" ], test: [""test/**/*.purs""], src: [""src/**/*.purs""] }, entries: { ""Entries.File"": { ""name"": ""file"", ""dir"": ""public"" }, ""Entries.Notebook"": { ""name"": ""notebook"", ""dir"": ""public"" } }, docs: ""MODULES.md"", tmpDir: ""dist"" }); gulp.task(""less"", function() { return gulp.src([""less/main.less""]) .pipe(less({ paths: [""less/**/*.less""] })) .pipe(gulp.dest(""public"")); }); gulp.task(""watch-less"", [""less""], function() { return gulp.watch([""less/**/*.less""], [""less""]); }); ","var mandragora = require(""mandragora-bucket/index.js""), gulp = require(""gulp""), less = require(""gulp-less""); mandragora(gulp, { paths: { bower: [ ""bower_components/purescript-*/src/**/*.purs"", ""bower_components/purescript-*/purescript-*/src/**/*.purs"" ], test: [""test/**/*.purs""], src: [""src/**/*.purs""] }, tmpDir: ""tmp"", entries: { ""Entries.File"": { ""name"": ""file"", ""dir"": ""public"" }, ""Entries.Notebook"": { ""name"": ""notebook"", ""dir"": ""public"" } }, docs: ""MODULES.md"", tmpDir: ""dist"" }); gulp.task(""less"", function() { return gulp.src([""less/main.less""]) .pipe(less({ paths: [""less/**/*.less""] })) .pipe(gulp.dest(""public"")); }); gulp.task(""watch-less"", [""less""], function() { return gulp.watch([""less/**/*.less""], [""less""]); }); " Print generated date & time,"import graph import datetime def generate(): count = graph.getTotalCount() zahajeni = graph.getSkupinaZahajeni(count) probihajici = graph.getSkupinaProbihajici(count) printHeader() printBody(count, zahajeni, probihajici) printFooter() def printHeader(): print(""<!DOCTYPE html>\n<html>\n<head>\n"" + ""<title>Skupiny clenu v RV</title>\n"" + ""</head>"") def printBody(count, zahajeni, probihajici): print(""<body>\n"" + ""<h1>Skupiny clenu v RV</h1>\n"" + ""<table border=\""1\""><thead><tr>\n"" + ""<td>Pocet clenu</td>\n"" + ""<td>Velikost skupiny pro zahajeni jednani</td>\n"" + ""<td>Velikost skupiny na probihajicim jednani</td>\n"" + ""</tr>\n</thead>\n<tbody>\n<tr>"" + ""<td>"" + str(count) + ""</td><td>"" + str(zahajeni) + ""</td><td>"" + str(probihajici) + ""</td></tr>\n"" + ""</tbody></table>\n"") def printFooter(): print(""<p>Generated: "" + datetime.datetime.now() + ""</p>"") print(""</body></html>"") generate() ","import graph def generate(): count = graph.getTotalCount() zahajeni = graph.getSkupinaZahajeni(count) probihajici = graph.getSkupinaProbihajici(count) printHeader() printBody(count, zahajeni, probihajici) printFooter() def printHeader(): print(""<!DOCTYPE html>\n<html>\n<head>\n"" + ""<title>Skupiny clenu v RV</title>\n"" + ""</head>"") def printBody(count, zahajeni, probihajici): print(""<body>\n"" + ""<h1>Skupiny clenu v RV</h1>\n"" + ""<table border=\""1\""><thead><tr>\n"" + ""<td>Pocet clenu</td>\n"" + ""<td>Velikost skupiny pro zahajeni jednani</td>\n"" + ""<td>Velikost skupiny na probihajicim jednani</td>\n"" + ""</tr>\n</thead>\n<tbody>\n<tr>"" + ""<td>"" + str(count) + ""</td><td>"" + str(zahajeni) + ""</td><td>"" + str(probihajici) + ""</td></tr>\n"" + ""</tbody></table>\n"" + ""</body>"") def printFooter(): print(""</html>"") generate() " Fix Python 3.4 import error,"import importlib try: from urlparse import urlparse except ImportError: # Python 3.x from urllib.parse import urlparse from celery_janitor import conf from celery_janitor.exceptions import BackendNotSupportedException BACKEND_MAPPING = { 'sqs': 'celery_janitor.backends.sqs.SQSBackend' } def import_class(path): path_bits = path.split('.') class_name = path_bits.pop() module_path = '.'.join(path_bits) module_itself = importlib.import_module(module_path) if not hasattr(module_itself, class_name): raise ImportError(""Module '%s' has no '%s' class."" % (module_path, class_name)) return getattr(module_itself, class_name) class Config(object): def __init__(self): self.broker = urlparse(conf.BROKER_URL) def get_backend_class(self): try: return BACKEND_MAPPING[self.broker.scheme] except KeyError: raise BackendNotSupportedException( ""{} not supported"".format(self.broker.scheme)) def get_credentials(self): if self.broker.scheme == 'sqs': access_id, access_secret = self.broker.netloc.split(':') access_secret = access_secret[:-1] return (access_id, access_secret) def get_backend(): config = Config() backend_class = config.get_backend() backend = import_class(backend_class) return backend(*config.get_credentials()) ","import importlib import urlparse from celery_janitor import conf from celery_janitor.exceptions import BackendNotSupportedException BACKEND_MAPPING = { 'sqs': 'celery_janitor.backends.sqs.SQSBackend' } def import_class(path): path_bits = path.split('.') class_name = path_bits.pop() module_path = '.'.join(path_bits) module_itself = importlib.import_module(module_path) if not hasattr(module_itself, class_name): raise ImportError(""Module '%s' has no '%s' class."" % (module_path, class_name)) return getattr(module_itself, class_name) class Config(object): def __init__(self): self.broker = urlparse.urlparse(conf.BROKER_URL) def get_backend_class(self): try: return BACKEND_MAPPING[self.broker.scheme] except KeyError: raise BackendNotSupportedException( ""{} not supported"".format(self.broker.scheme)) def get_credentials(self): if self.broker.scheme == 'sqs': access_id, access_secret = self.broker.netloc.split(':') access_secret = access_secret[:-1] return (access_id, access_secret) def get_backend(): config = Config() backend_class = config.get_backend() backend = import_class(backend_class) return backend(*config.get_credentials()) " Load initial user data via get,"(function() { 'use strict'; angular .module('app.layout') .controller('ShellController', ShellController); function ShellController( $rootScope, $scope, config, logger, coreevents, $sessionStorage, Users ) { var vm = this; vm.busyMessage = 'Please wait ...'; vm.isBusy = true; vm.inHeader = true; vm.currentUser = null; activate(); function activate() { logger.success(config.appTitle + ' loaded!', null); if ($sessionStorage.user) { setCurrentUser(null, $sessionStorage.user); } $rootScope.$on(coreevents.loginSuccess, setCurrentUser); $rootScope.$on(coreevents.logoutSuccess, unsetCurrentUser); } function setCurrentUser(event, user) { vm.currentUser = Users.get(user.data.id); $sessionStorage.user = user; } function unsetCurrentUser(event) { vm.currentUser = null; $sessionStorage.user = null; $scope.$apply(); } } })(); ","(function() { 'use strict'; angular .module('app.layout') .controller('ShellController', ShellController); function ShellController( $rootScope, $scope, config, logger, coreevents, $sessionStorage, Users ) { var vm = this; vm.busyMessage = 'Please wait ...'; vm.isBusy = true; vm.inHeader = true; vm.currentUser = null; activate(); function activate() { logger.success(config.appTitle + ' loaded!', null); if ($sessionStorage.user) { setCurrentUser(null, $sessionStorage.user); } $rootScope.$on(coreevents.loginSuccess, setCurrentUser); $rootScope.$on(coreevents.logoutSuccess, unsetCurrentUser); } function setCurrentUser(event, user) { vm.currentUser = Users.initialize(); vm.currentUser.new = false; vm.currentUser.stable = true; vm.currentUser.synchronized = true; vm.currentUser.data = user.data; vm.currentUser.refresh(); $sessionStorage.user = user; } function unsetCurrentUser(event) { vm.currentUser = null; $sessionStorage.user = null; $scope.$apply(); } } })(); " Update tastypie methods allowed for subscriptions,"from tastypie import fields from tastypie.resources import ModelResource, ALL from tastypie.authentication import ApiKeyAuthentication from tastypie.authorization import Authorization from subscription.models import Subscription, MessageSet from djcelery.models import PeriodicTask class PeriodicTaskResource(ModelResource): class Meta: queryset = PeriodicTask.objects.all() resource_name = 'periodic_task' list_allowed_methods = ['get'] include_resource_uri = True always_return_data = True authentication = ApiKeyAuthentication() class MessageSetResource(ModelResource): class Meta: queryset = MessageSet.objects.all() resource_name = 'message_set' list_allowed_methods = ['get'] include_resource_uri = True always_return_data = True authentication = ApiKeyAuthentication() class SubscriptionResource(ModelResource): schedule = fields.ToOneField(PeriodicTaskResource, 'schedule') message_set = fields.ToOneField(MessageSetResource, 'message_set') class Meta: queryset = Subscription.objects.all() resource_name = 'subscription' list_allowed_methods = ['post', 'get', 'put', 'patch'] include_resource_uri = True always_return_data = True authentication = ApiKeyAuthentication() authorization = Authorization() filtering = { 'to_addr': ALL, 'user_account': ALL } ","from tastypie import fields from tastypie.resources import ModelResource, ALL from tastypie.authentication import ApiKeyAuthentication from tastypie.authorization import Authorization from subscription.models import Subscription, MessageSet from djcelery.models import PeriodicTask class PeriodicTaskResource(ModelResource): class Meta: queryset = PeriodicTask.objects.all() resource_name = 'periodic_task' list_allowed_methods = ['get'] include_resource_uri = True always_return_data = True authentication = ApiKeyAuthentication() class MessageSetResource(ModelResource): class Meta: queryset = MessageSet.objects.all() resource_name = 'message_set' list_allowed_methods = ['get'] include_resource_uri = True always_return_data = True authentication = ApiKeyAuthentication() class SubscriptionResource(ModelResource): schedule = fields.ToOneField(PeriodicTaskResource, 'schedule') message_set = fields.ToOneField(MessageSetResource, 'message_set') class Meta: queryset = Subscription.objects.all() resource_name = 'subscription' list_allowed_methods = ['post', 'get'] include_resource_uri = True always_return_data = True authentication = ApiKeyAuthentication() authorization = Authorization() filtering = { 'to_addr': ALL, 'user_account': ALL } " Add documentation for Source class,"from mythril.solidity.soliditycontract import SolidityContract from mythril.ethereum.evmcontract import EVMContract class Source: """"""Class to handle to source data"""""" def __init__( self, source_type=None, source_format=None, source_list=None, meta=None ): """""" :param source_type: whether it is a solidity-file or evm-bytecode :param source_format: whether it is bytecode, ethereum-address or text :param source_list: List of files :param meta: meta data """""" self.source_type = source_type self.source_format = source_format self.source_list = [] self.meta = meta def get_source_from_contracts_list(self, contracts): """""" get the source data from the contracts list :param contracts: the list of contracts :return: """""" if contracts is None or len(contracts) == 0: return if isinstance(contracts[0], SolidityContract): self.source_type = ""solidity-file"" self.source_format = ""text"" for contract in contracts: self.source_list += [file.filename for file in contract.solidity_files] elif isinstance(contracts[0], EVMContract): self.source_format = ""evm-byzantium-bytecode"" self.source_type = ( ""raw-bytecode"" if contracts[0].name == ""MAIN"" else ""ethereum-address"" ) for contract in contracts: self.source_list.append(contract.bytecode_hash) else: assert False # Fail hard ","from mythril.solidity.soliditycontract import SolidityContract from mythril.ethereum.evmcontract import EVMContract class Source: def __init__( self, source_type=None, source_format=None, source_list=None, meta=None ): self.source_type = source_type self.source_format = source_format self.source_list = [] self.meta = meta def get_source_from_contracts_list(self, contracts): if contracts is None or len(contracts) == 0: return if isinstance(contracts[0], SolidityContract): self.source_type = ""solidity-file"" self.source_format = ""text"" for contract in contracts: self.source_list += [file.filename for file in contract.solidity_files] elif isinstance(contracts[0], EVMContract): self.source_format = ""evm-byzantium-bytecode"" self.source_type = ( ""raw-bytecode"" if contracts[0].name == ""MAIN"" else ""ethereum-address"" ) for contract in contracts: self.source_list.append(contract.bytecode_hash) else: assert False # Fail hard " Save connection name in session too,"<?php /** * Bareos Reporter * Application for managing Bareos Backup Email Reports * * Dashboard Controller * * @license The MIT License (MIT) See: LICENSE file * @copyright Copyright (c) 2016 Matt Clinton * @author Matt Clinton <matt@laralabs.uk> * @website http://www.magelabs.uk/ */ namespace App\Http\Controllers; use App\Catalogs; use Illuminate\Http\Request; use App\Http\Requests; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Session; class DashboardController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { return view('dashboard.index'); } /** * Change the active director, set active_director * session variable if input value not empty. * * @return \Illuminate\Http\Response */ public function changeDirector() { $director_id = Input::get('director-select'); if(!empty($director_id)) { $connectionName = Catalogs::getCatalogName($director_id); Session::set('active_connection', $connectionName); Session::set('active_director', $director_id); return redirect('directors')->with('success', 'Director changed successfully'); } else { return redirect('directors')->with('failed', 'Unable to change director'); } } } ","<?php /** * Bareos Reporter * Application for managing Bareos Backup Email Reports * * Dashboard Controller * * @license The MIT License (MIT) See: LICENSE file * @copyright Copyright (c) 2016 Matt Clinton * @author Matt Clinton <matt@laralabs.uk> * @website http://www.magelabs.uk/ */ namespace App\Http\Controllers; use App\Catalogs; use Illuminate\Http\Request; use App\Http\Requests; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Session; class DashboardController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { return view('dashboard.index'); } /** * Change the active director, set active_director * session variable if input value not empty. * * @return \Illuminate\Http\Response */ public function changeDirector() { $director_id = Input::get('director-select'); if(!empty($director_id)) { Session::set('active_director', $director_id); return redirect('directors')->with('success', 'Director changed successfully'); } else { return redirect('directors')->with('failed', 'Unable to change director'); } } } " Add di to allow access to the control's options from its angular controller," 'use strict'; L.Control.Angular = L.Control.extend({ options: { position: 'bottomleft', template: '' }, onAdd: function onAdd (map) { var that = this; var container = L.DomUtil.create('div', 'angular-control-leaflet'); angular.element(document).ready(function() { // Grab the injector for the current angular app var $injector = angular.element(document).injector(); var $rootScope = $injector.get('$rootScope'), $compile = $injector.get('$compile'), $controller = $injector.get('$controller'); var scope = $rootScope.$new(true); var element = angular.element(container); element.html(that.options.template); // Controller setup based on ui-router's code https://github.com/angular-ui/ui-router if (that.options.controller) { var controller = $controller(that.options.controller, { '$map': map, '$scope': scope, '$element': element, '$options': that.options }); if (that.options.controllerAs) { scope[that.options.controllerAs] = controller; } element.data('$ngControllerController', controller); element.children().data('$ngControllerController', controller); } $compile(element)(scope); scope.$apply(); }); return container; } }); L.control.angular = function(options) { return new L.Control.Angular(options); };"," 'use strict'; L.Control.Angular = L.Control.extend({ options: { position: 'bottomleft', template: '' }, onAdd: function(map) { var that = this; var container = L.DomUtil.create('div', 'angular-control-leaflet'); angular.element(document).ready(function() { // Grab the injector for the current angular app var $injector = angular.element(document).injector(); var $rootScope = $injector.get('$rootScope'), $compile = $injector.get('$compile'), $controller = $injector.get('$controller'); var scope = $rootScope.$new(true); var element = angular.element(container); element.html(that.options.template); var link = $compile(element); // Controller setup based on ui-router's code https://github.com/angular-ui/ui-router if (that.options.controller) { var controller = $controller(that.options.controller, { '$map': map, '$scope': scope, '$element': element }); if (that.options.controllerAs) { scope[that.options.controllerAs] = controller; } element.data('$ngControllerController', controller); element.children().data('$ngControllerController', controller); } link(scope); scope.$apply(); }); return container; } }); L.control.angular = function(options) { return new L.Control.Angular(options); };" Make compatible with Django >2.1,"from django.forms.widgets import Input, ClearableFileInput from django.template.loader import render_to_string class CIImgWidget(ClearableFileInput): def render(self, name, value, attrs=None): try: attrs[""data-value""] = getattr(value, ""url"", """") except ValueError: # attribute has no file associated with it. attrs[""data-value""] = """" return super(CIImgWidget, self).render(name, value, attrs) class CIThumbnailWidget(Input): input_type = ""text"" def render(self, name, value, attrs=None, renderer=None): if attrs: attrs.update(self.attrs) attrs[""type""] = ""hidden"" input_field = super(CIThumbnailWidget, self).render(name, value, attrs) return render_to_string(""cropimg/cropimg_widget.html"", { ""name"": name, ""value"": value, ""attrs"": attrs, ""input_field"": input_field }) class Media: js = (""cropimg/js/jquery_init.js"", ""cropimg/js/cropimg.jquery.js"", ""cropimg/js/cropimg_init.js"") css = {""all"": [""cropimg/resource/cropimg.css""]} ","from django.forms.widgets import Input, ClearableFileInput from django.template.loader import render_to_string class CIImgWidget(ClearableFileInput): def render(self, name, value, attrs=None): try: attrs[""data-value""] = getattr(value, ""url"", """") except ValueError: # attribute has no file associated with it. attrs[""data-value""] = """" return super(CIImgWidget, self).render(name, value, attrs) class CIThumbnailWidget(Input): input_type = ""text"" def render(self, name, value, attrs=None): if attrs: attrs.update(self.attrs) attrs[""type""] = ""hidden"" input_field = super(CIThumbnailWidget, self).render(name, value, attrs) return render_to_string(""cropimg/cropimg_widget.html"", { ""name"": name, ""value"": value, ""attrs"": attrs, ""input_field"": input_field }) class Media: js = (""cropimg/js/jquery_init.js"", ""cropimg/js/cropimg.jquery.js"", ""cropimg/js/cropimg_init.js"") css = {""all"": [""cropimg/resource/cropimg.css""]} " "Fix temporary files remaining after execution For each run of the plugin, a temporary file is created, but never cleaned. This check ensure that the temporary file is deleted at the JVM exit.","package net_alchim31_maven_yuicompressor; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import org.codehaus.plexus.util.IOUtil; import org.mozilla.javascript.ErrorReporter; //TODO: use MojoErrorReporter class JSLintChecker { private String jslintPath_; public JSLintChecker() throws Exception { FileOutputStream out = null; InputStream in = null; try { File jslint = File.createTempFile(""jslint"", "".js""); jslint.deleteOnExit(); in = getClass().getResourceAsStream(""/jslint.js""); out = new FileOutputStream(jslint); IOUtil.copy(in, out); jslintPath_ = jslint.getAbsolutePath(); } finally { IOUtil.close(in); IOUtil.close(out); } } public void check(File jsFile, ErrorReporter reporter) { String[] args = new String[2]; args[0] = jslintPath_; args[1] = jsFile.getAbsolutePath(); BasicRhinoShell.exec(args, reporter); //if (Main.exec(args) != 0) { // reporter.warning(""warnings during checking of :"" + jsFile.getAbsolutePath(), null, -1, null, -1); //} } } ","package net_alchim31_maven_yuicompressor; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import org.codehaus.plexus.util.IOUtil; import org.mozilla.javascript.ErrorReporter; //TODO: use MojoErrorReporter class JSLintChecker { private String jslintPath_; public JSLintChecker() throws Exception { FileOutputStream out = null; InputStream in = null; try { File jslint = File.createTempFile(""jslint"", "".js""); in = getClass().getResourceAsStream(""/jslint.js""); out = new FileOutputStream(jslint); IOUtil.copy(in, out); jslintPath_ = jslint.getAbsolutePath(); } finally { IOUtil.close(in); IOUtil.close(out); } } public void check(File jsFile, ErrorReporter reporter) { String[] args = new String[2]; args[0] = jslintPath_; args[1] = jsFile.getAbsolutePath(); BasicRhinoShell.exec(args, reporter); //if (Main.exec(args) != 0) { // reporter.warning(""warnings during checking of :"" + jsFile.getAbsolutePath(), null, -1, null, -1); //} } } " Add json library for repr() calls,"import json from lxml import html class XPathObject(object): input_properties = {} """"""Dict of keys (property names) and XPaths (to read vals from)"""""" @classmethod def FromHTML(cls, html_contents): inst = cls() print(""Reading through {b} bytes for {c} properties..."".format( b=len(html_contents), c=len(cls.input_properties))) tree = html.fromstring(html_contents) for attr_name, xpath in cls.input_properties.items(): print(""Searching for '{n}': {x}"".format( n=attr_name, x=xpath)) elements = tree.xpath(xpath) if not len(elements): print(""Failed to find '{n}': {x}"".format( n=attr_name, x=xpath)) continue setattr( inst, attr_name, elements[0].text) return inst def __repr__(self): return json.dumps( self.__dict__, indent=4, separators=(',', ': ')) ","from lxml import html class XPathObject(object): input_properties = {} """"""Dict of keys (property names) and XPaths (to read vals from)"""""" @classmethod def FromHTML(cls, html_contents): inst = cls() print(""Reading through {b} bytes for {c} properties..."".format( b=len(html_contents), c=len(cls.input_properties))) tree = html.fromstring(html_contents) for attr_name, xpath in cls.input_properties.items(): print(""Searching for '{n}': {x}"".format( n=attr_name, x=xpath)) elements = tree.xpath(xpath) if not len(elements): print(""Failed to find '{n}': {x}"".format( n=attr_name, x=xpath)) continue setattr( inst, attr_name, elements[0].text) return inst def __repr__(self): return json.dumps( self.__dict__, indent=4, separators=(',', ': ')) " Use function collect instead of class Collection,"<?php namespace App\Providers; use Facades\App\Services\SmsTools as SmsTools; use Illuminate\Support\ServiceProvider; use Validator; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { Validator::extend('smsCount', function ($attribute, $value, $parameters, $validator) { return SmsTools::count($value) <= intval($parameters[0]); }); Validator::replacer('smsCount', function ($message, $attribute, $rule, $parameters) { return str_replace(':size', $parameters[0], $message); }); Validator::extend('in_keys', function ($attribute, $value, $parameters, $validator) { return collect($parameters)->contains(function ($parameter) use ($value, $validator) { return array_key_exists($value, array_get($validator->getData(), $parameter)); }); }); } /** * Register any application services. * * @return void */ public function register() { if ($this->app->environment('local', 'dev', 'testing')) { $this->app->register(\Rap2hpoutre\LaravelLogViewer\LaravelLogViewerServiceProvider::class); } } } ","<?php namespace App\Providers; use Collection; use Facades\App\Services\SmsTools as SmsTools; use Illuminate\Support\ServiceProvider; use Validator; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { Validator::extend('smsCount', function ($attribute, $value, $parameters, $validator) { return SmsTools::count($value) <= intval($parameters[0]); }); Validator::replacer('smsCount', function ($message, $attribute, $rule, $parameters) { return str_replace(':size', $parameters[0], $message); }); Validator::extend('in_keys', function ($attribute, $value, $parameters, $validator) { return Collection($parameters)->contains(function ($parameter) use ($value, $validator) { return array_key_exists($value, array_get($validator->getData(), $parameter)); }); }); } /** * Register any application services. * * @return void */ public function register() { if ($this->app->environment('local', 'dev', 'testing')) { $this->app->register(\Rap2hpoutre\LaravelLogViewer\LaravelLogViewerServiceProvider::class); } } } " Remove usages of the deprecated helpers,"<?php use Illuminate\Support\Arr; if (!function_exists('array_except_value')) { function array_except_value(array $array, $value) { if (!is_array($value)) { $value = [$value]; } foreach ($value as $item) { while (($key = array_search($item, $array, true)) !== false) { unset($array[$key]); } } return $array; } } if (!function_exists('multiarray_set')) { function multiarray_set(array &$multiarray, $key, $value) { foreach ($multiarray as &$array) { Arr::set($array, $key, $value); } return $multiarray; } } if (!function_exists('multiarray_sort_by')) { function multiarray_sort_by(array $multiarray, $field1 = null, $sort1 = null, $_ = null) { $arguments = func_get_args(); $multiarray = array_shift($arguments); foreach ($arguments as $key => $value) { if (is_string($value)) { $arguments[$key] = Arr::pluck($multiarray, $value); } } $arguments[] = &$multiarray; call_user_func_array('array_multisort', $arguments); return array_pop($arguments); } } ","<?php if (!function_exists('array_except_value')) { function array_except_value(array $array, $value) { if (!is_array($value)) { $value = [$value]; } foreach ($value as $item) { while (($key = array_search($item, $array, true)) !== false) { unset($array[$key]); } } return $array; } } if (!function_exists('multiarray_set')) { function multiarray_set(array &$multiarray, $key, $value) { foreach ($multiarray as &$array) { array_set($array, $key, $value); } return $multiarray; } } if (!function_exists('multiarray_sort_by')) { function multiarray_sort_by(array $multiarray, $field1 = null, $sort1 = null, $_ = null) { $arguments = func_get_args(); $multiarray = array_shift($arguments); foreach ($arguments as $key => $value) { if (is_string($value)) { $arguments[$key] = array_pluck($multiarray, $value); } } $arguments[] = &$multiarray; call_user_func_array('array_multisort', $arguments); return array_pop($arguments); } } " Add currency property to pricing policies,"class TaxNotKnown(Exception): """""" Exception for when a tax-inclusive price is requested but we don't know what the tax applicable is (yet). """""" class Base(object): """""" The interface that any pricing policy must support """""" #: Whether any prices exist exists = False #: Whether tax is known is_tax_known = False #: Normal price properties excl_tax = incl_tax = tax = None #: Currency prices are in currency = None class Unavailable(Base): """""" No stockrecord, therefore no prices """""" class FixedPrice(Base): exists = True def __init__(self, excl_tax, tax=None): self.excl_tax = excl_tax self.tax = tax @property def incl_tax(self): if self.is_tax_known: return self.excl_tax + self.tax raise TaxNotKnown(""Can't calculate price.incl_tax as tax isn't known"") @property def is_tax_known(self): return self.tax is not None class DelegateToStockRecord(Base): is_tax_known = True def __init__(self, stockrecord): self.stockrecord = stockrecord @property def exists(self): return self.stockrecord is not None @property def excl_tax(self): return self.stockrecord.price_excl_tax @property def incl_tax(self): return self.stockrecord.price_incl_tax @property def tax(self): return self.stockrecord.price_tax @property def currency(self): return self.stockrecord.price_currency ","class TaxNotKnown(Exception): """""" Exception for when a tax-inclusive price is requested but we don't know what the tax applicable is (yet). """""" class Base(object): #: Whether any prices exist exists = False #: Whether tax is known for this product (and session) is_tax_known = False # Normal price properties excl_tax = incl_tax = tax = None class Unavailable(Base): """""" No stockrecord, therefore no prices """""" class FixedPrice(Base): exists = True def __init__(self, excl_tax, tax=None): self.excl_tax = excl_tax self.tax = tax @property def incl_tax(self): if self.is_tax_known: return self.excl_tax + self.tax raise TaxNotKnown(""Can't calculate price.incl_tax as tax isn't known"") @property def is_tax_known(self): return self.tax is not None class DelegateToStockRecord(Base): is_tax_known = True def __init__(self, stockrecord): self.stockrecord = stockrecord @property def exists(self): return self.stockrecord is not None @property def excl_tax(self): return self.stockrecord.price_excl_tax @property def incl_tax(self): return self.stockrecord.price_incl_tax @property def tax(self): return self.stockrecord.price_tax " Make installation print data path.,"from __future__ import print_function import sys import sputnik from sputnik.package_list import (PackageNotFoundException, CompatiblePackageNotFoundException) from . import about from . import util def download(lang, force=False, fail_on_exist=True): if force: sputnik.purge(about.__title__, about.__version__) try: sputnik.package(about.__title__, about.__version__, about.__models__.get(lang, lang)) if fail_on_exist: print(""Model already installed. Please run 'python -m "" ""spacy.%s.download --force' to reinstall."" % lang, file=sys.stderr) sys.exit(0) except (PackageNotFoundException, CompatiblePackageNotFoundException): pass package = sputnik.install(about.__title__, about.__version__, about.__models__.get(lang, lang)) try: sputnik.package(about.__title__, about.__version__, about.__models__.get(lang, lang)) except (PackageNotFoundException, CompatiblePackageNotFoundException): print(""Model failed to install. Please run 'python -m "" ""spacy.%s.download --force'."" % lang, file=sys.stderr) sys.exit(1) data_path = util.get_data_path() print(""Model successfully installed to %s"" % data_path, file=sys.stderr) ","from __future__ import print_function import sys import sputnik from sputnik.package_list import (PackageNotFoundException, CompatiblePackageNotFoundException) from . import about def download(lang, force=False, fail_on_exist=True): if force: sputnik.purge(about.__title__, about.__version__) try: sputnik.package(about.__title__, about.__version__, about.__models__.get(lang, lang)) if fail_on_exist: print(""Model already installed. Please run 'python -m "" ""spacy.%s.download --force' to reinstall."" % lang, file=sys.stderr) sys.exit(0) except (PackageNotFoundException, CompatiblePackageNotFoundException): pass package = sputnik.install(about.__title__, about.__version__, about.__models__.get(lang, lang)) try: sputnik.package(about.__title__, about.__version__, about.__models__.get(lang, lang)) except (PackageNotFoundException, CompatiblePackageNotFoundException): print(""Model failed to install. Please run 'python -m "" ""spacy.%s.download --force'."" % lang, file=sys.stderr) sys.exit(1) print(""Model successfully installed."", file=sys.stderr) " Fix for the never disappearing loading icon,"'use strict'; /** * @ngdoc function * @name ausEnvApp.controller:SearchCtrl * @description * # SearchCtrl * Controller of the ausEnvApp */ angular.module('ausEnvApp') .controller('SearchCtrl', function ($scope,$filter,staticData,selection,spatialFoci) { $scope.selection = selection; $scope.loadingPolygons = false; staticData.unwrap($scope,'options',spatialFoci.regionTypes); $scope.$watch('selection.mapMode',function(newVal){ if(newVal==='Grid') { selection.lastRegionType = selection.regionType; selection.regionType=null; } else { if(!selection.regionType) { selection.regionType = selection.lastRegionType; } } }); $scope.regionTypeChanged = function(newOption) { if(!newOption){ selection.mapMode = 'Grid'; return; } selection.mapMode = 'Polygon'; $scope.loadingPolygons = true; newOption.jsonData().then(function(data){ selection.availableFeatures = data.features.map(function(f){ return { name:f.properties[newOption.labelField], feature:f }; }); selection.availableFeatures.sort(function(a,b){return a.name.localeCompare(b.name);}); $scope.loadingPolygons = false; }); }; //regionTypeChanged $scope.canUseSearchText = function() { return ((!selection.isMapModeGrid()) && (selection.regionType !== null)); }; //canUseSearchText }); ","'use strict'; /** * @ngdoc function * @name ausEnvApp.controller:SearchCtrl * @description * # SearchCtrl * Controller of the ausEnvApp */ angular.module('ausEnvApp') .controller('SearchCtrl', function ($scope,$filter,staticData,selection,spatialFoci) { $scope.selection = selection; $scope.loadingPolygons = false; staticData.unwrap($scope,'options',spatialFoci.regionTypes); $scope.$watch('selection.mapMode',function(newVal){ if(newVal==='Grid') { selection.lastRegionType = selection.regionType; selection.regionType=null; } else { if(!selection.regionType) { selection.regionType = selection.lastRegionType; } } }); $scope.regionTypeChanged = function(newOption) { if(!newOption){ selection.mapMode = 'Grid'; return; } selection.mapMode = 'Polygon'; $scope.loadingPolygons = true; newOption.jsonData().then(function(data){ selection.availableFeatures = data.features.map(function(f){ return { name:f.properties[newOption.labelField], feature:f }; }); selection.availableFeatures.sort(function(a,b){return a.name.localeCompare(b.name);}); }); }; //regionTypeChanged $scope.canUseSearchText = function() { return ((!selection.isMapModeGrid()) && (selection.regionType !== null)); }; //canUseSearchText }); " Use new formatter in cmd,"import cmd from functools import partial from unjabberlib import formatters trim_print = partial(print, sep='', end='') class StdoutFormatter(formatters.Formatter): def append(self, text, format=None): if format is None or format == formatters.HOUR: trim_print(text) elif format == formatters.NAME: trim_print(' -- ', text) elif format == formatters.DAY: trim_print('== ', text, ' ==') class UnjabberCmd(cmd.Cmd): def __init__(self, queries, **cmdargs): super().__init__(**cmdargs) self.formatter = StdoutFormatter() self.queries = queries def do_who(self, arg): """"""Show list of people. Add part of a name to narrow down."""""" for name in self.queries.who(arg): print(name) def do_show(self, arg): """"""Show conversations with people matching name (or part of)."""""" previous = None for message in self.queries.messages_for_whom(arg): day, hour, shortname = message.after(previous) self.formatter.show(previous, day, hour, shortname, message.what) previous = message def do_grep(self, arg): """"""Show messages containing text."""""" for message in self.queries.grep(arg): print(message) def do_quit(self, arg): """"""Exit the program."""""" return True ","import cmd from itertools import zip_longest INDENT = 5 * ' ' class UnjabberCmd(cmd.Cmd): def __init__(self, queries, **cmdargs): super().__init__(**cmdargs) self.queries = queries def do_who(self, arg): """"""Show list of people. Add part of a name to narrow down."""""" for name in self.queries.who(arg): print(name) def do_show(self, arg): """"""Show conversations with people matching name (or part of)."""""" previous = None for message in self.queries.messages_for_whom(arg): print_message(previous, message) previous = message def do_grep(self, arg): """"""Show messages containing text."""""" for message in self.queries.grep(arg): print(message) def do_quit(self, arg): """"""Exit the program."""""" return True def print_message(previous, message): day, hour, shortname = message.after(previous) if day: if previous: print() print('==', day, '==') if shortname: if not day: print() print(hour, ' -- ', shortname) sub_print_message(INDENT, message.what) else: sub_print_message(hour if hour else INDENT, message.what) def sub_print_message(hour, what): for h, line in zip_longest([hour], what.split('\n'), fillvalue=INDENT): print(h, line) " "Revert ""fix ""NullPionterException could be thrown""-bug, see sonar qube L28, L35"" This reverts commit 7acc0b6500e513183324e369455e5ebcce412087.","package de.bmoth.typechecker; import de.bmoth.parser.Parser; import de.bmoth.parser.ast.TypeErrorException; import org.junit.Test; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class TypeErrorExceptionTest { @Test(expected = TypeErrorException.class) public void testTypeErrorException() { String formula = ""a = TRUE & b = 1 & a = b""; Parser.getFormulaAsSemanticAst(formula); } @Test(expected = TypeErrorException.class) public void testTypeErrorException2() { String formula = ""a = TRUE & a = 1 + 1""; Parser.getFormulaAsSemanticAst(formula); } @Test public void testSetEnumeration() { String formula = ""x = {1,2,(3,4)}""; String exceptionMessage = getExceptionMessage(formula); assertTrue(exceptionMessage.contains(""Expected INTEGER but found INTEGER*INTEGER"")); } @Test public void testSetEnumeration2() { String formula = ""x = {1,2,{3,4}}""; String exceptionMessage = getExceptionMessage(formula); assertTrue(exceptionMessage.contains(""found POW"")); } private static String getExceptionMessage(String formula) { try { Parser.getFormulaAsSemanticAst(formula); fail(""Expected a type error exception.""); return """"; } catch (TypeErrorException e) { return e.getMessage(); } } } ","package de.bmoth.typechecker; import de.bmoth.parser.Parser; import de.bmoth.parser.ast.TypeErrorException; import org.junit.Test; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class TypeErrorExceptionTest { @Test(expected = TypeErrorException.class) public void testTypeErrorException() { String formula = ""a = TRUE & b = 1 & a = b""; Parser.getFormulaAsSemanticAst(formula); } @Test(expected = TypeErrorException.class) public void testTypeErrorException2() { String formula = ""a = TRUE & a = 1 + 1""; Parser.getFormulaAsSemanticAst(formula); } @Test public void testSetEnumeration() { String formula = ""x = {1,2,(3,4)}""; String exceptionMessage = getExceptionMessage(formula); assertTrue(exceptionMessage != null &&exceptionMessage.contains(""Expected INTEGER but found INTEGER*INTEGER"")); } @Test public void testSetEnumeration2() { String formula = ""x = {1,2,{3,4}}""; String exceptionMessage = getExceptionMessage(formula); assertTrue(exceptionMessage != null &&exceptionMessage.contains(""found POW"")); } private static String getExceptionMessage(String formula) { try { Parser.getFormulaAsSemanticAst(formula); fail(""Expected a type error exception.""); return """"; } catch (TypeErrorException e) { return e.getMessage(); } } } " "fix(frontend): Fix bug with missed calls. Add replacing listener with the new one with same name.","/** * Created by stas on 24.01.16. */ 'use strict'; playzoneServices.factory('WebsocketService', function($websocket) { var listenersMap = {}; // Open a WebSocket connection var dataStream = $websocket('ws://localhost:1234/'); dataStream.onMessage( function(message) { var receivedMessage = angular.fromJson(message.data); if (!receivedMessage.method || !receivedMessage.data) { return; } if (!listenersMap[receivedMessage.method]) { return; } angular.forEach(listenersMap[receivedMessage.method], function (callback) { callback(receivedMessage.data); }); } ); return { addListener: function(listenerName, methodToListen, callback) { if (typeof callback !== 'function') { return; } if (!listenersMap[methodToListen]) { listenersMap[methodToListen] = {}; } listenersMap[methodToListen][listenerName] = callback; }, send: function(data) { var dataToSend = angular.toJson(data); dataStream.send(dataToSend); }, introduction: function(user) { this.send( { ""scope"": ""introduction"", ""method"": ""introduction"", ""data"": { ""login"": user.login, ""token"": user.token } } ); }, sendDataToLogins: function(method, data, logins) { this.send( { scope: 'send_to_users', method: method, logins: logins, data: data } ) } }; });","/** * Created by stas on 24.01.16. */ 'use strict'; playzoneServices.factory('WebsocketService', function($websocket) { var listeners = []; // Open a WebSocket connection var dataStream = $websocket('ws://localhost:1234/'); dataStream.onMessage( function(message) { } ); return { addListener: function(listenerName, methodToListen, callback) { if (listeners.indexOf(listenerName) !== -1) { return; } if (typeof callback !== 'function') { return; } dataStream.onMessage( function (message) { var receivedMessage = angular.fromJson(message.data); if (receivedMessage.method !== methodToListen) { return; } callback(receivedMessage.data); } ); listeners.push(listenerName); }, send: function(data) { var dataToSend = angular.toJson(data); dataStream.send(dataToSend); }, introduction: function(user) { this.send( { ""scope"": ""introduction"", ""method"": ""introduction"", ""data"": { ""login"": user.login, ""token"": user.token } } ); }, sendDataToLogins: function(method, data, logins) { this.send( { scope: 'send_to_users', method: method, logins: logins, data: data } ) } }; });" "Call eval(), if server returns javascript","var LiteAjax = (function () { var LiteAjax = {}; LiteAjax.options = { method: 'GET', url: window.location.href, async: true, }; LiteAjax.ajax = function (url, options) { if (typeof url == 'object') { options = url; url = undefined; } options = options || {}; url = url || options.url || location.href || ''; var xhr; xhr = new XMLHttpRequest(); xhr.addEventListener('load', function () { responseType = xhr.getResponseHeader('content-type'); if(responseType === 'text/javascript; charset=utf-8') { eval(xhr.response); } var event = new CustomEvent('ajaxComplete', {detail: xhr}); document.dispatchEvent(event); }); if (typeof options.success == 'function') xhr.addEventListener('load', function (event) { if (xhr.status >= 200 && xhr.status < 300) options.success(xhr); }); if (typeof options.error == 'function') { xhr.addEventListener('load', function (event) { if (xhr.status < 200 || xhr.status >= 300) options.error(xhr); }); xhr.addEventListener('error', function (event) { options.error(xhr); }); } xhr.open(options.method || 'GET', url, options.async); var beforeSend = new CustomEvent('ajax:before', {detail: xhr}); document.dispatchEvent(beforeSend); xhr.send(options.data); return xhr; }; return LiteAjax; })(); ","var LiteAjax = (function () { var LiteAjax = {}; LiteAjax.options = { method: 'GET', url: window.location.href, async: true, }; LiteAjax.ajax = function (url, options) { if (typeof url == 'object') { options = url; url = undefined; } options = options || {}; url = url || options.url || location.href || ''; var xhr; xhr = new XMLHttpRequest(); xhr.addEventListener('load', function () { var event = new CustomEvent('ajaxComplete', {detail: xhr}); document.dispatchEvent(event); }); if (typeof options.success == 'function') xhr.addEventListener('load', function (event) { if (xhr.status >= 200 && xhr.status < 300) options.success(xhr); }); if (typeof options.error == 'function') { xhr.addEventListener('load', function (event) { if (xhr.status < 200 || xhr.status >= 300) options.error(xhr); }); xhr.addEventListener('error', function (event) { options.error(xhr); }); } xhr.open(options.method || 'GET', url, options.async); var beforeSend = new CustomEvent('ajax:before', {detail: xhr}); document.dispatchEvent(beforeSend); xhr.send(options.data); return xhr; }; return LiteAjax; })(); " Clean useless format string in remote command,"import datetime import arrow from marty.commands import Command from marty.printer import printer class Remotes(Command): """""" Show the list of configured remotes. """""" help = 'Show the list of configured remotes' def run(self, args, config, storage, remotes): table_lines = [('<b>NAME</b>', '<b>TYPE</b>', '<b>LAST</b>', '<b>NEXT</b>')] for remote in sorted(remotes.list(), key=lambda x: x.name): latest_ref = '%s/latest' % remote.name latest_backup = storage.get_backup(latest_ref) latest_date_text = '-' next_date_text = '-' if latest_backup is None: if remote.scheduler is not None: next_date_text = '<color fg=yellow>now</color>' else: latest_date_text = latest_backup.start_date.humanize() if remote.scheduler is not None and remote.scheduler['enabled']: next_date = latest_backup.start_date + datetime.timedelta(seconds=remote.scheduler['interval'] * 60) if next_date > arrow.now(): next_date_text = '<color fg=green>%s</color>' % next_date.humanize() else: next_date_text = '<color fg=red>%s</color>' % next_date.humanize() table_lines.append((remote.name, remote.type, latest_date_text, next_date_text)) printer.table(table_lines) ","import datetime import arrow from marty.commands import Command from marty.printer import printer class Remotes(Command): """""" Show the list of configured remotes. """""" help = 'Show the list of configured remotes' def run(self, args, config, storage, remotes): table_lines = [('<b>NAME</b>', '<b>TYPE</b>', '<b>LAST</b>', '<b>NEXT</b>')] for remote in sorted(remotes.list(), key=lambda x: x.name): latest_ref = '%s/latest' % remote.name latest_backup = storage.get_backup(latest_ref) latest_date_text = '-' next_date_text = '-' if latest_backup is None: if remote.scheduler is not None: next_date_text = '<color fg=yellow>now</color>' else: latest_date_text = '%s' % latest_backup.start_date.humanize() if remote.scheduler is not None and remote.scheduler['enabled']: next_date = latest_backup.start_date + datetime.timedelta(seconds=remote.scheduler['interval'] * 60) if next_date > arrow.now(): next_date_text = '<color fg=green>%s</color>' % next_date.humanize() else: next_date_text = '<color fg=red>%s</color>' % next_date.humanize() table_lines.append((remote.name, remote.type, latest_date_text, next_date_text)) printer.table(table_lines) " "Fix mysqli driver connect, name and database","<?php namespace DB\Driver; class MYSQLI implements IDriver { private $mysqli; public function connect($host, $user, $password) { $this->mysqli = new \mysqli($host, $user, $password); } public function database($name) { $this->mysqli->select_db($name); } public function query($sql) { } public function bind($sql, $data=[]) { $length = count($data); for ($i=0;$i<$length;$i++) { $data[$i] = mysqli_escape_string($data[$i]); } $subs = 0; while (($pos = strpos($sql, '?')) !== false) { $sql = substr_replace($sql, $data[$subs], $pos); $subs++; } return $sql; } public function lastError() { return ''; } } ?> ","<?php class DB_MYSQLI implements IDriver { private $mysqli; public function connect($host, $user, $password) { $this->mysqli = new mysqli($host, $user, $password); return !((bool)$this->mysqli->connect_error); } public function database($name) { $this->mysqli->select_db($name); return !((bool)$this->mysqli->connect_error); } public function query($sql) { } public function bind($sql, $data=[]) { $length = count($data); for ($i=0;$i<$length;$i++) { $data[$i] = mysqli_escape_string($data[$i]); } $subs = 0; while (($pos = strpos($sql, '?')) !== false) { $sql = substr_replace($sql, $data[$subs], $pos); $subs++; } return $sql; } public function lastError() { return ''; } } ?> " Remove % character from search results,"package edu.cmu.cs.diamond.massfind2; import java.awt.Component; import java.awt.image.BufferedImage; import javax.swing.BorderFactory; import javax.swing.DefaultListCellRenderer; import javax.swing.ImageIcon; import javax.swing.JList; import javax.swing.SwingConstants; import javax.swing.border.Border; public class SearchListCellRenderer extends DefaultListCellRenderer { final private static Border border = BorderFactory.createEmptyBorder(10, 10, 10, 10); public SearchListCellRenderer() { super(); setHorizontalTextPosition(SwingConstants.CENTER); setVerticalTextPosition(SwingConstants.BOTTOM); } @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { DefaultListCellRenderer c = (DefaultListCellRenderer) super .getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); MassResult r = (MassResult) value; int similarity = r.getSimilarity(); String text = Integer.toString(similarity); c.setText(text); BufferedImage thumb = r.getThumbnail(); c.setIcon(new ImageIcon(thumb)); c.setBorder(border); c.setOpaque(isSelected); c.setToolTipText((r.isMalignant() ? ""Malignant"" : ""Benign"") + "", Similarity: "" + text); return c; } } ","package edu.cmu.cs.diamond.massfind2; import java.awt.Component; import java.awt.image.BufferedImage; import javax.swing.BorderFactory; import javax.swing.DefaultListCellRenderer; import javax.swing.ImageIcon; import javax.swing.JList; import javax.swing.SwingConstants; import javax.swing.border.Border; public class SearchListCellRenderer extends DefaultListCellRenderer { final private static Border border = BorderFactory.createEmptyBorder(10, 10, 10, 10); public SearchListCellRenderer() { super(); setHorizontalTextPosition(SwingConstants.CENTER); setVerticalTextPosition(SwingConstants.BOTTOM); } @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { DefaultListCellRenderer c = (DefaultListCellRenderer) super .getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); MassResult r = (MassResult) value; int similarity = r.getSimilarity(); String text = Integer.toString(similarity) + ""%""; c.setText(text); BufferedImage thumb = r.getThumbnail(); c.setIcon(new ImageIcon(thumb)); c.setBorder(border); c.setOpaque(isSelected); c.setToolTipText((r.isMalignant() ? ""Malignant"" : ""Benign"") + "", Similarity: "" + text); return c; } } " Add XYZ layer tiling code for tiles,"/* app.js */ //= require OpenLayers /*globals $,OpenLayers,otm*/ /*jslint indent: 4, white: true */ var app = (function ($,L,config) { ""use strict""; return { createMap: function (elmt) { var map = new L.Map({ div: elmt, projection: 'EPSG:3857', layers: this.getBasemapLayers(config) }); map.setCenter(config.instance.center, 10); return map; }, getBasemapLayers: function (config) { var layer; if (config.instance.basemap.type === 'bing') { layer = new L.Layer.Bing({ name: 'Road', key: config.instance.basemap.bing_api_key, type: 'Road' }); } else if (config.instance.basemap.type === 'tms') { layer = new L.Layer.XYZ( 'xyz', config.instance.basemap.data); } else { layer = new L.Layer.Google( ""Google Streets"", {numZoomLevels: 20}); } return [layer]; }, createPlotTileLayer: function(config) { return new L.Layer.XYZ( 'tiles', '/tile/' + config.instance.rev + '/database/otm/table/treemap_plot/${z}/${x}/${y}.png', { isBaseLayer: false }); }, init: function () { var map = app.createMap($(""#map"")[0]); map.addLayer(app.createPlotTileLayer(config)); } }; }($, OpenLayers, otm.settings)); $(app.init); ","/* app.js */ //= require OpenLayers /*globals $,OpenLayers,otm*/ /*jslint indent: 4, white: true */ var app = (function ($,L,config) { ""use strict""; return { createBasemap: function (elmt) { var map = new L.Map({ div: elmt, projection: 'EPSG:3857', layers: this.getBasemapLayers(config) }); map.setCenter(config.instance.center, 10); return map; }, getBasemapLayers: function (config) { var layer; if (config.instance.basemap.type === 'bing') { layer = new L.Layer.Bing({ name: 'Road', key: config.instance.basemap.bing_api_key, type: 'Road' }); } else if (config.instance.basemap.type === 'tms') { layer = new L.Layer.XYZ( 'xyz', config.instance.basemap.data); } else { layer = new L.Layer.Google( ""Google Streets"", {numZoomLevels: 20}); } return [layer]; }, init: function () { app.createBasemap($(""#map"")[0]); } }; }($, OpenLayers, otm.settings)); $(app.init); " Restructure menus to match mac patterns,"var app = require('app') var dialog = require('dialog') var menu = require('menu') /* Build the application menu for the current platform. */ exports.application_menu = function(window) { var file = { label: 'File', submenu: [ { label: 'Quit', accelerator: 'CmdOrCtrl+Q', click: function() { app.quit() } }, ] } var help = { label: 'Help', submenu: [] } var about = { label: 'About apollo', click: function() { dialog.showMessageBox(window, { title: 'About apollo', message: 'Apollo v' + app.getVersion(), buttons: ['ok'], }) } } if (process.platform == 'darwin') { file.submenu.push(about) } else { help.submenu.push(about) } return menu.buildFromTemplate([ file, help, ]) } ","var app = require('app') var dialog = require('dialog') var menu = require('menu') /* Build the application menu for the current platform. */ exports.application_menu = function(window) { var template = [ { label: 'File', submenu: [ { label: 'Quit', accelerator: 'CmdOrCtrl+Q', click: function() { app.quit() } } ] }, { label: 'Help', submenu: [ { label: 'About apollo', click: function() { dialog.showMessageBox(window, { title: 'About apollo', message: 'Apollo v' + app.getVersion(), buttons: ['ok'], }) } } ] } ] return menu.buildFromTemplate(template) } " Fix role in student model boot up,"<?php namespace App; use Illuminate\Database\Eloquent\Model; class Student extends Model { protected $fillable = [ 'first_name', 'last_name', 'email', 'password', 'major', 'semester' ]; protected $visible = [ 'id', 'first_name', 'last_name', 'email', 'password', 'major', 'semester', 'teams' ]; protected static function boot() { // TODO send email with randomly generated password Student::created(function($student) { $student->university->user()->create([ 'name' => $student->first_name . ' ' . $student->last_name, 'email' => $student->email, 'password' => bcrypt('1234'), 'role' => 'student' ]); }); } /** * A student is enrolled in an university. * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function university() { return $this->belongsTo('App\University'); } /** * A student belongs to many groups. * * @return $this */ public function teams() { return $this->belongsToMany('App\Team') ->withPivot('role'); } /** * Get the user instance of the student. * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function user() { return $this->belongsTo(User::class); } } ","<?php namespace App; use Illuminate\Database\Eloquent\Model; class Student extends Model { protected $fillable = [ 'first_name', 'last_name', 'email', 'password', 'major', 'semester' ]; protected $visible = [ 'id', 'first_name', 'last_name', 'email', 'password', 'major', 'semester', 'teams' ]; protected static function boot() { // TODO send email with randomly generated password Student::created(function($student) { $student->university->user()->create([ 'name' => $student->first_name . ' ' . $student->last_name, 'email' => $student->email, 'password' => bcrypt('1234'), 'role' => 'professor' ]); }); } /** * A student is enrolled in an university. * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function university() { return $this->belongsTo('App\University'); } /** * A student belongs to many groups. * * @return $this */ public function teams() { return $this->belongsToMany('App\Team') ->withPivot('role'); } /** * Get the user instance of the student. * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function user() { return $this->belongsTo(User::class); } } " Remove predefined globals list in favor of node:true and browser:true,"(function () { ""use strict""; var configureGrunt = function (grunt) { var cfg = { // JSLint all the things! jslint: { directives: { node: true, browser: true, nomen: true, todo: true }, files: [ // Lint files in the root, including Gruntfile.js ""*.js"", // Lint core files, but not libs [""core/**/*.js"", ""!**/assets/lib/**/*.js""] ] }, // Unit test all the things! nodeunit: { all: ['core/test/ghost/**/test-*.js'] }, // Compile all the SASS! compass: { options: { config: ""config.rb"" }, // No need for config, but separated for future options admin: {} } }; grunt.initConfig(cfg); grunt.loadNpmTasks(""grunt-jslint""); grunt.loadNpmTasks(""grunt-contrib-nodeunit""); grunt.loadNpmTasks(""grunt-contrib-compass""); // Prepare the project for development // TODO: Git submodule init/update (https://github.com/jaubourg/grunt-update-submodules)? grunt.registerTask(""init"", [""compass:admin""]); // Run tests and lint code grunt.registerTask(""validate"", [""jslint"", ""nodeunit:all""]); }; module.exports = configureGrunt; }());","(function () { ""use strict""; var configureGrunt = function (grunt) { var cfg = { // JSLint all the things! jslint: { directives: { nomen: true, todo: true, predef: [""__dirname"", ""module"", ""exports"", ""require"", ""process"", ""document"", ""console""] }, files: [ // Lint files in the root, including Gruntfile.js ""*.js"", // Lint core files, but not libs [""core/**/*.js"", ""!**/assets/lib/**/*.js""] ] }, // Unit test all the things! nodeunit: { all: ['core/test/ghost/**/test-*.js'] }, // Compile all the SASS! compass: { options: { config: ""config.rb"" }, // No need for config, but separated for future options admin: {} } }; grunt.initConfig(cfg); grunt.loadNpmTasks(""grunt-jslint""); grunt.loadNpmTasks(""grunt-contrib-nodeunit""); grunt.loadNpmTasks(""grunt-contrib-compass""); // Prepare the project for development // TODO: Git submodule init/update (https://github.com/jaubourg/grunt-update-submodules)? grunt.registerTask(""init"", [""compass:admin""]); // Run tests and lint code grunt.registerTask(""validate"", [""jslint"", ""nodeunit:all""]); }; module.exports = configureGrunt; }());" lib: Allow for connection string to be used.,"'use strict'; var Hoek = require('hoek'); var sqlizr = require('sqlizr'); var Sequelize = require('sequelize'); /** * Creates database connection, imports models, and exposes them via the db object * @param plugin * @param options * @param next */ exports.register = function(plugin, options, next) { // default directory for models options.models = options.models || 'models/**/*.js'; var defaultOptions = { host: options.host || 'localhost', dialect: options.dialect || 'mysql', port: options.port || 3306, logging: options.logging === false ? false : options.logging || console.log, uri: options.uri === false ? false : options.uri }; // apply top level plugin options to a full sequelize options object var sequelizeOptions = Hoek.applyToDefaults(defaultOptions, options.sequelize || {}); var sequelize = undefined; if (!options.uri) { delete options.uri; sequelize = new Sequelize(options.database, options.user, options.pass, sequelizeOptions); } else { sequelize = new Sequelize(options.uri, sequelizeOptions); } // test the database connection sequelize.authenticate() .then(function() { // import models sqlizr(sequelize, options.models); var db = { sequelize: sequelize, Sequelize: Sequelize }; // make available in hapi application plugin.expose('db', db); return next(); }) .catch(function(err) { return next(err); }); }; exports.register.attributes = { pkg: require('../package.json') }; ","'use strict'; var Hoek = require('hoek'); var sqlizr = require('sqlizr'); var Sequelize = require('sequelize'); /** * Creates database connection, imports models, and exposes them via the db object * @param plugin * @param options * @param next */ exports.register = function(plugin, options, next) { // default directory for models options.models = options.models || 'models/**/*.js'; var defaultOptions = { host: options.host || 'localhost', dialect: options.dialect || 'mysql', port: options.port || 3306, logging: options.logging === false ? false : options.logging || console.log }; // apply top level plugin options to a full sequelize options object var sequelizeOptions = Hoek.applyToDefaults(defaultOptions, options.sequelize || {}); var sequelize = new Sequelize(options.database, options.user, options.pass, sequelizeOptions); // test the database connection sequelize.authenticate() .then(function() { // import models sqlizr(sequelize, options.models); var db = { sequelize: sequelize, Sequelize: Sequelize }; // make available in hapi application plugin.expose('db', db); return next(); }) .catch(function(err) { return next(err); }); }; exports.register.attributes = { pkg: require('../package.json') }; " Add TODO to handle no-new-line case,"export default function discardChangesInBuffer(buffer, filePatch, discardedLines) { // TODO: store of buffer for restoring in case of undo buffer.transact(() => { let addedCount = 0; let removedCount = 0; let deletedCount = 0; filePatch.getHunks().forEach(hunk => { hunk.getLines().forEach(line => { if (discardedLines.has(line)) { if (line.status === 'deleted') { const row = (line.oldLineNumber - deletedCount) + addedCount - removedCount - 1; buffer.insert([row, 0], line.text + '\n'); addedCount++; } else if (line.status === 'added') { const row = line.newLineNumber + addedCount - removedCount - 1; if (buffer.lineForRow(row) === line.text) { buffer.deleteRow(row); removedCount++; } else { // eslint-disable-next-line no-console console.error(buffer.lineForRow(row) + ' does not match ' + line.text); } } else if (line.status === 'nonewline') { // TODO: handle no new line case } else { throw new Error(`unrecognized status: ${line.status}. Must be 'added' or 'deleted'`); } } if (line.getStatus() === 'deleted') { deletedCount++; } }); }); }); buffer.save(); } ","export default function discardChangesInBuffer(buffer, filePatch, discardedLines) { // TODO: store of buffer for restoring in case of undo buffer.transact(() => { let addedCount = 0; let removedCount = 0; let deletedCount = 0; filePatch.getHunks().forEach(hunk => { hunk.getLines().forEach(line => { if (discardedLines.has(line)) { if (line.status === 'deleted') { const row = (line.oldLineNumber - deletedCount) + addedCount - removedCount - 1; buffer.insert([row, 0], line.text + '\n'); addedCount++; } else if (line.status === 'added') { const row = line.newLineNumber + addedCount - removedCount - 1; if (buffer.lineForRow(row) === line.text) { buffer.deleteRow(row); removedCount++; } else { // eslint-disable-next-line no-console console.error(buffer.lineForRow(row) + ' does not match ' + line.text); } } else { throw new Error(`unrecognized status: ${line.status}. Must be 'added' or 'deleted'`); } } if (line.getStatus() === 'deleted') { deletedCount++; } }); }); }); buffer.save(); } " Fix detect Git-LFS in tests,"import email from os.path import dirname, join from django.utils import six from django_mailbox.models import Mailbox from feder.letters.signals import MessageParser class MessageMixin(object): def setUp(self): self.mailbox = Mailbox.objects.create(from_email='from@example.com') super(MessageMixin, self).setUp() @staticmethod def _get_email_path(filename): return join(dirname(__file__), 'messages', filename) @staticmethod def _get_email_object(filename): # See coddingtonbear/django-mailbox#89 path = MessageMixin._get_email_path(filename) for line in open(path, 'r'): if 'git-lfs' in line: raise Exception(""File '{}' not downloaded. Only Git-LFS reference available. Perform 'git lfs pull'."".format(filename)) if six.PY3: return email.message_from_file(open(path, 'r')) else: # Deprecated. Back-ward compatible for PY2.7< return email.message_from_file(open(path, 'rb')) def get_message(self, filename): message = self._get_email_object(filename) msg = self.mailbox._process_message(message) msg.save() return msg def load_letter(self, name): message = self.get_message(name) return MessageParser(message).insert() ","import email from os.path import dirname, join from django.utils import six from django_mailbox.models import Mailbox from feder.letters.signals import MessageParser class MessageMixin(object): def setUp(self): self.mailbox = Mailbox.objects.create(from_email='from@example.com') super(MessageMixin, self).setUp() @staticmethod def _get_email_path(filename): return join(dirname(__file__), 'messages', filename) @staticmethod def _get_email_object(filename): # See coddingtonbear/django-mailbox#89 path = MessageMixin._get_email_path(filename) for line in open('git-lfs.github.com', 'r'): if 'git-lfs' in line: raise Exception(""File '{}' not downloaded. Only Git-LFS reference available. Perform 'git lfs pull'."".format(filename)) if six.PY3: return email.message_from_file(open(path, 'r')) else: # Deprecated. Back-ward compatible for PY2.7< return email.message_from_file(open(path, 'rb')) def get_message(self, filename): message = self._get_email_object(filename) msg = self.mailbox._process_message(message) msg.save() return msg def load_letter(self, name): message = self.get_message(name) return MessageParser(message).insert() " Create release fix for fixing readme on Pypi,"from setuptools import setup from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='flask-swagger-ui', version='0.0.1a', description='Swagger UI blueprint for Flask', long_description=long_description, url='https://github.com/sveint/flask-swagger-ui', author='Svein Tore Koksrud Seljebotn', author_email='sveint@gmail.com', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], keywords='flask swagger', packages=['flask_swagger_ui'], package_data={ 'flask_swagger_ui': [ 'README.md', 'templates/*.html', 'dist/VERSION', 'dist/LICENSE', 'dist/README.md', 'dist/*.html', 'dist/*.js', 'dist/*/*.js', 'dist/*/*.css', 'dist/*/*.gif', 'dist/*/*.png', 'dist/*/*.ico', 'dist/*/*.ttf', ], } ) ","from setuptools import setup from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='flask-swagger-ui', version='0.0.1', description='SwaggerUI blueprint for Flask', long_description=long_description, url='https://github.com/sveint/flask-swagger-ui', author='Svein Tore Koksrud Seljebotn', author_email='sveint@gmail.com', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], keywords='flask swagger', packages=['flask_swagger_ui'], package_data={ 'flask_swagger_ui': [ 'README.md', 'templates/*.html', 'dist/VERSION', 'dist/LICENSE', 'dist/README.md', 'dist/*.html', 'dist/*.js', 'dist/*/*.js', 'dist/*/*.css', 'dist/*/*.gif', 'dist/*/*.png', 'dist/*/*.ico', 'dist/*/*.ttf', ], } ) " "Change comment from a charfield to a textfield, and add a date_created field; which is not working correctly.","from django.db import models from django.contrib.auth.models import User class Project(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=100) version = models.CharField(max_length=15, null=True) release_date = models.DateField(null=True) class Issue(models.Model): project = models.ForeignKey(Project) status_choices = ( (""0"", ""OPEN""), (""1"", ""IN PROGRESS""), (""2"", ""FINISHED""), (""3"", ""CLOSED""), (""4"", ""CANCELED""), ) status = models.CharField(max_length=10, choices=status_choices) level_choices = ( (""0"", ""LOW""), (""1"", ""MEDIUM""), (""2"", ""HIGH""), (""3"", ""CRITICAL""), (""4"", ""BLOCKER""), ) level = models.CharField(max_length=10, choices=level_choices) title = models.CharField(max_length=50, null=True) description = models.CharField(max_length=50, null=True) date_created = models.DateField(auto_now_add=True) date_completed = models.DateField(null=True) # TODO implement these # time_estimate # percentage_completed class Comments(models.Model): issue = models.ForeignKey(Issue) comment = models.TextField(max_length=500) date_created = models.DateTimeField(null=False, auto_now_add=True) user = models.ForeignKey(User,null=True, blank=True) ","from django.db import models from django.contrib.auth.models import User class Project(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=100) version = models.CharField(max_length=15, null=True) release_date = models.DateField(null=True) class Issue(models.Model): project = models.ForeignKey(Project) status_choices = ( (""0"", ""OPEN""), (""1"", ""IN PROGRESS""), (""2"", ""FINISHED""), (""3"", ""CLOSED""), (""4"", ""CANCELED""), ) status = models.CharField(max_length=10, choices=status_choices) level_choices = ( (""0"", ""LOW""), (""1"", ""MEDIUM""), (""2"", ""HIGH""), (""3"", ""CRITICAL""), (""4"", ""BLOCKER""), ) level = models.CharField(max_length=10, choices=level_choices) title = models.CharField(max_length=50, null=True) description = models.CharField(max_length=50, null=True) date_created = models.DateField(auto_now_add=True) date_completed = models.DateField(null=True) # TODO implement these # time_estimate # percentage_completed class Comments(models.Model): issue = models.ForeignKey(Issue) comment = models.CharField(max_length=500) user = models.ForeignKey(User,null=True, blank=True) " Fix for graphene ui on debug mode,"from django.conf import settings from django.http import JsonResponse from django.utils.decorators import method_decorator from django.utils.translation import ugettext_lazy as _ from graphene_django.views import GraphQLView from rest_framework import status from rest_framework.exceptions import APIException from rest_framework_jwt.authentication import JSONWebTokenAuthentication def check_jwt_decorator(func): """""" Check JWT Token by using DRF Authentication class. Returns UNAUTHORIZED response if headers don't contain alive token. :param func: :return: """""" def wrap(request, *args, **kwargs): if settings.DEBUG: if request.user.is_authenticated(): return func(request, *args, **kwargs) try: auth_tuple = JSONWebTokenAuthentication().authenticate(request) except APIException as e: return JsonResponse({'details': str(e)}, status=e.status_code) except Exception as e: raise e if auth_tuple is None: return JsonResponse({'details': _('Unauthorized user')}, status=status.HTTP_401_UNAUTHORIZED) request.user, request.auth = auth_tuple return func(request, *args, **kwargs) return wrap class DRFAuthenticatedGraphQLView(GraphQLView): """""" Extended default GraphQLView. """""" @method_decorator(check_jwt_decorator) def dispatch(self, request, *args, **kwargs): return super(DRFAuthenticatedGraphQLView, self).dispatch( request, *args, **kwargs) ","from django.http import JsonResponse from django.utils.decorators import method_decorator from django.utils.translation import ugettext_lazy as _ from graphene_django.views import GraphQLView from rest_framework import status from rest_framework.exceptions import APIException from rest_framework_jwt.authentication import JSONWebTokenAuthentication def check_jwt_decorator(func): """""" Check JWT Token by using DRF Authentication class. Returns UNAUTHORIZED response if headers don't contain alive token. :param func: :return: """""" def wrap(request, *args, **kwargs): try: auth_tuple = JSONWebTokenAuthentication().authenticate(request) except APIException as e: return JsonResponse({'details': str(e)}, status=e.status_code) except Exception as e: raise e if auth_tuple is None: return JsonResponse({'details': _('Unauthorized user')}, status=status.HTTP_401_UNAUTHORIZED) request.user, request.auth = auth_tuple return func(request, *args, **kwargs) return wrap class DRFAuthenticatedGraphQLView(GraphQLView): """""" Extended default GraphQLView. """""" @method_decorator(check_jwt_decorator) def dispatch(self, request, *args, **kwargs): return super(DRFAuthenticatedGraphQLView, self).dispatch( request, *args, **kwargs) " Fix migration to use actual value instead of non-existing attribute,"# Generated by Django 2.2.15 on 2020-09-21 11:38 from django.db import migrations from resolwe.flow.utils import iterate_fields def purge_data_dependencies(apps, schema_editor): Data = apps.get_model(""flow"", ""Data"") DataDependency = apps.get_model(""flow"", ""DataDependency"") for data in Data.objects.iterator(): parent_pks = [] for field_schema, fields in iterate_fields( data.input, data.process.input_schema ): name = field_schema[""name""] value = fields[name] if field_schema.get(""type"", """").startswith(""data:""): parent_pks.append(value) elif field_schema.get(""type"", """").startswith(""list:data:""): parent_pks.extend(value) parent_pks = [ pk if Data.objects.filter(pk=pk).exists() else None for pk in parent_pks ] for dependency in DataDependency.objects.filter(child=data.id, kind=""io""): parent_pk = dependency.parent.pk if dependency.parent else None if parent_pk in parent_pks: parent_pks.remove(parent_pk) else: dependency.delete() class Migration(migrations.Migration): dependencies = [ (""flow"", ""0045_unreferenced_storages""), ] operations = [ migrations.RunPython(purge_data_dependencies), ] ","# Generated by Django 2.2.15 on 2020-09-21 11:38 from django.db import migrations from resolwe.flow.utils import iterate_fields def purge_data_dependencies(apps, schema_editor): Data = apps.get_model(""flow"", ""Data"") DataDependency = apps.get_model(""flow"", ""DataDependency"") for data in Data.objects.iterator(): parent_pks = [] for field_schema, fields in iterate_fields( data.input, data.process.input_schema ): name = field_schema[""name""] value = fields[name] if field_schema.get(""type"", """").startswith(""data:""): parent_pks.append(value) elif field_schema.get(""type"", """").startswith(""list:data:""): parent_pks.extend(value) parent_pks = [ pk if Data.objects.filter(pk=pk).exists() else None for pk in parent_pks ] for dependency in DataDependency.objects.filter( child=data.id, kind=DataDependency.KIND_IO ): parent_pk = dependency.parent.pk if dependency.parent else None if parent_pk in parent_pks: parent_pks.remove(parent_pk) else: dependency.delete() class Migration(migrations.Migration): dependencies = [ (""flow"", ""0045_unreferenced_storages""), ] operations = [ migrations.RunPython(purge_data_dependencies), ] " Move close functionality on location change into mwMenuTopBar,"angular.module('mwUI.Menu') .directive('mwMenuTopEntries', function ($rootScope, $timeout) { return { scope: { menu: '=mwMenuTopEntries', right: '=' }, transclude: true, templateUrl: 'uikit/mw-menu/directives/templates/mw_menu_top_entries.html', controller: function ($scope) { var menu = $scope.menu || new mwUI.Menu.MwMenu(); this.getMenu = function () { return menu; }; }, link: function (scope, el, attrs, ctrl) { scope.entries = ctrl.getMenu(); scope.$on('mw-menu:triggerReorder', _.throttle(function () { $timeout(function () { scope.$broadcast('mw-menu:reorder'); }); })); scope.$on('mw-menu:triggerResort', _.throttle(function () { $timeout(function () { scope.$broadcast('mw-menu:resort'); scope.entries.sort(); }); })); scope.entries.on('add remove reset', _.throttle(function () { $timeout(function () { scope.$broadcast('mw-menu:reorder'); }); })); } }; });","angular.module('mwUI.Menu') .directive('mwMenuTopEntries', function ($rootScope, $timeout) { return { scope: { menu: '=mwMenuTopEntries', right: '=' }, transclude: true, templateUrl: 'uikit/mw-menu/directives/templates/mw_menu_top_entries.html', controller: function ($scope) { var menu = $scope.menu || new mwUI.Menu.MwMenu(); this.getMenu = function () { return menu; }; }, link: function (scope, el, attrs, ctrl) { scope.entries = ctrl.getMenu(); scope.unCollapse = function () { var collapseEl = el.find('.navbar-collapse'); if (collapseEl.hasClass('in')) { collapseEl.collapse('hide'); } }; $rootScope.$on('$locationChangeSuccess', function () { scope.unCollapse(); }); scope.$on('mw-menu:triggerReorder', _.throttle(function () { $timeout(function () { scope.$broadcast('mw-menu:reorder'); }); })); scope.$on('mw-menu:triggerResort', _.throttle(function () { $timeout(function () { scope.$broadcast('mw-menu:resort'); scope.entries.sort(); }); })); scope.entries.on('add remove reset', _.throttle(function () { $timeout(function () { scope.$broadcast('mw-menu:reorder'); }); })); } }; });" Fix returning to index and the navbar not turning transparent,"(function() { 'use strict'; angular .module('app.layout') .directive('pvTopNav', pvTopNav); /* @ngInject */ function pvTopNav () { var directive = { bindToController: true, controller: TopNavController, controllerAs: 'vm', restrict: 'EA', scope: { 'inHeader': '=' }, templateUrl: 'app/layout/pv-top-nav.html' }; /* @ngInject */ function TopNavController($scope, $document, $state, $rootScope) { var vm = this; activate(); function activate() { checkWithinIntro(); $document.on('scroll', checkWithinIntro); $rootScope.$on('$viewContentLoaded', checkWithinIntro); } function checkWithinIntro() { var aboutTopPosition = $document.find('#about').offset().top, navbarHeight = $document.find('#pv-top-nav').height(), triggerHeight = aboutTopPosition - navbarHeight - 1; vm.inHeader = $state.current.url === '/' && $document.scrollTop() <= triggerHeight; $scope.$applyAsync(); } } return directive; } })(); ","(function() { 'use strict'; angular .module('app.layout') .directive('pvTopNav', pvTopNav); /* @ngInject */ function pvTopNav () { var directive = { bindToController: true, controller: TopNavController, controllerAs: 'vm', restrict: 'EA', scope: { 'inHeader': '=' }, templateUrl: 'app/layout/pv-top-nav.html' }; /* @ngInject */ function TopNavController($scope, $document, $state) { var vm = this; activate(); function activate() { checkWithinIntro(); $document.on('scroll', checkWithinIntro); } function checkWithinIntro() { var aboutTopPosition = $document.find('#about').offset().top, navbarHeight = $document.find('#pv-top-nav').height(), triggerHeight = aboutTopPosition - navbarHeight - 1; vm.inHeader = $state.current.url === '/' && $document.scrollTop() <= triggerHeight; $scope.$applyAsync(); } } return directive; } })(); " "Create sqlite database if use select that. If a user decides to utilize sqlite, let's go ahead and make the database for them.","<?php namespace RachidLaasri\LaravelInstaller\Helpers; use Exception; use Illuminate\Support\Facades\Artisan; class DatabaseManager { /** * Migrate and seed the database. * * @return array */ public function migrateAndSeed() { $this->sqlite(); return $this->migrate(); } /** * Run the migration and call the seeder. * * @return array */ private function migrate() { try{ Artisan::call('migrate', [""--force""=> true ]); } catch(Exception $e){ return $this->response($e->getMessage()); } return $this->seed(); } /** * Seed the database. * * @return array */ private function seed() { try{ Artisan::call('db:seed'); } catch(Exception $e){ return $this->response($e->getMessage()); } return $this->response(trans('messages.final.finished'), 'success'); } /** * Return a formatted error messages. * * @param $message * @param string $status * @return array */ private function response($message, $status = 'danger') { return array( 'status' => $status, 'message' => $message ); } /** * check database type. If SQLite, then create the database file. */ private function sqlite() { if(DB::connection() instanceof SQLiteConnection) { $database = DB::connection()->getDatabaseName(); if(!file_exists($database)) { touch($database); DB::reconnect(Config::get('database.default')); } } } } ","<?php namespace RachidLaasri\LaravelInstaller\Helpers; use Exception; use Illuminate\Support\Facades\Artisan; class DatabaseManager { /** * Migrate and seed the database. * * @return array */ public function migrateAndSeed() { return $this->migrate(); } /** * Run the migration and call the seeder. * * @return array */ private function migrate() { try{ Artisan::call('migrate', [""--force""=> true ]); } catch(Exception $e){ return $this->response($e->getMessage()); } return $this->seed(); } /** * Seed the database. * * @return array */ private function seed() { try{ Artisan::call('db:seed'); } catch(Exception $e){ return $this->response($e->getMessage()); } return $this->response(trans('messages.final.finished'), 'success'); } /** * Return a formatted error messages. * * @param $message * @param string $status * @return array */ private function response($message, $status = 'danger') { return array( 'status' => $status, 'message' => $message ); } }" "Fix tag select with keyboard. Previously the selecting of a tag with the keyboard resulted in the whole tag list being replaced by just the one selected tag.","ep.ui.createTagsInput = function(source) { // partly from http://jqueryui.com/autocomplete/#multiple-remote function split(val) { return val.split(/,\s*/); } function extractLast(term) { return split(term).pop(); } if ($.ui && $.ui.autocomplete) { $('input.tags-input').each(function() { var $that = $(this); $that.bind(""keydown"", function(event) { if (event.keyCode === $.ui.keyCode.TAB && $(this).data(""ui-autocomplete"").menu.active) { event.preventDefault(); } }); $that.autocomplete({ delay: 300, source: function(request, response) { $.getJSON(source, { term: extractLast(request.term) }, response ); }, search: function() { var term = extractLast(this.value); if (term.length < 1) { return false; } }, focus: function() { return false; }, select: function(event, ui) { var terms = split(this.value); terms.pop(); terms.push(ui.item.value); terms.push(""""); this.value = terms.join("", ""); return false; } }); }); } }; ","ep.ui.createTagsInput = function(source) { // partly from http://jqueryui.com/autocomplete/#multiple-remote function split(val) { return val.split(/,\s*/); } function extractLast(term) { return split(term).pop(); } if ($.ui && $.ui.autocomplete) { $('input.tags-input').each(function() { var $that = $(this); $that.autocomplete({ delay: 300, source: function(request, response) { $.getJSON(source, { term: extractLast(request.term) }, response ); }, search: function() { var term = extractLast(this.value); if (term.length < 1) { return false; } }, select: function(event, ui) { var terms = split(this.value); terms.pop(); terms.push(ui.item.value); terms.push(""""); this.value = terms.join("", ""); return false; } }); }); } };" Clean up debug printing further,"import os, sys from glob import glob import GlobalVars def LoadFunction(path, loadAs=''): loadType = 'l' name = path src = __import__('Functions.' + name, globals(), locals(), []) if loadAs != '': name = loadAs if name in GlobalVars.functions: loadType = 'rel' del sys.modules['Functions.'+name] for f in glob ('Functions/%s.pyc' % name): os.remove(f) reload(src) components = name.split('.') for comp in components[:1]: src = getattr(src, comp) ModuleName = str(src).split(""from"")[0].strip(""("").rstrip("" "") if loadType != 'rel': print ModuleName + "" loaded."" else: print ModuleName + "" reloaded."" func = src.Instantiate() GlobalVars.functions.update({name:func}) return loadType def UnloadFunction(name): success = True if name in GlobalVars.functions.keys(): del GlobalVars.functions[name] else: success = False return success def AutoLoadFunctions(): root = os.path.join('.', 'Functions') for item in os.listdir(root): if not os.path.isfile(os.path.join(root, item)): continue if not item.endswith('.py'): continue try: if item[:-3] not in GlobalVars.nonDefaultModules: LoadFunction(item[:-3]) except Exception, x: print x.args ","import os, sys from glob import glob import GlobalVars def LoadFunction(path, loadAs=''): loadType = 'l' name = path src = __import__('Functions.' + name, globals(), locals(), []) if loadAs != '': name = loadAs if name in GlobalVars.functions: loadType = 'rel' del sys.modules['Functions.'+name] for f in glob ('Functions/%s.pyc' % name): os.remove(f) reload(src) components = name.split('.') for comp in components[:1]: src = getattr(src, comp) ModuleName = str(src).split(""from"")[0].strip(""("").rstrip("" "") if loadType != 'rel': print ModuleName + "" loaded."" func = src.Instantiate() GlobalVars.functions.update({name:func}) return loadType def UnloadFunction(name): success = True if name in GlobalVars.functions.keys(): del GlobalVars.functions[name] else: success = False return success def AutoLoadFunctions(): root = os.path.join('.', 'Functions') for item in os.listdir(root): if not os.path.isfile(os.path.join(root, item)): continue if not item.endswith('.py'): continue try: if item[:-3] not in GlobalVars.nonDefaultModules: LoadFunction(item[:-3]) except Exception, x: print x.args " "Fix killbill cost estimate logic - NC-738","import logging import calendar import datetime from nodeconductor.cost_tracking import CostTrackingStrategy from nodeconductor.iaas.models import Instance from nodeconductor.structure import ServiceBackendError logger = logging.getLogger(__name__) class IaaSCostTracking(CostTrackingStrategy): @classmethod def get_costs_estimates(cls, customer=None): # TODO: move this logic to IaaS backend method 'get_cost_estimate' # and get rid from app dependent cost tracking together with entry points queryset = Instance.objects.exclude(billing_backend_id='') if customer: queryset = queryset.filter(customer=customer) for instance in queryset.iterator(): try: backend = instance.order.backend invoice = backend.get_invoice_estimate(instance) except ServiceBackendError as e: logger.error( ""Failed to get price estimate for resource %s: %s"", instance, e) else: today = datetime.date.today() if not invoice['start_date'] <= today <= invoice['end_date']: logger.error( ""Wrong invoice estimate for resource %s: %s"", instance, invoice) continue # prorata monthly cost estimate based on daily usage cost days_in_month = calendar.monthrange(today.year, today.month)[1] daily_cost = invoice['amount'] / ((today - invoice['start_date']).days + 1) cost = daily_cost * days_in_month yield instance, cost ","import logging import calendar import datetime from nodeconductor.cost_tracking import CostTrackingStrategy from nodeconductor.iaas.models import Instance from nodeconductor.structure import ServiceBackendError logger = logging.getLogger(__name__) class IaaSCostTracking(CostTrackingStrategy): @classmethod def get_costs_estimates(cls, customer=None): # TODO: move this logic to IaaS backend method 'get_cost_estimate' # and get rid from app dependent cost tracking together with entry points queryset = Instance.objects.exclude(billing_backend_id='') if customer: queryset = queryset.filter(customer=customer) for instance in queryset.iterator(): try: backend = instance.order.backend invoice = backend.get_invoice_estimate(instance) except ServiceBackendError as e: logger.error( ""Failed to get price estimate for resource %s: %s"", instance, e) else: # prorata estimate calculation based on daily usage cost sd = invoice['start_date'] ed = invoice['end_date'] today = datetime.date.today() if not sd <= today <= ed: logger.error( ""Wrong invoice estimate for resource %s: %s"", instance, invoice) continue if sd.year == today.year and sd.month == today.month: days_in_month = calendar.monthrange(sd.year, sd.month)[1] days = sd.replace(day=days_in_month) - sd elif ed.year == today.year and ed.month == today.month: days = ed - ed.replace(day=1) daily_cost = invoice['amount'] / ((today - sd).days + 1) cost = daily_cost * (days.days + 1) yield instance, cost " Add deprecated fallback for SSLMiddleware.," from mezzanine.conf import settings from cartridge.shop.models import Cart class SSLRedirect(object): def __init__(self): old = (""SHOP_SSL_ENABLED"", ""SHOP_FORCE_HOST"", ""SHOP_FORCE_SSL_VIEWS"") for name in old: try: getattr(settings, name) except AttributeError: pass else: import warnings warnings.warn(""The settings %s are deprecated; "" ""use SSL_ENABLED, SSL_FORCE_HOST and "" ""SSL_FORCE_URL_PREFIXES, and add "" ""mezzanine.core.middleware.SSLRedirectMiddleware to "" ""MIDDLEWARE_CLASSES."" % "", "".join(old)) break class ShopMiddleware(SSLRedirect): """""" Adds cart and wishlist attributes to the current request. """""" def process_request(self, request): request.cart = Cart.objects.from_request(request) wishlist = request.COOKIES.get(""wishlist"", """").split("","") if not wishlist[0]: wishlist = [] request.wishlist = wishlist "," from mezzanine.conf import settings from cartridge.shop.models import Cart class ShopMiddleware(object): def __init__(self): old = (""SHOP_SSL_ENABLED"", ""SHOP_FORCE_HOST"", ""SHOP_FORCE_SSL_VIEWS"") for name in old: try: getattr(settings, name) except AttributeError: pass else: import warnings warnings.warn(""The settings %s are deprecated; "" ""use SSL_ENABLED, SSL_FORCE_HOST and "" ""SSL_FORCE_URL_PREFIXES, and add "" ""mezzanine.core.middleware.SSLRedirectMiddleware to "" ""MIDDLEWARE_CLASSES."" % "", "".join(old)) break def process_request(self, request): """""" Adds cart and wishlist attributes to the current request. """""" request.cart = Cart.objects.from_request(request) wishlist = request.COOKIES.get(""wishlist"", """").split("","") if not wishlist[0]: wishlist = [] request.wishlist = wishlist " Fix existing Array methods and support negative and >= size sets.," import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class RArray extends RObject { public final ArrayList<RObject> impl; public RArray() { impl = new ArrayList<RObject>(); } public RArray(RObject... args) { impl = new ArrayList<RObject>(Arrays.asList(args)); } public RArray(List<RObject> impl) { this.impl = new ArrayList<RObject>(impl); } public RObject $less$less(RObject what) { impl.add(what); return this; } public RObject $lbrack$rbrack(RObject where) { int index = (int)((RFixnum)where.to_i()).fix; if (index < 0) { index = impl.size() + index; } if (index < impl.size()) { return impl.get(index); } else { return RNil; } } public RObject $lbrack$rbrack$equal(RObject where, RObject what) { int index = (int)((RFixnum)where.to_i()).fix; if (index < 0) { index = impl.size() + index; } if (index >= impl.size()) { impl.ensureCapacity(index + 1); } impl.set(index, what); return this; } public RObject size() { return new RFixnum(impl.size()); } public RObject clear() { impl.clear(); return this; } } "," import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class RArray extends RObject { public final ArrayList<RObject> impl; public RArray() { impl = new ArrayList<RObject>(); } public RArray(RObject... args) { impl = new ArrayList<RObject>(Arrays.asList(args)); } public RArray(List<RObject> impl) { this.impl = new ArrayList<RObject>(impl); } public RObject $less$less(RObject what) { add(what); return this; } public RObject $lbrack$rbrack(RObject where) { int index = (int)((RFixnum)where.to_i()).fix; if (index < size()) { return get(index); } return RNil; } public RObject $lbrack$rbrack$equal(RObject where, RObject what) { int index = (int)((RFixnum)where.to_i()).fix; // TODO index >= size impl.set(index, what); return this; } public RObject size() { return new RFixnum(impl.size()); } public RObject clear() { impl.clear(); return this; } } " Make joke parsing more robust,"import re from os import path from pal.services.service import Service from pal.services.service import wrap_response def get_jokes(): file_path = path.realpath(path.join(path.dirname(__file__), ""jokes.txt"")) with open(file_path, 'rb') as joke_file: for line in joke_file.readlines(): if line.startswith(""#""): continue prompt, response = map(str.strip, line.split(""::"", 1)) yield prompt, response.replace(""\\n"", ""\n"") class JokeService(Service): _JOKES = {prompt: response for prompt, response in get_jokes()} def applies_to_me(self, client, feature_request_type): return True def get_confidence(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return 9001 return 0 @wrap_response def go(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return self._JOKES[joke] return ('ERROR', 'Tom Hanks was in 1 movies.') ","import re from os import path from pal.services.service import Service from pal.services.service import wrap_response def get_jokes(): file_path = path.realpath(path.join(path.dirname(__file__), ""jokes.txt"")) with open(file_path, 'rb') as joke_file: for line in joke_file.readlines(): if line.startswith(""#""): continue yield line.strip().split("" :: "", 1) class JokeService(Service): _JOKES = {prompt: response for prompt, response in get_jokes()} def applies_to_me(self, client, feature_request_type): return True def get_confidence(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return 9001 return 0 @wrap_response def go(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return self._JOKES[joke] return ('ERROR', 'Tom Hanks was in 1 movies.') " Fix packages test for CI env.,"/*global describe, it */ ""use strict""; var opencpu = require(""../lib/opencpu""), config = require(""./opencpu-config""), assert = require(""assert""); describe(""Packages test:"", function () { describe(""MASS getInfo"", function () { it(""should find Information word"", function (done) { opencpu.packages.getInfo(""MASS"", function (err, data) { if (!err) { assert.ok(/Information/.test(data)); } else { throw err; } done(); }, ""/library/"", config.getOptions()); }); }); describe(""MASS getExportedObjects"", function () { it(""should find addterm object"", function (done) { opencpu.packages.getExportedObjects(""MASS"", function (err, data) { if (!err) { assert.ok(/addterm/.test(data)); } else { throw err; } done(); }, ""/library/"", config.getOptions()); }); }); }); ","/*global describe, it */ ""use strict""; var opencpu = require(""../lib/opencpu""), config = require(""./opencpu-config""), assert = require(""assert""); describe(""Packages test:"", function () { describe(""MASS getInfo"", function () { it(""should find Information word"", function (done) { opencpu.packages.getInfo(""MASS"", function (err, data) { if (!err) { assert.equal(4, /Information/.exec(data).index); } else { throw err; } done(); }, ""/library/"", config.getOptions()); }); }); describe(""MASS getExportedObjects"", function () { it(""should find addterm object"", function (done) { opencpu.packages.getExportedObjects(""MASS"", function (err, data) { if (!err) { assert.equal(18, /addterm/.exec(data).index); } else { throw err; } done(); }, ""/library/"", config.getOptions()); }); }); }); " Change to new attribute names.,"#-----------------------------------------------------------------------------# # MODULE DESCRIPTION # #-----------------------------------------------------------------------------# """"""RedBrick Options Module; contains RBOpt class."""""" #-----------------------------------------------------------------------------# # DATA # #-----------------------------------------------------------------------------# __version__ = '$Revision: 1.2 $' __author__ = 'Cillian Sharkey' #-----------------------------------------------------------------------------# # CLASSES # #-----------------------------------------------------------------------------# class RBOpt: """"""Class for storing options to be shared by modules"""""" def __init__(self): """"""Create new RBOpt object."""""" # Used by all modules. self.override = None # Used by useradm, RBUserDB & RBAccount. self.test = None # Used by useradm & rrs. self.mode = None self.setpasswd = None # Used by useradm. self.args = [] self.help = None self.uid = None self.dbonly = None self.aconly = None self.updatedby = None self.newbie = None self.mailuser = None self.usertype = None self.cn = None self.altmail = None self.id = None self.course = None self.year = None self.yearsPaid = None self.birthday = None self.quiet = None # Used by rrs. self.action = None ","#-----------------------------------------------------------------------------# # MODULE DESCRIPTION # #-----------------------------------------------------------------------------# """"""RedBrick Options Module; contains RBOpt class."""""" #-----------------------------------------------------------------------------# # DATA # #-----------------------------------------------------------------------------# __version__ = '$Revision$' __author__ = 'Cillian Sharkey' #-----------------------------------------------------------------------------# # CLASSES # #-----------------------------------------------------------------------------# class RBOpt: """"""Class for storing options to be shared by modules"""""" def __init__(self): """"""Create new RBOpt object."""""" # Used by all modules. self.override = None # Used by useradm, RBUserDB & RBAccount. self.test = None # Used by useradm & rrs. self.mode = None self.setpasswd = None # Used by useradm. self.args = [] self.help = None self.username = None self.dbonly = None self.aconly = None self.updatedby = None self.newbie = None self.mailuser = None self.usertype = None self.name = None self.email = None self.id = None self.course = None self.year = None self.years_paid = None self.birthday = None self.quiet = None # Used by rrs. self.action = None " Fix content localizator for php7.2,"<?php namespace Milax\Mconsole\Processors; use Milax\Mconsole\Contracts\ContentLocalizator as Repository; use Milax\Mconsole\Models\Compiled; class ContentLocalizator implements Repository { public function localize($object, $lang = null) { $lang = is_null($lang) ? config('app.locale') : $lang; $attributes = $object->getAttributes(); $compiled = new Compiled; foreach ($attributes as $key => $value) { $hasLanguages = false; $value = $object->$key; switch (gettype($value)) { case 'array': if (array_has($value, $lang)) { $hasLanguages = true; } break; case 'string': $value = json_decode($value, true); if (json_last_error() === JSON_ERROR_NONE) { if (array_has(is_array($value) ? $value : [$value], $lang)) { $hasLanguages = true; } } break; default: continue; } if ($hasLanguages) { if (!is_array($value[$lang]) && strlen($value[$lang]) == 0) { $compiled->$key = null; } else { $compiled->$key = $value[$lang]; } } } return $compiled; } } ","<?php namespace Milax\Mconsole\Processors; use Milax\Mconsole\Contracts\ContentLocalizator as Repository; use Milax\Mconsole\Models\Compiled; class ContentLocalizator implements Repository { public function localize($object, $lang = null) { $lang = is_null($lang) ? config('app.locale') : $lang; $attributes = $object->getAttributes(); $compiled = new Compiled; foreach ($attributes as $key => $value) { $hasLanguages = false; $value = $object->$key; switch (gettype($value)) { case 'array': if (array_has($value, $lang)) { $hasLanguages = true; } break; case 'string': $value = json_decode($value, true); if (json_last_error() === JSON_ERROR_NONE) { if (array_has($value, $lang)) { $hasLanguages = true; } } break; default: continue; } if ($hasLanguages) { if (!is_array($value[$lang]) && strlen($value[$lang]) == 0) { $compiled->$key = null; } else { $compiled->$key = $value[$lang]; } } } return $compiled; } } " Save user email and name in session.,"var sys = require('sys'); var _ = require('underscore'); var users = require('./users'); module.exports= function(options) { options= options || {}; var that= {}; var my= {}; that.name = options.name || ""form""; var send_to_login = function(response) { response.redirect('/login',303); } that.authenticate= function(request, response, callback) { var context = this; var email = request.body.email; var password = request.body.password; if (!email || !password) { send_to_login(response); } users.get_by_email(email, function(err, user) { if (!user || err) { send_to_login(response); } else { user.checkPassword(password, function(err, result) { if (result) { context.success( {id : user.id, name : user.name, email : user.email}, callback ); } else { context.fail(callback); } }); } }); } return that; };","var sys = require('sys'); var _ = require('underscore'); var users = require('./users'); module.exports= function(options) { options= options || {}; var that= {}; var my= {}; that.name = options.name || ""form""; var send_to_login = function(response) { response.redirect('/login',303); } that.authenticate= function(request, response, callback) { var context = this; var email = request.body.email; var password = request.body.password; if (!email || !password) { send_to_login(response); } users.get_by_email(email, function(err, user) { if (!user || err) { send_to_login(response); } else { user.checkPassword(password, function(err, result) { if (result) { context.success( {id : user.id, name : user.email}, callback ); } else { context.fail(callback); } }); } }); } return that; };" "Use and , and add body class functionality","<?php use Nails\Factory; $aPageTitle = []; if (!empty($page->seo->title)) { $aPageTitle[] = $page->seo->title; } elseif (!empty($page->title)) { $aPageTitle[] = $page->title; } $aPageTitle[] = APP_NAME; $sBodyClass = !empty($page->body_class) ? $page->body_class : ''; ?> <!DOCTYPE html> <!--[if IE 8 ]><html class=""ie ie8"" lang=""en""> <![endif]--> <!--[if (gte IE 9)|!(IE)]><!--><html lang=""en""> <!--<![endif]--> <head> <?php echo '<title>'; echo implode(' - ', $aPageTitle); echo '</title>'; // -------------------------------------------------------------------------- // Meta tags $oMeta = Factory::service('Meta'); echo $oMeta->outputStr(); // -------------------------------------------------------------------------- // Assets $oAsset = Factory::service('Meta'); $oAsset->output('CSS'); $oAsset->output('CSS-INLINE'); $oAsset->output('JS-INLINE-HEADER'); ?> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src=""<?=NAILS_ASSETS_URL . 'bower_components/html5shiv/dist/html5shiv.js'?>""></script> <script src=""<?=NAILS_ASSETS_URL . 'bower_components/respond/dest/respond.min.js'?>""></script> <![endif]--> </head> <body <?=$sBodyClass ? 'class=""' . $sBodyClass . '""' : ''?>> ","<!DOCTYPE html> <!--[if IE 8 ]><html class=""ie ie8"" lang=""en""> <![endif]--> <!--[if (gte IE 9)|!(IE)]><!--><html lang=""en""> <!--<![endif]--> <head> <?php echo '<title>'; if (!empty($page->seo->title)) { echo $page->seo->title . ' - '; } elseif (!empty($page->title)) { echo $page->title . ' - '; } echo APP_NAME; echo '</title>'; // -------------------------------------------------------------------------- // Meta tags echo $this->meta->outputStr(); // -------------------------------------------------------------------------- // Assets $this->asset->output('CSS'); $this->asset->output('CSS-INLINE'); $this->asset->output('JS-INLINE-HEADER'); ?> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src=""<?=NAILS_ASSETS_URL . 'bower_components/html5shiv/dist/html5shiv.js'?>""></script> <script src=""<?=NAILS_ASSETS_URL . 'bower_components/respond/dest/respond.min.js'?>""></script> <![endif]--> </head> <body> " Replace browser history on roster filter update,"define(function (require) { 'use strict'; var Marionette = require('marionette'), LearnersRouter; LearnersRouter = Marionette.AppRouter.extend({ // Routes intended to show a page in the app should map to method names // beginning with ""show"", e.g. 'showLearnerRosterPage'. appRoutes: { '(/)(?*queryString)': 'showLearnerRosterPage', ':username(/)(?*queryString)': 'showLearnerDetailPage', '*notFound': 'showNotFoundPage' }, onRoute: function (routeName) { if (routeName.indexOf('show') === 0) { this.options.controller.triggerMethod('showPage'); } }, initialize: function (options) { this.options = options || {}; this.learnerCollection = options.controller.options.learnerCollection; this.listenTo(this.learnerCollection, 'sync', this.updateUrl); Marionette.AppRouter.prototype.initialize.call(this, options); }, // Called on LearnerCollection update. Converts the state of the collection (including any filters, searchers, // sorts, or page numbers) into a url and then navigates the router to that url. updateUrl: function () { this.navigate(this.learnerCollection.getQueryString(), {replace: true}); }, }); return LearnersRouter; }); ","define(function (require) { 'use strict'; var Marionette = require('marionette'), LearnersRouter; LearnersRouter = Marionette.AppRouter.extend({ // Routes intended to show a page in the app should map to method names // beginning with ""show"", e.g. 'showLearnerRosterPage'. appRoutes: { '(/)(?*queryString)': 'showLearnerRosterPage', ':username(/)(?*queryString)': 'showLearnerDetailPage', '*notFound': 'showNotFoundPage' }, onRoute: function (routeName) { if (routeName.indexOf('show') === 0) { this.options.controller.triggerMethod('showPage'); } }, initialize: function (options) { this.options = options || {}; this.learnerCollection = options.controller.options.learnerCollection; this.listenTo(this.learnerCollection, 'sync', this.updateUrl); Marionette.AppRouter.prototype.initialize.call(this, options); }, // Called on LearnerCollection update. Converts the state of the collection (including any filters, searchers, // sorts, or page numbers) into a url and then navigates the router to that url. updateUrl: function () { this.navigate(this.learnerCollection.getQueryString()); }, }); return LearnersRouter; }); " Add a few base attributes,"""""""Base classes that are extended by low level AMQP frames and higher level AMQP classes and methods. """""" class AMQPObject(object): """"""Base object that is extended by AMQP low level frames and AMQP classes and methods. """""" NAME = 'AMQPObject' INDEX = None def __repr__(self): items = list() for key, value in self.__dict__.iteritems(): if getattr(self.__class__, key, None) != value: items.append('%s=%s' % (key, value)) if not items: return ""<%s>"" % self.NAME return ""<%s(%s)>"" % (self.NAME, items) class Class(AMQPObject): """"""Is extended by AMQP classes"""""" NAME = 'Unextended Class' class Method(AMQPObject): """"""Is extended by AMQP methods"""""" NAME = 'Unextended Method' synchronous = False def _set_content(self, properties, body): """"""If the method is a content frame, set the properties and body to be carried as attributes of the class. :param pika.frame.Properties properties: AMQP Basic Properties :param str|unicode body: The message body """""" self._properties = properties self._body = body def get_properties(self): """"""Return the properties if they are set. :rtype: pika.frame.Properties """""" return self._properties def get_body(self): """"""Return the message body if it is set. :rtype: str|unicode """""" return self._body class Properties(AMQPObject): """"""Class to encompass message properties (AMQP Basic.Properties)"""""" NAME = 'Unextended Properties' ","""""""Base classes that are extended by low level AMQP frames and higher level AMQP classes and methods. """""" class AMQPObject(object): """"""Base object that is extended by AMQP low level frames and AMQP classes and methods. """""" NAME = 'AMQPObject' def __repr__(self): items = list() for key, value in self.__dict__.iteritems(): if getattr(self.__class__, key, None) != value: items.append('%s=%s' % (key, value)) if not items: return ""<%s>"" % self.NAME return ""<%s(%s)>"" % (self.NAME, items) class Class(AMQPObject): """"""Is extended by AMQP classes"""""" NAME = 'Unextended Class' class Method(AMQPObject): """"""Is extended by AMQP methods"""""" NAME = 'Unextended Method' def _set_content(self, properties, body): """"""If the method is a content frame, set the properties and body to be carried as attributes of the class. :param pika.frame.Properties properties: AMQP Basic Properties :param str|unicode body: The message body """""" self._properties = properties self._body = body def get_properties(self): """"""Return the properties if they are set. :rtype: pika.frame.Properties """""" return self._properties def get_body(self): """"""Return the message body if it is set. :rtype: str|unicode """""" return self._body class Properties(AMQPObject): """"""Class to encompass message properties (AMQP Basic.Properties)"""""" NAME = 'Unextended Properties' " Modify an importer skip minversion,"# encoding: utf-8 """""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """""" from __future__ import print_function, unicode_literals import pytest from pytablewriter import set_log_level, set_logger logbook = pytest.importorskip(""logbook"", minversion=""0.12.3"") import logbook # isort:skip class Test_set_logger(object): @pytest.mark.parametrize([""value""], [[True], [False]]) def test_smoke(self, value): set_logger(value) class Test_set_log_level(object): @pytest.mark.parametrize( [""value""], [ [logbook.CRITICAL], [logbook.ERROR], [logbook.WARNING], [logbook.NOTICE], [logbook.INFO], [logbook.DEBUG], [logbook.TRACE], [logbook.NOTSET], ], ) def test_smoke(self, value): set_log_level(value) @pytest.mark.parametrize( [""value"", ""expected""], [[None, LookupError], [""unexpected"", LookupError]] ) def test_exception(self, value, expected): with pytest.raises(expected): set_log_level(value) ","# encoding: utf-8 """""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """""" from __future__ import print_function, unicode_literals import pytest from pytablewriter import set_log_level, set_logger logbook = pytest.importorskip(""logbook"", minversion=""1.1.0"") import logbook # isort:skip class Test_set_logger(object): @pytest.mark.parametrize([""value""], [[True], [False]]) def test_smoke(self, value): set_logger(value) class Test_set_log_level(object): @pytest.mark.parametrize( [""value""], [ [logbook.CRITICAL], [logbook.ERROR], [logbook.WARNING], [logbook.NOTICE], [logbook.INFO], [logbook.DEBUG], [logbook.TRACE], [logbook.NOTSET], ], ) def test_smoke(self, value): set_log_level(value) @pytest.mark.parametrize( [""value"", ""expected""], [[None, LookupError], [""unexpected"", LookupError]] ) def test_exception(self, value, expected): with pytest.raises(expected): set_log_level(value) " Save parameter in init function,"var fs = require('fs') var documents = {} module.exports = { init: (config, callback) => { var directories = fs.readdirSync('.') if (directories.indexOf(config.directory) === -1) { fs.mkdirSync(config.directory) config.documents.forEach(document => { fs.writeFileSync(`${config.directory}/${document}.db`, '{}') documents[document] = {} }) return true } config.documents.forEach(document => { if (!fs.existsSync(`${config.directory}/${document}.db`)) { fs.writeFileSync(`${config.directory}/${document}.db`, '{}') } var file = fs.readFileSync(`${config.directory}/${document}.db`) documents[document] = JSON.parse(file.toString()) }) if (config.save !== false) { var keys = Object.keys(documents) setInterval(() => { keys.forEach((key) => { fs.writeFile(`${config.directory}/${key}.db`, JSON.stringify(documents[key]), (err) => { if (err) console.log(err) }) }) }, config.save) } return true }, get: (document, key) => { return documents[document][key] }, set: (document, key, value) => { documents[document][key] = value return true }, test: () => { // console.log('test') } } ","var fs = require('fs') var documents = {} module.exports = { init: (config, callback) => { var directories = fs.readdirSync('.') if (directories.indexOf(config.directory) === -1) { fs.mkdirSync(config.directory) config.documents.forEach(document => { fs.writeFileSync(`${config.directory}/${document}.db`, '{}') documents[document] = {} }) return true } config.documents.forEach(document => { if (!fs.existsSync(`${config.directory}/${document}.db`)) { fs.writeFileSync(`${config.directory}/${document}.db`, '{}') } var file = fs.readFileSync(`${config.directory}/${document}.db`) documents[document] = JSON.parse(file.toString()) }) var keys = Object.keys(documents) setInterval(() => { keys.forEach((key) => { fs.writeFile(`${config.directory}/${key}.db`, JSON.stringify(documents[key]), (err) => { if (err) console.log(err) }) }) }, 10000) return true }, get: (document, key) => { return documents[document][key] }, set: (document, key, value) => { documents[document][key] = value return true }, test: () => { // console.log('test') } } " Add prompt to guide user toward certificate or sso config.,"const fs = require('fs'); const csv = require(""fast-csv""); const jsforce = require('jsforce'); const sfdc = require(""./salesforce""); const prompt = require('prompt'); var schema = { properties: { tool: { description: 'Enter your tool: Salesforce (C)ertificates or Salesforce (S)SO.', required: true }, } }; function promptUser() { prompt.start(); prompt.get(schema, function (error, result) { if (error) { console.log(error); } if (result) { tool_map = { 'c': 'certificate', 's': 'sso' } selected_tool = tool_map[result.tool.toLowerCase()] if (selected_tool === undefined) { console.log(`Command line input ${result.tool} was unrecognized. Please try again.`) return promptUser(); } else { console.log(`Recognized input, getting ${selected_tool} data.`) return selected_tool; } } }); } function getCSV(fileName, tool) { tool_map = { 'certificate': sfdc.getSalesforceCertificates, 'sso': sfdc.getSalesforceSSO } selected_tool = tool_map[tool]; fs.createReadStream(fileName) .pipe(csv()) .on(""data"", function (data) { username = data[0] password = data[1] selected_tool(username, password) }) .on(""end"", function () { console.log(""done""); }); } function main() { tool = promptUser(); return getCSV('secret.csv', tool) } main();","const fs = require('fs'); const csv = require(""fast-csv""); const jsforce = require('jsforce'); const sfdc = require(""./salesforce""); const prompt = require('prompt'); var schema = { properties: { username: { description: 'Enter your username:', required: true }, password: { description: 'Enter your password:', hidden: true, replace: '*', } } }; function promptUser() { prompt.start(); prompt.get(schema, function (error, result) { if (error) { console.log(error); } if (result) { console.log(""commmand line input recieved:"", result.username, result.password); } }); } function getCSV(fileName) { fs.createReadStream(fileName) .pipe(csv()) .on(""data"", function (data) { username = data[0] password = data[1] //sfdc.getSalesforceCertificates(username, password) sfdc.getSalesforceSSO(username, password) }) .on(""end"", function () { console.log(""done""); }); } function main() { getCSV('secret.csv') } main();" Use simple TestCase in spam filter tests.,"# -*- coding: utf-8 -*- from __future__ import unicode_literals """""" Unit tests for spam filters. """""" import unittest from django.conf import settings try: import honeypot except ImportError: honeypot = None from envelope.spam_filters import check_honeypot # mocking form and request, no need to use the real things here class FakeForm(object): pass class FakeRequest(object): def __init__(self): self.method = 'POST' self.POST = {} class CheckHoneypotTestCase(unittest.TestCase): """""" Unit tests for ``check_honeypot`` spam filter. """""" def setUp(self): self.form = FakeForm() self.request = FakeRequest() self.honeypot = getattr(settings, 'HONEYPOT_FIELD_NAME', 'email2') def test_empty_honeypot(self): """""" Empty honeypot field is a valid situation. """""" self.request.POST[self.honeypot] = '' self.assertTrue(check_honeypot(self.request, self.form)) @unittest.skipIf(honeypot is None, ""django-honeypot is not installed"") def test_filled_honeypot(self): """""" A value in the honeypot field is an indicator of a bot request. """""" self.request.POST[self.honeypot] = 'Hi, this is a bot' self.assertFalse(check_honeypot(self.request, self.form)) ","# -*- coding: utf-8 -*- from __future__ import unicode_literals """""" Unit tests for spam filters. """""" import unittest from django.conf import settings from django.test import TestCase try: import honeypot except ImportError: honeypot = None from envelope.spam_filters import check_honeypot # mocking form and request, no need to use the real things here class FakeForm(object): pass class FakeRequest(object): def __init__(self): self.method = 'POST' self.POST = {} class CheckHoneypotTestCase(TestCase): """""" Unit tests for ``check_honeypot`` spam filter. """""" def setUp(self): self.form = FakeForm() self.request = FakeRequest() self.honeypot = getattr(settings, 'HONEYPOT_FIELD_NAME', 'email2') def test_empty_honeypot(self): """""" Empty honeypot field is a valid situation. """""" self.request.POST[self.honeypot] = '' self.assertTrue(check_honeypot(self.request, self.form)) @unittest.skipIf(honeypot is None, ""django-honeypot is not installed"") def test_filled_honeypot(self): """""" A value in the honeypot field is an indicator of a bot request. """""" self.request.POST[self.honeypot] = 'Hi, this is a bot' self.assertFalse(check_honeypot(self.request, self.form)) " Make ImageUploadExtensionValidator work with django 1.7 migrations,"from django.conf import settings from django.core.validators import ValidationError # A list of allowable thumbnail file extensions. ALLOWABLE_THUMBNAIL_EXTENSIONS = getattr( settings, 'ALLOWABLE_THUMBNAIL_EXTENSIONS', ['png', 'jpg', 'jpeg', 'gif']) class ImageUploadExtensionValidator(object): """""" Perform some basic image uploading extension validation. """""" compare = lambda self, a, b: a is not b clean = lambda self, x: x def deconstruct(self): path = ""athumb.validators.ImageUploadExtensionValidator"" args = [] kwargs = {} return (path, args, kwargs) def __call__(self, value): filename = value.name filename_split = filename.split('.') extension = filename_split[-1] # Decided to require file extensions. if len(filename_split) < 2: raise ValidationError( ""Your file lacks an extension such as .jpg or .png. "" ""Please re-name it on your computer and re-upload it."", code='no_extension' ) # Restrict allowable extensions. if extension.lower() not in ALLOWABLE_THUMBNAIL_EXTENSIONS: # Format for your viewing pleasure. allowable_str = ' '.join(ALLOWABLE_THUMBNAIL_EXTENSIONS) raise ValidationError( ""Your file is not one of the allowable types: %s"" % allowable_str, code='extension_not_allowed' )","from django.conf import settings from django.core.validators import ValidationError # A list of allowable thumbnail file extensions. ALLOWABLE_THUMBNAIL_EXTENSIONS = getattr( settings, 'ALLOWABLE_THUMBNAIL_EXTENSIONS', ['png', 'jpg', 'jpeg', 'gif']) class ImageUploadExtensionValidator(object): """""" Perform some basic image uploading extension validation. """""" compare = lambda self, a, b: a is not b clean = lambda self, x: x def __call__(self, value): filename = value.name filename_split = filename.split('.') extension = filename_split[-1] # Decided to require file extensions. if len(filename_split) < 2: raise ValidationError( ""Your file lacks an extension such as .jpg or .png. "" ""Please re-name it on your computer and re-upload it."", code='no_extension' ) # Restrict allowable extensions. if extension.lower() not in ALLOWABLE_THUMBNAIL_EXTENSIONS: # Format for your viewing pleasure. allowable_str = ' '.join(ALLOWABLE_THUMBNAIL_EXTENSIONS) raise ValidationError( ""Your file is not one of the allowable types: %s"" % allowable_str, code='extension_not_allowed' )" Fix CI for php 5.3,"<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Form\Annotation; /** * ComposedObject annotation * * Use this annotation to specify another object with annotations to parse * which you can then add to the form as a fieldset. The value should be a * string indicating the fully qualified class name of the composed object * to use. * * @Annotation */ class ComposedObject extends AbstractArrayOrStringAnnotation { /** * Retrieve the composed object classname * * @return null|string */ public function getComposedObject() { if (is_array($this->value)) { return $this->value['target_object']; } return $this->value; } /** * Is this composed object a collection or not * * @return bool */ public function isCollection() { return is_array($this->value) && isset($this->value['is_collection']) && $this->value['is_collection']; } /** * Retrieve the options for the composed object * * @return array */ public function getOptions() { return is_array($this->value) && isset($this->value['options']) ? $this->value['options'] : array(); } } ","<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Form\Annotation; /** * ComposedObject annotation * * Use this annotation to specify another object with annotations to parse * which you can then add to the form as a fieldset. The value should be a * string indicating the fully qualified class name of the composed object * to use. * * @Annotation */ class ComposedObject extends AbstractArrayOrStringAnnotation { /** * Retrieve the composed object classname * * @return null|string */ public function getComposedObject() { if (is_array($this->value)) { return $this->value['target_object']; } return $this->value; } /** * Is this composed object a collection or not * * @return bool */ public function isCollection() { return is_array($this->value) && isset($this->value['is_collection']) && $this->value['is_collection']; } /** * Retrieve the options for the composed object * * @return array */ public function getOptions() { return isset($this->value['options']) ? $this->value['options'] : array(); } } " Use `!util/isLikeNumber(key)` instead of `key.match(/\D/)`,"""use strict""; var Base = require('../base') var isLikeNumber =require('../util').isLikeNumber /** * @function raw converts the Base object into a normal javascript wObject, removing internal properties. * It also converts nested objects and rebuilds arrays from objects with nothing but integer keys. * @memberOf Base# * @param {object} [options] * @param {boolean} options.fnToString * @return {object} * @example * var a = new Base({ 'a': 123 }) * console.log(a.raw()) //it logs { 'a': 123 } */ exports.$define = { raw:function( options ) { var exclude if (options) { exclude = options.exclude } function raw ( obj ) { var newObj = {} var val = obj._$val if (val !== void 0) { newObj = val } else { var isArrayLike = true var asArray = [] var newVal for( var key in obj ) { if ( key[0] !== '_' && key !== '$key' && key !== '$val' && (!exclude||!exclude(key, obj)) ) { if (!isLikeNumber(key)) { isArrayLike = false } newVal = raw(obj[key]) newObj[key] = newVal if (isArrayLike) { asArray[key] = newVal } } } if (isArrayLike) { newObj = asArray } } return newObj } return raw(this) } } ","""use strict""; var Base = require('../base') /** * @function raw converts the Base object into a normal javascript wObject, removing internal properties. * It also converts nested objects and rebuilds arrays from objects with nothing but integer keys. * @memberOf Base# * @param {object} [options] * @param {boolean} options.fnToString * @return {object} * @example * var a = new Base({ 'a': 123 }) * console.log(a.raw()) //it logs { 'a': 123 } */ exports.$define = { raw:function( options ) { var exclude if (options) { exclude = options.exclude } function raw ( obj ) { var newObj = {} var val = obj._$val if (val !== void 0) { newObj = val } else { var isArrayLike = true var asArray = [] var newVal for( var key in obj ) { if ( key[0] !== '_' && key !== '$key' && key !== '$val' && (!exclude||!exclude(key, obj)) ) { if (key.match(/\D/)) { isArrayLike = false } newVal = raw(obj[key]) newObj[key] = newVal if (isArrayLike) { asArray[key] = newVal } } } if (isArrayLike) { newObj = asArray } } return newObj } return raw(this) } }" Add wrappedApp property to cache wrapped app closure,"<?php namespace Pux; use ReflectionClass; use Closure; class Compositor { protected $stacks = array(); protected $app; protected $mapApp; private $wrappedApp; public function __construct(callable $app = null) { $this->app = $app; } public function enable($appClass) { if ($appClass instanceof Closure) { $this->stacks[] = $appClass; } else { $args = func_get_args(); array_shift($args); $this->stacks[] = [$appClass, $args]; } return $this; } public function app($app) { $this->app = $app; return $this; } public function wrap() { $app = $this->app; for ($i = count($this->stacks) - 1; $i > 0; $i--) { $stack = $this->stacks[$i]; // middleware closure if ($stack instanceof Closure) { $app = $stack($app); } else { list($appClass, $args) = $stack; $refClass = new ReflectionClass($appClass); array_unshift($args, $app); $app = $refClass->newInstanceArgs($args); } } return $app; } public function __invoke(array $environment, array $response) { if ($app = $this->wrappedApp) { return $app($environment, $response); } $this->wrappedApp = $app = $this->wrap(); return $app($environment, $response); } } ","<?php namespace Pux; use ReflectionClass; use Closure; class Compositor { protected $stacks = array(); protected $app; protected $mapApp; public function __construct(callable $app = null) { $this->app = $app; } public function enable($appClass) { if ($appClass instanceof Closure) { $this->stacks[] = $appClass; } else { $args = func_get_args(); array_shift($args); $this->stacks[] = [$appClass, $args]; } return $this; } public function app($app) { $this->app = $app; return $this; } public function wrap() { $app = $this->app; for ($i = count($this->stacks) - 1; $i > 0; $i--) { $stack = $this->stacks[$i]; // middleware closure if ($stack instanceof Closure) { $app = $stack($app); } else { list($appClass, $args) = $stack; $refClass = new ReflectionClass($appClass); array_unshift($args, $app); $app = $refClass->newInstanceArgs($args); } } return $app; } public function __invoke(array $environment, array $response) { $app = $this->wrap(); return $app($environment, $response); } } " "Remove kwargs[""input_controller""] from the Game plugin template","from serpent.game import Game from .api.api import MyGameAPI from serpent.utilities import Singleton from serpent.game_launchers.web_browser_game_launcher import WebBrowser class SerpentGame(Game, metaclass=Singleton): def __init__(self, **kwargs): kwargs[""platform""] = ""PLATFORM"" kwargs[""window_name""] = ""WINDOW_NAME"" kwargs[""app_id""] = ""APP_ID"" kwargs[""app_args""] = None kwargs[""executable_path""] = ""EXECUTABLE_PATH"" kwargs[""url""] = ""URL"" kwargs[""browser""] = WebBrowser.DEFAULT super().__init__(**kwargs) self.api_class = MyGameAPI self.api_instance = None @property def screen_regions(self): regions = { ""SAMPLE_REGION"": (0, 0, 0, 0) } return regions @property def ocr_presets(self): presets = { ""SAMPLE_PRESET"": { ""extract"": { ""gradient_size"": 1, ""closing_size"": 1 }, ""perform"": { ""scale"": 10, ""order"": 1, ""horizontal_closing"": 1, ""vertical_closing"": 1 } } } return presets ","from serpent.game import Game from .api.api import MyGameAPI from serpent.utilities import Singleton from serpent.input_controller import InputControllers from serpent.game_launchers.web_browser_game_launcher import WebBrowser class SerpentGame(Game, metaclass=Singleton): def __init__(self, **kwargs): kwargs[""platform""] = ""PLATFORM"" kwargs[""input_controller""] = InputControllers.PYAUTOGUI kwargs[""window_name""] = ""WINDOW_NAME"" kwargs[""app_id""] = ""APP_ID"" kwargs[""app_args""] = None kwargs[""executable_path""] = ""EXECUTABLE_PATH"" kwargs[""url""] = ""URL"" kwargs[""browser""] = WebBrowser.DEFAULT super().__init__(**kwargs) self.api_class = MyGameAPI self.api_instance = None @property def screen_regions(self): regions = { ""SAMPLE_REGION"": (0, 0, 0, 0) } return regions @property def ocr_presets(self): presets = { ""SAMPLE_PRESET"": { ""extract"": { ""gradient_size"": 1, ""closing_size"": 1 }, ""perform"": { ""scale"": 10, ""order"": 1, ""horizontal_closing"": 1, ""vertical_closing"": 1 } } } return presets " "Revert ""updated required sentrylogs version"" This reverts commit 86f6fc2fb5a9e3c89088ddc135f66704cff36018.","import os from setuptools import setup, find_packages def read_file(filename): """"""Read a file into a string"""""" path = os.path.abspath(os.path.dirname(__file__)) filepath = os.path.join(path, filename) try: return open(filepath).read() except IOError: return '' setup( name='django-sentrylogs', version='1.0.1', author='<Include Your Name Here>', author_email='<Include Your Email Here>', packages=find_packages(), include_package_data=True, url='https://github.com/pulilab/django-sentrylogs', license='MIT', description='A django command to run sentrylogs easily', classifiers=[ 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Framework :: Django', 'Development Status :: 4 - Beta', 'Operating System :: OS Independent', ], long_description=read_file('README.rst'), test_suite=""runtests.runtests"", zip_safe=False, install_requires=[ ""Django >= 1.4"", ""SentryLogs >= 0.1.0"", ""raven >= 5.0.0"", ] ) ","import os from setuptools import setup, find_packages def read_file(filename): """"""Read a file into a string"""""" path = os.path.abspath(os.path.dirname(__file__)) filepath = os.path.join(path, filename) try: return open(filepath).read() except IOError: return '' setup( name='django-sentrylogs', version='2.2.0', author='<Include Your Name Here>', author_email='<Include Your Email Here>', packages=find_packages(), include_package_data=True, url='https://github.com/pulilab/django-sentrylogs', license='MIT', description='A django command to run sentrylogs easily', classifiers=[ 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Framework :: Django', 'Development Status :: 4 - Beta', 'Operating System :: OS Independent', ], long_description=read_file('README.rst'), test_suite=""runtests.runtests"", zip_safe=False, install_requires=[ ""Django >= 1.4"", ""SentryLogs >= 2.2.0"", ""raven >= 5.0.0"", ] ) " Update coverage values to match current,"'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'], options: { jshintrc: '.jshintrc', } }, mochacli: { all: ['test/**/*.js'], options: { reporter: 'spec', ui: 'tdd' } }, 'mocha_istanbul': { coveralls: { src: [ 'test/lib', 'test/lib/utils' ], options: { coverage: true, legend: true, check: { lines: 99, statements: 99 }, root: './lib', reportFormats: ['lcov'] } } } }) grunt.event.on('coverage', function(lcov, done){ require('coveralls').handleInput(lcov, function(error) { if (error) { console.log(error) return done(error) } done() }) }) // Load the plugins grunt.loadNpmTasks('grunt-contrib-jshint') grunt.loadNpmTasks('grunt-mocha-cli') grunt.loadNpmTasks('grunt-mocha-istanbul') // Configure tasks grunt.registerTask('coveralls', ['mocha_istanbul:coveralls']) grunt.registerTask('default', ['test']) grunt.registerTask('test', ['mochacli', 'jshint', 'coveralls']) } ","'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'], options: { jshintrc: '.jshintrc', } }, mochacli: { all: ['test/**/*.js'], options: { reporter: 'spec', ui: 'tdd' } }, 'mocha_istanbul': { coveralls: { src: [ 'test/lib', 'test/lib/utils' ], options: { coverage: true, legend: true, check: { lines: 100, statements: 99 }, root: './lib', reportFormats: ['lcov'] } } } }) grunt.event.on('coverage', function(lcov, done){ require('coveralls').handleInput(lcov, function(error) { if (error) { console.log(error) return done(error) } done() }) }) // Load the plugins grunt.loadNpmTasks('grunt-contrib-jshint') grunt.loadNpmTasks('grunt-mocha-cli') grunt.loadNpmTasks('grunt-mocha-istanbul') // Configure tasks grunt.registerTask('coveralls', ['mocha_istanbul:coveralls']) grunt.registerTask('default', ['test']) grunt.registerTask('test', ['mochacli', 'jshint', 'coveralls']) } " Add test for custom id in response,"import json import unittest from alerta.app import create_app, db class ApiResponseTestCase(unittest.TestCase): def setUp(self): test_config = { 'TESTING': True, 'BASE_URL': 'https://api.alerta.dev:9898/_' } self.app = create_app(test_config) self.client = self.app.test_client() self.prod_alert = { 'id': 'custom-alert-id', 'resource': 'node404', 'event': 'node_down', 'environment': 'Production', 'severity': 'major', 'correlate': ['node_down', 'node_marginal', 'node_up'], 'service': ['Core', 'Web', 'Network'], 'group': 'Network', 'tags': ['level=20', 'switch:off'] } def tearDown(self): db.destroy() def test_response_custom_id(self): # create alert response = self.client.post('/alert', json=self.prod_alert) self.assertEqual(response.status_code, 201) data = json.loads(response.data.decode('utf-8')) self.assertEqual(data['alert']['id'], 'custom-alert-id') self.assertEqual(data['id'], 'custom-alert-id') self.assertEqual(data['status'], 'ok') def test_response_href(self): # create alert response = self.client.post('/alert', json=self.prod_alert) self.assertEqual(response.status_code, 201) data = json.loads(response.data.decode('utf-8')) self.assertEqual(data['alert']['href'], 'https://api.alerta.dev:9898/_/alert/custom-alert-id') self.assertEqual(data['status'], 'ok') ","import json import unittest from alerta.app import create_app, db class ApiResponseTestCase(unittest.TestCase): def setUp(self): test_config = { 'TESTING': True, 'BASE_URL': 'https://api.alerta.dev:9898/_' } self.app = create_app(test_config) self.client = self.app.test_client() self.prod_alert = { 'id': 'custom-alert-id', 'resource': 'node404', 'event': 'node_down', 'environment': 'Production', 'severity': 'major', 'correlate': ['node_down', 'node_marginal', 'node_up'], 'service': ['Core', 'Web', 'Network'], 'group': 'Network', 'tags': ['level=20', 'switch:off'] } def tearDown(self): db.destroy() def test_response_href(self): # create alert response = self.client.post('/alert', json=self.prod_alert) self.assertEqual(response.status_code, 201) data = json.loads(response.data.decode('utf-8')) self.assertEqual(data['alert']['href'], 'https://api.alerta.dev:9898/_/alert/custom-alert-id') " Make links work in ProductCarousel,"/** * * ProductCarousel.js * */ import React from 'react'; import 'style!css!./ProductCarousel.css'; class ProductCarousel extends React.Component { constructor(props) { super(props); this.state = { selectedItem: 0, }; this.updateImage = this.updateImage.bind(this); } updateImage(newIndex) { this.setState({ selectedItem: newIndex, }); } render() { const { selectedItem } = this.state; return ( <div style={{ textAlign: 'center' }}> <div className=""carousel--selectedImage""> {this.props.children[selectedItem]} </div> <div className=""carousel--thumbnails""> {this.props.children.map((child, index) => ( <a key={index} className=""carousel--thumbnail"" href={`#carousel-${index}`} onClick={() => this.updateImage(index)} > {child} </a> ))} </div> </div> ); } } ProductCarousel.propTypes = { children: React.PropTypes.node, }; export default ProductCarousel; ","/** * * ProductCarousel.js * */ import React from 'react'; import 'style!css!./ProductCarousel.css'; class ProductCarousel extends React.Component { constructor(props) { super(props); this.state = { selectedItem: 0, }; this.updateImage = this.updateImage.bind(this); } updateImage(newIndex) { this.setState({ selectedItem: newIndex, }); } /* eslint-disable jsx-a11y/href-no-hash */ /* Ideally we wouldn't need to disable this, but our internal component is not ready for release yet */ render() { const { selectedItem } = this.state; return ( <div style={{ textAlign: 'center' }}> <div className=""carousel--selectedImage""> {this.props.children[selectedItem]} </div> <div className=""carousel--thumbnails""> {this.props.children.map((child, index) => ( <a key={index} className=""carousel--thumbnail"" href=""#"" onClick={() => this.updateImage(index)} > {child} </a> ))} </div> </div> ); } } ProductCarousel.propTypes = { children: React.PropTypes.node, }; export default ProductCarousel; " Fix appstore json parsing process.,"import asyncio import json from helper.filter import remove_emoji from helper.lang import find_out_language from lxml import etree from datetime import datetime from helper.http_client import request from speaker.appstore import NAMESPACE, REGIONS @asyncio.coroutine def latest_reviews(code, region, buffer_size): url = ""https://itunes.apple.com/{}/rss/customerreviews/id={}/sortBy=mostRecent/json"".format(region, code) body = yield from request(url) reviews = list() feed = json.loads(body.decode('utf-8')).get('feed') if feed is None: return reviews if region == 'sg': entries = feed.get('entry') else: entries = feed.get('feed').get('entry') if entries is None: return reviews for entry in entries: try: if entry.get('author') is None: continue title = entry['title']['label'] content = entry['content']['label'] reviews.append({ 'id': entry['id']['label'], 'title': title, 'content': content, 'name': entry['author']['name']['label'], 'score': score(entry['im:rating']['label']), 'version': entry['im:version']['label'], 'lang': find_out_language(REGIONS[region]['langs'], content, title), 'region': region }) except IndexError: pass return reviews def score(rating): return int(rating) * 20 ","import asyncio import json from helper.filter import remove_emoji from helper.lang import find_out_language from lxml import etree from datetime import datetime from helper.http_client import request from speaker.appstore import NAMESPACE, REGIONS @asyncio.coroutine def latest_reviews(code, region, buffer_size): url = ""https://itunes.apple.com/{}/rss/customerreviews/id={}/sortBy=mostRecent/json"".format(region, code) body = yield from request(url) reviews = list() feed = json.loads(body.decode('utf-8')).get('feed') if feed is None: return reviews entries = feed.get('entry') if entries is None: return reviews for entry in entries: try: if entry.get('author') is None: continue title = entry['title']['label'] content = entry['content']['label'] reviews.append({ 'id': entry['id']['label'], 'title': title, 'content': content, 'name': entry['author']['name']['label'], 'score': score(entry['im:rating']['label']), 'version': entry['im:version']['label'], 'lang': find_out_language(REGIONS[region]['langs'], content, title), 'region': region }) except IndexError: pass return reviews def score(rating): return int(rating) * 20 " Use constant instead of magic number for response status code,"<?php declare(strict_types=1); /* * This file is part of the qandidate/symfony-json-request-transformer package. * * (c) Qandidate.com <opensource@qandidate.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Qandidate\Common\Symfony\HttpKernel\EventListener; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\RequestEvent; /** * Transforms the body of a json request to POST parameters. */ class JsonRequestTransformerListener { public function onKernelRequest(RequestEvent $event): void { $request = $event->getRequest(); if (!$this->isJsonRequest($request)) { return; } $content = $request->getContent(); if (empty($content)) { return; } if (!$this->transformJsonBody($request)) { $response = Response::create('Unable to parse request.', Response::HTTP_BAD_REQUEST); $event->setResponse($response); } } private function isJsonRequest(Request $request): bool { return 'json' === $request->getContentType(); } private function transformJsonBody(Request $request): bool { $data = json_decode((string) $request->getContent(), true); if (JSON_ERROR_NONE !== json_last_error()) { return false; } if (null === $data) { return true; } $request->request->replace($data); return true; } } ","<?php declare(strict_types=1); /* * This file is part of the qandidate/symfony-json-request-transformer package. * * (c) Qandidate.com <opensource@qandidate.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Qandidate\Common\Symfony\HttpKernel\EventListener; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\RequestEvent; /** * Transforms the body of a json request to POST parameters. */ class JsonRequestTransformerListener { public function onKernelRequest(RequestEvent $event): void { $request = $event->getRequest(); if (!$this->isJsonRequest($request)) { return; } $content = $request->getContent(); if (empty($content)) { return; } if (!$this->transformJsonBody($request)) { $response = Response::create('Unable to parse request.', 400); $event->setResponse($response); } } private function isJsonRequest(Request $request): bool { return 'json' === $request->getContentType(); } private function transformJsonBody(Request $request): bool { $data = json_decode((string) $request->getContent(), true); if (JSON_ERROR_NONE !== json_last_error()) { return false; } if (null === $data) { return true; } $request->request->replace($data); return true; } } " Fix crash when frames are moving in chunks without nearby players.,"package com.rwtema.funkylocomotion.network; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper; import cpw.mods.fml.relauncher.Side; import net.minecraft.server.management.PlayerManager; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import java.util.WeakHashMap; public class FLNetwork { public static SimpleNetworkWrapper net; public static void init() { net = new SimpleNetworkWrapper(""FLoco""); net.registerMessage(MessageClearTile.Handler.class, MessageClearTile.class, 0, Side.SERVER); net.registerMessage(MessageClearTile.Handler.class, MessageClearTile.class, 0, Side.CLIENT); } private static WeakHashMap<World, PlayerManager> cache = new WeakHashMap<World, PlayerManager>(); public static void sendToAllWatchingChunk(World world, int x, int y, int z, IMessage message) { if (!cache.containsKey(world)) { if (!(world instanceof WorldServer)) { cache.put(world, null); } else cache.put(world, ((WorldServer) world).getPlayerManager()); } PlayerManager playerManager = cache.get(world); if (playerManager == null) return; PlayerManager.PlayerInstance watcher = playerManager.getOrCreateChunkWatcher(x >> 4, z >> 4, false); if (watcher != null) watcher.sendToAllPlayersWatchingChunk(net.getPacketFrom(message)); } } ","package com.rwtema.funkylocomotion.network; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper; import cpw.mods.fml.relauncher.Side; import net.minecraft.server.management.PlayerManager; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import java.util.WeakHashMap; public class FLNetwork { public static SimpleNetworkWrapper net; public static void init() { net = new SimpleNetworkWrapper(""FLoco""); net.registerMessage(MessageClearTile.Handler.class, MessageClearTile.class, 0, Side.SERVER); net.registerMessage(MessageClearTile.Handler.class, MessageClearTile.class, 0, Side.CLIENT); } private static WeakHashMap<World, PlayerManager> cache = new WeakHashMap<World, PlayerManager>(); public static void sendToAllWatchingChunk(World world, int x, int y, int z, IMessage message) { if (!cache.containsKey(world)) { if (!(world instanceof WorldServer)) { cache.put(world, null); } else cache.put(world, ((WorldServer) world).getPlayerManager()); } PlayerManager playerManager = cache.get(world); if (playerManager == null) return; PlayerManager.PlayerInstance watcher = playerManager.getOrCreateChunkWatcher(x >> 4, z >> 4, false); watcher.sendToAllPlayersWatchingChunk(net.getPacketFrom(message)); } } " Fix call for older PHP.,"<?php namespace Illuminate\Routing; use Exception; use Illuminate\Http\Request; use Illuminate\Contracts\Debug\ExceptionHandler; use Illuminate\Pipeline\Pipeline as BasePipeline; use Symfony\Component\Debug\Exception\FatalThrowableError; /** * This extended pipeline catches any exceptions that occur during each slice. * * The exceptions are converted to HTTP responses for proper middleware handling. */ class Pipeline extends BasePipeline { /** * Get a Closure that represents a slice of the application onion. * * @return \Closure */ protected function getSlice() { return function ($stack, $pipe) { return function ($passable) use ($stack, $pipe) { try { $slice = parent::getSlice(); return call_user_func($slice($stack, $pipe), $passable); } catch (Exception $e) { return $this->handleException($passable, $e); } catch (Throwable $e) { return $this->handleException($passable, new FatalThrowableError($e)); } }; }; } /** * Handle the given exception. * * @param \Exception $e * @return mixed */ protected function handleException($passable, Exception $e) { if (! $this->container->bound(ExceptionHandler::class) || ! $passable instanceof Request) { throw $e; } $handler = $this->container->make(ExceptionHandler::class); $handler->report($e); return $handler->render($passable, $e); } } ","<?php namespace Illuminate\Routing; use Exception; use Illuminate\Http\Request; use Illuminate\Contracts\Debug\ExceptionHandler; use Illuminate\Pipeline\Pipeline as BasePipeline; use Symfony\Component\Debug\Exception\FatalThrowableError; /** * This extended pipeline catches any exceptions that occur during each slice. * * The exceptions are converted to HTTP responses for proper middleware handling. */ class Pipeline extends BasePipeline { /** * Get a Closure that represents a slice of the application onion. * * @return \Closure */ protected function getSlice() { return function ($stack, $pipe) { return function ($passable) use ($stack, $pipe) { try { return call_user_func(parent::getSlice()($stack, $pipe), $passable); } catch (Exception $e) { return $this->handleException($passable, $e); } catch (Throwable $e) { return $this->handleException($passable, new FatalThrowableError($e)); } }; }; } /** * Handle the given exception. * * @param \Exception $e * @return mixed */ protected function handleException($passable, Exception $e) { if (! $this->container->bound(ExceptionHandler::class) || ! $passable instanceof Request) { throw $e; } $handler = $this->container->make(ExceptionHandler::class); $handler->report($e); return $handler->render($passable, $e); } } " Make tests compatible with python 2.5 and 2.6.,"import unittest from flask import Flask from flaskext.seasurf import SeaSurf class SeaSurfTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.debug = True app.secret_key = 'hunter2' self.app = app csrf = SeaSurf(app) csrf._csrf_disable = False self.csrf = csrf @csrf.exempt @app.route('/foo', methods=['POST']) def foo(): return 'bar' @app.route('/bar', methods=['POST']) def bar(): return 'foo' def test_generate_token(self): self.assertIsNotNone(self.csrf._generate_token()) def test_unique_generation(self): token_a = self.csrf._generate_token() token_b = self.csrf._generate_token() self.assertNotEqual(token_a, token_b) def test_token_is_string(self): token = self.csrf._generate_token() self.assertEqual(type(token), str) def test_exempt_view(self): rv = self.app.test_client().post('/foo') self.assertIn('bar', rv.data) def test_token_validation(self): # should produce a logger warning rv = self.app.test_client().post('/bar') self.assertIn('403 Forbidden', rv.data) # Methods for backwards compatibility with python 2.5 & 2.6 def assertIn(self, value, container): self.assertTrue(value in container) def assertIsNotNone(self, value): self.assertNotEqual(value, None) if __name__ == '__main__': unittest.main() ","import unittest from flask import Flask from flaskext.seasurf import SeaSurf class SeaSurfTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.debug = True app.secret_key = 'hunter2' self.app = app csrf = SeaSurf(app) csrf._csrf_disable = False self.csrf = csrf @csrf.exempt @app.route('/foo', methods=['POST']) def foo(): return 'bar' @app.route('/bar', methods=['POST']) def bar(): return 'foo' def test_generate_token(self): self.assertIsNotNone(self.csrf._generate_token()) def test_unique_generation(self): token_a = self.csrf._generate_token() token_b = self.csrf._generate_token() self.assertNotEqual(token_a, token_b) def test_token_is_string(self): token = self.csrf._generate_token() self.assertEqual(type(token), str) def test_exempt_view(self): rv = self.app.test_client().post('/foo') self.assertIn('bar', rv.data) def test_token_validation(self): # should produce a logger warning rv = self.app.test_client().post('/bar') self.assertIn('403 Forbidden', rv.data) if __name__ == '__main__': unittest.main() " Remove unused import and add type converter.,"package org.csveed.bean; import org.csveed.bean.conversion.Converter; import org.csveed.test.converters.BeanSimpleConverter; import org.csveed.test.model.BeanSimple; import org.csveed.test.model.BeanVariousNotAnnotated; import org.junit.Test; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import static junit.framework.Assert.*; public class BeanPropertyTest { @Test public void construct() throws IntrospectionException { BeanProperty property = new BeanProperty(); Converter<BeanSimple> converter = new BeanSimpleConverter(); PropertyDescriptor propertyDescriptor = new PropertyDescriptor(""name"", BeanSimple.class); property.setConverter(converter); property.setColumnIndex(3); property.setColumnName(""name""); property.setPropertyDescriptor(propertyDescriptor); property.setRequired(true); assertEquals(converter, property.getConverter()); assertEquals(3, property.getColumnIndex()); assertEquals(""name"", property.getColumnName()); assertEquals(propertyDescriptor, property.getPropertyDescriptor()); assertTrue(property.isRequired()); } @Test public void numberClass() throws IntrospectionException { BeanProperty property = new BeanProperty(); property.setPropertyDescriptor(new PropertyDescriptor(""number"", BeanVariousNotAnnotated.class)); assertNotNull(property.getNumberClass()); } @Test public void notANumberClass() throws IntrospectionException { BeanProperty property = new BeanProperty(); property.setPropertyDescriptor(new PropertyDescriptor(""name"", BeanSimple.class)); assertNull(property.getNumberClass()); } }","package org.csveed.bean; import org.csveed.bean.conversion.Converter; import org.csveed.test.converters.BeanSimpleConverter; import org.csveed.test.model.BeanSimple; import org.csveed.test.model.BeanVariousNotAnnotated; import org.junit.Test; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.math.BigDecimal; import static junit.framework.Assert.*; public class BeanPropertyTest { @Test public void construct() throws IntrospectionException { BeanProperty property = new BeanProperty(); Converter converter = new BeanSimpleConverter(); PropertyDescriptor propertyDescriptor = new PropertyDescriptor(""name"", BeanSimple.class); property.setConverter(converter); property.setColumnIndex(3); property.setColumnName(""name""); property.setPropertyDescriptor(propertyDescriptor); property.setRequired(true); assertEquals(converter, property.getConverter()); assertEquals(3, property.getColumnIndex()); assertEquals(""name"", property.getColumnName()); assertEquals(propertyDescriptor, property.getPropertyDescriptor()); assertTrue(property.isRequired()); } @Test public void numberClass() throws IntrospectionException { BeanProperty property = new BeanProperty(); property.setPropertyDescriptor(new PropertyDescriptor(""number"", BeanVariousNotAnnotated.class)); assertNotNull(property.getNumberClass()); } @Test public void notANumberClass() throws IntrospectionException { BeanProperty property = new BeanProperty(); property.setPropertyDescriptor(new PropertyDescriptor(""name"", BeanSimple.class)); assertNull(property.getNumberClass()); } }" Remove JsHamCrest and JsMockito initialization.,"var JsTestClass = new Class({ Implements: [Events, Options], options: { testCase: null, testMethods: [] }, initialize: function( options ){ this.setOptions( options ); this.testCaseChain = new Chain(); this.tracer; this.setUp(); }, afterAllTests: function(){ //Abstract method, should be overwritten by test the test class }, afterEachTest: function(){ //Abstract method, should be overwritten by test the test class }, beforeAllTests: function(){ //Abstract method, should be overwritten by test the test class }, beforeEachTest: function(){ //Abstract method, should be overwritten by test the test class }, //Properties getTestMethods: function() { return this.options.testMethods; }, isJsTestClass: function() { return true; }, //Protected, private helper methods debug : function( arguments ){ this.tracer.debug( arguments ); }.protect(), inform : function( arguments ){ this.tracer.inform( arguments ); }.protect(), setUp : function(){ this.tracer = top.tracer; }.protect(), testMethodReady: function( error ){ this.fireEvent( 'ready', error ); }.protect(), warn : function( arguments ){ this.tracer.warn( arguments ); }.protect() }); "," JsHamcrest.Integration.JsUnit(); JsMockito.Integration.JsUnit(); var JsTestClass = new Class({ Implements: [Events, Options], options: { testCase: null, testMethods: [] }, initialize: function( options ){ this.setOptions( options ); this.testCaseChain = new Chain(); this.tracer; this.setUp(); }, afterAllTests: function(){ //Abstract method, should be overwritten by test the test class }, afterEachTest: function(){ //Abstract method, should be overwritten by test the test class }, beforeAllTests: function(){ //Abstract method, should be overwritten by test the test class }, beforeEachTest: function(){ //Abstract method, should be overwritten by test the test class }, //Properties getTestMethods: function() { return this.options.testMethods; }, isJsTestClass: function() { return true; }, //Protected, private helper methods debug : function( arguments ){ this.tracer.debug( arguments ); }.protect(), inform : function( arguments ){ this.tracer.inform( arguments ); }.protect(), setUp : function(){ this.tracer = top.tracer; }.protect(), testMethodReady: function( error ){ this.fireEvent( 'ready', error ); }.protect(), warn : function( arguments ){ this.tracer.warn( arguments ); }.protect() }); " [TASK] Include fields should start with no inclusion at all,"<?php namespace Netlogix\JsonApiOrg\Schema\Traits; /* * This file is part of the Netlogix.JsonApiOrg package. * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use TYPO3\Flow\Utility\Arrays; /** * Include fields means naming individual relationship paths hand * having even nested relationships added to the TopLevel object. * * @see http://jsonapi.org/format/#fetching-includes */ trait IncludeFieldsTrait { /** * @var array */ protected $includeFields = array(); /** * @param mixed $includeFields */ public function setIncludeFields($includeFields) { if (is_array($includeFields)) { $includeFields = join(',', $includeFields); } $this->includeFields = array(); if (is_string($includeFields)) { foreach (Arrays::trimExplode(',', $includeFields) as $includeField) { if (!$includeField) { continue; } $this->includeFields[$includeField] = $includeField; } } } /** * @param string $fieldName * @return mixed */ public function isAllowedIncludeField($fieldName) { if (in_array('*', $this->includeFields)) { return true; } else { return in_array($fieldName, $this->includeFields); } } }","<?php namespace Netlogix\JsonApiOrg\Schema\Traits; /* * This file is part of the Netlogix.JsonApiOrg package. * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use TYPO3\Flow\Utility\Arrays; /** * Include fields means naming individual relationship paths hand * having even nested relationships added to the TopLevel object. * * @see http://jsonapi.org/format/#fetching-includes */ trait IncludeFieldsTrait { /** * @var array */ protected $includeFields = array('*'); /** * @param mixed $includeFields */ public function setIncludeFields($includeFields) { if (is_array($includeFields)) { $includeFields = join(',', $includeFields); } $this->includeFields = array(); if (is_string($includeFields)) { foreach (Arrays::trimExplode(',', $includeFields) as $includeField) { if (!$includeField) { continue; } $this->includeFields[$includeField] = $includeField; } } } /** * @param string $fieldName * @return mixed */ public function isAllowedIncludeField($fieldName) { if (in_array('*', $this->includeFields)) { return true; } else { return in_array($fieldName, $this->includeFields); } } }" Add 'lynch' color to logo,"import React, { Component } from 'react' import { Link, IndexLink } from 'react-router' export class Nav extends Component { constructor(props) { super(props) } render() { return ( <nav className=""transparent white-background wrap navbar navbar-default"" role=""navigation""> <div className=""container-fluid""> <div className=""navbar-header""> <button type=""button"" className=""white-background navbar-toggle collapsed"" data-toggle=""collapse"" data-target=""#navigation""> <span className=""sr-only"">Toggle navigation</span> <span className=""icon-bar""></span> <span className=""icon-bar""></span> <span className=""icon-bar""></span> </button> </div> <div className=""brand-centered""> <IndexLink to=""/"" className=""navbar-brand""><div className=""logo"">Journey</div></IndexLink> </div> <div className=""navbar-collapse collapse"" id=""navigation""> <ul className=""nav navbar-nav navbar-left""> <li><Link activeClassName=""nav-active"" to=""/journal"">Journal</Link></li> <li><Link activeClassName=""nav-active"" to=""/dashboard"">Dashboard</Link></li> </ul> <ul className=""nav navbar-nav navbar-right""> <li><Link activeClassName=""nav-active"" to=""/profile"">Profile</Link></li> <li><Link activeClassName=""nav-active"" to=""/login"">Log In</Link></li> </ul> </div> </div> </nav> ) } }","import React, { Component } from 'react' import { Link, IndexLink } from 'react-router' export class Nav extends Component { constructor(props) { super(props) } render() { return ( <nav className=""transparent white-background wrap navbar navbar-default"" role=""navigation""> <div className=""container-fluid""> <div className=""navbar-header""> <button type=""button"" className=""white-background navbar-toggle collapsed"" data-toggle=""collapse"" data-target=""#navigation""> <span className=""sr-only"">Toggle navigation</span> <span className=""icon-bar""></span> <span className=""icon-bar""></span> <span className=""icon-bar""></span> </button> </div> <div className=""brand-centered""> <IndexLink to=""/"" className=""navbar-brand"">Journey</IndexLink> </div> <div className=""navbar-collapse collapse"" id=""navigation""> <ul className=""nav navbar-nav navbar-left""> <li><Link activeClassName=""nav-active"" to=""/journal"">Journal</Link></li> <li><Link activeClassName=""nav-active"" to=""/dashboard"">Dashboard</Link></li> </ul> <ul className=""nav navbar-nav navbar-right""> <li><Link activeClassName=""nav-active"" to=""/profile"">Profile</Link></li> <li><Link activeClassName=""nav-active"" to=""/login"">Log In</Link></li> </ul> </div> </div> </nav> ) } }" Fix bad python 2.6 detection,"import sys from setuptools import setup, find_packages py26_dependency = [] if sys.version_info[:2] <= (2, 6): py26_dependency = [""argparse >= 1.2.1"", ""ordereddict >= 1.1""] setup( name='dataset', version='0.4.0', description=""Toolkit for Python-based data processing."", long_description="""", classifiers=[ ""Development Status :: 3 - Alpha"", ""Intended Audience :: Developers"", ""License :: OSI Approved :: MIT License"", ""Operating System :: OS Independent"", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3' ], keywords='sql sqlalchemy etl loading utility', author='Friedrich Lindenberg, Gregor Aisch', author_email='info@okfn.org', url='http://github.com/pudo/dataset', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'test']), namespace_packages=[], include_package_data=False, zip_safe=False, install_requires=[ 'sqlalchemy >= 0.9.1', 'alembic >= 0.6.2', 'python-slugify >= 0.0.6', ""PyYAML >= 3.10"" ] + py26_dependency, tests_require=[], test_suite='test', entry_points={ 'console_scripts': [ 'datafreeze = dataset.freeze.app:main', ] } ) ","import sys from setuptools import setup, find_packages py26_dependency = [] if sys.version_info <= (2, 6): py26_dependency = [""argparse >= 1.2.1"", ""ordereddict >= 1.1""] setup( name='dataset', version='0.4.0', description=""Toolkit for Python-based data processing."", long_description="""", classifiers=[ ""Development Status :: 3 - Alpha"", ""Intended Audience :: Developers"", ""License :: OSI Approved :: MIT License"", ""Operating System :: OS Independent"", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3' ], keywords='sql sqlalchemy etl loading utility', author='Friedrich Lindenberg, Gregor Aisch', author_email='info@okfn.org', url='http://github.com/pudo/dataset', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'test']), namespace_packages=[], include_package_data=False, zip_safe=False, install_requires=[ 'sqlalchemy >= 0.9.1', 'alembic >= 0.6.2', 'python-slugify >= 0.0.6', ""PyYAML >= 3.10"" ] + py26_dependency, tests_require=[], test_suite='test', entry_points={ 'console_scripts': [ 'datafreeze = dataset.freeze.app:main', ] } ) " Allow ommiting callback argument for serialize method,"'use strict'; Qt.include('call.js'); var createMessageType = (function() { var MessageBase = (function() { var constructor = function(descriptor) { this._descriptor = descriptor; this.serializeTo = function(output, cb) { try { output.descriptor = this._descriptor; var call = new UnaryMethod(output); call.call(this, function(data, err) { if (data) { console.warn('Serialize callback received data object unexpectedly and ignored it.'); } cb && cb(err); }); } catch (err) { console.log('Serialize Error !'); console.error(err); console.error(err.stack); cb && cb(err); } }; }; Object.defineProperties(constructor, { FIELD: {value: 0}, ONEOF: {value: 1}, }); return constructor; })(); var createMessageType = function(type, desc) { type.prototype = new MessageBase(desc); type.parseFrom = function(input, cb) { try { input.descriptor = desc; var call = new UnaryMethod(input); call.call(undefined, function(data, err) { if (err) { cb(undefined, err); } else { var obj = new type(); obj._mergeFromRawArray(data); cb(obj); } }); } catch (err) { console.log('Parse Error !'); console.error(err); console.error(err.stack); cb && cb(undefined, err); } }; }; return createMessageType; })(); ","'use strict'; Qt.include('call.js'); var createMessageType = (function() { var MessageBase = (function() { var constructor = function(descriptor) { this._descriptor = descriptor; this.serializeTo = function(output, cb) { try { output.descriptor = this._descriptor; var call = new UnaryMethod(output); call.call(this, function(data, err) { if (data) { console.warn('Serialize callback received data object unexpectedly and ignored it.'); } cb(err); }); } catch (err) { console.log('Serialize Error !'); console.error(err); console.error(err.stack); cb && cb(err); } }; }; Object.defineProperties(constructor, { FIELD: {value: 0}, ONEOF: {value: 1}, }); return constructor; })(); var createMessageType = function(type, desc) { type.prototype = new MessageBase(desc); type.parseFrom = function(input, cb) { try { input.descriptor = desc; var call = new UnaryMethod(input); call.call(undefined, function(data, err) { if (err) { cb(undefined, err); } else { var obj = new type(); obj._mergeFromRawArray(data); cb(obj); } }); } catch (err) { console.log('Parse Error !'); console.error(err); console.error(err.stack); cb && cb(undefined, err); } }; }; return createMessageType; })(); " Add `publicDir` option to plugin options,"import { resolve } from 'path'; import { init } from './server/init'; import { replaceInjectedVars } from './server/lib/replace_injected_vars'; export default function (kibana) { return new kibana.Plugin({ id: 'notification_center', configPrefix: 'notification_center', require: ['elasticsearch'], name: 'notification_center', publicDir: resolve(__dirname, 'public'), uiExports: { chromeNavControls: [ 'plugins/notification_center/nav_control' ], injectDefaultVars(server) { return { notificationCenter: { supportDarkTheme: server.config().get('notification_center.supportDarkTheme') } }; }, replaceInjectedVars }, config(Joi) { return Joi.object({ enabled: Joi.boolean().default(true), index: Joi.string().default('notification-%{+YYYY.MM.DD}'), template: Joi.object({ name: Joi.string().default('notification_center_template'), overwrite: Joi.boolean().default(false) }).default(), api: Joi.object({ enabled: Joi.boolean().default(true), pull: Joi.object({ maxSize: Joi.number().default(100) }).default() }).default(), supportDarkTheme: Joi.boolean().default(true) }).default(); }, init }); };","import { readdirSync, lstatSync } from 'fs'; import { resolve } from 'path'; import { init } from './server/init'; import { replaceInjectedVars } from './server/lib/replace_injected_vars'; export default function (kibana) { return new kibana.Plugin({ id: 'notification_center', configPrefix: 'notification_center', require: ['elasticsearch'], name: 'notification_center', uiExports: { chromeNavControls: [ 'plugins/notification_center/nav_control' ], injectDefaultVars(server) { return { notificationCenter: { supportDarkTheme: server.config().get('notification_center.supportDarkTheme') } }; }, replaceInjectedVars }, config(Joi) { return Joi.object({ enabled: Joi.boolean().default(true), index: Joi.string().default('notification-%{+YYYY.MM.DD}'), template: Joi.object({ name: Joi.string().default('notification_center_template'), overwrite: Joi.boolean().default(false) }).default(), api: Joi.object({ enabled: Joi.boolean().default(true), pull: Joi.object({ maxSize: Joi.number().default(100) }).default() }).default(), supportDarkTheme: Joi.boolean().default(true) }).default(); }, init }); };" Fix wrong timestamp format; no AM/PM,"/** * Retz * Copyright (C) 2016 Nautilus Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.retz.cli; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class TimestampHelper { // Use ISO8601-like extended format private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(""yyyy-MM-dd'T'HH:mm:ss.SSSXXX""); public static String now() { synchronized (DATE_FORMAT) { return DATE_FORMAT.format(Calendar.getInstance().getTime()); } } // Returns duration in second public static long diffMillisec(String lhs, String rhs) throws ParseException { synchronized (DATE_FORMAT) { Date l = DATE_FORMAT.parse(lhs); Date r = DATE_FORMAT.parse(rhs); // Date#getTime returns timestamp since 1970 in milliseconds return l.getTime() - r.getTime(); } } } ","/** * Retz * Copyright (C) 2016 Nautilus Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.retz.cli; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class TimestampHelper { // Use ISO8601-like extended format private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(""yyyy-MM-dd'T'hh:mm:ss.SSSXXX""); public static String now() { synchronized (DATE_FORMAT) { return DATE_FORMAT.format(Calendar.getInstance().getTime()); } } // Returns duration in second public static long diffMillisec(String lhs, String rhs) throws ParseException { synchronized (DATE_FORMAT) { Date l = DATE_FORMAT.parse(lhs); Date r = DATE_FORMAT.parse(rhs); // Date#getTime returns timestamp since 1970 in milliseconds return l.getTime() - r.getTime(); } } } " Add output when server has started.,"package no.javazone; import io.vertx.core.Vertx; import io.vertx.core.json.Json; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; public class VertxHttpServer { public static void main(String[] args) { Vertx vertx = Vertx.vertx(); Router router = Router.router(vertx); router.get(""/person/:id"").handler(VertxHttpServer::returnPerson); router.get(""/address/:id"").handler(VertxHttpServer::returnAddress); router.get(""/"").handler(ctx -> ctx.response().end(""Hello world"")); vertx.createHttpServer().requestHandler(router::accept).listen(8080); System.out.println(""Server started on port 8080""); } private static void returnPerson(RoutingContext ctx) { String id = ctx.request().getParam(""id""); ctx.response() .setStatusCode(200) .end(Json.encode(new TypicalExamples.Person(id, ""Me"", 29))); System.out.println(""requested person "" + id); } private static void returnAddress(RoutingContext ctx) { String id = ctx.request().getParam(""id""); ctx.response() .setStatusCode(200) .end(Json.encode(new TypicalExamples.Address(id, ""House 1"", ""Street 2"", ""1337"", ""Sandvika""))); System.out.println(""requested address "" + id); } } ","package no.javazone; import io.vertx.core.Vertx; import io.vertx.core.json.Json; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; public class VertxHttpServer { public static void main(String[] args) { Vertx vertx = Vertx.vertx(); Router router = Router.router(vertx); router.get(""/person/:id"").handler(VertxHttpServer::returnPerson); router.get(""/address/:id"").handler(VertxHttpServer::returnAddress); router.get(""/"").handler(ctx -> ctx.response().end(""Hello world"")); vertx.createHttpServer().requestHandler(router::accept).listen(8080); } private static void returnPerson(RoutingContext ctx) { String id = ctx.request().getParam(""id""); ctx.response() .setStatusCode(200) .end(Json.encode(new TypicalExamples.Person(id, ""Me"", 29))); System.out.println(""requested person "" + id); } private static void returnAddress(RoutingContext ctx) { String id = ctx.request().getParam(""id""); ctx.response() .setStatusCode(200) .end(Json.encode(new TypicalExamples.Address(id, ""House 1"", ""Street 2"", ""1337"", ""Sandvika""))); System.out.println(""requested address "" + id); } } " Ch22: Add name and joined date field to Profile.,"from django.conf import settings from django.contrib.auth.models import ( AbstractBaseUser, PermissionsMixin) from django.core.urlresolvers import reverse from django.db import models class Profile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL) name = models.CharField( max_length=255) slug = models.SlugField( max_length=30, unique=True) about = models.TextField() joined = models.DateTimeField( ""Date Joined"", auto_now_add=True) def __str__(self): return self.user.get_username() def get_absolute_url(self): return reverse( 'dj-auth:public_profile', kwargs={'slug': self.slug}) def get_update_url(self): return reverse('dj-auth:profile_update') class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( 'email address', max_length=254, unique=True) is_staff = models.BooleanField( 'staff status', default=False, help_text=( 'Designates whether the user can ' 'log into this admin site.')) is_active = models.BooleanField( 'active', default=True, help_text=( 'Designates whether this user should ' 'be treated as active. Unselect this ' 'instead of deleting accounts.')) USERNAME_FIELD = 'email' def __str__(self): return self.email def get_absolute_url(self): return self.profile.get_absolute_url() def get_full_name(self): return self.profile.name def get_short_name(self): return self.profile.name ","from django.conf import settings from django.contrib.auth.models import ( AbstractBaseUser, PermissionsMixin) from django.core.urlresolvers import reverse from django.db import models class Profile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL) slug = models.SlugField( max_length=30, unique=True) about = models.TextField() def __str__(self): return self.user.get_username() def get_absolute_url(self): return reverse( 'dj-auth:public_profile', kwargs={'slug': self.slug}) def get_update_url(self): return reverse('dj-auth:profile_update') class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( 'email address', max_length=254, unique=True) is_staff = models.BooleanField( 'staff status', default=False, help_text=( 'Designates whether the user can ' 'log into this admin site.')) is_active = models.BooleanField( 'active', default=True, help_text=( 'Designates whether this user should ' 'be treated as active. Unselect this ' 'instead of deleting accounts.')) USERNAME_FIELD = 'email' def __str__(self): return self.email def get_absolute_url(self): return self.profile.get_absolute_url() " Fix survey_scenario (use core v20 syntax),"# -*- coding: utf-8 -*- from openfisca_senegal import CountryTaxBenefitSystem as SenegalTaxBenefitSystem from openfisca_survey_manager.scenarios import AbstractSurveyScenario class SenegalSurveyScenario(AbstractSurveyScenario): id_variable_by_entity_key = dict( famille = 'id_famille', ) role_variable_by_entity_key = dict( famille = 'role_famille', ) def __init__(self, input_data_frame = None, tax_benefit_system = None, baseline_tax_benefit_system = None, year = None): super(SenegalSurveyScenario, self).__init__() assert input_data_frame is not None assert year is not None self.year = year if tax_benefit_system is None: tax_benefit_system = SenegalTaxBenefitSystem() self.set_tax_benefit_systems( tax_benefit_system = tax_benefit_system, baseline_tax_benefit_system = baseline_tax_benefit_system ) self.used_as_input_variables = list( set(tax_benefit_system.variables.keys()).intersection( set(input_data_frame.columns) )) self.init_from_data_frame(input_data_frame = input_data_frame) self.new_simulation() if baseline_tax_benefit_system is not None: self.new_simulation(use_baseline = True) ","# -*- coding: utf-8 -*- from openfisca_senegal import CountryTaxBenefitSystem as SenegalTaxBenefitSystem from openfisca_survey_manager.scenarios import AbstractSurveyScenario class SenegalSurveyScenario(AbstractSurveyScenario): id_variable_by_entity_key = dict( famille = 'id_famille', ) role_variable_by_entity_key = dict( famille = 'role_famille', ) def __init__(self, input_data_frame = None, tax_benefit_system = None, reference_tax_benefit_system = None, year = None): super(SenegalSurveyScenario, self).__init__() assert input_data_frame is not None assert year is not None self.year = year if tax_benefit_system is None: tax_benefit_system = SenegalTaxBenefitSystem() self.set_tax_benefit_systems( tax_benefit_system = tax_benefit_system, reference_tax_benefit_system = reference_tax_benefit_system ) self.used_as_input_variables = list( set(tax_benefit_system.column_by_name.keys()).intersection( set(input_data_frame.columns) )) self.init_from_data_frame(input_data_frame = input_data_frame) self.new_simulation() if reference_tax_benefit_system is not None: self.new_simulation(reference = True) " "Set lifetime of feed to 1 hour Solution for 3.4","<?php abstract class Kwc_Abstract_Feed_Component extends Kwc_Abstract { public static function getSettings() { $ret = parent::getSettings(); $ret['contentSender'] = 'Kwc_Abstract_Feed_ContentSender'; return $ret; } abstract protected function _getRssEntries(); protected function _getRssTitle() { return Zend_Registry::get('config')->application->name; } public function getXml() { $cache = Kwf_Component_Cache::getInstance(); if (!$xml = $cache->load($this->getData())) { $xml = $this->_getFeedXml(); $cache->save($this->getData(), $xml, 'component', 'component', '', 60*60); Kwf_Component_Cache::getInstance()->writeBuffer(); } return $xml; } private function _getFeedXml() { $host = isset($_SERVER['HTTP_HOST']) ? 'http://' . $_SERVER['HTTP_HOST'] : ''; $feedArray = array( 'title' => $this->_getRssTitle(), 'link' => $host.$this->getUrl(), //'lastUpdate' => , 'charset' => 'utf-8', 'description' => '', //'author' => , //'email' => , 'copyright' => Zend_Registry::get('config')->application->name, 'generator' => 'Vivid Planet Software GmbH', 'language' => 'de', //TODO 'entries' => $this->_getRssEntries() ); $feed = Zend_Feed::importArray($feedArray, 'rss'); return $feed->saveXml(); } } ","<?php abstract class Kwc_Abstract_Feed_Component extends Kwc_Abstract { public static function getSettings() { $ret = parent::getSettings(); $ret['contentSender'] = 'Kwc_Abstract_Feed_ContentSender'; return $ret; } abstract protected function _getRssEntries(); protected function _getRssTitle() { return Zend_Registry::get('config')->application->name; } public function getXml() { $cache = Kwf_Component_Cache::getInstance(); if (!$xml = $cache->load($this->getData())) { $xml = $this->_getFeedXml(); $cache->save($this->getData(), $xml); } return $xml; } private function _getFeedXml() { $host = isset($_SERVER['HTTP_HOST']) ? 'http://' . $_SERVER['HTTP_HOST'] : ''; $feedArray = array( 'title' => $this->_getRssTitle(), 'link' => $host.$this->getUrl(), //'lastUpdate' => , 'charset' => 'utf-8', 'description' => '', //'author' => , //'email' => , 'copyright' => Zend_Registry::get('config')->application->name, 'generator' => 'Vivid Planet Software GmbH', 'language' => 'de', //TODO 'entries' => $this->_getRssEntries() ); $feed = Zend_Feed::importArray($feedArray, 'rss'); return $feed->saveXml(); } } " Add check for Python 3 and increment version,"#!/usr/bin/env python3 from setuptools import setup import sys if not sys.version_info[0] == 3: sys.exit(""Sorry, Cistern only supports Python 3."") setup( name=""cistern"", version=""0.1.4"", license=""MIT"", url=""https://github.com/archangelic/cistern"", description=""Command line tool for downloading torrents from RSS feeds."", author=""Michael Hancock"", author_email=""michaelhancock89@gmail.com"", download_url=( ""https://github.com/archangelic/cistern/archive/v0.1.4.tar.gz"" ), install_requires=[ 'click', 'configobj', 'feedparser', 'peewee', 'tabulate', 'transmissionrpc', ], entry_points={ 'console_scripts': [ 'cistern=cistern.cistern:cli', ] }, packages=[ 'cistern', ], keywords=['torrent', 'rss', 'transmission'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'Topic :: Internet', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ] ) ","#!/usr/bin/env python3 from setuptools import setup setup( name=""cistern"", version=""0.1.3"", license=""MIT"", url=""https://github.com/archangelic/cistern"", description=""Command line tool for downloading torrents from RSS feeds."", author=""Michael Hancock"", author_email=""michaelhancock89@gmail.com"", download_url=( ""https://github.com/archangelic/cistern/archive/v0.1.3.tar.gz"" ), install_requires=[ 'click', 'configobj', 'feedparser', 'peewee', 'tabulate', 'transmissionrpc', ], entry_points={ 'console_scripts': [ 'cistern=cistern.cistern:cli', ] }, packages=[ 'cistern', ], keywords=['torrent', 'rss', 'transmission'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'Topic :: Internet', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ] ) " Allow any address line to be null,"<?php namespace Z38\SwissPayment; /** * This class holds a unstructured representation of a postal address */ class UnstructuredPostalAddress implements PostalAddressInterface { /** * @var array */ protected $addressLines; /** * @var string */ protected $country; /** * Constructor * * @param string $addressLine1 Street name and house number * @param string $addressLine2 Postcode and town * @param string $country Country code (ISO 3166-1 alpha-2) */ public function __construct($addressLine1 = null, $addressLine2 = null, $country = 'CH') { $this->addressLines = array(); if ($addressLine1 !== null) { $this->addressLines[] = $addressLine1; } if ($addressLine2 !== null) { $this->addressLines[] = $addressLine2; } $this->country = (string) $country; } /** * {@inheritdoc} */ public function asDom(\DOMDocument $doc) { $root = $doc->createElement('PstlAdr'); $root->appendChild($doc->createElement('Ctry', $this->country)); foreach ($this->addressLines as $line) { $root->appendChild($doc->createElement('AdrLine', $line)); } return $root; } } ","<?php namespace Z38\SwissPayment; /** * This class holds a unstructured representation of a postal address */ class UnstructuredPostalAddress implements PostalAddressInterface { /** * @var string */ protected $adrLine1; /** * @var string */ protected $adrLine2; /** * @var string */ protected $country; /** * Constructor * * @param string $adrLine1 Street name and house number * @param string $ardLine2 Postcode and town * @param string $country Country code (ISO 3166-1 alpha-2) */ public function __construct($adrLine1 = null, $ardLine2, $country = 'CH') { $this->adrLine1 = $adrLine1; $this->adrLine2 = $ardLine2; $this->country = (string) $country; } /** * {@inheritdoc} */ public function asDom(\DOMDocument $doc) { $root = $doc->createElement('PstlAdr'); $root->appendChild($doc->createElement('Ctry', $this->country)); if (null !== $this->adrLine1) { $root->appendChild($doc->createElement('AdrLine', $this->adrLine1)); } $root->appendChild($doc->createElement('AdrLine', $this->adrLine2)); return $root; } } " Reorder setupController and model for consistency,"import Ember from 'ember'; export default Ember.Route.extend({ queryParams: { page: { refreshModel: true }, sort: { refreshModel: true }, }, data: {}, model(params) { const { user_id } = params; return this.store.find('user', user_id).then( (user) => { params.user_id = user.get('id'); return Ember.RSVP.hash({ crates: this.store.query('crate', params), user }); }, (e) => { if (e.errors.any(e => e.detail === 'Not Found')) { this .controllerFor('application') .set('nextFlashError', `User '${params.user_id}' does not exist`); return this.replaceWith('index'); } } ); }, setupController(controller, model) { this._super(controller, model); controller.set('fetchingFeed', true); controller.set('crates', this.get('data.crates')); }, }); ","import Ember from 'ember'; export default Ember.Route.extend({ queryParams: { page: { refreshModel: true }, sort: { refreshModel: true }, }, data: {}, setupController(controller, model) { this._super(controller, model); controller.set('fetchingFeed', true); controller.set('crates', this.get('data.crates')); }, model(params) { const { user_id } = params; return this.store.find('user', user_id).then( (user) => { params.user_id = user.get('id'); return Ember.RSVP.hash({ crates: this.store.query('crate', params), user }); }, (e) => { if (e.errors.any(e => e.detail === 'Not Found')) { this .controllerFor('application') .set('nextFlashError', `User '${params.user_id}' does not exist`); return this.replaceWith('index'); } } ); }, }); " Update annotation list on job completion,"histomicstk.views.AnnotationSelectorWidget = histomicstk.views.Panel.extend({ events: _.extend(histomicstk.views.Panel.prototype.events, { 'click .h-annotation > span': 'toggleAnnotation' }), initialize: function () { this.listenTo(girder.eventStream, 'g:event.job_status', function (evt) { if (evt.data.status > 2) { this.collection.fetch(); } }); }, setItem: function (item) { if (this.collection) { this.stopListening(this.collection); } this.parentItem = item; this.collection = this.parentItem.annotations; if (this.collection) { this.collection.append = true; this.listenTo(this.collection, 'g:changed', this.render); this.listenTo(this.collection, 'add', this.render); this.collection.fetch(); } else { this.collection = new Backbone.Collection(); } return this; }, render: function () { this.$el.html(histomicstk.templates.annotationSelectorWidget({ annotations: this.collection.toArray(), id: 'annotation-panel-container', title: 'Annotations' })); return this; }, toggleAnnotation: function (evt) { var id = $(evt.currentTarget).data('id'); var model = this.collection.get(id); model.set('displayed', !model.get('displayed')); this.render(); } }); ","histomicstk.views.AnnotationSelectorWidget = histomicstk.views.Panel.extend({ events: _.extend(histomicstk.views.Panel.prototype.events, { 'click .h-annotation > span': 'toggleAnnotation' }), setItem: function (item) { if (this.collection) { this.stopListening(this.collection); } this.parentItem = item; this.collection = this.parentItem.annotations; if (this.collection) { this.collection.append = true; this.listenTo(this.collection, 'g:changed', this.render); this.listenTo(this.collection, 'add', this.render); this.collection.fetch(); } else { this.collection = new Backbone.Collection(); } return this; }, render: function () { this.$el.html(histomicstk.templates.annotationSelectorWidget({ annotations: this.collection.toArray(), id: 'annotation-panel-container', title: 'Annotations' })); return this; }, toggleAnnotation: function (evt) { var id = $(evt.currentTarget).data('id'); var model = this.collection.get(id); model.set('displayed', !model.get('displayed')); this.render(); } }); " Throw error if there's no match when discarding added lines,"export default function discardChangesInBuffer(buffer, filePatch, discardedLines) { // TODO: store of buffer for restoring in case of undo buffer.transact(() => { let addedCount = 0; let removedCount = 0; let deletedCount = 0; filePatch.getHunks().forEach(hunk => { hunk.getLines().forEach(line => { if (discardedLines.has(line)) { if (line.status === 'deleted') { const row = (line.oldLineNumber - deletedCount) + addedCount - removedCount - 1; buffer.insert([row, 0], line.text + '\n'); addedCount++; } else if (line.status === 'added') { const row = line.newLineNumber + addedCount - removedCount - 1; if (buffer.lineForRow(row) === line.text) { buffer.deleteRow(row); removedCount++; } else { throw new Error(buffer.lineForRow(row) + ' does not match ' + line.text); } } else if (line.status === 'nonewline') { // TODO: handle no new line case } else { throw new Error(`unrecognized status: ${line.status}. Must be 'added' or 'deleted'`); } } if (line.getStatus() === 'deleted') { deletedCount++; } }); }); }); buffer.save(); } ","export default function discardChangesInBuffer(buffer, filePatch, discardedLines) { // TODO: store of buffer for restoring in case of undo buffer.transact(() => { let addedCount = 0; let removedCount = 0; let deletedCount = 0; filePatch.getHunks().forEach(hunk => { hunk.getLines().forEach(line => { if (discardedLines.has(line)) { if (line.status === 'deleted') { const row = (line.oldLineNumber - deletedCount) + addedCount - removedCount - 1; buffer.insert([row, 0], line.text + '\n'); addedCount++; } else if (line.status === 'added') { const row = line.newLineNumber + addedCount - removedCount - 1; if (buffer.lineForRow(row) === line.text) { buffer.deleteRow(row); removedCount++; } else { // eslint-disable-next-line no-console console.error(buffer.lineForRow(row) + ' does not match ' + line.text); } } else if (line.status === 'nonewline') { // TODO: handle no new line case } else { throw new Error(`unrecognized status: ${line.status}. Must be 'added' or 'deleted'`); } } if (line.getStatus() === 'deleted') { deletedCount++; } }); }); }); buffer.save(); } " Clear history immediately when switching sources,"import * as d3 from 'd3'; import { t } from '../util/locale'; import { modeBrowse } from '../modes/index'; export function uiSourceSwitch(context) { var keys; function click() { d3.event.preventDefault(); if (context.history().hasChanges() && !window.confirm(t('source_switch.lose_changes'))) return; var live = d3.select(this) .classed('live'); context.history().clearSaved(); context.connection().switch(live ? keys[1] : keys[0]); context.enter(modeBrowse(context)); context.flush(); d3.select(this) .text(live ? t('source_switch.dev') : t('source_switch.live')) .classed('live', !live); } var sourceSwitch = function(selection) { selection .append('a') .attr('href', '#') .text(t('source_switch.live')) .classed('live', true) .attr('tabindex', -1) .on('click', click); }; sourceSwitch.keys = function(_) { if (!arguments.length) return keys; keys = _; return sourceSwitch; }; return sourceSwitch; } ","import * as d3 from 'd3'; import { t } from '../util/locale'; import { modeBrowse } from '../modes/index'; export function uiSourceSwitch(context) { var keys; function click() { d3.event.preventDefault(); if (context.history().hasChanges() && !window.confirm(t('source_switch.lose_changes'))) return; var live = d3.select(this) .classed('live'); context.connection() .switch(live ? keys[1] : keys[0]); context.enter(modeBrowse(context)); context.flush(); d3.select(this) .text(live ? t('source_switch.dev') : t('source_switch.live')) .classed('live', !live); } var sourceSwitch = function(selection) { selection .append('a') .attr('href', '#') .text(t('source_switch.live')) .classed('live', true) .attr('tabindex', -1) .on('click', click); }; sourceSwitch.keys = function(_) { if (!arguments.length) return keys; keys = _; return sourceSwitch; }; return sourceSwitch; } " "Fix Ghost icon is not clickable closes #3623 - Initialization of the link was done on login page where the ‚burger‘ did not exist. - initialization in application needs to be done to make it work on refresh","import {mobileQuery, responsiveAction} from 'ghost/utils/mobile'; var PostsView = Ember.View.extend({ target: Ember.computed.alias('controller'), classNames: ['content-view-container'], tagName: 'section', mobileInteractions: function () { Ember.run.scheduleOnce('afterRender', this, function () { var self = this; $(window).resize(function () { if (!mobileQuery.matches) { self.send('resetContentPreview'); } }); // ### Show content preview when swiping left on content list $('.manage').on('click', '.content-list ol li', function (event) { responsiveAction(event, '(max-width: 800px)', function () { self.send('showContentPreview'); }); }); // ### Hide content preview $('.manage').on('click', '.content-preview .button-back', function (event) { responsiveAction(event, '(max-width: 800px)', function () { self.send('hideContentPreview'); }); }); $('[data-off-canvas]').attr('href', this.get('controller.ghostPaths.blogRoot')); }); }.on('didInsertElement'), }); export default PostsView; ","import {mobileQuery, responsiveAction} from 'ghost/utils/mobile'; var PostsView = Ember.View.extend({ target: Ember.computed.alias('controller'), classNames: ['content-view-container'], tagName: 'section', mobileInteractions: function () { Ember.run.scheduleOnce('afterRender', this, function () { var self = this; $(window).resize(function () { if (!mobileQuery.matches) { self.send('resetContentPreview'); } }); // ### Show content preview when swiping left on content list $('.manage').on('click', '.content-list ol li', function (event) { responsiveAction(event, '(max-width: 800px)', function () { self.send('showContentPreview'); }); }); // ### Hide content preview $('.manage').on('click', '.content-preview .button-back', function (event) { responsiveAction(event, '(max-width: 800px)', function () { self.send('hideContentPreview'); }); }); }); }.on('didInsertElement'), }); export default PostsView; " Fix FK nullability on interaction table,"'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('DiscordInteractions', { id: { primaryKey: true, type: Sequelize.INTEGER, autoIncrement: true, allowNull: false, }, command: { type: Sequelize.STRING, }, alias: { type: Sequelize.STRING, }, properties: { type: Sequelize.JSONB, }, createdAt: { type: Sequelize.DATE, allowNull: false, }, updatedAt: { type: Sequelize.DATE, allowNull: false, }, UserId: { type: Sequelize.INTEGER, allowNull: false, references: { model: 'DiscordUsers', key: 'id', }, onUpdate: 'no action', onDelete: 'no action', }, ChannelId: { type: Sequelize.INTEGER, allowNull: false, references: { model: 'DiscordChannels', key: 'id', }, onUpdate: 'no action', onDelete: 'no action', }, GuildId: { type: Sequelize.INTEGER, allowNull: true, references: { model: 'DiscordGuilds', key: 'id', }, onUpdate: 'no action', onDelete: 'no action', }, }); }, down: (queryInterface, Sequelize) => { return queryInterface.dropTable('DiscordInteractions'); }, }; ","'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('DiscordInteractions', { id: { primaryKey: true, type: Sequelize.INTEGER, autoIncrement: true, allowNull: false, }, command: { type: Sequelize.STRING, }, alias: { type: Sequelize.STRING, }, properties: { type: Sequelize.JSONB, }, createdAt: { type: Sequelize.DATE, allowNull: false, }, updatedAt: { type: Sequelize.DATE, allowNull: false, }, UserId: { type: Sequelize.INTEGER, allowNull: false, references: { model: 'DiscordUsers', key: 'id', }, onUpdate: 'no action', onDelete: 'no action', }, ChannelId: { type: Sequelize.INTEGER, allowNull: true, references: { model: 'DiscordChannels', key: 'id', }, onUpdate: 'no action', onDelete: 'no action', }, GuildId: { type: Sequelize.INTEGER, allowNull: false, references: { model: 'DiscordGuilds', key: 'id', }, onUpdate: 'no action', onDelete: 'no action', }, }); }, down: (queryInterface, Sequelize) => { return queryInterface.dropTable('DiscordInteractions'); }, }; " Change value field in json output,"#! /usr/bin/env python2 # vim: set fenc=utf8 ts=4 sw=4 et : import sys import json import xml.sax class PdmlHandler( xml.sax.ContentHandler ): def __init__(self): self.CurrentData = """" self.type = """" self.format = """" self.year = """" self.rating = """" self.stars = """" self.description = """" # Call when an element starts def startElement(self, tag, attributes): self.CurrentData = tag if tag == ""packet"": pkt.clear() else: if attributes.has_key(""name"") and attributes.has_key(""show""): name = attributes.getValue(""name"") showname = attributes.getValue(""show"") pkt[name] = showname # Call when an elements ends def endElement(self, tag): if tag == ""packet"": json.dump(pkt,sys.stdout) sys.stdout.write(""\n"") sys.stdout.flush() # Call when a character is read def characters(self, content): pass if ( __name__ == ""__main__""): #pkt dictionary pkt = {} # create an XMLReader parser = xml.sax.make_parser() # turn off namepsaces parser.setFeature(xml.sax.handler.feature_namespaces, 0) # override the default ContextHandler Handler = PdmlHandler() parser.setContentHandler( Handler ) parser.parse(sys.stdin) ","#! /usr/bin/env python2 # vim: set fenc=utf8 ts=4 sw=4 et : import sys import json import xml.sax class PdmlHandler( xml.sax.ContentHandler ): def __init__(self): self.CurrentData = """" self.type = """" self.format = """" self.year = """" self.rating = """" self.stars = """" self.description = """" # Call when an element starts def startElement(self, tag, attributes): self.CurrentData = tag if tag == ""packet"": pkt.clear() else: if attributes.has_key(""name"") and attributes.has_key(""showname""): name = attributes.getValue(""name"") showname = attributes.getValue(""showname"") pkt[name] = showname # Call when an elements ends def endElement(self, tag): if tag == ""packet"": json.dump(pkt,sys.stdout) sys.stdout.write(""\n"") sys.stdout.flush() # Call when a character is read def characters(self, content): pass if ( __name__ == ""__main__""): #pkt dictionary pkt = {} # create an XMLReader parser = xml.sax.make_parser() # turn off namepsaces parser.setFeature(xml.sax.handler.feature_namespaces, 0) # override the default ContextHandler Handler = PdmlHandler() parser.setContentHandler( Handler ) parser.parse(sys.stdin) " Order similar artist results properly,"from django.db.models import Q import echonest from artists.models import Artist from echonest.models import SimilarResponse from users.models import User from .models import (GeneralArtist, UserSimilarity, Similarity, update_similarities) def add_new_similarities(artist, force_update=False): similarities = [] responses = SimilarResponse.objects.filter( normalized_name=artist.normalized_name) if responses.exists() and not force_update: return # Echo Nest similarities already added user = User.objects.get(email='echonest') artist_names = echonest.get_similar(artist.name) cc_artists = Artist.objects.filter(name__in=artist_names) for cc_artist in cc_artists: kwargs = dict( cc_artist=cc_artist, other_artist=artist, ) UserSimilarity.objects.get_or_create(defaults={'weight': 1}, user=user, **kwargs) similarities.append(Similarity.objects.get_or_create(**kwargs)[0]) update_similarities(similarities) def get_similar(name): artist, _ = GeneralArtist.objects.get_or_create( normalized_name=name.upper(), defaults={'name': name}) add_new_similarities(artist) similar = Q(similarity__other_artist=artist, similarity__weight__gt=0) return Artist.objects.filter(similar).order_by('-similarity__weight') ","import echonest from artists.models import Artist from echonest.models import SimilarResponse from users.models import User from .models import (GeneralArtist, UserSimilarity, Similarity, update_similarities) def add_new_similarities(artist, force_update=False): similarities = [] responses = SimilarResponse.objects.filter( normalized_name=artist.normalized_name) if responses.exists() and not force_update: return # Echo Nest similarities already added user = User.objects.get(email='echonest') artist_names = echonest.get_similar(artist.name) cc_artists = Artist.objects.filter(name__in=artist_names) for cc_artist in cc_artists: kwargs = dict( cc_artist=cc_artist, other_artist=artist, ) UserSimilarity.objects.get_or_create(defaults={'weight': 1}, user=user, **kwargs) similarities.append(Similarity.objects.get_or_create(**kwargs)[0]) update_similarities(similarities) def get_similar(name): artist, _ = GeneralArtist.objects.get_or_create( normalized_name=name.upper(), defaults={'name': name}) add_new_similarities(artist) return Artist.objects.filter(similarity__other_artist=artist, similarity__weight__gt=0) " Fix copying files that don't exist,"'use strict'; var yeoman = require( 'yeoman-generator' ), yosay = require( 'yosay' ); var DashGenerator = yeoman.generators.Base.extend( { initializing: function() { this.pkg = require( '../../package.json' ); }, prompting: function() { var done = this.async(); // Have Yeoman greet the user. this.log( yosay( 'Welcome to the world-class Dash generator!' ) ); var prompts = [ { type: 'confirm', name: 'someOption', message: 'Would you like to enable this option?', default: true } ]; this.prompt( prompts, function( props ) { this.someOption = props.someOption; done(); }.bind( this ) ); }, writing: { app: function() { this.dest.mkdir( 'app' ); this.dest.mkdir( 'app/templates' ); this.src.copy( '_package.json' , 'package.json' ); this.src.copy( '_bower.json', 'bower.json' ); }, projectfiles: function() { } }, end: function() { this.installDependencies(); } } ); module.exports = DashGenerator; ","'use strict'; var yeoman = require( 'yeoman-generator' ), yosay = require( 'yosay' ); var DashGenerator = yeoman.generators.Base.extend( { initializing: function() { this.pkg = require( '../../package.json' ); }, prompting: function() { var done = this.async(); // Have Yeoman greet the user. this.log( yosay( 'Welcome to the world-class Dash generator!' ) ); var prompts = [ { type: 'confirm', name: 'someOption', message: 'Would you like to enable this option?', default: true } ]; this.prompt( prompts, function( props ) { this.someOption = props.someOption; done(); }.bind( this ) ); }, writing: { app: function() { this.dest.mkdir( 'app' ); this.dest.mkdir( 'app/templates' ); this.src.copy( '_package.json' , 'package.json' ); this.src.copy( '_bower.json', 'bower.json' ); }, projectfiles: function() { this.src.copy( 'editorconfig', '.editorconfig'); this.src.copy( 'jshintrc', '.jshintrc'); } }, end: function() { this.installDependencies(); } } ); module.exports = DashGenerator; " Use newly exposed oauth2.is_secure_transport instead of duplicate.,"from __future__ import unicode_literals from oauthlib.oauth2 import WebApplicationClient, InsecureTransportError from oauthlib.oauth2 import is_secure_transport class OAuth2(object): """"""Adds proof of authorization (OAuth2 token) to the request."""""" def __init__(self, client_id=None, client=None, token=None): """"""Construct a new OAuth 2 authorization object. :param client_id: Client id obtained during registration :param client: :class:`oauthlib.oauth2.Client` to be used. Default is WebApplicationClient which is useful for any hosted application but not mobile or desktop. :param token: Token dictionary, must include access_token and token_type. """""" self._client = client or WebApplicationClient(client_id, token=token) if token: for k, v in token.items(): setattr(self._client, k, v) def __call__(self, r): """"""Append an OAuth 2 token to the request. Note that currently HTTPS is required for all requests. There may be a token type that allows for plain HTTP in the future and then this should be updated to allow plain HTTP on a white list basis. """""" if not is_secure_transport(r.url): raise InsecureTransportError() r.url, r.headers, r.body = self._client.add_token(r.url, http_method=r.method, body=r.body, headers=r.headers) return r ","from __future__ import unicode_literals from oauthlib.oauth2 import WebApplicationClient, InsecureTransportError from .utils import is_secure_transport class OAuth2(object): """"""Adds proof of authorization (OAuth2 token) to the request."""""" def __init__(self, client_id=None, client=None, token=None): """"""Construct a new OAuth 2 authorization object. :param client_id: Client id obtained during registration :param client: :class:`oauthlib.oauth2.Client` to be used. Default is WebApplicationClient which is useful for any hosted application but not mobile or desktop. :param token: Token dictionary, must include access_token and token_type. """""" self._client = client or WebApplicationClient(client_id, token=token) if token: for k, v in token.items(): setattr(self._client, k, v) def __call__(self, r): """"""Append an OAuth 2 token to the request. Note that currently HTTPS is required for all requests. There may be a token type that allows for plain HTTP in the future and then this should be updated to allow plain HTTP on a white list basis. """""" if not is_secure_transport(r.url): raise InsecureTransportError() r.url, r.headers, r.body = self._client.add_token(r.url, http_method=r.method, body=r.body, headers=r.headers) return r " Change default extension to yaml,"import json import yaml from jshbot.exceptions import ConfiguredBotException, ErrorTypes CBException = ConfiguredBotException('Configurations') def get(bot, plugin_name, key=None, extra=None, extension='yaml'): """"""Gets the configuration file for the given plugin. Keyword arguments: key -- Gets the specified key from the config file, otherwise everything. extra -- Looks for <plugin_name>-<extra>.<extension> extension -- If 'json', reads the file as json, otherwise reads it as text. """""" if extra: # Open from external configuration file filename = '{0}/config/{1}-{2}.{3}'.format(bot.path, plugin_name[:-3], extra, extension) else: # Open from configuration dictionary try: config = bot.configurations[plugin_name] except KeyError: raise CBException( ""Plugin {} not found in the configurations dictionary."".format(plugin_name)) try: if key: return config[key] else: return config except KeyError: raise CBException(""Key {} not found in the configuration file."".format(key)) try: with open(filename, 'r') as config_file: if extension.lower() == 'json': return json.load(config_file) elif extension.lower() == 'yaml': return yaml.load(config_file) else: return config_file.read() except FileNotFoundError: raise CBException(""File {} not found."".format(filename)) except Exception as e: raise CBException(""Failed to read {} properly."".format(filename), e=e) ","import json from jshbot.exceptions import ConfiguredBotException, ErrorTypes CBException = ConfiguredBotException('Configurations') def get(bot, plugin_name, key=None, extra=None, extension='json'): """"""Gets the configuration file for the given plugin. Keyword arguments: key -- Gets the specified key from the config file, otherwise everything. extra -- Looks for <plugin_name>-<extra>.<extension> extension -- If 'json', reads the file as json, otherwise reads it as text. """""" if extra: # Open from external configuration file filename = '{0}/config/{1}-{2}.{3}'.format( bot.path, plugin_name, extra, extension) else: # Open from configuration dictionary try: config = bot.configurations[plugin_name] except KeyError: raise CBException( ""Plugin {} not found in the configurations dictionary."".format(plugin_name)) try: if key: return config[key] else: return config except KeyError: raise CBException(""Key {} not found in the configuration file."".format(key)) try: with open(filename, 'r') as config_file: if extension.lower() == 'json': return json.load(config_file) else: return config_file.read() except FileNotFoundError: raise CBException(""File {} not found."".format(filename)) except Exception as e: raise CBException(""Failed to read {} properly."".format(filename), e=e) " Make path to version file relative,"from setuptools import setup, find_packages import sys, os _DIR_OF_THIS_SCRIPT = os.path.split(__file__)[0] _VERSION_FILE_NAME = 'version.txt' _VERSION_FILE_PATH = os.path.join(_DIR_OF_THIS_SCRIPT, _VERSION_FILE_NAME) with open(_VERSION_FILE_PATH, 'r') as fh: version = fh.read().strip() with open('README.md', 'r') as fh: long_description = fh.read() setup(name='adb-enhanced', version=version, description='Swiss-army knife for Android testing and development', long_description=long_description, long_description_content_type='text/markdown', classifiers=['Intended Audience :: Developers'], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='Android ADB developer', author='Ashish Bhatia', author_email='ashishb@ashishb.net', url='https://github.com/ashishb/adb-enhanced', license='Apache', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=True, install_requires=[ # -*- Extra requirements: -*- 'docopt', 'future', ], entry_points={ # -*- Entry points: -*- 'console_scripts': [ 'adbe=adbe:main', ], } ) ","from setuptools import setup, find_packages import sys, os with open('version.txt', 'r') as fh: version = fh.read().strip() with open('README.md', 'r') as fh: long_description = fh.read() setup(name='adb-enhanced', version=version, description='Swiss-army knife for Android testing and development', long_description=long_description, long_description_content_type='text/markdown', classifiers=['Intended Audience :: Developers'], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='Android ADB developer', author='Ashish Bhatia', author_email='ashishb@ashishb.net', url='https://github.com/ashishb/adb-enhanced', license='Apache', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=True, install_requires=[ # -*- Extra requirements: -*- 'docopt', 'future', ], entry_points={ # -*- Entry points: -*- 'console_scripts': [ 'adbe=adbe:main', ], } ) " "Make sure field names start with a letter So that properties like _item and _template and any we might add later to the extracted item can't be overwritten.","import Ember from 'ember'; import NotificationHandler from '../mixins/notification-handler'; export default Ember.Component.extend(NotificationHandler, { item: null, itemFields: null, extractionTypes: [], updateFields: function() { this.set('itemFields', (this.getWithDefault('item.fields', []) || []).copy()); }.on('init'), actions: { addField: function() { this.sendAction('addField', this.get('item')); this.updateFields(); }, deleteField: function(field) { this.sendAction('deleteField', this.get('item'), field); this.updateFields(); }, delete: function() { this.sendAction('delete', this.get('item')); }, editField: function(text, index) { // Ensuring that field names start with a letter prevents overwriting // _item, _template and any future ""protected"" property we might // add to extracted items. if (text === 'url' || !/^[a-z]/i.test(text)) { var field = this.get('item.fields').get(index); if (field) { field.set('name', this.get('itemFields').get(index).name); this.get('item.fields').replace(index, 1, [field]); } this.showErrorNotification(text === 'url' ? 'Naming a field ""url"" is not allowed as there is already a field with this name' : 'Field names must start with a letter' ); return; } this.updateFields(); } } }); ","import Ember from 'ember'; import NotificationHandler from '../mixins/notification-handler'; export default Ember.Component.extend(NotificationHandler, { item: null, itemFields: null, extractionTypes: [], updateFields: function() { this.set('itemFields', (this.getWithDefault('item.fields', []) || []).copy()); }.on('init'), actions: { addField: function() { this.sendAction('addField', this.get('item')); this.updateFields(); }, deleteField: function(field) { this.sendAction('deleteField', this.get('item'), field); this.updateFields(); }, delete: function() { this.sendAction('delete', this.get('item')); }, editField: function(text, index) { if (text === 'url') { var field = this.get('item.fields').get(index); if (field) { field.set('name', this.get('itemFields').get(index).name); this.get('item.fields').replace(index, 1, [field]); } this.showErrorNotification('Naming a field ""url"" is not allowed as there is already a field with this name'); return; } this.updateFields(); } } }); " Use array() instead of [] for older php versions,"<?php /* * This file is part of the Ruler package, an OpenSky project. * * (c) 2011 OpenSky Project Inc * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Ruler; /** * @author Jordan Raub <jordan@raub.me> */ abstract class Operator { const UNARY = 'UNARY'; const BINARY = 'BINARY'; const MULTIPLE = 'MULTIPLE'; protected $operands = array(); /** * @param array $operands */ public function __construct() { foreach (func_get_args() as $operand) { $this->addOperand($operand); } } public function getOperands() { switch ($this->getOperandCardinality()) { case self::UNARY: if (1 != count($this->operands)) { throw new \LogicException(get_class($this) . ' takes only 1 operand'); } break; case self::BINARY: if (2 != count($this->operands)) { throw new \LogicException(get_class($this) . ' takes 2 operands'); } break; case self::MULTIPLE: if (0 == count($this->operands)) { throw new \LogicException(get_class($this) . ' takes at least 1 operand'); } break; } return $this->operands; } abstract public function addOperand($operand); abstract protected function getOperandCardinality(); } ","<?php /* * This file is part of the Ruler package, an OpenSky project. * * (c) 2011 OpenSky Project Inc * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Ruler; /** * @author Jordan Raub <jordan@raub.me> */ abstract class Operator { const UNARY = 'UNARY'; const BINARY = 'BINARY'; const MULTIPLE = 'MULTIPLE'; protected $operands = []; /** * @param array $operands */ public function __construct() { foreach (func_get_args() as $operand) { $this->addOperand($operand); } } public function getOperands() { switch ($this->getOperandCardinality()) { case self::UNARY: if (1 != count($this->operands)) { throw new \LogicException(get_class($this) . ' takes only 1 operand'); } break; case self::BINARY: if (2 != count($this->operands)) { throw new \LogicException(get_class($this) . ' takes 2 operands'); } break; case self::MULTIPLE: if (0 == count($this->operands)) { throw new \LogicException(get_class($this) . ' takes at least 1 operand'); } break; } return $this->operands; } abstract public function addOperand($operand); abstract protected function getOperandCardinality(); } " Resolve promise with image value in image loader,"'use strict'; import $ from 'jquery'; export default class ImageLoader { constructor(dataSrcAttr) { this.dataSrcAttr = dataSrcAttr || 'data-preload-src'; } isInlineImage($el) { return $el.is('img'); } getDataSrc($el) { return $el.attr(this.dataSrcAttr); } setInlineImageSrc($el, src) { $el.attr('src', src); } setBackgroundImageUrl($el, src) { var val = `url(${src})`; $el.css({'background-image': val}); } setSrc($el, src) { if (this.isInlineImage($el)) { this.setInlineImageSrc($el, src); } else { this.setBackgroundImageUrl($el, src); } } loadImage($image) { return new Promise((resolve, reject) => { var img = new Image(), src = this.getDataSrc($image); img.src = src; img.addEventListener('load', () => { this.setSrc($image, src); resolve($image); }); img.addEventListener('error', () => { reject(`Error loading image src ${src}`); }); }); } loadImages($images) { var len = $images.length, promises = []; for (let i = 0; i < len; i++) { let $image = $($images[i]); var promise = this.loadImage($image); promises.push(promise); } return Promise.all(promises); } } ","'use strict'; import $ from 'jquery'; export default class ImageLoader { constructor(dataSrcAttr) { this.dataSrcAttr = dataSrcAttr || 'data-preload-src'; } isInlineImage($el) { return $el.is('img'); } getDataSrc($el) { return $el.attr(this.dataSrcAttr); } setInlineImageSrc($el, src) { $el.attr('src', src); } setBackgroundImageUrl($el, src) { var val = `url(${src})`; $el.css({'background-image': val}); } setSrc($el, src) { if (this.isInlineImage($el)) { this.setInlineImageSrc($el, src); } else { this.setBackgroundImageUrl($el, src); } } loadImage($image) { return new Promise((resolve, reject) => { var img = new Image(), src = this.getDataSrc($image); img.src = src; img.addEventListener('load', () => { this.setSrc($image, src); resolve(); }); img.addEventListener('error', () => { reject(`Error loading image src ${src}`); }); }); } loadImages($images) { var len = $images.length, promises = []; for (let i = 0; i < len; i++) { let $image = $($images[i]); var promise = this.loadImage($image); promises.push(promise); } return Promise.all(promises); } } " Disable trust all servers by default.,"package org.littleshoot.proxy.mitm; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSession; import org.littleshoot.proxy.MitmManager; /** * {@link MitmManager} that uses the given host name to create a dynamic * certificate for. If a port is given, it will be truncated. */ public class HostNameMitmManager implements MitmManager { private BouncyCastleSslEngineSource sslEngineSource; public HostNameMitmManager() throws RootCertificateException { this(new Authority()); } public HostNameMitmManager(Authority authority) throws RootCertificateException { try { boolean trustAllServers = false; boolean sendCerts = true; sslEngineSource = new BouncyCastleSslEngineSource(authority, trustAllServers, sendCerts); } catch (final Exception e) { throw new RootCertificateException( ""Errors during assembling root CA."", e); } } public SSLEngine serverSslEngine() { return sslEngineSource.newSslEngine(); } public SSLEngine clientSslEngineFor(SSLSession serverSslSession, String serverHostAndPort) { try { String serverName = serverHostAndPort.split("":"")[0]; SubjectAlternativeNameHolder san = new SubjectAlternativeNameHolder(); return sslEngineSource.createCertForHost(serverName, san); } catch (Exception e) { throw new FakeCertificateException( ""Creation dynamic certificate failed for "" + serverHostAndPort, e); } } } ","package org.littleshoot.proxy.mitm; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSession; import org.littleshoot.proxy.MitmManager; /** * {@link MitmManager} that uses the given host name to create a dynamic * certificate for. If a port is given, it will be truncated. */ public class HostNameMitmManager implements MitmManager { private BouncyCastleSslEngineSource sslEngineSource; public HostNameMitmManager() throws RootCertificateException { this(new Authority()); } public HostNameMitmManager(Authority authority) throws RootCertificateException { try { sslEngineSource = new BouncyCastleSslEngineSource(authority, true, true); } catch (final Exception e) { throw new RootCertificateException( ""Errors during assembling root CA."", e); } } public SSLEngine serverSslEngine() { return sslEngineSource.newSslEngine(); } public SSLEngine clientSslEngineFor(SSLSession serverSslSession, String serverHostAndPort) { try { String serverName = serverHostAndPort.split("":"")[0]; SubjectAlternativeNameHolder san = new SubjectAlternativeNameHolder(); return sslEngineSource.createCertForHost(serverName, san); } catch (Exception e) { throw new FakeCertificateException( ""Creation dynamic certificate failed for "" + serverHostAndPort, e); } } } " Use updated prettier ESLint config,"/* eslint-env node */ module.exports = { root: true, parser: '@typescript-eslint/parser', parserOptions: { ecmaFeatures: { jsx: true, }, ecmaVersion: 2020, sourceType: 'module', }, plugins: ['@typescript-eslint', 'jest', 'react-hooks', 'prettier'], extends: [ 'eslint:recommended', 'plugin:react/recommended', 'plugin:@typescript-eslint/eslint-recommended', 'plugin:@typescript-eslint/recommended', 'plugin:prettier/recommended', 'prettier', ], settings: { react: { version: 'detect', }, }, rules: { 'react/prop-types': 'off', '@typescript-eslint/explicit-function-return-type': 'off', '@typescript-eslint/explicit-module-boundary-types': 'off', '@typescript-eslint/no-unused-vars': 'off', '@typescript-eslint/member-delimiter-style': 'off', '@typescript-eslint/no-explicit-any': 'off', 'react-hooks/rules-of-hooks': 'error', 'react-hooks/exhaustive-deps': 'warn', }, overrides: [ { files: ['*.test.ts', '*.test.tsx'], env: { 'jest/globals': true, }, }, { files: ['*.tsx'], rules: { 'react/react-in-jsx-scope': 'error', }, }, ], } ","/* eslint-env node */ module.exports = { root: true, parser: '@typescript-eslint/parser', parserOptions: { ecmaFeatures: { jsx: true, }, ecmaVersion: 2020, sourceType: 'module', }, plugins: ['@typescript-eslint', 'jest', 'react-hooks', 'prettier'], extends: [ 'eslint:recommended', 'plugin:react/recommended', 'plugin:@typescript-eslint/eslint-recommended', 'plugin:@typescript-eslint/recommended', 'plugin:prettier/recommended', 'prettier/react', ], settings: { react: { version: 'detect', }, }, rules: { 'react/prop-types': 'off', '@typescript-eslint/explicit-function-return-type': 'off', '@typescript-eslint/explicit-module-boundary-types': 'off', '@typescript-eslint/no-unused-vars': 'off', '@typescript-eslint/member-delimiter-style': 'off', '@typescript-eslint/no-explicit-any': 'off', 'react-hooks/rules-of-hooks': 'error', 'react-hooks/exhaustive-deps': 'warn', }, overrides: [ { files: ['*.test.ts', '*.test.tsx'], env: { 'jest/globals': true, }, }, { files: ['*.tsx'], rules: { 'react/react-in-jsx-scope': 'error', }, }, ], } " Remove unused $window and $document,"/*jslint node: true */ /*global ZeroClipboard */ 'use strict'; angular.module('ngClipboard', []). provider('ngClip', function() { var self = this; this.path = '//cdnjs.cloudflare.com/ajax/libs/zeroclipboard/1.3.2/ZeroClipboard.swf'; return { setPath: function(newPath) { self.path = newPath; }, $get: function() { return { path: self.path }; } }; }). run(['ngClip', function(ngClip) { ZeroClipboard.config({ moviePath: ngClip.path, trustedDomains: [""*""], allowScriptAccess: ""always"", forceHandCursor: true }); }]). directive('clipCopy', ['ngClip', function (ngClip) { return { scope: { clipCopy: '&', clipClick: '&' }, restrict: 'A', link: function (scope, element, attrs) { // Create the clip object var clip = new ZeroClipboard(element); clip.on( 'load', function(client) { var onMousedown = function (client) { client.setText(scope.$eval(scope.clipCopy)); if (angular.isDefined(attrs.clipClick)) { scope.$apply(scope.clipClick); } }; client.on('mousedown', onMousedown); scope.$on('$destroy', function() { client.off('mousedown', onMousedown); client.unclip(element); }); }); } }; }]); ","/*jslint node: true */ /*global ZeroClipboard */ 'use strict'; angular.module('ngClipboard', []). provider('ngClip', function() { var self = this; this.path = '//cdnjs.cloudflare.com/ajax/libs/zeroclipboard/1.3.2/ZeroClipboard.swf'; return { setPath: function(newPath) { self.path = newPath; }, $get: function() { return { path: self.path }; } }; }). run(['$document', 'ngClip', function($document, ngClip) { ZeroClipboard.config({ moviePath: ngClip.path, trustedDomains: [""*""], allowScriptAccess: ""always"", forceHandCursor: true }); }]). directive('clipCopy', ['$window', 'ngClip', function ($window, ngClip) { return { scope: { clipCopy: '&', clipClick: '&' }, restrict: 'A', link: function (scope, element, attrs) { // Create the clip object var clip = new ZeroClipboard(element); clip.on( 'load', function(client) { var onMousedown = function (client) { client.setText(scope.$eval(scope.clipCopy)); if (angular.isDefined(attrs.clipClick)) { scope.$apply(scope.clipClick); } }; client.on('mousedown', onMousedown); scope.$on('$destroy', function() { client.off('mousedown', onMousedown); client.unclip(element); }); }); } }; }]); " Add links to status filtering,"@extends('layouts.default') @section('content') <h1>Support Tickets</h1> <div class=""statuses""> @foreach($statuses as $status) <a class=""btn btn-default"" role=""button"" href=""/tickets/status/{{ $status }}"">{{ $status }}</a> @endforeach </div> <table class=""table table-striped table-hover""> <thead> <th>Title</th> <th>Priority</th> <th>Status</th> <th>Replies</th> <th>Owner</th> <th>Updated At</th> </thead> <tbody> @foreach ($tickets as $ticket) @if (Sentry::inGroup(Sentry::findGroupByName('Admins')) || $ticket->owner_id == Sentry::getUser()->id) <tr> <td> <a href=""{{ action('TicketsController@show', array($ticket->id)) }}""> {{ $ticket->title }} </a> </td> <td> {{ $ticket->priority->title }} </td> <td> {{ $ticket->status->title }} </td> <td> {{ $ticket->replies }} </td> <td> {{ $ticket->owner->username }} </td> <td> {{ $ticket->updated_at }} </td> </tr> @endif @endforeach </tbody> </table> @stop","@extends('layouts.default') @section('content') <h1>Support Tickets</h1> <table class=""table table-striped table-hover""> <thead> <th>Title</th> <th>Priority</th> <th>Status</th> <th>Replies</th> <th>Owner</th> <th>Updated At</th> </thead> <tbody> @foreach ($tickets as $ticket) @if (Sentry::inGroup(Sentry::findGroupByName('Admins')) || $ticket->owner_id == Sentry::getUser()->id) <tr> <td> <a href=""{{ action('TicketsController@show', array($ticket->id)) }}""> {{ $ticket->title }} </a> </td> <td> {{ $ticket->priority->title }} </td> <td> {{ $ticket->status->title }} </td> <td> {{ $ticket->replies }} </td> <td> {{ $ticket->owner->username }} </td> <td> {{ $ticket->updated_at }} </td> </tr> @endif @endforeach </tbody> </table> @stop" "Stop propagation on file input click events, so we don't infinitely loop.","/* global angular: true, FileReader: true */ angular.module('webPGQ.directives') .directive('openFile', function() { function link(scope, element)//, attrs) { var input = element.find('input'); input.click(function(event) { event.stopPropagation(); }); input.change(function() { var file = this.files[0]; console.log(""Loading file:"", file); scope.$apply(function() { scope.loading = true; }); var reader = new FileReader(); reader.onload = function(ev) { scope.$apply(function() { console.log(""Loaded file "" + file.name + "".""); scope.onOpen({file: file, content: ev.target.result}); scope.loading = false; }); }; // end reader.onload reader.readAsText(file); }); element.click(function() { input.click(); }); } // end link return { restrict: 'E', scope: { onOpen: '&', class: '@' }, replace: true, link: link, templateUrl: '/js/directives/open-file.html' }; }); ","/* global angular: true, FileReader: true */ angular.module('webPGQ.directives') .directive('openFile', function() { function link(scope, element)//, attrs) { var input = element.find('input'); input.change(function() { var file = this.files[0]; console.log(""Loading file:"", file); scope.$apply(function() { scope.loading = true; }); var reader = new FileReader(); reader.onload = function(ev) { scope.$apply(function() { console.log(""Loaded file "" + file.name + "".""); scope.onOpen({file: file, content: ev.target.result}); scope.loading = false; }); }; // end reader.onload reader.readAsText(file); }); element.click(function() { input.click(); }); } // end link return { restrict: 'E', scope: { onOpen: '&', class: '@' }, replace: true, link: link, templateUrl: '/js/directives/open-file.html' }; }); " Add exhibitor_s3config option to Zookeeper creation,"from tyr.servers.server import Server class ZookeeperServer(Server): SERVER_TYPE = 'zookeeper' CHEF_RUNLIST = ['role[RoleZookeeper]'] IAM_ROLE_POLICIES = [ 'allow-describe-instances', 'allow-describe-tags', 'allow-volume-control' ] def __init__(self, group=None, server_type=None, instance_type=None, environment=None, ami=None, region=None, role=None, keypair=None, availability_zone=None, security_groups=None, block_devices=None, chef_path=None, subnet_id=None, dns_zones=None, exhibitor_s3config=None): if server_type is None: server_type = self.SERVER_TYPE self.exhibitor_s3config = exhibitor_s3config super(ZookeeperServer, self).__init__(group, server_type, instance_type, environment, ami, region, role, keypair, availability_zone, security_groups, block_devices, chef_path, subnet_id, dns_zones) def bake(self): super(ZookeeperServer, self).bake() with self.chef_api: if self.exhibitor_s3config: self.chef_node.attributes.set_dotted('exhibitor.cli.s3config', self.exhibitor_s3config) self.log.info('Set exhibitor.cli.s3config to {}' .format(self.exhibitor_s3config)) else: self.log.info('exhibitor.cli.s3config not set. Using default.') self.chef_node.save() self.log.info('Saved the Chef Node configuration') ","from tyr.servers.server import Server class ZookeeperServer(Server): SERVER_TYPE = 'zookeeper' CHEF_RUNLIST = ['role[RoleZookeeper]'] IAM_ROLE_POLICIES = [ 'allow-describe-instances', 'allow-describe-tags', 'allow-volume-control' ] def __init__(self, group=None, server_type=None, instance_type=None, environment=None, ami=None, region=None, role=None, keypair=None, availability_zone=None, security_groups=None, block_devices=None, chef_path=None, subnet_id=None, dns_zones=None): if server_type is None: server_type = self.SERVER_TYPE super(ZookeeperServer, self).__init__(group, server_type, instance_type, environment, ami, region, role, keypair, availability_zone, security_groups, block_devices, chef_path, subnet_id, dns_zones) " "Fix search:reindex to work with ""doc""","<?php namespace App\Console\Commands; use Elasticsearch; use App\Console\Helpers\Indexer; use Aic\Hub\Foundation\AbstractCommand as BaseCommand; class SearchReindex extends BaseCommand { use Indexer; protected $signature = 'search:reindex {dest : The prefix of the indexes to copy documents to} {source? : The prefix of the indexes to copy documents from}'; protected $description = 'Copy documents from one set of indices to another'; public function handle() { $dest = $this->argument('dest'); $source = $this->argument('source') ?? env('ELASTICSEARCH_INDEX'); $models = app('Search')->getSearchableModels(); foreach ($models as $model) { $endpoint = app('Resources')->getEndpointForModel($model); $index = $source . '-' . $endpoint; $params = [ 'wait_for_completion' => false, 'body' => [ 'source' => [ 'index' => $index, 'size' => 100, ], 'dest' => [ 'index' => $dest . '-' . $endpoint, 'type' => 'doc', ], ], ]; $return = Elasticsearch::reindex($params); $this->info('Reindex from ' . $index . 'has started. You can monitor the process here: ' . $this->baseUrl() . '/_tasks/' . $return['task']); } } } ","<?php namespace App\Console\Commands; use Elasticsearch; use App\Console\Helpers\Indexer; use Aic\Hub\Foundation\AbstractCommand as BaseCommand; class SearchReindex extends BaseCommand { use Indexer; protected $signature = 'search:reindex {dest : The prefix of the indexes to copy documents to} {source? : The prefix of the indexes to copy documents from}'; protected $description = 'Copy documents from one set of indices to another'; public function handle() { $dest = $this->argument('dest'); $source = $this->argument('source') ?? env('ELASTICSEARCH_INDEX'); $models = app('Search')->getSearchableModels(); foreach ($models as $model) { $endpoint = app('Resources')->getEndpointForModel($model); $index = $source . '-' . $endpoint; $params = [ 'wait_for_completion' => false, 'body' => [ 'source' => [ 'index' => $index, 'size' => 100, ], 'dest' => [ 'index' => $dest . '-' . $endpoint, ], ], ]; $return = Elasticsearch::reindex($params); $this->info('Reindex from ' . $index . 'has started. You can monitor the process here: ' . $this->baseUrl() . '/_tasks/' . $return['task']); } } } " Fix: Allow to clear cookie when the value is null,"<?php /* * Copyright (c) 2016 Refinery29, Inc. * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Refinery29\Piston; use Assert\Assertion; class CookieJar { /** * @var array */ private $cookies; /** * @param array $cookies */ public function __construct(array $cookies = []) { Assertion::allString(array_keys($cookies), 'CookieJar must be instantiated with an associative array'); $this->cookies = $cookies; } /** * @param string $key * * @return mixed */ public function get($key) { return isset($this->cookies[$key]) ? $this->cookies[$key] : null ; } /** * @param string $key * @param mixed $value */ public function set($key, $value) { $this->cookies[$key] = $value; } /** * @param string $key */ public function clear($key) { if (!array_key_exists($key, $this->cookies)) { return; } unset($this->cookies[$key]); } public function clearAll() { $this->cookies = []; } /** * @return array */ public function all() { return $this->cookies; } } ","<?php /* * Copyright (c) 2016 Refinery29, Inc. * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Refinery29\Piston; use Assert\Assertion; class CookieJar { /** * @var array */ private $cookies; /** * @param array $cookies */ public function __construct(array $cookies = []) { Assertion::allString(array_keys($cookies), 'CookieJar must be instantiated with an associative array'); $this->cookies = $cookies; } /** * @param string $key * * @return mixed */ public function get($key) { return isset($this->cookies[$key]) ? $this->cookies[$key] : null ; } /** * @param string $key * @param mixed $value */ public function set($key, $value) { $this->cookies[$key] = $value; } /** * @param string $key */ public function clear($key) { if (isset($this->cookies[$key])) { unset($this->cookies[$key]); } } public function clearAll() { $this->cookies = []; } /** * @return array */ public function all() { return $this->cookies; } } " Fix for error on creating new post in case of postgreql,"<?php namespace App\Http\Requests\Admin; use App\Rules\CanBeAuthor; use App\User; use Carbon\Carbon; use Illuminate\Foundation\Http\FormRequest; class PostsRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Prepare the data for validation. * * @return void */ protected function prepareForValidation() { $this->merge([ 'slug' => str_slug($this->input('title')) ]); $this->merge([ 'posted_at' => Carbon::parse($this->input('posted_at')) ]); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'title' => 'required', 'content' => 'required', 'posted_at' => 'required|date', 'author_id' => ['required', 'exists:users,id', new CanBeAuthor], 'slug' => 'unique:posts,slug,' . (optional($this->post)->id ?: 'NULL'), 'thumbnail' => 'image', ]; } } ","<?php namespace App\Http\Requests\Admin; use App\Rules\CanBeAuthor; use App\User; use Carbon\Carbon; use Illuminate\Foundation\Http\FormRequest; class PostsRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Prepare the data for validation. * * @return void */ protected function prepareForValidation() { $this->merge([ 'slug' => str_slug($this->input('title')) ]); $this->merge([ 'posted_at' => Carbon::parse($this->input('posted_at')) ]); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'title' => 'required', 'content' => 'required', 'posted_at' => 'required|date', 'author_id' => ['required', 'exists:users,id', new CanBeAuthor], 'slug' => 'unique:posts,slug,' . optional($this->post)->id, 'thumbnail' => 'image', ]; } } " Add visual separator between outputs.,"#! /usr/bin/env python from __future__ import print_function import os import sys import json def pretty_print(equation): print(equation[""description""][""terse""]) eqn_dict = equation[""unicode-pretty-print""] equation_text = eqn_dict[""multiline""] for line in equation_text: print(line) if ""parameters"" in eqn_dict: print(""where:"") for param_dict in eqn_dict[""parameters""]: symbol = param_dict[""symbol""] label = param_dict[""label""] print(symbol,'=',label) def main(query): here = sys.path[0] json_dir = os.path.join(here, 'equajson') for filename in os.listdir(json_dir): if not filename.endswith('.json'): continue filepath = os.path.join(json_dir, filename) with open(filepath) as json_file: try: equation = json.load(json_file) except ValueError: sys.stderr.write(""Invalid JSON for file: `{}'\n"".format(json_file.name)) continue # try the next file description = equation[""description""][""verbose""] if query.lower() in description.lower(): pretty_print(equation) print('-'*80) if __name__ == '__main__': num_args = len(sys.argv) - 1 if num_args != 1: sys.stderr.write(""Usage: python ""+sys.argv[0]+"" query""+'\n') sys.exit(1) main(sys.argv[1]) ","#! /usr/bin/env python from __future__ import print_function import os import sys import json def pretty_print(equation): print(equation[""description""][""terse""]) eqn_dict = equation[""unicode-pretty-print""] equation_text = eqn_dict[""multiline""] for line in equation_text: print(line) if ""parameters"" in eqn_dict: print(""where:"") for param_dict in eqn_dict[""parameters""]: symbol = param_dict[""symbol""] label = param_dict[""label""] print(symbol,'=',label) def main(query): here = sys.path[0] json_dir = os.path.join(here, 'equajson') for filename in os.listdir(json_dir): if not filename.endswith('.json'): continue filepath = os.path.join(json_dir, filename) with open(filepath) as json_file: try: equation = json.load(json_file) except ValueError: sys.stderr.write(""Invalid JSON for file: `{}'\n"".format(json_file.name)) continue # try the next file description = equation[""description""][""verbose""] if query.lower() in description.lower(): pretty_print(equation) print() if __name__ == '__main__': num_args = len(sys.argv) - 1 if num_args != 1: sys.stderr.write(""Usage: python ""+sys.argv[0]+"" query""+'\n') sys.exit(1) main(sys.argv[1]) " Hide section on demand for the overview page,"import React from 'react'; import PropTypes from 'prop-types'; import { hasPermission } from 'proton-shared/lib/helpers/permissions'; import LinkItem from './LinkItem'; const Sections = ({ route, sections = [], text, permissions = [], pagePermissions }) => { return ( <ul className=""unstyled mt0-5""> {sections.length ? ( sections .reduce((acc, { text, id, hide }) => { if (!hide) { acc.push({ text, id, route: `${route}#${id}` }); } return acc; }, []) .map(({ text, id, route, permissions: sectionPermissions }) => { return ( <li key={id}> <LinkItem route={route} text={text} permission={hasPermission(permissions, pagePermissions, sectionPermissions)} /> </li> ); }) ) : ( <li> <LinkItem route={route} text={text} permission={hasPermission(permissions, pagePermissions)} /> </li> )} </ul> ); }; Sections.propTypes = { route: PropTypes.string, sections: PropTypes.array, text: PropTypes.string, permissions: PropTypes.array, pagePermissions: PropTypes.array }; export default Sections; ","import React from 'react'; import PropTypes from 'prop-types'; import { hasPermission } from 'proton-shared/lib/helpers/permissions'; import LinkItem from './LinkItem'; const Sections = ({ route, sections = [], text, permissions = [], pagePermissions }) => { return ( <ul className=""unstyled mt0-5""> {sections.length ? ( sections .reduce((acc, { text, id }) => { acc.push({ text, id, route: `${route}#${id}` }); return acc; }, []) .map(({ text, id, route, permissions: sectionPermissions }) => { return ( <li key={id}> <LinkItem route={route} text={text} permission={hasPermission(permissions, pagePermissions, sectionPermissions)} /> </li> ); }) ) : ( <li> <LinkItem route={route} text={text} permission={hasPermission(permissions, pagePermissions)} /> </li> )} </ul> ); }; Sections.propTypes = { route: PropTypes.string, sections: PropTypes.array, text: PropTypes.string, permissions: PropTypes.array, pagePermissions: PropTypes.array }; export default Sections; " CHANGE: Add functionality to call a methode,"<?php /** * sfOrmBreadcrumbsDoctrine * * @package sfOrmBreadcrumbsPlugin * @subpackage lib * @author Nicolò Pignatelli <info@nicolopignatelli.com> */ class sfOrmBreadcrumbsDoctrine extends sfOrmBreadcrumbs { protected function buildBreadcrumb($item) { $request = sfContext::getInstance()->getRequest(); $routing = sfContext::getInstance()->getRouting(); if(isset($item['model']) && $item['model'] == true) { $object = $request->getAttribute('sf_route')->getObject(); if(isset($item['subobject'])) { $subobject = $object->get($item['subobject']); $route_object = $subobject; } else { $route_object = $object; } $name = preg_replace('/%(\w+)%/e', '""$1""', $item['name']); if(method_exists($route_object, $name)) { $name = $route_object->$name(); } else { $name = $route_object->get($name); } $breadcrumb = array('name' => $name, 'url' => isset($item['route']) ? $routing->generate($item['route'], $route_object) : null); } else { $url = isset($item['route']) ? $routing->generate($item['route']) : null; $breadcrumb = array('name' => $item['name'], 'url' => $url); } $case = $this->getCaseForItem($item); $breadcrumb['name'] = $this->switchCase($breadcrumb['name'], $case); return $breadcrumb; } } ?>","<?php /** * sfOrmBreadcrumbsDoctrine * * @package sfOrmBreadcrumbsPlugin * @subpackage lib * @author Nicolò Pignatelli <info@nicolopignatelli.com> */ class sfOrmBreadcrumbsDoctrine extends sfOrmBreadcrumbs { protected function buildBreadcrumb($item) { $request = sfContext::getInstance()->getRequest(); $routing = sfContext::getInstance()->getRouting(); if(isset($item['model']) && $item['model'] == true) { $object = $request->getAttribute('sf_route')->getObject(); if(isset($item['subobject'])) { $subobject = $object->get($item['subobject']); $route_object = $subobject; } else { $route_object = $object; } $name = preg_replace('/%(\w+)%/e', '$object->get(""$1"")', $item['name']); $breadcrumb = array('name' => $name, 'url' => $routing->generate($item['route'], $route_object)); } else { $url = isset($item['route']) ? $routing->generate($item['route']) : null; $breadcrumb = array('name' => $item['name'], 'url' => $url); } $case = $this->getCaseForItem($item); $breadcrumb['name'] = $this->switchCase($breadcrumb['name'], $case); return $breadcrumb; } } ?>" Use old style string format method to avoid formatting warning,"''' @date 2013-5-9 @author Hong-She Liang <starofrainnight@gmail.com> ''' import sys import os # Import the global logging unit, not our logging . global_logging = __import__('logging') def load_default_config(): arguments = { 'level': None, 'filename': None, 'filemode': None, 'format': None, 'datefmt': None, 'style': None, } for k in list(arguments.keys()): try: envionment_text = 'PYTHON_LOGGING_%s' % k.upper() arguments[k] = os.environ[envionment_text] except ValueError: pass except KeyError: pass # Remove all arguments that is None value. keys = list(arguments.keys()) for k in keys: if arguments[k] is None: del arguments[k] # Set default level to logging.INFO . if 'level' not in list(arguments.keys()): arguments['level'] = global_logging.INFO global_logging.basicConfig(**arguments) # Added console handler only there have filename argument. if 'filename' in list(arguments.keys()): global_logging.getLogger().addHandler(global_logging.StreamHandler(sys.stdout)) ","''' @date 2013-5-9 @author Hong-She Liang <starofrainnight@gmail.com> ''' import sys import os # Import the global logging unit, not our logging . global_logging = __import__('logging') def load_default_config(): arguments = { 'level': None, 'filename': None, 'filemode': None, 'format': None, 'datefmt': None, 'style': None, } for k in list(arguments.keys()): try: envionment_text = 'PYTHON_LOGGING_{}'.format(k.upper()) arguments[k] = os.environ[envionment_text] except ValueError: pass except KeyError: pass # Remove all arguments that is None value. keys = list(arguments.keys()) for k in keys: if arguments[k] is None: del arguments[k] # Set default level to logging.INFO . if 'level' not in list(arguments.keys()): arguments['level'] = global_logging.INFO global_logging.basicConfig(**arguments) # Added console handler only there have filename argument. if 'filename' in list(arguments.keys()): global_logging.getLogger().addHandler(global_logging.StreamHandler(sys.stdout)) " Remove debug print on getVersion,"import os import re from citrination_client.base import * from citrination_client.search import * from citrination_client.data import * from citrination_client.models import * from citrination_client.views.descriptors import * from .client import CitrinationClient from pkg_resources import get_distribution, DistributionNotFound def __get_version(): """""" Returns the version of this package, whether running from source or install :return: The version of this package """""" try: # Try local first, if missing setup.py, then use pkg info here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, ""../setup.py"")) as fp: version_file = fp.read() version_match = re.search(r""version=['\""]([^'\""]*)['\""]"", version_file, re.M) if version_match: return version_match.group(1) except IOError: pass try: _dist = get_distribution('citrination_client') # Normalize case for Windows systems dist_loc = os.path.normcase(_dist.location) here = os.path.normcase(__file__) if not here.startswith(os.path.join(dist_loc, 'citrination_client')): # not installed, but there is another version that *is* raise DistributionNotFound except DistributionNotFound: raise RuntimeError(""Unable to find version string."") else: return _dist.version __version__ = __get_version() ","import os import re from citrination_client.base import * from citrination_client.search import * from citrination_client.data import * from citrination_client.models import * from citrination_client.views.descriptors import * from .client import CitrinationClient from pkg_resources import get_distribution, DistributionNotFound def __get_version(): """""" Returns the version of this package, whether running from source or install :return: The version of this package """""" try: # Try local first, if missing setup.py, then use pkg info here = os.path.abspath(os.path.dirname(__file__)) print(""here:""+here) with open(os.path.join(here, ""../setup.py"")) as fp: version_file = fp.read() version_match = re.search(r""version=['\""]([^'\""]*)['\""]"", version_file, re.M) if version_match: return version_match.group(1) except IOError: pass try: _dist = get_distribution('citrination_client') # Normalize case for Windows systems dist_loc = os.path.normcase(_dist.location) here = os.path.normcase(__file__) if not here.startswith(os.path.join(dist_loc, 'citrination_client')): # not installed, but there is another version that *is* raise DistributionNotFound except DistributionNotFound: raise RuntimeError(""Unable to find version string."") else: return _dist.version __version__ = __get_version() " Order MongoForm fields according to the Document,"from django import forms from mongoengine.base import ValidationError from bson.objectid import ObjectId def mongoengine_validate_wrapper(old_clean, new_clean): """""" A wrapper function to validate formdata against mongoengine-field validator and raise a proper django.forms ValidationError if there are any problems. """""" def inner_validate(value): value = old_clean(value) try: new_clean(value) return value except ValidationError, e: raise forms.ValidationError(e) return inner_validate def iter_valid_fields(meta): """"""walk through the available valid fields.."""""" # fetch field configuration and always add the id_field as exclude meta_fields = getattr(meta, 'fields', ()) meta_exclude = getattr(meta, 'exclude', ()) id_field = meta.document._meta.get('id_field', 'id') if type(meta.document._fields.get(id_field)) == ObjectId: meta_exclude += (meta.document._meta.get(id_field),) # walk through meta_fields or through the document fields to keep # meta_fields order in the form if meta_fields: for field_name in meta_fields: field = meta.document._fields.get(field_name) if field: yield (field_name, field) else: for field_name in meta.document._fields_ordered: # skip excluded fields if field_name not in meta_exclude: field = meta.document._fields.get(field_name) yield (field_name, field) ","from django import forms from mongoengine.base import ValidationError from bson.objectid import ObjectId def mongoengine_validate_wrapper(old_clean, new_clean): """""" A wrapper function to validate formdata against mongoengine-field validator and raise a proper django.forms ValidationError if there are any problems. """""" def inner_validate(value): value = old_clean(value) try: new_clean(value) return value except ValidationError, e: raise forms.ValidationError(e) return inner_validate def iter_valid_fields(meta): """"""walk through the available valid fields.."""""" # fetch field configuration and always add the id_field as exclude meta_fields = getattr(meta, 'fields', ()) meta_exclude = getattr(meta, 'exclude', ()) id_field = meta.document._meta.get('id_field', 'id') if type(meta.document._fields.get(id_field)) == ObjectId: meta_exclude += (meta.document._meta.get(id_field),) # walk through meta_fields or through the document fields to keep # meta_fields order in the form if meta_fields: for field_name in meta_fields: field = meta.document._fields.get(field_name) if field: yield (field_name, field) else: for field_name, field in meta.document._fields.iteritems(): # skip excluded fields if field_name not in meta_exclude: yield (field_name, field) " Allow for multiple events with the @BotModule.event decorator.,"import logging import discord from applebot.utils import caller_attr log = logging.getLogger(__name__) class BotModule(object): def __init__(self, client=None): self.__name__ = None self.client = client or caller_attr('client', levels=3) or discord.Client() self.__register_handlers() def __register_handlers(self): for method in [getattr(self, m) for m in dir(self) if '__' not in m]: if callable(method): commands = method.__dict__.get('command_names', ()) for command in commands: log.debug('Adding command \'{}\' in {}'.format(commands, self.__class__.__name__)) self.client.commands.add(str(command), method) events = method.__dict__.get('event_names', ()) for event in events: log.debug('Registering event \'{}\' from {}'.format(event, self.__class__.__name__)) self.client.events.add(event, method) @staticmethod def event(*events): def inner_decorator(method): method.event_names = events return method return inner_decorator @staticmethod def command(*commands): def inner_decorator(method): method.command_names = commands return method return inner_decorator ","import logging import discord from applebot.utils import caller_attr log = logging.getLogger(__name__) class BotModule(object): def __init__(self, client=None): self.__name__ = None self.client = client or caller_attr('client', levels=3) or discord.Client() self.__register_handlers() def __register_handlers(self): for method in [getattr(self, m) for m in dir(self) if '__' not in m]: if callable(method): commands = method.__dict__.get('command_names') event = method.__dict__.get('event_name') if commands: for command in commands: log.debug('Adding command \'{}\' in {}'.format(commands, self.__class__.__name__)) self.client.commands.add(str(command), method) if event: log.debug('Registering event \'{}\' from {}'.format(event, self.__class__.__name__)) self.client.events.add(event, method) @staticmethod def event(event): def inner_decorator(method): method.event_name = str(event) return method return inner_decorator @staticmethod def command(*commands): def inner_decorator(method): method.command_names = commands return method return inner_decorator " "Add alias ""state"" for condition type ""status"".","package de.iani.cubequest.conditions; public enum ConditionType { NEGATED(NegatedQuestCondition.class), RENAMED(RenamedCondition.class), GAMEMODE(GameModeCondition.class), MINIMUM_QUEST_LEVEL(MinimumQuestLevelCondition.class), HAVE_QUEST_STATUS(HaveQuestStatusCondition.class), SERVER_FLAG(ServerFlagCondition.class), BE_IN_AREA(BeInAreaCondition.class); public final Class<? extends QuestCondition> concreteClass; public static ConditionType match(String s) { String u = s.toUpperCase(); String l = s.toLowerCase(); try { return valueOf(u); } catch (IllegalArgumentException e) { // ignore } if (l.startsWith(""not"") || l.startsWith(""nicht"") || l.contains(""negated"")) { return NEGATED; } if (l.contains(""rename"")) { return RENAMED; } if (l.startsWith(""gm"")) { return GAMEMODE; } if (l.contains(""level"")) { return MINIMUM_QUEST_LEVEL; } if (l.contains(""status"") || l.contains(""state"")) { return HAVE_QUEST_STATUS; } if (l.contains(""flag"")) { return SERVER_FLAG; } if (l.contains(""area"")) { return BE_IN_AREA; } return null; } private ConditionType(Class<? extends QuestCondition> concreteClass) { this.concreteClass = concreteClass; } } ","package de.iani.cubequest.conditions; public enum ConditionType { NEGATED(NegatedQuestCondition.class), RENAMED(RenamedCondition.class), GAMEMODE(GameModeCondition.class), MINIMUM_QUEST_LEVEL(MinimumQuestLevelCondition.class), HAVE_QUEST_STATUS(HaveQuestStatusCondition.class), SERVER_FLAG(ServerFlagCondition.class), BE_IN_AREA(BeInAreaCondition.class); public final Class<? extends QuestCondition> concreteClass; public static ConditionType match(String s) { String u = s.toUpperCase(); String l = s.toLowerCase(); try { return valueOf(u); } catch (IllegalArgumentException e) { // ignore } if (l.startsWith(""not"") || l.startsWith(""nicht"") || l.contains(""negated"")) { return NEGATED; } if (l.contains(""rename"")) { return RENAMED; } if (l.startsWith(""gm"")) { return GAMEMODE; } if (l.contains(""level"")) { return MINIMUM_QUEST_LEVEL; } if (l.contains(""status"")) { return HAVE_QUEST_STATUS; } if (l.contains(""flag"")) { return SERVER_FLAG; } if (l.contains(""area"")) { return BE_IN_AREA; } return null; } private ConditionType(Class<? extends QuestCondition> concreteClass) { this.concreteClass = concreteClass; } } " Set Accept header explicitly in GitHubChannel,"# -*- coding: utf-8 -*- import json import requests from .base import BaseChannel from ..exceptions import HttpError class GitHubChannel(BaseChannel): def __init__(self, token, owner, repository, base_url=""https://api.github.com"", *args, **kwargs): self.token = token self.url = base_url + ""/repos/"" + owner + ""/"" + repository + ""/issues"" def send(self, message, fail_silently=False, options=None): headers = { ""Accept"": ""application/vnd.github.v3+json"", ""Authorization"": ""token "" + self.token, ""Content-Type"": ""application/json"" } payload = { ""title"": message } self._set_payload_from_options(payload, options, ""github"", [ ""body"", ""milestone"", ""labels"", ""assignees""]) try: response = requests.post(self.url, headers=headers, data=json.dumps(payload)) if response.status_code != requests.codes.created: raise HttpError(response.status_code, response.text) except: if not fail_silently: raise ","# -*- coding: utf-8 -*- import json import requests from .base import BaseChannel from ..exceptions import HttpError class GitHubChannel(BaseChannel): def __init__(self, token, owner, repository, base_url=""https://api.github.com"", *args, **kwargs): self.token = token self.url = base_url + ""/repos/"" + owner + ""/"" + repository + ""/issues"" def send(self, message, fail_silently=False, options=None): headers = { ""Authorization"": ""token "" + self.token, ""Content-Type"": ""application/json"" } payload = { ""title"": message } self._set_payload_from_options(payload, options, ""github"", [ ""body"", ""milestone"", ""labels"", ""assignees""]) try: response = requests.post(self.url, headers=headers, data=json.dumps(payload)) if response.status_code != requests.codes.created: raise HttpError(response.status_code, response.text) except: if not fail_silently: raise " Fix error when there are no orders on the query,"<?php namespace Flarum\Sticky\Handlers; use Flarum\Core\Events\DiscussionSearchWillBePerformed; use Flarum\Categories\CategoryGambit; class StickySearchModifier { public function subscribe($events) { $events->listen('Flarum\Core\Events\DiscussionSearchWillBePerformed', __CLASS__.'@reorderSearch'); } public function reorderSearch(DiscussionSearchWillBePerformed $event) { if ($event->criteria->sort === null) { $query = $event->searcher->query(); if (!is_array($query->orders)) { $query->orders = []; } foreach ($event->searcher->getActiveGambits() as $gambit) { if ($gambit instanceof CategoryGambit) { array_unshift($query->orders, ['column' => 'is_sticky', 'direction' => 'desc']); return; } } $query->leftJoin('users_discussions', function ($join) use ($event) { $join->on('users_discussions.discussion_id', '=', 'discussions.id') ->where('discussions.is_sticky', '=', true) ->where('users_discussions.user_id', '=', $event->criteria->user->id); }); // might be quicker to do a subquery in the order clause than a join? array_unshift( $query->orders, ['type' => 'raw', 'sql' => '(is_sticky AND (users_discussions.read_number IS NULL OR discussions.last_post_number > users_discussions.read_number)) desc'] ); } } } ","<?php namespace Flarum\Sticky\Handlers; use Flarum\Core\Events\DiscussionSearchWillBePerformed; use Flarum\Categories\CategoryGambit; class StickySearchModifier { public function subscribe($events) { $events->listen('Flarum\Core\Events\DiscussionSearchWillBePerformed', __CLASS__.'@reorderSearch'); } public function reorderSearch(DiscussionSearchWillBePerformed $event) { if ($event->criteria->sort === null) { $query = $event->searcher->query(); foreach ($event->searcher->getActiveGambits() as $gambit) { if ($gambit instanceof CategoryGambit) { array_unshift($query->orders, ['column' => 'is_sticky', 'direction' => 'desc']); return; } } $query->leftJoin('users_discussions', function ($join) use ($event) { $join->on('users_discussions.discussion_id', '=', 'discussions.id') ->where('discussions.is_sticky', '=', true) ->where('users_discussions.user_id', '=', $event->criteria->user->id); }); // might be quicker to do a subquery in the order clause than a join? array_unshift( $query->orders, ['type' => 'raw', 'sql' => '(is_sticky AND (users_discussions.read_number IS NULL OR discussions.last_post_number > users_discussions.read_number)) desc'] ); } } } " "Add HHVM >= 3.8.0 support in the artisan serve command via Proxygen Web Server Now we can run Laravel development server with HHVM, like this: hhvm artisan serve","<?php namespace Illuminate\Foundation\Console; use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; class ServeCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'serve'; /** * The console command description. * * @var string */ protected $description = 'Serve the application on the PHP development server'; /** * Execute the console command. * * @return void */ public function fire() { chdir($this->laravel->publicPath()); $host = $this->input->getOption('host'); $port = $this->input->getOption('port'); $base = $this->laravel->basePath(); $this->info(""Laravel development server started on http://{$host}:{$port}/""); if (defined('HHVM_VERSION') && HHVM_VERSION >= '3.8.0') { passthru('""'.PHP_BINARY.'""'."" -m server -v Server.Type=proxygen -v Server.SourceRoot=\""{$base}\""/ -v Server.IP={$host} -v Server.Port={$port} -v Server.DefaultDocument=server.php -v Server.ErrorDocument404=server.php""); } else { passthru('""'.PHP_BINARY.'""'."" -S {$host}:{$port} \""{$base}\""/server.php""); } } /** * Get the console command options. * * @return array */ protected function getOptions() { return [ ['host', null, InputOption::VALUE_OPTIONAL, 'The host address to serve the application on.', 'localhost'], ['port', null, InputOption::VALUE_OPTIONAL, 'The port to serve the application on.', 8000], ]; } } ","<?php namespace Illuminate\Foundation\Console; use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; class ServeCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'serve'; /** * The console command description. * * @var string */ protected $description = 'Serve the application on the PHP development server'; /** * Execute the console command. * * @return void */ public function fire() { chdir($this->laravel->publicPath()); $host = $this->input->getOption('host'); $port = $this->input->getOption('port'); $base = $this->laravel->basePath(); $this->info(""Laravel development server started on http://{$host}:{$port}/""); passthru('""'.PHP_BINARY.'""'."" -S {$host}:{$port} \""{$base}\""/server.php""); } /** * Get the console command options. * * @return array */ protected function getOptions() { return [ ['host', null, InputOption::VALUE_OPTIONAL, 'The host address to serve the application on.', 'localhost'], ['port', null, InputOption::VALUE_OPTIONAL, 'The port to serve the application on.', 8000], ]; } } " Format support for w.error() if possible.,"(function(global) { 'use strict'; define([ ], function() { // $HEADER$ /** * This will be the <code>warmsea</code> namespace. * @namespace * @alias warmsea */ var w = _.extend({}, _); /** * The unmodified underlying underscore object. */ w._ = w.underscore = _; /** * The version of this WarmseaJS. * @type {string} */ w.VERSION = '$VERSION$'; /** * The global object of the executing environment. * @type {object} */ w.global = global; /** * Save the previous `warmsea`. */ var previousWarmsea = global.warmsea; /** * Return the current `warmsea` and restore the previous global one. * @return {warmsea} This warmsea object. */ w.noConflict = function() { global.warmsea = previousWarmsea; return this; }; /** * A function that throws an error with the message ""Unimplemented"". */ w.unimplemented = function() { w.error('Unimplemented'); }; /** * Throws an Error. * @method * @param {string} msg * @throws {Error} */ w.error = function(msg) { if (w.isFunction(w.format)) { msg = w.format.apply(w, arguments); } throw new Error(msg); }; // $FOOTER$ return w; }); })(this); ","(function(global) { 'use strict'; define([ ], function() { // $HEADER$ /** * This will be the <code>warmsea</code> namespace. * @namespace * @alias warmsea */ var w = _.extend({}, _); /** * The unmodified underlying underscore object. */ w._ = w.underscore = _; /** * The version of this WarmseaJS. * @type {string} */ w.VERSION = '$VERSION$'; /** * The global object of the executing environment. * @type {object} */ w.global = global; /** * Save the previous `warmsea`. */ var previousWarmsea = global.warmsea; /** * Return the current `warmsea` and restore the previous global one. * @return {warmsea} This warmsea object. */ w.noConflict = function() { global.warmsea = previousWarmsea; return this; }; /** * A function that throws an error with the message ""Unimplemented"". */ w.unimplemented = function() { w.error('Unimplemented'); }; /** * Throws an Error. * @method * @param {string} msg * @throws {Error} */ w.error = function(msg) { throw new Error(msg); }; // $FOOTER$ return w; }); })(this); " Add $property to cache key,"<?php class CM_Http_ClientDevice { /** @var \Jenssegers\Agent\Agent */ protected $_parser; /** @var array */ protected $_headerList; /** * @param CM_Http_Request_Abstract $request */ public function __construct(CM_Http_Request_Abstract $request) { $this->_request = $request; $headerList = []; foreach ($request->getHeaders() as $key => $header) { if (substr($key, 0, 8) !== 'content-') { $headerList['HTTP_' . str_replace('-', '_', strtoupper($key))] = $header; } } $this->_parser = new Jenssegers\Agent\Agent($headerList); $this->_headerList = $headerList; } /** * @return bool */ public function isMobile() { $cache = CM_Cache_Local::getInstance(); return $cache->get($cache->key(__METHOD__, $this->_headerList), function () { return $this->_parser->isMobile(); }); } /** * @param string $property * @return string|false */ public function getVersion($property) { $property = (string) $property; $cache = CM_Cache_Local::getInstance(); return $cache->get($cache->key(__METHOD__, $this->_headerList, $property), function () use ($property) { return $this->_parser->version($property); }); } } ","<?php class CM_Http_ClientDevice { /** @var \Jenssegers\Agent\Agent */ protected $_parser; /** @var array */ protected $_headerList; /** * @param CM_Http_Request_Abstract $request */ public function __construct(CM_Http_Request_Abstract $request) { $this->_request = $request; $headerList = []; foreach ($request->getHeaders() as $key => $header) { if (substr($key, 0, 8) !== 'content-') { $headerList['HTTP_' . str_replace('-', '_', strtoupper($key))] = $header; } } $this->_parser = new Jenssegers\Agent\Agent($headerList); $this->_headerList = $headerList; } /** * @return bool */ public function isMobile() { $cache = CM_Cache_Local::getInstance(); return $cache->get($cache->key(__METHOD__, $this->_headerList), function () { return $this->_parser->isMobile(); }); } /** * @param string $property * @return string|false */ public function getVersion($property) { $property = (string) $property; $cache = CM_Cache_Local::getInstance(); return $cache->get($cache->key(__METHOD__, $this->_headerList), function () use ($property) { return $this->_parser->version($property); }); } } " Set the bar low on staging,"from .base import * import os # how many data points are enough to calculate confidence? MINIMUM_SAMPLE_SIZE = 3 # original phrase is good enough for export TRANSCRIPT_PHRASE_POSITIVE_CONFIDENCE_LIMIT = .51 # original phrase needs correction TRANSCRIPT_PHRASE_NEGATIVE_CONFIDENCE_LIMIT = -.51 # correction is good enough to award points and export data TRANSCRIPT_PHRASE_CORRECTION_LOWER_LIMIT = .51 # correction no longer needs votes and can replace original phrase TRANSCRIPT_PHRASE_CORRECTION_UPPER_LIMIT = .66 SECRET_KEY = os.environ['SECRET_KEY'] DEBUG = True LOG_DIRECTORY = '/home/wgbh/logs' STATIC_ROOT = '/home/wgbh/webroot/static' ALLOWED_HOSTS = [ 'mlagame-dev.wgbhdigital.org', 'mlagame.wgbhdigital.org', 'fixit.wgbhdigital.org', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': 'localhost', 'NAME': 'mla', 'USER': 'mla', 'PASSWORD': os.environ['PG_PASS'], 'TEST': { 'NAME': 'mla-test', }, }, } GA_CODE = 'null' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': '{}/django.log'.format(LOG_DIRECTORY), }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } ","from .base import * import os SECRET_KEY = os.environ['SECRET_KEY'] DEBUG = True LOG_DIRECTORY = '/home/wgbh/logs' STATIC_ROOT = '/home/wgbh/webroot/static' ALLOWED_HOSTS = [ 'mlagame-dev.wgbhdigital.org', 'mlagame.wgbhdigital.org', 'fixit.wgbhdigital.org', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': 'localhost', 'NAME': 'mla', 'USER': 'mla', 'PASSWORD': os.environ['PG_PASS'], 'TEST': { 'NAME': 'mla-test', }, }, } GA_CODE = 'null' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': '{}/django.log'.format(LOG_DIRECTORY), }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } " Allow set scroll timeout param,"from rest_framework import pagination from amcat.tools import amcates from rest_framework.response import Response from django.core.urlresolvers import reverse from rest_framework.utils.urls import replace_query_param class ScrollingPaginator(pagination.BasePagination): def paginate_queryset(self, queryset, request, view=None): self.request = request es = amcates.ES() scroll_id = request.query_params.get(""scroll_id"") scroll = request.query_params.get(""scroll"", ""1m"") if scroll_id: res = es.es.scroll(scroll_id, scroll=scroll) else: res = es.search(scroll=scroll, **queryset) self.total = res['hits']['total'] self.scroll_id = res['_scroll_id'] self.done = not res['hits']['hits'] for hit in res['hits']['hits']: item = {'id': hit['_id']} if '_source' in hit: item.update({k: v for (k, v) in hit['_source'].items()}) yield item def get_paginated_response(self, data): return Response({ 'next': self.get_next_link(), 'results': data, 'total': self.total, }) def get_next_link(self): if not self.done: url = self.request.build_absolute_uri() return replace_query_param(url, ""scroll_id"", self.scroll_id) ","from rest_framework import pagination from amcat.tools import amcates from rest_framework.response import Response from django.core.urlresolvers import reverse from rest_framework.utils.urls import replace_query_param class ScrollingPaginator(pagination.BasePagination): def paginate_queryset(self, queryset, request, view=None): self.request = request es = amcates.ES() scroll_id = request.query_params.get(""scroll_id"") if scroll_id: res = es.es.scroll(scroll_id, scroll=""1m"") else: res = es.search(scroll=""1m"", **queryset) self.total = res['hits']['total'] self.scroll_id = res['_scroll_id'] self.done = not res['hits']['hits'] for hit in res['hits']['hits']: item = {'id': hit['_id']} if '_source' in hit: item.update({k: v for (k, v) in hit['_source'].items()}) yield item def get_paginated_response(self, data): return Response({ 'next': self.get_next_link(), 'results': data, 'total': self.total, }) def get_next_link(self): if not self.done: url = self.request.build_absolute_uri() return replace_query_param(url, ""scroll_id"", self.scroll_id) " Insert Embeddable instead of Embedded annotation for class,"package de.espend.idea.php.annotation.doctrine.action; import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.jetbrains.php.codeInsight.PhpCodeInsightUtil; import com.jetbrains.php.lang.psi.elements.PhpClass; import com.jetbrains.php.lang.psi.elements.PhpPsiElement; import de.espend.idea.php.annotation.doctrine.util.DoctrineUtil; import de.espend.idea.php.annotation.util.PhpDocUtil; import de.espend.idea.php.annotation.util.PhpElementsUtil; import org.jetbrains.annotations.NotNull; /** * @author Daniel Espendiller <daniel@espendiller.net> */ public class DoctrineEmbeddedClassAnnotationGenerateAction extends DoctrineClassGeneratorAction { @NotNull @Override protected String supportedClass() { return ""Doctrine\\ORM\\Mapping\\Embeddable""; } protected void execute(@NotNull Editor editor, @NotNull PhpClass phpClass, @NotNull PsiFile psiFile) { // insert ORM alias PhpPsiElement scopeForUseOperator = PhpCodeInsightUtil.findScopeForUseOperator(phpClass.getFirstChild()); if(scopeForUseOperator != null) { PhpElementsUtil.insertUseIfNecessary(scopeForUseOperator, DoctrineUtil.DOCTRINE_ORM_MAPPING, ""ORM""); PsiDocumentManager.getInstance(psiFile.getProject()).doPostponedOperationsAndUnblockDocument(editor.getDocument()); } PhpDocUtil.addClassEmbeddedDocs(phpClass, editor.getDocument(), psiFile); } } ","package de.espend.idea.php.annotation.doctrine.action; import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.jetbrains.php.codeInsight.PhpCodeInsightUtil; import com.jetbrains.php.lang.psi.elements.PhpClass; import com.jetbrains.php.lang.psi.elements.PhpPsiElement; import de.espend.idea.php.annotation.doctrine.util.DoctrineUtil; import de.espend.idea.php.annotation.util.PhpDocUtil; import de.espend.idea.php.annotation.util.PhpElementsUtil; import org.jetbrains.annotations.NotNull; /** * @author Daniel Espendiller <daniel@espendiller.net> */ public class DoctrineEmbeddedClassAnnotationGenerateAction extends DoctrineClassGeneratorAction { @NotNull @Override protected String supportedClass() { return ""Doctrine\\ORM\\Mapping\\Embedded""; } protected void execute(@NotNull Editor editor, @NotNull PhpClass phpClass, @NotNull PsiFile psiFile) { // insert ORM alias PhpPsiElement scopeForUseOperator = PhpCodeInsightUtil.findScopeForUseOperator(phpClass.getFirstChild()); if(scopeForUseOperator != null) { PhpElementsUtil.insertUseIfNecessary(scopeForUseOperator, DoctrineUtil.DOCTRINE_ORM_MAPPING, ""ORM""); PsiDocumentManager.getInstance(psiFile.getProject()).doPostponedOperationsAndUnblockDocument(editor.getDocument()); } PhpDocUtil.addClassEmbeddedDocs(phpClass, editor.getDocument(), psiFile); } } " Make a separate constructor for node,"(function () { ""use strict""; var Frame = function (elem) { if (typeof elem === 'string') { elem = document.getElementById(elem); } var height = elem.scrollHeight; var width = elem.scrollWidth; var viewAngle = 45; var aspect = width / (1.0 * height); var near = 0.1; var far = 10000; this.scene = new THREE.Scene(); this.camera = new THREE.PerspectiveCamera(viewAngle, aspect, near, far); this.camera.position.z = 10; this.scene.add(this.camera); this.renderer = new THREE.WebGLRenderer(); this.renderer.setSize(width, height); elem.appendChild(this.renderer.domElement); }; window.Frame = Frame; Frame.prototype.addNode = function (node) { this.scene.add(node.mesh); }; Frame.prototype.render = function () { this.renderer.render(this.scene, this.camera); }; var Node = function (x, y, z) { var geometry = new THREE.SphereGeometry(1, 4, 4); var material = new THREE.MeshBasicMaterial({color: 0x00ff00, wireframe: true}); this.mesh = new THREE.Mesh(geometry, material); this.mesh.position = {x: x, y: y, z: z}; }; window.Node = Node; }()); ","(function () { ""use strict""; var Frame = function (elem) { if (typeof elem === 'string') { elem = document.getElementById(elem); } var height = elem.scrollHeight; var width = elem.scrollWidth; var viewAngle = 45; var aspect = width / (1.0 * height); var near = 0.1; var far = 10000; this.scene = new THREE.Scene(); this.camera = new THREE.PerspectiveCamera(viewAngle, aspect, near, far); this.camera.position.z = 10; this.scene.add(this.camera); this.renderer = new THREE.WebGLRenderer(); this.renderer.setSize(width, height); elem.appendChild(this.renderer.domElement); }; window.Frame = Frame; Frame.prototype.addNode = function (x, y, z) { var geometry = new THREE.SphereGeometry(1, 4, 4); var material = new THREE.MeshBasicMaterial({color: 0x00ff00, wireframe: true}); var sphere = new THREE.Mesh(geometry, material); sphere.position = {x: x, y: y, z: z}; this.scene.add(sphere); }; Frame.prototype.render = function () { this.renderer.render(this.scene, this.camera); }; }()); " "Use more specific selector to just get tree nodes This is increases the test performance.","""use strict""; describe('Read tokens from xml url', function(){ var sentence1Url = 'http://services.perseids.org/llt-data/1999.02.0002.2.1.1.xml'; var sentence2Url = 'http://services.perseids.org/llt-data/1999.02.0002.2.1.2.xml'; beforeEach(function() { browser.get('/app/#/tree'); }); describe('Sentence 1', function() { beforeEach(function() { element(by.model('query')).sendKeys(sentence1Url); element(by.buttonText('Search')).click(); }); it('displays a dependency tree (que is above cum)', function() { var nodes = element.all(by.css(""g.node g text tspan"")); nodes.map(function(elm, index) { return { index: index, text: elm.getText(), location: elm.getLocation() }; }).then(function(nodeInfos) { var que; var cum; for (var index = 0; index < nodeInfos.length; ++index) { var element = nodeInfos[index]; if (element.text === ""que"") { que = element; } if (element.text === ""Cum"") { cum = element; } } expect(que).toBeDefined(); expect(cum).toBeDefined(); expect(que.location.y).toBeGreaterThan(cum.location.y); }); }); }); }); ","""use strict""; describe('Read tokens from xml url', function(){ var sentence1Url = 'http://services.perseids.org/llt-data/1999.02.0002.2.1.1.xml'; var sentence2Url = 'http://services.perseids.org/llt-data/1999.02.0002.2.1.2.xml'; beforeEach(function() { browser.get('/app/#/tree'); }); describe('Sentence 1', function() { beforeEach(function() { element(by.model('query')).sendKeys(sentence1Url); element(by.buttonText('Search')).click(); }); it('displays a dependency tree (que is above cum)', function() { var nodes = element.all(by.css(""tspan"")); nodes.map(function(elm, index) { return { index: index, text: elm.getText(), location: elm.getLocation() }; }).then(function(nodeInfos) { var que; var cum; for (var index = 0; index < nodeInfos.length; ++index) { var element = nodeInfos[index]; if (element.text === ""que"") { que = element; } if (element.text === ""Cum"") { cum = element; } } expect(que).toBeDefined(); expect(cum).toBeDefined(); expect(que.location.y).toBeGreaterThan(cum.location.y); }); }); }); }); " "Fix test failure on Numpy 1.9 and Python 3.5 The ""@"" operator between arrays is only supported by Numpy 1.10+.","import sys try: import scipy.linalg.cython_blas has_blas = True except ImportError: has_blas = False import numba.unittest_support as unittest from numba.numpy_support import version as numpy_version # The ""@"" operator only compiles on Python 3.5+. # It is only supported by Numpy 1.10+. has_matmul = sys.version_info >= (3, 5) and numpy_version >= (1, 10) if has_matmul: code = """"""if 1: def matmul_usecase(x, y): return x @ y def imatmul_usecase(x, y): x @= y return x """""" co = compile(code, ""<string>"", ""exec"") ns = {} eval(co, globals(), ns) globals().update(ns) del code, co, ns else: matmul_usecase = None imatmul_usecase = None needs_matmul = unittest.skipUnless( has_matmul, ""the matrix multiplication operator needs Python 3.5+ and Numpy 1.10+"") needs_blas = unittest.skipUnless(has_blas, ""BLAS needs Scipy 0.16+"") class DumbMatrix(object): def __init__(self, value): self.value = value def __matmul__(self, other): if isinstance(other, DumbMatrix): return DumbMatrix(self.value * other.value) return NotImplemented def __imatmul__(self, other): if isinstance(other, DumbMatrix): self.value *= other.value return self return NotImplemented ","import sys try: import scipy.linalg.cython_blas has_blas = True except ImportError: has_blas = False import numba.unittest_support as unittest # The ""@"" operator only compiles on Python 3.5+. has_matmul = sys.version_info >= (3, 5) if has_matmul: code = """"""if 1: def matmul_usecase(x, y): return x @ y def imatmul_usecase(x, y): x @= y return x """""" co = compile(code, ""<string>"", ""exec"") ns = {} eval(co, globals(), ns) globals().update(ns) del code, co, ns else: matmul_usecase = None imatmul_usecase = None needs_matmul = unittest.skipUnless( has_matmul, ""the matrix multiplication operator needs Python 3.5+"") needs_blas = unittest.skipUnless(has_blas, ""BLAS needs Scipy 0.16+"") class DumbMatrix(object): def __init__(self, value): self.value = value def __matmul__(self, other): if isinstance(other, DumbMatrix): return DumbMatrix(self.value * other.value) return NotImplemented def __imatmul__(self, other): if isinstance(other, DumbMatrix): self.value *= other.value return self return NotImplemented " Increase time between host refreshing to four minutes.,"package com.bubbletastic.android.ping; import android.app.Application; import android.app.job.JobInfo; import android.app.job.JobScheduler; import android.content.ComponentName; import android.content.Context; import com.squareup.otto.Bus; import com.squareup.otto.ThreadEnforcer; /** * Created by brendanmartens on 4/13/15. */ public class Ping extends Application { private Bus bus; private JobScheduler jobScheduler; private HostService hostService; @Override public void onCreate() { super.onCreate(); bus = new Bus(ThreadEnforcer.ANY); hostService = HostService.getInstance(this); JobInfo updateHostsJob = new JobInfo.Builder(UpdateHostsService.JOB_ID, new ComponentName(this, UpdateHostsService.class)) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) //update hosts once every 4 minutes .setPeriodic(240000) //service scheduling should survive reboots .setPersisted(true) .build(); //schedule the update hosts job jobScheduler = ((JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE)); jobScheduler.schedule(updateHostsJob); } public Bus getBus() { return bus; } public HostService getHostService() { return hostService; } } ","package com.bubbletastic.android.ping; import android.app.Application; import android.app.job.JobInfo; import android.app.job.JobScheduler; import android.content.ComponentName; import android.content.Context; import com.squareup.otto.Bus; import com.squareup.otto.ThreadEnforcer; /** * Created by brendanmartens on 4/13/15. */ public class Ping extends Application { private Bus bus; private JobScheduler jobScheduler; private HostService hostService; @Override public void onCreate() { super.onCreate(); bus = new Bus(ThreadEnforcer.ANY); hostService = HostService.getInstance(this); JobInfo updateHostsJob = new JobInfo.Builder(UpdateHostsService.JOB_ID, new ComponentName(this, UpdateHostsService.class)) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) //update hosts once a minute .setPeriodic(60000) //service scheduling should survive reboots .setPersisted(true) .build(); //schedule the update hosts job jobScheduler = ((JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE)); jobScheduler.schedule(updateHostsJob); } public Bus getBus() { return bus; } public HostService getHostService() { return hostService; } } " Add `minify` to gulp watch,"var gulp = require('gulp'); var less = require('gulp-less'); var cleancss = require('gulp-clean-css'); var csscomb = require('gulp-csscomb'); var concat = require('gulp-concat'); var rename = require('gulp-rename'); var uglify = require('gulp-uglify'); var LessPluginAutoPrefix = require('less-plugin-autoprefix'); var autoprefix= new LessPluginAutoPrefix({ browsers: [""last 4 versions""] }); gulp.task('watch', function() { gulp.watch('./**/*.less', ['build', 'minify']); }); gulp.task('build', function() { gulp.src('./src/less/*.less') .pipe(less({ plugins: [autoprefix] })) .pipe(csscomb()) .pipe(gulp.dest('./src/css')); }); gulp.task('minify', function() { gulp.src('./src/css/*.css') .pipe(concat('affinity.css')) .pipe(cleancss()) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('./assets')); gulp.src('./src/js/*.js') .pipe(concat('affinity.js')) .pipe(uglify()) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('./assets')); }); gulp.task('default', ['build']); ","var gulp = require('gulp'); var less = require('gulp-less'); var cleancss = require('gulp-clean-css'); var csscomb = require('gulp-csscomb'); var concat = require('gulp-concat'); var rename = require('gulp-rename'); var uglify = require('gulp-uglify'); var LessPluginAutoPrefix = require('less-plugin-autoprefix'); var autoprefix= new LessPluginAutoPrefix({ browsers: [""last 4 versions""] }); gulp.task('watch', function() { gulp.watch('./**/*.less', ['build']); }); gulp.task('build', function() { gulp.src('./src/less/*.less') .pipe(less({ plugins: [autoprefix] })) .pipe(csscomb()) .pipe(gulp.dest('./src/css')); }); gulp.task('minify', function() { gulp.src('./src/css/*.css') .pipe(concat('affinity.css')) .pipe(cleancss()) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('./assets')); gulp.src('./src/js/*.js') .pipe(concat('affinity.js')) .pipe(uglify()) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('./assets')); }); gulp.task('default', ['build']); " Add an empty line at the end of the file,"package org.fluentd.logger.sender; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Deque; import java.util.LinkedList; /** * Calculate exponential delay for reconnecting */ public class ConstantDelayReconnector implements Reconnector { private static final Logger LOG = LoggerFactory.getLogger(ConstantDelayReconnector.class); private double wait = 50; // Default wait to 50 ms private static final int MAX_ERROR_HISTORY_SIZE = 100; private Deque<Long> errorHistory = new LinkedList<Long>(); public ConstantDelayReconnector() { errorHistory = new LinkedList<Long>(); } public ConstantDelayReconnector(int wait) { this.wait = wait; errorHistory = new LinkedList<Long>(); } public void addErrorHistory(long timestamp) { errorHistory.addLast(timestamp); if (errorHistory.size() > MAX_ERROR_HISTORY_SIZE) { errorHistory.removeFirst(); } } public boolean isErrorHistoryEmpty() { return errorHistory.isEmpty(); } public void clearErrorHistory() { errorHistory.clear(); } public boolean enableReconnection(long timestamp) { int size = errorHistory.size(); if (size == 0) { return true; } return (!(timestamp - errorHistory.getLast() < wait)); } } ","package org.fluentd.logger.sender; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Deque; import java.util.LinkedList; /** * Calculate exponential delay for reconnecting */ public class ConstantDelayReconnector implements Reconnector { private static final Logger LOG = LoggerFactory.getLogger(ConstantDelayReconnector.class); private double wait = 50; // Default wait to 50 ms private static final int MAX_ERROR_HISTORY_SIZE = 100; private Deque<Long> errorHistory = new LinkedList<Long>(); public ConstantDelayReconnector() { errorHistory = new LinkedList<Long>(); } public ConstantDelayReconnector(int wait) { this.wait = wait; errorHistory = new LinkedList<Long>(); } public void addErrorHistory(long timestamp) { errorHistory.addLast(timestamp); if (errorHistory.size() > MAX_ERROR_HISTORY_SIZE) { errorHistory.removeFirst(); } } public boolean isErrorHistoryEmpty() { return errorHistory.isEmpty(); } public void clearErrorHistory() { errorHistory.clear(); } public boolean enableReconnection(long timestamp) { int size = errorHistory.size(); if (size == 0) { return true; } return (!(timestamp - errorHistory.getLast() < wait)); } }" Remove default checkbox from question answers,"import React from 'react'; class ContentQuestionAnswersItem extends React.Component { render() { const answer = this.props.answer; const name = this.props.name; // let rightIcon = (<i className=""icon""></i>); // switch (answer.correct) { // case true: // rightIcon = (<i className=""checkmark icon teal""></i>); // break; // } return ( // <div className=""item""> // {rightIcon} // <div className=""content""> // {answer.answer} // </div> // </div> <div className=""field""> <div className=""ui checkbox""> <input type=""checkbox"" name={name} id={name} /> //defaultChecked={answer.correct} /> <label htmlFor={name}> {answer.answer} </label> </div> </div> ); } } export default ContentQuestionAnswersItem; ","import React from 'react'; class ContentQuestionAnswersItem extends React.Component { render() { const answer = this.props.answer; const name = this.props.name; // let rightIcon = (<i className=""icon""></i>); // switch (answer.correct) { // case true: // rightIcon = (<i className=""checkmark icon teal""></i>); // break; // } return ( // <div className=""item""> // {rightIcon} // <div className=""content""> // {answer.answer} // </div> // </div> <div className=""field""> <div className=""ui checkbox""> <input type=""checkbox"" name={name} id={name} defaultChecked={answer.correct} /> <label htmlFor={name}> {answer.answer} </label> </div> </div> ); } } export default ContentQuestionAnswersItem; " Update the classification to production/stable.,"# -*- coding: utf-8 -*- import os from distutils.core import setup here = os.path.dirname(__file__) def get_long_desc(): return open(os.path.join(here, 'README.rst')).read() # Function borrowed from carljm. def get_version(): fh = open(os.path.join(here, ""gcframe"", ""__init__.py"")) try: for line in fh.readlines(): if line.startswith(""__version__ =""): return line.split(""="")[1].strip().strip(""'"") finally: fh.close() setup( name='django-gcframe', version=get_version(), description='Django middleware and decorators for working with Google Chrome Frame.', url='https://github.com/benspaulding/django-gcframe/', author='Ben Spaulding', author_email='ben@benspaulding.us', license='BSD', download_url='https://github.com/benspaulding/django-gcframe/tarball/v%s' % get_version(), long_description = get_long_desc(), packages = [ 'gcframe', 'gcframe.tests', ], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Browsers', 'Topic :: Internet :: WWW/HTTP :: Site Management', ], ) ","# -*- coding: utf-8 -*- import os from distutils.core import setup here = os.path.dirname(__file__) def get_long_desc(): return open(os.path.join(here, 'README.rst')).read() # Function borrowed from carljm. def get_version(): fh = open(os.path.join(here, ""gcframe"", ""__init__.py"")) try: for line in fh.readlines(): if line.startswith(""__version__ =""): return line.split(""="")[1].strip().strip(""'"") finally: fh.close() setup( name='django-gcframe', version=get_version(), description='Django middleware and decorators for working with Google Chrome Frame.', url='https://github.com/benspaulding/django-gcframe/', author='Ben Spaulding', author_email='ben@benspaulding.us', license='BSD', download_url='https://github.com/benspaulding/django-gcframe/tarball/v%s' % get_version(), long_description = get_long_desc(), packages = [ 'gcframe', 'gcframe.tests', ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Browsers', 'Topic :: Internet :: WWW/HTTP :: Site Management', ], ) " Refactor date in Byline to use string,"/** * ByLine.js * Description: view component that makes up a news item preview * Modules: React and React Native Modules * Dependencies: styles.js SmallText * Author: Tiffany Tse */ //import modules import React, { PropTypes } from 'react'; import { StyleSheet, View } from 'react-native'; import SmallText from './SmallText.js'; import * as globalStyles from '../styles/global.js'; const Byline ({date, author, location}) => ( <View> <View style={style.row}> <SmallText> {date} </SmallText> <SmallText> {author} </SmallText> </View> </View> {location ? ( <View style={styles.row}> <SmallText style={styles.location}> {location} </SmallText> </View> ) : null} ); //define propTypes Byline.propTypes = { date: PropTypes.string.isRequired, author: PropTypes.string.isRequired, location: PropTypes.string }; //define custom styles const styles = StyleSheet.create({ row: { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 5 }, location: { color: globalStyles.MUTED_COLOR } }); //export Byline export default Byline;","/** * ByLine.js * Description: view component that makes up a news item preview * Modules: React and React Native Modules * Dependencies: styles.js SmallText * Author: Tiffany Tse */ //import modules import React, { PropTypes } from 'react'; import { StyleSheet, View } from 'react-native'; import SmallText from './SmallText.js'; import * as globalStyles from '../styles/global.js'; const Byline ({date, author, location}) => ( <View> <View style={style.row}> <SmallText> {date.toLocaleDateString()} </SmallText> <SmallText> {author} </SmallText> </View> </View> {location ? ( <View style={styles.row}> <SmallText style={styles.location}> {location} </SmallText> </View> ) : null} ); //define propTypes Byline.propTypes = { date: PropTypes.instanceOf(Date).isRequired, author: PropTypes.string.isRequired, location: PropTypes.string }; //define custom styles const styles = StyleSheet.create({ row: { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 5 }, location: { color: globalStyles.MUTED_COLOR } }); //export Byline export default Byline;" Kill _changed from the Base so subclassing makes more sense.,"from functools import wraps import os from functools import wraps def restoring_chdir(fn): @wraps(fn) def decorator(*args, **kw): try: path = os.getcwd() return fn(*args, **kw) finally: os.chdir(path) return decorator class BaseBuilder(object): """""" The Base for all Builders. Defines the API for subclasses. """""" @restoring_chdir def force(self, version): """""" An optional step to force a build even when nothing has changed. """""" print ""Forcing a build by touching files"" os.chdir(version.project.conf_dir(version.slug)) os.system('touch * && touch */*') def clean(self, version): """""" Clean up the version so it's ready for usage. This is used to add RTD specific stuff to Sphinx, and to implement whitelists on projects as well. It is guaranteed to be called before your project is built. """""" raise NotImplementedError def build(self, version): """""" Do the actual building of the documentation. """""" raise NotImplementedError def move(self, version): """""" Move the documentation from it's generated place to its final home. This needs to understand both a single server dev environment, as well as a multi-server environment. """""" raise NotImplementedError @property def changed(self): """""" Says whether the documentation has changed, and requires further action. This is mainly used to short-circuit more expensive builds of other output formats if the project docs didn't change on an update. Defaults to `True` """""" return getattr(self, '_changed', True) ","from functools import wraps import os from functools import wraps def restoring_chdir(fn): @wraps(fn) def decorator(*args, **kw): try: path = os.getcwd() return fn(*args, **kw) finally: os.chdir(path) return decorator class BaseBuilder(object): """""" The Base for all Builders. Defines the API for subclasses. """""" _changed = True @restoring_chdir def force(self, version): """""" An optional step to force a build even when nothing has changed. """""" print ""Forcing a build by touching files"" os.chdir(version.project.conf_dir(version.slug)) os.system('touch * && touch */*') def clean(self, version): """""" Clean up the version so it's ready for usage. This is used to add RTD specific stuff to Sphinx, and to implement whitelists on projects as well. It is guaranteed to be called before your project is built. """""" raise NotImplementedError def build(self, version): """""" Do the actual building of the documentation. """""" raise NotImplementedError def move(self, version): """""" Move the documentation from it's generated place to its final home. This needs to understand both a single server dev environment, as well as a multi-server environment. """""" raise NotImplementedError @property def changed(self): """""" Says whether the documentation has changed, and requires further action. This is mainly used to short-circuit more expensive builds of other output formats if the project docs didn't change on an update. Defaults to `True` """""" return self._changed " "Refactor try-catch block by limiting code in the try block Always good to know which line will raise an exception and limit the try block to that statement","from wagtail.wagtailimages.models import get_image_model from wagtail.wagtailimages.formats import get_image_format class ImageEmbedHandler(object): """""" ImageEmbedHandler will be invoked whenever we encounter an element in HTML content with an attribute of data-embedtype=""image"". The resulting element in the database representation will be: <embed embedtype=""image"" id=""42"" format=""thumb"" alt=""some custom alt text""> """""" @staticmethod def get_db_attributes(tag): """""" Given a tag that we've identified as an image embed (because it has a data-embedtype=""image"" attribute), return a dict of the attributes we should have on the resulting <embed> element. """""" return { 'id': tag['data-id'], 'format': tag['data-format'], 'alt': tag['data-alt'], } @staticmethod def expand_db_attributes(attrs, for_editor): """""" Given a dict of attributes from the <embed> tag, return the real HTML representation. """""" Image = get_image_model() try: image = Image.objects.get(id=attrs['id']) except Image.DoesNotExist: return ""<img>"" image_format = get_image_format(attrs['format']) if for_editor: try: return image_format.image_to_editor_html(image, attrs['alt']) except: return '' else: return image_format.image_to_html(image, attrs['alt']) ","from wagtail.wagtailimages.models import get_image_model from wagtail.wagtailimages.formats import get_image_format class ImageEmbedHandler(object): """""" ImageEmbedHandler will be invoked whenever we encounter an element in HTML content with an attribute of data-embedtype=""image"". The resulting element in the database representation will be: <embed embedtype=""image"" id=""42"" format=""thumb"" alt=""some custom alt text""> """""" @staticmethod def get_db_attributes(tag): """""" Given a tag that we've identified as an image embed (because it has a data-embedtype=""image"" attribute), return a dict of the attributes we should have on the resulting <embed> element. """""" return { 'id': tag['data-id'], 'format': tag['data-format'], 'alt': tag['data-alt'], } @staticmethod def expand_db_attributes(attrs, for_editor): """""" Given a dict of attributes from the <embed> tag, return the real HTML representation. """""" Image = get_image_model() try: image = Image.objects.get(id=attrs['id']) image_format = get_image_format(attrs['format']) if for_editor: try: return image_format.image_to_editor_html(image, attrs['alt']) except: return '' else: return image_format.image_to_html(image, attrs['alt']) except Image.DoesNotExist: return ""<img>"" " Remove unused jobs state property refetchPage,"import { WS_INSERT_JOB, WS_UPDATE_JOB, WS_REMOVE_JOB, FIND_JOBS, GET_JOB, GET_RESOURCES, GET_LINKED_JOB } from ""../app/actionTypes""; import { updateDocuments, insert, update, remove } from ""../utils/reducers""; export const initialState = { documents: null, term: """", page: 0, total_count: 0, detail: null, filter: """", fetched: false, resources: null, linkedJobs: {} }; export default function jobsReducer(state = initialState, action) { switch (action.type) { case WS_INSERT_JOB: return insert(state, action, ""created_at""); case WS_UPDATE_JOB: return update(state, action, ""created_at""); case WS_REMOVE_JOB: return remove(state, action); case GET_LINKED_JOB.SUCCEEDED: return { ...state, linkedJobs: { ...state.linkedJobs, [action.data.id]: action.data } }; case FIND_JOBS.REQUESTED: return { ...state, term: action.term }; case FIND_JOBS.SUCCEEDED: return updateDocuments(state, action, ""created_at""); case GET_JOB.REQUESTED: return { ...state, detail: null }; case GET_JOB.SUCCEEDED: return { ...state, detail: action.data }; case GET_RESOURCES.SUCCEEDED: return { ...state, resources: action.data }; default: return state; } } ","import { WS_INSERT_JOB, WS_UPDATE_JOB, WS_REMOVE_JOB, FIND_JOBS, GET_JOB, GET_RESOURCES, GET_LINKED_JOB } from ""../app/actionTypes""; import { updateDocuments, insert, update, remove } from ""../utils/reducers""; export const initialState = { documents: null, term: """", page: 0, total_count: 0, detail: null, filter: """", fetched: false, refetchPage: false, resources: null, linkedJobs: {} }; export default function jobsReducer(state = initialState, action) { switch (action.type) { case WS_INSERT_JOB: return insert(state, action, ""created_at""); case WS_UPDATE_JOB: return update(state, action, ""created_at""); case WS_REMOVE_JOB: return remove(state, action); case GET_LINKED_JOB.SUCCEEDED: return { ...state, linkedJobs: { ...state.linkedJobs, [action.data.id]: action.data } }; case FIND_JOBS.REQUESTED: return { ...state, term: action.term }; case FIND_JOBS.SUCCEEDED: return updateDocuments(state, action, ""created_at""); case GET_JOB.REQUESTED: return { ...state, detail: null }; case GET_JOB.SUCCEEDED: return { ...state, detail: action.data }; case GET_RESOURCES.SUCCEEDED: return { ...state, resources: action.data }; default: return state; } } " Fix a bug where multiple people looking at the same RF/t energy module in a screen would not see the same thing.,"package mcjty.rftools.blocks.screens.modules; public class ScreenModuleHelper { private boolean showdiff = false; private long prevMillis = 0; private long prevContents = 0; private long lastPerTick = 0; public Object[] getContentsValue(long millis, long contents, long maxContents) { if (showdiff) { if (prevMillis == 0 || millis <= prevMillis + 100) { // <= prevMillis + 100 to make sure we show last value if the timing is too short prevMillis = millis; prevContents = contents; return new Object[] { contents, maxContents, lastPerTick }; } else { long diff = millis - prevMillis; int ticks = (int) (diff * 20 / 1000); if (ticks == 0) { ticks = 1; } long diffEnergy = contents - prevContents; prevMillis = millis; prevContents = contents; lastPerTick = diffEnergy / ticks; return new Object[] { contents, maxContents, lastPerTick }; } } else { return new Object[] { contents, maxContents, 0L }; } } public void setShowdiff(boolean showdiff) { this.showdiff = showdiff; } } ","package mcjty.rftools.blocks.screens.modules; public class ScreenModuleHelper { private boolean showdiff = false; private long prevMillis = 0; private long prevContents = 0; public Object[] getContentsValue(long millis, long contents, long maxContents) { if (showdiff) { if (prevMillis == 0 || millis <= prevMillis) { prevMillis = millis; prevContents = contents; return new Object[] { contents, maxContents, 0L }; } else { long diff = millis - prevMillis; int ticks = (int) (diff * 20 / 1000); if (ticks == 0) { ticks = 1; } long diffEnergy = contents - prevContents; prevMillis = millis; prevContents = contents; return new Object[] { contents, maxContents, diffEnergy / ticks }; } } else { return new Object[] { contents, maxContents, 0L }; } } public void setShowdiff(boolean showdiff) { this.showdiff = showdiff; } } " Fix typo that prevents urls from being auto linked,"<?php namespace Parsedown\Providers; use Illuminate\Support\Facades\Config; use Illuminate\Support\ServiceProvider; use Illuminate\View\Compilers\BladeCompiler; use Parsedown; /** * Class ParsedownServiceProvider * @package App\Providers */ class ParsedownServiceProvider extends ServiceProvider { /** * @return void */ public function boot(): void { $this->compiler()->directive('parsedown', function (string $expression = '') { return ""<?php echo parsedown($expression); ?>""; }); $this->publishes([ __DIR__ . '/../Support/parsedown.php' => config_path('parsedown.php'), ]); } /** * @return BladeCompiler */ protected function compiler(): BladeCompiler { return app('view') ->getEngineResolver() ->resolve('blade') ->getCompiler(); } /** * @return void */ public function register(): void { $this->app->singleton('parsedown', function () { $parsedown = Parsedown::instance(); $parsedown->setBreaksEnabled( Config::get('parsedown.breaks_enabled') ); $parsedown->setMarkupEscaped( Config::get('parsedown.markup_escaped') ); $parsedown->setSafeMode( Config::get('parsedown.safe_mode') ); $parsedown->setUrlsLinked( Config::get('parsedown.urls_linked') ); return $parsedown; }); $this->mergeConfigFrom(__DIR__ . '/../Support/parsedown.php', 'parsedown'); } } ","<?php namespace Parsedown\Providers; use Illuminate\Support\Facades\Config; use Illuminate\Support\ServiceProvider; use Illuminate\View\Compilers\BladeCompiler; use Parsedown; /** * Class ParsedownServiceProvider * @package App\Providers */ class ParsedownServiceProvider extends ServiceProvider { /** * @return void */ public function boot(): void { $this->compiler()->directive('parsedown', function (string $expression = '') { return ""<?php echo parsedown($expression); ?>""; }); $this->publishes([ __DIR__ . '/../Support/parsedown.php' => config_path('parsedown.php'), ]); } /** * @return BladeCompiler */ protected function compiler(): BladeCompiler { return app('view') ->getEngineResolver() ->resolve('blade') ->getCompiler(); } /** * @return void */ public function register(): void { $this->app->singleton('parsedown', function () { $parsedown = Parsedown::instance(); $parsedown->setBreaksEnabled( Config::get('parsedown.breaks_enabled') ); $parsedown->setMarkupEscaped( Config::get('parsedown.markup_escaped') ); $parsedown->setSafeMode( Config::get('parsedown.safe_mode') ); $parsedown->setUrlsLinked( Config::get('parswdown.urls_linked') ); return $parsedown; }); $this->mergeConfigFrom(__DIR__ . '/../Support/parsedown.php', 'parsedown'); } } " Enforce non-instantiability of utility classes with private constructors,"package uk.co.automatictester.lightning.core.reporters; import uk.co.automatictester.lightning.core.state.TestSet; public class TestSetReporter { private TestSetReporter() { } public static String getTestSetExecutionSummaryReport(TestSet testSet) { int testCount = testSet.getTestCount(); int passedTestCount = testSet.getPassCount(); int failedTestCount = testSet.getFailCount(); int errorTestCount = testSet.getErrorCount(); String testSetStatus = getTestSetStatus(testSet); return String.format(""%n============= EXECUTION SUMMARY =============%n"" + ""Tests executed: %s%n"" + ""Tests passed: %s%n"" + ""Tests failed: %s%n"" + ""Tests errors: %s%n"" + ""Test set status: %s"", testCount, passedTestCount, failedTestCount, errorTestCount, testSetStatus); } private static String getTestSetStatus(TestSet testSet) { return hasFailed(testSet) ? ""FAIL"" : ""Pass""; } private static boolean hasFailed(TestSet testSet) { return testSet.getFailCount() != 0 || testSet.getErrorCount() != 0; } } ","package uk.co.automatictester.lightning.core.reporters; import uk.co.automatictester.lightning.core.state.TestSet; public class TestSetReporter { public static String getTestSetExecutionSummaryReport(TestSet testSet) { int testCount = testSet.getTestCount(); int passedTestCount = testSet.getPassCount(); int failedTestCount = testSet.getFailCount(); int errorTestCount = testSet.getErrorCount(); String testSetStatus = getTestSetStatus(testSet); return String.format(""%n============= EXECUTION SUMMARY =============%n"" + ""Tests executed: %s%n"" + ""Tests passed: %s%n"" + ""Tests failed: %s%n"" + ""Tests errors: %s%n"" + ""Test set status: %s"", testCount, passedTestCount, failedTestCount, errorTestCount, testSetStatus); } private static String getTestSetStatus(TestSet testSet) { return hasFailed(testSet) ? ""FAIL"" : ""Pass""; } private static boolean hasFailed(TestSet testSet) { return testSet.getFailCount() != 0 || testSet.getErrorCount() != 0; } } " Use absolute path for 'describe'.,"package com.csforge.sstable; import com.google.common.base.Strings; import java.io.File; import java.util.Arrays; public class Driver { public static void main(String ... args) { if (args.length == 0) { printCommands(); System.exit(-1); } switch(args[0].toLowerCase()) { case ""tojson"": SSTable2Json.main(Arrays.copyOfRange(args, 1, args.length)); break; case ""select"": Query.main(Arrays.copyOfRange(args, 0, args.length)); break; case ""cqlsh"": Cqlsh.main(Arrays.copyOfRange(args, 1, args.length)); break; case ""describe"": String path = new File(args[1]).getAbsolutePath(); try { System.out.println(""\u001B[1;34m"" + path); System.out.println(TableTransformer.ANSI_CYAN + Strings.repeat(""="", path.length())); System.out.print(TableTransformer.ANSI_RESET); CassandraUtils.printStats(path, System.out); } catch (Exception e) { e.printStackTrace(); } break; default: System.err.println(""Unknown command: "" + args[0]); printCommands(); System.exit(-2); break; } } private static void printCommands() { System.err.println(""Available commands: cqlsh, toJson, select, describe""); } } ","package com.csforge.sstable; import com.google.common.base.Strings; import java.io.IOException; import java.util.Arrays; public class Driver { public static void main(String ... args) { if (args.length == 0) { printCommands(); System.exit(-1); } switch(args[0].toLowerCase()) { case ""tojson"": SSTable2Json.main(Arrays.copyOfRange(args, 1, args.length)); break; case ""select"": Query.main(Arrays.copyOfRange(args, 0, args.length)); break; case ""cqlsh"": Cqlsh.main(Arrays.copyOfRange(args, 1, args.length)); break; case ""describe"": String path = args[1]; try { System.out.println(""\u001B[1;34m"" + path); System.out.println(TableTransformer.ANSI_CYAN + Strings.repeat(""="", path.length())); System.out.print(TableTransformer.ANSI_RESET); CassandraUtils.printStats(path, System.out); } catch (Exception e) { e.printStackTrace(); } break; default: System.err.println(""Unknown command: "" + args[0]); printCommands(); System.exit(-2); break; } } private static void printCommands() { System.err.println(""Available commands: cqlsh, toJson, select, describe""); } } " Fix strict standards bug in authenticate,"<?php namespace TrkLife\Auth; use Interop\Container\ContainerInterface; use Psr\Http\Message\ServerRequestInterface; /** * Class Authentication * * @package TrkLife\Auth * @author George Webb <george@webb.uno> */ class Authentication { /** * @var ContainerInterface */ private $c; /** * Authentication constructor. * @param ContainerInterface $c */ public function __construct(ContainerInterface $c) { $this->c = $c; } /** * Authenticates the request * * @param ServerRequestInterface $request * @return bool | ServerRequestInterface False on failure, request on success */ public function authenticate(ServerRequestInterface $request) { $auth_header = $request->getHeader('Authorization'); $token = str_replace('Bearer ', '', (is_array($auth_header) ? array_pop($auth_header) : $auth_header)); if (empty($token)) { return false; } $token_repo = $this->c->EntityManager->getRepository('TrkLife\Entity\Token'); $token_entity = $token_repo->findOneByToken($token); if ($token_entity === null) { return false; } // Set user and token in request attribute $user_repository = $this->c->EntityManager->getRepository('TrkLife\Entity\User'); $request = $request->withAttribute('user', $user_repository->findOneById($token_entity->getUserId())); $request = $request->withAttribute('token_entity', $token_entity); return $request; } } ","<?php namespace TrkLife\Auth; use Interop\Container\ContainerInterface; use Psr\Http\Message\ServerRequestInterface; /** * Class Authentication * * @package TrkLife\Auth * @author George Webb <george@webb.uno> */ class Authentication { /** * @var ContainerInterface */ private $c; /** * Authentication constructor. * @param ContainerInterface $c */ public function __construct(ContainerInterface $c) { $this->c = $c; } /** * Authenticates the request * * @param ServerRequestInterface $request * @return bool | ServerRequestInterface False on failure, request on success */ public function authenticate(ServerRequestInterface $request) { $token = str_replace('Bearer ', '', array_pop($request->getHeader('Authorization'))); if (empty($token)) { return false; } $token_repo = $this->c->EntityManager->getRepository('TrkLife\Entity\Token'); $token_entity = $token_repo->findOneByToken($token); if ($token_entity === null) { return false; } // Set user and token in request attribute $user_repository = $this->c->EntityManager->getRepository('TrkLife\Entity\User'); $request = $request->withAttribute('user', $user_repository->findOneById($token_entity->getUserId())); $request = $request->withAttribute('token_entity', $token_entity); return $request; } } " Allow quoted and not quotes strings.,"package org.jboss.as.modcluster; import java.util.Iterator; import java.util.List; import org.jboss.as.controller.OperationFailedException; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; public class ContextHost { String webcontext = null; String webhost = null; int waittime = 10; public ContextHost(ModelNode operation) throws OperationFailedException { List<Property> list = operation.asPropertyList(); Iterator<Property> it= list.iterator(); webcontext = null; webhost = null; while(it.hasNext()) { Property prop= it.next(); if (prop.getName().equals(""context"")) { webcontext = prop.getValue().toString(); } if (prop.getName().equals(""virtualhost"")) { webhost = prop.getValue().toString(); } if (prop.getName().equals(""waittime"")) { waittime = Integer.parseInt(RemoveQuotes(prop.getValue().toString())); } } if (webcontext == null || webhost == null) throw new OperationFailedException(new ModelNode().set(""need context and host"")); webcontext = RemoveQuotes(webcontext); webhost = RemoveQuotes(webhost); if (webcontext.equals(""/"")) webcontext = """"; } public static String RemoveQuotes(String string) { if (string.endsWith(""\"""") && string.startsWith(""\"""")) return string.substring(1, string.length() -1); return string; } } ","package org.jboss.as.modcluster; import java.util.Iterator; import java.util.List; import org.jboss.as.controller.OperationFailedException; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; public class ContextHost { String webcontext = null; String webhost = null; int waittime = 10; public ContextHost(ModelNode operation) throws OperationFailedException { List<Property> list = operation.asPropertyList(); Iterator<Property> it= list.iterator(); webcontext = null; webhost = null; while(it.hasNext()) { Property prop= it.next(); if (prop.getName().equals(""context"")) { webcontext = prop.getValue().toString(); } if (prop.getName().equals(""virtualhost"")) { webhost = prop.getValue().toString(); } if (prop.getName().equals(""waittime"")) { waittime = Integer.parseInt(RemoveQuotes(prop.getValue().toString())); } } if (webcontext == null || webhost == null) throw new OperationFailedException(new ModelNode().set(""need context and host"")); webcontext = RemoveQuotes(webcontext); webhost = RemoveQuotes(webhost); if (webcontext.equals(""/"")) webcontext = """"; } public static String RemoveQuotes(String string) { if (string.endsWith(""\"""") && string.startsWith(""\"""")) return string.substring(1, string.length() -1); return null; } } " Add the class declaration service configuration,"<?php namespace EdpSuperluminal; use Zend\Console\Request as ConsoleRequest; use Zend\Mvc\MvcEvent; /** * Create a class cache of all classes used. * * @package EdpSuperluminal */ class Module { /** * Attach the cache event listener * * @param MvcEvent $e */ public function onBootstrap(MvcEvent $e) { $serviceManager = $e->getApplication()->getServiceManager(); /** @var CacheBuilder $cacheBuilder */ $cacheBuilder = $serviceManager->get('EdpSuperluminal\CacheBuilder'); $eventManager = $e->getApplication()->getEventManager()->getSharedManager(); $eventManager->attach('Zend\Mvc\Application', 'finish', function (MvcEvent $e) use ($cacheBuilder) { $request = $e->getRequest(); if ($request instanceof ConsoleRequest || $request->getQuery()->get('EDPSUPERLUMINAL_CACHE', null) === null) { return; } $cacheBuilder->cache(ZF_CLASS_CACHE); }); } public function getServiceConfig() { return array( 'factories' => array( 'EdpSuperluminal\CacheCodeGenerator' => 'EdpSuperluminal\CacheCodeGeneratorFactory', 'EdpSuperluminal\CacheBuilder' => 'EdpSuperluminal\CacheBuilderFactory', 'EdpSuperluminal\ShouldCacheClass' => 'EdpSuperluminal\ShouldCacheClass\ShouldCacheClassSpecificationFactory', 'EdpSuperluminal\ClassDeclarationService' => 'EdpSuperluminal\ClassDeclaration\ClassDeclarationServiceFactory', ) ); } } ","<?php namespace EdpSuperluminal; use Zend\Console\Request as ConsoleRequest; use Zend\Mvc\MvcEvent; /** * Create a class cache of all classes used. * * @package EdpSuperluminal */ class Module { /** * Attach the cache event listener * * @param MvcEvent $e */ public function onBootstrap(MvcEvent $e) { $serviceManager = $e->getApplication()->getServiceManager(); /** @var CacheBuilder $cacheBuilder */ $cacheBuilder = $serviceManager->get('EdpSuperluminal\CacheBuilder'); $eventManager = $e->getApplication()->getEventManager()->getSharedManager(); $eventManager->attach('Zend\Mvc\Application', 'finish', function (MvcEvent $e) use ($cacheBuilder) { $request = $e->getRequest(); if ($request instanceof ConsoleRequest || $request->getQuery()->get('EDPSUPERLUMINAL_CACHE', null) === null) { return; } $cacheBuilder->cache(ZF_CLASS_CACHE); }); } public function getServiceConfig() { return array( 'factories' => array( 'EdpSuperluminal\CacheCodeGenerator' => 'EdpSuperluminal\CacheCodeGeneratorFactory', 'EdpSuperluminal\CacheBuilder' => 'EdpSuperluminal\CacheBuilderFactory', 'EdpSuperluminal\ShouldCacheClass' => 'EdpSuperluminal\ShouldCacheClass\ShouldCacheClassSpecificationFactory', ) ); } } " Add CORS filter to constructor,"<?php defined('BASEPATH') OR exit('No direct script access allowed'); require(APPPATH.'libraries/REST_Controller.php'); class Users extends REST_Controller { public function __construct() { header('Access-Control-Allow-Origin: *'); header(""Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE""); parent::__construct(); $this->load->model('users_model'); } public function login_post() { $request = json_decode(file_get_contents('php://input')); $email = $request->email; $password = $request->password; if ($email == NULL || $password == NULL) $this->response(NULL, REST_Controller::HTTP_UNAUTHORIZED); else { $results = $this->users_model->get_users($email); if ( count($results) == 0 ) $this->response(NULL, REST_Controller::HTTP_NOT_FOUND); else { if ( $results[0]->Email == $email && $this->bcrypt->check_password($password, $results[0]->Password) ) { $this->response($this->users_model->get_users_session($email), REST_Controller::HTTP_OK); } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); } } } } } /* End of file Users.php */ /* Location: ./application/controllers/api/v1/Users.php */","<?php defined('BASEPATH') OR exit('No direct script access allowed'); require(APPPATH.'libraries/REST_Controller.php'); class Users extends REST_Controller { public function __construct() { parent::__construct(); $this->load->model('users_model'); } public function login_post() { $request = json_decode(file_get_contents('php://input')); $email = $request->email; $password = $request->password; if ($email == NULL || $password == NULL) $this->response(NULL, REST_Controller::HTTP_UNAUTHORIZED); else { $results = $this->users_model->get_users($email); if ( count($results) == 0 ) $this->response(NULL, REST_Controller::HTTP_NOT_FOUND); else { if ( $results[0]->Email == $email && $this->bcrypt->check_password($password, $results[0]->Password) ) { $this->response($this->users_model->get_users_session($email), REST_Controller::HTTP_OK); } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); } } } } } /* End of file Users.php */ /* Location: ./application/controllers/api/v1/Users.php */" Use anonymous functions instead of arrow functions for backward compatibility with node < v4.0,"/* globals module */ var EOL = require('os').EOL; module.exports = { description: 'Register test helpers', afterInstall: function( options ) { // Import statement var firstFile = 'tests/helpers/start-app.js'; var firstText = ""import slRegisterTestHelpers from './sl/register-test-helpers';""; var firstLocationText = ""import Ember from 'ember';"" + EOL; // Execution of registration function var secondFile = 'tests/helpers/start-app.js'; var secondText = "" slRegisterTestHelpers();""; var secondLocationText = ""application.setupForTesting();"" + EOL; // .jshintrc file var thirdFile = 'tests/.jshintrc'; var thirdText = ' ""contains"",' + EOL + ' ""requires"",'; var thirdLocationText = '""predef"": [' + EOL; return this.insertIntoFile( firstFile, firstText, { after: firstLocationText } ) // Execution of registration function .then( function() { return this.insertIntoFile( secondFile, secondText, { after: secondLocationText } ); }.bind( this )) .then( function() { return this.insertIntoFile( thirdFile, thirdText, { after: thirdLocationText } ); }.bind( this )) .then( function() { return this.addAddonToProject( 'ember-sinon' ); }.bind( this )); }, normalizeEntityName: function() {} }; ","/* globals module */ var EOL = require('os').EOL; module.exports = { description: 'Register test helpers', afterInstall: function( options ) { // Import statement var firstFile = 'tests/helpers/start-app.js'; var firstText = ""import slRegisterTestHelpers from './sl/register-test-helpers';""; var firstLocationText = ""import Ember from 'ember';"" + EOL; // Execution of registration function var secondFile = 'tests/helpers/start-app.js'; var secondText = "" slRegisterTestHelpers();""; var secondLocationText = ""application.setupForTesting();"" + EOL; // .jshintrc file var thirdFile = 'tests/.jshintrc'; var thirdText = ' ""contains"",' + EOL + ' ""requires"",'; var thirdLocationText = '""predef"": [' + EOL; return this.insertIntoFile( firstFile, firstText, { after: firstLocationText } ) // Execution of registration function .then( () => { return this.insertIntoFile( secondFile, secondText, { after: secondLocationText } ); }) .then( () => { return this.insertIntoFile( thirdFile, thirdText, { after: thirdLocationText } ); }) .then( () => { return this.addAddonToProject( 'ember-sinon' ); }); }, normalizeEntityName: function() {} }; " "Fix test to add assertion rmdir test now expected to fail","from __future__ import absolute_import, print_function import os import sys import pytest from ..pyautoupdate.launcher import Launcher @pytest.fixture(scope='function') def create_update_dir(request): os.mkdir('downloads') files=['tesfeo','fjfesf','fihghg'] filedir=[os.path.join('downloads',fi) for fi in files] os.mkdir(os.path.join('downloads','subfolder')) filedir.append(os.path.join('downloads','subfolder','oweigjoewig')) for each_file in filedir: with open(each_file, mode='w') as new_file: new_file.write('') def teardown(): for file_path in filedir: try: if os.path.isfile(file_path): os.unlink(file_path) raise AssertionError#fail test if files exist except OSError as error: print(error, file=sys.stderr) try: if os.path.isdir('downloads'): os.rmdir('downloads') except OSError as error: print(error, file=sys.stderr) request.addfinalizer(teardown) return create_update_dir def test_rm_dirs(create_update_dir): launch = Launcher('','') launch._reset_update_dir() assert os.path.isdir('downloads') ","from __future__ import absolute_import, print_function import os import sys import pytest from ..pyautoupdate.launcher import Launcher @pytest.fixture(scope='function') def create_update_dir(request): os.mkdir('downloads') files=['tesfeo','fjfesf','fihghg'] filedir=[os.path.join('downloads',fi) for fi in files] os.mkdir(os.path.join('downloads','subfolder')) filedir.append(os.path.join('downloads','subfolder','oweigjoewig')) for each_file in filedir: with open(each_file, mode='w') as new_file: new_file.write('') def teardown(): for file_path in filedir: try: if os.path.isfile(file_path): os.unlink(file_path) raise AssertionError#fail test if files exist except OSError as error: print(error, file=sys.stderr) try: if os.path.isdir('downloads'): os.rmdir('downloads') except OSError as error: print(error, file=sys.stderr) request.addfinalizer(teardown) return create_update_dir def test_rm_dirs(create_update_dir): launch = Launcher('','') launch._reset_update_dir() " Set default opacity to 1.0,"// Run after the DOM loads $(function () { 'use strict'; var map = geo.map({ node: '#map', center: { x: -122.445, y: 37.8 }, zoom: 6 }); $.ajax('https://s3.amazonaws.com/uploads.hipchat.com/446632/3114847/4dZfl0YfZpTfYzq/AdderallCities2015.csv', { success: function (resp) { var rows = resp.split(/\r\n|\n|\r/); rows = rows.map( function (r) { var fields = r.split(','); return [fields[12], fields[24], fields[25]].map(parseFloat); }); rows.splice(0, 1); var layer = map.createLayer('feature', {renderer: 'canvas'}); var heatmap = layer.createFeature('heatmap') .data(rows) .intensity(function (d) { return d[0]; }) .position(function (d) { return { x: d[2], y: d[1] }; }) .maxIntensity(20) .style('radius', 5) .style('blurRadius', 15) .style('opacity', 1.0); map.draw(); } }); var base = map.createLayer('osm'); map.draw(); }); ","// Run after the DOM loads $(function () { 'use strict'; var map = geo.map({ node: '#map', center: { x: -122.445, y: 37.8 }, zoom: 6 }); $.ajax('https://s3.amazonaws.com/uploads.hipchat.com/446632/3114847/4dZfl0YfZpTfYzq/AdderallCities2015.csv', { success: function (resp) { var rows = resp.split(/\r\n|\n|\r/); rows = rows.map( function (r) { var fields = r.split(','); return [fields[12], fields[24], fields[25]].map(parseFloat); }); rows.splice(0, 1); var layer = map.createLayer('feature', {renderer: 'canvas'}); var heatmap = layer.createFeature('heatmap') .data(rows) .intensity(function (d) { return d[0]; }) .position(function (d) { return { x: d[2], y: d[1] }; }) .maxIntensity(20) .style('radius', 5) .style('blurRadius', 15) .style('opacity', 0.5); map.draw(); } }); var base = map.createLayer('osm'); map.draw(); }); " "Use a FutureResponse object in the run command Fixes running centipede. `PHP Catchable fatal error: Argument 2 passed to Centipede\Console\Command\Run::Centipede\Console\Command\{closure}() must be an instance of Symfony\Component\BrowserKit\Response, instance of GuzzleHttp\Message\FutureResponse given, called in /pipeline/build/vendor/umpirsky/centipede-crawler/src/Centipede/Crawler.php on line 91 and defined in /pipeline/build/vendor/umpirsky/centipede/src/Centipede/Console/Command/Run.php on line 30`","<?php namespace Centipede\Console\Command; use GuzzleHttp\Message\FutureResponse; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Input\InputArgument; use Centipede\Crawler; class Run extends Command { private $exitCode = 0; protected function configure() { $this ->setName('run') ->setDefinition([ new InputArgument('url', InputArgument::REQUIRED, 'Base url'), new InputArgument('depth', InputArgument::OPTIONAL, 'Depth', 1), ]) ->setDescription('Runs specifications') ; } protected function execute(InputInterface $input, OutputInterface $output) { (new Crawler($input->getArgument('url'), $input->getArgument('depth')))->crawl(function ($url, FutureResponse $response) use ($output) { $tag = 'info'; if (200 != $response->getStatusCode()) { $this->exitCode = 1; $tag = 'error'; } $output->writeln(sprintf( '<%s>%d</%s> %s', $tag, $response->getStatusCode(), $tag, $url )); }); return $this->exitCode; } } ","<?php namespace Centipede\Console\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\BrowserKit\Response; use Centipede\Crawler; class Run extends Command { private $exitCode = 0; protected function configure() { $this ->setName('run') ->setDefinition([ new InputArgument('url', InputArgument::REQUIRED, 'Base url'), new InputArgument('depth', InputArgument::OPTIONAL, 'Depth', 1), ]) ->setDescription('Runs specifications') ; } protected function execute(InputInterface $input, OutputInterface $output) { (new Crawler($input->getArgument('url'), $input->getArgument('depth')))->crawl(function ($url, Response $response) use ($output) { $tag = 'info'; if (200 != $response->getStatus()) { $this->exitCode = 1; $tag = 'error'; } $output->writeln(sprintf( '<%s>%d</%s> %s', $tag, $response->getStatus(), $tag, $url )); }); return $this->exitCode; } } " Change test to check for contents instead of full string,"package bjohnson.ResponseHandlers; import bjohnson.Request; import org.hamcrest.CoreMatchers; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class HTMLDirectoryResponseBuilderTest { private String filePath; private Request request; @Before public void setUp(){ filePath = System.getProperty(""user.dir"") + ""/src/test/java/bjohnson/testResource""; request = new Request(); request.setURL(""/""); request.setMethod(""GET""); } @Test public void testReturns200Ok() throws Exception { Response response = new HTMLDirectoryResponseBuilder(filePath).getResponse(request); assertEquals(""200 OK"", response.getStatus()); } @Test public void testBodyContainsTestHtml() throws Exception { HTMLDirectoryResponseBuilder htmlDirectoryResponseBuilder = new HTMLDirectoryResponseBuilder(filePath); Response response = htmlDirectoryResponseBuilder.getResponse(request); assertThat(new String(response.getBody()), CoreMatchers.containsString(""<li><a href=\""/image.png\"">image.png</a></li>\n"")); assertThat(new String(response.getBody()), CoreMatchers.containsString(""<li><a href=\""/partial_content.txt\"">partial_content.txt</a></li>\n"")); assertThat(new String(response.getBody()), CoreMatchers.containsString(""<li><a href=\""/patch-content.txt\"">patch-content.txt</a></li>\n"")); assertThat(new String(response.getBody()), CoreMatchers.containsString(""<li><a href=\""/readerFile.txt\"">readerFile.txt</a></li>\n"")); } }","package bjohnson.ResponseHandlers; import bjohnson.Request; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class HTMLDirectoryResponseBuilderTest { private String filePath; private Request request; @Before public void setUp(){ filePath = System.getProperty(""user.dir"") + ""/src/test/java/bjohnson/testResource""; request = new Request(); request.setURL(""/""); request.setMethod(""GET""); } @Test public void testReturns200Ok() throws Exception { Response response = new HTMLDirectoryResponseBuilder(filePath).getResponse(request); assertEquals(""200 OK"", response.getStatus()); } @Test public void testBodyContainsTestHtml() throws Exception { HTMLDirectoryResponseBuilder htmlDirectoryResponseBuilder = new HTMLDirectoryResponseBuilder(filePath); Response response = htmlDirectoryResponseBuilder.getResponse(request); String testHtml = ""<Body>\n<ol>\n"" + ""<li><a href=\""/image.png\"">image.png</a></li>\n"" + ""<li><a href=\""/partial_content.txt\"">partial_content.txt</a></li>\n"" + ""<li><a href=\""/patch-content.txt\"">patch-content.txt</a></li>\n"" + ""<li><a href=\""/readerFile.txt\"">readerFile.txt</a></li>\n"" + ""</ol>\n</Body>\n""; assertArrayEquals(testHtml.getBytes(), response.getBody()); } }" Set to OK the answer of docker health endpoint,"package com.ippon.jug.slip; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.file.Files; import java.nio.file.Paths; @RestController public class SlipController { @RequestMapping(value = ""/request"") public String getRequest() throws InterruptedException, UnknownHostException { this.doSlip(); StringBuilder builder = new StringBuilder() .append(""Hello I'm "") .append(InetAddress.getLocalHost().getHostName()) .append("". My little secret is ... ""); try { Files.readAllLines(Paths.get(""/run/secrets/bdx"")) .forEach(builder::append); } catch (IOException e) { // No secret here builder.append("" UNKNOWN !""); } return builder.toString(); } private static final int SLEEP_MILLIS = 50; private synchronized void doSlip() throws InterruptedException { Thread.sleep(SLEEP_MILLIS); } @RequestMapping(value = ""/dockerHealth"") public ResponseEntity<Void> getHealth() { return new ResponseEntity<Void>(HttpStatus.OK); } } ","package com.ippon.jug.slip; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.file.Files; import java.nio.file.Paths; @RestController public class SlipController { @RequestMapping(value = ""/request"") public String getRequest() throws InterruptedException, UnknownHostException { this.doSlip(); StringBuilder builder = new StringBuilder() .append(""Hello I'm "") .append(InetAddress.getLocalHost().getHostName()) .append("". My little secret is ... ""); try { Files.readAllLines(Paths.get(""/run/secrets/bdx"")) .forEach(builder::append); } catch (IOException e) { // No secret here builder.append("" UNKNOWN !""); } return builder.toString(); } private static final int SLEEP_MILLIS = 50; private synchronized void doSlip() throws InterruptedException { Thread.sleep(SLEEP_MILLIS); } @RequestMapping(value = ""/dockerHealth"") public ResponseEntity<Void> getHealth() { return new ResponseEntity<Void>(HttpStatus.INTERNAL_SERVER_ERROR); } } " Disable cluster node Integration tests for travis build.,"package com.codingchili.core.protocol; import io.vertx.core.Vertx; import io.vertx.core.VertxOptions; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.After; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import static com.codingchili.core.configuration.CoreStrings.ERROR_CLUSTERING_REQUIRED; /** * @author Robin Duda * * Tests the clusternode class to require clustering. */ @Ignore(""Disable tests until the travis build passes."") @RunWith(VertxUnitRunner.class) public class ClusterNodeIT { private Vertx vertx; @After public void tearDown(TestContext test) { vertx.close(test.asyncAssertSuccess()); } @Test public void testVertxNotClusteredError(TestContext test) { try { vertx = Vertx.vertx(); vertx.deployVerticle(new ClusterNode() {}); } catch (RuntimeException e) { test.assertEquals(ERROR_CLUSTERING_REQUIRED, e.getMessage()); } } @Test public void testVertxClusteredOk(TestContext test) { Async async = test.async(); Vertx.clusteredVertx(new VertxOptions(), handler -> { vertx = handler.result(); handler.result().deployVerticle(new ClusterNode() {}); async.complete(); }); } } ","package com.codingchili.core.protocol; import io.vertx.core.Vertx; import io.vertx.core.VertxOptions; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.After; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import static com.codingchili.core.configuration.CoreStrings.ERROR_CLUSTERING_REQUIRED; /** * @author Robin Duda * * Tests the clusternode class to require clustering. */ @RunWith(VertxUnitRunner.class) public class ClusterNodeIT { private Vertx vertx; @After public void tearDown(TestContext test) { vertx.close(test.asyncAssertSuccess()); } @Test public void testVertxNotClusteredError(TestContext test) { try { vertx = Vertx.vertx(); vertx.deployVerticle(new ClusterNode() {}); } catch (RuntimeException e) { test.assertEquals(ERROR_CLUSTERING_REQUIRED, e.getMessage()); } } @Ignore(""Disable while memory constraint in travis are being figured out."") @Test public void testVertxClusteredOk(TestContext test) { Async async = test.async(); Vertx.clusteredVertx(new VertxOptions(), handler -> { vertx = handler.result(); handler.result().deployVerticle(new ClusterNode() {}); async.complete(); }); } } " Stop converting to upper case,"const logger = require('../../../log.js'); module.exports = { disconnect, connect, addParams }; function connect() { const config = require('../../config'); const Connection = require('tedious').Connection; let connection = new Connection({ userName: config.db.username, password: config.db.password, server: config.db.server, options: { encrypt: true, database: config.db.database, useColumnNames: true, rowCollectionOnRequestCompletion: true } }); connection.on('error', function(err) { if(err.message === 'Connection lost - read ECONNRESET') { logger.warn('Connection lost - read ECONNRESET'); logger.info('Azure loadbalancer timeout error - see https://github.com/tediousjs/tedious/issues/300'); } else { logger.error('DB error: ' + err.message); } }); logger.debug('Created new DB connection'); return connection; } function addParams(params, request) { params.forEach(function(param) { let paramValue = param.value; request.addParameter( param.column, param.type, paramValue); }); } function disconnect(connection) { logger.debug('Closing DB connection on disconnect'); connection.close(); } ","const logger = require('../../../log.js'); module.exports = { disconnect, connect, addParams }; function connect() { const config = require('../../config'); const Connection = require('tedious').Connection; let connection = new Connection({ userName: config.db.username, password: config.db.password, server: config.db.server, options: { encrypt: true, database: config.db.database, useColumnNames: true, rowCollectionOnRequestCompletion: true } }); connection.on('error', function(err) { if(err.message === 'Connection lost - read ECONNRESET') { logger.warn('Connection lost - read ECONNRESET'); logger.info('Azure loadbalancer timeout error - see https://github.com/tediousjs/tedious/issues/300'); } else { logger.error('DB error: ' + err.message); } }); logger.debug('Created new DB connection'); return connection; } function addParams(params, request) { params.forEach(function(param) { let paramValue = param.value; if (isNaN(paramValue)) { paramValue = paramValue.toUpperCase(); } request.addParameter( param.column, param.type, paramValue); }); } function disconnect(connection) { logger.debug('Closing DB connection on disconnect'); connection.close(); } " Load and test for admin users.,"module.exports = function(access) { 'use strict'; let _ = require('lodash'); let projectAccessCache = {}; let adminUsersCache = {}; return { find: find, clear: clear, validateAccess: validateAccess }; // find looks up a given project in the project cache. // If the projectAccessCache hasn't been loaded it loads the // cache. function *find(project_id) { if (_.isEmpty(adminUsersCache)) { let adminUsers = yield access.adminUsers(); adminUsers.forEach(function(user) { adminUsersCache[user.id] = user; }); } if (! _.isEmpty(projectAccessCache)) { return projectAccessCache[project_id]; } projectAccessCache = yield access.allByProject(); return projectAccessCache[project_id]; } // clear will clear the current project cache. This is useful // when project permissions have been updated or a new project // has been created. function clear() { projectAccessCache = {}; } // validateAccess checks if the user has access to the // given project. This method assumes that find was called // first so that the projectAccessCache was preloaded. If the // projectAccessCache is empty then it returns false (no access). function validateAccess(project_id, user) { if (user.id in adminUsersCache) { return true; } if (_.isEmpty(projectAccessCache)) { return false; } if (!(project_id in projectAccessCache)) { return false; } let index = _.indexOf(projectAccessCache[project_id], function(a) { return a.user_id == user.id; }); // when index !== -1 we found the given user in the project. return index !== -1; } }; ","module.exports = function(access) { 'use strict'; let _ = require('lodash'); let projectAccessCache = {}; return { find: find, clear: clear, validateAccess: validateAccess }; // find looks up a given project in the project cache. // If the projectAccessCache hasn't been loaded it loads the // cache. function *find(project_id) { if (! _.isEmpty(projectAccessCache)) { return projectAccessCache[project_id]; } projectAccessCache = yield access.allByProject(); return projectAccessCache[project_id]; } // clear will clear the current project cache. This is useful // when project permissions have been updated or a new project // has been created. function clear() { projectAccessCache = {}; } // validateAccess checks if the user has access to the // given project. This method assumes that find was called // first so that the projectAccessCache was preloaded. If the // projectAccessCache is empty then it returns false (no access). function validateAccess(project_id, user) { if (_.isEmpty(projectAccessCache)) { return false; } if (!(project_id in projectAccessCache)) { return false; } let index = _.indexOf(projectAccessCache[project_id], function(a) { return a.user_id == user.id; }); // when index !== -1 we found the given user in the project. return index !== -1; } }; " Add admin page tree view helper to helper map,"<?php return array( 'router' => array( 'routes' => array( 'admin' => array( 'type' => 'literal', 'options' => array( 'route' => '/admin', 'defaults' => array( 'controller' => 'SlmCmfAdmin\Controller\AdminController', 'action' => 'index', ), ), 'may_terminate' => true, 'child_routes' => array( 'page-open' => array( 'type' => 'SlmCmfAdmin\Router\Http\Segment', 'options' => array( 'route' => '/page/open/:id[/:params]', 'defaults' => array( 'controller' => 'SlmCmfAdmin\Controller\PageController', 'action' => 'open' ), ), ), ), ), ), ), 'view_manager' => array( 'template_map' => array( 'layout/admin' => __DIR__ . '/../view/layout/admin.phtml', ), 'template_path_stack' => array( __DIR__ . '/../view' ), 'helper_map' => array( 'adminPageTree' => 'SlmCmfAdmin\View\Helper\PageTree', ), ), ); ","<?php return array( 'router' => array( 'routes' => array( 'admin' => array( 'type' => 'literal', 'options' => array( 'route' => '/admin', 'defaults' => array( 'controller' => 'SlmCmfAdmin\Controller\AdminController', 'action' => 'index', ), ), 'may_terminate' => true, 'child_routes' => array( 'page-open' => array( 'type' => 'SlmCmfAdmin\Router\Http\Segment', 'options' => array( 'route' => '/page/open/:id[/:params]', 'defaults' => array( 'controller' => 'SlmCmfAdmin\Controller\PageController', 'action' => 'open' ), ), ), ), ), ), ), 'view_manager' => array( 'template_map' => array( 'layout/admin' => __DIR__ . '/../view/layout/admin.phtml', ), 'template_path_stack' => array( __DIR__ . '/../view' ), 'helper_map' => array( 'slug' => 'SlmCmfUtils\View\Helper\Slug', 'url' => 'SlmCmfUtils\View\Helper\Url', ), ), ); " Fix article list month links,"<?php $years = $this->em($this->ck->module->name('article'))->publishYears(); ?> <ul> <?php foreach ($years as $year) { ?> <li> <a href=""<?= $this->ck->url->route([ 'year' => $year['date']->format('Y'), ], $this->ck->module->name('main_archive'), true) ?>""> <?= $year['date']->format('Y') ?> (<?= $year['contentCount'] ?>) </a> <ul> <?php foreach ($year['months'] as $month) { ?> <li><a href=""<?= $this->ck->url->route([ 'year' => $month['date']->format('Y'), 'month' => $month['date']->format('m'), ], $this->ck->module->name('main_archive'), true) ?>""> <?= $month['date']->format('F') ?> (<?= $month['contentCount'] ?>) </a></li> <?php } ?> </ul> </li> <?php } ?> </ul>","<?php $years = $this->em($this->ck->module->name('article'))->publishYears(); ?> <ul> <?php foreach ($years as $year) { ?> <li> <a href=""<?= $this->ck->url->route([ 'year' => $year['date']->format('Y'), ], $this->ck->module->name('main_archive'), true) ?>""> <?= $year['date']->format('Y') ?> (<?= $year['contentCount'] ?>) </a> <ul> <?php foreach ($year['months'] as $month) { ?> <li><a href=""<?= $this->ck->url->route([ 'year' => $year['date']->format('Y'), 'month' => $year['date']->format('m'), ], $this->ck->module->name('main_archive'), true) ?>""> <?= $month['date']->format('F') ?> (<?= $month['contentCount'] ?>) </a></li> <?php } ?> </ul> </li> <?php } ?> </ul>" Replace PFI with PFN in copyright notice.,"try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup import os import sys import unittest import os.path import platform sys.path.append('jubatus') sys.path.append('test') def read(name): return open(os.path.join(os.path.dirname(__file__), name)).read() setup(name='jubatus', version=read('VERSION').rstrip(), description='Jubatus is a distributed processing framework and streaming machine learning library. This is the Jubatus client in Python.', long_description=read('README.rst'), author='PFN & NTT', author_email='jubatus@googlegroups.com', url='http://jubat.us', download_url='http://pypi.python.org/pypi/jubatus/', license='MIT License', platforms='Linux', packages=find_packages(exclude=['test']), install_requires=[ 'msgpack-rpc-python>=0.3.0' ], entry_points="""", ext_modules=[], classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Other Environment', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Topic :: Scientific/Engineering :: Information Analysis' ], test_suite='jubatus_test', ) ","try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup import os import sys import unittest import os.path import platform sys.path.append('jubatus') sys.path.append('test') def read(name): return open(os.path.join(os.path.dirname(__file__), name)).read() setup(name='jubatus', version=read('VERSION').rstrip(), description='Jubatus is a distributed processing framework and streaming machine learning library. This is the Jubatus client in Python.', long_description=read('README.rst'), author='PFI & NTT', author_email='jubatus@googlegroups.com', url='http://jubat.us', download_url='http://pypi.python.org/pypi/jubatus/', license='MIT License', platforms='Linux', packages=find_packages(exclude=['test']), install_requires=[ 'msgpack-rpc-python>=0.3.0' ], entry_points="""", ext_modules=[], classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Other Environment', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Topic :: Scientific/Engineering :: Information Analysis' ], test_suite='jubatus_test', ) " Add support for multiple return `Packet`s from `Handler`s,"""""""Handle handlers."""""" import logging from .packet import Packet class Handlers(object): """"""Handlers."""""" def __init__(self, *handlers): self.logger = logging.getLogger(__name__) self.handlers = handlers def handle(self, event, packet): """"""Handle incoming data."""""" for handler in self.handlers: if hasattr(handler, ""on_"" + event): try: response = getattr(handler, ""on_"" + event)(packet) except Exception: self.logger.warning( ""Exception in handler %s:"", type(handler).__name__, exc_info=1) else: if isinstance(response, Packet): yield response elif isinstance(response, (tuple, list)): yield from response elif response is StopIteration: return class Handler(object): """"""Handler."""""" def __init__(self): self.logger = logging.getLogger(__name__) ","""""""Handle handlers."""""" import logging class Handlers(object): """"""Handlers."""""" def __init__(self, *handlers): self.logger = logging.getLogger(__name__) self.handlers = handlers def handle(self, event, packet): """"""Handle incoming data."""""" for handler in self.handlers: if hasattr(handler, ""on_"" + event): try: response = getattr(handler, ""on_"" + event)(packet) except Exception: self.logger.warning( ""Exception in handler %s:"", type(handler).__name__, exc_info=1) else: # TODO: support for multiple responses in an iterable if response is not None: yield response elif response is StopIteration: break class Handler(object): """"""Handler."""""" def __init__(self): self.logger = logging.getLogger(__name__) " Remove attachment and use slack link unfurling,"from __future__ import unicode_literals from django.db import models from django.utils import timezone from django.dispatch import receiver from django.conf import settings from taggit.managers import TaggableManager import requests class Bookmark(models.Model): title = models.CharField(max_length=200, blank=True, null=True) description = models.TextField(blank=True, null=True) date_added = models.DateTimeField(default=timezone.now, blank=True) tags = TaggableManager(blank=True) private = models.BooleanField(default=False) url = models.URLField(max_length=500) def __unicode__(self): return ""{}: {} [{}]"".format( self.pk, self.title[:40], self.date_added ) @receiver(models.signals.post_save, sender=Bookmark) def bookmark_pre_save_handler(sender, instance, created, *args, **kwargs): # Only run for new items, not updates if created: if not hasattr(settings, 'SLACK_WEBHOOK_URL'): return payload = { 'channel': ""#bookmarks-dev"", 'username': ""Bookmarks"", 'text': ""<{}|{}>\n{}"".format( instance.url, instance.title, instance.description, ), 'icon_emoji': "":blue_book:"", 'unfurl_links': True } requests.post(settings.SLACK_WEBHOOK_URL, json=payload) ","from __future__ import unicode_literals from django.db import models from django.utils import timezone from django.dispatch import receiver from django.conf import settings from taggit.managers import TaggableManager import requests class Bookmark(models.Model): title = models.CharField(max_length=200, blank=True, null=True) description = models.TextField(blank=True, null=True) date_added = models.DateTimeField(default=timezone.now, blank=True) tags = TaggableManager(blank=True) private = models.BooleanField(default=False) url = models.URLField(max_length=500) def __unicode__(self): return ""{}: {} [{}]"".format( self.pk, self.title[:40], self.date_added ) @receiver(models.signals.post_save, sender=Bookmark) def bookmark_pre_save_handler(sender, instance, created, *args, **kwargs): # Only run for new items, not updates if created: if not hasattr(settings, 'SLACK_WEBHOOK_URL'): return payload = { 'channel': ""#bookmarks-dev"", 'username': ""Bookmarks"", 'text': ""{}"".format( ""Bookmark added:"", ), 'icon_emoji': "":blue_book:"", 'attachments': [ { ""fallback"": instance.title, ""color"": ""good"", ""title"": instance.title, ""title_link"": instance.url, ""text"": instance.description, } ] } requests.post(settings.SLACK_WEBHOOK_URL, json=payload) " Fix class in button group dropdown,"<?php // check if groups are not empty foreach ($groups as $key => $group) { $exists = false; foreach ($group as $action => $config) { $subaction = is_array($config) ? $action : $config; if (array_key_exists($subaction, $links)) { $exists = true; } } if (!$exists) { unset($groups[$key]); } } ?> <?php foreach ($groups as $key => $group) : ?> <div class='btn-group'> <?= $this->Html->link( sprintf(""%s %s"", $key, $this->Html->tag('span', '', ['class' => 'caret'])), '#', ['class' => 'btn btn-default dropdown-toggle', 'escape' => false, 'data-toggle' => 'dropdown', 'aria-haspopup' => true, 'aria-expanded' => false] ) ?> <ul class=""dropdown-menu dropdown-menu-right""> <?php foreach ($group as $action => $config) : ?> <?php $subaction = is_array($config) ? $action : $config; ?> <?php if (array_key_exists($subaction, $links)): ?> <li class=""dropdown-item""><?= $this->element('action-button', ['config' => $links[$subaction]]); ?></li> <?php endif; ?> <?php endforeach; ?> </ul> </div> <?php endforeach; ","<?php // check if groups are not empty foreach ($groups as $key => $group) { $exists = false; foreach ($group as $action => $config) { $subaction = is_array($config) ? $action : $config; if (array_key_exists($subaction, $links)) { $exists = true; } } if (!$exists) { unset($groups[$key]); } } ?> <?php foreach ($groups as $key => $group) : ?> <div class='btn-group'> <?= $this->Html->link( sprintf(""%s %s"", $key, $this->Html->tag('span', '', ['class' => 'caret'])), '#', ['class' => 'btn btn-default dropdown-toggle', 'escape' => false, 'data-toggle' => 'dropdown', 'aria-haspopup' => true, 'aria-expanded' => false] ) ?> <ul class=""dropdown-menu pull-right""> <?php foreach ($group as $action => $config) : ?> <?php $subaction = is_array($config) ? $action : $config; ?> <?php if (array_key_exists($subaction, $links)): ?> <li class=""dropdown-item""><?= $this->element('action-button', ['config' => $links[$subaction]]); ?></li> <?php endif; ?> <?php endforeach; ?> </ul> </div> <?php endforeach; " Add STRICT_DOCKER_SERVICE_NAME_COMPARISON to Collection of PropertyDefinition,"package org.bitsofinfo.hazelcast.discovery.docker.swarm; import com.hazelcast.config.properties.PropertyDefinition; import com.hazelcast.logging.ILogger; import com.hazelcast.spi.discovery.DiscoveryNode; import com.hazelcast.spi.discovery.DiscoveryStrategy; import com.hazelcast.spi.discovery.DiscoveryStrategyFactory; import java.util.Arrays; import java.util.Collection; import java.util.Map; public class DockerSwarmDiscoveryStrategyFactory implements DiscoveryStrategyFactory { private static final Collection<PropertyDefinition> PROPERTIES = Arrays.asList(DockerSwarmDiscoveryConfiguration.DOCKER_SERVICE_LABELS, DockerSwarmDiscoveryConfiguration.DOCKER_NETWORK_NAMES, DockerSwarmDiscoveryConfiguration.DOCKER_SERVICE_NAMES, DockerSwarmDiscoveryConfiguration.HAZELCAST_PEER_PORT, DockerSwarmDiscoveryConfiguration.SWARM_MGR_URI, DockerSwarmDiscoveryConfiguration.SKIP_VERIFY_SSL, DockerSwarmDiscoveryConfiguration.LOG_ALL_SERVICE_NAMES_ON_FAILED_DISCOVERY, DockerSwarmDiscoveryConfiguration.STRICT_DOCKER_SERVICE_NAME_COMPARISON); public Class<? extends DiscoveryStrategy> getDiscoveryStrategyType() { // Returns the actual class type of the DiscoveryStrategy // implementation, to match it against the configuration return DockerSwarmDiscoveryStrategy.class; } public Collection<PropertyDefinition> getConfigurationProperties() { return PROPERTIES; } public DiscoveryStrategy newDiscoveryStrategy(DiscoveryNode discoveryNode, ILogger logger, Map<String, Comparable> properties) { return new DockerSwarmDiscoveryStrategy(discoveryNode, logger, properties); } } ","package org.bitsofinfo.hazelcast.discovery.docker.swarm; import com.hazelcast.config.properties.PropertyDefinition; import com.hazelcast.logging.ILogger; import com.hazelcast.spi.discovery.DiscoveryNode; import com.hazelcast.spi.discovery.DiscoveryStrategy; import com.hazelcast.spi.discovery.DiscoveryStrategyFactory; import java.util.Arrays; import java.util.Collection; import java.util.Map; public class DockerSwarmDiscoveryStrategyFactory implements DiscoveryStrategyFactory { private static final Collection<PropertyDefinition> PROPERTIES = Arrays.asList(DockerSwarmDiscoveryConfiguration.DOCKER_SERVICE_LABELS, DockerSwarmDiscoveryConfiguration.DOCKER_NETWORK_NAMES, DockerSwarmDiscoveryConfiguration.DOCKER_SERVICE_NAMES, DockerSwarmDiscoveryConfiguration.HAZELCAST_PEER_PORT, DockerSwarmDiscoveryConfiguration.SWARM_MGR_URI, DockerSwarmDiscoveryConfiguration.SKIP_VERIFY_SSL, DockerSwarmDiscoveryConfiguration.LOG_ALL_SERVICE_NAMES_ON_FAILED_DISCOVERY); public Class<? extends DiscoveryStrategy> getDiscoveryStrategyType() { // Returns the actual class type of the DiscoveryStrategy // implementation, to match it against the configuration return DockerSwarmDiscoveryStrategy.class; } public Collection<PropertyDefinition> getConfigurationProperties() { return PROPERTIES; } public DiscoveryStrategy newDiscoveryStrategy(DiscoveryNode discoveryNode, ILogger logger, Map<String, Comparable> properties) { return new DockerSwarmDiscoveryStrategy(discoveryNode, logger, properties); } } " Rename Store into MongoStore to pass JSLint,"'use strict'; /* ** Module dependencies */ var mongoose = require('mongoose'); var util = require('util'); var TTL = 24*3600; var Schema = new mongoose.Schema({ sid: { type: String, required: true, unique: true }, data: { type: mongoose.Schema.Types.Mixed, required: true }, usedAt: { type: Date, expires: TTL } }); var Session = mongoose.model('Session', Schema); module.exports = function(session) { var Store = session.Store; function MongoStore(options) { Store.call(this, options); } util.inherits(Store, Store); MongoStore.prototype.get = function(sid, done) { Session.findOne({ sid: sid }, function(err, session) { if (err) return done(err); if (!session) return done(null, false); done(null, session.data); }); }; MongoStore.prototype.set = function(sid, data, done) { Session.update({ sid: sid }, { sid: sid, data: data, usedAt: new Date() }, { upsert: true }, done); }; MongoStore.prototype.destroy = function(sid, done) { Session.remove({ sid: sid }, done); }; MongoStore.prototype.clear = function(done) { Session.collection.drop(done); }; return Store; }; ","'use strict'; /* ** Module dependencies */ var mongoose = require('mongoose'); var util = require('util'); var TTL = 24*3600; var Schema = new mongoose.Schema({ sid: { type: String, required: true, unique: true }, data: { type: mongoose.Schema.Types.Mixed, required: true }, usedAt: { type: Date, expires: TTL } }); var Session = mongoose.model('Session', Schema); module.exports = function(session) { var Store = session.Store; function Store(options) { Store.call(this, options); } util.inherits(Store, Store); Store.prototype.get = function(sid, done) { Session.findOne({ sid: sid }, function(err, session) { if (err) return done(err); if (!session) return done(null, false); done(null, session.data); }); }; Store.prototype.set = function(sid, data, done) { Session.update({ sid: sid }, { sid: sid, data: data, usedAt: new Date() }, { upsert: true }, done); }; Store.prototype.destroy = function(sid, done) { Session.remove({ sid: sid }, done); }; Store.prototype.clear = function(done) { Session.collection.drop(done); }; return Store; }; " Fix hanging promise in mocha,"function testFeature(feature) { if (feature.annotations.ignore) { describe.skip(`Feature: ${feature.title}`, () => {}); } else { describe(`Feature: ${feature.title}`, function() { feature.scenarios.forEach(function(scenario) { if (scenario.annotations.ignore) { describe.skip(`Scenario: ${scenario.title}`, () => {}); } else { describe(`Scenario: ${scenario.title}`, function() { before(function() { this.application = startApp(); }); after(function() { destroyApp(this.application); }); let context = { ctx: {} }; let failed = false; scenario.steps.forEach(function(step) { it(step, function() { if (failed === true) { this.test.pending = true; this.skip(); } else { let self = this; let promise = new Ember.RSVP.Promise(function(resolve) { yadda.Yadda(library.default(), self).yadda(step, context, function next(err, result) { if (err) { failed = true; throw err; } resolve(result); }); }); return promise; } }); }); }); } }); }); } }","function testFeature(feature) { if (feature.annotations.ignore) { describe.skip(`Feature: ${feature.title}`, () => {}); } else { describe(`Feature: ${feature.title}`, function() { feature.scenarios.forEach(function(scenario) { if (scenario.annotations.ignore) { describe.skip(`Scenario: ${scenario.title}`, () => {}); } else { describe(`Scenario: ${scenario.title}`, function() { before(function() { this.application = startApp(); }); after(function() { destroyApp(this.application); }); let context = { ctx: {} }; let failed = false; scenario.steps.forEach(function(step) { it(step, function() { if (failed === true) { this.test.pending = true; this.skip(); } else { let self = this; let promise = new Ember.RSVP.Promise(function(resolve) { yadda.Yadda(library.default(), self).yadda(step, context, function next(err, result) { if (err) { failed = true; throw err; } return result; }); }); return promise; } }); }); }); } }); }); } }" Use data attributes instead of classes,"(function ($) { function addCSSRule (selector, rules) { $('head').append('<style type=""text/css"">' + selector + ' { ' + rules + ' }</style>'); } $.fn.sticky = function () { addCSSRule('.stuck', 'position: fixed !important; top: 0 !important; z-index: 10') addCSSRule('.stuck-wedge', 'padding: 0 !important; margin: 0 !important; height: 0') var elem = $(this), initialOffset = elem.offset().top, wedge = $('<div data-wedge></div>').prependTo(elem.parent()), stuck = false $(window).on('scroll', function () { var currentPosition = $(window).scrollTop(), offset = elem.offset().top if (currentPosition < initialOffset && offset !== initialOffset && !stuck) { // Update the initialOffset, because the DOM has caused the element's position to change initialOffset = offset } else if (currentPosition >= Math.max(offset, initialOffset)) { if (stuck) return; // The page has scrolled past the top position of the element, so fix it and // apply its height as a margin to the next visible element so it doesn't jump elem.data('stuck', true) wedge.css('height', elem.height() + 'px') stuck = true } else { if(!stuck) return; // Unstick, because the element can now rest in its original position elem.removeData('stuck') wedge.css('height', '') stuck = false } }) } })(jQuery) ","(function ($) { function addCSSRule (selector, rules) { $('head').append('<style type=""text/css"">' + selector + ' { ' + rules + ' }</style>'); } $.fn.sticky = function () { addCSSRule('.stuck', 'position: fixed !important; top: 0 !important; z-index: 10') addCSSRule('.stuck-wedge', 'padding: 0 !important; margin: 0 !important; height: 0') var elem = $(this), initialOffset = elem.offset().top, wedge = $('<div class=""stuck-wedge""></div>').prependTo(elem.parent()), stuck = false $(window).on('scroll', function () { var currentPosition = $(window).scrollTop(), offset = elem.offset().top if (currentPosition < initialOffset && offset !== initialOffset && !stuck) { // Update the initialOffset, because the DOM has caused the element's position to change initialOffset = offset } else if (currentPosition >= Math.max(offset, initialOffset)) { if (stuck) return; // The page has scrolled past the top position of the element, so fix it and // apply its height as a margin to the next visible element so it doesn't jump elem.addClass('stuck') wedge.css('height', elem.height() + 'px') stuck = true } else { if(!stuck) return; // Unstick, because the element can now rest in its original position elem.removeClass('stuck') wedge.css('height', '') stuck = false } }) } })(jQuery) " Allow decoding the status as string value,"package org.iotbricks.core.amqp.transport.utils; import static java.util.Optional.empty; import static java.util.Optional.of; import java.util.Map; import java.util.Objects; import java.util.Optional; import org.apache.qpid.proton.amqp.messaging.ApplicationProperties; import org.apache.qpid.proton.message.Message; public final class Properties { private Properties() { } /** * Extract the {@code status} value as Integer from the message * * @param message * the message to extract the value from * @return the status value, never {@code null}, but may be * {@link Optional#empty()} */ public static Optional<Integer> status(final Message message) { Objects.requireNonNull(message); // get application properties final ApplicationProperties properties = message.getApplicationProperties(); if (properties == null) { return empty(); } // get value map final Map<?, ?> value = properties.getValue(); if (value == null) { return empty(); } // get status value final Object status = value.get(""status""); if (status == null) { return empty(); } if (status instanceof Number) { // return value as int return of(((Number) status).intValue()); } try { return of(Integer.parseInt(status.toString())); } catch (final NumberFormatException e) { } // return nothing return empty(); } } ","package org.iotbricks.core.amqp.transport.utils; import static java.util.Optional.empty; import static java.util.Optional.of; import java.util.Map; import java.util.Objects; import java.util.Optional; import org.apache.qpid.proton.amqp.messaging.ApplicationProperties; import org.apache.qpid.proton.message.Message; public final class Properties { private Properties() { } /** * Extract the {@code status} value as Integer from the message * * @param message * the message to extract the value from * @return the status value, never {@code null}, but may be * {@link Optional#empty()} */ public static Optional<Integer> status(final Message message) { Objects.requireNonNull(message); // get application properties final ApplicationProperties properties = message.getApplicationProperties(); if (properties == null) { return empty(); } // get value map final Map<?, ?> value = properties.getValue(); if (value == null) { return empty(); } // get status value final Object status = value.get(""status""); if (status instanceof Number) { // return value as int return of(((Number) status).intValue()); } // return nothing return empty(); } } " Make OrganizationWorkspaceManager ignore the original workspace when sharing workspaces with groups,"from workspace.models import GroupPublishedWorkspace, PublishedWorkSpace, WorkSpace def ref_from_workspace(workspace): if isinstance(workspace, WorkSpace): return 'group/' + str(workspace.id) elif isinstance(workspace, PublishedWorkSpace): return 'group_published/' + str(workspace.id) class OrganizationWorkspaceManager: def get_id(self): return 'ezweb_organizations' def update_base_workspaces(self, user, current_workspace_refs): workspaces_to_remove = current_workspace_refs[:] workspaces_to_add = [] user_groups = user.groups.all() # workspaces assigned to the user's groups # the compression list outside the inside compression list is for flattening # the inside list workspaces = [workspace for sublist in [WorkSpace.objects.filter(targetOrganizations=org) for org in user_groups] for workspace in sublist] # published workspaces assigned to the user's groups # the compression list outside the inside compression list is for flattening # the inside list workspaces += [relation.workspace for sublist in [GroupPublishedWorkspace.objects.filter(group=group) for group in user_groups] for relation in sublist] workspaces = set(workspaces) for workspace in workspaces: if workspace.creator == user: # Ignore workspaces created by the user continue ref = ref_from_workspace(workspace) if ref not in current_workspace_refs: workspaces_to_add.append((ref, workspace)) else: workspaces_to_remove.remove(ref) return (workspaces_to_remove, workspaces_to_add) ","from workspace.models import GroupPublishedWorkspace, PublishedWorkSpace, WorkSpace def ref_from_workspace(workspace): if isinstance(workspace, WorkSpace): return 'group/' + str(workspace.id) elif isinstance(workspace, PublishedWorkSpace): return 'group_published/' + str(workspace.id) class OrganizationWorkspaceManager: def get_id(self): return 'ezweb_organizations' def update_base_workspaces(self, user, current_workspace_refs): workspaces_to_remove = current_workspace_refs[:] workspaces_to_add = [] user_groups = user.groups.all() # workspaces assigned to the user's groups # the compression list outside the inside compression list is for flattening # the inside list workspaces = [workspace for sublist in [WorkSpace.objects.filter(targetOrganizations=org) for org in user_groups] for workspace in sublist] # published workspaces assigned to the user's groups # the compression list outside the inside compression list is for flattening # the inside list workspaces += [relation.workspace for sublist in [GroupPublishedWorkspace.objects.filter(group=group) for group in user_groups] for relation in sublist] workspaces = set(workspaces) for workspace in workspaces: ref = ref_from_workspace(workspace) if ref not in current_workspace_refs: workspaces_to_add.append((ref, workspace)) else: workspaces_to_remove.remove(ref) return (workspaces_to_remove, workspaces_to_add) " "Make polestar's config useRawDomain = false Fix https://github.com/uwdata/voyager2/issues/202","'use strict'; // Service for the spec config. // We keep this separate so that changes are kept even if the spec changes. angular.module('vlui') .factory('Config', function() { var Config = {}; Config.data = {}; Config.config = {}; Config.getConfig = function() { return {}; }; Config.getData = function() { return Config.data; }; Config.large = function() { return { cell: { width: 300, height: 300 }, facet: { cell: { width: 150, height: 150 } }, scale: {useRawDomain: false} }; }; Config.small = function() { return { facet: { cell: { width: 150, height: 150 } } }; }; Config.updateDataset = function(dataset, type) { if (dataset.values) { Config.data.values = dataset.values; delete Config.data.url; Config.data.formatType = undefined; } else { Config.data.url = dataset.url; delete Config.data.values; Config.data.formatType = type; } }; return Config; }); ","'use strict'; // Service for the spec config. // We keep this separate so that changes are kept even if the spec changes. angular.module('vlui') .factory('Config', function() { var Config = {}; Config.data = {}; Config.config = {}; Config.getConfig = function() { return {}; }; Config.getData = function() { return Config.data; }; Config.large = function() { return { cell: { width: 300, height: 300 }, facet: { cell: { width: 150, height: 150 } } }; }; Config.small = function() { return { facet: { cell: { width: 150, height: 150 } } }; }; Config.updateDataset = function(dataset, type) { if (dataset.values) { Config.data.values = dataset.values; delete Config.data.url; Config.data.formatType = undefined; } else { Config.data.url = dataset.url; delete Config.data.values; Config.data.formatType = type; } }; return Config; }); " Move back since it's now cached,"{{-- Copyright 2015 ppy Pty. Ltd. This file is part of osu!web. osu!web is distributed with the hope of attracting more community contributions to the core ecosystem of osu!. osu!web is free software: you can redistribute it and/or modify it under the terms of the Affero GNU General Public License version 3 as published by the Free Software Foundation. osu!web is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with osu!web. If not, see <http://www.gnu.org/licenses/>. --}} @foreach($posts as $post) <?php if (Auth::check()) { $withDeleteLink = $post->poster_id === Auth::user()->user_id; } if (!isset($withDeleteLink) || !$withDeleteLink) { $withDeleteLink = authz('ForumPostDelete', $post)->can(); } ?> @include('forum.topics._post', [ 'post' => $post, 'options' => [ 'deleteLink' => $withDeleteLink, 'editLink' => authz('ForumPostEdit', $post)->can(), 'postPosition' => $postsPosition[$post->post_id], 'replyLink' => authz('ForumTopicReply', $topic)->can(), ], ]) @endforeach ","{{-- Copyright 2015 ppy Pty. Ltd. This file is part of osu!web. osu!web is distributed with the hope of attracting more community contributions to the core ecosystem of osu!. osu!web is free software: you can redistribute it and/or modify it under the terms of the Affero GNU General Public License version 3 as published by the Free Software Foundation. osu!web is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with osu!web. If not, see <http://www.gnu.org/licenses/>. --}} <?php $withReplyLink = authz('ForumTopicReply', $topic)->can(); ?> @foreach($posts as $post) <?php if (Auth::check()) { $withDeleteLink = $post->poster_id === Auth::user()->user_id; } if (!isset($withDeleteLink) || !$withDeleteLink) { $withDeleteLink = authz('ForumPostDelete', $post)->can(); } ?> @include('forum.topics._post', [ 'post' => $post, 'options' => [ 'deleteLink' => $withDeleteLink, 'editLink' => authz('ForumPostEdit', $post)->can(), 'postPosition' => $postsPosition[$post->post_id], 'replyLink' => $withReplyLink, ], ]) @endforeach " Add comments to pairing section,"/* * Socket.io Communication */ // module dependencies var crypto = require('crypto'); // variable declarations var socketCodes = {}; module.exports = function(socket) { // establish connection socket.emit('pair:init', {}); // pair mobile and PC // Reference: http://blog.artlogic.com/2013/06/21/phone-to-browser-html5-gaming-using-node-js-and-socket-io/ socket.on('pair:deviceType', function(data) { // if deviceType is 'pc', generate a unique code and send to PC if(data.deviceType == 'pc') { // generate a code var code = crypto.randomBytes(3).toString('hex'); // ensure code is unique while(code in socketCodes) { code = crypto.randomBytes(3).toString('hex'); } // store code / socket assocation socketCodes[code] = this; socket.code = code; // show code on PC socket.emit('pair:sendCode', { code: code }); } // if deviceType is 'mobile', check if submitted code is valid and pair else if(data.deviceType == 'mobile') { socket.on('pair:getCode', function(data) { if(data.code in socketCodes) { // save the code for mobile commands socket.code = data.code; // start mobile connection socket.emit('pair:connected', {}); // start PC connection socketCodes[data.code].emit('pair:connected', {}); } else { socket.emit('pair:fail', {}); socket.disconnect(); } }); } }); };","/* * Socket.io Communication */ // module dependencies var crypto = require('crypto'); // variable declarations var socketCodes = {}; module.exports = function(socket) { // establish connection socket.emit('pair:init', {}); // receive device type socket.on('pair:deviceType', function(data) { // if deviceType is 'pc', generate a unique code and send to PC if(data.deviceType == 'pc') { // generate a code var code = crypto.randomBytes(3).toString('hex'); // ensure uniqueness while(code in socketCodes) { code = crypto.randomBytes(3).toString('hex'); } // store pairing code / socket assocation socketCodes[code] = this; socket.code = code; // show code on PC socket.emit('pair:sendCode', { code: code }); } // if deviceType is 'mobile', check if submitted code is valid and pair else if(data.deviceType == 'mobile') { socket.on('pair:getCode', function(data) { if(data.code in socketCodes) { // save the code for controller commands socket.code = data.code; // initialize the controller socket.emit('pair:connected', {}); // start the PC socketCodes[data.code].emit('pair:connected', {}); } else { socket.emit('pair:fail', {}); socket.disconnect(); } }); } }); };" "Add ""ditu.google.com"" for google maps","// These URL paths will be transformed to CN mirrors. var mirrors = { ""//developers.google.com"" : ""//developers.google.cn"", ""//firebase.google.com"" : ""//firebase.google.cn"", ""//developer.android.com"" : ""//developer.android.google.cn"", ""//angular.io"" : ""//angular.cn"", ""//maps.google.com"" : ""//maps.google.cn"", ""//ditu.google.com"" : ""//ditu.google.cn"", ""google.com/maps"" : ""google.cn/maps"", ""//translate.google.com"" : ""//translate.google.cn"", ""//codelabs.developers.google.com"" : ""//code-labs.cn"", ""//code-labs.io"" : ""//code-labs.cn"" } // These URL paths are not available on CN mirrors, therefore won't be transformed. var whitelist = [ ""//developers.google.com/groups"", ""//developers.google.com/events"", ""//firebase.google.com/support/contact/"", ] function mirrorUrl(url) { // Check for whitelisting. for (var key in whitelist) { if (url.includes(whitelist[key])) { return url; } } // Check for mapping. for (var key in mirrors) { if (url.includes(key)) { url = url.replace(key, mirrors[key]); break; } } return url; } ","// These URL paths will be transformed to CN mirrors. var mirrors = { ""//developers.google.com"" : ""//developers.google.cn"", ""//firebase.google.com"" : ""//firebase.google.cn"", ""//developer.android.com"" : ""//developer.android.google.cn"", ""//angular.io"" : ""//angular.cn"", ""//maps.google.com"" : ""//maps.google.cn"", ""google.com/maps"" : ""google.cn/maps"", ""//translate.google.com"" : ""//translate.google.cn"", ""//codelabs.developers.google.com"" : ""//code-labs.cn"", ""//code-labs.io"" : ""//code-labs.cn"" } // These URL paths are not available on CN mirrors, therefore won't be transformed. var whitelist = [ ""//developers.google.com/groups"", ""//developers.google.com/events"", ""//firebase.google.com/support/contact/"", ] function mirrorUrl(url) { // Check for whitelisting. for (var key in whitelist) { if (url.includes(whitelist[key])) { return url; } } // Check for mapping. for (var key in mirrors) { if (url.includes(key)) { url = url.replace(key, mirrors[key]); break; } } return url; } " "Rename the package to ""nyaa""","#!/usr/bin/env python from setuptools import setup, find_packages def install(): desc = 'A Python client library for nyaa.se!', setup( name='nyaa', version='1.0', description=desc, long_description=desc, author='SuHun Han', author_email='ssut@ssut.me', url='https://github.com/ssut/py-nyaa', classifiers = ['Development Status :: 5 - Production/Stable', 'Intended Audience :: Education', 'Intended Audience :: End Users/Desktop', 'License :: Freeware', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS :: MacOS X', 'Topic :: Education', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4'], packages=find_packages(), install_requires=[ 'requests', 'xmltodict', ], ) if __name__ == ""__main__"": install()","#!/usr/bin/env python from setuptools import setup, find_packages def install(): desc = 'A Python client library for nyaa.se!', setup( name='py-nyaa', version='1.0', description=desc, long_description=desc, author='SuHun Han', author_email='ssut@ssut.me', url='https://github.com/ssut/py-nyaa', classifiers = ['Development Status :: 5 - Production/Stable', 'Intended Audience :: Education', 'Intended Audience :: End Users/Desktop', 'License :: Freeware', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS :: MacOS X', 'Topic :: Education', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4'], packages=find_packages(), install_requires=[ 'requests', 'xmltodict', ], ) if __name__ == ""__main__"": install()" Make test cases easier to identify,"<?php declare(strict_types=1); namespace Doctrine\DBAL\Tests\Functional\Schema; use Doctrine\DBAL\Schema\AbstractSchemaManager; use Doctrine\DBAL\Schema\Comparator; use Doctrine\DBAL\Schema\Table; use Doctrine\DBAL\Tests\FunctionalTestCase; use function array_merge; use function sprintf; use function var_export; class ComparatorTest extends FunctionalTestCase { /** @var AbstractSchemaManager */ private $schemaManager; protected function setUp(): void { $this->schemaManager = $this->connection->getSchemaManager(); } /** * @param callable(AbstractSchemaManager):Comparator $comparatorFactory * @param mixed $value * * @dataProvider defaultValueProvider */ public function testDefaultValueComparison(callable $comparatorFactory, string $type, $value): void { $table = new Table('default_value'); $table->addColumn('test', $type, ['default' => $value]); $this->dropAndCreateTable($table); $onlineTable = $this->schemaManager->listTableDetails('default_value'); self::assertFalse($comparatorFactory($this->schemaManager)->diffTable($table, $onlineTable)); } /** * @return iterable<mixed[]> */ public static function defaultValueProvider(): iterable { foreach (ComparatorTestUtils::comparatorProvider() as $comparatorType => $comparatorArguments) { foreach ( [ ['integer', 1], ['boolean', false], ] as $testArguments ) { yield sprintf( '%s with default %s value %s', $comparatorType, $testArguments[0], var_export($testArguments[1], true) ) => array_merge($comparatorArguments, $testArguments); } } } } ","<?php declare(strict_types=1); namespace Doctrine\DBAL\Tests\Functional\Schema; use Doctrine\DBAL\Schema\AbstractSchemaManager; use Doctrine\DBAL\Schema\Comparator; use Doctrine\DBAL\Schema\Table; use Doctrine\DBAL\Tests\FunctionalTestCase; use function array_merge; class ComparatorTest extends FunctionalTestCase { /** @var AbstractSchemaManager */ private $schemaManager; protected function setUp(): void { $this->schemaManager = $this->connection->getSchemaManager(); } /** * @param callable(AbstractSchemaManager):Comparator $comparatorFactory * @param mixed $value * * @dataProvider defaultValueProvider */ public function testDefaultValueComparison(callable $comparatorFactory, string $type, $value): void { $table = new Table('default_value'); $table->addColumn('test', $type, ['default' => $value]); $this->dropAndCreateTable($table); $onlineTable = $this->schemaManager->listTableDetails('default_value'); self::assertFalse($comparatorFactory($this->schemaManager)->diffTable($table, $onlineTable)); } /** * @return iterable<mixed[]> */ public static function defaultValueProvider(): iterable { foreach (ComparatorTestUtils::comparatorProvider() as $comparatorArguments) { foreach ( [ ['integer', 1], ['boolean', false], ] as $testArguments ) { yield array_merge($comparatorArguments, $testArguments); } } } } " Fix bug about showing totals.,"'use strict'; /* * SummaryBar * * Summary header for record list */ import React, { PropTypes, Component } from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; class SummaryBar extends Component { render() { const { totals } = this.props; return ( <ul className=""record-summary-kpi""> <li> <span>总收入: </span> <span className=""record-positive-val"">{ totals.income }</span> </li> <li> <span>总支出: </span> <span className=""record-negative-val"">{ totals.outcome }</span> </li> <li> { totals.debt > 0 ? <span>净欠款: </span> : <span>净还款: </span> } <span>{ Math.abs(totals.debt) }</span> </li> <li> { totals.loan > 0 ? <span>净借出: </span> : <span>净借入: </span> } <span>{ Math.abs(totals.loan) }</span> </li> <li><FormattedMessage {...messages.unit} /></li> </ul> ); } } SummaryBar.propTypes = { totals: PropTypes.shape({ income: PropTypes.number.isRequired, outcome: PropTypes.number.isRequired, debt: PropTypes.number.isRequired, loan: PropTypes.number.isRequired }).isRequired }; export default SummaryBar;","'use strict'; /* * SummaryBar * * Summary header for record list */ import React, { PropTypes, Component } from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; class SummaryBar extends Component { render() { const { totals } = this.props; return ( <ul className=""record-summary-kpi""> <li> <span>总收入: </span> <span className=""record-positive-val"">{ totals.income }</span> </li> <li> <span>总支出: </span> <span className=""record-negative-val"">{ totals.outcome }</span> </li> <li> { totals.debt > 0 ? <span>净欠款: </span> : <span>净还款: </span> } <span>{ Math.abs(totals.debt) }</span> </li> <li> { totals.debt > 0 ? <span>净借出: </span> : <span>净借入: </span> } <span>{ Math.abs(totals.loan) }</span> </li> <li><FormattedMessage {...messages.unit} /></li> </ul> ); } } SummaryBar.propTypes = { totals: PropTypes.shape({ income: PropTypes.number.isRequired, outcome: PropTypes.number.isRequired, debt: PropTypes.number.isRequired, loan: PropTypes.number.isRequired }).isRequired }; export default SummaryBar;" Fix for md to rst,"#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup try: from pypandoc import convert long_description = convert('README.md', 'md', format='rst') except IOError: print(""warning: README.md not found"") long_description = """" except ImportError: print(""warning: pypandoc module not found, could not convert Markdown to RST"") long_description = """" setup( name=""pybossa-pbs"", version=""1.1"", author=""Daniel Lombraña González"", author_email=""info@pybossa.com"", description=""PyBossa command line client"", long_description=long_description, license=""AGPLv3"", url=""https://github.com/PyBossa/pbs"", classifiers = ['Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Operating System :: OS Independent', 'Programming Language :: Python',], py_modules=['pbs', 'helpers'], install_requires=['Click', 'pybossa-client', 'requests', 'nose', 'mock', 'coverage', 'rednose', 'pypandoc'], entry_points=''' [console_scripts] pbs=pbs:cli ''' ) ","#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup try: from pypandoc import convert read_md = lambda f: convert(f, 'rst') long_description = read_md('README.md') except IOError: print(""warning: README.md not found"") long_description = """" except ImportError: print(""warning: pypandoc module not found, could not convert Markdown to RST"") long_description = """" setup( name=""pybossa-pbs"", version=""1.1"", author=""Daniel Lombraña González"", author_email=""info@pybossa.com"", description=""PyBossa command line client"", long_description=long_description, license=""AGPLv3"", url=""https://github.com/PyBossa/pbs"", classifiers = ['Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Operating System :: OS Independent', 'Programming Language :: Python',], py_modules=['pbs', 'helpers'], install_requires=['Click', 'pybossa-client', 'requests', 'nose', 'mock', 'coverage', 'rednose', 'pypandoc'], entry_points=''' [console_scripts] pbs=pbs:cli ''' ) " Add typehints to the database data collector class,"<?php namespace Common\DataCollector; use SpoonDatabase; use Symfony\Component\HttpKernel\DataCollector\DataCollector; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class DatabaseDataCollector extends DataCollector { /** * @var SpoonDatabase */ private $database; /** * DatabaseDataCollector constructor. * @param SpoonDatabase $database */ public function __construct(SpoonDatabase $database) { $this->database = $database; } /** * {@inheritdoc} */ public function collect(Request $request, Response $response, \Exception $exception = null) { $this->data = array( 'queries' => array_map( function (array $query) { $query['query_formatted'] = \SqlFormatter::format($query['query']); return $query; }, (array) $this->database->getQueries() ), 'queryCount' => count($this->database->getQueries()), ); } /** * @return int */ public function getQueryCount(): int { return $this->data['queryCount']; } /** * @return array[] */ public function getQueries(): array { return $this->data['queries']; } /** * @return string */ public function getName(): string { return 'database'; } } ","<?php namespace Common\DataCollector; use Symfony\Component\HttpKernel\DataCollector\DataCollector; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class DatabaseDataCollector extends DataCollector { private $database; /** * DatabaseDataCollector constructor. * @param \SpoonDatabase $database */ public function __construct(\SpoonDatabase $database) { $this->database = $database; } /** * {@inheritdoc} */ public function collect(Request $request, Response $response, \Exception $exception = null) { $this->data = array( 'queries' => $this->database->getQueries(), 'queryCount' => count($this->database->getQueries()), ); foreach ($this->data['queries'] as &$query) { $query['query_formatted'] = \SqlFormatter::format($query['query']); } } /** * @return mixed */ public function getQueryCount() { return $this->data['queryCount']; } /** * @return mixed */ public function getQueries() { return $this->data['queries']; } /** * @return string */ public function getName() { return 'database'; } } " [FIX] Fix missing id from the onchange,"# -*- coding: utf-8 -*- # © 2016 1200 WebDevelopment <1200wd.com> # © 2017 Therp BV <http://therp.nl> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp import models, fields, api class SaleOrder(models.Model): _inherit = ""sale.order"" sales_channel_id = fields.Many2one( comodel_name='res.partner', string='Sales channel', ondelete='set null', domain=""[('category_id', 'ilike', 'sales channel')]"", index=True, ) @api.multi def onchange_partner_id(self, partner_id): """"""Add values from sales_channel partner, if available."""""" res = super(SaleOrder, self).onchange_partner_id(partner_id) if partner_id: partner = self.env['res.partner'].browse(partner_id) if partner.sales_channel_id: res['value']['sales_channel_id'] = partner.sales_channel_id.id return res @api.model def _prepare_invoice(self, order, lines): """"""Make sure sales_channel_id is set on invoice."""""" val = super(SaleOrder, self)._prepare_invoice(order, lines) if order.sales_channel_id: val.update({ 'sales_channel_id': order.sales_channel_id.id, }) return val ","# -*- coding: utf-8 -*- # © 2016 1200 WebDevelopment <1200wd.com> # © 2017 Therp BV <http://therp.nl> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp import models, fields, api class SaleOrder(models.Model): _inherit = ""sale.order"" sales_channel_id = fields.Many2one( comodel_name='res.partner', string='Sales channel', ondelete='set null', domain=""[('category_id', 'ilike', 'sales channel')]"", index=True, ) @api.multi def onchange_partner_id(self, partner_id): """"""Add values from sales_channel partner, if available."""""" res = super(SaleOrder, self).onchange_partner_id(partner_id) if partner_id: partner = self.env['res.partner'].browse(partner_id) if partner.sales_channel_id: res['value']['sales_channel_id'] = partner.sales_channel_id return res @api.model def _prepare_invoice(self, order, lines): """"""Make sure sales_channel_id is set on invoice."""""" val = super(SaleOrder, self)._prepare_invoice(order, lines) if order.sales_channel_id: val.update({ 'sales_channel_id': order.sales_channel_id.id, }) return val " "Add __eq__, __ne__, __contains__ methods","# encoding: utf-8 ''' @author: Tsuyoshi Hombashi ''' class MinMaxContainer(object): @property def min_value(self): return self.__min_value @property def max_value(self): return self.__max_value def __init__(self, value_list=[]): self.__min_value = None self.__max_value = None for value in value_list: self.update(value) def __eq__(self, other): return all([ self.min_value == other.min_value, self.max_value == other.max_value, ]) def __ne__(self, other): return any([ self.min_value != other.min_value, self.max_value != other.max_value, ]) def __contains__(self, x): return self.min_value <= x <= self.max_value def diff(self): try: return self.max_value - self.min_value except TypeError: return float(""nan"") def mean(self): try: return (self.max_value + self.min_value) * 0.5 except TypeError: return float(""nan"") def update(self, value): if value is None: return if self.__min_value is None: self.__min_value = value else: self.__min_value = min(self.__min_value, value) if self.__max_value is None: self.__max_value = value else: self.__max_value = max(self.__max_value, value) ","# encoding: utf-8 ''' @author: Tsuyoshi Hombashi ''' class MinMaxContainer(object): @property def min_value(self): return self.__min_value @property def max_value(self): return self.__max_value def __init__(self, value_list=[]): self.__min_value = None self.__max_value = None for value in value_list: self.update(value) def diff(self): try: return self.max_value - self.min_value except TypeError: return float(""nan"") def mean(self): try: return (self.max_value + self.min_value) * 0.5 except TypeError: return float(""nan"") def update(self, value): if value is None: return if self.__min_value is None: self.__min_value = value else: self.__min_value = min(self.__min_value, value) if self.__max_value is None: self.__max_value = value else: self.__max_value = max(self.__max_value, value) " Use pytest for unit test,"import pytest from mock import Mock import sys import os import datetime from pytrac import Ticket class TestTicket(object): def setup_class(self): server = Mock() self.ticket = Ticket(server) def testSearchWithAllParams(self): self.ticket.search(summary='test_summary', owner='someowner', status='new') self.ticket.api.query.assert_called_with('max=0&summary~=test_summary&owner=someowner&status=new') class TestUpdateTicket(object): ticket_id = 1 def setup_class(self): server = Mock() self.timestamp = datetime.datetime.now() server.ticket.get.return_value = [self.ticket_id, self.timestamp, self.timestamp, {'_ts': self.timestamp, 'action': 'leave'}] server.ticket.update.return_value = [self.ticket_id, self.timestamp, self.timestamp, {'_ts': self.timestamp, 'action': 'leave'}] self.ticket = Ticket(server) def testComment(self): self.ticket.comment(self.ticket_id, ""some comment"") self.ticket.api.update.assert_called_with( self.ticket_id, comment=""some comment"", attrs={'action': 'leave', '_ts': self.timestamp}, notify=True) if __name__ == '__main__': pytest.main(__file__) ","import unittest from mock import Mock import sys import os import datetime from pytrac import Ticket class TestTicket(unittest.TestCase): def setUp(self): server = Mock() self.ticket = Ticket(server) def testSearchWithAllParams(self): self.ticket.search(summary='test_summary', owner='someowner', status='new') self.ticket.api.query.assert_called_with('max=0&summary~=test_summary&owner=someowner&status=new') class TestUpdateTicket(unittest.TestCase): ticket_id = 1 def setUp(self): server = Mock() self.timestamp = datetime.datetime.now() server.ticket.get.return_value = [self.ticket_id, self.timestamp, self.timestamp, {'_ts': self.timestamp, 'action': 'leave'}] server.ticket.update.return_value = [self.ticket_id, self.timestamp, self.timestamp, {'_ts': self.timestamp, 'action': 'leave'}] self.ticket = Ticket(server) def testComment(self): self.ticket.comment(self.ticket_id, ""some comment"") self.ticket.api.update.assert_called_with( self.ticket_id, comment=""some comment"", attrs={'action': 'leave', '_ts': self.timestamp}, notify=True) if __name__ == '__main__': unittest.main() " "Use built in template dirs list Add user to context","from collections import defaultdict from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA from django.template.backends.base import BaseEngine from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy from . import compiler from . import loader class KnightsTemplater(BaseEngine): def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() super(KnightsTemplater, self).__init__(params) def from_string(self, template_code): tmpl = compiler.kompile(template_code) return Template(tmpl) def get_template(self, template_name): try: tmpl = loader.load_template(template_name, self.template_dirs) except Exception as e: raise TemplateSyntaxError(e).with_traceback(e.__traceback__) if tmpl is None: raise TemplateDoesNotExist(template_name) return Template(tmpl) class Template(object): def __init__(self, template): self.template = template def render(self, context=None, request=None): if context is None: context = {} if request is not None: context['user'] = request.user context['request'] = request context['csrf_input'] = csrf_input_lazy(request) context['csrf_token'] = csrf_token_lazy(request) ctx = defaultdict(str) ctx.update(context) return self.template(ctx) ","from collections import defaultdict from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA from django.template.backends.base import BaseEngine from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy from . import compiler from . import loader class KnightsTemplater(BaseEngine): def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() super(KnightsTemplater, self).__init__(params) for path in params.get('DIRS', []): loader.add_path(path) def from_string(self, template_code): tmpl = compiler.kompile(template_code) return Template(tmpl) def get_template(self, template_name): tmpl = loader.load_template(template_name) if tmpl is None: raise TemplateDoesNotExist(template_name) return Template(tmpl) class Template(object): def __init__(self, template): self.template = template def render(self, context=None, request=None): if context is None: context = {} if request is not None: context['request'] = request context['csrf_input'] = csrf_input_lazy(request) context['csrf_token'] = csrf_token_lazy(request) ctx = defaultdict(str) ctx.update(context) return self.template(ctx) " Add profidence to managed channels,"<?php return [ /* |-------------------------------------------------------------------------- | Config options for the Slack bot |-------------------------------------------------------------------------- | | | */ 'api-url' => 'https://provibloc.slack.com/api/', 'api-token' => env('SLACK_API_TOKEN'), 'admin-token' => env('SLACK_ADMIN_TOKEN'), 'register-token' => env('SLACK_REGISTER_TOKEN'), 'post-url' => env('SLACK_POST_URL'), 'token-expression' => '/api_token: \'([a-zA-Z0-9-]*)\'/', 'auto-join-channels' => ['C04G7GNLT', 'C050GQPC0'], 'command-tokens' => [ '/portrait' => env('SLACK_PORTRAIT_TOKEN'), '/punk' => env('SLACK_PUNK_TOKEN'), ], 'cache-time' => 5, 'jamyl-id' => 'U04JN1L0C', 'channels-to-manage' => [ 'G04FM566L', // api_test 'G04V6HSHC', // group_test 'G04G7KMFM', // p_fc_chat 'G04G7KRUD', // p_fc_pings 'G04GC8QMX', // titan_pings 'G04HPDE74', // cap_fcs 'G04QGUA5H', // p_scouts 'G04N41BB8', // profidence ], ]; ","<?php return [ /* |-------------------------------------------------------------------------- | Config options for the Slack bot |-------------------------------------------------------------------------- | | | */ 'api-url' => 'https://provibloc.slack.com/api/', 'api-token' => env('SLACK_API_TOKEN'), 'admin-token' => env('SLACK_ADMIN_TOKEN'), 'register-token' => env('SLACK_REGISTER_TOKEN'), 'post-url' => env('SLACK_POST_URL'), 'token-expression' => '/api_token: \'([a-zA-Z0-9-]*)\'/', 'auto-join-channels' => ['C04G7GNLT', 'C050GQPC0'], 'command-tokens' => [ '/portrait' => env('SLACK_PORTRAIT_TOKEN'), '/punk' => env('SLACK_PUNK_TOKEN'), ], 'cache-time' => 5, 'jamyl-id' => 'U04JN1L0C', 'channels-to-manage' => [ 'G04FM566L', // api_test 'G04V6HSHC', // group_test 'G04G7KMFM', // p_fc_chat 'G04G7KRUD', // p_fc_pings 'G04GC8QMX', // titan_pings 'G04HPDE74', // cap_fcs 'G04QGUA5H', // p_scouts ], ]; " Add helper function to format numbers.,"""use strict""; /** * Get count of database-wide values. **/ define([ ""underscore"", ""underscore.string"", ""backbone"" ], function(_, _s, Backbone) { var GlobalCountModel = Backbone.Model.extend({ url: function() { return ""_view/global?group=true""; }, /** * Parse the *grouped* values. **/ parse: function(response, options){ var results = {}; if (_.has(response, ""rows"") && _.isArray(response.rows)) { _.each(response.rows, function(row) { results[row.key] = row.value; }); } return results; }, toJSON: function() { var result = this.attributes; // Customize the strings. _.each(_.pairs(this.attributes), function(pair) { result[pair[0] + ""_fmt""] = _s.numberFormat(pair[1], 0); }); return result; }, /* Custom functions. */ /** * Format a field simply (commas after thousands). */ formatSimply: function(fieldName) { return _s.numberFormat(this.get(fieldName), 0); } }); return GlobalCountModel; }); ","""use strict""; /** * Get count of database-wide values. **/ define([ ""underscore"", ""underscore.string"", ""backbone"" ], function(_, _s, Backbone) { var GlobalCountModel = Backbone.Model.extend({ url: function() { return ""_view/global?group=true""; }, /** * Parse the *grouped* values. **/ parse: function(response, options){ var results = {}; if (_.has(response, ""rows"") && _.isArray(response.rows)) { _.each(response.rows, function(row) { results[row.key] = row.value; }); } return results; }, toJSON: function() { var result = this.attributes; // Customize the strings. _.each(_.pairs(this.attributes), function(pair) { result[pair[0] + ""_fmt""] = _s.numberFormat(pair[1], 0); }); return result; } }); return GlobalCountModel; }); " Add newline to end of file,"function checkWindowSize(){ var w = document.documentElement.clientWidth; var panel = document.getElementById(""help-panel""); if (w < 978) { panel.style.position = ""static""; panel.style.width = ""auto""; } else if (w >= 978 && w < 1184) { panel.style.position = ""fixed""; panel.style.width = ""250px""; unfix(); } else { panel.style.position = ""fixed""; panel.style.width = ""275px""; unfix(); } } function unfix() { if (document.readyState === ""complete"") { var panel = document.getElementById(""help-panel""); if (panel.style.position !== ""static"") { var panelRect = panel.getBoundingClientRect(); var yOffset = document.body.clientHeight - 600 - panelRect.height - 95; if (window.pageYOffset > yOffset) { panel.style.top = """" + yOffset + ""px""; panel.style.position = ""absolute""; } else if (window.pageYOffset < yOffset) { panel.style.top = ""95px""; panel.style.position = ""fixed""; } } } } window.addEventListener(""resize"", checkWindowSize); window.addEventListener(""scroll"", unfix); $(document).ready(function() { checkWindowSize(); }); ","function checkWindowSize(){ var w = document.documentElement.clientWidth; var panel = document.getElementById(""help-panel""); if (w < 978) { panel.style.position = ""static""; panel.style.width = ""auto""; } else if (w >= 978 && w < 1184) { panel.style.position = ""fixed""; panel.style.width = ""250px""; unfix(); } else { panel.style.position = ""fixed""; panel.style.width = ""275px""; unfix(); } } function unfix() { if (document.readyState === ""complete"") { var panel = document.getElementById(""help-panel""); if (panel.style.position !== ""static"") { var panelRect = panel.getBoundingClientRect(); var yOffset = document.body.clientHeight - 600 - panelRect.height - 95; if (window.pageYOffset > yOffset) { panel.style.top = """" + yOffset + ""px""; panel.style.position = ""absolute""; } else if (window.pageYOffset < yOffset) { panel.style.top = ""95px""; panel.style.position = ""fixed""; } } } } window.addEventListener(""resize"", checkWindowSize); window.addEventListener(""scroll"", unfix); $(document).ready(function() { checkWindowSize(); });" Delete useless configs. Replace module section. Added devtool,"const rules = require(""./rules""); const webpack = require(""webpack""); const HtmlWebpackPlugin = require(""html-webpack-plugin""); const CleanWebpackPlugin = require(""clean-webpack-plugin""); const UglifyJSPlugin = require(""uglifyjs-webpack-plugin""); const path = require(""path""); module.exports = { context: path.join(__dirname, ""..""), entry: [""./src/index.ts""], output: { filename: ""build.js"", path: path.resolve(""./dist""), publicPath: ""/"" }, devtool: ""source-map"", resolve: { extensions: [ "".ts"", "".js"", "".json"" ] }, module: { rules: rules }, plugins: [ new CleanWebpackPlugin([""dist""], { root: path.join(__dirname, "".."") }), new UglifyJSPlugin({ uglifyOptions: { ecma: 5, compress: { dead_code: true, drop_console: true, toplevel: true, unsafe_proto: true, warnings: true }, output: { indent_level: 2, beautify: false } } }), new webpack.optimize.CommonsChunkPlugin({ name: ""manifest"", filename: ""manifest.js"", minChunks: Infinity }), new HtmlWebpackPlugin({ template: ""./src/index.html"", inject: ""body"", hash: true }) ] }; ","const rules = require(""./rules""); const webpack = require(""webpack""); const HtmlWebpackPlugin = require(""html-webpack-plugin""); const CleanWebpackPlugin = require(""clean-webpack-plugin""); const UglifyJSPlugin = require(""uglifyjs-webpack-plugin""); const path = require(""path""); module.exports = { context: path.join(__dirname, ""..""), entry: [""./src/index.ts""], output: { filename: ""build.js"", path: path.resolve(""./dist""), publicPath: ""/"" }, devtool: """", resolve: { extensions: [ "".ts"", "".js"", "".json"" ] }, resolveLoader: { modules: [""node_modules""] }, plugins: [ new CleanWebpackPlugin([""dist""], { root: path.join(__dirname, "".."") }), new UglifyJSPlugin({ uglifyOptions: { ecma: 5, compress: { dead_code: true, drop_console: true, toplevel: true, unsafe_proto: true, warnings: true }, output: { indent_level: 2, beautify: false } } }), new webpack.optimize.CommonsChunkPlugin({ name: ""manifest"", filename: ""manifest.js"", minChunks: Infinity }), new HtmlWebpackPlugin({ template: ""./src/index.html"", inject: ""body"", hash: true }) ], module: { rules: rules } }; " Use host instead of hostname,"/** * Created by crispin on 10/12/2015. */ function loadEmbedIframe(onSave) { // add modal window $('.workspace-menu').append(templates.embedIframe()); // variables var modal = $("".modal""); // modal functions function closeModal() { modal.remove(); } function saveUrl() { var embedUrl = $('input#embed-url').val(); var fullWidth = $('input#full-width-checkbox').is(':checked'); if (!embedUrl) { console.log(""No url added""); sweetAlert('URL field is empty', 'Please add a url and save again'); return; } var parsedEmbedUrl = new URL(embedUrl); console.log(parsedEmbedUrl); console.log(window.location); if (parsedEmbedUrl.host === window.location.host) { embedUrl = parsedEmbedUrl.pathname; } onSave('<ons-interactive url=""' + embedUrl + '"" full-width=""' + fullWidth + '""/>'); modal.remove(); } // bind events $('.btn-embed-cancel').click(function() { closeModal(); }); $('.btn-embed-save').click(function() { saveUrl(); }); modal.keyup(function(e) { if (e.keyCode == 27) { //close on esc key closeModal() } if (e.keyCode == 13) { //save on enter key saveUrl(); } }); }","/** * Created by crispin on 10/12/2015. */ function loadEmbedIframe(onSave) { // add modal window $('.workspace-menu').append(templates.embedIframe()); // variables var modal = $("".modal""); // modal functions function closeModal() { modal.remove(); } function saveUrl() { var embedUrl = $('input#embed-url').val(); var fullWidth = $('input#full-width-checkbox').is(':checked'); if (!embedUrl) { console.log(""No url added""); sweetAlert('URL field is empty', 'Please add a url and save again'); return; } var parsedEmbedUrl = new URL(embedUrl); if (parsedEmbedUrl.hostname === window.location.hostname) { embedUrl = parsedEmbedUrl.pathname; } onSave('<ons-interactive url=""' + embedUrl + '"" full-width=""' + fullWidth + '""/>'); modal.remove(); } // bind events $('.btn-embed-cancel').click(function() { closeModal(); }); $('.btn-embed-save').click(function() { saveUrl(); }); modal.keyup(function(e) { if (e.keyCode == 27) { //close on esc key closeModal() } if (e.keyCode == 13) { //save on enter key saveUrl(); } }); }" Make sure test dates are rounded properly by making they are over a day in the past.,"import datetime from osf_tests.factories import PreprintFactory, PreprintProviderFactory from osf.models import PreprintService from nose.tools import * # PEP8 asserts import mock import pytest import pytz import requests from scripts.analytics.preprint_summary import PreprintSummary @pytest.fixture() def preprint_provider(): return PreprintProviderFactory(name='Test 1') @pytest.fixture() def preprint(preprint_provider): return PreprintFactory._build(PreprintService, provider=preprint_provider) pytestmark = pytest.mark.django_db class TestPreprintCount: def test_get_preprint_count(self, preprint): requests.post = mock.MagicMock() resp = requests.Response() resp._content = '{""hits"" : {""total"" : 1}}' requests.post.return_value = resp field = PreprintService._meta.get_field('date_created') field.auto_now_add = False # We have to fudge the time because Keen doesn't allow same day queries. date = datetime.datetime.utcnow() - datetime.timedelta(days=1, hours=1) preprint.date_created = date - datetime.timedelta(hours=1) preprint.save() field.auto_now_add = True results = PreprintSummary().get_events(date.date()) assert_equal(len(results), 1) data = results[0] assert_equal(data['provider']['name'], 'Test 1') assert_equal(data['provider']['total'], 1) ","import datetime from osf_tests.factories import PreprintFactory, PreprintProviderFactory from osf.models import PreprintService from nose.tools import * # PEP8 asserts import mock import pytest import pytz import requests from scripts.analytics.preprint_summary import PreprintSummary @pytest.fixture() def preprint_provider(): return PreprintProviderFactory(name='Test 1') @pytest.fixture() def preprint(preprint_provider): return PreprintFactory._build(PreprintService, provider=preprint_provider) pytestmark = pytest.mark.django_db class TestPreprintCount: def test_get_preprint_count(self, preprint_provider, preprint): requests.post = mock.MagicMock() resp = requests.Response() resp._content = '{""hits"" : {""total"" : 1}}' requests.post.return_value = resp field = PreprintService._meta.get_field('date_created') field.auto_now_add = False # We have to fudge the time because Keen doesn't allow same day queries. date = datetime.datetime.utcnow() - datetime.timedelta(1) preprint.date_created = date - datetime.timedelta(0.1) preprint.save() field.auto_now_add = True results = PreprintSummary().get_events(date.date()) assert_equal(len(results), 1) data = results[0] assert_equal(data['provider']['name'], 'Test 1') assert_equal(data['provider']['total'], 1) " Add option to edit currency,""""""" Django Forms for interacting with Company app """""" # -*- coding: utf-8 -*- from __future__ import unicode_literals from InvenTree.forms import HelperForm from .models import Company from .models import SupplierPart from .models import SupplierPriceBreak class EditCompanyForm(HelperForm): """""" Form for editing a Company object """""" class Meta: model = Company fields = [ 'name', 'description', 'website', 'address', 'phone', 'email', 'contact', 'is_customer', 'is_supplier', 'notes' ] class CompanyImageForm(HelperForm): """""" Form for uploading a Company image """""" class Meta: model = Company fields = [ 'image' ] class EditSupplierPartForm(HelperForm): """""" Form for editing a SupplierPart object """""" class Meta: model = SupplierPart fields = [ 'part', 'supplier', 'SKU', 'description', 'manufacturer', 'MPN', 'URL', 'note', 'base_cost', 'multiple', 'packaging', 'lead_time' ] class EditPriceBreakForm(HelperForm): """""" Form for creating / editing a supplier price break """""" class Meta: model = SupplierPriceBreak fields = [ 'part', 'quantity', 'cost', 'currency', ] ",""""""" Django Forms for interacting with Company app """""" # -*- coding: utf-8 -*- from __future__ import unicode_literals from InvenTree.forms import HelperForm from .models import Company from .models import SupplierPart from .models import SupplierPriceBreak class EditCompanyForm(HelperForm): """""" Form for editing a Company object """""" class Meta: model = Company fields = [ 'name', 'description', 'website', 'address', 'phone', 'email', 'contact', 'is_customer', 'is_supplier', 'notes' ] class CompanyImageForm(HelperForm): """""" Form for uploading a Company image """""" class Meta: model = Company fields = [ 'image' ] class EditSupplierPartForm(HelperForm): """""" Form for editing a SupplierPart object """""" class Meta: model = SupplierPart fields = [ 'part', 'supplier', 'SKU', 'description', 'manufacturer', 'MPN', 'URL', 'note', 'base_cost', 'multiple', 'packaging', 'lead_time' ] class EditPriceBreakForm(HelperForm): """""" Form for creating / editing a supplier price break """""" class Meta: model = SupplierPriceBreak fields = [ 'part', 'quantity', 'cost' ] " Remove test server url and disable guzzle exceptions,"<?php namespace RIPS\APIConnector; use GuzzleHttp\Client; use RIPS\APIConnector\Requests\UserRequests; use RIPS\APIConnector\Requests\OrgRequests; use RIPS\APIConnector\Requests\QuotaRequests; class API { // @var string - version number public $version = '0.0.1'; // @var UserRequests public $users; // @var OrgRequests public $orgs; // @var QuotaRequests public $quotas; // @var array - Config values for $client protected $clientConfig = [ 'base_uri' => 'http://localhost:8000', 'timeout' => 10, 'connect_timeout' => 10, 'http_errors' => false, ]; /** * Initialize new API * * @param string $username * @param string $password * @param array $clientConfig */ public function __construct(string $username, string $password, array $clientConfig = []) { $mergedConfig = array_merge($this->clientConfig, $clientConfig, [ 'headers' => [ 'X-API-Username' => $username, 'X-API-Password' => $password, 'User-Agent' => ""RIPS-API-Connector/{$this->version}"", ], ]); $client = new Client($mergedConfig); $this->users = new UserRequests($client); $this->orgs = new OrgRequests($client); $this->quotas = new QuotaRequests($client); } } ","<?php namespace RIPS\APIConnector; use GuzzleHttp\Client; use RIPS\APIConnector\Requests\UserRequests; use RIPS\APIConnector\Requests\OrgRequests; use RIPS\APIConnector\Requests\QuotaRequests; class API { // @var string - version number public $version = '0.0.1'; // @var UserRequests public $users; // @var OrgRequests public $orgs; // @var QuotaRequests public $quotas; // @var array - Config values for $client protected $clientConfig = [ 'base_uri' => 'https://api-test2.internal.ripstech.com', 'timeout' => 10, 'connect_timeout' => 10, ]; /** * Initialize new API * * @param string $username * @param string $password * @param array $clientConfig */ public function __construct(string $username, string $password, array $clientConfig = []) { $mergedConfig = array_merge($this->clientConfig, $clientConfig, [ 'headers' => [ 'X-API-Username' => $username, 'X-API-Password' => $password, 'User-Agent' => ""RIPS-API-Connector/{$this->version}"", ], ]); $client = new Client($mergedConfig); $this->users = new UserRequests($client); $this->orgs = new OrgRequests($client); $this->quotas = new QuotaRequests($client); } } " Add pdo try again as lost connection message,"<?php namespace Illuminate\Database; use Illuminate\Support\Str; use Throwable; trait DetectsLostConnections { /** * Determine if the given exception was caused by a lost connection. * * @param \Throwable $e * @return bool */ protected function causedByLostConnection(Throwable $e) { $message = $e->getMessage(); return Str::contains($message, [ 'server has gone away', 'no connection to the server', 'Lost connection', 'is dead or not enabled', 'Error while sending', 'decryption failed or bad record mac', 'server closed the connection unexpectedly', 'SSL connection has been closed unexpectedly', 'Error writing data to the connection', 'Resource deadlock avoided', 'Transaction() on null', 'child connection forced to terminate due to client_idle_limit', 'query_wait_timeout', 'reset by peer', 'Physical connection is not usable', 'TCP Provider: Error code 0x68', 'ORA-03114', 'Packets out of order. Expected', 'Adaptive Server connection failed', 'Communication link failure', 'connection is no longer usable', 'Login timeout expired', 'Connection refused', 'running with the --read-only option so it cannot execute this statement', 'The connection is broken and recovery is not possible. The connection is marked by the client driver as unrecoverable. No attempt was made to restore the connection.', 'SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Try again', ]); } } ","<?php namespace Illuminate\Database; use Illuminate\Support\Str; use Throwable; trait DetectsLostConnections { /** * Determine if the given exception was caused by a lost connection. * * @param \Throwable $e * @return bool */ protected function causedByLostConnection(Throwable $e) { $message = $e->getMessage(); return Str::contains($message, [ 'server has gone away', 'no connection to the server', 'Lost connection', 'is dead or not enabled', 'Error while sending', 'decryption failed or bad record mac', 'server closed the connection unexpectedly', 'SSL connection has been closed unexpectedly', 'Error writing data to the connection', 'Resource deadlock avoided', 'Transaction() on null', 'child connection forced to terminate due to client_idle_limit', 'query_wait_timeout', 'reset by peer', 'Physical connection is not usable', 'TCP Provider: Error code 0x68', 'ORA-03114', 'Packets out of order. Expected', 'Adaptive Server connection failed', 'Communication link failure', 'connection is no longer usable', 'Login timeout expired', 'Connection refused', 'running with the --read-only option so it cannot execute this statement', 'The connection is broken and recovery is not possible. The connection is marked by the client driver as unrecoverable. No attempt was made to restore the connection.', ]); } } " Use the absolute path for the long description to work around CI issues.,"import os from distutils.core import setup version = '0.9.3' here = os.path.abspath(os.path.dirname(__file__)) def read_file(name): return open(os.path.join(here, name)).read() readme = read_file('README.rst') changes = read_file('CHANGES') setup( name='django-maintenancemode', version=version, description='Django-maintenancemode allows you to temporary shutdown your site for maintenance work', long_description='\n\n'.join([readme, changes]), author='Remco Wendt', author_email='remco@maykinmedia.nl', license=""BSD"", platforms=[""any""], url='https://github.com/shanx/django-maintenancemode', packages=[ 'maintenancemode', 'maintenancemode.conf', 'maintenancemode.conf.settings', 'maintenancemode.conf.urls', 'maintenancemode.tests', 'maintenancemode.views', ], package_data={ 'maintenancemode': [ 'tests/templates/503.html', ], }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities', ], ) ","import os from distutils.core import setup version = '0.9.3' def read_file(name): return open(os.path.join(os.path.dirname(__file__), name)).read() readme = read_file('README.rst') changes = read_file('CHANGES') setup( name='django-maintenancemode', version=version, description='Django-maintenancemode allows you to temporary shutdown your site for maintenance work', long_description='\n\n'.join([readme, changes]), author='Remco Wendt', author_email='remco@maykinmedia.nl', license=""BSD"", platforms=[""any""], url='https://github.com/shanx/django-maintenancemode', packages=[ 'maintenancemode', 'maintenancemode.conf', 'maintenancemode.conf.settings', 'maintenancemode.conf.urls', 'maintenancemode.tests', 'maintenancemode.views', ], package_data={ 'maintenancemode': [ 'tests/templates/503.html', ], }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities', ], ) " Fix file not found bug,"<?php namespace Way\Generators\Commands; use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; class ControllerGeneratorCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'generate:controller'; /** * The console command description. * * @var string */ protected $description = 'Generate a resourceful controller'; /** * Generate the controller */ public function fire() { // This command is nothing more than a helper, // that points directly to Laravel's // controller:make command $this->call('controller:make', [ 'name' => $this->argument('controllerName'), '--path' => $this->option('path') ]); } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return array( array('controllerName', InputArgument::REQUIRED, 'The name of the desired controller') ); } /** * Get the console command options. * * @return array */ protected function getOptions() { return array( array('path', null, InputOption::VALUE_OPTIONAL, 'Where should the file be created?'), ); } } ","<?php namespace Way\Generators\Commands; use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; class ControllerGeneratorCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'generate:controller'; /** * The console command description. * * @var string */ protected $description = 'Generate a resourceful controller'; /** * Generate the controller */ public function fire() { // This command is nothing more than a helper, // that points directly to Laravel's // controller:make command $this->call('controller:make', [ 'name' => $this->argument('controllerName'), '--path' => $this->option('path') ]); } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return array( array('controllerName', InputArgument::REQUIRED, 'The name of the desired controller') ); } /** * Get the console command options. * * @return array */ protected function getOptions() { return array( array('path', null, InputOption::VALUE_OPTIONAL, 'Where should the file be created?', app_path('controllers')), ); } } " "core: Use enum name to search providers Currently we build search queries for providers using the numeric value of the type, and comparing it to the ""providers.provider_type"" database column. But this column stores the name of the enum, not the numeric value. This patch changes the autocompleter so that it uses the name. Change-Id: I4822be2cfd57c093d4fdf11f0410c055faea8be2 Bug-Url: https://bugzilla.redhat.com/1145247 Signed-off-by: Juan Hernandez <59e5b8140de97cc91c3fb6c5342dce948469af8c@redhat.com>","package org.ovirt.engine.core.searchbackend; import org.ovirt.engine.core.common.businessentities.ProviderType; public class ProviderConditionFieldAutoCompleter extends BaseConditionFieldAutoCompleter { public static final String NAME = ""NAME""; public static final String TYPE = ""TYPE""; public static final String DESCRIPTION = ""DESCRIPTION""; public static final String URL = ""URL""; public ProviderConditionFieldAutoCompleter() { // Building the basic verbs dict. mVerbs.add(NAME); mVerbs.add(TYPE); mVerbs.add(DESCRIPTION); mVerbs.add(URL); // Building the autoCompletion dict. buildCompletions(); // Building the types dict. getTypeDictionary().put(NAME, String.class); getTypeDictionary().put(TYPE, ProviderType.class); getTypeDictionary().put(DESCRIPTION, String.class); getTypeDictionary().put(URL, String.class); // building the ColumnName dict. columnNameDict.put(NAME, ""name""); columnNameDict.put(TYPE, ""provider_type""); columnNameDict.put(DESCRIPTION, ""description""); columnNameDict.put(URL, ""url""); // Building the validation dict. buildBasicValidationTable(); } @Override public IAutoCompleter getFieldRelationshipAutoCompleter(final String fieldName) { return StringConditionRelationAutoCompleter.INSTANCE; } @Override public IConditionValueAutoCompleter getFieldValueAutoCompleter(String fieldName) { if (TYPE.equals(fieldName)) { return new EnumNameAutoCompleter(ProviderType.class); } return null; } } ","package org.ovirt.engine.core.searchbackend; import org.ovirt.engine.core.common.businessentities.ProviderType; public class ProviderConditionFieldAutoCompleter extends BaseConditionFieldAutoCompleter { public static final String NAME = ""NAME""; public static final String TYPE = ""TYPE""; public static final String DESCRIPTION = ""DESCRIPTION""; public static final String URL = ""URL""; public ProviderConditionFieldAutoCompleter() { // Building the basic verbs dict. mVerbs.add(NAME); mVerbs.add(TYPE); mVerbs.add(DESCRIPTION); mVerbs.add(URL); // Building the autoCompletion dict. buildCompletions(); // Building the types dict. getTypeDictionary().put(NAME, String.class); getTypeDictionary().put(TYPE, ProviderType.class); getTypeDictionary().put(DESCRIPTION, String.class); getTypeDictionary().put(URL, String.class); // building the ColumnName dict. columnNameDict.put(NAME, ""name""); columnNameDict.put(TYPE, ""provider_type""); columnNameDict.put(DESCRIPTION, ""description""); columnNameDict.put(URL, ""url""); // Building the validation dict. buildBasicValidationTable(); } @Override public IAutoCompleter getFieldRelationshipAutoCompleter(final String fieldName) { return StringConditionRelationAutoCompleter.INSTANCE; } @Override public IConditionValueAutoCompleter getFieldValueAutoCompleter(String fieldName) { if (TYPE.equals(fieldName)) { return new EnumValueAutoCompleter(ProviderType.class); } return null; } } " Move back to using callbacks instead of promises," var utils = { find: (url, config) => { for (var key in config) { var item = config[key] if (item.domains.some((domain) => (url.host === domain))) { item.key = key return item } } }, // The custom code is injected into style and script tags // at the end of the head tag // in order to give them enough weight for successful override load: (item, done) => { var load = file() var css = [], js = [] var exit = () => ( css.length === (item.inject.css || []).length && js.length === (item.inject.js || []).length ) && done(null, {css: utils.concat(css), js: utils.concat(js)}) var loop = (filtes, result) => { for (var i=0; i < filtes.length; i++) { load('sites/' + item.key + '/' + filtes[i], (err, code) => { result.push({file: filtes[i], code}) exit() }) } } loop(item.inject.css || [], css) loop(item.inject.js || [], js) }, concat: (items) => items.reduce((result, item) => (result += '\n/*' + item.file + '*/\n' + item.code.replace(/@-moz-document[^{]*\{/gi, '') ) || result , '') } "," var utils = { find: (url, config) => { for (var key in config) { var item = config[key] if (item.domains.some((domain) => (url.host === domain))) { item.key = key return item } } }, // The custom code is injected into style and script tags // at the end of the head tag // in order to give them enough weight for successful override load: (item, done) => { var load = file({promise: true}) var styles = (item.inject.css || []) .map((file) => load('sites/' + item.key + '/' + file)) var scripts = (item.inject.js || []) .map((file) => load('sites/' + item.key + '/' + file)) Promise.all([ new Promise((resolve, reject) => Promise.all(styles) .then((styles) => resolve({css: utils.concat(styles)})).catch(reject) ), new Promise((resolve, reject) => Promise.all(scripts) .then((scripts) => resolve({js: utils.concat(scripts)})).catch(reject) ) ]) .then((result) => done(null, {css: result[0].css, js: result[1].js})) .catch(done) }, concat: (files) => Object.keys(files).reduce((code, index) => (code += '\n/*' + index + '*/\n' + files[index].replace(/@-moz-document[^{]*\{/gi, '')) || code , '') } " "Add Schema edit link to top nav Don't think I like it there atm.","""use strict""; var m = require(""mithril""), db = require(""../lib/firebase""), layout = require(""./layout""), listings = require(""./content/listings""); module.exports = { controller : function() { var ctrl = this, schema = m.route.param(""schema""); db.child(""schemas/"" + schema).on(""value"", function(snap) { ctrl.schema = snap.val(); ctrl.schema.key = snap.key(); m.redraw(); }); ctrl.edit = function() { m.route(""/schema/"" + ctrl.schema.key); }; }, view : function(ctrl) { if(!ctrl.schema) { return m.component(layout, { title : ""Loading..."" }); } return m.component(layout, { title : [ ctrl.schema.name, m(""button.mdl-button.mdl-js-button.mdl-button--icon.mdl-button--accent"", { onclick : ctrl.edit }, m(""i.material-icons"", ""edit"") ), ], content : m.component(listings, { schema : ctrl.schema }) }); } }; ","""use strict""; var m = require(""mithril""), db = require(""../lib/firebase""), layout = require(""./layout""), listings = require(""./content/listings""); module.exports = { controller : function() { var ctrl = this, schema = m.route.param(""schema""); db.child(""schemas/"" + schema).on(""value"", function(snap) { ctrl.schema = snap.val(); ctrl.schema.key = snap.key(); m.redraw(); }); }, view : function(ctrl) { if(!ctrl.schema) { return m.component(layout, { title : ""Loading..."" }); } return m.component(layout, { title : ctrl.schema.name, content : m(""div"", m(""p"", m(""a"", { href : ""/schema/"" + ctrl.schema.key }, ""Edit "" + ctrl.schema.name) ), m.component(listings, { schema : ctrl.schema }) ) }); } }; " "Remove TODO - complete as of last commit Season object is passed to the table update","import requests from nflpool.data.dbsession import DbSessionFactory from nflpool.data.activeplayers import ActiveNFLPlayers import nflpool.data.secret as secret from requests.auth import HTTPBasicAuth from nflpool.data.seasoninfo import SeasonInfo class ActivePlayersService: @classmethod def add_active_nflplayers(cls, season: int, team_id: int, firstname: str, lastname: str, position: str, player_id: int): session = DbSessionFactory.create_session() season_row = session.query(SeasonInfo).filter(SeasonInfo.id == '1').first() season = season_row.current_season response = requests.get('https://api.mysportsfeeds.com/v1.1/pull/nfl/' + season + '-regular/active_players.json', auth=HTTPBasicAuth(secret.msf_username, secret.msf_pw)) player_info = response.json() player_list = player_info[""activeplayers""][""playerentry""] for players in player_list: try: firstname = (players[""player""][""FirstName""]) lastname = (players[""player""][""LastName""]) player_id = (players[""player""][""ID""]) team_id = (players[""team""][""ID""]) position = (players[""player""][""Position""]) except KeyError: continue active_players = ActiveNFLPlayers(firstname=firstname, lastname=lastname, player_id=player_id, team_id=team_id, position=position, season=season) session.add(active_players) session.commit() ","import requests from nflpool.data.dbsession import DbSessionFactory from nflpool.data.activeplayers import ActiveNFLPlayers import nflpool.data.secret as secret from requests.auth import HTTPBasicAuth from nflpool.data.seasoninfo import SeasonInfo class ActivePlayersService: @classmethod def add_active_nflplayers(cls, season: int, team_id: int, firstname: str, lastname: str, position: str, player_id: int): session = DbSessionFactory.create_session() season_row = session.query(SeasonInfo).filter(SeasonInfo.id == '1').first() season = season_row.current_season response = requests.get('https://api.mysportsfeeds.com/v1.1/pull/nfl/' + season + '-regular/active_players.json', auth=HTTPBasicAuth(secret.msf_username, secret.msf_pw)) player_info = response.json() player_list = player_info[""activeplayers""][""playerentry""] for players in player_list: try: firstname = (players[""player""][""FirstName""]) lastname = (players[""player""][""LastName""]) player_id = (players[""player""][""ID""]) team_id = (players[""team""][""ID""]) position = (players[""player""][""Position""]) except KeyError: continue # TODO Update season='2017' below to a variable active_players = ActiveNFLPlayers(firstname=firstname, lastname=lastname, player_id=player_id, team_id=team_id, position=position, season=season) session.add(active_players) session.commit() " Add basic output of found lines,"import os from clint.textui import colored class Searcher(object): """"""Searches files in dirs for specified string."""""" def __init__(self, currentdir, string_to_search_for): self.currentdir = currentdir self.string_to_search_for = string_to_search_for self.get_files_in_currentdir() def get_files_in_currentdir(self): # TODO implement iterator file; iterate lines file_list = [] for f in os.listdir(self.currentdir): if not os.path.isdir(f): file_list.append(f) if self.string_to_search_for: matched_file_dict = self.search_files_in_dir_for_string(file_list) if matched_file_dict: self.print_nicely(matched_file_dict) else: for f in file_list: print f def search_files_in_dir_for_string(self, file_list): matched_file_dict = {} for f in file_list: matched_line_dict = self.search_file_for_string(f) if matched_line_dict: matched_file_dict[f] = matched_line_dict return matched_file_dict def search_file_for_string(self, f): matched_line_dict = {} with open(f) as f: for index, line in enumerate(f): if self.string_to_search_for in line: matched_line_dict[index] = line return matched_line_dict def print_nicely(self, matched_file_dict): for key, value in matched_file_dict.iteritems(): for k, v in value.iteritems(): print (colored.magenta('./' + key + ':', True, False) + str(k) + ':' + v), ","import os class Searcher(object): """"""Searches files in dirs for specified string."""""" def __init__(self, currentdir, string_to_search_for): self.currentdir = currentdir self.string_to_search_for = string_to_search_for self.get_files_in_currentdir() def search_files_in_dir_for_string(self, file_list): for f in file_list: self.search_file_for_string(f) def get_files_in_currentdir(self): # TODO implement iterator file; iterate lines file_list = [] for f in os.listdir(self.currentdir): if not os.path.isdir(f): file_list.append(f) if self.string_to_search_for: self.search_files_in_dir_for_string(file_list) else: for f in file_list: print f def search_file_for_string(self, f): with open(f) as f: for line in f: if self.string_to_search_for in line: print 'now' def search_subdir(self): pass" "Return the event object when you call on, once or off"," function Events() { var listeners = {} $.extend(this, { on: function(type, cb) { if (!$.isArray(listeners[type])) listeners[type] = [] if (listeners[type].indexOf(cb) < 0) listeners[type].push(cb) return this; }, once: function(type, cb) { this.on(type, function observer() { this.off(type, observer) cb.apply(this, arguments) }) return this; }, emit: function(type) { var result = [] if (!$.isArray(listeners[type])) listeners[type] = [] var args = Array.prototype.slice.call(arguments, 1) var cbs = listeners[type].slice() while (cbs.length > 0) { result.push(cbs.shift().apply(this, args)) } return result }, call: function(type) { var result = this.emit.apply(this, arguments) if (result.length > 1) warn(""Too many results, choosing the first one"") return result[0] }, off: function(type, cb) { if (cb == undefined) throw new Error(""You cannot remove all listeners on an event"") if (!$.isFunction(cb)) throw new Error(""You must pass a listener to Event.off"") var index = listeners[type].indexOf(cb) if (index != undefined && index >= 0) { listeners[type].splice(index, 1); } return this; }, }) } "," function Events() { var listeners = {} $.extend(this, { on: function(type, cb) { if (!$.isArray(listeners[type])) listeners[type] = [] if (listeners[type].indexOf(cb) < 0) listeners[type].push(cb) }, once: function(type, cb) { this.on(type, function observer() { this.off(type, observer) cb.apply(this, arguments) }) }, emit: function(type) { var result = [] if (!$.isArray(listeners[type])) listeners[type] = [] var args = Array.prototype.slice.call(arguments, 1) var cbs = listeners[type].slice() while (cbs.length > 0) { result.push(cbs.shift().apply(this, args)) } return result }, call: function(type) { var result = this.emit.apply(this, arguments) if (result.length > 1) warn(""Too many results, choosing the first one"") return result[0] }, off: function(type, cb) { if (cb == undefined) throw new Error(""You cannot remove all listeners on an event"") if (!$.isFunction(cb)) throw new Error(""You must pass a listener to Event.off"") var index = listeners[type].indexOf(cb) if (index != undefined && index >= 0) { listeners[type].splice(index, 1); } }, }) } " Correct the Object service after rename of object_service.py file to object.py,"import os # Database configurations. DB_HOST = os.environ.get('OBJECTCUBE_DB_HOST', 'localhost') DB_USER = os.environ.get('OBJECTCUBE_DB_USER', os.environ.get('LOGNAME')) DB_PORT = int(os.environ.get('OBJECTCUBE_DB_PORT', 5432)) DB_DBNAME = os.environ.get('OBJECTCUBE_DB_NAME', os.environ.get('LOGNAME')) DB_PASSWORD = os.environ.get('OBJECTCUBE_DB_PASSWORD', os.environ.get('LOGNAME')) # Concept service configuration. FACTORY_CONFIG = { 'TagService': 'objectcube.services.impl.postgresql.tag.' 'TagService', 'DimensionService': 'objectcube.services.impl.postgresql.dimension.' 'DimensionService', 'ObjectService': 'objectcube.services.impl.postgresql.object.' 'ObjectService', 'BlobService': 'objectcube.services.impl.filesystem.' 'blob_service.FileBlobService', 'ConceptService': 'objectcube.services.impl.postgresql.concept.' 'ConceptService', 'PluginService': 'objectcube.services.impl.postgresql.plugin.' 'PluginService', 'TaggingService': 'objectcube.services.impl.postgresql.tagging.' 'TaggingService', } PLUGINS = ( 'objectcube.plugin.exif.ExifPlugin' ) ","import os # Database configurations. DB_HOST = os.environ.get('OBJECTCUBE_DB_HOST', 'localhost') DB_USER = os.environ.get('OBJECTCUBE_DB_USER', os.environ.get('LOGNAME')) DB_PORT = int(os.environ.get('OBJECTCUBE_DB_PORT', 5432)) DB_DBNAME = os.environ.get('OBJECTCUBE_DB_NAME', os.environ.get('LOGNAME')) DB_PASSWORD = os.environ.get('OBJECTCUBE_DB_PASSWORD', os.environ.get('LOGNAME')) # Concept service configuration. FACTORY_CONFIG = { 'TagService': 'objectcube.services.impl.postgresql.tag.' 'TagService', 'DimensionService': 'objectcube.services.impl.postgresql.dimension.' 'DimensionService', 'ObjectService': 'objectcube.services.impl.postgresql.object_service.' 'ObjectService', 'BlobService': 'objectcube.services.impl.filesystem.' 'blob_service.FileBlobService', 'ConceptService': 'objectcube.services.impl.postgresql.concept.' 'ConceptService', 'PluginService': 'objectcube.services.impl.postgresql.plugin.' 'PluginService', 'TaggingService': 'objectcube.services.impl.postgresql.tagging.' 'TaggingService', } PLUGINS = ( 'objectcube.plugin.exif.ExifPlugin' ) " "Update addCallback and add removeCallback function handle array api.list by keys","(function() { 'use strict'; angular .module('app.services') .factory('resizeUpdater', function($window, $q){ var api = {}; var size = { width: undefined, height: undefined }; api.getSize = function(){ size.width = $window.innerWidth; size.height = $window.innerHeight; return size; }; api.list = []; api.addCallback = function(callback) { console.log(callback); api.list[ callback ] = callback; }; api.removeCallback = function(callback){ delete api.list[ callback ]; console.log('('+callback+')' + 'removed'); }; var runAll = function() { for(var item in api.list){ //console.log('('+item+') starting'); var obj = new Obj(api.list[item]); obj.execute(); } console.log(api.list); }; function Obj(callback) { this.promise = undefined; this.callback = callback; this.execute = function () { var defer = $q.defer(); this.callback(function (response) { if (response === 'error') { defer.reject('Error occured.'); } else { defer.resolve(response); } }); this.promise = defer.promise; this.promise.then(function(result){ console.log('Promise result: _ '+result); }); }; } angular.element($window).on('resize',(function(){ var timer; return function(){ clearTimeout(timer); timer = setTimeout(function(){ runAll(); }, 500); }; })()); return api; }); })(); ","(function() { 'use strict'; angular .module('app.services') .factory('resizeUpdater', function($window, $q){ var api = {}; var size = { width: undefined, height: undefined }; api.getSize = function(){ size.width = $window.innerWidth; size.height = $window.innerHeight; return size; }; api.list = []; api.addCallback = function(callback) { api.list[ api.list.length ] = callback; }; var runAll = function() { for (var i=0; i<api.list.length; i++){ console.log('('+i+') starting'); var obj = new Obj(api.list[i]); obj.execute(); } }; function Obj(callback) { this.promise = undefined; this.callback = callback; this.execute = function () { var defer = $q.defer(); this.callback(function (response) { if (response === 'error') { defer.reject('Error occured.'); } else { defer.resolve(response); } }); this.promise = defer.promise; this.promise.then(function(result){ console.log('Promise result: _ '+result); }); }; } angular.element($window).on('resize',(function(){ var timer; return function(){ clearTimeout(timer); timer = setTimeout(function(){ runAll(); }, 500); }; })()); return api; }); })(); " Add minified file size notification on Grunt build,"module.exports = function(grunt) { grunt.initConfig({ pkg : grunt.file.readJSON('package.json'), jshint: { files: ['Gruntfile.js', '<%= pkg.name %>.js'], options: { globals: { window: true } } }, uglify: { options: { report: 'gzip', // Report minified size banner: '/* <%= pkg.name %> v<%= pkg.version %> (<%= grunt.template.today(""yyyy-mm-dd"") %>) */\n\n' }, build: { src: '<%= pkg.name %>.js', dest: 'build/<%= pkg.name %>.min.js', options: { sourceMap: 'build/<%= pkg.name %>.min.map', sourceMappingURL: '<%= pkg.name %>.min.map', preserveComments: 'some' } } }, mocha: { test: { src: ['tests/index.html'] } }, watch: { js: { files: ['<%= pkg.name %>.js'], tasks: ['test'], options: { spawn: false } } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-mocha'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-notify'); grunt.registerTask('test', ['jshint', 'mocha']); grunt.registerTask('build', ['test', 'uglify']); grunt.registerTask('default', ['build']); }; ","module.exports = function(grunt) { grunt.initConfig({ pkg : grunt.file.readJSON('package.json'), jshint: { files: ['Gruntfile.js', '<%= pkg.name %>.js'], options: { globals: { window: true } } }, uglify: { options: { banner: '/* <%= pkg.name %> v<%= pkg.version %> (<%= grunt.template.today(""yyyy-mm-dd"") %>) */\n\n' }, build: { src: '<%= pkg.name %>.js', dest: 'build/<%= pkg.name %>.min.js', options: { sourceMap: 'build/<%= pkg.name %>.min.map', sourceMappingURL: '<%= pkg.name %>.min.map', preserveComments: 'some' } } }, mocha: { test: { src: ['tests/index.html'] } }, watch: { js: { files: ['<%= pkg.name %>.js'], tasks: ['test'], options: { spawn: false } } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-mocha'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-notify'); grunt.registerTask('test', ['jshint', 'mocha']); grunt.registerTask('build', ['test', 'uglify']); grunt.registerTask('default', ['build']); }; " Use HTML5 utf8 meta tag,"<!DOCTYPE html> <html lang=""en""> <head> <title>EndofCodes Demo</title> <?php include 'helpers/html.php'; includeStyle( ""general"" ); includeStyle( ""header"" ); includeStyle( ""home"" ); includeStyle( ""register"" ); includeStyle( ""login"" ); ?> <meta charset=""utf-8""> </head> <body> <div id=""header""> <ul> <li><a href=""index.php"">Endofcodes</a></li> <li><a href="""">Rules</a></li> <?php if ( isset( $_SESSION[ 'user' ]['username' ] ) ) { ?><li><a href=""index.php?resource=user&method=view&username=<?php echo htmlspecialchars( $_SESSION[ 'user' ][ 'username' ] ); ?>"">Profile</a></li><?php } ?> <li><a href=""http://blog.endofcodes.com"">Blog</a></li> <?php if ( isset( $_SESSION[ 'user' ][ 'username' ] ) ) { ?><li id=""login"" class=""username""><?php echo htmlspecialchars( $_SESSION[ 'user' ][ 'username' ] ); ?><select> <option> </option> <option value=""logout"">Logout</option> </select></li><?php } else { ?><li id=""login""><a href=""index.php?resource=session&method=create"">Login</a></li><?php } ?> </ul> </div> ","<!DOCTYPE html> <html lang=""en""> <head> <title>EndofCodes Demo</title> <?php include 'helpers/html.php'; includeStyle( ""general"" ); includeStyle( ""header"" ); includeStyle( ""home"" ); includeStyle( ""register"" ); includeStyle( ""login"" ); ?> <meta http-equiv=""Content-type"" content=""text/html; charset=utf-8"" /> </head> <body> <div id=""header""> <ul> <li><a href=""index.php"">Endofcodes</a></li> <li><a href="""">Rules</a></li> <?php if ( isset( $_SESSION[ 'user' ]['username' ] ) ) { ?><li><a href=""index.php?resource=user&method=view&username=<?php echo htmlspecialchars( $_SESSION[ 'user' ][ 'username' ] ); ?>"">Profile</a></li><?php } ?> <li><a href=""http://blog.endofcodes.com"">Blog</a></li> <?php if ( isset( $_SESSION[ 'user' ][ 'username' ] ) ) { ?><li id=""login"" class=""username""><?php echo htmlspecialchars( $_SESSION[ 'user' ][ 'username' ] ); ?><select> <option> </option> <option value=""logout"">Logout</option> </select></li><?php } else { ?><li id=""login""><a href=""index.php?resource=session&method=create"">Login</a></li><?php } ?> </ul> </div> " "Add missing methods to TPStats Change-Id: I332a83f3816ee30597288180ed344da3161861f8 Reviewed-on: http://review.couchbase.org/79675 Tested-by: Build Bot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com> Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com>","from cbagent.collectors.libstats.remotestats import RemoteStats, parallel_task class TPStats(RemoteStats): METRICS = ( (""rss"", 1), # already in bytes ) def __init__(self, hosts, workers, user, password): super().__init__(hosts, workers, user, password) self.typeperf_cmd = ""typeperf \""\\Process(*{}*)\\Working Set\"" -sc 1|sed '3q;d'"" @parallel_task(server_side=True) def get_server_samples(self, process): samples = {} if process == ""beam.smp"": stdout = self.run(self.typeperf_cmd.format(""erl"")) values = stdout.split(',')[1:5] elif process == ""memcached"": stdout = self.run(self.typeperf_cmd.format(process)) values = stdout.split(',')[1:2] else: return samples sum_rss = 0 if stdout: for v in values: v = float(v.replace('""', '')) sum_rss += v metric, multiplier = self.METRICS[0] title = ""{}_{}"".format(process, metric) samples[title] = float(sum_rss) * multiplier return samples def get_client_samples(self, process): pass ","from cbagent.collectors.libstats.remotestats import RemoteStats, parallel_task class TPStats(RemoteStats): METRICS = ( (""rss"", 1), # already in bytes ) def __init__(self, hosts, workers, user, password): super().__init__(hosts, workers, user, password) self.typeperf_cmd = ""typeperf \""\\Process(*{}*)\\Working Set\"" -sc 1|sed '3q;d'"" @parallel_task(server_side=True) def get_samples(self, process): samples = {} if process == ""beam.smp"": stdout = self.run(self.typeperf_cmd.format(""erl"")) values = stdout.split(',')[1:5] elif process == ""memcached"": stdout = self.run(self.typeperf_cmd.format(process)) values = stdout.split(',')[1:2] else: return samples sum_rss = 0 if stdout: for v in values: v = float(v.replace('""', '')) sum_rss += v metric, multiplier = self.METRICS[0] title = ""{}_{}"".format(process, metric) samples[title] = float(sum_rss) * multiplier return samples " Revert master version to 0.4.0a0,"import re import sys from collections import namedtuple from .connection import connect, Connection from .cursor import Cursor from .pool import create_pool, Pool __all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool', 'version', 'version_info') __version__ = '0.4.0a0' version = __version__ + ' , Python ' + sys.version VersionInfo = namedtuple('VersionInfo', 'major minor micro releaselevel serial') def _parse_version(ver): RE = (r'^(?P<major>\d+)\.(?P<minor>\d+)\.' '(?P<micro>\d+)((?P<releaselevel>[a-z]+)(?P<serial>\d+)?)?$') match = re.match(RE, ver) try: major = int(match.group('major')) minor = int(match.group('minor')) micro = int(match.group('micro')) levels = {'rc': 'candidate', 'a': 'alpha', 'b': 'beta', None: 'final'} releaselevel = levels[match.group('releaselevel')] serial = int(match.group('serial')) if match.group('serial') else 0 return VersionInfo(major, minor, micro, releaselevel, serial) except Exception: raise ImportError(""Invalid package version {}"".format(ver)) version_info = _parse_version(__version__) # make pyflakes happy (connect, create_pool, Connection, Cursor, Pool) ","import re import sys from collections import namedtuple from .connection import connect, Connection from .cursor import Cursor from .pool import create_pool, Pool __all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool', 'version', 'version_info') __version__ = '0.3.2' version = __version__ + ' , Python ' + sys.version VersionInfo = namedtuple('VersionInfo', 'major minor micro releaselevel serial') def _parse_version(ver): RE = (r'^(?P<major>\d+)\.(?P<minor>\d+)\.' '(?P<micro>\d+)((?P<releaselevel>[a-z]+)(?P<serial>\d+)?)?$') match = re.match(RE, ver) try: major = int(match.group('major')) minor = int(match.group('minor')) micro = int(match.group('micro')) levels = {'rc': 'candidate', 'a': 'alpha', 'b': 'beta', None: 'final'} releaselevel = levels[match.group('releaselevel')] serial = int(match.group('serial')) if match.group('serial') else 0 return VersionInfo(major, minor, micro, releaselevel, serial) except Exception: raise ImportError(""Invalid package version {}"".format(ver)) version_info = _parse_version(__version__) # make pyflakes happy (connect, create_pool, Connection, Cursor, Pool) " "BAP-2874: Disable to delete user if he is used as owner, BAP-2843: it is possible to delete default business unit assigned to users","<?php namespace Oro\Bundle\OrganizationBundle\Ownership; use Doctrine\ORM\EntityManager; use Doctrine\ORM\QueryBuilder; /** * Default implementation of check owner assignment algorithm */ class OwnerAssignmentChecker implements OwnerAssignmentCheckerInterface { /** * {@inheritdoc} */ public function hasAssignments($ownerId, $entityClassName, $ownerFieldName, EntityManager $em) { $findResult = $this->getHasAssignmentsQueryBuilder($ownerId, $entityClassName, $ownerFieldName, $em) ->getQuery() ->getArrayResult(); return !empty($findResult); } /** * Returns a query builder is used to check if assignments exist * * @param mixed $ownerId * @param string $entityClassName * @param string $ownerFieldName * @param EntityManager $em * @return QueryBuilder */ protected function getHasAssignmentsQueryBuilder($ownerId, $entityClassName, $ownerFieldName, EntityManager $em) { return $em->getRepository($entityClassName) ->createQueryBuilder('entity') ->select('owner.id') ->innerJoin(sprintf('entity.%s', $ownerFieldName), 'owner') ->where('owner.id = :ownerId') ->setParameter('ownerId', $ownerId) ->setMaxResults(1); } } ","<?php namespace Oro\Bundle\OrganizationBundle\Ownership; use Doctrine\ORM\EntityManager; use Doctrine\ORM\QueryBuilder; /** * Default implementation of check owner assignment algorithm */ class OwnerAssignmentChecker implements OwnerAssignmentCheckerInterface { /** * {@inheritdoc} */ public function hasAssignments($ownerId, $entityClassName, $ownerFieldName, EntityManager $em) { $findResult = $this->getHasAssignmentsQueryBuilder($ownerId, $entityClassName, $ownerFieldName, $em) ->getQuery() ->getArrayResult(); return !empty($findResult); } /** * Returns a query builder is used to check if assignments exist * * @param mixed $ownerId * @param string $entityClassName * @param string $ownerFieldName * @param EntityManager $em * @return QueryBuilder */ protected function getHasAssignmentsQueryBuilder($ownerId, $entityClassName, $ownerFieldName, EntityManager $em) { return $em->getRepository($entityClassName) ->createQueryBuilder('entity') ->select('owner.id') ->innerJoin(sprintf('entity.%s', $ownerFieldName), 'owner') ->where('owner.id = ?1') ->setParameter(1, $ownerId) ->setMaxResults(1); } } " "Set defaults on group table Fixes #6","<?php /* * Copyright © 2017 Jesse Nicholson * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; /** * This table manages groups, to which users and filtering data can be assigned. * Users that belong to a group are able to pull data assigned to that group, * and use it in-application client side. */ class CreateGroupsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('groups', function (Blueprint $table) { $table->bigIncrements('id'); // Name of the group. $table->string('name'); // The app config for users in this group. $table->mediumText('app_cfg'); // The sha1 sum of the group's current data payload. $table->char('data_sha1', 40)->default(''); // Whether or not the group is activated. $table->boolean('isactive')->default(true); // Created at/modified at. $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('groups'); } } ","<?php /* * Copyright © 2017 Jesse Nicholson * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; /** * This table manages groups, to which users and filtering data can be assigned. * Users that belong to a group are able to pull data assigned to that group, * and use it in-application client side. */ class CreateGroupsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('groups', function (Blueprint $table) { $table->bigIncrements('id'); // Name of the group. $table->string('name'); // The app config for users in this group. $table->mediumText('app_cfg'); // The sha1 sum of the group's current data payload. $table->char('data_sha1', 40); // Whether or not the group is activated. $table->boolean('isactive'); // Created at/modified at. $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('groups'); } } " Remove test row generator. Adds `onRefresh` & `setTasks` methods.,"/** * * @flow */ 'use strict'; import React from 'react'; import TaskListView from './TaskListView'; import type {Task} from '../../reducers/tasks'; import ENV from '../../common/Environment'; export default class TaskListContainer extends React.Component { state: { tasks: Array<Task> }; constructor() { super(); this.state = { tasks: [] }; } setTasks(tasks: Array<Task>) { return this.setState({tasks: tasks}); } async getAllTasks(): Promise { try { let response = await fetch(ENV.__API_BRIDGE+'/tasks'); let responseJSON = await response.json(); return responseJSON.data; } catch (err) { console.error(""getAllTasks() -> Error: "", err); } } async onRefresh(): Promise { console.log(""Refreshing TaskList...""); this.getAllTasks().then(tasks => this.setTasks(tasks)); } componentDidMount() { this.getAllTasks().then(tasks => this.setTasks(tasks)); } render() { return ( <TaskListView tasks={this.state.tasks} navigator={this.props.navigator} onRefresh={this.onRefresh.bind(this)} /> ); } } ","/** * * @flow */ 'use strict'; import React from 'react'; import TaskListView from './TaskListView'; import type {Task} from '../../reducers/tasks'; import ENV from '../../common/Environment'; export default class TaskListContainer extends React.Component { state: { tasks: Array<Task> }; constructor() { super(); this.state = { tasks: [] }; } async getAllTasks(): Promise { try { let response = await fetch(ENV.__API_BRIDGE+'/tasks'); let responseJSON = await response.json(); return responseJSON.data; } catch (err) { console.error(""getAllTasks() -> Error: "", err); } } componentWillMount() { let testRows = () => { let arr = []; let flip = false; for (let i = 0; i < 20; i++) { arr.push({ id: `${i}`, title: `Task ${i}`, desc: `desc for task ${i}`, reward: '200', complete: '3/5', status: flip ? 'To Do' : 'Completed', address: ""asdasdadasdas"" }); flip = !flip; } return arr; }; let tr: Array<Task> = testRows(); this.setState({tasks: tr}); } componentDidMount() { this.getAllTasks().then(tasks => { this.setState({tasks: tasks}); }); } render() { return ( <TaskListView navigator={this.props.navigator} tasks={this.state.tasks} /> ); } } " Add remaining building types to MOSColors,"(function () { 'use strict'; /** * ngInject */ function StateConfig($urlRouterProvider) { $urlRouterProvider.otherwise('/'); } // color ramp for sectors var sectorColors = { 'School (K-12)': '#A6CEE3', 'Office': '#1F78B4', 'Medical Office': '#52A634', 'Warehouse': '#B2DF8A', 'College/ University': '#33A02C', 'Other': '#FB9A99', 'Retail': '#E31A1C', 'Municipal': '#FDBF6F', 'Multifamily': '#FF7F00', 'Hotel': '#CAB2D6', 'Industrial': '#6A3D9A', 'Worship': '#9C90C4', 'Supermarket': '#E8AE6C', 'Parking': '#C9DBE6', 'Laboratory': '#3AA3FF', 'Hospital': '#C6B4FF', 'Data Center': '#B8FFA8', 'Unknown': '#DDDDDD' }; /** * @ngdoc overview * @name mos * @description * # mos * * Main module of the application. */ angular .module('mos', [ 'mos.views.charts', 'mos.views.map', 'mos.views.info', 'mos.views.detail', 'mos.views.compare', 'headroom' ]).config(StateConfig); angular.module('mos').constant('MOSColors', sectorColors); })(); ","(function () { 'use strict'; /** * ngInject */ function StateConfig($urlRouterProvider) { $urlRouterProvider.otherwise('/'); } // color ramp for sectors var sectorColors = { 'School (K-12)': '#A6CEE3', 'Office': '#1F78B4', 'Warehouse': '#B2DF8A', 'College/ University': '#33A02C', 'Other': '#FB9A99', 'Retail': '#E31A1C', 'Municipal': '#FDBF6F', 'Multifamily': '#FF7F00', 'Hotel': '#CAB2D6', 'Industrial': '#6A3D9A', 'Unknown': '#DDDDDD' }; /** * @ngdoc overview * @name mos * @description * # mos * * Main module of the application. */ angular .module('mos', [ 'mos.views.charts', 'mos.views.map', 'mos.views.info', 'mos.views.detail', 'mos.views.compare', 'headroom' ]).config(StateConfig); angular.module('mos').constant('MOSColors', sectorColors); })(); " fix(kakao): Change field name from 'nickname' to 'username',"from allauth.account.models import EmailAddress from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class KakaoAccount(ProviderAccount): @property def properties(self): return self.account.extra_data.get('properties') def get_avatar_url(self): return self.properties.get('profile_image') def to_str(self): dflt = super(KakaoAccount, self).to_str() return self.properties.get('nickname', dflt) class KakaoProvider(OAuth2Provider): id = 'kakao' name = 'Kakao' account_class = KakaoAccount def extract_uid(self, data): return str(data['id']) def extract_common_fields(self, data): email = data['kakao_account'].get('email') nickname = data['properties'].get('nickname') return dict(email=email, username=nickname) def extract_email_addresses(self, data): ret = [] data = data['kakao_account'] email = data.get('email') if email: verified = data.get('is_email_verified') # data['is_email_verified'] imply the email address is # verified ret.append(EmailAddress(email=email, verified=verified, primary=True)) return ret provider_classes = [KakaoProvider] ","from allauth.account.models import EmailAddress from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class KakaoAccount(ProviderAccount): @property def properties(self): return self.account.extra_data.get('properties') def get_avatar_url(self): return self.properties.get('profile_image') def to_str(self): dflt = super(KakaoAccount, self).to_str() return self.properties.get('nickname', dflt) class KakaoProvider(OAuth2Provider): id = 'kakao' name = 'Kakao' account_class = KakaoAccount def extract_uid(self, data): return str(data['id']) def extract_common_fields(self, data): email = data['kakao_account'].get('email') nickname = data['properties'].get('nickname') return dict(email=email, nickname=nickname) def extract_email_addresses(self, data): ret = [] data = data['kakao_account'] email = data.get('email') if email: verified = data.get('is_email_verified') # data['is_email_verified'] imply the email address is # verified ret.append(EmailAddress(email=email, verified=verified, primary=True)) return ret provider_classes = [KakaoProvider] " Add PHPDbg support to HTTP components,"<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\VarDumper; use Symfony\Component\VarDumper\Cloner\VarCloner; use Symfony\Component\VarDumper\Dumper\CliDumper; use Symfony\Component\VarDumper\Dumper\HtmlDumper; // Load the global dump() function require_once __DIR__.'/Resources/functions/dump.php'; /** * @author Nicolas Grekas <p@tchwork.com> */ class VarDumper { private static $handler; public static function dump($var) { if (null === self::$handler) { $cloner = new VarCloner(); $dumper = \in_array(PHP_SAPI, array('cli', 'phpdbg'), true) ? new CliDumper() : new HtmlDumper(); self::$handler = function ($var) use ($cloner, $dumper) { $dumper->dump($cloner->cloneVar($var)); }; } return call_user_func(self::$handler, $var); } public static function setHandler($callable) { if (null !== $callable && !is_callable($callable, true)) { throw new \InvalidArgumentException('Invalid PHP callback.'); } $prevHandler = self::$handler; self::$handler = $callable; return $prevHandler; } } ","<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\VarDumper; use Symfony\Component\VarDumper\Cloner\VarCloner; use Symfony\Component\VarDumper\Dumper\CliDumper; use Symfony\Component\VarDumper\Dumper\HtmlDumper; // Load the global dump() function require_once __DIR__.'/Resources/functions/dump.php'; /** * @author Nicolas Grekas <p@tchwork.com> */ class VarDumper { private static $handler; public static function dump($var) { if (null === self::$handler) { $cloner = new VarCloner(); $dumper = in_array(PHP_SAPI, array('cli', 'phpdbg')) ? new CliDumper() : new HtmlDumper(); self::$handler = function ($var) use ($cloner, $dumper) { $dumper->dump($cloner->cloneVar($var)); }; } return call_user_func(self::$handler, $var); } public static function setHandler($callable) { if (null !== $callable && !is_callable($callable, true)) { throw new \InvalidArgumentException('Invalid PHP callback.'); } $prevHandler = self::$handler; self::$handler = $callable; return $prevHandler; } } " Add content disposition to BinaryFileResponse,"<?php namespace Theapi\CctvBundle\Controller; use Symfony\Component\HttpFoundation\StreamedResponse; use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\HttpFoundation\ResponseHeaderBag; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class DefaultController extends Controller { public function indexAction() { return $this->videoAction(); } public function videoAction($date = null) { $imageManager = $this->get('theapi_cctv.image_manager'); try { $file = $imageManager->getVideoFile($date); $root = $this->get('service_container')->getParameter('theapi_cctv.web_root'); $file = str_replace($root, '', $file); return $this->render('TheapiCctvBundle:Default:index.html.twig', array('file' => $file)); } catch (\Exception $e) { throw $this->createNotFoundException($e->getMessage()); } } /** * Serve the file using BinaryFileResponse. * * @param string $date */ public function vidAction($date) { $imageManager = $this->get('theapi_cctv.image_manager'); try { $filename = $imageManager->getVideoFile($date); $response = new BinaryFileResponse($filename); $response->trustXSendfileTypeHeader(); $response->setContentDisposition( ResponseHeaderBag::DISPOSITION_INLINE, $filename, iconv('UTF-8', 'ASCII//TRANSLIT', $filename) ); } catch (\Exception $e) { throw $this->createNotFoundException($e->getMessage()); } return $response; } } ","<?php namespace Theapi\CctvBundle\Controller; use Symfony\Component\HttpFoundation\StreamedResponse; use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class DefaultController extends Controller { public function indexAction() { return $this->videoAction(); } public function videoAction($date = null) { $imageManager = $this->get('theapi_cctv.image_manager'); try { $file = $imageManager->getVideoFile($date); $root = $this->get('service_container')->getParameter('theapi_cctv.web_root'); $file = str_replace($root, '', $file); return $this->render('TheapiCctvBundle:Default:index.html.twig', array('file' => $file)); } catch (\Exception $e) { throw $this->createNotFoundException($e->getMessage()); } } /** * This doesn't work too well. Android chrome will hang on longer videos * @param string $date */ public function vidAction($date) { $imageManager = $this->get('theapi_cctv.image_manager'); try { $file = $imageManager->getVideoFile($date); return new BinaryFileResponse($file); } catch (\Exception $e) { throw $this->createNotFoundException($e->getMessage()); } } } " Update missing bash environment statement,"#!/usr/bin/env node var cheerio = require('cheerio'), args = require('commander'), path = require('path'), fs = require('fs'), inputStream = process.stdin, outputStream = process.stdout, $, obj = {}; args.version('0.0.1') .option('-f, --file <filename>','specify an input file', setupNewFileStream, 'read') .option('-o, --output <filename>','specify an output file', setupNewFileStream, 'write') .parse(process.argv); /** * Setup streams */ function setupNewFileStream (file, type) { if (file) { if (type === 'read') { inputStream = fs.createReadStream(path.resolve(file)); } if (type === 'write') { outputStream = fs.createWriteStream(path.resolve(file)); } } }; /** * Process data */ inputStream.setEncoding('utf8'); inputStream.on('readable', function () { var chunk = inputStream.read(); if (chunk !== null) { $ = cheerio.load(chunk); $('a').each(function (index, element) { obj[index] = { 'title': $(this).text(), 'url': $(this).attr('href'), 'created_at': $(this).attr('add_date'), 'icon_data': $(this).attr('icon') }; }); outputStream.write(JSON.stringify(obj, undefined, 2)); } }); "," var cheerio = require('cheerio'), args = require('commander'), path = require('path'), fs = require('fs'), inputStream = process.stdin, outputStream = process.stdout, $, obj = {}; args.version('0.0.1') .option('-f, --file <filename>','specify an input file', setupNewFileStream, 'read') .option('-o, --output <filename>','specify an output file', setupNewFileStream, 'write') .parse(process.argv); /** * Setup streams */ function setupNewFileStream (file, type) { if (file) { if (type === 'read') { inputStream = fs.createReadStream(path.resolve(file)); } if (type === 'write') { outputStream = fs.createWriteStream(path.resolve(file)); } } }; /** * Process data */ inputStream.setEncoding('utf8'); inputStream.on('readable', function () { var chunk = inputStream.read(); if (chunk !== null) { $ = cheerio.load(chunk); $('a').each(function (index, element) { obj[index] = { 'title': $(this).text(), 'url': $(this).attr('href'), 'created_at': $(this).attr('add_date'), 'icon_data': $(this).attr('icon') }; }); outputStream.write(JSON.stringify(obj, undefined, 2)); } }); " Disable button should be the first thing to do,"function dform(formElement) { var eventEmitter = { on: function (name, handler) { this[name] = this[name] || []; this[name].push(handler); return this; }, trigger: function (name, event) { if (this[name]) { this[name].map(function (handler) { handler(event); }); } return this; } }; var submitElement = formElement.find('[type=submit]'); var inputElements = formElement.find('input, select'); formElement.submit(function (event) { event.preventDefault(); submitElement.attr('disabled', 'disabled'); var formData = {}; $.each(inputElements, function (_, element) { element = $(element); var name = element.attr('name'); if (name) { formData[name] = element.val(); } }); eventEmitter.trigger('submit'); $[formElement.attr('method')](formElement.attr('action'), formData) .always(function () { submitElement.removeAttr('disabled', 'disabled'); }) .done(function (responseData) { eventEmitter.trigger('done', responseData); }) .fail(function (jqXHR) { eventEmitter.trigger('fail', jqXHR); }); }); submitElement.removeAttr('disabled', 'disabled'); return eventEmitter; } ","function dform(formElement) { var eventEmitter = { on: function (name, handler) { this[name] = this[name] || []; this[name].push(handler); return this; }, trigger: function (name, event) { if (this[name]) { this[name].map(function (handler) { handler(event); }); } return this; } }; var submitElement = formElement.find('[type=submit]'); var inputElements = formElement.find('input, select'); formElement.submit(function (event) { event.preventDefault(); var formData = {}; $.each(inputElements, function (_, element) { element = $(element); var name = element.attr('name'); if (name) { formData[name] = element.val(); } }); submitElement.attr('disabled', 'disabled'); eventEmitter.trigger('submit'); $[formElement.attr('method')](formElement.attr('action'), formData) .always(function () { submitElement.removeAttr('disabled', 'disabled'); }) .done(function (data) { eventEmitter.trigger('done', data); }) .fail(function (jqXHR) { eventEmitter.trigger('fail', jqXHR); }); }); submitElement.removeAttr('disabled', 'disabled'); return eventEmitter; } " Change manage.py to require Pillow 2.0.0 This is to avoid PIL import errors for Mac users,"#/usr/bin/env python import os from setuptools import setup, find_packages ROOT_DIR = os.path.dirname(__file__) SOURCE_DIR = os.path.join(ROOT_DIR) version = '2.6.dev0' setup( name=""django-photologue"", version=version, description=""Powerful image management for the Django web framework."", author=""Justin Driscoll, Marcos Daniel Petry, Richard Barran"", author_email=""justin@driscolldev.com, marcospetry@gmail.com"", url=""https://github.com/jdriscoll/django-photologue"", packages=find_packages(), package_data={ 'photologue': [ 'res/*.jpg', 'locale/*/LC_MESSAGES/*', 'templates/photologue/*.html', 'templates/photologue/tags/*.html', ] }, zip_safe=False, classifiers=['Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities'], install_requires=['Django>=1.3', # Change to class-based views means 1.3 minimum. 'South>=0.7.5', # Might work with earlier versions, but not tested. 'Pillow>=2.0.0', # Might work with earlier versions, but not tested. ], ) ","#/usr/bin/env python import os from setuptools import setup, find_packages ROOT_DIR = os.path.dirname(__file__) SOURCE_DIR = os.path.join(ROOT_DIR) version = '2.6.dev0' setup( name=""django-photologue"", version=version, description=""Powerful image management for the Django web framework."", author=""Justin Driscoll, Marcos Daniel Petry, Richard Barran"", author_email=""justin@driscolldev.com, marcospetry@gmail.com"", url=""https://github.com/jdriscoll/django-photologue"", packages=find_packages(), package_data={ 'photologue': [ 'res/*.jpg', 'locale/*/LC_MESSAGES/*', 'templates/photologue/*.html', 'templates/photologue/tags/*.html', ] }, zip_safe=False, classifiers=['Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities'], install_requires=['Django>=1.3', # Change to class-based views means 1.3 minimum. 'South>=0.7.5', # Might work with earlier versions, but not tested. 'Pillow>=2.0', # Might work with earlier versions, but not tested. ], ) " Set the etag only if it was generated,"<?php namespace EXSyst\Bundle\RestBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; /** * @author Ener-Getick <egetick@gmail.com> */ abstract class RestController extends Controller { /** * @param mixed $value to be serialized * @param mixed $context Serialization context * @param string $format * * @return string */ protected function serializeView($value, $context, $format = null) { if ($format === null) { $format = $this->getParameter('exsyst_rest.serializer.default_format'); } $serializer = $this->get('exsyst_rest.serializer'); return $serializer->serialize($value, $format, $context); } /** * @param mixed $value to be serialized * @param mixed $context Serialization context * @param string $format * * @return Response */ protected function serialize($value, $context, $format = null, Response $response = null) { if ($response === null) { $response = new Response(); } $serializedValue = $this->serializeView($value, $context, $format); $response->setContent($serializedValue); $etagGenerator = $this->get('exsyst_rest.etag_generator'); $etag = $etagGenerator->generate($response->getContent()); if($etag !== false) { $response->setEtag($etag); $response->isNotModified( $this->get('request_stack')->getCurrentRequest() ); } return $response; } } ","<?php namespace EXSyst\Bundle\RestBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; /** * @author Ener-Getick <egetick@gmail.com> */ abstract class RestController extends Controller { /** * @param mixed $value to be serialized * @param mixed $context Serialization context * @param string $format * * @return string */ protected function serializeView($value, $context, $format = null) { if ($format === null) { $format = $this->getParameter('exsyst_rest.serializer.default_format'); } $serializer = $this->get('exsyst_rest.serializer'); return $serializer->serialize($value, $format, $context); } /** * @param mixed $value to be serialized * @param mixed $context Serialization context * @param string $format * * @return Response */ protected function serialize($value, $context, $format = null, Response $response = null) { if ($response === null) { $response = new Response(); } $serializedValue = $this->serializeView($value, $context, $format); $response->setContent($serializedValue); $etagGenerator = $this->get('exsyst_rest.etag_generator'); $response->setEtag( $etagGenerator->generate($response->getContent()) ); $response->isNotModified( $this->get('request_stack')->getCurrentRequest() ); return $response; } } " Test case for preserving the leading and trailing whitespace now passes.,"(function(host) { var exported = { preprocess: function(input, defines) { var lines = input.split(/\r?\n/); var ignoreLines = false; var output = """"; var outputLineSeparator = ""\n""; defines = defines.map(function(str) { return str.toUpperCase(); }); for (var i = 0; i < lines.length; i++) { var line = lines[i]; var isStartDirective = /#ifdef +(\S*)?/.exec(line); var isEndDirective = /#endif/.exec(line); var isDirective = isStartDirective || isEndDirective; if (isStartDirective) { var mode = isStartDirective[1]; if (defines.indexOf(mode.toUpperCase()) < 0) { ignoreLines = true; } } if (!ignoreLines && !isDirective) { output = output + line + outputLineSeparator; } if (isEndDirective) { ignoreLines = false; } }; return output.substring(0, output.length - outputLineSeparator.length); } }; if (module) { module.exports = exported; } else { host.prepr = exported; } })(this);","(function(host) { var exported = { preprocess: function(input, defines) { var lines = input.split(/\r?\n/); var ignoreLines = false; var output = """"; defines = defines.map(function(str) { return str.toUpperCase(); }); for (var i = 0; i < lines.length; i++) { var line = lines[i]; var isStartDirective = /#ifdef +(\S*)?/.exec(line); var isEndDirective = /#endif/.exec(line); var isDirective = isStartDirective || isEndDirective; if (isStartDirective) { var mode = isStartDirective[1]; if (defines.indexOf(mode.toUpperCase()) < 0) { ignoreLines = true; } } if (!ignoreLines && !isDirective) { output = output + line + ""\n""; } if (isEndDirective) { ignoreLines = false; } }; return output.trim(); } }; if (module) { module.exports = exported; } else { host.prepr = exported; } })(this);" Fix bug when parse version info,"#!/usr/bin/env python import os from .data_format import dumps class RemoteRepo(object): def __init__(self, repo_dir): self.repo_dir = repo_dir # initial setup pool_relative_dir = ""pool"" package_relative_path = ""index/package"" self.pool_absolute_dir = os.path.join(self.repo_dir, pool_relative_dir) self.package_abspath = os.path.join(self.repo_dir, package_relative_path) def make_package_index(self): package_data = self.scan_pool() package_stream = dumps(package_data) fd = open(self.package_abspath, 'w') fd.write(package_stream) fd.close() def scan_pool(self): files = [f for f in os.listdir(self.pool_absolute_dir) if os.path.isfile(os.path.join(self.pool_absolute_dir, f))] package_data = {} for file_name in files: pkg_name_segments = file_name.split(""_"") package_name = '_'.join(pkg_name_segments[:-1]) version_and_ext = pkg_name_segments[-1] version = os.path.splitext(version_and_ext)[0] path = os.path.join('pool/', file_name) package_info = {'version': version, 'path': path} package_data[package_name] = package_info return package_data ","#!/usr/bin/env python import os from .data_format import dumps class RemoteRepo(object): def __init__(self, repo_dir): self.repo_dir = repo_dir # initial setup pool_relative_dir = ""pool"" package_relative_path = ""index/package"" self.pool_absolute_dir = os.path.join(self.repo_dir, pool_relative_dir) self.package_abspath = os.path.join(self.repo_dir, package_relative_path) def make_package_index(self): package_data = self.scan_pool() package_stream = dumps(package_data) fd = open(self.package_abspath, 'w') fd.write(package_stream) fd.close() def scan_pool(self): files = [f for f in os.listdir(self.pool_absolute_dir) if os.path.isfile(os.path.join(self.pool_absolute_dir, f))] package_data = {} for file_name in files: package_name, version_and_ext = file_name.split('_', 1) version = os.path.splitext(version_and_ext)[0] path = os.path.join('pool/', file_name) package_info = {'version': version, 'path': path} package_data[package_name] = package_info return package_data " Remove minimum requirements for now until we can increase coverage,"'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { allFiles: ['*.js', 'lib/**/*.js', 'examples/**/*.js', 'test/**/*.js'], options: { jshintrc: '.jshintrc', } }, mochacli: { all: ['test/**/*.js'], options: { reporter: 'spec', ui: 'tdd' } }, 'mocha_istanbul': { coveralls: { src: 'test', options: { coverage: true, legend: true, /* check: { lines: 90, statements: 90 }, */ root: './lib', reportFormats: ['lcov'] } } } }) grunt.event.on('coverage', function(lcov, done){ require('coveralls').handleInput(lcov, function(error) { if (error) { console.log(error) return done(error) } done() }) }) // Load the plugins grunt.loadNpmTasks('grunt-contrib-jshint') grunt.loadNpmTasks('grunt-mocha-cli') grunt.loadNpmTasks('grunt-mocha-istanbul') // Configure tasks grunt.registerTask('coveralls', ['mocha_istanbul:coveralls']) grunt.registerTask('default', ['test']) grunt.registerTask('test', ['mochacli', 'jshint', 'coveralls']) } ","'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { allFiles: ['*.js', 'lib/**/*.js', 'examples/**/*.js', 'test/**/*.js'], options: { jshintrc: '.jshintrc', } }, mochacli: { all: ['test/**/*.js'], options: { reporter: 'spec', ui: 'tdd' } }, 'mocha_istanbul': { coveralls: { src: 'test', options: { coverage: true, legend: true, check: { lines: 68, statements: 66 }, root: './lib', reportFormats: ['lcov'] } } } }) grunt.event.on('coverage', function(lcov, done){ require('coveralls').handleInput(lcov, function(error) { if (error) { console.log(error) return done(error) } done() }) }) // Load the plugins grunt.loadNpmTasks('grunt-contrib-jshint') grunt.loadNpmTasks('grunt-mocha-cli') grunt.loadNpmTasks('grunt-mocha-istanbul') // Configure tasks grunt.registerTask('coveralls', ['mocha_istanbul:coveralls']) grunt.registerTask('default', ['test']) grunt.registerTask('test', ['mochacli', 'jshint', 'coveralls']) } " [API] Send 404 HTTP code if routing is not exist,"<?php namespace Api\Controller; use Phalcon\Mvc\Controller; use Phalcony\Application; class IndexController extends Controller { public function testAction() { return array( 'success' => true, 'version' => 1.0 ); } /** * @return array */ public function errorAction() { $this->response->setStatusCode(404, 'Not found'); $this->logger->debug('Error to handle: ' . $this->request->getURI()); return array( 'success' => false, 'url' => $this->request->getURI(), 'parameters' => $this->dispatcher->getParams() ); } /** * @return array */ public function exceptionAction() { /** * @var $exception \Exception */ $exception = $this->dispatcher->getParam('exception'); $message = $exception->getMessage(); if (empty($message)) { $message = 'Houston we have got a problem'; } if ($this->application->getEnv() == Application::ENV_PRODUCTION) { switch ($exception->getCode()) { case 500: $this->logger->critical((string) $exception); break; default: $this->logger->debug((string) $exception); break; } } else { $this->logger->debug((string) $exception); } return array( 'success' => false, 'message' => $message, ); } } ","<?php namespace Api\Controller; use Phalcon\Mvc\Controller; use Phalcony\Application; class IndexController extends Controller { public function testAction() { return array( 'success' => true, 'version' => 1.0 ); } /** * @return array */ public function errorAction() { $this->logger->debug('Error to handle: ' . $this->request->getURI()); return array( 'success' => false, 'url' => $this->request->getURI(), 'parameters' => $this->dispatcher->getParams() ); } /** * @return array */ public function exceptionAction() { /** * @var $exception \Exception */ $exception = $this->dispatcher->getParam('exception'); $message = $exception->getMessage(); if (empty($message)) { $message = 'Houston we have got a problem'; } if ($this->application->getEnv() == Application::ENV_PRODUCTION) { switch ($exception->getCode()) { case 500: $this->logger->critical((string) $exception); break; default: $this->logger->debug((string) $exception); break; } } else { $this->logger->debug((string) $exception); } return array( 'success' => false, 'message' => $message, ); } } " Add back the pathlib dependency on 2.7,"#!/usr/bin/env python2 from __future__ import print_function from setuptools import setup from sys import version_info if version_info < (3, 5): requirements = [""pathlib""] else: requirements = [] setup(name=""mpd_pydb"", author=""Wieland Hoffmann"", author_email=""themineo@gmail.com"", packages=[""mpd_pydb""], package_dir={""mpd_pydb"": ""mpd_pydb""}, download_url=""https://github.com/mineo/mpd_pydb/tarball/master"", url=""http://github.com/mineo/mpd_pydb"", license=""MIT"", classifiers=[""Development Status :: 4 - Beta"", ""License :: OSI Approved :: MIT License"", ""Natural Language :: English"", ""Operating System :: OS Independent"", ""Programming Language :: Python :: 2.7"", ""Programming Language :: Python :: 3.5"", ""Programming Language :: Python :: 3.6"",], description=""Module for reading an MPD database"", long_description=open(""README.rst"").read(), setup_requires=[""setuptools_scm"", ""pytest-runner""], use_scm_version={""write_to"": ""mpd_pydb/version.py""}, install_requires=requirements, extras_require={ 'docs': ['sphinx'] }, tests_require=[""pytest""], ) ","#!/usr/bin/env python2 from __future__ import print_function from setuptools import setup from sys import version_info setup(name=""mpd_pydb"", author=""Wieland Hoffmann"", author_email=""themineo@gmail.com"", packages=[""mpd_pydb""], package_dir={""mpd_pydb"": ""mpd_pydb""}, download_url=""https://github.com/mineo/mpd_pydb/tarball/master"", url=""http://github.com/mineo/mpd_pydb"", license=""MIT"", classifiers=[""Development Status :: 4 - Beta"", ""License :: OSI Approved :: MIT License"", ""Natural Language :: English"", ""Operating System :: OS Independent"", ""Programming Language :: Python :: 2.7"", ""Programming Language :: Python :: 3.5"", ""Programming Language :: Python :: 3.6"",], description=""Module for reading an MPD database"", long_description=open(""README.rst"").read(), setup_requires=[""setuptools_scm"", ""pytest-runner""], use_scm_version={""write_to"": ""mpd_pydb/version.py""}, extras_require={ 'docs': ['sphinx'] }, tests_require=[""pytest""], ) " Replace dependency on SQLAlchemy with Flask-SQLALchemy,"# Copyright 2013-2015 Massachusetts Open Cloud Contributors # # 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. from setuptools import setup, find_packages setup(name='haas', version='0.2rc2', url='https://github.com/CCI-MOC/haas', packages=find_packages(), scripts=['scripts/haas', 'scripts/create_bridges'], install_requires=['Flask-SQLAlchemy', 'Werkzeug>=0.9.4,<0.10', 'Flask>=0.10.1,<0.11', 'schema==0.3.1', 'importlib==1.0.3', 'passlib==1.6.2', 'pexpect==3.3', 'requests==2.4.1', 'pytest>=2.6.2,<3.0', 'pytest-cov==1.8.0', 'pytest-xdist', ]) ","# Copyright 2013-2015 Massachusetts Open Cloud Contributors # # 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. from setuptools import setup, find_packages setup(name='haas', version='0.2rc2', url='https://github.com/CCI-MOC/haas', packages=find_packages(), scripts=['scripts/haas', 'scripts/create_bridges'], install_requires=['SQLAlchemy==0.9.7', 'Werkzeug>=0.9.4,<0.10', 'Flask>=0.10.1,<0.11', 'schema==0.3.1', 'importlib==1.0.3', 'passlib==1.6.2', 'pexpect==3.3', 'requests==2.4.1', 'pytest>=2.6.2,<3.0', 'pytest-cov==1.8.0', 'pytest-xdist', ]) " Check that mongodb connection is alive or create a new connection,"package org.unitedid.jaas; import com.mongodb.DB; import com.mongodb.Mongo; import com.mongodb.MongoException; import com.mongodb.ServerAddress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.List; import java.util.Map; public class MongoDBFactory { /** Logger */ private static final Logger log = LoggerFactory.getLogger(MongoDBFactory.class); private static Map<List<ServerAddress>, DB> mongoDbFactoryMap = new HashMap<List<ServerAddress>, DB>(); private MongoDBFactory() {} public static DB get(List<ServerAddress> hosts, String database, String username, String password) { synchronized (mongoDbFactoryMap) { DB db = mongoDbFactoryMap.get(hosts); // Re-initiate a new connection if its not authenticated for some reason if (db != null && !db.isAuthenticated()) { log.debug(""Re-initiating mongo db connection!""); db.getMongo().close(); mongoDbFactoryMap.remove(hosts); db = null; } if (db == null) { log.debug(""Initiating a new mongo connection!""); Mongo connection = new Mongo(hosts); db = connection.getDB(database); if(!db.authenticate(username, password.toCharArray())) throw new MongoException(""Authentication failed, bad username or password!""); db.slaveOk(); mongoDbFactoryMap.put(hosts, db); } return db; } } } ","package org.unitedid.jaas; import com.mongodb.DB; import com.mongodb.Mongo; import com.mongodb.MongoException; import com.mongodb.ServerAddress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.List; import java.util.Map; public class MongoDBFactory { /** Logger */ private static final Logger log = LoggerFactory.getLogger(MongoDBFactory.class); private static Map<List<ServerAddress>, DB> mongoDbFactoryMap = new HashMap<List<ServerAddress>, DB>(); private MongoDBFactory() {} public static DB get(List<ServerAddress> hosts, String database, String username, String password) { synchronized (mongoDbFactoryMap) { DB db = mongoDbFactoryMap.get(hosts); if (db == null) { log.debug(""Initiating a new mongo connection!""); Mongo connection = new Mongo(hosts); db = connection.getDB(database); if(!db.authenticate(username, password.toCharArray())) throw new MongoException(""Authentication failed, bad username or password!""); db.slaveOk(); mongoDbFactoryMap.put(hosts, db); } return db; } } } " "Revert ""Resolve trailing white spaces"" This reverts commit 71880cb672c87ddd0b5c76120a1308ba24253d99.","package savvytodo.model.task; import savvytodo.commons.exceptions.IllegalValueException; /** * Represents a Task's priority in the task manager * Guarantees: immutable; is valid as declared in {@link #isValidPriority(String)} */ public class Priority { public static final String MESSAGE_PRIORITY_CONSTRAINTS = ""Task priority should be 'low', 'medium' or 'high'""; public static final String PRIORITY_VALIDATION_REGEX = ""(^low$)|(^medium$)|(^high$)""; public final String value; /** * Validates given priority. * * @throws IllegalValueException if given priority string is invalid. */ public Priority(String priority) throws IllegalValueException { assert priority != null; String trimmedPriority = priority.trim(); if (!isValidPriority(trimmedPriority)) { throw new IllegalValueException(MESSAGE_PRIORITY_CONSTRAINTS); } this.value = trimmedPriority; } /** * Returns true if a given string is a valid task priority. */ public static boolean isValidPriority(String test) { return test.matches(PRIORITY_VALIDATION_REGEX); } @Override public String toString() { return value; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof Priority // instanceof handles nulls && this.value.equals(((Priority) other).value)); // state check } @Override public int hashCode() { return value.hashCode(); } } ","package savvytodo.model.task; import savvytodo.commons.exceptions.IllegalValueException; /** * Represents a Task's priority in the task manager * Guarantees: immutable; is valid as declared in {@link #isValidPriority(String)} */ public class Priority { public static final String MESSAGE_PRIORITY_CONSTRAINTS = ""Task priority should be 'low', 'medium' or 'high'""; public static final String PRIORITY_VALIDATION_REGEX = ""(^low$)|(^medium$)|(^high$)""; public final String value; /** * Validates given priority. * * @throws IllegalValueException if given priority string is invalid. */ public Priority(String priority) throws IllegalValueException { assert priority != null; String trimmedPriority = priority.trim(); if (!isValidPriority(trimmedPriority)) { throw new IllegalValueException(MESSAGE_PRIORITY_CONSTRAINTS); } this.value = trimmedPriority; } /** * Returns true if a given string is a valid task priority. */ public static boolean isValidPriority(String test) { return test.matches(PRIORITY_VALIDATION_REGEX); } @Override public String toString() { return value; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof Priority // instanceof handles nulls && this.value.equals(((Priority) other).value)); // state check } @Override public int hashCode() { return value.hashCode(); } } " Add the shift function to be used in the console,"<?php namespace RH; use RH\Model\PlayItem; class Playlist { private $items; private $baseUrl; public function __construct(array $items, $baseUrl = '') { $this->items = $items; $this->baseUrl = $baseUrl; } public function toArray() { return array_map(array($this, 'makeItem'), $this->items); } private function makeItem(PlayItem $playItem) { $song = $playItem->getSong(); $attributes = array( 'id' => $playItem->getId(), 'order' => $playItem->getOrder(), 'song_id' => $song->getId(), 'song_name' => $song->getName(), 'song_media_url' => $this->baseUrl.$song->getWebPath() ); if ($artist = $song->getArtist()) { $attributes['song_artist_id'] = $artist->getId(); $attributes['song_artist'] = $artist->getName(); } if ($album = $song->getAlbum()) { $attributes['song_album_id'] = $album->getId(); $attributes['song_album'] = $album->getName(); } return $attributes; } public static function shift() { //This function will change when we will implements the historiq //We will have to shift all playItem in the negative and keep playItem between -1 and -10. //Less than -10 have to be delete. $playItem = new PlayItem(); $playItem = Model\PlayItemQuery::create() ->filterByOrder(0, \Criteria::GREATER_THAN) ->orderBy('order') ->findOne(); if($playItem != null) { $playItem->setOrder(-1); $playItem->save(); $song = $playItem->getSong(); } } } ","<?php namespace RH; use RH\Model\PlayItem; class Playlist { private $items; private $baseUrl; public function __construct(array $items, $baseUrl = '') { $this->items = $items; $this->baseUrl = $baseUrl; } public function toArray() { return array_map(array($this, 'makeItem'), $this->items); } private function makeItem(PlayItem $playItem) { $song = $playItem->getSong(); $attributes = array( 'id' => $playItem->getId(), 'order' => $playItem->getOrder(), 'song_id' => $song->getId(), 'song_name' => $song->getName(), 'song_media_url' => $this->baseUrl.$song->getWebPath() ); if ($artist = $song->getArtist()) { $attributes['song_artist_id'] = $artist->getId(); $attributes['song_artist'] = $artist->getName(); } if ($album = $song->getAlbum()) { $attributes['song_album_id'] = $album->getId(); $attributes['song_album'] = $album->getName(); } return $attributes; } } " JsMinify: Use DDG require to load the library on Beta,"DDH.js_minify = DDH.js_minify || {}; ""use strict""; DDH.js_minify.build = function(ops) { var shown = false; return { onShow: function() { // make sure this function is run only once, the first time // the IA is shown otherwise things will get initialized more than once if (shown) return; // set the flag to true so it doesn't get run again shown = true; var $dom = $('#zci-js_minify'), $main = $dom.find('.zci__main'), $minifyButton = $dom.find('.js_minify__action'), $input = $dom.find('#js_minify__input'), $output = $dom.find('#js_minify__output'); $main.toggleClass('c-base'); // hide output textarea by default $output.css('display', 'none'); DDG.require(‘prettydiff’, function() { // Add click handler for the minify button $minifyButton.click(function() { // Set config options for minify operation var args = { mode: ""minify"", lang: ""javascript"", source: $input.val() }; // Operate using the prettydiff function provided by the library var output = prettydiff(args); // hide output textarea by default $output.css('display', 'inline'); // Add the output to output textarea field $output.val(output); }); }) } }; }; ","DDH.js_minify = DDH.js_minify || {}; ""use strict""; DDH.js_minify.build = function(ops) { var shown = false; return { onShow: function() { // make sure this function is run only once, the first time // the IA is shown otherwise things will get initialized more than once if (shown) return; // set the flag to true so it doesn't get run again shown = true; var $dom = $('#zci-js_minify'), $main = $dom.find('.zci__main'), $minifyButton = $dom.find('.js_minify__action'), $input = $dom.find('#js_minify__input'), $output = $dom.find('#js_minify__output'); $main.toggleClass('c-base'); // hide output textarea by default $output.css('display', 'none'); $.getScript('http://sahildua.com/js/prettydiff.min.js', function() { // Add click handler for the minify button $minifyButton.click(function() { // Set config options for minify operation var args = { mode: ""minify"", lang: ""javascript"", source: $input.val() }; // Operate using the prettydiff function provided by the library var output = prettydiff(args); // hide output textarea by default $output.css('display', 'inline'); // Add the output to output textarea field $output.val(output); }); }) } }; }; " Add Lumen check and tags to assets,"<?php namespace Torann\GeoIP; use Illuminate\Support\ServiceProvider; use Torann\GeoIP\Console\UpdateCommand; class GeoIPServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { if ($this->isLumen() === false) { $this->publishes([ __DIR__ . '/config/geoip.php' => config_path('geoip.php'), ], 'config'); } } /** * Register the service provider. * * @return void */ public function register() { $this->app['geoip'] = $this->app->share(function ($app) { return new GeoIP( $app->config->get('geoip', []), $app['session.store'] ); }); $this->app['command.geoip.update'] = $this->app->share(function ($app) { return new UpdateCommand($app['geoip']); }); $this->commands(['command.geoip.update']); } /** * Check if package is running under Lumen app * * @return bool */ protected function isLumen() { return str_contains($this->app->version(), 'Lumen') === true; } }","<?php namespace Torann\GeoIP; use Illuminate\Support\ServiceProvider; use Torann\GeoIP\Console\UpdateCommand; class GeoIPServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->publishes([ __DIR__ . '/config/geoip.php' => config_path('geoip.php'), ]); } /** * Register the service provider. * * @return void */ public function register() { $this->app['geoip'] = $this->app->share(function ($app) { return new GeoIP( $app->config->get('geoip', []), $app['session.store'] ); }); $this->app['command.geoip.update'] = $this->app->share(function ($app) { return new UpdateCommand($app['geoip']); }); $this->commands(['command.geoip.update']); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return [ 'geoip', 'command.geoip.update', ]; } }" Allow advanced graph on medium sized displays,"import React from 'react' import GraphContainer from './components/GraphContainer' import { connect } from 'react-redux' import { PropTypes } from 'prop-types' import { fetchInitialTimeseries, fetchSchedule, fetchRecentTimeseries } from './actions' import moment from 'moment' import Grid from 'react-bootstrap/lib/Grid' import Col from 'react-bootstrap/lib/Col' class App extends React.PureComponent { static propTypes = { fetchInitialTimeseries: PropTypes.func.isRequired, fetchSchedule: PropTypes.func.isRequired, fetchRecentTimeseries: PropTypes.func.isRequired } componentWillMount () { this.props.fetchInitialTimeseries() this.props.fetchSchedule() setInterval(() => this.props.fetchRecentTimeseries(moment().subtract(1, 'hours').toDate()), 60 * 1000) } render () { return ( <Grid> <h3><a style={{border: '1.5px solid #ccc', padding: 5, backgroundColor: '#ddd'}} href='/'>Return Home</a></h3> <Col xsHidden smHidden> <GraphContainer fullscreen /> </Col> <Col lgHidden mdHidden className='section'> <h2>Oops!</h2> <div className='content'> <h3>Currently, advanced graphs are only supported on desktop. <a href='/'>Return Home</a></h3> </div> </Col> </Grid> ) } } export default connect(null, { fetchInitialTimeseries, fetchSchedule, fetchRecentTimeseries })(App) ","import React from 'react' import GraphContainer from './components/GraphContainer' import { connect } from 'react-redux' import { PropTypes } from 'prop-types' import { fetchInitialTimeseries, fetchSchedule, fetchRecentTimeseries } from './actions' import moment from 'moment' import Grid from 'react-bootstrap/lib/Grid' import Col from 'react-bootstrap/lib/Col' class App extends React.PureComponent { static propTypes = { fetchInitialTimeseries: PropTypes.func.isRequired, fetchSchedule: PropTypes.func.isRequired, fetchRecentTimeseries: PropTypes.func.isRequired } componentWillMount () { this.props.fetchInitialTimeseries() this.props.fetchSchedule() setInterval(() => this.props.fetchRecentTimeseries(moment().subtract(1, 'hours').toDate()), 60 * 1000) } render () { return ( <Grid> <h3><a style={{border: '1.5px solid #ccc', padding: 5, backgroundColor: '#ddd'}} href='/'>Return Home</a></h3> <Col xsHidden smHidden> <GraphContainer fullscreen /> </Col> <Col lgHidden className='section'> <h2>Oops!</h2> <div className='content'> <h3>Currently, advanced graphs are only supported on desktop. <a href='/'>Return Home</a></h3> </div> </Col> </Grid> ) } } export default connect(null, { fetchInitialTimeseries, fetchSchedule, fetchRecentTimeseries })(App) " Fix JavaScript file indentation inconsistency.,"$(function () { var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); $('#calendar-holder').fullCalendar({ header: { left: 'prev, next', center: 'title', right: 'month, basicWeek, basicDay,' }, lazyFetching: true, timeFormat: { // for agendaWeek and agendaDay agenda: 'h:mmt', // 5:00 - 6:30 // for all other views '': 'h:mmt' // 7p }, eventSources: [ { url: Routing.generate('fullcalendar_loader'), type: 'POST', // A way to add custom filters to your event listeners data: { }, error: function() { //alert('There was an error while fetching Google Calendar!'); } } ] }); }); ","$(function () { var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); $('#calendar-holder').fullCalendar({ header: { left: 'prev, next', center: 'title', right: 'month,basicWeek,basicDay,' }, lazyFetching:true, timeFormat: { // for agendaWeek and agendaDay agenda: 'h:mmt', // 5:00 - 6:30 // for all other views '': 'h:mmt' // 7p }, eventSources: [ { url: Routing.generate('fullcalendar_loader'), type: 'POST', // A way to add custom filters to your event listeners data: { }, error: function() { //alert('There was an error while fetching Google Calendar!'); } } ] }); }); " "Fix JS behaviour to show categories when noosfero is in a subdir environment Signed-off-by: Fabio Teixeira <a90b0aa793b4509973a022e6fee8cf8a263dd84e@gmail.com> Signed-off-by: Gabriela Navarro <61c2bac069eee966d94f5b4095f9a2d9fa323d86@gmail.com>","(function($){ fetch_sub_items = function(sub_items, category){ loading_for_button($(""#category-loading-""+category)[0]); $.ajax({ url: noosfero_root() + ""/admin/categories/get_children"", dataType: ""html"", data: {id: category}, success: function(data, st, ajax){ $(sub_items).append(data); $("".small-loading"").remove(); $(""#show-button-""+category).fadeOut(400, function(){ $(""#hide-button-""+category).fadeIn(); }); $(sub_items).slideDown(); }, error: function(ajax, st, errorThrown) { alert('HTTP '+st+': '+errorThrown); } }); }; $("".hide-button"").live('click', function(){ var category = $(this).attr('data-category'); var sub_items = $('#category-sub-items-'+category); $(this).fadeOut(400, function(){ $(""#show-button-""+category).fadeIn(); }); $(sub_items).slideUp(); }); $("".show-button"").live('click', function(){ var category = $(this).attr('data-category'); var sub_items = $('#category-sub-items-'+category); if(!$(this).attr('data-fetched')){ fetch_sub_items(sub_items, category); $(this).attr('data-fetched', true); } else{ $(this).fadeOut(400, function(){ $(""#hide-button-""+category).fadeIn(); }); $(sub_items).slideDown(); } }); })(jQuery); ","(function($){ fetch_sub_items = function(sub_items, category){ loading_for_button($(""#category-loading-""+category)[0]); $.ajax({ url: ""/admin/categories/get_children"", dataType: ""html"", data: {id: category}, success: function(data, st, ajax){ $(sub_items).append(data); $("".small-loading"").remove(); $(""#show-button-""+category).fadeOut(400, function(){ $(""#hide-button-""+category).fadeIn(); }); $(sub_items).slideDown(); }, error: function(ajax, st, errorThrown) { alert('HTTP '+st+': '+errorThrown); } }); }; $("".hide-button"").live('click', function(){ var category = $(this).attr('data-category'); var sub_items = $('#category-sub-items-'+category); $(this).fadeOut(400, function(){ $(""#show-button-""+category).fadeIn(); }); $(sub_items).slideUp(); }); $("".show-button"").live('click', function(){ var category = $(this).attr('data-category'); var sub_items = $('#category-sub-items-'+category); if(!$(this).attr('data-fetched')){ fetch_sub_items(sub_items, category); $(this).attr('data-fetched', true); } else{ $(this).fadeOut(400, function(){ $(""#hide-button-""+category).fadeIn(); }); $(sub_items).slideDown(); } }); })(jQuery); " Add qty when searching seller because even if not passed a verification is made by default in _select_seller,"# Copyright (C) 2021 Akretion (http://www.akretion.com). from odoo import _, exceptions, models class PurchaseOrderLine(models.Model): _inherit = ""purchase.order.line"" def _get_lines_by_profiles(self, partner): profile_lines = { key: self.env[""purchase.order.line""] for key in partner.edi_purchase_profile_ids } for line in self: product = line.product_id seller = product._select_seller( partner_id=partner, quantity=line.product_uom_qty ) purchase_edi = seller.purchase_edi_id # Services should not appear in EDI file unless an EDI profile # is specifically on the supplier info. This way, we avoid # adding transport of potential discount or anything else # in the EDI file. if product.type == ""service"" and not purchase_edi: continue if purchase_edi: profile_lines[purchase_edi] |= line elif partner.default_purchase_profile_id: profile_lines[partner.default_purchase_profile_id] |= line else: raise exceptions.UserError( _(""Some products don't have edi profile configured : %s"") % (product.default_code,) ) return profile_lines ","# Copyright (C) 2021 Akretion (http://www.akretion.com). from odoo import _, exceptions, models class PurchaseOrderLine(models.Model): _inherit = ""purchase.order.line"" def _get_lines_by_profiles(self, partner): profile_lines = { key: self.env[""purchase.order.line""] for key in partner.edi_purchase_profile_ids } for line in self: product = line.product_id seller = product._select_seller(partner_id=partner) purchase_edi = seller.purchase_edi_id # Services should not appear in EDI file unless an EDI profile # is specifically on the supplier info. This way, we avoid # adding transport of potential discount or anything else # in the EDI file. if product.type == ""service"" and not purchase_edi: continue if purchase_edi: profile_lines[purchase_edi] |= line elif partner.default_purchase_profile_id: profile_lines[partner.default_purchase_profile_id] |= line else: raise exceptions.UserError( _(""Some products don't have edi profile configured : %s"") % (product.default_code,) ) return profile_lines " Fix parsing make with || on line.,"# vim: set ts=4 sw=4 et: coding=UTF-8 from rpmsection import Section class RpmBuild(Section): """""" Replace various troublemakers in build phase """""" def add(self, line): line = self._complete_cleanup(line) # smp_mflags for jobs if not self.reg.re_comment.match(line): line = self.embrace_macros(line) line = self.reg.re_jobs.sub('%{?_smp_mflags}', line) # add jobs if we have just make call on line # if user want single thread he should specify -j1 if line.startswith('make'): # if there are no smp_flags or jobs spec just append it if line.find('%{?_smp_mflags}') == -1 and line.find('-j') == -1: # Don't append %_smp_mflags if the line ends with a backslash, # it would break the formatting if not line.endswith('\\') and not '||' in line: line = '{0} {1}'.format(line, '%{?_smp_mflags}') # if user uses cmake directly just recommend him using the macros if line.startswith('cmake'): self.lines.append('# FIXME: you should use %cmake macros') Section.add(self, line) ","# vim: set ts=4 sw=4 et: coding=UTF-8 from rpmsection import Section class RpmBuild(Section): """""" Replace various troublemakers in build phase """""" def add(self, line): line = self._complete_cleanup(line) # smp_mflags for jobs if not self.reg.re_comment.match(line): line = self.embrace_macros(line) line = self.reg.re_jobs.sub('%{?_smp_mflags}', line) # add jobs if we have just make call on line # if user want single thread he should specify -j1 if line.startswith('make'): # if there are no smp_flags or jobs spec just append it if line.find('%{?_smp_mflags}') == -1 and line.find('-j') == -1: # Don't append %_smp_mflags if the line ends with a backslash, # it would break the formatting if not line.endswith('\\'): line = '{0} {1}'.format(line, '%{?_smp_mflags}') # if user uses cmake directly just recommend him using the macros if line.startswith('cmake'): self.lines.append('# FIXME: you should use %cmake macros') Section.add(self, line) " "Hide user name from screen readers The user name will be available to screen readers from the adjacent avatar's aria-label","<?php namespace Kanboard\Formatter; use Kanboard\Core\Filter\FormatterInterface; /** * Class UserMentionFormatter * * @package Kanboard\Formatter * @author Frederic Guillot */ class UserMentionFormatter extends BaseFormatter implements FormatterInterface { protected $users = array(); /** * Set users * * @param array $users * @return $this */ public function withUsers(array $users) { $this->users = $users; return $this; } /** * Apply formatter * * @access public * @return array */ public function format() { $result = array(); foreach ($this->users as $user) { $html = $this->helper->avatar->small( $user['id'], $user['username'], $user['name'], $user['email'], $user['avatar_path'], 'avatar-inline' ); $html .= ' '.$this->helper->text->e($user['username']); if (! empty($user['name'])) { $html .= ' <small aria-hidden=""true"">'.$this->helper->text->e($user['name']).'</small>'; } $result[] = array( 'value' => $user['username'], 'html' => $html, ); } return $result; } }","<?php namespace Kanboard\Formatter; use Kanboard\Core\Filter\FormatterInterface; /** * Class UserMentionFormatter * * @package Kanboard\Formatter * @author Frederic Guillot */ class UserMentionFormatter extends BaseFormatter implements FormatterInterface { protected $users = array(); /** * Set users * * @param array $users * @return $this */ public function withUsers(array $users) { $this->users = $users; return $this; } /** * Apply formatter * * @access public * @return array */ public function format() { $result = array(); foreach ($this->users as $user) { $html = $this->helper->avatar->small( $user['id'], $user['username'], $user['name'], $user['email'], $user['avatar_path'], 'avatar-inline' ); $html .= ' '.$this->helper->text->e($user['username']); if (! empty($user['name'])) { $html .= ' <small>'.$this->helper->text->e($user['name']).'</small>'; } $result[] = array( 'value' => $user['username'], 'html' => $html, ); } return $result; } }" Use ForeignKey for foreign keys and NullBooleanField in tests,"from django.test import TestCase from django.conf import settings from phonenumber_field.modelfields import PhoneNumberField from whats_fresh.models import * from django.contrib.gis.db import models import os import time import sys import datetime class ProductTestCase(TestCase): def setUp(self): self.expected_fields = { 'name': models.TextField, 'variety': models.TextField, 'alt_name': models.TextField, 'description': models.TextField, 'origin': models.TextField, 'season': models.TextField, 'available': models.NullBooleanField, 'market_price': models.TextField, 'link': models.TextField, 'image_id': models.ForeignKey, 'story_id': models.ForeignKey, 'created': models.DateTimeField, 'modified': models.DateTimeField, 'id': models.AutoField } def test_fields_exist(self): model = models.get_model('whats_fresh', 'Product') for field, field_type in self.expected_fields.items(): self.assertEqual( field_type, type(model._meta.get_field_by_name(field)[0])) def test_no_additional_fields(self): fields = Product._meta.get_all_field_names() self.assertTrue(sorted(fields) == sorted(self.expected_fields.keys())) def test_created_modified_fields(self): self.assertTrue(Product._meta.get_field('modified').auto_now) self.assertTrue(Product._meta.get_field('created').auto_now_add) ","from django.test import TestCase from django.conf import settings from phonenumber_field.modelfields import PhoneNumberField from whats_fresh.models import * from django.contrib.gis.db import models import os import time import sys import datetime class ProductTestCase(TestCase): def setUp(self): self.expected_fields = { 'name': models.TextField, 'variety': models.TextField, 'alt_name': models.TextField, 'description': models.TextField, 'origin': models.TextField, 'season': models.TextField, 'available': models.BooleanField, 'market_price': models.TextField, 'link': models.TextField, 'image_id': models.FloatField, 'stories_id': models.FloatField, 'created': models.DateTimeField, 'modified': models.DateTimeField, 'id': models.AutoField } def test_fields_exist(self): model = models.get_model('whats_fresh', 'Product') for field, field_type in self.expected_fields.items(): self.assertEqual( field_type, type(model._meta.get_field_by_name(field)[0])) def test_no_additional_fields(self): fields = Product._meta.get_all_field_names() self.assertTrue(sorted(fields) == sorted(self.expected_fields.keys())) def test_created_modified_fields(self): self.assertTrue(Product._meta.get_field('modified').auto_now) self.assertTrue(Product._meta.get_field('created').auto_now_add) " Remove instantation of the engine,"var chai = require(""chai""); var engine = require(""../src/dslEngine""); var TokenAlreadyInsertException = require( ""../src/utils/tokenAlreadyInsertException"" ); var NoTokenConnectedException = require( ""../src/utils/noTokenConnectedException"" ); describe(""Token"", () => { var token; describe(""#createToken"", () => { it(""should return a not undefined token"", () => { token = engine.generateToken(undefined); chai.expect(token).to.not.undefined; }); }); describe(""#insertToken"", () => { it(""shoud not throw any exception when push a token"", () => { chai.expect( engine.pushToken.bind(engine, token) ).to.not.throw(); }); }); describe(""#insertTokenOneOtherTime"", () => { it(""should throw exception TokenAlreadyInsertException"", () => { chai.expect(engine.pushToken.bind(engine, token)).to.throw( TokenAlreadyInsertException ); }); }); describe(""#removeToken"", () => { it(""shoud return the same token"", () => { chai.expect(engine.ejectSafelyToken()).to.equal(token); }); }); describe(""#removeTokenOneOtherTime"", () => { it(""shoud throw exception NoTokenConnectedException"", () => { chai.expect(engine.ejectSafelyToken.bind(engine)).to.throw( NoTokenConnectedException ); }); }); }); ","var chai = require(""chai""); var DSLEngine = require(""../src/dslEngine""); var TokenAlreadyInsertException = require( ""../src/utils/tokenAlreadyInsertException"" ); var NoTokenConnectedException = require( ""../src/utils/noTokenConnectedException"" ); describe(""Token"", () => { var engine; var token; before(() => { engine = new DSLEngine(); }); describe(""#createToken"", () => { it(""should return a not undefined token"", () => { token = engine.generateToken(undefined); chai.expect(token).to.not.undefined; }); }); describe(""#insertToken"", () => { it(""shoud not throw any exception when push a token"", () => { chai.expect( engine.pushToken.bind(engine, token) ).to.not.throw(); }); }); describe(""#insertTokenOneOtherTime"", () => { it(""should throw exception TokenAlreadyInsertException"", () => { chai.expect(engine.pushToken.bind(engine, token)).to.throw( TokenAlreadyInsertException ); }); }); describe(""#removeToken"", () => { it(""shoud return the same token"", () => { chai.expect(engine.ejectSafelyToken()).to.equal(token); }); }); describe(""#removeTokenOneOtherTime"", () => { it(""shoud throw exception NoTokenConnectedException"", () => { chai.expect(engine.ejectSafelyToken.bind(engine)).to.throw( NoTokenConnectedException ); }); }); }); " Make compiled source file more readable,"import path from 'path'; import webpack from 'webpack'; import autoprefixer from 'autoprefixer'; module.exports = { entry: { 'react-image-lightbox': './src/index', }, output: { path: path.join(__dirname, 'dist', 'umd'), filename: '[name].js', libraryTarget: 'umd', library: 'ReactImageLightbox', }, resolve: { extensions: ['', '.js'] }, devtool: 'source-map', plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.EnvironmentPlugin([ ""NODE_ENV"", ]), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, mangle: false, beautify: true, comments: true, }), ], postcss: [ autoprefixer({ browsers: ['IE >= 9', '> 1%'] }), ], externals: { react: 'react', 'react-dom': 'react-dom', 'react-modal': 'react-modal', }, module: { loaders: [ { test: /\.jsx?$/, loaders: ['babel'], include: path.join(__dirname, 'src') }, { test: /\.scss$/, loaders: [ 'style-loader', 'css-loader?modules&importLoaders=1&localIdentName=[local]___[hash:base64:5]', 'postcss-loader', 'sass-loader', ], include: path.join(__dirname, 'src') }, ] } }; ","import path from 'path'; import webpack from 'webpack'; import autoprefixer from 'autoprefixer'; module.exports = { entry: { 'react-image-lightbox': './src/index', }, output: { path: path.join(__dirname, 'dist', 'umd'), filename: '[name].js', libraryTarget: 'umd', library: 'ReactImageLightbox', }, resolve: { extensions: ['', '.js'] }, devtool: 'source-map', plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.EnvironmentPlugin([ ""NODE_ENV"", ]), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, }), ], postcss: [ autoprefixer({ browsers: ['IE >= 9', '> 1%'] }), ], externals: { react: 'react', 'react-dom': 'react-dom', 'react-modal': 'react-modal', }, module: { loaders: [ { test: /\.jsx?$/, loaders: ['babel'], include: path.join(__dirname, 'src') }, { test: /\.scss$/, loaders: [ 'style-loader', 'css-loader?modules&importLoaders=1&localIdentName=[local]___[hash:base64:5]', 'postcss-loader', 'sass-loader', ], include: path.join(__dirname, 'src') }, ] } }; " Add small delay to allow PhantomJS to finish its startup process.,"<?php /** * PHP version 5.6 * * This source file is subject to the license that is bundled with this package in the file LICENSE. */ namespace Codeup\Console\Command\Listeners; use Symfony\Component\Console\Event\ConsoleCommandEvent; use Symfony\Component\Console\Event\ConsoleTerminateEvent; /** * Start and stop PhantomJS before and after executing command `codeup:rollcall` */ class PhantomJsListener { /** @var int */ private $pidPhantomJs; public function startPhantomJs(ConsoleCommandEvent $event) { if ('codeup:rollcall' !== $event->getCommand()->getName()) { return; } $output = []; exec( 'phantomjs --webdriver=127.0.0.1:8910 >/dev/null 2>&1 & echo $!', $output ); $this->pidPhantomJs = (int) $output[0]; $event->getOutput()->writeln(sprintf( '<info>PhantomJS is running with PID <comment>%d</comment></info>', $this->pidPhantomJs )); sleep(2); } public function stopPhantomJs(ConsoleTerminateEvent $event) { if ('codeup:rollcall' !== $event->getCommand()->getName()) { return; } exec(""kill {$this->pidPhantomJs}""); $event->getOutput()->writeln(sprintf( '<info>PhantomJS with PID <comment>%d</comment> was stopped</info>', $this->pidPhantomJs )); } } ","<?php /** * PHP version 5.6 * * This source file is subject to the license that is bundled with this package in the file LICENSE. */ namespace Codeup\Console\Command\Listeners; use Symfony\Component\Console\Event\ConsoleCommandEvent; use Symfony\Component\Console\Event\ConsoleTerminateEvent; /** * Start and stop PhantomJS before and after executing command `codeup:rollcall` */ class PhantomJsListener { /** @var int */ private $pidPhantomJs; public function startPhantomJs(ConsoleCommandEvent $event) { if ('codeup:rollcall' !== $event->getCommand()->getName()) { return; } $output = []; exec( 'phantomjs --webdriver=127.0.0.1:8910 >/dev/null 2>&1 & echo $!', $output ); $this->pidPhantomJs = (int) $output[0]; $event->getOutput()->writeln(sprintf( '<info>PhantomJS is running with PID <comment>%d</comment></info>', $this->pidPhantomJs )); } public function stopPhantomJs(ConsoleTerminateEvent $event) { if ('codeup:rollcall' !== $event->getCommand()->getName()) { return; } exec(""kill {$this->pidPhantomJs}""); $event->getOutput()->writeln(sprintf( '<info>PhantomJS with PID <comment>%d</comment> was stopped</info>', $this->pidPhantomJs )); } } " Fix generator path for service provider,"<?php namespace Pingpong\Modules\Commands; use Illuminate\Support\Str; use Pingpong\Generators\Stub; use Pingpong\Modules\Traits\ModuleCommandTrait; use Symfony\Component\Console\Input\InputArgument; class GenerateProviderCommand extends GeneratorCommand { use ModuleCommandTrait; /** * The console command name. * * @var string */ protected $name = 'module:provider'; /** * The console command description. * * @var string */ protected $description = 'Generate a new service provider for the specified module.'; /** * Get the console command arguments. * * @return array */ protected function getArguments() { return array( array('name', InputArgument::REQUIRED, 'The service provider name.'), array('module', InputArgument::OPTIONAL, 'The name of module will be used.'), ); } /** * @return mixed */ protected function getTemplateContents() { return new Stub('provider', [ 'MODULE' => $this->getModuleName(), 'NAME' => $this->getFileName() ]); } /** * @return mixed */ protected function getDestinationFilePath() { $path = $this->laravel['modules']->getModulePath($this->getModuleName()); $generatorPath = $this->laravel['modules']->config('paths.generator.provider'); return $path . $generatorPath . '/' . $this->getFileName() . '.php'; } /** * @return string */ private function getFileName() { return Str::studly($this->argument('name')); } } ","<?php namespace Pingpong\Modules\Commands; use Illuminate\Support\Str; use Pingpong\Generators\Stub; use Pingpong\Modules\Traits\ModuleCommandTrait; use Symfony\Component\Console\Input\InputArgument; class GenerateProviderCommand extends GeneratorCommand { use ModuleCommandTrait; /** * The console command name. * * @var string */ protected $name = 'module:provider'; /** * The console command description. * * @var string */ protected $description = 'Generate a new service provider for the specified module.'; /** * Get the console command arguments. * * @return array */ protected function getArguments() { return array( array('name', InputArgument::REQUIRED, 'The service provider name.'), array('module', InputArgument::OPTIONAL, 'The name of module will be used.'), ); } /** * @return mixed */ protected function getTemplateContents() { return new Stub('provider', [ 'MODULE' => $this->getModuleName(), 'NAME' => $this->getFileName() ]); } /** * @return mixed */ protected function getDestinationFilePath() { $path = $this->laravel['modules']->getModulePath($this->getModuleName()); $generatorPath = $this->laravel['modules']->get('paths.generator.provider'); return $path . $generatorPath . '/' . $this->getFileName() . '.php'; } /** * @return string */ private function getFileName() { return Str::studly($this->argument('name')); } } " Allow connecting to unknown hosts but warn,"from __future__ import print_function import select import paramiko class GerritEvents(object): def __init__(self, userid, host, key=None): self.userid = userid self.host = host self.port = 29418 self.key = key def _read_events(self, stream, use_poll=False): if not use_poll: yield stream.readline().strip() poller = select.poll() poller.register(stream.channel) while True: for fd, event in poller.poll(): if fd == stream.channel.fileno(): if event == select.POLLIN: yield stream.readline().strip() else: raise Exception('Non-POLLIN event on stdout!') @property def events(self): client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) connargs = { 'hostname': self.host, 'port': self.port, 'username': self.userid } if self.key: connargs['pkey'] = self.key client.connect(**connargs) stdin, stdout, stderr = client.exec_command('gerrit stream-events') for event in self._read_events(stdout, use_poll=True): yield event ","from __future__ import print_function import select import paramiko class GerritEvents(object): def __init__(self, userid, host, key=None): self.userid = userid self.host = host self.port = 29418 self.key = key def _read_events(self, stream, use_poll=False): if not use_poll: yield stream.readline().strip() poller = select.poll() poller.register(stream.channel) while True: for fd, event in poller.poll(): if fd == stream.channel.fileno(): if event == select.POLLIN: yield stream.readline().strip() else: raise Exception('Non-POLLIN event on stdout!') @property def events(self): client = paramiko.SSHClient() client.load_system_host_keys() connargs = { 'hostname': self.host, 'port': self.port, 'username': self.userid } if self.key: connargs['pkey'] = self.key client.connect(**connargs) stdin, stdout, stderr = client.exec_command('gerrit stream-events') for event in self._read_events(stdout, use_poll=True): yield event " Add tests for the __toString method of the File model,"<?php namespace Transmission\Tests\Model; use Transmission\Model\File; use Transmission\Util\PropertyMapper; class FileTest extends \PHPUnit_Framework_TestCase { protected $file; /** * @test */ public function shouldImplementModelInterface() { $this->assertInstanceOf('Transmission\Model\ModelInterface', $this->getFile()); } /** * @test */ public function shouldHaveNonEmptyMapping() { $this->assertNotEmpty($this->getFile()->getMapping()); } /** * @test */ public function shouldBeCreatedFromMapping() { $source = (object) array( 'name' => 'foo', 'length' => 100, 'bytesCompleted' => 10 ); PropertyMapper::map($this->getFile(), $source); $this->assertEquals('foo', $this->getFile()->getName()); $this->assertEquals(100, $this->getFile()->getSize()); $this->assertEquals(10, $this->getFile()->getCompleted()); $this->assertFalse($this->getFile()->isDone()); } /** * @test */ public function shouldConvertToString() { $this->getFile()->setName('foo'); $this->assertInternalType('string', (string) $this->getFile()); $this->assertEquals('foo', (string) $this->getFile()); } public function setup() { $this->file = new File(); } private function getFile() { return $this->file; } } ","<?php namespace Transmission\Tests\Model; use Transmission\Model\File; use Transmission\Util\PropertyMapper; class FileTest extends \PHPUnit_Framework_TestCase { protected $file; /** * @test */ public function shouldImplementModelInterface() { $this->assertInstanceOf('Transmission\Model\ModelInterface', $this->getFile()); } /** * @test */ public function shouldHaveNonEmptyMapping() { $this->assertNotEmpty($this->getFile()->getMapping()); } /** * @test */ public function shouldBeCreatedFromMapping() { $source = (object) array( 'name' => 'foo', 'length' => 100, 'bytesCompleted' => 10 ); PropertyMapper::map($this->getFile(), $source); $this->assertEquals('foo', $this->getFile()->getName()); $this->assertEquals(100, $this->getFile()->getSize()); $this->assertEquals(10, $this->getFile()->getCompleted()); $this->assertFalse($this->getFile()->isDone()); } public function setup() { $this->file = new File(); } private function getFile() { return $this->file; } } " Add Framework::Pytest to list of classifiers,"from setuptools import setup setup( name=""pytest-xdist"", use_scm_version={'write_to': 'xdist/_version.py'}, description='py.test xdist plugin for distributed testing' ' and loop-on-failing modes', long_description=open('README.rst').read(), license='MIT', author='holger krekel and contributors', author_email='pytest-dev@python.org,holger@merlinux.eu', url='https://github.com/pytest-dev/pytest-xdist', platforms=['linux', 'osx', 'win32'], packages=['xdist'], entry_points={ 'pytest11': [ 'xdist = xdist.plugin', 'xdist.looponfail = xdist.looponfail', 'xdist.boxed = xdist.boxed', ], }, zip_safe=False, install_requires=['execnet>=1.1', 'pytest>=2.4.2', 'py>=1.4.22'], setup_requires=['setuptools_scm'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Framework :: Pytest', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS :: MacOS X', 'Topic :: Software Development :: Testing', 'Topic :: Software Development :: Quality Assurance', 'Topic :: Utilities', 'Programming Language :: Python', 'Programming Language :: Python :: 3', ], ) ","from setuptools import setup setup( name=""pytest-xdist"", use_scm_version={'write_to': 'xdist/_version.py'}, description='py.test xdist plugin for distributed testing' ' and loop-on-failing modes', long_description=open('README.rst').read(), license='MIT', author='holger krekel and contributors', author_email='pytest-dev@python.org,holger@merlinux.eu', url='https://github.com/pytest-dev/pytest-xdist', platforms=['linux', 'osx', 'win32'], packages=['xdist'], entry_points={ 'pytest11': [ 'xdist = xdist.plugin', 'xdist.looponfail = xdist.looponfail', 'xdist.boxed = xdist.boxed', ], }, zip_safe=False, install_requires=['execnet>=1.1', 'pytest>=2.4.2', 'py>=1.4.22'], setup_requires=['setuptools_scm'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS :: MacOS X', 'Topic :: Software Development :: Testing', 'Topic :: Software Development :: Quality Assurance', 'Topic :: Utilities', 'Programming Language :: Python', 'Programming Language :: Python :: 3', ], ) " Switch field back to private as it was made protected by mistake,"package io.quarkus.runtime.configuration; import java.io.Serializable; import java.util.Map; import java.util.Set; import org.eclipse.microprofile.config.spi.ConfigSource; import org.wildfly.common.Assert; import org.wildfly.common.annotation.NotNull; import io.smallrye.config.ConfigSourceMap; /** * A base class for configuration sources which delegate to other configuration sources. */ public abstract class AbstractDelegatingConfigSource implements ConfigSource, Serializable { private static final long serialVersionUID = -6636734120743034580L; protected final ConfigSource delegate; private Map<String, String> propertiesMap; /** * Construct a new instance. * * @param delegate the delegate configuration source (must not be {@code null}) */ public AbstractDelegatingConfigSource(final ConfigSource delegate) { Assert.checkNotNullParam(""delegate"", delegate); this.delegate = delegate; } /** * Get the delegate config source. * * @return the delegate config source (not {@code null}) */ protected @NotNull ConfigSource getDelegate() { return delegate; } public final Map<String, String> getProperties() { Map<String, String> propertiesMap = this.propertiesMap; if (propertiesMap == null) { propertiesMap = this.propertiesMap = new ConfigSourceMap(this); } return propertiesMap; } public abstract Set<String> getPropertyNames(); public String getName() { return delegate.getName(); } public int getOrdinal() { return delegate.getOrdinal(); } } ","package io.quarkus.runtime.configuration; import java.io.Serializable; import java.util.Map; import java.util.Set; import org.eclipse.microprofile.config.spi.ConfigSource; import org.wildfly.common.Assert; import org.wildfly.common.annotation.NotNull; import io.smallrye.config.ConfigSourceMap; /** * A base class for configuration sources which delegate to other configuration sources. */ public abstract class AbstractDelegatingConfigSource implements ConfigSource, Serializable { private static final long serialVersionUID = -6636734120743034580L; protected final ConfigSource delegate; protected Map<String, String> propertiesMap; /** * Construct a new instance. * * @param delegate the delegate configuration source (must not be {@code null}) */ public AbstractDelegatingConfigSource(final ConfigSource delegate) { Assert.checkNotNullParam(""delegate"", delegate); this.delegate = delegate; } /** * Get the delegate config source. * * @return the delegate config source (not {@code null}) */ protected @NotNull ConfigSource getDelegate() { return delegate; } public final Map<String, String> getProperties() { Map<String, String> propertiesMap = this.propertiesMap; if (propertiesMap == null) { propertiesMap = this.propertiesMap = new ConfigSourceMap(this); } return propertiesMap; } public abstract Set<String> getPropertyNames(); public String getName() { return delegate.getName(); } public int getOrdinal() { return delegate.getOrdinal(); } } " Fix builds on systems where LANG=C,"import io import setuptools def read_long_description(): with io.open('README.rst', encoding='utf-8') as f: data = f.read() with io.open('CHANGES.rst', encoding='utf-8') as f: data += '\n\n' + f.read() return data setup_params = dict( name=""irc"", description=""IRC (Internet Relay Chat) protocol client library for Python"", long_description=read_long_description(), use_vcs_version=True, packages=setuptools.find_packages(), author=""Joel Rosdahl"", author_email=""joel@rosdahl.net"", maintainer=""Jason R. Coombs"", maintainer_email=""jaraco@jaraco.com"", url=""http://python-irclib.sourceforge.net"", license=""MIT"", classifiers = [ ""Development Status :: 5 - Production/Stable"", ""Intended Audience :: Developers"", ""Programming Language :: Python :: 2.7"", ""Programming Language :: Python :: 3"", ], install_requires=[ 'six', 'jaraco.util', ], setup_requires=[ 'hgtools>=5', 'pytest-runner', ], tests_require=[ 'pytest', 'mock', ], ) if __name__ == '__main__': setuptools.setup(**setup_params) ","import setuptools def read_long_description(): with open('README.rst') as f: data = f.read() with open('CHANGES.rst') as f: data += '\n\n' + f.read() return data setup_params = dict( name=""irc"", description=""IRC (Internet Relay Chat) protocol client library for Python"", long_description=read_long_description(), use_vcs_version=True, packages=setuptools.find_packages(), author=""Joel Rosdahl"", author_email=""joel@rosdahl.net"", maintainer=""Jason R. Coombs"", maintainer_email=""jaraco@jaraco.com"", url=""http://python-irclib.sourceforge.net"", license=""MIT"", classifiers = [ ""Development Status :: 5 - Production/Stable"", ""Intended Audience :: Developers"", ""Programming Language :: Python :: 2.7"", ""Programming Language :: Python :: 3"", ], install_requires=[ 'six', 'jaraco.util', ], setup_requires=[ 'hgtools>=5', 'pytest-runner', ], tests_require=[ 'pytest', 'mock', ], ) if __name__ == '__main__': setuptools.setup(**setup_params) " Correct error in namespace declaration,"<?php namespace DMS\Bundle\TwigExtensionBundle\Twig\Text; /** * Adds support for Padding a String in Twig */ class PadStringExtension extends \Twig_Extension { /** * Name of Extension * * @return string */ public function getName() { return 'PadStringExtension'; } /** * Available filters * * @return array */ public function getFilters() { return array( 'padString' => new \Twig_Filter_Method($this, 'padStringFilter'), ); } /** * Pads string on right or left with given padCharacter until string * reaches maxLength * * @param string $value * @param string $padCharacter * @param int $maxLength * @param bool $padLeft * @return string * @throws \InvalidArgumentException */ public function padStringFilter($value, $padCharacter, $maxLength, $padLeft = true) { if ( ! is_int($maxLength) ) { throw new \InvalidArgumentException('Pad String Filter expects its second argument to be an integer'); } if (function_exists('mb_strlen')) { $padLength = $maxLength - mb_strlen($value); } else { $padLength = $maxLength - strlen($value); } if ($padLength <= 0) { return $value; } $padString = str_repeat($padCharacter, $padLength); if ($padLeft) { return $padString . $value; } return $value . $padString; } } ","<?php namespace DMS\Bundle\TwigExtensionBundle\Twig\Date; /** * Adds support for Padding a String in Twig */ class PadStringExtension extends \Twig_Extension { /** * Name of Extension * * @return string */ public function getName() { return 'PadStringExtension'; } /** * Available filters * * @return array */ public function getFilters() { return array( 'padString' => new \Twig_Filter_Method($this, 'padStringFilter'), ); } /** * Pads string on right or left with given padCharacter until string * reaches maxLength * * @param string $value * @param string $padCharacter * @param int $maxLength * @param bool $padLeft * @return string * @throws \InvalidArgumentException */ public function padStringFilter($value, $padCharacter, $maxLength, $padLeft = true) { if ( ! is_int($maxLength) ) { throw new \InvalidArgumentException('Pad String Filter expects its second argument to be an integer'); } if (function_exists('mb_strlen')) { $padLength = $maxLength - mb_strlen($value); } else { $padLength = $maxLength - strlen($value); } if ($padLength <= 0) { return $value; } $padString = str_repeat($padCharacter, $padLength); if ($padLeft) { return $padString . $value; } return $value . $padString; } } " Fix NPE if property with @EL is null.,"package org.jboss.loom.utils.el; import java.lang.reflect.Field; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Ondrej Zizka, ozizka at redhat.com */ public class ELUtils { private static final Logger log = LoggerFactory.getLogger( ELUtils.class ); public static void evaluateObjectMembersEL( Object obj, JuelCustomResolverEvaluator eval, EL.ResolvingStage stage ) { Class curClass = obj.getClass(); while( curClass != null && ! Object.class.equals( curClass ) ){ for( Field fld : curClass.getDeclaredFields() ){ //if( ! fld.getType().equals( String.class )) if( ! String.class.isAssignableFrom( fld.getType() ) ) continue; final EL ann = fld.getAnnotation( EL.class ); if( null == ann ) continue; if( stage != null && ann.stage() != stage ) continue; try { fld.setAccessible( true ); String orig = (String) fld.get( obj ); if( orig == null || orig.trim().isEmpty() ) continue; String res = eval.evaluateEL( orig ); fld.set( obj, res ); } catch( IllegalArgumentException | IllegalAccessException ex ) { throw new IllegalStateException(""Failed resolving EL in "" + obj + ""."" + fld.getName() + "": "" + ex.getMessage(), ex); } } curClass = curClass.getSuperclass(); } } }// class ","package org.jboss.loom.utils.el; import java.lang.reflect.Field; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Ondrej Zizka, ozizka at redhat.com */ public class ELUtils { private static final Logger log = LoggerFactory.getLogger( ELUtils.class ); public static void evaluateObjectMembersEL( Object obj, JuelCustomResolverEvaluator eval, EL.ResolvingStage stage ) { Class curClass = obj.getClass(); while( curClass != null && ! Object.class.equals( curClass ) ){ for( Field fld : curClass.getDeclaredFields() ){ //if( ! fld.getType().equals( String.class )) if( ! String.class.isAssignableFrom( fld.getType() ) ) continue; final EL ann = fld.getAnnotation( EL.class ); if( null == ann ) continue; if( stage != null && ann.stage() != stage ) continue; try { fld.setAccessible( true ); String orig = (String) fld.get( obj ); String res = eval.evaluateEL( orig ); fld.set( obj, res ); } catch( IllegalArgumentException | IllegalAccessException ex ) { throw new IllegalStateException(""Failed resolving EL in "" + obj + "": "" + ex.getMessage(), ex); } } curClass = curClass.getSuperclass(); } } }// class " Make library compatible with PHPUnit 4,"<?php namespace Matthias\PhpUnitAsynchronicity; use Matthias\Polling\CallableProbe; use Matthias\Polling\Exception\Interrupted; use Matthias\Polling\Poller; use Matthias\Polling\ProbeInterface; use Matthias\Polling\SystemClock; use Matthias\Polling\Timeout; class Eventually extends \PHPUnit_Framework_Constraint { private $timeoutMilliseconds; private $waitMilliseconds; public function __construct($timeoutMilliseconds = 5000, $waitMilliseconds = 500) { // for compatibility with PHPUnit 4 $parentConstructor = array('parent', '__construct'); if (is_callable($parentConstructor)) { call_user_func($parentConstructor); } $this->timeoutMilliseconds = $timeoutMilliseconds; $this->waitMilliseconds = $waitMilliseconds; } public function evaluate($probe, $description = '', $returnResult = false) { if (is_callable($probe)) { $probe = new CallableProbe($probe); } if (!($probe instanceof ProbeInterface)) { throw new \InvalidArgumentException('Expected an instance of ProbeInterface'); } try { $poller = new Poller(); $poller->poll( $probe, new Timeout(new SystemClock(), $this->waitMilliseconds, $this->timeoutMilliseconds) ); } catch (Interrupted $exception) { if ($returnResult) { return false; } else { $this->fail($probe, ($description != '' ? $description . ""\n"" : '') . 'A timeout has occurred'); } } return true; } public function toString() { return 'was satisfied within the provided timeout'; } } ","<?php namespace Matthias\PhpUnitAsynchronicity; use Matthias\Polling\CallableProbe; use Matthias\Polling\Exception\Interrupted; use Matthias\Polling\Poller; use Matthias\Polling\ProbeInterface; use Matthias\Polling\SystemClock; use Matthias\Polling\Timeout; class Eventually extends \PHPUnit_Framework_Constraint { private $timeoutMilliseconds; private $waitMilliseconds; public function __construct($timeoutMilliseconds = 5000, $waitMilliseconds = 500) { parent::__construct(); $this->timeoutMilliseconds = $timeoutMilliseconds; $this->waitMilliseconds = $waitMilliseconds; } public function evaluate($probe, $description = '', $returnResult = false) { if (is_callable($probe)) { $probe = new CallableProbe($probe); } if (!($probe instanceof ProbeInterface)) { throw new \InvalidArgumentException('Expected an instance of ProbeInterface'); } try { $poller = new Poller(); $poller->poll( $probe, new Timeout(new SystemClock(), $this->waitMilliseconds, $this->timeoutMilliseconds) ); } catch (Interrupted $exception) { if ($returnResult) { return false; } else { $this->fail($probe, ($description != '' ? $description . ""\n"" : '') . 'A timeout has occurred'); } } return true; } public function toString() { return 'was satisfied within the provided timeout'; } } " fix: Move timestamp before dict for insertion,"""""""Notify Slack channel."""""" import time from ..utils import get_properties, get_template, post_slack_message class SlackNotification: """"""Post slack notification. Inform users about infrastructure changes to prod* accounts. """""" def __init__(self, app=None, env=None, prop_path=None): timestamp = time.strftime(""%B %d, %Y %H:%M:%S %Z"", time.gmtime()) self.info = {'app': app, 'env': env, 'properties': prop_path, 'timestamp': timestamp} self.settings = get_properties(self.info['properties']) self.info['config_commit_short'] = self.settings['pipeline'][ 'config_commit'][0:11] def post_message(self): """"""Send templated message to **#deployments-{env}**."""""" message = get_template( template_file='slack-templates/pipeline-prepare-ran.j2', info=self.info) channel = '#deployments-{}'.format(self.info['env'].lower()) post_slack_message(message, channel) def notify_slack_channel(self): """"""Post message to a defined Slack channel."""""" message = get_template( template_file='slack-templates/pipeline-prepare-ran.j2', info=self.info) if self.settings['pipeline']['notifications']['slack']: post_slack_message( message, self.settings['pipeline']['notifications']['slack']) ","""""""Notify Slack channel."""""" import time from ..utils import get_properties, get_template, post_slack_message class SlackNotification: """"""Post slack notification. Inform users about infrastructure changes to prod* accounts. """""" def __init__(self, app=None, env=None, prop_path=None): self.info = {'app': app, 'env': env, 'properties': prop_path} timestamp = time.strftime(""%B %d, %Y %H:%M:%S %Z"", time.gmtime()) self.info['timestamp'] = timestamp self.settings = get_properties(self.info['properties']) self.info['config_commit_short'] = self.settings['pipeline'][ 'config_commit'][0:11] def post_message(self): """"""Send templated message to **#deployments-{env}**."""""" message = get_template( template_file='slack-templates/pipeline-prepare-ran.j2', info=self.info) channel = '#deployments-{}'.format(self.info['env'].lower()) post_slack_message(message, channel) def notify_slack_channel(self): """"""Post message to a defined Slack channel."""""" message = get_template( template_file='slack-templates/pipeline-prepare-ran.j2', info=self.info) if self.settings['pipeline']['notifications']['slack']: post_slack_message( message, self.settings['pipeline']['notifications']['slack']) " Send view recovery code URL with email request.,"// @flow import { ServerAPI } from './server-utils' import log4js from 'log4js' const logger = log4js.getLogger(__filename) export function sendRecoveryEmail( email: string, blockstackId?: string, encryptedSeed: string ): Promise<any> { const { protocol, hostname, port } = location const thisUrl = `${protocol}//${hostname}${port && `:${port}`}` const seedRecovery = `${thisUrl}/seed?encrypted=${encodeURIComponent( encryptedSeed )}` return ServerAPI.post('/recovery', { email, seedRecovery, blockstackId }) .then( () => { logger.log(`email-utils: sent ${email} recovery email`) }, error => { logger.error('email-utils: error', error) throw error } ) .catch(error => { logger.error('email-utils: error', error) throw error }) } export function sendRestoreEmail( email: string, blockstackId?: string, encryptedSeed: string ): Promise<any> { const { protocol, hostname, port } = location const thisUrl = `${protocol}//${hostname}${port && `:${port}`}` const seedRecovery = `${thisUrl}/seed?encrypted=${encodeURIComponent( encryptedSeed )}` return ServerAPI.post('/restore', { email, encryptedSeed, blockstackId, seedRecovery }) .then( () => { logger.log(`email-utils: sent ${email} restore email`) }, error => { logger.error('email-utils: error', error) throw error } ) .catch(error => { logger.error('email-utils: error', error) throw error }) } ","// @flow import { ServerAPI } from './server-utils' import log4js from 'log4js' const logger = log4js.getLogger(__filename) export function sendRecoveryEmail( email: string, blockstackId?: string, encryptedSeed: string ): Promise<any> { const { protocol, hostname, port } = location const thisUrl = `${protocol}//${hostname}${port && `:${port}`}` const seedRecovery = `${thisUrl}/seed?encrypted=${encodeURIComponent( encryptedSeed )}` return ServerAPI.post('/recovery', { email, seedRecovery, blockstackId }) .then( () => { logger.log(`email-utils: sent ${email} recovery email`) }, error => { logger.error('email-utils: error', error) throw error } ) .catch(error => { logger.error('email-utils: error', error) throw error }) } export function sendRestoreEmail( email: string, blockstackId?: string, encryptedSeed: string ): Promise<any> { return ServerAPI.post('/restore', { email, encryptedSeed, blockstackId }) .then( () => { logger.log(`email-utils: sent ${email} restore email`) }, error => { logger.error('email-utils: error', error) throw error } ) .catch(error => { logger.error('email-utils: error', error) throw error }) } " Fix ip -> target bug,"<?php namespace CascadeEnergy\ServiceDiscovery\Consul; use CascadeEnergy\ServiceDiscovery\ServiceDiscoveryClientInterface; class ConsulDns implements ServiceDiscoveryClientInterface { private $lookupService; public function __construct(callable $lookupService = null) { $this->lookupService = $lookupService; if (is_null($lookupService)) { $this->lookupService = ""dns_get_record""; } } public function getServiceAddress($serviceName, $version = null) { $dnsEntry = ""$serviceName.service.consul""; if (!empty($version)) { $dnsEntry = ""$version.$dnsEntry""; } $resultList = call_user_func($this->lookupService, $dnsEntry, DNS_SRV); if (empty($resultList)) { return false; } $ipAddress = ''; $port = '80'; foreach ($resultList as $result) { if (isset($result['host'])) { $ipAddress = $result['host']; } if (isset($result['port'])) { $port = $result['port']; } } return ""$ipAddress:$port""; } } ","<?php namespace CascadeEnergy\ServiceDiscovery\Consul; use CascadeEnergy\ServiceDiscovery\ServiceDiscoveryClientInterface; class ConsulDns implements ServiceDiscoveryClientInterface { private $lookupService; public function __construct(callable $lookupService = null) { $this->lookupService = $lookupService; if (is_null($lookupService)) { $this->lookupService = ""dns_get_record""; } } public function getServiceAddress($serviceName, $version = null) { $dnsEntry = ""$serviceName.service.consul""; if (!empty($version)) { $dnsEntry = ""$version.$dnsEntry""; } $resultList = call_user_func($this->lookupService, $dnsEntry, DNS_SRV); if (empty($resultList)) { return false; } $ipAddress = ''; $port = '80'; foreach ($resultList as $result) { if (isset($result['ip'])) { $ipAddress = $result['ip']; } if (isset($result['port'])) { $port = $result['port']; } } return ""$ipAddress:$port""; } } " "Correct test criteria for time format for scheduled skill. Now matches current behaviour, previous behaviour is not a good idea since it depended on Locale.","from datetime import datetime, timedelta import unittest from mycroft.skills.scheduled_skills import ScheduledSkill from mycroft.util.log import getLogger __author__ = 'eward' logger = getLogger(__name__) class ScheduledSkillTest(unittest.TestCase): skill = ScheduledSkill(name='ScheduledSkillTest') def test_formatted_time_today_hours(self): date = datetime.now() + timedelta(hours=2) self.assertEquals(self.skill. get_formatted_time(float(date.strftime('%s'))), ""1 hours and 59 minutes from now"") def test_formatted_time_today_min(self): date = datetime.now() + timedelta(minutes=2) self.assertEquals(self.skill. get_formatted_time(float(date.strftime('%s'))), ""1 minutes and 59 seconds from now"") def test_formatted_time_days(self): date = datetime.now() + timedelta(days=2) self.assertEquals(self.skill. get_formatted_time(float(date.strftime('%s'))), date.strftime(""%d %B, %Y at %H:%M"")) ","from datetime import datetime, timedelta import unittest from mycroft.skills.scheduled_skills import ScheduledSkill from mycroft.util.log import getLogger __author__ = 'eward' logger = getLogger(__name__) class ScheduledSkillTest(unittest.TestCase): skill = ScheduledSkill(name='ScheduledSkillTest') def test_formatted_time_today_hours(self): date = datetime.now() + timedelta(hours=2) self.assertEquals(self.skill. get_formatted_time(float(date.strftime('%s'))), ""1 hours and 59 minutes from now"") def test_formatted_time_today_min(self): date = datetime.now() + timedelta(minutes=2) self.assertEquals(self.skill. get_formatted_time(float(date.strftime('%s'))), ""1 minutes and 59 seconds from now"") def test_formatted_time_days(self): date = datetime.now() + timedelta(days=2) self.assertEquals(self.skill. get_formatted_time(float(date.strftime('%s'))), date.strftime(""%A, %B %d, %Y at %H:%M"")) " Fix test after updating the French tokenizer stuff,"# coding: utf-8 from __future__ import unicode_literals from ...language import Language from ...attrs import LANG from ...fr.language_data import get_tokenizer_exceptions, STOP_WORDS from ...language_data.punctuation import TOKENIZER_INFIXES, ALPHA import pytest @pytest.fixture def fr_tokenizer_w_infix(): SPLIT_INFIX = r'(?<=[{a}]\')(?=[{a}])'.format(a=ALPHA) # create new Language subclass to add to default infixes class French(Language): lang = 'fr' class Defaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: 'fr' tokenizer_exceptions = get_tokenizer_exceptions() stop_words = STOP_WORDS infixes = TOKENIZER_INFIXES + [SPLIT_INFIX] return French.Defaults.create_tokenizer() @pytest.mark.parametrize('text,expected_tokens', [(""l'avion"", [""l'"", ""avion""]), (""j'ai"", [""j'"", ""ai""])]) def test_issue768(fr_tokenizer_w_infix, text, expected_tokens): """"""Allow zero-width 'infix' token during the tokenization process."""""" tokens = fr_tokenizer_w_infix(text) assert len(tokens) == 2 assert [t.text for t in tokens] == expected_tokens ","# coding: utf-8 from __future__ import unicode_literals from ...language import Language from ...attrs import LANG from ...fr.language_data import TOKENIZER_EXCEPTIONS, STOP_WORDS from ...language_data.punctuation import TOKENIZER_INFIXES, ALPHA import pytest @pytest.fixture def fr_tokenizer_w_infix(): SPLIT_INFIX = r'(?<=[{a}]\')(?=[{a}])'.format(a=ALPHA) # create new Language subclass to add to default infixes class French(Language): lang = 'fr' class Defaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: 'fr' tokenizer_exceptions = TOKENIZER_EXCEPTIONS stop_words = STOP_WORDS infixes = TOKENIZER_INFIXES + [SPLIT_INFIX] return French.Defaults.create_tokenizer() @pytest.mark.parametrize('text,expected_tokens', [(""l'avion"", [""l'"", ""avion""]), (""j'ai"", [""j'"", ""ai""])]) def test_issue768(fr_tokenizer_w_infix, text, expected_tokens): """"""Allow zero-width 'infix' token during the tokenization process."""""" tokens = fr_tokenizer_w_infix(text) assert len(tokens) == 2 assert [t.text for t in tokens] == expected_tokens " Fix for dynamic values in csv exporter,"<?php use Garp\Functional as f; use League\Csv\Reader; use League\Csv\Writer; /** * Garp_Content_Export_Csv * Export content in simple comma-separated-values format * * @package Garp_Content_Export * @author Harmen Janssen <harmen@grrr.nl> */ class Garp_Content_Export_Csv extends Garp_Content_Export_Abstract { /** * File extension * * @var string */ protected $_extension = 'csv'; /** * Format a recordset * * @param Garp_Model $model * @param array $rowset * @return string */ public function format(Garp_Model $model, array $rowset): string { $rowset = f\map( f\publish('_flatten', $this), $rowset ); $writer = Writer::createFromString(''); $writer->setDelimiter(';'); $writer->insertOne(array_keys($rowset[0])); $writer->insertAll($rowset); $writer->setOutputBOM(Reader::BOM_UTF8); return strval($writer); } protected function _flatten(array $row): array { return f\map( function ($value) { return is_array($value) ? implode(', ', $this->_flatten($value)) : $value; }, $row ); } } ","<?php use Garp\Functional as f; use League\Csv\Reader; use League\Csv\Writer; /** * Garp_Content_Export_Csv * Export content in simple comma-separated-values format * * @package Garp_Content_Export * @author Harmen Janssen <harmen@grrr.nl> */ class Garp_Content_Export_Csv extends Garp_Content_Export_Abstract { /** * File extension * * @var string */ protected $_extension = 'csv'; /** * Format a recordset * * @param Garp_Model $model * @param array $rowset * @return string */ public function format(Garp_Model $model, array $rowset): string { $rowset = f\map( f\publish('_flatten', $this), $rowset ); $writer = Writer::createFromString(''); $writer->setDelimiter(';'); $writer->insertOne(array_keys($rowset[0])); $writer->insertAll($rowset); $writer->setOutputBOM(Reader::BOM_UTF8); return strval($writer); } protected function _flatten(array $row): array { return f\reduce_assoc( function ($row, $value, $key) { // In the case of related hasMany or hasAndBelongsToMany // rowsets... return f\prop_set( $key, is_array($value) ? implode(', ', $this->_flatten($value)) : $value, $row ); }, [], $row ); } } " Add language parameter to get all route,"<?php namespace Backend\Modules\ContentBlocks\Api; use Backend\Modules\ContentBlocks\Domain\ContentBlock\ContentBlock; use Backend\Modules\ContentBlocks\Domain\ContentBlock\ContentBlockRepository; use FOS\RestBundle\Controller\Annotations as Rest; use JMS\Serializer\SerializerInterface; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; final class ApiController { /** @var ContentBlockRepository */ private $blockRepository; /** @var SerializerInterface */ private $serializer; public function __construct(ContentBlockRepository $blockRepository, SerializerInterface $serializer) { $this->blockRepository = $blockRepository; $this->serializer = $serializer; } /** * @Rest\Get(""/content-blocks/{language}"") */ public function getContentblocksAction(string $language): JsonResponse { return JsonResponse::create( json_decode( $this->serializer->serialize($this->blockRepository->findBy(['locale' => $language]), 'json'), true ) ); } /** * @Rest\Get(""/content-blocks/{language}/{id}"") */ public function getContentblockAction(string $language, int $id): JsonResponse { $contentBlock = $this->blockRepository->findOneBy(['locale' => $language, 'id' => $id]); if (!$contentBlock instanceof ContentBlock) { throw new NotFoundHttpException(); } return JsonResponse::create( json_decode( $this->serializer->serialize($contentBlock, 'json'), true ) ); } } ","<?php namespace Backend\Modules\ContentBlocks\Api; use Backend\Modules\ContentBlocks\Domain\ContentBlock\ContentBlock; use Backend\Modules\ContentBlocks\Domain\ContentBlock\ContentBlockRepository; use FOS\RestBundle\Controller\Annotations as Rest; use JMS\Serializer\SerializerInterface; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; final class ApiController { /** @var ContentBlockRepository */ private $blockRepository; /** @var SerializerInterface */ private $serializer; public function __construct(ContentBlockRepository $blockRepository, SerializerInterface $serializer) { $this->blockRepository = $blockRepository; $this->serializer = $serializer; } /** * @Rest\Get(""/content-blocks"") */ public function getContentblocksAction(): JsonResponse { return JsonResponse::create( json_decode( $this->serializer->serialize($this->blockRepository->findAll(), 'json'), true ) ); } /** * @Rest\Get(""/content-blocks/{language}/{id}"") */ public function getContentblockAction(string $language, int $id): JsonResponse { $contentBlock = $this->blockRepository->findOneBy(['locale' => $language, 'id' => $id]); if (!$contentBlock instanceof ContentBlock) { throw new NotFoundHttpException(); } return JsonResponse::create( json_decode( $this->serializer->serialize($contentBlock, 'json'), true ) ); } } " Add Python 3.9 to classifiers list,"from setuptools import setup with open(""README.rst"") as readme_file: readme = readme_file.read() setup( name='pytest-describe', version='2.0.0', description='Describe-style plugin for pytest', long_description=readme, long_description_content_type='text/x-rst', url='https://github.com/pytest-dev/pytest-describe', author='Robin Pedersen', author_email='robinpeder@gmail.com', license='MIT license', install_requires=[ 'pytest>=4.0.0', ], entry_points={ 'pytest11': [ 'pytest-describe = pytest_describe.plugin', ], }, packages=['pytest_describe'], classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS :: MacOS X', 'Topic :: Software Development :: Testing', 'Topic :: Software Development :: Libraries', 'Topic :: Utilities', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', ], ) ","from setuptools import setup with open(""README.rst"") as readme_file: readme = readme_file.read() setup( name='pytest-describe', version='2.0.0', description='Describe-style plugin for pytest', long_description=readme, long_description_content_type='text/x-rst', url='https://github.com/pytest-dev/pytest-describe', author='Robin Pedersen', author_email='robinpeder@gmail.com', license='MIT license', install_requires=[ 'pytest>=4.0.0', ], entry_points={ 'pytest11': [ 'pytest-describe = pytest_describe.plugin' ], }, packages=['pytest_describe'], classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS :: MacOS X', 'Topic :: Software Development :: Testing', 'Topic :: Software Development :: Libraries', 'Topic :: Utilities', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], ) " Fix mapbox gl errors in production mode,"const webpack = require('webpack'); const path = require('path'); const common = require('./webpack-common'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const UglifyJSPlugin = require('uglifyjs-webpack-plugin'); const entry = common.getEntries(false); const config = { resolve: { alias: { '@boundlessgeo/sdk': path.resolve(__dirname, 'src/'), }, }, // Entry points to the project entry: entry, devtool: 'source-map', node: {fs: ""empty""}, output: { path: __dirname, // Path of output file // [name] refers to the entry point's name. filename: 'build/hosted/examples/[name]/[name].bundle.js', }, plugins: [ new ExtractTextPlugin('build/hosted/examples/sdk.css'), new UglifyJSPlugin({ sourceMap: true, uglifyOptions: { compress: { warnings: false, comparisons: false, // don't optimize comparisons }, }, }), ], module: { rules: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader', query: { cacheDirectory: true, }, }, { test: /\.s?css$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: ['css-loader', { loader: 'sass-loader', options: { includePaths: ['node_modules'], } }], }), } ], }, }; module.exports = config; ","const webpack = require('webpack'); const path = require('path'); const common = require('./webpack-common'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const UglifyJSPlugin = require('uglifyjs-webpack-plugin'); const entry = common.getEntries(false); const config = { resolve: { alias: { '@boundlessgeo/sdk': path.resolve(__dirname, 'src/'), }, }, // Entry points to the project entry: entry, devtool: 'source-map', node: {fs: ""empty""}, output: { path: __dirname, // Path of output file // [name] refers to the entry point's name. filename: 'build/hosted/examples/[name]/[name].bundle.js', }, plugins: [ new ExtractTextPlugin('build/hosted/examples/sdk.css'), new UglifyJSPlugin({sourceMap: true}) ], module: { rules: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader', query: { cacheDirectory: true, }, }, { test: /\.s?css$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: ['css-loader', { loader: 'sass-loader', options: { includePaths: ['node_modules'], } }], }), } ], }, }; module.exports = config; " Add domain name to event properties,"var config = {}; var doRequest = function(method, path, body, callback) { var xhr = new XMLHttpRequest(); xhr.open(method, config.host+""/api/""+path, true); xhr.setRequestHeader(""Content-type"",""application/json""); xhr.setRequestHeader(""Authorization"", ""Basic "" + btoa(config.username + "":"" + config.password)); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { callback(); } } xhr.send(body? JSON.stringify(body) : undefined); }; var start = function(data) { if (!data.host || !data.username || !data.password) { console.error(""Invalid settings"", data); return; } console.log(""New settings"", data); config = data; }; chrome.history.onVisited.addListener(function(item) { console.log(""Track visit "", item); var matches = item.url.match(/^https?\:\/\/([^\/:?#]+)(?:[\/:?#]|$)/i); var domain = matches && matches[1]; doRequest(""POST"", ""events"", { 'type': ""chrome.visit"", 'properties': { ""url"": item.url, ""title"": item.title, 'domain': domain } }); }); chrome.storage.onChanged.addListener(function(changes, namespace) { console.log(""Changes in settings"", changes); chrome.storage.sync.get(['host', 'username', 'password'], function(data) { start(data); }); }); chrome.storage.sync.get(['host', 'username', 'password'], function(data) { start(data) });","var config = {}; var doRequest = function(method, path, body, callback) { var xhr = new XMLHttpRequest(); xhr.open(method, config.host+""/api/""+path, true); xhr.setRequestHeader(""Content-type"",""application/json""); xhr.setRequestHeader(""Authorization"", ""Basic "" + btoa(config.username + "":"" + config.password)); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { callback(); } } xhr.send(body? JSON.stringify(body) : undefined); }; var start = function(data) { if (!data.host || !data.username || !data.password) { console.error(""Invalid settings"", data); return; } console.log(""New settings"", data); config = data; }; chrome.history.onVisited.addListener(function(item) { console.log(""Track visit "", item.url); doRequest(""POST"", ""events"", { 'type': ""chrome.visit"", 'properties': { ""url"": item.url, ""title"": item.title } }); }); chrome.storage.onChanged.addListener(function(changes, namespace) { console.log(""Changes in settings"", changes); chrome.storage.sync.get(['host', 'username', 'password'], function(data) { start(data); }); }); chrome.storage.sync.get(['host', 'username', 'password'], function(data) { start(data) });" "Make getContainer and getPackagesToScan public. 3rd party component finder strategies living in different packages can now use those functions.","package com.structurizr.componentfinder; import com.structurizr.model.Component; import com.structurizr.model.Container; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; public class ComponentFinder { private Container container; private String packageToScan; private List<ComponentFinderStrategy> componentFinderStrategies = new ArrayList<>(); public ComponentFinder(Container container, String packageToScan, ComponentFinderStrategy... componentFinderStrategies) { this.container = container; this.packageToScan = packageToScan; for (ComponentFinderStrategy componentFinderStrategy : componentFinderStrategies) { this.componentFinderStrategies.add(componentFinderStrategy); componentFinderStrategy.setComponentFinder(this); } } public Collection<Component> findComponents() throws Exception { Collection<Component> componentsFound = new LinkedList<>(); for (ComponentFinderStrategy componentFinderStrategy : componentFinderStrategies) { componentFinderStrategy.findComponents(); } for (ComponentFinderStrategy componentFinderStrategy : componentFinderStrategies) { componentFinderStrategy.findDependencies(); } for (ComponentFinderStrategy componentFinderStrategy : componentFinderStrategies) { componentsFound.addAll(componentFinderStrategy.getComponents()); } return componentsFound; } public Container getContainer() { return this.container; } public String getPackageToScan() { return packageToScan; } } ","package com.structurizr.componentfinder; import com.structurizr.model.Component; import com.structurizr.model.Container; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; public class ComponentFinder { private Container container; private String packageToScan; private List<ComponentFinderStrategy> componentFinderStrategies = new ArrayList<>(); public ComponentFinder(Container container, String packageToScan, ComponentFinderStrategy... componentFinderStrategies) { this.container = container; this.packageToScan = packageToScan; for (ComponentFinderStrategy componentFinderStrategy : componentFinderStrategies) { this.componentFinderStrategies.add(componentFinderStrategy); componentFinderStrategy.setComponentFinder(this); } } public Collection<Component> findComponents() throws Exception { Collection<Component> componentsFound = new LinkedList<>(); for (ComponentFinderStrategy componentFinderStrategy : componentFinderStrategies) { componentFinderStrategy.findComponents(); } for (ComponentFinderStrategy componentFinderStrategy : componentFinderStrategies) { componentFinderStrategy.findDependencies(); } for (ComponentFinderStrategy componentFinderStrategy : componentFinderStrategies) { componentsFound.addAll(componentFinderStrategy.getComponents()); } return componentsFound; } Container getContainer() { return this.container; } String getPackageToScan() { return packageToScan; } } " Add some comments for the vulcanize grunt task,"var path = require('path'); module.exports = function(grunt) { grunt.initConfig({ 'pkg': grunt.file.readJSON('package.json'), 'dtsGenerator': { options: { baseDir: './', name: 'core-components', out: './index.d.ts', excludes: [ 'typings/**', '!typings/lib.ext.d.ts', 'bower_components/**' ] }, default: { src: [ 'debug-configuration/debug-configuration.ts' ] } }, 'tsc': { options: { tscPath: path.resolve('node_modules', 'typescript', 'bin', 'tsc') }, default: {} }, 'tsd': { lib: { options: { command: 'reinstall', latest: true, config: 'conf/tsd-lib.json', opts: { // props from tsd.Options } } } }, 'vulcanize': { default: { options: { // extract all inline JavaScript into a separate file to work around Atom's // Content Security Policy csp: 'dependencies_bundle.js' }, files: { // output: input 'dependencies_bundle.html': 'dependencies.html' } } } }); grunt.loadNpmTasks('grunt-tsc'); grunt.loadNpmTasks('grunt-tsd'); grunt.loadNpmTasks('dts-generator'); grunt.loadNpmTasks('grunt-vulcanize'); grunt.registerTask('default', ['vulcanize']); }; ","var path = require('path'); module.exports = function(grunt) { grunt.initConfig({ 'pkg': grunt.file.readJSON('package.json'), 'dtsGenerator': { options: { baseDir: './', name: 'core-components', out: './index.d.ts', excludes: [ 'typings/**', '!typings/lib.ext.d.ts', 'bower_components/**' ] }, default: { src: [ 'debug-configuration/debug-configuration.ts' ] } }, 'tsc': { options: { tscPath: path.resolve('node_modules', 'typescript', 'bin', 'tsc') }, default: {} }, 'tsd': { lib: { options: { command: 'reinstall', latest: true, config: 'conf/tsd-lib.json', opts: { // props from tsd.Options } } } }, 'vulcanize': { default: { options: { csp: 'dependencies_bundle.js' }, files: { 'dependencies_bundle.html': 'dependencies.html' } } } }); grunt.loadNpmTasks('grunt-tsc'); grunt.loadNpmTasks('grunt-tsd'); grunt.loadNpmTasks('dts-generator'); grunt.loadNpmTasks('grunt-vulcanize'); grunt.registerTask('default', ['vulcanize']); }; " Fix syntax error in OptionList,"import PropTypes from ""prop-types""; import React, { Component } from ""react""; import { StyleSheet, ScrollView, View, TouchableWithoutFeedback, ViewPropTypes } from ""react-native""; export default class OptionList extends Component { static defaultProps = { onSelect: () => {} }; static propTypes = { style: ViewPropTypes.style, onSelect: PropTypes.func }; render() { const { style, children, onSelect, selectedStyle, selected } = this.props; const renderedItems = React.Children.map(children, (item, key) => { if (!item) return null return <TouchableWithoutFeedback key={key} style={{ borderWidth: 0 }} onPress={() => onSelect(item.props.children, item.props.value)} > <View style={[ { borderWidth: 0 }, item.props.value === selected ? selectedStyle : null ]} > {item} </View> </TouchableWithoutFeedback> }); return ( <View style={[styles.scrollView, style]}> <ScrollView automaticallyAdjustContentInsets={false} bounces={false}> {renderedItems} </ScrollView> </View> ); } } var styles = StyleSheet.create({ scrollView: { height: 120, width: 300, borderWidth: 1 } }); ","import PropTypes from ""prop-types""; import React, { Component } from ""react""; import { StyleSheet, ScrollView, View, TouchableWithoutFeedback, ViewPropTypes } from ""react-native""; export default class OptionList extends Component { static defaultProps = { onSelect: () => {} }; static propTypes = { style: ViewPropTypes.style, onSelect: PropTypes.func }; render() { const { style, children, onSelect, selectedStyle, selected } = this.props; const renderedItems = React.Children.map(children, (item, key) => ( if (!item) return null <TouchableWithoutFeedback key={key} style={{ borderWidth: 0 }} onPress={() => onSelect(item.props.children, item.props.value)} > <View style={[ { borderWidth: 0 }, item.props.value === selected ? selectedStyle : null ]} > {item} </View> </TouchableWithoutFeedback> )); return ( <View style={[styles.scrollView, style]}> <ScrollView automaticallyAdjustContentInsets={false} bounces={false}> {renderedItems} </ScrollView> </View> ); } } var styles = StyleSheet.create({ scrollView: { height: 120, width: 300, borderWidth: 1 } }); " Make sure request body stream is writable.,"<?php namespace Meng\Soap\HttpBinding; use Meng\Soap\Interpreter; use Psr\Http\Message\RequestInterface; use Zend\Diactoros\Stream; class HttpBinding { private $interpreter; private $builder; public function __construct(Interpreter $interpreter, RequestBuilder $builder) { $this->interpreter = $interpreter; $this->builder = $builder; } /** * @return RequestInterface */ public function toHttpRequest($name, array $arguments, array $options = null, $inputHeaders = null) { $soapRequest = $this->interpreter->request($name, $arguments, $options, $inputHeaders); if ($soapRequest->getSoapVersion() == '1') { $this->builder->isSOAP11(); } else { $this->builder->isSOAP12(); } $this->builder->setEndpoint($soapRequest->getEndpoint()); $this->builder->setSoapAction($soapRequest->getSoapAction()); $stream = fopen('php://temp', 'r+'); fwrite($stream, $soapRequest->getSoapMessage()); fseek($stream, 0); $this->builder->setSoapMessage(new Stream($stream)); return $this->builder->getSoapHttpRequest(); } /** * @return mixed */ public function fromHttpResponse($response, $name, &$output_headers = null) { return $this->interpreter->response($response, $name, $output_headers); } }","<?php namespace Meng\Soap\HttpBinding; use Meng\Soap\Interpreter; use Psr\Http\Message\RequestInterface; use Zend\Diactoros\Stream; class HttpBinding { private $interpreter; private $builder; public function __construct(Interpreter $interpreter, RequestBuilder $builder) { $this->interpreter = $interpreter; $this->builder = $builder; } /** * @return RequestInterface */ public function toHttpRequest($name, array $arguments, array $options = null, $inputHeaders = null) { $soapRequest = $this->interpreter->request($name, $arguments, $options, $inputHeaders); if ($soapRequest->getSoapVersion() == '1') { $this->builder->isSOAP11(); } else { $this->builder->isSOAP12(); } $this->builder->setEndpoint($soapRequest->getEndpoint()); $this->builder->setSoapAction($soapRequest->getSoapAction()); $stream = fopen('php://temp', 'r'); fwrite($stream, $soapRequest->getSoapMessage()); fseek($stream, 0); $this->builder->setSoapMessage(new Stream($stream)); return $this->builder->getSoapHttpRequest(); } /** * @return mixed */ public function fromHttpResponse($response, $name, &$output_headers = null) { return $this->interpreter->response($response, $name, $output_headers); } }" "Fix pickling/unpickling of Resource objects Add __getstate__ and __setstate__ methods to the Resource class to avoid hitting the recursion limit when trying to pickle/unpickle Resource objects. A similar issue/solution can be found here: https://stackoverflow.com/a/12102691","from groupy import utils class Manager: """"""Class for interacting with the endpoint for a resource. :param session: the requests session :type session: :class:`~groupy.session.Session` :param str path: path relative to the base URL """""" #: the base URL base_url = 'https://api.groupme.com/v3/' def __init__(self, session, path=None): self.session = session self.url = utils.urljoin(self.base_url, path) class Resource: def __init__(self, **data): self.data = data def __getattr__(self, attr): if attr not in self.data: error_message = 'this {!s} resource does not have a {!r} field' raise AttributeError(error_message.format(self.__class__.__name__, attr)) return self.data[attr] def __getstate__(self): return self.__dict__ def __setstate__(self, d): self.__dict__.update(d) class ManagedResource(Resource): """"""Class to represent an API object."""""" def __init__(self, manager, **data): """"""Create an instance of the resource. :param manager: the resource's manager :type manager: :class:`~groupy.api.base.Manager` :param kwargs data: the resource data """""" super().__init__(**data) self.manager = manager ","from groupy import utils class Manager: """"""Class for interacting with the endpoint for a resource. :param session: the requests session :type session: :class:`~groupy.session.Session` :param str path: path relative to the base URL """""" #: the base URL base_url = 'https://api.groupme.com/v3/' def __init__(self, session, path=None): self.session = session self.url = utils.urljoin(self.base_url, path) class Resource: def __init__(self, **data): self.data = data def __getattr__(self, attr): if attr not in self.data: error_message = 'this {!s} resource does not have a {!r} field' raise AttributeError(error_message.format(self.__class__.__name__, attr)) return self.data[attr] class ManagedResource(Resource): """"""Class to represent an API object."""""" def __init__(self, manager, **data): """"""Create an instance of the resource. :param manager: the resource's manager :type manager: :class:`~groupy.api.base.Manager` :param kwargs data: the resource data """""" super().__init__(**data) self.manager = manager " Update reverse string method names,"package com.growingwiththeweb.algorithms.interviewquestions.reversestring; public class Program { public static void main(String[] args) { assert reverseViaCharArray(""abc123def"").equals(""fed321cba""); assert reverseViaStringBuilderA(""abc123def"").equals(""fed321cba""); assert reverseViaStringBuilderB(""abc123def"").equals(""fed321cba""); assert reverseViaCharArray(""abcd1234"").equals(""4321dcba""); assert reverseViaStringBuilderA(""abcd1234"").equals(""4321dcba""); assert reverseViaStringBuilderB(""abcd1234"").equals(""4321dcba""); System.out.println(""Tests passed""); } public static String reverseViaCharArray(String text) { char[] charArray = text.toCharArray(); int start = -1; int end = charArray.length; while (++start < --end) { char temp = charArray[start]; charArray[start] = charArray[end]; charArray[end] = temp; } return String.valueOf(charArray); } public static String reverseViaStringBuilderA(String text) { StringBuilder sb = new StringBuilder(); for (int i = text.length() - 1; i >= 0; i--) { sb.append(text.charAt(i)); } return sb.toString(); } public static String reverseViaStringBuilderB(String text) { return new StringBuilder(text).reverse().toString(); } } ","package com.growingwiththeweb.algorithms.interviewquestions.reversestring; public class Program { public static void main(String[] args) { assert reverse1(""abc123def"").equals(""fed321cba""); assert reverse2(""abc123def"").equals(""fed321cba""); assert reverse3(""abc123def"").equals(""fed321cba""); assert reverse1(""abcd1234"").equals(""4321dcba""); assert reverse2(""abcd1234"").equals(""4321dcba""); assert reverse3(""abcd1234"").equals(""4321dcba""); System.out.println(""Tests passed""); } public static String reverse1(String text) { char[] charArray = text.toCharArray(); int start = -1; int end = charArray.length; while (++start < --end) { char temp = charArray[start]; charArray[start] = charArray[end]; charArray[end] = temp; } return String.valueOf(charArray); } public static String reverse2(String text) { StringBuilder sb = new StringBuilder(); for (int i = text.length() - 1; i >= 0; i--) { sb.append(text.charAt(i)); } return sb.toString(); } public static String reverse3(String text) { return new StringBuilder(text).reverse().toString(); } } " Fix mistake from last commits,"package com.crowdin.cli.utils.concurrency; import java.util.List; import java.util.Objects; import java.util.concurrent.*; public class ConcurrencyUtil { private static final int CROWDIN_API_MAX_CONCURRENT_REQUESTS = 4; private ConcurrencyUtil() { throw new UnsupportedOperationException(); } /** * Executes list of provided tasks in thread pool and waits until all tasks are finished * * @param tasks list of tasks to execute in parallel */ public static void executeAndWait(List<Runnable> tasks) { run(tasks, CROWDIN_API_MAX_CONCURRENT_REQUESTS, tasks.size() * 2); } public static void executeAndWaitSingleThread(List<Runnable> tasks) { run(tasks, 1, 100); } private static void run(List<Runnable> tasks, int threadQnt, int minutesWait) { if (Objects.isNull(tasks) || tasks.size() == 0) { return; } ExecutorService executor = CrowdinExecutorService.newFixedThreadPool(threadQnt); tasks.forEach(executor::submit); executor.shutdown(); try { if (!executor.awaitTermination(minutesWait, TimeUnit.MINUTES)) { executor.shutdownNow(); } } catch (InterruptedException ex) { executor.shutdownNow(); Thread.currentThread().interrupt(); } } } ","package com.crowdin.cli.utils.concurrency; import java.util.List; import java.util.Objects; import java.util.concurrent.*; public class ConcurrencyUtil { private static final int CROWDIN_API_MAX_CONCURRENT_REQUESTS = 1; private ConcurrencyUtil() { throw new UnsupportedOperationException(); } /** * Executes list of provided tasks in thread pool and waits until all tasks are finished * * @param tasks list of tasks to execute in parallel */ public static void executeAndWait(List<Runnable> tasks) { run(tasks, CROWDIN_API_MAX_CONCURRENT_REQUESTS, tasks.size() * 2); } public static void executeAndWaitSingleThread(List<Runnable> tasks) { run(tasks, 1, 100); } private static void run(List<Runnable> tasks, int threadQnt, int minutesWait) { if (Objects.isNull(tasks) || tasks.size() == 0) { return; } ExecutorService executor = CrowdinExecutorService.newFixedThreadPool(threadQnt); tasks.forEach(executor::submit); executor.shutdown(); try { if (!executor.awaitTermination(minutesWait, TimeUnit.MINUTES)) { executor.shutdownNow(); } } catch (InterruptedException ex) { executor.shutdownNow(); Thread.currentThread().interrupt(); } } } " Fix 'cannot get context of undefined' exception,"import AWS from 'aws-sdk'; module.exports = class Sessions { constructor() { this.SESSION_TABLE = `${process.env.SERVERLESS_PROJECT}-sessions-${process.env.SERVERLESS_STAGE}`; this.db = new AWS.DynamoDB.DocumentClient(); } read(id) { return new Promise((resolve, reject) => { const params = { Key: { id }, TableName: this.SESSION_TABLE, ConsistentRead: true }; this.db.get(params, (err, data) => { if (err) { console.error(err.toString()); return reject(err); } console.log('db read: ' + JSON.stringify(data)); if (data.Item !== undefined) { return resolve(data.Item.context); } else { // return an empty context for new sessions return resolve({}); } }); }); } write(id, context) { return new Promise((resolve, reject) => { if (!id) { return reject(new TypeError('No session ID')); } // coerce session id to string id = id + ''; const params = { TableName: this.SESSION_TABLE, Item: { id, context } }; console.log('db write: ' + JSON.stringify(context)); this.db.put(params, (err, data) => { if (err) { console.error(err.toString()); return reject(err); } return resolve(context); }); }); } } ","import AWS from 'aws-sdk'; module.exports = class Sessions { constructor() { this.SESSION_TABLE = `${process.env.SERVERLESS_PROJECT}-sessions-${process.env.SERVERLESS_STAGE}`; this.db = new AWS.DynamoDB.DocumentClient(); } read(id) { return new Promise((resolve, reject) => { const params = { Key: { id }, TableName: this.SESSION_TABLE, ConsistentRead: true }; this.db.get(params, (err, data) => { if (err) { console.error(err.toString()); return reject(err); } console.log('db read: ' + JSON.stringify(data)); return resolve(data.Item.context); }); }); } write(id, context) { return new Promise((resolve, reject) => { if (!id) { return reject(new TypeError('No session ID')); } // coerce session id to string id = id + ''; const params = { TableName: this.SESSION_TABLE, Item: { id, context } }; console.log('db write: ' + JSON.stringify(context)); this.db.put(params, (err, data) => { if (err) { console.error(err.toString()); return reject(err); } return resolve(context); }); }); } } " Create parent directories as needed.,"#!/usr/bin/env python3 from __future__ import print_function from argparse import ArgumentParser import errno import json import os from urllib.request import urlopen import subprocess import sys def main(): parser = ArgumentParser() parser.add_argument('downloads_file', metavar='downloads-file') args = parser.parse_args() with open(args.downloads_file) as downloads_file: downloads = json.load(downloads_file) for download in downloads: path = download['path'] if os.path.isfile(path): print('File already exists: {}'.format(path)) else: print('Downloading: {}'.format(path), end='') sys.stdout.flush() try: os.makedirs(os.path.dirname(download['path'])) except OSError as e: if e.errno != errno.EEXIST: raise with open(download['path'], 'wb') as target: with urlopen(download['url']) as source: while True: chunk = source.read(102400) if len(chunk) == 0: break target.write(chunk) print('.', end='', file=sys.stderr) sys.stderr.flush() print('') print('Verifying hash') hashsum = subprocess.check_output( ['sha256sum', path]).split(b' ', 1)[0] hashsum = hashsum.decode('ascii') expected = download['sha256'] print(' {}\n {}'.format(hashsum, expected)) if hashsum != expected: raise ValueError('Incorrect hash for {}'.format(path)) if __name__ == '__main__': main() ","#!/usr/bin/env python3 from __future__ import print_function from argparse import ArgumentParser import json import os from urllib.request import urlopen import subprocess import sys def main(): parser = ArgumentParser() parser.add_argument('downloads_file', metavar='downloads-file') args = parser.parse_args() with open(args.downloads_file) as downloads_file: downloads = json.load(downloads_file) for download in downloads: path = download['path'] if os.path.isfile(path): print('File already exists: {}'.format(path)) else: print('Downloading: {}'.format(path), end='') sys.stdout.flush() with open(download['path'], 'wb') as target: with urlopen(download['url']) as source: while True: chunk = source.read(102400) if len(chunk) == 0: break target.write(chunk) print('.', end='', file=sys.stderr) sys.stderr.flush() print('') print('Verifying hash') hashsum = subprocess.check_output( ['sha256sum', path]).split(b' ', 1)[0] hashsum = hashsum.decode('ascii') expected = download['sha256'] print(' {}\n {}'.format(hashsum, expected)) if hashsum != expected: raise ValueError('Incorrect hash for {}'.format(path)) if __name__ == '__main__': main() " Add several flex-related numerical properties to the ignore list,"var postcss = require('postcss'), extend = require('extend'); module.exports = postcss.plugin('postcss-default-unit', function (opts) { opts = opts || {}; opts.unit = opts.unit || 'px'; opts.ignore = extend({ 'column-count': true, 'fill-opacity': true, 'font-weight': true, 'line-height': true, 'opacity': true, 'orphans': true, 'widows': true, 'z-index': true, 'zoom': true, 'flex': true, 'order': true, 'flex-grow': true, 'flex-shrink': true }, opts.ignore); function transformDecl(decl) { if (!opts.ignore[decl.prop] && !/\w\(.*\)/.test(decl.value)) { decl.value = decl.value.replace(/\d+(\s|\/|$)/g, function(match){ return parseInt(match) === 0 ? match : match.replace(/\d+/, '$&' + opts.unit); }); } } function transformRule(rule) { if (rule.name === 'media') { rule.params = rule.params.replace(/(height|width|resolution)\s*:\s*\d+\)/g, function(match){ return match.replace(/\d+/, '$&' + opts.unit); }); } } function defaultUnit(style) { style.eachDecl(transformDecl); style.eachAtRule(transformRule); } return defaultUnit; }); ","var postcss = require('postcss'), extend = require('extend'); module.exports = postcss.plugin('postcss-default-unit', function (opts) { opts = opts || {}; opts.unit = opts.unit || 'px'; opts.ignore = extend({ 'column-count': true, 'fill-opacity': true, 'font-weight': true, 'line-height': true, 'opacity': true, 'orphans': true, 'widows': true, 'z-index': true, 'zoom': true }, opts.ignore); function transformDecl(decl) { if (!opts.ignore[decl.prop] && !/\w\(.*\)/.test(decl.value)) { decl.value = decl.value.replace(/\d+(\s|\/|$)/g, function(match){ return parseInt(match) === 0 ? match : match.replace(/\d+/, '$&' + opts.unit); }); } } function transformRule(rule) { if (rule.name === 'media') { rule.params = rule.params.replace(/(height|width|resolution)\s*:\s*\d+\)/g, function(match){ return match.replace(/\d+/, '$&' + opts.unit); }); } } function defaultUnit(style) { style.eachDecl(transformDecl); style.eachAtRule(transformRule); } return defaultUnit; }); " "Add the ability to use a custom driver, in feature manager","<?php namespace DataSift\Feature; use DataSift\Feature\Driver\DriverManager; use DataSift\Feature\Driver\Services\DriverInterface; /** * Class FeatureManager * * @package DataSift\Feature */ class FeatureManager { /** * @var DriverInterface */ protected $driver; /** * FeatureManager constructor. * * @param array|DriverInterface $driverConfig */ public function __construct($driverConfig) { if ($driverConfig instanceof DriverInterface) { $this->driver = $driverConfig; } else { $this->driver = DriverManager::loadDriver($driverConfig); } } /** * Is the feature flag enabled * * @param string|array $keys * @param mixed $default * * @return bool */ public function isEnabled($keys, $default = false) { if (! is_array($keys)) { $keys = array($keys); } foreach ($keys as $key) { $value = $this->driver->get($key, $default); if ((is_string($value) && ($value == '' || $value == 'false')) || $value != true) { return false; } } return true; } /** * Inverse function for the isEnabled method * * @param string|array $keys * @param bool $default * * @return bool */ public function isNotEnabled($keys, $default = false) { return ! $this->isEnabled($keys, $default); } } ","<?php namespace DataSift\Feature; use DataSift\Feature\Driver\DriverManager; use DataSift\Feature\Driver\Services\DriverInterface; /** * Class FeatureManager * * @package DataSift\Feature */ class FeatureManager { /** * @var DriverInterface */ protected $driver; /** * FeatureManager constructor. * * @param array $config */ public function __construct(array $config) { $this->driver = DriverManager::loadDriver($config); } /** * Is the feature flag enabled * * @param string|array $keys * @param mixed $default * * @return bool */ public function isEnabled($keys, $default = false) { if (! is_array($keys)) { $keys = array($keys); } foreach ($keys as $key) { $value = $this->driver->get($key, $default); if ((is_string($value) && ($value == '' || $value == 'false')) || $value != true) { return false; } } return true; } /** * Inverse function for the isEnabled method * * @param string|array $keys * @param bool $default * * @return bool */ public function isNotEnabled($keys, $default = false) { return ! $this->isEnabled($keys, $default); } } " Set larger test stream length,"var assert = require('assert') var charStream = require('../app.js') describe('random-character-stream', function() { function getBuffer(charGen, size) { var buffer = '' var i = 0 while (i++ < size) { buffer += charGen.next().value } return buffer } context('when instantiated with a seed', function() { var stream_1, stream_2 beforeEach(function() { var charGen_1 = charStream(123) var charGen_2 = charStream(123) stream_1 = getBuffer(charGen_1, 1000) stream_2 = getBuffer(charGen_2, 1000) }) it('always returns the same characters', function() { assert.equal(stream_1, stream_2) }) }) context('when instantiated with an allowed character set', function() { var stream beforeEach(function() { var charGen = charStream(123, [97, 98, 99]) stream = getBuffer(charGen, 1000) }) it('only returns characters from that set', function() { for (i in stream) { var character = stream[i] assert.ok(['a', 'b', 'c'].indexOf(character) !== -1) } }) }) }) ","var assert = require('assert') var charStream = require('../app.js') describe('random-character-stream', function() { function getBuffer(charGen, size) { var buffer = '' var i = 0 while (i++ < size) { buffer += charGen.next().value } return buffer } context('when instantiated with a seed', function() { var stream_1, stream_2 beforeEach(function() { var charGen_1 = charStream(123) var charGen_2 = charStream(123) stream_1 = getBuffer(charGen_1, 10) stream_2 = getBuffer(charGen_2, 10) }) it('always returns the same characters', function() { assert.equal(stream_1, stream_2) }) }) context('when instantiated with an allowed character set', function() { var stream beforeEach(function() { var charGen = charStream(123, [97, 98, 99]) stream = getBuffer(charGen, 100) }) it('only returns characters from that set', function() { for (i in stream) { var character = stream[i] assert.ok(['a', 'b', 'c'].indexOf(character) !== -1) } }) }) }) " Update bootstrap to match the changed group schema,"var Promise = require('bluebird'), mongoose = Promise.promisifyAll(require('mongoose')), Group = mongoose.model('Group'), async = require('async'), collection; module.exports = { 'bootstrap' : BootStrap }; collection = [ { users : [], name : 'Basic Group', about : 'This is a basic group created on server startup.' } ]; function BootStrap(mainCb,defaultAdmins,defaultGroups) { var currGroup; async.series(collection.map(function(grpObj) { return function(cb) { Group.findOne({'name' : grpObj.name}) .execAsync() .then(function(grpFound) { if(grpFound) { return; } grpObj.admins = defaultAdmins; grpObj.creator = defaultAdmins[0]; currGroup = new Group(grpObj); return currGroup.saveAsync(); }) .then(function(groupCreated) { if(groupCreated) { groupCreated = groupCreated[0]; defaultGroups.push(groupCreated._id); } }) .finally(function() { cb(); }) } }),function(err,results) { mainCb(); }); }","var Promise = require('bluebird'), mongoose = Promise.promisifyAll(require('mongoose')), Group = mongoose.model('Group'), async = require('async'), collection; module.exports = { 'bootstrap' : BootStrap }; collection = [ { users : [], name : 'Basic Group', about : 'This is a basic group created on server startup.', created : (new Date()).getTime() } ]; function BootStrap(mainCb,defaultAdmins,defaultGroups) { var currGroup; async.series(collection.map(function(grpObj) { return function(cb) { Group.findOne({'name' : grpObj.name}) .execAsync() .then(function(grpFound) { if(grpFound) { return; } grpObj.admins = defaultAdmins; currGroup = new Group(grpObj); return currGroup.saveAsync(); }) .then(function(groupCreated) { if(groupCreated) { groupCreated = groupCreated[0]; defaultGroups.push(groupCreated._id); } }) .finally(function() { cb(); }) } }),function(err,results) { mainCb(); }); }" Add eslint rules for spacing,"module.exports = { parser: ""@typescript-eslint/parser"", parserOptions: { ecmaVersion: 2020, sourceType: ""module"", ecmaFeatures: { jsx: true } }, settings: { react: { version: ""detect"" } }, extends: [ ""plugin:react/recommended"", ""plugin:react-hooks/recommended"", ""plugin:@typescript-eslint/recommended"", ], rules: { ""@typescript-eslint/array-type"": [ ""warn"", { ""default"": ""array"" } ], ""@typescript-eslint/semi"": [ ""warn"", ""always"" ], ""@typescript-eslint/no-inferrable-types"": 0, ""max-len"": [ ""warn"", { ""code"": 120 } ], ""no-trailing-spaces"": [ ""warn"", { ""skipBlankLines"": true } ], ""no-multiple-empty-lines"": [ ""warn"", { ""max"": 2 } ], ""quotes"": [ ""warn"", ""single"" ], ""jsx-quotes"": [ ""warn"", ""prefer-double"" ], ""object-curly-spacing"": [""warn"", ""always""], ""no-multi-spaces"": [""warn""] } }; ","module.exports = { parser: ""@typescript-eslint/parser"", parserOptions: { ecmaVersion: 2020, sourceType: ""module"", ecmaFeatures: { jsx: true } }, settings: { react: { version: ""detect"" } }, extends: [ ""plugin:react/recommended"", ""plugin:react-hooks/recommended"", ""plugin:@typescript-eslint/recommended"", ], rules: { ""@typescript-eslint/array-type"": [ ""warn"", { ""default"": ""array"" } ], ""@typescript-eslint/semi"": [ ""warn"", ""always"" ], ""@typescript-eslint/no-inferrable-types"": 0, ""max-len"": [ ""warn"", { ""code"": 120 } ], ""no-trailing-spaces"": [ ""warn"", { ""skipBlankLines"": true } ], ""no-multiple-empty-lines"": [ ""warn"", { ""max"": 2 } ], ""quotes"": [ ""warn"", ""single"" ], ""jsx-quotes"": [ ""warn"", ""prefer-double"" ] } }; " Save old and new saldo in transaction instead of amount," exports.up = (knex, Promise) => Promise.all([ knex.schema.createTable('users', table => { table.uuid('id') .primary() .defaultTo(knex.raw('uuid_generate_v4()')); table.string('username', 20) .unique(); table.string('password'); table.float('saldo') .defaultTo(0); }), knex.schema.createTable('transactionTypes', table => { table.increments('id') .primary(); table.string('typename'); }), knex.schema.createTable('transactions', table => { table.increments('id') .primary(); table.integer('typeId') .unsigned() .references('id') .inTable('transactionTypes') .onDelete('SET NULL'); table.uuid('userId') .references('id') .inTable('users') .onDelete('SET NULL'); table.timestamp('timestamp') .defaultTo(knex.raw('now()')); table.float('oldSaldo'); table.float('newSaldo'); table.string('comment'); }) ]); exports.down = (knex, Promise) => Promise.all([ knex.schema.dropTable('transactions'), knex.schema.dropTable('users'), knex.schema.dropTable('transactionTypes') ]); "," exports.up = (knex, Promise) => Promise.all([ knex.schema.createTable('users', table => { table.uuid('id') .primary() .defaultTo(knex.raw('uuid_generate_v4()')); table.string('username', 20) .unique(); table.string('password'); table.float('saldo') .defaultTo('0.0'); }), knex.schema.createTable('transactionTypes', table => { table.increments('id') .primary(); table.string('typename'); }), knex.schema.createTable('transactions', table => { table.increments('id') .primary(); table.integer('typeId') .unsigned() .references('id') .inTable('transactionTypes') .onDelete('SET NULL'); table.float('amount'); table.uuid('userId') .references('id') .inTable('users') .onDelete('SET NULL'); table.string('comment'); }) ]); exports.down = (knex, Promise) => Promise.all([ knex.schema.dropTable('transactions'), knex.schema.dropTable('users'), knex.schema.dropTable('transactionTypes') ]); " Replace local variable with class attribute,"import sys from django.utils import six # I know, it's ugly, but I just can't write: # gettattr(settings, 'CONTROLCENTER_CHARTIST_COLORS', 'default') # This is way better: app_settings.CHARTIST_COLORS # TODO: move to separate project def proxy(attr, default): def wrapper(self): # It has to be most recent, # to override settings in tests from django.conf import settings return getattr(settings, attr, default) # Do I need this? wrapper.__name__ = attr return property(wrapper) class AppSettingsMeta(type): def __new__(mcs, name, bases, attrs): prefix = name.upper() + '_' for attr, value in attrs.items(): if not attr.startswith('__'): attrs[attr] = proxy(prefix + attr, value) abstract = attrs.pop('__abstract__', False) cls = super(AppSettingsMeta, mcs).__new__(mcs, name, bases, attrs) if not abstract: # http://mail.python.org/pipermail/python-ideas/2012-May/ # 014969.html ins = cls() ins.__name__ = ins.__module__ sys.modules[ins.__module__] = ins return cls class AppSettings(six.with_metaclass(AppSettingsMeta)): __abstract__ = True class ControlCenter(AppSettings): DASHBOARDS = [] CHARTIST_COLORS = 'default' SHARP = '#' ","import sys from django.utils import six # I know, it's ugly, but I just can't write: # gettattr(settings, 'CONTROLCENTER_CHARTIST_COLORS', 'default') # This is way better: app_settings.CHARTIST_COLORS # TODO: move to separate project def proxy(attr, default): def wrapper(self): # It has to be most recent, # to override settings in tests from django.conf import settings return getattr(settings, attr, default) # Do I need this? wrapper.__name__ = attr return property(wrapper) class AppSettingsMeta(type): def __new__(mcs, name, bases, attrs): prefix = name.upper() + '_' for attr, value in attrs.items(): if not attr.startswith('__'): attrs[attr] = proxy(prefix + attr, value) abstract = attrs.pop('__abstract__', False) cls = super(AppSettingsMeta, mcs).__new__(mcs, name, bases, attrs) if not abstract: # http://mail.python.org/pipermail/python-ideas/2012-May/ # 014969.html ins = cls() ins.__name__ = __name__ sys.modules[__name__] = ins return cls class AppSettings(six.with_metaclass(AppSettingsMeta)): __abstract__ = True class ControlCenter(AppSettings): DASHBOARDS = [] CHARTIST_COLORS = 'default' SHARP = '#' " Save default config before starting,"package com.seventh_root.atherna; import com.seventh_root.atherna.character.AthernaCharacterManager; import com.seventh_root.atherna.command.CharacterCommand; import com.seventh_root.atherna.player.AthernaPlayerManager; import org.bukkit.plugin.java.JavaPlugin; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import static java.util.logging.Level.SEVERE; public class Atherna extends JavaPlugin { private Connection databaseConnection; private AthernaCharacterManager characterManager; private AthernaPlayerManager playerManager; @Override public void onEnable() { saveDefaultConfig(); try { databaseConnection = DriverManager.getConnection( ""jdbc:mysql://"" + getConfig().getString(""url"") + ""/"" + getConfig().getString(""database""), getConfig().getString(""username""), getConfig().getString(""password"") ); } catch (SQLException exception) { getLogger().log(SEVERE, ""Failed to connect to database"", exception); } characterManager = new AthernaCharacterManager(this); playerManager = new AthernaPlayerManager(this); getCommand(""character"").setExecutor(new CharacterCommand(this)); } public Connection getDatabaseConnection() { return databaseConnection; } public AthernaCharacterManager getCharacterManager() { return characterManager; } public AthernaPlayerManager getPlayerManager() { return playerManager; } } ","package com.seventh_root.atherna; import com.seventh_root.atherna.character.AthernaCharacterManager; import com.seventh_root.atherna.command.CharacterCommand; import com.seventh_root.atherna.player.AthernaPlayerManager; import org.bukkit.plugin.java.JavaPlugin; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import static java.util.logging.Level.SEVERE; public class Atherna extends JavaPlugin { private Connection databaseConnection; private AthernaCharacterManager characterManager; private AthernaPlayerManager playerManager; @Override public void onEnable() { try { databaseConnection = DriverManager.getConnection( ""jdbc:mysql://"" + getConfig().getString(""url"") + ""/"" + getConfig().getString(""database""), getConfig().getString(""username""), getConfig().getString(""password"") ); } catch (SQLException exception) { getLogger().log(SEVERE, ""Failed to connect to database"", exception); } characterManager = new AthernaCharacterManager(this); playerManager = new AthernaPlayerManager(this); getCommand(""character"").setExecutor(new CharacterCommand(this)); } public Connection getDatabaseConnection() { return databaseConnection; } public AthernaCharacterManager getCharacterManager() { return characterManager; } public AthernaPlayerManager getPlayerManager() { return playerManager; } } " Change success to then manually,"export default function LoadConfig($log, $rootScope, $http, Store) { return function() { var configSettings = {}; var configInit = function() { // Auto-resolving what used to be found when attempting to load local_setting.json if ($rootScope.loginConfig) { $rootScope.loginConfig.resolve('config loaded'); } $rootScope.$emit('ConfigReady'); // Load new hardcoded settings from above global.$AnsibleConfig = configSettings; Store('AnsibleConfig', global.$AnsibleConfig); $rootScope.$emit('LoadConfig'); }; // Retrieve the custom logo information - update configSettings from above $http({ method: 'GET', url: '/api/', }) .then(function({data}) { if({data}.custom_logo) { configSettings.custom_logo = true; $rootScope.custom_logo = {data}.custom_logo; } else { configSettings.custom_logo = false; } if({data}.custom_login_info) { configSettings.custom_login_info = {data}.custom_login_info; $rootScope.custom_login_info = {data}.custom_login_info; } else { configSettings.custom_login_info = false; } configInit(); }).catch(({error}) => { $log.debug(error); configInit(); }); }; } LoadConfig.$inject = [ '$log', '$rootScope', '$http', 'Store' ]; ","export default function LoadConfig($log, $rootScope, $http, Store) { return function() { var configSettings = {}; var configInit = function() { // Auto-resolving what used to be found when attempting to load local_setting.json if ($rootScope.loginConfig) { $rootScope.loginConfig.resolve('config loaded'); } $rootScope.$emit('ConfigReady'); // Load new hardcoded settings from above global.$AnsibleConfig = configSettings; Store('AnsibleConfig', global.$AnsibleConfig); $rootScope.$emit('LoadConfig'); }; // Retrieve the custom logo information - update configSettings from above $http({ method: 'GET', url: '/api/', }) .success(function(response) { if(response.custom_logo) { configSettings.custom_logo = true; $rootScope.custom_logo = response.custom_logo; } else { configSettings.custom_logo = false; } if(response.custom_login_info) { configSettings.custom_login_info = response.custom_login_info; $rootScope.custom_login_info = response.custom_login_info; } else { configSettings.custom_login_info = false; } configInit(); }).catch(({error}) => { $log.debug(error); configInit(); }); }; } LoadConfig.$inject = [ '$log', '$rootScope', '$http', 'Store' ]; " Update UMD Named define to true,"const webpack = require('webpack'); const helpers = require('./helpers'); module.exports = { entry: { 'index': './src/index.js', // 'test': './src/test.js' }, output: { path: helpers.root('dist'), filename: '[name].js', chunkFilename: '[id].chunk.js', libraryTarget: 'umd', library: 'Servable', umdNamedDefine: true, }, performance: { hints: false }, resolve: { extensions: ['*', '.js'], modules: [helpers.root('node_modules')], }, resolveLoader: { modules: [helpers.root('node_modules')] }, module: { loaders: [ { test: /\.js?$/, exclude: /(node_modules)/, use: { loader: 'babel-loader', options: { presets: [['es2015', {modules: false, loose: true}], 'stage-0'], } }, include: helpers.root('src') }, ] }, }; ","const webpack = require('webpack'); const helpers = require('./helpers'); module.exports = { entry: { 'index': './src/index.js', // 'test': './src/test.js' }, output: { path: helpers.root('dist'), filename: '[name].js', chunkFilename: '[id].chunk.js', libraryTarget: 'umd', library: 'Servable', }, performance: { hints: false }, resolve: { extensions: ['*', '.js'], modules: [helpers.root('node_modules')], }, resolveLoader: { modules: [helpers.root('node_modules')] }, module: { loaders: [ { test: /\.js?$/, exclude: /(node_modules)/, use: { loader: 'babel-loader', options: { presets: [['es2015', {modules: false, loose: true}], 'stage-0'], } }, include: helpers.root('src') }, ] }, }; " Add pushstate flags to booleans,"var minimist = require('minimist') var xtend = require('xtend') module.exports = parseArgs function parseArgs (args, opt) { var argv = minimist(args, { boolean: [ 'stream', 'debug', 'errorHandler', 'forceDefaultIndex', 'open', 'portfind', 'pushstate', 'ndjson', 'verbose', 'cors', 'ssl' ], string: [ 'host', 'port', 'dir', 'onupdate', 'serve', 'title', 'watchGlob', 'cert', 'key' ], default: module.exports.defaults, alias: { port: 'p', ssl: 'S', serve: 's', cert: 'C', key: 'K', verbose: 'v', help: 'h', host: 'H', dir: 'd', live: 'l', open: 'o', watchGlob: [ 'wg', 'watch-glob' ], errorHandler: 'error-handler', forceDefaultIndex: 'force-default-index', 'live-port': ['L', 'livePort'], pushstate: 'P' }, '--': true }) return xtend(argv, opt) } module.exports.defaults = { title: 'budo', port: 9966, debug: true, stream: true, errorHandler: true, portfind: true } ","var minimist = require('minimist') var xtend = require('xtend') module.exports = parseArgs function parseArgs (args, opt) { var argv = minimist(args, { boolean: [ 'stream', 'debug', 'errorHandler', 'forceDefaultIndex', 'open', 'portfind', 'ndjson', 'verbose', 'cors', 'ssl' ], string: [ 'host', 'port', 'dir', 'onupdate', 'serve', 'title', 'watchGlob', 'cert', 'key' ], default: module.exports.defaults, alias: { port: 'p', ssl: 'S', serve: 's', cert: 'C', key: 'K', verbose: 'v', help: 'h', host: 'H', dir: 'd', live: 'l', open: 'o', watchGlob: [ 'wg', 'watch-glob' ], errorHandler: 'error-handler', forceDefaultIndex: 'force-default-index', 'live-port': ['L', 'livePort'], pushstate: 'P' }, '--': true }) return xtend(argv, opt) } module.exports.defaults = { title: 'budo', port: 9966, debug: true, stream: true, errorHandler: true, portfind: true } " Fix fullname syntax to handle login with (at) signs,"from collections import namedtuple import os import re import shutil import yaml Credential = namedtuple(""Credential"", ""name login password comment"") class CredentialExistsError(Exception): pass class CredentialNotFoundError(Exception): pass def expandpath(path, name, login): return os.path.join(path, name, ""{}.pyssword"".format(login)) def content(credential): return yaml.dump(credential) def asdict(credential): return credential._asdict() def asstring(credential): return ""{} {} {}"".format( credential.name, credential.login, credential.comment ) def exists(path, name, login): return True if os.path.isfile(expandpath(path, name, login)) else False def clean(path, name, login): if exists(path, name, login): os.remove(expandpath(path, name, login)) credential_dir = os.path.dirname(expandpath(path, name, login)) if not os.listdir(credential_dir): shutil.rmtree(credential_dir) def splitname(fullname): rgx = re.compile(r""(?:(?P<login>.+?@?.+)?@)?(?P<name>.+)"") if rgx.match(fullname): name = rgx.match(fullname).group(""name"") login = rgx.match(fullname).group(""login"") return name, login else: raise ValueError(""Not a valid name"") def asfullname(name, login): return ""{}@{}"".format(login if login else """", name) ","from collections import namedtuple import os import re import shutil import yaml Credential = namedtuple(""Credential"", ""name login password comment"") class CredentialExistsError(Exception): pass class CredentialNotFoundError(Exception): pass def expandpath(path, name, login): return os.path.join(path, name, ""{}.pyssword"".format(login)) def content(credential): return yaml.dump(credential) def asdict(credential): return credential._asdict() def asstring(credential): return ""{} {} {}"".format( credential.name, credential.login, credential.comment ) def exists(path, name, login): return True if os.path.isfile(expandpath(path, name, login)) else False def clean(path, name, login): if exists(path, name, login): os.remove(expandpath(path, name, login)) credential_dir = os.path.dirname(expandpath(path, name, login)) if not os.listdir(credential_dir): shutil.rmtree(credential_dir) def splitname(fullname): rgx = re.compile(r""(?:(?P<login>.+)?@)?(?P<name>.+)"") if rgx.match(fullname): name = rgx.match(fullname).group(""name"") login = rgx.match(fullname).group(""login"") return name, login else: raise ValueError(""Not a valid name"") def asfullname(name, login): return ""{}@{}"".format(login if login else """", name) " Fix spotbugs warning about modifiable byte[].,"package nl.sikken.bertrik.hab.ttn; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.node.ObjectNode; /** * Representation of a message received from the TTN MQTT stream. */ @JsonIgnoreProperties(ignoreUnknown = true) public final class TtnMessage { @JsonProperty(""app_id"") private String appId; @JsonProperty(""dev_id"") private String devId; @JsonProperty(""hardware_serial"") private String hardwareSerial; @JsonProperty(""port"") private int port; @JsonProperty(""counter"") private int counter; @JsonProperty(""payload_raw"") private byte[] payloadRaw; @JsonProperty(""payload_fields"") private ObjectNode payloadFields; @JsonProperty(""metadata"") private TtnMessageMetaData metaData; public String getAppId() { return appId; } public String getDevId() { return devId; } public String getHardwareSerial() { return hardwareSerial; } public int getPort() { return port; } public int getCounter() { return counter; } public byte[] getPayloadRaw() { return payloadRaw.clone(); } public ObjectNode getPayloadFields() { return payloadFields; } public TtnMessageMetaData getMetaData() { return metaData; } } ","package nl.sikken.bertrik.hab.ttn; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.node.ObjectNode; /** * Representation of a message received from the TTN MQTT stream. */ @JsonIgnoreProperties(ignoreUnknown = true) public final class TtnMessage { @JsonProperty(""app_id"") private String appId; @JsonProperty(""dev_id"") private String devId; @JsonProperty(""hardware_serial"") private String hardwareSerial; @JsonProperty(""port"") private int port; @JsonProperty(""counter"") private int counter; @JsonProperty(""payload_raw"") private byte[] payloadRaw; @JsonProperty(""payload_fields"") private ObjectNode payloadFields; @JsonProperty(""metadata"") private TtnMessageMetaData metaData; public String getAppId() { return appId; } public String getDevId() { return devId; } public String getHardwareSerial() { return hardwareSerial; } public int getPort() { return port; } public int getCounter() { return counter; } public byte[] getPayloadRaw() { return payloadRaw; } public ObjectNode getPayloadFields() { return payloadFields; } public TtnMessageMetaData getMetaData() { return metaData; } } " Make empty tag form valid,"from django.utils.translation import ugettext_lazy as _ from django import forms from django.contrib.admin.widgets import ForeignKeyRawIdWidget from taggit.forms import TagField from taggit.utils import edit_string_for_tags from .widgets import TagAutocompleteWidget class TagObjectForm(forms.Form): def __init__(self, *args, **kwargs): tags = kwargs.pop('tags', []) if tags: kwargs['initial'] = {'tags': edit_string_for_tags(tags)} autocomplete_url = kwargs.pop('autocomplete_url', None) if autocomplete_url is not None: self.tags_autocomplete_url = autocomplete_url super(TagObjectForm, self).__init__(*args, **kwargs) self.fields['tags'] = TagField( label=_(""Tags""), widget=TagAutocompleteWidget( attrs={'placeholder': _('Tags')}, autocomplete_url=self.tags_autocomplete_url ), required=False, help_text=_(""Comma separated and quoted"") ) def save(self, obj): obj.tags.set(*self.cleaned_data['tags']) obj.save() def get_fk_form_class(model, field, admin_site, queryset=None): remote_field = model._meta.get_field(field).remote_field if queryset is None: queryset = remote_field.model.objects.all() widget = ForeignKeyRawIdWidget(remote_field, admin_site) class ForeignKeyForm(forms.Form): obj = forms.ModelChoiceField(queryset=queryset, widget=widget) return ForeignKeyForm ","from django.utils.translation import ugettext_lazy as _ from django import forms from django.contrib.admin.widgets import ForeignKeyRawIdWidget from taggit.forms import TagField from taggit.utils import edit_string_for_tags from .widgets import TagAutocompleteWidget class TagObjectForm(forms.Form): def __init__(self, *args, **kwargs): tags = kwargs.pop('tags', []) if tags: kwargs['initial'] = {'tags': edit_string_for_tags(tags)} autocomplete_url = kwargs.pop('autocomplete_url', None) if autocomplete_url is not None: self.tags_autocomplete_url = autocomplete_url super(TagObjectForm, self).__init__(*args, **kwargs) self.fields['tags'] = TagField( label=_(""Tags""), widget=TagAutocompleteWidget( attrs={'placeholder': _('Tags')}, autocomplete_url=self.tags_autocomplete_url ), help_text=_(""Comma separated and quoted"") ) def save(self, obj): obj.tags.set(*self.cleaned_data['tags']) obj.save() def get_fk_form_class(model, field, admin_site, queryset=None): remote_field = model._meta.get_field(field).remote_field if queryset is None: queryset = remote_field.model.objects.all() widget = ForeignKeyRawIdWidget(remote_field, admin_site) class ForeignKeyForm(forms.Form): obj = forms.ModelChoiceField(queryset=queryset, widget=widget) return ForeignKeyForm " Set zip_safe=False to make TW2 happy,"from setuptools import setup, find_packages import os version = '0.6.3' here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.txt')).read() CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read() except IOError: README = CHANGES = '' setup(name='tgext.admin', version=version, description=""Admin Controller add-on for basic TG identity model."", long_description=README + ""\n"" + CHANGES, # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=[ ""Programming Language :: Python"", ""Topic :: Software Development :: Libraries :: Python Modules"", ], keywords='turbogears2.extension, TG2, TG, sprox, Rest, internet, admin', author='Christopher Perkins', author_email='chris@percious.com', url='https://github.com/TurboGears/tgext.admin', license='MIT', packages=find_packages(exclude=['ez_setup']), namespace_packages=['tgext'], include_package_data=True, zip_safe=False, install_requires=[ 'setuptools', 'tgext.crud>=0.7.1', # -*- Extra requirements: -*- ], entry_points="""""" # -*- Entry points: -*- """""", ) ","from setuptools import setup, find_packages import os version = '0.6.3' here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.txt')).read() CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read() except IOError: README = CHANGES = '' setup(name='tgext.admin', version=version, description=""Admin Controller add-on for basic TG identity model."", long_description=README + ""\n"" + CHANGES, # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=[ ""Programming Language :: Python"", ""Topic :: Software Development :: Libraries :: Python Modules"", ], keywords='turbogears2.extension, TG2, TG, sprox, Rest, internet, admin', author='Christopher Perkins', author_email='chris@percious.com', url='https://github.com/TurboGears/tgext.admin', license='MIT', packages=find_packages(exclude=['ez_setup']), namespace_packages=['tgext'], include_package_data=True, zip_safe=True, install_requires=[ 'setuptools', 'tgext.crud>=0.7.1', # -*- Extra requirements: -*- ], entry_points="""""" # -*- Entry points: -*- """""", ) " Work around when fqdn is not defined for a node.,"from chef import Search from chef.api import ChefAPI, autoconfigure from chef.exceptions import ChefError class Roledef(object): def __init__(self, name, api, hostname_attr): self.name = name self.api = api self.hostname_attr = hostname_attr def __call__(self): for row in Search('node', 'roles:'+self.name, api=self.api): fqdn = """" if row.object.attributes.has_dotted(self.hostname_attr): fqdn = row.object.attributes.get_dotted(self.hostname_attr) else if row.object.attributes.has_dotted(""ec2.hostname""): fqdn = row.object.attributes.get_dotted(""ec2.hostname"") yield fqdn def chef_roledefs(api=None, hostname_attr = 'fqdn'): """"""Build a Fabric roledef dictionary from a Chef server. Example: from fabric.api import env, run, roles from chef.fabric import chef_roledefs env.roledefs = chef_roledefs() @roles('web_app') def mytask(): run('uptime') hostname_attr is the attribute in the chef node that holds the real hostname. to refer to a nested attribute, separate the levels with '.'. for example 'ec2.public_hostname' """""" api = api or ChefAPI.get_global() or autoconfigure() if not api: raise ChefError('Unable to load Chef API configuration') roledefs = {} for row in Search('role', api=api): name = row['name'] roledefs[name] = Roledef(name, api, hostname_attr) return roledefs ","from chef import Search from chef.api import ChefAPI, autoconfigure from chef.exceptions import ChefError class Roledef(object): def __init__(self, name, api, hostname_attr): self.name = name self.api = api self.hostname_attr = hostname_attr def __call__(self): for row in Search('node', 'roles:'+self.name, api=self.api): yield row.object.attributes.get_dotted(self.hostname_attr) def chef_roledefs(api=None, hostname_attr = 'fqdn'): """"""Build a Fabric roledef dictionary from a Chef server. Example: from fabric.api import env, run, roles from chef.fabric import chef_roledefs env.roledefs = chef_roledefs() @roles('web_app') def mytask(): run('uptime') hostname_attr is the attribute in the chef node that holds the real hostname. to refer to a nested attribute, separate the levels with '.'. for example 'ec2.public_hostname' """""" api = api or ChefAPI.get_global() or autoconfigure() if not api: raise ChefError('Unable to load Chef API configuration') roledefs = {} for row in Search('role', api=api): name = row['name'] roledefs[name] = Roledef(name, api, hostname_attr) return roledefs " Make links go to internal page,"var maxLength = 20; var pendingRequest = undefined; function updateResults() { var query = $(""#query"").val(); if (pendingRequest) { pendingRequest.abort(); } pendingRequest = $.getJSON( ""/search"", {query: query}, function processQueryResult(data) { $(""#results"").html(""""); for (var x=0; x<data.length; x++) { var post = data[x]; showImage(x, post); if (x >= maxLength) { showImage(x, { title: ""Refine your search for more results"" }); break; } } $('img.result-img').lazyload({ effect: ""fadeIn"", threshold: 1000, skip_invisible: true }); } ); } function showImage(x, postData) { var postHTML = '<div id=""post' + x + '"" class=""result"">'; postHTML += '<h2>'; if (postData.url) postHTML += '<a href=""' + postData.internalURL + '"">'; postHTML += postData.title; if (postData.url) postHTML += '</a></h2>'; if (postData.image) postHTML += '<img data-original=""' + postData.image + '"" class=""result-img"" /><br />'; if (postData.likes) postHTML += postData.likes + ' likes'; postHTML += '</div>'; $(""#results"").append(postHTML); } $(""#query"").on('input', updateResults); $(function() { updateResults(); }); ","var maxLength = 20; var pendingRequest = undefined; function updateResults() { var query = $(""#query"").val(); if (pendingRequest) { pendingRequest.abort(); } pendingRequest = $.getJSON( ""/search"", {query: query}, function processQueryResult(data) { $(""#results"").html(""""); for (var x=0; x<data.length; x++) { var post = data[x]; showImage(x, post); if (x >= maxLength) { showImage(x, { title: ""Refine your search for more results"" }); break; } } $('img.result-img').lazyload({ effect: ""fadeIn"", threshold: 1000, skip_invisible: true }); } ); } function showImage(x, postData) { var postHTML = '<div id=""post' + x + '"" class=""result"">'; postHTML += '<h2>'; if (postData.url) postHTML += '<a href=""' + postData.url + '"">'; postHTML += postData.title; if (postData.url) postHTML += '</a></h2>'; if (postData.image) postHTML += '<img data-original=""' + postData.image + '"" class=""result-img"" /><br />'; if (postData.likes) postHTML += postData.likes + ' likes'; postHTML += '</div>'; $(""#results"").append(postHTML); } $(""#query"").on('input', updateResults); $(function() { updateResults(); }); " "Change the intercept and coefficients to be floats, not unicode","from sklearn.linear_model import LinearRegression from bs4 import BeautifulSoup import numpy def from_pmml(self, pmml): """"""Returns a model with the intercept and coefficients represented in PMML file."""""" model = self() # Reads the input PMML file with BeautifulSoup. with open(pmml, ""r"") as f: lm_soup = BeautifulSoup(f, ""xml"") if not lm_soup.RegressionTable: raise ValueError(""RegressionTable not found in the input PMML file."") else: ##### DO I WANT TO PULL THIS OUT AS ITS OWN FUNCTION? ##### # Pulls out intercept from the PMML file and assigns it to the # model. If the intercept does not exist, assign it to zero. intercept = 0 if ""intercept"" in lm_soup.RegressionTable.attrs: intercept = lm_soup.RegressionTable['intercept'] model.intercept_ = float(intercept) # Pulls out coefficients from the PMML file, and assigns them # to the model. if not lm_soup.find_all('NumericPredictor'): raise ValueError(""NumericPredictor not found in the input PMML file."") else: coefs = [] numeric_predictors = lm_soup.find_all('NumericPredictor') for i in numeric_predictors: i_coef = float(i['coefficient']) coefs.append(i_coef) model.coef_ = numpy.array(coefs) return model # TODO: check input data's X order and rearrange the array LinearRegression.from_pmml = classmethod(from_pmml) ","from sklearn.linear_model import LinearRegression from bs4 import BeautifulSoup import numpy def from_pmml(self, pmml): """"""Returns a model with the intercept and coefficients represented in PMML file."""""" model = self() # Reads the input PMML file with BeautifulSoup. with open(pmml, ""r"") as f: lm_soup = BeautifulSoup(f, ""xml"") if not lm_soup.RegressionTable: raise ValueError(""RegressionTable not found in the input PMML file."") else: ##### DO I WANT TO PULL THIS OUT AS ITS OWN FUNCTION? ##### # Pulls out intercept from the PMML file and assigns it to the # model. If the intercept does not exist, assign it to zero. intercept = 0 if ""intercept"" in lm_soup.RegressionTable.attrs: intercept = lm_soup.RegressionTable['intercept'] model.intercept_ = intercept # Pulls out coefficients from the PMML file, and assigns them # to the model. if not lm_soup.find_all('NumericPredictor'): raise ValueError(""NumericPredictor not found in the input PMML file."") else: coefs = [] numeric_predictors = lm_soup.find_all('NumericPredictor') for i in numeric_predictors: coefs.append(i['coefficient']) model.coef_ = numpy.array(coefs) return model # TODO: check input data's X order and rearrange the array LinearRegression.from_pmml = classmethod(from_pmml) " Move package registering to boot(),"<?php namespace Barryvdh\Debugbar; class ServiceProvider extends \Illuminate\Support\ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('barryvdh/laravel-debugbar'); if($this->app['config']->get('laravel-debugbar::config.enabled')){ /** @var LaravelDebugbar $debugbar */ $debugbar = $this->app['debugbar']; $debugbar->boot(); } } /** * Register the service provider. * * @return void */ public function register() { $self = $this; $this->app['debugbar'] = $this->app->share(function ($app) use($self) { $debugbar = new LaravelDebugBar($app); $sessionManager = $app['session']; $httpDriver = new SymfonyHttpDriver($sessionManager); $debugbar->setHttpDriver($httpDriver); return $debugbar; }); $this->app['command.debugbar.publish'] = $this->app->share(function($app) { return new Console\PublishCommand($app['asset.publisher']); }); $this->commands('command.debugbar.publish'); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('debugbar', 'command.debugbar.publish'); } } ","<?php namespace Barryvdh\Debugbar; class ServiceProvider extends \Illuminate\Support\ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { if($this->app['config']->get('laravel-debugbar::config.enabled')){ /** @var LaravelDebugbar $debugbar */ $debugbar = $this->app['debugbar']; $debugbar->boot(); } } /** * Register the service provider. * * @return void */ public function register() { $this->package('barryvdh/laravel-debugbar'); $self = $this; $this->app['debugbar'] = $this->app->share(function ($app) use($self) { $debugbar = new LaravelDebugBar($app); $sessionManager = $app['session']; $httpDriver = new SymfonyHttpDriver($sessionManager); $debugbar->setHttpDriver($httpDriver); return $debugbar; }); $this->app['command.debugbar.publish'] = $this->app->share(function($app) { return new Console\PublishCommand($app['asset.publisher']); }); $this->commands('command.debugbar.publish'); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('debugbar', 'command.debugbar.publish'); } } " Use CLOSED instead of CLOSE.,"/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import org.jsmpp.bean.BindType; import org.jsmpp.extra.SessionState; /** * Context defined session life cycle.<br/> * OPEN -> BOUND_TX | BOUND_RX | BOUND_TRX -> UNBOUND -> CLOSED. * * @author uudashr * */ public interface SessionContext extends ActivityNotifier { /** * Change state to open. */ void open(); /** * Change state to bound state. * @param bindType */ void bound(BindType bindType); /** * Change state to unbound. */ void unbound(); /** * Change state to close. */ void close(); /** * Get current session state. * * @return the current session state. */ SessionState getSessionState(); /** * Get the last activity of a session. * * @return the last activity timestamp. */ long getLastActivityTimestamp(); }","/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import org.jsmpp.bean.BindType; import org.jsmpp.extra.SessionState; /** * Context defined session life cycle.<br/> * OPEN -> BOUND_TX | BOUND_RX | BOUND_TRX -> UNBOUND -> CLOSE. * * @author uudashr * */ public interface SessionContext extends ActivityNotifier { /** * Change state to open. */ void open(); /** * Change state to bound state. * @param bindType */ void bound(BindType bindType); /** * Change state to unbound. */ void unbound(); /** * Change state to close. */ void close(); /** * Get current session state. * * @return the current session state. */ SessionState getSessionState(); /** * Get the last activity of a session. * * @return the last activity timestamp. */ long getLastActivityTimestamp(); }" Test for spaces removal from quarkus.container-image.group when it's set to the username,"package io.quarkus.container.image.deployment; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Optional; import org.junit.jupiter.api.Test; class ContainerImageConfigEffectiveGroupTest { public static final String USER_NAME_SYSTEM_PROPERTY = ""user.name""; private ContainerImageConfig sut = new ContainerImageConfig(); @Test void testFromLowercaseUsername() { testWithNewUsername(""test"", () -> { sut.group = Optional.of(System.getProperty(USER_NAME_SYSTEM_PROPERTY)); assertEquals(sut.getEffectiveGroup(), Optional.of(""test"")); }); } @Test void testFromUppercaseUsername() { testWithNewUsername(""TEST"", () -> { sut.group = Optional.of(System.getProperty(USER_NAME_SYSTEM_PROPERTY)); assertEquals(sut.getEffectiveGroup(), Optional.of(""test"")); }); } @Test void testFromSpaceInUsername() { testWithNewUsername(""user name"", () -> { sut.group = Optional.of(System.getProperty(USER_NAME_SYSTEM_PROPERTY)); assertEquals(sut.getEffectiveGroup(), Optional.of(""user-name"")); }); } @Test void testFromOther() { testWithNewUsername(""WhateveR"", () -> { sut.group = Optional.of(""OtheR""); assertEquals(sut.getEffectiveGroup(), Optional.of(""OtheR"")); }); } private void testWithNewUsername(String newUserName, Runnable test) { String previousUsernameValue = System.getProperty(USER_NAME_SYSTEM_PROPERTY); System.setProperty(USER_NAME_SYSTEM_PROPERTY, newUserName); test.run(); System.setProperty(USER_NAME_SYSTEM_PROPERTY, previousUsernameValue); } } ","package io.quarkus.container.image.deployment; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Optional; import org.junit.jupiter.api.Test; class ContainerImageConfigEffectiveGroupTest { public static final String USER_NAME_SYSTEM_PROPERTY = ""user.name""; private ContainerImageConfig sut = new ContainerImageConfig(); @Test void testFromLowercaseUsername() { testWithNewUsername(""test"", () -> { sut.group = Optional.of(System.getProperty(USER_NAME_SYSTEM_PROPERTY)); assertEquals(sut.getEffectiveGroup(), Optional.of(""test"")); }); } @Test void testFromUppercaseUsername() { testWithNewUsername(""TEST"", () -> { sut.group = Optional.of(System.getProperty(USER_NAME_SYSTEM_PROPERTY)); assertEquals(sut.getEffectiveGroup(), Optional.of(""test"")); }); } @Test void testFromOther() { testWithNewUsername(""WhateveR"", () -> { sut.group = Optional.of(""OtheR""); assertEquals(sut.getEffectiveGroup(), Optional.of(""OtheR"")); }); } private void testWithNewUsername(String newUserName, Runnable test) { String previousUsernameValue = System.getProperty(USER_NAME_SYSTEM_PROPERTY); System.setProperty(USER_NAME_SYSTEM_PROPERTY, newUserName); test.run(); System.setProperty(USER_NAME_SYSTEM_PROPERTY, previousUsernameValue); } } " Add tests for View Command,"package guitests; import static org.junit.Assert.assertEquals; import java.util.Set; import org.junit.Test; import javafx.scene.Node; import javafx.scene.control.TitledPane; import seedu.address.logic.commands.ViewCommand; public class ViewCommandTest extends TaskManagerGuiTest { protected final String TASK_LIST_FXML_ID = ""#taskListView""; @Test public void viewDefault() { assertGroupsDisplay(""All""); } @Test public void viewCalendar() { commandBox.runCommand(""view calendar""); assertGroupsDisplay(""Floating"", ""Overdue"", ""Today"", ""Tomorrow"", ""Future""); assertResultMessage(String.format(ViewCommand.MESSAGE_SUCCESS, ""Calendar"")); } @Test public void viewGroups() { commandBox.runCommand(""view done today tomorrow""); assertGroupsDisplay(""Done"", ""Today"", ""Tomorrow""); assertResultMessage(String.format(ViewCommand.MESSAGE_SUCCESS, ""Done|Today|Tomorrow"")); } @Test public void viewWrongInput() { commandBox.runCommand(""view randomstring""); assertGroupsDisplay(""All""); assertResultMessage(ViewCommand.MESSAGE_ERROR); } protected void assertGroupsDisplay(String... groupTitles) { Node taskListView = mainGui.getNodeWithID(TASK_LIST_FXML_ID); Set<Node> taskGroupNodes = taskListView.lookupAll(""#titledPane""); int index = 0; for (Node node : taskGroupNodes) { TitledPane titledPane = (TitledPane) node; // Title consists of title + no. of entries // e.g. Tomorrow (4) String title = titledPane.getText().split("" "")[0]; assertEquals(title, groupTitles[index]); index++; } } } ","package guitests; import static org.junit.Assert.assertEquals; import java.util.Set; import org.junit.Test; import javafx.scene.Node; import javafx.scene.control.TitledPane; public class ViewCommandTest extends TaskManagerGuiTest { protected final String TASK_LIST_FXML_ID = ""#taskListView""; @Test public void viewDefault() { assertGroupsDisplay(""All""); } @Test public void viewCalendar() { commandBox.runCommand(""view calendar""); assertGroupsDisplay(""Floating"", ""Overdue"", ""Today"", ""Tomorrow"", ""Future""); } @Test public void viewGroups() { commandBox.runCommand(""view done today tomorrow""); assertGroupsDisplay(""Done"", ""Today"", ""Tomorrow""); } protected void assertGroupsDisplay(String... groupTitles) { Node taskListView = mainGui.getNodeWithID(TASK_LIST_FXML_ID); Set<Node> taskGroupNodes = taskListView.lookupAll(""#titledPane""); int index = 0; for (Node node : taskGroupNodes) { TitledPane titledPane = (TitledPane) node; // Title consists of title + no. of entries // e.g. Tomorrow (4) String title = titledPane.getText().split("" "")[0]; assertEquals(title, groupTitles[index]); index++; } } } " Prepare entry function for multiple function forks.,"module.exports = function (context, req) { var https = require('https'); var input = JSON.stringify(req.body); var userquery = input.split('&')[8].split('=')[1]; var callback = input.split('&')[9].split('=')[1]; var username = input.split('&')[6].split('=')[1]; context.log('Input was %s',userquery); if ((userquery.length == 3 || userquery.length == 4) && userquery.match('/^[a-zA-Z]+$')) { context.bindings.response = `Hello ${username}, I am getting your weather for ${userquery}, try again if you have not heard back in 20s.`; function getMetar(icaocode) { context.log(`https://dogithub.azurewebsites.net/api/metarSlackbot?icao=${icaocode}&callback=${callback}`); https.get(`https://dogithub.azurewebsites.net/api/metarSlackbot?icao=${icaocode}&callback=${callback}`, function (res) { var body = ''; // Will contain the final response // Received data is a buffer. // Adding it to our body res.on('data', function (data) { body += data; }); // After the response is completed, parse it and log it to the console res.on('end', function () { var parsed = JSON.parse(body); context.log(parsed); }); }) // If any error has occured, log error to console .on('error', function (e) { context.log(""Got error: "" + e.message); }); } getMetar(userquery); context.done(); }; };","module.exports = function (context, req) { var https = require('https'); var input = JSON.stringify(req.body); var icao = input.split('&')[8].split('=')[1]; var callback = input.split('&')[9].split('=')[1]; var username = input.split('&')[6].split('=')[1]; context.log('Input was %s',icao); context.bindings.response = `Hello ${username}, I am getting your weather for ${icao}, try again if you have not heard back in 20s.`; function getMetar(icaocode) { context.log(`https://dogithub.azurewebsites.net/api/metarSlackbot?icao=${icaocode}&callback=${callback}`); https.get(`https://dogithub.azurewebsites.net/api/metarSlackbot?icao=${icaocode}&callback=${callback}`, function (res) { var body = ''; // Will contain the final response // Received data is a buffer. // Adding it to our body res.on('data', function (data) { body += data; }); // After the response is completed, parse it and log it to the console res.on('end', function () { var parsed = JSON.parse(body); context.log(parsed); }); }) // If any error has occured, log error to console .on('error', function (e) { context.log(""Got error: "" + e.message); }); } getMetar(icao); context.done(); };" Comment out AJAX data calls,"$(document).on(""ready"", function() { $(""#post"").on(""click"", function(event){ event.preventDefault(); $.ajax({ url : $(event.target).attr('href'), }).done(function(response){ $("".comment-form"").show(); }).fail(function(response){ alert(""You are unable to post a comment.""); }); }); // $(""a"").click("".snowflake"", function(event){ // event.preventDefault(); // event.stopPropagation(); // debugger // // var target = $(event.target).parent().find(""#vote_count"") // $.ajax({ // type: ""POST"", // url : $(this).attr('href'), // dataType: ""json"", // }).done(function(response){ // debugger // alert(""Success!"") // }).fail(function(response){ // console.log(response); // }); // }); // $('.comment-form').on(""submit"", 'form', function(event){ // event.preventDefault(); // var id = $('#comment_trail_id').val() // // debugger; // $.ajax({ // type: $(event.target).attr('method'), // url : '/trails/' + id + '/comments', // data: $(this).serialize() // }).done(function(response){ // debugger; // $("".river"").toggle().toggle(); // $("".comment-form"").remove(); // $("".comment-form"").hide(); // }).fail(function(){ // alert(""Your post has not been posted"") // }); // }); }); ","$(document).on(""ready"", function() { // $(""a"").click("".snowflake"", function(event){ // event.preventDefault(); // event.stopPropagation(); // debugger // // var target = $(event.target).parent().find(""#vote_count"") // $.ajax({ // type: ""POST"", // url : $(this).attr('href'), // dataType: ""json"", // }).done(function(response){ // debugger // alert(""Success!"") // }).fail(function(response){ // console.log(response); // }); // }); $(""#post"").on(""click"", function(event){ event.preventDefault(); $.ajax({ url : $(event.target).attr('href'), }).done(function(response){ $("".comment-form"").show(); }).fail(function(response){ alert(""You are unable to post a comment.""); }); }); $('.comment-form').on(""submit"", 'form', function(event){ event.preventDefault(); var id = $('#comment_trail_id').val() $.ajax({ type: $(event.target).attr('method'), url : '/trails/' + id + '/comments', data: $(this).serialize() }).done(function(response){ debugger; $("".river"").append(response); $("".comment-form"").remove(); $("".comment-form"").hide(); }).fail(function(){ alert(""Your post has not been posted"") }); }); }); " ":art: Remove the api prefix [ci skip] This project is always a API Only so we don't need the prefix anymore.","<?php namespace DoeSangue\Providers; use Illuminate\Support\Facades\Route; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * This namespace is applied to your controller routes. * * In addition, it is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'DoeSangue\Http\Controllers'; /** * Define your route model bindings, pattern filters, etc. */ public function boot() { parent::boot(); } /** * Define the routes for the application. */ public function map() { $this->mapApiRoutes(); // $this->mapWebRoutes(); } /** * Define the ""web"" routes for the application. * * These routes all receive session state, CSRF protection, etc. */ /* protected function mapWebRoutes() { Route::group( [ 'middleware' => 'web', 'namespace' => $this->namespace, ], function ($router) { include base_path('routes/web.php'); } ); } */ /** * Define the ""api"" routes for the application. * * These routes are typically stateless. */ protected function mapApiRoutes() { Route::group( [ 'middleware' => 'api', 'namespace' => $this->namespace, ], function ($router) { include base_path('routes/api.php'); } ); } } ","<?php namespace DoeSangue\Providers; use Illuminate\Support\Facades\Route; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * This namespace is applied to your controller routes. * * In addition, it is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'DoeSangue\Http\Controllers'; /** * Define your route model bindings, pattern filters, etc. */ public function boot() { parent::boot(); } /** * Define the routes for the application. */ public function map() { $this->mapApiRoutes(); // $this->mapWebRoutes(); } /** * Define the ""web"" routes for the application. * * These routes all receive session state, CSRF protection, etc. */ protected function mapWebRoutes() { Route::group( [ 'middleware' => 'web', 'namespace' => $this->namespace, ], function ($router) { include base_path('routes/web.php'); } ); } /** * Define the ""api"" routes for the application. * * These routes are typically stateless. */ protected function mapApiRoutes() { Route::group( [ 'middleware' => 'api', 'namespace' => $this->namespace, 'prefix' => 'api', ], function ($router) { include base_path('routes/api.php'); } ); } } " Add name and dimensions attributes to MockVariable class,"from netCDF4 import Dataset import tempfile class MockNetCDF(Dataset): """""" Wrapper object around NetCDF Dataset to write data only to memory. """""" def __init__(self): # taken from test/tst_diskless.py NetCDF library # even though we aren't persisting data to disk, the constructor # requires a filename not currently in use by another Dataset object.. tmp_filename = tempfile.NamedTemporaryFile(suffix='.nc', delete=True).name super(MockNetCDF, self).__init__(tmp_filename, 'w', diskless=True, persist=False) class MockTimeSeries(MockNetCDF): """""" Mock time series with time dimension and time, lon, lat, and depth variables defined """""" def __init__(self): super(MockTimeSeries, self).__init__() self.createDimension('time', 500) for v in ('time', 'lon', 'lat', 'depth'): self.createVariable(v, 'd', ('time',)) class MockVariable(object): ''' For mocking a dataset variable. Constructor optionally takes a NetCDF variable, the NetCDF attributes of which will be copied over to this object. ''' def __init__(self, copy_var=None): if copy_var is not None: self.name = copy_var.name self.dimensions = copy_var.dimensions for att in copy_var.ncattrs(): setattr(self, att, getattr(copy_var, att)) ","from netCDF4 import Dataset import tempfile class MockNetCDF(Dataset): """""" Wrapper object around NetCDF Dataset to write data only to memory. """""" def __init__(self): # taken from test/tst_diskless.py NetCDF library # even though we aren't persisting data to disk, the constructor # requires a filename not currently in use by another Dataset object.. tmp_filename = tempfile.NamedTemporaryFile(suffix='.nc', delete=True).name super(MockNetCDF, self).__init__(tmp_filename, 'w', diskless=True, persist=False) class MockTimeSeries(MockNetCDF): """""" Mock time series with time dimension and time, lon, lat, and depth variables defined """""" def __init__(self): super(MockTimeSeries, self).__init__() self.createDimension('time', 500) for v in ('time', 'lon', 'lat', 'depth'): self.createVariable(v, 'd', ('time',)) class MockVariable(object): ''' For mocking a dataset variable. Constructor optionally takes a NetCDF variable, the NetCDF attributes of which will be copied over to this object. ''' def __init__(self, copy_var=None): if copy_var is not None: for att in copy_var.ncattrs(): setattr(self, att, getattr(copy_var, att)) " Change ping interval to 25 seconds.,"package io.bekti.anubis.server.kafka; import org.eclipse.jetty.websocket.api.Session; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; public class PingThread extends Thread { private static Logger log = LoggerFactory.getLogger(DispatcherThread.class); private AtomicBoolean running = new AtomicBoolean(false); private Session session; private KafkaWebSocketClient client; public PingThread(Session session, KafkaWebSocketClient client) { this.session = session; this.client = client; } @Override public void run() { running.set(true); JSONObject payload = new JSONObject(); payload.put(""event"", ""ping""); while (running.get()) { try { if (session.isOpen()) { session.getRemote().sendString(payload.toString()); } else { client.shutdown(); } Thread.sleep(25000); } catch (IOException ioe) { client.shutdown(); } catch (InterruptedException ignored) { } catch (Exception e) { log.error(e.getMessage(), e); } } } public boolean isRunning() { return running.get(); } public void shutdown() { if (running.get()) { running.set(false); Thread.currentThread().interrupt(); } } } ","package io.bekti.anubis.server.kafka; import org.eclipse.jetty.websocket.api.Session; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; public class PingThread extends Thread { private static Logger log = LoggerFactory.getLogger(DispatcherThread.class); private AtomicBoolean running = new AtomicBoolean(false); private Session session; private KafkaWebSocketClient client; public PingThread(Session session, KafkaWebSocketClient client) { this.session = session; this.client = client; } @Override public void run() { running.set(true); JSONObject payload = new JSONObject(); payload.put(""event"", ""ping""); while (running.get()) { try { if (session.isOpen()) { session.getRemote().sendString(payload.toString()); } else { client.shutdown(); } Thread.sleep(5000); } catch (IOException ioe) { client.shutdown(); } catch (InterruptedException ignored) { } catch (Exception e) { log.error(e.getMessage(), e); } } } public boolean isRunning() { return running.get(); } public void shutdown() { if (running.get()) { running.set(false); Thread.currentThread().interrupt(); } } } " Reduce response data for HelpLink,"from django.contrib.auth.models import User from rest_framework import serializers from api.models import UserPreferences, HelpLink class HelpLinkSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = HelpLink fields = ( 'link_key', 'href' ) class UserPreferencesSummarySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UserPreferences fields = ( 'id', 'url' ) class UserRelatedField(serializers.PrimaryKeyRelatedField): def use_pk_only_optimization(self): return False def to_representation(self, value): serializer = UserSerializer(value, context=self.context) return serializer.data class UserSerializer(serializers.HyperlinkedModelSerializer): user_pref = UserPreferencesSummarySerializer( source='userpreferences_set', many=True) class Meta: model = User fields = ( 'id', 'url', 'username', 'first_name', 'last_name', 'email', 'is_staff', 'is_superuser', 'date_joined', 'user_pref' ) class UserPreferenceSerializer(serializers.HyperlinkedModelSerializer): user = UserRelatedField(read_only=True) class Meta: model = UserPreferences fields = ( 'id', 'url', 'user', 'show_beta_interface', 'airport_ui', 'created_date', 'modified_date' ) ","from django.contrib.auth.models import User from rest_framework import serializers from api.models import UserPreferences, HelpLink class HelpLinkSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = HelpLink fields = ( 'link_key', 'topic', 'href', 'created_date', 'modified_date' ) class UserPreferencesSummarySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UserPreferences fields = ( 'id', 'url' ) class UserRelatedField(serializers.PrimaryKeyRelatedField): def use_pk_only_optimization(self): return False def to_representation(self, value): serializer = UserSerializer(value, context=self.context) return serializer.data class UserSerializer(serializers.HyperlinkedModelSerializer): user_pref = UserPreferencesSummarySerializer( source='userpreferences_set', many=True) class Meta: model = User fields = ( 'id', 'url', 'username', 'first_name', 'last_name', 'email', 'is_staff', 'is_superuser', 'date_joined', 'user_pref' ) class UserPreferenceSerializer(serializers.HyperlinkedModelSerializer): user = UserRelatedField(read_only=True) class Meta: model = UserPreferences fields = ( 'id', 'url', 'user', 'show_beta_interface', 'airport_ui', 'created_date', 'modified_date' ) " "Add a custom event trigger I needed to add a custom event trigger so I could fire specific JS code when the element came into view (animating a count of numbers), so thought I'd suggest this simple edit which made it possible. It allowed me to then add code as follows: `$(selector).on(""inviewport"", function() { /* code here */ });`","/*jslint browser: true, indent: 2 */ (function ($) { 'use strict'; $.fn.inviewport = function (options) { var settings = $.extend({ 'minPercentageInView' : 100, 'standardClassName': 'in-view' }, options); this.each(function () { var $this = $(this), $win = $(window), changed = false, isVisible = function () { var c = settings.className || settings.standardClassName, min = (settings.threshold || settings.minPercentageInView) / 100, xMin = $this.width() * min, yMin = $this.height() * min, winPosX = $win.scrollLeft() + $win.width(), winPosY = $win.scrollTop() + $win.height(), elPosX = $this.offset().left + xMin, elPosY = $this.offset().top + yMin; if (winPosX > elPosX && winPosY > elPosY) { if(!$this.hasClass(c)) $this.trigger(""inviewport""); $this.addClass(c); } }; $win.on('ready', isVisible()) .on('resize scroll', function () { changed = true; }) setInterval(function () { if (changed) { changed = false; isVisible(); } }, 250); }); }; }(jQuery)); ","/*jslint browser: true, indent: 2 */ (function ($) { 'use strict'; $.fn.inviewport = function (options) { var settings = $.extend({ 'minPercentageInView' : 100, 'standardClassName': 'in-view' }, options); this.each(function () { var $this = $(this), $win = $(window), changed = false, isVisible = function () { var c = settings.className || settings.standardClassName, min = (settings.threshold || settings.minPercentageInView) / 100, xMin = $this.width() * min, yMin = $this.height() * min, winPosX = $win.scrollLeft() + $win.width(), winPosY = $win.scrollTop() + $win.height(), elPosX = $this.offset().left + xMin, elPosY = $this.offset().top + yMin; if (winPosX > elPosX && winPosY > elPosY) { $this.addClass(c); } }; $win.on('ready', isVisible()) .on('resize scroll', function () { changed = true; }) setInterval(function () { if (changed) { changed = false; isVisible(); } }, 250); }); }; }(jQuery)); " Fix: Set logger for request middleware,"<?php namespace PhalconUtils\Middleware; use Phalcon\Logger\Adapter\File; use Phalcon\Mvc\Micro; use PhalconUtils\Constants\Services; use PhalconUtils\Util\Logger; /** * Class LoggerMiddleware * @author Adeyemi Olaoye <yemi@cottacush.com> * @package App\Middleware */ class RequestLoggerMiddleware extends BaseMiddleware { /** @var Logger */ protected $logger; public function __construct($logTargets = []) { $config = $this->getDI()->get(Services::CONFIG); if (!$logTargets) { $fileTarget = new File($config->application->logsDir . 'requests.log'); $logTargets = [$fileTarget]; } $this->logger = new Logger($logTargets); } public function beforeExecuteRoute() { if ($this->isExcludedPath($this->getDI()->get(Services::CONFIG)->requestLogger->excluded_paths)) { return true; } /** @var \Phalcon\Http\Request $request */ $request = $this->getDI()->get(Services::REQUEST); $this->logger->info('Request URL:' . $request->getURI()); if ($request->isPost() || $request->isPut()) { $rawBody = $request->getRawBody(); $this->logger->info('Request Body: ' . $rawBody); } } public function call(Micro $application) { return true; } } ","<?php namespace PhalconUtils\Middleware; use Phalcon\Logger\Adapter\File; use Phalcon\Mvc\Micro; use PhalconUtils\Constants\Services; use PhalconUtils\Util\Logger; /** * Class LoggerMiddleware * @author Adeyemi Olaoye <yemi@cottacush.com> * @package App\Middleware */ class RequestLoggerMiddleware extends BaseMiddleware { /** @var Logger */ protected $logger; public function __construct($logTargets = []) { $config = $this->getDI()->get(Services::CONFIG); if (!$logTargets) { $fileTarget = new File($config->application->logsDir . 'requests.log'); $logger = new Logger([$fileTarget]); $this->logger = $logger; } } public function beforeExecuteRoute() { if ($this->isExcludedPath($this->getDI()->get(Services::CONFIG)->requestLogger->excluded_paths)) { return true; } /** @var \Phalcon\Http\Request $request */ $request = $this->getDI()->get(Services::REQUEST); $this->logger->info('Request URL:' . $request->getURI()); if ($request->isPost() || $request->isPut()) { $rawBody = $request->getRawBody(); $this->logger->info('Request Body: ' . $rawBody); } } public function call(Micro $application) { return true; } } " Correct ACE class name in subscibe config,"/*jslint browser: true, undef: true *//*global Ext*/ Ext.define('JarvusAceDemo.view.editor.Panel', { extend: 'Ext.Panel', xtype: 'editor-panel', requires: [ 'Jarvus.ace.Editor' ], layout: 'fit', items: [{ xtype: 'jarvus-ace-editor', // Ace configuration options: { theme: 'ace/theme/monokai', mode: 'ace/mode/javascript', keyboardHandler: 'ace/keyboard/vim', showPrintMargin: true, printMarginColumn: 20, fontSize: 24 }, // subcribe to ACE events subscribe: { 'Document': [ 'change' ], 'Editor': [ 'blur', 'change' ], 'EditSession': [ 'change' ], 'Selection': [ 'selectionchange' ] } }] }); ","/*jslint browser: true, undef: true *//*global Ext*/ Ext.define('JarvusAceDemo.view.editor.Panel', { extend: 'Ext.Panel', xtype: 'editor-panel', requires: [ 'Jarvus.ace.Editor' ], layout: 'fit', items: [{ xtype: 'jarvus-ace-editor', // Ace configuration options: { theme: 'ace/theme/monokai', mode: 'ace/mode/javascript', keyboardHandler: 'ace/keyboard/vim', showPrintMargin: true, printMarginColumn: 20, fontSize: 24 }, // subcribe to ACE events subscribe: { 'Document': [ 'change' ], 'Editor': [ 'blur', 'change' ], 'EditorSession': [ 'change' ], 'Selection': [ 'selectionchange' ] } }] }); " Move requireSaved check outside of loop,"<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. declare(strict_types=1); namespace Database\Factories; use App\Exceptions\ModelNotSavedException; use Illuminate\Database\Eloquent\Factories\Factory as BaseFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Collection; abstract class Factory extends BaseFactory { private bool $requireSaved = true; /** * Return the created model even if it fails to save. * * @return $this */ public function allowUnsaved(): static { $this->requireSaved = false; return $this; } protected function callAfterCreating(Collection $instances, ?Model $parent = null): void { if ($this->requireSaved) { $instances->each(function ($model) { if (!$model->exists) { throw new ModelNotSavedException( method_exists($model, 'validationErrors') ? $model->validationErrors()->toSentence() : 'Failed to save model', ); } }); } parent::callAfterCreating($instances, $parent); } protected function newInstance(array $arguments = []): static { $factory = parent::newInstance($arguments); $factory->requireSaved = $this->requireSaved; return $factory; } // TODO: remove following line after removing legacy-factories // fooling legacy-factories' ""isLegacyFactory"" check: class Hello extends Factory } ","<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. declare(strict_types=1); namespace Database\Factories; use App\Exceptions\ModelNotSavedException; use Illuminate\Database\Eloquent\Factories\Factory as BaseFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Collection; abstract class Factory extends BaseFactory { private bool $requireSaved = true; /** * Return the created model even if it fails to save. * * @return $this */ public function allowUnsaved(): static { $this->requireSaved = false; return $this; } protected function callAfterCreating(Collection $instances, ?Model $parent = null): void { $instances->each(function ($model) { if (!$model->exists && $this->requireSaved) { throw new ModelNotSavedException( method_exists($model, 'validationErrors') ? $model->validationErrors()->toSentence() : 'Failed to save model', ); } }); parent::callAfterCreating($instances, $parent); } protected function newInstance(array $arguments = []): static { $factory = parent::newInstance($arguments); $factory->requireSaved = $this->requireSaved; return $factory; } // TODO: remove following line after removing legacy-factories // fooling legacy-factories' ""isLegacyFactory"" check: class Hello extends Factory } " Add fallbacks for e-mail handling if outbox is not defined," import click import json import logging import requests from datetime import datetime from certidude import config def publish(event_type, event_data): """""" Publish event on push server """""" if not config.PUSH_PUBLISH: # Push server disabled return if not isinstance(event_data, basestring): from certidude.decorators import MyEncoder event_data = json.dumps(event_data, cls=MyEncoder) url = config.PUSH_PUBLISH % config.PUSH_TOKEN click.echo(""Publishing %s event '%s' on %s"" % (event_type, event_data, url)) try: notification = requests.post( url, data=event_data, headers={""X-EventSource-Event"": event_type, ""User-Agent"": ""Certidude API""}) if notification.status_code == requests.codes.created: pass # Sent to client elif notification.status_code == requests.codes.accepted: pass # Buffered in nchan else: click.echo(""Failed to submit event to push server, server responded %d"" % ( notification.status_code)) except requests.exceptions.ConnectionError: click.echo(""Failed to submit event to push server, connection error"") class PushLogHandler(logging.Handler): """""" To be used with Python log handling framework for publishing log entries """""" def emit(self, record): from certidude.push import publish publish(""log-entry"", dict( created = datetime.utcfromtimestamp(record.created), message = record.msg % record.args, severity = record.levelname.lower())) "," import click import json import logging import requests from datetime import datetime from certidude import config def publish(event_type, event_data): """""" Publish event on push server """""" if not isinstance(event_data, basestring): from certidude.decorators import MyEncoder event_data = json.dumps(event_data, cls=MyEncoder) url = config.PUSH_PUBLISH % config.PUSH_TOKEN click.echo(""Publishing %s event '%s' on %s"" % (event_type, event_data, url)) try: notification = requests.post( url, data=event_data, headers={""X-EventSource-Event"": event_type, ""User-Agent"": ""Certidude API""}) if notification.status_code == requests.codes.created: pass # Sent to client elif notification.status_code == requests.codes.accepted: pass # Buffered in nchan else: click.echo(""Failed to submit event to push server, server responded %d"" % ( notification.status_code)) except requests.exceptions.ConnectionError: click.echo(""Failed to submit event to push server, connection error"") class PushLogHandler(logging.Handler): """""" To be used with Python log handling framework for publishing log entries """""" def emit(self, record): from certidude.push import publish publish(""log-entry"", dict( created = datetime.utcfromtimestamp(record.created), message = record.msg % record.args, severity = record.levelname.lower())) " Fix proxy bypass for missing static case,"#!/usr/bin/env node var path = require('path'); var fs = require('fs'); var webpack = require('webpack'); var WebpackDevServer = require('webpack-dev-server'); // the following will be replaced with inline json var RunConfig = require('$RunConfig$'); var config = require(RunConfig.webPackConfig); config.entry = [ ""webpack-dev-server/client?http://localhost:"" + RunConfig.port + ""/"", ""webpack/hot/dev-server"", config.entry ]; if (!config.plugins) { config.plugins = []; } config.plugins.push(new webpack.HotModuleReplacementPlugin()); if (!config.devServer) { config.devServer = {}; } config.devServer.inline = true; var devServer = new WebpackDevServer( webpack(config), { contentBase: RunConfig.contentPath, hot: true, setup: function(app) { app.get(RunConfig.shutDownPath, function(req, res) { res.json({ shutdown: 'ok' }); devServer.close(); }); }, proxy: { ""**"" : (RunConfig.contentPath) ? { target: RunConfig.proxyUrl, secure: false, bypass: function(req, res, proxyOptions) { if (RunConfig.contentPath) { var file = path.join(RunConfig.contentPath, req.path); if (fs.existsSync(file)) { return req.path; } } } } : null } } ); devServer.listen(RunConfig.port, 'localhost'); ","#!/usr/bin/env node var path = require('path'); var fs = require('fs'); var webpack = require('webpack'); var WebpackDevServer = require('webpack-dev-server'); // the following will be replaced with inline json var RunConfig = require('$RunConfig$'); var config = require(RunConfig.webPackConfig); config.entry = [ ""webpack-dev-server/client?http://localhost:"" + RunConfig.port + ""/"", ""webpack/hot/dev-server"", config.entry ]; if (!config.plugins) { config.plugins = []; } config.plugins.push(new webpack.HotModuleReplacementPlugin()); if (!config.devServer) { config.devServer = {}; } config.devServer.inline = true; var devServer = new WebpackDevServer( webpack(config), { contentBase: RunConfig.contentPath, hot: true, setup: function(app) { app.get(RunConfig.shutDownPath, function(req, res) { res.json({ shutdown: 'ok' }); devServer.close(); }); }, proxy: { ""**"" : (RunConfig.contentPath) ? { target: RunConfig.proxyUrl, secure: false, bypass: function(req, res, proxyOptions) { var file = path.join(RunConfig.contentPath, req.path); if (fs.existsSync(file)) { return req.path; } } } : null } } ); devServer.listen(RunConfig.port, 'localhost'); " Replace anonymous class with lambda,"package org.springframework.samples.petclinic.system; import java.util.concurrent.TimeUnit; import javax.cache.CacheManager; import org.ehcache.config.CacheConfiguration; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.EntryUnit; import org.ehcache.expiry.Duration; import org.ehcache.expiry.Expirations; import org.ehcache.jsr107.Eh107Configuration; import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; /** * Cache could be disable in unit test. */ @Configuration @EnableCaching @Profile(""production"") class CacheConfig { @Bean public JCacheManagerCustomizer cacheManagerCustomizer() { return cacheManager -> { CacheConfiguration<Object, Object> config = CacheConfigurationBuilder .newCacheConfigurationBuilder(Object.class, Object.class, ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(100, EntryUnit.ENTRIES)) .withExpiry(Expirations.timeToLiveExpiration(Duration.of(60, TimeUnit.SECONDS))) .build(); cacheManager.createCache(""vets"", Eh107Configuration.fromEhcacheCacheConfiguration(config)); }; } } ","package org.springframework.samples.petclinic.system; import java.util.concurrent.TimeUnit; import javax.cache.CacheManager; import org.ehcache.config.CacheConfiguration; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.EntryUnit; import org.ehcache.expiry.Duration; import org.ehcache.expiry.Expirations; import org.ehcache.jsr107.Eh107Configuration; import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; /** * Cache could be disable in unit test. */ @Configuration @EnableCaching @Profile(""production"") class CacheConfig { @Bean public JCacheManagerCustomizer cacheManagerCustomizer() { return new JCacheManagerCustomizer() { @Override public void customize(CacheManager cacheManager) { CacheConfiguration<Object, Object> config = CacheConfigurationBuilder .newCacheConfigurationBuilder(Object.class, Object.class, ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(100, EntryUnit.ENTRIES)) .withExpiry(Expirations.timeToLiveExpiration(Duration.of(60, TimeUnit.SECONDS))) .build(); cacheManager.createCache(""vets"", Eh107Configuration.fromEhcacheCacheConfiguration(config)); } }; } } " Make RegExps with an empty character set (`[]`) invalid,"import TextFieldWithButton from '../text-field-with-button'; import NotificationHandler from '../../mixins/notification-handler'; export default TextFieldWithButton.extend(NotificationHandler, { classNames: ['regex-textfield'], actions: { sendText: function(text) { if (arguments.length > 0 && typeof(text) === 'string') { this.set('text', text); } try { new RegExp(this.get('text')); this.sendAction('action', this.get('text')); if(/([^\\]|^)\[\]/.test(this.get('text'))) { // A lone [] is invalid in a python RegExp but valid in JS throw new Error('Invalid regexp'); } } catch (e) { this.showWarningNotification('Validation Error', '""' + this.get('text') + '"" ' + 'is not a valid regular expression'); return; } if (this.get('reset')) { this.$().find('textarea').val(''); this.$().find('input[type=""text""]').val(''); } }, } }); ","import TextFieldWithButton from '../text-field-with-button'; import NotificationHandler from '../../mixins/notification-handler'; export default TextFieldWithButton.extend(NotificationHandler, { classNames: ['regex-textfield'], actions: { sendText: function(text) { if (arguments.length > 0 && typeof(text) === 'string') { this.set('text', text); } try { new RegExp(this.get('text')); this.sendAction('action', this.get('text')); } catch (e) { this.showWarningNotification('Validation Error', '""' + this.get('text') + '"" ' + 'is not a valid regular expression'); return; } if (this.get('reset')) { this.$().find('textarea').val(''); this.$().find('input[type=""text""]').val(''); } }, } }); " Use an absolute Path for localization tests,"import os import platform import subprocess import unittest from pathlib import Path class TestLocaleNormalization(unittest.TestCase): LOCALE_PATH = Path(""survey"", ""locale"").absolute() def test_normalization(self): """""" We test if the messages were properly created with makemessages --no-obsolete --no-wrap. """""" if platform.system() == ""Windows"": python_3 = [""py"", ""-3""] else: python_3 = [""python3""] makemessages_command = python_3 + [ ""manage.py"", ""makemessages"", ""--no-obsolete"", ""--no-wrap"", ""--ignore"", ""venv"", ] number_of_language = len(os.listdir(self.LOCALE_PATH)) subprocess.check_call(makemessages_command) git_diff_command = [""git"", ""diff"", self.LOCALE_PATH] git_diff = subprocess.check_output(git_diff_command).decode(""utf8"") # In the diff we should have a change only for the date of the generation # So 2 * @@ * number of language number_of_change = git_diff.count(""@@"") / 2 msg = ( ""You did not update the translation following your changes. Maybe you did not use the "" ""normalized 'python3 manage.py makemessages --no-obsolete --no-wrap' ? If you're "" ""working locally, just use 'git add {}', we launched it during tests."".format(self.LOCALE_PATH), ) self.assertEqual(number_of_change, number_of_language, msg) ","import os import platform import subprocess import unittest class TestLocaleNormalization(unittest.TestCase): LOCALE_PATH = ""survey/locale/"" def test_normalization(self): """""" We test if the messages were properly created with makemessages --no-obsolete --no-wrap. """""" if platform.system() == ""Windows"": python_3 = [""py"", ""-3""] else: python_3 = [""python3""] makemessages_command = python_3 + [ ""manage.py"", ""makemessages"", ""--no-obsolete"", ""--no-wrap"", ""--ignore"", ""venv"", ] number_of_language = len(os.listdir(self.LOCALE_PATH)) subprocess.check_call(makemessages_command) git_diff_command = [""git"", ""diff"", self.LOCALE_PATH] git_diff = subprocess.check_output(git_diff_command).decode(""utf8"") # In the diff we should have a change only for the date of the generation # So 2 * @@ * number of language number_of_change = git_diff.count(""@@"") / 2 msg = ( ""You did not update the translation following your changes. Maybe you did not use the "" ""normalized 'python3 manage.py makemessages --no-obsolete --no-wrap' ? If you're "" ""working locally, just use 'git add {}', we launched it during tests."".format(self.LOCALE_PATH), ) self.assertEqual(number_of_change, number_of_language, msg) " Stop the stdin thread if stdin get detached or not connected.,"package me.rkfg.xmpp.bot.plugins; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.regex.Matcher; import java.util.regex.Pattern; import me.rkfg.xmpp.bot.Main; import org.jivesoftware.smack.packet.Message; public class StdinPlugin implements MessagePlugin { @Override public Pattern getPattern() { return null; } @Override public String process(Message message, Matcher matcher) { return null; } @Override public void init() { new Thread(new Runnable() { @Override public void run() { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); while (!Thread.interrupted()) { try { String line = bufferedReader.readLine(); if (line == null) { // stdin is not connected break; } Main.sendMUCMessage(line); } catch (IOException e) { e.printStackTrace(); } } } }, ""Stdin handler"").start(); } @Override public String getManual() { return null; } } ","package me.rkfg.xmpp.bot.plugins; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.regex.Matcher; import java.util.regex.Pattern; import me.rkfg.xmpp.bot.Main; import org.jivesoftware.smack.packet.Message; public class StdinPlugin implements MessagePlugin { @Override public Pattern getPattern() { return null; } @Override public String process(Message message, Matcher matcher) { return null; } @Override public void init() { new Thread(new Runnable() { @Override public void run() { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); while (!Thread.interrupted()) { try { String line = bufferedReader.readLine(); Main.sendMUCMessage(line); } catch (IOException e) { e.printStackTrace(); } } } }, ""Stdin handler"").start(); } @Override public String getManual() { return null; } } " Sort languages by English name,"import subprocess import re from collections import defaultdict from babel import Locale authors_by_locale = defaultdict(set) file_listing = subprocess.Popen('find ../wagtail -iname *.po', shell=True, stdout=subprocess.PIPE) for file_listing_line in file_listing.stdout: filename = file_listing_line.strip() # extract locale string from filename locale = re.search(r'locale/(\w+)/LC_MESSAGES', filename).group(1) if locale == 'en': continue # read author list from each file with file(filename) as f: has_found_translators_heading = False for line in f: line = line.strip() if line.startswith('#'): if has_found_translators_heading: author = re.match(r'\# (.*), [\d\-]+', line).group(1) authors_by_locale[locale].add(author) elif line.startswith('# Translators:'): has_found_translators_heading = True else: if has_found_translators_heading: break else: raise Exception(""No 'Translators:' heading found in %s"" % filename) language_names = [ (Locale.parse(locale_string).english_name, locale_string) for locale_string in authors_by_locale.keys() ] language_names.sort() for (language_name, locale) in language_names: print(""%s - %s"" % (language_name, locale)) print(""-----"") for author in sorted(authors_by_locale[locale]): print(author) print('') ","import subprocess import re from collections import defaultdict authors_by_locale = defaultdict(set) file_listing = subprocess.Popen('find ../wagtail -iname *.po', shell=True, stdout=subprocess.PIPE) for file_listing_line in file_listing.stdout: filename = file_listing_line.strip() # extract locale string from filename locale = re.search(r'locale/(\w+)/LC_MESSAGES', filename).group(1) if locale == 'en': continue # read author list from each file with file(filename) as f: has_found_translators_heading = False for line in f: line = line.strip() if line.startswith('#'): if has_found_translators_heading: author = re.match(r'\# (.*), [\d\-]+', line).group(1) authors_by_locale[locale].add(author) elif line.startswith('# Translators:'): has_found_translators_heading = True else: if has_found_translators_heading: break else: raise Exception(""No 'Translators:' heading found in %s"" % filename) locales = sorted(authors_by_locale.keys()) for locale in locales: print(locale) print(""-----"") for author in sorted(authors_by_locale[locale]): print(author) print('') " Fix PHP 5.3 compatibility issue,"<?php namespace Kanboard\Plugin\GogsWebhook; use Kanboard\Core\Plugin\Base; use Kanboard\Core\Translator; class Plugin extends Base { public function initialize() { $this->on('app.bootstrap', function($container) { Translator::load($container['config']->getCurrentLanguage(), __DIR__.'/Locale'); $container['eventManager']->register(WebhookHandler::EVENT_COMMIT, t('Gogs commit received')); }); $this->actionManager->getAction('\Kanboard\Action\CommentCreation')->addEvent(WebhookHandler::EVENT_COMMIT); $this->actionManager->getAction('\Kanboard\Action\TaskClose')->addEvent(WebhookHandler::EVENT_COMMIT); $this->template->hook->attach('template:project:integrations', 'GogsWebhook:project/integrations'); $this->route->addRoute('/webhook/gogs/:project_id/:token', 'webhook', 'handler', 'GogsWebhook'); } public function getPluginName() { return 'Gogs Webhook'; } public function getPluginDescription() { return t('Bind Gogs webhook events to Kanboard automatic actions'); } public function getPluginAuthor() { return 'Frédéric Guillot'; } public function getPluginVersion() { return '1.0.1'; } public function getPluginHomepage() { return 'https://github.com/kanboard/plugin-gogs-webhook'; } } ","<?php namespace Kanboard\Plugin\GogsWebhook; use Kanboard\Core\Plugin\Base; use Kanboard\Core\Translator; class Plugin extends Base { public function initialize() { $this->on('app.bootstrap', function($container) { Translator::load($container['config']->getCurrentLanguage(), __DIR__.'/Locale'); $this->eventManager->register(WebhookHandler::EVENT_COMMIT, t('Gogs commit received')); }); $this->actionManager->getAction('\Kanboard\Action\CommentCreation')->addEvent(WebhookHandler::EVENT_COMMIT); $this->actionManager->getAction('\Kanboard\Action\TaskClose')->addEvent(WebhookHandler::EVENT_COMMIT); $this->template->hook->attach('template:project:integrations', 'GogsWebhook:project/integrations'); $this->route->addRoute('/webhook/gogs/:project_id/:token', 'webhook', 'handler', 'GogsWebhook'); } public function getPluginName() { return 'Gogs Webhook'; } public function getPluginDescription() { return t('Bind Gogs webhook events to Kanboard automatic actions'); } public function getPluginAuthor() { return 'Frédéric Guillot'; } public function getPluginVersion() { return '1.0.0'; } public function getPluginHomepage() { return 'https://github.com/kanboard/plugin-gogs-webhook'; } } " Support Both XML and HTML Documents (HTML is Default),"<?php namespace trejeraos; use \DOMDocument; use \DOMXpath; use Symfony\Component\CssSelector\CssSelectorConverter; /** * DOMSelector makes selecting XML elements easy by using CSS like selectors * * @author Jeremie Jarosh <jeremie@jarosh.org> * @version 0.3.0 */ class DOMSelector extends DOMXpath { /** * @var \Symfony\Component\CssSelector\CssSelectorConverter */ protected $converter; /** * Creates a new DOMSelector object * * @param DOMDocument $doc The DOMDocument associated with the DOMSelector. * @param bool $html Whether HTML support should be enabled. Disable it for XML documents. */ public function __construct(DOMDocument $doc, $html = true) { parent::__construct($doc); $this->converter = new CssSelectorConverter($html); } /** * Returns a list of the elements within the document that match the specified group of selectors. * * @param string $filename CSS Selector * * @return DOMNodeList */ public function querySelectorAll($cssSelectors) { $xpathQuery = $this->converter->toXPath($cssSelectors); return $this->query($xpathQuery); } /** * Returns the first element within the document that matches the specified group of selectors. * * @param string $filename CSS Selector * * @return DOMNode */ public function querySelector($cssSelectors) { return $this->querySelectorAll($cssSelectors)->item(0); } }","<?php namespace trejeraos; use \DOMDocument; use \DOMXpath; use Symfony\Component\CssSelector\CssSelectorConverter; /** * DOMSelector makes selecting XML elements easy by using CSS like selectors * * @author Jeremie Jarosh <jeremie@jarosh.org> * @version 0.3.0 */ class DOMSelector extends DOMXpath { /** * @var \Symfony\Component\CssSelector\CssSelectorConverter */ protected $converter; public function __construct(DOMDocument $doc) { parent::__construct($doc); $this->converter = new CssSelectorConverter(false); } /** * Returns a list of the elements within the document that match the specified group of selectors. * * @param string $filename CSS Selector * * @return DOMNodeList */ public function querySelectorAll($cssSelectors) { $xpathQuery = $this->converter->toXPath($cssSelectors); return $this->query($xpathQuery); } /** * Returns the first element within the document that matches the specified group of selectors. * * @param string $filename CSS Selector * * @return DOMNode */ public function querySelector($cssSelectors) { return $this->querySelectorAll($cssSelectors)->item(0); } }" Add logger for scapy Automaton," import logging import sys LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'verbose': { 'format': '%(asctime)s %(levelname)s' ' %(filename)s:%(lineno)s -' ' %(funcName)s - %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S' }, 'simple': { 'format': ""%(message)s"", }, 'sys': { 'format': ""%(module)s[%(process)s]: "" ""%(message)s"" } }, 'handlers': { 'stdout': { 'class': 'logging.StreamHandler', 'stream': sys.stdout, 'formatter': 'verbose', 'level': 'DEBUG', }, 'stdoutscapy': { 'class': 'logging.StreamHandler', 'stream': sys.stdout, 'formatter': 'simple', 'level': 'DEBUG', }, 'syslog': { 'class': 'logging.handlers.SysLogHandler', 'address': '/dev/log', 'formatter': 'sys', 'level': 'INFO', }, }, 'loggers': { 'dhcpcanon': { 'handlers': ['syslog', 'stdout'], 'level': logging.INFO, 'propagate': False }, ""scapy.interactive"": { 'handlers': ['stdoutscapy'], 'level': logging.INFO, 'propagate': False } } } "," import logging import sys LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'verbose': { 'format': '%(asctime)s %(levelname)s'\ '%(module)s[%(process)d.]'\ ' %(filename)s:%(lineno)s -'\ ' %(funcName)s - %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S' }, 'formsys': { 'format': ""%(asctime)s %(module)s[%(process)s.%(thread)s]: %(message)s"", 'datefmt': ""%b %d %H:%M:%S"" } }, 'handlers': { 'stdout': { 'class': 'logging.StreamHandler', 'stream': sys.stdout, 'formatter': 'verbose', 'level': 'DEBUG', }, 'syslog': { 'class': 'logging.handlers.SysLogHandler', 'address': '/dev/log', 'formatter': 'formsys', 'level': 'INFO', }, }, 'loggers': { 'dhcpcanon': { 'handlers': ['syslog', 'stdout'], 'level': logging.INFO, 'propagate': False }, } } " Clean up the argument parsing,"from .settings import BongSettings, DEFAULT_MESSAGE from .metadata import VERSION, SUMMARY import argparse PARSER = argparse.ArgumentParser(description=SUMMARY) PARSER.add_argument('-V', '--version', action='version', version='%(prog)s {}'.format(VERSION), help='show version') PARSER.add_argument('-s', '--short-break', action='store_const', const=5, dest='minutes', default=25, help='time for a Pomodoro system short break') PARSER.add_argument('-l', '--long-break', action='store_const', const=15, dest='minutes', help='time for a Pomodoro system long break') PARSER.add_argument('-p', '--pomodoro', action='store_const', const=25, dest='minutes', help='time for a Pomodoro system single Pomodoro') PARSER.add_argument('-t', '--time', action='store', type=int, dest='minutes', help='timer length, in minutes') PARSER.add_argument('-m', '--message', default=DEFAULT_MESSAGE, help='message to display in the notifier') def parse_args(args): settings = PARSER.parse_args(args) return BongSettings(time=60*settings.minutes, message=settings.message) ","from .settings import BongSettings, DEFAULT_MESSAGE from .metadata import VERSION, SUMMARY import argparse PARSER = argparse.ArgumentParser(description=SUMMARY) PARSER.add_argument('-V', '--version', action='version', version=VERSION, help='Show version') PARSER.add_argument('-s', '--short-break', action='store_const', const=5, dest='minutes', default=25, help='Time for a Pomodoro system short break') PARSER.add_argument('-l', '--long-break', action='store_const', const=15, dest='minutes', help='Time for a Pomodoro system long break') PARSER.add_argument('-p', '--pomodoro', action='store_const', const=25, dest='minutes', help='Time for a Pomodoro system single Pomodoro') PARSER.add_argument('-t', '--time', action='store', type=int, dest='minutes', help='Timer length, in minutes') PARSER.add_argument('-m', '--message', default=DEFAULT_MESSAGE, help='Message to display in the notifier') def parse_args(args): settings = PARSER.parse_args(args) return BongSettings(time=60*settings.minutes, message=settings.message) " USe browsers variable for Grunt.,"'use strict'; module.exports = function(grunt) { var browsers = [ 'Chrome', 'PhantomJS', 'Firefox' ]; if (process.env.TRAVIS){ browsers = ['PhantomJS']; } grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), karma: { unit: { options: { files: [ 'components/angular/angular.js', 'components/angular-mocks/angular-mocks.js', 'components/chai/chai.js', 'ngStorage.js', 'test/spec.js' ] }, frameworks: ['mocha'], browsers: browsers, singleRun: true } }, uglify: { options: { banner: '/*! <%= pkg.name %> <%= pkg.version %> | Copyright (c) <%= grunt.template.today(""yyyy"") %> Gias Kay Lee | MIT License */' }, build: { src: '<%= pkg.name %>.js', dest: '<%= pkg.name %>.min.js' } } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-karma'); grunt.registerTask('test', ['karma']); grunt.registerTask('default', [ 'test', 'uglify' ]); }; ","'use strict'; module.exports = function(grunt) { var browsers = [ 'Chrome', 'PhantomJS', 'Firefox' ]; if (process.env.TRAVIS){ browsers = ['PhantomJS']; } grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), karma: { unit: { options: { files: [ 'components/angular/angular.js', 'components/angular-mocks/angular-mocks.js', 'components/chai/chai.js', 'ngStorage.js', 'test/spec.js' ] }, frameworks: ['mocha'], browsers: [ 'Chrome', 'PhantomJS', 'Firefox' ], singleRun: true } }, uglify: { options: { banner: '/*! <%= pkg.name %> <%= pkg.version %> | Copyright (c) <%= grunt.template.today(""yyyy"") %> Gias Kay Lee | MIT License */' }, build: { src: '<%= pkg.name %>.js', dest: '<%= pkg.name %>.min.js' } } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-karma'); grunt.registerTask('test', ['karma']); grunt.registerTask('default', [ 'test', 'uglify' ]); }; " Allow images to be null,"<?php namespace Metrique\Building\Http\Requests; use Illuminate\Database\Eloquent\Builder; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rule; use Metrique\Building\Rules\AbsoluteUrlPathRule; class PageRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get custom attributes for validator errors. * * @return array */ public function attributes() { return [ 'path' => 'Path', 'published_at' => 'published date', ]; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'path' => [ 'required', 'string', new AbsoluteUrlPathRule, Rule::unique( 'pages', 'path' )->ignore( optional($this->page)->id )->where(function ($query) { return $query->whereNull('deleted_at'); }), ], 'title' => [ 'required', 'string', ], 'description' => [ 'required', 'string', ], 'image' => [ 'nullable', 'string', 'url', ], 'meta' => [ 'array', ], 'params' => [ 'array', ], 'published_at' => [ 'nullable', 'date', ], ]; } } ","<?php namespace Metrique\Building\Http\Requests; use Illuminate\Database\Eloquent\Builder; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rule; use Metrique\Building\Rules\AbsoluteUrlPathRule; class PageRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get custom attributes for validator errors. * * @return array */ public function attributes() { return [ 'path' => 'Path', 'published_at' => 'published date', ]; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'path' => [ 'required', 'string', new AbsoluteUrlPathRule, Rule::unique( 'pages', 'path' )->ignore( optional($this->page)->id )->where(function ($query) { return $query->whereNull('deleted_at'); }), ], 'title' => [ 'required', 'string', ], 'description' => [ 'required', 'string', ], 'image' => [ 'string', 'url' ], 'meta' => [ 'array', ], 'params' => [ 'array', ], 'published_at' => [ 'nullable', 'date', ], ]; } } " Add aliases for [] and []= to Kernel,"<?php namespace Phuby; class Kernel { static function initialized($self) { $self->alias_method('[]', 'array_access_offset_get'); $self->alias_method('[]=', 'array_access_offset_set'); } function extend($module) { return $this->__extend__($module); } function inspect() { return '<'.$this->__class()->name().':'.$this->object_id().'>'; } function is_a($module) { $module = (string) $module; foreach ($this->singleton_class()->ancestors() as $ancestor) if ($ancestor->name() == $module) return true; } function method($method_name) { if ($method = $this->singleton_class()->instance_method($method_name)) return $method->bind($this); } function methods() { return $this->singleton_class()->instance_methods(); } function object_id() { return $this->__id__(); } function respond_to($method_name) { return !!$this->method($method_name) || $this->respond_to_missing($method_name); } function respond_to_missing($method_name) { return false; } function send($method_name) { return call_user_func_array([$this, '__send__'], func_get_args()); } function splat($method_name, $args) { return $this->__splat__($method_name, $args); } function tap($block) { $block($this); return $this; } function to_s() { return $this->inspect(); } }","<?php namespace Phuby; class Kernel { function extend($module) { return $this->__extend__($module); } function inspect() { return '<'.$this->__class()->name().':'.$this->object_id().'>'; } function is_a($module) { $module = (string) $module; foreach ($this->singleton_class()->ancestors() as $ancestor) if ($ancestor->name() == $module) return true; } function method($method_name) { if ($method = $this->singleton_class()->instance_method($method_name)) return $method->bind($this); } function methods() { return $this->singleton_class()->instance_methods(); } function object_id() { return $this->__id__(); } function respond_to($method_name) { return !!$this->method($method_name) || $this->respond_to_missing($method_name); } function respond_to_missing($method_name) { return false; } function send($method_name) { return call_user_func_array([$this, '__send__'], func_get_args()); } function splat($method_name, $args) { return $this->__splat__($method_name, $args); } function tap($block) { $block($this); return $this; } function to_s() { return $this->inspect(); } }" Remove an unnecessary class attribute,"from .. import idiokit from ._iputils import parse_ip from ._conf import hosts from ._dns import DNSError, a, aaaa def _filter_ips(potential_ips): results = [] for ip in potential_ips: try: family, ip = parse_ip(ip) except ValueError: continue else: results.append((family, ip)) return results class HostLookup(object): def __init__(self, hosts_file=None): if hosts_file: self._hosts = hosts(path=hosts_file) else: self._hosts = hosts() @idiokit.stream def host_lookup(self, host, resolver=None): results = _filter_ips([host]) if not results: results = _filter_ips(self._hosts.load().name_to_ips(host)) if not results: results = [] error = None try: records = yield a(host, resolver) except DNSError as error: results = [] else: results = _filter_ips(records) try: records = yield aaaa(host, resolver) except DNSError: if error is not None: raise error else: results.extend(_filter_ips(records)) idiokit.stop(results) host_lookup = HostLookup().host_lookup ","from .. import idiokit from ._iputils import parse_ip from ._conf import hosts from ._dns import DNSError, a, aaaa def _filter_ips(potential_ips): results = [] for ip in potential_ips: try: family, ip = parse_ip(ip) except ValueError: continue else: results.append((family, ip)) return results class HostLookup(object): _hosts = None def __init__(self, hosts_file=None): if hosts_file: self._hosts = hosts(path=hosts_file) else: self._hosts = hosts() @idiokit.stream def host_lookup(self, host, resolver=None): results = _filter_ips([host]) if not results: results = _filter_ips(self._hosts.load().name_to_ips(host)) if not results: results = [] error = None try: records = yield a(host, resolver) except DNSError as error: results = [] else: results = _filter_ips(records) try: records = yield aaaa(host, resolver) except DNSError: if error is not None: raise error else: results.extend(_filter_ips(records)) idiokit.stop(results) host_lookup = HostLookup().host_lookup " Fix the rootfactory for no matchdict so we can get a 404 back out,"from pyramid.authentication import AuthTktAuthenticationPolicy from pyramid.authorization import ACLAuthorizationPolicy from pyramid.config import Configurator from sqlalchemy import engine_from_config from bookie.lib.access import RequestWithUserAttribute from bookie.models import initialize_sql from bookie.models.auth import UserMgr from bookie.routes import build_routes from pyramid.security import Allow from pyramid.security import Everyone from pyramid.security import ALL_PERMISSIONS class RootFactory(object): __acl__ = [ (Allow, Everyone, ALL_PERMISSIONS)] def __init__(self, request): if request.matchdict: self.__dict__.update(request.matchdict) def main(global_config, **settings): """""" This function returns a Pyramid WSGI application. """""" engine = engine_from_config(settings, 'sqlalchemy.') initialize_sql(engine) authn_policy = AuthTktAuthenticationPolicy(settings.get('auth.secret'), callback=UserMgr.auth_groupfinder) authz_policy = ACLAuthorizationPolicy() config = Configurator(settings=settings, root_factory='bookie.RootFactory', authentication_policy=authn_policy, authorization_policy=authz_policy) config.set_request_factory(RequestWithUserAttribute) config = build_routes(config) config.add_static_view('static', 'bookie:static') config.scan('bookie.views') return config.make_wsgi_app() ","from pyramid.authentication import AuthTktAuthenticationPolicy from pyramid.authorization import ACLAuthorizationPolicy from pyramid.config import Configurator from sqlalchemy import engine_from_config from bookie.lib.access import RequestWithUserAttribute from bookie.models import initialize_sql from bookie.models.auth import UserMgr from bookie.routes import build_routes from pyramid.security import Allow from pyramid.security import Everyone from pyramid.security import ALL_PERMISSIONS class RootFactory(object): __acl__ = [ (Allow, Everyone, ALL_PERMISSIONS)] def __init__(self, request): self.__dict__.update(request.matchdict) def main(global_config, **settings): """""" This function returns a Pyramid WSGI application. """""" engine = engine_from_config(settings, 'sqlalchemy.') initialize_sql(engine) authn_policy = AuthTktAuthenticationPolicy(settings.get('auth.secret'), callback=UserMgr.auth_groupfinder) authz_policy = ACLAuthorizationPolicy() config = Configurator(settings=settings, root_factory='bookie.RootFactory', authentication_policy=authn_policy, authorization_policy=authz_policy) config.set_request_factory(RequestWithUserAttribute) config = build_routes(config) config.add_static_view('static', 'bookie:static') config.scan('bookie.views') return config.make_wsgi_app() " Disable XYZ testing. Unclear if the tests or the implementation is wrong,"var vows = require('vows'), assert = require('assert'), namedColorSamples = require('./samples'), spaces = [ 'rgb', 'hsl', 'hsv' ]; function createTest(bundleFileName) { var Color = require(bundleFileName), batch = {}; Object.keys(namedColorSamples).forEach(function (namedColor) { var sub = batch[namedColor + ': ' + namedColorSamples[namedColor]] = { topic: Color(namedColorSamples[namedColor]) }; spaces.forEach(function (space) { sub[space.toUpperCase() + ' hex string comparison'] = function (topic) { assert.equal(topic[space]().hex(), topic.hex()); }; /* sub[space.toUpperCase() + ' strict comparison'] = function (topic) { assert.ok(topic.equals(topic[space]())); };*/ }); }); return batch; } /* vows.describe('Color').addBatch({ 'base, debug': createTest('../one-color-debug'), 'base, minified': createTest('../one-color') }).export(module); */ spaces.push( 'cmyk'/*, 'xyz', 'lab'*/ ); vows.describe('Color-all').addBatch({ //'all, debug': createTest('../one-color-all-debug'), 'all, minified': createTest('../one-color-all') }).export(module); ","var vows = require('vows'), assert = require('assert'), namedColorSamples = require('./samples'), spaces = [ 'rgb', 'hsl', 'hsv' ]; function createTest(bundleFileName) { var Color = require(bundleFileName), batch = {}; Object.keys(namedColorSamples).forEach(function (namedColor) { var sub = batch[namedColor + ': ' + namedColorSamples[namedColor]] = { topic: Color(namedColorSamples[namedColor]) }; spaces.forEach(function (space) { sub[space.toUpperCase() + ' hex string comparison'] = function (topic) { assert.equal(topic[space]().hex(), topic.hex()); }; /* sub[space.toUpperCase() + ' strict comparison'] = function (topic) { assert.ok(topic.equals(topic[space]())); };*/ }); }); return batch; } /* vows.describe('Color').addBatch({ 'base, debug': createTest('../one-color-debug'), 'base, minified': createTest('../one-color') }).export(module); */ spaces.push( 'cmyk', 'xyz'/*, 'lab'*/ ); vows.describe('Color-all').addBatch({ //'all, debug': createTest('../one-color-all-debug'), 'all, minified': createTest('../one-color-all') }).export(module); " Use state to load icons,"const {h, Component} = require('preact') const Location = require('../../modules/location') class SideBar extends Component { componentWillReceiveProps() { let icons = {} this.props.data.forEach(group => { group.locations.forEach(location => { let l = Location.resolve(location) l.getIcon((err, icon) => { icons[l.path] = icon this.setState({icons}) }) }) }) } render({data}, {icons = {}}) { return h('section', {class: 'side-bar'}, data.map(group => h('div', {class: 'group'}, [ h('h3', {}, group.label), h('ul', {}, group.locations.map(location => { let l = Location.resolve(location) let label = location.label || l.getName() return h('li', {}, [ h('img', {src: icons[l.path] || './img/blank.svg'}), label ]) })) ]) )) } } module.exports = SideBar ","const {h, Component} = require('preact') const Location = require('../../modules/location') class SideBar extends Component { render({data}) { return h('section', {class: 'side-bar'}, data.map(group => h('div', {class: 'group'}, [ h('h3', {}, group.label), h('ul', {}, group.locations.map(location => { let l = Location.resolve(location) let label = location.label || l.getName() return h('li', {}, [ h('img', { src: './img/blank.svg', ref: img => { if (!img) return l.getIcon((err, icon) => { if (err) return img.src = icon }) } }), label ]) })) ]) )) } } module.exports = SideBar " Resolve rules before making validation,"<?php namespace Laraplus\Form\Helpers; use Laraplus\Form\Form; use Illuminate\Contracts\Validation\Factory; use Illuminate\Contracts\Validation\Validator; trait FormBuilder { /** * @var Form */ protected $formBuilder = null; /** * @return Form */ public function getFormBuilder() { if ($this->formBuilder) { return $this->formBuilder; } $rules = method_exists($this, 'rules') ? $this->rules() : []; return $this->formBuilder = app('Laraplus\Form\Form')->rules($rules); } /** * Injects validator with rules and data if validation is required * * @param Factory $factory * * @return Validator */ public function validator(Factory $factory) { if (!$this->shouldBeValidated()) { return $factory->make([], []); } $rules = $this->container->call([$this, 'rules']); return $factory->make( $this->all(), $rules, $this->messages(), $this->attributes() ); } /** * Determines if the current request should be validated * * @return bool */ protected function shouldBeValidated() { return $this->method() != 'GET'; } } ","<?php namespace Laraplus\Form\Helpers; use Laraplus\Form\Form; use Illuminate\Contracts\Validation\Factory; use Illuminate\Contracts\Validation\Validator; trait FormBuilder { /** * @var Form */ protected $formBuilder = null; /** * @return Form */ public function getFormBuilder() { if ($this->formBuilder) { return $this->formBuilder; } $rules = method_exists($this, 'rules') ? $this->rules() : []; return $this->formBuilder = app('Laraplus\Form\Form')->rules($rules); } /** * Injects validator with rules and data if validation is required * * @param Factory $factory * * @return Validator */ public function validator(Factory $factory) { if (!$this->shouldBeValidated()) { return $factory->make([], []); } return $factory->make( $this->all(), $this->container->call([$this, 'rules']), $this->messages(), $this->attributes() ); } /** * Determines if the current request should be validated * * @return bool */ protected function shouldBeValidated() { return $this->method() != 'GET'; } } " Move the weapon roll from the modifiers to main properties,"define([], function(){ return { ""name"": { ""default"": ""New Item"", ""save"": true }, ""id"": { ""callback"": 0 }, ""selected"": { ""default"": false }, ""type"": { ""save"": true, ""default"": null, }, ""weapon"": { ""save"": true, ""default"": null }, ""modifiers"": { ""array"": [ { ""stat"": { ""save"": true, ""default"": ""hp"" }, ""amount"": { ""save"": true, ""default"": 0 }, ""spell"": { ""save"": true, ""default"": null } } ], ""save"": true } } });","define([], function(){ return { ""name"": { ""default"": ""New Item"", ""save"": true }, ""id"": { ""callback"": 0 }, ""selected"": { ""default"": false }, ""type"": { ""save"": true, ""default"": null, }, ""modifiers"": { ""array"": [ { ""stat"": { ""save"": true, ""default"": ""hp"" }, ""amount"": { ""save"": true, ""default"": 0 }, ""spell"": { ""save"": true, ""default"": null } } ], ""save"": true } } });" Add data getter to listcustomeremails,"<?php namespace Desk\Response\Customers; class ListCustomerEmails implements \ArrayAccess, \Iterator { protected $data; private $position = 0; public function __construct($data) { $this->data = $data; $this->position = 0; } public function getData() { return $this->data; } public function getAddresses() { return array_map(function ($item) { return $item['value']; }, $this->data); } public function offsetSet($offset, $value) { if (is_null($offset)) { $this->data[] = $value; } else { $this->data[$offset] = $value; } } public function offsetExists($offset) { return isset($this->data[$offset]); } public function offsetUnset($offset) { unset($this->data[$offset]); } public function offsetGet($offset) { return isset($this->data[$offset]) ? (object) $this->data[$offset] : null; } public function rewind() { $this->position = 0; } public function current() { return $this->data[$this->position]['value']; } public function key() { return $this->data[$this->position]['type']; } public function next() { ++$this->position; } public function valid() { return isset($this->data[$this->position]); } }","<?php namespace Desk\Response\Customers; class ListCustomerEmails implements \ArrayAccess, \Iterator { protected $data; private $position = 0; public function __construct($data) { $this->data = $data; $this->position = 0; } public function getAddresses() { return array_map(function ($item) { return $item['value']; }, $this->data); } public function offsetSet($offset, $value) { if (is_null($offset)) { $this->data[] = $value; } else { $this->data[$offset] = $value; } } public function offsetExists($offset) { return isset($this->data[$offset]); } public function offsetUnset($offset) { unset($this->data[$offset]); } public function offsetGet($offset) { return isset($this->data[$offset]) ? (object) $this->data[$offset] : null; } public function rewind() { $this->position = 0; } public function current() { return $this->data[$this->position]['value']; } public function key() { return $this->data[$this->position]['type']; } public function next() { ++$this->position; } public function valid() { return isset($this->data[$this->position]); } }" "Use a version of flask < 0.10 * Flask 0.10 has a bunch of changes which break nereid","#This file is part of Tryton & Nereid. The COPYRIGHT file at the top level of #this repository contains the full copyright notices and license terms. from setuptools import setup setup( name='Nereid', version='2.8.0.2', url='http://nereid.openlabs.co.in/docs/', license='GPLv3', author='Openlabs Technologies & Consulting (P) Limited', author_email='info@openlabs.co.in', description='Tryton - Web Framework', long_description=__doc__, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Tryton', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules', ], install_requires=[ 'distribute', 'flask<0.10', 'wtforms', 'wtforms-recaptcha', 'babel', 'speaklater', 'Flask-Babel', ], packages=[ 'nereid', 'nereid.contrib', 'nereid.tests', ], package_dir={ 'nereid': 'nereid', 'nereid.contrib': 'nereid/contrib', 'nereid.tests': 'tests', }, zip_safe=False, platforms='any', ) ","#This file is part of Tryton & Nereid. The COPYRIGHT file at the top level of #this repository contains the full copyright notices and license terms. from setuptools import setup setup( name='Nereid', version='2.8.0.2', url='http://nereid.openlabs.co.in/docs/', license='GPLv3', author='Openlabs Technologies & Consulting (P) Limited', author_email='info@openlabs.co.in', description='Tryton - Web Framework', long_description=__doc__, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Tryton', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules', ], install_requires=[ 'distribute', 'flask', 'wtforms', 'wtforms-recaptcha', 'babel', 'speaklater', 'Flask-Babel', ], packages=[ 'nereid', 'nereid.contrib', 'nereid.tests', ], package_dir={ 'nereid': 'nereid', 'nereid.contrib': 'nereid/contrib', 'nereid.tests': 'tests', }, zip_safe=False, platforms='any', ) " Set Boule defaultteamsize to 3,"/** * Boule presets: swiss as played in the PVO, round similar to chess, and ko * with a matched cadrage. Point-based rankings. * * @return Presets * @author Erik E. Lorenz <erik@tuvero.de> * @license MIT License * @see LICENSE */ define(function () { var Presets; Presets = { target: ""boule"", systems: { swiss: { ranking: [""wins"", ""buchholz"", ""finebuchholz"", ""headtohead"", ""saldo"", ""votes"" ], mode: ""wins"" }, ko: { mode: ""matched"" }, round: { ranking: [""wins"", ""sonneborn"", ""headtohead"", ""points""] }, placement: {}, poules: {} }, ranking: { components: [""buchholz"", ""finebuchholz"", ""points"", ""saldo"", ""sonneborn"", ""numgames"", ""wins"", ""headtohead"" ] }, registration: { defaultteamsize: 3, minteamsize: 1, maxteamsize: 3, teamsizeicon: true }, names: { playernameurl: """", dbplayername: ""bouleplayers"", apitoken: ""apitoken"", teamsfile: ""tuvero-anmeldungen.txt"" } }; return Presets; });","/** * Boule presets: swiss as played in the PVO, round similar to chess, and ko * with a matched cadrage. Point-based rankings. * * @return Presets * @author Erik E. Lorenz <erik@tuvero.de> * @license MIT License * @see LICENSE */ define(function () { var Presets; Presets = { target: ""boule"", systems: { swiss: { ranking: [""wins"", ""buchholz"", ""finebuchholz"", ""headtohead"", ""saldo"", ""votes"" ], mode: ""wins"" }, ko: { mode: ""matched"" }, round: { ranking: [""wins"", ""sonneborn"", ""headtohead"", ""points""] }, placement: {}, poules: {} }, ranking: { components: [""buchholz"", ""finebuchholz"", ""points"", ""saldo"", ""sonneborn"", ""numgames"", ""wins"", ""headtohead"" ] }, registration: { defaultteamsize: 1, minteamsize: 1, maxteamsize: 3, teamsizeicon: true }, names: { playernameurl: """", dbplayername: ""bouleplayers"", apitoken: ""apitoken"", teamsfile: ""tuvero-anmeldungen.txt"" } }; return Presets; });" "Add operation parameter to recalls route Instead of having the operation parameter in the query string it optimizes for Restangular to have it as an action on the route.","'use strict'; var _ = require('lodash'), Promise = require('bluebird'); module.exports = ['data', function (data) { var filters = function (query) { var where = data.utils.rangeFilter('Year', query.start, query.end); return _.assign(where, data.utils.inFilter('Make', query.makes)); }; return { '/:operation?': { get: function (req) { return new Promise(function (resolve, reject) { var op = data.utils.operation(req.params), pagination = data.utils.pagination(req.query); switch (op) { case 'count': data.Recall.count(filters(req.query)).exec(function (err, count) { if (err) { reject(err); return; } resolve([200, undefined, { count: count }]); }); break; default: var query = data.Recall.find(filters(req.query)); if (pagination) { query.skip(pagination.from).limit(pagination.limit); } query.exec(function (err, recalls) { if (err) { reject(err); return; } resolve([200, undefined, recalls]); }); break; } }); } } }; }];","'use strict'; var _ = require('lodash'), Promise = require('bluebird'); module.exports = ['data', function (data) { var filters = function (query) { var where = data.utils.rangeFilter('Year', query.start, query.end); return _.assign(where, data.utils.inFilter('Make', query.makes)); }; return { '/': { get: function (req) { return new Promise(function (resolve, reject) { var op = data.utils.operation(req.query), pagination = data.utils.pagination(req.query); switch (op) { case 'count': data.Recall.count(filters(req.query)).exec(function (err, count) { if (err) { reject(err); return; } resolve([200, undefined, { count: count }]); }); break; default: var query = data.Recall.find(filters(req.query)); if (pagination) { query.skip(pagination.from).limit(pagination.limit); } query.exec(function (err, recalls) { if (err) { reject(err); return; } resolve([200, undefined, recalls]); }); break; } }); } } }; }];" "Fix agent creation configuration to make tests great again lint","import unittest import craft_ai from . import settings from .utils import generate_entity_id from .data import valid_data class TestListGenerators(unittest.TestCase): """"""Checks that the client succeeds when getting an agent with OK input"""""" @classmethod def setUpClass(cls): cls.client = craft_ai.Client(settings.CRAFT_CFG) cls.n_generators = 5 cls.generators_id = [ generate_entity_id(""list_generators"") for i in range(cls.n_generators) ] cls.agent_id = generate_entity_id(""list_generators_agent"") def setUp(self): self.client.delete_agent(self.agent_id) self.client.create_agent(valid_data.VALID_CONFIGURATION, self.agent_id) for generators_id in self.generators_id: self.client.delete_generator(generators_id) self.client.create_generator( valid_data.VALID_GENERATOR_CONFIGURATION, generators_id ) def tearDown(self): # Makes sure that no generator with the standard ID remains for generator_id in self.generators_id: self.client.delete_generator(generator_id) self.client.delete_agent(self.agent_id) def test_list_generators(self): """"""list_generators should returns the list of generators in the current project."""""" generators_list = self.client.list_generators() self.assertIsInstance(generators_list, list) for generator_id in self.generators_id: self.assertTrue(generator_id in generators_list) ","import unittest import craft_ai from . import settings from .utils import generate_entity_id from .data import valid_data class TestListGenerators(unittest.TestCase): """"""Checks that the client succeeds when getting an agent with OK input"""""" @classmethod def setUpClass(cls): cls.client = craft_ai.Client(settings.CRAFT_CFG) cls.n_generators = 5 cls.generators_id = [ generate_entity_id(""list_generators"") for i in range(cls.n_generators) ] cls.agent_id = generate_entity_id(""list_generators_agent"") def setUp(self): self.client.delete_agent(self.agent_id) self.client.create_agent( valid_data.VALID_GENERATOR_CONFIGURATION, self.agent_id ) for generators_id in self.generators_id: self.client.delete_generator(generators_id) self.client.create_generator( valid_data.VALID_GENERATOR_CONFIGURATION, generators_id ) def tearDown(self): # Makes sure that no generator with the standard ID remains for generator_id in self.generators_id: self.client.delete_generator(generator_id) self.client.delete_agent(self.agent_id) def test_list_generators(self): """"""list_generators should returns the list of generators in the current project."""""" generators_list = self.client.list_generators() self.assertIsInstance(generators_list, list) for generator_id in self.generators_id: self.assertTrue(generator_id in generators_list) " Patch event listener for 5.4 support,"<?php namespace Caffeinated\Repository\Listeners; use Caffeinated\Repository\Contracts\Repository; class RepositoryEventListener { /** * Register the listeners for the subscriber. * * @param Illuminate\Events\Dispatcher $events */ public function subscribe($events) { $events->listen('*.entity.created', __CLASS__.'@entityCreated'); $events->listen('*.entity.updated', __CLASS__.'@entityUpdated'); $events->listen('*.entity.deleted', __CLASS__.'@entityDeleted'); } /** * Listen for the *.entity.created event. * * @param Repository $repository * @param mixed $entity * * @return void */ public function entityCreated($event, $data) { $repository = $data[0]; $repository->flushCache(); } /** * Listen for the *.entity.updated event. * * @param Repository $repository * @param mixed $entity * * @return void */ public function entityUpdated($event, $data) { $repository = $data[0]; $repository->flushCache(); } /** * Listen for the *.entity.deleted event. * * @param Repository $repository * @param mixed $entity * * @return void */ public function entityDeleted($event, $data) { $repository = $data[0]; $repository->flushCache(); } } ","<?php namespace Caffeinated\Repository\Listeners; use Caffeinated\Repository\Contracts\Repository; class RepositoryEventListener { /** * Register the listeners for the subscriber. * * @param Illuminate\Events\Dispatcher $events */ public function subscribe($events) { $events->listen('*.entity.created', __CLASS__.'@entityCreated'); $events->listen('*.entity.updated', __CLASS__.'@entityUpdated'); $events->listen('*.entity.deleted', __CLASS__.'@entityDeleted'); } /** * Listen for the *.entity.created event. * * @param Repository $repository * @param mixed $entity * * @return void */ public function entityCreated(Repository $repository, $entity) { $repository->flushCache(); } /** * Listen for the *.entity.updated event. * * @param Repository $repository * @param mixed $entity * * @return void */ public function entityUpdated(Repository $repository, $entity) { $repository->flushCache(); } /** * Listen for the *.entity.deleted event. * * @param Repository $repository * @param mixed $entity * * @return void */ public function entityDeleted(Repository $repository, $entity) { $repository->flushCache(); } } " Use transform instead of left/top CSS properties,"import React, { Component, PropTypes } from 'react' import { Spring } from 'react-motion' import { COLS } from '../constants/Board' const TILE_SIZE = 60 const basicStyles = { position: 'absolute', border: '1px solid', width: TILE_SIZE, height: TILE_SIZE } export default class Tile extends Component { static propTypes = { type: PropTypes.number.isRequired, position: PropTypes.number.isRequired, onClickCb: PropTypes.func } onClick(position) { if (this.props.onClickCb) { this.props.onClickCb(position) } } getLeftValue(position) { return (position % COLS) * TILE_SIZE } getTopValue(position) { return (Math.ceil((position + 1) / COLS) - 1) * TILE_SIZE } render() { const {type, position} = this.props return ( <Spring endValue={{val: {left: this.getLeftValue(position), top: this.getTopValue(position)}}} > {interpolated => <div style={{ ...basicStyles, opacity: type <= 0 ? 0.1 : 1, transform: `translate(${interpolated.val.left}px, ${interpolated.val.top}px)` }} onClick={this.onClick.bind(this, position)} >{type}</div> } </Spring> ) } } ","import React, { Component, PropTypes } from 'react' import { Spring } from 'react-motion' import { COLS } from '../constants/Board' const TILE_SIZE = 60 const basicStyles = { position: 'absolute', border: '1px solid', width: TILE_SIZE, height: TILE_SIZE } export default class Tile extends Component { static propTypes = { type: PropTypes.number.isRequired, position: PropTypes.number.isRequired, onClickCb: PropTypes.func } onClick(position) { if (this.props.onClickCb) { this.props.onClickCb(position) } } getLeftValue(position) { return (position % COLS) * TILE_SIZE } getTopValue(position) { return (Math.ceil((position + 1) / COLS) - 1) * TILE_SIZE } render() { const {type, position} = this.props return ( <Spring endValue={{val: {left: this.getLeftValue(position), top: this.getTopValue(position)}}} > {interpolated => <div style={{ ...basicStyles, opacity: type <= 0 ? 0.1 : 1, top: interpolated.val.top, left: interpolated.val.left }} onClick={this.onClick.bind(this, position)} >{type}</div> } </Spring> ) } } " Change Footer report link to issues,"import React, { Component } from ""react"" import styles from ""./index.css"" import logo from ""./evilmartians.svg"" export default class Footer extends Component { render() { return ( <footer className={ styles.root } role=""contentinfo""> <div className={ styles.inner }> <div className={ styles.info }> <p className={ styles.license }> { ""Distributed under the MIT License."" } </p> <p className={ styles.issue }>{ ""Found an issue?"" } <a className={ styles.report } href=""https://github.com/postcss/postcss.org/issues"" > { ""Report it!"" } </a> </p> </div> <div className={ styles.logo }> <img alt=""Evil Martians Logo"" className={ styles.logoInner } src={ logo } /> </div> </div> </footer> ) } } ","import React, { Component } from ""react"" import styles from ""./index.css"" import logo from ""./evilmartians.svg"" export default class Footer extends Component { render() { return ( <footer className={ styles.root } role=""contentinfo""> <div className={ styles.inner }> <div className={ styles.info }> <p className={ styles.license }> { ""Distributed under the MIT License."" } </p> <p className={ styles.issue }>{ ""Found an issue?"" } <a className={ styles.report } href=""https://github.com/postcss/postcss.org"" > { ""Report it!"" } </a> </p> </div> <div className={ styles.logo }> <img alt=""Evil Martians Logo"" className={ styles.logoInner } src={ logo } /> </div> </div> </footer> ) } } " Set file permissions for app.,"<?php umask('0022'); use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new Symfony\Bundle\DoctrineBundle\DoctrineBundle(), new Symfony\Bundle\AsseticBundle\AsseticBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Acme\DemoBundle\AcmeDemoBundle(); $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); } return $bundles; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); } } ","<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new Symfony\Bundle\DoctrineBundle\DoctrineBundle(), new Symfony\Bundle\AsseticBundle\AsseticBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Acme\DemoBundle\AcmeDemoBundle(); $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); } return $bundles; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); } } " Change logging to use print because of logger configuration error,"# -*- coding: utf-8 -*- import ConfigParser import logging class PropertiesParser(object): """"""Parse a java like properties file Parser wrapping around ConfigParser allowing reading of java like properties file. Based on stackoverflow example: https://stackoverflow.com/questions/2819696/parsing-properties-file-in-python/2819788#2819788 Example usage ------------- >>> pp = PropertiesParser() >>> props = pp.parse('/home/kola/configfiles/dev/application.properties') >>> print props """""" def __init__(self): self.secheadname = 'fakeSectionHead' self.sechead = '[' + self.secheadname + ']\n' #self.logger = logging.getLogger(__name__) def readline(self): if self.sechead: try: return self.sechead finally: self.sechead = None else: return self.fp.readline() def parse(self, filepath): """"""Parse file containing java like properties."""""" try: self.fp = open(filepath) cp = ConfigParser.SafeConfigParser() cp.readfp(self) self.fp.close() # reset the section head incase the parser will be used again self.sechead = '[' + self.secheadname + ']\n' return cp.items(self.secheadname) except Exception as e: #self.logger.error(""Problem parsing "" + filepath + "". Error message: "" + str(e)) print ""Problem parsing "" + filepath + "". Error message: "" + str(e) return {} ","# -*- coding: utf-8 -*- import ConfigParser import logging class PropertiesParser(object): """"""Parse a java like properties file Parser wrapping around ConfigParser allowing reading of java like properties file. Based on stackoverflow example: https://stackoverflow.com/questions/2819696/parsing-properties-file-in-python/2819788#2819788 Example usage ------------- >>> pp = PropertiesParser() >>> props = pp.parse('/home/kola/configfiles/dev/application.properties') >>> print props """""" def __init__(self): self.secheadname = 'fakeSectionHead' self.sechead = '[' + self.secheadname + ']\n' self.logger = logging.getLogger(__name__) def readline(self): if self.sechead: try: return self.sechead finally: self.sechead = None else: return self.fp.readline() def parse(self, filepath): """"""Parse file containing java like properties."""""" try: self.fp = open(filepath) cp = ConfigParser.SafeConfigParser() cp.readfp(self) self.fp.close() # reset the section head incase the parser will be used again self.sechead = '[' + self.secheadname + ']\n' return cp.items(self.secheadname) except Exception as e: self.logger.error(""Problem parsing "" + filepath + "". Error message: "" + str(e)) return {} " "Raise ValueError explicitly from __call__ rather than with super() because super() would make another lookup, but we already know the value isn't there.","from enum import Enum, EnumMeta from functools import total_ordering class _MultiValueMeta(EnumMeta): def __init__(self, cls, bases, classdict): # make sure we only have tuple values, not single values for member in self.__members__.values(): if not isinstance(member.value, tuple): raise TypeError('{} = {!r}, should be tuple!' .format(member.name, member.value)) def __call__(cls, value): """"""Return the appropriate instance with any of the values listed."""""" for member in cls: if value in member.value: return member else: raise ValueError(""%s is not a valid %s"" % (value, cls.__name__)) class MultiValueEnum(Enum, metaclass=_MultiMeta): """"""Enum subclass where members are declared as tuples."""""" @total_ordering class OrderableMixin: """"""Mixin for comparable Enums. The order is the definition order from smaller to bigger. """""" def __eq__(self, other): if self.__class__ is other.__class__: return self.value == other.value return NotImplemented def __lt__(self, other): if self.__class__ is other.__class__: names = self.__class__._member_names_ return names.index(self.name) < names.index(other.name) return NotImplemented ","from enum import Enum, EnumMeta from functools import total_ordering class _MultiValueMeta(EnumMeta): def __init__(self, cls, bases, classdict): # make sure we only have tuple values, not single values for member in self.__members__.values(): if not isinstance(member.value, tuple): raise TypeError('{} = {!r}, should be tuple!' .format(member.name, member.value)) def __call__(cls, value): """"""Return the appropriate instance with any of the values listed."""""" for member in cls: if value in member.value: return member # raise ValueError otherwise return super().__call__(value) class MultiValueEnum(Enum, metaclass=_MultiMeta): """"""Enum subclass where members are declared as tuples."""""" @total_ordering class OrderableMixin: """"""Mixin for comparable Enums. The order is the definition order from smaller to bigger. """""" def __eq__(self, other): if self.__class__ is other.__class__: return self.value == other.value return NotImplemented def __lt__(self, other): if self.__class__ is other.__class__: names = self.__class__._member_names_ return names.index(self.name) < names.index(other.name) return NotImplemented " Fix silly prefix change on this branch so that it won't affect master again,"# coding: utf-8 """""" Created on 2016-08-23 @author: naoey """""" VERSION = ""0.0.3"" BOT_PREFIX = "","" PATHS = { ""logs_dir"": ""./../logs/"", ""database"": ""./../slash_bot.db"", ""discord_creds"": ""./../private/discord.json"", ""rito_creds"": ""./../private/rito.json"", ""assets"": ""./../assets/"", } MODULES = { ""League of Legends"": { ""location"": ""games.lol"", ""class"": ""LeagueOfLegends"", ""active"": True, ""prefix"": ""lol"", ""config"": { ""static_refresh_interval"": { ""value"": ""604800"", ""description"": ""The time interval in seconds before refreshing static data"" } } }, ""osu!"": { ""location"": ""games.osu.Osu"", ""class"": ""Osu"", ""active"": False, ""prefix"": ""osu"", ""config"": {}, }, ""MyAnimeList"": { ""location"": ""anime.mal.MyAnimeList"", ""class"": ""MyAnimeList"", ""active"": False, ""prefix"": ""mal"", ""config"": {}, }, } API_LIMITS = { ""riot"": { ""10"": ""10"", ""600"": ""500"", } } GLOBAL = { } DISCORD_STATUS_ITER = [ ""procrastination \(^-^)/"", ] ","# coding: utf-8 """""" Created on 2016-08-23 @author: naoey """""" VERSION = ""0.0.3"" BOT_PREFIX = "":"" PATHS = { ""logs_dir"": ""./../logs/"", ""database"": ""./../slash_bot.db"", ""discord_creds"": ""./../private/discord.json"", ""rito_creds"": ""./../private/rito.json"", ""assets"": ""./../assets/"", } MODULES = { ""League of Legends"": { ""location"": ""games.lol"", ""class"": ""LeagueOfLegends"", ""active"": True, ""prefix"": ""lol"", ""config"": { ""static_refresh_interval"": { ""value"": ""604800"", ""description"": ""The time interval in seconds before refreshing static data"" } } }, ""osu!"": { ""location"": ""games.osu.Osu"", ""class"": ""Osu"", ""active"": False, ""prefix"": ""osu"", ""config"": {}, }, ""MyAnimeList"": { ""location"": ""anime.mal.MyAnimeList"", ""class"": ""MyAnimeList"", ""active"": False, ""prefix"": ""mal"", ""config"": {}, }, } API_LIMITS = { ""riot"": { ""10"": ""10"", ""600"": ""500"", } } GLOBAL = { } DISCORD_STATUS_ITER = [ ""procrastination \(^-^)/"", ] " Make the throttle time configurable,"import { get } from '@ember/object'; import RSVP from 'rsvp'; import { task } from 'ember-concurrency'; import wait from 'nomad-ui/utils/wait'; export function watchRecord(modelName) { return task(function*(id, throttle = 2000) { id = get(id, 'id') || id; while (true) { try { yield RSVP.all([ this.get('store').findRecord(modelName, id, { reload: true, adapterOptions: { watch: true }, }), wait(throttle), ]); } catch (e) { yield e; break; } } }); } export function watchRelationship(staticRelationshipName) { return task(function*(model, throttle = 2000) { while (true) { try { yield RSVP.all([ this.get('store') .adapterFor(model.constructor.modelName) .reloadRelationship(model, staticRelationshipName, true), wait(throttle), ]); } catch (e) { yield e; break; } } }); } export function watchAll(modelName) { return task(function*(throttle = 2000) { while (true) { try { yield RSVP.all([ this.get('store').findAll(modelName, { reload: true, adapterOptions: { watch: true } }), wait(throttle), ]); } catch (e) { yield e; break; } } }); } ","import { get } from '@ember/object'; import RSVP from 'rsvp'; import { task } from 'ember-concurrency'; import wait from 'nomad-ui/utils/wait'; export function watchRecord(modelName) { return task(function*(id) { id = get(id, 'id') || id; while (true) { try { yield RSVP.all([ this.store.findRecord(modelName, id, { reload: true, adapterOptions: { watch: true } }), wait(2000), ]); } catch (e) { yield e; break; } } }); } export function watchRelationship(staticRelationshipName) { return task(function*(model, throttle = 2000) { while (true) { try { yield RSVP.all([ this.get('store') .adapterFor(model.constructor.modelName) .reloadRelationship(model, staticRelationshipName, true), wait(throttle), ]); } catch (e) { yield e; break; } } }); } export function watchAll(modelName) { return task(function*(throttle = 2000) { while (true) { try { yield RSVP.all([ this.get('store').findAll(modelName, { reload: true, adapterOptions: { watch: true } }), wait(throttle), ]); } catch (e) { yield e; break; } } }); } " Hide currently bogus contact text,"@extends ('base') @section ('subheader') @stop @section ('content') <div class=""row""> <div class=""col-xs-12 col-md-8 col-md-offset-2""> <p> @lang('app.contact.info') </p> <ul class=""list-unstyled""> <li> <i class=""fa fa-github"" aria-hidden=""true""></i> <a href=""https://github.com/OParl"">GitHub</a> <p> @lang('app.contact.github') </p> </li> <li> <i class=""fa fa-sticky-note"" aria-hidden=""true""></i> <a href=""https://lists.okfn.org/mailman/listinfo/oparl-tech"">@OParl-Tech</a> <p> @lang('app.contact.mailinglist') </p> </li> {{--<li>--}} {{--<i class=""fa fa-info"" aria-hidden=""true""></i>--}} {{--<a href=""{{ route('contact.index') }}"">@lang('app.contact.form_info')</a>--}} {{--<p>--}} {{--@lang('app.contact.form')--}} {{--</p>--}} {{--</li>--}} </ul> </div> </div> @stop @section ('scripts') <script type=""text/javascript"" src=""{{ asset('js/developers.js') }}""></script> @stop ","@extends ('base') @section ('subheader') @stop @section ('content') <div class=""row""> <div class=""col-xs-12 col-md-8 col-md-offset-2""> <p> @lang('app.contact.info') </p> <ul class=""list-unstyled""> <li> <i class=""fa fa-github"" aria-hidden=""true""></i> <a href=""https://github.com/OParl"">GitHub</a> <p> @lang('app.contact.github') </p> </li> <li> <i class=""fa fa-sticky-note"" aria-hidden=""true""></i> <a href=""https://lists.okfn.org/mailman/listinfo/oparl-tech"">@OParl-Tech</a> <p> @lang('app.contact.mailinglist') </p> </li> <li> <i class=""fa fa-info"" aria-hidden=""true""></i> <a href=""{{ route('contact.index') }}"">@lang('app.contact.form_info')</a> <p> @lang('app.contact.form') </p> </li> </ul> </div> </div> @stop @section ('scripts') <script type=""text/javascript"" src=""{{ asset('js/developers.js') }}""></script> @stop " Fix issue causing api to connect to incorrect mail host,"import nodemailer from 'nodemailer' import Mailgen from 'mailgen' import path from 'path' import config from '../config' /** * Class for managing sending emails */ export default class Mail { /** * Create a mail sender class instance */ constructor () { this.transporter = nodemailer.createTransport({ host: config.smtp.hostname, port: config.smtp.port }) this.mailgen = new Mailgen({ theme: { path: path.resolve('static/mailgen/index.html'), plaintextPath: path.resolve('static/mailgen/index.txt') }, product: { name: 'The Fuel Rats', link: 'https://fuelrats.com/', logo: 'https://wordpress.fuelrats.com/wp-content/uploads/2018/09/email.jpg' } }) } /** * Send an email * @param {object} arg function arguments object * @param {string} arg.to the email recipient * @param {string } arg.subject the email subject * @param {object} arg.body mailgen body configuration * @returns {Promise<void>} fulfills a promise when successful */ async send ({ to: recipient, subject, body }) { const email = { body } await this.transporter.sendMail({ from: 'Fuel Rats (Do Not Reply) <blackhole@fuelrats.com>', to: recipient, subject, text: this.mailgen.generatePlaintext(email), html: this.mailgen.generate(email) }) } } ","import nodemailer from 'nodemailer' import Mailgen from 'mailgen' import path from 'path' import config from '../config' /** * Class for managing sending emails */ export default class Mail { /** * Create a mail sender class instance */ constructor () { this.transporter = nodemailer.createTransport({ host: config.smtp.host, port: config.smtp.port }) this.mailgen = new Mailgen({ theme: { path: path.resolve('static/mailgen/index.html'), plaintextPath: path.resolve('static/mailgen/index.txt') }, product: { name: 'The Fuel Rats', link: 'https://fuelrats.com/', logo: 'https://wordpress.fuelrats.com/wp-content/uploads/2018/09/email.jpg' } }) } /** * Send an email * @param {object} arg function arguments object * @param {string} arg.to the email recipient * @param {string } arg.subject the email subject * @param {object} arg.body mailgen body configuration * @returns {Promise<void>} fulfills a promise when successful */ async send ({ to: recipient, subject, body }) { const email = { body } await this.transporter.sendMail({ from: 'Fuel Rats (Do Not Reply) <blackhole@fuelrats.com>', to: recipient, subject, text: this.mailgen.generatePlaintext(email), html: this.mailgen.generate(email) }) } } " Fix: Use the correct module path for the AmazonFPS app.,"from billing.integration import Integration from django.conf import settings from boto.fps.connection import FPSConnection FPS_PROD_API_ENDPOINT = ""fps.amazonaws.com"" FPS_SANDBOX_API_ENDPOINT = ""fps.sandbox.amazonaws.com"" class AmazonFpsIntegration(Integration): # TODO: Document the fields for each flow fields = {""transactionAmount"": """", ""pipelineName"": """", ""paymentReason"": """", ""returnURL"": """",} def __init__(self, options={}): self.aws_access_key = options.get(""aws_access_key"", None) or settings.AWS_ACCESS_KEY self.aws_secret_access_key = options.get(""aws_secret_access_key"", None) or settings.AWS_SECRET_ACCESS_KEY super(AmazonFpsIntegration, self).__init__(options=options) self.fps_connection = FPSConnection(self.aws_access_key, self.aws_secret_access_key, **options) @property def service_url(self): if self.test_mode: return FPS_SANDBOX_API_ENDPOINT return FPS_PROD_API_ENDPOINT @property def link_url(self): return self.fps_connection.make_url(self.fields[""returnURL""], self.fields[""paymentReason""], self.fields[""pipelineName""], self.fields[""transactionAmount""], **self.fields) ","from billing.integration import Integration from django.conf import settings from boto.connection import FPSConnection FPS_PROD_API_ENDPOINT = ""fps.amazonaws.com"" FPS_SANDBOX_API_ENDPOINT = ""fps.sandbox.amazonaws.com"" class AmazonFpsIntegration(Integration): # TODO: Document the fields for each flow fields = {""transactionAmount"": """", ""pipelineName"": """", ""paymentReason"": """", ""returnURL"": """",} def __init__(self, options={}): self.aws_access_key = options.get(""aws_access_key"", None) or settings.AWS_ACCESS_KEY self.aws_secret_access_key = options.get(""aws_secret_access_key"", None) or settings.AWS_SECRET_ACCESS_KEY super(AmazonFpsIntegration, self).__init__(options=options) self.fps_connection = FPSConnection(self.aws_access_key, self.aws_secret_access_key, **options) @property def service_url(self): if self.test_mode: return FPS_SANDBOX_API_ENDPOINT return FPS_PROD_API_ENDPOINT @property def link_url(self): return self.fps_connection.make_url(self.fields[""returnURL""], self.fields[""paymentReason""], self.fields[""pipelineName""], self.fields[""transactionAmount""], **self.fields) " Increase number of posts to preview to 6,"<div class=""panel panel-default qanda-panel""> <div class=""panel-heading""> <?php echo $group; ?> </div> <div class=""list-group""> <?php foreach($categories as $category) { ?> <?php if($category['subCategory']) { ?> <a href=""<?php echo $category['link']; ?>"" class=""list-group-item""> <b class=""list-group-item-heading""><?php echo $category['name']; ?></b> <p class=""list-group-item-text""><?php echo $category['description']; ?></p> </a> <?php } ?> <small> <ul> <?php $questions = \humhub\modules\questionanswer\models\Question::find() ->contentContainer($category['space']) ->andFilterWhere(['post_type' => 'question']) ->orderBy('created_at DESC') ->limit(6) ->all(); foreach($questions as $q) { echo ""<li>""; echo \yii\helpers\Html::a(\yii\helpers\Html::encode($q['post_title']), \humhub\modules\questionanswer\helpers\Url::createUrl('view', [ 'id'=> $q['id'], 'sguid' => $category['space']->guid ])); echo ""</li>""; } ?> </ul> </small> <?php } ?> </div> </div>","<div class=""panel panel-default qanda-panel""> <div class=""panel-heading""> <?php echo $group; ?> </div> <div class=""list-group""> <?php foreach($categories as $category) { ?> <?php if($category['subCategory']) { ?> <a href=""<?php echo $category['link']; ?>"" class=""list-group-item""> <b class=""list-group-item-heading""><?php echo $category['name']; ?></b> <p class=""list-group-item-text""><?php echo $category['description']; ?></p> </a> <?php } ?> <small> <ul> <?php $questions = \humhub\modules\questionanswer\models\Question::find() ->contentContainer($category['space']) ->andFilterWhere(['post_type' => 'question']) ->orderBy('created_at DESC') ->limit(3) ->all(); foreach($questions as $q) { echo ""<li>""; echo \yii\helpers\Html::a(\yii\helpers\Html::encode($q['post_title']), \humhub\modules\questionanswer\helpers\Url::createUrl('view', [ 'id'=> $q['id'], 'sguid' => $category['space']->guid ])); echo ""</li>""; } ?> </ul> </small> <?php } ?> </div> </div>" "Change reference to web token secret environment variable Refactor auth controller to return an instance of the authenticated user","var authController = (models, _validate, _h, jwt, co) => { var Authenticate = (req, res) => { _validate.validateAuthParams(req, function (err) { co(function* () { if (err) return res.status(400).json(err); // Authenticate a user // find the user var user = yield models.User.findOne({ $or: [{ username: req.body.login }, { email: req.body.login }] }).populate('role'); if (!user) { res.status(404).json({ success: false, message: 'Authentication failed. User not found.' }); } else if (user) { // check if password matches if (_h.comparePassword(req.body.password, user.hashedPass)) { // if user is found and password is right // create a token var options = { expiresIn: '24h' // expires in 24 hours from creation. }; jwt.sign(user, process.env.WEB_TOKEN_SECRET, options, (token) => { // return the information including token as JSON res.json({ success: true, message: 'Authentication successful!', user: user, token: token }); }); } else { res.status(401).json({ success: false, message: 'Authentication failed. Wrong password.' }); } } }); }); }; return Authenticate; }; module.exports = authController; ","var authController = (models, _validate, _h, jwt, co) => { var Authenticate = (req, res) => { _validate.validateAuthParams(req, function (err) { co(function* () { if (err) return res.status(400).json(err); // Authenticate a user // find the user var user = yield models.User.findOne({ $or: [{ username: req.body.login }, { email: req.body.login }] }).populate('role'); if (!user) { res.status(404).json({ success: false, message: 'Authentication failed. User not found.' }); } else if (user) { // check if password matches if (_h.comparePassword(req.body.password, user.hashedPass)) { // if user is found and password is right // create a token var options = { expiresIn: '24h' // expires in 24 hours from creation. }; jwt.sign(user, process.env.SECRET_KEY, options, (token) => { // return the information including token as JSON res.json({ success: true, message: 'Authentication successful. Enjoy your token!', token: token }); }); } else { res.status(401).json({ success: false, message: 'Authentication failed. Wrong password.' }); } } }); }); }; return Authenticate; }; module.exports = authController; " "Use __NAMESPACE__ because ::class won't work in php 5.3 Patched version of #64","<?php /* * This file is part of composer/semver. * * (c) Composer <https://github.com/composer> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Composer\Semver\Constraint; trigger_error('The ' . __NAMESPACE__ . '\AbstractConstraint abstract class is deprecated, there is no replacement for it, it will be removed in the next major version.', E_USER_DEPRECATED); /** * Base constraint class. */ abstract class AbstractConstraint implements ConstraintInterface { /** @var string */ protected $prettyString; /** * @param ConstraintInterface $provider * * @return bool */ public function matches(ConstraintInterface $provider) { if ($provider instanceof $this) { // see note at bottom of this class declaration return $this->matchSpecific($provider); } // turn matching around to find a match return $provider->matches($this); } /** * @param string $prettyString */ public function setPrettyString($prettyString) { $this->prettyString = $prettyString; } /** * @return string */ public function getPrettyString() { if ($this->prettyString) { return $this->prettyString; } return $this->__toString(); } // implementations must implement a method of this format: // not declared abstract here because type hinting violates parameter coherence (TODO right word?) // public function matchSpecific(<SpecificConstraintType> $provider); } ","<?php /* * This file is part of composer/semver. * * (c) Composer <https://github.com/composer> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Composer\Semver\Constraint; trigger_error('The ' . __CLASS__ . ' abstract class is deprecated, there is no replacement for it, it will be removed in the next major version.', E_USER_DEPRECATED); /** * Base constraint class. */ abstract class AbstractConstraint implements ConstraintInterface { /** @var string */ protected $prettyString; /** * @param ConstraintInterface $provider * * @return bool */ public function matches(ConstraintInterface $provider) { if ($provider instanceof $this) { // see note at bottom of this class declaration return $this->matchSpecific($provider); } // turn matching around to find a match return $provider->matches($this); } /** * @param string $prettyString */ public function setPrettyString($prettyString) { $this->prettyString = $prettyString; } /** * @return string */ public function getPrettyString() { if ($this->prettyString) { return $this->prettyString; } return $this->__toString(); } // implementations must implement a method of this format: // not declared abstract here because type hinting violates parameter coherence (TODO right word?) // public function matchSpecific(<SpecificConstraintType> $provider); } " Fix application menu missing first menu on macOS.,"import { app } from ""electron""; export default menus => { if (process.platform === ""darwin"") { menus.unshift({ label: app.getName(), submenu: [ { role: ""about"" }, { type: ""separator"" }, { role: ""services"", submenu: [] }, { type: ""separator"" }, { role: ""hide"" }, { role: ""hideothers"" }, { role: ""unhide"" }, { type: ""separator"" }, { role: ""quit"" } ] }); // Edit menu menus[1].submenu.push( { type: ""separator"" }, { label: ""Speech"", submenu: [{ role: ""startspeaking"" }, { role: ""stopspeaking"" }] } ); // Window menu menus[3].submenu = [ { role: ""close"" }, { role: ""minimize"" }, { role: ""zoom"" }, { type: ""separator"" }, { role: ""front"" } ]; } return menus; }; ","import { app } from ""electron""; export default menus => { if (process.platform !== ""darwin"") { menus.unshift({ label: app.getName(), submenu: [ { role: ""about"" }, { type: ""separator"" }, { role: ""services"", submenu: [] }, { type: ""separator"" }, { role: ""hide"" }, { role: ""hideothers"" }, { role: ""unhide"" }, { type: ""separator"" }, { role: ""quit"" } ] }); // Edit menu menus[1].submenu.push( { type: ""separator"" }, { label: ""Speech"", submenu: [{ role: ""startspeaking"" }, { role: ""stopspeaking"" }] } ); // Window menu menus[3].submenu = [ { role: ""close"" }, { role: ""minimize"" }, { role: ""zoom"" }, { type: ""separator"" }, { role: ""front"" } ]; } return menus; }; " Remove Alpha from dev status.,"import textwrap from setuptools import setup setup(name='dip', version='1.0.0b0', author='amancevice', author_email='smallweirdnum@gmail.com', packages=['dip'], url='http://www.smallweirdnumber.com', description='Install CLIs using docker-compose', long_description=textwrap.dedent( '''See GitHub_ for documentation. .. _GitHub: https://github.com/amancevice/dip'''), classifiers=['Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Topic :: Utilities', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python'], install_requires=['click>=6.7.0', 'colored>=1.3.4', 'docker-compose>=1.10.0', 'gitpython>=2.1.3'], entry_points={'console_scripts': ['dip=dip.main:dip']}) ","import textwrap from setuptools import setup setup(name='dip', version='1.0.0b0', author='amancevice', author_email='smallweirdnum@gmail.com', packages=['dip'], url='http://www.smallweirdnumber.com', description='Install CLIs using docker-compose', long_description=textwrap.dedent( '''See GitHub_ for documentation. .. _GitHub: https://github.com/amancevice/dip'''), classifiers=['Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Topic :: Utilities', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python'], install_requires=['click>=6.7.0', 'colored>=1.3.4', 'docker-compose>=1.10.0', 'gitpython>=2.1.3'], entry_points={'console_scripts': ['dip=dip.main:dip']}) " "Fix WSGI middleware to call close() on the iterable instead of checking if it's callable, and reraising the exception if one results as per spec. Also call sender correctly","import logging from raygun4py import raygunprovider log = logging.getLogger(__name__) class Provider(object): def __init__(self, app, apiKey): self.app = app self.sender = raygunprovider.RaygunSender(apiKey) def __call__(self, environ, start_response): if not self.sender: log.error(""Raygun-WSGI: Cannot send as provider not attached"") iterable = None try: iterable = self.app(environ, start_response) for event in iterable: yield event except Exception as e: request = self.build_request(environ) self.sender.send_exception(exception=e, request=request) raise finally: if hasattr(iterable, 'close'): try: iterable.close() except Exception as e: request = self.build_request(environ) self.sender.send_exception(exception=e, request=request) raise def build_request(self, environ): request = {} try: request = { 'httpMethod': environ['REQUEST_METHOD'], 'url': environ['PATH_INFO'], 'ipAddress': environ['REMOTE_ADDR'], 'hostName': environ['HTTP_HOST'].replace(' ', ''), 'queryString': environ['QUERY_STRING'], 'headers': {}, 'form': {}, 'rawData': {} } except Exception: pass for key, value in environ.items(): if key.startswith('HTTP_'): request['headers'][key] = value return request ","import logging from raygun4py import raygunprovider log = logging.getLogger(__name__) class Provider(object): def __init__(self, app, apiKey): self.app = app self.sender = raygunprovider.RaygunSender(apiKey) def __call__(self, environ, start_response): if not self.sender: log.error(""Raygun-WSGI: Cannot send as provider not attached"") try: chunk = self.app(environ, start_response) except Exception as e: request = self.build_request(environ) self.sender.send_exception(exception=e, request=request) raise try: for event in chunk: yield event except Exception as e: request = build_request(environ) self.sender.send_exception(exception=e, request=request) raise finally: if chunk and hasattr(chunk, 'close') and callable(chunk.close): try: chunk.close() except Exception as e: request = build_request(environ) self.send_exception(exception=e, request=request) def build_request(self, environ): request = {} try: request = { 'httpMethod': environ['REQUEST_METHOD'], 'url': environ['PATH_INFO'], 'ipAddress': environ['REMOTE_ADDR'], 'hostName': environ['HTTP_HOST'].replace(' ', ''), 'queryString': environ['QUERY_STRING'], 'headers': {}, 'form': {}, 'rawData': {} } except Exception: pass for key, value in environ.items(): if key.startswith('HTTP_'): request['headers'][key] = value return request " Remove Hungarian notation in fields,"package com.trevorhalvorson.actorflix; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; /** * Created by Trevor Halvorson on 12/30/2015. */ public class RecyclerViewItemClickListener implements RecyclerView.OnItemTouchListener { private OnItemClickListener clickListener; public interface OnItemClickListener { public void onItemClick(View view, int position); } GestureDetector gestureDetector; public RecyclerViewItemClickListener(Context context, OnItemClickListener listener) { clickListener = listener; gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { return true; } }); } @Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) { View childView = view.findChildViewUnder(e.getX(), e.getY()); if (childView != null && clickListener != null && gestureDetector.onTouchEvent(e)) { clickListener.onItemClick(childView, view.getChildAdapterPosition(childView)); } return false; } @Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { } }","package com.trevorhalvorson.actorflix; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; /** * Created by Trevor Halvorson on 12/30/2015. */ public class RecyclerViewItemClickListener implements RecyclerView.OnItemTouchListener { private OnItemClickListener mListener; public interface OnItemClickListener { public void onItemClick(View view, int position); } GestureDetector mGestureDetector; public RecyclerViewItemClickListener(Context context, OnItemClickListener listener) { mListener = listener; mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { return true; } }); } @Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) { View childView = view.findChildViewUnder(e.getX(), e.getY()); if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) { mListener.onItemClick(childView, view.getChildAdapterPosition(childView)); } return false; } @Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { } }" Fix value attribute name to _value,"""""""Kraken - objects.Attributes.IntegerAttribute module. Classes: IntegerAttribute - Base Attribute. """""" from number_attribute import NumberAttribute from kraken.core.kraken_system import ks class IntegerAttribute(NumberAttribute): """"""Float Attribute. Implemented value type checking and limiting."""""" def __init__(self, name, value=0, minValue=None, maxValue=None): super(IntegerAttribute, self).__init__(name, value, minValue=minValue, maxValue=maxValue) if minValue is None: if value < 0: self.setMin(value) else: self.setMin(0) if maxValue is None: if value == 0: self.setMax(10) else: self.setMax(value * 3) assert type(self._value) is int, ""Value is not of type 'int'."" def setValue(self, value): """"""Sets the value of the attribute. Arguments: value -- Value to set the attribute to. Return: True if successful. """""" if type(value) not in (int): raise TypeError(""Value is not of type 'int'."") if value < self._min: raise ValueError(""Value is less than attribute minimum."") elif value > self._max: raise ValueError(""Value is greater than attribute maximum."") super(IntegerAttribute, self).setValue(value) return True def getRTVal(self): """"""Returns and RTVal object for this attribute. Return: RTVal """""" return ks.rtVal('Integer', self._value) ","""""""Kraken - objects.Attributes.IntegerAttribute module. Classes: IntegerAttribute - Base Attribute. """""" from number_attribute import NumberAttribute from kraken.core.kraken_system import ks class IntegerAttribute(NumberAttribute): """"""Float Attribute. Implemented value type checking and limiting."""""" def __init__(self, name, value=0, minValue=None, maxValue=None): super(IntegerAttribute, self).__init__(name, value, minValue=minValue, maxValue=maxValue) if minValue is None: if value < 0: self.setMin(value) else: self.setMin(0) if maxValue is None: if value == 0: self.setMax(10) else: self.setMax(value * 3) assert type(self.value) is int, ""Value is not of type 'int'."" def setValue(self, value): """"""Sets the value of the attribute. Arguments: value -- Value to set the attribute to. Return: True if successful. """""" if type(value) not in (int): raise TypeError(""Value is not of type 'int'."") if value < self._min: raise ValueError(""Value is less than attribute minimum."") elif value > self._max: raise ValueError(""Value is greater than attribute maximum."") super(IntegerAttribute, self).setValue(value) return True def getRTVal(self): """"""Returns and RTVal object for this attribute. Return: RTVal """""" return ks.rtVal('Integer', self._value) " Fix typo: `OccurenceOrderPlugin` to `OccurrenceOrderPlugin`,"import webpack from 'webpack'; import ExtractTextPlugin from 'extract-text-webpack-plugin'; import baseConfig from './webpack.config.base'; const config = { ...baseConfig, devtool: 'source-map', entry: './app/index', output: { ...baseConfig.output, publicPath: '../dist/' }, module: { ...baseConfig.module, loaders: [ ...baseConfig.module.loaders, { test: /\.global\.css$/, loader: ExtractTextPlugin.extract( 'style-loader', 'css-loader' ) }, { test: /^((?!\.global).)*\.css$/, loader: ExtractTextPlugin.extract( 'style-loader', 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]' ) } ] }, plugins: [ ...baseConfig.plugins, new webpack.optimize.OccurrenceOrderPlugin(), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }), new webpack.optimize.UglifyJsPlugin({ compressor: { screw_ie8: true, warnings: false } }), new ExtractTextPlugin('style.css', { allChunks: true }) ], target: 'electron-renderer' }; export default config; ","import webpack from 'webpack'; import ExtractTextPlugin from 'extract-text-webpack-plugin'; import baseConfig from './webpack.config.base'; const config = { ...baseConfig, devtool: 'source-map', entry: './app/index', output: { ...baseConfig.output, publicPath: '../dist/' }, module: { ...baseConfig.module, loaders: [ ...baseConfig.module.loaders, { test: /\.global\.css$/, loader: ExtractTextPlugin.extract( 'style-loader', 'css-loader' ) }, { test: /^((?!\.global).)*\.css$/, loader: ExtractTextPlugin.extract( 'style-loader', 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]' ) } ] }, plugins: [ ...baseConfig.plugins, new webpack.optimize.OccurenceOrderPlugin(), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }), new webpack.optimize.UglifyJsPlugin({ compressor: { screw_ie8: true, warnings: false } }), new ExtractTextPlugin('style.css', { allChunks: true }) ], target: 'electron-renderer' }; export default config; " Remove placeholder for amount to prevent confusion,"<?php namespace Intracto\SecretSantaBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Intracto\SecretSantaBundle\Form\EntryType; class PoolType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('message') ->add( 'entries', 'collection', array( 'type' => new EntryType(), 'allow_add' => true, 'allow_delete' => true, 'by_reference' => false, ) ) ->add( 'date', 'genemu_jquerydate', array( 'widget' => 'single_text', 'attr' => array('placeholder' => date('Y') . '-12-23'), 'label' => 'Date of your Secret Santa party', ) ) ->add( 'amount', 'text', array( 'label' => 'Amount to spend', ) ); } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults( array( 'data_class' => 'Intracto\SecretSantaBundle\Entity\Pool' ) ); } public function getName() { return 'intracto_secretsantabundle_pooltype'; } } ","<?php namespace Intracto\SecretSantaBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Intracto\SecretSantaBundle\Form\EntryType; class PoolType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('message') ->add( 'entries', 'collection', array( 'type' => new EntryType(), 'allow_add' => true, 'allow_delete' => true, 'by_reference' => false, ) ) ->add( 'date', 'genemu_jquerydate', array( 'widget' => 'single_text', 'attr' => array('placeholder' => date('Y') . '-12-23'), 'label' => 'Date of your Secret Santa party', ) ) ->add( 'amount', 'text', array( 'attr' => array('placeholder' => '15 EUR'), 'label' => 'Amount to spend', ) ); } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults( array( 'data_class' => 'Intracto\SecretSantaBundle\Entity\Pool' ) ); } public function getName() { return 'intracto_secretsantabundle_pooltype'; } } " Add nonce in FB callback," <?php echo $head; ?> <div class=""centered-row""> <div class=""l-box""> <h2><?php echo _('Facebook login successful!') ?></h2> </div> </div> <div class=""pure-g centered-row""> <div class=""pure-u-1 pure-u-md-1-2""> <div class=""l-box""> <p> <?php echo _('The last step.'); echo ' '; echo _('You can add a message to your check-in.'); echo ' '; ?> </p> </div> </div> <div class=""pure-u-1 pure-u-md-1-2""> <div class=""l-box""> <p> <form class=""pure-form pure-form-stacked"" action=""<?php echo $post_action; ?>""> <fieldset> <legend><?php echo _('Check In'); ?></legend> <label for=""text_fb_message""><?php echo _('Message'); ?></label> <textarea rows=""2"" name=""message"" id=""text_fb_message"" placeholder=""<?php echo _('Optional');?>""></textarea> <input type=""hidden"" name=""nonce"" id=""fb_message_nonce"" value=""<?php echo $nonce; ?>""/> <button type=""submit"" class=""pure-button pure-button-primary""> <i class=""fa fa-facebook-official fa-lg""></i> <?php echo _('Check in to') . ' ' .$place_name; ?> </button> </fieldset> </form> </p> </div> </div> </div> <?php echo $back_to_code_widget ?> <?php echo $foot; ?> "," <?php echo $head; ?> <div class=""centered-row""> <div class=""l-box""> <h2><?php echo _('Facebook login successful!') ?></h2> </div> </div> <div class=""pure-g centered-row""> <div class=""pure-u-1 pure-u-md-1-2""> <div class=""l-box""> <p> <?php echo _('The last step.'); echo ' '; echo _('You can add a message to your check-in.'); echo ' '; ?> </p> </div> </div> <div class=""pure-u-1 pure-u-md-1-2""> <div class=""l-box""> <p> <form class=""pure-form pure-form-stacked"" action=""<?php echo $post_action; ?>""> <fieldset> <legend><?php echo _('Check In'); ?></legend> <label for=""text_fb_message""><?php echo _('Message'); ?></label> <textarea rows=""2"" name=""message"" id=""text_fb_message"" placeholder=""<?php echo _('Optional');?>""></textarea> <button type=""submit"" class=""pure-button pure-button-primary""> <i class=""fa fa-facebook-official fa-lg""></i> <?php echo _('Check in to') . ' ' .$place_name; ?> </button> </fieldset> </form> </p> </div> </div> </div> <?php echo $back_to_code_widget ?> <?php echo $foot; ?> " Correct Author string in module,""""""""" Introduction Adventure Author: Ignacio Avas (iavas@sophilabs.com) """""" import codecs import io import sys import unittest from story.adventures import AdventureVerificationError, BaseAdventure from story.translation import gettext as _ class TestOutput(unittest.TestCase): ""Introduction Adventure test"" def __init__(self, sourcefile): ""Inits the test"" super(TestOutput, self).__init__() self.sourcefile = sourcefile def setUp(self): self.__old_stdout = sys.stdout sys.stdout = self.__mockstdout = io.StringIO() def tearDown(self): sys.stdout = self.__old_stdout self.__mockstdout.close() @staticmethod def mock_print(stringy): ""Mock function"" pass def runTest(self): ""Makes a simple test of the output"" raw_program = codecs.open(self.sourcefile).read() code = compile(raw_program, self.sourcefile, 'exec', optimize=0) exec(code) self.assertEqual( self.__mockstdout.getvalue().lower().strip(), 'hello world', ""Should have printed 'Hello World'"" ) class Adventure(BaseAdventure): ""Introduction Adventure"" title = _('Introduction') @classmethod def test(cls, sourcefile): ""Test against the provided file"" suite = unittest.TestSuite() suite.addTest(TestOutput(sourcefile)) result = unittest.TextTestRunner().run(suite) if not result.wasSuccessful(): raise AdventureVerificationError() ",""""""""" Introduction Adventure Author: igui """""" import codecs import io import sys import unittest from story.adventures import AdventureVerificationError, BaseAdventure from story.translation import gettext as _ class TestOutput(unittest.TestCase): ""Introduction Adventure test"" def __init__(self, sourcefile): ""Inits the test"" super(TestOutput, self).__init__() self.sourcefile = sourcefile def setUp(self): self.__old_stdout = sys.stdout sys.stdout = self.__mockstdout = io.StringIO() def tearDown(self): sys.stdout = self.__old_stdout self.__mockstdout.close() @staticmethod def mock_print(stringy): ""Mock function"" pass def runTest(self): ""Makes a simple test of the output"" raw_program = codecs.open(self.sourcefile).read() code = compile(raw_program, self.sourcefile, 'exec', optimize=0) exec(code) self.assertEqual( self.__mockstdout.getvalue().lower().strip(), 'hello world', ""Should have printed 'Hello World'"" ) class Adventure(BaseAdventure): ""Introduction Adventure"" title = _('Introduction') @classmethod def test(cls, sourcefile): ""Test against the provided file"" suite = unittest.TestSuite() suite.addTest(TestOutput(sourcefile)) result = unittest.TextTestRunner().run(suite) if not result.wasSuccessful(): raise AdventureVerificationError() " Fix bookmark adding and removing,"<?php class Bookmarks_Controller extends List_Controller { protected $view = 'interface.bookmarks'; protected $viewdata = array ( 'recordToolbarView' => 'components.result-toolbar-common', 'recordPaneView' => 'components.bookmarksrecordpane' ); public function __construct() { parent::__construct(); $this->records = new Bookmarks(); $this->records->autosave = true; } public function post_add($record = null) { return json_encode( array( 'message' => __('bookmarks.' . $this->records->add($record) . 'flash')->get(), 'count' => $this->records->size() ) ); } public function get_add($record = null) { $this->records->add($record); return Redirect::to('bookmarks'); } public function post_delete($record = null) { return json_encode( array( 'message' => __('bookmarks.' . $this->records->remove($record) . 'flash')->get(), 'count' => $this->records->size() ) ); } public function get_delete($record = null) { $this->records->remove($record); return Redirect::to('bookmarks'); } } ","<?php class Bookmarks_Controller extends List_Controller { protected $view = 'interface.bookmarks'; protected $viewdata = array ( 'recordToolbarView' => 'components.result-toolbar-common', 'recordPaneView' => 'components.bookmarksrecordpane' ); public function __construct() { parent::__construct(); $this->records = new Bookmarks(); $this->records->autosave = true; } public function post_add($record = null) { return json_encode( array( 'message' => __('bookmarks.' . $this->bookmarks->add($record) . 'flash')->get(), 'count' => $this->bookmarks->size() ) ); } public function get_add($record = null) { $this->bookmarks->add($record); return Redirect::to('bookmarks'); } public function post_delete($record = null) { return json_encode( array( 'message' => __('bookmarks.' . $this->bookmarks->remove($record) . 'flash')->get(), 'count' => $this->bookmarks->size() ) ); } public function get_delete($record = null) { $this->bookmarks->remove($record); return Redirect::to('bookmarks'); } } " Fix error when no questions,"<?php namespace Egzaminer\Question; use Egzaminer\Model; use PDO; class Answers extends Model { public function getAnswersByQuestions(array $answers) { if (empty($answers)) { return; } $where = ''; foreach ($answers as $key => $value) { $where .= ' OR question_id = :question_id_'.md5($value['id']); } $stmt = $this->db->prepare('SELECT * FROM answers WHERE '.trim($where, ' OR ')); foreach ($answers as $key => $value) { $stmt->bindValue(':question_id_'.md5($value['id']), $value['id'], PDO::PARAM_INT); } $stmt->execute(); $array = []; foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $key => $value) { $array[$value['question_id']][] = $value; } if (!isset($array)) { return; } return $array; } public function getAnswersByOneQuestionId($id) { $stmt = $this->db->prepare('SELECT * FROM answers WHERE question_id = :qid'); $stmt->bindValue(':qid', $id, PDO::PARAM_INT); $stmt->execute(); return $stmt->fetchAll(PDO::FETCH_ASSOC); } } ","<?php namespace Egzaminer\Question; use Egzaminer\Model; use PDO; class Answers extends Model { public function getAnswersByQuestions($answers) { $where = ''; foreach ($answers as $key => $value) { $where .= ' OR question_id = :question_id_'.md5($value['id']); } $stmt = $this->db->prepare('SELECT * FROM answers WHERE '.trim($where, ' OR ')); foreach ($answers as $key => $value) { $stmt->bindValue(':question_id_'.md5($value['id']), $value['id'], PDO::PARAM_INT); } $stmt->execute(); $array = []; foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $key => $value) { $array[$value['question_id']][] = $value; } if (!isset($array)) { return; } return $array; } public function getAnswersByOneQuestionId($id) { $stmt = $this->db->prepare('SELECT * FROM answers WHERE question_id = :qid'); $stmt->bindValue(':qid', $id, PDO::PARAM_INT); $stmt->execute(); return $stmt->fetchAll(PDO::FETCH_ASSOC); } } " Adjust unit test expected result.,"/** * Created by rgwozdz on 8/15/15. */ var moduleUnderTest = require(""../../app/common.js"") var assert = require('chai').assert; var equal = require('deep-equal'); describe('common.js module', function() { describe('parseQueryOptions', function () { it('should return expected Object with properties and values', function () { var result = moduleUnderTest.parseQueryOptions({fields:'a,b', limit: 2, order_by: 'a,b', order:'DESC', returnGeom:'false'},'a,b,c', { geometryColumn: null }); var expectedResult = { columns: 'a,b', geometryColumn: null, limit: 'LIMIT 2', order_by: 'ORDER BY a,b DESC' }; assert.equal(equal(result,expectedResult), true); }); it('should return expected Object with properties and values', function () { var result = moduleUnderTest.parseQueryOptions({},'a,b,c', { columns: 'a,b,c', geometryColumn: 'geom'}); var expectedResult = { columns: 'a,b,c', geometryColumn: null }; assert.equal(equal(result,expectedResult), true); }); }); }); ","/** * Created by rgwozdz on 8/15/15. */ var moduleUnderTest = require(""../../app/common.js"") var assert = require('chai').assert; var equal = require('deep-equal'); describe('common.js module', function() { describe('parseQueryOptions', function () { it('should return expected Object with properties and values', function () { var result = moduleUnderTest.parseQueryOptions({fields:'a,b', limit: 2, order_by: 'a,b', order:'DESC', returnGeom:'false'},'a,b,c', { geometryColumn: null }); var expectedResult = { columns: 'a,b', geometryColumn: null, limit: 'LIMIT 2', order_by: 'ORDER BY a,b' }; assert.equal(equal(result,expectedResult), true); }); it('should return expected Object with properties and values', function () { var result = moduleUnderTest.parseQueryOptions({},'a,b,c', { columns: 'a,b,c', geometryColumn: 'geom'}); var expectedResult = { columns: 'a,b,c', geometryColumn: null }; assert.equal(equal(result,expectedResult), true); }); }); }); " "Fix repeated inserts of ""Code"" team notices.","import DashboardWidgetComponent from 'appkit/components/dashboard-widget'; var GithubTeamNotices = DashboardWidgetComponent.extend({ init: function() { this._super(); this.set(""contents"", []); }, actions: { receiveEvent: function(data) { var items = Ember.A(JSON.parse(data)); this.updatePullRequests(items.pull_requests); // eventually Issues too } }, updatePullRequests: function(items) { var contents = this.get(""contents""); if (!Ember.isEmpty(items)) { // Remove items that have disappeared. var itemsToRemove = []; contents.forEach(function(existingItem) { var isNotPresent = !items.findBy(""id"", existingItem.get(""id"")); if (isNotPresent) { itemsToRemove.pushObject(existingItem); } }); contents.removeObjects(itemsToRemove); // Process current items. items.forEach(function(item) { var existingItem = contents.findBy(""id"", item.id); if (Ember.isEmpty(existingItem)) { // Add new items. var newItem = contents.pushObject(Ember.Object.create(item)); newItem.set(""dashEventType"", ""Pull Request""); } else { // Update existing items. existingItem.setProperties(item); } }); } } }); export default GithubTeamNotices; ","import DashboardWidgetComponent from 'appkit/components/dashboard-widget'; var GithubTeamNotices = DashboardWidgetComponent.extend({ init: function() { this._super(); this.set(""contents"", []); }, actions: { receiveEvent: function(data) { var items = Ember.A(JSON.parse(data)); this.updatePullRequests(items.pull_requests); // eventually Issues too } }, updatePullRequests: function(items) { var contents = this.get(""contents""); if (!Ember.isEmpty(items)) { // Remove items that have disappeared. var itemsToRemove = []; contents.forEach(function(existingItem) { var isNotPresent = !items.findBy(""id"", existingItem.get(""id"")); if (isNotPresent) { itemsToRemove.pushObject(existingItem); } }); contents.removeObjects(itemsToRemove); // Process current items. items.forEach(function(item) { var existingItem = contents.findBy(""url"", item.id); if (Ember.isEmpty(existingItem)) { // Add new items. var newItem = contents.pushObject(Ember.Object.create(item)); newItem.set(""dashEventType"", ""Pull Request""); } else { // Update existing items. existingItem.setProperties(item); } }); } } }); export default GithubTeamNotices; " "Revert ""Change test case with partial message in expectedExceptino annotation to use full expectedExceptionMessage one"" This reverts commit b5ff03e2117f38fa5af341b10cc877bc62fa2a81.","<?php /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\TestCase; class ExceptionMessageRegExpTest extends TestCase { /** * @expectedException \Exception * @expectedExceptionMessageRegExp /^A polymorphic \w+ message/ */ public function testRegexMessage() { throw new \Exception('A polymorphic exception message'); } /** * @expectedException \Exception * @expectedExceptionMessageRegExp /^a poly[a-z]+ [a-zA-Z0-9_]+ me(s){2}age$/i */ public function testRegexMessageExtreme() { throw new \Exception('A polymorphic exception message'); } /** * @runInSeparateProcess * @requires extension xdebug * @expectedException \Exception * @expectedExceptionMessageRegExp #Screaming preg_match# */ public function testMessageXdebugScreamCompatibility() { \ini_set('xdebug.scream', '1'); throw new \Exception('Screaming preg_match'); } /** * @expectedException \Exception variadic * @expectedExceptionMessageRegExp /^A variadic \w+ message/ */ public function testSimultaneousLiteralAndRegExpExceptionMessage() { throw new \Exception('A variadic exception message'); } } ","<?php /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\TestCase; class ExceptionMessageRegExpTest extends TestCase { /** * @expectedException \Exception * @expectedExceptionMessageRegExp /^A polymorphic \w+ message/ */ public function testRegexMessage() { throw new \Exception('A polymorphic exception message'); } /** * @expectedException \Exception * @expectedExceptionMessageRegExp /^a poly[a-z]+ [a-zA-Z0-9_]+ me(s){2}age$/i */ public function testRegexMessageExtreme() { throw new \Exception('A polymorphic exception message'); } /** * @runInSeparateProcess * @requires extension xdebug * @expectedException \Exception * @expectedExceptionMessageRegExp #Screaming preg_match# */ public function testMessageXdebugScreamCompatibility() { \ini_set('xdebug.scream', '1'); throw new \Exception('Screaming preg_match'); } /** * @expectedException \Exception * @expectedExceptionMessage A variadic exception message * @expectedExceptionMessageRegExp /^A variadic \w+ message/ */ public function testSimultaneousLiteralAndRegExpExceptionMessage() { throw new \Exception('A variadic exception message'); } } " Add quotes around a query variable to work better with Mongo.,"Template.foundbill.created = function(){ Meteor.subscribe(""allbills""); Session.set('message', ''); }; Template.foundbill.events({ ""submit form"": function(e){ e.preventDefault(); var serial = e.target.serialnumber.value; serial = serial.toLowerCase(); var zip = e.target.zip.value; var have = e.target.have.checked; var note = e.target.note.value; var email = Meteor.user().emails[0].address; var thisbill = bills.findOne({'serial': serial}); // check to see if this bill exists if (thisbill){ var billId = thisbill._id; bills.update({_id:billId}, {$push: { ""history"": { timestamp: new Date(), zip: zip, recordedby: Meteor.userId(), note: note } } }); e.target.serialnumber.value = ''; e.target.zip.value = ''; e.target.note.value = ''; e.target.have.checked = false; Session.set('message', '<div class=""no-data alert alert-success"">Thanks for registering this bill!</div>') }else{ Session.set('message', '<div class=""no-data alert alert-danger"">Couldn\'t find this bill in our records. <a href=""/new-bill"">Register it as new here!</a></div>'); } } }); Template.foundbill.helpers({ alertbox: function(){ return Session.get('message'); } }); ","Template.foundbill.created = function(){ Meteor.subscribe(""allbills""); Session.set('message', ''); }; Template.foundbill.events({ ""submit form"": function(e){ e.preventDefault(); var serial = e.target.serialnumber.value; serial = serial.toLowerCase(); var zip = e.target.zip.value; var have = e.target.have.checked; var note = e.target.note.value; var email = Meteor.user().emails[0].address; var thisbill = bills.findOne({serial: serial}); // check to see if this bill exists if (thisbill){ var billId = thisbill._id; bills.update({_id:billId}, {$push: { ""history"": { timestamp: new Date(), zip: zip, recordedby: Meteor.userId(), note: note } } }); e.target.serialnumber.value = ''; e.target.zip.value = ''; e.target.note.value = ''; e.target.have.checked = false; Session.set('message', '<div class=""no-data alert alert-success"">Thanks for registering this bill!</div>') }else{ Session.set('message', '<div class=""no-data alert alert-danger"">Couldn\'t find this bill in our records. <a href=""/new-bill"">Register it as new here!</a></div>'); } } }); Template.foundbill.helpers({ alertbox: function(){ return Session.get('message'); } }); " Set package name to 'dice-sim',"from setuptools import setup, find_packages from os import path from dice import __version__ here = path.abspath(path.dirname(__file__)) try: with open(path.join(here, 'requirements.txt')) as f: requirements = f.read().splitlines() except: requirements = [] # Get the long description from the README file # pandoc --from=markdown --to=rst --output=README.rst README.md with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='dice-sim', version=__version__, author='Simon Muller', author_email='samullers@gmail.com', url='https://github.com/samuller/dice', description='Simulate various dice throw situations', long_description=long_description, py_modules=['dice'], packages=find_packages(exclude=['*.tests*']), install_requires=requirements, include_package_data=True, entry_points={ 'console_scripts': [ 'dice=dice:main', ], }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Other Audience', 'License :: OSI Approved :: GNU Lesser General Public License v2 (LGPLv2)', 'Natural Language :: English', 'Programming Language :: Python', 'Topic :: Games/Entertainment', 'Topic :: Games/Entertainment :: Board Games', 'Topic :: Utilities', ], ) ","from setuptools import setup, find_packages from os import path from dice import __version__ here = path.abspath(path.dirname(__file__)) try: with open(path.join(here, 'requirements.txt')) as f: requirements = f.read().splitlines() except: requirements = [] # Get the long description from the README file # pandoc --from=markdown --to=rst --output=README.rst README.md with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='sim-dice', version=__version__, author='Simon Muller', author_email='samullers@gmail.com', url='https://github.com/samuller/dice', description='Simulate various dice throw situations', long_description=long_description, py_modules=['dice'], packages=find_packages(exclude=['*.tests*']), install_requires=requirements, include_package_data=True, entry_points={ 'console_scripts': [ 'dice=dice:main', ], }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Other Audience', 'License :: OSI Approved :: GNU Lesser General Public License v2 (LGPLv2)', 'Natural Language :: English', 'Programming Language :: Python', 'Topic :: Games/Entertainment', 'Topic :: Games/Entertainment :: Board Games', 'Topic :: Utilities', ], ) " Change data directory back to test data.,"'use strict'; var bowlingApp = angular.module('bowling', ['ngRoute']); bowlingApp.config(['$routeProvider', function($routeProvider) { $routeProvider.otherwise({ redirectTo: '/main' }); }]); bowlingApp.factory(""dataProvider"", ['$q', function ($q) { var dataLoaded = false; var currentPromise = null; return { getData: function () { if (currentPromise == null) { if (!dataLoaded) { var result = bowling.initialize({""root"": ""testdata""}, $q); currentPromise = result.then(function (league) { dataLoaded = true; currentPromise = null; return league; }); } else { return $q(function (resolve, reject) { resolve(bowling.currentLeague); }); } } return currentPromise; } } }]);","'use strict'; var bowlingApp = angular.module('bowling', ['ngRoute']); bowlingApp.config(['$routeProvider', function($routeProvider) { $routeProvider.otherwise({ redirectTo: '/main' }); }]); bowlingApp.factory(""dataProvider"", ['$q', function ($q) { var dataLoaded = false; var currentPromise = null; return { getData: function () { if (currentPromise == null) { if (!dataLoaded) { var result = bowling.initialize({""root"": ""polarbowler""}, $q); currentPromise = result.then(function (league) { dataLoaded = true; currentPromise = null; return league; }); } else { return $q(function (resolve, reject) { resolve(bowling.currentLeague); }); } } return currentPromise; } } }]);" Update hydrator to silently ignore missing request_time field,"<?php namespace CdliTwoStageSignup\Mapper; use Zend\Stdlib\Hydrator\ClassMethods; use CdliTwoStageSignup\Entity\EmailVerification as Entity; class EmailVerificationHydrator extends ClassMethods { /** * Extract values from an object * * @param object $object * @return array * @throws Exception\InvalidArgumentException */ public function extract($object) { if (!$object instanceof Entity) { throw new \InvalidArgumentException('$object must be an instance of EmailVerification entity'); } /* @var $object Entity*/ $data = parent::extract($object); unset($data['is_expired']); if ( isset($data['request_time']) && $data['request_time'] instanceof \DateTime ) { $data['request_time'] = $data['request_time']->format('Y-m-d H:i:s'); } return $data; } /** * Hydrate $object with the provided $data. * * @param array $data * @param object $object * @return UserInterface * @throws Exception\InvalidArgumentException */ public function hydrate(array $data, $object) { if (!$object instanceof Entity) { throw new \InvalidArgumentException('$object must be an instance of EmailVerification entity'); } if ( isset($data['request_time']) && ! $data['request_time'] instanceof \DateTime ) { $data['request_time'] = new \DateTime($data['request_time']); } return parent::hydrate($data, $object); } } ","<?php namespace CdliTwoStageSignup\Mapper; use Zend\Stdlib\Hydrator\ClassMethods; use CdliTwoStageSignup\Entity\EmailVerification as Entity; class EmailVerificationHydrator extends ClassMethods { /** * Extract values from an object * * @param object $object * @return array * @throws Exception\InvalidArgumentException */ public function extract($object) { if (!$object instanceof Entity) { throw new \InvalidArgumentException('$object must be an instance of EmailVerification entity'); } /* @var $object Entity*/ $data = parent::extract($object); if ( $data['request_time'] instanceof \DateTime ) { $data['request_time'] = $data['request_time']->format('Y-m-d H:i:s'); } return $data; } /** * Hydrate $object with the provided $data. * * @param array $data * @param object $object * @return UserInterface * @throws Exception\InvalidArgumentException */ public function hydrate(array $data, $object) { if (!$object instanceof Entity) { throw new \InvalidArgumentException('$object must be an instance of EmailVerification entity'); } if ( ! $data['request_time'] instanceof \DateTime ) { $data['request_time'] = new \DateTime($data['request_time']); } return parent::hydrate($data, $object); } protected function mapField($keyFrom, $keyTo, array $array) { $array[$keyTo] = $array[$keyFrom]; unset($array[$keyFrom]); return $array; } } " Add option for custom CSS styling of typeahead component; actual styling forthcoming,"import React, { PropTypes, Component } from 'react'; import { Typeahead } from 'react-typeahead'; import _ from 'lodash'; import { Companies } from '../constants'; import CompanyProfile from './CompanyProfile'; export default class SearchCompany extends Component { constructor () { super(); this.state = {}; } componentWillMount() { this.setState({companyNames: _.pluck(Companies, 'name')}); } //CSS styling forthcoming render() { return ( <div> Company Name: <Typeahead className=""form-control"" name=""company"" options={ this.state.companyNames } placeholder=""Google"" maxVisible={10} onOptionSelected={ (name) => { let companyEntry = _.find(Companies, 'name', name); this.setState({companyId: companyEntry.id}); } } customClasses={ { input: ""typeahead-input"", results: ""typeahead-results"", listItem: ""typeahead-item"", hover: ""typeahead-active""} } /> {this.state.companyId && <CompanyProfile apiData={this.props.apiData} companyId={this.state.companyId} fetchApiData={this.props.fetchApiData}/> } </div> ); } } ","import React, { PropTypes, Component } from 'react'; import { Typeahead } from 'react-typeahead'; import _ from 'lodash'; import { Companies } from '../constants'; import CompanyProfile from './CompanyProfile'; export default class SearchCompany extends Component { constructor () { super(); this.state = {}; } componentWillMount() { this.setState({companyNames: _.pluck(Companies, 'name')}); } render() { return ( <div> Company Name: <Typeahead className=""form-control"" name=""company"" options={ this.state.companyNames } placeholder=""Google"" maxVisible={10} onOptionSelected={ (name) => { let companyEntry = _.find(Companies, 'name', name); this.setState({companyId: companyEntry.id}); } } /> {this.state.companyId && <CompanyProfile apiData={this.props.apiData} companyId={this.state.companyId} fetchApiData={this.props.fetchApiData}/> } </div> ); } } " Fix mirror_channel widget on OPPS_MIRROR_CHANNEL false,"#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from django.conf import settings from opps.db.models.fields.jsonf import JSONFormField from opps.fields.widgets import JSONField from opps.fields.models import Field, FieldOption class ContainerAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ContainerAdminForm, self).__init__(*args, **kwargs) if not settings.OPPS_MIRROR_CHANNEL: self.fields['mirror_channel'].widget = forms.HiddenInput() self.fields['json'] = JSONFormField( widget=JSONField( attrs={'_model': self._meta.model.__name__}), required=False) for field in Field.objects.filter(application__contains= self._meta.model.__name__): if field.type == 'checkbox': for fo in FieldOption.objects.filter(field=field): self.fields[ 'json_{}_{}'.format( field.slug, fo.option.slug )] = forms.CharField(required=False) else: self.fields[ 'json_{}'.format(field.slug) ] = forms.CharField(required=False) ","#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from django.conf import settings from opps.db.models.fields.jsonf import JSONFormField from opps.fields.widgets import JSONField from opps.fields.models import Field, FieldOption class ContainerAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ContainerAdminForm, self).__init__(*args, **kwargs) self.fields['json'] = JSONFormField( widget=JSONField( attrs={'_model': self._meta.model.__name__}), required=False) for field in Field.objects.filter(application__contains= self._meta.model.__name__): if field.type == 'checkbox': for fo in FieldOption.objects.filter(field=field): self.fields[ 'json_{}_{}'.format( field.slug, fo.option.slug )] = forms.CharField(required=False) else: self.fields[ 'json_{}'.format(field.slug) ] = forms.CharField(required=False) if settings.OPPS_MIRROR_CHANNEL: self.field['mirror_channel'] = forms.CharField( widget=forms.HiddenInput(), required=False) " Make sure sort works for numeric fields also.,"function() { $(""#form-Flight"").validator(); $(this).show(); $.tablesorter.addParser({ id: 'surname', is: function(s) { return false; }, format: function(s) { var names = s.trim().replace(/ +/g, "" "").split("" ""); var sortVal = names.length > 1 ? names[1] : s; return sortVal; }, type: 'text' }); $.tablesorter.addParser({ id: 'checkboxes', is: function(s) { return false; }, format: function(s, table, cell) { var checked = $(cell).children("":checkbox"").get(0).checked; return checked ? 1 : 0; }, type: 'numeric' }); $(""#fltdetail"").tablesorter({ headers: { 0: { sorter:""surname"" }, 1: { sorter:""checkboxes"" }, 2: { sorter:""checkboxes"" }, 5: { sorter:""checkboxes"" }, 6: { sorter:""checkboxes"" }, 7: { sorter:""checkboxes"" }, 8: { sorter:""checkboxes"" }, 10: { sorter:""surname"" } }, textExtraction: function(elem) { var $input = $(""input"", elem); return $input.val() || $(elem).text(); } }); }; //@ sourceURL=/flight_other/after.js ","function() { $(""#form-Flight"").validator(); $(this).show(); $.tablesorter.addParser({ id: 'surname', is: function(s) { return false; }, format: function(s) { var names = s.trim().replace(/ +/g, "" "").split("" ""); var sortVal = names.length > 1 ? names[1] : s; return sortVal; }, type: 'text' }); $.tablesorter.addParser({ id: 'checkboxes', is: function(s) { return false; }, format: function(s, table, cell) { var checked = $(cell).children("":checkbox"").get(0).checked; return checked ? 1 : 0; }, type: 'numeric' }); $(""#fltdetail"").tablesorter({ headers: { 0: { sorter:""surname"" }, 1: { sorter:""checkboxes"" }, 2: { sorter:""checkboxes"" }, 5: { sorter:""checkboxes"" }, 6: { sorter:""checkboxes"" }, 7: { sorter:""checkboxes"" }, 8: { sorter:""checkboxes"" }, 10: { sorter:""surname"" } }, textExtraction: function(elem) { var $input = $(""input[type=text]"", elem); return $input.val() || $(elem).text(); } }); }; //@ sourceURL=/flight_other/after.js " Fix unicode keys in addition to values for windows/py2 environment,"# -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- # Copyright © 2016, Continuum Analytics, Inc. All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. # ---------------------------------------------------------------------------- from __future__ import absolute_import, print_function import platform import sys _PY2 = sys.version_info[0] == 2 def is_string(s): if _PY2: # pragma: no cover (py2/py3) return isinstance(s, basestring) # pragma: no cover (py2/py3) # noqa else: # pragma: no cover (py2/py3) return isinstance(s, str) # pragma: no cover (py2/py3) def env_without_unicode(environ): # On Windows / Python 2.7, Popen explodes if given unicode strings in the environment. if _PY2 and platform.system() == 'Windows': # pragma: no cover (py2/py3) environ_copy = dict() for key, value in environ.items(): if isinstance(key, unicode): # noqa key = key.encode() if isinstance(value, unicode): # noqa value = value.encode() assert isinstance(key, str) assert isinstance(value, str) environ_copy[key] = value return environ_copy else: # pragma: no cover (py2/py3) return environ ","# -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- # Copyright © 2016, Continuum Analytics, Inc. All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. # ---------------------------------------------------------------------------- from __future__ import absolute_import, print_function import platform import sys _PY2 = sys.version_info[0] == 2 def is_string(s): if _PY2: # pragma: no cover (py2/py3) return isinstance(s, basestring) # pragma: no cover (py2/py3) # noqa else: # pragma: no cover (py2/py3) return isinstance(s, str) # pragma: no cover (py2/py3) def env_without_unicode(environ): # On Windows / Python 2.7, Popen explodes if given unicode strings in the environment. if _PY2 and platform.system() == 'Windows': # pragma: no cover (py2/py3) environ_copy = dict() for key, value in environ.items(): assert isinstance(key, basestring) # noqa assert isinstance(key, str) if isinstance(value, unicode): # noqa environ_copy[key] = value.encode() assert isinstance(environ_copy[key], str) elif not isinstance(value, str): raise TypeError(""Environment contains non-unicode non-str value %r"" % value) else: environ_copy[key] = value return environ_copy else: # pragma: no cover (py2/py3) return environ " Attach the parent web socket to the child iframe.,"(function () { ""use strict""; var socket = null; var iframe = document.getElementById(""iframe""); var iframeWindow = iframe.contentWindow; function runScriptInIframe(string) { function onLoad() { iframe.removeEventListener(""load"", onLoad); iframeWindow.socket = socket; iframeWindow.mocha.setup({ ui: ""bdd"" }); iframeWindow.mocha.ignoreLeaks = true; var scriptEl = iframeWindow.document.createElement(""script""); MSApp.execUnsafeLocalFunction(function () { scriptEl.innerHTML = string; }); iframeWindow.document.body.appendChild(scriptEl); iframeWindow.mocha.run(); } iframe.addEventListener(""load"", onLoad); iframeWindow.location.reload(true); } function connect() { socket = new WebSocket(""ws://localhost:8080""); socket.onerror = function (error) { console.error(error); retry(); }; socket.onclose = function () { console.log(""WebSocket connection closed""); retry(); }; socket.onmessage = function (ev) { runScriptInIframe(ev.data); }; } var isRetrying = false; function retry() { if (isRetrying) { return; } isRetrying = true; setTimeout(function () { connect(); isRetrying = false; }, 500); } connect(); }()); ","(function () { ""use strict""; var iframe = document.getElementById(""iframe""); var iframeWindow = iframe.contentWindow; function runScriptInIframe(string) { function onLoad() { iframe.removeEventListener(""load"", onLoad); iframeWindow.mocha.setup({ ui: ""bdd"" }); iframeWindow.mocha.ignoreLeaks = true; var scriptEl = iframeWindow.document.createElement(""script""); MSApp.execUnsafeLocalFunction(function () { scriptEl.innerHTML = string; }); iframeWindow.document.body.appendChild(scriptEl); iframeWindow.mocha.run(); } iframe.addEventListener(""load"", onLoad); iframeWindow.location.reload(true); } function connect() { var connection = new WebSocket(""ws://localhost:8080""); connection.onerror = function (error) { console.error(error); retry(); }; connection.onclose = function () { console.log(""WebSocket connection closed""); retry(); }; connection.onmessage = function (ev) { runScriptInIframe(ev.data); }; } var isRetrying = false; function retry() { if (isRetrying) { return; } isRetrying = true; setTimeout(function () { connect(); isRetrying = false; }, 500); } connect(); }()); " Update sample for static presenter typing,"package net.grandcentix.thirtyinch.sample; import com.jakewharton.rxbinding.view.RxView; import net.grandcentrix.thirtyinch.android.ThirtyInchActivity; import android.os.Bundle; import android.support.annotation.NonNull; import android.widget.Button; import android.widget.TextView; import rx.Observable; public class HelloWorldActivity extends ThirtyInchActivity<HelloWorldPresenter, HelloWorldView> implements HelloWorldView { private Button mButton; private TextView mOutput; private TextView mUptime; @Override public Observable<Void> onButtonClicked() { return RxView.clicks(mButton); } @NonNull @Override public HelloWorldPresenter providePresenter(final Bundle activityIntentBundle) { return new HelloWorldPresenter(); } @Override public void showPresenterUpTime(final Long uptime) { mUptime.setText(String.format(""Presenter alive fore %ss"", uptime)); } @Override public void showText(final String text) { mOutput.setText(text); } @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hello_world); mButton = (Button) findViewById(R.id.button); mOutput = (TextView) findViewById(R.id.output); mUptime = (TextView) findViewById(R.id.uptime); } @NonNull @Override protected HelloWorldView provideView() { return this; } } ","package net.grandcentix.thirtyinch.sample; import com.jakewharton.rxbinding.view.RxView; import net.grandcentrix.thirtyinch.Presenter; import net.grandcentrix.thirtyinch.android.ThirtyInchActivity; import android.os.Bundle; import android.support.annotation.NonNull; import android.widget.Button; import android.widget.TextView; import rx.Observable; public class HelloWorldActivity extends ThirtyInchActivity<HelloWorldView> implements HelloWorldView { private Button mButton; private TextView mOutput; private TextView mUptime; @Override public Observable<Void> onButtonClicked() { return RxView.clicks(mButton); } @Override public void showPresenterUpTime(final Long uptime) { mUptime.setText(String.format(""Presenter alive fore %ss"", uptime)); } @Override public void showText(final String text) { mOutput.setText(text); } @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hello_world); mButton = (Button) findViewById(R.id.button); mOutput = (TextView) findViewById(R.id.output); mUptime = (TextView) findViewById(R.id.uptime); } @NonNull @Override protected Presenter<HelloWorldView> providePresenter( @NonNull final Bundle activityIntentBundle) { return new HelloWorldPresenter(); } @NonNull @Override protected HelloWorldView provideView() { return this; } } " Exclude fields from the RestrcitedForm (no verification),"from django import forms from .models import Project class ProjectForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(ProjectForm, self).__init__(*args, **kwargs) def save(self, *args, **kwargs): instance = super(ProjectForm, self).save(commit=False) instance.user = self.user instance.flp = self.user instance.save(*args, **kwargs) self.save_m2m() return instance class Meta: model = Project fields = ( 'name', 'team', 'description', 'targets', 'tasks', 'target_group', 'schedule', 'resources', 'finance_description', 'partners',) class RestrictedProjectForm(forms.ModelForm): def save(self, *args, **kwargs): instance = super(RestrictedProjectForm, self).save(commit=False) return instance class Meta: model = Project exclude = ( 'name', 'team', 'description', 'targets', 'tasks', 'target_group', 'schedule', 'resources', 'finance_description', 'partners', 'flp', 'created_at', 'user', ) fileds = ( 'status', 'attitude', ) ","from django import forms from .models import Project class ProjectForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(ProjectForm, self).__init__(*args, **kwargs) def save(self, *args, **kwargs): instance = super(ProjectForm, self).save(commit=False) instance.user = self.user instance.flp = self.user instance.save(*args, **kwargs) self.save_m2m() return instance class Meta: model = Project fields = ( 'name', 'team', 'description', 'targets', 'tasks', 'target_group', 'schedule', 'resources', 'finance_description', 'partners',) class RestrictedProjectForm(forms.ModelForm): def save(self, *args, **kwargs): instance = super(RestrictedProjectForm, self).save(commit=False) return instance class Meta: model = Project fileds = ( 'status', 'attitude', )" Add support for interface typehints,"<?php declare(strict_types=1); namespace Stratadox\Di; use ReflectionClass; final class AutoWiring { private $container; private $links; private function __construct(ContainerInterface $container, array $links) { $this->container = $container; $this->links = $links; } public static function the(ContainerInterface $container) : self { return new self($container, []); } public function link(string $interface, string $class) : self { return new self($this->container, [$interface => $class]); } public function get(string $service) { if (!$this->container->has($service)) { $this->resolve($service); } return $this->container->get($service); } private function resolve(string $service) { if (interface_exists($service)) { $this->resolveInterface($service); } else { $this->resolveClass($service); } } private function resolveInterface(string $service) { $class = $this->links[$service]; $this->resolveClass($class); $this->container->set($service, function () use ($class) { return $this->container->get($class); }); } private function resolveClass(string $service) { $constructor = (new ReflectionClass($service))->getConstructor(); $dependencies = []; if (isset($constructor)) { foreach ($constructor->getParameters() as $parameter) { $dependency = (string) $parameter->getType(); $this->resolve($dependency); $dependencies[] = $dependency; } } $this->container->set($service, function () use ($service, $dependencies) { $parameters = []; foreach ($dependencies as $dependency) { $parameters[] = $this->container->get($dependency); } return new $service(...$parameters); } ); } } ","<?php declare(strict_types=1); namespace Stratadox\Di; use ReflectionClass; final class AutoWiring { private $container; private function __construct(ContainerInterface $container) { $this->container = $container; } public static function the(ContainerInterface $container) : self { return new self($container, []); } public function get(string $service) { if (!$this->container->has($service)) { $this->resolve($service); } return $this->container->get($service); } private function resolve(string $service) { $constructor = (new ReflectionClass($service))->getConstructor(); $dependencies = []; if (isset($constructor)) { foreach ($constructor->getParameters() as $parameter) { $dependency = (string) $parameter->getType(); $this->resolve($dependency); $dependencies[] = $dependency; } } $this->container->set($service, function () use ($service, $dependencies) { $parameters = []; foreach ($dependencies as $dependency) { $parameters[] = $this->container->get($dependency); } return new $service(...$parameters); } ); } } " Make a new connection per request,"var mssql = require(""mssql""); var database = { query: function(connectionString, query, callback) { var connection = new mssql.Connection(connectionString, function(connectionError) { if(connectionError) { mssql.close(); callback(connectionError, []); } else { var request = new mssql.Request(connection); // Attach the input params to the request var values = query.values || []; for(var i = 0; i !== values.length; i++) { request.input((i + 1).toString(), query.values[i]); } request.query(query.text, function(queryError, rows) { callback(queryError, rows || []); }); } }); mssql.on('error', callback); }, execute: function(connectionString, name, parameters, callback) { var connection = new mssql.Connection(connectionString, function(connectionError) { if(connectionError) { mssql.close(); callback(connectionError, []); } else { var request = new mssql.Request(connection); // Attach input params to the request var params = parameters || {}; var keys = Object.keys(params); for(var i = 0; i !== keys.length; i++) { var key = keys[i]; request.input(key, params[key]); } request.execute(name, function(error, recordsets) { callback(error, recordsets || []); }); } }); mssql.on('error', callback); } }; module.exports = database; ","var mssql = require(""mssql""); var database = { query: function(connection, query, callback) { mssql.connect(connection, function(connectionError) { if(connectionError) { mssql.close(); callback(connectionError, []); } else { var request = new mssql.Request(); // Attach the input params to the request var values = query.values || []; for(var i = 0; i !== values.length; i++) { request.input((i + 1).toString(), query.values[i]); } request.query(query.text, function(queryError, rows) { callback(queryError, rows || []); }); } }); mssql.on('error', callback); }, execute: function(connection, name, parameters, callback) { mssql.connect(connection, function(connectionError) { if(connectionError) { mssql.close(); callback(connectionError, []); } else { var request = new mssql.Request(); // Attach input params to the request var params = parameters || {}; var keys = Object.keys(params); for(var i = 0; i !== keys.length; i++) { var key = keys[i]; request.input(key, params[key]); } request.execute(name, function(error, recordsets) { callback(error, recordsets || []); }); } }); mssql.on('error', callback); } }; module.exports = database; " Fix dimensions of periodic kernel parameters,"from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import math import torch from torch import nn from .kernel import Kernel class PeriodicKernel(Kernel): def __init__( self, log_lengthscale_bounds=(-10000, 10000), log_period_length_bounds=(-10000, 10000), eps=1e-5, active_dims=None, ): super(PeriodicKernel, self).__init__( has_lengthscale=True, log_lengthscale_bounds=log_lengthscale_bounds, active_dims=active_dims, ) self.eps = eps self.register_parameter( 'log_period_length', nn.Parameter(torch.zeros(1, 1, 1)), bounds=log_period_length_bounds, ) def forward(self, x1, x2): lengthscale = (self.log_lengthscale.exp() + self.eps).sqrt_() period_length = (self.log_period_length.exp() + self.eps).sqrt_() diff = torch.sum((x1.unsqueeze(2) - x2.unsqueeze(1)).abs(), -1) res = - 2 * torch.sin(math.pi * diff / period_length).pow(2) / lengthscale return res.exp() ","from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import math import torch from torch import nn from .kernel import Kernel class PeriodicKernel(Kernel): def __init__( self, log_lengthscale_bounds=(-10000, 10000), log_period_length_bounds=(-10000, 10000), eps=1e-5, active_dims=None, ): super(PeriodicKernel, self).__init__( has_lengthscale=True, log_lengthscale_bounds=log_lengthscale_bounds, active_dims=active_dims, ) self.eps = eps self.register_parameter( 'log_period_length', nn.Parameter(torch.zeros(1, 1)), bounds=log_period_length_bounds, ) def forward(self, x1, x2): lengthscale = (self.log_lengthscale.exp() + self.eps).sqrt_() period_length = (self.log_period_length.exp() + self.eps).sqrt_() diff = torch.sum((x1.unsqueeze(2) - x2.unsqueeze(1)).abs(), -1) res = - 2 * torch.sin(math.pi * diff / period_length).pow(2) / lengthscale return res.exp().unsqueeze(1) " "Revert ""Fix unit test python3 compatibility."" This reverts commit 6807e5a5966f1f37f69a54e255a9981918cc8fb6.","import base64 import os from distutils.core import Command class TestCommand(Command): description = ""Launch all tests under fusion_tables app"" user_options = [] def initialize_options(self): pass def finalize_options(self): pass def create_client_secret_file(self): client_secret = open(""/tmp/client_secret.json"", ""w"") data = os.environ.get(""CLIENT_SECRET"") client_secret.write(base64.b64decode(data)) client_secret.close() def configure_settings(self): from django.conf import settings settings.configure( DATABASES={ ""default"": { ""NAME"": "":memory:"", ""ENGINE"": ""django.db.backends.sqlite3"", ""TEST"": { ""NAME"": "":memory:"" } } }, INSTALLED_APPS=( ""django.contrib.contenttypes"", ""fusion_tables"", ), ROOT_URLCONF=""tests.urls"", MODELS_TO_SYNC=(""fusion_tables.SampleModel"", ), CLIENT_SECRET_JSON_FILEPATH=""/tmp/client_secret.json"", LOCATION_FIELDS=(""TextField"", ) ) def run(self): import django from django.core.management import call_command self.create_client_secret_file() self.configure_settings() django.setup() call_command(""test"", ""fusion_tables"") ","import base64 import os from distutils.core import Command class TestCommand(Command): description = ""Launch all tests under fusion_tables app"" user_options = [] def initialize_options(self): pass def finalize_options(self): pass def create_client_secret_file(self): client_secret = open(""/tmp/client_secret.json"", ""w"") data = os.environ.get(""CLIENT_SECRET"").decode(""utf-8"") client_secret.write(base64.b64decode(data)) client_secret.close() def configure_settings(self): from django.conf import settings settings.configure( DATABASES={ ""default"": { ""NAME"": "":memory:"", ""ENGINE"": ""django.db.backends.sqlite3"", ""TEST"": { ""NAME"": "":memory:"" } } }, INSTALLED_APPS=( ""django.contrib.contenttypes"", ""fusion_tables"", ), ROOT_URLCONF=""tests.urls"", MODELS_TO_SYNC=(""fusion_tables.SampleModel"", ), CLIENT_SECRET_JSON_FILEPATH=""/tmp/client_secret.json"", LOCATION_FIELDS=(""TextField"", ) ) def run(self): import django from django.core.management import call_command self.create_client_secret_file() self.configure_settings() django.setup() call_command(""test"", ""fusion_tables"") " Reorder AJAX response class constructor arguments.,"<?php /** * @author Igor Nikolaev <igor.sv.n@gmail.com> * @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\Utils\HttpFoundation; use Symfony\Component\HttpFoundation\JsonResponse; /** * AJAX response */ class AjaxResponse extends JsonResponse { /** * @param string $html HTML * @param bool $success Is success * @param string $message Message * @param array $data Additional data * @param bool $reloadPage Whether to reload page * @param int $status Response status code * @param array $headers Response headers */ public function __construct( $html = '', $success = true, $message = null, array $data = array(), $reloadPage = false, $status = 200, array $headers = array() ) { parent::__construct(array_merge($data, array( 'html' => $html, 'message' => $message, 'reloadPage' => $reloadPage, 'success' => $success, )), $status, $headers); } } ","<?php /** * @author Igor Nikolaev <igor.sv.n@gmail.com> * @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\Utils\HttpFoundation; use Symfony\Component\HttpFoundation\JsonResponse; /** * AJAX response */ class AjaxResponse extends JsonResponse { /** * @param string $html HTML * @param bool $success Is success * @param string $message Message * @param bool $reloadPage Whether to reload page * @param array $data Additional data * @param int $status Response status code * @param array $headers Response headers */ public function __construct( $html = '', $success = true, $message = null, $reloadPage = false, array $data = array(), $status = 200, array $headers = array() ) { parent::__construct(array_merge($data, array( 'html' => $html, 'message' => $message, 'reloadPage' => $reloadPage, 'success' => $success, )), $status, $headers); } } " "Update example to 'try' authentication, so guest user can be used","var Hapi = require('hapi'); var Path = require('path'); var server = new Hapi.Server(); server.connection({ port: 4000 }); server.views({ engines: { hbs: require('handlebars'), jade: require('jade') }, path: __dirname, isCached: false }); server.register([ { register: require('../../index'), // hapi-context-credentials }, { register: require('hapi-auth-basic') } ], function (err) { if (err) { throw err; } var validateFunc = function (username, password, callback) { // Just authenticate everyone and store username // in credentials if (username === 'john' && password === 'secret') { return callback(null, true, {username: 'john'}); } return callback(null, false, {}); }; server.auth.strategy('simple', 'basic', { validateFunc: validateFunc }); server.route([{ config: { auth: { strategy: 'simple', mode: 'try' } }, method: 'GET', path: '/hbs', handler: function(request, reply) { reply.view('example.hbs'); // Handlebars example } }, { config: { auth: { strategy: 'simple', mode: 'try' } }, method: 'GET', path: '/jade', handler: function(request, reply) { reply.view('example.jade'); // Jade example } } ]); server.start(function() { console.log('Started server'); }); }); ","var Hapi = require('hapi'); var Path = require('path'); var server = new Hapi.Server(); server.connection({ port: 4000 }); server.views({ engines: { hbs: require('handlebars'), jade: require('jade') }, path: __dirname, isCached: false }); server.register([ { register: require('../../index'), // hapi-context-credentials }, { register: require('hapi-auth-basic') } ], function (err) { if (err) { throw err; } var validateFunc = function (username, password, callback) { // Just authenticate everyone and store username // in credentials callback(null, true, { username: username }); }; server.auth.strategy('simple', 'basic', { validateFunc: validateFunc }); server.route([{ config: { auth: 'simple' }, method: 'GET', path: '/hbs', handler: function(request, reply) { reply.view('example.hbs'); // Handlebars example } }, { config: { auth: 'simple' }, method: 'GET', path: '/jade', handler: function(request, reply) { reply.view('example.jade'); // Jade example } } ]); server.start(function() { console.log('Started server'); }); }); " Java: Put patterns directly in function call to follow style of the rest of benchmarks,"import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class Benchmark { public static void main(String... args) throws IOException { if (args.length != 1) { System.out.println(""Usage: java Benchmark <filename>""); System.exit(1); } final String data = Files.readString(Paths.get(args[0])); measure(data, ""[\\w.+-]+@[\\w.-]+\\.[\\w.-]+""); measure(data, ""[\\w]+://[^/\\s?#]+[^\\s?#]+(?:\\?[^\\s#]*)?(?:#[^\\s]*)?""); measure(data, ""(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])""); } private static void measure(String data, String pattern) { long startTime = System.nanoTime(); final Matcher matcher = Pattern.compile(pattern).matcher(data); int count = 0; while (matcher.find()) { ++count; } long elapsed = System.nanoTime() - startTime; System.out.println(elapsed / 1e6 + "" - "" + count); } } ","import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class Benchmark { private static final String PATTERN_EMAIL = ""[\\w.+-]+@[\\w.-]+\\.[\\w.-]+""; private static final String PATTERN_URI = ""[\\w]+://[^/\\s?#]+[^\\s?#]+(?:\\?[^\\s#]*)?(?:#[^\\s]*)?""; private static final String PATTERN_IP = ""(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])\\.){3}"" + ""(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])""; public static void main(String... args) throws IOException { if (args.length != 1) { System.out.println(""Usage: java Benchmark <filename>""); System.exit(1); } final String data = Files.readString(Paths.get(args[0])); measure(data, PATTERN_EMAIL); measure(data, PATTERN_URI); measure(data, PATTERN_IP); } private static void measure(String data, String pattern) { long startTime = System.nanoTime(); final Matcher matcher = Pattern.compile(pattern).matcher(data); int count = 0; while (matcher.find()) { ++count; } long elapsed = System.nanoTime() - startTime; System.out.println(elapsed / 1e6 + "" - "" + count); } } " Exclude tests package from installing.,"import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-pgallery', version=__import__('pgallery').__version__, description='Photo gallery app for PostgreSQL and Django.', long_description=read('README.rst'), author='Zbigniew Siciarz', author_email='zbigniew@siciarz.net', url='http://github.com/zsiciarz/django-pgallery', download_url='http://pypi.python.org/pypi/django-pgallery', license='MIT', install_requires=[ 'Django>=1.4', 'Pillow', 'psycopg2>=2.4', 'django-markitup>=1.0', 'django-model-utils>=1.1', 'djorm-ext-core>=0.4.2', 'djorm-ext-expressions>=0.4.4', 'djorm-ext-hstore>=0.4.2', 'djorm-ext-pgarray', 'sorl-thumbnail>=11', ], packages=find_packages(exclude=['tests']), include_package_data=True, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities', ], ) ","import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-pgallery', version=__import__('pgallery').__version__, description='Photo gallery app for PostgreSQL and Django.', long_description=read('README.rst'), author='Zbigniew Siciarz', author_email='zbigniew@siciarz.net', url='http://github.com/zsiciarz/django-pgallery', download_url='http://pypi.python.org/pypi/django-pgallery', license='MIT', install_requires=[ 'Django>=1.4', 'Pillow', 'psycopg2>=2.4', 'django-markitup>=1.0', 'django-model-utils>=1.1', 'djorm-ext-core>=0.4.2', 'djorm-ext-expressions>=0.4.4', 'djorm-ext-hstore>=0.4.2', 'djorm-ext-pgarray', 'sorl-thumbnail>=11', ], packages=find_packages(), include_package_data=True, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities', ], ) " Select inline editable fields by default.,"""use strict""; require(['jquery', 'messages', 'jquery.cookie', 'jquery.jeditable'], function($, messages) { if (!$.ajaxSettings.headers) $.ajaxSettings.headers = {}; $.ajaxSettings.headers['X-CSRFToken'] = $.cookie('csrftoken'); $.fn.csrfEditable = function(url) { var self = this; function error(xhr, status, error) { if (status == 403) { self.css(""background-color"", ""#fcc""); } } self.editable(url, { select: true, ajaxoptions: { error: error }, data: function(string, settings) { return $.trim(string, settings); }}); self.addClass(""editable""); }; $(document).ready(function() { // Make the login link activatable. $(""#login_link"").click(function(event) { $(this).toggleClass('selected'); $(""#login_popup_form"").slideToggle(); return false; }); $('#submit-ajax').click(function() { var $elem = $(this); var df = $.ajax({ url: $elem.data('url'), type: 'POST' }); df.done(function() { messages.addInfo(""Your extension has been locked."").hide().slideDown(); $elem.attr('disabled', true); $('h3, p.description').csrfEditable('disable').removeClass('editable'); }); return false; }); if (window._SW) try { window._SW(); } catch(e) { console.error(e); } }); }); ","""use strict""; require(['jquery', 'messages', 'jquery.cookie', 'jquery.jeditable'], function($, messages) { if (!$.ajaxSettings.headers) $.ajaxSettings.headers = {}; $.ajaxSettings.headers['X-CSRFToken'] = $.cookie('csrftoken'); $.fn.csrfEditable = function(url) { var self = this; function error(xhr, status, error) { if (status == 403) { self.css(""background-color"", ""#fcc""); } } self.editable(url, { ajaxoptions: { error: error }, data: function(string, settings) { return $.trim(string, settings); }}); self.addClass(""editable""); }; $(document).ready(function() { // Make the login link activatable. $(""#login_link"").click(function(event) { $(this).toggleClass('selected'); $(""#login_popup_form"").slideToggle(); return false; }); $('#submit-ajax').click(function() { var $elem = $(this); var df = $.ajax({ url: $elem.data('url'), type: 'POST' }); df.done(function() { messages.addInfo(""Your extension has been locked."").hide().slideDown(); $elem.attr('disabled', true); $('h3, p.description').csrfEditable('disable').removeClass('editable'); }); return false; }); if (window._SW) try { window._SW(); } catch(e) { console.error(e); } }); }); " Add description on root route,"import config from flask import Flask, request import json import os import requests import modules ACCESS_TOKEN = os.environ.get('ACCESS_TOKEN', config.ACCESS_TOKEN) VERIFY_TOKEN = os.environ.get('VERIFY_TOKEN', config.VERIFY_TOKEN) app = Flask(__name__) @app.route('/') def about(): return 'Just A Rather Very Intelligent System, now on Messenger!' @app.route('/webhook/', methods=['GET', 'POST']) def webhook(): if request.method == 'POST': data = request.get_json(force=True) messaging_events = data['entry'][0]['messaging'] for event in messaging_events: sender = event['sender']['id'] if 'message' in event and 'text' in event['message']: text = event['message']['text'] payload = { 'recipient': { 'id': sender }, 'message': { 'text': modules.search(text) } } r = requests.post('https://graph.facebook.com/v2.6/me/messages', params={'access_token': ACCESS_TOKEN}, json=payload) return '' # 200 OK elif request.method == 'GET': # Verification if request.args.get('hub.verify_token') == VERIFY_TOKEN: return request.args.get('hub.challenge') else: return 'Error, wrong validation token' if __name__ == '__main__': app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 5000)), debug=True) ","import config from flask import Flask, request import json import os import requests import modules ACCESS_TOKEN = os.environ.get('ACCESS_TOKEN', config.ACCESS_TOKEN) VERIFY_TOKEN = os.environ.get('VERIFY_TOKEN', config.VERIFY_TOKEN) app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' @app.route('/webhook/', methods=['GET', 'POST']) def webhook(): if request.method == 'POST': data = request.get_json(force=True) messaging_events = data['entry'][0]['messaging'] for event in messaging_events: sender = event['sender']['id'] if 'message' in event and 'text' in event['message']: text = event['message']['text'] payload = { 'recipient': { 'id': sender }, 'message': { 'text': modules.search(text) } } r = requests.post('https://graph.facebook.com/v2.6/me/messages', params={'access_token': ACCESS_TOKEN}, json=payload) return '' # 200 OK elif request.method == 'GET': # Verification if request.args.get('hub.verify_token') == VERIFY_TOKEN: return request.args.get('hub.challenge') else: return 'Error, wrong validation token' if __name__ == '__main__': app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 5000)), debug=True) " TASK: Fix return typehint for getBuiltinType,"<?php namespace Neos\Flow\Reflection; /* * This file is part of the Neos.Flow package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use Neos\Flow\Annotations as Flow; /** * Extended version of the ReflectionParameter * * @Flow\Proxy(false) */ class ParameterReflection extends \ReflectionParameter { /** * @var string */ protected $parameterClassName; /** * Returns the declaring class * * @return ClassReflection The declaring class */ public function getDeclaringClass() { return new ClassReflection(parent::getDeclaringClass()->getName()); } /** * Returns the parameter class * * @return ClassReflection The parameter class */ public function getClass() { try { $class = parent::getClass(); } catch (\Exception $exception) { return null; } return is_object($class) ? new ClassReflection($class->getName()) : null; } /** * @return string|null The name of a builtin type (e.g. string, int) if it was declared for the parameter (scalar type declaration), null otherwise */ public function getBuiltinType() { $type = $this->getType(); if (!$type instanceof \ReflectionNamedType) { return null; } return $type->isBuiltin() ? $type->getName() : null; } } ","<?php namespace Neos\Flow\Reflection; /* * This file is part of the Neos.Flow package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use Neos\Flow\Annotations as Flow; /** * Extended version of the ReflectionParameter * * @Flow\Proxy(false) */ class ParameterReflection extends \ReflectionParameter { /** * @var string */ protected $parameterClassName; /** * Returns the declaring class * * @return ClassReflection The declaring class */ public function getDeclaringClass() { return new ClassReflection(parent::getDeclaringClass()->getName()); } /** * Returns the parameter class * * @return ClassReflection The parameter class */ public function getClass() { try { $class = parent::getClass(); } catch (\Exception $exception) { return null; } return is_object($class) ? new ClassReflection($class->getName()) : null; } /** * @return string The name of a builtin type (e.g. string, int) if it was declared for the parameter (scalar type declaration), null otherwise */ public function getBuiltinType() { $type = $this->getType(); if (!$type instanceof \ReflectionNamedType) { return null; } return $type->isBuiltin() ? $type->getName() : null; } } " Update for document form type,"<?php /* * This file is part of the VinceCmsSonataAdmin bundle. * * (c) Vincent Chalamon <vincentchalamon@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Vince\Bundle\CmsSonataAdminBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Vince\Bundle\CmsBundle\Entity\Area; /** * AreaType manage areas list for a specific template * * @author Vincent Chalamon <vincentchalamon@gmail.com> */ class AreaType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { foreach ($options['areas'] as $area) { /** @var Area $area */ $fieldOptions = array( 'label' => $area->getTitle(), 'required' => $area->isRequired() ); if ($area->getType() == 'document') { $fieldOptions['string'] = true; } $builder->add($area->getName(), $area->getType(), $fieldOptions); } } /** * {@inheritdoc} */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setRequired(array('areas')); } /** * {@inheritdoc} */ public function getName() { return 'area'; } /** * {@inheritdoc} */ public function getParent() { return 'form'; } }","<?php /* * This file is part of the VinceCmsSonataAdmin bundle. * * (c) Vincent Chalamon <vincentchalamon@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Vince\Bundle\CmsSonataAdminBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Vince\Bundle\CmsBundle\Entity\Area; /** * AreaType manage areas list for a specific template * * @author Vincent Chalamon <vincentchalamon@gmail.com> */ class AreaType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { foreach ($options['areas'] as $area) { /** @var Area $area */ $builder->add($area->getName(), $area->getType(), array( 'label' => $area->getTitle(), 'required' => $area->isRequired() ) ); } } /** * {@inheritdoc} */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setRequired(array('areas')); } /** * {@inheritdoc} */ public function getName() { return 'area'; } /** * {@inheritdoc} */ public function getParent() { return 'form'; } }" Fix grunt not copying files correctly when syncing sometimes,"'use strict'; // # Globbing // for performance reasons we're only matching one level down: // 'test/spec/{,*/}*.js' // use this if you want to match all subfolders: // 'test/spec/**/*.js' module.exports = function (grunt) { // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // configurable paths var config = { app: 'upload/', dist: '../' }; grunt.initConfig({ config: config, watch: { upload: { files: ['<%= config.app %>/**'], tasks: ['sync:main'] } }, sync: { main: { files: [{ expand: true, cwd: '<%= config.app %>', src: [ '**' ], dest: '<%= config.dist %>' }] } }, copy: { dist: { files: [{ expand: true, dot: true, cwd: '<%= config.app %>', dest: '<%= config.dist %>', src: [ '**' ] }] } } }); grunt.loadNpmTasks('grunt-newer'); grunt.registerTask('live', [ 'build', 'watch' ]); grunt.registerTask('build', [ 'copy:dist' ]); grunt.registerTask('default', [ 'build' ]); };","'use strict'; // # Globbing // for performance reasons we're only matching one level down: // 'test/spec/{,*/}*.js' // use this if you want to match all subfolders: // 'test/spec/**/*.js' module.exports = function (grunt) { // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // configurable paths var config = { app: 'upload/', dist: '../' }; grunt.initConfig({ config: config, watch: { upload: { files: ['<%= config.app %>/**'], tasks: ['sync:main'] } }, sync: { main: { files: [{ cwd: '<%= config.app %>', src: [ '**' ], dest: '<%= config.dist %>' }] } }, copy: { dist: { files: [{ expand: true, dot: true, cwd: '<%= config.app %>', dest: '<%= config.dist %>', src: [ '**' ] }] } } }); grunt.loadNpmTasks('grunt-newer'); grunt.registerTask('live', [ 'build', 'watch' ]); grunt.registerTask('build', [ 'newer:copy:dist' ]); grunt.registerTask('default', [ 'build' ]); };" Fix missing this in function call,"var util = require('util'); var dsUtil = require('./_utils.js'); var Baro = function(data) { this.config = data.Config; this.start = new Date(1000 * data.Activation.sec); this.end = new Date(1000 * data.Expiry.sec); this.location = data.Node; this.manifest = data.Manifest; } Baro.prototype.toString = function() { if(!this.isActive()) { return 'Baro is not here yet, he will arrive in ' + this.getStartString() + ' at ' + this.location; } var baroString = ''; for(i in this.manifest) { baroString += util.format('== %s ==\n' + '- price: %d ducats + %dcr -\n\n', this.manifest[i].ItemType, this.manifest[i].PrimePrice, this.manifest[i].RegularPrice); } baroString += 'Trader departing in ' + this.getEndString(); return baroString; } Baro.prototype.getStartString = function() { return dsUtil.timeDeltaToString(this.start.getTime() - Date.now()); } Baro.prototype.getEndString = function() { return dsUtil.timeDeltaToString(this.end.getTime() - Date.now()); } Baro.prototype.isActive = function() { return (this.start.getTime() < Date.now() && this.end.getTime() > Date.now()); } module.exports = Baro; ","var util = require('util'); var dsUtil = require('./_utils.js'); var Baro = function(data) { this.config = data.Config; this.start = new Date(1000 * data.Activation.sec); this.end = new Date(1000 * data.Expiry.sec); this.location = data.Node; this.manifest = data.Manifest; } Baro.prototype.toString = function() { if(!this.isActive()) { return 'Baro is not here yet, he will arrive in ' + this.getStartString() + ' at ' + this.location; } var baroString = ''; for(i in this.manifest) { baroString += util.format('== %s ==\n' + '- price: %d ducats + %dcr -\n\n', this.manifest[i].ItemType, this.manifest[i].PrimePrice, this.manifest[i].RegularPrice); } baroString += 'Trader departing in ' + getEndString(); return baroString; } Baro.prototype.getStartString = function() { return dsUtil.timeDeltaToString(this.start.getTime() - Date.now()); } Baro.prototype.getEndString = function() { return dsUtil.timeDeltaToString(this.end.getTime() - Date.now()); } Baro.prototype.isActive = function() { return (this.start.getTime() < Date.now() && this.end.getTime() > Date.now()); } module.exports = Baro; " "Revert ""zmiana pola z data"" This reverts commit 5b4dd9eb","<?php namespace Coyote\Services\Elasticsearch\Builders\Forum; use Coyote\Services\Elasticsearch\Filters\Post\OnlyThoseWithAccess; use Coyote\Services\Elasticsearch\Filters\Term; use Coyote\Services\Elasticsearch\MoreLikeThis; use Coyote\Services\Elasticsearch\QueryBuilder; use Coyote\Topic; class MoreLikeThisBuilder extends QueryBuilder { /** * @var Topic */ private $topic; /** * @var int[] */ private $forumId; /** * @param Topic $topic * @param int[] $forumsId */ public function __construct(Topic $topic, $forumsId) { $this->topic = $topic; $this->forumId = $forumsId; } /** * @return array */ public function build() { $mlt = new MoreLikeThis(['subject', 'posts.text']); $mlt->addDoc([ '_index' => config('elasticsearch.default_index'), '_type' => '_doc', '_id' => ""topic_{$this->topic->id}"" ]); $this->must($mlt); $this->must(new Term('model', 'topic')); $this->must(new OnlyThoseWithAccess($this->forumId)); // we need only those fields to save in cache $this->source(['id', 'subject', 'slug', 'updated_at', 'forum.*']); return parent::build(); } } ","<?php namespace Coyote\Services\Elasticsearch\Builders\Forum; use Coyote\Services\Elasticsearch\Filters\Post\OnlyThoseWithAccess; use Coyote\Services\Elasticsearch\Filters\Term; use Coyote\Services\Elasticsearch\MoreLikeThis; use Coyote\Services\Elasticsearch\QueryBuilder; use Coyote\Topic; class MoreLikeThisBuilder extends QueryBuilder { /** * @var Topic */ private $topic; /** * @var int[] */ private $forumId; /** * @param Topic $topic * @param int[] $forumsId */ public function __construct(Topic $topic, $forumsId) { $this->topic = $topic; $this->forumId = $forumsId; } /** * @return array */ public function build() { $mlt = new MoreLikeThis(['subject', 'posts.text']); $mlt->addDoc([ '_index' => config('elasticsearch.default_index'), '_type' => '_doc', '_id' => ""topic_{$this->topic->id}"" ]); $this->must($mlt); $this->must(new Term('model', 'topic')); $this->must(new OnlyThoseWithAccess($this->forumId)); // we need only those fields to save in cache $this->source(['id', 'subject', 'slug', 'created_at', 'forum.*']); return parent::build(); } } " Update links to privacy and contact page,"import React from 'react' import i18n from '../../i18n' const MapFooter = () => ( <footer className=""map-footer""> <ul> <li className=""map-footer-home""> <a href=""http://ernte-teilen.org/"" target=""_blank"" rel=""noopener noreferrer"" > ernte-teilen.org </a> </li> <li className=""map-footer-terms""> <a href=""http://ernte-teilen.org/datenschutz/"" target=""_blank"" rel=""noopener noreferrer"" > {i18n.t('nav.privacy')} </a> </li> <li className=""map-footer-imprint""> <a href=""http://ernte-teilen.org/impressum/"" target=""_blank"" rel=""noopener noreferrer"" > {i18n.t('nav.imprint')} </a> </li> </ul> {i18n.t('nav.map_data')} <a href=""https://www.mapbox.com/about/maps/"" target=""_blank"" rel=""noopener noreferrer"" > © MapBox </a> | <a href=""http://www.openstreetmap.org/about/"" target=""_blank"" rel=""noopener noreferrer"" > © OpenStreetMap </a> </footer> ) export default MapFooter ","import React from 'react' import i18n from '../../i18n' const MapFooter = () => ( <footer className=""map-footer""> <ul> <li className=""map-footer-home""> <a href=""http://ernte-teilen.org/"" target=""_blank"" rel=""noopener noreferrer"" > ernte-teilen.org </a> </li> <li className=""map-footer-terms""> <a href=""http://ernte-teilen.org/privacy/"" target=""_blank"" rel=""noopener noreferrer"" > {i18n.t('nav.privacy')} </a> </li> <li className=""map-footer-imprint""> <a href=""http://ernte-teilen.org/contact/"" target=""_blank"" rel=""noopener noreferrer"" > {i18n.t('nav.imprint')} </a> </li> </ul> {i18n.t('nav.map_data')} <a href=""https://www.mapbox.com/about/maps/"" target=""_blank"" rel=""noopener noreferrer"" > © MapBox </a> | <a href=""http://www.openstreetmap.org/about/"" target=""_blank"" rel=""noopener noreferrer"" > © OpenStreetMap </a> </footer> ) export default MapFooter " Add login required to new and edit post views,"from flask import render_template, redirect, url_for from flask_classy import FlaskView, route from flask_user import login_required from ..models import PostModel from ..forms import PostForm class Post(FlaskView): """""" Here will handle post creations, delete and update."""""" def get(self, entity_id): post = PostModel() post = post.get(entity_id) return render_template(""post/post.html"", post=post) @login_required @route(""/new/"", methods=[""GET"", ""POST""]) def new(self): form = PostForm() if form.validate_on_submit(): post = PostModel(**form.data) post.put() return redirect(url_for(""Post:get"", entity_id=post.id)) return render_template(""post/post_form.html"", form=form, url=""Post:new"") @login_required @route(""/edit/<entity_id>"", methods=[""GET"", ""POST""]) def edit(self, entity_id): post = PostModel() entity = post.get(entity_id) form = PostForm(**entity) if form.validate_on_submit(): post.update(entity_id, form.data) return redirect(url_for(""Post:get"", entity_id=entity_id)) return render_template(""post/post_form.html"", form=form, url=""Post:edit"", entity_id=entity_id) ","from flask import render_template, redirect, url_for from flask_classy import FlaskView, route from ..models import PostModel from ..forms import PostForm class Post(FlaskView): """""" Here will handle post creations, delete and update."""""" def get(self, entity_id): post = PostModel() post = post.get(entity_id) return render_template(""post/post.html"", post=post) @route(""/new/"", methods=[""GET"", ""POST""]) def new(self): form = PostForm() if form.validate_on_submit(): post = PostModel(**form.data) post.put() return redirect(url_for(""Post:get"", entity_id=post.id)) return render_template(""post/post_form.html"", form=form, url=""Post:new"") @route(""/edit/<entity_id>"", methods=[""GET"", ""POST""]) def edit(self, entity_id): post = PostModel() entity = post.get(entity_id) form = PostForm(**entity) if form.validate_on_submit(): post.update(entity_id, form.data) return redirect(url_for(""Post:get"", entity_id=entity_id)) return render_template(""post/post_form.html"", form=form, url=""Post:edit"", entity_id=entity_id) " "Copy over all cordova.cordova.* properties that plugins add to the cordova.* level This is done by plugins like ionic-pluing-keyboard. They assume that cordova is available on the window object - this does not have to be true","// Loads all the cordova plugins module.exports = function(context) { // Load each plugin var pluginList = require('cordova/plugin_list'); var modulemapper = require('cordova/modulemapper'); var channel = require('cordova/channel'); pluginList.forEach(function(module) { try { if (module.clobbers && module.clobbers.length) { for (var j = 0; j < module.clobbers.length; j++) { modulemapper.clobbers(module.id, module.clobbers[j]); } } if (module.merges && module.merges.length) { for (var k = 0; k < module.merges.length; k++) { modulemapper.merges(module.id, module.merges[k]); } } // Finally, if runs is truthy we want to simply require() the module. if (module.runs) { modulemapper.runs(module.id); } } catch (e) { console.error('Error loading Plugin %s', module.id, e); } }); modulemapper.mapModules(context); // FIX for plugins like ionic-plugin-keyboard that assume that // cordova is always available on window object. This is not always true if (context.cordova) { for (var key in context.cordova) { if (typeof context[key] !== 'undefined') { console.error('cordova[' + key + '] is already defined, the plugin is trying to re-define it'); } else { context[key] = context.cordova[key]; } } } // END of fix setTimeout(function() { channel.onPluginsReady.fire(); }, 0); }; ","// Loads all the cordova plugins module.exports = function() { // Load each plugin var pluginList = require('cordova/plugin_list'); var modulemapper = require('cordova/modulemapper'); var channel = require('cordova/channel'); pluginList.forEach(function(module) { try { if (module.clobbers && module.clobbers.length) { for (var j = 0; j < module.clobbers.length; j++) { modulemapper.clobbers(module.id, module.clobbers[j]); } } if (module.merges && module.merges.length) { for (var k = 0; k < module.merges.length; k++) { modulemapper.merges(module.id, module.merges[k]); } } // Finally, if runs is truthy we want to simply require() the module. if (module.runs) { modulemapper.runs(module.id); } modulemapper.mapModules(cordova); } catch (e) { console.error('Error loading Plugin %s', module.id, e); } }); setTimeout(function() { channel.onPluginsReady.fire(); }, 0); }; " "Rewrite import to avoid accidental misuse Don't import the AuroraWatchUK class into the snapshot namespace, it enables the original AuroraWatchUK class to be used when it was intended to use the snapshot version, AuroraWatchUK_SS.","import aurorawatchuk __author__ = 'Steve Marple' __version__ = '0.1.2' __license__ = 'MIT' class AuroraWatchUK_SS(object): """"""Take a snapshot of the AuroraWatch UK status. This class mimics the behaviour of the :class:`.aurorawatchuk.AuroraWatchUK` class but its fields are evaluated just once and cached, at the time first requested. Thus the values it returns are snapshots of the ``status``, ``activity`` and ``description`` fields. This is useful when the information may be required multiple times as it avoids the possibility that the value could change between uses. If the information is not required then no network traffic is generated. For documentation see :class:`.aurorawatchuk.AuroraWatchUK`."""""" def __init__(self, *args, **kwargs): object.__setattr__(self, '_awuk', aurorawatchuk.AuroraWatchUK(*args, **kwargs)) object.__setattr__(self, '_fields', {}) def __getattr__(self, item): if item[0] != '_': # Cache this item if item not in self._fields: self._fields[item] = getattr(self._awuk, item) return self._fields[item] def __setattr__(self, key, value): if key[0] == '_': raise AttributeError else: return object.__setattr__(self, key, value) def __delattr__(self, item): if item[0] == '_': raise AttributeError else: return object.__delattr__(self, item) ","from aurorawatchuk import AuroraWatchUK __author__ = 'Steve Marple' __version__ = '0.1.2' __license__ = 'MIT' class AuroraWatchUK_SS(object): """"""Take a snapshot of the AuroraWatch UK status. This class mimics the behaviour of the :class:`.aurorawatchuk.AuroraWatchUK` class but its fields are evaluated just once and cached, at the time first requested. Thus the values it returns are snapshots of the ``status``, ``activity`` and ``description`` fields. This is useful when the information may be required multiple times as it avoids the possibility that the value could change between uses. If the information is not required then no network traffic is generated. For documentation see :class:`.aurorawatchuk.AuroraWatchUK`."""""" def __init__(self, *args, **kwargs): object.__setattr__(self, '_awuk', AuroraWatchUK(*args, **kwargs)) object.__setattr__(self, '_fields', {}) def __getattr__(self, item): if item[0] != '_': # Cache this item if item not in self._fields: self._fields[item] = getattr(self._awuk, item) return self._fields[item] def __setattr__(self, key, value): if key[0] == '_': raise AttributeError else: return object.__setattr__(self, key, value) def __delattr__(self, item): if item[0] == '_': raise AttributeError else: return object.__delattr__(self, item) " "Make the bot respond to its name Implements GH-7","from twisted.plugin import IPlugin from heufybot.moduleinterface import BotModule, IBotModule from zope.interface import implements class CommandHandler(BotModule): implements(IPlugin, IBotModule) name = ""CommandHandler"" def actions(self): return [ (""message-channel"", 1, self.handleChannelMessage), (""message-user"", 1, self.handlePrivateMessage) ] def handleChannelMessage(self, server, channel, user, messageBody): message = { ""server"": server, ""source"": channel.name, ""channel"": channel, ""user"": user, ""body"": messageBody } self._handleCommand(message) def handlePrivateMessage(self, server, user, messageBody): message = { ""server"": server, ""source"": user.nick, ""user"": user, ""body"": messageBody } self._handleCommand(message) def _handleCommand(self, message): commandPrefix = self.bot.config.serverItemWithDefault(message[""server""], ""command_prefix"", ""!"") botNick = self.bot.servers[message[""server""]].nick.lower() params = message[""body""].split() if message[""body""].startswith(commandPrefix): message[""command""] = params[0][params[0].index(commandPrefix) + len(commandPrefix):] del params[0] elif message[""body""].lower().startswith(botNick): message[""command""] = params[1] del params[0:2] else: return # We don't need to be handling things that aren't bot commands message[""params""] = params self.bot.moduleHandler.runProcessingAction(""botmessage"", message) commandHandler = CommandHandler() ","from twisted.plugin import IPlugin from heufybot.moduleinterface import BotModule, IBotModule from zope.interface import implements class CommandHandler(BotModule): implements(IPlugin, IBotModule) name = ""CommandHandler"" def actions(self): return [ (""message-channel"", 1, self.handleChannelMessage), (""message-user"", 1, self.handlePrivateMessage) ] def handleChannelMessage(self, server, channel, user, messageBody): message = { ""server"": server, ""source"": channel.name, ""channel"": channel, ""user"": user, ""body"": messageBody } self._handleCommand(message) def handlePrivateMessage(self, server, user, messageBody): message = { ""server"": server, ""source"": user.nick, ""user"": user, ""body"": messageBody } self._handleCommand(message) def _handleCommand(self, message): commandPrefix = self.bot.config.serverItemWithDefault(message[""server""], ""command_prefix"", ""!"") if not message[""body""].startswith(commandPrefix): return # We don't need to be handling things that aren't bot commands params = message[""body""].split() message[""command""] = params[0][params[0].index(commandPrefix) + len(commandPrefix):] del params[0] message[""params""] = params self.bot.moduleHandler.runProcessingAction(""botmessage"", message) commandHandler = CommandHandler() " Allow `package.php` to proxy the original one,"var request = require('request'); var rest = require('rest-sugar'); var sugar = require('object-sugar'); var Library = require('./schemas').Library; module.exports = function(app) { var root = '/api/v1'; app.get(root + '/libraries/:name/:version', function(req, res) { var version = req.params.version; sugar.getOne(Library, { name: req.params.name }, function(err, library) { if(err) { return res.send(404); } var d = library.assets.filter(function(asset) { return asset.version === version; })[0]; if(d && d.files) { return res.json(d.files); } return res.send(404); }); }); app.get(root + '/libraries/:name', function(req, res) { sugar.getOne(Library, { name: req.params.name }, function(err, library) { if(err) { return res.send(404); } res.json([library]); }); }); var api = rest(app, root, { libraries: Library }, sugar); api.pre(function() { api.use(rest.only('GET')); }); app.get('/packages.php', function(req, res) { request.get({ url: 'http://api.jsdelivr.com/packages.php', pool: { maxSockets: 100 } }).pipe(res); }); }; ","var rest = require('rest-sugar'); var sugar = require('object-sugar'); var Library = require('./schemas').Library; module.exports = function(app) { var root = '/api/v1'; app.get(root + '/libraries/:name/:version', function(req, res) { var version = req.params.version; sugar.getOne(Library, { name: req.params.name }, function(err, library) { if(err) { return res.send(404); } var d = library.assets.filter(function(asset) { return asset.version === version; })[0]; if(d && d.files) { return res.json(d.files); } return res.send(404); }); }); app.get(root + '/libraries/:name', function(req, res) { sugar.getOne(Library, { name: req.params.name }, function(err, library) { if(err) { return res.send(404); } res.json([library]); }); }); var api = rest(app, root, { libraries: Library }, sugar); api.pre(function() { api.use(rest.only('GET')); }); var librariesRoute = app.routes.get.filter(function(v) { return v.path === '/api/v1/libraries'; })[0]; app.get('/packages.php', librariesRoute.callbacks[0]); }; " Use project slug as folder name instead of project name," import os import datetime from django.conf import settings from django.core.management.base import BaseCommand, CommandError from pontoon.administration.views import _update_from_repository from pontoon.base.models import Project class Command(BaseCommand): help = 'Update all projects from their repositories and store changes \ to the database' def handle(self, *args, **options): for project in Project.objects.all(): try: repository_type = project.repository_type repository_url = project.repository_url repository_path_master = os.path.join( settings.MEDIA_ROOT, repository_type, project.slug) _update_from_repository( project, repository_type, repository_url, repository_path_master) now = datetime.datetime.now() self.stdout.write( '[%s]: Successfully updated project ""%s""\n' % (now, project)) except Exception as e: now = datetime.datetime.now() raise CommandError( '[%s]: UpdateProjectsFromRepositoryError: %s\n' % (now, unicode(e))) "," import os import datetime from django.conf import settings from django.core.management.base import BaseCommand, CommandError from pontoon.administration.views import _update_from_repository from pontoon.base.models import Project class Command(BaseCommand): help = 'Update all projects from their repositories and store changes \ to the database' def handle(self, *args, **options): for project in Project.objects.all(): try: repository_type = project.repository_type repository_url = project.repository_url repository_path_master = os.path.join( settings.MEDIA_ROOT, repository_type, project.name) _update_from_repository( project, repository_type, repository_url, repository_path_master) now = datetime.datetime.now() self.stdout.write( '[%s]: Successfully updated project ""%s""\n' % (now, project)) except Exception as e: now = datetime.datetime.now() raise CommandError( '[%s]: UpdateProjectsFromRepositoryError: %s\n' % (now, unicode(e))) " Fix import error for custom Field validation,"""""""This module provides SQL Server specific fields for Django models."""""" from django.db.models import AutoField, ForeignKey, IntegerField from django.forms import ValidationError class BigAutoField(AutoField): """"""A bigint IDENTITY field"""""" def get_internal_type(self): return ""BigAutoField"" def to_python(self, value): if value is None: return value try: return long(value) except (TypeError, ValueError): raise ValidationError( _(""This value must be an long."")) def get_db_prep_value(self, value): if value is None: return None return long(value) class BigForeignKey(ForeignKey): """"""A ForeignKey field that points to a BigAutoField or BigIntegerField"""""" def db_type(self): return BigIntegerField().db_type() class BigIntegerField(IntegerField): """"""A BigInteger field, until Django ticket #399 lands (if ever.)"""""" def get_internal_type(self): return ""BigIntegerField"" def to_python(self, value): if value is None: return value try: return long(value) except (TypeError, ValueError): raise ValidationError( _(""This value must be an long."")) def get_db_prep_value(self, value): if value is None: return None return long(value) ","""""""This module provides SQL Server specific fields for Django models."""""" from django.db.models import AutoField, ForeignKey, IntegerField class BigAutoField(AutoField): """"""A bigint IDENTITY field"""""" def get_internal_type(self): return ""BigAutoField"" def to_python(self, value): if value is None: return value try: return long(value) except (TypeError, ValueError): raise exceptions.ValidationError( _(""This value must be an long."")) def get_db_prep_value(self, value): if value is None: return None return long(value) class BigForeignKey(ForeignKey): """"""A ForeignKey field that points to a BigAutoField or BigIntegerField"""""" def db_type(self): return BigIntegerField().db_type() class BigIntegerField(IntegerField): """"""A BigInteger field, until Django ticket #399 lands (if ever.)"""""" def get_internal_type(self): return ""BigIntegerField"" def to_python(self, value): if value is None: return value try: return long(value) except (TypeError, ValueError): raise exceptions.ValidationError( _(""This value must be an long."")) def get_db_prep_value(self, value): if value is None: return None return long(value) " Set Published date as subtitle,"(function (env) { ""use strict""; env.ddg_spice_cve_summary = function(api_result){ // fail the spice if the API does not return a result if(api_result == undefined) { return Spice.failed('cve_summary'); } // Validate the response (customize for your Spice) if (api_result.error) { return Spice.failed('cve_summary'); } // Render the response Spice.add({ id: ""cve_summary"", // Customize these properties name: ""CVE Summary"", data: api_result, meta: { sourceName: ""cve.circl.lu"", sourceUrl: 'http://cve.circl.lu/cve/' + api_result.id }, templates: { group: 'text', options: { content: Spice.cve_summary.content, moreAt: true } }, normalize: function(item) { return { title: api_result.id, subtitle: ""Published "" + api_result.Published, description: api_result.summary }; } }); }; }(this)); ","(function (env) { ""use strict""; env.ddg_spice_cve_summary = function(api_result){ // fail the spice if the API does not return a result if(api_result == undefined) { return Spice.failed('cve_summary'); } // Validate the response (customize for your Spice) if (api_result.error) { return Spice.failed('cve_summary'); } // Render the response Spice.add({ id: ""cve_summary"", // Customize these properties name: ""CVE Summary"", data: api_result, meta: { sourceName: ""cve.circl.lu"", sourceUrl: 'http://cve.circl.lu/cve/' + api_result.id }, templates: { group: 'text', options: { content: Spice.cve_summary.content, moreAt: true } }, normalize: function(item) { return { title: api_result.id, description: api_result.summary }; } }); }; }(this)); " New: Print SEP urls for debug,"from lxml import html import re import requests from constants import SEP_URL class SEPSearchResult(): query = None results = None def __init__(self, query): self.set_query(query) def set_query(self, query): pattern = re.compile('[^a-zA-Z\d\s]') stripped_query = re.sub(pattern, '', query) self.query = str(stripped_query).lower().split() @property def url(self): url = SEP_URL + ""search/searcher.py?query="" for word in self.query: url += word + ""+"" print url return url def request_results(self): page = requests.get(self.url) # Remvoe bold tags text_no_bold = re.sub('</? ?b>', '', page.text) text_no_newlines = re.sub('\n', '', text_no_bold) tree = html.fromstring(text_no_newlines) titles = tree.xpath(""//div[@class='result_title']/a/text()"") urls = tree.xpath(""//div[@class='result_title']/a/@href"") # Build the output tuples output = [] for i in range(len(titles)): output.append( { ""title"": titles[i], ""url"": SEP_URL + urls[i].lstrip(""../"") } ) self.results = output return output","from lxml import html import re import requests from constants import SEP_URL class SEPSearchResult(): query = None results = None def __init__(self, query): self.set_query(query) def set_query(self, query): pattern = re.compile('[^a-zA-Z\d\s]') stripped_query = re.sub(pattern, '', query) self.query = str(stripped_query).lower().split() @property def url(self): url = SEP_URL + ""search/searcher.py?query="" for word in self.query: url += word + ""+"" return url def request_results(self): page = requests.get(self.url) # Remvoe bold tags text_no_bold = re.sub('</? ?b>', '', page.text) text_no_newlines = re.sub('\n', '', text_no_bold) tree = html.fromstring(text_no_newlines) titles = tree.xpath(""//div[@class='result_title']/a/text()"") urls = tree.xpath(""//div[@class='result_title']/a/@href"") # Build the output tuples output = [] for i in range(len(titles)): output.append( { ""title"": titles[i], ""url"": SEP_URL + urls[i].lstrip(""../"") } ) self.results = output return output" Make shell=True for the conda subprocess,"import subprocess from os import unlink from os.path import realpath, islink, isfile, isdir import sys import shutil import time def rm_rf(path): if islink(path) or isfile(path): # Note that we have to check if the destination is a link because # exists('/path/to/dead-link') will return False, although # islink('/path/to/dead-link') is True. unlink(path) elif isdir(path): if sys.platform == 'win32': subprocess.check_call(['cmd', '/c', 'rd', '/s', '/q', path]) else: shutil.rmtree(path) def main(pyversion, envdir): envdir = realpath(envdir) rm_rf(envdir) packages = ['cython', 'scipy', 'nose'] while True: p = subprocess.Popen(['conda', 'create', '--yes', '-p', envdir, 'python=%s' % pyversion] + packages, stderr=subprocess.PIPE, shell=True) stdout, stderr = p.communicate() if p.returncode != 0: print >> sys.stderr, stderr if ""LOCKERROR"" in stderr: print ""Conda is locked. Trying again in 60 seconds"" print time.sleep(60) else: sys.exit(p.returncode) else: sys.exit(p.returncode) if __name__ == '__main__': sys.exit(main(sys.argv[1], sys.argv[2])) ","import subprocess from os import unlink from os.path import realpath, islink, isfile, isdir import sys import shutil import time def rm_rf(path): if islink(path) or isfile(path): # Note that we have to check if the destination is a link because # exists('/path/to/dead-link') will return False, although # islink('/path/to/dead-link') is True. unlink(path) elif isdir(path): if sys.platform == 'win32': subprocess.check_call(['cmd', '/c', 'rd', '/s', '/q', path]) else: shutil.rmtree(path) def main(pyversion, envdir): envdir = realpath(envdir) rm_rf(envdir) packages = ['cython', 'scipy', 'nose'] while True: p = subprocess.Popen(['conda', 'create', '--yes', '-p', envdir, 'python=%s' % pyversion] + packages, stderr=subprocess.PIPE) stdout, stderr = p.communicate() if p.returncode != 0: print >> sys.stderr, stderr if ""LOCKERROR"" in stderr: print ""Conda is locked. Trying again in 60 seconds"" print time.sleep(60) else: sys.exit(p.returncode) else: sys.exit(p.returncode) if __name__ == '__main__': sys.exit(main(sys.argv[1], sys.argv[2])) " "Fix an issue with rendering some commit hovercards Summary: This logic wasn't quite right. Test Plan: Hovered over a recognized commit, got a valid hovercard Reviewers: chad Reviewed By: chad Differential Revision: https://secure.phabricator.com/D14925","<?php final class DiffusionHovercardEngineExtension extends PhabricatorHovercardEngineExtension { const EXTENSIONKEY = 'diffusion'; public function isExtensionEnabled() { return PhabricatorApplication::isClassInstalled( 'PhabricatorDiffusionApplication'); } public function getExtensionName() { return pht('Diffusion Commits'); } public function canRenderObjectHovercard($object) { return ($object instanceof PhabricatorRepositoryCommit); } public function renderHovercard( PhabricatorHovercardView $hovercard, PhabricatorObjectHandle $handle, $commit, $data) { $viewer = $this->getViewer(); $author_phid = $commit->getAuthorPHID(); if ($author_phid) { $author = $viewer->renderHandle($author_phid); } else { $commit_data = $commit->loadCommitData(); $author = phutil_tag('em', array(), $commit_data->getAuthorName()); } $hovercard->setTitle($handle->getName()); $hovercard->setDetail($commit->getSummary()); $hovercard->addField(pht('Author'), $author); $hovercard->addField(pht('Date'), phabricator_date($commit->getEpoch(), $viewer)); if ($commit->getAuditStatus() != PhabricatorAuditCommitStatusConstants::NONE) { $hovercard->addField(pht('Audit Status'), PhabricatorAuditCommitStatusConstants::getStatusName( $commit->getAuditStatus())); } } } ","<?php final class DiffusionHovercardEngineExtension extends PhabricatorHovercardEngineExtension { const EXTENSIONKEY = 'diffusion'; public function isExtensionEnabled() { return PhabricatorApplication::isClassInstalled( 'PhabricatorDiffusionApplication'); } public function getExtensionName() { return pht('Diffusion Commits'); } public function canRenderObjectHovercard($object) { return ($object instanceof PhabricatorRepositoryCommit); } public function renderHovercard( PhabricatorHovercardView $hovercard, PhabricatorObjectHandle $handle, $commit, $data) { $viewer = $this->getViewer(); $author_phid = $commit->getAuthorPHID(); if ($author_phid) { $author = $viewer->loadHandle($author)->renderLink(); } else { $commit_data = $commit->loadCommitData(); $author = phutil_tag('em', array(), $commit_data->getAuthorName()); } $hovercard->setTitle($handle->getName()); $hovercard->setDetail($commit->getSummary()); $hovercard->addField(pht('Author'), $author); $hovercard->addField(pht('Date'), phabricator_date($commit->getEpoch(), $viewer)); if ($commit->getAuditStatus() != PhabricatorAuditCommitStatusConstants::NONE) { $hovercard->addField(pht('Audit Status'), PhabricatorAuditCommitStatusConstants::getStatusName( $commit->getAuditStatus())); } } } " Integrate authenticator into to app,"package com.hamishrickerby.http_server; import com.hamishrickerby.http_server.auth.Authenticator; import com.hamishrickerby.http_server.auth.RequestAuthenticator; /** * Created by rickerbh on 15/08/2016. */ public class App { private static String DEFAULT_PORT = ""5000""; public static void main(String[] args) { AppArguments arguments = new AppArguments(args); Integer port = Integer.parseInt(arguments.getOrDefault(""-p"", DEFAULT_PORT)); String rootDirectory = arguments.get(""-d""); if (rootDirectory == null) { System.err.println(""Must provide a root directory with a -d argument.""); System.exit(1); } Server server = null; try { server = new AsynchronousSocketServer(port); Logger logger = new MemoryLogger(); HTTPResponseCoordinator coordinator = new HTTPResponseCoordinator(rootDirectory, logger); coordinator.setAuthenticator(getAuthenticator()); server.setResponseCoordinator(coordinator); server.start(); System.out.println(""Mounted "" + rootDirectory + "" as the directory to serve from.""); System.out.println(""Server started on port "" + port); server.awaitTermination(Long.MAX_VALUE); } catch (Exception e) { e.printStackTrace(); } finally { server.stop(); } } public static Authenticator getAuthenticator() { RequestAuthenticator authenticator = new RequestAuthenticator(); authenticator.addRoute(""/logs""); authenticator.addCredentials(""admin"", ""hunter2""); return authenticator; } } ","package com.hamishrickerby.http_server; import com.hamishrickerby.http_server.responses.ResponseCoordinator; /** * Created by rickerbh on 15/08/2016. */ public class App { private static String DEFAULT_PORT = ""5000""; public static void main(String[] args) { AppArguments arguments = new AppArguments(args); Integer port = Integer.parseInt(arguments.getOrDefault(""-p"", DEFAULT_PORT)); String rootDirectory = arguments.get(""-d""); if (rootDirectory == null) { System.err.println(""Must provide a root directory with a -d argument.""); System.exit(1); } Server server = null; try { server = new AsynchronousSocketServer(port); Logger logger = new MemoryLogger(); ResponseCoordinator coordinator = new HTTPResponseCoordinator(rootDirectory, logger); server.setResponseCoordinator(coordinator); server.start(); System.out.println(""Mounted "" + rootDirectory + "" as the directory to serve from.""); System.out.println(""Server started on port "" + port); server.awaitTermination(Long.MAX_VALUE); } catch (Exception e) { e.printStackTrace(); } finally { server.stop(); } } } " Fix key warning of snackbar elements,"import React from 'react'; import SnackbarItem from './SnackbarItem'; import './Snackbar.css'; import { useSnackbarContext } from '../../utils/SnackbarProvider'; const SnackbarContainer = () => { const { snackbarItems, hide } = useSnackbarContext(); const renderItem = item => { return <SnackbarItem key={item.itemId} options={item} onClose={hide} />; }; if (!snackbarItems) { return null; } const renderItems = () => { const items = { topLeft: [], topCenter: [], topRight: [], bottomLeft: [], bottomCenter: [], bottomRight: [], }; snackbarItems.map(item => { items[item.position].push(item); }); return ( <div> {Object.keys(items).map(pos => { if (!items[pos].length) { return null; } return ( <div key={pos} className={`sb-container sb-${pos}`}> {items[pos].map((item, index) => ( <div key={item.id + index}>{renderItem(item)}</div> ))} </div> ); })} </div> ); }; return <>{renderItems()}</>; }; export default SnackbarContainer; ","import React from 'react'; import SnackbarItem from './SnackbarItem'; import './Snackbar.css'; import { useSnackbarContext } from '../../utils/SnackbarProvider'; const SnackbarContainer = () => { const { snackbarItems, hide } = useSnackbarContext(); const renderItem = item => { return <SnackbarItem key={item.itemId} options={item} onClose={hide} />; }; if (!snackbarItems) { return null; } const renderItems = () => { const items = { topLeft: [], topCenter: [], topRight: [], bottomLeft: [], bottomCenter: [], bottomRight: [], }; snackbarItems.map(item => { items[item.position].push(item); }); return ( <div> {Object.keys(items).map(pos => { if (!items[pos].length) { return null; } return ( <div key={pos} className={`sb-container sb-${pos}`}> {items[pos].map(item => ( <div key={item.id}>{renderItem(item)}</div> ))} </div> ); })} </div> ); }; return <>{renderItems()}</>; }; export default SnackbarContainer; " "Replace placeholder text with site description Signed-off-by: Eddie Ringle <bacc1c505cb1756c59242c0a8ee25cd990a210e9@eringle.net>","<!DOCTYPE html> <html> <head> <title><?php wp_title('«', true, 'right'); bloginfo('name'); ?></title> <meta charset=""utf-8"" /> <link rel=""stylesheet"" type=""text/css"" href=""<?php bloginfo('template_directory'); ?>/style.css"" /> <link rel=""stylesheet"" type=""text/css"" href=""<?php bloginfo('template_directory'); ?>/css/superfish.css"" /> <?php wp_head(); comments_popup_script(400, 400); ?> </head> <body> <div id=""wrapper""> <div id=""header-wrap""> <div id=""header""> <div id=""logo""> <h1><a href=""/"">WicketPixie</a></h1> </div> <div id=""sideline""> <p><?php bloginfo('description'); ?></p> </div> </div> </div> <div id=""body-wrap""> <div id=""body""> <div id=""navigation""> <ul class=""sf-menu""> <?php if (!is_home()) { ?> <li><a href=""<?php bloginfo('home'); ?>"">Home</a></li> <?php } wp_list_pages('sort_column=menu_order&title_li='); ?> </ul> </div> <div id=""page"">","<!DOCTYPE html> <html> <head> <title><?php wp_title('«', true, 'right'); bloginfo('name'); ?></title> <meta charset=""utf-8"" /> <link rel=""stylesheet"" type=""text/css"" href=""<?php bloginfo('template_directory'); ?>/style.css"" /> <link rel=""stylesheet"" type=""text/css"" href=""<?php bloginfo('template_directory'); ?>/css/superfish.css"" /> <?php wp_head(); comments_popup_script(400, 400); ?> </head> <body> <div id=""wrapper""> <div id=""header-wrap""> <div id=""header""> <div id=""logo""> <h1><a href=""/"">WicketPixie</a></h1> </div> <div id=""sideline""> <p>< insert site description/status update here ></p> </div> </div> </div> <div id=""body-wrap""> <div id=""body""> <div id=""navigation""> <ul class=""sf-menu""> <?php if (!is_home()) { ?> <li><a href=""<?php bloginfo('home'); ?>"">Home</a></li> <?php } wp_list_pages('sort_column=menu_order&title_li='); ?> </ul> </div> <div id=""page"">" Add uncontrolled with default example,"import React, { Component } from ""react""; import PlaygroundSection from ""../PlaygroundSection""; import { Checkbox } from ""../../react-hig""; const checkboxStyle = { display: ""flex"", flexDirection: ""row"", justifyContent: ""space-between"" }; function logEvent(event) { let messageParts = [`Checkbox triggered a ${event.type} event`]; if (event.target.value !== undefined) { messageParts = messageParts.concat(`: ${event.target.value}`); } console.log(messageParts.join("""")); } class CheckboxSection extends Component { constructor(props) { super(props); this.state = { controlledChecked: false } } setControlledChecked = event => { this.setState({ controlledChecked: event.target.checked }); }; render() { return ( <PlaygroundSection title=""Checkbox""> <div style={checkboxStyle}> <Checkbox label=""Required"" required=""You must check this box"" /> <Checkbox label=""Disabled"" disabled={true} /> <Checkbox label=""Controlled"" checked={this.state.controlledChecked} onChange={this.setControlledChecked} /> <Checkbox label=""Uncontrolled"" /> <Checkbox label=""Uncontrolled w/ default"" defaultChecked={true} /> <Checkbox label=""With event logging"" onHover={logEvent} onChange={logEvent} onFocus={logEvent} /> </div> </PlaygroundSection> ); } } export default CheckboxSection; ","import React, { Component } from ""react""; import PlaygroundSection from ""../PlaygroundSection""; import { Checkbox } from ""../../react-hig""; const checkboxStyle = { display: ""flex"", flexDirection: ""row"", justifyContent: ""space-between"" }; function logEvent(event) { let messageParts = [`Checkbox triggered a ${event.type} event`]; if (event.target.value !== undefined) { messageParts = messageParts.concat(`: ${event.target.value}`); } console.log(messageParts.join("""")); } class CheckboxSection extends Component { constructor(props) { super(props); this.state = { controlledChecked: false } } setControlledChecked = event => { this.setState({ controlledChecked: event.target.checked }); }; render() { return ( <PlaygroundSection title=""Checkbox""> <div style={checkboxStyle}> <Checkbox label=""Required"" required=""You must check this box"" /> <Checkbox label=""Disabled"" disabled={true} /> <Checkbox label=""Controlled"" checked={this.state.controlledChecked} onChange={this.setControlledChecked} /> <Checkbox label=""Uncontrolled"" /> <Checkbox label=""With event logging"" onHover={logEvent} onChange={logEvent} onFocus={logEvent} /> </div> </PlaygroundSection> ); } } export default CheckboxSection; " Update test to ensure that default configuration values are available via getConfOpt,"from synapse.tests.common import * import synapse.lib.config as s_config class ConfTest(SynTest): def test_conf_base(self): defs = ( ('fooval',{'type':'int','doc':'what is foo val?','defval':99}), ('enabled',{'type':'bool','doc':'is thing enabled?','defval':0}), ) data = {} def callback(v): data['woot'] = v with s_config.Config(defs=defs) as conf: self.eq(conf.getConfOpt('enabled'), 0) self.eq(conf.getConfOpt('fooval'), 99) conf.onConfOptSet('enabled',callback) conf.setConfOpt('enabled','true') self.eq(data.get('woot'), 1) conf.setConfOpts({'fooval':'0x20'}) self.eq(conf.getConfOpt('fooval'), 0x20) conf.setConfOpts({'fooval':0x30}) self.eq(conf.getConfOpt('fooval'), 0x30) self.assertRaises( NoSuchOpt, conf.setConfOpts, {'newp':'hehe'} ) def test_conf_asloc(self): with s_config.Config() as conf: conf.addConfDef('foo',type='int',defval=0,asloc='_foo_valu') self.eq( conf._foo_valu, 0 ) conf.setConfOpt('foo','0x20') self.eq( conf._foo_valu, 0x20) ","from synapse.tests.common import * import synapse.lib.config as s_config class ConfTest(SynTest): def test_conf_base(self): defs = ( ('fooval',{'type':'int','doc':'what is foo val?','defval':99}), ('enabled',{'type':'bool','doc':'is thing enabled?','defval':0}), ) data = {} def callback(v): data['woot'] = v with s_config.Config(defs=defs) as conf: conf.onConfOptSet('enabled',callback) conf.setConfOpt('enabled','true') self.eq(data.get('woot'), 1) conf.setConfOpts({'fooval':'0x20'}) self.eq(conf.getConfOpt('fooval'), 0x20) conf.setConfOpts({'fooval':0x30}) self.eq(conf.getConfOpt('fooval'), 0x30) self.assertRaises( NoSuchOpt, conf.setConfOpts, {'newp':'hehe'} ) def test_conf_asloc(self): with s_config.Config() as conf: conf.addConfDef('foo',type='int',defval=0,asloc='_foo_valu') self.eq( conf._foo_valu, 0 ) conf.setConfOpt('foo','0x20') self.eq( conf._foo_valu, 0x20) " Remove minor unwanted code change,"package org.skyscreamer.jsonassert.comparator; import org.json.JSONException; import org.skyscreamer.jsonassert.Customization; import org.skyscreamer.jsonassert.JSONCompareMode; import org.skyscreamer.jsonassert.JSONCompareResult; import org.skyscreamer.jsonassert.ValueMatcherException; import java.util.Arrays; import java.util.Collection; public class CustomComparator extends DefaultComparator { private final Collection<Customization> customizations; public CustomComparator(JSONCompareMode mode, Customization... customizations) { super(mode); this.customizations = Arrays.asList(customizations); } @Override public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException { Customization customization = getCustomization(prefix); if (customization != null) { try { if (!customization.matches(prefix, actualValue, expectedValue, result)) { result.fail(prefix, expectedValue, actualValue); } } catch (ValueMatcherException e) { result.fail(prefix, e); } } else { super.compareValues(prefix, expectedValue, actualValue, result); } } private Customization getCustomization(String path) { for (Customization c : customizations) if (c.appliesToPath(path)) return c; return null; } } ","package org.skyscreamer.jsonassert.comparator; import org.json.JSONException; import org.skyscreamer.jsonassert.Customization; import org.skyscreamer.jsonassert.JSONCompareMode; import org.skyscreamer.jsonassert.JSONCompareResult; import org.skyscreamer.jsonassert.ValueMatcherException; import java.util.Arrays; import java.util.Collection; public class CustomComparator extends DefaultComparator { private final Collection<Customization> customizations; public CustomComparator(JSONCompareMode mode, Customization... customizations) { super(mode); this.customizations = Arrays.asList((Customization[])customizations); } @Override public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException { Customization customization = getCustomization(prefix); if (customization != null) { try { if (!customization.matches(prefix, actualValue, expectedValue, result)) { result.fail(prefix, expectedValue, actualValue); } } catch (ValueMatcherException e) { result.fail(prefix, e); } } else { super.compareValues(prefix, expectedValue, actualValue, result); } } private Customization getCustomization(String path) { for (Customization c : customizations) if (c.appliesToPath(path)) return c; return null; } } " Remove version number of html2text in install_requires,"from setuptools import setup, find_packages import sys userena = __import__('userena') readme_file = 'README.mkd' try: long_description = open(readme_file).read() except IOError: sys.stderr.write(""[ERROR] Cannot find file specified as "" ""``long_description`` (%s)\n"" % readme_file) sys.exit(1) install_requires = ['easy_thumbnails', 'django-guardian', 'html2text'] try: from collections import OrderedDict except ImportError: install_requires.append('ordereddict') setup(name='django-userena', version=userena.get_version(), description='Complete user management application for Django', long_description=long_description, zip_safe=False, author='Petar Radosevic', author_email='petar@wunki.org', url='https://github.com/bread-and-pepper/django-userena/', download_url='https://github.com/bread-and-pepper/django-userena/downloads', packages = find_packages(exclude=['demo', 'demo.*']), include_package_data=True, install_requires = install_requires, test_suite='tests.main', classifiers = ['Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities'], ) ","from setuptools import setup, find_packages import sys userena = __import__('userena') readme_file = 'README.mkd' try: long_description = open(readme_file).read() except IOError: sys.stderr.write(""[ERROR] Cannot find file specified as "" ""``long_description`` (%s)\n"" % readme_file) sys.exit(1) install_requires = ['easy_thumbnails', 'django-guardian', 'html2text==2014.12.29'] try: from collections import OrderedDict except ImportError: install_requires.append('ordereddict') setup(name='django-userena', version=userena.get_version(), description='Complete user management application for Django', long_description=long_description, zip_safe=False, author='Petar Radosevic', author_email='petar@wunki.org', url='https://github.com/bread-and-pepper/django-userena/', download_url='https://github.com/bread-and-pepper/django-userena/downloads', packages = find_packages(exclude=['demo', 'demo.*']), include_package_data=True, install_requires = install_requires, test_suite='tests.main', classifiers = ['Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities'], ) " Stop mysql auto-inserting 0 into owner_id field,"var common = require('../common'); var assert = require('assert'); common.createConnection(function (err, db) { var testRequired = function(required, done) { var Person = db.define('test_association_hasone_required_owner', common.getModelProperties()); var Animal = db.define('test_association_hasone_required_animal', common.getModelProperties()); Animal.hasOne('owner', Person, { required: required }); if (!db.driver.sync) return; var test = function(cb) { Person.sync(function (err) { assert(!err); Animal.sync(function (err) { assert(!err); var john = new Person({name: 'John'}); john.save(function(err) { assert(!err); var emu = new Animal({name: 'emu', owner_id: null}); emu.save(function(err) { // When required is true, there should be an error. // When required is false, there should be no errors. assert.equal(!!err, required); cb(); }); }); }); }); } Person.drop(function (err) { Animal.drop(function (err) { test(function() { done(); }); }); }); } testRequired(false, function() { testRequired(true, function() { db.close(); }); }); }); ","var common = require('../common'); var assert = require('assert'); common.createConnection(function (err, db) { var testRequired = function(required, done) { var Person = db.define('test_association_hasone_required_owner', common.getModelProperties()); var Animal = db.define('test_association_hasone_required_animal', common.getModelProperties()); Animal.hasOne('owner', Person, { required: required }); if (!db.driver.sync) return; var test = function(cb) { Person.sync(function (err) { assert(!err); Animal.sync(function (err) { assert(!err); var john = new Person({name: 'John'}); john.save(function(err) { assert(!err); var emu = new Animal({name: 'emu'}); emu.save(function(err) { // When required is true, there should be an error. // When required is false, there should be no errors. assert.equal(!!err, required); cb(); }); }); }); }); } Person.drop(function (err) { Animal.drop(function (err) { test(function() { done(); }); }); }); } testRequired(false, function() { testRequired(true, function() { db.close(); }); }); }); " Declare tornado application outside __main__ block,"#!/usr/bin/python # Launch a very light-HTTP server: Tornado # # Requirements (import from): # - tornado # # Syntax: # ./start.py <port=8080> import tornado.ioloop import tornado.web import sys from os import path #sys.path.append(path.join(path.dirname(__file__), ""../scripts/"")) #from generate_db import DEFAULT_DB class MainHandler(tornado.web.RequestHandler): def get(self): self.write(""Hello World ^^"") # Define tornado application application = tornado.web.Application([ (r""/"", MainHandler), ]) if __name__ == ""__main__"": if len(sys.argv) != 1 and len(sys.argv) != 2: print('''Syntax: ./start.py <port=8080>''') exit(1) try: if (len(sys.argv) == 2): port = int(sys.argv[1]) else: port = 8080 except ValueError, e: print('''ERROR: {}'''.format(e)) print('''Syntax: ./start.py <port=8080>''') exit(2) except TypeError, e: print('''ERROR: {}'''.format(e)) print('''Syntax: ./start.py <port=8080>''') exit(3) # Start the server application.listen(port) tornado.ioloop.IOLoop.instance().start() ","#!/usr/bin/python # Launch a very light-HTTP server: Tornado # # Requirements (import from): # - tornado # # Syntax: # ./start.py <port=8080> import tornado.ioloop import tornado.web import sys from os import path #sys.path.append(path.join(path.dirname(__file__), ""../scripts/"")) #from generate_db import DEFAULT_DB class MainHandler(tornado.web.RequestHandler): def get(self): self.write(""Hello World ^^"") if __name__ == ""__main__"": if len(sys.argv) != 1 and len(sys.argv) != 2: print('''Syntax: ./start.py <port=8080>''') exit(1) try: if (len(sys.argv) == 2): port = int(sys.argv[1]) else: port = 8080 except ValueError, e: print('''ERROR: {}'''.format(e)) print('''Syntax: ./start.py <port=8080>''') exit(2) except TypeError, e: print('''ERROR: {}'''.format(e)) print('''Syntax: ./start.py <port=8080>''') exit(3) # Define server parameters application = tornado.web.Application([ (r""/"", MainHandler), ]) application.listen(port) # Start the server tornado.ioloop.IOLoop.instance().start() " Fix getter if no date found,"define( [ 'jquery', 'backbone', 'underscore', 'moment' ], function ($, Backbone, _, moment) { ""use strict""; return Backbone.Model.extend({ url : function() { var base = $('body').data('api-url') + '/repos'; return this.isNew() ? base : base + '/' + this.id; }, presenter: function () { return _.extend(this.toJSON(), { status: this.getStatus(), travisUrl: this.getTravisUrl(), githubUrl: this.getGithubUrl(), lastBuildFinishedAt: this.getLastBuildFinishedAt(), humanizedLastBuildFinishedAt: this.getHumanizedBuildFinishedAt() }); }, getStatus: function () { var lastBuildStatus = this.get('last_build_status'); if (0 === lastBuildStatus) { return 'passing'; } else if (1 === lastBuildStatus) { return 'failing'; } return 'unknown'; }, getTravisUrl: function () { return 'https://travis-ci.org/' + this.get('slug') + '/builds/' + this.get('last_build_id'); }, getGithubUrl: function () { return 'https://github.com/' + this.get('slug'); }, getLastBuildFinishedAt: function () { return this.get('last_build_finished_at'); }, getHumanizedBuildFinishedAt: function () { if (this.getLastBuildFinishedAt()) { return moment(this.getLastBuildFinishedAt()).fromNow(); } return ''; } }); } ); ","define( [ 'jquery', 'backbone', 'underscore', 'moment' ], function ($, Backbone, _, moment) { ""use strict""; return Backbone.Model.extend({ url : function() { var base = $('body').data('api-url') + '/repos'; return this.isNew() ? base : base + '/' + this.id; }, presenter: function () { return _.extend(this.toJSON(), { status: this.getStatus(), travisUrl: this.getTravisUrl(), githubUrl: this.getGithubUrl(), lastBuildFinishedAt: this.getLastBuildFinishedAt(), humanizedLastBuildFinishedAt: this.getHumanizedBuildFinishedAt() }); }, getStatus: function () { var lastBuildStatus = this.get('last_build_status'); if (0 === lastBuildStatus) { return 'passing'; } else if (1 === lastBuildStatus) { return 'failing'; } return 'unknown'; }, getTravisUrl: function () { return 'https://travis-ci.org/' + this.get('slug') + '/builds/' + this.get('last_build_id'); }, getGithubUrl: function () { return 'https://github.com/' + this.get('slug'); }, getLastBuildFinishedAt: function () { return this.get('last_build_finished_at'); }, getHumanizedBuildFinishedAt: function () { if (undefined !== this.getLastBuildFinishedAt()) { return moment(this.getLastBuildFinishedAt()).fromNow(); } return ''; } }); } ); " Disable dragging marker from map,"""use strict""; var photoSingle = angular.module('photo.single', ['ionic', 'ngCordova', '500px.service', 'uiGmapgoogle-maps']) photoSingle.controller('PhotoSingleController', ['$rootScope', '$scope', 'FiveHundredService', '$cordovaGeolocation', '$stateParams', '$ionicPlatform', function ($rootScope, $scope, FiveHundredService, $cordovaGeolocation, $stateParams, $ionicPlatform) { $scope.photoId = $stateParams.photoid; $scope.photoItem = null; if ($scope.photoId) { FiveHundredService.getPhoto($scope.photoId).then(function (data) { $scope.photoItem = data; $scope.initMap(); }, function (error) { }); }; $scope.initMap = function () { $scope.map = { center: { latitude: $scope.photoItem.photo.latitude, longitude: $scope.photoItem.photo.longitude }, zoom: 16 }; $scope.marker = { id: 0, coords: { latitude: $scope.photoItem.photo.latitude, longitude: $scope.photoItem.photo.longitude }, options: { draggable: false }, }; }; }]);","""use strict""; var photoSingle = angular.module('photo.single', ['ionic', 'ngCordova', '500px.service', 'uiGmapgoogle-maps']) photoSingle.controller('PhotoSingleController', ['$rootScope', '$scope', 'FiveHundredService', '$cordovaGeolocation', '$stateParams', '$ionicPlatform', function ($rootScope, $scope, FiveHundredService, $cordovaGeolocation, $stateParams, $ionicPlatform) { $scope.photoId = $stateParams.photoid; $scope.photoItem = null; if ($scope.photoId) { FiveHundredService.getPhoto($scope.photoId).then(function (data) { $scope.photoItem = data; $scope.initMap(); }, function (error) { }); }; $scope.initMap = function () { $scope.map = { center: { latitude: $scope.photoItem.photo.latitude, longitude: $scope.photoItem.photo.longitude }, zoom: 16 }; $scope.marker = { id: 0, coords: { latitude: $scope.photoItem.photo.latitude, longitude: $scope.photoItem.photo.longitude }, options: { draggable: true }, }; }; }]);" Fix one coding styleguide violation,"/* * Copyright (c) 2016 Jeremy Thomerson * Licensed under the MIT license. */ 'use strict'; var _ = require('underscore'), cheerio = require('cheerio'), BasePlugin = require('./BasePlugin'); module.exports = BasePlugin.extend({ run: function(files, metalsmith, done) { _.each(files, function(file) { var contents = file.contents.toString(), $ = cheerio.load(contents), headings = [], stack = []; $('h1, h2, h3, h4, h5, h6').each(function() { var elem = $(this); headings.push({ id: elem.attr('id'), text: elem.text(), weight: parseInt(elem.get(0).tagName.replace('h', ''), 10), subheadings: [], }); }); file.headings = _.reduce(headings, function(list, heading) { var parentWeight; parentWeight = _.findLastIndex(stack, function(h) { return h && h.weight < heading.weight; }); if (parentWeight === -1) { list.push(heading); } else { stack[parentWeight].subheadings.push(heading); } _.each(stack, function(h) { if (h && h.weight >= heading.weight) { delete stack[h.weight]; } }); stack[heading.weight] = heading; return list; }, []); }.bind(this)); done(); }, }); ","/* * Copyright (c) 2016 Jeremy Thomerson * Licensed under the MIT license. */ 'use strict'; var _ = require('underscore'), cheerio = require('cheerio'), BasePlugin = require('./BasePlugin'); module.exports = BasePlugin.extend({ run: function(files, metalsmith, done) { _.each(files, function(file) { var contents = file.contents.toString(), $ = cheerio.load(contents), headings = [], stack = []; $('h1, h2, h3, h4, h5, h6').each(function() { var elem = $(this); headings.push({ id: elem.attr('id'), text: elem.text(), weight: parseInt(elem.get(0).tagName.replace('h', ''), 10), subheadings: [], }); }); file.headings = _.reduce(headings, function(list, heading) { var parentWeight; parentWeight = _.findLastIndex(stack, function(h) { return h && h.weight < heading.weight; }); if (parentWeight === -1) { list.push(heading); } else { stack[parentWeight].subheadings.push(heading); } _.each(stack, function(h) { if (h && h.weight >= heading.weight) { delete stack[h.weight]; } }); stack[heading.weight] = heading; return list; }, []); }.bind(this)); done(); }, }); " Stop looking in the old fuzzing/ directory,"#!/usr/bin/env python import os THIS_SCRIPT_DIRECTORY = os.path.dirname(os.path.abspath(__file__)) THIS_REPO_PATH = os.path.abspath(os.path.join(THIS_SCRIPT_DIRECTORY, os.pardir)) REPO_PARENT_PATH = os.path.abspath(os.path.join(THIS_SCRIPT_DIRECTORY, os.pardir, os.pardir)) # Lets us combine ignore lists: # from private&public fuzzing repos # for project branches and for their base branches (e.g. mozilla-central) # # Given a targetRepo ""mozilla-central/ionmonkey"" and a name ""crashes.txt"", returns a list of 2N absolute paths like: # ???/funfuzz*/known/mozilla-central/ionmonkey/crashes.txt # ???/funfuzz*/known/mozilla-central/crashes.txt def findIgnoreLists(targetRepo, needle): r = [] assert not targetRepo.startswith(""/"") for name in sorted(os.listdir(REPO_PARENT_PATH)): if name.startswith(""funfuzz""): knownPath = os.path.join(REPO_PARENT_PATH, name, ""known"", targetRepo) if os.path.isdir(knownPath): while os.path.basename(knownPath) != ""known"": filename = os.path.join(knownPath, needle) if os.path.exists(filename): r.append(filename) knownPath = os.path.dirname(knownPath) assert len(r) > 0 return r ","#!/usr/bin/env python import os THIS_SCRIPT_DIRECTORY = os.path.dirname(os.path.abspath(__file__)) THIS_REPO_PATH = os.path.abspath(os.path.join(THIS_SCRIPT_DIRECTORY, os.pardir)) REPO_PARENT_PATH = os.path.abspath(os.path.join(THIS_SCRIPT_DIRECTORY, os.pardir, os.pardir)) # Lets us combine ignore lists: # from private&public fuzzing repos # for project branches and for their base branches (e.g. mozilla-central) # # Given a targetRepo ""mozilla-central/ionmonkey"" and a name ""crashes.txt"", returns a list of 2N absolute paths like: # ???/funfuzz*/known/mozilla-central/ionmonkey/crashes.txt # ???/funfuzz*/known/mozilla-central/crashes.txt def findIgnoreLists(targetRepo, needle): r = [] assert not targetRepo.startswith(""/"") for name in sorted(os.listdir(REPO_PARENT_PATH)): if name.startswith(""fuzzing"") or name.startswith(""funfuzz""): knownPath = os.path.join(REPO_PARENT_PATH, name, ""known"", targetRepo) if os.path.isdir(knownPath): while os.path.basename(knownPath) != ""known"": filename = os.path.join(knownPath, needle) if os.path.exists(filename): r.append(filename) knownPath = os.path.dirname(knownPath) assert len(r) > 0 return r " Set cov-core dependency to 1.12,"import setuptools setuptools.setup(name='pytest-cov', version='1.6', description='py.test plugin for coverage reporting with ' 'support for both centralised and distributed testing, ' 'including subprocesses and multiprocessing', long_description=open('README.rst').read().strip(), author='Marc Schlaich', author_email='marc.schlaich@gmail.com', url='https://github.com/schlamar/pytest-cov', py_modules=['pytest_cov'], install_requires=['pytest>=2.5.2', 'cov-core>=1.12'], entry_points={'pytest11': ['pytest_cov = pytest_cov']}, license='MIT License', zip_safe=False, keywords='py.test pytest cover coverage distributed parallel', classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.4', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.0', 'Programming Language :: Python :: 3.1', 'Topic :: Software Development :: Testing']) ","import setuptools setuptools.setup(name='pytest-cov', version='1.6', description='py.test plugin for coverage reporting with ' 'support for both centralised and distributed testing, ' 'including subprocesses and multiprocessing', long_description=open('README.rst').read().strip(), author='Marc Schlaich', author_email='marc.schlaich@gmail.com', url='https://github.com/schlamar/pytest-cov', py_modules=['pytest_cov'], install_requires=['pytest>=2.5.2', 'cov-core>=1.11'], entry_points={'pytest11': ['pytest_cov = pytest_cov']}, license='MIT License', zip_safe=False, keywords='py.test pytest cover coverage distributed parallel', classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.4', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.0', 'Programming Language :: Python :: 3.1', 'Topic :: Software Development :: Testing']) " Update service provider with new migration and translations loader,"<?php namespace Lecturize\Taxonomies; use Illuminate\Support\ServiceProvider; class TaxonomiesServiceProvider extends ServiceProvider { protected $migrations = [ 'CreateTaxonomiesTable' => 'create_taxonomies_table', 'UpdateTaxonomiesTable' => 'extend_taxonomies_table' ]; public function boot() { $this->handleConfig(); $this->handleMigrations(); $this->loadTranslationsFrom(__DIR__ .'/../resources/lang', 'taxonomies'); } /** @inheritdoc */ public function register() { // } /** @inheritdoc */ public function provides() { return []; } /** * Publish and merge the config file. * * @return void */ private function handleConfig() { $configPath = __DIR__ . '/../config/config.php'; $this->publishes([$configPath => config_path('lecturize.php')]); $this->mergeConfigFrom($configPath, 'lecturize'); } /** * Publish migrations. * * @return void */ private function handleMigrations() { $count = 0; foreach ($this->migrations as $class => $file) { if (! class_exists($class)) { $timestamp = date('Y_m_d_Hi'. sprintf('%02d', $count), time()); $this->publishes([ __DIR__ .'/../database/migrations/'. $file .'.php.stub' => database_path('migrations/'. $timestamp .'_'. $file .'.php') ], 'migrations'); $count++; } } } }","<?php namespace Lecturize\Taxonomies; use Illuminate\Support\ServiceProvider; class TaxonomiesServiceProvider extends ServiceProvider { protected $migrations = [ 'CreateTaxonomiesTable' => 'create_taxonomies_table' ]; /** * @inheritdoc */ public function boot() { $this->handleConfig(); $this->handleMigrations(); } /** * @inheritdoc */ public function register() { // } /** * @inheritdoc */ public function provides() { return []; } /** * Publish and merge the config file. * * @return void */ private function handleConfig() { $configPath = __DIR__ . '/../config/config.php'; $this->publishes([$configPath => config_path('lecturize.php')]); $this->mergeConfigFrom($configPath, 'lecturize'); } /** * Publish migrations. * * @return void */ private function handleMigrations() { foreach ($this->migrations as $class => $file) { if (! class_exists($class)) { $timestamp = date('Y_m_d_His', time()); $this->publishes([ __DIR__ .'/../database/migrations/'. $file .'.php.stub' => database_path('migrations/'. $timestamp .'_'. $file .'.php') ], 'migrations'); } } } }" Add testing of loading and saving for Dendrogram_Stats,"# Licensed under an MIT open source license - see LICENSE ''' Tests for Dendrogram statistics ''' import numpy as np import numpy.testing as npt import os from ..statistics import Dendrogram_Stats, DendroDistance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances min_deltas = np.logspace(-1.5, 0.5, 40) def test_DendroStat(): tester = Dendrogram_Stats(dataset1[""cube""], min_deltas=min_deltas) tester.run(periodic_bounds=False) npt.assert_allclose(tester.numfeatures, computed_data[""dendrogram_val""]) # Test loading and saving tester.save_results(keep_data=False) tester.load_results(""dendrogram_stats_output.pkl"") # Remove the file os.remove(""dendrogram_stats_output.pkl"") npt.assert_allclose(tester.numfeatures, computed_data[""dendrogram_val""]) def test_DendroDistance(): tester_dist = \ DendroDistance(dataset1[""cube""], dataset2[""cube""], min_deltas=min_deltas, periodic_bounds=False).distance_metric() npt.assert_almost_equal(tester_dist.histogram_distance, computed_distances[""dendrohist_distance""]) npt.assert_almost_equal(tester_dist.num_distance, computed_distances[""dendronum_distance""]) ","# Licensed under an MIT open source license - see LICENSE ''' Tests for Dendrogram statistics ''' import numpy as np import numpy.testing as npt from ..statistics import Dendrogram_Stats, DendroDistance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances min_deltas = np.logspace(-1.5, 0.5, 40) def test_DendroStat(): tester = Dendrogram_Stats(dataset1[""cube""], min_deltas=min_deltas) tester.run(periodic_bounds=False) npt.assert_allclose(tester.numfeatures, computed_data[""dendrogram_val""]) def test_DendroDistance(): tester_dist = \ DendroDistance(dataset1[""cube""], dataset2[""cube""], min_deltas=min_deltas, periodic_bounds=False).distance_metric() npt.assert_almost_equal(tester_dist.histogram_distance, computed_distances[""dendrohist_distance""]) npt.assert_almost_equal(tester_dist.num_distance, computed_distances[""dendronum_distance""]) " "Add UMD target for use without ""require""/""import""","var CopyWebpackPlugin = require('copy-webpack-plugin'); var path = require('path'); module.exports = [{ entry: { horizontal: './shim/horizontal.js', vertical: './shim/vertical.js' }, output: { library: 'ScratchBlocks', libraryTarget: 'commonjs2', path: path.resolve(__dirname, 'dist'), filename: '[name].js' } }, { entry: { horizontal: './shim/horizontal.js', vertical: './shim/vertical.js' }, output: { library: 'Blockly', libraryTarget: 'umd', path: path.resolve(__dirname, 'dist', 'web'), filename: '[name].js' } }, { output: { filename: '[name].js', path: path.resolve(__dirname, 'gh-pages') }, plugins: [ new CopyWebpackPlugin([{ from: 'node_modules/google-closure-library', to: 'closure-library' }, { from: 'blocks_common', to: 'playgrounds/blocks_common', }, { from: 'blocks_horizontal', to: 'playgrounds/blocks_horizontal', }, { from: 'blocks_vertical', to: 'playgrounds/blocks_vertical', }, { from: 'core', to: 'playgrounds/core' }, { from: 'media', to: 'playgrounds/media' }, { from: 'msg', to: 'playgrounds/msg' }, { from: 'tests', to: 'playgrounds/tests' }, { from: '*.js', ignore: 'webpack.config.js', to: 'playgrounds' }]) ] }]; ","var CopyWebpackPlugin = require('copy-webpack-plugin'); var path = require('path'); module.exports = [{ entry: { horizontal: './shim/horizontal.js', vertical: './shim/vertical.js' }, output: { library: 'ScratchBlocks', libraryTarget: 'commonjs2', path: path.resolve(__dirname, 'dist'), filename: '[name].js' } }, { output: { filename: '[name].js', path: path.resolve(__dirname, 'gh-pages') }, plugins: [ new CopyWebpackPlugin([{ from: 'node_modules/google-closure-library', to: 'closure-library' }, { from: 'blocks_common', to: 'playgrounds/blocks_common', }, { from: 'blocks_horizontal', to: 'playgrounds/blocks_horizontal', }, { from: 'blocks_vertical', to: 'playgrounds/blocks_vertical', }, { from: 'core', to: 'playgrounds/core' }, { from: 'media', to: 'playgrounds/media' }, { from: 'msg', to: 'playgrounds/msg' }, { from: 'tests', to: 'playgrounds/tests' }, { from: '*.js', ignore: 'webpack.config.js', to: 'playgrounds' }]) ] }]; " Test that typo in sources break the CI build,"(function() { 'use strict'; angular .module('afterHeap') .config(routerConfig); /** @ngInject */ function routerConfig($stateProvider, $urlRouterProvider) { $stateProvider .state('city', { abstract: true, url: '/:cityId', template: '<ui-view/>' }) .state('city.highlights', { url: '/', templateUrl: 'app/highlights/highlights.html', controller: 'HighlightsController', controllerAs: 'highlightsController', resolve: { highlights: function(api, processResponse, $stateParams){ return api.getCityFeed($stateParams.cityId).then(function(res) { return processResponse.createTopSuggestions(res); }) } }this_should_break_the_build }) .state('city.feed', { url: '/feed', templateUrl: 'app/activityfeed/activityfeed.html', controller: 'ActivityFeedController', controllerAs: 'activityFeed', resolve: { checkins: function(api, processResponse, $stateParams){ return api.getCityFeed($stateParams.cityId).then(function(res){ return processResponse.removeBlackListed(res); }); } } }); $urlRouterProvider.otherwise('/Tampere/'); } })(); ","(function() { 'use strict'; angular .module('afterHeap') .config(routerConfig); /** @ngInject */ function routerConfig($stateProvider, $urlRouterProvider) { $stateProvider .state('city', { abstract: true, url: '/:cityId', template: '<ui-view/>' }) .state('city.highlights', { url: '/', templateUrl: 'app/highlights/highlights.html', controller: 'HighlightsController', controllerAs: 'highlightsController', resolve: { highlights: function(api, processResponse, $stateParams){ return api.getCityFeed($stateParams.cityId).then(function(res) { return processResponse.createTopSuggestions(res); }) } } }) .state('city.feed', { url: '/feed', templateUrl: 'app/activityfeed/activityfeed.html', controller: 'ActivityFeedController', controllerAs: 'activityFeed', resolve: { checkins: function(api, processResponse, $stateParams){ return api.getCityFeed($stateParams.cityId).then(function(res){ return processResponse.removeBlackListed(res); }); } } }); $urlRouterProvider.otherwise('/Tampere/'); } })(); " Add checkbox validation in main activity,"package br.com.bloder.blorm; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; import br.com.bloder.blormlib.Blorm; import br.com.bloder.blormlib.validation.Action; import static br.com.bloder.blormlib.validation.Validations.*; public class MainActivity extends AppCompatActivity { private EditText editTextFilled; private Button submit; private CheckBox checkBox; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editTextFilled = (EditText) findViewById(R.id.edit_text_filled); submit = (Button) findViewById(R.id.submit); checkBox = (CheckBox) findViewById(R.id.check_box); editTextFilled.setText(""Hello""); new Blorm.Builder() .field(editTextFilled).is(filled) .field(checkBox).is(checked) .onSuccess(new Action() { @Override public void call() { onSuccess(); } }) .onError(new Action() { @Override public void call() { onError(); } }) .submitOn(submit); } private void onSuccess() { editTextFilled.setError(null); checkBox.setError(null); Toast.makeText(this, ""Success"", Toast.LENGTH_SHORT).show(); } private void onError() { Toast.makeText(this, ""Error"", Toast.LENGTH_SHORT).show(); } } ","package br.com.bloder.blorm; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import br.com.bloder.blormlib.Blorm; import br.com.bloder.blormlib.validation.Action; import static br.com.bloder.blormlib.validation.Validations.*; public class MainActivity extends AppCompatActivity { private EditText editTextFilled; private Button submit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editTextFilled = (EditText) findViewById(R.id.edit_text_filled); submit = (Button) findViewById(R.id.submit); editTextFilled.setText(""Hello""); new Blorm.Builder() .field(editTextFilled).is(filled) .onSuccess(new Action() { @Override public void call() { onSuccess(); }}) .onError(new Action() { @Override public void call() { onError(); } }) .submitOn(submit); } private void onSuccess() { editTextFilled.setError(null); Toast.makeText(this, ""Success"", Toast.LENGTH_SHORT).show(); } private void onError() { Toast.makeText(this, ""Error"", Toast.LENGTH_SHORT).show(); } } " Remove fallback part from error messages,"<?php namespace Amp\Loop; // @codeCoverageIgnoreStart class DriverFactory { /** * Creates a new loop instance and chooses the best available driver. * * @return Driver * * @throws \Error If an invalid class has been specified via AMP_LOOP_DRIVER */ public function create(): Driver { if ($driver = $this->createDriverFromEnv()) { return $driver; } if (UvDriver::isSupported()) { return new UvDriver; } if (EvDriver::isSupported()) { return new EvDriver; } if (EventDriver::isSupported()) { return new EventDriver; } return new NativeDriver; } private function createDriverFromEnv() { $driver = \getenv(""AMP_LOOP_DRIVER""); if (!$driver) { return null; } if (!\class_exists($driver)) { throw new \Error(\sprintf( ""Driver '%s' does not exist."", $driver )); } if (!\is_subclass_of($driver, Driver::class)) { throw new \Error(\sprintf( ""Driver '%s' is not a subclass of '%s'."", $driver, Driver::class )); } return new $driver; } } // @codeCoverageIgnoreEnd ","<?php namespace Amp\Loop; // @codeCoverageIgnoreStart class DriverFactory { /** * Creates a new loop instance and chooses the best available driver. * * @return Driver * * @throws \Error If an invalid class has been specified via AMP_LOOP_DRIVER */ public function create(): Driver { if ($driver = $this->createDriverFromEnv()) { return $driver; } if (UvDriver::isSupported()) { return new UvDriver; } if (EvDriver::isSupported()) { return new EvDriver; } if (EventDriver::isSupported()) { return new EventDriver; } return new NativeDriver; } private function createDriverFromEnv() { $driver = \getenv(""AMP_LOOP_DRIVER""); if (!$driver) { return null; } if (!\class_exists($driver)) { throw new \Error(\sprintf( ""Driver '%s' does not exist, falling back to default driver."", $driver )); } if (!\is_subclass_of($driver, Driver::class)) { throw new \Error(\sprintf( ""Driver '%s' is not a subclass of '%s', falling back to default driver."", $driver, Driver::class )); } return new $driver; } } // @codeCoverageIgnoreEnd " Fix ASDF tag test helper to load schemas correctly,"# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- import os import urllib.parse import urllib.request import yaml import numpy as np def run_schema_example_test(organization, standard, name, version, check_func=None): import asdf from asdf.tests import helpers from asdf.types import format_tag from asdf.resolver import default_tag_to_url_mapping from asdf.schema import load_schema tag = format_tag(organization, standard, version, name) uri = asdf.resolver.default_tag_to_url_mapping(tag) r = asdf.AsdfFile().resolver examples = [] schema = load_schema(uri, resolver=r) for node in asdf.treeutil.iter_tree(schema): if (isinstance(node, dict) and 'examples' in node and isinstance(node['examples'], list)): for desc, example in node['examples']: examples.append(example) for example in examples: buff = helpers.yaml_to_asdf('example: ' + example.strip()) ff = asdf.AsdfFile(uri=uri) # Add some dummy blocks so that the ndarray examples work for i in range(3): b = asdf.block.Block(np.zeros((1024*1024*8), dtype=np.uint8)) b._used = True ff.blocks.add(b) ff._open_impl(ff, buff, mode='r') if check_func: check_func(ff) ","# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- import os import urllib.parse import yaml import numpy as np def run_schema_example_test(organization, standard, name, version, check_func=None): import asdf from asdf.tests import helpers from asdf.types import format_tag from asdf.resolver import default_resolver tag = format_tag(organization, standard, version, name) schema_path = urllib.parse.urlparse(default_resolver(tag)).path with open(schema_path, 'rb') as ff: schema = yaml.load(ff) examples = [] for node in asdf.treeutil.iter_tree(schema): if (isinstance(node, dict) and 'examples' in node and isinstance(node['examples'], list)): for desc, example in node['examples']: examples.append(example) for example in examples: buff = helpers.yaml_to_asdf('example: ' + example.strip()) ff = asdf.AsdfFile(uri=schema_path) # Add some dummy blocks so that the ndarray examples work for i in range(3): b = asdf.block.Block(np.zeros((1024*1024*8), dtype=np.uint8)) b._used = True ff.blocks.add(b) ff._open_impl(ff, buff, mode='r') if check_func: check_func(ff) " "Support hostname that resolve to IPv6-only address The current hostname validation does not cope with IPv6-only hostnames. Use getaddrinfo instead of gethostbyname to fix this. getaddrinfo raises the same exceptions and should work like a drop-in-replacement in this scenario. We should also address the IPv4-only check for if then input is an IP-address but the use of split on ':' is problematic and prevents code to check for IPv6-addresses as input. I'm not sure what the thought behind allowing ""name:host"" is so leaving it untouched. I have proposed code to check and warn for both IPv4 and IPv6 address input that I can provide as soon as I understand the scope of parsing ""name:host"" input.","import socket import argparse import re class RegexMatch(object): """""" Performs regular expression match on value. If the regular expression pattern matches it will it will return an error message that will work with argparse. """""" def __init__(self, pattern, statement=None): self.string_pattern = pattern self.pattern = re.compile(pattern) self.statement = statement if not self.statement: self.statement = ""must match pattern %s"" % self.string_pattern def __call__(self, string): match = self.pattern.search(string) if match: raise argparse.ArgumentError(None, self.statement) return string class Hostname(object): """""" Checks wether a given hostname is resolvable in DNS, otherwise raising and argparse error. """""" def __init__(self, _socket=None): self.socket = _socket or socket # just used for testing def __call__(self, string): parts = string.split(':') name = parts[0] host = parts[-1] try: self.socket.getaddrinfo(host, 0) except self.socket.gaierror: msg = ""hostname: %s is not resolvable"" % host raise argparse.ArgumentError(None, msg) try: self.socket.inet_aton(name) except self.socket.error: return string # not an IP else: msg = '%s must be a hostname not an IP' % name raise argparse.ArgumentError(None, msg) return string ","import socket import argparse import re class RegexMatch(object): """""" Performs regular expression match on value. If the regular expression pattern matches it will it will return an error message that will work with argparse. """""" def __init__(self, pattern, statement=None): self.string_pattern = pattern self.pattern = re.compile(pattern) self.statement = statement if not self.statement: self.statement = ""must match pattern %s"" % self.string_pattern def __call__(self, string): match = self.pattern.search(string) if match: raise argparse.ArgumentError(None, self.statement) return string class Hostname(object): """""" Checks wether a given hostname is resolvable in DNS, otherwise raising and argparse error. """""" def __init__(self, _socket=None): self.socket = _socket or socket # just used for testing def __call__(self, string): parts = string.split(':') name = parts[0] host = parts[-1] try: self.socket.gethostbyname(host) except self.socket.gaierror: msg = ""hostname: %s is not resolvable"" % host raise argparse.ArgumentError(None, msg) try: self.socket.inet_aton(name) except self.socket.error: return string # not an IP else: msg = '%s must be a hostname not an IP' % name raise argparse.ArgumentError(None, msg) return string " Add width parameter before height in options array,"<?php namespace Uploadify\Casts; use Uploadify\Casts\Cast as BaseCast; class ImageCast extends BaseCast { /** * Get full url to file * * @param int|array $width * @param int $height * @param array $options * @return string */ public function url($width = null, $height = null, array $options = []) { if (is_array($width)) { $options = $width; } elseif ($width) { if ($height) { $options = array_merge(['h' => $height], $options); } $options = array_merge(['w' => $width], $options); } if (! empty($options)) { return $this->getStorage()->url($this->path().'/'.$this->prepareOptions($options).'/'.$this->name()); } return $this->getStorage()->url($this->path().'/'.$this->name()); } /** * Prepare and convert options from array to string * * @param array $options */ protected function prepareOptions(array $options = []) { $string = implode(',', array_map( function ($value, $key) { return $key.'_'.$value; }, $options, array_keys($options) )); $from = ['width', 'height']; $to = ['w', 'h']; return str_replace($from, $to, $string); } } ","<?php namespace Uploadify\Casts; use Uploadify\Casts\Cast as BaseCast; class ImageCast extends BaseCast { /** * Get full url to file * * @param int|array $width * @param int $height * @param array $options * @return string */ public function url($width = null, $height = null, array $options = []) { if (is_array($width)) { $options = $width; } elseif ($width) { $options = array_merge(['w' => $width], $options); } if ($height) { $options = array_merge(['h' => $height], $options); } if (! empty($options)) { return $this->getStorage()->url($this->path().'/'.$this->prepareOptions($options).'/'.$this->name()); } return $this->getStorage()->url($this->path().'/'.$this->name()); } /** * Prepare and convert options from array to string * * @param array $options */ protected function prepareOptions(array $options = []) { $string = implode(',', array_map( function ($value, $key) { return $key.'_'.$value; }, $options, array_keys($options) )); $from = ['width', 'height']; $to = ['w', 'h']; return str_replace($from, $to, $string); } } " Insert missing line break at end-of-file,"/*global define:false */ define([""underscore"", ""backbone""], function (_, Backbone) { ""use strict""; var views = { BookListItem: Backbone.View.extend({ tagName: 'li', template: _.template(""<a href='/#book-details/<%-id%>'><%-title%></a>""), initialize: function (opts) { this.$el.html(this.template(opts.book.toJSON())); } }), BookList: Backbone.View.extend({ tagName: 'ul', initialize: function (opts) { this.$el.append.apply(this.$el, opts.books.map(function (book) { return (new views.BookListItem({ book: book })).el; })); } }), BookDetails: Backbone.View.extend({ template: _.template(""<div>'<%-title%>' written by <%-author%> sometime around <%-year%></div><div><a href='/#books-list'>back</a></div>""), initialize: function (opts) { this.$el.html(this.template(opts.book.toJSON())); } }), Error: Backbone.View.extend({ template: _.template(""<div>Oops, an error occured: <%-error%></div>""), initialize: function (opts) { this.$el.html(this.template({ error: opts.error })); } }) }; return views; }); ","/*global define:false */ define([""underscore"", ""backbone""], function (_, Backbone) { ""use strict""; var views = { BookListItem: Backbone.View.extend({ tagName: 'li', template: _.template(""<a href='/#book-details/<%-id%>'><%-title%></a>""), initialize: function (opts) { this.$el.html(this.template(opts.book.toJSON())); } }), BookList: Backbone.View.extend({ tagName: 'ul', initialize: function (opts) { this.$el.append.apply(this.$el, opts.books.map(function (book) { return (new views.BookListItem({ book: book })).el; })); } }), BookDetails: Backbone.View.extend({ template: _.template(""<div>'<%-title%>' written by <%-author%> sometime around <%-year%></div><div><a href='/#books-list'>back</a></div>""), initialize: function (opts) { this.$el.html(this.template(opts.book.toJSON())); } }), Error: Backbone.View.extend({ template: _.template(""<div>Oops, an error occured: <%-error%></div>""), initialize: function (opts) { this.$el.html(this.template({ error: opts.error })); } }) }; return views; });" Return resulting object from decorated function if any,"import os from functools import wraps from argparse import ArgumentParser from fabric.context_managers import prefix def cached_property(func): cach_attr = '_{0}'.format(func.__name__) @property def wrap(self): if not hasattr(self, cach_attr): value = func(self) if value is not None: setattr(self, cach_attr, value) return getattr(self, cach_attr, None) return wrap def cli(*args, **kwargs): def decorator(func): class Parser(ArgumentParser): def handle(self, *args, **kwargs): try: func(*args, **kwargs) except Exception, e: self.error(e.message) # No catching of exceptions def handle_raw(self, *args, **kwargs): func(*args, **kwargs) return Parser(*args, **kwargs) return decorator def virtualenv(path): ""Wraps a function and prefixes the call with the virtualenv active."" if path is None: activate = None else: activate = os.path.join(path, 'bin/activate') def decorator(func): @wraps(func) def inner(*args, **kwargs): if path is not None: with prefix('source {0}'.format(activate)): return func(*args, **kwargs) else: return func(*args, **kwargs) return inner return decorator ","import os from functools import wraps from argparse import ArgumentParser from fabric.context_managers import prefix def cached_property(func): cach_attr = '_{0}'.format(func.__name__) @property def wrap(self): if not hasattr(self, cach_attr): value = func(self) if value is not None: setattr(self, cach_attr, value) return getattr(self, cach_attr, None) return wrap def cli(*args, **kwargs): def decorator(func): class Parser(ArgumentParser): def handle(self, *args, **kwargs): try: func(*args, **kwargs) except Exception, e: self.error(e.message) # No catching of exceptions def handle_raw(self, *args, **kwargs): func(*args, **kwargs) return Parser(*args, **kwargs) return decorator def virtualenv(path): ""Wraps a function and prefixes the call with the virtualenv active."" if path is None: activate = None else: activate = os.path.join(path, 'bin/activate') def decorator(func): @wraps(func) def inner(*args, **kwargs): if path is not None: with prefix('source {0}'.format(activate)): func(*args, **kwargs) else: func(*args, **kwargs) return inner return decorator " Add destination directory to default arguments for scripts,"""""""A set of functions to standardize some options for python scripts."""""" def setup_parser_help(parser, additional_docs=None): """""" Set formatting for parser to raw and add docstring to help output Parameters ---------- parser : `ArgumentParser` The parser to be modified. additional_docs: str Any documentation to be added to the documentation produced by `argparse` """""" from argparse import RawDescriptionHelpFormatter parser.formatter_class = RawDescriptionHelpFormatter if additional_docs is not None: parser.epilog = additional_docs def add_verbose(parser): """""" Add a verbose option (--verbose or -v) to parser. Parameters: ----------- parser : `ArgumentParser` """""" verbose_help = ""provide more information during processing"" parser.add_argument(""-v"", ""--verbose"", help=verbose_help, action=""store_true"") def add_directories(parser, nargs_in='+'): """""" Add a positional argument that is one or more directories. Parameters ---------- parser : `ArgumentParser` """""" parser.add_argument(""dir"", metavar='dir', nargs=nargs_in, help=""Directory to process"") def add_destination_directory(parser): """""" Add a destination directory option Parameters ---------- parser : `ArgumentParser` """""" arg_help = 'Directory in which output from this script will be stored' parser.add_argument(""-d"", ""--destination-dir"", help=arg_help, default=None) def construct_default_parser(docstring=None): #import script_helpers import argparse parser = argparse.ArgumentParser() if docstring is not None: setup_parser_help(parser, docstring) add_verbose(parser) add_directories(parser) add_destination_directory(parser) return parser ","""""""A set of functions to standardize some options for python scripts."""""" def setup_parser_help(parser, additional_docs=None): """""" Set formatting for parser to raw and add docstring to help output Parameters ---------- parser : `ArgumentParser` The parser to be modified. additional_docs: str Any documentation to be added to the documentation produced by `argparse` """""" from argparse import RawDescriptionHelpFormatter parser.formatter_class = RawDescriptionHelpFormatter if additional_docs is not None: parser.epilog = additional_docs def add_verbose(parser): """""" Add a verbose option (--verbose or -v) to parser. Parameters: ----------- parser : `ArgumentParser` """""" verbose_help = ""provide more information during processing"" parser.add_argument(""-v"", ""--verbose"", help=verbose_help, action=""store_true"") def add_directories(parser, nargs_in='+'): """""" Add a positional argument that is one or more directories. Parameters ---------- parser : `ArgumentParser` """""" parser.add_argument(""dir"", metavar='dir', nargs=nargs_in, help=""Directory to process"") def construct_default_parser(docstring=None): #import script_helpers import argparse parser = argparse.ArgumentParser() if docstring is not None: setup_parser_help(parser, docstring) add_verbose(parser) add_directories(parser) return parser " Fix bug by adding JWTAuthServiceProvider declaration back to the file,"<?php namespace WWON\JwtGuard\Providers; use Illuminate\Support\Facades\Auth; use Tymon\JWTAuth\Providers\JWTAuthServiceProvider; use WWON\JwtGuard\Contract\TokenManager as TokenManagerContract; use WWON\JwtGuard\JwtGuard; class JwtGuardServiceProvider extends JWTAuthServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Boot the service provider. */ public function boot() { Auth::extend('jwt', function($app, $name, array $config) { return new JwtGuard( $app['auth']->createUserProvider($config['provider']), $app[TokenManagerContract::class], $app['request'] ); }); $this->publishConfig(); $this->publishes([ __DIR__ . '/../database/migrations/' => database_path('migrations') ], 'migrations'); } /** * Publish the configuration file. * * @return void */ private function publishConfig() { $configFile = __DIR__ . '/../config/jwt_guard.php'; $this->publishes([ $configFile => config_path('jwt_guard.php') ], 'config'); $this->mergeConfigFrom($configFile, 'jwt_guard'); } /** * Register any application services. * * @return void */ public function register() { $this->app->rebinding('request', function ($app, $request) { $request->setUserResolver(function ($guard = null) { return auth()->guard($guard)->user(); }); }); } }","<?php namespace WWON\JwtGuard\Providers; use Illuminate\Support\Facades\Auth; use WWON\JwtGuard\Contract\TokenManager as TokenManagerContract; use WWON\JwtGuard\JwtGuard; class JwtGuardServiceProvider extends JWTAuthServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Boot the service provider. */ public function boot() { Auth::extend('jwt', function($app, $name, array $config) { return new JwtGuard( $app['auth']->createUserProvider($config['provider']), $app[TokenManagerContract::class], $app['request'] ); }); $this->publishConfig(); $this->publishes([ __DIR__ . '/../database/migrations/' => database_path('migrations') ], 'migrations'); } /** * Publish the configuration file. * * @return void */ private function publishConfig() { $configFile = __DIR__ . '/../config/jwt_guard.php'; $this->publishes([ $configFile => config_path('jwt_guard.php') ], 'config'); $this->mergeConfigFrom($configFile, 'jwt_guard'); } /** * Register any application services. * * @return void */ public function register() { $this->app->rebinding('request', function ($app, $request) { $request->setUserResolver(function ($guard = null) { return auth()->guard($guard)->user(); }); }); } }" Add shib auth to similar projects page,"from django.shortcuts import redirect from django.core.urlresolvers import reverse from django.contrib.auth.decorators import login_required from approver.workflows import project_crud import approver.utils as utils @login_required def similar_projects(request, project_id=None,from_page=None): project = project_crud.get_project_or_none(project_id) if project is None: utils.dashboard_redirect_and_toast(request, 'Invalid request'.format(project_id)) elif request.method == 'GET': project_scores = project_crud.get_similar_projects(project) if (len(project_scores) == 0) : utils.set_toast(request.session, 'No relevant projects were found!') if(from_page == ""dashboard"") : return redirect(reverse(""approver:dashboard"")) else : return redirect(reverse(""approver:approve"") + str(project.id) + '/') context = { 'content': 'approver/similar_projects.html', 'project_scores': project_scores, 'project_id' : project_id, } return utils.layout_render(request, context) elif request.method == 'POST': return redirect(reverse(""approver:approve"") + str(project.id) + '/') ","from django.shortcuts import redirect from approver.workflows import project_crud from approver.decorators import login_required import approver.utils as utils from django.core.urlresolvers import reverse @login_required def similar_projects(request, project_id=None,from_page=None): project = project_crud.get_project_or_none(project_id) if project is None: utils.dashboard_redirect_and_toast(request, 'Invalid request'.format(project_id)) elif request.method == 'GET': project_scores = project_crud.get_similar_projects(project) if (len(project_scores) == 0) : utils.set_toast(request.session, 'No relevant projects were found!') if(from_page == ""dashboard"") : return redirect(reverse(""approver:dashboard"")) else : return redirect(reverse(""approver:approve"") + str(project.id) + '/') context = { 'content': 'approver/similar_projects.html', 'project_scores': project_scores, 'project_id' : project_id, } return utils.layout_render(request, context) elif request.method == 'POST': return redirect(reverse(""approver:approve"") + str(project.id) + '/')" Fix typo in upgrade script,"import os.path import shutil sql = """""" -- Remove empty values from the milestone list DELETE FROM milestone WHERE COALESCE(name,'')=''; -- Add a description column to the version table, and remove unnamed versions CREATE TEMP TABLE version_old AS SELECT * FROM version; DROP TABLE version; CREATE TABLE version ( name text PRIMARY KEY, time integer, description text ); INSERT INTO version(name,time,description) SELECT name,time,'' FROM version_old WHERE COALESCE(name,'')<>''; -- Add a description column to the component table, and remove unnamed components CREATE TEMP TABLE component_old AS SELECT * FROM component; DROP TABLE component; CREATE TABLE component ( name text PRIMARY KEY, owner text, description text ); INSERT INTO component(name,owner,description) SELECT name,owner,'' FROM component_old WHERE COALESCE(name,'')<>''; """""" def do_upgrade(env, ver, cursor): cursor.execute(sql) # Copy the new default wiki macros over to the environment from trac.siteconfig import __default_macros_dir__ as macros_dir for f in os.listdir(macros_dir): if not f.endswith('.py'): continue src = os.path.join(macros_dir, f) dst = os.path.join(env.path, 'wiki-macros', f) if not os.path.isfile(dst): shutil.copy2(src, dst) ","import os.path import shutil sql = """""" -- Remove empty values from the milestone list DELETE FROM milestone WHERE COALESCE(name,'')=''; -- Add a description column to the version table, and remove unnamed versions CREATE TEMP TABLE version_old AS SELECT * FROM version; DROP TABLE version; CREATE TABLE version ( name text PRIMARY KEY, time integer, description text ); INSERT INTO version(name,time,description) SELECT name,time,'' FROM version_old WHERE COALESCE(name,'')<>''; -- Add a description column to the component table, and remove unnamed components CREATE TEMP TABLE component_old AS SELECT * FROM component; DROP TABLE component; CREATE TABLE component ( name text PRIMARY KEY, owner text, description text ); INSERT INTO component(name,owner,description) SELECT name,owner,'' FROM component_old WHERE COALESCE(name,'')<>''; """""" def do_upgrade(env, ver, cursor): cursor.execute(sql) # Copy the new default wiki macros over to the environment from trac.siteconfig import __default_macro_dir__ as macro_dir for f in os.listdir(macro_dir): if not f.endswith('.py'): continue src = os.path.join(macro_dir, f) dst = os.path.join(env.path, 'wiki-macros', f) if not os.path.isfile(dst): shutil.copy2(src, dst) " Remove a deprecated call to bindRequest(),"<?php namespace Acme\DemoBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\RedirectResponse; use Acme\DemoBundle\Form\ContactType; // these import the ""@Route"" and ""@Template"" annotations use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; class DemoController extends Controller { /** * @Route(""/"", name=""_demo"") * @Template() */ public function indexAction() { return array(); } /** * @Route(""/hello/{name}"", name=""_demo_hello"") * @Template() */ public function helloAction($name) { return array('name' => $name); } /** * @Route(""/contact"", name=""_demo_contact"") * @Template() */ public function contactAction() { $form = $this->get('form.factory')->create(new ContactType()); $request = $this->get('request'); if ('POST' == $request->getMethod()) { $form->bind($request); if ($form->isValid()) { $mailer = $this->get('mailer'); // .. setup a message and send it // http://symfony.com/doc/current/cookbook/email.html $this->get('session')->setFlash('notice', 'Message sent!'); return new RedirectResponse($this->generateUrl('_demo')); } } return array('form' => $form->createView()); } } ","<?php namespace Acme\DemoBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\RedirectResponse; use Acme\DemoBundle\Form\ContactType; // these import the ""@Route"" and ""@Template"" annotations use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; class DemoController extends Controller { /** * @Route(""/"", name=""_demo"") * @Template() */ public function indexAction() { return array(); } /** * @Route(""/hello/{name}"", name=""_demo_hello"") * @Template() */ public function helloAction($name) { return array('name' => $name); } /** * @Route(""/contact"", name=""_demo_contact"") * @Template() */ public function contactAction() { $form = $this->get('form.factory')->create(new ContactType()); $request = $this->get('request'); if ('POST' == $request->getMethod()) { $form->bindRequest($request); if ($form->isValid()) { $mailer = $this->get('mailer'); // .. setup a message and send it // http://symfony.com/doc/current/cookbook/email.html $this->get('session')->setFlash('notice', 'Message sent!'); return new RedirectResponse($this->generateUrl('_demo')); } } return array('form' => $form->createView()); } } " Fix a crash if a country has no languages spoken,"from django.core.exceptions import ObjectDoesNotExist from countries_plus.models import Country from .models import Language, CultureCode def associate_countries_and_languages(): for country in Country.objects.all(): langs = '' try: langs = country.languages.strip(',') if langs: codes = langs.split("","") for code in codes: if '-' in code: lang_code, country_code = code.split('-') try: language = Language.objects.get(iso_639_1=lang_code) except ObjectDoesNotExist: print(""Cannot find language identified by code %s"" % lang_code) continue try: country = Country.objects.get(iso=country_code) except ObjectDoesNotExist: print(""Cannot find country identified by code %s"" % country_code) continue country.language_set.add(language) CultureCode.objects.get_or_create(code=code, language=language, country=country) else: try: language = Language.objects.get_by_code(code) country.language_set.add(language) except ObjectDoesNotExist: print(""Cannot find language identified by code %s"" % code) continue else: print (""No langauges found for country %s"" % country) ","from django.core.exceptions import ObjectDoesNotExist from countries_plus.models import Country from .models import Language, CultureCode def associate_countries_and_languages(): for country in Country.objects.all(): langs = country.languages.strip(',') if langs: codes = langs.split("","") for code in codes: if '-' in code: lang_code, country_code = code.split('-') try: language = Language.objects.get(iso_639_1=lang_code) except ObjectDoesNotExist: print(""Cannot find language identified by code %s"" % lang_code) continue try: country = Country.objects.get(iso=country_code) except ObjectDoesNotExist: print(""Cannot find country identified by code %s"" % country_code) continue country.language_set.add(language) CultureCode.objects.get_or_create(code=code, language=language, country=country) else: try: language = Language.objects.get_by_code(code) country.language_set.add(language) except ObjectDoesNotExist: print(""Cannot find language identified by code %s"" % code) continue else: print (""No langauges found for country %s"" % country) " Add copy url to clipboard setting,"import ftplib import ntpath import logging import urllib.parse import win32clipboard class FileUploader: def __init__(self, config): self._host = config['Server']['host'] self._user = config['Server']['user'] self._passwd = config['Server']['password'] self._path = config['Server']['remote_path'] self._url = config['Server']['url'] self._copy_url = config.getboolean('Settings', 'copy_url_to_clipboard') # test ftp login def upload(self, filepath): try: with ftplib.FTP(self._host, self._user, self._passwd) as ftp: ftp.cwd(self._path) name = ntpath.basename(filepath) logging.info('Upload \'{}\''.format(name)) msg = ftp.storbinary('STOR ' + name, open(filepath, 'rb')) logging.info(msg) if self._copy_url: self._copy_to_clipboard(name) except ftplib.all_errors as e: logging.exception(e, exc_info=False) def _copy_to_clipboard(self, name): url = urllib.parse.urljoin(self._url, urllib.parse.quote(name)) win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardText(url) win32clipboard.CloseClipboard() logging.info('Copied to clipboard \'{}\''.format(url)) ","import ftplib import ntpath import logging import urllib.parse import win32clipboard class FileUploader: def __init__(self, config): self._host = config['Server']['host'] self._user = config['Server']['user'] self._passwd = config['Server']['password'] self._path = config['Server']['remote_path'] self._url = config['Server']['url'] # test ftp login def upload(self, filepath): try: with ftplib.FTP(self._host, self._user, self._passwd) as ftp: ftp.cwd(self._path) name = ntpath.basename(filepath) logging.info('Upload \'{}\''.format(name)) msg = ftp.storbinary('STOR ' + name, open(filepath, 'rb')) logging.info(msg) self._copy_to_clipboard(name) except ftplib.all_errors as e: logging.exception(e, exc_info=False) def _copy_to_clipboard(self, name): url = self._url + urllib.parse.quote(name) win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardText(url) win32clipboard.CloseClipboard() logging.info('Copied to clipboard \'{}\''.format(url)) " Bump version for relative path fix,"""""""Setuptools configuration for rpmvenv."""""" from setuptools import setup from setuptools import find_packages with open('README.rst', 'r') as readmefile: README = readmefile.read() setup( name='rpmvenv', version='0.20.0', url='https://github.com/kevinconway/rpmvenv', description='RPM packager for Python virtualenv.', author=""Kevin Conway"", author_email=""kevinjacobconway@gmail.com"", long_description=README, license='MIT', packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']), install_requires=[ 'jinja2', 'venvctrl', 'argparse', 'confpy', 'ordereddict', 'semver', ], entry_points={ 'console_scripts': [ 'rpmvenv = rpmvenv.cli:main', ], 'rpmvenv.extensions': [ 'core = rpmvenv.extensions.core:Extension', 'file_permissions = rpmvenv.extensions.files.permissions:Extension', 'file_extras = rpmvenv.extensions.files.extras:Extension', 'python_venv = rpmvenv.extensions.python.venv:Extension', 'blocks = rpmvenv.extensions.blocks.generic:Extension', ] }, package_data={ ""rpmvenv"": [""templates/*""], }, ) ","""""""Setuptools configuration for rpmvenv."""""" from setuptools import setup from setuptools import find_packages with open('README.rst', 'r') as readmefile: README = readmefile.read() setup( name='rpmvenv', version='0.19.0', url='https://github.com/kevinconway/rpmvenv', description='RPM packager for Python virtualenv.', author=""Kevin Conway"", author_email=""kevinjacobconway@gmail.com"", long_description=README, license='MIT', packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']), install_requires=[ 'jinja2', 'venvctrl', 'argparse', 'confpy', 'ordereddict', 'semver', ], entry_points={ 'console_scripts': [ 'rpmvenv = rpmvenv.cli:main', ], 'rpmvenv.extensions': [ 'core = rpmvenv.extensions.core:Extension', 'file_permissions = rpmvenv.extensions.files.permissions:Extension', 'file_extras = rpmvenv.extensions.files.extras:Extension', 'python_venv = rpmvenv.extensions.python.venv:Extension', 'blocks = rpmvenv.extensions.blocks.generic:Extension', ] }, package_data={ ""rpmvenv"": [""templates/*""], }, ) " Use error response instead of throwing error,"#!/usr/bin/env node var fs = require('fs'), path = require('path'), url = require('url'), templates = require('./templates'), Server = require('./server').Server; Server.new(function (req, res) { console.log(req.url); var parsedUrl = url.parse(req.url, true); var pathname = path.normalize(parsedUrl.pathname); fs.stat('.' + pathname, function (err, stats) { if(err && err.code === ""ENOENT"") { Server.notFound(res); } else if (err) { Server.serverError(res, err); } else if(stats.isDirectory()) { res.writeHead(200, Server.contentTypes['text/html']); fs.readdir('.' + pathname, function(err, files) { if (err) { Server.serverError(res, err); } var baseUrl = pathname.match(/^\/$/)? '/' : pathname + '/'; res.end(templates.main({baseUrl: baseUrl, files: files})); }); } else { var contentType = Server.mimetype(pathname); res.writeHead(200, Server.contentTypes[contentType]); fs.readFile('.' + pathname, function(err, data){ if(err) { return Server.serverError(res, err); } return res.end(data); }); } }); }); ","#!/usr/bin/env node var fs = require('fs'), path = require('path'), url = require('url'), templates = require('./templates'), Server = require('./server').Server; Server.new(function (req, res) { console.log(req.url); var parsedUrl = url.parse(req.url, true); var pathname = path.normalize(parsedUrl.pathname); fs.stat('.' + pathname, function (err, stats) { if(err && err.code === ""ENOENT"") { Server.notFound(res); } else if (err) { Server.serverError(res, err); } else if(stats.isDirectory()) { res.writeHead(200, Server.contentTypes['text/html']); fs.readdir('.' + pathname, function(err, files) { if (err) { Server.serverError(res, err); } var baseUrl = pathname.match(/^\/$/)? '/' : pathname + '/'; res.end(templates.main({baseUrl: baseUrl, files: files})); }); } else { var contentType = Server.mimetype(pathname); res.writeHead(200, Server.contentTypes[contentType]); fs.readFile('.' + pathname, function(err, data){ if(err) { throw err; } res.end(data); }); } }); }); " Add a usage in retry,"# -*- coding: utf-8 -*- from functools import wraps import time class RetryExceededError(Exception): pass class retry(object): '''A decorator encapsulated retry logic. Usage: @retry(errors=(TTransportException, AnyExpectedError)) @retry() # detect whatsoever errors and retry 3 times ''' def __init__(self, errors=(Exception, ), tries=3, delay=0): self.errors = errors self.tries = tries self.delay = delay def __call__(self, func): @wraps(func) def _(*args, **kw): retry_left_count = self.tries while retry_left_count: try: return func(*args, **kw) except Exception, e: retry_left_count -= 1 if not isinstance(e, self.errors): raise e if not retry_left_count: raise RetryExceededError if self.delay: time.sleep(self.delay) return _ ","# -*- coding: utf-8 -*- from functools import wraps import time class RetryExceededError(Exception): pass class retry(object): '''A decorator encapsulated retry logic. Usage: @retry(errors=(TTransportException, AnyExpectedError)) ''' def __init__(self, errors=(Exception, ), tries=3, delay=0): self.errors = errors self.tries = tries self.delay = delay def __call__(self, func): @wraps(func) def _(*args, **kw): retry_left_count = self.tries while retry_left_count: try: return func(*args, **kw) except Exception, e: retry_left_count -= 1 if not isinstance(e, self.errors): raise e if not retry_left_count: raise RetryExceededError if self.delay: time.sleep(self.delay) return _ " Load script will put scripts in header,"<?php // vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: // +-------------------------------------------------------------------------+ // | Author: Armen Baghumian <armen@OpenSourceClub.org> | // +-------------------------------------------------------------------------+ // | Smarty {arag_load_script} function plugin | // | | // | Type: function | // | Name: arag_load_script | // | Purpose: load a scrip | // +-------------------------------------------------------------------------+ // $Id$ // --------------------------------------------------------------------------- static $_loaded = Array(); function smarty_function_arag_load_script($params, &$smarty) { if (is_array($params) && count($params)) { foreach ($params as $_key => $_val) { switch ($_key) { case 'src': $$_key = (string)$_val; break; default: $smarty->trigger_error(""arag_function_arag_load_script: Unknown attribute '$_key'""); } } } if (!isset($src)) { $smarty->trigger_error(""arag_function_arag_load_script: You have to set 'src' attribute.""); } global $_loaded; if (!isset($_loaded[sha1($src)])) { $_loaded[sha1($src)] = True; $GLOBALS['headers'][] = html::script($src); } return Null; } ","<?php // vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: // +-------------------------------------------------------------------------+ // | Author: Armen Baghumian <armen@OpenSourceClub.org> | // +-------------------------------------------------------------------------+ // | Smarty {arag_load_script} function plugin | // | | // | Type: function | // | Name: arag_load_script | // | Purpose: load a scrip | // +-------------------------------------------------------------------------+ // $Id$ // --------------------------------------------------------------------------- static $_loaded = Array(); function smarty_function_arag_load_script($params, &$smarty) { if (is_array($params) && count($params)) { foreach ($params as $_key => $_val) { switch ($_key) { case 'src': $$_key = (string)$_val; break; default: $smarty->trigger_error(""arag_function_arag_load_script: Unknown attribute '$_key'""); } } } if (!isset($src)) { $smarty->trigger_error(""arag_function_arag_load_script: You have to set 'src' attribute.""); } global $_loaded; if (!isset($_loaded[sha1($src)])) { $_loaded[sha1($src)] = True; return html::script($src); } return Null; } " Add log to self play,"import random from game import Game, DiscState class SelfPlay: def __init__(self, game): self.game = game self.log = [] def play(self): while self.game.winner is None: col_index = self.calc_move(self.game.current_player) if self.game.can_add_disc(col_index): success = self.game.try_turn(self.game.current_player, col_index) assert success self.log.append(col_index) self.render_board() print(""Winner is: %s"" % self.disc_state_to_player_name(self.game.winner)) def calc_move(self, current_player): return random.randint(0, self.game.grid.width) def render_board(self): str_repr = ["" %i "" % col_index for col_index in range(self.game.grid.width)] + [""\n""] for row in reversed(self.game.grid): row_repr = [] for disc_value in row: if disc_value is DiscState.empty: row_repr.append(""| |"") elif disc_value is DiscState.red: row_repr.append(""|O|"") else: # disc_value is black row_repr.append(""|X|"") row_repr.append(""\n"") str_repr += row_repr print("""".join(str_repr)) def disc_state_to_player_name(self, disc_state): if disc_state is DiscState.red: return ""O"" else: return ""X""","import random from game import Game, DiscState class SelfPlay: def __init__(self, game): self.game = game def play(self): while self.game.winner is None: col_index = self.calc_move(self.game.current_player) if self.game.can_add_disc(col_index): success = self.game.try_turn(self.game.current_player, col_index) assert success self.render_board() print(""Winner is: %s"" % self.disc_state_to_player_name(self.game.winner)) def calc_move(self, current_player): return random.randint(0, self.game.grid.width) def render_board(self): str_repr = ["" %i "" % col_index for col_index in range(self.game.grid.width)] + [""\n""] for row in reversed(self.game.grid): row_repr = [] for disc_value in row: if disc_value is DiscState.empty: row_repr.append(""| |"") elif disc_value is DiscState.red: row_repr.append(""|O|"") else: # disc_value is black row_repr.append(""|X|"") row_repr.append(""\n"") str_repr += row_repr print("""".join(str_repr)) def disc_state_to_player_name(self, disc_state): if disc_state is DiscState.red: return ""O"" else: return ""X""" Revert dependencies for ES client,"from setuptools import setup try: from pypandoc import convert read_md = lambda f: convert(f, 'rst') except ImportError: print(""warning: pypandoc module not found, could not convert Markdown to RST"") read_md = lambda f: open(f, 'r').read() setup( name=""elyzer"", entry_points={ 'console_scripts': [ 'elyzer=elyzer.__main__:main' ] }, packages=['elyzer'], version=""0.2.2"", description=""Step-by-Step Debug Elasticsearch Analyzers"", long_description=read_md('README.md'), license=""Apache"", author=""Doug Turnbull"", author_email=""dturnbull@o19s.com"", url='https://github.com/o19s/elyzer', install_requires=['elasticsearch>=1.6.0,<2.3'], keywords=[""elasticsearch"", ""database""], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Utilities' ] ) ","from setuptools import setup try: from pypandoc import convert read_md = lambda f: convert(f, 'rst') except ImportError: print(""warning: pypandoc module not found, could not convert Markdown to RST"") read_md = lambda f: open(f, 'r').read() setup( name=""elyzer"", entry_points={ 'console_scripts': [ 'elyzer=elyzer.__main__:main' ] }, packages=['elyzer'], version=""0.2.1"", description=""Step-by-Step Debug Elasticsearch Analyzers"", long_description=read_md('README.md'), license=""Apache"", author=""Doug Turnbull"", author_email=""dturnbull@o19s.com"", url='https://github.com/o19s/elyzer', py_modules=['subredis'], install_requires=['elasticsearch>=1.6.0,<5.1'], keywords=[""elasticsearch"", ""database""], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Utilities' ] ) " "Fix bug with features not appearing when feature app loaded before main app - Trigger class initialization of generated features file before showing features app","package com.github.michaelengland.fliptheswitch.app; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ListView; import com.github.michaelengland.fliptheswitch.Feature; import com.github.michaelengland.fliptheswitch.FlipTheSwitch; public class FeaturesActivity extends AppCompatActivity { private FlipTheSwitch flipTheSwitch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { Class.forName(""com.github.michaelengland.fliptheswitch.Features""); } catch (ClassNotFoundException ignored) { } flipTheSwitch = new FlipTheSwitch(this); setContentView(R.layout.activitiy_features); } @Override protected void onStart() { super.onStart(); getResetButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { flipTheSwitch.resetAllFeatures(); } }); FeaturesAdapter adapter = new FeaturesAdapter(getLayoutInflater(), FlipTheSwitch.getDefaultFeatures(), new FeaturesAdapter.OnFeatureToggledListener() { @Override public void onFeatureToggled(Feature feature, boolean enabled) { flipTheSwitch.setFeatureEnabled(feature.getName(), enabled); } }); getListView().setAdapter(adapter); } private ListView getListView() { return (ListView) findViewById(R.id.activity_features_list_view); } private Button getResetButton() { return (Button) findViewById(R.id.toolbar_reset_button); } } ","package com.github.michaelengland.fliptheswitch.app; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ListView; import com.github.michaelengland.fliptheswitch.Feature; import com.github.michaelengland.fliptheswitch.FlipTheSwitch; public class FeaturesActivity extends AppCompatActivity { private FlipTheSwitch flipTheSwitch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); flipTheSwitch = new FlipTheSwitch(this); setContentView(R.layout.activitiy_features); } @Override protected void onStart() { super.onStart(); getResetButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { flipTheSwitch.resetAllFeatures(); } }); FeaturesAdapter adapter = new FeaturesAdapter(getLayoutInflater(), FlipTheSwitch.getDefaultFeatures(), new FeaturesAdapter.OnFeatureToggledListener() { @Override public void onFeatureToggled(Feature feature, boolean enabled) { flipTheSwitch.setFeatureEnabled(feature.getName(), enabled); } }); getListView().setAdapter(adapter); } private ListView getListView() { return (ListView) findViewById(R.id.activity_features_list_view); } private Button getResetButton() { return (Button) findViewById(R.id.toolbar_reset_button); } } "