text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix typo and missing acces modifier
<?php namespace Qandidate\Toggle; use Symfony\Component\ExpressionLanguage\ExpressionLanguage; /** * A condition written as a symfony language expression that gets evaluated against the * full context, allowing access to several keys of the context in a single condition */ class ExpressionCondition extends Condition { protected $expression; protected $language; /** * @param string $expression The expression to be evaluated * @param ExpressionLanguage $language The instance of the Expression Language */ public function __construct($expression, ExpressionLanguage $language) { $this->expression = $expression; $this->language = $language; } /** * @inheritdoc */ public function holdsFor(Context $context) { return $this->language->evaluate($this->expression, $context->toArray()) === true; } }
<?php namespace Qandidate\Toggle; use Symfony\Component\ExpressionLanguage\ExpressionLanguage; /** * A condition written as a symfony language expression that gets evaluated against the * full context, allowing access to several keys of the context in a single condition */ class ExpressionCondition extends Condition { protected $expression; protected $language; /** * @param string $expression The expression to ve evaluated * @param ExpressionLanguage $language The instance of the Expression Language */ function __construct($expression, ExpressionLanguage $language) { $this->expression = $expression; $this->language = $language; } /** * @inheritdoc */ public function holdsFor(Context $context) { return $this->language->evaluate($this->expression, $context->toArray()) === true; } }
Use new path name to Models for test case
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.opensim.view; import java.io.File; import java.net.URL; import java.security.CodeSource; import java.security.ProtectionDomain; /** * * @author Jingjing */ public class TestEnvironment { private static String modelPath = null; public static void initializePath() { ProtectionDomain pd = FileOpenOsimModelAction.class.getProtectionDomain(); CodeSource cs = pd.getCodeSource(); URL url = cs.getLocation(); File f = new File(url.getFile()); File targetFile = f.getParentFile().getParentFile().getParentFile().getParentFile().getParentFile().getParentFile(); String ap = targetFile.getAbsolutePath() + "\\opensim-models\\Models\\Arm26\\arm26.osim"; modelPath = ap; } public static String getModelPath() { if (modelPath == null) { initializePath(); } return modelPath; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.opensim.view; import java.io.File; import java.net.URL; import java.security.CodeSource; import java.security.ProtectionDomain; /** * * @author Jingjing */ public class TestEnvironment { private static String modelPath = null; public static void initializePath() { ProtectionDomain pd = FileOpenOsimModelAction.class.getProtectionDomain(); CodeSource cs = pd.getCodeSource(); URL url = cs.getLocation(); File f = new File(url.getFile()); File targetFile = f.getParentFile().getParentFile().getParentFile().getParentFile().getParentFile().getParentFile(); String ap = targetFile.getAbsolutePath() + "\\Models\\Arm26\\arm26.osim"; modelPath = ap; } public static String getModelPath() { if (modelPath == null) { initializePath(); } return modelPath; } }
Make name more specific to avoid clash in repo
package test.ccn.security.access; import java.util.SortedSet; import junit.framework.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.parc.ccn.data.ContentName; import com.parc.ccn.library.CCNLibrary; import com.parc.ccn.library.EnumeratedNameList; import com.parc.ccn.library.io.repo.RepositoryOutputStream; public class SampleTestRepo { static final String base = "/parc.com/csl/ccn/repositories/SampleTestRepo"; static final String file_name = "simon.txt"; static final String txt = "Sample text file from Simon."; static final String UTF8 = "UTF-8"; @BeforeClass public static void setUpBeforeClass() throws Exception { ContentName name = ContentName.fromNative(base + "/" + file_name); RepositoryOutputStream os = new RepositoryOutputStream(name, CCNLibrary.getLibrary()); os.write(txt.getBytes(UTF8)); os.close(); } @Test public void readWrite() throws Exception { EnumeratedNameList l = new EnumeratedNameList(ContentName.fromNative(base), null); SortedSet<ContentName> r = l.getNewData(); Assert.assertNotNull(r); Assert.assertEquals(1, r.size()); Assert.assertEquals(file_name.getBytes(UTF8), r.first().lastComponent()); } }
package test.ccn.security.access; import java.util.SortedSet; import junit.framework.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.parc.ccn.data.ContentName; import com.parc.ccn.library.CCNLibrary; import com.parc.ccn.library.EnumeratedNameList; import com.parc.ccn.library.io.repo.RepositoryOutputStream; public class SampleTestRepo { static final String base = "/parc.com/csl/ccn/repositories"; static final String file_name = "simon.txt"; static final String txt = "Sample text file from Simon."; static final String UTF8 = "UTF-8"; @BeforeClass public static void setUpBeforeClass() throws Exception { ContentName name = ContentName.fromNative(base + "/" + file_name); RepositoryOutputStream os = new RepositoryOutputStream(name, CCNLibrary.getLibrary()); os.write(txt.getBytes(UTF8)); os.close(); } @Test public void readWrite() throws Exception { EnumeratedNameList l = new EnumeratedNameList(ContentName.fromNative(base), null); SortedSet<ContentName> r = l.getNewData(); Assert.assertNotNull(r); Assert.assertEquals(1, r.size()); Assert.assertEquals(file_name.getBytes(UTF8), r.first().lastComponent()); } }
Use the logic from sdc-login for zone lookup
/* * pushit push hooks * * Right now, only contains functions that are run in variable expansion */ var child_process = require('child_process'); var util = require('util'); var common = require('./common'); var debug = common.debug; var verbose = common.verbose; /* * Runs an ssh command on the remote host */ function ssh(state, cmd, callback) { var cmd = util.format("ssh %s@%s '%s'", state.config.username, state.config.hostname, cmd); verbose("# %s", cmd); child_process.exec(cmd, function (err, stdout, stderr) { if (err) { return callback(err); } return callback(null, { stdout: stdout, stderr: stderr }); }); } /* * Gets the zone root based on its alias */ function getZoneRoot(state, zoneAlias, callback) { debug("====> getZoneRoot start"); var cmd = util.format( "vmadm get $(vmadm lookup -1 tags.smartdc_role=~^%s) | json zonepath", zoneAlias); ssh(state, cmd, function(err, res) { if (err) { return callback(err); } var stdout = res.stdout.replace("\n", ""); verbose(" %s", stdout); return callback(null, stdout); }); } module.exports = { getZoneRoot: getZoneRoot, debug: debug }
/* * pushit push hooks * * Right now, only contains functions that are run in variable expansion */ var child_process = require('child_process'); var util = require('util'); var common = require('./common'); var debug = common.debug; var verbose = common.verbose; /* * Runs an ssh command on the remote host */ function ssh(state, cmd, callback) { var cmd = util.format("ssh %s@%s '%s'", state.config.username, state.config.hostname, cmd); verbose("# %s", cmd); child_process.exec(cmd, function (err, stdout, stderr) { if (err) { return callback(err); } return callback(null, { stdout: stdout, stderr: stderr }); }); } /* * Gets the zone root based on its alias */ function getZoneRoot(state, zoneAlias, callback) { debug("====> getZoneRoot start"); var cmd = util.format( "vmadm get $(vmadm lookup -1 alias=%s0) | json zonepath", zoneAlias); ssh(state, cmd, function(err, res) { if (err) { return callback(err); } var stdout = res.stdout.replace("\n", ""); verbose(" %s", stdout); return callback(null, stdout); }); } module.exports = { getZoneRoot: getZoneRoot, debug: debug }
Change the Date format to String
package com.ice.av.sample.entity; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Info { @SuppressWarnings("unused") private static final Logger log = LoggerFactory.getLogger(Info.class); private String info = "This is a test info..."; public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } public String getTimestamp() { return new Date().toString(); } public void setTimestamp(String timestamp) { } @Override public String toString() { return "Info [info=" + info + "]"; } }
package com.ice.av.sample.entity; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Info { @SuppressWarnings("unused") private static final Logger log = LoggerFactory.getLogger(Info.class); private String info = "This is a test info..."; public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } public Date getTimestamp() { return new Date(); } public void setTimestamp(Date timestamp) { } @Override public String toString() { return "Info [info=" + info + "]"; } }
Change Autoload Third Party to Global Class
<?php function ThirdPartyAutoload($class) { $class_array = explode('\\', $class); //if (count($class_array)>1) { //if ($class_array[0] == 'ThirdParty') { if (isset($class_array[1])) $file_load = \Kecik\Config::get('path.third_party').'/'.$class_array[0].'/'.$class_array[1].'.php'; else $file_load = \Kecik\Config::get('path.third_party').'/'.$class_array[0].'/'.$class_array[0].'.php'; if (file_exists($file_load)) { include_once $file_load; } else { $file_load = \Kecik\Config::get('path.third_party').'/'.$class_array[0].'.php'; if (file_exists($file_load)) include_once $file_load; } //} //} } spl_autoload_register('ThirdPartyAutoload');
<?php class ThirdParty { public static function init() { spl_autoload_register(array(self, '::autoload'), true, true); } public static function autoload($class) { $class_array = explode('\\', $class); if (count($class_array)>1) { if ($class_array[0] == 'ThirdParty') { $file_load = Config::get('path.third_party').'/'.$class_array[1].'/'.$class_array[2].'.php'; if (file_exists($file_load)) { $namespace = "<?php\nnamespace ThirdParty\\$class_array[1];\n?>\n"; $thirdpartyfile = fopen($file_load, "r"); $thirdpartyclass = fread($thirdpartyfile,filesize($file_load)); fclose($thirdpartyfile); eval("?>$namespace.$thirdpartyclass"); //include_once $file_load; } } } } }
Add content type text/html to response
import falcon import template def get_paragraphs(pathname: str) -> list: result = [] with open(pathname) as f: for line in f.readlines(): if line != '\n': result.append(line[:-1]) return result class BooksResource: def on_get(self, req, resp): resp.status = falcon.HTTP_200 resp.content_type = 'text/html' paragraphs = get_paragraphs('/home/sanchopanca/Documents/thunder.txt') resp.body = template.render_template('book.html', paragraphs=paragraphs) app = falcon.API() books = BooksResource() app.add_route('/books', books) if __name__ == '__main__': paragraphs = get_paragraphs('/home/sanchopanca/Documents/thunder.txt') print(paragraphs)
import falcon import template def get_paragraphs(pathname: str) -> list: result = [] with open(pathname) as f: for line in f.readlines(): if line != '\n': result.append(line[:-1]) return result class BooksResource: def on_get(self, req, resp): resp.status = falcon.HTTP_200 paragraphs = get_paragraphs('/home/sanchopanca/Documents/thunder.txt') resp.body = template.render_template('book.html', paragraphs=paragraphs) app = falcon.API() books = BooksResource() app.add_route('/books', books) if __name__ == '__main__': paragraphs = get_paragraphs('/home/sanchopanca/Documents/thunder.txt') print(paragraphs)
Fix the missing getter for proper Jackson desserialization of truffle compilation result
package org.adridadou.ethereum.propeller.solidity; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.adridadou.ethereum.propeller.solidity.abi.AbiEntry; import org.adridadou.ethereum.propeller.values.EthData; @JsonIgnoreProperties(ignoreUnknown = true) public class TruffleSolidityContractDetails implements SolidityContractDetails { private final List<AbiEntry> abi; private final String bytecode; private final String metadata; public TruffleSolidityContractDetails() { this(null, null, null); } public TruffleSolidityContractDetails(List<AbiEntry> abi, String bytecode, String metadata) { this.abi = abi; this.bytecode = bytecode; this.metadata = metadata; } @Override public List<AbiEntry> getAbi() { return abi; } @Override public String getMetadata() { return metadata; } @Override public EthData getBinary() { return EthData.of(bytecode); } public String getBytecode() { return bytecode; } }
package org.adridadou.ethereum.propeller.solidity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.adridadou.ethereum.propeller.solidity.abi.AbiEntry; import org.adridadou.ethereum.propeller.values.EthData; import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) public class TruffleSolidityContractDetails implements SolidityContractDetails { private final List<AbiEntry> abi; private final String bytecode; private final String metadata; public TruffleSolidityContractDetails() { this(null, null, null); } public TruffleSolidityContractDetails(List<AbiEntry> abi, String bytecode, String metadata) { this.abi = abi; this.bytecode = bytecode; this.metadata = metadata; } @Override public List<AbiEntry> getAbi() { return abi; } @Override public String getMetadata() { return metadata; } @Override public EthData getBinary() { return EthData.of(bytecode); } }
Set self.build_flow before calling the super __init__ method
from cumulusci.core.config import YamlGlobalConfig from cumulusci.core.config import YamlProjectConfig class MrbelvedereProjectConfig(YamlProjectConfig): def __init__(self, global_config_obj, build_flow): self.build_flow = build_flow super(MrbelvedereProjectConfig, self).__init__(global_config_obj) @property def config_project_local_path(self): """ mrbelvedere never uses the local path """ return @property def repo_root(self): return self.build_flow.build_dir @property def repo_name(self): return self.build_flow.build.repo.name @property def repo_url(self): return self.build_flow.build.repo.url @property def repo_owner(self): return self.build_flow.build.repo.url.split('/')[-2] @property def repo_branch(self): return self.build_flow.build.branch.name @property def repo_commit(self): return self.build_flow.build.commit class MrbelvedereGlobalConfig(YamlGlobalConfig): project_config_class = MrbelvedereProjectConfig def get_project_config(self, build_flow): return self.project_config_class(self, build_flow)
from cumulusci.core.config import YamlGlobalConfig from cumulusci.core.config import YamlProjectConfig class MrbelvedereProjectConfig(YamlProjectConfig): def __init__(self, global_config_obj, build_flow): super(MrbelvedereProjectConfig, self).__init__(global_config_obj) self.build_flow = build_flow @property def config_project_local_path(self): """ mrbelvedere never uses the local path """ return @property def repo_root(self): return self.build_flow.build_dir @property def repo_name(self): return self.build_flow.build.repo.name @property def repo_url(self): return self.build_flow.build.repo.url @property def repo_owner(self): return self.build_flow.build.repo.url.split('/')[-2] @property def repo_branch(self): return self.build_flow.build.branch.name @property def repo_commit(self): return self.build_flow.build.commit class MrbelvedereGlobalConfig(YamlGlobalConfig): project_config_class = MrbelvedereProjectConfig def get_project_config(self, build_flow): return self.project_config_class(self, build_flow)
Add language support in assets helper
<?php class Kwf_View_Helper_Assets { public function assets($assetsPackage, $language = null, $subroot = null) { if (!$language) $language = Kwf_Trl::getInstance()->getTargetLanguage(); $ev = new Kwf_Events_Event_CreateAssetsPackageUrls(get_class($this), $assetsPackage, $subroot); Kwf_Events_Dispatcher::fireEvent($ev); $prefix = $ev->prefix; $indent = str_repeat(' ', 8); $ret = ''; $c = file_get_contents('build/assets/'.$assetsPackage.'.'.$language.'.html'); $c = preg_replace('#</?head>#', '', $c); $c = str_replace('/assets/build/./', '/assets/build/', $c); $ret .= $c; return $ret; } }
<?php class Kwf_View_Helper_Assets { public function assets($assetsPackage, $language = null, $subroot = null) { if (!$language) $language = Kwf_Trl::getInstance()->getTargetLanguage(); $ev = new Kwf_Events_Event_CreateAssetsPackageUrls(get_class($this), $assetsPackage, $subroot); Kwf_Events_Dispatcher::fireEvent($ev); $prefix = $ev->prefix; $indent = str_repeat(' ', 8); $ret = ''; $c = file_get_contents('build/assets/'.$assetsPackage.'.html'); $c = preg_replace('#</?head>#', '', $c); $c = str_replace('/assets/build/./', '/assets/build/', $c); $ret .= $c; return $ret; } }
Use .state instead of .is_online to keep internal state
import glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] def property_changed(_, message): if message.get_member() == "PropertyChanged": _, state = message.get_args_list() if state == 'online' and detector.state == 'offline': logger.info('network state change: online' ) detector.emit('up') detector.state = 'online' elif state == 'idle': logger.info('network state change: offline' ) detector.emit('down') detector.state = 'online' detector = EventEmitter() DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() bus.add_match_string_non_blocking("interface='net.connman.Manager'") bus.add_message_filter(property_changed) manager = dbus.Interface(bus.get_object('net.connman', "/"), 'net.connman.Manager') def is_online(): properties = manager.GetProperties() if properties['State'] == 'online': return True return False def run(): mainloop = glib.MainLoop() mainloop.run() detector.run = run detector.is_online = is_online detector.state = 'online' if is_online() else 'offline'
import glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] def property_changed(_, message): if message.get_member() == "PropertyChanged": _, state = message.get_args_list() if state == 'online' and not detector.is_online: logger.info('network state change: online' ) detector.emit('up') detector.is_online = True elif state == 'idle': logger.info('network state change: offline' ) detector.emit('down') detector.is_online = False detector = EventEmitter() detector.is_online = is_online() DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() bus.add_match_string_non_blocking("interface='net.connman.Manager'") bus.add_message_filter(property_changed) manager = dbus.Interface(bus.get_object('net.connman', "/"), 'net.connman.Manager') def is_online(): properties = manager.GetProperties() if properties['State'] == 'online': return True return False def run(): mainloop = glib.MainLoop() mainloop.run() detector.run = run detector.is_online = is_online
Change the way we retrieve statistics
'use strict'; const config = require(`${__dirname}/../config/init`); /** * makeAllRowRequestBody(str) * @param string field Field to query parameters from. * @param string from Date to query results from. * @param string to Date to query results to. * @return object Request to be performed body. */ exports.makeAllRowRequest = function make(field, from, to, response) { config.client.search({ index: config.index, type: config.type, body: { size: 0, query: { bool: { must: [ { range: { "@timestamp": { from, to }, }, }, ], }, }, aggs: { results: { terms: { size: 10, field, }, }, }, }, }).then((body) => { response.json({ success: true, hits: body.aggregations.results.buckets }); }, (error) => { response.json({ success: false, message: error.message }); }); };
'use strict'; const config = require(`${__dirname}/../config/init`); /** * makeAllRowRequestBody(str) * @param string field Field to query parameters from. * @param string from Date to query results from. * @param string to Date to query results to. * @return object Request to be performed body. */ exports.makeAllRowRequest = function make(field, from, to, response) { config.client.search({ index: config.index, type: config.type, body: { size: 0, query: { bool: { must: [ { range: { "@timestamp": { from, to }, }, }, ], }, }, aggs: { results: { terms: { size: 10, field, }, }, }, }, }).then((body) => { response.json({ success: true, hits: body.aggregations.results.buckets }); }, (error) => { response.json({ success: false, message: error.message }); }); };
Use mv command instead of os.Rename because avoid invalid cross-device link error.
package main import ( "os" "os/exec" "path" "path/filepath" ) func newFileStorage(params *params) storager { return &fileStorage{params} } type fileStorage struct { params *params } func (f fileStorage) isExist() bool { if _, err := os.Stat(f.pathByParams()); err != nil { return false } return true } func (f fileStorage) save(from string) error { if err := os.MkdirAll(f.pathByParams(), 0755); err != nil { return err } return exec.Command("mv", from, filepath.Join(f.pathByParams(), path.Base(from))).Run() } func (f fileStorage) pathByParams() string { return filepath.Join( storageDir, f.params.remote, f.params.owner(), f.params.repo, f.params.goos, f.params.goarch, f.params.version, ) } func (f fileStorage) get(file string) (string, error) { return filepath.Join(f.pathByParams(), file), nil }
package main import ( "os" "path" "path/filepath" ) func newFileStorage(params *params) storager { return &fileStorage{params} } type fileStorage struct { params *params } func (f fileStorage) isExist() bool { if _, err := os.Stat(f.pathByParams()); err != nil { return false } return true } func (f fileStorage) save(from string) error { if err := os.MkdirAll(f.pathByParams(), 0755); err != nil { return err } return os.Rename(from, filepath.Join(f.pathByParams(), path.Base(from))) } func (f fileStorage) pathByParams() string { return filepath.Join( storageDir, f.params.remote, f.params.owner(), f.params.repo, f.params.goos, f.params.goarch, f.params.version, ) } func (f fileStorage) get(file string) (string, error) { return filepath.Join(f.pathByParams(), file), nil }
Fix pluralisation for missing keys
import i18next from 'i18next' import t from './t' // Formats a pluralized string const tPlural = (messages, options = {}) => { if (!Number.isInteger(options.count)) { console.error('[react-globe] tPlural requires a integer "count" option') return null } if (!messages.one || !messages.many) { console.error('[react-globe] tPlural requires a "one" and "many" strings') return null } if (options.count === 0) { return handleZero(messages, options) } // Manually generate english pluralisation based on gettext style if (i18next.language === 'en' || !i18next.exists(messages.one, options)) { return englishPlural(messages, options) } // The translation function figures out plurals for us return t(messages.one, options) } const handleZero = (messages, options) => { // When the language is no english, fallback to the 'one' string, // because the "t" translation function will pick the correct plural that way var fallback = i18next.language === 'en' || !i18next.exists(messages.one, options) ? messages.many : messages.one return t(messages.zero || fallback, options) } const englishPlural = (messages, options) => { if (options.count === 1) { return t(messages.one, options) } return t(messages.many, options) } export default tPlural
import i18next from 'i18next' import t from './t' // Formats a pluralized string const tPlural = (messages, options = {}) => { if (!Number.isInteger(options.count)) { console.error('[react-globe] tPlural requires a integer "count" option') return null } if (!messages.one || !messages.many) { console.error('[react-globe] tPlural requires a "one" and "many" strings') return null } // Manually generate english pluralisation based on gettext style if (i18next.language === 'en' || !i18next.exists(messages.one)) { return englishPlural(messages, options) } // Return an extra string for 0 counts if (options.count === 0) { return t(messages.zero || messages.one, options) } // The translation function figures out plurals for us return t(messages.one, options) } const englishPlural = (messages, options) => { if (options.count === 0) { return t(messages.zero || messages.many, options) } if (options.count === 1) { return t(messages.one, options) } return t(messages.many, options) } export default tPlural
Use copy instead of create
/* Example usage: var A = Class(function() { var defaults = { foo: 'cat', bar: 'dum' } this.init = function(opts) { opts = std.extend(opts, defaults) this._foo = opts.foo this._bar = opts.bar } this.getFoo = function() { return this._foo } this.getBar = function() { return this._bar } }) var a = new A({ bar:'sim' }) a.getFoo() == 'cat' a.getBar() == 'sim' */ var copy = require('std/copy') module.exports = function extend(target, extendWith) { target = target ? copy(target) : {} for (var key in extendWith) { if (typeof target[key] != 'undefined') { continue } target[key] = extendWith[key] } return target }
/* Example usage: var A = Class(function() { var defaults = { foo: 'cat', bar: 'dum' } this.init = function(opts) { opts = std.extend(opts, defaults) this._foo = opts.foo this._bar = opts.bar } this.getFoo = function() { return this._foo } this.getBar = function() { return this._bar } }) var a = new A({ bar:'sim' }) a.getFoo() == 'cat' a.getBar() == 'sim' */ var create = require('std/create') module.exports = function extend(target, extendWith) { target = target ? create(target) : {} for (var key in extendWith) { if (typeof target[key] != 'undefined') { continue } target[key] = extendWith[key] } return target }
Revert "Tweaked with header a bit" This reverts commit b00daf557e643f477109164091778effed450b10.
<div class="bluewrap ue-header"> <div class="container" style="text-align: center;"> <div class="row"> <h1> <span class="med-font" style="font-size: 72px;"><?php bloginfo("name") ?></span> <br /> <?php bloginfo("description") ?> </h1> <a class="btn btn-default btn-lg" href="downloads"><i class="glyphicon glyphicon-download-alt"></i>&nbsp;&nbsp;Download</a> <div class="spacer"></div> </div> </div> </div> <?php while (have_posts()) : the_post(); ?> <?php remove_filter( 'the_content', 'wpautop' ); ?> <?php the_content(); ?> <?php wp_link_pages(array('before' => '<nav class="pagination">', 'after' => '</nav>')); ?> <?php endwhile; ?>
<div class="bluewrap ue-header"> <div class="container" style="text-align: center;"> <div class="row"> <div> <h1 class="med-font" style="font-size: 72px;"> <?php bloginfo("name") ?> <br /> <small><?php bloginfo("description") ?></small> </h1> </div> <a class="btn btn-default btn-lg" href="downloads"><i class="glyphicon glyphicon-download-alt"></i>&nbsp;&nbsp;Download</a> <div class="spacer"></div> </div> </div> </div> <?php while (have_posts()) : the_post(); ?> <?php remove_filter( 'the_content', 'wpautop' ); ?> <?php the_content(); ?> <?php wp_link_pages(array('before' => '<nav class="pagination">', 'after' => '</nav>')); ?> <?php endwhile; ?>
Reset landing page state only upon logout This change prevents the signup and login page analytics events to be fired erroneously. [Finishes #133219321]
'use strict'; import { LOGOUT } from 'app/actions/auth'; import { SET_PAGE_LOGIN_STATE, SET_PAGE_SIGNUP_STATE, SET_OVERRIDE_FRAME, CLEAR_OVERRIDE_FRAME } from 'app/actions/landingPage'; import { initialLPState } from 'app/constants'; export default function landingPageState(state = initialLPState, action) { switch (action.type) { case SET_PAGE_LOGIN_STATE: return { ...state, frame: 'login' }; case SET_PAGE_SIGNUP_STATE: return { ...state, frame: 'signup' }; case SET_OVERRIDE_FRAME: return { ...state, overrideFrame: action.frame }; case CLEAR_OVERRIDE_FRAME: case LOGOUT: return initialLPState; } return state; }
'use strict'; import { API_LOGIN_SUCCESS, API_SIGNUP_SUCCESS } from 'app/actions/auth'; import { SET_PAGE_LOGIN_STATE, SET_PAGE_SIGNUP_STATE, SET_OVERRIDE_FRAME, CLEAR_OVERRIDE_FRAME } from 'app/actions/landingPage'; import { initialLPState } from 'app/constants'; export default function landingPageState(state = initialLPState, action) { switch (action.type) { case SET_PAGE_LOGIN_STATE: return { ...state, frame: 'login' }; case SET_PAGE_SIGNUP_STATE: return { ...state, frame: 'signup' }; case SET_OVERRIDE_FRAME: return { ...state, overrideFrame: action.frame }; case CLEAR_OVERRIDE_FRAME: case API_LOGIN_SUCCESS: case API_SIGNUP_SUCCESS: return initialLPState; } return state; }
Add test for certain required locale keys
import test from "ava"; const fs = require("fs"); const path = require("path"); const localesPath = path.join(__dirname, "..", "locales"); const filenameRegex = /^[a-z][a-z](_[A-Z]+)*\.json$/; test("locale files are valid", t => { const filenames = fs.readdirSync(localesPath); filenames.forEach(filename => { /* test filename */ if (!filenameRegex.test(filename)) t.fail(`locale filename "${filename}" is invalid`); /* test file json */ const content = fs.readFileSync(path.join(localesPath, filename), { encoding: "utf8" }); let json; try { json = JSON.parse(content); } catch (e) { t.fail(`locale file "${filename}" contains invalid JSON`); } /* test file contents */ t.truthy(json["__redirect__"] || json["__locale_name__"], `locale file "${filename}" is missing both "__locale_name__" and "__redirect__"`); }); t.pass(); // if nothing has failed so far });
import test from "ava"; const fs = require("fs"); const path = require("path"); const localesPath = path.join(__dirname, "..", "locales"); const filenameRegex = /^[a-z][a-z](_[A-Z]+)*\.json$/; test("locale files are valid", t => { const filenames = fs.readdirSync(localesPath); filenames.forEach(filename => { /* test filename */ if (!filenameRegex.test(filename)) t.fail(`locale filename "${filename}" is invalid`); /* test file json */ const content = fs.readFileSync(path.join(localesPath, filename), { encoding: "utf8" }); let valid = false; try { JSON.parse(content); valid = true; } catch (e) {} if (!valid) t.fail(`locale file "${filename}" is invalid`); }); t.pass(); // if nothing has failed so far });
Make allowSearch default to true
(function() { 'use strict'; var buttons = { root: 'Home', edit: 'Edit', select: 'Select', deselect: 'Deselect', goToSubitems: 'Go to subitems', addSubitems: 'Add subitems', addNode: 'Add node', remove: 'Delete', done: 'Done', search: '&rsaquo;', searchClear: '&times;', showSelected: 'Show selected', hideSelected: 'Hide selected', deselectAll: 'Deselect all', backToList: 'Back to list', move: 'Move', modalSelect: 'Select', up: 'Up a level', searchText: 'Search for an item by title' }; var nodeTemplate = { id: '_id', nodes: 'nodes', title: 'title' }; var defaultOptions = { allowSelect: true, allowSearch: true, canEdit: false, inline: false, buttons: {}, limit: 0 }; var sortableOptions = { sort: true, handle: '.sequoia-move-handle', ghostClass: 'as-sortable-dragging' }; angular.module('ngSequoia') .constant('BUTTONS', buttons) .constant('NODE_TEMPLATE', nodeTemplate) .constant('DEFAULT_OPTIONS', defaultOptions) .constant('SORTABLE_OPTIONS', sortableOptions); })();
(function() { 'use strict'; var buttons = { root: 'Home', edit: 'Edit', select: 'Select', deselect: 'Deselect', goToSubitems: 'Go to subitems', addSubitems: 'Add subitems', addNode: 'Add node', remove: 'Delete', done: 'Done', search: '&rsaquo;', searchClear: '&times;', showSelected: 'Show selected', hideSelected: 'Hide selected', deselectAll: 'Deselect all', backToList: 'Back to list', move: 'Move', modalSelect: 'Select', up: 'Up a level', searchText: 'Search for an item by title' }; var nodeTemplate = { id: '_id', nodes: 'nodes', title: 'title' }; var defaultOptions = { allowSelect: true, allowSearch: false, canEdit: false, inline: false, buttons: {}, limit: 0 }; var sortableOptions = { sort: true, handle: '.sequoia-move-handle', ghostClass: 'as-sortable-dragging' }; angular.module('ngSequoia') .constant('BUTTONS', buttons) .constant('NODE_TEMPLATE', nodeTemplate) .constant('DEFAULT_OPTIONS', defaultOptions) .constant('SORTABLE_OPTIONS', sortableOptions); })();
Reorganize imports (and bump version)
version_info = (0, 21, 0) __version__ = '.'.join(map(str, version_info)) try: from . import greenpool from . import queue from .hubs.trampoline import gyield from .greenthread import sleep, spawn, spawn_n, spawn_after, kill from .greenpool import GreenPool, GreenPile from .timeout import Timeout, with_timeout from .patcher import import_patched, monkey_patch from .server import serve, listen, connect, StopServe, wrap_ssl import pyuv_cffi # only to compile the shared library before monkey-patching except ImportError as e: # This is to make Debian packaging easier, it ignores import errors of greenlet so that the # packager can still at least access the version. Also this makes easy_install a little quieter if 'greenlet' not in str(e): # any other exception should be printed import traceback traceback.print_exc()
version_info = (0, 20, 0) __version__ = '.'.join(map(str, version_info)) try: from . import greenthread from . import greenpool from . import queue from . import timeout from . import patcher from . import server from .hubs.trampoline import gyield import greenlet import pyuv_cffi # only to compile the shared library before monkey-patching sleep = greenthread.sleep spawn = greenthread.spawn spawn_n = greenthread.spawn_n spawn_after = greenthread.spawn_after kill = greenthread.kill Timeout = timeout.Timeout with_timeout = timeout.with_timeout GreenPool = greenpool.GreenPool GreenPile = greenpool.GreenPile Queue = queue.Queue import_patched = patcher.import_patched monkey_patch = patcher.monkey_patch serve = server.serve listen = server.listen connect = server.connect StopServe = server.StopServe wrap_ssl = server.wrap_ssl getcurrent = greenlet.greenlet.getcurrent except ImportError as e: # This is to make Debian packaging easier, it ignores import errors of greenlet so that the # packager can still at least access the version. Also this makes easy_install a little quieter if 'greenlet' not in str(e): # any other exception should be printed import traceback traceback.print_exc()
Revert "Updated docstring for the file (mostly to diagnose/solve a git branch/merge problem)" This reverts commit 3bcc40305193f3a46de63f4345812c9c2ee4c27f [formerly e2fe152ba58cfa853637bc5bd805adf0ae9617eb] [formerly 8e549c3bfb3650f08aca2ba204d2904e53aa4ab4]. Former-commit-id: e783ac4d5946403a9d608fe9dffa42212796b402 Former-commit-id: abafc2efec64a1e360594c18b203daa4ea0f7ced
#! /usr/bin/env python # -*- coding: utf-8 -*- # Author: CEF PNM Team # License: TBD # Copyright (c) 2012 #from __future__ import print_function """ module __GenericPhysics__: Base class to define pore scale physics ================================================================== .. warning:: The classes of this module should be loaded through the 'PHYS.__init__.py' file. """ import OpenPNM import scipy as sp import numpy as np class GenericPhysics(OpenPNM.BAS.OpenPNMbase): r""" """ def __init__(self,net=OpenPNM.NET.GenericNetwork,**kwords): r""" Initialize """ super(GenericPhysics,self).__init__(**kwords) self.indent = "" self._logger.debug("Construct class") self._net = net def Washburn(self): self._net.throat_properties['Pc_entry'] = -4*0.072*np.cos(np.radians(105))/self._net.throat_properties['diameter'] if __name__ =="__main__": test = GenericPhysics(loggername="TestGenericPhys") test.run()
#! /usr/bin/env python # -*- coding: utf-8 -*- # Author: CEF PNM Team # License: TBD # Copyright (c) 2012 #from __future__ import print_function """ module __GenericPhysics__: Base class to define pore scale physics ================================================================== .. warning:: The classes of this module should be loaded through the 'PHYS.__init__.py' file. """ import OpenPNM import scipy as sp import numpy as np class GenericPhysics(OpenPNM.BAS.OpenPNMbase): r""" """ def __init__(self,net=OpenPNM.NET.GenericNetwork,**kwords): r""" Initialize """ super(GenericPhysics,self).__init__(**kwords) self.indent = "" self._logger.debug("Construct class") self._net = net def Washburn(self): r''' this uses the Washburn equation to relate pore size to entry pressure ''' self._net.throat_properties['Pc_entry'] = -4*0.072*np.cos(np.radians(105))/self._net.throat_properties['diameter'] if __name__ =="__main__": test = GenericPhysics(loggername="TestGenericPhys") test.run()
Fix 401 error for requests that require authentication
import base64 from .models import Device class BasicAuthRemote(object): def __init__(self, get_response): self.get_response = get_response def get_user_token(self, email, token): try: device = Device.objects.get(token=token) if device.user.email != email: return None return user except: return None def __call__(self, request): if not request.user.is_authenticated and 'HTTP_AUTHORIZATION' in request.META: auth = request.META['HTTP_AUTHORIZATION'].split() if len(auth) == 2 and auth[0].lower() == "basic": email, token = base64.b64decode(auth[1]).decode('utf-8').split(':') user = self.get_user_token(email, token) if user: request.user = user return self.get_response(request)
import base64 from .models import Device class BasicAuthRemote(object): def __init__(self, get_response): self.get_response = get_response def get_user_token(self, email, token): try: device = Device.objects.get(token=token).select_related('user') if device.user.email is not email: return None return user except: return None def __call__(self, request): if not request.user.is_authenticated and 'HTTP_AUTHORIZATION' in request.META: auth = request.META['HTTP_AUTHORIZATION'].split() if len(auth) == 2 and auth[0].lower() == "basic": email, token = base64.b64decode(auth[1]).decode('utf-8').split(':') user = self.get_user_token(email, token) if user: request.user = user return self.get_response(request)
Allow passing User directly to get_change_metadata
import sys from datetime import datetime from random import randint def get_client_ip(request): x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR") if x_forwarded_for: ip = x_forwarded_for.split(",")[-1].strip() else: ip = request.META.get("REMOTE_ADDR") return ip def create_version_id(): """Generate a random ID to use to identify a person version""" return "{:016x}".format(randint(0, sys.maxsize)) def get_current_timestamp(): return datetime.utcnow().isoformat() def get_change_metadata(request, information_source, user=None): """ :type user: django.contrib.auth.models.User """ result = { "information_source": information_source, "version_id": create_version_id(), "timestamp": get_current_timestamp(), } if request is not None: result["username"] = request.user.username if user: result["username"] = user.username return result
import sys from datetime import datetime from random import randint def get_client_ip(request): x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR") if x_forwarded_for: ip = x_forwarded_for.split(",")[-1].strip() else: ip = request.META.get("REMOTE_ADDR") return ip def create_version_id(): """Generate a random ID to use to identify a person version""" return "{:016x}".format(randint(0, sys.maxsize)) def get_current_timestamp(): return datetime.utcnow().isoformat() def get_change_metadata(request, information_source): result = { "information_source": information_source, "version_id": create_version_id(), "timestamp": get_current_timestamp(), } if request is not None: result["username"] = request.user.username return result
Set default application name to folder name Fixes #1
'use strict'; var util = require('util'); var path = require('path'); var yeoman = require('yeoman-generator'); var AppengineGenerator = module.exports = function AppengineGenerator(args, options, config) { yeoman.generators.Base.apply(this, arguments); this.args = args; this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json'))); }; util.inherits(AppengineGenerator, yeoman.generators.Base); AppengineGenerator.prototype.askFor = function askFor() { var cb = this.async(); this.appId = this.args[0] || undefined; var prompts = []; if (this.args[0] === undefined) { prompts.push({ name: 'appId', message: 'What is the application ID?', default: path.basename(process.cwd()) }) } else { this.appId = this.args[0]; } this.prompt(prompts, function (props) { for (var prop in props) { this[prop] = props[prop]; } cb(); }.bind(this)); }; AppengineGenerator.prototype.projectfiles = function projectfiles() { this.copy('editorconfig', '.editorconfig'); }; AppengineGenerator.prototype.AppEngineFiles = function AppEngineFiles() { this.template('app.yaml'); this.copy('index.yaml'); }; AppengineGenerator.prototype.StaticFiles = function StaticFiles() { this.mkdir('assets'); this.directory('assets'); };
'use strict'; var util = require('util'); var path = require('path'); var yeoman = require('yeoman-generator'); var AppengineGenerator = module.exports = function AppengineGenerator(args, options, config) { yeoman.generators.Base.apply(this, arguments); this.args = args; this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json'))); }; util.inherits(AppengineGenerator, yeoman.generators.Base); AppengineGenerator.prototype.askFor = function askFor() { var cb = this.async(); this.appId = this.args[0] || undefined; var prompts = []; if (this.args[0] === undefined) { prompts.push({ name: 'appId', message: 'What is the application ID?', default: 'new-application' }) } else { this.appId = this.args[0]; } this.prompt(prompts, function (props) { for (var prop in props) { this[prop] = props[prop]; } cb(); }.bind(this)); }; AppengineGenerator.prototype.projectfiles = function projectfiles() { this.copy('editorconfig', '.editorconfig'); }; AppengineGenerator.prototype.AppEngineFiles = function AppEngineFiles() { this.template('app.yaml'); this.copy('index.yaml'); }; AppengineGenerator.prototype.StaticFiles = function StaticFiles() { this.mkdir('assets'); this.directory('assets'); };
Add classes to run ./configure
# # Copyright (c) 2004 Specifix, Inc. # All rights reserved # import os import shutil import util class ManualConfigure: def doBuild(self, dir): os.system("cd %s; ./configure %s" % (dir, self.extraflags)) def __init__(self, extraflags=""): self.extraflags = extraflags class Configure: def doBuild(self, dir): os.system("cd %s; ./configure --prefix=/usr --sysconfdir=/etc %s" % (dir, self.extraflags)) def __init__(self, extraflags=""): self.extraflags = extraflags class Make: def doBuild(self, dir): os.system("cd %s; make" % dir) class MakeInstall: def doInstall(self, dir, root): os.system("cd %s; make %s=%s install" % (dir, self.rootVar, root)) def __init__(self, rootVar = "DESTDIR"): self.rootVar = rootVar class InstallFile: def doInstall(self, dir, root): dest = root + self.toFile util.mkdirChain(os.path.dirname(dest)) shutil.copyfile(self.toFile, dest) os.chmod(dest, self.mode) def __init__(self, fromFile, toFile, perms = 0644): self.toFile = toFile self.file = fromFile self.mode = perms
# # Copyright (c) 2004 Specifix, Inc. # All rights reserved # import os import shutil import util class Make: def doBuild(self, dir): os.system("cd %s; make" % dir) class MakeInstall: def doInstall(self, dir, root): os.system("cd %s; make %s=%s install" % (dir, self.rootVar, root)) def __init__(self, rootVar = "DESTDIR"): self.rootVar = rootVar class InstallFile: def doInstall(self, dir, root): dest = root + self.toFile util.mkdirChain(os.path.dirname(dest)) shutil.copyfile(self.toFile, dest) os.chmod(dest, self.mode) def __init__(self, fromFile, toFile, perms = 0644): self.toFile = toFile self.file = fromFile self.mode = perms
Update with some boilerplate comment header
package org.ensembl.healthcheck.testcase.funcgen; import java.sql.Connection; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.ReportManager; /** * @author mnuhn * * Abstract class providing method "getSpeciesAssemblyDataFileBasePath". This * can be used to write checks for external files. * */ public abstract class AbstractExternalFileUsingTestcase extends AbstractCoreDatabaseUsingTestCase { protected String getSpeciesAssemblyDataFileBasePath(DatabaseRegistryEntry dbre) { Connection coreConnection = getCoreDb(dbre).getConnection(); String productionName = getProductionName(coreConnection); String assemblyName = getAssembly(coreConnection); String dbFileRootDir = getDataFileBasePath(); if (dbFileRootDir.equals("")) { ReportManager.problem(this, dbre.getConnection(), "datafile_base_path has not been set!"); } String speciesAssemblyDataFileBasePath = dbFileRootDir + "/" + productionName + "/" + assemblyName; return speciesAssemblyDataFileBasePath; } }
package org.ensembl.healthcheck.testcase.funcgen; import java.sql.Connection; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.ReportManager; public abstract class AbstractExternalFileUsingTestcase extends AbstractCoreDatabaseUsingTestCase { protected String getSpeciesAssemblyDataFileBasePath(DatabaseRegistryEntry dbre) { Connection coreConnection = getCoreDb(dbre).getConnection(); String productionName = getProductionName(coreConnection); String assemblyName = getAssembly(coreConnection); String dbFileRootDir = getDataFileBasePath(); if (dbFileRootDir.equals("")) { ReportManager.problem(this, dbre.getConnection(), "datafile_base_path has not been set!"); } String speciesAssemblyDataFileBasePath = dbFileRootDir + "/" + productionName + "/" + assemblyName; return speciesAssemblyDataFileBasePath; } }
Improve comments in example 2
package main import ( "fmt" sci "github.com/samuell/scipipe" ) func main() { // Init barReplacer task barReplacer := sci.Sh("sed 's/foo/bar/g' {i:foo2} > {o:bar}") // Init function for generating output file pattern barReplacer.OutPathFuncs["bar"] = func() string { return barReplacer.GetInPath("foo2") + ".bar" } // Set up tasks for execution barReplacer.Init() // Manually send file targets on the inport of barReplacer for _, name := range []string{"foo1", "foo2", "foo3"} { barReplacer.InPorts["foo2"] <- sci.NewFileTarget(name + ".txt") } // We have to manually close the inport as well here, to // signal that we are done sending targets (the tasks outport will // then automatically be closed as well) close(barReplacer.InPorts["foo2"]) for f := range barReplacer.OutPorts["bar"] { fmt.Println("Finished processing file", f.GetPath(), "...") } }
package main import ( "fmt" sci "github.com/samuell/scipipe" ) func main() { // Init barReplacer task barReplacer := sci.Sh("sed 's/foo/bar/g' {i:foo2} > {o:bar}") // Init function for generating output file pattern barReplacer.OutPathFuncs["bar"] = func() string { return barReplacer.GetInPath("foo2") + ".bar" } // Set up tasks for execution barReplacer.Init() // Connect network for _, name := range []string{"foo1", "foo2", "foo3"} { barReplacer.InPorts["foo2"] <- sci.NewFileTarget(name + ".txt") } close(barReplacer.InPorts["foo2"]) for f := range barReplacer.OutPorts["bar"] { fmt.Println("Processed file", f.GetPath(), "...") } }
Test profiles manager filterting method
import json from nose.tools import eq_, raises from mock import MagicMock, patch from buffer.managers.profiles import Profiles from buffer.models.profile import Profile, PATHS mocked_response = { 'name': 'me', 'service': 'twiter', 'id': 1 } def test_profiles_manager_all_method(): ''' Test basic profiles retrieving ''' mocked_api = MagicMock() mocked_api.get.return_value = [{'a':'b'}] with patch('buffer.managers.profiles.Profile') as mocked_profile: mocked_profile.return_value = 1 profiles = Profiles(api=mocked_api).all() eq_(profiles, [1]) mocked_api.get.assert_called_once_with(url=PATHS['GET_PROFILES']) mocked_profile.assert_called_once_with(mocked_api, {'a': 'b'}) def test_profiles_manager_filter_method(): ''' Test basic profiles filtering based on some minimal criteria ''' mocked_api = MagicMock() profiles = Profiles(mocked_api, [{'a':'b'}, {'a': 'c'}]) eq_(profiles.filter(a='b'), [{'a': 'b'}]) def test_profiles_manager_filter_method_empty(): ''' Test basic profiles filtering when the manager is empty ''' mocked_api = MagicMock() mocked_api.get.return_value = [{'a':'b'}, {'a': 'c'}] profiles = Profiles(api=mocked_api) eq_(profiles.filter(a='b'), [Profile(mocked_api, {'a': 'b'})])
import json from nose.tools import eq_, raises from mock import MagicMock, patch from buffer.managers.profiles import Profiles from buffer.models.profile import PATHS mocked_response = { 'name': 'me', 'service': 'twiter', 'id': 1 } def test_profiles_manager_all_method(): ''' Test basic profiles retrieving ''' mocked_api = MagicMock() mocked_api.get.return_value = [{'a':'b'}] with patch('buffer.managers.profiles.Profile') as mocked_profile: mocked_profile.return_value = 1 profiles = Profiles(api=mocked_api).all() eq_(profiles, [1]) mocked_api.get.assert_called_once_with(url=PATHS['GET_PROFILES']) mocked_profile.assert_called_once_with(mocked_api, {'a': 'b'})
Fix bug where supersamples would not run without a supersamples.opt file
var fs = require('fs'); var path = require('path'); var cjson = require('cjson'); var _ = require('lodash'); var data = null; var OPTS_FILE = 'supersamples.opts'; var DEFAULTS = { output: './tmp', renderer: { name: 'html', options: { title: 'API Documentation', baseUrl: 'http://localhost', intro: null, styles: [] } } }; exports.read = function() { if (fs.existsSync(OPTS_FILE) === false) { return DEFAULTS; } try { var opts = cjson.load(OPTS_FILE); return _.defaults(opts, DEFAULTS); } catch (ex) { console.error('Invalid config file: ' + path.resolve('supersamples.opts')); console.error(ex); process.exit(1); } }; exports.get = function() { if (!data) data = exports.read(); return data; };
var fs = require('fs'); var path = require('path'); var cjson = require('cjson'); var _ = require('lodash'); var data = null; var OPTS_FILE = 'supersamples.opts'; var DEFAULTS = { output: './tmp', renderer: { name: 'html', options: { title: 'API Documentation', baseUrl: 'http://localhost', intro: null, styles: [] } } }; exports.read = function() { if (fs.exists(OPTS_FILE) === false) { return DEFAULTS; } try { var opts = cjson.load(OPTS_FILE); return _.defaults(opts, DEFAULTS); } catch (ex) { console.error('Invalid config file: ' + path.resolve('supersamples.opts')); console.error(ex); process.exit(1); } }; exports.get = function() { if (!data) data = exports.read(); return data; };
Add more objects to cache in the service worker.
/** * Created by Alvaro on 18/03/2017. */ // use a cacheName for cache versioning var CACHE_NAME = 'static-v0.0.1'; var urlsToCache = [ './', './js/main.js', './js/build/ObjectivesList.js', './js/vendor/react.min.js', './js/vendor/react-com.min.js' ]; // during the install phase you usually want to cache static assets self.addEventListener('install', function(event) { // once the SW is installed, go ahead and fetch the resources to make this work offline event.waitUntil( caches.open(CACHE_NAME).then(function(cache) { console.log('Opening cache for ' + CACHE_NAME); return cache.addAll(urlsToCache).then(function() { self.skipWaiting(); }); }) ); }); // when the browser fetches a url self.addEventListener('fetch', function(event) { // either respond with the cached object or go ahead and fetch the actual url event.respondWith( caches.match(event.request).then(function(response) { if (response) { // retrieve from cache return response; } // fetch as normal return fetch(event.request); }) ); });
/** * Created by Alvaro on 18/03/2017. */ // use a cacheName for cache versioning var CACHE_NAME = 'static-v1'; var urlsToCache = [ './', './js/main.js' ]; // during the install phase you usually want to cache static assets self.addEventListener('install', function(event) { // once the SW is installed, go ahead and fetch the resources to make this work offline event.waitUntil( caches.open(CACHE_NAME).then(function(cache) { console.log('Opening cache for ' + CACHE_NAME); return cache.addAll(urlsToCache).then(function() { self.skipWaiting(); }); }) ); }); // when the browser fetches a url self.addEventListener('fetch', function(event) { // either respond with the cached object or go ahead and fetch the actual url event.respondWith( caches.match(event.request).then(function(response) { if (response) { // retrieve from cache return response; } // fetch as normal return fetch(event.request); }) ); });
Move back to 0.9.0 for prod PyPi upload
import os from setuptools import setup setup( name='algorithmia', version='0.9.0', description='Algorithmia Python Client', long_description='Algorithmia Python Client is a client library for accessing Algorithmia from python code. This library also gets bundled with any Python algorithms in Algorithmia.', url='http://github.com/algorithmiaio/algorithmia-python', license='MIT', author='Algorithmia', author_email='support@algorithmia.com', packages=['Algorithmia'], include_package_data=True, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Natural Language :: English', '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', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
import os from setuptools import setup setup( name='algorithmia', version='0.9.2', description='Algorithmia Python Client', long_description='Algorithmia Python Client is a client library for accessing Algorithmia from python code. This library also gets bundled with any Python algorithms in Algorithmia.', url='http://github.com/algorithmiaio/algorithmia-python', license='MIT', author='Algorithmia', author_email='support@algorithmia.com', packages=['Algorithmia'], include_package_data=True, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Natural Language :: English', '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', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
Add a couple unittest helpers
package unittest import ( "testing" ) type Any interface{} func Failure(t *testing.T, msg ...Any) { t.Fail() t.Log(msg) } func CheckEqual(t *testing.T, x, y Any) { if x != y { Failure(t, x, "!=", y) } } func CheckNotEqual(t *testing.T, x, y Any) { if x == y { Failure(t, x, "==", y) } } func Check(t *testing.T, x Any) { if x == false { Failure(t, x, "== false") } } func CheckFalse(t *testing.T, x Any) { if x == true { Failure(t, x, "== true") } } func CheckNil(t *testing.T, x Any) { if x == nil { Failure(t, x, "!= nil") } } func CheckNotNil(t *testing.T, x Any) { if x == nil { Failure(t, x, "== nil") } }
package unittest import ( "testing" ) type Any interface{} func Failure(t *testing.T, msg ...Any) { t.Fail() t.Log(msg) } func CheckEqual(t *testing.T, x, y Any) { if x != y { Failure(t, x, "!=", y) } } func CheckNotEqual(t *testing.T, x, y Any) { if x == y { Failure(t, x, "==", y) } } func Check(t *testing.T, x Any) { if x == false { Failure(t, x, "== false") } } func CheckFalse(t *testing.T, x Any) { if x == true { Failure(t, x, "== true") } }
Add a test for sysdig
import pytest @pytest.mark.parametrize("name", [ ("apt-file"), ("apt-transport-https"), ("atom"), ("blktrace"), ("ca-certificates"), ("chromium-browser"), ("cron"), ("curl"), ("diod"), ("docker-ce"), ("fonts-font-awesome"), ("git"), ("gnupg"), ("gnupg2"), ("gnupg-agent"), ("handbrake"), ("handbrake-cli"), ("haveged"), ("htop"), ("i3"), ("iotop"), ("language-pack-en-base"), ("laptop-mode-tools"), ("nfs-common"), ("ntop"), ("ntp"), ("openssh-client"), ("openssh-server"), ("openssh-sftp-server"), ("openssl"), ("pavucontrol"), ("pinta"), ("pulseaudio"), ("pulseaudio-module-x11"), ("pulseaudio-utils"), ("python"), ("python-pip"), ("scrot"), ("software-properties-common"), ("suckless-tools"), ("sysdig"), ("sysstat"), ("tree"), ("vagrant"), ("vim"), ("virtualbox"), ("vlc"), ("wget"), ("whois"), ("x264"), ("xfce4-terminal"), ("xfonts-terminus"), ("xinit"), ]) def test_packages(host, name): pkg = host.package(name) assert pkg.is_installed
import pytest @pytest.mark.parametrize("name", [ ("apt-file"), ("apt-transport-https"), ("atom"), ("blktrace"), ("ca-certificates"), ("chromium-browser"), ("cron"), ("curl"), ("diod"), ("docker-ce"), ("fonts-font-awesome"), ("git"), ("gnupg"), ("gnupg2"), ("gnupg-agent"), ("handbrake"), ("handbrake-cli"), ("haveged"), ("htop"), ("i3"), ("iotop"), ("language-pack-en-base"), ("laptop-mode-tools"), ("nfs-common"), ("ntop"), ("ntp"), ("openssh-client"), ("openssh-server"), ("openssh-sftp-server"), ("openssl"), ("pavucontrol"), ("pinta"), ("pulseaudio"), ("pulseaudio-module-x11"), ("pulseaudio-utils"), ("python"), ("python-pip"), ("scrot"), ("software-properties-common"), ("suckless-tools"), ("sysstat"), ("tree"), ("vagrant"), ("vim"), ("virtualbox"), ("vlc"), ("wget"), ("whois"), ("x264"), ("xfce4-terminal"), ("xfonts-terminus"), ("xinit"), ]) def test_packages(host, name): pkg = host.package(name) assert pkg.is_installed
Add requests to dep list
# Copyright 2017 Google 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. """Setup defines metadata for the python Chatbase Module.""" from setuptools import setup setup(name='chatbase', version='0.1', description='Python module for interacting with Chatbase APIs', url='https://chatbase.com/documentation', author='Google Inc.', author_email='chatbase-feedback@google.com', license='Apache-2.0', packages=['chatbase'], install_requires=['requests'], zip_safe=False)
# Copyright 2017 Google 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. """Setup defines metadata for the python Chatbase Module.""" from setuptools import setup setup(name='chatbase', version='0.1', description='Python module for interacting with Chatbase APIs', url='https://chatbase.com/documentation', author='Google Inc.', author_email='chatbase-feedback@google.com', license='Apache-2.0', packages=['chatbase'], zip_safe=False)
:bug: Fix bug that personFinder used unfiltered list
import { isFunction } from '../../utils/is'; export default function getList(data, orm, inputValue) { let retVal = []; if (Array.isArray(orm.groups)) { orm.groups.forEach(({ key, show }) => { if (!(isFunction(show) && !show(inputValue) && (!isFunction(orm.filter) || orm.filter(inputValue)))) { const list = data[key]; retVal = retVal.concat(list); } }); } else { Object.keys(data) .forEach((key) => { if (!isFunction(orm.filter) || orm.filter(inputValue)) { const list = data[key]; retVal = retVal.concat(list); } }); } return retVal; }
export default function getList(data, orm, inputValue) { let retVal = []; if (Array.isArray(orm.groups)) { orm.groups.forEach(({ key, show }) => { if (!(typeof show === 'function' && !show(inputValue))) { const list = data[key]; retVal = retVal.concat(list); } }); } else { Object.keys(data) .forEach((key) => { const list = data[key]; retVal = retVal.concat(list); }); } return retVal; }
Allow queue xml path to be set by prior extensions
package com.voodoodyne.gstrap.gae.test; import com.voodoodyne.gstrap.test.util.TestInfoContextAdapter; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ExtensionContext.Namespace; import org.junit.jupiter.api.extension.ExtensionContext.Store; /** */ public class GAEExtension implements BeforeEachCallback, AfterEachCallback { private static final Namespace NAMESPACE = Namespace.create(GAEExtension.class); /** Key in the store for the queue xml path. If not set, the maven default is used. */ private static final String QUEUE_XML_PATH = "queueXmlPath"; /** Optionally override the queue xml path for the GAEHelper */ public static void setQueueXmlPath(final ExtensionContext context, final String path) { context.getStore(NAMESPACE).put(QUEUE_XML_PATH, path); } @Override public void beforeEach(final ExtensionContext context) throws Exception { final Store store = context.getStore(NAMESPACE); final String queueXmlPath = store.get(QUEUE_XML_PATH, String.class); final GAEHelper helper = queueXmlPath == null ? new GAEHelper() : new GAEHelper(queueXmlPath); store.put(GAEHelper.class, helper); helper.setUp(new TestInfoContextAdapter(context)); } @Override public void afterEach(final ExtensionContext context) throws Exception { final GAEHelper helper = context.getStore(NAMESPACE).get(GAEHelper.class, GAEHelper.class); helper.tearDown(); } }
package com.voodoodyne.gstrap.gae.test; import com.voodoodyne.gstrap.test.util.TestInfoContextAdapter; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ExtensionContext.Namespace; /** */ public class GAEExtension implements BeforeEachCallback, AfterEachCallback { private static final Namespace NAMESPACE = Namespace.create(GAEExtension.class); @Override public void beforeEach(final ExtensionContext context) throws Exception { final GAEHelper helper = new GAEHelper(); context.getStore(NAMESPACE).put(GAEHelper.class, helper); helper.setUp(new TestInfoContextAdapter(context)); } @Override public void afterEach(final ExtensionContext context) throws Exception { final GAEHelper helper = context.getStore(NAMESPACE).get(GAEHelper.class, GAEHelper.class); helper.tearDown(); } }
Set date to NULL if not present or invalid
<?php function convert_mysql_date_to_php_date($date) { if ($date == "0000-00-00") { $date = "N/A"; } else { $date = date('d-M-y', strtotime($date)); } return $date; } function convert_str_date_to_mysql_date($date) { if ($date == "N/A" || $date == "0") { $date = NULL; } else { try { $date = date('Y-m-d', strtotime($date)); } catch (Exception $e) { $date = NULL; } } return $date; } ?>
<?php function convert_mysql_date_to_php_date($date) { if ($date == "0000-00-00") { $date = "N/A"; } else { $date = date('d-M-y', strtotime($date)); } return $date; } function convert_str_date_to_mysql_date($date) { if ($date == "N/A" || $date == "0") { $date = "0"; } else { try { $date = date('Y-m-d', strtotime($date)); } catch (Exception $e) { $date = "0"; } } return $date; } ?>
Use an example component without transparent background.
import React from 'react'; import { Button } from '@storybook/components'; export default { title: 'Core/Layout', parameters: { layout: 'padded', }, }; export const InheritedLayout = () => <Button primary>a button</Button>; export const PaddedLayout = () => <Button primary>a button</Button>; PaddedLayout.story = { parameters: { layout: 'padded', }, }; export const CenteredLayout = () => <Button primary>a button</Button>; CenteredLayout.story = { parameters: { layout: 'centered', }, }; export const CenteredBlockLayout = () => ( <div> <Button primary>a button</Button> </div> ); CenteredBlockLayout.story = { parameters: { layout: 'centered', }, }; export const FullScreenLayout = () => <Button primary>a button</Button>; FullScreenLayout.story = { parameters: { layout: 'fullscreen', }, };
import React from 'react'; import { Button } from '@storybook/components'; export default { title: 'Core/Layout', parameters: { layout: 'padded', }, }; export const InheritedLayout = () => <Button>a button</Button>; export const PaddedLayout = () => <Button>a button</Button>; PaddedLayout.story = { parameters: { layout: 'padded', }, }; export const CenteredLayout = () => <Button>a button</Button>; CenteredLayout.story = { parameters: { layout: 'centered', }, }; export const CenteredBlockLayout = () => ( <div> <Button>a button</Button> </div> ); CenteredBlockLayout.story = { parameters: { layout: 'centered', }, }; export const FullScreenLayout = () => <Button>a button</Button>; FullScreenLayout.story = { parameters: { layout: 'fullscreen', }, };
Improve Worker resistance against external code exceptions
import queue import threading class Worker: def __init__(self, name: str, work_queue: queue.Queue, error_handler: callable): self.name = name self.queue = work_queue # using an event instead of a boolean flag to avoid race conditions between threads self.end = threading.Event() self.error_handler = error_handler def run(self): while self._should_run(): work = self.queue.get() self._work(work) def _should_run(self): return not self.end.is_set() def _work(self, work: Work): try: work.do_work() except BaseException as e: self._error(e, work) def _error(self, e: BaseException, work: Work): try: self.error_handler(e, work, self) except: pass def post(self, work: Work): self.queue.put(work) def shutdown(self): self.end.set() class Work: def __init__(self, func: callable, name: str): self.func = func self.name = name def do_work(self): self.func()
import queue import threading class Worker: def __init__(self, name: str, work_queue: queue.Queue, error_handler: callable): self.name = name self.queue = work_queue # using an event instead of a boolean flag to avoid race conditions between threads self.end = threading.Event() self.error_handler = error_handler def run(self): while self._should_run(): work = self.queue.get() self._work(work) def _should_run(self): return not self.end.is_set() def _work(self, work: Work): try: work.do_work() except Exception as e: self.error_handler(e, work, self) def post(self, work: Work): self.queue.put(work) def shutdown(self): self.end.set() class Work: def __init__(self, func: callable, name: str): self.func = func self.name = name def do_work(self): self.func()
[FIX] Add meta data to Serializer
from django.urls import reverse from rest_framework import serializers from .models import Tafseer, TafseerText class TafseerSerializer(serializers.ModelSerializer): class Meta: model = Tafseer fields = ['id', 'name', 'language', 'author', 'book_name'] class TafseerTextSerializer(serializers.ModelSerializer): tafseer_id = serializers.IntegerField(source='tafseer.id') tafseer_name = serializers.CharField(source='tafseer.name') ayah_url = serializers.SerializerMethodField() ayah_number = serializers.IntegerField(source='ayah.number') def get_ayah_url(self, obj): return reverse('ayah-detail', kwargs={'number': obj.ayah.number, 'sura_num': obj.ayah.sura.pk}) class Meta: model = TafseerText fields = ['tafseer_id', 'tafseer_name', 'ayah_url', 'ayah_number', 'text']
from django.urls import reverse from rest_framework import serializers from .models import Tafseer, TafseerText class TafseerSerializer(serializers.ModelSerializer): class Meta: model = Tafseer fields = ['id', 'name'] class TafseerTextSerializer(serializers.ModelSerializer): tafseer_id = serializers.IntegerField(source='tafseer.id') tafseer_name = serializers.CharField(source='tafseer.name') ayah_url = serializers.SerializerMethodField() ayah_number = serializers.IntegerField(source='ayah.number') def get_ayah_url(self, obj): return reverse('ayah-detail', kwargs={'number': obj.ayah.number, 'sura_num': obj.ayah.sura.pk}) class Meta: model = TafseerText fields = ['tafseer_id', 'tafseer_name', 'ayah_url', 'ayah_number', 'text']
Fix regexp for rpm-related RPMs
package main import ( "bufio" "fmt" "os" "strings" "regexp" ) func main() { reader := bufio.NewReader(os.Stdin) re := regexp.MustCompile(`[^/]+\.rpm`) for true { line, _ := reader.ReadString('\n') parts := strings.Split(line, " ") url := parts[0] filename := re.FindString(url) if len(filename) > 0 { fmt.Printf("OK store-id=%v\n", filename); } else { fmt.Printf("OK store-id=%v\n", url); } } }
package main import ( "bufio" "fmt" "os" "strings" "regexp" ) func main() { reader := bufio.NewReader(os.Stdin) re := regexp.MustCompile("[^/]+.rpm") for true { line, _ := reader.ReadString('\n') parts := strings.Split(line, " ") url := parts[0] filename := re.FindString(url) if len(filename) > 0 { fmt.Printf("OK store-id=%v\n", filename); } else { fmt.Printf("OK store-id=%v\n", url); } } }
Fix Add MW Deployment not working The correct variable holding the reference to the file is `filePath` instead of just `file`.
ManageIQ.angular.app.controller('mwAddDeploymentController', MwAddDeploymentController); MwAddDeploymentController.$inject = ['$scope', '$http', 'miqService']; function MwAddDeploymentController($scope, $http, miqService) { $scope.$on('mwAddDeploymentEvent', function(event, data) { var fd = new FormData(); fd.append('file', data.filePath); fd.append('id', data.serverId); fd.append('enabled', data.enableDeployment); fd.append('runtimeName', data.runtimeName); $http.post('/middleware_server/add_deployment', fd, { transformRequest: angular.identity, headers: {'Content-Type': undefined} }) .then( function() { // success miqService.miqFlash('success', 'Deployment "' + data.runtimeName + '" has been initiated on this server.'); }, function() { // error miqService.miqFlash('error', 'Unable to deploy "' + data.runtimeName + '" on this server.'); }) .finally(function() { angular.element("#modal_d_div").modal('hide'); miqService.sparkleOff(); }); }); }
ManageIQ.angular.app.controller('mwAddDeploymentController', MwAddDeploymentController); MwAddDeploymentController.$inject = ['$scope', '$http', 'miqService']; function MwAddDeploymentController($scope, $http, miqService) { $scope.$on('mwAddDeploymentEvent', function(event, data) { var fd = new FormData(); fd.append('file', data.file); fd.append('id', data.serverId); fd.append('enabled', data.enableDeployment); fd.append('runtimeName', data.runtimeName); $http.post('/middleware_server/add_deployment', fd, { transformRequest: angular.identity, headers: {'Content-Type': undefined} }) .then( function() { // success miqService.miqFlash('success', 'Deployment "' + data.runtimeName + '" has been initiated on this server.'); }, function() { // error miqService.miqFlash('error', 'Unable to deploy "' + data.runtimeName + '" on this server.'); }) .finally(function() { angular.element("#modal_d_div").modal('hide'); miqService.sparkleOff(); }); }); }
Use default host when not specified
import sys import argparse from elasticsearch import Elasticsearch from annotator.reindexer import Reindexer description = """ Reindex an elasticsearch index. WARNING: Documents that are created while reindexing may be lost! """ def main(argv): argparser = argparse.ArgumentParser(description=description) argparser.add_argument('old_index', help="Index to read from") argparser.add_argument('new_index', help="Index to write to") argparser.add_argument('--host', help="Elasticsearch server, host[:port]") argparser.add_argument('--alias', help="Alias for the new index") args = argparser.parse_args() host = args.host old_index = args.old_index new_index = args.new_index alias = args.alias if host: conn = Elasticsearch([host]) else: conn = Elasticsearch() reindexer = Reindexer(conn, interactive=True) reindexer.reindex(old_index, new_index) if alias: reindexer.alias(new_index, alias) if __name__ == '__main__': main(sys.argv)
import sys import argparse from elasticsearch import Elasticsearch from annotator.reindexer import Reindexer description = """ Reindex an elasticsearch index. WARNING: Documents that are created while reindexing may be lost! """ def main(argv): argparser = argparse.ArgumentParser(description=description) argparser.add_argument('old_index', help="Index to read from") argparser.add_argument('new_index', help="Index to write to") argparser.add_argument('--host', help="Elasticsearch server, host[:port]") argparser.add_argument('--alias', help="Alias for the new index") args = argparser.parse_args() host = args.host old_index = args.old_index new_index = args.new_index alias = args.alias conn = Elasticsearch([host]) reindexer = Reindexer(conn, interactive=True) reindexer.reindex(old_index, new_index) if alias: reindexer.alias(new_index, alias) if __name__ == '__main__': main(sys.argv)
Normalize all to spinal-case before other convertions. Added toSpaceCase.
var p = String.prototype; // normalize always returns the string in spinal-case function normalize(str) { var arr = str.split(/[\s-_.]/); if(arr.length > 1) return arr.map(function(part) { return part.toLowerCase(); }).join('-'); else return (str.charAt(0).toLowerCase() + str.slice(1)).replace(/([A-Z])/, '-$&').toLowerCase(); } // Converts spinal-case, snake_case or space case to camelCase p.toCamelCase = function(pascalCase) { var str = this.toLowerCase(); var arr = str.split(/[\s-_]/); for(var i = pascalCase ? 0 : 1; i < arr.length; i++) { arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1); } return arr.join(''); }; // Converts spinal-case, snake_case or space case to PascalCase p.toPascalCase = function() { return normalize(this).toCamelCase(true); }; // converts camelCase or PascalCase to spinal-case/ p.toSpinalCase = function() { return normalize(this); }; // converts camelCase or PascalCase to snake_case/ p.toSnakeCase = function() { return normalize(this).split('-').join('_'); }; p.toSpaceCase = function(capitals) { return normalize(this).split('-').map(function(part) { return capitals ? part.charAt(0).toUpperCase() + part.slice(1) : part; }).join(' '); };
var p = String.prototype; // Converts spinal-case, snake_case or space case to camelCase p.toCamelCase = function(pascalCase) { var str = this.toLowerCase(); var arr = str.split(/[\s-_]/); for(var i = pascalCase ? 0 : 1; i < arr.length; i++) { arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1); } return arr.join(''); }; // Converts spinal-case, snake_case or space case to PascalCase p.toPascalCase = function() { return this.toCamelCase(true); }; // converts camelCase or PascalCase to spinal-case/ p.toSpinalCase = function() { return (this.charAt(0).toLowerCase() + this.slice(1)).replace(/([A-Z])/, '-$&').toLowerCase(); }; // converts camelCase or PascalCase to snake_case/ p.toSnakeCase = function() { return (this.charAt(0).toLowerCase() + this.slice(1)).replace(/([A-Z])/, '_$&').toLowerCase(); };
Rename DELETE request route to reflect prepended /collection
const express = require('express'), router = express.Router({mergeParams: true}), db = require('../models'); router.get('/', function(req, res, next) { db.Emoticon.find({}).then(function(emoticons) { res.render('emoticons/index', {emoticons}); }).catch(function(err) { console.log(err); }); }); router.get('/new', function(req, res, next) { res.render('emoticons/new', {user: req.params.username}); }); router.post('/new', function(req, res, next) { db.User.findOne({username: req.params.username}).then(function(user) { db.Emoticon.create({content: req.body.content, category: req.body.category, user: user._id}).then(function(newEmoticon) { user.emoticons.push(newEmoticon); res.redirect(`/user/${user.username}/collection`); }).catch(function(err) { console.log(err); }); }); }); router.delete('/:id', function(req, res, next) { }); module.exports = router;
const express = require('express'), router = express.Router({mergeParams: true}), db = require('../models'); router.get('/', function(req, res, next) { db.Emoticon.find({}).then(function(emoticons) { res.render('emoticons/index', {emoticons}); }).catch(function(err) { console.log(err); }); }); router.get('/new', function(req, res, next) { res.render('emoticons/new', {user: req.params.username}); }); router.post('/new', function(req, res, next) { db.User.findOne({username: req.params.username}).then(function(user) { db.Emoticon.create({content: req.body.content, category: req.body.category, user: user._id}).then(function(newEmoticon) { user.emoticons.push(newEmoticon); res.redirect(`/user/${user.username}/collection`); }).catch(function(err) { console.log(err); }); }); }); router.delete('/collection/:id', function(req, res, next) { }); module.exports = router;
Move remaining writeas/nerds/store funcs to web-core Finishes the work started in #8.
package id import ( "crypto/rand" "fmt" ) // GenerateRandomString creates a random string of characters of the given // length from the given dictionary of possible characters. // // This example generates a hexadecimal string 6 characters long: // GenerateRandomString("0123456789abcdef", 6) func GenerateRandomString(dictionary string, l int) string { var bytes = make([]byte, l) rand.Read(bytes) for k, v := range bytes { bytes[k] = dictionary[v%byte(len(dictionary))] } return string(bytes) } // GenSafeUniqueSlug generatees a reasonably unique random slug from the given // original slug. It's "safe" because it uses 0-9 b-z excluding vowels. func GenSafeUniqueSlug(slug string) string { return fmt.Sprintf("%s-%s", slug, GenerateRandomString("0123456789bcdfghjklmnpqrstvwxyz", 4)) } // Generate62RandomString creates a random string with the given length // consisting of characters in [A-Za-z0-9]. func Generate62RandomString(l int) string { return GenerateRandomString("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", l) } // GenerateFriendlyRandomString creates a random string of characters with the // given length consisting of characters in [a-z0-9]. func GenerateFriendlyRandomString(l int) string { return GenerateRandomString("0123456789abcdefghijklmnopqrstuvwxyz", l) }
package id import ( "fmt" "crypto/rand" ) // GenerateRandomString creates a random string of characters of the given // length from the given dictionary of possible characters. // // This example generates a hexadecimal string 6 characters long: // GenerateRandomString("0123456789abcdef", 6) func GenerateRandomString(dictionary string, l int) string { var bytes = make([]byte, l) rand.Read(bytes) for k, v := range bytes { bytes[k] = dictionary[v%byte(len(dictionary))] } return string(bytes) } // GenSafeUniqueSlug generatees a reasonably unique random slug from the given // original slug. It's "safe" because it uses 0-9 b-z excluding vowels. func GenSafeUniqueSlug(slug string) string { return fmt.Sprintf("%s-%s", slug, GenerateRandomString("0123456789bcdfghjklmnpqrstvwxyz", 4)) }
Fix jsx-runtime props not unmangled in tests
module.exports = function(api) { api.cache(true); const minify = String(process.env.MINIFY) === 'true'; const rename = {}; const mangle = require('./mangle.json'); for (let prop in mangle.props.props) { let name = prop; if (name[0] === '$') { name = name.slice(1); } rename[name] = mangle.props.props[prop]; } return { presets: [ [ '@babel/preset-env', { loose: true, exclude: ['@babel/plugin-transform-typeof-symbol'], targets: { browsers: ['last 2 versions', 'IE >= 9'] } } ] ], plugins: [ '@babel/plugin-proposal-object-rest-spread', '@babel/plugin-transform-react-jsx', 'babel-plugin-transform-async-to-promises', ['babel-plugin-transform-rename-properties', { rename }] ], include: ['jsx-runtime.js', '**/src/**/*.js', '**/test/**/*.js'], overrides: [ { test: /(component-stack|debug)\.test\.js$/, plugins: ['@babel/plugin-transform-react-jsx-source'] } ] }; };
module.exports = function(api) { api.cache(true); const minify = String(process.env.MINIFY) === 'true'; const rename = {}; const mangle = require('./mangle.json'); for (let prop in mangle.props.props) { let name = prop; if (name[0] === '$') { name = name.slice(1); } rename[name] = mangle.props.props[prop]; } return { presets: [ [ '@babel/preset-env', { loose: true, exclude: ['@babel/plugin-transform-typeof-symbol'], targets: { browsers: ['last 2 versions', 'IE >= 9'] } } ] ], plugins: [ '@babel/plugin-proposal-object-rest-spread', '@babel/plugin-transform-react-jsx', 'babel-plugin-transform-async-to-promises', ['babel-plugin-transform-rename-properties', { rename }] ], include: ['**/src/**/*.js', '**/test/**/*.js'], overrides: [ { test: /(component-stack|debug)\.test\.js$/, plugins: ['@babel/plugin-transform-react-jsx-source'] } ] }; };
Change argument name to stop probable name clash.
from django.contrib.contenttypes.models import ContentType # USEFUL FUNCTIONS FOR FLUENT CONTENTS ############################################################# # Fluent Contents Helper Functions ################################################################# def create_content_instance(content_plugin_class, test_page, placeholder_name='main', **kwargs): """ Creates a content instance from a content plugin class. :param content_plugin_class: The class of the content plugin. :param test_page: The fluent_page instance to create the content instance one. :param placeholder_name: The placeholder name defined in the template. [DEFAULT: main] :param kwargs: Additional keyword arguments to be used in the content instance creation. :return: The content instance created. """ # Get the placeholders that are currently available for the slot. placeholders = test_page.get_placeholder_by_slot(placeholder_name) # If a placeholder exists for the placeholder_name use the first one provided otherwise create # a new placeholder instance. if placeholders.exists(): placeholder = placeholders[0] else: placeholder = test_page.create_placeholder(placeholder_name) # Obtain the content type for the page instance class. ct = ContentType.objects.get_for_model(type(test_page)) # Create the actual plugin instance. content_instance = content_plugin_class.objects.create( parent_type=ct, parent_id=test_page.id, placeholder=placeholder, **kwargs ) return content_instance # END Fluent Contents Helper Functions #############################################################
from django.contrib.contenttypes.models import ContentType # USEFUL FUNCTIONS FOR FLUENT CONTENTS ############################################################# # Fluent Contents Helper Functions ################################################################# def create_content_instance(content_plugin_class, page, placeholder_name='main', **kwargs): """ Creates a content instance from a content plugin class. :param content_plugin_class: The class of the content plugin. :param page: The fluent_page instance to create the content instance one. :param placeholder_name: The placeholder name defined in the template. [DEFAULT: main] :param kwargs: Additional keyword arguments to be used in the content instance creation. :return: The content instance created. """ # Get the placeholders that are currently available for the slot. placeholders = page.get_placeholder_by_slot(placeholder_name) # If a placeholder exists for the placeholder_name use the first one provided otherwise create # a new placeholder instance. if placeholders.exists(): placeholder = placeholders[0] else: placeholder = page.create_placeholder(placeholder_name) # Obtain the content type for the page instance class. ct = ContentType.objects.get_for_model(type(page)) # Create the actual plugin instance. content_instance = content_plugin_class.objects.create( parent_type=ct, parent_id=page.id, placeholder=placeholder, **kwargs ) return content_instance # END Fluent Contents Helper Functions #############################################################
Fix linter issue with test describe path
describe('test/test-harness-test.js', function() { describe('globals', function() { it('should expose should as a global', function() { should.exist(should); }); it('should expose sinon as a global', function() { should.exist(sinon); }); }); describe('should-sinon plugin', function() { it('should use the should-sinon plugin', function() { const test_stub = sinon.stub().returns('hello'); test_stub().should.eql('hello'); test_stub.should.have.callCount(1); }); }); describe('should-promised plugin', function() { it('should use the should-promised plugin', function() { return Promise.resolve().should.be.fulfilled(); }); }); describe('should-http plugin', function() { it('should use the should-http plugin', function() { ({ statusCode: 200 }).should.have.status(200); }); }); });
describe('test-harness', function() { describe('globals', function() { it('should expose should as a global', function() { should.exist(should); }); it('should expose sinon as a global', function() { should.exist(sinon); }); }); describe('should-sinon plugin', function() { it('should use the should-sinon plugin', function() { const test_stub = sinon.stub().returns('hello'); test_stub().should.eql('hello'); test_stub.should.have.callCount(1); }); }); describe('should-promised plugin', function() { it('should use the should-promised plugin', function() { return Promise.resolve().should.be.fulfilled(); }); }); describe('should-http plugin', function() { it('should use the should-http plugin', function() { ({ statusCode: 200 }).should.have.status(200); }); }); });
pywrap: Fix the loaders extend context after API change.
from ..utils import extend, add_swig_getmethod, add_swig_setmethod from . import loaders_c def extend_context(_context): """ Extends _context class with loader module methods for calling convenience. Called once on loaders module inicialization. """ @extend(_context, name='load') @staticmethod def Load(filename): "Load image from given file, guess type." c = loaders_c.GP_LoadImage_Wrap(filename) return c @extend(_context) def Save(self, filename, format=None, callback=None): """Save the image in given format (or guess it from the extension) Currently, JPG, PNG and P[BGP]M are supported, but not for all context pixel types. """ if not format: format = filename.rsplit('.', 1)[-1] format = format.lower() if format == 'jpg': res = loaders_c.GP_SaveJPG(self, filename, callback) elif format == 'png': res = loaders_c.GP_SavePNG(self, filename, callback) elif format == 'pbm': res = loaders_c.GP_SavePBM(filename, self, callback) elif format == 'pgm': res = loaders_c.GP_SavePGM(filename, self, callback) elif format == 'ppm': res = loaders_c.GP_SavePPM(filename, self, callback) else: raise Exception("Format %r not supported.", format) if res != 0: raise Exception("Error saving %r (code %d)", filename, res)
from ..utils import extend, add_swig_getmethod, add_swig_setmethod from . import loaders_c def extend_context(_context): """ Extends _context class with loader module methods for calling convenience. Called once on loaders module inicialization. """ @extend(_context, name='load') @staticmethod def Load(filename): "Load image from given file, guess type." c = loaders_c.GP_LoadImage_Wrap(filename) return c @extend(_context) def Save(self, filename, format=None): """Save the image in given format (or guess it from the extension) Currently, JPG, PNG and P[BGP]M are supported, but not for all context pixel types. """ if not format: format = filename.rsplit('.', 1)[-1] format = format.lower() if format == 'jpg': res = loaders_c.GP_SaveJPG(filename, self, None) elif format == 'png': res = loaders_c.GP_SavePNG(filename, self, None) elif format == 'pbm': res = loaders_c.GP_SavePBM(filename, self, None) elif format == 'pgm': res = loaders_c.GP_SavePGM(filename, self, None) elif format == 'ppm': res = loaders_c.GP_SavePPM(filename, self, None) else: raise Exception("Format %r not supported.", format) if res != 0: raise Exception("Error saving %r (code %d)", filename, res)
Correct exit code on help
#!/usr/bin/env node "use strict"; process.title = "oui"; var arg = process.argv[2], oui = require("./"), spin = require("char-spinner"); if (arg === "--update") { var interval = spin(); oui.update(true, function (err) { clearInterval(interval); if (err) process.stdout.write(err + "\n"); process.exit(err ? 1 : 0); }); } else if (!arg || arg === "--help") { process.stdout.write([ "", " Usage: oui mac [options]", "", " Options:", "", " --help display this help", " --update update the database", "", "" ].join("\n")); process.exit(0); } else { var result; try { result = oui(arg); } catch (err) { process.stdout.write(err.message + "\n"); process.exit(1); } if (result) process.stdout.write(result + "\n"); else process.stdout.write(arg + " not found in database\n"); process.exit(0); }
#!/usr/bin/env node "use strict"; process.title = "oui"; var arg = process.argv[2], oui = require("./"), spin = require("char-spinner"); if (arg === "--update") { var interval = spin(); oui.update(true, function (err) { clearInterval(interval); if (err) process.stdout.write(err + "\n"); process.exit(err ? 1 : 0); }); } else if (!arg || arg === "--help") { process.stdout.write([ "", " Usage: oui mac [options]", "", " Options:", "", " --help display this help", " --update update the database", "", "" ].join("\n")); process.exit(1); } else { var result; try { result = oui(arg); } catch (err) { process.stdout.write(err.message + "\n"); process.exit(1); } if (result) { process.stdout.write(result + "\n"); } else { process.stdout.write(arg + " not found in database\n"); } process.exit(0); }
Sort the result list to eliminate test flakiness.
package util import ( "reflect" "sort" "testing" ) func doubleIt(v reflect.Value) reflect.Value { return reflect.ValueOf(v.Int() * 2) } func TestMergeChannel(t *testing.T) { chan1 := make(chan reflect.Value) chan2 := make(chan reflect.Value) go func() { chan1 <- reflect.ValueOf(1) close(chan1) }() go func() { chan2 <- reflect.ValueOf(2) close(chan2) }() outChan := make(chan reflect.Value, 2) MergeChannelTo([]chan reflect.Value{chan1, chan2}, doubleIt, outChan) got := make([]int, 0, 2) for v := range outChan { got = append(got, int(v.Int())) } sort.Ints(got) want := []int{2, 4} if !reflect.DeepEqual(got, want) { t.Errorf("Got %v want %v", got, want) } }
package util import ( "reflect" "testing" ) func doubleIt(v reflect.Value) reflect.Value { return reflect.ValueOf(v.Int() * 2) } func TestMergeChannel(t *testing.T) { chan1 := make(chan reflect.Value) chan2 := make(chan reflect.Value) go func() { chan1 <- reflect.ValueOf(1) close(chan1) }() go func() { chan2 <- reflect.ValueOf(2) close(chan2) }() outChan := make(chan reflect.Value, 2) MergeChannelTo([]chan reflect.Value{chan1, chan2}, doubleIt, outChan) got := make([]int64, 0, 2) for v := range outChan { got = append(got, v.Int()) } want := []int64{2, 4} if !reflect.DeepEqual(got, want) { t.Errorf("Got %v want %v", got, want) } }
Update method of loading creds Changed the way of loading credentials from config.ini file to a json credentials file.
#!/usr/bin/env python import json from twython import Twython #These values are all pulled from a file called 'config.ini' #You can call yours myawesomebotconfig.ini or whatever else! #Just remember to change it here with open('creds.json') as f: credentials = json.loads(f.read()) #SECURE YOUR CONFIG FILE - Don't put it in source code twitter = Twython(credentials["consumer_key"], credentials["consumer_secret"], credentials["access_token_key"], credentials["access_token_secret"]) def send_tweet(tweet_text): twitter.update_status(status = tweet_text) send_tweet("This is my first tweet with Sparrow by @fmcorey - https://github.com/fmcorey/sparrow")
#!/usr/bin/env python from ConfigParser import SafeConfigParser from twython import Twython #These values are all pulled from a file called 'config.ini' #You can call yours myawesomebotconfig.ini or whatever else! #Just remember to change it here config_file_name = 'config.ini' #SECURE YOUR CONFIG FILE - Don't put it in source code parser = SafeConfigParser() parser.read(config_file_name) API_KEY = parser.get(config_file_name,'API_KEY') #AKA 'Consumer Key' API_SECRET = parser.get(config_file_name,'API_SECRET') #AKA 'Consumer Secret' ACCESS_TOKEN = parser.get(config_file_name,'ACCESS_TOKEN') #AKA 'OAUTH Token' ACCESS_TOKEN_SECRET = parser.get(config_file_name,'ACCESS_TOKEN_SECRET') #AKA 'OAUTH Token Secret' twitter = Twython(API_KEY, API_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET) def send_tweet(tweet_text): twitter.update_status(status = tweet_text) send_tweet("This is my first tweet with Sparrow by @fmcorey - https://github.com/fmcorey/sparrow")
Tweak the ring to make it actually useful
package xyz.brassgoggledcoders.modularutilities.modules.baubles; import baubles.api.BaubleType; import baubles.api.IBauble; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; public class ItemBloodboundRing extends ItemBaubleBase implements IBauble { public ItemBloodboundRing() { super("bloodbound_ring"); this.setMaxStackSize(1); } @Override public BaubleType getBaubleType(ItemStack arg0) { return BaubleType.RING; } @Override public boolean canUnequip(ItemStack arg0, EntityLivingBase arg1) { return false; } @Override public void onWornTick(ItemStack stack, EntityLivingBase living) { if(living.getHealth() == living.getMaxHealth()) { living.setHealth(living.getMaxHealth() * 0.75F); living.addPotionEffect( new PotionEffect(Potion.getPotionFromResourceLocation("strength"), 120, 2, false, false)); } } }
package xyz.brassgoggledcoders.modularutilities.modules.baubles; import baubles.api.BaubleType; import baubles.api.IBauble; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; public class ItemBloodboundRing extends ItemBaubleBase implements IBauble { public ItemBloodboundRing() { super("bloodbound_ring"); this.setMaxStackSize(1); } @Override public BaubleType getBaubleType(ItemStack arg0) { return BaubleType.RING; } @Override public boolean canUnequip(ItemStack arg0, EntityLivingBase arg1) { return false; } @Override public void onWornTick(ItemStack stack, EntityLivingBase living) { if(living.getHealth() == living.getMaxHealth()) { living.setHealth(living.getMaxHealth() * 0.75F); living.addPotionEffect( new PotionEffect(Potion.getPotionFromResourceLocation("strength"), 30, 3, false, false)); } } }
Disable double addFile as legacy code has not been verified yet.
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.config.server.filedistribution; import com.yahoo.config.FileReference; import com.yahoo.config.application.api.FileRegistry; import java.util.List; public class CombinedLegacyRegistry implements FileRegistry { private final FileDBRegistry legacy; private final FileDBRegistry future; CombinedLegacyRegistry(FileDBRegistry legacy, FileDBRegistry future) { this.legacy = legacy; this.future = future; } @Override public FileReference addFile(String relativePath) { FileReference reference = legacy.addFile(relativePath); // TODO: Enable when system tested future.addFile(relativePath, reference); return reference; } @Override public String fileSourceHost() { return future.fileSourceHost(); } @Override public List<Entry> export() { return future.export(); } }
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.config.server.filedistribution; import com.yahoo.config.FileReference; import com.yahoo.config.application.api.FileRegistry; import java.util.List; public class CombinedLegacyRegistry implements FileRegistry { private final FileDBRegistry legacy; private final FileDBRegistry future; CombinedLegacyRegistry(FileDBRegistry legacy, FileDBRegistry future) { this.legacy = legacy; this.future = future; } @Override public FileReference addFile(String relativePath) { FileReference reference = legacy.addFile(relativePath); return future.addFile(relativePath, reference); } @Override public String fileSourceHost() { return future.fileSourceHost(); } @Override public List<Entry> export() { return future.export(); } }
Enable filtering ProposalVotes by reviewer.
from django.contrib import admin from conf_site.reviews.models import ( ProposalFeedback, ProposalNotification, ProposalResult, ProposalVote, ) class ProposalInline(admin.StackedInline): model = ProposalNotification.proposals.through @admin.register(ProposalFeedback) class ProposalFeedbackAdmin(admin.ModelAdmin): list_display = ("proposal", "author", "comment", "date_created") @admin.register(ProposalNotification) class ProposalNotificationAdmin(admin.ModelAdmin): exclude = ("proposals",) inlines = [ProposalInline] list_display = ("subject", "body", "date_sent") @admin.register(ProposalResult) class ProposalResultAdmin(admin.ModelAdmin): list_display = ("proposal", "status") @admin.register(ProposalVote) class ProposalVoteAdmin(admin.ModelAdmin): list_display = ("proposal", "voter", "score", "comment") list_filter = ["score", "voter"]
from django.contrib import admin from conf_site.reviews.models import ( ProposalFeedback, ProposalNotification, ProposalResult, ProposalVote, ) class ProposalInline(admin.StackedInline): model = ProposalNotification.proposals.through @admin.register(ProposalFeedback) class ProposalFeedbackAdmin(admin.ModelAdmin): list_display = ("proposal", "author", "comment", "date_created") @admin.register(ProposalNotification) class ProposalNotificationAdmin(admin.ModelAdmin): exclude = ("proposals",) inlines = [ProposalInline] list_display = ("subject", "body", "date_sent") @admin.register(ProposalResult) class ProposalResultAdmin(admin.ModelAdmin): list_display = ("proposal", "status") @admin.register(ProposalVote) class ProposalVoteAdmin(admin.ModelAdmin): list_display = ("proposal", "voter", "score", "comment") list_filter = ("score",)
Add icon that works for linux apps also
const electron = require('electron'); const app = electron.app; const BrowserWindow = electron.BrowserWindow; const Menu = electron.Menu; var menu = require('./menu'); var argv = require('optimist').argv; let mainWindow; app.on('ready', function() { mainWindow = new BrowserWindow({ center: true, title: 'JBrowseDesktop', width: 1024, height: 768, icon: require('path').resolve(__dirname, 'icons/jbrowse.png') }); var queryString = Object.keys(argv).map(key => key + '=' + argv[key]).join('&'); mainWindow.loadURL('file://' + require('path').resolve(__dirname, '../index.html?'+queryString)); Menu.setApplicationMenu(Menu.buildFromTemplate(menu)); mainWindow.on('closed', function () { mainWindow = null; }); }); // Quit when all windows are closed. app.on('window-all-closed', function () { app.quit(); });
const electron = require('electron'); const app = electron.app; const BrowserWindow = electron.BrowserWindow; const Menu = electron.Menu; var menu = require('./menu'); var argv = require('optimist').argv; let mainWindow; app.on('ready', function() { mainWindow = new BrowserWindow({ center: true, title: 'JBrowseDesktop', width: 1024, height: 768 }); var queryString = Object.keys(argv).map(key => key + '=' + argv[key]).join('&'); mainWindow.loadURL('file://' + require('path').resolve(__dirname, '../index.html?'+queryString)); Menu.setApplicationMenu(Menu.buildFromTemplate(menu)); mainWindow.on('closed', function () { mainWindow = null; }); }); // Quit when all windows are closed. app.on('window-all-closed', function () { app.quit(); });
Add checks to get_app_instance to avoid Resolver404 even if namespace does not exists
# -*- coding: utf-8 -*- from app_data import AppDataContainer, app_registry from cms.apphook_pool import apphook_pool from django.core.urlresolvers import resolve, Resolver404 def get_app_instance(request): """ Returns a tuple containing the current namespace and the AppHookConfig instance :param request: request object :return: namespace, config """ app = None if getattr(request, 'current_page', None): app = apphook_pool.get_apphook(request.current_page.application_urls) if app and app.app_config: try: config = None namespace = resolve(request.path).namespace if app and app.app_config: config = app.get_config(namespace) return namespace, config except Resolver404: pass return '', None def setup_config(form_class, config_model): """ Register the provided form as config form for the provided config model :param form_class: Form class derived from AppDataForm :param config_model: Model class derived from AppHookConfig :return: """ app_registry.register('config', AppDataContainer.from_form(form_class), config_model)
# -*- coding: utf-8 -*- from app_data import AppDataContainer, app_registry from cms.apphook_pool import apphook_pool from django.core.urlresolvers import resolve def get_app_instance(request): """ Returns a tuple containing the current namespace and the AppHookConfig instance :param request: request object :return: namespace, config """ app = None if getattr(request, 'current_page', None): app = apphook_pool.get_apphook(request.current_page.application_urls) config = None namespace = resolve(request.path_info).namespace if app and app.app_config: config = app.get_config(namespace) return namespace, config def setup_config(form_class, config_model): """ Register the provided form as config form for the provided config model :param form_class: Form class derived from AppDataForm :param config_model: Model class derived from AppHookConfig :return: """ app_registry.register('config', AppDataContainer.from_form(form_class), config_model)
Fix Random Chance of Exception w/ customs
package main import "math/rand" import "time" const DEFAULT_AD_CHANCE = 95 type Plug struct { ID int S3ID string Owner string ViewsRemaining int Approved bool PresignedURL string } type PlugList struct { Data []string `form:"plugs[]"` } func (p Plug) IsDefault() bool { return p.ViewsRemaining < 0 } func ChoosePlug(plugs []Plug) Plug { rand.Seed(time.Now().Unix()) // Split plugs into default and custom ads var defaults []Plug var customs []Plug for i := 0; i < len(plugs); i++ { if plugs[i].IsDefault() { defaults = append(defaults, plugs[i]) } else { customs = append(customs, plugs[i]) } } // Decide whether to chose default ad or user submitted ad var pickDefault int = rand.Intn(100) if pickDefault >= DEFAULT_AD_CHANCE && len(customs) == 0 { return defaults[rand.Intn(len(defaults))] } else { return customs[rand.Intn(len(customs))] } }
package main import "math/rand" import "time" const DEFAULT_AD_CHANCE = 95 type Plug struct { ID int S3ID string Owner string ViewsRemaining int Approved bool PresignedURL string } type PlugList struct { Data []string `form:"plugs[]"` } func (p Plug) IsDefault() bool { return p.ViewsRemaining < 0 } func ChoosePlug(plugs []Plug) Plug { rand.Seed(time.Now().Unix()) // Split plugs into default and custom ads var defaults []Plug var customs []Plug for i := 0; i < len(plugs); i++ { if plugs[i].IsDefault() { defaults = append(defaults, plugs[i]) } else { customs = append(customs, plugs[i]) } } // Decide whether to chose default ad or user submitted ad var pickDefault int = rand.Intn(100) if pickDefault >= DEFAULT_AD_CHANCE && len(defaults) != 0 { return defaults[rand.Intn(len(defaults))] } else { return customs[rand.Intn(len(customs))] } }
Add DendriticLayerBase to init to ease experimentation
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2021, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # 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 Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- from .apply_dendrites import * from .boosted_dendrites import * from .dendrite_segments import DendriteSegments from .dendritic_layers import ( AbsoluteMaxGatingDendriticLayer, AbsoluteMaxGatingDendriticLayer2d, BiasingDendriticLayer, GatingDendriticLayer, GatingDendriticLayer2d, DendriticLayerBase, )
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2021, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # 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 Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- from .apply_dendrites import * from .boosted_dendrites import * from .dendrite_segments import DendriteSegments from .dendritic_layers import ( AbsoluteMaxGatingDendriticLayer, AbsoluteMaxGatingDendriticLayer2d, BiasingDendriticLayer, GatingDendriticLayer, GatingDendriticLayer2d, )
Fix typo (nil instaed of null)
function BetterContentController(){ this.listeners = {}; } BetterContentController.prototype.registerListener = function(client, func) { this.listeners[client] = func; } BetterContentController.prototype.removeListener = function(client) { this.listeners[client] = null; } BetterContentController.prototype.onMessage = function(originator, message) { if (originator === module.exports.NATIVE_APP){ if (this.listeners[module.exports.WEB_CLIENT]){ this.listeners[module.exports.WEB_CLIENT](message); } } if (originator === module.exports.WEB_CLIENT){ if (this.listeners[module.exports.NATIVE_APP]){ this.listeners[module.exports.NATIVE_APP](message); } } } module.exports = BetterContentController; module.exports.NATIVE_APP = 'nativeApp'; module.exports.WEB_CLIENT = 'webClient';
function BetterContentController(){ this.listeners = {}; } BetterContentController.prototype.registerListener = function(client, func) { this.listeners[client] = func; } BetterContentController.prototype.removeListener = function(client) { this.listeners[client] = nil; } BetterContentController.prototype.onMessage = function(originator, message) { if (originator === module.exports.NATIVE_APP){ if (this.listeners[module.exports.WEB_CLIENT]){ this.listeners[module.exports.WEB_CLIENT](message); } } if (originator === module.exports.WEB_CLIENT){ if (this.listeners[module.exports.NATIVE_APP]){ this.listeners[module.exports.NATIVE_APP](message); } } } module.exports = BetterContentController; module.exports.NATIVE_APP = 'nativeApp'; module.exports.WEB_CLIENT = 'webClient';
Change default HTTP timeout to 10 seconds
<?php require 'check_setup.php'; require 'vendor/password.php'; require 'vendor/PicoTools/Dependency_Injection.php'; require 'vendor/PicoTools/Translator.php'; require 'vendor/PicoDb/Database.php'; require 'vendor/PicoDb/Table.php'; require 'schema.php'; require 'model.php'; const DB_VERSION = 8; const APP_VERSION = 'master'; const APP_USERAGENT = 'Miniflux - http://miniflux.net'; const HTTP_TIMEOUT = 10; const LIMIT_ALL = -1; function get_db_filename() { return 'data/db.sqlite'; } PicoTools\container('db', function() { $db = new PicoDb\Database(array( 'driver' => 'sqlite', 'filename' => get_db_filename() )); if ($db->schema()->check(DB_VERSION)) { return $db; } else { die('Unable to migrate database schema.'); } });
<?php require 'check_setup.php'; require 'vendor/password.php'; require 'vendor/PicoTools/Dependency_Injection.php'; require 'vendor/PicoTools/Translator.php'; require 'vendor/PicoDb/Database.php'; require 'vendor/PicoDb/Table.php'; require 'schema.php'; require 'model.php'; const DB_VERSION = 8; const APP_VERSION = 'master'; const APP_USERAGENT = 'Miniflux - http://miniflux.net'; const HTTP_TIMEOUT = 5; const LIMIT_ALL = -1; function get_db_filename() { return 'data/db.sqlite'; } PicoTools\container('db', function() { $db = new PicoDb\Database(array( 'driver' => 'sqlite', 'filename' => get_db_filename() )); if ($db->schema()->check(DB_VERSION)) { return $db; } else { die('Unable to migrate database schema.'); } });
Use ADVISER_DIR instead of getcwd().
<?php namespace Adviser\Utilities; class CommandRunnerUtilityTest extends \Adviser\Testing\UtilityTestCase { /** * @test */ public function it_runs_a_terminal_command() { $output = (new CommandRunnerUtility())->run(ADVISER_DIR."/testing/utility-command.sh"); $this->assertInternalType("array", $output); $this->assertEquals($output["stdout"], "from stdout".PHP_EOL); $this->assertEquals($output["stderr"], "from stderr".PHP_EOL); } /** * @test */ public function it_throws_an_exception_if_something_goes_wrong() { $this->setExpectedException("RuntimeException"); // Redefine "proc_open" in the current namespace for the purpose of testing. function proc_open() { return false; } (new CommandRunnerUtility())->run("some command"); } }
<?php namespace Adviser\Utilities; class CommandRunnerUtilityTest extends \Adviser\Testing\UtilityTestCase { /** * @test */ public function it_runs_a_terminal_command() { $output = (new CommandRunnerUtility())->run(getcwd()."/testing/utility-command.sh"); $this->assertInternalType("array", $output); $this->assertEquals($output["stdout"], "from stdout".PHP_EOL); $this->assertEquals($output["stderr"], "from stderr".PHP_EOL); } /** * @test */ public function it_throws_an_exception_if_something_goes_wrong() { $this->setExpectedException("RuntimeException"); // Redefine "proc_open" in the current namespace for the purpose of testing. function proc_open() { return false; } (new CommandRunnerUtility())->run("some command"); } }
Fix a problem that coverage decreased
<?php namespace Tests\Feature; use Tests\TestCase; use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; use App; class LoginTest extends TestCase { use DatabaseMigrations; public function testBasicTest() { $this->get('/')->assertRedirect('/login'); $this->get('/', [ 'X-Requested-With' => 'XMLHttpRequest' ]) ->assertStatus(401); } public function testLoggedIn() { $user = factory(App\User::class)->create(); $this->actingAs($user)->get('/')->assertStatus(200); } public function testLogout() { $user = factory(App\User::class)->create(); $this->actingAs($user)->post('/logout')->assertRedirect('/'); } }
<?php namespace Tests\Feature; use Tests\TestCase; use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; use App; class LoginTest extends TestCase { use DatabaseMigrations; public function testBasicTest() { $this->get('/')->assertRedirect('/login'); $this->get('/', [ 'X-Requested-With' => 'XMLHttpRequest' ]) ->assertStatus(401); } public function testLoggedIn() { $user = [ 'email' => 'example@example.com', 'name' => 'Example', 'password' => 'testtest', ]; factory(App\User::class)->create($user); $this->post('/login', $user)->assertRedirect('/'); } public function testLogout() { $user = factory(App\User::class)->create(); $this->actingAs($user)->post('/logout')->assertRedirect('/'); } }
Fix doctest - not sure why it was failing on the quotation marks
import re import os import contextlib from . import pipeline @contextlib.contextmanager def maintained_selection(): comp = pipeline.get_current_comp() previous_selection = comp.GetToolList(True).values() try: yield finally: flow = comp.CurrentFrame.FlowView flow.Select() # No args equals clearing selection if previous_selection: for tool in previous_selection: flow.Select(tool, True) def get_frame_path(path): """Get filename for the Fusion Saver with padded number as '#' >>> get_frame_path("C:/test.exr") ('C:/test', 4, '.exr') >>> get_frame_path("filename.00.tif") ('filename.', 2, '.tif') >>> get_frame_path("foobar35.tif") ('foobar', 2, '.tif') Args: path (str): The path to render to. Returns: tuple: head, padding, tail (extension) """ filename, ext = os.path.splitext(path) # Find a final number group match = re.match('.*?([0-9]+)$', filename) if match: padding = len(match.group(1)) # remove number from end since fusion # will swap it with the frame number filename = filename[:-padding] else: padding = 4 # default Fusion padding return filename, padding, ext
import re import os import contextlib from . import pipeline @contextlib.contextmanager def maintained_selection(): comp = pipeline.get_current_comp() previous_selection = comp.GetToolList(True).values() try: yield finally: flow = comp.CurrentFrame.FlowView flow.Select() # No args equals clearing selection if previous_selection: for tool in previous_selection: flow.Select(tool, True) def get_frame_path(path): """Get filename for the Fusion Saver with padded number as '#' >>> get_frame_path("C:/test.exr") ("C:/test", 4, ".exr") >>> get_frame_path("filename.00.tif") ("filename.", 2, ".tif") >>> get_frame_path("foobar35.tif") ("foobar", 2, ".tif") Args: path (str): The path to render to. Returns: tuple: head, padding, tail (extension) """ filename, ext = os.path.splitext(path) # Find a final number group match = re.match('.*?([0-9]+)$', filename) if match: padding = len(match.group(1)) # remove number from end since fusion # will swap it with the frame number filename = filename[:-padding] else: padding = 4 # default Fusion padding return filename, padding, ext
Add new function for relative paths.
/*jslint node: true*/ "use strict"; var fs = require('fs'); var path = require('path'); var S = require('string'); var options = require('./options.js'); var logging = require('./logging.js'); module.exports.uriToFilename = function(uri) { var filename = path.join(options.fileBase, uri); // Make sure filename ends with '/' if filename exists and is a directory. try { var fileStats = fs.statSync(filename); if (fileStats.isDirectory() && !S(filename).endsWith('/')) { filename += '/'; } else if (fileStats.isFile() && S(filename).endsWith('/')) { filename = S(filename).chompRight('/').s; } } catch (err) {} return filename; }; module.exports.uriToRelativeFilename = function(uri) { var filename = this.uriToFilename(uri); var relative = path.relative(options.fileBase, filename); return relative; }; module.exports.filenameToBaseUri = function(filename) { var uriPath = S(filename).strip(options.fileBase).toString(); return path.join(options.uriBase, uriPath); };
/*jslint node: true*/ "use strict"; var fs = require('fs'); var path = require('path'); var S = require('string'); var options = require('./options.js'); var logging = require('./logging.js'); module.exports.uriToFilename = function(uri) { var filename = path.join(options.fileBase, uri); // Make sure filename ends with '/' if filename exists and is a directory. try { var fileStats = fs.statSync(filename); if (fileStats.isDirectory() && !S(filename).endsWith('/')) { filename += '/'; } else if (fileStats.isFile() && S(filename).endsWith('/')) { filename = S(filename).chompRight('/').s; } } catch (err) {} return filename; }; module.exports.filenameToBaseUri = function(filename) { var uriPath = S(filename).strip(options.fileBase).toString(); return path.join(options.uriBase, uriPath); };
Fix exception on missing options object If the JumpPointFinder constructor was not passed the options object there was a ReferenceError.
/** * @author aniero / https://github.com/aniero */ var DiagonalMovement = require('../core/DiagonalMovement'); var JPFNeverMoveDiagonally = require('./JPFNeverMoveDiagonally'); var JPFAlwaysMoveDiagonally = require('./JPFAlwaysMoveDiagonally'); var JPFMoveDiagonallyIfNoObstacles = require('./JPFMoveDiagonallyIfNoObstacles'); var JPFMoveDiagonallyIfAtMostOneObstacle = require('./JPFMoveDiagonallyIfAtMostOneObstacle'); /** * Path finder using the Jump Point Search algorithm * @param {object} opt * @param {function} opt.heuristic Heuristic function to estimate the distance * (defaults to manhattan). * @param {DiagonalMovement} opt.diagonalMovement Condition under which diagonal * movement will be allowed. */ function JumpPointFinder(opt) { opt = opt || {}; if (opt.diagonalMovement === DiagonalMovement.Never) { return new JPFNeverMoveDiagonally(opt); } else if (opt.diagonalMovement === DiagonalMovement.Always) { return new JPFAlwaysMoveDiagonally(opt); } else if (opt.diagonalMovement === DiagonalMovement.OnlyWhenNoObstacles) { return new JPFMoveDiagonallyIfNoObstacles(opt); } else { return new JPFMoveDiagonallyIfAtMostOneObstacle(opt); } } module.exports = JumpPointFinder;
/** * @author aniero / https://github.com/aniero */ var DiagonalMovement = require('../core/DiagonalMovement'); var JPFNeverMoveDiagonally = require('./JPFNeverMoveDiagonally'); var JPFAlwaysMoveDiagonally = require('./JPFAlwaysMoveDiagonally'); var JPFMoveDiagonallyIfNoObstacles = require('./JPFMoveDiagonallyIfNoObstacles'); var JPFMoveDiagonallyIfAtMostOneObstacle = require('./JPFMoveDiagonallyIfAtMostOneObstacle'); /** * Path finder using the Jump Point Search algorithm * @param {object} opt * @param {function} opt.heuristic Heuristic function to estimate the distance * (defaults to manhattan). * @param {DiagonalMovement} opt.diagonalMovement Condition under which diagonal * movement will be allowed. */ function JumpPointFinder(opt) { if (opt.diagonalMovement === DiagonalMovement.Never) { return new JPFNeverMoveDiagonally(opt); } else if (opt.diagonalMovement === DiagonalMovement.Always) { return new JPFAlwaysMoveDiagonally(opt); } else if (opt.diagonalMovement === DiagonalMovement.OnlyWhenNoObstacles) { return new JPFMoveDiagonallyIfNoObstacles(opt); } else { return new JPFMoveDiagonallyIfAtMostOneObstacle(opt); } } module.exports = JumpPointFinder;
Fix unresolvable /lib/rogue path leftover by fixing merge conflicts
'use strict'; /* eslint-disable global-require */ function start() { const config = require('../config'); const logger = require('./logger'); const app = require('../app'); // Setup Gateway client. require('./gateway').getClient(); // Start mongoose connection require('../config/mongoose')(config.dbUri); const mongoose = require('mongoose'); /** * For practical reasons, a Connection equals a Db. * @see http://mongoosejs.com/docs/4.x/docs/api.html#connection_Connection */ const db = mongoose.connection; logger.info('worker process started.'); // Register connection open listener db.once('open', () => { app.listen(config.port, () => logger.info(`Conversations API is running on port=${config.port}.`)); }); } module.exports = { start, };
'use strict'; /* eslint-disable global-require */ function start() { const config = require('../config'); const logger = require('./logger'); const app = require('../app'); // Setup rogue client. require('./rogue').getClient(); // Start mongoose connection require('../config/mongoose')(config.dbUri); const mongoose = require('mongoose'); /** * For practical reasons, a Connection equals a Db. * @see http://mongoosejs.com/docs/4.x/docs/api.html#connection_Connection */ const db = mongoose.connection; logger.info('worker process started.'); // Register connection open listener db.once('open', () => { app.listen(config.port, () => logger.info(`Conversations API is running on port=${config.port}.`)); }); } module.exports = { start, };
Use key fixture in boto tests.
#!/usr/bin/env python import os from tempdir import TempDir import pytest boto = pytest.importorskip('boto') from simplekv.net.botostore import BotoStore from basic_store import BasicStore from url_store import UrlStore from bucket_manager import boto_credentials, boto_bucket @pytest.fixture(params=boto_credentials, ids=[c['access_key'] for c in boto_credentials]) def credentials(request): return request.param @pytest.yield_fixture() def bucket(credentials): with boto_bucket(**credentials) as bucket: yield bucket class TestBotoStorage(BasicStore, UrlStore): @pytest.fixture(params=['', '/test-prefix']) def prefix(self, request): return request.param @pytest.fixture def store(self, bucket, prefix): return BotoStore(bucket, prefix) def test_get_filename_nonexistant(self, store, key): # NOTE: boto misbehaves here and tries to erase the target file # the parent tests use /dev/null, which you really should not try # to os.remove! with TempDir() as tmpdir: with pytest.raises(KeyError): store.get_file(key, os.path.join(tmpdir, 'a'))
#!/usr/bin/env python import os from tempdir import TempDir import pytest boto = pytest.importorskip('boto') from simplekv.net.botostore import BotoStore from basic_store import BasicStore from url_store import UrlStore from bucket_manager import boto_credentials, boto_bucket @pytest.fixture(params=boto_credentials, ids=[c['access_key'] for c in boto_credentials]) def credentials(request): return request.param @pytest.yield_fixture() def bucket(credentials): with boto_bucket(**credentials) as bucket: yield bucket class TestBotoStorage(BasicStore, UrlStore): @pytest.fixture(params=['', '/test-prefix']) def prefix(self, request): return request.param @pytest.fixture def store(self, bucket, prefix): return BotoStore(bucket, prefix) def test_get_filename_nonexistant(self, store): # NOTE: boto misbehaves here and tries to erase the target file # the parent tests use /dev/null, which you really should not try # to os.remove! with TempDir() as tmpdir: with pytest.raises(KeyError): store.get_file('nonexistantkey', os.path.join(tmpdir, 'a'))
Use skipIfExists instead of true
/* * grunt-contrib-internal * http://gruntjs.com/ * * Copyright (c) 2016 Tyler Kellen, contributors * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { var path = require('path'); grunt.registerTask('contrib-ci', 'Normalizes AppVeyor and Travis CI configs.', function(skipIfExists) { skipIfExists = skipIfExists === "skipIfExists"; var travis = grunt.file.read(path.join(__dirname, '..', '.travis.yml')); var appveyor = grunt.file.read(path.join(__dirname, '..', 'appveyor.yml')); var taskTravis = path.join(process.cwd(), '.travis.yml'); if (!skipIfExists || !grunt.file.exists(taskTravis)) { grunt.file.write(taskTravis, travis); } var taskAppveyor = path.join(process.cwd(), 'appveyor.yml'); if (!skipIfExists || !grunt.file.exists(taskAppveyor)) { grunt.file.write(taskAppveyor, appveyor); } grunt.log.ok('Normalized .travis.yml and appveyor.yml for grunt-contrib.'); }); };
/* * grunt-contrib-internal * http://gruntjs.com/ * * Copyright (c) 2016 Tyler Kellen, contributors * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { var path = require('path'); grunt.registerTask('contrib-ci', 'Normalizes AppVeyor and Travis CI configs.', function(skipIfExists) { skipIfExists = skipIfExists === true; var travis = grunt.file.read(path.join(__dirname, '..', '.travis.yml')); var appveyor = grunt.file.read(path.join(__dirname, '..', 'appveyor.yml')); var taskTravis = path.join(process.cwd(), '.travis.yml'); if (!skipIfExists || !grunt.file.exists(taskTravis)) { grunt.file.write(taskTravis, travis); } var taskAppveyor = path.join(process.cwd(), 'appveyor.yml'); if (!skipIfExists || !grunt.file.exists(taskAppveyor)) { grunt.file.write(taskAppveyor, appveyor); } grunt.log.ok('Normalized .travis.yml and appveyor.yml for grunt-contrib.'); }); };
FIx warning and remove use of preventDefault on checkbox
import React from 'react' export default class Prefs extends React.Component { static propTypes = { prefs: React.PropTypes.object.isRequired, setPrefs: React.PropTypes.func.isRequired, providerRefresh: React.PropTypes.func.isRequired, } setEnabled = this.setEnabled.bind(this) handleRefresh = this.handleRefresh.bind(this) setEnabled(e) { let prefs = Object.assign({}, this.props.prefs) prefs.enabled = e.target.checked this.props.setPrefs('provider.cdg', prefs) } handleRefresh() { this.props.providerRefresh('cdg') } render() { const { prefs } = this.props if (!prefs) return null const enabled = prefs.enabled === true let paths = prefs.paths || [] paths = paths.map(path => ( <p key={path}>{path}</p> )) return ( <div> <label> <input type='checkbox' checked={enabled} onChange={this.setEnabled}/> <strong> CD+Graphics</strong> </label> <button onClick={this.handleRefresh}>Refresh</button> {paths} </div> ) } }
import React from 'react' export default class Prefs extends React.Component { static propTypes = { prefs: React.PropTypes.object.isRequired, setPrefs: React.PropTypes.func.isRequired, providerRefresh: React.PropTypes.func.isRequired, } toggleEnabled = this.toggleEnabled.bind(this) handleRefresh = this.handleRefresh.bind(this) toggleEnabled(e) { e.preventDefault() let prefs = Object.assign({}, this.props.prefs) prefs.enabled = !prefs.enabled this.props.setPrefs('provider.cdg', prefs) } handleRefresh() { this.props.providerRefresh('cdg') } render() { const { prefs } = this.props if (!prefs) return null const enabled = prefs.enabled === true let paths = prefs.paths || [] paths = paths.map(path => ( <p key={path}>{path}</p> )) return ( <div> <label> <input type='checkbox' checked={enabled} onClick={this.toggleEnabled}/> <strong> CD+Graphics</strong> </label> <button onClick={this.handleRefresh}>Refresh</button> {paths} </div> ) } }
Fix IndexLink component without href value can't be a link
import React, {Component} from 'react' import {IndexLink, Link} from 'react-router' import styles from '../sass/Navbar' class Navbar extends Component { constructor() { super() } render() { return ( <nav className={styles.navbar}> <IndexLink className={styles.link} activeClassName={styles.active} to="/">home</IndexLink> <Link className={styles.link} activeClassName={styles.active} to="explore">explore</Link> <Link className={styles.link} activeClassName={styles.active} to="about">about</Link> </nav> ) } } export default Navbar
import React, {Component} from 'react' import {IndexLink, Link} from 'react-router' import styles from '../sass/Navbar' class Navbar extends Component { constructor() { super() } render() { return ( <nav className={styles.navbar}> <IndexLink className={styles.link} activeClassName={styles.active} to="">home</IndexLink> <Link className={styles.link} activeClassName={styles.active} to="explore">explore</Link> <Link className={styles.link} activeClassName={styles.active} to="about">about</Link> </nav> ) } } export default Navbar
Use custom logger on gevent>=1.1
''' This module provides some function to make running a webserver a little easier ''' def gevent_run(app): from gevent.wsgi import WSGIServer import gevent.monkey from werkzeug.debug import DebuggedApplication gevent.monkey.patch_socket() run_app = app if app.config['DEBUG']: run_app = DebuggedApplication(app) def run_server(): from gevent import version_info logger = app._logger port = int(app.config.get('PORT', 5000)) address = app.config.get('ADDRESS', '') logger.info('Listening on http://{}:{}/'.format(address or '0.0.0.0', port)) server_params = dict() #starting from gevent version 1.1b1 we can pass custom logger to gevent if version_info[:2] >= (1,1): server_params['log'] = logger http_server = WSGIServer((address, port), run_app, **server_params) http_server.serve_forever() if app.config['DEBUG']: from werkzeug._reloader import run_with_reloader run_with_reloader(run_server) else: run_server()
''' This module provides some function to make running a webserver a little easier ''' def gevent_run(app): from gevent.wsgi import WSGIServer import gevent.monkey from werkzeug.debug import DebuggedApplication gevent.monkey.patch_socket() run_app = app if app.config['DEBUG']: run_app = DebuggedApplication(app) def run_server(): import logging port = int(app.config.get('PORT', 5000)) address = app.config.get('ADDRESS', '') logging.getLogger('webant').info('Listening on http://{}:{}/'.format(address or '0.0.0.0', port)) http_server = WSGIServer((address, port), run_app) http_server.serve_forever() if app.config['DEBUG']: from werkzeug._reloader import run_with_reloader run_with_reloader(run_server) else: run_server()
Fix error al pulsar creditos Se añade errors en la ruta de creditos...
var express = require('express'); var router = express.Router(); var quizController = require('../controllers/quiz_controller'); /* GET home page. */ router.get('/', function(req, res) { res.render('index', { title: 'Quiz', errors: []}); }); router.get('/author', function(req, res) { res.render('author', { title: 'Creditos', errors: [] }); }); //router.get('/quizes/question', quizController.question); //router.get('/quizes/answer', quizController.answer) // Autoload de comandos con :quizId router.param('quizId', quizController.load); // autoload :quizId router.get('/quizes', quizController.index); router.get('/quizes/:quizId(\\d+)', quizController.show); router.get('/quizes/:quizId(\\d+)/answer', quizController.answer); router.get('/quizes/new', quizController.new); router.post('/quizes/create', quizController.create); router.get('/quizes/:quizId(\\d+)/edit', quizController.edit); router.put('/quizes/:quizId(\\d+)', quizController.update); router.delete('/quizes/:quizId(\\d+)', quizController.destroy); module.exports = router;
var express = require('express'); var router = express.Router(); var quizController = require('../controllers/quiz_controller'); /* GET home page. */ router.get('/', function(req, res) { res.render('index', { title: 'Quiz', errors: []}); }); router.get('/author', function(req, res) { res.render('author', { title: 'Creditos' }); }); //router.get('/quizes/question', quizController.question); //router.get('/quizes/answer', quizController.answer) // Autoload de comandos con :quizId router.param('quizId', quizController.load); // autoload :quizId router.get('/quizes', quizController.index); router.get('/quizes/:quizId(\\d+)', quizController.show); router.get('/quizes/:quizId(\\d+)/answer', quizController.answer); router.get('/quizes/new', quizController.new); router.post('/quizes/create', quizController.create); router.get('/quizes/:quizId(\\d+)/edit', quizController.edit); router.put('/quizes/:quizId(\\d+)', quizController.update); router.delete('/quizes/:quizId(\\d+)', quizController.destroy); module.exports = router;
Configure redux-logger to be a bit prettier.
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { applyMiddleware, combineReducers, compose, createStore } from 'redux'; import { initializeCurrentLocation } from 'redux-little-router'; import { createLogger } from 'redux-logger'; import thunk from 'redux-thunk'; import DevTools from 'control_new/components/devtools'; import { enhancer as routerEnhancer, middleware as routerMiddleware, reducer as routerReducer, Router, } from 'control_new/routes'; import applicationState from 'control_new/state'; const reducers = combineReducers({ app: applicationState, router: routerReducer, }); const store = createStore(reducers, reducers(undefined, { type: 'initial' }), compose( applyMiddleware( createLogger({ collapsed: true, diff: true, duration: true, timestamp: true, }), routerMiddleware, thunk ), routerEnhancer, DEVELOPMENT ? DevTools.instrument() : x => x, )); const initialLocation = store.getState().router; if (initialLocation) { store.dispatch(initializeCurrentLocation(initialLocation)); } function Root() { return ( <Provider store={store}> <Router /> </Provider> ); } ReactDOM.render(<Root />, document.querySelector('#main'));
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { applyMiddleware, combineReducers, compose, createStore } from 'redux'; import { initializeCurrentLocation } from 'redux-little-router'; import logger from 'redux-logger'; import thunk from 'redux-thunk'; import DevTools from 'control_new/components/devtools'; import { enhancer as routerEnhancer, middleware as routerMiddleware, reducer as routerReducer, Router, } from 'control_new/routes'; import applicationState from 'control_new/state'; const reducers = combineReducers({ app: applicationState, router: routerReducer, }); const store = createStore(reducers, reducers(undefined, { type: 'initial' }), compose( applyMiddleware( logger, routerMiddleware, thunk ), routerEnhancer, DEVELOPMENT ? DevTools.instrument() : x => x, )); const initialLocation = store.getState().router; if (initialLocation) { store.dispatch(initializeCurrentLocation(initialLocation)); } function Root() { return ( <Provider store={store}> <Router /> </Provider> ); } ReactDOM.render(<Root />, document.querySelector('#main'));
Send computeWorkflow message when tag is deselected
'use strict'; /** * @ngdoc function * @name tagrefineryGuiApp.controller:WorkflowCtrl * @description * # WorkflowCtrl * Controller of the tagrefineryGuiApp */ angular.module('tagrefineryGuiApp') .controller('WorkflowCtrl', ["$scope", "socket", function ($scope, socket) { var that = this; // State variables that.guided = true; that.showStep = false; that.currentStep = 0; //////////////////////////////////////////////// // Start //////////////////////////////////////////////// socket.on('isGuided', function (data) { that.guided = data == "true"; socket.emit("getParameters", ""); }); that.ok = function() { that.showStep = true; }; that.next = function() { that.showStep = false; that.currentStep++; // Let the child apply changes $scope.$broadcast("apply"); }; that.apply = function() { // Let the child apply changes $scope.$broadcast("apply"); socket.emit("computeWorkflow", ""); } }]);
'use strict'; /** * @ngdoc function * @name tagrefineryGuiApp.controller:WorkflowCtrl * @description * # WorkflowCtrl * Controller of the tagrefineryGuiApp */ angular.module('tagrefineryGuiApp') .controller('WorkflowCtrl', ["$scope", "socket", function ($scope, socket) { var that = this; // State variables that.guided = true; that.showStep = false; that.currentStep = 0; //////////////////////////////////////////////// // Start //////////////////////////////////////////////// socket.on('isGuided', function (data) { that.guided = data == "true"; socket.emit("getParameters", ""); }); that.ok = function() { that.showStep = true; }; that.next = function() { that.showStep = false; that.currentStep++; // Let the child apply changes $scope.$broadcast("apply"); }; that.apply = function() { // Let the child apply changes $scope.$broadcast("apply"); } }]);
Update test to reflect changing git codebase
import unittest from pylons import c, g from ming.orm import ThreadLocalORMSession from pyforge.tests import helpers from pyforge.lib import helpers as h class TestGitApp(unittest.TestCase): def setUp(self): helpers.setup_basic_test() helpers.setup_global_objects() h.set_context('test', 'src_git') ThreadLocalORMSession.flush_all() ThreadLocalORMSession.close_all() def test_templates(self): assert c.app.templates.endswith('forgegit/templates') def test_admin_menu(self): assert len(c.app.admin_menu()) == 1 def test_uninstall(self): c.app.uninstall(c.project) assert g.mock_amq.pop('audit') g.mock_amq.setup_handlers() c.app.uninstall(c.project) g.mock_amq.handle_all()
import unittest from pylons import c, g from ming.orm import ThreadLocalORMSession from pyforge.tests import helpers from pyforge.lib import helpers as h class TestGitApp(unittest.TestCase): def setUp(self): helpers.setup_basic_test() helpers.setup_global_objects() h.set_context('test', 'src_git') ThreadLocalORMSession.flush_all() ThreadLocalORMSession.close_all() def test_templates(self): assert c.app.templates.endswith('forgegit/templates') def test_admin_menu(self): assert c.app.admin_menu() == [] def test_uninstall(self): c.app.uninstall(c.project) assert g.mock_amq.pop('audit') g.mock_amq.setup_handlers() c.app.uninstall(c.project) g.mock_amq.handle_all()
Add balancing for cleaver scripts.
exports.listeners = { wield: function (l10n) { return function (location, player, players) { player.say('You ready the weighty cleaver.'); player.combat.addToHitMod({ name: 'cleaver ' + this.getUuid(), effect: toHit => toHit + 1 }); player.combat.addToDodgeMod({ name: 'cleaver ' + this.getUuid(), effect: dodge => dodge - 1 }); } }, remove: function (l10n) { return function (player) { player.say('You place the bulky cleaver in your pack.'); player.combat.deleteAllMods('cleaver' + this.getUuid()); } }, hit: function (l10n) { return function (player) { player.say('<bold>The blade of your cleaver <red>does its job.</red></bold>'); player.combat.addDamageMod({ name: 'cleaver' + this.getUuid(), effect: damage => damage + .5 }); } }, parry: function(l10n) { return function (player) { player.say('<bold><white>The blade of your cleaver halts their attack.</white></bold>'); player.combat.addDamageMod({ name: 'cleaver' + this.getUuid(), effect: damage => damage - .5 }); } } };
exports.listeners = { wield: function (l10n) { return function (location, player, players) { player.say('You ready the weighty cleaver.'); player.combat.addToHitMod({ name: 'cleaver ' + this.getUuid(), effect: toHit => toHit + 1 }); } }, remove: function (l10n) { return function (player) { player.say('You place the bulky cleaver in your pack.'); player.combat.deleteAllMods('cleaver' + this.getUuid()); } }, hit: function (l10n) { return function (player) { player.say('<bold>The blade of your cleaver <red>does its job.</red></bold>'); player.combat.addDamageMod({ name: 'cleaver' + this.getUuid(), effect: damage => damage + .5 }); } } };
Add comment to test settings to advice disabling search indexing
import logging from {{ project_name }}.settings import * # noqa logging.disable(logging.CRITICAL) DEBUG = False DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '{{ project_name }}', 'USER': 'postgres' }, } # Add middleware to add a meta tag with the response status code for Selenium MIDDLEWARE += [ 'tests.middleware.PageStatusMiddleware' ] # Fixture location FIXTURE_DIRS = ['tests/fixtures/'] # Set the default cache to be a dummy cache CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } # Use dummy backend for safety and performance EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend' # Disable the automatic indexing (sigals) of your search backend # In WAGTAILSEARCH_BACKENDS set AUTO_UPDATE for each backend to False
import logging from {{ project_name }}.settings import * # noqa logging.disable(logging.CRITICAL) DEBUG = False DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '{{ project_name }}', 'USER': 'postgres' }, } # Add middleware to add a meta tag with the response status code for Selenium MIDDLEWARE += [ 'tests.middleware.PageStatusMiddleware' ] # Fixture location FIXTURE_DIRS = ['tests/fixtures/'] # Set the default cache to be a dummy cache CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } # Use dummy backend for safety and performance EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
Add xspress3 to step-scan detector list
# vim: sw=4 ts=4 sts expandtab smarttab # HXN step-scan configuration import hxntools.scans from bluesky.global_state import get_gs gs = get_gs() hxntools.scans.setup() ct = hxntools.scans.count ascan = hxntools.scans.absolute_scan dscan = hxntools.scans.relative_scan fermat = hxntools.scans.relative_fermat spiral = hxntools.scans.relative_spiral mesh = hxntools.scans.absolute_mesh dmesh = hxntools.scans.relative_mesh gs.DETS = [zebra, sclr1, merlin1, xspress3, smll, lakeshore2, xbpm, dcm, s1] gs.TABLE_COLS = ['sclr2_ch2','sclr2_ch3', 'sclr2_ch4', 'ssx', 'ssy', 'ssz', 't_base', 't_sample', 't_vlens', 't_hlens'] # Plot this by default versus motor position: gs.PLOT_Y = 'Det2_V'
# vim: sw=4 ts=4 sts expandtab smarttab # HXN step-scan configuration import hxntools.scans from bluesky.global_state import get_gs gs = get_gs() hxntools.scans.setup() ct = hxntools.scans.count ascan = hxntools.scans.absolute_scan dscan = hxntools.scans.relative_scan fermat = hxntools.scans.relative_fermat spiral = hxntools.scans.relative_spiral mesh = hxntools.scans.absolute_mesh dmesh = hxntools.scans.relative_mesh gs.DETS = [zebra, sclr1, merlin1, smll, lakeshore2, xbpm, dcm, s1] gs.TABLE_COLS = ['sclr2_ch2','sclr2_ch3', 'sclr2_ch4', 'ssx', 'ssy', 'ssz', 't_base', 't_sample', 't_vlens', 't_hlens'] # Plot this by default versus motor position: gs.PLOT_Y = 'Det2_V'
Fix bug in launch-instances subcommand of ami-publisher.
package main import ( "fmt" "github.com/Symantec/Dominator/imagepublishers/amipublisher" "github.com/Symantec/Dominator/lib/awsutil" "github.com/Symantec/Dominator/lib/log" "os" "path" ) func launchInstancesSubcommand(args []string, logger log.Logger) { domImage := "" if len(args) > 1 { domImage = args[1] } err := launchInstances(args[0], domImage, logger) if err != nil { fmt.Fprintf(os.Stderr, "Error launching instances: %s\n", err) os.Exit(1) } os.Exit(0) } func launchInstances(bootImage, domImage string, logger log.Logger) error { bootImage = path.Clean(bootImage) tags, err := makeTags() if err != nil { return err } tags["Name"] = *unpackerName if domImage != "" { tags["RequiredImage"] = domImage } imageTags := make(awsutil.Tags) for key, value := range searchTags { imageTags[key] = value } imageTags["Name"] = bootImage return amipublisher.LaunchInstances(targets, skipTargets, imageTags, vpcSearchTags, subnetSearchTags, securityGroupSearchTags, *instanceType, *sshKeyName, tags, logger) }
package main import ( "fmt" "github.com/Symantec/Dominator/imagepublishers/amipublisher" "github.com/Symantec/Dominator/lib/awsutil" "github.com/Symantec/Dominator/lib/log" "os" "path" ) func launchInstancesSubcommand(args []string, logger log.Logger) { domImage := "" if len(args) > 1 { domImage = args[1] } err := launchInstances(args[0], domImage, logger) if err != nil { fmt.Fprintf(os.Stderr, "Error copying bootstrap images: %s\n", err) os.Exit(1) } os.Exit(0) } func launchInstances(bootImage, domImage string, logger log.Logger) error { bootImage = path.Clean(bootImage) tags, err := makeTags() if err != nil { return err } tags["Name"] = *unpackerName if domImage != "" { tags["RequiredImage"] = domImage } imageTags := make(awsutil.Tags) for key, value := range searchTags { imageTags[key] = value } imageTags["Name"] = bootImage return amipublisher.LaunchInstances(targets, skipTargets, imageTags, subnetSearchTags, vpcSearchTags, securityGroupSearchTags, *instanceType, *sshKeyName, tags, logger) }
Fix edge-case with blank user agent in FastBoot * Call the isMobile class with the current context to avoid leaking the global.
import Service from '@ember/service'; import { computed, get, set } from '@ember/object'; import { getOwner } from '@ember/application'; import { isBlank } from '@ember/utils'; import isMobile from 'ismobilejs'; /** * The attributes returned by isMobile are accessible. However, they should be * accessed using the `get` helper, since they may be undefined if the user * agent header is blank. */ export default Service.extend({ fastboot: computed(function() { return getOwner(this).lookup('service:fastboot'); }), init() { this._super(...arguments); let queries = []; if (get(this, 'fastboot.isFastBoot')) { const headers = get(this, 'fastboot.request.headers'); let userAgent = get(headers, 'headers.user-agent'); // isMobile tries to fetch `navigator` if we give it a blank user agent. if (isBlank(userAgent)) { return; } userAgent = userAgent[0]; // Call with the current context to avoid leaking the node global space! queries = isMobile.call(this, userAgent); } else { queries = isMobile; } for (let media in queries) { set(this, media, queries[media]); } } });
import Service from '@ember/service'; import { computed, get, getProperties, set } from '@ember/object'; import { getOwner } from '@ember/application'; import { isBlank } from '@ember/utils'; import isMobile from 'ismobilejs'; export default Service.extend({ fastboot: computed(function() { return getOwner(this).lookup('service:fastboot'); }), init() { this._super(...arguments); let queries = []; if (get(this, 'fastboot.isFastBoot')) { const headers = get(this, 'fastboot.request.headers'); let userAgent = get(headers, 'headers.user-agent')[0]; if (isBlank(userAgent)) { return; } queries = getProperties( isMobile(userAgent), ['any', 'phone', 'tablet', 'apple', 'android', 'amazon', 'windows', 'seven_inch', 'other'] ); } else { queries = isMobile; } for (let media in queries) { set(this, media, queries[media]); } } });
Correct for None appearing in requirements list
#!/usr/bin/env python """ Install the packages you have listed in the requirements file you input as first argument. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import fileinput import subprocess from pip.req import parse_requirements def get_requirements(*args): """Parse all requirements files given and return a list of the dependencies""" install_deps = [] try: for fpath in args: install_deps.extend([str(d.req) for d in parse_requirements(fpath)]) except: print('Error reading {} file looking for dependencies.'.format(fpath)) return [dep for dep in install_deps if dep != 'None'] if __name__ == '__main__': for line in fileinput.input(): req_filepaths = sys.argv[1:] deps = get_requirements(*req_filepaths) try: for dep_name in deps: cmd = "pip install {0}".format(dep_name) print('#', cmd) subprocess.check_call(cmd, shell=True) except: print('Error installing {}'.format(dep_name))
#!/usr/bin/env python """ Install the packages you have listed in the requirements file you input as first argument. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import fileinput import subprocess from pip.req import parse_requirements def get_requirements(*args): """Parse all requirements files given and return a list of the dependencies""" install_deps = [] try: for fpath in args: install_deps.extend([str(d.req) for d in parse_requirements(fpath)]) except: print('Error reading {} file looking for dependencies.'.format(fpath)) return install_deps if __name__ == '__main__': for line in fileinput.input(): req_filepaths = sys.argv[1:] deps = get_requirements(*req_filepaths) try: for dep_name in deps: if dep_name == 'None': continue cmd = "pip install {0}".format(dep_name) print('#', cmd) subprocess.check_call(cmd, shell=True) except: print('Error installing {}'.format(dep_name))
Fix issue with 'who' lagging behind user typing
"use strict" import React from "react" import StatusMessage from "./status-message" import PollTable from "./poll-table" import PollReport from "./poll-report" import Nav from "./nav" import throttle from "lodash/function/throttle" // Declare here for global throttling const updateWho = throttle((flux, who) => flux.getActions("poll").updateWho(who), 5000) export default class App extends React.Component { constructor(props) { super(props) // "who" is a state here for better reactivity (*) this.state = {"who": props.who} } onChangeWho(e) { // (*) Note this function is throttled because it's an onChange // (*) so prop "who" will not always be updated, which could cause undecent latency updateWho(this.props.flux, e.target.value) // (*) So we rely on state this.setState({"who": e.target.value}) } render() { const props = {...this.props, ...this.state} const input = this.props.showTable ? <input placeholder="Entrez votre nom" defaultValue={ this.state.who } onChange={ e => this.onChangeWho(e) } /> : null const table = this.props.showTable ? <PollTable { ...props } /> : null const report = this.props.showReport ? <PollReport { ...props } /> : null return ( <div className="poll"> { input } { table } <Nav { ...props } /> { report } <StatusMessage /> </div> ); } }
"use strict" import React from "react" import StatusMessage from "./status-message" import PollTable from "./poll-table" import PollReport from "./poll-report" import Nav from "./nav" import throttle from "lodash/function/throttle" // Declare here for global throttling const updateWho = throttle((flux, who) => flux.getActions("poll").updateWho(who), 5000) export default class App extends React.Component { onChangeWho(e) { updateWho(this.props.flux, e.target.value) } render() { const input = this.props.showTable ? <input placeholder="Entrez votre nom" defaultValue={ this.props.who } onChange={ e => this.onChangeWho(e) } /> : null const table = this.props.showTable ? <PollTable { ...this.props } /> : null const report = this.props.showReport ? <PollReport { ...this.props } /> : null return ( <div className="poll"> { input } { table } <Nav { ...this.props } /> { report } <StatusMessage /> </div> ); } }
Send actual output to standard out instead of error.
package main import ( "log" "os" "fmt" "go/ast" "go/parser" "go/token" ) func validator(name string, s *ast.StructType) { fmt.Println(name) for _, fld := range(s.Fields.List) { nam := fld.Names[0].Name typ := fld.Type.(*ast.Ident) fmt.Printf("%s %s\n", nam, typ) } } func main() { log.SetFlags(0) fs := token.NewFileSet() f, err := parser.ParseFile(fs, "-", os.Stdin, 0) if err != nil { log.Fatal(err) } for _, obj := range f.Scope.Objects { if obj.Kind != ast.Typ { continue } ts, ok := obj.Decl.(*ast.TypeSpec) if !ok { continue } s, ok := ts.Type.(*ast.StructType) if !ok { continue } if s.Fields == nil { log.Fatalf("type %s struct has empty field list %v", ts.Name, ts) } validator(ts.Name.Name, s) } }
package main import ( "log" "os" "go/ast" "go/parser" "go/token" ) func validator(name string, s *ast.StructType) { log.Print(name) for _, fld := range(s.Fields.List) { nam := fld.Names[0].Name typ := fld.Type.(*ast.Ident) log.Printf("%s %s", nam, typ) } } func main() { log.SetFlags(0) fs := token.NewFileSet() f, err := parser.ParseFile(fs, "-", os.Stdin, 0) if err != nil { log.Fatal(err) } for _, obj := range f.Scope.Objects { if obj.Kind != ast.Typ { continue } ts, ok := obj.Decl.(*ast.TypeSpec) if !ok { continue } s, ok := ts.Type.(*ast.StructType) if !ok { continue } if s.Fields == nil { log.Fatalf("type %s struct has empty field list %v", ts.Name, ts) } validator(ts.Name.Name, s) } }
Apply the empty promise to the promise class
PromiseAllSync = { extend: function(PromiseClass) { var emptyPromise = PromiseClass.resolve || PromiseClass.when; PromiseClass.allSync = function(collection, fn, unfn) { var stack = []; return collection.reduce(function(promise, item) { return promise.then(function() { var nextPromise = fn ? fn(item) : item; return nextPromise.then(function() { if(unfn) stack.push(item); }); }); }, emptyPromise.apply(PromiseClass)) .catch(function(e) { if(unfn) while(stack.length) unfn(stack.pop()); return PromiseClass.reject(e); }); } } };
PromiseAllSync = { extend: function(PromiseClass) { PromiseClass.allSync = function(collection, fn, unfn) { var stack = []; return collection.reduce(function(promise, item) { return promise.then(function() { var nextPromise = fn ? fn(item) : item; return nextPromise.then(function() { if(unfn) stack.push(item); }); }); }, (PromiseClass.resolve || PromiseClass.when)()) .catch(function(e) { if(unfn) while(stack.length) unfn(stack.pop()); return PromiseClass.reject(e); }); } } };
Switch to using Eimann's mirror to resolve jamendo track ids, due to jamendo downtime.
<?php function resolve_external_url($url) { if (substr($url, 0, 10) == 'jamendo://') { return process_jamendo_url($url); } return $url; } function process_jamendo_url($url) { if (substr($url, 10, 13) == 'track/stream/') { $id = substr($url, 23); return 'http://gigue.rrbone.net/' . $id . '.ogg2'; } if (substr($url, 10, 15) == 'album/download/') { $id = substr($url, 25); return 'http://api.jamendo.com/get2/bittorrent/file/plain/?album_id=' . $id . '&type=archive&class=ogg3'; } if (substr($url, 10, 10) == 'album/art/') { $id = substr($url, 20); return 'http://api.jamendo.com/get2/image/album/redirect/?id=' . $id . '&imagesize=200'; } // We don't know what this is return $url; }
<?php function resolve_external_url($url) { if (substr($url, 0, 10) == 'jamendo://') { return process_jamendo_url($url); } return $url; } function process_jamendo_url($url) { if (substr($url, 10, 13) == 'track/stream/') { $id = substr($url, 23); return 'http://api.jamendo.com/get2/stream/track/redirect/?id=' . $id . '&streamencoding=ogg2'; } if (substr($url, 10, 15) == 'album/download/') { $id = substr($url, 25); return 'http://api.jamendo.com/get2/bittorrent/file/plain/?album_id=' . $id . '&type=archive&class=ogg3'; } if (substr($url, 10, 10) == 'album/art/') { $id = substr($url, 20); return 'http://api.jamendo.com/get2/image/album/redirect/?id=' . $id . '&imagesize=200'; } // We don't know what this is return $url; }
Remove public getProfile method to base controller
<?php namespace base; class Controller{ private $_views = array(); private $_res = null; private $_req = null; public $currentPath = null; protected function getRequest() { return Request::getInstance(); } protected function getResponse() { if(empty($this->_res)){ $this->_res = new Response(); } return $this->_res; } protected function getView($tplName, $isNew = false) { if(!$isNew && !empty($this->_views[$tplName])) { return $this->_views[$tplName]; } else { if(empty($this->currentPath) || empty($this->className)) { $class_info = new \ReflectionClass($this); $this->currentPath = dirname($class_info->getFileName()); $this->className = $class_info->getShortName(); } $ds = DIRECTORY_SEPARATOR; $tplName = $this->currentPath.$ds.$this->className.'.Views'.$ds."{$tplName}.php"; $this->_views[$tplName] = new View($tplName); return $this->_views[$tplName]; } } }
<?php namespace base; class Controller{ private $_views = array(); private $_res = null; private $_req = null; public $currentPath = null; protected function getRequest() { return Request::getInstance(); } protected function getResponse() { if(empty($this->_res)){ $this->_res = new Response(); } return $this->_res; } protected function getView($tplName, $isNew = false) { if(!$isNew && !empty($this->_views[$tplName])) { return $this->_views[$tplName]; } else { if(empty($this->currentPath) || empty($this->className)) { $class_info = new \ReflectionClass($this); $this->currentPath = dirname($class_info->getFileName()); $this->className = $class_info->getShortName(); } $ds = DIRECTORY_SEPARATOR; $tplName = $this->currentPath.$ds.$this->className.'.Views'.$ds."{$tplName}.php"; $this->_views[$tplName] = new View($tplName); return $this->_views[$tplName]; } } public function getProfile() { return "Profile"; } }
Test getComponentName() should throw when nothing passed in
import React, { Component } from 'react'; import getComponentName from '../getComponentName'; /* eslint-disable */ class Foo extends Component { render() { return <div />; } } function Bar() { return <div />; } const OldComp = React.createClass({ render: function() { return <div />; } }); const OldCompRev = React.createClass({ displayName: 'Rev(OldComp)', render: function() { return <div />; } }); class FooRev extends Component { static displayName = 'Rev(Foo)'; render() { return <span />; } } /* eslint-enable */ it('reads name from React components', () => { expect(getComponentName(Foo)).toBe('Foo'); expect(getComponentName(Bar)).toBe('Bar'); expect(getComponentName(OldComp)).toBe('OldComp'); }); it('reads name from components with custom name', () => { expect(getComponentName(OldCompRev)).toBe('Rev(OldComp)'); expect(getComponentName(FooRev)).toBe('Rev(Foo)'); }); it('throws if no Component passed in', () => { expect(() => getComponentName()).toThrow(); });
import React, { Component } from 'react'; import getComponentName from '../getComponentName'; /* eslint-disable */ class Foo extends Component { render() { return <div />; } } function Bar() { return <div />; } const OldComp = React.createClass({ render: function() { return <div />; } }); const OldCompRev = React.createClass({ displayName: 'Rev(OldComp)', render: function() { return <div />; } }); class FooRev extends Component { static displayName = 'Rev(Foo)'; render() { return <span />; } } /* eslint-enable */ it('reads name from React components', () => { expect(getComponentName(Foo)).toBe('Foo'); expect(getComponentName(Bar)).toBe('Bar'); expect(getComponentName(OldComp)).toBe('OldComp'); }); it('reads name from components with custom name', () => { expect(getComponentName(OldCompRev)).toBe('Rev(OldComp)'); expect(getComponentName(FooRev)).toBe('Rev(Foo)'); });
Add client side user detail permission
(function() { 'use strict'; var app = angular.module('radar.users'); app.factory('UserPermission', ['AdminPermission', function(AdminPermission) { return AdminPermission; }]); app.factory('UserInfoController', ['ModelDetailController', '$injector', 'UserPermission', function(ModelDetailController, $injector, UserPermission) { function UserInfoController($scope) { var self = this; $injector.invoke(ModelDetailController, self, { $scope: $scope, params: { permission: new UserPermission() } }); self.load($scope.user).then(function() { self.view(); }); } UserInfoController.$inject = ['$scope']; UserInfoController.prototype = Object.create(ModelDetailController.prototype); return UserInfoController; }]); app.directive('userInfoComponent', ['UserInfoController', function(UserInfoController) { return { scope: { user: '=' }, controller: UserInfoController, templateUrl: 'app/users/user-info-component.html' }; }]); })();
(function() { 'use strict'; var app = angular.module('radar.users'); app.factory('UserInfoController', ['ModelDetailController', '$injector', function(ModelDetailController, $injector) { function UserInfoController($scope) { var self = this; $injector.invoke(ModelDetailController, self, { $scope: $scope, params: {} }); self.load($scope.user).then(function() { self.view(); }); } UserInfoController.$inject = ['$scope']; UserInfoController.prototype = Object.create(ModelDetailController.prototype); return UserInfoController; }]); app.directive('userInfoComponent', ['UserInfoController', function(UserInfoController) { return { scope: { user: '=' }, controller: UserInfoController, templateUrl: 'app/users/user-info-component.html' }; }]); })();
Remove run_hook from list of imported commands.
# -*- coding: utf-8 -*- # Copyright (c) 2014-2019 Dontnod Entertainment # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' Nimp subcommands declarations ''' __all__ = [ 'build', 'check', 'commandlet', 'dev', 'download_fileset', 'fileset', 'p4', 'package', 'run', 'symbol_server', 'update_symbol_server', 'upload', 'upload_fileset', ]
# -*- coding: utf-8 -*- # Copyright (c) 2014-2019 Dontnod Entertainment # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' Nimp subcommands declarations ''' __all__ = [ 'build', 'check', 'commandlet', 'dev', 'download_fileset', 'fileset', 'p4', 'package', 'run', 'run_hook', 'symbol_server', 'update_symbol_server', 'upload', 'upload_fileset', ]
Change from MySQL to SQLite3
import os import peewee APP_DIR = os.path.dirname(__file__) try: import urlparse import psycopg2 urlparse.uses_netloc.append('postgres') url = urlparse.urlparse(os.environ["DATABASE_URL"]) database = peewee.PostgresqlDatabase(database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port) except KeyError: database = peewee.SqliteDatabase('my_app.db')
import os import peewee APP_DIR = os.path.dirname(__file__) try: import urlparse import psycopg2 urlparse.uses_netloc.append('postgres') url = urlparse.urlparse(os.environ["DATABASE_URL"]) database = peewee.PostgresqlDatabase(database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port) except KeyError: database = peewee.MySQLDatabase(os.environ["MYSQL_DATABASE"], os.environ["MYSQL_HOST"], user=os.environ["MYSQL_USER"], passwd=os.environ["MYSQL_PASSWD"])
Fix for zero arg constructor
package org.gwtbootstrap3.extras.slider.client.ui; /* * #%L * GwtBootstrap3 * %% * Copyright (C) 2013 GwtBootstrap3 * %% * 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. * #L% */ import org.gwtbootstrap3.extras.slider.client.ui.base.SliderBase; /** * @author Grant Slender */ public class Slider extends SliderBase { public Slider() { super(); } public Slider(float min, float max, float value) { super(); setMin(min); setMax(max); setValue(value); } public Slider(int min, int max, int value) { this((float)min,(float)max,(float)value); } }
package org.gwtbootstrap3.extras.slider.client.ui; /* * #%L * GwtBootstrap3 * %% * Copyright (C) 2013 GwtBootstrap3 * %% * 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. * #L% */ import org.gwtbootstrap3.extras.slider.client.ui.base.SliderBase; /** * @author Grant Slender */ public class Slider extends SliderBase { public Slider(float min, float max, float value) { super(); setMin(min); setMax(max); setValue(value); } public Slider(int min, int max, int value) { this((float)min,(float)max,(float)value); } }
Remove unreachable code per `go vet`
package main import ( log "github.com/sirupsen/logrus" "github.com/urfave/cli" "time" ) func RunPeriodically(c *cli.Context) error { log.SetFormatter(_makeFormatter(c.String("format"))) log.WithFields(log.Fields{ "appName": c.App.Name, }).Info("Running periodically") period := time.Duration(c.Int("period")) * time.Second for { go func() { PrintHeartbeat() }() time.Sleep(period) } } func PrintHeartbeat() { log.WithFields(log.Fields{ "type": "heartbeat", }).Info("Every heartbeat bears your name") } func _makeFormatter(format string) log.Formatter { switch format { case "text": return &log.TextFormatter{DisableColors: true} case "json": return &log.JSONFormatter{} default: return &log.JSONFormatter{} } }
package main import ( log "github.com/sirupsen/logrus" "github.com/urfave/cli" "time" ) func RunPeriodically(c *cli.Context) error { log.SetFormatter(_makeFormatter(c.String("format"))) log.WithFields(log.Fields{ "appName": c.App.Name, }).Info("Running periodically") period := time.Duration(c.Int("period")) * time.Second for { go func() { PrintHeartbeat() }() time.Sleep(period) } return nil } func PrintHeartbeat() { log.WithFields(log.Fields{ "type": "heartbeat", }).Info("Every heartbeat bears your name") } func _makeFormatter(format string) log.Formatter { switch format { case "text": return &log.TextFormatter{DisableColors: true} case "json": return &log.JSONFormatter{} default: return &log.JSONFormatter{} } }
Increment port number with each execution
var RSVP = require('rsvp'); var request = RSVP.denodeify(require('request')); var jsdom = require("jsdom").jsdom; var express = require('express'); var FastBootServer = require('ember-fastboot-server'); var server = new FastBootServer({ distPath: 'fastboot-dist', ui: { writeLine: function() { console.log.apply(console, arguments); } } }); var appPort = 3210; function moduleForFastboot(name, opts) { appPort++; var opts = opts || {}; var app = express(); app.get('/*', server.middleware()); app.listen(appPort); function visit(path) { return request('http://localhost:' + appPort + path) .then(function(response) { return [ response.statusCode, response.headers, jsdom(response.body).defaultView.document ]; }); } QUnit.module('Fastboot: ' + name, { beforeEach: function() { this.app = app; this.visit = visit.bind(this); if (opts.beforeEach) { opts.beforeEach.call(this); } }, afterEach() { // Kill the app if (opts.beforeEach) { opts.beforeEach.call(this); } } }); } module.exports = { moduleForFastboot: moduleForFastboot };
var RSVP = require('rsvp'); var request = RSVP.denodeify(require('request')); var jsdom = require("jsdom").jsdom; var express = require('express'); var FastBootServer = require('ember-fastboot-server'); var server = new FastBootServer({ distPath: 'fastboot-dist', ui: { writeLine: function() { console.log.apply(console, arguments); } } }); function moduleForFastboot(name, opts) { var opts = opts || {}; var app = express(); var appPort = 3211; app.get('/*', server.middleware()); app.listen(3211); function visit(path) { return request('http://localhost:' + appPort + path) .then(function(response) { return [ response.statusCode, response.headers, jsdom(response.body).defaultView.document ]; }); } QUnit.module('Fastboot: ' + name, { beforeEach: function() { this.app = app; this.visit = visit.bind(this); if (opts.beforeEach) { opts.beforeEach.call(this); } }, afterEach() { // Kill the app if (opts.beforeEach) { opts.beforeEach.call(this); } } }); } module.exports = { moduleForFastboot: moduleForFastboot };
Use global.datadir to obtain package files
'use strict'; const path = require('path'); const fs = require('fs'); const jsontolua = require('../jsontolua'); const registry = require('../registry'); module.exports = function(req, res) { req.params.version = req.params.version.replace(/^latest$/, '>=0.0.0'); registry.wrap(req.params.package) .then(pkg => { const version = pkg.getIdealVersion(req.params.version); if(version) { const pkgFile = require( path.resolve( global.datadir, 'packages', `${pkg.getName()}@${version.version.toString()}.json` ) ); res.status(200).respondAccording(pkgFile); } else throw `This version does not exist for '${pkg.getName()}'`; }).catch(err => res.status(404).respondAccording({ 'error': err })); };
'use strict'; const path = require('path'); const fs = require('fs'); const jsontolua = require('../jsontolua'); const registry = require('../registry'); module.exports = function(req, res) { req.params.version = req.params.version.replace(/^latest$/, '>=0.0.0'); registry.wrap(req.params.package) .then(pkg => { const version = pkg.getIdealVersion(req.params.version); if(version) { const pkgFile = require( path.resolve( __dirname, '..', '..', 'packages', `${pkg.getName()}@${version.version.toString()}.json` ) ); res.status(200).respondAccording(pkgFile); } else throw `This version does not exist for '${pkg.getName()}'`; }).catch(err => res.status(404).respondAccording({ 'error': err })); };
Remove old comment that no longer applies
# Copyright 2011-2012 Michael Garski (mgarski@mac.com) # # 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 setup( name='stellr', version='0.3.2', description='Solr client library for gevent utilizing urllib3 and ZeroMQ.', author='Michael Garski', author_email='mgarski@mac.com', install_requires=['urllib3>=1.1', 'gevent>=0.13.6', 'gevent_zeromq>=0.2.2', 'pyzmq>=2.0.10.1', 'simplejson>=2.1.6'], url='https://github.com/mgarski/stellr', packages=['stellr'] )
# Copyright 2011-2012 Michael Garski (mgarski@mac.com) # # 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 setup( name='stellr', version='0.3.2', description='Solr client library for gevent utilizing urllib3 and ZeroMQ.', author='Michael Garski', author_email='mgarski@mac.com', #TODO: is 'depends' valid? seeing warnings that it is not install_requires=['urllib3>=1.1', 'gevent>=0.13.6', 'gevent_zeromq>=0.2.2', 'pyzmq>=2.0.10.1', 'simplejson>=2.1.6'], url='https://github.com/mgarski/stellr', packages=['stellr'] )
Add utility methods for yesterday's date
"""class to convert datetime values""" import datetime class DatetimeConverter(object): """stuff""" _EPOCH_0 = datetime.datetime(1970, 1, 1) def __init__(self): """stuff""" pass @staticmethod def get_tomorrow(): """stuff""" return datetime.datetime.today() + datetime.timedelta(days=1) @staticmethod def get_yesterday(): return datetime.datetime.today() - datetime.timedelta(days=1) @classmethod def get_timestamp(cls, datetime_obj): """helper method to return timestamp fo datetime object""" return (datetime_obj - cls._EPOCH_0).total_seconds() @classmethod def get_tomorrow_timestamp(cls): """stuff""" return cls.get_timestamp(cls.get_tomorrow()) @classmethod def get_yesterday_timestamp(cls): return cls.get_timestamp(cls.get_yesterday())
"""class to convert datetime values""" import datetime class DatetimeConverter(object): """stuff""" _EPOCH_0 = datetime.datetime(1970, 1, 1) def __init__(self): """stuff""" pass @staticmethod def get_tomorrow(): """stuff""" return datetime.datetime.today() + datetime.timedelta(days=1) @classmethod def get_timestamp(cls, datetime_obj): """helper method to return timestamp fo datetime object""" return (datetime_obj - cls._EPOCH_0).total_seconds() @classmethod def get_tomorrow_timestamp(cls): """stuff""" return cls.get_timestamp(cls.get_tomorrow())
Fix product_id filter on content delivery repos The value should be an integer. JIRA: PDC-1104
# # Copyright (c) 2015 Red Hat # Licensed under The MIT License (MIT) # http://opensource.org/licenses/MIT # import django_filters as filters from pdc.apps.common.filters import MultiValueFilter, MultiIntFilter from . import models class RepoFilter(filters.FilterSet): arch = MultiValueFilter(name='variant_arch__arch__name') content_category = MultiValueFilter(name='content_category__name') content_format = MultiValueFilter(name='content_format__name') release_id = MultiValueFilter(name='variant_arch__variant__release__release_id') variant_uid = MultiValueFilter(name='variant_arch__variant__variant_uid') repo_family = MultiValueFilter(name='repo_family__name') service = MultiValueFilter(name='service__name') shadow = filters.BooleanFilter() product_id = MultiIntFilter() class Meta: model = models.Repo fields = ('arch', 'content_category', 'content_format', 'name', 'release_id', 'repo_family', 'service', 'shadow', 'variant_uid', 'product_id') class RepoFamilyFilter(filters.FilterSet): name = filters.CharFilter(lookup_type="icontains") class Meta: model = models.RepoFamily fields = ('name',)
# # Copyright (c) 2015 Red Hat # Licensed under The MIT License (MIT) # http://opensource.org/licenses/MIT # import django_filters as filters from pdc.apps.common.filters import MultiValueFilter from . import models class RepoFilter(filters.FilterSet): arch = MultiValueFilter(name='variant_arch__arch__name') content_category = MultiValueFilter(name='content_category__name') content_format = MultiValueFilter(name='content_format__name') release_id = MultiValueFilter(name='variant_arch__variant__release__release_id') variant_uid = MultiValueFilter(name='variant_arch__variant__variant_uid') repo_family = MultiValueFilter(name='repo_family__name') service = MultiValueFilter(name='service__name') shadow = filters.BooleanFilter() product_id = MultiValueFilter() class Meta: model = models.Repo fields = ('arch', 'content_category', 'content_format', 'name', 'release_id', 'repo_family', 'service', 'shadow', 'variant_uid', 'product_id') class RepoFamilyFilter(filters.FilterSet): name = filters.CharFilter(lookup_type="icontains") class Meta: model = models.RepoFamily fields = ('name',)
Streamline the filesystem looping code.
#!/usr/bin/env python import os import sys import subprocess import getopt class Checker: def __init__(self, path): if not os.path.isdir(path): sys.exit(1); self.path = os.path.realpath(path) self.jobs = self.getExecutableFiles(self.path) def getExecutableFiles(self,path): files = [] for dirname, dirnames, filenames in os.walk(path): for filename in filenames: filename_path = os.path.join(dirname, filename) if os.access(filename_path,os.X_OK): files.append(filename_path) return files; def run(self): for job in self.jobs: subprocess.call(job) if __name__ == '__main__': opts, path = getopt.getopt(sys.argv[1], "h") for opt, arg in opts: if opt == '-h': print './main.py /full/path/to/jobs' sys.exit() check = Checker(path) check.run()
#!/usr/bin/env python import os import sys import subprocess import getopt class Chdir: def __init__(self, newPath): self.savedPath = os.getcwd() os.chdir(newPath) class Checker: def __init__(self, path): self.path = path def get_jobs(self): Chdir(self.path) jobs = [] for dirname, dirnames, filenames in os.walk('.'): for filename in filenames: i = os.path.join(dirname, filename) if i != "./__init__.py": jobs.append(self.path + i[2:]) self.run_jobs(jobs) def run_jobs(self, jobs): for job in jobs: subprocess.call(job) if __name__ == '__main__': opts, path = getopt.getopt(sys.argv[1], "h") for opt, arg in opts: if opt == '-h': print './main.py /full/path/to/jobs' sys.exit() check = Checker(path) check.get_jobs()