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,"title = 'Users'; $this->params['breadcrumbs'][] = $this->title; ?>

title) ?>

'btn btn-success']) ?>

$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; } ) ] ]); ?>
","title = 'Users'; $this->params['breadcrumbs'][] = $this->title; ?>

title) ?>

'btn btn-success']) ?>

$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; } ) ] ]); ?>
" Test the replacement method too,"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]; } } ","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," * * 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']; } } "," * * 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","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); } } ","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 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 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,"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); } } ","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,"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); } } ","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,"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'; } ","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.,"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; } } ","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; } 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; } 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 (

Email

Password

{ signUpError &&

{ signUpError }

}
); } } 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 (

Email

Password

{ signUpError &&

{ signUpError }

}
); } } 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","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; } } ","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 endDateList = new DateTimeParser().parse( argsTokenizer.getValue(PREFIX_DEADLINE).get()).get(0).getDates(); List 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 ( ); } }); 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 ( ); } }); 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,"There was an error collecting ganglia data "". ""(${conf['ganglia_ip']}:${conf['ganglia_port']}): $error\n""; exit; } # If we have no child data sources, assume something is wrong. if (!count($grid) and !count($cluster)) { print ""

Ganglia cannot find a data source. Is gmond running?

""; 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']; } } ?> ","There was an error collecting ganglia data "". ""(${conf['ganglia_ip']}:${conf['ganglia_port']}): $error\n""; exit; } # If we have no child data sources, assume something is wrong. if (!count($grid) and !count($cluster)) { print ""

Ganglia cannot find a data source. Is gmond running?

""; 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'); } ","/* 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'); } " 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 ( ); } } 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 ( ); } } 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.,"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']); } } ","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 = ( ); return (
  • {menuLanguage.recentTracks}
  • {menuLanguage.topArtists}
  • {menuLanguage.userInfo}
{this.state.showUser ? userElement : null}
); } }); 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 = ( ); return (
  • {menuLanguage.recentTracks}
  • {menuLanguage.topArtists}
  • {menuLanguage.userInfo}
{this.state.showUser ? userElement : null}
); } }); 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.","
{{ trans('cachet.incidents.scheduled') }}
@foreach($scheduled_maintenance as $schedule)
id }}""> {{ $schedule->name }} scheduled_at_formatted }}"" data-timeago=""{{ $schedule->scheduled_at_iso }}"">
{!! $schedule->formatted_message !!}
@if($schedule->components->count() > 0)
@foreach($schedule->components as $affected_component) {{ $affected_component->component->name }} @endforeach @endif
@endforeach
","
{{ trans('cachet.incidents.scheduled') }}
@foreach($scheduled_maintenance as $schedule)
id }}""> {{ $schedule->name }} scheduled_at_formatted }}"" data-timeago=""{{ $schedule->scheduled_at_iso }}"">
{!! $schedule->formatted_message !!}
@if($schedule->components->count() > 0)
@foreach($schedule->components as $affected_component) {{ $affected_component->component->name }} @endforeach @endif
@endforeach
" 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," 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," * @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()); } } } "," * @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) => ( 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') ? : {color} )} ); 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) => ( 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') ? : {color} )} ); 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 outputs; public int run(List 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 outputs; public void run(List 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,"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); } } ","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 Contributors: Evgeny Stepanischev 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: ' Contributors: Evgeny Stepanischev 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: ' { 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," 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 _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 _scheduled = Lists.newArrayList(); } " Change default path for the config json,"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; } } ","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,"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); } } } ","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 = () if (this.state.mechanism === ""ldap"") { mechanism = () } return (
Authenticate
{mechanism}
) } }","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 = () if (this.state.mechanism === ""ldap"") { mechanism = () } return (
Authenticate
{mechanism}
) } }" Change the search field resolving logic,"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 []; } } ","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","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 []; } } ","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"," '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"" => '.' ] ];"," '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 ( ) } } ","import React, { Component } from ""react"" import styles from ""./index.css"" import logo from ""./evilmartians.svg"" export default class Footer extends Component { render() { return ( ) } } " Use preg_quote() for escaping horizontal rule markers.," Copyright (c) 2004 John Gruber * > * * @author Kazuyuki Hayashi */ 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'; } } "," Copyright (c) 2004 John Gruber * > * * @author Kazuyuki Hayashi */ 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","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); } } ","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,"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)); } } ","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,"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'); } } ","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 ","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,"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); } } } ","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,"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); } } ","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) => (
    {state.items.map(item =>
  1. {item}
  2. )}
actions.setItem(e.target.value)} value="""" />
actions.setDelete(e.target.value)} value="""" />
), 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) => (
    {state.items.map(item =>
  1. {item}
  2. )}
actions.setItem(e.target.value)} value="""" />
actions.setDelete(e.target.value)} value="""" />
), 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', '') != '': 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>","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)); } } ","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.," * @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'], ]); } } } } "," * @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,"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 ] ); } } ","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: '' , 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: '' , 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,"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; } } ?>","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.,"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[] = '
'; } } } } } 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'; } ?>","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[] = '
'; // 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 TJSN. */ 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 TJSN. */ 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) ') 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,"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.'.'); } } } ","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,"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.' ); } } ","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) { $('').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: '
', 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: '
', 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","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, ]); } } ","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.","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); } } } ","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."," $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;}""; } } "," $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( {roleStr} {permissionsStr} ); }); } return rows; } render() { const headers = []; this.props.headers.forEach((header) => { headers.push({header}); }); return ( {headers} {this.getRows()}
); } } ","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( {roleStr} {permissionsStr} ); }); } return rows; } render() { const headers = []; this.props.headers.forEach((header) => { headers.push({header}); }); return ( {headers} {this.getRows()}
); } } " 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 ","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 """""" 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 """""" 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> extractors = new HashMap>(); public ExtractorRepository add(Iterable> 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> extractors = new HashMap>(); public ExtractorRepository add(Iterable> 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 ( route.sceneConfig || Navigator.SceneConfigs.FloatFromBottomAndroid} renderScene={(route, navigator) => { switch (route.name) { case 'splash': return ; case 'login': return ; case 'register': return ; case 'overview': return ; default: return Bad route name given! } }} /> ); } } 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 ( route.sceneConfig || Navigator.SceneConfigs.FloatFromBottomAndroid} renderScene={(route, navigator) => { switch (route.name) { case 'splash': return ; case 'login': return ; case 'register': return ; case 'overview': return ; default: return Bad route name given! } }} /> ); } } 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 = $('
').text(json.feedback).addClass('feedback'); var artwork = $('
').append($('').attr('src', artworkUrl)) .append($('').attr('src', json.image).addClass('redline')) .addClass('drawing'); var item = $('
').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 = $('
').text(json.feedback).addClass('feedback'); var artwork = $('
').append($('').attr('src', artworkUrl)) .append($('').attr('src', json.image).addClass('redline')) .addClass('drawing'); var item = $('
').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,"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; } } ","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 Contributors: Evgeny Stepanischev 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: ' Contributors: Evgeny Stepanischev 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: '. 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, ]; } } ",". 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," 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); } } "," 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,"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; } } ","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 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 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 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 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,"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'; } } ","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
\ '; } 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 ''; 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 = '
'; var editorTemplate = ''; 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,"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(); } } ","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 ); 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,"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); } } ","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.,"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; } }","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","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(); } } ","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,"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 '); }) ->tag('agreement-docusign-received') ->metadata('envelope-id', strval($this->envelope->id)); } } ","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 '); }) ->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 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> getWithPrefixes() { Map> result = new TreeMap>(); 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 cur_list = result.get(splits[0]); if (cur_list == null) { cur_list = new ArrayList(); } 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 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> getWithPrefixes() { Map> result = new HashMap>(); 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 cur_list = result.get(splits[0]); if (cur_list == null) { cur_list = new ArrayList(); } 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.,"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(); } } ","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.,"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); } ); } } ","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.
"" ""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.
"" ""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')
@yield('settings_title') {{ csrf_field() }} @yield('settings_body')
@endsection ","@extends('layout') @section('body')
@yield('settings_title')
{{ csrf_field() }} @yield('settings_body')
@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 """" }; let buildAsHtml = function (lines) { let output = [buildHeader(lines[0])]; for (let i = 1; i < lines.length; i++) output.push("""" + lines[i].slice(0, -1).split("","").join("""") + """"); return """" + output.join("""") + ""
""; }; 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(""""); for (i = 1; i < lines.length; i++) output.push("""" + lines[i].slice(0, -1).split("","").join("""") + """"); output = """" + output.join("""") + ""
""; 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 = $('').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 = $('').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,"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); } } ","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']])
{!! $page['content']['main'] !!} @for ($i = 0; $i < 10; $i++) @endfor
First Name Last Name Email
{{ $faker->firstName }} {{ $faker->lastName }} {{ $faker->email }}
See Table Code
        {!! htmlspecialchars('
') !!}
@endsection ","@extends('components.content-area') @section('content') @include('components.page-title', ['title' => $page['title']])
{!! $page['content']['main'] !!} @for ($i = 0; $i < 10; $i++) @endfor
First Name Last Name Email
{{ $faker->firstName }} {{ $faker->lastName }} {{ $faker->email }}
See Table Code
        {!! htmlspecialchars('
') !!}
@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,". 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); } } } ",". 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,"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' ); } } ","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," * * 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; } }"," * * 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 ', 'Path to output directory, defaults to ./_book') .option('-f, --format ', 'Change generation format, defaults to site, availables are: '+_.keys(generators).join("", "")) .option('--config ', '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 ', 'Path to output directory, defaults to ./_book') .option('-f, --format ', 'Change generation format, defaults to site, availables are: '+_.keys(generators).join("", "")) .option('--config ', '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
@foreach ($contacts as $contact)
@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)
@endif
@include('partials.information')
@endcard
@endforeach
","@if (!$hideTitle && !empty($postTitle)) @typography([ 'id' => 'mod-text-' . $ID .'-label', 'element' => 'h4', 'variant' => 'h2', 'classList' => ['module-title'] ]) {!! $postTitle !!} @endtypography @endif
@foreach ($contacts as $contact)
@card([ 'collapsible' => $contact['hasBody'], 'attributeList' => [ 'itemscope' => '', 'itemtype' => 'http://schema.org/Person' ], 'classList' => [ 'c-card--square-image' ], 'context' => 'module.contacts.card' ]) @if($showImages)
@endif
@include('partials.information')
@endcard
@endforeach
" "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(); } return (
  • {model.name}

    Rating: {ratings}

  • ) } } 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(); } return (
  • {model.name}

    Rating: {ratings}

  • ) } } 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 ","#!/usr/bin/env python import sys, os MAX_PACKSIZE = 1024*1024*1024 def usage(): sys.stderr.write(""usage: kurt.py \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 \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,"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; } }","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 . 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 . 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 '
    = 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.," * * 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(); } } "," * * 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,"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; } } ","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 = '
    '; 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 = '
    '; 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."," */ 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'; } } "," */ 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.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,"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')); } } ","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 ' + self.get('status') + '.'); }, 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 ' + self.get('status') + '.'); }, 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.,"_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); } } }","_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," [ '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); } }"," [ '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"""""" %s     """""" % (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( """""" %s     """""" % (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,"_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); } } ","_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","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); } } ","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,"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() ) ); } } } ","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","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(); } } } ","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 * @author Abby Walker */ 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 * @author Abby Walker */ 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."," * (c) Mell Zamora * * 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)); } } "," * (c) Mell Zamora * * 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.,"_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; } } ","_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.,"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; } } ","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.,"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'], ]); } } ","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 data; @Before public void setup() { data = new HashMap(); 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 data; @Before public void setup() { data = new HashMap(); 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 findByName(String name); List findNuggetsByTwoFactTypes( @Param(""lessonName"") String lessonName, @Param(""factType1"") String questionType, @Param(""factType2"") String answerType); List findNuggetsBySuccessrate( @Param(""username"") String username, @Param(""lessonName"") String lessonName, @Param(""factType1"") String questionType, @Param(""factType2"") String answerType); List 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 findVocabularyLessons(); @Query(""select l from Lesson l where l.description = 'quiz' order by l.name"") List 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 findByName(String name); List findNuggetsByTwoFactTypes( @Param(""lessonName"") String lessonName, @Param(""factType1"") String questionType, @Param(""factType2"") String answerType); List findNuggetsBySuccessrate( @Param(""username"") String username, @Param(""lessonName"") String lessonName, @Param(""factType1"") String questionType, @Param(""factType2"") String answerType); List 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 findVocabularyLessons(); @Query(""select l from Lesson l where l.description = 'quiz'"") List findQuizLessons(); } " Add better connection management ...,"#!/usr/bin/python # -*- coding: -*- 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: -*- 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 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 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,"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); } } ","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.," @forelse($users as $user) @empty @endforelse
    Name Contact Methods Last Visited
    id]) }}"">{{ $user->display_name }} {{ $user->email_preview }} @if ($user->email_preview && $user->mobile_preview) and @endif {{ $user->mobile_preview }} {{ $user->last_accessed_at ? $user->last_accessed_at->diffForHumans() : 'N/A' }}
    "," @forelse($users as $user) @empty @endforelse
    Name Contact Methods Last Visited
    id]) }}"">{{ $user->display_name }} {{ $user->email_preview }} @if ($user->email_preview && $user->mobile_preview) and @endif {{ $user->mobile_preview }} {{ $user->last_accessed_at ? $user->last_accessed_at->diffForHumans() : 'more than 2 years ago' }}
    " 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,"setIntitule($poste); $p->setDescription(""a completer""); $manager->persist($p); } $manager->flush(); } } ","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 mValidationHolderList; public Validator() { mValidationHolderList = new ArrayList(); } 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 mValidationHolderList; public Validator() { mValidationHolderList = new ArrayList(); } 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` `; /* eslint-enable indent */ } } ","import { HeaderService } from ""./header.service.js""; export class HeaderTemplate { static update(render) { const start = Date.now(); /* eslint-disable indent */ render` `; /* 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 (
    {this.state.displayDeleteAccountMessage ?
    We hate to see you leaving. Are you sure?   Yes No
    : null}
    ); } } 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 (
    {this.state.displayDeleteAccountMessage ?
    We hate to see you leaving. Are you sure?   Yes No
    : null}
    ); } } 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,"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'); } } ","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//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 ( CentralConfig ); } } 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 ( CentralConfig ); } } 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,"'; 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 = '' + ''; 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," * * 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'; } } "," * * 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='', 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='', 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","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); } } ","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," $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; } } "," $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,"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); }; } } ","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"," tag. The Base URI * is taken from the current request. * In FLOW3, you should always include this ViewHelper to make the links work. * * = Examples = * * * * * * * (depending on your domain) * * * @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 'controllerContext->getRequest()->getHttpRequest()->getBaseUri() . '"" />'; } } ?> "," tag. The Base URI * is taken from the current request. * In FLOW3, you should always include this ViewHelper to make the links work. * * = Examples = * * * * * * * (depending on your domain) * * * @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 '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,"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*', $client->getResponse()->getContent() ); self::assertContains( 'Visible on site', $client->getResponse()->getContent() ); self::assertContains( 'Add content block', $client->getResponse()->getContent() ); } } ","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 *', $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 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 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ä , Sakari Rautiainen , Teppo Malinen , Jarno Tuovinen ', 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ä , Sakari Rautiainen , Teppo Malinen ', 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,"
    Who to follow
    @if (count($follow_suggestions)) @foreach ($follow_suggestions as $follow_suggestion)
    username) }}""> photo($follow_suggestion->id) }}"" style=""max-width: 32px; max-height: 32px;"" alt=""User photo"">
    username) }}"" style=""color: #555;""> {{ $follow_suggestion->name }} @if ($follow_suggestion->verified > 0) @endif username }}"">{{ '@' . $follow_suggestion->username }}
    id }}"" :current-user-id=""{{ Auth::id() }}"">

    @endforeach Search by interests @else No suggestions. @endif
    ","
    Who to follow
    @if (count($follow_suggestions)) @foreach ($follow_suggestions as $follow_suggestion)
    username) }}""> photo($follow_suggestion->id) }}"" style=""max-width: 48px; max-height: 48px;"" alt=""User photo"">
    username) }}"" style=""color: #555;""> {{ $follow_suggestion->name }} @if ($follow_suggestion->verified > 0) @endif {{ '@' . $follow_suggestion->username }}
    id }}"" :current-user-id=""{{ Auth::id() }}"">

    @endforeach Search by interests @else No suggestions. @endif
    " 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,"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; } } ","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 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," 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); } } "," 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 """""" wrong page """""" @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 """""" wrong page """""" @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 (
    ); } } 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 (
    ); } } 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 (
    this.setState({ income: event.target.value })} inputProps={{ step: '10000' }} margin=""normal"" style={{ width: '100%' }} />
    this.setState({ expenses: event.target.value })} inputProps={{ step: '10000' }} margin=""normal"" style={{ width: '100%' }} />
    ); } } 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 (
    this.setState({ income: event.target.value })} margin=""normal"" style={{ width: '100%' }} />
    this.setState({ expenses: event.target.value })} margin=""normal"" style={{ width: '100%' }} />
    ); } } export default TextFields; " [NodeBundle] Set correct typehints on methods and properties,"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; } } ","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 # 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 # 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 { 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 ( {accordionStore => ( )} ); } } 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 { 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 ( {accordionStore => ( )} ); } } 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(""\n\n\n"" + ""Skupiny clenu v RV\n"" + """") def printBody(count, zahajeni, probihajici): print(""\n"" + ""

    Skupiny clenu v RV

    \n"" + ""\n"" + ""\n"" + ""\n"" + ""\n"" + ""\n\n\n"" + ""\n"" + ""
    Pocet clenuVelikost skupiny pro zahajeni jednaniVelikost skupiny na probihajicim jednani
    "" + str(count) + """" + str(zahajeni) + """" + str(probihajici) + ""
    \n"") def printFooter(): print(""

    Generated: "" + datetime.datetime.now() + ""

    "") print("""") 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(""\n\n\n"" + ""Skupiny clenu v RV\n"" + """") def printBody(count, zahajeni, probihajici): print(""\n"" + ""

    Skupiny clenu v RV

    \n"" + ""\n"" + ""\n"" + ""\n"" + ""\n"" + ""\n\n\n"" + ""\n"" + ""
    Pocet clenuVelikost skupiny pro zahajeni jednaniVelikost skupiny na probihajicim jednani
    "" + str(count) + """" + str(zahajeni) + """" + str(probihajici) + ""
    \n"" + """") def printFooter(): print("""") 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," * @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'); } } } "," * @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,"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); } } } ","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," $value) { if (is_string($value)) { $arguments[$key] = Arr::pluck($multiarray, $value); } } $arguments[] = &$multiarray; call_user_func_array('array_multisort', $arguments); return array_pop($arguments); } } "," $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 = [('NAME', 'TYPE', 'LAST', 'NEXT')] 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 = 'now' 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 = '%s' % next_date.humanize() else: next_date_text = '%s' % 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 = [('NAME', 'TYPE', 'LAST', 'NEXT')] 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 = 'now' 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 = '%s' % next_date.humanize() else: next_date_text = '%s' % 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","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 ''; } } ?> ","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,"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); } } ","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.","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')); } } } } ","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 impl; public RArray() { impl = new ArrayList(); } public RArray(RObject... args) { impl = new ArrayList(Arrays.asList(args)); } public RArray(List impl) { this.impl = new ArrayList(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 impl; public RArray() { impl = new ArrayList(); } public RArray(RObject... args) { impl = new ArrayList(Arrays.asList(args)); } public RArray(List impl) { this.impl = new ArrayList(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,"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; } } ","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","seo->title)) { $aPageTitle[] = $page->seo->title; } elseif (!empty($page->title)) { $aPageTitle[] = $page->title; } $aPageTitle[] = APP_NAME; $sBodyClass = !empty($page->body_class) ? $page->body_class : ''; ?> '; echo implode(' - ', $aPageTitle); echo ''; // -------------------------------------------------------------------------- // 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'); ?> > "," '; if (!empty($page->seo->title)) { echo $page->seo->title . ' - '; } elseif (!empty($page->title)) { echo $page->title . ' - '; } echo APP_NAME; echo ''; // -------------------------------------------------------------------------- // Meta tags echo $this->meta->outputStr(); // -------------------------------------------------------------------------- // Assets $this->asset->output('CSS'); $this->asset->output('CSS-INLINE'); $this->asset->output('JS-INLINE-HEADER'); ?> " 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 """""" 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 """""" 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,"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(); } } ","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,"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); } } ","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='', author_email='', 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='', author_email='', 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 (
    {this.props.children[selectedItem]}
    {this.props.children.map((child, index) => ( this.updateImage(index)} > {child} ))}
    ); } } 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 (
    {this.props.children[selectedItem]}
    {this.props.children.map((child, index) => ( this.updateImage(index)} > {child} ))}
    ); } } 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," * * 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; } } "," * * 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 cache = new WeakHashMap(); 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 cache = new WeakHashMap(); 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.,"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); } } ","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 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,"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); } } }","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 ( ) } }","import React, { Component } from 'react' import { Link, IndexLink } from 'react-router' export class Nav extends Component { constructor(props) { super(props) } render() { return ( ) } }" 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","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(); } } ","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,"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; } } ","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 -. 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 -. 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," */ 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(); } "," */ 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')

    Support Tickets

    @foreach($statuses as $status) {{ $status }} @endforeach
    @foreach ($tickets as $ticket) @if (Sentry::inGroup(Sentry::findGroupByName('Admins')) || $ticket->owner_id == Sentry::getUser()->id) @endif @endforeach
    Title Priority Status Replies Owner Updated At
    id)) }}""> {{ $ticket->title }} {{ $ticket->priority->title }} {{ $ticket->status->title }} {{ $ticket->replies }} {{ $ticket->owner->username }} {{ $ticket->updated_at }}
    @stop","@extends('layouts.default') @section('content')

    Support Tickets

    @foreach ($tickets as $ticket) @if (Sentry::inGroup(Sentry::findGroupByName('Admins')) || $ticket->owner_id == Sentry::getUser()->id) @endif @endforeach
    Title Priority Status Replies Owner Updated At
    id)) }}""> {{ $ticket->title }} {{ $ticket->priority->title }} {{ $ticket->status->title }} {{ $ticket->replies }} {{ $ticket->owner->username }} {{ $ticket->updated_at }}
    @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""","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']); } } } ","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,"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; } } ","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,"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', ]; } } ","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 (
      {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 (
    • ); }) ) : (
    • )}
    ); }; 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 (
      {sections.length ? ( sections .reduce((acc, { text, id }) => { acc.push({ text, id, route: `${route}#${id}` }); return acc; }, []) .map(({ text, id, route, permissions: sectionPermissions }) => { return (
    • ); }) ) : (
    • )}
    ); }; 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," */ 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; } } ?>"," */ 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 ''' 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 ''' 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 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 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 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 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,"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'] ); } } } ","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","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], ]; } } ","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 warmsea 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 warmsea 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,"_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); }); } } ","_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 */ 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 */ 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, """", ""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, """", ""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 errorHistory = new LinkedList(); public ConstantDelayReconnector() { errorHistory = new LinkedList(); } public ConstantDelayReconnector(int wait) { this.wait = wait; errorHistory = new LinkedList(); } 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 errorHistory = new LinkedList(); public ConstantDelayReconnector() { errorHistory = new LinkedList(); } public ConstantDelayReconnector(int wait) { this.wait = wait; errorHistory = new LinkedList(); } 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 = (); // switch (answer.correct) { // case true: // rightIcon = (); // break; // } return ( //
    // {rightIcon} //
    // {answer.answer} //
    //
    //defaultChecked={answer.correct} />
    ); } } 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 = (); // switch (answer.correct) { // case true: // rightIcon = (); // break; // } return ( //
    // {rightIcon} //
    // {answer.answer} //
    //
    ); } } 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}) => ( {date} {author} {location ? ( {location} ) : 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}) => ( {date.toLocaleDateString()} {author} {location ? ( {location} ) : 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: """""" @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 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 tag, return the real HTML representation. """""" Image = get_image_model() try: image = Image.objects.get(id=attrs['id']) except Image.DoesNotExist: return """" 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: """""" @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 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 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 """" " 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,"compiler()->directive('parsedown', function (string $expression = '') { return """"; }); $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'); } } ","compiler()->directive('parsedown', function (string $expression = '') { return """"; }); $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," */ 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; } } "," */ 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 list = operation.asPropertyList(); Iterator 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 list = operation.asPropertyList(); Iterator 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,"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', ) ); } } ","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,"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 */","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`","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', $tag, $response->getStatusCode(), $tag, $url )); }); return $this->exitCode; } } ","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', $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(""
  • image.png
  • \n"")); assertThat(new String(response.getBody()), CoreMatchers.containsString(""
  • partial_content.txt
  • \n"")); assertThat(new String(response.getBody()), CoreMatchers.containsString(""
  • patch-content.txt
  • \n"")); assertThat(new String(response.getBody()), CoreMatchers.containsString(""
  • readerFile.txt
  • \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 = ""\n
      \n"" + ""
    1. image.png
    2. \n"" + ""
    3. partial_content.txt
    4. \n"" + ""
    5. patch-content.txt
    6. \n"" + ""
    7. readerFile.txt
    8. \n"" + ""
    \n\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 getHealth() { return new ResponseEntity(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 getHealth() { return new ResponseEntity(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," 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', ), ), ); "," 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,"em($this->ck->module->name('article'))->publishYears(); ?> ","em($this->ck->module->name('article'))->publishYears(); ?> " 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," $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]); } } ?> $group) : ?>
    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] ) ?>
      $config) : ?>
    • element('action-button', ['config' => $links[$subaction]]); ?>
    $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]); } } ?> $group) : ?>
    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] ) ?>
      $config) : ?>
    • element('action-button', ['config' => $links[$subaction]]); ?>
    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 getDiscoveryStrategyType() { // Returns the actual class type of the DiscoveryStrategy // implementation, to match it against the configuration return DockerSwarmDiscoveryStrategy.class; } public Collection getConfigurationProperties() { return PROPERTIES; } public DiscoveryStrategy newDiscoveryStrategy(DiscoveryNode discoveryNode, ILogger logger, Map 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 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 getDiscoveryStrategyType() { // Returns the actual class type of the DiscoveryStrategy // implementation, to match it against the configuration return DockerSwarmDiscoveryStrategy.class; } public Collection getConfigurationProperties() { return PROPERTIES; } public DiscoveryStrategy newDiscoveryStrategy(DiscoveryNode discoveryNode, ILogger logger, Map 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(''); } $.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 = $('
    ').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(''); } $.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 = $('
    ').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 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 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 . --}} @foreach($posts as $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 . --}} can(); ?> @foreach($posts as $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,"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 */ 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); } } } } ","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 */ 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 (
    • 总收入: { totals.income }
    • 总支出: { totals.outcome }
    • { totals.debt > 0 ? 净欠款: : 净还款: } { Math.abs(totals.debt) }
    • { totals.loan > 0 ? 净借出: : 净借入: } { Math.abs(totals.loan) }
    ); } } 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 (
    • 总收入: { totals.income }
    • 总支出: { totals.outcome }
    • { totals.debt > 0 ? 净欠款: : 净还款: } { Math.abs(totals.debt) }
    • { totals.debt > 0 ? 净借出: : 净借入: } { Math.abs(totals.loan) }
    ); } } 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,"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'; } } ","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 # 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 # 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," '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 ], ]; "," '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(''); 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(''); 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," '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); } } "," '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,"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', ]); } } ","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,"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?'), ); } } ","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.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," EndofCodes Demo "," EndofCodes Demo " "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 ","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\d+)\.(?P\d+)\.' '(?P\d+)((?P[a-z]+)(?P\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\d+)\.(?P\d+)\.' '(?P\d+)((?P[a-z]+)(?P\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","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); } } ","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","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'); } } ","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 }; constructor() { super(); this.state = { tasks: [] }; } setTasks(tasks: Array) { 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 ( ); } } ","/** * * @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 }; 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 = testRows(); this.setState({tasks: tr}); } componentDidMount() { this.getAllTasks().then(tasks => { this.setState({tasks: tasks}); }); } render() { return ( ); } } " 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," * * 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 */ 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; } } "," * * 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 */ 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,"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; } } ","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 ','specify an input file', setupNewFileStream, 'read') .option('-o, --output ','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 ','specify an input file', setupNewFileStream, 'read') .option('-o, --output ','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," */ 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; } } "," */ 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," 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, ); } } "," 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, DB> mongoDbFactoryMap = new HashMap, DB>(); private MongoDBFactory() {} public static DB get(List 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, DB> mongoDbFactoryMap = new HashMap, DB>(); private MongoDBFactory() {} public static DB get(List 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,"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(); } } } ","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,"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; } }","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 (

    Return Home

    Oops!

    Currently, advanced graphs are only supported on desktop. Return Home

    ) } } 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 (

    Return Home

    Oops!

    Currently, advanced graphs are only supported on desktop. Return Home

    ) } } 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 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","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 .= ' '.$this->helper->text->e($user['name']).''; } $result[] = array( 'value' => $user['username'], 'html' => $html, ); } return $result; } }","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 .= ' '.$this->helper->text->e($user['name']).''; } $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.,"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( 'PhantomJS is running with PID %d', $this->pidPhantomJs )); sleep(2); } public function stopPhantomJs(ConsoleTerminateEvent $event) { if ('codeup:rollcall' !== $event->getCommand()->getName()) { return; } exec(""kill {$this->pidPhantomJs}""); $event->getOutput()->writeln(sprintf( 'PhantomJS with PID %d was stopped', $this->pidPhantomJs )); } } ","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( 'PhantomJS is running with PID %d', $this->pidPhantomJs )); } public function stopPhantomJs(ConsoleTerminateEvent $event) { if ('codeup:rollcall' !== $event->getCommand()->getName()) { return; } exec(""kill {$this->pidPhantomJs}""); $event->getOutput()->writeln(sprintf( 'PhantomJS with PID %d was stopped', $this->pidPhantomJs )); } } " Fix generator path for service provider," $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')); } } "," $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,"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; } } ","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 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 getProperties() { Map propertiesMap = this.propertiesMap; if (propertiesMap == null) { propertiesMap = this.propertiesMap = new ConfigSourceMap(this); } return propertiesMap; } public abstract Set 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 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 getProperties() { Map propertiesMap = this.propertiesMap; if (propertiesMap == null) { propertiesMap = this.propertiesMap = new ConfigSourceMap(this); } return propertiesMap; } public abstract Set 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," 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; } } "," 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,"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'; } } ","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 { 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 { 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 { 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 { 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,"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""; } } ","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," */ 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 ); } } "," */ 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,"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 ) ); } } ","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 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 findComponents() throws Exception { Collection 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 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 findComponents() throws Exception { Collection 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 onSelect(item.props.children, item.props.value)} > {item} }); return ( {renderedItems} ); } } 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 onSelect(item.props.children, item.props.value)} > {item} )); return ( {renderedItems} ); } } var styles = StyleSheet.create({ scrollView: { height: 120, width: 300, borderWidth: 1 } }); " Make sure request body stream is writable.,"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); } }","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 tasks) { run(tasks, CROWDIN_API_MAX_CONCURRENT_REQUESTS, tasks.size() * 2); } public static void executeAndWaitSingleThread(List tasks) { run(tasks, 1, 100); } private static void run(List 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 tasks) { run(tasks, CROWDIN_API_MAX_CONCURRENT_REQUESTS, tasks.size() * 2); } public static void executeAndWaitSingleThread(List tasks) { run(tasks, 1, 100); } private static void run(List 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","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); } } ","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.+?@?.+)?@)?(?P.+)"") 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.+)?@)?(?P.+)"") 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= 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 = '
    '; postHTML += '

    '; if (postData.url) postHTML += ''; postHTML += postData.title; if (postData.url) postHTML += '

    '; if (postData.image) postHTML += '
    '; if (postData.likes) postHTML += postData.likes + ' likes'; postHTML += '
    '; $(""#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= 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 = '
    '; postHTML += '

    '; if (postData.url) postHTML += ''; postHTML += postData.title; if (postData.url) postHTML += '

    '; if (postData.image) postHTML += '
    '; if (postData.likes) postHTML += postData.likes + ' likes'; postHTML += '
    '; $(""#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(),"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'); } } ","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.
    * 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.
    * 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 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 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.","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'); } ); } } ","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," * @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; } } "," * @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,". 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 } ",". 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 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 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,"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'; } } ","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)," * @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); } }"," * @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," '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', ], ]; } } "," '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,"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(); } }","__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,"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'; } } ","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,"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]); } }","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 * @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 * @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,"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(); } } ","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 ( {interpolated =>
    {type}
    }
    ) } } ","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 ( {interpolated =>
    {type}
    }
    ) } } " 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 ( ) } } ","import React, { Component } from ""react"" import styles from ""./index.css"" import logo from ""./evilmartians.svg"" export default class Footer extends Component { render() { return ( ) } } " Set file permissions for app.,"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'); } } ","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')

    @lang('app.contact.info')

    @stop @section ('scripts') @stop ","@extends ('base') @section ('subheader') @stop @section ('content')

    @lang('app.contact.info')

    @stop @section ('scripts') @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} fulfills a promise when successful */ async send ({ to: recipient, subject, body }) { const email = { body } await this.transporter.sendMail({ from: 'Fuel Rats (Do Not Reply) ', 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} fulfills a promise when successful */ async send ({ to: recipient, subject, body }) { const email = { body } await this.transporter.sendMail({ from: 'Fuel Rats (Do Not Reply) ', 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,"
    "" class=""list-group-item"">

      contentContainer($category['space']) ->andFilterWhere(['post_type' => 'question']) ->orderBy('created_at DESC') ->limit(6) ->all(); foreach($questions as $q) { echo ""
    • ""; 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 ""
    • ""; } ?>
    ","
    "" class=""list-group-item"">

      contentContainer($category['space']) ->andFilterWhere(['post_type' => 'question']) ->orderBy('created_at DESC') ->limit(3) ->all(); foreach($questions as $q) { echo ""
    • ""; 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 ""
    • ""; } ?>
    " "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"," * * 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( $provider); } "," * * 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( $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,"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'; } } ","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,"

    "">
    ""/>

    ","

    "">

    " 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," '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'); } } "," '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," $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); } } "," $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."," * * 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'); } } "," * * 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', '
    Thanks for registering this bill!
    ') }else{ Session.set('message', '
    Couldn\'t find this bill in our records. Register it as new here!
    '); } } }); 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', '
    Thanks for registering this bill!
    ') }else{ Session.set('message', '
    Couldn\'t find this bill in our records. Register it as new here!
    '); } } }); 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,"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); } } ","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 (
    Company 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 && }
    ); } } ","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 (
    Company Name: { let companyEntry = _.find(Companies, 'name', name); this.setState({companyId: companyEntry.id}); } } /> {this.state.companyId && }
    ); } } " 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 implements HelloWorldView { private Button mButton; private TextView mOutput; private TextView mUptime; @Override public Observable 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 implements HelloWorldView { private Button mButton; private TextView mOutput; private TextView mUptime; @Override public Observable 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 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,"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); } ); } } ","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.," * @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); } } "," * @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 ""); 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 ""); 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,"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; } } ","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," * * 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 */ 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'; } }"," * * 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 */ 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","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(); } } ","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 = () => ( ) export default MapFooter ","import React from 'react' import i18n from '../../i18n' const MapFooter = () => ( ) 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/"", 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/"", 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('', '', 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('', '', 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","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())); } } } ","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 ; }; if (!snackbarItems) { return null; } const renderItems = () => { const items = { topLeft: [], topCenter: [], topRight: [], bottomLeft: [], bottomCenter: [], bottomRight: [], }; snackbarItems.map(item => { items[item.position].push(item); }); return (
    {Object.keys(items).map(pos => { if (!items[pos].length) { return null; } return (
    {items[pos].map((item, index) => (
    {renderItem(item)}
    ))}
    ); })}
    ); }; 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 ; }; if (!snackbarItems) { return null; } const renderItems = () => { const items = { topLeft: [], topCenter: [], topRight: [], bottomLeft: [], bottomCenter: [], bottomRight: [], }; snackbarItems.map(item => { items[item.position].push(item); }); return (
    {Object.keys(items).map(pos => { if (!items[pos].length) { return null; } return (
    {items[pos].map(item => (
    {renderItem(item)}
    ))}
    ); })}
    ); }; return <>{renderItems()}; }; export default SnackbarContainer; " "Replace placeholder text with site description Signed-off-by: Eddie Ringle "," <?php wp_title('«', true, 'right'); bloginfo('name'); ?> /style.css"" /> /css/superfish.css"" />
    "," <?php wp_title('«', true, 'right'); bloginfo('name'); ?> /style.css"" /> /css/superfish.css"" />

    < insert site description/status update here >

    " 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 (
    ); } } 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 (
    ); } } 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 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 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 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 ''') 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 ''') exit(2) except TypeError, e: print('''ERROR: {}'''.format(e)) print('''Syntax: ./start.py ''') 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 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 ''') 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 ''') exit(2) except TypeError, e: print('''ERROR: {}'''.format(e)) print('''Syntax: ./start.py ''') 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," '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++; } } } }"," '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: '' }) .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: '' }) .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,"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 ","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," $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); } } "," $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(""<%-title%>""), 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(""
    '<%-title%>' written by <%-author%> sometime around <%-year%>
    ""), initialize: function (opts) { this.$el.html(this.template(opts.book.toJSON())); } }), Error: Backbone.View.extend({ template: _.template(""
    Oops, an error occured: <%-error%>
    ""), 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(""<%-title%>""), 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(""
    '<%-title%>' written by <%-author%> sometime around <%-year%>
    ""), initialize: function (opts) { this.$el.html(this.template(opts.book.toJSON())); } }), Error: Backbone.View.extend({ template: _.template(""
    Oops, an error occured: <%-error%>
    ""), 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,"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(); }); }); } }","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()," $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()); } } "," $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," | // +-------------------------------------------------------------------------+ // | 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; } "," | // +-------------------------------------------------------------------------+ // | 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); } } "