hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
028f0c0aa110eecc237a7d243405e725df5e167e
|
diff --git a/zubbi/scraper/repos/github.py b/zubbi/scraper/repos/github.py
index <HASH>..<HASH> 100644
--- a/zubbi/scraper/repos/github.py
+++ b/zubbi/scraper/repos/github.py
@@ -138,7 +138,11 @@ class GitHubRepository(Repository):
return flat_blame
def _get_repo_object(self):
- owner, repo_name = self.repo_name.split("/")
+ try:
+ owner, repo_name = self.repo_name.split("/")
+ except ValueError:
+ LOGGER.error("Invalid repo name '%s'", self.repo_name)
+ return None
gh_client = self.gh_con.create_github_client(self.repo_name)
if gh_client is None:
return None
|
Avoid splitting invalid GH repository names
This invalid repo name actually comes from a bug in the tenant config
parser, which results in a repo 'include' that cannot be split into
(owner, /, repo). Thus, the error should be fixed directly in the tenant
parser. Still, I find it's a good idea to make this part more
robust and avoid similar errors in the future.
|
bmwcarit_zubbi
|
train
|
bce462ceb0df329b2a53a611285ad436384e5dd4
|
diff --git a/test/integration/sandbox-libraries/ajv.test.js b/test/integration/sandbox-libraries/ajv.test.js
index <HASH>..<HASH> 100644
--- a/test/integration/sandbox-libraries/ajv.test.js
+++ b/test/integration/sandbox-libraries/ajv.test.js
@@ -24,14 +24,14 @@ describe('sandbox library - AJV', function () {
};
pm.test("ajv.validate", function () {
- var ajv = new Ajv();
+ var ajv = new Ajv({logger: false});
pm.expect(ajv.validate(schema, {alpha: true})).to.be.true;
pm.expect(ajv.validate(schema, {alpha: 123})).to.be.false;
});
pm.test("ajv.compile", function () {
- var ajv = new Ajv(),
+ var ajv = new Ajv({logger: false}),
validate = ajv.compile(schema);
pm.expect(validate({alpha: true})).to.be.true;
@@ -88,6 +88,7 @@ describe('sandbox library - AJV', function () {
},
ajv = new Ajv({
+ logger: false,
loadSchema: function(uri) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
|
Test: Disable Ajv logs
|
postmanlabs_postman-runtime
|
train
|
619dcd7130455a0880ff0297c59c7dd01670b96a
|
diff --git a/udata/harvest/backends/ods.py b/udata/harvest/backends/ods.py
index <HASH>..<HASH> 100644
--- a/udata/harvest/backends/ods.py
+++ b/udata/harvest/backends/ods.py
@@ -22,6 +22,7 @@ class OdsHarvester(BaseBackend):
LICENSES = {
"Open Database License (ODbL)": "odc-odbl",
"Licence Ouverte (Etalab)": "fr-lo",
+ "Licence ouverte / Open Licence": "fr-lo",
"CC BY-SA": "cc-by-sa",
"Public Domain": "other-pd"
}
|
Added alternative Open License labelling handling
|
opendatateam_udata
|
train
|
451b3cc96db2b3595fb35f5a3bc3b6e4a49a1978
|
diff --git a/src/messaging.js b/src/messaging.js
index <HASH>..<HASH> 100644
--- a/src/messaging.js
+++ b/src/messaging.js
@@ -13,22 +13,33 @@ export function getMessage(channel) {
})
}
-
export function pushMessage(channel, message) {
assertChannel(channel)
channel.pushToQueue(channel.queue, message)
}
+export function droppingChannel(capacity) {
+ return _createChannel({dropping: capacity})
+}
+
+export function slidingChannel(capacity) {
+ return _createChannel({sliding: capacity})
+}
+
export function createChannel(transducer = null) {
- const queue = new Queue()
+ return _createChannel({transducer})
+}
+
+function _createChannel(options) {
+ const queue = new Queue({sliding: options.sliding, dropping: options.dropping})
let pushToQueue = (queue, message) => {
queue.push(message)
return queue
}
- if (transducer != null) {
- pushToQueue = t.toFn(transducer, pushToQueue)
+ if (options.transducer != null) {
+ pushToQueue = t.toFn(options.transducer, pushToQueue)
}
return ({
diff --git a/src/queue.js b/src/queue.js
index <HASH>..<HASH> 100644
--- a/src/queue.js
+++ b/src/queue.js
@@ -11,12 +11,27 @@ export class Queue {
push = (val) => {
this.data[`${this.max}`] = val
this.max += 1
+ if (this.options.sliding != null) {
+ const sliding = this.options.sliding
+ if (this.max - this.min > sliding) {
+ this.min = this.max - sliding
+ }
+ }
+ if (this.options.dropping != null) {
+ const dropping = this.options.dropping
+ if (this.max - this.min > dropping) {
+ this.max = this.min + dropping
+ }
+ }
this.trySatisfy()
}
empty = () => (this.max <= this.min)
pop = (val) => {
+ if (this.empty()) {
+ throw new Error('cannot pop empty queue')
+ }
const result = this.data[`${this.min}`]
delete this.data[`${this.min}`]
this.min += 1
diff --git a/tests/messaging-advanced.js b/tests/messaging-advanced.js
index <HASH>..<HASH> 100644
--- a/tests/messaging-advanced.js
+++ b/tests/messaging-advanced.js
@@ -1,4 +1,5 @@
-import {run, pushMessage, getMessage, createChannel, mult, kill, merge} from '../dist'
+import {run, pushMessage, getMessage, createChannel,
+ droppingChannel, slidingChannel, mult, kill, merge} from '../dist'
import {assert} from 'chai'
//import {resetTimer, timeApprox} from './utils'
import Promise from 'bluebird'
@@ -83,5 +84,38 @@ describe('mult', () => {
})
yield c1
}))
+})
+
+describe('sliding channel', () => {
+
+ it('basics', () => run(function*() {
+ const ch = slidingChannel(2)
+ for (let i = 0; i < 10; i++) {
+ pushMessage(ch, i)
+ }
+ run(function*() {
+ const msg1 = yield run(getMessage, ch)
+ assert.equal(msg1, 8)
+ const msg2 = yield run(getMessage, ch)
+ assert.equal(msg2, 9)
+ })
+ }))
})
+
+describe('dropping channel', () => {
+
+ it('basics', () => run(function*() {
+ const ch = droppingChannel(2)
+ for (let i = 0; i < 10; i++) {
+ pushMessage(ch, i)
+ }
+ run(function*() {
+ const msg1 = yield run(getMessage, ch)
+ assert.equal(msg1, 0)
+ const msg2 = yield run(getMessage, ch)
+ assert.equal(msg2, 1)
+ })
+ }))
+})
+
|
Sliding and dropping chanels
|
vacuumlabs_yacol
|
train
|
3ba7af30e7d8195957a98047f377547e4cb04cfa
|
diff --git a/jquery.fileupload.js b/jquery.fileupload.js
index <HASH>..<HASH> 100644
--- a/jquery.fileupload.js
+++ b/jquery.fileupload.js
@@ -1,5 +1,5 @@
/*
- * jQuery File Upload Plugin 3.8.1
+ * jQuery File Upload Plugin 3.8.2
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
@@ -434,7 +434,7 @@
},
initFileInput = function () {
- fileInput = uploadForm.find('input:file')
+ fileInput = (uploadForm.length ? uploadForm : container).find('input:file')
.filter(settings.fileInputFilter);
},
|
Update to find file input fields without a surrounding form.
|
blueimp_jQuery-File-Upload
|
train
|
825e83afc2802c22d626aa92d38e14355c14416b
|
diff --git a/orator/query/builder.py b/orator/query/builder.py
index <HASH>..<HASH> 100644
--- a/orator/query/builder.py
+++ b/orator/query/builder.py
@@ -1605,12 +1605,16 @@ class QueryBuilder(object):
:param query: The query to merge with
:type query: QueryBuilder
"""
+ self.columns += query.columns
self.joins += query.joins
self.wheres += query.wheres
self.groups += query.groups
self.havings += query.havings
self.orders += query.orders
+ if self.columns:
+ self.columns = Collection(self.columns).unique().all()
+
if query.limit_:
self.limit_ = query.limit_
diff --git a/orator/support/grammar.py b/orator/support/grammar.py
index <HASH>..<HASH> 100644
--- a/orator/support/grammar.py
+++ b/orator/support/grammar.py
@@ -14,7 +14,7 @@ class Grammar(object):
self.marker = marker
def wrap_list(self, values):
- return map(self.wrap, values)
+ return list(map(self.wrap, values))
def wrap_table(self, table):
if self.is_expression(table):
diff --git a/tests/integrations/__init__.py b/tests/integrations/__init__.py
index <HASH>..<HASH> 100644
--- a/tests/integrations/__init__.py
+++ b/tests/integrations/__init__.py
@@ -283,9 +283,11 @@ class IntegrationTestCase(object):
post2 = user.posts().create(name='Second Post')
user = OratorTestUser.with_('posts').first()
+ columns = ', '.join(self.connection().get_query_grammar().wrap_list(['id', 'name', 'user_id']))
self.assertEqual(
- 'SELECT * FROM %(table)s WHERE %(table)s.%(user_id)s = %(marker)s ORDER BY %(name)s DESC'
+ 'SELECT %(columns)s FROM %(table)s WHERE %(table)s.%(user_id)s = %(marker)s ORDER BY %(name)s DESC'
% {
+ 'columns': columns,
'marker': self.marker,
'table': self.grammar().wrap('test_posts'),
'user_id': self.grammar().wrap('user_id'),
@@ -296,8 +298,9 @@ class IntegrationTestCase(object):
user = OratorTestUser.first()
self.assertEqual(
- 'SELECT * FROM %(table)s WHERE %(table)s.%(user_id)s = %(marker)s ORDER BY %(name)s DESC'
+ 'SELECT %(columns)s FROM %(table)s WHERE %(table)s.%(user_id)s = %(marker)s ORDER BY %(name)s DESC'
% {
+ 'columns': columns,
'marker': self.marker,
'table': self.grammar().wrap('test_posts'),
'user_id': self.grammar().wrap('user_id'),
@@ -423,7 +426,7 @@ class OratorTestUser(Model):
@has_one('user_id')
def post(self):
- return OratorTestPost.order_by('name', 'desc')
+ return OratorTestPost.select('id', 'name', 'name', 'user_id').order_by('name', 'desc')
@morph_many('imageable')
def photos(self):
|
Merging queries also merges columns.
Fixes #<I>
|
sdispater_orator
|
train
|
fc65b3806feea088d68cadab14fc0855d81ae46a
|
diff --git a/MAVProxy/mavproxy.py b/MAVProxy/mavproxy.py
index <HASH>..<HASH> 100644
--- a/MAVProxy/mavproxy.py
+++ b/MAVProxy/mavproxy.py
@@ -237,6 +237,7 @@ class MPState(object):
MPSetting('streamrate2', int, 4, 'Stream rate link2', range=(-1,500), increment=1),
MPSetting('heartbeat', float, 1, 'Heartbeat rate (Hz)', range=(0,100), increment=0.1),
MPSetting('mavfwd', bool, True, 'Allow forwarded control'),
+ MPSetting('mavfwd_disarmed', bool, True, 'Allow forwarded control when disarmed'),
MPSetting('mavfwd_rate', bool, False, 'Allow forwarded rate control'),
MPSetting('mavfwd_link', int, -1, 'Forward to a specific link'),
MPSetting('shownoise', bool, True, 'Show non-MAVLink data'),
@@ -837,7 +838,12 @@ def process_mavlink(slave):
return
if msgs is None:
return
- if mpstate.settings.mavfwd and not mpstate.status.setup_mode:
+ allow_fwd = mpstate.settings.mavfwd
+ if not allow_fwd and mpstate.settings.mavfwd_disarmed and not mpstate.master(-1).motors_armed():
+ allow_fwd = True
+ if mpstate.status.setup_mode:
+ allow_fwd = False
+ if allow_fwd:
for m in msgs:
target_sysid = getattr(m, 'target_system', -1)
mbuf = m.get_msgbuf()
|
added mavfwd_disarmed settings
allows for forwarding from downstream links only when disarmed,
allowing then to connect and get parameters but not impact on flight
|
ArduPilot_MAVProxy
|
train
|
77c3d8a67839c8b1f24413af5a2937a59f278ec7
|
diff --git a/lib/Dough/Twig/DoughExtension.php b/lib/Dough/Twig/DoughExtension.php
index <HASH>..<HASH> 100644
--- a/lib/Dough/Twig/DoughExtension.php
+++ b/lib/Dough/Twig/DoughExtension.php
@@ -49,8 +49,12 @@ class DoughExtension extends \Twig_Extension
* @param MoneyInterface $money A MoneyInterface instance
* @param string $currency The currency code
*/
- public function getAmount(MoneyInterface $money, $currency = null)
+ public function getAmount(MoneyInterface $money = null, $currency = null)
{
+ if (null === $money) {
+ return 0.0;
+ }
+
$reduced = $this->bank->reduce($money, $currency);
return $reduced->getAmount();
|
Return 0 when a null is passed into dough_currency
|
merk_Dough
|
train
|
73bff7730004908be2a9b23cb0da37c16c167116
|
diff --git a/lib/benchmark/bigo.rb b/lib/benchmark/bigo.rb
index <HASH>..<HASH> 100644
--- a/lib/benchmark/bigo.rb
+++ b/lib/benchmark/bigo.rb
@@ -41,7 +41,7 @@ module Benchmark
$stdout.sync = sync
- return job.reports
+ return job.full_report
end
end
diff --git a/lib/benchmark/bigo/job.rb b/lib/benchmark/bigo/job.rb
index <HASH>..<HASH> 100644
--- a/lib/benchmark/bigo/job.rb
+++ b/lib/benchmark/bigo/job.rb
@@ -35,7 +35,11 @@ module Benchmark
include Chartkick::Helper
- attr_accessor :increments, :logscale
+ # how many total increments are being measured
+ attr_accessor :increments
+
+ # whether to graph the results on a log scale
+ attr_accessor :logscale
# whether to generate a chart of the results
# if nil, do not generate chart
@@ -44,10 +48,11 @@ module Benchmark
def initialize opts={}
super
+
@generator = nil
@incrementer = nil
- @reports = Report.new
+ @full_report = Report.new
# defaults
@increments = 5
@@ -59,7 +64,7 @@ module Benchmark
super
@increments = opts[:increments] if opts[:increments]
@logscale = opts[:logscale] if opts[:logscale]
- @reports.logscale! if @logscale
+ @full_report.logscale! if @logscale
end
def chart?
@@ -72,7 +77,7 @@ module Benchmark
def logscale= val
@logscale = val
- @reports.logscale! if @logscale
+ @full_report.logscale! if @logscale
end
def generator &blk
@@ -114,22 +119,22 @@ module Benchmark
super
max_timing = @timing.values.max
- @reports.per_iterations = 10**Math.log10(max_timing).ceil
+ @full_report.per_iterations = 10**Math.log10(max_timing).ceil
end
def generate_chart
return if @chart.nil?
- all_data = @reports.chart_data
+ all_data = @full_report.chart_data
charts = []
- charts << { name: 'Growth Chart', data: all_data, opts: @reports.chart_opts(all_data) }
+ charts << { name: 'Growth Chart', data: all_data, opts: @full_report.chart_opts(all_data) }
if compare?
all_sizes = sizes
for chart_data in all_data
- comparison_data = @reports.comparison_chart_data chart_data, all_sizes
- charts << { name: chart_data[:name], data: comparison_data, opts: @reports.chart_opts(chart_data) }
+ comparison_data = @full_report.comparison_chart_data chart_data, all_sizes
+ charts << { name: chart_data[:name], data: comparison_data, opts: @full_report.chart_opts(chart_data) }
end
end
|
Switch @reports to @full_report
To match changes in Benchmark::IPS, change references to @reports to
@full_report
|
davy_benchmark-bigo
|
train
|
69d00fb9369172f8337d688a3196db10d950597f
|
diff --git a/test/extended/oauth/groupsync.go b/test/extended/oauth/groupsync.go
index <HASH>..<HASH> 100644
--- a/test/extended/oauth/groupsync.go
+++ b/test/extended/oauth/groupsync.go
@@ -10,8 +10,12 @@ import (
g "github.com/onsi/ginkgo"
o "github.com/onsi/gomega"
+ "time"
+
"github.com/openshift/origin/test/extended/testdata"
testutil "github.com/openshift/origin/test/extended/util"
+ "k8s.io/kubernetes/staging/src/k8s.io/apimachinery/pkg/util/wait"
+ e2e "k8s.io/kubernetes/test/e2e/framework"
)
var _ = g.Describe("[Suite:openshift/oauth][Serial] ldap group sync", func() {
@@ -76,6 +80,17 @@ var _ = g.Describe("[Suite:openshift/oauth][Serial] ldap group sync", func() {
err = pod.CopyFromHost(groupSyncScriptPath, path.Join("/usr", "bin", "groupsync.sh"))
o.Expect(err).NotTo(o.HaveOccurred())
+ // Fix flake executing groupsync.sh before it has landed on the pod.
+ err = wait.PollImmediate(2*time.Second, 5*time.Minute, func() (done bool, err error) {
+ _, lsErr := pod.Exec("/bin/ls /usr/bin/groupsync.sh &> /dev/null")
+ if lsErr != nil {
+ e2e.Logf("groupsync.sh is not available, retrying...")
+ return false, nil
+ }
+ return true, nil
+ })
+ o.Expect(err).NotTo(o.HaveOccurred())
+
// Make it executable
_, err = pod.Exec("chmod +x /usr/bin/groupsync.sh")
o.Expect(err).NotTo(o.HaveOccurred())
|
try to fix flake copying groupsync.sh
|
openshift_origin
|
train
|
4fab1c0888aaa6c4e4568c53ba26eecae85a25bd
|
diff --git a/packages/site/pages/components/dropdown.js b/packages/site/pages/components/dropdown.js
index <HASH>..<HASH> 100644
--- a/packages/site/pages/components/dropdown.js
+++ b/packages/site/pages/components/dropdown.js
@@ -1,5 +1,6 @@
/* eslint-disable react/display-name */
import React, { forwardRef, useState } from 'react'
+import CorePropTypes from 'prop-types'
import Button from '@pluralsight/ps-design-system-button'
import * as core from '@pluralsight/ps-design-system-core'
@@ -143,6 +144,7 @@ const DropdownWithIcon = forwardRef(({ icon, ...props }, forwardedRef) => {
/>
)
})
+DropdownWithIcon.propTypes = { icon: CorePropTypes.node }
const FixedIconExample = () => {
return (
|
style(site): fix some linting errors
|
pluralsight_design-system
|
train
|
5bb37a15e63ae8f747c9ff19383dd0c856f06390
|
diff --git a/lib/Mongo/MongoCollection.php b/lib/Mongo/MongoCollection.php
index <HASH>..<HASH> 100644
--- a/lib/Mongo/MongoCollection.php
+++ b/lib/Mongo/MongoCollection.php
@@ -667,7 +667,11 @@ class MongoCollection
*/
public function deleteIndexes()
{
- return TypeConverter::toLegacy($this->collection->dropIndexes());
+ try {
+ return TypeConverter::toLegacy($this->collection->dropIndexes());
+ } catch (\MongoDB\Driver\Exception\Exception $e) {
+ return ExceptionConverter::toResultArray($e);
+ }
}
/**
diff --git a/tests/Alcaeus/MongoDbAdapter/Mongo/MongoCollectionTest.php b/tests/Alcaeus/MongoDbAdapter/Mongo/MongoCollectionTest.php
index <HASH>..<HASH> 100644
--- a/tests/Alcaeus/MongoDbAdapter/Mongo/MongoCollectionTest.php
+++ b/tests/Alcaeus/MongoDbAdapter/Mongo/MongoCollectionTest.php
@@ -928,6 +928,16 @@ class MongoCollectionTest extends TestCase
$this->assertCount(1, iterator_to_array($newCollection->listIndexes())); // ID index is present by default
}
+ public function testDeleteIndexesForNonExistingCollection()
+ {
+ $expected = [
+ 'ok' => 0.0,
+ 'errmsg' => 'ns not found',
+ 'code' => 26,
+ ];
+ $this->assertSame($expected, $this->getcollection('nonExisting')->deleteIndexes());
+ }
+
public function testGetIndexInfo()
{
$collection = $this->getCollection();
|
Properly catch exceptions when deleting indexes
|
alcaeus_mongo-php-adapter
|
train
|
2371d8cb1c4b4e66871a4745e6fc0fec567b362e
|
diff --git a/troposphere/autoscaling.py b/troposphere/autoscaling.py
index <HASH>..<HASH> 100644
--- a/troposphere/autoscaling.py
+++ b/troposphere/autoscaling.py
@@ -206,6 +206,41 @@ class StepAdjustments(AWSProperty):
}
+class MetricDimension(AWSProperty):
+ props = {
+ 'Name': (basestring, True),
+ 'Value': (basestring, True),
+ }
+
+
+class CustomizedMetricSpecification(AWSProperty):
+ props = {
+ 'Dimensions': ([MetricDimension], False),
+ 'MetricName': (basestring, True),
+ 'Namespace': (basestring, True),
+ 'Statistic': (basestring, True),
+ 'Unit': (basestring, False),
+ }
+
+
+class PredefinedMetricSpecification(AWSProperty):
+ props = {
+ 'PredefinedMetricType': (basestring, True),
+ 'ResourceLabel': (basestring, False),
+ }
+
+
+class TargetTrackingConfiguration(AWSProperty):
+ props = {
+ 'CustomizedMetricSpecification':
+ (CustomizedMetricSpecification, False),
+ 'DisableScaleIn': (boolean, False),
+ 'PredefinedMetricSpecification':
+ (PredefinedMetricSpecification, False),
+ 'TargetValue': (float, True),
+ }
+
+
class ScalingPolicy(AWSObject):
resource_type = "AWS::AutoScaling::ScalingPolicy"
@@ -219,6 +254,7 @@ class ScalingPolicy(AWSObject):
'PolicyType': (basestring, False),
'ScalingAdjustment': (integer, False),
'StepAdjustments': ([StepAdjustments], False),
+ 'TargetTrackingConfiguration': (TargetTrackingConfiguration, False),
}
|
Add TargetTrackingConfiguration to AutoScaling::ScalingPolicy
|
cloudtools_troposphere
|
train
|
1e8d8d7f183b264286de21d9ac1e07594aa3e86a
|
diff --git a/src/CRUDlex/Entity.php b/src/CRUDlex/Entity.php
index <HASH>..<HASH> 100644
--- a/src/CRUDlex/Entity.php
+++ b/src/CRUDlex/Entity.php
@@ -145,10 +145,13 @@ class Entity {
$this->set($field, $file->getClientOriginalName());
}
} else if ($type === 'many') {
- $many = array_map(function($id) {
- return ['id' => $id];
- }, $request->get($field));
- $this->set($field, $many);
+ $array = $request->get($field);
+ if (is_array($array)) {
+ $many = array_map(function($id) {
+ return ['id' => $id];
+ }, $array);
+ $this->set($field, $many);
+ }
} else {
$this->set($field, $request->get($field));
}
|
don't crash if no many value was given
|
philiplb_CRUDlex
|
train
|
d8e980a9dda8a1eb4eec259104042a44c79ba872
|
diff --git a/pake.py b/pake.py
index <HASH>..<HASH> 100644
--- a/pake.py
+++ b/pake.py
@@ -152,9 +152,7 @@ class Target(object):
content = urllib2.urlopen(url).read()
if md5 and hashlib.md5(content).hexdigest() != md5:
raise BuildError(self, 'corrupt download')
- # FIXME Python on Windoze corrupts the content when writing it
- # FIXME probably something to do with encodings
- with open(self.name, 'w') as f:
+ with open(self.name, 'wb') as f:
f.write(content)
def error(self, message):
@@ -178,6 +176,10 @@ class Target(object):
self.info('mkdir -p %s', path)
os.makedirs(path)
+ def newer(self, *args):
+ args = flatten_expand_list(args)
+ return [arg for arg in args if targets.get(arg).timestamp > self.timestamp]
+
def output(self, *args, **kwargs):
args = flatten_expand_list(args)
self.info(' '.join(args))
|
Upgrade to latest version of pake
|
openlayers_openlayers
|
train
|
77e2f1636eca738ba49945647b7c61313f1796a9
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -191,6 +191,10 @@ get information on a chat
##### `#getChatAdministrators(chatId)`
get the administrators of a chat
- chatId: the chat's id
+-
+##### `#getChatMembersCount(chatId)`
+get the number of members of a chat
+- chatId: the chat's id
### Additional methods:
diff --git a/src/apiclient.js b/src/apiclient.js
index <HASH>..<HASH> 100644
--- a/src/apiclient.js
+++ b/src/apiclient.js
@@ -229,6 +229,12 @@ function ApiClient(token){
return _get('getChatAdministrators', payload);
};
+ this.getChatMembersCount = function(chatId){
+ var payload = {
+ chat_id: chatId
+ };
+ return _get('getChatMembersCount', payload);
+ };
this.kickChatMember = function(chatId, userId){
var payload = {
diff --git a/test/test.js b/test/test.js
index <HASH>..<HASH> 100644
--- a/test/test.js
+++ b/test/test.js
@@ -190,13 +190,24 @@ describe('TelegramBotClient', function(){
this.timeout(10000);
var client = new TelegramBotClient(TOKEN);
it('gets infos about the bot', function(){
- return client.getChat(CHAT_ID).promise().then(function(res){
+ return client.getChatAdministrators(CHAT_ID).promise().then(function(res){
assert(res.result);
assert(Array.isArray(res.result));
});
});
});
+ describe('#getChatMembersCount(chatId)', function(){
+ this.timeout(10000);
+ var client = new TelegramBotClient(TOKEN);
+ it('gets infos about the bot', function(){
+ return client.getChatMembersCount(CHAT_ID).promise().then(function(res){
+ assert(res.result);
+ assert(isFinite(res.result));
+ });
+ });
+ });
+
describe('#getUpdates([options])', function(){
this.timeout(10000);
var client = new TelegramBotClient(TOKEN);
|
add getChatMembersCount method
|
m90_telegram-bot-client
|
train
|
87ba5d2b4b7a3bcbaf54394ae3a5d9671ba7aa79
|
diff --git a/ayrton/utils.py b/ayrton/utils.py
index <HASH>..<HASH> 100644
--- a/ayrton/utils.py
+++ b/ayrton/utils.py
@@ -100,10 +100,8 @@ def dump_dict (d, level=1): # pragma: no cover
def read (src, buf_len):
if isinstance (src, int):
return os.read (src, buf_len)
- elif isinstance (src, socket):
+ elif isinstance (src, (socket, paramiko.channel.Channel)):
return src.recv (buf_len)
- elif isinstance (src, paramiko.channel.Channel):
- return os.read (src.fileno (), buf_len)
else:
return src.read (buf_len)
@@ -111,7 +109,7 @@ def read (src, buf_len):
def write (dst, data):
if isinstance (dst, int):
return os.write (dst, data)
- elif isinstance (dst, socket):
+ elif isinstance (dst, (socket, paramiko.channel.Channel)):
return dst.send (data)
else:
ans= dst.write (data)
|
[*] paramiko.channel.Channel does not have read()/write() ops, but recv()/send().
|
StyXman_ayrton
|
train
|
0bf73877f860a86d9cf601154e9a9f76292e63c9
|
diff --git a/smmap/mman.py b/smmap/mman.py
index <HASH>..<HASH> 100644
--- a/smmap/mman.py
+++ b/smmap/mman.py
@@ -7,6 +7,7 @@ import sys
import mmap
from mmap import PAGESIZE
+from sys import getrefcount
#{ Utilities
@@ -71,7 +72,6 @@ class MappedRegion(object):
__slots__ = [
'_b' , # beginning of mapping
'_mf', # mapped memory chunk (as returned by mmap)
- '_nc', # number of clients using this region
'_uc', # total amount of usages
'_ms' # actual size of the mapping
]
@@ -90,24 +90,24 @@ class MappedRegion(object):
allocated the the size automatically adjusted
:raise Exception: if no memory can be allocated"""
self._b = ofs
- self._nc = 0
self._uc = 0
fd = os.open(path, os.O_RDONLY|getattr(os, 'O_BINARY', 0))
try:
kwargs = dict(access=mmap.ACCESS_READ, offset=ofs)
corrected_size = size
+ sizeofs = ofs
if self._need_compat_layer:
del(kwargs['offset'])
corrected_size += ofs
+ sizeofs = 0
# END handle python not supporting offset ! Arg
# have to correct size, otherwise (instead of the c version) it will
# bark that the size is too large ... many extra file accesses because
# if this ... argh !
- self._mf = mmap.mmap(fd, min(os.fstat(fd).st_size, corrected_size), **kwargs)
+ self._mf = mmap.mmap(fd, min(os.fstat(fd).st_size - sizeofs, corrected_size - sizeofs), **kwargs)
- print len(self._mf)
if self._need_compat_layer:
self._mfb = buffer(self._mf, ofs, size)
#END handle buffer wrapping
@@ -133,7 +133,8 @@ class MappedRegion(object):
def client_count(self):
""":return: number of clients currently using this region"""
- return self._nc
+ # -1: self on stack, -1 self in this method, -1 self in getrefcount
+ return getrefcount(self)-3
def adjust_client_count(self, ofs):
"""Adjust the client count by the given positive or negative offset"""
@@ -157,6 +158,15 @@ class MappedRegion(object):
#END handle compat layer
+class Cursor(object):
+ """Pointer into the mapped region of the memory manager, keeping the current window
+ alive until it is destroyed"""
+
+
+class MappedRegionList(list):
+ """List of MappedRegion instances with specific functionality"""
+
+
class MappedMemoryManager(object):
"""Maintains a list of ranges of mapped memory regions in one or more files and allows to easily
obtain additional regions assuring there is no overlap.
diff --git a/smmap/test/test_mman.py b/smmap/test/test_mman.py
index <HASH>..<HASH> 100644
--- a/smmap/test/test_mman.py
+++ b/smmap/test/test_mman.py
@@ -1,8 +1,11 @@
from lib import TestBase, FileCreator
from smmap.mman import *
-from smmap.mman import MappedRegion
+from smmap.mman import align_to_page
from smmap.mman import Window
+from smmap.mman import MappedRegion
+from smmap.mman import MappedRegionList
+from smmap.mman import Cursor
import sys
import mmap
@@ -56,11 +59,10 @@ class TestMMan(TestBase):
wc.align()
assert wc.ofs == 0 and wc.size == mmap.PAGESIZE*2
-
def test_region(self):
fc = FileCreator(self._window_test_size, "window_test")
half_size = fc.size / 2
- rofs = 4000
+ rofs = align_to_page(4200, False)
rfull = MappedRegion(fc.path, 0, fc.size)
rhalfofs = MappedRegion(fc.path, rofs, fc.size)
rhalfsize = MappedRegion(fc.path, 0, half_size)
@@ -76,10 +78,20 @@ class TestMMan(TestBase):
assert not rfull.includes_ofs(-1) and not rfull.includes_ofs(sys.maxint)
assert rhalfofs.includes_ofs(rofs) and not rhalfofs.includes_ofs(0)
+ # auto-refcount
+ assert rfull.client_count() == 1
+ rfull2 = rfull
+ assert rfull.client_count() == 2
+
# window constructor
w = Window.from_region(rfull)
assert w.ofs == rfull.ofs_begin() and w.ofs_end() == rfull.ofs_end()
+ def test_region_list(self):
+ pass
+
+ def test_cursor(self):
+ pass
def test_basics(self):
pass
|
Fixed bug in test case as it didn't properly align its offset to a page
|
gitpython-developers_smmap
|
train
|
a7a536ec07381178ace6e3abd6b85a5a7f88f012
|
diff --git a/tests/sample/morris/test_morris_strategies.py b/tests/sample/morris/test_morris_strategies.py
index <HASH>..<HASH> 100644
--- a/tests/sample/morris/test_morris_strategies.py
+++ b/tests/sample/morris/test_morris_strategies.py
@@ -7,8 +7,10 @@ from SALib.sample.morris.brute import BruteForce
from SALib.util import read_param_file
import numpy as np
+import pytest
from numpy.testing import assert_equal, assert_allclose
from pytest import fixture, raises
+import numpy.random as rd
@fixture(scope='function')
@@ -156,6 +158,9 @@ class TestSharedMethods:
class TestLocallyOptimalStrategy:
def test_local(self, setup_problem):
+
+ rd.seed(12345)
+
(input_sample, num_samples, _,
k_choices, groups, num_params, expected) = setup_problem
@@ -168,11 +173,18 @@ class TestLocallyOptimalStrategy:
def test_find_local_maximum_distance(self, setup_input):
'''
Test whether finding the local maximum distance equals the global
- maximum distance in a simple case.
+ maximum distance in a simple case for a defined random seed.
From Saltelli et al. 2008, in the solution to exercise 3a,
Chapter 3, page 134.
+
+ Note that local and brute force methods are not guaranteed to produce
+ the same results, even for simple problems,
+ hence forcing the seed here.
+
'''
+ rd.seed(12345)
+
local_strategy = LocalOptimisation()
brute_strategy = BruteForce()
@@ -187,14 +199,39 @@ class TestLocallyOptimalStrategy:
num_params, k_choices)
assert_equal(output_global, output_local)
+ def test_random_seed(self, setup_param_groups_prime):
+ """Setting the seed before generating a sample results in two
+ identical samples
+ """
+ N = 8
+ param_file = setup_param_groups_prime
+ problem = read_param_file(param_file)
+ num_levels = 4
+ grid_jump = num_levels / 2
+
+ np.random.seed(12345)
+ expected = _sample_groups(problem, N, num_levels, grid_jump)
+
+ np.random.seed(12345)
+ actual = _sample_groups(problem, N, num_levels, grid_jump)
+
+ assert_equal(actual, expected)
+
+ @pytest.mark.parametrize('execution_number', range(1))
def test_local_optimised_groups(self,
- setup_param_groups_prime):
+ setup_param_groups_prime,
+ execution_number):
"""
Tests that the local optimisation problem gives
the same answer as the brute force problem
(for small values of `k_choices` and `N`)
- with groups
+ with groups for a defined random seed.
+
+ Note that local and brute force methods are not guaranteed to produce
+ exact answers, even for small problems.
"""
+ rd.seed(12345)
+
N = 8
param_file = setup_param_groups_prime
problem = read_param_file(param_file)
@@ -208,11 +245,11 @@ class TestLocallyOptimalStrategy:
input_sample = _sample_groups(problem, N, num_levels, grid_jump)
- strategy = LocalOptimisation()
+ local = LocalOptimisation()
# From local optimal trajectories
- actual = strategy.find_local_maximum(input_sample, N, num_params,
- k_choices, num_groups)
+ actual = local.find_local_maximum(input_sample, N, num_params,
+ k_choices, num_groups)
brute = BruteForce()
desired = brute.brute_force_most_distant(input_sample,
@@ -220,6 +257,9 @@ class TestLocallyOptimalStrategy:
num_params,
k_choices,
num_groups)
+
+ print("Actual: {}\nDesired: {}\n".format(actual, desired))
+ print(input_sample)
assert_equal(actual, desired)
|
Adds fixed random seeds to failing tests
|
SALib_SALib
|
train
|
63f17cd0f9804ab16c901f3c75d17acfbcb42cf4
|
diff --git a/js/language/c.js b/js/language/c.js
index <HASH>..<HASH> 100644
--- a/js/language/c.js
+++ b/js/language/c.js
@@ -7,6 +7,7 @@
*/
Rainbow.extend('c', [
{
+ 'name': 'meta.preprocessor',
'matches': {
1: [
{
@@ -14,11 +15,11 @@ Rainbow.extend('c', [
1: 'keyword.define',
2: 'entity.name'
},
- 'pattern': /(\#\w+)\s(\w+)\b/g
+ 'pattern': /(\w+)\s(\w+)\b/g
},
{
'name': 'keyword.define',
- 'pattern': /\#endif/g
+ 'pattern': /endif/g
},
{
'name': 'constant.numeric',
@@ -29,11 +30,11 @@ Rainbow.extend('c', [
1: 'keyword.include',
2: 'string'
},
- 'pattern': /(\#include)\s(.*?)$/g
+ 'pattern': /(include)\s(.*?)$/g
}
]
},
- 'pattern': /(\#[\S\s]*?)$/gm
+ 'pattern': /\#([\S\s]*?)$/gm
},
{
'name': 'keyword',
|
Preprocessor tweaks
-Keep the hash separate from the group matches
-Add a global class to the entire group
|
ccampbell_rainbow
|
train
|
98056a680fde6bede9ce4c159b72d1ac01bf9067
|
diff --git a/setuptools/tests/test_test.py b/setuptools/tests/test_test.py
index <HASH>..<HASH> 100644
--- a/setuptools/tests/test_test.py
+++ b/setuptools/tests/test_test.py
@@ -93,10 +93,6 @@ def test_test(capfd):
assert out == 'Foo\n'
-@pytest.mark.skipif(
- sys.version_info < (2, 7),
- reason="No discover support for unittest on Python 2.6",
-)
@pytest.mark.usefixtures('tmpdir_cwd', 'quiet_log')
def test_tests_are_run_once(capfd):
params = dict(
diff --git a/setuptools/tests/test_virtualenv.py b/setuptools/tests/test_virtualenv.py
index <HASH>..<HASH> 100644
--- a/setuptools/tests/test_virtualenv.py
+++ b/setuptools/tests/test_virtualenv.py
@@ -57,9 +57,6 @@ def test_pip_upgrade_from_source(virtualenv):
Check pip can upgrade setuptools from source.
"""
dist_dir = virtualenv.workspace
- if sys.version_info < (2, 7):
- # Python 2.6 support was dropped in wheel 0.30.0.
- virtualenv.run('pip install -U "wheel<0.30.0"')
# Generate source distribution / wheel.
virtualenv.run(' && '.join((
'cd {source}',
|
Remove pytest marker and code for Python < <I>
|
pypa_setuptools
|
train
|
b8a7013f62afd02c7bddc3d5c4022a215ca9bd7d
|
diff --git a/lib/adapter.js b/lib/adapter.js
index <HASH>..<HASH> 100644
--- a/lib/adapter.js
+++ b/lib/adapter.js
@@ -3,13 +3,20 @@
* Licensed under the terms of the MIT License (see LICENSE.md).
*/
-( function( window ) {
+( function( window, factory ) {
'use strict';
+ // Chai doesn't go global if AMD is available in the page, so we must retrieve it in two different ways.
+ if ( typeof define == 'function' && define.amd ) {
+ require( [ 'chai' ], factory );
+ } else {
+ factory( chai );
+ }
+} )( this, function( chai ) {
// fix for PhantomJS issue
window.should = null;
window.should = chai.should();
window.expect = chai.expect;
window.assert = chai.assert;
-} )( this );
+} );
|
Made the adapter compatible with chai in AMD.
|
benderjs_benderjs-chai
|
train
|
85e1c2127c7f68f6d980125802b85325a3aac568
|
diff --git a/src/com/opera/core/systems/OperaDesktopDriver.java b/src/com/opera/core/systems/OperaDesktopDriver.java
index <HASH>..<HASH> 100644
--- a/src/com/opera/core/systems/OperaDesktopDriver.java
+++ b/src/com/opera/core/systems/OperaDesktopDriver.java
@@ -116,6 +116,10 @@ public class OperaDesktopDriver extends OperaDriver {
return widget;
}
+ public QuickWindow findWindowByName(String windowName){
+ return desktopWindowManager.getQuickWindow(QuickWidgetSearchType.NAME, windowName);
+ }
+
/**
* @param windowId
* @return String: name of the window
diff --git a/src/com/opera/core/systems/QuickWidget.java b/src/com/opera/core/systems/QuickWidget.java
index <HASH>..<HASH> 100644
--- a/src/com/opera/core/systems/QuickWidget.java
+++ b/src/com/opera/core/systems/QuickWidget.java
@@ -149,7 +149,7 @@ public class QuickWidget {
/**
* @return DesktopWindowRect of the widget
*/
- private DesktopWindowRect getRect() {
+ public DesktopWindowRect getRect() {
return info.getRect();
}
diff --git a/src/com/opera/core/systems/QuickWindow.java b/src/com/opera/core/systems/QuickWindow.java
index <HASH>..<HASH> 100644
--- a/src/com/opera/core/systems/QuickWindow.java
+++ b/src/com/opera/core/systems/QuickWindow.java
@@ -58,7 +58,7 @@ public class QuickWindow {
/**
* @return DesktopWindowRect of the widget
*/
- private DesktopWindowRect getRect() {
+ public DesktopWindowRect getRect() {
return info.getRect();
}
@@ -77,7 +77,7 @@ public class QuickWindow {
DesktopWindowRect rect = getRect();
return new Dimension(rect.getWidth(), rect.getHeight());
}
-
+
@Override
// TODO: FIXME
public boolean equals(Object obj) {
diff --git a/src/com/opera/core/systems/RunDriver.java b/src/com/opera/core/systems/RunDriver.java
index <HASH>..<HASH> 100644
--- a/src/com/opera/core/systems/RunDriver.java
+++ b/src/com/opera/core/systems/RunDriver.java
@@ -28,6 +28,16 @@ class RunDriver {
// String window_name = "New Preferences Dialog", action_name = "Show preferences";
String window_name = "", action_name = "Delete private data";
+ QuickWindow qw = driver.findWindowByName("Browser Window");
+ QuickWidget tb = driver.findWidgetByName(qw.getWindowID(), "Status Toolbar Head");
+ QuickWidget b = driver.findWidgetByName(qw.getWindowID(), "tbb_Panel", "Status Toolbar Head");
+
+ ArrayList mods = new ArrayList();
+ mods.add(ModifierPressed.NONE);
+
+ b.click(MouseButton.LEFT, 1, mods);
+
+/*
driver.waitStart(); // wait for dialog to open
System.out.println("-- wait for dialog -- ");
driver.operaDesktopAction(action_name);
@@ -61,7 +71,7 @@ class RunDriver {
}
-
+ */
/*
driver.waitStart();
diff --git a/src/com/opera/core/systems/scope/services/IDesktopWindowManager.java b/src/com/opera/core/systems/scope/services/IDesktopWindowManager.java
index <HASH>..<HASH> 100644
--- a/src/com/opera/core/systems/scope/services/IDesktopWindowManager.java
+++ b/src/com/opera/core/systems/scope/services/IDesktopWindowManager.java
@@ -71,6 +71,15 @@ public interface IDesktopWindowManager {
QuickWidget getQuickWidget(int id, QuickWidgetSearchType property, String value, String parentName);
/*
+ * Get the quick window with value value for property property
+ *
+ * @param property
+ * @param value - value of property given
+ * @return
+ */
+ QuickWindow getQuickWindow(QuickWidgetSearchType property, String value);
+
+ /*
* Get the string specified by the given string id
* @param enum_text
* @return
diff --git a/src/com/opera/core/systems/scope/services/ums/DesktopWindowManager.java b/src/com/opera/core/systems/scope/services/ums/DesktopWindowManager.java
index <HASH>..<HASH> 100644
--- a/src/com/opera/core/systems/scope/services/ums/DesktopWindowManager.java
+++ b/src/com/opera/core/systems/scope/services/ums/DesktopWindowManager.java
@@ -128,7 +128,20 @@ public class DesktopWindowManager extends AbstractService implements IDesktopWin
}
return null;
}
-
+
+ public QuickWindow getQuickWindow(QuickWidgetSearchType property, String value)
+ {
+ List<QuickWindow> windows = getQuickWindowList();
+ for (QuickWindow window : windows) {
+ if (property.equals(QuickWidgetSearchType.NAME)){
+ if (window.getName().equals(value)) {
+ return window;
+ }
+ }
+ }
+ return null;
+ }
+
public List<QuickWidget> getQuickWidgetList(int id) {
if (id <= 0)
id = getActiveWindowId();
|
Updated web-driver to find quick windows and return sizes
|
operasoftware_operaprestodriver
|
train
|
2f7da7d7c369508fde10a2580256c563a2eff62e
|
diff --git a/lib/discordrb/data.rb b/lib/discordrb/data.rb
index <HASH>..<HASH> 100644
--- a/lib/discordrb/data.rb
+++ b/lib/discordrb/data.rb
@@ -796,7 +796,7 @@ module Discordrb
# @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech.
# @return [Message] the message that was sent.
def send_message(content, tts = false)
- @bot.send_message(@id, content, tts)
+ @bot.send_message(@id, content, tts, @server && @server.id)
end
# Sends multiple messages to a channel
|
Send the server ID (if it exists) to Bot#send_message in Channel#send_message
|
meew0_discordrb
|
train
|
946c9b2f92a00f23a9ac1145675628db8b3800ad
|
diff --git a/ds4drv/actions.py b/ds4drv/actions.py
index <HASH>..<HASH> 100644
--- a/ds4drv/actions.py
+++ b/ds4drv/actions.py
@@ -73,10 +73,11 @@ class ReportActionBinding(ReportAction):
def handle_report(self, report):
for combo, action in self.bindings.items():
- active = all(getattr(report, button) for button in combo)
- released = not any(getattr(report, button) for button in combo)
+ modifiers = all(getattr(report, button) for button in combo[:-1])
+ active = getattr(report, combo[-1])
+ released = not active
- if active and combo not in self.active:
+ if modifiers and active and combo not in self.active:
self.active.add(combo)
elif released and combo in self.active:
self.active.remove(combo)
|
actions: Improve button combo usage.
Only require last button to be released before triggering a action
instead of the whole combo.
|
chrippa_ds4drv
|
train
|
6ed58fe1e9f214a2d4b6f245e80860a829d61706
|
diff --git a/lib/rspec_command/rake.rb b/lib/rspec_command/rake.rb
index <HASH>..<HASH> 100644
--- a/lib/rspec_command/rake.rb
+++ b/lib/rspec_command/rake.rb
@@ -62,7 +62,9 @@ module RSpecCommand
Process.waitpid fork {
# This has to be nocov because simpldecov doesn't track across fork.
# :nocov:
- # Defang SimpleCov so it doesn't print its stuff.
+ # Defang SimpleCov so it doesn't print its stuff. Can be removed
+ # when https://github.com/colszowka/simplecov/pull/377 is in a
+ # released version.
if defined?(SimpleCov)
SimpleCov.at_exit { SimpleCov.instance_variable_set(:@result, nil) }
end
|
Add a note about the PR on simplecov to fix this more globally.
|
coderanger_rspec-command
|
train
|
a1327affcffe36113b80afa08a7678e118364cb7
|
diff --git a/public/js/meme_captain.js b/public/js/meme_captain.js
index <HASH>..<HASH> 100644
--- a/public/js/meme_captain.js
+++ b/public/js/meme_captain.js
@@ -184,7 +184,8 @@ var MEMECAPTAIN = (function (window, $, fabric) {
left : canvas.getWidth() / 2.0,
width : textWidth,
height : textHeight,
- fill : 'red'
+ fill : 'red',
+ cornersize : 20
});
rect1.name = '1';
@@ -197,7 +198,8 @@ var MEMECAPTAIN = (function (window, $, fabric) {
left : canvas.getWidth() / 2.0,
width : textWidth,
height : textHeight,
- fill: 'red'
+ fill : 'red',
+ cornersize : 20
});
rect2.name = '2';
|
Increase text positioning widget corner size.
Larger corners make it easier to use on touchscreen devices.
|
mmb_meme_captain
|
train
|
4d3ff312e8edc120b0190ac185eefe930c4f53ba
|
diff --git a/pecan/tests/test_scaffolds.py b/pecan/tests/test_scaffolds.py
index <HASH>..<HASH> 100644
--- a/pecan/tests/test_scaffolds.py
+++ b/pecan/tests/test_scaffolds.py
@@ -372,14 +372,14 @@ class TestGunicornServeCommand(TestTemplateBuilds):
super(TestGunicornServeCommand, self).create_virtualenv()
# Install gunicorn
- self.gunicorn_exe = self.install_dependency('gunicorn')
+ self.install_dependency('gunicorn')
- def install_dependency(self, name):
- return super(
- TestGunicornServeCommand,
- self
- ).install_dependency(name).replace(
- 'gunicorn', 'gunicorn_pecan'
+ @property
+ def gunicorn_exe(self):
+ return os.path.join(
+ self.install_dir,
+ 'bin',
+ 'gunicorn_pecan'
)
def poll_gunicorn(self, proc, port):
|
A big of refactoring for the ``$ gunicorn_pecan`` tests.
|
pecan_pecan
|
train
|
c2f9d846953c88a47398572dd35b99a8bfcda3de
|
diff --git a/src/compatibility/json.js b/src/compatibility/json.js
index <HASH>..<HASH> 100644
--- a/src/compatibility/json.js
+++ b/src/compatibility/json.js
@@ -17,8 +17,6 @@ _gpfCompatibilityInstallGlobal("JSON", {
/*#ifndef(UMD)*/
// Generates an empty function to reflect the null complexity of this module
-function _gpfCompatibilityJson () {}
-/*exported _gpfCompatibilityJson*/
+(function _gpfCompatibilityJson () {}());
/*#endif*/
-
|
Also consider coverage (#<I>)
|
ArnaudBuchholz_gpf-js
|
train
|
a817b6ed35c645bb4a197de3f2c9f3b4dd93bde2
|
diff --git a/molgenis-model-registry/src/main/java/org/molgenis/standardsregistry/StandardsRegistryController.java b/molgenis-model-registry/src/main/java/org/molgenis/standardsregistry/StandardsRegistryController.java
index <HASH>..<HASH> 100644
--- a/molgenis-model-registry/src/main/java/org/molgenis/standardsregistry/StandardsRegistryController.java
+++ b/molgenis-model-registry/src/main/java/org/molgenis/standardsregistry/StandardsRegistryController.java
@@ -94,8 +94,7 @@ public class StandardsRegistryController extends MolgenisPluginController
int total = packageResponses.size();
if (packageSearchRequest.getOffset() != null)
{
- packageResponses = packageResponses.subList(packageSearchRequest.getOffset(),
- packageResponses.size() - 1);
+ packageResponses = packageResponses.subList(packageSearchRequest.getOffset(), packageResponses.size());
}
if (packageSearchRequest.getNum() != null && packageResponses.size() > packageSearchRequest.getNum())
{
|
Fix last model not displayed in standards registry
|
molgenis_molgenis
|
train
|
3a5315d54047f06732d3f751130193fba32983cf
|
diff --git a/controller/Results.php b/controller/Results.php
index <HASH>..<HASH> 100644
--- a/controller/Results.php
+++ b/controller/Results.php
@@ -22,6 +22,7 @@
namespace oat\taoOutcomeUi\controller;
use \Exception;
+use \common_exception_BadRequest;
use \core_kernel_classes_Resource;
use oat\generis\model\GenerisRdf;
use oat\generis\model\OntologyRdfs;
@@ -237,12 +238,13 @@ class Results extends \tao_actions_CommonModule
/**
* Delete a result or a result class
* @throws Exception
+ * @throws common_exception_BadRequest
* @return string json {'deleted' : true}
*/
public function delete()
{
if (!tao_helpers_Request::isAjax()) {
- throw new Exception("wrong request mode");
+ throw new common_exception_BadRequest('wrong request mode');
}
$deliveryExecutionUri = tao_helpers_Uri::decode($this->getRequestParameter('uri'));
$de = $this->getServiceProxy()->getDeliveryExecution($deliveryExecutionUri);
diff --git a/manifest.php b/manifest.php
index <HASH>..<HASH> 100644
--- a/manifest.php
+++ b/manifest.php
@@ -37,7 +37,7 @@ return [
'label' => 'Result visualisation',
'description' => 'TAO Results extension',
'license' => 'GPL-2.0',
- 'version' => '7.2.1',
+ 'version' => '7.3.0',
'author' => 'Open Assessment Technologies, CRP Henri Tudor',
// taoItems is only needed for the item model property retrieval
'requires' => [
diff --git a/scripts/update/Updater.php b/scripts/update/Updater.php
index <HASH>..<HASH> 100644
--- a/scripts/update/Updater.php
+++ b/scripts/update/Updater.php
@@ -170,7 +170,7 @@ class Updater extends \common_ext_ExtensionUpdater
$this->setVersion('5.13.0');
}
- $this->skip('5.13.0', '7.2.1');
+ $this->skip('5.13.0', '7.3.0');
}
}
|
Throw bad request exception when request mode is wrong
|
oat-sa_extension-tao-outcomeui
|
train
|
04cd3801e31e148356f7a3b0b7a0c1e6d42bcb0f
|
diff --git a/libsubmit/utils.py b/libsubmit/utils.py
index <HASH>..<HASH> 100644
--- a/libsubmit/utils.py
+++ b/libsubmit/utils.py
@@ -45,7 +45,10 @@ class RepresentationMixin(object):
def __repr__(self):
argspec = inspect.getargspec(self.__init__)
- defaults = dict(zip(reversed(argspec.args), reversed(argspec.defaults)))
+ if len(argspec.args) > 1:
+ defaults = dict(zip(reversed(argspec.args), reversed(argspec.defaults)))
+ else:
+ defaults = []
for arg in argspec.args[1:]:
if not hasattr(self, arg):
|
Fix rep mixin when there are no args
Fixes Parsl/parsl#<I>.
|
Parsl_libsubmit
|
train
|
8b6dc3a38e9b7c53fb6c3f93dbd726b21c7785ef
|
diff --git a/imgaug/augmenters/convolutional.py b/imgaug/augmenters/convolutional.py
index <HASH>..<HASH> 100644
--- a/imgaug/augmenters/convolutional.py
+++ b/imgaug/augmenters/convolutional.py
@@ -395,17 +395,19 @@ def DirectedEdgeDetect(alpha=0, direction=(0.0, 1.0), name=None, deterministic=F
Parameters
----------
- alpha : int or float or tuple of two ints/floats or StochasticParameter, optional(default=0)
+ alpha : number or tuple of number or list of number or StochasticParameter, optional(default=0)
Visibility of the sharpened image. At 0, only the original image is
visible, at 1.0 only its sharpened version is visible.
* If an int or float, exactly that value will be used.
* If a tuple (a, b), a random value from the range a <= x <= b will
be sampled per image.
+ * If a list, then a random value will be sampled from that list
+ per image.
* If a StochasticParameter, a value will be sampled from the
parameter per image.
- direction : int or float or tuple of two ints/floats or StochasticParameter, optional(default=(0.0, 1.0))
+ direction : number or tuple of number or list of number or StochasticParameter, optional(default=(0.0, 1.0))
Angle of edges to pronounce, where 0 represents 0 degrees and 1.0
represents 360 degrees (both clockwise, starting at the top).
Default value is (0.0, 1.0), i.e. pick a random angle per image.
@@ -413,6 +415,8 @@ def DirectedEdgeDetect(alpha=0, direction=(0.0, 1.0), name=None, deterministic=F
* If an int or float, exactly that value will be used.
* If a tuple (a, b), a random value from the range a <= x <= b will
be sampled per image.
+ * If a list, then a random value will be sampled from that list
+ per image.
* If a StochasticParameter, a value will be sampled from the
parameter per image.
@@ -451,25 +455,8 @@ def DirectedEdgeDetect(alpha=0, direction=(0.0, 1.0), name=None, deterministic=F
(e.g. for 0.3 then `0.7*old_image + 0.3*edge_image`).
"""
- if ia.is_single_number(alpha):
- alpha_param = Deterministic(alpha)
- elif ia.is_iterable(alpha):
- ia.do_assert(len(alpha) == 2, "Expected tuple/list with 2 entries, got %d entries." % (len(alpha),))
- alpha_param = Uniform(alpha[0], alpha[1])
- elif isinstance(alpha, StochasticParameter):
- alpha_param = alpha
- else:
- raise Exception("Expected float, int, tuple/list with 2 entries or StochasticParameter. Got %s." % (type(alpha),))
-
- if ia.is_single_number(direction):
- direction_param = Deterministic(direction)
- elif ia.is_iterable(direction):
- ia.do_assert(len(direction) == 2, "Expected tuple/list with 2 entries, got %d entries." % (len(direction),))
- direction_param = Uniform(direction[0], direction[1])
- elif isinstance(direction, StochasticParameter):
- direction_param = direction
- else:
- raise Exception("Expected float, int, tuple/list with 2 entries or StochasticParameter. Got %s." % (type(direction),))
+ alpha_param = iap.handle_continuous_param(alpha, "alpha", value_range=(0, 1.0), tuple_to_uniform=True, list_to_choice=True)
+ direction_param = iap.handle_continuous_param(direction, "direction", value_range=None, tuple_to_uniform=True, list_to_choice=True)
def create_matrices(image, nb_channels, random_state_func):
alpha_sample = alpha_param.draw_sample(random_state=random_state_func)
|
Reduce code duplication in DirectedEdgeDetect
This commit decreases code duplication in the
parameter parsing of
augmenters.convolutional.DirectedEdgeDetect
by using the parameter handling function
in parameters.py.
Additionally, alpha and direction now supports
lists, which are interpreted as Choices.
|
aleju_imgaug
|
train
|
201dc9eef2f2723118b48728c6955556f97e9743
|
diff --git a/tinymongo/tinymongo.py b/tinymongo/tinymongo.py
index <HASH>..<HASH> 100644
--- a/tinymongo/tinymongo.py
+++ b/tinymongo/tinymongo.py
@@ -115,7 +115,7 @@ class TinyMongoCollection(object):
def count(self):
if self.table is None:self.buildTable()
- return self.table.count(self.lastcond)
+ return len(self.table)
class TinyMongoCursor(object):
|
Count command should get all documents.
If we use lastcond, the user does not know why. The pymongo specs at <URL>
|
schapman1974_tinymongo
|
train
|
14f2e52e8da86609748acbce45550d7d8de595fc
|
diff --git a/test/kv.go b/test/kv.go
index <HASH>..<HASH> 100644
--- a/test/kv.go
+++ b/test/kv.go
@@ -400,7 +400,7 @@ func concurrentEnum(kv kvdb.Kvdb, t *testing.T) {
for i := 0; i < 3; i++ {
go func() {
id := atomic.AddInt32(&shared, 1)
- fmt.Printf("> Adder #%d started ...\n", id)
+ fmt.Printf("+> Adder #%d started\n", id)
content := []byte(fmt.Sprintf("adder #%d", id))
wg.Add(1)
defer wg.Done()
@@ -408,14 +408,14 @@ func concurrentEnum(kv kvdb.Kvdb, t *testing.T) {
for j := 0; ; j++ {
select {
case <-quit:
- fmt.Printf("> Adder #%d quit ...\n", id)
+ fmt.Printf("+> Adder #%d quit (stored %d keys)\n", id, j)
return
default:
key := fmt.Sprintf("%s/%d-%d", prefix, id, j%100000)
_, err := kv.Put(key, content, 0)
assert.NoError(t, err, "Unexpected error on Put")
// sleep a bit, not to be overly aggressive
- time.Sleep(time.Duration(rand.Intn(50)) * time.Millisecond)
+ time.Sleep(time.Duration(rand.Intn(10)) * time.Millisecond)
}
}
assert.Fail(t, "I should not be here")
@@ -427,12 +427,12 @@ func concurrentEnum(kv kvdb.Kvdb, t *testing.T) {
go func() {
wg.Add(1)
defer wg.Done()
- fmt.Printf("> Deleter started ...\n")
+ fmt.Printf("+> Deleter started\n")
_ = <-latch // sync-point
for j := 0; ; { // cap at max 100k
select {
case <-quit:
- fmt.Printf("> Deleter quit ...\n")
+ fmt.Printf("+> Deleter quit (deleted %d keys)\n", j)
return
default:
key := fmt.Sprintf("%s/%d-%d", prefix, rand.Intn(numGoroutines), j%100000)
@@ -442,36 +442,41 @@ func concurrentEnum(kv kvdb.Kvdb, t *testing.T) {
j++
}
// sleep a bit, not to be overly aggressive
- time.Sleep(time.Duration(rand.Intn(50)) * time.Millisecond)
+ time.Sleep(time.Duration(rand.Intn(10)) * time.Millisecond)
}
}
assert.Fail(t, "I should not be here")
}()
numGoroutines++
- fmt.Printf("> MAIN wait ...\n")
+ fmt.Printf("> MAIN waiting for workers\n")
time.Sleep(50 * time.Millisecond)
close(latch) // release sync-points
- time.Sleep(1500 * time.Millisecond)
+ time.Sleep(5500 * time.Millisecond)
// make sure these two just work, otherwise we cannot assume how many elements found
- fmt.Printf("> MAIN run Enum ...\n")
- _, err := kv.Enumerate(prefix)
- assert.NoError(t, err)
-
- fmt.Printf("> MAIN run Keys ...\n")
- _, err = kv.Keys(prefix, "")
- assert.NoError(t, err)
+ sep := ':'
+ fmt.Printf("> MAIN run")
+ for i := 0; i < 5; i++ {
+ fmt.Printf("%c Enumerate", sep)
+ _, err := kv.Enumerate(prefix)
+ assert.NoError(t, err)
+
+ sep = ','
+ fmt.Printf("%c Keys", sep)
+ _, err = kv.Keys(prefix, "")
+ assert.NoError(t, err)
+ }
- fmt.Printf("> MAIN quit goroutines ...\n")
+ fmt.Printf("%c stop workers\n", sep)
for i := 0; i < numGoroutines; i++ {
quit <- true
}
close(quit)
- fmt.Printf("> MAIN waiting ...\n")
+ fmt.Printf("> MAIN waiting ...")
wg.Wait()
- fmt.Printf("> MAIN done ...\n")
+ fmt.Printf("DONE.\n")
}
func snapshot(kv kvdb.Kvdb, t *testing.T) {
|
concurrentEnum test runs more iterations
|
portworx_kvdb
|
train
|
93922bf9e62969b515c221efc8fe6f392a53c83f
|
diff --git a/descriptor/fingerprint/src/test/java/org/openscience/cdk/fingerprint/CircularFingerprintSmartsTest.java b/descriptor/fingerprint/src/test/java/org/openscience/cdk/fingerprint/CircularFingerprintSmartsTest.java
index <HASH>..<HASH> 100644
--- a/descriptor/fingerprint/src/test/java/org/openscience/cdk/fingerprint/CircularFingerprintSmartsTest.java
+++ b/descriptor/fingerprint/src/test/java/org/openscience/cdk/fingerprint/CircularFingerprintSmartsTest.java
@@ -1,6 +1,5 @@
package org.openscience.cdk.fingerprint;
-import org.junit.Assert;
import org.junit.Test;
import org.openscience.cdk.CDKTestCase;
import org.openscience.cdk.fingerprint.CircularFingerprinter.FP;
@@ -10,6 +9,14 @@ import org.openscience.cdk.smiles.SmilesParser;
import org.openscience.cdk.tools.ILoggingTool;
import org.openscience.cdk.tools.LoggingToolFactory;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+
+import static org.hamcrest.CoreMatchers.everyItem;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.collection.IsIn.isIn;
+
/**
* @cdk.module test-standard
*/
@@ -91,6 +98,11 @@ public class CircularFingerprintSmartsTest extends CDKTestCase {
private void checkFPSmartsForMolecule(String moleculeSmiles,
String expectedFPSmarts[][]) throws Exception {
+
+ Set<String> expected = new HashSet<>();
+ for (String[] strs : expectedFPSmarts)
+ Collections.addAll(expected, strs);
+
// expectedFPSmarts[][] is a double array because for each smarts
// several equivalent variants
// of the smarts are given e.g. CCC C(C)C
@@ -99,22 +111,13 @@ public class CircularFingerprintSmartsTest extends CDKTestCase {
CircularFingerprinter circ = new CircularFingerprinter();
circ.calculate(mol);
int numFP = circ.getFPCount();
+
+ Set<String> actual = new HashSet<>();
for (int i = 0; i < numFP; i++) {
FP fp = circ.getFP(i);
- String smarts = circ.getFPSmarts(fp, mol);
- int res = findSmarts(smarts, expectedFPSmarts);
- Assert.assertEquals("serching fp smarts: " + smarts, true, res >= 0);
+ actual.add(circ.getFPSmarts(fp, mol));
}
- }
- private int findSmarts(String smarts, String smartsSet[][]) {
- for (int i = 0; i < smartsSet.length; i++) {
- String s[] = smartsSet[i];
- for (int k = 0; k < s.length; k++)
- if (s[k].equals(smarts))
- return i;
- }
- return -1;
+ assertThat(actual, everyItem(isIn(expected)));
}
-
}
|
More verbose unit testing with hamcrest matchers.
|
cdk_cdk
|
train
|
f5e17fce654ffb1a405001e04362eee409df28c9
|
diff --git a/fastods/src/main/java/com/github/jferard/fastods/style/TableCellStyle.java b/fastods/src/main/java/com/github/jferard/fastods/style/TableCellStyle.java
index <HASH>..<HASH> 100644
--- a/fastods/src/main/java/com/github/jferard/fastods/style/TableCellStyle.java
+++ b/fastods/src/main/java/com/github/jferard/fastods/style/TableCellStyle.java
@@ -67,6 +67,7 @@ public class TableCellStyle implements ObjectStyle {
private final Align textAlign; // 'center','end','start','justify'
private final TextProperties textProperties;
private final VerticalAlign verticalAlign; // 'middle', 'bottom', 'top'
+ private final TextRotating rotating;
private final boolean wrap; // No line wrap when false, line wrap when
private final DataStyle dataStyle;
private String key;
@@ -89,7 +90,7 @@ public class TableCellStyle implements ObjectStyle {
TableCellStyle(final String name, final boolean hidden, final DataStyle dataStyle, final Color backgroundColor,
final TextProperties textProperties, final Align textAlign, final VerticalAlign verticalAlign,
final boolean wrap, final TableCellStyle parentCellStyle, final Borders borders,
- final Margins margins) {
+ final Margins margins, final TextRotating textRotating) {
this.hidden = hidden;
this.borders = borders;
this.margins = margins;
@@ -101,6 +102,7 @@ public class TableCellStyle implements ObjectStyle {
this.verticalAlign = verticalAlign;
this.wrap = wrap;
this.parentCellStyle = parentCellStyle;
+ this.rotating = textRotating;
}
@Override
@@ -118,7 +120,8 @@ public class TableCellStyle implements ObjectStyle {
if (this.verticalAlign != null)
util.appendAttribute(appendable, "style:vertical-align", this.verticalAlign.attrValue);
-
+ if (this.rotating!=null)
+ util.appendAttribute(appendable, "style:rotation-angle", this.rotating.attrValue);
this.borders.appendXMLContent(util, appendable);
if (this.wrap) util.appendAttribute(appendable, "fo:wrap-option", "wrap");
@@ -201,7 +204,7 @@ public class TableCellStyle implements ObjectStyle {
private boolean hasCellProperties() {
return this.backgroundColor != SimpleColor.NONE || this.verticalAlign != null || !this.borders
- .areVoid() || this.wrap;
+ .areVoid() || this.wrap || this.rotating!=null;
}
/**
@@ -224,6 +227,24 @@ public class TableCellStyle implements ObjectStyle {
}
/**
+ * Text rotation
+ * 20.339 style:rotation-angle http://docs.oasis-open.org/office/v1.2/os/OpenDocument-v1.2-os-part1.html#__RefHeading__1420142_253892949
+ */
+ public enum TextRotating
+ {
+
+ NO_ROTATING("0"),
+ ROTATE_90("90"),
+ ROTATE_180("180"),
+ ROTATE_270("270");
+
+ private final String attrValue;
+
+ TextRotating(final String attrValue) {
+ this.attrValue = attrValue;
+ }
+ }
+ /**
* An horizontal alignment.
* 20.216 fo:text-align. See https://www.w3.org/TR/2001/REC-xsl-20011015/slice7.html#text-align
*/
diff --git a/fastods/src/main/java/com/github/jferard/fastods/style/TableCellStyleBuilder.java b/fastods/src/main/java/com/github/jferard/fastods/style/TableCellStyleBuilder.java
index <HASH>..<HASH> 100644
--- a/fastods/src/main/java/com/github/jferard/fastods/style/TableCellStyleBuilder.java
+++ b/fastods/src/main/java/com/github/jferard/fastods/style/TableCellStyleBuilder.java
@@ -26,6 +26,7 @@ package com.github.jferard.fastods.style;
import com.github.jferard.fastods.Color;
import com.github.jferard.fastods.SimpleColor;
import com.github.jferard.fastods.datastyle.DataStyle;
+import com.github.jferard.fastods.style.TableCellStyle.TextRotating;
import com.github.jferard.fastods.util.Length;
import com.github.jferard.fastods.util.StyleBuilder;
@@ -43,6 +44,7 @@ public class TableCellStyleBuilder implements StyleBuilder<TableCellStyle>, Hida
// true
private TableCellStyle.Align textAlign; // 'center','end','start','justify'
private TableCellStyle.VerticalAlign verticalAlign; // 'middle', 'bottom',
+ private TableCellStyle.TextRotating textRotating;
// 'top'
private boolean wrap; // No line wrap when false, line wrap when
private boolean hidden;
@@ -166,10 +168,19 @@ public class TableCellStyleBuilder implements StyleBuilder<TableCellStyle>, Hida
public TableCellStyle build() {
return new TableCellStyle(this.name, this.hidden, this.dataStyle, this.backgroundColor, this.tpBuilder.build(),
this.textAlign, this.verticalAlign, this.wrap, this.parentCellStyle, this.bordersBuilder.build(),
- this.marginsBuilder.build());
+ this.marginsBuilder.build(),this.textRotating);
}
/**
+ * Set text rotation angle
+ * @param tr TextRotation to be used
+ * @return this for fluent style
+ */
+ public TableCellStyleBuilder textRotating(final TextRotating tr) {
+ this.textRotating = tr;
+ return this;
+ }
+ /**
* Set the data style for this TableFamilyStyle to ds.<br>
* If the StyleType of this TableFamilyStyle is not STYLE_TABLECELL, an
* exception is thrown
|
style:rotation-angle rotation angle for text in cell
|
jferard_fastods
|
train
|
9af7c6c6e1b3503acfb37fef0569367c56494528
|
diff --git a/odl/tomo/analytic/filtered_back_projection.py b/odl/tomo/analytic/filtered_back_projection.py
index <HASH>..<HASH> 100644
--- a/odl/tomo/analytic/filtered_back_projection.py
+++ b/odl/tomo/analytic/filtered_back_projection.py
@@ -29,14 +29,28 @@ __all__ = ('fbp_op',)
def fbp_op(ray_trafo, padding=True):
- """Create Filtered BackProjection from a ray transform.
+ """Create filtered back-projection from a `RayTransform`.
+
+ The filtered back-projection is an approximate inverse to the ray
+ transform.
Parameters
----------
ray_trafo : `RayTransform`
-
- padding : bool
- If the data space should be zero padded.
+ The ray transform (forward operator) whose approximate inverse should
+ be computed. Its geometry has to be any of the following
+ Parallel2DGeometry : Exact reconstruction
+ Parallel3dAxisGeometry : Exact reconstruction
+ FanFlatGeometry : Approximate reconstruction, correct in limit of fan
+ angle = 0.
+ CircularConeFlatGeometry : Approximate reconstruction, correct in limit
+ of fan angle = 0.
+ HelicalConeFlatGeometry : Very approximate.
+
+ padding : bool, optional
+ If the data space should be zero padded. Without padding, the data may
+ be corrupted due to the circular convolution used. Using padding makes
+ the algorithm slower.
Returns
-------
@@ -75,6 +89,14 @@ def fbp_op(ray_trafo, padding=True):
assert cnorm != 0
c /= cnorm
+ used_axes = c != 0
+ if used_axes[0] and not used_axes[1]:
+ axes = [1]
+ elif not used_axes[0] and used_axes[1]:
+ axes = [2]
+ else:
+ axes = [1, 2]
+
# Define ramp filter
def fft_filter(x):
return np.abs(c[0] * x[1] + c[1] * x[2]) / (2 * alen)
@@ -83,26 +105,27 @@ def fbp_op(ray_trafo, padding=True):
if padding:
# Define padding operator
ran_shp = (ray_trafo.range.shape[0],
- ray_trafo.range.shape[1] * 2 - 1,
- ray_trafo.range.shape[2] * 2 - 1)
+ ray_trafo.range.shape[1] * 2 - 1 if used_axes[0]
+ else ray_trafo.range.shape[1],
+ ray_trafo.range.shape[2] * 2 - 1 if used_axes[1]
+ else ray_trafo.range.shape[2])
resizing = ResizingOperator(ray_trafo.range, ran_shp=ran_shp)
- fourier = FourierTransform(resizing.range, axes=[1, 2], impl=impl)
+ fourier = FourierTransform(resizing.range, axes=axes, impl=impl)
fourier = fourier * resizing
else:
- fourier = FourierTransform(ray_trafo.range, axes=[1, 2], impl=impl)
+ fourier = FourierTransform(ray_trafo.range, axes=axes, impl=impl)
else:
raise NotImplementedError('FBP only implemented in 2d and 3d')
# Create ramp in the detector direction
ramp_function = fourier.range.element(fft_filter)
- # Create ramp filter via the
- # convolution formula with fourier transforms
+ # Create ramp filter via the convolution formula with fourier transforms
ramp_filter = fourier.inverse * ramp_function * fourier
# Create filtered backprojection by composing the backprojection
- # (adjoint) with the ramp filter. Also apply a scaling.
+ # (adjoint) with the ramp filter.
return ray_trafo.adjoint * ramp_filter
|
ENH: Optimizations to fbp for axis aligned geometries
|
odlgroup_odl
|
train
|
663448a34226f663c9a08a478aeee39227321172
|
diff --git a/law/contrib/__init__.py b/law/contrib/__init__.py
index <HASH>..<HASH> 100644
--- a/law/contrib/__init__.py
+++ b/law/contrib/__init__.py
@@ -15,6 +15,9 @@ from law.util import flatten
logger = logging.getLogger(__name__)
+loaded_packages = []
+
+
def load(*packages):
"""
Loads contrib *packages* and adds members exposed in ``__all__`` to the law main module.
@@ -27,8 +30,15 @@ def load(*packages):
print(law.NumpyFormatter)
# -> <class 'law.contrib.numpy.formatter.NumpyFormatter'>
+
+ It is ensured that packages are loaded only once.
"""
for pkg in flatten(packages):
+ if pkg in loaded_packages:
+ logger.debug("skip contrib package '{}', already loaded".format(pkg))
+ continue
+ loaded_packages.append(pkg)
+
mod = __import__("law.contrib.{}".format(pkg), globals(), locals(), [pkg])
logger.debug("loaded contrib package '{}'".format(pkg))
|
Prevent contrib packages from being loaded twice.
|
riga_law
|
train
|
3407c88d7b83a35dd15cd4b02a5ebd78dd85c2bd
|
diff --git a/version.go b/version.go
index <HASH>..<HASH> 100644
--- a/version.go
+++ b/version.go
@@ -1,6 +1,6 @@
package gobot
-const version = "1.1.0"
+const version = "1.2.0"
// Version returns the current Gobot version
func Version() string {
|
Update version to <I> for release
|
hybridgroup_gobot
|
train
|
a101dca347af5d412f0ae78353f0b99dd37bfad2
|
diff --git a/bulbs/poll/models.py b/bulbs/poll/models.py
index <HASH>..<HASH> 100644
--- a/bulbs/poll/models.py
+++ b/bulbs/poll/models.py
@@ -167,7 +167,6 @@ class Poll(Content):
if 'answer_02' not in payload:
payload['answer_02'] = DEFAULT_ANSWER_2
- print(payload)
return payload
def save(self, *args, **kwargs):
diff --git a/tests/poll/test_views.py b/tests/poll/test_views.py
index <HASH>..<HASH> 100644
--- a/tests/poll/test_views.py
+++ b/tests/poll/test_views.py
@@ -316,7 +316,7 @@ class GetPollDataTestCase(BaseAPITestCase):
if PY2:
data = json.loads(response.content)
else:
- data = json.loads(response.read().decode('utf-8'))
+ data = json.loads(response.content.decode('utf-8'))
self.assertEqual(data['id'], poll.id)
self.assertEqual(data['total_votes'], 0)
|
remove print statement and pass tests in py3
|
theonion_django-bulbs
|
train
|
a6cca0934c9ce5d506b218cc7dca21c92ea335fd
|
diff --git a/pkg/generate/app/sourcelookup.go b/pkg/generate/app/sourcelookup.go
index <HASH>..<HASH> 100644
--- a/pkg/generate/app/sourcelookup.go
+++ b/pkg/generate/app/sourcelookup.go
@@ -259,6 +259,9 @@ func (r *SourceRepository) LocalPath() (string, error) {
return "", err
}
}
+ if _, err := os.Stat(r.localDir); os.IsNotExist(err) {
+ return "", fmt.Errorf("supplied context directory '%s' does not exist in '%s'", r.contextDir, r.url.String())
+ }
return r.localDir, nil
}
diff --git a/test/integration/newapp_test.go b/test/integration/newapp_test.go
index <HASH>..<HASH> 100644
--- a/test/integration/newapp_test.go
+++ b/test/integration/newapp_test.go
@@ -495,6 +495,49 @@ func TestNewAppRunAll(t *testing.T) {
expectedErr: nil,
},
{
+ name: "failed app generation using missing context dir",
+ config: &cmd.AppConfig{
+ ComponentInputs: cmd.ComponentInputs{
+ SourceRepositories: []string{"https://github.com/openshift/sti-ruby"},
+ },
+ GenerationInputs: cmd.GenerationInputs{
+ ContextDir: "2.0/test/missing-dir",
+ },
+
+ Resolvers: cmd.Resolvers{
+ DockerSearcher: dockerSearcher,
+ ImageStreamSearcher: fakeImageStreamSearcher(),
+ ImageStreamByAnnotationSearcher: app.NewImageStreamByAnnotationSearcher(&client.Fake{}, &client.Fake{}, []string{"default"}),
+ TemplateSearcher: app.TemplateSearcher{
+ Client: &client.Fake{},
+ TemplateConfigsNamespacer: &client.Fake{},
+ Namespaces: []string{"openshift", "default"},
+ },
+ Detector: app.SourceRepositoryEnumerator{
+ Detectors: source.DefaultDetectors,
+ DockerfileTester: dockerfile.NewTester(),
+ JenkinsfileTester: jenkinsfile.NewTester(),
+ },
+ },
+
+ Typer: kapi.Scheme,
+ OSClient: &client.Fake{},
+ OriginNamespace: "default",
+ },
+ expected: map[string][]string{
+ "imageStream": {"sti-ruby"},
+ "buildConfig": {"sti-ruby"},
+ "deploymentConfig": {"sti-ruby"},
+ "service": {"sti-ruby"},
+ },
+ expectedName: "sti-ruby",
+ expectedVolumes: nil,
+ errFn: func(err error) bool {
+ return err.Error() == "supplied context directory '2.0/test/missing-dir' does not exist in 'https://github.com/openshift/sti-ruby'"
+ },
+ },
+
+ {
name: "insecure registry generation",
config: &cmd.AppConfig{
ComponentInputs: cmd.ComponentInputs{
|
oc new-app display correct error on missing context directory
Adds additional check for existence of supplied context directory
and displays correct error
Also added test for the correct error
Previously a missing context directory would display an error
about a missing Dockerfile (when using the docker strategy)
Fixes #<I>
|
openshift_origin
|
train
|
218bb2ecf71c516c85b1b6e075454bba13090cd8
|
diff --git a/valkka/live/gui.py b/valkka/live/gui.py
index <HASH>..<HASH> 100644
--- a/valkka/live/gui.py
+++ b/valkka/live/gui.py
@@ -24,12 +24,7 @@ You should have received a copy of the GNU Affero General Public License along w
from valkka.live import constant
import imp
import sys
-
-assert(sys.version_info.major >= 3)
-if sys.version_info.minor < 6:
- importerror = ImportError
-else:
- importerror = ModuleNotFoundError
+from valkka.live.tools import importerror
try:
import valkka.core
diff --git a/valkka/live/tools.py b/valkka/live/tools.py
index <HASH>..<HASH> 100644
--- a/valkka/live/tools.py
+++ b/valkka/live/tools.py
@@ -32,6 +32,13 @@ import re
home = os.path.expanduser("~")
config_dir = os.path.join(home, ".valkka", "live")
+assert(sys.version_info.major >= 3)
+
+if sys.version_info.minor < 6:
+ importerror = ImportError
+else:
+ importerror = ModuleNotFoundError
+
def getConfigDir():
return config_dir
@@ -65,7 +72,7 @@ def scanMVisionClasses():
In Ubuntu 16, which uses python 3.5 : https://docs.python.org/3.5/library/pkgutil.html#pkgutil.iter_modules : obj = (module_finder, name, ispkg)
"""
if obj.__class__ == tuple:
- name = obj[1] # ubuntu 16
+ name = obj[1] # ubuntu 16 / python 3.5
else:
name = obj.name
@@ -73,7 +80,7 @@ def scanMVisionClasses():
# print("mvision scan: >",p)
try:
m = importlib.import_module(name)
- except ModuleNotFoundError:
+ except importerror:
print("mvision scan: could not import", name)
else:
# print(m)
|
python <I> compatilibity, maybe
|
elsampsa_valkka-live
|
train
|
612e748d9fe9697d1ceb0ffbbef7e280de242da4
|
diff --git a/template/app/controller/Classes.js b/template/app/controller/Classes.js
index <HASH>..<HASH> 100644
--- a/template/app/controller/Classes.js
+++ b/template/app/controller/Classes.js
@@ -131,11 +131,11 @@ Ext.define('Docs.controller.Classes', {
docTabPanel.setLoading(false);
}
- var prevCls = historyStore.find('cls', cls.name);
- if (prevCls === -1) {
- historyStore.add({cls: cls.name});
- historyStore.sync();
- }
+ // var prevCls = historyStore.find('cls', cls.name);
+ // if (prevCls === -1) {
+ // historyStore.add({cls: cls.name});
+ // historyStore.sync();
+ // }
Ext.getCmp('treePanelCmp').selectClass(cls.name);
}
|
Comment out use of historyStore.
Currently it throws errors.
|
senchalabs_jsduck
|
train
|
963d19387e8621094b45fed56e5be23b39a4f910
|
diff --git a/pyemma/coordinates/transform/transformer.py b/pyemma/coordinates/transform/transformer.py
index <HASH>..<HASH> 100644
--- a/pyemma/coordinates/transform/transformer.py
+++ b/pyemma/coordinates/transform/transformer.py
@@ -345,5 +345,6 @@ class Transformer(object):
distances : ndarray(m)
euclidean distances between points in Y to x
"""
+ x = np.atleast_2d(x)
dists = cdist(Y, x)
return dists
|
[transformer] ensure x is 2d.
|
markovmodel_PyEMMA
|
train
|
e66cf50d72bb062c5bcb1c1267e6a10d4f877c19
|
diff --git a/src/array.js b/src/array.js
index <HASH>..<HASH> 100644
--- a/src/array.js
+++ b/src/array.js
@@ -1,16 +1 @@
export var slice = Array.prototype.slice;
-
-export function shuffle(array) {
- var m = array.length,
- t,
- i;
-
- while (m) {
- i = Math.random() * m-- | 0;
- t = array[m];
- array[m] = array[i];
- array[i] = t;
- }
-
- return array;
-}
diff --git a/src/pack/enclose.js b/src/pack/enclose.js
index <HASH>..<HASH> 100644
--- a/src/pack/enclose.js
+++ b/src/pack/enclose.js
@@ -1,10 +1,10 @@
-import {shuffle, slice} from "../array";
+import {slice} from "../array";
-export default function(circles) {
- var i = 0, n = (circles = shuffle(slice.call(circles))).length, B = [], p, e;
+export default function(L) {
+ var i = 0, j, n = (L = slice.call(L)).length, B = [], p, e;
while (i < n) {
- p = circles[i];
+ p = L[j = i + (Math.random() * (n - i) | 0)], L[j] = L[i], L[i] = p;
if (e && enclosesWeak(e, p)) ++i;
else e = encloseBasis(B = extendBasis(B, p)), i = 0;
}
|
Lazy shuffling.
This also implicitly reshuffles the array on restart, improving performance!
|
d3_d3-hierarchy
|
train
|
2a65e91e0163c00a3090f4406292a881c9951e32
|
diff --git a/treetime/node_interpolator.py b/treetime/node_interpolator.py
index <HASH>..<HASH> 100644
--- a/treetime/node_interpolator.py
+++ b/treetime/node_interpolator.py
@@ -112,7 +112,7 @@ class NodeInterpolator (Distribution):
grid_left =[]
# make grid and calculate convolution
- t_grid_0 = np.concatenate([grid_left[:-1], grid_center, grid_right[1:]])
+ t_grid_0 = np.concatenate([grid_left[:-1], grid_center, grid_right[1:], [tmin, tmax]])
t_grid_0 = t_grid_0[(t_grid_0 > tmin-ttconf.TINY_NUMBER) & (t_grid_0 < tmax+ttconf.TINY_NUMBER)]
res_0 = np.array([_convolution_in_point(t_val, node_interp, branch_interp,
n_integral=n_integral, return_log=True,
|
make sure integration boudaries are part of grid
|
neherlab_treetime
|
train
|
94577bce51e7f9a080041b2acc9ac2eaadc42f1d
|
diff --git a/src/Json/JsonSchema.php b/src/Json/JsonSchema.php
index <HASH>..<HASH> 100644
--- a/src/Json/JsonSchema.php
+++ b/src/Json/JsonSchema.php
@@ -25,7 +25,7 @@ class JsonSchema extends Json
throw new \LogicException('Cannot resolve JsonSchema without uri parameter');
}
- $resolver->resolve($this->encode(false), $this->uri);
+ $resolver->resolve($this->getRawContent(), $this->uri);
return $this;
}
diff --git a/tests/Units/Json/JsonSchema.php b/tests/Units/Json/JsonSchema.php
index <HASH>..<HASH> 100644
--- a/tests/Units/Json/JsonSchema.php
+++ b/tests/Units/Json/JsonSchema.php
@@ -40,7 +40,7 @@ class JsonSchema extends atoum
)
->mock($resolver)
->call('resolve')
- ->withArguments('{}', 'file://test')
+ ->withArguments(new \stdClass, 'file://test')
->once()
->object($result)
|
Fix wrong usage of RefResolver
|
ubirak_rest-api-behat-extension
|
train
|
d9e13c0b7565c02aa3eed7eb43e17f01bc978cbd
|
diff --git a/includes/types/font.php b/includes/types/font.php
index <HASH>..<HASH> 100644
--- a/includes/types/font.php
+++ b/includes/types/font.php
@@ -66,10 +66,11 @@ abstract class Icon_Picker_Type_Font extends Icon_Picker_Type {
* Constructor
*
* @since 0.1.0
+ * @param array $args Optional arguments passed to parent class.
*/
- public function __construct() {
+ public function __construct( array $args = array() ) {
add_action( 'icon_picker_loader_init', array( $this, 'register_assets' ) );
- parent::__construct();
+ parent::__construct( $args );
}
|
Font type: Pass arguments from sub-class to parent class.
|
ineagu_wp-icon-picker
|
train
|
be3b233b26353ca58dd0c2fe5db051b4ab2b4fc4
|
diff --git a/src/components/VApp/mixins/app-theme.js b/src/components/VApp/mixins/app-theme.js
index <HASH>..<HASH> 100644
--- a/src/components/VApp/mixins/app-theme.js
+++ b/src/components/VApp/mixins/app-theme.js
@@ -47,7 +47,7 @@ export default {
watch: {
generatedStyles () {
- this.applyTheme()
+ !this.meta && this.applyTheme()
}
},
@@ -82,7 +82,7 @@ export default {
methods: {
applyTheme () {
- this.style.innerHTML = this.generatedStyles
+ if (this.style) this.style.innerHTML = this.generatedStyles
},
genStyle () {
let style = document.getElementById('vuetify-theme-stylesheet')
|
fix(theme): only apply theme to head element when not using vue-meta (#<I>)
fixes #<I>
|
vuetifyjs_vuetify
|
train
|
8af81b1ef6775fb0f6d616bf4cf7a68647e13b43
|
diff --git a/ontobio/golr/golr_query.py b/ontobio/golr/golr_query.py
index <HASH>..<HASH> 100644
--- a/ontobio/golr/golr_query.py
+++ b/ontobio/golr/golr_query.py
@@ -1450,6 +1450,7 @@ class GolrAssociationQuery(GolrAbstractQuery):
if 'aspect' in d and id.startswith('GO:'):
obj['aspect'] = ASPECT_MAP[d['aspect']]
+ del d['aspect']
cf = fname + "_category"
if cf in d:
|
Delete aspect from doc after parsing
|
biolink_ontobio
|
train
|
7e8f21cfd0f940afb149aae963db770eb01822b7
|
diff --git a/lib/sitemap.rb b/lib/sitemap.rb
index <HASH>..<HASH> 100644
--- a/lib/sitemap.rb
+++ b/lib/sitemap.rb
@@ -23,7 +23,7 @@ module Sitemap
:priority => "priority"
}
- attr_accessor :entries, :host
+ attr_accessor :entries, :host, :routes
def initialize
self.class.send(:include, Rails.application.routes.url_helpers)
@@ -34,7 +34,7 @@ module Sitemap
options.each do |k, v|
self.send("#{k}=", v)
end
- instance_exec(self, &block)
+ self.routes = block
end
def path(object, options = {})
@@ -60,6 +60,7 @@ module Sitemap
end
def build
+ instance_exec(self, &routes)
xml = Builder::XmlMarkup.new(:indent => 2)
file = File.read(File.expand_path("../views/index.xml.builder", __FILE__))
instance_eval file
|
Paths aren't parsed on load anymore.
|
viseztrance_rails-sitemap
|
train
|
f4c4f6884c633287e7632d62481e06c9f0b762f5
|
diff --git a/hazelcast/src/test/java/com/hazelcast/test/AbstractHazelcastClassRunner.java b/hazelcast/src/test/java/com/hazelcast/test/AbstractHazelcastClassRunner.java
index <HASH>..<HASH> 100644
--- a/hazelcast/src/test/java/com/hazelcast/test/AbstractHazelcastClassRunner.java
+++ b/hazelcast/src/test/java/com/hazelcast/test/AbstractHazelcastClassRunner.java
@@ -51,7 +51,7 @@ import static java.lang.Integer.getInteger;
*/
public abstract class AbstractHazelcastClassRunner extends AbstractParameterizedHazelcastClassRunner {
- protected static final boolean DISABLE_THREAD_DUMP_ON_FAILURE = getBoolean("hazelcast.test.disableThreadDumpOnFailure");
+ protected static final boolean THREAD_DUMP_ON_FAILURE = getBoolean("hazelcast.test.threadDumpOnFailure");
protected static final int DEFAULT_TEST_TIMEOUT_IN_SECONDS = getInteger("hazelcast.test.defaultTestTimeoutInSeconds", 300);
private static final ThreadLocal<String> TEST_NAME_THREAD_LOCAL = new InheritableThreadLocal<String>();
@@ -153,7 +153,7 @@ public abstract class AbstractHazelcastClassRunner extends AbstractParameterized
@Override
protected Statement withAfters(FrameworkMethod method, Object target, Statement statement) {
List<FrameworkMethod> afters = getTestClass().getAnnotatedMethods(After.class);
- if (!DISABLE_THREAD_DUMP_ON_FAILURE) {
+ if (THREAD_DUMP_ON_FAILURE) {
return new ThreadDumpAwareRunAfters(method, statement, afters, target);
}
if (afters.isEmpty()) {
|
Reverse default for thread dump on test failure (#<I>)
Replaces the sysprop hazelcast.test.disableThreadDumpOnFailure
with hazelcast.test.threadDumpOnFailure
|
hazelcast_hazelcast
|
train
|
3e1ddc57e15aaa8c18daccf334ad79ce6f2dfc42
|
diff --git a/emannotationschemas/mesh_models.py b/emannotationschemas/mesh_models.py
index <HASH>..<HASH> 100644
--- a/emannotationschemas/mesh_models.py
+++ b/emannotationschemas/mesh_models.py
@@ -34,57 +34,55 @@ def make_neuron_compartment_model(dataset, version: int = 1):
version=version)
-def make_post_synaptic_compartment_model(dataset,
- synapse_table,
- version: int = 1):
-
- psc_name_lower = post_synaptic_compartment_name.lower()
- synapse_table_name = format_table_name(dataset, synapse_table, version=version)
+def make_pre_post_synaptic_compartment_model(dataset,
+ synapse_table,
+ pre_post_name,
+ version: int = 1):
+ name_lower = pre_post_name.lower()
+ synapse_table_name = format_table_name(dataset,
+ synapse_table,
+ version=version)
attr_dict = {
'__tablename__': format_table_name(dataset,
- psc_name_lower,
+ name_lower,
version=version),
'label': Column(Integer),
- 'synapse_id': Column(Numeric, ForeignKey(synapse_table_name + ".id"), primary_key=True)
+ 'soma_distance': Column(Float),
+ 'synapse_id': Column(Numeric,
+ ForeignKey(synapse_table_name + ".id"),
+ primary_key=True)
}
- model_name = dataset.capitalize() + post_synaptic_compartment_name
+ model_name = dataset.capitalize() + pre_post_name
if not annotation_models.contains_model(dataset,
- psc_name_lower,
+ name_lower,
version=version):
annotation_models.set_model(dataset,
- psc_name_lower,
+ name_lower,
type(model_name, (Base,), attr_dict),
version=version)
return annotation_models.get_model(dataset,
- psc_name_lower,
+ name_lower,
version=version)
+def make_post_synaptic_compartment_model(dataset,
+ synapse_table,
+ version: int = 1):
+
+ return make_pre_post_synaptic_compartment_model(dataset,
+ synapse_table,
+ post_synaptic_compartment_name,
+ version)
+
+
def make_pre_synaptic_compartment_model(dataset,
synapse_table,
version: int = 1):
- psc_name_lower = pre_synaptic_compartment_name.lower()
- synapse_table_name = format_table_name(dataset, synapse_table, version=version)
-
- attr_dict = {
- '__tablename__': format_table_name(dataset,
- psc_name_lower,
- version=version),
- 'label': Column(Integer),
- 'synapse_id': Column(Numeric, ForeignKey(synapse_table_name + ".id"), primary_key=True)
- }
- model_name = dataset.capitalize() + pre_synaptic_compartment_name
- if not annotation_models.contains_model(dataset,
- psc_name_lower,
- version=version):
- annotation_models.set_model(dataset,
- psc_name_lower,
- type(model_name, (Base,), attr_dict),
- version=version)
-
- return annotation_models.get_model(dataset,
- psc_name_lower,
- version=version)
+ return make_pre_post_synaptic_compartment_model(dataset,
+ synapse_table,
+ pre_synaptic_compartment_name,
+ version)
+
|
making presynaptic models and distance to soma
|
seung-lab_EMAnnotationSchemas
|
train
|
0e5bef5b99963a656ba796a4e587c021d90c7ce7
|
diff --git a/lib/rapns/daemon/logger.rb b/lib/rapns/daemon/logger.rb
index <HASH>..<HASH> 100644
--- a/lib/rapns/daemon/logger.rb
+++ b/lib/rapns/daemon/logger.rb
@@ -3,8 +3,9 @@ module Rapns
class Logger
def initialize(options)
@options = options
- log_path = File.join(Rails.root, 'log', 'rapns.log')
- @logger = ActiveSupport::BufferedLogger.new(log_path, Rails.logger.level)
+ log = File.open(File.join(Rails.root, 'log', 'rapns.log'))
+ log.sync = true
+ @logger = ActiveSupport::BufferedLogger.new(log, Rails.logger.level)
@logger.auto_flushing = Rails.logger.respond_to?(:auto_flushing) ? Rails.logger.auto_flushing : true
end
diff --git a/spec/rapns/daemon/logger_spec.rb b/spec/rapns/daemon/logger_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/rapns/daemon/logger_spec.rb
+++ b/spec/rapns/daemon/logger_spec.rb
@@ -21,6 +21,8 @@ module Airbrake
end
describe Rapns::Daemon::Logger do
+ let(:log) { stub(:sync= => true) }
+
before do
Rails.stub(:root).and_return("/rails_root")
@buffered_logger = mock("BufferedLogger", :info => nil, :error => nil, :level => 0, :auto_flushing => 1, :auto_flushing= => nil)
@@ -28,10 +30,21 @@ describe Rapns::Daemon::Logger do
ActiveSupport::BufferedLogger.stub(:new).and_return(@buffered_logger)
configuration = mock("Configuration", :airbrake_notify? => true)
Rapns::Daemon.stub(:configuration).and_return(configuration)
+ File.stub(:open => log)
end
it "should open the a log file in the Rails log directory" do
- ActiveSupport::BufferedLogger.should_receive(:new).with("/rails_root/log/rapns.log", Rails.logger.level)
+ File.should_receive(:open).with("/rails_root/log/rapns.log")
+ Rapns::Daemon::Logger.new(:foreground => true)
+ end
+
+ it 'sets sync mode on the log descriptor' do
+ log.should_receive(:sync=).with(true)
+ Rapns::Daemon::Logger.new(:foreground => true)
+ end
+
+ it 'instantiates the BufferedLogger' do
+ ActiveSupport::BufferedLogger.should_receive(:new).with(log, Rails.logger.level)
Rapns::Daemon::Logger.new(:foreground => true)
end
|
BufferedLogger#auto_flushing is deprecated. Set sync mode on the log IO.
|
ileitch_rapns
|
train
|
ca29b437f49400fd3d18ec3e03a1b21a757ea7c4
|
diff --git a/exchangelib/properties.py b/exchangelib/properties.py
index <HASH>..<HASH> 100644
--- a/exchangelib/properties.py
+++ b/exchangelib/properties.py
@@ -777,6 +777,23 @@ class CalendarView(EWSElement):
raise ValueError("'start' must be before 'end'")
+class CalendarEventDetails(EWSElement):
+ # MSDN: https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/calendareventdetails
+ ELEMENT_NAME = 'CalendarEventDetails'
+ FIELDS = [
+ CharField('id', field_uri='ID'),
+ CharField('subject', field_uri='Subject'),
+ CharField('location', field_uri='Location'),
+ BooleanField('is_meeting', field_uri='IsMeeting'),
+ BooleanField('is_recurring', field_uri='IsRecurring'),
+ BooleanField('is_exception', field_uri='IsException'),
+ BooleanField('is_reminder_set', field_uri='IsReminderSet'),
+ BooleanField('is_private', field_uri='IsPrivate'),
+ ]
+
+ __slots__ = tuple(f.name for f in FIELDS)
+
+
class CalendarEvent(EWSElement):
# MSDN: https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/calendarevent
ELEMENT_NAME = 'CalendarEvent'
@@ -784,7 +801,7 @@ class CalendarEvent(EWSElement):
DateTimeField('start', field_uri='StartTime'),
DateTimeField('end', field_uri='EndTime'),
FreeBusyStatusField('busy_type', field_uri='BusyType', is_required=True, default='Busy'),
- # CalendarEventDetails
+ EWSElementField('details', field_uri='CalendarEventDetails', value_cls=CalendarEventDetails),
]
__slots__ = tuple(f.name for f in FIELDS)
|
Support CalendarEventDetails element in free/busy response. Fixes #<I>
|
ecederstrand_exchangelib
|
train
|
f7800e2d6b48a2a4906ac6d6c2b27b73388e30ec
|
diff --git a/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodDelegation.java b/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodDelegation.java
index <HASH>..<HASH> 100644
--- a/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodDelegation.java
+++ b/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodDelegation.java
@@ -1466,6 +1466,7 @@ public class MethodDelegation implements Implementation.Composable {
* @param matcher The matcher any delegation target needs to match in order to be considered a for delegation.
* @return A new delegation configuration which only considers methods for delegation if they match the supplied matcher.
*/
+ @SuppressWarnings("unchecked")
public WithCustomProperties filter(ElementMatcher<? super MethodDescription> matcher) {
return new WithCustomProperties(ambiguityResolver,
parameterBinders,
|
Suppress unchecked warning.
|
raphw_byte-buddy
|
train
|
b794c9ec84c9e2be697328ebf5a157c0c4898bb4
|
diff --git a/lib/datasource/maven.js b/lib/datasource/maven.js
index <HASH>..<HASH> 100644
--- a/lib/datasource/maven.js
+++ b/lib/datasource/maven.js
@@ -2,20 +2,23 @@ const got = require('got');
const url = require('url');
const fs = require('fs-extra');
const { XmlDocument } = require('xmldoc');
+const is = require('@sindresorhus/is');
module.exports = {
getPkgReleases,
};
// eslint-disable-next-line no-unused-vars
-async function getPkgReleases(purl, config) {
+async function getPkgReleases(purl) {
const versions = [];
const dependency = getDependencyParts(purl);
- const repositories = getRepositories(purl);
- if (repositories.length < 1) {
+ if (!is.nonEmptyArray(purl.repositoryUrls)) {
logger.error(`No repositories defined for ${dependency.display}`);
return null;
}
+ const repositories = purl.repositoryUrls.map(repository =>
+ repository.replace(/\/?$/, '/')
+ );
logger.debug(
`Found ${repositories.length} repositories for ${dependency.display}`
);
@@ -56,18 +59,6 @@ function getDependencyParts(purl) {
};
}
-function getRepositories(purl) {
- if (!purl.qualifiers || !purl.qualifiers.repository_url) {
- return [];
- }
- return purl.qualifiers.repository_url.split(',').map(repoUrl => {
- if (!repoUrl.endsWith('/')) {
- return repoUrl + '/';
- }
- return repoUrl;
- });
-}
-
async function downloadMavenMetadata(dependency, repoUrl) {
const pkgUrl = new url.URL(
`${dependency.dependencyUrl}/maven-metadata.xml`,
diff --git a/lib/util/purl.js b/lib/util/purl.js
index <HASH>..<HASH> 100644
--- a/lib/util/purl.js
+++ b/lib/util/purl.js
@@ -45,6 +45,10 @@ function parse(input) {
res.lookupType = res.qualifiers.lookupType;
delete res.qualifiers.lookupType;
}
+ if (res.qualifiers.repository_url) {
+ res.repositoryUrls = res.qualifiers.repository_url.split(',');
+ delete res.qualifiers.repository_url;
+ }
} else {
res.qualifiers = {};
}
diff --git a/test/datasource/maven.spec.js b/test/datasource/maven.spec.js
index <HASH>..<HASH> 100644
--- a/test/datasource/maven.spec.js
+++ b/test/datasource/maven.spec.js
@@ -45,7 +45,7 @@ describe('datasource/maven', () => {
expect(releases).toBeNull();
});
- it('should return all versions of a specific library', async () => {
+ it('should simply return all versions of a specific library', async () => {
const releases = await datasource.getPkgReleases({
...config,
purl:
@@ -150,7 +150,7 @@ describe('datasource/maven', () => {
.get('/maven2/mysql/mysql-connector-java/maven-metadata.xml')
.reply(200, invalidMavenMetadata);
const releases = await datasource.getPkgReleases({
- config,
+ ...config,
purl:
'pkg:maven/mysql/mysql-connector-java?repository_url=http://central.maven.org/maven2/,http://invalid_metadata_repo/maven2/',
});
@@ -159,7 +159,7 @@ describe('datasource/maven', () => {
it('should return all versions of a specific library if a repository does not end with /', async () => {
const releases = await datasource.getPkgReleases({
- config,
+ ...config,
purl:
'pkg:maven/mysql/mysql-connector-java?repository_url=http://central.maven.org/maven2',
});
diff --git a/test/util/__snapshots__/purl.spec.js.snap b/test/util/__snapshots__/purl.spec.js.snap
index <HASH>..<HASH> 100644
--- a/test/util/__snapshots__/purl.spec.js.snap
+++ b/test/util/__snapshots__/purl.spec.js.snap
@@ -58,6 +58,17 @@ Object {
}
`;
+exports[`util/purl parse() parses repository_url qualifier 1`] = `
+Object {
+ "datasource": "maven",
+ "lookupName": "org.apache.xmlgraphics/batik-anim",
+ "qualifiers": Object {},
+ "repositoryUrls": Array [
+ "repo.spring.io/release",
+ ],
+}
+`;
+
exports[`util/purl parse() parses simple npm 1`] = `
Object {
"datasource": "npm",
diff --git a/test/util/purl.spec.js b/test/util/purl.spec.js
index <HASH>..<HASH> 100644
--- a/test/util/purl.spec.js
+++ b/test/util/purl.spec.js
@@ -29,5 +29,12 @@ describe('util/purl', () => {
it('parses github with lookupType', () => {
expect(parse('pkg:github/abc/def?lookupType=releases')).toMatchSnapshot();
});
+ it('parses repository_url qualifier', () => {
+ expect(
+ parse(
+ 'pkg:maven/org.apache.xmlgraphics/batik-anim@1.9.1?repository_url=repo.spring.io/release'
+ )
+ ).toMatchSnapshot();
+ });
});
});
|
refactor: maven repositoryUrls
|
renovatebot_renovate
|
train
|
97f8cc0392caa003f382487541adc664c5fde786
|
diff --git a/library/aik099/QATools/BEM/Element/Block.php b/library/aik099/QATools/BEM/Element/Block.php
index <HASH>..<HASH> 100644
--- a/library/aik099/QATools/BEM/Element/Block.php
+++ b/library/aik099/QATools/BEM/Element/Block.php
@@ -136,4 +136,19 @@ class Block extends Part implements IBlock
return $items;
}
+ /**
+ * Waits for an element(-s) to appear and returns it.
+ *
+ * @param integer $timeout Maximal allowed waiting time in milliseconds.
+ * @param callable $callback Callback, which result is both used as waiting condition and returned.
+ * Will receive reference to `this element` as first argument.
+ *
+ * @return mixed
+ * @throws \LogicException Always.
+ */
+ public function waitFor($timeout, $callback)
+ {
+ throw new \LogicException('Waiting for elements not supported by the BEM methodology');
+ }
+
}
diff --git a/library/aik099/QATools/BEM/Proxy/BlockProxy.php b/library/aik099/QATools/BEM/Proxy/BlockProxy.php
index <HASH>..<HASH> 100644
--- a/library/aik099/QATools/BEM/Proxy/BlockProxy.php
+++ b/library/aik099/QATools/BEM/Proxy/BlockProxy.php
@@ -127,4 +127,19 @@ class BlockProxy extends PartProxy implements IBlock
return $this->getObject()->find($selector, $locator);
}
+ /**
+ * Waits for an element(-s) to appear and returns it.
+ *
+ * @param integer $timeout Maximal allowed waiting time in milliseconds.
+ * @param callable $callback Callback, which result is both used as waiting condition and returned.
+ * Will receive reference to `this element` as first argument.
+ *
+ * @return mixed
+ * @throws \LogicException Always.
+ */
+ public function waitFor($timeout, $callback)
+ {
+ return $this->getObject()->waitFor($timeout, $callback);
+ }
+
}
|
Adding dummy Block::waitFor method for BEM module
|
qa-tools_qa-tools
|
train
|
6d80bf0801ee35782c1c70b7dce6d7d8b22ca659
|
diff --git a/dynaconf/cli.py b/dynaconf/cli.py
index <HASH>..<HASH> 100644
--- a/dynaconf/cli.py
+++ b/dynaconf/cli.py
@@ -430,7 +430,10 @@ def _list(env, key, more, loader, _all=False, output=None, flat=False):
if not key:
datalines = "\n".join(
"%s: %s"
- % (click.style(k, bg=color(k), fg="white"), pprint.pformat(v))
+ % (
+ click.style(k, bg=color(k), fg="white"),
+ pprint.pformat("{} -> {}".format(type(v).__name__, v)),
+ )
for k, v in data.items()
)
(click.echo_via_pager if more else click.echo)(datalines)
|
Changed CLI list to show data type of the envvars to fix #<I>
|
rochacbruno_dynaconf
|
train
|
f53d606f2dba9c60dab3d0446463936248f5bc62
|
diff --git a/python_modules/dagster/dagster/core/instance/__init__.py b/python_modules/dagster/dagster/core/instance/__init__.py
index <HASH>..<HASH> 100644
--- a/python_modules/dagster/dagster/core/instance/__init__.py
+++ b/python_modules/dagster/dagster/core/instance/__init__.py
@@ -1,4 +1,3 @@
-import configparser
import logging
import os
from abc import ABCMeta
@@ -6,12 +5,14 @@ from collections import defaultdict, namedtuple
from enum import Enum
import six
+import yaml
from rx import Observable
from dagster import check, seven
from dagster.core.errors import DagsterInvariantViolationError
from dagster.core.serdes import whitelist_for_serdes
from dagster.core.storage.pipeline_run import PipelineRun
+from dagster.utils.yaml_utils import load_yaml_from_globs
from .features import DagsterFeatures
@@ -21,19 +22,13 @@ def _is_dagster_home_set():
def _dagster_config(base_dir):
- config = configparser.ConfigParser(allow_no_value=True)
-
- config_path = os.path.join(base_dir, "dagster.cfg")
- if os.path.exists(config_path):
- config.read(config_path)
-
- return config
+ return load_yaml_from_globs(os.path.join(base_dir, "dagster.yaml"))
def _dagster_feature_set(base_dir):
config = _dagster_config(base_dir)
- if config.has_section('FEATURES'):
- return {k for k, _ in config.items('FEATURES')}
+ if 'features' in config:
+ return {k for k, _ in config['features']}
return None
diff --git a/python_modules/dagster/dagster/utils/yaml_utils.py b/python_modules/dagster/dagster/utils/yaml_utils.py
index <HASH>..<HASH> 100644
--- a/python_modules/dagster/dagster/utils/yaml_utils.py
+++ b/python_modules/dagster/dagster/utils/yaml_utils.py
@@ -19,8 +19,6 @@ def load_yaml_from_glob_list(glob_list):
for env_file_pattern in glob_list:
all_files_list.extend(glob.glob(env_file_pattern))
- check.invariant(all_files_list, 'Config file(s) not found at path(s) {}'.format(glob_list))
-
return merge_yamls(all_files_list)
diff --git a/python_modules/dagster/dagster_tests/utils_tests/test_yaml.py b/python_modules/dagster/dagster_tests/utils_tests/test_yaml.py
index <HASH>..<HASH> 100644
--- a/python_modules/dagster/dagster_tests/utils_tests/test_yaml.py
+++ b/python_modules/dagster/dagster_tests/utils_tests/test_yaml.py
@@ -1,6 +1,3 @@
-import pytest
-
-from dagster import check
from dagster.utils import script_relative_path
from dagster.utils.yaml_utils import (
load_yaml_from_glob_list,
@@ -32,5 +29,4 @@ def test_from_glob_list():
script_relative_path('yamls/yaml_one.yaml'), script_relative_path('yamls/yaml_two.yaml')
) == {'key_one': {'key_one_one': 'value_one', 'key_one_two': 'value_two'}}
- with pytest.raises(check.CheckError):
- load_yaml_from_glob_list(['flskhfhjsdf'])
+ assert load_yaml_from_glob_list(['flskhfhjsdf']) == {}
|
Use .yaml rather than .cfg
Summary: Let's only have one config language.
Test Plan: Unit and manual
Reviewers: #ft, sashank, alangenfeld
Reviewed By: #ft, sashank
Differential Revision: <URL>
|
dagster-io_dagster
|
train
|
9fd5b9e39dc8141507ebd2bb9bd1f86e634a9c75
|
diff --git a/plugin/fs/plugin.go b/plugin/fs/plugin.go
index <HASH>..<HASH> 100644
--- a/plugin/fs/plugin.go
+++ b/plugin/fs/plugin.go
@@ -278,20 +278,7 @@ func (p FSPlugin) Store(endpoint plugin.ShieldEndpoint) (string, int64, error) {
}
func (p FSPlugin) Retrieve(endpoint plugin.ShieldEndpoint, file string) error {
- cfg, err := getFSConfig(endpoint)
- if err != nil {
- return err
- }
-
- f, err := os.Open(fmt.Sprintf("%s/%s", cfg.BasePath, file))
- if err != nil {
- return err
- }
- defer f.Close()
-
- _, err = io.Copy(os.Stdout, f)
- return err
-
+ return plugin.UNIMPLEMENTED
}
func (p FSPlugin) Purge(endpoint plugin.ShieldEndpoint, file string) error {
|
Remove Retrieve() behavior from fs plugin
This is a holdover from the days when we let `fs` act as a storage
plugin, which we no longer allow for safety reasons.
|
starkandwayne_shield
|
train
|
01560c1a2721c8090110f4e40551f21ca8a9bec5
|
diff --git a/h2o-algos/src/main/java/hex/deeplearning/DeepLearningModel.java b/h2o-algos/src/main/java/hex/deeplearning/DeepLearningModel.java
index <HASH>..<HASH> 100644
--- a/h2o-algos/src/main/java/hex/deeplearning/DeepLearningModel.java
+++ b/h2o-algos/src/main/java/hex/deeplearning/DeepLearningModel.java
@@ -685,6 +685,8 @@ public class DeepLearningModel extends SupervisedModel<DeepLearningModel,DeepLea
public float error() { return (float) (_output.isClassifier() ? cm().err() : mse()); }
+ @Override public boolean isSupervised() { return !model_info.get_params()._autoencoder; }
+
public int compareTo(DeepLearningModel o) {
if (o._output.isClassifier() != _output.isClassifier()) throw new UnsupportedOperationException("Cannot compare classifier against regressor.");
if (o._output.nclasses() != _output.nclasses()) throw new UnsupportedOperationException("Cannot compare models with different number of classes.");
diff --git a/h2o-algos/src/main/java/hex/glm/GLMModel.java b/h2o-algos/src/main/java/hex/glm/GLMModel.java
index <HASH>..<HASH> 100644
--- a/h2o-algos/src/main/java/hex/glm/GLMModel.java
+++ b/h2o-algos/src/main/java/hex/glm/GLMModel.java
@@ -27,7 +27,6 @@ public class GLMModel extends SupervisedModel<GLMModel,GLMModel.GLMParameters,GL
_nobs = nobs;
_dinfo = dinfo;
}
- @Override public boolean isSupervised(){return true;}
public static class GetScoringModelTask extends DTask.DKeyTask<GetScoringModelTask,GLMModel> {
final double _lambda;
|
Add isSupervised() for DeepLearningModel (autoencoder: false)
Remove isSupervised() from GLM (always true, same as base class).
|
h2oai_h2o-3
|
train
|
b2eca7af9ba0f0352def3f95fbdc0bd0a07555b7
|
diff --git a/LiSE/LiSE/thing.py b/LiSE/LiSE/thing.py
index <HASH>..<HASH> 100644
--- a/LiSE/LiSE/thing.py
+++ b/LiSE/LiSE/thing.py
@@ -249,7 +249,10 @@ class Thing(Node):
loc, nxtloc = self._get_locations()
nobjs = self.engine._node_objs
charn = self.character.name
- return nobjs[charn, loc], [charn, nxtloc]
+ loc = nobjs[charn, loc]
+ if nxtloc is not None:
+ nxtloc = nobjs[charn, nxtloc]
+ return loc, nxtloc
@locations.setter
def locations(self, v):
|
Make Thing.locations a pair of node objects
The next_location used to be a mere tuple and that's not very good
|
LogicalDash_LiSE
|
train
|
f8a6ebdf236a5f760a914a1a2fe3a32b141a76cc
|
diff --git a/src/Codeception/Lib/Friend.php b/src/Codeception/Lib/Friend.php
index <HASH>..<HASH> 100644
--- a/src/Codeception/Lib/Friend.php
+++ b/src/Codeception/Lib/Friend.php
@@ -31,7 +31,7 @@ class Friend {
foreach ($this->multiSessionModules as $module) {
$name = $module->_getName();
$currentUserData[$name] = $module->_backupSessionData();
- if (empty($this->data)) {
+ if (empty($this->data[$name])) {
$module->_initializeSession();
$this->data[$name] = $module->_backupSessionData();
continue;
|
Fix Friend class to allow multiple MultiSession modules to run properly
|
Codeception_Codeception
|
train
|
0d6a64932ea155bcbc09efe0060c77aabc856d26
|
diff --git a/tests/simulation/conftest.py b/tests/simulation/conftest.py
index <HASH>..<HASH> 100644
--- a/tests/simulation/conftest.py
+++ b/tests/simulation/conftest.py
@@ -5,13 +5,13 @@ from ..compat import mock
from ..helpers import SettingsMock
-server_addess = None
+server_address = None
@pytest.fixture(scope="session", autouse=True)
def target_website(request):
- global server_addess
- server_process, server_addess = start_server()
+ global server_address
+ server_process, server_address = start_server()
request.addfinalizer(cleanup_fetchers)
request.addfinalizer(lambda: stop_server(server_process))
for module in ("browser", "script"):
@@ -25,8 +25,8 @@ def target_website(request):
@pytest.fixture
def target():
- global server_addess
- return server_addess
+ global server_address
+ return server_address
@pytest.fixture
|
Fixed typo: server_addess -> server_address
|
kibitzr_kibitzr
|
train
|
db3c0bf7b176258bb3e8285e04c1cdd872e644e3
|
diff --git a/simuvex/plugins/symbolic_memory.py b/simuvex/plugins/symbolic_memory.py
index <HASH>..<HASH> 100644
--- a/simuvex/plugins/symbolic_memory.py
+++ b/simuvex/plugins/symbolic_memory.py
@@ -285,39 +285,41 @@ class SimSymbolicMemory(SimMemory): #pylint:disable=abstract-method
i = 0
while i < num_bytes:
actual_addr = addr + i
+ page_num = actual_addr/self.mem._page_size
+
try:
b = self.mem[actual_addr]
- if isinstance(b, (int, long, str)):
- b = self.state.se.BVV(b, 8)
the_bytes[i] = b
- try:
- page = self.mem._pages[actual_addr/self.mem._page_size]
- if page._sinkholed and len(page) == 0:
- i += self.mem._page_size - actual_addr%self.mem._page_size
- else:
- i += 1
- except KeyError: # this one is from missing pages
+ page = self.mem._pages[page_num]
+ if page._sinkholed and len(page) == 0:
+ i += self.mem._page_size - actual_addr%self.mem._page_size
+ else:
i += 1
except KeyError: # this one is from missing bytes
missing.append(i)
- i += 1
+ if len(self.mem._pages[page_num]) == 0: # the whole page is missing!
+ i += self.mem._page_size - actual_addr%self.mem._page_size
+ else:
+ i += 1
l.debug("... %d found, %d missing", len(the_bytes), len(missing))
if len(missing) > 0:
name = "%s_%x" % (self.id, addr)
- b = self.get_unconstrained_bytes(name, num_bytes*8, source=addr)
+ all_missing = [ self.get_unconstrained_bytes(name, min(self.mem._page_size, num_bytes)*8, source=i) for i in range(addr, addr+num_bytes, self.mem._page_size) ]
if self.id == 'reg' and self.state.arch.register_endness == 'Iend_LE':
- b = b.reversed
+ all_missing = [ a.reversed for a in all_missing ]
if self.id == 'mem' and self.state.arch.memory_endness == 'Iend_LE':
- b = b.reversed
+ all_missing = [ a.reversed for a in all_missing ]
+ b = self.state.se.Concat(*all_missing)
self.state.log.add_event('uninitialized', memory_id=self.id, addr=addr, size=num_bytes)
default_mo = SimMemoryObject(b, addr)
for m in missing:
the_bytes[m] = default_mo
- self.mem[addr+m] = default_mo
+ # self.mem[addr+m] = default_mo
+ self.mem.store_memory_object(default_mo, overwrite=False)
if 0 in the_bytes and isinstance(the_bytes[0], SimMemoryObject) and len(the_bytes) == the_bytes[0].object.length/8:
for mo in the_bytes.itervalues():
|
change the way unconstrained bytes are created (do it by page at the most to avoid crashing Z3)
|
angr_angr
|
train
|
14c5a708661e10308e7634de0a520927a97830b0
|
diff --git a/complete_test.go b/complete_test.go
index <HASH>..<HASH> 100644
--- a/complete_test.go
+++ b/complete_test.go
@@ -13,7 +13,6 @@ const (
type IncrementorJob struct {
current int
next chan int
- stop chan bool
}
func (i *IncrementorJob) Serve(ctx context.Context) error {
@@ -22,22 +21,16 @@ func (i *IncrementorJob) Serve(ctx context.Context) error {
case i.next <- i.current + 1:
i.current++
if i.current >= JobLimit {
+ fmt.Println("Stopping the service")
return ErrComplete
}
- case <-ctx.Done():
- fmt.Println("Stopping the service")
- // We sync here just to guarantee the output of "Stopping the service",
- // so this passes the test reliably.
- // Most services would simply "return" here.
- i.stop <- true
- return ctx.Err()
}
}
}
func TestCompleteJob(t *testing.T) {
supervisor := NewSimple("Supervisor")
- service := &IncrementorJob{0, make(chan int), make(chan bool)}
+ service := &IncrementorJob{0, make(chan int)}
supervisor.Add(service)
supervisor.ServeBackground()
@@ -45,10 +38,6 @@ func TestCompleteJob(t *testing.T) {
fmt.Println("Got:", <-service.next)
fmt.Println("Got:", <-service.next)
- <-service.stop
-
- fmt.Println("IncrementorJob exited as Complete()")
-
supervisor.Stop()
// Output:
|
Fix for TestCompleteJob maybe? not sure I understand how this test works
|
thejerf_suture
|
train
|
60c0ea533b3f6645f66386758389125bd1ae987d
|
diff --git a/lib/chef/resource/dsc_resource.rb b/lib/chef/resource/dsc_resource.rb
index <HASH>..<HASH> 100644
--- a/lib/chef/resource/dsc_resource.rb
+++ b/lib/chef/resource/dsc_resource.rb
@@ -55,7 +55,6 @@ class Chef
super
@properties = ToTextHash.new
@resource = nil
- @reboot_action = :nothing
end
def resource(value = nil)
@@ -105,13 +104,7 @@ class Chef
# If the set method of the DSC resource indicate that a reboot
# is necessary, reboot_action provides the mechanism for a reboot to
# be requested.
- def reboot_action(value = nil)
- if value
- @reboot_action = value
- else
- @reboot_action
- end
- end
+ property :reboot_action, Symbol, default: :nothing, equal_to: [:nothing, :reboot_now, :request_reboot]
def timeout(arg = nil)
set_or_return(
|
Properly validate reboot_action in dsc_resource
Check the passed value to see if it's one of the values we support instead of failing hard later when the user passes the wrong thing.
|
chef_chef
|
train
|
9df4234de6615f904c8a8e066b90911c236f1e52
|
diff --git a/agent/agent.go b/agent/agent.go
index <HASH>..<HASH> 100644
--- a/agent/agent.go
+++ b/agent/agent.go
@@ -112,7 +112,11 @@ func (a *HostAgent) startService(controlClient *client.ControlClient, service *s
portOps += fmt.Sprintf(" -p %d", endpoint.PortNumber)
}
}
- cmdString := fmt.Sprintf("docker run %s -d %s %s", portOps, service.ImageId, service.Startup)
+
+ volumeBinding := "/opt/serviced:/serviced"
+ proxyCmd := "/serviced/bin/proxy -config /serviced/conf/proxy.conf"
+
+ cmdString := fmt.Sprintf("docker run %s -d -v %s %s %s", portOps, volumeBinding, service.ImageId, proxyCmd)
log.Printf("Starting: %s", cmdString)
diff --git a/interfaces.go b/interfaces.go
index <HASH>..<HASH> 100644
--- a/interfaces.go
+++ b/interfaces.go
@@ -155,7 +155,7 @@ type ContainerState struct {
Cmd []string
Dns []string
Image string
- Volumes map[string]string
+ Volumes map[string]map[string]string
VolumesFrom string
Entrypoint []string
}
@@ -180,7 +180,7 @@ type ContainerState struct {
SysInitPath string
ResolvConfPath string
Volumes map[string]string
- VolumesRW map[string]string
+ VolumesRW map[string]bool
}
// A new service instance (ServiceState)
|
Fix ContainerState issue; inject the proxy and configuration at container start
|
control-center_serviced
|
train
|
715da9c55a29cbcbeccf196742a965c2ec622342
|
diff --git a/lib/brightbox-cli/commands/groups-create.rb b/lib/brightbox-cli/commands/groups-create.rb
index <HASH>..<HASH> 100644
--- a/lib/brightbox-cli/commands/groups-create.rb
+++ b/lib/brightbox-cli/commands/groups-create.rb
@@ -8,12 +8,9 @@ module Brightbox
c.flag [:d, :description]
c.action do |global_options, options, args|
- name = options[:n]
- raise "You must specify a name for the server group" if !name || name.empty?
-
params = {}
- params[:name] = name
+ params[:name] = options[:n] if options[:n]
params[:description] = options[:d] if options[:d]
info "Creating a new server group"
diff --git a/lib/brightbox-cli/vendor/fog/lib/fog/brightbox/models/compute/server.rb b/lib/brightbox-cli/vendor/fog/lib/fog/brightbox/models/compute/server.rb
index <HASH>..<HASH> 100644
--- a/lib/brightbox-cli/vendor/fog/lib/fog/brightbox/models/compute/server.rb
+++ b/lib/brightbox-cli/vendor/fog/lib/fog/brightbox/models/compute/server.rb
@@ -41,11 +41,19 @@ module Fog
end
def zone_id
- attributes[:zone_id] || zone[:id] || zone['id']
+ if t_zone_id = attributes[:zone_id]
+ t_zone_id
+ elsif zone
+ zone[:id] || zone['id']
+ end
end
def flavor_id
- attributes[:flavor_id] || server_type[:id] || server_type['id']
+ if t_flavour_id = attributes[:flavor_id]
+ t_flavour_id
+ elsif server_type
+ server_type[:id] || server_type['id']
+ end
end
def zone_id=(incoming_zone_id)
diff --git a/lib/brightbox-cli/vendor/fog/lib/fog/brightbox/models/compute/server_group.rb b/lib/brightbox-cli/vendor/fog/lib/fog/brightbox/models/compute/server_group.rb
index <HASH>..<HASH> 100644
--- a/lib/brightbox-cli/vendor/fog/lib/fog/brightbox/models/compute/server_group.rb
+++ b/lib/brightbox-cli/vendor/fog/lib/fog/brightbox/models/compute/server_group.rb
@@ -18,7 +18,6 @@ module Fog
attribute :default
def save
- requires :name
options = {
:name => name,
:description => description
|
Sync fog with latest version and update group create command
|
brightbox_brightbox-cli
|
train
|
739c787f7e9698852ee1ada24227c6f9519f9fba
|
diff --git a/buffalo/cmd/updater/dep.go b/buffalo/cmd/updater/dep.go
index <HASH>..<HASH> 100644
--- a/buffalo/cmd/updater/dep.go
+++ b/buffalo/cmd/updater/dep.go
@@ -63,24 +63,36 @@ func DepEnsure(r *Runner) error {
return errors.WithStack(err)
}
- for _, p := range []string{"github.com/gobuffalo/tags@v2.0.0", "github.com/gobuffalo/suite@v2.0.0"} {
- cc = exec.Command("dep", "ensure", "-v", "-add", p)
- cc.Stdin = os.Stdin
- cc.Stderr = os.Stderr
- cc.Stdout = os.Stdout
- if err := cc.Run(); err != nil {
- return errors.WithStack(err)
- }
+ apkg := []string{
+ "github.com/gobuffalo/tags@v2.0.0",
+ "github.com/gobuffalo/suite@v2.0.0",
}
+ args := []string{"ensure", "-v", "-add"}
- for _, p := range []string{"github.com/markbates/inflect"} {
- cc = exec.Command("dep", "ensure", "-v", "-update", p)
- cc.Stdin = os.Stdin
- cc.Stderr = os.Stderr
- cc.Stdout = os.Stdout
- if err := cc.Run(); err != nil {
- return errors.WithStack(err)
- }
+ for _, p := range apkg {
+ args = append(args, p)
}
- return nil
+ cc = exec.Command("dep", args...)
+ cc.Stdin = os.Stdin
+ cc.Stderr = os.Stderr
+ cc.Stdout = os.Stdout
+ if err := cc.Run(); err != nil {
+ return errors.WithStack(err)
+ }
+
+ upkg := []string{
+ "github.com/gobuffalo/buffalo",
+ "github.com/gobuffalo/plush",
+ "github.com/markbates/inflect",
+ }
+
+ args = []string{"ensure", "-v", "-update"}
+ for _, p := range upkg {
+ args = append(args, p)
+ }
+ cc = exec.Command("dep", args...)
+ cc.Stdin = os.Stdin
+ cc.Stderr = os.Stderr
+ cc.Stdout = os.Stdout
+ return cc.Run()
}
|
improved the updater a bit more
|
gobuffalo_buffalo
|
train
|
506d304f1ac20bbdffde22282993001ecff5b34c
|
diff --git a/apispec/ext/marshmallow/__init__.py b/apispec/ext/marshmallow/__init__.py
index <HASH>..<HASH> 100644
--- a/apispec/ext/marshmallow/__init__.py
+++ b/apispec/ext/marshmallow/__init__.py
@@ -47,13 +47,13 @@ class MarshmallowPlugin(BasePlugin):
def __init__(self, schema_name_resolver=None):
super(MarshmallowPlugin, self).__init__()
self.schema_name_resolver = schema_name_resolver
+ self.spec = None
+ self.openapi_version = None
+ self.openapi = None
def init_spec(self, spec):
- """Initialize plugin with APISpec object
-
- :param APISpec spec: APISpec object this plugin instance is attached to
- """
super(MarshmallowPlugin, self).init_spec(spec)
+ self.spec = spec
self.openapi_version = spec.openapi_version
self.openapi = OpenAPIConverter(openapi_version=spec.openapi_version)
diff --git a/apispec/plugin.py b/apispec/plugin.py
index <HASH>..<HASH> 100644
--- a/apispec/plugin.py
+++ b/apispec/plugin.py
@@ -11,7 +11,6 @@ class BasePlugin(object):
:param APISpec spec: APISpec object this plugin instance is attached to
"""
- self.spec = spec
def definition_helper(self, name, definition, **kwargs):
"""Must return definition as a dict."""
diff --git a/tests/test_core.py b/tests/test_core.py
index <HASH>..<HASH> 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -379,15 +379,6 @@ class TestPlugins:
if method == 'delete':
return {'description': 'Clever description'}
- def test_plugin_init_spec(self):
- plugin = BasePlugin()
- spec = APISpec(
- title='Swagger Petstore',
- version='1.0.0',
- plugins=(plugin, )
- )
- assert plugin.spec == spec
-
def test_plugin_definition_helper_is_used(self):
spec = APISpec(
title='Swagger Petstore',
|
Don't store spec object in BasePlugin.init_spec
|
marshmallow-code_apispec
|
train
|
ccd17e74f3c7edd36ab87e93440d868dd397713b
|
diff --git a/polyaxon_cli/managers/deploy.py b/polyaxon_cli/managers/deploy.py
index <HASH>..<HASH> 100644
--- a/polyaxon_cli/managers/deploy.py
+++ b/polyaxon_cli/managers/deploy.py
@@ -172,7 +172,9 @@ class DeployManager(object):
args = ['delete', '--purge', 'polyaxon']
if hooks:
args += ['--no-hooks']
+ click.echo('Running teardown command ...')
self.helm.execute(args=args)
+ Printer.print_success('Deployment successfully deleted.', add_sign=True)
def teardown_on_docker_compose(self, hooks):
pass
|
Add logging for teardown
* Fix deploy logging
|
polyaxon_polyaxon
|
train
|
e41e0c4a1d79d619c29ecfe0b38625ab36d2fe47
|
diff --git a/core/src/main/java/com/google/bitcoin/core/ECKey.java b/core/src/main/java/com/google/bitcoin/core/ECKey.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/com/google/bitcoin/core/ECKey.java
+++ b/core/src/main/java/com/google/bitcoin/core/ECKey.java
@@ -560,7 +560,8 @@ public class ECKey implements EncryptableItem, Serializable {
* EC maths on them.
*
* @param aesKey The AES key to use for decryption of the private key. If null then no decryption is required.
- * @throws KeyCrypterException if this ECKey doesn't have a private part.
+ * @throws KeyCrypterException if there's something wrong with aesKey.
+ * @throws ECKey.MissingPrivateKeyException if this key cannot sign because it's pubkey only.
*/
public ECDSASignature sign(Sha256Hash input, @Nullable KeyParameter aesKey) throws KeyCrypterException {
KeyCrypter crypter = getKeyCrypter();
@@ -721,8 +722,6 @@ public class ECKey implements EncryptableItem, Serializable {
* @throws KeyCrypterException if this ECKey is encrypted and no AESKey is provided or it does not decrypt the ECKey.
*/
public String signMessage(String message, @Nullable KeyParameter aesKey) throws KeyCrypterException {
- if (priv == null)
- throw new MissingPrivateKeyException();
byte[] data = Utils.formatMessageForSigning(message);
Sha256Hash hash = Sha256Hash.createDouble(data);
ECDSASignature sig = sign(hash, aesKey);
diff --git a/core/src/test/java/com/google/bitcoin/wallet/DeterministicKeyChainTest.java b/core/src/test/java/com/google/bitcoin/wallet/DeterministicKeyChainTest.java
index <HASH>..<HASH> 100644
--- a/core/src/test/java/com/google/bitcoin/wallet/DeterministicKeyChainTest.java
+++ b/core/src/test/java/com/google/bitcoin/wallet/DeterministicKeyChainTest.java
@@ -72,6 +72,12 @@ public class DeterministicKeyChainTest {
}
@Test
+ public void signMessage() throws Exception {
+ ECKey key = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
+ key.verifyMessage("test", key.signMessage("test"));
+ }
+
+ @Test
public void events() throws Exception {
// Check that we get the right events at the right time.
final List<List<ECKey>> listenerKeys = Lists.newArrayList();
|
Allow usage of signMessage for deterministic keys.
|
bitcoinj_bitcoinj
|
train
|
e3ed3b58c5722dee6d0b87a3ef609134852a28e8
|
diff --git a/src/system/modules/metamodels/TableMetaModel.php b/src/system/modules/metamodels/TableMetaModel.php
index <HASH>..<HASH> 100644
--- a/src/system/modules/metamodels/TableMetaModel.php
+++ b/src/system/modules/metamodels/TableMetaModel.php
@@ -44,7 +44,7 @@ class TableMetaModel extends Backend
*/
public function checkDependencies($strBuffer, $strTemplate)
{
- if ($this->Input->get('do') != 'metamodel')
+ if ($this->Input->get('do') != 'metamodels')
{
return $strBuffer;
}
|
Fixed typo in checkDependencies.
|
MetaModels_core
|
train
|
dd5dc0f4ec9d3ad49abdc979acead7f1d9f375d4
|
diff --git a/massautocomplete.js b/massautocomplete.js
index <HASH>..<HASH> 100644
--- a/massautocomplete.js
+++ b/massautocomplete.js
@@ -175,22 +175,22 @@ angular.module('MassAutoComplete', [])
// It is important that before triggering hooks the model's view
// value will be synced with the visible value to the user. This will
// allow the consumer controller to rely on its local ng-model.
- function update_model_value() {
- var val = current_element.val();
- if (current_model.$modelValue !== val) {
- current_model.$setViewValue(val);
+ function update_model_value(value) {
+ if (current_model.$modelValue !== value) {
+ current_model.$setViewValue(value);
current_model.$render();
}
- return val;
}
// Set the current selection while navigating through the menu.
function set_selection(i) {
- // We use jquery val instead of setting the model's view value
+ // We use value instead of setting the model's view value
// because we watch the model value and setting it will trigger
// a new suggestion cycle.
- current_element.val($scope.results[i].value);
+ var selected = $scope.results[i];
+ current_element.val(selected.value);
$scope.selected_index = i;
+ return selected;
}
// Apply and accept the current selection made from the menu.
@@ -201,8 +201,9 @@ angular.module('MassAutoComplete', [])
if (!$scope.show_autocomplete || i > $scope.results.length || i < 0)
return;
- set_selection(i);
- last_selected_value = update_model_value();
+ var selected = set_selection(i);
+ last_selected_value = selected.value;
+ update_model_value(selected.value);
$scope.show_autocomplete = false;
current_options.on_select && current_options.on_select($scope.results[$scope.selected_index]);
|
Fetch selected value only once per suggestion cycle. Resolves #4
To avoid inconsistencies between the various debounced events we fgetch the value once when setting the selected index and caring it throughout the rest of the suggestion cycle.
|
hakib_MassAutocomplete
|
train
|
268a0392c03b63958ea342f440a3173195b3e78d
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -119,18 +119,18 @@ var decoders = [
c += varint.decode.bytes
//TODO: positive integers keys are always in order!
//floats or negative numbers encoded as strings. or may not be keys?
- if(type === 7) throw new Error('reserved type')
+ if(type === 7) throw new Error('reserved type:key')
var key = decoders[type](buffer, start+c, len)
c += len
var tag2 = varint.decode(buffer, start+c)
var type2 = tag2 & TAG_MASK
+ if(type2 === 7) throw new Error('reserved type:value')
var len2 = tag2 >> TAG_SIZE
c += varint.decode.bytes
-
var value = decoders[type2](buffer, start+c, len2)
- c+= len
+ c+= len2
o[key] = value
}
return o
@@ -174,7 +174,7 @@ function encode (value, buffer, start) {
if(type === 7) throw new Error('reserved type')
varint.encode(len << TAG_SIZE | type, buffer, start)
var bytes = varint.encode.bytes
- return encoders[type](value, buffer, start+varint.encode.bytes) + bytes
+ return encoders[type](value, buffer, start+bytes) + bytes
}
function decode (buffer, start) {
@@ -189,14 +189,38 @@ function decode (buffer, start) {
return value
}
+function seekKey (buffer, start, target) {
+ var targetLength = Buffer.byteLength(target) //Buffer.isBuffer(target) ? target.length : Buffer.byteLength(target)
+ var tag = varint.decode(buffer, start)
+ var len = tag >> TAG_SIZE
+ var type = tag & TAG_MASK
+ if(type != OBJECT) throw new Error('expected object')
+ for(var c = varint.decode.bytes; c < len;) {
+ var key_tag = varint.decode(buffer, start+c)
+ c += varint.decode.bytes
+ var key_len = key_tag >> TAG_SIZE
+ var key_type = key_tag & TAG_MASK
+ if(key_type === STRING && targetLength === key_len) {
+ var key = decoders[STRING](buffer, c, key_len)
+ if(key === target)
+ return c+key_len //just return a pointer!
+ }
+ c += key_len
+ var value_tag = varint.decode(buffer, start+c)
+ c += varint.decode.bytes
+ var value_len = value_tag >> TAG_SIZE
+ c += value_len
+ }
+ return -1
+}
+
module.exports = {
encode: encode,
decode: decode,
encodingLength: encodingLength,
- buffer: true
+ buffer: true,
+ seekKey: seekKey
}
-
-
|
seekKey find a key inside on object without parsing!
|
dominictarr_bipf
|
train
|
958b25bf37eb4106292151e0e4e27659c0c49ff8
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -137,18 +137,6 @@ status, input and both outputs to it:
Cheetah.run("ls -l", :logger => logger)
```
-By default, the `Logger::INFO` level will be used for normal messages and the
-`Logger::ERROR` level for messages about errors (non-zero exit status or
-non-empty error output), but this can be changed if needed:
-
-```ruby
-Cheetah.run("ls -l",
- :logger => logger,
- :logger_level_info => Logger::DEBUG,
- :logger_level_error => Logger::WARN
-)
-```
-
### Setting Defaults
To avoid repetition, you can set global default value of any option passed too
diff --git a/lib/cheetah.rb b/lib/cheetah.rb
index <HASH>..<HASH> 100644
--- a/lib/cheetah.rb
+++ b/lib/cheetah.rb
@@ -70,16 +70,16 @@ module Cheetah
# @private
class LogAdapter
- def initialize(logger, level_info, level_error)
- @logger, @level_info, @level_error = logger, level_info, level_error
+ def initialize(logger)
+ @logger = logger
end
def info(message)
- @logger.add(@level_info, message) if @logger
+ @logger.info(message) if @logger
end
def error(message)
- @logger.add(@level_error, message) if @logger
+ @logger.error(message) if @logger
end
end
@@ -88,9 +88,7 @@ module Cheetah
:stdin => "",
:stdout => nil,
:stderr => nil,
- :logger => nil,
- :logger_level_info => Logger::INFO,
- :logger_level_error => Logger::ERROR
+ :logger => nil
}
READ = 0 # @private
@@ -133,12 +131,9 @@ module Cheetah
# If a logger is set, the method will log the executed command(s), final
# exit status, passed input and both captured outputs (unless the `:stdin`,
# `:stdout` or `:stderr` option is set to an `IO`, which prevents logging
- # the corresponding input or output).
- #
- # By default, the `Logger::INFO` level will be used for normal messages and
- # the `Logger::ERROR` level for messages about errors (non-zero exit status
- # or non-empty error output). This can be changed using the
- # `:logger_level_info` and `:logger_level_error` options.
+ # the corresponding input or output). The `Logger::INFO` level will be used
+ # for normal messages and the `Logger::ERROR` level for messages about
+ # errors (non-zero exit status or non-empty error output).
#
# Values of options not set using the `options` parameter are taken from
# {Cheetah.default_options}. If a value is not specified there too, the
@@ -172,10 +167,6 @@ module Cheetah
# produces it
# @option options [Logger, nil] :logger (nil) logger to log the command
# execution
- # @option options [Integer] :logger_level_info (Logger::INFO) level for
- # logging normal messages; makes sense only if `:logger` is specified
- # @option options [Integer] :logger_level_error (Logger::ERROR) level for
- # logging error messages; makes sense only if `:logger` is specified
#
# @example
# Cheetah.run("tar", "xzf", "foo.tar.gz")
@@ -292,11 +283,7 @@ module Cheetah
end
def build_log_adapter(options)
- LogAdapter.new(
- options[:logger],
- options[:logger_level_info],
- options[:logger_level_error]
- )
+ LogAdapter.new(options[:logger])
end
def fork_commands_recursive(commands, pipes)
diff --git a/spec/cheetah_spec.rb b/spec/cheetah_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/cheetah_spec.rb
+++ b/spec/cheetah_spec.rb
@@ -455,34 +455,6 @@ describe Cheetah do
INFO Error output: (none)
EOT
end
-
- it "logs info messages on the level specified by the :logger_level_info option" do
- lambda { |logger|
- Cheetah.run("/bin/true", :logger => logger, :logger_level_info => Logger::DEBUG)
- }.should log(<<-EOT)
- DEBUG Executing "/bin/true".
- DEBUG Standard input: (none)
- DEBUG Status: 0
- DEBUG Standard output: (none)
- DEBUG Error output: (none)
- EOT
- end
-
- it "logs error messages on the level specified by the :logger_level_error option" do
- lambda { |logger|
- begin
- Cheetah.run("/bin/false", :logger => logger, :logger_level_error => Logger::WARN)
- rescue Cheetah::ExecutionFailed
- # Eat it.
- end
- }.should log(<<-EOT)
- INFO Executing "/bin/false".
- INFO Standard input: (none)
- WARN Status: 1
- INFO Standard output: (none)
- INFO Error output: (none)
- EOT
- end
end
describe "options handling" do
|
Recorder: Remove options for setting log levels
Log levels will be handled by the Cheetah::Recorder class that will come
in future commit(s).
|
openSUSE_cheetah
|
train
|
f0734d342ea430310ec6c755b68810b8d75a11a0
|
diff --git a/lib/waterline/utils/query/help-find.js b/lib/waterline/utils/query/help-find.js
index <HASH>..<HASH> 100644
--- a/lib/waterline/utils/query/help-find.js
+++ b/lib/waterline/utils/query/help-find.js
@@ -214,7 +214,7 @@ module.exports = function helpFind(WLModel, s2q, omen, done) {
// Start building the query to the junction table.
var junctionTableQuery = {
- using: firstJoin.child,
+ using: firstJoin.child,// TODO: we should use the same identity as below, right? (e.g. `firstJoin.childCollectionIdentity`)
method: 'find',
criteria: {
where: {
@@ -251,6 +251,13 @@ module.exports = function helpFind(WLModel, s2q, omen, done) {
junctionTableAdapter.find(junctionTableDatastoreName, junctionTableQuery, function(err, junctionTableResults) {
if (err) {
err = forgeAdapterError(err, omen, 'find', junctionTableQuery.using, orm);
+ // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+ // TODO: change the line above back to the following:
+ // ```
+ // err = forgeAdapterError(err, omen, 'find', junctionTableQuery.using, orm);
+ // ```
+ // (this will be fine to do once the bug is fixed that is causing `firstJoin.child` to be built w/ different letter casing than the actual model identity)
+ // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
return nextSetOfJoins(err);
}
|
Add TODOs related to normalizing where identities are coming from (this appears to be the source of the case sensitivity issue with vialess associations).
|
balderdashy_waterline
|
train
|
589425eeca52e8e4e3eed4f55e2aaecffb02a816
|
diff --git a/lib/http.js b/lib/http.js
index <HASH>..<HASH> 100755
--- a/lib/http.js
+++ b/lib/http.js
@@ -17,7 +17,7 @@ exports.request = function(rurl, data, callback, exheaders, exoptions) {
var method = data ? "POST" : "GET";
var headers = {
"User-Agent": "node-soap/" + VERSION,
- "Accept" : "text/html,application/xhtml+xml,application/xml",
+ "Accept" : "text/html,application/xhtml+xml,application/xml,text/xml",
"Accept-Encoding": "none",
"Accept-Charset": "utf-8",
"Connection": "close",
diff --git a/lib/wsdl.js b/lib/wsdl.js
index <HASH>..<HASH> 100755
--- a/lib/wsdl.js
+++ b/lib/wsdl.js
@@ -986,7 +986,7 @@ function open_wsdl(uri, options, callback) {
wsdl.onReady(callback);
}
else {
- callback(new Error('Invalid WSDL URL: '+uri))
+ callback(new Error('Invalid WSDL URL: '+uri + "\n\n\r Code: "+ response.statusCode + "\n\n\r Response Body: " + response.body));
}
});
}
|
Added additional XML mime type. Included server response code and response body in Error
|
vpulim_node-soap
|
train
|
1c54d999f66ab0dd2b69361ffda3a32979671c2b
|
diff --git a/config/hoe.rb b/config/hoe.rb
index <HASH>..<HASH> 100644
--- a/config/hoe.rb
+++ b/config/hoe.rb
@@ -52,6 +52,7 @@ $hoe = Hoe.spec(GEM_NAME) do |p|
p.summary = SUMMARY
p.url = HOMEPATH
p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT
+ p.readme_file = "README.markdown"
p.test_globs = ["test/**/test_*.rb"]
p.clean_globs |= ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store', 'classes'] #An array of file patterns to delete on clean.
|
let hoe know about the renamed readme
|
jarib_celerity
|
train
|
89b0a773e11b86b2a1afffffee96e7596d258105
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -160,6 +160,12 @@ You can also import a specific sheet by its number:
$users = (new FastExcel)->sheet(3)->import('file.xlsx');
```
+Import sheets with sheets names
+
+```phpregexp
+$sheets = (new FastExcel)->withSheetsNames()->importSheets('file.xlsx');
+```
+
### Export large collections with chunk
Export rows one by one to avoid `memory_limit` issues [using `yield`](https://www.php.net/manual/en/language.generators.syntax.php):
diff --git a/src/FastExcel.php b/src/FastExcel.php
index <HASH>..<HASH> 100644
--- a/src/FastExcel.php
+++ b/src/FastExcel.php
@@ -27,6 +27,11 @@ class FastExcel
private $with_header = true;
/**
+ * @var bool
+ */
+ private $with_sheets_names = false;
+
+ /**
* @var int
*/
private $start_row = 1;
@@ -105,6 +110,16 @@ class FastExcel
/**
* @return $this
*/
+ public function withSheetsNames()
+ {
+ $this->with_sheets_names = true;
+
+ return $this;
+ }
+
+ /**
+ * @return $this
+ */
public function startRow(int $row)
{
$this->start_row = $row;
diff --git a/src/Importable.php b/src/Importable.php
index <HASH>..<HASH> 100644
--- a/src/Importable.php
+++ b/src/Importable.php
@@ -70,7 +70,11 @@ trait Importable
$collections = [];
foreach ($reader->getSheetIterator() as $key => $sheet) {
- $collections[] = $this->importSheet($sheet, $callback);
+ if ($this->with_sheets_names) {
+ $collections[$sheet->getName()] = $this->importSheet($sheet, $callback);
+ } else {
+ $collections[] = $this->importSheet($sheet, $callback);
+ }
}
$reader->close();
diff --git a/tests/FastExcelTest.php b/tests/FastExcelTest.php
index <HASH>..<HASH> 100644
--- a/tests/FastExcelTest.php
+++ b/tests/FastExcelTest.php
@@ -175,6 +175,32 @@ class FastExcelTest extends TestCase
* @throws \Box\Spout\Reader\Exception\ReaderNotOpenedException
* @throws \Box\Spout\Writer\Exception\WriterNotOpenedException
*/
+ public function testImportMultiSheetWithSheetNamesXLSX()
+ {
+ $collections = [
+ 'Sheet with name A' => collect([['test' => 'row1 col1'], ['test' => 'row2 col1'], ['test' => 'row3 col1']]),
+ 'Sheet with name B' => $this->collection(),
+ ];
+ $file = __DIR__.'/test_multi_sheets_with_sheets_names.xlsx';
+ $sheets = new SheetCollection($collections);
+ (new FastExcel($sheets))->export($file);
+
+ $sheets = (new FastExcel())->withSheetsNames()->importSheets($file);
+ $this->assertInstanceOf(SheetCollection::class, $sheets);
+
+ $this->assertEquals($collections['Sheet with name A'], collect($sheets->get('Sheet with name A')));
+ $this->assertEquals($collections['Sheet with name B'], collect($sheets->get('Sheet with name B')));
+
+ unlink($file);
+ }
+
+ /**
+ * @throws \Box\Spout\Common\Exception\IOException
+ * @throws \Box\Spout\Common\Exception\InvalidArgumentException
+ * @throws \Box\Spout\Common\Exception\UnsupportedTypeException
+ * @throws \Box\Spout\Reader\Exception\ReaderNotOpenedException
+ * @throws \Box\Spout\Writer\Exception\WriterNotOpenedException
+ */
public function testExportWithHeaderStyle()
{
$original_collection = $this->collection();
|
Import multiple sheets with sheets name. Issue #<I> (#<I>)
|
rap2hpoutre_fast-excel
|
train
|
2a7c779f6b678d441e3c79fa6bddcdf75d427996
|
diff --git a/dist/nlmaps.iife.js b/dist/nlmaps.iife.js
index <HASH>..<HASH> 100644
--- a/dist/nlmaps.iife.js
+++ b/dist/nlmaps.iife.js
@@ -2056,6 +2056,6 @@ nlmaps.geoLocate = function (map) {
addGeoLocControlToMap(nlmaps.lib, geolocator, map);
};
-return nlmaps;
+exports.nlmaps = nlmaps;
}((this.window = this.window || {})));
|
and added builded version for nlmaps export change
|
geo-frontend_nlmaps
|
train
|
e5b469733ba9a6b5979ec6a6bbfdbcd46f64e259
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -5,9 +5,9 @@ import re
from setuptools import find_packages, setup
VERSIONFILE = "tweepy/__init__.py"
-ver_file = open(VERSIONFILE, "rt").read()
VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]"
-mo = re.search(VSRE, ver_file, re.M)
+with open(VERSIONFILE, "rt") as ver_file:
+ mo = re.search(VSRE, ver_file.read(), re.M)
if mo:
version = mo.group(1)
|
Properly handle and close file in setup.py
|
tweepy_tweepy
|
train
|
65a7c6ac6cb09bf5b5191cf668182fcb3f88317b
|
diff --git a/Swat/SwatTextarea.php b/Swat/SwatTextarea.php
index <HASH>..<HASH> 100644
--- a/Swat/SwatTextarea.php
+++ b/Swat/SwatTextarea.php
@@ -1,8 +1,8 @@
<?php
-require_once('Swat/SwatControl.php');
-require_once('Swat/SwatHtmlTag.php');
-require_once('Swat/SwatState.php');
+require_once 'Swat/SwatControl.php';
+require_once 'Swat/SwatHtmlTag.php';
+require_once 'Swat/SwatState.php';
/**
* A multi-line text entry widget
@@ -11,8 +11,8 @@ require_once('Swat/SwatState.php');
* @copyright 2004-2005 silverorange
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
*/
-class SwatTextarea extends SwatControl implements SwatState {
-
+class SwatTextarea extends SwatControl implements SwatState
+{
/**
* Text content of the widget
*
@@ -23,7 +23,7 @@ class SwatTextarea extends SwatControl implements SwatState {
/**
* Required
*
- * Must have a non-empty value when processed
+ * Whether a value is required for this widget.
*
* @var bool
*/
@@ -32,7 +32,7 @@ class SwatTextarea extends SwatControl implements SwatState {
/**
* Rows
*
- * Number of rows for the HTML textarea tag
+ * The number of rows for the XHTML textarea tag.
*
* @var int
*/
@@ -41,16 +41,24 @@ class SwatTextarea extends SwatControl implements SwatState {
/**
* Columns
*
- * Number of columns for the HTML textarea tag
+ * The number of columns for the XHTML textarea tag.
+ *
* @var int
*/
public $cols = 50;
-
- public function display() {
+
+ /**
+ * Displays this textarea
+ *
+ * Outputs an appropriate XHTML tag.
+ */
+ public function display()
+ {
$textarea_tag = new SwatHtmlTag('textarea');
$textarea_tag->name = $this->id;
$textarea_tag->id = $this->id;
- // Attributes rows and cols are required in a textarea for XHTML strict.
+ // NOTE: The attributes rows and cols are required in
+ // a textarea for XHTML strict.
$textarea_tag->rows = $this->rows;
$textarea_tag->cols = $this->cols;
@@ -59,7 +67,14 @@ class SwatTextarea extends SwatControl implements SwatState {
$textarea_tag->close();
}
- public function process() {
+ /**
+ * Processes this textarea
+ *
+ * If a validation error occurs, an error message is attached to this
+ * widget.
+ */
+ public function process()
+ {
$this->value = $_POST[$this->id];
if ($this->required && !strlen($this->value)) {
@@ -68,11 +83,27 @@ class SwatTextarea extends SwatControl implements SwatState {
}
}
- public function getState() {
+ /**
+ * Gets the current state of this textarea
+ *
+ * @return boolean the current state of this textarea.
+ *
+ * @see SwatState::getState()
+ */
+ public function getState()
+ {
return $this->value;
}
- public function setState($state) {
+ /**
+ * Sets the current state of this textarea
+ *
+ * @param boolean $state the new state of this textarea.
+ *
+ * @see SwatState::setState()
+ */
+ public function setState($state)
+ {
$this->value = $state;
}
}
|
Clean up this file.
svn commit r<I>
|
silverorange_swat
|
train
|
752a0f85504f567ab64175ca78715260a47680a6
|
diff --git a/modules/archi/includes/archiAdresse.class.php b/modules/archi/includes/archiAdresse.class.php
index <HASH>..<HASH> 100644
--- a/modules/archi/includes/archiAdresse.class.php
+++ b/modules/archi/includes/archiAdresse.class.php
@@ -493,41 +493,43 @@ class archiAdresse extends ArchiContenu
));
- $evenement = $e->displaySingleEvent(152,$t,'list');
-
- $t->assign_block_vars('evenement', $evenement['evenementData']);
+ $requeteIdEvenements = "
+ SELECT idEvenement
+ FROM _adresseEvenement
+ WHERE idAdresse = ".$idAdresse."
+ ";
+ $resultIdEvenements = $this->connexionBdd->requete($requeteIdEvenements);
- foreach ($evenement['menuArray'] as $menuElt){
- $t->assign_block_vars($menuElt[0], $menuElt[1]);
- }
- foreach ($evenement['arrayPersonne'] as $personne){
- $t->assign_block_vars($personne[0], $personne[1]);
+ while($fetch = mysql_fetch_assoc($resultIdEvenements)){
+ $evenement = $e->getEventInfos($fetch['idEvenement']);
+
+ $t->assign_block_vars('evenement', $evenement['evenementData']);
+
+
+ if(isset($evenement['menuArray'])){
+ foreach ($evenement['menuArray'] as $menuElt){
+ $t->assign_block_vars($menuElt[0], $menuElt[1]);
+ }
+ }
+ if(isset($evenement['arrayPersonne'])){
+ foreach ($evenement['arrayPersonne'] as $personne){
+ $t->assign_block_vars($personne[0], $personne[1]);
+ }
+ }
+
+ if(isset($evenement['arrayFormEvent'])){
+ $t->assign_block_vars($personne[0], $personne[1]);
+ }
+
+ if(isset($evenement['arrayCourantArchi'])){
+ foreach ($evenement['arrayCourantArchi'] as $courantArchi){
+ $t->assign_block_vars($courantArchi[0], $courantArchi[1]);
+ }
+ }
}
-
-
- //debug($hoho);
- //eval($hoho);
-
- /*
- $t->assign_block_vars('listEvt', array());
- $t->assign_var_from_handle('listEvt.evenement', 'list');
-
- */
-
- //$t->assign_var('listeEvenements', $hoho,'list');
- /*$t->assign_var_from_handle(
- 'listeEvenements', 'list'
- );
- */
-
- //$e->displaySingleEvent(153,$t);
- /*$t->assign_var_from_handle(
- 'listeEvenements', 'list'
- );*/
-
-
+
$t->assign_vars(array(
'title' => $title
diff --git a/modules/archi/includes/archiEvenement.class.php b/modules/archi/includes/archiEvenement.class.php
index <HASH>..<HASH> 100644
--- a/modules/archi/includes/archiEvenement.class.php
+++ b/modules/archi/includes/archiEvenement.class.php
@@ -1331,7 +1331,7 @@ class archiEvenement extends config
* @param unknown $idEvenement : id of the event to display
* @return string : html of the detail event
*/
- public function displaySingleEvent($idEvenement,$template,$handle,$params = array()){
+ public function getEventInfos($idEvenement,$params = array()){
$html ="";
$authentification = new archiAuthentification();
@@ -1461,7 +1461,7 @@ class archiEvenement extends config
'url' => $this->creerUrl('', 'evenementListe', array('selection' => 'courant', 'id' => $res->idCourantArchitectural)),
'nom' => $res->nom));
*/
- $arrayCourantArchi[] = array('isCourantArchi.archi' , array(
+ $arrayCourantArchi[] = array('evenement.isCourantArchi.archi' , array(
'url' => $this->creerUrl('', 'evenementListe', array('selection' => 'courant', 'id' => $res->idCourantArchitectural)),
'nom' => $res->nom));
}
@@ -7093,7 +7093,6 @@ class archiEvenement extends config
} else {
$nomTypeEvenement=strtolower($res['nomTypeEvenement']);
}
- debug($datetime);
$dateTxt=_("Année")." ".$articleAvantTypeEvenement." <time itemprop='startDate' datetime='".$datetime."'>".$nomTypeEvenement." : $environDateDebutTxt".$this->date->toFrenchAffichage($res['dateDebut'])."</time>";
} else {
if (archiPersonne::isPerson($idEvenementGroupeAdresse)) {
|
Merged two templates and processing related, still some missing
informations
|
Archi-Strasbourg_archi-wiki
|
train
|
c0cb60294e9a307168a37b120fe7c17affa5e9b6
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -61,8 +61,9 @@ function prepeare(stack) {
}
module.exports = function (options) {
+ var parse = stackman(options);
return function (err, req, res, next) {
- stackman(options)(err, function (stack) {
+ parse(err, function (stack) {
stack = prepeare(stack);
stack.message = err.message || err.toString();
res
|
Move stackman init to outer scope
|
floatdrop_express-stackman
|
train
|
9283169d7abd458982fffdaf72063fe87468d1aa
|
diff --git a/treeherder/log_parser/failureline.py b/treeherder/log_parser/failureline.py
index <HASH>..<HASH> 100644
--- a/treeherder/log_parser/failureline.py
+++ b/treeherder/log_parser/failureline.py
@@ -138,7 +138,16 @@ def create_failure_line(job_log, failure_line):
def create(job_log, log_list):
- failure_lines = [create_failure_line(job_log, failure_line) for failure_line in log_list]
+ for failure_line in log_list:
+ action = failure_line['action']
+ if action not in FailureLine.ACTION_LIST:
+ newrelic.agent.record_custom_event("unsupported_failure_line_action", failure_line)
+ logger.exception(ValueError(f'Unsupported FailureLine ACTION: {action}'))
+ failure_lines = [
+ create_failure_line(job_log, failure_line)
+ for failure_line in log_list
+ if failure_line['action'] in FailureLine.ACTION_LIST
+ ]
job_log.update_status(JobLog.PARSED)
return failure_lines
|
Bug <I> - Only create FailureLines for supported actions (#<I>)
|
mozilla_treeherder
|
train
|
c93f2e118cabd9278bf4d95812e1e0bd74069c21
|
diff --git a/holoviews/plotting/__init__.py b/holoviews/plotting/__init__.py
index <HASH>..<HASH> 100644
--- a/holoviews/plotting/__init__.py
+++ b/holoviews/plotting/__init__.py
@@ -243,8 +243,9 @@ styles = {'default': './default.mplstyle'}
set_style('default')
# Upgrade Dimension formatters to matplotlib
-Dimension.type_formatters = {k: fn if isinstance(fn, ticker.Formatter) else ticker.FuncFormatter(fn)
- for k, fn in Dimension.type_formatters.items()}
+wrapped_formatters = {k: fn if isinstance(fn, ticker.Formatter) else ticker.FuncFormatter(fn)
+ for k, fn in Dimension.type_formatters.items()}
+Dimension.type_formatters.update(wrapped_formatters)
# Define matplotlib based style cycles and Palettes
Cycle.default_cycles.update({'default_colors': plt.rcParams['axes.color_cycle']})
|
Updating rather than replacing wrapped Dimension.type_formatters
Avoids param warnings
|
pyviz_holoviews
|
train
|
7e163de0ffb03f3ff0844f25c12ad27c70915d24
|
diff --git a/api/opentrons/robot/robot_configs.py b/api/opentrons/robot/robot_configs.py
index <HASH>..<HASH> 100644
--- a/api/opentrons/robot/robot_configs.py
+++ b/api/opentrons/robot/robot_configs.py
@@ -1,3 +1,7 @@
+# In this file we often align code for readability triggering PEP8 warnings
+# So...
+# pylama:skip=1
+
# TODO: jmg 11/2 This file is meant to be a temporary
# fix to make development easier and should be removed
# once this configuration information is part of persistent robot data
@@ -44,14 +48,11 @@ Amedeo = robot_config(
max_speeds='M203.1 X300 Y200 Z50 A50 B8 C8',
acceleration='M204 S1000 X4000 Y3000 Z2000 A2000 B3000 C3000',
current='M907 X1.2 Y1.5 Z0.8 A0.8 B0.25 C0.25',
- gantry_calibration=[[ 1.00283019e+00, -4.83425414e-03, 0.00000000e+00,
- -3.52323132e+01],
- [ -1.13207547e-02, 9.97237569e-01, 0.00000000e+00,
- -1.81761811e+00],
- [ 0.00000000e+00, 0.00000000e+00, 1.00000000e+00,
- 4.50000000e+00],
- [ -5.03305613e-19, 2.60208521e-18, 0.00000000e+00,
- 1.00000000e+00]],
+ gantry_calibration=[
+ [ 1.00283019e+00, -4.83425414e-03, 0.00000000e+00, -3.52323132e+01],
+ [ -1.13207547e-02, 9.97237569e-01, 0.00000000e+00, -1.81761811e+00],
+ [ 0.00000000e+00, 0.00000000e+00, 1.00000000e+00, 4.50000000e+00],
+ [ -5.03305613e-19, 2.60208521e-18, 0.00000000e+00, 1.00000000e+00]],
probe_center=(289, 295, 55.0),
instrument_offset=(-37.99669417, 30.15314473, -0.25), # left to right
# X, Y and Z measurement of imaginary bounding box surrounding the probe
@@ -84,14 +85,11 @@ Rosalind = robot_config(
# X, Y and Z measurement of imaginary bounding box surrounding the probe
# giving safe distance to position for probing
probe_dimensions=(60.0, 60.0, 60.0),
- gantry_calibration=[[ 9.99056604e-01, 4.83425414e-03, 0.00000000e+00,
- -2.63882414e+01],
- [ -9.43396226e-04, 1.00069061e+00, 0.00000000e+00,
- -2.30371104e+00],
- [ 0.00000000e+00, 0.00000000e+00, 1.00000000e+00,
- 5.00000000e+00],
- [ -5.03305613e-19, 2.60208521e-18, 0.00000000e+00,
- 1.00000000e+00]],
+ gantry_calibration=[
+ [ 9.99056604e-01, 4.83425414e-03, 0.00000000e+00, -2.63882414e+01],
+ [ -9.43396226e-04, 1.00069061e+00, 0.00000000e+00, -2.30371104e+00],
+ [ 0.00000000e+00, 0.00000000e+00, 1.00000000e+00, 5.00000000e+00],
+ [ -5.03305613e-19, 2.60208521e-18, 0.00000000e+00, 1.00000000e+00]],
instrument_offset=(-37.43826124, 31.44202338, -0.5) # left to right
)
diff --git a/api/tests/opentrons/labware/test_pipette.py b/api/tests/opentrons/labware/test_pipette.py
index <HASH>..<HASH> 100644
--- a/api/tests/opentrons/labware/test_pipette.py
+++ b/api/tests/opentrons/labware/test_pipette.py
@@ -50,7 +50,7 @@ def test_aspirate_move_to(robot):
assert (current_pos == (9.5, 0.0, 0.0)).all()
current_pos = pose_tracker.absolute(robot.poses, p200)
- assert isclose(current_pos, (175.34, 127.94, 10.25)).all()
+ assert isclose(current_pos, (175.34, 127.94, 10)).all()
def test_blow_out_move_to(robot):
|
Formatting, disabled PEP8 for config, fixed value in test that depends on robot settings after changing the robot
|
Opentrons_opentrons
|
train
|
c8f6bec3f0b495b21d93d94bd0c689b8604f391f
|
diff --git a/jlib.container/src/main/java/org/jlib/container/sequence/SequenceUtility.java b/jlib.container/src/main/java/org/jlib/container/sequence/SequenceUtility.java
index <HASH>..<HASH> 100644
--- a/jlib.container/src/main/java/org/jlib/container/sequence/SequenceUtility.java
+++ b/jlib.container/src/main/java/org/jlib/container/sequence/SequenceUtility.java
@@ -1,6 +1,10 @@
package org.jlib.container.sequence;
+import java.util.Iterator;
+
import org.jlib.core.array.ArrayUtility;
+import org.jlib.core.traverser.BidirectionalTraversible;
+import org.jlib.core.traverser.Traverser;
/**
* Facade utility for {@link Sequence} creation and operations.
@@ -93,4 +97,25 @@ public final class SequenceUtility {
throws IllegalSequenceArgumentException {
append(sequence, ArrayUtility.iterable(items));
}
+
+ /**
+ * Returns a concatenated view of the specified
+ * {@link BidirectionalTraversible} instances. The behaviour of the returned
+ * {@link Sequence} and its {@link Traverser} or {@link Iterator} is
+ * unspecified if one of the {@link BidirectionalTraversible} instances is
+ * modified.
+ *
+ * @param <Item>
+ * type of the items provided by {@code traversibles}
+ *
+ * @param traversibles
+ * comma separated sequence of {@link BidirectionalTraversible}
+ * instances
+ *
+ * @return concatenated {@link Sequence} view
+ */
+ @SafeVarargs
+ public static <Item> Sequence<Item> concatenated(final BidirectionalTraversible<Item>... traversibles) {
+ return new ConcatenatedSequence<>(traversibles);
+ }
}
|
SequenceUtility: concatenated method added
|
jlib-framework_jlib-operator
|
train
|
6901fcd85fe28015435b7ba08c9aabdc49f1c0f8
|
diff --git a/lib/graph_matching/bipartite_graph.rb b/lib/graph_matching/bipartite_graph.rb
index <HASH>..<HASH> 100644
--- a/lib/graph_matching/bipartite_graph.rb
+++ b/lib/graph_matching/bipartite_graph.rb
@@ -11,6 +11,8 @@ module GraphMatching
# edge connects a vertex in U to one in V.
class BipartiteGraph < Graph
+ MAX_STAGES = 100
+
# `maximum_cardinality_matching` returns a `Set` of arrays,
# each representing an edge in the matching.
#
@@ -34,7 +36,111 @@ module GraphMatching
# path was found, the algorithm halts.
#
def maximum_cardinality_matching
- Set.new
+ m = Set.new # the matching
+ u, v = partition # complementary proper subsets of the vertexes
+ puts "partitions: #{u.inspect} #{v.inspect}"
+
+ # For each stage (until no augmenting path is found)
+ stage = 0
+ while stage <= MAX_STAGES do
+ puts "begin stage: #{m.inspect}"
+
+ # 0. Clear all labels and marks
+ label_t = Set.new
+ label_r = Set.new
+ mark_t = Set.new
+ mark_r = Set.new
+ predecessor = Hash.new
+ augmenting_path = nil
+
+ # 1. Label unmatched vertexes in U with label R
+ # These R-vertexes are candidates for the start of an augmenting path.
+ u.each { |ui| label_r.add(ui) if m.none? { |mi| mi.include?(ui) } }
+ puts "label r: #{label_r.inspect}"
+
+ # 2. While there are unmarked R-vertexes
+ unmarked_r = label_r
+ while augmenting_path.nil? && !unmarked_r.empty?
+ start = unmarked_r.first
+ mark_r.add(start)
+ puts "r-mark: #{start}"
+
+ # 3. Follow the unmatched edges (if any) to vertexes in V
+ each_adjacent(start) do |vi|
+ puts " adjacent: #{vi}"
+ if m.any? { |mi| mi.include?(vi) }
+ puts " not following matched edge"
+ else
+ puts " follow unmatched edge to: #{vi}"
+
+ # 4. Does the vertex in V have label T?
+ if label_t.include?(vi)
+ # A. If yes, do what?
+ raise " Found a T-vertex. What next?"
+ else
+ # B. If no, label with T and mark. Now, is it matched?
+ puts " t-label: #{vi}"
+ label_t.add(vi)
+ puts " t-mark: #{vi}"
+ mark_t.add(vi)
+ predecessor[vi] = start
+
+ vi_edges = adjacent_vertices(vi).reject { |vie| vie == start }
+ if vi_edges.empty?
+ puts " vi_edges is empty, so we found an augmenting path?"
+ augmenting_path = [vi, start]
+ puts " augmenting path: #{augmenting_path.inspect}"
+ break
+ else
+ vi_edges.each do |stop|
+ puts " adjacent: #{stop}"
+
+ # is it matched?
+ if m.any? { |mi| mi.include?(stop) }
+ # i. If so, follow that edge to a vertex in U
+ # a. Label the U-vertex with R
+ puts " r-label: #{stop}"
+ label_r.add(stop)
+ predecessor[stop] = vi
+
+ # b. Stop. Return to step 2
+ else
+ # ii. If not,
+ # a. Backtrack to construct an augmenting path
+ # a. Augment the matching and return to step 1
+ puts " woot. we found an augmenting path. backtracking .."
+ path = [stop]
+ while predecessor.has_key?(path.last)
+ path.push(predecessor[path.last])
+ end
+ puts " augmenting path: #{path.inspect}"
+ end
+ end
+ end
+ end
+ end
+ end
+
+ unmarked_r = label_r - mark_r
+ end
+
+ if augmenting_path.nil?
+ puts "Unable to find an augmenting path. We're done!"
+ break
+ else
+ new_matching = Set.new
+ augmenting_path_edges = Set.new
+ 0.upto(augmenting_path.length - 2).each do |j|
+ augmenting_path_edges.add([augmenting_path[j], augmenting_path[j + 1]])
+ end
+ puts "Augmenting the matching with #{(augmenting_path_edges - m).inspect}"
+ m.merge(augmenting_path_edges - m)
+ end
+
+ stage += 1
+ end
+
+ m
end
# `partition` either returns two disjoint proper subsets
diff --git a/spec/graph_matching/bipartite_graph_spec.rb b/spec/graph_matching/bipartite_graph_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/graph_matching/bipartite_graph_spec.rb
+++ b/spec/graph_matching/bipartite_graph_spec.rb
@@ -24,7 +24,13 @@ describe GraphMatching::BipartiteGraph do
end
context 'single edge' do
- it 'returns set with one edge'
+ it 'returns set with one edge' do
+ e = ['a', 'b']
+ g.add_edge(*e)
+ m = g.maximum_cardinality_matching
+ expect(m.size).to eq(1)
+ expect(m.first).to match_array(e)
+ end
end
end
|
First (disgusting) draft of `BipartiteGraph.maximum_cardinality_matching`
|
jaredbeck_graph_matching
|
train
|
e19c23620cc72e18ceab8803a57f7f2bab67f66e
|
diff --git a/src/main/java/com/redhat/contentspec/builder/ContentSpecBuilder.java b/src/main/java/com/redhat/contentspec/builder/ContentSpecBuilder.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/redhat/contentspec/builder/ContentSpecBuilder.java
+++ b/src/main/java/com/redhat/contentspec/builder/ContentSpecBuilder.java
@@ -35,7 +35,7 @@ public class ContentSpecBuilder implements ShutdownAbleApp {
public ContentSpecBuilder(final RESTManager restManager) {
this.restManager = restManager;
- this.rocbookdtd = restManager.getRESTClient().getJSONBlobConstant(BuilderConstants.ROCBOOK_DTD_BLOB_ID,
+ this.rocbookdtd = restManager.getRESTClient().getJSONBlobConstant(CommonConstants.ROCBOOK_DTD_BLOB_ID,
BuilderConstants.BLOB_CONSTANT_EXPAND);
}
diff --git a/src/main/java/com/redhat/contentspec/builder/constants/BuilderConstants.java b/src/main/java/com/redhat/contentspec/builder/constants/BuilderConstants.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/redhat/contentspec/builder/constants/BuilderConstants.java
+++ b/src/main/java/com/redhat/contentspec/builder/constants/BuilderConstants.java
@@ -186,10 +186,6 @@ public class BuilderConstants {
public static final List<String> VALID_PROGRAM_LISTING_LANGS = Arrays.asList("Java", "SQL", "C", "C++", "Bash", "Perl", "JavaScript",
"Python", "XML", "Ruby", "C#", "HTML", "CSS", "Javadoc", "Haskell", "Lua", "Makefile", "Pascal", "RPM Spec", "Diff");
/**
- * The BlobConstant ID for the Rocbook DTD
- */
- public static final Integer ROCBOOK_DTD_BLOB_ID = 9;
- /**
* The StringConstantsID that represents the icon.svg file
*/
public static final Integer ICON_SVG_ID = 6;
|
Minor fix to go with a Constant being moved to another package.
|
pressgang-ccms_PressGangCCMSBuilder
|
train
|
dbc1fb37d0ab04e62b197b19fb6a78abadea81eb
|
diff --git a/pkg/server/sandbox_run_unix.go b/pkg/server/sandbox_run_unix.go
index <HASH>..<HASH> 100644
--- a/pkg/server/sandbox_run_unix.go
+++ b/pkg/server/sandbox_run_unix.go
@@ -108,6 +108,13 @@ func (c *criService) sandboxContainerSpec(id string, config *runtime.PodSandboxC
Type: "bind",
Options: []string{"rbind", "ro"},
},
+ // Add resolv.conf for katacontainers to setup the DNS of pod VM properly.
+ {
+ Source: c.getResolvPath(id),
+ Destination: resolvConfPath,
+ Type: "bind",
+ Options: []string{"rbind", "ro"},
+ },
}))
selinuxOpt := securityContext.GetSelinuxOptions()
|
Provide resolvConf to sandbox container's mounts
As <URL>
|
containerd_containerd
|
train
|
bfbff180da1a9b6783f498e5110630ab462193ef
|
diff --git a/lib/Model.js b/lib/Model.js
index <HASH>..<HASH> 100644
--- a/lib/Model.js
+++ b/lib/Model.js
@@ -220,19 +220,6 @@ Model.prototype.invalidate = function invalidate() {
Model.prototype.deref = require("./deref");
/**
- * Synchronously returns a clone of the {@link Model} bound to a location within the {@link JSONGraph}. Unlike bind or bindSync, softBind never optimizes its path. Soft bind is ideal if you want to retrieve the bound path every time, rather than retrieve the optimized path once and then always retrieve paths from that object in the JSON Graph. For example, if you always wanted to retrieve the name from the first item in a list you could softBind to the path "list[0]".
- * @param {Path} path - The path prefix to retrieve every time an operation is executed on a Model.
- * @return {Model}
- */
-Model.prototype.softDeref = function softDeref(path) {
- path = pathSyntax.fromPath(path);
- if(Array.isArray(path) === false) {
- throw new Error("Model#softDeref must be called with an Array path.");
- }
- return this.clone({ _path: path });
-};
-
-/**
* Get data for a single {@link Path}
* @param {Path} path - The path to retrieve
* @return {Observable.<*>} - The value for the path
|
Removing softDeref/bind
|
Netflix_falcor
|
train
|
cd35dc67d8b36252f16d27d559dc1750f78e655b
|
diff --git a/hazelcast/src/main/java/com/hazelcast/map/DefaultRecordStore.java b/hazelcast/src/main/java/com/hazelcast/map/DefaultRecordStore.java
index <HASH>..<HASH> 100644
--- a/hazelcast/src/main/java/com/hazelcast/map/DefaultRecordStore.java
+++ b/hazelcast/src/main/java/com/hazelcast/map/DefaultRecordStore.java
@@ -101,9 +101,11 @@ public class DefaultRecordStore extends AbstractEvictableRecordStore implements
@Override
public void putRecord(Data key, Record record) {
+ final long now = getNow();
final Record existingRecord = records.put(key, record);
updateSizeEstimator(-calculateRecordHeapCost(existingRecord));
updateSizeEstimator(calculateRecordHeapCost(record));
+ evictEntries(now);
}
@Override
@@ -510,13 +512,11 @@ public class DefaultRecordStore extends AbstractEvictableRecordStore implements
public Object remove(Data key) {
checkIfLoaded();
final long now = getNow();
- evictEntries(now);
Record record = records.get(key);
Object oldValue;
if (record == null) {
oldValue = mapDataStore.load(key);
-
if (oldValue != null) {
removeIndex(key);
mapDataStore.remove(key, now);
@@ -524,20 +524,7 @@ public class DefaultRecordStore extends AbstractEvictableRecordStore implements
} else {
oldValue = removeRecord(key, record, now);
}
- return oldValue;
- }
-
- public Object removeRecord(Data key, Record record, long now) {
- Object oldValue = record.getValue();
- oldValue = mapServiceContext.interceptRemove(name, oldValue);
- if (oldValue != null) {
- removeIndex(key);
- mapDataStore.remove(key, now);
- onStore(record);
- }
- // reduce size
- updateSizeEstimator(-calculateRecordHeapCost(record));
- deleteRecord(key);
+ evictEntries(now);
return oldValue;
}
@@ -584,6 +571,7 @@ public class DefaultRecordStore extends AbstractEvictableRecordStore implements
} else {
return removeRecord(key, record, now) != null;
}
+ evictEntries(now);
return false;
}
@@ -591,12 +579,12 @@ public class DefaultRecordStore extends AbstractEvictableRecordStore implements
public Object get(Data key) {
checkIfLoaded();
long now = getNow();
- final Object value = get0(key, now);
+ final Object value = getInternal(key, now);
postReadCleanUp(now);
return value;
}
- private Object get0(Data key, long now) {
+ private Object getInternal(Data key, long now) {
Record record = records.get(key);
record = nullIfExpired(record);
Object value;
@@ -1000,4 +988,18 @@ public class DefaultRecordStore extends AbstractEvictableRecordStore implements
return mapDataStore;
}
+ private Object removeRecord(Data key, Record record, long now) {
+ Object oldValue = record.getValue();
+ oldValue = mapServiceContext.interceptRemove(name, oldValue);
+ if (oldValue != null) {
+ removeIndex(key);
+ mapDataStore.remove(key, now);
+ onStore(record);
+ }
+ // reduce size
+ updateSizeEstimator(-calculateRecordHeapCost(record));
+ deleteRecord(key);
+ return oldValue;
+ }
+
}
|
trigger eviction upon putRecord when replication in progress
|
hazelcast_hazelcast
|
train
|
29dfc690bdac0491fc22228de3880f4612fcb567
|
diff --git a/aws-sdk-resources/lib/aws-sdk-resources.rb b/aws-sdk-resources/lib/aws-sdk-resources.rb
index <HASH>..<HASH> 100644
--- a/aws-sdk-resources/lib/aws-sdk-resources.rb
+++ b/aws-sdk-resources/lib/aws-sdk-resources.rb
@@ -64,11 +64,11 @@ module Aws
'stop' => 'batch_stop',
'terminate' => 'batch_terminate!',
'unmonitor' => 'batch_unmonitor',
- }.each do |deprecated_name, name|
+ }.each do |deprecated_name, correct_name|
Resources::Operations::DeprecatedOperation.define({
resource_class: EC2::Instance,
deprecated_name: deprecated_name,
- name: name,
+ name: correct_name,
})
end
Resources::Operations::DeprecatedOperation.define({
|
Fix Aws::Resources warning
Previously this loop was shadowing an outer variable, resulting in a ruby warning.
```
/Users/kdeisz/.rbenv/versions/<I>/lib/ruby/gems/<I>/gems/aws-sdk-resources-<I>/lib/aws-sdk-resources.rb:<I>: warning: shadowing outer local variable - name
```
|
aws_aws-sdk-ruby
|
train
|
708720c49c1597a75445a748c98850a5aa42065c
|
diff --git a/src/MigratorConsole.php b/src/MigratorConsole.php
index <HASH>..<HASH> 100644
--- a/src/MigratorConsole.php
+++ b/src/MigratorConsole.php
@@ -28,7 +28,7 @@ class MigratorConsole extends \atk4\ui\Console
foreach ($models as $model) {
if (!is_object($model)) {
- $model = $this->factory($model);
+ $model = $this->factory((array) $model);
$persistence->add($model);
}
|
fix seed (#<I>)
|
atk4_schema
|
train
|
c31d0804af69895f7c10afb71865e68b84eb8b27
|
diff --git a/tests/Carbon/TestingAidsTest.php b/tests/Carbon/TestingAidsTest.php
index <HASH>..<HASH> 100644
--- a/tests/Carbon/TestingAidsTest.php
+++ b/tests/Carbon/TestingAidsTest.php
@@ -357,6 +357,7 @@ class TestingAidsTest extends AbstractTestCase
Carbon::setTestNowAndTimezone(new class ('2000-01-01 00:00 UTC') extends Carbon {
public function modify($modify)
{
+ /** @phpstan-ignore-next-line */
return $this->toDateTimeImmutable()->modify($modify);
}
});
|
Ignore phpstan check for test broken on purpose
|
briannesbitt_Carbon
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.