hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
---|---|---|---|---|
41f56e45b49ec1966a72cba12955bc1185cf7284 | diff --git a/eth_account/_utils/structured_data/validation.py b/eth_account/_utils/structured_data/validation.py
index <HASH>..<HASH> 100644
--- a/eth_account/_utils/structured_data/validation.py
+++ b/eth_account/_utils/structured_data/validation.py
@@ -63,21 +63,30 @@ def validate_field_declared_only_once_in_struct(field_name, struct_data, struct_
)
+EIP712_DOMAIN_FIELDS = [
+ "name",
+ "version",
+ "chainId",
+ "verifyingContract",
+]
+
+
+def used_header_fields(EIP712Domain_data):
+ return [field["name"] for field in EIP712Domain_data if field["name"] in EIP712_DOMAIN_FIELDS]
+
+
def validate_EIP712Domain_schema(structured_data):
# Check that the `types` attribute contains `EIP712Domain` schema declaration
if "EIP712Domain" not in structured_data["types"]:
raise ValidationError("`EIP712Domain struct` not found in types attribute")
# Check that the names and types in `EIP712Domain` are what are mentioned in the EIP-712
- # and they are declared only once
+ # and they are declared only once (if defined at all)
EIP712Domain_data = structured_data["types"]["EIP712Domain"]
- validate_field_declared_only_once_in_struct("name", EIP712Domain_data, "EIP712Domain")
- validate_field_declared_only_once_in_struct("version", EIP712Domain_data, "EIP712Domain")
- validate_field_declared_only_once_in_struct("chainId", EIP712Domain_data, "EIP712Domain")
- validate_field_declared_only_once_in_struct(
- "verifyingContract",
- EIP712Domain_data,
- "EIP712Domain",
- )
+ header_fields = used_header_fields(EIP712Domain_data)
+ if len(header_fields) == 0:
+ raise ValidationError(f"One of {EIP712_DOMAIN_FIELDS} must be defined in {structured_data}")
+ for field in header_fields:
+ validate_field_declared_only_once_in_struct(field, EIP712Domain_data, "EIP712Domain")
def validate_primaryType_attribute(structured_data): | fix: only one of the domain fields needs to be included, not all | ethereum_eth-account | train |
d42ad81791bfee4e310501788bce940c093cfd63 | diff --git a/src/scanner/index.js b/src/scanner/index.js
index <HASH>..<HASH> 100644
--- a/src/scanner/index.js
+++ b/src/scanner/index.js
@@ -102,7 +102,17 @@ class Scanner {
// Multi-character tokens
default:
- const IDENTIFIERS = /[_a-z]/i
+ const NUMBERS = /[0-9]/
+ if (NUMBERS.test(current)) {
+ let number = current
+ while (NUMBERS.test(this.peek())) {
+ number += this.consume()
+ }
+ this.emitToken('NUMBER', number)
+ break
+ }
+
+ const IDENTIFIERS = /[_a-z0-9]/i
if (IDENTIFIERS.test(current)) {
let identifier = current
while (IDENTIFIERS.test(this.peek())) {
@@ -117,16 +127,6 @@ class Scanner {
break
}
- const NUMBERS = /[0-9]/
- if (NUMBERS.test(current)) {
- let number = current
- while (NUMBERS.test(this.peek())) {
- number += this.consume()
- }
- this.emitToken('NUMBER', number)
- break
- }
-
this.report(`Unexpected character "${current}"`)
}
} | Allow numbers in identifiers (except for the beginning) | aragon_radspec | train |
7a3e36c1af0903c72f491fcbbe609d827c70ae97 | diff --git a/src/utils/gulp/gulp-tasks-dev.js b/src/utils/gulp/gulp-tasks-dev.js
index <HASH>..<HASH> 100644
--- a/src/utils/gulp/gulp-tasks-dev.js
+++ b/src/utils/gulp/gulp-tasks-dev.js
@@ -77,7 +77,7 @@ module.exports = function(gulp, options, webpackConfig, dist) {
var devServerConfig = {
contentBase: dist,
- hot: true,
+ hot: options.devServerDisableHot ? false : true,
inline: true,
stats: {
colors: true
@@ -139,5 +139,17 @@ module.exports = function(gulp, options, webpackConfig, dist) {
}
});
+ server.app.get('/reload', function(req, res) {
+ // Tell connected browsers to reload.
+ server.io.sockets.emit('ok');
+ res.sendStatus(200);
+ });
+
+ server.app.get('/invalid', function(req, res) {
+ // Tell connected browsers to reload.
+ server.io.sockets.emit('invalid');
+ res.sendStatus(200);
+ });
+
});
}; | Added feature to invoke dev server reloads manually | grommet_grommet | train |
cd3fa2a7be080ef1cc4abed2073b4521b3622d12 | diff --git a/tests/testrunner_test.py b/tests/testrunner_test.py
index <HASH>..<HASH> 100644
--- a/tests/testrunner_test.py
+++ b/tests/testrunner_test.py
@@ -9,11 +9,14 @@ import os.path as op
from mock import Mock
from purkinje_pytest import testrunner as sut
-obs_mock = Mock()
+
[email protected]
+def obs_mock():
+ return Mock()
@pytest.fixture
-def testrunner(tmpdir, monkeypatch):
+def testrunner(tmpdir, monkeypatch, obs_mock):
monkeypatch.setattr(sut, 'Observer', Mock(return_value=obs_mock))
return sut.TestRunner(str(tmpdir))
@@ -39,9 +42,22 @@ def test_get_max_user_watches(testrunner):
def test_start(testrunner):
- assert not obs_mock.schedule.called
+ assert not testrunner.observer.schedule.called
testrunner.start(single_run=True)
- assert obs_mock.schedule.called
+ assert testrunner.observer.schedule.called
+
+
+def test_start_keyboard_interrupted(testrunner, monkeypatch):
+ assert not testrunner.observer.schedule.called
+
+ def keyboard_interrupt(_):
+ raise KeyboardInterrupt('Dummy keyboard interrupt')
+
+ monkeypatch.setattr(
+ sut.time, 'sleep', Mock(side_effect=keyboard_interrupt))
+ testrunner.start(single_run=False)
+ assert testrunner.observer.schedule.called
+ assert testrunner.observer.stop.called
def test_main(monkeypatch): | new test case: keyboard interruption of test runner | bbiskup_pytest-purkinje | train |
d0d8ccb86e7fe64613641c4648d75de3dd0a09f7 | diff --git a/achilles-core/src/main/java/info/archinnov/achilles/internal/statement/wrapper/AbstractStatementWrapper.java b/achilles-core/src/main/java/info/archinnov/achilles/internal/statement/wrapper/AbstractStatementWrapper.java
index <HASH>..<HASH> 100644
--- a/achilles-core/src/main/java/info/archinnov/achilles/internal/statement/wrapper/AbstractStatementWrapper.java
+++ b/achilles-core/src/main/java/info/archinnov/achilles/internal/statement/wrapper/AbstractStatementWrapper.java
@@ -38,6 +38,7 @@ import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.Statement;
+import com.datastax.driver.core.exceptions.TraceRetrievalException;
import com.google.common.base.Optional;
import info.archinnov.achilles.exception.AchillesCASException;
import info.archinnov.achilles.internal.reflection.RowMethodInvoker;
@@ -187,11 +188,15 @@ public abstract class AbstractStatementWrapper {
actualLogger.trace("Query tracing at host {} with achieved consistency level {} ", executionInfo.getQueriedHost(), executionInfo.getAchievedConsistencyLevel());
actualLogger.trace("****************************");
actualLogger.trace(String.format("%1$-80s | %2$-16s | %3$-24s | %4$-20s", "Description", "Source", "Source elapsed in micros", "Thread name"));
- final List<QueryTrace.Event> events = new ArrayList<>(executionInfo.getQueryTrace().getEvents());
- Collections.sort(events, EVENT_TRACE_COMPARATOR);
- for (QueryTrace.Event event : events) {
- final String formatted = String.format("%1$-80s | %2$-16s | %3$-24s | %4$-20s", event.getDescription(), event.getSource(), event.getSourceElapsedMicros(), event.getThreadName());
- actualLogger.trace(formatted);
+ try {
+ final List<QueryTrace.Event> events = new ArrayList<>(executionInfo.getQueryTrace().getEvents());
+ Collections.sort(events, EVENT_TRACE_COMPARATOR);
+ for (QueryTrace.Event event : events) {
+ final String formatted = String.format("%1$-80s | %2$-16s | %3$-24s | %4$-20s", event.getDescription(), event.getSource(), event.getSourceElapsedMicros(), event.getThreadName());
+ actualLogger.trace(formatted);
+ }
+ } catch (TraceRetrievalException e) {
+ actualLogger.trace("Cannot retrieve asynchronous trace, reason: " + e.getMessage());
}
actualLogger.trace("****************************");
} | Make test more resilient by catching TraceRetrievalException | doanduyhai_Achilles | train |
331113ca173cc8baf3de4b2e71e00150b3bb4d64 | diff --git a/target/js/browser.maker.js b/target/js/browser.maker.js
index <HASH>..<HASH> 100644
--- a/target/js/browser.maker.js
+++ b/target/js/browser.maker.js
@@ -2686,6 +2686,7 @@ var MakerJs;
* Measures the smallest rectangle which contains a model.
*
* @param modelToMeasure The model to measure.
+ * @param atlas Optional atlas to save measurements.
* @returns object with low and high points.
*/
function modelExtents(modelToMeasure, atlas) {
@@ -2719,11 +2720,31 @@ var MakerJs;
return atlas.modelMap[''];
}
measure.modelExtents = modelExtents;
+ /**
+ * A list of maps of measurements.
+ *
+ * @param modelToMeasure The model to measure.
+ * @param atlas Optional atlas to save measurements.
+ * @returns object with low and high points.
+ */
var Atlas = (function () {
+ /**
+ * Constructor.
+ * @param modelContext The model to measure.
+ */
function Atlas(modelContext) {
this.modelContext = modelContext;
+ /**
+ * Flag that models have been measured.
+ */
this.modelsMeasured = false;
+ /**
+ * Map of model measurements, mapped by routeKey.
+ */
this.modelMap = {};
+ /**
+ * Map of path measurements, mapped by routeKey.
+ */
this.pathMap = {};
}
Atlas.prototype.measureModels = function () {
diff --git a/target/js/node.maker.js b/target/js/node.maker.js
index <HASH>..<HASH> 100644
--- a/target/js/node.maker.js
+++ b/target/js/node.maker.js
@@ -2519,6 +2519,7 @@ var MakerJs;
* Measures the smallest rectangle which contains a model.
*
* @param modelToMeasure The model to measure.
+ * @param atlas Optional atlas to save measurements.
* @returns object with low and high points.
*/
function modelExtents(modelToMeasure, atlas) {
@@ -2552,11 +2553,31 @@ var MakerJs;
return atlas.modelMap[''];
}
measure.modelExtents = modelExtents;
+ /**
+ * A list of maps of measurements.
+ *
+ * @param modelToMeasure The model to measure.
+ * @param atlas Optional atlas to save measurements.
+ * @returns object with low and high points.
+ */
var Atlas = (function () {
+ /**
+ * Constructor.
+ * @param modelContext The model to measure.
+ */
function Atlas(modelContext) {
this.modelContext = modelContext;
+ /**
+ * Flag that models have been measured.
+ */
this.modelsMeasured = false;
+ /**
+ * Map of model measurements, mapped by routeKey.
+ */
this.modelMap = {};
+ /**
+ * Map of path measurements, mapped by routeKey.
+ */
this.pathMap = {};
}
Atlas.prototype.measureModels = function () {
diff --git a/target/ts/makerjs.d.ts b/target/ts/makerjs.d.ts
index <HASH>..<HASH> 100644
--- a/target/ts/makerjs.d.ts
+++ b/target/ts/makerjs.d.ts
@@ -1280,14 +1280,35 @@ declare namespace MakerJs.measure {
* Measures the smallest rectangle which contains a model.
*
* @param modelToMeasure The model to measure.
+ * @param atlas Optional atlas to save measurements.
* @returns object with low and high points.
*/
function modelExtents(modelToMeasure: IModel, atlas?: measure.Atlas): IMeasure;
+ /**
+ * A list of maps of measurements.
+ *
+ * @param modelToMeasure The model to measure.
+ * @param atlas Optional atlas to save measurements.
+ * @returns object with low and high points.
+ */
class Atlas {
modelContext: IModel;
+ /**
+ * Flag that models have been measured.
+ */
modelsMeasured: boolean;
+ /**
+ * Map of model measurements, mapped by routeKey.
+ */
modelMap: IMeasureMap;
+ /**
+ * Map of path measurements, mapped by routeKey.
+ */
pathMap: IMeasureMap;
+ /**
+ * Constructor.
+ * @param modelContext The model to measure.
+ */
constructor(modelContext: IModel);
measureModels(): void;
} | add comments for measure.Atlas | Microsoft_maker.js | train |
5f1792ef069e56e9b19d6e6a49b8d072f15d8724 | diff --git a/spyder/plugins/findinfiles/widgets.py b/spyder/plugins/findinfiles/widgets.py
index <HASH>..<HASH> 100644
--- a/spyder/plugins/findinfiles/widgets.py
+++ b/spyder/plugins/findinfiles/widgets.py
@@ -677,16 +677,26 @@ class LineMatchItem(QTreeWidgetItem):
class FileMatchItem(QTreeWidgetItem):
- def __init__(self, parent, filename, sorting, text_color):
+ def __init__(self, parent, path, filename, sorting, text_color):
self.sorting = sorting
self.filename = osp.basename(filename)
+ # Get relative dirname according to the path we're searching in.
+ dirname = osp.dirname(filename)
+ rel_dirname = dirname.split(path)[1]
+ if rel_dirname.startswith(osp.sep):
+ rel_dirname = rel_dirname[1:]
+
+ # Use a dimmer color for directories
+ dir_color_name = QStylePalette.COLOR_TEXT_2
+
title = (
f'<!-- FileMatchItem -->'
f'<b style="color:{text_color}">{osp.basename(filename)}</b>'
f' '
- f'<span style="color:{text_color}"><em>{osp.dirname(filename)}</em>'
+ f'<span style="color:{dir_color_name}">'
+ f'<em>{rel_dirname}</em>'
f'</span>'
)
@@ -769,6 +779,7 @@ class ResultsBrowser(OneColumnTree):
self.files = None
self.root_items = None
self.text_color = text_color
+ self.path = None
# Setup
self.set_title('')
@@ -823,8 +834,8 @@ class ResultsBrowser(OneColumnTree):
def append_file_result(self, filename):
"""Real-time update of file items."""
if len(self.data) < self.max_results:
- self.files[filename] = FileMatchItem(
- self, filename, self.sorting, self.text_color)
+ self.files[filename] = FileMatchItem(self, self.path, filename,
+ self.sorting, self.text_color)
self.files[filename].setExpanded(True)
self.num_files += 1
@@ -856,6 +867,10 @@ class ResultsBrowser(OneColumnTree):
"""Set maximum amount of results to add."""
self.max_results = value
+ def set_path(self, path):
+ """Set path where the search is performed."""
+ self.path = path
+
class FindInFilesWidget(PluginMainWidget):
"""
@@ -1343,6 +1358,9 @@ class FindInFilesWidget(PluginMainWidget):
# Update and set options
self._update_options()
+ # Set path in result_browser
+ self.result_browser.set_path(options[0])
+
# Start
self.running = True
self.start_spinner() | Find: Show directory name relative to the path we're searching in
Also use a dimmer color for it. | spyder-ide_spyder | train |
1c57a33a73689c4cf2b8d506cf3466f1df4c1cd1 | diff --git a/hazelcast/src/main/java/com/hazelcast/spi/impl/BinaryOperationFactory.java b/hazelcast/src/main/java/com/hazelcast/spi/impl/BinaryOperationFactory.java
index <HASH>..<HASH> 100644
--- a/hazelcast/src/main/java/com/hazelcast/spi/impl/BinaryOperationFactory.java
+++ b/hazelcast/src/main/java/com/hazelcast/spi/impl/BinaryOperationFactory.java
@@ -28,6 +28,10 @@ import com.hazelcast.spi.OperationFactory;
import java.io.IOException;
+/**
+ * An {@link OperationFactory} that creates operations by cloning
+ * the passed Operation.
+ */
public final class BinaryOperationFactory implements OperationFactory, NodeAware, IdentifiedDataSerializable {
private Data operationData; | Added javadoc to BinaryOperationFactory | hazelcast_hazelcast | train |
4dff2004308a7a1e5b9afc7a5b3b9cb515e12514 | diff --git a/git/index/base.py b/git/index/base.py
index <HASH>..<HASH> 100644
--- a/git/index/base.py
+++ b/git/index/base.py
@@ -490,8 +490,8 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable):
return path_map
@classmethod
- def entry_key(cls, entry: Union[Tuple[BaseIndexEntry], Tuple[PathLike, StageType]]) -> Tuple[PathLike, StageType]:
- return entry_key(entry)
+ def entry_key(cls, *entry: Union[Tuple[BaseIndexEntry], Tuple[PathLike, StageType]]) -> Tuple[PathLike, StageType]:
+ return entry_key(*entry)
def resolve_blobs(self, iter_blobs: Iterator[Blob]) -> 'IndexFile':
"""Resolve the blobs given in blob iterator. This will effectively remove the
diff --git a/git/index/fun.py b/git/index/fun.py
index <HASH>..<HASH> 100644
--- a/git/index/fun.py
+++ b/git/index/fun.py
@@ -1,7 +1,7 @@
# Contains standalone functions to accompany the index implementation and make it
# more versatile
# NOTE: Autodoc hates it if this is a docstring
-from git.types import PathLike, TBD
+from git.types import PathLike
from io import BytesIO
import os
from stat import (
@@ -168,13 +168,13 @@ def read_header(stream):
return version, num_entries
-def entry_key(entry: Union[Tuple[BaseIndexEntry], Tuple[PathLike, TBD]]):
+def entry_key(*entry: Union[Tuple[BaseIndexEntry], Tuple[PathLike, int]]):
""":return: Key suitable to be used for the index.entries dictionary
:param entry: One instance of type BaseIndexEntry or the path and the stage"""
- if len(entry) == 1:
+ if len(*entry) == 1:
entry_first = cast(BaseIndexEntry, entry[0]) # type: BaseIndexEntry
return (entry_first.path, entry_first.stage)
- return tuple(entry)
+ return tuple(*entry)
# END handle entry | Add initial types to IndexFile .init() to _to_relative_path() | gitpython-developers_GitPython | train |
12b304d981b840d054c64341591de2571fe7734d | diff --git a/middleware/file/xfr.go b/middleware/file/xfr.go
index <HASH>..<HASH> 100644
--- a/middleware/file/xfr.go
+++ b/middleware/file/xfr.go
@@ -16,13 +16,13 @@ type (
}
)
-// Serve an AXFR (or maybe later an IXFR) as well.
+// Serve an AXFR (and fallback of IXFR) as well.
func (x Xfr) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
state := middleware.State{W: w, Req: r}
if !x.TransferAllowed(state) {
return dns.RcodeServerFailure, nil
}
- if state.QType() != dns.TypeAXFR {
+ if state.QType() != dns.TypeAXFR && state.QType() != dns.TypeIXFR {
return 0, fmt.Errorf("xfr called with non transfer type: %d", state.QType())
} | Allow IXFR as well (#<I>) | coredns_coredns | train |
3bfc46db9d8e61ea98fc27e38d86988469913cda | diff --git a/library/src/com/nostra13/universalimageloader/core/LoadAndDisplayImageTask.java b/library/src/com/nostra13/universalimageloader/core/LoadAndDisplayImageTask.java
index <HASH>..<HASH> 100644
--- a/library/src/com/nostra13/universalimageloader/core/LoadAndDisplayImageTask.java
+++ b/library/src/com/nostra13/universalimageloader/core/LoadAndDisplayImageTask.java
@@ -74,7 +74,7 @@ final class LoadAndDisplayImageTask implements Runnable {
private static final String ERROR_POST_PROCESSOR_NULL = "Pre-processor returned null [%s]";
private static final String ERROR_PROCESSOR_FOR_DISC_CACHE_NULL = "Bitmap processor for disc cache returned null [%s]";
- private static final int BUFFER_SIZE = 8 * 1024; // 8 Kb
+ private static final int BUFFER_SIZE = 32 * 1024; // 32 Kb
private final ImageLoaderEngine engine;
private final ImageLoadingInfo imageLoadingInfo;
diff --git a/library/src/com/nostra13/universalimageloader/core/download/BaseImageDownloader.java b/library/src/com/nostra13/universalimageloader/core/download/BaseImageDownloader.java
index <HASH>..<HASH> 100644
--- a/library/src/com/nostra13/universalimageloader/core/download/BaseImageDownloader.java
+++ b/library/src/com/nostra13/universalimageloader/core/download/BaseImageDownloader.java
@@ -51,7 +51,7 @@ public class BaseImageDownloader implements ImageDownloader {
public static final int DEFAULT_HTTP_READ_TIMEOUT = 20 * 1000; // milliseconds
/** {@value} */
- protected static final int BUFFER_SIZE = 8 * 1024; // 8 Kb
+ protected static final int BUFFER_SIZE = 32 * 1024; // 32 Kb
/** {@value} */
protected static final String ALLOWED_URI_CHARS = "@#&=*+-_.,:!?()/~'%";
diff --git a/library/src/com/nostra13/universalimageloader/utils/IoUtils.java b/library/src/com/nostra13/universalimageloader/utils/IoUtils.java
index <HASH>..<HASH> 100644
--- a/library/src/com/nostra13/universalimageloader/utils/IoUtils.java
+++ b/library/src/com/nostra13/universalimageloader/utils/IoUtils.java
@@ -28,7 +28,7 @@ import java.io.OutputStream;
*/
public final class IoUtils {
- private static final int BUFFER_SIZE = 8 * 1024; // 8 KB
+ private static final int BUFFER_SIZE = 32 * 1024; // 32 KB
private IoUtils() {
} | Issue #<I> : Buffer size 8K -> <I>K | nostra13_Android-Universal-Image-Loader | train |
11fd5c4215bd4dbd8d25d5f29e845f0cbf692bd7 | diff --git a/lib/materialize-sass.rb b/lib/materialize-sass.rb
index <HASH>..<HASH> 100644
--- a/lib/materialize-sass.rb
+++ b/lib/materialize-sass.rb
@@ -3,6 +3,13 @@ require "materialize-sass/version"
module Materialize
module Sass
class Engine < ::Rails::Engine
+ initializer 'bootstrap-sass.assets.precompile' do |app|
+ %w(stylesheets javascripts fonts images).each do |sub|
+ app.config.assets.paths << root.join('assets', sub).to_s
+ end
+ app.config.assets.precompile << %r(material-design-icons/Material-Design-Icons\.(?:eot|svg|ttf|woff2?)$)
+ app.config.assets.precompile << %r(roboto/Roboto-Bold\.(?:eot|svg|ttf|woff2?)$)
+ end
end
end
end | Add assets folder to sprockets assets path | mkhairi_materialize-sass | train |
9468022c3fa317ffdb503abd9418edd82ebd9b52 | diff --git a/ember_debug/adapters/web-extension.js b/ember_debug/adapters/web-extension.js
index <HASH>..<HASH> 100644
--- a/ember_debug/adapters/web-extension.js
+++ b/ember_debug/adapters/web-extension.js
@@ -1,4 +1,5 @@
-import BasicAdapter from "./basic";
+import BasicAdapter from './basic';
+
const Ember = window.Ember;
const { run, typeOf } = Ember;
const { isArray } = Array;
@@ -6,9 +7,10 @@ const { keys } = Object;
export default BasicAdapter.extend({
init() {
- this._super(...arguments);
this.set('_channel', new MessageChannel());
this.set('_chromePort', this.get('_channel.port1'));
+
+ this._super(...arguments);
},
connect() { | Fix setting _channel by moving before super call (#<I>) | emberjs_ember-inspector | train |
cf30fafb55a930dfd8927e35043dc9f8ead0b7eb | diff --git a/spring-boot-starter-data-jpa-eclipselink/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/EclipselinkJpaAutoconfiguration.java b/spring-boot-starter-data-jpa-eclipselink/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/EclipselinkJpaAutoconfiguration.java
index <HASH>..<HASH> 100644
--- a/spring-boot-starter-data-jpa-eclipselink/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/EclipselinkJpaAutoconfiguration.java
+++ b/spring-boot-starter-data-jpa-eclipselink/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/EclipselinkJpaAutoconfiguration.java
@@ -102,7 +102,7 @@ public class EclipselinkJpaAutoconfiguration extends JpaBaseConfiguration {
}
}
- return ConditionOutcome.match("did not find EclipselinkEntityManager class");
+ return ConditionOutcome.noMatch("did not find EclipselinkEntityManager class");
}
} | fix condition to 'noMatch' if no EclipselinkEntityManager was found | zalando-stups_booties | train |
600ace2ca9a518964246258c78ea2f7de6689585 | diff --git a/devices.js b/devices.js
index <HASH>..<HASH> 100755
--- a/devices.js
+++ b/devices.js
@@ -13144,6 +13144,24 @@ const devices = [
exposes: [e.cover_position(), e.battery()],
},
+ // Yookee
+ {
+ zigbeeModel: ['D10110'],
+ model: 'D10110',
+ vendor: 'Yookee',
+ description: 'Smart blind controller',
+ fromZigbee: [fz.cover_position_tilt, fz.battery],
+ toZigbee: [tz.cover_state, tz.cover_position_tilt],
+ meta: {configureKey: 1},
+ configure: async (device, coordinatorEndpoint, logger) => {
+ const endpoint = device.getEndpoint(1);
+ await reporting.bind(endpoint, coordinatorEndpoint, ['genPowerCfg', 'closuresWindowCovering']);
+ await reporting.batteryPercentageRemaining(endpoint);
+ await reporting.currentPositionLiftPercentage(endpoint);
+ },
+ exposes: [e.cover_position(), e.battery()],
+ },
+
// SONOFF
{
zigbeeModel: ['BASICZBR3'], | Add support for yookee cover (#<I>) | Koenkk_zigbee-shepherd-converters | train |
9ab694a38f8c024da2a5121da2e4eeca43e05d28 | diff --git a/genericm2m/genericm2m_tests/models.py b/genericm2m/genericm2m_tests/models.py
index <HASH>..<HASH> 100644
--- a/genericm2m/genericm2m_tests/models.py
+++ b/genericm2m/genericm2m_tests/models.py
@@ -1,4 +1,7 @@
-from django.contrib.contenttypes.generic import GenericForeignKey
+try:
+ from django.contrib.contenttypes.fields import GenericForeignKey
+except ImportError:
+ from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
diff --git a/genericm2m/models.py b/genericm2m/models.py
index <HASH>..<HASH> 100644
--- a/genericm2m/models.py
+++ b/genericm2m/models.py
@@ -1,5 +1,8 @@
# -*- coding: utf-8 -*-
-from django.contrib.contenttypes.generic import GenericForeignKey
+try:
+ from django.contrib.contenttypes.fields import GenericForeignKey
+except ImportError:
+ from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models import Q | Moved import of `GenericForeignKey`
> RemovedInDjango<I>Warning: django.contrib.contenttypes.generic is deprecated and will be removed in Django <I>.
> Its contents have been moved to the fields, forms, and admin submodules of django.contrib.contenttypes. | coleifer_django-generic-m2m | train |
cfcf3b2bbfd95a447beff23b282e893e2abdf0c4 | diff --git a/cordova-lib/src/cordova/metadata/ios_parser.js b/cordova-lib/src/cordova/metadata/ios_parser.js
index <HASH>..<HASH> 100644
--- a/cordova-lib/src/cordova/metadata/ios_parser.js
+++ b/cordova-lib/src/cordova/metadata/ios_parser.js
@@ -122,7 +122,10 @@ module.exports.prototype = {
{dest: 'Resources/splash/Default-Portrait@2x~ipad.png', width: 1536, height: 2048},
{dest: 'Resources/splash/Default-Landscape~ipad.png', width: 1024, height: 768},
{dest: 'Resources/splash/Default-Landscape@2x~ipad.png', width: 2048, height: 1536},
- {dest: 'Resources/splash/Default-568h@2x~iphone.png', width: 640, height: 1136}
+ {dest: 'Resources/splash/Default-568h@2x~iphone.png', width: 640, height: 1136},
+ {dest: 'Resources/splash/Default-667h.png', width: 750, height: 1334},
+ {dest: 'Resources/splash/Default-736h.png', width: 1242, height: 2208},
+ {dest: 'Resources/splash/Default-Landscape-736h.png', width: 2208, height: 1242}
];
platformSplashScreens.forEach(function(item) { | CB-<I> - [iOS 8] Support new iPhone 6 and 6 Plus Images in the CLI config.xml (closes #<I>) | apache_cordova-lib | train |
ab436a4a2f6a55c944e3f389a83625e780586f1d | diff --git a/spec/Fixture/Jit/Patcher/Monkey/Class.php b/spec/Fixture/Jit/Patcher/Monkey/Class.php
index <HASH>..<HASH> 100644
--- a/spec/Fixture/Jit/Patcher/Monkey/Class.php
+++ b/spec/Fixture/Jit/Patcher/Monkey/Class.php
@@ -150,7 +150,7 @@ class Example extends \Kahlan\Fixture\Parent
return $this->dialect()->quote((string) json_encode($value));
}
]
- ]);
+ ]));
}
public function noIndent()
@@ -278,6 +278,15 @@ rand();
WHILE(FALSE){};
TRUE XOR(TRUE);
}
+
+ public function ignoreBackslashedControlStructure()
+ {
+ \compact();
+ \extract();
+ \func_get_arg();
+ \func_get_args();
+ \func_num_args();
+ }
}
Exemple::reset();
diff --git a/spec/Fixture/Jit/Patcher/Monkey/ClassProcessed.php b/spec/Fixture/Jit/Patcher/Monkey/ClassProcessed.php
index <HASH>..<HASH> 100644
--- a/spec/Fixture/Jit/Patcher/Monkey/ClassProcessed.php
+++ b/spec/Fixture/Jit/Patcher/Monkey/ClassProcessed.php
@@ -150,7 +150,7 @@ class Example extends \Kahlan\Fixture\Parent
return $this->dialect()->quote((string) $__KMONKEY__20($value));
}
]
- ]));
+ ])));
}
public function noIndent()
@@ -278,6 +278,15 @@ $__KMONKEY__21();
WHILE(FALSE){};
TRUE XOR(TRUE);
}
+
+ public function ignoreBackslashedControlStructure()
+ {
+ \compact();
+ \extract();
+ \func_get_arg();
+ \func_get_args();
+ \func_num_args();
+ }
}($__KMONKEY__28__?$__KMONKEY__28__:
$__KMONKEY__28::reset());
diff --git a/spec/Fixture/Jit/Patcher/Monkey/ClassProcessedLegacy.php b/spec/Fixture/Jit/Patcher/Monkey/ClassProcessedLegacy.php
index <HASH>..<HASH> 100644
--- a/spec/Fixture/Jit/Patcher/Monkey/ClassProcessedLegacy.php
+++ b/spec/Fixture/Jit/Patcher/Monkey/ClassProcessedLegacy.php
@@ -150,7 +150,7 @@ class Example extends \Kahlan\Fixture\Parent
return $this->dialect()->quote((string) $__KMONKEY__20($value));
}
]
- ]);
+ ]));
}
public function noIndent()
@@ -278,6 +278,15 @@ $__KMONKEY__21();
WHILE(FALSE){};
TRUE XOR(TRUE);
}
+
+ public function ignoreBackslashedControlStructure()
+ {
+ \compact();
+ \extract();
+ \func_get_arg();
+ \func_get_args();
+ \func_num_args();
+ }
}
$__KMONKEY__28::reset();
diff --git a/src/Jit/Patcher/Monkey.php b/src/Jit/Patcher/Monkey.php
index <HASH>..<HASH> 100644
--- a/src/Jit/Patcher/Monkey.php
+++ b/src/Jit/Patcher/Monkey.php
@@ -238,7 +238,7 @@ class Monkey
$isClass = $isStaticCall || $isInstance;
$method = $match[4][0] ? $match[4][0] : 'null';
- if (!isset(static::$_blacklist[strtolower($name)]) && ($isClass || $nextChar === '(')) {
+ if (!isset(static::$_blacklist[ltrim(strtolower($name), '\\')]) && ($isClass || $nextChar === '(')) {
$tokens = explode('\\', $name, 2);
if ($name[0] === '\\') { | Also ignore backslashed introspection functions. | kahlan_kahlan | train |
c3badb14c2caf45472af2d253dbf9f0df41441ce | diff --git a/spillway/filters.py b/spillway/filters.py
index <HASH>..<HASH> 100644
--- a/spillway/filters.py
+++ b/spillway/filters.py
@@ -7,9 +7,7 @@ class GeoQuerySetFilter(BaseFilterBackend):
precision = 4
def filter_queryset(self, request, queryset, view):
- #params = view.form.cleaned_data
- form = view.get_query_form()
- params = form.cleaned_data if form.is_valid() else {}
+ params = view.clean_params()
tolerance, srs = map(params.get, ('simplify', 'srs'))
srid = getattr(srs, 'srid', None)
kwargs = {}
diff --git a/spillway/mixins.py b/spillway/mixins.py
index <HASH>..<HASH> 100644
--- a/spillway/mixins.py
+++ b/spillway/mixins.py
@@ -7,3 +7,7 @@ class QueryFormMixin(object):
return self.query_form_class(
self.request.QUERY_PARAMS or self.request.DATA,
self.request.FILES or None)
+
+ def clean_params(self):
+ form = self.get_query_form()
+ return form.cleaned_data if form.is_valid() else {}
diff --git a/spillway/renderers.py b/spillway/renderers.py
index <HASH>..<HASH> 100644
--- a/spillway/renderers.py
+++ b/spillway/renderers.py
@@ -107,18 +107,10 @@ class BaseGDALRenderer(BaseRenderer):
fname = os.path.basename(item['path'])
return os.path.splitext(fname)[0] + self.file_ext
- def get_context(self, renderer_context):
- view = renderer_context.get('view')
- try:
- form = view.get_query_form()
- except AttributeError:
- return {}
- return form.cleaned_data if form.is_valid() else {}
-
def render(self, data, accepted_media_type=None, renderer_context=None):
renderer_context = renderer_context or {}
- ctx = self.get_context(renderer_context)
- geom = ctx.get('g')
+ view = renderer_context.get('view')
+ geom = view and view.clean_params().get('g')
if isinstance(data, dict):
self.set_filename(self.basename(data), renderer_context)
# No conversion is needed if the original format without clipping | Add clean_params() method to QueryFormMixin | bkg_django-spillway | train |
696d2df180116f8e0c1151ad52742339e00631b7 | diff --git a/test/v2_integration.py b/test/v2_integration.py
index <HASH>..<HASH> 100644
--- a/test/v2_integration.py
+++ b/test/v2_integration.py
@@ -361,6 +361,20 @@ def test_overlapping_wildcard():
finally:
cleanup()
+def test_highrisk_blocklist():
+ """
+ Test issuance for a subdomain of a HighRiskBlockedNames entry. It should
+ fail with a policy error.
+ """
+
+ # We include "example.org" in `test/hostname-policy.yaml` in the
+ # HighRiskBlockedNames list so issuing for "foo.example.org" should be
+ # blocked.
+ domain = "foo.example.org"
+ # We expect this to produce a policy problem
+ chisel2.expect_problem("urn:ietf:params:acme:error:rejectedIdentifier",
+ lambda: chisel2.auth_and_issue([domain], chall_type="dns-01"))
+
def test_wildcard_exactblacklist():
"""
Test issuance for a wildcard that would cover an exact blacklist entry. It | tests: add int. test for highrisk blocklist. (#<I>) | letsencrypt_boulder | train |
fefd96f7e86d797c9d03439237e0387f06d83736 | diff --git a/lib/android/app/src/main/java/com/reactnativenavigation/views/ComponentLayout.java b/lib/android/app/src/main/java/com/reactnativenavigation/views/ComponentLayout.java
index <HASH>..<HASH> 100644
--- a/lib/android/app/src/main/java/com/reactnativenavigation/views/ComponentLayout.java
+++ b/lib/android/app/src/main/java/com/reactnativenavigation/views/ComponentLayout.java
@@ -57,7 +57,7 @@ public class ComponentLayout extends FrameLayout implements ReactComponent, TopB
}
public void applyOptions(Options options) {
- touchDelegate.setInterceptTouchOutside(options.overlayOptions.interceptTouchOutside.isTrue());
+ touchDelegate.setInterceptTouchOutside(options.overlayOptions.interceptTouchOutside);
}
@Override
diff --git a/lib/android/app/src/main/java/com/reactnativenavigation/views/touch/OverlayTouchDelegate.java b/lib/android/app/src/main/java/com/reactnativenavigation/views/touch/OverlayTouchDelegate.java
index <HASH>..<HASH> 100644
--- a/lib/android/app/src/main/java/com/reactnativenavigation/views/touch/OverlayTouchDelegate.java
+++ b/lib/android/app/src/main/java/com/reactnativenavigation/views/touch/OverlayTouchDelegate.java
@@ -5,6 +5,8 @@ import android.support.annotation.VisibleForTesting;
import android.view.MotionEvent;
import android.view.ViewGroup;
+import com.reactnativenavigation.parse.params.Bool;
+import com.reactnativenavigation.parse.params.NullBool;
import com.reactnativenavigation.utils.UiUtils;
import com.reactnativenavigation.viewcontrollers.IReactView;
@@ -12,13 +14,14 @@ public class OverlayTouchDelegate {
private enum TouchLocation {Outside, Inside}
private final Rect hitRect = new Rect();
private IReactView reactView;
- private boolean interceptTouchOutside;
+ private Bool interceptTouchOutside = new NullBool();
public OverlayTouchDelegate(IReactView reactView) {
this.reactView = reactView;
}
public boolean onInterceptTouchEvent(MotionEvent event) {
+ if (interceptTouchOutside instanceof NullBool) return false;
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
return handleDown(event);
@@ -35,7 +38,7 @@ public class OverlayTouchDelegate {
if (location == TouchLocation.Inside) {
reactView.dispatchTouchEventToJs(event);
}
- if (interceptTouchOutside) {
+ if (interceptTouchOutside.isTrue()) {
return location == TouchLocation.Inside;
}
return location == TouchLocation.Outside;
@@ -48,7 +51,7 @@ public class OverlayTouchDelegate {
TouchLocation.Outside;
}
- public void setInterceptTouchOutside(boolean interceptTouchOutside) {
+ public void setInterceptTouchOutside(Bool interceptTouchOutside) {
this.interceptTouchOutside = interceptTouchOutside;
}
}
diff --git a/lib/android/app/src/test/java/com/reactnativenavigation/views/TouchDelegateTest.java b/lib/android/app/src/test/java/com/reactnativenavigation/views/TouchDelegateTest.java
index <HASH>..<HASH> 100644
--- a/lib/android/app/src/test/java/com/reactnativenavigation/views/TouchDelegateTest.java
+++ b/lib/android/app/src/test/java/com/reactnativenavigation/views/TouchDelegateTest.java
@@ -4,6 +4,7 @@ import android.view.MotionEvent;
import com.reactnativenavigation.BaseTest;
import com.reactnativenavigation.mocks.SimpleOverlay;
+import com.reactnativenavigation.parse.params.Bool;
import com.reactnativenavigation.views.touch.OverlayTouchDelegate;
import org.junit.Test;
@@ -29,28 +30,28 @@ public class TouchDelegateTest extends BaseTest {
}
@Test
- public void downEventIsHandled() throws Exception {
- uut.setInterceptTouchOutside(true);
+ public void downEventIsHandled() {
+ uut.setInterceptTouchOutside(new Bool(true));
uut.onInterceptTouchEvent(downEvent);
verify(uut, times(1)).handleDown(downEvent);
}
@Test
- public void onlyDownEventIsHandled() throws Exception {
- uut.setInterceptTouchOutside(true);
+ public void onlyDownEventIsHandled() {
+ uut.setInterceptTouchOutside(new Bool(true));
uut.onInterceptTouchEvent(upEvent);
verify(uut, times(0)).handleDown(upEvent);
}
@Test
- public void nonDownEventsDontIntercept() throws Exception {
- uut.setInterceptTouchOutside(true);
+ public void nonDownEventsDontIntercept() {
+ uut.setInterceptTouchOutside(new Bool(true));
assertThat(uut.onInterceptTouchEvent(upEvent)).isFalse();
}
@Test
- public void nonDownEventsDispatchTouchEventsToJs() throws Exception {
- uut.setInterceptTouchOutside(true);
+ public void nonDownEventsDispatchTouchEventsToJs() {
+ uut.setInterceptTouchOutside(new Bool(true));
uut.onInterceptTouchEvent(upEvent);
verify(reactView, times(1)).dispatchTouchEventToJs(upEvent);
} | InterceptTouchOutside only when requested explicitly by the user
This works around an issue with RN's view reconciliation when the
root component has no background color defined. | wix_react-native-navigation | train |
b3af69c09a0e44eff4ba3c771986b8b3c2486c9d | diff --git a/bot/manager.py b/bot/manager.py
index <HASH>..<HASH> 100644
--- a/bot/manager.py
+++ b/bot/manager.py
@@ -17,6 +17,7 @@ from bot.action.standard.admin.fail import FailAction
from bot.action.standard.admin.instance import InstanceAction
from bot.action.standard.admin.state import StateAction
from bot.action.standard.answer import AnswerAction
+from bot.action.standard.async import AsyncApiAction
from bot.action.standard.asynchronous import AsynchronousAction
from bot.action.standard.benchmark import BenchmarkAction, WorkersAction
from bot.action.standard.chatsettings.action import ChatSettingsAction
@@ -91,7 +92,9 @@ class BotManager:
TextMessageAction().then(
CommandAction("start").then(
- AnswerAction("Hello! I am " + self.bot.cache.bot_info.first_name + " and I am here to serve you.")
+ AsyncApiAction().then(
+ AnswerAction("Hello! I am " + self.bot.cache.bot_info.first_name + " and I am here to serve you.")
+ )
),
CommandAction("about").then( | Make /start response to be async using AsyncApiAction | alvarogzp_telegram-bot-framework | train |
44d440027d6e5a21041be3ee67d6fc73d8150af9 | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -96,9 +96,13 @@ if USE_CYTHON:
print("")
print("Using Cython !!!!!!!!!")
print("")
- extensions = [Extension(name="tofu.geom."+gg, sources=["tofu/geom/"+gg+".pyx"], define_macros=[('CYTHON_TRACE_NOGIL', '1')],
+ extensions = [Extension(name="tofu.geom."+gg, sources=["tofu/geom/"+gg+".pyx"],
+ extra_compile_args=["-a"], # add the needed argument
+ define_macros=[('CYTHON_TRACE_NOGIL', '1')],
compiler_directives={'profile': True}),
- Extension(name="tofu.geom."+gg_lm, sources=["tofu/geom/"+gg_lm+".pyx"], define_macros=[('CYTHON_TRACE_NOGIL', '1')],
+ Extension(name="tofu.geom."+gg_lm, sources=["tofu/geom/"+gg_lm+".pyx"],
+ extra_compile_args=["-a"], # add the needed argument
+ define_macros=[('CYTHON_TRACE_NOGIL', '1')],
compiler_directives={'profile': True})]
extensions = cythonize(extensions)
else: | [LOS] NOT finished. implemented cython ray_tracing method slower that numpy's path.contains_point | ToFuProject_tofu | train |
412e0facc84af93307817a83bd9b4540cc88af06 | diff --git a/cmd/notary/tuf.go b/cmd/notary/tuf.go
index <HASH>..<HASH> 100644
--- a/cmd/notary/tuf.go
+++ b/cmd/notary/tuf.go
@@ -367,9 +367,12 @@ func getTransport(gun string, readOnly bool) http.RoundTripper {
}
}
+ insecureSkipVerify := false
+ if mainViper.IsSet("remote_server.skipTLSVerify") {
+ insecureSkipVerify = mainViper.GetBool("remote_server.skipTLSVerify")
+ }
tlsConfig, err := utils.ConfigureClientTLS(
- rootCAFile, "", mainViper.GetBool("remote_server.skipTLSVerify"),
- "", "")
+ rootCAFile, "", insecureSkipVerify, "", "")
if err != nil {
logrus.Fatal("Unable to configure TLS: ", err.Error())
}
diff --git a/utils/tls_config.go b/utils/tls_config.go
index <HASH>..<HASH> 100644
--- a/utils/tls_config.go
+++ b/utils/tls_config.go
@@ -73,9 +73,9 @@ func ConfigureServerTLS(serverCert, serverKey string, clientAuth bool, caCertDir
// ConfigureClientTLS generates a tls configuration for clients using the
// provided parameters.
-func ConfigureClientTLS(rootCA, serverName string, skipVerify bool, clientCert, clientKey string) (*tls.Config, error) {
+func ConfigureClientTLS(rootCA, serverName string, insecureSkipVerify bool, clientCert, clientKey string) (*tls.Config, error) {
tlsConfig := &tls.Config{
- InsecureSkipVerify: skipVerify,
+ InsecureSkipVerify: insecureSkipVerify,
MinVersion: tls.VersionTLS12,
CipherSuites: clientCipherSuites,
ServerName: serverName, | Explicitly check the skip tls verify boolean in notary client | theupdateframework_notary | train |
d39f3a2094bfaf4b24f000dc8db70a6ee1a7e236 | diff --git a/spec/stream.spec.js b/spec/stream.spec.js
index <HASH>..<HASH> 100644
--- a/spec/stream.spec.js
+++ b/spec/stream.spec.js
@@ -93,7 +93,7 @@ describe("Streaming Queries", function() {
});
- it("should return the initial result", function() {
+ it.skip("should return the initial result", function() {
var received = [];
var promise = new Promise(function(success, error) {
stream = db[bucket].find().stream();
@@ -110,7 +110,7 @@ describe("Streaming Queries", function() {
});
});
- it("should return updated object", function() {
+ it.skip("should return updated object", function() {
stream = db[bucket].find().stream(false);
var result = {};
stream.on('match', function(object, operation, match) {
@@ -150,7 +150,7 @@ describe("Streaming Queries", function() {
});
it("should return removed object", function() {
- stream = db[bucket].find().equal("name", "franz").stream(false);
+ stream = db[bucket].find().equal("name", "franzi").stream(false);
var result = {};
stream.on('remove', function(obj, operation, match) {
result.operation = operation;
@@ -158,7 +158,7 @@ describe("Streaming Queries", function() {
});
var object = db[bucket].fromJSON(p3.toJSON(true));
- object.name = "franz";
+ object.name = "franzi";
return object.insert().then(function() {
return sleep(t, object.delete());
@@ -168,7 +168,7 @@ describe("Streaming Queries", function() {
});
});
- it("should allow multiple listeners", function() {
+ it.skip("should allow multiple listeners", function() {
var received = [];
var insert = db[bucket].fromJSON(p3.toJSON(true));
insert.name = "franz";
@@ -191,7 +191,7 @@ describe("Streaming Queries", function() {
});
});
- it("should allow to unregister", function() {
+ it.skip("should allow to unregister", function() {
var calls = 0;
stream = db[bucket].find().stream(false);
var listener = function(object, operation, match) {
@@ -213,7 +213,7 @@ describe("Streaming Queries", function() {
});
- it("should only be called once", function() {
+ it.skip("should only be called once", function() {
var calls = 0;
stream = db[bucket].find().stream(false);
var listener = function(object, operation, match) { | -Prevent double publishing for stateful queries | Baqend_js-sdk | train |
f5d688ea121c8d9249d1c4e274bf1616199ebaba | diff --git a/src/FastRoute/Router.php b/src/FastRoute/Router.php
index <HASH>..<HASH> 100644
--- a/src/FastRoute/Router.php
+++ b/src/FastRoute/Router.php
@@ -75,8 +75,8 @@ class Router implements RouterInterface
case \FastRoute\Dispatcher::FOUND:
$handler = $routeInfo[1];
$vars = $routeInfo[2];
- $request->keep(App::CONTROLLER, $handler);
- $request->keep(App::ROUTE_PARAM, $vars);
+ $request->setAttribute(App::CONTROLLER, $handler);
+ $request->setAttribute(App::ROUTE_PARAM, $vars);
return [$handler, $vars];
}
diff --git a/src/PhRouter/Router.php b/src/PhRouter/Router.php
index <HASH>..<HASH> 100644
--- a/src/PhRouter/Router.php
+++ b/src/PhRouter/Router.php
@@ -69,8 +69,8 @@ class Router implements RouterInterface
$uri = $request->getPathInfo();
$found = $this->matchRoute($method, $uri);
- $request->keep(App::CONTROLLER, $found[0]);
- $request->keep(App::ROUTE_PARAM, $found[2]);
+ $request->setAttribute(App::CONTROLLER, $found[0]);
+ $request->setAttribute(App::ROUTE_PARAM, $found[2]);
return $found;
} | renamed bag/keep to {get|set}Attribute, | TuumPHP_Router | train |
0293ca444dc6813436da3f82c96f360f84bdc5c3 | diff --git a/src/article/shared/EditorPanel.js b/src/article/shared/EditorPanel.js
index <HASH>..<HASH> 100644
--- a/src/article/shared/EditorPanel.js
+++ b/src/article/shared/EditorPanel.js
@@ -57,6 +57,7 @@ export default class EditorPanel extends Component {
this.editorSession.initialize()
this.appState.addObserver(['workflowId'], this.rerender, this, { stage: 'render' })
this.appState.addObserver(['viewName'], this._updateViewName, this, { stage: 'render' })
+ this.appState.addObserver(['settings'], this.rerender, this, { stage: 'render' })
// HACK: ATM there is no better way than to listen to an archive
// event and forcing the CommandManager to update commandStates | Rerender EditorPanel when settings are updated. | substance_texture | train |
3bea9c9f1ceeb3a4145838fbbce4e7218a682abe | diff --git a/structr-ui/src/main/java/org/structr/web/common/FileHelper.java b/structr-ui/src/main/java/org/structr/web/common/FileHelper.java
index <HASH>..<HASH> 100644
--- a/structr-ui/src/main/java/org/structr/web/common/FileHelper.java
+++ b/structr-ui/src/main/java/org/structr/web/common/FileHelper.java
@@ -450,7 +450,7 @@ public class FileHelper {
}
long fileSize = FileHelper.getSize(fileOnDisk);
- if (fileSize > 0) {
+ if (fileSize >= 0) {
map.put(sizeKey, fileSize);
} | Bugfix: Allow saving the filesize for files with 0 bytes | structr_structr | train |
292a9be350a470c23b07cb69cd46ee1d1893885b | diff --git a/test/helpers/test-get-user.js b/test/helpers/test-get-user.js
index <HASH>..<HASH> 100644
--- a/test/helpers/test-get-user.js
+++ b/test/helpers/test-get-user.js
@@ -51,7 +51,9 @@ describe('getUser', function() {
* used.
*/
function fakeInit(app) {
- var config = require('stormpath/lib/config.json');
+ var defaultConfig = require('stormpath/lib/config.json');
+
+ var config = deepExtend({},defaultConfig);
deepExtend(config, {
application: { | Fixing tests to not mutate the default state object | stormpath_express-stormpath | train |
d09fa2ae4c62b0a30c393beb78626bc1dfefa04d | diff --git a/lib/ExportsFieldPlugin.js b/lib/ExportsFieldPlugin.js
index <HASH>..<HASH> 100644
--- a/lib/ExportsFieldPlugin.js
+++ b/lib/ExportsFieldPlugin.js
@@ -7,6 +7,7 @@
const path = require("path");
const DescriptionFileUtils = require("./DescriptionFileUtils");
+const forEachBail = require("./forEachBail");
const { checkExportsFieldTarget } = require("./pathUtils");
const processExportsField = require("./processExportsField");
@@ -90,49 +91,35 @@ module.exports = class ExportsFieldPlugin {
if (paths.length === 0) return callback(null, null);
- let i = 0;
+ forEachBail(
+ paths,
+ (p, callback) => {
+ const error = checkExportsFieldTarget(p);
- const resolveNext = () => {
- const errorMsg = checkExportsFieldTarget(paths[i]);
-
- if (errorMsg) {
- return callback(new Error(errorMsg));
- }
-
- const obj = {
- ...request,
- request: undefined,
- path: path.join(
- /** @type {string} */ (request.descriptionFileRoot),
- paths[i]
- ),
- relativePath: paths[i]
- };
-
- resolver.doResolve(
- target,
- obj,
- "using exports field: " + paths[i],
- resolveContext,
- (err, result) => {
- if (err) {
- i++;
-
- return i !== paths.length ? resolveNext() : callback(err);
- } else if (result === undefined) {
- i++;
-
- return i === paths.length
- ? callback(null, null)
- : resolveNext();
- }
-
- callback(null, result);
+ if (error) {
+ return callback(error);
}
- );
- };
- resolveNext();
+ const obj = {
+ ...request,
+ request: undefined,
+ path: path.join(
+ /** @type {string} */ (request.descriptionFileRoot),
+ p
+ ),
+ relativePath: p
+ };
+
+ resolver.doResolve(
+ target,
+ obj,
+ "using exports field: " + p,
+ resolveContext,
+ callback
+ );
+ },
+ (err, result) => callback(err, result || null)
+ );
});
}
};
diff --git a/lib/pathUtils.js b/lib/pathUtils.js
index <HASH>..<HASH> 100644
--- a/lib/pathUtils.js
+++ b/lib/pathUtils.js
@@ -196,7 +196,9 @@ const checkExportsFieldTarget = relativePath => {
case "..": {
cd--;
if (cd < 0)
- return `Trying to access out of package scope. Requesting ${relativePath}`;
+ return new Error(
+ `Trying to access out of package scope. Requesting ${relativePath}`
+ );
break;
}
default: | use forEachBail in ExportsFieldPlugin
improve error reporting | webpack_enhanced-resolve | train |
467b6aaaac0964231f85d3d87c60076b688cc5f1 | diff --git a/lib/express/core.js b/lib/express/core.js
index <HASH>..<HASH> 100644
--- a/lib/express/core.js
+++ b/lib/express/core.js
@@ -19,9 +19,10 @@ Route = Class({
// --- Router
+var captures = [],
+ params = {}
+
Router = Class({
- captures: [],
- params: {},
route: function(request){
this.request = request
return this.matchingRoute().run()
@@ -43,7 +44,7 @@ Router = Class({
match: function(route) {
if (this.request.method.toLowerCase() == route.method)
- if (this.captures = this.request.uri.path.match(route.path)) {
+ if (captures = this.request.uri.path.match(route.path)) {
this.mapParams()
return true
}
@@ -51,7 +52,7 @@ Router = Class({
mapParams: function() {
for (var i = 0, len = keys.length; i < len; ++i)
- this.params[keys[i]] = this.captures[i+1]
+ params[keys[i]] = captures[i+1]
}
})
@@ -104,7 +105,7 @@ function normalizePath(path) {
}
param = function(key) {
- return Express.server.router.params[key]
+ return params[key]
}
jsonEncode = function(object) {
@@ -173,9 +174,10 @@ function route(method) {
* @api private
*/
-var keys = []
+var keys
function pathToRegexp(path) {
if (path instanceof RegExp) return path
+ keys = []
return new RegExp('^' +
escapeRegexp(path.replace(/:(\w+)/g, function(_, key){
keys.push(key)
diff --git a/spec/spec.core.routing.js b/spec/spec.core.routing.js
index <HASH>..<HASH> 100644
--- a/spec/spec.core.routing.js
+++ b/spec/spec.core.routing.js
@@ -93,7 +93,6 @@ describe 'Express'
-{ get('/user') }.should.throw_error
try { get('/user') }
catch (e){
- print(e.stack)
e.stack.should.include('get')
e.stack.should.include('("/user")')
} | Fixed param() with multiple placeholders | expressjs_express | train |
41626eee42c4cd91a04f00e013b72faab66509d5 | diff --git a/threadedcomments/models.py b/threadedcomments/models.py
index <HASH>..<HASH> 100644
--- a/threadedcomments/models.py
+++ b/threadedcomments/models.py
@@ -11,7 +11,7 @@ class ThreadedComment(Comment):
path = models.TextField(null=True, blank=True, db_index=True)
def _get_depth(self):
- return len(self.path.split(PATH_SEPARATOR)) - 1
+ return len(self.path.split(PATH_SEPARATOR))
depth = property(_get_depth)
def save(self, *args, **kwargs): | Decided it was fine for the depth to be 1-based instead of 0-based, so we don't need to remove 1 from the length of the split path field. | HonzaKral_django-threadedcomments | train |
f71c8d6a6c8b543ac63cbbd6e6c409c3a0ad9efb | diff --git a/src/tabris/Events.js b/src/tabris/Events.js
index <HASH>..<HASH> 100644
--- a/src/tabris/Events.js
+++ b/src/tabris/Events.js
@@ -131,7 +131,7 @@ export default {
const value = callback.fn.call(callback.ctx || this, dispatchObject);
if (value instanceof Promise) {
value.catch(ex => console.error(
- `Listener for ${target.constructor.name} event "${type}" rejected with ${ex.stack || ex}`
+ `Listener for ${target.constructor.name} event "${type}" rejected:\n${ex.toString()}`
));
}
returnValues.push(value); | Improve error asynchronous error handling
In case of asynchronous listeners rejecting the error should be printed
with a source-mapped stack trace. This is only the case when calling
`toString()`, since this method is patched by tabris.
Change-Id: Ia<I>a<I>f2f<I>a3ddb<I>d<I>f4a<I>f2f8e | eclipsesource_tabris-js | train |
77e9b9e910a918b17dc33fb4c86e4bf7f26d37b3 | diff --git a/v2/security_group.go b/v2/security_group.go
index <HASH>..<HASH> 100644
--- a/v2/security_group.go
+++ b/v2/security_group.go
@@ -220,9 +220,7 @@ func (c *Client) CreateSecurityGroupRule(
// Look for an unknown rule: if we find one we hope it's the one we've just created.
for _, r := range sgUpdated.Rules {
- if _, ok := rules[*r.ID]; !ok && (*r.Protocol == *rule.Protocol &&
- *r.StartPort == *rule.StartPort &&
- *r.EndPort == *rule.EndPort) {
+ if _, ok := rules[*r.ID]; !ok && (*r.FlowDirection == *rule.FlowDirection && *r.Protocol == *rule.Protocol) {
return r, nil
}
} | v2: fix CreateSecurityGroupRule() method
This change fixes a bug in the `Client.CreateSecurityGroupRule()`
method, where a crash would occur when creating a rule without a
start/end port (e.g. ICMP rules). | exoscale_egoscale | train |
95a74c6728a68cd7204f6346e60873244a4be58e | diff --git a/helpers.go b/helpers.go
index <HASH>..<HASH> 100644
--- a/helpers.go
+++ b/helpers.go
@@ -3,6 +3,7 @@ package gorma
import (
"fmt"
"strings"
+ "unicode"
"bitbucket.org/pkg/inflect"
@@ -150,6 +151,44 @@ func pkUpdateFields(pks map[string]PrimaryKey) string {
func lower(s string) string {
return strings.ToLower(s)
}
+
+// camelToSnake converts a given string to snake case.
+func camelToSnake(s string) string {
+ var result string
+ var words []string
+ var lastPos int
+ rs := []rune(s)
+
+ for i := 0; i < len(rs); i++ {
+ if i > 0 && unicode.IsUpper(rs[i]) {
+ if initialism := startsWithInitialism(s[lastPos:]); initialism != "" {
+ words = append(words, initialism)
+
+ i += len(initialism) - 1
+ lastPos = i
+ continue
+ }
+
+ words = append(words, s[lastPos:i])
+ lastPos = i
+ }
+ }
+
+ // append the last word
+ if s[lastPos:] != "" {
+ words = append(words, s[lastPos:])
+ }
+
+ for k, word := range words {
+ if k > 0 {
+ result += "_"
+ }
+
+ result += strings.ToLower(word)
+ }
+
+ return result
+}
func belongsTo(utd *design.UserTypeDefinition) []BelongsTo {
var belongs []BelongsTo
def := utd.Definition()
@@ -159,8 +198,8 @@ func belongsTo(utd *design.UserTypeDefinition) []BelongsTo {
for n := range actual {
if bt, ok := metaLookup(actual[n].Metadata, gengorma.MetaBelongsTo); ok {
bel := BelongsTo{
- Parent: n,
- DatabaseField: bt,
+ Parent: strings.Replace(n, "ID", "", -1),
+ DatabaseField: camelToSnake(bt),
}
belongs = append(belongs, bel)
}
@@ -231,3 +270,51 @@ func storageDef(res *design.UserTypeDefinition) string {
return associations
}
+
+// startsWithInitialism returns the initialism if the given string begins with it
+func startsWithInitialism(s string) string {
+ var initialism string
+ // the longest initialism is 5 char, the shortest 2
+ for i := 1; i <= 5; i++ {
+ if len(s) > i-1 && commonInitialisms[s[:i]] {
+ initialism = s[:i]
+ }
+ }
+ return initialism
+}
+
+// commonInitialisms, taken from
+// https://github.com/golang/lint/blob/3d26dc39376c307203d3a221bada26816b3073cf/lint.go#L482
+var commonInitialisms = map[string]bool{
+ "API": true,
+ "ASCII": true,
+ "CPU": true,
+ "CSS": true,
+ "DNS": true,
+ "EOF": true,
+ "GUID": true,
+ "HTML": true,
+ "HTTP": true,
+ "HTTPS": true,
+ "ID": true,
+ "IP": true,
+ "JSON": true,
+ "LHS": true,
+ "QPS": true,
+ "RAM": true,
+ "RHS": true,
+ "RPC": true,
+ "SLA": true,
+ "SMTP": true,
+ "SSH": true,
+ "TLS": true,
+ "TTL": true,
+ "UI": true,
+ "UID": true,
+ "UUID": true,
+ "URI": true,
+ "URL": true,
+ "UTF8": true,
+ "VM": true,
+ "XML": true,
+}
diff --git a/writers.go b/writers.go
index <HASH>..<HASH> 100644
--- a/writers.go
+++ b/writers.go
@@ -614,7 +614,7 @@ func (m {{.UserType.TypeName}}) GetRole() string {
func {{$typename}}FilterBy{{$bt.Parent}}(parentid int, originaldb *gorm.DB) func(db *gorm.DB) *gorm.DB {
if parentid > 0 {
return func(db *gorm.DB) *gorm.DB {
- return db.Where("{{ $bt.DatabaseField }}_id = ?", parentid)
+ return db.Where("{{ $bt.DatabaseField }} = ?", parentid)
}
} else {
return func(db *gorm.DB) *gorm.DB { | fix camel/snake case issues | goadesign_gorma | train |
bb0fc5a8383dff07f22208e842345e0cac91b76f | diff --git a/src/Picqer/Financials/Moneybird/Moneybird.php b/src/Picqer/Financials/Moneybird/Moneybird.php
index <HASH>..<HASH> 100644
--- a/src/Picqer/Financials/Moneybird/Moneybird.php
+++ b/src/Picqer/Financials/Moneybird/Moneybird.php
@@ -19,6 +19,7 @@ use Picqer\Financials\Moneybird\Entities\PurchaseInvoiceDetail;
use Picqer\Financials\Moneybird\Entities\Receipt;
use Picqer\Financials\Moneybird\Entities\RecurringSalesInvoice;
use Picqer\Financials\Moneybird\Entities\Note;
+use Picqer\Financials\Moneybird\Entities\RecurringSalesInvoiceDetail;
use Picqer\Financials\Moneybird\Entities\SalesInvoice;
use Picqer\Financials\Moneybird\Entities\SalesInvoiceCustomField;
use Picqer\Financials\Moneybird\Entities\SalesInvoiceDetail;
@@ -225,6 +226,15 @@ class Moneybird
/**
* @param array $attributes
+ * @return RecurringSalesInvoiceDetail
+ */
+ public function recurringSalesInvoiceDetail($attributes = [])
+ {
+ return new RecurringSalesInvoiceDetail($this->connection, $attributes);
+ }
+
+ /**
+ * @param array $attributes
* @return SalesInvoice
*/
public function salesInvoice($attributes = []) | Added missing factory for RecurringSalesInvoiceDetail | picqer_moneybird-php-client | train |
b902bd9d9a4993aaf2cfc609701f3aa3e266b9e6 | diff --git a/lib/apiUrl.js b/lib/apiUrl.js
index <HASH>..<HASH> 100644
--- a/lib/apiUrl.js
+++ b/lib/apiUrl.js
@@ -11,10 +11,8 @@
module.exports = function apiUrl(path, options, tokenNeeded) {
var queryObj = {};
- if(options.oauth)
- return protocol + '://' + proxyHost + '/' + path;
- if (tokenNeeded) {
+ if (!options.oauth && tokenNeeded) {
queryObj.api_token = options.apiToken;
}
if (options.strictMode === true) { | Query must still be created to properly pass strict mode | pipedrive_client-nodejs | train |
a951c0e49c43d345d73219e642e0810db77939c0 | diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/ByteArrayKeyTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/ByteArrayKeyTest.java
index <HASH>..<HASH> 100644
--- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/ByteArrayKeyTest.java
+++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/ByteArrayKeyTest.java
@@ -3,13 +3,6 @@ package com.orientechnologies.orient.test.database.auto;
import java.util.Arrays;
import java.util.Collection;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Parameters;
-import org.testng.annotations.Test;
-
import com.orientechnologies.common.collection.OCompositeKey;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.index.OIndex;
@@ -19,6 +12,13 @@ import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.tx.OTransaction;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Parameters;
+import org.testng.annotations.Test;
+
/**
* @author Andrey Lomakin
* @since 03.07.12 | Issue <I> was partially fixed. | orientechnologies_orientdb | train |
4809841321634ae8787a90e23e543f17cf2f3b80 | diff --git a/leancloud/utils.py b/leancloud/utils.py
index <HASH>..<HASH> 100644
--- a/leancloud/utils.py
+++ b/leancloud/utils.py
@@ -140,6 +140,7 @@ def decode(key, value):
if meta_data:
f._metadata = meta_data
f._url = value["url"]
+ f._successful_url = value["url"]
f.id = value["objectId"]
return f
diff --git a/tests/test_query.py b/tests/test_query.py
index <HASH>..<HASH> 100644
--- a/tests/test_query.py
+++ b/tests/test_query.py
@@ -17,6 +17,7 @@ import leancloud
from leancloud import Query
from leancloud import Object
from leancloud import GeoPoint
+from leancloud.file_ import File
__author__ = "asaka <[email protected]>"
@@ -68,6 +69,9 @@ def make_setup_func(use_master_key=False):
game_score.set("playerName", "张三")
game_score.set("location", GeoPoint(latitude=i, longitude=-i))
game_score.set("random", random.randrange(100))
+ f = File("Blah.txt", open("tests/sample_text.txt", "rb"))
+ f.save()
+ game_score.set("attachment", f)
game_score.save()
return setup_func
@@ -468,6 +472,12 @@ def test_include(): # type: () -> None
result = Query(GameScore).include(["score"]).find()
assert len(result) == 10
+@with_setup(make_setup_func())
+def test_attachment(): # type: () -> None
+ result = Query(GameScore).first()
+ print(result.dump())
+ attachment = result.get('attachment')
+ assert attachment.url
@with_setup(make_setup_func())
def test_select(): # type: () -> None | fix: missing url attribute when decoding file object
Thank 沉寂 for bringing this to our attention. | leancloud_python-sdk | train |
a4f73c81e8460ce64f77c51599ddc5e1e9de50f0 | diff --git a/tuning/curve.py b/tuning/curve.py
index <HASH>..<HASH> 100644
--- a/tuning/curve.py
+++ b/tuning/curve.py
@@ -759,7 +759,7 @@ def to_poynting_curve(curve, save_directory):
headers = collections.OrderedDict()
headers['file created'] = timestamp.RFC3339
headers['interaction'] = curve.interaction
- headers['name'] = ['Color (wn)', 'phi', 'theta']
+ headers['name'] = ['Color (wn)', 'Phi', 'Theta']
wt_kit.write_headers(out_path, headers)
with open(out_path, 'ab') as f:
np.savetxt(f, out_arr.T, fmt=['%.2f','%.0f', '%.0f'], | capitalization in to poynting curve | wright-group_WrightTools | train |
869fc840ea470f915f2d5eedafb2ff50400c41e4 | diff --git a/test/express-adapter.test.js b/test/express-adapter.test.js
index <HASH>..<HASH> 100644
--- a/test/express-adapter.test.js
+++ b/test/express-adapter.test.js
@@ -12,14 +12,22 @@ suite('Adaption for express application', function() {
var testRestPlugin = {
api: new command.HTTPCommand({
path: '/path/to/api',
- requestConverter: function(event, request) { return [event, 'api requested']; },
- responseConverter: function(event, data) { return [event, 'api OK']; }
+ onRequest: function(request, connection) {
+ connection.emit('api', 'api requested');
+ },
+ onResponse: function(data, response) {
+ response.jsonp('api OK', 200);
+ }
})
};
var testSocketPlugin = {
api: new command.SocketRequestResponse({
- requestConverter: function(event, data) { return [event, 'api requested']; },
- responseConverter: function(event, data) { return [event, 'api OK']; }
+ onRequest: function(data, connection) {
+ connection.emit('api', 'api requested');
+ },
+ onResponse: function(data, socket) {
+ socket.emit('api', 'api OK');
+ }
})
}; | Update tests for the new style of command definitions | droonga_express-droonga | train |
ae828c446885cd068e5a0a1b7fb4a75b459764a1 | diff --git a/estnltk/storage/postgres/collection.py b/estnltk/storage/postgres/collection.py
index <HASH>..<HASH> 100755
--- a/estnltk/storage/postgres/collection.py
+++ b/estnltk/storage/postgres/collection.py
@@ -1050,6 +1050,9 @@ class PgCollection:
(technically, you can create duplicates, because there is no
duplicate checking).
+ The layer table will be created in the self.storage.schema.
+ TODO: add a possibility to use a different schema
+
Parameters:
:param layer: str | Updated collection.export_layer doc | estnltk_estnltk | train |
b3ad5a2d2372333cc07790d829483febbaab9429 | diff --git a/example-integrations/angular/.bolt/.boltrc.js b/example-integrations/angular/.bolt/.boltrc.js
index <HASH>..<HASH> 100644
--- a/example-integrations/angular/.bolt/.boltrc.js
+++ b/example-integrations/angular/.bolt/.boltrc.js
@@ -21,7 +21,6 @@ const config = {
'@bolt/components-chip-list',
'@bolt/components-code-snippet',
'@bolt/components-copy-to-clipboard',
- '@bolt/components-critical-css',
'@bolt/components-device-viewer',
'@bolt/components-dropdown',
'@bolt/components-figure',
@@ -53,9 +52,6 @@ const config = {
'@bolt/components-ul',
'@bolt/components-video',
],
- individual: [
- '@bolt/components-critical-css',
- ],
},
};
diff --git a/example-integrations/angular/.bolt/package.json b/example-integrations/angular/.bolt/package.json
index <HASH>..<HASH> 100644
--- a/example-integrations/angular/.bolt/package.json
+++ b/example-integrations/angular/.bolt/package.json
@@ -25,7 +25,6 @@
"@bolt/components-chip-list": "^2.13.0",
"@bolt/components-code-snippet": "^2.13.0",
"@bolt/components-copy-to-clipboard": "^2.13.0",
- "@bolt/components-critical-css": "^2.13.0",
"@bolt/components-device-viewer": "^2.13.0",
"@bolt/components-dropdown": "^2.13.0",
"@bolt/components-figure": "^2.13.0",
diff --git a/example-integrations/static-html/.bolt/.boltrc.js b/example-integrations/static-html/.bolt/.boltrc.js
index <HASH>..<HASH> 100644
--- a/example-integrations/static-html/.bolt/.boltrc.js
+++ b/example-integrations/static-html/.bolt/.boltrc.js
@@ -25,7 +25,6 @@ const config = {
'@bolt/components-chip-list',
'@bolt/components-code-snippet',
'@bolt/components-copy-to-clipboard',
- '@bolt/components-critical-css',
'@bolt/components-device-viewer',
'@bolt/components-dropdown',
'@bolt/components-figure',
@@ -57,9 +56,6 @@ const config = {
'@bolt/components-ul',
'@bolt/components-video',
],
- individual: [
- '@bolt/components-critical-css',
- ],
},
};
diff --git a/example-integrations/static-html/.bolt/package.json b/example-integrations/static-html/.bolt/package.json
index <HASH>..<HASH> 100644
--- a/example-integrations/static-html/.bolt/package.json
+++ b/example-integrations/static-html/.bolt/package.json
@@ -29,7 +29,6 @@
"@bolt/components-chip-list": "^2.13.0",
"@bolt/components-code-snippet": "^2.13.0",
"@bolt/components-copy-to-clipboard": "^2.13.0",
- "@bolt/components-critical-css": "^2.13.0",
"@bolt/components-device-viewer": "^2.13.0",
"@bolt/components-dropdown": "^2.13.0",
"@bolt/components-figure": "^2.13.0",
diff --git a/packages/base-starter-kit/.boltrc.js b/packages/base-starter-kit/.boltrc.js
index <HASH>..<HASH> 100644
--- a/packages/base-starter-kit/.boltrc.js
+++ b/packages/base-starter-kit/.boltrc.js
@@ -65,8 +65,5 @@ module.exports = {
'@bolt/components-ul',
'@bolt/components-video',
],
- individual: [
- '@bolt/components-critical-css',
- ],
},
}; | feature: remove references to `critial-css` | bolt-design-system_bolt | train |
7787fa4d464d4f9557a47bac8ba90abf11b31a42 | diff --git a/gulpfile.js b/gulpfile.js
index <HASH>..<HASH> 100644
--- a/gulpfile.js
+++ b/gulpfile.js
@@ -92,6 +92,7 @@ gulp.task('tag', function() {
gulp.task('release', function(cb) {
runSequence(
+ 'default',
'bump',
'bump-commit',
'tag', | Make sure we run default tests before releasing. | petejohanson_hy-res | train |
8054ed3778386045f236495b3c0ac5767cead22d | diff --git a/mvvmfx/src/test/java/de/saxsys/mvvmfx/utils/commands/CompositeCommandTest.java b/mvvmfx/src/test/java/de/saxsys/mvvmfx/utils/commands/CompositeCommandTest.java
index <HASH>..<HASH> 100644
--- a/mvvmfx/src/test/java/de/saxsys/mvvmfx/utils/commands/CompositeCommandTest.java
+++ b/mvvmfx/src/test/java/de/saxsys/mvvmfx/utils/commands/CompositeCommandTest.java
@@ -16,6 +16,7 @@ import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -155,6 +156,7 @@ public class CompositeCommandTest {
compositeCommand.unregister(delegateCommand2);
}
+ @Ignore("unstable test. Needs to be fixed. see bug #260")
@Test
public void longRunningAsyncComposite() throws Exception { | #<I> set failing test to ignore as a temporal fix | sialcasa_mvvmFX | train |
ae67f8201f18221fb778307eb447c81f4244a5fa | diff --git a/admin/tool/generator/classes/site_backend.php b/admin/tool/generator/classes/site_backend.php
index <HASH>..<HASH> 100644
--- a/admin/tool/generator/classes/site_backend.php
+++ b/admin/tool/generator/classes/site_backend.php
@@ -189,7 +189,8 @@ class tool_generator_site_backend extends tool_generator_backend {
}
// SQL order by is not appropiate here as is ordering strings.
$shortnames = array_keys($testcourses);
- rsort($shortnames, SORT_NATURAL);
+ core_collator::asort($shortnames, core_collator::SORT_NATURAL);
+ $shortnames = array_reverse($shortnames);
// They come ordered by shortname DESC, so non-numeric values will be the first ones.
$prefixnchars = strlen(self::SHORTNAMEPREFIX); | MDL-<I> Use moodle collator for NATURAL sort | moodle_moodle | train |
46631d0cdde44290a86b523d4c2544dd79c961a7 | diff --git a/pythonforandroid/recipes/python2/__init__.py b/pythonforandroid/recipes/python2/__init__.py
index <HASH>..<HASH> 100644
--- a/pythonforandroid/recipes/python2/__init__.py
+++ b/pythonforandroid/recipes/python2/__init__.py
@@ -30,7 +30,8 @@ class Python2Recipe(Recipe):
self.apply_patch(join('patches', 'fix-remove-corefoundation.patch'))
self.apply_patch(join('patches', 'fix-dynamic-lookup.patch'))
self.apply_patch(join('patches', 'fix-dlfcn.patch'))
- self.apply_patch(join('patches', 'ctypes-find-library.patch'))
+ # self.apply_patch(join('patches', 'ctypes-find-library.patch'))
+ self.apply_patch(join('patches', 'ctypes-find-library-updated.patch'))
if uname()[0] == 'Linux':
self.apply_patch(join('patches', 'fix-configure-darwin.patch'))
diff --git a/pythonforandroid/recipes/vispy/__init__.py b/pythonforandroid/recipes/vispy/__init__.py
index <HASH>..<HASH> 100644
--- a/pythonforandroid/recipes/vispy/__init__.py
+++ b/pythonforandroid/recipes/vispy/__init__.py
@@ -8,8 +8,10 @@ import glob
class VispyRecipe(PythonRecipe):
version = '0.4.0'
url = 'https://github.com/vispy/vispy/archive/v{version}.tar.gz'
+ # version = 'campagnola-scenegraph-update'
+ # url = 'https://github.com/campagnola/vispy/archive/scenegraph-update.zip'
- depends = ['python2', 'numpy']
+ depends = ['python2', 'numpy', 'pysdl2']
def prebuild_arch(self, arch):
super(VispyRecipe, self).prebuild_arch(arch)
@@ -20,6 +22,7 @@ class VispyRecipe(PythonRecipe):
self.apply_patch('disable_freetype.patch')
self.apply_patch('disable_font_triage.patch')
self.apply_patch('use_es2.patch')
+ self.apply_patch('remove_ati_check.patch')
shprint(sh.touch, join(build_dir, '.patched'))
recipe = VispyRecipe() | Small changes to vispy and python2 recipes | kivy_python-for-android | train |
f6f6d7b90f7f4b40be60593fd3c4265028246f8c | diff --git a/lib/file_system_backend.js b/lib/file_system_backend.js
index <HASH>..<HASH> 100644
--- a/lib/file_system_backend.js
+++ b/lib/file_system_backend.js
@@ -31,8 +31,10 @@ class FileSystem {
page.exposeFunction('registerFileSystem', this._registerFileSystem.bind(this)),
page.exposeFunction('fileSystemGetEntry', this._fileSystemGetEntry.bind(this, (changed, added, removed) => {
page.safeEvaluate((changed, added, removed) => {
- if (self.InspectorFrontendAPI)
- self.InspectorFrontendAPI.fileSystemFilesChangedAddedRemoved(changed, added, removed);
+ callFrontend(_ => {
+ if (self.InspectorFrontendAPI)
+ self.InspectorFrontendAPI.fileSystemFilesChangedAddedRemoved(changed, added, removed);
+ });
}, changed, added, removed);
})),
page.exposeFunction('fileSystemDirectoryReaderReadEntries', this._fileSystemDirectoryReaderReadEntries.bind(this)),
@@ -41,9 +43,11 @@ class FileSystem {
page.exposeFunction('fileSystemEntryMoveTo', this._fileSystemEntryMoveTo.bind(this)),
page.exposeFunction('fileSystemEntryFile', this._fileSystemEntryFile.bind(this, (readerId, event, ...args) => {
page.safeEvaluate(function(readerId, event, ...args) {
- const reader = FileSystem._readers.get(readerId);
- if (reader)
- reader[`on${event}`](...args);
+ callFrontend(_ => {
+ const reader = FileSystem._readers.get(readerId);
+ if (reader)
+ reader[`on${event}`](...args);
+ });
}, readerId, event, ...args);
})),
page.exposeFunction('fileSystemWriteFile', this._fileSystemWriteFile.bind(this)),
diff --git a/lib/search_backend.js b/lib/search_backend.js
index <HASH>..<HASH> 100644
--- a/lib/search_backend.js
+++ b/lib/search_backend.js
@@ -214,7 +214,7 @@ class SearchBackend {
*/
indexingTotalWorkCalculated(requestId, fileSystemPath, totalWork) {
this._frontend.safeEvaluate((requestId, fileSystemPath, totalWork) => {
- InspectorFrontendAPI.indexingTotalWorkCalculated(requestId, fileSystemPath, totalWork);
+ callFrontend(_ => InspectorFrontendAPI.indexingTotalWorkCalculated(requestId, fileSystemPath, totalWork));
}, requestId, fileSystemPath, totalWork);
}
@@ -225,7 +225,7 @@ class SearchBackend {
*/
indexingWorked(requestId, fileSystemPath, worked) {
this._frontend.safeEvaluate((requestId, fileSystemPath, worked) => {
- InspectorFrontendAPI.indexingWorked(requestId, fileSystemPath, worked);
+ callFrontend(_ => InspectorFrontendAPI.indexingWorked(requestId, fileSystemPath, worked));
}, requestId, fileSystemPath, worked);
}
@@ -235,7 +235,7 @@ class SearchBackend {
*/
indexingDone(requestId, fileSystemPath) {
this._frontend.safeEvaluate((requestId, fileSystemPath) => {
- InspectorFrontendAPI.indexingDone(requestId, fileSystemPath);
+ callFrontend(_ => InspectorFrontendAPI.indexingDone(requestId, fileSystemPath));
}, requestId, fileSystemPath);
}
@@ -246,7 +246,7 @@ class SearchBackend {
*/
searchCompleted(requestId, fileSystemPath, files) {
this._frontend.safeEvaluate((requestId, fileSystemPath, files) => {
- InspectorFrontendAPI.searchCompleted(requestId, fileSystemPath, files);
+ callFrontend(_ => InspectorFrontendAPI.searchCompleted(requestId, fileSystemPath, files));
}, requestId, fileSystemPath, files);
}
diff --git a/ndb.js b/ndb.js
index <HASH>..<HASH> 100755
--- a/ndb.js
+++ b/ndb.js
@@ -73,6 +73,9 @@ updateNotifier({pkg: require('./package.json')}).notify();
serviceDir: path.join(__dirname, 'services'),
repl: require.resolve('./lib/repl.js')
})};`),
+ frontend.evaluateOnNewDocument(`function callFrontend(f) {
+ ${!!process.env.NDB_DEBUG_FRONTEND ? 'setTimeout(_ => f(), 0)' : 'f()'}
+ }`),
frontend.setRequestInterception(true),
frontend.exposeFunction('openInNewTab', url => require('opn')(url)),
frontend.exposeFunction('copyText', text => require('clipboardy').write(text))
diff --git a/services/services.js b/services/services.js
index <HASH>..<HASH> 100644
--- a/services/services.js
+++ b/services/services.js
@@ -18,9 +18,9 @@ class Services {
static async create(frontend) {
const services = new Services((serviceId, message) => {
- frontend.safeEvaluate(function(serviceId, message) {
- Ndb.serviceManager.notify(serviceId, message);
- }, serviceId, message);
+ frontend.safeEvaluate(function(serviceId, message, isDebugFrontend) {
+ callFrontend(_ => Ndb.serviceManager.notify(serviceId, message));
+ }, serviceId, message, !!process.env.NDB_DEBUG_FRONTEND);
});
await Promise.all([
frontend.exposeFunction('createNdbService', services.createNdbService.bind(services)), | fix(debug_frontend): improve frontend debugging experience (#<I>)
When NDB_DEBUG_FRONTEND is set we should route each call to frontend
through setTimeout, otherwise as soon as we pause at breakpoint on
frontend side, all calls will be processed in incorrect order. | GoogleChromeLabs_ndb | train |
0eda06b5ead3e0e9e05743705eb15d5a2e7ab5fd | diff --git a/lib/saddle/endpoint.rb b/lib/saddle/endpoint.rb
index <HASH>..<HASH> 100644
--- a/lib/saddle/endpoint.rb
+++ b/lib/saddle/endpoint.rb
@@ -24,11 +24,8 @@ module Saddle
# Generic request wrapper
def request(method, action, params={}, options={})
# Augment in interesting options
- options[:saddle] ||= {}
- options[:saddle] = {
- :call_chain => _path_array,
- :action => action,
- }
+ options[:call_chain] = _path_array
+ options[:action] = action
@requester.send(method, _path(action), params, options)
end
diff --git a/lib/saddle/faraday/rack_builder.rb b/lib/saddle/faraday/rack_builder.rb
index <HASH>..<HASH> 100644
--- a/lib/saddle/faraday/rack_builder.rb
+++ b/lib/saddle/faraday/rack_builder.rb
@@ -12,4 +12,4 @@ module Saddle
end
end
-end
\ No newline at end of file
+end
diff --git a/lib/saddle/middleware/logging/rails.rb b/lib/saddle/middleware/logging/rails.rb
index <HASH>..<HASH> 100644
--- a/lib/saddle/middleware/logging/rails.rb
+++ b/lib/saddle/middleware/logging/rails.rb
@@ -15,7 +15,7 @@ module Saddle
@app.call(env)
rescue => e
if defined?(Rails.logger)
- Rails.logger.error("#{env[:saddle][:saddle][:client].name} error: #{e}")
+ Rails.logger.error("#{env[:saddle][:client].name} error: #{e}")
end
# Re-raise the error
raise
diff --git a/lib/saddle/middleware/logging/statsd.rb b/lib/saddle/middleware/logging/statsd.rb
index <HASH>..<HASH> 100644
--- a/lib/saddle/middleware/logging/statsd.rb
+++ b/lib/saddle/middleware/logging/statsd.rb
@@ -35,14 +35,14 @@ module Saddle
# Try to build up a path for the STATSD logging
if env[:saddle][:statsd_path]
statsd_path = env[:saddle][:statsd_path]
- elsif env[:saddle][:saddle]
+ elsif env[:saddle][:client]
statsd_path_components = [
'saddle',
- env[:saddle][:saddle][:client].name.underscore,
+ env[:saddle][:client].name.underscore,
]
- if env[:saddle][:saddle][:call_chain] && env[:saddle][:saddle][:action]
- statsd_path_components += env[:saddle][:saddle][:call_chain]
- statsd_path_components << env[:saddle][:saddle][:action]
+ if env[:saddle][:call_chain] && env[:saddle][:action]
+ statsd_path_components += env[:saddle][:call_chain]
+ statsd_path_components << env[:saddle][:action]
else
statsd_path_components << 'raw'
statsd_path_components << "#{env[:url].host}#{env[:url].path}"
diff --git a/lib/saddle/middleware/request/user_agent.rb b/lib/saddle/middleware/request/user_agent.rb
index <HASH>..<HASH> 100644
--- a/lib/saddle/middleware/request/user_agent.rb
+++ b/lib/saddle/middleware/request/user_agent.rb
@@ -13,7 +13,7 @@ module Saddle
user_agent = nil
# Build a user agent that looks like 'SaddleExample 0.0.1'
begin
- user_agent = client_name = env[:saddle][:saddle][:client].name
+ user_agent = client_name = env[:saddle][:client].name
parent_module = client_name.split('::')[0..-2].join('::').constantize
if parent_module
if defined?(parent_module::VERSION)
diff --git a/lib/saddle/requester.rb b/lib/saddle/requester.rb
index <HASH>..<HASH> 100644
--- a/lib/saddle/requester.rb
+++ b/lib/saddle/requester.rb
@@ -140,9 +140,7 @@ module Saddle
connection.options[:timeout] = @timeout
connection.builder.saddle_options[:request_style] = @request_style
connection.builder.saddle_options[:num_retries] = @num_retries
- connection.builder.saddle_options[:saddle] = {
- :client => @parent_client,
- }
+ connection.builder.saddle_options[:client] = @parent_client
# Support default return values upon exception
connection.use(Saddle::Middleware::Response::DefaultResponse) | Make changes suggested in code review.
Primarily: remove [:saddle][:saddle]. | mLewisLogic_saddle | train |
813f55f60f9538f65a61527994227803bdff35fd | diff --git a/lib/diff-array.js b/lib/diff-array.js
index <HASH>..<HASH> 100644
--- a/lib/diff-array.js
+++ b/lib/diff-array.js
@@ -164,18 +164,16 @@ var diffObjectChanges = function (oldItem, newItem) {
// Diffs two objects and returns the keys that have been removed.
// Can be used to construct a Mongo {$unset: {}} modifier
var diffObjectRemovals = function (oldItem, newItem) {
- if (newItem == null)
- return true;
-
var oldItemKeys = _.keys(oldItem);
var newItemKeys = _.keys(newItem);
+
var result = {};
angular.forEach(oldItemKeys, function (key) {
- if (!_.contains(newItemKeys, key))
+ if (!_.contains(newItemKeys, key) ||
+ angular.isUndefined(newItem[key]))
result[key] = true;
-
- if (isActualObject(oldItem[key])) {
+ else if (isActualObject(oldItem[key])) {
var diff = diffObjectRemovals(oldItem[key], newItem[key]);
if (diff) result[key] = diff;
}
@@ -187,39 +185,34 @@ var diffObjectRemovals = function (oldItem, newItem) {
return flattenObject(result);
};
+var handleDeepProperties = function(object, paths, cb) {
+ angular.forEach(paths, function(value, path) {
+ var props = path.split('.');
+ var currentObject = object;
+
+ for (var i = 0; i < props.length - 1; i++) {
+ currentObject = currentObject[props[i]];
+ }
+
+ cb(currentObject, props[i], value);
+ });
+};
+
// Diffs two objects and returns the keys that have been added or changed.
// Can be used to construct a Mongo {$set: {}} modifier
var deepCopyObjectChanges = function (oldItem, newItem) {
+ var setDiff = diffObjectChanges(oldItem, newItem);
- angular.forEach(newItem, function (value, key) {
- if (oldItem && angular.equals(value, oldItem[key]))
- return;
-
- if (isActualObject(value)) {
- if (!oldItem[key])
- oldItem[key] = value;
- else
- deepCopyObjectChanges(oldItem[key], value);
- } else {
- oldItem[key] = value;
- }
+ handleDeepProperties(oldItem, setDiff, function(object, prop, value) {
+ object[prop] = value;
});
};
var deepCopyObjectRemovals = function (oldItem, newItem) {
- var oldItemKeys = _.keys(oldItem);
- var newItemKeys = _.keys(newItem);
+ var unsetDiff = diffObjectRemovals(oldItem, newItem);
- angular.forEach(oldItemKeys, function (key) {
- if (!_.contains(newItemKeys, key) ||
- angular.isUndefined(newItem[key]) ||
- newItem[key] == null)
- delete oldItem[key];
- else {
- if (isActualObject(oldItem[key])) {
- deepCopyObjectRemovals(oldItem[key], newItem[key]);
- }
- }
+ handleDeepProperties(oldItem, unsetDiff, function(object, prop) {
+ delete object[prop];
});
};
diff --git a/tests/integration/angular-meteor-diff-array-spec.js b/tests/integration/angular-meteor-diff-array-spec.js
index <HASH>..<HASH> 100644
--- a/tests/integration/angular-meteor-diff-array-spec.js
+++ b/tests/integration/angular-meteor-diff-array-spec.js
@@ -3,11 +3,13 @@ describe('diffArray module', function() {
describe('diffArray service', function() {
var diffArray,
- deepCopyRemovals;
+ deepCopyRemovals,
+ deepCopyChanges;
- beforeEach(angular.mock.inject(function(_diffArray_, _deepCopyRemovals_) {
+ beforeEach(angular.mock.inject(function(_diffArray_, _deepCopyRemovals_, _deepCopyChanges_) {
diffArray = _diffArray_;
deepCopyRemovals = _deepCopyRemovals_;
+ deepCopyChanges = _deepCopyChanges_;
}));
it('should notify addedAt and changedAt changes between two arrays', function() {
@@ -68,6 +70,27 @@ describe('diffArray module', function() {
expect(oldItem).toEqual(newItem);
});
+
+ it('should not remove fields with null value', function() {
+ var oldItem = {_id: 1, field : 0, another : 3};
+ var newItem = {_id: 1, field : 0, another: null};
+ var oldItemBefore = angular.copy(oldItem);
+
+ deepCopyRemovals(oldItem, newItem);
+
+ expect(oldItem).toEqual(oldItemBefore);
+ });
+ });
+
+ describe('deepCopyChanges', function() {
+ it('should copy null values', function() {
+ var oldItem = {_id: 1, field : 0, another : 3};
+ var newItem = {_id: 1, field : 0, another: null};
+
+ deepCopyChanges(oldItem, newItem);
+
+ expect(oldItem).toEqual(newItem);
+ });
});
});
}); | (refractor): unite the change functions (diff and copy) to reuse each other. | Urigo_angular-meteor | train |
c102dc8ba21b2077068afe428915f2208cd932ef | diff --git a/soda/commands/commands.go b/soda/commands/commands.go
index <HASH>..<HASH> 100644
--- a/soda/commands/commands.go
+++ b/soda/commands/commands.go
@@ -13,6 +13,12 @@ import (
// _ "github.com/mattes/migrate/driver/sqlite3"
)
+var commonFlags = []cli.Flag{
+ EnvFlag,
+ ConfigFlag,
+ DebugFlag,
+}
+
var EnvFlag = cli.StringFlag{
Name: "e",
Value: "development",
@@ -30,6 +36,11 @@ var DebugFlag = cli.BoolFlag{
Usage: "Debug/verbose mode",
}
+func commandInit(c *cli.Context) {
+ pop.Debug = c.Bool("d")
+ setConfigLocation(c)
+}
+
func getEnv(c *cli.Context) string {
return defaults.String(os.Getenv("GO_ENV"), c.String("e"))
}
diff --git a/soda/commands/create.go b/soda/commands/create.go
index <HASH>..<HASH> 100644
--- a/soda/commands/create.go
+++ b/soda/commands/create.go
@@ -11,18 +11,15 @@ import (
func Create() cli.Command {
return cli.Command{
Name: "create",
- Flags: []cli.Flag{
- EnvFlag,
- ConfigFlag,
+ Flags: append(commonFlags,
cli.BoolFlag{
Name: "all",
Usage: "Creates all of the databases in the database.yml",
},
- DebugFlag,
- },
+ ),
Usage: "Creates databases for you",
Action: func(c *cli.Context) {
- pop.Debug = c.Bool("d")
+ commandInit(c)
if c.Bool("all") {
for _, conn := range pop.Connections {
createDB(conn)
diff --git a/soda/commands/drop.go b/soda/commands/drop.go
index <HASH>..<HASH> 100644
--- a/soda/commands/drop.go
+++ b/soda/commands/drop.go
@@ -11,30 +11,27 @@ import (
func Drop() cli.Command {
return cli.Command{
Name: "drop",
- Flags: []cli.Flag{
- EnvFlag,
- ConfigFlag,
+ Flags: append(commonFlags,
cli.BoolFlag{
Name: "all",
Usage: "Drops all of the databases in the database.yml",
},
- DebugFlag,
- },
+ ),
Usage: "Drops databases for you",
Action: func(c *cli.Context) {
- pop.Debug = c.Bool("d")
+ commandInit(c)
if c.Bool("all") {
for _, conn := range pop.Connections {
- dropDB(conn)
+ Dropper(conn)
}
} else {
- dropDB(getConn(c))
+ Dropper(getConn(c))
}
},
}
}
-func dropDB(c *pop.Connection) error {
+func Dropper(c *pop.Connection) error {
var err error
if c.Dialect.Details().Database != "" {
err = c.Dialect.DropDB()
diff --git a/soda/commands/migrate.go b/soda/commands/migrate.go
index <HASH>..<HASH> 100644
--- a/soda/commands/migrate.go
+++ b/soda/commands/migrate.go
@@ -26,19 +26,16 @@ the `migrate` binary being installed, and this makes life a lot nicer.
func Migrate() cli.Command {
return cli.Command{
Name: "migrate",
- Flags: []cli.Flag{
+ Flags: append(commonFlags,
cli.StringFlag{
Name: "path",
Value: "./migrations",
Usage: "Path to the migrations folder",
},
- EnvFlag,
- ConfigFlag,
- DebugFlag,
- },
+ ),
Usage: "Runs migrations against your database.",
Action: func(c *cli.Context) {
- pop.Debug = c.Bool("d")
+ commandInit(c)
cmd := "up"
if len(c.Args()) > 0 {
cmd = c.Args().Get(0)
diff --git a/soda/main.go b/soda/main.go
index <HASH>..<HASH> 100644
--- a/soda/main.go
+++ b/soda/main.go
@@ -11,7 +11,7 @@ func main() {
app := cli.NewApp()
app.Name = "soda"
app.Usage = "A tasty treat for all your database needs"
- app.Version = "2.6.1"
+ app.Version = "2.6.2"
app.Commands = []cli.Command{
commands.Migrate(), | fixed issue with create/drop not working | gobuffalo_pop | train |
deddd1fff00039f83faa054aab6bc90e8dc00e9e | diff --git a/corc-core/src/main/java/com/hotels/corc/mapred/CorcInputFormat.java b/corc-core/src/main/java/com/hotels/corc/mapred/CorcInputFormat.java
index <HASH>..<HASH> 100644
--- a/corc-core/src/main/java/com/hotels/corc/mapred/CorcInputFormat.java
+++ b/corc-core/src/main/java/com/hotels/corc/mapred/CorcInputFormat.java
@@ -168,6 +168,7 @@ public class CorcInputFormat implements InputFormat<NullWritable, Corc> {
*/
static void setReadColumns(Configuration conf, StructTypeInfo actualStructTypeInfo) {
StructTypeInfo readStructTypeInfo = getTypeInfo(conf);
+ LOG.info("Read StructTypeInfo: {}", readStructTypeInfo);
List<Integer> ids = new ArrayList<>();
List<String> names = new ArrayList<>();
@@ -189,8 +190,11 @@ public class CorcInputFormat implements InputFormat<NullWritable, Corc> {
ids.add(i);
names.add(actualName);
}
- LOG.debug("Set column projection on columns: {} ({})", ids, readNames);
}
+ if (ids.size() == 0) {
+ throw new IllegalStateException("None of the selected columns were found in the ORC file.");
+ }
+ LOG.info("Set column projection on columns: {} ({})", ids, names);
ColumnProjectionUtils.appendReadColumns(conf, ids, names);
}
@@ -215,8 +219,10 @@ public class CorcInputFormat implements InputFormat<NullWritable, Corc> {
public RecordReader<NullWritable, Corc> getRecordReader(InputSplit inputSplit, JobConf conf, Reporter reporter)
throws IOException {
StructTypeInfo typeInfo = getSchemaTypeInfo(conf);
+ LOG.info("Conf StructTypeInfo: {}", typeInfo);
if (typeInfo == null) {
typeInfo = readStructTypeInfoFromSplit(inputSplit, conf);
+ LOG.info("File StructTypeInfo: {}", typeInfo);
}
setReadColumns(conf, typeInfo);
RecordReader<NullWritable, OrcStruct> reader = orcInputFormat.getRecordReader(inputSplit, conf, reporter);
diff --git a/corc-core/src/test/java/com/hotels/corc/mapred/CorcInputFormatTest.java b/corc-core/src/test/java/com/hotels/corc/mapred/CorcInputFormatTest.java
index <HASH>..<HASH> 100644
--- a/corc-core/src/test/java/com/hotels/corc/mapred/CorcInputFormatTest.java
+++ b/corc-core/src/test/java/com/hotels/corc/mapred/CorcInputFormatTest.java
@@ -266,6 +266,18 @@ public class CorcInputFormatTest {
}
@Test(expected = IllegalStateException.class)
+ public void setInputReadColumnsAllMissing() {
+ StructTypeInfo typeInfo = new StructTypeInfoBuilder()
+ .add("a", TypeInfoFactory.stringTypeInfo)
+ .add("b", TypeInfoFactory.longTypeInfo)
+ .build();
+
+ conf.set(CorcInputFormat.INPUT_TYPE_INFO, "struct<_col0:string,_col1:bigint>");
+
+ CorcInputFormat.setReadColumns(conf, typeInfo);
+ }
+
+ @Test(expected = IllegalStateException.class)
public void setInputReadColumnsDifferentTypes() {
StructTypeInfo typeInfo = new StructTypeInfoBuilder().add("a", TypeInfoFactory.stringTypeInfo).build(); | Extra logging for declared and selected columns | HotelsDotCom_corc | train |
ccb4f760223c42ebfffda062eb1eaa4f5eeb5c32 | diff --git a/calais.gemspec b/calais.gemspec
index <HASH>..<HASH> 100644
--- a/calais.gemspec
+++ b/calais.gemspec
@@ -41,7 +41,6 @@ Gem::Specification.new do |s|
s.add_dependency("nokogiri", ">= 1.3.3")
s.add_dependency("json", ">= 1.1.3")
- s.add_dependency("curb", ">= 0.1.4")
s.add_development_dependency("rspec", ">= 2.0.0")
end
diff --git a/lib/calais.rb b/lib/calais.rb
index <HASH>..<HASH> 100644
--- a/lib/calais.rb
+++ b/lib/calais.rb
@@ -1,5 +1,6 @@
require 'digest/sha1'
require 'net/http'
+require 'uri'
require 'cgi'
require 'iconv'
require 'set'
@@ -8,7 +9,6 @@ require 'date'
require 'rubygems'
require 'nokogiri'
require 'json'
-require 'curb'
if RUBY_VERSION.to_f < 1.9
$KCODE = "UTF8"
diff --git a/lib/calais/client.rb b/lib/calais/client.rb
index <HASH>..<HASH> 100644
--- a/lib/calais/client.rb
+++ b/lib/calais/client.rb
@@ -27,13 +27,7 @@ module Calais
"paramsXML" => params_xml
}
- @client ||= Curl::Easy.new
- @client.url = @use_beta ? BETA_REST_ENDPOINT : REST_ENDPOINT
- @client.timeout = HTTP_TIMEOUT
-
- post_fields = post_args.map {|k,v| Curl::PostField.content(k, v) }
-
- do_request(post_fields)
+ do_request(post_args)
end
def params_xml
@@ -73,6 +67,10 @@ module Calais
params_node.to_xml(:indent => 2)
end
+ def url
+ @url ||= URI.parse(calais_endpoint)
+ end
+
private
def check_params
raise 'missing content' if @content.nil? || @content.empty?
@@ -103,11 +101,13 @@ module Calais
end
def do_request(post_fields)
- unless @client.http_post(post_fields)
- raise 'unable to post to api endpoint'
- end
+ @request ||= Net::HTTP::Post.new(url.path)
+ @request.set_form_data(post_fields)
+ Net::HTTP.new(url.host, url.port).start {|http| http.request(@request)}.body
+ end
- @client.body_str
+ def calais_endpoint
+ @use_beta ? BETA_REST_ENDPOINT : REST_ENDPOINT
end
end
-end
\ No newline at end of file
+end
diff --git a/spec/calais/client_spec.rb b/spec/calais/client_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/calais/client_spec.rb
+++ b/spec/calais/client_spec.rb
@@ -66,7 +66,7 @@ describe Calais::Client, :enlighten do
it 'provides access to the enlighten command on the generic rest endpoint' do
@client.should_receive(:do_request).with(anything).and_return(SAMPLE_RESPONSE)
@client.enlighten
- @client.instance_variable_get(:@client).url.should == Calais::REST_ENDPOINT
+ @client.url.should == URI.parse(Calais::REST_ENDPOINT)
end
it 'provides access to the enlighten command on the beta rest endpoint' do
@@ -74,6 +74,6 @@ describe Calais::Client, :enlighten do
@client.should_receive(:do_request).with(anything).and_return(SAMPLE_RESPONSE)
@client.enlighten
- @client.instance_variable_get(:@client).url.should == Calais::BETA_REST_ENDPOINT
+ @client.url.should == URI.parse(Calais::BETA_REST_ENDPOINT)
end
end | Removes curb dependency in favor of ruby core net/http | abhay_calais | train |
e3cd8e7be2154e7e1618325e57d68e3adc0b27ac | diff --git a/install/local/addPortableSharedLibraries.php b/install/local/addPortableSharedLibraries.php
index <HASH>..<HASH> 100644
--- a/install/local/addPortableSharedLibraries.php
+++ b/install/local/addPortableSharedLibraries.php
@@ -41,4 +41,5 @@ $registry->registerFromFile('OAT/util/EventMgr', $installBasePath . '/OAT/util/E
$registry->registerFromFile('OAT/util/event', $installBasePath . '/OAT/util/event.js');
$registry->registerFromFile('OAT/sts/common', $installBasePath . '/OAT/sts/common.js');
$registry->registerFromFile('OAT/interact', $installBasePath . '/OAT/interact.js');
-$registry->registerFromFile('OAT/interact-rotate', $installBasePath . '/OAT/interact-rotate.js');
\ No newline at end of file
+$registry->registerFromFile('OAT/interact-rotate', $installBasePath . '/OAT/interact-rotate.js');
+$registry->registerFromFile('OAT/sts/transform-helper', $installBasePath . '/OAT/sts/transform-helper.js');
\ No newline at end of file
diff --git a/manifest.php b/manifest.php
index <HASH>..<HASH> 100755
--- a/manifest.php
+++ b/manifest.php
@@ -26,7 +26,7 @@ return array(
'label' => 'QTI item model',
'description' => 'TAO QTI item model',
'license' => 'GPL-2.0',
- 'version' => '2.7.1',
+ 'version' => '2.7.2',
'author' => 'Open Assessment Technologies',
'requires' => array(
'taoItems' => '>=2.6'
diff --git a/scripts/update/Updater.php b/scripts/update/Updater.php
index <HASH>..<HASH> 100644
--- a/scripts/update/Updater.php
+++ b/scripts/update/Updater.php
@@ -72,6 +72,14 @@ class Updater extends \common_ext_ExtensionUpdater
$currentVersion = '2.7.1';
}
+ //migrate from 2.7.0 to 2.7.1
+ if($currentVersion == '2.7.1'){
+
+ $registry->registerFromFile('OAT/sts/transform-helper', $installBasePath . '/OAT/sts/transform-helper.js');
+
+ $currentVersion = '2.7.2';
+ }
+
return $currentVersion;
} | added transform-helper to install/update routine | oat-sa_extension-tao-itemqti | train |
07f06f1ef84153d9686d78bf67a11e9185c53bf6 | diff --git a/neo/Prompt/Commands/Invoke.py b/neo/Prompt/Commands/Invoke.py
index <HASH>..<HASH> 100644
--- a/neo/Prompt/Commands/Invoke.py
+++ b/neo/Prompt/Commands/Invoke.py
@@ -30,6 +30,7 @@ from neo.Fixed8 import Fixed8
from neo.Core.Blockchain import Blockchain
+from neo.VM.OpCode import *
from neo.BigInteger import BigInteger
import traceback
import pdb
@@ -106,9 +107,10 @@ def TestInvokeContract(wallet, args):
if type(item) is list:
listlength = len(item)
- sb.push(listlength)
for listitem in item:
sb.push(listitem)
+ sb.push(listlength)
+ sb.Emit(PACK)
else:
sb.push(item) | put array length and PACK at end of array | CityOfZion_neo-python | train |
268c77e641f92950426c14a0dcf2743f1c34bfe9 | diff --git a/emma2/coordinates/transform/masstransform/filetransform.py b/emma2/coordinates/transform/masstransform/filetransform.py
index <HASH>..<HASH> 100644
--- a/emma2/coordinates/transform/masstransform/filetransform.py
+++ b/emma2/coordinates/transform/masstransform/filetransform.py
@@ -10,7 +10,7 @@ This could be a file format transformation, a coordinate transformation, or a cl
import os
import fnmatch
-class FileTransform:
+class FileTransform(object):
def __init__(self,
name,
transformer, | derive transform class from 'object', to make usage of 'isinstance' work | markovmodel_PyEMMA | train |
87b04cac813bf5c5795998b3c1b75cf3c676bf87 | diff --git a/lib/usb_connection.js b/lib/usb_connection.js
index <HASH>..<HASH> 100644
--- a/lib/usb_connection.js
+++ b/lib/usb_connection.js
@@ -1,7 +1,8 @@
var util = require('util'),
Duplex = require('stream').Duplex,
Promise = require('bluebird'),
- EventEmitter = require('events').EventEmitter;
+ EventEmitter = require('events').EventEmitter,
+ logs = require('./logs');
var haveusb = true;
try {
@@ -62,17 +63,31 @@ USBConnection.prototype._write = function(chunk, enc, callback) {
};
USBConnection.prototype._read = function() {
- var self = this;
-
- if (self.closed) {
- return self.push(null);
+ if (this.closed) {
+ return this.push(null);
}
+};
- self.epIn.transfer(4096, function(err, data) {
- if (err) {
- self.emit('error', err);
+USBConnection.prototype._receiveMessages = function() {
+ var self = this;
+ // Default transfer size
+ var transferSize = 4096;
+ // Start polling
+ self.epIn.startPoll(2, transferSize);
+
+ // When we get data, push it into the stream
+ self.epIn.on('data', self.push.bind(self));
+
+ // Report errors as they arise
+ self.epIn.on('error', function(e) {
+ // If this stream was already closed, just return
+ if (self.closed) {
+ return;
} else {
- self.push(data);
+ // Otherwise print the error
+ logs.error('Error reading USB message endpoint:', e);
+ // Return a non-zero return code
+ process.exit(-5);
}
});
};
@@ -117,9 +132,10 @@ USBConnection.prototype.open = function() {
}
self.serialNumber = data;
-
// Register this connection with daemon (keeps track of active remote processes)
Daemon.register(self);
+ // Start receiving messages
+ self._receiveMessages();
// If all is well, resolve the promise with the valid connection
return resolve(self);
}); | Switch to USB data streaming rather than transfer | tessel_t2-cli | train |
63ca34f18b4cd153a042cac570fa2fa087b709a3 | diff --git a/OpenPNM/Network/__DelaunayCubic__.py b/OpenPNM/Network/__DelaunayCubic__.py
index <HASH>..<HASH> 100644
--- a/OpenPNM/Network/__DelaunayCubic__.py
+++ b/OpenPNM/Network/__DelaunayCubic__.py
@@ -46,6 +46,8 @@ class DelaunayCubic(Delaunay):
self._arr = np.atleast_3d(np.empty(shape))
elif template != None:
self._arr = sp.array(template,ndmin=3,dtype=bool)
+ else:
+ self._arr = np.atleast_3d(np.empty([3,3,3]))
self._shape = sp.shape(self._arr) # Store original network shape
self._spacing = sp.asarray(spacing) # Store network spacing instead of calculating it | Make sure DelaunayCubic works with no arguments | PMEAL_OpenPNM | train |
a17d8f5e51e33e59d56f70c79c2115dc99e2e676 | diff --git a/lib/Cldr.js b/lib/Cldr.js
index <HASH>..<HASH> 100644
--- a/lib/Cldr.js
+++ b/lib/Cldr.js
@@ -444,13 +444,21 @@ Cldr.prototype = {
});
}
- if (options.exemplarCharacters) {
+ if (options.characters) {
localeData.exemplarCharacters = {};
find("/ldml/characters/exemplarCharacters").forEach(function (exemplarCharactersNode) {
var typeAttr = exemplarCharactersNode.attr('type'),
type = (typeAttr && typeAttr.value()) || 'default';
localeData.exemplarCharacters[type] = localeData.exemplarCharacters[type] || exemplarCharactersNode.text().replace(/^\[|\]$/g, '').split(" ");
});
+ localeData.ellipsis = {};
+ find("/ldml/characters/ellipsis").forEach(function (ellipsisNode) {
+ var type = ellipsisNode.attr('type').value();
+ localeData.ellipsis[type] = localeData.ellipsis[type] || ellipsisNode.text();
+ });
+ find("/ldml/characters/moreInformation").forEach(function (moreInformationNode) {
+ localeData.moreInformation = localeData.moreInformation || moreInformationNode.text();
+ });
}
if (options.timeZones) { | --exemplarcharacters => --characters, include ellipsis and moreInformation. | papandreou_node-cldr | train |
c509dfd5d7ba03cccfed2598c13e4191018f93e7 | diff --git a/lib/index.js b/lib/index.js
index <HASH>..<HASH> 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -6,11 +6,11 @@ import EventEmitter from 'events'
// Packages
import bytes from 'bytes'
import chalk from 'chalk'
-import retry from 'async-retry'
-import {parse as parseIni} from 'ini'
-import {readFile} from 'fs-promise'
import resumer from 'resumer'
+import retry from 'async-retry'
import splitArray from 'split-array'
+import {parse as parseIni} from 'ini'
+import {readFile, stat} from 'fs-promise'
// Ours
import {npm as getNpmFiles, docker as getDockerFiles} from './get-files'
@@ -124,6 +124,25 @@ export default class Now extends EventEmitter {
console.time('> [debug] /now/create')
}
+ // Flatten the array to contain files to sync where each nested input
+ // array has a group of files with the same sha but different path
+ const files = await Promise.all(Array.prototype.concat.apply([], await Promise.all((Array.from(this._files)).map(async ([sha, {data, names}]) => {
+ return await names.map(async name => {
+ if (this._static && toRelative(name, this._path) !== 'package.json') {
+ name = this.pathInsideContent(name)
+ }
+
+ const st = await stat(name)
+
+ return {
+ sha,
+ size: data.length,
+ file: toRelative(name, this._path),
+ mode: st.mode
+ }
+ })
+ }))))
+
const res = await this._fetch('/now/create', {
method: 'POST',
body: {
@@ -135,21 +154,7 @@ export default class Now extends EventEmitter {
description,
deploymentType,
registryAuthToken: authToken,
- // Flatten the array to contain files to sync where each nested input
- // array has a group of files with the same sha but different path
- files: Array.prototype.concat.apply([], Array.from(this._files).map(([sha, {data, names}]) => {
- return names.map(n => {
- if (this._static && toRelative(n, this._path) !== 'package.json') {
- n = this.pathInsideContent(n)
- }
-
- return {
- sha,
- size: data.length,
- file: toRelative(n, this._path)
- }
- })
- })),
+ files,
engines
}
}) | Support basic file modes (#<I>)
now-cli should pass file mode bits when creating a deployment. | zeit_now-cli | train |
3fed554f45717290ca74e798ff0d5523ff051c32 | diff --git a/src/main/java/com/netflix/zeno/fastblob/state/FastBlobTypeDeserializationState.java b/src/main/java/com/netflix/zeno/fastblob/state/FastBlobTypeDeserializationState.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/netflix/zeno/fastblob/state/FastBlobTypeDeserializationState.java
+++ b/src/main/java/com/netflix/zeno/fastblob/state/FastBlobTypeDeserializationState.java
@@ -193,6 +193,20 @@ public class FastBlobTypeDeserializationState<T> implements Iterable<T> {
return count;
}
+ /**
+ * Returns the current maximum ordinal for this type. Returns -1 if this type has no objects.
+ *
+ * @return
+ */
+ public int maxOrdinal() {
+ int ordinal = objects.size();
+ while(--ordinal >= 0) {
+ if(objects.get(ordinal) != null)
+ return ordinal;
+ }
+ return -1;
+ }
+
@Override
public Iterator<T> iterator() {
return new TypeDeserializationStateIterator<T>(objects); | Adding maxOrdinal method to FastBlobTypeDeserialization state, required by FlatBlob | Netflix_zeno | train |
407ce02efaed63bfef8a4e386bd9f00805fbe148 | diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/PlanOptimizersFactory.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/PlanOptimizersFactory.java
index <HASH>..<HASH> 100644
--- a/presto-main/src/main/java/com/facebook/presto/sql/planner/PlanOptimizersFactory.java
+++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/PlanOptimizersFactory.java
@@ -45,7 +45,8 @@ public class PlanOptimizersFactory
new LimitPushDown(), // Run the LimitPushDown after flattening set operators to make it easier to do the set flattening
new PredicatePushDown(metadata),
new MergeProjections(),
- new SimplifyExpressions(metadata)); // Re-run the SimplifyExpressions to simplify any recomposed expressions from other optimizations
+ new SimplifyExpressions(metadata), // Re-run the SimplifyExpressions to simplify any recomposed expressions from other optimizations
+ new PruneUnreferencedOutputs()); // Prune outputs again in case predicate pushdown move predicates all the way into the table scan
// TODO: figure out how to improve the set flattening optimizer so that it can run at any point
this.optimizers = builder.build(); | Run prune unreferenced outputs one more time for predicate pushdown | prestodb_presto | train |
11a3e27db536f70984ee3fc988c22a5b2aa300ac | diff --git a/lib/Context/Process.php b/lib/Context/Process.php
index <HASH>..<HASH> 100644
--- a/lib/Context/Process.php
+++ b/lib/Context/Process.php
@@ -98,7 +98,7 @@ class Process implements Context {
$command = \implode(" ", [
\escapeshellarg($binary),
$this->formatOptions($options),
- $scriptPath,
+ \escapeshellarg($scriptPath),
$script,
]); | Escape script path in Process command (#<I>) | amphp_parallel | train |
be9ee41c13e767aa8179b5a49d2808933b17ac88 | diff --git a/app/controllers/UsersController.java b/app/controllers/UsersController.java
index <HASH>..<HASH> 100644
--- a/app/controllers/UsersController.java
+++ b/app/controllers/UsersController.java
@@ -172,7 +172,7 @@ public class UsersController extends AuthenticatedController {
User user = userService.load(username);
if (user != null) {
Map<String, Object> result = Maps.newHashMap();
- result.put("preferences", initDefaultPreferences(user.getPreferences()));
+ result.put("preferences", user.getPreferences());
// TODO: there is more than preferences
return ok(Json.toJson(result));
} else {
@@ -196,19 +196,6 @@ public class UsersController extends AuthenticatedController {
}
}
- private Map<String, Object> initDefaultPreferences(Map<String, Object> preferences) {
- Map<String, Object> effectivePreferences = Maps.newHashMap();
- // TODO: Move defaults into a static map once we have more preferences
- effectivePreferences.put("updateUnfocussed", false);
- effectivePreferences.put("disableExpensiveUpdates", false);
- effectivePreferences.put("enableSmartSearch", false);
- effectivePreferences.put("enableNewWidgets", true);
- if (preferences != null) {
- effectivePreferences.putAll(preferences);
- }
- return effectivePreferences;
- }
-
private Map<String, Object> normalizePreferences(Map<String, Object> preferences) {
Map<String, Object> normalizedPreferences = Maps.newHashMap();
// TODO: Move types into a static map once we have more preferences | Rely on graylog server to manage user preferences | Graylog2_graylog2-server | train |
beb1a013db3b31498f479854c9bbfe6fc4a9b98f | diff --git a/api/tasks.go b/api/tasks.go
index <HASH>..<HASH> 100644
--- a/api/tasks.go
+++ b/api/tasks.go
@@ -103,6 +103,9 @@ type ReschedulePolicy struct {
}
func (r *ReschedulePolicy) Merge(rp *ReschedulePolicy) {
+ if rp == nil {
+ return
+ }
if rp.Interval != nil {
r.Interval = rp.Interval
}
@@ -432,7 +435,7 @@ func (g *TaskGroup) Canonicalize(job *Job) {
}
}
- if defaultReschedulePolicy != nil && g.ReschedulePolicy != nil {
+ if defaultReschedulePolicy != nil {
defaultReschedulePolicy.Merge(g.ReschedulePolicy)
g.ReschedulePolicy = defaultReschedulePolicy
} | Always merge with default reschedule policy if its not nil | hashicorp_nomad | train |
735f53fab7b34cc6d4465217ac88843ebbf0e5e4 | diff --git a/elpy/ropebackend.py b/elpy/ropebackend.py
index <HASH>..<HASH> 100644
--- a/elpy/ropebackend.py
+++ b/elpy/ropebackend.py
@@ -89,7 +89,6 @@ class RopeBackend(object):
except (rope.base.exceptions.BadIdentifierError,
rope.base.exceptions.ModuleSyntaxError,
IndentationError,
- IndexError,
LookupError):
# Rope can't parse this file
return []
@@ -175,7 +174,6 @@ class RopeBackend(object):
except (rope.base.exceptions.BadIdentifierError,
rope.base.exceptions.ModuleSyntaxError,
IndentationError,
- IndexError,
LookupError):
# Rope can't parse this file
return None
diff --git a/elpy/tests/support.py b/elpy/tests/support.py
index <HASH>..<HASH> 100644
--- a/elpy/tests/support.py
+++ b/elpy/tests/support.py
@@ -103,10 +103,20 @@ class GenericRPCTests(object):
self.rpc(filename, source, offset)
def test_should_not_fail_for_bad_indentation(self):
+ # Bug in Rope: rope#80
source, offset = source_and_offset(
"def foo():\n"
- " print 23_|_\n"
- " print 17\n")
+ " print(23)_|_\n"
+ " print(17)\n")
+ filename = self.project_file("test.py", source)
+
+ self.rpc(filename, source, offset)
+
+ def test_should_not_fail_for_relative_import(self):
+ # Bug in Rope: rope#81 and rope#82
+ source, offset = source_and_offset(
+ "from .. import foo_|_"
+ )
filename = self.project_file("test.py", source)
self.rpc(filename, source, offset)
@@ -122,10 +132,13 @@ class GenericRPCTests(object):
self.rpc(filename, source, offset)
def test_should_not_fail_with_bad_encoding(self):
- source = u'# coding: utf-8X\n'
+ # Bug in Rope: rope#83
+ source, offset = source_and_offset(
+ u'# coding: utf-8X_|_\n'
+ )
filename = self.project_file("test.py", source)
- self.rpc(filename, source, 16)
+ self.rpc(filename, source, offset)
def test_should_not_fail_with_form_feed_characters(self):
# Bug in Jedi: jedi#424 | Add comments to indicate which Rope bugs we're testing for. | jorgenschaefer_elpy | train |
25ec571de4210b91c59b92c92258d6dea86d4c67 | diff --git a/database/migrations/create_likes_table.php b/database/migrations/create_likes_table.php
index <HASH>..<HASH> 100755
--- a/database/migrations/create_likes_table.php
+++ b/database/migrations/create_likes_table.php
@@ -1,13 +1,6 @@
<?php
-/*
- * This file is part of Laravel Likeable.
- *
- * (c) Brian Faust <[email protected]>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
+
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
diff --git a/src/Counter.php b/src/Counter.php
index <HASH>..<HASH> 100755
--- a/src/Counter.php
+++ b/src/Counter.php
@@ -1,24 +1,10 @@
<?php
-/*
- * This file is part of Laravel Likeable.
- *
- * (c) Brian Faust <[email protected]>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
+
declare(strict_types=1);
-/*
- * This file is part of Laravel Likeable.
- *
- * (c) Brian Faust <[email protected]>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
+
namespace BrianFaust\Likeable;
diff --git a/src/HasLikesTrait.php b/src/HasLikesTrait.php
index <HASH>..<HASH> 100755
--- a/src/HasLikesTrait.php
+++ b/src/HasLikesTrait.php
@@ -1,24 +1,10 @@
<?php
-/*
- * This file is part of Laravel Likeable.
- *
- * (c) Brian Faust <[email protected]>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
+
declare(strict_types=1);
-/*
- * This file is part of Laravel Likeable.
- *
- * (c) Brian Faust <[email protected]>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
+
namespace BrianFaust\Likeable;
diff --git a/src/Like.php b/src/Like.php
index <HASH>..<HASH> 100755
--- a/src/Like.php
+++ b/src/Like.php
@@ -1,24 +1,10 @@
<?php
-/*
- * This file is part of Laravel Likeable.
- *
- * (c) Brian Faust <[email protected]>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
+
declare(strict_types=1);
-/*
- * This file is part of Laravel Likeable.
- *
- * (c) Brian Faust <[email protected]>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
+
namespace BrianFaust\Likeable;
diff --git a/src/LikeableServiceProvider.php b/src/LikeableServiceProvider.php
index <HASH>..<HASH> 100755
--- a/src/LikeableServiceProvider.php
+++ b/src/LikeableServiceProvider.php
@@ -1,24 +1,10 @@
<?php
-/*
- * This file is part of Laravel Likeable.
- *
- * (c) Brian Faust <[email protected]>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
+
declare(strict_types=1);
-/*
- * This file is part of Laravel Likeable.
- *
- * (c) Brian Faust <[email protected]>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
+
namespace BrianFaust\Likeable;
diff --git a/tests/AbstractTestCase.php b/tests/AbstractTestCase.php
index <HASH>..<HASH> 100644
--- a/tests/AbstractTestCase.php
+++ b/tests/AbstractTestCase.php
@@ -1,24 +1,10 @@
<?php
-/*
- * This file is part of Laravel Likeable.
- *
- * (c) Brian Faust <[email protected]>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
+
declare(strict_types=1);
-/*
- * This file is part of Laravel Likeable.
- *
- * (c) Brian Faust <[email protected]>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
+
namespace BrianFaust\Tests\Likeable;
diff --git a/tests/ServiceProviderTest.php b/tests/ServiceProviderTest.php
index <HASH>..<HASH> 100644
--- a/tests/ServiceProviderTest.php
+++ b/tests/ServiceProviderTest.php
@@ -1,24 +1,10 @@
<?php
-/*
- * This file is part of Laravel Likeable.
- *
- * (c) Brian Faust <[email protected]>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
+
declare(strict_types=1);
-/*
- * This file is part of Laravel Likeable.
- *
- * (c) Brian Faust <[email protected]>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
+
namespace BrianFaust\Tests\Likeable; | Try to fix the mess StyleCI makes | faustbrian_Laravel-Likeable | train |
efd383703a6cbd5b78456417ad04bcc33d4b42ba | diff --git a/salesforce/fields.py b/salesforce/fields.py
index <HASH>..<HASH> 100644
--- a/salesforce/fields.py
+++ b/salesforce/fields.py
@@ -64,9 +64,9 @@ class SalesforceAutoField(fields.AutoField):
def contribute_to_class(self, cls, name):
name = name if self.name is None else self.name
- if name != SF_PK or not self.primary_key:
- raise ImproperlyConfigured("SalesforceAutoField must be a primary key "
- "with name '%s' (as configured by settings)." % SF_PK)
+ if name != SF_PK or not self.primary_key or not self.auto_created:
+ raise ImproperlyConfigured("SalesforceAutoField must be an auto created "
+ "primary key with name '%s' (as configured by settings)." % SF_PK)
if cls._meta.has_auto_field:
if (type(self) == type(cls._meta.auto_field) and self.model._meta.abstract and
cls._meta.auto_field.name == SF_PK):
diff --git a/salesforce/models.py b/salesforce/models.py
index <HASH>..<HASH> 100644
--- a/salesforce/models.py
+++ b/salesforce/models.py
@@ -92,7 +92,8 @@ class SalesforceModel(with_metaclass(SalesforceModelBase, models.Model)):
# Name of primary key 'Id' can be easily changed to 'id'
# by "settings.SF_PK='id'".
- Id = fields.SalesforceAutoField(primary_key=True, name=SF_PK, db_column='Id')
+ id = fields.SalesforceAutoField(primary_key=True, name=SF_PK, db_column='Id',
+ verbose_name='ID', auto_created=True)
Model = SalesforceModel | Migrations: more similar to normal migrations in Django. | django-salesforce_django-salesforce | train |
198740af3e778f413d89c4acf70a5bafd180b8d6 | diff --git a/upoints/utils.py b/upoints/utils.py
index <HASH>..<HASH> 100644
--- a/upoints/utils.py
+++ b/upoints/utils.py
@@ -175,7 +175,7 @@ def repr_assist(obj, remap=None):
data.append(str(value))
return obj.__class__.__name__ + '(' + ", ".join(data) + ')'
-def prepare_read(data, method="readlines"):
+def prepare_read(data, method="readlines", mode="r"):
"""Prepare various input types for parsing
>>> prepare_read(open("real_file"))
@@ -191,6 +191,8 @@ def prepare_read(data, method="readlines"):
Data to read
method : `str`
Method to process data with
+ mode : `str`
+ Custom mode to process with, if data is a file
:rtype: `list`
:return: List suitable for parsing
:raise TypeError: Invalid value for data
@@ -202,7 +204,7 @@ def prepare_read(data, method="readlines"):
if method == "read":
return "".join(data)
elif isinstance(data, basestring):
- data = getattr(open(data), method)()
+ data = getattr(open(data, mode), method)()
else:
raise TypeError("Unable to handle data of type `%s`" % type(data))
return data | Added support for custom modes to prepare_read function. | JNRowe_upoints | train |
0bf6c57a473137d6bb2763ad528c4df7ae7d0961 | diff --git a/src/RunningTool.php b/src/RunningTool.php
index <HASH>..<HASH> 100644
--- a/src/RunningTool.php
+++ b/src/RunningTool.php
@@ -44,14 +44,11 @@ class RunningTool
return $this->allowedErrorsCount;
}
- public function areErrorsIgnored()
+ public function analyzeResult($hasNoOutput = false)
{
- return !is_numeric($this->allowedErrorsCount);
- }
-
- public function analyzeResult()
- {
- if (!$this->errorsXPath) {
+ if ($hasNoOutput) {
+ return $this->evaluteErrorsCount($this->process->getExitCode() ? 1 : 0);
+ } elseif (!$this->errorsXPath) {
return [true, ''];
} elseif (!file_exists($this->getMainXml())) {
return [false, 0];
@@ -59,10 +56,20 @@ class RunningTool
$xml = simplexml_load_file($this->getMainXml());
$errorsCount = count($xml->xpath($this->errorsXPath));
+ return $this->evaluteErrorsCount($errorsCount);
+ }
+
+ private function evaluteErrorsCount($errorsCount)
+ {
$isOk = $errorsCount <= $this->allowedErrorsCount || $this->areErrorsIgnored();
return [$isOk, $errorsCount];
}
+ private function areErrorsIgnored()
+ {
+ return !is_numeric($this->allowedErrorsCount);
+ }
+
public function getXmlFiles()
{
return $this->xmlFiles;
diff --git a/src/Task/TableSummary.php b/src/Task/TableSummary.php
index <HASH>..<HASH> 100644
--- a/src/Task/TableSummary.php
+++ b/src/Task/TableSummary.php
@@ -34,10 +34,8 @@ class TableSummary
$totalErrors = 0;
$failedTools = [];
foreach ($usedTools as $tool) {
- list($isOk, $errorsCount) = $this->options->isSavedToFiles ?
- $tool->analyzeResult() :
- array($tool->process->getExitCode() <= $tool->getAllowedErrorsCount() || $tool->areErrorsIgnored(), $tool->process->getExitCode());
- $totalErrors += $this->options->isSavedToFiles ? ((int) $errorsCount) : ((int) $isOk);
+ list($isOk, $errorsCount) = $tool->analyzeResult(!$this->options->isSavedToFiles);
+ $totalErrors += (int) $errorsCount;
$row = array(
"<comment>{$tool}</comment>",
$tool->getAllowedErrorsCount(),
diff --git a/tests/RunningToolTest.php b/tests/RunningToolTest.php
index <HASH>..<HASH> 100644
--- a/tests/RunningToolTest.php
+++ b/tests/RunningToolTest.php
@@ -47,4 +47,25 @@ class RunningToolTest extends \PHPUnit_Framework_TestCase
'failure when errors count > allowed count' => [$this->errorsCountInXmlFile - 1, false],
];
}
+
+ /** @dataProvider provideProcess */
+ public function testAnalyzeExitCodeInCliMode($allowedErrors, $exitCode, array $expectedResult)
+ {
+ $tool = new RunningTool('tool', [
+ 'allowedErrorsCount' => $allowedErrors
+ ]);
+ $tool->process = $this->prophesize('Symfony\Component\Process\Process')
+ ->getExitCode()->willReturn($exitCode)
+ ->getObjectProphecy()->reveal();
+ assertThat($tool->analyzeResult(true), is($expectedResult));
+ }
+
+ public function provideProcess()
+ {
+ return [
+ 'success when exit code = 0' => [0, 0, [true, 0]],
+ 'success when exit code <= allowed code' => [1, 1, [true, 1]],
+ 'failure when errors count > allowed count but errors count is always one' => [0, 2, [false, 1]],
+ ];
+ }
} | Summary - extract analyzing exit code | EdgedesignCZ_phpqa | train |
25fdad98f2ab818eb92bf9600356e206f9eeef54 | diff --git a/src/lib/compile-route.js b/src/lib/compile-route.js
index <HASH>..<HASH> 100644
--- a/src/lib/compile-route.js
+++ b/src/lib/compile-route.js
@@ -186,7 +186,6 @@ const generateMatcher = (route, config) => {
}
const limitMatcher = (route) => {
-
if (!route.repeat) {
return;
}
diff --git a/src/lib/index.js b/src/lib/index.js
index <HASH>..<HASH> 100644
--- a/src/lib/index.js
+++ b/src/lib/index.js
@@ -14,7 +14,8 @@ FetchMock.config = {
FetchMock.createInstance = function () {
const instance = Object.create(FetchMock);
- instance.routes = (this.routes || []).slice();
+ instance._uncompiledRoutes = (this._uncompiledRoutes || []).slice();
+ instance.routes = instance._uncompiledRoutes.map(config => instance.compileRoute(config));
instance.fallbackResponse = this.fallbackResponse || undefined;
instance.config = Object.assign({}, this.config || FetchMock.config);
instance._calls = {};
diff --git a/src/lib/inspecting.js b/src/lib/inspecting.js
index <HASH>..<HASH> 100644
--- a/src/lib/inspecting.js
+++ b/src/lib/inspecting.js
@@ -93,4 +93,4 @@ FetchMock.done = function (name) {
.filter(bool => !bool).length === 0
};
-module.exports = FetchMock;
\ No newline at end of file
+module.exports = FetchMock;
diff --git a/src/lib/set-up-and-tear-down.js b/src/lib/set-up-and-tear-down.js
index <HASH>..<HASH> 100644
--- a/src/lib/set-up-and-tear-down.js
+++ b/src/lib/set-up-and-tear-down.js
@@ -24,6 +24,7 @@ FetchMock.mock = function (matcher, response, options = {}) {
const getMatcher = (route, propName) => (route2) => route[propName] === route2[propName];
FetchMock.addRoute = function (route) {
+ this._uncompiledRoutes.push(route);
route = this.compileRoute(route);
const clashes = this.routes.filter(getMatcher(route, 'name'));
@@ -91,6 +92,7 @@ FetchMock.restore = function () {
}
this.fallbackResponse = undefined;
this.routes = [];
+ this._uncompiledRoutes = [];
this.reset();
return this;
}
@@ -103,4 +105,4 @@ FetchMock.reset = function () {
return this;
}
-module.exports = FetchMock;
\ No newline at end of file
+module.exports = FetchMock;
diff --git a/test/specs/repeat.test.js b/test/specs/repeat.test.js
index <HASH>..<HASH> 100644
--- a/test/specs/repeat.test.js
+++ b/test/specs/repeat.test.js
@@ -128,6 +128,67 @@ module.exports = (fetchMock) => {
console.warn.restore();//eslint-disable-line
});
+ describe('sandbox isolation', () => {
+ it('doesn\'t propagate to children of global', () => {
+ fm
+ .mock('http://it.at.there/', 200, {repeat: 1});
+
+ const sb1 = fm.sandbox();
+
+ fm.fetchHandler('http://it.at.there/');
+
+ expect(fm.done()).to.be.true;
+ expect(sb1.done()).to.be.false;
+
+ expect(() => sb1.fetchHandler('http://it.at.there/')).not.to.throw();
+ });
+
+ it('doesn\'t propagate to global from children', () => {
+ fm
+ .mock('http://it.at.there/', 200, {repeat: 1});
+
+ const sb1 = fm.sandbox();
+
+ sb1.fetchHandler('http://it.at.there/');
+
+ expect(fm.done()).to.be.false;
+ expect(sb1.done()).to.be.true;
+
+ expect(() => fm.fetchHandler('http://it.at.there/')).not.to.throw();
+ });
+
+ it('doesn\'t propagate to children of sandbox', () => {
+ const sb1 = fm
+ .sandbox()
+ .mock('http://it.at.there/', 200, {repeat: 1});
+
+ const sb2 = sb1.sandbox();
+
+ sb1.fetchHandler('http://it.at.there/');
+
+ expect(sb1.done()).to.be.true;
+ expect(sb2.done()).to.be.false;
+
+ expect(() => sb2.fetchHandler('http://it.at.there/')).not.to.throw();
+ });
+
+ it('doesn\'t propagate to sandbox from children', () => {
+ const sb1 = fm
+ .sandbox()
+ .mock('http://it.at.there/', 200, {repeat: 1});
+
+ const sb2 = sb1.sandbox();
+
+ sb2.fetchHandler('http://it.at.there/');
+
+ expect(sb1.done()).to.be.false;
+ expect(sb2.done()).to.be.true;
+
+ expect(() => sb1.fetchHandler('http://it.at.there/')).not.to.throw();
+ });
+ });
+
+
describe('strict matching shorthands', () => {
it('has once shorthand method', () => {
sinon.stub(fm, 'mock'); | Subclassing and repeat (#<I>)
* added tests for done-ness isolation
* added tests for done-ness isolation
* turned all tests back on
* refined tests, and fixed scoping of repeat | wheresrhys_fetch-mock | train |
f5e6213af378a9e088e77b962bb3fefd8624cac9 | diff --git a/UIUtils/conform/index.js b/UIUtils/conform/index.js
index <HASH>..<HASH> 100644
--- a/UIUtils/conform/index.js
+++ b/UIUtils/conform/index.js
@@ -15,13 +15,13 @@ import {findDOMNode} from 'react-dom';
* Each must be able to be mixed and matched without overwriting each other,
* with the exception of `id`, where `props.id`
*
- * @param {function} render a pre-build render function to take in vdom and render to a designated place
- * @param {function} Constructor a valid ReactClass
- * @param {object} baseProps any fundamental props that are needed for the component to be rendered successfully
- * @param {string} [ref] a specific ref identifier to check for compliance instead of the base element; this is
+ * @param {function} render a pre-build render function to take in vdom and render to a designated place
+ * @param {function} Constructor a valid ReactClass
+ * @param {object} baseProps any fundamental props that are needed for the component to be rendered successfully
+ * @param {string} [key] an instance key to check for compliance instead of the base element; this is
* used for React components that render to <body> or a node other than its logical parent
*/
-export default function verifyConformance(render, Constructor, baseProps, ref) {
+export default function verifyConformance(render, Constructor, baseProps, key) {
let node;
const renderWithPropsAndGetNode = props => {
@@ -34,10 +34,10 @@ export default function verifyConformance(render, Constructor, baseProps, ref) {
)
);
- if (ref) {
- return element.refs[ref] instanceof HTMLElement
- ? element.refs[ref]
- : findDOMNode(element.refs[ref]);
+ if (key) {
+ return element[key] instanceof HTMLElement
+ ? element[key]
+ : findDOMNode(element[key]);
}
return findDOMNode(element); | Refactor conformance checker to not use refs | enigma-io_boundless | train |
3441fd7417c1b0f6168446da8a4c20fd065f5b7d | diff --git a/bench.go b/bench.go
index <HASH>..<HASH> 100644
--- a/bench.go
+++ b/bench.go
@@ -4,15 +4,20 @@ Package bench provides a generic framework for performing latency benchmarks.
package bench
import (
+ "context"
+ "math"
"sync"
"time"
+ "golang.org/x/time/rate"
+
"github.com/codahale/hdrhistogram"
)
const (
maxRecordableLatencyNS = 300000000000
sigFigs = 5
+ defaultBurst = 1000
)
// RequesterFactory creates new Requesters.
@@ -48,9 +53,11 @@ type Benchmark struct {
// connections specified, so if requestRate is 50,000 and connections is 10,
// each connection will attempt to issue 5,000 requests per second. A zero
// value disables rate limiting entirely. The duration argument specifies how
-// long to run the benchmark.
+// long to run the benchmark. Requests will be issued in bursts with the
+// specified burst rate. If burst == 0 then burst will be the lesser of
+// (0.1 * requestRate) and 1000 but at least 1.
func NewBenchmark(factory RequesterFactory, requestRate, connections uint64,
- duration time.Duration) *Benchmark {
+ duration time.Duration, burst uint64) *Benchmark {
if connections == 0 {
connections = 1
@@ -59,7 +66,7 @@ func NewBenchmark(factory RequesterFactory, requestRate, connections uint64,
benchmarks := make([]*connectionBenchmark, connections)
for i := uint64(0); i < connections; i++ {
benchmarks[i] = newConnectionBenchmark(
- factory.GetRequester(i), requestRate/connections, duration)
+ factory.GetRequester(i), requestRate/connections, duration, burst)
}
return &Benchmark{connections: connections, benchmarks: benchmarks}
@@ -138,18 +145,25 @@ type connectionBenchmark struct {
successTotal uint64
errorTotal uint64
elapsed time.Duration
+ burst int
}
// newConnectionBenchmark creates a connectionBenchmark which runs a system
// benchmark using the given Requester. The requestRate argument specifies the
// number of requests per second to issue. A zero value disables rate limiting
// entirely. The duration argument specifies how long to run the benchmark.
-func newConnectionBenchmark(requester Requester, requestRate uint64, duration time.Duration) *connectionBenchmark {
+func newConnectionBenchmark(requester Requester, requestRate uint64, duration time.Duration, burst uint64) *connectionBenchmark {
var interval time.Duration
if requestRate > 0 {
interval = time.Duration(1000000000 / requestRate)
}
+ if burst == 0 {
+
+ // burst is at least 1 - otherwise it's the smaller of DefaultBurst and 10% of requestRate
+ burst = uint64(math.Max(1, math.Min(float64(requestRate)*0.1, float64(defaultBurst))))
+ }
+
return &connectionBenchmark{
requester: requester,
requestRate: requestRate,
@@ -159,6 +173,7 @@ func newConnectionBenchmark(requester Requester, requestRate uint64, duration ti
uncorrectedSuccessHistogram: hdrhistogram.New(1, maxRecordableLatencyNS, sigFigs),
errorHistogram: hdrhistogram.New(1, maxRecordableLatencyNS, sigFigs),
uncorrectedErrorHistogram: hdrhistogram.New(1, maxRecordableLatencyNS, sigFigs),
+ burst: int(burst),
}
}
@@ -197,6 +212,9 @@ func (c *connectionBenchmark) runRateLimited() (time.Duration, error) {
interval = c.expectedInterval.Nanoseconds()
stop = time.After(c.duration)
start = time.Now()
+ limit = rate.Every(c.expectedInterval)
+ limiter = rate.NewLimiter(limit, c.burst)
+ ctx = context.Background()
)
for {
select {
@@ -205,29 +223,28 @@ func (c *connectionBenchmark) runRateLimited() (time.Duration, error) {
default:
}
- before := time.Now()
- err := c.requester.Request()
- latency := time.Since(before).Nanoseconds()
- if err != nil {
- if err := c.errorHistogram.RecordCorrectedValue(latency, interval); err != nil {
- return 0, err
- }
- if err := c.uncorrectedErrorHistogram.RecordValue(latency); err != nil {
- return 0, err
- }
- c.errorTotal++
- } else {
- if err := c.successHistogram.RecordCorrectedValue(latency, interval); err != nil {
- return 0, err
+ limiter.WaitN(ctx, c.burst)
+ for i := 0; i < c.burst; i++ {
+ before := time.Now()
+ err := c.requester.Request()
+ latency := time.Since(before).Nanoseconds()
+ if err != nil {
+ if err := c.errorHistogram.RecordCorrectedValue(latency, interval); err != nil {
+ return 0, err
+ }
+ if err := c.uncorrectedErrorHistogram.RecordValue(latency); err != nil {
+ return 0, err
+ }
+ c.errorTotal++
+ } else {
+ if err := c.successHistogram.RecordCorrectedValue(latency, interval); err != nil {
+ return 0, err
+ }
+ if err := c.uncorrectedSuccessHistogram.RecordValue(latency); err != nil {
+ return 0, err
+ }
+ c.successTotal++
}
- if err := c.uncorrectedSuccessHistogram.RecordValue(latency); err != nil {
- return 0, err
- }
- c.successTotal++
- }
-
- for c.expectedInterval > (time.Now().Sub(before)) {
- // Busy spin
}
}
} | Use Token Bucket based rate limiter instead of busy loop | tylertreat_bench | train |
1697b5164d17c54e98aead0c114a347c205ea0d8 | diff --git a/resultdb/cmd/recorder/finalize_invocation.go b/resultdb/cmd/recorder/finalize_invocation.go
index <HASH>..<HASH> 100644
--- a/resultdb/cmd/recorder/finalize_invocation.go
+++ b/resultdb/cmd/recorder/finalize_invocation.go
@@ -60,11 +60,11 @@ func (s *recorderServer) FinalizeInvocation(ctx context.Context, in *pb.Finalize
var retErr error
_, err = span.ReadWriteTransaction(ctx, func(ctx context.Context, txn *spanner.ReadWriteTransaction) error {
+ retErr = nil
now := clock.Now(ctx)
var updateToken spanner.NullString
-
- err = span.ReadInvocation(ctx, txn, invID, map[string]interface{}{
+ err := span.ReadInvocation(ctx, txn, invID, map[string]interface{}{
"UpdateToken": &updateToken,
"State": &ret.State,
"Interrupted": &ret.Interrupted,
@@ -83,8 +83,10 @@ func (s *recorderServer) FinalizeInvocation(ctx context.Context, in *pb.Finalize
case ret.State == pb.Invocation_COMPLETED && ret.Interrupted == in.Interrupted:
// Idempotent.
return nil
+
case ret.State == pb.Invocation_COMPLETED && ret.Interrupted != in.Interrupted:
return getUnmatchedInterruptedFlagError(invID)
+
case deadline.Before(now):
ret.State = pb.Invocation_COMPLETED
ret.FinalizeTime = ret.Deadline
@@ -94,6 +96,7 @@ func (s *recorderServer) FinalizeInvocation(ctx context.Context, in *pb.Finalize
if !in.Interrupted {
retErr = getUnmatchedInterruptedFlagError(invID)
}
+
default:
// Finalize as requested.
ret.State = pb.Invocation_COMPLETED
@@ -101,7 +104,7 @@ func (s *recorderServer) FinalizeInvocation(ctx context.Context, in *pb.Finalize
ret.Interrupted = in.Interrupted
}
- if err = validateUserUpdateToken(updateToken, userToken); err != nil {
+ if err := validateUserUpdateToken(updateToken, userToken); err != nil {
return err
} | [resultdb] Fix flake
err variable was shadowed.
R=<EMAIL>
Bug: <I>
Change-Id: Ib<I>ded<I>df<I>a<I>bb<I>b<I>fabcb<I>
Reviewed-on: <URL> | luci_luci-go | train |
e468fd406d5fe199b7a81bfea710d8dd06544384 | diff --git a/src/main/java/com/contentful/java/cda/SyncQuery.java b/src/main/java/com/contentful/java/cda/SyncQuery.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/contentful/java/cda/SyncQuery.java
+++ b/src/main/java/com/contentful/java/cda/SyncQuery.java
@@ -24,7 +24,7 @@ public class SyncQuery {
this.client = checkNotNull(builder.client, "Client must not be null.");
this.syncToken = builder.syncToken;
this.space = builder.space;
- this.initial = space == null && syncToken == null;
+ this.initial = builder.isInitial();
this.type = builder.type;
}
@@ -50,8 +50,8 @@ public class SyncQuery {
@Override public Flowable<Response<SynchronizedSpace>> apply(Cache cache) {
return client.service.sync(client.spaceId,
initial ? initial : null, token,
- type != null ? type.getName() : null,
- type != null ? type.getContentType() : null);
+ initial && type != null ? type.getName() : null,
+ initial && type != null ? type.getContentType() : null);
}
}).map(new Function<Response<SynchronizedSpace>, SynchronizedSpace>() {
@Override public SynchronizedSpace apply(Response<SynchronizedSpace> synchronizedSpace) {
@@ -110,10 +110,16 @@ public class SyncQuery {
}
Builder setType(SyncType type) {
- this.type = type;
+ if (isInitial()) {
+ this.type = type;
+ }
return this;
}
+ boolean isInitial() {
+ return space == null && syncToken == null;
+ }
+
SyncQuery build() {
return new SyncQuery(this);
} | polish: set type only on initial sync | contentful_contentful.java | train |
16e92b79c8d1a874d73ff70181a8849774ffa5a6 | diff --git a/packages/node_modules/samples/browser-single-party-call/app.js b/packages/node_modules/samples/browser-single-party-call/app.js
index <HASH>..<HASH> 100644
--- a/packages/node_modules/samples/browser-single-party-call/app.js
+++ b/packages/node_modules/samples/browser-single-party-call/app.js
@@ -42,10 +42,16 @@ function connect() {
// Let's get the name of the person calling us; in production, you'd
// probably want to cache this so that you're not adding latency on
// incoming calls
- // FIXME: this is a temporary hack until the people batcher gets fixed
- spark.people.get(atob(call.from.personId).split(`/`).pop())
+ spark.people.get(call.from.personId)
+ .catch((err) => {
+ // Fallback to the person id if we can't look up the person object.
+ // This can happen if the call is coming from a telephone number
+ // instead of a spark account.
+ console.warn(err);
+ return call.from.personId;
+ })
.then((person) => {
- if (confirm(`Answer incoming call from ${person.displayName}`)) {
+ if (confirm(`Answer incoming call from ${person.displayName || person}`)) {
call.answer({
constraints: {
audio: true, | fix(samples): handle PSTN users for incoming calls | webex_spark-js-sdk | train |
71c241824ff38158c18792bd4f79cb056f326548 | diff --git a/bokeh/session.py b/bokeh/session.py
index <HASH>..<HASH> 100644
--- a/bokeh/session.py
+++ b/bokeh/session.py
@@ -44,7 +44,7 @@ class Session(object):
self._dirty = True
# This stores a reference to all models in the object graph.
# Eventually consider making this be weakrefs?
- self._models = set()
+ self._models = {}
def __enter__(self):
pass
@@ -60,8 +60,8 @@ class Session(object):
"""
for obj in objects:
obj.session = self
- self._models.update(objects)
-
+ self._models[obj._id] = obj
+
def view(self):
""" Triggers the OS to open a web browser pointing to the file
that is connected to this session.
@@ -127,13 +127,7 @@ class BaseHTMLSession(Session):
def get_ref(self, obj):
- # Eventually should use our own memo instead of storing
- # an attribute on the class
- if not getattr(obj, "_id", None):
- obj._id = self.make_id(obj)
-
- self._models.add(obj)
-
+ self._models[obj._id] = obj
return {
'type': obj.__view_model__,
'id': obj._id
@@ -214,7 +208,7 @@ class HTMLFileSession(BaseHTMLSession):
the path to the various static files should be computed.
"""
# FIXME: Handle this more intelligently
- the_plot = [m for m in self._models if isinstance(m, Plot)][0]
+ the_plot = [m for m in self._models.itervalues() if isinstance(m, Plot)][0]
plot_ref = self.get_ref(the_plot)
elementid = str(uuid.uuid4())
@@ -223,7 +217,7 @@ class HTMLFileSession(BaseHTMLSession):
# vm_serialize into the PlotObjEncoder, because that would cause
# all the attributes to be duplicated multiple times.)
models = []
- for m in self._models:
+ for m in self._models.itervalues():
ref = self.get_ref(m)
ref["attributes"] = m.vm_serialize()
ref["attributes"].update({"id": ref["id"], "doc": None})
@@ -332,7 +326,7 @@ class HTMLFileSession(BaseHTMLSession):
Mostly used for debugging.
"""
models = []
- for m in self._models:
+ for m in self._models.itervalues():
ref = self.get_ref(m)
ref["attributes"] = m.vm_serialize()
ref["attributes"].update({"id": ref["id"], "doc": None})
@@ -487,36 +481,50 @@ class PlotServerSession(BaseHTMLSession):
url = utils.urljoin(self.base_url, self.docid + "/" + ref["type"] +\
"/" + ref["id"] + "/")
self.http_session.put(url, data=self.serialize(data))
-
+
+ def load_type(self, typename, asdict=False):
+ url = utils.urljoin(self.baseurl, self.docid +"/", typename + "/")
+ attrs = protocol.deserialize_json(self.s.get(url).content)
+ if not asdict:
+ models = [PlotObject.get_obj(attr) for attr in attrs]
+ else:
+ models = attrs
+ return models
+
+ def load_all(self, asdict=False):
+ url = utils.urljoin(self.baseurl, self.docid +"/")
+ attrs = protocol.deserialize_json(self.s.get(url).content)
+ if not asdict:
+ models = [PlotObject.get_obj(attr) for attr in attrs]
+ else:
+ models = attrs
+ return models
+
def load_obj(self, ref, asdict=False):
+
""" Unserializes the object given by **ref**, into a new object
of the type in the serialization. If **asdict** is True,
then the raw dictionary (including object type and ref) is
returned, and no new object is instantiated.
"""
- # TODO: Do URL and path stuff to read json data from persistence
- # backend into jsondata string
- jsondata = None
- attrs = protocol.deserialize_json(jsondata)
- if asdict:
- return attrs
+ typename = ref["type"]
+ ref_id = ref["id"]
+ url = utils.urljoin(self.base_url, self.docid + "/" + ref["type"] +\
+ "/" + ref["id"] + "/")
+ attr = protocol.deserialize_json(self.s.get(url).content)
+ if not asdict:
+ return PlotObject.get_obj(attr)
else:
- from bokeh.objects import PlotObject
- objtype = attrs["type"]
- ref_id = attrs["id"]
- cls = PlotObject.get_class(objtype)
- newobj = cls(id=ref_id)
- # TODO: finish this...
- return newobj
+ return attr
def store_all(self):
models = []
# Look for the Plot to stick into here. PlotContexts only
# want things with a corresponding BokehJS View, so Plots and
# GridPlots for now.
- theplot = [x for x in self._models if isinstance(x, Plot)][0]
+ theplot = [x for x in self._models.itervalues() if isinstance(x, Plot)][0]
self.plotcontext.children = [theplot]
- for m in list(self._models) + [self.plotcontext]:
+ for m in self._models.values() + [self.plotcontext]:
ref = self.get_ref(m)
ref["attributes"] = m.vm_serialize()
# FIXME: Is it really necessary to add the id and doc to the | session._models now is a dict that stores objects by their id _ | bokeh_bokeh | train |
c8f014ff1f68bca8deb22f57dd8c7fde9deb7030 | diff --git a/actionpack/test/dispatch/session/cookie_store_test.rb b/actionpack/test/dispatch/session/cookie_store_test.rb
index <HASH>..<HASH> 100644
--- a/actionpack/test/dispatch/session/cookie_store_test.rb
+++ b/actionpack/test/dispatch/session/cookie_store_test.rb
@@ -13,8 +13,9 @@ class CookieStoreTest < ActionDispatch::IntegrationTest
Generator = ActiveSupport::KeyGenerator.new(SessionSecret, iterations: 1000)
Rotations = ActiveSupport::Messages::RotationConfiguration.new
- Encryptor = ActiveSupport::MessageEncryptor.new \
+ Encryptor = ActiveSupport::MessageEncryptor.new(
Generator.generate_key(SessionSalt, 32), cipher: "aes-256-gcm", serializer: Marshal
+ )
class TestController < ActionController::Base
def no_session_access | Embrace the instantiation in loving parens <3 | rails_rails | train |
7af002134285ef40ab8758af947d3e8cd7ed6a7a | diff --git a/client.go b/client.go
index <HASH>..<HASH> 100644
--- a/client.go
+++ b/client.go
@@ -31,7 +31,7 @@ type Client struct {
// The maximum number of pending requests in the queue.
// Default is 32768.
- PendingRequestsCount int
+ PendingRequests int
// Delay between request flushes.
// Default value is 5ms.
@@ -70,8 +70,8 @@ func (c *Client) Start() {
panic("gorpc.Client: the given client is already started. Call Client.Stop() before calling Client.Start() again!")
}
- if c.PendingRequestsCount <= 0 {
- c.PendingRequestsCount = 32768
+ if c.PendingRequests <= 0 {
+ c.PendingRequests = 32768
}
if c.FlushDelay <= 0 {
c.FlushDelay = 5 * time.Millisecond
@@ -86,7 +86,7 @@ func (c *Client) Start() {
c.RecvBufferSize = 1024 * 1024
}
- c.requestsChan = make(chan *clientMessage, c.PendingRequestsCount)
+ c.requestsChan = make(chan *clientMessage, c.PendingRequests)
c.clientStopChan = make(chan struct{})
if c.Conns <= 0 {
@@ -296,7 +296,7 @@ func clientWriter(c *Client, w io.Writer, pendingRequests map[uint64]*clientMess
pendingRequests[msgID] = rpcM
pendingRequestsLock.Unlock()
- if n > 10*c.PendingRequestsCount {
+ if n > 10*c.PendingRequests {
err = fmt.Errorf("gorpc.Client: [%s]. The server didn't return %d responses yet. Closing server connection in order to prevent client resource leaks", c.Addr, n)
return
}
diff --git a/rpc_test.go b/rpc_test.go
index <HASH>..<HASH> 100644
--- a/rpc_test.go
+++ b/rpc_test.go
@@ -172,9 +172,9 @@ func TestServerStuck(t *testing.T) {
defer s.Stop()
c := &Client{
- Addr: ":16359",
- PendingRequestsCount: 100,
- RequestTimeout: 300 * time.Millisecond,
+ Addr: ":16359",
+ PendingRequests: 100,
+ RequestTimeout: 300 * time.Millisecond,
}
c.Start()
defer c.Stop() | PendingRequestsCount renamed to PendingRequests | valyala_gorpc | train |
cf87338fd741916d89c0c94c215dac869ff0d7c2 | diff --git a/indra/sources/tees/parse_tees.py b/indra/sources/tees/parse_tees.py
index <HASH>..<HASH> 100644
--- a/indra/sources/tees/parse_tees.py
+++ b/indra/sources/tees/parse_tees.py
@@ -471,10 +471,12 @@ def tees_parse_networkx_to_dot(G, output_file, subgraph_nodes):
mentioned_nodes = set()
for from_node in subgraph_nodes:
- for to_node in G.edge[from_node]:
+ for edge in G.edges(from_node):
+ to_node = edge[1]
+
mentioned_nodes.add(from_node)
mentioned_nodes.add(to_node)
- relation = G.edge[from_node][to_node]['relation']
+ relation = G.edges[from_node, to_node]['relation']
f.write('%s -> %s [ label = "%s" ];\n' % (from_node, to_node,
relation))
diff --git a/indra/sources/tees/processor.py b/indra/sources/tees/processor.py
index <HASH>..<HASH> 100644
--- a/indra/sources/tees/processor.py
+++ b/indra/sources/tees/processor.py
@@ -95,8 +95,10 @@ class TEESProcessor(object):
The text in the relation property of the edge
"""
G = self.G
- for to in G.edge[node_name].keys():
- relation_name = G.edge[node_name][to]['relation']
+ for edge in G.edges(node_name):
+ to = edge[1]
+
+ relation_name = G.edges[node_name, to]['relation']
if relation_name == edge_label:
return to
return None
@@ -120,16 +122,16 @@ class TEESProcessor(object):
print(general_node_label(G, node))
tabs = '\t'
for parent in parents:
- relation = G.edge[parent][node]['relation']
+ relation = G.edges[parent, node]['relation']
print(tabs + 'Parent (%s): %s' % (relation,
general_node_label(G, parent)))
for cop in G.successors(parent):
if cop != node:
- relation = G.edge[parent][cop]['relation']
+ relation = G.edges[parent, cop]['relation']
print(tabs + 'Child of parent (%s): %s' % (relation,
general_node_label(G, cop)))
for child in children:
- relation = G.edge[node][child]['relation']
+ relation = G.edges[node, child]['relation']
print(tabs + 'Child (%s): (%s)' % (relation,
general_node_label(G, child)))
@@ -174,8 +176,8 @@ class TEESProcessor(object):
for node in G.node.keys():
if G.node[node]['is_event'] and G.node[node]['type'] == event_name:
- has_relations = [G.edge[node][to]['relation'] for
- to in G.edge[node].keys()]
+ has_relations = [G.edges[node, edge[1]]['relation'] for
+ edge in G.edges(node)]
has_relations = set(has_relations)
# Did the outgoing edges from this node have all of the
# desired relations?
@@ -188,8 +190,10 @@ class TEESProcessor(object):
annotated with the given relation. If there exists such an edge,
returns the name of the node it points to. Otherwise, returns None."""
G = self.G
- for to in G.edge[node]:
- to_relation = G.edge[node][to]['relation']
+ for edge in G.edges(node):
+ to = edge[1]
+
+ to_relation = G.edges[node, to]['relation']
if to_relation == relation:
return to
return None
@@ -354,8 +358,12 @@ class TEESProcessor(object):
# Make annotations object containing the fully connected subgraph
# containing these nodes
subgraph = self.connected_subgraph(entity_node)
+ edge_properties = {}
+ for edge in subgraph.edges():
+ edge_properties[edge] = subgraph.edges[edge]
+
annotations = {'node_properties': subgraph.node,
- 'edge_properties': subgraph.edge}
+ 'edge_properties': edge_properties}
# Make evidence object
epistemics = dict() | Updated TEES processor to work with networkx 2 | sorgerlab_indra | train |
0a3e94049ef36bfd1dbc16b9a963c053ff1a464a | diff --git a/jodd-bean/src/main/java/jodd/bean/BeanVisitor.java b/jodd-bean/src/main/java/jodd/bean/BeanVisitor.java
index <HASH>..<HASH> 100644
--- a/jodd-bean/src/main/java/jodd/bean/BeanVisitor.java
+++ b/jodd-bean/src/main/java/jodd/bean/BeanVisitor.java
@@ -7,14 +7,14 @@ import jodd.introspector.ClassIntrospector;
import jodd.introspector.FieldDescriptor;
import jodd.introspector.MethodDescriptor;
import jodd.introspector.PropertyDescriptor;
-import jodd.util.ArraysUtil;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
/**
- * Visitor for bean properties.
+ * Visitor for bean properties. It extracts properties names
+ * from the source bean and then visits one by one.
*/
public abstract class BeanVisitor {
@@ -99,6 +99,45 @@ public abstract class BeanVisitor {
}
/**
+ * Accepts property and returns <code>true</code> if property should be visited.
+ */
+ protected boolean acceptProperty(String propertyName) {
+ boolean included = true;
+
+ // check excluded
+ if (excludeNames != null) {
+ for (String excludeName : excludeNames) {
+ if (match(propertyName, excludeName, false)) {
+ // property is excluded, mark the flag
+ included = false;
+ break;
+ }
+ }
+ }
+
+ if (includeNames != null) {
+ for (String includeName : includeNames) {
+ if (match(propertyName, includeName, true)) {
+ // property is included, hey!
+ return true;
+ }
+ }
+ // property was not included
+ return false;
+ }
+
+ return included;
+ }
+
+ /**
+ * Matches property name with pattern.
+ */
+ protected boolean match(String propertyName, String pattern, boolean included) {
+ return pattern.equals(propertyName);
+ }
+
+
+ /**
* Starts visiting properties.
*/
public void visit() {
@@ -109,16 +148,8 @@ public abstract class BeanVisitor {
continue;
}
- if (excludeNames != null) {
- if (ArraysUtil.contains(excludeNames, name) == true) {
- continue;
- }
- }
-
- if (includeNames != null) {
- if (ArraysUtil.contains(includeNames, name) == false) {
- continue;
- }
+ if (!acceptProperty(name)) {
+ continue;
}
Object value;
@@ -142,4 +173,5 @@ public abstract class BeanVisitor {
* visiting should continue, otherwise <code>false</code> to stop.
*/
protected abstract boolean visitProperty(String name, Object value);
-}
+
+}
\ No newline at end of file
diff --git a/jodd-bean/src/test/java/jodd/bean/BeanCopyTest.java b/jodd-bean/src/test/java/jodd/bean/BeanCopyTest.java
index <HASH>..<HASH> 100644
--- a/jodd-bean/src/test/java/jodd/bean/BeanCopyTest.java
+++ b/jodd-bean/src/test/java/jodd/bean/BeanCopyTest.java
@@ -4,6 +4,8 @@ package jodd.bean;
import jodd.bean.data.FooBean;
import jodd.bean.data.FooBeanString;
+import jodd.datetime.JDateTime;
+import jodd.util.Wildcard;
import org.junit.Test;
import java.util.HashMap;
@@ -438,6 +440,97 @@ public class BeanCopyTest {
assertEquals("2", dest.get("priv").toString());
assertEquals("8", dest.get("_prop").toString());
assertEquals("wof", dest.get("moo").toString());
+ }
+
+ public static class Moo {
+
+ private String name = "cow";
+ private Integer value = Integer.valueOf(7);
+ private long time = 100;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Integer getValue() {
+ return value;
+ }
+
+ public void setValue(Integer value) {
+ this.value = value;
+ }
+
+ public long getTime() {
+ return time;
+ }
+
+ public void setTime(long time) {
+ this.time = time;
+ }
+ }
+
+ @Test
+ public void testIncludeExclude() {
+ Moo moo = new Moo();
+ HashMap map = new HashMap();
+
+ BeanCopy beanCopy = new BeanCopy(moo, map) {
+ @Override
+ protected boolean match(String propertyName, String pattern, boolean included) {
+ return Wildcard.match(propertyName, pattern);
+ }
+ };
+
+ // + exclude all
+
+ beanCopy.exclude("*");
+ beanCopy.copy();
+
+ assertEquals(0, map.size());
+
+
+ // + exclude all but one
+
+ beanCopy.exclude("*");
+ beanCopy.include("name");
+ beanCopy.copy();
+
+ assertEquals(1, map.size());
+ assertEquals("cow", map.get("name"));
+
+ // + include all but one
+
+ beanCopy.exclude("time");
+ beanCopy.include(null);
+ beanCopy.copy();
+
+ assertEquals(2, map.size());
+ assertEquals("cow", map.get("name"));
+ assertEquals("7", map.get("value").toString());
+
+ // + include one
+
+ beanCopy.exclude(null);
+ beanCopy.include("name");
+ beanCopy.copy();
+
+ assertEquals(1, map.size());
+ assertEquals("cow", map.get("name"));
+
+ // + include all
+
+ beanCopy.exclude(null);
+ beanCopy.include(null);
+ beanCopy.copy();
+
+ assertEquals(3, map.size());
+ assertEquals("cow", map.get("name"));
+ assertEquals("7", map.get("value").toString());
+ assertEquals("100", map.get("time").toString());
}
} | BeanVisitor refactored so it can be better implemented for property matching | oblac_jodd | train |
9b3eae2a126ba2e1b5b2d9dc2604259de0d78a0f | diff --git a/contribs/gmf/src/backgroundlayerselector/component.js b/contribs/gmf/src/backgroundlayerselector/component.js
index <HASH>..<HASH> 100644
--- a/contribs/gmf/src/backgroundlayerselector/component.js
+++ b/contribs/gmf/src/backgroundlayerselector/component.js
@@ -204,7 +204,7 @@ exports.Controller_.prototype.handleThemesChange_ = function() {
* @export
*/
exports.Controller_.prototype.getSetBgLayerOpacity = function(val) {
- if (val) {
+ if (val !== undefined) {
this.opacityLayer.setOpacity(val);
}
return this.opacityLayer.getOpacity(); | Use undefined to check opacity value | camptocamp_ngeo | train |
9e5e871bb496fac58ffaf3e0c2a943f398068763 | diff --git a/api/src/main/java/com/capitalone/dashboard/service/BuildServiceImpl.java b/api/src/main/java/com/capitalone/dashboard/service/BuildServiceImpl.java
index <HASH>..<HASH> 100644
--- a/api/src/main/java/com/capitalone/dashboard/service/BuildServiceImpl.java
+++ b/api/src/main/java/com/capitalone/dashboard/service/BuildServiceImpl.java
@@ -134,10 +134,12 @@ public class BuildServiceImpl implements BuildService {
option.put("instanceUrl", request.getInstanceUrl());
tempCi.setNiceName(request.getNiceName());
tempCi.getOptions().putAll(option);
- if (StringUtils.isEmpty(tempCi.getNiceName())) {
- return collectorService.createCollectorItem(tempCi);
- }
- return collectorService.createCollectorItemByNiceName(tempCi);
+ // FIXME: CollectorItem creation via nice name is broken!
+// if (StringUtils.isEmpty(tempCi.getNiceName())) {
+// return collectorService.createCollectorItem(tempCi);
+// }
+// return collectorService.createCollectorItemByNiceName(tempCi);
+ return collectorService.createCollectorItem(tempCi);
}
private Build createBuild(CollectorItem collectorItem, BuildDataCreateRequest request) {
diff --git a/api/src/main/java/com/capitalone/dashboard/service/CodeQualityServiceImpl.java b/api/src/main/java/com/capitalone/dashboard/service/CodeQualityServiceImpl.java
index <HASH>..<HASH> 100644
--- a/api/src/main/java/com/capitalone/dashboard/service/CodeQualityServiceImpl.java
+++ b/api/src/main/java/com/capitalone/dashboard/service/CodeQualityServiceImpl.java
@@ -171,10 +171,12 @@ public class CodeQualityServiceImpl implements CodeQualityService {
option.put("instanceUrl", request.getServerUrl());
tempCi.getOptions().putAll(option);
tempCi.setNiceName(request.getNiceName());
- if (StringUtils.isEmpty(tempCi.getNiceName())) {
- return collectorService.createCollectorItem(tempCi);
- }
- return collectorService.createCollectorItemByNiceName(tempCi);
+ // FIXME: CollectorItem creation via nice name is broken!
+// if (StringUtils.isEmpty(tempCi.getNiceName())) {
+// return collectorService.createCollectorItem(tempCi);
+// }
+// return collectorService.createCollectorItemByNiceName(tempCi);
+ return collectorService.createCollectorItem(tempCi);
}
private CodeQuality createCodeQuality(CollectorItem collectorItem, CodeQualityCreateRequest request) {
diff --git a/api/src/main/java/com/capitalone/dashboard/service/CollectorServiceImpl.java b/api/src/main/java/com/capitalone/dashboard/service/CollectorServiceImpl.java
index <HASH>..<HASH> 100644
--- a/api/src/main/java/com/capitalone/dashboard/service/CollectorServiceImpl.java
+++ b/api/src/main/java/com/capitalone/dashboard/service/CollectorServiceImpl.java
@@ -102,6 +102,9 @@ public class CollectorServiceImpl implements CollectorService {
@Override
public CollectorItem createCollectorItemByNiceName(CollectorItem item) throws HygieiaException {
+ /*
+ * FIXME - This logic is currently broken!!
+ */
//Try to find a matching by collector ID and niceName.
List<CollectorItem> existing = collectorItemRepository.findByCollectorIdAndNiceName(item.getCollectorId(), item.getNiceName());
diff --git a/api/src/main/java/com/capitalone/dashboard/service/TestResultServiceImpl.java b/api/src/main/java/com/capitalone/dashboard/service/TestResultServiceImpl.java
index <HASH>..<HASH> 100644
--- a/api/src/main/java/com/capitalone/dashboard/service/TestResultServiceImpl.java
+++ b/api/src/main/java/com/capitalone/dashboard/service/TestResultServiceImpl.java
@@ -151,10 +151,12 @@ public class TestResultServiceImpl implements TestResultService {
option.put("instanceUrl", request.getServerUrl());
tempCi.getOptions().putAll(option);
tempCi.setNiceName(request.getNiceName());
- if (StringUtils.isEmpty(tempCi.getNiceName())) {
- return collectorService.createCollectorItem(tempCi);
- }
- return collectorService.createCollectorItemByNiceName(tempCi);
+ // FIXME: CollectorItem creation via nice name is broken!
+// if (StringUtils.isEmpty(tempCi.getNiceName())) {
+// return collectorService.createCollectorItem(tempCi);
+// }
+// return collectorService.createCollectorItemByNiceName(tempCi);
+ return collectorService.createCollectorItem(tempCi);
}
private TestResult createTest(CollectorItem collectorItem, TestDataCreateRequest request) {
diff --git a/core/src/main/java/com/capitalone/dashboard/event/HygieiaMongoEventListener.java b/core/src/main/java/com/capitalone/dashboard/event/HygieiaMongoEventListener.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/com/capitalone/dashboard/event/HygieiaMongoEventListener.java
+++ b/core/src/main/java/com/capitalone/dashboard/event/HygieiaMongoEventListener.java
@@ -55,6 +55,7 @@ public abstract class HygieiaMongoEventListener<T> extends AbstractMongoEventLis
EnvironmentStage stage = pipeline.getStages().get(stageName);
if(stage == null){
stage = new EnvironmentStage();
+ pipeline.getStages().put(stageName, stage);
}
return stage;
} | Comment out broken logic around finding CollectorItems using the "nice name"; fixed bug in find or create environment stage logic | Hygieia_Hygieia | train |
18b39d6384ee8de3bc98b8c94e9f173cd0c09d5b | diff --git a/karma.conf.js b/karma.conf.js
index <HASH>..<HASH> 100644
--- a/karma.conf.js
+++ b/karma.conf.js
@@ -36,8 +36,8 @@ module.exports = function (config) {
htmlReporter: {
outputFile: 'report/testReport.html',
// Optional
- pageTitle: 'Unit Tests',
- subPageTitle: 'A sample project description',
+ pageTitle: 'Hamsters.js Jasmine Output',
+ subPageTitle: '',
groupSuites: true,
useCompactStyle: true,
useLegacyStyle: true
diff --git a/src/core.js b/src/core.js
index <HASH>..<HASH> 100644
--- a/src/core.js
+++ b/src/core.js
@@ -347,7 +347,7 @@ export class hamsters {
}
parseJsonOnThread(string, onSuccess) {
- runHamster({input: string}, function() {
+ this.runHamster({input: string}, function() {
rtn.data = JSON.parse(params.input);
}, function(output) {
onSuccess(output[0]);
@@ -355,7 +355,7 @@ export class hamsters {
}
stringifyJsonOnThread(json, onSuccess) {
- runHamster({input: json}, function() {
+ this.runHamster({input: json}, function() {
rtn.data = JSON.stringify(params.input);
}, function(output) {
onSuccess(output[0]);
@@ -366,7 +366,7 @@ export class hamsters {
let params = {
count: count
};
- runHamster(params, function() {
+ this.runHamster(params, function() {
while(params.count > 0) {
rtn.data[rtn.data.length] = Math.round(Math.random() * (100 - 1) + 1);
params.count -= 1;
@@ -388,7 +388,7 @@ export class hamsters {
for (i; i < len; i += 1) {
bufferLength += input[i].length;
}
- let output = processDataType(dataType, bufferLength);
+ let output = this.processDataType(dataType, bufferLength);
let offset = 0;
for (i = 0; i < len; i += 1) {
output.set(input[i], offset);
@@ -431,7 +431,7 @@ export class hamsters {
return 'Error processing for loop, missing params or function';
}
workers = (this.habitat.legacy ? 1 : (workers || 1));
- let task = newTask(this.pool.tasks.length, workers, order, dataType, fn, onSuccess);
+ let task = this.newTask(this.pool.tasks.length, workers, order, dataType, fn, onSuccess);
if(dataType) {
dataType = dataType.toLowerCase();
}
@@ -445,13 +445,13 @@ export class hamsters {
return;
}
}
- work(task, params, fn, onSuccess, aggregate, dataType, memoize, order);
+ this.work(task, params, fn, onSuccess, aggregate, dataType, memoize, order);
}
work(task, params, fn, onSuccess, aggregate, dataType, memoize, order) {
let workArray = params.array;
if(workArray && task.threads !== 1) {
- workArray = splitArray(workArray, task.threads); //Divide our array into equal array sizes
+ workArray = this.splitArray(workArray, task.threads); //Divide our array into equal array sizes
}
let food = {};
let key;
@@ -460,7 +460,7 @@ export class hamsters {
food[key] = params[key];
}
}
- food.fn = prepareFunction(fn);
+ food.fn = this.prepareFunction(fn);
food.dataType = dataType;
let i = 0;
while(i < task.threads) { | Update karma conf, more progress for class | austinksmith_Hamsters.js | train |
8c92a200dce5270dede9d128a91bdb5b95997dd0 | diff --git a/bigquery/docs/snippets.py b/bigquery/docs/snippets.py
index <HASH>..<HASH> 100644
--- a/bigquery/docs/snippets.py
+++ b/bigquery/docs/snippets.py
@@ -179,7 +179,7 @@ def test_create_table_cmek(client, to_delete):
# Set the encryption key to use for the table.
# TODO: Replace this key with a key you have created in Cloud KMS.
kms_key_name = "projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}".format(
- "cloud-samples-tests", "us-central1", "test", "test"
+ "cloud-samples-tests", "us", "test", "test"
)
table.encryption_configuration = bigquery.EncryptionConfiguration(
kms_key_name=kms_key_name
@@ -500,7 +500,7 @@ def test_update_table_cmek(client, to_delete):
table = bigquery.Table(dataset.table(table_id))
original_kms_key_name = "projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}".format(
- "cloud-samples-tests", "us-central1", "test", "test"
+ "cloud-samples-tests", "us", "test", "test"
)
table.encryption_configuration = bigquery.EncryptionConfiguration(
kms_key_name=original_kms_key_name
@@ -516,8 +516,7 @@ def test_update_table_cmek(client, to_delete):
# Set a new encryption key to use for the destination.
# TODO: Replace this key with a key you have created in KMS.
updated_kms_key_name = (
- "projects/cloud-samples-tests/locations/us-central1/"
- "keyRings/test/cryptoKeys/otherkey"
+ "projects/cloud-samples-tests/locations/us/keyRings/test/cryptoKeys/otherkey"
)
table.encryption_configuration = bigquery.EncryptionConfiguration(
kms_key_name=updated_kms_key_name
@@ -831,7 +830,7 @@ def test_load_table_from_uri_cmek(client, to_delete):
# Set the encryption key to use for the destination.
# TODO: Replace this key with a key you have created in KMS.
kms_key_name = "projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}".format(
- "cloud-samples-tests", "us-central1", "test", "test"
+ "cloud-samples-tests", "us", "test", "test"
)
encryption_config = bigquery.EncryptionConfiguration(kms_key_name=kms_key_name)
job_config.destination_encryption_configuration = encryption_config
@@ -1305,7 +1304,7 @@ def test_copy_table_cmek(client, to_delete):
# Set the encryption key to use for the destination.
# TODO: Replace this key with a key you have created in KMS.
kms_key_name = "projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}".format(
- "cloud-samples-tests", "us-central1", "test", "test"
+ "cloud-samples-tests", "us", "test", "test"
)
encryption_config = bigquery.EncryptionConfiguration(kms_key_name=kms_key_name)
job_config = bigquery.CopyJobConfig()
@@ -1685,7 +1684,7 @@ def test_client_query_destination_table_cmek(client, to_delete):
# Set the encryption key to use for the destination.
# TODO: Replace this key with a key you have created in KMS.
kms_key_name = "projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}".format(
- "cloud-samples-tests", "us-central1", "test", "test"
+ "cloud-samples-tests", "us", "test", "test"
)
encryption_config = bigquery.EncryptionConfiguration(kms_key_name=kms_key_name)
job_config.destination_encryption_configuration = encryption_config | refactor(bigquery): use multi-regional key path for CMEK in snippets (#<I>)
* refactor(bigquery): use multi-regional key path for CMEK in snippets
* black reformat | googleapis_google-cloud-python | train |
172b515fa5fa7595833efb5c4e8a9d9c824ffbdf | diff --git a/.eslintrc b/.eslintrc
index <HASH>..<HASH> 100644
--- a/.eslintrc
+++ b/.eslintrc
@@ -240,10 +240,7 @@
"int32Hint": false
}
],
- "space-return-throw-case": [
- 2,
- "always"
- ],
+ "space-return-throw-case": 2,
"space-unary-ops": [
2,
{
@@ -257,6 +254,6 @@
],
"wrap-regex": 0,
"no-var": 0,
- "max-len": 80
+ "max-len": [2, 80, 4]
}
}
diff --git a/src/validator/rules/NoUndefinedVariables.js b/src/validator/rules/NoUndefinedVariables.js
index <HASH>..<HASH> 100644
--- a/src/validator/rules/NoUndefinedVariables.js
+++ b/src/validator/rules/NoUndefinedVariables.js
@@ -8,7 +8,6 @@
* of patent rights can be found in the PATENTS file in the same directory.
*/
-import type { ValidationContext } from '../index';
import { GraphQLError } from '../../error';
import { FRAGMENT_DEFINITION } from '../../language/kinds';
import {
@@ -23,7 +22,7 @@ import {
* A GraphQL operation is only valid if all variables encountered, both directly
* and via fragment spreads, are defined by that operation.
*/
-export default function NoUndefinedVariables(context: ValidationContext): any {
+export default function NoUndefinedVariables(): any {
var operation;
var visitedFragmentNames = {};
var definedVariableNames = {};
diff --git a/src/validator/rules/NoUnusedFragments.js b/src/validator/rules/NoUnusedFragments.js
index <HASH>..<HASH> 100644
--- a/src/validator/rules/NoUnusedFragments.js
+++ b/src/validator/rules/NoUnusedFragments.js
@@ -8,8 +8,6 @@
* of patent rights can be found in the PATENTS file in the same directory.
*/
-import type { ValidationContext } from '../index';
-
import { GraphQLError } from '../../error';
import { unusedFragMessage } from '../errors';
@@ -19,7 +17,7 @@ import { unusedFragMessage } from '../errors';
* A GraphQL document is only valid if all fragment definitions are spread
* within operations, or spread within other fragments spread within operations.
*/
-export default function NoUnusedFragments(context: ValidationContext): any {
+export default function NoUnusedFragments(): any {
var fragmentDefs = [];
var spreadsWithinOperation = [];
var fragAdjacencies = {};
diff --git a/src/validator/rules/NoUnusedVariables.js b/src/validator/rules/NoUnusedVariables.js
index <HASH>..<HASH> 100644
--- a/src/validator/rules/NoUnusedVariables.js
+++ b/src/validator/rules/NoUnusedVariables.js
@@ -8,7 +8,6 @@
* of patent rights can be found in the PATENTS file in the same directory.
*/
-import type { ValidationContext } from '../index';
import { GraphQLError } from '../../error';
import { unusedVariableMessage } from '../errors';
@@ -19,7 +18,7 @@ import { unusedVariableMessage } from '../errors';
* A GraphQL operation is only valid if all variables defined by an operation
* are used, either directly or within a spread fragment.
*/
-export default function NoUnusedVariables(context: ValidationContext): any {
+export default function NoUnusedVariables(): any {
var visitedFragmentNames = {};
var variableDefs = [];
var variableNameUsed = {}; | fix lint issues found by newer eslint | graphql_graphql-js | train |
cf781bc595dd8eafbe6d3080ec8326766342a23e | diff --git a/breadability/utils.py b/breadability/utils.py
index <HASH>..<HASH> 100644
--- a/breadability/utils.py
+++ b/breadability/utils.py
@@ -4,17 +4,16 @@
def cached_property(getter):
"""
Decorator that converts a method into memoized property.
- The decorator will work as expected only for immutable properties.
+ The decorator works as expected only for classes with
+ attribute '__dict__' and immutable properties.
"""
def decorator(self):
- if not hasattr(self, "__cached_property_data"):
- self.__cached_property_data = {}
+ key = "_cached_property_" + getter.__name__
- key = getter.__name__
- if key not in self.__cached_property_data:
- self.__cached_property_data[key] = getter(self)
+ if not hasattr(self, key):
+ setattr(self, key, getter(self))
- return self.__cached_property_data[key]
+ return getattr(self, key)
decorator.__name__ = getter.__name__
decorator.__module__ = getter.__module__ | Updated implementation of cached property
Cached value of properties are stored
in instance's '__dict__'. | bookieio_breadability | train |
85e463b43ce1be46600680cea59c2092f4157eed | diff --git a/src/Ouzo/Goodies/Utilities/Arrays.php b/src/Ouzo/Goodies/Utilities/Arrays.php
index <HASH>..<HASH> 100644
--- a/src/Ouzo/Goodies/Utilities/Arrays.php
+++ b/src/Ouzo/Goodies/Utilities/Arrays.php
@@ -15,6 +15,7 @@ use InvalidArgumentException;
class Arrays
{
const TREAT_NULL_AS_VALUE = 1;
+ const REMOVE_EMPTY_PARENTS = true;
/**
* Returns true if every element in array satisfies the predicate.
@@ -850,14 +851,18 @@ class Arrays
*
* @param array $array
* @param array $keys
+ * @param bool $removeEmptyParents
*/
- public static function removeNestedKey(array &$array, array $keys)
+ public static function removeNestedKey(array &$array, array $keys, $removeEmptyParents = false)
{
$key = array_shift($keys);
if (count($keys) == 0) {
unset($array[$key]);
} else if ($array[$key] !== null) {
self::removeNestedKey($array[$key], $keys);
+ if ($removeEmptyParents && empty($array[$key])) {
+ unset($array[$key]);
+ }
}
}
diff --git a/test/src/Ouzo/Goodies/Utilities/ArraysTest.php b/test/src/Ouzo/Goodies/Utilities/ArraysTest.php
index <HASH>..<HASH> 100644
--- a/test/src/Ouzo/Goodies/Utilities/ArraysTest.php
+++ b/test/src/Ouzo/Goodies/Utilities/ArraysTest.php
@@ -735,7 +735,7 @@ class ArraysTest extends PHPUnit_Framework_TestCase
/**
* @test
*/
- public function shouldRemoveNestedKey()
+ public function shouldRemoveNestedKeyWithoutEmptyParent()
{
//given
$array = array('1' => array('2' => array('3' => 'value')));
@@ -750,6 +750,21 @@ class ArraysTest extends PHPUnit_Framework_TestCase
/**
* @test
*/
+ public function shouldRemoveNestedKeyWithEmptyParent()
+ {
+ //given
+ $array = array('1' => array('2' => array('3' => 'value')));
+
+ //when
+ Arrays::removeNestedKey($array, array('1', '2'), Arrays::REMOVE_EMPTY_PARENTS);
+
+ //then
+ $this->assertEquals(array(), $array);
+ }
+
+ /**
+ * @test
+ */
public function shouldNotRemoveNestedKeyWhenKeyNotFoundAndValueIsNull()
{
//given | added Arrays::removeNestedKey can also remove arrays that are empty when key is removed | letsdrink_ouzo | train |
0a4dd3aba7b392d00e4a07874df19dc54d34e670 | diff --git a/ethereum-tx.gemspec b/ethereum-tx.gemspec
index <HASH>..<HASH> 100644
--- a/ethereum-tx.gemspec
+++ b/ethereum-tx.gemspec
@@ -1,11 +1,11 @@
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
-require 'ethereum'
+require 'ethereum/tx'
Gem::Specification.new do |spec|
spec.name = "ethereum-tx"
- spec.version = '0.2.0'
+ spec.version = Ethereum::Tx::VERSION
spec.authors = ["Steve Ellis"]
spec.email = ["[email protected]"]
diff --git a/lib/ethereum.rb b/lib/ethereum.rb
index <HASH>..<HASH> 100644
--- a/lib/ethereum.rb
+++ b/lib/ethereum.rb
@@ -21,4 +21,8 @@ module Ethereum
class ValidationError < StandardError; end
class InvalidTransaction < ValidationError; end
+ class Tx
+ VERSION = '0.2.1'
+ end
+
end
diff --git a/lib/ethereum/tx.rb b/lib/ethereum/tx.rb
index <HASH>..<HASH> 100644
--- a/lib/ethereum/tx.rb
+++ b/lib/ethereum/tx.rb
@@ -1,5 +1,6 @@
#lifted from https://github.com/janx/ruby-ethereum
#TODO: try to extract gem for common behavior
+require_relative '../ethereum'
module Ethereum
class Tx | Use require_relative to grab the right file | se3000_ruby-eth | train |
7f24dba32d21cde55fe8e08f0464360d342c7c03 | diff --git a/marrow/mongo/core/field/plugin.py b/marrow/mongo/core/field/plugin.py
index <HASH>..<HASH> 100644
--- a/marrow/mongo/core/field/plugin.py
+++ b/marrow/mongo/core/field/plugin.py
@@ -22,6 +22,7 @@ class PluginReference(Field):
namespace = Attribute() # The plugin namespace to use when loading.
explicit = Attribute() # Allow explicit, non-plugin references.
+ dynamic = Attribute(default=False) # Allow variable replacements within the namespace name.
__foreign__ = {'string'}
@@ -32,34 +33,38 @@ class PluginReference(Field):
super(PluginReference, self).__init__(*args, **kw)
- def to_native(self, obj, name, value): # pylint:disable=unused-argument
- """Transform the MongoDB value into a Marrow Mongo value."""
-
+ @property
+ def _namespace(self):
try:
namespace = self.namespace
except AttributeError:
namespace = None
+ else:
+ if self.dynamic and '${' in namespace:
+ namespace = namespace.format(self=obj, cls=cls, field=self)
- return load(value, namespace) if namespace else load(value)
+ return namespace
+
+ def to_native(self, obj, name, value): # pylint:disable=unused-argument
+ """Transform the MongoDB value into a Marrow Mongo value."""
+
+ return load(value, self._namespace)
def to_foreign(self, obj, name, value): # pylint:disable=unused-argument
"""Transform to a MongoDB-safe value."""
- try:
- namespace = self.namespace
- except AttributeError:
- namespace = None
+ namespace = self._namespace
try:
explicit = self.explicit
except AttributeError:
- explicit = not bool(namespace)
+ explicit = not namespace
if not isinstance(value, (str, unicode)):
value = canon(value)
if namespace and ':' in value: # Try to reduce to a known plugin short name.
- for point in iter_entry_points(namespace):
+ for point in iter_entry_points(namespace): # TODO: Isolate.
qualname = point.module_name
if point.attrs: | Allow for dynamic namepaces, DRY. | marrow_mongo | train |
cc74beee2e16a79428adb9c54149c0c592256846 | diff --git a/src/document.js b/src/document.js
index <HASH>..<HASH> 100644
--- a/src/document.js
+++ b/src/document.js
@@ -237,7 +237,10 @@ Document.Prototype = function() {
return a.property === property;
});
for (var idx = 0; idx < annotations.length; idx++) {
- Operator.TextOperation.Range.transform(annotations[idx].range, change);
+ var a = annotations[idx];
+ var changed = Operator.TextOperation.Range.transform(a.range, change);
+ // TODO: here we could check if the range is collapsed and remove the annotation.
+ if (changed) this.trigger("annotation:changed", a);
}
}; | Trigger an event if an annotation has been changed. | substance_document | train |
014d11b79338a8daf855d374ea8d6ab1e95b1fd5 | diff --git a/naming/src/main/java/org/jboss/as/naming/ExternalContextObjectFactory.java b/naming/src/main/java/org/jboss/as/naming/ExternalContextObjectFactory.java
index <HASH>..<HASH> 100644
--- a/naming/src/main/java/org/jboss/as/naming/ExternalContextObjectFactory.java
+++ b/naming/src/main/java/org/jboss/as/naming/ExternalContextObjectFactory.java
@@ -119,6 +119,7 @@ public class ExternalContextObjectFactory implements ObjectFactory {
config.setClassLoader(loader);
config.setSuperClass(initialContextClass);
config.setProxyName(initialContextClassName + "$$$$Proxy" + PROXY_ID.incrementAndGet());
+ config.setProtectionDomain(context.getClass().getProtectionDomain());
ProxyFactory<?> factory = new ProxyFactory<Object>(config);
return (Context) factory.newInstance(new CachedContext(context));
}
diff --git a/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/naming/ExternalContextBindingTestCase.java b/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/naming/ExternalContextBindingTestCase.java
index <HASH>..<HASH> 100644
--- a/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/naming/ExternalContextBindingTestCase.java
+++ b/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/naming/ExternalContextBindingTestCase.java
@@ -39,6 +39,7 @@ import static org.jboss.as.naming.subsystem.NamingSubsystemModel.CLASS;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.ENVIRONMENT;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.EXTERNAL_CONTEXT;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.MODULE;
+import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import javax.naming.Context;
import javax.naming.InitialContext;
@@ -78,6 +79,7 @@ import org.junit.runner.RunWith;
import com.sun.jndi.ldap.LdapCtx;
import com.sun.jndi.ldap.LdapCtxFactory;
+import org.wildfly.naming.java.permission.JndiPermission;
/**
* Test for external context binding. There are tests which use a usual InitialContext and treat it
@@ -312,7 +314,8 @@ public class ExternalContextBindingTestCase {
@Deployment
public static JavaArchive deploy() {
return ShrinkWrap.create(JavaArchive.class, "externalContextBindingTest.jar")
- .addClasses(ExternalContextBindingTestCase.class, LookupEjb.class);
+ .addClasses(ExternalContextBindingTestCase.class, LookupEjb.class)
+ .addAsManifestResource(createPermissionsXmlAsset(new JndiPermission("*", "lookup")), "jboss-permissions.xml");
}
@Test | WFLY-<I> make cached context proxy use the same protection domain of the context | wildfly_wildfly | train |
15e75dfccb6dfb3a92fe044aceaea5cd59353db6 | diff --git a/lib/pdf2img.js b/lib/pdf2img.js
index <HASH>..<HASH> 100644
--- a/lib/pdf2img.js
+++ b/lib/pdf2img.js
@@ -100,7 +100,7 @@ class Pdf2Img {
var inputStream = fs.createReadStream(input);
var outputFile = this.options.outputdir + this.options.outputname + '_' + page + '.' + this.options.type;
- convertPdf2Img(inputStream, outputFile, parseInt(page), function (error, result) {
+ this.convertPdf2Img(inputStream, outputFile, parseInt(page), function (error, result) {
if (error) {
return callbackmap(error);
} | apply OOP encapsulation to support concurrent calls | fitraditya_node-pdf2img | train |
9b5c9df321b5f9556859b8f3a0d90978b0cff331 | diff --git a/core/dnsserver/register.go b/core/dnsserver/register.go
index <HASH>..<HASH> 100644
--- a/core/dnsserver/register.go
+++ b/core/dnsserver/register.go
@@ -16,7 +16,6 @@ const serverType = "dns"
func init() {
flag.StringVar(&Port, "port", DefaultPort, "Default port")
- flag.BoolVar(&Quiet, "quiet", false, "Quiet mode (no initialization output)")
caddy.RegisterServerType(serverType, caddy.ServerType{
Directives: func() []string { return directives },
@@ -138,7 +137,4 @@ var (
// GracefulTimeout is the maximum duration of a graceful shutdown.
GracefulTimeout time.Duration
-
- // Quiet mode will not show any informative output on initialization.
- Quiet bool
)
diff --git a/core/dnsserver/server.go b/core/dnsserver/server.go
index <HASH>..<HASH> 100644
--- a/core/dnsserver/server.go
+++ b/core/dnsserver/server.go
@@ -218,7 +218,7 @@ func (s *Server) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
}
// OnStartupComplete lists the sites served by this server
-// and any relevant information, assuming Quiet == false.
+// and any relevant information, assuming Quiet is false.
func (s *Server) OnStartupComplete() {
if Quiet {
return
@@ -259,3 +259,8 @@ const (
tcp = 0
udp = 1
)
+
+var (
+ // Quiet mode will not show any informative output on initialization.
+ Quiet bool
+)
diff --git a/coremain/run.go b/coremain/run.go
index <HASH>..<HASH> 100644
--- a/coremain/run.go
+++ b/coremain/run.go
@@ -15,6 +15,7 @@ import (
"github.com/mholt/caddy"
"github.com/miekg/coredns/core/dnsserver"
+
// Plug in CoreDNS
_ "github.com/miekg/coredns/core"
)
@@ -31,6 +32,7 @@ func init() {
flag.StringVar(&logfile, "log", "", "Process log file")
flag.StringVar(&caddy.PidFile, "pidfile", "", "Path to write pid file")
flag.BoolVar(&version, "version", false, "Show version")
+ flag.BoolVar(&dnsserver.Quiet, "quiet", false, "Quiet mode (no initialization output)")
caddy.RegisterCaddyfileLoader("flag", caddy.LoaderFunc(confLoader))
caddy.SetDefaultCaddyfileLoader("default", caddy.LoaderFunc(defaultLoader))
@@ -81,7 +83,9 @@ func Run() {
}
logVersion()
- showVersion()
+ if !dnsserver.Quiet {
+ showVersion()
+ }
// Twiddle your thumbs
instance.Wait()
@@ -142,9 +146,6 @@ func logVersion() { log.Print("[INFO] " + versionString()) }
// showVersion prints the version that is starting.
func showVersion() {
- if dnsserver.Quiet {
- return
- }
fmt.Print(versionString())
if devBuild && gitShortStat != "" {
fmt.Printf("%s\n%s\n", gitShortStat, gitFilesModified)
@@ -153,7 +154,7 @@ func showVersion() {
// versionString returns the CoreDNS version as a string.
func versionString() string {
- return fmt.Sprintf("%s-%s starting\n", caddy.AppName, caddy.AppVersion)
+ return fmt.Sprintf("%s-%s\n", caddy.AppName, caddy.AppVersion)
}
// setVersion figures out the version information | Don't register quiet flag in register.go (#<I>)
This clashes to Caddy, which also has its own quiet flag. Move stuff
around a bit, also to prevent cyclic imports. | coredns_coredns | train |
8d1b2471f4b43266e1a9ffa44677e9b8aeac4d71 | diff --git a/aws/resource_aws_secretsmanager_secret_policy_test.go b/aws/resource_aws_secretsmanager_secret_policy_test.go
index <HASH>..<HASH> 100644
--- a/aws/resource_aws_secretsmanager_secret_policy_test.go
+++ b/aws/resource_aws_secretsmanager_secret_policy_test.go
@@ -70,6 +70,7 @@ func TestAccAwsSecretsManagerSecretPolicy_basic(t *testing.T) {
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSSecretsManager(t) },
+ ErrorCheck: testAccErrorCheck(t, secretsmanager.EndpointsID),
Providers: testAccProviders,
CheckDestroy: testAccCheckAwsSecretsManagerSecretPolicyDestroy,
Steps: []resource.TestStep{
@@ -106,6 +107,7 @@ func TestAccAwsSecretsManagerSecretPolicy_blockPublicPolicy(t *testing.T) {
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSSecretsManager(t) },
+ ErrorCheck: testAccErrorCheck(t, secretsmanager.EndpointsID),
Providers: testAccProviders,
CheckDestroy: testAccCheckAwsSecretsManagerSecretPolicyDestroy,
Steps: []resource.TestStep{
@@ -147,6 +149,7 @@ func TestAccAwsSecretsManagerSecretPolicy_disappears(t *testing.T) {
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSSecretsManager(t) },
+ ErrorCheck: testAccErrorCheck(t, secretsmanager.EndpointsID),
Providers: testAccProviders,
CheckDestroy: testAccCheckAwsSecretsManagerSecretPolicyDestroy,
Steps: []resource.TestStep{ | tests/r/secretsmanager_secret_policy: Add ErrorCheck | terraform-providers_terraform-provider-aws | train |
0bbc3bc8fb9ef514d5c78cf3b2169fbca398b204 | diff --git a/sirmordred/task.py b/sirmordred/task.py
index <HASH>..<HASH> 100644
--- a/sirmordred/task.py
+++ b/sirmordred/task.py
@@ -213,13 +213,6 @@ class Task():
clean, enrich_backend)
enrich_backend.set_elastic(elastic_enrich)
- if 'github' in self.conf.keys() and \
- 'backend_token' in self.conf['github'].keys() and \
- self.get_backend(self.backend_section) == "git":
-
- gh_token = self.conf['github']['backend_token']
- enrich_backend.set_github_token(gh_token)
-
if self.db_unaffiliate_group:
enrich_backend.unaffiliated_group = self.db_unaffiliate_group
diff --git a/sirmordred/task_enrich.py b/sirmordred/task_enrich.py
index <HASH>..<HASH> 100644
--- a/sirmordred/task_enrich.py
+++ b/sirmordred/task_enrich.py
@@ -124,11 +124,10 @@ class TaskEnrich(Task):
ElasticSearch.max_items_bulk = cfg['general']['bulk_size']
no_incremental = False
+ # not used due to https://github.com/chaoss/grimoirelab-elk/pull/773
github_token = None
pair_programming = False
node_regex = None
- if 'github' in cfg and 'backend_token' in cfg['github']:
- github_token = cfg['github']['backend_token']
if 'git' in cfg and 'pair-programming' in cfg['git']:
pair_programming = cfg['git']['pair-programming']
if 'jenkins' in cfg and 'node_regex' in cfg['jenkins']: | [sirmordred] Remove support for github commit
This code removes the support to include author and committer
information extracted from github commits, when enriching git data. Thus,
the code used to initialize the github token needed to query the API is
removed. | chaoss_grimoirelab-sirmordred | train |
bab93959c5ce52d7dddf99bc08499a9822eb005f | diff --git a/src/Request/Api/BaseRequest.php b/src/Request/Api/BaseRequest.php
index <HASH>..<HASH> 100644
--- a/src/Request/Api/BaseRequest.php
+++ b/src/Request/Api/BaseRequest.php
@@ -60,7 +60,7 @@ abstract class BaseRequest implements IRequest
{
if ($arg instanceof IMergeableArgument) {
if (!isset($this->mergeableArguments[$arg->getKey()])) {
- $this->mergeableArguments[$arg->getKey()] = new ArgMerger();
+ $this->mergeableArguments[$arg->getKey()] = new ArgMerger($arg::glue());
}
$this->mergeableArguments[$arg->getKey()]->addArgument($arg);
diff --git a/src/Request/Arguments/Mergeable/ArgMerger.php b/src/Request/Arguments/Mergeable/ArgMerger.php
index <HASH>..<HASH> 100644
--- a/src/Request/Arguments/Mergeable/ArgMerger.php
+++ b/src/Request/Arguments/Mergeable/ArgMerger.php
@@ -12,12 +12,29 @@ use ZEROSPAM\Framework\SDK\Utils\Contracts\PrimalValued;
class ArgMerger implements PrimalValued
{
+
+ /**
+ * @var string
+ */
+ private $glue;
+
+
/**
* @var IMergeableArgument[]
*/
private $args = [];
/**
+ * ArgMerger constructor.
+ *
+ * @param string $glue
+ */
+ public function __construct(string $glue)
+ {
+ $this->glue = $glue;
+ }
+
+ /**
* Add the argument.
*
* @param IMergeableArgument $argument
@@ -58,7 +75,7 @@ class ArgMerger implements PrimalValued
$values = array_keys($this->args);
- return implode($this->args[$values[0]]->glue(), $values);
+ return implode($this->glue, $values);
}
/**
diff --git a/src/Request/Arguments/Mergeable/IMergeableArgument.php b/src/Request/Arguments/Mergeable/IMergeableArgument.php
index <HASH>..<HASH> 100644
--- a/src/Request/Arguments/Mergeable/IMergeableArgument.php
+++ b/src/Request/Arguments/Mergeable/IMergeableArgument.php
@@ -24,5 +24,5 @@ interface IMergeableArgument extends IArgument
*
* @return string
*/
- public function glue();
+ public static function glue();
}
diff --git a/tests/src/Base/Argument/TestMergeableArg.php b/tests/src/Base/Argument/TestMergeableArg.php
index <HASH>..<HASH> 100644
--- a/tests/src/Base/Argument/TestMergeableArg.php
+++ b/tests/src/Base/Argument/TestMergeableArg.php
@@ -42,7 +42,7 @@ class TestMergeableArg implements IMergeableArgument
*
* @return string
*/
- public function glue()
+ public static function glue()
{
return ';';
} | feat(argument): Change how glue is defined
For the mergeable argument.
BREAKING CHANGE: IMergeableArgument::glue() is now static. | zerospam_sdk-framework | train |
cec35d6be0be61d7b7474a6b6620539a858b624f | diff --git a/db/storage.go b/db/storage.go
index <HASH>..<HASH> 100644
--- a/db/storage.go
+++ b/db/storage.go
@@ -19,10 +19,9 @@ import (
)
var (
- conn = make(map[string]*session) // pool of connections
- mut sync.RWMutex // for pool thread safety
- ticker *time.Ticker // for garbage collection
- maxIdleTime = 5 * time.Minute // max idle time for connections
+ conn = make(map[string]*session) // pool of connections
+ mut sync.RWMutex // for pool thread safety
+ ticker *time.Ticker // for garbage collection
)
const period time.Duration = 7 * 24 * time.Hour
@@ -44,10 +43,6 @@ func open(addr, dbname string) (*Storage, error) {
return nil, err
}
copy := sess.Copy()
- go func(t time.Duration) {
- time.Sleep(t)
- copy.Close()
- }(maxIdleTime)
storage := &Storage{session: copy, dbname: dbname}
mut.Lock()
conn[addr] = &session{s: sess, used: time.Now()}
@@ -77,10 +72,6 @@ func Open(addr, dbname string) (storage *Storage, err error) {
conn[addr] = session
mut.Unlock()
copy := session.s.Copy()
- go func() {
- time.Sleep(maxIdleTime)
- copy.Close()
- }()
return &Storage{copy, dbname}, nil
}
return open(addr, dbname)
diff --git a/db/storage_test.go b/db/storage_test.go
index <HASH>..<HASH> 100644
--- a/db/storage_test.go
+++ b/db/storage_test.go
@@ -134,23 +134,6 @@ func (s *S) TestOpenConnectionRefused(c *gocheck.C) {
c.Assert(err, gocheck.NotNil)
}
-func (s *S) TestOpenClosesTheCopy(c *gocheck.C) {
- defer func() {
- r := recover()
- c.Assert(r, gocheck.NotNil)
- }()
- old := maxIdleTime
- maxIdleTime = 1e6
- defer func() {
- maxIdleTime = old
- }()
- storage, err := Open("127.0.0.1:27017", "tsuru_storage_test")
- c.Assert(err, gocheck.IsNil)
- time.Sleep(1e9)
- err = storage.session.Ping()
- c.Assert(err, gocheck.NotNil)
-}
-
func (s *S) TestClose(c *gocheck.C) {
defer func() {
r := recover() | db: remove the maxIdleTime thing
It doesn't help much, and leads to bad code. | tsuru_tsuru | train |
73d7652524b263e42f456c6cc9f7a699df56286d | diff --git a/ue4cli/__main__.py b/ue4cli/__main__.py
index <HASH>..<HASH> 100644
--- a/ue4cli/__main__.py
+++ b/ue4cli/__main__.py
@@ -2,8 +2,8 @@ from .cli import main
import os, sys
if __name__ == '__main__':
-
- # Rewrite sys.argv[0] so our help prompts display the correct base command
- interpreter = sys.executable if sys.executable not in [None, ''] else 'python3'
- sys.argv[0] = '{} -m ue4cli'.format(os.path.basename(interpreter))
- main()
+
+ # Rewrite sys.argv[0] so our help prompts display the correct base command
+ interpreter = sys.executable if sys.executable not in [None, ''] else 'python3'
+ sys.argv[0] = '{} -m ue4cli'.format(os.path.basename(interpreter))
+ main() | Make indentation in __main__.py consistent with other files | adamrehn_ue4cli | train |
ae3c98824cf9aec85cbf9e0250c2f6fd20ad0f23 | diff --git a/lib/omise/OmiseCapabilities.php b/lib/omise/OmiseCapabilities.php
index <HASH>..<HASH> 100644
--- a/lib/omise/OmiseCapabilities.php
+++ b/lib/omise/OmiseCapabilities.php
@@ -7,9 +7,9 @@ class OmiseCapabilities extends OmiseApiResource
/**
* @var array of the filterable keys.
*/
- const FILTERS = array(
- 'backend' => array('currency', 'type', 'chargeAmount')
- );
+ static $filters = [
+ 'backend' => ['currency', 'type', 'chargeAmount']
+ ];
protected function __construct($publickey = null, $secretkey = null)
{
@@ -25,14 +25,14 @@ class OmiseCapabilities extends OmiseApiResource
*/
protected function setupFilterShortcuts()
{
- foreach (self::FILTERS as $filterSubject => $availableFilters) {
+ foreach (self::$filters as $filterSubject => $availableFilters) {
$filterArrayName = $filterSubject . 'Filter';
- $this->$filterArrayName = array();
+ $this->$filterArrayName = [];
$tempArr = &$this->$filterArrayName;
foreach ($availableFilters as $type) {
$funcName = 'make' . ucfirst($filterSubject) . 'Filter' . $type;
$tempArr[$type] = function () use ($funcName) {
- return call_user_func_array(array($this, $funcName), func_get_args());
+ return call_user_func_array([$this, $funcName], func_get_args());
};
}
} | Fixes issue with use of array constant (mandated PHP <I>+)
Also switches to short array syntax as we're now mandating PHP <I>+ | omise_omise-php | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.