hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
0a1a14e8a77ffb04af85fac87025f9ed9b84e202
diff --git a/csg/core.py b/csg/core.py index <HASH>..<HASH> 100644 --- a/csg/core.py +++ b/csg/core.py @@ -103,7 +103,9 @@ class CSG(object): for poly in self.polygons: for vert in poly.vertices: vert.pos = newVector(vert.pos) - vert.normal = newVector(vert.normal) + normal = vert.normal + if normal.length() > 0: + vert.normal = newVector(vert.normal) def toVerticesAndPolygons(self): """ diff --git a/test/test_csg.py b/test/test_csg.py index <HASH>..<HASH> 100644 --- a/test/test_csg.py +++ b/test/test_csg.py @@ -87,6 +87,18 @@ class TestCSG(unittest.TestCase): a.saveVTK('a.vtk') a.translate([0.1, 0.2, 0.3]) a.saveVTK('aTranslated.vtk') + + def test_rotate_Cube(self): + a = CSG.cube() + a.saveVTK('a.vtk') + a.rotate(axis=[0.1, 0.2, 0.3], angleDeg=20.0) + a.saveVTK('aRotated.vtk') + + def test_rotate_cylinder(self): + b = CSG.cylinder() + b.saveVTK('b.vtk') + b.rotate(axis=[0.1, 0.2, 0.3], angleDeg=20.0) + b.saveVTK('bRotated.vtk') if __name__ == '__main__': unittest.main()
rotate runs but seeing weird results for cylinder
timknip_pycsg
train
0a942a9b76c76c2618a5522fe67fdf319dd7d9d6
diff --git a/tests/parser/syntax/test_code_size.py b/tests/parser/syntax/test_code_size.py index <HASH>..<HASH> 100644 --- a/tests/parser/syntax/test_code_size.py +++ b/tests/parser/syntax/test_code_size.py @@ -23,10 +23,15 @@ def test_block_fail(bad_code): valid_list = [ """ @external -def foo() -> int128: +def foo() -> uint256: x: address = 0x1234567890123456789012345678901234567890 return x.codesize + """, """ +@external +def foo() -> uint256: + return self.codesize + """, ]
test: update address.codesize tests
ethereum_vyper
train
e72bf24a3c8572b9ad37dfa704777b0aaee95c03
diff --git a/fades/envbuilder.py b/fades/envbuilder.py index <HASH>..<HASH> 100644 --- a/fades/envbuilder.py +++ b/fades/envbuilder.py @@ -76,6 +76,9 @@ class FadesEnvBuilder(EnvBuilder): logger.error('Virtualenv is not installed. It is needed to create a virtualenv with ' 'a different python version than fades (got {})'.format(error)) exit() + except helpers.ExecutionError as error: + error.dump_to_log(logger) + exit() except Exception as error: logger.exception("Error creating virtualenv: %s", error) exit() diff --git a/fades/helpers.py b/fades/helpers.py index <HASH>..<HASH> 100644 --- a/fades/helpers.py +++ b/fades/helpers.py @@ -31,6 +31,23 @@ d.update(zip('major minor micro releaselevel serial'.split(), sys.version_info)) print(json.dumps(d)) """ +STDOUT_LOG_PREFIX = ":: " + + +class ExecutionError(Exception): + """Execution of subprocess ended not in 0.""" + def __init__(self, retcode, cmd, collected_stdout): + self._retcode = retcode + self._cmd = cmd + self._collected_stdout = collected_stdout + super().__init__() + + def dump_to_log(self, logger): + """Send the cmd info and collected stdout to logger.""" + logger.error("Execution ended in %s for cmd %s", self._retcode, self._cmd) + for line in self._collected_stdout: + logger.error(STDOUT_LOG_PREFIX + line) + def logged_exec(cmd): """Execute a command, redirecting the output to the log.""" @@ -41,10 +58,10 @@ def logged_exec(cmd): for line in p.stdout: line = line[:-1].decode("utf8") stdout.append(line) - logger.debug(":: " + line) + logger.debug(STDOUT_LOG_PREFIX + line) retcode = p.wait() if retcode: - raise subprocess.CalledProcessError(retcode, cmd) + raise ExecutionError(retcode, cmd, stdout) return stdout diff --git a/fades/pipmanager.py b/fades/pipmanager.py index <HASH>..<HASH> 100644 --- a/fades/pipmanager.py +++ b/fades/pipmanager.py @@ -56,6 +56,9 @@ class PipManager(): logger.info("Installing dependency: %s", str_dep) try: helpers.logged_exec(args) + except helpers.ExecutionError as error: + error.dump_to_log(logger) + exit() except Exception as error: logger.exception("Error installing %s: %s", str_dep, error) exit()
Better error reporting when executing a subprocess.
PyAr_fades
train
dd59ba682be61fdd12f4ddfbf71c3a10950a9343
diff --git a/Classes/Factory/AbstractFormFactory.php b/Classes/Factory/AbstractFormFactory.php index <HASH>..<HASH> 100644 --- a/Classes/Factory/AbstractFormFactory.php +++ b/Classes/Factory/AbstractFormFactory.php @@ -94,7 +94,7 @@ abstract class AbstractFormFactory implements FormFactoryInterface { * @var array * @api */ - protected $settings; + protected $formSettings; /** * @FLOW3\Inject @@ -107,7 +107,7 @@ abstract class AbstractFormFactory implements FormFactoryInterface { * @internal */ public function initializeObject() { - $this->settings = $this->configurationManager->getConfiguration(\TYPO3\FLOW3\Configuration\ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'TYPO3.Form'); + $this->formSettings = $this->configurationManager->getConfiguration(\TYPO3\FLOW3\Configuration\ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'TYPO3.Form'); } /** @@ -120,10 +120,10 @@ abstract class AbstractFormFactory implements FormFactoryInterface { * @api */ protected function getPresetConfiguration($presetName) { - if (!isset($this->settings['Presets'][$presetName])) { + if (!isset($this->formSettings['Presets'][$presetName])) { throw new \TYPO3\Form\Exception\PresetNotFoundException(sprintf('The Preset "%s" was not found underneath TYPO3: Form: Presets.', $presetName), 1325685498); } - $preset = $this->settings['Presets'][$presetName]; + $preset = $this->formSettings['Presets'][$presetName]; if (isset($preset['parentPreset'])) { $parentPreset = $this->getPresetConfiguration($preset['parentPreset']); unset($preset['parentPreset']); diff --git a/Tests/Unit/Domain/Factory/AbstractFormFactoryTest.php b/Tests/Unit/Domain/Factory/AbstractFormFactoryTest.php index <HASH>..<HASH> 100644 --- a/Tests/Unit/Domain/Factory/AbstractFormFactoryTest.php +++ b/Tests/Unit/Domain/Factory/AbstractFormFactoryTest.php @@ -82,7 +82,7 @@ class AbstractFormFactoryTest extends \TYPO3\FLOW3\Tests\UnitTestCase { */ public function getPresetConfigurationReturnsCorrectConfigurationForPresets($presets, $presetName, $expected) { $abstractFormFactory = $this->getAbstractFormFactory(); - $abstractFormFactory->_set('settings', array( + $abstractFormFactory->_set('formSettings', array( 'Presets' => $presets )); @@ -113,7 +113,7 @@ class AbstractFormFactoryTest extends \TYPO3\FLOW3\Tests\UnitTestCase { $abstractFormFactory->_set('configurationManager', $mockConfigurationManager); $abstractFormFactory->_call('initializeObject'); - $this->assertSame('MyConfig', $abstractFormFactory->_get('settings')); + $this->assertSame('MyConfig', $abstractFormFactory->_get('formSettings')); } /**
[TASK] Rename FormFactory::settings to formSettings - in order to be able to inject Package settings to custom factories
neos_form
train
27346b64989c1cbed6cbba15c75bec456dd463e6
diff --git a/thinc/neural/_classes/difference.py b/thinc/neural/_classes/difference.py index <HASH>..<HASH> 100644 --- a/thinc/neural/_classes/difference.py +++ b/thinc/neural/_classes/difference.py @@ -46,11 +46,13 @@ def CauchySimilarity(ops, length): diff = vec1-vec2 square_diff = diff ** 2 total = (weights * square_diff).sum(axis=1) + total *= total > 0 sim, bp_sim = inverse(total) total = total.reshape((vec1.shape[0], 1)) def finish_update(d_sim, sgd=None): d_total = ops.asarray(bp_sim(d_sim), dtype='float32') d_total = d_total.reshape(total.shape) + d_total *= total > 0 d_weights = (d_total * square_diff).sum(axis=0) d_square_diff = weights * d_total d_diff = 2 * d_square_diff * diff
Apply a ReLu transform in the CauchyDifference, so we don't get negative sim
explosion_thinc
train
7bfd64907730bf410fe667f5ac63e3cc71ca594c
diff --git a/js/base/Exchange.js b/js/base/Exchange.js index <HASH>..<HASH> 100644 --- a/js/base/Exchange.js +++ b/js/base/Exchange.js @@ -169,13 +169,13 @@ module.exports = class Exchange { initRestRateLimiter () { - this.tokenBucket = { + this.tokenBucket = this.extend ({ refillRate: 1 / this.rateLimit, delay: 1, capacity: 1, defaultCost: 1, maxCapacity: 1000, - } + }, this.tokenBucket) this.throttle = throttle (this.tokenBucket) diff --git a/js/base/throttle.js b/js/base/throttle.js index <HASH>..<HASH> 100644 --- a/js/base/throttle.js +++ b/js/base/throttle.js @@ -5,7 +5,7 @@ const { sleep } = require ('./functions') const throttle = cfg => { let lastTimestamp = Date.now () - , numTokens = cfg.capacity + , numTokens = (typeof cfg.numTokens != 'undefined') ? cfg.numTokens : cfg.capacity , queue = [] , running = false , counter = 0 @@ -22,17 +22,18 @@ const throttle = cfg => { if (!running) { running = true while (queue.length > 0) { - let now = Date.now () - let elapsed = now - lastTimestamp - lastTimestamp = now - numTokens = Math.min (cfg.capacity, numTokens + elapsed * cfg.refillRate) - if (numTokens > 0) { + const hasEnoughTokens = cfg.capacity ? (numTokens > 0) : (numTokens >= 0) + if (hasEnoughTokens) { if (queue.length > 0) { let { cost, resolve, reject } = queue.shift () numTokens -= (cost || cfg.defaultCost) resolve () } } + let now = Date.now () + let elapsed = now - lastTimestamp + lastTimestamp = now + numTokens = Math.min (cfg.capacity, numTokens + elapsed * cfg.refillRate) await sleep (cfg.delay) } running = false diff --git a/js/test/test_base.js b/js/test/test_base.js index <HASH>..<HASH> 100644 --- a/js/test/test_base.js +++ b/js/test/test_base.js @@ -89,14 +89,18 @@ describe ('ccxt base code', () => { const calls = [] const rateLimit = 100 + const capacity = 0 + const numTokens = 0 + const defaultCost = 1 + const delay = 0 const exchange = new ccxt.Exchange ({ id: 'mock', rateLimit, enableRateLimit: true, + tokenBucket: { capacity, numTokens, defaultCost, delay }, async ping (...args) { return this.throttle ().then (() => exchange.pong (...args)) }, - async pong (...args) { calls.push ({ when: Date.now (), path: args[0], args }) } }) @@ -112,8 +116,9 @@ describe ('ccxt base code', () => { assert.deepEqual (calls.map (x => x.path), ['foo', 'bar', 'baz', 'qux', 'zap', 'lol']) + log (calls) calls.reduce ((prevTime, call) => { - // log ('delta T:', call.when - prevTime) + log ('delta T:', call.when - prevTime) assert ((call.when - prevTime) >= (rateLimit - 1)) return call.when }, 0)
minor edits to js rate limiter
ccxt_ccxt
train
5e6ed75baf7dce51e3d67e2ffbd3cc03522c3987
diff --git a/src/index.js b/src/index.js index <HASH>..<HASH> 100644 --- a/src/index.js +++ b/src/index.js @@ -1850,6 +1850,9 @@ mapmap.prototype.applyBehavior = function(spec, selection) { var map = this; this._promise.geometry.then(function(topo) { var sel = map.getRepresentations(selection); + // TODO: this should be configurable via options + // and needs to integrate with managing pointer events (see hoverInfo) + sel.style('pointer-events','visiblePainted'); if (typeof spec == 'function') { spec.call(map, sel); }
activate pointer event for selection of behavior
floledermann_mapmap.js
train
6b326ceae2cb3d6c5a22b63ccb681b103fc17c3f
diff --git a/Classes/Helper/InlineHelper.php b/Classes/Helper/InlineHelper.php index <HASH>..<HASH> 100644 --- a/Classes/Helper/InlineHelper.php +++ b/Classes/Helper/InlineHelper.php @@ -67,6 +67,10 @@ class InlineHelper } else { $uid = $data["uid"]; } + + if(!is_int($uid)) { + return; + } $fieldHelper = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('MASK\\Mask\\Helper\\FieldHelper'); $objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
Fixed missing $uid validation check You need to ensure that $uid is a valid integer. If it is not given (e.g. when rendering a FluidTemplate outside of a content element scope), the call in line <I> ```$fileRepository->findByRelation($table, $fieldKey, $uid);``` throws an exception.
Gernott_mask
train
70312901395093a23e408331d2850a33c3d35a3a
diff --git a/lifecycleScripts/install.js b/lifecycleScripts/install.js index <HASH>..<HASH> 100644 --- a/lifecycleScripts/install.js +++ b/lifecycleScripts/install.js @@ -108,12 +108,15 @@ function build() { target = "--target=" + nwVersion; } - builder = path.resolve(".", "node_modules", ".bin", builder); - builder = builder.replace(/\s/g, "\\$&"); - var cmd = [prefix, builder, "rebuild", target, debug, distUrl] - .join(" ").trim(); + return exec("npm install " + builder) + .then(function() { + builder = path.resolve(".", "node_modules", ".bin", builder); + builder = builder.replace(/\s/g, "\\$&"); + var cmd = [prefix, builder, "rebuild", target, debug, distUrl] + .join(" ").trim(); - return exec(cmd, opts) + return exec(cmd, opts); + }) .then(function() { console.info("[nodegit] Compilation complete."); console.info("[nodegit] Completed installation successfully.");
Confirm builder exists before building When not using Node <I>.x we would sometimes have a missing builder (i.e. pangyp or nw-gyp). We'll now do an `npm install` for whatever builder we're using to make sure it exists.
nodegit_nodegit
train
9567e769e91854e432ba625c733b8a769a00bc52
diff --git a/lib/active_record/connection_adapters/oracle_enhanced/column_dumper.rb b/lib/active_record/connection_adapters/oracle_enhanced/column_dumper.rb index <HASH>..<HASH> 100644 --- a/lib/active_record/connection_adapters/oracle_enhanced/column_dumper.rb +++ b/lib/active_record/connection_adapters/oracle_enhanced/column_dumper.rb @@ -23,13 +23,14 @@ module ActiveRecord #:nodoc: spec[:null] = 'false' if !column.null spec[:as] = column.virtual_column_data_default if column.virtual? spec[:default] = schema_default(column) if column.has_default? && !column.virtual? + spec[:comment] = column.comment.inspect unless column.comment.nil? spec.delete(:default) if spec[:default].nil? spec end def migration_keys # TODO `& column_specs.map(&:keys).flatten` should be exetuted here - [:name, :limit, :precision, :scale, :default, :null, :as, :virtual_type] + [:name, :limit, :precision, :scale, :default, :null, :as, :virtual_type, :comment] end end end diff --git a/lib/active_record/connection_adapters/oracle_enhanced/schema_dumper.rb b/lib/active_record/connection_adapters/oracle_enhanced/schema_dumper.rb index <HASH>..<HASH> 100644 --- a/lib/active_record/connection_adapters/oracle_enhanced/schema_dumper.rb +++ b/lib/active_record/connection_adapters/oracle_enhanced/schema_dumper.rb @@ -121,6 +121,11 @@ module ActiveRecord #:nodoc: # addition to make temporary option work tbl.print ", temporary: true" if @connection.temporary_table?(table) + table_comments = @connection.table_comment(table) + unless table_comments.nil? + tbl.print ", comment: #{table_comments.inspect}" + end + if columns.detect { |c| c.name == pk } if pk != 'id' tbl.print %Q(, primary_key: "#{pk}") diff --git a/spec/active_record/connection_adapters/oracle_enhanced_schema_dump_spec.rb b/spec/active_record/connection_adapters/oracle_enhanced_schema_dump_spec.rb index <HASH>..<HASH> 100644 --- a/spec/active_record/connection_adapters/oracle_enhanced_schema_dump_spec.rb +++ b/spec/active_record/connection_adapters/oracle_enhanced_schema_dump_spec.rb @@ -474,4 +474,44 @@ describe "OracleEnhancedAdapter schema dump" do expect(standard_dump).to match(/t\.float "hourly_rate"$/) end end + + describe "table comments" do + before(:each) do + schema_define do + create_table :test_table_comments, :comment => "this is a \"table comment\"!", force: true do |t| + t.string :blah + end + end + end + + after(:each) do + schema_define do + drop_table :test_table_comments + end + end + + it "should dump table comments" do + standard_dump.should =~ /comment: "this is a \\"table comment\\"!"/ + end + end + + describe "column comments" do + before(:each) do + schema_define do + create_table :test_column_comments, force: true do |t| + t.string :blah, :comment => "this is a \"column comment\"!" + end + end + end + + after(:each) do + schema_define do + drop_table :test_column_comments + end + end + + it "should dump column comments" do + standard_dump.should =~ /comment: "this is a \\"column comment\\"!"/ + end + end end
Add table and column comments to schema dump
rsim_oracle-enhanced
train
b1e7114910c4032ccbf7156aac16fce0277ed7b0
diff --git a/src/org/opencms/search/solr/CmsSolrDocument.java b/src/org/opencms/search/solr/CmsSolrDocument.java index <HASH>..<HASH> 100644 --- a/src/org/opencms/search/solr/CmsSolrDocument.java +++ b/src/org/opencms/search/solr/CmsSolrDocument.java @@ -49,6 +49,7 @@ import java.util.List; import org.apache.commons.logging.Log; import org.apache.solr.client.solrj.util.ClientUtils; import org.apache.solr.common.SolrDocument; +import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.SolrInputField; import org.apache.solr.schema.DateField; @@ -171,16 +172,28 @@ public class CmsSolrDocument implements I_CmsSearchDocument { for (String fieldName : fieldsToAdd) { IndexSchema schema = OpenCms.getSearchManager().getSolrServerConfiguration().getSolrSchema(); - FieldType type = schema.getFieldType(fieldName); - if (type instanceof DateField) { - value = DateField.formatExternal(new Date(new Long(value).longValue())); - } - - SolrInputField exfield = m_doc.getField(fieldName); - if (exfield == null) { - m_doc.addField(fieldName, value, field.getBoost()); - } else { - m_doc.setField(fieldName, value, field.getBoost()); + try { + FieldType type = schema.getFieldType(fieldName); + if (type instanceof DateField) { + value = DateField.formatExternal(new Date(new Long(value).longValue())); + } + + SolrInputField exfield = m_doc.getField(fieldName); + if (exfield == null) { + if (schema.hasExplicitField(fieldName)) { + m_doc.addField(fieldName, value); + } else { + m_doc.addField(fieldName, value, field.getBoost()); + } + } else { + if (schema.hasExplicitField(fieldName)) { + m_doc.setField(fieldName, value); + } else { + m_doc.setField(fieldName, value, field.getBoost()); + } + } + } catch (SolrException e) { + LOG.error(e.getMessage(), e); } } } @@ -322,6 +335,9 @@ public class CmsSolrDocument implements I_CmsSearchDocument { m_score = score; } + /** + * @see java.lang.Object#toString() + */ @Override public String toString() {
Improved adding field to document behavior.
alkacon_opencms-core
train
979be44d9538c49354321ec3e259f57eaa9cc628
diff --git a/protoc-gen-grpc-gateway/descriptor/registry.go b/protoc-gen-grpc-gateway/descriptor/registry.go index <HASH>..<HASH> 100644 --- a/protoc-gen-grpc-gateway/descriptor/registry.go +++ b/protoc-gen-grpc-gateway/descriptor/registry.go @@ -239,6 +239,9 @@ func (r *Registry) goPackagePath(f *descriptor.FileDescriptorProto) string { gopkg := f.Options.GetGoPackage() idx := strings.LastIndex(gopkg, "/") if idx >= 0 { + if sc := strings.LastIndex(gopkg, ";"); sc > 0 { + gopkg = gopkg[:sc+1-1] + } return gopkg } @@ -269,11 +272,19 @@ func (r *Registry) SetAllowDeleteBody(allow bool) { r.allowDeleteBody = allow } +// sanitizePackageName replaces unallowed character in package name +// with allowed character. +func sanitizePackageName(pkgName string) string { + pkgName = strings.Replace(pkgName, ".", "_", -1) + pkgName = strings.Replace(pkgName, "-", "_", -1) + return pkgName +} + // defaultGoPackageName returns the default go package name to be used for go files generated from "f". // You might need to use an unique alias for the package when you import it. Use ReserveGoPackageAlias to get a unique alias. func defaultGoPackageName(f *descriptor.FileDescriptorProto) string { name := packageIdentityName(f) - return strings.Replace(name, ".", "_", -1) + return sanitizePackageName(name) } // packageIdentityName returns the identity of packages. @@ -284,10 +295,18 @@ func packageIdentityName(f *descriptor.FileDescriptorProto) string { gopkg := f.Options.GetGoPackage() idx := strings.LastIndex(gopkg, "/") if idx < 0 { - return gopkg + gopkg = gopkg[idx+1:] } - return gopkg[idx+1:] + gopkg = gopkg[idx+1:] + // package name is overrided with the string after the + // ';' character + sc := strings.IndexByte(gopkg, ';') + if sc < 0 { + return sanitizePackageName(gopkg) + + } + return sanitizePackageName(gopkg[sc+1:]) } if f.Package == nil { diff --git a/protoc-gen-grpc-gateway/descriptor/registry_test.go b/protoc-gen-grpc-gateway/descriptor/registry_test.go index <HASH>..<HASH> 100644 --- a/protoc-gen-grpc-gateway/descriptor/registry_test.go +++ b/protoc-gen-grpc-gateway/descriptor/registry_test.go @@ -531,3 +531,21 @@ func TestLoadWithInconsistentTargetPackage(t *testing.T) { } } } + +func TestLoadOverridedPackageName(t *testing.T) { + reg := NewRegistry() + loadFile(t, reg, ` + name: 'example.proto' + package: 'example' + options < go_package: 'example.com/xyz;pb' > + `) + file := reg.files["example.proto"] + if file == nil { + t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") + return + } + wantPkg := GoPackage{Path: "example.com/xyz", Name: "pb"} + if got, want := file.GoPkg, wantPkg; got != want { + t.Errorf("file.GoPkg = %#v; want %#v", got, want) + } +}
fixes package name override doesn't work (#<I>) * adds a test case for package overriding * fixes package name override doesn't work * sanitizes package name
grpc-ecosystem_grpc-gateway
train
83c2049c043c4a35ea462e3225ce05da97c27d89
diff --git a/carto/sql.py b/carto/sql.py index <HASH>..<HASH> 100644 --- a/carto/sql.py +++ b/carto/sql.py @@ -13,6 +13,7 @@ Module for the SQL API import zlib import time +import warnings from .exceptions import CartoException from requests import HTTPError @@ -217,6 +218,8 @@ class BatchSQLClient(object): json_body={"query": sql_query}, http_header=header) + warnings.warn('Batch SQL job created with job_id: {job_id}'.format(job_id=data['job_id'])) + while data and data['status'] in BATCH_JOBS_PENDING_STATUSES: time.sleep(BATCH_READ_STATUS_AFTER_SECONDS) data = self.read(data['job_id'])
add userwarning with job_id
CartoDB_carto-python
train
191e8a7e9629f004ae3a2991b15e833b58070903
diff --git a/src/ResponseBuilder.php b/src/ResponseBuilder.php index <HASH>..<HASH> 100644 --- a/src/ResponseBuilder.php +++ b/src/ResponseBuilder.php @@ -49,7 +49,7 @@ class ResponseBuilder implements PostProcessorInterface $response = (new Response())->withProtocolVersion('1.1'); if ($output instanceof DownloadableResult && $output->getFilename()) { - $response = $response->withHeader('Content-Disposition', 'inline; filename=' . $output); + $response = $response->withHeader('Content-Disposition', 'inline; filename=' . $output->getFilename()); } if ($output instanceof TemplateResult) {
Fixed bug: missing call of getFilename
creios_creiwork-framework
train
f05394d89220872c9d5e9b0d1e76d8e9f22490c8
diff --git a/src/instrumentation/index.js b/src/instrumentation/index.js index <HASH>..<HASH> 100644 --- a/src/instrumentation/index.js +++ b/src/instrumentation/index.js @@ -1,30 +1,38 @@ var Transaction = require('./transaction') var request = require('../lib/transport') +var logger = require('../lib/logger') var Instrumentation = function () { this._queue = [] + this.scheduler = setInterval(this._dispatch.bind(this), 10000) } Instrumentation.prototype.add = function (transaction) { this._queue.push(transaction) - this._send() } Instrumentation.prototype.startTransaction = function (name, type) { return new Transaction(this, name, type) } -Instrumentation.prototype._send = function () { - var formattedTransactions = this._formatTransactions() - - request.sendTransaction(formattedTransactions) - .then(this._flush.bind(this)) -} - Instrumentation.prototype._flush = function () { this._queue = [] } +Instrumentation.prototype._dispatch = function() { + + logger.log('Instrumentation.scheduler._dispatch', this._queue.length) + + if(!this._queue.length) { + return + } + + var transactions = this._formatTransactions() + var flush = this._flush.bind(this) + + request.sendTransaction(transactions).then(flush) +} + Instrumentation.prototype._formatTransactions = function () { var transactions = groupTransactions(this._queue) @@ -82,17 +90,17 @@ function getRawGroupedTracesTimings (traces, groupedTraces) { }) return Object.keys(groupedByTransaction).map(function (key) { - var traces = groupedByTransaction[key] - var transaction = traces[0].transaction + var traces = groupedByTransaction[key] + var transaction = traces[0].transaction - var data = [transaction.duration()] + var data = [transaction.duration()] - traces.forEach(function(trace) { - var groupIndex = getTraceGroupIndex(groupedTraces, trace) - data.push([groupIndex, trace._start - transaction._start, trace.duration()]) - }) + traces.forEach(function(trace) { + var groupIndex = getTraceGroupIndex(groupedTraces, trace) + data.push([groupIndex, trace._start - transaction._start, trace.duration()]) + }) - return data; + return data; }); }
Add scheduler to dispatch finished transactions every <I> sec
opbeat_opbeat-js-core
train
58af416c59c68742e7dc4ab6a03efe0f81c3814b
diff --git a/core-bundle/contao/widgets/ImageSize.php b/core-bundle/contao/widgets/ImageSize.php index <HASH>..<HASH> 100644 --- a/core-bundle/contao/widgets/ImageSize.php +++ b/core-bundle/contao/widgets/ImageSize.php @@ -144,10 +144,9 @@ class ImageSize extends \Widget } } - $arrFields[] = sprintf('<select name="%s[]" id="ctrl_%s" class="tl_select_interval"%s onfocus="Backend.getScrollOffset()">%s</select>', + $arrFields[] = sprintf('<select name="%s[]" id="ctrl_%s" class="tl_select_interval" onfocus="Backend.getScrollOffset()">%s</select>', $this->strName, $this->strId.'_3', - $this->getAttributes(), implode(' ', $arrOptions)); return sprintf('<div id="ctrl_%s"%s>%s</div>%s', diff --git a/core-bundle/contao/widgets/InputUnit.php b/core-bundle/contao/widgets/InputUnit.php index <HASH>..<HASH> 100644 --- a/core-bundle/contao/widgets/InputUnit.php +++ b/core-bundle/contao/widgets/InputUnit.php @@ -130,14 +130,13 @@ class InputUnit extends \Widget $this->varValue = array('value'=>$this->varValue); } - return sprintf('<input type="text" name="%s[value]" id="ctrl_%s" class="tl_text_unit%s" value="%s"%s onfocus="Backend.getScrollOffset()"> <select name="%s[unit]" class="tl_select_unit"%s onfocus="Backend.getScrollOffset()">%s</select>%s', + return sprintf('<input type="text" name="%s[value]" id="ctrl_%s" class="tl_text_unit%s" value="%s"%s onfocus="Backend.getScrollOffset()"> <select name="%s[unit]" class="tl_select_unit" onfocus="Backend.getScrollOffset()">%s</select>%s', $this->strName, $this->strId, (strlen($this->strClass) ? ' ' . $this->strClass : ''), specialchars($this->varValue['value']), $this->getAttributes(), $this->strName, - $this->getAttributes(), implode('', $arrUnits), $this->wizard); } diff --git a/core-bundle/contao/widgets/TimePeriod.php b/core-bundle/contao/widgets/TimePeriod.php index <HASH>..<HASH> 100644 --- a/core-bundle/contao/widgets/TimePeriod.php +++ b/core-bundle/contao/widgets/TimePeriod.php @@ -126,14 +126,13 @@ class TimePeriod extends \Widget $this->varValue = array('value'=>$this->varValue); } - return sprintf('<input type="text" name="%s[value]" id="ctrl_%s" class="tl_text_interval%s" value="%s"%s onfocus="Backend.getScrollOffset()"> <select name="%s[unit]" class="tl_select_interval"%s onfocus="Backend.getScrollOffset()">%s</select>%s', + return sprintf('<input type="text" name="%s[value]" id="ctrl_%s" class="tl_text_interval%s" value="%s"%s onfocus="Backend.getScrollOffset()"> <select name="%s[unit]" class="tl_select_interval" onfocus="Backend.getScrollOffset()">%s</select>%s', $this->strName, $this->strId, (($this->strClass != '') ? ' ' . $this->strClass : ''), specialchars($this->varValue['value']), $this->getAttributes(), $this->strName, - $this->getAttributes(), implode('', $arrUnits), $this->wizard); } diff --git a/core-bundle/contao/widgets/TrblField.php b/core-bundle/contao/widgets/TrblField.php index <HASH>..<HASH> 100644 --- a/core-bundle/contao/widgets/TrblField.php +++ b/core-bundle/contao/widgets/TrblField.php @@ -129,10 +129,9 @@ class TrblField extends \Widget $this->getAttributes()); } - return sprintf('%s <select name="%s[unit]" class="tl_select_unit"%s onfocus="Backend.getScrollOffset()">%s</select>%s', + return sprintf('%s <select name="%s[unit]" class="tl_select_unit" onfocus="Backend.getScrollOffset()">%s</select>%s', implode(' ', $arrFields), $this->strName, - $this->getAttributes(), implode('', $arrUnits), $this->wizard); }
[Core] Only apply the widget attributes to the input field(s) but not the select fields (see #<I>)
contao_contao
train
246e2b2bbeecc3ee0fac99b5e14e47272c1c3685
diff --git a/src/Container.php b/src/Container.php index <HASH>..<HASH> 100644 --- a/src/Container.php +++ b/src/Container.php @@ -21,21 +21,21 @@ class Container * * @var array */ - protected $_routes = []; + protected $routes = []; /** * Current Route * * @var \SlaxWeb\Router\Route */ - protected $_currentRoute = null; + protected $currentRoute = null; /** * Logger * * @var \Psr\Log\LoggerInterface */ - protected $_logger = null; + protected $logger = null; /** * Class constructor @@ -47,9 +47,9 @@ class Container */ public function __construct(\Psr\Log\LoggerInterface $logger) { - $this->_logger = $logger; + $this->logger = $logger; - $this->_logger->info("Route Container initialized"); + $this->logger->info("Route Container initialized"); } /** @@ -66,16 +66,16 @@ class Container if ($route->uri === "" || $route->method === "" || $route->action === null) { - $this->_logger->error("Route incomplete. Unable to add"); - $this->_logger->debug("Incomplete Route", [$route]); + $this->logger->error("Route incomplete. Unable to add"); + $this->logger->debug("Incomplete Route", [$route]); throw new Exception\RouteIncompleteException( "Retrieved Route is not complete and can not be stored" ); } - $this->_routes[] = $route; + $this->routes[] = $route; - $this->_logger->info( + $this->logger->info( "Route successfully added to Container", ["uri" => $route->uri] ); @@ -92,7 +92,7 @@ class Container */ public function getAll(): array { - return $this->_routes; + return $this->routes; } /** @@ -106,10 +106,10 @@ class Container public function next() { $func = "next"; - if ($this->_currentRoute === null) { + if ($this->currentRoute === null) { $func = "current"; } - return $this->_iterateRoutes($func); + return $this->iterateRoutes($func); } /** @@ -123,10 +123,10 @@ class Container public function prev() { $func = "prev"; - if ($this->_currentRoute === null) { + if ($this->currentRoute === null) { $func = "end"; } - return $this->_iterateRoutes($func); + return $this->iterateRoutes($func); } /** @@ -139,11 +139,11 @@ class Container * @param string $function Function name for array iteration * @return \SlaxWeb\Router\Route|bool */ - protected function _iterateRoutes(string $function) + protected function iterateRoutes(string $function) { - if (($route = $function($this->_routes)) !== false) { - $this->_currentRoute = $route; - return $this->_currentRoute; + if (($route = $function($this->routes)) !== false) { + $this->currentRoute = $route; + return $this->currentRoute; } return false; }
remove leadinng undescores for protected members in container
SlaxWeb_Router
train
c282a3ecb32b6c7505016e10ba621bbbe1d7a968
diff --git a/lib/static_config/reader/environment.rb b/lib/static_config/reader/environment.rb index <HASH>..<HASH> 100644 --- a/lib/static_config/reader/environment.rb +++ b/lib/static_config/reader/environment.rb @@ -37,7 +37,7 @@ module StaticConfig case env_value when /^\d+$/ env_value.to_i - when /^(\d*\.\d+)|(\d+\.\d*)$/ + when /^(\d*\.\d+|\d+\.\d*)$/ env_value.to_f when 'true' true diff --git a/spec/static_config/reader/environment_spec.rb b/spec/static_config/reader/environment_spec.rb index <HASH>..<HASH> 100644 --- a/spec/static_config/reader/environment_spec.rb +++ b/spec/static_config/reader/environment_spec.rb @@ -39,12 +39,14 @@ describe StaticConfig::Reader::Environment do 'MY_CONFIG_FALSE' => 'false', 'MY_CONFIG_FLOAT' => '123.45', 'MY_CONFIG_STRING' => 'string', + 'MY_CONFIG_IP' => '10.10.10.10', }) it { subject['int'].should == 123 } it { subject['true'].should == true } it { subject['false'].should == false } it { subject['float'].should == 123.45 } it { subject['string'].should == 'string' } + it { subject['ip'].should == '10.10.10.10' } end end
Support IP addresses in env vars.
spraints_static_config
train
bf744da0e723391ee4d725b75a611090098e92c6
diff --git a/utils.js b/utils.js index <HASH>..<HASH> 100644 --- a/utils.js +++ b/utils.js @@ -25,7 +25,11 @@ utils.mergeTypedArraysUnsafe = function(a, b) { // Take care of inability to con utils.objectfrom = function(data, hints={}) { // Generic way to turn something into a object (typically expecting a string, or a buffer) - return (typeof data === "string" || data instanceof Buffer) ? JSON.parse(data) : data; + // This can get weird, there appear to be two DIFFERENT Uint8Arrays, one has a constructor "TypedArray" the other "Uint8Array" + // "TypedArray" doesnt appear to be defined so can't test if its an instance of that, but in tests the TypedArray ones are + // not instances of Buffer and need converting first + if ((data instanceof Uint8Array) && !(data instanceof Buffer)) return utils.objectfrom(new Buffer(data)); + return (typeof data === "string" || data instanceof Buffer || data instanceof Uint8Array) ? JSON.parse(data) : data; } utils.keyFilter = function(dic, keys) {
Bug with strange double Uint8Array type
internetarchive_dweb-objects
train
436752972dcc26714f0768ef6dfc562283f9cdc2
diff --git a/packages/ember-metal/lib/platform.js b/packages/ember-metal/lib/platform.js index <HASH>..<HASH> 100644 --- a/packages/ember-metal/lib/platform.js +++ b/packages/ember-metal/lib/platform.js @@ -140,7 +140,6 @@ if (!(Object.create && !Object.create(null).hasOwnProperty)) { delete empty.toLocaleString; delete empty.toString; delete empty.valueOf; - empty.__proto__ = null; function Empty() {} Empty.prototype = empty;
remove __proto__ set as it pollutes enumeration..
emberjs_ember.js
train
32587cc27436cd46b05aca97259ddd4dfd8b3b58
diff --git a/tests/function/test_load_act_block.py b/tests/function/test_load_act_block.py index <HASH>..<HASH> 100644 --- a/tests/function/test_load_act_block.py +++ b/tests/function/test_load_act_block.py @@ -91,7 +91,7 @@ def test_raises_in_cm(function): assert isinstance(result, ActBlock) assert result.block_type == ActBlockType.pytest_raises - assert result.node.first_token.line == ' existing_user.create()\n' + assert result.node.first_token.line == ' with pytest.raises(ValidationError):\n' @pytest.mark.parametrize( @@ -110,8 +110,8 @@ def test_marked_in_cm(function): result = function.load_act_block() assert isinstance(result, ActBlock) - assert result.block_type == ActBlockType.pytest_raises - assert result.node.first_token.line == ' stub_user.create() # act' + assert result.block_type == ActBlockType.marked_act + assert result.node.first_token.line == ' stub_user.create() # act\n' # --- FAILURES ---
Fix tests of nested act block loading
jamescooke_flake8-aaa
train
a45293ef12ab61c996ef12f28e2017cbbc6de7f6
diff --git a/readme.md b/readme.md index <HASH>..<HASH> 100644 --- a/readme.md +++ b/readme.md @@ -13,7 +13,7 @@ $ yarn add @tneu/news ```js const {parsePage} = require('@tneu/news'); -const page = await parsePage(1); // returns {pageNumber, totalPages, items} +const page = await parsePage(1); // returns {items, pageNumber, totalPages, hasPrevious, hasNext} ``` And the object in `items` array looks like: diff --git a/src/newsfeed.js b/src/newsfeed.js index <HASH>..<HASH> 100644 --- a/src/newsfeed.js +++ b/src/newsfeed.js @@ -22,6 +22,8 @@ module.exports.parsePage = async function parsePage(pageNumber) { return { pageNumber, totalPages, + hasPrevious: pageNumber !== 1, + hasNext: pageNumber < totalPages, items: itemsWithArticleContentSorted }; }; diff --git a/src/newsfeed.test.js b/src/newsfeed.test.js index <HASH>..<HASH> 100644 --- a/src/newsfeed.test.js +++ b/src/newsfeed.test.js @@ -59,6 +59,16 @@ it('should return pageNumber of parsed page', async () => { expect(news.pageNumber).toEqual(1); }); +it('should return hasPrevious boolean', async () => { + const news = await parsePage(1); + expect(news.hasPrevious).toEqual(false); +}); + +it('should return hasNext boolean', async () => { + const news = await parsePage(1); + expect(news.hasNext).toEqual(true); +}); + it('should return number of total pages', async () => { const news = await parsePage(1); expect(news.totalPages).toEqual(508);
feat: return hasPrevious and hasNext properties from newsfeed
tneudevteam_tneu-news
train
160a17140df17aa5ce7a8602d776762c928fdf7b
diff --git a/napoleon/CHANGES b/napoleon/CHANGES index <HASH>..<HASH> 100644 --- a/napoleon/CHANGES +++ b/napoleon/CHANGES @@ -2,6 +2,12 @@ This file describes user-visible changes between the extension versions. +Version 0.2.1 (2013-07-26) +-------------------------- + +* Corrects package url in setup.py + + Version 0.2 (2013-07-26) ------------------------ diff --git a/napoleon/docs/source/conf.py b/napoleon/docs/source/conf.py index <HASH>..<HASH> 100644 --- a/napoleon/docs/source/conf.py +++ b/napoleon/docs/source/conf.py @@ -115,9 +115,9 @@ copyright = u'2013, Rob Ruana' # built documents. # # The short X.Y version. -version = '0.2' +version = '0.2.1' # The full version, including alpha/beta/rc tags. -release = '0.2' +release = '0.2.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/napoleon/setup.py b/napoleon/setup.py index <HASH>..<HASH> 100644 --- a/napoleon/setup.py +++ b/napoleon/setup.py @@ -12,7 +12,7 @@ reqs_test = open('requirements_test.txt', 'r').read().strip().splitlines() setup( name='sphinxcontrib-napoleon', - version='0.2', + version='0.2.1', url='https://bitbucket.org/birkenfeld/sphinx-contrib', download_url='http://pypi.python.org/pypi/sphinxcontrib-napoleon', license='BSD',
Bumps version number to <I>
sphinx-contrib_paverutils
train
bf9bfd61067f0bdab11624c41c8e7624dfdfb684
diff --git a/database.go b/database.go index <HASH>..<HASH> 100644 --- a/database.go +++ b/database.go @@ -216,19 +216,32 @@ func (m *Measurement) seriesByTags(tags map[string]string) *Series { } // mapValues converts a map of values with string keys to field id keys. -// Returns nil if any field doesn't exist. -func (m *Measurement) mapValues(values map[string]interface{}) map[uint8]interface{} { +// +// If a field exists, but its type is different, return an error. If error is +// nil, but at least 1 field has not been mapped, nil is returned as the map. +func (m *Measurement) mapValues(values map[string]interface{}) (map[uint8]interface{}, error) { + unmapped := false other := make(map[uint8]interface{}, len(values)) for k, v := range values { - // TODO: Cast value to original field type. - f := m.FieldByName(k) + if f == nil { - return nil + unmapped = true + } else { + if influxql.InspectDataType(v) != f.Type { + return nil, fmt.Errorf("field %s is not of type %s", k, f.Type) + } + other[f.ID] = v } - other[f.ID] = v } - return other + + // At least 1 field isn't mapped, so return nil. + if unmapped { + return nil, nil + } + + // All fields exist, and are of the expected type. + return other, nil } func (m *Measurement) seriesIDsAndFilters(stmt *influxql.SelectStatement) (seriesIDs, map[uint32]influxql.Expr) { diff --git a/influxql/ast.go b/influxql/ast.go index <HASH>..<HASH> 100644 --- a/influxql/ast.go +++ b/influxql/ast.go @@ -32,6 +32,8 @@ func InspectDataType(v interface{}) DataType { switch v.(type) { case float64: return Number + case int: + return Number case bool: return Boolean case string: diff --git a/server.go b/server.go index <HASH>..<HASH> 100644 --- a/server.go +++ b/server.go @@ -1605,8 +1605,12 @@ func (s *Server) writePoint(database, retentionPolicy string, point *Point) (uin sh := g.ShardBySeriesID(seriesID) // Convert string-key/values to fieldID-key/values. + rawValues, err := m.mapValues(values) + if err != nil { + return 0, err + } + // If not all fields can be converted then send as a non-raw write series. - rawValues := m.mapValues(values) if rawValues == nil { // Encode the command. data := mustMarshalJSON(&writeSeriesCommand{
Error if field's type has changed
influxdata_influxdb
train
c25963484c9e6b4a6a387cb82733fd1ff0ab2db5
diff --git a/pymc3/tests/test_parallel_sampling.py b/pymc3/tests/test_parallel_sampling.py index <HASH>..<HASH> 100644 --- a/pymc3/tests/test_parallel_sampling.py +++ b/pymc3/tests/test_parallel_sampling.py @@ -25,6 +25,8 @@ from aesara.tensor.type import TensorType import pymc3 as pm import pymc3.parallel_sampling as ps +from pymc3.aesaraf import floatX + def test_context(): with pm.Model(): @@ -83,15 +85,13 @@ def test_remote_pipe_closed(): pm.sample(step=step, mp_ctx="spawn", tune=2, draws=2, cores=2, chains=2) [email protected]( - reason="Possibly the same issue described in https://github.com/pymc-devs/pymc3/pull/4701" -) [email protected](reason="Unclear") def test_abort(): with pm.Model() as model: a = pm.Normal("a", shape=1) - pm.HalfNormal("b") - step1 = pm.NUTS([a]) - step2 = pm.Metropolis([model["b_log__"]]) + b = pm.HalfNormal("b") + step1 = pm.NUTS([model.rvs_to_values[a]]) + step2 = pm.Metropolis([model.rvs_to_values[b]]) step = pm.CompoundStep([step1, step2]) @@ -104,7 +104,7 @@ def test_abort(): chain=3, seed=1, mp_ctx=ctx, - start={"a": np.array([1.0]), "b_log__": np.array(2.0)}, + start={"a": floatX(np.array([1.0])), "b_log__": floatX(np.array(2.0))}, step_method_pickled=None, ) proc.start() @@ -118,15 +118,12 @@ def test_abort(): proc.join() [email protected]( - reason="Possibly the same issue described in https://github.com/pymc-devs/pymc3/pull/4701" -) def test_explicit_sample(): with pm.Model() as model: a = pm.Normal("a", shape=1) - pm.HalfNormal("b") - step1 = pm.NUTS([a]) - step2 = pm.Metropolis([model["b_log__"]]) + b = pm.HalfNormal("b") + step1 = pm.NUTS([model.rvs_to_values[a]]) + step2 = pm.Metropolis([model.rvs_to_values[b]]) step = pm.CompoundStep([step1, step2]) @@ -138,7 +135,7 @@ def test_explicit_sample(): chain=3, seed=1, mp_ctx=ctx, - start={"a": np.array([1.0]), "b_log__": np.array(2.0)}, + start={"a": floatX(np.array([1.0])), "b_log__": floatX(np.array(2.0))}, step_method_pickled=None, ) proc.start() @@ -153,19 +150,16 @@ def test_explicit_sample(): proc.join() [email protected]( - reason="Possibly the same issue described in https://github.com/pymc-devs/pymc3/pull/4701" -) def test_iterator(): with pm.Model() as model: a = pm.Normal("a", shape=1) - pm.HalfNormal("b") - step1 = pm.NUTS([a]) - step2 = pm.Metropolis([model["b_log__"]]) + b = pm.HalfNormal("b") + step1 = pm.NUTS([model.rvs_to_values[a]]) + step2 = pm.Metropolis([model.rvs_to_values[b]]) step = pm.CompoundStep([step1, step2]) - start = {"a": np.array([1.0]), "b_log__": np.array(2.0)} + start = {"a": floatX(np.array([1.0])), "b_log__": floatX(np.array(2.0))} sampler = ps.ParallelSampler(10, 10, 3, 2, [2, 3, 4], [start] * 3, step, 0, False) with sampler: for draw in sampler:
Fix failing tests in `test_parallel_sampling`
pymc-devs_pymc
train
4441092ededc262918712db6584ffe45de8bced2
diff --git a/lib/t/cli.rb b/lib/t/cli.rb index <HASH>..<HASH> 100644 --- a/lib/t/cli.rb +++ b/lib/t/cli.rb @@ -168,7 +168,7 @@ module T end desc "reply SCREEN_NAME MESSAGE", "Post your Tweet as a reply directed at another person." - method_option :location, :aliases => "-l", :type => :boolean, :default => true + method_option :location, :aliases => "-l", :type => :boolean, :default => false def reply(screen_name, message) screen_name = screen_name.strip_at defaults = {:include_entities => false, :trim_user => true} @@ -228,7 +228,7 @@ module T end desc "status MESSAGE", "Post a Tweet." - method_option :location, :aliases => "-l", :type => :boolean, :default => true + method_option :location, :aliases => "-l", :type => :boolean, :default => false def status(message) defaults = {:include_entities => false, :trim_user => true} defaults.merge!(:lat => location.lat, :long => location.lng) if options['location']
Set location off by default Fixes #5.
sferik_t
train
406988cf8de3d2bd875d1d31488ba591cb481dc4
diff --git a/lib/sprout/executable/boolean.rb b/lib/sprout/executable/boolean.rb index <HASH>..<HASH> 100644 --- a/lib/sprout/executable/boolean.rb +++ b/lib/sprout/executable/boolean.rb @@ -59,7 +59,8 @@ module Sprout end def default_option_parser_declaration - [prefix, '[no-]', option_parser_name] + return [prefix, '[no-]', option_parser_name] if default == true + super end ## diff --git a/test/unit/boolean_param_test.rb b/test/unit/boolean_param_test.rb index <HASH>..<HASH> 100644 --- a/test/unit/boolean_param_test.rb +++ b/test/unit/boolean_param_test.rb @@ -32,6 +32,11 @@ class BooleanParamTest < Test::Unit::TestCase @param.hidden_value = false assert_equal "--[no-]foo [BOOL]", @param.option_parser_declaration end + + should "not insert [no] param modifier unless default true" do + @param.name = 'something_off' + assert_equal "--something-off", @param.option_parser_declaration + end end end end
Updated option parser boolean parameters so that [no] option is only added to params with default value == true
lukebayes_project-sprouts
train
4ac888a051642d3d013eb8bb962a854eebeff285
diff --git a/core/lib/refinery/application_controller.rb b/core/lib/refinery/application_controller.rb index <HASH>..<HASH> 100644 --- a/core/lib/refinery/application_controller.rb +++ b/core/lib/refinery/application_controller.rb @@ -48,7 +48,7 @@ module Refinery end def home_page? - refinery.root_path =~ /^#{Regexp.escape(request.path.sub("//", "/"))}\/?/ + refinery.root_path =~ %r{^#{Regexp.escape(request.path.sub("//", "/"))}} end def just_installed? diff --git a/core/spec/lib/refinery/application_controller_spec.rb b/core/spec/lib/refinery/application_controller_spec.rb index <HASH>..<HASH> 100644 --- a/core/spec/lib/refinery/application_controller_spec.rb +++ b/core/spec/lib/refinery/application_controller_spec.rb @@ -1,7 +1,7 @@ require "spec_helper" -describe "Refinery::ApplicationController" do - describe "DummyController", :type => :controller do +module Refinery + describe ApplicationController, :type => :controller do controller do include ::Refinery::ApplicationController @@ -23,10 +23,21 @@ describe "Refinery::ApplicationController" do controller.home_page?.should be_true end + it "matches localised root url with trailing slash" do + controller.refinery.stub(:root_path).and_return("/en/") + request.stub(:path).and_return("/en/") + controller.home_page?.should be_true + end + it "escapes regexp" do request.stub(:path).and_return("\/huh)") expect { controller.home_page? }.to_not raise_error(RegexpError) end + + it "returns false for non root url" do + request.stub(:path).and_return("/foo/") + controller.should_not be_home_page + end end describe "force_ssl" do
Reformat regexp that broke vim's syntax highlighting.
refinery_refinerycms
train
896911721edb2982d32f974aec7383a71a436efc
diff --git a/src/environ/secrets.py b/src/environ/secrets.py index <HASH>..<HASH> 100644 --- a/src/environ/secrets.py +++ b/src/environ/secrets.py @@ -33,6 +33,17 @@ from .exceptions import MissingSecretError log = logging.getLogger(__name__) +def _get_default_secret(var, default): + """ + Get default or raise MissingSecretError. + """ + if isinstance(default, attr.Factory): + return attr.NOTHING + elif isinstance(default, Raise): + raise MissingSecretError(var) + return default + + @attr.s class INISecrets(object): """ @@ -113,13 +124,10 @@ class INISecrets(object): var = "_".join((prefix[1:] + (name,))) try: log.debug("looking for '%s' in section '%s'." % (var, section)) - return _SecretStr(self._cfg.get(section, var)) + val = self._cfg.get(section, var) + return _SecretStr(val) except NoOptionError: - if isinstance(ce.default, attr.Factory): - return attr.NOTHING - elif not isinstance(ce.default, Raise): - return ce.default - raise MissingSecretError(var) + return _get_default_secret(var, ce.default) @attr.s @@ -157,17 +165,11 @@ class VaultEnvSecrets(object): var = "_".join(((vp,) + prefix[1:] + (name,))).upper() log.debug("looking for env var '%s'." % (var,)) - val = environ.get( - var, - ( - attr.NOTHING - if isinstance(ce.default, attr.Factory) - else ce.default - ), - ) - if isinstance(val, Raise): - raise MissingSecretError(var) - return _SecretStr(val) + try: + val = environ[var] + return _SecretStr(val) + except KeyError: + return _get_default_secret(var, ce.default) class _SecretStr(str):
Move default value logic to a separate function Getting the default value if the variable is not specified is implemented multiple times, so we can refactor it to a common function, which future secret reader classes can use.
hynek_environ_config
train
d00e7e85480941188cb8048104a305f62271731a
diff --git a/lib/geocoder.rb b/lib/geocoder.rb index <HASH>..<HASH> 100644 --- a/lib/geocoder.rb +++ b/lib/geocoder.rb @@ -94,18 +94,19 @@ module Geocoder # generate hash lat_attr = geocoder_options[:latitude] lon_attr = geocoder_options[:longitude] + distance = "3956 * 2 * ASIN(SQRT(" + + "POWER(SIN((#{latitude} - #{lat_attr}) * " + + "PI() / 180 / 2), 2) + COS(#{latitude} * PI()/180) * " + + "COS(#{lat_attr} * PI() / 180) * " + + "POWER(SIN((#{longitude} - #{lon_attr}) * " + + "PI() / 180 / 2), 2) ))" { - :select => "*, 3956 * 2 * ASIN(SQRT(" + - "POWER(SIN((#{latitude} - #{lat_attr}) * " + - "PI() / 180 / 2), 2) + COS(#{latitude} * PI()/180) * " + - "COS(#{lat_attr} * PI() / 180) * " + - "POWER(SIN((#{longitude} - #{lon_attr}) * " + - "PI() / 180 / 2), 2) )) as distance", + :select => "*, #{distance} AS distance", :conditions => [ "#{lat_attr} BETWEEN ? AND ? AND " + "#{lon_attr} BETWEEN ? AND ?", lat_lo, lat_hi, lon_lo, lon_hi], - :having => "distance <= #{radius}", + :having => "#{distance} <= #{radius}", :order => options[:order], :limit => limit }
Fix PostgreSQL bug reported by developish. Avoid using column aliases in the HAVING clause (not allowed by PostgreSQL).
alexreisner_geocoder
train
b20f4e7ac32a110b11579d5047f5e48f99b0d0d0
diff --git a/src/__tests__/reducer.spec.js b/src/__tests__/reducer.spec.js index <HASH>..<HASH> 100644 --- a/src/__tests__/reducer.spec.js +++ b/src/__tests__/reducer.spec.js @@ -1,5 +1,5 @@ import expect from 'expect'; -import reducer from '../reducer'; +import reducer, {getValues} from '../reducer'; import bindActionData from '../bindActionData'; import {blur, change, focus, initialize, reset, startAsyncValidation, startSubmit, stopAsyncValidation, stopSubmit, touch, untouch, destroy} from '../actions'; @@ -977,3 +977,26 @@ describe('reducer.normalize', () => { }); }); }); + +describe('reducer.getValues', () => { + it('should extract field values from state', () => { + const state = { + _active: undefined, + _asyncValidating: false, + _error: undefined, + _submitting: false, + _submitFailed: false, + myField: { + value: 'myValue' + }, + myOtherField: { + value: 'myOtherValue' + } + }; + + expect(getValues(state)).toEqual({ + myField: 'myValue', + myOtherField: 'myOtherValue' + }); + }); +}); diff --git a/src/reducer.js b/src/reducer.js index <HASH>..<HASH> 100644 --- a/src/reducer.js +++ b/src/reducer.js @@ -10,7 +10,7 @@ export const initialState = { _submitFailed: false }; -const getValues = (state) => { +export const getValues = (state) => { return Object.keys(state).reduce((accumulator, name) => { if (name[0] !== '_') { accumulator[name] = state[name].value;
Add test for reducer getValues
erikras_redux-form
train
3a76d9f71ffb23d12a67434638ae2569838fc2ef
diff --git a/spec/lock_jar/config_spec.rb b/spec/lock_jar/config_spec.rb index <HASH>..<HASH> 100644 --- a/spec/lock_jar/config_spec.rb +++ b/spec/lock_jar/config_spec.rb @@ -29,7 +29,6 @@ describe LockJar::Config do end context 'using home dir config' do - before do allow(Dir).to receive(:home).and_return(TEMP_DIR) end
rubocop is the law :oncoming_police_car:
mguymon_lock_jar
train
00bc47243e2769bd2b4638577c1be0d818de80a5
diff --git a/examples/quickhowto2/config.py b/examples/quickhowto2/config.py index <HASH>..<HASH> 100644 --- a/examples/quickhowto2/config.py +++ b/examples/quickhowto2/config.py @@ -37,8 +37,12 @@ LANGUAGES = { UPLOAD_FOLDER = basedir + '/app/static/uploads/' IMG_UPLOAD_FOLDER = basedir + '/app/static/uploads/' IMG_UPLOAD_URL = '/static/uploads/' -AUTH_TYPE = AUTH_DB -#AUTH_LDAP_SERVER = "ldap://dc.domain.net" +AUTH_TYPE = AUTH_LDAP +AUTH_LDAP_SERVER = "ldap://10.1.0.100" + +AUTH_USER_REGISTRATION = True +AUTH_USER_REGISTRATION_ROLE = 'User' +AUTH_LDAP_BIND_FIRST = True AUTH_ROLE_ADMIN = 'Admin' AUTH_ROLE_PUBLIC = 'Public' diff --git a/flask_appbuilder/base.py b/flask_appbuilder/base.py index <HASH>..<HASH> 100644 --- a/flask_appbuilder/base.py +++ b/flask_appbuilder/base.py @@ -107,8 +107,14 @@ class AppBuilder(object): if app is not None: self.init_app(app, session) - def init_app(self, app, session): + """ + Will initialize the Flask app, supporting the app factory pattern. + + :param app: + :param session: The SQLAlchemy session + + """ app.config.setdefault('APP_NAME', 'F.A.B.') app.config.setdefault('APP_THEME', '') app.config.setdefault('APP_ICON', '') @@ -118,8 +124,6 @@ class AppBuilder(object): from flask_appbuilder.security.sqla.manager import SecurityManager self.security_manager_class = SecurityManager self.session = session - if not self.security_manager_class: - self.security_manager_class = dynamic_class_import(app.config.get("SECURITY_CLASS")) self.sm = self.security_manager_class(self) self.bm = BabelManager(self) self._add_global_static() diff --git a/flask_appbuilder/security/manager.py b/flask_appbuilder/security/manager.py index <HASH>..<HASH> 100644 --- a/flask_appbuilder/security/manager.py +++ b/flask_appbuilder/security/manager.py @@ -359,16 +359,15 @@ class BaseSecurityManager(AbstractSecurityManager): import ldap except: raise Exception("No ldap library for python.") + return None try: if self.auth_ldap_allow_self_signed: ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) - con = ldap.initialize(self.auth_ldap_server) con.set_option(ldap.OPT_REFERRALS, 0) try: if self.auth_ldap_bind_first: con.bind_s(username, password) - if not self.auth_ldap_search: bind_username = username else: @@ -380,12 +379,11 @@ class BaseSecurityManager(AbstractSecurityManager): self.auth_ldap_lastname_field, self.auth_ldap_email_field ]) - if bind_username_array == []: + if not bind_username_array: return None else: bind_username = bind_username_array[0][0] ldap_user_info = bind_username_array[0][1] - if not self.auth_ldap_bind_first: con.bind_s(bind_username, password)
ldap rework
dpgaspar_Flask-AppBuilder
train
eb64dd3ad25b06da01f33fbc6ebc936f11109c2a
diff --git a/src/test/java/com/j256/ormlite/stmt/QueryBuilderTest.java b/src/test/java/com/j256/ormlite/stmt/QueryBuilderTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/com/j256/ormlite/stmt/QueryBuilderTest.java +++ b/src/test/java/com/j256/ormlite/stmt/QueryBuilderTest.java @@ -1528,6 +1528,33 @@ public class QueryBuilderTest extends BaseCoreStmtTest { assertEquals(bar2.id, results.get(2).baz.bar.id); } + @Test + public void testCountInReadOnlyField() throws Exception { + Dao<AsField, Integer> dao = createDao(AsField.class, true); + + AsField foo1 = new AsField(); + int val1 = 123213; + foo1.val = val1; + assertEquals(1, dao.create(foo1)); + + AsField foo2 = new AsField(); + int val2 = 122433213; + foo2.val = val2; + assertEquals(1, dao.create(foo2)); + + QueryBuilder<AsField, Integer> qb = dao.queryBuilder(); + qb.selectRaw("*"); + int val3 = 12; + qb.selectRaw(val3 + " AS " + AsField.SUM_FIELD); + + List<AsField> results = dao.queryRaw(qb.prepareStatementString(), dao.getRawRowMapper()).getResults(); + assertEquals(2, results.size()); + assertEquals(val1, (int) results.get(0).val); + assertEquals(val3, (int) results.get(0).sum); + assertEquals(val2, (int) results.get(1).val); + assertEquals(val3, (int) results.get(1).sum); + } + /* ======================================================================================================== */ private static class LimitInline extends BaseDatabaseType { @@ -1645,6 +1672,20 @@ public class QueryBuilderTest extends BaseCoreStmtTest { } } + protected static class AsField { + public static final String VAL_FIELD = "val"; + public static final String SUM_FIELD = "sum"; + @DatabaseField(generatedId = true) + int id; + @DatabaseField(columnName = VAL_FIELD) + int val; + @DatabaseField(readOnly = true, columnName = SUM_FIELD) + Integer sum; + + public AsField() { + } + } + protected static class BaseModel { @DatabaseField(generatedId = true) int id;
Added in read-only field test.
j256_ormlite-core
train
71d2ff494694d7f18310c7994daa34dce33af98b
diff --git a/utils.go b/utils.go index <HASH>..<HASH> 100644 --- a/utils.go +++ b/utils.go @@ -20,7 +20,8 @@ func CompareConfig(a, b *Config) bool { if len(a.Cmd) != len(b.Cmd) || len(a.Dns) != len(b.Dns) || len(a.Env) != len(b.Env) || - len(a.PortSpecs) != len(b.PortSpecs) { + len(a.PortSpecs) != len(b.PortSpecs) || + len(a.Entrypoint) != len(b.Entrypoint) { return false }
Hotfix: check the length of entrypoint before comparing.
containers_storage
train
1e2bc5b5da0383b904a13889c96b11fb14c93a7f
diff --git a/server/src/main/java/io/atomix/copycat/server/state/LeaderState.java b/server/src/main/java/io/atomix/copycat/server/state/LeaderState.java index <HASH>..<HASH> 100644 --- a/server/src/main/java/io/atomix/copycat/server/state/LeaderState.java +++ b/server/src/main/java/io/atomix/copycat/server/state/LeaderState.java @@ -18,6 +18,7 @@ package io.atomix.copycat.server.state; import io.atomix.catalyst.concurrent.ComposableFuture; import io.atomix.catalyst.concurrent.Scheduled; import io.atomix.catalyst.transport.Connection; +import io.atomix.catalyst.util.Assert; import io.atomix.copycat.Command; import io.atomix.copycat.Query; import io.atomix.copycat.error.CopycatError; @@ -94,7 +95,7 @@ final class LeaderState extends ActiveState { try (InitializeEntry entry = context.getLog().create(InitializeEntry.class)) { entry.setTerm(term) .setTimestamp(appender.time()); - assert context.getLog().append(entry) == appender.index(); + Assert.state(context.getLog().append(entry) == appender.index(), "Initialize entry not appended at the start of the leader's term"); LOGGER.debug("{} - Appended {}", context.getCluster().member().address(), entry); } @@ -224,7 +225,7 @@ final class LeaderState extends ActiveState { .setTimestamp(System.currentTimeMillis()) .setMembers(members); index = context.getLog().append(entry); - LOGGER.debug("{} - Appended {} to log at index {}", context.getCluster().member().address(), entry, index); + LOGGER.debug("{} - Appended {}", context.getCluster().member().address(), entry); // Store the index of the configuration entry in order to prevent other configurations from // being logged and committed concurrently. This is an important safety property of Raft. @@ -528,7 +529,7 @@ final class LeaderState extends ActiveState { .setSequence(request.sequence()) .setCommand(command); index = context.getLog().append(entry); - LOGGER.debug("{} - Appended {} to log at index {}", context.getCluster().member().address(), entry, index); + LOGGER.debug("{} - Appended {}", context.getCluster().member().address(), entry); } // Replicate the command to followers.
Remove assert statement when appending InitializeEntry to the log.
atomix_copycat
train
286c2cf366188460e1787b864c80831c63755886
diff --git a/src/Url.php b/src/Url.php index <HASH>..<HASH> 100644 --- a/src/Url.php +++ b/src/Url.php @@ -11,6 +11,7 @@ use Innmind\Url\{ Authority\Port, Exception\DomainException, }; +use Innmind\Immutable\Maybe; use League\Uri; /** @@ -69,6 +70,22 @@ final class Url ); } + /** + * Similar to self::of() but will return nothing instead of throwing an + * exception + * + * @return Maybe<self> + */ + public static function maybe(string $string): Maybe + { + try { + return Maybe::just(self::of($string)); + } catch (DomainException $e) { + /** @var Maybe<self> */ + return Maybe::nothing(); + } + } + public function equals(self $url): bool { return $this->scheme->equals($url->scheme()) && diff --git a/tests/UrlTest.php b/tests/UrlTest.php index <HASH>..<HASH> 100644 --- a/tests/UrlTest.php +++ b/tests/UrlTest.php @@ -88,6 +88,26 @@ class UrlTest extends TestCase $this->assertSame($fragment, $url->fragment()->toString()); } + /** + * @dataProvider fromString + * @dataProvider parseable + */ + public function testValidStringsReturnAnUrl($string) + { + $this->assertInstanceOf(Url::class, Url::maybe($string)->match( + static fn($url) => $url, + static fn() => null, + )); + } + + public function testMaybeReturnNothingForUnparseableStrings() + { + $this->assertNull(Url::maybe('http://user:password/path')->match( + static fn($url) => $url, + static fn() => null, + )); + } + public function testThrowWhenBuildingFromInvalidString() { $this->expectException(DomainException::class);
add named constructor to return a Maybe instead of throwing an exception
Innmind_Url
train
2a6bd52690646bef9409f3327cfb1134ff51c1be
diff --git a/commands/pull_request.go b/commands/pull_request.go index <HASH>..<HASH> 100644 --- a/commands/pull_request.go +++ b/commands/pull_request.go @@ -158,9 +158,21 @@ func pullRequest(cmd *Command, args *Args) { var editor *github.Editor if title == "" && flagPullRequestIssue == "" { - baseBranch := fmt.Sprintf("%s/%s", baseProject.Remote, base) - remoteBranch := fmt.Sprintf("%s/%s", headProject.Remote, head) - message, err := pullRequestChangesMessage(baseBranch, remoteBranch, fullBase, fullHead) + baseTracking := base + headTracking := head + + remote := gitRemoteForProject(baseProject) + if remote != nil { + baseTracking = fmt.Sprintf("%s/%s", remote.Name, base) + } + if remote == nil || !baseProject.SameAs(headProject) { + remote = gitRemoteForProject(headProject) + } + if remote != nil { + headTracking = fmt.Sprintf("%s/%s", remote.Name, head) + } + + message, err := pullRequestChangesMessage(baseTracking, headTracking, fullBase, fullHead) utils.Check(err) editor, err = github.NewEditor("PULLREQ", "pull request", message) diff --git a/github/project.go b/github/project.go index <HASH>..<HASH> 100644 --- a/github/project.go +++ b/github/project.go @@ -15,7 +15,6 @@ type Project struct { Owner string Host string Protocol string - Remote *Remote } func (p Project) String() string { @@ -102,17 +101,6 @@ func useHttpProtocol() bool { return https == "https" } -func NewProjectFromRemote(remote *Remote) (*Project, error) { - p, err := NewProjectFromURL(remote.URL) - if err != nil { - return nil, err - } - - p.Remote = remote - - return p, nil -} - func NewProjectFromURL(url *url.URL) (p *Project, err error) { if !knownGitHubHosts().Include(url.Host) { err = fmt.Errorf("Invalid GitHub URL: %s", url) diff --git a/github/remote.go b/github/remote.go index <HASH>..<HASH> 100644 --- a/github/remote.go +++ b/github/remote.go @@ -23,7 +23,7 @@ func (remote *Remote) String() string { } func (remote *Remote) Project() (*Project, error) { - return NewProjectFromRemote(remote) + return NewProjectFromURL(remote.URL) } func Remotes() (remotes []Remote, err error) {
Revert to @mislav's solution to get base branch for pull request As discussed <URL>
github_hub
train
13a9a5825466d036c2f0ec033cca1701174d020c
diff --git a/charmhelpers/contrib/openstack/context.py b/charmhelpers/contrib/openstack/context.py index <HASH>..<HASH> 100644 --- a/charmhelpers/contrib/openstack/context.py +++ b/charmhelpers/contrib/openstack/context.py @@ -428,9 +428,9 @@ class HAProxyContext(OSContextGenerator): } if config('haproxy-server-timeout'): - ctxt['haproxy-server-timeout'] = config('haproxy-server-timeout') + ctxt['haproxy_server_timeout'] = config('haproxy-server-timeout') if config('haproxy-client-timeout'): - ctxt['haproxy-client-timeout'] = config('haproxy-client-timeout') + ctxt['haproxy_client_timeout'] = config('haproxy-client-timeout') if config('prefer-ipv6'): ctxt['local_host'] = 'ip6-localhost' diff --git a/charmhelpers/contrib/openstack/templates/haproxy.cfg b/charmhelpers/contrib/openstack/templates/haproxy.cfg index <HASH>..<HASH> 100644 --- a/charmhelpers/contrib/openstack/templates/haproxy.cfg +++ b/charmhelpers/contrib/openstack/templates/haproxy.cfg @@ -14,14 +14,14 @@ defaults retries 3 timeout queue 1000 timeout connect 1000 -{% if haproxy-client-timeout -%} - timeout client {{ haproxy-client-timeout }} +{% if haproxy_client_timeout -%} + timeout client {{ haproxy_client_timeout }} {% else -%} timeout client 30000 {% endif -%} -{% if haproxy-server-timeout -%} - timeout server {{ haproxy-server-timeout }} +{% if haproxy_server_timeout -%} + timeout server {{ haproxy_server_timeout }} {% else -%} timeout server 30000 {% endif -%} diff --git a/tests/contrib/openstack/test_os_contexts.py b/tests/contrib/openstack/test_os_contexts.py index <HASH>..<HASH> 100644 --- a/tests/contrib/openstack/test_os_contexts.py +++ b/tests/contrib/openstack/test_os_contexts.py @@ -948,8 +948,8 @@ class ContextTests(unittest.TestCase): }, 'local_host': '127.0.0.1', - 'haproxy-server-timeout': 50000, - 'haproxy-client-timeout': 50000, + 'haproxy_server_timeout': 50000, + 'haproxy_client_timeout': 50000, 'haproxy_host': '0.0.0.0', 'stat_port': ':8888', }
Fix use of '-' in http timeout variables in a haproxy template which causes explosions
juju_charm-helpers
train
df9ec497a6c5b2cd3cfea305c4ea30cbab964664
diff --git a/repairbox/coverage.py b/repairbox/coverage.py index <HASH>..<HASH> 100644 --- a/repairbox/coverage.py +++ b/repairbox/coverage.py @@ -69,6 +69,13 @@ class CoverageReport(object): self.__files = files + def files(self): + """ + A list of the names of the files that are included in this report. + """ + return list(self.__files.keys()) + + def file(self, name: str) -> FileCoverageReport: assert name != "" return self.__files[name]
added CoverageReport.files
squaresLab_BugZoo
train
9ad0dd8a1fac2e03be1fe3b44eb3b198994586ad
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -3,4 +3,5 @@ import setuptools setuptools.setup( setup_requires=['pbr>=1.3', 'setuptools>=17.1'], + python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*', pbr=True)
Add python_requires to help pip
testing-cabal_mock
train
b2d871d8998a5b1643134e5db7bf9281cb81225a
diff --git a/src/main/java/com/ning/billing/recurly/model/Redemption.java b/src/main/java/com/ning/billing/recurly/model/Redemption.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/ning/billing/recurly/model/Redemption.java +++ b/src/main/java/com/ning/billing/recurly/model/Redemption.java @@ -43,6 +43,9 @@ public class Redemption extends RecurlyObject { @XmlElement(name = "account_code") private String accountCode; + @XmlElement(name = "subscription_uuid") + private String subscriptionUuid; + @XmlElement(name = "coupon") private Coupon coupon; @@ -75,6 +78,14 @@ public class Redemption extends RecurlyObject { this.accountCode = stringOrNull(accountCode); } + public String getSubscriptionUuid() { + return subscriptionUuid; + } + + public void setSubscriptionUuid(String subscriptionUuid) { + this.subscriptionUuid = subscriptionUuid; + } + public Coupon getCoupon() { if (coupon != null && coupon.getCouponCode() == null) { coupon = fetch(coupon, Coupon.class); @@ -158,6 +169,7 @@ public class Redemption extends RecurlyObject { final StringBuilder sb = new StringBuilder(); sb.append("Redemption"); sb.append("{accountCode=").append(accountCode); + sb.append(", subscriptionUuid=").append(subscriptionUuid); sb.append(", coupon=").append(coupon); sb.append(", account=").append(account); sb.append(", uuid=").append(uuid); @@ -181,6 +193,9 @@ public class Redemption extends RecurlyObject { if (accountCode != null ? !accountCode.equals(that.accountCode) : that.accountCode != null) { return false; } + if (subscriptionUuid != null ? !subscriptionUuid.equals(that.subscriptionUuid) : that.subscriptionUuid != null) { + return false; + } if (coupon != null ? !coupon.equals(that.coupon) : that.coupon != null) { return false; } @@ -217,6 +232,7 @@ public class Redemption extends RecurlyObject { public int hashCode() { return Objects.hashCode( accountCode, + subscriptionUuid, coupon, account, singleUse, diff --git a/src/test/java/com/ning/billing/recurly/TestUtils.java b/src/test/java/com/ning/billing/recurly/TestUtils.java index <HASH>..<HASH> 100644 --- a/src/test/java/com/ning/billing/recurly/TestUtils.java +++ b/src/test/java/com/ning/billing/recurly/TestUtils.java @@ -769,6 +769,7 @@ public class TestUtils { redemption.setAccount(account); redemption.setAccountCode(account.getAccountCode()); + redemption.setSubscriptionUuid(randomAlphaNumericString(10, seed)); redemption.setCoupon(createRandomCoupon(seed)); redemption.setSingleUse(true); redemption.setState("redeemed"); diff --git a/src/test/java/com/ning/billing/recurly/model/TestRedemption.java b/src/test/java/com/ning/billing/recurly/model/TestRedemption.java index <HASH>..<HASH> 100644 --- a/src/test/java/com/ning/billing/recurly/model/TestRedemption.java +++ b/src/test/java/com/ning/billing/recurly/model/TestRedemption.java @@ -54,12 +54,24 @@ public class TestRedemption extends TestModelBase { final Redemption redemption = new Redemption(); redemption.setAccountCode("1"); redemption.setCurrency("USD"); + redemption.setSubscriptionUuid("374a1c75374bd81493a3f7425db0a2b8"); final String xml = xmlMapper.writeValueAsString(redemption); Assert.assertEquals(xml, "<redemption xmlns=\"\">" + "<account_code>1</account_code>" + + "<subscription_uuid>374a1c75374bd81493a3f7425db0a2b8</subscription_uuid>" + "<currency>USD</currency>" + "</redemption>"); + + final Redemption redemptionWithoutUuid = new Redemption(); + redemptionWithoutUuid.setAccountCode("1"); + redemptionWithoutUuid.setCurrency("USD"); + + final String secondXml = xmlMapper.writeValueAsString(redemptionWithoutUuid); + Assert.assertEquals(secondXml, "<redemption xmlns=\"\">" + + "<account_code>1</account_code>" + + "<currency>USD</currency>" + + "</redemption>"); } @Test(groups = "fast")
Add ability to set subscription UUID when redeeming a coupon
killbilling_recurly-java-library
train
de4299205a406018caa2e247eb09136bc2391d55
diff --git a/trunk/mapreduce/src/java/com/marklogic/mapreduce/InternalUtilities.java b/trunk/mapreduce/src/java/com/marklogic/mapreduce/InternalUtilities.java index <HASH>..<HASH> 100644 --- a/trunk/mapreduce/src/java/com/marklogic/mapreduce/InternalUtilities.java +++ b/trunk/mapreduce/src/java/com/marklogic/mapreduce/InternalUtilities.java @@ -7,6 +7,8 @@ import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.BooleanWritable; import org.apache.hadoop.io.BytesWritable; @@ -19,6 +21,7 @@ import org.apache.hadoop.io.VIntWritable; import org.apache.hadoop.io.VLongWritable; import org.apache.hadoop.io.Writable; import org.apache.hadoop.util.ReflectionUtils; +import org.apache.hadoop.util.VersionInfo; import com.marklogic.xcc.ContentSource; import com.marklogic.xcc.ContentSourceFactory; @@ -39,7 +42,9 @@ import com.marklogic.xcc.types.XSInteger; * @author jchen */ public class InternalUtilities implements MarkLogicConstants { - + public static final Log LOG = + LogFactory.getLog(MarkLogicConstants.class); + /** * Get input server URI based on the job configuration. * @param conf job configuration @@ -261,7 +266,8 @@ public class InternalUtilities implements MarkLogicConstants { } else if (valueClass.equals(MarkLogicNode.class) && (result.getValueType() == ValueType.NODE || result.getValueType() == ValueType.ELEMENT || - result.getValueType() == ValueType.DOCUMENT)) { + result.getValueType() == ValueType.DOCUMENT || + result.getValueType() == ValueType.ATTRIBUTE)) { ((MarkLogicNode)value).set(result); } else { throw new UnsupportedOperationException("Value " + @@ -298,4 +304,20 @@ public class InternalUtilities implements MarkLogicConstants { throw new IllegalStateException("No host found while taskId = " + taskId + ", forestHostMap.size() = " + count); } + + /** + * Check against unsupported versions. + */ + public static void checkVersion() { + // check version + String version = VersionInfo.getVersion(); + if (LOG.isDebugEnabled()) { + LOG.debug("version: " + VersionInfo.getVersion()); + } + if (version.startsWith("0.20.203") || + version.startsWith("0.20.204")) { + throw new UnsupportedOperationException( + "Hadoop version " + version + " is not supported."); + } + } } \ No newline at end of file diff --git a/trunk/mapreduce/src/java/com/marklogic/mapreduce/MarkLogicInputFormat.java b/trunk/mapreduce/src/java/com/marklogic/mapreduce/MarkLogicInputFormat.java index <HASH>..<HASH> 100644 --- a/trunk/mapreduce/src/java/com/marklogic/mapreduce/MarkLogicInputFormat.java +++ b/trunk/mapreduce/src/java/com/marklogic/mapreduce/MarkLogicInputFormat.java @@ -38,8 +38,8 @@ import com.marklogic.xcc.types.XSString; * * @author jchen */ -public abstract class MarkLogicInputFormat<KEYIN, VALUEIN> extends InputFormat<KEYIN, VALUEIN> -implements MarkLogicConstants { +public abstract class MarkLogicInputFormat<KEYIN, VALUEIN> +extends InputFormat<KEYIN, VALUEIN> implements MarkLogicConstants { public static final Log LOG = LogFactory.getLog(MarkLogicInputFormat.class); static final String DEFAULT_DOCUMENT_SELECTOR = "fn:collection()"; @@ -52,7 +52,9 @@ implements MarkLogicConstants { */ @Override public List<InputSplit> getSplits(JobContext jobContext) throws IOException, - InterruptedException { + InterruptedException { + InternalUtilities.checkVersion(); + // get input from job configuration Configuration jobConf = jobContext.getConfiguration(); long maxSplitSize; diff --git a/trunk/mapreduce/src/java/com/marklogic/mapreduce/MarkLogicOutputFormat.java b/trunk/mapreduce/src/java/com/marklogic/mapreduce/MarkLogicOutputFormat.java index <HASH>..<HASH> 100644 --- a/trunk/mapreduce/src/java/com/marklogic/mapreduce/MarkLogicOutputFormat.java +++ b/trunk/mapreduce/src/java/com/marklogic/mapreduce/MarkLogicOutputFormat.java @@ -63,6 +63,8 @@ implements MarkLogicConstants, Configurable { @Override public void checkOutputSpecs(JobContext context) throws IOException, InterruptedException { + InternalUtilities.checkVersion(); + Session session = null; ResultSequence result = null; try {
<I>: Check against unsupported Hadoop versions.
marklogic_marklogic-contentpump
train
0e689fcf94af3a36ddab9075c7328aa7f1656cbd
diff --git a/cloudfoundry-client/src/main/java/org/cloudfoundry/client/v2/applications/_ApplicationInstanceInfo.java b/cloudfoundry-client/src/main/java/org/cloudfoundry/client/v2/applications/_ApplicationInstanceInfo.java index <HASH>..<HASH> 100644 --- a/cloudfoundry-client/src/main/java/org/cloudfoundry/client/v2/applications/_ApplicationInstanceInfo.java +++ b/cloudfoundry-client/src/main/java/org/cloudfoundry/client/v2/applications/_ApplicationInstanceInfo.java @@ -57,6 +57,13 @@ abstract class _ApplicationInstanceInfo { abstract Integer getDebugPort(); /** + * The details + */ + @JsonProperty("details") + @Nullable + abstract String getDetails(); + + /** * The since */ @JsonProperty("since")
Add Missing Payload This change adds a payload element that was missing.
cloudfoundry_cf-java-client
train
68660753f35075cf9eb5b70c688a063ee1235099
diff --git a/app/src/main/java/com/mikepenz/materialdrawer/app/DrawerActivity.java b/app/src/main/java/com/mikepenz/materialdrawer/app/DrawerActivity.java index <HASH>..<HASH> 100755 --- a/app/src/main/java/com/mikepenz/materialdrawer/app/DrawerActivity.java +++ b/app/src/main/java/com/mikepenz/materialdrawer/app/DrawerActivity.java @@ -17,7 +17,7 @@ import com.mikepenz.fastadapter.utils.RecyclerViewCacheUtil; import com.mikepenz.fontawesome_typeface_library.FontAwesome; import com.mikepenz.google_material_typeface_library.GoogleMaterial; import com.mikepenz.iconics.IconicsDrawable; -import com.mikepenz.itemanimators.AlphaInAnimator; +import com.mikepenz.itemanimators.AlphaCrossFadeAnimator; import com.mikepenz.materialdrawer.AccountHeader; import com.mikepenz.materialdrawer.AccountHeaderBuilder; import com.mikepenz.materialdrawer.Drawer; @@ -41,7 +41,7 @@ import com.mikepenz.materialdrawer.model.interfaces.Nameable; import com.mikepenz.octicons_typeface_library.Octicons; public class DrawerActivity extends AppCompatActivity { - private static final int PROFILE_SETTING = 1; + private static final int PROFILE_SETTING = 100000; //save our header or result private AccountHeader headerResult = null; @@ -81,7 +81,7 @@ public class DrawerActivity extends AppCompatActivity { profile6, //don't ask but google uses 14dp for the add account icon in gmail but 20dp for the normal icons (like manage account) new ProfileSettingDrawerItem().withName("Add Account").withDescription("Add new GitHub Account").withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_plus).actionBar().paddingDp(5).colorRes(R.color.material_drawer_primary_text)).withIdentifier(PROFILE_SETTING), - new ProfileSettingDrawerItem().withName("Manage Account").withIcon(GoogleMaterial.Icon.gmd_settings) + new ProfileSettingDrawerItem().withName("Manage Account").withIcon(GoogleMaterial.Icon.gmd_settings).withIdentifier(100001) ) .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() { @Override @@ -111,7 +111,7 @@ public class DrawerActivity extends AppCompatActivity { .withActivity(this) .withToolbar(toolbar) .withHasStableIds(true) - .withItemAnimator(new AlphaInAnimator()) + .withItemAnimator(new AlphaCrossFadeAnimator()) .withAccountHeader(headerResult) //set the AccountHeader we created earlier for the header .addDrawerItems( new PrimaryDrawerItem().withName(R.string.drawer_item_compact_header).withDescription(R.string.drawer_item_compact_header_desc).withIcon(GoogleMaterial.Icon.gmd_sun).withIdentifier(1).withSelectable(false),
* use better animator in sample * use unique identifier for profileSettings so the animation looks better
mikepenz_MaterialDrawer
train
97508dec45b76a3f0eb7c60ebe5d2b03fb3fa010
diff --git a/synapse/lib/socket.py b/synapse/lib/socket.py index <HASH>..<HASH> 100644 --- a/synapse/lib/socket.py +++ b/synapse/lib/socket.py @@ -270,6 +270,7 @@ class Socket(EventBus): except Exception as e: return None, None + logger.debug('Accepting connection from %r', addr) sock = self.__class__(sock, accept=True) relay = self.get('relay')
Log socket.getpeername on connections.
vertexproject_synapse
train
fd6488b3d5f490af7ea5705940606edebe1c9512
diff --git a/actors/spec/instance_setup_spec.rb b/actors/spec/instance_setup_spec.rb index <HASH>..<HASH> 100644 --- a/actors/spec/instance_setup_spec.rb +++ b/actors/spec/instance_setup_spec.rb @@ -45,6 +45,9 @@ describe InstanceSetup do flexmock(RightScale::AuditorProxy).should_receive(:new).and_return(@auditor) @results_factory = RightScale::NaniteResultsMock.new InstanceSetup.results_factory = @results_factory + @mgr = RightScale::LoginManager.instance + flexmock(@mgr).should_receive(:supported_by_platform?).and_return(true) + flexmock(@mgr).should_receive(:write_keys_file).and_return(true) setup_state setup_script_execution end diff --git a/agents/spec/login_manager_spec.rb b/agents/spec/login_manager_spec.rb index <HASH>..<HASH> 100644 --- a/agents/spec/login_manager_spec.rb +++ b/agents/spec/login_manager_spec.rb @@ -9,7 +9,8 @@ describe RightScale::LoginManager do before(:all) do flexmock(RightScale::RightLinkLog).should_receive(:debug).by_default @mgr = RightScale::LoginManager.instance - flexmock(@mgr).should_receive(:supported_by_platform?).and_return(true) + flexmock(@mgr).should_receive(:supported_by_platform?).and_return(true).by_default + flexmock(@mgr).should_receive(:write_keys_file).and_return(true).by_default end context :update_policy do
Keep LoginManager from writing authorized_keys during tests.
rightscale_right_agent
train
b8e2e2c9c9113819e66abd5704acbd55698f2b3e
diff --git a/polymodels/__init__.py b/polymodels/__init__.py index <HASH>..<HASH> 100644 --- a/polymodels/__init__.py +++ b/polymodels/__init__.py @@ -1 +1 @@ -__version__ = (1, 0, 0) \ No newline at end of file +__version__ = (1, 0, 1) \ No newline at end of file
Bumped version to <I>
charettes_django-polymodels
train
cea1a984e90661390462ed22399ef5df5b01d7b4
diff --git a/config/tests/testgrids/config_test.go b/config/tests/testgrids/config_test.go index <HASH>..<HASH> 100644 --- a/config/tests/testgrids/config_test.go +++ b/config/tests/testgrids/config_test.go @@ -46,6 +46,7 @@ var ( "istio", "googleoss", "google", + "knative", // This allows both "knative" and "knative-sandbox", as well as "knative-google" "kopeio", "redhat", "vmware",
Fix testgrid prefix problem for knative
kubernetes_test-infra
train
4245b45252b34fb5d3e3651d1b11f05a80ac35b1
diff --git a/llrb_test.go b/llrb_test.go index <HASH>..<HASH> 100644 --- a/llrb_test.go +++ b/llrb_test.go @@ -135,9 +135,14 @@ func makeTree(desc string) (n *Node) { continue } if b == ')' { + if cn.Left == nil && cn.Right == nil { + return nil, i + } continue } - cn.Elem = compRune(b) + if b != ';' { + cn.Elem = compRune(b) + } return cn, i } @@ -145,6 +150,9 @@ func makeTree(desc string) (n *Node) { } n, _ = build([]rune(desc)) + if n.Left == nil && n.Right == nil { + n = nil + } return } @@ -182,7 +190,11 @@ func describeTree(n *Node, char, color bool) string { } } } - follow(n) + if n == nil { + s = []rune("()") + } else { + follow(n) + } s = append(s, ';') return string(s) @@ -196,9 +208,15 @@ type S struct{} var _ = check.Suite(&S{}) func (s *S) TestMakeAndDescribeTree(c *check.C) { - desc := "((a,c)b,(e,g)f)d;" - tree := makeTree(desc) - c.Check(describeTree(tree, true, false), check.DeepEquals, desc) + c.Check(describeTree((*Node)(nil), true, false), check.DeepEquals, "();") + for _, desc := range []string{ + "();", + "((a,c)b,(e,g)f)d;", + } { + t := makeTree(desc) + c.Logf("%#v", t) + c.Check(describeTree(t, true, false), check.DeepEquals, desc) + } } // ((a,c)b,(e,g)f)d -rotL-> (((a,c)b,e)d,g)f
Make describeTree nil-safe What is the Newick for an empty tree: `();' or `;'? I think the former.
biogo_store
train
53cefb03f1bf91a06bd7f138508cca8a38a3929b
diff --git a/borax/htmls.py b/borax/htmls.py index <HASH>..<HASH> 100644 --- a/borax/htmls.py +++ b/borax/htmls.py @@ -51,4 +51,4 @@ def html_tag(tag_name, content=None, **kwargs): if content: return HTMLString('<{0} {1}>{2}</{0}>'.format(tag_name, html_params(**kwargs), content)) else: - return HTMLString('<{0} {1} />'.format(tag_name, html_params(**kwargs))) + return HTMLString('<{0} {1}>'.format(tag_name, html_params(**kwargs))) diff --git a/tests/test_htmls.py b/tests/test_htmls.py index <HASH>..<HASH> 100644 --- a/tests/test_htmls.py +++ b/tests/test_htmls.py @@ -8,7 +8,7 @@ from borax.htmls import HTMLString, html_tag class HtmlTagTest(unittest.TestCase): def test_html_tags(self): html = html_tag('img', id_='idDemoImg', src='/demo.png') - self.assertEqual(html, '<img id="idDemoImg" src="/demo.png" />') + self.assertEqual(html, '<img id="idDemoImg" src="/demo.png">') html = html_tag('div', content='Test', id_='idDemo', data_my_attr='23') self.assertEqual(html, '<div id="idDemo" data-my-attr="23">Test</div>')
:rotating_light: Remove ending slash for self-closed tag for borax.html.html_tag
kinegratii_borax
train
749ca07380d1b5e8858c9fa36c6bbbf8b6855a21
diff --git a/test/src/test/java/hudson/cli/CLITest.java b/test/src/test/java/hudson/cli/CLITest.java index <HASH>..<HASH> 100644 --- a/test/src/test/java/hudson/cli/CLITest.java +++ b/test/src/test/java/hudson/cli/CLITest.java @@ -167,6 +167,9 @@ public class CLITest { args.addAll(Arrays.asList("build", "-s", "-v", "p")); Proc proc = new Launcher.LocalLauncher(StreamTaskListener.fromStderr()).launch().cmds(args).stdout(new TeeOutputStream(baos, System.out)).stderr(System.err).start(); while (!baos.toString().contains("Sleeping ")) { + if (!proc.isAlive()) { + throw new AssertionError("Process failed to start with " + proc.join()); + } Thread.sleep(100); } System.err.println("Killing client");
Do not timeout the test when cli invocation fails
jenkinsci_jenkins
train
47edbfe8fc6a012305f21d340c5f43c34f833b5e
diff --git a/core/manifest/ConfigStaticManifest.php b/core/manifest/ConfigStaticManifest.php index <HASH>..<HASH> 100644 --- a/core/manifest/ConfigStaticManifest.php +++ b/core/manifest/ConfigStaticManifest.php @@ -80,7 +80,7 @@ class SS_ConfigStaticManifest { if ($static['access'] != T_PRIVATE) { Deprecation::notice('3.2.0', "Config static $class::\$$name must be marked as private", Deprecation::SCOPE_GLOBAL); // Don't warn more than once per static - $static['access'] = T_PRIVATE; + $this->statics[$class][$name]['access'] = T_PRIVATE; } return $static['value']; @@ -231,11 +231,12 @@ class SS_ConfigStaticManifest_Parser { else if($type == T_PUBLIC || $type == T_PRIVATE || $type == T_PROTECTED) { $access = $type; } - else if($type == T_STATIC) { - if($class && $depth == $clsdepth) $this->parseStatic($access, $namespace ? $namespace.'\\'.$class : $class); + else if($type == T_STATIC && $class && $depth == $clsdepth) { + $this->parseStatic($access, $namespace ? $namespace.'\\'.$class : $class); + $access = 0; } else { - $access = ''; + $access = 0; } } } diff --git a/tests/core/manifest/ConfigStaticManifestTest.php b/tests/core/manifest/ConfigStaticManifestTest.php index <HASH>..<HASH> 100644 --- a/tests/core/manifest/ConfigStaticManifestTest.php +++ b/tests/core/manifest/ConfigStaticManifestTest.php @@ -12,6 +12,7 @@ class ConfigStaticManifestTest extends SapphireTest { static public $public2; static protected $protected2; static private $private2; + static $nolevel_after_private; // Assigning values static $snone; @@ -96,7 +97,8 @@ DOC; 'protected' => T_PROTECTED, 'protected2' => T_PROTECTED, 'private' => T_PRIVATE, - 'private2' => T_PRIVATE + 'private2' => T_PRIVATE, + 'nolevel_after_private' => null ); foreach($levels as $var => $level) {
FIX ConfigStaticManifest persisting access level after parsing a static
silverstripe_silverstripe-framework
train
1fb7b68c51bd5435d4a4c3ce164d24d69f00ccde
diff --git a/py2/cherrypy/lib/reprconf.py b/py2/cherrypy/lib/reprconf.py index <HASH>..<HASH> 100644 --- a/py2/cherrypy/lib/reprconf.py +++ b/py2/cherrypy/lib/reprconf.py @@ -437,7 +437,7 @@ def unrepr(s): """Return a Python object compiled from a string.""" if not s: return s - if sys.version_info <= (3, 0): + if sys.version_info < (3, 0): b = _Builder2() else: b = _Builder3() diff --git a/py2/cherrypy/test/fcgi.conf b/py2/cherrypy/test/fcgi.conf index <HASH>..<HASH> 100644 --- a/py2/cherrypy/test/fcgi.conf +++ b/py2/cherrypy/test/fcgi.conf @@ -1,7 +1,7 @@ # Apache2 server conf file for testing CherryPy with mod_fcgid. -DocumentRoot "C:\Python25\Lib\site-packages\cherrypy\test" +DocumentRoot "/usr/lib/python2.6/site-packages/cproot/trunk/cherrypy/test" ServerName 127.0.0.1 Listen 8080 LoadModule fastcgi_module modules/mod_fastcgi.dll @@ -11,4 +11,4 @@ Options ExecCGI SetHandler fastcgi-script RewriteEngine On RewriteRule ^(.*)$ /fastcgi.pyc [L] -FastCgiExternalServer "C:\\Python25\\Lib\\site-packages\\cherrypy\\test\\fastcgi.pyc" -host 127.0.0.1:4000 +FastCgiExternalServer "/usr/lib/python2.6/site-packages/cproot/trunk/cherrypy/test/fastcgi.pyc" -host 127.0.0.1:4000 diff --git a/py2/cherrypy/test/logtest.py b/py2/cherrypy/test/logtest.py index <HASH>..<HASH> 100644 --- a/py2/cherrypy/test/logtest.py +++ b/py2/cherrypy/test/logtest.py @@ -4,7 +4,7 @@ import sys import time import cherrypy -from cherrypy._cpcompat import ntob +from cherrypy._cpcompat import basestring, ntob, unicodestr try: @@ -112,6 +112,8 @@ class LogCase(object): if marker is None: return open(logfile, 'rb').readlines() + if isinstance(marker, unicodestr): + marker = marker.encode('utf-8') data = [] in_region = False for line in open(logfile, 'rb'): @@ -163,9 +165,11 @@ class LogCase(object): # Single arg. Use __getitem__ and allow lines to be str or list. if isinstance(lines, (tuple, list)): lines = lines[0] + if isinstance(lines, unicodestr): + lines = lines.encode('utf-8') if lines not in data[sliceargs]: msg = "%r not found on log line %r" % (lines, sliceargs) - self._handleLogError(msg, [data[sliceargs]], marker, lines) + self._handleLogError(msg, [data[sliceargs],"--EXTRA CONTEXT--"] + data[sliceargs+1:sliceargs+6], marker, lines) else: # Multiple args. Use __getslice__ and require lines to be list. if isinstance(lines, tuple): @@ -176,6 +180,8 @@ class LogCase(object): start, stop = sliceargs for line, logline in zip(lines, data[start:stop]): + if isinstance(line, unicodestr): + line = line.encode('utf-8') if line not in logline: msg = "%r not found in log" % line self._handleLogError(msg, data[start:stop], marker, line) diff --git a/py2/cherrypy/test/test_config.py b/py2/cherrypy/test/test_config.py index <HASH>..<HASH> 100644 --- a/py2/cherrypy/test/test_config.py +++ b/py2/cherrypy/test/test_config.py @@ -57,7 +57,10 @@ def setup_server(): return 'Hello world' silly.exposed = True silly._cp_config = {'response.headers.X-silly': 'sillyval'} - + + # Test the expose and config decorators + #@cherrypy.expose + #@cherrypy.config(foo='this3', **{'bax': 'this4'}) def bar(self, key): return repr(cherrypy.request.config.get(key, None)) bar.exposed = True diff --git a/py2/cherrypy/test/test_core.py b/py2/cherrypy/test/test_core.py index <HASH>..<HASH> 100644 --- a/py2/cherrypy/test/test_core.py +++ b/py2/cherrypy/test/test_core.py @@ -56,8 +56,7 @@ class CoreRequestHandlingTest(helper.CPWebCase): if isinstance(value, types.FunctionType): value.exposed = True setattr(root, name.lower(), cls()) - class Test(object): - __metaclass__ = TestType + Test = TestType('Test', (object, ), {}) class URL(Test):
Even more sync for py2 ;)
cherrypy_cheroot
train
7a2a1741ee3e6cfd552d261738aabbe9d1cbc705
diff --git a/tests/middleware/test_logging.py b/tests/middleware/test_logging.py index <HASH>..<HASH> 100644 --- a/tests/middleware/test_logging.py +++ b/tests/middleware/test_logging.py @@ -7,6 +7,15 @@ import websockets from tests.utils import run_server from uvicorn import Config +from uvicorn.protocols.http.h11_impl import H11Protocol + +try: + from uvicorn.protocols.http.httptools_impl import HttpToolsProtocol +except ImportError: # pragma: nocover + HttpToolsProtocol = None + + +HTTP_PROTOCOLS = [p for p in [H11Protocol, HttpToolsProtocol] if p is not None] @contextlib.contextmanager @@ -49,7 +58,7 @@ async def test_trace_logging(caplog, logging_config): @pytest.mark.anyio [email protected]("http_protocol", [("h11"), ("httptools")]) [email protected]("http_protocol", HTTP_PROTOCOLS) async def test_trace_logging_on_http_protocol(http_protocol, caplog, logging_config): config = Config( app=app, diff --git a/tests/protocols/test_http.py b/tests/protocols/test_http.py index <HASH>..<HASH> 100644 --- a/tests/protocols/test_http.py +++ b/tests/protocols/test_http.py @@ -766,6 +766,7 @@ async def test_invalid_http_request(request_line, protocol_cls, caplog): assert b"Invalid HTTP request received." in protocol.transport.buffer [email protected](HttpToolsProtocol is None, reason="httptools is not installed") def test_fragmentation(): def receive_all(sock): chunks = []
Fix skipping tests requiring httptools (#<I>) The test suite currently skips some tests when httptools are missing. However, there are more tests requiring it and they currently fail if that is the case. Cover them with necessary skips as well.
encode_uvicorn
train
fc87d871e007d306e86c12d11f410c97006cf769
diff --git a/lib/cucumber/ast/feature.rb b/lib/cucumber/ast/feature.rb index <HASH>..<HASH> 100644 --- a/lib/cucumber/ast/feature.rb +++ b/lib/cucumber/ast/feature.rb @@ -29,13 +29,22 @@ module Cucumber init visitor.visit_comment(@comment) unless @comment.empty? visitor.visit_tags(@tags) - visitor.visit_feature_name(@keyword, @name) + visitor.visit_feature_name(@keyword, indented_name) visitor.visit_background(@background) if @background @feature_elements.each do |feature_element| visitor.visit_feature_element(feature_element) end end + def indented_name + indent = "" + @name.split("\n").map do |l| + s = "#{indent}#{l}" + indent = " " + s + end.join("\n") + end + def source_tag_names @tags.tag_names end
Tweak indentation of name
cucumber_cucumber-ruby
train
004ab10fc79401cf3d3cf21f0e29ba45e6135150
diff --git a/lib/graphql/client/http.rb b/lib/graphql/client/http.rb index <HASH>..<HASH> 100644 --- a/lib/graphql/client/http.rb +++ b/lib/graphql/client/http.rb @@ -71,7 +71,12 @@ module GraphQL request.body = JSON.generate(body) response = http.request(request) - JSON.parse(response.body) + case response + when Net::HTTPOK + JSON.parse(response.body) + else + { "errors" => [{ "message" => "#{response.code} #{response.message}" }] } + end end end end
Handle non-<I> responses
github_graphql-client
train
f54b5d4224d4f0596748cef54dcb92a6f6f026b3
diff --git a/bokeh/io.py b/bokeh/io.py index <HASH>..<HASH> 100644 --- a/bokeh/io.py +++ b/bokeh/io.py @@ -626,6 +626,7 @@ def _get_screenshot_as_png(obj, driver): web_driver = driver web_driver.get("file:///" + html_path) + web_driver.maximize_window() ## resize for PhantomJS compat web_driver.execute_script("document.body.style.width = '100%';") diff --git a/bokeh/tests/test_io.py b/bokeh/tests/test_io.py index <HASH>..<HASH> 100644 --- a/bokeh/tests/test_io.py +++ b/bokeh/tests/test_io.py @@ -339,6 +339,23 @@ def test__get_screenshot_as_png_with_driver(): @pytest.mark.unit @pytest.mark.selenium +def test__get_screenshot_as_png_large_plot(): + layout = Plot(x_range=Range1d(), y_range=Range1d(), + plot_height=800, plot_width=800, toolbar_location=None, + outline_line_color=None, background_fill_color=None, + border_fill_color=None) + + driver = webdriver.PhantomJS(service_log_path=os.path.devnull) + assert driver.get_window_size() == {'width': 400, 'height': 300} + + io._get_screenshot_as_png(layout, driver) + + # LC: Although the window size doesn't match the plot dimensions (unclear + # why), the window resize allows for the whole plot to be captured + assert driver.get_window_size() == {'width': 1366, 'height': 768} + [email protected] [email protected] def test__get_svgs_no_svg_present(): layout = Plot(x_range=Range1d(), y_range=Range1d(), plot_height=20, plot_width=20, toolbar_location=None)
Maximize window for png screenshot to capture whole output (#<I>)
bokeh_bokeh
train
3b35818fc6e34f5684819010249eb362dd465394
diff --git a/great_expectations/render/renderer/site_builder.py b/great_expectations/render/renderer/site_builder.py index <HASH>..<HASH> 100644 --- a/great_expectations/render/renderer/site_builder.py +++ b/great_expectations/render/renderer/site_builder.py @@ -185,6 +185,9 @@ class SiteBuilder(object): site_section_builders = nested_update(default_site_section_builders_config, site_section_builders) self.site_section_builders = {} for site_section_name, site_section_config in site_section_builders.items(): + if not site_section_config or site_section_config in \ + ['0', 'None', 'False', 'false', 'FALSE', 'none', 'NONE']: + continue module_name = site_section_config.get('module_name') or 'great_expectations.render.renderer.site_builder' self.site_section_builders[site_section_name] = instantiate_class_from_config( config=site_section_config,
Add ability to exclude site section - if site section config is None or other falsey value
great-expectations_great_expectations
train
fff0f8ade7318406df8d10fbc13b426e7e97809b
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -4,7 +4,7 @@ from setuptools import setup, find_packages setup( name='jawa', packages=find_packages(), - version='2.1.0', + version='3.0.0', description='Doing fun stuff with JVM ClassFiles.', long_description=open('README.md', 'r').read(), long_description_content_type='text/markdown', @@ -27,10 +27,11 @@ setup( 'Topic :: Software Development :: Disassemblers' ], install_requires=[ - 'click>=5.0' + 'click>=7.0' ], tests_require=[ 'pytest>=2.10', + 'pytest-cov' ], extras_require={ 'dev': [ @@ -41,7 +42,6 @@ setup( 'sphinx-click', 'ghp-import', 'pyyaml', - 'ipython', 'twine', 'wheel' ]
Update setup.py for version and deps.
TkTech_Jawa
train
5bec41efd8759bcc52000dd7d421c481b9509ccd
diff --git a/src/dropbox.js b/src/dropbox.js index <HASH>..<HASH> 100644 --- a/src/dropbox.js +++ b/src/dropbox.js @@ -14,26 +14,26 @@ * initialize and replace remoteStorage.remote with remoteStorage.dropbox. * * In order to ensure compatibility with the public folder, <BaseClient.getItemURL> - * gets hijacked to return the DropBox public share URL. + * gets hijacked to return the Dropbox public share URL. * - * To use this backend, you need to specify the DropBox API key like so: + * To use this backend, you need to specify the Dropbox app key like so: * * (start code) * - * remoteStorage.setaApiKeys('dropbox', { - * api_key: 'your-api-key' + * remoteStorage.setApiKeys('dropbox', { + * api_key: 'your-app-key' * }); - * + * * (end code) * - * An API key can be obtained by registering your app at https://www.dropbox.com/developers/apps + * An app key can be obtained by registering your app at https://www.dropbox.com/developers/apps * * Known issues: * * - Storing files larger than 150MB is not yet supported * - Listing and deleting folders with more than 10'000 files will cause problems - * - Content-Type is not fully supported due to limitations of the DropBox API - * - DropBox preserves cases but is not case-sensitive + * - Content-Type is not fully supported due to limitations of the Dropbox API + * - Dropbox preserves cases but is not case-sensitive * - getItemURL is asynchronous which means getIetmURL returns useful values * after the syncCycle */ @@ -204,7 +204,7 @@ * Method: connect * * Set the backed to 'dropbox' and start the authentication flow in order - * to obtain an API token from DropBox. + * to obtain an API token from Dropbox. */ connect: function () { // TODO handling when token is already present @@ -516,7 +516,7 @@ /** * Method: share * - * Gets a publicly-accessible URL for the path from DropBox and stores it + * Gets a publicly-accessible URL for the path from Dropbox and stores it * in _itemRefs. * * Returns: @@ -529,13 +529,13 @@ return this._request('POST', url, {}).then(function (response) { if (response.status !== 200) { - return Promise.reject(new Error('Invalid DropBox API response status when sharing "' + path + '":' + response.status)); + return Promise.reject(new Error('Invalid Dropbox API response status when sharing "' + path + '":' + response.status)); } try { response = JSON.parse(response.responseText); } catch (e) { - return Promise.reject(new Error('Invalid DropBox API response when sharing "' + path + '": ' + response.responseText)); + return Promise.reject(new Error('Invalid Dropbox API response when sharing "' + path + '": ' + response.responseText)); } self._itemRefs[path] = response.url; @@ -546,7 +546,7 @@ return Promise.resolve(url); }, function (error) { - err.message = 'Sharing DropBox file or folder ("' + path + '") failed.' + err.message; + err.message = 'Sharing dropbox file or folder ("' + path + '") failed.' + err.message; return Promise.reject(error); }); }, @@ -554,7 +554,7 @@ /** * Method: info * - * Fetches the user's info from DropBox and returns a promise for it. + * Fetches the user's info from dropbox and returns a promise for it. * * Returns: * @@ -605,7 +605,7 @@ /** * Method: fetchDelta * - * Fetches the revision of all the files from DropBox API and puts them + * Fetches the revision of all the files from dropbox API and puts them * into _revCache. These values can then be used to determine if something * has changed. */ @@ -766,7 +766,7 @@ return Promise.reject(e); } - // Conflict happened. Delete the copy created by DropBox + // Conflict happened. Delete the copy created by dropbox if (response.path !== params.path) { var deleteUrl = 'https://api.dropbox.com/1/fileops/delete?root=auto&path=' + encodeURIComponent(response.path); self._request('POST', deleteUrl, {});
Fix Dropbox docs (refs #<I>) * Change wording from "API key" to "app key" * Use correct spelling in all places (it's not CamelCase)
remotestorage_remotestorage.js
train
08fb5f1c5f9e5435c87a76b86edd78269ec71d8a
diff --git a/resolwe/flow/managers/workload_connectors/kubernetes.py b/resolwe/flow/managers/workload_connectors/kubernetes.py index <HASH>..<HASH> 100644 --- a/resolwe/flow/managers/workload_connectors/kubernetes.py +++ b/resolwe/flow/managers/workload_connectors/kubernetes.py @@ -118,6 +118,58 @@ class Connector(BaseConnector): """Get unique EBS claim name.""" return f"{base_name}-{data_id}" + def _create_configmap_if_needed(self, name: str, content: Dict, core_api: Any): + """Create configmap if necessary.""" + try: + core_api.read_namespaced_config_map( + name=name, namespace=self.kubernetes_namespace + ) + except kubernetes.client.rest.ApiException: + # The configmap is not found, create one. + configmap_description = { + "apiVersion": "v1", + "kind": "ConfigMap", + "metadata": {"name": name}, + "data": content, + } + # The configmap might have already been created in the meantime. + with suppress(kubernetes.client.rest.ApiException): + core_api.create_namespaced_config_map( + body=configmap_description, + namespace=self.kubernetes_namespace, + _request_timeout=KUBERNETES_TIMEOUT, + ) + + def _get_tools_configmaps(self, core_api): + """Get and return configmaps for tools.""" + + def dict_from_directory(directory: Path) -> Dict[str, str]: + """Get dictionary from given directory. + + File names are keys and corresponding file contents are values. + """ + return { + entry.name: entry.read_text() + for entry in directory.glob("*") + if entry.is_file() + } + + configmap_names = [] + preparer = BaseFlowExecutorPreparer() + tools_paths = preparer.get_tools_paths() + for tool_path in tools_paths: + tool_path = Path(tool_path) + data = dict_from_directory(tool_path) + data_md5 = hashlib.md5( + json.dumps(data, sort_keys=True).encode() + ).hexdigest() + configmap_name = self._sanitize_kubernetes_label( + f"tools-{tool_path.name}-{data_md5}" + ) + self._create_configmap_if_needed(configmap_name, data, core_api) + configmap_names.append(configmap_name) + return configmap_names + def _get_files_configmap_name(self, location_subpath: Path, core_api: Any): """Get or create configmap for files. @@ -152,28 +204,7 @@ class Connector(BaseConnector): data_md5 = hashlib.md5(json.dumps(data, sort_keys=True).encode()).hexdigest() configmap_name = f"configmap-files-{data_md5}" - logger.debug(f"Files configmap: {configmap_name}") - - try: - core_api.read_namespaced_config_map( - name=configmap_name, namespace=self.kubernetes_namespace - ) - except kubernetes.client.rest.ApiException: - # The configmap is not found, create one. - configmap_description = { - "apiVersion": "v1", - "kind": "ConfigMap", - "metadata": {"name": configmap_name}, - "data": data, - } - # The configmap might have already been created in the meantime. - with suppress(kubernetes.client.rest.ApiException): - core_api.create_namespaced_config_map( - body=configmap_description, - namespace=self.kubernetes_namespace, - _request_timeout=KUBERNETES_TIMEOUT, - ) - + self._create_configmap_if_needed(configmap_name, data, core_api) return configmap_name def _get_mountable_connectors(self) -> Iterable[Tuple[str, BaseStorageConnector]]: @@ -219,9 +250,19 @@ class Connector(BaseConnector): {"name": "sockets-volume", "emptyDir": {}}, {"name": "secrets-volume", "emptyDir": {}}, ] + tools_configmaps = self._get_tools_configmaps(core_api) + for index, configmap_name in enumerate(tools_configmaps): + volumes.append( + { + "name": f"tools-{index}", + "configMap": {"name": configmap_name, "defaultMode": 0o755}, + } + ) + volumes += [ - volume_from_config(volume) - for volume in storage_settings.FLOW_VOLUMES.values() + volume_from_config(volume_name, volume_config) + for volume_name, volume_config in storage_settings.FLOW_VOLUMES.items() + if volume_config["config"]["name"] != "tools" ] volumes += [ { @@ -365,25 +406,13 @@ class Connector(BaseConnector): "readOnly": True, }, ] - - if "tools" in storage_settings.FLOW_VOLUMES: - # Create volumes for tools. In kubernetes all tools must be inside - # volume of type persistent_volume or host_path. - volume = storage_settings.FLOW_VOLUMES["tools"] - preparer = BaseFlowExecutorPreparer() - tools_paths = preparer.get_tools_paths() - base_tools_path = volume["config"]["path"] - subpath = volume["config"].get("subpath", "") - if subpath: - tools_paths = [f"{subpath}/{path}" for path in tools_paths] - mount_points += [ + for tool_index in range(len(BaseFlowExecutorPreparer().get_tools_paths())): + mount_points.append( { - "name": volume["config"]["name"], - "mountPath": os.fspath(Path("/usr/local/bin/resolwe") / str(index)), - "subPath": os.fspath(Path(tool).relative_to(base_tools_path)), + "name": f"tools-{tool_index}", + "mountPath": f"/usr/local/bin/resolwe/{tool_index}", } - for index, tool in enumerate(tools_paths) - ] + ) from resolwe.flow.managers import manager
Create configmap from tools and mount it inside processing container
genialis_resolwe
train
dac1467b23bbcb4399075b14d4882b8bc3f58abe
diff --git a/lib/capybara/node/actions.rb b/lib/capybara/node/actions.rb index <HASH>..<HASH> 100644 --- a/lib/capybara/node/actions.rb +++ b/lib/capybara/node/actions.rb @@ -230,7 +230,7 @@ module Capybara # @option options [String] id Match fields that match the id attribute # @option options [String] name Match fields that match the name attribute # @option options [String, Array<String>] :class Match links that match the class(es) provided - # @option options [Hash] style A Hash of CSS styles to change before attempting to attach the file (may not be supported by all driver) + # @option options [true, Hash] make_visible A Hash of CSS styles to change before attempting to attach the file, if `true` { opacity: 1, display: 'block', visibility: 'visible' } is used (may not be supported by all drivers) # # @return [Capybara::Node::Element] The file field element def attach_file(locator, path, options={}) @@ -239,11 +239,18 @@ module Capybara raise Capybara::FileNotFound, "cannot attach file, #{p} does not exist" unless File.exist?(p.to_s) end # Allow user to update the CSS style of the file input since they are so often hidden on a page - if style = options.delete(:style) + if style = options.delete(:make_visible) + style = { opacity: 1, display: 'block', visibility: 'visible' } if style == true ff = find(:file_field, locator, options.merge({visible: :all})) _update_style(ff, style) + if ff.visible? + ff.set(path) + else + raise ExpectationNotMet, "The style changes in :make_visible did not make the file input visible" + end + else + find(:file_field, locator, options).set(path) end - find(:file_field, locator, options).set(path) end private diff --git a/lib/capybara/spec/session/attach_file_spec.rb b/lib/capybara/spec/session/attach_file_spec.rb index <HASH>..<HASH> 100644 --- a/lib/capybara/spec/session/attach_file_spec.rb +++ b/lib/capybara/spec/session/attach_file_spec.rb @@ -108,11 +108,27 @@ Capybara::SpecHelper.spec "#attach_file" do end end - context "with :style option", requires: [:js, :es_args] do - it "can change the CSS style of the file input field" do + context "with :make_visible option", requires: [:js, :es_args] do + it "applies a default style change when true" do @session.visit('/with_js') expect { @session.attach_file("hidden_file", __FILE__) }.to raise_error Capybara::ElementNotFound - @session.attach_file("hidden_file", __FILE__, style: { opacity: 1, display: 'block' }) + expect { + @session.attach_file("hidden_file", __FILE__, make_visible: true) + }.not_to raise_error + end + + it "accepts a hash of styles to be applied" do + @session.visit('/with_js') + expect { + @session.attach_file("hidden_file", __FILE__, make_visible: { opacity: 1, display: 'block' }) + }.not_to raise_error + end + + it "raises an error when the file input is not made visible" do + @session.visit('/with_js') + expect { + @session.attach_file("hidden_file", __FILE__, make_visible: { color: 'red' }) + }.to raise_error(Capybara::ExpectationNotMet) end end end
Change :style option for attach_file to :make_visible
teamcapybara_capybara
train
0b788de07249fd2bb8c712d75dd1d82e9eeb2e65
diff --git a/src/adapters/pouch.idb.js b/src/adapters/pouch.idb.js index <HASH>..<HASH> 100644 --- a/src/adapters/pouch.idb.js +++ b/src/adapters/pouch.idb.js @@ -214,7 +214,7 @@ var IdbPouch = function(opts, callback) { return; } var metadata = result.metadata; - var rev = winningRev(metadata); + var rev = Pouch.merge.winningRev(metadata); aresults.push({ ok: true, @@ -411,7 +411,7 @@ var IdbPouch = function(opts, callback) { return; } - var rev = winningRev(metadata); + var rev = Pouch.merge.winningRev(metadata); var key = opts.rev ? opts.rev : rev; var index = txn.objectStore(BY_SEQ_STORE).index('_rev'); @@ -628,12 +628,12 @@ var IdbPouch = function(opts, callback) { id: metadata.id, key: metadata.id, value: { - rev: winningRev(metadata) + rev: Pouch.merge.winningRev(metadata) } }; if (opts.include_docs) { doc.doc = data; - doc.doc._rev = winningRev(metadata); + doc.doc._rev = Pouch.merge.winningRev(metadata); if (opts.conflicts) { doc.doc._conflicts = collectConflicts(metadata.rev_tree); } @@ -790,7 +790,7 @@ var IdbPouch = function(opts, callback) { return cursor['continue'](); } - var mainRev = winningRev(metadata); + var mainRev = Pouch.merge.winningRev(metadata); var index = txn.objectStore(BY_SEQ_STORE).index('_rev'); index.get(mainRev).onsuccess = function(docevent) { var doc = docevent.target.result; diff --git a/src/adapters/pouch.websql.js b/src/adapters/pouch.websql.js index <HASH>..<HASH> 100644 --- a/src/adapters/pouch.websql.js +++ b/src/adapters/pouch.websql.js @@ -154,7 +154,7 @@ var webSqlPouch = function(opts, callback) { return; } var metadata = result.metadata; - var rev = winningRev(metadata); + var rev = Pouch.merge.winningRev(metadata); aresults.push({ ok: true, @@ -231,7 +231,7 @@ var webSqlPouch = function(opts, callback) { var seq = docInfo.metadata.seq = result.insertId; delete docInfo.metadata.rev; - var mainRev = winningRev(docInfo.metadata); + var mainRev = Pouch.merge.winningRev(docInfo.metadata); var sql = isUpdate ? 'UPDATE ' + DOC_STORE + ' SET seq=?, json=?, winningseq=(SELECT seq FROM ' + BY_SEQ_STORE + ' WHERE rev=?) WHERE id=?' : @@ -421,7 +421,7 @@ var webSqlPouch = function(opts, callback) { return; } - var rev = winningRev(metadata); + var rev = Pouch.merge.winningRev(metadata); var key = opts.rev ? opts.rev : rev; var sql = 'SELECT * FROM ' + BY_SEQ_STORE + ' WHERE rev=?'; tx.executeSql(sql, [key], function(tx, results) { @@ -513,11 +513,11 @@ var webSqlPouch = function(opts, callback) { var doc = { id: metadata.id, key: metadata.id, - value: {rev: winningRev(metadata)} + value: {rev: Pouch.merge.winningRev(metadata)} }; if (opts.include_docs) { doc.doc = data; - doc.doc._rev = winningRev(metadata); + doc.doc._rev = Pouch.merge.winningRev(metadata); if (opts.conflicts) { doc.doc._conflicts = collectConflicts(metadata.rev_tree); } @@ -584,7 +584,7 @@ var webSqlPouch = function(opts, callback) { changes: collectLeaves(metadata.rev_tree), doc: JSON.parse(doc.data), }; - change.doc._rev = winningRev(metadata); + change.doc._rev = Pouch.merge.winningRev(metadata); if (isDeleted(metadata, change.doc._rev)) { change.deleted = true; } diff --git a/src/pouch.utils.js b/src/pouch.utils.js index <HASH>..<HASH> 100644 --- a/src/pouch.utils.js +++ b/src/pouch.utils.js @@ -45,7 +45,7 @@ var parseDocId = function(id) { var isDeleted = function(metadata, rev) { if (!metadata || !metadata.deletions) return false; if (!rev) { - rev = winningRev(metadata); + rev = Pouch.merge.winningRev(metadata); } if (rev.indexOf('-') >= 0) { rev = rev.split('-')[1]; @@ -269,7 +269,7 @@ var writeCheckpoint = function(src, target, opts, checkpoint, callback) { // tree (most edits) win // The final sort algorithm is slightly documented in a sidebar here: // http://guide.couchdb.org/draft/conflicts.html -var winningRev = function(metadata) { +Pouch.merge.winningRev = function(metadata) { var deletions = metadata.deletions || {}; var leafs = [];
winning rev is now Pouch.merge.winningRev
pouchdb_pouchdb
train
9c62ec842aacae93c3ae7374a9ba82c091f82d52
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -4,7 +4,7 @@ from setuptools import setup, find_packages setup( name="OLCTools", - version="0.5.3", + version="0.5.4", packages=find_packages(), include_package_data=True, author="Andrew Low", diff --git a/spadespipeline/reporter.py b/spadespipeline/reporter.py index <HASH>..<HASH> 100755 --- a/spadespipeline/reporter.py +++ b/spadespipeline/reporter.py @@ -161,10 +161,10 @@ class Reporter(object): # AMR_Profile and resistant/sensitive status if sample.resfinder_assembled.pipelineresults: # Profile - # data += ';'.join(sorted(sample.resfinder_assembled.pipelineresults)) + ',' for resistance, resistance_set in sample.resfinder_assembled.pipelineresults.items(): - data += '{res}{r_set};'.format(res=resistance, - r_set=';'.join(sorted(list(resistance_set)))) + data += '{res}({r_set});'.format(res=resistance, + r_set=';'.join(sorted(list(resistance_set)))) + data += ',' # Resistant/Sensitive data += 'Resistant,' else: @@ -173,13 +173,12 @@ class Reporter(object): # Resistant/Sensitive data += 'Sensitive,' # Plasmid Result' - try: - plasmid_profile = sorted(sample.plasmidextractor.plasmids) - if plasmid_profile: - data += ';'.join(plasmid_profile) + ',' - else: - data += 'ND,' - except AttributeError: + if sample.mobrecon.pipelineresults: + for plasmid, details in sorted(sample.mobrecon.pipelineresults.items()): + data += '{plasmid}({details});'.format(plasmid=plasmid, + details=details) + data += ',' + else: data += 'ND,' # TotalPredictedGenes data += GenObject.returnattr(sample.prodigal, 'predictedgenestotal')
Added MOB-recon, and modified resfinder outputs
lowandrew_OLCTools
train
6102bfbbb169dca1e25ded4d6dba8a8f56868e50
diff --git a/src/OkulBilisim/OjsImportBundle/Entity/PendingStatisticImportRepository.php b/src/OkulBilisim/OjsImportBundle/Entity/PendingStatisticImportRepository.php index <HASH>..<HASH> 100644 --- a/src/OkulBilisim/OjsImportBundle/Entity/PendingStatisticImportRepository.php +++ b/src/OkulBilisim/OjsImportBundle/Entity/PendingStatisticImportRepository.php @@ -2,12 +2,14 @@ namespace OkulBilisim\OjsImportBundle\Entity; +use Doctrine\ORM\EntityRepository; + /** * PendingStatisticImportRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ -class PendingStatisticImportRepository extends \Doctrine\ORM\EntityRepository +class PendingStatisticImportRepository extends EntityRepository { } diff --git a/src/OkulBilisim/OjsImportBundle/Importer/PKP/ArticleImporter.php b/src/OkulBilisim/OjsImportBundle/Importer/PKP/ArticleImporter.php index <HASH>..<HASH> 100644 --- a/src/OkulBilisim/OjsImportBundle/Importer/PKP/ArticleImporter.php +++ b/src/OkulBilisim/OjsImportBundle/Importer/PKP/ArticleImporter.php @@ -5,8 +5,6 @@ namespace OkulBilisim\OjsImportBundle\Importer\PKP; use DateTime; use Doctrine\DBAL\Connection; use Doctrine\ORM\EntityManager; -use Ojs\AnalyticsBundle\Entity\ArticleFileStatistic; -use Ojs\AnalyticsBundle\Entity\ArticleStatistic; use Ojs\JournalBundle\Entity\Article; use Ojs\JournalBundle\Entity\ArticleAuthor; use Ojs\JournalBundle\Entity\Author; diff --git a/src/OkulBilisim/OjsImportBundle/Importer/PKP/SectionImporter.php b/src/OkulBilisim/OjsImportBundle/Importer/PKP/SectionImporter.php index <HASH>..<HASH> 100644 --- a/src/OkulBilisim/OjsImportBundle/Importer/PKP/SectionImporter.php +++ b/src/OkulBilisim/OjsImportBundle/Importer/PKP/SectionImporter.php @@ -2,7 +2,6 @@ namespace OkulBilisim\OjsImportBundle\Importer\PKP; -use DateTime; use Ojs\JournalBundle\Entity\Section; use Ojs\JournalBundle\Entity\SectionTranslation; use Ojs\JournalBundle\Entity\Journal;
Remove unused imports and don't use unnecessary fully qualified names
academic_VipaImportBundle
train
b69027b6860c7bdc3c8f2e701634004e8c00f55d
diff --git a/lib/classes/Utils.js b/lib/classes/Utils.js index <HASH>..<HASH> 100644 --- a/lib/classes/Utils.js +++ b/lib/classes/Utils.js @@ -249,7 +249,7 @@ class Utils { }, }; - fetch('https://api.segment.io/v1/track', { + return fetch('https://api.segment.io/v1/track', { headers: { Authorization: `Basic ${new Buffer(auth).toString('base64')}`, 'content-type': 'application/json', diff --git a/tests/classes/Utils.js b/tests/classes/Utils.js index <HASH>..<HASH> 100644 --- a/tests/classes/Utils.js +++ b/tests/classes/Utils.js @@ -3,6 +3,8 @@ const path = require('path'); const os = require('os'); const expect = require('chai').expect; +const fse = require('fs-extra'); +const fs = require('fs'); const Serverless = require('../../lib/Serverless'); const testUtils = require('../../tests/utils'); @@ -215,5 +217,40 @@ describe('Utils', () => { process.chdir(testDir); }); }); + + describe('#track()', () => { + let serverlessPath; + + beforeEach(() => { + serverless.init(); + + const tmpDirPath = testUtils.getTmpDirPath(); + fse.mkdirsSync(tmpDirPath); + + serverlessPath = tmpDirPath; + serverless.config.serverlessPath = tmpDirPath; + }); + + it('should create a new file with a tracking id if not found', () => { + const trackingIdFilePath = path.join(serverlessPath, 'tracking-id'); + + return serverless.utils.track(serverless).then(() => { + expect(fs.readFileSync(trackingIdFilePath).toString().length).to.be.above(1); + }); + }); + + it('should re-use an existing file which contains the tracking id if found', () => { + const trackingIdFilePath = path.join(serverlessPath, 'tracking-id'); + const trackingId = 'some-tracking-id'; + + // create a new file with a tracking id + fse.ensureFileSync(trackingIdFilePath); + fs.writeFileSync(trackingIdFilePath, trackingId); + + return serverless.utils.track(serverless).then(() => { + expect(fs.readFileSync(trackingIdFilePath).toString()).to.be.equal(trackingId); + }); + }); + }); });
Add tests for tracking functionality which check the existence of the trackingId
serverless_serverless
train
952871f0eab3d6a9ef2cdac96916def177246644
diff --git a/pyprel.py b/pyprel.py index <HASH>..<HASH> 100644 --- a/pyprel.py +++ b/pyprel.py @@ -39,7 +39,7 @@ #from __future__ import division name = "pyprel" -version = "2016-07-12T1553Z" +version = "2017-01-16T1611Z" import shijian import subprocess diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -2,18 +2,19 @@ # -*- coding: utf-8 -*- import os + import setuptools def main(): setuptools.setup( name = "pyprel", - version = "2016.07.12.1553", + version = "2017.01.16.1611", description = "Python print elegant", - long_description = Markdown_to_reStructuredText("README.md"), + long_description = long_description(), url = "https://github.com/wdbm/pyprel", author = "Will Breaden Madden", - author_email = "[email protected]", + author_email = "[email protected]", license = "GPLv3", py_modules = [ "pyprel" @@ -28,17 +29,19 @@ def main(): """ ) -def read(*paths): - with open(os.path.join(*paths), "r") as filename: - return filename.read() +def long_description( + filename = "README.md" + ): -def Markdown_to_reStructuredText(filename): - try: - import pypandoc - return pypandoc.convert(filename, "rst") - except: - print("pypandoc not found; long description could be corrupted") - return read(filename) + if os.path.isfile(os.path.expandvars(filename)): + try: + import pypandoc + long_description = pypandoc.convert_file(filename, "rst") + except ImportError: + long_description = open(filename).read() + else: + long_description = "" + return long_description if __name__ == "__main__": main()
change e-mail, add file existence check to setup.py, add long_description function to setup.py
wdbm_pyprel
train
07731611462a845516186452b202597f9f0b54c8
diff --git a/doc/sphinxext/ipython_directive.py b/doc/sphinxext/ipython_directive.py index <HASH>..<HASH> 100644 --- a/doc/sphinxext/ipython_directive.py +++ b/doc/sphinxext/ipython_directive.py @@ -344,7 +344,11 @@ class EmbeddedSphinxShell(object): splitter.push(line) more = splitter.push_accepts_more() if not more: - source_raw = splitter.source_raw_reset()[1] + try: + source_raw = splitter.source_raw_reset()[1] + except: + # recent ipython #4504 + source_raw = splitter.raw_reset() self.IP.run_cell(source_raw, store_history=store_history) finally: sys.stdout = stdout
BLD/DOC: fix ipython_directive to workaround ipython/<I>
pandas-dev_pandas
train
2155b46915a4df821405d26f576d9fae9fa5178e
diff --git a/cli/command/container/stop.go b/cli/command/container/stop.go index <HASH>..<HASH> 100644 --- a/cli/command/container/stop.go +++ b/cli/command/container/stop.go @@ -39,11 +39,15 @@ func NewStopCommand(dockerCli *command.DockerCli) *cobra.Command { func runStop(dockerCli *command.DockerCli, opts *stopOptions) error { ctx := context.Background() + timeout := time.Duration(opts.time) * time.Second var errs []string + + errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, id string) error { + return dockerCli.Client().ContainerStop(ctx, id, &timeout) + }) for _, container := range opts.containers { - timeout := time.Duration(opts.time) * time.Second - if err := dockerCli.Client().ContainerStop(ctx, container, &timeout); err != nil { + if err := <-errChan; err != nil { errs = append(errs, err.Error()) } else { fmt.Fprintf(dockerCli.Out(), "%s\n", container) diff --git a/cli/command/container/utils.go b/cli/command/container/utils.go index <HASH>..<HASH> 100644 --- a/cli/command/container/utils.go +++ b/cli/command/container/utils.go @@ -90,3 +90,35 @@ func getExitCode(dockerCli *command.DockerCli, ctx context.Context, containerID } return c.State.Running, c.State.ExitCode, nil } + +func parallelOperation(ctx context.Context, cids []string, op func(ctx context.Context, id string) error) chan error { + if len(cids) == 0 { + return nil + } + const defaultParallel int = 50 + sem := make(chan struct{}, defaultParallel) + errChan := make(chan error) + + // make sure result is printed in correct order + output := map[string]chan error{} + for _, c := range cids { + output[c] = make(chan error, 1) + } + go func() { + for _, c := range cids { + err := <-output[c] + errChan <- err + } + }() + + go func() { + for _, c := range cids { + sem <- struct{}{} // Wait for active queue sem to drain. + go func(container string) { + output[container] <- op(ctx, container) + <-sem + }(c) + } + }() + return errChan +}
Enhancement: allow parallel stop Stop multiple containers in parallel to speed up stop process, allow maximum <I> parallel stops.
moby_moby
train
ea0005add45af3be575676cfc9261701eb2cb611
diff --git a/src/Notification/Notification.php b/src/Notification/Notification.php index <HASH>..<HASH> 100644 --- a/src/Notification/Notification.php +++ b/src/Notification/Notification.php @@ -35,10 +35,11 @@ class Notification * * @param $message * @param null $format + * @return NotificationBag */ public function success($message, $format = null) { - $this->addMessage(null, 'success', $message, true, $format); + return $this->addMessage(null, 'success', $message, true, $format); } /** @@ -46,10 +47,11 @@ class Notification * * @param $message * @param null $format + * @return NotificationBag */ public function successInstant($message, $format = null) { - $this->addMessage(null, 'success', $message, false, $format); + return $this->addMessage(null, 'success', $message, false, $format); } /** @@ -57,10 +59,11 @@ class Notification * * @param $message * @param null $format + * @return NotificationBag */ public function error($message, $format = null) { - $this->addMessage(null, 'error', $message, true, $format); + return $this->addMessage(null, 'error', $message, true, $format); } /** @@ -68,10 +71,11 @@ class Notification * * @param $message * @param null $format + * @return NotificationBag */ public function errorInstant($message, $format = null) { - $this->addMessage(null, 'error', $message, false, $format); + return $this->addMessage(null, 'error', $message, false, $format); } /** @@ -79,10 +83,11 @@ class Notification * * @param $message * @param null $format + * @return NotificationBag */ public function warning($message, $format = null) { - $this->addMessage(null, 'warning', $message, true, $format); + return $this->addMessage(null, 'warning', $message, true, $format); } /** @@ -90,10 +95,11 @@ class Notification * * @param $message * @param null $format + * @return NotificationBag */ public function warningInstant($message, $format = null) { - $this->addMessage(null, 'warning', $message, false, $format); + return $this->addMessage(null, 'warning', $message, false, $format); } /** @@ -101,10 +107,11 @@ class Notification * * @param $message * @param null $format + * @return NotificationBag */ public function info($message, $format = null) { - $this->addMessage(null, 'info', $message, true, $format); + return $this->addMessage(null, 'info', $message, true, $format); } /** @@ -112,10 +119,11 @@ class Notification * * @param $message * @param null $format + * @return NotificationBag */ public function infoInstant($message, $format = null) { - $this->addMessage(null, 'info', $message, false, $format); + return $this->addMessage(null, 'info', $message, false, $format); } /** @@ -140,7 +148,7 @@ class Notification */ protected function addMessage($container, $type, $message, $flash = true, $format = null) { - $this->container($container)->add($type, $message, $flash, $format); + return $this->container($container)->add($type, $message, $flash, $format); } /**
Added return statement for adding messages, now able to chain methods without using Notification::container()
edvinaskrucas_notification
train
8b2e2d032e9c68a683095a071d9c807560af7d2b
diff --git a/Specification/TextSearchQuery.php b/Specification/TextSearchQuery.php index <HASH>..<HASH> 100644 --- a/Specification/TextSearchQuery.php +++ b/Specification/TextSearchQuery.php @@ -6,9 +6,6 @@ use Happyr\DoctrineSpecification\Filter\Filter; class TextSearchQuery extends TextSearchSpecification implements Filter { - /** @var bool */ - private static $searchConfigurationSetUp = false; - /** @var string */ private $searchTerm; @@ -35,10 +32,6 @@ class TextSearchQuery extends TextSearchSpecification implements Filter */ public function getFilter(QueryBuilder $queryBuilder, $dqlAlias): string { - if (!self::$searchConfigurationSetUp) { - $this->setUpSearchConfiguration($queryBuilder); - } - $queryBuilder->setParameter('_searchQuery', $this->processSearchTerm($this->searchTerm)); return sprintf( @@ -47,19 +40,4 @@ class TextSearchQuery extends TextSearchSpecification implements Filter $this->searchDocumentField ); } - - /** - * @param QueryBuilder $queryBuilder - */ - private function setUpSearchConfiguration(QueryBuilder $queryBuilder) - { - /*$db = $queryBuilder->getEntityManager()->getConnection(); - if (!$db->fetchColumn("SELECT true FROM pg_ts_dict WHERE dictname = 'cs'")) { - $db->query('CREATE TEXT SEARCH DICTIONARY cs (template=ispell, dictfile = czech, afffile=czech, stopwords=czech)'); - $db->query('CREATE TEXT SEARCH CONFIGURATION ru (copy=english)'); - $db->query('ALTER TEXT SEARCH CONFIGURATION ru ALTER MAPPING FOR word, asciiword WITH cs, simple'); - }*/ - - self::$searchConfigurationSetUp = true; - } }
Removed text search configuration setup from TextSearchQuery
vaniocz_vanio-domain-bundle
train
f2642a70db1202e35c85f464956e347201b06362
diff --git a/htlcswitch/link.go b/htlcswitch/link.go index <HASH>..<HASH> 100644 --- a/htlcswitch/link.go +++ b/htlcswitch/link.go @@ -120,6 +120,11 @@ type ChannelLinkConfig struct { // in thread-safe manner. Registry InvoiceDatabase + // PreimageCache is a global witness baacon that houses any new + // preimges discovered by other links. We'll use this to add new + // witnesses that we discover which will notify any sub-systems + // subscribed to new events. + PreimageCache contractcourt.WitnessBeacon // FeeEstimator is an instance of a live fee estimator which will be // used to dynamically regulate the current fee of the commitment // transaction to ensure timely confirmation. @@ -840,8 +845,15 @@ func (l *channelLink) handleUpstreamMsg(msg lnwire.Message) { return } - // TODO(roasbeef): add preimage to DB in order to swipe - // repeated r-values + // TODO(roasbeef): pipeline to switch + + // As we've learned of a new preimage for the first time, we'll + // add it to to our preimage cache. By doing this, we ensure + // any contested contracts watched by any on-chain arbitrators + // can now sweep this HTLC on-chain. + if err := l.cfg.PreimageCache.AddPreimage(pre[:]); err != nil { + log.Errorf("unable to add preimage=%x to cache", pre[:]) + } case *lnwire.UpdateFailMalformedHTLC: // Convert the failure type encoded within the HTLC fail @@ -918,7 +930,7 @@ func (l *channelLink) handleUpstreamMsg(msg lnwire.Message) { // As we've just just accepted a new state, we'll now // immediately send the remote peer a revocation for our prior // state. - nextRevocation, err := l.channel.RevokeCurrentCommitment() + nextRevocation, currentHtlcs, err := l.channel.RevokeCurrentCommitment() if err != nil { log.Errorf("unable to revoke commitment: %v", err) return @@ -1478,7 +1490,7 @@ func (l *channelLink) processLockedInHtlcs( // we'll cancel the HTLC directly. if pd.Amount < l.cfg.FwrdingPolicy.MinHTLC { log.Errorf("Incoming htlc(%x) is too "+ - "small: min_htlc=%v, hltc_value=%v", + "small: min_htlc=%v, htlc_value=%v", pd.RHash[:], l.cfg.FwrdingPolicy.MinHTLC, pd.Amount)
htlcswitch: once we discover a pre-image, add it to the witness cache In this commit, we add some additional logic to the case when we receive a pre-image from an upstream peer. We’ll immediately add it to the witness cache, as an incoming HTLC might be waiting on-chain to fully resolve the HTLC with knowledge of the newly discovered pre-image.
lightningnetwork_lnd
train
fe5b0f158ebe0b721d39e72bb282216cbff5aca7
diff --git a/lib/stealth/server.rb b/lib/stealth/server.rb index <HASH>..<HASH> 100644 --- a/lib/stealth/server.rb +++ b/lib/stealth/server.rb @@ -41,7 +41,7 @@ module Stealth dispatcher = Stealth::Dispatcher.new( service: params[:service], params: params, - headers: request.env + headers: get_helpers_from_request(request) ) dispatcher.coordinate @@ -49,5 +49,13 @@ module Stealth status 202 end + private + + def get_helpers_from_request(request) + request.env.reject do |header, value| + header.match(/rack\.|puma\.|sinatra\./) + end + end + end end
Drop infrastructure specific headers These are fairly large and unneccessary at the service level.
hellostealth_stealth
train
0c61265f93d7f3fb0bcd68887dd9fdf33f8a2b5b
diff --git a/core/lib/comable/deprecator.rb b/core/lib/comable/deprecator.rb index <HASH>..<HASH> 100644 --- a/core/lib/comable/deprecator.rb +++ b/core/lib/comable/deprecator.rb @@ -1,7 +1,26 @@ -module Comable - class Deprecator < ActiveSupport::Deprecation - def initialize(deprecation_horizon = '0.4.0', gem_name = 'Comable') - super +if Rails::VERSION::MAJOR > 3 + module Comable + class Deprecator < ActiveSupport::Deprecation + def initialize(deprecation_horizon = '0.4.0', gem_name = 'Comable') + super + end end end +else + # TODO: Deprecated itself! + module Comable + class Deprecator + include Singleton + end + end + + class Module + def deprecate_with_deprecator(*method_names) + options = method_names.extract_options! + options.delete(:deprecator) if options.present? + deprecate_without_deprecator + end + + alias_method_chain :deprecate, :deprecator + end end
Rails <I>: Fix tests to work
appirits_comable
train
677a4654786c29f49bf2964142d4e458e278e25a
diff --git a/test/integration/test-pool.js b/test/integration/test-pool.js index <HASH>..<HASH> 100644 --- a/test/integration/test-pool.js +++ b/test/integration/test-pool.js @@ -253,7 +253,7 @@ describe('Pool', () => { }); }); - it('create pool', function (done) { + it('create pool', async function () { if ( process.env.srv === 'maxscale' || process.env.srv === 'skysql' || @@ -263,26 +263,15 @@ describe('Pool', () => { this.timeout(5000); const pool = base.createPool({ connectionLimit: 1 }); const initTime = Date.now(); - pool.getConnection().then((conn) => { - conn.query('SELECT SLEEP(1)').then(() => { - conn.release(); - }); - }); - pool.getConnection().then((conn) => { - conn - .query('SELECT SLEEP(1)') - .then(() => { - assert( - Date.now() - initTime >= 1999, - 'expected > 2s, but was ' + (Date.now() - initTime) - ); - conn.release(); - return pool.end(); - }) - .then(() => { - done(); - }); - }); + let conn = await pool.getConnection(); + await conn.query('SELECT SLEEP(1)'); + conn.release(); + + await pool.getConnection(); + await conn.query('SELECT SLEEP(1)'); + assert(Date.now() - initTime >= 1999, 'expected > 2s, but was ' + (Date.now() - initTime)); + conn.release(); + await pool.end(); }); it('create pool with multipleStatement', function (done) {
[misc] pool test rewrite as promise
MariaDB_mariadb-connector-nodejs
train
1d0a79962c86d7441e51f244ca1b259bcaff2a34
diff --git a/index.php b/index.php index <HASH>..<HASH> 100644 --- a/index.php +++ b/index.php @@ -190,7 +190,7 @@ respond( function( $request, $response, $app, $matches ) { dispatch( substr( $_SERVER['REQUEST_URI'], - ( strlen( $config['app-meta']['base_url'] ) - 1 ) // Remove the starting slash + strlen( rtrim( $config['app-meta']['base_url'], '/' ) ) // Remove a potential trailing slash ) );
More efficient and more compatibile way of dispatching the PATH INFO to klein
Rican7_Paulus
train
a7de635e5091ff6a0f8141e22d05827117475938
diff --git a/cptv/bitstream.py b/cptv/bitstream.py index <HASH>..<HASH> 100644 --- a/cptv/bitstream.py +++ b/cptv/bitstream.py @@ -39,6 +39,9 @@ class BitStream: def uint64(self): return struct.unpack("<Q", self.bytes(8))[0] + + def int32(self): + return struct.unpack("<l", self.bytes(4))[0] def iter_int(self, total_size, bitw): """Return an iterator which processes the the next total_size diff --git a/cptv/reader.py b/cptv/reader.py index <HASH>..<HASH> 100644 --- a/cptv/reader.py +++ b/cptv/reader.py @@ -118,7 +118,7 @@ class CPTVReader: if section_type != Section.FRAME: raise IOError("unexpected section: {}".format(section_type)) - v = self.s.uint32() # read starting value + v = self.s.int32() # read starting value delta_frame[0][0] = v # ... then apply deltas
Fixed overflow reading first value of a frame.
TheCacophonyProject_python-cptv
train
82c21a2c28eeb0b7b99efd0b9db8bd191a96f880
diff --git a/vext/__init__.py b/vext/__init__.py index <HASH>..<HASH> 100644 --- a/vext/__init__.py +++ b/vext/__init__.py @@ -289,11 +289,13 @@ def open_spec(f): keys = ['modules', 'pths', 'test_import'] data = yaml.load(f) parsed = dict() + ## pattern = re.compile("^\s+|\s*,\s*|\s+$") for k in keys: v = data.get(k, []) # Items are always lists if isinstance(v, basestring): - parsed[k] = re.split(r",| ", v) + parsed[k] = [ m for m in re.split(r",| ", v) ] + #parsed[k] = re.split(pattern, v) else: parsed[k] = v @@ -305,6 +307,8 @@ def test_imports(modules, py=None): """ # TODO - allow passing different python to run remotely for module in modules: + if not module: + continue # TODO - removeme once spec loading is fixed try: __import__(module) yield True, module diff --git a/vext/cmdline/__init__.py b/vext/cmdline/__init__.py index <HASH>..<HASH> 100644 --- a/vext/cmdline/__init__.py +++ b/vext/cmdline/__init__.py @@ -91,16 +91,26 @@ def status(): else: print('Not running in virtualenv [%s]' % enabled_msg) -def check(vextfile): +def check(vextname): + """ + Attempt to import everything in the 'test-imports' section of + the vext file + + :param vextfile: Which vext to check, '*' to check all + """ import vext # not efficient ... but then there shouldn't be many of these for fn in vext.spec_files(): - if os.path.splitext(os.path.basename(fn))[0] == vextfile: + if vextname == '*' or os.path.splitext(os.path.basename(fn))[0] == vextname: + print(os.path.basename(fn)) f = vext.open_spec(open(fn)) modules = f.get('test_import', []) for success, module in vext.test_imports(modules): - print(module + ' OK' if success else module + ' FAIL') - break + line = "import %s: %s" % (module, '[success]' if success else '[failed]') + print(line) + print('') + if vextname != '*': + break def main(): import argparse
Some work on 'check' option to test imports
stuaxo_vext
train
1718963c7b06a4bc97bff104b6f6fa12a62afe56
diff --git a/salt/utils/cloud.py b/salt/utils/cloud.py index <HASH>..<HASH> 100644 --- a/salt/utils/cloud.py +++ b/salt/utils/cloud.py @@ -1197,6 +1197,13 @@ def deploy_script(host, if remote_dir not in remote_dirs: root_cmd('mkdir -p \'{0}\''.format(remote_dir), tty, sudo, **ssh_kwargs) + if ssh_kwargs['username'] != 'root': + root_cmd( + 'chown {0} \'{1}\''.format( + ssh_kwargs['username'], remote_dir + ), + tty, sudo, **ssh_kwargs + ) remote_dirs.append(remote_dir) sftp_file( remote_file, kwargs=ssh_kwargs, local_file=local_file
file_map: chmod created directories if not root
saltstack_salt
train
af0071403cb348c3dd5c253457078806303efec4
diff --git a/docker/api/service.py b/docker/api/service.py index <HASH>..<HASH> 100644 --- a/docker/api/service.py +++ b/docker/api/service.py @@ -136,12 +136,14 @@ class ServiceApiMixin(object): @utils.minimum_version('1.24') @utils.check_resource('service') - def inspect_service(self, service): + def inspect_service(self, service, insert_defaults=None): """ Return information about a service. Args: - service (str): Service name or ID + service (str): Service name or ID. + insert_defaults (boolean): If true, default values will be merged + into the service inspect output. Returns: ``True`` if successful. @@ -151,7 +153,15 @@ class ServiceApiMixin(object): If the server returns an error. """ url = self._url('/services/{0}', service) - return self._result(self._get(url), True) + params = {} + if insert_defaults is not None: + if utils.version_lt(self._version, '1.29'): + raise errors.InvalidVersion( + 'insert_defaults is not supported in API version < 1.29' + ) + params['insertDefaults'] = insert_defaults + + return self._result(self._get(url, params=params), True) @utils.minimum_version('1.24') @utils.check_resource('task') diff --git a/docker/models/services.py b/docker/models/services.py index <HASH>..<HASH> 100644 --- a/docker/models/services.py +++ b/docker/models/services.py @@ -177,12 +177,14 @@ class ServiceCollection(Collection): service_id = self.client.api.create_service(**create_kwargs) return self.get(service_id) - def get(self, service_id): + def get(self, service_id, insert_defaults=None): """ Get a service. Args: service_id (str): The ID of the service. + insert_defaults (boolean): If true, default values will be merged + into the output. Returns: (:py:class:`Service`): The service. @@ -192,8 +194,13 @@ class ServiceCollection(Collection): If the service does not exist. :py:class:`docker.errors.APIError` If the server returns an error. + :py:class:`docker.errors.InvalidVersion` + If one of the arguments is not supported with the current + API version. """ - return self.prepare_model(self.client.api.inspect_service(service_id)) + return self.prepare_model( + self.client.api.inspect_service(service_id, insert_defaults) + ) def list(self, **kwargs): """ diff --git a/tests/integration/api_service_test.py b/tests/integration/api_service_test.py index <HASH>..<HASH> 100644 --- a/tests/integration/api_service_test.py +++ b/tests/integration/api_service_test.py @@ -99,6 +99,17 @@ class ServiceTest(BaseAPIIntegrationTest): assert 'ID' in svc_info assert svc_info['ID'] == svc_id['ID'] + @requires_api_version('1.29') + def test_inspect_service_insert_defaults(self): + svc_name, svc_id = self.create_simple_service() + svc_info = self.client.inspect_service(svc_id) + svc_info_defaults = self.client.inspect_service( + svc_id, insert_defaults=True + ) + assert svc_info != svc_info_defaults + assert 'RollbackConfig' in svc_info_defaults['Spec'] + assert 'RollbackConfig' not in svc_info['Spec'] + def test_remove_service_by_id(self): svc_name, svc_id = self.create_simple_service() assert self.client.remove_service(svc_id)
Add support for insert_defaults in inspect_service
docker_docker-py
train
6579cd8e9e4b104950655f2502222450cc542d0b
diff --git a/test/e2e/scheduling/ubernetes_lite.go b/test/e2e/scheduling/ubernetes_lite.go index <HASH>..<HASH> 100644 --- a/test/e2e/scheduling/ubernetes_lite.go +++ b/test/e2e/scheduling/ubernetes_lite.go @@ -20,6 +20,7 @@ import ( "context" "fmt" "math" + "time" "github.com/onsi/ginkgo" "github.com/onsi/gomega" @@ -42,6 +43,7 @@ var _ = SIGDescribe("Multi-AZ Clusters", func() { f := framework.NewDefaultFramework("multi-az") var zoneCount int var err error + var cleanUp func() ginkgo.BeforeEach(func() { e2eskipper.SkipUnlessProviderIs("gce", "gke", "aws") if zoneCount <= 0 { @@ -52,6 +54,20 @@ var _ = SIGDescribe("Multi-AZ Clusters", func() { msg := fmt.Sprintf("Zone count is %d, only run for multi-zone clusters, skipping test", zoneCount) e2eskipper.SkipUnlessAtLeast(zoneCount, 2, msg) // TODO: SkipUnlessDefaultScheduler() // Non-default schedulers might not spread + + cs := f.ClientSet + e2enode.WaitForTotalHealthy(cs, time.Minute) + nodeList, err := e2enode.GetReadySchedulableNodes(cs) + framework.ExpectNoError(err) + + // make the nodes have balanced cpu,mem usage + cleanUp, err = createBalancedPodForNodes(f, cs, f.Namespace.Name, nodeList.Items, podRequestedResource, 0.0) + framework.ExpectNoError(err) + }) + ginkgo.AfterEach(func() { + if cleanUp != nil { + cleanUp() + } }) ginkgo.It("should spread the pods of a service across zones", func() { SpreadServiceOrFail(f, 5*zoneCount, imageutils.GetPauseImageName())
Balance nodes in scheduling e2e This adds a call to createBalancedPods during the ubernetes_lite scheduling e2es, which are prone to improper score balancing due to unbalanced utilization.
kubernetes_kubernetes
train
bd75a41f9b813850f748e928a7f528abb38a9dcb
diff --git a/code/cms/DMSGridFieldDeleteAction.php b/code/cms/DMSGridFieldDeleteAction.php index <HASH>..<HASH> 100644 --- a/code/cms/DMSGridFieldDeleteAction.php +++ b/code/cms/DMSGridFieldDeleteAction.php @@ -47,7 +47,7 @@ class DMSGridFieldDeleteAction extends GridFieldDeleteAction implements GridFiel //set a class telling JS what kind of warning to display when clicking the delete button if ($numberOfRelations > 1) $field->addExtraClass('dms-delete-link-only'); - else $field->addExtraClasS('dms-delete-last-warning'); + else $field->addExtraClass('dms-delete-last-warning'); //set a class to show if the document is hidden if ($record->isHidden()) { diff --git a/code/cms/DMSGridFieldDetailForm.php b/code/cms/DMSGridFieldDetailForm.php index <HASH>..<HASH> 100644 --- a/code/cms/DMSGridFieldDetailForm.php +++ b/code/cms/DMSGridFieldDetailForm.php @@ -11,10 +11,13 @@ class DMSGridFieldDetailForm_ItemRequest extends GridFieldDetailForm_ItemRequest //add a data attribute specifying how many pages this document is referenced on if ($record = $this->record) { - $numberOfRelations = $record->Pages()->Count(); + $numberOfPageRelations = $record->Pages()->Count(); + $relations = new ShortCodeRelationFinder(); + $numberOfInlineRelations = $relations->findPageCount($record->ID); //add the number of pages attached to this field as a data-attribute - $form->setAttribute('data-pages-count', $numberOfRelations); + $form->setAttribute('data-pages-count', $numberOfPageRelations); + $form->setAttribute('data-relation-count', $numberOfInlineRelations); } return $form; } diff --git a/code/tools/ShortCodeRelationFinder.php b/code/tools/ShortCodeRelationFinder.php index <HASH>..<HASH> 100644 --- a/code/tools/ShortCodeRelationFinder.php +++ b/code/tools/ShortCodeRelationFinder.php @@ -30,6 +30,11 @@ class ShortCodeRelationFinder { return $found; } + function findPageCount($number) { + $list = $this->getList($number); + return $list->count(); + } + /** * @return DataList */ diff --git a/javascript/DMSDocumentCMSFields.js b/javascript/DMSDocumentCMSFields.js index <HASH>..<HASH> 100644 --- a/javascript/DMSDocumentCMSFields.js +++ b/javascript/DMSDocumentCMSFields.js @@ -114,11 +114,27 @@ //work out how many pages are left attached to this document var form = this.closest('form'); var pagesCount = form.data('pages-count'); + var relationCount = form.data('relation-count'); //display an appropriate message var message = ''; - if (pagesCount > 1) { - message = "Permanently delete this document and remove it from all pages where it is referenced?\n\nWarning: this document is attached to a total of "+pagesCount+" pages. Deleting it here will permanently delete it from this page and all other pages where it is referenced."; + if (pagesCount > 1 || relationCount > 0) { + var pages = ''; + if (pagesCount > 1) { + pages = "\nWarning: doc is attached to a total of "+pagesCount+" pages. "; + } + var references = ''; + var referencesWarning = ''; + if (relationCount > 0) { + var pname = 'pages'; + referencesWarning = "\n\nBefore deleting: please update the content on the pages where this document is referenced, otherwise the links on those pages will break."; + if (relationCount === 1) { + pname = 'page'; + referencesWarning = "\n\nBefore deleting: please update the content on the page where this document is referenced, otherwise the links on that page will break."; + } + references = "\nWarning: doc is referenced in the text of "+relationCount +" "+pname+"."; + } + message = "Permanently delete this document and remove it from all pages where it is referenced?\n"+pages+references+"\n\nDeleting it here will permanently delete it from this page and all other pages where it is referenced."+referencesWarning; } else { message = "Permanently delete this document and remove it from this page?\n\nNotice: this document is only attached to this page, so deleting it won't affect any other pages."; }
ENHANCEMENT: warning when deleting a document that is referenced on other pages
silverstripe_silverstripe-dms
train
661b6e7692f6fb28dff7eb5bc853076b6014b38b
diff --git a/Manager/ApiManager.php b/Manager/ApiManager.php index <HASH>..<HASH> 100644 --- a/Manager/ApiManager.php +++ b/Manager/ApiManager.php @@ -25,25 +25,34 @@ class ApiManager private $questionRepo; private $interactionQcmRepo; private $handlerCollector; + private $exerciseManager; /** * @DI\InjectParams({ * "om" = @DI\Inject("claroline.persistence.object_manager"), * "validator" = @DI\Inject("ujm.exo.json_validator"), - * "collector" = @DI\Inject("ujm.exo.question_handler_collector") + * "collector" = @DI\Inject("ujm.exo.question_handler_collector"), + * "manager" = @DI\Inject("ujm.exo.exercise_manager") * }) * * @param ObjectManager $om * @param Validator $validator * @param QuestionHandlerCollector $collector + * @param ExerciseManager $manager */ - public function __construct(ObjectManager $om, Validator $validator, QuestionHandlerCollector $collector) + public function __construct( + ObjectManager $om, + Validator $validator, + QuestionHandlerCollector $collector, + ExerciseManager $manager + ) { $this->om = $om; $this->validator = $validator; $this->questionRepo = $om->getRepository('UJMExoBundle:Question'); $this->interactionQcmRepo = $om->getRepository('UJMExoBundle:InteractionQCM'); $this->handlerCollector = $collector; + $this->exerciseManager = $manager; } /** @@ -153,8 +162,8 @@ class ApiManager { return [ 'id' => $exercise->getId(), - 'meta' => $this->getMetadata($exercise), - 'steps' => $this->getSteps($exercise, $withSolutions), + 'meta' => $this->exportMetadata($exercise), + 'steps' => $this->exportSteps($exercise, $withSolutions), ]; } @@ -171,7 +180,7 @@ class ApiManager { return [ 'exercise' => $this->exportExercise($exercise, $withSolutions), - 'paper' => $this->getPaper($exercise, $user) + 'paper' => $this->exportPaper($exercise, $user) ]; } @@ -267,7 +276,7 @@ class ApiManager * @param Exercise $exercise * @return array */ - private function getMetadata(Exercise $exercise) + private function exportMetadata(Exercise $exercise) { $node = $exercise->getResourceNode(); $creator = $node->getCreator(); @@ -291,7 +300,7 @@ class ApiManager * @param bool $withSolutions * @return array */ - private function getSteps(Exercise $exercise, $withSolutions = true) + private function exportSteps(Exercise $exercise, $withSolutions = true) { return array_map(function ($question) use ($withSolutions) { return [ @@ -301,32 +310,17 @@ class ApiManager }, $this->questionRepo->findByExercise($exercise)); } - private function getPaper(Exercise $exercise, User $user) + private function exportPaper(Exercise $exercise, User $user) { $repo = $this->om->getRepository('UJMExoBundle:Paper'); $papers = $repo->findUnfinishedPapers($user, $exercise); if (count($papers) === 0) { - $lastPaper = $repo->findOneBy( - ['user' => $user, 'exercise' => $exercise], - ['start' => 'DESC'] - ); - - $paperNum = $lastPaper ? $lastPaper->getNumPaper() + 1 : 1; - - $paper = new Paper(); - $paper->setExercise($exercise); - $paper->setUser($user); - $paper->setNumPaper($paperNum); - $paper->setOrdreQuestion('not used...'); - - $this->om->persist($paper); - $this->om->flush(); - + $paper = $this->createPaper($user, $exercise); $questions = []; } else { $paper = $papers[0]; - $questions = $this->getPaperQuestions($paper); + $questions = $this->exportPaperQuestions($paper); } return [ @@ -335,7 +329,34 @@ class ApiManager ]; } - private function getPaperQuestions(Paper $paper) + private function createPaper(User $user, Exercise $exercise) + { + $lastPaper = $this->om->getRepository('UJMExoBundle:Paper')->findOneBy( + ['user' => $user, 'exercise' => $exercise], + ['start' => 'DESC'] + ); + + $paperNum = $lastPaper ? $lastPaper->getNumPaper() + 1 : 1; + $questions = $this->exerciseManager->pickQuestions($exercise); + $order = ''; + + foreach ($questions as $question) { + $order .= $question->getId().';'; + } + + $paper = new Paper(); + $paper->setExercise($exercise); + $paper->setUser($user); + $paper->setNumPaper($paperNum); + $paper->setOrdreQuestion($order); + + $this->om->persist($paper); + $this->om->flush(); + + return $paper; + } + + private function exportPaperQuestions(Paper $paper) { $responseRepo = $this->om->getRepository('UJMExoBundle:Response'); $linkRepo = $this->om->getRepository('UJMExoBundle:LinkHintPaper'); diff --git a/Services/classes/PaperService.php b/Services/classes/PaperService.php index <HASH>..<HASH> 100755 --- a/Services/classes/PaperService.php +++ b/Services/classes/PaperService.php @@ -350,7 +350,7 @@ class PaperService /** * To interupt an assessment. * - * + * * @param SessionInterface session * * @return \UJM\ExoBundle\Entity\Paper
[ExoBundle] Set question order
claroline_Distribution
train
6cbc7a2e0614892c1585bba5d506dcacd0ffcc62
diff --git a/src/ReactServer/DataTypes/VarInt.php b/src/ReactServer/DataTypes/VarInt.php index <HASH>..<HASH> 100644 --- a/src/ReactServer/DataTypes/VarInt.php +++ b/src/ReactServer/DataTypes/VarInt.php @@ -6,28 +6,11 @@ use PublicUHC\MinecraftAuth\ReactServer\InvalidDataException; class VarInt extends DataType { /** - * Writes to the stream - * - * @param $fd resource the stream to write to - * @param $data String the data to write - * @param $length int the length of the data - * @throws InvalidDataException - */ - private static function write($fd, $data, $length) - { - $written = fwrite($fd, $data, $length); - if ($written !== $length) { - throw new InvalidDataException(); - } - } - - /** * Reads from the stream * * @param $fd resource the stream to read from * @param $length int the length to read - * @return string the read bytes - * @throws InvalidDataException + * @return string|false the read bytes or false if read failed */ private static function read($fd, $length) { @@ -36,31 +19,30 @@ class VarInt extends DataType { $bytes = fread($fd, $length); if (false === $bytes) { - throw new InvalidDataException(); + return false; } return $bytes; } /** - * Read a varint from string or resource. + * Read a varint from beginning of the string. * - * @param $data String|resource the data + * @param $data String the data * @throws InvalidDataException on invalid data - * @return VarInt the parsed VarInt + * @return VarInt|false the parsed VarInt if parsed, false if not enough data */ public static function readUnsignedVarInt($data) { - $fd = null; - if (is_resource($data)) { - $fd = $data; - } else { - $fd = fopen('data://text/plain,' . urlencode($data), 'rb'); - } + $fd = $fd = fopen('data://text/plain,' . urlencode($data), 'rb'); + $original = ''; $result = $shift = 0; do { $readValue = self::read($fd, 1); + if(false === $readValue) { + return false; + } $original .= $readValue; $byte = ord($readValue); $result |= ($byte & 0x7f) << $shift++ * 7; @@ -77,11 +59,10 @@ class VarInt extends DataType { * Writes a VarInt * * @param $data int the value to write - * @param null $connection if null nothing happens, if set will write the data to the stream * @return VarInt the encoded value * @throws InvalidDataException */ - public static function writeUnsignedVarInt($data, $connection = null) { + public static function writeUnsignedVarInt($data) { if($data < 0) { throw new InvalidDataException('Cannot write negative values'); } @@ -89,8 +70,6 @@ class VarInt extends DataType { //single bytes don't need encoding if ($data < 0x80) { - if($connection != null) - self::write($connection, chr($data), 1); return new VarInt($data, $data, 1); } @@ -106,9 +85,6 @@ class VarInt extends DataType { //build the actual bytes from the encoded array $bytes = call_user_func_array('pack', array_merge(array('C*'), $encodedBytes));; - if($connection != null) - self::write($connection, $bytes, strlen($bytes)); - return new VarInt($orig, $bytes, strlen($bytes)); } } \ No newline at end of file
no need to deal with connection resources any more
Eluinhost_minecraft-auth
train
f064b7987d99ccd966eb6277f1966e3f4829422c
diff --git a/components/table/row.js b/components/table/row.js index <HASH>..<HASH> 100644 --- a/components/table/row.js +++ b/components/table/row.js @@ -210,6 +210,7 @@ export default class Row extends PureComponent { tabIndex="0" onMouseMove={this.onMouseEnter} onClick={this.onClick} + onDoubleClick={item.onRowDoubleClick} data-test="ring-table-row" {...testAttrs} >{cells}</tr>
Add dbl click handler for whole row [publish]
JetBrains_ring-ui
train
c4bef38929c8fc70e30ac7768da2ac8a89eaf000
diff --git a/api/services/model.js b/api/services/model.js index <HASH>..<HASH> 100644 --- a/api/services/model.js +++ b/api/services/model.js @@ -707,7 +707,9 @@ module.exports = function() { newProp = this[property]; } else { newProp = this.$properties[property]; - oldProp = this.$properties.$context.changed.has( property ) ? this.$properties.$context.changed.get( property ) : this.$properties[property]; + oldProp = this.$properties.$context.changed.has( property ) ? + this.$properties.$context.changed.get( property ) : + this.$properties[property]; } if ( newProp !== oldProp ) { diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -40,7 +40,8 @@ module.exports = function() { if ( adapter ) { if ( !( adapter instanceof services.OdemAdapter ) ) { logError( "invalid adapter:", adapter ); - return; + + return Promise.reject( new Error( "invalid adapter rejected" ) ); } logDebug( "discovering model definitions to be managed via %s with %j", adapter.constructor.name, adapter.options || adapter.config || adapter.id ); @@ -50,7 +51,8 @@ module.exports = function() { logDebug( "discovering model definitions to be managed via memory adapter by default" ); } - services.OdemConverter.processModelDefinitions( models, adapter ); + return ( adapter.onPrepared || Promise.resolve() ) + .then( () => services.OdemConverter.processModelDefinitions( models, adapter ) ); } }; };
fixing odem initialization * support waiting for adapter optionally exposing promise for being prepared * always waiting for model definitions defined (to capture issues there)
hitchyjs_odem
train
fc76d439995fbd67634513acdee254d5bfecc14e
diff --git a/libkbfs/folder_branch_ops.go b/libkbfs/folder_branch_ops.go index <HASH>..<HASH> 100644 --- a/libkbfs/folder_branch_ops.go +++ b/libkbfs/folder_branch_ops.go @@ -3211,6 +3211,14 @@ func (fbo *folderBranchOps) maybeWaitOnDeferredWritesLocked( c := fbo.deferredBlockingChan doLock = true fbo.blockLock.Unlock(lState) + + select { + // If we can't send on the channel, that means a sync is + // already in progress + case fbo.forceSyncChan <- struct{}{}: + default: + } + // Check again periodically, in case some other TLF is hogging // all the dirty bytes. t := time.NewTimer(100 * time.Millisecond)
folder_branch_ops: force a sync when write is blocked Issue: KBFS-<I>
keybase_client
train
f92b7a562103ba8a99543a2a04c59d978fc4aa4d
diff --git a/cmd/web-handlers.go b/cmd/web-handlers.go index <HASH>..<HASH> 100644 --- a/cmd/web-handlers.go +++ b/cmd/web-handlers.go @@ -2177,6 +2177,7 @@ func presignedGet(host, bucket, object string, expiry int64, creds auth.Credenti query.Set(xhttp.AmzCredential, credential) query.Set(xhttp.AmzDate, dateStr) query.Set(xhttp.AmzExpires, expiryStr) + query.Set(xhttp.ContentDisposition, fmt.Sprintf("attachment; filename=\"%s\"", object)) // Set session token if available. if sessionToken != "" { query.Set(xhttp.AmzSecurityToken, sessionToken)
Browser: Shared link has content-disposition header (#<I>) The shared link will be automatically downloadable when the user opens the shared link in a browser.
minio_minio
train
b656cd85670e0d5187498e3e38f13b9144cf333f
diff --git a/core/src/main/java/hudson/Util.java b/core/src/main/java/hudson/Util.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/hudson/Util.java +++ b/core/src/main/java/hudson/Util.java @@ -503,9 +503,9 @@ public class Util { else if (seconds >= 10) return Messages.Util_second(seconds); else if (seconds >= 1) - return Messages.Util_second(seconds+"."+millisecs/100); // render "1.2 sec" + return Messages.Util_second(seconds+(float)(millisecs/100)/10); // render "1.2 sec" else if(millisecs>=100) - return Messages.Util_second(String.format("0.%02d",millisecs/10)); // render "0.12 sec". + return Messages.Util_second((float)(millisecs/10)/100); // render "0.12 sec". else return Messages.Util_millisecond(millisecs); } diff --git a/core/src/test/java/hudson/UtilTest.java b/core/src/test/java/hudson/UtilTest.java index <HASH>..<HASH> 100644 --- a/core/src/test/java/hudson/UtilTest.java +++ b/core/src/test/java/hudson/UtilTest.java @@ -4,6 +4,7 @@ import junit.framework.TestCase; import java.util.Map; import java.util.HashMap; +import java.util.Locale; /** * @author Kohsuke Kawaguchi @@ -60,11 +61,20 @@ public class UtilTest extends TestCase { // 171ms -> 0.17sec assertEquals(Messages.Util_second(0.17), Util.getTimeSpanString(171L)); // 101ms -> 0.10sec - assertEquals(Messages.Util_second("0.10"), Util.getTimeSpanString(101L)); + assertEquals(Messages.Util_second(0.1), Util.getTimeSpanString(101L)); // 17ms assertEquals(Messages.Util_millisecond(17), Util.getTimeSpanString(17L)); // 1ms assertEquals(Messages.Util_millisecond(1), Util.getTimeSpanString(1L)); + // Test HUDSON-2843 (locale with comma as fraction separator got exception for <10 sec) + Locale saveLocale = Locale.getDefault(); + Locale.setDefault(Locale.GERMANY); + try { + // Just verifying no exception is thrown: + assertNotNull("German locale", Util.getTimeSpanString(1234)); + assertNotNull("German locale <1 sec", Util.getTimeSpanString(123)); + } + finally { Locale.setDefault(saveLocale); } }
[FIXED HUDSON-<I>] Util.getTimeSpanString() got exception for times <<I> sec on locales with comma as fraction separator. Now passing time value to localizer as float instead of String. git-svn-id: <URL>
jenkinsci_jenkins
train
a092291b6345664a373187d6683a6647fd455169
diff --git a/Gruntfile.js b/Gruntfile.js index <HASH>..<HASH> 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -15,7 +15,8 @@ module.exports = function(grunt) { return function(tree) { return new Promise(function(resolve) { tree.match({ tag: 'style' }, function(node) { - postcss([ require('postcss-custom-properties') ]) + postcss([ require('postcss-custom-properties'), + require('postcss-color-function') ]) .process(rootStyles + node.content[0] /*, { from: 'src/app.css', to: 'app.css' }*/) .then(function(result) { node.content[0] = result.css; @@ -113,7 +114,13 @@ module.exports = function(grunt) { files: [ 'src/*.html' ], - tasks: ['bosonic', 'copy:elements'] + tasks: ['bosonic'] + }, + dist: { + files: [ + 'dist/*.html' + ], + tasks: ['copy:elements'] }, globalCss: { files: ['src/b-styles.css'], @@ -127,7 +134,7 @@ module.exports = function(grunt) { }); - grunt.registerTask('demo', ['bosonic', 'copy', 'connect', 'watch']); + grunt.registerTask('demo', ['bosonic', 'postcss', 'copy', 'connect', 'watch']); require('load-grunt-tasks')(grunt); }; \ No newline at end of file
Added watcher for easier dev
bosonic_core-elements
train
ed61b4123fa5dab349506aa1725894ef2b087f82
diff --git a/lib/utils.js b/lib/utils.js index <HASH>..<HASH> 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -83,3 +83,12 @@ function setESModule(exports) { } exports.setESModule = setESModule; + +function toString(value) { + if (typeof value === "string") { + return value; + } + return value == null ? "" : String(value); +} + +exports.toString = toString; diff --git a/node/utils.js b/node/utils.js index <HASH>..<HASH> 100644 --- a/node/utils.js +++ b/node/utils.js @@ -3,8 +3,8 @@ const createHash = require("crypto").createHash; const data = require("./data.js"); const fs = require("fs"); -const isObject = require("../lib/utils.js").isObject; const path = require("path"); +const utils = require("../lib/utils.js"); const zlib = require("minizlib"); const FastObject = require("../lib/fast-object.js"); @@ -73,7 +73,7 @@ function fallbackReadFile(filepath, options) { function getReifyRange(json, name) { var entry = json[name]; - return isObject(entry) && hasOwn.call(entry, "reify") + return utils.isObject(entry) && hasOwn.call(entry, "reify") ? SemVer.validRange(entry.reify) : null; } @@ -84,10 +84,6 @@ function streamToBuffer(stream, data) { return Buffer.concat(result); } -function toString(value) { - return typeof value === "string" ? value : String(value); -} - function getCacheFileName(filename, cacheKey, pkgInfo) { const ext = typeof filename === "string" ? path.extname(filename) @@ -98,9 +94,9 @@ function getCacheFileName(filename, cacheKey, pkgInfo) { return createHash("sha1") .update(reifySemVer.major + "." + reifySemVer.minor) .update("\0") - .update(toString(filename)) + .update(utils.toString(filename)) .update("\0") - .update(toString(cacheKey)) + .update(utils.toString(cacheKey)) .update("\0") .update(JSON.stringify(pkgInfo.config)) .update("\0") @@ -238,7 +234,7 @@ function readdir(dirpath) { exports.readdir = readdir; function readFile(filepath, options) { - const encoding = isObject(options) ? options.encoding : options; + const encoding = utils.isObject(options) ? options.encoding : options; if (useReadFileFastPath && encoding === "utf8") { try {
Move toString helper to lib/utils.
benjamn_reify
train
bc2db53a2171be19b83f1bda3538df5920e2a516
diff --git a/lib/index.js b/lib/index.js index <HASH>..<HASH> 100644 --- a/lib/index.js +++ b/lib/index.js @@ -67,7 +67,9 @@ function expandAsObject(property, value, recurse) { value = list.space(value); } - for (var i = 0, j = 0, l = subs.length, jl = value.length; i < l; i++) { + for (var i = 0, j, l = subs.length, jl = value.length; i < l; i++) { + j = i < jl ? i : (jl < 2 ? 0 : i % 2); + if (recurse) { var recRes = expandAsObject(subs[i], value[j], recurse); var keys = Object.keys(recRes); @@ -77,7 +79,6 @@ function expandAsObject(property, value, recurse) { } else { res[subs[i]] = value[j]; } - j = (j + 1) % jl; } return res; diff --git a/test/03.expand-as-object.js b/test/03.expand-as-object.js index <HASH>..<HASH> 100644 --- a/test/03.expand-as-object.js +++ b/test/03.expand-as-object.js @@ -1,6 +1,6 @@ describe('expand as object', function () { - it('should expand border shorthand with a value and flag to an object', function () { + it('should expand border shorthand with a flag', function () { SC.expand('border', '1px solid red', false) .should.eql({ 'border-width': '1px', @@ -9,7 +9,7 @@ describe('expand as object', function () { }); }); - it('should expand border shorthand with a value to an object', function () { + it('should expand border shorthand', function () { SC.expand('border', '1px solid red') .should.eql({ 'border-top-width': '1px', @@ -27,4 +27,14 @@ describe('expand as object', function () { }); }); + it('should expand border-radius shorthand', function () { + SC.expand('border-radius', '0px 4em 3px') + .should.eql({ + 'border-top-left-radius': '0px', + 'border-top-right-radius': '4em', + 'border-bottom-right-radius': '3px', + 'border-bottom-left-radius': '4em', + }); + }); + });
Misc: fixup repeating values assigning according to browsers
theprotein_shortcss
train
ce2d09f7b4af6311ba465f2a4a1e7fd0b21173e4
diff --git a/tools/interop_matrix/client_matrix.py b/tools/interop_matrix/client_matrix.py index <HASH>..<HASH> 100644 --- a/tools/interop_matrix/client_matrix.py +++ b/tools/interop_matrix/client_matrix.py @@ -115,6 +115,7 @@ LANG_RELEASE_MATRIX = { ('v1.38.0', ReleaseInfo()), ('v1.39.0', ReleaseInfo()), ('v1.41.1', ReleaseInfo()), + ('v1.42.0', ReleaseInfo()), ]), 'go': OrderedDict([ @@ -391,6 +392,7 @@ LANG_RELEASE_MATRIX = { ReleaseInfo(runtimes=['python'], testcases_file='python__v1.18.0')), ('v1.41.1', ReleaseInfo(runtimes=['python'])), + ('v1.42.0', ReleaseInfo(runtimes=['python'])), ]), 'node': OrderedDict([ @@ -460,6 +462,7 @@ LANG_RELEASE_MATRIX = { ('v1.38.0', ReleaseInfo()), ('v1.39.0', ReleaseInfo()), ('v1.41.1', ReleaseInfo()), + ('v1.42.0', ReleaseInfo()), ]), 'php': OrderedDict([ @@ -502,6 +505,7 @@ LANG_RELEASE_MATRIX = { ('v1.38.0', ReleaseInfo()), ('v1.39.0', ReleaseInfo()), ('v1.41.1', ReleaseInfo()), + ('v1.42.0', ReleaseInfo()), ]), 'csharp': OrderedDict([ @@ -549,5 +553,6 @@ LANG_RELEASE_MATRIX = { ('v1.38.1', ReleaseInfo()), ('v1.39.1', ReleaseInfo()), ('v1.41.1', ReleaseInfo()), + ('v1.42.0', ReleaseInfo()), ]), }
add <I> to interop matrix (#<I>)
grpc_grpc
train
e287ef4388d2443aee89dbdabe797562db1d7d77
diff --git a/cmd/gb-vendor/alldocs.go b/cmd/gb-vendor/alldocs.go index <HASH>..<HASH> 100644 --- a/cmd/gb-vendor/alldocs.go +++ b/cmd/gb-vendor/alldocs.go @@ -119,7 +119,7 @@ Usage: gb vendor restore [-precaire] -Restore vendor dependecies. +Restore vendor dependencies. Flags: -precaire diff --git a/cmd/gb-vendor/restore.go b/cmd/gb-vendor/restore.go index <HASH>..<HASH> 100644 --- a/cmd/gb-vendor/restore.go +++ b/cmd/gb-vendor/restore.go @@ -19,7 +19,7 @@ var cmdRestore = &cmd.Command{ Name: "restore", UsageLine: "restore [-precaire]", Short: "restore dependencies from the manifest", - Long: `Restore vendor dependecies. + Long: `Restore vendor dependencies. Flags: -precaire
Fix minor typo ("dependecies" vs "dependencies") (#<I>)
constabulary_gb
train
fbffa7840cca747b884b1429513966764fdec40a
diff --git a/src/OAuth2/Client/Provider/Google.php b/src/OAuth2/Client/Provider/Google.php index <HASH>..<HASH> 100755 --- a/src/OAuth2/Client/Provider/Google.php +++ b/src/OAuth2/Client/Provider/Google.php @@ -1,84 +1,40 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); -/** - * Google OAuth2 Provider - * - * @package CodeIgniter/OAuth2 - * @category Provider - * @author Phil Sturgeon - * @copyright (c) 2012 HappyNinjas Ltd - * @license http://philsturgeon.co.uk/code/dbad-license - */ +<?php -class OAuth2_Provider_Google extends OAuth2_Provider +namespace OAuth2\Client\Provider; + +class Google extends IdentityProvider { - /** - * @var string the method to use when requesting tokens - */ - public $method = 'POST'; + public $scopeSeperator = ' '; - /** - * @var string scope separator, most use "," but some like Google are spaces - */ - public $scope_seperator = ' '; + public $scope = array( + 'https://www.googleapis.com/auth/userinfo.profile', + 'https://www.googleapis.com/auth/userinfo.email' + ); - public function url_authorize() + public function urlAuthorize() { return 'https://accounts.google.com/o/oauth2/auth'; } - public function url_access_token() + public function urlAccessToken() { return 'https://accounts.google.com/o/oauth2/token'; } - public function __construct(array $options = array()) - { - // Now make sure we have the default scope to get user data - empty($options['scope']) and $options['scope'] = array( - 'https://www.googleapis.com/auth/userinfo.profile', - 'https://www.googleapis.com/auth/userinfo.email' - ); - - // Array it if its string - $options['scope'] = (array) $options['scope']; - - parent::__construct($options); - } - - /* - * Get access to the API - * - * @param string The access code - * @return object Success or failure along with the response details - */ - public function access($code, $options = array()) + public function urlUserDetails(\OAuth2\Client\Token\AccessToken $token) { - if ($code === null) - { - throw new OAuth2_Exception(array('message' => 'Expected Authorization Code from '.ucfirst($this->name).' is missing')); - } - - return parent::access($code, $options); + return 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token='.$token; } - public function get_user_info(OAuth2_Token_Access $token) + public function userDetails($response, \OAuth2\Client\Token\AccessToken $token) { - $url = 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&'.http_build_query(array( - 'access_token' => $token->access_token, - )); - - $user = json_decode(file_get_contents($url), true); - return array( - 'uid' => $user['id'], - 'nickname' => url_title($user['name'], '_', true), - 'name' => $user['name'], - 'first_name' => $user['given_name'], - 'last_name' => $user['family_name'], - 'email' => $user['email'], - 'location' => null, - 'image' => (isset($user['picture'])) ? $user['picture'] : null, - 'description' => null, - 'urls' => array(), - ); + $user = new User; + $user->uid = $response['id']; + $user->name = $response['name']; + $user->first_name = $response['given_name']; + $user->last_name = $response['family_name']; + $user->email = $response['email']; + $user->image = (isset($response['picture'])) ? $response['picture'] : null; + return $user; } }
Updated Google and Github providers
thephpleague_oauth2-google
train
4bb7ae3e79f45849a2abd2dd00db630e9a500713
diff --git a/src/main/java/mousio/etcd4j/transport/EtcdNettyClient.java b/src/main/java/mousio/etcd4j/transport/EtcdNettyClient.java index <HASH>..<HASH> 100644 --- a/src/main/java/mousio/etcd4j/transport/EtcdNettyClient.java +++ b/src/main/java/mousio/etcd4j/transport/EtcdNettyClient.java @@ -117,9 +117,18 @@ public class EtcdNettyClient implements EtcdClientImpl { @SuppressWarnings("unchecked") protected <R> void connect(final EtcdRequest<R> etcdRequest, final ConnectionState connectionState) throws IOException { + + URI uri = uris[connectionState.uriIndex]; + + // when we are called from a redirect, the url in the request contains also host and port! + String requestUrl = etcdRequest.getUrl(); + if(requestUrl.contains("://")){ + uri = URI.create(requestUrl); + } + // Start the connection attempt. final ChannelFuture connectFuture = bootstrap.clone() - .connect(uris[connectionState.uriIndex].getHost(), uris[connectionState.uriIndex].getPort()); + .connect(uri.getHost(), uri.getPort()); final Channel channel = connectFuture.channel(); etcdRequest.getPromise().attachNettyPromise(
fixed redirect: new Url contains host and port!
jurmous_etcd4j
train
f285e8757bcc4284dee413df2b69e639db99ddd5
diff --git a/astroplan/core.py b/astroplan/core.py index <HASH>..<HASH> 100644 --- a/astroplan/core.py +++ b/astroplan/core.py @@ -455,8 +455,7 @@ class Observer(object): Examples -------- Create an instance of the `~astropy.coordinates.AltAz` frame for an - observer at Apache Point Observatory at a particular time; and - transform that + observer at Apache Point Observatory at a particular time: >>> from astroplan import Observer >>> from astropy.time import Time @@ -465,8 +464,15 @@ class Observer(object): >>> time = Time('2001-02-03 04:05:06') >>> target = SkyCoord(0*u.deg, 0*u.deg) >>> altaz_frame = apo.altaz(time) - >>> target_transformed_to_altaz_frame = target.transform_to(altaz_frame) - >>> target_transformed_to_altaz_frame = apo.altaz(time, target) # Alternatively + + Now transform the target's coordinates to the alt/az frame: + + >>> target_altaz = target.transform_to(altaz_frame) + + Alternatively, construct an alt/az frame and transform the target to + that frame all in one step: + + >>> target_altaz = apo.altaz(time, target) """ if not isinstance(time, Time): time = Time(time)
Making altaz e example clearer, as per rec. by @cdeil
astropy_astroplan
train
77ab2d59e8bbe099075dd4eac68b8fd4bf530772
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -112,6 +112,7 @@ setuptools.setup( 'quantum-nec-agent = ' 'quantum.plugins.nec.agent.nec_quantum_agent:main', 'quantum-server = quantum.server:main', + 'quantum-debug = quantum.debug.shell:main', ] }, )
Implements agent for Quantum Networking testing This agent client plugs itself into each network. Then tries to ping each fixed_ips. Implements blueprint test-agent Change-Id: I<I>e<I>e9e<I>ceae<I>e<I>cfcdd<I>b<I>
openstack_networking-cisco
train
f0ab0f81d3cab5d030132ea1b2c6f898a66bbcc2
diff --git a/packages/babel-standalone/test/babel.js b/packages/babel-standalone/test/babel.js index <HASH>..<HASH> 100644 --- a/packages/babel-standalone/test/babel.js +++ b/packages/babel-standalone/test/babel.js @@ -92,12 +92,9 @@ describe("babel-standalone", () => { it("handles plugins with options", () => { const output = Babel.transform("`${x}`", { - plugins: [["transform-es2015-template-literals", { spec: true }]], + plugins: [["transform-es2015-template-literals", { loose: true }]], }).code; - assert.equal( - output, - '"".concat(x);', // https://github.com/babel/babel/pull/5791 - ); + assert.equal(output, '"" + x;'); }); it("throws on invalid preset name", () => {
transform-es<I>-template-literals doesn't have spec mode anymore, change test to use loose mode (#<I>)
babel_babel
train