hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
b1a876353322a258bd95d101bb5500e4b04a8754
|
diff --git a/packages/ember-glimmer/tests/integration/components/target-action-test.js b/packages/ember-glimmer/tests/integration/components/target-action-test.js
index <HASH>..<HASH> 100644
--- a/packages/ember-glimmer/tests/integration/components/target-action-test.js
+++ b/packages/ember-glimmer/tests/integration/components/target-action-test.js
@@ -600,13 +600,18 @@ moduleFor('Components test: send', class extends RenderingTest {
}
['@test actions cannot be provided at create time'](assert) {
- expectAssertion(() => Component.create({
- actions: {
- foo() {
- assert.ok(true, 'foo');
+ this.registerComponent('foo-bar', Component.extend());
+ let ComponentFactory = this.owner.factoryFor('component:foo-bar');
+
+ expectAssertion(() => {
+ ComponentFactory.create({
+ actions: {
+ foo() {
+ assert.ok(true, 'foo');
+ }
}
- }
- }));
+ });
+ }, /`actions` must be provided at extend time, not at create time/);
// but should be OK on an object that doesn't mix in Ember.ActionHandler
EmberObject.create({
actions: ['foo']
|
Fixup test to ensure correct assertion is thrown.
This test previously allowed any old assertion to satisfy it, but now
will properly validate that the one we expected was what was thrown.
|
emberjs_ember.js
|
train
|
202f623165c773f996df9fbca21f1b64fd295874
|
diff --git a/code/serializers/EmberData/RESTfulAPI_EmberDataSerializer.php b/code/serializers/EmberData/RESTfulAPI_EmberDataSerializer.php
index <HASH>..<HASH> 100644
--- a/code/serializers/EmberData/RESTfulAPI_EmberDataSerializer.php
+++ b/code/serializers/EmberData/RESTfulAPI_EmberDataSerializer.php
@@ -235,7 +235,7 @@ class RESTfulAPI_EmberDataSerializer extends RESTfulAPI_BasicSerializer
$newData = array($newData);
}
- $data[$relationName] = $newData;
+ $data[$relationClass] = $newData;
}
}
else if ( $dataSource instanceof DataList )
@@ -248,9 +248,9 @@ class RESTfulAPI_EmberDataSerializer extends RESTfulAPI_BasicSerializer
}
// remove duplicates
- foreach ($data as $relationName => $relationData)
+ foreach ($data as $relationClass => $relationData)
{
- $data[$relationName] = array_unique($relationData, SORT_REGULAR);
+ $data[$relationClass] = array_unique($relationData, SORT_REGULAR);
}
}
@@ -274,13 +274,19 @@ class RESTfulAPI_EmberDataSerializer extends RESTfulAPI_BasicSerializer
$sideloadData = $this->getSideloadData($dataSource);
// attached those to the root
- foreach ($sideloadData as $relationName => $relationData)
+ foreach ($sideloadData as $relationClass => $relationData)
{
- $rootRelationName = $this->formatName( $relationName );
- $rootRelationName = Inflector::pluralize( $rootRelationName );
+ $rootRelationClass = $this->formatName( $relationClass );
+
+ // pluralize only set of records
+ $allArrays = array_filter($relationData,'is_array');
+ if ( count($allArrays) == count($relationData) )
+ {
+ $rootRelationClass = Inflector::pluralize( $rootRelationClass );
+ }
// attach to root
- $root->{$rootRelationName} = $relationData;
+ $root->{$rootRelationClass} = $relationData;
}
return $root;
|
FIX sideloaded records inflection + class name as root
Only set of multiple records have their root pluralized and the root key
is now the class name not the relation name
|
colymba_silverstripe-restfulapi
|
train
|
2aff22e0d0fa2b694450c1ad8a725958061c877d
|
diff --git a/__tests__/components/Timestamp-test.js b/__tests__/components/Timestamp-test.js
index <HASH>..<HASH> 100644
--- a/__tests__/components/Timestamp-test.js
+++ b/__tests__/components/Timestamp-test.js
@@ -8,7 +8,15 @@ import Timestamp from '../../src/js/components/Timestamp';
describe('Timestamp', () => {
it('has correct default options', () => {
const component = renderer.create(
- <Timestamp value='4/7/2015 10:00 am' />
+ <Timestamp value='4/7/2015 10:00:01 am' />
+ );
+ let tree = component.toJSON();
+ expect(tree).toMatchSnapshot();
+ });
+
+ it('displays second', () => {
+ const component = renderer.create(
+ <Timestamp value='4/7/2015 10:00:01 am' seconds={true}/>
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
diff --git a/__tests__/components/__snapshots__/Timestamp-test.js.snap b/__tests__/components/__snapshots__/Timestamp-test.js.snap
index <HASH>..<HASH> 100644
--- a/__tests__/components/__snapshots__/Timestamp-test.js.snap
+++ b/__tests__/components/__snapshots__/Timestamp-test.js.snap
@@ -1,3 +1,18 @@
+exports[`Timestamp displays second 1`] = `
+<span
+ className="grommetux-timestamp">
+ <span
+ className="grommetux-timestamp__date">
+ Apr 7, 2015
+ </span>
+
+ <span
+ className="grommetux-timestamp__time">
+ 10:00:01 AM
+ </span>
+</span>
+`;
+
exports[`Timestamp has correct default options 1`] = `
<span
className="grommetux-timestamp">
diff --git a/src/js/components/Timestamp.js b/src/js/components/Timestamp.js
index <HASH>..<HASH> 100644
--- a/src/js/components/Timestamp.js
+++ b/src/js/components/Timestamp.js
@@ -46,7 +46,10 @@ export default class Timestamp extends Component {
let time;
if (_showField('time', props.fields)) {
- const timeOptions = { hour: '2-digit', minute: '2-digit' };
+ const timeOptions = (props.seconds)
+ ? { hour: '2-digit', minute: '2-digit', second: '2-digit' }
+ : { hour: '2-digit', minute: '2-digit' };
+
time = value.toLocaleTimeString(locale, timeOptions);
}
@@ -90,6 +93,7 @@ Timestamp.propTypes = {
PropTypes.arrayOf(FIELD_TYPES),
FIELD_TYPES
]),
+ seconds: PropTypes.bool,
value: PropTypes.oneOfType([
PropTypes.string, // ISO-8601 string
PropTypes.object // Date object
|
Added seconds to Timestamp.
|
grommet_grommet
|
train
|
71c940993b25620944e0dcb31f8a7d43649d0210
|
diff --git a/package.php b/package.php
index <HASH>..<HASH> 100644
--- a/package.php
+++ b/package.php
@@ -4,7 +4,7 @@
require_once 'PEAR/PackageFileManager2.php';
-$version = '1.3.48';
+$version = '1.3.49';
$notes = <<<EOT
* Fix bug in SwatDBRecordsetWrapper::loadAllSubRecordsets()
* add optional extended-check-all to checkall widget
|
prepare for release of <I>
svn commit r<I>
|
silverorange_swat
|
train
|
c96c6ece503541cf34282826d7ca709a419ef4d3
|
diff --git a/webapps/webapp/src/test/js/e2e/cockpit/pages/table.js b/webapps/webapp/src/test/js/e2e/cockpit/pages/table.js
index <HASH>..<HASH> 100644
--- a/webapps/webapp/src/test/js/e2e/cockpit/pages/table.js
+++ b/webapps/webapp/src/test/js/e2e/cockpit/pages/table.js
@@ -9,7 +9,7 @@ module.exports = Table.extend({
},
selectTab: function() {
- this.tableTabs().get(this.tabIndex).click();
+ return this.tableTabs().get(this.tabIndex).click();
},
tabSelectionStatus: function() {
diff --git a/webapps/webapp/src/test/js/e2e/cockpit/specs/process-definition-spec.js b/webapps/webapp/src/test/js/e2e/cockpit/specs/process-definition-spec.js
index <HASH>..<HASH> 100644
--- a/webapps/webapp/src/test/js/e2e/cockpit/specs/process-definition-spec.js
+++ b/webapps/webapp/src/test/js/e2e/cockpit/specs/process-definition-spec.js
@@ -22,24 +22,46 @@ describe('Cockpit Process Definition Spec', function() {
});
});
+
it('should display process diagram', function() {
expect(processPage.diagram.diagramElement().isDisplayed()).to.eventually.be.true;
});
+
it('should display the number of running process instances', function() {
expect(processPage.diagram.instancesBadgeFor('UserTask_1').getText()).to.eventually.eql('2');
});
- it('should process clicks in diagram', function() {
+
+ it('should select activity', function() {
+
+ // when
processPage.diagram.selectActivity('UserTask_1');
+ // then
expect(processPage.diagram.isActivitySelected('UserTask_1')).to.eventually.be.true;
expect(processPage.filter.activityFilter('User Task 1').isPresent()).to.eventually.be.true;
});
+
+ it('should keep selection after page refresh', function() {
+
+ // when
+ browser.getCurrentUrl().then(function (url) {
+ browser.get(url);
+ });
+
+ // then
+ expect(processPage.diagram.isActivitySelected('UserTask_1')).to.eventually.be.true;
+ });
+
+
it('should process clicks in Filter table', function() {
+
+ // when
processPage.filter.removeFilterButton('User Task 1').click();
+ // then
expect(processPage.diagram.isActivitySelected('UserTask_1')).to.eventually.be.false;
});
diff --git a/webapps/webapp/src/test/js/e2e/cockpit/specs/process-instance-spec.js b/webapps/webapp/src/test/js/e2e/cockpit/specs/process-instance-spec.js
index <HASH>..<HASH> 100644
--- a/webapps/webapp/src/test/js/e2e/cockpit/specs/process-instance-spec.js
+++ b/webapps/webapp/src/test/js/e2e/cockpit/specs/process-instance-spec.js
@@ -23,30 +23,58 @@ describe('Cockpit Process Instance Spec', function() {
});
});
+
it('should display process diagram', function() {
expect(instancePage.diagram.diagramElement().isDisplayed()).to.eventually.be.true;
});
+
it('should display the number of concurrent activities', function() {
expect(instancePage.diagram.instancesBadgeFor('UserTask_1').getText()).to.eventually.eql('1');
});
+
it('should process clicks in diagram', function() {
+
+ // given
+ instancePage.instanceTree.selectInstance('User Task 1');
+ expect(instancePage.diagram.isActivitySelected('UserTask_1')).to.eventually.be.true;
+
+ // when
instancePage.diagram.deselectAll();
+ // then
expect(instancePage.diagram.isActivitySelected('UserTask_1')).to.eventually.be.false;
expect(instancePage.instanceTree.isInstanceSelected('User Task 1')).to.eventually.be.false;
});
- it('should deselect activities in diagram', function() {
+
+ it('should keep selection after page refresh', function() {
+
+ // given
instancePage.instanceTree.selectInstance('User Task 1');
+ expect(instancePage.diagram.isActivitySelected('UserTask_1')).to.eventually.be.true;
+
+ // when
+ browser.getCurrentUrl().then(function (url) {
+ browser.get(url);
+ });
+ // then
expect(instancePage.diagram.isActivitySelected('UserTask_1')).to.eventually.be.true;
});
+
it('should reflect the tree view selection in diagram', function() {
+
+ // given
+ instancePage.instanceTree.selectInstance('User Task 1');
+ expect(instancePage.diagram.isActivitySelected('UserTask_1')).to.eventually.be.true;
+
+ // when
instancePage.instanceTree.deselectInstance('User Task 1');
+ // then
expect(instancePage.diagram.isActivitySelected('UserTask_1')).to.eventually.be.false;
});
|
test(cockpit e2e): test activity selection after refresh
related to CAM-<I>
|
camunda_camunda-bpm-platform
|
train
|
ad7d456ae136ccbdb4a674cb3427bbf4c0082542
|
diff --git a/plugins/context2d.js b/plugins/context2d.js
index <HASH>..<HASH> 100644
--- a/plugins/context2d.js
+++ b/plugins/context2d.js
@@ -362,8 +362,8 @@
}
if (scale === 1) {
this.pdf.text(text, x, this._getBaseline(y), {
- stroke: true
- }, degs);
+ stroke: true
+ }, degs);
}
else {
var oldSize = this.pdf.internal.getFontSize();
@@ -1143,16 +1143,16 @@
moves[moves.length - 1].deltas.push(delta);
break;
case 'arc':
- //TODO this was hack to avoid out-of-bounds issue
+ //TODO this was hack to avoid out-of-bounds issue when drawing circle
// No move-to before drawing the arc
- if (moves.length == 0) {
- moves.push({start: {x: 0, y: 0}, deltas: [], abs: []});
+ if (moves.length === 0) {
+ moves.push({deltas: [], abs: []});
}
moves[moves.length - 1].arc = true;
moves[moves.length - 1].abs.push(pt);
break;
case 'close':
- //moves[moves.length - 1].deltas.push('close');
+ moves.push({close: true});
break;
}
}
@@ -1168,7 +1168,14 @@
style = null;
}
- if (moves[i].arc) {
+ if (moves[i].close) {
+ this.pdf.internal.out('h');
+ this.pdf.internal.out('f');
+ }
+ else if (moves[i].arc) {
+ if (moves[i].start) {
+ this.internal.move2(this, moves[i].start.x, moves[i].start.y);
+ }
var arcs = moves[i].abs;
for (var ii = 0; ii < arcs.length; ii++) {
var arc = arcs[ii];
@@ -1176,32 +1183,24 @@
if (typeof arc.startAngle !== 'undefined') {
var start = arc.startAngle * 360 / (2 * Math.PI);
var end = arc.endAngle * 360 / (2 * Math.PI);
- // Add the current position (last move to)
- //var x = moves[i].start.x + arc.x;
- //var y = moves[i].start.y + arc.y;
var x = arc.x;
var y = arc.y;
- if (ii == 0) {
+ if (ii === 0) {
this.internal.move2(this, x, y);
}
this.internal.arc2(this, x, y, arc.radius, start, end, arc.anticlockwise, null, isClip);
+ if (ii === arcs.length - 1) {
+ // The original arc move did not occur because of the algorithm
+ if (moves[i].start) {
+ var x = moves[i].start.x;
+ var y = moves[i].start.y;
+ this.internal.line2(c2d, x, y);
+ }
+ }
} else {
this.internal.line2(c2d, arc.x, arc.y);
}
}
-
- if (this.pdf.hotfix && this.pdf.hotfix.fill_close) {
- // do nothing
- }
- else {
- // extra move bug causing close to resolve to wrong point
- var x = moves[i].start.x;
- var y = moves[i].start.y;
- this.internal.line2(c2d, x, y);
- }
-
- this.pdf.internal.out('h');
- this.pdf.internal.out('f');
}
else {
var x = moves[i].start.x;
@@ -1422,7 +1421,7 @@
for (var i = 0; i < curves.length; i++) {
var curve = curves[i];
- if (includeMove && i == 0) {
+ if (includeMove && i === 0) {
this.pdf.internal.out([
f2((curve.x1 + xc) * k), f2((pageHeight - (curve.y1 + yc)) * k), 'm', f2((curve.x2 + xc) * k), f2((pageHeight - (curve.y2 + yc)) * k), f2((curve.x3 + xc) * k), f2((pageHeight - (curve.y3 + yc)) * k), f2((curve.x4 + xc) * k), f2((pageHeight - (curve.y4 + yc)) * k), 'c'
].join(' '));
@@ -1552,7 +1551,7 @@
if (startAngleN < 0) {
startAngleN = twoPI + startAngleN;
}
-
+
while (startAngle > endAngle) {
startAngle = startAngle - twoPI;
}
|
Fix issues with IE crashing and stray lines (#<I>)
|
MrRio_jsPDF
|
train
|
0fc0d4df375f271c53d1b32dd701b210e720dc5c
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,7 @@
+* Fail gracefully when honeybadger.yml is empty or invalid.
+
+ *Joshua Wood*
+
* Handle bad encodings in exception payloads.
*Joshua Wood*
diff --git a/lib/honeybadger/config/yaml.rb b/lib/honeybadger/config/yaml.rb
index <HASH>..<HASH> 100644
--- a/lib/honeybadger/config/yaml.rb
+++ b/lib/honeybadger/config/yaml.rb
@@ -15,7 +15,7 @@ module Honeybadger
elsif !@path.readable?
raise ConfigError, "The configuration file #{@path} is not readable."
else
- yaml = YAML.load(ERB.new(@path.read).result)
+ yaml = load_yaml
yaml.merge!(yaml[env]) if yaml[env].kind_of?(Hash)
update(dotify_keys(yaml))
end
@@ -23,6 +23,18 @@ module Honeybadger
private
+ def load_yaml
+ yaml = YAML.load(ERB.new(@path.read).result)
+ case yaml
+ when Hash
+ yaml
+ when NilClass, FalseClass
+ {}
+ else
+ raise ConfigError, "The configuration file #{@path} is invalid."
+ end
+ end
+
def dotify_keys(hash, key_prefix = nil)
{}.tap do |new_hash|
hash.each_pair do |k,v|
diff --git a/spec/unit/honeybadger/config/yaml_spec.rb b/spec/unit/honeybadger/config/yaml_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/honeybadger/config/yaml_spec.rb
+++ b/spec/unit/honeybadger/config/yaml_spec.rb
@@ -77,6 +77,30 @@ logging:
end
end
+ context "when the YAML content is" do
+ before { allow(path).to receive(:read).and_return(yaml) }
+
+ context "nil" do
+ let(:yaml) { '---' }
+ it { should eq({}) }
+ end
+
+ context "empty" do
+ let(:yaml) { '' }
+ it { should eq({}) }
+ end
+
+ context "invalid" do
+ let(:yaml) { 'foo' }
+ specify { expect { subject }.to raise_error(Honeybadger::Config::ConfigError) }
+ end
+
+ context "valid" do
+ let(:yaml) { 'foo: bar' }
+ it { should eq({ foo: 'bar' }) }
+ end
+ end
+
context "when an unknown error occurs" do
before do
allow(YAML).to receive(:load).and_raise(RuntimeError)
|
Raise a ConfigError when the contents of honeybadger.yml are invalid.
|
honeybadger-io_honeybadger-ruby
|
train
|
03f1b5feb10c226d5a49091cffd658e7ea2dd257
|
diff --git a/includes/class-pb-book.php b/includes/class-pb-book.php
index <HASH>..<HASH> 100644
--- a/includes/class-pb-book.php
+++ b/includes/class-pb-book.php
@@ -363,7 +363,7 @@ class Book {
* @param $id
*
*/
- static function getSubsections( $id ) {
+ static function getSubsections( $id, $prefix = false ) {
$parent = get_post( $id );
$output = array();
$s = 1;
diff --git a/includes/modules/export/xhtml/class-pb-xhtml11.php b/includes/modules/export/xhtml/class-pb-xhtml11.php
index <HASH>..<HASH> 100644
--- a/includes/modules/export/xhtml/class-pb-xhtml11.php
+++ b/includes/modules/export/xhtml/class-pb-xhtml11.php
@@ -729,7 +729,7 @@ class Xhtml11 extends Export {
echo '</a>';
if ( \PressBooks\Export\Export::shouldParseSections() == true ) {
- $sections = \PressBooks\Book::getSubsections( $chapter['ID'] );
+ /* $sections = \PressBooks\Book::getSubsections( $chapter['ID'] );
if ( $sections ) {
echo '<ul class="sections">';
foreach ( $sections as $section ) {
@@ -737,7 +737,7 @@ class Xhtml11 extends Export {
++$s;
}
echo '</ul>';
- }
+ } */
}
echo '</li>';
@@ -787,7 +787,7 @@ class Xhtml11 extends Export {
echo '</a>';
if ( \PressBooks\Export\Export::shouldParseSections() == true ) {
- $sections = \PressBooks\Book::getSubsections( $val['ID'] );
+ /* $sections = \PressBooks\Book::getSubsections( $val['ID'], true );
if ( $sections ) {
echo '<ul class="sections">';
foreach ( $sections as $section ) {
@@ -795,7 +795,7 @@ class Xhtml11 extends Export {
++$s;
}
echo '</ul>';
- }
+ } */
}
echo '</li>';
@@ -842,10 +842,11 @@ class Xhtml11 extends Export {
$subtitle = trim( get_post_meta( $id, 'pb_subtitle', true ) );
$author = trim( get_post_meta( $id, 'pb_section_author', true ) );
- $sections = \PressBooks\Book::getSubsections( $id );
-
- if ( $sections ) {
- $content = \PressBooks\Book::tagSubsections( $content, 'front-matter' );
+ if ( \PressBooks\Export\Export::shouldParseSections() == true ) {
+ $sections = \PressBooks\Book::getSubsections( $id );
+ if ( $sections ) {
+ $content = \PressBooks\Book::tagSubsections( $content, 'front-matter' );
+ }
}
if ( $author ) {
@@ -967,10 +968,11 @@ class Xhtml11 extends Export {
$subtitle = trim( get_post_meta( $id, 'pb_subtitle', true ) );
$author = trim( get_post_meta( $id, 'pb_section_author', true ) );
- $sections = \PressBooks\Book::getSubsections( $id );
-
- if ( $sections ) {
- $content = \PressBooks\Book::tagSubsections( $content );
+ if ( \PressBooks\Export\Export::shouldParseSections() == true ) {
+ $sections = \PressBooks\Book::getSubsections( $id );
+ if ( $sections ) {
+ $content = \PressBooks\Book::tagSubsections( $content, );
+ }
}
if ( $author ) {
@@ -1060,10 +1062,11 @@ class Xhtml11 extends Export {
$subtitle = trim( get_post_meta( $id, 'pb_subtitle', true ) );
$author = trim( get_post_meta( $id, 'pb_section_author', true ) );
- $sections = \PressBooks\Book::getSubsections( $id );
-
- if ( $sections ) {
- $content = \PressBooks\Book::tagSubsections( $content, 'back-matter' );
+ if ( \PressBooks\Export\Export::shouldParseSections() == true ) {
+ $sections = \PressBooks\Book::getSubsections( $id );
+ if ( $sections ) {
+ $content = \PressBooks\Book::tagSubsections( $content, 'back-matter' );
+ }
}
if ( $author ) {
|
Debugging multi-level TOC in XHMTL.
|
pressbooks_pressbooks
|
train
|
c3afe691f1ec7728a7ecbf5e2e7bde1dff4533a0
|
diff --git a/test/unit/map-each.js b/test/unit/map-each.js
index <HASH>..<HASH> 100644
--- a/test/unit/map-each.js
+++ b/test/unit/map-each.js
@@ -0,0 +1,41 @@
+'use strict';
+
+var sinon = require('sinon');
+var expect = require('chai').expect;
+
+describe('series', function() {
+
+ var MapEach;
+ var nextTickStub;
+
+ before(function () {
+ MapEach = require('../../lib/map-each.js');
+ nextTickStub = sinon.stub(process, 'nextTick');
+ });
+
+ beforeEach(function () {
+ nextTickStub.reset();
+ });
+
+ after(function () {
+ process.nextTick.restore();
+ });
+
+ describe('map-each - entry-point', function() {
+
+ });
+
+ describe('map-eaech - callback', function() {
+ describe('when invoked with an error', function() {
+
+ });
+
+ describe('when invoked with the final array element', function() {
+
+ });
+
+ describe('when invoked with the n-1th array element', function() {
+
+ });
+ });
+});
\ No newline at end of file
|
map-each detailed unit test scaffolding
|
GannettDigital_palinode
|
train
|
f3e3ad472b190f0144b36e95da1d54f2bfd96640
|
diff --git a/lib/parallel.js b/lib/parallel.js
index <HASH>..<HASH> 100644
--- a/lib/parallel.js
+++ b/lib/parallel.js
@@ -15,13 +15,12 @@ class AigleParallel extends AigleProxy {
constructor(collection) {
super();
this._promise = new Aigle(INTERNAL);
- this._result = {};
this._rest = undefined;
this._coll = undefined;
this._keys = undefined;
- this._iterate = undefined;
- this._callResolve = undefined;
+ this._result = undefined;
if (collection === PENDING) {
+ this._result = this._callResolve;
this._callResolve = execute;
} else {
set.call(this, collection);
@@ -39,6 +38,13 @@ class AigleParallel extends AigleProxy {
return this._promise;
}
+ _callResolve(value, index) {
+ this._result[index] = value;
+ if (--this._rest === 0) {
+ this._promise._resolve(this._result);
+ }
+ }
+
_callReject(reason) {
this._promise._reject(reason);
}
@@ -47,8 +53,8 @@ class AigleParallel extends AigleProxy {
module.exports = { parallel, AigleParallel };
function execute(collection) {
+ this._callResolve = this._result;
set.call(this, collection);
- this._callResolve = callResolve;
this._execute();
}
@@ -68,18 +74,11 @@ function set(collection) {
this._iterate = promiseObjectEach;
} else {
this._rest = 0;
+ this._result = {};
}
- this._callResolve = callResolve;
return this;
}
-function callResolve(value, index) {
- this._result[index] = value;
- if (--this._rest === 0) {
- this._promise._resolve(this._result);
- }
-}
-
/**
* @param {Array|Object} collection - it should be an array/object of Promise instances
* @example
diff --git a/lib/race.js b/lib/race.js
index <HASH>..<HASH> 100644
--- a/lib/race.js
+++ b/lib/race.js
@@ -1,56 +1,16 @@
'use strict';
-const { AigleProxy } = require('aigle-core');
-const { Aigle } = require('./aigle');
-const { INTERNAL, promiseArrayEach, promiseObjectEach } = require('./internal/util');
+const { AigleParallel } = require('./parallel');
-class RaceArray extends AigleProxy {
+class AigleRace extends AigleParallel {
- constructor(array) {
- super();
- const size = array.length;
- this._promise = new Aigle(INTERNAL);
- this._rest = size;
- this._coll = array;
- if (size === 0) {
- this._promise._resolve();
- } else {
- promiseArrayEach(this);
- }
+ constructor(collection) {
+ super(collection);
+ this._result = undefined;
}
_callResolve(value) {
- this._promise._resolved === 0 && this._promise._resolve(value);
- }
-
- _callReject(reason) {
- this._promise._resolved === 0 && this._promise._reject(reason);
- }
-}
-
-class RaceObject extends AigleProxy {
-
- constructor(object) {
- super();
- const keys = Object.keys(object);
- const size = keys.length;
- this._promise = new Aigle(INTERNAL);
- this._rest = size;
- this._keys = keys;
- this._coll = object;
- if (size === 0) {
- this._promise._resolve();
- } else {
- promiseObjectEach(this);
- }
- }
-
- _callResolve(value) {
- this._promise._resolved === 0 && this._promise._resolve(value);
- }
-
- _callReject(reason) {
- this._promise._resolved === 0 && this._promise._reject(reason);
+ this._promise._resolve(value);
}
}
@@ -75,11 +35,5 @@ module.exports = race;
* .then(value => console.log(value)); // 3
*/
function race(collection) {
- if (Array.isArray(collection)) {
- return new RaceArray(collection)._promise;
- }
- if (collection && typeof collection === 'object') {
- return new RaceObject(collection)._promise;
- }
- return Aigle.resolve();
+ return new AigleRace(collection)._execute();
}
diff --git a/test/lib/test.race.js b/test/lib/test.race.js
index <HASH>..<HASH> 100644
--- a/test/lib/test.race.js
+++ b/test/lib/test.race.js
@@ -75,6 +75,7 @@ parallel('race', () => {
assert.deepEqual(order, ['test3']);
});
});
+
it('should return undefined if tasks is an empty array', () => {
return Aigle.race([])
|
refactor(race): refactor race
|
suguru03_aigle
|
train
|
901895e47768c43fb8e7f59c61a657b280f7f309
|
diff --git a/plugins/cache/redis_php/redis_php.cache.php b/plugins/cache/redis_php/redis_php.cache.php
index <HASH>..<HASH> 100644
--- a/plugins/cache/redis_php/redis_php.cache.php
+++ b/plugins/cache/redis_php/redis_php.cache.php
@@ -148,8 +148,14 @@ class redis_phpCacheDriver implements jICacheDriver {
* @param int $ttl data time expiration
* @return boolean false if failure
*/
- public function set($key, $value, $ttl = 0) {
- if (is_resource($value)) {
+ public function set($key, $value, $ttl = 0)
+ {
+ if (function_exists('\\Jelix\\Utilities\\is_resource')) {
+ if (\Jelix\Utilities\is_resource($value)) {
+ return false;
+ }
+ }
+ else if (is_resource($value)) {
return false;
}
$used_key = $this->getUsedKey($key);
diff --git a/plugins/kvdb/redis_php/redis_php.kvdriver.php b/plugins/kvdb/redis_php/redis_php.kvdriver.php
index <HASH>..<HASH> 100644
--- a/plugins/kvdb/redis_php/redis_php.kvdriver.php
+++ b/plugins/kvdb/redis_php/redis_php.kvdriver.php
@@ -28,6 +28,14 @@ class redis_phpKVDriver extends jKVDriver implements jIKVSet, jIKVttl {
*/
protected $key_prefix_flush_method = 'direct';
+ protected function isResource($value) {
+ if (function_exists('\\Jelix\\Utilities\\is_resource')) {
+ return \Jelix\Utilities\is_resource($value);
+ }
+ return is_resource($value);
+ }
+
+
/**
* Connects to the redis server
* @return \PhpRedis\Redis object
@@ -109,14 +117,14 @@ class redis_phpKVDriver extends jKVDriver implements jIKVSet, jIKVttl {
}
public function set($key, $value) {
- if (is_resource($value))
+ if ($this->isResource($value))
return false;
$res = $this->_connection->set($this->getUsedKey($key), $this->esc($value));
return ($res === 'OK');
}
public function insert($key, $value) {
- if (is_resource($value))
+ if ($this->isResource($value))
return false;
$key = $this->getUsedKey($key);
if ($this->_connection->exists($key) == 1)
@@ -126,7 +134,7 @@ class redis_phpKVDriver extends jKVDriver implements jIKVSet, jIKVttl {
}
public function replace($key, $value) {
- if (is_resource($value))
+ if ($this->isResource($value))
return false;
$key = $this->getUsedKey($key);
if ($this->_connection->exists($key) == 0)
@@ -159,7 +167,7 @@ class redis_phpKVDriver extends jKVDriver implements jIKVSet, jIKVttl {
}
public function append($key, $value) {
- if (is_resource($value))
+ if ($this->isResource($value))
return false;
$key = $this->getUsedKey($key);
$val = $this->_connection->get($key);
@@ -173,7 +181,7 @@ class redis_phpKVDriver extends jKVDriver implements jIKVSet, jIKVttl {
}
public function prepend($key, $value) {
- if (is_resource($value))
+ if ($this->isResource($value))
return false;
$key = $this->getUsedKey($key);
$val = $this->_connection->get($key);
@@ -218,7 +226,7 @@ class redis_phpKVDriver extends jKVDriver implements jIKVSet, jIKVttl {
// jIKVttl -------------------------------------------------------------
public function setWithTtl($key, $value, $ttl) {
- if (is_resource($value))
+ if ($this->isResource($value))
return false;
if ($ttl != 0 && $ttl > 2592000) {
|
Fix compatibility with PHP8
It requires at least Jelix <I> and <I>
|
jelix_php-redis-plugin
|
train
|
f7e1a0480c0444f2eeb191c1c2a55735f20a3a3e
|
diff --git a/gulpfile.js b/gulpfile.js
index <HASH>..<HASH> 100644
--- a/gulpfile.js
+++ b/gulpfile.js
@@ -69,7 +69,7 @@ gulp.task('bump-typings', function () {
gulp.task('bump-readme', function () {
gulp.src(['gitbook/READMEv3.md'])
- .pipe(replace(/(v\d+\.\d+\.)(\d+)/g, function (matches, match1, match2) {
+ .pipe(replace(/(v[124567890]\d*\.\d+\.)(\d+)/g, function (matches, match1, match2) {
return match1 + (Number(match2) + 1);
}))
.pipe(gulp.dest('gitbook/'))
|
update bump logic for "README"
|
clarketm_TableExport
|
train
|
a94344d61be0ddb2f3a98a173ab60aae0d8b1570
|
diff --git a/lionengine-editor/src/main/java/com/b3dgs/lionengine/editor/collision/EntityCollisionEditor.java b/lionengine-editor/src/main/java/com/b3dgs/lionengine/editor/collision/EntityCollisionEditor.java
index <HASH>..<HASH> 100644
--- a/lionengine-editor/src/main/java/com/b3dgs/lionengine/editor/collision/EntityCollisionEditor.java
+++ b/lionengine-editor/src/main/java/com/b3dgs/lionengine/editor/collision/EntityCollisionEditor.java
@@ -21,10 +21,14 @@ import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.TreeItem;
import com.b3dgs.lionengine.editor.UtilEclipse;
import com.b3dgs.lionengine.editor.dialogs.AbstractEditor;
+import com.b3dgs.lionengine.game.Collision;
+import com.b3dgs.lionengine.game.configurer.ConfigCollisions;
import com.b3dgs.lionengine.game.configurer.Configurer;
+import com.b3dgs.lionengine.stream.XmlNode;
/**
* Entity collision editor.
@@ -41,6 +45,8 @@ public class EntityCollisionEditor
/** Configurer reference. */
private final Configurer configurer;
+ /** Collisions list. */
+ private EntityCollisionList entityCollisionList;
/**
* Constructor.
@@ -65,11 +71,26 @@ public class EntityCollisionEditor
content.setLayout(new GridLayout(2, false));
final EntityCollisionProperties entityCollisionProperties = new EntityCollisionProperties();
- final EntityCollisionList entityCollisionList = new EntityCollisionList(configurer, entityCollisionProperties);
+ entityCollisionList = new EntityCollisionList(configurer, entityCollisionProperties);
entityCollisionList.create(content);
entityCollisionProperties.create(content);
entityCollisionList.loadCollisions();
}
+
+ @Override
+ protected void onExit()
+ {
+ final XmlNode root = configurer.getRoot();
+ root.removeChildren(ConfigCollisions.COLLISION);
+ for (final TreeItem item : entityCollisionList.getTree().getItems())
+ {
+ final Collision collision = (Collision) item.getData();
+ final String coll = item.getText();
+ final XmlNode nodeAnim = ConfigCollisions.createNode(coll, collision);
+ root.add(nodeAnim);
+ }
+ configurer.save();
+ }
}
diff --git a/lionengine-game/src/main/java/com/b3dgs/lionengine/game/configurer/ConfigCollisions.java b/lionengine-game/src/main/java/com/b3dgs/lionengine/game/configurer/ConfigCollisions.java
index <HASH>..<HASH> 100644
--- a/lionengine-game/src/main/java/com/b3dgs/lionengine/game/configurer/ConfigCollisions.java
+++ b/lionengine-game/src/main/java/com/b3dgs/lionengine/game/configurer/ConfigCollisions.java
@@ -23,6 +23,7 @@ import java.util.Map;
import com.b3dgs.lionengine.Check;
import com.b3dgs.lionengine.LionEngineException;
import com.b3dgs.lionengine.game.Collision;
+import com.b3dgs.lionengine.stream.Stream;
import com.b3dgs.lionengine.stream.XmlNode;
/**
@@ -83,6 +84,25 @@ public class ConfigCollisions
return new Collision(offsetX, offsetY, width, height, mirror);
}
+ /**
+ * Create an XML node from a collision.
+ *
+ * @param name The collision name.
+ * @param collision The collision reference.
+ * @return The collision node.
+ */
+ public static XmlNode createNode(String name, Collision collision)
+ {
+ final XmlNode node = Stream.createXmlNode(ConfigCollisions.COLLISION);
+ node.writeString(ConfigCollisions.COLLISION_NAME, name);
+ node.writeInteger(ConfigCollisions.COLLISION_OFFSETX, collision.getOffsetX());
+ node.writeInteger(ConfigCollisions.COLLISION_OFFSETY, collision.getOffsetY());
+ node.writeInteger(ConfigCollisions.COLLISION_WIDTH, collision.getWidth());
+ node.writeInteger(ConfigCollisions.COLLISION_HEIGHT, collision.getHeight());
+ node.writeBoolean(ConfigCollisions.COLLISION_MIRROR, collision.hasMirror());
+ return node;
+ }
+
/** Collisions map. */
private final Map<String, Collision> collisions;
|
#<I>: Can edit and save collisions.
|
b3dgs_lionengine
|
train
|
273aadfacae9d3f53d1fcb9d68193c30554d1bc7
|
diff --git a/classes/Gems/Tracker/Field/SelectField.php b/classes/Gems/Tracker/Field/SelectField.php
index <HASH>..<HASH> 100644
--- a/classes/Gems/Tracker/Field/SelectField.php
+++ b/classes/Gems/Tracker/Field/SelectField.php
@@ -38,7 +38,11 @@ class SelectField extends FieldAbstract
*/
protected function addModelSettings(array &$settings)
{
- $empty = $this->util->getTranslated()->getEmptyDropdownArray();
+ $empty = [];
+ if (!$this->_fieldDefinition['gtf_required'] || $this->_fieldDefinition['gtf_field_default'] === null) {
+ $empty = $this->util->getTranslated()->getEmptyDropdownArray();
+ }
+
$multi = explode(parent::FIELD_SEP, $this->_fieldDefinition['gtf_field_values']);
$settings['elementClass'] = 'Select';
diff --git a/classes/Gems/Tracker/Model/AddTrackFieldsTransformer.php b/classes/Gems/Tracker/Model/AddTrackFieldsTransformer.php
index <HASH>..<HASH> 100644
--- a/classes/Gems/Tracker/Model/AddTrackFieldsTransformer.php
+++ b/classes/Gems/Tracker/Model/AddTrackFieldsTransformer.php
@@ -65,6 +65,20 @@ class AddTrackFieldsTransformer extends \MUtil_Model_ModelTransformerAbstract
}
/**
+ * Get default values of empty fields
+ *
+ * @return array
+ */
+ public function getEmptyFieldsData()
+ {
+ $fields = [];
+ foreach ($this->_trackFields as $key => $field) {
+ $fields[$key] = $field['gtf_field_default'];
+ }
+ return $fields;
+ }
+
+ /**
* If the transformer add's fields, these should be returned here.
* Called in $model->AddTransformer(), so the transformer MUST
* know which fields to add by then (optionally using the model
@@ -106,7 +120,7 @@ class AddTrackFieldsTransformer extends \MUtil_Model_ModelTransformerAbstract
} else {
if (! $empty) {
- $empty = array_fill_keys(array_keys($this->fieldsDefinition->getFieldNames()), null);
+ $empty = $this->getEmptyFieldsData();
}
$fields = $empty;
}
|
Fixed #<I> Added default fields as empty values and disabled an empty value in a select track field if the field is required and there is a default available
|
GemsTracker_gemstracker-library
|
train
|
faa5f33c7c29803916caac608416a39df08aebaa
|
diff --git a/lxd/firewall/drivers/drivers_nftables.go b/lxd/firewall/drivers/drivers_nftables.go
index <HASH>..<HASH> 100644
--- a/lxd/firewall/drivers/drivers_nftables.go
+++ b/lxd/firewall/drivers/drivers_nftables.go
@@ -471,8 +471,10 @@ func (d Nftables) InstanceSetupProxyNAT(projectName string, instanceName string,
listenAddressStr := forward.ListenAddress.String()
targetAddressStr := forward.TargetAddress.String()
- // Generate a slice of rules to add.
- var rules []map[string]interface{}
+ // Generate slices of rules to add.
+ var dnatRules []map[string]interface{}
+ var snatRules []map[string]interface{}
+
for i := range forward.ListenPorts {
// Use the target port that corresponds to the listen port (unless only 1 is specified, in which
// case use the same target port for all listen ports).
@@ -489,8 +491,7 @@ func (d Nftables) InstanceSetupProxyNAT(projectName string, instanceName string,
targetDest = fmt.Sprintf("[%s]:%d", targetAddressStr, targetPort)
}
- rules = append(rules, map[string]interface{}{
- "family": "inet",
+ dnatRules = append(dnatRules, map[string]interface{}{
"ipFamily": ipFamily,
"protocol": forward.Protocol,
"listenAddress": listenAddressStr,
@@ -498,17 +499,27 @@ func (d Nftables) InstanceSetupProxyNAT(projectName string, instanceName string,
"targetDest": targetDest,
"targetHost": targetAddressStr,
"targetPort": targetPort,
- "addHairpinNat": targetIndex == i, // Only add >1 hairpin NAT rules if connect range used.
})
+
+ // Only add >1 hairpin NAT rules if connect range used.
+ if targetIndex == i {
+ snatRules = append(snatRules, map[string]interface{}{
+ "ipFamily": ipFamily,
+ "protocol": forward.Protocol,
+ "targetHost": targetAddressStr,
+ "targetPort": targetPort,
+ })
+ }
}
deviceLabel := d.instanceDeviceLabel(projectName, instanceName, deviceName)
tplFields := map[string]interface{}{
"namespace": nftablesNamespace,
"chainSeparator": nftablesChainSeparator,
- "family": rules[0]["family"], // Family should be same for all rules, so use 1st as global.
+ "family": "inet",
"deviceLabel": deviceLabel,
- "rules": rules,
+ "dnatRules": dnatRules,
+ "snatRules": snatRules,
}
err := d.applyNftConfig(nftablesNetProxyNAT, tplFields)
diff --git a/lxd/firewall/drivers/drivers_nftables_templates.go b/lxd/firewall/drivers/drivers_nftables_templates.go
index <HASH>..<HASH> 100644
--- a/lxd/firewall/drivers/drivers_nftables_templates.go
+++ b/lxd/firewall/drivers/drivers_nftables_templates.go
@@ -79,25 +79,23 @@ chain out{{.chainSeparator}}{{.networkName}} {
var nftablesNetProxyNAT = template.Must(template.New("nftablesNetProxyNAT").Parse(`
chain prert{{.chainSeparator}}{{.deviceLabel}} {
type nat hook prerouting priority -100; policy accept;
- {{- range .rules}}
+ {{- range .dnatRules}}
{{.ipFamily}} daddr {{.listenAddress}} {{.protocol}} dport {{.listenPort}} dnat to {{.targetDest}}
{{- end}}
}
chain out{{.chainSeparator}}{{.deviceLabel}} {
type nat hook output priority -100; policy accept;
- {{- range .rules}}
+ {{- range .dnatRules}}
{{.ipFamily}} daddr {{.listenAddress}} {{.protocol}} dport {{.listenPort}} dnat to {{.targetDest}}
{{- end}}
}
chain pstrt{{.chainSeparator}}{{.deviceLabel}} {
type nat hook postrouting priority 100; policy accept;
- {{- range .rules}}
- {{if .addHairpinNat}}
+ {{- range .snatRules}}
{{.ipFamily}} saddr {{.targetHost}} {{.ipFamily}} daddr {{.targetHost}} {{.protocol}} dport {{.targetPort}} masquerade
{{- end}}
- {{- end}}
}
`))
|
lxd/firewall/drivers/drivers/nftables: Separate DNAT rules from SNAT rules in InstanceSetupProxyNAT
Lays the groundwork for fixing #<I> and supporting network forwards.
|
lxc_lxd
|
train
|
f3f8ac0709d3311fd6215850320c026a21e80841
|
diff --git a/test.py b/test.py
index <HASH>..<HASH> 100644
--- a/test.py
+++ b/test.py
@@ -200,17 +200,16 @@ def test_memory():
s1.add_constraints(c == 1)
nose.tools.assert_equal(set(s1.se.any_n_int(s1.mem_expr(0x8000, 4), 10)), { 0x11223344, 0xAA223344, 0xAABB3344, 0xAABBCC44, 0xAABBCCDD })
-
-def broken_abstractmemory():
+def test_abstract_memory():
from claripy.vsa import TrueResult
- initial_memory_global = {0: 'A', 1: 'B', 2: 'C', 3: 'D'}
- initial_memory = {'global': initial_memory_global}
+ initial_memory = {0: 'A', 1: 'B', 2: 'C', 3: 'D'}
s = SimState(mode='static',
arch="AMD64",
memory_backer=initial_memory,
add_options={simuvex.o.ABSTRACT_SOLVER, simuvex.o.ABSTRACT_MEMORY})
+ se = s.se
def to_vs(region, offset):
return s.se.VS(region=region, bits=s.arch.bits, val=offset)
@@ -222,7 +221,7 @@ def broken_abstractmemory():
nose.tools.assert_equal(s.se.min_int(expr), 0x43)
# Store a single-byte constant to global region
- s.memory.store(to_vs('global', 1), s.se.BitVecVal(ord('D'), 8))
+ s.memory.store(to_vs('global', 1), s.se.BitVecVal(ord('D'), 8), 1)
expr = s.memory.load(to_vs('global', 1), 1)[0]
nose.tools.assert_equal(s.se.any_int(expr), 0x44)
@@ -250,11 +249,11 @@ def broken_abstractmemory():
# Load the four-byte StridedInterval object from global region
expr = s.memory.load(to_vs('global', 1), 4)[0]
- nose.tools.assert_equal(expr.model == s.se.StridedInterval(bits=32, stride=2, lower_bound=8000, upper_bound=9000), TrueResult())
+ nose.tools.assert_true(se.is_true(expr.model == s.se.StridedInterval(bits=32, stride=2, lower_bound=8000, upper_bound=9000)))
# Test default values
expr = s.memory.load(to_vs('global', 100), 4)[0]
- nose.tools.assert_equal(expr.model == s.se.StridedInterval(bits=32, stride=0, lower_bound=0, upper_bound=0), TrueResult())
+ nose.tools.assert_true(se.is_true(expr.model == s.se.StridedInterval(bits=32, stride=0, lower_bound=0, upper_bound=0)))
#
# Merging
@@ -267,7 +266,32 @@ def broken_abstractmemory():
b = s.merge(a)[0]
expr = b.memory.load(to_vs('function_merge', 0), 1)[0]
- nose.tools.assert_equal(expr.model == s.se.StridedInterval(bits=8, stride=0x10, lower_bound=0x10, upper_bound=0x20), TrueResult())
+ nose.tools.assert_true(se.is_true(expr.model == s.se.StridedInterval(bits=8, stride=0x10, lower_bound=0x10, upper_bound=0x20)))
+
+ # | MO(value_0) |
+ # | MO(value_1) |
+ # 0x20 0x24
+ # Merge one byte in value_0/1 means merging the entire MemoryObject
+ a = s.copy()
+ a.memory.store(to_vs('function_merge', 0x20), se.SI(bits=32, stride=0, lower_bound=0x100000, upper_bound=0x100000))
+ b = s.copy()
+ b.memory.store(to_vs('function_merge', 0x20), se.SI(bits=32, stride=0, lower_bound=0x100001, upper_bound=0x100001))
+ c = a.merge(b)[0]
+ expr = c.memory.load(to_vs('function_merge', 0x20), 4)[0]
+ nose.tools.assert_true(se.is_true(expr.model == se.SI(bits=32, stride=1, lower_bound=0x100000, upper_bound=0x100001)))
+ c_mem = c.memory.regions['function_merge'].memory.mem
+ object_set = set([ c_mem[0x20], c_mem[0x20], c_mem[0x22], c_mem[0x23]])
+ nose.tools.assert_equal(len(object_set), 1)
+
+ a = s.copy()
+ a.memory.store(to_vs('function_merge', 0x20), se.SI(bits=32, stride=0x100000, lower_bound=0x100000, upper_bound=0x200000))
+ b = s.copy()
+ b.memory.store(to_vs('function_merge', 0x20), se.SI(bits=32, stride=0, lower_bound=0x300000, upper_bound=0x300000))
+ c = a.merge(b)[0]
+ expr = c.memory.load(to_vs('function_merge', 0x20), 4)[0]
+ nose.tools.assert_true(se.is_true(expr.model == se.SI(bits=32, stride=0x100000, lower_bound=0x100000, upper_bound=0x300000)))
+ object_set = set([c_mem[0x20], c_mem[0x20], c_mem[0x22], c_mem[0x23]])
+ nose.tools.assert_equal(len(object_set), 1)
#
# Widening
@@ -1483,6 +1507,9 @@ if __name__ == '__main__':
print 'memory'
test_memory()
+ print "abstract memory"
+ test_abstract_memory()
+
print 'registers'
test_registers()
|
Revived test_abstract_memory. Added a testcase for the new memory merging logic.
|
angr_angr
|
train
|
fb7542f920276689e0db30061df632d8e745985a
|
diff --git a/salt/config/__init__.py b/salt/config/__init__.py
index <HASH>..<HASH> 100644
--- a/salt/config/__init__.py
+++ b/salt/config/__init__.py
@@ -2965,7 +2965,7 @@ def apply_minion_config(overrides=None,
return opts
-def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None):
+def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
@@ -2992,8 +2992,8 @@ def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None):
defaults['default_include'])
include = overrides.get('include', [])
- overrides.update(include_config(default_include, path, verbose=False))
- overrides.update(include_config(include, path, verbose=True))
+ overrides.update(include_config(default_include, path, verbose=False), exit_on_config_errors=exit_on_config_errors)
+ overrides.update(include_config(include, path, verbose=True), exit_on_config_errors=exit_on_config_errors)
opts = apply_master_config(overrides, defaults)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
|
Add option to master config reader on ignoring system exit for wrong configuration
|
saltstack_salt
|
train
|
82a093b23ea93d92e3642f890e384d08bd172d61
|
diff --git a/base/src/main/java/uk/ac/ebi/atlas/utils/ExperimentSorter.java b/base/src/main/java/uk/ac/ebi/atlas/utils/ExperimentSorter.java
index <HASH>..<HASH> 100644
--- a/base/src/main/java/uk/ac/ebi/atlas/utils/ExperimentSorter.java
+++ b/base/src/main/java/uk/ac/ebi/atlas/utils/ExperimentSorter.java
@@ -79,7 +79,8 @@ public class ExperimentSorter {
}
private long estimateSizeOfRnaSeqBaselineExperiment(String experimentAccession) {
- return dataFileHub.getRnaSeqBaselineExperimentFiles(experimentAccession).dataFile(ExpressionUnit.Absolute.Rna.TPM).size();
+ DataFileHub.RnaSeqBaselineExperimentFiles files = dataFileHub.getRnaSeqBaselineExperimentFiles(experimentAccession);
+ return files.dataFile(files.dataFiles().iterator().next()).size();
}
private long estimateSizeOfProteomicsBaselineExperiment(String experimentAccession) {
|
Fix experiment sorter - do not assume there is a tpm file for everything
|
ebi-gene-expression-group_atlas
|
train
|
6a042ddd79df61663ebff477d32857946a38a4d5
|
diff --git a/faq-bundle/src/Resources/contao/languages/de/modules.php b/faq-bundle/src/Resources/contao/languages/de/modules.php
index <HASH>..<HASH> 100644
--- a/faq-bundle/src/Resources/contao/languages/de/modules.php
+++ b/faq-bundle/src/Resources/contao/languages/de/modules.php
@@ -39,7 +39,7 @@ $GLOBALS['TL_LANG']['MOD']['faq'] = array('FAQ', 'Häufig gestellte Fragen verwa
* Front end modules
*/
$GLOBALS['TL_LANG']['FMD']['faq'] = 'FAQ';
-$GLOBALS['TL_LANG']['FMD']['faqlist'] = array('FAQ-Liste', 'fügt der Seite eine Liste häufig gestellter Fragen hinzu.');
-$GLOBALS['TL_LANG']['FMD']['faqreader'] = array('FAQ-Leser', 'stellt die Antwort zu einer häufig gestellten Frage dar.');
+$GLOBALS['TL_LANG']['FMD']['faqlist'] = array('FAQ-Liste', 'Fügt der Seite eine Liste häufig gestellter Fragen hinzu.');
+$GLOBALS['TL_LANG']['FMD']['faqreader'] = array('FAQ-Leser', 'Stellt die Antwort zu einer häufig gestellten Frage dar.');
?>
\ No newline at end of file
diff --git a/faq-bundle/src/Resources/contao/languages/en/modules.php b/faq-bundle/src/Resources/contao/languages/en/modules.php
index <HASH>..<HASH> 100644
--- a/faq-bundle/src/Resources/contao/languages/en/modules.php
+++ b/faq-bundle/src/Resources/contao/languages/en/modules.php
@@ -39,7 +39,7 @@ $GLOBALS['TL_LANG']['MOD']['faq'] = array('FAQ', 'Manage frequently asked questi
* Front end modules
*/
$GLOBALS['TL_LANG']['FMD']['faq'] = 'FAQ';
-$GLOBALS['TL_LANG']['FMD']['faqlist'] = array('FAQ list', 'adds a list of frequently asked questions to the page.');
-$GLOBALS['TL_LANG']['FMD']['faqreader'] = array('FAQ reader', 'shows the answer to a frequently asked question.');
+$GLOBALS['TL_LANG']['FMD']['faqlist'] = array('FAQ list', 'Adds a list of frequently asked questions to the page.');
+$GLOBALS['TL_LANG']['FMD']['faqreader'] = array('FAQ reader', 'Shows the answer to a frequently asked question.');
?>
\ No newline at end of file
|
[Faq] Version <I>.RC1 candidate
|
contao_contao
|
train
|
930da631733faeca95f02bbd15abc56745e23925
|
diff --git a/pkg/cmd/grafana-server/server.go b/pkg/cmd/grafana-server/server.go
index <HASH>..<HASH> 100644
--- a/pkg/cmd/grafana-server/server.go
+++ b/pkg/cmd/grafana-server/server.go
@@ -56,7 +56,7 @@ func (g *GrafanaServerImpl) Start() {
g.writePIDFile()
initSql()
- err, _ := dsSettings.Init(filepath.Join(setting.HomePath, "conf/datasources.yaml"))
+ err := dsSettings.Init(filepath.Join(setting.HomePath, "conf/datasources.yaml"))
if err != nil {
g.log.Error("Failed to load datasources from config", "error", err)
g.Shutdown(1, "Startup failed")
diff --git a/pkg/setting/datasources/datasources.go b/pkg/setting/datasources/datasources.go
index <HASH>..<HASH> 100644
--- a/pkg/setting/datasources/datasources.go
+++ b/pkg/setting/datasources/datasources.go
@@ -1,7 +1,6 @@
package datasources
import (
- "io"
"io/ioutil"
"path/filepath"
@@ -14,18 +13,16 @@ import (
// TODO: secure jsonData
// TODO: auto reload on file changes
+// TODO: remove get method since all datasources is in memory
type DatasourcesAsConfig struct {
PurgeOtherDatasources bool
Datasources []models.DataSource
}
-func Init(configPath string) (error, io.Closer) {
-
+func Init(configPath string) error {
dc := NewDatasourceConfiguration()
- dc.applyChanges(configPath)
-
- return nil, ioutil.NopCloser(nil)
+ return dc.applyChanges(configPath)
}
type DatasourceConfigurator struct {
@@ -47,18 +44,39 @@ func newDatasourceConfiguration(log log.Logger, cfgProvider configProvider, repo
}
func (dc *DatasourceConfigurator) applyChanges(configPath string) error {
- datasources, err := dc.cfgProvider.readConfig(configPath)
+ cfg, err := dc.cfgProvider.readConfig(configPath)
if err != nil {
return err
}
- //read all datasources
- //delete datasources not in list
+ all, err := dc.repository.loadAllDatasources()
+ if err != nil {
+ return err
+ }
- for _, ds := range datasources.Datasources {
- if ds.OrgId == 0 {
- ds.OrgId = 1
+ for i, _ := range cfg.Datasources {
+ if cfg.Datasources[i].OrgId == 0 {
+ cfg.Datasources[i].OrgId = 1
}
+ }
+
+ if cfg.PurgeOtherDatasources {
+ for _, dbDatasource := range all {
+ delete := true
+ for _, cfgDatasource := range cfg.Datasources {
+ if dbDatasource.Name == cfgDatasource.Name && dbDatasource.OrgId == cfgDatasource.OrgId {
+ delete = false
+ }
+ }
+
+ if delete {
+ dc.log.Info("deleting datasource since PurgeOtherDatasource is enabled", "name", dbDatasource.Name)
+ dc.repository.delete(&models.DeleteDataSourceByIdCommand{Id: dbDatasource.Id, OrgId: dbDatasource.OrgId})
+ }
+ }
+ }
+
+ for _, ds := range cfg.Datasources {
query := &models.GetDataSourceByNameQuery{Name: ds.Name, OrgId: ds.OrgId}
err := dc.repository.get(query)
diff --git a/pkg/setting/datasources/datasources_test.go b/pkg/setting/datasources/datasources_test.go
index <HASH>..<HASH> 100644
--- a/pkg/setting/datasources/datasources_test.go
+++ b/pkg/setting/datasources/datasources_test.go
@@ -14,7 +14,6 @@ var logger log.Logger = log.New("fake.logger")
func TestDatasourceAsConfig(t *testing.T) {
Convey("Testing datasource as configuration", t, func() {
fakeCfg := &fakeConfig{}
-
fakeRepo := &fakeRepository{}
Convey("One configured datasource", func() {
@@ -101,6 +100,37 @@ func TestDatasourceAsConfig(t *testing.T) {
So(len(fakeRepo.updated), ShouldEqual, 0)
})
})
+
+ })
+
+ Convey("Two configured datasource and purge others = false", func() {
+ fakeCfg.cfg = &DatasourcesAsConfig{
+ PurgeOtherDatasources: false,
+ Datasources: []models.DataSource{
+ models.DataSource{Name: "graphite", OrgId: 1},
+ models.DataSource{Name: "prometheus", OrgId: 1},
+ },
+ }
+
+ Convey("two other datasources in database", func() {
+ fakeRepo.loadAll = []*models.DataSource{
+ &models.DataSource{Name: "old-graphite", OrgId: 1, Id: 1},
+ &models.DataSource{Name: "old-graphite2", OrgId: 1, Id: 2},
+ }
+
+ Convey("should have two new datasources", func() {
+ dc := newDatasourceConfiguration(logger, fakeCfg, fakeRepo)
+ err := dc.applyChanges("mock/config.yaml")
+ if err != nil {
+ t.Fatalf("applyChanges return an error %v", err)
+ }
+
+ So(len(fakeRepo.deleted), ShouldEqual, 0)
+ So(len(fakeRepo.inserted), ShouldEqual, 2)
+ So(len(fakeRepo.updated), ShouldEqual, 0)
+ })
+ })
+
})
})
}
|
datasource as cfg: setting for purging datasources not in cfg
|
grafana_grafana
|
train
|
42388beec05e537d0b0559368b2f8c6bbf8c31e1
|
diff --git a/gspread/models.py b/gspread/models.py
index <HASH>..<HASH> 100644
--- a/gspread/models.py
+++ b/gspread/models.py
@@ -1750,7 +1750,9 @@ class Worksheet(object):
return self.spreadsheet.values_append(range_label, params, body)
def delete_row(self, index):
- """Deletes the row from the worksheet at the specified index.
+ """.. deprecated:: 5.0
+
+ Deletes the row from the worksheet at the specified index.
:param int index: Index of a row for deletion.
"""
|
Add deprecation warning for delete_row method in documentation (#<I>)
|
burnash_gspread
|
train
|
cf8860bb10dfb9a76de54d20f33782f42c8f8831
|
diff --git a/pyu2f/u2f.py b/pyu2f/u2f.py
index <HASH>..<HASH> 100644
--- a/pyu2f/u2f.py
+++ b/pyu2f/u2f.py
@@ -115,7 +115,7 @@ class U2FInterface(object):
raise errors.U2FError(errors.U2FError.BAD_REQUEST, e)
# Now register the new key
- for _ in range(10):
+ for _ in range(30):
try:
resp = self.security_key.CmdRegister(challenge_param, app_param)
return model.RegisterResponse(resp, client_data)
@@ -143,9 +143,8 @@ class U2FInterface(object):
format.
Raises:
- U2FError: There was some kind of problem with registration (e.g.
- the device was already registered or there was a timeout while
- waiting for the test of user presence.)
+ U2FError: There was some kind of problem with authentication (e.g.
+ there was a timeout while waiting for the test of user presence.)
"""
client_data = model.ClientData(model.ClientData.TYP_AUTHENTICATION,
challenge, self.origin)
@@ -156,7 +155,7 @@ class U2FInterface(object):
try:
if key.version != 'U2F_V2':
continue
- for _ in range(10):
+ for _ in range(30):
try:
resp = self.security_key.CmdAuthenticate(challenge_param, app_param,
key.key_handle)
|
Increase timeout for register & authenticate
|
google_pyu2f
|
train
|
eea5e40117b254115fe45d84cd69f63c3398b28b
|
diff --git a/api/resolver.py b/api/resolver.py
index <HASH>..<HASH> 100644
--- a/api/resolver.py
+++ b/api/resolver.py
@@ -220,7 +220,7 @@ def get_profile(fqa):
zonefile = res['zonefile']
address = res['name_record']['address']
- if 'expired' in res['name_record']:
+ if 'expired' in res['name_record'] and res['name_record']['expired']:
profile_expired_grace = True
except Exception as e:
|
oops-- actually need to *check* the expired flag
|
blockstack_blockstack-core
|
train
|
0d39cd0f7fcafd4f4570fee66a57260e5d8acc6c
|
diff --git a/gogs_api.gemspec b/gogs_api.gemspec
index <HASH>..<HASH> 100755
--- a/gogs_api.gemspec
+++ b/gogs_api.gemspec
@@ -1,6 +1,6 @@
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
-require "main/gogs/version"
+require "megam/gogs/version"
Gem::Specification.new do |s|
s.name = "megam_gogs"
diff --git a/lib/gogs_api.rb b/lib/gogs_api.rb
index <HASH>..<HASH> 100644
--- a/lib/gogs_api.rb
+++ b/lib/gogs_api.rb
@@ -1 +1 @@
-require(File.join(File.dirname(__FILE__), "main", "gogs"))
+require(File.join(File.dirname(__FILE__), "megam", "gogs"))
diff --git a/lib/megam/core/gogs_client/gogs_tokens.rb b/lib/megam/core/gogs_client/gogs_tokens.rb
index <HASH>..<HASH> 100644
--- a/lib/megam/core/gogs_client/gogs_tokens.rb
+++ b/lib/megam/core/gogs_client/gogs_tokens.rb
@@ -32,9 +32,10 @@ module Megam
end
- # Load a account by email_p
+
def self.list(username, password)
#acct = self.new(username, password)
+ puts "Entering into the GOGS API successfully-0-0-0-0-0-0-0-0"
megams = Megam::Gogs.new
res = megams.get_tokens(username, password)
hash = {}
diff --git a/lib/megam/gogs.rb b/lib/megam/gogs.rb
index <HASH>..<HASH> 100644
--- a/lib/megam/gogs.rb
+++ b/lib/megam/gogs.rb
@@ -19,6 +19,7 @@ require "megam/gogs/repos"
require "megam/gogs/tokens"
require "megam/core/gogs_client/gogs_repo"
require "megam/core/gogs_client/gogs_account"
+require "megam/core/gogs_client/gogs_tokens"
module Megam
@@ -38,7 +39,7 @@ module Megam
OPTIONS = {
:headers => {},
:host => 'localhost',
- :port => '3000',
+ :port => '6001',
:nonblock => false,
:scheme => 'http'
}
@@ -138,7 +139,7 @@ def connection_repo
@connection = Excon.new("#{@options[:scheme]}://#{@options[:host]}",@options)
else
Excon.defaults[:ssl_verify_peer] = false
- @connection = Excon.new("#{@options[:scheme]}://#{@options[:host]}:3000",@options)
+ @connection = Excon.new("#{@options[:scheme]}://#{@options[:host]}:6001",@options)
end
@connection
end
@@ -166,7 +167,7 @@ def connection_repo
@connection = Excon.new("#{@options[:scheme]}://#{@options[:host]}",@options)
else
Excon.defaults[:ssl_verify_peer] = false
- @connection = Excon.new("#{@options[:scheme]}://#{@options[:host]}:3000",@options)
+ @connection = Excon.new("#{@options[:scheme]}://#{@options[:host]}:6001",@options)
end
@connection
end
diff --git a/test/test_helper.rb b/test/test_helper.rb
index <HASH>..<HASH> 100755
--- a/test/test_helper.rb
+++ b/test/test_helper.rb
@@ -7,7 +7,7 @@ require 'time'
SANDBOX_HOST_OPTIONS = {
:host => 'localhost',
- :port => 3000
+ :port => 6001
}
|
gogs port <I> - few fixes
|
megamsys_megam_gogs.rb
|
train
|
3ca8c382348b603807b5515ece090f8027a34470
|
diff --git a/codeanalyzer.py b/codeanalyzer.py
index <HASH>..<HASH> 100644
--- a/codeanalyzer.py
+++ b/codeanalyzer.py
@@ -366,6 +366,26 @@ class CodeAnalyzer(object):
self.write_addrs = []
# ======================================================================== #
+ def set_arch_info(self, arch_info):
+ self._arch_info = arch_info
+
+ def get_operand_var(self, operand):
+ return self._translator._translate_src_oprnd(operand)
+
+ def get_operand_expr(self, operand, mode="post"):
+ if isinstance(operand, ReilRegisterOperand):
+ if operand.name in self._arch_info.registers_gp_all:
+ expr = self.get_register_expr(operand.name, mode=mode)
+ else:
+ expr = self.get_tmp_register_expr(
+ operand.name, operand.size, mode=mode)
+ elif isinstance(operand, ReilRegisterOperand):
+ expr = self.get_immediate_expr(operand.immediate, operand.size)
+ else:
+ raise Exception("Invalid operand: %s" % str(operand))
+
+ return expr
+
def get_register_expr(self, register_name, mode="post"):
"""Return a smt bit vector that represents a register.
"""
@@ -453,6 +473,9 @@ class CodeAnalyzer(object):
return mem
+ def add_constraint(self, contraint):
+ self._solver.add(contraint)
+
def add_instruction(self, reil_instruction):
"""Add an instruction for analysis.
"""
|
BARF: Add missing functionality to CodeAnalyzer.py
|
programa-stic_barf-project
|
train
|
5e229b626ea4e218c0c04a4d436c6be8b7aea4e7
|
diff --git a/server/sonar-server/src/main/java/org/sonar/server/batch/ProjectRepositoryLoader.java b/server/sonar-server/src/main/java/org/sonar/server/batch/ProjectRepositoryLoader.java
index <HASH>..<HASH> 100644
--- a/server/sonar-server/src/main/java/org/sonar/server/batch/ProjectRepositoryLoader.java
+++ b/server/sonar-server/src/main/java/org/sonar/server/batch/ProjectRepositoryLoader.java
@@ -227,7 +227,9 @@ public class ProjectRepositoryLoader implements ServerComponent {
private void addActiveRules(ProjectRepositories ref) {
for (org.sonar.batch.protocol.input.QProfile qProfile : ref.qProfiles()) {
Map<RuleKey, ActiveRule> activeRules = activeRuleByRuleKey(qProfileLoader.findActiveRulesByProfile(qProfile.key()));
- for (Rule rule : ruleService.search(new RuleQuery().setQProfileKey(qProfile.key()).setActivation(true), new QueryContext()).getHits()) {
+ Iterator<Rule> rules = ruleService.search(new RuleQuery().setQProfileKey(qProfile.key()).setActivation(true), new QueryContext().setScroll(true)).scroll();
+ while (rules.hasNext()) {
+ Rule rule = rules.next();
RuleKey templateKey = rule.templateKey();
ActiveRule activeRule = activeRules.get(rule.key());
org.sonar.batch.protocol.input.ActiveRule inputActiveRule = new org.sonar.batch.protocol.input.ActiveRule(
diff --git a/server/sonar-server/src/test/java/org/sonar/server/batch/ProjectRepositoryLoaderMediumTest.java b/server/sonar-server/src/test/java/org/sonar/server/batch/ProjectRepositoryLoaderMediumTest.java
index <HASH>..<HASH> 100644
--- a/server/sonar-server/src/test/java/org/sonar/server/batch/ProjectRepositoryLoaderMediumTest.java
+++ b/server/sonar-server/src/test/java/org/sonar/server/batch/ProjectRepositoryLoaderMediumTest.java
@@ -614,6 +614,29 @@ public class ProjectRepositoryLoaderMediumTest {
}
@Test
+ public void return_more_than_10_active_rules() throws Exception {
+ ComponentDto project = ComponentTesting.newProjectDto();
+ MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION);
+ tester.get(DbClient.class).componentDao().insert(dbSession, project);
+
+ QualityProfileDto profileDto = QProfileTesting.newDto(QProfileName.createFor(ServerTester.Xoo.KEY, "SonarQube way"), "abcd")
+ .setRulesUpdatedAt(DateUtils.formatDateTime(DateUtils.parseDateTime("2014-01-14T13:00:00+0100")));
+ tester.get(DbClient.class).qualityProfileDao().insert(dbSession, profileDto);
+ tester.get(DbClient.class).propertiesDao().setProperty(new PropertyDto().setKey("sonar.profile.xoo").setValue("SonarQube way"), dbSession);
+
+ for (int i = 0; i<20; i++) {
+ RuleKey ruleKey = RuleKey.of("squid", "Rule" + i);
+ tester.get(DbClient.class).ruleDao().insert(dbSession, RuleTesting.newDto(ruleKey).setName("Rule" + i).setLanguage(ServerTester.Xoo.KEY));
+ tester.get(RuleActivator.class).activate(dbSession, new RuleActivation(ruleKey).setSeverity(Severity.MINOR), profileDto.getKey());
+ }
+
+ dbSession.commit();
+
+ ProjectRepositories ref = loader.load(ProjectRepositoryQuery.create().setModuleKey(project.key()));
+ assertThat(ref.activeRules()).hasSize(20);
+ }
+
+ @Test
public void return_custom_rule() throws Exception {
Date ruleUpdatedAt = DateUtils.parseDateTime("2014-01-14T13:00:00+0100");
|
SONAR-<I> Number of returned active rules should not be limited
|
SonarSource_sonarqube
|
train
|
5dbfaa6a8cf3d1cd2ac9e5d62474681cc13427a0
|
diff --git a/spec/node/asciidoctor.spec.js b/spec/node/asciidoctor.spec.js
index <HASH>..<HASH> 100644
--- a/spec/node/asciidoctor.spec.js
+++ b/spec/node/asciidoctor.spec.js
@@ -279,6 +279,24 @@ describe('Node.js', function () {
expect(result).toContain('Lorem ipsum dolor sit amet');
});
+ it('should be able to pass an extension registry to the processor', function () {
+ var registry = Opal.Asciidoctor.$$scope.Extensions.create(function () {
+ this.block(function () {
+ var self = this;
+ self.named('whisper');
+ self.onContext('paragraph');
+ self.process(function (parent, reader) {
+ var lines = reader.$lines().map(function (l) { return l.toLowerCase().replace('!', '.'); });
+ return self.createBlock(parent, 'paragraph', lines);
+ });
+ });
+ });
+ var opts = {};
+ opts[asciidoctorVersionGreaterThan('1.5.5') ? 'extension_registry' : 'extensions_registry'] = registry;
+ var result = asciidoctor.convert('[whisper]\nWE HAVE LIFTOFF!', opts);
+ expect(result).toContain('we have liftoff.');
+ });
+
it('should be able to convert a file and include the default stylesheet', function () {
var options = {safe: 'safe', header_footer: true};
var html = asciidoctor.convert('=== Test', options);
diff --git a/src/asciidoctor-extensions-api.js b/src/asciidoctor-extensions-api.js
index <HASH>..<HASH> 100644
--- a/src/asciidoctor-extensions-api.js
+++ b/src/asciidoctor-extensions-api.js
@@ -48,6 +48,17 @@ var Extensions = Opal.Asciidoctor.$$scope.Extensions;
/**
* @memberof Extensions
*/
+Extensions.create = function (name, block) {
+ if (typeof name === 'function' && typeof block === 'undefined') {
+ return Opal.send(this, 'build_registry', null, toBlock(name));
+ } else {
+ return Opal.send(this, 'build_registry', [name], toBlock(block));
+ }
+};
+
+/**
+ * @memberof Extensions
+ */
Extensions.register = function (name, block) {
if (typeof name === 'function' && typeof block === 'undefined') {
return Opal.send(this, 'register', null, toBlock(name));
|
:sparkles: resolves #<I> map the Extensions.create API and test (#<I>)
|
asciidoctor_asciidoctor.js
|
train
|
107483f169b1b0dae5efa9e716b4d6484bc00409
|
diff --git a/db/seeds/demo/100_rabbit_demographics.rb b/db/seeds/demo/100_rabbit_demographics.rb
index <HASH>..<HASH> 100644
--- a/db/seeds/demo/100_rabbit_demographics.rb
+++ b/db/seeds/demo/100_rabbit_demographics.rb
@@ -8,16 +8,44 @@ module Renalware
rabbit.marital_status = "divorced"
rabbit.telephone1 = "0201 555 1212"
rabbit.email = "rogerrabbit@rmail.co.uk"
- rabbit.religion_id = 1
- rabbit.language_id = 1
+ rabbit.religion = Renalware::Patients::Religion.second!
+ rabbit.language = Renalware::Patients::Language.first!
rabbit.by = user
rabbit.document = {referral:
{referral_date: 1.week.ago,
referral_type: "Urgent",
referral_notes: "NB family friend of referrer",
referring_physician_name: "Dr Jack L N Hyde"},
- admin_notes: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
-tempor incididunt ut labore et dolore magna aliqua."
+ admin_notes: "Lorem ipsum dolor sit amet, consectetur adipisicing elit.",
+ pharmacist:
+ {name: "P N Boots",
+ address: {city: "London",
+ postcode: "W1A 1AA",
+ street_1: "Hallam St",
+ organisation_name: "Boots Pharmacist"
+ },
+ telephone: "0201 555 1288"
+ },
+ next_of_kin:
+ {name: "Sir Reginald Rabbit",
+ address: {city: "London",
+ postcode: "W1 A11",
+ street_1: "221B Baker St"
+ },
+ telephone: "0201 555 7788"
+ },
+ district_nurse:
+ {name: "Flo Nightingale",
+ address:
+ {city: "London",
+ street_1: "333 Tooley St",
+ street_2: "3rd Floor",
+ organisation_name: "Southwark Nurses"
+ },
+ telephone: "0201 555 9999"
+ },
+ interpreter_notes: "Second language French",
+ special_needs_notes: "Lorem ipsum dolor sit amet"
}
rabbit.save!
end
|
Complete Rabbit seeded demographics (JSONB)
|
airslie_renalware-core
|
train
|
e66c454b0ac86a790e00afd9eae1e1a77b88d083
|
diff --git a/app/models/rapidfire/attempt.rb b/app/models/rapidfire/attempt.rb
index <HASH>..<HASH> 100644
--- a/app/models/rapidfire/attempt.rb
+++ b/app/models/rapidfire/attempt.rb
@@ -1,7 +1,12 @@
module Rapidfire
class Attempt < ActiveRecord::Base
belongs_to :survey
- belongs_to :user, polymorphic: true
has_many :answers, inverse_of: :attempt, autosave: true
+
+ if Rails::VERSION::MAJOR >= 5
+ belongs_to :user, polymorphic: true, optional: true
+ else
+ belongs_to :user, polymorphic: true
+ end
end
end
|
Add a flag to user in attempts model to make it optional
In rails 5, `belongs_to` adds the required validation by default with
it. Make it optional so that non-logged in users can also take the
survey.
|
code-mancers_rapidfire
|
train
|
dc927f18d7e6cf70ff18b32622481085b193130e
|
diff --git a/lib/Array/prototype/uniq.js b/lib/Array/prototype/uniq.js
index <HASH>..<HASH> 100644
--- a/lib/Array/prototype/uniq.js
+++ b/lib/Array/prototype/uniq.js
@@ -4,12 +4,15 @@
'use strict';
+var filter = Array.prototype.filter
+ , indexOf = Array.prototype.indexOf
+
+ , isFirst;
+
+isFirst = function (value, index) {
+ return indexOf.call(this, value) === index;
+};
+
module.exports = function () {
- var i;
- for (i = this.length; i >= 0; --i) {
- if (this.indexOf(this[i]) !== i) {
- this.splice(i, 1);
- }
- }
- return this;
+ return filter.call(this, isFirst, this);
};
diff --git a/lib/Object/get-property-names.js b/lib/Object/get-property-names.js
index <HASH>..<HASH> 100644
--- a/lib/Object/get-property-names.js
+++ b/lib/Object/get-property-names.js
@@ -11,6 +11,5 @@ module.exports = f(function () {
while((o = Object.getPrototypeOf(o))) {
push.apply(keys, Object.getOwnPropertyNames(o));
}
- uniq.call(keys);
- return keys;
+ return uniq.call(keys);
});
diff --git a/test/Array/prototype/uniq.js b/test/Array/prototype/uniq.js
index <HASH>..<HASH> 100644
--- a/test/Array/prototype/uniq.js
+++ b/test/Array/prototype/uniq.js
@@ -1,9 +1,9 @@
'use strict';
module.exports = function (t, a) {
- var o, x = {}, y = {}, z = {};
+ var o, x = {}, y = {}, z = {}, w;
o = [1, 2, x, 3, 1, 'raz', '1', y, x, 'trzy', z, 'raz'];
- t.call(o);
- a.deep(o, [1, 2, x, 3, 'raz', '1', y, 'trzy', z]);
+ a.not(w = t.call(o), o, "Returns different object");
+ a.deep(w, [1, 2, x, 3, 'raz', '1', y, 'trzy', z], "Result");
};
diff --git a/test/Array/uniq.js b/test/Array/uniq.js
index <HASH>..<HASH> 100644
--- a/test/Array/uniq.js
+++ b/test/Array/uniq.js
@@ -1,8 +1,8 @@
'use strict';
module.exports = function (t, a) {
- var x = [1, 1, 'raz', 'raz'];
+ var x = [1, 1, 'raz', 'raz'], y;
- a(t(x), x, "Return");
- a.deep(x, [1, 'raz'], "Operation");
+ a.not(y = t(x), x, "Return");
+ a.deep(y, [1, 'raz'], "Operation");
};
|
Make Array's uniq not destructive (destructive methods may not be needed, if they would be we will provide them with special prefix)
|
medikoo_es5-ext
|
train
|
bd00823a7e9aa00cb3b1738fde244573ba7cce2c
|
diff --git a/binding.go b/binding.go
index <HASH>..<HASH> 100644
--- a/binding.go
+++ b/binding.go
@@ -32,7 +32,7 @@ import (
"gopkg.in/macaron.v1"
)
-const _VERSION = "0.3.0"
+const _VERSION = "0.3.1"
func Version() string {
return _VERSION
@@ -459,9 +459,11 @@ VALIDATE_RULES:
// Apply custom validation rules.
var isValid bool
for i := range ruleMapper {
- isValid, errors = ruleMapper[i].IsValid(errors, field.Name, fieldValue)
- if ruleMapper[i].IsMatch(rule) && !isValid {
- break VALIDATE_RULES
+ if ruleMapper[i].IsMatch(rule) {
+ isValid, errors = ruleMapper[i].IsValid(errors, field.Name, fieldValue)
+ if !isValid {
+ break VALIDATE_RULES
+ }
}
}
}
|
#9 fix match and valid order problem
|
go-macaron_binding
|
train
|
963d45ca5d38f044482b72fe8be571d275f0dcd7
|
diff --git a/lib/respect/schema.rb b/lib/respect/schema.rb
index <HASH>..<HASH> 100644
--- a/lib/respect/schema.rb
+++ b/lib/respect/schema.rb
@@ -223,6 +223,10 @@ module Respect
end
end
+ def to_pretty_json(format = :json_schema_v3)
+ JSON.pretty_generate(self.to_h(format))
+ end
+
# Return the options with no default value.
# (Useful when writing a dumper)
def non_default_options
diff --git a/test/schema_test.rb b/test/schema_test.rb
index <HASH>..<HASH> 100644
--- a/test/schema_test.rb
+++ b/test/schema_test.rb
@@ -105,6 +105,11 @@ class SchemaTest < Test::Unit::TestCase
Respect::ObjectSchema.new.to_json(:json_schema_v3))
end
+ def test_schema_to_pretty_json_schema_v3
+ assert_equal("{\n \"type\": \"object\"\n}",
+ Respect::ObjectSchema.new.to_pretty_json(:json_schema_v3))
+ end
+
def test_def_class_name
assert_equal "Respect::SchemaDef", Respect::Schema.def_class_name
assert_equal "Respect::ArrayDef", Respect::ArraySchema.def_class_name
|
Add Schema#to_pretty_json and test it.
|
nicolasdespres_respect
|
train
|
f9a0d21fab682198629e56fbcb404c98ad28ea29
|
diff --git a/cgroups/systemd/apply_systemd.go b/cgroups/systemd/apply_systemd.go
index <HASH>..<HASH> 100644
--- a/cgroups/systemd/apply_systemd.go
+++ b/cgroups/systemd/apply_systemd.go
@@ -3,7 +3,6 @@
package systemd
import (
- "bytes"
"fmt"
"io/ioutil"
"os"
@@ -247,6 +246,21 @@ func writeFile(dir, file, data string) error {
return ioutil.WriteFile(filepath.Join(dir, file), []byte(data), 0700)
}
+func join(c *configs.Cgroup, subsystem string, pid int) (string, error) {
+ path, err := getSubsystemPath(c, subsystem)
+ if err != nil {
+ return "", err
+ }
+ if err := os.MkdirAll(path, 0755); err != nil && !os.IsExist(err) {
+ return "", err
+ }
+ if err := writeFile(path, "cgroup.procs", strconv.Itoa(pid)); err != nil {
+ return "", err
+ }
+
+ return path, nil
+}
+
func joinCpu(c *configs.Cgroup, pid int) error {
path, err := getSubsystemPath(c, "cpu")
if err != nil {
@@ -266,16 +280,11 @@ func joinCpu(c *configs.Cgroup, pid int) error {
}
func joinFreezer(c *configs.Cgroup, pid int) error {
- path, err := getSubsystemPath(c, "freezer")
- if err != nil {
+ if _, err := join(c, "freezer", pid); err != nil {
return err
}
- if err := os.MkdirAll(path, 0755); err != nil && !os.IsExist(err) {
- return err
- }
-
- return ioutil.WriteFile(filepath.Join(path, "cgroup.procs"), []byte(strconv.Itoa(pid)), 0700)
+ return nil
}
func getSubsystemPath(c *configs.Cgroup, subsystem string) (string, error) {
@@ -360,29 +369,16 @@ func getUnitName(c *configs.Cgroup) string {
// because systemd will re-write the device settings if it needs to re-apply the cgroup context.
// This happens at least for v208 when any sibling unit is started.
func joinDevices(c *configs.Cgroup, pid int) error {
- path, err := getSubsystemPath(c, "devices")
+ path, err := join(c, "devices", pid)
if err != nil {
return err
}
- if err := os.MkdirAll(path, 0755); err != nil && !os.IsExist(err) {
- return err
- }
-
- if err := ioutil.WriteFile(filepath.Join(path, "cgroup.procs"), []byte(strconv.Itoa(pid)), 0700); err != nil {
+ devices := subsystems["devices"]
+ if err := devices.Set(path, c); err != nil {
return err
}
- if !c.AllowAllDevices {
- if err := writeFile(path, "devices.deny", "a"); err != nil {
- return err
- }
- }
- for _, dev := range c.AllowedDevices {
- if err := writeFile(path, "devices.allow", dev.CgroupString()); err != nil {
- return err
- }
- }
return nil
}
|
cleanup for systemd cgroup
Add join function so we can reduce duplicate code, and we can
call Set api in fs cgroup, that can reduce sync work on fs side
and systemd side.
|
opencontainers_runc
|
train
|
466fee86343afa4998b985f50b4c9155100c3656
|
diff --git a/pkg/util/net/port_split_test.go b/pkg/util/net/port_split_test.go
index <HASH>..<HASH> 100644
--- a/pkg/util/net/port_split_test.go
+++ b/pkg/util/net/port_split_test.go
@@ -28,16 +28,18 @@ func TestSplitSchemeNamePort(t *testing.T) {
normalized bool
}{
{
- in: "aoeu:asdf",
- name: "aoeu",
- port: "asdf",
- valid: true,
+ in: "aoeu:asdf",
+ name: "aoeu",
+ port: "asdf",
+ valid: true,
+ normalized: true,
}, {
- in: "http:aoeu:asdf",
- scheme: "http",
- name: "aoeu",
- port: "asdf",
- valid: true,
+ in: "http:aoeu:asdf",
+ scheme: "http",
+ name: "aoeu",
+ port: "asdf",
+ valid: true,
+ normalized: true,
}, {
in: "https:aoeu:",
scheme: "https",
@@ -46,26 +48,34 @@ func TestSplitSchemeNamePort(t *testing.T) {
valid: true,
normalized: false,
}, {
- in: "https:aoeu:asdf",
- scheme: "https",
- name: "aoeu",
- port: "asdf",
- valid: true,
+ in: "https:aoeu:asdf",
+ scheme: "https",
+ name: "aoeu",
+ port: "asdf",
+ valid: true,
+ normalized: true,
}, {
in: "aoeu:",
name: "aoeu",
valid: true,
normalized: false,
}, {
+ in: "aoeu",
+ name: "aoeu",
+ valid: true,
+ normalized: true,
+ }, {
in: ":asdf",
valid: false,
}, {
in: "aoeu:asdf:htns",
valid: false,
}, {
- in: "aoeu",
- name: "aoeu",
- valid: true,
+ in: "http::asdf",
+ valid: false,
+ }, {
+ in: "http::",
+ valid: false,
}, {
in: "",
valid: false,
|
Optimize port_split_test test case.
|
kubernetes_kubernetes
|
train
|
1c13f7a1c30c5171c4784e7254ede7538270ba1b
|
diff --git a/lib/yard/templates/template.rb b/lib/yard/templates/template.rb
index <HASH>..<HASH> 100644
--- a/lib/yard/templates/template.rb
+++ b/lib/yard/templates/template.rb
@@ -7,7 +7,19 @@ module YARD
attr_reader :options
class << self
- # @return [Array<Module>] a list of modules to be automatically included
+ # Extra includes are mixins that are included after a template is created. These
+ # mixins can be registered by plugins to operate on templates and override behaviour.
+ #
+ # Note that this array can be filled with modules or proc objects. If a proc object
+ # is given, the proc will be called with the {Template#options} hash containing
+ # relevant template information like the object, format, and more. The proc should
+ # return a module or nil if there is none.
+ #
+ # @example Adding in extra mixins to include on a template
+ # Template.extra_includes << MyHelper
+ # @example Conditionally including a mixin if the format is html
+ # Template.extra_includes << proc {|opts| MyHelper if opts[:format] == :html }
+ # @return [Array<Module, Proc>] a list of modules to be automatically included
# into any new template module
attr_accessor :extra_includes
@@ -15,10 +27,29 @@ module YARD
def included(klass)
klass.extend(ClassMethods)
end
+
+ # Includes the {extra_includes} modules into the template object.
+ #
+ # @param [Template] template the template object to mixin the extra includes.
+ # @param [SymbolHash] options the options hash containing all template information
+ # @return [void]
+ def include_extra(template, options)
+ extra_includes.each do |mod|
+ mod = mod.call(options) if mod.is_a?(Proc)
+ next unless mod.is_a?(Module)
+ template.extend(mod)
+ end
+ end
end
- self.extra_includes = []
-
+ self.extra_includes = [
+ proc {|options|
+ { :html => Helpers::HtmlHelper,
+ :text => Helpers::TextHelper,
+ :dot => Helpers::UMLHelper }[options[:format]]
+ }
+ ]
+
include ErbCache
include Helpers::BaseHelper
include Helpers::MethodHelper
@@ -135,12 +166,7 @@ module YARD
@cache, @cache_filename = {}, {}
@sections, @options = [], opts.class.new
add_options(opts)
-
- extend(Helpers::HtmlHelper) if options.format == :html
- extend(Helpers::TextHelper) if options.format == :text
- extend(Helpers::UMLHelper) if options.format == :dot
- extend(*Template.extra_includes) unless Template.extra_includes.empty?
-
+ Template.include_extra(self, options)
init
end
|
Add support for pushing procs into the Template.extra_includes array
|
lsegal_yard
|
train
|
3a58016aebfda95a14991f4ef0308110101851d2
|
diff --git a/addon/components/flexberry-base-component.js b/addon/components/flexberry-base-component.js
index <HASH>..<HASH> 100644
--- a/addon/components/flexberry-base-component.js
+++ b/addon/components/flexberry-base-component.js
@@ -53,6 +53,15 @@ export default Ember.Component.extend({
dynamicProperties: null,
/**
+ * Store record to which current component's value is related.
+ *
+ * @property relatedRecord
+ * @type Object
+ * @default null
+ */
+ relatedRecord: null,
+
+ /**
* Path to component's settings in application configuration (JSON from ./config/environment.js).
*
* @property appConfigSettingsPath
diff --git a/addon/components/flexberry-lookup.js b/addon/components/flexberry-lookup.js
index <HASH>..<HASH> 100644
--- a/addon/components/flexberry-lookup.js
+++ b/addon/components/flexberry-lookup.js
@@ -135,7 +135,7 @@ var FlexberryLookup = FlexberryBaseComponent.extend({
relationName: this.get('relationName'),
title: this.get('title'),
limitFunction: this.get('limitFunction'),
- modelToLookup: undefined
+ modelToLookup: this.get('relatedRecord')
};
}),
@@ -148,7 +148,7 @@ var FlexberryLookup = FlexberryBaseComponent.extend({
removeData: Ember.computed('relationName', function() {
return {
relationName: this.get('relationName'),
- modelToLookup: undefined
+ modelToLookup: this.get('relatedRecord')
};
}),
@@ -201,6 +201,7 @@ var FlexberryLookup = FlexberryBaseComponent.extend({
let autocompleteUrl = this.get('autocompleteUrl')(relationName);
let limitFunction = this.get('limitFunction');
+ let modelToLookup = this.get('relatedRecord');
this.set('autocompleteValue', this.get('value'));
let _this = this;
@@ -234,7 +235,7 @@ var FlexberryLookup = FlexberryBaseComponent.extend({
'autocompleteUpdateAction',
{
relationName: relationName,
- modelToLookup: undefined,
+ modelToLookup: modelToLookup,
newRelationValue: result
});
}
diff --git a/app/templates/components/object-list-view.hbs b/app/templates/components/object-list-view.hbs
index <HASH>..<HASH> 100644
--- a/app/templates/components/object-list-view.hbs
+++ b/app/templates/components/object-list-view.hbs
@@ -42,6 +42,7 @@
<td>
{{component column.cellComponent.componentName
dynamicProperties=column.cellComponent.componentProperties
+ relatedRecord=record.data
value=(mut (get record.data column.propName))
readonly=readonly
required=required
|
Add relatedRecord property to flexberry-base-component
|
Flexberry_ember-flexberry
|
train
|
256137d0b037e7e3f7c62f132132b1b7e57d919d
|
diff --git a/lib/minder/database/database_migrator.rb b/lib/minder/database/database_migrator.rb
index <HASH>..<HASH> 100644
--- a/lib/minder/database/database_migrator.rb
+++ b/lib/minder/database/database_migrator.rb
@@ -2,7 +2,7 @@ module Minder
class DatabaseMigrator
attr_reader :database
- def initialize(database:)
+ def initialize(database: nil)
@database = database
end
diff --git a/lib/minder/tasks/task_manager.rb b/lib/minder/tasks/task_manager.rb
index <HASH>..<HASH> 100644
--- a/lib/minder/tasks/task_manager.rb
+++ b/lib/minder/tasks/task_manager.rb
@@ -8,7 +8,7 @@ module Minder
:database,
:tasks
- def initialize(database:)
+ def initialize(database: nil)
@database = database
@selected_task_index = 0
@selected_search_result = 0
diff --git a/minder.gemspec b/minder.gemspec
index <HASH>..<HASH> 100644
--- a/minder.gemspec
+++ b/minder.gemspec
@@ -16,7 +16,7 @@ Gem::Specification.new do |spec|
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
- spec.required_ruby_version = '>= 2.1'
+ spec.required_ruby_version = '>= 2.0'
spec.add_runtime_dependency 'curses', '~> 1.0', '>= 1.0.1'
spec.add_runtime_dependency 'virtus', '~> 1.0', '>= 1.0.5'
|
Don't target Ruby <I> for now
|
tristil_minder
|
train
|
5be0a66b6132403cdf8c713ef47501b762d85b02
|
diff --git a/nefertari/view.py b/nefertari/view.py
index <HASH>..<HASH> 100644
--- a/nefertari/view.py
+++ b/nefertari/view.py
@@ -299,9 +299,12 @@ class BaseView(object):
ids = self._json_params[name]
if isinstance(ids, list):
- self._json_params[name] = [_get_object(_id) for _id in ids]
+ self._json_params[name] = []
+ for _id in ids:
+ obj = _id if _id is None else _get_object(_id)
+ self._json_params[name].append(obj)
else:
- self._json_params[name] = _get_object(ids)
+ self._json_params[name] = ids if ids is None else _get_object(ids)
class ESAggregationMixin(object):
diff --git a/tests/test_view.py b/tests/test_view.py
index <HASH>..<HASH> 100644
--- a/tests/test_view.py
+++ b/tests/test_view.py
@@ -539,6 +539,22 @@ class TestBaseView(object):
model.get.assert_called_once_with(idname='1')
@patch('nefertari.view.BaseView._run_init_actions')
+ def test_id2obj_value_none(self, run):
+ model = Mock()
+ model.pk_field.return_value = 'idname'
+ model.get.return_value = 'foo'
+ request = Mock(content_type='', method='', accept=[''], user=None)
+ view = BaseView(
+ context={}, request=request, _json_params={'foo': 'bar'},
+ _query_params={'foo1': 'bar1'})
+ view._json_params['users'] = [None, '1']
+ view._json_params['story'] = None
+ view.id2obj(name='users', model=model)
+ view.id2obj(name='story', model=model)
+ assert view._json_params['users'] == [None, 'foo']
+ assert view._json_params['story'] is None
+
+ @patch('nefertari.view.BaseView._run_init_actions')
def test_id2obj_already_object(self, run):
id_ = Mock()
model = Mock()
|
Skip None in id2obj
|
ramses-tech_nefertari
|
train
|
4ae3e99177da18e57e51680b14c9db99b6bc6bd6
|
diff --git a/pkg/kubelet/dockertools/docker.go b/pkg/kubelet/dockertools/docker.go
index <HASH>..<HASH> 100644
--- a/pkg/kubelet/dockertools/docker.go
+++ b/pkg/kubelet/dockertools/docker.go
@@ -301,7 +301,7 @@ func GetKubeletDockerContainers(client DockerInterface, allContainers bool) (Doc
// TODO(dchen1107): Remove the old separator "--" by end of Oct
if !strings.HasPrefix(container.Names[0], "/"+containerNamePrefix+"_") &&
!strings.HasPrefix(container.Names[0], "/"+containerNamePrefix+"--") {
- glog.Infof("Docker Container: %s is not managed by kubelet.", container.Names[0])
+ glog.V(3).Infof("Docker Container: %s is not managed by kubelet.", container.Names[0])
continue
}
result[DockerID(container.ID)] = container
|
Change a spammy log to V(3)
|
kubernetes_kubernetes
|
train
|
2ac51107ca80d87ce3b9046a4b1f94a8cbb79699
|
diff --git a/pybar/online_monitor.py b/pybar/online_monitor.py
index <HASH>..<HASH> 100644
--- a/pybar/online_monitor.py
+++ b/pybar/online_monitor.py
@@ -133,7 +133,7 @@ class OnlineMonitorApplication(QtGui.QMainWindow):
super(OnlineMonitorApplication, self).closeEvent(event)
# wait for thread
self.worker.stop()
-# self.thread.wait()
+ self.thread.wait(1) # fixes message: QThread: Destroyed while thread is still running
def setup_data_worker_and_start(self, socket_addr):
self.thread = QtCore.QThread() # no parent
|
BUG: fixing QThread existing while closing
|
SiLab-Bonn_pyBAR
|
train
|
cb3adaa435d4618a3d96b4329fc0da478d86721a
|
diff --git a/Tests/Compiler/ExpressionParserTest.php b/Tests/Compiler/ExpressionParserTest.php
index <HASH>..<HASH> 100644
--- a/Tests/Compiler/ExpressionParserTest.php
+++ b/Tests/Compiler/ExpressionParserTest.php
@@ -72,7 +72,7 @@ class ExpressionParserTest extends \PHPUnit_Framework_TestCase
$multLeftNode = $multNode->getChild(OperatorNode::OPERAND_LEFT);
$multRightNode = $multNode->getChild(OperatorNode::OPERAND_RIGHT);
- $dataNode = $plusNode->getChild(OperatorNode::OPERAND_RIGHT);
+ $dataNode = $plusNode->getChild(OperatorNode::OPERAND_RIGHT);
$this->assertSame($this->multiplyOperator, $multNode->getOperator());
$this->assertSame($this->plusOperator, $plusNode->getOperator());
diff --git a/Tests/Compiler/ParserTest.php b/Tests/Compiler/ParserTest.php
index <HASH>..<HASH> 100644
--- a/Tests/Compiler/ParserTest.php
+++ b/Tests/Compiler/ParserTest.php
@@ -2,7 +2,6 @@
namespace Modules\Templating\Compiler;
-use Modules\Templating\Compiler\Exceptions\ParseException;
use Modules\Templating\Environment;
class ParserTest extends \PHPUnit_Framework_TestCase
diff --git a/src/Compiler/Tags/IfTag.php b/src/Compiler/Tags/IfTag.php
index <HASH>..<HASH> 100644
--- a/src/Compiler/Tags/IfTag.php
+++ b/src/Compiler/Tags/IfTag.php
@@ -78,7 +78,7 @@ class IfTag extends Tag
$body = $parser->parseBlock($stream, array('else', 'elseif', 'endif'));
$branchNode->addChild($body, 'body');
- $token = $stream->expectCurrent(Token::TAG);
+ $token = $stream->expectCurrent(Token::TAG);
$tagName = $token->getValue();
if ($tagName === 'else') {
$condition = null;
diff --git a/src/Compiler/Tags/MetaTag.php b/src/Compiler/Tags/MetaTag.php
index <HASH>..<HASH> 100644
--- a/src/Compiler/Tags/MetaTag.php
+++ b/src/Compiler/Tags/MetaTag.php
@@ -14,7 +14,6 @@ use Modules\Templating\Compiler\Nodes\TagNode;
use Modules\Templating\Compiler\Parser;
use Modules\Templating\Compiler\Stream;
use Modules\Templating\Compiler\Tag;
-use Modules\Templating\Compiler\Tokenizer;
abstract class MetaTag extends Tag
{
|
Reformat code and remove unused imports.
|
bugadani_Minty
|
train
|
5a84e4694dcca0e7a69d3707512f62c44cdb1432
|
diff --git a/utwist/_utwist.py b/utwist/_utwist.py
index <HASH>..<HASH> 100644
--- a/utwist/_utwist.py
+++ b/utwist/_utwist.py
@@ -145,22 +145,8 @@ def _twisted_test_sync(callee, call_args, call_kwargs, timeout=120):
# the value with the string representation provided by `failure`.
failure = retval.failure
- if failure.type == TypeError:
- raise failure.type, failure.getTraceback(), None
- elif failure.type == DirtyReactorAggregateError:
- # I really don't understand this yet. failure.getTraceback() returns
- # a string, but somehow a "\n".join(..) is done on it, leading to
- # one charater per line. Does only seem to happen with this specific
- # failure type.
- raise failure.type, [failure.getTraceback()], None
- else:
- try:
- # Sometimes this fails with a TypeError. Probably has problems
- # creating the exception instance.
- raise failure.type, failure.getTraceback(), None
- except TypeError:
- failure.raiseException()
-
+ failure.printTraceback(file=sys.stderr)
+ failure.raiseException()
else:
return retval
|
Improved (or at least changed) failure handling.
|
pydron_utwist
|
train
|
d78c667ba79070ea2520b4d0f9f40406f14035bb
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -27,8 +27,12 @@ module.exports.uninstall = function(packages, options) {
return npm('uninstall', packages, options);
};
-module.exports.view = function(pkg) {
- return npm('view', pkg).then(results => JSON5.parse(results));
+module.exports.view = function(pkg, field) {
+ const args = [pkg];
+ if (field) {
+ args.push(field);
+ }
+ return npm('view', args);
};
function npm(command, args, options) {
@@ -58,7 +62,7 @@ function npm(command, args, options) {
if (!options.ignoreErrors && code !== 0) {
return reject();
}
- return resolve(results);
+ return resolve(results ? results : null);
});
});
}
diff --git a/test/index.js b/test/index.js
index <HASH>..<HASH> 100644
--- a/test/index.js
+++ b/test/index.js
@@ -56,8 +56,20 @@ describe('xenpm-utils', () => {
});
it('can view package info', function() {
- return pm.view('json5').then(results => {
- return expect(results.name).not.to.be.undefined();
+ return pm.view('xenon-css-mode').then(results => {
+ return expect(results).not.to.be.empty();
+ });
+ });
+
+ it('can view a package field', function() {
+ return pm.view('xenon-css-mode', 'xenon').then(results => {
+ return expect(results).not.to.be.empty();
+ });
+ });
+
+ it('returns null when there are no results', function() {
+ return pm.view('left-pad', 'xenon').then(results => {
+ return expect(results).to.be.null();
});
});
|
updated view to return strings since deep objects are not returned and therefore not parseable
|
XenonApp_xenpm-utils
|
train
|
b712a79da6c0d12d07ff2eab73df1f9bbd17f77c
|
diff --git a/tests/test_decoding.py b/tests/test_decoding.py
index <HASH>..<HASH> 100755
--- a/tests/test_decoding.py
+++ b/tests/test_decoding.py
@@ -118,23 +118,19 @@ class TestDecoding(unittest.TestCase):
input_duration = decoder.input_totalframes / decoder.input_samplerate
output_duration = decoder.totalframes() / decoder.output_samplerate
+
if self.test_exact_duration:
self.assertEqual(input_duration, output_duration)
- self.assertEqual(input_duration,
- decoder.uri_duration)
- self.assertEqual(self.source_duration,
- decoder.uri_duration)
+ self.assertEqual(input_duration, decoder.uri_duration)
+ self.assertEqual(self.source_duration, decoder.uri_duration)
self.assertEqual(totalframes, expected_totalframes)
-
else:
self.assertAlmostEqual(input_duration, output_duration,
- places=1)
- self.assertAlmostEqual(input_duration,
- decoder.uri_duration,
- places=1)
- self.assertAlmostEqual(self.source_duration,
- decoder.uri_duration,
- places=1)
+ places=5)
+ self.assertAlmostEqual(input_duration, decoder.uri_duration,
+ places=3)
+ self.assertAlmostEqual(self.source_duration, decoder.uri_duration,
+ delta=.08)
self.assertAlmostEqual(totalframes, expected_totalframes, delta=69)
|
[test] tighten duration tests in test_decoding.py, relax one test from places=1 to delta=<I> for mp3 files to pass the test
|
Parisson_TimeSide
|
train
|
fc3a26cd7328e5e58f0debb890216bc9c64ec990
|
diff --git a/src/Orchestra/Support/Html.php b/src/Orchestra/Support/Html.php
index <HASH>..<HASH> 100644
--- a/src/Orchestra/Support/Html.php
+++ b/src/Orchestra/Support/Html.php
@@ -1,7 +1,5 @@
<?php namespace Orchestra\Support;
-use Illuminate\Support\Facades\Config;
-
class Html {
/**
|
Orchestra\Support\Html doesn't require Config
|
orchestral_support
|
train
|
ab2797ca98040114af5b43b6d92684ac267482a3
|
diff --git a/examples/publishing/publish.rb b/examples/publishing/publish.rb
index <HASH>..<HASH> 100755
--- a/examples/publishing/publish.rb
+++ b/examples/publishing/publish.rb
@@ -5,9 +5,8 @@ $stdout.sync = true
require 'philotic'
require 'philotic/dummy_event'
-Philotic.logger = Logger.new('/dev/null')
+Philotic.logger.level = Logger::WARN
-Philotic::Connection.connect!
@event = Philotic::DummyEvent.new
@event.philotic_firehose = true
diff --git a/lib/philotic/publisher.rb b/lib/philotic/publisher.rb
index <HASH>..<HASH> 100644
--- a/lib/philotic/publisher.rb
+++ b/lib/philotic/publisher.rb
@@ -16,6 +16,10 @@ module Philotic
private
def _publish(payload, message_metadata = {})
+ if config.disable_publish
+ Philotic.log_event_published(:warn, message_metadata, payload, 'attempted to publish a message when publishing is disabled.')
+ return false
+ end
Philotic.connect!
unless Philotic::Connection.connected?
Philotic.log_event_published(:error, message_metadata, payload, 'unable to publish event, not connected to RabbitMQ')
@@ -25,8 +29,6 @@ module Philotic
payload = normalize_payload_times(payload)
- return if config.disable_publish
-
Philotic::Connection.exchange.publish(payload.to_json, message_metadata)
Philotic.log_event_published(:debug, message_metadata, payload, 'published event')
end
|
short circuit publishing earlier when publishing is disabled
|
nkeyes_philotic
|
train
|
a2d3bd126bc2b0e724ba560e46d3e290efafa47f
|
diff --git a/compiler/doc/json.py b/compiler/doc/json.py
index <HASH>..<HASH> 100644
--- a/compiler/doc/json.py
+++ b/compiler/doc/json.py
@@ -20,11 +20,39 @@ class Component(object):
localComma = "" if last == value.name else ","
docText = value.doc.text if value.doc is not None else ""
internal = "true" if (value.doc is not None) and ("@private" in value.doc.text) else "false"
- isProperty = hasattr(value, 'type')
+ category = value.__class__.__name__
+
ref = '"ref": "' + value.ref + '", ' if hasattr(value, 'ref') else ""
- if isProperty:
+ if category == 'Property':
r.append('\t\t\t"%s": { "text": "%s", %s"internal": %s, "type": "%s" }%s' %(value.name, docText, ref, internal, value.type, localComma))
+ elif category == 'Method' and docText:
+ argText = docText.replace(" ", "")
+ argIdx = argText.find("@args(")
+ if argIdx >= 0:
+ argEnd = argText.find(")", argIdx)
+ if argEnd > argIdx:
+ argText = argText[argIdx + 6:argEnd]
+ methodArgs = argText.split(',')
+ argText = '"args": ['
+
+ if methodArgs.count <= 0:
+ argText += "]"
+ continue
+
+ lastArg = methodArgs[-1]
+ for a in methodArgs:
+ elem = a.split(":")
+ if elem.count <= 0:
+ continue
+ argText += '{ "name": "' + elem[0] + '", "type": "' + elem[1] + '" }'
+ if a is not lastArg:
+ argText += ", "
+ argText += "]"
+ else:
+ argText = ""
+ docText = docText.replace(docText[argIdx : docText.find(")", argIdx) + 1], "")
+ r.append('\t\t\t"%s": { "text": "%s", %s"internal": %s }%s' %(value.name, docText, argText, internal, localComma))
else:
r.append('\t\t\t"%s": { "text": "%s", "internal": %s }%s' %(value.name, docText, internal, localComma))
|
Implement functions arguments parsing from comments in json docs.
|
pureqml_qmlcore
|
train
|
04fd4c636c57ede555192d968e61a9a9b8f49517
|
diff --git a/languages/en.php b/languages/en.php
index <HASH>..<HASH> 100644
--- a/languages/en.php
+++ b/languages/en.php
@@ -27,7 +27,7 @@ $english = array(
'interactions:settings:enable_attachments:help' => 'Allow users to attach files to comments',
'interactions:settings:enable_url_preview' => 'Enable URL previews',
'interactions:settings:enable_url_preview:help' => 'Scrape URLs from comment text and add URL previews',
-
+ 'hypeInteractions:usersettings:title' => 'Comments',
/**
* PAGES
*/
diff --git a/lib/settings.php b/lib/settings.php
index <HASH>..<HASH> 100644
--- a/lib/settings.php
+++ b/lib/settings.php
@@ -9,9 +9,15 @@ if (!$handler) {
define('HYPEINTERACTIONS_HANDLER', $handler);
define('HYPEINTERACTIONS_MAX_COMMENT_DEPTH', (int) elgg_get_plugin_setting('max_comment_depth', 'hypeInteractions'));
-define('HYPEINTERACTIONS_COMMENT_FORM_POSITION', elgg_get_plugin_setting('comment_form_position', 'hypeInteractions'));
-define('HYPEINTERACTIONS_COMMENTS_ORDER', elgg_get_plugin_setting('comments_order', 'hypeInteractions'));
-define('HYPEINTERACTIONS_COMMENTS_LOAD_STYLE', elgg_get_plugin_setting('comments_load_style', 'hypeInteractions'));
+
+$position = elgg_get_plugin_user_setting('comment_form_position', 0, 'hypeInteractions') ? : elgg_get_plugin_setting('comment_form_position', 'hypeInteractions');
+define('HYPEINTERACTIONS_COMMENT_FORM_POSITION', $position);
+
+$order = elgg_get_plugin_user_setting('comments_order', 0, 'hypeInteractions') ? : elgg_get_plugin_setting('comments_order', 'hypeInteractions');
+define('HYPEINTERACTIONS_COMMENTS_ORDER', $order);
+
+$style = elgg_get_plugin_user_setting('comments_load_style', 0, 'hypeInteractions') ? : elgg_get_plugin_setting('comments_load_style', 'hypeInteractions');
+define('HYPEINTERACTIONS_COMMENTS_LOAD_STYLE', $style);
$limit = elgg_get_plugin_setting('comments_limit', 'hypeInteractions');
if (!$limit || $limit > 100) {
|
feature(settings): allow users to configure their own comments
settings
|
hypeJunction_hypeInteractions
|
train
|
8ae99f9123148bc18d2ba836747c5b38a4bc008b
|
diff --git a/jenetics/src/main/java/io/jenetics/IntegerChromosome.java b/jenetics/src/main/java/io/jenetics/IntegerChromosome.java
index <HASH>..<HASH> 100644
--- a/jenetics/src/main/java/io/jenetics/IntegerChromosome.java
+++ b/jenetics/src/main/java/io/jenetics/IntegerChromosome.java
@@ -76,64 +76,6 @@ public class IntegerChromosome
super(genes, lengthRange);
}
- /**
- * Create a new random chromosome.
- *
- * @since 4.0
- *
- * @param min the min value of the {@link IntegerGene}s (inclusively).
- * @param max the max value of the {@link IntegerGene}s (inclusively).
- * @param lengthRange the allowed length range of the chromosome.
- * @throws NullPointerException if one of the arguments is {@code null}.
- * @throws IllegalArgumentException if the length is smaller than one
- *
- * @deprecated Use {@link #of(int, int, IntRange)} instead.
- */
- @Deprecated
- public IntegerChromosome(
- final Integer min,
- final Integer max,
- final IntRange lengthRange
- ) {
- this(IntegerGene.seq(min, max, lengthRange), lengthRange);
- _valid = true;
- }
-
- /**
- * Create a new random {@code IntegerChromosome}.
- *
- * @param min the min value of the {@link IntegerGene}s (inclusively).
- * @param max the max value of the {@link IntegerGene}s (inclusively).
- * @param length the length of the chromosome.
- * @throws NullPointerException if one of the arguments is {@code null}.
- * @throws IllegalArgumentException if the {@code length} is smaller than
- * one.
- *
- * @deprecated Use {@link #of(int, int, int)} instead.
- */
- @Deprecated
- public IntegerChromosome(
- final Integer min,
- final Integer max,
- final int length
- ) {
- this(min, max, IntRange.of(length));
- }
-
- /**
- * Create a new random {@code IntegerChromosome} of length one.
- *
- * @param min the minimal value of this chromosome (inclusively).
- * @param max the maximal value of this chromosome (inclusively).
- * @throws NullPointerException if one of the arguments is {@code null}.
- *
- * @deprecated Use {@link #of(int, int)} instead.
- */
- @Deprecated
- public IntegerChromosome(final Integer min, final Integer max) {
- this(min, max, 1);
- }
-
@Override
public IntegerChromosome newInstance(final ISeq<IntegerGene> genes) {
return new IntegerChromosome(genes, lengthRange());
|
#<I>: Remove deprecated methods from 'IntegerChromosome'.
|
jenetics_jenetics
|
train
|
6a14f1a540d1c97d812cfcc2aecb1654028b279f
|
diff --git a/python/ray/autoscaler/local/node_provider.py b/python/ray/autoscaler/local/node_provider.py
index <HASH>..<HASH> 100644
--- a/python/ray/autoscaler/local/node_provider.py
+++ b/python/ray/autoscaler/local/node_provider.py
@@ -28,10 +28,15 @@ class ClusterState(object):
with self.file_lock:
if os.path.exists(self.save_path):
workers = json.loads(open(self.save_path).read())
+ head_config = workers.get(provider_config["head_ip"])
+ if not head_config or head_config.get(
+ "tags", {}).get(TAG_RAY_NODE_TYPE) != "head":
+ workers = {}
+ logger.info("Head IP changed - recreating cluster.")
else:
workers = {}
logger.info("ClusterState: "
- "Loaded cluster state: {}".format(workers))
+ "Loaded cluster state: {}".format(list(workers)))
for worker_ip in provider_config["worker_ips"]:
if worker_ip not in workers:
workers[worker_ip] = {
@@ -55,8 +60,8 @@ class ClusterState(object):
TAG_RAY_NODE_TYPE] == "head"
assert len(workers) == len(provider_config["worker_ips"]) + 1
with open(self.save_path, "w") as f:
- logger.info("ClusterState: "
- "Writing cluster state: {}".format(workers))
+ logger.debug("ClusterState: "
+ "Writing cluster state: {}".format(workers))
f.write(json.dumps(workers))
def get(self):
@@ -74,11 +79,17 @@ class ClusterState(object):
workers[worker_id] = info
with open(self.save_path, "w") as f:
logger.info("ClusterState: "
- "Writing cluster state: {}".format(workers))
+ "Writing cluster state: {}".format(
+ list(workers)))
f.write(json.dumps(workers))
class LocalNodeProvider(NodeProvider):
+ """NodeProvider for private/local clusters.
+
+ `node_id` is overloaded to also be `node_ip` in this class.
+ """
+
def __init__(self, provider_config, cluster_name):
NodeProvider.__init__(self, provider_config, cluster_name)
self.state = ClusterState("/tmp/cluster-{}.lock".format(cluster_name),
diff --git a/python/ray/autoscaler/updater.py b/python/ray/autoscaler/updater.py
index <HASH>..<HASH> 100644
--- a/python/ray/autoscaler/updater.py
+++ b/python/ray/autoscaler/updater.py
@@ -23,6 +23,7 @@ logger = logging.getLogger(__name__)
# How long to wait for a node to start, in seconds
NODE_START_WAIT_S = 300
SSH_CHECK_INTERVAL = 5
+CONTROL_PATH_MAX_LENGTH = 70
def get_default_ssh_options(private_key, connect_timeout, ssh_control_path):
@@ -56,7 +57,7 @@ class NodeUpdater(object):
use_internal_ip=False):
ssh_control_path = "/tmp/{}_ray_ssh_sockets/{}".format(
- getuser(), cluster_name)
+ getuser(), cluster_name)[:CONTROL_PATH_MAX_LENGTH]
self.daemon = True
self.process_runner = process_runner
@@ -197,12 +198,11 @@ class NodeUpdater(object):
m = "{}: Synced {} to {}".format(self.node_id, local_path,
remote_path)
with LogTimer("NodeUpdater {}".format(m)):
- with open("/dev/null", "w") as redirect:
- self.ssh_cmd(
- "mkdir -p {}".format(os.path.dirname(remote_path)),
- redirect=redirect,
- )
- sync_cmd(local_path, remote_path, redirect=redirect)
+ self.ssh_cmd(
+ "mkdir -p {}".format(os.path.dirname(remote_path)),
+ redirect=None,
+ )
+ sync_cmd(local_path, remote_path, redirect=None)
def do_update(self):
self.provider.set_node_tags(self.node_id,
@@ -223,7 +223,6 @@ class NodeUpdater(object):
# Run init commands
self.provider.set_node_tags(self.node_id,
{TAG_RAY_NODE_STATUS: "setting-up"})
-
m = "{}: Initialization commands completed".format(self.node_id)
with LogTimer("NodeUpdater: {}".format(m)):
for cmd in self.initialization_commands:
|
[autoscaler] Small fixes for local cluster usability (#<I>)
|
ray-project_ray
|
train
|
a22c0e74dab72e3f83df33d65e76867ac4cfdab0
|
diff --git a/entity-store/src/main/java/jetbrains/exodus/entitystore/EntityIterableCacheAdapter.java b/entity-store/src/main/java/jetbrains/exodus/entitystore/EntityIterableCacheAdapter.java
index <HASH>..<HASH> 100644
--- a/entity-store/src/main/java/jetbrains/exodus/entitystore/EntityIterableCacheAdapter.java
+++ b/entity-store/src/main/java/jetbrains/exodus/entitystore/EntityIterableCacheAdapter.java
@@ -59,7 +59,11 @@ class EntityIterableCacheAdapter {
if (key.isSticky()) {
return (CachedInstanceIterable) getStickyObject(key);
}
- return parseCachedObject(key, cache.tryKey(key));
+ CachedInstanceIterable cached = parseCachedObject(key, cache.tryKey(key));
+ if (cached == null) {
+ cached = (CachedInstanceIterable) getStickyObjectUnsafe(key);
+ }
+ return cached;
}
@Nullable
@@ -67,7 +71,11 @@ class EntityIterableCacheAdapter {
if (key.isSticky()) {
return (CachedInstanceIterable) getStickyObject(key);
}
- return parseCachedObject(key, cache.getObject(key));
+ CachedInstanceIterable cached = parseCachedObject(key, cache.getObject(key));
+ if (cached == null) {
+ cached = (CachedInstanceIterable) getStickyObjectUnsafe(key);
+ }
+ return cached;
}
@Nullable
@@ -75,7 +83,11 @@ class EntityIterableCacheAdapter {
if (key.isSticky()) {
return getStickyObject(key);
}
- return (Updatable) parseCachedObject(key, cache.getObject(key));
+ Updatable updatable = (Updatable) parseCachedObject(key, cache.getObject(key));
+ if (updatable == null) {
+ updatable = getStickyObjectUnsafe(key);
+ }
+ return updatable;
}
void cacheObject(@NotNull final EntityIterableHandle key, @NotNull final CachedInstanceIterable it) {
|
if EntityIterableHandle is not marked as sticky then check map of sticky objects not only cache
|
JetBrains_xodus
|
train
|
fdd59ef53b6f3878b8745ebf9196c91a0f23f8b0
|
diff --git a/ext_localconf.php b/ext_localconf.php
index <HASH>..<HASH> 100644
--- a/ext_localconf.php
+++ b/ext_localconf.php
@@ -45,7 +45,7 @@ if (!$bootstrapPackageConfiguration['disablePageTsTtContentPreviews']) {
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addPageTSConfig('<INCLUDE_TYPOSCRIPT: source="FILE:EXT:' . $_EXTKEY . '/Configuration/PageTS/Mod/WebLayout/TtContent/preview.txt">');
}
-// Add BackendLayouts BackendLayouts for the BackendLayout DataProvider
+// Add BackendLayouts for the BackendLayout DataProvider
if (!$bootstrapPackageConfiguration['disablePageTsBackendLayouts']) {
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addPageTSConfig('<INCLUDE_TYPOSCRIPT: source="FILE:EXT:' . $_EXTKEY . '/Configuration/PageTS/Mod/WebLayout/BackendLayouts.txt">');
}
|
[BUGFIX] Remove double BackendLayouts in comment (#<I>)
|
benjaminkott_bootstrap_package
|
train
|
9e3f0eea4338b281fad63947c316dfa5d5fa4685
|
diff --git a/lib/lotus/cli.rb b/lib/lotus/cli.rb
index <HASH>..<HASH> 100644
--- a/lib/lotus/cli.rb
+++ b/lib/lotus/cli.rb
@@ -5,6 +5,11 @@ module Lotus
class Cli < Thor
include Thor::Actions
+ desc 'version', 'prints Lotus version'
+ def version
+ puts Lotus::VERSION
+ end
+
desc 'server', 'starts a lotus server'
method_option :port, aliases: '-p', desc: 'The port to run the server on, '
method_option :server, desc: 'choose a specific Rack::Handler, e.g. webrick, thin etc'
|
Add `lotus version` to print version
|
hanami_hanami
|
train
|
c460de7afb2aa3e2dae68ef5244b6a192de46b22
|
diff --git a/src/log.js b/src/log.js
index <HASH>..<HASH> 100644
--- a/src/log.js
+++ b/src/log.js
@@ -100,7 +100,7 @@ module.exports = function construct(config, logProvider, bunyan, PrettyStream, T
};
-function createEventLogger(logger) {
+function createEventLogger(logger, context) {
logger.observers = {};
var enactObservers = function() {
@@ -140,7 +140,7 @@ function createEventLogger(logger) {
// The log method itself is a little special. It does 2 things:
// 1. Calls bunyan info() log level logger.
// 2. Checks for observers to this log event and fires their handlers.
- var log = function() {
+ var log = function log() {
var logObject = parseLogObject.apply(undefined,arguments);
enactObservers.apply(logger, arguments);
logger.info(logObject, logObject.msg);
@@ -192,11 +192,47 @@ function createEventLogger(logger) {
logger.child(logObject);
};
+
// assign aliases:
log.logFatal = log.fatal;
log.log = log;
log.logError = log.error;
log.logWarn = log.warn;
+ // bonus
+
+ log.context = function(funcName, params, object) {
+ return createEventLogger(log, {
+ where: object? object.toString() + '->' +funcName: funcName,
+ params: params
+ })
+ }
+
+ log.rejectWithCode = function(code) {
+ return function rejectWithCodeHandler(err) {
+ var details = {
+ what: code,
+ context: context,
+ err: err
+ };
+ log.error(code, details)
+ return p.reject(details)
+ };
+ }
+
+ log.resolve = function(result) {
+ if (context)
+ log.log(context.what+' resolved.', {context: context, result: result});
+ return result;
+ }
+
+ log.errorReport = function(what, details) {
+ if (context) {
+ details = _.extend(context, details)
+ }
+ log.error(what, details);
+ return details;
+ }
+
return log;
}
\ No newline at end of file
|
Added resolve(), rejectWithCode(), and context()
|
webinverters_win-with-logs
|
train
|
6bcdd6c90a9f6a1d4f61f3d5cc057915a7deaee3
|
diff --git a/test/normalize-ice.js b/test/normalize-ice.js
index <HASH>..<HASH> 100644
--- a/test/normalize-ice.js
+++ b/test/normalize-ice.js
@@ -1,7 +1,7 @@
var test = require('tape');
var detect = require('../detect.js');
var normalize = require('../normalize-ice');
-var RTCPeerConnection;
+var RTCPeerConnection = detect('RTCPeerConnection');
var stunFormatA = [
{ url: 'stun:stun.l.google.com:19302' }
@@ -58,43 +58,40 @@ test('normalizing turn url with embedded username (transport specified)', functi
t.equal(server.credential, 'test');
});
-test('can detect an RTCPeerConnection constructor', function(t) {
- t.plan(1);
- t.ok(RTCPeerConnection = detect('RTCPeerConnection'));
-});
-
-test('can create a connection with a single stun server', function(t) {
- var config;
- var pc;
-
- t.plan(2);
- t.ok(config = { iceServers: [ stunFormatA[0] ].map(normalize) }, 'created config');
- t.ok(pc = new RTCPeerConnection(config), 'created pc');
-});
-
-test('can create a connection with a single turn server', function(t) {
- var config;
- var pc;
-
- t.plan(2);
- t.ok(config = { iceServers: [ turnFormatA[0] ].map(normalize) }, 'created config');
- t.ok(pc = new RTCPeerConnection(config), 'created pc');
-});
-
-test('can create a connection with a single turn server (no port)', function(t) {
- var config;
- var pc;
-
- t.plan(2);
- t.ok(config = { iceServers: [ turnFormatA[1] ].map(normalize) }, 'created config');
- t.ok(pc = new RTCPeerConnection(config), 'created pc');
-});
-
-test('can create a connection with multiple turn servers', function(t) {
- var config;
- var pc;
-
- t.plan(2);
- t.ok(config = { iceServers: turnFormatA.map(normalize) }, 'created config');
- t.ok(pc = new RTCPeerConnection(config), 'created pc');
-});
+if (typeof RTCPeerConnection != 'undefined') {
+ test('can create a connection with a single stun server', function(t) {
+ var config;
+ var pc;
+
+ t.plan(2);
+ t.ok(config = { iceServers: [ stunFormatA[0] ].map(normalize) }, 'created config');
+ t.ok(pc = new RTCPeerConnection(config), 'created pc');
+ });
+
+ test('can create a connection with a single turn server', function(t) {
+ var config;
+ var pc;
+
+ t.plan(2);
+ t.ok(config = { iceServers: [ turnFormatA[0] ].map(normalize) }, 'created config');
+ t.ok(pc = new RTCPeerConnection(config), 'created pc');
+ });
+
+ test('can create a connection with a single turn server (no port)', function(t) {
+ var config;
+ var pc;
+
+ t.plan(2);
+ t.ok(config = { iceServers: [ turnFormatA[1] ].map(normalize) }, 'created config');
+ t.ok(pc = new RTCPeerConnection(config), 'created pc');
+ });
+
+ test('can create a connection with multiple turn servers', function(t) {
+ var config;
+ var pc;
+
+ t.plan(2);
+ t.ok(config = { iceServers: turnFormatA.map(normalize) }, 'created config');
+ t.ok(pc = new RTCPeerConnection(config), 'created pc');
+ });
+}
|
Only run RTCPeerConnection tests in a browser instance
|
rtc-io_rtc-core
|
train
|
2ed597a79dae9935201bade489d1d4b6f394f8bf
|
diff --git a/clldutils/source.py b/clldutils/source.py
index <HASH>..<HASH> 100644
--- a/clldutils/source.py
+++ b/clldutils/source.py
@@ -119,7 +119,12 @@ class Source(OrderedDict):
"""
genre = getattr(self.genre, 'value', self.genre)
pages_at_end = genre in (
- 'book', 'phdthesis', 'mastersthesis', 'misc', 'techreport')
+ 'book',
+ 'phdthesis',
+ 'mastersthesis',
+ 'misc',
+ 'techreport')
+ thesis = genre in ('phdthesis', 'mastersthesis')
if self.get('editor'):
editors = self['editor']
@@ -164,7 +169,7 @@ class Source(OrderedDict):
res.append("In %s" % editors)
for attr in [
- 'school',
+ #'school',
'journal',
'volume' if genre != 'book' else None,
]:
@@ -180,11 +185,18 @@ class Source(OrderedDict):
if self.get('publisher'):
res.append(": ".join(filter(None, [self.get('address'), self['publisher']])))
- if pages_at_end and self.get('pages'):
+ if not thesis and pages_at_end and self.get('pages'):
res.append(self['pages'] + 'pp')
note = self.get('note') or self._genre_note.get(genre)
if note and note not in res:
+ if thesis:
+ joiner = ','
+ if self.get('school'):
+ note += '{0} {1}'.format(joiner, self.get('school'))
+ joiner = ';'
+ if self.get('pages'):
+ note += '{0} {1}pp.'.format(joiner, self.get('pages'))
res.append('(%s)' % note)
return ' '.join(
diff --git a/clldutils/tests/test_source.py b/clldutils/tests/test_source.py
index <HASH>..<HASH> 100644
--- a/clldutils/tests/test_source.py
+++ b/clldutils/tests/test_source.py
@@ -111,7 +111,19 @@ class Tests(unittest.TestCase):
}""",
"Moisik, Scott R. and Esling, John H. 2011. The 'whole larynx' approach "
"to laryngeal features. In Proceedings of the Congress of "
- "Phonetic Sciences (ICPhS XVII), 1406-1409.")
+ "Phonetic Sciences (ICPhS XVII), 1406-1409."),
+ (
+ """@mastersthesis{116989,
+ address = {Ann Arbor},
+ author = {Bryant, Michael G.},
+ pages = {ix+151},
+ publisher = {UMI},
+ school = {University of Texas at Arlington},
+ title = {Aspects of Tirmaga Grammar},
+ year = {1999}
+}""",
+ "Bryant, Michael G. 1999. Aspects of Tirmaga Grammar. Ann Arbor: UMI. "
+ "(MA thesis, University of Texas at Arlington; ix+151pp.)"),
]:
rec = Source.from_bibtex(bib, lowercase=True)
self.assertEqual(rec.text(), txt)
|
closes clld/glottolog#<I>
|
clld_clldutils
|
train
|
83dc98bc77cef0ed8a8a82c427319a451ea37b1f
|
diff --git a/dipper/sources/Monochrom.py b/dipper/sources/Monochrom.py
index <HASH>..<HASH> 100644
--- a/dipper/sources/Monochrom.py
+++ b/dipper/sources/Monochrom.py
@@ -196,7 +196,7 @@ class Monochrom(Source):
if genome_id is None:
genome_id = geno.makeGenomeID(taxon_id) # makes a blank node allways
- geno.addGenome(taxon_id, genome_label)
+ geno.addGenome(taxon_id, genome_label, genome_id)
model.addOWLPropertyClassRestriction(
genome_id, self.globaltt['in taxon'], taxon_id)
@@ -252,12 +252,13 @@ class Monochrom(Source):
maplocclass_id = cclassid+band
maplocclass_label = makeChromLabel(chrom+band, genome_label)
if band is not None and band.strip() != '':
+
region_type_id = self.map_type_of_region(rtype)
model.addClassToGraph(
- maplocclass_id, maplocclass_label,
- region_type_id)
+ maplocclass_id, maplocclass_label, region_type_id)
else:
region_type_id = self.globaltt['chromosome']
+
# add the staining intensity of the band
if re.match(r'g(neg|pos|var)', rtype):
if region_type_id in [
@@ -274,7 +275,7 @@ class Monochrom(Source):
# they don't actually have banding info
LOG.info("feature type %s != chr band", region_type_id)
else:
- LOG.warning('staining type not found: %s', rtype)
+ LOG.info('staining type not found for: %s', rtype)
# get the parent bands, and make them unique
parents = list(self.make_parent_bands(band, set()))
|
include genomi_id param
|
monarch-initiative_dipper
|
train
|
3cb939079782935de21932db7d235eca677d0167
|
diff --git a/osrframework/phonefy/config_phonefy.py b/osrframework/phonefy/config_phonefy.py
index <HASH>..<HASH> 100644
--- a/osrframework/phonefy/config_phonefy.py
+++ b/osrframework/phonefy/config_phonefy.py
@@ -65,7 +65,7 @@ def getPlatformNames(platList = None):
listNames = ['all']
# going through the platList
for r in platList:
- listNames.append(r.platformName)
+ listNames.append(str.lower(r.platformName))
return listNames
def getPlatformsByName(platformNames = ['all']):
|
Now the options for phonefy are never capitalised
|
i3visio_osrframework
|
train
|
46d71a492fa927069fa96963b57c43bf18a74f64
|
diff --git a/lib/sinatra/cache/helpers.rb b/lib/sinatra/cache/helpers.rb
index <HASH>..<HASH> 100644
--- a/lib/sinatra/cache/helpers.rb
+++ b/lib/sinatra/cache/helpers.rb
@@ -662,6 +662,6 @@ module Sinatra
end #/ Cache
- # register(Sinatra::Cache) # not really needed here
+ register(Sinatra::Cache) # support classic apps
end #/ Sinatra
\ No newline at end of file
|
[BUG FIX] Now should support "classic" apps
Thanks to waferbaby for highlighting this.
|
kematzy_sinatra-cache
|
train
|
6184fb10b7a48df4e7c75485ed12b4a389dd3c3c
|
diff --git a/avatar/conf.py b/avatar/conf.py
index <HASH>..<HASH> 100644
--- a/avatar/conf.py
+++ b/avatar/conf.py
@@ -8,7 +8,7 @@ class AvatarConf(AppConf):
DEFAULT_SIZE = 80
RESIZE_METHOD = Image.ANTIALIAS
STORAGE_DIR = 'avatars'
- GRAVATAR_BASE_URL = 'http://www.gravatar.com/avatar/'
+ GRAVATAR_BASE_URL = 'https://www.gravatar.com/avatar/'
GRAVATAR_BACKUP = True
GRAVATAR_DEFAULT = None
DEFAULT_URL = 'avatar/img/default.jpg'
|
Use https to gravatar url
|
grantmcconnaughey_django-avatar
|
train
|
e2f8bae30cc838b53ccc2c5e6b79f179245cb077
|
diff --git a/core/src/main/java/org/mwg/core/task/CoreTaskResultIterator.java b/core/src/main/java/org/mwg/core/task/CoreTaskResultIterator.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/org/mwg/core/task/CoreTaskResultIterator.java
+++ b/core/src/main/java/org/mwg/core/task/CoreTaskResultIterator.java
@@ -2,15 +2,16 @@ package org.mwg.core.task;
import org.mwg.task.TaskResultIterator;
+import java.util.concurrent.atomic.AtomicInteger;
+
class CoreTaskResultIterator<A> implements TaskResultIterator<A> {
private final Object[] _backend;
-
private final int _size;
-
- private int _current = 0;
+ private final AtomicInteger _current;
CoreTaskResultIterator(Object[] p_backend) {
+ _current = new AtomicInteger(0);
if (p_backend != null) {
this._backend = p_backend;
} else {
@@ -20,11 +21,10 @@ class CoreTaskResultIterator<A> implements TaskResultIterator<A> {
}
@Override
- public synchronized A next() {
- if (_current < _size) {
- Object result = _backend[_current];
- _current++;
- return (A) result;
+ public A next() {
+ final int cursor = _current.getAndIncrement();
+ if (cursor < _size) {
+ return (A) _backend[cursor];
} else {
return null;
}
|
optimize the parralel protection by using a CAS instead of a synchronized
|
datathings_greycat
|
train
|
badf6dd817cc7f50cfab6742bee5f6bc0cbb0343
|
diff --git a/datapoint/Forecast.py b/datapoint/Forecast.py
index <HASH>..<HASH> 100644
--- a/datapoint/Forecast.py
+++ b/datapoint/Forecast.py
@@ -38,15 +38,13 @@ class Forecast(object):
# this is the number of seconds through the day
for_total_seconds = d - \
d.replace(hour=0, minute=0, second=0, microsecond=0)
- # python 2.6 does not have timedelta.total_seconds()
- if sys.version_info < (2,7):
- msm = self.timedelta_total_seconds(for_total_seconds) / 60
- else:
- # In the example time,
- # for_total_seconds.total_seconds() = 61528 + 0.337439
- # This is the number of seconds after midnight
- # msm is then the number of minutes after midnight
- msm = for_total_seconds.total_seconds() / 60
+
+ # In the example time,
+ # for_total_seconds.total_seconds() = 61528 + 0.337439
+ # This is the number of seconds after midnight
+ # msm is then the number of minutes after midnight
+ msm = for_total_seconds.total_seconds() / 60
+
# If the date now and the date in the forecast are the same, proceed
if self.days[0].date.strftime("%Y-%m-%dZ") == d.strftime("%Y-%m-%dZ"):
# We have determined that the date in the forecast and the date now
|
Remove py<I> compatibility code from Forecast.py
|
jacobtomlinson_datapoint-python
|
train
|
2be327dca9ea2b35bbc40684b65e27e16dcc64fb
|
diff --git a/calendar/export_execute.php b/calendar/export_execute.php
index <HASH>..<HASH> 100644
--- a/calendar/export_execute.php
+++ b/calendar/export_execute.php
@@ -189,10 +189,14 @@ foreach($events as $event) {
$ev->add_property('class', 'PUBLIC'); // PUBLIC / PRIVATE / CONFIDENTIAL
$ev->add_property('last-modified', Bennu::timestamp_to_datetime($event->timemodified));
$ev->add_property('dtstamp', Bennu::timestamp_to_datetime()); // now
- $ev->add_property('dtstart', Bennu::timestamp_to_datetime($event->timestart)); // when event starts
if ($event->timeduration > 0) {
//dtend is better than duration, because it works in Microsoft Outlook and works better in Korganizer
+ $ev->add_property('dtstart', Bennu::timestamp_to_datetime($event->timestart)); // when event starts.
$ev->add_property('dtend', Bennu::timestamp_to_datetime($event->timestart + $event->timeduration));
+ } else {
+ // When no duration is present, ie an all day event, VALUE should be date instead of time and dtend = dtstart + 1 day
+ $ev->add_property('dtstart', Bennu::timestamp_to_date($event->timestart), array('value' => 'DATE')); // All day event.
+ $ev->add_property('dtend', Bennu::timestamp_to_date($event->timestart + 86400), array('value' => 'DATE')); // All day event.
}
if ($event->courseid != 0) {
$coursecontext = context_course::instance($event->courseid);
diff --git a/lib/bennu/bennu.class.php b/lib/bennu/bennu.class.php
index <HASH>..<HASH> 100644
--- a/lib/bennu/bennu.class.php
+++ b/lib/bennu/bennu.class.php
@@ -20,6 +20,14 @@ class Bennu {
return gmstrftime('%Y%m%dT%H%M%SZ', $t);
}
+ static function timestamp_to_date($t = NULL) {
+ if($t === NULL) {
+ $t = time();
+ }
+ return strftime('%Y%m%d', $t);
+ }
+
+
static function generate_guid() {
// Implemented as per the Network Working Group draft on UUIDs and GUIDs
|
MDL-<I> core_calendar: Fix ical export for events with no duration
|
moodle_moodle
|
train
|
1834e545b4bbdacfebe8d56971b5ce4f29c5bcb6
|
diff --git a/libraries/lithium/tests/cases/data/ConnectionsTest.php b/libraries/lithium/tests/cases/data/ConnectionsTest.php
index <HASH>..<HASH> 100644
--- a/libraries/lithium/tests/cases/data/ConnectionsTest.php
+++ b/libraries/lithium/tests/cases/data/ConnectionsTest.php
@@ -43,6 +43,9 @@ class ConnectionsTest extends \lithium\test\Unit {
$expected = $this->config + array('type' => 'database');
$this->assertEqual($expected, $result);
+ $message = 'Your PHP was not compiled with the MySQL extension';
+ $this->skipIf(!extension_loaded('mysql'), $message);
+
$this->expectException('/mysql_get_server_info/');
$this->expectException('/mysql_select_db/');
$this->expectException('/mysql_connect/');
@@ -64,6 +67,9 @@ class ConnectionsTest extends \lithium\test\Unit {
Connections::add('conn-test-2', $this->config);
$this->assertEqual(array('conn-test', 'conn-test-2'), Connections::get());
+ $message = 'Your PHP was not compiled with the MySQL extension';
+ $this->skipIf(!extension_loaded('mysql'), $message);
+
$expected = $this->config + array('type' => 'database', 'filters' => array());
$this->assertEqual($expected, Connections::get('conn-test', array('config' => true)));
@@ -77,6 +83,9 @@ class ConnectionsTest extends \lithium\test\Unit {
Connections::add('conn-test', $this->config);
Connections::add('conn-test-2', $this->config);
+ $message = 'Your PHP was not compiled with the MySQL extension';
+ $this->skipIf(!extension_loaded('mysql'), $message);
+
$this->expectException('/mysql_get_server_info/');
$this->expectException('/mysql_select_db/');
$this->expectException('/mysql_connect/');
|
Adding skips to `ConnectionsTest` to account for PHP installations that
do not include any MySQL extension.
|
UnionOfRAD_framework
|
train
|
95128b08cf63056f02ba28bf10b63a65a43a6519
|
diff --git a/h2network/src/test/java/org/h2gis/network/graph_creator/ST_ShortestPathLengthTest.java b/h2network/src/test/java/org/h2gis/network/graph_creator/ST_ShortestPathLengthTest.java
index <HASH>..<HASH> 100644
--- a/h2network/src/test/java/org/h2gis/network/graph_creator/ST_ShortestPathLengthTest.java
+++ b/h2network/src/test/java/org/h2gis/network/graph_creator/ST_ShortestPathLengthTest.java
@@ -643,15 +643,37 @@ public class ST_ShortestPathLengthTest {
manyToManySTDT(U, W, SOURCE_TABLE, DEST_TABLE, distances);
}
+ @Test
+ public void manyToManyWDOSTSTSquare() throws Exception {
+ // SELECT * FROM ST_ShortestPathLength('CORMEN_EDGES_ALL',
+ // 'directed - edge_orientation', 'weight', 'source_table', 'source_table')
+ final double[][] distances = {{0.0, 8.0, 5.0},
+ {11.0, 0.0, 2.0},
+ {9.0, 3.0, 0.0}};
+ manyToManySTDT(DO, W, SOURCE_TABLE, SOURCE_TABLE, distances, 9);
+ }
private void manyToManySTDT(String orientation, String weight,
String sourceTable,
- String destinationTable, double[][] distances) throws SQLException {
+ String destinationTable,
+ double[][] distances, int distancesSize) throws SQLException {
ResultSet rs = st.executeQuery(
"SELECT * FROM ST_ShortestPathLength('CORMEN_EDGES_ALL', "
+ orientation + ((weight != null) ? ", " + weight : "")
+ ", " + sourceTable + ", " + destinationTable + ")");
- checkManyToMany(rs, distances, 6);
+ checkManyToMany(rs, distances, distancesSize);
+ }
+
+ private void manyToManySTDT(String orientation, String weight,
+ String sourceTable,
+ String destinationTable, double[][] distances) throws SQLException {
+ manyToManySTDT(orientation, weight, sourceTable, destinationTable, distances, 6);
+ }
+
+ private void manyToManySTDT(String orientation,
+ String sourceTable,
+ String destinationTable, double[][] distances) throws SQLException {
+ manyToManySTDT(orientation, null, sourceTable, destinationTable, distances);
}
@Test(expected = IllegalArgumentException.class)
@@ -690,12 +712,6 @@ public class ST_ShortestPathLengthTest {
}
}
- private void manyToManySTDT(String orientation,
- String sourceTable,
- String destinationTable, double[][] distances) throws SQLException {
- manyToManySTDT(orientation, null, sourceTable, destinationTable, distances);
- }
-
// ************************* One-to-Several ***************************************
@Test
|
Add unit test for same table used as ST,DT (square)
|
orbisgis_h2gis
|
train
|
fe0cf6f0b2a8201b0c38b73fd80ab076c200d344
|
diff --git a/lib/imageconf.py b/lib/imageconf.py
index <HASH>..<HASH> 100644
--- a/lib/imageconf.py
+++ b/lib/imageconf.py
@@ -53,6 +53,7 @@ class ImageConfig:
self.indices = None
self.title = 'image'
self.style = 'image'
+ self.highlight_areas = []
self.ncontour_levels = None
self.contour_levels = None
self.contour_labels = True
diff --git a/lib/imageframe.py b/lib/imageframe.py
index <HASH>..<HASH> 100644
--- a/lib/imageframe.py
+++ b/lib/imageframe.py
@@ -16,17 +16,30 @@ from baseframe import BaseFrame
from colors import rgb2hex
from utils import Closure, LabelEntry
+CURSOR_MENULABELS = {'zoom': ('Zoom to Rectangle\tCtrl+B',
+ 'Left-Drag to zoom to rectangular box'),
+ 'lasso': ('Select Points\tCtrl+X',
+ 'Left-Drag to select points freehand'),
+ 'prof': ('Select Line Profile\tCtrl+K',
+ 'Left-Drag to select like for profile')}
+
class ImageFrame(BaseFrame):
"""
MatPlotlib Image Display ons a wx.Frame, using ImagePanel
"""
+
def __init__(self, parent=None, size=None,
config_on_frame=True, lasso_callback=None,
- show_xsections=True,
+ show_xsections=True, cursor_labels=None,
output_title='Image', **kws):
if size is None: size = (550, 450)
self.config_on_frame = config_on_frame
self.lasso_callback = lasso_callback
+ self.cursor_menulabels = {}
+ self.cursor_menulabels.update(CURSOR_MENULABELS)
+ if cursor_labels is not None:
+ self.cursor_menulabels.update(cursor_labels)
+
BaseFrame.__init__(self, parent=parent,
title = 'Image Display Frame',
output_title=output_title,
@@ -77,12 +90,13 @@ class ImageFrame(BaseFrame):
m.Append(mids.FLIP_H, 'Flip Left/Right\tCtrl+F', '')
# m.Append(mids.FLIP_O, 'Flip to Original', '')
m.AppendSeparator()
- m.AppendRadioItem(mids.CUR_ZOOM, 'Cursor Mode: Zoom to Box\tCtrl+B',
- 'Left-Drag Cursor to zoom to box')
- m.AppendRadioItem(mids.CUR_PROF, 'Cursor Mode: Profile\tCtrl+K',
- 'Left-Drag Cursor to select cut for profile')
- m.AppendRadioItem(mids.CUR_LASSO, 'Cursor Mode: Lasso\tCtrl+N',
- 'Left-Drag Cursor to select points')
+ m.Append(wx.NewId(), 'Cursor Modes : ',
+ 'Action taken on with Left-Click and Left-Drag')
+
+ clabs = self.cursor_menulabels
+ m.AppendRadioItem(mids.CUR_ZOOM, clabs['zoom'][0], clabs['zoom'][1])
+ m.AppendRadioItem(mids.CUR_LASSO, clabs['lasso'][0], clabs['lasso'][1])
+ m.AppendRadioItem(mids.CUR_PROF, clabs['prof'][0], clabs['prof'][1])
m.AppendSeparator()
self.Bind(wx.EVT_MENU, self.onFlip, id=mids.FLIP_H)
self.Bind(wx.EVT_MENU, self.onFlip, id=mids.FLIP_V)
@@ -416,6 +430,13 @@ class ImageFrame(BaseFrame):
conf.contour.set_cmap(getattr(colormap, xname))
if hasattr(conf, 'image'):
conf.image.set_cmap(conf.cmap)
+ if hasattr(conf, 'highlight_areas'):
+ rgb = (int(i*200)^255 for i in cmap._lut[0][:3])
+ col = '#%02x%02x%02x' % tuple(rgb)
+ for area in conf.highlight_areas:
+ for lin in area.collections:
+ lin.set_color(col)
+
self.redraw_cmap()
def redraw_cmap(self):
diff --git a/lib/imagepanel.py b/lib/imagepanel.py
index <HASH>..<HASH> 100644
--- a/lib/imagepanel.py
+++ b/lib/imagepanel.py
@@ -71,6 +71,7 @@ class ImagePanel(BasePanel):
conf.rot, conf.log_scale = False, False
conf.flip_ud, conf.flip_lr = False, False
conf.auto_intensity, conf.interp = True, 'nearest'
+ conf.highlight_areas = []
self.data_shape = data.shape
self.data_range = [0, data.shape[1], 0, data.shape[0]]
if x is not None:
@@ -136,6 +137,24 @@ class ImagePanel(BasePanel):
if hasattr(self.data_callback, '__call__'):
self.data_callback(data, x=x, y=y, **kws)
+ def add_highlight_area(mask):
+ """add a highlighted area -- outline an arbitrarily shape --
+ as if drawn from a Lasso event.
+
+ This takes a mask, which should be a boolean array of the
+ same shape as the image.
+ """
+ patch = mask * ones(mask.shape) * 0.9
+
+ cmap = self.conf.cmap
+ area = self.axes.contour(patch, cmap=cmap, levels=[0.8])
+
+ self.conf.highlight_areas.append(area)
+ rgb = (int(i*200)^255 for i in cmap._lut[0][:3])
+ col = '#%02x%02x%02x' % tuple(rgb)
+ for l in area.collections:
+ l.set_color(col)
+
def set_viewlimits(self, axes=None, autoscale=False):
""" update xy limits of a plot"""
if axes is None:
|
add 'highlight area' to images, as for patches defined with Lasso
|
newville_wxmplot
|
train
|
1b40b60e1f80e61053ce50fb5ae4a964b7eeee79
|
diff --git a/frontend/components/Home.js b/frontend/components/Home.js
index <HASH>..<HASH> 100644
--- a/frontend/components/Home.js
+++ b/frontend/components/Home.js
@@ -273,18 +273,24 @@ class Home extends React.Component {
<div className='footer ui basic center aligned segment'>
See an issue or want to add to this website? Fork it or create an issue on
- <a href='https://github.com/ryanhugh/neusearch'>GitHub</a>.
+ <a href='https://github.com/ryanhugh/neusearch'>
+ GitHub
+ </a>.
</div>
<div className='ui divider' />
<div className='footer ui basic center aligned segment'>
- Made with
+ Made with
<i className='rocket circular small icon' />
- by
- <a href='http://github.com/ryanhugh'>Ryan Hughes</a>
- and UI borrowed from
- <a href='https://github.com/2factorauth/twofactorauth'>Two Factor Authenticaton</a>.
+ by
+ <a href='http://github.com/ryanhugh'>
+ Ryan Hughes
+ </a>
+ and UI borrowed from
+ <a href='https://github.com/2factorauth/twofactorauth'>
+ Two Factor Authenticaton
+ </a>.
</div>
</div>
);
|
fixed spacing in the footer of the page.
|
ryanhugh_searchneu
|
train
|
5d2504df0a29a5d15dd7f9469668f007d642ad6e
|
diff --git a/py/execnet/gateway_base.py b/py/execnet/gateway_base.py
index <HASH>..<HASH> 100644
--- a/py/execnet/gateway_base.py
+++ b/py/execnet/gateway_base.py
@@ -223,7 +223,7 @@ def _setupmessages():
class CHANNEL_LAST_MESSAGE(Message):
def received(self, gateway):
- gateway._channelfactory._local_last_message(self.channelid)
+ gateway._channelfactory._local_close(self.channelid, sendonly=True)
classes = [CHANNEL_OPEN, CHANNEL_NEW, CHANNEL_DATA,
CHANNEL_CLOSE, CHANNEL_CLOSE_ERROR, CHANNEL_LAST_MESSAGE]
@@ -269,31 +269,36 @@ class Channel(object):
self._remoteerrors = []
def setcallback(self, callback, endmarker=NO_ENDMARKER_WANTED):
- items = self._items
- lock = self.gateway._channelfactory._receivelock
- lock.acquire()
+ # we first execute the callback on all already received
+ # items. We need to hold the receivelock to prevent
+ # race conditions with newly arriving items.
+ # after having cleared the queue we register
+ # the callback only if the channel is not closed already.
+ _callbacks = self.gateway._channelfactory._callbacks
+ _receivelock = self.gateway._channelfactory._receivelock
+ _receivelock.acquire()
try:
- _callbacks = self.gateway._channelfactory._callbacks
- dictvalue = (callback, endmarker)
- if _callbacks.setdefault(self.id, dictvalue) != dictvalue:
+ if self._items is None:
raise IOError("%r has callback already registered" %(self,))
+ items = self._items
self._items = None
while 1:
try:
olditem = items.get(block=False)
except queue.Empty:
+ if not (self._closed or self._receiveclosed.isSet()):
+ _callbacks[self.id] = (callback, endmarker)
break
else:
if olditem is ENDMARKER:
- items.put(olditem)
+ items.put(olditem) # for other receivers
+ if endmarker is not NO_ENDMARKER_WANTED:
+ callback(endmarker)
break
else:
callback(olditem)
- if self._closed or self._receiveclosed.isSet():
- # no need to keep a callback
- self.gateway._channelfactory._close_callback(self.id)
finally:
- lock.release()
+ _receivelock.release()
def __repr__(self):
flag = self.isclosed() and "closed" or "open"
@@ -462,9 +467,6 @@ class ChannelFactory(object):
del self._channels[id]
except KeyError:
pass
- self._close_callback(id)
-
- def _close_callback(self, id):
try:
callback, endmarker = self._callbacks.pop(id)
except KeyError:
@@ -473,7 +475,7 @@ class ChannelFactory(object):
if endmarker is not NO_ENDMARKER_WANTED:
callback(endmarker)
- def _local_close(self, id, remoteerror=None):
+ def _local_close(self, id, remoteerror=None, sendonly=False):
channel = self._channels.get(id)
if channel is None:
# channel already in "deleted" state
@@ -483,20 +485,8 @@ class ChannelFactory(object):
# state transition to "closed" state
if remoteerror:
channel._remoteerrors.append(remoteerror)
- channel._closed = True # --> "closed"
- channel._receiveclosed.set()
- queue = channel._items
- if queue is not None:
- queue.put(ENDMARKER)
- self._no_longer_opened(id)
-
- def _local_last_message(self, id):
- channel = self._channels.get(id)
- if channel is None:
- # channel already in "deleted" state
- pass
- else:
- # state transition: if "opened", change to "sendonly"
+ if not sendonly: # otherwise #--> "sendonly"
+ channel._closed = True # --> "closed"
channel._receiveclosed.set()
queue = channel._items
if queue is not None:
@@ -505,21 +495,17 @@ class ChannelFactory(object):
def _local_receive(self, id, data):
# executes in receiver thread
- self._receivelock.acquire()
try:
- try:
- callback, endmarker = self._callbacks[id]
- except KeyError:
- channel = self._channels.get(id)
- queue = channel and channel._items
- if queue is None:
- pass # drop data
- else:
- queue.put(data)
+ callback, endmarker = self._callbacks[id]
+ except KeyError:
+ channel = self._channels.get(id)
+ queue = channel and channel._items
+ if queue is None:
+ pass # drop data
else:
- callback(data) # even if channel may be already closed
- finally:
- self._receivelock.release()
+ queue.put(data)
+ else:
+ callback(data) # even if channel may be already closed
def _finished_receiving(self):
self._writelock.acquire()
@@ -528,9 +514,9 @@ class ChannelFactory(object):
finally:
self._writelock.release()
for id in list(self._channels):
- self._local_last_message(id)
+ self._local_close(id, sendonly=True)
for id in list(self._callbacks):
- self._close_callback(id)
+ self._no_longer_opened(id)
class ChannelFile(object):
def __init__(self, channel, proxyclose=True):
@@ -648,7 +634,12 @@ class BaseGateway(object):
try:
msg = Message.readfrom(self._io)
self._trace("received <- %r" % msg)
- msg.received(self)
+ _receivelock = self._channelfactory._receivelock
+ _receivelock.acquire()
+ try:
+ msg.received(self)
+ finally:
+ _receivelock.release()
except sysex:
break
except EOFError:
@@ -736,7 +727,7 @@ class BaseGateway(object):
finally:
close()
self._trace("execution finished:", repr(source)[:50])
- except (KeyboardInterrupt, SystemExit):
+ except sysex:
pass
except self._StopExecLoop:
channel.close()
|
* simplify lock acquiration for received messages, review code
* try to fix seldomly occuring race condition with setcallback/receive and closing of channel
--HG--
branch : trunk
|
pytest-dev_pytest
|
train
|
7cfe193d12ab1539050c3c7f1563d6df6e163778
|
diff --git a/Brocfile.js b/Brocfile.js
index <HASH>..<HASH> 100644
--- a/Brocfile.js
+++ b/Brocfile.js
@@ -10,8 +10,6 @@ var app = new EmberAddon();
app.import('vendor/styles/layout.css');
app.import('vendor/styles/theme.css');
-app.import(app.bowerDirectory + '/velocity/velocity.min.js');
-
// Use `app.import` to add additional libraries to the generated
// output files.
//
|
Velocity removed as a dependency
|
sir-dunxalot_ember-flash-messages
|
train
|
58768059b7561389ff0d5d20c558d1d1878324b2
|
diff --git a/src/adafruit_blinka/microcontroller/bcm283x/pin.py b/src/adafruit_blinka/microcontroller/bcm283x/pin.py
index <HASH>..<HASH> 100644
--- a/src/adafruit_blinka/microcontroller/bcm283x/pin.py
+++ b/src/adafruit_blinka/microcontroller/bcm283x/pin.py
@@ -142,6 +142,10 @@ spiPorts = (
(0, SCLK, MOSI, MISO),
(1, SCLK_1, MOSI_1, MISO_1),
(2, SCLK_2, MOSI_2, MISO_2),
+ (3, D3, D2, D1), #SPI3 on Pi4/CM4
+ (4, D7, D6, D5), #SPI4 on Pi4/CM4
+ (5, D15, D14, D13), #SPI5 on Pi4/CM4
+
)
# ordered as uartId, txId, rxId
|
Add additional SPI ports for BCM<I>
Currently the additional SPI ports on the Pi4 or CM4 are not usable in Blinka without doing this change manually.
SPI6 uses the same pins as the default SPI1 pins.
|
adafruit_Adafruit_Blinka
|
train
|
8bb90aa70280b4189e3ac8a3ab60a156091c04aa
|
diff --git a/docs/release_notes.rst b/docs/release_notes.rst
index <HASH>..<HASH> 100644
--- a/docs/release_notes.rst
+++ b/docs/release_notes.rst
@@ -5,6 +5,7 @@ Release Notes
Version 0.14.0, UNRELEASED
--------------------------
+* (2018-12-04) Add support for string types within computations (inspector, computation panel).
* (2018-11-15) Make menu item for Assign Variable Reference be named sensibly.
* (2018-10-29) Fix bug where line plot grid lines were not consistently drawn.
* (2018-10-15) Introduce composite line plot display items (all inputs must have same calibration units).
diff --git a/nion/swift/ComputationPanel.py b/nion/swift/ComputationPanel.py
index <HASH>..<HASH> 100644
--- a/nion/swift/ComputationPanel.py
+++ b/nion/swift/ComputationPanel.py
@@ -498,7 +498,7 @@ class ComputationPanelSection:
name_text_edit = ui.create_line_edit_widget()
name_text_edit.bind_text(ChangeVariableBinding(document_controller, computation, variable, "name"))
- type_items = [("boolean", _("Boolean")), ("integral", _("Integer")), ("real", _("Real")), ("data_source", _("Data Source")), ("graphic", _("Graphic"))]
+ type_items = [("boolean", _("Boolean")), ("integral", _("Integer")), ("real", _("Real")), ("string", _("String")),("data_source", _("Data Source")), ("graphic", _("Graphic"))]
type_combo_box = ui.create_combo_box_widget(items=type_items, item_getter=operator.itemgetter(1))
remove_button = ui.create_push_button_widget(_("X"))
@@ -602,6 +602,41 @@ class ComputationPanelSection:
return column
+ def make_string_row(ui, variable: Symbolic.ComputationVariable, converter, on_change_type_fn, on_remove_fn):
+ name_type_row = make_name_type_row(ui, variable, on_change_type_fn, on_remove_fn)
+
+ value_text_edit = ui.create_line_edit_widget()
+
+ value_default_text_edit = ui.create_line_edit_widget()
+
+ value_row = ui.create_row_widget()
+ value_row.add_spacing(8)
+ value_row.add(value_text_edit)
+ value_row.add_spacing(4)
+ value_row.add(value_default_text_edit)
+ value_row.add_stretch()
+
+ label_text_edit = ui.create_line_edit_widget()
+ label_text_edit.bind_text(ChangeVariableBinding(document_controller, computation, variable, "label"))
+
+ display_row = ui.create_row_widget()
+ display_row.add_spacing(8)
+ display_row.add(label_text_edit)
+ display_row.add_stretch()
+
+ column = ui.create_column_widget()
+ column.add(make_label_row(ui, _("Variable Name / Type")))
+ column.add(name_type_row)
+ column.add(make_label_row(ui, _("Value / Default")))
+ column.add(value_row)
+ column.add(make_label_row(ui, _("Label")))
+ column.add(display_row)
+
+ value_text_edit.bind_text(ChangeVariableBinding(document_controller, computation, variable, "value", converter=converter))
+ value_default_text_edit.bind_text(ChangeVariableBinding(document_controller, computation, variable, "value_default", converter=converter))
+
+ return column
+
def make_specifier_row(ui, variable: Symbolic.ComputationVariable, on_change_type_fn, on_remove_fn, *, include_secondary=False):
column = ui.create_column_widget()
@@ -669,6 +704,8 @@ class ComputationPanelSection:
stack.add(make_number_row(ui, variable, Converter.IntegerToStringConverter(), change_type, on_remove))
elif variable_type == "real":
stack.add(make_number_row(ui, variable, Converter.FloatToStringConverter(), change_type, on_remove))
+ elif variable_type == "string":
+ stack.add(make_string_row(ui, variable, None, change_type, on_remove))
elif variable_type == "data_source":
stack.add(make_specifier_row(ui, variable, change_type, on_remove, include_secondary=True))
elif variable_type == "graphic":
diff --git a/nion/swift/Inspector.py b/nion/swift/Inspector.py
index <HASH>..<HASH> 100644
--- a/nion/swift/Inspector.py
+++ b/nion/swift/Inspector.py
@@ -2485,6 +2485,10 @@ class VariableWidget(Widgets.CompositeWidgetBase):
widget, closeables = make_image_chooser(document_controller, computation, variable)
self.content_widget.add(widget)
self.closeables.extend(closeables)
+ elif variable.variable_type == "string":
+ widget, closeables = make_field(document_controller, computation, variable, None)
+ self.content_widget.add(widget)
+ self.closeables.extend(closeables)
class ComputationInspectorSection(InspectorSection):
|
Added UI for string variables to computation panel and inspector.
|
nion-software_nionswift
|
train
|
4fbec15b8ab3d14f60a3fc5186868475db990b7b
|
diff --git a/lib/ohm.rb b/lib/ohm.rb
index <HASH>..<HASH> 100644
--- a/lib/ohm.rb
+++ b/lib/ohm.rb
@@ -785,6 +785,7 @@ module Ohm
def delete_from_indices
db.smembers(key(:_indices)).each do |index|
db.srem(index, id)
+ db.srem(key(:_indices), index)
end
end
diff --git a/test/model_test.rb b/test/model_test.rb
index <HASH>..<HASH> 100644
--- a/test/model_test.rb
+++ b/test/model_test.rb
@@ -259,20 +259,18 @@ class TestRedis < Test::Unit::TestCase
end
context "Delete" do
- class ModelToBeDeleted < Ohm::Model
- attribute :name
- set :foos
- list :bars
- end
+ should "delete an existing model" do
+ class ModelToBeDeleted < Ohm::Model
+ attribute :name
+ set :foos
+ list :bars
+ end
- setup do
@model = ModelToBeDeleted.create(:name => "Lorem")
@model.foos << "foo"
@model.bars << "bar"
- end
- should "delete an existing model" do
id = @model.id
@model.delete
@@ -284,6 +282,23 @@ class TestRedis < Test::Unit::TestCase
assert ModelToBeDeleted.all.empty?
end
+
+ should "be no leftover keys" do
+ class ::Foo < Ohm::Model
+ attribute :name
+ index :name
+ end
+
+ assert_equal [], Ohm.redis.keys("*")
+
+ Foo.create(name: "Bar")
+
+ assert_equal ["Foo:1:_indices", "Foo:1:name", "Foo:all", "Foo:id", "Foo:name:QmFy"], Ohm.redis.keys("*").sort
+
+ Foo[1].delete
+
+ assert_equal ["Foo:id"], Ohm.redis.keys("*")
+ end
end
context "Listing" do
|
Fix that index keys were not removed from the indexes set.
|
soveran_ohm
|
train
|
4d05c65b0d845e822330415aaf3a135f0ba83bcc
|
diff --git a/lib/consumerGroup.js b/lib/consumerGroup.js
index <HASH>..<HASH> 100644
--- a/lib/consumerGroup.js
+++ b/lib/consumerGroup.js
@@ -396,6 +396,7 @@ ConsumerGroup.prototype.handleSyncGroup = function (syncGroupResponse, callback)
callback
);
} else {
+ self.topicPayloads = [];
// no partitions assigned
callback(null, false);
}
|
Clear topic payload if no partitions are assigned (#<I>)
This handles case where more consumers join than their are partitions.
when this occurs, one of the consumers may receive no partitions, and
this topicPayloads variable still contained reference to their previous
partition assignment.
|
SOHU-Co_kafka-node
|
train
|
de7f9c3ceb586ae269362f581dfb77c3e5a237f8
|
diff --git a/molgenis-omx-dataexplorer/src/main/resources/js/dataexplorer-wizard.js b/molgenis-omx-dataexplorer/src/main/resources/js/dataexplorer-wizard.js
index <HASH>..<HASH> 100644
--- a/molgenis-omx-dataexplorer/src/main/resources/js/dataexplorer-wizard.js
+++ b/molgenis-omx-dataexplorer/src/main/resources/js/dataexplorer-wizard.js
@@ -93,18 +93,16 @@
$.each(compoundAttributes, function(i, compoundAttribute) {
var tabId = compoundAttribute.name + '-tab';
var label = compoundAttribute.label || compoundAttribute.name;
- listItems.push('<li' + (i === 0 ? ' class="active"' : '') + '><a href="#' + tabId + '" data-toggle="tab">' + label + '</a></li>');
+ listItems.push('<li><a href="#' + tabId + '" data-toggle="tab">' + label + '</a></li>');
var pane = $('<div class="tab-pane' + (i === 0 ? ' active"' : '') + '" id="' + tabId + '">');
var paneContainer = $('<div class="well"></div>');
- var form = $('<form class="form-horizontal"></form>');
- paneContainer.append(form);
- pane.append(paneContainer);
$.each(compoundAttribute.attributes, function(i, attribute) {
if(attribute.fieldType !== 'COMPOUND') {
paneContainer.append(molgenis.dataexplorer.createFilterControls(attribute, attributeFilters[attribute.href], true));
}
});
+ pane.append(paneContainer);
paneItems.push(pane);
});
@@ -123,19 +121,24 @@
var $current = index+1;
// If it's the last tab then hide the last button and show the finish instead
- if($total == 1) {
+ if($total === 1) {
wizard.find('.pager').hide();
} else if($current === 1) {
wizard.find('.pager .previous').hide();
wizard.find('.pager .next').show();
} else if($current > 1 && $current < $total) {
+ wizard.find('.pager').show();
+ } else if($current === $total && $current>1) {
wizard.find('.pager .previous').show();
- wizard.find('.pager .next').show();
+ wizard.find('.pager .next').hide();
} else {
- wizard.find('.pager .previous').show();
+ wizard.find('.pager .previous').hide();
wizard.find('.pager .next').hide();
}
- }
+ },
+ onNext: function(tab, navigation, index) {
+ // BugFix: Don't remove this empty function
+ }
});
}
})($, window.top.molgenis = window.top.molgenis || {});
\ No newline at end of file
|
Fixed previous button on start wizard.
Fixed the next button
|
molgenis_molgenis
|
train
|
1ebea2d8cec276b50ee78352dd7f5e20b81320ac
|
diff --git a/lib/ponder.rb b/lib/ponder.rb
index <HASH>..<HASH> 100644
--- a/lib/ponder.rb
+++ b/lib/ponder.rb
@@ -14,9 +14,9 @@ module Ponder
require 'ponder/logger/blind_io'
if RUBY_VERSION < '1.9'
- require 'ruby/1.8/string'
require 'ponder/logger/twoflogger18'
else
require 'ponder/logger/twoflogger'
end
end
+
|
removed requiring (already removed) string addition
|
tbuehlmann_ponder
|
train
|
d96985d8a26f1ac8a491f598c4103d3d18360065
|
diff --git a/tests/test_calls.py b/tests/test_calls.py
index <HASH>..<HASH> 100644
--- a/tests/test_calls.py
+++ b/tests/test_calls.py
@@ -45,3 +45,18 @@ class DescribeGenerateGenericCalls:
generate_generic_calls(base, namespace)
base_funcs = (m.split('.', 1)[1] for m in METHODS if m.startswith(base))
assert sorted(namespace['__all__']) == list(sorted(base_funcs))
+
+ def it_adds_doc_string_to_funcs_that_already_exist(self):
+ func = lambda: None
+ base = 'uber'
+ namespace = {'method_list': func}
+ generate_generic_calls(base, namespace)
+ assert namespace['method_list'].__doc__ == METHODS['uber.method_list']
+
+ def it_does_not_add_doc_string_to_funcs_that_already_have_them(self):
+ func = lambda: None
+ func.__doc__ = 'foobar'
+ base = 'uber'
+ namespace = {'method_list': func}
+ generate_generic_calls(base, namespace)
+ assert namespace['method_list'].__doc__ == 'foobar'
|
Finish coverage for generate_generic_calls.
|
jasonkeene_python-ubersmith
|
train
|
a5c4dd0c4ab41d2b953f57852ccc7e9c4e3a12f8
|
diff --git a/src/Overlay.react.js b/src/Overlay.react.js
index <HASH>..<HASH> 100644
--- a/src/Overlay.react.js
+++ b/src/Overlay.react.js
@@ -1,4 +1,5 @@
import cx from 'classnames';
+import {isEqual, throttle} from 'lodash';
import React, {Children, cloneElement, PropTypes} from 'react';
import {findDOMNode} from 'react-dom';
import {Portal} from 'react-overlays';
@@ -49,16 +50,20 @@ const Overlay = React.createClass({
},
componentDidMount() {
- this._maybeUpdatePosition();
- window.addEventListener('resize', this._maybeUpdatePosition);
+ this._updatePosition();
+ this._updatePositionThrottled = throttle(this._updatePosition, 100);
+
+ window.addEventListener('resize', this._updatePositionThrottled);
+ window.addEventListener('scroll', this._updatePositionThrottled, true);
},
componentWillReceiveProps(nextProps) {
- this._maybeUpdatePosition();
+ this._updatePositionThrottled();
},
componentWillUnmount() {
- window.removeEventListener('resize', this._maybeUpdatePosition);
+ window.removeEventListener('resize', this._updatePositionThrottled);
+ window.removeEventListener('scroll', this._updatePositionThrottled);
},
render() {
@@ -88,7 +93,7 @@ const Overlay = React.createClass({
);
},
- _maybeUpdatePosition() {
+ _updatePosition() {
// Positioning is only used when body is the container.
if (!isBody(this.props.container)) {
return;
@@ -101,13 +106,17 @@ const Overlay = React.createClass({
if (targetNode) {
const {innerHeight, innerWidth, pageYOffset} = window;
const {bottom, left, top, width} = targetNode.getBoundingClientRect();
-
- this.setState({
+ const newState = {
bottom: innerHeight - pageYOffset - top,
left,
right: innerWidth - left - width,
top: pageYOffset + bottom,
- });
+ };
+
+ // Don't update unless the target element position has changed.
+ if (!isEqual(this.state, newState)) {
+ this.setState(newState);
+ }
}
},
});
|
Fix redraw on scroll event when menu is attached to body
|
ericgio_react-bootstrap-typeahead
|
train
|
956b0f01e18950445947aa296d9567b4c62ed42f
|
diff --git a/lib/yell/configuration.rb b/lib/yell/configuration.rb
index <HASH>..<HASH> 100644
--- a/lib/yell/configuration.rb
+++ b/lib/yell/configuration.rb
@@ -1,5 +1,6 @@
# encoding: utf-8
+require 'erb'
require 'yaml'
module Yell #:nodoc:
@@ -9,7 +10,11 @@ module Yell #:nodoc:
class Configuration
def self.load!( file )
- YAML.load_file( file )[ Yell.env ] || {}
+ # parse through ERB
+ yaml = ERB.new(File.read(file)).result
+
+ # parse through YAML
+ YAML.load(yaml)[Yell.env] || {}
end
end
|
Parse yell.yml with ERB first to allow advanced config.
|
rudionrails_yell
|
train
|
0d88549a7e1229856ff8bf659692554f85733b1a
|
diff --git a/ravel.py b/ravel.py
index <HASH>..<HASH> 100644
--- a/ravel.py
+++ b/ravel.py
@@ -3083,6 +3083,9 @@ def def_proxy_interface(kind, *, name, introspected, is_async) :
# class that will be returned.
__slots__ = ("connection", "dest", "timeout", "_set_prop_pending", "_set_prop_failed")
+ # class variables:
+ # template -- = proxy class (set up above)
+ # props -- dict of introspected.properties by name
def __init__(self, *, connection, dest, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
if is_async :
@@ -3111,40 +3114,90 @@ def def_proxy_interface(kind, *, name, introspected, is_async) :
)
#end __getitem__
- async def set_prop_flush(self) :
- "workaround for the fact that prop-setter has to queue a separate" \
- " asynchronous task; caller can await this coroutine to ensure that" \
- " all pending set-property calls have completed."
- if not is_async :
- raise RuntimeError("not without an event loop")
- #end if
- if self._set_prop_failed != None :
- set_prop_pending = [self._set_prop_failed]
- self._set_prop_failed = None
- else :
- set_prop_pending = self._set_prop_pending
- #end if
- if len(set_prop_pending) != 0 :
- if "loop" in asyncio.wait.__kwdefaults__ :
- done = (await asyncio.wait(set_prop_pending, loop = self.connection.loop))[0]
- # no default loop in pre-3.7
+ if is_async :
+
+ async def set_prop_flush(self) :
+ "workaround for the fact that prop-setter has to queue a separate" \
+ " asynchronous task; caller can await this coroutine to ensure that" \
+ " all pending set-property calls have completed."
+ if not is_async :
+ raise RuntimeError("not without an event loop")
+ #end if
+ if self._set_prop_failed != None :
+ set_prop_pending = [self._set_prop_failed]
+ self._set_prop_failed = None
else :
- # loop arg removed in 3.10
- done = (await asyncio.wait(set_prop_pending))[0]
+ set_prop_pending = self._set_prop_pending
#end if
- failed = list(e for f in done for e in (f.exception(),) if e != None)
- if len(failed) > 1 :
- raise RuntimeError \
+ if len(set_prop_pending) != 0 :
+ if "loop" in asyncio.wait.__kwdefaults__ :
+ done = (await asyncio.wait(set_prop_pending, loop = self.connection.loop))[0]
+ # no default loop in pre-3.7
+ else :
+ # loop arg removed in 3.10
+ done = (await asyncio.wait(set_prop_pending))[0]
+ #end if
+ failed = list(e for f in done for e in (f.exception(),) if e != None)
+ if len(failed) > 1 :
+ raise RuntimeError \
+ (
+ "multiple failures to set properties: %s"
+ %
+ ", ".join(str(f) for f in failed)
+ )
+ elif len(failed) == 1 :
+ raise failed[0]
+ #end if
+ #end if
+ #end set_prop_flush
+
+ def set_prop(self, path, propname, newvalue) :
+ "alternative way of asynchronously setting a new property value:" \
+ " returns a Future that can be explicitly awaited."
+ if propname not in self.props :
+ raise dbus.DBusError \
(
- "multiple failures to set properties: %s"
- %
- ", ".join(str(f) for f in failed)
+ DBUS.ERROR_UNKNOWN_PROPERTY,
+ message = "no such property “%s”" % propname
)
- elif len(failed) == 1 :
- raise failed[0]
#end if
- #end if
- #end set_prop_flush
+ propdef = self.props[propname]
+ if propdef.access == Introspection.ACCESS.READ :
+ raise dbus.DBusError \
+ (
+ DBUS.ERROR_PROPERTY_READ_ONLY,
+ message = "property “%s” cannot be written" % propdef.name
+ )
+ #end if
+ message = dbus.Message.new_method_call \
+ (
+ destination = self.dest,
+ path = dbus.unsplit_path(path),
+ iface = DBUS.INTERFACE_PROPERTIES,
+ method = "Set"
+ )
+ message.append_objects("ssv", self.template._iface_name, propname, (propdef.type, newvalue))
+ set_prop_pending = self.connection.loop.create_future()
+ pending = self.connection.send_with_reply(message, self.timeout)
+ async def sendit() :
+ reply = await pending.await_reply()
+ if reply.type == DBUS.MESSAGE_TYPE_METHOD_RETURN :
+ set_prop_pending.set_result(None)
+ elif reply.type == DBUS.MESSAGE_TYPE_ERROR :
+ set_prop_pending.set_exception \
+ (
+ dbus.DBusError(reply.error_name, reply.expect_objects("s")[0])
+ )
+ else :
+ raise ValueError("unexpected reply type %d" % reply.type)
+ #end if
+ #end sendit
+ self.connection.create_task(sendit())
+ return \
+ set_prop_pending
+ #end set_prop
+
+ #end if
#end proxy_factory
@@ -3199,6 +3252,11 @@ def def_proxy_interface(kind, *, name, introspected, is_async) :
}
)
proxy_factory.template = proxy
+ proxy_factory.props = dict \
+ (
+ (prop.name, prop)
+ for prop in introspected.properties
+ )
return \
proxy_factory
#end def_proxy_interface
|
Add alternative way of asynchronously setting properties, via an explicit
set_prop() method as opposed to property assignment; the new method
returns a Future that can be awaited to return None (on success) or raise
an exception (on failure).
|
ldo_dbussy
|
train
|
d65fe11dd90596355d90c3913df864b80eb13e05
|
diff --git a/bremersee-pagebuilder/src/main/java/org/bremersee/pagebuilder/spring/PageBuilderSpringUtils.java b/bremersee-pagebuilder/src/main/java/org/bremersee/pagebuilder/spring/PageBuilderSpringUtils.java
index <HASH>..<HASH> 100644
--- a/bremersee-pagebuilder/src/main/java/org/bremersee/pagebuilder/spring/PageBuilderSpringUtils.java
+++ b/bremersee-pagebuilder/src/main/java/org/bremersee/pagebuilder/spring/PageBuilderSpringUtils.java
@@ -16,7 +16,12 @@
package org.bremersee.pagebuilder.spring;
+import java.util.ArrayList;
+import java.util.List;
+
import org.bremersee.comparator.spring.ComparatorSpringUtils;
+import org.bremersee.pagebuilder.PageBuilderUtils;
+import org.bremersee.pagebuilder.PageEntryTransformer;
import org.bremersee.pagebuilder.PageResult;
import org.bremersee.pagebuilder.model.Page;
import org.bremersee.pagebuilder.model.PageRequest;
@@ -79,6 +84,32 @@ public abstract class PageBuilderSpringUtils {
//@formatter:on
}
+ public static <E, T> PageImpl<T> toSpringPage(Page<E> page, PageEntryTransformer<T, E> transformer) {
+ if (page == null) {
+ return null;
+ }
+ if (transformer == null) {
+ transformer = new PageEntryTransformer<T, E>() {
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public T transform(E source) {
+ return (T)source;
+ }
+ };
+ }
+ List<T> transformedEntries = new ArrayList<>(page.getEntries().size());
+ for (E entry : page.getEntries()) {
+ transformedEntries.add(transformer.transform(entry));
+ }
+ //@formatter:off
+ return new SpringPageImpl<T>(
+ transformedEntries,
+ toSpringPageRequest(page.getPageRequest()),
+ page.getTotalSize());
+ //@formatter:on
+ }
+
public static <E> PageResult<E> fromSpringPage(org.springframework.data.domain.Page<E> springPage) {
if (springPage == null) {
return null;
@@ -87,6 +118,24 @@ public abstract class PageBuilderSpringUtils {
return new PageResult<E>(springPage.getContent(), pageRequest, springPage.getTotalElements());
}
+ public static <E, T> PageResult<T> fromSpringPage(org.springframework.data.domain.Page<E> springPage, PageEntryTransformer<T, E> transformer) {
+ if (springPage == null) {
+ return null;
+ }
+ if (transformer == null) {
+ transformer = new PageEntryTransformer<T, E>() {
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public T transform(E source) {
+ return (T)source;
+ }
+ };
+ }
+ PageRequestDto pageRequest = getPageRequest(springPage);
+ return PageBuilderUtils.createPage(springPage.getContent(), pageRequest, springPage.getTotalElements(), transformer);
+ }
+
private static PageRequestDto getPageRequest(org.springframework.data.domain.Page<?> springPage) {
if (springPage == null) {
return null;
|
Transformer added to PageBuilderSpringUtils
|
bremersee_pagebuilder
|
train
|
f5b8bd8c28acde4a845262377d2bdc8604e0c6f9
|
diff --git a/src/python/pants/ivy/BUILD b/src/python/pants/ivy/BUILD
index <HASH>..<HASH> 100644
--- a/src/python/pants/ivy/BUILD
+++ b/src/python/pants/ivy/BUILD
@@ -3,6 +3,7 @@
python_library(
dependencies = [
+ '3rdparty/python:future',
'3rdparty/python/twitter/commons:twitter.common.collections',
'3rdparty/python:six',
'src/python/pants/base:build_environment',
diff --git a/src/python/pants/ivy/bootstrapper.py b/src/python/pants/ivy/bootstrapper.py
index <HASH>..<HASH> 100644
--- a/src/python/pants/ivy/bootstrapper.py
+++ b/src/python/pants/ivy/bootstrapper.py
@@ -8,6 +8,7 @@ import hashlib
import logging
import os
import shutil
+from builtins import map, object
from pants.base.build_environment import get_buildroot
from pants.ivy.ivy import Ivy
diff --git a/src/python/pants/ivy/ivy.py b/src/python/pants/ivy/ivy.py
index <HASH>..<HASH> 100644
--- a/src/python/pants/ivy/ivy.py
+++ b/src/python/pants/ivy/ivy.py
@@ -5,6 +5,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
import os.path
+from builtins import object
from contextlib import contextmanager
from six import string_types
|
Port ivy to Python 3 (#<I>)
Part of #<I>.
|
pantsbuild_pants
|
train
|
6de70f9aadd6c40f903ba7d519a58bdfa1611d90
|
diff --git a/myql/myql.py b/myql/myql.py
index <HASH>..<HASH> 100755
--- a/myql/myql.py
+++ b/myql/myql.py
@@ -25,12 +25,13 @@ class MYQL(object):
community_data = "env 'store://datatables.org/alltableswithkeys'; " #Access to community table
def __init__(self, community=True, format='json', jsonCompact=False, crossProduct=None, debug=False, oauth=None):
+ self.community = community # True means access to community data
self.format = format
+ self._table = None
self._query = None # used to build query when using methods such as <select>, <insert>, ...
self._payload = {} # Last payload
self.diagnostics = False # Who knows, someone would like to turn it ON lol
- self.limit = ''
- self.community = community # True means access to community data
+ self.limit = None
self.crossProduct = crossProduct
self.jsonCompact = jsonCompact
self.debug = debug
@@ -41,7 +42,7 @@ class MYQL(object):
def __repr__(self):
'''Returns information on the current instance
'''
- return "<url>: '{0}' - <table>: '{1}' - <format> : '{2}' ".format(self.url, self.table, self.format)
+ return "<Community>: {0} - <Foramt>: {1} ".format(self.community, self.format)
def payloadBuilder(self, query, format=None):
'''Build the payload'''
@@ -151,7 +152,7 @@ class MYQL(object):
>>>
'''
if not table:
- #query = "desc {0} ".format(self.table)
+ #query = "desc {0} ".format(self._table)
raise errors.NoTableSelectedError('No table selected')
query = "desc {0}".format(table)
response = self.rawQuery(query)
@@ -163,14 +164,14 @@ class MYQL(object):
'''Just a select which returns a response
>>> yql.get("geo.countries', ['name', 'woeid'], 5")
'''
- self.table = table
+ self._table = table
if not items:
items = ['*']
- self._query = "SELECT {1} FROM {0} ".format(self.table, ','.join(items))
+ self._query = "SELECT {1} FROM {0} ".format(self._table, ','.join(items))
if limit:
self._query += "limit {0}".format(limit)
- if not self.table :
+ if not self._table :
raise errors.NoTableSelectedError('Please select a table')
payload = self.payloadBuilder(self._query)
@@ -185,10 +186,10 @@ class MYQL(object):
>>> yql.select('geo.countries', limit=5)
>>> yql.select('social.profile', ['guid', 'givenName', 'gender'])
'''
- self.table = table
+ self._table = table
if not items:
items = ['*']
- self._query = "SELECT {1} FROM {0} ".format(self.table, ','.join(items))
+ self._query = "SELECT {1} FROM {0} ".format(self._table, ','.join(items))
try: #Checking wether a limit is set or not
self._limit = limit
except (Exception,) as e:
@@ -213,10 +214,10 @@ class MYQL(object):
"""Updates a YQL Table
>>> yql.update('yql.storage',['value'],['https://josuebrunel.orkg']).where(['name','=','store://YEl70PraLLMSMuYAauqNc7'])
"""
- self.table = table
+ self._table = table
self._limit = None
items_values = ','.join(["{0} = '{1}'".format(k,v) for k,v in zip(items,values)])
- self._query = "UPDATE {0} SET {1}".format(self.table, items_values)
+ self._query = "UPDATE {0} SET {1}".format(self._table, items_values)
return self
@@ -225,9 +226,9 @@ class MYQL(object):
"""Deletes record in table
>>> yql.delete('yql.storage').where(['name','=','store://YEl70PraLLMSMuYAauqNc7'])
"""
- self.table = table
+ self._table = table
self._limit = None
- self._query = "DELETE FROM {0}".format(self.table)
+ self._query = "DELETE FROM {0}".format(self._table)
return self
@@ -236,7 +237,7 @@ class MYQL(object):
''' This method simulates a where condition. Use as follow:
>>> yql.select('mytable').where(['name', '=', 'alain'], ['location', '!=', 'paris'])
'''
- if not self.table:
+ if not self._table:
raise errors.NoTableSelectedError('No Table Selected')
clause = []
|
self.table changed into self._table
|
josuebrunel_myql
|
train
|
a93d67b05feb7c4a8530187a828f84f2d40ac972
|
diff --git a/lib/parser.js b/lib/parser.js
index <HASH>..<HASH> 100644
--- a/lib/parser.js
+++ b/lib/parser.js
@@ -188,10 +188,8 @@ TokenParser.prototype = {
utils.throwError('Invalid filter "' + match + '"', self.line, self.filename);
}
self.escape = self.filters[match].safe ? false : self.escape;
- temp = self.filterApplyIdx.pop();
- self.out.splice(temp, 0, '_filters["' + match + '"](');
+ self.out.splice(self.filterApplyIdx[self.filterApplyIdx.length - 1], 0, '_filters["' + match + '"](');
self.state.push(token.type);
- self.filterApplyIdx.push(temp);
break;
case _t.FILTEREMPTY:
@@ -244,8 +242,10 @@ TokenParser.prototype = {
self.out.push(')');
// Once off the previous entry
self.filterApplyIdx.pop();
- // Once for the open paren
- self.filterApplyIdx.pop();
+ if (temp !== _t.FILTER) {
+ // Once for the open paren
+ self.filterApplyIdx.pop();
+ }
break;
case _t.COMMA:
diff --git a/lib/tags/for.js b/lib/tags/for.js
index <HASH>..<HASH> 100644
--- a/lib/tags/for.js
+++ b/lib/tags/for.js
@@ -121,6 +121,7 @@ exports.parse = function (str, line, parser, types) {
throw new Error('Unexpected token "' + token.match + '" on line ' + line + '.');
}
ready = true;
+ this.filterApplyIdx.push(this.out.length);
});
return true;
diff --git a/lib/tags/if.js b/lib/tags/if.js
index <HASH>..<HASH> 100644
--- a/lib/tags/if.js
+++ b/lib/tags/if.js
@@ -58,6 +58,7 @@ exports.parse = function (str, line, parser, types) {
throw new Error('Attempted logic "not ' + token.match + '" on line ' + line + '. Use !(foo ' + token.match + ') instead.');
}
this.out.push(token.match);
+ this.filterApplyIdx.push(this.out.length);
});
parser.on(types.NOT, function (token) {
diff --git a/lib/tags/set.js b/lib/tags/set.js
index <HASH>..<HASH> 100644
--- a/lib/tags/set.js
+++ b/lib/tags/set.js
@@ -100,6 +100,7 @@ exports.parse = function (str, line, parser, types) {
'_ctx.' + nameSet
);
this.out.push(token.match);
+ this.filterApplyIdx.push(this.out.length);
});
return true;
diff --git a/tests/basic.test.js b/tests/basic.test.js
index <HASH>..<HASH> 100644
--- a/tests/basic.test.js
+++ b/tests/basic.test.js
@@ -265,7 +265,12 @@ describe('swig.renderFile', function () {
});
describe('swig.run', function () {
- var tpl = swig.precompile('Hello {{ foobar }}').tpl;
+ var tpl;
+
+ beforeEach(function () {
+ tpl = swig.precompile('Hello {{ foobar }}').tpl;
+ });
+
it('runs compiled templates', function () {
expect(swig.run(tpl)).to.equal('Hello ');
expect(swig.run(tpl, { foobar: 'Tacos'})).to.equal('Hello Tacos');
diff --git a/tests/filters.test.js b/tests/filters.test.js
index <HASH>..<HASH> 100644
--- a/tests/filters.test.js
+++ b/tests/filters.test.js
@@ -298,4 +298,19 @@ describe('Filters:', function () {
expect(swig.render("{{ t|replace('L', r('items').length)|replace('N', u) }}", { locals: locals })).to.equal('3 Tacos');
});
+ it("gh-441: Chaining filters on top of functions within tags", function () {
+ var locals = {
+ getFoo: function () {
+ return [1, 3, 0];
+ }
+ };
+
+ expect(swig.render('{{ foo|default("bar")|reverse }}')).to.equal('rab');
+ expect(swig.render("{{ getFoo('foo')|join('*')|reverse }}", { locals: locals })).to.equal('0*3*1');
+ expect(swig.render("{% set foo = getFoo('foo')|join('+')|reverse %}{{ foo }}", { locals: locals })).to.equal('0+3+1');
+ expect(swig.render("{% for a in getFoo('foo')|sort(true)|reverse %}{{ a }}%{% endfor %}", { locals: locals })).to.equal('3%1%0%');
+ expect(swig.render('{% if "0+3+1" === getFoo("f")|join("+")|reverse %}yep{% endif %}', { locals: locals })).to.equal('yep');
+ expect(swig.render('{% if "0+3+1" === getFoo("f")|join("+")|reverse && null|default(true) %}yep{% endif %}', { locals: locals })).to.equal('yep');
+ });
+
});
|
Fix filter chaining within tags. Fixes gh-<I>
|
Thunf_swiger
|
train
|
c32ea42b1b6843490e4aa8229db319a2cfa23e82
|
diff --git a/libraries/lithium/template/helper/Form.php b/libraries/lithium/template/helper/Form.php
index <HASH>..<HASH> 100644
--- a/libraries/lithium/template/helper/Form.php
+++ b/libraries/lithium/template/helper/Form.php
@@ -365,7 +365,13 @@ class Form extends \lithium\template\Helper {
$label = $input = null;
if ($options['label'] === null || $options['label']) {
- $for = (isset($options['id'])) ? $options['id'] : $name;
+ $for = $name;
+ if (isset($options['id'])) {
+ $for = $options['id'];
+ if (!isset($options['label'])) {
+ $options['label'] = Inflector::humanize($name);
+ }
+ }
$label = $this->label($for, $options['label']);
}
|
fixing label for field to use field as title if using id as for
|
UnionOfRAD_framework
|
train
|
cd65bbe60b60b1addd1e374ae0529864135b08a6
|
diff --git a/lib/tilelive/sphericalmercator.js b/lib/tilelive/sphericalmercator.js
index <HASH>..<HASH> 100644
--- a/lib/tilelive/sphericalmercator.js
+++ b/lib/tilelive/sphericalmercator.js
@@ -4,8 +4,8 @@ var cache = {},
D2R = Math.PI / 180,
R2D = 180 / Math.PI,
// 900913 properties.
- a = 6378137,
- b = 6378137;
+ A = 6378137,
+ MAXEXTENT = 20037508.34;
// SphericalMercator constructor: precaches calculations
@@ -43,6 +43,10 @@ SphericalMercator.prototype.px = function(ll, zoom) {
var f = Math.min(Math.max(Math.sin(D2R * ll[1]), -0.9999), 0.9999);
var x = Math.round(d + ll[0] * this.Bc[zoom]);
var y = Math.round(d + 0.5 * Math.log((1 + f) / (1 - f)) * (-this.Cc[zoom]));
+ (x > this.Ac[zoom]) && (x = this.Ac[zoom]);
+ (y > this.Ac[zoom]) && (y = this.Ac[zoom]);
+ (x < 0) && (x = 0);
+ (y < 0) && (y = 0);
return [x, y];
};
@@ -133,23 +137,23 @@ SphericalMercator.prototype.convert = function(bbox, to) {
// Convert lon/lat values to 900913 x/y.
SphericalMercator.prototype.forward = function(ll) {
- // ll value is at poles.
- // @TODO: return 900913 max extents.
- if (Math.abs(Math.abs(ll[1] * D2R) - (Math.PI*0.5)) <= EPSLN) {
- return null;
- } else {
- return [
- a * ll[0] * D2R,
- a * Math.log(Math.tan((Math.PI*0.25) + (0.5 * ll[1] * D2R)))
- ];
- }
+ var xy = [
+ A * ll[0] * D2R,
+ A * Math.log(Math.tan((Math.PI*0.25) + (0.5 * ll[1] * D2R)))
+ ];
+ // if xy value is beyond maxextent (e.g. poles), return maxextent.
+ (xy[0] > MAXEXTENT) && (xy[0] = MAXEXTENT);
+ (xy[0] < -MAXEXTENT) && (xy[0] = -MAXEXTENT);
+ (xy[1] > MAXEXTENT) && (xy[1] = MAXEXTENT);
+ (xy[1] < -MAXEXTENT) && (xy[1] = -MAXEXTENT);
+ return xy;
};
// Convert 900913 x/y values to lon/lat.
SphericalMercator.prototype.inverse = function(xy) {
return [
- (xy[0] * R2D / a),
- ((Math.PI*0.5) - 2.0 * Math.atan(Math.exp(-xy[1] / a))) * R2D
+ (xy[0] * R2D / A),
+ ((Math.PI*0.5) - 2.0 * Math.atan(Math.exp(-xy[1] / A))) * R2D
];
};
|
Adjust post-calculation for rounding problems.
|
mapbox_tilelive
|
train
|
ce86b1a093d713e18a98f7f45d6873fcb36552c7
|
diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Locale.java b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Locale.java
index <HASH>..<HASH> 100644
--- a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Locale.java
+++ b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Locale.java
@@ -533,7 +533,7 @@ import sun.util.locale.ParseStatus;
* <td><a href="http://www.unicode.org/versions/Unicode11.0.0/">Unicode 11.0</a></td></tr>
* </table>
*
- * <a name="default_locale"></a><h4>Be wary of the default locale</h3>
+ * <a name="default_locale"></a><h4>Be wary of the default locale</h4>
* <p>Note that there are many convenience methods that automatically use the default locale, but
* using them may lead to subtle bugs.
*
|
Fixed HTML tag in doc-comment, which broke javadoc generation for that class.
PiperOrigin-RevId: <I>
|
google_j2objc
|
train
|
50b779faa16600127933af9c1d194b2f253f0fe4
|
diff --git a/lib/onebox/engine/standard_embed.rb b/lib/onebox/engine/standard_embed.rb
index <HASH>..<HASH> 100644
--- a/lib/onebox/engine/standard_embed.rb
+++ b/lib/onebox/engine/standard_embed.rb
@@ -22,6 +22,7 @@ module Onebox
add_oembed_provider /www\.meetup\.com\//, 'http://api.meetup.com/oembed'
add_oembed_provider /www\.kickstarter\.com\//, 'https://www.kickstarter.com/services/oembed'
add_oembed_provider /www\.ted\.com\//, 'http://www.ted.com/services/v1/oembed.json'
+ add_oembed_provider /(.*\.)?vimeo\.com\//, 'http://vimeo.com/api/oembed.json'
# Sites that work better with OpenGraph
add_opengraph_provider /gfycat\.com\//
|
FIX: allow hidden but embeddable vimeo videos to display preview
Vimeo videos that are embeddable but hidden from Vimeos search do not contain
an oembed url, despite this being available. The endpoint is taken from iframely:
<URL>
|
discourse_onebox
|
train
|
cdd456160cc0643db48c626cd4a331f1cfa9f535
|
diff --git a/lib/lint.js b/lib/lint.js
index <HASH>..<HASH> 100644
--- a/lib/lint.js
+++ b/lib/lint.js
@@ -6,11 +6,17 @@ Object.defineProperty(exports, "__esModule", {
exports.default = {
root: {
default: 75,
- typeOf: 'number'
+ typeOf: 'number',
+ coerce: function coerce(val) {
+ return val && Number(val);
+ }
},
fixed: {
default: 6,
- typeOf: 'number'
+ typeOf: 'number',
+ coerce: function coerce(val) {
+ return val && Number(val);
+ }
},
filter: {
default: null,
diff --git a/src/lint.js b/src/lint.js
index <HASH>..<HASH> 100644
--- a/src/lint.js
+++ b/src/lint.js
@@ -1,11 +1,17 @@
export default {
root: {
default: 75,
- typeOf: 'number'
+ typeOf: 'number',
+ coerce(val) {
+ return val && Number(val)
+ }
},
fixed: {
default: 6,
- typeOf: 'number'
+ typeOf: 'number',
+ coerce(val) {
+ return val && Number(val)
+ }
},
filter: {
default: null,
|
fix: coerce option root to be number
|
cupools_pxrem
|
train
|
0d59d61c6137c9e65831c090a23e3a24de5f90e5
|
diff --git a/lib/rollbar/notifier.rb b/lib/rollbar/notifier.rb
index <HASH>..<HASH> 100644
--- a/lib/rollbar/notifier.rb
+++ b/lib/rollbar/notifier.rb
@@ -412,6 +412,7 @@ module Rollbar
item = build_item('error', nil, exception, { :internal => true }, nil)
rescue => e
send_failsafe('build_item in exception_data', e)
+ log_error "[Rollbar] Exception: #{exception}"
return
end
@@ -419,6 +420,7 @@ module Rollbar
process_item(item)
rescue => e
send_failsafe('error in process_item', e)
+ log_error "[Rollbar] Item: #{item}"
return
end
@@ -426,6 +428,7 @@ module Rollbar
log_instance_link(item['data'])
rescue => e
send_failsafe('error logging instance link', e)
+ log_error "[Rollbar] Item: #{item}"
return
end
end
|
<I>: log_error original exception on report failute
|
rollbar_rollbar-gem
|
train
|
cfd375d32d1ffbf80f6cafcafa9d28e8a38679e3
|
diff --git a/lib/chart.js b/lib/chart.js
index <HASH>..<HASH> 100644
--- a/lib/chart.js
+++ b/lib/chart.js
@@ -58,7 +58,7 @@ var LineDefaults = proto.Line.defaults = {
scaleLineWidth : 1,
//Boolean - Whether to show labels on the scale
- scaleShowLabels : false,
+ scaleShowLabels : true,
//Interpolated JS string - can access value
scaleLabel : "<%=value%>",
|
Set scaleShowLabels to true to be consistent with chart.js.
|
my-archives_nchart
|
train
|
7144315135e1428930f79edc84b379ae71d3bd3b
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -58,7 +58,7 @@ module.exports = function (options) {
var parts = [];
parts.push(Buffer(content.substring(0, matches.index)));
- parts.push(Buffer('styles: [\''));
+ parts.push(Buffer('styles: [`'));
for (var i=0; i<entrances.length; i++) {
parts.push(Buffer(entrances[i].replace(/\n/g, '')));
@@ -66,7 +66,7 @@ module.exports = function (options) {
parts.push(Buffer('\', \''));
}
}
- parts.push(Buffer('\']'));
+ parts.push(Buffer('`]'));
parts.push(Buffer(content.substr(matches.index + matches[0].length)));
return Buffer.concat(parts);
|
fixed bug
Now it's allowed to use ' symbol in scss files, also comments
|
amritk_gulp-angular2-embed-sass
|
train
|
148ae330ac3b2edd860c7a1f60d7731c061de1b8
|
diff --git a/test/Psy/Test/CodeCleaner/FunctionReturnInWriteContextPassTest.php b/test/Psy/Test/CodeCleaner/FunctionReturnInWriteContextPassTest.php
index <HASH>..<HASH> 100644
--- a/test/Psy/Test/CodeCleaner/FunctionReturnInWriteContextPassTest.php
+++ b/test/Psy/Test/CodeCleaner/FunctionReturnInWriteContextPassTest.php
@@ -53,7 +53,10 @@ class FunctionReturnInWriteContextPassTest extends CodeCleanerTestCase
$this->fail();
} catch (FatalErrorException $e) {
if (version_compare(PHP_VERSION, '5.5', '>=')) {
- $this->assertContains('Cannot use isset() on the result of a function call (you can use "null !== func()" instead)', $e->getMessage());
+ $this->assertContains(
+ 'Cannot use isset() on the result of a function call (you can use "null !== func()" instead)',
+ $e->getMessage()
+ );
} else {
$this->assertContains("Can't use function return value in write context", $e->getMessage());
}
diff --git a/test/Psy/Test/Formatter/SignatureFormatterTest.php b/test/Psy/Test/Formatter/SignatureFormatterTest.php
index <HASH>..<HASH> 100644
--- a/test/Psy/Test/Formatter/SignatureFormatterTest.php
+++ b/test/Psy/Test/Formatter/SignatureFormatterTest.php
@@ -63,7 +63,9 @@ class SignatureFormatterTest extends \PHPUnit_Framework_TestCase
),
array(
new \ReflectionClass('Psy\CodeCleaner\CodeCleanerPass'),
- 'abstract class Psy\CodeCleaner\CodeCleanerPass extends PhpParser\NodeVisitorAbstract implements PhpParser\NodeVisitor',
+ 'abstract class Psy\CodeCleaner\CodeCleanerPass '
+ . 'extends PhpParser\NodeVisitorAbstract '
+ . 'implements PhpParser\NodeVisitor',
),
);
}
diff --git a/test/Psy/Test/TabCompletion/AutoCompleterTest.php b/test/Psy/Test/TabCompletion/AutoCompleterTest.php
index <HASH>..<HASH> 100644
--- a/test/Psy/Test/TabCompletion/AutoCompleterTest.php
+++ b/test/Psy/Test/TabCompletion/AutoCompleterTest.php
@@ -114,7 +114,11 @@ class AutoCompleterTest extends \PHPUnit_Framework_TestCase
array('ls ', array(), array('ls')),
array('sho', array('show'), array()),
array('12 + clone $', array('foo'), array()),
- // array('$foo ', array('+', 'clone'), array('$foo', 'DOMDocument', 'array_map')), requires a operator matcher?
+ // array(
+ // '$foo ',
+ // array('+', 'clone'),
+ // array('$foo', 'DOMDocument', 'array_map')
+ // ), requires a operator matcher?
array('$', array('foo', 'bar'), array('require', 'array_search', 'T_OPEN_TAG', 'Psy')),
array(
'Psy\\',
|
Fix some long line CS warnings.
|
bobthecow_psysh
|
train
|
beccf7f6b05bc2527b1bfa287c9908e594053f5a
|
diff --git a/src/ORM/AssociationCollection.php b/src/ORM/AssociationCollection.php
index <HASH>..<HASH> 100644
--- a/src/ORM/AssociationCollection.php
+++ b/src/ORM/AssociationCollection.php
@@ -114,7 +114,7 @@ class AssociationCollection implements IteratorAggregate
* @param string|array $class The type of associations you want.
* For example 'BelongsTo' or array like ['BelongsTo', 'HasOne']
* @return array An array of Association objects.
- * @deprecated 3.6.0 Use getByType() instead.
+ * @deprecated 3.5.3 Use getByType() instead.
*/
public function type($class)
{
|
Update version in deprecated tag.
|
cakephp_cakephp
|
train
|
25e8fdf1f349c9e640b0d14bfd267317b1fcf061
|
diff --git a/java/client/src/org/openqa/selenium/remote/Augmenter.java b/java/client/src/org/openqa/selenium/remote/Augmenter.java
index <HASH>..<HASH> 100644
--- a/java/client/src/org/openqa/selenium/remote/Augmenter.java
+++ b/java/client/src/org/openqa/selenium/remote/Augmenter.java
@@ -62,10 +62,14 @@ public class Augmenter extends BaseAugmenter {
@Override
protected RemoteWebDriver extractRemoteWebDriver(WebDriver driver) {
- if (driver.getClass() == RemoteWebDriver.class) {
+ if (driver.getClass() == RemoteWebDriver.class
+ || driver.getClass().getName().startsWith("org.openqa.selenium.remote.RemoteWebDriver$$EnhancerByCGLIB"))
+ {
return (RemoteWebDriver) driver;
+
} else {
- logger.warning("Augmenter should be applied to RemoteWebDriver instances only");
+ logger.warning("Augmenter should be applied to RemoteWebDriver instances " +
+ "or previously augmented instances only");
return null;
}
}
|
Implementing augmentation of previousely augmented instances
|
SeleniumHQ_selenium
|
train
|
0f5302a2391ea795d21d33c639b7b3a9c37ad610
|
diff --git a/src/keo.js b/src/keo.js
index <HASH>..<HASH> 100644
--- a/src/keo.js
+++ b/src/keo.js
@@ -11,6 +11,13 @@ export {memoize, trace, partial} from 'funkel';
export {objectAssign, compose, composeDeferred};
/**
+ * @method throwError
+ * @param {String} message
+ * @return {void}
+ */
+const throwError = message => console.error(`Keo: ${message}.`);
+
+/**
* @method isFunction
* @param {*} fn
* @return {Boolean}
@@ -319,22 +326,26 @@ export const createWithCompose = component => {
return (component.shouldComponentUpdate || (() => true))({
...passArguments.apply(this),
- nextProps,
- nextState
+ nextProps, nextState
});
},
/**
* @method componentWillUpdate
- * @param prevProps {Object}
+ * @param nextProps {Object}
+ * @param nextState {Object}
* @return {*}
*/
- componentWillUpdate(prevProps) {
+ componentWillUpdate(nextProps, nextState) {
- orFunction(component.componentWillUpdate)(prevProps, {
+ orFunction(component.componentWillUpdate)({
...passArguments.apply(this),
- setState: state => state
+ nextProps, nextState,
+ setState: state => {
+ throwError('You cannot `setState` inside of `componentWillUpdate`, instead use `componentWillReceiveProps`');
+ return state;
+ }
});
},
|
Added message for setState inside of
|
Wildhoney_Keo
|
train
|
bde2bbc1ebc1d50bfb968e41bac39d0949e93bcf
|
diff --git a/spec/maxima/core_spec.rb b/spec/maxima/core_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/maxima/core_spec.rb
+++ b/spec/maxima/core_spec.rb
@@ -61,12 +61,10 @@ module Maxima
actual_output = Maxima.lagrangian("x ^ 10 + y ^ (1/10)", [:x, :y], "x + y - 10", [1,1])
}.to_not raise_error
- expect(actual_output).to eq(
- {
- x: Maxima::Float.new(0.4787078489206559),
- y: Maxima::Float.new(9.521286271045522)
- }
- )
+ x, y = actual_output.values_at(:x, :y)
+
+ expect(x.to_f).to be_within(0.001 * 0.4787078489206621).of(0.4787078489206621)
+ expect(y.to_f).to be_within(0.001 * 9.5212862710455170).of(9.5212862710455170)
end
end
|
Added tolerance for float outputs of lagrangian tests
|
Danieth_rb_maxima
|
train
|
bdd0df3fc56e5c01d05bad5c59c1512b8adcbea0
|
diff --git a/lib/racecar/runner.rb b/lib/racecar/runner.rb
index <HASH>..<HASH> 100644
--- a/lib/racecar/runner.rb
+++ b/lib/racecar/runner.rb
@@ -103,10 +103,20 @@ module Racecar
def process_method
@process_method ||= begin
case
- when processor.respond_to?(:process_batch) then :batch
- when processor.respond_to?(:process) then :single
+ when processor.respond_to?(:process_batch)
+ if processor.method(:process_batch).arity != 1
+ raise Racecar::Error, "Invalid method signature for `process_batch`. The method must take exactly 1 argument."
+ end
+
+ :batch
+ when processor.respond_to?(:process)
+ if processor.method(:process).arity != 1
+ raise Racecar::Error, "Invalid method signature for `process`. The method must take exactly 1 argument."
+ end
+
+ :single
else
- raise NotImplementedError, "Consumer class must implement process or process_batch method"
+ raise NotImplementedError, "Consumer class `#{processor.class}` must implement a `process` or `process_batch` method"
end
end
end
diff --git a/spec/runner_spec.rb b/spec/runner_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/runner_spec.rb
+++ b/spec/runner_spec.rb
@@ -653,6 +653,22 @@ RSpec.describe Racecar::Runner do
end
end
+ context "with a consumer class with an invalid #process_batch method signature" do
+ class TestInvalidConsumer < Racecar::Consumer
+ subscribes_to "greetings"
+
+ def process_batch(batch, hello); end
+ end
+
+ let(:processor) { TestInvalidConsumer.new }
+
+ it "raises NotImplementedError" do
+ kafka.deliver_message("hello world", topic: "greetings")
+
+ expect { runner.run }.to raise_error(Racecar::Error, "Invalid method signature for `process_batch`. The method must take exactly 1 argument.")
+ end
+ end
+
context "with a consumer that produces messages" do
let(:processor) { TestProducingConsumer.new }
|
Validate the arity of the processing method
|
zendesk_racecar
|
train
|
d52d5bb0b4b7b4e9948a009e868dbc99d12214c8
|
diff --git a/src/toil_scripts/adam_pipeline/adam_preprocessing.py b/src/toil_scripts/adam_pipeline/adam_preprocessing.py
index <HASH>..<HASH> 100644
--- a/src/toil_scripts/adam_pipeline/adam_preprocessing.py
+++ b/src/toil_scripts/adam_pipeline/adam_preprocessing.py
@@ -129,14 +129,19 @@ def remove_file(masterIP, filename, sparkOnToil):
masterIP = masterIP.actual
if sparkOnToil:
try:
- containerID = check_output(["ssh", "-o", "StrictHostKeyChecking=no", masterIP, "docker", "ps", \
- "|", "grep", "apache-hadoop-master", "|", "awk", "'{print $1}'"])[:-1]
- check_call(["ssh", "-o", "StrictHostKeyChecking=no", masterIP, "docker", "exec", containerID, \
- "/opt/apache-hadoop/bin/hdfs", "dfs", "-rm", "-r", "/"+filename])
+ output = check_output(['ssh',
+ '-o', 'StrictHostKeyChecking=no',
+ masterIP, 'docker', 'ps'])
+ containerID = next(line.split()[0] for line in output.splitlines() if 'apache-hadoop-master' in line)
+ check_call(['ssh',
+ '-o', 'StrictHostKeyChecking=no',
+ masterIP,
+ 'docker', 'exec', containerID,
+ 'hdfs', 'dfs', '-rm', '-r', '/' + filename])
except:
pass
else:
- log.warning("Cannot remove file %s. Can only remove files when running Spark-on-Toil", filename)
+ log.warning('Cannot remove file %s. Can only remove files when running Spark-on-Toil', filename)
# FIXME: unused parameter sparkOnToil
|
Fixed line wrapping in SSH command and replaced awk/grep with pure Python
|
BD2KGenomics_toil-scripts
|
train
|
e7206a36bca40eee54e7cf1fc493f8a069a0223c
|
diff --git a/imagemounter/volume.py b/imagemounter/volume.py
index <HASH>..<HASH> 100644
--- a/imagemounter/volume.py
+++ b/imagemounter/volume.py
@@ -470,7 +470,8 @@ class Volume(object):
fsdesc = fsdesc.lower()
# for the purposes of this function, logical volume is nothing, and 'primary' is rather useless info
- if fsdesc in ('logical volume', 'luks volume', 'bde volume', 'primary', 'basic data partition'):
+ if fsdesc in ('logical volume', 'luks volume', 'bde volume', 'raid volume',
+ 'primary', 'basic data partition'):
continue
if fsdesc == 'directory':
|
Exclude raid volume from being a useful raid volume
|
ralphje_imagemounter
|
train
|
6023a6358ef35dee0fb59de2983a128f2ab70202
|
diff --git a/lib/rollbar/util.rb b/lib/rollbar/util.rb
index <HASH>..<HASH> 100644
--- a/lib/rollbar/util.rb
+++ b/lib/rollbar/util.rb
@@ -42,36 +42,60 @@ module Rollbar
end
end
- def self.deep_copy(obj)
+ def self.deep_copy(obj, copied = {})
+ # if we've already made a copy, return it.
+ return copied[obj.object_id] if copied[obj.object_id]
+
+ result = clone_obj(obj)
+
+ # Memoize the cloned object before recursive calls to #deep_copy below.
+ # This is the point of doing the work in two steps.
+ copied[obj.object_id] = result
+
+ if obj.is_a?(::Hash)
+ obj.each { |k, v| result[k] = deep_copy(v, copied) }
+ elsif obj.is_a?(Array)
+ obj.each { |v| result << deep_copy(v, copied) }
+ end
+
+ result
+ end
+
+ def self.clone_obj(obj)
if obj.is_a?(::Hash)
- result = obj.clone
- obj.each { |k, v| result[k] = deep_copy(v)}
- result
+ obj.clone
elsif obj.is_a?(Array)
- result = obj.clone
- result.clear
- obj.each { |v| result << deep_copy(v)}
- result
+ obj.clone.clear
else
obj
end
end
- def self.deep_merge(hash1, hash2)
+ def self.deep_merge(hash1, hash2, merged = {})
hash1 ||= {}
hash2 ||= {}
+ # If we've already merged these two objects, return hash1 now.
+ return hash1 if merged[hash1.object_id] && merged[hash1.object_id].include?(hash2.object_id)
+
+ merged[hash1.object_id] ||= []
+ merged[hash1.object_id] << hash2.object_id
+
+ perform_deep_merge(hash1, hash2, merged)
+
+ hash1
+ end
+
+ def self.perform_deep_merge(hash1, hash2, merged)
hash2.each_key do |k|
if hash1[k].is_a?(::Hash) && hash2[k].is_a?(::Hash)
- hash1[k] = deep_merge(hash1[k], hash2[k])
+ hash1[k] = deep_merge(hash1[k], hash2[k], merged)
elsif hash1[k].is_a?(Array) && hash2[k].is_a?(Array)
hash1[k] += deep_copy(hash2[k])
elsif hash2[k]
hash1[k] = deep_copy(hash2[k])
end
end
-
- hash1
end
def self.truncate(str, length)
diff --git a/spec/rollbar/util_spec.rb b/spec/rollbar/util_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/rollbar/util_spec.rb
+++ b/spec/rollbar/util_spec.rb
@@ -11,12 +11,92 @@ describe Rollbar::Util do
{ :foo => :bar }
end
- it 'doesnt fail and returns same hash' do
+ it "doesn't fail and returns same hash" do
result = Rollbar::Util.deep_merge(nil, data)
expect(result).to be_eql(data)
end
end
+
+ context 'with circular data' do
+ let(:data1) do
+ { :foo => 'bar' }.tap do |a|
+ b = { :a => a }
+ c = { :b => b }
+ a[:c] = c
+
+ array1 = %w[a b]
+ array2 = ['c', array1]
+ a[:array] = array1
+ array1 << array2
+ end
+ end
+
+ let(:data2) do
+ { :bar => 'baz' }.tap do |a|
+ b = { :a => a }
+ c = { :b => b }
+ a[:d] = c
+
+ array3 = %w[d e]
+ array4 = ['f', 'g', array3]
+ a[:array] = array3
+ array3 << array4
+ end
+ end
+
+ let(:merged) do
+ { :foo => 'bar' }.tap do |a|
+ b = { :a => a }
+ c = { :b => b }
+ a[:c] = c
+
+ array1 = %w[a b]
+ array2 = ['c', array1]
+ array1 << array2
+ array3 = %w[d e]
+ array4 = ['f', 'g', array3]
+ array3 << array4
+ a[:array] = array1 + array3
+ a[:bar] = 'baz'
+ a[:d] = c
+ end
+ end
+
+ it "doesn't crash and returns merged hash" do
+ result = Rollbar::Util.deep_merge(data1, data2)
+
+ expect(result.keys).to be_eql(merged.keys)
+ expect(result[:array]).to be_eql(merged[:array])
+ expect(result[:foo]).to be_eql(merged[:foo])
+ expect(result[:bar]).to be_eql(merged[:bar])
+ expect(result[:c].keys).to be_eql(merged[:c].keys)
+ expect(result[:d].keys).to be_eql(merged[:d].keys)
+ end
+ end
+ end
+
+ describe '.deep_copy' do
+ context 'with circular data' do
+ let(:data) do
+ { :foo => 'bar' }.tap do |a|
+ b = { :a => a }
+ c = { :b => b }
+ a[:c] = c
+
+ array1 = %w[a b]
+ array2 = ['c', 'd', array1]
+ a[:array] = array1
+ array1 << array2
+ end
+ end
+
+ it "doesn't crash and returns same hash" do
+ result = Rollbar::Util.deep_copy(data)
+
+ expect(result).to be_eql(data)
+ end
+ end
end
describe '.enforce_valid_utf8' do
|
allow deep_merge and deep_copy to handle cycles in the data
|
rollbar_rollbar-gem
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.