hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
e30424808e0628f3d624e15a2a204218e376caba
|
diff --git a/source/Components/View/Compiler/Processors/Templater/Node.php b/source/Components/View/Compiler/Processors/Templater/Node.php
index <HASH>..<HASH> 100644
--- a/source/Components/View/Compiler/Processors/Templater/Node.php
+++ b/source/Components/View/Compiler/Processors/Templater/Node.php
@@ -341,6 +341,11 @@ class Node
$this->nodes = $node->nodes;
}
+ /**
+ * Register string node content.
+ *
+ * @param string|array $content String content or html tokens.
+ */
protected function registerContent($content)
{
if ($this->extended || empty($content))
@@ -389,6 +394,13 @@ class Node
$this->nodes[] = $content;
}
+ /**
+ * Compile node content.
+ *
+ * @param array $compiled
+ * @param array $outerBlocks All outer blocks will be aggregated in this array.
+ * @return string
+ */
public function compile(&$compiled = [], &$outerBlocks = [])
{
//We have to pre-compile outer nodes first
|
more node refactoring.
|
spiral_exceptions
|
train
|
e698b41fd23dc4968cb80b60e9b0ff9d5fcd09e3
|
diff --git a/test_xbee1.py b/test_xbee1.py
index <HASH>..<HASH> 100755
--- a/test_xbee1.py
+++ b/test_xbee1.py
@@ -1,9 +1,8 @@
#! /usr/bin/python
import unittest
-from test_xbee import FakeDevice
+from test_xbee import FakeDevice, FakeReadDevice
from xbee1 import XBee1
-import pdb
"""
test_xbee1.py
@@ -181,7 +180,19 @@ class TestReadFromDevice(unittest.TestCase):
XBee1 class should properly read and parse binary data from a serial
port device.
"""
- pass
+ def test_read_at(self):
+ """
+ read and parse a parameterless AT command
+ """
+ device = FakeReadDevice('\x7E\x00\x05\x88DMY\x01\x8c')
+ xbee = XBee1(device)
+
+ info = xbee.wait_read_frame()
+ expected_info = {'id':'at_response',
+ 'frame_id':'D',
+ 'command':'MY',
+ 'status':'\x01'}
+ self.assertEqual(info, expected_info)
if __name__ == '__main__':
unittest.main()
|
Added test for reading an AT command response from a device
|
niolabs_python-xbee
|
train
|
42f36c25d1b6f0f821ee11a78fe9df5d06f9440c
|
diff --git a/debian/changelog b/debian/changelog
index <HASH>..<HASH> 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,4 +1,6 @@
[Michele Simionato]
+ * Honored the `individual_curves` parameter in avg_losses, agg_losses and
+ and agg_curves (i.e. by default only expose the statistical results)
* Refactored the `oq commands` and removed the redundant `oq help` since
there is `oq --help` instead
* Support for input URLs associated to an input archive
diff --git a/demos/risk/EventBasedRisk/job_eb.ini b/demos/risk/EventBasedRisk/job_eb.ini
index <HASH>..<HASH> 100644
--- a/demos/risk/EventBasedRisk/job_eb.ini
+++ b/demos/risk/EventBasedRisk/job_eb.ini
@@ -36,7 +36,7 @@ exposure_file = exposure_model.xml
[risk_calculation]
asset_hazard_distance = 20
-individual_curves = true
+individual_curves = false
minimum_asset_loss = {'structural': 1000, 'nonstructural': 1000}
[outputs]
diff --git a/openquake/calculators/ebrisk.py b/openquake/calculators/ebrisk.py
index <HASH>..<HASH> 100644
--- a/openquake/calculators/ebrisk.py
+++ b/openquake/calculators/ebrisk.py
@@ -260,4 +260,4 @@ class EbriskCalculator(event_based.EventBasedCalculator):
self.datastore.create_dframe('avg_gmf', self.avg_gmf.items())
prc = PostRiskCalculator(oq, self.datastore.calc_id)
prc.datastore.parent = self.datastore.parent
- prc.run()
+ prc.run(exports='')
diff --git a/openquake/calculators/export/risk.py b/openquake/calculators/export/risk.py
index <HASH>..<HASH> 100644
--- a/openquake/calculators/export/risk.py
+++ b/openquake/calculators/export/risk.py
@@ -23,7 +23,6 @@ import numpy
import pandas
from openquake.baselib import hdf5
-from openquake.baselib.python3compat import decode
from openquake.hazardlib.stats import compute_stats2
from openquake.risklib import scientific
from openquake.calculators.extract import (
diff --git a/openquake/calculators/scenario_risk.py b/openquake/calculators/scenario_risk.py
index <HASH>..<HASH> 100644
--- a/openquake/calculators/scenario_risk.py
+++ b/openquake/calculators/scenario_risk.py
@@ -163,7 +163,8 @@ class ScenarioRiskCalculator(base.RiskCalculator):
set_rlzs_stats(self.datastore, 'agg_losses',
agg_id=K, loss_types=oq.loss_names, units=units)
else: # event_based_risk, run post_risk
- post_risk.PostRiskCalculator(oq, self.datastore.calc_id).run()
+ prc = post_risk.PostRiskCalculator(oq, self.datastore.calc_id)
+ prc.run(exports='')
@base.calculators.add('event_based_risk')
diff --git a/openquake/engine/engine.py b/openquake/engine/engine.py
index <HASH>..<HASH> 100644
--- a/openquake/engine/engine.py
+++ b/openquake/engine/engine.py
@@ -162,9 +162,10 @@ def expose_outputs(dstore, owner=getpass.getuser(), status='complete'):
dskeys.add('uhs') # export them
if oq.hazard_maps:
dskeys.add('hmaps') # export them
- if 'avg_losses-stats' in dstore or (
- 'avg_losses-rlzs' in dstore and len(rlzs)):
- dskeys.add('avg_losses-stats')
+ if len(rlzs) > 1 and not oq.individual_curves:
+ for out in ['avg_losses-rlzs', 'agg_losses-rlzs', 'agg_curves-rlzs']:
+ if out in dskeys:
+ dskeys.remove(out)
if 'curves-rlzs' in dstore and len(rlzs) == 1:
dskeys.add('loss_curves-rlzs')
if 'curves-stats' in dstore and len(rlzs) > 1:
@@ -172,12 +173,8 @@ def expose_outputs(dstore, owner=getpass.getuser(), status='complete'):
if oq.conditional_loss_poes: # expose loss_maps outputs
if 'loss_curves-stats' in dstore:
dskeys.add('loss_maps-stats')
- if 'all_loss_ratios' in dskeys:
- dskeys.remove('all_loss_ratios') # export only specific IDs
if 'ruptures' in dskeys and 'scenario' in calcmode:
exportable.remove('ruptures') # do not export, as requested by Vitor
- if 'rup_loss_table' in dskeys: # keep it hidden for the moment
- dskeys.remove('rup_loss_table')
if 'hmaps' in dskeys and not oq.hazard_maps:
dskeys.remove('hmaps') # do not export the hazard maps
if logs.dbcmd('get_job', dstore.calc_id) is None:
@@ -188,11 +185,11 @@ def expose_outputs(dstore, owner=getpass.getuser(), status='complete'):
keysize = []
for key in sorted(dskeys & exportable):
try:
- size_mb = dstore.get_attr(key, 'nbytes') / MB
+ size_mb = dstore.getsize(key) / MB
except (KeyError, AttributeError):
size_mb = None
keysize.append((key, size_mb))
- ds_size = os.path.getsize(dstore.filename) / MB
+ ds_size = dstore.getsize() / MB
logs.dbcmd('create_outputs', dstore.calc_id, keysize, ds_size)
|
Honor individual_curves in risk results too
|
gem_oq-engine
|
train
|
8961bdc00bcc1d6cdbc0de9b25ca92114da0c0ad
|
diff --git a/packages/plugin-conversation/src/conversation.js b/packages/plugin-conversation/src/conversation.js
index <HASH>..<HASH> 100644
--- a/packages/plugin-conversation/src/conversation.js
+++ b/packages/plugin-conversation/src/conversation.js
@@ -81,6 +81,17 @@ const Conversation = SparkPlugin.extend({
}
return this._createGrouped(params);
+ })
+ .then((c) => {
+ if (!params.files) {
+ return c;
+ }
+
+ return this.spark.conversation.share(c, params.files)
+ .then((a) => {
+ c.activities.items.push(a);
+ return c;
+ });
});
},
diff --git a/packages/plugin-conversation/test/integration/spec/create.js b/packages/plugin-conversation/test/integration/spec/create.js
index <HASH>..<HASH> 100644
--- a/packages/plugin-conversation/test/integration/spec/create.js
+++ b/packages/plugin-conversation/test/integration/spec/create.js
@@ -9,8 +9,9 @@ import {patterns} from '@ciscospark/common';
import CiscoSpark from '@ciscospark/spark-core';
import {assert} from '@ciscospark/test-helper-chai';
import testUsers from '@ciscospark/test-helper-test-users';
-import {find, map} from 'lodash';
+import {find, last, map} from 'lodash';
import uuid from 'uuid';
+import fh from '@ciscospark/test-helper-file';
describe(`plugin-conversation`, function() {
this.timeout(20000);
@@ -39,6 +40,10 @@ describe(`plugin-conversation`, function() {
]);
}));
+ let sampleTextOne = `sample-text-one.txt`;
+ before(() => fh.fetch(sampleTextOne)
+ .then((f) => {sampleTextOne = f;}));
+
after(() => Promise.all([
spark.mercury.disconnect(),
mccoy.spark.mercury.disconnect()
@@ -108,7 +113,13 @@ describe(`plugin-conversation`, function() {
.then((c) => spark.conversation.get(c, {activitiesLimit: 2}))
.then((c) => assert.equal(c.activities.items[1].object.displayName, `comment`)));
- it(`creates a conversation with a share`);
+ it(`creates a conversation with a share`, () => spark.conversation.create({participants, files: [sampleTextOne]})
+ .then((c) => spark.conversation.get(c, {activitiesLimit: 10}))
+ .then((c) => {
+ assert.equal(last(c.activities.items).verb, `share`);
+ return spark.conversation.download(last(c.activities.items).object.files.items[0]);
+ })
+ .then((file) => fh.isMatchingFile(file, sampleTextOne)));
it(`ensures the current user is in the participants list`, () => spark.conversation.create({comment: `comment`, participants: [mccoy, checkov]})
.then((c) => spark.conversation.get(c, {includeParticipants: true}))
|
feat(plugin-conversation): allow creating a conversation with a file
|
webex_spark-js-sdk
|
train
|
c730099a9dddd8ae0ef58f60b6d0c0a7f7f79c5f
|
diff --git a/fs/archive/_utils.py b/fs/archive/_utils.py
index <HASH>..<HASH> 100644
--- a/fs/archive/_utils.py
+++ b/fs/archive/_utils.py
@@ -2,8 +2,13 @@
from __future__ import absolute_import
from __future__ import unicode_literals
+import os
+import io
+import sys
+import errno
import importlib
+
def import_from_names(*names):
for name in names:
try:
@@ -11,3 +16,27 @@ def import_from_names(*names):
except ImportError:
continue
return None
+
+
+def writable_path(path):
+ if os.path.exists(path):
+ return os.access(path, os.W_OK)
+ try:
+ with open(path, 'w'):
+ pass
+ except OSError as oe:
+ return False
+ else:
+ os.remove(path)
+ return True
+
+
+def writable_stream(handle):
+ if isinstance(handle, io.IOBase) and sys.version_info >= (3, 5):
+ return handle.writable()
+ try:
+ handle.write(b'')
+ except (io.UnsupportedOperation, OSError):
+ return False
+ else:
+ return True
|
Add methods to _utils to check if path and handles are writable
|
althonos_fs.archive
|
train
|
2cefd2f6eadc78d494e1023f58732be66013379f
|
diff --git a/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/PortalDialectResolver.java b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/PortalDialectResolver.java
index <HASH>..<HASH> 100644
--- a/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/PortalDialectResolver.java
+++ b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/PortalDialectResolver.java
@@ -18,6 +18,7 @@ import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import org.apereo.portal.utils.hibernate4.dialects.MySQL5InnoDBCompressedDialect;
import org.apereo.portal.utils.hibernate4.dialects.PostgreSQL81Dialect;
+import org.apereo.portal.utils.hibernate4.dialects.Oracle12ForceClobDialect;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.SQLServer2005Dialect;
import org.hibernate.service.jdbc.dialect.internal.AbstractDialectResolver;
|
fix(#<I>): Import the new Oracle<I>ForceClobDialect dialect
|
Jasig_uPortal
|
train
|
c893d0b197322fca84ce80e01d2508c003a45b4e
|
diff --git a/lib/mohawk/adapters/uia/menu_item.rb b/lib/mohawk/adapters/uia/menu_item.rb
index <HASH>..<HASH> 100644
--- a/lib/mohawk/adapters/uia/menu_item.rb
+++ b/lib/mohawk/adapters/uia/menu_item.rb
@@ -6,18 +6,11 @@ module Mohawk
end
def select
- wait_until do
- begin
- element.select_menu_item(*path)
- true
- rescue
- false
- end
- end
+ until_successful { element.select_menu_item(*path) }
end
def click
- element.menu_item(*path).click_center
+ until_successful { element.menu_item(*path).click_center }
end
def exist?
@@ -34,6 +27,17 @@ module Mohawk
def path
[@locator[:path] || @locator[:text]].flatten
end
+
+ def until_successful(&block)
+ wait_until do
+ begin
+ block.call
+ true
+ rescue
+ false
+ end
+ end
+ end
end
end
end
diff --git a/spec/lib/mohawk/menu_spec.rb b/spec/lib/mohawk/menu_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lib/mohawk/menu_spec.rb
+++ b/spec/lib/mohawk/menu_spec.rb
@@ -20,7 +20,11 @@ describe 'menus' do
context 'waiting for' do
Given { Mohawk.timeout = 2 }
+
When(:non_existent_menu) { main_form.non_existent_menu }
+ When(:click_non_existent_menu) { main_form.click_non_existent_menu }
+
Then { expect(non_existent_menu).to have_failed(Mohawk::Waiter::WaitTimeout) }
+ Then { expect(click_non_existent_menu).to have_failed(Mohawk::Waiter::WaitTimeout) }
end
end
\ No newline at end of file
|
MenuItem#click waits until it is successful
|
leviwilson_mohawk
|
train
|
c7f4ebb72657ba456150dd965633ba5d1824c4c3
|
diff --git a/dist/Leaflet.BlurredLocation.js b/dist/Leaflet.BlurredLocation.js
index <HASH>..<HASH> 100644
--- a/dist/Leaflet.BlurredLocation.js
+++ b/dist/Leaflet.BlurredLocation.js
@@ -539,7 +539,7 @@ BlurredLocation = function BlurredLocation(options) {
options = options || {};
options.location = options.location || {
lat: 1.0,
- lon: 1.0
+ lon: 10.0
};
options.zoom = options.zoom || 6;
@@ -555,14 +555,14 @@ BlurredLocation = function BlurredLocation(options) {
options.Interface = options.Interface || require('./ui/Interface.js');
- gridSystemOptions = options.gridSystemOptions || {};
+ var gridSystemOptions = options.gridSystemOptions || {};
gridSystemOptions.map = options.map;
gridSystemOptions.gridWidthInPixels = gridWidthInPixels;
gridSystemOptions.getMinimumGridWidth = getMinimumGridWidth;
- gridSystem = options.gridSystem(gridSystemOptions);
+ var gridSystem = options.gridSystem(gridSystemOptions);
- InterfaceOptions = options.InterfaceOptions || {};
+ var InterfaceOptions = options.InterfaceOptions || {};
InterfaceOptions.panMap = panMap;
InterfaceOptions.getPlacenameFromCoordinates = getPlacenameFromCoordinates;
InterfaceOptions.getLat = getLat;
@@ -570,7 +570,7 @@ BlurredLocation = function BlurredLocation(options) {
InterfaceOptions.map = options.map;
InterfaceOptions.getPrecision = getPrecision;
- Interface = options.Interface(InterfaceOptions);
+ var Interface = options.Interface(InterfaceOptions);
var tileLayer = L.tileLayer("https://a.tiles.mapbox.com/v3/jywarren.map-lmrwb2em/{z}/{x}/{y}.png").addTo(options.map);
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "leaflet-blurred-location",
- "version": "1.1.10",
+ "version": "1.1.11",
"description": "",
"main": "Gruntfile.js",
"scripts": {
diff --git a/spec/javascripts/test_spec.js b/spec/javascripts/test_spec.js
index <HASH>..<HASH> 100644
--- a/spec/javascripts/test_spec.js
+++ b/spec/javascripts/test_spec.js
@@ -12,14 +12,14 @@ describe("Basic testing", function() {
it("Checks if getLon returns the correct longitude with correct precision", function () {
blurredLocation.setZoom(13);
- expect(blurredLocation.getLon()).toBe(1.0);
+ expect(blurredLocation.getLon()).toBe(10);
blurredLocation.setZoom(10);
- expect(blurredLocation.getLon()).toBe(1.0);
+ expect(blurredLocation.getLon()).toBe(10);
});
it("Checks if goTo changes the map location to given parameters", function() {
expect(blurredLocation.getLat()).toBe(1.0);
- expect(blurredLocation.getLon()).toBe(1.0);
+ expect(blurredLocation.getLon()).toBe(10);
blurredLocation.goTo(51.50223, -0.09123213, 13);
expect(blurredLocation.getLat()).toBe(51.50);
expect(blurredLocation.getLon()).toBe(-0.09);
diff --git a/src/blurredLocation.js b/src/blurredLocation.js
index <HASH>..<HASH> 100644
--- a/src/blurredLocation.js
+++ b/src/blurredLocation.js
@@ -24,14 +24,14 @@ BlurredLocation = function BlurredLocation(options) {
options.Interface = options.Interface || require('./ui/Interface.js');
- gridSystemOptions = options.gridSystemOptions || {};
+ var gridSystemOptions = options.gridSystemOptions || {};
gridSystemOptions.map = options.map;
gridSystemOptions.gridWidthInPixels = gridWidthInPixels;
gridSystemOptions.getMinimumGridWidth = getMinimumGridWidth;
- gridSystem = options.gridSystem(gridSystemOptions);
+ var gridSystem = options.gridSystem(gridSystemOptions);
- InterfaceOptions = options.InterfaceOptions || {};
+ var InterfaceOptions = options.InterfaceOptions || {};
InterfaceOptions.panMap = panMap;
InterfaceOptions.getPlacenameFromCoordinates = getPlacenameFromCoordinates;
InterfaceOptions.getLat = getLat;
@@ -39,7 +39,7 @@ BlurredLocation = function BlurredLocation(options) {
InterfaceOptions.map = options.map;
InterfaceOptions.getPrecision = getPrecision;
- Interface = options.Interface(InterfaceOptions);
+ var Interface = options.Interface(InterfaceOptions);
var tileLayer = L.tileLayer("https://a.tiles.mapbox.com/v3/jywarren.map-lmrwb2em/{z}/{x}/{y}.png").addTo(options.map);
|
Remove globals (#<I>)
* tried to remove globals - manually tested to work
* version update
* re-added deps
* Update test_spec.js
|
publiclab_leaflet-blurred-location
|
train
|
e6ce6bb132e6b62e1b9acf32bae5fa1708015f28
|
diff --git a/src/cli/common.js b/src/cli/common.js
index <HASH>..<HASH> 100644
--- a/src/cli/common.js
+++ b/src/cli/common.js
@@ -81,6 +81,8 @@ function normalizeSpecHandling(options) {
}
if (options.spec === undefined) return;
+ options.flatten = true; //infer flattening when extracting specs
+
if (!options.spec.dir) options.spec.dir = ".";
if (!options.spec.url) options.spec.url = "/";
}
diff --git a/test/cli/common.js b/test/cli/common.js
index <HASH>..<HASH> 100644
--- a/test/cli/common.js
+++ b/test/cli/common.js
@@ -224,21 +224,21 @@ describe("common cli module", function () {
should: "should set options from run control",
runControl: { log: "warn", spec: true },
input: { _: ["export"] },
- expected: Object.assign(defaultSettings("export"), { log: "warn", spec: { dir: ".", url: "/" } })
+ expected: Object.assign(defaultSettings("export"), { log: "warn", spec: { dir: ".", url: "/" }, flatten: true })
},
{
description: "when run control file present with spec values and 'export'",
should: "should set options from run control",
runControl: { log: "warn", spec: { dir: "specs", url: "/specs/" } },
input: { _: ["export"] },
- expected: Object.assign(defaultSettings("export"), { log: "warn", spec: { dir: "specs", url: "/specs/" } })
+ expected: Object.assign(defaultSettings("export"), { log: "warn", spec: { dir: "specs", url: "/specs/" }, flatten: true })
},
{
description: "when run control file present with spec values and 'start'",
should: "should set options from run control but delete 'spec'",
runControl: { log: "warn", spec: { dir: "specs", url: "/specs/" } },
input: { _: ["start"] },
- expected: Object.assign(defaultSettings("start"), { log: "warn", spec: { dir: "specs", url: "/specs/" } })
+ expected: Object.assign(defaultSettings("start"), { log: "warn", spec: { dir: "specs", url: "/specs/" }, flatten: true })
},
{
description: "when run control file present with export values",
@@ -259,7 +259,7 @@ describe("common cli module", function () {
should: "should set options from run control and override values from export",
runControl: { log: "warn", spec: true, export: { root: "foo", output: "bar", format: "baz", log: "info", spec: { dir: "specs", url: "/specs/" } } },
input: { _: ["export"] },
- expected: Object.assign(defaultSettings("export"), { log: "info", root: ["foo"], output: "bar", format: "baz", spec: { dir: "specs", url: "/specs/" } })
+ expected: Object.assign(defaultSettings("export"), { log: "info", root: ["foo"], output: "bar", format: "baz", spec: { dir: "specs", url: "/specs/" }, flatten: true })
},
{
description: "when run control file present with start values and overrides",
@@ -273,7 +273,7 @@ describe("common cli module", function () {
should: "should set options from cli switches",
runControl: { log: "warn", export: { root: "foo", output: "bar", format: "baz", log: "info", spec: { dir: "specs", url: "/specs/" } } },
input: { _: ["export"], log: "error", root: ["no foo"], output: "no bar", format: "no baz", spec: { dir: "no-specs", url: "/no-specs/" } },
- expected: Object.assign(defaultSettings("export"), { log: "error", root: ["no foo"], output: "no bar", format: "no baz", spec: { dir: "no-specs", url: "/no-specs/" } })
+ expected: Object.assign(defaultSettings("export"), { log: "error", root: ["no foo"], output: "no bar", format: "no baz", spec: { dir: "no-specs", url: "/no-specs/" }, flatten: true })
},
];
|
Infer flatten when extracting specs
|
lynx-json_lynx-docs
|
train
|
1500d9fb65efeb1046e7f0b0593e79e92e7a5e35
|
diff --git a/drivers/python2/rethinkdb/internal.py b/drivers/python2/rethinkdb/internal.py
index <HASH>..<HASH> 100644
--- a/drivers/python2/rethinkdb/internal.py
+++ b/drivers/python2/rethinkdb/internal.py
@@ -71,14 +71,6 @@ class WriteQuery(query.BaseExpression):
root.type = p.Query.WRITE
self._write_ast(root.write_query)
-class Delete(WriteQuery):
- def __init__(self, parent_view):
- self.parent_view = parent_view
-
- def _write_ast(self, parent):
- parent.type = p.WriteQuery.DELETE
- self.parent_view._write_ast(parent.delete.view)
-
class Insert(WriteQuery):
def __init__(self, table, entries):
self.table = table
@@ -90,6 +82,25 @@ class Insert(WriteQuery):
for entry in self.entries:
entry._write_ast(parent.insert.terms.add())
+class Delete(WriteQuery):
+ def __init__(self, parent_view):
+ self.parent_view = parent_view
+
+ def _write_ast(self, parent):
+ parent.type = p.WriteQuery.DELETE
+ self.parent_view._write_ast(parent.delete.view)
+
+class Mutate(WriteQuery):
+ def __init__(self, parent_view, mapping):
+ super(Mutate, self).__init__()
+ self.parent_view = parent_view
+ self.mapping = mapping
+
+ def _write_ast(self, parent):
+ parent.type = p.WriteQuery.MUTATE
+ self.parent_view._write_ast(parent.mutate.view)
+ self.mapping.write_mapping(parent.mutate.mapping)
+
class InsertStream(WriteQuery):
def __init__(self, table, stream):
self.table = table
diff --git a/drivers/python2/rethinkdb/query.py b/drivers/python2/rethinkdb/query.py
index <HASH>..<HASH> 100644
--- a/drivers/python2/rethinkdb/query.py
+++ b/drivers/python2/rethinkdb/query.py
@@ -406,6 +406,12 @@ class BaseSelection(object):
"""
raise NotImplementedError
+ def mutate(self, mapping):
+ """TODO: get rid of this ?"""
+ if not isinstance(mapping, internal.Function):
+ mapping = internal.Function(mapping)
+ return internal.Mutate(self, mapping)
+
class MultiRowSelection(Stream, BaseSelection):
"""A sequence of rows which can be read or written."""
diff --git a/src/rdb_protocol/query_language.cc b/src/rdb_protocol/query_language.cc
index <HASH>..<HASH> 100644
--- a/src/rdb_protocol/query_language.cc
+++ b/src/rdb_protocol/query_language.cc
@@ -767,8 +767,8 @@ void execute(WriteQuery *w, runtime_environment_t *env, Response *res, const bac
int modified = 0, deleted = 0;
while (boost::shared_ptr<scoped_cJSON_t> json = view.stream->next()) {
variable_val_scope_t::new_scope_t scope_maker(&env->scope);
- env->scope.put_in_scope(w->update().mapping().arg(), json);
- boost::shared_ptr<scoped_cJSON_t> val = eval(w->mutable_update()->mutable_mapping()->mutable_body(), env, backtrace.with("mapping"));
+ env->scope.put_in_scope(w->mutate().mapping().arg(), json);
+ boost::shared_ptr<scoped_cJSON_t> val = eval(w->mutable_mutate()->mutable_mapping()->mutable_body(), env, backtrace.with("mapping"));
if (val->type() == cJSON_NULL) {
point_delete(view.access, json->GetObjectItem(view.primary_key.c_str()), env, backtrace);
diff --git a/test/drivers/python/test2.py b/test/drivers/python/test2.py
index <HASH>..<HASH> 100644
--- a/test/drivers/python/test2.py
+++ b/test/drivers/python/test2.py
@@ -455,6 +455,16 @@ class RDBTest(unittest.TestCase):
self.expect(self.table.map(js('this')), docs)
self.expect(self.table.map(js('this.name')), names)
+ def test_mutate(self):
+ self.clear_table()
+
+ docs = [{"id": 100 + n, "a": n, "b": n % 3} for n in range(10)]
+ self.do_insert(docs)
+
+ self.expect(self.table.mutate(fn('x', R('$x'))), {"modified": len(docs), "deleted": 0})
+
+ self.expect(self.table, docs)
+
# def test_huge(self):
# self.clear_table()
# self.do_insert([{"id": 1}])
|
mutate *actually* works now. fixes #<I>
|
rethinkdb_rethinkdb
|
train
|
b8dd4f7e983cc9b7392b239b40f83167961a0df2
|
diff --git a/lib/zendesk_api/resources.rb b/lib/zendesk_api/resources.rb
index <HASH>..<HASH> 100644
--- a/lib/zendesk_api/resources.rb
+++ b/lib/zendesk_api/resources.rb
@@ -22,11 +22,6 @@ module ZendeskAPI
class Topic < Resource; end
class Bookmark < Resource; end
class Ability < DataResource; end
- class UserView < Resource
- def self.preview(client, options = {})
- Collection.new(client, UserViewRow, options.merge!(:path => "user_views/preview", :verb => :post))
- end
- end
class Group < Resource; end
class SharingAgreement < ReadResource; end
class JobStatus < ReadResource; end
@@ -485,6 +480,12 @@ module ZendeskAPI
end
end
+ class UserView < Rule
+ def self.preview(client, options = {})
+ Collection.new(client, UserViewRow, options.merge!(:path => "user_views/preview", :verb => :post))
+ end
+ end
+
class GroupMembership < Resource
has User
has Group
diff --git a/spec/live/user_view_spec.rb b/spec/live/user_view_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/live/user_view_spec.rb
+++ b/spec/live/user_view_spec.rb
@@ -10,7 +10,7 @@ describe ZendeskAPI::UserView, :delete_after do
}
end
- it_should_be_creatable
it_should_be_readable :user_views
+ it_should_be_creatable
it_should_be_deletable
end
|
UserView is a subclass of Rule
|
zendesk_zendesk_api_client_rb
|
train
|
de6219a76cf3169a9721b2e22f18b1c1242f63f5
|
diff --git a/goristock.py b/goristock.py
index <HASH>..<HASH> 100644
--- a/goristock.py
+++ b/goristock.py
@@ -264,6 +264,6 @@ class goristock(object):
print self.stock_name,self.stock_no
print self.data_date[-1],self.raw_data[-1],self.stock_range[-1]
for i in arg:
- print 'MA%02s %.2f %s(%s)' % (i,self.MA(i),self.MAC(i),self.MA_serial(i)[0])
- print self.MAVOL(1),self.MACVOL(1)
+ print ' - MA%02s %.2f %s(%s)' % (i,self.MA(i),self.MAC(i),self.MA_serial(i)[0])
+ print ' - Volume: %s%s' % (self.MAVOL(1),self.MACVOL(1))
print self.stock_vol
diff --git a/main.py b/main.py
index <HASH>..<HASH> 100644
--- a/main.py
+++ b/main.py
@@ -82,6 +82,8 @@ class goritest(webapp.RequestHandler):
print a.num_data
print a.stock_no,a.stock_name
print a.MA(5),a.MAC(5),a.MA(20),a.MAC(20),a.MA(60),a.MAC(60)
+ print '='*40
+ print a.display(3,6,18)
############## main Models ##############
def main():
|
Tiny change for appengine display.
|
toomore_goristock
|
train
|
859a3587e9d61352d0948c44b19219871caf5683
|
diff --git a/Neos.ContentRepository/Tests/Functional/Domain/NodesTest.php b/Neos.ContentRepository/Tests/Functional/Domain/NodesTest.php
index <HASH>..<HASH> 100644
--- a/Neos.ContentRepository/Tests/Functional/Domain/NodesTest.php
+++ b/Neos.ContentRepository/Tests/Functional/Domain/NodesTest.php
@@ -879,12 +879,16 @@ class NodesTest extends FunctionalTestCase
$childNodeA = $parentNode->createNode('child-node-a');
$childNodeB = $parentNode->createNode('child-node-b');
$childNodeB1 = $childNodeB->createNode('child-node-b1');
+ $childNodeB2 = $childNodeB->createNode('child-node-not-unique');
+ $childNodeC = $parentNode->createNode('child-node-not-unique');
$this->persistenceManager->persistAll();
$childNodeB->moveInto($childNodeA, 'renamed-child-node-b');
+ $childNodeC->moveInto($childNodeB, 'child-node-now-unique');
$this->persistenceManager->persistAll();
$this->assertNull($parentNode->getNode('child-node-b'));
$this->assertSame($childNodeB, $childNodeA->getNode('renamed-child-node-b'));
$this->assertSame($childNodeB1, $childNodeA->getNode('renamed-child-node-b')->getNode('child-node-b1'));
+ $this->assertSame($childNodeC, $childNodeB->getNode('child-node-now-unique'));
}
/**
|
TASK: Added additional assert to existing test
|
neos_neos-development-collection
|
train
|
34ab4c7f8056287afd9c582897ef253241ce41c5
|
diff --git a/angr/sim_type.py b/angr/sim_type.py
index <HASH>..<HASH> 100644
--- a/angr/sim_type.py
+++ b/angr/sim_type.py
@@ -1106,7 +1106,8 @@ def parse_file(defn, preprocess=True):
if piece.name is not None:
out[piece.name] = ty
elif isinstance(piece, pycparser.c_ast.Typedef):
- extra_types[piece.name] = _decl_to_type(piece.type, extra_types)
+ extra_types[piece.name] = copy.copy(_decl_to_type(piece.type, extra_types))
+ extra_types[piece.name].label = piece.name
for ty in ignoreme:
del extra_types[ty]
|
Set typedef types as having a label with their given name (#<I>)
|
angr_angr
|
train
|
82e8d268def2a3863cabad6254ff6a99ec67c382
|
diff --git a/lang/en_utf8/portfolio.php b/lang/en_utf8/portfolio.php
index <HASH>..<HASH> 100644
--- a/lang/en_utf8/portfolio.php
+++ b/lang/en_utf8/portfolio.php
@@ -44,6 +44,7 @@ $string['failedtosendpackage'] = 'Failed to send your data to the selected portf
$string['failedtopackage'] = 'Could not find files to package';
$string['filedenied'] = 'Access denied to this file';
$string['filenotfound'] = 'File not found';
+$string['fileoutputnotsupported'] = 'Rewriting file output is not supported for this format';
$string['format_document'] = 'Document';
$string['format_file'] = 'File';
$string['format_richhtml'] = 'HTML with attachments';
diff --git a/lib/portfolio/formats.php b/lib/portfolio/formats.php
index <HASH>..<HASH> 100644
--- a/lib/portfolio/formats.php
+++ b/lib/portfolio/formats.php
@@ -122,7 +122,7 @@ class portfolio_format_file extends portfolio_format {
}
public static function get_file_directory() {
- throw new portfolio_exception('fileoutputnotsupported', 'portfolio');
+ return false;
}
public static function file_output($file, $options=null) {
|
portfolio MDL-<I> added a missing lang string and removed a too strict exception
|
moodle_moodle
|
train
|
6da6591dbc4a093f4e1fd822fb20608865fdb450
|
diff --git a/plenum/cli/cli.py b/plenum/cli/cli.py
index <HASH>..<HASH> 100644
--- a/plenum/cli/cli.py
+++ b/plenum/cli/cli.py
@@ -121,7 +121,7 @@ class Cli:
psep = re.escape(os.path.sep)
- grams = [
+ self.grams = [
"(\s* (?P<simple>{}) \s*) |".format(relist(self.simpleCmds)),
"(\s* (?P<client_command>{}) \s+ (?P<node_or_cli>clients?) \s+ (?P<client_name>[a-zA-Z0-9]+) \s*) |".format(relist(self.cliCmds)),
"(\s* (?P<node_command>{}) \s+ (?P<node_or_cli>nodes?) \s+ (?P<node_name>[a-zA-Z0-9]+)\s*) |".format(relist(self.nodeCmds)),
@@ -134,9 +134,9 @@ class Cli:
"(\s* (?P<command>list) \s*)"
]
- self.grammar = compile("".join(grams))
+ self.grammar = compile("".join(self.grams))
- lexer = GrammarLexer(self.grammar, lexers={
+ self.lexer = GrammarLexer(self.grammar, lexers={
'node_command': SimpleLexer(Token.Keyword),
'command': SimpleLexer(Token.Keyword),
'helpable': SimpleLexer(Token.Keyword),
@@ -156,7 +156,7 @@ class Cli:
self.clientWC = WordCompleter([])
- completer = GrammarCompleter(self.grammar, {
+ self.completer = GrammarCompleter(self.grammar, {
'node_command': WordCompleter(self.nodeCmds),
'client_command': WordCompleter(self.cliCmds),
'client': WordCompleter(['client']),
@@ -195,8 +195,8 @@ class Cli:
# Create interface.
app = create_prompt_application('{}> '.format(self.name),
- lexer=lexer,
- completer=completer,
+ lexer=self.lexer,
+ completer=self.completer,
style=self.style,
history=pers_hist)
@@ -482,6 +482,8 @@ Commands:
return
else:
names = [nodeName]
+
+ nodes = []
for name in names:
node = self.NodeClass(name,
self.nodeReg,
@@ -494,6 +496,7 @@ Commands:
self.bootstrapClientKey(client, node)
for identifier, verkey in self.externalClientKeys.items():
node.clientAuthNr.addClient(identifier, verkey)
+ nodes.append(node)
def ensureValidClientId(self, clientName):
"""
@@ -599,6 +602,7 @@ Commands:
self.bootstrapClientKey(client, node)
self.clients[clientName] = client
self.clientWC.words = list(self.clients.keys())
+ return client
except ValueError as ve:
self.print(ve.args[0], Token.Error)
|
cli node and client creation return node and client respectively
|
hyperledger_indy-plenum
|
train
|
5b559330e2c0389be052c64b6fcb9951aa600140
|
diff --git a/GEOparse/GEOTypes.py b/GEOparse/GEOTypes.py
index <HASH>..<HASH> 100755
--- a/GEOparse/GEOTypes.py
+++ b/GEOparse/GEOTypes.py
@@ -2,7 +2,7 @@
Classes that represent different GEO entities
"""
-from pandas import DataFrame
+from pandas import DataFrame, concat
from sys import stderr, stdout
import abc
import gzip
@@ -301,6 +301,7 @@ class GDS(SimpleGEO):
SimpleGEO.__init__(self, name=name, metadata=metadata, table=table, columns=columns)
+ self.columns = self.columns.dropna() # effectively deletes the columns with ID_REF
self.subsets = subsets
self.database = database
@@ -400,6 +401,24 @@ class GSE(BaseGEO):
else:
return data[0].join(data[1:])
+ def pivot_samples(self, values, index="ID_REF"):
+ """Construct a table in which columns (names) are the samples, index
+ is a specified column eg. ID_REF and values in the columns are of one
+ specified type.
+
+ :param values: str -- column name present in the GSMs (all)
+ :param index: str -- column name that will become an index in pivoted table
+ :returns: pandas.DataFrame
+
+ """
+ data = []
+ for gsm in self.gsms.values():
+ tmp_data = gsm.table.copy()
+ tmp_data["name"] = gsm.name
+ data.append(tmp_data)
+ ndf = concat(data).pivot(index=index, values=values, columns="name")
+ return ndf
+
def _get_object_as_soft(self):
"""
Return object as SOFT formated string.
|
Added pivot_samples to GSE object
|
guma44_GEOparse
|
train
|
03300b0632d1839b12139022bd0a3aa6055f6ddb
|
diff --git a/tests/Database/DatabaseEloquentBuilderTest.php b/tests/Database/DatabaseEloquentBuilderTest.php
index <HASH>..<HASH> 100755
--- a/tests/Database/DatabaseEloquentBuilderTest.php
+++ b/tests/Database/DatabaseEloquentBuilderTest.php
@@ -477,7 +477,7 @@ class DatabaseEloquentBuilderTest extends PHPUnit_Framework_TestCase
{
$model = new EloquentBuilderTestModelParentStub;
- $builder = $model->select('id')->withCount(['activeFoo' => function($q){
+ $builder = $model->select('id')->withCount(['activeFoo' => function ($q) {
$q->where('bam', '>', 'qux');
}]);
|
Add test for merged wheres in withCount
|
laravel_framework
|
train
|
4732e47ec6196c0c78e8cc06c4b8e3578aad7fa6
|
diff --git a/src/python/twitter/pants/targets/jar_dependency.py b/src/python/twitter/pants/targets/jar_dependency.py
index <HASH>..<HASH> 100644
--- a/src/python/twitter/pants/targets/jar_dependency.py
+++ b/src/python/twitter/pants/targets/jar_dependency.py
@@ -54,7 +54,7 @@ class JarDependency(object):
self.artifacts = []
if ext or url or type_ or classifier:
self.with_artifact(name=name, ext=ext, url=url, type_=type_, classifier=classifier)
- self.id = None
+ self.id = "%s-%s-%s" % (self.org, self.name, self.rev)
self._configurations = [ 'default' ]
# Support legacy method names
@@ -116,7 +116,7 @@ class JarDependency(object):
return not self.__eq__(other)
def __repr__(self):
- return "%s-%s-%s" % (self.org, self.name, self.rev)
+ return self.id
def resolve(self):
yield self
|
Add an "id" field to JarDependency
Auditors: benjy
(sapling split of fb<I>f<I>a<I>b0af<I>d<I>bb<I>d<I>a8ccac)
|
pantsbuild_pants
|
train
|
543ff1563fab099dfb64919a2a275f5adc123a1d
|
diff --git a/db/schema.rb b/db/schema.rb
index <HASH>..<HASH> 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -11,7 +11,7 @@
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 114) do
+ActiveRecord::Schema.define(:version => 115) do
create_table "articles_tags", :id => false, :force => true do |t|
t.integer "article_id"
@@ -23,23 +23,6 @@ ActiveRecord::Schema.define(:version => 114) do
t.string "base_url"
end
- create_table "categories", :force => true do |t|
- t.string "name"
- t.integer "position"
- t.string "permalink"
- t.text "keywords"
- t.text "description"
- t.integer "parent_id"
- end
-
- add_index "categories", ["permalink"], :name => "index_categories_on_permalink"
-
- create_table "categorizations", :force => true do |t|
- t.integer "article_id"
- t.integer "category_id"
- t.boolean "is_primary"
- end
-
create_table "contents", :force => true do |t|
t.string "type"
t.string "title"
diff --git a/spec/controllers/admin/users_controller_spec.rb b/spec/controllers/admin/users_controller_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/controllers/admin/users_controller_spec.rb
+++ b/spec/controllers/admin/users_controller_spec.rb
@@ -77,15 +77,6 @@ describe Admin::UsersController, "rough port of the old functional test" do
expect { User.find(id) }.to_not raise_error
end
end
-
- context "GET" do
- it "destroys the user" do
- id = user.id
- post :destroy, :id => id
- response.should redirect_to(:action => 'index')
- expect { User.find(id) }.to raise_error(ActiveRecord::RecordNotFound)
- end
- end
end
end
|
Fix schema.rb and spec (no more user destroy action)
|
publify_publify
|
train
|
ae034b5ca2498026f1b8cf31bc54ec884e55d7b9
|
diff --git a/gson/src/main/java/com/google/gson/internal/bind/ObjectTypeAdapter.java b/gson/src/main/java/com/google/gson/internal/bind/ObjectTypeAdapter.java
index <HASH>..<HASH> 100644
--- a/gson/src/main/java/com/google/gson/internal/bind/ObjectTypeAdapter.java
+++ b/gson/src/main/java/com/google/gson/internal/bind/ObjectTypeAdapter.java
@@ -85,8 +85,9 @@ public final class ObjectTypeAdapter extends TypeAdapter<Object> {
in.nextNull();
return null;
+ default:
+ throw new IllegalStateException();
}
- throw new IllegalStateException();
}
@SuppressWarnings("unchecked")
|
eliminated eclipse warnings by adding a default label to switch.
|
google_gson
|
train
|
8528581a047fe22e461a9a2cf780d5212b3b711f
|
diff --git a/src/marshmallow/fields.py b/src/marshmallow/fields.py
index <HASH>..<HASH> 100644
--- a/src/marshmallow/fields.py
+++ b/src/marshmallow/fields.py
@@ -52,6 +52,8 @@ __all__ = [
"URL",
"Email",
"IP",
+ "IPv4",
+ "IPv6",
"Method",
"Function",
"Str",
|
Expose IP v4/v6 specific fields for wildcard imports
|
marshmallow-code_marshmallow
|
train
|
ef94c05b02c82a56c84ae2587b3ae17eeb1e470f
|
diff --git a/spec/lib/maven_runner_spec.rb b/spec/lib/maven_runner_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lib/maven_runner_spec.rb
+++ b/spec/lib/maven_runner_spec.rb
@@ -21,7 +21,8 @@ describe Tetra::MavenRunner do
@project.from_directory do
commandline = @kit_runner.get_maven_commandline(".", ["--otheroption"])
- expect(commandline).to eq "./#{executable_path} -Dmaven.repo.local=./kit/m2 -s./kit/m2/settings.xml --otheroption"
+ expected_commandline = "./#{executable_path} -Dmaven.repo.local=./kit/m2 -s./kit/m2/settings.xml --otheroption"
+ expect(commandline).to eq expected_commandline
end
end
it "doesn't return commandline options if Maven is not available" do
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
@@ -1,7 +1,7 @@
# encoding: UTF-8
require "tetra"
-Dir["./spec/support/**/*.rb"].sort.each { |f| require f}
+Dir["./spec/support/**/*.rb"].sort.each { |f| require f }
module Tetra
# custom mock methods
|
Refactoring: project name change to tetra, rubocop fixes
|
moio_tetra
|
train
|
9d6d0530f57c638e51d20f9da2b51cf949e8d02c
|
diff --git a/lib/digest-client.js b/lib/digest-client.js
index <HASH>..<HASH> 100644
--- a/lib/digest-client.js
+++ b/lib/digest-client.js
@@ -126,7 +126,7 @@ module.exports = class DigestClient {
_compileParams(params) {
const parts = [];
for (const i in params) {
- if (['nc', 'algorithm'].includes(i)) parts.push(`${i}=${params[i]}`);
+ if (['nc', 'algorithm', 'qop'].includes(i)) parts.push(`${i}=${params[i]}`);
else parts.push(`${i}="${params[i]}"`);
}
return `Digest ${parts.join(',')}`;
|
on response to Challenge, QOP should be without quotes.
|
davehorton_drachtio-srf
|
train
|
bb6675dbfcac72135ad86a02087ee178ce5dda35
|
diff --git a/hanlp/common/dataset.py b/hanlp/common/dataset.py
index <HASH>..<HASH> 100644
--- a/hanlp/common/dataset.py
+++ b/hanlp/common/dataset.py
@@ -682,13 +682,15 @@ class KMeansSampler(BucketSampler):
class SortingSampler(Sampler):
# noinspection PyMissingConstructor
- def __init__(self, lengths: List[int], batch_size=None, batch_max_tokens=None, shuffle=False) -> None:
+ def __init__(self, lengths: List[int], batch_size=None, batch_max_tokens=None, use_effective_tokens=False,
+ shuffle=False) -> None:
"""A sampler which sort samples according to their lengths. It takes a continuous chunk of sorted samples to
make a batch.
Args:
lengths: Lengths of each sample, usually measured by number of tokens.
batch_max_tokens: Maximum tokens per batch.
+ use_effective_tokens: Whether to calculate effective number of tokens when applying the `batch_max_tokens`.
batch_size: Maximum samples per batch.
shuffle: ``True`` to shuffle batches and samples in a batch.
"""
@@ -701,10 +703,11 @@ class SortingSampler(Sampler):
mini_batch = []
for i in torch.argsort(torch.tensor(lengths), descending=True).tolist():
# if batch_max_tokens:
- if (batch_max_tokens is None or num_tokens + lengths[i] <= batch_max_tokens) and (
+ effective_tokens = lengths[i] if (not mini_batch or not use_effective_tokens) else lengths[mini_batch[0]]
+ if (batch_max_tokens is None or num_tokens + effective_tokens <= batch_max_tokens) and (
batch_size is None or len(mini_batch) < batch_size):
mini_batch.append(i)
- num_tokens += lengths[i]
+ num_tokens += effective_tokens
else:
if not mini_batch: # this sequence is longer than batch_max_tokens
mini_batch.append(i)
@@ -714,9 +717,10 @@ class SortingSampler(Sampler):
else:
self.batch_indices.append(mini_batch)
mini_batch = [i]
- num_tokens = lengths[i]
+ num_tokens = effective_tokens
if mini_batch:
self.batch_indices.append(mini_batch)
+ # print(len(max(self.batch_indices, key=len)))
def __iter__(self):
if self.shuffle:
@@ -766,13 +770,15 @@ class SamplerBuilder(AutoConfigurable, ABC):
class SortingSamplerBuilder(SortingSampler, SamplerBuilder):
# noinspection PyMissingConstructor
- def __init__(self, batch_size=None, batch_max_tokens=None) -> None:
+ def __init__(self, batch_size=None, batch_max_tokens=None, use_effective_tokens=False) -> None:
"""Builds a :class:`~hanlp.common.dataset.SortingSampler`.
Args:
batch_max_tokens: Maximum tokens per batch.
+ use_effective_tokens: Whether to calculate effective number of tokens when applying the `batch_max_tokens`.
batch_size: Maximum samples per batch.
"""
+ self.use_effective_tokens = use_effective_tokens
self.batch_max_tokens = batch_max_tokens
self.batch_size = batch_size
|
Support whether to calculate effective number of tokens when applying the `batch_max_tokens`
|
hankcs_HanLP
|
train
|
b1aa00d9e10df425ca4cbdfb2ad34832f24e98af
|
diff --git a/Branch-SDK/src/io/branch/referral/util/BranchEvent.java b/Branch-SDK/src/io/branch/referral/util/BranchEvent.java
index <HASH>..<HASH> 100644
--- a/Branch-SDK/src/io/branch/referral/util/BranchEvent.java
+++ b/Branch-SDK/src/io/branch/referral/util/BranchEvent.java
@@ -226,7 +226,7 @@ public class BranchEvent {
if (standardProperties.length() > 0) {
reqBody.put(Defines.Jsonkey.EventData.getKey(), standardProperties);
}
- if (isStandardEvent && buoList.size() > 0) {
+ if (buoList.size() > 0) {
JSONArray contentItemsArray = new JSONArray();
reqBody.put(Defines.Jsonkey.ContentItems.getKey(), contentItemsArray);
for (BranchUniversalObject buo : buoList) {
|
DEVEX-<I>: Add BUO to custom
|
BranchMetrics_android-branch-deep-linking
|
train
|
67655f924ad7d10205cb8ff20447e32bf0736755
|
diff --git a/lib/fog/rackspace/models/load_balancers/load_balancer.rb b/lib/fog/rackspace/models/load_balancers/load_balancer.rb
index <HASH>..<HASH> 100644
--- a/lib/fog/rackspace/models/load_balancers/load_balancer.rb
+++ b/lib/fog/rackspace/models/load_balancers/load_balancer.rb
@@ -70,10 +70,6 @@ module Fog
virtual_ips.load(new_virtual_ips)
end
- def connection_logging
- attributes[:connection_logging]
- end
-
def enable_connection_logging
requires :identity
connection.set_connection_logging identity, true
@@ -200,16 +196,15 @@ module Fog
def connection_logging=(new_value)
if !new_value.nil? and new_value.is_a?(Hash)
attributes[:connection_logging] = case new_value['enabled']
- when 'true'
+ when true,'true'
true
- when 'false'
+ when false,'false'
false
end
else
attributes[:connection_logging] = new_value
end
end
-
end
end
end
diff --git a/tests/rackspace/models/load_balancers/load_balancer_tests.rb b/tests/rackspace/models/load_balancers/load_balancer_tests.rb
index <HASH>..<HASH> 100644
--- a/tests/rackspace/models/load_balancers/load_balancer_tests.rb
+++ b/tests/rackspace/models/load_balancers/load_balancer_tests.rb
@@ -25,6 +25,11 @@ Shindo.tests('Fog::Rackspace::LoadBalancers | load_balancer', ['rackspace']) do
returns(true) { @instance.connection_logging }
end
+ tests('#enable_connection_logging after reload').succeeds do
+ @instance.reload
+ returns(true) { @instance.connection_logging }
+ end
+
@instance.wait_for { ready? }
tests('#disable_connection_logging').succeeds do
@instance.disable_connection_logging
|
[rackspace|lb] fix for #<I> - Connection logging now loads appropriately
|
fog_fog
|
train
|
dfee87602632d7691823179cd919491f60365c63
|
diff --git a/Schema/PostgresSchemaState.php b/Schema/PostgresSchemaState.php
index <HASH>..<HASH> 100644
--- a/Schema/PostgresSchemaState.php
+++ b/Schema/PostgresSchemaState.php
@@ -51,7 +51,13 @@ class PostgresSchemaState extends SchemaState
*/
public function load($path)
{
- $process = $this->makeProcess('PGPASSWORD=$LARAVEL_LOAD_PASSWORD pg_restore --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --username=$LARAVEL_LOAD_USER --dbname=$LARAVEL_LOAD_DATABASE $LARAVEL_LOAD_PATH');
+ $command = 'PGPASSWORD=$LARAVEL_LOAD_PASSWORD pg_restore --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --username=$LARAVEL_LOAD_USER --dbname=$LARAVEL_LOAD_DATABASE $LARAVEL_LOAD_PATH';
+
+ if (preg_match('/\.sql$/', $path) !== false) {
+ $command = 'PGPASSWORD=$LARAVEL_LOAD_PASSWORD psql --file=$LARAVEL_LOAD_PATH --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --username=$LARAVEL_LOAD_USER --dbname=$LARAVEL_LOAD_DATABASE';
+ }
+
+ $process = $this->makeProcess($command);
$process->mustRun(null, array_merge($this->baseVariables($this->connection->getConfig()), [
'LARAVEL_LOAD_PATH' => $path,
|
support psql and pg_restore commands in schema load (#<I>)
* support psql and pg_restore command in schema load
* Update PostgresSchemaState.php
|
illuminate_database
|
train
|
3b02fee06938929f6c534dd826fe382b72a67080
|
diff --git a/lib/evalhook.rb b/lib/evalhook.rb
index <HASH>..<HASH> 100644
--- a/lib/evalhook.rb
+++ b/lib/evalhook.rb
@@ -180,10 +180,12 @@ module EvalHook
nil
end
+ # Overwrite to handle the evaluation o colon3 nodes (access to global namespace)
def handle_colon3(*args)
nil
end
+ # Overwrite to handle the evaluation o xstr nodes (execution of shell commands)
def handle_xstr(*args)
nil
end
@@ -193,6 +195,7 @@ module EvalHook
nil
end
+ # used internally
def hooked_super(*args)
hm = caller_obj(2).hooked_method(caller_method(2))
hm.set_class(caller_class(2).superclass)
@@ -207,12 +210,14 @@ module EvalHook
end
end
+ # used internally
def hooked_xstr(str)
runstr = handle_xstr(str) || str
end
define_eval_method :evalhook
+ # used internally
def internal_eval(b_, original_args)
raise ArgumentError if original_args.size == 0
evalhook_i(original_args[0], original_args[1] || b_, original_args[2] || "(eval)", original_args[3] || 0)
|
added doc for HookHandler methods
|
tario_evalhook
|
train
|
147f52fedc4283dec24f291c83a2b9a54541d958
|
diff --git a/moto/mediaconnect/models.py b/moto/mediaconnect/models.py
index <HASH>..<HASH> 100644
--- a/moto/mediaconnect/models.py
+++ b/moto/mediaconnect/models.py
@@ -97,7 +97,7 @@ class MediaConnectBackend(BaseBackend):
for index, _source in enumerate(flow.sources):
self._add_source_details(_source, flow_id, f"127.0.0.{index}")
- for index, output in enumerate(flow.outputs):
+ for index, output in enumerate(flow.outputs or []):
if output.get("protocol") in ["srt-listener", "zixi-pull"]:
output["listenerAddress"] = f"{index}.0.0.0"
diff --git a/tests/test_mediaconnect/test_mediaconnect.py b/tests/test_mediaconnect/test_mediaconnect.py
index <HASH>..<HASH> 100644
--- a/tests/test_mediaconnect/test_mediaconnect.py
+++ b/tests/test_mediaconnect/test_mediaconnect.py
@@ -108,6 +108,7 @@ def test_create_flow_alternative_succeeds():
"SourcePriority": {"PrimarySource": "Source-B"},
"State": "ENABLED",
},
+ outputs=None,
)
response = client.create_flow(**channel_config)
|
mediaconnect: fix, actually fixing create_flow to allow no outputs argument (#<I>)
|
spulec_moto
|
train
|
d68008479b53612c1254039edd47834cff557aa5
|
diff --git a/lib/browsers/chrome.js b/lib/browsers/chrome.js
index <HASH>..<HASH> 100644
--- a/lib/browsers/chrome.js
+++ b/lib/browsers/chrome.js
@@ -418,7 +418,6 @@ chrome.loadUrlThenWaitForPageLoadEvent = function(tab, url) {
Page.addScriptToEvaluateOnNewDocument({source: 'if (window.customElements) customElements.forcePolyfill = true'})
Page.addScriptToEvaluateOnNewDocument({source: 'ShadyDOM = {force: true}'})
Page.addScriptToEvaluateOnNewDocument({source: 'ShadyCSS = {shimcssproperties: true}'})
- Page.addScriptToEvaluateOnNewDocument({source: 'localStorage.clear()'})
Page.navigate({
url: tab.prerender.url
|
remove the clearing of local storage. we are seeing a possible bug with this across customers when the context should already clear local storage
|
prerender_prerender
|
train
|
7e8d9602c0c31399336aedac28c109b1fc1666b3
|
diff --git a/modules/bcrypt-cli/src/main/java/at/favre/lib/crypto/bcrypt/cli/CLIParser.java b/modules/bcrypt-cli/src/main/java/at/favre/lib/crypto/bcrypt/cli/CLIParser.java
index <HASH>..<HASH> 100644
--- a/modules/bcrypt-cli/src/main/java/at/favre/lib/crypto/bcrypt/cli/CLIParser.java
+++ b/modules/bcrypt-cli/src/main/java/at/favre/lib/crypto/bcrypt/cli/CLIParser.java
@@ -1,7 +1,13 @@
package at.favre.lib.crypto.bcrypt.cli;
import at.favre.lib.bytes.Bytes;
-import org.apache.commons.cli.*;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.DefaultParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.OptionGroup;
+import org.apache.commons.cli.Options;
/**
* Parses the command line input and converts it to a structured model ({@link Arg}
@@ -40,40 +46,9 @@ public final class CLIParser {
if (commandLine.hasOption(ARG_HASH)) {
- String[] hashParams = commandLine.getOptionValues(ARG_HASH);
-
- if (hashParams == null || hashParams.length == 0) {
- throw new IllegalArgumentException("Hash mode expects at least the cost parameter. (e.g. '-" + ARG_HASH + " 12')");
- }
-
- final int costFactor;
- try {
- costFactor = Integer.valueOf(hashParams[0]);
- } catch (Exception e) {
- throw new IllegalArgumentException("First parameter of hash expected to be integer type, was " + hashParams[0]);
- }
-
- byte[] salt = null;
- if (hashParams.length > 1) {
- try {
- salt = Bytes.parseHex(hashParams[1]).array();
- } catch (Exception e) {
- throw new IllegalArgumentException("Salt parameter could not be parsed as hex [0-9a-f], was " + hashParams[1]);
- }
-
- if (salt.length != 16) {
- throw new IllegalArgumentException("Salt parameter must be exactly 16 bytes (32 characters hex)");
- }
- }
- return new Arg(password, salt, costFactor);
+ return handleHash(commandLine, password);
} else if (commandLine.hasOption(ARG_CHECK)) {
- String refBcrypt = commandLine.getOptionValue(ARG_CHECK);
-
- if (refBcrypt == null || refBcrypt.trim().length() != 60) {
- throw new IllegalArgumentException("Reference bcrypt hash must be exactly 60 characters, e.g. '$2a$10$6XBbrUraPyfq7nxeaYsR4u.3.ZuGNCy3tOT4reneAI/qoWvP6AX/e' was " + refBcrypt);
- }
-
- return new Arg(password, refBcrypt);
+ return handleCheck(commandLine, password);
}
} catch (Exception e) {
String msg = e.getMessage();
@@ -87,6 +62,45 @@ public final class CLIParser {
return argument;
}
+ private static Arg handleHash(CommandLine commandLine, char[] password) {
+ String[] hashParams = commandLine.getOptionValues(ARG_HASH);
+
+ if (hashParams == null || hashParams.length == 0) {
+ throw new IllegalArgumentException("Hash mode expects at least the cost parameter. (e.g. '-" + ARG_HASH + " 12')");
+ }
+
+ final int costFactor;
+ try {
+ costFactor = Integer.valueOf(hashParams[0]);
+ } catch (Exception e) {
+ throw new IllegalArgumentException("First parameter of hash expected to be integer type, was " + hashParams[0]);
+ }
+
+ byte[] salt = null;
+ if (hashParams.length > 1) {
+ try {
+ salt = Bytes.parseHex(hashParams[1]).array();
+ } catch (Exception e) {
+ throw new IllegalArgumentException("Salt parameter could not be parsed as hex [0-9a-f], was " + hashParams[1]);
+ }
+
+ if (salt.length != 16) {
+ throw new IllegalArgumentException("Salt parameter must be exactly 16 bytes (32 characters hex)");
+ }
+ }
+ return new Arg(password, salt, costFactor);
+ }
+
+ private static Arg handleCheck(CommandLine commandLine, char[] password) {
+ String refBcrypt = commandLine.getOptionValue(ARG_CHECK);
+
+ if (refBcrypt == null || refBcrypt.trim().length() != 60) {
+ throw new IllegalArgumentException("Reference bcrypt hash must be exactly 60 characters, e.g. '$2a$10$6XBbrUraPyfq7nxeaYsR4u.3.ZuGNCy3tOT4reneAI/qoWvP6AX/e' was " + refBcrypt);
+ }
+
+ return new Arg(password, refBcrypt);
+ }
+
static Options setupOptions() {
Options options = new Options();
Option optHash = Option.builder(ARG_HASH).longOpt("bhash").argName("cost> <[16-hex-byte-salt]").hasArgs().desc("Use this flag if you want to compute the bcrypt hash. Pass the logarithm cost factor (4-31) and optionally the used salt" +
|
Refactor CLIParser to have shorter methods
|
patrickfav_bcrypt
|
train
|
15b0d3223eba9b224c5201174ba928667a583575
|
diff --git a/db/mysql/migrations/20130916125820_CreatePointsTable.sql b/db/mysql/migrations/20130916125820_CreatePointsTable.sql
index <HASH>..<HASH> 100644
--- a/db/mysql/migrations/20130916125820_CreatePointsTable.sql
+++ b/db/mysql/migrations/20130916125820_CreatePointsTable.sql
@@ -1,5 +1,5 @@
-- +goose Up
-CREATE TABLE points (lat float, lng, float);
+CREATE TABLE points (lat float, lng float);
-- +goose Down
DROP TABLE points;
diff --git a/geo.go b/geo.go
index <HASH>..<HASH> 100644
--- a/geo.go
+++ b/geo.go
@@ -2,6 +2,7 @@ package geo
import (
"database/sql"
+ _ "github.com/erikstmartin/go-testdb"
_ "github.com/lib/pq"
_ "github.com/ziutek/mymysql/godrv"
)
@@ -23,4 +24,4 @@ func HandleWithSQL() (*SQLMapper, error) {
}
return nil, sqlConfErr
-}
\ No newline at end of file
+}
diff --git a/geo_test.go b/geo_test.go
index <HASH>..<HASH> 100644
--- a/geo_test.go
+++ b/geo_test.go
@@ -3,6 +3,8 @@ package geo
import (
_ "database/sql"
"fmt"
+ "github.com/erikstmartin/go-testdb"
+ "os"
"strconv"
"testing"
)
@@ -13,7 +15,14 @@ import (
// @spec: golang-geo should
// - Should correctly return a set of [lat, lng] within a certain radius
func TestPointsWithinRadiusIntegration(t *testing.T) {
+ // TODO Determine if we actually need to test SQL logic across databases.
+ dbEnv := os.Getenv("DB")
+ if dbEnv == "test" {
+ stubPointsWithinRadiusQueries()
+ }
+
s, sqlErr := HandleWithSQL()
+
if sqlErr != nil {
t.Error("ERROR: %s", sqlErr)
}
@@ -38,12 +47,16 @@ func TestPointsWithinRadiusIntegration(t *testing.T) {
panic(err)
}
+ // TODO Write a test to check for expected results of PointAtDistanceAndBearing
+
// Should get both the first point and second point
_, err2 := s.PointsWithinRadius(origin, 9)
if err2 != nil {
panic(err2)
}
+ // TODO Write a test to check for expected results of PointAtDistanceAndBearing
+
// Clear Test DB
FlushTestDB(s)
}
@@ -62,3 +75,11 @@ func RoundFloat(x float64, prec int) float64 {
f, _ := strconv.ParseFloat(frep, 64)
return f
}
+
+func stubPointsWithinRadiusQueries() {
+ insideRangeQuery := "SELECT * FROM points a WHERE acos(sin(radians(37.619002)) * sin(radians(a.lat)) + cos(radians(37.619002)) * cos(radians(a.lat)) * cos(radians(a.lng) - radians(-122.374840))) * 6356.752300 <= 8.000000"
+ testdb.StubQuery(insideRangeQuery, nil)
+
+ outsideRangeQuery := "SELECT * FROM points a WHERE acos(sin(radians(37.619002)) * sin(radians(a.lat)) + cos(radians(37.619002)) * cos(radians(a.lat)) * cos(radians(a.lng) - radians(-122.374840))) * 6356.752300 <= 9.000000"
+ testdb.StubQuery(outsideRangeQuery, nil)
+}
diff --git a/sql_conf.go b/sql_conf.go
index <HASH>..<HASH> 100644
--- a/sql_conf.go
+++ b/sql_conf.go
@@ -19,16 +19,19 @@ type SQLConf struct {
const (
DEFAULT_PGSQL_OPEN_STR = "user=postgres dbname=points sslmode=disable"
DEFAULT_MYSQL_OPEN_STR = "points/root/"
+ DEFAULT_TEST_OPEN_STR = ""
)
// Returns a SQLConf based on the $DB environment variable
// Returns a PostgreSQL configuration as a default
-func sqlConfFromEnv() (*SQLConf) {
+func sqlConfFromEnv() *SQLConf {
var dbEnv = os.Getenv("DB")
switch dbEnv {
case "mysql":
return &SQLConf{driver: "mymysql", openStr: DEFAULT_MYSQL_OPEN_STR, table: "points", latCol: "lat", lngCol: "lng"}
+ case "test":
+ return &SQLConf{driver: "testdb", openStr: DEFAULT_TEST_OPEN_STR, table: "points", latCol: "lat", lngCol: "lng"}
default:
return &SQLConf{driver: "postgres", openStr: DEFAULT_PGSQL_OPEN_STR, table: "points", latCol: "lat", lngCol: "lng"}
}
|
[src][migrations][test] Adding in the ability to stub out database queries during tests with a database mocking library. Also fixed some issues with mysql migrations.
|
kellydunn_golang-geo
|
train
|
1f29f333efe18ab8e2176596359bcd1842bf0158
|
diff --git a/lib/after_do/version.rb b/lib/after_do/version.rb
index <HASH>..<HASH> 100644
--- a/lib/after_do/version.rb
+++ b/lib/after_do/version.rb
@@ -1,3 +1,3 @@
module AfterDo
- VERSION = "0.2.0"
+ VERSION = "0.2.1"
end
|
Version bump to <I> with private methods regression fix
|
PragTob_after_do
|
train
|
dfb9ec54c683665a4b8e84bb61abdbd4c7174c30
|
diff --git a/RELEASE.md b/RELEASE.md
index <HASH>..<HASH> 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -4,6 +4,9 @@
m: minor
p: patch
+## next
+* p: suprocess.Popen is now run with shell=True
+
## 1.2.0
* m: idd 9.4.0 and 9.5.0 added
diff --git a/opyplus/simulation/simulation.py b/opyplus/simulation/simulation.py
index <HASH>..<HASH> 100644
--- a/opyplus/simulation/simulation.py
+++ b/opyplus/simulation/simulation.py
@@ -283,11 +283,13 @@ class Simulation:
# launch calculation
run_subprocess(
- cmd_l,
+ " ".join(cmd_l),
+ shell=True,
cwd=self._dir_abs_path,
stdout=std_out_err,
stderr=std_out_err,
- beat_freq=beat_freq
+ beat_freq=beat_freq,
+ message="simulation is still running\n"
)
# if needed, we delete temp weather data (only on Windows, see above)
diff --git a/opyplus/util.py b/opyplus/util.py
index <HASH>..<HASH> 100644
--- a/opyplus/util.py
+++ b/opyplus/util.py
@@ -162,7 +162,14 @@ class PrintFunctionStreamWriter:
self._print_function(message)
-def run_subprocess(command, cwd=None, stdout=None, stderr=None, shell=False, beat_freq=None):
+def run_subprocess(
+ command,
+ cwd=None,
+ stdout=None,
+ stderr=None,
+ shell=False,
+ beat_freq=None,
+ message="subprocess is still running\n"):
"""
Run a subprocess and manage its stdout/stderr streams.
@@ -196,7 +203,7 @@ def run_subprocess(command, cwd=None, stdout=None, stderr=None, shell=False, bea
sub_p.wait(timeout=beat_freq)
break
except subprocess.TimeoutExpired:
- stdout.write("subprocess is still running\n")
+ stdout.write(message)
if hasattr(sys.stdout, "flush"):
sys.stdout.flush()
return sub_p.returncode
|
* p: suprocess.Popen is now run with shell=True
|
openergy_oplus
|
train
|
6d1cb88b73e2d2841ced658c79dd0e892b936505
|
diff --git a/pkg/oc/cli/admin/migrate/storage/storage.go b/pkg/oc/cli/admin/migrate/storage/storage.go
index <HASH>..<HASH> 100644
--- a/pkg/oc/cli/admin/migrate/storage/storage.go
+++ b/pkg/oc/cli/admin/migrate/storage/storage.go
@@ -9,6 +9,7 @@ import (
"github.com/spf13/cobra"
"golang.org/x/time/rate"
+ "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/sets"
@@ -302,6 +303,13 @@ func (o *MigrateAPIStorageOptions) save(info *resource.Info, reporter migrate.Re
Resource(info.Mapping.Resource).
Namespace(info.Namespace).
Update(oldObject)
+ // storage migration is special in that all it needs to do is a no-op update to cause
+ // the api server to migrate the object to the preferred version. thus if we encounter
+ // a conflict, we know that something updated the object and we no longer need to do
+ // anything - if the object needed migration, the api server has already migrated it.
+ if errors.IsConflict(err) {
+ return migrate.ErrUnchanged
+ }
if err != nil {
return migrate.DefaultRetriable(info, err)
}
|
Do not retry conflicts during storage migration
Storage migration is special in that all it needs to do is a no-op
update to cause the API server to migrate the object to the
preferred version. Thus if we encounter a conflict, we know that
something updated the object and we no longer need to do anything.
If the object needed migration, the API server has already migrated
it.
|
openshift_origin
|
train
|
301d558446e12eb1a14f345e8c000093a02b3d9c
|
diff --git a/src/Lib/ProfferPath.php b/src/Lib/ProfferPath.php
index <HASH>..<HASH> 100644
--- a/src/Lib/ProfferPath.php
+++ b/src/Lib/ProfferPath.php
@@ -10,7 +10,7 @@ namespace Proffer\Lib;
use Cake\ORM\Entity;
use Cake\ORM\Table;
-use Cake\Utility\String;
+use Cake\Utility\Text;
class ProfferPath implements ProfferPathInterface
{
@@ -199,7 +199,7 @@ class ProfferPath implements ProfferPathInterface
return $seed;
}
- return String::uuid();
+ return Text::uuid();
}
/**
diff --git a/src/Model/Behavior/ProfferBehavior.php b/src/Model/Behavior/ProfferBehavior.php
index <HASH>..<HASH> 100644
--- a/src/Model/Behavior/ProfferBehavior.php
+++ b/src/Model/Behavior/ProfferBehavior.php
@@ -71,7 +71,7 @@ class ProfferBehavior extends Behavior
$path->createPathFolder();
if ($this->moveUploadedFile($entity->get($field)['tmp_name'], $path->fullPath())) {
- $entity->set($field, $entity->get($field)['name']);
+ $entity->set($field, $path->getFilename());
$entity->set($settings['dir'], $path->getSeed());
// Only generate thumbnails for image uploads
@@ -119,7 +119,7 @@ class ProfferBehavior extends Behavior
$path->deleteFiles($path->getFolder(), true);
}
- unset($path);
+ $path = null;
}
return true;
|
Resolve #<I>. Resolve #<I>. Resolve #<I>. Implements webme's fixes
|
davidyell_CakePHP3-Proffer
|
train
|
a4a7d7fb1ce78420d3d028e5a0535431baaeaea1
|
diff --git a/src/Mouf/Mvc/Splash/SplashGenerateService.php b/src/Mouf/Mvc/Splash/SplashGenerateService.php
index <HASH>..<HASH> 100644
--- a/src/Mouf/Mvc/Splash/SplashGenerateService.php
+++ b/src/Mouf/Mvc/Splash/SplashGenerateService.php
@@ -27,7 +27,7 @@ class SplashGenerateService {
$strExtentions = implode('|', $exludeExtentions);
$strFolders = '^' . implode('|^', $exludeFolders);
- $str = "Options FollowSymLinks
+ $str = "Options +FollowSymLinks
RewriteEngine on
RewriteBase $rootUri
|
Fix Apache <I> bug : options should have either "+" or "-"
|
thecodingmachine_mvc.splash
|
train
|
495d93d885604ba7c7ba6a72102b5994aa2e7c7f
|
diff --git a/resource_aws_elastic_beanstalk_environment.go b/resource_aws_elastic_beanstalk_environment.go
index <HASH>..<HASH> 100644
--- a/resource_aws_elastic_beanstalk_environment.go
+++ b/resource_aws_elastic_beanstalk_environment.go
@@ -462,7 +462,7 @@ func fetchAwsElasticBeanstalkEnvironmentSettings(d *schema.ResourceData, meta in
return nil, fmt.Errorf("Error reading environment settings: option setting with no name: %v", optionSetting)
}
- if optionSetting.ResourceName != nil {
+ if *optionSetting.Namespace == "aws:autoscaling:scheduledaction" && optionSetting.ResourceName != nil {
m["resource"] = *optionSetting.ResourceName
}
@@ -647,8 +647,10 @@ func extractOptionSettings(s *schema.Set) []*elasticbeanstalk.ConfigurationOptio
OptionName: aws.String(setting.(map[string]interface{})["name"].(string)),
Value: aws.String(setting.(map[string]interface{})["value"].(string)),
}
- if v, ok := setting.(map[string]interface{})["resource"].(string); ok && v != "" {
- optionSetting.ResourceName = aws.String(v)
+ if *optionSetting.Namespace == "aws:autoscaling:scheduledaction" {
+ if v, ok := setting.(map[string]interface{})["resource"].(string); ok && v != "" {
+ optionSetting.ResourceName = aws.String(v)
+ }
}
settings = append(settings, &optionSetting)
}
|
provider/aws: fix Elastic Beanstalk settings diff (#<I>)
Fixes an issue where terraform plan or apply will always have a diff.
The Elastic Beanstalk API returns data for the `resource` attribute for
some settings that are not documented. This limits the `resource`
attribute to settings in the `aws:autoscaling:scheduledaction`
namespace.
|
terraform-providers_terraform-provider-aws
|
train
|
84c5e26b447251088826737612ccf0817ef43db2
|
diff --git a/tpot/base.py b/tpot/base.py
index <HASH>..<HASH> 100644
--- a/tpot/base.py
+++ b/tpot/base.py
@@ -32,7 +32,7 @@ from deap import algorithms, base, creator, tools, gp
from tqdm import tqdm
from sklearn.base import BaseEstimator
-from sklearn.cross_validation import cross_val_score
+from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline, make_union
from sklearn.preprocessing import FunctionTransformer
from sklearn.ensemble import VotingClassifier
@@ -42,14 +42,14 @@ from update_checker import update_check
from ._version import __version__
from .export_utils import export_pipeline, expr_to_tree, generate_pipeline_code
-from .decorators import _gp_new_generation, _timeout
+from .decorators import _gp_new_generation#, _timeout
from . import operators
from .operators import CombineDFs
from .gp_types import Bool, Output_DF
from .metrics import SCORERS
# add time limit for imported function
-cross_val_score = _timeout(cross_val_score)
+#cross_val_score = _timeout(cross_val_score)
class TPOTBase(BaseEstimator):
"""TPOT automatically creates and optimizes machine learning pipelines using genetic programming"""
@@ -89,7 +89,7 @@ class TPOTBase(BaseEstimator):
TPOT assumes that this scoring function should be maximized, i.e.,
higher is better.
- Offers the same options as sklearn.cross_validation.cross_val_score:
+ Offers the same options as sklearn.model_selection.cross_val_score:
['accuracy', 'adjusted_rand_score', 'average_precision', 'f1',
'f1_macro', 'f1_micro', 'f1_samples', 'f1_weighted',
@@ -561,7 +561,7 @@ class TPOTBase(BaseEstimator):
with warnings.catch_warnings():
warnings.simplefilter('ignore')
- cv_scores = cross_val_score(self, sklearn_pipeline, features, classes,
+ cv_scores = cross_val_score(sklearn_pipeline, features, classes,
cv=self.num_cv_folds, scoring=self.scoring_function)
resulting_score = np.mean(cv_scores)
diff --git a/tpot/driver.py b/tpot/driver.py
index <HASH>..<HASH> 100644
--- a/tpot/driver.py
+++ b/tpot/driver.py
@@ -20,7 +20,7 @@ with the TPOT library. If not, see http://www.gnu.org/licenses/.
import numpy as np
import argparse
-from sklearn.cross_validation import train_test_split
+from sklearn.model_selection import train_test_split
from .tpot import TPOTClassifier, TPOTRegressor
from ._version import __version__
@@ -139,7 +139,7 @@ def main():
'and allow TPOT to run until it runs out of time.')
parser.add_argument('-maxeval', action='store', dest='MAX_EVAL_MINS', default=5,
- type=int, help='How many minutes TPOT has to evaluate a single pipeline. '
+ type=float, help='How many minutes TPOT has to evaluate a single pipeline. '
'Setting this parameter to higher values will allow TPOT to explore more complex '
'pipelines but will also allow TPOT to run longer.')
diff --git a/tpot/export_utils.py b/tpot/export_utils.py
index <HASH>..<HASH> 100644
--- a/tpot/export_utils.py
+++ b/tpot/export_utils.py
@@ -110,7 +110,7 @@ def generate_import_code(pipeline):
# Always start with these imports
pipeline_imports = {
- 'sklearn.cross_validation': ['train_test_split'],
+ 'sklearn.model_selection': ['train_test_split'],
'sklearn.pipeline': ['make_pipeline', 'make_union'],
'sklearn.preprocessing': ['FunctionTransformer'],
'sklearn.ensemble': ['VotingClassifier']
diff --git a/tpot/operators/preprocessors/pca.py b/tpot/operators/preprocessors/pca.py
index <HASH>..<HASH> 100644
--- a/tpot/operators/preprocessors/pca.py
+++ b/tpot/operators/preprocessors/pca.py
@@ -19,11 +19,11 @@ with the TPOT library. If not, see http://www.gnu.org/licenses/.
"""
from .base import Preprocessor
-from sklearn.decomposition import RandomizedPCA
+from sklearn.decomposition import PCA
class TPOTRandomizedPCA(Preprocessor):
- """Uses scikit-learn's RandomizedPCA to transform the feature set
+ """Uses scikit-learn's randomized PCA to transform the feature set
Parameters
----------
@@ -31,8 +31,8 @@ class TPOTRandomizedPCA(Preprocessor):
Number of iterations for the power method. [1, 10]
"""
- import_hash = {'sklearn.decomposition': ['RandomizedPCA']}
- sklearn_class = RandomizedPCA
+ import_hash = {'sklearn.decomposition': ['PCA']}
+ sklearn_class = PCA
arg_types = (int, )
def __init__(self):
@@ -42,5 +42,6 @@ class TPOTRandomizedPCA(Preprocessor):
iterated_power = min(10, max(1, iterated_power))
return {
+ 'svd_solver': 'randomized',
'iterated_power': iterated_power
}
|
Update for scikit-learn <I>
Changed all references from `cross_validation` to `model_selection`.
Changed `RandomizedPCA` to `PCA` with `svd_solver=‘randomized’`
|
EpistasisLab_tpot
|
train
|
6281c2ab4ede3d67ff3fdf648e013e1cd132038e
|
diff --git a/lib/sprinkle/installers/installer.rb b/lib/sprinkle/installers/installer.rb
index <HASH>..<HASH> 100644
--- a/lib/sprinkle/installers/installer.rb
+++ b/lib/sprinkle/installers/installer.rb
@@ -1,4 +1,8 @@
module Sprinkle
+ # Installers are where the bulk of the work in Sprinkle happens. Installers are
+ # the building blocks of packages. Typically each unique type of install
+ # command has it's own installer class.
+ #
module Installers
# The base class which all installers must subclass, this class makes
# sure all installers share some general features, which are outlined
@@ -8,9 +12,16 @@ module Sprinkle
#
# With all installation methods you have the ability to specify multiple
# pre/post installation hooks. This gives you the ability to specify
- # commands to run before and after an installation takes place. All
- # commands by default are sudo'd so there is no need to include "sudo"
- # in the command itself. There are three ways to specify a pre/post hook.
+ # commands to run before and after an installation takes place.
+ # There are three ways to specify a pre/post hook.
+
+ # Note about sudo:
+ # When using the Capistrano actor all commands by default are run using
+ # sudo (unless your Capfile includes "set :use_sudo, false"). If you wish
+ # to use sudo periodically with "set :user_sudo, false" or with an actor
+ # other than Capistrano then you can just append it to your command. Some
+ # installers (transfer) also support a :sudo option, so check each
+ # installer for details.
#
# First, a single command:
#
|
update instructions to be clear about sudo and capistrano and other actors
|
sprinkle-tool_sprinkle
|
train
|
2085228b506505035b5431731bc13eaff8d0cd57
|
diff --git a/pkg/action/hooks.go b/pkg/action/hooks.go
index <HASH>..<HASH> 100644
--- a/pkg/action/hooks.go
+++ b/pkg/action/hooks.go
@@ -48,16 +48,27 @@ func (cfg *Configuration) execHook(rl *release.Release, hook release.HookEvent,
if err != nil {
return errors.Wrapf(err, "unable to build kubernetes object for %s hook %s", hook, h.Path)
}
- if _, err := cfg.KubeClient.Create(resources); err != nil {
- return errors.Wrapf(err, "warning: Hook %s %s failed", hook, h.Path)
- }
- // Get the time at which the hook was applied to the cluster
+ // Record the time at which the hook was applied to the cluster
h.LastRun = release.HookExecution{
StartedAt: time.Now(),
- Phase: release.HookPhaseUnknown,
+ Phase: release.HookPhaseRunning,
+ }
+ cfg.recordRelease(rl)
+
+ // As long as the implementation of WatchUntilReady does not panic, HookPhaseFailed or HookPhaseSucceeded
+ // should always be set by this function. If we fail to do that for any reason, then HookPhaseUnknown is
+ // the most appropriate value to surface.
+ h.LastRun.Phase = release.HookPhaseUnknown
+
+ // Create hook resources
+ if _, err := cfg.KubeClient.Create(resources); err != nil {
+ h.LastRun.CompletedAt = time.Now()
+ h.LastRun.Phase = release.HookPhaseFailed
+ return errors.Wrapf(err, "warning: Hook %s %s failed", hook, h.Path)
}
- // Execute the hook
+
+ // Watch hook resources until they have completed
err = cfg.KubeClient.WatchUntilReady(resources, timeout)
// Note the time of success/failure
h.LastRun.CompletedAt = time.Now()
diff --git a/pkg/release/hook.go b/pkg/release/hook.go
index <HASH>..<HASH> 100644
--- a/pkg/release/hook.go
+++ b/pkg/release/hook.go
@@ -94,6 +94,8 @@ type HookPhase string
const (
// HookPhaseUnknown indicates that a hook is in an unknown state
HookPhaseUnknown HookPhase = "Unknown"
+ // HookPhaseRunning indicates that a hook is currently executing
+ HookPhaseRunning HookPhase = "Running"
// HookPhaseSucceeded indicates that hook execution succeeded
HookPhaseSucceeded HookPhase = "Succeeded"
// HookPhaseFailed indicates that hook execution failed
|
feat(hooks): add Running phase
|
helm_helm
|
train
|
e4c7b93cdbcde2aaa172fba8ffec361f736a4802
|
diff --git a/common-core-open/src/main/java/com/bbn/bue/common/evaluation/SummaryConfusionMatrices.java b/common-core-open/src/main/java/com/bbn/bue/common/evaluation/SummaryConfusionMatrices.java
index <HASH>..<HASH> 100644
--- a/common-core-open/src/main/java/com/bbn/bue/common/evaluation/SummaryConfusionMatrices.java
+++ b/common-core-open/src/main/java/com/bbn/bue/common/evaluation/SummaryConfusionMatrices.java
@@ -115,6 +115,16 @@ public final class SummaryConfusionMatrices {
(float) falseNegatives);
}
+ /**
+ * Helper function to avoid division by zero.
+ */
+ private static double safeXoverY(final double x, final double y) {
+ if (y != 0.0) {
+ return x / y;
+ } else {
+ return 0.0;
+ }
+ }
/**
* Returns accuracy, which is defined as the sum of the cells of the form (X,X) over the sum of
@@ -127,12 +137,30 @@ public final class SummaryConfusionMatrices {
for (final Symbol key : Sets.intersection(m.leftLabels(), m.rightLabels())) {
matching += m.cell(key, key);
}
- if (total != 0.0) {
- return matching / total;
- } else {
- return 0.0;
+ return safeXoverY(matching, total);
+ }
+
+ /**
+ * Returns the maximum accuracy that would be achieved if a single classification were
+ * selected for all instances.
+ */
+ public static final double chooseMostCommonRightHandClassAccuracy(SummaryConfusionMatrix m) {
+ final double total = m.sumOfallCells();
+ double max = 0.0;
+ for (final Symbol right : m.rightLabels()) {
+ max = Math.max(max, m.columnSum(right));
}
+ return safeXoverY(max, total);
}
+ public static final double chooseMostCommonLeftHandClassAccuracy(SummaryConfusionMatrix m) {
+ final double total = m.sumOfallCells();
+ double max = 0.0;
+ for (final Symbol left : m.leftLabels()) {
+ max = Math.max(max, m.rowSum(left));
+ }
+ return safeXoverY(max, total);
+ }
+
public static Builder builder() {
return new Builder();
|
Changes to add baseline accuracy functions.
Needed to change example in the test case so that the maximum choice differed
between the right and left hand.
|
BBN-E_bue-common-open
|
train
|
aa9059b965a98ddb29524bf3093fb044a0edc4db
|
diff --git a/mod/forum/externallib.php b/mod/forum/externallib.php
index <HASH>..<HASH> 100644
--- a/mod/forum/externallib.php
+++ b/mod/forum/externallib.php
@@ -906,7 +906,7 @@ class mod_forum_external extends external_api {
'forumid' => new external_value(PARAM_INT, 'Forum instance ID'),
'subject' => new external_value(PARAM_TEXT, 'New Discussion subject'),
'message' => new external_value(PARAM_RAW, 'New Discussion message (only html format allowed)'),
- 'groupid' => new external_value(PARAM_INT, 'The group, default to -1', VALUE_DEFAULT, -1),
+ 'groupid' => new external_value(PARAM_INT, 'The group, default to 0', VALUE_DEFAULT, 0),
'options' => new external_multiple_structure (
new external_single_structure(
array(
@@ -938,7 +938,7 @@ class mod_forum_external extends external_api {
* @since Moodle 3.0
* @throws moodle_exception
*/
- public static function add_discussion($forumid, $subject, $message, $groupid = -1, $options = array()) {
+ public static function add_discussion($forumid, $subject, $message, $groupid = 0, $options = array()) {
global $DB, $CFG;
require_once($CFG->dirroot . "/mod/forum/lib.php");
@@ -994,7 +994,7 @@ class mod_forum_external extends external_api {
} else {
// Check if we receive the default or and empty value for groupid,
// in this case, get the group for the user in the activity.
- if ($groupid === -1 or empty($params['groupid'])) {
+ if (empty($params['groupid'])) {
$groupid = groups_get_activity_group($cm);
} else {
// Here we rely in the group passed, forum_user_can_post_discussion will validate the group.
|
MDL-<I> forum: Allow creating new discussions with groupid -1
|
moodle_moodle
|
train
|
f015673f30fe4573627203ee6533c2e671e7e86e
|
diff --git a/src/Symfony/Component/HttpKernel/Kernel.php b/src/Symfony/Component/HttpKernel/Kernel.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/HttpKernel/Kernel.php
+++ b/src/Symfony/Component/HttpKernel/Kernel.php
@@ -76,12 +76,12 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl
private static $freshCache = [];
- public const VERSION = '4.4.22-DEV';
+ public const VERSION = '4.4.22';
public const VERSION_ID = 40422;
public const MAJOR_VERSION = 4;
public const MINOR_VERSION = 4;
public const RELEASE_VERSION = 22;
- public const EXTRA_VERSION = 'DEV';
+ public const EXTRA_VERSION = '';
public const END_OF_MAINTENANCE = '11/2022';
public const END_OF_LIFE = '11/2023';
|
Update VERSION for <I>
|
symfony_symfony
|
train
|
2ba703e1b81f80c8f604cf15127b94581290be78
|
diff --git a/server.go b/server.go
index <HASH>..<HASH> 100644
--- a/server.go
+++ b/server.go
@@ -150,7 +150,7 @@ func (s *Server) Run(addr string) {
log.Fatal("ListenAndServe:", err)
}
- s.Logger.Printf("web.go serving %s\n", l.Addr().String())
+ s.Logger.Printf("web.go serving %s\n", l.Addr())
s.l = l
err = http.Serve(s.l, mux)
@@ -177,13 +177,12 @@ func (s *Server) RunTLS(addr string, config *tls.Config) error {
mux := http.NewServeMux()
mux.Handle("/", s)
- s.Logger.Printf("web.go serving %s\n", addr)
-
l, err := tls.Listen("tcp", addr, config)
if err != nil {
log.Fatal("Listen:", err)
return err
}
+ s.Logger.Printf("web.go serving %s\n", l.Addr())
s.l = l
return http.Serve(s.l, mux)
|
Clean up initial log statements
1. In RunTLS, only print the initial log statement if `Listen` is
successful. Also, print the actual address instead of the one passed
in.
2. Change `l.Addr().String()` to `l.Addr()`. The Addr interface has a
`String` method, which will be called by fmt.
|
hoisie_web
|
train
|
ea1306c0f879e3be65b3ae2df1ec0cda98697ee7
|
diff --git a/lib/typhoeus/request.rb b/lib/typhoeus/request.rb
index <HASH>..<HASH> 100644
--- a/lib/typhoeus/request.rb
+++ b/lib/typhoeus/request.rb
@@ -1,9 +1,13 @@
module Typhoeus
class Request
- attr_accessor :method, :params, :body, :headers, :connect_timeout, :timeout, :user_agent, :response, :cache_timeout, :follow_location, :max_redirects, :proxy, :disable_ssl_peer_verification, :ssl_cert, :ssl_cert_type, :ssl_key, :ssl_key_type, :ssl_key_password, :ssl_cacert, :ssl_capath, :verbose, :username, :password,
-:auth_method
-
attr_reader :url
+ attr_writer :headers
+ attr_accessor :method, :params, :body, :connect_timeout, :timeout,
+ :user_agent, :response, :cache_timeout, :follow_location,
+ :max_redirects, :proxy, :disable_ssl_peer_verification,
+ :ssl_cert, :ssl_cert_type, :ssl_key, :ssl_key_type,
+ :ssl_key_password, :ssl_cacert, :ssl_capath, :verbose,
+ :username, :password, :auth_method
# Initialize a new Request
#
|
Fix #headers warning with Request.
|
typhoeus_typhoeus
|
train
|
4d77c8713f358efe2d200c285ce4bb46a3aec68d
|
diff --git a/lib/opFns.js b/lib/opFns.js
index <HASH>..<HASH> 100644
--- a/lib/opFns.js
+++ b/lib/opFns.js
@@ -1023,8 +1023,7 @@ function makeCall (runState, callOptions, localOpts, cb) {
// check if account has enough ether
// Note: in the case of delegatecall, the value is persisted and doesn't need to be deducted again
if (runState.depth >= fees.stackLimit.v || (callOptions.delegatecall !== true && new BN(runState.contract.balance).lt(callOptions.value))) {
- runState.stack.push(Buffer.from([0]))
- cb(null)
+ cb(null, Buffer.from([0]))
} else {
// if creating a new contract then increament the nonce
if (!callOptions.to) {
|
Do not manipulate stack directly in CALLs
|
ethereumjs_ethereumjs-vm
|
train
|
066803df92e8b40e4f36e16853c622e39ae406e5
|
diff --git a/bat/lib/bat/deployment_helper.rb b/bat/lib/bat/deployment_helper.rb
index <HASH>..<HASH> 100644
--- a/bat/lib/bat/deployment_helper.rb
+++ b/bat/lib/bat/deployment_helper.rb
@@ -152,7 +152,11 @@ module Bat
end
def dynamic_network?
- @spec['properties']['network']['type'] == 'dynamic'
+ network_type == 'dynamic'
+ end
+
+ def network_type
+ @spec['properties']['network']['type']
end
def get_task_id(output, state = 'done')
diff --git a/bat/lib/bat/stemcell.rb b/bat/lib/bat/stemcell.rb
index <HASH>..<HASH> 100644
--- a/bat/lib/bat/stemcell.rb
+++ b/bat/lib/bat/stemcell.rb
@@ -38,6 +38,11 @@ module Bat
!((name =~ /vsphere/ || name =~ /vcloud/) && (name =~ /centos/ || name !~ /go_agent/))
end
+ def supports_changing_static_ip?(network_type)
+ # Does not support for openstack dynamic
+ supports_network_reconfiguration? && !(name =~ /openstack/ && network_type == 'dynamic')
+ end
+
def ==(other)
to_s == other.to_s
end
diff --git a/bat/spec/system/network_configuration_spec.rb b/bat/spec/system/network_configuration_spec.rb
index <HASH>..<HASH> 100644
--- a/bat/spec/system/network_configuration_spec.rb
+++ b/bat/spec/system/network_configuration_spec.rb
@@ -69,7 +69,7 @@ describe 'network configuration' do
context 'when using manual networking' do
before do
- unless @requirements.stemcell.supports_network_reconfiguration?
+ unless @requirements.stemcell.supports_changing_static_ip?(network_type)
pending "network reconfiguration does not work for #{@requirements.stemcell}"
end
end
diff --git a/bat/templates/openstack.yml.erb b/bat/templates/openstack.yml.erb
index <HASH>..<HASH> 100644
--- a/bat/templates/openstack.yml.erb
+++ b/bat/templates/openstack.yml.erb
@@ -81,10 +81,16 @@ jobs:
networks:
- name: default
default: [dns, gateway]
- <% if properties.use_static_ip %>
- - name: static
+ <% if p('network.type') == 'manual' %>
static_ips:
+ <% if properties.use_static_ip %>
- <%= properties.deployment_static_ip %>
+ <% end %>
+ <% end %>
+ - name: static
+ static_ips:
+ <% if properties.use_vip %>
+ - <%= properties.vip %>
<% end %>
properties:
|
Set static ip only for openstack manual network
Floating IP on openstack bat environment is basically a static ip.
You need to have a static IP range to assign floating ip.
|
cloudfoundry_bosh
|
train
|
c70451abd50aee741e668590f5c6fed641f8f534
|
diff --git a/src/Exception/OAuthServerException.php b/src/Exception/OAuthServerException.php
index <HASH>..<HASH> 100644
--- a/src/Exception/OAuthServerException.php
+++ b/src/Exception/OAuthServerException.php
@@ -196,6 +196,21 @@ class OAuthServerException extends \Exception
}
/**
+ * Missing scope error
+ *
+ * @param null|string $redirectUri A HTTP URI to redirect the user back to
+ *
+ * @return static
+ */
+ public static function missingScope($redirectUri = null)
+ {
+ $errorMessage = 'No scope was specified for this request';
+ $hint = 'Set a default scope on the server if no scopes are passed in the request';
+
+ return new static($errorMessage, 11, 'missing_scope', 400, $hint, $redirectUri);
+ }
+
+ /**
* @return string
*/
public function getErrorType()
|
Add an exception for a missing scope
|
thephpleague_oauth2-server
|
train
|
567de4282bc5a6079918825a113478c2b937be2b
|
diff --git a/client/state/plugins/premium/actions.js b/client/state/plugins/premium/actions.js
index <HASH>..<HASH> 100644
--- a/client/state/plugins/premium/actions.js
+++ b/client/state/plugins/premium/actions.js
@@ -41,12 +41,12 @@ const normalizePluginInstructions = ( data ) => {
* Return a SitePlugin instance used to handle the plugin
*
* @param {Object} site - site object
- * @param {String} pluginId - plugin identifier
+ * @param {String} plugin - plugin identifier
* @return {SitePlugin} SitePlugin instance
*/
-const getPluginHandler = ( site, pluginId ) => {
+const getPluginHandler = ( site, plugin ) => {
const siteHandler = wpcom.site( site.ID );
- const pluginHandler = siteHandler.plugin( pluginId );
+ const pluginHandler = siteHandler.plugin( plugin );
return pluginHandler;
};
@@ -72,7 +72,7 @@ function install( site, plugin, dispatch ) {
return;
}
- getPluginHandler( site, plugin.id ).install().then( ( data ) => {
+ getPluginHandler( site, plugin.slug ).install().then( ( data ) => {
dispatch( {
type: PLUGIN_SETUP_ACTIVATE,
siteId: site.ID,
@@ -105,7 +105,7 @@ function install( site, plugin, dispatch ) {
function update( site, plugin, dispatch ) {
console.log( '# Trying to update', plugin.name );
- getPluginHandler( site, plugin.id ).update().then( ( data ) => {
+ getPluginHandler( site, plugin.id ).updateVersion().then( ( data ) => {
dispatch( {
type: PLUGIN_SETUP_ACTIVATE,
siteId: site.ID,
|
The install process needs the plugin *slug*, not the ID — it’ll install correctly if it’s not available, but it will fail with an incorrect message if it already exists.
|
Automattic_wp-calypso
|
train
|
f6f759b2272c7247a6333d0e71fa43825e58be16
|
diff --git a/src/main/org/openscience/cdk/charges/AtomTypeCharges.java b/src/main/org/openscience/cdk/charges/AtomTypeCharges.java
index <HASH>..<HASH> 100644
--- a/src/main/org/openscience/cdk/charges/AtomTypeCharges.java
+++ b/src/main/org/openscience/cdk/charges/AtomTypeCharges.java
@@ -134,7 +134,9 @@ public class AtomTypeCharges implements IChargeCalculator {
}
return ac;
}
-
+
+ @TestMethod("testCharges_pOC,testCharges_pOP,testCharges_pOS," +
+ "testCharges_p_p,testCharges_p_n")
public void calculateCharges(IAtomContainer container) throws CDKException {
try {
this.setInitialCharges(container);
|
Added missing @TestMethod annotation
|
cdk_cdk
|
train
|
32e8a3dee4b58986394a426075e65dc357de7ad7
|
diff --git a/resolwe/storage/tests/test_manager.py b/resolwe/storage/tests/test_manager.py
index <HASH>..<HASH> 100644
--- a/resolwe/storage/tests/test_manager.py
+++ b/resolwe/storage/tests/test_manager.py
@@ -261,7 +261,7 @@ class DecisionMakerOverrideRuleTest(TestCase):
def test_override_process_type(self):
decision_maker = DecisionMaker(self.file_storage1)
settings = copy.deepcopy(CONNECTORS_SETTINGS)
- override = {"data:test:": {"delay": 10}}
+ override = {"data:test": {"delay": 10}}
override_nonexisting = {"data:nonexisting": {"delay": 10}}
FileStorage.objects.filter(pk=self.file_storage1.pk).update(
created=timezone.now() - timedelta(days=6)
|
Add test for missing colon
Change previous test to expose bug when colon was missing at the end of
process_type in the connector settings.
|
genialis_resolwe
|
train
|
95dcd01073d079dd12528dcf4b91f1088b4c36b7
|
diff --git a/zipkin-ui/js/component_ui/traceSummary.js b/zipkin-ui/js/component_ui/traceSummary.js
index <HASH>..<HASH> 100644
--- a/zipkin-ui/js/component_ui/traceSummary.js
+++ b/zipkin-ui/js/component_ui/traceSummary.js
@@ -147,12 +147,15 @@ export function traceSummary(spans = []) {
}
}
-function totalServiceTime(stamps, acc = 0) {
- if (stamps.length === 0) {
+export function totalServiceTime(stamps, acc = 0) {
+ // This is a recursive function that performs arithmetic on duration
+ // If duration is undefined, it will infinitely recurse. Filter out that case
+ const filtered = stamps.filter((s) => s.duration);
+ if (filtered.length === 0) {
return acc;
} else {
- const ts = _(stamps).minBy((s) => s.timestamp);
- const [current, next] = _(stamps)
+ const ts = _(filtered).minBy((s) => s.timestamp);
+ const [current, next] = _(filtered)
.partition((t) =>
t.timestamp >= ts.timestamp
&& t.timestamp + t.duration <= ts.timestamp + ts.duration)
diff --git a/zipkin-ui/test/component_ui/traceSummary.test.js b/zipkin-ui/test/component_ui/traceSummary.test.js
index <HASH>..<HASH> 100644
--- a/zipkin-ui/test/component_ui/traceSummary.test.js
+++ b/zipkin-ui/test/component_ui/traceSummary.test.js
@@ -2,7 +2,8 @@ import {
traceSummary,
getServiceName,
traceSummariesToMustache,
- mkDurationStr
+ mkDurationStr,
+ totalServiceTime
} from '../../js/component_ui/traceSummary';
import {Constants} from '../../js/component_ui/traceConstants';
import {endpoint, annotation, span} from './traceTestHelpers';
@@ -310,3 +311,27 @@ describe('mkDurationStr', () => {
mkDurationStr(2534999).should.equal('2.535s');
});
});
+
+describe('totalServiceTime', () => {
+ const time1 = {name: 'service', timestamp: 1456447911000000, duration: 1000};
+ const time2 = {name: 'service', timestamp: 1456447912000000, duration: 2000};
+ const time3 = {name: 'service', timestamp: 1456447913000000, duration: 3000};
+
+ it('should return zero on empty input', () => {
+ totalServiceTime([]).should.equal(0);
+ });
+
+ it('should return duration on single input', () => {
+ totalServiceTime([time1]).should.equal(time1.duration);
+ });
+
+ it('should sum on multiple inputs', () => {
+ totalServiceTime([time1, time2, time3]).should.equal(6000);
+ });
+
+ it('shouldnt infinitely recurse when duration is undefined', () => {
+ // when json form of span is missing the duration key
+ const undefinedDuration = {name: 'zipkin-web', timestamp: time1.timestamp, duration: undefined};
+ totalServiceTime([time1, time2, time3, undefinedDuration]).should.equal(6000);
+ });
+});
|
Filters undefined duration when calculating totalServiceTime
The zipkin api is supposed to return Span.timestamp and Span.duration.
There's a test `getSpansByTraceIds_doesntPerformQueryTimeAdjustment`,
which was added recently, which should insure that this is set.
Until all span store tests update to running this test, notably
zipkin-java, we'll need to guard as opposed to recursing indefinitely.
|
apache_incubator-zipkin
|
train
|
b225e86b120091b213d32e657180ecc446057c0a
|
diff --git a/CHANGELOG b/CHANGELOG
index <HASH>..<HASH> 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,3 +1,5 @@
+ Fixed #1017 -- environment-specific modulepath is no longer ignored.
+
Fixed #971 -- classes can once again be included multiple
times.
diff --git a/lib/puppet/parser/parser_support.rb b/lib/puppet/parser/parser_support.rb
index <HASH>..<HASH> 100644
--- a/lib/puppet/parser/parser_support.rb
+++ b/lib/puppet/parser/parser_support.rb
@@ -180,7 +180,7 @@ class Puppet::Parser::Parser
"in file #{@lexer.file} at line #{@lexer.line}"
)
end
- files = Puppet::Module::find_manifests(pat, :cwd => dir)
+ files = Puppet::Module::find_manifests(pat, :cwd => dir, :environment => @environment)
if files.size == 0
raise Puppet::ImportError.new("No file(s) found for import " +
"of '#{pat}'")
diff --git a/test/language/parser.rb b/test/language/parser.rb
index <HASH>..<HASH> 100755
--- a/test/language/parser.rb
+++ b/test/language/parser.rb
@@ -1188,5 +1188,17 @@ file { "/tmp/yayness":
assert_equal(result, parser.finddefine("", "fUntEst"),
"%s was not matched" % "fUntEst")
end
+
+ def test_manifests_with_multiple_environments
+ parser = mkparser :environment => "something"
+
+ # We use an exception to cut short the processing to simplify our stubbing
+ #Puppet::Module.expects(:find_manifests).with("test", {:cwd => ".", :environment => "something"}).raises(Puppet::ParseError)
+ Puppet::Module.expects(:find_manifests).with("test", {:cwd => ".", :environment => "something"}).returns([])
+
+ assert_raise(Puppet::ImportError) do
+ parser.import("test")
+ end
+ end
end
diff --git a/test/lib/puppettest/parsertesting.rb b/test/lib/puppettest/parsertesting.rb
index <HASH>..<HASH> 100644
--- a/test/lib/puppettest/parsertesting.rb
+++ b/test/lib/puppettest/parsertesting.rb
@@ -58,8 +58,8 @@ module PuppetTest::ParserTesting
Puppet::Parser::Interpreter.new
end
- def mkparser
- Puppet::Parser::Parser.new()
+ def mkparser(args = {})
+ Puppet::Parser::Parser.new(args)
end
def mkscope(hash = {})
|
Fixing #<I> -- environment-specific modulepath is no
longer ignored.
|
puppetlabs_puppet
|
train
|
34b7eb209ade193223591a211bf00526dd95f325
|
diff --git a/library/CM/Frontend/Environment.php b/library/CM/Frontend/Environment.php
index <HASH>..<HASH> 100644
--- a/library/CM/Frontend/Environment.php
+++ b/library/CM/Frontend/Environment.php
@@ -59,7 +59,7 @@ class CM_Frontend_Environment extends CM_Class_Abstract {
* @return bool
*/
public function hasViewer() {
- return null !== $this->_viewer
+ return null !== $this->_viewer;
}
/**
diff --git a/tests/helpers/CMTest/library/CMTest/TestCase.php b/tests/helpers/CMTest/library/CMTest/TestCase.php
index <HASH>..<HASH> 100644
--- a/tests/helpers/CMTest/library/CMTest/TestCase.php
+++ b/tests/helpers/CMTest/library/CMTest/TestCase.php
@@ -181,6 +181,21 @@ abstract class CMTest_TestCase extends PHPUnit_Framework_TestCase {
}
/**
+ * @param string $uri
+ * @param CM_Model_User $viewer
+ * @return CM_Response_Abstract
+ */
+ public function processRequest($uri, CM_Model_User $viewer = null) {
+ $request = CM_Request_Abstract::factory('GET', $uri);
+ if ($viewer) {
+ $request->getSession()->setUser($viewer);
+ }
+ $response = CM_Response_Abstract::factory($request);
+ $response->process();
+ return $response;
+ }
+
+ /**
* @param string $pageClass
* @param array $params OPTIONAL
* @return CM_Page_Abstract
@@ -205,7 +220,7 @@ abstract class CMTest_TestCase extends PHPUnit_Framework_TestCase {
}
/**
- * @param CM_Frontend_Render $render
+ * @param CM_Frontend_Render $render
* @param CM_FormField_Abstract $formField
* @param CM_Params|array|null $params
* @return CM_Dom_NodeList
@@ -279,8 +294,8 @@ abstract class CMTest_TestCase extends PHPUnit_Framework_TestCase {
}
/**
- * @param CM_Component_Abstract $cmp
- * @param CM_Frontend_Environment $environment
+ * @param CM_Component_Abstract $cmp
+ * @param CM_Frontend_Environment $environment
*/
public static function assertComponentAccessible(CM_Component_Abstract $cmp, CM_Frontend_Environment $environment) {
try {
@@ -294,8 +309,8 @@ abstract class CMTest_TestCase extends PHPUnit_Framework_TestCase {
}
/**
- * @param CM_Component_Abstract $cmp
- * @param CM_Frontend_Environment $environment
+ * @param CM_Component_Abstract $cmp
+ * @param CM_Frontend_Environment $environment
*/
public static function assertComponentNotAccessible(CM_Component_Abstract $cmp, CM_Frontend_Environment $environment, $expectedExceptionClass = null) {
$expectedExceptionClassList = array(
|
Fix environment, add processRequest test helper method
|
cargomedia_cm
|
train
|
a566ae916e5d7ac3ee4ee67823f0f90f470653f7
|
diff --git a/ryu/ofproto/nx_match.py b/ryu/ofproto/nx_match.py
index <HASH>..<HASH> 100644
--- a/ryu/ofproto/nx_match.py
+++ b/ryu/ofproto/nx_match.py
@@ -34,8 +34,10 @@ FWW_IN_PORT = 1 << 0
FWW_DL_TYPE = 1 << 4
FWW_NW_PROTO = 1 << 5
# No corresponding OFPFW_* bits
-FWW_NW_DSCP = 1 << 6
-FWW_NW_ECN = 1 << 7
+FWW_NW_DSCP = 1 << 1
+FWW_NW_ECN = 1 << 2
+FWW_ARP_SHA = 1 << 3
+FWW_ARP_THA = 1 << 6
FWW_NW_TTL = 1 << 8
FWW_ALL = (1 << 13) - 1
@@ -69,6 +71,8 @@ class Flow(object):
self.vlan_tci = 0
self.nw_ttl = 0
self.nw_proto = 0
+ self.arp_sha = 0
+ self.arp_tha = 0
class FlowWildcards(object):
@@ -160,6 +164,14 @@ class ClsRule(object):
self.wc.wildcards &= ~FWW_NW_TTL
self.flow.nw_ttl = nw_ttl
+ def set_arp_sha(self, sha):
+ self.wc.wildcards &= ~FWW_ARP_SHA
+ self.flow.arp_sha = sha
+
+ def set_arp_tha(self, tha):
+ self.wc.wildcards &= ~FWW_ARP_THA
+ self.flow.arp_tha = tha
+
def flow_format(self):
# Tunnel ID is only supported by NXM
if self.wc.tun_id_mask != 0:
@@ -396,6 +408,28 @@ class MFTPSRC(MFField):
return self.putm(buf, offset, rule.flow.tp_dst, rule.wc.tp_dst_mask)
+@_register_make
+@_set_nxm_headers([ofproto_v1_0.NXM_NX_ARP_SHA])
+class MFArpSha(MFField):
+ @classmethod
+ def make(cls):
+ return cls(MF_PACK_STRING_MAC)
+
+ def put(self, buf, offset, rule):
+ return self._put(buf, offset, rule.flow.arp_sha)
+
+
+@_register_make
+@_set_nxm_headers([ofproto_v1_0.NXM_NX_ARP_THA])
+class MFArpTha(MFField):
+ @classmethod
+ def make(cls):
+ return cls(MF_PACK_STRING_MAC)
+
+ def put(self, buf, offset, rule):
+ return self._put(buf, offset, rule.flow.arp_tha)
+
+
def serialize_nxm_match(rule, buf, offset):
old_offset = offset
@@ -470,7 +504,11 @@ def serialize_nxm_match(rule, buf, offset):
offset += nxm_put(buf, offset, header, rule)
# XXX: IP Source and Destination
# XXX: IPv6
- # XXX: ARP
+ # ARP
+ if not rule.wc.wildcards & FWW_ARP_SHA:
+ offset += nxm_put(buf, offset, ofproto_v1_0.NXM_NX_ARP_SHA, rule)
+ if not rule.wc.wildcards & FWW_ARP_THA:
+ offset += nxm_put(buf, offset, ofproto_v1_0.NXM_NX_ARP_THA, rule)
# Tunnel Id
if rule.wc.tun_id_mask != 0:
|
nxm: add NXM_NX_ARP_* support
|
osrg_ryu
|
train
|
38c457a3b8251c003d6a3c5a302c485cbcc7a932
|
diff --git a/src/django_like/__init__.py b/src/django_like/__init__.py
index <HASH>..<HASH> 100644
--- a/src/django_like/__init__.py
+++ b/src/django_like/__init__.py
@@ -4,8 +4,8 @@ from django.db.models.fields import Field, subclassing
from django.db.models.sql.constants import QUERY_TERMS
-QUERY_TERMS['like'] = None
-QUERY_TERMS['ilike'] = None
+QUERY_TERMS.add("like")
+QUERY_TERMS.add("like")
connection.operators['like'] = connection.operators['contains']
connection.operators['ilike'] = connection.operators['icontains']
NEW_LOOKUP_TYPE = ('like', 'ilike')
|
Now works with Django versions >= <I>
|
goinnn_django-like
|
train
|
fcbb11d95d34745d2a45ed82500d42457fde515b
|
diff --git a/salt/states/network.py b/salt/states/network.py
index <HASH>..<HASH> 100644
--- a/salt/states/network.py
+++ b/salt/states/network.py
@@ -493,6 +493,17 @@ def managed(name, enabled=True, **kwargs):
# Pull interface type out of kwargs
iface_type = str(kwargs.pop("type", "eth"))
+ if "addr" in kwargs:
+ hwaddr = kwargs.pop("addr")
+ msg = "'addr' is not a valid argument name, "
+ if "hwaddr" not in kwargs:
+ msg += "its value has been assigned to 'hwaddr' instead."
+ kwargs["hwaddr"] = hwaddr
+ else:
+ msg += "it has been ignored in favor of 'hwaddr'."
+ msg += " Update your SLS file to get rid of this warning."
+ ret.setdefault("warnings", []).append(msg)
+
# Build interface
try:
old = __salt__["ip.get_interface"](name)
|
Warn when using incorrect value "addr" for hwaddr
|
saltstack_salt
|
train
|
548018656b1263c65c0fb28a3518bfd8773f66f1
|
diff --git a/logging/src/components/Shared/QueryInput/QueryInput.js b/logging/src/components/Shared/QueryInput/QueryInput.js
index <HASH>..<HASH> 100644
--- a/logging/src/components/Shared/QueryInput/QueryInput.js
+++ b/logging/src/components/Shared/QueryInput/QueryInput.js
@@ -1,7 +1,9 @@
import React, { useState } from 'react';
import { FormInput } from 'fundamental-react';
-const labelRegexp = new RegExp(/[a-z0-9A-Z-_.]+="[a-z0-9A-Z-_.]+"/);
+const labelRegexp = new RegExp(
+ /[a-z0-9A-Z-_.]+(!?=|=~|!~)["`][a-z0-9A-Z-_.|*+\\[\]]+["`]/,
+);
const convertLabelsToString = labels => `{${labels.join(', ')}}`;
|
Fix validation error for logQL regex in log ui advanced search (#<I>)
* Support logql expressions
* update the regex
* fix linter error
|
kyma-project_console
|
train
|
66df2996aa83627daa5a1ac281e50344afab1f4a
|
diff --git a/spyder/plugins/ipythonconsole/widgets/shell.py b/spyder/plugins/ipythonconsole/widgets/shell.py
index <HASH>..<HASH> 100644
--- a/spyder/plugins/ipythonconsole/widgets/shell.py
+++ b/spyder/plugins/ipythonconsole/widgets/shell.py
@@ -23,9 +23,8 @@ from qtpy.QtWidgets import QMessageBox
from spyder.config.manager import CONF
from spyder.config.base import _
from spyder.config.gui import config_shortcut
-from spyder.py3compat import PY2, to_text_string
-from spyder.utils import encoding
-from spyder.utils import programs
+from spyder.py3compat import to_text_string
+from spyder.utils import programs, encoding
from spyder.utils import syntaxhighlighters as sh
from spyder.plugins.ipythonconsole.utils.style import create_qss_style, create_style_class
from spyder.widgets.helperwidgets import MessageCheckBox
@@ -501,8 +500,9 @@ the sympy module (e.g. plot)
editor = self.get_editor(filename)
if editor is None:
- raise RuntimeError(
- "File {} not open in the editor".format(filename))
+ # Load it from file instead
+ text, _enc = encoding.read(filename)
+ return text
return editor.toPlainText()
|
Load code from file if not open in editor.
|
spyder-ide_spyder
|
train
|
85b2705d2364edadf92910ea872fd56d2ea31191
|
diff --git a/sdl/sdl_events.go b/sdl/sdl_events.go
index <HASH>..<HASH> 100644
--- a/sdl/sdl_events.go
+++ b/sdl/sdl_events.go
@@ -326,6 +326,8 @@ type SysWMEvent struct {
msg unsafe.Pointer
}
+type EventFilter C.SDL_EventFilter
+
func PumpEvents() {
C.SDL_PumpEvents()
}
|
Split constants.go to different files
|
veandco_go-sdl2
|
train
|
4e075c370c6c55f2686a7ed469cb6cde5150c4bf
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -283,6 +283,7 @@ export default class Drawer extends Component {
};
onPanResponderRelease = (e, gestureState) => {
+ this._panning = false;
if (gestureState.moveX < 125) this.processTapGestures()
if (Math.abs(gestureState.dx) < 50 && this._activeTween) return
@@ -290,7 +291,6 @@ export default class Drawer extends Component {
this.updatePosition()
this._prevLeft = this._left
- this._panning = false
};
processShouldSet = (e, gestureState) => {
|
Adjusted for panning release (#<I>)
|
root-two_react-native-drawer
|
train
|
53993e4e775463e8cb61a35d8b75d99824128a51
|
diff --git a/nnpy/__init__.py b/nnpy/__init__.py
index <HASH>..<HASH> 100644
--- a/nnpy/__init__.py
+++ b/nnpy/__init__.py
@@ -14,4 +14,4 @@ class PollSet(object):
def poll(self, timeout=0):
rc = nanomsg.nn_poll(self.fd_set, len(self.data), timeout)
- return errors.convert(rc, lambda: self.fd_set[0].revents)
+ return errors.convert(rc, lambda: [fd.revents for fd in self.fd_set])
|
Return poll result for all SP sockets, not first socket only. (#<I>)
|
nanomsg_nnpy
|
train
|
a9cfbdb496283687f6b841a6dc55f391aae3ed9a
|
diff --git a/lib/pdf_ravager/field_types/acro_form.rb b/lib/pdf_ravager/field_types/acro_form.rb
index <HASH>..<HASH> 100644
--- a/lib/pdf_ravager/field_types/acro_form.rb
+++ b/lib/pdf_ravager/field_types/acro_form.rb
@@ -22,7 +22,6 @@ module PDFRavager
def set_acro_form_value(acro_fields)
begin
acro_fields.setField(SOM.short_name(@name), acro_form_value)
- true
rescue java.lang.NullPointerException
false
end
|
AcroFields#setField already returns boolean
|
abevoelker_pdf_ravager
|
train
|
c15f52bec475c4d15b81ae7199f057c2a1fbfd6b
|
diff --git a/lib/custom/src/MShop/Service/Provider/Payment/Datatrans.php b/lib/custom/src/MShop/Service/Provider/Payment/Datatrans.php
index <HASH>..<HASH> 100644
--- a/lib/custom/src/MShop/Service/Provider/Payment/Datatrans.php
+++ b/lib/custom/src/MShop/Service/Provider/Payment/Datatrans.php
@@ -64,4 +64,21 @@ class Datatrans
throw new \Aimeos\MShop\Service\Exception( sprintf( 'Token based payment failed: %1$s', $msg ) );
}
}
+
+
+ /**
+ * Returns the value for the given configuration key
+ *
+ * @param string $key Configuration key name
+ * @param mixed $default Default value if no configuration is found
+ * @return mixed Configuration value
+ */
+ protected function getValue( $key, $default = null )
+ {
+ switch( $key ) {
+ case 'type': return 'Datatrans';
+ }
+
+ return parent::getValue( $key, $default );
+ }
}
|
Use Omnipay Datatrans driver by default
|
aimeoscom_ai-payments
|
train
|
4d2fb7b3b245206ca6f15c3b97177efd7d7e99c9
|
diff --git a/src/Charcoal/Object/ObjectRoute.php b/src/Charcoal/Object/ObjectRoute.php
index <HASH>..<HASH> 100644
--- a/src/Charcoal/Object/ObjectRoute.php
+++ b/src/Charcoal/Object/ObjectRoute.php
@@ -3,7 +3,6 @@ namespace Charcoal\Object;
use DateTime;
use DateTimeInterface;
-use Exception;
use InvalidArgumentException;
use RuntimeException;
use Exception;
|
Improved ‘RoutableTrait::isActiveRoute()’
Changes:
- Modified ‘RoutableTrait::isActiveRoute()’ to check if “active” is available, if not consider route activated;
- Added ‘RoutableInterface::isActiveRoute()’;
- Fixed PHPCS Issues;
|
locomotivemtl_charcoal-object
|
train
|
46c31c82fb77a2568e1021e1bd2f08e198d3c7ae
|
diff --git a/eZ/Publish/Core/Repository/LocationService.php b/eZ/Publish/Core/Repository/LocationService.php
index <HASH>..<HASH> 100644
--- a/eZ/Publish/Core/Repository/LocationService.php
+++ b/eZ/Publish/Core/Repository/LocationService.php
@@ -426,7 +426,7 @@ class LocationService implements LocationServiceInterface
}
$createStruct = new CreateStruct();
- $createStruct->priority = $locationCreateStruct->priority === null ?: (int) $locationCreateStruct->priority;
+ $createStruct->priority = $locationCreateStruct->priority !== null ? (int) $locationCreateStruct->priority : null;
// if we declare the new location as hidden, it is automatically invisible
// otherwise, it remains unhidden, and picks up visibility from parent
@@ -450,8 +450,15 @@ class LocationService implements LocationServiceInterface
$createStruct->contentId = (int) $contentInfo->contentId;
$createStruct->contentVersion = (int) $contentInfo->currentVersionNo;
- $createStruct->sortField = $locationCreateStruct->sortField === null ? APILocation::SORT_FIELD_NAME : (int) $locationCreateStruct->sortField;
- $createStruct->sortOrder = $locationCreateStruct->sortOrder === null ? APILocation::SORT_ORDER_ASC : (int) $locationCreateStruct->sortOrder;
+ // @todo: set pathIdentificationString
+ // $createStruct->pathIdentificationString = null;
+
+ $mainLocation = $this->loadMainLocation( $contentInfo );
+ if ( $mainLocation !== null )
+ $createStruct->mainLocationId = $mainLocation->id;
+
+ $createStruct->sortField = $locationCreateStruct->sortField !== null ? (int) $locationCreateStruct->sortField : APILocation::SORT_FIELD_NAME;
+ $createStruct->sortOrder = $locationCreateStruct->sortOrder !== null ? (int) $locationCreateStruct->sortOrder : APILocation::SORT_ORDER_ASC;
$createStruct->parentId = $loadedParentLocation->id;
$newLocation = $this->persistenceHandler->locationHandler()->create( $createStruct );
|
Set main location id in location create struct
|
ezsystems_ezpublish-kernel
|
train
|
21b157001a4ba746209f5eae0c7bb2f8e6e990a3
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
jQuery background parallax plugin used for adding a smooth parallax scrolling effect to background images and Youtube/Vimeo videos using CSS3 transforms (translate3d). With a background-position fallback when CSS transforms are not supported.
## Tested Browsers
-* IE7+
+* IE9+
* Safari 5.1.7+
* Opera 12+
* Latest browsers on Mac and Windows (Chrome, Firefox, Safari, IE, Edge)
diff --git a/jarallax/jarallax-video.js b/jarallax/jarallax-video.js
index <HASH>..<HASH> 100644
--- a/jarallax/jarallax-video.js
+++ b/jarallax/jarallax-video.js
@@ -396,13 +396,6 @@
}(function($) {
var Jarallax = $.fn.jarallax.constructor;
- // check if parallax container is in viewport
- // http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport
- function isElementInViewport($el) {
- var rect = $el[0].getBoundingClientRect();
- return (rect.bottom >= 0 && rect.right >= 0 && rect.top <= (window.innerHeight || document.documentElement.clientHeight) && rect.left <= (window.innerWidth || document.documentElement.clientWidth));
- }
-
// append video after init Jarallax
var def_init = Jarallax.prototype.init;
Jarallax.prototype.init = function() {
@@ -457,7 +450,7 @@
video.on('ready', function() {
function checkViewport() {
- if(isElementInViewport(_this.$item)) {
+ if(_this.isVisible()) {
video.play();
} else {
video.pause();
diff --git a/jarallax/jarallax.js b/jarallax/jarallax.js
index <HASH>..<HASH> 100644
--- a/jarallax/jarallax.js
+++ b/jarallax/jarallax.js
@@ -368,6 +368,10 @@
}
};
+ Jarallax.prototype.isVisible = function() {
+ return this.isElementInViewport || false;
+ }
+
Jarallax.prototype.onScroll = function(force) {
var _this = this;
@@ -375,37 +379,40 @@
return;
}
- var scrollTop = $(window).scrollTop(),
- windowHeight = $(window).height(),
- // starting position of each element to have parallax applied to it
- sectionTop = _this.$item.offset().top,
- sectionHeight = _this.$item.outerHeight(true),
+ var section = _this.$item[0].getBoundingClientRect();
+ console.log($(window)[0].getBoundingClientRect())
+ var windowHeight = $(window).height(),
+ windowWidth = $(window).width(),
css = {
visibility : 'visible',
backgroundPosition : '50% 50%'
};
+ _this.isElementInViewport = (
+ section.bottom >= 0 &&
+ section.right >= 0 &&
+ section.top <= windowHeight &&
+ section.left <= windowWidth
+ );
+
// Check if totally above or totally below viewport
- var check = force ? false
- : sectionTop + sectionHeight < scrollTop || sectionTop > scrollTop + windowHeight;
+ var check = force ? false : !_this.isElementInViewport;
if (check) {
return;
}
// calculate parallax helping variables
- var dy = scrollTop - sectionTop;
-
- var beforeTop = Math.max(0, -dy);
- var beforeTopEnd = Math.max(0, sectionHeight - dy);
- var afterTop = Math.max(0, dy);
- var beforeBottom = Math.max(0, -dy + sectionHeight - windowHeight);
- var beforeBottomEnd = Math.max(0, sectionHeight - (-dy + sectionHeight - windowHeight));
- var afterBottom = Math.max(0, dy + windowHeight - sectionHeight);
+ var beforeTop = Math.max(0, section.top);
+ var beforeTopEnd = Math.max(0, section.height + section.top);
+ var afterTop = Math.max(0, -section.top);
+ var beforeBottom = Math.max(0, section.top + section.height - windowHeight);
+ var beforeBottomEnd = Math.max(0, section.height - (section.top + section.height - windowHeight));
+ var afterBottom = Math.max(0, -section.top + windowHeight - section.height);
// calculate on how percent of section is visible
var visiblePercent = 1;
- if(sectionHeight < windowHeight) {
- visiblePercent = 1 - (afterTop || beforeBottom) / sectionHeight;
+ if(section.height < windowHeight) {
+ visiblePercent = 1 - (afterTop || beforeBottom) / section.height;
} else {
if(beforeTopEnd <= windowHeight) {
visiblePercent = beforeTopEnd / windowHeight;
@@ -431,7 +438,7 @@
// scroll
if(_this.options.type == 'scroll' || _this.options.type == 'scroll-opacity') {
- var positionY = - dy * _this.options.speed;
+ var positionY = section.top * _this.options.speed;
positionY = _this.round(positionY);
if(supportTransform && _this.options.enableTransform) {
css.transform = 'translateY(' + positionY + 'px)';
@@ -449,9 +456,8 @@
// call onScroll event
if(_this.options.onScroll) {
_this.options.onScroll.call(_this, {
- scrollTop: scrollTop,
- sectionHeight: sectionHeight,
windowHeight: windowHeight,
+ section: section,
beforeTop: beforeTop,
beforeTopEnd: beforeTopEnd,
|
changed jQuery offset to getBoundingClientRect (less browser compatibility, more performance)
|
nk-o_jarallax
|
train
|
2d7823211cac8b24faec809ca4bb07f7e4f252aa
|
diff --git a/security-jwt/src/main/java/io/micronaut/security/token/jwt/signature/jwks/JwksSignature.java b/security-jwt/src/main/java/io/micronaut/security/token/jwt/signature/jwks/JwksSignature.java
index <HASH>..<HASH> 100644
--- a/security-jwt/src/main/java/io/micronaut/security/token/jwt/signature/jwks/JwksSignature.java
+++ b/security-jwt/src/main/java/io/micronaut/security/token/jwt/signature/jwks/JwksSignature.java
@@ -58,7 +58,7 @@ import java.util.Optional;
public class JwksSignature implements SignatureConfiguration {
private static final Logger LOG = LoggerFactory.getLogger(JwksSignature.class);
- private static final int REFRESH_JWKS_ATTEMPTS = 1;
+ public static final int DEFAULT_REFRESH_JWKS_ATTEMPTS = 1;
@Nullable
private JWKSet jwkSet;
@@ -129,7 +129,7 @@ public class JwksSignature implements SignatureConfiguration {
*/
@Override
public boolean verify(SignedJWT jwt) throws JOSEException {
- List<JWK> matches = matches(jwt, getJWKSet().orElse(null), REFRESH_JWKS_ATTEMPTS);
+ List<JWK> matches = matches(jwt, getJWKSet().orElse(null), getRefreshJwksAttempts());
if (LOG.isDebugEnabled()) {
LOG.debug("Found {} matching JWKs", matches.size());
}
@@ -247,4 +247,12 @@ public class JwksSignature implements SignatureConfiguration {
}
});
}
+
+ /**
+ * Returns the number of attempts to refresh the cached JWKS.
+ * @return Number of attempts to refresh the cached JWKS.
+ */
+ public int getRefreshJwksAttempts() {
+ return DEFAULT_REFRESH_JWKS_ATTEMPTS;
+ }
}
|
ease override of number of JWS refresh attempts
|
micronaut-projects_micronaut-core
|
train
|
3723afad0bab93201b21379c2bb69387a7ca75c0
|
diff --git a/Manager/NotificationManager.php b/Manager/NotificationManager.php
index <HASH>..<HASH> 100644
--- a/Manager/NotificationManager.php
+++ b/Manager/NotificationManager.php
@@ -7,6 +7,7 @@ use Doctrine\ORM\NoResultException;
use Icap\NotificationBundle\Entity\FollowerResource;
use Claroline\CoreBundle\Event\Log\NotifiableInterface;
use Icap\NotificationBundle\Entity\Notification;
+use Icap\NotificationBundle\Entity\NotificationPluginConfiguration;
use Icap\NotificationBundle\Entity\NotificationViewer;
use Doctrine\ORM\EntityManager;
use Icap\NotificationBundle\Event\Notification\NotificationCreateDelegateViewEvent;
@@ -52,9 +53,38 @@ class NotificationManager
*/
protected $notificationPluginConfigurationManager;
+ private function getLoggedUser()
+ {
+ $securityToken = $this->security->getToken();
+
+ if (null !== $securityToken) {
+ $doer = $securityToken->getUser();
+ }
+
+ return $doer;
+ }
+
private function getConfigurationAndPurge()
{
- return $this->notificationPluginConfigurationManager->getConfigOrEmpty();
+ $config = $this->notificationPluginConfigurationManager->getConfigOrEmpty();
+ if($config->getPurgeEnabled())$this->purgeNotifications($config);
+
+ return $config;
+ }
+
+ private function purgeNotifications(NotificationPluginConfiguration $config)
+ {
+ $lastPurgeDate = $config->getLastPurgeDate();
+ $today = (new \DateTime())->setTime(0, 0, 0);
+ if ($lastPurgeDate === null || $today > $lastPurgeDate) {
+ $purgeBeforeDate = clone $today;
+ $purgeBeforeDate->sub(new \DateInterval('P'.$config->getPurgeAfterDays().'D'));
+ $this->getNotificationRepository()->deleteNotificationsBeforeDate($purgeBeforeDate);
+
+ $config->setLastPurgeDate($today);
+ $this->em->persist($config);
+ $this->em->flush();
+ }
}
/**
@@ -220,11 +250,7 @@ class NotificationManager
$doerId = null;
if ($doer === null) {
- $securityToken = $this->security->getToken();
-
- if (null !== $securityToken) {
- $doer = $securityToken->getUser();
- }
+ $doer = $this->getLoggedUser();
}
if (is_a($doer, 'Claroline\CoreBundle\Entity\User')) {
@@ -262,7 +288,7 @@ class NotificationManager
{
if (count($userIds) > 0) {
foreach ($userIds as $userId) {
- if ($userId !== null) {
+ if ($userId !== null && $notification->getUserId() !== $userId) {
$notificationViewer = new NotificationViewer();
$notificationViewer->setNotification($notification);
$notificationViewer->setViewerId($userId);
diff --git a/Repository/NotificationRepository.php b/Repository/NotificationRepository.php
index <HASH>..<HASH> 100644
--- a/Repository/NotificationRepository.php
+++ b/Repository/NotificationRepository.php
@@ -6,5 +6,14 @@ use Doctrine\ORM\EntityRepository;
class NotificationRepository extends EntityRepository
{
+ public function deleteNotificationsBeforeDate(\DateTime $date)
+ {
+ $qb = $this->createQueryBuilder("notification");
+ $qb
+ ->delete()
+ ->andWhere("notification.creationDate < :limitDate")
+ ->setParameter("limitDate", $date);
+ $qb->getQuery()->execute();
+ }
}
\ No newline at end of file
|
[NotificationBundle] Implemented purge functionality
|
claroline_Distribution
|
train
|
8df9de85c965f153dff3873228ab770825c275db
|
diff --git a/structr-ui/src/main/resources/structr/js/contents.js b/structr-ui/src/main/resources/structr/js/contents.js
index <HASH>..<HASH> 100644
--- a/structr-ui/src/main/resources/structr/js/contents.js
+++ b/structr-ui/src/main/resources/structr/js/contents.js
@@ -76,7 +76,7 @@ var _Contents = {
_Entities.appendAccessControlIcon(div, entity);
- div.append('<img title="Clone content node \'' + entity.name + '\'" alt="Clone content node \'' + entity.name + '\'" class="clone_icon button" src="icon/page_copy.png">');
+ div.append('<img title="Clone content node ' + entity.id + '" alt="Clone content node ' + entity.id + '" class="clone_icon button" src="icon/page_copy.png">');
$('.clone_icon', div).on('click', function(e) {
e.stopPropagation();
Command.cloneNode(entity.id, entity.parent.id, true)
diff --git a/structr-ui/src/main/resources/structr/js/elements.js b/structr-ui/src/main/resources/structr/js/elements.js
index <HASH>..<HASH> 100644
--- a/structr-ui/src/main/resources/structr/js/elements.js
+++ b/structr-ui/src/main/resources/structr/js/elements.js
@@ -369,7 +369,7 @@ var _Elements = {
+ _Elements.classIdString(entity._html_id, entity._html_class)
+ '</div>');
- div.append('<img title="Clone element \'' + entity.name + '\'" alt="Clone element \'' + entity.name + '\'" class="clone_icon button" src="icon/page_copy.png">');
+ div.append('<img title="Clone ' + entity.tag + ' element ' + entity.id + '\" alt="Clone ' + entity.tag + ' element ' + entity.id + '" class="clone_icon button" src="icon/page_copy.png">');
$('.clone_icon', div).on('click', function(e) {
e.stopPropagation();
Command.cloneNode(entity.id, entity.parent.id, true);
|
Fixed title/alt tag of clone icons.
|
structr_structr
|
train
|
1ddfb28a7802d93b4753d5238b8011fe441105c2
|
diff --git a/common/test/unit/com/thoughtworks/go/domain/PipelineConfigValidationTest.java b/common/test/unit/com/thoughtworks/go/domain/PipelineConfigValidationTest.java
index <HASH>..<HASH> 100644
--- a/common/test/unit/com/thoughtworks/go/domain/PipelineConfigValidationTest.java
+++ b/common/test/unit/com/thoughtworks/go/domain/PipelineConfigValidationTest.java
@@ -373,7 +373,7 @@ public class PipelineConfigValidationTest {
@Test
public void shouldValidateAPipelineHasAtleastOneStage() {
PipelineConfig pipelineConfig = new PipelineConfig(new CaseInsensitiveString("p"), new MaterialConfigs());
- pipelineConfig.validateTemplate(null);
+ pipelineConfig.validateTree(PipelineConfigSaveValidationContext.forChain(true, "group", new BasicCruiseConfig(new BasicPipelineConfigs("group", new Authorization())), pipelineConfig));
assertThat(pipelineConfig.errors().on("pipeline"), is("Pipeline 'p' does not have any stages configured. A pipeline must have at least one stage."));
}
diff --git a/config/config-api/src/com/thoughtworks/go/config/PipelineConfig.java b/config/config-api/src/com/thoughtworks/go/config/PipelineConfig.java
index <HASH>..<HASH> 100644
--- a/config/config-api/src/com/thoughtworks/go/config/PipelineConfig.java
+++ b/config/config-api/src/com/thoughtworks/go/config/PipelineConfig.java
@@ -159,6 +159,9 @@ public class PipelineConfig extends BaseCollection<StageConfig> implements Param
validateLabelTemplate();
validatePipelineName();
validateStageNameUniqueness();
+ if (!hasTemplate() && isEmpty()) {
+ addError("pipeline", String.format("Pipeline '%s' does not have any stages configured. A pipeline must have at least one stage.", name()));
+ }
}
public void validateTemplate(PipelineTemplateConfig templateConfig) {
@@ -173,10 +176,6 @@ public class PipelineConfig extends BaseCollection<StageConfig> implements Param
if (templateConfig==null) {
addError("pipeline", String.format("Pipeline '%s' refers to non-existent template '%s'.", name(), templateName));
}
- } else {
- if (isEmpty()) {
- addError("pipeline", String.format("Pipeline '%s' does not have any stages configured. A pipeline must have at least one stage.", name()));
- }
}
}
|
had missing empty stages validation - #<I>, #<I>
|
gocd_gocd
|
train
|
8fb84cef7139964598fdb800dfaac9259a80bcc1
|
diff --git a/template/html/d3-graph.js b/template/html/d3-graph.js
index <HASH>..<HASH> 100644
--- a/template/html/d3-graph.js
+++ b/template/html/d3-graph.js
@@ -37,6 +37,18 @@
text: []
};
+ function cerialize(text)
+ {
+ var svgxml = (new XMLSerializer()).serializeToString(d3.select('svg').node());
+ console.log('!!! serialize data -- text: ' + text);
+ console.log('!!! svg: ' + svgxml);
+ if (data)
+ {
+ console.log('!!! data.links: ' + JSON.stringify(data.links));
+ console.log('!!! data.nodes: ' + JSON.stringify(data.nodes));
+ }
+ }
+
function bootstrap()
{
// Controllers
@@ -222,13 +234,13 @@
}
else
{
- var elmAllLinks = $('path.link:not([data-show])');
-
- elmAllLinks.attr('marker-end', opacity === 1 ? 'url(#regular)' : '');
-
return opacity;
}
});
+
+ // Modify all links that have not had 'data-show' added above.
+ var elmAllLinks = $('path.link:not([data-show])');
+ elmAllLinks.attr('marker-end', opacity === 1 ? 'url(#regular)' : '');
}
function findElementByNode(prefix, node)
@@ -433,7 +445,7 @@
function onControlTableRowContextClick(node, event)
{
- event.preventDefault();
+ event.preventDefault(); // Prevents default browser context menu from showing.
onNodeContextClick(node, { x: event.pageX, y: event.pageY });
}
@@ -653,12 +665,13 @@
recycleGraph();
// Lines
+ // Note: on second render o.source / target will be an object instead of a number.
links = graph.append(getSVG('g')).selectAll('line')
.data(data.links)
.enter().append(getSVG('path'))
.attr('class', 'link')
- .attr('data-target', function(o) { return o.target; })
- .attr('data-source', function(o) { return o.source; })
+ .attr('data-target', function(o) { return typeof o.target === 'number' ? o.target : o.target.index; })
+ .attr('data-source', function(o) { return typeof o.source === 'number' ? o.source : o.source.index; })
.attr('marker-end', function() { return 'url(#regular)'; });
// Nodes
|
fixed link arrow selection on redraw.
|
typhonjs-node-esdoc_esdoc-plugin-dependency-graphs
|
train
|
1cefff0f3ef9188176b216f5bad8e068e0f9a1de
|
diff --git a/core-bundle/src/Resources/contao/library/Contao/Database.php b/core-bundle/src/Resources/contao/library/Contao/Database.php
index <HASH>..<HASH> 100644
--- a/core-bundle/src/Resources/contao/library/Contao/Database.php
+++ b/core-bundle/src/Resources/contao/library/Contao/Database.php
@@ -63,6 +63,12 @@ abstract class Database
*/
protected $arrCache = array();
+ /**
+ * Model registry
+ * @var \Model\Registry
+ */
+ protected $objModelRegistry;
+
/**
* Establish the database connection
@@ -75,6 +81,7 @@ abstract class Database
{
$this->arrConfig = $arrConfig;
$this->connect();
+ $this->objModelRegistry = new \Model\Registry($this);
if (!is_resource($this->resConnection) && !is_object($this->resConnection))
{
@@ -165,6 +172,17 @@ abstract class Database
/**
+ * Return the model registry bound to this connection.
+ *
+ * @return \Model\Registry The model registry.
+ */
+ public function getModelRegistry()
+ {
+ return $this->objModelRegistry;
+ }
+
+
+ /**
* Prepare a query and return a Database\Statement object
*
* @param string $strQuery The query string
|
[Core] Add a registry to each database connection.
|
contao_contao
|
train
|
cd0e8407e19a8ecd8a81c3f6c65272d80e902ac7
|
diff --git a/src/unity/python/turicreate/test/test_boosted_trees.py b/src/unity/python/turicreate/test/test_boosted_trees.py
index <HASH>..<HASH> 100644
--- a/src/unity/python/turicreate/test/test_boosted_trees.py
+++ b/src/unity/python/turicreate/test/test_boosted_trees.py
@@ -235,6 +235,11 @@ class BoostedTreesRegressionTest(unittest.TestCase):
sf = self.model.get_feature_importance()
self.assertEqual(sf.column_names(), ["name", "index", "count"])
+ def test_trees_json(self):
+ tree_0_vert_0 = eval(self.model.trees_json[0])['vertices'][0]
+ self.assertEquals(set(tree_0_vert_0.keys()),
+ set(['name','value_hexadecimal','yes_child','cover','missing_child','no_child','type','id','value','gain']))
+
def test_list_and_dict_type(self):
rmse_threshold = 0.2
|
Add unitest for boosted trees model json.
The model json sould include 'gain' and 'cover' keys.
|
apple_turicreate
|
train
|
09e3f0b4f5ceb19b1976e53d0a115d6a9f68e79a
|
diff --git a/tests/test_views.py b/tests/test_views.py
index <HASH>..<HASH> 100644
--- a/tests/test_views.py
+++ b/tests/test_views.py
@@ -257,7 +257,7 @@ def test_login_redirect_based_on_cookie(monkeypatch, django_user_model, settings
assert response.status_code == 302
assert response['Location'] == '/admin/'
- assert 'CASNEXT' not in request.session
+ assert request.session['CASNEXT'] is None
assert django_user_model.objects.get(username='test@example.com').is_authenticated is True
|
Update test assertion, as session key is set to None
The 'CASNEXT' key is not deleted anymore since <URL>
|
mingchen_django-cas-ng
|
train
|
27d5caf40e41fc3576518c4dc9469b5896fbe5fb
|
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
@@ -20,6 +20,7 @@ import re
from typing import Callable
from .filter import Filter
+from ..types import Message, CallbackQuery, InlineQuery
from ..types.bots_and_keyboards import InlineKeyboardMarkup, ReplyKeyboardMarkup
CUSTOM_FILTER_NAME = "CustomFilter"
@@ -288,26 +289,39 @@ class Filters:
)
@staticmethod
- def regex(pattern, flags: int = 0):
- """Filter message texts or captions that match a given regular expression pattern.
+ def regex(pattern: str, flags: int = 0):
+ """Filter updates that match a given regular expression pattern.
+
+ Can be applied to handlers that receive one of the following updates:
+
+ - :obj:`Message`: The filter will match ``text`` or ``caption``.
+ - :obj:`CallbackQuery`: The filter will match ``data``.
+ - :obj:`InlineQuery`: The filter will match ``query``.
+
+ When a pattern matches, all the `Match Objects <https://docs.python.org/3/library/re.html#match-objects>`_ are
+ stored in the ``matches`` field of the update object itself.
Parameters:
pattern (``str``):
- The RegEx pattern as string, it will be applied to the text or the caption of a message. When a pattern
- matches, all the `Match Objects <https://docs.python.org/3/library/re.html#match-objects>`_ are stored
- in the *matches* field of the :obj:`Message` itself.
+ The regex pattern as string.
flags (``int``, *optional*):
- RegEx flags.
+ Regex flags.
"""
- def func(flt, message):
- text = message.text or message.caption
+ def func(flt, update):
+ if isinstance(update, Message):
+ value = update.text or update.caption
+ elif isinstance(update, CallbackQuery):
+ value = update.data
+ elif isinstance(update, InlineQuery):
+ value = update.query
+ else:
+ raise ValueError("Regex filter doesn't work with {}".format(type(update)))
- if text:
- message.matches = list(flt.p.finditer(text)) or None
+ update.matches = list(flt.p.finditer(value)) or None
- return bool(message.matches)
+ return bool(update.matches)
return create(func, "RegexFilter", p=re.compile(pattern, flags))
diff --git a/pyrogram/client/types/bots_and_keyboards/callback_query.py b/pyrogram/client/types/bots_and_keyboards/callback_query.py
index <HASH>..<HASH> 100644
--- a/pyrogram/client/types/bots_and_keyboards/callback_query.py
+++ b/pyrogram/client/types/bots_and_keyboards/callback_query.py
@@ -18,7 +18,7 @@
from base64 import b64encode
from struct import pack
-from typing import Union
+from typing import Union, List, Match
import pyrogram
from pyrogram.api import types
@@ -59,6 +59,9 @@ class CallbackQuery(Object, Update):
game_short_name (``str``, *optional*):
Short name of a Game to be returned, serves as the unique identifier for the game.
+ matches (List of regex Matches, *optional*):
+ A list containing all `Match Objects <https://docs.python.org/3/library/re.html#match-objects>`_ that match
+ the data of this callback query. Only applicable when using :obj:`Filters.regex <pyrogram.Filters.regex>`.
"""
def __init__(
@@ -71,7 +74,8 @@ class CallbackQuery(Object, Update):
message: "pyrogram.Message" = None,
inline_message_id: str = None,
data: Union[str, bytes] = None,
- game_short_name: str = None
+ game_short_name: str = None,
+ matches: List[Match] = None
):
super().__init__(client)
@@ -82,6 +86,7 @@ class CallbackQuery(Object, Update):
self.inline_message_id = inline_message_id
self.data = data
self.game_short_name = game_short_name
+ self.matches = matches
@staticmethod
def _parse(client, callback_query, users) -> "CallbackQuery":
diff --git a/pyrogram/client/types/inline_mode/inline_query.py b/pyrogram/client/types/inline_mode/inline_query.py
index <HASH>..<HASH> 100644
--- a/pyrogram/client/types/inline_mode/inline_query.py
+++ b/pyrogram/client/types/inline_mode/inline_query.py
@@ -16,7 +16,7 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
-from typing import List
+from typing import List, Match
import pyrogram
from pyrogram.api import types
@@ -47,6 +47,10 @@ class InlineQuery(Object, Update):
location (:obj:`Location`. *optional*):
Sender location, only for bots that request user location.
+
+ matches (List of regex Matches, *optional*):
+ A list containing all `Match Objects <https://docs.python.org/3/library/re.html#match-objects>`_ that match
+ the query of this inline query. Only applicable when using :obj:`Filters.regex <pyrogram.Filters.regex>`.
"""
def __init__(
@@ -57,7 +61,8 @@ class InlineQuery(Object, Update):
from_user: User,
query: str,
offset: str,
- location: Location = None
+ location: Location = None,
+ matches: List[Match] = None
):
super().__init__(client)
@@ -66,6 +71,7 @@ class InlineQuery(Object, Update):
self.query = query
self.offset = offset
self.location = location
+ self.matches = matches
@staticmethod
def _parse(client, inline_query: types.UpdateBotInlineQuery, users: dict) -> "InlineQuery":
|
Give Filters.regex superpowers
Basically make it work on Message, CallbackQuery and InlineQuery updates
|
pyrogram_pyrogram
|
train
|
5c045a86af61ed0732c46eace39c4e71229a460a
|
diff --git a/salt/states/cmd.py b/salt/states/cmd.py
index <HASH>..<HASH> 100644
--- a/salt/states/cmd.py
+++ b/salt/states/cmd.py
@@ -55,6 +55,11 @@ This means that if a ``cmd`` state is watched by another state then the
state that's watching will always be executed due to the `changed` state in
the ``cmd`` state.
+.. _stateful-argument:
+
+Using the "Stateful" Argument
+-----------------------------
+
Many state functions in this module now also accept a ``stateful`` argument.
If ``stateful`` is specified to be true then it is assumed that the command
or script will determine its own state and communicate it back by following
@@ -470,7 +475,7 @@ def wait(name,
stateful
The command being executed is expected to return data about executing
- a state
+ a state. For more information, see the :ref:`stateful-argument` section.
creates
Only run if the file specified by ``creates`` does not exist.
@@ -599,7 +604,7 @@ def wait_script(name,
stateful
The command being executed is expected to return data about executing
- a state
+ a state. For more information, see the :ref:`stateful-argument` section.
use_vt
Use VT utils (saltstack) to stream the command output more
@@ -708,7 +713,7 @@ def run(name,
stateful
The command being executed is expected to return data about executing
- a state
+ a state. For more information, see the :ref:`stateful-argument` section.
umask
The umask (in octal) to use when running the command.
@@ -951,7 +956,7 @@ def script(name,
stateful
The command being executed is expected to return data about executing
- a state
+ a state. For more information, see the :ref:`stateful-argument` section.
timeout
If the command has not terminated after timeout seconds, send the
|
Link "stateful" kwargs to definition of what "stateful" means for cmd state.
Fixes #<I>
|
saltstack_salt
|
train
|
f57398072fedfeac00e1ba9d1f683b0b82e74f4a
|
diff --git a/scripts/tofucustom.py b/scripts/tofucustom.py
index <HASH>..<HASH> 100755
--- a/scripts/tofucustom.py
+++ b/scripts/tofucustom.py
@@ -1,6 +1,7 @@
#!/usr/bin/env python
# Built-in
+import sys
import os
from shutil import copyfile
diff --git a/scripts/tofuversion.py b/scripts/tofuversion.py
index <HASH>..<HASH> 100755
--- a/scripts/tofuversion.py
+++ b/scripts/tofuversion.py
@@ -1,6 +1,7 @@
#!/usr/bin/env python
# Built-in
+import sys
import os
import warnings
diff --git a/tofu/version.py b/tofu/version.py
index <HASH>..<HASH> 100644
--- a/tofu/version.py
+++ b/tofu/version.py
@@ -1,2 +1,2 @@
# Do not edit, pipeline versioning governed by git tags!
-__version__ = '1.4.7-2-g5ad46212'
+__version__ = '1.4.7-3-g827b989c'
|
[Issue<I>] Added import sys to tofuversion.py and tofucustom.py
|
ToFuProject_tofu
|
train
|
231ae194ccae827d3a7c46cf77fd8e8d86b32149
|
diff --git a/imgaug/augmenters/convolutional.py b/imgaug/augmenters/convolutional.py
index <HASH>..<HASH> 100644
--- a/imgaug/augmenters/convolutional.py
+++ b/imgaug/augmenters/convolutional.py
@@ -333,13 +333,15 @@ def EdgeDetect(alpha=0, name=None, deterministic=False, random_state=None):
Parameters
----------
- alpha : int or float or tuple of two ints/floats or StochasticParameter, optional(default=0)
+ alpha : number or tuple of number or list of number or StochasticParameter, optional(default=0)
Visibility of the sharpened image. At 0, only the original image is
visible, at 1.0 only its sharpened version is visible.
* If an int or float, exactly that value will be used.
* If a tuple (a, b), a random value from the range a <= x <= b will
be sampled per image.
+ * If a list, then a random value will be sampled from that list
+ per image.
* If a StochasticParameter, a value will be sampled from the
parameter per image.
@@ -360,15 +362,7 @@ def EdgeDetect(alpha=0, name=None, deterministic=False, random_state=None):
in the range 0.0 <= a <= 1.0 over the old image.
"""
- if ia.is_single_number(alpha):
- alpha_param = Deterministic(alpha)
- elif ia.is_iterable(alpha):
- ia.do_assert(len(alpha) == 2, "Expected tuple/list with 2 entries, got %d entries." % (len(alpha),))
- alpha_param = Uniform(alpha[0], alpha[1])
- elif isinstance(alpha, StochasticParameter):
- alpha_param = alpha
- else:
- raise Exception("Expected float, int, tuple/list with 2 entries or StochasticParameter. Got %s." % (type(alpha),))
+ alpha_param = iap.handle_continuous_param(alpha, "alpha", value_range=(0, 1.0), tuple_to_uniform=True, list_to_choice=True)
def create_matrices(image, nb_channels, random_state_func):
alpha_sample = alpha_param.draw_sample(random_state=random_state_func)
|
Reduce code duplication in EdgeDetect
This commit decreases code duplication in the
parameter parsing of
augmenters.convolutional.EdgeDetect by using
the parameter handling functions in
parameters.py.
Additionally, alpha now supports lists, which
are interpreted as Choices.
|
aleju_imgaug
|
train
|
c2748e97dde8e7ac46bf7c77585f6da84eda2ace
|
diff --git a/java-asset/google-cloud-asset/src/test/java/com/google/cloud/asset/v1/MockAssetServiceImpl.java b/java-asset/google-cloud-asset/src/test/java/com/google/cloud/asset/v1/MockAssetServiceImpl.java
index <HASH>..<HASH> 100644
--- a/java-asset/google-cloud-asset/src/test/java/com/google/cloud/asset/v1/MockAssetServiceImpl.java
+++ b/java-asset/google-cloud-asset/src/test/java/com/google/cloud/asset/v1/MockAssetServiceImpl.java
@@ -28,7 +28,7 @@ import java.util.Queue;
@javax.annotation.Generated("by GAPIC")
@BetaApi
public class MockAssetServiceImpl extends AssetServiceImplBase {
- private ArrayList<AbstractMessage> requests;
+ private List<AbstractMessage> requests;
private Queue<Object> responses;
public MockAssetServiceImpl() {
diff --git a/java-asset/google-cloud-asset/src/test/java/com/google/cloud/asset/v1beta1/MockAssetServiceImpl.java b/java-asset/google-cloud-asset/src/test/java/com/google/cloud/asset/v1beta1/MockAssetServiceImpl.java
index <HASH>..<HASH> 100644
--- a/java-asset/google-cloud-asset/src/test/java/com/google/cloud/asset/v1beta1/MockAssetServiceImpl.java
+++ b/java-asset/google-cloud-asset/src/test/java/com/google/cloud/asset/v1beta1/MockAssetServiceImpl.java
@@ -28,7 +28,7 @@ import java.util.Queue;
@javax.annotation.Generated("by GAPIC")
@BetaApi
public class MockAssetServiceImpl extends AssetServiceImplBase {
- private ArrayList<AbstractMessage> requests;
+ private List<AbstractMessage> requests;
private Queue<Object> responses;
public MockAssetServiceImpl() {
diff --git a/java-asset/google-cloud-asset/synth.metadata b/java-asset/google-cloud-asset/synth.metadata
index <HASH>..<HASH> 100644
--- a/java-asset/google-cloud-asset/synth.metadata
+++ b/java-asset/google-cloud-asset/synth.metadata
@@ -1,19 +1,19 @@
{
- "updateTime": "2019-04-01T14:06:38.380692Z",
+ "updateTime": "2019-04-02T07:33:08.616294Z",
"sources": [
{
"generator": {
"name": "artman",
- "version": "0.16.21",
- "dockerImage": "googleapis/artman@sha256:854131ec1af7b3a313253474c24748dc0acd217a58a0b74dbfb559f340a15d78"
+ "version": "0.16.22",
+ "dockerImage": "googleapis/artman@sha256:e7f9554322a8aa1416c122c918fdc4cdec8cfe816f027fc948dec0be7edef320"
}
},
{
"git": {
"name": "googleapis",
"remote": "https://github.com/googleapis/googleapis.git",
- "sha": "396a61102a4ca1e08194a6a52026d2d17834bc66",
- "internalRef": "241317525"
+ "sha": "6c48ab5aef47dc14e02e2dc718d232a28067129d",
+ "internalRef": "241437588"
}
}
],
|
Regenerate asset client (#<I>)
|
googleapis_google-cloud-java
|
train
|
54ef74c269f1705c89def8999043cfd0fbb7c58c
|
diff --git a/app/controllers/google-map/marker.js b/app/controllers/google-map/marker.js
index <HASH>..<HASH> 100644
--- a/app/controllers/google-map/marker.js
+++ b/app/controllers/google-map/marker.js
@@ -9,6 +9,7 @@ var alias = computed.alias;
*/
export default Ember.Controller.extend({
title: alias('model.title'),
+ description: alias('model.description'),
opacity: alias('model.opacity'),
zIndex: alias('model.zIndex'),
isVisible: alias('model.isVisible'),
|
alias marker.description
if a marker with infoWindow was created without a template the description was not displayed
|
huafu_ember-google-map
|
train
|
8181245907bae9cb953bf794e1bcd7e47562555e
|
diff --git a/bin/check-http.rb b/bin/check-http.rb
index <HASH>..<HASH> 100755
--- a/bin/check-http.rb
+++ b/bin/check-http.rb
@@ -93,7 +93,7 @@ class CheckHttp < Sensu::Plugin::Check::CLI
description: 'Specify a uri path'
option :method,
- short: '-m GET|POST',
+ short: '-m GET|HEAD|POST|PUT',
long: '--method GET|HEAD|POST|PUT',
description: 'Specify a GET, HEAD, POST, or PUT operation; defaults to GET',
in: %w[GET HEAD POST PUT],
|
update the short `method` message too (PUT was also missing)
|
sensu-plugins_sensu-plugins-http
|
train
|
04123ecd31c0e5c49bed0a2baf8bee344cc536ba
|
diff --git a/dramatiq/brokers/redis.py b/dramatiq/brokers/redis.py
index <HASH>..<HASH> 100644
--- a/dramatiq/brokers/redis.py
+++ b/dramatiq/brokers/redis.py
@@ -26,7 +26,7 @@ from uuid import uuid4
import redis
from ..broker import Broker, Consumer, MessageProxy
-from ..common import compute_backoff, current_millis, dq_name
+from ..common import compute_backoff, current_millis, dq_name, getenv_int
from ..errors import ConnectionClosed, QueueJoinTimeout
from ..logging import get_logger
from ..message import Message
@@ -46,7 +46,9 @@ DEFAULT_DEAD_MESSAGE_TTL = 86400000 * 7
#: heartbeat for a worker to be considered offline.
DEFAULT_HEARTBEAT_TIMEOUT = 60000
-DEFAULT_LUA_MAX_STACK = getenv("dramatiq_lua_max_stack", None)
+#: A hint for the max lua stack size. The broker discovers this value
+#: the first time it's run, but it may be overwritten using this var.
+DEFAULT_LUA_MAX_STACK = getenv_int("dramatiq_lua_max_stack")
class RedisBroker(Broker):
diff --git a/dramatiq/common.py b/dramatiq/common.py
index <HASH>..<HASH> 100644
--- a/dramatiq/common.py
+++ b/dramatiq/common.py
@@ -14,6 +14,7 @@
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
+from os import getenv
from queue import Empty
from random import uniform
from time import time
@@ -21,6 +22,18 @@ from time import time
from .errors import QueueJoinTimeout
+def getenv_int(name):
+ """Parse an optional environment variable as an integer.
+ """
+ v = getenv(name, None)
+ if v is None:
+ return None
+ try:
+ return int(v)
+ except ValueError:
+ raise ValueError("invalid integer value for env var %r: %r" % (name, v)) from None
+
+
def compute_backoff(attempts, *, factor=5, jitter=True, max_backoff=2000, max_exponent=32):
"""Compute an exponential backoff value based on some number of attempts.
|
broker,redis: parse DEFAULT_LUA_MAX_STACK as int
|
Bogdanp_dramatiq
|
train
|
60858b67c63b8994a7b00b49ef0c181007d24d6d
|
diff --git a/lib/webuser.py b/lib/webuser.py
index <HASH>..<HASH> 100644
--- a/lib/webuser.py
+++ b/lib/webuser.py
@@ -841,8 +841,13 @@ def collect_user_info(req):
try:
if req is None:
uid = -1
- elif type(req) in [type(1), type(1L)]:
+ elif type(req) in (type(1), type(1L)):
+ ## req is infact a user identification
uid = req
+ elif type(req) is dict:
+ ## req is by mistake already a user_info
+ user_info.update(req)
+ return user_info
else:
uid = getUid(req)
user_info['remote_ip'] = gethostbyname(req.connection.remote_ip)
|
collect_user_info allows now a dictionary as input. It will consider it as a
previous call to collect_user_info and will just return. (useful for build
function around collect_user_info that should work with uid, user_info or
req).
|
inveniosoftware_invenio-accounts
|
train
|
f9a2fc253e2f36acbc310dda4185cf1bd21e8619
|
diff --git a/pronto/__init__.py b/pronto/__init__.py
index <HASH>..<HASH> 100644
--- a/pronto/__init__.py
+++ b/pronto/__init__.py
@@ -7,7 +7,7 @@
-__version__='0.1.10'
+__version__='0.1.12'
__author__='Martin Larralde'
__author_email__ = 'martin.larralde@ens-cachan.fr'
diff --git a/pronto/parser/__init__.py b/pronto/parser/__init__.py
index <HASH>..<HASH> 100644
--- a/pronto/parser/__init__.py
+++ b/pronto/parser/__init__.py
@@ -1,3 +1,5 @@
+import warnings
+
import pronto.utils
__all__ = ["Parser", "OboParser", "OwlXMLParser"]
@@ -61,4 +63,9 @@ class Parser(object):
from pronto.parser.obo import OboParser
-from pronto.parser.owl import OwlXMLParser
+
+try:
+ from pronto.parser.owl import OwlXMLParser
+except ImportError:
+ warnings.warn("You don't seem to have lxml installed on your machine, "
+ ".owl parsing will be disabled", pronto.utils.ProntoWarning)
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -2,6 +2,9 @@
# released under the GNU General Public License version 3.0 (GPLv3)
from setuptools import setup, find_packages
+import warnings
+
+warnings.simplefilter("ignore")
import pronto
## SETUPTOOLS VERSION
|
Corrected an lxml import that would make the setup fail when lxml was not found.
|
althonos_pronto
|
train
|
7e886f297614afe876d6b16afdc171f1b81397cc
|
diff --git a/docs/source/conf.py b/docs/source/conf.py
index <HASH>..<HASH> 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -45,10 +45,7 @@ html_extra_path = ['ipyvolume.mp4', 'Big.Buck.Bunny.mp3', 'Big.Buck.Bunny.mp4']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
-source_suffix = ['.rst', '.md']
-source_parsers = {
- '.md': 'recommonmark.parser.CommonMarkParser',
-}
+source_suffix = ['.rst']
# The master toctree document.
master_doc = 'index'
|
DOC: Remove unused CommonMark settings
|
maartenbreddels_ipywebrtc
|
train
|
ce6a049a4b730c8211311e949b5eba9877f00075
|
diff --git a/lib/mini_magick.rb b/lib/mini_magick.rb
index <HASH>..<HASH> 100644
--- a/lib/mini_magick.rb
+++ b/lib/mini_magick.rb
@@ -60,7 +60,7 @@ module MiniMagick
# === Returns
# * [Boolean]
def mogrify?
- processor.to_sym == :mogrify
+ processor && processor.to_sym == :mogrify
end
##
@@ -69,7 +69,7 @@ module MiniMagick
# === Returns
# * [Boolean]
def gm?
- processor.to_sym == :gm
+ processor && processor.to_sym == :gm
end
end
end
|
Fix case when processor is nil
|
minimagick_minimagick
|
train
|
76a9b6da99a3c800720ea4f6e36dcf991211218d
|
diff --git a/src/Propel/Generator/Builder/Om/ObjectBuilder.php b/src/Propel/Generator/Builder/Om/ObjectBuilder.php
index <HASH>..<HASH> 100644
--- a/src/Propel/Generator/Builder/Om/ObjectBuilder.php
+++ b/src/Propel/Generator/Builder/Om/ObjectBuilder.php
@@ -3745,6 +3745,8 @@ abstract class ".$this->getUnqualifiedClassName().$parentClass." implements Acti
$collName = $this->getRefFKCollVarName($refFK);
+ $scheduledForDeletion = lcfirst($this->getRefFKPhpNameAffix($refFK, $plural = true)) . "ScheduledForDeletion";
+
$script .= "
/**
* Method called to associate a $className object to this object
@@ -3762,6 +3764,10 @@ abstract class ".$this->getUnqualifiedClassName().$parentClass." implements Acti
if (!\$this->{$collName}->contains(\$l)) {
\$this->doAdd" . $this->getRefFKPhpNameAffix($refFK, $plural = false) . "(\$l);
+
+ if (\$this->{$scheduledForDeletion} and \$this->{$scheduledForDeletion}->contains(\$l)) {
+ \$this->{$scheduledForDeletion}->remove(\$this->{$scheduledForDeletion}->search(\$l));
+ }
}
return \$this;
diff --git a/tests/Propel/Tests/Generator/Builder/Om/GeneratedObjectRelTest.php b/tests/Propel/Tests/Generator/Builder/Om/GeneratedObjectRelTest.php
index <HASH>..<HASH> 100644
--- a/tests/Propel/Tests/Generator/Builder/Om/GeneratedObjectRelTest.php
+++ b/tests/Propel/Tests/Generator/Builder/Om/GeneratedObjectRelTest.php
@@ -859,6 +859,39 @@ class GeneratedObjectRelTest extends BookstoreEmptyTestBase
$this->assertEquals(1, BookListRelQuery::create()->count(), 'One BookClubList has been remove');
}
+ public function testSymfonyFormManyToOne()
+ {
+ BookQuery::create()->deleteAll();
+ AuthorQuery::create()->deleteAll();
+
+ // We create a simple book and a simple Author and simply link them to each other before reloading them
+ $book = new Book();
+ $book->setISBN('012345');
+ $book->setTitle('Propel Book');
+
+ $author = new Author();
+ $author->setFirstName('François');
+ $author->setLastName('Z');
+ $author->addBook($book);
+ $author->save();
+ $book->save();
+
+ $author->reload(true);
+ $book->reload(true);
+
+ // Symfony is cloning the book object in a ManyToOne form with by_reference = false
+ $book2 = clone $book;
+
+ $author->removeBook($book);
+ $author->addBook($book2);
+ $author->save();
+
+ $author->reload(true);
+
+ $books = $author->getBooks();
+ $this->assertCount(1, $books);
+ }
+
public function testRemoveObjectOneToMany()
{
BookQuery::create()->deleteAll();
|
Fix the child deletion issue in many-to-one form - #<I>
|
propelorm_Propel2
|
train
|
88ba67cf7e3cc67cd0cdebaa8c36c9dba99a2581
|
diff --git a/MAVProxy/modules/mavproxy_param.py b/MAVProxy/modules/mavproxy_param.py
index <HASH>..<HASH> 100644
--- a/MAVProxy/modules/mavproxy_param.py
+++ b/MAVProxy/modules/mavproxy_param.py
@@ -137,6 +137,7 @@ class ParamState:
return
for h in args:
+ h = h.upper()
if h in htree:
help = htree[h]
print("%s: %s\n" % (h, help.get('humanName')))
|
param help: support non-upper case param names
Currently "param help gps_type" will error. This commit fixes that issue
by converting the param name to upper case prior to searching the help
tree.
|
ArduPilot_MAVProxy
|
train
|
b6749a69f498db801e9e12268cfd3a1cd5ebc316
|
diff --git a/src/javascripts/ng-admin/Crud/routing.js b/src/javascripts/ng-admin/Crud/routing.js
index <HASH>..<HASH> 100644
--- a/src/javascripts/ng-admin/Crud/routing.js
+++ b/src/javascripts/ng-admin/Crud/routing.js
@@ -138,12 +138,7 @@ function routing($stateProvider) {
return true;
}],
entries: ['dataStore', 'view', 'response', 'referencedEntries', function (dataStore, view, response, referencedEntries) {
- var entries = dataStore.mapEntries(
- view.entity.name(),
- view.identifier(),
- view.getFields(),
- response.data
- );
+ var entries = view.mapEntries(response.data);
// shortcut to diplay collection of entry with included referenced values
dataStore.fillReferencesValuesFromCollection(entries, view.getReferences(), true);
@@ -182,13 +177,8 @@ function routing($stateProvider) {
rawEntry: ['$stateParams', 'ReadQueries', 'view', function ($stateParams, ReadQueries, view) {
return ReadQueries.getOne(view.getEntity(), view.type, $stateParams.id, view.identifier(), view.getUrl());
}],
- entry: ['dataStore', 'view', 'rawEntry', function(dataStore, view, rawEntry) {
- return dataStore.mapEntry(
- view.entity.name(),
- view.identifier(),
- view.getFields(),
- rawEntry
- );
+ entry: ['view', 'rawEntry', function(view, rawEntry) {
+ return view.mapEntry(rawEntry);
}],
nonOptimizedReferencedData: ['ReadQueries', 'view', 'entry', function (ReadQueries, view, entry) {
return ReadQueries.getFilteredReferenceData(view.getNonOptimizedReferences(), [entry.values]);
@@ -324,13 +314,8 @@ function routing($stateProvider) {
rawEntry: ['$stateParams', 'ReadQueries', 'view', function ($stateParams, ReadQueries, view) {
return ReadQueries.getOne(view.getEntity(), view.type, $stateParams.id, view.identifier(), view.getUrl());
}],
- entry: ['dataStore', 'view', 'rawEntry', function(dataStore, view, rawEntry) {
- return dataStore.mapEntry(
- view.entity.name(),
- view.identifier(),
- view.getFields(),
- rawEntry
- );
+ entry: ['view', 'rawEntry', function(view, rawEntry) {
+ return view.mapEntry(rawEntry);
}],
nonOptimizedReferencedData: ['ReadQueries', 'view', 'entry', function (ReadQueries, view, entry) {
return ReadQueries.getFilteredReferenceData(view.getNonOptimizedReferences(), [entry.values]);
@@ -442,13 +427,8 @@ function routing($stateProvider) {
rawEntry: ['$stateParams', 'ReadQueries', 'view', function ($stateParams, ReadQueries, view) {
return ReadQueries.getOne(view.getEntity(), view.type, $stateParams.id, view.identifier(), view.getUrl());
}],
- entry: ['dataStore', 'view', 'rawEntry', function(dataStore, view, rawEntry) {
- return dataStore.mapEntry(
- view.entity.name(),
- view.identifier(),
- view.getFields(),
- rawEntry
- );
+ entry: ['view', 'rawEntry', function(view, rawEntry) {
+ return view.mapEntry(rawEntry);
}],
}
});
|
Prepare move of mapEntry from datastore to view
|
marmelab_ng-admin
|
train
|
de052fb76f95aefd3661d7101483c73bbb7c5f81
|
diff --git a/src/shared/scripts/Autocomplete.js b/src/shared/scripts/Autocomplete.js
index <HASH>..<HASH> 100644
--- a/src/shared/scripts/Autocomplete.js
+++ b/src/shared/scripts/Autocomplete.js
@@ -337,8 +337,12 @@
// IE8 don't support the input event at all
// IE9 is the only browser that doesn't fire the input event when characters are removed
+ var ua = navigator.userAgent;
+ var MSIE = (/(msie|trident)/i).test(ua) ?
+ ua.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false;
+
if (turn === 'on') {
- if (!ch.util.isMsie() || ch.util.isMsie() > 9) {
+ if (!MSIE || MSIE > 9) {
ch.Event.addListener(this.trigger, ch.onkeyinput, turnOn);
} else {
'keydown cut paste'.split(' ').forEach(function(evtName) {
@@ -347,7 +351,7 @@
}
} else if (turn === 'off') {
this.hide();
- if (!ch.util.isMsie() || ch.util.isMsie() > 9) {
+ if (!MSIE || MSIE > 9) {
ch.Event.removeListener(this.trigger, ch.onkeyinput, turnOn);
} else {
'keydown cut paste'.split(' ').forEach(function(evtName) {
diff --git a/src/shared/scripts/Calendar.js b/src/shared/scripts/Calendar.js
index <HASH>..<HASH> 100644
--- a/src/shared/scripts/Calendar.js
+++ b/src/shared/scripts/Calendar.js
@@ -2,7 +2,7 @@
'use strict';
function normalizeOptions(options) {
- if (typeof options === 'string' || ch.util.isArray(options)) {
+ if (typeof options === 'string' || Array.isArray(options)) {
options = {
'selected': options
};
@@ -271,7 +271,7 @@
if (!selected) { return selected; }
// Simple date selection
- if (!ch.util.isArray(selected)) {
+ if (!Array.isArray(selected)) {
if (selected !== 'today') {
// Return date object and update currentDate
@@ -285,7 +285,7 @@
} else {
selected.forEach(function (e, i){
// Simple date
- if (!ch.util.isArray(e)) {
+ if (!Array.isArray(e)) {
selected[i] = (selected[i] !== 'today') ? createDateObject(e) : that._dates.today;
// Range
} else {
@@ -601,7 +601,7 @@
yepnope = false;
// Simple selection
- if (!ch.util.isArray(this._dates.selected)) {
+ if (!Array.isArray(this._dates.selected)) {
if (year === this._dates.selected.year && month === this._dates.selected.month && day === this._dates.selected.day) {
yepnope = true;
return yepnope;
@@ -611,7 +611,7 @@
} else {
this._dates.selected.forEach(function (e, i) {
// Simple date
- if (!ch.util.isArray(e)) {
+ if (!Array.isArray(e)) {
if (year === e.year && month === e.month && day === e.day) {
yepnope = true;
return yepnope;
diff --git a/src/shared/scripts/util.js b/src/shared/scripts/util.js
index <HASH>..<HASH> 100644
--- a/src/shared/scripts/util.js
+++ b/src/shared/scripts/util.js
@@ -5,43 +5,6 @@
ch.util = {
/**
- * Returns true if an object is an array, false if it is not.
- *
- * @memberof ch.util
- * @method
- * @param {Object} obj The object to be checked.
- * @returns {Boolean}
- * @example
- * ch.util.isArray([1, 2, 3]); // true
- */
- 'isArray': (function () {
- if (typeof Array.isArray === 'function') {
- return Array.isArray;
- }
-
- return function (obj) {
- if (obj === undefined) {
- throw new Error('"ch.util.isArray(obj)": It must receive a parameter.');
- }
-
- return (Object.prototype.toString.call(obj) === '[object Array]');
- };
- }()),
-
- /**
- * Detects an Internet Explorer and returns the version if so.
- *
- * @memberof ch.util
- * @see From <a href="https://github.com/ded/bowser/blob/master/bowser.js">bowser</a>
- * @returns {Boolean|Number}
- */
- 'isMsie': function() {
- var ua = navigator.userAgent;
- return (/(msie|trident)/i).test(ua) ?
- ua.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false;
- },
-
- /**
* Adds CSS rules to disable text selection highlighting.
*
* @memberof ch.util
@@ -369,11 +332,11 @@
}
// Recurse if we're merging plain objects or arrays
- if (deep && copy && (ch.util.isPlainObject(copy) || (copyIsArray = ch.util.isArray(copy)) ) ) {
+ if (deep && copy && (ch.util.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)) ) ) {
if (copyIsArray) {
copyIsArray = false;
- clone = src && ch.util.isArray(src) ? src : [];
+ clone = src && Array.isArray(src) ? src : [];
} else {
clone = src && ch.util.isPlainObject(src) ? src : {};
|
Move IE detection to a component where it is really required
|
mercadolibre_chico
|
train
|
9fa86bf6e5a14eac3681e6c5d4d0fdde81b16541
|
diff --git a/server/bundler/babel/babel-plugin-transform-wpcalypso-async/index.js b/server/bundler/babel/babel-plugin-transform-wpcalypso-async/index.js
index <HASH>..<HASH> 100644
--- a/server/bundler/babel/babel-plugin-transform-wpcalypso-async/index.js
+++ b/server/bundler/babel/babel-plugin-transform-wpcalypso-async/index.js
@@ -71,7 +71,10 @@ module.exports = ( { types: t } ) => {
// In both asynchronous and synchronous case, we'll finish by
// calling require on the loaded module
- let requireCall = t.callExpression( t.identifier( 'require' ), [ argument ] );
+ let requireCall = t.memberExpression(
+ t.callExpression( t.identifier( 'require' ), [ argument ] ),
+ t.identifier( 'default' )
+ );
// If a callback was passed as an argument, wrap it as part of
// the transformation
diff --git a/server/bundler/babel/babel-plugin-transform-wpcalypso-async/test/index.js b/server/bundler/babel/babel-plugin-transform-wpcalypso-async/test/index.js
index <HASH>..<HASH> 100644
--- a/server/bundler/babel/babel-plugin-transform-wpcalypso-async/test/index.js
+++ b/server/bundler/babel/babel-plugin-transform-wpcalypso-async/test/index.js
@@ -36,7 +36,7 @@ describe( 'babel-plugin-transform-wpcalypso-async', () => {
it( 'should replace a require string prop with hoisting', () => {
const code = transform( 'export default () => <AsyncLoad require="foo" />;' );
- expect( code ).to.equal( 'var _ref = function (callback) {\n require.ensure("foo", function (require) {\n callback(require("foo"));\n }, "async-load-foo");\n};\n\nexport default (() => <AsyncLoad require={_ref} />);' );
+ expect( code ).to.equal( 'var _ref = function (callback) {\n require.ensure("foo", function (require) {\n callback(require("foo").default);\n }, "async-load-foo");\n};\n\nexport default (() => <AsyncLoad require={_ref} />);' );
} );
} );
@@ -44,7 +44,7 @@ describe( 'babel-plugin-transform-wpcalypso-async', () => {
it( 'should replace a require string prop with hoisting', () => {
const code = transform( 'export default () => <AsyncLoad require="foo" />;', false );
- expect( code ).to.equal( 'var _ref = function (callback) {\n callback(require("foo"));\n};\n\nexport default (() => <AsyncLoad require={_ref} />);' );
+ expect( code ).to.equal( 'var _ref = function (callback) {\n callback(require("foo").default);\n};\n\nexport default (() => <AsyncLoad require={_ref} />);' );
} );
} );
} );
@@ -66,13 +66,13 @@ describe( 'babel-plugin-transform-wpcalypso-async', () => {
it( 'should call require directly after ensure when no callback', () => {
const code = transform( 'asyncRequire( "foo/bar" );' );
- expect( code ).to.equal( 'require.ensure("foo/bar", function (require) {\n require("foo/bar");\n}, "async-load-foo-bar");' );
+ expect( code ).to.equal( 'require.ensure("foo/bar", function (require) {\n require("foo/bar").default;\n}, "async-load-foo-bar");' );
} );
it( 'should invoke callback with require after ensure', () => {
const code = transform( 'asyncRequire( "foo/bar", cb );' );
- expect( code ).to.equal( 'require.ensure("foo/bar", function (require) {\n cb(require("foo/bar"));\n}, "async-load-foo-bar");' );
+ expect( code ).to.equal( 'require.ensure("foo/bar", function (require) {\n cb(require("foo/bar").default);\n}, "async-load-foo-bar");' );
} );
} );
@@ -80,13 +80,13 @@ describe( 'babel-plugin-transform-wpcalypso-async', () => {
it( 'should call require directly when no callback', () => {
const code = transform( 'asyncRequire( "foo" );', false );
- expect( code ).to.equal( 'require("foo");' );
+ expect( code ).to.equal( 'require("foo").default;' );
} );
it( 'should invoke callback with require', () => {
const code = transform( 'asyncRequire( "foo", cb );', false );
- expect( code ).to.equal( 'cb(require("foo"));' );
+ expect( code ).to.equal( 'cb(require("foo").default);' );
} );
} );
} );
|
Framework: Pass default export in asyncRequire callback
|
Automattic_wp-calypso
|
train
|
95c4b2525e112cb0ef52509e0d3beda8760d9c0b
|
diff --git a/docs/conf.py b/docs/conf.py
index <HASH>..<HASH> 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -57,9 +57,9 @@ author = 'Tim Paine'
# built documents.
#
# The short X.Y version.
-version = 'v0.0.18'
+version = 'v0.0.19'
# The full version, including alpha/beta/rc tags.
-release = 'v0.0.18'
+release = 'v0.0.19'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
diff --git a/jlab/package.json b/jlab/package.json
index <HASH>..<HASH> 100644
--- a/jlab/package.json
+++ b/jlab/package.json
@@ -1,6 +1,6 @@
{
"name": "pylantern",
- "version": "0.0.7",
+ "version": "0.1.0",
"description": "A JupyterLab extension.",
"author": "Tim Paine",
"main": "lib/index.js",
diff --git a/lantern/__init__.py b/lantern/__init__.py
index <HASH>..<HASH> 100644
--- a/lantern/__init__.py
+++ b/lantern/__init__.py
@@ -7,6 +7,7 @@ from .extensions import *
__all__ = ['plot', 'figure', 'grids', 'data', 'extensions']
+__version__ = '0.0.19'
def _jupyter_server_extension_paths():
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -9,11 +9,11 @@ with open(path.join(here, 'README.md'), encoding='utf-8') as f:
setup(
name='pylantern',
- version='0.0.18',
+ version='0.0.19',
description='Analytics library',
long_description=long_description,
url='https://github.com/timkpaine/lantern',
- download_url='https://github.com/timkpaine/lantern/archive/v0.0.18.tar.gz',
+ download_url='https://github.com/timkpaine/lantern/archive/v0.0.19.tar.gz',
author='Tim Paine',
author_email='timothy.k.paine@gmail.com',
license='Apache 2.0',
|
upping version, not compatible with perspective until pull request comes in
|
timkpaine_lantern
|
train
|
92986967b988d89c0ef5d147fc90b1c3cdd6d5c9
|
diff --git a/savannaclient/nova/utils.py b/savannaclient/nova/utils.py
index <HASH>..<HASH> 100644
--- a/savannaclient/nova/utils.py
+++ b/savannaclient/nova/utils.py
@@ -181,9 +181,6 @@ def print_list(objs, fields, formatters={}, sortby_index=None):
else:
result = strutils.safe_encode(pt.get_string())
- if six.PY3:
- result = result.decode()
-
print(result)
|
print_list(): do not call decode() on a text string
In Python3, we already have a text string at this point of the code, so there
is no need to try and decode it.
Change-Id: I<I>d<I>a5a2d8d7e1a<I>e4d<I>e9b<I>ffe<I>
|
openstack_python-saharaclient
|
train
|
5ea4a557011bb7c7c4f582fd8d4cbe18503b374c
|
diff --git a/spdx/creationinfo.py b/spdx/creationinfo.py
index <HASH>..<HASH> 100644
--- a/spdx/creationinfo.py
+++ b/spdx/creationinfo.py
@@ -100,4 +100,21 @@ class CreationInfo(object):
@property
def created_iso_format(self):
- return datetime_iso_format(self.created)
\ No newline at end of file
+ return datetime_iso_format(self.created)
+
+ def validate(self, messages):
+ return self.validate_creators(messages) & self.validate_created(messages)
+
+ def validate_creators(self, messages):
+ if len(self.creators) != 0:
+ return True
+ else:
+ messages.append('No creators defined, must have at least one.')
+ return False
+
+ def validate_created(self, messages):
+ if self.created is not None:
+ return True
+ else:
+ messages.append('Creation info missing created date.')
+ return False
|
Adds validations to CreationInfo model
|
spdx_tools-python
|
train
|
222ad9ea35d21e7d9e70910a89095ac15ac4f28b
|
diff --git a/bfg9000/builtins/install.py b/bfg9000/builtins/install.py
index <HASH>..<HASH> 100644
--- a/bfg9000/builtins/install.py
+++ b/bfg9000/builtins/install.py
@@ -1,5 +1,4 @@
import warnings
-from itertools import chain
from six import itervalues
from . import builtin
@@ -18,33 +17,33 @@ class InstallOutputs(object):
self.explicit = []
self.implicit = []
- def add(self, item, explicit=True):
+ def add(self, item):
+ if item not in self.explicit:
+ self.explicit.append(item)
+
for i in item.all:
- if not isinstance(i, File):
- raise TypeError('expected a file or directory')
- if i.path.root not in (path.Root.srcdir, path.Root.builddir):
- raise ValueError('external files are not installable')
-
- if explicit:
- if i in self.implicit:
- self.implicit.remove(i)
- if i not in self.explicit:
- self.explicit.append(i)
- else:
- if i not in self.explicit and i not in self.implicit:
- self.implicit.append(i)
-
- for j in i.install_deps:
- self.add(j, explicit=False)
+ self._add_implicit(i)
+
+ def _add_implicit(self, item):
+ if not isinstance(item, File):
+ raise TypeError('expected a file or directory')
+ if item.path.root not in (path.Root.srcdir, path.Root.builddir):
+ raise ValueError('external files are not installable')
+
+ if item not in self.implicit:
+ self.implicit.append(item)
+
+ for i in item.install_deps:
+ self._add_implicit(i)
def __nonzero__(self):
return self.__bool__()
def __bool__(self):
- return bool(self.explicit) or bool(self.implicit)
+ return bool(self.implicit)
def __iter__(self):
- return chain(self.explicit, self.implicit)
+ return iter(self.implicit)
def can_install(env):
diff --git a/bfg9000/builtins/pkg_config.py b/bfg9000/builtins/pkg_config.py
index <HASH>..<HASH> 100644
--- a/bfg9000/builtins/pkg_config.py
+++ b/bfg9000/builtins/pkg_config.py
@@ -367,12 +367,12 @@ def finalize_pkg_config(builtins, build, env):
defaults = {
'name': build['project'].name,
'version': build['project'].version or '0.0',
- 'includes': [i for i in install
+
+ # Get all the explicitly-installed headers/libraries.
+ 'includes': [i for i in install.explicit
if isinstance(i, (HeaderFile, HeaderDirectory))],
- # Get all the explicitly-installed libraries, fetching the
- # DualUseLibrary (i.e. the `parent`) if applicable.
- 'libs': uniques(getattr(i, 'parent', i) for i in install.explicit
- if isinstance(i, Library)),
+ 'libs': [i for i in install.explicit
+ if isinstance(i, (Library, DualUseLibrary))],
}
for info in build['pkg_config']:
diff --git a/test/integration/test_pkg_config.py b/test/integration/test_pkg_config.py
index <HASH>..<HASH> 100644
--- a/test/integration/test_pkg_config.py
+++ b/test/integration/test_pkg_config.py
@@ -16,6 +16,14 @@ def pkg_config(args, path='pkgconfig'):
env=env).rstrip()
+def readPcFile(filename, field):
+ with open(filename) as f:
+ for line in f:
+ if line.startswith(field + ':'):
+ return line[len(field) + 1:].strip()
+ raise ValueError('unable to find {!r} field'.format(field))
+
+
@skip_if_backend('msbuild')
@skip_if(is_mingw, 'no libogg on mingw (yet)')
class TestPkgConfig(IntegrationTest):
@@ -43,7 +51,10 @@ class TestPkgConfig(IntegrationTest):
@skip_if(is_msvc, hide=True)
def test_configure_dual(self):
self.configure(extra_args=['--enable-shared', '--enable-static'])
- self.assertExists(os.path.join('pkgconfig', 'hello.pc'))
+
+ hello = os.path.join('pkgconfig', 'hello.pc')
+ self.assertExists(hello)
+ self.assertEqual(readPcFile(hello, 'Libs'), "-L'${libdir}' -lhello")
if env.host_platform.genus == 'linux':
self.assertEqual(pkg_config(['hello', '--print-requires']), '')
@@ -130,7 +141,10 @@ class TestPkgConfigAuto(IntegrationTest):
@skip_if(is_msvc, hide=True)
def test_configure_dual(self):
self.configure(extra_args=['--enable-shared', '--enable-static'])
- self.assertExists(os.path.join('pkgconfig', 'hello.pc'))
+
+ hello = os.path.join('pkgconfig', 'hello.pc')
+ self.assertExists(hello)
+ self.assertEqual(readPcFile(hello, 'Libs'), "-L'${libdir}' -lhello")
self.assertEqual(pkg_config(['hello', '--libs-only-l']), '-lhello')
self.assertEqual(pkg_config(['hello', '--libs-only-l', '--static']),
|
Improve how installed files are recorded
Now, we keep the raw input for tracking explicitly-installed objects. This
makes it easier to track when a DualUseLibrary is set to be installed.
|
jimporter_bfg9000
|
train
|
b0677b19de26ebd6aecf19e7a9c865d401b56aa8
|
diff --git a/bin/ns-status.js b/bin/ns-status.js
index <HASH>..<HASH> 100755
--- a/bin/ns-status.js
+++ b/bin/ns-status.js
@@ -40,11 +40,16 @@ function mmtuneStatus (status) {
function uploaderStatus (status) {
if (uploader_input ) {
- var uploader = require(cwd + '/' + uploader_input);
- if (uploader) {
- status.uploader = {};
- status.uploader.battery = uploader;
- }
+ var uploader = require(cwd + '/' + uploader_input);
+ if (uploader) {
+ if (typeof uploader === 'number') {
+ status.uploader = {
+ battery: uploader
+ };
+ } else {
+ status.uploader = uploader;
+ }
+ }
}
}
|
check type of uploader value, number or object (#<I>)
|
openaps_oref0
|
train
|
3be67e9d6203577e1835d320e56875295fe4ed99
|
diff --git a/ppp_datamodel/nodes/triple.py b/ppp_datamodel/nodes/triple.py
index <HASH>..<HASH> 100644
--- a/ppp_datamodel/nodes/triple.py
+++ b/ppp_datamodel/nodes/triple.py
@@ -18,21 +18,11 @@ class Triple(AbstractNode):
raise TypeError('One of Triple\'s constructor argument '
'is not an AbstractNode instance.')
- def predicate_among(self, L):
- # Be quite permissive about what we accept as L and convert it to
- # a (frozen)set.
- if isinstance(L, AbstractNode):
- L = frozenset({L})
- elif not isinstance(L, (set, frozenset)):
- pass
- elif hasattr(L, '__iter__'):
- L = frozenset(L)
- else:
- raise TypeError('%r is neither an interable or an AbstractNode.' %
- L)
-
- # Check if any of the predicates is in L.
+ @property
+ def predicate_set(self):
+ """Return a frozenset of predicates, extracting it from the list
+ if it is a List node."""
if isinstance(self.predicate, List):
- return not frozenset(self.predicate.list).isdisjoint(L)
+ return frozenset(self.predicate.list)
else:
- return self.predicate in L
+ return frozenset({self.predicate})
diff --git a/tests/test_triple.py b/tests/test_triple.py
index <HASH>..<HASH> 100644
--- a/tests/test_triple.py
+++ b/tests/test_triple.py
@@ -12,20 +12,8 @@ R = Resource
M = Missing
class BaseAbstractNodeTests(TestCase):
- def testPredicateAmong(self):
- self.assertTrue(T(M(), R('foo'), M()).predicate_among(R('foo')))
- self.assertTrue(T(M(), R('bar'), M()).predicate_among([
- R('foo'), R('bar'), R('baz')]))
- self.assertFalse(T(M(), R('qux'), M()).predicate_among([
- R('foo'), R('bar'), R('baz')]))
- self.assertTrue(T(M(), R('bar'), M()).predicate_among({
- R('foo'), R('bar'), R('baz')}))
- self.assertFalse(T(M(), R('qux'), M()).predicate_among({
- R('foo'), R('bar'), R('baz')}))
- self.assertTrue(T(M(), List([R('qux'), R('bar')]), M()) \
- .predicate_among({R('foo'), R('bar'), R('baz')}))
- self.assertFalse(T(M(), List([R('qux'), R('quux')]), M()) \
- .predicate_among({R('foo'), R('bar'), R('baz')}))
- with self.assertRaises(TypeError):
- self.assertFalse(T(M(), R('foo'), M()).predicate_among('foo'))
-
+ def testPredicateSet(self):
+ self.assertEqual(T(M(), R('foo'), M()).predicate_set,
+ {R('foo')})
+ self.assertEqual(T(M(), List([R('foo'), R('bar')]), M()).predicate_set,
+ {R('foo'), R('bar')})
|
Simplify predicate_among by just returning a set.
|
ProjetPP_PPP-datamodel-Python
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.