hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
---|---|---|---|---|
4f631d117218489e7286dddc494e2c9752b527b5 | diff --git a/src/widgets/NumberInputWidget.js b/src/widgets/NumberInputWidget.js
index <HASH>..<HASH> 100644
--- a/src/widgets/NumberInputWidget.js
+++ b/src/widgets/NumberInputWidget.js
@@ -300,35 +300,37 @@ OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
var delta = 0;
- // Standard 'wheel' event
- if ( event.originalEvent.deltaMode !== undefined ) {
- this.sawWheelEvent = true;
- }
- if ( event.originalEvent.deltaY ) {
- delta = -event.originalEvent.deltaY;
- } else if ( event.originalEvent.deltaX ) {
- delta = event.originalEvent.deltaX;
- }
+ if ( !this.isDisabled() ) {
+ // Standard 'wheel' event
+ if ( event.originalEvent.deltaMode !== undefined ) {
+ this.sawWheelEvent = true;
+ }
+ if ( event.originalEvent.deltaY ) {
+ delta = -event.originalEvent.deltaY;
+ } else if ( event.originalEvent.deltaX ) {
+ delta = event.originalEvent.deltaX;
+ }
- // Non-standard events
- if ( !this.sawWheelEvent ) {
- if ( event.originalEvent.wheelDeltaX ) {
- delta = -event.originalEvent.wheelDeltaX;
- } else if ( event.originalEvent.wheelDeltaY ) {
- delta = event.originalEvent.wheelDeltaY;
- } else if ( event.originalEvent.wheelDelta ) {
- delta = event.originalEvent.wheelDelta;
- } else if ( event.originalEvent.detail ) {
- delta = -event.originalEvent.detail;
+ // Non-standard events
+ if ( !this.sawWheelEvent ) {
+ if ( event.originalEvent.wheelDeltaX ) {
+ delta = -event.originalEvent.wheelDeltaX;
+ } else if ( event.originalEvent.wheelDeltaY ) {
+ delta = event.originalEvent.wheelDeltaY;
+ } else if ( event.originalEvent.wheelDelta ) {
+ delta = event.originalEvent.wheelDelta;
+ } else if ( event.originalEvent.detail ) {
+ delta = -event.originalEvent.detail;
+ }
}
- }
- if ( delta ) {
- delta = delta < 0 ? -1 : 1;
- this.adjustValue( delta * this.step );
- }
+ if ( delta ) {
+ delta = delta < 0 ? -1 : 1;
+ this.adjustValue( delta * this.step );
+ }
- return false;
+ return false;
+ }
};
/** | NumberInputWidget: Disable onWheel action when the widget is disabled
I'd like to just return if the widget is disabled, but putting the entire
code inside the condition seems to be convention.
Bug: T<I>
Change-Id: I<I>ff<I>a<I>ddbe<I>a<I>b6c<I>d<I>fa0 | wikimedia_oojs-ui | train |
b612101ea3fa51ac183120da25e01b009831e897 | diff --git a/test/Psy/Test/ShellTest.php b/test/Psy/Test/ShellTest.php
index <HASH>..<HASH> 100644
--- a/test/Psy/Test/ShellTest.php
+++ b/test/Psy/Test/ShellTest.php
@@ -76,7 +76,6 @@ class ShellTest extends \PHPUnit_Framework_TestCase
$includes = $shell->getIncludes();
$this->assertEquals('/file.php', $includes[0]);
- $this->assertTrue(function_exists('global_test_function_for_existance'));
}
public function testRenderingExceptions() | Remove assertion that function was included. The included file doesnt get loaded until the execution loop which is outside the scope of this test. | bobthecow_psysh | train |
76ddc4f8b271508747c962f705148d67456fa6cc | diff --git a/tests/test-rest-posts-controller.php b/tests/test-rest-posts-controller.php
index <HASH>..<HASH> 100644
--- a/tests/test-rest-posts-controller.php
+++ b/tests/test-rest-posts-controller.php
@@ -167,7 +167,7 @@ class WP_Test_REST_Posts_Controller extends WP_Test_REST_Post_Type_Controller_Te
$attachments_url = rest_url( '/wp/v2/media' );
$attachments_url = add_query_arg( 'post_parent', $this->post_id, $attachments_url );
- $this->assertEquals( $attachments_url, $links['attachments'][0]['href'] );
+ $this->assertEquals( $attachments_url, $links['http://wp-api.org/v2/attachment'][0]['href'] );
$tags_url = rest_url( '/wp/v2/terms/tag' );
$tags_url = add_query_arg( 'post', $this->post_id, $tags_url ); | Switch link relation in test for attachments | WP-API_WP-API | train |
ebb70b475b167a2eef0fd9a9b0392c3f6a818097 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -56,6 +56,13 @@
* `stubbles\lang\reflect\constructorParameter()`
+5.5.1 (2015-05-12)
+------------------
+
+ * fixed annotation string values which contained both ' and "
+
+
+
5.5.0 (2015-05-06)
------------------
diff --git a/src/main/php/lang/reflect/annotation/parser/AnnotationStateParser.php b/src/main/php/lang/reflect/annotation/parser/AnnotationStateParser.php
index <HASH>..<HASH> 100644
--- a/src/main/php/lang/reflect/annotation/parser/AnnotationStateParser.php
+++ b/src/main/php/lang/reflect/annotation/parser/AnnotationStateParser.php
@@ -99,10 +99,11 @@ class AnnotationStateParser implements AnnotationParser
$this->currentState = $this->states[$state];
$this->currentState->selected();
- $this->currentSignals = array_flip($this->currentState->signalTokens());
if (null != $currentToken) {
$this->currentState->process('', $currentToken, $nextToken);
}
+
+ $this->currentSignals = array_flip($this->currentState->signalTokens());
}
/**
diff --git a/src/main/php/lang/reflect/annotation/parser/state/AnnotationParamEnclosedValueState.php b/src/main/php/lang/reflect/annotation/parser/state/AnnotationParamEnclosedValueState.php
index <HASH>..<HASH> 100644
--- a/src/main/php/lang/reflect/annotation/parser/state/AnnotationParamEnclosedValueState.php
+++ b/src/main/php/lang/reflect/annotation/parser/state/AnnotationParamEnclosedValueState.php
@@ -52,7 +52,13 @@ class AnnotationParamEnclosedValueState extends AnnotationAbstractState implemen
*/
public function signalTokens()
{
- return ["'", '"', '\\'];
+ if (null === $this->enclosed) {
+ return ["'", '"', '\\'];
+ } elseif ('"' === $this->enclosed) {
+ return ['"', '\\'];
+ }
+
+ return ["'", '\\'];
}
/**
diff --git a/src/test/php/lang/reflect/annotation/parser/AnnotationStateParserTest.php b/src/test/php/lang/reflect/annotation/parser/AnnotationStateParserTest.php
index <HASH>..<HASH> 100644
--- a/src/test/php/lang/reflect/annotation/parser/AnnotationStateParserTest.php
+++ b/src/test/php/lang/reflect/annotation/parser/AnnotationStateParserTest.php
@@ -388,4 +388,22 @@ class AnnotationStateParserTest extends \PHPUnit_Framework_TestCase
$this->annotationStateParser->setAnnotationParamValue('paramValue');
$this->annotationStateParser->registerSingleAnnotationParam('singleAnnotationValue');
}
+
+ /**
+ * @test
+ * @since 5.5.1
+ */
+ public function foobar()
+ {
+ $annotations = $this->annotationStateParser->parse('/**
+ * a method with an annotation for its parameter
+ *
+ * @Foo(name=\'dum "di" dam\')
+ */',
+ 'target');
+ assertEquals(
+ 'dum "di" dam',
+ $annotations['target']->firstNamed('Foo')->getName()
+ );
+ }
} | fix annotation string values which contained both ' and " | stubbles_stubbles-core | train |
daecda61ef92c3451c8b7e92abfb8372fa16614d | diff --git a/quest-test/src/main/java/it/unibz/krdb/obda/owlrefplatform/owlapi3/SameAsOntowisTest.java b/quest-test/src/main/java/it/unibz/krdb/obda/owlrefplatform/owlapi3/SameAsOntowisTest.java
index <HASH>..<HASH> 100644
--- a/quest-test/src/main/java/it/unibz/krdb/obda/owlrefplatform/owlapi3/SameAsOntowisTest.java
+++ b/quest-test/src/main/java/it/unibz/krdb/obda/owlrefplatform/owlapi3/SameAsOntowisTest.java
@@ -11,7 +11,7 @@ import it.unibz.krdb.obda.owlrefplatform.core.QuestConstants;
import it.unibz.krdb.obda.owlrefplatform.core.QuestPreferences;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.*;
-import org.semanticweb.owlapi.reasoner.SimpleConfiguration;
+
import java.io.*;
import java.util.ArrayList;
@@ -300,13 +300,16 @@ public class SameAsOntowisTest {
* Create the instance of Quest OWL reasoner.
*/
QuestOWLFactory factory = new QuestOWLFactory();
- factory.setOBDAController(obdaModel);
- factory.setPreferenceHolder(preference);
+// factory.setOBDAController(obdaModel);
+// factory.setPreferenceHolder(preference);
+
+ QuestOWLConfiguration config;
+ config = QuestOWLConfiguration.builder().obdaModel(obdaModel).build();
- QuestOWL reasoner = factory.createReasoner(ontology, new SimpleConfiguration());
+ QuestOWL reasoner = factory.createReasoner(ontology,config);
this.reasoner = reasoner;
/*
diff --git a/quest-test/src/test/java/it/unibz/krdb/odba/H2ComplexSameAsTest.java b/quest-test/src/test/java/it/unibz/krdb/odba/H2ComplexSameAsTest.java
index <HASH>..<HASH> 100644
--- a/quest-test/src/test/java/it/unibz/krdb/odba/H2ComplexSameAsTest.java
+++ b/quest-test/src/test/java/it/unibz/krdb/odba/H2ComplexSameAsTest.java
@@ -33,7 +33,6 @@ import org.junit.Test;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyManager;
-import org.semanticweb.owlapi.reasoner.SimpleConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -97,11 +96,12 @@ public class H2ComplexSameAsTest {
// Creating a new instance of the reasoner
QuestOWLFactory factory = new QuestOWLFactory();
- factory.setOBDAController(obdaModel);
+ QuestOWLConfiguration config;
- factory.setPreferenceHolder(p);
+ config = QuestOWLConfiguration.builder().obdaModel(obdaModel).build();
- reasoner = (QuestOWL) factory.createReasoner(ontology, new SimpleConfiguration());
+
+ reasoner = (QuestOWL) factory.createReasoner(ontology, config);
// Now we are ready for querying
conn = reasoner.getConnection();
diff --git a/quest-test/src/test/java/it/unibz/krdb/odba/H2SameAsTest.java b/quest-test/src/test/java/it/unibz/krdb/odba/H2SameAsTest.java
index <HASH>..<HASH> 100644
--- a/quest-test/src/test/java/it/unibz/krdb/odba/H2SameAsTest.java
+++ b/quest-test/src/test/java/it/unibz/krdb/odba/H2SameAsTest.java
@@ -97,11 +97,10 @@ public class H2SameAsTest {
// Creating a new instance of the reasoner
QuestOWLFactory factory = new QuestOWLFactory();
- factory.setOBDAController(obdaModel);
- factory.setPreferenceHolder(p);
+ QuestOWLConfiguration config = QuestOWLConfiguration.builder().obdaModel(obdaModel).build();
- reasoner = (QuestOWL) factory.createReasoner(ontology, new SimpleConfiguration());
+ reasoner = (QuestOWL) factory.createReasoner(ontology, config);
// Now we are ready for querying
conn = reasoner.getConnection(); | update same as test with new quest owl configuration | ontop_ontop | train |
18bead8c560d3f8f1e7c8db6fbbcc403c1be7879 | diff --git a/syndicate/adapters/aio.py b/syndicate/adapters/aio.py
index <HASH>..<HASH> 100644
--- a/syndicate/adapters/aio.py
+++ b/syndicate/adapters/aio.py
@@ -56,7 +56,7 @@ class AioAdapter(base.AdapterBase):
raise KeyError(cookie)
def get_pager(self, *args, **kwargs):
- return AsyncPager(*args, **kwargs)
+ return AioPager(*args, **kwargs)
@asyncio.coroutine
def request(self, method, url, data=None, query=None, callback=None,
@@ -153,7 +153,7 @@ class HeaderAuth(object):
request.headers.update(self.headers)
-class AsyncPager(base.AdapterPager):
+class AioPager(base.AdapterPager):
max_overflow = 1000
@@ -212,3 +212,5 @@ class AsyncPager(base.AdapterPager):
self.waiting.popleft().set_exception(StopIteration())
else:
self.queue_next_page()
+
+pager_class = AioPager # For public reference
diff --git a/syndicate/adapters/requests.py b/syndicate/adapters/requests.py
index <HASH>..<HASH> 100644
--- a/syndicate/adapters/requests.py
+++ b/syndicate/adapters/requests.py
@@ -26,7 +26,7 @@ class RequestsAdapter(base.AdapterBase):
return self.session.cookies.get_dict()[cookie]
def get_pager(self, *args, **kwargs):
- return SyncPager(*args, **kwargs)
+ return RequestsPager(*args, **kwargs)
@property
def auth(self):
@@ -119,7 +119,7 @@ class LoginAuth(requests.auth.AuthBase):
return json.dumps(data)
-class SyncPager(base.AdapterPager):
+class RequestsPager(base.AdapterPager):
length_unset = object() | Rename SyncPager and AsyncPager to RequestsPager and AioPager | mayfield_syndicate | train |
02609625e2af454d7c2da5f19e33604c196500cf | diff --git a/src/Pho/Lib/Graph/ClusterTrait.php b/src/Pho/Lib/Graph/ClusterTrait.php
index <HASH>..<HASH> 100644
--- a/src/Pho/Lib/Graph/ClusterTrait.php
+++ b/src/Pho/Lib/Graph/ClusterTrait.php
@@ -124,7 +124,7 @@ trait ClusterTrait {
*/
public function toArray(): array
{
- return $this->baseToArray();
+ return $this->clusterToArray();
}
/**
@@ -138,7 +138,7 @@ trait ClusterTrait {
*
* @return array The object in array format.
*/
- protected function baseToArray(): array
+ protected function clusterToArray(): array
{
return ["members"=>$this->node_ids];
}
diff --git a/src/Pho/Lib/Graph/EntityTrait.php b/src/Pho/Lib/Graph/EntityTrait.php
index <HASH>..<HASH> 100644
--- a/src/Pho/Lib/Graph/EntityTrait.php
+++ b/src/Pho/Lib/Graph/EntityTrait.php
@@ -108,7 +108,7 @@ trait EntityTrait {
*
* @return array The object in array format.
*/
- protected function baseToArray(): array
+ protected function entityToArray(): array
{
return [
"id" => (string) $this->id,
@@ -121,7 +121,7 @@ trait EntityTrait {
*/
public function toArray(): array
{
- return $this->baseToArray();
+ return $this->entityToArray();
}
/**
diff --git a/src/Pho/Lib/Graph/Node.php b/src/Pho/Lib/Graph/Node.php
index <HASH>..<HASH> 100644
--- a/src/Pho/Lib/Graph/Node.php
+++ b/src/Pho/Lib/Graph/Node.php
@@ -97,7 +97,7 @@ class Node implements EntityInterface, NodeInterface, \SplObserver, \Serializabl
*/
public function toArray(): array
{
- $array = $this->baseToArray();
+ $array = $this->entityToArray();
$array["edge_list"] = $this->edge_list->toArray();
$array["context"] = $this->context_id;
return $array;
diff --git a/src/Pho/Lib/Graph/SubGraph.php b/src/Pho/Lib/Graph/SubGraph.php
index <HASH>..<HASH> 100644
--- a/src/Pho/Lib/Graph/SubGraph.php
+++ b/src/Pho/Lib/Graph/SubGraph.php
@@ -21,9 +21,7 @@ namespace Pho\Lib\Graph;
*/
class SubGraph extends Node implements GraphInterface {
- use ClusterTrait {
- ClusterTrait::baseToArray as clusterToArray;
- }
+ use ClusterTrait;
/**
* {@inheritdoc} | minor bugfix re: serialization | phonetworks_pho-lib-graph | train |
82f03d5ece7aacf178458dfa93e7e85c522944a8 | diff --git a/sharding-jdbc/src/test/java/io/shardingsphere/dbtest/env/authority/AuthorityEnvironmentManager.java b/sharding-jdbc/src/test/java/io/shardingsphere/dbtest/env/authority/AuthorityEnvironmentManager.java
index <HASH>..<HASH> 100644
--- a/sharding-jdbc/src/test/java/io/shardingsphere/dbtest/env/authority/AuthorityEnvironmentManager.java
+++ b/sharding-jdbc/src/test/java/io/shardingsphere/dbtest/env/authority/AuthorityEnvironmentManager.java
@@ -17,8 +17,10 @@
package io.shardingsphere.dbtest.env.authority;
+import com.google.common.base.Preconditions;
import io.shardingsphere.core.constant.DatabaseType;
import io.shardingsphere.dbtest.cases.authority.Authority;
+import lombok.extern.slf4j.Slf4j;
import javax.sql.DataSource;
import javax.xml.bind.JAXBContext;
@@ -34,6 +36,7 @@ import java.util.Collection;
*
* @author panjuan
*/
+@Slf4j
public final class AuthorityEnvironmentManager {
private final Authority authority;
@@ -54,33 +57,41 @@ public final class AuthorityEnvironmentManager {
* Initialize data.
*
*/
- public void initialize() {
+ public void initialize() throws SQLException {
Collection<String> initSQLs = authority.getInitSQLs(databaseType);
if (initSQLs.isEmpty()) {
return;
}
- try (Connection connection = dataSource.getConnection()) {
- for (String each : initSQLs) {
+ Connection connection = dataSource.getConnection();
+ Preconditions.checkState(null != connection, "No available connection.");
+ for (String each : initSQLs) {
+ try {
connection.createStatement().execute(each);
+ } catch (final SQLException ex) {
+ log.warn("Init SQL: "+ex.getMessage());
}
- } catch (final SQLException ignored) {
}
+ connection.close();
}
/**
* Clean data.
*
*/
- public void clean() {
+ public void clean() throws SQLException {
Collection<String> cleanSQLs = authority.getCleanSQLs(databaseType);
if (cleanSQLs.isEmpty()) {
return;
}
- try (Connection connection = dataSource.getConnection()) {
- for (String each : cleanSQLs) {
+ Connection connection = dataSource.getConnection();
+ Preconditions.checkState(null != connection, "No available connection.");
+ for (String each : cleanSQLs) {
+ try {
connection.createStatement().execute(each);
+ } catch (final SQLException ex) {
+ log.warn("Clean SQL: "+ex.getMessage());
}
- } catch (final SQLException ignored) {
}
+ connection.close();
}
} | rewrite initialize() and clean() for not auto closing connection. | apache_incubator-shardingsphere | train |
576ccc5b8013cd2778683eeb8c7f8b943c95c4b5 | diff --git a/clients/core-java/src/main/java/org/commonjava/indy/client/core/IndyClientHttp.java b/clients/core-java/src/main/java/org/commonjava/indy/client/core/IndyClientHttp.java
index <HASH>..<HASH> 100644
--- a/clients/core-java/src/main/java/org/commonjava/indy/client/core/IndyClientHttp.java
+++ b/clients/core-java/src/main/java/org/commonjava/indy/client/core/IndyClientHttp.java
@@ -933,6 +933,9 @@ public class IndyClientHttp
private void addLoggingMDCToHeaders(HttpRequestBase request)
{
Map<String, String> context = MDC.getCopyOfContextMap();
+ if (context == null) {
+ return;
+ }
for (Map.Entry<String, String> mdcKeyHeaderKey : mdcCopyMappings.entrySet())
{
String mdcValue = context.get(mdcKeyHeaderKey.getKey()); | Check for null in AddLoggingMDCToHeaders. | Commonjava_indy | train |
451ed52bb180c8dcbcab5a139b974ca02f08f0a2 | diff --git a/HorizontalPicker/src/main/java/com/wefika/horizontalpicker/HorizontalPicker.java b/HorizontalPicker/src/main/java/com/wefika/horizontalpicker/HorizontalPicker.java
index <HASH>..<HASH> 100644
--- a/HorizontalPicker/src/main/java/com/wefika/horizontalpicker/HorizontalPicker.java
+++ b/HorizontalPicker/src/main/java/com/wefika/horizontalpicker/HorizontalPicker.java
@@ -1191,6 +1191,11 @@ public class HorizontalPicker extends View {
super(superState);
}
+ private SavedState(Parcel in) {
+ super(in);
+ mSelItem = in.readInt();
+ }
+
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
@@ -1205,6 +1210,18 @@ public class HorizontalPicker extends View {
+ " selItem=" + mSelItem
+ "}";
}
+
+ @SuppressWarnings("hiding")
+ public static final Parcelable.Creator<SavedState> CREATOR
+ = new Parcelable.Creator<SavedState>() {
+ public SavedState createFromParcel(Parcel in) {
+ return new SavedState(in);
+ }
+
+ public SavedState[] newArray(int size) {
+ return new SavedState[size];
+ }
+ };
}
private static class PickerTouchHelper extends ExploreByTouchHelper { | Fixing saved state. Fixes #<I> | blazsolar_HorizontalPicker | train |
b75b419058b5005edf71802c44f7e33675081aec | diff --git a/junit/samples/SimpleTest.java b/junit/samples/SimpleTest.java
index <HASH>..<HASH> 100644
--- a/junit/samples/SimpleTest.java
+++ b/junit/samples/SimpleTest.java
@@ -54,8 +54,11 @@ public class SimpleTest extends TestCase {
assertEquals(12, 12);
assertEquals(12L, 12L);
assertEquals(new Long(12), new Long(12));
-
+
assertEquals("Size", 12, 13);
assertEquals("Capacity", 12.0, 11.99, 0.0);
}
+ public static void main (String[] args) {
+ junit.textui.TestRunner.run(suite());
+ }
}
\ No newline at end of file | Added a main to SimpleTest, thanks Lynn Allan | junit-team_junit4 | train |
79ea511df911656926c50f2bbae4553685abd4df | diff --git a/commerce-openapi-admin/src/main/java/com/liferay/commerce/openapi/admin/internal/util/DTOUtils.java b/commerce-openapi-admin/src/main/java/com/liferay/commerce/openapi/admin/internal/util/DTOUtils.java
index <HASH>..<HASH> 100644
--- a/commerce-openapi-admin/src/main/java/com/liferay/commerce/openapi/admin/internal/util/DTOUtils.java
+++ b/commerce-openapi-admin/src/main/java/com/liferay/commerce/openapi/admin/internal/util/DTOUtils.java
@@ -110,7 +110,7 @@ public class DTOUtils {
productDTO.setShortDescription(cpDefinition.getShortDescription());
productDTO.setTitle(cpDefinition.getMetaTitle(locale.getLanguage()));
- return null;
+ return productDTO;
}
public static ProductOptionDTO modelToDTO( | COMMERCE-<I> Return with the constructed object | liferay_com-liferay-commerce | train |
7390a41a5bfd858561d8c453c8c69187d4d7cbbc | diff --git a/cache/refs.go b/cache/refs.go
index <HASH>..<HASH> 100644
--- a/cache/refs.go
+++ b/cache/refs.go
@@ -204,12 +204,24 @@ func (cr *cacheRecord) Mount(ctx context.Context, readonly bool) (snapshot.Mount
return nil, err
}
if cr.viewMount == nil { // TODO: handle this better
- cr.view = identity.NewID()
- m, err := cr.cm.Snapshotter.View(ctx, cr.view, getSnapshotID(cr.md))
+ view := identity.NewID()
+ l, err := cr.cm.LeaseManager.Create(ctx, func(l *leases.Lease) error {
+ l.ID = view
+ l.Labels = map[string]string{
+ "containerd.io/gc.flat": time.Now().UTC().Format(time.RFC3339Nano),
+ }
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ ctx = leases.WithLease(ctx, l.ID)
+ m, err := cr.cm.Snapshotter.View(ctx, view, getSnapshotID(cr.md))
if err != nil {
- cr.view = ""
+ cr.cm.LeaseManager.Delete(context.TODO(), leases.Lease{ID: l.ID})
return nil, errors.Wrapf(err, "failed to mount %s", cr.ID())
}
+ cr.view = view
cr.viewMount = m
}
return cr.viewMount, nil
@@ -421,8 +433,8 @@ func (sr *immutableRef) release(ctx context.Context) error {
if len(sr.refs) == 0 {
if sr.viewMount != nil { // TODO: release viewMount earlier if possible
- if err := sr.cm.Snapshotter.Remove(ctx, sr.view); err != nil {
- return errors.Wrapf(err, "failed to remove view %s", sr.view)
+ if err := sr.cm.LeaseManager.Delete(ctx, leases.Lease{ID: sr.view}); err != nil {
+ return errors.Wrapf(err, "failed to remove view lease %s", sr.view)
}
sr.view = ""
sr.viewMount = nil
@@ -431,7 +443,6 @@ func (sr *immutableRef) release(ctx context.Context) error {
if sr.equalMutable != nil {
sr.equalMutable.release(ctx)
}
- // go sr.cm.GC()
}
return nil | cache: track views with a lease | moby_buildkit | train |
c982165e219cc5763e4dfc02cfc3f01f3bcdc863 | diff --git a/pkutils.py b/pkutils.py
index <HASH>..<HASH> 100644
--- a/pkutils.py
+++ b/pkutils.py
@@ -29,7 +29,7 @@ standard_library.install_aliases()
from os import path as p
-__version__ = '0.6.2'
+__version__ = '0.7.0'
__title__ = 'pkutils'
__author__ = 'Reuben Cummings' | Bump to version <I> | reubano_pkutils | train |
926b1c8c82655353b8b637c3abc2adc1285425c8 | diff --git a/ez_setup.py b/ez_setup.py
index <HASH>..<HASH> 100644
--- a/ez_setup.py
+++ b/ez_setup.py
@@ -36,7 +36,7 @@ try:
except ImportError:
USER_SITE = None
-DEFAULT_VERSION = "9.2"
+DEFAULT_VERSION = "10.0"
DEFAULT_URL = "https://pypi.python.org/packages/source/s/setuptools/"
def _python_cmd(*args):
diff --git a/setuptools/version.py b/setuptools/version.py
index <HASH>..<HASH> 100644
--- a/setuptools/version.py
+++ b/setuptools/version.py
@@ -1 +1 @@
-__version__ = '9.2'
+__version__ = '10.0' | Bumped to <I> in preparation for next release. | pypa_setuptools | train |
07b7d78a8d342bdf38813adfef4ba15603103c8c | diff --git a/src/JWTHelper.php b/src/JWTHelper.php
index <HASH>..<HASH> 100644
--- a/src/JWTHelper.php
+++ b/src/JWTHelper.php
@@ -66,7 +66,8 @@ class JWTHelper
$includes = env('JWT_INCLUDE');
// if (is_null($includes)) throw new \RuntimeException("Please set 'JWT_INCLUDES' in Lumen env file. Ex: id,email,phone");
- $this->includes = is_null($includes) ? [] : explode(",", $includes);
+ $this->includes = is_null($includes) ? ['id'] : explode(",", $includes);
+ if (!in_array('id', $this->includes)) $this->includes[] = 'id'; // always add user id
}
/** | make sure user ID is always added to JWT payload | gboyegadada_lumen-jwt | train |
a5177d16821cf11ef3e53fd8d93cefb2280fcfcb | diff --git a/Swat/SwatContentBlock.php b/Swat/SwatContentBlock.php
index <HASH>..<HASH> 100644
--- a/Swat/SwatContentBlock.php
+++ b/Swat/SwatContentBlock.php
@@ -11,7 +11,7 @@ require_once('Swat/SwatControl.php');
*/
class SwatContentBlock extends SwatControl {
- /*
+ /**
* Text content of the widget.
* @var string
*/
diff --git a/Swat/SwatUI.php b/Swat/SwatUI.php
index <HASH>..<HASH> 100644
--- a/Swat/SwatUI.php
+++ b/Swat/SwatUI.php
@@ -63,14 +63,19 @@ class SwatUI extends SwatObject {
/**
* Retrieve a widget.
* Lookup a widget in the widget tree by name.
- * @return SwatWidget A reference to the widget.
* @param string $name Name of the widget to retrieve.
+ * @param boolean $silent If true, return null instead of throwing an
+ * exception if the widget is not found.
+ * @return SwatWidget A reference to the widget.
*/
- public function getWidget($name) {
+ public function getWidget($name, $silent = false) {
if (array_key_exists($name, $this->widgets))
return $this->widgets[$name];
else
- throw new SwatException(__CLASS__.": no widget named '$name'");
+ if ($silent)
+ return null;
+ else
+ throw new SwatException(__CLASS__.": no widget named '$name'");
}
/** | Add option to supress SwatUI:getWidget() from throwing an exception.
svn commit r<I> | silverorange_swat | train |
fbdf846732427126360d767855407a064611f1aa | diff --git a/src/SAML2/XML/ExtendableElementTrait.php b/src/SAML2/XML/ExtendableElementTrait.php
index <HASH>..<HASH> 100644
--- a/src/SAML2/XML/ExtendableElementTrait.php
+++ b/src/SAML2/XML/ExtendableElementTrait.php
@@ -18,17 +18,17 @@ trait ExtendableElementTrait
*
* Array of extension elements.
*
- * @var \SAML2\XML\md\Extensions
+ * @var \SAML2\XML\md\Extensions|null
*/
- protected $Extensions;
+ protected $Extensions = null;
/**
* Collect the value of the Extensions property.
*
- * @return \SAML2\XML\md\Extensions
+ * @return \SAML2\XML\md\Extensions|null
*/
- public function getExtensions(): Extensions
+ public function getExtensions(): ?Extensions
{
return $this->Extensions;
}
@@ -41,10 +41,6 @@ trait ExtendableElementTrait
*/
protected function setExtensions(?Extensions $extensions): void
{
- if ($extensions === null) {
- return;
- }
-
$this->Extensions = $extensions;
}
} | Extendables don't HAVE to be extended all the time; allow null | simplesamlphp_saml2 | train |
6c97c1cdb8cfd1f7cea314c0acbf35b6928c96cd | diff --git a/src/gl-matrix/quat.js b/src/gl-matrix/quat.js
index <HASH>..<HASH> 100644
--- a/src/gl-matrix/quat.js
+++ b/src/gl-matrix/quat.js
@@ -489,9 +489,9 @@ quat.fromMat3 = function(out, m) {
fRoot = Math.sqrt(fTrace + 1.0); // 2w
out[3] = 0.5 * fRoot;
fRoot = 0.5/fRoot; // 1/(4w)
- out[0] = (m[7]-m[5])*fRoot;
- out[1] = (m[2]-m[6])*fRoot;
- out[2] = (m[3]-m[1])*fRoot;
+ out[0] = (m[5]-m[7])*fRoot;
+ out[1] = (m[6]-m[2])*fRoot;
+ out[2] = (m[1]-m[3])*fRoot;
} else {
// |w| <= 1/2
var i = 0;
@@ -505,7 +505,7 @@ quat.fromMat3 = function(out, m) {
fRoot = Math.sqrt(m[i*3+i]-m[j*3+j]-m[k*3+k] + 1.0);
out[i] = 0.5 * fRoot;
fRoot = 0.5 / fRoot;
- out[3] = (m[k*3+j] - m[j*3+k]) * fRoot;
+ out[3] = (m[j*3+k] - m[k*3+j]) * fRoot;
out[j] = (m[j*3+i] + m[i*3+j]) * fRoot;
out[k] = (m[k*3+i] + m[i*3+k]) * fRoot;
} | fix issue #<I>
quat.fromMat3() return wrong (transposed) quaternion.
fixed this. | toji_gl-matrix | train |
8f3b88da5fbc63babf71e29a2a12d2a1e847c5f0 | diff --git a/shellen/shell.py b/shellen/shell.py
index <HASH>..<HASH> 100644
--- a/shellen/shell.py
+++ b/shellen/shell.py
@@ -6,7 +6,7 @@ import shellen_native as native
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.shortcuts import prompt
-from prompt_toolkit.styles import style_from_pygments, style_from_dict
+from prompt_toolkit.styles import style_from_pygments_dict
from pygments.token import Token
@@ -78,7 +78,7 @@ class Shellen(CLI):
self.asm_history = InMemoryHistory()
self.dsm_history = InMemoryHistory()
- self.prompt_style = style_from_dict({
+ self.prompt_style = style_from_pygments_dict({
Token: '#ff0066',
Token.OS: '#ff3838',
Token.Colon: '#ffffff',
@@ -94,16 +94,16 @@ class Shellen(CLI):
return self.dsm_history
def prompt(self):
- def get_prompt_tokens(cli):
- return [
- (Token.OS, OS_MATCHING[self.os]),
- (Token.Colon, ':'),
- (Token.Mode, self.mode),
- (Token.Colon, ':'),
- (Token.Arch, self.pexec.arch),
- (Token.Pound, ' > ')
- ]
- return prompt(get_prompt_tokens=get_prompt_tokens, style=self.prompt_style, history=self.__get_history())
+ message = [
+ ('class:pygments.os', OS_MATCHING[self.os]),
+ ('class:pygments.colon', ':'),
+ ('class:pygments.mode', self.mode),
+ ('class:pygments.colon', ':'),
+ ('class:pygments.arch', self.pexec.arch),
+ ('class:pygments.pound', ' > ')
+ ]
+
+ return prompt(message, style=self.prompt_style, history=self.__get_history())
def __create_handlers(self):
self.handlers = { | Fix ImportErorr due to prompt_toolkit upgrade | merrychap_shellen | train |
673577d8edceb34f43a52b755eb8bbc6c08d095c | diff --git a/lib/node_modules/@stdlib/math/base/special/gammaincinv/test/test.js b/lib/node_modules/@stdlib/math/base/special/gammaincinv/test/test.js
index <HASH>..<HASH> 100644
--- a/lib/node_modules/@stdlib/math/base/special/gammaincinv/test/test.js
+++ b/lib/node_modules/@stdlib/math/base/special/gammaincinv/test/test.js
@@ -98,7 +98,6 @@ tape( 'the function returns `NaN` if provided `p` outside the interval `[0,1]`',
t.end();
});
-
tape( 'the function returns `0` if provided `p = 1`', function test( t ) {
var val;
var a;
diff --git a/lib/node_modules/@stdlib/math/base/special/gammaln/test/test.js b/lib/node_modules/@stdlib/math/base/special/gammaln/test/test.js
index <HASH>..<HASH> 100644
--- a/lib/node_modules/@stdlib/math/base/special/gammaln/test/test.js
+++ b/lib/node_modules/@stdlib/math/base/special/gammaln/test/test.js
@@ -44,20 +44,19 @@ tape( 'the function returns `infinity` when provided `infinity`', function test(
t.end();
});
-tape( 'the function returns `+infinity` when provided `0`' , function test( t ) {
+tape( 'the function returns `+infinity` when provided `0`', function test( t ) {
var v = gammaln( 0.0 );
t.equal( v, PINF, 'returns +Inf when provided 0' );
t.end();
});
-tape( 'the function returns `+infinity` for x smaller than `-2^52`' , function test( t ) {
- var v = gammaln( -pow( 2.0, 53 ) );
+tape( 'the function returns `+infinity` for x smaller than `-2^52`', function test( t ) {
+ var v = gammaln( -pow( 2.0, 53 ) );
t.equal( v, PINF, 'returns +Inf when provided 2^53' );
t.end();
});
-
-tape( 'the function returns `-ln(x)` for very small x' , function test( t ) {
+tape( 'the function returns `-ln(x)` for very small x', function test( t ) {
var x;
var v; | Remove extra lines and fix lint errors | stdlib-js_stdlib | train |
b724e4323ccbc4bd96a501b80faf24295e9e7e1e | diff --git a/robolectric/src/test/java/org/robolectric/shadows/ShadowNonAppLibraryTest.java b/robolectric/src/test/java/org/robolectric/shadows/ShadowNonAppLibraryTest.java
index <HASH>..<HASH> 100644
--- a/robolectric/src/test/java/org/robolectric/shadows/ShadowNonAppLibraryTest.java
+++ b/robolectric/src/test/java/org/robolectric/shadows/ShadowNonAppLibraryTest.java
@@ -2,39 +2,41 @@ package org.robolectric.shadows;
import static org.assertj.core.api.Assertions.assertThat;
+import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.robolectric.MultiApiRobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.TestApplication;
import org.robolectric.TestRunners;
import org.robolectric.annotation.Config;
@Config(manifest = Config.NONE)
-@RunWith(TestRunners.MultiApiWithDefaults.class)
+@RunWith(MultiApiRobolectricTestRunner.class)
public class ShadowNonAppLibraryTest {
@Test public void shouldStillCreateAnApplication() throws Exception {
- assertThat(RuntimeEnvironment.application).isExactlyInstanceOf(TestApplication.class);
+ assertThat(RuntimeEnvironment.application).isExactlyInstanceOf(Application.class);
}
@Test public void applicationShouldHaveSomeReasonableConfig() throws Exception {
- assertThat(RuntimeEnvironment.application.getPackageName()).isEqualTo("org.robolectric");
+ assertThat(RuntimeEnvironment.application.getPackageName()).isEqualTo("org.robolectric.default");
}
@Test public void shouldHaveDefaultPackageInfo() throws Exception {
- PackageInfo packageInfo = RuntimeEnvironment.getPackageManager().getPackageInfo("org.robolectric", 0);
+ PackageInfo packageInfo = RuntimeEnvironment.getPackageManager().getPackageInfo("org.robolectric.default", 0);
assertThat(packageInfo).isNotNull();
ApplicationInfo applicationInfo = packageInfo.applicationInfo;
assertThat(applicationInfo).isNotNull();
- assertThat(applicationInfo.packageName).isEqualTo("org.robolectric");
+ assertThat(applicationInfo.packageName).isEqualTo("org.robolectric.default");
}
@Test public void shouldCreatePackageContext() throws Exception {
- Context packageContext = RuntimeEnvironment.application.createPackageContext("org.robolectric", 0);
+ Context packageContext = RuntimeEnvironment.application.createPackageContext("org.robolectric.default", 0);
assertThat(packageContext).isNotNull();
}
} | Fix test.
Test class @Config(manifest=...) is ineffective with TestRunners.MultiApiWithDefaults. | robolectric_robolectric | train |
bad2c9f18d5038c9b6377c916dec2f46cc500479 | diff --git a/builtin/providers/openstack/resource_openstack_compute_instance_v2.go b/builtin/providers/openstack/resource_openstack_compute_instance_v2.go
index <HASH>..<HASH> 100644
--- a/builtin/providers/openstack/resource_openstack_compute_instance_v2.go
+++ b/builtin/providers/openstack/resource_openstack_compute_instance_v2.go
@@ -673,34 +673,43 @@ func getFloatingIPs(networkingClient *gophercloud.ServiceClient) ([]floatingips.
}
func getImageID(client *gophercloud.ServiceClient, d *schema.ResourceData) (string, error) {
- imageID := d.Get("image_id").(string)
+ imageId := d.Get("image_id").(string)
imageName := d.Get("image_name").(string)
- if imageID == "" {
- pager := images.ListDetail(client, nil)
+ imageCount := 0
+ if imageId == "" && imageName != "" {
+ pager := images.ListDetail(client, &images.ListOpts{
+ Name: imageName,
+ })
pager.EachPage(func(page pagination.Page) (bool, error) {
imageList, err := images.ExtractImages(page)
-
if err != nil {
return false, err
}
for _, i := range imageList {
if i.Name == imageName {
- imageID = i.ID
+ imageCount++
+ imageId = i.ID
}
}
return true, nil
})
- if imageID == "" {
- return "", fmt.Errorf("Unable to find image: %v", imageName)
+ switch imageCount {
+ case 0:
+ return "", fmt.Errorf("Unable to find image: %s", imageName)
+ case 1:
+ return imageId, nil
+ default:
+ return "", fmt.Errorf("Found %d images matching %s", imageCount, imageName)
}
}
- if imageID == "" && imageName == "" {
+ if imageId == "" && imageName == "" {
return "", fmt.Errorf("Neither an image ID nor an image name were able to be determined.")
}
- return imageID, nil
+ return imageId, nil
+
} | Accounting for multiple results of an image name
If multiple results are found, an error will be returned to the user. | hashicorp_terraform | train |
689817ca20ac3c8eebdd95ad422297f16dba93b6 | diff --git a/salt/states/file.py b/salt/states/file.py
index <HASH>..<HASH> 100644
--- a/salt/states/file.py
+++ b/salt/states/file.py
@@ -580,8 +580,8 @@ def _test_owner(kwargs, user=None):
return user
-def _unify_sources_and_hashes(source=None,source_hash=None,
- sources=[],source_hashes=[]):
+def _unify_sources_and_hashes(source=None, source_hash=None,
+ sources=[], source_hashes=[]):
'''
Silly lil function to give us a standard tuple list for sources and
source_hashes
@@ -590,12 +590,12 @@ def _unify_sources_and_hashes(source=None,source_hash=None,
return (False,
"source and sources are mutally exclusive", [] )
- if ( source_hash and sources_hash ):
+ if ( source_hash and source_hashes ):
return (False,
"source_hash and source_hashes are mutally exclusive", [] )
if ( source ):
- return (True,'', [ (source,source_hash) ] )
+ return (True, '', [ (source,source_hash) ] )
# Make a nice neat list of tuples exactly len(sources) long..
return (True, '', map(None, sources, source_hashes[:len(sources)]) ) | Fix typo - its 'source_hashes' not 'soures_hash' | saltstack_salt | train |
630f3026b32a2f08e388097dffad4696ae1e7195 | diff --git a/src/view/MainViewManager.js b/src/view/MainViewManager.js
index <HASH>..<HASH> 100644
--- a/src/view/MainViewManager.js
+++ b/src/view/MainViewManager.js
@@ -25,12 +25,12 @@
/*global define, $ */
/**
- * MainViewManager Manages the arrangement of all open panes as well as provides the controller
+ * MainViewManager manages the arrangement of all open panes as well as provides the controller
* logic behind all views in the MainView (e.g. ensuring that a file doesn't appear in 2 lists)
*
* Each pane contains one or more views wich are created by a view factory and inserted into a pane list.
- * There may be several panes managed by the MainViewManager with each pane containing a list of views.
- * The panes are always visible and the layout is determined by the MainViewManager and the user.
+ * There may be several panes managed by the MainViewManager with each pane containing a list of views.
+ * The panes are always visible and the layout is determined by the MainViewManager and the user.
*
* Currently we support only 2 panes.
*
@@ -354,7 +354,7 @@ define(function (require, exports, module) {
/**
* Makes the Pane's current file the most recent
- * @param {!string} paneId - id of the pane to mae th file most recent or ACTIVE_PANE
+ * @param {!string} paneId - id of the pane to make the file most recent, or ACTIVE_PANE
* @param {!File} file - File object to make most recent
* @private
*/
@@ -367,7 +367,7 @@ define(function (require, exports, module) {
}
/**
- * Switch active pane to the specified pane Id (or ACTIVE_PANE/ALL_PANES, in which case this
+ * Switch active pane to the specified pane id (or ACTIVE_PANE/ALL_PANES, in which case this
* call does nothing).
* @param {!string} paneId - the id of the pane to activate
*/
@@ -515,7 +515,7 @@ define(function (require, exports, module) {
/**
- * Retrieves the WorkingSet for the given PaneId not including temporary views
+ * Retrieves the WorkingSet for the given paneId not including temporary views
* @param {!string} paneId - id of the pane in which to get the view list, ALL_PANES or ACTIVE_PANE
* @return {Array.<File>}
*/
@@ -532,7 +532,7 @@ define(function (require, exports, module) {
/**
- * Retrieves the list of all open files inlcuding temporary views
+ * Retrieves the list of all open files including temporary views
* @return {array.<File>} the list of all open files in all open panes
*/
function getAllOpenFiles() {
@@ -916,8 +916,8 @@ define(function (require, exports, module) {
/**
* Get the next or previous file in the MRU list.
* @param {!number} direction - Must be 1 or -1 to traverse forward or backward
- * @return {?{file:File, paneId:string}} The File object of the next item in the travesal order or null if there aren't any files to traverse.
- * may return current file if there are no other files to traverse.
+ * @return {?{file:File, paneId:string}} The File object of the next item in the traversal order or null if there aren't any files to traverse.
+ * May return current file if there are no other files to traverse.
*/
function traverseToNextViewByMRU(direction) {
var file = getCurrentlyViewedFile(), | Fix several typos in MainViewManager docs | adobe_brackets | train |
1d3e8e21722d7354f77ebd0c8b19855e7a8045c6 | diff --git a/extension.py b/extension.py
index <HASH>..<HASH> 100644
--- a/extension.py
+++ b/extension.py
@@ -103,10 +103,11 @@ class Extension:
optional=None,
**kw # To catch unknown keywords
):
- assert isinstance(name, str), "'name' must be a string"
- assert (isinstance(sources, list) and
- all(isinstance(v, str) for v in sources)), \
- "'sources' must be a list of strings"
+ if not isinstance(name, str):
+ raise AssertionError("'name' must be a string")
+ if not (isinstance(sources, list) and
+ all(isinstance(v, str) for v in sources)):
+ raise AssertionError("'sources' must be a list of strings")
self.name = name
self.sources = sources | Issue #<I>: Removed assert statements in distutils.Extension, so the behavior is similar when used with -O | pypa_setuptools | train |
9d225fa7a82e916e5e330661cf1652979c523b11 | diff --git a/src/Page/PageQuery.php b/src/Page/PageQuery.php
index <HASH>..<HASH> 100644
--- a/src/Page/PageQuery.php
+++ b/src/Page/PageQuery.php
@@ -52,7 +52,7 @@ class PageQuery
// Cleanup request and query string input, normalize using allowed
// values from current datasource filter and base query
if ($baseQuery) {
- $this->query = $this->filterQueryWithBaseQuery($this->query, $baseQuery);
+ $this->query = $this->mergeQueries([$baseQuery, $this->filterQueryWithBaseQuery($this->query, $baseQuery)]);
}
if ($this->search) { | properly merge request, filter and base queries | makinacorpus_drupal-calista | train |
01d1a19ba38a236ae7d2f292a31f8515e118ae51 | diff --git a/src/main/java/com/annimon/stream/Stream.java b/src/main/java/com/annimon/stream/Stream.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/annimon/stream/Stream.java
+++ b/src/main/java/com/annimon/stream/Stream.java
@@ -557,11 +557,25 @@ public class Stream<T> {
* @return the new stream
*/
public Stream<T> distinct() {
- final Set<T> set = new HashSet<T>();
- while (iterator.hasNext()) {
- set.add(iterator.next());
- }
- return new Stream<T>(set);
+ return new Stream<T>(new LsaExtIterator<T>() {
+
+ private Iterator<T> distinctIterator;
+
+ @Override
+ protected void nextIteration() {
+ if (!isInit) {
+ final Set<T> set = new HashSet<T>();
+ while (iterator.hasNext()) {
+ set.add(iterator.next());
+ }
+ distinctIterator = set.iterator();
+ }
+ hasNext = distinctIterator.hasNext();
+ if (hasNext) {
+ next = distinctIterator.next();
+ }
+ }
+ });
}
/**
@@ -594,10 +608,24 @@ public class Stream<T> {
* @param comparator the {@code Comparator} to compare elements
* @return the new stream
*/
- public Stream<T> sorted(Comparator<? super T> comparator) {
- final List<T> list = collectToList();
- Collections.sort(list, comparator);
- return new Stream<T>(list);
+ public Stream<T> sorted(final Comparator<? super T> comparator) {
+ return new Stream<T>(new LsaExtIterator<T>() {
+
+ private Iterator<T> sortedIterator;
+
+ @Override
+ protected void nextIteration() {
+ if (!isInit) {
+ final List<T> list = collectToList();
+ Collections.sort(list, comparator);
+ sortedIterator = list.iterator();
+ }
+ hasNext = sortedIterator.hasNext();
+ if (hasNext) {
+ next = sortedIterator.next();
+ }
+ }
+ });
}
/**
diff --git a/src/test/java/com/annimon/stream/StreamTest.java b/src/test/java/com/annimon/stream/StreamTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/com/annimon/stream/StreamTest.java
+++ b/src/test/java/com/annimon/stream/StreamTest.java
@@ -360,6 +360,19 @@ public class StreamTest {
}
@Test
+ public void testDistinctLazy() {
+ List<Integer> expected = Arrays.asList(-1, 1, 2, 3, 5);
+
+ List<Integer> input = new ArrayList<Integer>(10);
+ input.addAll(Arrays.asList(1, 1, 2, 3, 5));
+ Stream<Integer> stream = Stream.of(input).distinct().sorted();
+ input.addAll(Arrays.asList(3, 2, 1, 1, -1));
+
+ List<Integer> data = stream.collect(Collectors.<Integer>toList());
+ assertThat(data, is(expected));
+ }
+
+ @Test
public void testSorted() {
List<Integer> expected = Arrays.asList(-7, 0, 3, 6, 9, 19);
List<Integer> data = Stream.of(6, 3, 9, 0, -7, 19)
@@ -369,6 +382,19 @@ public class StreamTest {
}
@Test
+ public void testSortedLazy() {
+ List<Integer> expected = Arrays.asList(-7, 0, 3, 6, 9, 19);
+
+ List<Integer> input = new ArrayList<Integer>(6);
+ input.addAll(Arrays.asList(6, 3, 9));
+ Stream<Integer> stream = Stream.of(input).sorted();
+ input.addAll(Arrays.asList(0, -7, 19));
+
+ List<Integer> data = stream.collect(Collectors.<Integer>toList());
+ assertThat(data, is(expected));
+ }
+
+ @Test
public void testSortedWithComparator() {
List<Integer> expected = Arrays.asList(19, 9, -7, 6, 3, 0);
List<Integer> data = Stream.of(6, 3, 9, 0, -7, 19) | Fix Stream.sorted and Stream.distinct laziness | aNNiMON_Lightweight-Stream-API | train |
a979b91b27d6533db8c02862c73b79aec3f065df | diff --git a/routing/payment_lifecycle.go b/routing/payment_lifecycle.go
index <HASH>..<HASH> 100644
--- a/routing/payment_lifecycle.go
+++ b/routing/payment_lifecycle.go
@@ -13,20 +13,6 @@ import (
"github.com/lightningnetwork/lnd/routing/route"
)
-// errNoRoute is returned when all routes from the payment session have been
-// attempted.
-type errNoRoute struct {
- // lastError is the error encountered during the last payment attempt,
- // if at least one attempt has been made.
- lastError error
-}
-
-// Error returns a string representation of the error.
-func (e errNoRoute) Error() string {
- return fmt.Sprintf("unable to route payment to destination: %v",
- e.lastError)
-}
-
// paymentLifecycle holds all information about the current state of a payment
// needed to resume if from any point.
type paymentLifecycle struct {
@@ -146,14 +132,6 @@ func (p *paymentLifecycle) resumePayment() ([32]byte, *route.Route, error) {
return [32]byte{}, nil, saveErr
}
- // If there was an error already recorded for this
- // payment, we'll return that.
- if shardHandler.lastError != nil {
- return [32]byte{}, nil, errNoRoute{
- lastError: shardHandler.lastError,
- }
- }
-
// Terminal state, return.
return [32]byte{}, nil, err
}
@@ -232,8 +210,6 @@ func (p *paymentLifecycle) resumePayment() ([32]byte, *route.Route, error) {
type shardHandler struct {
paymentHash lntypes.Hash
router *ChannelRouter
-
- lastError error
}
// launchOutcome is a type returned from launchShard that indicates whether the
@@ -542,9 +518,6 @@ func (p *shardHandler) handleSendError(attempt *channeldb.HTLCAttemptInfo,
attempt.AttemptID, &attempt.Route, sendErr,
)
if reason == nil {
- // Save the forwarding error so it can be returned if
- // this turns out to be the last attempt.
- p.lastError = sendErr
return nil
}
diff --git a/routing/router_test.go b/routing/router_test.go
index <HASH>..<HASH> 100644
--- a/routing/router_test.go
+++ b/routing/router_test.go
@@ -792,10 +792,33 @@ func TestSendPaymentErrorPathPruning(t *testing.T) {
// The final error returned should also indicate that the peer wasn't
// online (the last error we returned).
- if !strings.Contains(err.Error(), "UnknownNextPeer") {
+ // TODO: proper err code
+ if !strings.Contains(err.Error(), "unable to find") {
t.Fatalf("expected UnknownNextPeer instead got: %v", err)
}
+ // Inspect the two attempts that were made before the payment failed.
+ p, err := ctx.router.cfg.Control.FetchPayment(payHash)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if len(p.HTLCs) != 2 {
+ t.Fatalf("expected two attempts got %v", len(p.HTLCs))
+ }
+
+ // We expect the first attempt to have failed with a
+ // TemporaryChannelFailure, the second with UnknownNextPeer.
+ msg := p.HTLCs[0].Failure.Message
+ if _, ok := msg.(*lnwire.FailTemporaryChannelFailure); !ok {
+ t.Fatalf("unexpected fail message: %T", msg)
+ }
+
+ msg = p.HTLCs[1].Failure.Message
+ if _, ok := msg.(*lnwire.FailUnknownNextPeer); !ok {
+ t.Fatalf("unexpected fail message: %T", msg)
+ }
+
ctx.router.cfg.MissionControl.(*MissionControl).ResetHistory()
// Next, we'll modify the SendToSwitch method to indicate that the | routing: remove errNoRoute and lastError
Now that SendToRoute is no longer using the payment lifecycle, we
remove the error structs and vars used to cache the last encountered
error. For SendToRoute this will now be returned directly after a shard
has failed.
For SendPayment this means that the last error encountered durinng
pathfinding no longer will be returned. All errors encounterd can
instead be inspected from the HTLC list. | lightningnetwork_lnd | train |
844a9e1fa4be30a1785dff2c25f4b0f5395113b9 | diff --git a/generator/parser.go b/generator/parser.go
index <HASH>..<HASH> 100644
--- a/generator/parser.go
+++ b/generator/parser.go
@@ -18,11 +18,12 @@
package generator
import (
- "errors"
"fmt"
"go/ast"
+ "go/doc"
"go/parser"
"go/token"
+ "regexp"
)
type StructField struct {
@@ -42,23 +43,25 @@ func NewStructInfo(name string) *StructInfo {
}
}
+var skipre = regexp.MustCompile("(.*)ffjson:(\\s*)((skip)|(ignore))(.*)")
+
func ExtractStructs(inputPath string) (string, []*StructInfo, error) {
fset := token.NewFileSet()
- f, err := parser.ParseFile(fset, inputPath, nil, 0)
+ f, err := parser.ParseFile(fset, inputPath, nil, parser.ParseComments)
if err != nil {
return "", nil, err
}
packageName := f.Name.String()
- structs := make([]*StructInfo, 0)
+ structs := make(map[string]*StructInfo)
for k, d := range f.Scope.Objects {
if d.Kind == ast.Typ {
ts, ok := d.Decl.(*ast.TypeSpec)
if !ok {
- return "", nil, errors.New(fmt.Sprintf("Unknown type without TypeSec: %v", d))
+ return "", nil, fmt.Errorf("Unknown type without TypeSec: %v", d)
}
_, ok = ts.Type.(*ast.StructType)
@@ -69,9 +72,26 @@ func ExtractStructs(inputPath string) (string, []*StructInfo, error) {
// TODO(pquerna): Add // ffjson:skip or similiar tagging.
stobj := NewStructInfo(k)
- structs = append(structs, stobj)
+ structs[k] = stobj
+ }
+ }
+
+ files := map[string]*ast.File{
+ inputPath: f,
+ }
+
+ pkg, _ := ast.NewPackage(fset, files, nil, nil)
+
+ d := doc.New(pkg, f.Name.String(), doc.AllDecls)
+ for _, t := range d.Types {
+ if skipre.MatchString(t.Doc) {
+ delete(structs, t.Name)
}
}
- return packageName, structs, nil
+ rv := make([]*StructInfo, 0)
+ for _, v := range structs {
+ rv = append(rv, v)
+ }
+ return packageName, rv, nil
}
diff --git a/inception/reflect.go b/inception/reflect.go
index <HASH>..<HASH> 100644
--- a/inception/reflect.go
+++ b/inception/reflect.go
@@ -18,9 +18,10 @@
package ffjsoninception
import (
+ fflib "github.com/pquerna/ffjson/fflib/v1"
+
"bytes"
"encoding/json"
- fflib "github.com/pquerna/ffjson/fflib/v1"
"reflect"
"sort"
) | Add support for an "ffjson: skip" comment to mark a struct as something ffjson should ignore | pquerna_ffjson | train |
90897f469e5f76212dc338b1aee74320f7353b48 | diff --git a/bitex/api/api.py b/bitex/api/api.py
index <HASH>..<HASH> 100644
--- a/bitex/api/api.py
+++ b/bitex/api/api.py
@@ -38,31 +38,39 @@ class RESTAPI:
"""
Dummy Signature creation method. Override this in child.
Returned dict must have keywords usable by requests.get or requests.post
+ URL is required to be returned, as some Signatures use the url for
+ sig generation, and api calls made must match the address exactly.
"""
- return kwargs
+ return url, kwargs
def query(self, endpoint, authenticate=False, request_method=requests.get,
*args, **kwargs):
"""
Queries exchange using given data. Defaults to unauthenticated GET query.
"""
- print(endpoint, authenticate, request_method, args, kwargs)
if self.apiversion:
urlpath = '/' + self.apiversion + '/' + endpoint
else:
urlpath = '/' + endpoint
+ print(endpoint, authenticate, request_method, args, kwargs)
+
if authenticate: # Pass all locally vars to sign(); Sorting left to children
kwargs['urlpath'] = urlpath
- kwargs = self.sign(endpoint, *args, **kwargs)
+ url, kwargs = self.sign(endpoint, *args, **kwargs)
+ else:
+ url = self.uri + urlpath
- url = self.uri + urlpath
print(url)
-
r = request_method(url, timeout=5, **kwargs)
return r
+
+
+
+
+
diff --git a/bitex/api/bitfinex.py b/bitex/api/bitfinex.py
index <HASH>..<HASH> 100644
--- a/bitex/api/bitfinex.py
+++ b/bitex/api/bitfinex.py
@@ -47,6 +47,7 @@ class API(RESTAPI):
headers = {"X-BFX-APIKEY": self.key,
"X-BFX-SIGNATURE": signature,
"X-BFX-PAYLOAD": data}
+ url = self.uri + kwargs['urlpath']
- return {'headers': headers}
+ return url, {'headers': headers}
diff --git a/bitex/api/bitstamp.py b/bitex/api/bitstamp.py
index <HASH>..<HASH> 100644
--- a/bitex/api/bitstamp.py
+++ b/bitex/api/bitstamp.py
@@ -56,5 +56,5 @@ class API(RESTAPI):
req['nonce'] = nonce
req['signature'] = signature
print(req)
-
- return {'data': req}
+ url = self.uri + kwargs['urlpath']
+ return url, {'data': req}
diff --git a/bitex/api/bittrex.py b/bitex/api/bittrex.py
index <HASH>..<HASH> 100644
--- a/bitex/api/bittrex.py
+++ b/bitex/api/bittrex.py
@@ -20,9 +20,8 @@ log = logging.getLogger(__name__)
class API(RESTAPI):
- def __init__(self, user_id='', key='', secret='', api_version='v1.1',
+ def __init__(self, key='', secret='', api_version='v1.1',
url='https://bittrex.com/api'):
- self.id = user_id
super(API, self).__init__(url, api_version=api_version, key=key,
secret=secret)
@@ -39,11 +38,7 @@ class API(RESTAPI):
req_string = urlpath + '?apikey=' + self.key + "&nonce=" + nonce + '&'
req_string += urllib.parse.urlencode(params)
- params['apikey'] = self.key
- params['nonce'] = nonce
-
headers = {"apisign": hmac.new(self.secret.encode(), req_string.encode(),
hashlib.sha512).hexdigest()}
- requests.get(urlpath, params=params, headers=headers)
- return {'headers': headers, 'params': params}
+ return req_string, {'headers': headers, 'params': {}}
diff --git a/bitex/api/coincheck.py b/bitex/api/coincheck.py
index <HASH>..<HASH> 100644
--- a/bitex/api/coincheck.py
+++ b/bitex/api/coincheck.py
@@ -156,5 +156,5 @@ class _API(RESTAPI):
headers = {"ACCESS-KEY": self.key,
"ACCESS-NONCE": nonce,
"ACCESS-SIGNATURE": signature}
-
- return {'headers': headers}
+ url = self.uri + kwargs['urlpath']
+ return url, {'headers': headers}
diff --git a/bitex/api/gdax.py b/bitex/api/gdax.py
index <HASH>..<HASH> 100644
--- a/bitex/api/gdax.py
+++ b/bitex/api/gdax.py
@@ -68,4 +68,6 @@ class API(RESTAPI):
except KeyError:
js = {}
- return {'json': js, 'auth': auth}
+ url = self.uri + kwargs['urlpath']
+
+ return url, {'json': js, 'auth': auth}
diff --git a/bitex/api/kraken.py b/bitex/api/kraken.py
index <HASH>..<HASH> 100644
--- a/bitex/api/kraken.py
+++ b/bitex/api/kraken.py
@@ -45,4 +45,6 @@ class API(RESTAPI):
'API-Sign': sigdigest.decode()
}
- return {'data': req, 'headers': headers}
\ No newline at end of file
+ url = self.uri + kwargs['urlpath']
+
+ return url, {'data': req, 'headers': headers}
\ No newline at end of file | added url to returned args for sig, generalize call furhter | Crypto-toolbox_bitex | train |
27f550f72b4e1b52e232ade9d181f1b3166ed743 | diff --git a/src/ElasticaExtraBundle/Command/ListAliasCommand.php b/src/ElasticaExtraBundle/Command/ListAliasCommand.php
index <HASH>..<HASH> 100644
--- a/src/ElasticaExtraBundle/Command/ListAliasCommand.php
+++ b/src/ElasticaExtraBundle/Command/ListAliasCommand.php
@@ -46,7 +46,7 @@ class ListAliasCommand extends ElasticaAwareCommand
;
foreach ($aliases as $alias) {
- $output->writeln(' * ' . $alias);
+ $output->writeln(' * '.$alias);
}
}
} | Scrutinizer Auto-Fixes
This commit consists of patches automatically generated for this project on <URL> | gbprod_elastica-extra-bundle | train |
6f11d298eee5bbdff6403e4443490f04e99b467e | diff --git a/networkdb/delegate.go b/networkdb/delegate.go
index <HASH>..<HASH> 100644
--- a/networkdb/delegate.go
+++ b/networkdb/delegate.go
@@ -228,7 +228,8 @@ func (nDB *NetworkDB) handleTableEvent(tEvent *TableEvent) bool {
// If it is a delete event and we did not have a state for it, don't propagate to the application
// If the residual reapTime is lower or equal to 1/6 of the total reapTime don't bother broadcasting it around
// most likely the cluster is already aware of it, if not who will sync with this node will catch the state too.
- return e.reapTime > reapPeriod/6
+ // This also avoids that deletion of entries close to their garbage collection ends up circuling around forever
+ return e.reapTime > reapEntryInterval/6
}
var op opType | Fix comparison against wrong constant
The comparison was against the wrong constant value.
As described in the comment the check is there to guarantee
to not propagate events realted to stale deleted elements | docker_libnetwork | train |
07dde2ed3ab97aba979fd6c6ce8be20894ab3d99 | diff --git a/lib/packetgen/capture.rb b/lib/packetgen/capture.rb
index <HASH>..<HASH> 100644
--- a/lib/packetgen/capture.rb
+++ b/lib/packetgen/capture.rb
@@ -42,7 +42,7 @@ module PacketGen
@pcap = PCAPRUB::Pcap.open_live(@iface, @snaplen, @promisc, 1)
set_filter
- cap_thread = Thread.new do
+ @cap_thread = Thread.new do
@pcap.each do |packet_data|
@raw_packets << packet_data
if @parse
@@ -57,7 +57,16 @@ module PacketGen
end
end
end
- cap_thread.join(@timeout)
+ @cap_thread.join(@timeout)
+ end
+
+ # Stop capture. Should be used from another thread, as {#start} blocs.
+ #
+ # BEWARE: multiple capture should not be started in different threads. No effort
+ # has been made to make Capture nor PacketGen thread-safe.
+ # @return [void]
+ def stop
+ @cap_thread.kill
end
private
diff --git a/spec/support/capture_helper.rb b/spec/support/capture_helper.rb
index <HASH>..<HASH> 100644
--- a/spec/support/capture_helper.rb
+++ b/spec/support/capture_helper.rb
@@ -7,7 +7,8 @@ module CaptureHelper
cap_thread = Thread.new { cap.start }
sleep 0.1
blk.call
- cap_thread.join(timeout * 2 + 1)
+ sleep timeout + 2
+ cap.stop
cap
end | Add Capture#stop to ease writing specs. | sdaubert_packetgen | train |
28ead6c9b7ee8869667e3601ae7e43cdbe59b968 | diff --git a/opal/browser/dom/builder.rb b/opal/browser/dom/builder.rb
index <HASH>..<HASH> 100644
--- a/opal/browser/dom/builder.rb
+++ b/opal/browser/dom/builder.rb
@@ -137,7 +137,13 @@ class Builder < BasicObject
def extend!(element = nil, &block)
old, @current = @current, element
- block.call(self)
+
+ result = block.call(self)
+
+ if String === result
+ @current.inner_html = result
+ end
+
@current = old
self | dom/builder: properly set inner_html with #extend! | opal_opal-browser | train |
c2e4e93862a0a52da471ace7bc4198f14f20813e | diff --git a/lib/gov_kit/resource.rb b/lib/gov_kit/resource.rb
index <HASH>..<HASH> 100644
--- a/lib/gov_kit/resource.rb
+++ b/lib/gov_kit/resource.rb
@@ -46,16 +46,12 @@ module GovKit
if record.is_a?(Array)
instantiate_collection(record)
else
- instantiate_record(record)
+ new(record)
end
end
- def self.instantiate_record(record)
- new(record)
- end
-
def self.instantiate_collection(collection)
- collection.collect! { |record| instantiate_record(record) }
+ collection.collect! { |record| new(record) }
end
def unload(attributes) | Get rid of instantiate_record() | opengovernment_govkit | train |
1711df421083be53444a65053d30eac75e5f979b | diff --git a/factories/factories.go b/factories/factories.go
index <HASH>..<HASH> 100644
--- a/factories/factories.go
+++ b/factories/factories.go
@@ -67,6 +67,13 @@ func NewValueMetric(name string, value float64, unit string) *events.ValueMetric
}
}
+func NewCounterEvent(name string, delta uint64) *events.CounterEvent {
+ return &events.CounterEvent{
+ Name: proto.String(name),
+ Delta: proto.Uint64(delta),
+ }
+}
+
func NewLogMessage(messageType events.LogMessage_MessageType, messageString, appId, sourceType string) *events.LogMessage {
currentTime := time.Now() | Add CounterEvent factory
[#<I>] | cloudfoundry_dropsonde | train |
5d9758325f2b2f389df776dce17ac471d35ec80b | diff --git a/npm_mjs/management/commands/create_package_json.py b/npm_mjs/management/commands/create_package_json.py
index <HASH>..<HASH> 100644
--- a/npm_mjs/management/commands/create_package_json.py
+++ b/npm_mjs/management/commands/create_package_json.py
@@ -27,7 +27,7 @@ def deep_merge_dicts(old_dict, merge_dict, scripts=False):
# In the scripts section, allow adding to hooks such as
# "preinstall" and "postinstall"
if scripts and key in old_dict:
- old_dict[key] += ' & %s' % merge_dict[key]
+ old_dict[key] += ' && %s' % merge_dict[key]
else:
old_dict[key] = merge_dict[key]
else:
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -9,7 +9,7 @@ os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-npm-mjs',
- version='0.7.3',
+ version='0.7.4',
packages=find_packages(),
include_package_data=True,
license='LGPL License', | <I>: make post/preinstall scripts not execute in parallel | fiduswriter_django-npm-mjs | train |
ee449786973c6f3a238e399af586aa4f00c42342 | diff --git a/lib/podio/models/promotion.rb b/lib/podio/models/promotion.rb
index <HASH>..<HASH> 100644
--- a/lib/podio/models/promotion.rb
+++ b/lib/podio/models/promotion.rb
@@ -13,6 +13,8 @@ class Podio::Promotion < ActivePodio::Base
property :sleep, :integer
property :condition_set_ids, :array
+ has_many :condition_sets, :class => 'ConditionSet'
+
alias_method :id, :promotion_id
class << self | Added has_many relationship between Promotion and ConditionSet | podio_podio-rb | train |
7354f68adc72f2bfc472f41596af6ee8b3e6ea88 | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -13,29 +13,7 @@ setup(
'lxml (> 3.2.1)',
],
description = 'Download URLs using a compressed disk cache and a random throttling interval.',
- long_description = """
- Each Downloader maintains an sqlite3-based disk cache that utilizes zlib
- compression. Network requests are only made if the cached version of the
- resource has an age larger or equal to the stale_after value provided by the
- programmer.
-
- Between network requests a throttling interval needs to elapse. This throttling
- interval is randomly chosen, but lies within the throttle_bounds defined by the
- programmer.
-
- HTML resources can be parsed using lxml and in this case an lxml ElementTree is
- returned instead of a file object, with the links rewritten to be absolute in
- order to facilitate following them. The parsing is done leniently in order to
- not fail when invalid HTML is encountered.
-
- The programmer can also supply a function that decides whether the server has
- banned the client (possibly by examining the returned resource). In this case
- an exception will be raised.
-
- Downloader's features make it ideal for writing scrapers, as it can keep its
- network footprint small (due to the cache) and irregular (due to the random
- throttling interval).
- """,
+ long_description = open('README').read(),
classifiers = ['Programming Language :: Python',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent', | Updated setup.py for <I> version. | gtzampanakis_downloader | train |
abc346a8fb3e1865ba46982c122d138a67074b4c | diff --git a/src/main/java/org/osiam/client/oauth/Scope.java b/src/main/java/org/osiam/client/oauth/Scope.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/osiam/client/oauth/Scope.java
+++ b/src/main/java/org/osiam/client/oauth/Scope.java
@@ -53,4 +53,31 @@ public class Scope {
public String toString() {
return value;
}
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((value == null) ? 0 : value.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ Scope other = (Scope) obj;
+ if (value == null) {
+ if (other.value != null)
+ return false;
+ } else if (!value.equals(other.value))
+ return false;
+ return true;
+ }
+
+
} | [enhancement] added equals and hashcode to scope class | osiam_connector4java | train |
1a57b5f4de62485d038996cec4b178686248abcf | diff --git a/cli/polyaxon/cli/init.py b/cli/polyaxon/cli/init.py
index <HASH>..<HASH> 100644
--- a/cli/polyaxon/cli/init.py
+++ b/cli/polyaxon/cli/init.py
@@ -99,8 +99,16 @@ def create_polyaxonfile():
show_default=False,
help="Init a polyaxonignore file in this project.",
)
[email protected](
+ "--yes",
+ "-y",
+ is_flag=True,
+ default=False,
+ help="Automatic yes to prompts. "
+ 'Assume "yes" as answer to all prompts and run non-interactively.',
+)
@clean_outputs
-def init(project, git_connection, git_url, polyaxonfile, polyaxonignore):
+def init(project, git_connection, git_url, polyaxonfile, polyaxonignore, yes):
"""Initialize a new local project and cache directory.
Note: Make sure to add the local cache `.polyaxon`
@@ -136,7 +144,7 @@ def init(project, git_connection, git_url, polyaxonfile, polyaxonignore):
with indentation.indent(4):
indentation.puts("Owner: {}".format(local_project.owner))
indentation.puts("Project: {}".format(local_project.name))
- if click.confirm(
+ if yes or click.confirm(
"Would you like to override this current config?", default=False
):
init_project = True
@@ -167,7 +175,7 @@ def init(project, git_connection, git_url, polyaxonfile, polyaxonignore):
GitConfigManager.CONFIG_FILE_NAME
)
)
- if click.confirm("Would you like to override it?", default=False):
+ if yes or click.confirm("Would you like to override it?", default=False):
init_git = True
else:
init_git = True
@@ -198,7 +206,7 @@ def init(project, git_connection, git_url, polyaxonfile, polyaxonignore):
IgnoreConfigManager.CONFIG_FILE_NAME
)
)
- if click.confirm("Would you like to override it?", default=False):
+ if yes or click.confirm("Would you like to override it?", default=False):
init_ignore = True
else:
init_ignore = True | Add `-y/--yes` arg to `init` command to Assume "yes" as answer to all prompts and run non-interactively | polyaxon_polyaxon-cli | train |
da37518ef257866ce7072fb5650cc03a49fd0be6 | diff --git a/notario/validators/chainable.py b/notario/validators/chainable.py
index <HASH>..<HASH> 100644
--- a/notario/validators/chainable.py
+++ b/notario/validators/chainable.py
@@ -22,7 +22,12 @@ class BasicChainValidator(object):
class AllIn(BasicChainValidator):
"""
- Validates against all the validators passed in.
+ Validates against all the validators passed in. This chainable validator
+ will pass in the actual to every single validator that is contained as an
+ argument.
+
+
+ :raises: TypeError if the validator is *not* a callable
"""
def __call__(self, value):
@@ -38,6 +43,8 @@ class AllIn(BasicChainValidator):
class AnyIn(BasicChainValidator):
"""
If any contained validator passes it skips any others
+
+ :raises: TypeError if the validator is *not* a callable
"""
__name__ = 'AnyIn' | better docstrings for docs | alfredodeza_notario | train |
a614b1f4b5ccad7f9d5946d6c5444c378d2d8c40 | diff --git a/openquake/calculators/event_based_risk.py b/openquake/calculators/event_based_risk.py
index <HASH>..<HASH> 100644
--- a/openquake/calculators/event_based_risk.py
+++ b/openquake/calculators/event_based_risk.py
@@ -41,7 +41,7 @@ getweight = operator.attrgetter('weight')
indices_dt = numpy.dtype([('start', U32), ('stop', U32)])
-def build_rup_loss_table(dstore, alt):
+def build_rup_loss_table(dstore):
"""
Save the total losses by rupture.
"""
@@ -50,13 +50,12 @@ def build_rup_loss_table(dstore, alt):
events = dstore['events']
rup_by_eid = dict(zip(events['eid'], events['rup_id']))
losses_by_rup = {}
- for rec in alt:
+ for rec in dstore['agg_loss_table'].value: # .value is essential for speed
rupid = rup_by_eid[rec['eid']]
if rupid in losses_by_rup:
losses_by_rup[rupid] += rec['loss']
else:
losses_by_rup[rupid] = rec['loss']
- print('built losses_by_rup')
assert losses_by_rup, 'Empty agg_loss_table'
dtlist = [('ridx', numpy.uint32)] + oq.loss_dt_list()
serials = dstore['ruptures']['serial']
@@ -453,16 +452,14 @@ class EbriskCalculator(base.RiskCalculator):
eff_time)
return
b = get_loss_builder(dstore)
- alt = dstore['agg_loss_table']
if 'ruptures' in dstore:
logging.info('Building rup_loss_table')
with self.monitor('building rup_loss_table', measuremem=True):
- dstore['rup_loss_table'] = build_rup_loss_table(
- dstore, alt.value)
+ dstore['rup_loss_table'] = build_rup_loss_table(dstore)
stats = oq.risk_stats()
logging.info('Building aggregate loss curves')
with self.monitor('building agg_curves', measuremem=True):
- array, array_stats = b.build(alt.value, stats)
+ array, array_stats = b.build(dstore['agg_loss_table'].value, stats)
self.datastore['agg_curves-rlzs'] = array
units = self.assetcol.units(loss_types=array.dtype.names)
self.datastore.set_attrs( | Cleanup [skip CI] | gem_oq-engine | train |
9ecaf63bcda8eb69092ad30da84295306704b150 | diff --git a/django_conneg/views.py b/django_conneg/views.py
index <HASH>..<HASH> 100644
--- a/django_conneg/views.py
+++ b/django_conneg/views.py
@@ -7,6 +7,7 @@ from django.utils.decorators import classonlymethod
from django import http
from django.template import RequestContext
from django.shortcuts import render_to_response
+from django.utils.cache import patch_vary_headers
from django_conneg.http import MediaType
from django_conneg.decorators import renderer
@@ -72,12 +73,16 @@ class ContentNegotiatedView(View):
if response is NotImplemented:
continue
response.status_code = status_code
- return response
except NotImplementedError:
continue
else:
tried_mimetypes = list(itertools.chain(*[r.mimetypes for r in request.renderers]))
- return self.http_not_acceptable(request, tried_mimetypes)
+ response = self.http_not_acceptable(request, tried_mimetypes)
+
+ # We're doing content-negotiation, so tell the user-agent that the
+ # response will vary depending on the accept header.
+ patch_vary_headers(response, ('Accept',))
+ return response
def http_not_acceptable(self, request, tried_mimetypes, *args, **kwargs):
tried_mimetypes = () | Added support for Vary: Accept. | ox-it_django-conneg | train |
dfa99172dce16dce0735ba4fe0fb6b1a934bace3 | diff --git a/alerta/auth/decorators.py b/alerta/auth/decorators.py
index <HASH>..<HASH> 100644
--- a/alerta/auth/decorators.py
+++ b/alerta/auth/decorators.py
@@ -68,8 +68,13 @@ def permission(scope):
if not Permission.is_in_scope(scope, have_scopes=g.scopes):
raise ApiError('Missing required scope: %s' % scope.value, 403)
- else:
- return f(*args, **kwargs)
+
+ if current_app.config['XSRF_ENABLED']:
+ xsrf_header = request.headers.get(current_app.config['XSRF_HEADER'])
+ if request.method not in current_app.config['XSRF_ALLOWED_METHODS'] and jwt.xsrf_token != xsrf_header:
+ raise ApiError('Invalid XSRF token', 403)
+
+ return f(*args, **kwargs)
# Basic Auth
auth_header = request.headers.get('Authorization', '')
diff --git a/alerta/auth/utils.py b/alerta/auth/utils.py
index <HASH>..<HASH> 100644
--- a/alerta/auth/utils.py
+++ b/alerta/auth/utils.py
@@ -68,7 +68,8 @@ def create_token(user_id: str, name: str, login: str, provider: str, customers:
scopes=scopes,
email=email,
email_verified=email_verified,
- customers=customers
+ customers=customers,
+ xsrfToken=str(uuid4())
)
diff --git a/alerta/models/token.py b/alerta/models/token.py
index <HASH>..<HASH> 100644
--- a/alerta/models/token.py
+++ b/alerta/models/token.py
@@ -33,6 +33,7 @@ class Jwt:
self.scopes = kwargs.get('scopes', list())
self.email_verified = kwargs.get('email_verified', None)
self.customers = kwargs.get('customers', None)
+ self.xsrf_token = kwargs.get('xsrfToken', None)
@classmethod
def parse(cls, token: str, key: str=None, verify: bool=True, algorithm: str='HS256') -> 'Jwt':
@@ -64,7 +65,8 @@ class Jwt:
roles=json.get('roles', list()),
scopes=json.get('scope', '').split(' '), # eg. scope='read write' => scopes=['read', 'write']
email_verified=json.get('email_verified', None),
- customers=[json['customer']] if 'customer' in json else json.get('customers', list())
+ customers=[json['customer']] if 'customer' in json else json.get('customers', list()),
+ xsrfToken=json.get('xsrfToken', None)
)
@property
@@ -99,6 +101,9 @@ class Jwt:
data['email_verified'] = self.email_verified
if current_app.config['CUSTOMER_VIEWS']:
data['customers'] = self.customers
+
+ if self.xsrf_token:
+ data['xsrfToken'] = self.xsrf_token
return data
@property
diff --git a/alerta/settings.py b/alerta/settings.py
index <HASH>..<HASH> 100644
--- a/alerta/settings.py
+++ b/alerta/settings.py
@@ -97,8 +97,13 @@ AUDIT_TRAIL = ['admin'] # possible categories are 'admin', 'write', and 'auth'
AUDIT_LOG = None # set to True to log to application logger
AUDIT_URL = None # send audit log events via webhook URL
+# Cross-site Request Forgery (XSRF) settings
+XSRF_ENABLED = False
+XSRF_HEADER = 'X-XSRF-TOKEN'
+XSRF_ALLOWED_METHODS = ['GET', 'HEAD', 'OPTIONS']
+
# CORS settings
-CORS_ALLOW_HEADERS = ['Content-Type', 'Authorization', 'Access-Control-Allow-Origin']
+CORS_ALLOW_HEADERS = ['Content-Type', 'Authorization', 'Access-Control-Allow-Origin', XSRF_HEADER]
CORS_ORIGINS = [
# 'http://try.alerta.io',
# 'http://explorer.alerta.io',
diff --git a/tests/test_cors.py b/tests/test_cors.py
index <HASH>..<HASH> 100644
--- a/tests/test_cors.py
+++ b/tests/test_cors.py
@@ -37,7 +37,7 @@ class AlertTestCase(unittest.TestCase):
# check Access-Control-Allow-Headers header
response = self.client.options('/alerts', headers=headers)
self.assertEqual(response.status_code, 200)
- self.assertEqual(response.headers.get(ACL_ALLOW_HEADERS), 'authorization, content-type')
+ self.assertEqual(response.headers.get(ACL_ALLOW_HEADERS), 'X-XSRF-TOKEN, authorization, content-type')
headers = {
'Origin': 'http://try.alerta.io' | Add CSRF token check on Bearer auth (#<I>) | alerta_alerta | train |
32a7b23923ee94ca05bcc7da1c1e52e81b21e777 | diff --git a/octodns/manager.py b/octodns/manager.py
index <HASH>..<HASH> 100644
--- a/octodns/manager.py
+++ b/octodns/manager.py
@@ -6,7 +6,7 @@ from __future__ import absolute_import, division, print_function, \
unicode_literals
from StringIO import StringIO
-from concurrent.futures import ThreadPoolExecutor
+from concurrent.futures import Future, ThreadPoolExecutor
from importlib import import_module
from os import environ
import logging
@@ -37,10 +37,21 @@ class _AggregateTarget(object):
return True
+class MainThreadExecutor(object):
+
+ def submit(self, func, *args, **kwargs):
+ future = Future()
+ try:
+ future.set_result(func(*args, **kwargs))
+ except Exception as e:
+ future.set_exception(e)
+ return future
+
+
class Manager(object):
log = logging.getLogger('Manager')
- def __init__(self, config_file):
+ def __init__(self, config_file, max_workers=None):
self.log.info('__init__: config_file=%s', config_file)
# Read our config file
@@ -48,8 +59,12 @@ class Manager(object):
self.config = safe_load(fh, enforce_order=False)
manager_config = self.config.get('manager', {})
- max_workers = manager_config.get('max_workers', 4)
- self._executor = ThreadPoolExecutor(max_workers=max_workers)
+ max_workers = manager_config.get('max_workers', 1) \
+ if max_workers is None else max_workers
+ if max_workers > 1:
+ self._executor = ThreadPoolExecutor(max_workers=max_workers)
+ else:
+ self._executor = MainThreadExecutor()
self.log.debug('__init__: configuring providers')
self.providers = {}
diff --git a/tests/test_octodns_manager.py b/tests/test_octodns_manager.py
index <HASH>..<HASH> 100644
--- a/tests/test_octodns_manager.py
+++ b/tests/test_octodns_manager.py
@@ -115,6 +115,11 @@ class TestManager(TestCase):
.sync(dry_run=False, force=True)
self.assertEquals(19, tc)
+ # Again with max_workers = 1
+ tc = Manager(get_config_filename('simple.yaml'), max_workers=1) \
+ .sync(dry_run=False, force=True)
+ self.assertEquals(19, tc)
+
def test_eligible_targets(self):
with TemporaryDirectory() as tmpdir:
environ['YAML_TMP_DIR'] = tmpdir.dirname | Don't use threads when max_workers=1 | github_octodns | train |
39acf5f2f602e34cf70fe6e1dbeeb04511e1ff26 | diff --git a/live_test.py b/live_test.py
index <HASH>..<HASH> 100644
--- a/live_test.py
+++ b/live_test.py
@@ -83,10 +83,10 @@ message = Mail(from_email=From('[email protected]', 'DX'),
try:
sendgrid_client = SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
print(json.dumps(message.get(), sort_keys=True, indent=4))
- # response = sendgrid_client.send(message=message)
- # print(response.status_code)
- # print(response.body)
- # print(response.headers)
+ response = sendgrid_client.send(message=message)
+ print(response.status_code)
+ print(response.body)
+ print(response.headers)
except SendGridException as e:
print(e.message)
diff --git a/sendgrid/helpers/mail/email.py b/sendgrid/helpers/mail/email.py
index <HASH>..<HASH> 100644
--- a/sendgrid/helpers/mail/email.py
+++ b/sendgrid/helpers/mail/email.py
@@ -49,6 +49,9 @@ class Email(object):
if name is not None:
self.name = name
+
+ if substitutions is not None:
+ self.substitutions = substitutions
@property
def name(self):
diff --git a/sendgrid/helpers/mail/personalization.py b/sendgrid/helpers/mail/personalization.py
index <HASH>..<HASH> 100644
--- a/sendgrid/helpers/mail/personalization.py
+++ b/sendgrid/helpers/mail/personalization.py
@@ -26,11 +26,15 @@ class Personalization(object):
def tos(self, value):
self._tos = value
- def add_to(self, email, substitutions=None):
+ def add_to(self, email):
"""Add a single recipient to this Personalization.
:type email: Email
"""
+ if email.substitutions:
+ print(email.substitutions)
+ for substition in email.substitutions:
+ self.add_substitution(substition)
self._tos.append(email.get())
@property | Send Multiple Emails to Multiple Recipients | sendgrid_sendgrid-python | train |
de7d8f445af771a17670f8c6982b360230c6aeb3 | diff --git a/centinel/backend.py b/centinel/backend.py
index <HASH>..<HASH> 100644
--- a/centinel/backend.py
+++ b/centinel/backend.py
@@ -312,8 +312,9 @@ def sync(config):
for suf in suffixes:
for path in glob.glob(os.path.join(results_dir, '[!_]*' + suf)):
- npath = path.replace(suf, '-fin' + suf)
- os.rename(path, npath)
+ if '-fin' not in path:
+ npath = path.replace(suf, '-fin' + suf)
+ os.rename(path, npath)
# VPN Users don't need to submit results
if config['user']['is_vpn']: | Update backend.py
prevent adding -fin to the files that already have -fin | iclab_centinel | train |
398ee3c3b7f1e4a3838c737e581f0ba515ab57b1 | diff --git a/hardware/opentrons_hardware/hardware_control/move_group_runner.py b/hardware/opentrons_hardware/hardware_control/move_group_runner.py
index <HASH>..<HASH> 100644
--- a/hardware/opentrons_hardware/hardware_control/move_group_runner.py
+++ b/hardware/opentrons_hardware/hardware_control/move_group_runner.py
@@ -313,20 +313,23 @@ class MoveScheduler:
seq_id = message.payload.seq_id.value
group_id = message.payload.group_id.value
node_id = arbitration_id.parts.originating_node_id
- log.info(
- f"Received completion for {node_id} group {group_id} seq {seq_id}"
- ", which "
- f"{'is' if (node_id, seq_id) in self._moves[group_id] else 'isn''t'}"
- " in group"
- )
try:
+ in_group = (node_id, seq_id) in self._moves[group_id]
self._moves[group_id].remove((node_id, seq_id))
self._completion_queue.put_nowait((arbitration_id, message))
+ log.info(
+ f"Received completion for {node_id} group {group_id} seq {seq_id}"
+ f", which {'is' if in_group else 'isn''t'} in group"
+ )
except KeyError:
log.warning(
f"Got a move ack for ({node_id}, {seq_id}) which is not in this "
"group; may have leaked from an earlier timed-out group"
)
+ except IndexError:
+ # If we have two move groups running at once, we need to handle
+ # moves from a group we don't own
+ return
if not self._moves[group_id]:
log.info(f"Move group {group_id} has completed.")
@@ -335,20 +338,28 @@ class MoveScheduler:
def _handle_move_completed(self, message: MoveCompleted) -> None:
group_id = message.payload.group_id.value
ack_id = message.payload.ack_id.value
- if self._stop_condition[
- group_id
- ] == MoveStopCondition.limit_switch and ack_id != UInt8Field(2):
- if ack_id == UInt8Field(1):
- condition = "Homing timed out."
- log.warning(f"Homing failed. Condition: {condition}")
- raise MoveConditionNotMet()
+ try:
+ if self._stop_condition[
+ group_id
+ ] == MoveStopCondition.limit_switch and ack_id != UInt8Field(2):
+ if ack_id == UInt8Field(1):
+ condition = "Homing timed out."
+ log.warning(f"Homing failed. Condition: {condition}")
+ raise MoveConditionNotMet()
+ except IndexError:
+ # If we have two move group runners running at once, they each
+ # pick up groups they don't care about, and need to not fail.
+ pass
def _handle_tip_action(self, message: TipActionResponse) -> None:
group_id = message.payload.group_id.value
ack_id = message.payload.ack_id.value
- limit_switch = bool(
- self._stop_condition[group_id] == MoveStopCondition.limit_switch
- )
+ try:
+ limit_switch = bool(
+ self._stop_condition[group_id] == MoveStopCondition.limit_switch
+ )
+ except IndexError:
+ return
success = message.payload.success.value
# TODO need to add tip action type to the response message.
if limit_switch and limit_switch != ack_id and not success:
diff --git a/hardware/tests/opentrons_hardware/hardware_control/test_move_group_runner.py b/hardware/tests/opentrons_hardware/hardware_control/test_move_group_runner.py
index <HASH>..<HASH> 100644
--- a/hardware/tests/opentrons_hardware/hardware_control/test_move_group_runner.py
+++ b/hardware/tests/opentrons_hardware/hardware_control/test_move_group_runner.py
@@ -344,6 +344,11 @@ class MockSendMoveCompleter:
self._move_groups = move_groups
self._listener = listener
+ @property
+ def groups(self) -> MoveGroups:
+ """Retrieve the groups, for instance from a child class."""
+ return self._move_groups
+
async def mock_send(
self,
node_id: NodeId,
@@ -562,3 +567,37 @@ async def test_empty_groups(
mg = MoveGroupRunner(empty_group)
await mg.run(mock_can_messenger)
mock_can_messenger.send.assert_not_called()
+
+
+class MockSendMoveCompleterWithUnknown(MockSendMoveCompleter):
+ """Completes moves, injecting an unknown group ID."""
+
+ async def mock_send(self, node_id: NodeId, message: MessageDefinition) -> None:
+ """Overrides the send method of the messenger."""
+ if isinstance(message, md.ExecuteMoveGroupRequest):
+ groups = super().groups
+ bad_id = len(groups)
+ payload = MoveCompletedPayload(
+ group_id=UInt8Field(bad_id),
+ seq_id=UInt8Field(0),
+ current_position_um=UInt32Field(0),
+ encoder_position_um=Int32Field(0),
+ ack_id=UInt8Field(1),
+ )
+ sender = next(iter(groups[0][0].keys()))
+ arbitration_id = ArbitrationId(
+ parts=ArbitrationIdParts(originating_node_id=sender)
+ )
+ self._listener(md.MoveCompleted(payload=payload), arbitration_id)
+ await super().mock_send(node_id, message)
+
+
+async def test_handles_unknown_group_ids(
+ mock_can_messenger: AsyncMock, move_group_single: MoveGroups
+) -> None:
+ """Acks with unknown group ids should not cause crashes."""
+ subject = MoveScheduler(move_group_single)
+ mock_sender = MockSendMoveCompleterWithUnknown(move_group_single, subject)
+ mock_can_messenger.send.side_effect = mock_sender.mock_send
+ # this should not throw
+ await subject.run(can_messenger=mock_can_messenger) | fix(hardware): Tolerate unknown group ids in acks (#<I>)
It's possible to run multiple move group runners at the same time. We do
it during home, to speed things up and keep it all understandable.
However, all move group runners get all move-complete messages, which
means that they need to not throw exceptions and break when they get
messages with group IDs they don't own.
Closes RCORE-<I> | Opentrons_opentrons | train |
d6f81df16f394c9eb99654792c72c25fd4ab4b9d | diff --git a/go/kbfs/tlfhandle/resolve.go b/go/kbfs/tlfhandle/resolve.go
index <HASH>..<HASH> 100644
--- a/go/kbfs/tlfhandle/resolve.go
+++ b/go/kbfs/tlfhandle/resolve.go
@@ -17,6 +17,7 @@ import (
"github.com/keybase/client/go/kbfs/kbfsmd"
"github.com/keybase/client/go/kbfs/tlf"
kbname "github.com/keybase/client/go/kbun"
+ "github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/logger"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/pkg/errors"
@@ -834,11 +835,20 @@ func parseHandleLoose(
if iteamHandle.tlfID != tlf.NullID {
return iteamHandle, nil
}
+
+ } else {
+ switch err.(type) {
+ case libkb.TeamContactSettingsBlockError:
+ // The implicit team couldn't be created due to one of the
+ // users' privacy settings, so fail the handle lookup completely.
+ return nil, err
+ default:
+ // This is not an implicit team, so continue on to check for a
+ // normal team. TODO: return non-nil errors immediately if they
+ // don't simply indicate the implicit team doesn't exist yet
+ // (i.e., when we start creating them by default).
+ }
}
- // This is not an implicit team, so continue on to check for a
- // normal team. TODO: return non-nil errors immediately if they
- // don't simply indicate the implicit team doesn't exist yet
- // (i.e., when we start creating them by default).
}
// Before parsing the tlf handle (which results in identify
diff --git a/go/libkb/rpc_exim.go b/go/libkb/rpc_exim.go
index <HASH>..<HASH> 100644
--- a/go/libkb/rpc_exim.go
+++ b/go/libkb/rpc_exim.go
@@ -744,6 +744,17 @@ func ImportStatusAsError(g *GlobalContext, s *keybase1.Status) error {
return NewFeatureFlagError(s.Desc, feature)
case SCNoPaperKeys:
return NoPaperKeysError{}
+ case SCTeamContactSettingsBlock:
+ e := TeamContactSettingsBlockError{}
+ for _, field := range s.Fields {
+ switch field.Key {
+ case "uids":
+ e.blockedUIDs = parseUIDsFromString(field.Value)
+ case "usernames":
+ e.blockedUsernames = parseUsernamesFromString(field.Value)
+ }
+ }
+ return e
default:
ase := AppStatusError{
Code: s.Code,
@@ -2402,3 +2413,29 @@ func (e NoPaperKeysError) ToStatus() (ret keybase1.Status) {
ret.Desc = e.Error()
return
}
+
+func (e TeamContactSettingsBlockError) ToStatus() (ret keybase1.Status) {
+ ret.Code = SCTeamContactSettingsBlock
+ ret.Name = "TEAM_CONTACT_SETTINGS_BLOCK"
+ ret.Desc = e.Error()
+ ret.Fields = []keybase1.StringKVPair{
+ {Key: "uids", Value: parseUIDsToString(e.blockedUIDs)},
+ {Key: "usernames", Value: parseUsernamesToString(e.blockedUsernames)},
+ }
+ return
+}
+
+func parseUIDsToString(input []keybase1.UID) string {
+ uids := make([]string, len(input))
+ for i, uid := range input {
+ uids[i] = uid.String()
+ }
+ return strings.Join(uids, ",")
+}
+func parseUsernamesToString(input []NormalizedUsername) string {
+ usernames := make([]string, len(input))
+ for i, username := range input {
+ usernames[i] = username.String()
+ }
+ return strings.Join(usernames, ",")
+} | Propagate contact settings error to service and kbfs (#<I>)
* add contact settings error to rpc_exim | keybase_client | train |
91c46af486335a0def10e444027135e669d59540 | diff --git a/api/service/handler.go b/api/service/handler.go
index <HASH>..<HASH> 100644
--- a/api/service/handler.go
+++ b/api/service/handler.go
@@ -15,8 +15,15 @@ func ServiceAndServiceInstancesByTeams(teamKind string, u *auth.User) []ServiceM
var teams []auth.Team
q := bson.M{"users": u.Email}
db.Session.Teams().Find(q).Select(bson.M{"_id": 1}).All(&teams)
- var services []Service
- q = bson.M{teamKind: bson.M{"$in": auth.GetTeamsNames(teams)}}
+ var services []Service
+ q = bson.M{"$or":
+ []bson.M{
+ bson.M{
+ teamKind: bson.M{"$in": auth.GetTeamsNames(teams)},
+ },
+ bson.M{"is_restricted": false},
+ },
+ }
db.Session.Services().Find(q).Select(bson.M{"name": 1}).All(&services)
var sInsts []ServiceInstance
q = bson.M{"service_name": bson.M{"$in": GetServicesNames(services)}}
diff --git a/api/service/handler_test.go b/api/service/handler_test.go
index <HASH>..<HASH> 100644
--- a/api/service/handler_test.go
+++ b/api/service/handler_test.go
@@ -33,3 +33,21 @@ func (s *S) TestServiceAndServiceInstancesByOwnerTeams(c *C) {
}
c.Assert(obtained, DeepEquals, expected)
}
+
+func (s *S) TestServiceAndServiceInstancesByTeamsShouldAlsoReturnServicesWithIsRestrictedFalse(c *C) {
+ srv := Service{Name: "mongodb", OwnerTeams: []string{s.team.Name}}
+ srv.Create()
+ defer srv.Delete()
+ srv2 := Service{Name: "mysql"}
+ srv2.Create()
+ defer srv2.Delete()
+ si := ServiceInstance{Name: "my_nosql", ServiceName: srv.Name}
+ si.Create()
+ defer si.Delete()
+ obtained := ServiceAndServiceInstancesByTeams("owner_teams", s.user)
+ expected := []ServiceModel{
+ ServiceModel{Service: "mongodb", Instances: []string{"my_nosql"}},
+ ServiceModel{Service: "mysql"},
+ }
+ c.Assert(obtained, DeepEquals, expected)
+} | api.service: Also filtering for services that has is_restricted: false | tsuru_tsuru | train |
ca6b183d67b753aa75fcab4b327c8ddaa61df46b | diff --git a/gulpfile.js b/gulpfile.js
index <HASH>..<HASH> 100644
--- a/gulpfile.js
+++ b/gulpfile.js
@@ -115,7 +115,7 @@ gulp.task('test-coverage', ['peg', 'juttle-spec', 'instrument'], function() {
global: {
statements: 93,
branches: 87,
- functions: 92,
+ functions: 91,
lines: 93
}
} | gulpfile.js: Lower functions coverage threshold to <I>% | juttle_juttle | train |
dde2be4f6a0484f23756009ceaa424de084879ba | diff --git a/tk_tools/canvas.py b/tk_tools/canvas.py
index <HASH>..<HASH> 100644
--- a/tk_tools/canvas.py
+++ b/tk_tools/canvas.py
@@ -305,9 +305,6 @@ class Gauge(ttk.Frame):
self._redraw()
-
-
-
# Gauge2 : modifications from Gauge
# ************************
# 3 numeric values added : min, center, max,
@@ -322,7 +319,6 @@ class Gauge(ttk.Frame):
# idem on value
# math correction now min_value can be different from 0 or negative
-
class Gauge2(ttk.Frame):
"""
Shows a gauge, much like the RotaryGauge::
@@ -342,10 +338,12 @@ class Gauge2(ttk.Frame):
:parm red: the beginning of the red (danger) zone in percent
:parm yellow_low: in percent warning for low values
:parm red_low: in percent if very low values are a danger
+ :param bg: background
"""
def __init__(self, parent, width=200, height=100,
min_value=0.0, max_value=100.0, label='', unit='',
- divisions=8, yellow=50, red=80, yellow_low=0, red_low=0, bg='lightgrey'):
+ divisions=8, yellow=50, red=80, yellow_low=0,
+ red_low=0, bg='lightgrey'):
self._parent = parent
self._width = width
self._height = height
@@ -362,30 +360,26 @@ class Gauge2(ttk.Frame):
super().__init__(self._parent)
- self._canvas = tk.Canvas(self, width=self._width, height=self._height, bg=bg)
- # ,bg='lavender'
+ self._canvas = tk.Canvas(self, width=self._width,
+ height=self._height, bg=bg)
self._canvas.grid(row=0, column=0, sticky='news')
-
self._min_value = EngNumber(min_value)
self._max_value = EngNumber(max_value)
self._value = self._min_value
-
self._redraw()
# ----------------------------------------------------------------------
def _redraw(self):
self._canvas.delete('all')
-
max_angle = 120.0
- value_as_percent = (self._value - self._min_value) / (self._max_value - self._min_value)
+ value_as_percent = ((self._value - self._min_value) /
+ (self._max_value - self._min_value))
value = float(max_angle * value_as_percent)
# no int() => accuracy
-
# create the tick marks and colors across the top
for i in range(self._divisions):
extent = (max_angle / self._divisions)
start = (150.0 - i * extent)
-
rate = (i+1)/(self._divisions+1)
if rate < self._red_low:
bg_color = 'red'
@@ -404,10 +398,8 @@ class Gauge2(ttk.Frame):
start=start, extent=-extent, width=2,
fill=bg_color, style='pie'
)
-
bg_color = 'white'
red = '#c21807'
-
ratio = 0.06
self._canvas.create_arc(self._width * ratio,
int(self._height * 0.25),
@@ -415,7 +407,6 @@ class Gauge2(ttk.Frame):
int(self._height * 1.8 * (1.0 - ratio * 1.1)),
start=150, extent=-120, width=2,
fill=bg_color, style='pie')
-
# readout & title
self.readout(self._value, 'black') # BG black if OK
@@ -434,7 +425,6 @@ class Gauge2(ttk.Frame):
self._canvas.create_text(
self._width * 0.5, self._height * 0.1,
font=('Courier New', 10), text=value_text)
-
# create first half (red needle)
self._canvas.create_arc(0, int(self._height * 0.15),
self._width, int(self._height * 1.8),
@@ -446,7 +436,6 @@ class Gauge2(ttk.Frame):
self._width, int(self._height * 1.8),
start=30, extent=120-value, width=3,
outline=red)'''
-
# create inset red
self._canvas.create_arc(self._width * 0.35, int(self._height * 0.7),
self._width * 0.65, int(self._height * 1.2),
@@ -481,21 +470,17 @@ class Gauge2(ttk.Frame):
self._canvas.create_text(
self._width * 0.5, self._height * 0.5 + r_offset,
font=('Courier New', 10), text=value_text, fill='white')
-
# ----------------------------------------------------------------------
def set_value(self, value):
self._value = EngNumber(value)
if self._min_value * 1.02 < value < self._max_value * 0.98:
self._redraw() # refresh all
- else: # OFF limits refresh only readout
+ else: # OFF limits refresh only readout
self.readout(self._value, 'red') # on RED BackGround
-
-
-
class Graph(ttk.Frame):
"""
Tkinter native graph (pretty basic, but doesn't require heavy install).:: | For flake8
Modified too long lines | slightlynybbled_tk_tools | train |
7d52688350e7194159f499f0ce71846765fa0397 | diff --git a/modules/citrus-ftp/src/main/java/com/consol/citrus/ftp/client/FtpClient.java b/modules/citrus-ftp/src/main/java/com/consol/citrus/ftp/client/FtpClient.java
index <HASH>..<HASH> 100644
--- a/modules/citrus-ftp/src/main/java/com/consol/citrus/ftp/client/FtpClient.java
+++ b/modules/citrus-ftp/src/main/java/com/consol/citrus/ftp/client/FtpClient.java
@@ -104,8 +104,8 @@ public class FtpClient extends AbstractEndpoint implements Producer, ReplyConsum
log.info(String.format("FTP message was successfully sent to: '%s:%s'", getEndpointConfiguration().getHost(), getEndpointConfiguration().getPort()));
correlationManager.store(correlationKey, new FtpMessage(ftpMessage.getCommand(), ftpMessage.getArguments())
- .setReplyCode(reply)
- .setReplyString(ftpClient.getReplyString()));
+ .replyCode(reply)
+ .replyString(ftpClient.getReplyString()));
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to execute ftp command", e);
}
diff --git a/modules/citrus-ftp/src/main/java/com/consol/citrus/ftp/message/FtpMessage.java b/modules/citrus-ftp/src/main/java/com/consol/citrus/ftp/message/FtpMessage.java
index <HASH>..<HASH> 100644
--- a/modules/citrus-ftp/src/main/java/com/consol/citrus/ftp/message/FtpMessage.java
+++ b/modules/citrus-ftp/src/main/java/com/consol/citrus/ftp/message/FtpMessage.java
@@ -50,12 +50,39 @@ public class FtpMessage extends DefaultMessage {
* @param command
* @return
*/
- public FtpMessage setCommand(FTPCmd command) {
+ public FtpMessage command(FTPCmd command) {
setHeader(FtpMessageHeaders.FTP_COMMAND, command);
return this;
}
/**
+ * Sets the reply string.
+ * @param replyString
+ */
+ public FtpMessage replyString(String replyString) {
+ setHeader(FtpMessageHeaders.FTP_REPLY_STRING, replyString);
+ return this;
+ }
+
+ /**
+ * Sets the command args.
+ * @param arguments
+ */
+ public FtpMessage arguments(String arguments) {
+ setHeader(FtpMessageHeaders.FTP_ARGS, arguments);
+ return this;
+ }
+
+ /**
+ * Sets the reply code.
+ * @param replyCode
+ */
+ public FtpMessage replyCode(Integer replyCode) {
+ setHeader(FtpMessageHeaders.FTP_REPLY_CODE, replyCode);
+ return this;
+ }
+
+ /**
* Gets the ftp command
*/
public FTPCmd getCommand() {
@@ -69,15 +96,6 @@ public class FtpMessage extends DefaultMessage {
}
/**
- * Sets the command args.
- * @param arguments
- */
- public FtpMessage setArguments(String arguments) {
- setHeader(FtpMessageHeaders.FTP_ARGS, arguments);
- return this;
- }
-
- /**
* Gets the command args.
*/
public String getArguments() {
@@ -91,15 +109,6 @@ public class FtpMessage extends DefaultMessage {
}
/**
- * Sets the reply code.
- * @param replyCode
- */
- public FtpMessage setReplyCode(Integer replyCode) {
- setHeader(FtpMessageHeaders.FTP_REPLY_CODE, replyCode);
- return this;
- }
-
- /**
* Gets the reply code.
*/
public Integer getReplyCode() {
@@ -117,15 +126,6 @@ public class FtpMessage extends DefaultMessage {
}
/**
- * Sets the reply string.
- * @param replyString
- */
- public FtpMessage setReplyString(String replyString) {
- setHeader(FtpMessageHeaders.FTP_REPLY_STRING, replyString);
- return this;
- }
-
- /**
* Gets the reply string.
*/
public String getReplyString() {
diff --git a/modules/citrus-ftp/src/test/java/com/consol/citrus/ftp/server/FtpServerLetTest.java b/modules/citrus-ftp/src/test/java/com/consol/citrus/ftp/server/FtpServerLetTest.java
index <HASH>..<HASH> 100644
--- a/modules/citrus-ftp/src/test/java/com/consol/citrus/ftp/server/FtpServerLetTest.java
+++ b/modules/citrus-ftp/src/test/java/com/consol/citrus/ftp/server/FtpServerLetTest.java
@@ -61,7 +61,7 @@ public class FtpServerLetTest {
Assert.assertNull(ftpMessage.getReplyCode());
Assert.assertNull(ftpMessage.getReplyString());
- return new FtpMessage(FTPCmd.MKD, "testDir").setReplyCode(200). setReplyString("OK");
+ return new FtpMessage(FTPCmd.MKD, "testDir").replyCode(200).replyString("OK");
}
}); | Use builder pattern style setter methods for message implementations | citrusframework_citrus | train |
f44ceba98c7586eb933abb20d079cd94f6435c6c | diff --git a/tests/system/Filters/FiltersTest.php b/tests/system/Filters/FiltersTest.php
index <HASH>..<HASH> 100644
--- a/tests/system/Filters/FiltersTest.php
+++ b/tests/system/Filters/FiltersTest.php
@@ -13,8 +13,10 @@ namespace CodeIgniter\Filters;
use CodeIgniter\Config\Services;
use CodeIgniter\Filters\Exceptions\FilterException;
+use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Test\CIUnitTestCase;
+use CodeIgniter\Test\Mock\MockAppConfig;
require_once __DIR__ . '/fixtures/GoogleMe.php';
require_once __DIR__ . '/fixtures/GoogleYou.php';
@@ -60,7 +62,8 @@ final class FiltersTest extends CIUnitTestCase
'cli' => ['foo'],
],
];
- $filters = new Filters((object) $config, $this->request, $this->response);
+ $request = new CLIRequest(new MockAppConfig());
+ $filters = new Filters((object) $config, $request, $this->response);
$expected = [
'before' => ['foo'], | test: fix test
CLIRequest should be used when CLI testing | codeigniter4_CodeIgniter4 | train |
8d6023fb0600b3209ca78b6fe9ded04568e5d9af | diff --git a/ssr-helpers/create-renderer.js b/ssr-helpers/create-renderer.js
index <HASH>..<HASH> 100644
--- a/ssr-helpers/create-renderer.js
+++ b/ssr-helpers/create-renderer.js
@@ -84,7 +84,7 @@ function ensureTrailingSlash (path) {
function createRenderContext ({ clientManifest, publicPath }) {
return {
clientManifest,
- publicPath: ensureTrailingSlash(publicPath || clientManifest.publicPath || '/'),
+ publicPath: ensureTrailingSlash(clientManifest.publicPath || publicPath || '/'),
preloadFiles: (clientManifest.initial || []).map(normalizeFile),
mapFiles: createMapper(clientManifest)
} | fix(ssr): Give clientManifest.publicPath priority (#<I>) | quasarframework_quasar | train |
f34859415eaa122b451410904931c4eaf964872d | diff --git a/lib/collection/property-list.js b/lib/collection/property-list.js
index <HASH>..<HASH> 100644
--- a/lib/collection/property-list.js
+++ b/lib/collection/property-list.js
@@ -405,6 +405,18 @@ _.assign(PropertyList.prototype, /** @lends PropertyList.prototype */ {
return obj;
},
+ /**
+ * Adds ability to convert a list to a string provided it's underlying format has unparse function defined
+ * @return {String}
+ */
+ toString: function () {
+ if (this.Type.unparse) {
+ return this.Type.unparse(this.members);
+ }
+
+ return this.constructor ? this.constructor.prototype.toString.call(this) : '';
+ },
+
toJSON: function () {
if (!this.count()) {
return []; | Added toString in property list to leverage underlying Type.unparse | postmanlabs_postman-collection | train |
228a8a3f5a0c62d3a9f444241a1c1b8a8f6efe1d | diff --git a/cmd/jujud/unit.go b/cmd/jujud/unit.go
index <HASH>..<HASH> 100644
--- a/cmd/jujud/unit.go
+++ b/cmd/jujud/unit.go
@@ -7,6 +7,7 @@ import (
"launchpad.net/juju-core/log"
"launchpad.net/juju-core/state"
"launchpad.net/juju-core/worker"
+ "launchpad.net/juju-core/worker/deployer"
"launchpad.net/juju-core/worker/uniter"
"launchpad.net/tomb"
"time"
@@ -96,8 +97,19 @@ func (a *UnitAgent) runOnce() error {
return err
}
}
- return runTasks(a.tomb.Dying(),
+ tasks := []task{
uniter.NewUniter(st, unit.Name(), a.Conf.DataDir),
NewUpgrader(st, unit, a.Conf.DataDir),
- )
+ }
+ if unit.IsPrincipal() {
+ info := &state.Info{
+ EntityName: unit.EntityName(),
+ CACert: st.CACert(),
+ Addrs: st.Addrs(),
+ }
+ mgr := deployer.NewSimpleManager(info, a.Conf.DataDir)
+ tasks = append(tasks,
+ deployer.NewDeployer(st, mgr, unit.WatchSubordinateUnits()))
+ }
+ return runTasks(a.tomb.Dying(), tasks...)
} | unit agent now deploys subordinates | juju_juju | train |
a02369cd92e1a42b6514f2e658ab622086af7486 | diff --git a/pluginsmanager/model/effect.py b/pluginsmanager/model/effect.py
index <HASH>..<HASH> 100644
--- a/pluginsmanager/model/effect.py
+++ b/pluginsmanager/model/effect.py
@@ -196,9 +196,10 @@ class Effect(metaclass=ABCMeta):
return False
def __repr__(self):
- return "<{} object as '{}' at 0x{:x}>".format(
+ return "<{} object as '{}' {} active at 0x{:x}>".format(
self.__class__.__name__,
str(self),
+ '' if self.active else 'not',
id(self)
) | Issue #<I> - Improve effect description | PedalPi_PluginsManager | train |
e24652e94c114764f20d0b9f38e3c11f015164b0 | diff --git a/salt/states/netconfig.py b/salt/states/netconfig.py
index <HASH>..<HASH> 100644
--- a/salt/states/netconfig.py
+++ b/salt/states/netconfig.py
@@ -147,8 +147,8 @@ def managed(name,
.. code-block:: yaml
file_roots:
- base:
- - /etc/salt/states
+ base:
+ - /etc/salt/states
Placing the template under ``/etc/salt/states/templates/example.jinja``, it can be used as
``salt://templates/example.jinja``.
@@ -481,3 +481,65 @@ def managed(name,
**template_vars)
return salt.utils.napalm.loaded_ret(ret, config_update_ret, test, debug)
+
+
+def commit_cancelled(name):
+ '''
+ .. versionadded:: Fluorine
+
+ Cancel a commit scheduled to be executed via the ``commit_in`` and
+ ``commit_at`` arguments from the
+ :py:func:`net.load_template <salt.modules.napalm_network.load_template>` or
+ :py:func:`net.load_config <salt.modules.napalm_network.load_config`
+ execution functions. The commit ID is displayed when the commit is scheduled
+ via the functions named above.
+
+ State SLS Example:
+
+ .. code-block:: yaml
+
+ 20180726083540640360:
+ netconfig.commit_cancelled
+ '''
+ cancelled = {
+ 'result': None,
+ 'changes': {},
+ 'comment': ''
+ }
+ if __opts__['test']:
+ cancelled['comment'] = 'It would cancel commit #{}'.format(name)
+ return cancelled
+ cancelled = __salt__['net.cancel_commit'](name)
+ cancelled['changes'] = {}
+ return cancelled
+
+
+def commit_confirmed(name):
+ '''
+ .. versionadded:: Fluorine
+
+ Confirm a commit scheduled to be reverted via the ``revert_in`` and
+ ``revert_at`` arguments from the
+ :mod:`net.load_template <salt.modules.napalm_network.load_template>` or
+ :mod:`net.load_config <salt.modules.napalm_network.load_config`
+ execution functions. The commit ID is displayed when the commit confirmed
+ is scheduled via the functions named above.
+
+ State SLS Example:
+
+ .. code-block:: yaml
+
+ 20180726083540640360:
+ netconfig.commit_confirmed
+ '''
+ confirmed = {
+ 'result': None,
+ 'changes': {},
+ 'comment': ''
+ }
+ if __opts__['test']:
+ confirmed['comment'] = 'It would confirm commit #{}'.format(name)
+ return confirmed
+ confirmed = __salt__['net.confirm_commit'](name)
+ confirmed['changes'] = {}
+ return confirmed | Add commit_confirmed and commit_cancelled functions | saltstack_salt | train |
3c169c343e8c2c2cd46b29e6a23e76d133a46d9a | diff --git a/spyder/config/main.py b/spyder/config/main.py
index <HASH>..<HASH> 100644
--- a/spyder/config/main.py
+++ b/spyder/config/main.py
@@ -491,6 +491,7 @@ DEFAULTS = [
'pydocstyle/ignore': '',
'pydocstyle/match': '(?!test_).*\\.py',
'pydocstyle/match_dir': '[^\\.].*',
+ 'advanced': False,
'advanced/module': 'pyls',
'advanced/host': '127.0.0.1',
'advanced/port': 2087,
@@ -591,4 +592,4 @@ NAME_MAP = {
# or if you want to *rename* options, then you need to do a MAJOR update in
# version, e.g. from 3.0.0 to 4.0.0
# 3. You don't need to touch this value if you're just adding a new option
-CONF_VERSION = '53.0.0'
+CONF_VERSION = '53.1.0'
diff --git a/spyder/plugins/completion/languageserver/confpage.py b/spyder/plugins/completion/languageserver/confpage.py
index <HASH>..<HASH> 100644
--- a/spyder/plugins/completion/languageserver/confpage.py
+++ b/spyder/plugins/completion/languageserver/confpage.py
@@ -937,6 +937,10 @@ class LanguageServerConfigPage(GeneralConfigPage):
advanced_label.setWordWrap(True)
advanced_label.setAlignment(Qt.AlignJustify)
+ # Advanced settings checkbox
+ self.advanced_options_check = self.create_checkbox(
+ _("Enable advanced settings"), 'advanced')
+
# Advanced options
self.advanced_module = self.create_lineedit(
_("Module for the Python language server: "),
@@ -969,13 +973,30 @@ class LanguageServerConfigPage(GeneralConfigPage):
advanced_host_port_g_layout.addWidget(self.advanced_port.spinbox, 1, 2)
advanced_g_layout.addLayout(advanced_host_port_g_layout, 2, 1)
- advanced_widget = QWidget()
+ # External server and stdio options layout
+ external_server_layout = QVBoxLayout()
+ external_server_layout.addWidget(self.external_server)
+ external_server_layout.addWidget(self.use_stdio)
+
+ advanced_options_layout = QVBoxLayout()
+ advanced_options_layout.addLayout(advanced_g_layout)
+ advanced_options_layout.addLayout(external_server_layout)
+
+ # Set advanced options enabled/disabled
+ advanced_g_widget = QWidget()
+ advanced_g_widget.setLayout(advanced_options_layout)
+ advanced_g_widget.setEnabled(self.get_option('advanced'))
+ self.advanced_options_check.toggled.connect(
+ advanced_g_widget.setEnabled)
+
+ # Advanced options layout
advanced_layout = QVBoxLayout()
advanced_layout.addWidget(advanced_label)
+ advanced_layout.addWidget(self.advanced_options_check)
advanced_layout.addSpacing(12)
- advanced_layout.addLayout(advanced_g_layout)
- advanced_layout.addWidget(self.external_server)
- advanced_layout.addWidget(self.use_stdio)
+ advanced_layout.addWidget(advanced_g_widget)
+
+ advanced_widget = QWidget()
advanced_widget.setLayout(advanced_layout)
# --- Other servers tab --- | add checkbox to verify changes in advanced options in lsp preferences | spyder-ide_spyder | train |
513d4e2d1cc0abf22448de035e1149c395f5888a | diff --git a/cmd/juju/commands/bootstrap.go b/cmd/juju/commands/bootstrap.go
index <HASH>..<HASH> 100644
--- a/cmd/juju/commands/bootstrap.go
+++ b/cmd/juju/commands/bootstrap.go
@@ -8,6 +8,7 @@ import (
"fmt"
"os"
"os/user"
+ "sort"
"strings"
"github.com/juju/cmd"
@@ -354,6 +355,9 @@ func (c *bootstrapCommand) Run(ctx *cmd.Context) (resultErr error) {
for authType := range schemas {
authTypes = append(authTypes, authType)
}
+ // Since we are iterating over a map, lets sort the authTypes so
+ // they are always in a consistent order.
+ sort.Sort(jujucloud.AuthTypes(authTypes))
cloud = &jujucloud.Cloud{
Type: c.Cloud,
AuthTypes: authTypes, | Ensure ordering of auth types. | juju_juju | train |
8cbf2f11d95d35096908fcc3a3df86922d5102d7 | diff --git a/ruby_event_store/lib/ruby_event_store/client.rb b/ruby_event_store/lib/ruby_event_store/client.rb
index <HASH>..<HASH> 100644
--- a/ruby_event_store/lib/ruby_event_store/client.rb
+++ b/ruby_event_store/lib/ruby_event_store/client.rb
@@ -108,6 +108,19 @@ module RubyEventStore
repository.position_in_stream(event_id, Stream.new(stream_name))
end
+ # Gets position of the event in global stream
+ #
+ # The position is always nonnegative.
+ # Global position may have gaps, meaning, there may be event at
+ # position 40, but no event at position 39.
+ #
+ # @param event_id [String]
+ # @raise [EventNotFound]
+ # @return [Integer] nonnegno ative integer position of event in global stream
+ def global_position(event_id)
+ repository.global_position(event_id)
+ end
+
# Subscribes a handler (subscriber) that will be invoked for published events of provided type.
#
# @overload subscribe(subscriber, to:)
diff --git a/ruby_event_store/lib/ruby_event_store/in_memory_repository.rb b/ruby_event_store/lib/ruby_event_store/in_memory_repository.rb
index <HASH>..<HASH> 100644
--- a/ruby_event_store/lib/ruby_event_store/in_memory_repository.rb
+++ b/ruby_event_store/lib/ruby_event_store/in_memory_repository.rb
@@ -128,6 +128,10 @@ module RubyEventStore
event_in_stream.position
end
+ def global_position(event_id)
+ storage.fetch(event_id) { raise EventNotFound.new(event_id) }.global_position
+ end
+
private
def read_scope(spec)
serialized_records = serialized_records_of_stream(spec.stream)
diff --git a/ruby_event_store/lib/ruby_event_store/spec/event_repository_lint.rb b/ruby_event_store/lib/ruby_event_store/spec/event_repository_lint.rb
index <HASH>..<HASH> 100644
--- a/ruby_event_store/lib/ruby_event_store/spec/event_repository_lint.rb
+++ b/ruby_event_store/lib/ruby_event_store/spec/event_repository_lint.rb
@@ -723,6 +723,18 @@ module RubyEventStore
expect(repository.position_in_stream(event1.event_id, stream)).to eq(nil)
end
+ it '#global_position happy path' do
+ skip unless helper.supports_position_queries?
+ repository.append_to_stream([
+ event0 = SRecord.new,
+ event1 = SRecord.new
+ ], stream, version_any)
+
+ expect(repository.global_position(event0.event_id)).to be >= 0
+ expect(repository.global_position(event1.event_id)).to be >= 0
+ expect(repository.global_position(event0.event_id)).to be < repository.global_position(event1.event_id)
+ end
+
it 'knows last event in stream' do
repository.append_to_stream([a =SRecord.new(event_id: '00000000-0000-0000-0000-000000000001')], stream, version_none)
repository.append_to_stream([b = SRecord.new(event_id: '00000000-0000-0000-0000-000000000002')], stream, version_0) | Add Client#global_position and support for it in RubyEventStore::InMemoryRepository | RailsEventStore_rails_event_store | train |
f9d0752a7ee8dd66b02822e813695fd9075392da | diff --git a/example/multi.rb b/example/multi.rb
index <HASH>..<HASH> 100644
--- a/example/multi.rb
+++ b/example/multi.rb
@@ -23,6 +23,7 @@ EM.run{
result[0] = response
fiber.resume(result) if result.size == 2
}
+ puts "It's not blocking..."
client.get('cardinalblue'){ |response|
result[1] = response
fiber.resume(result) if result.size == 2 | example/multi.rb: show more puts to demonstrate it's not blocking | godfat_rest-core | train |
4d09dd5cc01871a69ede061ea5f210e76e21d42c | diff --git a/server/src/main/java/org/jboss/as/server/deployment/ExplodedDeploymentAddContentHandler.java b/server/src/main/java/org/jboss/as/server/deployment/ExplodedDeploymentAddContentHandler.java
index <HASH>..<HASH> 100644
--- a/server/src/main/java/org/jboss/as/server/deployment/ExplodedDeploymentAddContentHandler.java
+++ b/server/src/main/java/org/jboss/as/server/deployment/ExplodedDeploymentAddContentHandler.java
@@ -87,7 +87,7 @@ public class ExplodedDeploymentAddContentHandler implements OperationStepHandler
final String managementName = context.getCurrentAddress().getLastElement().getValue();
final PathAddress address = PathAddress.pathAddress(DEPLOYMENT, managementName);
final byte[] oldHash = CONTENT_HASH.resolveModelAttribute(context, contentItemNode).asBytes();
- final boolean overwrite = OVERWRITE.resolveModelAttribute(context, contentItemNode).asBoolean(true);
+ final boolean overwrite = OVERWRITE.resolveModelAttribute(context, operation).asBoolean(true);
List<ModelNode> contents = EXPLODED_CONTENT.resolveModelAttribute(context, operation).asList();
final List<ExplodedContent> addedFiles = new ArrayList<>(contents.size());
final byte[] newHash; | [WFCORE-<I>]: add-content operation fails to overwrite existing content with overwrite=true set when passing content by file path.
The overwrite is part of the operation, not of the content node. | wildfly_wildfly-core | train |
6cb24ee46d4e9535784fbc302930c35c5461e2da | diff --git a/test/ordered-collection.js b/test/ordered-collection.js
index <HASH>..<HASH> 100644
--- a/test/ordered-collection.js
+++ b/test/ordered-collection.js
@@ -26,8 +26,9 @@ function generateRandomNumberObjectList() {
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
- const length = getRandomNumber(0, maxLength);
+ const length = getRandomNumber(0, maxLength) / 5;
var result = [];
+
for (var i = 0; i < length; i++) {
result.push({
a: getRandomNumber(-1 * maxValue, maxValue),
@@ -37,6 +38,57 @@ function generateRandomNumberObjectList() {
e: getRandomNumber(-1 * maxValue, maxValue),
});
}
+
+ for (var i = 0; i < length; i++) {
+ const a = getRandomNumber(-1 * maxValue, maxValue);
+ result.push({
+ a: a,
+ b: getRandomNumber(-1 * maxValue, maxValue),
+ c: getRandomNumber(-1 * maxValue, maxValue),
+ d: getRandomNumber(-1 * maxValue, maxValue),
+ e: getRandomNumber(-1 * maxValue, maxValue),
+ });
+ }
+
+ for (var i = 0; i < length; i++) {
+ const a = getRandomNumber(-1 * maxValue, maxValue);
+ const b = getRandomNumber(-1 * maxValue, maxValue);
+ result.push({
+ a: a,
+ b: b,
+ c: getRandomNumber(-1 * maxValue, maxValue),
+ d: getRandomNumber(-1 * maxValue, maxValue),
+ e: getRandomNumber(-1 * maxValue, maxValue),
+ });
+ }
+
+ for (var i = 0; i < length; i++) {
+ const a = getRandomNumber(-1 * maxValue, maxValue);
+ const b = getRandomNumber(-1 * maxValue, maxValue);
+ const c = getRandomNumber(-1 * maxValue, maxValue);
+ result.push({
+ a: a,
+ b: b,
+ c: c,
+ d: getRandomNumber(-1 * maxValue, maxValue),
+ e: getRandomNumber(-1 * maxValue, maxValue),
+ });
+ }
+
+ for (var i = 0; i < length; i++) {
+ const a = getRandomNumber(-1 * maxValue, maxValue);
+ const b = getRandomNumber(-1 * maxValue, maxValue);
+ const c = getRandomNumber(-1 * maxValue, maxValue);
+ const d = getRandomNumber(-1 * maxValue, maxValue);
+ result.push({
+ a: a,
+ b: b,
+ c: c,
+ d: d,
+ e: getRandomNumber(-1 * maxValue, maxValue),
+ });
+ }
+
return result;
} | Changed random list generation to generate more similar elements for proper thenBy sorting testing | SvSchmidt_linqjs | train |
e1388f7a884c632db2c446ac86c9e389c6ac07c8 | diff --git a/lib/fakefs/file.rb b/lib/fakefs/file.rb
index <HASH>..<HASH> 100644
--- a/lib/fakefs/file.rb
+++ b/lib/fakefs/file.rb
@@ -94,7 +94,7 @@ module FakeFS
def self.size?(path)
if exists?(path) && !size(path).zero?
- true
+ size(path)
else
nil
end
diff --git a/test/fakefs_test.rb b/test/fakefs_test.rb
index <HASH>..<HASH> 100644
--- a/test/fakefs_test.rb
+++ b/test/fakefs_test.rb
@@ -522,7 +522,7 @@ class FakeFSTest < Test::Unit::TestCase
File.open(path, 'w') do |f|
f << 'Yada Yada'
end
- assert File.size?(path)
+ assert_equal 9, File.size?(path)
assert_nil File.size?("other.txt")
end | Fixed both File.size? and the test for such to match the documented
behavior for both Ruby <I> and <I>, which is to return nil if
the file is missing or is a zer-length file, but is to otherwise
return the actual size (not true as fakefs used to return). | fakefs_fakefs | train |
aeeb0a81b354e37cc65ed2eb941d67f08556dc07 | diff --git a/lib/subsequence-provider.js b/lib/subsequence-provider.js
index <HASH>..<HASH> 100644
--- a/lib/subsequence-provider.js
+++ b/lib/subsequence-provider.js
@@ -79,6 +79,8 @@ class SubsequenceProvider {
}))
}
+ // This is kind of a hack. We throw the config suggestions in a buffer, so
+ // we can use .findWordsWithSubsequence on them.
configSuggestionsToSubsequenceMatches (suggestions, prefix) {
const suggestionText = suggestions
.map(sug => sug.displayText || sug.snippet || sug.text)
@@ -146,11 +148,7 @@ class SubsequenceProvider {
editor.getBuffer().getTextInRange(cursor.getCurrentWordBufferRange())
)
- const subsequenceMatchToType = (match) => {
- const editor = this.watchedBuffers.get(match.buffer)
- const scopeDescriptor = editor.scopeDescriptorForBufferPosition(match.positions[0])
- return this.providerConfig.scopeDescriptorToType(scopeDescriptor)
- }
+ const strictMatchRegex = new RegExp(`^${prefix}`)
const bufferToMaxSearchRange = (buffer) => {
const position = this.watchedBuffers.get(buffer).getCursorBufferPosition()
@@ -158,35 +156,33 @@ class SubsequenceProvider {
}
const bufferToSubsequenceMatches = (buffer) => {
- const assocBuffer = match => { match.buffer = buffer; return match }
-
return buffer.findWordsWithSubsequenceInRange(
prefix,
this.additionalWordChars,
this.maxResultsPerBuffer,
bufferToMaxSearchRange(buffer)
- ).then(matches => matches.map(assocBuffer))
+ )
}
- const sortByScore = matches => matches.sort((a, b) => b.score - a.score)
-
- const head = matches => _.head(matches, this.maxSuggestions)
+ const subsequenceMatchToType = (match) => {
+ const editor = this.watchedBuffers.get(match.buffer)
+ const scopeDescriptor = editor.scopeDescriptorForBufferPosition(match.positions[0])
+ return this.providerConfig.scopeDescriptorToType(scopeDescriptor)
+ }
- const subsequenceMatchesToSuggestions = matches => matches.map(m => {
- return m.configSuggestion || {
- text: m.word,
- type: subsequenceMatchToType(m)
+ const matchToSuggestion = match => {
+ return match.configSuggestion || {
+ text: match.word,
+ type: subsequenceMatchToType(match)
}
- })
-
- const uniqueByWord = matches => _.uniq(matches, false, m => m.word)
+ }
- const notWordUnderCursor = matches => matches.filter(match =>
- wordsUnderCursors.indexOf(match.word) === -1 ||
- match.positions.length > wordsUnderCursors.filter(word => match.word === word).length
- )
+ const isWordUnderCursor = match => {
+ return !(wordsUnderCursors.indexOf(match.word) === -1 ||
+ match.positions.length > wordsUnderCursors.filter(word => match.word === word).length)
+ }
- const applyLocalityBonus = matches => matches.map(match => {
+ const applyLocalityBonus = match => {
if (match.buffer === editor.getBuffer() && match.score > 0) {
let lastCursorRow = editor.getLastCursor().getBufferPosition().row
let distances = match
@@ -196,28 +192,47 @@ class SubsequenceProvider {
match.score += Math.floor(11 / (1 + 0.04 * closest))
}
return match
- })
+ }
- const removeNonPrefixMatches = matches => matches.filter(match => {
- const regex = new RegExp('^' + prefix)
- return regex.exec(match.word)
- })
+ const isStrictIfEnabled = match => {
+ return this.strictMatching ? strictMatchRegex.exec(match.word) : true
+ }
- // when thinking about this, go from the bottom (flatten) up
- const transformToSuggestions = _.compose(
- subsequenceMatchesToSuggestions,
- head,
- notWordUnderCursor,
- uniqueByWord,
- sortByScore,
- (this.useLocalityBonus ? applyLocalityBonus : identity),
- (this.strictMatching ? removeNonPrefixMatches : identity),
- _.flatten
- )
+ const bufferResultsToSuggestions = matchesByBuffer => {
+ const relevantMatches = []
+ let matchedWords = {}
+
+ for (let k = 0; k < matchesByBuffer.length; k++) {
+ for (let l = 0; l < matchesByBuffer[k].length; l++) {
+ let match = matchesByBuffer[k][l]
+
+ if (isWordUnderCursor(match)) continue
+
+ if (!isStrictIfEnabled(match)) continue
+
+ if (matchedWords[match.word]) continue
+
+ if (k < matchesByBuffer.length - 1) {
+ match.buffer = buffers[k]
+ }
+
+ relevantMatches.push(
+ this.useLocalityBonus ? applyLocalityBonus(match) : match
+ )
+
+ matchedWords[match.word] = true
+ }
+ }
+
+ return relevantMatches
+ .sort((a, b) => b.score - a.score)
+ .slice(0, this.maxSuggestions)
+ .map(matchToSuggestion)
+ }
return Promise
.all(buffers.map(bufferToSubsequenceMatches).concat(configMatches))
- .then(transformToSuggestions)
+ .then(bufferResultsToSuggestions)
}
} | refactor subsequence provider to imperative | atom_autocomplete-plus | train |
55a9b05870ede2adf93b207a8ff1b8b60e5af06e | diff --git a/impl/src/main/java/org/jboss/weld/context/AbstractContext.java b/impl/src/main/java/org/jboss/weld/context/AbstractContext.java
index <HASH>..<HASH> 100644
--- a/impl/src/main/java/org/jboss/weld/context/AbstractContext.java
+++ b/impl/src/main/java/org/jboss/weld/context/AbstractContext.java
@@ -74,7 +74,7 @@ public abstract class AbstractContext implements AlterableContext {
throw new ContextNotActiveException();
}
checkContextInitialized();
- BeanStore beanStore = getBeanStore();
+ final BeanStore beanStore = getBeanStore();
if (beanStore == null) {
return null;
}
@@ -98,7 +98,7 @@ public abstract class AbstractContext implements AlterableContext {
T instance = contextual.create(creationalContext);
if (instance != null) {
beanInstance = new SerializableContextualInstanceImpl<Contextual<T>, T>(contextual, instance, creationalContext, serviceRegistry.get(ContextualStore.class));
- getBeanStore().put(id, beanInstance);
+ beanStore.put(id, beanInstance);
}
return instance;
} finally {
@@ -125,11 +125,12 @@ public abstract class AbstractContext implements AlterableContext {
if (contextual == null) {
throw ContextLogger.LOG.contextualIsNull();
}
- if (getBeanStore() == null) {
+ final BeanStore beanStore = getBeanStore();
+ if (beanStore == null) {
throw ContextLogger.LOG.noBeanStoreAvailable(this);
}
BeanIdentifier id = getId(contextual);
- ContextualInstance<?> beanInstance = getBeanStore().remove(id);
+ ContextualInstance<?> beanInstance = beanStore.remove(id);
if (beanInstance != null) {
RequestScopedCache.invalidate();
destroyContextualInstance(beanInstance);
@@ -137,10 +138,11 @@ public abstract class AbstractContext implements AlterableContext {
}
private <T> ContextualInstance<T> getContextualInstance(BeanIdentifier id) {
- if (getBeanStore() == null) {
+ final BeanStore beanStore = getBeanStore();
+ if (beanStore == null) {
throw ContextLogger.LOG.noBeanStoreAvailable(this);
}
- return getBeanStore().get(id);
+ return beanStore.get(id);
}
private <T> void destroyContextualInstance(ContextualInstance<T> instance) {
@@ -153,13 +155,14 @@ public abstract class AbstractContext implements AlterableContext {
*/
protected void destroy() {
ContextLogger.LOG.contextCleared(this);
- if (getBeanStore() == null) {
+ final BeanStore beanStore = getBeanStore();
+ if (beanStore == null) {
throw ContextLogger.LOG.noBeanStoreAvailable(this);
}
- for (BeanIdentifier id : getBeanStore()) {
+ for (BeanIdentifier id : beanStore) {
destroyContextualInstance(getContextualInstance(id));
}
- getBeanStore().clear();
+ beanStore.clear();
}
/**
@@ -170,11 +173,12 @@ public abstract class AbstractContext implements AlterableContext {
protected abstract BeanStore getBeanStore();
public void cleanup() {
- if (getBeanStore() != null) {
+ final BeanStore beanStore = getBeanStore();
+ if (beanStore != null) {
try {
- getBeanStore().clear();
+ beanStore.clear();
} catch (Exception e) {
- ContextLogger.LOG.unableToClearBeanStore(getBeanStore());
+ ContextLogger.LOG.unableToClearBeanStore(beanStore);
ContextLogger.LOG.catchingDebug(e);
}
}
diff --git a/impl/src/main/java/org/jboss/weld/context/http/HttpRequestContextImpl.java b/impl/src/main/java/org/jboss/weld/context/http/HttpRequestContextImpl.java
index <HASH>..<HASH> 100644
--- a/impl/src/main/java/org/jboss/weld/context/http/HttpRequestContextImpl.java
+++ b/impl/src/main/java/org/jboss/weld/context/http/HttpRequestContextImpl.java
@@ -53,8 +53,9 @@ public class HttpRequestContextImpl extends AbstractBoundContext<HttpServletRequ
ContextLogger.LOG.beanStoreLeakDuringAssociation(this.getClass().getName(), request);
}
// We always associate a new bean store to avoid possible leaks (security threats)
- setBeanStore(new RequestBeanStore(request, namingScheme));
- getBeanStore().attach();
+ final RequestBeanStore beanStore = new RequestBeanStore(request, namingScheme);
+ setBeanStore(beanStore);
+ beanStore.attach();
return true;
} | Contexts - minor improvements
An invocation of getBeanStore() usually involves ThreadLoca.get().
Therefore we should avoid unnecessary invocations if possible. | weld_core | train |
ce4945b6d07bede73a737d4b4c89e4b0e2c6b4a9 | diff --git a/openquake/engine/calculators/hazard/classical/core.py b/openquake/engine/calculators/hazard/classical/core.py
index <HASH>..<HASH> 100644
--- a/openquake/engine/calculators/hazard/classical/core.py
+++ b/openquake/engine/calculators/hazard/classical/core.py
@@ -333,10 +333,10 @@ class ClassicalHazardCalculator(general.BaseHazardCalculator):
for gsim_obj, probs in result:
gsim = gsim_obj.__class__.__name__
# probabilities of no exceedence per IMT
- pnes = numpy.array([1 if all_equal(p, 0) else 1 - p
- for p in probs])
+ pnes = numpy.array(
+ [1 - (zero if all_equal(prob, 0) else prob)
+ for prob, zero in itertools.izip(probs, self.zero)])
# TODO: add a test like Yufang computation testing the broadcast
- # add a test with different imls lenghts
self.curves[trt_model_id, gsim] = 1 - (
1 - self.curves.get((trt_model_id, gsim), self.zero)) * pnes | Fixed a broadcasting in the classical calculator
Former-commit-id: f<I>d2a<I>f<I>c<I>d<I>a<I> | gem_oq-engine | train |
d9150ecdadb47fbc725badea59dd0928d7baeeb2 | diff --git a/composer.json b/composer.json
index <HASH>..<HASH> 100644
--- a/composer.json
+++ b/composer.json
@@ -9,7 +9,7 @@
{"name": "Marek Štípek", "email": "[email protected]"}
],
"require": {
- "php": ">=7.0"
+ "php": ">=7.1"
},
"require-dev": {
"phpunit/phpunit": "^5.5",
@@ -29,7 +29,7 @@
},
"extra": {
"branch-alias": {
- "dev-master": "0.1.x-dev"
+ "dev-master": "0.2.x-dev"
}
}
}
diff --git a/src/Enum.php b/src/Enum.php
index <HASH>..<HASH> 100644
--- a/src/Enum.php
+++ b/src/Enum.php
@@ -122,8 +122,17 @@ abstract class Enum
{
static $valueNames = [];
- return $valueNames[static::class]
- ?? $valueNames[static::class] = array_keys((new ReflectionClass(static::class))->getConstants());
+ if (!isset($valueNames[static::class])) {
+ $valueNames[static::class] = [];
+
+ foreach ((new \ReflectionClass(static::class))->getReflectionConstants() as $reflectionConstant) {
+ if ($reflectionConstant->isPublic() && !$reflectionConstant->getDeclaringClass()->isInterface()) {
+ $valueNames[static::class][] = $reflectionConstant->name;
+ }
+ }
+ }
+
+ return $valueNames[static::class];
}
/**
diff --git a/tests/EnumTest.php b/tests/EnumTest.php
index <HASH>..<HASH> 100644
--- a/tests/EnumTest.php
+++ b/tests/EnumTest.php
@@ -7,11 +7,18 @@ use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
use Vanio\Stdlib\Enum;
-class Foo extends Enum
+interface Bar
{
- const BAR = 'FooBar';
- const BAZ = ['FooBaz'];
- const QUX = ['FooQux1', 'FooQux2'];
+ public const CORGE = 'BarCorge';
+}
+
+class Foo extends Enum implements Bar
+{
+ public const BAR = 'FooBar';
+ public const BAZ = ['FooBaz'];
+ public const QUX = ['FooQux1', 'FooQux2'];
+
+ private const QUUX = 'FooQux';
/** @var string */
public $value; | BC BREAK: Enum::valueNames excludes private constants and constants defined in interfaces | vaniocz_stdlib | train |
e2b287337aac88529660b80027c4614710cbdd82 | diff --git a/liquibase-core/src/main/java/liquibase/exception/ValidationErrors.java b/liquibase-core/src/main/java/liquibase/exception/ValidationErrors.java
index <HASH>..<HASH> 100644
--- a/liquibase-core/src/main/java/liquibase/exception/ValidationErrors.java
+++ b/liquibase-core/src/main/java/liquibase/exception/ValidationErrors.java
@@ -28,7 +28,24 @@ public class ValidationErrors {
}
}
- public void checkDisallowedField(String disallowedFieldName, Object value, Database database, Class<? extends Database>... disallowedDatabases) {
+ /**
+ * <p>Checks if a field is forbidden in combination with a given Database (most often because that database
+ * does not implement the features required by the field/value combination). If a "forbidden" use is detected,
+ * a validation error is added to the current list of ValidationErrors.</p>
+ * Note:
+ * <ul>
+ * <li>if value==null, the field is ALLOWED for all DBs</li>
+ * <li>if the disallowedDatabases list does not at least contain 1 entry, the field is NOT allowed</li>
+ * </ul>
+ *
+ * @param disallowedFieldName field whose value is checked
+ * @param value value that might be disallowed
+ * @param database database the object/value combination is checked against
+ * @param disallowedDatabases a list of "forbidden" databases that do not allow this field/value combination
+ */
+ @SafeVarargs
+ public final void checkDisallowedField(String disallowedFieldName, Object value, Database database,
+ Class<? extends Database>... disallowedDatabases) {
boolean isDisallowed = false;
if ((disallowedDatabases == null) || (disallowedDatabases.length == 0)) {
isDisallowed = true; | CLEANUP: Comment checkDisallowedField and mark it as @SafeVarargs | liquibase_liquibase | train |
98a26bbcc605d687f79f7b95c2eec73b793e297c | diff --git a/zipline/algorithm.py b/zipline/algorithm.py
index <HASH>..<HASH> 100644
--- a/zipline/algorithm.py
+++ b/zipline/algorithm.py
@@ -36,6 +36,7 @@ from six import (
from zipline._protocol import handle_non_market_minutes
from zipline.assets.synthetic import make_simple_equity_info
from zipline.data.data_portal import DataPortal
+from zipline.data.us_equity_pricing import PanelDailyBarReader
from zipline.errors import (
AttachPipelineAfterInitialize,
HistoryInInitialize,
@@ -76,7 +77,7 @@ from zipline.finance.slippage import (
SlippageModel
)
from zipline.finance.cancel_policy import NeverCancel, CancelPolicy
-from zipline.assets import Asset, Equity, Future
+from zipline.assets import Asset, Future
from zipline.assets.futures import FutureChain
from zipline.gens.tradesimulation import AlgorithmSimulator
from zipline.pipeline.engine import (
@@ -594,24 +595,18 @@ class TradingAlgorithm(object):
copy_panel.items = self._write_and_map_id_index_to_sids(
copy_panel.items, copy_panel.major_axis[0],
)
- self._assets_from_source = \
- set(self.trading_environment.asset_finder.retrieve_all(
+ self._assets_from_source = (
+ self.trading_environment.asset_finder.retrieve_all(
copy_panel.items
- ))
- equities = []
- for asset in self._assets_from_source:
- if isinstance(asset, Equity):
- equities.append(asset)
- if equities:
- from zipline.data.us_equity_pricing import \
- PanelDailyBarReader
- equity_daily_reader = PanelDailyBarReader(
- self.trading_environment.trading_days, copy_panel)
- else:
- equity_daily_reader = None
+ )
+ )
self.data_portal = DataPortal(
self.trading_environment,
- equity_daily_reader=equity_daily_reader)
+ equity_daily_reader=PanelDailyBarReader(
+ self.trading_environment.trading_days,
+ copy_panel,
+ ),
+ )
# Force a reset of the performance tracker, in case
# this is a repeat run of the algorithm. | BUG: Set _assets_from_source as a list. | quantopian_zipline | train |
bfc9d8bbea2f41247fa543034bbbf64704ae3aae | diff --git a/daemon/attach.go b/daemon/attach.go
index <HASH>..<HASH> 100644
--- a/daemon/attach.go
+++ b/daemon/attach.go
@@ -114,7 +114,7 @@ func (daemon *Daemon) ContainerAttach(job *engine.Job) engine.Status {
// FIXME: this should be private, and every outside subsystem
// should go through the "container_attach" job. But that would require
-// that job to be properly documented, as well as the relationship betweem
+// that job to be properly documented, as well as the relationship between
// Attach and ContainerAttach.
//
// This method is in use by builder/builder.go.
diff --git a/daemon/exec.go b/daemon/exec.go
index <HASH>..<HASH> 100644
--- a/daemon/exec.go
+++ b/daemon/exec.go
@@ -243,7 +243,7 @@ func (container *Container) Exec(execConfig *execConfig) error {
callback := func(processConfig *execdriver.ProcessConfig, pid int) {
if processConfig.Tty {
// The callback is called after the process Start()
- // so we are in the parent process. In TTY mode, stdin/out/err is the PtySlace
+ // so we are in the parent process. In TTY mode, stdin/out/err is the PtySlave
// which we close here.
if c, ok := processConfig.Stdout.(io.Closer); ok {
c.Close()
diff --git a/daemon/monitor.go b/daemon/monitor.go
index <HASH>..<HASH> 100644
--- a/daemon/monitor.go
+++ b/daemon/monitor.go
@@ -236,7 +236,7 @@ func (m *containerMonitor) shouldRestart(exitStatus int) bool {
func (m *containerMonitor) callback(processConfig *execdriver.ProcessConfig, pid int) {
if processConfig.Tty {
// The callback is called after the process Start()
- // so we are in the parent process. In TTY mode, stdin/out/err is the PtySlace
+ // so we are in the parent process. In TTY mode, stdin/out/err is the PtySlave
// which we close here.
if c, ok := processConfig.Stdout.(io.Closer); ok {
c.Close() | Fix typo:betweem->between and PtySlace->PtySlave | containers_storage | train |
3b1d24b8b4f3d53fd5784d7042c699314570bf22 | diff --git a/lib/mo-helpers.js b/lib/mo-helpers.js
index <HASH>..<HASH> 100644
--- a/lib/mo-helpers.js
+++ b/lib/mo-helpers.js
@@ -24,7 +24,7 @@ var moToAsciiMath = {
'¯' : 'bar',
'→' : 'vec',
'↔' : 'line',
- '\u2312' : 'arc',
+ '\u23DC' : 'arc',
'±': '+-',
'?' : '?',
'∠' : '/_', | top parens for arc; is in MathJax font | learningobjectsinc_mathml-to-asciimath | train |
bf9ce3ce48906cf43916a66bac09a47e3c3ec118 | diff --git a/gitenberg/make.py b/gitenberg/make.py
index <HASH>..<HASH> 100644
--- a/gitenberg/make.py
+++ b/gitenberg/make.py
@@ -41,31 +41,47 @@ class CdContext():
sh.cd(self._og_directory)
-def make_local_repo(book_path):
+class LocalRepo():
- with CdContext(book_path):
+ def __init__(self, book_id, book_path):
+ self.book_id = book_id
+ self.book_path = book_path
- repo = git.Repo.init('./')
+ def add_file(self, filename):
+ filetype = os.path.splitext(filename)[1]
+ if filetype not in IGNORE_FILES:
+ sh.git('add', filename)
- for _file in repo.untracked_files:
- filetype = os.path.splitext(_file)[1]
- if filetype not in IGNORE_FILES:
- sh.git('add', _file)
+ def commit(self, message):
+ with CdContext(self.book_path):
+ try:
+ # note the double quotes around the message
+ sh.git(
+ 'commit',
+ '-m',
+ '"{message}"'.format(message=message)
+ )
+ except sh.ErrorReturnCode_1:
+ print "Commit aborted for {0} with msg {1}".format(self.book_id, message)
- try:
- # note the double quotes
- sh.git('commit', '-m', '"Initial import from Project Gutenberg"')
- except sh.ErrorReturnCode_1:
- print "we have already created this repo locally, aborting"
+ def add_all_files(self):
+
+ with CdContext(self.book_path):
+ repo = git.Repo.init('./')
+ for _file in repo.untracked_files:
+ self.add_file(_file)
class NewFilesHandler():
""" NewFilesHandler - templates and copies additional files to book repos
"""
+ README_FILENAME = 'README.rst'
+
def __init__(self, book_id, book_path):
self.meta = EbookRecord(book_id)
self.book_path = book_path
+ self.added_files = []
package_loader = jinja2.PackageLoader('gitenberg', 'templates')
self.env = jinja2.Environment(loader=package_loader)
@@ -78,9 +94,10 @@ class NewFilesHandler():
#print type(self.meta.title), self.meta.title
#print type(self.meta.author), self.meta.author
- readme_path = "{0}/{1}".format(self.book_path, 'README.rst')
+ readme_path = "{0}/{1}".format(self.book_path, self.README_FILENAME)
with codecs.open(readme_path, 'w', 'utf-8') as readme_file:
readme_file.write(readme_text)
+ self.added_files.append(self.README_FILENAME)
def copy_files(self):
""" Copy the LICENSE and CONTRIBUTING files to each folder repo """
@@ -91,9 +108,14 @@ class NewFilesHandler():
'{0}/templates/{1}'.format(this_dir, _file),
'{0}/'.format(self.book_path)
)
+ self.added_files.append(_file)
def make(book_id):
book_path = path_to_library_book(book_id)
- make_local_repo(book_path)
+ local_repo = LocalRepo(book_id, book_path)
+ local_repo.add_all_files()
+ local_repo.commit("Initial import from Project Gutenberg")
NewFilesHandler(book_id, book_path)
+ local_repo.add_all_files()
+ local_repo.commit("Adds Readme, contributing and license files to book repo") | refactors git operations into a class | gitenberg-dev_gitberg | train |
96271ea87273bf601818ec4062ec3177254ea5dd | diff --git a/spec/unit/compiler/file/coffee_script_file_spec.rb b/spec/unit/compiler/file/coffee_script_file_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/compiler/file/coffee_script_file_spec.rb
+++ b/spec/unit/compiler/file/coffee_script_file_spec.rb
@@ -32,7 +32,7 @@ module Epuber
end
it 'handles ugly file with all xml bullshit lines' do
- source = <<-COFFEE.strip_heredoc
+ source = <<~COFFEE
math =
root: Math.sqrt
square: square
@@ -51,7 +51,7 @@ module Epuber
file.compilation_context = ctx
file.process(ctx)
- expected_content = <<-JS.strip_heredoc
+ expected_content = <<~JS
(function() {
var math;
diff --git a/spec/unit/compiler/text_processor_spec.rb b/spec/unit/compiler/text_processor_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/compiler/text_processor_spec.rb
+++ b/spec/unit/compiler/text_processor_spec.rb
@@ -37,7 +37,7 @@ module Epuber
end
it 'can parse xml with headers' do
- input = <<-XML.strip_heredoc
+ input = <<~XML
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html>
<p>abc</p>
@@ -54,7 +54,7 @@ module Epuber
expect(doc.root.name).to eq 'body'
expect(doc.root.children.count).to eq 15 # 7 elements + 8 newlines
- expected_output = <<-XML.strip_heredoc
+ expected_output = <<~XML
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html>
<body> | tests - drop using String#strip_heredoc from Bade | epuber-io_epuber | train |
6b7b43216762283bfae7d5988f4493a935cfa965 | diff --git a/pkg/endpoint/endpoint_status_test.go b/pkg/endpoint/endpoint_status_test.go
index <HASH>..<HASH> 100644
--- a/pkg/endpoint/endpoint_status_test.go
+++ b/pkg/endpoint/endpoint_status_test.go
@@ -282,6 +282,42 @@ func (s *EndpointSuite) TestgetEndpointPolicyMapState(c *check.C) {
ingressResult []apiResult
}{
{
+ name: "Deny all",
+ },
+ {
+ name: "Allow world ingress",
+ args: []args{
+ {uint32(identity.ReservedIdentityWorld), 0, 0, trafficdirection.Ingress},
+ },
+ ingressResult: []apiResult{
+ {"reserved:world", uint64(identity.ReservedIdentityWorld), 0, 0},
+ },
+ egressResult: nil,
+ },
+ {
+ name: "Allow world egress",
+ args: []args{
+ {uint32(identity.ReservedIdentityWorld), 0, 0, trafficdirection.Egress},
+ },
+ ingressResult: nil,
+ egressResult: []apiResult{
+ {"reserved:world", uint64(identity.ReservedIdentityWorld), 0, 0},
+ },
+ },
+ {
+ name: "Allow world both directions",
+ args: []args{
+ {uint32(identity.ReservedIdentityWorld), 0, 0, trafficdirection.Ingress},
+ {uint32(identity.ReservedIdentityWorld), 0, 0, trafficdirection.Egress},
+ },
+ ingressResult: []apiResult{
+ {"reserved:world", uint64(identity.ReservedIdentityWorld), 0, 0},
+ },
+ egressResult: []apiResult{
+ {"reserved:world", uint64(identity.ReservedIdentityWorld), 0, 0},
+ },
+ },
+ {
name: "Ingress mix of L3, L4, L3-dependent L4",
args: []args{
{uint32(fooIdentity.ID), 0, 0, trafficdirection.Ingress}, // L3-only map state
@@ -295,6 +331,20 @@ func (s *EndpointSuite) TestgetEndpointPolicyMapState(c *check.C) {
},
egressResult: nil,
},
+ {
+ name: "Egress mix of L3, L4, L3-dependent L4",
+ args: []args{
+ {uint32(fooIdentity.ID), 0, 0, trafficdirection.Egress}, // L3-only map state
+ {0, 80, 6, trafficdirection.Egress}, // L4-only map state
+ {uint32(fooIdentity.ID), 80, 6, trafficdirection.Egress}, // L3-dependent L4 map state
+ },
+ ingressResult: nil,
+ egressResult: []apiResult{
+ {"unspec:foo", uint64(fooIdentity.ID), 0, 0},
+ {"", 0, 80, 6},
+ {"unspec:foo", uint64(fooIdentity.ID), 80, 6},
+ },
+ },
}
for _, tt := range tests { | endpoint: Expand coverage of EndpointPolicy API | cilium_cilium | train |
0d6c8cc3f5e0707164344d33581a8b5068ba59a1 | diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -119,6 +119,32 @@ The `.nodeshift` directory is responsible for holding your resource files. Thes
Currently, nodeshift will only create resources based on the files specified, in the future, its possible somethings could be created by default
+#### Template Parameters
+
+Some templates might need to have a value set at "run time". For example, in the template below, we have the `${SSO_AUTH_SERVER_URL}` parameter:
+
+ apiVersion: v1
+ kind: Deployment
+ metadata:
+ name: nodejs-rest-http-secured
+ spec:
+ template:
+ spec:
+ containers:
+ - env:
+ - name: SSO_AUTH_SERVER_URL
+ value: "${SSO_AUTH_SERVER_URL}"
+ - name: REALM
+ value: master
+
+To set that using nodeshift, use the `-d` option with a KEY=VALUE, like this:
+
+ nodeshift -d SSO_AUTH_SERVER_URL=https://sercure-url
+
+__note that we left off the "${}" on the key, nodeshift knows to search for a key with ${} added back on__
+
+For more on writing openshift templates, [see here](https://docs.openshift.org/latest/dev_guide/templates.html#writing-templates)
+
### Advanced Options
There are a few options available on the CLI or when using the API
diff --git a/lib/resource-loader.js b/lib/resource-loader.js
index <HASH>..<HASH> 100644
--- a/lib/resource-loader.js
+++ b/lib/resource-loader.js
@@ -21,8 +21,9 @@ function loadYamls (resourceList, config) {
// Do i parse the result here? or should i wait?
const jsonYaml = helpers.yamlToJson(data);
const stringJSON = JSON.stringify(jsonYaml);
+ /* eslint prefer-template: "off" */
const reduced = config.definedProperties.reduce((acc, curr) => {
- return acc.split(curr.key).join(curr.value);
+ return acc.split('${' + curr.key + '}').join(curr.value);
}, stringJSON);
const backToJSON = JSON.parse(reduced);
return resolve(backToJSON);
diff --git a/test/resource-loader-test.js b/test/resource-loader-test.js
index <HASH>..<HASH> 100644
--- a/test/resource-loader-test.js
+++ b/test/resource-loader-test.js
@@ -145,12 +145,13 @@ test.skip('test error reading file from list', (t) => {
});
});
+/* eslint no-template-curly-in-string: "off" */
test('test string substitution', (t) => {
const mockedHelper = {
yamlToJson: (file) => {
return {
templates: {
- SSO_AUTH_SERVER_URL: '{SSO_AUTH_SERVER_URL}'
+ SSO_AUTH_SERVER_URL: '${SSO_AUTH_SERVER_URL}'
}
};
}
@@ -175,7 +176,7 @@ test('test string substitution', (t) => {
const config = {
projectLocation: process.cwd(),
nodeshiftDirectory: '.nodeshift',
- definedProperties: [{key: '{SSO_AUTH_SERVER_URL}', value: 'https://yea'}]
+ definedProperties: [{key: 'SSO_AUTH_SERVER_URL', value: 'https://yea'}]
};
resourceLoader(config).then((resourceList) => { | fix: Template parameters should be inline with the openshift templates.
A small change, but it is important.
Now the user doesn't need to pass in the key with the {} added on, nodeshift will add around the key
fixes #<I> | nodeshift_nodeshift | train |
06bd446c5c731b722b9e9316f1c8294829f0197a | diff --git a/scripts/run.py b/scripts/run.py
index <HASH>..<HASH> 100755
--- a/scripts/run.py
+++ b/scripts/run.py
@@ -1065,8 +1065,8 @@ class TestRunner:
"-f",
runner_setup_package_r]
if self.path_to_tar is not None:
- print "Using R TAR located at: " + self.path_to_tar
- cmd += ["--args", self.path_to_tar]
+ print "Using R TAR located at: " + self.path_to_tar
+ cmd += ["--args", self.path_to_tar]
child = subprocess.Popen(args=cmd,
stdout=out,
stderr=subprocess.STDOUT)
@@ -1653,8 +1653,8 @@ def parse_args(argv):
elif s == "--c":
g_convenient = True
elif s == "--tar":
- i += 1
- g_path_to_tar = os.path.abspath(argv[i])
+ i += 1
+ g_path_to_tar = os.path.abspath(argv[i])
elif (s == "--jvm.xmx"):
i += 1
if (i > len(argv)): | Fix PEP-8 indentation warnings. | h2oai_h2o-3 | train |
bdb0a164fe0d8884d3d7b22daaf762607df3eb35 | diff --git a/module/communication/controller/src/main/java/org/openbase/jul/communication/controller/AbstractControllerServer.java b/module/communication/controller/src/main/java/org/openbase/jul/communication/controller/AbstractControllerServer.java
index <HASH>..<HASH> 100644
--- a/module/communication/controller/src/main/java/org/openbase/jul/communication/controller/AbstractControllerServer.java
+++ b/module/communication/controller/src/main/java/org/openbase/jul/communication/controller/AbstractControllerServer.java
@@ -793,9 +793,6 @@ public abstract class AbstractControllerServer<M extends AbstractMessage, MB ext
newData = updateDataToPublish(cloneDataBuilder());
final Event event = Event.newBuilder()
.setPayload(Any.pack(newData))
- .putHeader(
- RPCUtils.USER_TIME_KEY,
- Any.pack(Primitive.newBuilder().setLong(System.nanoTime()).build()))
.build();
// only publish if controller is active | remove now unnecessary usage of user time in our custom event type | openbase_jul | train |
2162b7a50c97ae40e450ae38e3e8e3c7bd1be95a | diff --git a/Swat/SwatPagination.php b/Swat/SwatPagination.php
index <HASH>..<HASH> 100644
--- a/Swat/SwatPagination.php
+++ b/Swat/SwatPagination.php
@@ -15,13 +15,15 @@ class SwatPagination extends SwatControl {
/**
* Href
*
- * The URL of the current page, used to build links.
+ * The initial HREF used when building links. If null, link HREF's will
+ * begin with '?'.
+ *
* @var int
*/
public $href = null;
/**
- * Get vars to clobber
+ * HTTP GET vars to clobber
*
* An array of GET variable names to unset before rebuilding new link.
* @var int
@@ -169,8 +171,7 @@ class SwatPagination extends SwatControl {
$href.= $name.'='.$value.'&';
// remove trailing ampersand
- if (count($vars))
- $href = substr($href, 0, -1);
+ $href = substr($href, 0, -1);
return $href;
} | Cleanup docs and bugfix.
svn commit r<I> | silverorange_swat | train |
d85becb90341b6c0f6e9bedd6d1117cc5df14b3a | diff --git a/models.py b/models.py
index <HASH>..<HASH> 100644
--- a/models.py
+++ b/models.py
@@ -25,7 +25,7 @@ BibDoc Filesystem database model.
from invenio.ext.sqlalchemy import db
# Create your models here.
-from invenio.modules.record_editor.models import Bibdoc
+from invenio.modules.editor.models import Bibdoc
class Bibdocfsinfo(db.Model): | editor: move from record_editor | inveniosoftware-attic_invenio-documents | train |
fc30b0041aa9c13da831b982f254d29838b584a7 | diff --git a/lib/class-wp-json-posts.php b/lib/class-wp-json-posts.php
index <HASH>..<HASH> 100644
--- a/lib/class-wp-json-posts.php
+++ b/lib/class-wp-json-posts.php
@@ -1185,13 +1185,13 @@ class WP_JSON_Posts {
if ( ! empty( $data['date'] ) ) {
$date_data = $this->server->get_date_with_gmt( $data['date'] );
if ( ! empty( $date_data ) ) {
- list( $post['post_date'], $post['post_date_gmt'] ) = $data;
+ list( $post['post_date'], $post['post_date_gmt'] ) = $date_data;
}
}
elseif ( ! empty( $data['date_gmt'] ) ) {
$date_data = $this->server->get_date_with_gmt( $data['date_gmt'], true );
if ( ! empty( $date_data ) ) {
- list( $post['post_date'], $post['post_date_gmt'] ) = $data;
+ list( $post['post_date'], $post['post_date_gmt'] ) = $date_data;
}
}
@@ -1199,13 +1199,13 @@ class WP_JSON_Posts {
if ( ! empty( $data['modified'] ) ) {
$date_data = $this->server->get_date_with_gmt( $data['modified'] );
if ( ! empty( $date_data ) ) {
- list( $post['post_modified'], $post['post_modified_gmt'] ) = $data;
+ list( $post['post_modified'], $post['post_modified_gmt'] ) = $date_data;
}
}
elseif ( ! empty( $data['modified_gmt'] ) ) {
$date_data = $this->server->get_date_with_gmt( $data['modified_gmt'], true );
if ( ! empty( $date_data ) ) {
- list( $post['post_modified'], $post['post_modified_gmt'] ) = $data;
+ list( $post['post_modified'], $post['post_modified_gmt'] ) = $date_data;
}
} | Set post dates and modified dates with the correct variable. Fixes #<I>. | WP-API_WP-API | train |
db43eece1ce74dd3992f40e5efab6249fee496f9 | diff --git a/RoboFile.php b/RoboFile.php
index <HASH>..<HASH> 100644
--- a/RoboFile.php
+++ b/RoboFile.php
@@ -16,7 +16,7 @@ class RoboFile extends \Robo\Tasks
$this->publishDocs();
$this->installDependenciesForPhp54();
$this->buildPhar54();
- $this->installDependenciesForPhp55();
+ $this->installDependenciesForPhp56();
$this->buildPhar();
$this->revertComposerJsonChanges();
$this->publishPhar();
@@ -156,11 +156,11 @@ class RoboFile extends \Robo\Tasks
$this->taskComposerUpdate()->run();
}
- private function installDependenciesForPhp55()
+ private function installDependenciesForPhp56()
{
$this->taskReplaceInFile('composer.json')
->regex('/"platform": \{.*?\}/')
- ->to('"platform": {"php": "5.5.10"}')
+ ->to('"platform": {"php": "5.6.0"}')
->run();
$this->taskComposerUpdate()->run();
@@ -449,7 +449,7 @@ class RoboFile extends \Robo\Tasks
}
$versionLine = "* [$releaseName](http://codeception.com/releases/$releaseName/codecept.phar)";
if (file_exists("releases/$releaseName/php54/codecept.phar")) {
- $versionLine .= ", [for PHP 5.4](http://codeception.com/releases/$releaseName/php54/codecept.phar)";
+ $versionLine .= ", [for PHP 5.4 or 5.5](http://codeception.com/releases/$releaseName/php54/codecept.phar)";
}
$releaseFile->line($versionLine);
} | Build codecept.phar for PHP <I> to include PHPUnit 5 | Codeception_Codeception | train |
01fe731a14bb59f6935515565e2bac28dbb5ffaf | diff --git a/js/calendar.js b/js/calendar.js
index <HASH>..<HASH> 100644
--- a/js/calendar.js
+++ b/js/calendar.js
@@ -767,25 +767,25 @@ if(!String.prototype.format) {
if(!this.options.views[this.options.view].slide_events) {
return;
}
-
var self = this;
- var activecell = 0;
+ var activecell = 0;
var downbox = $(document.createElement('div')).attr('id', 'cal-day-box').html('<i class="icon-chevron-down"></i>');
- $('.cal-month-day, .cal-year-box .span3').each(function(k, v) {
- $(v).on('mouseenter', function() {
- if($('.events-list', v).length == 0) return;
+ $('.cal-month-day, .cal-year-box .span3')
+ .on('mouseenter', function() {
+ if($('.events-list', this).length == 0) return;
if($(this).children('[data-cal-date]').text() == self.activecell) return;
- downbox.show().appendTo(v);
- }).on('mouseleave', function() {
+ downbox.show().appendTo(this);
+ })
+ .on('mouseleave', function() {
downbox.hide();
- }).on('click', function(event){
- if($('.events-list', v).length == 0) return;
+ })
+ .on('click', function(event){
+ if($('.events-list', this).length == 0) return;
if($(this).children('[data-cal-date]').text() == self.activecell) return;
- showEventsList(event, downbox, slider, self);
- });
- });
-
+ showEventsList(event, downbox, slider, self);
+ })
+ ;
var slider = $(document.createElement('div')).attr('id', 'cal-slide-box');
slider.hide().click(function(event) { | Simplify event calls
Remove useless $.each | Serhioromano_bootstrap-calendar | train |
0c165605384d9fbc57aa71c855950696a3852b81 | diff --git a/test/basic-CRUD.js b/test/basic-CRUD.js
index <HASH>..<HASH> 100644
--- a/test/basic-CRUD.js
+++ b/test/basic-CRUD.js
@@ -26,7 +26,7 @@ describe("basic CRUD including working liveQueries",function(){
fighterModel = mr.model('fighter');
});
- it('should allow to query model', function(done){
+ it.only('should allow to query model', function(done){
LQ = fighterModel.liveQuery().sort('health').exec();
var subId = LQ.on('init', function(evName, params) { | reuse promise from socket.io-rpc and test only first test | capaj_Moonridge | train |
650862a59de06ab1eee63f4de97385c22aceacb6 | diff --git a/test/runtime/verifier.go b/test/runtime/verifier.go
index <HASH>..<HASH> 100644
--- a/test/runtime/verifier.go
+++ b/test/runtime/verifier.go
@@ -1,4 +1,4 @@
-// Copyright 2018 Authors of Cilium
+// Copyright 2018-2019 Authors of Cilium
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@@ -41,6 +41,9 @@ var _ = Describe("RuntimeVerifier", func() {
ExpectCiliumNotRunning(vm)
res = vm.ExecWithSudo("rm -f /sys/fs/bpf/tc/globals/cilium*")
res.ExpectSuccess()
+ cmd := fmt.Sprintf("make -C %s/../bpf clean V=0", helpers.BasePath)
+ res = vm.Exec(cmd)
+ res.ExpectSuccess("Expected cleaning the bpf/ tree to succeed")
})
AfterFailed(func() { | test: Ensure that verifier test runs on clean dir
Clean the bpf/ directory at the beginning of the verifier tests, to
ensure that the datapath is freshly compiled during the test and that
version is validated (rather than some cached version from prior
compilation earlier in the build process). | cilium_cilium | train |
f5f32db6999ad9e56db9bb3559200b5892c10d18 | diff --git a/lib/building/tasks.js b/lib/building/tasks.js
index <HASH>..<HASH> 100644
--- a/lib/building/tasks.js
+++ b/lib/building/tasks.js
@@ -24,12 +24,9 @@ bozon.task('scripts:main', function () {
bozon.task('scripts:renderer', function () {
var webpack = bozon.requireLocal('webpack-stream')
- return bozon.src('javascripts/renderer/application.*').pipe(webpack({
- target: 'electron',
- output: {
- filename: 'application.js'
- }
- })).pipe(bozon.dest('javascripts/renderer'))
+ return bozon.src('javascripts/renderer/application.*').pipe(
+ webpack(bozon.webpackConfig())
+ ).pipe(bozon.dest('javascripts/renderer'))
})
bozon.task('images', function () {
diff --git a/lib/utils/bozon.js b/lib/utils/bozon.js
index <HASH>..<HASH> 100644
--- a/lib/utils/bozon.js
+++ b/lib/utils/bozon.js
@@ -1,3 +1,4 @@
+var fs = require('fs')
var path = require('path')
var childProcess = require('child_process')
var Settings = require('./settings')
@@ -5,6 +6,13 @@ var Settings = require('./settings')
var bozon = {
Settings: Settings,
+ defaultWebpackConfig: {
+ target: "electron",
+ output: {
+ filename: "application.js"
+ }
+ },
+
task: function () {
return this.requireLocal('gulp').task.apply(this.requireLocal('gulp'), arguments)
},
@@ -85,6 +93,16 @@ var bozon = {
return path.join(process.cwd(), 'builds', settings.env(), suffix)
},
+ webpackConfig: function () {
+ var webpackConfig = path.join(process.cwd(), '/webpack.config.js')
+
+ if (fs.existsSync(webpackConfig)) {
+ return require(webpackConfig)
+ } else {
+ return this.defaultWebpackConfig
+ }
+ },
+
hooks: []
} | Allow to configure webpack with webpack.config.js | railsware_bozon | train |
669c56f57ea066e9d1e348af4a0fc3f5f68a4f98 | diff --git a/andes/config/system.py b/andes/config/system.py
index <HASH>..<HASH> 100644
--- a/andes/config/system.py
+++ b/andes/config/system.py
@@ -10,15 +10,6 @@ try:
except ImportError:
klu = None
-try:
- cupy_sparse = importlib.import_module('cupyx.scipy.sparse')
- cupy_solve = importlib.import_module('cupyx.scipy.sparse.linalg.solve')
- cu_csc = getattr(cupy_sparse, 'csc_matrix')
- cu_lsqr = getattr(cupy_solve, 'lsqr')
-except ImportError:
- cu_csc = None
- cu_lsqr = None
-
class System(ConfigBase):
def __init__(self, **kwargs):
@@ -74,8 +65,14 @@ class System(ConfigBase):
logger.info("KLU not found. Install with \"pip install cvxoptklu\" ")
self.sparselib = 'umfpack'
- elif self.sparselib == 'cupy' and (any((cu_csc, cu_lsqr)) is None):
- logger.info("CuPy not found. Fall back to UMFPACK.")
- self.sparselib = 'umfpack'
+ elif self.sparselib == 'cupy':
+ try:
+ cupy_sparse = importlib.import_module('cupyx.scipy.sparse')
+ cupy_solve = importlib.import_module('cupyx.scipy.sparse.linalg.solve')
+ _ = getattr(cupy_sparse, 'csc_matrix') # NOQA
+ _ = getattr(cupy_solve, 'lsqr') # NOQA
+ except (ImportError, AttributeError):
+ logger.info("CuPy not found. Fall back to UMFPACK.")
+ self.sparselib = 'umfpack'
return True
diff --git a/andes/utils/solver.py b/andes/utils/solver.py
index <HASH>..<HASH> 100644
--- a/andes/utils/solver.py
+++ b/andes/utils/solver.py
@@ -1,12 +1,6 @@
from scipy.sparse import csc_matrix
from scipy.sparse.linalg import spsolve
-try:
- import cupy as cp
- from cupyx.scipy.sparse import csc_matrix as csc_cu
- from cupyx.scipy.sparse.linalg.solve import lsqr as cu_lsqr
-except ImportError:
- CP = False
from cvxopt import umfpack, matrix
@@ -146,6 +140,11 @@ class Solver(object):
return matrix(x)
elif self.sparselib == 'cupy':
+ # delayed import for startup speed
+ import cupy as cp # NOQA
+ from cupyx.scipy.sparse import csc_matrix as csc_cu # NOQA
+ from cupyx.scipy.sparse.linalg.solve import lsqr as cu_lsqr # NOQA
+
cu_A = csc_cu(A)
cu_b = cp.array(np.array(b).reshape((-1,)))
x = cu_lsqr(cu_A, cu_b) | Delay cupy import for startup speed improvement | cuihantao_andes | train |
5f497da5a4f35543efa8fa3c84f790e3f60419a5 | diff --git a/graphviz/backend/upstream_version.py b/graphviz/backend/upstream_version.py
index <HASH>..<HASH> 100644
--- a/graphviz/backend/upstream_version.py
+++ b/graphviz/backend/upstream_version.py
@@ -51,7 +51,6 @@ def version() -> typing.Tuple[int, ...]:
https://gitlab.com/graphviz/graphviz/-/blob/f94e91ba819cef51a4b9dcb2d76153684d06a913/gen_version.py#L17-20
"""
cmd = [dot_command.DOT_BINARY, '-V']
- log.debug('run %r', cmd)
proc = execute.run_check(cmd,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
encoding='ascii') | drop run logging from version(), logged inside execute.run_check() | xflr6_graphviz | train |
01d9488bcc0a84d75f0955901268188564fb0387 | diff --git a/Request/RequestHandler.php b/Request/RequestHandler.php
index <HASH>..<HASH> 100755
--- a/Request/RequestHandler.php
+++ b/Request/RequestHandler.php
@@ -19,7 +19,7 @@ use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Serializer\SerializerInterface;
use WellCommerce\Bundle\ApiBundle\Exception\ResourceNotFoundException;
-use WellCommerce\Bundle\CoreBundle\Manager\ManagerInterface;
+use WellCommerce\Bundle\DoctrineBundle\Manager\ManagerInterface;
use WellCommerce\Component\DataSet\Conditions\ConditionsCollection;
use WellCommerce\Component\DataSet\Conditions\ConditionsResolver;
use WellCommerce\Component\DataSet\DataSetInterface;
diff --git a/Request/RequestHandlerInterface.php b/Request/RequestHandlerInterface.php
index <HASH>..<HASH> 100755
--- a/Request/RequestHandlerInterface.php
+++ b/Request/RequestHandlerInterface.php
@@ -34,7 +34,7 @@ interface RequestHandlerInterface
public function getDataset();
/**
- * @return \WellCommerce\Bundle\CoreBundle\Manager\ManagerInterface
+ * @return \WellCommerce\Bundle\DoctrineBundle\Manager\ManagerInterface
*/
public function getManager(); | New managers, datasets, removed query builders | WellCommerce_CouponBundle | train |
16d64d692505e289a2f80ba00d854cfd8dce39e2 | diff --git a/hack/.golint_failures b/hack/.golint_failures
index <HASH>..<HASH> 100644
--- a/hack/.golint_failures
+++ b/hack/.golint_failures
@@ -151,7 +151,6 @@ pkg/kubelet/apis/deviceplugin/v1beta1
pkg/kubelet/cadvisor
pkg/kubelet/cadvisor/testing
pkg/kubelet/checkpointmanager/testing/example_checkpoint_formats/v1
-pkg/kubelet/client
pkg/kubelet/cm
pkg/kubelet/config
pkg/kubelet/configmap
diff --git a/pkg/kubelet/client/kubelet_client.go b/pkg/kubelet/client/kubelet_client.go
index <HASH>..<HASH> 100644
--- a/pkg/kubelet/client/kubelet_client.go
+++ b/pkg/kubelet/client/kubelet_client.go
@@ -22,7 +22,7 @@ import (
"strconv"
"time"
- "k8s.io/api/core/v1"
+ v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
utilnet "k8s.io/apimachinery/pkg/util/net"
@@ -31,11 +31,16 @@ import (
nodeutil "k8s.io/kubernetes/pkg/util/node"
)
+// KubeletClientConfig defines config parameters for the kubelet client
type KubeletClientConfig struct {
- // Default port - used if no information about Kubelet port can be found in Node.NodeStatus.DaemonEndpoints.
- Port uint
+ // Port specifies the default port - used if no information about Kubelet port can be found in Node.NodeStatus.DaemonEndpoints.
+ Port uint
+
+ // ReadOnlyPort specifies the Port for ReadOnly communications.
ReadOnlyPort uint
- EnableHttps bool
+
+ // EnableHTTPs specifies if traffic should be encrypted.
+ EnableHTTPS bool
// PreferredAddressTypes - used to select an address from Node.NodeStatus.Addresses
PreferredAddressTypes []string
@@ -66,6 +71,7 @@ type ConnectionInfoGetter interface {
GetConnectionInfo(ctx context.Context, nodeName types.NodeName) (*ConnectionInfo, error)
}
+// MakeTransport creates a RoundTripper for HTTP Transport.
func MakeTransport(config *KubeletClientConfig) (http.RoundTripper, error) {
tlsConfig, err := transport.TLSConfigFor(config.transportConfig())
if err != nil {
@@ -96,7 +102,7 @@ func (c *KubeletClientConfig) transportConfig() *transport.Config {
},
BearerToken: c.BearerToken,
}
- if c.EnableHttps && !cfg.HasCA() {
+ if c.EnableHTTPS && !cfg.HasCA() {
cfg.TLS.Insecure = true
}
return cfg
@@ -110,6 +116,7 @@ type NodeGetter interface {
// NodeGetterFunc allows implementing NodeGetter with a function
type NodeGetterFunc func(ctx context.Context, name string, options metav1.GetOptions) (*v1.Node, error)
+// Get fetches information via NodeGetterFunc.
func (f NodeGetterFunc) Get(ctx context.Context, name string, options metav1.GetOptions) (*v1.Node, error) {
return f(ctx, name, options)
}
@@ -128,9 +135,10 @@ type NodeConnectionInfoGetter struct {
preferredAddressTypes []v1.NodeAddressType
}
+// NewNodeConnectionInfoGetter creates a new NodeConnectionInfoGetter.
func NewNodeConnectionInfoGetter(nodes NodeGetter, config KubeletClientConfig) (ConnectionInfoGetter, error) {
scheme := "http"
- if config.EnableHttps {
+ if config.EnableHTTPS {
scheme = "https"
}
@@ -154,6 +162,7 @@ func NewNodeConnectionInfoGetter(nodes NodeGetter, config KubeletClientConfig) (
}, nil
}
+// GetConnectionInfo retrieves connection info from the status of a Node API object.
func (k *NodeConnectionInfoGetter) GetConnectionInfo(ctx context.Context, nodeName types.NodeName) (*ConnectionInfo, error) {
node, err := k.nodes.Get(ctx, string(nodeName), metav1.GetOptions{})
if err != nil {
diff --git a/pkg/kubelet/client/kubelet_client_test.go b/pkg/kubelet/client/kubelet_client_test.go
index <HASH>..<HASH> 100644
--- a/pkg/kubelet/client/kubelet_client_test.go
+++ b/pkg/kubelet/client/kubelet_client_test.go
@@ -24,7 +24,7 @@ import (
func TestMakeTransportInvalid(t *testing.T) {
config := &KubeletClientConfig{
- EnableHttps: true,
+ EnableHTTPS: true,
//Invalid certificate and key path
TLSClientConfig: restclient.TLSClientConfig{
CertFile: "../../client/testdata/mycertinvalid.cer",
@@ -45,12 +45,12 @@ func TestMakeTransportInvalid(t *testing.T) {
func TestMakeTransportValid(t *testing.T) {
config := &KubeletClientConfig{
Port: 1234,
- EnableHttps: true,
+ EnableHTTPS: true,
TLSClientConfig: restclient.TLSClientConfig{
CertFile: "../../client/testdata/mycertvalid.cer",
- // TLS Configuration, only applies if EnableHttps is true.
+ // TLS Configuration, only applies if EnableHTTPS is true.
KeyFile: "../../client/testdata/mycertvalid.key",
- // TLS Configuration, only applies if EnableHttps is true.
+ // TLS Configuration, only applies if EnableHTTPS is true.
CAFile: "../../client/testdata/myCA.cer",
},
} | Fix golint issues in pkg/kubelet/client
Add comments to exported functions in `pkg/kubelet/client/client.go`
In `KubeletClientConfig` rename `EnableHttps` to `EnableHTTPS`. This requires
renaming it in `pkg/kubelet/client/client_test.go` | kubernetes_kubernetes | train |
519f05ffe84a5802ac4fcb40da9f4942ee162554 | diff --git a/lib/jira/version.rb b/lib/jira/version.rb
index <HASH>..<HASH> 100644
--- a/lib/jira/version.rb
+++ b/lib/jira/version.rb
@@ -1,3 +1,3 @@
module JIRA
- VERSION = "0.1.1"
+ VERSION = "0.1.2"
end | Incremented version to <I> | sumoheavy_jira-ruby | train |
6ff48091e58b522502d893511dd0fdebd39aa6ad | diff --git a/oidc_provider/views.py b/oidc_provider/views.py
index <HASH>..<HASH> 100644
--- a/oidc_provider/views.py
+++ b/oidc_provider/views.py
@@ -189,8 +189,8 @@ class JwksView(View):
'alg': 'RS256',
'use': 'sig',
'kid': md5(key).hexdigest(),
- 'n': long_to_base64(public_key.n).decode('utf-8'),
- 'e': long_to_base64(public_key.e).decode('utf-8'),
+ 'n': long_to_base64(public_key.n),
+ 'e': long_to_base64(public_key.e),
})
return JsonResponse(dic)
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -37,11 +37,11 @@ setup(
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
tests_require=[
- 'pyjwkest>=1.0.3,<1.1',
+ 'pyjwkest>=1.0.6,<1.1',
'mock==1.3.0',
],
install_requires=[
- 'pyjwkest>=1.0.3,<1.1',
+ 'pyjwkest>=1.0.6,<1.1',
],
) | Fix #<I> updating pyjwkest version to <I>
pyjwkest has changed the type of value returned by the `long_to_base<I>`
function, now it returns unicode. | juanifioren_django-oidc-provider | train |
fb083a0c21439e4661bd3811a618978dd2452eec | diff --git a/lib/yaks/format/collection_json.rb b/lib/yaks/format/collection_json.rb
index <HASH>..<HASH> 100644
--- a/lib/yaks/format/collection_json.rb
+++ b/lib/yaks/format/collection_json.rb
@@ -26,7 +26,7 @@ module Yaks
result[:href] = item.self_link.uri if item.self_link
item.links.each do |link|
next if link.rel == :self
- result[:links] ||= []
+ result[:links] = [] unless result.key?(:links)
result[:links] << {rel: link.rel, href: link.uri}
result[:links].last[:name] = link.name if link.name
end | Rewrite the statement that trips current mutant up (<URL>) | plexus_yaks | train |
7c8c62e8618e641f1fb8de4749e432cee4cb4494 | diff --git a/packages/jsio.js b/packages/jsio.js
index <HASH>..<HASH> 100644
--- a/packages/jsio.js
+++ b/packages/jsio.js
@@ -60,11 +60,18 @@
this.global = GLOBAL;
this.getCwd = process.cwd;
this.log = function() {
+ var msg;
try {
- process.stdio.writeError(Array.prototype.map.call(arguments, JSON.stringify).join(' ') + '\n');
+ process.stdio.writeError(msg = Array.prototype.map.call(arguments, function(a) {
+ if ((a instanceof Error) && a.message) {
+ return 'Error:' + a.message + '\nStack:' + a.stack + '\nArguments:' + a.arguments;
+ }
+ return typeof a == 'string' ? a : JSON.stringify(a);
+ }).join(' ') + '\n');
} catch(e) {
- process.stdio.writeError(Array.prototype.join.call(arguments, ' ') + '\n');
+ process.stdio.writeError(msg = Array.prototype.join.call(arguments, ' ') + '\n');
}
+ return msg;
}
this.getPath = function() {
@@ -94,7 +101,12 @@
this.global = window;
this.global.jsio = jsio;
- this.log = typeof console != 'undefined' && console.log ? bind(console, 'log') : function() {}
+ this.log = function() {
+ if(typeof console != 'undefined' && console.log) {
+ console.log.apply(console, arguments);
+ }
+ return Array.prototype.join.call(arguments, ' ');
+ }
var cwd = null, path = null;
this.getCwd = function() { | - environment log functions should return the string values that they print so we can use their formatting to construct a message to throw when using 'throw logger.error("something broke")'
- pretty print error messages in node (stack, message, and arguments) | gameclosure_js.io | train |
9e031ae3de302e0d9c0e6e1a5ad6705c50e82ded | diff --git a/controller-client/src/main/java/org/jboss/as/controller/client/ModelControllerClient.java b/controller-client/src/main/java/org/jboss/as/controller/client/ModelControllerClient.java
index <HASH>..<HASH> 100644
--- a/controller-client/src/main/java/org/jboss/as/controller/client/ModelControllerClient.java
+++ b/controller-client/src/main/java/org/jboss/as/controller/client/ModelControllerClient.java
@@ -311,7 +311,7 @@ public interface ModelControllerClient extends Closeable {
* @throws UnknownHostException if the host cannot be found
*/
public static ModelControllerClient create(final String protocol, final String hostName, final int port, final CallbackHandler handler, final SSLContext sslContext, final int connectionTimeout, final Map<String, String> saslOptions) throws UnknownHostException {
- return create(ClientConfigurationImpl.create(protocol, hostName, port, handler, sslContext, connectionTimeout));
+ return create(ClientConfigurationImpl.create(protocol, hostName, port, handler, sslContext, connectionTimeout, saslOptions));
}
/** | pass saslOptions to the ModelControllerClient configuration | wildfly_wildfly | train |
0f3657fb70bc14720e32e5f78e521764d7a9bc06 | diff --git a/lib/active_relation/relations/alias.rb b/lib/active_relation/relations/alias.rb
index <HASH>..<HASH> 100644
--- a/lib/active_relation/relations/alias.rb
+++ b/lib/active_relation/relations/alias.rb
@@ -1,7 +1,7 @@
module ActiveRelation
class Alias < Compound
attr_reader :alias
-
+
def initialize(relation, aliaz)
@relation, @alias = relation, aliaz
end
@@ -9,7 +9,7 @@ module ActiveRelation
def alias?
true
end
-
+
def ==(other)
self.class == other.class and
relation == other.relation and
diff --git a/spec/active_relation/unit/relations/join_spec.rb b/spec/active_relation/unit/relations/join_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/active_relation/unit/relations/join_spec.rb
+++ b/spec/active_relation/unit/relations/join_spec.rb
@@ -144,6 +144,19 @@ module ActiveRelation
end
end
+ describe 'when joining aliased relations' do
+ it 'aliases the table and attributes properly' do
+ pending
+ aliased_relation = @relation1.as(:alias)
+ @relation1.join(aliased_relation).on(@relation1[:id].eq(aliased_relation[:id])).to_sql.should be_like("
+ SELECT `users`.`id`, `users`.`name`, `alias`.`id`, `alias`.`name`
+ FROM `users`
+ INNER JOIN `alias`
+ ON `users`.`id` = `alias`.`id`
+ ")
+ end
+ end
+
describe 'when joining with a string' do
it "passes the string through to the where clause" do
Join.new("INNER JOIN asdf ON fdsa", @relation1).to_sql.should be_like(" | added pending test for (difficult) problem of aliasing tables for adjacency lists | rails_rails | train |
Subsets and Splits