hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
6dda1926f7d3abd833a86856654996ee133ddbda
|
diff --git a/app/actors/curation_concerns/actors/actor_stack.rb b/app/actors/curation_concerns/actors/actor_stack.rb
index <HASH>..<HASH> 100644
--- a/app/actors/curation_concerns/actors/actor_stack.rb
+++ b/app/actors/curation_concerns/actors/actor_stack.rb
@@ -24,6 +24,15 @@ module CurationConcerns
def update(attributes)
actor.update(attributes.with_indifferent_access)
end
+
+ def destroy
+ curation_concern.in_collection_ids.each do |id|
+ destination_collection = ::Collection.find(id)
+ destination_collection.members.delete(curation_concern)
+ destination_collection.update_index
+ end
+ curation_concern.destroy
+ end
end
end
end
diff --git a/app/controllers/concerns/curation_concerns/curation_concern_controller.rb b/app/controllers/concerns/curation_concerns/curation_concern_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/concerns/curation_concerns/curation_concern_controller.rb
+++ b/app/controllers/concerns/curation_concerns/curation_concern_controller.rb
@@ -95,9 +95,10 @@ module CurationConcerns::CurationConcernController
def destroy
title = curation_concern.to_s
- curation_concern.destroy
- CurationConcerns.config.callback.run(:after_destroy, curation_concern.id, current_user)
- after_destroy_response(title)
+ if actor.destroy
+ CurationConcerns.config.callback.run(:after_destroy, curation_concern.id, current_user)
+ after_destroy_response(title)
+ end
end
def file_manager
diff --git a/spec/controllers/curation_concerns/generic_works_controller_spec.rb b/spec/controllers/curation_concerns/generic_works_controller_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/controllers/curation_concerns/generic_works_controller_spec.rb
+++ b/spec/controllers/curation_concerns/generic_works_controller_spec.rb
@@ -235,6 +235,7 @@ describe CurationConcerns::GenericWorksController do
describe '#destroy' do
let(:work_to_be_deleted) { create(:private_generic_work, user: user) }
+ let(:parent_collection) { create(:collection) }
it 'deletes the work' do
delete :destroy, id: work_to_be_deleted
@@ -242,6 +243,19 @@ describe CurationConcerns::GenericWorksController do
expect(GenericWork).not_to exist(work_to_be_deleted.id)
end
+ context "when work is a member of a collection" do
+ before do
+ parent_collection.members = [work_to_be_deleted]
+ parent_collection.save!
+ end
+ it 'deletes the work and updates the parent collection' do
+ delete :destroy, id: work_to_be_deleted
+ expect(GenericWork).not_to exist(work_to_be_deleted.id)
+ expect(response).to redirect_to main_app.search_catalog_path
+ expect(parent_collection.reload.members).to eq []
+ end
+ end
+
it "invokes the after_destroy callback" do
expect(CurationConcerns.config.callback).to receive(:run)
.with(:after_destroy, work_to_be_deleted.id, user)
|
Add DestroyActor to remove work from collection and destroy the work
Add tests
|
samvera_hyrax
|
train
|
b725623f4ea7e93e37de54afaa252730387686eb
|
diff --git a/src/toil/job.py b/src/toil/job.py
index <HASH>..<HASH> 100644
--- a/src/toil/job.py
+++ b/src/toil/job.py
@@ -168,8 +168,8 @@ class Job(object):
if parentService is not None:
# Do check to ensure that parentService is a service of this job
def check(services):
- for s, jS in services:
- if s == parentService or check(s._childServices):
+ for jS in services:
+ if jS.service == parentService or check(jS.service._childServices):
return True
return False
if not check(self._services):
@@ -180,7 +180,7 @@ class Job(object):
raise JobException("The service already has a parent service")
service._hasParent = True
jobService = ServiceJob(service)
- self._services.append((service, jobService))
+ self._services.append(jobService)
return jobService.rv()
##Convenience functions for creating jobs
@@ -952,7 +952,7 @@ class Job(object):
raise JobException("The service already has a parent service")
service._parent = True
jobService = ServiceJob(service)
- self._childServices.append((service, jobService))
+ self._childServices.append(jobService)
return jobService.rv()
####################################################
@@ -1228,14 +1228,14 @@ class Job(object):
"""
Serialises the services for a job.
"""
- def processService(service, serviceJob, depth):
+ def processService(serviceJob, depth):
# Extend the depth of the services if necessary
if depth == len(jobWrapper.services):
jobWrapper.services.append([])
# Recursively call to process child services
- for childService, childServiceJob in service._childServices:
- processService(childService, childServiceJob, depth+1)
+ for childServiceJob in serviceJob.service._childServices:
+ processService(childServiceJob, depth+1)
# Make a job wrapper
serviceJobWrapper = serviceJob._createEmptyJobWrapperForJob(jobStore, predecessorNumber=1)
@@ -1258,18 +1258,24 @@ class Job(object):
jobWrapper.services[depth].append(j)
# Break the links between the services to stop them being serialised together
- childServices = service._childServices
- service._childServices = None
+ #childServices = serviceJob.service._childServices
+ serviceJob.service._childServices = None
assert serviceJob._services == []
+ #service = serviceJob.service
+
+ # Pickle the job
+ serviceJob.pickledService = cPickle.dumps(serviceJob.service)
+ serviceJob.service = None
# Serialise the service job and job wrapper
serviceJob._serialiseJob(jobStore, { serviceJob:serviceJobWrapper }, rootJobWrapper)
# Restore values
- service._childServices = childServices
+ #serviceJob.service = service
+ #serviceJob.service._childServices = childServices
- for service, serviceJob in self._services:
- processService(service, serviceJob, 0)
+ for serviceJob in self._services:
+ processService(serviceJob, 0)
self._services = []
@@ -1293,12 +1299,12 @@ class Job(object):
# Temporarily set the jobStore strings for the promise call back functions
for job in ordering:
job._promiseJobStore = jobStore
- def setForServices(service, serviceJob):
+ def setForServices(serviceJob):
serviceJob._promiseJobStore = jobStore
- for (childService, childJobService) in service._childServices:
- setForServices(childService, childJobService)
- for service, serviceJob in self._services:
- setForServices(service, serviceJob)
+ for childServiceJob in serviceJob.service._childServices:
+ setForServices(childServiceJob)
+ for serviceJob in self._services:
+ setForServices(serviceJob)
ordering.reverse()
assert self == ordering[-1]
@@ -1545,11 +1551,9 @@ class ServiceJob(Job):
# service.__module__ is the module defining the class service is an instance of.
self.serviceModule = ModuleDescriptor.forModule(service.__module__).globalize()
- #The service to run, pickled
- childServices = service._childServices
- service._childServices = [] #Ensure we don't pickle the children
- self.pickledService = cPickle.dumps(service)
- service._childServices = childServices
+ #The service to run - this will be replace before serialization with a pickled version
+ self.service = service
+ self.pickledService = None
# This references the parent job wrapper. It is initialised just before
# the job is run. It is used to access the start and terminate flags.
diff --git a/src/toil/test/src/jobServiceTest.py b/src/toil/test/src/jobServiceTest.py
index <HASH>..<HASH> 100644
--- a/src/toil/test/src/jobServiceTest.py
+++ b/src/toil/test/src/jobServiceTest.py
@@ -30,7 +30,22 @@ class JobServiceTest(ToilTest):
"""
Tests testing the Job.Service class
"""
-
+
+ def testServiceSerialization(self):
+ """
+ Tests that a service can receive a promise without producing a serialization
+ error.
+ """
+ job = Job()
+ service = TestServiceSerialization("woot")
+ startValue = job.addService(service) # Add a first service to job
+ subService = TestServiceSerialization(startValue) # Now create a child of
+ # that service that takes the start value promise from the parent service
+ job.addService(subService, parentService=service) # This should work if
+ # serialization on services is working correctly.
+
+ self.runToil(job)
+
def testService(self, checkpoint=False):
"""
Tests the creation of a Job.Service with random failures of the worker.
@@ -274,3 +289,20 @@ def serviceAccessor(job, communicationFiles, outFile, randInt):
return
assert 0 # Job failed to get info from the service
+
+class TestServiceSerialization(Job.Service):
+ def __init__(self, messageInt, *args, **kwargs):
+ """
+ Trivial service for testing serialization.
+ """
+ Job.Service.__init__(self, *args, **kwargs)
+ self.messageInt = messageInt
+
+ def start(self, fileStore):
+ return self.messageInt
+
+ def stop(self, fileStore):
+ pass
+
+ def check(self):
+ return True
|
Fix service promise serialization (resolves #<I>)
Adds a test in toil.test.jobServiceTest.testServiceSerialization which now passes
illustrating the issues.
|
DataBiosphere_toil
|
train
|
9e55150afa7cdbe1b6323230e11af153175fefc6
|
diff --git a/test/test_qimageview.py b/test/test_qimageview.py
index <HASH>..<HASH> 100644
--- a/test/test_qimageview.py
+++ b/test/test_qimageview.py
@@ -1,34 +1,35 @@
-from qimage2ndarray import qimageview
+from qimage2ndarray import _qimageview
from PyQt4 import QtGui
from nose.tools import raises, assert_equal
def test_viewcreation():
qimg = QtGui.QImage(320, 240, QtGui.QImage.Format_RGB32)
- v = qimageview.qimageview(qimg)
+ v = _qimageview(qimg)
assert_equal(v.shape, (240, 320))
assert v.base is qimg
del qimg
w, h = v.base.width(), v.base.height() # should not segfault
+ assert (w, h) == (320, 240)
@raises(TypeError)
def test_qimageview_noargs():
- v = qimageview.qimageview()
+ v = _qimageview()
@raises(TypeError)
def test_qimageview_manyargs():
qimg = QtGui.QImage(320, 240, QtGui.QImage.Format_Indexed8)
- v = qimageview.qimageview(qimg, 1)
+ v = _qimageview(qimg, 1)
@raises(TypeError)
def test_qimageview_wrongarg():
- v = qimageview.qimageview(42)
+ v = _qimageview(42)
def test_data_access():
qimg = QtGui.QImage(320, 240, QtGui.QImage.Format_Indexed8)
qimg.setNumColors(256)
qimg.fill(42)
- v = qimageview.qimageview(qimg)
+ v = _qimageview(qimg)
assert_equal(v.shape, (240, 320))
assert_equal(v[10,10], 42)
assert_equal(v.nbytes, qimg.numBytes())
@@ -37,7 +38,7 @@ def test_being_view():
qimg = QtGui.QImage(320, 240, QtGui.QImage.Format_Indexed8)
qimg.setNumColors(256)
qimg.fill(23)
- v = qimageview.qimageview(qimg)
+ v = _qimageview(qimg)
qimg.fill(42)
assert_equal(v.shape, (240, 320))
assert_equal(v[10,10], 42)
@@ -47,7 +48,7 @@ def test_coordinate_access():
qimg = QtGui.QImage(320, 240, QtGui.QImage.Format_Indexed8)
qimg.setNumColors(256)
qimg.fill(0)
- v = qimageview.qimageview(qimg)
+ v = _qimageview(qimg)
qimg.fill(23)
qimg.setPixel(12, 10, 42)
assert_equal(v.shape, (240, 320))
@@ -58,7 +59,7 @@ def test_coordinate_access():
def test_RGB32():
qimg = QtGui.QImage(320, 240, QtGui.QImage.Format_RGB32)
qimg.fill(0)
- v = qimageview.qimageview(qimg)
+ v = _qimageview(qimg)
qimg.fill(23)
qimg.setPixel(12, 10, 42)
assert_equal(v.shape, (240, 320))
@@ -69,7 +70,7 @@ def test_RGB32():
def test_ARGB32():
qimg = QtGui.QImage(320, 240, QtGui.QImage.Format_ARGB32)
qimg.fill(0)
- v = qimageview.qimageview(qimg)
+ v = _qimageview(qimg)
qimg.setPixel(12, 10, 42)
assert_equal(v.shape, (240, 320))
assert_equal(v[10,12], 42)
@@ -79,7 +80,7 @@ def test_odd_size_8bit():
qimg = QtGui.QImage(321, 240, QtGui.QImage.Format_Indexed8)
qimg.setNumColors(256)
qimg.fill(0)
- v = qimageview.qimageview(qimg)
+ v = _qimageview(qimg)
qimg.setPixel(12, 10, 42)
assert_equal(v.shape, (240, 321))
assert_equal(v[10,12], 42)
@@ -88,7 +89,7 @@ def test_odd_size_8bit():
def test_odd_size_32bit():
qimg = QtGui.QImage(321, 240, QtGui.QImage.Format_ARGB32)
qimg.fill(0)
- v = qimageview.qimageview(qimg)
+ v = _qimageview(qimg)
qimg.setPixel(12, 10, 42)
assert_equal(v.shape, (240, 321))
assert_equal(v[10,12], 42)
@@ -97,9 +98,9 @@ def test_odd_size_32bit():
@raises(ValueError)
def test_mono():
qimg = QtGui.QImage(320, 240, QtGui.QImage.Format_Mono)
- v = qimageview.qimageview(qimg)
+ v = _qimageview(qimg)
@raises(ValueError)
def test_rgb666():
qimg = QtGui.QImage(320, 240, QtGui.QImage.Format_RGB666)
- v = qimageview.qimageview(qimg)
+ v = _qimageview(qimg)
|
test_qimageview: don’t import qimageview directly
instead, use function imported as _qimageview, which may come from
different sources (e.g. different DLLs or pure python implementation)
|
hmeine_qimage2ndarray
|
train
|
42afb6c2ac7b70cc8c9a4e1ab5001f2ff64549d7
|
diff --git a/version.php b/version.php
index <HASH>..<HASH> 100644
--- a/version.php
+++ b/version.php
@@ -29,7 +29,7 @@
defined('MOODLE_INTERNAL') || die();
-$version = 2018020600.00; // YYYYMMDD = weekly release date of this DEV branch.
+$version = 2018020600.01; // YYYYMMDD = weekly release date of this DEV branch.
// RR = release increments - 00 in DEV branches.
// .XX = incremental changes.
|
MDL-<I> version: Bump to update system capabilities and lang str
|
moodle_moodle
|
train
|
14239b50b4ad0d90df051aa2ab468fe09b3cdde3
|
diff --git a/src/main/java/water/api/SummaryPage.java b/src/main/java/water/api/SummaryPage.java
index <HASH>..<HASH> 100644
--- a/src/main/java/water/api/SummaryPage.java
+++ b/src/main/java/water/api/SummaryPage.java
@@ -45,7 +45,7 @@ public class SummaryPage extends Request {
String cname = o.get("name").getAsString();
pageBldr.append("<div style='margin-left:5px;'><a href='#col_" + cname + "'>" + cname + "</a></div>");
long N = o.get("N").getAsLong();
- sb.append("<div class='table' id='col_" + cname + "' style='width:100%;heigth:90%;overflow-y:scroll;border-top-style:solid;'><h4>Column: " + cname + "</h4>\n");
+ sb.append("<div class='table' id='col_" + cname + "' style='width:100%;heigth:90%;overflow-y:scroll;border-top-style:solid;'><div class='alert-success'><h4>Column: " + cname + "</h4></div>\n");
if(o.has("min") && o.has("max")){
StringBuilder minRow = new StringBuilder("<tr><th>μ</th><td>" + Utils.p2d(o.get("mean").getAsDouble())+"</td><th style='border-left-style:solid; borde-left:1px;border-left-color:#ddd;'>min[5]</th>");
StringBuilder maxRow = new StringBuilder("<tr><th>σ</th><td>" + Utils.p2d(o.get("sigma").getAsDouble()) + "</td><th style='border-left-style:solid; borde-left:1px;border-left-color:#ddd;'>max[5]</th>");
|
just added some colors to summary page...
|
h2oai_h2o-2
|
train
|
ff28668dd8ef0986dd2da329f313d5411de14106
|
diff --git a/h2o-docs/src/booklets/v2_2015/source/python/ipython_machinelearning_input.py b/h2o-docs/src/booklets/v2_2015/source/python/ipython_machinelearning_input.py
index <HASH>..<HASH> 100644
--- a/h2o-docs/src/booklets/v2_2015/source/python/ipython_machinelearning_input.py
+++ b/h2o-docs/src/booklets/v2_2015/source/python/ipython_machinelearning_input.py
@@ -1,25 +1,93 @@
+
import h2o
+from h2o.estimators.gbm import H2OGradientBoostingEstimator
h2o.init()
-airlines_url = "https://s3.amazonaws.com/h2o-airlines-unpacked/allyears2k.csv"
+iris_data_path = h2o.system_file("iris.csv") # load demonstration data
+iris_df = h2o.import_file(path=iris_data_path)
+iris_df.describe()
+gbm_regessor = H2OGradientBoostingEstimator(distribution="gaussian", ntrees=10, max_depth=3, min_rows=2, learn_rate="0.2")
+gbm_regessor.train(x=range(1,iris_df.ncol), y=0, training_frame=iris_df)
+gbm_regessor
+
+gbm_classifier = H2OGradientBoostingEstimator(distribution="multinomial", ntrees=10, max_depth=3, min_rows=2, learn_rate="0.2")
+gbm_classifier.train(x=range(0,iris_df.ncol-1), y=iris_df.ncol-1, training_frame=iris_df)
+gbm_classifier
-airlines_df = h2o.import_file(airlines_url)
+from h2o.estimators.glm import H2OGeneralizedLinearEstimator
+prostate_data_path = h2o.system_file("prostate.csv")
+prostate_df = h2o.import_file(path=prostate_data_path)
+prostate_df["RACE"] = prostate_df["RACE"].asfactor()
+prostate_df.describe()
+glm_classifier = H2OGeneralizedLinearEstimator(family="binomial", nfolds=10, alpha=0.5)
+glm_classifier.train(x=["AGE","RACE","PSA","DCAPS"],y="CAPSULE", training_frame=prostate_df)
+glm_classifier
-airlines_df.columns
+from h2o.estimators.kmeans import H2OKMeansEstimator
+cluster_estimator = H2OKMeansEstimator(k=3)
+cluster_estimator.train(x=[0,1,2,3], training_frame=iris_df)
+cluster_estimator
-airlines_df.describe() # output suppressed
+from h2o.transforms.decomposition import H2OPCA
+pca_decomp = H2OPCA(k=2, transform="NONE", pca_method="Power")
+pca_decomp.train(x=range(0,4), training_frame=iris_df)
+pca_decomp
-airlines_df["IsArrDelayed"].describe()
+pred = pca_decomp.predict(iris_df)
+pred.head() # Projection results
-independent_vars = ["Year","Month","DayOfWeek","CRSDepTime","CRSArrTime","Origin","Dest","UniqueCarrier"]
-dependent_var = "IsArrDelayed"
+# Grid Search
+
+ntrees_opt = [5,10,15]
+max_depth_opt = [2,3,4]
+learn_rate_opt = [0.1,0.2]
+hyper_parameters = {"ntrees": ntrees_opt, "max_depth":max_depth_opt, "learn_rate":learn_rate_opt}
+
+from h2o.grid.grid_search import H2OGridSearch
+gs = H2OGridSearch(H2OGradientBoostingEstimator(distribution="multinomial"), hyper_params=hyper_parameters)
+gs.train(x=range(0,iris_df.ncol-1), y=iris_df.ncol-1, training_frame=iris_df, nfold=10)
+print gs.sort_by('logloss', increasing=True)
+
+# Pipeline
+from h2o.transforms.preprocessing import H2OScaler
+from sklearn.pipeline import Pipeline
+
+# build transformation pipeline using sklearn's Pipeline and H2O transforms
+pipeline = Pipeline([("standardize", H2OScaler()),
+ ("pca", H2OPCA(k=2)),
+ ("gbm", H2OGradientBoostingEstimator(distribution="multinomial"))])
+pipeline.fit(iris_df[:4],iris_df[4])
+
+# Random CV using H2O and Scikit-learn
+from sklearn.grid_search import RandomizedSearchCV
+from h2o.cross_validation import H2OKFold
+from h2o.model.regression import h2o_r2_score
+from sklearn.metrics.scorer import make_scorer
+
+params = {"standardize__center": [True, False], # Parameters to test
+ "standardize__scale": [True, False],
+ "pca__k": [2,3],
+ "gbm__ntrees": [10,20],
+ "gbm__max_depth": [1,2,3],
+ "gbm__learn_rate": [0.1,0.2]}
+
+custom_cv = H2OKFold(iris_df, n_folds=5, seed=42)
+
+pipeline = Pipeline([("standardize", H2OScaler()),
+ ("pca", H2OPCA(k=2)),
+ ("gbm", H2OGradientBoostingEstimator(distribution="gaussian"))])
+
+random_search = RandomizedSearchCV(pipeline, params,
+ n_iter=5,
+ scoring=make_scorer(h2o_r2_score),
+ cv=custom_cv,
+ random_state=42,
+ n_jobs=1)
-from h2o.estimators.glm import H2OGeneralizedLinearEstimator
-linear_classification_estimator = H2OGeneralizedLinearEstimator(family="binomial")
+random_search.fit(iris_df[1:], iris_df[0])
-linear_classification_estimator.train(X=independent_vars, y=dependent_var, training_frame=airlines_df)
+print random_search.best_estimator_
-linear_classification_estimator.show()
|
script that will be used in the python booklet for ML
section
|
h2oai_h2o-3
|
train
|
4372ca7997f07dd5c3bb8ebb47c302314705ac30
|
diff --git a/wizard/src/main/java/me/panavtec/wizard/Wizard.java b/wizard/src/main/java/me/panavtec/wizard/Wizard.java
index <HASH>..<HASH> 100644
--- a/wizard/src/main/java/me/panavtec/wizard/Wizard.java
+++ b/wizard/src/main/java/me/panavtec/wizard/Wizard.java
@@ -116,7 +116,7 @@ public class Wizard implements FragmentManager.OnBackStackChangedListener {
}
public static class Builder extends WizardBuilder {
- public Builder(ActionBarActivity activity, WizardPage[] pages) {
+ public Builder(ActionBarActivity activity, WizardPage... pages) {
super(activity, pages);
}
}
|
Update missing dot notation builder constructor
|
PaNaVTEC_Wizard
|
train
|
35409367f7f1be2f7468ac61da00e60b5d281016
|
diff --git a/indra/sources/indra_db_rest/query.py b/indra/sources/indra_db_rest/query.py
index <HASH>..<HASH> 100644
--- a/indra/sources/indra_db_rest/query.py
+++ b/indra/sources/indra_db_rest/query.py
@@ -7,7 +7,8 @@ into sophisticated and optimized SQL. Different classes represent different
types of constraint and are named as much as possible to fit together when
spoken aloud in English. For example:
->>> HasAgent("MEK") & HasAgent("ERK") & HasType(["Phosphorylation"])
+>>>
+>> HasAgent("MEK") & HasAgent("ERK") & HasType(["Phosphorylation"])
will find any Statement that has an agent MEK and an agent ERK and has the type
phosphorylation.
@@ -70,11 +71,12 @@ documentation for more usage details):
**Example 1**: Get statements that have database evidence and have either MEK or
MAP2K1 as a name for any of its agents.
->>> from indra.sources.indra_db_rest.api import get_statements_from_query
->>> from indra.sources.indra_db_rest.query import *
->>> q = HasAgent('MEK') | HasAgent('MAP2K1') & HasDatabases()
->>> p = get_statements_from_query(q)
->>> p.statements
+>>>
+>> from indra.sources.indra_db_rest.api import get_statements_from_query
+>> from indra.sources.indra_db_rest.query import *
+>> q = HasAgent('MEK') | HasAgent('MAP2K1') & HasDatabases()
+>> p = get_statements_from_query(q)
+>> p.statements
[Activation(MEK(), ERK()),
Phosphorylation(MEK(), ERK()),
Activation(MAP2K1(), ERK()),
@@ -103,9 +105,10 @@ MAP2K1 as a name for any of its agents.
**Example 2**: Get statements that have an agent MEK and an agent ERK and more
than 10 evidence.
->>> q = HasAgent('MEK') & HasAgent('ERK') & HasEvidenceBound(["> 10"])
->>> p = get_statements_from_query(q)
->>> p.statements
+>>>
+>> q = HasAgent('MEK') & HasAgent('ERK') & HasEvidenceBound(["> 10"])
+>> p = get_statements_from_query(q)
+>> p.statements
[Activation(MEK(), ERK()),
Phosphorylation(MEK(), ERK()),
Complex(ERK(), MEK()),
@@ -119,9 +122,10 @@ than 10 evidence.
**Example 3**: An example of using the ``~`` feature.
->>> q = HasAgent('MEK', namespace='FPLX') & ~HasAgent('ERK', namespace='FPLX')
->>> p = get_statements_from_query(q)
->>> p.statements[:10]
+>>>
+>> q = HasAgent('MEK', namespace='FPLX') & ~HasAgent('ERK', namespace='FPLX')
+>> p = get_statements_from_query(q)
+>> p.statements[:10]
[Phosphorylation(None, MEK()),
Phosphorylation(RAF(), MEK()),
Activation(RAF(), MEK()),
@@ -141,7 +145,8 @@ object:
Consider the last query we wrote. You can examine the simple JSON sent to
the server:
->>> q.to_simple_json()
+>>>
+>> q.to_simple_json()
{'class': 'And',
'constraint': {'queries': [{'class': 'HasAgent',
'constraint': {'agent_id': 'MEK',
@@ -160,7 +165,8 @@ the server:
Or you can retrieve the more "true" JSON representation that is generated by
the server from your simpler query:
->>> q.get_query_json()
+>>>
+>> q.get_query_json()
{'class': 'Intersection',
'constraint': {'query_list': [{'class': 'HasAgent',
'constraint': {'_regularized_id': 'MEK',
@@ -181,8 +187,9 @@ the server:
And last of all you can retrieve a human readable English description of the
query from the server:
->>> query_english = q.get_query_english()
->>> print("I am finding statements that", query_english)
+>>>
+>> query_english = q.get_query_english()
+>> print("I am finding statements that", query_english)
I am finding statements that do not have an agent where FPLX=ERK and have an
agent where FPLX=MEK
"""
@@ -347,8 +354,10 @@ class Query:
class And(Query):
"""The intersection of two queries.
- This are generally generated from the use of &, e.g.
- q_and = HashAgent('MEK') & HasAgent('ERK').
+ This are generally generated from the use of ``&``, for example:
+
+ >>>
+ >> q_and = HashAgent('MEK') & HasAgent('ERK')
"""
def __init__(self, queries: list):
@@ -379,8 +388,10 @@ class And(Query):
class Or(Query):
"""The union of two queries.
- These are generally generate from the use of '|', e.g.
- q_or = HasOnlySource('reach') | HasOnlySource('medscan').
+ These are generally generate from the use of ``|``, for example:
+
+ >>>
+ >> q_or = HasOnlySource('reach') | HasOnlySource('medscan')
"""
def __init__(self, queries: list):
|
Remove code blocks from doctests.
|
sorgerlab_indra
|
train
|
914d32c930a4909e040d4b1693934edeb3dd56bc
|
diff --git a/doxypypy/doxypypy.py b/doxypypy/doxypypy.py
index <HASH>..<HASH> 100755
--- a/doxypypy/doxypypy.py
+++ b/doxypypy/doxypypy.py
@@ -71,7 +71,9 @@ class AstWalker(NodeVisitor):
' @copyright ': regexpCompile(r"^(\s*Copyright:\s*)(.*)$", IGNORECASE),
' @date ': regexpCompile(r"^(\s*Date:\s*)(.*)$", IGNORECASE),
' @file ': regexpCompile(r"^(\s*File:\s*)(.*)$", IGNORECASE),
- ' @version: ': regexpCompile(r"^(\s*Version:\s*)(.*)$", IGNORECASE)
+ ' @version: ': regexpCompile(r"^(\s*Version:\s*)(.*)$", IGNORECASE),
+ ' @note ': regexpCompile(r"^(\s*Note:\s*)(.*)$", IGNORECASE),
+ ' @warning ': regexpCompile(r"^(\s*Warning:\s*)(.*)$", IGNORECASE)
}
__argsStartRE = regexpCompile(r"^(\s*(?:(?:Keyword\s+)?"
r"(?:A|Kwa)rg(?:ument)?|Attribute)s?"
@@ -678,20 +680,6 @@ class AstWalker(NodeVisitor):
tail = '@namespace {0}'.format(modifiedContextTag)
else:
tail = self._processMembers(node, '')
- lineNum = node.lineno - 1
- decoratorComment = False
- while True:
- topLine = self.lines[lineNum].lstrip()
- if topLine.startswith('def'):
- break
- elif topLine.startswith('@'):
- # we have a decorator
- decoratorComment = True
- if self.options.debug:
- stderr.write("# Decorator{0}".format(linesep))
- if decoratorComment:
- self.lines[lineNum] = '# {0}'.format(self.lines[lineNum])
- lineNum += 1
if get_docstring(node):
self._processDocstring(node, tail,
containingNodes=containingNodes)
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -10,7 +10,7 @@ if dirname(__file__):
setup(
name='doxypypy',
- version='0.8.6',
+ version='0.8.7',
description='A Doxygen filter for Python',
long_description=open('README.md').read(),
keywords='Doxygen filter Python documentation',
|
Added a couple additional single line REs that people had requested, and removed a little bit of extra code that accidentally stowed away in with the last check-in.
|
Feneric_doxypypy
|
train
|
6ee802e3afec1ed72976d2867fac01820d0f3775
|
diff --git a/compliance_checker/cf/cf_1_6.py b/compliance_checker/cf/cf_1_6.py
index <HASH>..<HASH> 100644
--- a/compliance_checker/cf/cf_1_6.py
+++ b/compliance_checker/cf/cf_1_6.py
@@ -1091,25 +1091,21 @@ class CF1_6Check(CFNCCheck):
flag_meanings = getattr(variable, "flag_meanings", None)
valid_values = TestCtx(BaseCheck.HIGH, self.section_titles["3.5"])
- # flag_values must be a list of values, not a string or anything else
- valid_values.assert_true(
- isinstance(flag_values, np.ndarray),
- "{}'s flag_values must be an array of values not {}".format(
- name, type(flag_values)
- ),
+ # IMPLEMENTATION CONFORMANCE 3.5 REQUIRED 2/8
+ valid_values.assert_true(hasattr(variable, "flag_meanings"),
+ f"Variable {variable.name} must have attribute flag_meanings "
+ "defined when flag_values attribute is present"
)
- # We can't perform any more checks
- if not isinstance(flag_values, np.ndarray):
- return valid_values.to_result()
# the flag values must be independent, no repeating values
flag_set = set(flag_values)
valid_values.assert_true(
- len(flag_set) == len(flag_values),
+ len(flag_set) == np.array(flag_values).size,
"{}'s flag_values must be independent and can not be repeated".format(name),
)
+ # IMPLEMENTATION CONFORMANCE 3.5 REQUIRED 1/8
# the data type for flag_values should be the same as the variable
valid_values.assert_true(
variable.dtype.type == flag_values.dtype.type,
@@ -1117,10 +1113,11 @@ class CF1_6Check(CFNCCheck):
"".format(flag_values.dtype.type, name, variable.dtype.type),
)
+ # IMPLEMENTATION CONFORMANCE 3.5 REQUIRED 4/8
if isinstance(flag_meanings, str):
flag_meanings = flag_meanings.split()
valid_values.assert_true(
- len(flag_meanings) == len(flag_values),
+ len(flag_meanings) == np.array(flag_values).size
"{}'s flag_meanings and flag_values should have the same number ".format(
name
)
@@ -1145,21 +1142,11 @@ class CF1_6Check(CFNCCheck):
variable = ds.variables[name]
flag_masks = variable.flag_masks
- flag_meanings = getattr(ds, "flag_meanings", None)
+ flag_meanings = getattr(variable, "flag_meanings", None)
valid_masks = TestCtx(BaseCheck.HIGH, self.section_titles["3.5"])
valid_masks.assert_true(
- isinstance(flag_masks, np.ndarray),
- "{}'s flag_masks must be an array of values not {}".format(
- name, type(flag_masks).__name__
- ),
- )
-
- if not isinstance(flag_masks, np.ndarray):
- return valid_masks.to_result()
-
- valid_masks.assert_true(
variable.dtype.type == flag_masks.dtype.type,
"flag_masks ({}) mustbe the same data type as {} ({})"
"".format(flag_masks.dtype.type, name, variable.dtype.type),
@@ -1179,11 +1166,11 @@ class CF1_6Check(CFNCCheck):
if isinstance(flag_meanings, str):
flag_meanings = flag_meanings.split()
valid_masks.assert_true(
- len(flag_meanings) == len(flag_masks),
- "{} flag_meanings and flag_masks should have the same number ".format(
- name
- )
- + "of elements.",
+ # cast to array here as single element arrays are returned as
+ # scalars from netCDF4 Python
+ len(flag_meanings) == np.array(flag_masks).size,
+ f"{name} flag_meanings and flag_masks should have the same "
+ "number of elements."
)
return valid_masks.to_result()
@@ -1222,6 +1209,7 @@ class CF1_6Check(CFNCCheck):
len(flag_meanings) > 0, "{}'s flag_meanings can't be empty".format(name)
)
+ # IMPLEMENTATION CONFORMANCE REQUIRED 3.5 3/8
flag_regx = regex.compile(r"^[0-9A-Za-z_\-.+@]+$")
meanings = flag_meanings.split()
for meaning in meanings:
diff --git a/compliance_checker/tests/test_cf.py b/compliance_checker/tests/test_cf.py
index <HASH>..<HASH> 100644
--- a/compliance_checker/tests/test_cf.py
+++ b/compliance_checker/tests/test_cf.py
@@ -658,6 +658,14 @@ class TestCF1_6(BaseTestCase):
assert scored > 0
assert scored == out_of
+ dataset = MockTimeSeries()
+ flags_var = dataset.createVariable("flags", "f8", ("time",))
+ flags_var.standard_name = "quality_flag"
+ flags_var.flag_meanings = "LAND"
+ flags_var.flag_masks = np.array([1], dtype="i2")
+ results = self.cf.check_flags(dataset)
+ assert scored > 0 and scored == out_of
+
def test_check_bad_units(self):
"""Load a dataset with units that are expected to fail (bad_units.nc).
There are 6 variables in this dataset, three of which should give
|
Fix handling of flag attributes when a single value/scalar is passed
|
ioos_compliance-checker
|
train
|
2bc3ff9fefcba362a45eb51ea74bbd4dad9c004b
|
diff --git a/jssearch.js b/jssearch.js
index <HASH>..<HASH> 100644
--- a/jssearch.js
+++ b/jssearch.js
@@ -47,21 +47,21 @@ var jssearch = {
queryWords: [],
search: function(query) {
- var words = $.jssearch.tokenizeString(query);
+ var words = jssearch.tokenizeString(query);
var result = {};
- $.jssearch.queryWords = words.map(function(i) { return i.t; });
+ jssearch.queryWords = words.map(function(i) { return i.t; });
// do not search when no words given
if (!words.length) {
return result;
}
-// result = $.jssearch.searchForWords(words);
+// result = jssearch.searchForWords(words);
// if ($.isEmptyObject(result)) {
- words = $.jssearch.completeWords(words);
- $.jssearch.queryWords = words.map(function(i) { return i.t; });
- result = $.jssearch.searchForWords(words);
+ words = jssearch.completeWords(words);
+ jssearch.queryWords = words.map(function(i) { return i.t; });
+ result = jssearch.searchForWords(words);
// }
var res = [];
@@ -75,13 +75,13 @@ var jssearch = {
searchForWords: function(words) {
var result = {};
words.forEach(function(word) {
- if ($.jssearch.index[word.t]) {
- $.jssearch.index[word.t].forEach(function(file) {
+ if (jssearch.index[word.t]) {
+ jssearch.index[word.t].forEach(function(file) {
if (result[file.f]) {
result[file.f].weight *= file.w * word.w;
} else {
result[file.f] = {
- file: $.jssearch.files[file.f],
+ file: jssearch.files[file.f],
weight: file.w * word.w
};
}
@@ -95,9 +95,9 @@ var jssearch = {
var result = [];
words.forEach(function(word) {
- if (!$.jssearch.index[word.t] && word.t.length > 2) {
+ if (!jssearch.index[word.t] && word.t.length > 2) {
// complete words that are not in the index
- for(var w in $.jssearch.index) {
+ for(var w in jssearch.index) {
if (w.substr(0, word.t.length) === word.t) {
result.push({t: w, w: 1});
}
diff --git a/lib/Indexer.php b/lib/Indexer.php
index <HASH>..<HASH> 100644
--- a/lib/Indexer.php
+++ b/lib/Indexer.php
@@ -77,9 +77,9 @@ class Indexer
$tokenizeString = $this->getTokenizer()->tokenizeJs();
return <<<JS
-$.jssearch.index = $index;
-$.jssearch.files = $files;
-$.jssearch.tokenizeString = $tokenizeString;
+jssearch.index = $index;
+jssearch.files = $files;
+jssearch.tokenizeString = $tokenizeString;
JS;
}
|
rename of jssearch
|
cebe_js-search
|
train
|
6e2e5447303592fd3141e21c4409beadb5432421
|
diff --git a/src/Model/Product/HeurekaProductDomainFacade.php b/src/Model/Product/HeurekaProductDomainFacade.php
index <HASH>..<HASH> 100644
--- a/src/Model/Product/HeurekaProductDomainFacade.php
+++ b/src/Model/Product/HeurekaProductDomainFacade.php
@@ -74,8 +74,8 @@ class HeurekaProductDomainFacade
foreach ($heurekaProductDomains as $heurekaProductDomain) {
$this->em->remove($heurekaProductDomain);
- $this->em->flush();
}
+ $this->em->flush();
}
/**
|
flushes executed in loops are now executed outside of loop (#<I>)
- execution of flush inside loop is bad practice
- execution of flush outside of loop will increase performance
- fixes issue (#<I>)
|
shopsys_product-feed-heureka
|
train
|
170a90685edf966d064537e97a2218a634d990a8
|
diff --git a/lib/jitsu/package.js b/lib/jitsu/package.js
index <HASH>..<HASH> 100644
--- a/lib/jitsu/package.js
+++ b/lib/jitsu/package.js
@@ -452,13 +452,13 @@ package.properties = function (dir) {
},
{
name: 'version',
- validator: /[\w|\-|\.]+/,
+ validator: semver.valid,
default: '0.0.0'
},
{
name: 'engines.node',
message: 'engines',
- validator: /[\w|\-|\.]+/,
+ validator: semver.valid,
default: process.version.split('.').slice(0, 2).join('.') + '.x'
}
];
|
[api] Use semver.valid to test versions
|
nodejitsu_jitsu
|
train
|
4edf7205239fae1f5d1579131548f35f3cab9ad2
|
diff --git a/pynlpl/tests/folia.py b/pynlpl/tests/folia.py
index <HASH>..<HASH> 100755
--- a/pynlpl/tests/folia.py
+++ b/pynlpl/tests/folia.py
@@ -2595,11 +2595,61 @@ class Test8Validation(unittest.TestCase):
class Test9Validation(unittest.TestCase):
def test001_deepvalidation(self):
"""Validation - Deep Validation"""
- folia.Document(file=os.path.join(FOLIAPATH,'test/example.deep.xml'), deepvalidation=True, allowadhocsets=True)
+ folia.Document(file=os.path.join(FOLIAPATH,'test/example.deep.xml'), deepvalidation=True, textvalidation=True, allowadhocsets=True)
def test002_textvalidation(self):
"""Validation - Text Validation"""
- folia.Document(file=os.path.join(FOLIAPATH,'test/example.textvalidation.xml'))
+ folia.Document(file=os.path.join(FOLIAPATH,'test/example.textvalidation.xml'), textvalidation=True)
+
+ def test003_invalid_text_misspelled(self):
+ """Validation - Invalid Text (Misspelled word)"""
+ xml = """<?xml version="1.0" encoding="UTF-8"?>
+<?xml-stylesheet type="text/xsl" href="folia.xsl"?>
+<FoLiA xmlns="http://ilk.uvt.nl/folia" xmlns:xlink="http://www.w3.org/1999/xlink" xml:id="test" version="{version}" generator="{generator}">
+ <metadata type="native">
+ <annotations>
+ <token-annotation annotator="ucto" annotatortype="auto" datetime="2017-09-25T10:29:52" set="tokconfig-nld"/>
+ </annotations>
+ </metadata>
+ <text xml:id="example.text">
+ <p xml:id="example.p.1">
+ <t>Is het creëren van een volwaardig literair oeuvre voorbehouden aan schrijvers als Couperus, Haasse, of Grunberg? Of kan een computer net zo goed een rol vervullen in de creatie ervan? Met het kunstwerk 'Writers in the cloud' wagen kunstenaars en wetenschappers zich gezamenlijk aan het beantwoorden van deze vraag. Het resultaat is een interactieve installatie die draait om thema's als authenticiteit, creativiteit en de invloed van de digitale wereld op kunst.</t>
+ <s xml:id="example.p.1.s.1">
+ <t>Is het creëren van een volwaardig literrair oeuvre voorbehouden aan schrijvers
+ als Couperus, Haasse, of
+ Grunberg?</t>
+ </s>
+ </p>
+ </text>
+</FoLiA>""".format(version=folia.FOLIAVERSION, generator='pynlpl.formats.folia-v' + folia.LIBVERSION)
+ self.assertRaises( folia.InconsistentText, folia.Document, string=xml, textvalidation=True) #exception
+
+
+ def test004_invalid_text_missing(self):
+ """Validation - Invalid Text (Missing Word)"""
+ xml = """<?xml version="1.0" encoding="UTF-8"?>
+<?xml-stylesheet type="text/xsl" href="folia.xsl"?>
+<FoLiA xmlns="http://ilk.uvt.nl/folia" xmlns:xlink="http://www.w3.org/1999/xlink" xml:id="test" version="{version}" generator="{generator}">
+ <metadata type="native">
+ <annotations>
+ <token-annotation annotator="ucto" annotatortype="auto" datetime="2017-09-25T10:29:52" set="tokconfig-nld"/>
+ </annotations>
+ </metadata>
+ <text xml:id="example.text">
+ <p xml:id="example.p.1">
+ <t>Is het creëren van een volwaardig literair oeuvre voorbehouden aan schrijvers als Couperus, Haasse, of Grunberg? Of kan een computer net zo goed een rol vervullen in de creatie ervan? Met het kunstwerk 'Writers in the cloud' wagen kunstenaars en wetenschappers zich gezamenlijk aan het beantwoorden van deze vraag. Het resultaat is een interactieve installatie die draait om thema's als authenticiteit, creativiteit en de invloed van de digitale wereld op kunst.</t>
+ <s xml:id="example.p.1.s.1">
+ <t>Is het creëren van een volwaardig oeuvre voorbehouden aan schrijvers
+ als Couperus, Haasse, of
+ Grunberg?</t>
+ </s>
+ </p>
+ </text>
+</FoLiA>""".format(version=folia.FOLIAVERSION, generator='pynlpl.formats.folia-v' + folia.LIBVERSION)
+ self.assertRaises( folia.InconsistentText, folia.Document, string=xml, textvalidation=True) #exception
+
+
+
with io.open(FOLIAPATH + '/test/example.xml', 'r',encoding='utf-8') as foliaexample_f:
FOLIAEXAMPLE = foliaexample_f.read()
|
Added two invalid text tests (proycon/folia#<I>)
|
proycon_pynlpl
|
train
|
9cbae1e5b22e714740e1c858140ebec2a133d37d
|
diff --git a/app/models/ems/article.rb b/app/models/ems/article.rb
index <HASH>..<HASH> 100644
--- a/app/models/ems/article.rb
+++ b/app/models/ems/article.rb
@@ -6,9 +6,11 @@ module Ems
friendly_id :title, use: :slugged
searchable do
- text :title
+ text :title, :stored => true
text :standfirst, :stored => true
- text :content, :stored => true, :more_like_this => true
+ text :content, :stored => true, :more_like_this => true do
+ sanitize self.content_as_html.gsub(/(\n|\r)/, "")
+ end
integer :category_id, :references => Category
end
diff --git a/app/models/ems/news.rb b/app/models/ems/news.rb
index <HASH>..<HASH> 100644
--- a/app/models/ems/news.rb
+++ b/app/models/ems/news.rb
@@ -5,9 +5,11 @@ module Ems
friendly_id :title, use: :slugged
searchable do
- text :title
+ text :title, :stored => true
text :standfirst, :stored => true
- text :content, :stored => true, :more_like_this => true
+ text :content, :stored => true, :more_like_this => true do
+ sanitize self.content_as_html.gsub(/(\n|\r)/, "")
+ end
integer :category_id, :references => Category
end
diff --git a/app/models/ems/report.rb b/app/models/ems/report.rb
index <HASH>..<HASH> 100644
--- a/app/models/ems/report.rb
+++ b/app/models/ems/report.rb
@@ -5,9 +5,11 @@ module Ems
friendly_id :title, use: :slugged
searchable do
- text :title
+ text :title, :stored => true
text :standfirst, :stored => true
- text :content, :stored => true, :more_like_this => true
+ text :content, :stored => true, :more_like_this => true do
+ sanitize self.content_as_html.gsub(/(\n|\r)/, "")
+ end
integer :category_id, :references => Category
end
|
updating search to make sure none of the html is indexed
|
thebeansgroup_ems
|
train
|
4d313447b8b6517184a02b7ac41d1ac7d3f5a501
|
diff --git a/h2o-admissibleml/src/main/java/hex/Infogram/InfogramUtils.java b/h2o-admissibleml/src/main/java/hex/Infogram/InfogramUtils.java
index <HASH>..<HASH> 100644
--- a/h2o-admissibleml/src/main/java/hex/Infogram/InfogramUtils.java
+++ b/h2o-admissibleml/src/main/java/hex/Infogram/InfogramUtils.java
@@ -206,8 +206,8 @@ public class InfogramUtils {
Vec vCMI = Vec.makeVec(cmi, vg.addVec());
Vec vCMIRaw = Vec.makeVec(cmiRaw, vg.addVec());
String[] columnNames = buildCore ? new String[]{"column", "admissible", "admissible_index", "total_information",
- "net_information", "net_information_raw"} : new String[]{"column", "admissible", "admissible_index",
- "relevance_index", "safety_index", "safety_index_raw"};
+ "net_information", "cmi_raw"} : new String[]{"column", "admissible", "admissible_index",
+ "relevance_index", "safety_index", "cmi_raw"};
Frame cmiRelFrame = new Frame(Key.<Frame>make(), columnNames, new Vec[]{vName, vAdm, vAdmIndex, vRel, vCMI, vCMIRaw});
DKV.put(cmiRelFrame);
return cmiRelFrame;
|
Admissible score frame: Rename both raw CMI columns to simply cmi_raw
|
h2oai_h2o-3
|
train
|
60a94df6869f18f75e9e694751f7436c914a4fd4
|
diff --git a/ngTagsInput.js b/ngTagsInput.js
index <HASH>..<HASH> 100644
--- a/ngTagsInput.js
+++ b/ngTagsInput.js
@@ -13,10 +13,9 @@ angular.module('tags-input', []).directive('tagsInput', function() {
' <div class="tag" ng-repeat="tag in tags">' +
' <span>{{ tag }}</span><button type="button" class="removeTag" ng-click="remove($index)">{{ removeTagSymbol }}</button>' +
' </div>' +
- ' <input class="newTag" type="text" placeholder="{{ placeholder }}" size="{{ placeholder.length }}" maxlength="{{ maxLength }}" ng-model="newTag">' +
+ ' <input class="newTag" type="text" placeholder="{{ placeholder }}" size="{{ placeholder.length }}" maxlength="{{ maxLength }}">' +
'</div>',
controller: ['$scope', '$attrs', function($scope, $attrs) {
- $scope.newTag = '';
$scope.placeholder = $attrs.placeholder || 'Add a tag';
$scope.removeTagSymbol = $attrs.removeTagSymbol || String.fromCharCode(215);
$scope.replaceSpacesWithDashes = toBool($attrs.replaceSpacesWithDashes, true);
@@ -27,16 +26,14 @@ angular.module('tags-input', []).directive('tagsInput', function() {
$scope.tags = [];
}
- $scope.add = function() {
+ $scope.add = function(tag) {
if ($scope.replaceSpacesWithDashes) {
- $scope.newTag = $scope.newTag.replace(/\s/g, '-');
+ tag = tag.replace(/\s/g, '-');
}
- if ($scope.tags.indexOf($scope.newTag) == -1) {
- $scope.tags.push($scope.newTag);
+ if ($scope.tags.indexOf(tag) == -1) {
+ $scope.tags.push(tag);
}
-
- $scope.newTag = '';
};
$scope.removeLast = function() {
@@ -60,9 +57,11 @@ angular.module('tags-input', []).directive('tagsInput', function() {
if ((e.keyCode == ENTER && addOnEnter ||
e.keyCode == COMMA && addOnComma ||
e.keyCode == SPACE && addOnSpace) && this.value.trim().length >= scope.minLength) {
- scope.add();
+
+ scope.add(this.value.trim());
scope.$apply();
+ this.value = '';
e.preventDefault();
}
else if (e.keyCode == BACKSPACE && this.value.length == 0) {
|
Changed the code a little bit to make unit tests easier to write
|
mbenford_ngTagsInput
|
train
|
1083ed9c112e039dbf5f4a1d9b14bbb571019c16
|
diff --git a/client/src/main/java/com/metamx/druid/client/cache/MemcachedCacheBroker.java b/client/src/main/java/com/metamx/druid/client/cache/MemcachedCacheBroker.java
index <HASH>..<HASH> 100644
--- a/client/src/main/java/com/metamx/druid/client/cache/MemcachedCacheBroker.java
+++ b/client/src/main/java/com/metamx/druid/client/cache/MemcachedCacheBroker.java
@@ -23,8 +23,10 @@ import net.iharder.base64.Base64;
import net.spy.memcached.AddrUtil;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.DefaultHashAlgorithm;
+import net.spy.memcached.FailureMode;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.MemcachedClientIF;
+import net.spy.memcached.transcoders.SerializingTranscoder;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
@@ -35,15 +37,21 @@ import java.util.concurrent.atomic.AtomicLong;
public class MemcachedCacheBroker implements CacheBroker
{
- public static CacheBroker create(final MemcachedCacheBrokerConfig config)
+ public static MemcachedCacheBroker create(final MemcachedCacheBrokerConfig config)
{
try {
+ SerializingTranscoder transcoder = new SerializingTranscoder(config.getMaxObjectSize());
+ // disable compression
+ transcoder.setCompressionThreshold(Integer.MAX_VALUE);
+
return new MemcachedCacheBroker(
new MemcachedClient(
new ConnectionFactoryBuilder().setProtocol(ConnectionFactoryBuilder.Protocol.BINARY)
.setHashAlg(DefaultHashAlgorithm.FNV1A_64_HASH)
.setLocatorType(ConnectionFactoryBuilder.Locator.CONSISTENT)
.setDaemon(true)
+ .setFailureMode(FailureMode.Retry)
+ .setTranscoder(transcoder)
.setShouldOptimize(true)
.build(),
AddrUtil.getAddresses(config.getHosts())
@@ -133,4 +141,9 @@ public class MemcachedCacheBroker implements CacheBroker
private String computeKey(String identifier, byte[] key) {
return identifier + Base64.encodeBytes(key, Base64.DONT_BREAK_LINES);
}
+
+ protected MemcachedClientIF getClient()
+ {
+ return client;
+ }
}
diff --git a/client/src/main/java/com/metamx/druid/client/cache/MemcachedCacheBrokerConfig.java b/client/src/main/java/com/metamx/druid/client/cache/MemcachedCacheBrokerConfig.java
index <HASH>..<HASH> 100644
--- a/client/src/main/java/com/metamx/druid/client/cache/MemcachedCacheBrokerConfig.java
+++ b/client/src/main/java/com/metamx/druid/client/cache/MemcachedCacheBrokerConfig.java
@@ -15,4 +15,7 @@ public abstract class MemcachedCacheBrokerConfig
@Config("${prefix}.hosts")
public abstract String getHosts();
+
+ @Config("${prefix}.maxObjectSize")
+ public abstract int getMaxObjectSize();
}
|
make max cache object size configurable and disable client-side compressions
|
apache_incubator-druid
|
train
|
26fde9110f932df8cb5cc24396e7a54a6d3a94c2
|
diff --git a/utils.go b/utils.go
index <HASH>..<HASH> 100644
--- a/utils.go
+++ b/utils.go
@@ -206,7 +206,7 @@ func getValueFromFields(value reflect.Value, fieldNames []string) (results []int
// as FieldByName could panic
if indirectValue := reflect.Indirect(value); indirectValue.IsValid() {
for _, fieldName := range fieldNames {
- if fieldValue := indirectValue.FieldByName(fieldName); fieldValue.IsValid() {
+ if fieldValue := reflect.Indirect(indirectValue.FieldByName(fieldName)); fieldValue.IsValid() {
result := fieldValue.Interface()
if r, ok := result.(driver.Valuer); ok {
result, _ = r.Value()
|
getValueFromFields doesn't panic on nil pointers (#<I>)
* `IsValid()` won't return `false` for nil pointers unless Value
is wrapped in a `reflect.Indirect`.
|
jinzhu_gorm
|
train
|
55fb5ccaa16194b4d996dd11936e93840e4e84c1
|
diff --git a/Lib/glyphsLib/builder/anchors.py b/Lib/glyphsLib/builder/anchors.py
index <HASH>..<HASH> 100644
--- a/Lib/glyphsLib/builder/anchors.py
+++ b/Lib/glyphsLib/builder/anchors.py
@@ -125,16 +125,16 @@ def _adjust_anchors(anchor_data, ufo, parent, component):
glyph = ufo[component.baseGlyph]
t = Transform(*component.transformation)
for anchor in glyph.anchors:
- # component is attached to a specific named anchor (e.g. top_2 for a ligature glyph) rather than to the standard anchors (top/bottom)
_namedAnchor = _anchor(parent, component)
- if _namedAnchor in anchor_data:
- anchor_data[_namedAnchor] = t.transformPoint((anchor.x, anchor.y))
# only adjust if this anchor has data and the component also contains
# the associated mark anchor (e.g. "_top" for "top")
- elif anchor.name in anchor_data and any(
+ if anchor.name in anchor_data and any(
a.name == "_" + anchor.name for a in glyph.anchors
):
anchor_data[anchor.name] = t.transformPoint((anchor.x, anchor.y))
+ # component is attached to a specific named anchor (e.g. top_2 for a ligature glyph) rather than to the standard anchors (top/bottom)
+ elif _namedAnchor in anchor_data:
+ anchor_data[_namedAnchor] = t.transformPoint((anchor.x, anchor.y))
def to_ufo_glyph_anchors(self, glyph, anchors):
|
Changed order, the named anchor code needs to be secondary
|
googlefonts_glyphsLib
|
train
|
52eeb8551e8b8104c5339b29eb1b46fd2999d809
|
diff --git a/builtin/logical/aws/secret_access_keys_test.go b/builtin/logical/aws/secret_access_keys_test.go
index <HASH>..<HASH> 100644
--- a/builtin/logical/aws/secret_access_keys_test.go
+++ b/builtin/logical/aws/secret_access_keys_test.go
@@ -9,7 +9,17 @@ func TestNormalizeDisplayName(t *testing.T) {
expectedName := "___test_name_should_be_normalized___"
normalizedName := normalizeDisplayName(invalidName)
if normalizedName != expectedName {
- t.Fatalf("normalizeDisplayName does not normalize AWS name correctly: %s", normalizedName)
+ t.Fatalf(
+ "normalizeDisplayName does not normalize AWS name correctly: %s",
+ normalizedName)
+ }
+
+ validName := "test_name_should_normalize_to_itself@example.com"
+ normalizedValidName := normalizeDisplayName(validName)
+ if normalizedValidName != validName {
+ t.Fatalf(
+ "normalizeDisplayName erroneously normalizes valid names: %s",
+ normalizedName)
}
}
|
Adding one more test (for no-op case)
|
hashicorp_vault
|
train
|
e4a5de9baf93ed3ccb4c385b5df74fa25bdd79e5
|
diff --git a/spring-cloud-aws-messaging/src/test/java/org/springframework/cloud/aws/messaging/config/annotation/SqsConfigurationTest.java b/spring-cloud-aws-messaging/src/test/java/org/springframework/cloud/aws/messaging/config/annotation/SqsConfigurationTest.java
index <HASH>..<HASH> 100644
--- a/spring-cloud-aws-messaging/src/test/java/org/springframework/cloud/aws/messaging/config/annotation/SqsConfigurationTest.java
+++ b/spring-cloud-aws-messaging/src/test/java/org/springframework/cloud/aws/messaging/config/annotation/SqsConfigurationTest.java
@@ -20,7 +20,6 @@ import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
-import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.AmazonSQSAsync;
import com.amazonaws.services.sqs.AmazonSQSAsyncClient;
import com.amazonaws.services.sqs.buffered.AmazonSQSBufferedAsyncClient;
@@ -52,6 +51,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.withSettings;
/**
* @author Alain Sahli
@@ -189,7 +189,7 @@ public class SqsConfigurationTest {
@Configuration
public static class ConfigurationWithCustomAmazonClient {
- public static final AmazonSQSAsync CUSTOM_SQS_CLIENT = mock(AmazonSQSAsync.class);
+ public static final AmazonSQSAsync CUSTOM_SQS_CLIENT = mock(AmazonSQSAsync.class, withSettings().stubOnly());
@Bean
public AWSCredentialsProvider awsCredentials() {
@@ -209,7 +209,7 @@ public class SqsConfigurationTest {
public static final HandlerMethodReturnValueHandler CUSTOM_RETURN_VALUE_HANDLER = mock(HandlerMethodReturnValueHandler.class);
public static final HandlerMethodArgumentResolver CUSTOM_ARGUMENT_RESOLVER = mock(HandlerMethodArgumentResolver.class);
- public static final AmazonSQSAsync CUSTOM_AMAZON_SQS = mock(AmazonSQSAsync.class);
+ public static final AmazonSQSAsync CUSTOM_AMAZON_SQS = mock(AmazonSQSAsync.class, withSettings().stubOnly());
public static final ResourceIdResolver CUSTOM_RESOURCE_ID_RESOLVER = mock(ResourceIdResolver.class);
@Bean
@@ -229,7 +229,7 @@ public class SqsConfigurationTest {
@Configuration
public static class ConfigurationWithCustomContainerFactory {
- public static final AmazonSQSAsync AMAZON_SQS = mock(AmazonSQSAsync.class);
+ public static final AmazonSQSAsync AMAZON_SQS = mock(AmazonSQSAsync.class, withSettings().stubOnly());
public static final boolean AUTO_STARTUP = true;
public static final int MAX_NUMBER_OF_MESSAGES = 1456;
public static final QueueMessageHandler MESSAGE_HANDLER;
@@ -237,7 +237,7 @@ public class SqsConfigurationTest {
public static final SimpleAsyncTaskExecutor TASK_EXECUTOR = new SimpleAsyncTaskExecutor();
public static final int VISIBILITY_TIMEOUT = 1789;
public static final int WAIT_TIME_OUT = 12;
- public static final DestinationResolver<String> DESTINATION_RESOLVER = new DynamicQueueUrlDestinationResolver(mock(AmazonSQS.class));
+ public static final DestinationResolver<String> DESTINATION_RESOLVER = new DynamicQueueUrlDestinationResolver(mock(AmazonSQSAsync.class, withSettings().stubOnly()));
public static final long BACK_OFF_TIME = 5000;
static {
|
Use stubonly mocking for async client (to avoid OOM on Linux)
|
spring-cloud_spring-cloud-aws
|
train
|
5903d151f83229f69cc5b89f140927901798f69f
|
diff --git a/lib/transforms/decreaseItemDepth.js b/lib/transforms/decreaseItemDepth.js
index <HASH>..<HASH> 100644
--- a/lib/transforms/decreaseItemDepth.js
+++ b/lib/transforms/decreaseItemDepth.js
@@ -22,48 +22,47 @@ function decreaseItemDepth(opts, transform, ordered) {
return transform;
}
- let currentItem = getCurrentItem(opts, state);
+ const currentItem = getCurrentItem(opts, state);
const currentList = document.getParent(currentItem.key);
const parentItem = document.getParent(currentList.key);
const parentList = document.getParent(parentItem.key);
- // The items following will be moved as a sublist of currentItem
+ // The items following the item will be moved to a sublist of currentItem
const followingItems = currentList.nodes
.skipUntil(i => i === currentItem)
.rest();
- // Remove the item and following from current list
- if (currentList.nodes.count() === followingItems.count() + 1) {
- // If current list will be emptied, remove the whole list
- transform = transform.removeNodeByKey(currentList.key);
- } else {
- // Just remove the items
- transform = transform.setNodeByKey(currentList.key, {
- nodes: currentList.nodes.takeUntil(i => i === currentItem)
- });
- }
+ // True if the currentItem and the followingItems make the whole
+ // currentList, and hence the currentList will be emptied
+ const willEmptyCurrentList = currentList.nodes.count() === followingItems.count() + 1;
if (!followingItems.isEmpty()) {
// Add them as sublist of currentItem
const sublist = Slate.Block.create({
kind: 'block',
- type: currentList.type,
- nodes: followingItems
- });
- currentItem = currentItem.merge({
- nodes: currentItem.nodes.push(sublist)
+ type: currentList.type
});
+ // Add the sublist
+ transform = transform.insertNodeByKey(
+ currentItem.key, currentItem.nodes.size, sublist, { normalize: false }
+ );
+
+ // Move the followingItems to the sublist
+ transform = followingItems.reduce((tr, item) => {
+ return tr.moveNodeByKey(
+ item.key, sublist.key, sublist.nodes.size, { normalize: false }
+ );
+ }, transform);
}
- // Insert the item after parent item
- const afterRemoval = transform.state;
- let newParentListItems = afterRemoval.document.getDescendant(parentList).nodes;
- newParentListItems = newParentListItems.insert(
- parentList.nodes.indexOf(parentItem) + 1,
- currentItem
+ // Move the item after parent item and normalize
+ transform = transform.moveNodeByKey(
+ currentItem.key, parentList.key, parentList.nodes.indexOf(parentItem) + 1
);
- transform = transform.setNodeByKey(parentList.key, {
- nodes: newParentListItems
- });
+
+ // Remove the currentList completely if needed
+ if (willEmptyCurrentList) {
+ transform = transform.removeNodeByKey(currentList.key);
+ }
return transform;
}
|
Adapt decreaseItemDepth with appropriate transform
|
GitbookIO_slate-edit-list
|
train
|
439316f5d089bbf618e4269a5799805448cdc105
|
diff --git a/pandas/core/format.py b/pandas/core/format.py
index <HASH>..<HASH> 100644
--- a/pandas/core/format.py
+++ b/pandas/core/format.py
@@ -165,7 +165,9 @@ def _encode_diff_func():
encoding = get_option("display.encoding")
def _encode_diff(x):
- return len(x) - len(x.decode(encoding))
+ if not isinstance(x,unicode):
+ return len(x) - len(x.decode(encoding))
+ return 0
return _encode_diff
|
BUG: don't rely on sys.getdefaultencoding if we don't need to GH<I>
|
pandas-dev_pandas
|
train
|
d79c55f61d224e138979e6b799cf7706f041132b
|
diff --git a/jlib.container/src/main/java/org/jlib/container/sequence/ReplaceSequenceIterator.java b/jlib.container/src/main/java/org/jlib/container/sequence/ReplaceSequenceIterator.java
index <HASH>..<HASH> 100644
--- a/jlib.container/src/main/java/org/jlib/container/sequence/ReplaceSequenceIterator.java
+++ b/jlib.container/src/main/java/org/jlib/container/sequence/ReplaceSequenceIterator.java
@@ -40,4 +40,12 @@ extends ReplaceContainerIterator<Element>, SequenceIterator<Element> {
@Override
public void replace(final Element element)
throws NoElementToReplaceException;
+
+ /**
+ * Returns the traversed {@link ReplaceSequence}
+ *
+ * @return traversed {@link ReplaceSequence}
+ */
+ @Override
+ public ReplaceSequence<Element> getSequence();
}
|
ReplaceSequenceIterator: getSequence method added
|
jlib-framework_jlib-operator
|
train
|
43aad1dc768fef64ae12ffb90ffbd761165abe34
|
diff --git a/rest/core/src/main/java/org/seedstack/seed/rest/internal/RestPlugin.java b/rest/core/src/main/java/org/seedstack/seed/rest/internal/RestPlugin.java
index <HASH>..<HASH> 100644
--- a/rest/core/src/main/java/org/seedstack/seed/rest/internal/RestPlugin.java
+++ b/rest/core/src/main/java/org/seedstack/seed/rest/internal/RestPlugin.java
@@ -131,10 +131,12 @@ public class RestPlugin extends AbstractPlugin implements RestProvider {
return new AbstractModule() {
@Override
protected void configure() {
- install(new RestModule(restConfiguration, resources, providers));
install(new HypermediaModule(jsonHome, relRegistry));
- if (enabled && !rootResourcesByVariant.isEmpty()) {
- install(new RootResourcesModule(rootResourcesByVariant));
+ if (enabled) {
+ install(new RestModule(restConfiguration, resources, providers));
+ if (!rootResourcesByVariant.isEmpty()) {
+ install(new RootResourcesModule(rootResourcesByVariant));
+ }
}
}
};
|
Bind resources only in servlet context
|
seedstack_seed
|
train
|
6ec0d82a7e693da0c9d265b8aea0a0cbebf64410
|
diff --git a/errors.go b/errors.go
index <HASH>..<HASH> 100644
--- a/errors.go
+++ b/errors.go
@@ -8,7 +8,7 @@ import (
"sync"
)
-type Error struct {
+type Err struct {
Message string
reportable bool
InnerError error
@@ -18,16 +18,16 @@ type Error struct {
type HttpError struct {
StatusCode int
- *Error
+ *Err
}
// NewError wraps an error with the error's message.
-func NewError(err error) *Error {
+func NewError(err error) *Err {
return NewErrorf(err, "")
}
// NewErrorf wraps an error with a formatted message.
-func NewErrorf(err error, format string, a ...interface{}) *Error {
+func NewErrorf(err error, format string, a ...interface{}) *Err {
var msg string
if len(format) > 0 {
msg = fmt.Sprintf(format, a...)
@@ -35,7 +35,7 @@ func NewErrorf(err error, format string, a ...interface{}) *Error {
msg = err.Error()
}
- return &Error{
+ return &Err{
Message: msg,
reportable: true,
InnerError: err,
@@ -60,28 +60,36 @@ func NewHttpErrorf(err error, status int, format string, a ...interface{}) *Http
// Error returns the error message. This will be the inner error's message,
// unless a formatted message is provided from Errorf().
-func (e *Error) Error() string {
+func (e *Err) Error() string {
+ if e.InnerError != nil {
+ return e.InnerError.Error()
+ }
return e.Message
}
// Stack returns the runtime stack stored with this Error.
-func (e *Error) Stack() []byte {
+func (e *Err) Stack() []byte {
return e.stack
}
// Data returns the error's current grohl.Data context.
-func (e *Error) Data() Data {
+func (e *Err) Data() Data {
return e.data
}
// Reportable returns whether this error should be sent to the grohl
// ErrorReporter.
-func (e *Error) Reportable() bool {
+func (e *Err) Reportable() bool {
return e.reportable
}
+// ErrorMessage returns a user-visible error message.
+func (e *Err) ErrorMessage() string {
+ return e.Message
+}
+
// Add adds the key and value to this error's context.
-func (e *Error) Add(key string, value interface{}) {
+func (e *Err) Add(key string, value interface{}) {
if e.data == nil {
e.data = Data{}
}
@@ -89,14 +97,14 @@ func (e *Error) Add(key string, value interface{}) {
}
// Delete removes the key from this error's context.
-func (e *Error) Delete(key string) {
+func (e *Err) Delete(key string) {
if e.data != nil {
delete(e.data, key)
}
}
// SetReportable sets whether the ErrorReporter should ignore this error.
-func (e *Error) SetReportable(v bool) {
+func (e *Err) SetReportable(v bool) {
e.reportable = v
}
diff --git a/errors_test.go b/errors_test.go
index <HASH>..<HASH> 100644
--- a/errors_test.go
+++ b/errors_test.go
@@ -101,8 +101,8 @@ func TestLogsWrappedError(t *testing.T) {
"c=3",
"d=4",
"at=exception",
- "class=*grohl.Error",
- "message=wat",
+ "class=*grohl.Err",
+ "message=sup",
}
otherRows := append(firstRow, "~site=")
|
rename type to *grohl.Err, to remove conflict with Error()
|
technoweenie_grohl
|
train
|
b5efe78de9dd721f9135f65c525a3e8ab8b06f79
|
diff --git a/sklearn_porter/Template.py b/sklearn_porter/Template.py
index <HASH>..<HASH> 100644
--- a/sklearn_porter/Template.py
+++ b/sklearn_porter/Template.py
@@ -98,7 +98,8 @@ class Template(object):
self.estimator_type, class_name, 'templates',
self.target_language, name + '.txt')
if os.path.isfile(path):
- template = open(path, 'r').read()
+ with open(path, 'r') as file_:
+ template = file_.read()
if n_indents is not None:
template = self.indent(template, n_indents, skipping)
return template
@@ -112,4 +113,4 @@ class Template(object):
def data(self, dict_):
copy = self.__dict__.copy()
copy.update(dict_) # update and extend dictionary
- return copy
\ No newline at end of file
+ return copy
|
release/<I>: Add closing file
|
nok_sklearn-porter
|
train
|
c250c5123b1732ba9ae117a35d8311e19ec9a1d7
|
diff --git a/src/Helper/Type/Any.php b/src/Helper/Type/Any.php
index <HASH>..<HASH> 100644
--- a/src/Helper/Type/Any.php
+++ b/src/Helper/Type/Any.php
@@ -20,11 +20,6 @@ class Any
return count($var) < 1;
}
- // var seems to be object?
- if (is_object($var)) {
- return count(get_object_vars($var)) < 1;
- }
-
// float,int,string,bool and null left. Check if not empty. Int and float will never equal to null.
return ($var === null || $var === '' || $var === false);
}
|
Fix obj check with private methods
|
phpffcms_ffcms-core
|
train
|
41615f2edbe5a2e82f1a375ace232114c4b92589
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -21,28 +21,36 @@ function configureDefaults(options) {
options.properties = options.properties || parsePropertiesFromEnv(process.env.PROPERTIES) || null;
options.toConsole = !!options.toConsole;
options.suiteTitleSeparedBy = options.suiteTitleSeparedBy || ' ';
+ options.rootSuiteTitle = 'Root Suite';
return options;
}
function defaultSuiteTitle(suite) {
+ if (suite.root && suite.title === '') {
+ return this._options.rootSuiteTitle;
+ }
return suite.title;
}
-function fullSuiteTitle(suite, options) {
+function fullSuiteTitle(suite) {
var parent = suite.parent;
var title = [ suite.title ];
while (parent) {
- title.unshift(parent.title);
+ if (parent.root && parent.title === '') {
+ title.unshift(this._options.rootSuiteTitle);
+ } else {
+ title.unshift(parent.title);
+ }
parent = parent.parent;
}
- return title.join(options.suiteTitleSeparedBy);
+ return title.join(this._options.suiteTitleSeparedBy);
}
function isInvalidSuite(suite) {
- return suite.title === '' || suite.tests.length === 0 && suite.suites.length === 0;
+ return (!suite.root && suite.title === '') || (suite.tests.length === 0 && suite.suites.length === 0);
}
function parsePropertiesFromEnv(envValue) {
@@ -106,10 +114,6 @@ function MochaJUnitReporter(runner, options) {
}.bind(this));
this._runner.on('suite', function(suite) {
- if (suite.root) {
- suite.title = 'Root Suite';
- }
-
if (!isInvalidSuite(suite)) {
testsuites.push(this.getTestsuiteData(suite));
}
@@ -147,7 +151,7 @@ MochaJUnitReporter.prototype.getTestsuiteData = function(suite) {
testsuite: [
{
_attr: {
- name: this._generateSuiteTitle(suite, this._options),
+ name: this._generateSuiteTitle(suite),
timestamp: new Date().toISOString().slice(0,-5),
tests: suite.tests.length
}
|
fix 'Root Suite' prefixed to every testcase name (#<I>)
* Do not modify suite's title and only show 'Root Suite' if necessary
* 'Root Suite' modifiable via option
|
michaelleeallen_mocha-junit-reporter
|
train
|
b1f2be4453e6c58f751cfcd58459c28fc7fe6efc
|
diff --git a/tasklib/task.py b/tasklib/task.py
index <HASH>..<HASH> 100644
--- a/tasklib/task.py
+++ b/tasklib/task.py
@@ -421,6 +421,12 @@ class Task(TaskResource):
"""
pass
+ class ActiveTask(Exception):
+ """
+ Raised when the operation cannot be performed on the active task.
+ """
+ pass
+
class InactiveTask(Exception):
"""
Raised when the operation cannot be performed on an inactive task.
@@ -600,6 +606,8 @@ class Task(TaskResource):
raise Task.CompletedTask("Cannot start a completed task")
elif self.deleted:
raise Task.DeletedTask("Deleted task cannot be started")
+ elif self.active:
+ raise Task.ActiveTask("Task is already active")
self.warrior.execute_command([self['uuid'], 'start'])
|
Task: Do not allow starting a Task which has already been started
|
robgolding_tasklib
|
train
|
a84da22d6b09559c14be3b038b30c50e89a14092
|
diff --git a/apex.go b/apex.go
index <HASH>..<HASH> 100644
--- a/apex.go
+++ b/apex.go
@@ -18,7 +18,7 @@ Examples:
force apex ~/test.apex
force apex
- >> Start typing Apex code; press CTRL-D(for Max/Unix) / Ctrl-Z (for Windows) when finished
+ >> Start typing Apex code; press CTRL-D(for Mac/Linux) / Ctrl-Z (for Windows) when finished
`,
}
@@ -34,7 +34,7 @@ func runApex(cmd *Command, args []string) {
} else if len(args) > 1 {
fmt.Println("Got test indication.")
} else {
- fmt.Println(">> Start typing Apex code; press CTRL-D(for Max/Unix) / Ctrl-Z (for Windows) when finished")
+ fmt.Println(">> Start typing Apex code; press CTRL-D(for Mac/Linux) / Ctrl-Z (for Windows) when finished")
code, err = ioutil.ReadAll(os.Stdin)
fmt.Println("\n\n>> Executing code...")
}
|
Corrected "Max/Unix" to "Mac/Linux"
- Spelling mistake in "Max"
- Changed "Unix" to "Linux". Since, Mac is already a Unix based system
|
ForceCLI_force
|
train
|
ed8727515259c9689ffddf505a4c7aabfd599509
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -360,62 +360,58 @@ const execa = (file, args, options) => {
}
}), cleanup);
- const handlePromise = () => {
+ const handlePromise = async () => {
const stdoutPromise = getStreamPromise(spawned.stdout, {encoding, buffer, maxBuffer});
const stderrPromise = getStreamPromise(spawned.stderr, {encoding, buffer, maxBuffer});
const allPromise = getStreamPromise(spawned.all, {encoding, buffer, maxBuffer: maxBuffer * 2});
- const finalize = async () => {
- let results;
- try {
- results = await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]);
- } catch (error) {
- const {code, signal} = error;
- results = await Promise.all([
- {error, code, signal},
- getBufferedData(spawned.stdout, stdoutPromise),
- getBufferedData(spawned.stderr, stderrPromise),
- getBufferedData(spawned.all, allPromise)
- ]);
- }
+ let results;
+ try {
+ results = await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]);
+ } catch (error) {
+ const {code, signal} = error;
+ results = await Promise.all([
+ {error, code, signal},
+ getBufferedData(spawned.stdout, stdoutPromise),
+ getBufferedData(spawned.stderr, stderrPromise),
+ getBufferedData(spawned.all, allPromise)
+ ]);
+ }
- const [result, stdout, stderr, all] = results;
- result.stdout = handleOutput(parsed.options, stdout);
- result.stderr = handleOutput(parsed.options, stderr);
- result.all = handleOutput(parsed.options, all);
-
- if (result.error || result.code !== 0 || result.signal !== null) {
- const error = makeError(result, {
- code: result.code,
- command,
- parsed,
- timedOut,
- isCanceled,
- killed: spawned.killed
- });
-
- if (!parsed.options.reject) {
- return error;
- }
-
- throw error;
- }
+ const [result, stdout, stderr, all] = results;
+ result.stdout = handleOutput(parsed.options, stdout);
+ result.stderr = handleOutput(parsed.options, stderr);
+ result.all = handleOutput(parsed.options, all);
- return {
+ if (result.error || result.code !== 0 || result.signal !== null) {
+ const error = makeError(result, {
+ code: result.code,
command,
- exitCode: 0,
- exitCodeName: 'SUCCESS',
- stdout: result.stdout,
- stderr: result.stderr,
- all: result.all,
- failed: false,
- timedOut: false,
- isCanceled: false,
- killed: false
- };
- };
+ parsed,
+ timedOut,
+ isCanceled,
+ killed: spawned.killed
+ });
- return finalize();
+ if (!parsed.options.reject) {
+ return error;
+ }
+
+ throw error;
+ }
+
+ return {
+ command,
+ exitCode: 0,
+ exitCodeName: 'SUCCESS',
+ stdout: result.stdout,
+ stderr: result.stderr,
+ all: result.all,
+ failed: false,
+ timedOut: false,
+ isCanceled: false,
+ killed: false
+ };
};
crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed);
|
Refactor `finalize()` method (#<I>)
|
sindresorhus_execa
|
train
|
a9024de734726013a49ca00a237d4915c0be4c06
|
diff --git a/core/src/main/java/org/springframework/security/core/SpringSecurityCoreVersion.java b/core/src/main/java/org/springframework/security/core/SpringSecurityCoreVersion.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/org/springframework/security/core/SpringSecurityCoreVersion.java
+++ b/core/src/main/java/org/springframework/security/core/SpringSecurityCoreVersion.java
@@ -40,7 +40,7 @@ public class SpringSecurityCoreVersion {
*/
public static final long SERIAL_VERSION_UID = 420L;
- static final String MIN_SPRING_VERSION = "4.3.3.RELEASE";
+ static final String MIN_SPRING_VERSION = "4.3.4.RELEASE";
static {
performVersionChecks();
|
Polish Spring Version Update
Fix related tests.
Issue gh-<I>
|
spring-projects_spring-security
|
train
|
43cb95d46b227f1562cfbb80adeb30af065720ba
|
diff --git a/client/_set-emmet.js b/client/_set-emmet.js
index <HASH>..<HASH> 100644
--- a/client/_set-emmet.js
+++ b/client/_set-emmet.js
@@ -23,18 +23,18 @@ module.exports = function() {
exec.if(this._Emmet, () => {
this.setOption('enableEmmet', true);
- }, (callback) => {
+ }, async (callback) => {
const url = _PREFIX + join([
dirVendor + 'emmet.js',
dir + 'ext-emmet.js',
]);
- load.js(url, () => {
- this._Emmet = ace.require('ace/ext/emmet');
- this._Emmet.setCore(window.emmet);
-
- callback();
- });
+ await load.js(url);
+
+ this._Emmet = ace.require('ace/ext/emmet');
+ this._Emmet.setCore(window.emmet);
+
+ callback();
});
};
diff --git a/client/edward.js b/client/edward.js
index <HASH>..<HASH> 100644
--- a/client/edward.js
+++ b/client/edward.js
@@ -15,12 +15,11 @@ const smalltalk = require('smalltalk');
const {promisify} = require('es6-promisify');
const jssha = require('jssha');
const restafary = require('restafary/client');
+const tryToCatch = require('try-to-catch');
window.load = window.load || load;
window.exec = window.exec || exec;
-const loadJSON = promisify(load.json);
-
const Story = require('./story');
const _clipboard = require('./_clipboard');
const _setEmmet = require('./_set-emmet');
@@ -121,7 +120,7 @@ Edward.prototype._init = function(fn) {
callback();
});
},
- () => {
+ async () => {
this._Emitter = Emitify();
this._Ace = ace.edit(this._Element);
this._Modelist = ace.require('ace/ext/modelist');
@@ -135,23 +134,24 @@ Edward.prototype._init = function(fn) {
this._addCommands();
this._Ace.$blockScrolling = Infinity;
- load.json(this._PREFIX + '/edit.json', (error, config) => {
- const {
- options = {},
- } = config;
- const preventOverwrite = () => {
- for (const name of Object.keys(this._Config.options)) {
- options[name] = this._Config.options[name];
- }
- };
-
- fn();
- preventOverwrite();
-
- this._Config = config;
-
- edward.setOptions(options);
- });
+ const config = await load.json(this._PREFIX + '/edit.json');
+
+ const {
+ options = {},
+ } = config;
+
+ const preventOverwrite = () => {
+ for (const name of Object.keys(this._Config.options)) {
+ options[name] = this._Config.options[name];
+ }
+ };
+
+ fn();
+ preventOverwrite();
+
+ this._Config = config;
+
+ edward.setOptions(options);
},
]);
};
@@ -461,7 +461,7 @@ Edward.prototype._loadOptions = async function() {
if (this._Options)
return this._Options;
- const data = await loadJSON(url);
+ const data = await load.json(url);
this._Options = data;
@@ -495,14 +495,14 @@ Edward.prototype._diff = function(newValue) {
Edward.prototype._setEmmet = _setEmmet;
-Edward.prototype._addExt = function(name, fn) {
+Edward.prototype._addExt = async function (name, fn) {
if (this._Ext)
return add(null, this._Ext);
- load.json(this._PREFIX + '/json/ext.json', (error, data) => {
- this._Ext = data;
- add(error, this._Ext);
- });
+ const [error, data] = await tryToCatch(load.json, this._PREFIX + '/json/ext.json');
+ this._Ext = data;
+
+ add(error, this._Ext);
function add(error, exts) {
if (error)
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -74,7 +74,7 @@
"eslint-plugin-putout": "^2.0.0",
"execon": "^1.2.9",
"jssha": "^2.3.1",
- "load.js": "^2.0.0",
+ "load.js": "^3.0.2",
"madrun": "^3.0.1",
"nodemon": "^1.11.0",
"once": "^1.4.0",
|
feature(package) load.js <I>
|
cloudcmd_edward
|
train
|
0d0b9db2ec5598854c6b00a8c8e08c939789db01
|
diff --git a/Hydrators/UserHydrator.php b/Hydrators/UserHydrator.php
index <HASH>..<HASH> 100644
--- a/Hydrators/UserHydrator.php
+++ b/Hydrators/UserHydrator.php
@@ -74,66 +74,6 @@ class UserHydrator
$hydrated->setValidUntil(new DateTime($user->valid_until));
}
- if (isset($user->created_comments) && is_array($user->created_comments)) {
- $hydrated->setCreatedComments(CommentHydrator::hydrateCollection($user->created_comments));
- }
-
- if (isset($user->created_reviews) && is_array($user->created_reviews)) {
- $hydrated->setCreatedReviews(ReviewHydrator::hydrateCollection($user->created_reviews));
- }
-
- if (isset($user->created_applications) && is_array($user->created_applications)) {
- $hydrated->setCreatedApplications(ApplicationHydrator::hydrateCollection($user->created_applications));
- }
-
- if (isset($user->created_scans) && is_array($user->created_scans)) {
- $hydrated->setCreatedScans(ScanHydrator::hydrateCollection($user->created_scans));
- }
-
- if (isset($user->created_application_acls) && is_array($user->created_application_acls)) {
- $hydrated->setCreatedApplicationAcls(ApplicationAclHydrator::hydrateCollection($user->created_application_acls));
- }
-
- if (isset($user->created_quota_acls) && is_array($user->created_quota_acls)) {
- $hydrated->setCreatedQuotaAcls(QuotaAclHydrator::hydrateCollection($user->created_quota_acls));
- }
-
- if (isset($user->created_licenses) && is_array($user->created_licenses)) {
- $hydrated->setCreatedLicenses(LicenseHydrator::hydrateCollection($user->created_licenses));
- }
-
- if (isset($user->created_users) && is_array($user->created_users)) {
- $hydrated->setCreatedUsers(self::hydrateCollection($user->created_users));
- }
-
- if (isset($user->created_teams) && is_array($user->created_teams)) {
- $hydrated->setCreatedTeams(TeamHydrator::hydrateCollection($user->created_teams));
- }
-
- if (isset($user->created_uploads) && is_array($user->created_uploads)) {
- $hydrated->setCreatedUploads(UploadHydrator::hydrateCollection($user->created_uploads));
- }
-
- if (isset($user->application_acls) && is_array($user->application_acls)) {
- $hydrated->setApplicationAcls(ApplicationAclHydrator::hydrateCollection($user->application_acls));
- }
-
- if (isset($user->quota_acls) && is_array($user->quota_acls)) {
- $hydrated->setQuotaAcls(QuotaAclHydrator::hydrateCollection($user->quota_acls));
- }
-
- if (isset($user->logs) && is_array($user->logs)) {
- $hydrated->setLogs(LogHydrator::hydrateCollection($user->logs));
- }
-
- if (isset($user->created_by)) {
- $hydrated->setCreatedBy(self::hydrate($user->created_by));
- }
-
- if (isset($user->chargedQuota)) {
- $hydrated->setChargedQuota(QuotaHydrator::hydrate($user->charged_quota));
- }
-
if (isset($user->organization)) {
$hydrated->setOrganization(OrgHydrator::hydrate($user->organization));
}
|
Remove relics from user hydrator
|
rips_php-connector-bundle
|
train
|
e3cceb60389acd53e2feab64b6faea2afe0d4206
|
diff --git a/javascript/DateField.js b/javascript/DateField.js
index <HASH>..<HASH> 100644
--- a/javascript/DateField.js
+++ b/javascript/DateField.js
@@ -1,28 +1,33 @@
(function($) {
- /**
- * Initialize and open a datepicker
- * live() doesn't have "onmatch", and jQuery.entwine is a bit too
- * heavyweight for this, so we need to do this onclick.
- */
- var fields = $('.field.date input.text');
- fields.siblings("button").addClass("ui-icon ui-icon-calendar");
+ $.fn.extend({
+ ssDatepicker: function(opts) {
+ return $(this).each(function() {
+ if($(this).data('datepicker')) return; // already applied
+
+ this.siblings("button").addClass("ui-icon ui-icon-calendar");
+
+ var holder = $(this).parents('.field.date:first'),
+ config = $.extend(opts || {}, $(this).metadata({type: 'class'}), {});
+ if(!config.showcalendar) return;
+
+ if(config.locale && $.datepicker.regional[config.locale]) {
+ config = $.extend(config, $.datepicker.regional[config.locale], {});
+ }
+
+ if(config.min) config.minDate = $.datepicker.parseDate('yy-mm-dd', config.min);
+ if(config.max) config.maxDate = $.datepicker.parseDate('yy-mm-dd', config.max);
- fields.live('click', function() {
- var holder = $(this).parents('.field.date:first'), config = $(this).metadata({type: 'class'});
- if(!config.showcalendar) return;
-
- if(config.locale && $.datepicker.regional[config.locale]) {
- config = $.extend(config, $.datepicker.regional[config.locale], {});
+ // Initialize and open a datepicker
+ // live() doesn't have "onmatch", and jQuery.entwine is a bit too heavyweight for this, so we need to do this onclick.
+ config.dateFormat = config.jqueryDateformat;
+ $(this).datepicker(config);
+ });
}
-
- if(config.min) config.minDate = $.datepicker.parseDate('yy-mm-dd', config.min);
- if(config.max) config.maxDate = $.datepicker.parseDate('yy-mm-dd', config.max);
-
- // Initialize and open a datepicker
- // live() doesn't have "onmatch", and jQuery.entwine is a bit too heavyweight for this, so we need to do this onclick.
- config.dateFormat = config.jqueryDateformat;
- $(this).datepicker(config);
+ });
+
+ $('.field.date input.text').live('click', function() {
+ $(this).ssDatepicker();
$(this).datepicker('show');
});
}(jQuery));
\ No newline at end of file
|
MINOR Refactored DateField.js from inline jQuery.live() application to a ssDatepicker() plugin which can be applied explicitly as well
|
silverstripe_silverstripe-framework
|
train
|
1a9d9388a5ec7803450660e3188e10815ba0d53c
|
diff --git a/indra/statements/statements.py b/indra/statements/statements.py
index <HASH>..<HASH> 100644
--- a/indra/statements/statements.py
+++ b/indra/statements/statements.py
@@ -381,10 +381,9 @@ class Statement(object):
"type %s." % type(ag_attr))
return ag_list
- def get_agent_by_role(self, role):
- if not role in self._agent_order:
- raise ValueError('Invalid role %s' % role)
- return getattr(self, role)
+ def real_agent_list(self):
+ """Return all agents in the statement that are not None."""
+ return [a for a in self.agent_list() if a is not None]
def entities_match(self, other):
self_key = self.entities_match_key()
diff --git a/indra/tests/test_statements.py b/indra/tests/test_statements.py
index <HASH>..<HASH> 100644
--- a/indra/tests/test_statements.py
+++ b/indra/tests/test_statements.py
@@ -2042,3 +2042,10 @@ def test_agent_get_grounding():
assert gr == ('XYZ', '123'), gr
gr = ag.get_grounding(ns_order=['ZYX', 'XYZ'])
assert gr == ('ZYX', '321'), gr
+
+
+def test_real_agent_list():
+ x = Agent('x')
+ agents = Phosphorylation(None, x).real_agent_list()
+ assert len(agents) == 1
+ assert agents[0] == x
|
Implement getting not-none agent list
|
sorgerlab_indra
|
train
|
4e6d18dda73bc7c842c9b1d48845c869bdba94be
|
diff --git a/concrete/src/Cache/Driver/RedisStashDriver.php b/concrete/src/Cache/Driver/RedisStashDriver.php
index <HASH>..<HASH> 100644
--- a/concrete/src/Cache/Driver/RedisStashDriver.php
+++ b/concrete/src/Cache/Driver/RedisStashDriver.php
@@ -115,6 +115,7 @@ class RedisStashDriver extends AbstractDriver
} else {
$serverArray = [];
$ttl = 0.5;
+ $password = null;
foreach ($this->getRedisServers($servers) as $server) {
$serverString = $server['server'];
if (isset($server['port'])) {
@@ -122,13 +123,19 @@ class RedisStashDriver extends AbstractDriver
}
// We can only use one ttl for connection timeout so use the last set ttl
// isset allows for 0 - unlimited
- if (!isset($server['ttl'])) {
+ if (isset($server['ttl'])) {
$ttl = $server['ttl'];
}
-
+ if (isset($server['password'])) {
+ $password = $server['password'];
+ }
$serverArray[] = $serverString;
}
- $redis = new RedisArray($serverArray, ['connect_timeout' => $ttl]);
+ $options = ['connect_timeout' => $ttl];
+ if ($password !== null) {
+ $options['auth'] = $password;
+ }
+ $redis = new RedisArray($serverArray, $options);
}
return $redis;
@@ -145,15 +152,12 @@ class RedisStashDriver extends AbstractDriver
{
if (!empty($servers)) {
foreach ($servers as $server) {
- $password = null;
- if (isset($server['password'])) {
- $password = $server['password'];
- }
if (isset($server['socket'])) {
$server = [
'server' => array_get($server, 'socket', ''),
'ttl' => array_get($server, 'ttl', null),
+ 'password' => array_get($server, 'password', null)
];
} else {
$host = array_get($server, 'host', '');
@@ -163,12 +167,10 @@ class RedisStashDriver extends AbstractDriver
'server' => $host,
'port' => array_get($server, 'port', 11211),
'ttl' => array_get($server, 'ttl', null),
+ 'password' => array_get($server, 'password', null)
];
}
- if ($password != null) {
- $server['password'] = $password;
- }
yield $server;
}
diff --git a/concrete/src/Session/SessionFactory.php b/concrete/src/Session/SessionFactory.php
index <HASH>..<HASH> 100644
--- a/concrete/src/Session/SessionFactory.php
+++ b/concrete/src/Session/SessionFactory.php
@@ -311,6 +311,7 @@ class SessionFactory implements SessionFactoryInterface
} else {
$serverArray = [];
$ttl = 0.5;
+ $password = null;
foreach ($this->getRedisServers($servers) as $server) {
$serverString = $server['server'];
if (isset($server['port'])) {
@@ -318,13 +319,20 @@ class SessionFactory implements SessionFactoryInterface
}
// We can only use one ttl for connection timeout so use the last set ttl
// isset allows for 0 - unlimited
- if (!isset($server['ttl'])) {
+ if (isset($server['ttl'])) {
$ttl = $server['ttl'];
}
+ if (isset($server['password'])) {
+ $password = $server['password'];
+ }
$serverArray[] = $serverString;
}
- $redis = $this->app->make(RedisArray::class, [$serverArray, ['connect_timeout' => $ttl]]);
+ $options = ['connect_timeout' => $ttl];
+ if ($password !== null) {
+ $options['auth'] = $password;
+ }
+ $redis = $this->app->make(RedisArray::class, [$serverArray, $options]);
}
return $redis;
@@ -345,6 +353,7 @@ class SessionFactory implements SessionFactoryInterface
$server = [
'server' => array_get($server, 'socket', ''),
'ttl' => array_get($server, 'ttl', null),
+ 'password' => array_get($server, 'password', null),
];
} else {
$host = array_get($server, 'host', '');
@@ -354,6 +363,7 @@ class SessionFactory implements SessionFactoryInterface
'server' => $host,
'port' => array_get($server, 'port', 11211),
'ttl' => array_get($server, 'ttl', null),
+ 'password' => array_get($server, 'password', null),
];
}
yield $server;
|
Fixing not sending password to RedisArray in session and cache drivers
Removes unused code from #<I>
Fix ttl not being used in RedisArray correctly
|
concrete5_concrete5
|
train
|
09cd1cb0725ba7215e2b30c8685c9e97623111f6
|
diff --git a/lib/xo/board.rb b/lib/xo/board.rb
index <HASH>..<HASH> 100644
--- a/lib/xo/board.rb
+++ b/lib/xo/board.rb
@@ -18,7 +18,7 @@ module TTT
end
def free?(r, c)
- ![:x, :o].include?(self[r, c])
+ !self.class.is_token?(self[r, c])
end
def clear
@@ -53,8 +53,12 @@ module TTT
r.between?(1, ROWS) && c.between?(1, COLS)
end
+ def self.is_token?(val)
+ [:x, :o].include?(val)
+ end
+
def state(token)
- raise ArgumentError, token unless [:x, :o].include?(token)
+ raise ArgumentError, token unless self.class.is_token?(token)
raise TooManyMovesAheadError if two_or_more_moves_ahead?
raise TwoWinnersError if two_winners?
@@ -139,7 +143,7 @@ module TTT
end
def add_winner(token, details)
- if [:x, :o].include?(token)
+ if self.class.is_token?(token)
if winners.has_key?(token)
winners[token] << details
else
diff --git a/spec/board_spec.rb b/spec/board_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/board_spec.rb
+++ b/spec/board_spec.rb
@@ -31,6 +31,21 @@ module TTT
end
end
+ describe 'Board#token?' do
+
+ it 'returns true for :x' do
+ Board.is_token?(:x).must_equal true
+ end
+
+ it 'returns true for :o' do
+ Board.is_token?(:o).must_equal true
+ end
+
+ it 'return false if the argument is neither :x nor :o' do
+ Board.is_token?(:neither_x_nor_o).must_equal false
+ end
+ end
+
let(:board) { Board.new }
describe '#empty?' do
|
Add Board#is_token? to help classify tokens, i.e. :x and :o
|
dwayne_xo
|
train
|
117e4f6f3de14b6a20832b02c874fc003ef6ca9b
|
diff --git a/pkg/build/controller/controller.go b/pkg/build/controller/controller.go
index <HASH>..<HASH> 100644
--- a/pkg/build/controller/controller.go
+++ b/pkg/build/controller/controller.go
@@ -128,11 +128,6 @@ func (bc *BuildController) nextBuildPhase(build *buildapi.Build) error {
}
build.Status.OutputDockerImageReference = ref
- // Set the build phase, which will be persisted if no error occurs.
- build.Status.Phase = buildapi.BuildPhasePending
- build.Status.Reason = ""
- build.Status.Message = ""
-
// Make a copy to avoid mutating the build from this point on.
copy, err := kapi.Scheme.Copy(build)
if err != nil {
@@ -164,6 +159,7 @@ func (bc *BuildController) nextBuildPhase(build *buildapi.Build) error {
if _, err := bc.PodManager.CreatePod(build.Namespace, podSpec); err != nil {
if errors.IsAlreadyExists(err) {
+ bc.Recorder.Eventf(build, "failedCreate", "Pod already exists: %s/%s", podSpec.Namespace, podSpec.Name)
glog.V(4).Infof("Build pod already existed: %#v", podSpec)
return nil
}
@@ -174,6 +170,11 @@ func (bc *BuildController) nextBuildPhase(build *buildapi.Build) error {
}
glog.V(4).Infof("Created pod for build: %#v", podSpec)
+
+ // Set the build phase, which will be persisted.
+ build.Status.Phase = buildapi.BuildPhasePending
+ build.Status.Reason = ""
+ build.Status.Message = ""
return nil
}
diff --git a/pkg/build/controller/controller_test.go b/pkg/build/controller/controller_test.go
index <HASH>..<HASH> 100644
--- a/pkg/build/controller/controller_test.go
+++ b/pkg/build/controller/controller_test.go
@@ -186,6 +186,7 @@ func TestHandleBuild(t *testing.T) {
imageClient imageStreamClient
podManager podManager
outputSpec string
+ errExpected bool
}
tests := []handleBuildTest{
@@ -251,7 +252,7 @@ func TestHandleBuild(t *testing.T) {
},
{ // 6
inStatus: buildapi.BuildPhaseNew,
- outStatus: buildapi.BuildPhaseError,
+ outStatus: buildapi.BuildPhaseNew,
buildStrategy: &errStrategy{},
buildOutput: buildapi.BuildOutput{
To: &kapi.ObjectReference{
@@ -259,10 +260,11 @@ func TestHandleBuild(t *testing.T) {
Name: "repository/dataBuild",
},
},
+ errExpected: true,
},
{ // 7
inStatus: buildapi.BuildPhaseNew,
- outStatus: buildapi.BuildPhaseError,
+ outStatus: buildapi.BuildPhaseNew,
podManager: &errPodManager{},
buildOutput: buildapi.BuildOutput{
To: &kapi.ObjectReference{
@@ -270,10 +272,11 @@ func TestHandleBuild(t *testing.T) {
Name: "repository/dataBuild",
},
},
+ errExpected: true,
},
{ // 8
inStatus: buildapi.BuildPhaseNew,
- outStatus: buildapi.BuildPhasePending,
+ outStatus: buildapi.BuildPhaseNew,
podManager: &errExistsPodManager{},
buildOutput: buildapi.BuildOutput{
To: &kapi.ObjectReference{
@@ -318,7 +321,7 @@ func TestHandleBuild(t *testing.T) {
},
{ // 12
inStatus: buildapi.BuildPhaseNew,
- outStatus: buildapi.BuildPhaseError,
+ outStatus: buildapi.BuildPhaseNew,
imageClient: &errNotFoundImageStreamClient{},
buildOutput: buildapi.BuildOutput{
To: &kapi.ObjectReference{
@@ -326,10 +329,11 @@ func TestHandleBuild(t *testing.T) {
Name: "foo:tag",
},
},
+ errExpected: true,
},
{ // 13
inStatus: buildapi.BuildPhaseNew,
- outStatus: buildapi.BuildPhaseError,
+ outStatus: buildapi.BuildPhaseNew,
imageClient: &errImageStreamClient{},
buildOutput: buildapi.BuildOutput{
To: &kapi.ObjectReference{
@@ -337,6 +341,7 @@ func TestHandleBuild(t *testing.T) {
Name: "foo:tag",
},
},
+ errExpected: true,
},
{ // 14
inStatus: buildapi.BuildPhaseNew,
@@ -382,14 +387,11 @@ func TestHandleBuild(t *testing.T) {
// ensure we return an error for cases where expected output is an error.
// these will be retried by the retrycontroller
- if tc.inStatus != buildapi.BuildPhaseError && tc.outStatus == buildapi.BuildPhaseError {
- if err == nil {
- t.Errorf("(%d) Expected an error from HandleBuild, got none!", i)
- }
- continue
+ if tc.errExpected && err == nil {
+ t.Errorf("(%d) Expected an error from HandleBuild, got none!", i)
}
- if err != nil {
+ if !tc.errExpected && err != nil {
t.Errorf("(%d) Unexpected error %v", i, err)
}
if build.Status.Phase != tc.outStatus {
|
Build controller - set build status only if pod creation succeeds
|
openshift_origin
|
train
|
3d81867aff7ac6c8ca2da8211bdadcd16d496a73
|
diff --git a/packages/ember-routing/lib/system/route.js b/packages/ember-routing/lib/system/route.js
index <HASH>..<HASH> 100644
--- a/packages/ember-routing/lib/system/route.js
+++ b/packages/ember-routing/lib/system/route.js
@@ -1228,9 +1228,8 @@ var Route = EmberObject.extend(ActionHandler, {
@return {Object} the model object
*/
modelFor: function(name) {
-
var route = this.container.lookup('route:' + name),
- transition = this.router.router.activeTransition;
+ transition = this.router ? this.router.router.activeTransition : null;
// If we are mid-transition, we want to try and look up
// resolved parent contexts on the current transitionEvent.
diff --git a/packages/ember-routing/tests/system/route_test.js b/packages/ember-routing/tests/system/route_test.js
index <HASH>..<HASH> 100644
--- a/packages/ember-routing/tests/system/route_test.js
+++ b/packages/ember-routing/tests/system/route_test.js
@@ -130,6 +130,22 @@ test("'store' does not need to be injected", function() {
ok(true, 'no error was raised');
});
+test("modelFor doesn't require the router", function() {
+ var container = new Container();
+ route.container = container;
+
+ var foo = { name: 'foo' };
+
+ var fooRoute = EmberRoute.extend({
+ container: container,
+ currentModel: foo
+ });
+
+ container.register('route:foo', fooRoute);
+
+ equal(route.modelFor('foo'), foo);
+});
+
QUnit.module("Ember.Route serialize", {
setup: createRoute,
teardown: cleanupRoute
|
[BUGFIX beta] Route#modelFor shouldn't rely on router
This is especially useful for unit testing. In cases where
there is no router, `modelFor` will no longer cause an exception.
|
emberjs_ember.js
|
train
|
143330a65094bf0fc229986b1407fc3ac9d67b66
|
diff --git a/cmd/config_diff_table.go b/cmd/config_diff_table.go
index <HASH>..<HASH> 100644
--- a/cmd/config_diff_table.go
+++ b/cmd/config_diff_table.go
@@ -33,8 +33,8 @@ func (t ConfigDiffTable) Print() {
}
result := []boshtbl.Value{
- boshtbl.NewValueString(formatId(t.opts.FromID)),
- boshtbl.NewValueString(formatId(t.opts.ToID)),
+ boshtbl.NewValueString(t.opts.FromID),
+ boshtbl.NewValueString(t.opts.ToID),
boshtbl.NewValueString(t.diff.String()),
}
@@ -42,10 +42,3 @@ func (t ConfigDiffTable) Print() {
t.ui.PrintTable(table)
}
-
-func formatId(id string) string {
- if id == "" {
- return "-"
- }
- return id
-}
diff --git a/cmd/config_diff_table_test.go b/cmd/config_diff_table_test.go
index <HASH>..<HASH> 100644
--- a/cmd/config_diff_table_test.go
+++ b/cmd/config_diff_table_test.go
@@ -31,61 +31,34 @@ var _ = Describe("DiffConfigTable", func() {
})
Describe("Print", func() {
- Context("when FromID and ToID are specified", func() {
- It("shows diff config as transposed table", func() {
- NewConfigDiffTable(diff, opts, ui).Print()
-
- Expect(ui.Table).To(Equal(
- boshtbl.Table{
- Content: "",
-
- Header: []boshtbl.Header{
- boshtbl.NewHeader("From ID"),
- boshtbl.NewHeader("To ID"),
- boshtbl.NewHeader("Diff"),
- },
-
- Rows: [][]boshtbl.Value{
- {
- boshtbl.NewValueString("1"),
- boshtbl.NewValueString("2"),
- boshtbl.NewValueString(" some line that stayed\n+ some line that was added\n- some line that was removed\n"),
- },
+ It("shows diff config as transposed table", func() {
+ NewConfigDiffTable(diff, opts, ui).Print()
+
+ Expect(ui.Table).To(Equal(
+ boshtbl.Table{
+ Content: "",
+
+ Header: []boshtbl.Header{
+ boshtbl.NewHeader("From ID"),
+ boshtbl.NewHeader("To ID"),
+ boshtbl.NewHeader("Diff"),
+ },
+
+ Rows: [][]boshtbl.Value{
+ {
+ boshtbl.NewValueString("1"),
+ boshtbl.NewValueString("2"),
+ boshtbl.NewValueString(" some line that stayed\n+ some line that was added\n- some line that was removed\n"),
},
+ },
- Notes: []string{},
+ Notes: []string{},
- FillFirstColumn: true,
+ FillFirstColumn: true,
- Transpose: true,
- }))
- })
+ Transpose: true,
+ }))
})
-
- Context("when FromID is not specified in the response", func() {
- optsWithoutFromID := DiffConfigOpts{
- ToID: "2",
- }
- It("marks From ID with -", func() {
- NewConfigDiffTable(diff, optsWithoutFromID, ui).Print()
-
- fromIdContent := ui.Table.Rows[0][0].String()
- Expect(fromIdContent).To(Equal("-"))
- })
- })
-
- Context("when ToID is not specified in the response", func() {
- optsWithoutToID := DiffConfigOpts{
- FromID: "1",
- }
- It("marks To ID with -", func() {
- NewConfigDiffTable(diff, optsWithoutToID, ui).Print()
-
- toIdContent := ui.Table.Rows[0][1].String()
- Expect(toIdContent).To(Equal("-"))
- })
- })
-
})
})
|
Remove unnecessary empty id rendering in diff-config
|
cloudfoundry_bosh-cli
|
train
|
8fe6d56bf7ae0dae00c29237fd7101931ab8ff2f
|
diff --git a/thredds_crawler/crawl.py b/thredds_crawler/crawl.py
index <HASH>..<HASH> 100644
--- a/thredds_crawler/crawl.py
+++ b/thredds_crawler/crawl.py
@@ -28,7 +28,6 @@ except ImportError:
def emit(self, record):
pass
logger = logging.getLogger("thredds_crawler")
-logger.addHandler(NullHandler())
def request_xml(url):
@@ -66,6 +65,8 @@ class Crawl(object):
formatter = logging.Formatter('%(asctime)s - [%(levelname)s] %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
+ else:
+ logger.addHandler(NullHandler())
# Only process these dataset IDs
if select is not None:
|
Don't swallow logging during testing
|
ioos_thredds_crawler
|
train
|
b3220cf3e8ff6d8b55ea0056238d022073bc0e97
|
diff --git a/src/body/Body.js b/src/body/Body.js
index <HASH>..<HASH> 100644
--- a/src/body/Body.js
+++ b/src/body/Body.js
@@ -20,6 +20,7 @@ var Common = require('../core/Common');
var Bounds = require('../geometry/Bounds');
var Axes = require('../geometry/Axes');
+
(function() {
Body._inertiaScale = 4;
@@ -82,7 +83,22 @@ var Axes = require('../geometry/Axes');
yOffset: 0
},
lineWidth: 0
- }
+ },
+
+ events: null,
+ bounds: null,
+ chamfer: null,
+ circleRadius: 0,
+ positionPrev: null,
+ anglePrev: 0,
+ parent: null,
+
+ axes: null,
+ area: 0,
+ mass: 0,
+ inertia: 0,
+
+ _original: null
};
var body = Common.extend(defaults, options);
@@ -166,24 +182,18 @@ var Axes = require('../geometry/Axes');
* Prefer to use the actual setter functions in performance critical situations.
* @method set
* @param {body} body
- * @param {} settings A property name (or map of properties and values) to set on the body.
- * @param {} value The value to set if `settings` is a single property name.
+ * @param {object} settings A map of properties and values to set on the body.
*/
- Body.set = function(body, settings, value) {
- var property;
-
- if (typeof settings === 'string') {
- property = settings;
- settings = {};
- settings[property] = value;
- }
+ Body.set = function(body, settings) {
+ var property,
+ value;
for (property in settings) {
- value = settings[property];
if (!settings.hasOwnProperty(property))
continue;
+ value = settings[property];
switch (property) {
case 'isStatic':
@@ -269,7 +279,7 @@ var Axes = require('../geometry/Axes');
part.inverseMass = part._original.inverseMass;
part.inverseInertia = part._original.inverseInertia;
- delete part._original;
+ part._original = null;
}
}
};
|
Optimized Body's hidden class
|
liabru_matter-js
|
train
|
02c7c8451c331b0206a9db2fb50360cd44618efa
|
diff --git a/src/Core/Form/View/Helper/SummaryForm.php b/src/Core/Form/View/Helper/SummaryForm.php
index <HASH>..<HASH> 100644
--- a/src/Core/Form/View/Helper/SummaryForm.php
+++ b/src/Core/Form/View/Helper/SummaryForm.php
@@ -245,7 +245,33 @@ class SummaryForm extends AbstractHelper
if ('' != $elementValue && $element instanceof \Zend\Form\Element\Select) {
$options = $element->getValueOptions();
- $elementValue = $this->getTranslator()->translate($options[$elementValue]);
+ $translator = $this->getTranslator();
+ if (true == $element->getAttribute('multiple')) {
+
+ $multiOptions = [];
+ foreach ($elementValue as $optionKey) {
+ if (isset($options[$optionKey])) {
+ $multiOptions['__general__'][] = $translator->translate($options[$optionKey]);
+ continue;
+ }
+
+ foreach ($options as $optKey => $optVal) {
+ if (!is_array($optVal) || !array_key_exists($optionKey, $optVal['options'])) { continue; }
+
+ $optGroupLabel = isset($optVal['label']) ? $translator->translate($optVal['label']) : $optKey;
+ $multiOptions[$optGroupLabel][] = $translator->translate($optVal['options'][$optionKey]);
+ }
+ }
+
+ $elementValue = [];
+ foreach ($multiOptions as $optGroupLabel => $vals) {
+ $elementValue[] = "<b>$optGroupLabel</b><br>" . join(', ', $vals);
+ }
+ $elementValue = join('<br>', $elementValue) . '<br>';
+
+ } else {
+ $elementValue = $translator->translate($options[$elementValue]);
+ }
}
if ('' != $elementValue && $element instanceOf \Zend\Form\Element\File) {
|
[Core] Improves summary view of summary form. Handles select elements with "multiple" attribute.
|
yawik_core
|
train
|
6bce73887147753383c5e526b86a4afe43ec1dea
|
diff --git a/worker/lease/manager.go b/worker/lease/manager.go
index <HASH>..<HASH> 100644
--- a/worker/lease/manager.go
+++ b/worker/lease/manager.go
@@ -314,11 +314,19 @@ func (manager *Manager) retryingClaim(claim claim) {
manager.config.Logger.Warningf("[%s] retrying timed out while handling claim %q for %q",
manager.logContext, claim.leaseKey, claim.holderName)
case lease.IsInvalid(err):
- // we want to see this, but it doesn't indicate something a user
+ // We want to see this, but it doesn't indicate something a user
// can do something about.
manager.config.Logger.Infof("[%s] got %v after %d retries, denying claim %q for %q",
manager.logContext, err, maxRetries, claim.leaseKey, claim.holderName)
claim.respond(lease.ErrClaimDenied)
+ case lease.IsHeld(err):
+ // This can happen in HA if the original check for an extant lease
+ // (against the local node) returned nothing, but the leader FSM
+ // has this lease being held by another entity.
+ manager.config.Logger.Tracef(
+ "[%s] %s asked for lease %s, held by by another entity; local Raft node may syncing",
+ manager.logContext, claim.holderName, claim.leaseKey.Lease)
+ claim.respond(lease.ErrClaimDenied)
default:
// Stop the main loop because we got an abnormal error
manager.catacomb.Kill(errors.Trace(err))
|
Modifies the lease manager to handle the specific error from the FSM,
for a lease claim that is held by another entity. In this case we reject
the claim without retrying.
Previously errors like these were returned as invalid, which would
trigger subsequent retries. We know this lease will not be granted, so
retries are wasteful.
|
juju_juju
|
train
|
520724e87af10c5c20eb478cff23e47f4bfbe5af
|
diff --git a/src/main/groovy/lang/Closure.java b/src/main/groovy/lang/Closure.java
index <HASH>..<HASH> 100644
--- a/src/main/groovy/lang/Closure.java
+++ b/src/main/groovy/lang/Closure.java
@@ -535,6 +535,14 @@ public abstract class Closure extends GroovyObjectSupport implements Cloneable,
public Closure curry(final Object arguments[]) {
return (new CurriedClosure(this,arguments)).asWritable();
}
+
+ public void setResolveStrategy(int resolveStrategy) {
+ Closure.this.setResolveStrategy(resolveStrategy);
+ }
+
+ public int getResolveStrategy() {
+ return Closure.this.getResolveStrategy();
+ }
}
/**
|
let WritableClosure proxy resolve strategy access to the outer Closure.
git-svn-id: <URL>
|
groovy_groovy-core
|
train
|
02884309b5142224bc9e017245369f8502442744
|
diff --git a/lib/ideone.rb b/lib/ideone.rb
index <HASH>..<HASH> 100644
--- a/lib/ideone.rb
+++ b/lib/ideone.rb
@@ -33,7 +33,7 @@ module Ideone
request_body[:run] = run
request_body[:private] = is_private
- response = call_request(:create_submission, :message => @request_body)
+ response = call_request(:create_submission)
return response.to_hash[:create_submission_response][:return][:item][1][:value]
end
@@ -42,7 +42,7 @@ module Ideone
request_body = @request_body
request_body[:link] = link
- response = call_request(:get_submission_status, :message => request_body)
+ response = call_request(:get_submission_status)
status = response.to_hash[:get_submission_status_response][:return][:item][1][:value].to_i
result = response.to_hash[:get_submission_status_response][:return][:item][2][:value].to_i
@@ -78,7 +78,7 @@ module Ideone
# Get a list of supported languages and cache it.
def languages
unless @languages_cache
- response = call_request(:get_languages, :message => @request_body)
+ response = call_request(:get_languages)
languages = response.to_hash[:get_languages_response][:return][:item][1][:value][:item]
# Create a sorted hash
@@ -89,7 +89,7 @@ module Ideone
# A test function that always returns the same thing.
def test
- response = call_request(:test_function, :message => @request_body)
+ response = call_request(:test_function)
items = response.to_hash[:test_function_response][:return][:item]
@@ -105,9 +105,9 @@ module Ideone
end
end
- def call_request(api_endpoint, **params)
+ def call_request(api_endpoint)
begin
- response = @client.call(api_endpoint, params)
+ response = @client.call(api_endpoint, :message => @request_body)
rescue Exception => e
raise e
end
|
Fix support for Ruby <= <I>
Older ruby versions do not support keyword arguments. Updated code.
|
kennym_ideone-ruby-api
|
train
|
aed9e821d84f0cc2e9b5eaa5133eebd029d67274
|
diff --git a/src/configure/webpack/plugins/archetype-library.js b/src/configure/webpack/plugins/archetype-library.js
index <HASH>..<HASH> 100644
--- a/src/configure/webpack/plugins/archetype-library.js
+++ b/src/configure/webpack/plugins/archetype-library.js
@@ -10,7 +10,7 @@ export default {
return {
entry: './index.js',
output: {
- path: join(projectPath, 'lib'),
+ path: join(projectPath, 'dist'),
filename: 'index.js',
libraryTarget: buildTarget === 'test' ? undefined : 'commonjs2',
library
diff --git a/src/configure/webpack/plugins/archetype-library.spec.js b/src/configure/webpack/plugins/archetype-library.spec.js
index <HASH>..<HASH> 100644
--- a/src/configure/webpack/plugins/archetype-library.spec.js
+++ b/src/configure/webpack/plugins/archetype-library.spec.js
@@ -33,9 +33,9 @@ describe('configure webpack library', function () {
expect(webpackConfig.output.filename).eql('index.js')
})
- it('should have the output path configured as the lib folder', function () {
+ it('should have the output path configured as the dist folder', function () {
const webpackConfig = configure(baseConfiguration)
- expect(webpackConfig.output.path).eql(join(projectPath, 'lib'))
+ expect(webpackConfig.output.path).eql(join(projectPath, 'dist'))
})
describe('externals', function () {
|
Simplify in an initial moment and make the library output the same as pages
|
saguijs_sagui
|
train
|
ae01706f0134e5f74e3915aa7942e8b63bdeacd9
|
diff --git a/rebound/simulation.py b/rebound/simulation.py
index <HASH>..<HASH> 100644
--- a/rebound/simulation.py
+++ b/rebound/simulation.py
@@ -927,8 +927,9 @@ class reb_variational_configuration(Structure):
("index_1st_order_a", c_int),
("index_1st_order_b", c_int)]
- def vary(self, particle_index, variation, variation2=None):
- order = self.order
+ def vary(self, particle_index, variation, variation2=None, order=None):
+ if order is None:
+ order = self.order
sim = self._sim.contents
if order==0:
raise ValueError("Cannot find variation for given index. ")
|
Allow to manually override order in vary()
|
hannorein_rebound
|
train
|
57dd2acfaf95baa41bbc879ed02554b159ffee50
|
diff --git a/absl/flags/BUILD b/absl/flags/BUILD
index <HASH>..<HASH> 100644
--- a/absl/flags/BUILD
+++ b/absl/flags/BUILD
@@ -103,6 +103,7 @@ py_test(
deps = [
":_argument_parser",
"//absl/testing:absltest",
+ "@six_archive//:six",
],
)
diff --git a/absl/flags/_argument_parser.py b/absl/flags/_argument_parser.py
index <HASH>..<HASH> 100644
--- a/absl/flags/_argument_parser.py
+++ b/absl/flags/_argument_parser.py
@@ -277,7 +277,7 @@ class BooleanParser(ArgumentParser):
def parse(self, argument):
"""See base class."""
- if isinstance(argument, str):
+ if isinstance(argument, six.string_types):
if argument.lower() in ('true', 't', '1'):
return True
elif argument.lower() in ('false', 'f', '0'):
diff --git a/absl/flags/tests/_argument_parser_test.py b/absl/flags/tests/_argument_parser_test.py
index <HASH>..<HASH> 100644
--- a/absl/flags/tests/_argument_parser_test.py
+++ b/absl/flags/tests/_argument_parser_test.py
@@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-
"""Additional tests for flag argument parsers.
Most of the argument parsers are covered in the flags_test.py.
@@ -24,6 +23,8 @@ from __future__ import print_function
from absl.flags import _argument_parser
from absl.testing import absltest
+import six
+
class ArgumentParserTest(absltest.TestCase):
@@ -43,6 +44,25 @@ class ArgumentParserTest(absltest.TestCase):
parser.parse(b'')
+class BooleanParserTest(absltest.TestCase):
+
+ def setUp(self):
+ self.parser = _argument_parser.BooleanParser()
+
+ def test_parse_bytes(self):
+ if six.PY2:
+ self.assertTrue(self.parser.parse(b'true'))
+ else:
+ with self.assertRaises(ValueError):
+ self.parser.parse(b'true')
+
+ def test_parse_str(self):
+ self.assertTrue(self.parser.parse('true'))
+
+ def test_parse_unicode(self):
+ self.assertTrue(self.parser.parse(u'true'))
+
+
class FloatParserTest(absltest.TestCase):
def setUp(self):
|
Change argument parser to accept unicode boolean rhs as well as strings in Python 2.
PiperOrigin-RevId: <I>
|
abseil_abseil-py
|
train
|
761cf00b02edbfc2a6e7c9a0f98e40d6074ae207
|
diff --git a/src/java/grails/util/GrailsNameUtils.java b/src/java/grails/util/GrailsNameUtils.java
index <HASH>..<HASH> 100644
--- a/src/java/grails/util/GrailsNameUtils.java
+++ b/src/java/grails/util/GrailsNameUtils.java
@@ -121,6 +121,11 @@ public class GrailsNameUtils {
}
public static String getLogicalPropertyName(String className, String trailingName) {
+ if(!isBlank(className) && !isBlank(trailingName)) {
+ if(className.length() == trailingName.length() + 1 && className.endsWith(trailingName)) {
+ return className.substring(0, 1).toLowerCase();
+ }
+ }
return getLogicalName(getPropertyName(className), trailingName);
}
diff --git a/src/test/grails/util/GrailsNameUtilsTests.java b/src/test/grails/util/GrailsNameUtilsTests.java
index <HASH>..<HASH> 100644
--- a/src/test/grails/util/GrailsNameUtilsTests.java
+++ b/src/test/grails/util/GrailsNameUtilsTests.java
@@ -46,6 +46,11 @@ public class GrailsNameUtilsTests extends TestCase {
assertEquals("payRoll", GrailsNameUtils.getLogicalPropertyName("org.something.PayRollController", "Controller"));
}
+ public void testGetLogicalPropertyNameForArtefactWithSingleCharacterName() {
+ assertEquals("a", GrailsNameUtils.getLogicalPropertyName("AController", "Controller"));
+ assertEquals("b", GrailsNameUtils.getLogicalPropertyName("BService", "Service"));
+ }
+
public void testGetScriptName() {
assertEquals("grails-name-utils-tests", GrailsNameUtils.getScriptName(getClass()));
assertEquals("", GrailsNameUtils.getScriptName(""));
diff --git a/src/test/org/codehaus/groovy/grails/web/servlet/mvc/RedirectMethodTests.groovy b/src/test/org/codehaus/groovy/grails/web/servlet/mvc/RedirectMethodTests.groovy
index <HASH>..<HASH> 100644
--- a/src/test/org/codehaus/groovy/grails/web/servlet/mvc/RedirectMethodTests.groovy
+++ b/src/test/org/codehaus/groovy/grails/web/servlet/mvc/RedirectMethodTests.groovy
@@ -167,11 +167,10 @@ class UrlMappings {
}
void testRedirectInControllerWithOneLetterClassName() {
- if(notYetImplemented()) return
def c = ga.getControllerClass("AController").newInstance()
webRequest.controllerName = 'a'
c.index.call()
- assertEquals "/test/a/list", response.redirectedUrl
+ assertEquals "/a/list", response.redirectedUrl
}
void testRedirectToAction() {
|
GRAILS-<I> - improve the handling of logical property names for artifacts with single letter names (AController, BService etc...)
|
grails_grails-core
|
train
|
f007b124864ab8b733aef6c98bfbc3a2d94fcfd0
|
diff --git a/scripts/gulp-tasks/release.js b/scripts/gulp-tasks/release.js
index <HASH>..<HASH> 100644
--- a/scripts/gulp-tasks/release.js
+++ b/scripts/gulp-tasks/release.js
@@ -58,37 +58,45 @@ gulp.task('gitPush', (done) => {
/**
* Bump Prerelease Task
*/
-gulp.task('bump:prerelease', () => {
+gulp.task('bump:prerelease', (done) => {
gulp.src(packageFilePath)
.pipe(bump({type: 'prerelease'}))
.pipe(gulp.dest('./'))
+ .on('error', done)
+ .on('finish', done)
})
/**
* Bump Patch Task
*/
-gulp.task('bump:patch', () => {
+gulp.task('bump:patch', (done) => {
gulp.src(packageFilePath)
.pipe(bump({type: 'patch'}))
.pipe(gulp.dest('./'))
+ .on('error', done)
+ .on('finish', done)
})
/**
* Bump Minor Task
*/
-gulp.task('bump:minor', () => {
+gulp.task('bump:minor', (done) => {
gulp.src(packageFilePath)
.pipe(bump({type: 'minor'}))
.pipe(gulp.dest('./'))
+ .on('error', done)
+ .on('finish', done)
})
/**
* Bump Major Task
*/
-gulp.task('bump:major', () => {
+gulp.task('bump:major', (done) => {
gulp.src(packageFilePath)
.pipe(bump({type: 'major'}))
.pipe(gulp.dest('./'))
+ .on('error', done)
+ .on('finish', done)
})
/**
|
call missing done callback on bump tasks finishes
|
sirap-group_generate-swap-project
|
train
|
387f1c5aaf747cf266ac01e29d45a5a26e4f57f8
|
diff --git a/cmd/runhcs/main.go b/cmd/runhcs/main.go
index <HASH>..<HASH> 100644
--- a/cmd/runhcs/main.go
+++ b/cmd/runhcs/main.go
@@ -35,32 +35,23 @@ const (
specConfig = "config.json"
usage = `Open Container Initiative runtime
-runc is a command line client for running applications packaged according to
-the Open Container Initiative (OCI) format and is a compliant implementation of the
-Open Container Initiative specification.
+runhcs is a is a modified version of runc modified to run on Windows with Hyper-V isolated containers. Much like runc, it is a command line client for running applications packaged according to the Open Container Initiative (OCI) format and is a compliant implementation of the Open Container Initiative specification.
-runc integrates well with existing process supervisors to provide a production
-container runtime environment for applications. It can be used with your
-existing process monitoring tools and the container will be spawned as a
-direct child of the process supervisor.
+runhcs integrates well with existing process supervisors to provide a production container runtime environment for applications. It can be used with your existing process monitoring tools and the container will be spawned as a direct child of the process supervisor.
-Containers are configured using bundles. A bundle for a container is a directory
-that includes a specification file named "` + specConfig + `" and a root filesystem.
+Containers are configured using bundles. A bundle for a container is a directory that includes a specification file named "` + specConfig + `" and a root filesystem.
The root filesystem contains the contents of the container.
To start a new instance of a container:
- # runc run [ -b bundle ] <container-id>
+ # runhcs run [ -b bundle ] <container-id>
-Where "<container-id>" is your name for the instance of the container that you
-are starting. The name you provide for the container instance must be unique on
-your host. Providing the bundle directory using "-b" is optional. The default
-value for "bundle" is the current directory.`
+Where "<container-id>" is your name for the instance of the container that you are starting. The name you provide for the container instance must be unique on your host. Providing the bundle directory using "-b" is optional. The default value for "bundle" is the current directory.`
)
func main() {
app := cli.NewApp()
- app.Name = "runc"
+ app.Name = "runhcs"
app.Usage = usage
var v []string
|
removed runc reference from main - this will need to be updated to reflect differences between runhcs and runc
|
Microsoft_hcsshim
|
train
|
0f8bcde86bdc8242efd6f2ad1c6ba0eec947819f
|
diff --git a/lib/block.js b/lib/block.js
index <HASH>..<HASH> 100644
--- a/lib/block.js
+++ b/lib/block.js
@@ -53,7 +53,7 @@ var Block = module.exports = function (name, config) {
Block.prototype.updateFiles = function () {
var srcFiles = this.config.src.length ? this.config.src : this.files;
var maps = grunt.file.expandMapping(srcFiles, this.config.prefix, this.config);
- var files = _.flatten(maps, 'dest');
+ var files = _.flatten(_.pluck(maps, 'dest'));
var previousIdx = _.object(this.files, _.range(this.files.length));
var currentIdx = _.object(files, _.range(files.length));
diff --git a/lib/fileprocessor.js b/lib/fileprocessor.js
index <HASH>..<HASH> 100644
--- a/lib/fileprocessor.js
+++ b/lib/fileprocessor.js
@@ -27,7 +27,7 @@ var findConfig = function (configs, name) {
* @returns {RegExp} A regular expression that can capture the file name.
*/
var getRegExp = function (template) {
- var pattern = _.template(template, fileReplace);
+ var pattern = _.template(template)(fileReplace);
pattern = pattern.replace(/\//g, '\\/');
pattern = pattern.replace(/\s+/g, '\\s*');
pattern = '\\s*' + pattern + '\\s*';
@@ -154,7 +154,7 @@ FileProcessor.prototype.processBlock = function (block) {
file = block.templateFn.call(this, file);
}
- var line = _.template(block.template, { 'file': file } );
+ var line = _.template(block.template)({ 'file': file });
lines.push(indent + line);
});
@@ -174,4 +174,4 @@ FileProcessor.prototype.replace = function (original, replacement) {
if (!!this.file.content) {
this.file.content = this.file.content.replace(original, replacement);
}
-};
\ No newline at end of file
+};
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -36,7 +36,7 @@
"grunt-bump": "0.0.13"
},
"dependencies": {
- "lodash": "~2.3.0"
+ "lodash": "^3.6.0"
},
"peerDependencies": {
"grunt": "~0.4.1"
|
Update lodash to latest version. Fix breaking lodash API changes
|
rrharvey_grunt-file-blocks
|
train
|
beede408daf19cb4628055bf2527789f2831c727
|
diff --git a/AsyncStream.php b/AsyncStream.php
index <HASH>..<HASH> 100644
--- a/AsyncStream.php
+++ b/AsyncStream.php
@@ -6,8 +6,8 @@ use Kraken\Throwable\Io\WriteException;
use Kraken\Throwable\Runtime\InvalidArgumentException;
use Kraken\Loop\LoopAwareTrait;
use Kraken\Loop\LoopInterface;
-use Kraken\Pattern\Buffer\Buffer;
-use Kraken\Pattern\Buffer\BufferInterface;
+use Kraken\Util\Buffer\Buffer;
+use Kraken\Util\Buffer\BufferInterface;
use Error;
use Exception;
diff --git a/AsyncStreamWriter.php b/AsyncStreamWriter.php
index <HASH>..<HASH> 100644
--- a/AsyncStreamWriter.php
+++ b/AsyncStreamWriter.php
@@ -6,8 +6,8 @@ use Kraken\Throwable\Io\WriteException;
use Kraken\Throwable\Runtime\InvalidArgumentException;
use Kraken\Loop\LoopAwareTrait;
use Kraken\Loop\LoopInterface;
-use Kraken\Pattern\Buffer\Buffer;
-use Kraken\Pattern\Buffer\BufferInterface;
+use Kraken\Util\Buffer\Buffer;
+use Kraken\Util\Buffer\BufferInterface;
use Error;
use Exception;
|
KRF-<I> #resolve Moved Pattern API to Util API
|
dazzle-php_stream
|
train
|
94f8b5b7e7951e62a08433c9fed5891e4982ad4c
|
diff --git a/io3d/datareaderqt.py b/io3d/datareaderqt.py
index <HASH>..<HASH> 100644
--- a/io3d/datareaderqt.py
+++ b/io3d/datareaderqt.py
@@ -95,25 +95,25 @@ class DataReaderWidget(QtGui.QWidget):
"""
if self.cache is not None:
- self.loadfiledir = self.cache.get_or_none('loadfiledir')
+ self.loadfiledir = str(self.cache.get_or_none('loadfiledir'))
if self.loadfiledir is None:
self.loadfiledir = ''
- directory=self.loadfiledir
+ directory = str(self.loadfiledir)
from PyQt4.QtGui import QFileDialog
if app:
- dcmdir = QFileDialog.getOpenFileName(
+ dcmdir = str(QFileDialog.getOpenFileName(
caption='Select Data File',
directory=directory
# ptions=QFileDialog.ShowDirsOnly,
- )
+ ))
else:
app = QApplication(sys.argv)
- dcmdir = QFileDialog.getOpenFileName(
+ dcmdir = str(QFileDialog.getOpenFileName(
caption='Select DICOM Folder',
# ptions=QFileDialog.ShowDirsOnly,
directory=directory
- )
+ ))
# pp.exec_()
app.exit(0)
if len(dcmdir) > 0:
@@ -137,7 +137,7 @@ class DataReaderWidget(QtGui.QWidget):
# if :
# directory = self.oseg.input_datapath_start
if self.cache is not None:
- self.loaddir = self.cache.get_or_none('loaddir')
+ self.loaddir = str(self.cache.get_or_none('loaddir'))
if self.loaddir is None:
self.loaddir = ''
@@ -146,18 +146,18 @@ class DataReaderWidget(QtGui.QWidget):
from PyQt4.QtGui import QFileDialog
if app:
- dcmdir = QFileDialog.getExistingDirectory(
+ dcmdir = str(QFileDialog.getExistingDirectory(
caption='Select DICOM Folder',
options=QFileDialog.ShowDirsOnly,
directory=directory
- )
+ ))
else:
app = QApplication(sys.argv)
- dcmdir = QFileDialog.getExistingDirectory(
+ dcmdir = str(QFileDialog.getExistingDirectory(
caption='Select DICOM Folder',
options=QFileDialog.ShowDirsOnly,
directory=directory
- )
+ ))
# pp.exec_()
app.exit(0)
if len(dcmdir) > 0:
|
fix qt gui: bytes to str
|
mjirik_io3d
|
train
|
338279f1dcc7e5fbbed0ac5b9ba428decbff1551
|
diff --git a/tests/test_normalize.py b/tests/test_normalize.py
index <HASH>..<HASH> 100644
--- a/tests/test_normalize.py
+++ b/tests/test_normalize.py
@@ -21,53 +21,53 @@ normalize_vcf_no_trim = partial(normalize_seq, mode=NormalizationMode.VCF, trim=
@pytest.mark.parametrize('normalize_trim', [normalize_trim, normalize_trim_no_shuffle])
-def test_trim(normalize_trim):
+def test_trim(normalize_fn):
"""Should trim common prefix and suffix when trim=True."""
- assert ((25, 25), ("", "AC")) == normalize_trim(
+ assert ((25, 25), ("", "AC")) == normalize_fn(
interval=(22, 25), alleles=(None, "AGCAC")
)
- assert ((24, 25), ("C", "", "CAC")) == normalize_trim(
+ assert ((24, 25), ("C", "", "CAC")) == normalize_fn(
interval=(22, 25), alleles=(None, "AG", "AGCAC")
)
- assert ((23, 24), ("G", "", "GCA")) == normalize_trim(
+ assert ((23, 24), ("G", "", "GCA")) == normalize_fn(
interval=(22, 25), alleles=(None, "AC", "AGCAC")
)
- assert ((22, 24), ("AG", "G", "AGCA")) == normalize_trim(
+ assert ((22, 24), ("AG", "G", "AGCA")) == normalize_fn(
interval=(22, 25), alleles=(None, "GC", "AGCAC")
)
@pytest.mark.parametrize('normalize_trim', [normalize_trim, normalize_trim_no_shuffle])
-def test_anchor(normalize_trim):
- assert ((23, 25), ("GC", "")) == normalize_trim(
+def test_anchor(normalize_fn):
+ assert ((23, 25), ("GC", "")) == normalize_fn(
interval=(22, 25), alleles=(None, "A"), anchor_length=0
)
- assert ((22, 26), ("AGCA", "AA")) == normalize_trim(
+ assert ((22, 26), ("AGCA", "AA")) == normalize_fn(
interval=(22, 25), alleles=(None, "A"), anchor_length=1
)
- assert ((21, 27), ("CAGCAG", "CAAG")) == normalize_trim(
+ assert ((21, 27), ("CAGCAG", "CAAG")) == normalize_fn(
interval=(22, 25), alleles=(None, "A"), anchor_length=2
)
# off the left
- assert ((1, 1), ("", "C")) == normalize_trim(
+ assert ((1, 1), ("", "C")) == normalize_fn(
interval=(1, 1), alleles=(None, "C"), anchor_length=0
)
- assert ((0, 2), ("CC", "CCC")) == normalize_trim(
+ assert ((0, 2), ("CC", "CCC")) == normalize_fn(
interval=(1, 1), alleles=(None, "C"), anchor_length=1
)
- assert ((0, 3), ("CCC", "CCCC")) == normalize_trim(
+ assert ((0, 3), ("CCC", "CCCC")) == normalize_fn(
interval=(1, 1), alleles=(None, "C"), anchor_length=2
)
# off the right
- assert ((28, 28), ("", "C")) == normalize_trim(
+ assert ((28, 28), ("", "C")) == normalize_fn(
interval=(28, 28), alleles=(None, "C"), anchor_length=0
)
- assert ((27, 29), ("CA", "CCA")) == normalize_trim(
+ assert ((27, 29), ("CA", "CCA")) == normalize_fn(
interval=(28, 28), alleles=(None, "C"), anchor_length=1
)
- assert ((26, 29), ("GCA", "GCCA")) == normalize_trim(
+ assert ((26, 29), ("GCA", "GCCA")) == normalize_fn(
interval=(28, 28), alleles=(None, "C"), anchor_length=2
)
@@ -140,10 +140,10 @@ def test_input_alleles_not_modified():
@pytest.mark.parametrize('normalize_trim', [normalize_trim, normalize_trim_no_shuffle])
-def test_error_distinct(normalize_trim):
+def test_error_distinct(normalize_fn):
"""Must have at least two distinct allele sequences (incl. ref) to normalize"""
with pytest.raises(ValueError):
- normalize_trim(interval=(22, 25), alleles=(None, "AGC"))
+ normalize_fn(interval=(22, 25), alleles=(None, "AGC"))
def test_error_ref_allele():
|
don't overload outer fn
|
biocommons_bioutils
|
train
|
d3974d1b54d402f0fb2af16e68bdc8b4637bea49
|
diff --git a/lib/pseudohiki/markdownformat.rb b/lib/pseudohiki/markdownformat.rb
index <HASH>..<HASH> 100644
--- a/lib/pseudohiki/markdownformat.rb
+++ b/lib/pseudohiki/markdownformat.rb
@@ -90,6 +90,7 @@ module PseudoHiki
formatter[EmNode] = EmNodeFormatter.new(formatter, options)
formatter[StrongNode] = StrongNodeFormatter.new(formatter, options)
formatter[DelNode] = DelNodeFormatter.new(formatter, options)
+ formatter[LiteralNode] = LiteralNodeFormatter.new(formatter, options)
# formatter[PluginNode] = PluginNodeFormatter.new(formatter, options)
# formatter[DescLeaf] = DescLeafFormatter.new(formatter, options)
# formatter[TableCellNode] = TableCellNodeFormatter.new(formatter, options)
@@ -184,6 +185,12 @@ module PseudoHiki
end
end
+ class LiteralNodeFormatter < self
+ def visit(tree)
+ "`#{super(tree).join.strip}`"
+ end
+ end
+
# class PluginNodeFormatter < self; end
# class DescLeafFormatter < self; end
# class TableCellNodeFormatter < self; end
diff --git a/test/test_markdownformat.rb b/test/test_markdownformat.rb
index <HASH>..<HASH> 100644
--- a/test/test_markdownformat.rb
+++ b/test/test_markdownformat.rb
@@ -85,6 +85,12 @@ IMAGE
assert_equal("a ~~striked out string~~#{$/}", @formatter.format(tree).to_s)
end
+ def test_literal
+ text = "a ``literal`` word"
+ tree = BlockParser.parse(text.lines.to_a)
+ assert_equal("a `literal` word#{$/}", @formatter.format(tree).to_s)
+ end
+
def test_hr
text = "----#{$/}"
md_text = "----#{$/}"
|
MarkDownFormat supports the notation for inline literals.
|
nico-hn_PseudoHikiParser
|
train
|
518680fd805f5af5e1c994d3cad34d6f6a7f0851
|
diff --git a/.gitignore b/.gitignore
index <HASH>..<HASH> 100644
--- a/.gitignore
+++ b/.gitignore
@@ -27,23 +27,14 @@ build/Release
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git-
node_modules
+bower_components
+
# Debug log from npm
npm-debug.log
-# test database
-files/sqlite
-
-# upload files
-files/upload
-files/uploads
-files/tmp
-
-# private files
-files/private
-
+files
npm-debug.log
.sql
.tmp
-node_modules
diff --git a/lib/express.js b/lib/express.js
index <HASH>..<HASH> 100644
--- a/lib/express.js
+++ b/lib/express.js
@@ -8,7 +8,6 @@ var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
-var multer = require('multer');
var themeEngine = require('./themeEngine');
var log = require('./log')();
@@ -20,7 +19,7 @@ module.exports = function initExpress(we) {
// set default vars
weExpress.use(function setDefaultVars(req, res, next) {
- req.we = we;
+ req.getWe = function getWejs() { return we };
req.context = {};
return next();
});
@@ -44,10 +43,6 @@ module.exports = function initExpress(we) {
weExpress.use(flash());
- // form body parser
- weExpress.use(multer(we.config.upload));
- //weExpress.use(require('less-middleware')(path.join(process.cwd(), 'public')));
-
// prod public folder
weExpress.use('/public', express.static(path.join(we.projectPath, 'files/public')));
diff --git a/plugin.js b/plugin.js
index <HASH>..<HASH> 100644
--- a/plugin.js
+++ b/plugin.js
@@ -2,9 +2,22 @@
* We.js plugin config
*/
+var uuid = require('node-uuid');
+var log = require('./lib/log')();
+
module.exports = function loadPlugin(projectPath, Plugin) {
var plugin = new Plugin(__dirname);
+ var imageMimeTypes = [
+ 'image/png',
+ 'image/jpg',
+ 'image/jpeg',
+ 'image/gif',
+ 'image/bmp',
+ 'image/x-icon',
+ 'image/tiff'
+ ];
+
// set plugin configs
plugin.setConfigs({
port: process.env.PORT || '3000',
@@ -12,10 +25,12 @@ module.exports = function loadPlugin(projectPath, Plugin) {
log: {
level: 'debug'
},
- upload: {
- dest: projectPath + '/files/tmp',
- rename: function (fieldname, filename) {
- return filename.replace(/\W+/g, '-').toLowerCase() + Date.now()
+ upload: {
+ file: {
+ dest: projectPath + '/files/uploads/files',
+ rename: function (fieldname, filename) {
+ return Date.now() + '_' + uuid.v1();
+ }
}
},
session: {
@@ -71,6 +86,79 @@ module.exports = function loadPlugin(projectPath, Plugin) {
},
//
+ // -- Images routes
+ //
+ 'get /api/v1/image': {
+ controller : 'image',
+ action : 'find',
+ model : 'image'
+ },
+ 'get /api/v1/image/:name?': {
+ controller : 'image',
+ action : 'findOne',
+ model : 'image'
+ },
+ // Image style thumbnail | medium | large
+ 'get /api/v1/image/:style(original|mini|thumbnail|medium|large)/:name': {
+ controller : 'image',
+ action : 'findOne',
+ model : 'image'
+ },
+ 'get /api/v1/image/:id/data': {
+ controller : 'image',
+ action : 'findOneReturnData',
+ model : 'image'
+ },
+ 'get /api/v1/image-crop/:id': {
+ controller : 'image',
+ action : 'cropImage',
+ model : 'image'
+ },
+ 'post /api/v1/image-crop/:id': {
+ controller : 'image',
+ action : 'cropImage',
+ model : 'image'
+ },
+ // upload one image
+ 'post /api/v1/image': {
+ controller : 'image',
+ action : 'create',
+ model : 'image',
+ upload: {
+ dest: projectPath + '/files/uploads/images/original',
+ rename: function (fieldname, filename) {
+ return Date.now() + '_' + uuid.v1();
+ },
+ limits: {
+ fieldNameSize: 150,
+ files: 1,
+ fileSize: 10*1000000, // 10MB
+ fieldSize: 20*1000000 // 20MB
+ },
+ onFileUploadStart: function(file) {
+ // check if file is valir on upload start
+ if (imageMimeTypes.indexOf(file.mimetype) < 0) {
+ log.debug('Image:onFileUploadStart: Invalid file type for file:', file);
+ // cancel upload on invalid type
+ return false;
+ }
+ }
+ }
+ },
+
+ // -- FILES
+
+ 'get /files': {
+ controller : 'files',
+ action : 'find'
+ },
+
+ 'post /files': {
+ controller : 'files',
+ action : 'create'
+ },
+
+ //
// - Auth routes
//
|
update image upload feature and configs
|
wejs_we-core
|
train
|
89f54046a79d85057939c8cb3d49b2cb8184d5d8
|
diff --git a/fireplace/player.py b/fireplace/player.py
index <HASH>..<HASH> 100644
--- a/fireplace/player.py
+++ b/fireplace/player.py
@@ -234,7 +234,9 @@ class Player(Entity, TargetableByAuras):
return cards[0][0]
def concede(self):
- return self.game.cheat_action(self, [Concede(self)])
+ ret = self.game.cheat_action(self, [Concede(self)])
+ self.game.check_for_end_game()
+ return ret
def fatigue(self):
return self.game.cheat_action(self, [Fatigue(self)])[0]
|
Always check for end game after Player.concede()
|
jleclanche_fireplace
|
train
|
a41b64474a242ea25380b3ce00363a13b6474ba1
|
diff --git a/source/test/network_test/test_acknowledged_messages.py b/source/test/network_test/test_acknowledged_messages.py
index <HASH>..<HASH> 100644
--- a/source/test/network_test/test_acknowledged_messages.py
+++ b/source/test/network_test/test_acknowledged_messages.py
@@ -4,6 +4,9 @@ import threading
import time
import pytest
+import sys
+sys.path.insert(1, '/volume/software/common/packages/python_acknowledged_udp/latest/lib/python2.7')
+
from os.path import realpath, dirname, join, exists, expanduser, expandvars, isdir
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
diff --git a/source/test/network_test/test_multi_clients.py b/source/test/network_test/test_multi_clients.py
index <HASH>..<HASH> 100644
--- a/source/test/network_test/test_multi_clients.py
+++ b/source/test/network_test/test_multi_clients.py
@@ -296,7 +296,7 @@ def launch_server(interacting_function_handle_server_, multiprocessing_queue_dic
import sys
sys.path.insert(1, '/volume/software/common/packages/python_acknowledged_udp/latest/lib/python2.7')
-
+
return server
diff --git a/source/test/network_test/test_non_acknowledged_messages.py b/source/test/network_test/test_non_acknowledged_messages.py
index <HASH>..<HASH> 100644
--- a/source/test/network_test/test_non_acknowledged_messages.py
+++ b/source/test/network_test/test_non_acknowledged_messages.py
@@ -4,6 +4,9 @@ import threading
import time
import pytest
+import sys
+sys.path.insert(1, '/volume/software/common/packages/python_acknowledged_udp/latest/lib/python2.7')
+
from os.path import realpath, dirname, join, exists, expanduser, expandvars, isdir
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
|
fix python_acknowledged_udp syspath
for other unit tests as well
|
DLR-RM_RAFCON
|
train
|
4ced638abcbc9a3a23d2b3e4fb638c00ed83f2d9
|
diff --git a/hecate-cql3/src/main/java/com/savoirtech/hecate/cql3/schema/CreateVerifier.java b/hecate-cql3/src/main/java/com/savoirtech/hecate/cql3/schema/CreateVerifier.java
index <HASH>..<HASH> 100644
--- a/hecate-cql3/src/main/java/com/savoirtech/hecate/cql3/schema/CreateVerifier.java
+++ b/hecate-cql3/src/main/java/com/savoirtech/hecate/cql3/schema/CreateVerifier.java
@@ -23,7 +23,7 @@ public class CreateVerifier implements SchemaVerifier {
cql.append("CREATE TABLE IF NOT EXISTS ");
cql.append(session.getLoggedKeyspace());
cql.append(".");
- cql.append(mapping.getPojoMetadata().getTableName());
+ cql.append(mapping.getTableName());
cql.append(" (");
cql.append(StringUtils.join(mapping.getFacetMappings(), ", "));
cql.append(")");
diff --git a/hecate-cql3/src/test/java/com/savoirtech/hecate/cql3/dao/def/DefaultPojoDaoTest.java b/hecate-cql3/src/test/java/com/savoirtech/hecate/cql3/dao/def/DefaultPojoDaoTest.java
index <HASH>..<HASH> 100644
--- a/hecate-cql3/src/test/java/com/savoirtech/hecate/cql3/dao/def/DefaultPojoDaoTest.java
+++ b/hecate-cql3/src/test/java/com/savoirtech/hecate/cql3/dao/def/DefaultPojoDaoTest.java
@@ -1,5 +1,11 @@
package com.savoirtech.hecate.cql3.dao.def;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
import com.google.common.collect.Sets;
import com.savoirtech.hecate.cql3.dao.PojoDao;
import com.savoirtech.hecate.cql3.entities.NestedPojo;
@@ -7,18 +13,17 @@ import com.savoirtech.hecate.cql3.entities.SimplePojo;
import com.savoirtech.hecate.cql3.test.CassandraTestCase;
import org.junit.Test;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
public class DefaultPojoDaoTest extends CassandraTestCase {
-//----------------------------------------------------------------------------------------------------------------------
-// Other Methods
-//----------------------------------------------------------------------------------------------------------------------
+ //----------------------------------------------------------------------------------------------------------------------
+ // Other Methods
+ //----------------------------------------------------------------------------------------------------------------------
@Test
public void testSave() throws Exception {
@@ -34,6 +39,19 @@ public class DefaultPojoDaoTest extends CassandraTestCase {
assertEquals(pojo.getId(), found.getId());
}
+ @Test
+ public void testSaveWithTable() throws Exception {
+ DefaultPojoDaoFactory factory = new DefaultPojoDaoFactory(connect());
+ final PojoDao<String, SimplePojo> dao = factory.createPojoDao(SimplePojo.class, "BOB");
+ final SimplePojo pojo = new SimplePojo();
+ pojo.setName("name");
+ dao.save(pojo);
+
+ final SimplePojo found = dao.findByKey(pojo.getId());
+ assertNotNull(found);
+ assertEquals("name", found.getName());
+ assertEquals(pojo.getId(), found.getId());
+ }
@Test
public void testDelete() throws Exception {
@@ -149,7 +167,6 @@ public class DefaultPojoDaoTest extends CassandraTestCase {
assertEquals("one", found.getListOfStrings().get(0));
assertEquals("two", found.getListOfStrings().get(1));
assertEquals("three", found.getListOfStrings().get(2));
-
}
@Test
@@ -165,7 +182,6 @@ public class DefaultPojoDaoTest extends CassandraTestCase {
assertEquals(2, found.getPojoList().size());
assertEquals(pojo.getPojoList().get(0), found.getPojoList().get(0));
assertEquals(pojo.getPojoList().get(1), found.getPojoList().get(1));
-
}
@Test
@@ -187,7 +203,6 @@ public class DefaultPojoDaoTest extends CassandraTestCase {
assertEquals(2, found.getPojoMap().size());
assertEquals(nested1, found.getPojoMap().get("one"));
assertEquals(nested2, found.getPojoMap().get("two"));
-
}
@Test
@@ -205,8 +220,6 @@ public class DefaultPojoDaoTest extends CassandraTestCase {
assertEquals(2, found.getPojoSet().size());
assertTrue(found.getPojoSet().contains(nested1));
assertTrue(found.getPojoSet().contains(nested2));
-
-
}
@Test
|
Make sure we use the right converter.
|
savoirtech_hecate
|
train
|
840151447d0ca673c0c2947bea91d31cec4ef321
|
diff --git a/transformers/CropTransformer.php b/transformers/CropTransformer.php
index <HASH>..<HASH> 100644
--- a/transformers/CropTransformer.php
+++ b/transformers/CropTransformer.php
@@ -33,11 +33,11 @@ class CropTransformer extends TransformerAbstract {
* @return string
*/
public function transform() {
- $options = $this->_config;
+ $config = $this->_config;
$baseWidth = $this->_width;
$baseHeight = $this->_height;
- $width = $options['width'];
- $height = $options['height'];
+ $width = $config['width'];
+ $height = $config['height'];
if (is_numeric($width) && !$height) {
$height = round(($baseHeight / $baseWidth) * $width);
@@ -49,7 +49,7 @@ class CropTransformer extends TransformerAbstract {
return null;
}
- $location = $options['location'];
+ $location = $config['location'];
$widthScale = $baseWidth / $width;
$heightScale = $baseHeight / $height;
$src_x = 0;
@@ -91,7 +91,7 @@ class CropTransformer extends TransformerAbstract {
'source_y' => $src_y,
'source_w' => $src_w,
'source_h' => $src_h,
- 'quality' => $options['quality']
+ 'quality' => $config['quality']
));
}
diff --git a/transformers/FlipTransformer.php b/transformers/FlipTransformer.php
index <HASH>..<HASH> 100644
--- a/transformers/FlipTransformer.php
+++ b/transformers/FlipTransformer.php
@@ -29,7 +29,7 @@ class FlipTransformer extends TransformerAbstract {
* @return string
*/
public function transform() {
- $options = $this->_config;
+ $config = $this->_config;
$width = $this->_width;
$height = $this->_height;
$src_x = 0;
@@ -37,7 +37,7 @@ class FlipTransformer extends TransformerAbstract {
$src_w = $width;
$src_h = $height;
- switch ($options['direction']) {
+ switch ($config['direction']) {
case self::VERTICAL:
$src_y = --$height;
$src_h = -$height;
@@ -64,7 +64,7 @@ class FlipTransformer extends TransformerAbstract {
'source_y' => $src_y,
'source_w' => $src_w,
'source_h' => $src_h,
- 'quality' => $options['quality']
+ 'quality' => $config['quality']
));
}
diff --git a/transformers/ResizeTransformer.php b/transformers/ResizeTransformer.php
index <HASH>..<HASH> 100644
--- a/transformers/ResizeTransformer.php
+++ b/transformers/ResizeTransformer.php
@@ -32,11 +32,11 @@ class ResizeTransformer extends TransformerAbstract {
* @return string
*/
public function transform() {
- $options = $this->_config;
+ $config = $this->_config;
$baseWidth = $this->_width;
$baseHeight = $this->_height;
- $width = $options['width'];
- $height = $options['height'];
+ $width = $config['width'];
+ $height = $config['height'];
$newWidth = null;
$newHeight = null;
@@ -51,15 +51,15 @@ class ResizeTransformer extends TransformerAbstract {
}
// Maintains the aspect ratio of the image
- if ($options['aspect']) {
+ if ($config['aspect']) {
$widthScale = $width / $baseWidth;
$heightScale = $height / $baseHeight;
- if (($options['mode'] == self::WIDTH && $widthScale < $heightScale) || ($options['mode'] == self::HEIGHT && $widthScale > $heightScale)) {
+ if (($config['mode'] == self::WIDTH && $widthScale < $heightScale) || ($config['mode'] == self::HEIGHT && $widthScale > $heightScale)) {
$newWidth = $width;
$newHeight = ($baseHeight * $newWidth) / $baseWidth;
- } else if (($options['mode'] == self::WIDTH && $widthScale > $heightScale) || ($options['mode'] == self::HEIGHT && $widthScale < $heightScale)) {
+ } else if (($config['mode'] == self::WIDTH && $widthScale > $heightScale) || ($config['mode'] == self::HEIGHT && $widthScale < $heightScale)) {
$newHeight = $height;
$newWidth = ($newHeight * $baseWidth) / $baseHeight;
@@ -73,7 +73,7 @@ class ResizeTransformer extends TransformerAbstract {
}
// Don't expand if we don't want it too
- if (!$options['expand']) {
+ if (!$config['expand']) {
if ($newWidth > $baseWidth) {
$newWidth = $baseWidth;
}
@@ -86,7 +86,7 @@ class ResizeTransformer extends TransformerAbstract {
return $this->process(array(
'dest_w' => $newWidth,
'dest_h' => $newHeight,
- 'quality' => $options['quality']
+ 'quality' => $config['quality']
));
}
|
Renamed $options to $config
|
ljgpartners_transit
|
train
|
edf172ffc64b7598902832046b0dc4773b9f69dd
|
diff --git a/includes/functions/functions_print_lists.php b/includes/functions/functions_print_lists.php
index <HASH>..<HASH> 100644
--- a/includes/functions/functions_print_lists.php
+++ b/includes/functions/functions_print_lists.php
@@ -1451,7 +1451,7 @@ function format_surname_list($surnames, $style, $totals, $script) {
foreach ($surns as $spfxsurn=>$indis) {
$subtotal+=count($indis);
}
- $subhtml.=' ('.$subtotal.')';
+ $subhtml.=' ('.$subtotal.')';
}
$html[]=$subhtml;
|
Non-breaking space in semicolon-separated lists.
|
fisharebest_webtrees
|
train
|
63ce49df9bb3aa6c04290121df414b7b91ea73ae
|
diff --git a/lib/tests/grouplib_test.php b/lib/tests/grouplib_test.php
index <HASH>..<HASH> 100644
--- a/lib/tests/grouplib_test.php
+++ b/lib/tests/grouplib_test.php
@@ -1562,6 +1562,8 @@ class core_grouplib_testcase extends advanced_testcase {
* Test groups_get_all_groups_for_courses() method.
*/
public function test_groups_get_all_groups_for_courses_with_courses() {
+ global $DB;
+
$this->resetAfterTest(true);
$generator = $this->getDataGenerator();
@@ -1611,6 +1613,18 @@ class core_grouplib_testcase extends advanced_testcase {
$generator->create_group_member(array('groupid' => $group9->id, 'userid' => $user1->id));
$generator->create_group_member(array('groupid' => $group9->id, 'userid' => $user2->id));
+ // The process of modifying group members changes the timemodified of the group.
+ // Refresh the group records.
+ $group1 = $DB->get_record('groups', ['id' => $group1->id]);
+ $group2 = $DB->get_record('groups', ['id' => $group2->id]);
+ $group3 = $DB->get_record('groups', ['id' => $group3->id]);
+ $group4 = $DB->get_record('groups', ['id' => $group4->id]);
+ $group5 = $DB->get_record('groups', ['id' => $group5->id]);
+ $group6 = $DB->get_record('groups', ['id' => $group6->id]);
+ $group7 = $DB->get_record('groups', ['id' => $group7->id]);
+ $group8 = $DB->get_record('groups', ['id' => $group8->id]);
+ $group9 = $DB->get_record('groups', ['id' => $group9->id]);
+
$result = groups_get_all_groups_for_courses($courses);
$assertpropertiesmatch = function($expected, $actual) {
$props = get_object_vars($expected);
|
MDL-<I> groupslib: Fix time issue in unit test
|
moodle_moodle
|
train
|
7a3fcda5ef49ac30e08ac37757233644357cb96f
|
diff --git a/core/codegen/src/main/java/org/overture/codegen/transform/LetBeStStrategy.java b/core/codegen/src/main/java/org/overture/codegen/transform/LetBeStStrategy.java
index <HASH>..<HASH> 100644
--- a/core/codegen/src/main/java/org/overture/codegen/transform/LetBeStStrategy.java
+++ b/core/codegen/src/main/java/org/overture/codegen/transform/LetBeStStrategy.java
@@ -1,10 +1,13 @@
package org.overture.codegen.transform;
+import java.util.LinkedList;
import java.util.List;
import org.overture.codegen.cgast.analysis.AnalysisException;
import org.overture.codegen.cgast.declarations.ALocalVarDeclCG;
import org.overture.codegen.cgast.expressions.PExpCG;
+import org.overture.codegen.cgast.pattern.AIdentifierPatternCG;
+import org.overture.codegen.cgast.statements.ABlockStmCG;
import org.overture.codegen.cgast.statements.PStmCG;
import org.overture.codegen.cgast.types.SSetTypeCG;
import org.overture.codegen.constants.JavaTempVarPrefixes;
@@ -28,9 +31,18 @@ public class LetBeStStrategy extends AbstractIterationStrategy
}
@Override
- public List<ALocalVarDeclCG> getOuterBlockDecls()
+ public List<ALocalVarDeclCG> getOuterBlockDecls(List<AIdentifierPatternCG> ids) throws AnalysisException
{
- return packDecl(letBeStAssistant.consSuccessVarDecl(successVarName));
+ List<ALocalVarDeclCG> outerBlockDecls = new LinkedList<ALocalVarDeclCG>();
+
+ for(AIdentifierPatternCG id : ids)
+ {
+ outerBlockDecls.add(letBeStAssistant.consIdDecl(setType, id.getName()));
+ }
+
+ outerBlockDecls.add(letBeStAssistant.consSuccessVarDecl(successVarName));
+
+ return outerBlockDecls;
}
@Override
@@ -38,6 +50,13 @@ public class LetBeStStrategy extends AbstractIterationStrategy
{
return letBeStAssistant.conForCondition(setType, iteratorName, successVarName);
}
+
+ @Override
+ public ABlockStmCG getForLoopBody(AIdentifierPatternCG id,
+ String iteratorName) throws AnalysisException
+ {
+ return letBeStAssistant.consForBodyNextElementAssigned(setType, id.getName(), iteratorName);
+ }
@Override
public List<PStmCG> getLastForLoopStms()
@@ -50,5 +69,4 @@ public class LetBeStStrategy extends AbstractIterationStrategy
{
return packStm(letBeStAssistant.consIfCheck(successVarName));
}
-
}
|
Made the 'let be st' strategy realize the new abstract iteration interface. Now the strategy explicitly declares the identifiers at the outermost level
|
overturetool_overture
|
train
|
12d02fc61895cf4f8b700e69705f76d2536cac78
|
diff --git a/service/src/main/java/org/ops4j/pax/web/service/internal/ng/Activator.java b/service/src/main/java/org/ops4j/pax/web/service/internal/ng/Activator.java
index <HASH>..<HASH> 100644
--- a/service/src/main/java/org/ops4j/pax/web/service/internal/ng/Activator.java
+++ b/service/src/main/java/org/ops4j/pax/web/service/internal/ng/Activator.java
@@ -48,9 +48,9 @@ public class Activator
m_logger.info( "Starting pax http service" );
}
m_bundleContext = bundleContext;
- createHttpServiceServer();
+ createServerController();
createHttpServiceConfigurer();
- createHttpService();
+ createHttpServiceFactory();
if( m_logger.isInfoEnabled() )
{
m_logger.info( "Started pax http service" );
@@ -73,7 +73,7 @@ public class Activator
}
}
- private void createHttpService()
+ private void createHttpServiceFactory()
{
m_httpServiceFactory = new HttpServiceFactoryImpl( m_serverController );
m_httpServiceFactoryReg = m_bundleContext.registerService(
@@ -88,7 +88,7 @@ public class Activator
configurer.configure( new SysPropsHttpServiceConfiguration() );
}
- private void createHttpServiceServer()
+ private void createServerController()
{
m_registrationsCluster = new RegistrationsClusterImpl();
m_serverController = new ServerControllerImpl( new JettyFactoryImpl(), m_registrationsCluster );
|
small refactoring for better naming of private methods
|
ops4j_org.ops4j.pax.web
|
train
|
e17d8ddbeb01a7e3eb745431d39c93661e167bbc
|
diff --git a/core/block_processor.go b/core/block_processor.go
index <HASH>..<HASH> 100644
--- a/core/block_processor.go
+++ b/core/block_processor.go
@@ -342,7 +342,7 @@ func (sm *BlockProcessor) VerifyUncles(statedb *state.StateDB, block, parent *ty
// GetBlockReceipts returns the receipts beloniging to the block hash
func (sm *BlockProcessor) GetBlockReceipts(bhash common.Hash) types.Receipts {
if block := sm.ChainManager().GetBlock(bhash); block != nil {
- return GetReceiptsFromBlock(sm.extraDb, block)
+ return GetBlockReceipts(sm.extraDb, block.Hash())
}
return nil
@@ -352,7 +352,7 @@ func (sm *BlockProcessor) GetBlockReceipts(bhash common.Hash) types.Receipts {
// where it tries to get it from the (updated) method which gets them from the receipts or
// the depricated way by re-processing the block.
func (sm *BlockProcessor) GetLogs(block *types.Block) (logs state.Logs, err error) {
- receipts := GetReceiptsFromBlock(sm.extraDb, block)
+ receipts := GetBlockReceipts(sm.extraDb, block.Hash())
if len(receipts) > 0 {
// coalesce logs
for _, receipt := range receipts {
diff --git a/core/chain_manager.go b/core/chain_manager.go
index <HASH>..<HASH> 100644
--- a/core/chain_manager.go
+++ b/core/chain_manager.go
@@ -667,6 +667,8 @@ func (self *ChainManager) InsertChain(chain types.Blocks) (int, error) {
queue[i] = ChainSplitEvent{block, logs}
queueEvent.splitCount++
}
+ PutBlockReceipts(self.extraDb, block, receipts)
+
stats.processed++
}
@@ -744,7 +746,12 @@ func (self *ChainManager) merge(oldBlock, newBlock *types.Block) error {
// insert blocks. Order does not matter. Last block will be written in ImportChain itself which creates the new head properly
self.mu.Lock()
for _, block := range newChain {
+ // insert the block in the canonical way, re-writing history
self.insert(block)
+ // write canonical receipts and transactions
+ PutTransactions(self.extraDb, block, block.Transactions())
+ PutReceipts(self.extraDb, GetBlockReceipts(self.extraDb, block.Hash()))
+
}
self.mu.Unlock()
diff --git a/core/transaction_util.go b/core/transaction_util.go
index <HASH>..<HASH> 100644
--- a/core/transaction_util.go
+++ b/core/transaction_util.go
@@ -24,7 +24,10 @@ import (
"github.com/ethereum/go-ethereum/rlp"
)
-var receiptsPre = []byte("receipts-")
+var (
+ receiptsPre = []byte("receipts-")
+ blockReceiptsPre = []byte("receipts-block-")
+)
// PutTransactions stores the transactions in the given database
func PutTransactions(db common.Database, block *types.Block, txs types.Transactions) {
@@ -85,17 +88,40 @@ func GetReceipt(db common.Database, txHash common.Hash) *types.Receipt {
return &receipt
}
-// GetReceiptFromBlock returns all receipts with the given block
-func GetReceiptsFromBlock(db common.Database, block *types.Block) types.Receipts {
- // at some point we want:
- //receipts := make(types.Receipts, len(block.Transactions()))
- // but since we need to support legacy, we can't (yet)
- var receipts types.Receipts
- for _, tx := range block.Transactions() {
- if receipt := GetReceipt(db, tx.Hash()); receipt != nil {
- receipts = append(receipts, receipt)
- }
+// GetBlockReceipts returns the receipts generated by the transactions
+// included in block's given hash.
+func GetBlockReceipts(db common.Database, hash common.Hash) types.Receipts {
+ data, _ := db.Get(append(blockReceiptsPre, hash[:]...))
+ if len(data) == 0 {
+ return nil
}
+ var receipts types.Receipts
+ err := rlp.DecodeBytes(data, &receipts)
+ if err != nil {
+ glog.V(logger.Core).Infoln("GetReceiptse err", err)
+ }
return receipts
}
+
+// PutBlockReceipts stores the block's transactions associated receipts
+// and stores them by block hash in a single slice. This is required for
+// forks and chain reorgs
+func PutBlockReceipts(db common.Database, block *types.Block, receipts types.Receipts) error {
+ rs := make([]*types.ReceiptForStorage, len(receipts))
+ for i, receipt := range receipts {
+ rs[i] = (*types.ReceiptForStorage)(receipt)
+ }
+ bytes, err := rlp.EncodeToBytes(rs)
+ if err != nil {
+ return err
+ }
+
+ hash := block.Hash()
+ err = db.Put(append(blockReceiptsPre, hash[:]...), bytes)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
|
core: during chain reorg rewrite receipts and transactions
Added PutBlockReceipts; storing receipts by blocks. Eventually this will
require pruning during some cleanup cycle. During forks the receipts by
block are used to get the new canonical receipts and transactions.
This PR fixes #<I> by rewriting transactions and receipts from the point
of where the fork occured.
|
ethereum_go-ethereum
|
train
|
c7831546a101d7ec5d66da56b3362af28fee1b3e
|
diff --git a/test/end2end_test.go b/test/end2end_test.go
index <HASH>..<HASH> 100644
--- a/test/end2end_test.go
+++ b/test/end2end_test.go
@@ -7436,6 +7436,7 @@ func (s *httpServer) start(t *testing.T, lis net.Listener) {
}
func doHTTPHeaderTest(t *testing.T, errCode codes.Code, headerFields ...[]string) {
+ t.Helper()
lis, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatalf("Failed to listen. Err: %v", err)
@@ -7445,13 +7446,13 @@ func doHTTPHeaderTest(t *testing.T, errCode codes.Code, headerFields ...[]string
headerFields: headerFields,
}
server.start(t, lis)
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
- defer cancel()
- cc, err := grpc.DialContext(ctx, lis.Addr().String(), grpc.WithInsecure())
+ cc, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure())
if err != nil {
t.Fatalf("failed to dial due to err: %v", err)
}
defer cc.Close()
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
client := testpb.NewTestServiceClient(cc)
stream, err := client.FullDuplexCall(ctx)
if err != nil {
|
test: extend RPC timeout for TestHTTPHeaderFrameErrorHandlingHTTPMode (#<I>)
This test sometimes fails with error creating stream due to
DeadlineExceeded. It's very hard to reproduce (failed twice in <I>
runs). Extend the RPC timeout in case it's too short.
|
grpc_grpc-go
|
train
|
6e9f414f514e99293e541473367603c4f86abc1b
|
diff --git a/action/edit.go b/action/edit.go
index <HASH>..<HASH> 100644
--- a/action/edit.go
+++ b/action/edit.go
@@ -90,5 +90,9 @@ func (s *Action) editor(content []byte) ([]byte, error) {
return []byte{}, fmt.Errorf("failed to read from tmpfile: %v", err)
}
+ // enforce unix line endings in the password store
+ nContent = bytes.Replace(nContent, []byte("\r\n"), []byte("\n"), -1)
+ nContent = bytes.Replace(nContent, []byte("\r"), []byte("\n"), -1)
+
return nContent, nil
}
|
Enforce UNIX style line endings in the password store
|
gopasspw_gopass
|
train
|
d32424ca421f920f7ee471dcef15e8f9d522fc8d
|
diff --git a/src/components/Tooltip/Tooltip.js b/src/components/Tooltip/Tooltip.js
index <HASH>..<HASH> 100644
--- a/src/components/Tooltip/Tooltip.js
+++ b/src/components/Tooltip/Tooltip.js
@@ -268,16 +268,18 @@ export default class Tooltip extends Component {
document.body;
handleMouse = evt => {
- const state =
- typeof evt === 'string'
- ? evt
- : { mouseover: 'over', mouseout: 'out', focus: 'over', blur: 'out' }[
- evt.type
- ];
+ const state = {
+ mouseover: 'over',
+ mouseout: 'out',
+ focus: 'over',
+ blur: 'out',
+ click: 'click',
+ }[evt.type];
const hadContextMenu = this._hasContextMenu;
this._hasContextMenu = evt.type === 'contextmenu';
if (this.props.clickToOpen) {
if (state === 'click') {
+ evt.stopPropagation();
const shouldOpen = !this.state.open;
if (shouldOpen) {
this.getTriggerPosition();
@@ -304,6 +306,7 @@ export default class Tooltip extends Component {
const key = evt.key || evt.which;
if (key === 'Enter' || key === 13 || key === ' ' || key === 32) {
+ evt.stopPropagation();
this.setState({ open: !this.state.open });
}
};
@@ -361,6 +364,8 @@ export default class Tooltip extends Component {
id={triggerId}
role="button"
tabIndex="0"
+ onClick={evt => this.handleMouse(evt)}
+ onKeyDown={evt => this.handleKeyPress(evt)}
onMouseOver={evt => this.handleMouse(evt)}
onMouseOut={evt => this.handleMouse(evt)}
onFocus={evt => this.handleMouse(evt)}
@@ -369,8 +374,6 @@ export default class Tooltip extends Component {
aria-expanded={open}
{...ariaOwnsProps}>
<Icon
- onKeyDown={this.handleKeyPress}
- onClick={() => this.handleMouse('click')}
icon={!icon && !iconName ? iconInfoGlyph : icon}
name={iconName}
description={iconDescription}
|
Make keyboard events work with Tooltip when `clickToOpen` is true, prevent clicks and keyboard events bubbling up through the dom (#<I>)
* Moved onClick/onKeyDown handlers to correct element (previously only the click handler was firing). Added stopPropagation to prevent the events bubbling up (e.g. when a tooltip is inside a button)
* Fix linting
|
carbon-design-system_carbon-components
|
train
|
70f0cd78db860b86c8a611e658e745dffa3f04fc
|
diff --git a/src/python/pants/backend/project_info/list_targets.py b/src/python/pants/backend/project_info/list_targets.py
index <HASH>..<HASH> 100644
--- a/src/python/pants/backend/project_info/list_targets.py
+++ b/src/python/pants/backend/project_info/list_targets.py
@@ -25,6 +25,8 @@ class ListSubsystem(LineOriented, GoalSubsystem):
type=bool,
default=False,
help="List only targets that provide an artifact.",
+ removal_version="2.9.0.dev0",
+ removal_hint="Filter on python distributions instead: ./pants filter --target-type=python_distribution ::\n",
)
register(
"--documented",
|
Deprecate `--list-provides` option. (#<I>)
This is pre-work for getting rid of `python_artifact` in favour of fields directly on `python_distribution`. See #<I>
|
pantsbuild_pants
|
train
|
549c1ae6808b8798b899deaa80783da79468de1c
|
diff --git a/lib/portfolio/caller.php b/lib/portfolio/caller.php
index <HASH>..<HASH> 100644
--- a/lib/portfolio/caller.php
+++ b/lib/portfolio/caller.php
@@ -315,8 +315,6 @@ abstract class portfolio_caller_base {
* and what the selected portfolio plugin supports
* will be used
* use the constants PORTFOLIO_FORMAT_*
- * if $caller is passed, that can be used for more specific guesses
- * as this function <b>must</b> be called statically.
*
* @return array list of formats
*
@@ -327,7 +325,7 @@ abstract class portfolio_caller_base {
$specific = array();
} else if (!is_array($this->supportedformats)) {
debugging(get_class($caller) . ' has set a non array value of member variable supported formats - working around but should be fixed in code');
- $specific = array($formats);
+ $specific = array($this->supportedformats);
} else {
$specific = $this->supportedformats;
}
@@ -428,27 +426,13 @@ abstract class portfolio_caller_base {
$base = $this->base_supported_formats();
if (count($base) != count($formats)
|| count($base) != count(array_intersect($base, $formats))) {
- return $this->supportedformats = portfolio_most_specific_formats($formats, $base);
+ $this->supportedformats = portfolio_most_specific_formats($formats, $base);
+ return;
}
// in the case where the button hasn't actually set anything,
// we need to run through again and resolve conflicts
- $removed = array();
- foreach ($formats as $f1key => $f1) {
- if (in_array($f1, $removed)) {
- continue;
- }
- $f1obj = portfolio_format_object($f1);
- foreach ($formats as $f2key => $f2) {
- if (in_array($f2, $removed)) {
- continue;
- }
- if ($f1obj->conflicts($f2)) {
- unset($formats[$f2key]);
- $removed[] = $f2;
- }
- }
- }
- $this->supportedformats = $formats;
+ // TODO revisit this comment - it looks to me like it's lying
+ $this->supportedformats = portfolio_most_specific_formats($formats, $formats);
}
/**
@@ -465,13 +449,19 @@ abstract class portfolio_caller_base {
return;
}
$formatobj = portfolio_format_object($format);
+ // TODO look at replacing this code with another call to
+ //$this->supportedformats = portfolio_most_specific_formats($this->supportedformats, $formats);
+ //requires testing forum, which is the only place this is implemented right now
foreach ($this->supportedformats as $key => $f) {
$f2obj = portfolio_format_object($f);
+ $class = get_class($f2obj);
+ if ($formatobj instanceof $class) {
+ unset($this->supportedformats[$key]);
+ }
if ($formatobj->conflicts($f)) {
unset($this->supportedformats[$key]);
}
- $class = get_class($f2obj);
- if ($formatobj instanceof $class) {
+ if ($f2obj->conflicts($format)) {
unset($this->supportedformats[$key]);
}
}
diff --git a/lib/portfolio/formats.php b/lib/portfolio/formats.php
index <HASH>..<HASH> 100644
--- a/lib/portfolio/formats.php
+++ b/lib/portfolio/formats.php
@@ -154,7 +154,8 @@ class portfolio_format_plainhtml extends portfolio_format_file {
}
public static function conflicts($format) {
- return ($format == PORTFOLIO_FORMAT_RICHHTML);
+ return ($format == PORTFOLIO_FORMAT_RICHHTML
+ || $format == PORTFOLIO_FORMAT_FILE);
}
}
diff --git a/lib/portfoliolib.php b/lib/portfoliolib.php
index <HASH>..<HASH> 100644
--- a/lib/portfoliolib.php
+++ b/lib/portfoliolib.php
@@ -681,14 +681,22 @@ function portfolio_most_specific_formats($specificformats, $generalformats) {
$fobj = new $allformats[$f];
foreach ($generalformats as $key => $cf) {
$cfclass = $allformats[$cf];
+ $cfobj = new $allformats[$cf];
if ($fobj instanceof $cfclass && $cfclass != get_class($fobj)) {
debugging("unsetting $key $cf because it's not specific enough ($f is better)");
unset($generalformats[$key]);
+ continue;
}
// check for conflicts
if ($fobj->conflicts($cf)) {
debugging("unsetting $key $cf because it conflicts with $f");
unset($generalformats[$key]);
+ continue;
+ }
+ if ($cfobj->conflicts($f)) {
+ debugging("unsetting $key $cf because it reverse-conflicts with $f");
+ unset($generalformats[$key]);
+ continue;
}
}
//debugging('inside loop');
diff --git a/mod/forum/locallib.php b/mod/forum/locallib.php
index <HASH>..<HASH> 100644
--- a/mod/forum/locallib.php
+++ b/mod/forum/locallib.php
@@ -126,10 +126,12 @@ class forum_portfolio_caller extends portfolio_module_caller_base {
$this->multifiles = array($this->singlefile); // copy_files workaround
}
// depending on whether there are files or not, we might have to change richhtml/plainhtml
- if (!empty($this->multifiles)) {
- $this->add_format(PORTFOLIO_FORMAT_RICHHTML);
- } else {
- $this->add_format(PORTFOLIO_FORMAT_PLAINHTML);
+ if (empty($this->attachment)) {
+ if (!empty($this->multifiles)) {
+ $this->add_format(PORTFOLIO_FORMAT_RICHHTML);
+ } else {
+ $this->add_format(PORTFOLIO_FORMAT_PLAINHTML);
+ }
}
}
|
portfolio MDL-<I> fixed broken forum attachment export
- fixed a lot of logic in the format conflict stuff
- fixed a very specific bug in forum export when exporting a single
attachment.
|
moodle_moodle
|
train
|
06f7675fad88aa51c13569dfae02a218f7d29405
|
diff --git a/src/org/ddogleg/optimization/trustregion/TrustRegionUpdateDogleg_F64.java b/src/org/ddogleg/optimization/trustregion/TrustRegionUpdateDogleg_F64.java
index <HASH>..<HASH> 100644
--- a/src/org/ddogleg/optimization/trustregion/TrustRegionUpdateDogleg_F64.java
+++ b/src/org/ddogleg/optimization/trustregion/TrustRegionUpdateDogleg_F64.java
@@ -102,14 +102,14 @@ public class TrustRegionUpdateDogleg_F64<S extends DMatrix> implements TrustRegi
direction.reshape(numberOfParameters,1);
stepGN.reshape(numberOfParameters,1);
stepCauchy.reshape(numberOfParameters,1);
- tmp0 = owner.math.createMatrix();
+ tmp0 = owner.math != null ? owner.math.createMatrix() : null;
}
@Override
public void initializeUpdate() {
// Scale the gradient vector to make it less likely to overflow/underflow
CommonOps_DDRM.divide(owner.gradient,owner.gradientNorm, direction);
- gBg = owner.math.innerProduct(direction,owner.hessian);
+ gBg = innerProductHessian(direction);
if(UtilEjml.isUncountable(gBg))
throw new OptimizationException("Uncountable. gBg="+gBg);
@@ -127,6 +127,14 @@ public class TrustRegionUpdateDogleg_F64<S extends DMatrix> implements TrustRegi
}
}
+ /**
+ * Inner product of this matrix and the hessian. In it's own function so that it can be overloaded
+ * easily.
+ */
+ protected double innerProductHessian( DMatrixRMaj v ) {
+ return owner.math.innerProduct(v,owner.hessian);
+ }
+
protected boolean solveGaussNewtonPoint(DMatrixRMaj pointGN ) {
// Compute Gauss-Newton step and make sure the input hessian isn't modified
S H;
diff --git a/src/org/ddogleg/optimization/trustregion/UnconLeastSqTrustRegionSchur_F64.java b/src/org/ddogleg/optimization/trustregion/UnconLeastSqTrustRegionSchur_F64.java
index <HASH>..<HASH> 100644
--- a/src/org/ddogleg/optimization/trustregion/UnconLeastSqTrustRegionSchur_F64.java
+++ b/src/org/ddogleg/optimization/trustregion/UnconLeastSqTrustRegionSchur_F64.java
@@ -58,7 +58,7 @@ public class UnconLeastSqTrustRegionSchur_F64
public UnconLeastSqTrustRegionSchur_F64(){
this.parameterUpdate = new SchurDogleg();
- this.math = new DummyMath();
+ this.math = null; // the math is represented completely differently here.
this.schur = new SchurComplementMath();
// Mark the hessian as null to ensure the code will blow up if a function is missed
@@ -107,7 +107,6 @@ public class UnconLeastSqTrustRegionSchur_F64
@Override
public void initialize(double[] initial, int numberOfParameters, double minimumFunctionValue) {
int M = functionResiduals.getNumOfOutputsM();
- int N = functionResiduals.getNumOfInputsN();
residuals.reshape(M,1);
super.initialize(initial, numberOfParameters, minimumFunctionValue);
@@ -151,6 +150,11 @@ public class UnconLeastSqTrustRegionSchur_F64
private class SchurDogleg extends TrustRegionUpdateDogleg_F64<DMatrixSparseCSC> {
@Override
+ protected double innerProductHessian(DMatrixRMaj v) {
+ return schur.innerProductHessian(v);
+ }
+
+ @Override
protected boolean solveGaussNewtonPoint(DMatrixRMaj pointGN) {
return schur.computeStep(gradient,pointGN);
}
@@ -185,64 +189,4 @@ public class UnconLeastSqTrustRegionSchur_F64
return residuals;
}
- /**
- * Math is hacked to integrate the schur complement
- */
- private class DummyMath implements TrustRegionBase_F64.MatrixMath<DMatrixSparseCSC> {
-
- @Override
- public double innerProduct(DMatrixRMaj v, DMatrixSparseCSC M) {
- if( M != null )
- throw new RuntimeException("Expected the hessian");
- return schur.innerProductHessian(v);
- }
-
- @Override
- public void setIdentity(DMatrixSparseCSC matrix) {
- if( matrix != null )
- throw new RuntimeException("Expected the hessian");
- // this can be ignored. Only used to initialize the hessian which is overwritten
- }
-
- @Override
- public void innerMatrixProduct(DMatrixSparseCSC A, DMatrixSparseCSC output) {
- throw new RuntimeException("What's calling this?");
- }
-
- @Override
- public void extractDiag(DMatrixSparseCSC A, double[] diag) {
- throw new RuntimeException("What's calling this?");
- }
-
- @Override
- public void divideRows(double[] scaling, DMatrixSparseCSC A) {
- throw new RuntimeException("What's calling this?");
- }
-
- @Override
- public void divideColumns(double[] scaling, DMatrixSparseCSC A) {
- throw new RuntimeException("What's calling this?");
- }
-
- @Override
- public void scaleRows(double[] scaling, DMatrixSparseCSC A) {
- throw new RuntimeException("What's calling this?");
- }
-
- @Override
- public void scaleColumns(double[] scaling, DMatrixSparseCSC A) {
- throw new RuntimeException("What's calling this?");
- }
-
- @Override
- public void multTransA(DMatrixSparseCSC A, DMatrixRMaj B, DMatrixRMaj output) {
- throw new RuntimeException("What's calling this?");
- }
-
- @Override
- public DMatrixSparseCSC createMatrix() {
- return new DMatrixSparseCSC(1,1);
- }
- }
-
}
|
- removed the dummy math class from trust region schur
|
lessthanoptimal_ddogleg
|
train
|
71b685a862f2125244e669245fc3921523f6f381
|
diff --git a/lib/gcli/ui/focus.js b/lib/gcli/ui/focus.js
index <HASH>..<HASH> 100644
--- a/lib/gcli/ui/focus.js
+++ b/lib/gcli/ui/focus.js
@@ -356,6 +356,10 @@ FocusManager.prototype._checkShow = function() {
* available inputs
*/
FocusManager.prototype._shouldShowTooltip = function() {
+ if (!this._hasFocus) {
+ return { visible: false, reason: '!hasFocus' };
+ }
+
if (eagerHelper.value === Eagerness.NEVER) {
return { visible: false, reason: 'eagerHelper !== NEVER' };
}
@@ -384,6 +388,10 @@ FocusManager.prototype._shouldShowTooltip = function() {
* available inputs
*/
FocusManager.prototype._shouldShowOutput = function() {
+ if (!this._hasFocus) {
+ return { visible: false, reason: '!hasFocus' };
+ }
+
if (this._recentOutput) {
return { visible: true, reason: 'recentOutput' };
}
|
Bug <I> (focus): Add missing checks for hasFocus
If the input element doesn't have focus then we shouldn't ever have either
the output or the hint area showing.
|
joewalker_gcli
|
train
|
5d1af6233491f0d5eb9be174eb4ad4553e819302
|
diff --git a/src/properties/class-papi-property-flexible.php b/src/properties/class-papi-property-flexible.php
index <HASH>..<HASH> 100644
--- a/src/properties/class-papi-property-flexible.php
+++ b/src/properties/class-papi-property-flexible.php
@@ -511,20 +511,22 @@ class Papi_Property_Flexible extends Papi_Property_Repeater {
}
foreach ( $value['items'] as $index => $property ) {
- // Don't show the property if it's disabled.
- if ( $property->disabled() ) {
+ $property = $this->prepare_property_for_json( $property );
+
+ if ( $property === false ) {
unset( $options->settings->items[$key]['items'][$index] );
continue;
}
- $options->settings->items[$key]['items'][$index] = clone $property->get_options();
+ $options->settings->items[$key]['items'][$index] = $property;
}
}
- ?>
- <script type="application/json" data-papi-json="<?php echo $slug; ?>_repeater_json">
- <?php echo json_encode( [$options] ); ?>
- </script>
- <?php
+
+ papi_render_html_tag( 'script', [
+ 'data-papi-json' => sprintf( '%s_repeater_json', $slug ),
+ 'type' => 'application/json',
+ json_encode( [$options] )
+ ] );
}
/**
diff --git a/src/properties/class-papi-property-repeater.php b/src/properties/class-papi-property-repeater.php
index <HASH>..<HASH> 100644
--- a/src/properties/class-papi-property-repeater.php
+++ b/src/properties/class-papi-property-repeater.php
@@ -462,6 +462,32 @@ class Papi_Property_Repeater extends Papi_Property {
}
/**
+ * Prepare property for JSON.
+ *
+ * @param Papi_Property $property
+ *
+ * @return bool|object
+ */
+ protected function prepare_property_for_json( $property ) {
+ // Only real property objects and not properties that are disabled.
+ if ( ! papi_is_property( $property ) || $property->disabled() ) {
+ return false;
+ }
+
+ $options = clone $property->get_options();
+
+ if ( isset( $options->settings->items ) ) {
+ foreach ( $options->settings->items as $index => $property ) {
+ if ( $property = $this->prepare_property_for_json( $property ) ) {
+ $options->settings->items[$index] = $property;
+ }
+ }
+ }
+
+ return $options;
+ }
+
+ /**
* Remove all repeater rows from the database.
*
* @param int $post_id
@@ -532,12 +558,14 @@ class Papi_Property_Repeater extends Papi_Property {
$options->settings->items = papi_to_array( $options->settings->items );
foreach ( $options->settings->items as $key => $value ) {
- if ( ! papi_is_property( $value ) ) {
+ $property = $this->prepare_property_for_json( $property );
+
+ if ( $property === false ) {
unset( $options->settings->items[$key] );
continue;
}
- $options->settings->items[$key] = clone $value->get_options();
+ $options->settings->items[$key] = $property;
}
papi_render_html_tag( 'script', [
|
Fix so flexible and repeaters can handle properties with children
|
wp-papi_papi
|
train
|
c1071fd3839759fb213c284a08b409f66c7ad962
|
diff --git a/core-bundle/contao/library/Contao/Controller.php b/core-bundle/contao/library/Contao/Controller.php
index <HASH>..<HASH> 100644
--- a/core-bundle/contao/library/Contao/Controller.php
+++ b/core-bundle/contao/library/Contao/Controller.php
@@ -1058,19 +1058,36 @@ abstract class Controller extends \System
*/
public static function generateFrontendUrl(array $arrRow, $strParams=null, $strForceLang=null, $blnFixDomain=false)
{
- $strRequest = '';
+ $strLanguage = '';
- if ($strParams != '')
+ if (\Config::get('addLanguageToUrl'))
{
- $arrChunks = explode('/', preg_replace('@^/@', '', $strParams));
-
- for ($i=0, $c=count($arrChunks); $i<$c; $i=($i+2))
+ if ($strForceLang != '')
+ {
+ $strLanguage = $strForceLang . '/';
+ }
+ elseif (isset($arrRow['language']) && $arrRow['type'] == 'root')
{
- $strRequest .= sprintf('&%s=%s', $arrChunks[$i], $arrChunks[($i+1)]);
+ $strLanguage = $arrRow['language'] . '/';
+ }
+ elseif (TL_MODE == 'FE')
+ {
+ /** @var \PageModel $objPage */
+ global $objPage;
+
+ $strLanguage = $objPage->rootLanguage . '/';
}
}
- $strUrl = \Environment::get('script') . '?id=' . $arrRow['id'] . $strRequest;
+ // Correctly handle the "index" alias (see #3961)
+ if ($arrRow['alias'] == 'index' && $strParams == '')
+ {
+ $strUrl = (\Config::get('rewriteURL') ? '' : \Environment::get('script') . '/') . $strLanguage;
+ }
+ else
+ {
+ $strUrl = (\Config::get('rewriteURL') ? '' : \Environment::get('script') . '/') . $strLanguage . ($arrRow['alias'] ?: $arrRow['id']) . $strParams . \Config::get('urlSuffix');
+ }
// Add the domain if it differs from the current one (see #3765 and #6927)
if ($blnFixDomain && $arrRow['domain'] != '' && $arrRow['domain'] != \Environment::get('host'))
@@ -1577,7 +1594,7 @@ abstract class Controller extends \System
$strHref = preg_replace('/(&(amp;)?|\?)file=[^&]+/', '', $strHref);
}
- $strHref .= (strpos($strHref, '?') !== false ? '&' : '?') . 'file=' . \System::urlEncode($objFiles->path);
+ $strHref .= ((\Config::get('disableAlias') || strpos($strHref, '?') !== false) ? '&' : '?') . 'file=' . \System::urlEncode($objFiles->path);
$arrMeta = \Frontend::getMetaData($objFiles->meta, $objPage->language);
|
[Core] Remove the correct part of the if-else condition in gernerateFrontendUrl()
|
contao_contao
|
train
|
b24763365b06de8310db6d58e9e46fbfd7be85ba
|
diff --git a/multiqc/modules/ngsderive/ngsderive.py b/multiqc/modules/ngsderive/ngsderive.py
index <HASH>..<HASH> 100644
--- a/multiqc/modules/ngsderive/ngsderive.py
+++ b/multiqc/modules/ngsderive/ngsderive.py
@@ -202,11 +202,9 @@ class MultiqcModule(BaseMultiqcModule):
}
self.general_stats_addcols(general_data, general_headers)
- samples = []
instruments = set()
- for s, d in general_data.items():
- samples.append(s)
+ for d in general_data.values():
instruments.update(d.get("instrument").split(" / "))
# move multiple instruments to the end if it exists
|
refactor: remove unnecessary samples var
|
ewels_MultiQC
|
train
|
115e86584c896cc139e72b5041187d6e9e0a260d
|
diff --git a/ChangeLog.txt b/ChangeLog.txt
index <HASH>..<HASH> 100644
--- a/ChangeLog.txt
+++ b/ChangeLog.txt
@@ -1,3 +1,11 @@
+2013-11-06 Version 0.7.1
+ * Fixes for bugs:
+ #118 Proxy doesn't support specifying credentials
+ #117 Service bus authorization code doesn't go through the proxy server
+ #108 Create VM, Administrator Password Base-64 Encoding
+ #106 Why isn't setup.py in the root of the project?
+ #96 Change default connection protocol to https
+
2013-07-08 Version 0.7.0
* Added service bus management API
* Added support for list blobs delimiter (for easier hierarchical listings)
diff --git a/azure/__init__.py b/azure/__init__.py
index <HASH>..<HASH> 100644
--- a/azure/__init__.py
+++ b/azure/__init__.py
@@ -26,7 +26,7 @@ from xml.sax.saxutils import escape as xml_escape
# constants
__author__ = 'Microsoft Corp. <ptvshelp@microsoft.com>'
-__version__ = '0.7.0'
+__version__ = '0.7.1'
#Live ServiceClient URLs
BLOB_SERVICE_HOST_BASE = '.blob.core.windows.net'
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -30,9 +30,17 @@ from distutils.core import setup
# python setup.py sdist upload
setup(name='azure',
- version='0.7.0',
+ version='0.7.1',
description='Windows Azure client APIs',
+ license='Apache License 2.0',
+ author='Microsoft Corporation',
+ author_email='ptvshelp@microsoft.com',
url='https://github.com/WindowsAzure/azure-sdk-for-python',
+ classifiers=[
+ 'Development Status :: 5 - Production/Stable',
+ 'Programming Language :: Python',
+ 'Programming Language :: Python :: 2.7',
+ 'License :: OSI Approved :: Apache Software License'],
packages=['azure',
'azure.http',
'azure.servicebus',
|
Updated version to <I> (bug fixes only, backwards compatible)
Updated change log
Added metadata to setup.py
|
Azure_azure-sdk-for-python
|
train
|
e8b40129f591e8111d8f5eca3d8961fc97fac770
|
diff --git a/.jshintrc b/.jshintrc
index <HASH>..<HASH> 100644
--- a/.jshintrc
+++ b/.jshintrc
@@ -19,6 +19,7 @@
"maxcomplexity" : 10,
"maxlen" : 120,
"browser" : true,
+ "debug": true,
"strict": false,
"-W040": true,
"globals": {
diff --git a/src/core/Canvas.js b/src/core/Canvas.js
index <HASH>..<HASH> 100644
--- a/src/core/Canvas.js
+++ b/src/core/Canvas.js
@@ -41,6 +41,35 @@ function Canvas(config, events, commandStack, svgFactory) {
return true;
}
});
+ commandStack.register('moveShape', {
+ do: function moveShapeDo(param) {
+ var dragCtx = param.event.dragCtx;
+ if(dragCtx) {
+ _.forEach(dragCtx.allDraggedGfx, function(gfx) {
+ var actualTMatrix = gfx.transform().local;
+ gfx.attr({
+ transform: actualTMatrix + (actualTMatrix ? 'T' : 't') + [dragCtx.dx, dragCtx.dy]
+ });
+ });
+ }
+ return true;
+ },
+ undo: function moveShapeUndo(param) {
+ var dragCtx = param.event.dragCtx;
+ if(dragCtx) {
+ _.forEach(dragCtx.allDraggedGfx, function(gfx) {
+ var actualTMatrix = gfx.transform().local;
+ gfx.attr({
+ transform: actualTMatrix + (actualTMatrix ? 'T' : 't') + [(-1)*dragCtx.dx, (-1)*dragCtx.dy]
+ });
+ });
+ }
+ return true;
+ },
+ canDo: function canUndoMoveShape() {
+ return true;
+ }
+ });
})();
/**
diff --git a/src/features/DragEvents.js b/src/features/DragEvents.js
index <HASH>..<HASH> 100644
--- a/src/features/DragEvents.js
+++ b/src/features/DragEvents.js
@@ -169,7 +169,7 @@ function Drag(events, selection, shapes, commandStack) {
events.fire('shape.dragend', event);
if (!event.isDefaultPrevented()) {
- commandStack.execute('moveshape', { event: event });
+ commandStack.execute('moveShape', { event: event });
}
}
diff --git a/src/features/services/CommandStack.js b/src/features/services/CommandStack.js
index <HASH>..<HASH> 100644
--- a/src/features/services/CommandStack.js
+++ b/src/features/services/CommandStack.js
@@ -62,6 +62,10 @@ function CommandStack() {
*/
function internalApplyAction(id, ctx, saveRedoStack) {
var commandListeners = getCommandListener(id);
+ if(!commandListeners ||
+ commandListeners.length < 1) {
+ console.warn('[CommandStack] command \'%s\' is not registered.', id);
+ }
_.forEach(commandListeners, function(commandListener) {
if(commandListener.do(ctx)) {
pushAction(id, ctx);
|
feat(canvas) implement drop
After drag end event is fired the shape now remains at the new position.
Drag and Drop is using the CommandStack service and undo is available.
|
bpmn-io_diagram-js
|
train
|
942f53ea8a207f632a2b65af3d78051663a394fb
|
diff --git a/lib/spring/client/rails.rb b/lib/spring/client/rails.rb
index <HASH>..<HASH> 100644
--- a/lib/spring/client/rails.rb
+++ b/lib/spring/client/rails.rb
@@ -20,7 +20,7 @@ module Spring
if COMMANDS.include?(command_name)
Run.call(["rails_#{command_name}", *args.drop(2)])
- elsif command_name.start_with?("db:")
+ elsif command_name&.start_with?("db:")
Run.call(["rake", *args.drop(1)])
else
require "spring/configuration"
diff --git a/test/support/acceptance_test.rb b/test/support/acceptance_test.rb
index <HASH>..<HASH> 100644
--- a/test/support/acceptance_test.rb
+++ b/test/support/acceptance_test.rb
@@ -694,6 +694,10 @@ module Spring
refute_output_includes "bin/rails runner ''", stderr: "WARN"
end
+ test "rails without arguments" do
+ assert_success "bin/rails"
+ end
+
test "rails db:migrate" do
assert_speedup do
2.times { app.run "bin/rails db:migrate" }
|
Fix check when no command is supplied
Closes #<I>.
|
rails_spring
|
train
|
15c550ec592794ef0290ff14766f5a102171dfbc
|
diff --git a/ObjJAcornCompiler.js b/ObjJAcornCompiler.js
index <HASH>..<HASH> 100644
--- a/ObjJAcornCompiler.js
+++ b/ObjJAcornCompiler.js
@@ -721,7 +721,7 @@ TryStatement: function(node, st, c) {
if (generate) {
buffer = compiler.jsBuffer;
buffer.concat(indentation);
- buffer.concat("try");
+ buffer.concat("try ");
}
indentation += indentStep;
c(node.block, st, "Statement");
@@ -733,6 +733,7 @@ TryStatement: function(node, st, c) {
name = param.name;
inner.vars[name] = {type: "catch clause", node: param};
if (generate) {
+ buffer.concat("\n");
buffer.concat(indentation);
buffer.concat("catch(");
buffer.concat(name);
@@ -745,6 +746,7 @@ TryStatement: function(node, st, c) {
}
if (node.finalizer) {
if (generate) {
+ buffer.concat("\n");
buffer.concat(indentation);
buffer.concat("finally ");
}
|
Fixed: Better format on code generated try statements
|
mrcarlberg_objj-transpiler
|
train
|
0c030d92f9d7db237b4e9916d385a05bc44495ce
|
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPass.php b/src/Symfony/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPass.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPass.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPass.php
@@ -161,16 +161,11 @@ class ResolveDefinitionTemplatesPass extends AbstractRecursivePass
foreach ($definition->getArguments() as $k => $v) {
if (is_numeric($k)) {
$def->addArgument($v);
- continue;
- }
-
- if (0 === strpos($k, 'index_')) {
- $index = (int) substr($k, strlen('index_'));
- } elseif (0 !== strpos($k, '$')) {
- throw new RuntimeException(sprintf('Invalid argument key "%s" found.', $k));
+ } elseif (0 === strpos($k, 'index_')) {
+ $def->replaceArgument((int) substr($k, strlen('index_')), $v);
+ } else {
+ $def->setArgument($k, $v);
}
-
- $def->replaceArgument($index, $v);
}
// merge properties
diff --git a/src/Symfony/Component/DependencyInjection/Definition.php b/src/Symfony/Component/DependencyInjection/Definition.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/DependencyInjection/Definition.php
+++ b/src/Symfony/Component/DependencyInjection/Definition.php
@@ -216,6 +216,13 @@ class Definition
return $this;
}
+ public function setArgument($key, $value)
+ {
+ $this->arguments[$key] = $value;
+
+ return $this;
+ }
+
/**
* Gets the arguments to pass to the service constructor/factory method.
*
diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveDefinitionTemplatesPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveDefinitionTemplatesPassTest.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveDefinitionTemplatesPassTest.php
+++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveDefinitionTemplatesPassTest.php
@@ -364,6 +364,23 @@ class ResolveDefinitionTemplatesPassTest extends TestCase
$this->assertSame('ParentClass', $def->getClass());
}
+ public function testProcessSetsArguments()
+ {
+ $container = new ContainerBuilder();
+
+ $container->register('parent', 'ParentClass')->setArguments(array(0));
+ $container->setDefinition('child', (new ChildDefinition('parent'))->setArguments(array(
+ 1,
+ 'index_0' => 2,
+ 'foo' => 3,
+ )));
+
+ $this->process($container);
+
+ $def = $container->getDefinition('child');
+ $this->assertSame(array(2, 1, 'foo' => 3), $def->getArguments());
+ }
+
protected function process(ContainerBuilder $container)
{
$pass = new ResolveDefinitionTemplatesPass();
|
[DI] Fix named args overridding
|
symfony_symfony
|
train
|
3bd02f38d2835187f88611c09e6c9355c6176b86
|
diff --git a/inspire_dojson/hep/model.py b/inspire_dojson/hep/model.py
index <HASH>..<HASH> 100644
--- a/inspire_dojson/hep/model.py
+++ b/inspire_dojson/hep/model.py
@@ -163,12 +163,20 @@ def reorder_abstracts(record, blob):
return record
+def merge_authors(record, blob):
+ authors_second = record.pop('authors_second', [])
+ record.setdefault('authors', []).extend(authors_second)
+
+ return record
+
+
hep_filters = [
add_schema('hep.json'),
add_arxiv_categories,
convert_publication_infos,
move_incomplete_publication_infos,
reorder_abstracts,
+ merge_authors,
ensure_curated,
ensure_document_type,
ensure_unique_documents_and_figures,
diff --git a/inspire_dojson/hep/rules/bd1xx.py b/inspire_dojson/hep/rules/bd1xx.py
index <HASH>..<HASH> 100644
--- a/inspire_dojson/hep/rules/bd1xx.py
+++ b/inspire_dojson/hep/rules/bd1xx.py
@@ -40,10 +40,7 @@ from ...utils import (
ORCID = re.compile('\d{4}-\d{4}-\d{4}-\d{3}[0-9Xx]')
-@hep.over('authors', '^(100|700|701)..')
-@utils.flatten
-@utils.for_each_value
-def authors(self, key, value):
+def _authors(key, value):
def _get_affiliations(value):
result = []
@@ -172,6 +169,20 @@ def authors(self, key, value):
]
+@hep.over('authors', '^100..')
+@utils.flatten
+@utils.for_each_value
+def authors(self, key, value):
+ return _authors(key, value)
+
+
+@hep.over('authors_second', '^700..', '^701..')
+@utils.flatten
+@utils.for_each_value
+def authors_second(self, key, value):
+ return _authors(key, value)
+
+
@hep2marc.over('100', '^authors$')
def authors2marc(self, key, value):
value = force_list(value)
diff --git a/tests/test_hep_bd1xx.py b/tests/test_hep_bd1xx.py
index <HASH>..<HASH> 100644
--- a/tests/test_hep_bd1xx.py
+++ b/tests/test_hep_bd1xx.py
@@ -162,6 +162,42 @@ def test_authors_from_100__a_u_w_y_and_700_a_u_w_x_y():
assert expected_700 == result['700']
+def test_authors_from_100__a_and_700__a_orders_correctly():
+ schema = load_schema('hep')
+ subschema = schema['properties']['authors']
+
+ snippet = (
+ '<record>'
+ ' <datafield tag="700" ind1=" " ind2=" ">'
+ ' <subfield code="a">Author, Second</subfield>'
+ ' </datafield>'
+ ' <datafield tag="100" ind1=" " ind2=" ">'
+ ' <subfield code="a">Author, First</subfield>'
+ ' </datafield>'
+ '</record>'
+ ) # synthetic data
+
+ expected = [
+ {'full_name': 'Author, First'},
+ {'full_name': 'Author, Second'},
+ ]
+ result = hep.do(create_record(snippet))
+
+ assert validate(result['authors'], subschema) is None
+ assert expected == result['authors']
+
+ expected = {
+ '100': {'a': 'Author, First'},
+ '700': [
+ {'a': 'Author, Second'},
+ ],
+ }
+ result = hep2marc.do(result)
+
+ assert expected['100'] == result['100']
+ assert expected['700'] == result['700']
+
+
def test_authors_from_100__a_e_w_y_and_700_a_e_w_y():
schema = load_schema('hep')
subschema = schema['properties']['authors']
|
hep: don't trust MARC <I>/<I> order
|
inspirehep_inspire-dojson
|
train
|
2fa4ccc1da05e2919d510cc62c3b9d9045f831a6
|
diff --git a/framework/db/Connection.php b/framework/db/Connection.php
index <HASH>..<HASH> 100644
--- a/framework/db/Connection.php
+++ b/framework/db/Connection.php
@@ -403,11 +403,11 @@ class Connection extends Component
*/
private $_driverName;
/**
- * @var Connection the currently active master connection
+ * @var Connection|false the currently active master connection
*/
private $_master = false;
/**
- * @var Connection the currently active slave connection
+ * @var Connection|false the currently active slave connection
*/
private $_slave = false;
/**
|
Fix phpdoc for $_master and $_slave properties in yii\db\Connection (#<I>)
|
yiisoft_yii2
|
train
|
ea8807987cf4aeb226f09f8a1050f621f2c4c622
|
diff --git a/flusher.go b/flusher.go
index <HASH>..<HASH> 100644
--- a/flusher.go
+++ b/flusher.go
@@ -796,7 +796,6 @@ func flushSpansLightstep(ctx context.Context, s *Server, lightstepTracer opentra
for _, ssfSpan := range ssfSpans {
flushSpanLightstep(lightstepTracer, ssfSpan)
}
- lightstep.FlushLightStepTracer(lightstepTracer)
// Confusingly, this will still get called even if the Opentracing client fails to reach the collector
// because we don't get access to the error if that happens.
|
Don't explicitly flush, let the lightstep client manage itself.
|
stripe_veneur
|
train
|
3e8884a7f1ddd492f127fd8cc7607a536809d9b6
|
diff --git a/middleware_test.go b/middleware_test.go
index <HASH>..<HASH> 100644
--- a/middleware_test.go
+++ b/middleware_test.go
@@ -6,6 +6,7 @@ package gin
import (
"errors"
+ "strings"
"testing"
@@ -245,11 +246,5 @@ func TestMiddlewareWrite(t *testing.T) {
w := performRequest(router, "GET", "/")
assert.Equal(t, w.Code, 400)
- assert.Equal(t, w.Body.String(), `hola
-<map><foo>bar</foo></map>{"foo":"bar"}
-{"foo":"bar"}
-event:test
-data:message
-
-`)
+ assert.Equal(t, strings.Replace(w.Body.String(), " ", "", -1), strings.Replace("hola\n<map><foo>bar</foo></map>{\"foo\":\"bar\"}\n{\"foo\":\"bar\"}\nevent:test\ndata:message\n\n", " ", "", -1))
}
|
Fix MiddlewareWrite in middleware_test.go
|
gin-gonic_gin
|
train
|
0cdce4d520387986a787258056ca2cacf0ddcc0e
|
diff --git a/question/type/ddmarker/yui/dd/dd.js b/question/type/ddmarker/yui/dd/dd.js
index <HASH>..<HASH> 100644
--- a/question/type/ddmarker/yui/dd/dd.js
+++ b/question/type/ddmarker/yui/dd/dd.js
@@ -408,6 +408,8 @@ YUI.add('moodle-qtype_ddmarker-dd', function(Y) {
var dragitemhome = this.doc.drag_item_home(choiceno);
for (var i=0; i < coords.length; i++) {
var dragitem;
+ coords[i][0] = Math.round(coords[i][0]);
+ coords[i][1] = Math.round(coords[i][1]);
dragitem = this.doc.drag_item_for_choice(choiceno, i);
if (!dragitem || dragitem.hasClass('beingdragged')) {
dragitem = this.clone_new_drag_item(dragitemhome, i);
@@ -481,6 +483,8 @@ YUI.add('moodle-qtype_ddmarker-dd', function(Y) {
drop_zone_key_press : function (e) {
var dragitem = e.target;
var xy = dragitem.getXY();
+ xy[0] = Math.round(xy[0]);
+ xy[1] = Math.round(xy[1]);
switch (e.direction) {
case 'left' :
xy[0] -= 1;
@@ -542,7 +546,33 @@ YUI.add('moodle-qtype_ddmarker-dd', function(Y) {
this, notifier);
}
});
+ M.qtype_ddmarker.isGetBoundingClientRectOverridden = false;
+ M.qtype_ddmarker.overrideGetBoundingClientRect = function() {
+ if(M.qtype_ddmarker.isGetBoundingClientRectOverridden){
+ return;
+ }
+
+ if(Y.UA.ie != 10 || !Element.prototype.getBoundingClientRect){
+ return;
+ }
+
+ M.qtype_ddmarker.isGetBoundingClientRectOverridden = true;
+ Element.prototype.getBoundingClientRectOld = Element.prototype.getBoundingClientRect;
+ Element.prototype.getBoundingClientRect = function(){
+ var rect = this.getBoundingClientRectOld();
+
+ var newRect = new Object();
+ newRect.top = Math.round(rect.top);
+ newRect.bottom = Math.round(rect.bottom);
+ newRect.left = Math.round(rect.left);
+ newRect.right = Math.round(rect.right);
+ newRect.height = Math.round(rect.height);
+ newRect.width = Math.round(rect.width);
+ return newRect;
+ }
+ }
M.qtype_ddmarker.init_question = function(config) {
+ M.qtype_ddmarker.overrideGetBoundingClientRect();
return new DDMARKER_QUESTION(config);
};
}, '@VERSION@', {
|
MDL-<I> ddmarker: Fix weird drag-drop marker behaviour in IE<I>. #<I>
Moving the markers with the keyboard was not working. The markers would
move in weird directions!
|
moodle_moodle
|
train
|
08bf7f02e4715e3c484f20e7c2f3e77fdd99fbf8
|
diff --git a/services/maintenance/maintenance.service.js b/services/maintenance/maintenance.service.js
index <HASH>..<HASH> 100644
--- a/services/maintenance/maintenance.service.js
+++ b/services/maintenance/maintenance.service.js
@@ -1,27 +1,56 @@
'use strict'
-const LegacyService = require('../legacy-service')
-const { makeBadgeData: getBadgeData } = require('../../lib/badge-data')
-const log = require('../../core/server/log')
-
-// This legacy service should be rewritten to use e.g. BaseJsonService.
-//
-// Tips for rewriting:
-// https://github.com/badges/shields/blob/master/doc/rewriting-services.md
-//
-// Do not base new services on this code.
-module.exports = class Maintenance extends LegacyService {
- static get category() {
- return 'other'
- }
+const { BaseService } = require('..')
+module.exports = class Maintenance extends BaseService {
static get route() {
return {
base: 'maintenance',
- pattern: ':maintained(yes|no)/:year(\\d{4})',
+ pattern: ':maintained/:year(\\d{4})',
}
}
+ static get defaultBadgeData() {
+ return {
+ label: 'maintained',
+ }
+ }
+
+ async handle({ maintained, year }) {
+ const now = new Date()
+ const cy = now.getUTCFullYear() // current year.
+ const m = now.getUTCMonth() // month.
+
+ if (maintained === 'no') {
+ return this.constructor.render({ message: `no! (as of ${year})` })
+ } else if (cy <= year) {
+ return this.constructor.render({ message: maintained })
+ } else if (parseInt(cy) === parseInt(year) + 1 && parseInt(m) < 3) {
+ return this.constructor.render({ message: `stale (as of ${cy})` })
+ } else {
+ return this.constructor.render({ message: `no! (as of ${year})` })
+ }
+ }
+
+ static render({ message }) {
+ if (message.startsWith('yes')) {
+ return {
+ message,
+ color: 'brightgreen',
+ }
+ } else if (message.startsWith('no')) {
+ return {
+ message,
+ color: 'red',
+ }
+ } else {
+ return { message }
+ }
+ }
+
+ static get category() {
+ return 'other'
+ }
static get examples() {
return [
{
@@ -31,47 +60,9 @@ module.exports = class Maintenance extends LegacyService {
maintained: 'yes',
year: '2019',
},
- staticPreview: {
- label: 'yes',
- message: '2019',
- color: 'brightgreen',
- },
+ staticPreview: this.render({ message: 'yes' }),
keywords: ['maintained'],
},
]
}
-
- static registerLegacyRouteHandler({ camp, cache }) {
- camp.route(
- /^\/maintenance\/([^/]+)\/([^/]+)\.(svg|png|gif|jpg|json)$/,
- cache((data, match, sendBadge, request) => {
- const status = match[1] // eg, yes
- const year = +match[2] // eg, 2016
- const format = match[3]
- const badgeData = getBadgeData('maintained', data)
- try {
- const now = new Date()
- const cy = now.getUTCFullYear() // current year.
- const m = now.getUTCMonth() // month.
- if (status === 'no') {
- badgeData.text[1] = `no! (as of ${year})`
- badgeData.colorscheme = 'red'
- } else if (cy <= year) {
- badgeData.text[1] = status
- badgeData.colorscheme = 'brightgreen'
- } else if (cy === year + 1 && m < 3) {
- badgeData.text[1] = `stale (as of ${cy})`
- } else {
- badgeData.text[1] = `no! (as of ${year})`
- badgeData.colorscheme = 'red'
- }
- sendBadge(format, badgeData)
- } catch (e) {
- log.error(e.stack)
- badgeData.text[1] = 'invalid'
- sendBadge(format, badgeData)
- }
- })
- )
- }
}
diff --git a/services/maintenance/maintenance.tester.js b/services/maintenance/maintenance.tester.js
index <HASH>..<HASH> 100644
--- a/services/maintenance/maintenance.tester.js
+++ b/services/maintenance/maintenance.tester.js
@@ -1,9 +1,6 @@
'use strict'
-const { ServiceTester } = require('../tester')
-
-const t = new ServiceTester({ id: 'maintenance', title: 'Maintenance' })
-module.exports = t
+const t = (module.exports = require('../tester').createServiceTester())
const currentYear = new Date().getUTCFullYear()
@@ -22,3 +19,7 @@ t.create('yes this year (yes)')
t.create(`until end of ${currentYear} (yes)`)
.get(`/until end of ${currentYear}/${currentYear}.json`)
.expectJSON({ name: 'maintained', value: `until end of ${currentYear}` })
+
+t.create(`stale last maintained ${currentYear - 1} (yes)`)
+ .get(`/yes/${currentYear - 1}.json`)
+ .expectJSON({ name: 'maintained', value: `stale (as of ${currentYear})` })
|
refactor maintenance service (#<I>)
|
badges_shields
|
train
|
b3a7b63532376e443d9b8b3ba3c03ac223875fd6
|
diff --git a/packages/sproutcore-metal/tests/computed_test.js b/packages/sproutcore-metal/tests/computed_test.js
index <HASH>..<HASH> 100644
--- a/packages/sproutcore-metal/tests/computed_test.js
+++ b/packages/sproutcore-metal/tests/computed_test.js
@@ -540,6 +540,31 @@ testBoth('depending on complex Global chain', function(get, set) {
});
+testBoth('chained dependent keys should respect SC.beginPropertyChanges', function(get,set){
+ var run_count;
+
+ set(obj.foo, 'a', 1);
+ set(obj.foo, 'b', 2);
+
+ SC.defineProperty(obj.foo, 'c', SC.computed(function(){
+ run_count++;
+ return get(obj.foo, 'a') + get(obj.foo, 'b')
+ }).property('a', 'b').cacheable());
+
+ SC.addObserver(obj, 'foo.c', this, function(){});
+
+ run_count = 0;
+
+ SC.beginPropertyChanges();
+ set(obj.foo, 'a', 10);
+ set(obj.foo, 'b', 20);
+ SC.endPropertyChanges();
+
+ equals(run_count, 1, 'should only run once');
+});
+
+
+
// ..........................................................
// BUGS
//
|
Adding unit test to demonstrate issue #<I>.
|
emberjs_ember.js
|
train
|
a2232a28bd22732f611abd1c6a054a79b1afb603
|
diff --git a/ricecooker/utils/jsontrees.py b/ricecooker/utils/jsontrees.py
index <HASH>..<HASH> 100644
--- a/ricecooker/utils/jsontrees.py
+++ b/ricecooker/utils/jsontrees.py
@@ -22,13 +22,14 @@ DOCUMENT_NODE = content_kinds.DOCUMENT
HTML5_NODE = content_kinds.HTML5
# TODO(Ivan): add constants.file_types to le_utils and discuss with Jordan
-# from le_utils.constants import file_types
-VIDEO_FILE = "video" # = file_types.VIDEO
-AUDIO_FILE = "audio" # = file_types.AUDIO
-DOCUMENT_FILE = "document" # = file_types.DOCUMENT etc..
-HTML5_FILE = "html5"
-THUMBNAIL_FILE = "thumbnail"
-SUBTITLES_FILE = "subtitles"
+from le_utils.constants import file_types
+VIDEO_FILE = file_types.VIDEO
+AUDIO_FILE = file_types.AUDIO
+DOCUMENT_FILE = file_types.DOCUMENT
+EPUB_FILE = file_types.EPUB
+HTML5_FILE = file_types.HTML5
+THUMBNAIL_FILE = file_types.THUMBNAIL
+SUBTITLES_FILE = file_types.SUBTITLES
from le_utils.constants import exercises
INPUT_QUESTION = exercises.INPUT_QUESTION
@@ -184,7 +185,7 @@ def build_tree_from_json(parent_node, sourcetree):
def add_files(node, file_list):
- EXPECTED_FILE_TYPES = [VIDEO_FILE, AUDIO_FILE, DOCUMENT_FILE, HTML5_FILE,
+ EXPECTED_FILE_TYPES = [VIDEO_FILE, AUDIO_FILE, DOCUMENT_FILE, EPUB_FILE, HTML5_FILE,
THUMBNAIL_FILE, SUBTITLES_FILE]
for f in file_list:
@@ -239,6 +240,13 @@ def add_files(node, file_list):
)
)
+ elif file_type == EPUB_FILE:
+ node.add_file(
+ files.EPubFile(
+ path=path,
+ language=f.get('language', None)
+ )
+ )
elif file_type == HTML5_FILE:
node.add_file(
diff --git a/ricecooker/utils/linecook.py b/ricecooker/utils/linecook.py
index <HASH>..<HASH> 100644
--- a/ricecooker/utils/linecook.py
+++ b/ricecooker/utils/linecook.py
@@ -6,7 +6,7 @@ from le_utils.constants import content_kinds
from .metadata_provider import path_to_tuple
from .jsontrees import (TOPIC_NODE, VIDEO_NODE, AUDIO_NODE, EXERCISE_NODE,
DOCUMENT_NODE, HTML5_NODE)
-from .jsontrees import (VIDEO_FILE, AUDIO_FILE, DOCUMENT_FILE, HTML5_FILE,
+from .jsontrees import (VIDEO_FILE, AUDIO_FILE, DOCUMENT_FILE, EPUB_FILE, HTML5_FILE,
THUMBNAIL_FILE, SUBTITLES_FILE)
from .jsontrees import write_tree_to_json_tree
@@ -313,8 +313,24 @@ def make_content_node(channeldir, rel_path, filename, metadata):
language=lang,
license=license_dict,
thumbnail=thumbnail_rel_path,
- files=[{'file_type':DOCUMENT_FILE, 'path':filepath, 'language':lang}],
+ files=[]
)
+ if ext == 'pdf':
+ pdf_file = {
+ 'file_type':DOCUMENT_FILE,
+ 'path':filepath,
+ 'language':lang
+ }
+ content_node['files'].append(pdf_file)
+ elif ext == 'epub':
+ epub_file = {
+ 'file_type':EPUB_FILE,
+ 'path':filepath,
+ 'language':lang
+ }
+ content_node['files'].append(epub_file)
+ else:
+ raise ValueError('Ext {} not supported for kind {}'.format(ext, kind))
elif kind == HTML5_NODE:
content_node = dict(
|
Add ePub support to LineCook json channels
|
learningequality_ricecooker
|
train
|
eee3a7861d2494ef06d48204ddb9167ed40014bd
|
diff --git a/src/Http/Guard.php b/src/Http/Guard.php
index <HASH>..<HASH> 100644
--- a/src/Http/Guard.php
+++ b/src/Http/Guard.php
@@ -74,7 +74,7 @@ class Guard implements GuardContract {
* @return bool|WP_Error
*/
protected function can_edit_others_posts() {
- return current_user_can( 'edit_others_posts' ) ?: new WP_Error( '401', __( 'Unauthorized user', 'jaxion' ) );
+ return current_user_can( 'edit_others_posts' ) ?: new WP_Error( 'unauthorized', __( 'Unauthorized user', 'jaxion' ), array( 'status' => 401 ) );
}
/**
@@ -83,7 +83,7 @@ class Guard implements GuardContract {
* @return bool|WP_Error
*/
protected function user_logged_in() {
- return is_user_logged_in() ?: new WP_Error( '401', __( 'Unauthorized user', 'jaxion' ) );
+ return is_user_logged_in() ?: new WP_Error( 'unauthorized', __( 'Unauthorized user', 'jaxion' ), array( 'status' => 401 ) );
}
/**
|
Set correct status codes for API response
The status codes need to be set in the WP_Error data, rather than the code, in order
to set the correct HTTP status code in the header.
|
intraxia_jaxion
|
train
|
18e5898ec420d7e5b29e53c12abf475ca6ed829a
|
diff --git a/vcr/patch.py b/vcr/patch.py
index <HASH>..<HASH> 100644
--- a/vcr/patch.py
+++ b/vcr/patch.py
@@ -87,7 +87,7 @@ class CassettePatcherBuilder(object):
def _recursively_apply_get_cassette_subclass(self, replacement_dict_or_obj):
if isinstance(replacement_dict_or_obj, dict):
- for key, replacement_obj in replacement_dict_or_obj:
+ for key, replacement_obj in replacement_dict_or_obj.items():
replacement_obj = self._recursively_apply_get_cassette_subclass(
replacement_obj)
replacement_dict_or_obj[key] = replacement_obj
@@ -121,7 +121,7 @@ class CassettePatcherBuilder(object):
try:
import requests.packages.urllib3.connectionpool as cpool
except ImportError: # pragma: no cover
- return
+ return ()
from .stubs.requests_stubs import VCRRequestsHTTPConnection, VCRRequestsHTTPSConnection
mock_triples = (
(cpool, 'VerifiedHTTPSConnection', VCRRequestsHTTPSConnection),
|
Return a tuple from the _request function on CassettePatcherBuilder even if import fails. Make _recursively_apply_get_cassette_subclass actually work with dictionaries.
|
kevin1024_vcrpy
|
train
|
4766aadf733a21a1f07e61af9fb9df889eeda93c
|
diff --git a/ezp/Persistence/Storage/InMemory/UserHandler.php b/ezp/Persistence/Storage/InMemory/UserHandler.php
index <HASH>..<HASH> 100644
--- a/ezp/Persistence/Storage/InMemory/UserHandler.php
+++ b/ezp/Persistence/Storage/InMemory/UserHandler.php
@@ -61,7 +61,7 @@ class UserHandler implements UserHandlerInterface
public function create( User $user )
{
$userArr = (array) $user;
- return $this->backend->create( 'User', $userArr );
+ return $this->backend->create( 'User', $userArr, false );
}
/**
diff --git a/ezp/Persistence/Tests/UserHandlerTest.php b/ezp/Persistence/Tests/UserHandlerTest.php
index <HASH>..<HASH> 100644
--- a/ezp/Persistence/Tests/UserHandlerTest.php
+++ b/ezp/Persistence/Tests/UserHandlerTest.php
@@ -55,13 +55,14 @@ class UserHandlerTest extends HandlerTest
{
$handler = $this->repositoryHandler->userHandler();
$obj = new User();
+ $obj->id = 1;
$obj->email = 'unit@ez.no';
$obj->hashAlgorithm = 2;
$obj->login = 'unit';
$obj->password = 'SomeRandomStuffShouldHaveBeenHash';
$obj = $handler->create( $obj );
$this->assertInstanceOf( 'ezp\\Persistence\\User', $obj );
- $this->assertEquals( 15, $obj->id );
+ $this->assertEquals( 1, $obj->id );
$this->assertEquals( 'unit@ez.no', $obj->email );
$this->assertEquals( 2, $obj->hashAlgorithm );
$this->assertEquals( 'unit', $obj->login );
|
Change: UserHandler to require User->id to be set
|
ezsystems_ezpublish-kernel
|
train
|
9383d2814ec9489fbf6b3d12e80ecd830f17443e
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -26,7 +26,9 @@ setup(name='papermill',
url='https://github.com/nteract/papermill',
packages=['papermill'],
install_requires=[
+ 'boto3',
'click',
+ 'concurrent',
'pyyaml',
'nbformat',
ipython_req,
|
adding in boto3 and concurrent to setup.py
|
nteract_papermill
|
train
|
4c7333e4cab60a3d3438b0933764ac1928e1c710
|
diff --git a/src/controllers/UploadController.php b/src/controllers/UploadController.php
index <HASH>..<HASH> 100644
--- a/src/controllers/UploadController.php
+++ b/src/controllers/UploadController.php
@@ -152,7 +152,7 @@ class UploadController extends LfmController
protected function replaceInsecureSuffix($name)
{
- return preg_replace("/\.php$/", '', $name);
+ return preg_replace("/\.php$/i", '', $name);
}
private function getNewName($file)
|
Triming php suffix should be case insensitive
|
UniSharp_laravel-filemanager
|
train
|
ff4920a415e3bd8c276395a5d5303ed7517e090d
|
diff --git a/src/Models/Taxonomy.php b/src/Models/Taxonomy.php
index <HASH>..<HASH> 100644
--- a/src/Models/Taxonomy.php
+++ b/src/Models/Taxonomy.php
@@ -6,7 +6,6 @@ use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
-use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Collection;
@@ -166,16 +165,6 @@ class Taxonomy extends Model
}
/**
- * Return the related items.
- *
- * @return HasMany
- */
- public function taxables(): HasMany
- {
- return $this->hasMany(Taxable::class, 'taxonomy_id');
- }
-
- /**
* Get the breadcrumbs for this Taxonomy.
*
* @param bool $exclude_self
diff --git a/src/Taxonomy.php b/src/Taxonomy.php
index <HASH>..<HASH> 100644
--- a/src/Taxonomy.php
+++ b/src/Taxonomy.php
@@ -14,19 +14,8 @@ use Lecturize\Taxonomies\Models\Term;
*/
class Taxonomy
{
- /**
- * The application instance.
- *
- * @var Application
- */
protected Application $app;
- /**
- * Create a new Cache manager instance.
- *
- * @param Application $app
- * @return void
- */
public function __construct(Application $app)
{
$this->app = $app;
@@ -138,18 +127,28 @@ class Taxonomy
* Get category tree item.
*
* @param Collection $taxonomies
- * @param string $taxable_class
+ * @param string $taxable_relation_attribute
* @param string $taxable_callback
* @param boolean $is_child
* @return Collection
* @throws Exception
*/
- public static function buildTree(Collection $taxonomies, string $taxable_class = '', string $taxable_callback = '', bool $is_child = false): Collection
+ public static function buildTree(Collection $taxonomies, string $taxable_relation_attribute = '', string $taxable_callback = '', bool $is_child = false): Collection
{
$terms = collect();
- if ($taxable_class)
- $taxonomies->load('taxables');
+ $relation = '';
+
+ if ($taxable_relation_attribute) {
+ if (str_contains($taxable_relation_attribute, '\\')) {
+ $relation = strtolower(substr($taxable_relation_attribute, strrpos($taxable_relation_attribute, '\\') + 1));
+ $relation = Str::plural($relation);
+ } else {
+ $relation = $taxable_relation_attribute;
+ }
+
+ $taxonomies->load($relation);
+ }
foreach ($taxonomies->sortBy('sort') as $taxonomy) {
if (! $is_child && ! is_null($taxonomy->parent_id))
@@ -160,20 +159,19 @@ class Taxonomy
if ($children = $taxonomy->children) {
if (($children_count = $children->count()) > 0) {
$children->load('parent', 'children');
- $children = self::buildTree($children, $taxable_class, $taxable_callback, true);
+ $children = self::buildTree($children, $taxable_relation_attribute, $taxable_callback, true);
}
}
$item_count = 0;
- if ($taxable_class && ($taxables = $taxonomy->taxables)) {
+ if ($relation && method_exists($taxonomy, $relation) && ($taxables = $taxonomy->{$relation})) {
$key = "taxonomies.$taxonomy->id";
- $key.= '.'. Str::slug($taxable_class);
+ $key.= '.'. Str::slug($relation);
$key.= $taxable_callback ? '.filter-'. Str::slug($taxable_callback) : '';
$key.= '.count';
- $item_count = maybe_tagged_cache(['taxonomies', 'taxonomies:tree'])->remember($key, config('lecturize.taxonomies.cache-expiry', now()->addWeek()), function() use($taxables, $taxable_class, $taxable_callback) {
- return $taxables->where('taxable_type', $taxable_class)
- ->filter(function ($item) use ($taxable_callback) {
+ $item_count = maybe_tagged_cache(['taxonomies', 'taxonomies:tree'])->remember($key, config('lecturize.taxonomies.cache-expiry', now()->addWeek()), function() use($taxables, $taxable_callback) {
+ return $taxables->filter(function ($item) use ($taxable_callback) {
if ($taxable_callback && ($taxable = $item->taxable) && method_exists($taxable, $taxable_callback)) {
try {
return $taxable->{$taxable_callback}();
@@ -198,7 +196,7 @@ class Taxonomy
'searchable' => $taxonomy->searchable,
'alias-params' => ($alias = $taxonomy->alias) ? $alias->getRouteParameters() : null,
'children' => $children_count > 0 ? $children : null,
- 'taxable' => $taxable_class,
+ 'taxable' => $relation,
'count' => $item_count,
'count-cumulative' => $item_count + ($children ? $children->sum('count-cumulative') : 0),
]);
@@ -206,4 +204,4 @@ class Taxonomy
return $terms;
}
-}
\ No newline at end of file
+}
|
Refactor taxable class into relation attribute
|
Lecturize_Laravel-Taxonomies
|
train
|
2adc51baa65543df5cf6662d2c8448ea261abc1d
|
diff --git a/lib/celluloid/supervision_group.rb b/lib/celluloid/supervision_group.rb
index <HASH>..<HASH> 100644
--- a/lib/celluloid/supervision_group.rb
+++ b/lib/celluloid/supervision_group.rb
@@ -60,7 +60,7 @@ module Celluloid
@members = []
@registry = registry || Registry.root
- yield self if block_given?
+ yield current_actor if block_given?
end
def supervise(klass, *args, &block)
|
Do not leak self in SupervisionGroup#initialize
|
celluloid_celluloid
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.