hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
64de7017088413b7b6e542ea7a89c3d88bbd6d12
|
diff --git a/pythomics/proteomics/parsers.py b/pythomics/proteomics/parsers.py
index <HASH>..<HASH> 100644
--- a/pythomics/proteomics/parsers.py
+++ b/pythomics/proteomics/parsers.py
@@ -1248,6 +1248,7 @@ class ThermoMSFIterator(templates.GenericIterator, GenericProteomicIterator):
labels = {}
from six.moves import html_parser as HTMLParser
html_parser = HTMLParser.HTMLParser()
+ silac = None
if self.version == 1:
sql = 'select ParameterValue from processingnodeparameters where ParameterName == "QuantificationMethod"'
self.cur.execute(sql)
@@ -1259,6 +1260,8 @@ class ThermoMSFIterator(templates.GenericIterator, GenericProteomicIterator):
silac = etree.fromstring(str(xml).encode('utf-16'))
elif self.version == 2:
silac = etree.fromstring([i for i in self.root.iterdescendants('QuantitationMethod')][0].text.encode('utf-16'))
+ if silac is None:
+ return labels
for method in silac.findall('*MethodPart'):
if self.version == 1 and method.getparent().get('name') != 'QuanChannels':
continue
|
handle cases where silac is undefined
|
pandeylab_pythomics
|
train
|
023d20842d5a09c9ea2eb625611ba2aa4c7279e2
|
diff --git a/tests/org.eclipse.xtext.tests/src/org/eclipse/xtext/scoping/impl/ImportedNamespaceAwareLocalScopeProviderTest.java b/tests/org.eclipse.xtext.tests/src/org/eclipse/xtext/scoping/impl/ImportedNamespaceAwareLocalScopeProviderTest.java
index <HASH>..<HASH> 100644
--- a/tests/org.eclipse.xtext.tests/src/org/eclipse/xtext/scoping/impl/ImportedNamespaceAwareLocalScopeProviderTest.java
+++ b/tests/org.eclipse.xtext.tests/src/org/eclipse/xtext/scoping/impl/ImportedNamespaceAwareLocalScopeProviderTest.java
@@ -89,8 +89,13 @@ public class ImportedNamespaceAwareLocalScopeProviderTest extends AbstractXtextT
XtextResource resource = getResource(new StringInputStream("import foo.bar.* "), URI
.createURI("import.indextestlanguage"));
resource.getResourceSet().createResource(URI.createURI("foo.indextestlanguage")).load(
- new StringInputStream("foo.bar { " + " entity Person { " + " String name " + " } "
- + " datatype String " + "}"), null);
+ new StringInputStream(
+ "foo.bar { "
+ + " entity Person { "
+ + " String name "
+ + " } "
+ + " datatype String "
+ + "}"), null);
IScope scope = scopeProvider.getScope(resource.getContents().get(0), IndexTestLanguagePackage.eINSTANCE
.getFile_Elements());
@@ -217,7 +222,44 @@ public class ImportedNamespaceAwareLocalScopeProviderTest extends AbstractXtextT
assertNotNull(scope.getSingleElement(selectByName(nameConverter.toQualifiedName("Bar"))));
}
- public void testDuplicateImportAreShadowed_00() throws Exception {
+ public void testDuplicateImportsAreIgnored() throws Exception {
+ final XtextResource resource = getResource(new StringInputStream(
+ "foo { "
+ + " entity Foo {}"
+ + " entity Bar {}"
+ + "}"
+ + "bar {"
+ + " entity Foo {}"
+ + "}"
+ + "baz {"
+ + " import foo.*"
+ + " import foo.*"
+ + " entity Baz{}"
+ + "}"), URI
+ .createURI("withoutwildcard.indextestlanguage"));
+ Iterable<EObject> allContents = new Iterable<EObject>() {
+ public Iterator<EObject> iterator() {
+ return resource.getAllContents();
+ }
+ };
+ Entity foo = find(Iterables.filter(allContents, Entity.class), new Predicate<Entity>(){
+ public boolean apply(Entity input) {
+ return input.getName().equals("Baz");
+ }});
+
+ IScope scope = scopeProvider.getScope(foo, IndexTestLanguagePackage.eINSTANCE.getProperty_Type());
+ assertNotNull(scope.getSingleElement(selectByName(nameConverter.toQualifiedName("Bar"))));
+ assertNotNull(scope.getSingleElement(selectByName(nameConverter.toQualifiedName("Foo"))));
+ ArrayList<IEObjectDescription> list = newArrayList(scope.getElements(ISelector.SELECT_ALL));
+ assertEquals(7,list.size());
+ assertTrue(any(list, new Predicate<IEObjectDescription>() {
+ public boolean apply(IEObjectDescription input) {
+ return input.getName().equals(QualifiedName.create("Foo"));
+ }
+ }));
+ }
+
+ public void testUnambiguousImportAreShadowed_00() throws Exception {
final XtextResource resource = getResource(new StringInputStream(
"foo { "
+ " entity Foo {}"
@@ -249,11 +291,11 @@ public class ImportedNamespaceAwareLocalScopeProviderTest extends AbstractXtextT
assertEquals(6,list.size());
assertFalse(any(list, new Predicate<IEObjectDescription>() {
public boolean apply(IEObjectDescription input) {
- return input.getName().equals("Foo");
+ return input.getName().equals(QualifiedName.create("Foo"));
}
}));
}
- public void testDuplicateImportAreShadowed_01() throws Exception {
+ public void testUnambiguousImportAreShadowed_01() throws Exception {
final XtextResource resource = getResource(new StringInputStream(
"foo { "
+ " entity Foo {}"
@@ -285,11 +327,11 @@ public class ImportedNamespaceAwareLocalScopeProviderTest extends AbstractXtextT
assertEquals(6,list.size());
assertFalse(any(list, new Predicate<IEObjectDescription>() {
public boolean apply(IEObjectDescription input) {
- return input.getName().equals("Foo");
+ return input.getName().equals(QualifiedName.create("Foo"));
}
}));
}
- public void testDuplicateImportAreShadowed_02() throws Exception {
+ public void testUnambiguousImportAreShadowed_02() throws Exception {
final XtextResource resource = getResource(new StringInputStream(
"foo { "
+ " entity Foo {}"
@@ -321,7 +363,7 @@ public class ImportedNamespaceAwareLocalScopeProviderTest extends AbstractXtextT
assertEquals(5,list.size());
assertFalse(any(list, new Predicate<IEObjectDescription>() {
public boolean apply(IEObjectDescription input) {
- return input.getName().equals("Foo");
+ return input.getName().equals(QualifiedName.create("Foo"));
}
}));
}
|
[scoping] optimized ImportScope for huge selection (ISelector.SELECT_ALL), ignore duplicate imports, removed LocalScope replaced usages by ImportScope
|
eclipse_xtext-extras
|
train
|
10f1ae30a4f81e9a7e8c820408cccd2907175173
|
diff --git a/threadedcomments/models.py b/threadedcomments/models.py
index <HASH>..<HASH> 100644
--- a/threadedcomments/models.py
+++ b/threadedcomments/models.py
@@ -7,6 +7,7 @@ PATH_DIGITS = getattr(settings, 'COMMENT_PATH_DIGITS', 10)
class ThreadedComment(Comment):
+ title = models.TextField(blank=True)
parent = models.ForeignKey('self', null=True, blank=True, default=None,
related_name='children')
last_child = models.ForeignKey('self', null=True, blank=True)
|
Added a non-required title field
|
HonzaKral_django-threadedcomments
|
train
|
ab852a0405d9687aebe33555e975482d163d6121
|
diff --git a/lib/redfish/glassfish/interpreter/interpreter.rb b/lib/redfish/glassfish/interpreter/interpreter.rb
index <HASH>..<HASH> 100644
--- a/lib/redfish/glassfish/interpreter/interpreter.rb
+++ b/lib/redfish/glassfish/interpreter/interpreter.rb
@@ -385,6 +385,8 @@ module Redfish #nodoc
end
def interpret_jvm_options(run_context, config)
+ return unless (config['managed'].nil? ? true : !!config['managed'])
+
options = config['options'] || []
defines = config['defines'] || {}
default_defines = config['default_defines'].nil? ? true : config['default_defines']
|
if managed flag is set to false then skip managing jvm options
|
realityforge_redfish
|
train
|
e71d697d80f19afabcc5e2fdc5c7c87440f4ba46
|
diff --git a/src/utilities.js b/src/utilities.js
index <HASH>..<HASH> 100644
--- a/src/utilities.js
+++ b/src/utilities.js
@@ -56,18 +56,20 @@ export function buildQueryString({ select, filter, groupBy, orderBy, top, skip,
}
}
-function buildFilter(filter = {}) {
- if (typeof(filter) === 'string') {
- return filter;
- } else {
- const filters = Object.keys(filter).reduce((result, filterKey) => {
+function buildFilter(filters = {}) {
+ if (typeof(filters) === 'string') {
+ return filters;
+ } else if (Array.isArray(filters)) {
+ return filters.map(f => buildFilter(f)).join(' and ');
+ } else if (typeof(filters) === 'object') {
+ const filtersArray = Object.keys(filters).reduce((result, filterKey) => {
// TODO: Smartly build filter based on object (determine query syntax to pass)
// return '(Tasks/any(t:((t/AssignedGroupId eq 109343))))'
- if (filterKey === 'Tasks' && Object.keys(filter.Tasks).length) {
- const tasksFilter = Object.keys(filter.Tasks).map(key => `(t/${key} eq ${filter.Tasks[key]})`).join(' and ')
+ if (filterKey === 'Tasks' && Object.keys(filters.Tasks).length) {
+ const tasksFilter = Object.keys(filters.Tasks).map(key => `(t/${key} eq ${filters.Tasks[key]})`).join(' and ')
result.push(`Tasks/any(t:(${tasksFilter}))`);
} else {
- const value = filter[filterKey];
+ const value = filters[filterKey];
if (value instanceof Object) {
const operators = Object.keys(value);
operators.forEach(op => {
@@ -81,6 +83,8 @@ function buildFilter(filter = {}) {
return result;
}, [])
- return filters.join(' and ');
+ return filtersArray.join(' and ');
+ } else {
+ throw new Error(`Unexpected filters type: "${typeof(filters)}"`)
}
}
\ No newline at end of file
diff --git a/src/utilities.test.js b/src/utilities.test.js
index <HASH>..<HASH> 100644
--- a/src/utilities.test.js
+++ b/src/utilities.test.js
@@ -25,6 +25,13 @@ describe('filter', () => {
const actual = buildQueryString({ filter });
expect(actual).toEqual(expected);
});
+
+ it('should allow passing filter as an array of objects and strings', () => {
+ const filter = [{ SomeProp: 1 }, { AnotherProp: 2 }, 'startswith(Name, "foo")'];
+ const expected = '$filter=SomeProp eq 1 and AnotherProp eq 2 and startswith(Name, "foo")'
+ const actual = buildQueryString({ filter });
+ expect(actual).toEqual(expected);
+ });
})
describe('groupBy', () => {
|
Add support for passing filter as an array
|
techniq_react-odata
|
train
|
da48400609e9f11177b6ed2ee6a816d6b1fa458a
|
diff --git a/glue/LSCsegFindServer.py b/glue/LSCsegFindServer.py
index <HASH>..<HASH> 100644
--- a/glue/LSCsegFindServer.py
+++ b/glue/LSCsegFindServer.py
@@ -234,7 +234,7 @@ class ServerHandler(SocketServer.BaseRequestHandler):
result = ""
for x in res:
if len(x) == 1:
- result += x.strip() + '\n'
+ result += x[0].strip() + '\n'
else:
result += str(x) + '\n'
|
don't strip a tuple
|
gwastro_pycbc-glue
|
train
|
dbcf7a02a08d9e3578039770c1d44c0cbed5b449
|
diff --git a/lib/model/rwfolder.go b/lib/model/rwfolder.go
index <HASH>..<HASH> 100644
--- a/lib/model/rwfolder.go
+++ b/lib/model/rwfolder.go
@@ -81,7 +81,7 @@ const (
const (
defaultCopiers = 2
defaultPullerPause = 60 * time.Second
- defaultPullerPendingKiB = 8192 // must be larger than block size
+ defaultPullerPendingKiB = 2 * protocol.MaxBlockSize
maxPullerIterations = 3
)
|
lib/model: Increase the default pull limit (fixes #<I>)
Bumping the limit to 2 * the max block size (<I> MiB) is a slight
increase compared to previously. Nonetheless I think it's good to allow
us to queue one request and have one on the way in, or conversely have
one large block on the way in and be able to ask for smaller blocks from
others at the same time.
|
syncthing_syncthing
|
train
|
6aea14e7047fab016cac20f7ad8c6163fc060411
|
diff --git a/tests/test_read_simple_markdown.py b/tests/test_read_simple_markdown.py
index <HASH>..<HASH> 100644
--- a/tests/test_read_simple_markdown.py
+++ b/tests/test_read_simple_markdown.py
@@ -265,6 +265,25 @@ def test_split_on_header_after_two_blank_lines(
compare(markdown2, markdown)
+def test_split_at_heading_in_metadata(
+ markdown="""---
+jupyter:
+ jupytext:
+ split_at_heading: true
+---
+
+A paragraph
+
+# H1 Header
+""",
+ nb_expected=new_notebook(
+ cells=[new_markdown_cell("A paragraph"), new_markdown_cell("# H1 Header")]
+ ),
+):
+ nb = jupytext.reads(markdown, ".md")
+ compare_notebooks(nb, nb_expected)
+
+
def test_code_cell_with_metadata(
markdown="""```python tags=["parameters"]
a = 1
|
Test that the split_at_heading option in the metadata works
|
mwouts_jupytext
|
train
|
782052f4726fd2c5e0c8a95d1779d48688a480d5
|
diff --git a/upup/pkg/fi/cloudup/apply_cluster.go b/upup/pkg/fi/cloudup/apply_cluster.go
index <HASH>..<HASH> 100644
--- a/upup/pkg/fi/cloudup/apply_cluster.go
+++ b/upup/pkg/fi/cloudup/apply_cluster.go
@@ -401,7 +401,6 @@ func (c *ApplyClusterCmd) Run(ctx context.Context) error {
return fmt.Errorf("GCE support is currently alpha, and is feature-gated. export KOPS_FEATURE_FLAGS=AlphaAllowGCE")
}
- modelContext.SSHPublicKeys = sshPublicKeys
}
case kops.CloudProviderDO:
@@ -410,7 +409,6 @@ func (c *ApplyClusterCmd) Run(ctx context.Context) error {
return fmt.Errorf("SSH public key must be specified when running with DigitalOcean (create with `kops create secret --name %s sshpublickey admin -i ~/.ssh/id_rsa.pub`)", cluster.ObjectMeta.Name)
}
- modelContext.SSHPublicKeys = sshPublicKeys
}
case kops.CloudProviderAWS:
{
@@ -427,8 +425,6 @@ func (c *ApplyClusterCmd) Run(ctx context.Context) error {
return fmt.Errorf("SSH public key must be specified when running with AWS (create with `kops create secret --name %s sshpublickey admin -i ~/.ssh/id_rsa.pub`)", cluster.ObjectMeta.Name)
}
- modelContext.SSHPublicKeys = sshPublicKeys
-
if len(sshPublicKeys) > 1 {
return fmt.Errorf("exactly one 'admin' SSH public key can be specified when running with AWS; please delete a key using `kops delete secret`")
}
@@ -448,8 +444,6 @@ func (c *ApplyClusterCmd) Run(ctx context.Context) error {
return fmt.Errorf("SSH public key must be specified when running with ALICloud (create with `kops create secret --name %s sshpublickey admin -i ~/.ssh/id_rsa.pub`)", cluster.ObjectMeta.Name)
}
- modelContext.SSHPublicKeys = sshPublicKeys
-
if len(sshPublicKeys) != 1 {
return fmt.Errorf("exactly one 'admin' SSH public key can be specified when running with ALICloud; please delete a key using `kops delete secret`")
}
@@ -464,8 +458,6 @@ func (c *ApplyClusterCmd) Run(ctx context.Context) error {
return fmt.Errorf("SSH public key must be specified when running with AzureCloud (create with `kops create secret --name %s sshpublickey admin -i ~/.ssh/id_rsa.pub`)", cluster.ObjectMeta.Name)
}
- modelContext.SSHPublicKeys = sshPublicKeys
-
if len(sshPublicKeys) != 1 {
return fmt.Errorf("exactly one 'admin' SSH public key can be specified when running with AzureCloud; please delete a key using `kops delete secret`")
}
@@ -476,8 +468,6 @@ func (c *ApplyClusterCmd) Run(ctx context.Context) error {
return fmt.Errorf("SSH public key must be specified when running with Openstack (create with `kops create secret --name %s sshpublickey admin -i ~/.ssh/id_rsa.pub`)", cluster.ObjectMeta.Name)
}
- modelContext.SSHPublicKeys = sshPublicKeys
-
if len(sshPublicKeys) != 1 {
return fmt.Errorf("exactly one 'admin' SSH public key can be specified when running with Openstack; please delete a key using `kops delete secret`")
}
@@ -486,6 +476,7 @@ func (c *ApplyClusterCmd) Run(ctx context.Context) error {
return fmt.Errorf("unknown CloudProvider %q", cluster.Spec.CloudProvider)
}
+ modelContext.SSHPublicKeys = sshPublicKeys
modelContext.Region = cloud.Region()
if dns.IsGossipHostname(cluster.ObjectMeta.Name) {
|
Set ssh key on the model context in one location
|
kubernetes_kops
|
train
|
67bfe65fc94fa70478c36ce64d079a2863ed405d
|
diff --git a/src/CoandaCMS/Coanda/Pages/Exceptions/PublishHandlerException.php b/src/CoandaCMS/Coanda/Pages/Exceptions/PublishHandlerException.php
index <HASH>..<HASH> 100644
--- a/src/CoandaCMS/Coanda/Pages/Exceptions/PublishHandlerException.php
+++ b/src/CoandaCMS/Coanda/Pages/Exceptions/PublishHandlerException.php
@@ -7,7 +7,7 @@
class PublishHandlerException extends \Exception {
/**
- * @var array|string
+ * @var array
*/
private $invalid_fields = [];
@@ -16,7 +16,10 @@ class PublishHandlerException extends \Exception {
*/
public function __construct($invalid_fields)
{
- $this->invalid_fields = $invalid_fields;
+ if (is_array($invalid_fields))
+ {
+ $this->invalid_fields = $invalid_fields;
+ }
}
/**
|
Invalid fields must be an array.
|
CoandaCMS_coanda-core
|
train
|
9703be932d78bf07455557ad42fb97d9a51f25bc
|
diff --git a/src/ol/control/attributioncontrol.js b/src/ol/control/attributioncontrol.js
index <HASH>..<HASH> 100644
--- a/src/ol/control/attributioncontrol.js
+++ b/src/ol/control/attributioncontrol.js
@@ -64,11 +64,11 @@ ol.control.Attribution = function(opt_options) {
this.collapsed_ = false;
}
- var className = options.className ? options.className : 'ol-attribution';
+ var className = options.className !== undefined ? options.className : 'ol-attribution';
- var tipLabel = options.tipLabel ? options.tipLabel : 'Attributions';
+ var tipLabel = options.tipLabel !== undefined ? options.tipLabel : 'Attributions';
- var collapseLabel = options.collapseLabel ? options.collapseLabel : '\u00BB';
+ var collapseLabel = options.collapseLabel !== undefined ? options.collapseLabel : '\u00BB';
/**
* @private
@@ -78,7 +78,7 @@ ol.control.Attribution = function(opt_options) {
goog.dom.createDom('SPAN', {}, collapseLabel) :
collapseLabel;
- var label = options.label ? options.label : 'i';
+ var label = options.label !== undefined ? options.label : 'i';
/**
* @private
|
Fix checks for undefined in attributioncontrol
|
openlayers_openlayers
|
train
|
ea6d5563c08f83fab7a4ec98712182d0a649fed1
|
diff --git a/cdm-test/src/test/java/ucar/nc2/grib/TestGribIndexCreation.java b/cdm-test/src/test/java/ucar/nc2/grib/TestGribIndexCreation.java
index <HASH>..<HASH> 100644
--- a/cdm-test/src/test/java/ucar/nc2/grib/TestGribIndexCreation.java
+++ b/cdm-test/src/test/java/ucar/nc2/grib/TestGribIndexCreation.java
@@ -37,26 +37,44 @@ import org.junit.Test;
import thredds.catalog.parser.jdom.FeatureCollectionReader;
import thredds.featurecollection.FeatureCollectionConfig;
import thredds.inventory.CollectionUpdateType;
+import ucar.nc2.Group;
+import ucar.nc2.NetcdfFile;
+import ucar.nc2.Variable;
import ucar.nc2.grib.collection.GribCdmIndex;
import ucar.unidata.test.util.TestDir;
import java.io.IOException;
+import java.util.List;
/**
- * Describe
+ * Tests whether a feature collection config that includes gdshash actually
+ * correctly remaps variables onto a common grid. This is addressing a problem
+ * with the NDFD that silently cropped in and back out.
*
- * @author caron
- * @since 11/14/2014
+ * @author rmay
+ * @since 11/18/2014
*/
public class TestGribIndexCreation {
@Test
public void testGdsHashChange() throws IOException {
- String dataDir2 = TestDir.cdmUnitTestDir + "gribCollections/gdsHashChange/";
- FeatureCollectionConfig config = FeatureCollectionReader.readFeatureCollection(TestDir.cdmUnitTestDir + "gribCollections/gdsHashChange/config.xml#NDFD-CONUS_5km_conduit");
+ String dataDir = TestDir.cdmUnitTestDir + "gribCollections/gdsHashChange/";
+ FeatureCollectionConfig config = FeatureCollectionReader
+ .readFeatureCollection(dataDir +
+ "/config.xml#NDFD-CONUS_5km_conduit");
org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger("test");
- boolean changed = GribCdmIndex.updateGribCollection(config, CollectionUpdateType.always, logger);
- System.out.printf("changed = %s%n", changed);
+ GribCdmIndex.updateGribCollection(config, CollectionUpdateType.always,
+ logger);
+ // Open the index file
+ NetcdfFile f = NetcdfFile.open(dataDir +
+ "NDFD_CONUS_5km_conduit_20141114_1300.grib2.ncx2");
+
+ // Check that we have no groups other than the root
+ List<Group> groups = f.getRootGroup().getGroups();
+ assert groups.size() == 0;
+
+ List<Variable> vars = f.getRootGroup().getVariables();
+ assert vars.size() == 35;
}
}
|
Add unit test for gdsHash.
This should help detect any changes to the gdsHash functionality, like
those observed with the TDM on the thredds test machines.
|
Unidata_thredds
|
train
|
5a5fd93cb690de333129b8527842a837b56104f4
|
diff --git a/packages/react-jsx-highcharts/src/components/Axis/Axis.js b/packages/react-jsx-highcharts/src/components/Axis/Axis.js
index <HASH>..<HASH> 100644
--- a/packages/react-jsx-highcharts/src/components/Axis/Axis.js
+++ b/packages/react-jsx-highcharts/src/components/Axis/Axis.js
@@ -64,7 +64,10 @@ class Axis extends Component {
}
componentWillUnmount () {
- attempt(this.axis.remove.bind(this.axis)); // Axis may have already been removed, i.e. when Chart unmounted
+ if (this.axis.remove) {
+ // Axis may have already been removed, i.e. when Chart unmounted
+ attempt(this.axis.remove.bind(this.axis));
+ }
}
getAxisConfig = () => {
|
Check that axis.remove exists before calling it. Try to prevent bugs with future highcharts versions
|
whawker_react-jsx-highcharts
|
train
|
13bc9531059443efa8957b037c9f51f602b091f3
|
diff --git a/tests/minifier.js b/tests/minifier.js
index <HASH>..<HASH> 100644
--- a/tests/minifier.js
+++ b/tests/minifier.js
@@ -513,6 +513,10 @@
output = '<textarea> foo bar baz \n\n x \t y </textarea>';
equal(minify(input, { collapseWhitespace: true }), output);
+ input = '<div><textarea></textarea> </div>';
+ output = '<div><textarea></textarea></div>';
+ equal(minify(input, { collapseWhitespace: true }), output);
+
input = '<pre title="some title..."> hello world </pre>';
output = '<pre title="some title..."> hello world </pre>';
equal(minify(input, { collapseWhitespace: true }), output);
|
Added new collapseWhitespace test ...
Failing currently.
|
kangax_html-minifier
|
train
|
8c1fe9e73fc5ed6c652d28191d05efe8e9dd25ad
|
diff --git a/pysat/tests/test_utils_io.py b/pysat/tests/test_utils_io.py
index <HASH>..<HASH> 100644
--- a/pysat/tests/test_utils_io.py
+++ b/pysat/tests/test_utils_io.py
@@ -1226,8 +1226,10 @@ class TestMetaTranslation(object):
new_meta = io.add_netcdf4_standards_to_metadict(self.test_inst,
self.meta_dict,
epoch_name)
+ labels = self.test_inst.meta.labels
filt_meta = io.remove_netcdf4_standards_from_meta(new_meta,
- epoch_name)
+ epoch_name,
+ labels)
# Test the logging message
captured = caplog.text
@@ -1239,6 +1241,10 @@ class TestMetaTranslation(object):
# else.
for var in self.meta_dict.keys():
assert var in filt_meta, 'Lost metadata variable {}'.format(var)
+ # Creating exception for time-index of higher order data. The
+ # long_name comes out differently.
+ if var == 'profiles':
+ continue
for key in self.meta_dict[var].keys():
if key not in ['fill', 'value_min', 'value_max']:
assert key in filt_meta[var], \
|
TST: Tests pass with 'profiles' time index exception
|
rstoneback_pysat
|
train
|
b116115f71447a3d6e8c4a4fa7b2cc6271ad1ea5
|
diff --git a/lib/cisco_node_utils/bgp_neighbor_af.rb b/lib/cisco_node_utils/bgp_neighbor_af.rb
index <HASH>..<HASH> 100644
--- a/lib/cisco_node_utils/bgp_neighbor_af.rb
+++ b/lib/cisco_node_utils/bgp_neighbor_af.rb
@@ -573,7 +573,8 @@ module Cisco
# NOTE: 'standard' is default but does not nvgen on some platforms
# Returns: none, both, extended, or standard
def send_community_nexus(val)
- return 'both' if val.grep(/extended|standard/).size == 2
+ reg = 'send-community extended|send-community standard|send-community'
+ return 'both' if val.grep(/#{reg}/).size == 2
val = val[0].split.last
return 'standard' if val[/send-community/] # Workaround
val
|
fix for send-community (#<I>)
|
cisco_cisco-network-node-utils
|
train
|
a35153b3ee3d962faee219136bd4bad227458df7
|
diff --git a/upoints/__init__.py b/upoints/__init__.py
index <HASH>..<HASH> 100644
--- a/upoints/__init__.py
+++ b/upoints/__init__.py
@@ -71,5 +71,6 @@ from upoints import (baken, cellid, cities, geonames, gpx, kml, nmea, osm,
point, trigpoints, tzdata, utils, weather_stations,
xearth)
-__all__ = (baken, cellid, cities, geonames, gpx, kml, nmea, osm, point,
- trigpoints, tzdata, utils, weather_stations, xearth)
+__all__ = ('baken', 'cellid', 'cities', 'geonames', 'gpx', 'kml', 'nmea',
+ 'osm', 'point', 'trigpoints', 'tzdata', 'utils', 'weather_stations',
+ 'xearth')
|
[QA] __all__ should be strings not objects
|
JNRowe_upoints
|
train
|
9cff696c3da74c4a743933036f449ac37371ac7c
|
diff --git a/scripts/build/build.js b/scripts/build/build.js
index <HASH>..<HASH> 100644
--- a/scripts/build/build.js
+++ b/scripts/build/build.js
@@ -13,12 +13,12 @@ let cmd = `./node_modules/.bin/rollup ` +
`--format ${type} `;
// Production version (minified with sourcemap, argument validation removed)
-let production = cmd + ` --file dist/webmidi.${type}.min.js ` +
+let production = cmd + ` --file dist/webmidi.${type}.production.js ` +
`--sourcemap ` +
`--config ${__dirname}/rollup.config.${type}.production.js`;
// Development version (non-minified, with argument validation)
-let development = cmd + ` --file dist/webmidi.${type}.js ` +
+let development = cmd + ` --file dist/webmidi.${type}.development.js ` +
`--config ${__dirname}/rollup.config.${type}.development.js`;
async function execute() {
@@ -28,7 +28,7 @@ async function execute() {
console.info(
"\x1b[32m", // green font
- `The "${type}" production build was saved to "dist/webmidi.${type}.min.js"`,
+ `The "${type}" production build was saved to "dist/webmidi.${type}.production.js"`,
"\x1b[0m" // reset font
);
@@ -37,7 +37,7 @@ async function execute() {
console.info(
"\x1b[32m", // green font
- `The "${type}" development build was saved to "dist/webmidi.${type}.js"`,
+ `The "${type}" development build was saved to "dist/webmidi.${type}.development.js"`,
"\x1b[0m" // reset font
);
|
Generate two builds (production and development) for each format
|
djipco_webmidi
|
train
|
4b72d4d02904ea463939374d717108ca95879f72
|
diff --git a/openpnm/network/Cubic.py b/openpnm/network/Cubic.py
index <HASH>..<HASH> 100644
--- a/openpnm/network/Cubic.py
+++ b/openpnm/network/Cubic.py
@@ -168,11 +168,11 @@ class Cubic(GenericNetwork):
hits = sp.zeros_like(self.Ps, dtype=bool)
dims = topotools.dimensionality(self)
mn = sp.amin(self['pore.coords'], axis=0)
- mx = sp.amax(self['pore.coords'], axis=1)
+ mx = sp.amax(self['pore.coords'], axis=0)
for ax in [0, 1, 2]:
if dims[ax]:
- hits += sp.any(self['pore.coords'][:, ax] <= mn[ax])
- hits += sp.any(self['pore.coords'][:, ax] >= mx[ax])
+ hits += self['pore.coords'][:, ax] <= mn[ax]
+ hits += self['pore.coords'][:, ax] >= mx[ax]
self['pore.surface'] = hits
def add_boundary_pores(self, labels=['top', 'bottom', 'front', 'back',
|
fixing bug in label_pores on Cubic class
|
PMEAL_OpenPNM
|
train
|
c11360bf368bc505f8d71df30265077bb7041abe
|
diff --git a/multigtfs/models/base.py b/multigtfs/models/base.py
index <HASH>..<HASH> 100644
--- a/multigtfs/models/base.py
+++ b/multigtfs/models/base.py
@@ -31,6 +31,7 @@ logger = getLogger(__name__)
re_point = re.compile(r'(?P<name>point)\[(?P<index>\d)\]')
batch_size = 1000
large_queryset_size = 100000
+CSV_BOM = BOM_UTF8.decode('utf-8') if PY3 else BOM_UTF8
class BaseQuerySet(GeoQuerySet):
@@ -215,17 +216,13 @@ class Base(models.Model):
count = 0
first = True
extra_counts = defaultdict(int)
- if PY3: # pragma: no cover
- bom = BOM_UTF8.decode('utf-8')
- else: # pragma: no cover
- bom = BOM_UTF8
new_objects = []
for row in csv_reader:
if first:
# Read the columns
columns = row
- if columns[0].startswith(bom):
- columns[0] = columns[0][len(bom):]
+ if columns[0].startswith(CSV_BOM):
+ columns[0] = columns[0][len(CSV_BOM):]
first = False
continue
|
Refactor to remove branches around BOM handling
This eliminates some # pragma: no cover
|
tulsawebdevs_django-multi-gtfs
|
train
|
5cad32be5d9e4587869506969b3511cefc3e26ee
|
diff --git a/Branch-SDK-TestBed/src/io/branch/branchandroiddemo/MainActivity.java b/Branch-SDK-TestBed/src/io/branch/branchandroiddemo/MainActivity.java
index <HASH>..<HASH> 100644
--- a/Branch-SDK-TestBed/src/io/branch/branchandroiddemo/MainActivity.java
+++ b/Branch-SDK-TestBed/src/io/branch/branchandroiddemo/MainActivity.java
@@ -305,6 +305,15 @@ public class MainActivity extends Activity {
}
});
+ // Add optional deep link debug params
+// try {
+// JSONObject debugObj = new JSONObject();
+// debugObj.put("DeeplinkTestKey1", "DeeplinkTestValue1");
+// debugObj.put("DeeplinkTestKey2", "DeeplinkTestValue2");
+// Branch.getInstance().setDeepLinkDebugMode(debugObj);
+// }catch (JSONException ignore){
+// }
+
}
@Override
diff --git a/Branch-SDK/src/io/branch/indexing/BranchUniversalObject.java b/Branch-SDK/src/io/branch/indexing/BranchUniversalObject.java
index <HASH>..<HASH> 100644
--- a/Branch-SDK/src/io/branch/indexing/BranchUniversalObject.java
+++ b/Branch-SDK/src/io/branch/indexing/BranchUniversalObject.java
@@ -486,9 +486,14 @@ public class BranchUniversalObject implements Parcelable {
Branch branchInstance = Branch.getInstance();
try {
if (branchInstance != null && branchInstance.getLatestReferringParams() != null) {
+ // Check if link clicked. Unless deepvlink debug enabled return null if there is no link click
if (branchInstance.getLatestReferringParams().has("+clicked_branch_link") && branchInstance.getLatestReferringParams().getBoolean("+clicked_branch_link")) {
branchUniversalObject = createInstance(branchInstance.getLatestReferringParams());
}
+ // If debug params are set then send BUO object even if link click is false
+ else if (branchInstance.getDeeplinkDebugParams() != null && branchInstance.getDeeplinkDebugParams().length() > 0) {
+ branchUniversalObject = createInstance(branchInstance.getLatestReferringParams());
+ }
}
} catch (Exception ignore) {
}
diff --git a/Branch-SDK/src/io/branch/referral/Branch.java b/Branch-SDK/src/io/branch/referral/Branch.java
index <HASH>..<HASH> 100644
--- a/Branch-SDK/src/io/branch/referral/Branch.java
+++ b/Branch-SDK/src/io/branch/referral/Branch.java
@@ -285,6 +285,9 @@ public class Branch {
*/
private static final int PREVENT_CLOSE_TIMEOUT = 500;
+ /* Json object containing key-value pairs for debugging deep linking */
+ private JSONObject deeplinkDebugParams_;
+
/**
* <p>A {@link Branch} object that is instantiated on init and holds the singleton instance of
* the class during application runtime.</p>
@@ -392,7 +395,6 @@ public class Branch {
debugHandler_ = new Handler();
debugStarted_ = false;
linkCache_ = new HashMap<>();
-
}
@@ -658,6 +660,15 @@ public class Branch {
}
/**
+ * Sets the key-value pairs for debugging the deep link. The key-value set in debug mode is given back with other deep link data on branch init session.
+ * This method should be called from onCreate() of activity which listens to Branch Init Session callbacks
+ * @param debugParams A {@link JSONObject} containing key-value pairs for debugging branch deep linking
+ */
+ public void setDeepLinkDebugMode(JSONObject debugParams){
+ deeplinkDebugParams_ = debugParams;
+ }
+
+ /**
* <p>Calls the {@link PrefHelper#disableExternAppListing()} on the local instance to prevent
* a list of installed apps from being returned to the Branch API.</p>
*/
@@ -1702,7 +1713,9 @@ public class Branch {
*/
public JSONObject getFirstReferringParams() {
String storedParam = prefHelper_.getInstallParams();
- return convertParamsStringToDictionary(storedParam);
+ JSONObject firstReferringParams = convertParamsStringToDictionary(storedParam);
+ firstReferringParams = appendDebugParams(firstReferringParams);
+ return firstReferringParams;
}
/**
@@ -1717,7 +1730,33 @@ public class Branch {
*/
public JSONObject getLatestReferringParams() {
String storedParam = prefHelper_.getSessionParams();
- return convertParamsStringToDictionary(storedParam);
+ JSONObject latestParams = convertParamsStringToDictionary(storedParam);
+ latestParams = appendDebugParams(latestParams);
+ return latestParams;
+ }
+
+ /**
+ * Append the deep link debug params to the original params
+ *
+ * @param originalParams A {@link JSONObject} original referrer parameters
+ * @return A new {@link JSONObject} with debug params appended.
+ */
+ private JSONObject appendDebugParams(JSONObject originalParams) {
+ try {
+ if (originalParams != null && deeplinkDebugParams_ != null) {
+ Iterator<String> keys = deeplinkDebugParams_.keys();
+ while (keys.hasNext()) {
+ String key = keys.next();
+ originalParams.put(key, deeplinkDebugParams_.get(key));
+ }
+ }
+ } catch (Exception ignore) {
+ }
+ return originalParams;
+ }
+
+ public JSONObject getDeeplinkDebugParams(){
+ return deeplinkDebugParams_;
}
|
Adding <I>% deplane debug support
Adding API setDeepLinkDebugMode() to set the deep link debug
parameters. These parameters are returned back <I> % time with init
session callbacks
Note: This method should be called from onCreate() of activity which
listens to Branch Init Session
|
BranchMetrics_android-branch-deep-linking
|
train
|
a06b715c269292552d267537ab167bf51718278e
|
diff --git a/media/js/views/room.js b/media/js/views/room.js
index <HASH>..<HASH> 100644
--- a/media/js/views/room.js
+++ b/media/js/views/room.js
@@ -88,6 +88,18 @@
this.atwhoRooms();
this.atwhoEmotes();
},
+ getEmotes: function(cb) {
+ if (!window.LCB.RoomView.emotes) {
+ window.LCB.RoomView.emotes = $.get('/extras/emotes');
+ }
+ window.LCB.RoomView.emotes.success(cb);
+ },
+ getUsers: function(cb) {
+ if (!window.LCB.RoomView.users) {
+ window.LCB.RoomView.users = $.get('/users');
+ }
+ window.LCB.RoomView.users.success(cb);
+ },
atwhoTplEval: function(tpl, map) {
var error;
try {
@@ -138,16 +150,19 @@
});
}
- this.$('.lcb-entry-input')
- .atwho({
- at: '@',
- data: '/users',
- tpl: '<li data-value="@${username}"><img src="https://www.gravatar.com/avatar/${avatar}?s=20" height="20" width="20" /> @${username} <small>${displayName}</small></li>',
- callbacks: {
- filter: filter,
- sorter: sorter,
- tpl_eval: this.atwhoTplEval
- }
+ var that = this;
+ this.getUsers(function(users) {
+ that.$('.lcb-entry-input')
+ .atwho({
+ at: '@',
+ data: users,
+ tpl: '<li data-value="@${username}"><img src="https://www.gravatar.com/avatar/${avatar}?s=20" height="20" width="20" /> @${username} <small>${displayName}</small></li>',
+ callbacks: {
+ filter: filter,
+ sorter: sorter,
+ tpl_eval: that.atwhoTplEval
+ }
+ });
});
},
atwhoRooms: function() {
@@ -177,12 +192,15 @@
});
},
atwhoEmotes: function() {
- this.$('.lcb-entry-input')
- .atwho({
- at: ':',
- search_key: 'emote',
- data: '/extras/emotes',
- tpl: '<li data-value=":${emote}:"><img src="${image}" height="32" width="32" alt=":${emote}:" /> :${emote}:</li>'
+ var that = this;
+ this.getEmotes(function(emotes) {
+ that.$('.lcb-entry-input')
+ .atwho({
+ at: ':',
+ search_key: 'emote',
+ data: emotes,
+ tpl: '<li data-value=":${emote}:"><img src="${image}" height="32" width="32" alt=":${emote}:" /> :${emote}:</li>'
+ });
});
},
goodbye: function() {
|
Only load emotes and users once per window
|
sdelements_lets-chat
|
train
|
28b6aa71da1e6c844008eb9dadab3f2f19a7150c
|
diff --git a/CGRtools/files/MRVrw.py b/CGRtools/files/MRVrw.py
index <HASH>..<HASH> 100644
--- a/CGRtools/files/MRVrw.py
+++ b/CGRtools/files/MRVrw.py
@@ -415,8 +415,8 @@ class MRVWrite:
self._file.write('</molecule>')
self._file.write(f'</{j}>')
- self._file.write(f'<arrow type="DEFAULT" x1="{data._arrow[0]:.4f}" y1="1" x2="{data._arrow[1]:.4f}" '
- f'y2="1"/>')
+ self._file.write(f'<arrow type="DEFAULT" x1="{data._arrow[0] * 2:.4f}" y1="0" '
+ f'x2="{data._arrow[1] * 2:.4f}" y2="0"/>')
self._file.write('</reaction>')
self._file.write('</MChemicalStruct></MDocument>\n')
|
fixed MRW reaction arrow position
|
cimm-kzn_CGRtools
|
train
|
df4f211437a7a5c4b4e1bbc3df8fd1eee8d1aa76
|
diff --git a/lib/be_valid_asset.rb b/lib/be_valid_asset.rb
index <HASH>..<HASH> 100644
--- a/lib/be_valid_asset.rb
+++ b/lib/be_valid_asset.rb
@@ -1,10 +1,10 @@
module BeValidAsset
class Configuration
@@config = {
- :display_invalid_content => false,
- :enable_caching => false,
- :display_invalid_lines => false,
- :display_lines_around => 5
+ :display_invalid_content => false,
+ :enable_caching => false,
+ :display_invalid_lines => false,
+ :display_invalid_lines_count => 5
}
def self.method_missing(name, *args)
diff --git a/lib/be_valid_asset/be_valid_base.rb b/lib/be_valid_asset/be_valid_base.rb
index <HASH>..<HASH> 100644
--- a/lib/be_valid_asset/be_valid_base.rb
+++ b/lib/be_valid_asset/be_valid_base.rb
@@ -38,8 +38,8 @@ module BeValidAsset
@message << "#{error_line_prefix}: line #{e.elements['m:line'].text}: #{e.elements['m:message'].get_text.value.strip}\n"
if Configuration.display_invalid_lines
line_no = e.elements['m:line'].text.to_i
- start_line = [line_no - (Configuration.display_lines_around / 2), 1].max
- end_line = [line_no + (Configuration.display_lines_around / 2), lines.length].min
+ start_line = [line_no - (Configuration.display_invalid_lines_count / 2), 1].max
+ end_line = [line_no + (Configuration.display_invalid_lines_count / 2), lines.length].min
for i in start_line..end_line
@message << "#{'%04i' % i}#{ i == line_no ? '>>' : ' ' }: #{ lines[i - 1] }#{ $/ }"
end
diff --git a/spec/be_valid_asset/be_valid_xhtml_spec.rb b/spec/be_valid_asset/be_valid_xhtml_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/be_valid_asset/be_valid_xhtml_spec.rb
+++ b/spec/be_valid_asset/be_valid_xhtml_spec.rb
@@ -69,6 +69,7 @@ describe 'be_valid_xhtml' do
end
after :each do
BeValidAsset::Configuration.display_invalid_lines = false
+ BeValidAsset::Configuration.display_invalid_lines_count = 5 # Restore the default value
end
it "should display invalid lines when requested" do
@@ -88,7 +89,7 @@ describe 'be_valid_xhtml' do
end
it "should display specified invalid lines window when requested" do
- BeValidAsset::Configuration.display_lines_around = 3
+ BeValidAsset::Configuration.display_invalid_lines_count = 3
html = get_file('invalid.html')
lambda do
html.should be_valid_xhtml
@@ -100,11 +101,10 @@ describe 'be_valid_xhtml' do
e.message.should match(/0013 :/)
e.message.should_not match(/0014 :/)
}
- BeValidAsset::Configuration.display_lines_around = 5 # Restore the default value
end
it "should not underrun the beginning of the source" do
- BeValidAsset::Configuration.display_lines_around = 7
+ BeValidAsset::Configuration.display_invalid_lines_count = 7
html = get_file('invalid2.html')
lambda do
html.should be_valid_xhtml
@@ -114,11 +114,10 @@ describe 'be_valid_xhtml' do
e.message.should match(/0001 :/)
e.message.should match(/0003>>:/)
}
- BeValidAsset::Configuration.display_lines_around = 5 # Restore the default value
end
it "should not overrun the end of the source" do
- BeValidAsset::Configuration.display_lines_around = 11
+ BeValidAsset::Configuration.display_invalid_lines_count = 11
html = get_file('invalid.html')
lambda do
html.should be_valid_xhtml
@@ -128,7 +127,6 @@ describe 'be_valid_xhtml' do
e.message.should match(/0015 :/)
e.message.should_not match(/0016 :/)
}
- BeValidAsset::Configuration.display_lines_around = 5 # Restore the default value
end
end
|
Renamed config variable for number of lines to display.
|
unboxed_be_valid_asset
|
train
|
60c96d79f8326efd84bbe055d8b5ff66812b9b2f
|
diff --git a/core/Pimf/View/Twig.php b/core/Pimf/View/Twig.php
index <HASH>..<HASH> 100644
--- a/core/Pimf/View/Twig.php
+++ b/core/Pimf/View/Twig.php
@@ -63,7 +63,7 @@ class Twig extends View implements Reunitable
$root = String::ensureTrailing('/', dirname(dirname(dirname(dirname(dirname(__FILE__))))));
- require_once $root."Twig/lib/Autoloader.php";
+ require_once $root."Twig/lib/Twig/Autoloader.php";
\Twig_Autoloader::register();
|
make PIMF ready for #twig
|
gjerokrsteski_pimf-framework
|
train
|
5af98bc4453cc65260150305e9d0e585ec024ce0
|
diff --git a/src/main/java/de/biomedical_imaging/traj/math/PowerLawCurveFit.java b/src/main/java/de/biomedical_imaging/traj/math/PowerLawCurveFit.java
index <HASH>..<HASH> 100644
--- a/src/main/java/de/biomedical_imaging/traj/math/PowerLawCurveFit.java
+++ b/src/main/java/de/biomedical_imaging/traj/math/PowerLawCurveFit.java
@@ -64,8 +64,8 @@ public class PowerLawCurveFit {
doFit(xdata, ydata, method, false, 0, 0);
}
- public void doFit(double[] xdata, double[] ydata, FitMethod method,double initalAlpha, double initalDiffCoeff){
- doFit(xdata, ydata, method, initalAlpha, initalDiffCoeff);
+ public void doFit(double[] xdata, double[] ydata, FitMethod method, double initalAlpha, double initalDiffCoeff){
+ doFit(xdata, ydata, method, false, initalAlpha, initalDiffCoeff);
}
private void doFit(double[] xdata, double[] ydata, FitMethod method, boolean useInitialGuess, double initalAlpha, double initalDiffCoeff){
|
Fix overloaded public method doFit()
By default, run without using an initial guess.
|
thorstenwagner_TraJ
|
train
|
3611176b55718f91eca4d16b90baefd2fa3a7b0c
|
diff --git a/cy_scripts/convert.js b/cy_scripts/convert.js
index <HASH>..<HASH> 100644
--- a/cy_scripts/convert.js
+++ b/cy_scripts/convert.js
@@ -11,7 +11,8 @@ var glob = Promise.promisify(glob)
var startsWithNumberAndDashRe = /(\d+-)/
var excerptRe = /excerpt:.+/
var newLinesRe = /\n{3,}/
-var calloutRe = /\[block:callout\](\n.\s\s.+\n.+\n.+\n+.+\n)\[\/block\]/g
+var calloutGlobalRe = /\[block:callout\]([^]+?)\[\/block\]/g
+var calloutRe = /\[block:callout\]([^]+?)\[\/block\]/
var LOOKUP = {
guides: 'v0.0',
@@ -120,9 +121,23 @@ transfer = function(type) {
// Explore talks, blogs, and podcasts about testing in Cypress.
// {% endnote %}
- // matches = calloutRe.exec(string)
- //
- // return string
+ const callouts = string.match(calloutGlobalRe)
+ if (!callouts) return string
+
+ callouts
+ .map((callout) => callout.match(calloutRe))
+ .forEach((callout) => {
+ // callout[0] includes [block:callout]
+ // callout[1] is just the JSON string
+ let calloutData = JSON.parse(callout[1])
+
+ string = string.replace(
+ callout[0],
+ `{% note ${calloutData.type} ${calloutData.title ? calloutData.title : ''} %}\n${calloutData.body}\n{% endnote %}`
+ )
+ })
+
+ return string
})
.then(function(string) {
return fs.writeFileAsync(dest, string)
|
Added code to convert block callouts to note tags
|
cypress-io_cypress
|
train
|
0973b0541642d1b8010f8dd720e6c91a9a40da64
|
diff --git a/ui/src/status/fixtures.js b/ui/src/status/fixtures.js
index <HASH>..<HASH> 100644
--- a/ui/src/status/fixtures.js
+++ b/ui/src/status/fixtures.js
@@ -1,12 +1,12 @@
export const fixtureStatusPageCells = [
{
- i: 'c-bar-graphs-fly',
+ i: 'alerts-bar-graph',
isWidget: false,
x: 0,
y: 0,
w: 12,
h: 4,
- name: 'Alerts – Last 30 Days – Aspiring Bar Graph',
+ name: 'Alerts – Last 30 Days',
queries: [
{
query:
@@ -33,7 +33,7 @@ export const fixtureStatusPageCells = [
},
},
],
- type: 'line',
+ type: 'bar',
links: {
self: '/chronograf/v1/status/23/cells/c-bar-graphs-fly',
},
|
Modify status fixture graph type to 'bar'
Update bar graph fixture title to spec
|
influxdata_influxdb
|
train
|
1a2eb58535638609dd60d05fea54e4e8797b4ea5
|
diff --git a/src/main/java/nl/jqno/equalsverifier/api/MultipleTypeEqualsVerifierApi.java b/src/main/java/nl/jqno/equalsverifier/api/MultipleTypeEqualsVerifierApi.java
index <HASH>..<HASH> 100644
--- a/src/main/java/nl/jqno/equalsverifier/api/MultipleTypeEqualsVerifierApi.java
+++ b/src/main/java/nl/jqno/equalsverifier/api/MultipleTypeEqualsVerifierApi.java
@@ -1,5 +1,6 @@
package nl.jqno.equalsverifier.api;
+import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import nl.jqno.equalsverifier.ConfiguredEqualsVerifier;
@@ -20,7 +21,7 @@ public class MultipleTypeEqualsVerifierApi implements EqualsVerifierApi<Void> {
private final ConfiguredEqualsVerifier ev = new ConfiguredEqualsVerifier();
public MultipleTypeEqualsVerifierApi(List<Class<?>> types) {
- this.types = types;
+ this.types = new ArrayList<>(types);
}
/** {@inheritDoc} */
|
Multiple types: adds some defensive copying
|
jqno_equalsverifier
|
train
|
fdb4299eb2569c8e7e247ae6e57f42a746b83adc
|
diff --git a/autofit/non_linear/analysis/analysis.py b/autofit/non_linear/analysis/analysis.py
index <HASH>..<HASH> 100644
--- a/autofit/non_linear/analysis/analysis.py
+++ b/autofit/non_linear/analysis/analysis.py
@@ -127,7 +127,6 @@ class CombinedAnalysis(Analysis):
def func(child_paths, analysis):
analysis.save_attributes_for_aggregator(
child_paths,
- analysis
)
self._for_each_analysis(
@@ -187,6 +186,11 @@ class CombinedAnalysis(Analysis):
paths
)
+ def make_result(
+ self, samples, model, search
+ ):
+ return [analysis.make_result(samples, model, search) for analysis in self.analyses]
+
def __len__(self):
return len(self.analyses)
diff --git a/test_autofit/config/general.ini b/test_autofit/config/general.ini
index <HASH>..<HASH> 100644
--- a/test_autofit/config/general.ini
+++ b/test_autofit/config/general.ini
@@ -15,4 +15,7 @@ iterations_per_update=5000
ignore_prior_limits=False
[test]
-test_mode=False
\ No newline at end of file
+test_mode=False
+
+[analysis]
+n_cores=1
\ No newline at end of file
diff --git a/test_autofit/non_linear/test_analysis.py b/test_autofit/non_linear/test_analysis.py
index <HASH>..<HASH> 100644
--- a/test_autofit/non_linear/test_analysis.py
+++ b/test_autofit/non_linear/test_analysis.py
@@ -33,6 +33,16 @@ def test_visualise():
assert analysis_1.did_visualise is True
assert analysis_2.did_visualise is True
+def test_make_result():
+
+ analysis_1 = Analysis()
+ analysis_2 = Analysis()
+
+ result = (analysis_1 + analysis_2).make_result(
+ samples=None, model=None, search=None
+ )
+
+ assert len(result) == 2
def test_add_analysis():
assert (Analysis() + Analysis()).log_likelihood_function(
|
added make_result to CombinedAnalysis
|
rhayes777_PyAutoFit
|
train
|
9b7000939225adcd23acb74b3e3f4e58cd8bcda0
|
diff --git a/AltContainer.js b/AltContainer.js
index <HASH>..<HASH> 100644
--- a/AltContainer.js
+++ b/AltContainer.js
@@ -10,11 +10,13 @@ export default class AltContainer extends React.Component {
super(props)
const { store, stores } = props;
- if (!stores && !store) {
- throw new Error('Must define either store or stores')
- }
- if (stores && store) {
- throw new Error('Cannot define both store and stores')
+ if (process.env.NODE_ENV !== 'production') {
+ if (!stores && !store) {
+ throw new Error('Must define either store or stores')
+ }
+ if (stores && store) {
+ throw new Error('Cannot define both store and stores')
+ }
}
this.onStoreChange = this.onStoreChange.bind(this);
this.state = this._reduceState();
|
Move validations to dev stage only
|
koliseoapi_alt-ng
|
train
|
3a664d39f123959216f4526537d5ef3d11b553fd
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100755
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,9 @@
All Notable changes to `laravel-blade-javascript` will be documented in this file
+## 1.0.5 - 2016-08-01
+- fixed a bug where floats were casted to ints
+
## 1.0.4 - 2016-06-26
- removed type attribute on script tags
diff --git a/src/Transformers/NumericTransformer.php b/src/Transformers/NumericTransformer.php
index <HASH>..<HASH> 100644
--- a/src/Transformers/NumericTransformer.php
+++ b/src/Transformers/NumericTransformer.php
@@ -15,11 +15,11 @@ class NumericTransformer implements Transformer
}
/**
- * @param int $value
+ * @param float|int $value
*
- * @return int
+ * @return float|int
*/
- public function transform($value): int
+ public function transform($value)
{
return $value;
}
diff --git a/tests/BladeTest.php b/tests/BladeTest.php
index <HASH>..<HASH> 100644
--- a/tests/BladeTest.php
+++ b/tests/BladeTest.php
@@ -30,30 +30,41 @@ class BladeTest extends TestCase
}
/** @test */
- public function it_can_render_a_numeric_value()
+ public function it_can_render_a_boolean()
{
- $parameter = ['number' => 1];
+ $parameter = ['boolean' => true];
+
+ $this->assertEquals(
+ '<script>window[\'js\'] = window[\'js\'] || {};window[\'js\'][\'boolean\'] = true;</script>',
+ $this->renderView('variable', compact('parameter'))
+ );
+
+ $parameter = ['boolean' => false];
$this->assertEquals(
- '<script>window[\'js\'] = window[\'js\'] || {};window[\'js\'][\'number\'] = 1;</script>',
+ '<script>window[\'js\'] = window[\'js\'] || {};window[\'js\'][\'boolean\'] = false;</script>',
$this->renderView('variable', compact('parameter'))
);
}
/** @test */
- public function it_can_render_a_boolean()
+ public function it_can_render_an_integer()
{
- $parameter = ['boolean' => true];
+ $parameter = ['number' => 5];
$this->assertEquals(
- '<script>window[\'js\'] = window[\'js\'] || {};window[\'js\'][\'boolean\'] = true;</script>',
+ '<script>window[\'js\'] = window[\'js\'] || {};window[\'js\'][\'number\'] = 5;</script>',
$this->renderView('variable', compact('parameter'))
);
+ }
- $parameter = ['boolean' => false];
+ /** @test */
+ public function it_can_render_a_float()
+ {
+ $parameter = ['number' => 5.5];
$this->assertEquals(
- '<script>window[\'js\'] = window[\'js\'] || {};window[\'js\'][\'boolean\'] = false;</script>',
+ '<script>window[\'js\'] = window[\'js\'] || {};window[\'js\'][\'number\'] = 5.5;</script>',
$this->renderView('variable', compact('parameter'))
);
}
|
Fixed a bug where floats were casted to ints
|
spatie_laravel-blade-javascript
|
train
|
75686a493329fc8f813a3e7208eca908ad878b8c
|
diff --git a/watchdog/src/watchdog/briefkasten_watchdog/__init__.py b/watchdog/src/watchdog/briefkasten_watchdog/__init__.py
index <HASH>..<HASH> 100644
--- a/watchdog/src/watchdog/briefkasten_watchdog/__init__.py
+++ b/watchdog/src/watchdog/briefkasten_watchdog/__init__.py
@@ -232,11 +232,7 @@ def main(fs_config=None):
stream=sys.stdout, level=getattr(logging, config["log_level"].upper())
)
- errors = once(config)
- if len(errors) > 0:
- exit(1)
- else:
- exit(0)
+ once(config)
if __name__ == '__main__':
|
FIX: don't exit non-zero habitually
this should be reserved for when something goes wrong on a
infrastructure level, not to signal that the watchdog has found an isse
(as that will be handled via logging and alerting) otherwise this just
creates noise on the container level
|
ZeitOnline_briefkasten
|
train
|
4b9ce1c153483a5978c09a3446348a9b680a1ecd
|
diff --git a/vtki/plotting.py b/vtki/plotting.py
index <HASH>..<HASH> 100755
--- a/vtki/plotting.py
+++ b/vtki/plotting.py
@@ -197,25 +197,17 @@ def plot(var_item, off_screen=False, full_screen=False, screenshot=None,
else:
plotter.camera_position = cpos
- cpos = plotter.show(window_size=window_size,
+ result = plotter.show(window_size=window_size,
autoclose=False,
interactive=interactive,
- full_screen=full_screen)
-
- # take screenshot
- if screenshot:
- if screenshot == True:
- img = plotter.screenshot()
- else:
- img = plotter.screenshot(screenshot)
+ full_screen=full_screen,
+ screenshot=screenshot)
# close and return camera position and maybe image
plotter.close()
- if screenshot:
- return cpos, img
- else:
- return cpos
+ # Result will be handled by plotter.show(): cpos or [cpos, img]
+ return result
def plot_arrows(cent, direction, **kwargs):
@@ -1900,7 +1892,8 @@ class Plotter(BasePlotter):
def show(self, title=None, window_size=None, interactive=True,
- autoclose=True, interactive_update=False, full_screen=False):
+ autoclose=True, interactive_update=False, full_screen=False,
+ screenshot=False):
"""
Creates plotting window
@@ -1978,12 +1971,22 @@ class Plotter(BasePlotter):
img = PIL.Image.fromarray(self.screenshot())
disp = IPython.display.display(img)
+ # take screenshot
+ if screenshot:
+ if screenshot == True:
+ img = self.screenshot()
+ else:
+ img = self.screenshot(screenshot)
+
if autoclose:
self.close()
if self.notebook:
return disp
+ if screenshot:
+ return cpos, img
+
return cpos
def plot(self, *args, **kwargs):
|
Cleanup for windows plotting window close bug
|
vtkiorg_vtki
|
train
|
6b416b4740b93515d665d3a609d8385a26801c48
|
diff --git a/testware/src/main/java/org/datacleaner/cli/JobTestHelper.java b/testware/src/main/java/org/datacleaner/cli/JobTestHelper.java
index <HASH>..<HASH> 100644
--- a/testware/src/main/java/org/datacleaner/cli/JobTestHelper.java
+++ b/testware/src/main/java/org/datacleaner/cli/JobTestHelper.java
@@ -41,7 +41,9 @@ public class JobTestHelper {
public static void testJob(final File repository, final String jobName, final Map<String, String[]> expectedResultSets,
final String... extraCLIArgs) throws Exception {
- final InputStream resultInputStream = new ByteArrayInputStream(runJob(repository, jobName, extraCLIArgs).getBytes());
+ final String jobResult = runJob(repository, jobName, extraCLIArgs);
+
+ final InputStream resultInputStream = new ByteArrayInputStream(jobResult.getBytes());
final InputStreamReader resultInputStreamReader = new InputStreamReader(resultInputStream);
final BufferedReader resultReader = new BufferedReader(resultInputStreamReader);
@@ -71,7 +73,7 @@ public class JobTestHelper {
}
}
- assertEquals(0, expectedResultSets.size());
+ assertEquals("CLI result:" + System.lineSeparator() + jobResult, 0, expectedResultSets.size());
} finally {
resultReader.close();
resultInputStreamReader.close();
|
Log the output produced by the CLI when the test doesn't produce the expected (number of) resultsets, because it will typically contain a usefull error message in that case. (#<I>)
|
datacleaner_DataCleaner
|
train
|
b34e9d5a7ca9c7fffad7260c9331ecbee7e9c68f
|
diff --git a/lib/multi_mail/mandrill/sender.rb b/lib/multi_mail/mandrill/sender.rb
index <HASH>..<HASH> 100644
--- a/lib/multi_mail/mandrill/sender.rb
+++ b/lib/multi_mail/mandrill/sender.rb
@@ -27,7 +27,7 @@ module MultiMail
end
- ## extract html part
+ ## extract html
html = mail.parts.find do |part|
part.content_type == 'text/html; charset=UTF-8'
end
@@ -42,15 +42,25 @@ module MultiMail
}
end
+ ## extract images
+ images = attachments.find do |a|
+ a[:type].start_with?('image/')
+ end
+ attachments.reject! {|a| a[:type].start_with?('image/')}
+
message = {
+ :html => html,
+ :text => mail.body.decoded,
:subject => mail[:subject].to_s,
+ :from_email => smtp_from,
:from_name => mail[:from].display_names.first, #change this
- :text => mail.body.decoded,
:to => to,
- :html => html,
- :from_email => smtp_from,
- :attachments => attachments
+ :headers => mail[:headers],
+ :bcc_address => mail.bcc,
+ :attachments => attachments,
+ :images => images,
+ :tags => mail[:tags]
}
response = m.messages.send message
diff --git a/spec/mandrill/sender_spec.rb b/spec/mandrill/sender_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/mandrill/sender_spec.rb
+++ b/spec/mandrill/sender_spec.rb
@@ -21,11 +21,11 @@ describe MultiMail::Sender::Mandrill do
})
end
-# let :tagged_message do
-# message.tap do |m|
-# m.tag "postmark-gem"
-# end
-# end
+ let :tagged_message do
+ message.tap do |m|
+ m[:tag] = "postmark-gem"
+ end
+ end
let :message_with_no_body do
Mail.new do
@@ -88,22 +88,22 @@ describe MultiMail::Sender::Mandrill do
end
end
- it 'rejects an invalid email address' do
- expect { service.deliver!(message_with_invalid_to) }.to raise_error
+ it 'delivers a tagged message' do
+ service.deliver!(tagged_message)[0]["status"].should eq "sent"
end
-# it 'delivers a tagged message' do
-# service.deliver!(tagged_message)[0]["status"].should eq "sent"
-# end
-
- it 'delivers a message with attachment' do
- service.deliver!(message_with_attachment)[0]["status"].should eq "queued"
- end
+ it 'delivers a message with attachment' do
+ service.deliver!(message_with_attachment)[0]["status"].should eq "queued"
+ end
- it 'sends multipart emails' do
- service.deliver!(multipart_message)[0]['status'].should eq "sent"
- end
+ it 'delivers multipart emails' do
+ service.deliver!(multipart_message)[0]['status'].should eq "sent"
+ end
+ it 'rejects an invalid email' do
+ expect { service.deliver!(message_with_invalid_to) }.to raise_error
+ expect { service.deliver!(message_with_no_body) }.to raise_error
+ end
end
end
diff --git a/spec/postmark/sender_spec.rb b/spec/postmark/sender_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/postmark/sender_spec.rb
+++ b/spec/postmark/sender_spec.rb
@@ -61,6 +61,7 @@ describe MultiMail::Sender::Postmark do
end
describe '#deliver' do
+
it 'sends email' do
service.deliver!(message)
message.delivered.should eq true
@@ -71,6 +72,11 @@ describe MultiMail::Sender::Postmark do
response["To"].should eq message[:to].to_s
end
+ it 'sends to multiple recipients' do
+ response = service.deliver!(message).postmark_response
+ response["To"].split(',').size.should eq 2
+ end
+
it 'updates a message object with full postmark response' do
expect { service.deliver!(message) }.to change{message.postmark_response}.from(nil)
end
@@ -91,11 +97,7 @@ describe MultiMail::Sender::Postmark do
expect { service.deliver!(message_with_invalid_to) }.to raise_error
expect { service.deliver!(message_with_no_body) }.to raise_error
end
-
end
-
-
-
end
context 'after initialization without api_key' do
|
tests standardized, more fields added to mandrill
|
jpmckinney_multi_mail
|
train
|
22d02a0df2d28706b472244458ae4dc9a15aee62
|
diff --git a/lib/cf/cli/space/delete.rb b/lib/cf/cli/space/delete.rb
index <HASH>..<HASH> 100644
--- a/lib/cf/cli/space/delete.rb
+++ b/lib/cf/cli/space/delete.rb
@@ -39,6 +39,7 @@ module CF::Space
line c(boom.description, :bad)
line c("If you want to delete the space along with all dependent objects, rerun the command with the #{b("'--recursive'")} flag.", :bad)
exit_status(1)
+ return
end
end
diff --git a/spec/cf/cli/space/delete_spec.rb b/spec/cf/cli/space/delete_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/cf/cli/space/delete_spec.rb
+++ b/spec/cf/cli/space/delete_spec.rb
@@ -65,12 +65,25 @@ describe CF::Space::Delete do
end
context "when deleting the current space" do
- it "warns the user what they've done" do
+ before do
stub(client).current_space { space }
+ end
+ it "warns the user what they've done" do
subject
expect(output).to say("The space that you were targeting has now been deleted. Please use `cf target -s SPACE_NAME` to target a different one.")
end
+
+ context "when the current space has dependent objects" do
+ before do
+ stub(space).delete! { raise CFoundry::AssociationNotEmpty.new("We don't delete children.", 10006) }
+ end
+
+ it "does not print a success message" do
+ subject
+ expect(output).to_not say("The space that you were targeting has now been deleted")
+ end
+ end
end
context "when a space fails to delete" do
|
Dont return misleading messages when the current space fails to delete
[#<I>]
|
cloudfoundry-attic_cf
|
train
|
d2f65f223638f0ace70525c564c1ae5304a2b5f8
|
diff --git a/src/ApiClient.php b/src/ApiClient.php
index <HASH>..<HASH> 100644
--- a/src/ApiClient.php
+++ b/src/ApiClient.php
@@ -26,6 +26,8 @@ use Illuminate\Support\Facades\Cache;
* @method getRequest()
* @method setRequest(Request $request)
* @method getResponse()
+ *
+ * @mixin \EthicalJobs\SDK\HttpClient
*/
class ApiClient
{
@@ -118,12 +120,12 @@ class ApiClient
/**
* Dynamic http verb methods
*
- * @param String $name
- * @param array $arguments
+ * @param string $name
+ * @param array<int|string, mixed> $arguments
* @return Mixed
* @throws Exception
*/
- public function __call($name, $arguments)
+ public function __call(string $name, array $arguments)
{
if (method_exists($this->http, $name)) {
return $this->http->$name(...$arguments);
|
Add types to ApiClient
|
ethical-jobs_sdk-php
|
train
|
8edbc581c1b0e0d9f325ab0320af8b78359f0917
|
diff --git a/zipline/gens/utils.py b/zipline/gens/utils.py
index <HASH>..<HASH> 100644
--- a/zipline/gens/utils.py
+++ b/zipline/gens/utils.py
@@ -8,26 +8,29 @@ from itertools import izip_longest
from zipline import ndict
from zipline.protocol import DATASOURCE_TYPE
+
def mock_raw_event(sid, dt):
event = {
- 'sid' : sid,
- 'dt' : dt,
- 'price' : 1.0,
- 'volume' : 1
+ 'sid': sid,
+ 'dt': dt,
+ 'price': 1.0,
+ 'volume': 1
}
return event
+
def mock_done(id):
return ndict({
- 'dt' : "DONE",
- "source_id" : id,
- 'tnfm_id' : id,
+ 'dt': "DONE",
+ "source_id": id,
+ 'tnfm_id': id,
'tnfm_value': None,
- 'type' : DATASOURCE_TYPE.DONE
+ 'type': DATASOURCE_TYPE.DONE
})
done_message = mock_done
+
def alternate(g1, g2):
"""Specialized version of roundrobin for just 2 generators."""
for e1, e2 in izip_longest(g1, g2):
@@ -36,6 +39,7 @@ def alternate(g1, g2):
if e2 != None:
yield e2
+
def roundrobin(sources, namestrings):
"""
Takes N generators, pulling one element off each until all inputs
@@ -56,32 +60,36 @@ def roundrobin(sources, namestrings):
yield done_message(namestring)
del mapping[namestring]
+
def hash_args(*args, **kwargs):
"""Define a unique string for any set of representable args."""
arg_string = '_'.join([str(arg) for arg in args])
- kwarg_string = '_'.join([str(key) + '=' + str(value) for key, value in kwargs.iteritems()])
+ kwarg_string = '_'.join([str(key) + '=' + str(value)
+ for key, value in kwargs.iteritems()])
combined = ':'.join([arg_string, kwarg_string])
hasher = md5()
hasher.update(combined)
return hasher.hexdigest()
-def create_trade(sid, price, amount, datetime, source_id = "test_factory"):
+
+def create_trade(sid, price, amount, datetime, source_id="test_factory"):
row = ndict({
- 'source_id' : source_id,
- 'type' : DATASOURCE_TYPE.TRADE,
- 'sid' : sid,
- 'dt' : datetime,
- 'price' : price,
- 'close' : price,
- 'open' : price,
- 'low' : price * .95,
- 'high' : price * 1.05,
- 'volume' : amount
+ 'source_id': source_id,
+ 'type': DATASOURCE_TYPE.TRADE,
+ 'sid': sid,
+ 'dt': datetime,
+ 'price': price,
+ 'close': price,
+ 'open': price,
+ 'low': price * .95,
+ 'high': price * 1.05,
+ 'volume': amount
})
return row
+
def sum_true(bool_iterable):
"""
Takes an iterable of boolean values and returns the number of
@@ -102,6 +110,7 @@ def assert_datasource_protocol(event):
assert isinstance(event.dt, datetime)
assert event.dt.tzinfo == pytz.utc
+
def assert_trade_protocol(event):
"""Assert that an event meets the protocol for datasource TRADE outputs."""
assert_datasource_protocol(event)
@@ -113,32 +122,38 @@ def assert_trade_protocol(event):
assert isinstance(event.volume, numbers.Integral)
assert isinstance(event.dt, datetime)
+
def assert_datasource_unframe_protocol(event):
"""Assert that an event is valid output of zp.DATASOURCE_UNFRAME."""
assert isinstance(event, ndict)
assert isinstance(event.source_id, basestring)
assert event.type in DATASOURCE_TYPE
- assert event.has_key('dt')
+ assert 'dt' in event
+
def assert_sort_protocol(event):
"""Assert that an event is valid input to zp.FEED_FRAME."""
assert isinstance(event, ndict)
assert isinstance(event.source_id, basestring)
assert event.type in DATASOURCE_TYPE
- assert event.has_key('dt')
+ assert 'dt' in event
+
def assert_sort_unframe_protocol(event):
"""Same as above."""
assert isinstance(event, ndict)
assert isinstance(event.source_id, basestring)
assert event.type in DATASOURCE_TYPE
- assert event.has_key('dt')
+ assert 'dt' in event
+
def assert_transform_protocol(event):
"""Transforms should return an ndict to be merged by merge."""
assert isinstance(event, ndict)
+
def assert_merge_protocol(tnfm_ids, message):
- """Merge should output an ndict with a field for each id in its transform set."""
+ """Merge should output an ndict with a field for each id
+ in its transform set."""
assert isinstance(message, ndict)
assert set(tnfm_ids) == set(message.keys())
|
Applies PEP-8 recommendations.
Whitespace wrangling.
|
quantopian_zipline
|
train
|
69b7ccd79d0d3bf03aa440b429e780b081425296
|
diff --git a/spec/factories/repositories.rb b/spec/factories/repositories.rb
index <HASH>..<HASH> 100644
--- a/spec/factories/repositories.rb
+++ b/spec/factories/repositories.rb
@@ -23,7 +23,6 @@ FactoryGirl.define do
scm_type "GIT"
address "https://github.com/rafamanzo/runge-kutta-vtk.git"
kalibro_configuration_id 1
- send_email "test@test.com"
end
factory :ruby_repository, class: Repository do
@@ -35,7 +34,6 @@ FactoryGirl.define do
scm_type "GIT"
address "https://github.com/mezuro/kalibro_processor.git"
kalibro_configuration_id 1
- send_email "test@test.com"
end
factory :another_repository, parent: :repository do
|
Fixes Repository factory after kalibro_client update
|
mezuro_prezento
|
train
|
2982f1bc2f85014590003feb50e793b9a7ae8b70
|
diff --git a/pom.xml b/pom.xml
index <HASH>..<HASH> 100644
--- a/pom.xml
+++ b/pom.xml
@@ -35,7 +35,7 @@
<dependency>
<groupId>com.blackducksoftware.integration</groupId>
<artifactId>hub-common-response</artifactId>
- <version>3.7.0</version>
+ <version>3.8.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.blackducksoftware.integration</groupId>
diff --git a/src/main/java/com/blackducksoftware/integration/hub/api/item/MetaService.java b/src/main/java/com/blackducksoftware/integration/hub/api/item/MetaService.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/blackducksoftware/integration/hub/api/item/MetaService.java
+++ b/src/main/java/com/blackducksoftware/integration/hub/api/item/MetaService.java
@@ -84,6 +84,8 @@ public class MetaService {
public static final String TEXT_LINK = "text";
+ public static final String ROLES_LINK = "roles";
+
private final IntLogger logger;
public MetaService(final IntLogger logger) {
diff --git a/src/main/java/com/blackducksoftware/integration/hub/dataservice/user/UserDataService.java b/src/main/java/com/blackducksoftware/integration/hub/dataservice/user/UserDataService.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/blackducksoftware/integration/hub/dataservice/user/UserDataService.java
+++ b/src/main/java/com/blackducksoftware/integration/hub/dataservice/user/UserDataService.java
@@ -31,6 +31,7 @@ import com.blackducksoftware.integration.hub.api.item.MetaService;
import com.blackducksoftware.integration.hub.api.user.UserRequestService;
import com.blackducksoftware.integration.hub.model.view.AssignedProjectView;
import com.blackducksoftware.integration.hub.model.view.ProjectView;
+import com.blackducksoftware.integration.hub.model.view.RoleView;
import com.blackducksoftware.integration.hub.model.view.UserView;
import com.blackducksoftware.integration.hub.rest.RestConnection;
import com.blackducksoftware.integration.hub.service.HubResponseService;
@@ -71,4 +72,16 @@ public class UserDataService extends HubResponseService {
return resolvedProjectViews;
}
+ public List<RoleView> getRolesForUser(final String userName) throws IntegrationException {
+ final UserView user = userRequestService.getUserByUserName(userName);
+ return getRolesForUser(user);
+ }
+
+ public List<RoleView> getRolesForUser(final UserView userView) throws IntegrationException {
+ final String userRolesLink = metaService.getFirstLink(userView, MetaService.ROLES_LINK);
+ final List<RoleView> assignedRoles = this.getAllItems(userRolesLink, RoleView.class);
+
+ return assignedRoles;
+ }
+
}
diff --git a/src/test/groovy/com/blackducksoftware/integration/hub/dataservice/user/UserDataServiceTestIT.java b/src/test/groovy/com/blackducksoftware/integration/hub/dataservice/user/UserDataServiceTestIT.java
index <HASH>..<HASH> 100644
--- a/src/test/groovy/com/blackducksoftware/integration/hub/dataservice/user/UserDataServiceTestIT.java
+++ b/src/test/groovy/com/blackducksoftware/integration/hub/dataservice/user/UserDataServiceTestIT.java
@@ -24,11 +24,15 @@
package com.blackducksoftware.integration.hub.dataservice.user;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import java.util.List;
+import org.junit.Test;
+
import com.blackducksoftware.integration.exception.IntegrationException;
import com.blackducksoftware.integration.hub.model.view.ProjectView;
+import com.blackducksoftware.integration.hub.model.view.RoleView;
import com.blackducksoftware.integration.hub.rest.RestConnection;
import com.blackducksoftware.integration.hub.rest.RestConnectionTestHelper;
import com.blackducksoftware.integration.hub.rest.TestingPropertyKey;
@@ -48,4 +52,15 @@ public class UserDataServiceTestIT {
final List<ProjectView> projectsForUser = userDS.getProjectsForUser(restConnectionTestHelper.getTestUsername());
assertNotNull(projectsForUser);
}
+
+ @Test
+ public void getRolesForUserTestIT() throws IllegalArgumentException, IntegrationException {
+ final RestConnection connection = restConnectionTestHelper.getIntegrationHubRestConnection();
+ final HubServicesFactory hubServicesFactory = restConnectionTestHelper.createHubServicesFactory();
+
+ final UserDataService userDS = new UserDataService(connection, hubServicesFactory.createUserRequestService(), hubServicesFactory.createMetaService());
+
+ final List<RoleView> rolesForUser = userDS.getRolesForUser(restConnectionTestHelper.getTestUsername());
+ assertTrue(rolesForUser.size() == 4);
+ }
}
|
Added ability to get user role through user data service
|
blackducksoftware_blackduck-common
|
train
|
ef5efaf0d911754ce5c372a14c34d289085ed994
|
diff --git a/config.rb b/config.rb
index <HASH>..<HASH> 100644
--- a/config.rb
+++ b/config.rb
@@ -42,6 +42,8 @@ set :images_dir, 'images'
# Build-specific configuration
configure :build do
+ ignore 'base.haml'
+
# For example, change the Compass output style for deployment
# activate :minify_css
|
Added file to ignore when `middleman build`
|
tyom_stratum
|
train
|
7efbd62b2240523c7a492e5aa1e74423f53128bf
|
diff --git a/lib/jsonld-signatures.js b/lib/jsonld-signatures.js
index <HASH>..<HASH> 100644
--- a/lib/jsonld-signatures.js
+++ b/lib/jsonld-signatures.js
@@ -252,7 +252,7 @@ api.verify = util.callbackify(async function(input, options) {
// of them may be is known in advance.)
const [expanded] = await jsonld.expand(input, opts);
const framed = await jsonld.compact(
- input, constants.SECURITY_CONTEXT_URL, opts);
+ expanded, constants.SECURITY_CONTEXT_URL, {...opts, skipExpansion: true});
// ensure there is at least one `proof` or `signature`
const proofs = jsonld.getValues(framed, 'signature')
|
Use the expanded input for compaction.
|
digitalbazaar_jsonld-signatures
|
train
|
1ecd3cca3a9717aceb33a3327e32f787ae3b79c3
|
diff --git a/languagetool-language-modules/uk/src/main/java/org/languagetool/rules/uk/MixedAlphabetsRule.java b/languagetool-language-modules/uk/src/main/java/org/languagetool/rules/uk/MixedAlphabetsRule.java
index <HASH>..<HASH> 100644
--- a/languagetool-language-modules/uk/src/main/java/org/languagetool/rules/uk/MixedAlphabetsRule.java
+++ b/languagetool-language-modules/uk/src/main/java/org/languagetool/rules/uk/MixedAlphabetsRule.java
@@ -42,7 +42,7 @@ public class MixedAlphabetsRule extends Rule {
private static final Pattern LIKELY_LATIN_NUMBER = Pattern.compile("[XVIХІ]{2,8}");
private static final Pattern LATIN_NUMBER_WITH_CYRILLICS = Pattern.compile("Х{1,3}І{1,3}|І{1,3}Х{1,3}|Х{2,3}|І{2,3}");
- private static final Pattern MIXED_ALPHABETS = Pattern.compile(".*([a-zA-Z]'?[а-яіїєґА-ЯІЇЄҐ]|[а-яіїєґА-ЯІЇЄҐ]'?[a-zA-Z]).*");
+ private static final Pattern MIXED_ALPHABETS = Pattern.compile(".*([a-zA-ZïáÁéÉíÍḯḮóÓúýÝ]'?[а-яіїєґА-ЯІЇЄҐ]|[а-яіїєґА-ЯІЇЄҐ]'?[a-zA-ZïáÁéÉíÍḯḮóÓúýÝ]).*");
private static final Pattern CYRILLIC_ONLY = Pattern.compile(".*[бвгґдєжзийїлнпфцчшщьюяБГҐДЄЖЗИЙЇЛПФЦЧШЩЬЮЯ].*");
private static final Pattern LATIN_ONLY = Pattern.compile(".*[bdfghjlqrstvzDFGJLNQRSUVZ].*");
private static final Pattern COMMON_CYR_LETTERS = Pattern.compile("[АВЕІКОРСТУХ]+");
@@ -157,8 +157,10 @@ public class MixedAlphabetsRule extends Rule {
private static final Map<Character, Character> toLatMap = new HashMap<>();
private static final Map<Character, Character> toCyrMap = new HashMap<>();
- private static final String cyrChars = "аеікморстухАВЕІКМНОРСТУХ";
- private static final String latChars = "aeikmopctyxABEIKMHOPCTYX";
+ private static final String cyrChars = "аеіїкморстухАВЕІКМНОРСТУХ";
+ private static final String latChars = "aeiïkmopctyxABEIKMHOPCTYX";
+ private static final String[] umlauts = { "á", "Á", "é", "É", "í", "Í", "ḯ", "Ḯ", "ó", "Ó", "ú", "ý", "Ý" };
+ private static final String[] umlautsReplace = { "а́", "А́", "е́", "Е́", "і́", "І́", "ї́", "Ї́", "о́", "О́", "и́", "у́", "У́" };
static {
for (int i = 0; i < cyrChars.length(); i++) {
@@ -171,6 +173,9 @@ public class MixedAlphabetsRule extends Rule {
for (Map.Entry<Character, Character> entry : toCyrMap.entrySet()) {
word = word.replace(entry.getKey(), entry.getValue());
}
+ for(int i=0; i<umlauts.length; i++) {
+ word = word.replace(umlauts[i], umlautsReplace[i]);
+ }
return word;
}
diff --git a/languagetool-language-modules/uk/src/test/java/org/languagetool/rules/uk/MixedAlphabetsRuleTest.java b/languagetool-language-modules/uk/src/test/java/org/languagetool/rules/uk/MixedAlphabetsRuleTest.java
index <HASH>..<HASH> 100644
--- a/languagetool-language-modules/uk/src/test/java/org/languagetool/rules/uk/MixedAlphabetsRuleTest.java
+++ b/languagetool-language-modules/uk/src/test/java/org/languagetool/rules/uk/MixedAlphabetsRuleTest.java
@@ -52,7 +52,12 @@ public class MixedAlphabetsRuleTest {
assertEquals(1, matches.length);
assertEquals(Arrays.asList("mixed"), matches[0].getSuggestedReplacements());
-
+
+ matches = rule.match(langTool.getAnalyzedSentence("горíти")); // umlaut instead of accented і
+
+ assertEquals(1, matches.length);
+ assertEquals(Arrays.asList("горі́ти"), matches[0].getSuggestedReplacements());
+
matches = rule.match(langTool.getAnalyzedSentence("XІ")); // cyrillic І and latin X
assertEquals(1, matches.length);
@@ -75,7 +80,7 @@ public class MixedAlphabetsRuleTest {
matches = rule.match(langTool.getAnalyzedSentence("група А")); // cyrillic А
assertEquals(1, matches.length);
assertEquals("A", matches[0].getSuggestedReplacements().get(0));
-
+
matches = rule.match(langTool.getAnalyzedSentence("На 0,6°С.")); // cyrillic С
assertEquals(1, matches.length);
assertEquals("0,6°C", matches[0].getSuggestedReplacements().get(0));
|
[uk] detect umlauts used as stressed Ukrainian letters
|
languagetool-org_languagetool
|
train
|
eaedd4347ff38ec38cf4b467859ae115e535d1b2
|
diff --git a/zap/src/main/java/org/zaproxy/zap/view/AbstractFormDialog.java b/zap/src/main/java/org/zaproxy/zap/view/AbstractFormDialog.java
index <HASH>..<HASH> 100644
--- a/zap/src/main/java/org/zaproxy/zap/view/AbstractFormDialog.java
+++ b/zap/src/main/java/org/zaproxy/zap/view/AbstractFormDialog.java
@@ -24,6 +24,7 @@ import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Rectangle;
+import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
@@ -235,9 +236,17 @@ public abstract class AbstractFormDialog extends JDialog {
private void centreOnOwner() {
Dimension frameSize = this.getSize();
- Rectangle mainrect = getOwner().getBounds();
+ Rectangle mainrect = getMainRectangle();
int x = mainrect.x + (mainrect.width - frameSize.width) / 2;
int y = mainrect.y + (mainrect.height - frameSize.height) / 2;
this.setLocation(x, y);
}
+
+ private Rectangle getMainRectangle() {
+ Window owner = getOwner();
+ if (owner != null) {
+ return owner.getBounds();
+ }
+ return new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
+ }
}
|
Centre dialogue on screen if no owner
Change `AbstractFormDialog` to centre the dialogue on the screen when
it has no owner.
|
zaproxy_zaproxy
|
train
|
ffc8dd43ab4d519b648c1ae2ee6bd6f26523c060
|
diff --git a/src/Spork/Fifo.php b/src/Spork/Fifo.php
index <HASH>..<HASH> 100644
--- a/src/Spork/Fifo.php
+++ b/src/Spork/Fifo.php
@@ -35,7 +35,7 @@ class Fifo
$this->pid = $pid;
foreach (array_combine($directions, $modes) as $direction => $mode) {
- $fifo = realpath(sys_get_temp_dir()).'/spork'.$this->pid.'.'.$direction;
+ $fifo = $this->getPath($direction);
if (!file_exists($fifo) && !posix_mkfifo($fifo, 0600) && 17 !== $error = posix_get_last_error()) {
throw new ProcessControlException(sprintf('Error while creating FIFO: %s (%d)', posix_strerror($error), $error));
@@ -96,4 +96,20 @@ class Fifo
fclose($this->write);
}
}
+
+ public function cleanup()
+ {
+ foreach (array('up', 'down') as $direction) {
+ if (file_exists($path = $this->getPath($direction))) {
+ unlink($path);
+ }
+ }
+ }
+
+ // private
+
+ private function getPath($direction)
+ {
+ return realpath(sys_get_temp_dir()).'/spork'.$this->pid.'.'.$direction;
+ }
}
diff --git a/src/Spork/Fork.php b/src/Spork/Fork.php
index <HASH>..<HASH> 100644
--- a/src/Spork/Fork.php
+++ b/src/Spork/Fork.php
@@ -83,6 +83,7 @@ class Fork implements DeferredInterface
if ($this->isExited()) {
list($this->result, $this->output, $this->error) = $this->fifo->receive();
$this->fifo->close();
+ $this->fifo->cleanup();
$this->isSuccessful() ? $this->resolve() : $this->reject();
|
cleanup fifos
closes #<I>
|
kriswallsmith_spork
|
train
|
3307b410b4dd2b0fdcebe2d740985a52d90fcc68
|
diff --git a/pyrogram/client/filters/filters.py b/pyrogram/client/filters/filters.py
index <HASH>..<HASH> 100644
--- a/pyrogram/client/filters/filters.py
+++ b/pyrogram/client/filters/filters.py
@@ -265,26 +265,34 @@ class Filters:
and message.from_user.username.lower() in self))
)
- @staticmethod
- def chat(chat: int or str or list):
- """Filter messages coming from specific chats.
+ # noinspection PyPep8Naming
+ class chat(Filter, set):
+ """Filter messages coming from one or more chats.
+
+ You can use `set bound methods <https://docs.python.org/3/library/stdtypes.html#set>`_ to manipulate the
+ chats container.
Args:
- chat (``int`` | ``str`` | ``list``):
- The chat or list of chat IDs (int) or usernames (str) the filter should look for.
+ chats (``int`` | ``str`` | ``list``):
+ Pass one or more chat ids/usernames to filter the chats.
+ Defaults to None (no chats).
"""
- return create(
- "Chat",
- lambda _, m: bool(m.chat
- and (m.chat.id in _.c
- or (m.chat.username
- and m.chat.username.lower() in _.c))),
- c=(
- {chat.lower().strip("@") if type(chat) is str else chat}
- if not isinstance(chat, list)
- else {i.lower().strip("@") if type(i) is str else i for i in chat}
+
+ def __init__(self, chats: int or str or list = None):
+ chats = [] if chats is None else chats if type(chats) is list else [chats]
+ super().__init__(
+ {i.lower().strip("@") if type(i) is str else i for i in chats}
+ if type(chats) is list else
+ {chats.lower().strip("@") if type(chats) is str else chats}
+ )
+
+ def __call__(self, message):
+ return bool(
+ message.chat
+ and (message.chat.id in self
+ or (message.chat.username
+ and message.chat.username.lower() in self))
)
- )
service = create(
"Service",
|
Give superpowers to Filters.chat too
It can now add and remove chats at runtime
|
pyrogram_pyrogram
|
train
|
4236161fa19afd556b34e5bcc7d674b10d551d73
|
diff --git a/src/Core/Checkout/Order/OrderDefinition.php b/src/Core/Checkout/Order/OrderDefinition.php
index <HASH>..<HASH> 100644
--- a/src/Core/Checkout/Order/OrderDefinition.php
+++ b/src/Core/Checkout/Order/OrderDefinition.php
@@ -96,20 +96,4 @@ class OrderDefinition extends EntityDefinition
{
return OrderEntity::class;
}
-
- public static function getWriteOrder(): array
- {
- $order = parent::getWriteOrder();
-
- $deliveryIndex = array_search(OrderDeliveryDefinition::class, $order, true);
- $lineItemIndex = array_search(OrderLineItemDefinition::class, $order, true);
-
- $max = max($deliveryIndex, $lineItemIndex);
- $min = min($deliveryIndex, $lineItemIndex);
-
- $order[$max] = OrderDeliveryDefinition::class;
- $order[$min] = OrderLineItemDefinition::class;
-
- return $order;
- }
}
diff --git a/src/Core/Framework/DataAbstractionLayer/Write/Command/WriteCommandQueue.php b/src/Core/Framework/DataAbstractionLayer/Write/Command/WriteCommandQueue.php
index <HASH>..<HASH> 100644
--- a/src/Core/Framework/DataAbstractionLayer/Write/Command/WriteCommandQueue.php
+++ b/src/Core/Framework/DataAbstractionLayer/Write/Command/WriteCommandQueue.php
@@ -3,6 +3,11 @@
namespace Shopware\Core\Framework\DataAbstractionLayer\Write\Command;
use Shopware\Core\Framework\DataAbstractionLayer\EntityDefinition;
+use Shopware\Core\Framework\DataAbstractionLayer\Field\Field;
+use Shopware\Core\Framework\DataAbstractionLayer\Field\ManyToOneAssociationField;
+use Shopware\Core\Framework\DataAbstractionLayer\Field\OneToManyAssociationField;
+use Shopware\Core\Framework\DataAbstractionLayer\FieldCollection;
+use Shopware\Core\Framework\DataAbstractionLayer\Write\Flag\ReadOnly;
use Shopware\Core\System\Language\LanguageDefinition;
class WriteCommandQueue
@@ -106,21 +111,74 @@ class WriteCommandQueue
*/
public function getCommandsInOrder(): array
{
- $result = [];
- foreach ($this->order as $identifier) {
- $commands = $this->commands[$identifier];
+ $commands = array_filter($this->commands);
+
+ $order = [];
- /** @var WriteCommandInterface $command */
- foreach ($commands as $command) {
- if (!$command->isValid()) {
+ while (!empty($commands)) {
+ foreach ($commands as $definition => $defCommands) {
+ $dependencies = $this->hasDependencies($definition, $commands);
+
+ if (!empty($dependencies)) {
continue;
}
- $result[] = $command;
+ foreach ($defCommands as $command) {
+ $order[] = $command;
+ }
+
+ unset($commands[$definition]);
+ }
+ }
+
+ return $order;
+ }
+
+ public function hasDependencies(string $definition, array $commands): array
+ {
+ /** @var string|EntityDefinition $definition */
+ $fields = $definition::getFields()
+ ->filter(function (Field $field) {
+ return !$field->is(ReadOnly::class) && $field instanceof ManyToOneAssociationField;
+ });
+
+ $toManyDefinitions = $definition::getFields()
+ ->filterInstance(OneToManyAssociationField::class)
+ ->fmap(function (OneToManyAssociationField $field) {
+ return $field->getReferenceClass();
+ });
+
+ $toManyDefinitions = array_flip($toManyDefinitions);
+
+ $dependencies = [];
+
+ /** @var ManyToOneAssociationField $dependency */
+ /** @var FieldCollection $fields */
+ foreach ($fields as $dependency) {
+ $class = $dependency->getReferenceClass();
+
+ //skip self references, this dependencies are resolved by the ChildrenAssociationField
+ if ($class === $definition) {
+ continue;
+ }
+
+ //check if many to one has pending commands
+ if (!array_key_exists($class, $commands)) {
+ continue;
+ }
+
+ //if the current dependency is defined also defined as OneToManyAssociationField, skip
+ if (array_key_exists($class, $toManyDefinitions)) {
+ continue;
+ }
+
+ /** @var string $class */
+ if (!empty($commands[$class])) {
+ $dependencies[] = $class;
}
}
- return $result;
+ return $dependencies;
}
/**
|
NEXT-<I> - Resolve write order on demand if the commands are requested in order.
|
shopware_platform
|
train
|
1320c29722b8a83175e12032e41e9e695b9d4200
|
diff --git a/framework/src/play/src/main/java/play/mvc/Http.java b/framework/src/play/src/main/java/play/mvc/Http.java
index <HASH>..<HASH> 100644
--- a/framework/src/play/src/main/java/play/mvc/Http.java
+++ b/framework/src/play/src/main/java/play/mvc/Http.java
@@ -314,7 +314,7 @@ public class Http {
public abstract java.util.Map<String,String[]> headers();
/**
- * Retrieves a single header.
+ * Retrieves a single header. Case-insensitive.
*/
public String getHeader(String headerName) {
String[] headers = null;
@@ -330,6 +330,13 @@ public class Http {
return headers[0];
}
+ /**
+ * Checks if the request has the header. Case-insensitive.
+ */
+ public boolean containsHeader(String headerName){
+ return getHeader(headerName) != null;
+ }
+
}
/**
|
Added containsHeader to Http.RequestHeader. Clarified case-insensitivity of getHeader.
|
playframework_playframework
|
train
|
cfb501936670fa34caf4d1b5ca08c72c34c3102e
|
diff --git a/api/healthcheck.go b/api/healthcheck.go
index <HASH>..<HASH> 100644
--- a/api/healthcheck.go
+++ b/api/healthcheck.go
@@ -38,7 +38,7 @@ func healthcheck(w http.ResponseWriter, r *http.Request) {
_, err = c.GetHealthCheck()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
- fmt.Fprintf(w, err.Error())
+ fmt.Fprint(w, err.Error())
return
}
w.Write([]byte("WORKING"))
|
api/healthcheck: remove unecessary call to printf
Just print is good.
|
tsuru_tsuru
|
train
|
dd4a0bb79ee7c4886b71ac2e597e1dd9b525b2f8
|
diff --git a/peg.js b/peg.js
index <HASH>..<HASH> 100644
--- a/peg.js
+++ b/peg.js
@@ -125,11 +125,10 @@
seq($('atm'), txt('?')).select(0).as('opt'),
seq($('atm'), $('qtf')).then(function (r) { r[1].rep = r[0]; return r[1]; }),
$('atm'));
-
this.grp = seq(txt('('), $('def'), txt(')'), opt(seq(txt('.'), $('lbl')).select(1))).map({ def: 1, key: 3 });
this.qtf = seq(opt($('sep')), any(txt('+').make(1), txt('*').make(0))).map({ sep: 0, min: 1 });
this.sep = seq(txt('<'), $('def'), txt('>')).select(1);
- this.lbl = rgx(/[a-z]+/i);
+ this.lbl = rgx(/[a-z0-9]+/i);
this.def = $('alt');
});
diff --git a/test/peg.js b/test/peg.js
index <HASH>..<HASH> 100644
--- a/test/peg.js
+++ b/test/peg.js
@@ -1,38 +1,38 @@
var assert = require('assert');
var PEG = require('../peg');
-console.inspect = function (object) {
- var inspect = require('util').inspect;
- return console.log(inspect(object, { depth: null }));
-};
-
-function forEach(dict, fn) {
- for (var key in dict)
- fn(dict[key], key);
-}
-
-function ptest(pattern, samples) {
- var rules = {
- 'num': PEG(/\d+/).parseInt(),
- 'var': /[a-zA-Z]\w+/
+suite('PEG', function () {
+ 'use strict';
+
+ console.inspect = function (object) {
+ var inspect = require('util').inspect;
+ return console.log(inspect(object, { depth: null }));
};
- if (arguments.length == 3) {
- rules = arguments[1];
- samples = arguments[2];
+ function forEach(dict, fn) {
+ for (var key in dict)
+ fn(dict[key], key);
}
- forEach(samples, function (expectedResult, input) {
- var testName = 'PEG(' + pattern + ').exec(' + input + ') = ' + expectedResult;
- test(testName, function () {
- var result = PEG(pattern, rules).exec(input);
- assert.deepEqual(result, expectedResult);
+ function ptest(pattern, samples) {
+ var rules = {
+ 'num': PEG(/\d+/).parseInt(),
+ 'var': /[a-zA-Z]\w+/
+ };
+
+ if (arguments.length == 3) {
+ rules = arguments[1];
+ samples = arguments[2];
+ }
+
+ forEach(samples, function (expectedResult, input) {
+ var testName = 'PEG(' + pattern + ').exec(' + input + ') = ' + expectedResult;
+ test(testName, function () {
+ var result = PEG(pattern, rules).exec(input);
+ assert.deepEqual(result, expectedResult);
+ });
});
- });
-}
-
-suite('PEG', function () {
- 'use strict';
+ }
suite('BasicParsing', function () {
suite('Text', function () {
@@ -57,7 +57,7 @@ suite('PEG', function () {
});
});
- suite('Class', function () {
+ suite('Charset', function () {
ptest('[]', {
'': null,
'a': null
@@ -127,6 +127,14 @@ suite('PEG', function () {
'abca': null,
'': null
});
+
+ ptest('[a-z]+ ("=" [0-9]+).1', {
+ 'abc=123': [['a', 'b', 'c'], ['1', '2', '3']],
+ });
+
+ ptest('tag:[a-z]+ val:("=" x:[0-9]+).x', {
+ 'abc=123': { tag: ['a', 'b', 'c'], val: ['1', '2', '3'] },
+ });
});
suite('Alternation', function () {
|
Added a couple unit tests for PEG.
|
c5f7c9_llkp
|
train
|
7f8f0fe4d97d904620f7101eb9c12d9e059e1a05
|
diff --git a/lib/vagrant_snap.rb b/lib/vagrant_snap.rb
index <HASH>..<HASH> 100644
--- a/lib/vagrant_snap.rb
+++ b/lib/vagrant_snap.rb
@@ -102,6 +102,7 @@ module Snap
def with_target(target, &blk)
target_found = false
env.vms.each do |name, vm|
+ next if vm.vm.nil? # not yet created
vagvmname = vm.name
vmname = vm.vm.name
|
don't die on VM defined in env but not yet created
|
t9md_vagrant-snap
|
train
|
2f7c118d8587c7aa83779461d57a2b1d58d99b5f
|
diff --git a/extensions/apidoc/commands/RenderController.php b/extensions/apidoc/commands/RenderController.php
index <HASH>..<HASH> 100644
--- a/extensions/apidoc/commands/RenderController.php
+++ b/extensions/apidoc/commands/RenderController.php
@@ -44,6 +44,9 @@ class RenderController extends Controller
}
$renderer = $this->findRenderer();
+ if ($renderer === false) {
+ return 1;
+ }
$renderer->targetDir = $targetDir;
$this->stdout('Searching files to process... ');
@@ -106,7 +109,7 @@ class RenderController extends Controller
$rendererClass = 'yii\\apidoc\\templates\\' . $this->template . '\\Renderer';
if (!class_exists($rendererClass)) {
$this->stderr('Renderer not found.' . PHP_EOL);
- exit(0);
+ return false;
}
return new $rendererClass();
}
|
improved erorr handling in api doc controller
|
yiisoft_yii-core
|
train
|
41e070a9578845c3fc358daca7a6bb6214a8428f
|
diff --git a/lib/dependency-checker.js b/lib/dependency-checker.js
index <HASH>..<HASH> 100644
--- a/lib/dependency-checker.js
+++ b/lib/dependency-checker.js
@@ -24,13 +24,17 @@ function isNotSymlinked(pkg) {
return !pkg.isSymlinked;
}
+function isDisabled(project) {
+ return project && project.cli && project.cli.disableDependencyChecker;
+}
+
function EmberCLIDependencyChecker(project, reporter) {
this.project = project;
this.reporter = reporter;
}
EmberCLIDependencyChecker.prototype.checkDependencies = function() {
- if (alreadyChecked || process.env.SKIP_DEPENDENCY_CHECKER) {
+ if (alreadyChecked || process.env.SKIP_DEPENDENCY_CHECKER || isDisabled(this.project)) {
return;
}
|
added check for project.cli.disableDependencyChecker to circumvent dependency checker when testing blueprints
|
quaertym_ember-cli-dependency-checker
|
train
|
583b98a9accc90a21dfd96938bf5793a152ad419
|
diff --git a/composer.json b/composer.json
index <HASH>..<HASH> 100644
--- a/composer.json
+++ b/composer.json
@@ -8,7 +8,7 @@
"guzzlehttp/psr7": "^1.0",
"react/socket": "^0.7",
"react/event-loop": "0.4.*",
- "react/stream": "^0.5|^0.6",
+ "react/stream": "^1.0 || ^0.7 || ^0.6 || ^0.5 || ^0.4.2",
"react/promise": "~2.2",
"evenement/evenement": "~2.0"
},
diff --git a/tests/RequestTest.php b/tests/RequestTest.php
index <HASH>..<HASH> 100644
--- a/tests/RequestTest.php
+++ b/tests/RequestTest.php
@@ -5,6 +5,7 @@ namespace React\Tests\HttpClient;
use React\HttpClient\Request;
use React\HttpClient\RequestData;
use React\Stream\Stream;
+use React\Stream\DuplexResourceStream;
use React\Promise\RejectedPromise;
use React\Promise\Deferred;
use React\Promise\Promise;
@@ -428,7 +429,7 @@ class RequestTest extends TestCase
$request->setResponseFactory($factory);
$stream = fopen('php://memory', 'r+');
- $stream = new Stream($stream, $loop);
+ $stream = class_exists('React\Stream\DuplexResourceStream') ? new DuplexResourceStream($stream, $loop) : new Stream($stream, $loop);
$stream->pipe($request);
$stream->emit('data', array('some'));
diff --git a/tests/ResponseTest.php b/tests/ResponseTest.php
index <HASH>..<HASH> 100644
--- a/tests/ResponseTest.php
+++ b/tests/ResponseTest.php
@@ -11,8 +11,7 @@ class ResponseTest extends TestCase
public function setUp()
{
- $this->stream = $this->getMockBuilder('React\Stream\Stream')
- ->disableOriginalConstructor()
+ $this->stream = $this->getMockBuilder('React\Stream\DuplexStreamInterface')
->getMock();
}
|
Forward compatibility with upcoming Stream <I> through old <I>
|
reactphp_http-client
|
train
|
53b0088b0bb20289859a7e5583f5ae6f6987b949
|
diff --git a/python/neuroglancer/viewer_state.py b/python/neuroglancer/viewer_state.py
index <HASH>..<HASH> 100644
--- a/python/neuroglancer/viewer_state.py
+++ b/python/neuroglancer/viewer_state.py
@@ -177,6 +177,12 @@ class ImageLayer(Layer):
shader = wrapped_property('shader', text_type)
opacity = wrapped_property('opacity', optional(float, 0.5))
+ @staticmethod
+ def interpolate(a, b, t):
+ c = copy.deepcopy(a)
+ c.opacity = a.opacity * (1 - t) + b.opacity * t
+ return c
+
def uint64_equivalence_map(obj, _readonly=False):
if isinstance(obj, EquivalenceMap):
@@ -204,6 +210,13 @@ class SegmentationLayer(Layer):
object_alpha = objectAlpha = wrapped_property('objectAlpha', optional(float, 1.0))
skeleton_shader = skeletonShader = wrapped_property('skeletonShader', text_type)
+ @staticmethod
+ def interpolate(a, b, t):
+ c = copy.deepcopy(a)
+ for k in ['selected_alpha', 'not_selected_alpha', 'object_alpha']:
+ setattr(c, k, getattr(a, k) * (1 - t) + getattr(b, k) * t)
+ return c
+
layer_types = {
'image': ImageLayer,
@@ -376,6 +389,19 @@ class Layers(object):
def __repr__(self):
return repr(self._layers)
+ @staticmethod
+ def interpolate(a, b, t):
+ c = copy.deepcopy(a)
+ for layer in c:
+ index = b.index(layer.name)
+ if index == -1:
+ continue
+ other_layer = b[index]
+ if type(other_layer.layer) != type(layer.layer): # pylint: disable=unidiomatic-typecheck
+ continue
+ layer.layer = type(layer.layer).interpolate(layer.layer, other_layer.layer, t)
+ return c
+
def layout_specification(x, _readonly=False):
if isinstance(x, six.string_types):
@@ -535,4 +561,5 @@ class ViewerState(JsonObjectWrapper):
c.perspective_zoom = interpolate_zoom(a.perspective_zoom, b.perspective_zoom, t)
c.perspective_orientation = quaternion_slerp(a.perspective_orientation,
b.perspective_orientation, t)
+ c.layers = Layers.interpolate(a.layers, b.layers, t)
return c
|
feat(python): support interpolation between layer states
|
google_neuroglancer
|
train
|
9a044954bb8da041223bb4014aab679c7d76e9fb
|
diff --git a/tests/mocks/models.py b/tests/mocks/models.py
index <HASH>..<HASH> 100644
--- a/tests/mocks/models.py
+++ b/tests/mocks/models.py
@@ -29,6 +29,19 @@ class Keras(lore.models.keras.Base):
)
+class KerasMulti(lore.models.keras.Base):
+ def __init__(self):
+ super(KerasMulti, self).__init__(
+ tests.mocks.pipelines.XorMulti(),
+ lore.estimators.keras.MultiClassifier(
+ batch_size=1024,
+ embed_size=10,
+ hidden_layers=1,
+ hidden_width=100
+ )
+ )
+
+
class XGBoostBinaryClassifier(lore.models.xgboost.Base):
def __init__(self):
super(XGBoostBinaryClassifier, self).__init__(
diff --git a/tests/mocks/pipelines.py b/tests/mocks/pipelines.py
index <HASH>..<HASH> 100644
--- a/tests/mocks/pipelines.py
+++ b/tests/mocks/pipelines.py
@@ -31,6 +31,11 @@ class Xor(lore.pipelines.holdout.Base):
return Pass('xor')
+class XorMulti(Xor):
+ def get_output_encoder(self):
+ return OneHot('xor')
+
+
class MockData(lore.pipelines.time_series.Base):
def get_data(self):
return pandas.DataFrame({
diff --git a/tests/unit/test_models.py b/tests/unit/test_models.py
index <HASH>..<HASH> 100644
--- a/tests/unit/test_models.py
+++ b/tests/unit/test_models.py
@@ -65,6 +65,13 @@ class TestKeras(unittest.TestCase):
assert True
+class TestKerasMulti(unittest.TestCase):
+ def test_multi(self):
+ model = tests.mocks.models.KerasMulti()
+ model.fit(epochs=1)
+ assert True
+
+
class TestXGBoostRegression(unittest.TestCase):
def test_lifecycle(self):
model = tests.mocks.models.XGBoostRegression()
|
Test Keras MultiClassifier (#<I>)
* failing test for multi
* change unique to onehot
|
instacart_lore
|
train
|
4ab5a6a757e6c0ab14af29f1faf3a38249971701
|
diff --git a/openpnm/algorithms/ChargeConservation.py b/openpnm/algorithms/ChargeConservation.py
index <HASH>..<HASH> 100644
--- a/openpnm/algorithms/ChargeConservation.py
+++ b/openpnm/algorithms/ChargeConservation.py
@@ -6,9 +6,9 @@ logger = logging.getLogger(__name__)
docstr = Docorator()
-@docstr.get_sectionsf('ChargeConservasionSettings', sections=['Parameters'])
+@docstr.get_sectionsf('ChargeConservationSettings', sections=['Parameters'])
@docstr.dedent
-class ChargeConservasionSettings(GenericSettings):
+class ChargeConservationSettings(GenericSettings):
r"""
Parameters
@@ -61,7 +61,7 @@ class ChargeConservation(ReactiveTransport):
def __init__(self, settings={}, **kwargs):
super().__init__(**kwargs)
- self.settings._update_settings_and_docs(ChargeConservasionSettings())
+ self.settings._update_settings_and_docs(ChargeConservationSettings())
self.settings.update(settings)
@docstr.dedent
diff --git a/openpnm/algorithms/ReactiveTransport.py b/openpnm/algorithms/ReactiveTransport.py
index <HASH>..<HASH> 100644
--- a/openpnm/algorithms/ReactiveTransport.py
+++ b/openpnm/algorithms/ReactiveTransport.py
@@ -9,6 +9,20 @@ docstr = Docorator()
logger = logging.getLogger(__name__)
+# class RelaxationSettings(GenericSettings):
+# r"""
+# This class is a demonstration of how we can add nested settings classes
+# to other settings classes to make categories for some settings. This is
+# being appended to the ReactiveTransportSettings class under the
+# 'relaxation' attribute, and it works as planned by allowing the nested
+# dot access to its parameters. More work would be required to get it
+# functional such as dealing with deeply nested dicts and so on, but it
+# works in principal.
+# """
+# source = 1.0
+# quantity = 1.0
+
+
@docstr.get_sectionsf('ReactiveTransportSettings',
sections=['Parameters', 'Other Parameters'])
@docstr.dedent
@@ -55,6 +69,7 @@ class ReactiveTransportSettings(GenericSettings):
"""
max_iter = 5000
+ # relaxation = RelaxationSettings()
relaxation_source = 1.0
relaxation_quantity = 1.0
rxn_tolerance = 1e-8
|
Adding proof of concept to add nested settings classes for hierarchical 'dot' access
|
PMEAL_OpenPNM
|
train
|
c93c1e92f79dbed3e9074187b7f9a8653fd6c5b7
|
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index <HASH>..<HASH> 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -48,8 +48,24 @@ shared_examples_for "an engine" do
CGI.escapeHTML(data[key])
end
+ it "includes subname" do
+ expect(html).to include(%|<aside class="onebox #{described_class.template_name}">|)
+ end
+
it "includes title" do
expect(html).to include(value_of(:title))
end
+
+ it "includes link" do
+ expect(html).to include(%|class="link" href="#{value_of(:link)}|)
+ end
+
+ it "includes badge" do
+ expect(html).to include(%|<strong class="name">#{value_of(:badge)}</strong>|)
+ end
+
+ it "includes domain" do
+ expect(html).to include(%|class="domain" href="#{value_of(:domain)}|)
+ end
end
end
|
We want to make sure the various pieces are in the template
|
discourse_onebox
|
train
|
a7dd19beb6572e47a071565daa1cec02265b0045
|
diff --git a/lib/instrumentation/index.js b/lib/instrumentation/index.js
index <HASH>..<HASH> 100644
--- a/lib/instrumentation/index.js
+++ b/lib/instrumentation/index.js
@@ -77,7 +77,7 @@ Instrumentation.prototype.addEndedTransaction = function (transaction) {
var payload = new AsyncValuePromise()
- payload.then(null, function (err) {
+ payload.catch(function (err) {
logger.error('error encoding transaction %s: %s', transaction.id, err.message)
})
|
refactor: use new catch function in async-value-promise (#<I>)
|
elastic_apm-agent-nodejs
|
train
|
4d0b29ee8af36185552b736fe227edd2dfda024a
|
diff --git a/src/statement.js b/src/statement.js
index <HASH>..<HASH> 100644
--- a/src/statement.js
+++ b/src/statement.js
@@ -655,7 +655,12 @@ pp.checkVariableExport = function(exports, decls) {
}
pp.shouldParseExportStatement = function() {
- return this.type.keyword || this.isLet() || this.isAsyncFunction()
+ return this.type.keyword === "var"
+ || this.type.keyword === "const"
+ || this.type.keyword === "class"
+ || this.type.keyword === "function"
+ || this.isLet()
+ || this.isAsyncFunction()
}
// Parses a comma-separated list of module exports.
diff --git a/test/tests-harmony.js b/test/tests-harmony.js
index <HASH>..<HASH> 100644
--- a/test/tests-harmony.js
+++ b/test/tests-harmony.js
@@ -4116,6 +4116,9 @@ test("export class Class {}", {
locations: true
});
+testFail("export new Foo();", "Unexpected token (1:7)", {ecmaVersion: 6, sourceType: "module"});
+testFail("export typeof foo;", "Unexpected token (1:7)", {ecmaVersion: 6, sourceType: "module"});
+
test("export default 42", {
type: "Program",
body: [{
|
Throw "unexpected token" error when exporting a non-declaration
|
acornjs_acorn
|
train
|
f4df7149913e951ba065770bf7594ea23d405fb9
|
diff --git a/lib/rworkflow/minitest/test.rb b/lib/rworkflow/minitest/test.rb
index <HASH>..<HASH> 100644
--- a/lib/rworkflow/minitest/test.rb
+++ b/lib/rworkflow/minitest/test.rb
@@ -24,10 +24,11 @@ module Rworkflow
# @params [Hash] options hash
# @option [Class] :flow workflow class to instantiate; defaults to SidekiqFlow
# @option [Class] :name the state name
- def rworkflow_worker(worker_class, flow: ::SidekiqFlow, name: nil)
+ def rworkflow_worker(worker_class, flow: ::SidekiqFlow, name: nil, meta: {})
name ||= worker_class.name
worker = worker_class.new
workflow = flow.new(name)
+ meta.each { |key, value| workflow.set(key, value) }
worker.instance_variable_set(:@workflow, workflow)
worker.instance_variable_set(:@state_name, name)
@@ -37,7 +38,7 @@ module Rworkflow
yield(workflow) if block_given?
- return worker
+ return worker, workflow
end
end
|
return workflow as well as worker, and add possibility to pass meta data to set for workflow
|
barcoo_rworkflow
|
train
|
d96fdbc94802c062be61f7ffe9f629b45e43300f
|
diff --git a/lenstronomy/LensModel/lens_model_extensions.py b/lenstronomy/LensModel/lens_model_extensions.py
index <HASH>..<HASH> 100644
--- a/lenstronomy/LensModel/lens_model_extensions.py
+++ b/lenstronomy/LensModel/lens_model_extensions.py
@@ -209,9 +209,9 @@ class LensModelExtensions(LensModel):
x_grid += center_x
y_grid += center_y
kappa = self.kappa(x_grid, y_grid, kwargs_lens_list, k=k)
- if self.lens_model_list[0] in ['INTERPOL', 'INTERPOL_SCALED']:
- center_x = x_grid[kappa == np.max(kappa)]
- center_y = y_grid[kappa == np.max(kappa)]
+ #if self.lens_model_list[0] in ['INTERPOL', 'INTERPOL_SCALED']:
+ center_x = x_grid[kappa == np.max(kappa)]
+ center_y = y_grid[kappa == np.max(kappa)]
kappa = util.array2image(kappa)
r_array = np.linspace(0.0001, numPix*deltaPix/2., 200)
for r in r_array:
diff --git a/lenstronomy/LensModel/multi_plane.py b/lenstronomy/LensModel/multi_plane.py
index <HASH>..<HASH> 100644
--- a/lenstronomy/LensModel/multi_plane.py
+++ b/lenstronomy/LensModel/multi_plane.py
@@ -25,7 +25,10 @@ class MultiLens(object):
raise ValueError("The length of lens_model_list does not correspond to redshift_list")
self._lens_model_list = lens_model_list
self._redshift_list = redshift_list
- self._sorted_redshift_index = self._index_ordering(redshift_list)
+ if len(lens_model_list) < 1:
+ self._sorted_redshift_index = []
+ else:
+ self._sorted_redshift_index = self._index_ordering(redshift_list)
self._lens_model = SinglePlane(lens_model_list)
z_before = 0
self._T_ij_list = []
@@ -57,7 +60,7 @@ class MultiLens(object):
y = np.zeros_like(theta_y)
alpha_x = theta_x
alpha_y = theta_y
- i = 0
+ i = -1
for i, idex in enumerate(self._sorted_redshift_index):
delta_T = self._T_ij_list[i]
x, y = self._ray_step(x, y, alpha_x, alpha_y, delta_T)
diff --git a/test/test_LensModel/test_multi_plane.py b/test/test_LensModel/test_multi_plane.py
index <HASH>..<HASH> 100644
--- a/test/test_LensModel/test_multi_plane.py
+++ b/test/test_LensModel/test_multi_plane.py
@@ -55,6 +55,18 @@ class TestMultiPlane(object):
npt.assert_almost_equal(f_yx_simple, f_yx_multi, decimal=5)
npt.assert_almost_equal(f_yy_simple, f_yy_multi, decimal=5)
+ def test_empty(self):
+ z_source = 1.5
+ lens_model_list = []
+ redshift_list = []
+ lensModelMutli = MultiLens(z_source=z_source, lens_model_list=lens_model_list, redshift_list=redshift_list)
+ kwargs_lens = []
+ f_xx_multi, f_xy_multi, f_yx_multi, f_yy_multi = lensModelMutli.hessian(1, 0, kwargs_lens, diff=0.000001)
+ npt.assert_almost_equal(0, f_xx_multi, decimal=5)
+ npt.assert_almost_equal(0, f_xy_multi, decimal=5)
+ npt.assert_almost_equal(0, f_yx_multi, decimal=5)
+ npt.assert_almost_equal(0, f_yy_multi, decimal=5)
+
def test_sis_kappa_gamma_mag(self):
z_source = 1.5
lens_model_list = ['SIS']
|
multiPlane compatible with empty lens model
|
sibirrer_lenstronomy
|
train
|
433be6ac9bf44947c99e178d12a71eaf5b37767f
|
diff --git a/scripts/emulator.js b/scripts/emulator.js
index <HASH>..<HASH> 100644
--- a/scripts/emulator.js
+++ b/scripts/emulator.js
@@ -52,7 +52,7 @@ const askForEmu = [
.concat([
new inquirer.Separator(),
{
- name: 'Other Sdk',
+ name: 'Other Sdk (Require download)',
value: null,
},
new inquirer.Separator(),
@@ -73,13 +73,14 @@ const askForEmu = [
},
]
-const openEmu = options => {
+const emulatorTasks = options => {
const { name, sdk } = options
+ const tasks = []
if (sdk !== undefined) {
const sdkPath =
sdk.length === 2 ? `system-images;android-${sdk.replace(/\s/g, '')};google_apis;x86` : sdk
- return [
- {
+ if (sdk.length === 2) {
+ tasks.push({
title: 'Downloading Emulator Image',
task: () => {
// eslint-disable-next-line
@@ -88,27 +89,27 @@ const openEmu = options => {
execSync('export JAVA_OPTS="-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee"')
execSync(`$ANDROID_HOME/tools/bin/sdkmanager "${sdkPath}"`)
},
- },
- {
- title: `Creating Emulator ${name}`,
- task: () => {
- execSync(
- `echo no | $ANDROID_HOME/tools/bin/avdmanager \
+ })
+ }
+ tasks.push({
+ title: `Creating Emulator ${name}`,
+ task: () => {
+ execSync(
+ `echo no | $ANDROID_HOME/tools/bin/avdmanager \
create avd -n ${name.replace(/\s/g, '')} -k "${sdkPath}" --device "Nexus 6P"`,
- )
- },
+ )
},
- ]
+ })
}
- return [
- {
- title: 'Open Emulator',
- task: () => execSync(`$ANDROID_HOME/emulator/emulator @${name}`),
- },
- ]
+ tasks.push({
+ title: 'Open Emulator',
+ task: () => execSync(`$ANDROID_HOME/emulator/emulator @${name}`),
+ })
+ return tasks
}
+
inquirer.prompt(askForEmu).then(options => {
- const tasks = openEmu(options)
+ const tasks = emulatorTasks(options)
const listr = new Listr(tasks)
listr.run()
})
|
[Scripts][Emulator] Better managment of tasks
|
Nozbe_WatermelonDB
|
train
|
4b8652f1c416c8477a787b65d77e1665b40f25f7
|
diff --git a/test/integration/022_bigquery_test/test_bigquery_copy_failing_models.py b/test/integration/022_bigquery_test/test_bigquery_copy_failing_models.py
index <HASH>..<HASH> 100644
--- a/test/integration/022_bigquery_test/test_bigquery_copy_failing_models.py
+++ b/test/integration/022_bigquery_test/test_bigquery_copy_failing_models.py
@@ -32,5 +32,5 @@ class TestBigqueryCopyTableFails(DBTIntegrationTest):
@use_profile('bigquery')
def test__bigquery_copy_table_fails(self):
results = self.run_dbt(expect_pass=False)
- self.assertEqual(len(results), 1)
+ self.assertEqual(len(results), 2)
self.assertTrue(results[0].error)
|
Should be two results for original table and (failing) copy
|
fishtown-analytics_dbt
|
train
|
489857fa8719f39bd6b10f1f8c366a9cbb5b0de6
|
diff --git a/js/demo.js b/js/demo.js
index <HASH>..<HASH> 100644
--- a/js/demo.js
+++ b/js/demo.js
@@ -6,7 +6,7 @@ demoApp.controller("ctrl", ['$scope', function($scope) {
$scope.mode = "custom";
$scope.firstDay = 1;
$scope.weekendDays = [0,6];
- $scope.maxHeight = 300;
+ $scope.maxHeight = 0;
$scope.addSamples = function () {
$scope.loadData(getSampleData().data1);
|
MaxHeight is deactivated by default in the demo
|
angular-gantt_angular-gantt
|
train
|
09d7f0fd6f45df5ed10775a682d2b48c6bb672a2
|
diff --git a/cfg4j-core/src/main/java/org/cfg4j/source/metered/MeteredConfigurationSource.java b/cfg4j-core/src/main/java/org/cfg4j/source/metered/MeteredConfigurationSource.java
index <HASH>..<HASH> 100644
--- a/cfg4j-core/src/main/java/org/cfg4j/source/metered/MeteredConfigurationSource.java
+++ b/cfg4j-core/src/main/java/org/cfg4j/source/metered/MeteredConfigurationSource.java
@@ -30,6 +30,7 @@ import java.util.Properties;
* with a string passed at construction time):
* <ul>
* <li>source.getConfiguration</li>
+ * <li>source.init</li>
* <li>source.reload</li>
* </ul>
* Each of those metrics is of {@link Timer} type (i.e. includes execution time percentiles, execution count, etc.)
@@ -39,11 +40,12 @@ public class MeteredConfigurationSource implements ConfigurationSource {
private final ConfigurationSource delegate;
private final Timer getConfigurationTimer;
+ private final Timer initTimer;
private final Timer reloadTimer;
/**
* Create decorator for given {@code delegate} and using {@code metricRegistry} for constructing metrics. Each metric will
- * be prefixed with {@code metricPrefix}
+ * be prefixed with {@code metricPrefix}.
*
* @param metricRegistry metric registry to hold execution metrics
* @param metricPrefix prefix for metric names (trailing dot will be added to it)
@@ -55,6 +57,7 @@ public class MeteredConfigurationSource implements ConfigurationSource {
this.delegate = requireNonNull(delegate);
getConfigurationTimer = metricRegistry.timer(metricPrefix + "source.getConfiguration");
+ initTimer = metricRegistry.timer(metricPrefix + "source.init");
reloadTimer = metricRegistry.timer(metricPrefix + "source.reload");
}
@@ -70,6 +73,17 @@ public class MeteredConfigurationSource implements ConfigurationSource {
}
@Override
+ public void init() {
+ Timer.Context context = initTimer.time();
+
+ try {
+ delegate.init();
+ } finally {
+ context.stop();
+ }
+ }
+
+ @Override
public void reload() {
Timer.Context context = reloadTimer.time();
diff --git a/cfg4j-core/src/test/java/org/cfg4j/source/metered/MeteredConfigurationSourceTest.java b/cfg4j-core/src/test/java/org/cfg4j/source/metered/MeteredConfigurationSourceTest.java
index <HASH>..<HASH> 100644
--- a/cfg4j-core/src/test/java/org/cfg4j/source/metered/MeteredConfigurationSourceTest.java
+++ b/cfg4j-core/src/test/java/org/cfg4j/source/metered/MeteredConfigurationSourceTest.java
@@ -61,6 +61,7 @@ public class MeteredConfigurationSourceTest {
when(metricRegistry.timer(anyString())).thenReturn(timer);
source = new MeteredConfigurationSource(metricRegistry, "configSource", delegate);
+ source.init();
}
@Test
@@ -77,4 +78,9 @@ public class MeteredConfigurationSourceTest {
verify(delegate, times(1)).reload();
}
+
+ @Test
+ public void initShouldCallDelegate() throws Exception {
+ verify(delegate, times(1)).init();
+ }
}
\ No newline at end of file
|
support delayed initialization in Metered source
|
cfg4j_cfg4j
|
train
|
06f51e2d921930138dc112e5356cfec8f9174911
|
diff --git a/helios-testing/src/main/java/com/spotify/helios/testing/HeliosSoloDeployment.java b/helios-testing/src/main/java/com/spotify/helios/testing/HeliosSoloDeployment.java
index <HASH>..<HASH> 100644
--- a/helios-testing/src/main/java/com/spotify/helios/testing/HeliosSoloDeployment.java
+++ b/helios-testing/src/main/java/com/spotify/helios/testing/HeliosSoloDeployment.java
@@ -43,7 +43,6 @@ import com.spotify.docker.client.messages.HostConfig;
import com.spotify.docker.client.messages.Info;
import com.spotify.docker.client.messages.NetworkSettings;
import com.spotify.docker.client.messages.PortBinding;
-import com.spotify.docker.client.shaded.javax.ws.rs.core.Response;
import com.spotify.helios.client.HeliosClient;
import com.spotify.helios.common.descriptors.Goal;
import com.spotify.helios.common.descriptors.HostStatus;
@@ -459,8 +458,10 @@ public class HeliosSoloDeployment implements HeliosDeployment {
for (Map.Entry<String, TaskStatus> status : statuses.entrySet()) {
final String host = status.getKey();
- if (status.getValue().getGoal().equals(Goal.START)) {
- log.info("Job {} is still set to START on host {}. Undeploying it now.", jobId, host);
+ final Goal goal = status.getValue().getGoal();
+ if (goal != Goal.UNDEPLOY) {
+ log.info("Job {} is still set to {} on host {}. Undeploying it now.",
+ jobId, goal, host);
final JobUndeployResponse undeployResponse = heliosClient.undeploy(jobId, host).get();
log.info("Undeploy response for job {} is {}.", jobId, undeployResponse.getStatus());
@@ -468,11 +469,11 @@ public class HeliosSoloDeployment implements HeliosDeployment {
log.warn("Undeploy response for job {} was not OK. Not waiting for job to " +
"actually be undeployed.", jobId);
}
-
- log.info("Waiting for job {} to actually be undeployed...", jobId);
- awaitJobUndeployed(heliosClient, host, jobId, jobUndeployWaitSeconds, TimeUnit.SECONDS);
- log.info("Job {} successfully undeployed.", jobId);
}
+
+ log.info("Waiting for job {} to actually be undeployed...", jobId);
+ awaitJobUndeployed(heliosClient, host, jobId, jobUndeployWaitSeconds, TimeUnit.SECONDS);
+ log.info("Job {} successfully undeployed.", jobId);
}
}
} catch (Exception e) {
|
Move awaitJobUndeployed() to outside of if
|
spotify_helios
|
train
|
edffe8864c29cf5bdf90a649b04567edca3927f7
|
diff --git a/src/libhoney.js b/src/libhoney.js
index <HASH>..<HASH> 100644
--- a/src/libhoney.js
+++ b/src/libhoney.js
@@ -120,10 +120,13 @@ export default class Libhoney extends EventEmitter {
}
_responseCallback(responses) {
- let queue = this._responseQueue;
- if (queue.length < this._options.maxResponseQueueSize) {
- this._responseQueue = this._responseQueue.concat(responses);
- }
+ const [queue, limit] = [
+ this._responseQueue,
+ this._options.maxResponseQueueSize
+ ];
+
+ this._responseQueue = concatWithMaxLimit(queue, responses, limit);
+
this.emit("response", this._responseQueue);
}
@@ -500,3 +503,32 @@ function getAndInitTransmission(transmission, options) {
}
}
}
+
+ /**
+ * Concatenates two arrays while keeping the length of the returned result
+ * less than the limit. As many elements from arr2 will be appended onto the
+ * end of arr1 as will remain under the limit. If arr1 is already too long it
+ * will be truncated to match the limit. Order is preserved; arr2's contents
+ * will appear after those already in arr1.
+ *
+ * Modifies and returns arr1.
+ */
+ function concatWithMaxLimit(arr1, arr2, limit) {
+ // if queue is full or somehow over the max
+ if (arr1.length >= limit) {
+ //return up to the max length
+ return arr1.slice(0, limit);
+ }
+
+ // if queue is not yet full but incoming responses
+ // would put the queue over
+ if (arr1.length + arr2.length > limit) {
+ // find the difference and return only enough responses to fill the queue
+ const diff = limit - arr1.length;
+ const slicedArr2 = arr2.slice(0, diff);
+ return arr1.concat(slicedArr2);
+ }
+
+ // otherwise assume it'll all fit, combine the responses with the queue
+ return arr1.concat(arr2);
+}
|
Enforce limited response queue
* add logic to limit new responses to queue max
* refactor array-slicing logic
* move all logic into concatWithMaxLimit
* Add detailed function description
|
honeycombio_libhoney-js
|
train
|
d130a6067227f541c4f04e5c9de6282f1a7409ed
|
diff --git a/src/language/parser.js b/src/language/parser.js
index <HASH>..<HASH> 100644
--- a/src/language/parser.js
+++ b/src/language/parser.js
@@ -19,7 +19,6 @@ import {
type VariableNode,
type DocumentNode,
type DefinitionNode,
- type ExecutableDefinitionNode,
type OperationDefinitionNode,
type OperationTypeNode,
type VariableDefinitionNode,
@@ -217,6 +216,10 @@ class Parser {
* - ExecutableDefinition
* - TypeSystemDefinition
* - TypeSystemExtension
+ *
+ * ExecutableDefinition :
+ * - OperationDefinition
+ * - FragmentDefinition
*/
parseDefinition(): DefinitionNode {
if (this.peek(TokenKind.NAME)) {
@@ -224,8 +227,9 @@ class Parser {
case 'query':
case 'mutation':
case 'subscription':
+ return this.parseOperationDefinition();
case 'fragment':
- return this.parseExecutableDefinition();
+ return this.parseFragmentDefinition();
case 'schema':
case 'scalar':
case 'type':
@@ -239,7 +243,7 @@ class Parser {
return this.parseTypeSystemExtension();
}
} else if (this.peek(TokenKind.BRACE_L)) {
- return this.parseExecutableDefinition();
+ return this.parseOperationDefinition();
} else if (this.peekDescription()) {
return this.parseTypeSystemDefinition();
}
@@ -247,29 +251,6 @@ class Parser {
throw this.unexpected();
}
- /**
- * ExecutableDefinition :
- * - OperationDefinition
- * - FragmentDefinition
- */
- parseExecutableDefinition(): ExecutableDefinitionNode {
- if (this.peek(TokenKind.NAME)) {
- switch (this._lexer.token.value) {
- case 'query':
- case 'mutation':
- case 'subscription':
- return this.parseOperationDefinition();
-
- case 'fragment':
- return this.parseFragmentDefinition();
- }
- } else if (this.peek(TokenKind.BRACE_L)) {
- return this.parseOperationDefinition();
- }
-
- throw this.unexpected();
- }
-
// Implements the parsing rules in the Operations section.
/**
|
parser: Inline 'parseExecutableDefinition' to simplify code (#<I>)
|
graphql_graphql-js
|
train
|
33b2ae7adef917ddcafb93f3bca6a28d0f750c03
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,8 +2,8 @@
## Unreleased
-* Including a recipe from a cookbook not in the dependency graph raises
- a MissingCookbookDependency exception. Fixes CHEF-4367.
+* Including a recipe from a cookbook not in the dependency graph logs
+ a MissingCookbookDependency warning. Fixes CHEF-4367.
* Improves syntax check speed for Ruby 1.9+, especially when using bundler.
* Send X-Remote-Request-Id header in order to be able to correlate actions during a single run.
* Fix for CHEF-5048.
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index <HASH>..<HASH> 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -8,7 +8,7 @@ Details about the thing that changed that needs to get included in the Release N
-->
# Chef Client Release Notes:
-#### Chef Solo Missing Dependency Improvments ([CHEF-4367](https://tickets.opscode.com/browse/CHEF-4367))
+#### Chef Solo Missing Dependency Warning ([CHEF-4367](https://tickets.opscode.com/browse/CHEF-4367))
Chef 11.0 introduced ordered evaluation of non-recipe files in
cookbooks, based on the dependencies specified in your cookbooks'
@@ -23,8 +23,8 @@ did not suggest the actual cause of the failure.
We've added a check to `include_recipe` so that attempting to include a
recipe which is not a dependency of any cookbook specified in the run
-list will now raise an error with a message describing the problem and
-solution.
+list will now log a warning with a message describing the problem and
+solution. In the future, this warning will become an error.
#### reboot_pending?
diff --git a/lib/chef/exceptions.rb b/lib/chef/exceptions.rb
index <HASH>..<HASH> 100644
--- a/lib/chef/exceptions.rb
+++ b/lib/chef/exceptions.rb
@@ -76,7 +76,7 @@ class Chef
class CookbookNotFoundInRepo < ArgumentError; end
class RecipeNotFound < ArgumentError; end
class AttributeNotFound < RuntimeError; end
- class MissingCookbookDependency < StandardError; end
+ class MissingCookbookDependency < StandardError; end # CHEF-5120
class InvalidCommandOption < RuntimeError; end
class CommandTimeout < RuntimeError; end
class RequestedUIDUnavailable < RuntimeError; end
diff --git a/lib/chef/run_context.rb b/lib/chef/run_context.rb
index <HASH>..<HASH> 100644
--- a/lib/chef/run_context.rb
+++ b/lib/chef/run_context.rb
@@ -145,7 +145,8 @@ class Chef
cookbook_name, recipe_short_name = Chef::Recipe.parse_recipe_name(recipe_name)
if unreachable_cookbook?(cookbook_name) # CHEF-4367
- raise(Exceptions::MissingCookbookDependency,<<-ERROR_MESSAGE)
+ Chef::Log.warn(<<-ERROR_MESSAGE)
+MissingCookbookDependency:
Recipe `#{recipe_name}` is not in the run_list, and cookbook '#{cookbook_name}'
is not a dependency of any cookbook in the run_list. To load this recipe,
first add a dependency on cookbook '#{cookbook_name}' in the cookbook you're
diff --git a/spec/integration/solo/solo_spec.rb b/spec/integration/solo/solo_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/integration/solo/solo_spec.rb
+++ b/spec/integration/solo/solo_spec.rb
@@ -55,8 +55,8 @@ cookbook_path "#{path_to('cookbooks')}"
file_cache_path "#{path_to('config/cache')}"
EOM
result = shell_out("ruby bin/chef-solo -c \"#{path_to('config/solo.rb')}\" -o 'x::default' -l debug", :cwd => chef_dir)
- result.exitstatus.should == 1
- result.stdout.should include("Chef::Exceptions::MissingCookbookDependency")
+ result.exitstatus.should == 0 # For CHEF-5120 this becomes 1
+ result.stdout.should include("WARN: MissingCookbookDependency")
end
end
diff --git a/spec/unit/run_context_spec.rb b/spec/unit/run_context_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/run_context_spec.rb
+++ b/spec/unit/run_context_spec.rb
@@ -80,9 +80,11 @@ describe Chef::RunContext do
end
it "raises an error when attempting to include_recipe from a cookbook not reachable by run list or dependencies" do
+ @node.should_receive(:loaded_recipe).with(:ancient, "aliens")
lambda do
@run_context.include_recipe("ancient::aliens")
- end.should raise_error(Chef::Exceptions::MissingCookbookDependency)
+ # In CHEF-5120, this becomes a Chef::Exceptions::MissingCookbookDependency error:
+ end.should raise_error(Chef::Exceptions::CookbookNotFound)
end
end
|
Change missing dependency from hard error to warning for now.
|
chef_chef
|
train
|
a64c009eb3a1d38501f1c398a06e382807374c43
|
diff --git a/src/DOM/shapes/nodeWithComponent.js b/src/DOM/shapes/nodeWithComponent.js
index <HASH>..<HASH> 100644
--- a/src/DOM/shapes/nodeWithComponent.js
+++ b/src/DOM/shapes/nodeWithComponent.js
@@ -6,7 +6,7 @@ import { handleHooks } from '../addAttributes';
export default function createNodeWithComponent(componentIndex, props) {
let domNode;
- let currentItem;
+ const currentItemMap = {};
const instanceMap = {};
const statelessRenderMap = {};
const node = {
@@ -21,7 +21,7 @@ export default function createNodeWithComponent(componentIndex, props) {
}
const Component = getValueWithIndex(toUseItem, componentIndex);
- currentItem = item;
+ currentItemMap[item.id] = item;
if (isVoid(Component)) {
domNode = document.createTextNode('');
instance = null;
@@ -97,7 +97,7 @@ export default function createNodeWithComponent(componentIndex, props) {
const Component = getValueWithIndex(nextItem, componentIndex);
const instance = instanceMap[lastItem.id];
- currentItem = nextItem;
+ currentItemMap[lastItem.id] = nextItem;
if (!Component) {
recreateNode(domNode, lastItem, nextItem, node, treeLifecycle, context);
if (instance) {
diff --git a/src/DOM/shapes/rootNodeWithComponent.js b/src/DOM/shapes/rootNodeWithComponent.js
index <HASH>..<HASH> 100644
--- a/src/DOM/shapes/rootNodeWithComponent.js
+++ b/src/DOM/shapes/rootNodeWithComponent.js
@@ -145,18 +145,7 @@ export default function createRootNodeWithComponent(componentIndex, props, recyc
}
currentItem.rootNode = newDomNode;
} else {
- const newDomNode = nextRender.tree.dom.create(statelessRender, treeLifecycle, context);
-
- if (newDomNode) {
- if (nextRender.rootNode.parentNode) {
- nextRender.rootNode.parentNode.replaceChild(newDomNode, nextRender.rootNode);
- } else {
- lastItem.rootNode.parentNode.replaceChild(newDomNode, lastItem.rootNode);
- }
- currentItem.rootNode = newDomNode;
- } else {
- currentItem.rootNode = nextRender.rootNode;
- }
+ recreateRootNode(nextItem.rootNode, lastItem, nextItem, node, treeLifecycle, context);
}
} else {
recreateRootNode(nextItem.rootNode, lastItem, nextItem, node, treeLifecycle, context);
diff --git a/src/component/__tests__/components.spec.jsx.js b/src/component/__tests__/components.spec.jsx.js
index <HASH>..<HASH> 100644
--- a/src/component/__tests__/components.spec.jsx.js
+++ b/src/component/__tests__/components.spec.jsx.js
@@ -1146,7 +1146,7 @@ describe('Components (JSX)', () => {
});
});
- describe('should render a component with a list that insantly changes', () => {
+ describe('should render a component with a list that instantly changes', () => {
class ChangeChildrenCount extends Component {
constructor(props) {
super(props);
@@ -1202,4 +1202,60 @@ describe('Components (JSX)', () => {
});
});
-});
+ describe('should render a conditional stateless component', () => {
+ const StatelessComponent = ({value}) => (
+ <p>{value}</p>
+ );
+
+ class First extends Component {
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ counter: 0
+ };
+
+ this._onClick = this._onClick.bind(this);
+ }
+
+ _onClick() {
+ this.setState({
+ counter: ++this.state.counter
+ });
+ }
+
+ render() {
+ return (
+ <div>
+ <button onClick={this._onClick}>Increase! {this.state.counter}</button>
+ {true ? <StatelessComponent value={this.state.counter} /> : null}
+ </div>
+ )
+ }
+ }
+
+ it('should correctly render', () => {
+ render(<First />, container);
+ expect(
+ container.innerHTML
+ ).to.equal(
+ innerHTML('<div><button>Increase! 0</button><p>0</p></div>')
+ );
+ });
+
+ it('should handle update upon click', (done) => {
+ render(<First />, container);
+ const buttons = Array.prototype.slice.call(container.querySelectorAll('button'));
+
+ buttons.forEach(button => button.click());
+ requestAnimationFrame(() => {
+ expect(
+ container.innerHTML
+ ).to.equal(
+ innerHTML('<div><button>Increase! 1</button><p>1</p></div>')
+ );
+ done();
+ });
+ });
+ });
+});
\ No newline at end of file
|
fixed issue with a root component regenerating
|
infernojs_inferno
|
train
|
c5e66883ed1a8ed91369f23c9f08de4cd8c1d32b
|
diff --git a/mod/hotpot/report/default.php b/mod/hotpot/report/default.php
index <HASH>..<HASH> 100644
--- a/mod/hotpot/report/default.php
+++ b/mod/hotpot/report/default.php
@@ -544,8 +544,9 @@ class hotpot_default_report {
}
}
function print_text_start(&$course, &$hotpot, &$options) {
+ $downloadfilename = clean_filename("$course->shortname $hotpot->name.txt");
header("Content-Type: application/download\n");
- header("Content-Disposition: attachment; filename=$course->shortname-$hotpot->name.txt");
+ header("Content-Disposition: attachment; filename=$downloadfilename");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0,pre-check=0");
header("Pragma: public");
|
use clean_filename for filename of text file download
|
moodle_moodle
|
train
|
715ae7e5dcbee832860bca09fffd71ea4ba645ff
|
diff --git a/src/satosa/internal_data.py b/src/satosa/internal_data.py
index <HASH>..<HASH> 100644
--- a/src/satosa/internal_data.py
+++ b/src/satosa/internal_data.py
@@ -99,8 +99,12 @@ class DataConverter(object):
"""
internal_dict = {}
- for internal_key in self.from_internal_attributes:
- external_key = self.from_internal_attributes[internal_key][external_type]
+ for internal_key, mapping in self.from_internal_attributes.items():
+ if external_type not in mapping:
+ # skip this internal attribute if we have no mapping in the specified profile
+ continue
+
+ external_key = mapping[external_type]
attribute_values = self._collate_attribute_values_by_priority_order(external_key,
external_dict)
if attribute_values: # Only insert key if it has some values
|
Don't raise exception if no mapping exists for an internal attribute in a certain profile.
|
IdentityPython_SATOSA
|
train
|
5ef018c20659585fcf7313704a53916cd23aefac
|
diff --git a/src/PhpImap/Mailbox.php b/src/PhpImap/Mailbox.php
index <HASH>..<HASH> 100644
--- a/src/PhpImap/Mailbox.php
+++ b/src/PhpImap/Mailbox.php
@@ -164,15 +164,35 @@ class Mailbox {
}
/**
- * Creates a new mailbox specified by mailbox.
- *
+ * Creates a new mailbox
+ * @param $name
* @return bool
*/
+ public function createMailbox($name) {
+ return imap_createmailbox($this->getImapStream(), imap_utf7_encode($this->imapPath . '.' . $name));
+ }
+
+ /**
+ * Delete mailbox
+ * @param $name
+ * @return bool
+ */
+ public function deleteMailbox($name) {
+ return imap_deletemailbox($this->getImapStream(), imap_utf7_encode($this->imapPath . '.' . $name));
+ }
- public function createMailbox() {
- return imap_createmailbox($this->getImapStream(), imap_utf7_encode($this->imapPath));
+ /**
+ * Rename mailbox
+ * @param $oldName
+ * @param $newName
+ * @return bool
+ */
+ public function renameMailbox($oldName, $newName) {
+ return imap_renamemailbox($this->getImapStream(), imap_utf7_encode($this->imapPath . '.' . $oldName), imap_utf7_encode($this->imapPath . '.' . $newName));
}
+
+
/**
* Gets status information about the given mailbox.
*
@@ -181,7 +201,6 @@ class Mailbox {
*
* @return stdClass if the box doesn't exist
*/
-
public function statusMailbox() {
return imap_status($this->getImapStream(), $this->imapPath, SA_ALL);
}
@@ -194,7 +213,6 @@ class Mailbox {
*
* @return array listing the folders
*/
-
public function getListingFolders() {
$folders = imap_list($this->getImapStream(), $this->imapPath, "*");
foreach($folders as $key => $folder) {
|
Mailbox create/rename/delete methods
closes #<I>
|
barbushin_php-imap
|
train
|
844951ff44fe6f910565b674e5639e027933a774
|
diff --git a/src/directives/scroll-container.js b/src/directives/scroll-container.js
index <HASH>..<HASH> 100644
--- a/src/directives/scroll-container.js
+++ b/src/directives/scroll-container.js
@@ -1,5 +1,5 @@
-angular.module('duScroll.scrollContainer', ['duScroll.scrollContainerAPI']).
-directive('duScrollContainer', function(scrollContainerAPI){
+angular.module('duScroll.scrollContainer', ['duScroll.scrollContainerAPI', 'duScroll.spyAPI']).
+directive('duScrollContainer', function(scrollContainerAPI, spyAPI){
return {
restrict: 'A',
scope: true,
@@ -8,8 +8,22 @@ directive('duScrollContainer', function(scrollContainerAPI){
pre: function preLink($scope, iElement, iAttrs, controller) {
iAttrs.$observe('duScrollContainer', function(element) {
if(angular.isString(element)) {
- element = document.getElementById(element);
+ var elementId = element;
+ element = document.getElementById(elementId);
+
+ //Rebind scroll watchers on location change
+ var rebindContainer = function() {
+ var newElement = document.getElementById(elementId);
+ if($scope.$$destroyed || $scope.$parent.$$destroyed || !newElement) {
+ return;
+ }
+ element = angular.element(newElement);
+ scrollContainerAPI.setContainer($scope, element);
+ spyAPI.rebindContainer($scope, element);
+ };
+ $scope.$on('$locationChangeSuccess', rebindContainer);
}
+
element = (angular.isElement(element) ? angular.element(element) : iElement);
scrollContainerAPI.setContainer($scope, element);
$scope.$on('$destroy', function() {
diff --git a/src/services/spy-api.js b/src/services/spy-api.js
index <HASH>..<HASH> 100644
--- a/src/services/spy-api.js
+++ b/src/services/spy-api.js
@@ -1,5 +1,5 @@
angular.module('duScroll.spyAPI', ['duScroll.scrollContainerAPI']).
-factory('spyAPI', function($rootScope, scrollContainerAPI, duScrollGreedy) {
+factory('spyAPI', function($rootScope, $timeout, scrollContainerAPI, duScrollGreedy) {
var createScrollHandler = function(context) {
return function() {
var container = context.container,
@@ -72,6 +72,21 @@ factory('spyAPI', function($rootScope, scrollContainerAPI, duScrollGreedy) {
delete contexts[id];
};
+ var rebindContainer = function($scope, container) {
+ var context = getContextForScope($scope);
+ if(context.container) {
+ context.container.off('scroll', context.handler);
+ }
+ if(container) {
+ context.container = container;
+ context.handler = createScrollHandler(context);
+ container.on('scroll', context.handler);
+ $timeout(function() {
+ container.triggerHandler('scroll');
+ }, 0);
+ }
+ };
+
var defaultContextId = createContext($rootScope);
var getContextForScope = function(scope) {
@@ -123,6 +138,7 @@ factory('spyAPI', function($rootScope, scrollContainerAPI, duScrollGreedy) {
removeSpy: removeSpy,
createContext: createContext,
destroyContext: destroyContext,
+ rebindContainer: rebindContainer,
getContextForScope: getContextForScope
};
});
|
Rebind scroll container watchers on location change. Fixes #<I>.
|
oblador_angular-scroll
|
train
|
189aa0ea705f5aa68f54307ec7d1552ec51b48f5
|
diff --git a/bin/index.js b/bin/index.js
index <HASH>..<HASH> 100755
--- a/bin/index.js
+++ b/bin/index.js
@@ -122,7 +122,6 @@ if (argv.help || argv._[0] === 'help') {
options = profiles[argv.profile || argv._[0]];
console.log('Using profile ' + (argv.profile ? argv.profile : argv._[0]));
} else {
- console.log('Using default profile');
options = {
up: argv.up || defaultUp,
down: argv.down || defaultDown,
|
Remove default profile console log (that was confusing)
|
sitespeedio_throttle
|
train
|
6fc7a230074774c3351e63517a216ee40683aa68
|
diff --git a/utils/multires/generate.py b/utils/multires/generate.py
index <HASH>..<HASH> 100755
--- a/utils/multires/generate.py
+++ b/utils/multires/generate.py
@@ -298,7 +298,7 @@ if haov < 360 or vaov < 180:
genPreview = False
if genPreview:
# Generate SHT-hash preview
- shtHash = img2shtHash(np.array(Image.open(args.inputFile)))
+ shtHash = img2shtHash(np.array(Image.open(args.inputFile).resize((1024, 512))))
if args.thumbnailSize > 0:
# Create low-resolution base64-encoded equirectangular preview image
img = Image.open(args.inputFile)
|
Resize image before SHT calculation to ensure even dimensions (fixes #<I>).
This probably also speeds up the calculation.
|
mpetroff_pannellum
|
train
|
0f2bd9b0854fa426338c04a804efdfd94a1efd50
|
diff --git a/pylls/__init__.py b/pylls/__init__.py
index <HASH>..<HASH> 100644
--- a/pylls/__init__.py
+++ b/pylls/__init__.py
@@ -17,3 +17,8 @@
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+__all__ = ['client', 'cachet']
+
+from pylls import client
+from pylls import cachet
|
Fixing imports for python3
|
outini_python-pylls
|
train
|
e08c981888ab17c53b808408ac90a33fa6644d5e
|
diff --git a/lib/reports_kit/configuration.rb b/lib/reports_kit/configuration.rb
index <HASH>..<HASH> 100644
--- a/lib/reports_kit/configuration.rb
+++ b/lib/reports_kit/configuration.rb
@@ -13,7 +13,6 @@ module ReportsKit
self.autocomplete_results_method = nil
self.cache_duration = 5.minutes
self.cache_store = nil
- self.context_record_method = nil
self.custom_methods = {}
self.default_dimension_limit = 30
self.default_properties = nil
|
Remove call to Configuration#context_record_method=, which is deprecated
|
tombenner_reports_kit
|
train
|
dac56751e6c53f06078c85eaed414a80c0fdf487
|
diff --git a/lib/dat-tcp/version.rb b/lib/dat-tcp/version.rb
index <HASH>..<HASH> 100644
--- a/lib/dat-tcp/version.rb
+++ b/lib/dat-tcp/version.rb
@@ -1,3 +1,3 @@
module DatTCP
- VERSION = "0.3.1"
+ VERSION = "0.4.0"
end
|
<I>
* Replace internal worker pool with DatWorkerPool (#<I>)
|
redding_dat-tcp
|
train
|
6a31f2f6f1a4c722fccb9fe5186f02194e2d9c54
|
diff --git a/src/Omnipay/Pacnet/Message/AuthorizeRequest.php b/src/Omnipay/Pacnet/Message/AuthorizeRequest.php
index <HASH>..<HASH> 100644
--- a/src/Omnipay/Pacnet/Message/AuthorizeRequest.php
+++ b/src/Omnipay/Pacnet/Message/AuthorizeRequest.php
@@ -13,7 +13,7 @@ class AuthorizeRequest extends SubmitRequest
$data['PymtType'] = 'cc_preauth';
- if ( ! $this->getTransactionReference()) {
+ if (false !== $this->getTransactionReference()) {
$this->validate('card');
$data['CardBrand'] = $this->getCard()->getBrand();
|
My guess is this was why the build is failing
|
mfauveau_omnipay-pacnet
|
train
|
b6f9453ab41a56053fb669df3f29d50be7566c45
|
diff --git a/lib/dynamic_paperclip/attachment_style_generator.rb b/lib/dynamic_paperclip/attachment_style_generator.rb
index <HASH>..<HASH> 100644
--- a/lib/dynamic_paperclip/attachment_style_generator.rb
+++ b/lib/dynamic_paperclip/attachment_style_generator.rb
@@ -19,7 +19,7 @@ module DynamicPaperclip
attachment = klass.find(id).send(name)
# When the filename is wrong, return a 404
- if attachment.original_filename != URI.unescape(match[:filename])
+ if !attachment.exists? || attachment.original_filename != URI.unescape(match[:filename])
return [404, {}, []]
end
|
Verify if the original image file exists. Returns a <I> if not.
|
room118solutions_dynamic_paperclip
|
train
|
932f299bc0cf55c24a294d1d2fba7dde466e1a36
|
diff --git a/lib/blocklib.php b/lib/blocklib.php
index <HASH>..<HASH> 100644
--- a/lib/blocklib.php
+++ b/lib/blocklib.php
@@ -2537,6 +2537,6 @@ function blocks_add_default_system_blocks() {
}
$newblocks = array('private_files', 'online_users', 'badges', 'calendar_month', 'calendar_upcoming');
- $newcontent = array('lp', 'course_overview');
+ $newcontent = array('lp', 'myoverview');
$page->blocks->add_blocks(array(BLOCK_POS_RIGHT => $newblocks, 'content' => $newcontent), 'my-index', $subpagepattern);
}
diff --git a/lib/db/upgrade.php b/lib/db/upgrade.php
index <HASH>..<HASH> 100644
--- a/lib/db/upgrade.php
+++ b/lib/db/upgrade.php
@@ -2611,5 +2611,15 @@ function xmldb_main_upgrade($oldversion) {
upgrade_main_savepoint(true, 2017031400.00);
}
+ if ($oldversion < 2017040300.04) {
+
+ // If the 'Course overview' block is no longer present, replace with the 'My overview' block.
+ if (!file_exists($CFG->dirroot . '/blocks/course_overview/block_course_overview.php')) {
+ $DB->set_field('block_instances', 'blockname', 'myoverview', array('blockname' => 'course_overview'));
+ }
+
+ upgrade_main_savepoint(true, 2017040300.04);
+ }
+
return true;
}
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 = 2017033100.00; // YYYYMMDD = weekly release date of this DEV branch.
+$version = 2017040300.04; // YYYYMMDD = weekly release date of this DEV branch.
// RR = release increments - 00 in DEV branches.
// .XX = incremental changes.
|
MDL-<I> core: upgrade code for introduction of block_myoverview
Part of MDL-<I> epic.
|
moodle_moodle
|
train
|
e6b32e21adeaaa96103911992dd09c7bbd2d853c
|
diff --git a/cake/console/libs/acl.php b/cake/console/libs/acl.php
index <HASH>..<HASH> 100644
--- a/cake/console/libs/acl.php
+++ b/cake/console/libs/acl.php
@@ -1,10 +1,6 @@
<?php
-/* SVN FILE: $Id$ */
-
/**
- * Short description for file.
- *
- * Long description for file
+ * Acl Shell provides Acl access in the CLI environment
*
* PHP versions 4 and 5
*
@@ -220,13 +216,38 @@ class AclShell extends Shell {
$this->_checkArgs(2, 'getPath');
$this->checkNodeType();
extract($this->__dataVars());
- $id = ife(is_numeric($this->args[1]), intval($this->args[1]), $this->args[1]);
+ $identifier = $this->parseIdentifier($this->args[1]);
+
+ $id = $this->_getNodeId($class, $identifier);
$nodes = $this->Acl->{$class}->getPath($id);
+
if (empty($nodes)) {
- $this->error(sprintf(__("Supplied Node '%s' not found", true), $this->args[1]), __("No tree returned.", true));
+ $this->error(
+ sprintf(__("Supplied Node '%s' not found", true), $this->args[1]),
+ __("No tree returned.", true)
+ );
}
for ($i = 0; $i < count($nodes); $i++) {
- $this->out(str_repeat(' ', $i) . "[" . $nodes[$i][$class]['id'] . "]" . $nodes[$i][$class]['alias'] . "\n");
+ $this->_outputNode($class, $nodes[$i], $i);
+ }
+ }
+
+/**
+ * Outputs a single node, Either using the alias or Model.key
+ *
+ * @param string $class Class name that is being used.
+ * @param array $node Array of node information.
+ * @param integer $indent indent level.
+ * @return void
+ * @access protected
+ **/
+ function _outputNode($class, $node, $indent) {
+ $indent = str_repeat(' ', $indent);
+ $data = $node[$class];
+ if ($data['alias']) {
+ $this->out($indent . "[" . $data['id'] . "] " . $data['alias']);
+ } else {
+ $this->out($indent . "[" . $data['id'] . "] " . $data['model'] . '.' . $data['foreign_key']);
}
}
diff --git a/cake/tests/cases/console/libs/acl.test.php b/cake/tests/cases/console/libs/acl.test.php
index <HASH>..<HASH> 100644
--- a/cake/tests/cases/console/libs/acl.test.php
+++ b/cake/tests/cases/console/libs/acl.test.php
@@ -1,6 +1,4 @@
<?php
-/* SVN FILE: $Id$ */
-
/**
* AclShell Test file
*
@@ -270,5 +268,37 @@ class AclShellTest extends CakeTestCase {
$this->Task->expectAt(3, 'out', array(new PatternExpectation('/not allowed/'), true));
$this->Task->check();
}
+
+/**
+ * test inherit and that it 0's the permission fields.
+ *
+ * @return void
+ **/
+ function testInherit() {
+ $this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create');
+ $this->Task->expectAt(0, 'out', array(new PatternExpectation('/Permission granted/'), true));
+ $this->Task->grant();
+
+ $this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'all');
+ $this->Task->expectAt(1, 'out', array(new PatternExpectation('/permission inherited/i'), true));
+ $this->Task->inherit();
+
+ $node = $this->Task->Acl->Aro->read(null, 4);
+ $this->assertFalse(empty($node['Aco'][0]));
+ $this->assertEqual($node['Aco'][0]['Permission']['_create'], 0);
+ }
+
+/**
+ * test getting the path for an aro/aco
+ *
+ * @return void
+ **/
+ function testGetPath() {
+ $this->Task->args = array('aro', 'AuthUser.2');
+ $this->Task->expectAt(0, 'out', array('[1] ROOT'));
+ $this->Task->expectAt(1, 'out', array(' [2] admins'));
+ $this->Task->expectAt(2, 'out', array(' [4] Elrond'));
+ $this->Task->getPath();
+ }
}
?>
\ No newline at end of file
|
Adding tests for getPath and inherit.
Refactoring the output of getPath
|
cakephp_cakephp
|
train
|
e346c01e0db97841c218c821e574a363e522e4cf
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -63,7 +63,7 @@ function invokeSequentialTargets(config) {
let targetOptions = { _targets, target, targetName, config: (config[namespace] || {}) };
acc.push(targetOptions);
} else {
- console.log('no target found');
+ console.log(`[${chalk.yellow("Target Not Found")}]`, targetName);
}
return acc;
}
|
clearer error when target does not exist
|
targets-framework_targets
|
train
|
e905f4de5f1b234f5a34e1e124b7017805374b55
|
diff --git a/bin/yaml-validator.js b/bin/yaml-validator.js
index <HASH>..<HASH> 100644
--- a/bin/yaml-validator.js
+++ b/bin/yaml-validator.js
@@ -8,8 +8,6 @@
* Licensed under the MIT license.
*/
-'use strict';
-
const fs = require('fs'),
path = require('path');
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -6,8 +6,6 @@
* Licensed under the MIT license.
*/
-'use strict';
-
const fs = require('fs');
const yaml = require('js-yaml');
diff --git a/tests/cli_test.js b/tests/cli_test.js
index <HASH>..<HASH> 100644
--- a/tests/cli_test.js
+++ b/tests/cli_test.js
@@ -6,8 +6,6 @@
* Licensed under the MIT license.
*/
-'use strict';
-
const fs = require('fs'),
path = require('path'),
{
diff --git a/tests/index_test.js b/tests/index_test.js
index <HASH>..<HASH> 100644
--- a/tests/index_test.js
+++ b/tests/index_test.js
@@ -6,15 +6,12 @@
* Licensed under the MIT license.
*/
-'use strict';
-
const fs = require('fs');
const tape = require('tape');
const Validator = require('../index');
-
tape('Exporting function', (test) => {
test.plan(2);
|
Who needs strict when its already bed time for ES5? :santa:
|
paazmaya_yaml-validator
|
train
|
a796bc67b72c4c11f22fc1720dbb4810d990976a
|
diff --git a/src/Transport/StreamInsert.php b/src/Transport/StreamInsert.php
index <HASH>..<HASH> 100644
--- a/src/Transport/StreamInsert.php
+++ b/src/Transport/StreamInsert.php
@@ -57,21 +57,12 @@ class StreamInsert
$this->request->header('Transfer-Encoding', 'chunked');
$this->request->setReadFunction($callback);
- $this->request->setCallbackFunction(function (Request $request) {
- fclose($this->source);
- });
-
- $this->curlerRolling->addQueLoop($this->request);
- $this->curlerRolling->execLoopWait();
-
+ $this->curlerRolling->execOne($this->request, true);
$statement = new Statement($this->request);
$statement->error();
- } catch (\Exception $e) {
- if (is_resource($this->source)) {
- fclose($this->source);
- }
- throw $e;
+ return $statement;
+ } finally {
+ fclose($this->source);
}
- return $statement;
}
}
\ No newline at end of file
|
FIX: one stream work faster and safe than loop
|
smi2_phpClickHouse
|
train
|
2ead87f0af9f35aa2290fb8355cc9f544859c48b
|
diff --git a/src/commands/status/index.js b/src/commands/status/index.js
index <HASH>..<HASH> 100644
--- a/src/commands/status/index.js
+++ b/src/commands/status/index.js
@@ -8,7 +8,14 @@ class StatusCommand extends Command {
async run() {
const { globalConfig, api, site } = this.netlify
const current = globalConfig.get('userId')
- const accessToken = this.configToken
+ const [ accessToken, location ] = this.getConfigToken()
+
+ if (!accessToken) {
+ this.log(`Not logged in. Please log in to see site status.`)
+ this.log()
+ this.log('Login with "netlify login" command')
+ this.exit()
+ }
const siteId = site.id
@@ -16,29 +23,26 @@ class StatusCommand extends Command {
Current Netlify User │
──────────────────────┘`)
let accountData
- if (accessToken) {
- const accounts = await api.listAccountsForUser()
- const user = await this.netlify.api.getCurrentUser()
+ const accounts = await api.listAccountsForUser()
+ const user = await this.netlify.api.getCurrentUser()
- const ghuser = this.netlify.globalConfig.get(`users.${current}.auth.github.user`)
- accountData = {
- Name: get(user, 'full_name'),
- // 'Account slug': get(personal, 'slug'),
- // 'Account id': get(personal, 'id'),
- // Name: get(personal, 'billing_name'),
- Email: get(user, 'email'),
- Github: ghuser
- }
- const teamsData = {}
+ const ghuser = this.netlify.globalConfig.get(`users.${current}.auth.github.user`)
+ accountData = {
+ Name: get(user, 'full_name'),
+ // 'Account slug': get(personal, 'slug'),
+ // 'Account id': get(personal, 'id'),
+ // Name: get(personal, 'billing_name'),
+ Email: get(user, 'email'),
+ Github: ghuser
+ }
+ const teamsData = {}
- accounts.forEach(team => {
- return (teamsData[team.name] = team.roles_allowed.join(' '))
- })
+ accounts.forEach(team => {
+ return (teamsData[team.name] = team.roles_allowed.join(' '))
+ })
+
+ accountData.Teams = teamsData
- accountData.Teams = teamsData
- } else {
- this.error(`Not logged in. Log in to see site status.`)
- }
this.log(prettyjson.render(clean(accountData)))
|
update netlify status logic & exit early if no token
|
netlify_cli
|
train
|
2d379e211b1bab9fc0f9114fbd87591a4264ec9e
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -1,17 +1,22 @@
#encoding: utf-8
+import io
import os
import re
-from setuptools import setup, find_packages
+
+from setuptools import find_packages, setup
# parse version from ate/__init__.py
with open(os.path.join(os.path.dirname(__file__), 'ate', '__init__.py')) as f:
version = re.compile(r"__version__\s+=\s+'(.*)'", re.I).match(f.read()).group(1)
+with io.open("README.md", encoding='utf-8') as f:
+ long_description = f.read()
+
setup(
name='HttpRunner',
version=version,
description='HTTP test runner, not just about api test and load test.',
- long_description="HTTP test runner, not just about api test and load test.",
+ long_description=long_description,
author='Leo Lee',
author_email='mail@debugtalk.com',
url='https://github.com/debugtalk/HttpRunner',
|
setup long description read from README
|
HttpRunner_HttpRunner
|
train
|
88019ca0af112c4507b237a275267839ba7c2715
|
diff --git a/ruby/import-js/importer.rb b/ruby/import-js/importer.rb
index <HASH>..<HASH> 100644
--- a/ruby/import-js/importer.rb
+++ b/ruby/import-js/importer.rb
@@ -3,7 +3,6 @@ require 'yaml'
module ImportJS
class Importer
def initialize
- @buffer = VIM::Buffer.current
@config = { 'lookup_paths' => ['.'], 'aliases' => {} }
config_file = '.importjs'
if File.exist? config_file
@@ -30,22 +29,26 @@ module ImportJS
private
+ def buffer
+ VIM::Buffer.current
+ end
+
def write_imports(variable_name, path_to_file)
current_imports = find_current_imports
current_imports.length.times do
- @buffer.delete(1)
+ buffer.delete(1)
end
current_imports << "var #{variable_name} = require('#{path_to_file}');"
current_imports.sort!.uniq!
current_imports.reverse.each do |import_line|
- @buffer.append(0, import_line)
+ buffer.append(0, import_line)
end
- unless @buffer[current_imports.length + 1].strip.empty?
+ unless buffer[current_imports.length + 1].strip.empty?
# Add a newline after imports
- @buffer.append(current_imports.length, '')
+ buffer.append(current_imports.length, '')
end
VIM.message("[import-js] Imported `#{path_to_file}`")
@@ -53,8 +56,8 @@ module ImportJS
def find_current_imports
lines = []
- @buffer.count.times do |n|
- line = @buffer[n + 1]
+ buffer.count.times do |n|
+ line = buffer[n + 1]
break unless line.match(/^var\s+.+=\s+require\(.*\);\s*$/)
lines << line
end
|
Don't memoize buffer
I ran into a bug where the import would end up in a different buffer. It
turns out that a past me was a bit stupid and decided to memoize the
buffer in an instance variable.
|
Galooshi_import-js
|
train
|
14a4dfb41e7f3109f9ccbfb09d250900de4db09f
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -50,7 +50,7 @@ class ReleaseCheck(Command):
def run(self):
from subprocess import check_output
- tag = check_output(['git', 'describe', '--all', '--exact-match', 'HEAD']).strip()
+ tag = check_output(['git', 'describe', 'HEAD']).strip()
version = read_version()
if tag != version:
print('Missing %s tag on release' % version)
|
Fix release check for multiple versions of git
|
TriOptima_tri.form
|
train
|
640925c22c4f634a3efc31c4bab95eb34868888f
|
diff --git a/src/main/java/com/slickqa/client/model/Feature.java b/src/main/java/com/slickqa/client/model/Feature.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/slickqa/client/model/Feature.java
+++ b/src/main/java/com/slickqa/client/model/Feature.java
@@ -5,6 +5,9 @@ public class Feature {
/* A String representation of a BSON ObjectId */
private String id = null;
private String name = null;
+ private StoredFile img = null;
+ private String imgUrl = null;
+
public String getDescription() {
return description;
}
@@ -25,6 +28,19 @@ public class Feature {
public void setName(String name) {
this.name = name;
}
+ public StoredFile getImg() {
+ return img;
+ }
+ public void setImg(StoredFile img) {
+ this.img = img;
+ }
+ public String getImgUrl() {
+ return imgUrl;
+ }
+ public void setImgUrl(String imgUrl) {
+ this.imgUrl = imgUrl;
+ }
+
@Override
public String toString() {
@@ -33,6 +49,8 @@ public class Feature {
sb.append(" description: ").append(description).append("\n");
sb.append(" id: ").append(id).append("\n");
sb.append(" name: ").append(name).append("\n");
+ sb.append(" img: ").append(img).append("\n");
+ sb.append(" imgUrl: ").append(imgUrl).append("\n");
sb.append("}\n");
return sb.toString();
}
|
adding img and imgUrl to Feature
|
slickqa_slickqa-java-client
|
train
|
3a440c847e6a28dac1140d1e29aa03083dba1e6c
|
diff --git a/api/firewaller/application.go b/api/firewaller/application.go
index <HASH>..<HASH> 100644
--- a/api/firewaller/application.go
+++ b/api/firewaller/application.go
@@ -64,3 +64,32 @@ func (s *Application) IsExposed() (bool, error) {
}
return result.Result, nil
}
+
+// ExposeInfo returns a flag to indicate whether an application is exposed
+// as well as any endpoint-specific expose settings (if present).
+func (s *Application) ExposeInfo() (bool, map[string]params.ExposedEndpoint, error) {
+ if s.st.BestAPIVersion() < 6 {
+ // ExposeInfo() was introduced in FirewallerAPIV6.
+ return false, nil, errors.NotImplementedf("ExposeInfo() (need V6+)")
+ }
+
+ var results params.ExposeInfoResults
+ args := params.Entities{
+ Entities: []params.Entity{{Tag: s.tag.String()}},
+ }
+ err := s.st.facade.FacadeCall("GetExposeInfo", args, &results)
+ if err != nil {
+ return false, nil, err
+ }
+ if len(results.Results) != 1 {
+ return false, nil, fmt.Errorf("expected 1 result, got %d", len(results.Results))
+ }
+ result := results.Results[0]
+ if result.Error != nil {
+ if params.IsCodeNotFound(result.Error) {
+ return false, nil, errors.NewNotFound(result.Error, "")
+ }
+ return false, nil, result.Error
+ }
+ return result.Exposed, result.ExposedEndpoints, nil
+}
diff --git a/api/firewaller/application_test.go b/api/firewaller/application_test.go
index <HASH>..<HASH> 100644
--- a/api/firewaller/application_test.go
+++ b/api/firewaller/application_test.go
@@ -9,7 +9,10 @@ import (
gc "gopkg.in/check.v1"
"github.com/juju/juju/api/firewaller"
+ "github.com/juju/juju/apiserver/params"
+ "github.com/juju/juju/core/network"
"github.com/juju/juju/core/watcher/watchertest"
+ "github.com/juju/juju/state"
)
type applicationSuite struct {
@@ -78,3 +81,31 @@ func (s *applicationSuite) TestIsExposed(c *gc.C) {
c.Assert(err, jc.ErrorIsNil)
c.Assert(isExposed, jc.IsFalse)
}
+
+func (s *applicationSuite) TestExposeInfo(c *gc.C) {
+ err := s.application.MergeExposeSettings(map[string]state.ExposedEndpoint{
+ "": {
+ ExposeToSpaceIDs: []string{network.AlphaSpaceId},
+ ExposeToCIDRs: []string{"10.0.0.0/16", "192.168.0.0/24"},
+ },
+ })
+ c.Assert(err, jc.ErrorIsNil)
+
+ isExposed, exposedEndpoints, err := s.apiApplication.ExposeInfo()
+ c.Assert(err, jc.ErrorIsNil)
+ c.Assert(isExposed, jc.IsTrue)
+ c.Assert(exposedEndpoints, gc.DeepEquals, map[string]params.ExposedEndpoint{
+ "": {
+ ExposeToSpaces: []string{network.AlphaSpaceId},
+ ExposeToCIDRs: []string{"10.0.0.0/16", "192.168.0.0/24"},
+ },
+ })
+
+ err = s.application.ClearExposed()
+ c.Assert(err, jc.ErrorIsNil)
+
+ isExposed, exposedEndpoints, err = s.apiApplication.ExposeInfo()
+ c.Assert(err, jc.ErrorIsNil)
+ c.Assert(isExposed, jc.IsFalse)
+ c.Assert(exposedEndpoints, gc.HasLen, 0)
+}
|
Implement client for ExposeInfo API call
|
juju_juju
|
train
|
22e3e3235099faae6ae552dff4b0de57c0d59982
|
diff --git a/cli/src/main/java/com/bazaarvoice/auth/hmac/cli/HurlCli.java b/cli/src/main/java/com/bazaarvoice/auth/hmac/cli/HurlCli.java
index <HASH>..<HASH> 100644
--- a/cli/src/main/java/com/bazaarvoice/auth/hmac/cli/HurlCli.java
+++ b/cli/src/main/java/com/bazaarvoice/auth/hmac/cli/HurlCli.java
@@ -10,6 +10,7 @@ import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup;
import net.sourceforge.argparse4j.inf.Namespace;
+import javax.ws.rs.core.HttpHeaders;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
@@ -20,6 +21,8 @@ import static net.sourceforge.argparse4j.impl.Arguments.storeConst;
import static net.sourceforge.argparse4j.impl.Arguments.storeTrue;
public class HurlCli {
+ private static final String USER_AGENT = "hurl/" + HurlCli.class.getPackage().getImplementationVersion();
+
public static void main(String[] args) {
ArgumentParser parser = ArgumentParsers.newArgumentParser("hurl")
.description("Like curl, for hmac-protected resources")
@@ -109,8 +112,10 @@ public class HurlCli {
}
WebResource.Builder request = client.resource(url).getRequestBuilder();
+ request.header(HttpHeaders.USER_AGENT, USER_AGENT);
+
if (contentType != null && contentType.length() > 0) {
- request.header("Content-Type", contentType);
+ request.header(HttpHeaders.CONTENT_TYPE, contentType);
}
if ("POST".equalsIgnoreCase(method)) {
|
Include user agent string for hurl
|
bazaarvoice_jersey-hmac-auth
|
train
|
2de4ab0068f1db5f2ccb28fafe1117665d5b91e4
|
diff --git a/_uniout.py b/_uniout.py
index <HASH>..<HASH> 100644
--- a/_uniout.py
+++ b/_uniout.py
@@ -6,11 +6,6 @@ __all__ = ['unescape', 'make_unistream', 'runs_in_ipython']
import sys
import re
-try:
- import chardet
-except ImportError:
- chardet = None
-
def literalize(content, is_unicode=False):
quote_mark = "'"
@@ -29,18 +24,10 @@ def unescape_string_literal(b, target_encoding):
b = b[1:-1].decode('string-escape')
- if chardet:
-
- r = chardet.detect(b)
- confidence, b_encoding = r['confidence'], r['encoding']
-
- if confidence >= 0.5 and b_encoding.lower() not in ('ascii', target_encoding.lower()):
- try:
- b = b.decode(b_encoding)
- except (UnicodeDecodeError, LookupError):
- pass
- else:
- b = b.encode(target_encoding)
+ try:
+ b.decode(target_encoding)
+ except UnicodeDecodeError:
+ b = b.encode('string-escape')
return literalize(b)
|
removed the chardet feature
It is because there has some problem to show the correct literal.
|
moskytw_uniout
|
train
|
3a4aba88ce3d67d393d19d3d1db10e473d6f29f8
|
diff --git a/pyathena/__init__.py b/pyathena/__init__.py
index <HASH>..<HASH> 100644
--- a/pyathena/__init__.py
+++ b/pyathena/__init__.py
@@ -6,6 +6,12 @@ import datetime
from pyathena.error import * # noqa
+try:
+ from multiprocessing import cpu_count
+except ImportError:
+ def cpu_count():
+ return None
+
__version__ = '1.10.3'
# Globals https://www.python.org/dev/peps/pep-0249/#globals
diff --git a/pyathena/async_cursor.py b/pyathena/async_cursor.py
index <HASH>..<HASH> 100644
--- a/pyathena/async_cursor.py
+++ b/pyathena/async_cursor.py
@@ -5,18 +5,12 @@ from __future__ import unicode_literals
import logging
from concurrent.futures.thread import ThreadPoolExecutor
+from pyathena import cpu_count
from pyathena.common import CursorIterator
from pyathena.cursor import BaseCursor
from pyathena.error import NotSupportedError, ProgrammingError
from pyathena.result_set import AthenaResultSet
-try:
- from multiprocessing import cpu_count
-except ImportError:
- def cpu_count():
- return None
-
-
_logger = logging.getLogger(__name__)
diff --git a/pyathena/async_pandas_cursor.py b/pyathena/async_pandas_cursor.py
index <HASH>..<HASH> 100644
--- a/pyathena/async_pandas_cursor.py
+++ b/pyathena/async_pandas_cursor.py
@@ -4,17 +4,11 @@ from __future__ import unicode_literals
import logging
+from pyathena import cpu_count
from pyathena.async_cursor import AsyncCursor
from pyathena.common import CursorIterator
from pyathena.result_set import AthenaPandasResultSet
-try:
- from multiprocessing import cpu_count
-except ImportError:
- def cpu_count():
- return None
-
-
_logger = logging.getLogger(__name__)
diff --git a/pyathena/util.py b/pyathena/util.py
index <HASH>..<HASH> 100644
--- a/pyathena/util.py
+++ b/pyathena/util.py
@@ -2,12 +2,14 @@
from __future__ import absolute_import
from __future__ import unicode_literals
+import concurrent
import functools
import logging
import threading
import re
import uuid
from collections import OrderedDict
+from concurrent.futures.thread import ThreadPoolExecutor
import tenacity
from future.utils import iteritems
@@ -15,7 +17,7 @@ from past.builtins import xrange
from tenacity import (after_log, retry_if_exception,
stop_after_attempt, wait_exponential)
-from pyathena import DataError, OperationalError
+from pyathena import DataError, OperationalError, cpu_count
from pyathena.model import AthenaCompression
_logger = logging.getLogger(__name__)
@@ -112,7 +114,9 @@ def to_parquet(df, conn, bucket, prefix, compression=None, flavor='spark'):
def to_sql(df, name, conn, location, schema='default',
index=False, index_label=None, partitions=None, chunksize=None,
if_exists='fail', compression=None, flavor='spark',
- type_mappings=to_sql_type_mappings):
+ type_mappings=to_sql_type_mappings,
+ executor_class=ThreadPoolExecutor,
+ max_workers=(cpu_count() or 1) * 5):
# TODO Supports orc, avro, json, csv or tsv format
if if_exists not in ('fail', 'replace', 'append'):
raise ValueError('`{0}` is not valid for if_exists'.format(if_exists))
@@ -146,25 +150,23 @@ def to_sql(df, name, conn, location, schema='default',
if index:
reset_index(df, index_label)
- if partitions:
- for keys, group in df.groupby(by=partitions, observed=True):
- group = group.drop(partitions, axis=1)
- partition_prefix = '/'.join(['{0}={1}'.format(key, val)
- for key, val in zip(partitions, list(keys))])
- for chunk in get_chunks(group, chunksize):
- # TODO threading
- # TODO executor, max_workers
- to_parquet(chunk, conn, bucket,
- '{0}/{1}'.format(key_prefix, partition_prefix),
- compression=compression,
- flavor=flavor)
- else:
- for chunk in get_chunks(df, chunksize):
- # TODO threading
- # TODO executor, max_workers
- to_parquet(chunk, conn, bucket, key_prefix,
- compression=compression,
- flavor=flavor)
+ with executor_class(max_workers=max_workers) as e:
+ futures = []
+ if partitions:
+ for keys, group in df.groupby(by=partitions, observed=True):
+ group = group.drop(partitions, axis=1)
+ partition_prefix = '/'.join(['{0}={1}'.format(key, val)
+ for key, val in zip(partitions, list(keys))])
+ for chunk in get_chunks(group, chunksize):
+ futures.append(e.submit(to_parquet, chunk, conn, bucket,
+ '{0}/{1}'.format(key_prefix, partition_prefix),
+ compression, flavor))
+ else:
+ for chunk in get_chunks(df, chunksize):
+ futures.append(e.submit(to_parquet, chunk, conn, bucket,
+ key_prefix, compression, flavor))
+ for future in concurrent.futures.as_completed(futures):
+ future.result()
ddl = generate_ddl(df=df,
name=name,
|
Implement parallel execution of conversion to parquet and upload to s3
|
laughingman7743_PyAthena
|
train
|
da7fe8b87a0aa31953a3fb5aa2aedf6bcaddcf14
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -78,7 +78,15 @@ BinWrapper.prototype.use = function (str) {
return this._use;
}
- this._use = path.join(this.dest(), str);
+ var opts = { path: this.dest(), global: this.global, exclude: 'node_modules/.bin' };
+ var bin = find(str, opts);
+
+ if (bin && bin.length > 0) {
+ this._use = bin[0];
+ } else {
+ this._use = path.join(this.dest(), str);
+ }
+
return this;
};
@@ -95,7 +103,7 @@ BinWrapper.prototype.run = function (cmd, cb) {
var self = this;
this.parse(this.src());
- this.test(cmd, function (err, bin) {
+ this.test(cmd, function (err) {
if (err) {
return download(self.src(), self.dest(), { mode: '0755' })
.on('error', function (err) {
@@ -112,8 +120,6 @@ BinWrapper.prototype.run = function (cmd, cb) {
});
}
- self.dest(path.dirname(bin));
- self.use(path.basename(bin));
cb();
});
};
@@ -127,12 +133,10 @@ BinWrapper.prototype.run = function (cmd, cb) {
*/
BinWrapper.prototype.test = function (cmd, cb) {
- var opts = { path: this.dest(), global: this.global, exclude: 'node_modules/.bin' };
- var bin = find(path.basename(this.use()), opts) || [];
var self = this;
- if (bin.length > 0) {
- return binCheck(bin[0], cmd, function (err, works) {
+ if (this.use()) {
+ return binCheck(self.use(), cmd, function (err, works) {
if (err) {
return cb(err);
}
@@ -142,16 +146,16 @@ BinWrapper.prototype.test = function (cmd, cb) {
}
if (self.opts.version) {
- return binCheck(bin[0], ['--version'], function (err, works, msg) {
+ return binCheck(self.use(), ['--version'], function (err, works, msg) {
if (msg.indexOf(self.opts.version) !== -1) {
- return cb(null, bin[0]);
+ return cb(null, self.use());
}
cb('wrong version');
});
}
- cb(null, bin[0]);
+ cb(null, self.use());
});
}
|
Global binary path should be set outside the `.run()` method
|
kevva_bin-wrapper
|
train
|
fe3e24d64de9026d24015e24c618a2bf6bbe404c
|
diff --git a/src/JimmyOak/Collection/Collection.php b/src/JimmyOak/Collection/Collection.php
index <HASH>..<HASH> 100644
--- a/src/JimmyOak/Collection/Collection.php
+++ b/src/JimmyOak/Collection/Collection.php
@@ -10,7 +10,7 @@ class Collection implements \ArrayAccess
/** @var string */
private $objectType;
/** @var array */
- private $collection = [];
+ protected $collection = [];
public function __construct($objectType)
{
|
Collection internal var protected for extending purposes
|
jimmyoak_utilities
|
train
|
de69d7a7e5a6edaa007bae9f74c0665299480579
|
diff --git a/src/yield_handler.js b/src/yield_handler.js
index <HASH>..<HASH> 100644
--- a/src/yield_handler.js
+++ b/src/yield_handler.js
@@ -7,7 +7,7 @@ import Promise from 'bluebird';
let yieldHandlers = [];
export function isThenable( obj ) {
- return obj !== void 0 && obj !== null && (obj instanceof Promise || typeof obj.then === 'function');
+ return obj && typeof obj.then === 'function';
}
export let isPromise = isThenable;
@@ -44,19 +44,14 @@ function isNativeObject( obj ) {
}
}
-class YieldException extends TypeError {
-}
-
function objectToPromise( obj ) {
let results = new obj.constructor();
let keys = Object.keys( obj );
let promises = new Array( keys.length );
let current = 0;
- let toPromiseThis = toPromise.bind( this );
-
for( let key of keys ) {
- let promise = toPromiseThis( obj[key] );
+ let promise = toPromise.call( this, obj[key] );
if( isThenable( promise ) ) {
results[key] = void 0;
@@ -73,27 +68,18 @@ function objectToPromise( obj ) {
function resolveGenerator( gen ) {
return new Promise( ( resolve, reject ) => {
- let toPromiseThis = toPromise.bind( this );
-
function next( ret ) {
if( ret.done ) {
return resolve( ret.value );
} else {
- try {
- let value = toPromiseThis( ret.value, true );
+ let value = toPromise.call( this, ret.value );
- if( isThenable( value ) ) {
- return value.then( onFulfilled, onRejected );
+ if( isThenable( value ) ) {
+ return value.then( onFulfilled, onRejected );
- } else {
- let err = new TypeError( `You may only yield a function, promise, generator, array, or object, but the following object was passed: "${ret.value}"` );
-
- return onRejected( err );
- }
-
- } catch( err ) {
- return onRejected( err );
+ } else {
+ return onRejected( new TypeError( `You may only yield a function, promise, generator, array, or object, but the following object was passed: "${ret.value}"` ) );
}
}
}
@@ -120,16 +106,14 @@ function resolveGenerator( gen ) {
} );
}
-function toPromise( value, strict ) {
+function toPromise( value ) {
if( isThenable( value ) ) {
return value;
} else if( Array.isArray( value ) ) {
- let toPromiseThis = toPromise.bind( this );
-
- return Promise.all( value.map( val => toPromiseThis( val ) ) );
+ return Promise.all( value.map( toPromise, this ) );
- } else if( typeof value === 'object' && value !== null ) {
+ } else if( value && typeof value === 'object' ) {
if( isGenerator( value ) ) {
return resolveGenerator.call( this, value );
@@ -182,12 +166,7 @@ function toPromise( value, strict ) {
}
}
- if( strict ) {
- throw new YieldException( `You may only yield a function, promise, generator, array, or object, but the following object was passed: "${value}"` );
-
- } else {
- return Promise.resolve( value );
- }
+ return value;
}
export function addYieldHandler( handler ) {
@@ -204,15 +183,16 @@ let addedYieldHandler = false;
if( !addedYieldHandler ) {
Promise.coroutine.addYieldHandler( function( value ) {
try {
- return toPromise.call( this, value, true );
-
- } catch( err ) {
- if( err instanceof YieldException ) {
- return void 0;
+ let res = toPromise.call( this, value );
- } else {
- return Promise.reject( err );
+ if( !isThenable( res ) ) {
+ throw new TypeError( `You may only yield a function, promise, generator, array, or object, but the following object was passed: "${value}"` );
}
+
+ return res;
+
+ } catch( err ) {
+ return Promise.reject( err );
}
} );
|
src: Boost performance in a couple ways.
Mostly by getting rid of the function binds. Apparently calling with a specific context is still faster than binding it to that context.
Also since everything checks if the result is thenable anyway, I removed the exception stuff.
|
novacrazy_bluebird-co
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.