text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Refactor import path and usage
import os from os.path import dirname import sys import MySQLdb root_path = dirname(dirname(os.getcwd())) require_path = os.path.join(root_path, 'lib\\simplequery') sys.path.append(require_path) from table_data import * from simplequery import * def get_mysql_connection(): args = {'host':'localhost', 'user':'root', 'passwd':'root', 'db':"test"} conn = MySQLdb.connect(**args) with conn.cursor() as c: c.execute('show databases;') print(list(map(lambda x: x[0], c.fetchall()))) return conn def usage(): print('Help:') """ Run file with argv[] """ if __name__ == '__main__': if len(sys.argv) < 2: usage() exit() e = SimpleQueryExecutor() conn = get_mysql_connection() #print(conn) #exit() e.set_connection(conn) filename = sys.argv[1] params = None if len(sys.argv) > 2: params = sys.argv[2:] if os.path.exists(filename): e.run_file(filename, params)
import os import sys import MySQLdb sys.path.append('D:\\Projects\\PySQLKits\\lib\\simplequery') from table_data import * from simplequery import * def get_mysql_connection(): args = {'host':'localhost', 'user':'root', 'passwd':'root', 'db':"test"} conn = MySQLdb.connect(**args) with conn.cursor() as c: c.execute('show databases;') print(list(map(lambda x: x[0], c.fetchall()))) return conn """ """ if __name__ == '__main__': e = SimpleQueryExecutor() conn = get_mysql_connection() #print(conn) #exit() e.set_connection(conn) filename = sys.argv[1] params = None if len(sys.argv) > 2: params = sys.argv[2:] if os.path.exists(filename): e.run_file(filename, params)
Change 'not implemented' log INFO to ERROR
"""Utilities module for of_core OpenFlow v0x04 operations""" from kytos.core import log from kytos.core.switch import Interface def update_flow_list(controller, switch): """Method responsible for request stats of flow to switches. Args: controller(:class:`~kytos.core.controller.Controller`): the controller beeing used. switch(:class:`~kytos.core.switch.Switch`): target to send a stats request. """ log.error("update_flow_list not implemented yet for OF v0x04") def handle_features_reply(controller, event): """Handle OF v0x04 features_reply message events. This is the end of the Handshake workflow of the OpenFlow Protocol. Parameters: controller (Controller): Controller beeing used. event (KytosEvent): Event with features reply message. """ connection = event.source features_reply = event.content['message'] dpid = features_reply.datapath_id.value switch = controller.get_switch_or_create(dpid=dpid, connection=connection) switch.update_features(features_reply) return switch
"""Utilities module for of_core OpenFlow v0x04 operations""" from kytos.core import log from kytos.core.switch import Interface def update_flow_list(controller, switch): """Method responsible for request stats of flow to switches. Args: controller(:class:`~kytos.core.controller.Controller`): the controller beeing used. switch(:class:`~kytos.core.switch.Switch`): target to send a stats request. """ log.info("update_flow_list not implemented yet for OF v0x04") def handle_features_reply(controller, event): """Handle OF v0x04 features_reply message events. This is the end of the Handshake workflow of the OpenFlow Protocol. Parameters: controller (Controller): Controller beeing used. event (KytosEvent): Event with features reply message. """ connection = event.source features_reply = event.content['message'] dpid = features_reply.datapath_id.value switch = controller.get_switch_or_create(dpid=dpid, connection=connection) switch.update_features(features_reply) return switch
Add default value for period of dump.
'use strict'; const rethinkDB = require('rethinkdb'); const program = require('commander'); const UserDB = require('./UserDB'); const metrics = require('./metrics'); program .version('0.0.1') .option('-p, --port <n>', 'Port for WebSocket', parseInt) .option('-d, --dump <n>', 'Period for dump of user positions, sec', parseInt) .option('-d, --dbname [name]', 'Name of world database') .parse(process.argv); if (program.dump === undefined) { program.dump = 60; } if (require.main === module) { const m = new metrics.Metrics(5000); m.runMeasures(); rethinkDB.connect( {host: 'localhost', port: 28015}, function(err, conn) { if (err) throw err; const userDB = new UserDB.UserDB( conn, program.dbname, program.dump, program.port, 100 // location size ); userDB.run(); }); }
'use strict'; const rethinkDB = require('rethinkdb'); const program = require('commander'); const UserDB = require('./UserDB'); const metrics = require('./metrics'); program .version('0.0.1') .option('-p, --port <n>', 'Port for WebSocket', parseInt) .option('-d, --dump <n>', 'Period for dump of user positions, sec', parseInt) .option('-d, --dbname [name]', 'Name of world database') .parse(process.argv); if (require.main === module) { const m = new metrics.Metrics(5000); m.runMeasures(); rethinkDB.connect( {host: 'localhost', port: 28015}, function(err, conn) { if (err) throw err; const userDB = new UserDB.UserDB( conn, program.dbname, program.dump, program.port, 100 // location size ); userDB.run(); }); }
Connect to localhost brick daemon.
package de.graeuler.garden.config; import java.util.EnumMap; public class StaticAppConfig implements AppConfig { private EnumMap<AppConfig.Key, Object> config = new EnumMap<>(Key.class); public StaticAppConfig() { this.config.put(AppConfig.Key.TF_DAEMON_HOST, "localhost"); this.config.put(AppConfig.Key.TF_DAEMON_PORT, Integer.valueOf(4223)); this.config.put(AppConfig.Key.UPLINK_ADRESS, "http://localhost:8081/datafeed/collect/garden"); // this.config.put(AppConfig.Key.API_TOKEN, "non-working-token"); } @Override public Object get(Key key) { if (config.containsKey(key)) return config.get(key); else return key.getDefaultValue(); } @Override public Object get(Key key, Object defaultValue) { return this.config.getOrDefault(key, defaultValue); } }
package de.graeuler.garden.config; import java.util.EnumMap; public class StaticAppConfig implements AppConfig { private EnumMap<AppConfig.Key, Object> config = new EnumMap<>(Key.class); public StaticAppConfig() { this.config.put(AppConfig.Key.TF_DAEMON_HOST, "192.168.1.10"); this.config.put(AppConfig.Key.TF_DAEMON_PORT, Integer.valueOf(4223)); this.config.put(AppConfig.Key.UPLINK_ADRESS, "http://localhost:8081/datafeed/collect/garden"); // this.config.put(AppConfig.Key.API_TOKEN, "non-working-token"); } @Override public Object get(Key key) { if (config.containsKey(key)) return config.get(key); else return key.getDefaultValue(); } @Override public Object get(Key key, Object defaultValue) { return this.config.getOrDefault(key, defaultValue); } }
Remove "(*Classifier).Weight" to prohibit the access to weight vector from the outside.
package perceptron import ( "github.com/mitsuse/perceptron-go/vector" ) type Classifier struct { model *Model } func NewClassifier(indexer Indexer) *Classifier { c := &Classifier{ model: &Model{ weight: vector.NewZeroDense(0), indexer: indexer, }, } return c } func (c *Classifier) Update(learner Learner, instance Instance) error { feature := c.model.Extract(instance, true) score, err := c.model.Score(feature) if err != nil { return err } if score > 0 != (instance.Label() == 1) { return learner.Learn(c.model, instance.Label(), feature) } return nil } func (c *Classifier) Classify(instance Instance) (int, error) { feature := c.model.Extract(instance, false) score, err := c.model.Score(feature) if err != nil { return 0, err } var label int if score > 0 { label = 1 } else { label = -1 } return label, nil } type Indexer interface { Size() int Index(identifier []int32, indexed bool) int }
package perceptron import ( "github.com/mitsuse/perceptron-go/vector" ) type Classifier struct { model *Model } func NewClassifier(indexer Indexer) *Classifier { c := &Classifier{ model: &Model{ weight: vector.NewZeroDense(0), indexer: indexer, }, } return c } func (c *Classifier) Weight() vector.Vector { return c.model.Weight() } func (c *Classifier) Update(learner Learner, instance Instance) error { feature := c.model.Extract(instance, true) score, err := c.model.Score(feature) if err != nil { return err } if score > 0 != (instance.Label() == 1) { return learner.Learn(c.model, instance.Label(), feature) } return nil } func (c *Classifier) Classify(instance Instance) (int, error) { feature := c.model.Extract(instance, false) score, err := c.model.Score(feature) if err != nil { return 0, err } var label int if score > 0 { label = 1 } else { label = -1 } return label, nil } type Indexer interface { Size() int Index(identifier []int32, indexed bool) int }
Write missing tests for ThrowMatcher.
<?php namespace Essence\Matchers; class ThrowMatcherTest extends \MatcherTestCase { protected $subject = "Essence\Matchers\ThrowMatcher"; /** * @test */ public function it_works_as_expected() { $matcher = new ThrowMatcher(function() {}, ["RuntimeException"]); $this->assertFalse($matcher->run()); $this->assertNotNull($matcher->getMessage()); $this->assertFalse((new ThrowMatcher(function() { throw new \Exception; }, ["InvalidArgumentException"]))->run()); $this->assertTrue((new ThrowMatcher(function() { throw new \UnexpectedValueException; }, ["UnexpectedValueException"]))->run()); // Create some sort of "context". $context = new ThrowMatcherTest; $this->assertFalse((new ThrowMatcher(function() { if ($this instanceof ThrowMatcherTest) { throw new \Exception("Hello, world!"); } }, ["Exception", "hello world", $context]))->run()); } }
<?php namespace Essence\Matchers; class ThrowMatcherTest extends \MatcherTestCase { protected $subject = "Essence\Matchers\ThrowMatcher"; /** * @test */ public function it_works_as_expected() { $matcher = new ThrowMatcher(function() {}, ["RuntimeException"]); $this->assertFalse($matcher->run()); $this->assertNotNull($matcher->getMessage()); $this->assertFalse((new ThrowMatcher(function() { throw new \Exception; }, ["InvalidArgumentException"]))->run()); $this->assertTrue((new ThrowMatcher(function() { throw new \UnexpectedValueException; }, ["UnexpectedValueException"]))->run()); } }
[ui][fix] Update cucumber options to new format
package io.syndesis.qe; import com.codeborne.selenide.Configuration; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; import org.junit.BeforeClass; import org.junit.runner.RunWith; @RunWith(Cucumber.class) @CucumberOptions( features = "classpath:features", tags = {"not @wip", "not @manual", "not @deprecated"}, format = {"pretty", "html:target/cucumber/cucumber-html", "junit:target/cucumber/cucumber-junit.xml", "json:target/cucumber/cucumber-report.json"} ) public class CucumberTest extends TestSuiteParent { @BeforeClass public static void setupCucumber() { //set up Selenide Configuration.timeout = TestConfiguration.getConfigTimeout() * 1000; //We will now use custom web driver //Configuration.browser = TestConfiguration.syndesisBrowser(); Configuration.browser = "io.syndesis.qe.CustomWebDriverProvider"; Configuration.browserSize= "1920x1080"; } }
package io.syndesis.qe; import com.codeborne.selenide.Configuration; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; import org.junit.BeforeClass; import org.junit.runner.RunWith; @RunWith(Cucumber.class) @CucumberOptions( features = "classpath:features", tags = "not @wip, @manual, @deprecated", format = {"pretty", "html:target/cucumber/cucumber-html", "junit:target/cucumber/cucumber-junit.xml", "json:target/cucumber/cucumber-report.json"} ) public class CucumberTest extends TestSuiteParent { @BeforeClass public static void setupCucumber() { //set up Selenide Configuration.timeout = TestConfiguration.getConfigTimeout() * 1000; //We will now use custom web driver //Configuration.browser = TestConfiguration.syndesisBrowser(); Configuration.browser = "io.syndesis.qe.CustomWebDriverProvider"; Configuration.browserSize= "1920x1080"; } }
Use the right set of sample names
package org.broadinstitute.sting.gatk.walkers.varianteval.stratifications; import org.broadinstitute.sting.gatk.contexts.ReferenceContext; import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker; import org.broadinstitute.sting.utils.variantcontext.VariantContext; import java.util.ArrayList; public class Sample extends VariantStratifier { // needs the sample names private ArrayList<String> samples; @Override public void initialize() { samples = new ArrayList<String>(); samples.addAll(getVariantEvalWalker().getSampleNamesForStratification()); } public ArrayList<String> getAllStates() { return samples; } public ArrayList<String> getRelevantStates(ReferenceContext ref, RefMetaDataTracker tracker, VariantContext comp, String compName, VariantContext eval, String evalName, String sampleName) { ArrayList<String> relevantStates = new ArrayList<String>(); relevantStates.add(sampleName); return relevantStates; } }
package org.broadinstitute.sting.gatk.walkers.varianteval.stratifications; import org.broadinstitute.sting.gatk.contexts.ReferenceContext; import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker; import org.broadinstitute.sting.utils.variantcontext.VariantContext; import java.util.ArrayList; public class Sample extends VariantStratifier { // needs the sample names private ArrayList<String> samples; @Override public void initialize() { samples = new ArrayList<String>(); samples.addAll(getVariantEvalWalker().getSampleNamesForEvaluation()); } public ArrayList<String> getAllStates() { return samples; } public ArrayList<String> getRelevantStates(ReferenceContext ref, RefMetaDataTracker tracker, VariantContext comp, String compName, VariantContext eval, String evalName, String sampleName) { ArrayList<String> relevantStates = new ArrayList<String>(); relevantStates.add(sampleName); return relevantStates; } }
Add logic for es5 to take in arguments instead of array.
"use strict"; var counter = function() { var numbers = Array.prototype.slice.call(arguments); return numbers.reduce(function(prev, curr) { return prev + curr; }, 0); } var curryItUp = function(fn, firstNumbers) { let args; if (!Array.isArray(firstNumbers)) { args = Array.prototype.slice.call(arguments, 1); } return function(secondNumbers) { let otherArgs; if (!Array.isArray(secondNumbers)) { otherArgs = Array.prototype.slice.call(arguments); return fn.apply(this, Array.prototype.concat.call(args, otherArgs)); } return fn.apply(this, Array.prototype.concat.call(firstNumbers, secondNumbers)); } } const counterES6 = (...numbers) => numbers.reduce((prev, curr) => prev + curr, 0); const curryItUpES6 = (fn, ...firstNumbers) => (...secondNumbers) => { return fn.apply(this, Array.prototype.concat.call(...firstNumbers, ...secondNumbers)); } module.exports = { counter, curryItUp, counterES6, curryItUpES6 }
"use strict"; var counter = function() { var numbers = Array.prototype.slice.call(arguments); return numbers.reduce(function(prev, curr) { return prev + curr; }, 0); } var curryItUp = function(fn) { var args = Array.isArray(Array.prototype.slice.call(arguments, 1)) ? Array.prototype.slice.call(arguments, 1)[0] : Array.prototype.slice.call(arguments, 1); return function() { var otherArgs = Array.isArray(Array.prototype.slice.call(arguments)) ? Array.prototype.slice.call(arguments)[0] : Array.prototype.slice.call(arguments); return fn.apply(this, args.concat(otherArgs)); } } const counterES6 = (...numbers) => numbers.reduce((prev, curr) => prev + curr, 0); const curryItUpES6 = (fn, ...firstNumbers) => (...secondNumbers) => { return fn.apply(this, Array.prototype.concat.call(...firstNumbers, ...secondNumbers)); } module.exports = { counter, curryItUp, counterES6, curryItUpES6 }
Make the example webpack build less noisy
import path from 'path' import fs from 'fs' import HtmlWebpackPlugin from 'html-webpack-plugin' module.exports = { entry: './app.js', output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js' }, devServer: { inline: true, historyApiFallback: true, stats: { colors: true, hash: false, version: false, chunks: false, children: false } }, module: { loaders: [ { test: /\.js$/, loaders: [ 'babel' ], exclude: /node_modules/, include: __dirname } ] }, plugins: [ new HtmlWebpackPlugin({ template: 'index.html', // Load a custom template inject: 'body' // Inject all scripts into the body }) ] } // This will make the redux-auth-wrapper module resolve to the // latest src instead of using it from npm. Remove this if running // outside of the source. const src = path.join(__dirname, '..', '..', 'src') if (fs.existsSync(src)) { // Use the latest src module.exports.resolve = { alias: { 'redux-auth-wrapper': src } } module.exports.module.loaders.push({ test: /\.js$/, loaders: [ 'babel' ], include: src }) }
import path from 'path' import fs from 'fs' import HtmlWebpackPlugin from 'html-webpack-plugin' module.exports = { entry: './app.js', output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js' }, devServer: { inline: true, historyApiFallback: true }, module: { loaders: [ { test: /\.js$/, loaders: [ 'babel' ], exclude: /node_modules/, include: __dirname } ] }, plugins: [ new HtmlWebpackPlugin({ template: 'index.html', // Load a custom template inject: 'body' // Inject all scripts into the body }) ] } // This will make the redux-auth-wrapper module resolve to the // latest src instead of using it from npm. Remove this if running // outside of the source. const src = path.join(__dirname, '..', '..', 'src') if (fs.existsSync(src)) { // Use the latest src module.exports.resolve = { alias: { 'redux-auth-wrapper': src } } module.exports.module.loaders.push({ test: /\.js$/, loaders: [ 'babel' ], include: src }) }
Add todo for color extract
from keras import backend as K from keras.layers import Layer # TODO REMOVE class ColorExtract(Layer): """ TODO: Make is scalable to any amount of channels. """ def __init__(self, channel, **kwargs): super().__init__(**kwargs) assert channel in (0, 1, 2) self.channel = channel def call(self, x, mask=None): return x[:, :, :, (self.channel*256):(self.channel+1)*256] def get_output_shape_for(self, input_shape): output = list(input_shape) return (output[0], output[1], output[2], 256) def get_config(self): return dict(list(super().get_config().items()) + list({'channel': self.channel}.items()))
from keras import backend as K from keras.layers import Layer class ColorExtract(Layer): """ TODO: Make is scalable to any amount of channels. """ def __init__(self, channel, **kwargs): super().__init__(**kwargs) assert channel in (0, 1, 2) self.channel = channel def call(self, x, mask=None): return x[:, :, :, (self.channel*256):(self.channel+1)*256] def get_output_shape_for(self, input_shape): output = list(input_shape) return (output[0], output[1], output[2], 256) def get_config(self): return dict(list(super().get_config().items()) + list({'channel': self.channel}.items()))
Add "Changes Planned" and "In Preparation" states for revisions Summary: Ref T2222. Discussion in T4481. Ref T2543. Primarily, this will let me fix some of the rough edges that came out of ApplicationTransactions and state-based transitions. I'm also adding a constant for T2543 while I'm in here. Test Plan: Used `grep` to look for any weird special behavior, didn't see any. Reviewers: btrahan Reviewed By: btrahan CC: aran Maniphest Tasks: T2543, T2222 Differential Revision: https://secure.phabricator.com/D8400
<?php final class ArcanistDifferentialRevisionStatus { const NEEDS_REVIEW = 0; const NEEDS_REVISION = 1; const ACCEPTED = 2; const CLOSED = 3; const ABANDONED = 4; const CHANGES_PLANNED = 5; const IN_PREPARATION = 6; public static function getNameForRevisionStatus($status) { $map = array( self::NEEDS_REVIEW => pht('Needs Review'), self::NEEDS_REVISION => pht('Needs Revision'), self::ACCEPTED => pht('Accepted'), self::CLOSED => pht('Closed'), self::ABANDONED => pht('Abandoned'), self::CHANGES_PLANNED => pht('Changes Planned'), self::IN_PREPARATION => pht('In Preparation'), ); return idx($map, coalesce($status, '?'), 'Unknown'); } }
<?php final class ArcanistDifferentialRevisionStatus { const NEEDS_REVIEW = 0; const NEEDS_REVISION = 1; const ACCEPTED = 2; const CLOSED = 3; const ABANDONED = 4; public static function getNameForRevisionStatus($status) { static $map = array( self::NEEDS_REVIEW => 'Needs Review', self::NEEDS_REVISION => 'Needs Revision', self::ACCEPTED => 'Accepted', self::CLOSED => 'Closed', self::ABANDONED => 'Abandoned', ); return idx($map, coalesce($status, '?'), 'Unknown'); } }
Decrease user and group IDs from 1000 to 0.
# Basic config for stuff that can be easily changed, but which is git-managed. # See also apikeys_sample.py for the configs which are _not_ git-managed. app_name = "fore" server_domain = "http://www.infiniteglitch.net" lag_limit = 88200 # samples - how much we can lag by before dropping frames. restart_timeout = 3 # seconds between polls to restart.txt http_port = 8888 mini_http_port = 8193 uid = 0 # User ID and group ID to drop privileges to gid = 0 # Set both to 0 to not drop privileges, eg if the server is started without privs use_sudo_uid_gid = True # If set, uid/gid will be overridden with SUDO_UID/SUDO_GID if available frontend_buffer = 20 # seconds of audio to buffer in frontend past_played_buffer = 600 # seconds of audio to store track metadata for in the past template_dir = "templates/" drift_limit = 0.1 # seconds of audio after which drift should be corrected max_track_length = 400 min_track_length = 90 # Default values when nothing exists no_bpm_diff = 20
# Basic config for stuff that can be easily changed, but which is git-managed. # See also apikeys_sample.py for the configs which are _not_ git-managed. app_name = "fore" server_domain = "http://www.infiniteglitch.net" lag_limit = 88200 # samples - how much we can lag by before dropping frames. restart_timeout = 3 # seconds between polls to restart.txt http_port = 8888 mini_http_port = 8193 uid = 1000 # User ID and group ID to drop privileges to gid = 1000 # Set both to 0 to not drop privileges, eg if the server is started without privs use_sudo_uid_gid = True # If set, uid/gid will be overridden with SUDO_UID/SUDO_GID if available frontend_buffer = 20 # seconds of audio to buffer in frontend past_played_buffer = 600 # seconds of audio to store track metadata for in the past template_dir = "templates/" drift_limit = 0.1 # seconds of audio after which drift should be corrected max_track_length = 400 min_track_length = 90 # Default values when nothing exists no_bpm_diff = 20
Throw exception if native returns null, until native is fixed
/* (C) 2014 Peter Conrad * All rights reserved. */ package de.quisquis.ec.impl.pp; import de.quisquis.ec.Decrypter; import java.security.PrivateKey; import java.security.PublicKey; import java.security.interfaces.ECPrivateKey; /** * * @author Peter Conrad */ public class CryptoppDecrypter implements Decrypter { private final EcData keyData; public CryptoppDecrypter(PrivateKey priv, PublicKey pub) { keyData = new EcData((ECPrivateKey) priv); } @Override public byte[] decrypt(byte[] ciphertext) { byte result[] = CryptoppNative.decrypt(ciphertext, keyData.curveModulus, keyData.curveA, keyData.curveB, keyData.gX, keyData.gY,keyData.n, keyData.x); if (result == null) { throw new IllegalStateException("Decryption failed!"); } return result; } }
/* (C) 2014 Peter Conrad * All rights reserved. */ package de.quisquis.ec.impl.pp; import de.quisquis.ec.Decrypter; import java.security.PrivateKey; import java.security.PublicKey; import java.security.interfaces.ECPrivateKey; /** * * @author Peter Conrad */ public class CryptoppDecrypter implements Decrypter { private final EcData keyData; public CryptoppDecrypter(PrivateKey priv, PublicKey pub) { keyData = new EcData((ECPrivateKey) priv); } @Override public byte[] decrypt(byte[] ciphertext) { return CryptoppNative.decrypt(ciphertext, keyData.curveModulus, keyData.curveA, keyData.curveB, keyData.gX, keyData.gY, keyData.n, keyData.x); } }
Delete extra white space at bottom of doc
var colors = ["red", "blue", "magenta", "yellow"] var names = ["Dan", "Dave", "Eleanor", "Rupert"] colors.push("green") names.push("Nathaniel") happyHorses = {} for (i = 0; i < names.length; i++) { happyHorses[names[i]] = colors[i] } console.log(happyHorses) // โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€” function Car(color, manual, make) { console.log("Our new car:", this); this.color = color; this.manual = manual; this.make = make; this.drive = function() {console.log(this.color + " " + this.make + " went vroom!");}; console.log("Have fun driving your new car :)") } var firstCar = new Car("black", true, "Honda"); var secondCar = new Car("green", false, "Toyota") var thirdCar = new Car("silver", false, "Lexus") console.log(Car) firstCar.drive(); thirdCar.drive();
var colors = ["red", "blue", "magenta", "yellow"] var names = ["Dan", "Dave", "Eleanor", "Rupert"] colors.push("green") names.push("Nathaniel") happyHorses = {} for (i = 0; i < names.length; i++) { happyHorses[names[i]] = colors[i] } console.log(happyHorses) // โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€” function Car(color, manual, make) { console.log("Our new car:", this); this.color = color; this.manual = manual; this.make = make; this.drive = function() {console.log(this.color + " " + this.make + " went vroom!");}; console.log("Have fun driving your new car :)") } var firstCar = new Car("black", true, "Honda"); var secondCar = new Car("green", false, "Toyota") var thirdCar = new Car("silver", false, "Lexus") console.log(Car) firstCar.drive(); thirdCar.drive();
Remove body from configuration options Merging `body` with defaults was problematic since `body` is not always an object. For example, it might be `FormData`.
/** * Prepare request configuration, deeply merging some specific keys */ var assign = require('./assign') var toArray = require('./toArray') var DEFAULTS = { baseURL : '/', basePath : '', params : undefined, headers : { 'Accept': 'application/json' }, method : 'GET', path : '', query : {}, timeout : 15000, type : 'application/json', buildQuery : function(query) { return query }, beforeSend : function(ajax) { return ajax }, onResponse : function(response) { return response.body }, onError : function(error) { return error }, Promise : global.Promise } module.exports = function prepare (/* options list */) { var options = [ DEFAULTS ].concat(toArray(arguments)) return options.reduce(function (memo, next) { return next ? assign(memo, next, { params : assign(memo.params, next.params), query : assign(memo.query, next.query), headers : assign(memo.headers, next.headers) }) : memo }, {}) }
/** * Prepare request configuration, deeply merging some specific keys */ var assign = require('./assign') var toArray = require('./toArray') var DEFAULTS = { baseURL : '/', basePath : '', body : undefined, params : undefined, headers : { 'Accept': 'application/json' }, method : 'GET', path : '', query : {}, timeout : 15000, type : 'application/json', buildQuery : function(query) { return query }, beforeSend : function(ajax) { return ajax }, onResponse : function(response) { return response.body }, onError : function(error) { return error }, Promise : global.Promise } module.exports = function prepare (/* options list */) { var options = [ DEFAULTS ].concat(toArray(arguments)) return options.reduce(function (memo, next) { return next ? assign(memo, next, { body : next.body ? assign(memo.body, next.body) : next.body, params : assign(memo.params, next.params), query : assign(memo.query, next.query), headers : assign(memo.headers, next.headers) }) : memo }, {}) }
Make sure we're comparing integers in positive_integer
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. def boolean(x): if x in [True, 1, '1', 'true', 'True']: return "true" if x in [False, 0, '0', 'false', 'False']: return "false" raise ValueError def integer(x): if isinstance(x, int): return x if isinstance(x, basestring): int(x) return x def positive_integer(x): p = integer(x) if int(p) < 0: raise ValueError return x def integer_range(minimum_val, maximum_val): def integer_range_checker(x): i = int(x) if i < minimum_val or i > maximum_val: raise ValueError('Integer must be between %d and %d' % ( minimum_val, maximum_val)) return x return integer_range_checker def network_port(x): from . import AWSHelperFn # Network ports can be Ref items if isinstance(x, AWSHelperFn): return x i = int(x) if i < -1 or i > 65535: raise ValueError return x
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. def boolean(x): if x in [True, 1, '1', 'true', 'True']: return "true" if x in [False, 0, '0', 'false', 'False']: return "false" raise ValueError def integer(x): if isinstance(x, int): return x if isinstance(x, basestring): int(x) return x def positive_integer(x): p = integer(x) if p < 0: raise ValueError return x def integer_range(minimum_val, maximum_val): def integer_range_checker(x): i = int(x) if i < minimum_val or i > maximum_val: raise ValueError('Integer must be between %d and %d' % ( minimum_val, maximum_val)) return x return integer_range_checker def network_port(x): from . import AWSHelperFn # Network ports can be Ref items if isinstance(x, AWSHelperFn): return x i = int(x) if i < -1 or i > 65535: raise ValueError return x
Remove package requirements (for testing only); add download URL
from distutils.core import setup long_description = open('README.rst').read() setup( name = 'lcboapi', packages = ['lcboapi'], version = '0.1.3', description = 'Python wrapper for the unofficial LCBO API', long_description = long_description, author = 'Shane Martin', author_email = 'dev.sh@nemart.in', license='MIT License', url = 'https://github.com/shamrt/LCBOAPI', download_url = 'https://github.com/shamrt/LCBOAPI/archive/v0.1.3.tar.gz', keywords = ['api', 'lcbo'], platforms = ['any'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Environment :: Web Environment', ], )
from distutils.core import setup long_description = open('README.rst').read() setup( name = 'lcboapi', packages = ['lcboapi'], version = '0.1.3', description = 'Python wrapper for the unofficial LCBO API', long_description = long_description, author = 'Shane Martin', author_email = 'dev.sh@nemart.in', license='MIT License', url = 'https://github.com/shamrt/LCBOAPI', install_requires = ['pytest==2.7.2'], keywords = ['api', 'lcbo'], platforms = ['any'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Environment :: Web Environment', ], )
Disable L3 agents scheduler extension in Tempest Change-Id: Ibc2d85bce9abb821e897693ebdade66d3b9199c3 Closes-Bug: #1707496
# # 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. # If you update this list, please also update # doc/source/features.rst. # NOTE (dimak): This used only for tempest's enabled network API extensions SUPPORTED_API_EXTENSIONS = [ 'agent', 'quotas', 'extra_dhcp_opt', 'binding', 'dhcp_agent_scheduler', 'security-group', 'external-net', 'router', 'subnet_allocation', 'port-security', 'allowed-address-pairs', 'net-mtu', 'default-subnetpools', 'extraroute', 'bgp', 'trunk', 'flow_classifier', 'sfc', ]
# # 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. # If you update this list, please also update # doc/source/features.rst. SUPPORTED_API_EXTENSIONS = [ 'agent', 'quotas', 'extra_dhcp_opt', 'binding', 'dhcp_agent_scheduler', 'security-group', 'external-net', 'router', 'l3_agent_scheduler', 'subnet_allocation', 'port-security', 'allowed-address-pairs', 'net-mtu', 'default-subnetpools', 'extraroute', 'bgp', 'trunk', 'flow_classifier', 'sfc', ]
Implement following via many-to-many relation
import Knex from 'knex'; import Bookshelf from 'bookshelf'; export default function initBookshelf(config) { let knex = Knex(config); let bookshelf = Bookshelf(knex); bookshelf.plugin('registry'); bookshelf.plugin('visibility'); let User, Post; User = bookshelf.Model.extend({ tableName: 'users', posts: function() { return this.hasMany(Post, 'user_id'); }, following: function() { return this.belongsToMany(User, 'user_id', 'followers', 'user_id'); }, followers: function() { return this.belongsToMany(User, 'user_id', 'followers', 'following_user_id'); }, hidden: ['hashed_password', 'email'] // exclude from json-exports }); Post = bookshelf.Model.extend({ tableName: 'posts', user: function() { return this.belongsTo(User, 'user_id'); } }); let Posts Posts = bookshelf.Collection.extend({ model: Post }); // adding to registry bookshelf.model('User', User); bookshelf.model('Post', Post); bookshelf.collection('Posts', Posts); return bookshelf; }
import Knex from 'knex'; import Bookshelf from 'bookshelf'; export default function initBookshelf(config) { let knex = Knex(config); let bookshelf = Bookshelf(knex); bookshelf.plugin('registry'); bookshelf.plugin('visibility'); let User, Post, Following; User = bookshelf.Model.extend({ tableName: 'users', posts: function() { return this.hasMany(Post, 'user_id'); }, following: function() { return this.hasMany(Following, 'user_id'); }, followers: function() { return this.hasMany(Following, 'following_user_id'); }, hidden: ['hashed_password', 'email'] // exclude from json-exports }); Following = bookshelf.Model.extend({ tableName: 'followers', user: function() { return this.belongsTo(User, 'user_id'); }, following: function() { return this.hasOne(User, 'following_user_id'); }, hidden: ['hashed_password', 'email'] // exclude from json-exports }); Post = bookshelf.Model.extend({ tableName: 'posts', user: function() { return this.belongsTo(User, 'user_id'); } }); let Posts Posts = bookshelf.Collection.extend({ model: Post }); // adding to registry bookshelf.model('User', User); bookshelf.model('Post', Post); bookshelf.model('Following', Following); bookshelf.collection('Posts', Posts); return bookshelf; }
Use to store activeCategory for filtering
// js/controllers/nw-category-select.controller (function() { "use strict"; angular.module("NoteWrangler") .controller("nwCategorySelectController", nwCategorySelectController); nwCategorySelectController.$inject = ["Category", "$scope"]; function nwCategorySelectController(Category, $scope) { let vm = this; vm.query = _query; vm.getActiveCategory = _getActiveCategory; vm.setActiveCategory = _setActiveCategory; vm.getCategoryCount = _getCategoryCount; function _query() { return Category.query(); } function _getActiveCategory() { return vm.activeCategory; } function _setActiveCategory(newCategory) { vm.activeCategory = newCategory.name; // need refactoring $scope.activeCategory = newCategory.name; } function _getCategoryCount(notes, category) { let categoryNotes = notes.filter( (v) => { return v.category.name == category.name; }); return categoryNotes.length; } } })();
// js/controllers/nw-category-select.controller (function() { "use strict"; angular.module("NoteWrangler") .controller("nwCategorySelectController", nwCategorySelectController); nwCategorySelectController.$inject = ["Category"]; function nwCategorySelectController(Category) { let vm = this; vm.query = _query; vm.getActiveCategory = _getActiveCategory; vm.setActiveCategory = _setActiveCategory; vm.getCategoryCount = _getCategoryCount; function _query() { return Category.query(); } function _getActiveCategory() { return vm.activeCategory; } function _setActiveCategory(newCategory) { vm.activeCategory = newCategory.name; } function _getCategoryCount(notes, category) { let categoryNotes = notes.filter( (v) => { return v.category.name == category.name; }); return categoryNotes.length; } } })();
Add the real description to events in the ics feed. Signed-off-by: Franรงois de Metz <5187da0b934cc25eb2201a3ec9206c24b13cb23b@stormz.me>
var icalendar = require('icalendar'); exports.generateIcal = function(boards) { var ical = new icalendar.iCalendar(); boards.each(function(board) { board.cards().each(function(card) { // no arm, no chocolate if (!card.get('badges').due) return; var event = new icalendar.VEvent(card.id); event.setSummary(card.get('name')); event.setDescription(card.get('desc')); event.setDate(card.get('badges').due); event.addProperty('ATTACH', card.get('url')); event.addProperty('URL', card.get('url')); ical.addComponent(event); }); }); return ical; }
var icalendar = require('icalendar'); exports.generateIcal = function(boards) { var ical = new icalendar.iCalendar(); boards.each(function(board) { board.cards().each(function(card) { // no arm, no chocolate if (!card.get('badges').due) return; var event = new icalendar.VEvent(card.id); event.setSummary(card.get('name')); event.setDescription(card.get('description')); event.setDate(card.get('badges').due); event.addProperty('ATTACH', card.get('url')); event.addProperty('URL', card.get('url')); ical.addComponent(event); }); }); return ical; }
Work on MySQL schema builder.
<?php namespace Illuminate\Database\Schema; class MySqlBuilder extends Builder { /** * Determine if the given table exists. * * @param string $table * @return bool */ public function hasTable($table) { $table = $this->connection->getTablePrefix().$table; return count($this->connection->select( $this->grammar->compileTableExists(), [$this->connection->getDatabaseName(), $table] )) > 0; } /** * Get the column listing for a given table. * * @param string $table * @return array */ public function getColumnListing($table) { $table = $this->connection->getTablePrefix().$table; $results = $this->connection->select( $this->grammar->compileColumnListing(), [$this->connection->getDatabaseName(), $table] ); return $this->connection->getPostProcessor()->processColumnListing($results); } }
<?php namespace Illuminate\Database\Schema; class MySqlBuilder extends Builder { /** * Determine if the given table exists. * * @param string $table * @return bool */ public function hasTable($table) { $sql = $this->grammar->compileTableExists(); $database = $this->connection->getDatabaseName(); $table = $this->connection->getTablePrefix().$table; return count($this->connection->select($sql, [$database, $table])) > 0; } /** * Get the column listing for a given table. * * @param string $table * @return array */ public function getColumnListing($table) { $sql = $this->grammar->compileColumnListing(); $database = $this->connection->getDatabaseName(); $table = $this->connection->getTablePrefix().$table; $results = $this->connection->select($sql, [$database, $table]); return $this->connection->getPostProcessor()->processColumnListing($results); } }
Upgrade from alpha to beta
# -*- coding: utf-8 -*- # from __future__ import print_function from setuptools import setup, find_packages import tunic DESCRIPTION = 'Deployment related Fabric utilities' AUTHOR = 'TSH Labs' EMAIL = 'projects@tshlabs.org' URL = 'http://www.tshlabs.org/' LICENSE = 'MIT' CLASSIFIERS = [ "Development Status :: 4 - Beta", "License :: OSI Approved :: MIT License", "Operating System :: POSIX", "Programming Language :: Python", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Topic :: System :: Installation/Setup" ] def get_contents(filename): """Get the contents of the given file.""" with open(filename, 'rb') as handle: return handle.read().decode('utf-8') REQUIRES = [ 'fabric' ] README = get_contents('README.rst') setup( name='tunic', version=tunic.__version__, author=AUTHOR, description=DESCRIPTION, long_description=README, author_email=EMAIL, classifiers=CLASSIFIERS, license=LICENSE, url=URL, zip_safe=True, install_requires=REQUIRES, packages=find_packages())
# -*- coding: utf-8 -*- # from __future__ import print_function from setuptools import setup, find_packages import tunic DESCRIPTION = 'Deployment related Fabric utilities' AUTHOR = 'TSH Labs' EMAIL = 'projects@tshlabs.org' URL = 'http://www.tshlabs.org/' LICENSE = 'MIT' CLASSIFIERS = [ "Development Status :: 3 - Alpha", "License :: OSI Approved :: MIT License", "Operating System :: POSIX", "Programming Language :: Python", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Topic :: System :: Installation/Setup" ] def get_contents(filename): """Get the contents of the given file.""" with open(filename, 'rb') as handle: return handle.read().decode('utf-8') REQUIRES = [ 'fabric' ] README = get_contents('README.rst') setup( name='tunic', version=tunic.__version__, author=AUTHOR, description=DESCRIPTION, long_description=README, author_email=EMAIL, classifiers=CLASSIFIERS, license=LICENSE, url=URL, zip_safe=True, install_requires=REQUIRES, packages=find_packages())
Make cleanup checks command terminate
package main import "fmt" func commandCleanupChecks(done chan bool, printOnly bool) { if !printOnly { dbOpen() } stmts := []string{ `DELETE FROM check_instance_configurations;`, `DELETE FROM check_instance_configuration_dependencies;`, `DELETE FROM check_instances;`, `DELETE FROM checks;`, `DELETE FROM configuration_thresholds;`, `DELETE FROM constraints_custom_property;`, `DELETE FROM constraints_native_property;`, `DELETE FROM constraints_oncall_property;`, `DELETE FROM constraints_service_attribute;`, `DELETE FROM constraints_service_property;`, `DELETE FROM constraints_system_property;`, `DELETE FROM check_configurations;`, } for _, stmt := range stmts { if printOnly { fmt.Println(stmt) continue } db.Exec(stmt) } done <- true } // vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix
package main import "fmt" func commandCleanupChecks(done chan bool, printOnly bool) { if !printOnly { dbOpen() } stmts := []string{ `DELETE FROM check_instance_configurations;`, `DELETE FROM check_instance_configuration_dependencies;`, `DELETE FROM check_instances;`, `DELETE FROM checks;`, `DELETE FROM configuration_thresholds;`, `DELETE FROM constraints_custom_property;`, `DELETE FROM constraints_native_property;`, `DELETE FROM constraints_oncall_property;`, `DELETE FROM constraints_service_attribute;`, `DELETE FROM constraints_service_property;`, `DELETE FROM constraints_system_property;`, `DELETE FROM check_configurations;`, } for _, stmt := range stmts { if printOnly { fmt.Println(stmt) continue } db.Exec(stmt) } } // vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix
Add a quick url for voting for demo winners This needs to be removed after May 4th, 2017
var express = require('express'); module.exports = (keystone) => { let router = express.Router(); /* GET home page. */ router.get('/', function(req, res) { res.render('index', {title: 'Exchange.js'}); }); router.get('/talks', (req, res) => { keystone.list('Talk').model.find() .sort('-presentedOn') .populate('speaker') .exec((err, talks) => { res.render('talks', { title: 'Talks | Exchange.js', talks: talks }); }); }); router.get('/:page', function(req, res, next) { keystone.list('Page').model.findOne({ state: 'published', slug: req.params.page }).exec(function(err, result) { if (!result) { return next(); } res.render('page', { title: result.title, content: result.content.html }); }); }); // REDIRECT TO DEMO NIGHT VOTE FORM // REMOVE AFTER MAY 4TH 2017 router.get('/vote', function(req, res) { res.redirect('https://docs.google.com/forms/d/e/1FAIpQLScCJjxmCA8Zg4ONi0UzV32d59-j1w0cHKgQK4iDMdE9EJZdvQ/viewform?usp=sf_link'); }); return router; }
var express = require('express'); module.exports = (keystone) => { let router = express.Router(); /* GET home page. */ router.get('/', function(req, res) { res.render('index', {title: 'Exchange.js'}); }); router.get('/talks', (req, res) => { keystone.list('Talk').model.find() .sort('-presentedOn') .populate('speaker') .exec((err, talks) => { res.render('talks', { title: 'Talks | Exchange.js', talks: talks }); }); }); router.get('/:page', function(req, res, next) { keystone.list('Page').model.findOne({ state: 'published', slug: req.params.page }).exec(function(err, result) { if (!result) { return next(); } res.render('page', { title: result.title, content: result.content.html }); }); }); return router; }
Mark these tests on FreeBSD and Linux as non-flakey. We don't know that they are git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@257656 91177308-0d34-0410-b5e6-96231b3b80d8
""" Test that LLDB correctly allows scripted commands to set an immediate output file """ from __future__ import print_function import os, time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import * class CommandScriptImmediateOutputTestCase (PExpectTest): mydir = TestBase.compute_mydir(__file__) def setUp(self): # Call super's setUp(). PExpectTest.setUp(self) @skipIfRemote # test not remote-ready llvm.org/pr24813 @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows") def test_command_script_immediate_output (self): """Test that LLDB correctly allows scripted commands to set an immediate output file.""" self.launch(timeout=5) script = os.path.join(os.getcwd(), 'custom_command.py') prompt = "(lldb)" self.sendline('command script import %s' % script, patterns=[prompt]) self.sendline('command script add -f custom_command.command_function mycommand', patterns=[prompt]) self.sendline('mycommand', patterns='this is a test string, just a test string') self.sendline('command script delete mycommand', patterns=[prompt]) self.quit(gracefully=False)
""" Test that LLDB correctly allows scripted commands to set an immediate output file """ from __future__ import print_function import os, time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import * class CommandScriptImmediateOutputTestCase (PExpectTest): mydir = TestBase.compute_mydir(__file__) def setUp(self): # Call super's setUp(). PExpectTest.setUp(self) @skipIfRemote # test not remote-ready llvm.org/pr24813 @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot") @expectedFlakeyLinux("llvm.org/pr25172") @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows") def test_command_script_immediate_output (self): """Test that LLDB correctly allows scripted commands to set an immediate output file.""" self.launch(timeout=5) script = os.path.join(os.getcwd(), 'custom_command.py') prompt = "(lldb)" self.sendline('command script import %s' % script, patterns=[prompt]) self.sendline('command script add -f custom_command.command_function mycommand', patterns=[prompt]) self.sendline('mycommand', patterns='this is a test string, just a test string') self.sendline('command script delete mycommand', patterns=[prompt]) self.quit(gracefully=False)
Edit field encapsulation for cache
"use strict"; var Cache = require('./Cache'), inherits = require('inherits'); var MemCache = function () { this._cache = { }; this._timestamps = { }; this._expireTime = 1000 * 60 * 10; }; inherits(MemCache, Cache); MemCache.prototype.setData = function (tag, data) { if (tag) { this._timestamps[tag] = getCurrentTimestamp(); this._cache = data; } }; MemCache.prototype.getData = function (tag) { if (!tag) return null; if (getCurrentTimestamp() - this._timestamps[tag] < this._expireTime) return this._cache[tag]; return null; }; MemCache.prototype.expire = function (tag) { if (tag) { this._cache[tag] = null; this._timestamps[tag] = null; } }; MemCache.prototype.expireAll = function () { this._cache = []; this._timestamps = []; }; MemCache.prototype.setExpireTime = function (milliseconds) { this._expireTime = milliseconds; }; function getCurrentTimestamp() { return Date.now(); } module.exports = MemCache;
"use strict"; var Cache = require('./Cache'), inherits = require('inherits'); var MemCache = function () { this._cache = { }; this._timestamps = { }; this._expireTime = 1000 * 60 * 10; }; inherits(MemCache, Cache); MemCache.prototype.setData = function (tag, data) { if (tag) this.timestamps[tag] = getCurrentTimestamp(); }; MemCache.prototype.getData = function (tag) { if (!tag) return null; if (getCurrentTimestamp() - this.timestamps[tag] < this.expireTime) return this.cache[tag]; return null; }; MemCache.prototype.expire = function (tag) { if (tag) { this.cache[tag] = null; this.timestamps[tag] = null; } }; MemCache.prototype.expireAll = function () { this.cache = []; this.timestamps = []; }; MemCache.prototype.setExpireTime = function (milliseconds) { this.expireTime = milliseconds; }; function getCurrentTimestamp() { return Date.now(); } module.exports = MemCache;
Throw RuntimeException if new type is not added here also
/* * Copyright 2014-2015 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hawkular.metrics.api.jaxrs.util; import org.hawkular.metrics.core.api.MetricType; /** * Returns the longer path format used by the REST-interface from the given MetricType * * @author Michael Burman */ public class MetricTypeTextConverter { private MetricTypeTextConverter() { } public static String getLongForm(MetricType<?> mt) { if(mt == MetricType.GAUGE) { return "gauges"; } else if(mt == MetricType.COUNTER) { return "counters"; } else if(mt == MetricType.AVAILABILITY) { return mt.getText(); } else { throw new RuntimeException("Unsupported type " + mt.getText()); } } }
/* * Copyright 2014-2015 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hawkular.metrics.api.jaxrs.util; import org.hawkular.metrics.core.api.MetricType; /** * Returns the longer path format used by the REST-interface from the given MetricType * * @author Michael Burman */ public class MetricTypeTextConverter { private MetricTypeTextConverter() { } public static String getLongForm(MetricType<?> mt) { if(mt == MetricType.GAUGE) { return "gauges"; } else if(mt == MetricType.COUNTER) { return "counters"; } else { return mt.getText(); } } }
Add trailing new line to compiled output
'use strict'; var to5 = require('6to5'); var anymatch = require('anymatch'); function ES6to5Compiler(config) { if (!config) config = {}; var options = config.plugins && config.plugins.ES6to5 || {}; this.options = {}; Object.keys(options).forEach(function(key) { if (key === 'sourceMap' || key === 'ignore') return; this.options[key] = options[key]; }, this); this.options.sourceMap = !!config.sourceMaps; this.isIgnored = anymatch(options.ignore || /^(bower_components|vendor)/); } ES6to5Compiler.prototype.brunchPlugin = true; ES6to5Compiler.prototype.type = 'javascript'; ES6to5Compiler.prototype.extension = 'js'; ES6to5Compiler.prototype.compile = function (params, callback) { if (this.isIgnored(params.path)) return callback(null, params); this.options.filename = params.path; var compiled; try { compiled = to5.transform(params.data, this.options); } catch (err) { return callback(err); } var result = {data: compiled.code || compiled}; // Concatenation is broken by trailing comments in files, which occur // frequently when comment nodes are lost in the AST from 6to5. result.data += '\n'; if (compiled.map) result.map = JSON.stringify(compiled.map); callback(null, result); }; module.exports = ES6to5Compiler;
'use strict'; var to5 = require('6to5'); var anymatch = require('anymatch'); function ES6to5Compiler(config) { if (!config) config = {}; var options = config.plugins && config.plugins.ES6to5 || {}; this.options = {}; Object.keys(options).forEach(function(key) { if (key === 'sourceMap' || key === 'ignore') return; this.options[key] = options[key]; }, this); this.options.sourceMap = !!config.sourceMaps; this.isIgnored = anymatch(options.ignore || /^(bower_components|vendor)/); } ES6to5Compiler.prototype.brunchPlugin = true; ES6to5Compiler.prototype.type = 'javascript'; ES6to5Compiler.prototype.extension = 'js'; ES6to5Compiler.prototype.compile = function (params, callback) { if (this.isIgnored(params.path)) return callback(null, params); this.options.filename = params.path; var compiled; try { compiled = to5.transform(params.data, this.options); } catch (err) { return callback(err); } var result = {data: compiled.code || compiled}; if (compiled.map) result.map = JSON.stringify(compiled.map); callback(null, result); }; module.exports = ES6to5Compiler;
Add X-XSS-Protection header absence test
const frisby = require('frisby') const URL = 'http://localhost:3000' describe('HTTP', function () { it('response must contain CORS header allowing all origins', function (done) { frisby.get(URL) .expect('status', 200) .expect('header', 'Access-Control-Allow-Origin', '*') .done(done) }) it('response must contain sameorigin frameguard header', function (done) { frisby.get(URL) .expect('status', 200) .expect('header', 'X-Frame-Options', 'sameorigin') .done(done) }) it('response must contain CORS header allowing all origins', function (done) { frisby.get(URL) .expect('status', 200) .expect('header', 'X-Content-Type-Options', 'nosniff') .done(done) }) it('response must not contain XSS protection header', function (done) { frisby.get(URL) .expect('status', 200) .expectNot('header', 'X-XSS-Protection') .done(done) }) })
const frisby = require('frisby') const URL = 'http://localhost:3000' describe('HTTP', function () { it('response must contain CORS header allowing all origins', function (done) { frisby.get(URL) .expect('status', 200) .expect('header', 'Access-Control-Allow-Origin', '*') .done(done) }) it('response must contain sameorigin frameguard header', function (done) { frisby.get(URL) .expect('status', 200) .expect('header', 'X-Frame-Options', 'sameorigin') .done(done) }) it('response must contain CORS header allowing all origins', function (done) { frisby.get(URL) .expect('status', 200) .expect('header', 'X-Content-Type-Options', 'nosniff') .done(done) }) })
Change template URLs to relative
var CenterScout = angular.module('CenterScout', ['ngRoute']); CenterScout.config(function($routeProvider) { $routeProvider.when('/', { controller: 'HomeController', templateUrl: 'views/home.html' }); $routeProvider.when('/home', { controller: 'HomeController', templateUrl: 'views/home.html' }); $routeProvider.when('/class', { controller: 'ClassController', templateUrl: 'views/class.html' }); $routeProvider.when('/about', { controller: 'AboutController', templateUrl: 'views/about.html' }); $routeProvider.when('/404', { controller: 'ErrorController', templateUrl: 'views/404.html' }); $routeProvider.otherwise({ redirectTo: '/404' }); });
var CenterScout = angular.module('CenterScout', ['ngRoute']); CenterScout.config(function($routeProvider) { $routeProvider.when('/', { controller: 'HomeController', templateUrl: '/views/home.html' }); $routeProvider.when('/home', { controller: 'HomeController', templateUrl: '/views/home.html' }); $routeProvider.when('/class', { controller: 'ClassController', templateUrl: '/views/class.html' }); $routeProvider.when('/about', { controller: 'AboutController', templateUrl: '/views/about.html' }); $routeProvider.when('/404', { controller: 'ErrorController', templateUrl: '/views/404.html' }); $routeProvider.otherwise({ redirectTo: '/404' }); });
Add entrypoint for Dusty client
import os import sys import imp from setuptools import find_packages try: from restricted_pkg import setup except: # allow falling back to setuptools only if # we are not trying to upload if 'upload' in sys.argv: raise ImportError('restricted_pkg is required to upload, first do pip install restricted_pkg') from setuptools import setup requirements = imp.load_source('requirements', os.path.realpath('requirements.py')) setup( name='dusty', version='0.0.1', description='Docker-based development environment manager', url='https://github.com/gamechanger/dusty', private_repository='gamechanger', author='GameChanger', author_email='travis@gamechanger.io', packages=find_packages(), install_requires=requirements.install_requires, tests_require=requirements.test_requires, test_suite="nose.collector", entry_points={'console_scripts': ['dustyd = dusty.daemon:main', 'dusty = dusty.client:main']}, zip_safe=False )
import os import sys import imp from setuptools import find_packages try: from restricted_pkg import setup except: # allow falling back to setuptools only if # we are not trying to upload if 'upload' in sys.argv: raise ImportError('restricted_pkg is required to upload, first do pip install restricted_pkg') from setuptools import setup requirements = imp.load_source('requirements', os.path.realpath('requirements.py')) setup( name='dusty', version='0.0.1', description='Docker-based development environment manager', url='https://github.com/gamechanger/dusty', private_repository='gamechanger', author='GameChanger', author_email='travis@gamechanger.io', packages=find_packages(), install_requires=requirements.install_requires, tests_require=requirements.test_requires, test_suite="nose.collector", entry_points={'console_scripts': ['dustyd = dusty.daemon:main']}, zip_safe=False )
Check for test subreddits case insensitively.
from urllib import quote from pylons import c, g from r2.lib.pages import Ads as BaseAds class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) adzerk_test_srs = g.live_config.get("adzerk_test_srs") if adzerk_test_srs and c.site.name.lower() in adzerk_test_srs: url_key = "adzerk_https_url" if c.secure else "adzerk_url" self.ad_url = g.config[url_key].format( subreddit=quote(c.site.name), origin=c.request_origin, ) self.frame_id = "ad_main"
from urllib import quote from pylons import c, g from r2.lib.pages import Ads as BaseAds class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) adzerk_test_srs = g.live_config.get("adzerk_test_srs") if adzerk_test_srs and c.site.name in adzerk_test_srs: url_key = "adzerk_https_url" if c.secure else "adzerk_url" self.ad_url = g.config[url_key].format( subreddit=quote(c.site.name), origin=c.request_origin, ) self.frame_id = "ad_main"
Make env.path to /var/praekelt/<PROJECT> an absolute path.
from fabric.api import cd, sudo, env import os expected_vars = [ 'PROJECT', ] for var in expected_vars: if var not in os.environ: raise Exception('Please specify %s environment variable' % ( var,)) PROJECT = os.environ['PROJECT'] USER = os.environ.get('USER', 'jmbo') env.path = os.path.join('/', 'var', 'praekelt', PROJECT) def restart(): sudo('/etc/init.d/nginx restart') sudo('supervisorctl reload') def deploy(): with cd(env.path): sudo('git pull', user=USER) sudo('ve/bin/python manage.py syncdb --migrate --noinput', user=USER) sudo('ve/bin/python manage.py collectstatic --noinput', user=USER) def install_packages(force=False): with cd(env.path): sudo('ve/bin/pip install %s -r requirements.pip' % ( '--upgrade' if force else '',), user=USER)
from fabric.api import cd, sudo, env import os expected_vars = [ 'PROJECT', ] for var in expected_vars: if var not in os.environ: raise Exception('Please specify %s environment variable' % ( var,)) PROJECT = os.environ['PROJECT'] USER = os.environ.get('USER', 'jmbo') env.path = os.path.join('var', 'praekelt', PROJECT) def restart(): sudo('/etc/init.d/nginx restart') sudo('supervisorctl reload') def deploy(): with cd(env.path): sudo('git pull', user=USER) sudo('ve/bin/python manage.py syncdb --migrate --noinput', user=USER) sudo('ve/bin/python manage.py collectstatic --noinput', user=USER) def install_packages(force=False): with cd(env.path): sudo('ve/bin/pip install %s -r requirements.pip' % ( '--upgrade' if force else '',), user=USER)
Increase timeout for locking archives
import { placeStylesheet } from "../../common/styles"; window.Buttercup = { fetchArchives: function() { return new Promise(function(resolve, reject) { let timeout = setTimeout(() => reject(new Error("Timed-out getting archive list")), 200); chrome.runtime.sendMessage({ command: "get-archive-states" }, function(response) { clearTimeout(timeout); resolve(response); }); }); }, lockArchive: function(name) { return new Promise(function(resolve, reject) { let timeout = setTimeout(() => reject(new Error("Timed-out locking archive")), 4000); chrome.runtime.sendMessage({ command: "lock-archive", name }, function(response) { clearTimeout(timeout); if (response && response.ok) { resolve(response); } else { reject(new Error(response.error)); } }); }); } }; placeStylesheet();
import { placeStylesheet } from "../../common/styles"; window.Buttercup = { fetchArchives: function() { return new Promise(function(resolve, reject) { let timeout = setTimeout(() => reject(new Error("Timed-out getting archive list")), 200); chrome.runtime.sendMessage({ command: "get-archive-states" }, function(response) { clearTimeout(timeout); resolve(response); }); }); }, lockArchive: function(name) { return new Promise(function(resolve, reject) { let timeout = setTimeout(() => reject(new Error("Timed-out locking archive")), 200); chrome.runtime.sendMessage({ command: "lock-archive", name }, function(response) { clearTimeout(timeout); if (response && response.ok) { resolve(response); } else { reject(new Error(response.error)); } }); }); } }; placeStylesheet();
Set the sip QDate API for enaml interop.
#------------------------------------------------------------------------------ # Copyright (c) 2010, Enthought Inc # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # # Author: Enthought Inc # Description: Qt API selector. Can be used to switch between pyQt and PySide #------------------------------------------------------------------------------ import os def prepare_pyqt4(): # Set PySide compatible APIs. import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) sip.setapi('QDate', 2) qt_api = os.environ.get('QT_API') if qt_api is None: try: import PySide qt_api = 'pyside' except ImportError: try: prepare_pyqt4() import PyQt4 qt_api = 'pyqt' except ImportError: raise ImportError('Cannot import PySide or PyQt4') elif qt_api == 'pyqt': prepare_pyqt4() elif qt_api != 'pyside': raise RuntimeError("Invalid Qt API %r, valid values are: 'pyqt' or 'pyside'" % qt_api)
#------------------------------------------------------------------------------ # Copyright (c) 2010, Enthought Inc # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # # Author: Enthought Inc # Description: Qt API selector. Can be used to switch between pyQt and PySide #------------------------------------------------------------------------------ import os def prepare_pyqt4(): # Set PySide compatible APIs. import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) qt_api = os.environ.get('QT_API') if qt_api is None: try: import PySide qt_api = 'pyside' except ImportError: try: prepare_pyqt4() import PyQt4 qt_api = 'pyqt' except ImportError: raise ImportError('Cannot import PySide or PyQt4') elif qt_api == 'pyqt': prepare_pyqt4() elif qt_api != 'pyside': raise RuntimeError("Invalid Qt API %r, valid values are: 'pyqt' or 'pyside'" % qt_api)
Implement filtering of builds based on package IDs
/* * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cloudfoundry.client.v3.builds; import org.cloudfoundry.client.v3.FilterParameter; import org.cloudfoundry.client.v3.PaginatedRequest; import org.immutables.value.Value; import java.util.List; /** * The request payload for the List Builds operation */ @Value.Immutable abstract class _ListBuildsRequest extends PaginatedRequest { /** * The application ids */ @FilterParameter("app_guids") abstract List<String> getApplicationIds(); /** * The package ids */ @FilterParameter("package_guids") abstract List<String> getPackageIds(); /** * The build states */ @FilterParameter("states") abstract List<String> getStates(); }
/* * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cloudfoundry.client.v3.builds; import org.cloudfoundry.client.v3.FilterParameter; import org.cloudfoundry.client.v3.PaginatedRequest; import org.immutables.value.Value; import java.util.List; /** * The request payload for the List Builds operation */ @Value.Immutable abstract class _ListBuildsRequest extends PaginatedRequest { /** * The application ids */ @FilterParameter("app_guids") abstract List<String> getApplicationIds(); /** * The build states */ @FilterParameter("states") abstract List<String> getStates(); }
Create log directory if does'nt exist.
<?php namespace Rad\Logging\Adapter; use Rad\Logging\AbstractAdapter; /** * File Adapter * * @package Rad\Logging\Adapter */ class FileAdapter extends AbstractAdapter { protected $handle; /** * Rad\Logging\Adapter\FileAdapter constructor * * @param string $filePath Log file path */ public function __construct($filePath) { $dirPath = dirname($filePath); if (false === is_dir($dirPath)) { mkdir($dirPath, 0775, true); } if (substr($filePath, -4) !== '.log') { $filePath .= '.log'; } $this->handle = fopen($filePath, 'ab+'); } /** * Rad\Logging\Adapter\FileAdapter destructor */ public function __destruct() { $this->close(); } /** * Closes an open file pointer * * @return bool */ public function close() { return fclose($this->handle); } /** * {@inheritdoc} */ public function log($level, $message, $time, array $context = []) { fwrite($this->handle, $this->getFormatter()->format($level, $message, $time, $context)); } }
<?php namespace Rad\Logging\Adapter; use Rad\Logging\AbstractAdapter; /** * File Adapter * * @package Rad\Logging\Adapter */ class FileAdapter extends AbstractAdapter { protected $handle; /** * Rad\Logging\Adapter\FileAdapter constructor * * @param string $filePath Log file path */ public function __construct($filePath) { $this->handle = fopen($filePath, 'ab+'); } /** * Rad\Logging\Adapter\FileAdapter destructor */ public function __destruct() { $this->close(); } /** * Closes an open file pointer * * @return bool */ public function close() { return fclose($this->handle); } /** * {@inheritdoc} */ public function log($level, $message, $time, array $context = []) { fwrite($this->handle, $this->getFormatter()->format($level, $message, $time, $context)); } }
Return different values for carry and output.
# Copyright 2020 Google LLC # # 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 # # https://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. """Unittests for scan method.""" import unittest import jax.numpy as jn import objax class TestScan(unittest.TestCase): def test_scan(self): def cell(carry, x): return jn.array([2]) * carry * x, jn.array([3]) * carry * x carry = jn.array([8., 8.]) output = jn.array([[3., 3.], [6., 6.], [12., 12.]]) test_carry, test_output = objax.functional.scan(cell, jn.ones((2,)), jn.ones((3,))) self.assertTrue(jn.array_equal(carry, test_carry)) self.assertTrue(jn.array_equal(output, test_output))
# Copyright 2020 Google LLC # # 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 # # https://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. """Unittests for scan method.""" import unittest import jax.numpy as jn import objax class TestScan(unittest.TestCase): def test_scan(self): def cell(carry, x): return jn.array([2]) * carry * x, jn.array([2]) * carry * x carry = jn.array([8., 8.]) output = jn.array([[2., 2.], [4., 4.], [8., 8.]]) test_carry, test_output = objax.functional.scan(cell, jn.ones((2,)), jn.ones((3,))) self.assertTrue(jn.array_equal(carry, test_carry)) self.assertTrue(jn.array_equal(output, test_output))
Increment version to 1.14.0 for release.
__version_info__ = ('1', '14', '0') __version__ = '.'.join(__version_info__) from .wrappers import (ObjectProxy, CallableObjectProxy, FunctionWrapper, BoundFunctionWrapper, WeakFunctionProxy, PartialCallableObjectProxy, resolve_path, apply_patch, wrap_object, wrap_object_attribute, function_wrapper, wrap_function_wrapper, patch_function_wrapper, transient_function_wrapper) from .decorators import (adapter_factory, AdapterFactory, decorator, synchronized) from .importer import (register_post_import_hook, when_imported, notify_module_loaded, discover_post_import_hooks) # Import of inspect.getcallargs() included for backward compatibility. An # implementation of this was previously bundled and made available here for # Python <2.7. Avoid using this in future. from inspect import getcallargs # Variant of inspect.formatargspec() included here for forward compatibility. # This is being done because Python 3.11 dropped inspect.formatargspec() but # code for handling signature changing decorators relied on it. Exposing the # bundled implementation here in case any user of wrapt was also needing it. from .arguments import formatargspec
__version_info__ = ('1', '14', '0rc1') __version__ = '.'.join(__version_info__) from .wrappers import (ObjectProxy, CallableObjectProxy, FunctionWrapper, BoundFunctionWrapper, WeakFunctionProxy, PartialCallableObjectProxy, resolve_path, apply_patch, wrap_object, wrap_object_attribute, function_wrapper, wrap_function_wrapper, patch_function_wrapper, transient_function_wrapper) from .decorators import (adapter_factory, AdapterFactory, decorator, synchronized) from .importer import (register_post_import_hook, when_imported, notify_module_loaded, discover_post_import_hooks) # Import of inspect.getcallargs() included for backward compatibility. An # implementation of this was previously bundled and made available here for # Python <2.7. Avoid using this in future. from inspect import getcallargs # Variant of inspect.formatargspec() included here for forward compatibility. # This is being done because Python 3.11 dropped inspect.formatargspec() but # code for handling signature changing decorators relied on it. Exposing the # bundled implementation here in case any user of wrapt was also needing it. from .arguments import formatargspec
display.pvtable: Fix tool tip of last row
/******************************************************************************* * Copyright (c) 2010 Oak Ridge National Laboratory. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.csstudio.display.pvtable.ui; import org.csstudio.display.pvtable.model.PVTableItem; import org.eclipse.jface.viewers.CellLabelProvider; /** Cell label provider for PV Table that handles the tool tip * @author Kay Kasemir */ abstract public class PVTableCellLabelProvider extends CellLabelProvider { private static final int TOOL_TIP_MAX = 100; @Override public String getToolTipText(final Object element) { final PVTableItem item = (PVTableItem) element; if (item == PVTableModelContentProvider.NEW_ITEM) return "Add new PV to table by adding its name"; final String text = item.toString(); // Limit size of tool tip (in case of array data) if (text.length() > TOOL_TIP_MAX) return text.substring(0, TOOL_TIP_MAX) + "..."; return text; } }
/******************************************************************************* * Copyright (c) 2010 Oak Ridge National Laboratory. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.csstudio.display.pvtable.ui; import org.csstudio.display.pvtable.model.PVTableItem; import org.eclipse.jface.viewers.CellLabelProvider; /** Cell label provider for PV Table that handles the tool tip * @author Kay Kasemir */ abstract public class PVTableCellLabelProvider extends CellLabelProvider { private static final int TOOL_TIP_MAX = 100; @Override public String getToolTipText(final Object element) { final PVTableItem item = (PVTableItem) element; final String text = item.toString(); // Limit size of tool tip (in case of array data) if (text.length() > TOOL_TIP_MAX) return text.substring(0, TOOL_TIP_MAX) + "..."; return text; } }
Update chrome plugin for concourse 2.1.0 It was mostly working, but just left a dark bar across the top with the env name in it. This updates it to remove that bar as well to maintain consistency with the existing appearence.
// ==UserScript== // @name Remove concourse elements // @namespace cloudpipeline.digital // @description Strips away some of the cruft from the concourse pipeline view when showing it on monitoring screens. // @include https://deployer.*.cloudpipeline.digital/* // @include https://deployer.cloud.service.gov.uk/* // @version 1 // @grant none // ==/UserScript== var readyStateCheckInterval = setInterval(function() { if (document.readyState === "complete") { clearInterval(readyStateCheckInterval); console.log("Monitor mode is go"); var element = document.getElementsByClassName("legend")[0]; element.parentNode.removeChild(element); var element = document.getElementsByClassName("lower-right-info")[0]; element.parentNode.removeChild(element); var hostname = location.hostname.replace("deployer.", "").replace(".cloudpipeline.digital","") var element = document.getElementById("top-bar-app"); element.innerHTML = "&nbsp;<font size=5>" + hostname + "</font>"; } }, 10);
// ==UserScript== // @name Remove concourse elements // @namespace cloudpipeline.digital // @description Strips away some of the cruft from the concourse pipeline view when showing it on monitoring screens. // @include https://deployer.*.cloudpipeline.digital/* // @include https://deployer.cloud.service.gov.uk/* // @version 1 // @grant none // ==/UserScript== var readyStateCheckInterval = setInterval(function() { if (document.readyState === "complete") { clearInterval(readyStateCheckInterval); console.log("Monitor mode is go"); var element = document.getElementsByClassName("legend")[0]; element.parentNode.removeChild(element); var element = document.getElementsByClassName("lower-right-info")[0]; element.parentNode.removeChild(element); var hostname = location.hostname.replace("deployer.", "").replace(".cloudpipeline.digital","") var element = document.getElementsByTagName("nav")[0]; element.innerHTML = "&nbsp;<font size=5>" + hostname + "</font>"; } }, 10);
Fix wrong slice length in initialization
package of10 import ( "bytes" "encoding/binary" ) const MaxPortNameLength = 16 const EthernetAddressLength = 6 type PortNumber uint16 type PortConfig uint16 type PortState uint16 type PortFeature uint16 type PhysicalPort struct { PortNumber PortNumber HardwareAddress [EthernetAddressLength]uint8 Name [MaxPortNameLength]uint8 Config PortConfig State PortState CurrentFeatures PortFeature AdvertisedFeatures PortFeature SupportedFeatures PortFeature PeerFeatures PortFeature } func readPhysicalPort(b []byte) ([]PhysicalPort, error) { var port PhysicalPort count := len(b) / binary.Size(port) ports := make([]PhysicalPort, 0, count) buf := bytes.NewBuffer(b) if err := binary.Read(buf, binary.BigEndian, port); err != nil { return nil, err } return ports, nil }
package of10 import ( "bytes" "encoding/binary" ) const MaxPortNameLength = 16 const EthernetAddressLength = 6 type PortNumber uint16 type PortConfig uint16 type PortState uint16 type PortFeature uint16 type PhysicalPort struct { PortNumber PortNumber HardwareAddress [EthernetAddressLength]uint8 Name [MaxPortNameLength]uint8 Config PortConfig State PortState CurrentFeatures PortFeature AdvertisedFeatures PortFeature SupportedFeatures PortFeature PeerFeatures PortFeature } func readPhysicalPort(b []byte) ([]PhysicalPort, error) { var port PhysicalPort count := len(b) / binary.Size(port) ports := make([]PhysicalPort, count) buf := bytes.NewBuffer(b) if err := binary.Read(buf, binary.BigEndian, port); err != nil { return nil, err } return ports, nil }
BAP-16497: Change ClassLoader component - trigger unit test run
<?php namespace Oro\Bundle\TranslationBundle\Tests\Unit\Command\Stubs; use Symfony\Component\ClassLoader\UniversalClassLoader; use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class TestKernel extends Kernel { public function __construct() { parent::__construct('test_stub_env', true); } public function init() { } public function getRootDir() { return sys_get_temp_dir() . '/translation-test-stub-cache'; } public function registerBundles() { // Run unit test $loader = new UniversalClassLoader(); $loader->registerNamespace('SomeProject\\', array(__DIR__)); $loader->registerNamespace('SomeAnotherProject\\', array(__DIR__)); $loader->register(); return array( new \SomeProject\Bundle\SomeBundle\SomeBundle(), new \SomeAnotherProject\Bundle\SomeAnotherBundle\SomeAnotherBundle() ); } public function registerContainerConfiguration(LoaderInterface $loader) { } }
<?php namespace Oro\Bundle\TranslationBundle\Tests\Unit\Command\Stubs; use Symfony\Component\ClassLoader\UniversalClassLoader; use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class TestKernel extends Kernel { public function __construct() { parent::__construct('test_stub_env', true); } public function init() { } public function getRootDir() { return sys_get_temp_dir() . '/translation-test-stub-cache'; } public function registerBundles() { $loader = new UniversalClassLoader(); $loader->registerNamespace('SomeProject\\', array(__DIR__)); $loader->registerNamespace('SomeAnotherProject\\', array(__DIR__)); $loader->register(); return array( new \SomeProject\Bundle\SomeBundle\SomeBundle(), new \SomeAnotherProject\Bundle\SomeAnotherBundle\SomeAnotherBundle() ); } public function registerContainerConfiguration(LoaderInterface $loader) { } }
Fix default behavior; popup window pref is (for now) stored as a string 'true'/'false', not a python Bool.
import logging logger = logging.getLogger(__name__) KNOWN_PREFS = {'popups': 'true'} def get_preferences(session): edit_prefs = {} for pref, default in KNOWN_PREFS.iteritems(): value = session.get('editpref_' + pref, default) if value: edit_prefs[pref] = value return edit_prefs def set_preferences(session, prefs_requested): for pref in KNOWN_PREFS: value = prefs_requested.get(pref, None) if value: value = str(value)[:10] # limit length of stored value logger.debug("User set pref %s = %s", pref, value) session['editpref_' + pref] = value
import logging logger = logging.getLogger(__name__) KNOWN_PREFS = {'popups': True} PREF_MAP = {'false': False, 'true': True} def get_preferences(session): edit_prefs = {} for pref, default in KNOWN_PREFS.iteritems(): value = session.get('editpref_' + pref, default) if value: edit_prefs[pref] = value return edit_prefs def set_preferences(session, prefs_requested): for pref in KNOWN_PREFS: value = prefs_requested.get(pref, None) if value: value = str(value)[:10] # limit length of stored value logger.debug("User set pref %s = %s", pref, value) session['editpref_' + pref] = value
Fix bug in python loader.
import os.path import sys from .loader import Loader, I18nFileLoadError class PythonLoader(Loader): """class to load python files""" def __init__(self): super(PythonLoader, self).__init__() def load_file(self, filename): path, name = os.path.split(filename) module_name, ext = os.path.splitext(name) if path not in sys.path: sys.path.append(path) try: return __import__(module_name) except ImportError: raise I18nFileLoadError("error loading file {0}".format(filename)) def parse_file(self, file_content): return file_content def check_data(self, data, root_data): return hasattr(data, root_data) def get_data(self, data, root_data): return getattr(data, root_data)
import os.path import sys from .loader import Loader, I18nFileLoadError class PythonLoader(Loader): """class to load python files""" def __init__(self): super(PythonLoader, self).__init__() def load_file(self, filename): path, name = os.path.split(filename) module_name, ext = os.path.splitext(name) if path not in sys.path: sys.path.append(path) try: return __import__(module_name) except ImportError as e: raise I18nFileLoadError("error loading file {0}: {1}".format(filename, e.msg)) def parse_file(self, file_content): return file_content def check_data(self, data, root_data): return hasattr(data, root_data) def get_data(self, data, root_data): return getattr(data, root_data)
Change to LF end of line
<?php namespace pshopws; /** * @author Marcos Redondo <kusflo at gmail.com> */ class ServiceSimpleXmlToArray { public static function take($xmlObject) { $service = new self($xmlObject); return $service->xmlToArray($xmlObject); } public static function takeMultiple($xmlObjects) { $array = array(); foreach ($xmlObjects as $obj) { $array[] = self::take($obj); } return $array; } private function __construct($xmlObject) { if (!is_a($xmlObject, \SimpleXMLElement::class)) { throw new PShopWsException('The service '.__CLASS__.' has received a parameter other than SimpleXmlElement'); } } private function xmlToArray($xmlObject, $out = array()) { foreach ((array)$xmlObject as $index => $node) { $out[$index] = (is_object($node)) ? $this->xmlToArray($node) : $node; } return $out; } }
<?php namespace pshopws; /** * @author Marcos Redondo <kusflo at gmail.com> */ class ServiceSimpleXmlToArray { public static function take($xmlObject) { $service = new self($xmlObject); return $service->xmlToArray($xmlObject); } public static function takeMultiple($xmlObjects) { foreach ($xmlObjects as $obj) { $array[] = self::take($obj); } return $array; } private function __construct($xmlObject) { if (!is_a($xmlObject, \SimpleXMLElement::class)) { throw new PShopWsException('The service ' . __CLASS__ . ' has received a parameter other than SimpleXmlElement'); } } private function xmlToArray($xmlObject, $out = array()) { foreach ((array)$xmlObject as $index => $node) { $out[$index] = (is_object($node)) ? $this->xmlToArray($node) : $node; } return $out; } }
Fix false positive octal syntax warning
#!/usr/bin/env python import os import urllib import zipfile script_path = os.path.dirname(os.path.realpath(__file__)) packer_archive_path = script_path + "/packer.zip" bin_path = script_path + "/bin" if not os.path.isfile(bin_path + "/packer"): if not os.path.exists(bin_path): os.makedirs(bin_path) try: urllib.urlretrieve("https://dl.bintray.com/mitchellh/packer/packer_0.8.6_linux_amd64.zip", packer_archive_path) with zipfile.ZipFile(packer_archive_path, "r") as packer_archive: packer_archive.extractall(path=bin_path) finally: os.remove(packer_archive_path) for root, subdirectories, files in os.walk(bin_path): for f in files: os.chmod(root + "/" + f, 755)
#!/usr/bin/env python import os import urllib import zipfile script_path = os.path.dirname(os.path.realpath(__file__)) packer_archive_path = script_path + "/packer.zip" bin_path = script_path + "/bin" if not os.path.isfile(bin_path + "/packer"): if not os.path.exists(bin_path): os.makedirs(bin_path) try: urllib.urlretrieve("https://dl.bintray.com/mitchellh/packer/packer_0.8.6_linux_amd64.zip", packer_archive_path) with zipfile.ZipFile(packer_archive_path, "r") as packer_archive: packer_archive.extractall(path=bin_path) finally: os.remove(packer_archive_path) for root, subdirectories, files in os.walk(bin_path): for f in files: os.chmod("%s/%s" % (root, f), 0755)
Clear instead of Flush. Clearing now allows for a certain type to be filtered out.
var Reflux = require('reflux'); var objectAssign = require('object-assign'); var MessageActions = require('./MessageActions'); var _stack = []; // Container for the each object of message var _counter = 0; /** * Registry of all messages, mixin to manage all drawers. * Contains add, flush, and remove to do the mentioned. */ var MessageStore = Reflux.createStore({ listenables: MessageActions, /** * Removes the message with given key * @param {int} id ID/Key of message which would be removed */ onRemove: function(id) { // Index of the message var index = _stack.map(function(message) { return message.id }).indexOf(id); // Throw an exception if there are no results of the given id if ( index == -1 ) throw new Error('The message (id) does not exist in the stack'); _stack.splice(index, 1); this.trigger(_stack); }, /** * Adds a new message to the stack */ onAdd: function(data) { // Message defaults var _defaults = { id: ++_counter, duration: 10000, template: '' }; _stack.push( data ? objectAssign(_defaults, data) : _defaults ); this.trigger(_stack); }, /** * Removes everything in the stack */ onClear: function(filter) { this.trigger(_stack = !!filter ? _stack.filter(function(message) { return filter == message.type }) : [] ); } }; module.exports = MessageStore;
var Reflux = require('reflux'); var objectAssign = require('object-assign'); var MessageActions = require('./MessageActions'); var _stack = []; // Container for the each object of message var _counter = 0; /** * Registry of all messages, mixin to manage all drawers. * Contains add, flush, and remove to do the mentioned. */ var MessageStore = Reflux.createStore({ listenables: MessageActions, /** * Removes the message with given key * @param {int} id ID/Key of message which would be removed */ onRemove: function(id) { // Index of the message var index = _stack.map(function(message) { return message.id }).indexOf(id); // Throw an exception if there are no results of the given id if ( index == -1 ) throw new Error('The message (id) does not exist in the stack'); _stack.splice(index, 1); this.trigger(_stack); }, /** * Adds a new message to the stack */ onAdd: function(data) { // Message defaults var _defaults = { id: ++_counter, duration: 10000, template: '' }; _stack.push( data ? objectAssign(_defaults, data) : _defaults ); this.trigger(_stack); }, /** * Removes everything in the stack */ onFlush: function() { this.trigger(_stack = []); } }; module.exports = MessageStore;
Add Message.debug with access key.
/* * Copyright 2010 SpringSource * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.aws.ivy; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.ivy.plugins.resolver.RepositoryResolver; import org.apache.ivy.util.Message; /** * A dependency resolver that looks to an S3 repository to resolve dependencies. * * @author Ben Hale */ public class S3Resolver extends RepositoryResolver { static { Logger.getLogger("org.jets3t").setLevel(Level.OFF); } public void setAccessKey(String accessKey) { Message.debug("S3Resolver using accessKey " + accessKey); ((S3Repository)getRepository()).setAccessKey(accessKey); } public void setSecretKey(String secretKey) { ((S3Repository)getRepository()).setSecretKey(secretKey); } public S3Resolver() { setRepository(new S3Repository()); } public String getTypeName() { return "S3"; } }
/* * Copyright 2010 SpringSource * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.aws.ivy; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.ivy.plugins.resolver.RepositoryResolver; /** * A dependency resolver that looks to an S3 repository to resolve dependencies. * * @author Ben Hale */ public class S3Resolver extends RepositoryResolver { static { Logger.getLogger("org.jets3t").setLevel(Level.OFF); } public void setAccessKey(String accessKey) { ((S3Repository)getRepository()).setAccessKey(accessKey); } public void setSecretKey(String secretKey) { ((S3Repository)getRepository()).setSecretKey(secretKey); } public S3Resolver() { setRepository(new S3Repository()); } public String getTypeName() { return "S3"; } }
Revert "Remove need to call paramsFor on self" This reverts commit f190d4997853ced4d1982eb2f32388395594a994.
import Ember from 'ember'; import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; const { isPresent } = Ember; export default Ember.Route.extend(AuthenticatedRouteMixin, { queryParams: { state: { refreshModel: true }, sort: { refreshModel: true }, q: { refreshModel: true }, match: { refreshModel: true } }, model() { let params = this.paramsFor('experiments.list'); var query = { q: ['state:(-Deleted)'] }; if (isPresent(params.state) && params.state !== 'All') { query.q.push(`state:${params.state}`); } if (isPresent(params.sort)) { query.sort = params.sort; } if (isPresent(params.match)) { query.q.push(params.match); } return this.store.query('experiment', query); } });
import Ember from 'ember'; import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; const { isPresent } = Ember; export default Ember.Route.extend(AuthenticatedRouteMixin, { queryParams: { state: { refreshModel: true }, sort: { refreshModel: true }, q: { refreshModel: true }, match: { refreshModel: true } }, model(params) { var query = { q: ['state:(-Deleted)'] }; if (isPresent(params.state) && params.state !== 'All') { query.q.push(`state:${params.state}`); } if (isPresent(params.sort)) { query.sort = params.sort; } if (isPresent(params.match)) { query.q.push(params.match); } return this.store.query('experiment', query); } });
Fix proper property name place_id
/** |========================================================================================== | This is a container that displays the list of restaurants. | Needs access to redux state. | Does not need to dispatch to redux state. | | A. When redux's places state is updated via the map container: | 1. This list rerenders with the new places. |------------------------------------------------------------------------------------------ */ import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import ListItem from '../components/listItem'; class List extends Component { /** * Scroll up when list is applied a new filter */ componentDidUpdate() { document.getElementById('list-scroll').scrollTop = 0; } render() { return ( <div id="list-scroll" className="list-scroll"> {this.props.places.map((place, index) => ( <div key={place.place_id} className="list-item-container"> <h4 className="list-item-number">{index + 1}</h4> <ListItem place={place} /> </div> ) )} </div> ); } } List.propTypes = { places: PropTypes.array.isRequired, }; function mapStateToProps({ places }) { return { places, }; } export default connect(mapStateToProps)(List);
/** |========================================================================================== | This is a container that displays the list of restaurants. | Needs access to redux state. | Does not need to dispatch to redux state. | | A. When redux's places state is updated via the map container: | 1. This list rerenders with the new places. |------------------------------------------------------------------------------------------ */ import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import ListItem from '../components/listItem'; class List extends Component { /** * Scroll up when list is applied a new filter */ componentDidUpdate() { document.getElementById('list-scroll').scrollTop = 0; } render() { return ( <div id="list-scroll" className="list-scroll"> {this.props.places.map((place, index) => ( <div key={place.id} className="list-item-container"> <h4 className="list-item-number">{index + 1}</h4> <ListItem place={place} /> </div> ) )} </div> ); } } List.propTypes = { places: PropTypes.array.isRequired, }; function mapStateToProps({ places }) { return { places, }; } export default connect(mapStateToProps)(List);
Add test_requires dependency on python-spidermonkey.
from setuptools import setup import jasinja, sys requires = ['Jinja2'] if sys.version_info < (2, 6): requires += ['simplejson'] setup( name='jasinja', version=jasinja.__version__, url='http://bitbucket.org/djc/jasinja', license='BSD', author='Dirkjan Ochtman', author_email='dirkjan@ochtman.nl', description='A JavaScript code generator for Jinja templates', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], packages=['jasinja', 'jasinja.tests'], package_data={ 'jasinja': ['*.js'] }, install_requires=requires, test_suite='jasinja.tests.run.suite', test_requires=['python-spidermonkey'], entry_points={ 'console_scripts': ['jasinja-compile = jasinja.compile:main'], }, )
from setuptools import setup import jasinja, sys requires = ['Jinja2'] if sys.version_info < (2, 6): requires += ['simplejson'] setup( name='jasinja', version=jasinja.__version__, url='http://bitbucket.org/djc/jasinja', license='BSD', author='Dirkjan Ochtman', author_email='dirkjan@ochtman.nl', description='A JavaScript code generator for Jinja templates', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], packages=['jasinja', 'jasinja.tests'], package_data={ 'jasinja': ['*.js'] }, install_requires=requires, test_suite='jasinja.tests.run.suite', entry_points={ 'console_scripts': ['jasinja-compile = jasinja.compile:main'], }, )
Fix addon page with wrong baseURL
/* jshint node: true */ module.exports = function (environment) { var ENV = { modulePrefix: "dummy", environment: environment, baseURL: "/", locationType: "auto", EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. "with-controller": true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === "development") { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === "test") { // Testem prefers this... ENV.baseURL = "/"; ENV.locationType = "none"; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = "#ember-testing"; } if (environment === "production") { var name = this.project.pkg.name; ENV.locationType = "hash"; ENV.baseURL = "/" + name + "/"; } return ENV; };
/* jshint node: true */ module.exports = function (environment) { var ENV = { modulePrefix: "dummy", environment: environment, baseURL: "/", locationType: "auto", EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. "with-controller": true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === "development") { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === "test") { // Testem prefers this... ENV.baseURL = "/"; ENV.locationType = "none"; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = "#ember-testing"; } if (environment === "production") { } return ENV; };
Exit with 1 if client tests fail
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2015 Red Hat # Licensed under The MIT License (MIT) # http://opensource.org/licenses/MIT # import unittest import argparse import sys """ Use this script either without arguments to run all tests: python client_test_run.py or with specific module/test to run only part of the test suite: python client_test_run.py pdc_client.tests.release.tests.ReleaseTestCase.test_list_all """ if __name__ == '__main__': parser = argparse.ArgumentParser('client_test_run.py') parser.add_argument('tests', metavar='TEST', nargs='*') options = parser.parse_args() loader = unittest.TestLoader() if options.tests: suite = loader.loadTestsFromNames(options.tests) else: suite = loader.discover('pdc_client/tests', top_level_dir='.') result = unittest.TextTestRunner().run(suite) if not result.wasSuccessful(): sys.exit(1)
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2015 Red Hat # Licensed under The MIT License (MIT) # http://opensource.org/licenses/MIT # import unittest import argparse """ Use this script either without arguments to run all tests: python client_test_run.py or with specific module/test to run only part of the test suite: python client_test_run.py pdc_client.tests.release.tests.ReleaseTestCase.test_list_all """ if __name__ == '__main__': parser = argparse.ArgumentParser('client_test_run.py') parser.add_argument('tests', metavar='TEST', nargs='*') options = parser.parse_args() loader = unittest.TestLoader() if options.tests: suite = loader.loadTestsFromNames(options.tests) else: suite = loader.discover('pdc_client/tests', top_level_dir='.') unittest.TextTestRunner().run(suite)
Add missing import in API base controller
<?php /** * Copyright 2015 ppy Pty. Ltd. * * This file is part of osu!web. osu!web is distributed with the hope of * attracting more community contributions to the core ecosystem of osu!. * * osu!web is free software: you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License version 3 * as published by the Free Software Foundation. * * osu!web is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with osu!web. If not, see <http://www.gnu.org/licenses/>. */ namespace App\Http\Controllers\API; use Auth; use Illuminate\Foundation\Bus\DispatchesCommands; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Routing\Controller as BaseController; class Controller extends BaseController { use DispatchesCommands, ValidatesRequests; public function __construct() { Auth::onceUsingId(Authorizer::getResourceOwnerId()); } }
<?php /** * Copyright 2015 ppy Pty. Ltd. * * This file is part of osu!web. osu!web is distributed with the hope of * attracting more community contributions to the core ecosystem of osu!. * * osu!web is free software: you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License version 3 * as published by the Free Software Foundation. * * osu!web is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with osu!web. If not, see <http://www.gnu.org/licenses/>. */ namespace App\Http\Controllers\API; use Illuminate\Foundation\Bus\DispatchesCommands; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Routing\Controller as BaseController; class Controller extends BaseController { use DispatchesCommands, ValidatesRequests; public function __construct() { Auth::onceUsingId(Authorizer::getResourceOwnerId()); } }
Python: Handle django v4 as well in tests
from django.urls import path, re_path from . import views urlpatterns = [ path("foo/", views.foo), # $routeSetup="foo/" # TODO: Doesn't include standard `$` to mark end of string, due to problems with # inline expectation tests (which thinks the `$` would mark the beginning of a new # line) re_path(r"^ba[rz]/", views.bar_baz), # $routeSetup="^ba[rz]/" path("basic-view-handler/", views.MyBasicViewHandler.as_view()), # $routeSetup="basic-view-handler/" path("custom-inheritance-view-handler/", views.MyViewHandlerWithCustomInheritance.as_view()), # $routeSetup="custom-inheritance-view-handler/" path("CustomRedirectView/<foo>", views.CustomRedirectView.as_view()), # $routeSetup="CustomRedirectView/<foo>" path("CustomRedirectView2/<foo>", views.CustomRedirectView2.as_view()), # $routeSetup="CustomRedirectView2/<foo>" ] from django import __version__ as django_version if django_version[0] == "3": # This version 1.x way of defining urls is deprecated in Django 3.1, but still works. # However, it is removed in Django 4.0, so we need this guard to make our code runnable from django.conf.urls import url old_urlpatterns = urlpatterns # we need this assignment to get our logic working... maybe it should be more # sophisticated? urlpatterns = [ url(r"^deprecated/", views.deprecated), # $routeSetup="^deprecated/" ] urlpatterns += old_urlpatterns
from django.urls import path, re_path # This version 1.x way of defining urls is deprecated in Django 3.1, but still works from django.conf.urls import url from . import views urlpatterns = [ path("foo/", views.foo), # $routeSetup="foo/" # TODO: Doesn't include standard `$` to mark end of string, due to problems with # inline expectation tests (which thinks the `$` would mark the beginning of a new # line) re_path(r"^ba[rz]/", views.bar_baz), # $routeSetup="^ba[rz]/" url(r"^deprecated/", views.deprecated), # $routeSetup="^deprecated/" path("basic-view-handler/", views.MyBasicViewHandler.as_view()), # $routeSetup="basic-view-handler/" path("custom-inheritance-view-handler/", views.MyViewHandlerWithCustomInheritance.as_view()), # $routeSetup="custom-inheritance-view-handler/" path("CustomRedirectView/<foo>", views.CustomRedirectView.as_view()), # $routeSetup="CustomRedirectView/<foo>" path("CustomRedirectView2/<foo>", views.CustomRedirectView2.as_view()), # $routeSetup="CustomRedirectView2/<foo>" ]
III-758: Apply events when parameter parent class matches
<?php /** * @file */ namespace CultuurNet\UDB3\EventHandling; use Broadway\Domain\DomainMessage; trait DelegateEventHandlingToSpecificMethodTrait { /** * {@inheritDoc} */ public function handle(DomainMessage $domainMessage) { $event = $domainMessage->getPayload(); $method = $this->getHandleMethod($event); if (!method_exists($this, $method)) { return; } try { $parameter = new \ReflectionParameter(array($this, $method), 0); } catch (\ReflectionException $e) { // No parameter for the method, so we ignore it. return; } $expectedClass = $parameter->getClass(); if (is_a($event, $expectedClass->getName())) { $this->$method($event, $domainMessage); } } private function getHandleMethod($event) { $classParts = explode('\\', get_class($event)); return 'apply' . end($classParts); } }
<?php /** * @file */ namespace CultuurNet\UDB3\EventHandling; use Broadway\Domain\DomainMessage; trait DelegateEventHandlingToSpecificMethodTrait { /** * {@inheritDoc} */ public function handle(DomainMessage $domainMessage) { $event = $domainMessage->getPayload(); $method = $this->getHandleMethod($event); if (!method_exists($this, $method)) { return; } try { $parameter = new \ReflectionParameter(array($this, $method), 0); } catch (\ReflectionException $e) { // No parameter for the method, so we ignore it. return; } $expectedClass = $parameter->getClass(); if ($expectedClass->getName() == get_class($event)) { $this->$method($event, $domainMessage); } } private function getHandleMethod($event) { $classParts = explode('\\', get_class($event)); return 'apply' . end($classParts); } }
Allow subtitles to be blank.
const React = require('react') const Result = React.createClass({ propTypes: { active: React.PropTypes.bool.isRequired, value: React.PropTypes.object.isRequired, activate: React.PropTypes.func.isRequired, onClick: React.PropTypes.func.isRequired, }, click () { this.props.onClick(this.props.value) }, activate () { this.props.activate(this.props.value) }, render () { const { active, value } = this.props return React.createElement( 'li', { onClick: this.click, onMouseOver: this.activate, className: active ? 'active' : 'inactive', }, React.createElement('img', { src: value.icon, alt: '' }), React.createElement('h2', null, value.title), value.subtitle && React.createElement('h3', null, value.subtitle) ) }, }) module.exports = Result
const React = require('react') const Result = React.createClass({ propTypes: { active: React.PropTypes.bool.isRequired, value: React.PropTypes.object.isRequired, activate: React.PropTypes.func.isRequired, onClick: React.PropTypes.func.isRequired, }, click () { this.props.onClick(this.props.value) }, activate () { this.props.activate(this.props.value) }, render () { const { active, value } = this.props return React.createElement( 'li', { onClick: this.click, onMouseOver: this.activate, className: active ? 'active' : 'inactive', }, React.createElement('img', { src: value.icon, alt: '' }), React.createElement('h2', null, value.title), React.createElement('h3', null, value.subtitle) ) }, }) module.exports = Result
Fix library name in Latex.
import sys import os import shlex import subprocess read_the_docs_build = os.environ.get('READTHEDOCS', None) == 'True' if read_the_docs_build: subprocess.call('doxygen', shell=True) extensions = ['breathe'] breathe_projects = { 'Nanoshield_LoadCell': 'xml' } breathe_default_project = "Nanoshield_LoadCell" templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'Nanoshield_LoadCell' copyright = u'2015, Nanoshield_LoadCell' author = u'Nanoshield_LoadCell' version = '1.0' release = '1.0' language = None exclude_patterns = ['_build'] pygments_style = 'sphinx' todo_include_todos = False html_static_path = ['_static'] htmlhelp_basename = 'Nanoshield_LoadCelldoc' latex_elements = { } latex_documents = [ (master_doc, 'Nanoshield_LoadCell.tex', u'Nanoshield\_LoadCell Documentation', u'Nanoshield_LoadCell', 'manual'), ]
import sys import os import shlex import subprocess read_the_docs_build = os.environ.get('READTHEDOCS', None) == 'True' if read_the_docs_build: subprocess.call('doxygen', shell=True) extensions = ['breathe'] breathe_projects = { 'Nanoshield_LoadCell': 'xml' } breathe_default_project = "Nanoshield_LoadCell" templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'Nanoshield_LoadCell' copyright = u'2015, Nanoshield_LoadCell' author = u'Nanoshield_LoadCell' version = '1.0' release = '1.0' language = None exclude_patterns = ['_build'] pygments_style = 'sphinx' todo_include_todos = False html_static_path = ['_static'] htmlhelp_basename = 'Nanoshield_LoadCelldoc' latex_elements = { } latex_documents = [ (master_doc, 'Nanoshield_LoadCell.tex', u'Nanoshield_LoadCell Documentation', u'Nanoshield_LoadCell', 'manual'), ]
Fix issue where switching from a component to an element of the same resulting `nodeName` would not trigger unmount.
import { clone, isString, isFunction, toLowerCase } from '../util'; import { isFunctionalComponent } from './functional-component'; /** Check if two nodes are equivalent. * @param {Element} node * @param {VNode} vnode * @private */ export function isSameNodeType(node, vnode) { if (isString(vnode)) { return node instanceof Text; } if (isString(vnode.nodeName)) { return !node._componentConstructor && isNamedNode(node, vnode.nodeName); } if (isFunction(vnode.nodeName)) { return node._componentConstructor===vnode.nodeName || isFunctionalComponent(vnode); } } export function isNamedNode(node, nodeName) { return node.normalizedNodeName===nodeName || toLowerCase(node.nodeName)===toLowerCase(nodeName); } /** * Reconstruct Component-style `props` from a VNode. * Ensures default/fallback values from `defaultProps`: * Own-properties of `defaultProps` not present in `vnode.attributes` are added. * @param {VNode} vnode * @returns {Object} props */ export function getNodeProps(vnode) { let props = clone(vnode.attributes); props.children = vnode.children; let defaultProps = vnode.nodeName.defaultProps; if (defaultProps) { for (let i in defaultProps) { if (props[i]===undefined) { props[i] = defaultProps[i]; } } } return props; }
import { clone, isString, isFunction, toLowerCase } from '../util'; import { isFunctionalComponent } from './functional-component'; /** Check if two nodes are equivalent. * @param {Element} node * @param {VNode} vnode * @private */ export function isSameNodeType(node, vnode) { if (isString(vnode)) { return node instanceof Text; } if (isString(vnode.nodeName)) { return isNamedNode(node, vnode.nodeName); } if (isFunction(vnode.nodeName)) { return node._componentConstructor===vnode.nodeName || isFunctionalComponent(vnode); } } export function isNamedNode(node, nodeName) { return node.normalizedNodeName===nodeName || toLowerCase(node.nodeName)===toLowerCase(nodeName); } /** * Reconstruct Component-style `props` from a VNode. * Ensures default/fallback values from `defaultProps`: * Own-properties of `defaultProps` not present in `vnode.attributes` are added. * @param {VNode} vnode * @returns {Object} props */ export function getNodeProps(vnode) { let props = clone(vnode.attributes); props.children = vnode.children; let defaultProps = vnode.nodeName.defaultProps; if (defaultProps) { for (let i in defaultProps) { if (props[i]===undefined) { props[i] = defaultProps[i]; } } } return props; }
Tidy up the installation process a little
from distutils.core import setup setup( name='Flask-Roots', version='0.0.1', description='Lightweight personal git server.', url='http://github.com/mikeboers/Flask-Roots', packages=['flask_roots'], author='Mike Boers', author_email='flask-roots@mikeboers.com', license='BSD-3', entry_points={ 'console_scripts': [ ], }, install_requires=''' Baker jsmin watchdog Flask Flask-Mako Markdown PyHAML Flask-SQLAlchemy sqlalchemy-migrate Flask-Mail pillowcase Flask-Images Flask-Login Flask-ACL gunicorn gevent ''', classifiers=[ # 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', ], )
from distutils.core import setup setup( name='Flask-Roots', version='0.0.1', description='Lightweight personal git server.', url='http://github.com/mikeboers/Flask-Roots', packages=['flask_roots'], author='Mike Boers', author_email='flask-roots@mikeboers.com', license='BSD-3', entry_points={ 'console_scripts': [ ], }, install_requires=''' Baker jsmin watchdog Flask Flask-Mako Markdown PyHAML Flask-SQLAlchemy sqlalchemy-migrate Flask-Mail PIL Flask-Images Flask-Login Flask-ACL gunicorn gevent ''', classifiers=[ # 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', ], )
Include sourcesContent in source map
/* eslint-disable no-console */ import { createFilter } from 'rollup-pluginutils'; import { resolve } from 'source-map-resolve'; import { readFile } from 'fs'; import { promisify } from './utils'; const readFileAsync = promisify(readFile); const resolveSourceMapAsync = promisify(resolve); export default function sourcemaps({ include, exclude } = {}) { const filter = createFilter(include, exclude); return { async load(id) { if (!filter(id)) { return null; } let code; try { code = await readFileAsync(id, 'utf8'); } catch (err) { // Failed, let Rollup deal with it return null; } let sourceMap; try { sourceMap = await resolveSourceMapAsync(code, id, readFile); } catch (err) { console.error(`rollup-plugin-sourcemaps: Failed resolving source map from ${id}: ${err}`); return code; } // No source map detected, return code if (sourceMap === null) { return code; } const { map, sourcesContent } = sourceMap; map.sourcesContent = sourcesContent; return { code, map }; }, }; }
/* eslint-disable no-console */ import { createFilter } from 'rollup-pluginutils'; import { resolveSourceMap } from 'source-map-resolve'; import { readFile } from 'fs'; import { promisify } from './utils'; const readFileAsync = promisify(readFile); const resolveSourceMapAsync = promisify(resolveSourceMap); export default function sourcemaps({ include, exclude } = {}) { const filter = createFilter(include, exclude); return { async load(id) { if (!filter(id)) { return null; } let code; try { code = await readFileAsync(id, 'utf8'); } catch (err) { // Failed, let Rollup deal with it return null; } let sourceMap; try { sourceMap = await resolveSourceMapAsync(code, id, readFile); } catch (err) { console.error(`rollup-plugin-sourcemaps: Failed resolving source map from ${id}: ${err}`); return code; } // No source map detected, return code if (sourceMap === null) { return code; } const { map } = sourceMap; return { code, map }; }, }; }
Change unused WriteCloser to Writer Signed-off-by: Alexandr Morozov <4efb7da3e38416208b41d8021a942884d8a9435c@docker.com>
package jsonlog import ( "encoding/json" "fmt" "io" "log" "time" ) type JSONLog struct { Log string `json:"log,omitempty"` Stream string `json:"stream,omitempty"` Created time.Time `json:"time"` } func (jl *JSONLog) Format(format string) (string, error) { if format == "" { return jl.Log, nil } if format == "json" { m, err := json.Marshal(jl) return string(m), err } return fmt.Sprintf("[%s] %s", jl.Created.Format(format), jl.Log), nil } func WriteLog(src io.Reader, dst io.Writer, format string) error { dec := json.NewDecoder(src) for { l := &JSONLog{} if err := dec.Decode(l); err == io.EOF { return nil } else if err != nil { log.Printf("Error streaming logs: %s", err) return err } line, err := l.Format(format) if err != nil { return err } fmt.Fprintf(dst, "%s", line) } }
package jsonlog import ( "encoding/json" "fmt" "io" "log" "time" ) type JSONLog struct { Log string `json:"log,omitempty"` Stream string `json:"stream,omitempty"` Created time.Time `json:"time"` } func (jl *JSONLog) Format(format string) (string, error) { if format == "" { return jl.Log, nil } if format == "json" { m, err := json.Marshal(jl) return string(m), err } return fmt.Sprintf("[%s] %s", jl.Created.Format(format), jl.Log), nil } func WriteLog(src io.Reader, dst io.WriteCloser, format string) error { dec := json.NewDecoder(src) for { l := &JSONLog{} if err := dec.Decode(l); err == io.EOF { return nil } else if err != nil { log.Printf("Error streaming logs: %s", err) return err } line, err := l.Format(format) if err != nil { return err } fmt.Fprintf(dst, "%s", line) } }
Update theme name, licence and author
<?php /** * i-MSCP - internet Multi Server Control Panel * Copyright (C) 2010-2015 by i-MSCP Team * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ return array( 'theme_name' => 'bootstrap', 'theme_version' => '1.0.0', 'theme_authors' => array( 'Kevin' => 'kevin@totalwipeout.com' ), 'theme_licence' => 'MIT', 'theme_color_set' => array('black', 'blue', 'green', 'red', 'yellow') );
<?php /** * i-MSCP - internet Multi Server Control Panel * Copyright (C) 2010-2015 by i-MSCP Team * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ return array( 'theme_name' => 'default', 'theme_version' => '1.0.0', 'theme_authors' => array( 'Henrik Schytte' => 'henrik@schytte.net', 'Marc Pujol' => 'kilburn@la3.org' ), 'theme_licence' => 'GPLv2++', 'theme_color_set' => array('black', 'blue', 'green', 'red', 'yellow') );
MAINT: Add a missing subscription slot to `NestedSequence`
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = [ "Array", "Device", "Dtype", "SupportsDLPack", "SupportsBufferProtocol", "PyCapsule", ] import sys from typing import Any, Literal, Sequence, Type, Union, TYPE_CHECKING, TypeVar from . import Array from numpy import ( dtype, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, ) # This should really be recursive, but that isn't supported yet. See the # similar comment in numpy/typing/_array_like.py _T = TypeVar("_T") NestedSequence = Sequence[Sequence[_T]] Device = Literal["cpu"] if TYPE_CHECKING or sys.version_info >= (3, 9): Dtype = dtype[Union[ int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, ]] else: Dtype = dtype SupportsDLPack = Any SupportsBufferProtocol = Any PyCapsule = Any
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = [ "Array", "Device", "Dtype", "SupportsDLPack", "SupportsBufferProtocol", "PyCapsule", ] import sys from typing import Any, Literal, Sequence, Type, Union, TYPE_CHECKING from . import Array from numpy import ( dtype, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, ) # This should really be recursive, but that isn't supported yet. See the # similar comment in numpy/typing/_array_like.py NestedSequence = Sequence[Sequence[Any]] Device = Literal["cpu"] if TYPE_CHECKING or sys.version_info >= (3, 9): Dtype = dtype[Union[ int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, ]] else: Dtype = dtype SupportsDLPack = Any SupportsBufferProtocol = Any PyCapsule = Any
Deal with MalwareDomains non-ASCII characters
import urllib2 import re from Malcom.model.datatypes import Hostname, Evil from feed import Feed import Malcom.auxiliary.toolbox as toolbox class MalwareDomains(Feed): def __init__(self, name): super(MalwareDomains, self).__init__(name) self.source = "http://mirror1.malwaredomains.com/files/domains.txt" self.description = "Malware domains blocklist" self.confidence = 50 self.name = "MalwareDomains" def update(self): self.update_lines() def analyze(self, line): if line.startswith('#') or line.startswith('\n'): return splitted_mdl = line.split('\t') # 20151201 agasi-story.info malicious blog.dynamoo.com 20131130 20121201 20120521 20110217 # Create the new hostname and store it in the DB hostname = Hostname(hostname=splitted_mdl[2]) if hostname['value'] == None: return # hostname not found evil = Evil() evil['value'] = "Malware domain blocklist (%s)" % hostname['value'] evil['tags'] = ['malwaredomains', re.sub(r'[^\w]', '', splitted_mdl[3])] evil['reference'] = splitted_mdl[4] return hostname, evil
import urllib2 import re from Malcom.model.datatypes import Hostname, Evil from feed import Feed import Malcom.auxiliary.toolbox as toolbox class MalwareDomains(Feed): def __init__(self, name): super(MalwareDomains, self).__init__(name) self.source = "http://mirror1.malwaredomains.com/files/domains.txt" self.description = "Malware domains blocklist" self.confidence = 50 self.name = "MalwareDomains" def update(self): self.update_lines() def analyze(self, line): if line.startswith('#') or line.startswith('\n'): return splitted_mdl = line.split('\t') # 20151201 agasi-story.info malicious blog.dynamoo.com 20131130 20121201 20120521 20110217 # Create the new hostname and store it in the DB hostname = Hostname(hostname=splitted_mdl[2]) if hostname['value'] == None: return # hostname not found evil = Evil() evil['value'] = "Malware domain blocklist (%s)" % hostname['value'] evil['tags'] = ['malwaredomains', splitted_mdl[3]] evil['reference'] = splitted_mdl[4] return hostname, evil
Return suffix ordered by name
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Suffix; class SuffixController extends Controller { public function __construct() {} public function getSuffixes() { try { $suffixes = Suffix::orderBy('name')->get(); } catch (\Exception $e) { throw new \Symfony\Component\HttpKernel\Exception\HttpException('Get failed'); } return response()->json([ 'data' => $suffixes, ]); } public function create(Request $request) { try { $suffix = new Suffix(); $suffix->name = $request->name; $suffix->save(); } catch (\Exception $e) { throw new \Symfony\Component\HttpKernel\Exception\HttpException('Create failed'); } return response()->json([ 'data' => $suffix, ]); } public function delete($id) { try { $suffix = Suffix::find($id); $suffix->delete(); } catch (\Exception $e) { throw new \Symfony\Component\HttpKernel\Exception\HttpException('Delete failed'); } return response()->json(['meta' => ['message' => 'success', 'status_code' => 200]]); } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Suffix; class SuffixController extends Controller { public function __construct() {} public function getSuffixes() { try { $suffixes = Suffix::all(); } catch (\Exception $e) { throw new \Symfony\Component\HttpKernel\Exception\HttpException('Get failed'); } return response()->json([ 'data' => $suffixes, ]); } public function create(Request $request) { try { $suffix = new Suffix(); $suffix->name = $request->name; $suffix->save(); } catch (\Exception $e) { throw new \Symfony\Component\HttpKernel\Exception\HttpException('Create failed'); } return response()->json([ 'data' => $suffix, ]); } public function delete($id) { try { $suffix = Suffix::find($id); $suffix->delete(); } catch (\Exception $e) { throw new \Symfony\Component\HttpKernel\Exception\HttpException('Delete failed'); } return response()->json(['meta' => ['message' => 'success', 'status_code' => 200]]); } }
Set name for users in migration
<?php use DB; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddPasswordAndUsernameFields extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function(Blueprint $table) { $table->string('email')->unique()->change(); $table->string('username', 40)->default(''); $table->string('password')->default(''); }); // Copy name to username. DB::update('UPDATE users SET username = name'); Schema::table('users', function(Blueprint $table) { $table->string('username', 40)->unique()->change(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function(Blueprint $table) { $table->dropColumn('username', 'password'); $table->dropUnique('users_email_unique'); }); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddPasswordAndUsernameFields extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function(Blueprint $table) { $table->string('email')->unique()->change(); $table->string('username', 40)->default(''); $table->string('password')->default(''); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function(Blueprint $table) { $table->dropColumn('username', 'password'); $table->dropUnique('users_email_unique'); }); } }
Fix an import path bug masked by remaining .pyc files
import socket import logger from sockets.broadcast_socket import BroadcastSocket import logger log = logger.getLogger(__name__) class BroadcastAnnouncer(BroadcastSocket): def __init__(self, port): super(BroadcastAnnouncer, self).__init__() self._addr = '255.255.255.255', port self._name = None self.broadcast_payload = "PING None" @property def name(self): return self._name @name.setter def name(self, value): self._name = value self.broadcast_payload = "PING %s" % (self._name) def ping(self): log.info("ping payload: %s" % (self.broadcast_payload)) transmitted = self.socket.sendto(self.broadcast_payload, self._addr) if transmitted != len(self.broadcast_payload): log.warning("ping wasn't successfully broadcast")
import socket import logger from groundstation.broadcast_socket import BroadcastSocket import logger log = logger.getLogger(__name__) class BroadcastAnnouncer(BroadcastSocket): def __init__(self, port): super(BroadcastAnnouncer, self).__init__() self._addr = '255.255.255.255', port self._name = None self.broadcast_payload = "PING None" @property def name(self): return self._name @name.setter def name(self, value): self._name = value self.broadcast_payload = "PING %s" % (self._name) def ping(self): log.info("ping payload: %s" % (self.broadcast_payload)) transmitted = self.socket.sendto(self.broadcast_payload, self._addr) if transmitted != len(self.broadcast_payload): log.warning("ping wasn't successfully broadcast")
Update config to remove Propel feed handler This should be added by an app that combines propel and rssr feeds.
<?php namespace Rssr\Aura_Feeds_Bundle\Config; use Aura\Di\Container; use Aura\Di\ContainerConfig; class Common extends ContainerConfig { public function define(Container $di) { $di->set('rssr/feeds:factory', $di->lazyNew('Rssr\Feed\Factory')); $di->set('rssr/feeds:collection-factory', $di->lazyNew('Rssr\Feed\Collection\Factory')); } public function modify(Container $di) { /** * @var \Rssr\Feed\Factory */ $factory = $di->get('rssr/feeds:factory'); $factory->addHandler('Rssr\Feed\Atom'); $factory->addHandler('Rssr\Feed\Rss'); /** * @var \Rssr\Feed\Collection\Factory */ $collectionFactory = $di->get('rssr/feeds:collection-factory'); $collectionFactory->setHandler('Rssr\Feed\Collection'); } }
<?php namespace Rssr\Aura_Feeds_Bundle\Config; use Aura\Di\Container; use Aura\Di\ContainerConfig; class Common extends ContainerConfig { public function define(Container $di) { $di->set('rssr/feeds:factory', $di->lazyNew('Rssr\Feed\Factory')); $di->set('rssr/feeds:collection-factory', $di->lazyNew('Rssr\Feed\Collection\Factory')); } public function modify(Container $di) { /** * @var \Rssr\Feed\Factory */ $factory = $di->get('rssr/feeds:factory'); $factory->addHandler('Rssr\Feed\Propel'); $factory->addHandler('Rssr\Feed\Atom'); $factory->addHandler('Rssr\Feed\Rss'); /** * @var \Rssr\Feed\Collection\Factory */ $collectionFactory = $di->get('rssr/feeds:collection-factory'); $collectionFactory->setHandler('Rssr\Feed\Collection'); } }
Test that @cached_property really caches
import sys from funcy.objects import * ### @cached_property def test_set_cached_property(): calls = [0] class A(object): @cached_property def prop(self): calls[0] += 1 return 7 a = A() assert a.prop == 7 assert a.prop == 7 assert calls == [1] a.prop = 42 assert a.prop == 42 ### Monkey tests def test_monkey(): class A(object): def f(self): return 7 @monkey(A) def f(self): return f.original(self) * 6 assert A().f() == 42 def test_monkey_property(): class A(object): pass @monkey(A) @property def prop(self): return 42 assert A().prop == 42 def f(x): return x def test_monkey_module(): this_module = sys.modules[__name__] @monkey(this_module) def f(x): return f.original(x) * 2 assert f(21) == 42
import sys from funcy.objects import * ### @cached_property def test_set_cached_property(): class A(object): @cached_property def prop(self): return 7 a = A() assert a.prop == 7 a.prop = 42 assert a.prop == 42 ### Monkey tests def test_monkey(): class A(object): def f(self): return 7 @monkey(A) def f(self): return f.original(self) * 6 assert A().f() == 42 def test_monkey_property(): class A(object): pass @monkey(A) @property def prop(self): return 42 assert A().prop == 42 def f(x): return x def test_monkey_module(): this_module = sys.modules[__name__] @monkey(this_module) def f(x): return f.original(x) * 2 assert f(21) == 42
Remove focus from search field after search for better mobile experience
import $ from 'jquery'; import _ from 'underscore'; import {View} from 'backbone'; import templates from '../models/templates'; class Header extends View { constructor(model) { super(); this.setElement('#header'); this.model = model; this.template = 'header'; if (templates.get(this.template)) { this.render(); } this.listenTo(templates, `change:${this.template}`, this.render); } events() { return { 'submit #form': 'search' } } render() { const template = _.template(templates.get(this.template)); this.$('.header__search').html(template()); return this; } search(event) { event.preventDefault(); const query = $(event.target).find('#search_input').blur().val(); this.model.search(query); } } export default Header;
import $ from 'jquery'; import _ from 'underscore'; import {View} from 'backbone'; import templates from '../models/templates'; class Header extends View { constructor(model) { super(); this.setElement('#header'); this.model = model; this.template = 'header'; if (templates.get(this.template)) { this.render(); } this.listenTo(templates, `change:${this.template}`, this.render); } events() { return { 'submit #form': 'search' } } render() { const template = _.template(templates.get(this.template)); this.$('.header__search').html(template()); return this; } search(event) { event.preventDefault(); const query = $(event.target).find('#search_input').val(); this.model.search(query); } } export default Header;
Update Harmonia client example to reflect changes in 0.4
'use strict'; var Harmonia = require('harmonia'); // Create a new server that listens to a given queue var harmonia = new Harmonia.Server('rpc'); harmonia.route({ method : 'math.add', module : './math/add.js' }); harmonia.route({ method : 'math.subtract', module : './math/subtract.js', }); harmonia.route({ method : 'math.divide', module : './math/divide.js', }); // Start the server harmonia.listen('amqp://localhost'); // Make some requests using the Harmonia client var client = Harmonia.Client.createClient('amqp://localhost', 'request'); client.then(function(client) { client.call('math.add', { x : 15, y : 5 }) .then(function(result) { console.log('add', result.content); }); client.call('math.subtract', { x : 15, y : 5 }) .then(function(result) { console.log('subtract', result.content); }); client.call('math.divide', { x : 15, y : 5 }) .then(function(result) { console.log('divide', result.content); }); });
'use strict'; var Harmonia = require('harmonia'); // Create a new server that listens to a given queue var harmonia = new Harmonia.Server('rpc'); harmonia.route({ method : 'math.add', module : './math/add.js' }); harmonia.route({ method : 'math.subtract', module : './math/subtract.js', }); harmonia.route({ method : 'math.divide', module : './math/divide.js', }); // Start the server harmonia.listen('amqp://localhost'); // Make some requests using the Harmonia client var client = Harmonia.Client.createClient('amqp://localhost', 'request', 'math.add'); client.call('math.add', { x : 15, y : 5 }) .then(function(result) { console.log('add', result.content); }); client.call('math.subtract', { x : 15, y : 5 }) .then(function(result) { console.log('subtract', result.content); }); client.call('math.divide', { x : 15, y : 5 }) .then(function(result) { console.log('divide', result.content); });
Add Parameterizable flag at the toplevel for now.
package de.lmu.ifi.dbs.elki.distance.distancefunction; import de.lmu.ifi.dbs.elki.data.DatabaseObject; import de.lmu.ifi.dbs.elki.database.Database; import de.lmu.ifi.dbs.elki.database.query.DistanceQuery; import de.lmu.ifi.dbs.elki.distance.distancevalue.Distance; import de.lmu.ifi.dbs.elki.utilities.optionhandling.Parameterizable; /** * Base interface for any kind of distances. * * @author Erich Schubert * * @param <O> Object type * @param <D> Distance result type */ public interface DistanceFunction<O extends DatabaseObject, D extends Distance<D>> extends Parameterizable { /** * Method to get the distance functions factory. * * @return Factory for distance objects */ D getDistanceFactory(); /** * Is this function symmetric? * * @return {@code true} when symmetric */ boolean isSymmetric(); /** * Is this distance function metric (in particular, does it satisfy the * triangle equation?) * * @return {@code true} when metric. */ boolean isMetric(); /** * Get the input data type of the function. */ Class<? super O> getInputDatatype(); /** * Instantiate with a database to get the actual distance query. * * @param database * @return Actual distance query. */ public <T extends O> DistanceQuery<T, D> instantiate(Database<T> database); }
package de.lmu.ifi.dbs.elki.distance.distancefunction; import de.lmu.ifi.dbs.elki.data.DatabaseObject; import de.lmu.ifi.dbs.elki.database.Database; import de.lmu.ifi.dbs.elki.database.query.DistanceQuery; import de.lmu.ifi.dbs.elki.distance.distancevalue.Distance; /** * Base interface for any kind of distances. * * @author Erich Schubert * * @param <O> Object type * @param <D> Distance result type */ public interface DistanceFunction<O extends DatabaseObject, D extends Distance<D>> { /** * Method to get the distance functions factory. * * @return Factory for distance objects */ D getDistanceFactory(); /** * Is this function symmetric? * * @return {@code true} when symmetric */ boolean isSymmetric(); /** * Is this distance function metric (in particular, does it satisfy the * triangle equation?) * * @return {@code true} when metric. */ boolean isMetric(); /** * Get the input data type of the function. */ Class<? super O> getInputDatatype(); /** * Instantiate with a database to get the actual distance query. * * @param database * @return Actual distance query. */ public <T extends O> DistanceQuery<T, D> instantiate(Database<T> database); }
Sort by key now confirms both inputs are objects before comparing keys.
exports.sort = function (Handlebars) { return function (input, key, options) { if (arguments.length === 1) { throw new Error('Handlebars Helper "sort" needs 1 parameter'); } options = arguments[arguments.length - 1]; if (arguments.length === 2) { key = undefined; } var results = input.concat(); if (key === undefined) { results.sort(); } else { results.sort(function (a, b) { if (typeof a !== 'object' && typeof b !== 'object') return 0; if (typeof a !== 'object') return -1; if (typeof b !== 'object') return 1; return a[key] > b[key]; }); } if (!options.fn) { return results; } else { if (results.length) { var data = Handlebars.createFrame(options.data); return results.map(function (result, i) { data.index = i; data.first = (i === 0); data.last = (i === results.length - 1); return options.fn(result, {data: data}); }).join(''); } else { return options.inverse(this); } } }; };
exports.sort = function (Handlebars) { return function (array, field, options) { if (arguments.length === 1) { throw new Error('Handlebars Helper "sort" needs 1 parameter'); } options = arguments[arguments.length - 1]; if (arguments.length === 2) { field = undefined; } var results; if (field === undefined) { results = array.sort(); } else { results = array.sort(function (a, b) { return a[field] > b[field]; }); } if (!options.fn) { return results; } else { if (results.length) { var data = Handlebars.createFrame(options.data); return results.map(function (result, i) { data.index = i; data.first = (i === 0); data.last = (i === results.length - 1); return options.fn(result, {data: data}); }).join(''); } else { return options.inverse(this); } } }; };
Support for junit 4.7+ maven test runner, previously this test would not have been run and without this change it receives a No runnable methods found error.
/****************************************************************************** * Copyright (c) 2006, 2010 VMware Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html and the Apache License v2.0 * is available at http://www.opensource.org/licenses/apache2.0.php. * You may elect to redistribute this code under either of these licenses. * * Contributors: * VMware Inc. *****************************************************************************/ package org.eclipse.gemini.blueprint.internal.service.collection.threading; import edu.umd.cs.mtc.MultithreadedTest; import edu.umd.cs.mtc.TestFramework; import org.junit.Test; /** * @author Costin Leau * */ public abstract class BaseThreadingTest extends MultithreadedTest { static int RUN_TIMES = 3; @Test public void runTest() throws Throwable { TestFramework.runManyTimes(this, RUN_TIMES); } }
/****************************************************************************** * Copyright (c) 2006, 2010 VMware Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html and the Apache License v2.0 * is available at http://www.opensource.org/licenses/apache2.0.php. * You may elect to redistribute this code under either of these licenses. * * Contributors: * VMware Inc. *****************************************************************************/ package org.eclipse.gemini.blueprint.internal.service.collection.threading; import edu.umd.cs.mtc.MultithreadedTest; import edu.umd.cs.mtc.TestFramework; /** * @author Costin Leau * */ public abstract class BaseThreadingTest extends MultithreadedTest { static int RUN_TIMES = 3; public void runTest() throws Throwable { TestFramework.runManyTimes(this, RUN_TIMES); } public void testRun() throws Throwable { // do nothing - just to comply with the test suite } }
Refactor common logic for setting up RootCtrl and scope
'use strict'; /* jasmine specs for controllers go here */ describe('RootCtrl', function(){ var scope; beforeEach(module('swiftBrowser.controllers')); beforeEach(inject(function($controller) { scope = {}; $controller('RootCtrl', {$scope: scope}); })); it('should list containers', inject(function($httpBackend) { var containers = [ {"count": 10, "bytes": 1234, "name": "foo"}, {"count": 20, "bytes": 2345, "name": "bar"}, ]; $httpBackend.whenGET('/v1/AUTH_abc?format=json') .respond(200, containers); expect(scope.containers).toEqual([]); $httpBackend.flush(); expect(scope.containers).toEqual(containers); })); it('should set sort order', function() { expect(scope.orderProp).toEqual('name'); }); });
'use strict'; /* jasmine specs for controllers go here */ describe('RootCtrl', function(){ beforeEach(module('swiftBrowser.controllers')); it('should list containers', inject(function($controller, $httpBackend) { var containers = [ {"count": 10, "bytes": 1234, "name": "foo"}, {"count": 20, "bytes": 2345, "name": "bar"}, ]; var scope = {}; $httpBackend.whenGET('/v1/AUTH_abc?format=json') .respond(200, containers); $controller('RootCtrl', {$scope: scope}); expect(scope.containers).toEqual([]); $httpBackend.flush(); expect(scope.containers).toEqual(containers); })); it('should set sort order', inject(function($controller) { var scope = {}; $controller('RootCtrl', {$scope: scope}); expect(scope.orderProp).toEqual('name'); })); });
Correct fake action test name Change-Id: Ibb2322139fd8d7f3365d3522afde622def910fe9
# -*- coding: utf-8 -*- # # Copyright 2013 - StackStorm, 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. from mistral.engine.actions import actions from mistral.engine.actions import action_types from mistral.tests import base class FakeActionTest(base.BaseTest): def test_fake_action(self): expected = "my output" action = actions.EchoAction(action_types.ECHO, "test", output=expected) self.assertEqual(action.run(), expected)
# -*- coding: utf-8 -*- # # Copyright 2013 - StackStorm, 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. from mistral.engine.actions import actions from mistral.engine.actions import action_types from mistral.tests import base class FakeActionTest(base.BaseTest): def test_send_email_real(self): expected = "my output" action = actions.EchoAction(action_types.ECHO, "test", output=expected) self.assertEqual(action.run(), expected)
Update link to repo and description
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( # Application name: name="blynkapi", # Version number (initial): version="0.1.2", description="This is a simple blynk HTTP/HTTPS API wrapper.", long_description=long_description, #URL url='https://github.com/xandr2/blynkapi', download_url = 'https://github.com/xandr2/blynkapi/archive/0.1.2.tar.gz', # Application author details: author="Alexandr Borysov", author_email="xandr2@gmail.com", # License license='MIT', keywords=['python', 'blynk', 'HTTP/HTTPS', 'API', 'wrapper'], # Packages packages=["blynkapi"], # Include additional files into the package #include_package_data=True, # # license="LICENSE.txt", # long_description=open("README.txt").read(), # Dependent packages (distributions) #install_requires=[ # "urllib2", #], classifiers = [], )
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( # Application name: name="blynkapi", # Version number (initial): version="0.1.1", description="This is a simple blynk API wrapper.", long_description=long_description, #URL url='https://github.com/xandr2/python-blynk-api', download_url = 'https://github.com/xandr2/blynkapi/archive/0.1.1.tar.gz', # Application author details: author="Alexandr Borysov", author_email="xandr2@gmail.com", # License license='MIT', keywords=['python', 'blynk', 'API', 'wrapper'], # Packages packages=["blynkapi"], # Include additional files into the package #include_package_data=True, # # license="LICENSE.txt", # long_description=open("README.txt").read(), # Dependent packages (distributions) #install_requires=[ # "urllib2", #], classifiers = [], )
Update name of institution search URL route
from django.conf.urls import url from api.search import views urlpatterns = [ url(r'^$', views.Search.as_view(), name=views.Search.view_name), url(r'^components/$', views.SearchComponents.as_view(), name=views.SearchComponents.view_name), url(r'^files/$', views.SearchFiles.as_view(), name=views.SearchFiles.view_name), url(r'^projects/$', views.SearchProjects.as_view(), name=views.SearchProjects.view_name), url(r'^registrations/$', views.SearchRegistrations.as_view(), name=views.SearchRegistrations.view_name), url(r'^users/$', views.SearchUsers.as_view(), name=views.SearchUsers.view_name), url(r'^institutions/$', views.SearchInstitutions.as_view(), name=views.SearchInstitutions.view_name), # not currently supported by v1, but should be supported by v2 # url(r'^nodes/$', views.SearchProjects.as_view(), name=views.SearchProjects.view_name), ]
from django.conf.urls import url from api.search import views urlpatterns = [ url(r'^$', views.Search.as_view(), name=views.Search.view_name), url(r'^components/$', views.SearchComponents.as_view(), name=views.SearchComponents.view_name), url(r'^files/$', views.SearchFiles.as_view(), name=views.SearchFiles.view_name), url(r'^projects/$', views.SearchProjects.as_view(), name=views.SearchProjects.view_name), url(r'^registrations/$', views.SearchRegistrations.as_view(), name=views.SearchRegistrations.view_name), url(r'^users/$', views.SearchUsers.as_view(), name=views.SearchUsers.view_name), url(r'^institution/$', views.SearchInstitutions.as_view(), name=views.SearchInstitutions.view_name), # not currently supported by v1, but should be supported by v2 # url(r'^nodes/$', views.SearchProjects.as_view(), name=views.SearchProjects.view_name), ]
Fix nav bar back style
import React from 'react-native' import { Fonts, Metrics, Colors } from '../Themes/' const NavigationStyle = React.StyleSheet.create({ titleWrapper: { flex: 1, padding: Metrics.baseMargin, flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }, navTitle: { color: Colors.black, fontSize: Metrics.fonts.regular, fontFamily: Fonts.bold, justifyContent: 'center', alignSelf: 'center' }, navSubtitle: { flex: 1, color: Colors.black, fontSize: Metrics.fonts.medium, fontFamily: Fonts.base, alignSelf: 'center' }, backButton: { color: Colors.black, padding: Metrics.baseMargin }, navigationBar: { backgroundColor: Colors.steel }, settingsButton: { paddingRight: Metrics.baseMargin, paddingTop: Metrics.baseMargin + 3 } }) export default NavigationStyle
import React from 'react-native' import { Fonts, Metrics, Colors } from '../Themes/' const NavigationStyle = React.StyleSheet.create({ titleWrapper: { flex: 1, padding: Metrics.baseMargin, flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }, navTitle: { color: Colors.black, fontSize: Metrics.fonts.regular, fontFamily: Fonts.bold, justifyContent: 'center', alignSelf: 'center' }, navSubtitle: { flex: 1, color: Colors.black, fontSize: Metrics.fonts.medium, fontFamily: Fonts.base, alignSelf: 'center' }, backButtonText: { color: Colors.white, marginTop: 8, marginLeft: 8, fontFamily: Fonts.bold, padding: Metrics.baseMargin }, navigationBar: { backgroundColor: Colors.steel }, settingsButton: { paddingRight: Metrics.baseMargin, paddingTop: Metrics.baseMargin + 3 } }) export default NavigationStyle
Replace many double quotes with single quotes
""" Defaults for all settings used by AnchorHub """ WRAPPER = '{ }' INPUT = '.' OUTPUT = 'out-anchorhub' ARGPARSER = { 'description': "anchorhub parses through Markdown files and precompiles " "links to specially formatted anchors." } ARGPARSE_INPUT = { 'help': "Path of directory tree to be parsed", } ARGPARSE_OUTPUT = { 'help': "Desired output location (default is \"" + OUTPUT + "\")", 'default': OUTPUT } ARGPARSE_OVERWRITE = { 'help': "Overwrite input files; ignore output location" } ARGPARSE_EXTENSION = { 'help': "Indicate which file extensions to search and run anchorhub on.", 'default': [".md"] } ARGPARSE_WRAPPER = { 'help': "Specify custom wrapper format (default is \"" + WRAPPER + "\")", 'default': WRAPPER }
""" Defaults for all settings used by AnchorHub """ WRAPPER = "{ }" INPUT = "." OUTPUT = "out-anchorhub" ARGPARSER = { "description": "anchorhub parses through Markdown files and precompiles " "links to specially formatted anchors." } ARGPARSE_INPUT = { "help": "Path of directory tree to be parsed", } ARGPARSE_OUTPUT = { "help": "Desired output location (default is \"" + OUTPUT + "\")", "default": OUTPUT } ARGPARSE_OVERWRITE = { "help": "Overwrite input files; ignore output location" } ARGPARSE_EXTENSION = { "help": "Indicate which file extensions to search and run anchorhub on.", "default": [".md"] } ARGPARSE_WRAPPER = { "help": "Specify custom wrapper format (default is \"" + WRAPPER + "\")", "default": WRAPPER }
Add support for the sort parameter when performing a search
<?php namespace SocalNick\Orchestrate; class SearchOperation implements OperationInterface { protected $collection; protected $query = '*'; protected $limit = 10; protected $offset = 0; protected $sort = null; public function __construct($collection, $query = '*', $limit = 10, $offset = 0, $sort = null) { $this->collection = $collection; $this->query = $query; $this->limit = $limit; $this->sort = $sort; if ($limit > 100) { trigger_error(sprintf('Invalid limit: %d. Maximum is 100', $limit)); $limit = 100; } $this->offset = $offset; } public function getEndpoint() { $queryParams = array( 'query' => $this->query, 'limit' => $this->limit, 'offset' => $this->offset, 'sort' => $this->sort, ); return $this->collection . '/?' . http_build_query($queryParams); } public function getObjectFromResponse($link = null, $value = null, $rawValue = null) { return new SearchResult($this->collection, $value, $rawValue); } }
<?php namespace SocalNick\Orchestrate; class SearchOperation implements OperationInterface { protected $collection; protected $query = '*'; protected $limit = 10; protected $offset = 0; public function __construct($collection, $query = '*', $limit = 10, $offset = 0) { $this->collection = $collection; $this->query = $query; $this->limit = $limit; if ($limit > 100) { trigger_error(sprintf('Invalid limit: %d. Maximum is 100', $limit)); $limit = 100; } $this->offset = $offset; } public function getEndpoint() { $queryParams = array( 'query' => $this->query, 'limit' => $this->limit, 'offset' => $this->offset, ); return $this->collection . '/?' . http_build_query($queryParams); } public function getObjectFromResponse($link = null, $value = null, $rawValue = null) { return new SearchResult($this->collection, $value, $rawValue); } }
Add Windows Phone to mobile Add Windows Phone to mobile userAgents
Facebook = {}; // Request Facebook credentials for the user // // @param options {optional} // @param credentialRequestCompleteCallback {Function} Callback function to call on // completion. Takes one argument, credentialToken on success, or Error on // error. Facebook.requestCredential = function (options, credentialRequestCompleteCallback) { // support both (options, callback) and (callback). if (!credentialRequestCompleteCallback && typeof options === 'function') { credentialRequestCompleteCallback = options; options = {}; } var config = ServiceConfiguration.configurations.findOne({service: 'facebook'}); if (!config) { credentialRequestCompleteCallback && credentialRequestCompleteCallback(new ServiceConfiguration.ConfigError("Service not configured")); return; } var credentialToken = Random.id(); var mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone/i.test(navigator.userAgent); var display = mobile ? 'touch' : 'popup'; var scope = "email"; if (options && options.requestPermissions) scope = options.requestPermissions.join(','); var loginUrl = 'https://www.facebook.com/dialog/oauth?client_id=' + config.appId + '&redirect_uri=' + Meteor.absoluteUrl('_oauth/facebook?close') + '&display=' + display + '&scope=' + scope + '&state=' + credentialToken; Oauth.showPopup( loginUrl, _.bind(credentialRequestCompleteCallback, null, credentialToken) ); };
Facebook = {}; // Request Facebook credentials for the user // // @param options {optional} // @param credentialRequestCompleteCallback {Function} Callback function to call on // completion. Takes one argument, credentialToken on success, or Error on // error. Facebook.requestCredential = function (options, credentialRequestCompleteCallback) { // support both (options, callback) and (callback). if (!credentialRequestCompleteCallback && typeof options === 'function') { credentialRequestCompleteCallback = options; options = {}; } var config = ServiceConfiguration.configurations.findOne({service: 'facebook'}); if (!config) { credentialRequestCompleteCallback && credentialRequestCompleteCallback(new ServiceConfiguration.ConfigError("Service not configured")); return; } var credentialToken = Random.id(); var mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent); var display = mobile ? 'touch' : 'popup'; var scope = "email"; if (options && options.requestPermissions) scope = options.requestPermissions.join(','); var loginUrl = 'https://www.facebook.com/dialog/oauth?client_id=' + config.appId + '&redirect_uri=' + Meteor.absoluteUrl('_oauth/facebook?close') + '&display=' + display + '&scope=' + scope + '&state=' + credentialToken; Oauth.showPopup( loginUrl, _.bind(credentialRequestCompleteCallback, null, credentialToken) ); };
Fix notification about flushing the database
var restify = require('restify'); var messenger = require('./lib/messenger'); var session = require('./lib/session'); var server = restify.createServer(); server.use(restify.queryParser()); server.use(restify.bodyParser()); server.use(restify.authorizationParser()); server.get('/', function (req, res, next) { res.send(200, {status: 'ok'}); }); server.post('/messages', function (req, res, next) { var phoneNumber = req.params.From; var message = req.params.Body.toLowerCase(); if (message === 'flush') { session.flushall(function () { messenger.send('The database has been flushed.'); }); } session.get(phoneNumber, function(err, user) { if (err) { messenger.send(phoneNumber, 'There was some kind of error.'); res.send(500, {error: 'Something went wrong.'}); } if (user) { messenger.send(phoneNumber, 'Hello, old friend.'); } else { session.set(phoneNumber, 'initial', function () { messenger.send(phoneNumber, 'Nice to meet you.'); }); } }); res.send(200, {status: 'ok'}); }); server.listen(process.env.PORT || '3000', function() { console.log('%s listening at %s', server.name, server.url); });
var restify = require('restify'); var messenger = require('./lib/messenger'); var session = require('./lib/session'); var server = restify.createServer(); server.use(restify.queryParser()); server.use(restify.bodyParser()); server.use(restify.authorizationParser()); server.get('/', function (req, res, next) { res.send(200, {status: 'ok'}); }); server.post('/messages', function (req, res, next) { var phoneNumber = req.params.From; var message = req.params.Body.toLowerCase(); if (message === 'flush') { session.flushall(function () { messenger('The database has been flushed.'); }); } session.get(phoneNumber, function(err, user) { if (err) { messenger.send(phoneNumber, 'There was some kind of error.'); res.send(500, {error: 'Something went wrong.'}); } if (user) { messenger.send(phoneNumber, 'Hello, old friend.'); } else { session.set(phoneNumber, 'initial', function () { messenger.send(phoneNumber, 'Nice to meet you.'); }); } }); res.send(200, {status: 'ok'}); }); server.listen(process.env.PORT || '3000', function() { console.log('%s listening at %s', server.name, server.url); });
Move logic to new RelativeFallbackResolver
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Mvc\Service; use Zend\ServiceManager\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; use Zend\View\Resolver as ViewResolver; class ViewResolverFactory implements FactoryInterface { /** * Create the aggregate view resolver * * Creates a Zend\View\Resolver\AggregateResolver and attaches the template * map resolver and path stack resolver * * @param ServiceLocatorInterface $serviceLocator * @return ViewResolver\AggregateResolver */ public function createService(ServiceLocatorInterface $serviceLocator) { $resolver = new ViewResolver\AggregateResolver(); $resolver->attach(new ViewResolver\RelativeFallbackResolver($serviceLocator->get('ViewTemplateMapResolver'))); $resolver->attach(new ViewResolver\RelativeFallbackResolver($serviceLocator->get('ViewTemplatePathStack'))); return $resolver; } }
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Mvc\Service; use Zend\ServiceManager\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; use Zend\View\Resolver as ViewResolver; class ViewResolverFactory implements FactoryInterface { /** * Create the aggregate view resolver * * Creates a Zend\View\Resolver\AggregateResolver and attaches the template * map resolver and path stack resolver * * @param ServiceLocatorInterface $serviceLocator * @return ViewResolver\AggregateResolver */ public function createService(ServiceLocatorInterface $serviceLocator) { $resolver = new ViewResolver\AggregateResolver(); $resolver->attach($serviceLocator->get('ViewTemplateMapResolver')); $resolver->attach($serviceLocator->get('ViewTemplatePathStack')); return $resolver; } }
Fix bugs in item test case
package org.qpt.receipt; import org.junit.Test; import static org.junit.Assert.*; /** * Created by Sora on 2016/7/6. */ public class ItemTest { private static Goods getGoods() { Goods goods = new Goods("ITEM000001", "ๅฏๅฃๅฏไน"); goods.setCategory("้ฃŸๅ“", "้ฅฎๆ–™"); goods.setPrice(3.00f, "็“ถ"); return goods; } @Test public void shouldStoreRightQuantity() throws Exception { Item item = new Item(ItemTest.getGoods()); assertEquals(0, item.getQuantity()); item.add(1); assertEquals(1, item.getQuantity()); item.setQuantity(3); assertEquals(3, item.getQuantity()); item.add(2); assertEquals(5, item.getQuantity()); item.remove(3); assertEquals(2, item.getQuantity()); item = new Item(ItemTest.getGoods(), 2); assertEquals(2, item.getQuantity()); } }
package org.qpt.receipt; import org.junit.Test; import static org.junit.Assert.*; /** * Created by Sora on 2016/7/6. */ public class ItemTest { private static Goods getGoods() { Goods goods = new Goods("ITEM000001", "ๅฏๅฃๅฏไน"); goods.setCategory("้ฃŸๅ“", "้ฅฎๆ–™"); goods.setPrice(3.00f, "็“ถ"); return goods; } @Test public void shouldStoreRightQuantity() throws Exception { Item item = new Item(ItemTest.getGoods()); assertEquals(0, item.getQuantity()); item.add(1); assertEquals(1, item.getQuantity()); item.setQuantity(3); assertEquals(3, item.getQuantity()); item.add(2); assertEquals(5, item.getQuantity()); item.remove(3); assertEquals(2, item.getQuantity()); assertEquals(2, new Item(ItemTest.getGoods(), 2)); } }
Use ValidationException for destination_files error Throw VE when an unexpected file appears in the destination that is not matched by the destination_files glob. This is always a user error so we shouldn't use RepoException for this. Change-Id: I7d233a2729d91be92984f9904c8e07b57331d8c8
/* * Copyright (C) 2016 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. */ package com.google.copybara; import java.nio.file.Path; import java.nio.file.PathMatcher; /** * An exception that indicates a file that was to be written to a destination is not actually * included in {@code destination_files}, indicating a bad configuration. */ public class NotADestinationFileException extends ValidationException { NotADestinationFileException(String message) { super(message); } }
/* * Copyright (C) 2016 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. */ package com.google.copybara; import java.nio.file.Path; import java.nio.file.PathMatcher; /** * An exception that indicates a file that was to be written to a destination is not actually * included in {@code destination_files}, indicating a bad configuration. */ public class NotADestinationFileException extends RepoException { public NotADestinationFileException(String message) { super(message); } }
Add avatars for in nearby giveaway sidebar
import React from 'react'; import { List, ListItem } from 'material-ui/List'; import Divider from 'material-ui/Divider'; import Subheader from 'material-ui/Subheader'; import Avatar from 'material-ui/Avatar'; import * as Helper from '../../../util/helper'; import * as AvatarHelper from '../../../util/avatar'; import * as GiveawaysHelper from '../../../util/giveaways'; import * as Colors from 'material-ui/styles/colors'; const giveawayRow = (touchTapHandler) => (ga) => ( <ListItem key={ ga._id } primaryText={ <span className="single-line" style={{ color: Colors.grey700 }}>{ ga.title }</span> } secondaryText={ <p> <span className="location">{ ga.location }</span> </p> } leftAvatar={ ga.avatarId ? <Avatar src={ AvatarHelper.getAvatar(ga.avatarId, 64) } /> : <Avatar icon={ GiveawaysHelper.getCategoryIcon(ga) } backgroundColor={ GiveawaysHelper.getStatusColor(ga) } /> } secondaryTextLines={2} onTouchTap={ touchTapHandler(ga) } /> ); export const NearbyGiveaways = (props) => ( <List> <Subheader> <h3 style={{ margin:"20px 0px 10px" }}>Nearby Giveaways</h3> </Subheader> { Helper.insertDividers(props.giveaways.map(giveawayRow(props.nearbyOnClick))) } </List> );
import React from 'react'; import { List, ListItem } from 'material-ui/List'; import Divider from 'material-ui/Divider'; import Subheader from 'material-ui/Subheader'; import Avatar from 'material-ui/Avatar'; import * as Helper from '../../../util/helper'; import * as Colors from 'material-ui/styles/colors'; const giveawayRow = (touchTapHandler) => (ga) => ( <ListItem key={ ga._id } primaryText={ <span style={{ color: Colors.grey700 }}>{ ga.title }</span> } secondaryText={ <p> <span className="location">{ ga.location }</span> </p> } secondaryTextLines={2} onTouchTap={ touchTapHandler(ga) } /> ); export const NearbyGiveaways = (props) => ( <List> <Subheader> <h3 style={{ margin:"20px 0px 10px" }}>Nearby Giveaways</h3> </Subheader> { Helper.insertDividers(props.giveaways.map(giveawayRow(props.nearbyOnClick))) } </List> );
Update available log screen settings
var url = require('url'); var extend = require('xtend'); module.exports = function matrixUrl(opts) { var _opts = {}; if (typeof opts === 'string') _opts = url.parse(opts); if (typeof opts === 'object' && typeof opts.href === 'string') _opts = url.parse(opts.href); _opts.query = { SQ_BACKEND_PAGE: 'main', backend_section: 'am', am_section: 'edit_asset', assetid: opts.assetId || '', asset_ei_screen: '', ignore_frames: '1' }; if (/log/.test(opts.screen)) { _opts.query = extend(_opts.query, { assetid: '3', log_manager_3_direct_connection: 'true', log_manager_3_action: 'monitor', log_manager_3_log: opts.level || 'error', rand: opts.rand || '', log_manager_3_num_lines: opts.lines || '25', log_manager_3_offset: opts.offset || '' }); } return url.format(_opts); };
var url = require('url'); var extend = require('xtend'); module.exports = function matrixUrl(opts) { var _opts = {}; if (typeof opts === 'string') _opts = url.parse(opts); if (typeof opts === 'object' && typeof opts.href === 'string') _opts = url.parse(opts.href); _opts.query = { SQ_BACKEND_PAGE: 'main', backend_section: 'am', am_section: 'edit_asset', assetid: opts.assetId || '', asset_ei_screen: '', ignore_frames: '1' }; if (/log/.test(opts.screen)) { _opts.query = extend(_opts.query, { assetid: '3', log_manager_3_direct_connection: 'true', log_manager_3_action: 'monitor', log_manager_3_log: opts.level || 'error', rand: opts.rand || '', log_manager_3_num_lines: opts.lines || '25', log_manager_3_offset: '' }); } return url.format(_opts); };
Add draggable attr to <img>s and set it to false
Emoji = {}; Emoji.baseImagePath = '/packages/davidfrancisco_twemoji/img/'; Emoji.convert = function (str) { if (typeof str !== 'string') { return ''; } return str.replace(/:[\+\-a-z0-9_]+:/gi, function(match) { var imgName = match.slice(1, -1), path = Emoji.baseImagePath + imgName + '.png'; return '<img class="emoji" alt="' + match + '" src="' + path + '" draggable="false" />'; }); }; // borrowed code from https://github.com/meteor/meteor/blob/devel/packages/showdown/template-integration.js if (Package.templating) { var Template = Package.templating.Template; var Blaze = Package.blaze.Blaze; // implied by `templating` var HTML = Package.htmljs.HTML; // implied by `blaze` Blaze.Template.registerHelper('emoji', new Template('emoji', function () { var view = this, content = ''; if (view.templateContentBlock) { // this is for the block usage eg: {{#emoji}}:smile:{{/emoji}} content = Blaze._toText(view.templateContentBlock, HTML.TEXTMODE.STRING); } else { // this is for the direct usage eg: {{> emoji ':blush:'}} content = view.parentView.dataVar.get(); } return HTML.Raw(Emoji.convert(content)); })); }
Emoji = {}; Emoji.baseImagePath = '/packages/davidfrancisco_twemoji/img/'; Emoji.convert = function (str) { if (typeof str !== 'string') { return ''; } return str.replace(/:[\+\-a-z0-9_]+:/gi, function(match) { var imgName = match.slice(1, -1), path = Emoji.baseImagePath + imgName + '.png'; return '<img class="emoji" alt="' + match + '" src="' + path + '"/>'; }); }; // borrowed code from https://github.com/meteor/meteor/blob/devel/packages/showdown/template-integration.js if (Package.templating) { var Template = Package.templating.Template; var Blaze = Package.blaze.Blaze; // implied by `templating` var HTML = Package.htmljs.HTML; // implied by `blaze` Blaze.Template.registerHelper('emoji', new Template('emoji', function () { var view = this, content = ''; if (view.templateContentBlock) { // this is for the block usage eg: {{#emoji}}:smile:{{/emoji}} content = Blaze._toText(view.templateContentBlock, HTML.TEXTMODE.STRING); } else { // this is for the direct usage eg: {{> emoji ':blush:'}} content = view.parentView.dataVar.get(); } return HTML.Raw(Emoji.convert(content)); })); }
Call all socket functions in socket handler
"use strict"; var game = game || {}; game.socketHandlers = { init : function(app) { /*me.canvas = document.querySelector('#area'); me.ctx = me.canvas.getContext('2d'); me.ctx.lineWidth = 5; me.arena = game.createArena('white', me.canvas.height/2-10, me.canvas.width/2, me.canvas.height/2);*/ //Set up socket events --Ha Andrew don't look at this --You can't stop me socket.on('player join', function(data){ var x = app.canvas.width/2, y = app.canvas.height/2; app.players[data.id] = new game.Player(data.id, data.color, x, y); app.playerIDs.push(data.id); }); socket.on('player leave', function(data){ app.playerIDs.splice(app.playerIDs.indexOf(data.id),1); delete app.players[data.id]; }); socket.on('charge start', function(data){ app.players[data.id].beginCharge(); }); socket.on('charge end', function(data){ app.players[data.id].endCharge(); }); socket.on('phone tilt', function(data) { if(app.players[data.id]) { app.players[data.id].updateAcceleration(data.yAcc/300, -data.xAcc/300); } //my eyes are everywhere --I will gouge your eyes out }); } }
me.canvas = document.querySelector('#area'); me.ctx = me.canvas.getContext('2d'); me.ctx.lineWidth = 5; me.arena = game.createArena('white', /*230*/me.canvas.height/2-10, me.canvas.width/2, me.canvas.height/2); //Set up socket events --Ha Andrew don't look at this --You can't stop me socket.on('player join', function(data){ var x = me.canvas.width/2, y = me.canvas.height/2; me.players[data.id] = new game.Player(data.id, data.color, x, y); me.playerIDs.push(data.id); }); socket.on('player leave', function(data){ me.playerIDs.splice(me.playerIDs.indexOf(data.id),1); delete me.players[data.id]; }); socket.on('charge start', function(data){ me.players[data.id].beginCharge(); }); socket.on('charge end', function(data){ me.players[data.id].endCharge(); }); socket.on('phone tilt', function(data) { if(me.players[data.id]) { me.players[data.id].updateAcceleration(data.yAcc/300, -data.xAcc/300); } //my eyes are everywhere --I will gouge your eyes out });
Change the way to find a store saved Signed-off-by: Aitor Magรกn <a93a7d273b830b2e8a26461c1a80328a1d7ad27a@conwet.com>
/** * Copyright (c) 2015, CoNWeT Lab., Universidad Politรฉcnica de Madrid * Code licensed under BSD 3-Clause (https://github.com/conwetlab/WMarket/blob/master/LICENSE) */ var StoreManager = (function () { "use strict"; var StoreManager = function StoreManager() { this.storeList = {}; }; StoreManager.prototype.addStore = function addStore(data) { var store; store = new Store(data); this.storeList[store.name] = store; return store; }; StoreManager.prototype.getStoreByName = function getStoreByName(name) { var store, storeException; if (!(store=this.storeList[name])) { storeException = new Exception("The store '%(name)s' is not saved.".replace("%(name)s", name)); storeException.name = "Store Not Found"; throw storeException; } return store; }; if (WMarket && WMarket.resources) { WMarket.resources.stores = new StoreManager(); } return StoreManager; })();
/** * Copyright (c) 2015, CoNWeT Lab., Universidad Politรฉcnica de Madrid * Code licensed under BSD 3-Clause (https://github.com/conwetlab/WMarket/blob/master/LICENSE) */ var StoreManager = (function () { "use strict"; var StoreManager = function StoreManager() { this.storeList = []; }; StoreManager.prototype.addStore = function addStore(data) { var newStore; newStore = new Store(data); this.storeList.push(newStore); return newStore; }; StoreManager.prototype.getStoreByName = function getStoreByName(name) { var found, i, storeFound; for (found = false, i = 0; !found && i < this.storeList.length; i++) { if (this.storeList[i].name == name) { found = true; storeFound = this.storeList[i]; } } return storeFound; }; if (typeof WMarket !== 'undefined' && 'resources' in WMarket) { WMarket.resources.stores = new StoreManager(); } return StoreManager; })();
Allow the option of specifying a path in startup
import subprocess import commands import signal import os import logging _logger = logging.getLogger(__name__) TARGET_DIR='test/target' PORT='27018' def startup(mongo_path): _logger.info("about to start mongod") path = mongo_path or commands.getoutput('which mongod') p = subprocess.Popen([path, '--port', PORT, '--fork', '--dbpath', '{0}/db'.format(TARGET_DIR), '--logpath', '{0}/mongo.log'.format(TARGET_DIR), '--smallfiles', '--noprealloc']) p.wait() _logger.info("mongod started successfully") def teardown(): _logger.info("about to stop mongod") with open('{0}/db/mongod.lock'.format(TARGET_DIR), 'r') as log_file: first_line = log_file.readline() pid = int(first_line) os.kill(pid, signal.SIGTERM) _logger.info("mongodb stopped")
import subprocess import commands import re import signal import os import logging _logger = logging.getLogger(__name__) TARGET_DIR='test/target' PORT='27018' def startup(): _logger.info("about to start mongod") p = subprocess.Popen([commands.getoutput('which mongod'), '--port', PORT, '--fork', '--dbpath', '{0}/db'.format(TARGET_DIR), '--logpath', '{0}/mongo.log'.format(TARGET_DIR), '--smallfiles', '--noprealloc']) p.wait() _logger.info("mongod started successfully") def teardown(): _logger.info("about to stop mongod") with open('{0}/db/mongod.lock'.format(TARGET_DIR), 'r') as log_file: first_line = log_file.readline() pid = int(first_line) os.kill(pid, signal.SIGTERM) _logger.info("mongodb stopped")
Call the callback function only when the target element is intersecting the root element; Avoids extra calls.
import React from 'react' import Link from 'gatsby-link' export default class InfiniteScrollLink extends React.Component { constructor (props) { super(props) const observerOptions = { root: null, rootMargin: '0px', threshold: 0.25 } this.observerCallback = this.observerCallback.bind(this) this.state = { observer: new window.IntersectionObserver(this.observerCallback(props.callback || (() => {})), observerOptions) } } componentDidMount () { this.state.observer.observe(document.querySelector('#infinite-scroll-link')) } componentWillUnmount () { if (this.state.observer.unobserve instanceof Function) { this.state.observer.unobserve(document.querySelector('#infinite-scroll-link')) } } observerCallback (callback) { return (entries) => { entries.forEach(entry => { if (entry.isIntersecting) { callback(this.props.url) } }) } } render () { return ( <Link id='infinite-scroll-link' to={this.props.url}> { this.props.linkName } </Link> ) } }
import React from 'react' import Link from 'gatsby-link' export default class InfiniteScrollLink extends React.Component { constructor (props) { super(props) const observerOptions = { root: null, rootMargin: '0px', threshold: 0.25 } this.observerCallback = this.observerCallback.bind(this) this.state = { observer: new window.IntersectionObserver(this.observerCallback(props.callback || (() => {})), observerOptions) } } componentDidMount () { this.state.observer.observe(document.querySelector('#infinite-scroll-link')) } componentWillUnmount () { if (this.state.observer.unobserve instanceof Function) { this.state.observer.unobserve(document.querySelector('#infinite-scroll-link')) } } observerCallback (callback) { return () => { return callback(this.props.url) } } render () { return ( <Link id='infinite-scroll-link' to={this.props.url}> { this.props.linkName } </Link> ) } }
Add missing function calls in tests
'use strict'; var Chance = require('chance'), chance = new Chance(); class InvitePage { constructor () { this.titleEl = element(by.css('.project-title')); this.message = chance.sentence(); this.AddPeopleBtn = element(by.css('.invite-button')); this.inviteBtn = element(by.css('[ng-click="inviteUsers()"]')); } get () { browser.wait(protractor.ExpectedConditions.visibilityOf(this.AddPeopleBtn)); this.AddPeopleBtn.click(); } invite (who) { this.inputInvite = element(by.css('.selectize-input input')); this.inviteOption = () => element(by.css('.create[data-selectable], .cachedOption[data-selectable]')); browser.wait(protractor.ExpectedConditions.visibilityOf(this.inputInvite)); this.inputInvite.click(); this.inputInvite.sendKeys(who); browser.wait(protractor.ExpectedConditions.presenceOf(this.inviteOption())); browser.wait(protractor.ExpectedConditions.visibilityOf(this.inviteOption())); this.inviteOption().click(); this.focusedInvite = element(by.css('.selectize-input input:focus')); // to blur input in email invite case. this.inputInvite.sendKeys(protractor.Key.TAB); browser.wait(protractor.ExpectedConditions.visibilityOf(this.inviteBtn)); return this.inviteBtn.click(); } } module.exports = InvitePage;
'use strict'; var Chance = require('chance'), chance = new Chance(); class InvitePage { constructor () { this.titleEl = element(by.css('.project-title')); this.message = chance.sentence(); this.AddPeopleBtn = element(by.css('.invite-button')); this.inviteBtn = element(by.css('[ng-click="inviteUsers()"]')); } get () { browser.wait(protractor.ExpectedConditions.visibilityOf(this.AddPeopleBtn)); this.AddPeopleBtn.click(); } invite (who) { this.inputInvite = element(by.css('.selectize-input input')); this.inviteOption = () => element(by.css('.create[data-selectable], .cachedOption[data-selectable]')); browser.wait(protractor.ExpectedConditions.visibilityOf(this.inputInvite)); this.inputInvite.click(); this.inputInvite.sendKeys(who); browser.wait(protractor.ExpectedConditions.presenceOf(this.inviteOption)); browser.wait(protractor.ExpectedConditions.visibilityOf(this.inviteOption)); this.inviteOption().click(); this.focusedInvite = element(by.css('.selectize-input input:focus')); // to blur input in email invite case. this.inputInvite.sendKeys(protractor.Key.TAB); browser.wait(protractor.ExpectedConditions.visibilityOf(this.inviteBtn)); return this.inviteBtn.click(); } } module.exports = InvitePage;
Fix unicode tests to work with new temp file assertions
import os from tests.test_pip import here, reset_env, run_pip def test_install_package_that_emits_unicode(): """ Install a package with a setup.py that emits UTF-8 output and then fails. This works fine in Python 2, but fails in Python 3 with: Traceback (most recent call last): ... File "/Users/marc/python/virtualenvs/py3.1-phpserialize/lib/python3.2/site-packages/pip-1.0.2-py3.2.egg/pip/__init__.py", line 230, in call_subprocess line = console_to_str(stdout.readline()) File "/Users/marc/python/virtualenvs/py3.1-phpserialize/lib/python3.2/site-packages/pip-1.0.2-py3.2.egg/pip/backwardcompat.py", line 60, in console_to_str return s.decode(console_encoding) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 17: ordinal not in range(128) Refs https://github.com/pypa/pip/issues/326 """ env = reset_env() to_install = os.path.abspath(os.path.join(here, 'packages', 'BrokenEmitsUTF8')) result = run_pip('install', to_install, expect_error=True, expect_temp=True, quiet=True) assert '__main__.FakeError: this package designed to fail on install' in result.stdout assert 'UnicodeDecodeError' not in result.stdout
import os from tests.test_pip import here, reset_env, run_pip def test_install_package_that_emits_unicode(): """ Install a package with a setup.py that emits UTF-8 output and then fails. This works fine in Python 2, but fails in Python 3 with: Traceback (most recent call last): ... File "/Users/marc/python/virtualenvs/py3.1-phpserialize/lib/python3.2/site-packages/pip-1.0.2-py3.2.egg/pip/__init__.py", line 230, in call_subprocess line = console_to_str(stdout.readline()) File "/Users/marc/python/virtualenvs/py3.1-phpserialize/lib/python3.2/site-packages/pip-1.0.2-py3.2.egg/pip/backwardcompat.py", line 60, in console_to_str return s.decode(console_encoding) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 17: ordinal not in range(128) Refs https://github.com/pypa/pip/issues/326 """ env = reset_env() to_install = os.path.abspath(os.path.join(here, 'packages', 'BrokenEmitsUTF8')) result = run_pip('install', to_install, expect_error=True) assert '__main__.FakeError: this package designed to fail on install' in result.stdout assert 'UnicodeDecodeError' not in result.stdout
Include Rank in transforms registry.
module.exports = { aggregate: require('./Aggregate'), bin: require('./Bin'), cross: require('./Cross'), countpattern: require('./CountPattern'), linkpath: require('./LinkPath'), facet: require('./Facet'), filter: require('./Filter'), fold: require('./Fold'), force: require('./Force'), formula: require('./Formula'), geo: require('./Geo'), geopath: require('./GeoPath'), hierarchy: require('./Hierarchy'), impute: require('./Impute'), lookup: require('./Lookup'), pie: require('./Pie'), rank: require('./Rank'), sort: require('./Sort'), stack: require('./Stack'), treeify: require('./Treeify'), treemap: require('./Treemap'), voronoi: require('./Voronoi'), wordcloud: require('./Wordcloud') };
module.exports = { aggregate: require('./Aggregate'), bin: require('./Bin'), cross: require('./Cross'), countpattern: require('./CountPattern'), linkpath: require('./LinkPath'), facet: require('./Facet'), filter: require('./Filter'), fold: require('./Fold'), force: require('./Force'), formula: require('./Formula'), geo: require('./Geo'), geopath: require('./GeoPath'), hierarchy: require('./Hierarchy'), impute: require('./Impute'), lookup: require('./Lookup'), pie: require('./Pie'), sort: require('./Sort'), stack: require('./Stack'), treeify: require('./Treeify'), treemap: require('./Treemap'), voronoi: require('./Voronoi'), wordcloud: require('./Wordcloud') };