hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
123da4dd948a2bf9939ebde59675b0fd22fc2662
|
diff --git a/lib/oauth2.js b/lib/oauth2.js
index <HASH>..<HASH> 100755
--- a/lib/oauth2.js
+++ b/lib/oauth2.js
@@ -149,6 +149,13 @@ Strategy.prototype.makeRequest = function makeRequest(options, done) {
}
}
+ // CASE: e.g. auth url is wrong
+ if (!body) {
+ return done(new errors.BadRequestError({
+ message: 'The response of the service could not be understood.'
+ }));
+ }
+
try {
body = JSON.parse(body || null);
return done(null, body);
|
🎨 error handling if auth url is wrong
no issue
|
TryGhost_passport-ghost
|
train
|
d2063cf7c42b187a26fdd297ab23194d94d950cf
|
diff --git a/lucene/src/main/java/com/orientechnologies/lucene/operator/OLuceneOperatorFactory.java b/lucene/src/main/java/com/orientechnologies/lucene/operator/OLuceneOperatorFactory.java
index <HASH>..<HASH> 100644
--- a/lucene/src/main/java/com/orientechnologies/lucene/operator/OLuceneOperatorFactory.java
+++ b/lucene/src/main/java/com/orientechnologies/lucene/operator/OLuceneOperatorFactory.java
@@ -30,7 +30,7 @@ public class OLuceneOperatorFactory implements OQueryOperatorFactory {
static {
final Set<OQueryOperator> operators = new HashSet<OQueryOperator>();
-// operators.add(new OLuceneTextOperator());
+ operators.add(new OLuceneTextOperator());
OPERATORS = Collections.unmodifiableSet(operators);
}
|
enables old lucene operator until all will be migrated
|
orientechnologies_orientdb
|
train
|
72adb4c0f5815386ee4f290d2f1ca757d99ef08c
|
diff --git a/src/Proxy/ProxyTrait.php b/src/Proxy/ProxyTrait.php
index <HASH>..<HASH> 100644
--- a/src/Proxy/ProxyTrait.php
+++ b/src/Proxy/ProxyTrait.php
@@ -36,7 +36,6 @@ use function array_flip;
use function array_keys;
use function array_pop;
use function class_exists;
-use function class_implements;
use function count;
use function current;
use function debug_backtrace;
|
Remove not used "use" in ProxyTrait
|
TeknooSoftware_states
|
train
|
80d2fcfb6c1719f7087fb8792b9d69c17697b690
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -40,6 +40,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- The argument `field` within the `OrderByClause` used for `@orderBy` will be renamed to `column`
in v5 https://github.com/nuwave/lighthouse/pull/1118
+### Removed
+
+- Remove broken `NOT` conditional when using `@whereConstraints` https://github.com/nuwave/lighthouse/pull/1125
+
## [4.7.2](https://github.com/nuwave/lighthouse/compare/v4.7.1...v4.7.2)
### Fixed
diff --git a/docs/master/api-reference/directives.md b/docs/master/api-reference/directives.md
index <HASH>..<HASH> 100644
--- a/docs/master/api-reference/directives.md
+++ b/docs/master/api-reference/directives.md
@@ -2910,7 +2910,6 @@ input PeopleWhereWhereConstraints {
value: Mixed
AND: [PeopleWhereWhereConstraints!]
OR: [PeopleWhereWhereConstraints!]
- NOT: [PeopleWhereWhereConstraints!]
}
"Allowed column names for the `where` argument on the query `people`."
@@ -2965,7 +2964,7 @@ The following query gets actors over age 37 who either have red hair or are at l
```
Some operators require passing lists of values - or no value at all. The following
-query gets people that have no hair and do not have blue-ish eyes:
+query gets people that have no hair and blue-ish eyes:
```graphql
{
@@ -2973,11 +2972,7 @@ query gets people that have no hair and do not have blue-ish eyes:
where: {
AND: [
{ column: HAIRCOLOUR, operator: IS_NULL }
- {
- NOT: [
- { column: EYES, operator: IN, value: ["blue", "aqua", "turquoise"] }
- ]
- }
+ { column: EYES, operator: IN, value: ["blue", "aqua", "turquoise"] }
]
}
) {
diff --git a/src/WhereConstraints/WhereConstraintsDirective.php b/src/WhereConstraints/WhereConstraintsDirective.php
index <HASH>..<HASH> 100644
--- a/src/WhereConstraints/WhereConstraintsDirective.php
+++ b/src/WhereConstraints/WhereConstraintsDirective.php
@@ -80,17 +80,6 @@ SDL;
);
}
- if ($notConnectedConstraints = $whereConstraints['NOT'] ?? null) {
- $builder->whereNested(
- function ($builder) use ($notConnectedConstraints): void {
- foreach ($notConnectedConstraints as $constraint) {
- $this->handleBuilder($builder, $constraint);
- }
- },
- 'not'
- );
- }
-
if ($column = $whereConstraints['column'] ?? null) {
static::assertValidColumnName($column);
diff --git a/src/WhereConstraints/WhereConstraintsServiceProvider.php b/src/WhereConstraints/WhereConstraintsServiceProvider.php
index <HASH>..<HASH> 100644
--- a/src/WhereConstraints/WhereConstraintsServiceProvider.php
+++ b/src/WhereConstraints/WhereConstraintsServiceProvider.php
@@ -89,7 +89,6 @@ class WhereConstraintsServiceProvider extends ServiceProvider
value: Mixed
AND: [$name!]
OR: [$name!]
- NOT: [$name!]
}
");
}
diff --git a/tests/Integration/WhereConstraints/WhereConstraintsDirectiveTest.php b/tests/Integration/WhereConstraints/WhereConstraintsDirectiveTest.php
index <HASH>..<HASH> 100644
--- a/tests/Integration/WhereConstraints/WhereConstraintsDirectiveTest.php
+++ b/tests/Integration/WhereConstraints/WhereConstraintsDirectiveTest.php
@@ -278,9 +278,10 @@ class WhereConstraintsDirectiveTest extends DBTestCase
]);
}
- public function testAddsNestedNot(): void
+ public function testAddsNot(): void
{
- factory(User::class, 3)->create();
+ $this->markTestSkipped('Kind of works, but breaks down when more nested conditions are added, see https://github.com/nuwave/lighthouse/issues/1124');
+ factory(User::class, 2)->create();
$this->graphQL(/** @lang GraphQL */ '
{
@@ -297,7 +298,52 @@ class WhereConstraintsDirectiveTest extends DBTestCase
id
}
}
- ')->assertJsonCount(2, 'data.users');
+ ')->assertExactJson([
+ 'data' => [
+ 'users' => [
+ [
+ 'id' => '2',
+ ],
+ ],
+ ],
+ ]);
+ }
+
+ public function testAddsNestedNot(): void
+ {
+ $this->markTestSkipped('Not working because of limitations in Eloquent, see https://github.com/nuwave/lighthouse/issues/1124');
+ factory(User::class, 3)->create();
+
+ $this->graphQL(/** @lang GraphQL */ '
+ {
+ users(
+ where: {
+ NOT: {
+ OR: [
+ {
+ column: "id"
+ value: 1
+ }
+ {
+ column: "id"
+ value: 2
+ }
+ ]
+ }
+ }
+ ) {
+ id
+ }
+ }
+ ')->assertExactJson([
+ 'data' => [
+ 'users' => [
+ [
+ 'id' => '3',
+ ],
+ ],
+ ],
+ ]);
}
public function testRejectsInvalidColumnName(): void
@@ -306,7 +352,7 @@ class WhereConstraintsDirectiveTest extends DBTestCase
{
users(
where: {
- NOT: [
+ AND: [
{
column: "Robert\'); DROP TABLE Students;--"
value: "https://xkcd.com/327/"
|
Remove broken NOT from @whereConstraints #<I> (#<I>)
|
nuwave_lighthouse
|
train
|
d229584946de3eee27d8d78907dcd63c48f8255c
|
diff --git a/quilt/error.py b/quilt/error.py
index <HASH>..<HASH> 100644
--- a/quilt/error.py
+++ b/quilt/error.py
@@ -22,7 +22,14 @@
class QuiltError(Exception):
pass
+
class NoPatchesInSeries(QuiltError):
def __str__(self):
return "No patch in series file %s" % self.args[0].series_file
+
+
+class NoAppliedPatch(QuiltError):
+
+ def __str__(self):
+ return "No applied patch in file %s" % self.args[0].series_file
|
Add new NoAppliedPatch error class
The class is intended to be raised if a no applied patches are
available.
|
bjoernricks_python-quilt
|
train
|
51b973ac09f593c4dfc057c7a0348fb424e0d281
|
diff --git a/src/app/Exceptions/Template.php b/src/app/Exceptions/Template.php
index <HASH>..<HASH> 100644
--- a/src/app/Exceptions/Template.php
+++ b/src/app/Exceptions/Template.php
@@ -17,7 +17,7 @@ class Template extends EnsoException
public static function unknownRootAttributes($attrs)
{
return new static(__(
- 'Unknown attribute(s) found: ":attr"',
+ 'Unknown attribute(s) found: ":attrs"',
['attrs' => $attrs]
));
}
|
fixed wrong placeholder name in form template validation
|
laravel-enso_FormBuilder
|
train
|
155c3fc4361df1d2700e4c51963570060c671693
|
diff --git a/src/tagify.js b/src/tagify.js
index <HASH>..<HASH> 100644
--- a/src/tagify.js
+++ b/src/tagify.js
@@ -14,10 +14,14 @@ import events, { triggerChangeEvent } from './parts/events'
*/
function Tagify( input, settings ){
if( !input ){
- console.warn('Tagify: ', 'input element not found', input)
- return this
+ console.warn('Tagify:', 'input element not found', input)
+ // return an empty mock of all methods, so the code using tagify will not break
+ // because it might be calling methods even though the input element does not exists
+ const mockInstance = new Proxy(this, { get(){ return () => mockInstance } })
+ return mockInstance
}
+
if( input.previousElementSibling && input.previousElementSibling.classList.contains('tagify') ){
console.warn('Tagify: ', 'input element is already Tagified', input)
return this
|
[bugfix] mock tagify methods when input element does not exists
|
yairEO_tagify
|
train
|
55e625ceaf5b7b935d61144bd2c560790075d742
|
diff --git a/lib/summary.js b/lib/summary.js
index <HASH>..<HASH> 100644
--- a/lib/summary.js
+++ b/lib/summary.js
@@ -255,7 +255,7 @@ _.assign(RunSummary, {
emitter.on('request', function (err, o) {
if (err || !(o && o.response)) { return; }
- var size = o.response.size(),
+ var size = _.isFunction(o.response.size) && o.response.size(),
time = o.response.responseTime,
requestCount = summary.stats.requests.total;
diff --git a/test/unit/run-summary.test.js b/test/unit/run-summary.test.js
index <HASH>..<HASH> 100644
--- a/test/unit/run-summary.test.js
+++ b/test/unit/run-summary.test.js
@@ -6,6 +6,7 @@ describe('run summary', function () {
// @todo add test for computation of timings, transfer sizes and avergare response time
var Summary = require('../../lib/summary'),
EventEmitter = require('eventemitter3'),
+ sdk = require('postman-collection'),
TRACKED_EVENTS = ['iteration', 'item', 'script', 'prerequest', 'request', 'test', 'assertion',
'testScript', 'prerequestScript'],
@@ -138,6 +139,7 @@ describe('run summary', function () {
emitter = new EventEmitter();
summary = new Summary(emitter);
});
+
afterEach(function () {
emitter = null;
summary = null;
@@ -173,5 +175,92 @@ describe('run summary', function () {
});
});
});
+
+ describe('execution tracking', function () {
+ var emitter,
+ collection,
+ summary;
+
+ beforeEach(function () {
+ collection = new sdk.Collection({
+ item: [{
+ id: 'i1', request: 'http://localhost/1'
+ }, {
+ id: 'i2', request: 'http://localhost/1'
+ }]
+ });
+ emitter = new EventEmitter();
+ summary = new Summary(emitter, {
+ collection: collection
+ });
+ });
+
+ afterEach(function () {
+ collection = null;
+ emitter = null;
+ summary = null;
+ });
+
+ it('should add executions array', function () {
+ var item = collection.items.one('i1');
+
+ emitter.emit('request', null, {
+ item: item,
+ cursor: { iteration: 0 }
+ });
+ emitter.emit('request', null, {
+ item: item,
+ cursor: { iteration: 1 }
+ });
+
+ expect(item).have.property('executions');
+ expect(item.executions).be.an('array');
+ expect(item.executions.length).be(2);
+
+ expect(collection.items.one('i2')).not.have.property('executions');
+ });
+
+ it('should store request and response', function () {
+ var item = collection.items.one('i1');
+
+ emitter.emit('request', null, {
+ item: item,
+ request: { id: 'request-1' },
+ response: { id: 'response-1' },
+ cursor: { iteration: 0 }
+ });
+
+ expect(item).have.property('executions');
+ expect(item.executions).be.an('array');
+ expect(item.executions.length).be(1);
+
+ expect(item.executions).to.eql([{
+ request: { id: 'request-1' },
+ requestError: null,
+ response: { id: 'response-1' }
+ }]);
+ });
+
+ it('should store request error with response info even if request is missing', function () {
+ var item = collection.items.one('i1');
+
+ emitter.emit('request', null, {
+ item: item,
+ request: { id: 'request-1' },
+ response: { id: 'response-1' },
+ cursor: { iteration: 0 }
+ });
+
+ expect(item).have.property('executions');
+ expect(item.executions).be.an('array');
+ expect(item.executions.length).be(1);
+
+ expect(item.executions).to.eql([{
+ request: { id: 'request-1' },
+ requestError: null,
+ response: { id: 'response-1' }
+ }]);
+ });
+ });
});
});
|
Added tests and fixed issue with size function missing from response
|
postmanlabs_newman
|
train
|
b812a1d8f670443bfc48f6c294c4ef2b81299805
|
diff --git a/pyVmomi/VmomiSupport.py b/pyVmomi/VmomiSupport.py
index <HASH>..<HASH> 100644
--- a/pyVmomi/VmomiSupport.py
+++ b/pyVmomi/VmomiSupport.py
@@ -1260,9 +1260,6 @@ class _BuildVersions:
def GetNamespace(self, vmodlNs):
return self._nsMap[vmodlNs]
- def GetInternalNamespace(self, vmodlNs):
- return "internal%s" % self.GetNamespace(vmodlNs)
-
types = Object()
nsMap = {}
versionIdMap = {}
|
Support for build-time versions in pyVmomi
Since introduction of meta-versions and related
generated versions, we need facility, allowing
code to specify those versions during run-time.
(Note that although version classes are well-
defined, the particular versions that correspond
to a class change from build to build, depending
on meta-version state.)
|
vmware_pyvmomi
|
train
|
8c1c8e08eb799cdb9f157ff65f9a23fdba22f6e4
|
diff --git a/cleverhans/attacks_tfe.py b/cleverhans/attacks_tfe.py
index <HASH>..<HASH> 100644
--- a/cleverhans/attacks_tfe.py
+++ b/cleverhans/attacks_tfe.py
@@ -1,8 +1,10 @@
from abc import ABCMeta
-import numpy as np
-from six.moves import xrange
+from distutils.version import LooseVersion
import warnings
import collections
+
+import numpy as np
+from six.moves import xrange
import tensorflow as tf
import cleverhans.attacks as attacks
@@ -11,7 +13,6 @@ from cleverhans.compat import reduce_max
from cleverhans.compat import reduce_sum
from cleverhans.model import Model
from cleverhans.loss import LossCrossEntropy
-from distutils.version import LooseVersion
_logger = utils.create_logger("cleverhans.attacks_tfe")
|
fix imports for attacks_tfe.py
|
tensorflow_cleverhans
|
train
|
924f963e695077fcce1128f53f97bcce239172f7
|
diff --git a/executor/distsql.go b/executor/distsql.go
index <HASH>..<HASH> 100644
--- a/executor/distsql.go
+++ b/executor/distsql.go
@@ -374,6 +374,9 @@ type IndexLookUpExecutor struct {
// extraPIDColumnIndex is used for partition reader to add an extra partition ID column, default -1
extraPIDColumnIndex offsetOptional
+
+ // cancelFunc is called when close the executor
+ cancelFunc context.CancelFunc
}
type getHandleType int8
@@ -487,6 +490,8 @@ func (e *IndexLookUpExecutor) open(ctx context.Context) error {
func (e *IndexLookUpExecutor) startWorkers(ctx context.Context, initBatchSize int) error {
// indexWorker will write to workCh and tableWorker will read from workCh,
// so fetching index and getting table data can run concurrently.
+ ctx, cancel := context.WithCancel(ctx)
+ e.cancelFunc = cancel
workCh := make(chan *lookupTableTask, 1)
if err := e.startIndexWorker(ctx, workCh, initBatchSize); err != nil {
return err
@@ -676,6 +681,10 @@ func (e *IndexLookUpExecutor) Close() error {
return nil
}
+ if e.cancelFunc != nil {
+ e.cancelFunc()
+ e.cancelFunc = nil
+ }
close(e.finished)
// Drain the resultCh and discard the result, in case that Next() doesn't fully
// consume the data, background worker still writing to resultCh and block forever.
|
executor: call cancel when closing IndexLookUpExecutor (#<I>)
|
pingcap_tidb
|
train
|
5739ca8e5b29250219e6b8d90b3d1dfe38db76f9
|
diff --git a/addon/affinity-engine/configs/affinity-engine.js b/addon/affinity-engine/configs/affinity-engine.js
index <HASH>..<HASH> 100644
--- a/addon/affinity-engine/configs/affinity-engine.js
+++ b/addon/affinity-engine/configs/affinity-engine.js
@@ -1,33 +1,35 @@
export default {
priority: 0,
- all: {
- attrs: {
- animator: 'jquery',
- keys: {
- accept: ['Space', 'Enter'],
- cancel: ['Escape'],
- moveDown: ['ArrowDown', 'KeyS', 'Numpad2'],
- moveLeft: ['ArrowLeft', 'KeyA', 'Numpad4'],
- moveRight: ['ArrowRight', 'KeyD', 'Numpad6'],
- moveUp: ['ArrowUp', 'KeyW', 'Numpad8']
- },
- menu: {
- columns: 1
- },
- transitionIn: {
- effect: { opacity: [1, 0] },
- duration: 100
- },
- transitionOut: {
- effect: { opacity: 0 },
- duration: 100
- },
- lxlAnimation: {
- effect: {
- opacity: 1
+ default: {
+ all: {
+ attrs: {
+ animator: 'jquery',
+ keys: {
+ accept: ['Space', 'Enter'],
+ cancel: ['Escape'],
+ moveDown: ['ArrowDown', 'KeyS', 'Numpad2'],
+ moveLeft: ['ArrowLeft', 'KeyA', 'Numpad4'],
+ moveRight: ['ArrowRight', 'KeyD', 'Numpad6'],
+ moveUp: ['ArrowUp', 'KeyW', 'Numpad8']
},
- duration: 100,
- rate: 25
+ menu: {
+ columns: 1
+ },
+ transitionIn: {
+ effect: { opacity: [1, 0] },
+ duration: 100
+ },
+ transitionOut: {
+ effect: { opacity: 0 },
+ duration: 100
+ },
+ lxlAnimation: {
+ effect: {
+ opacity: 1
+ },
+ duration: 100,
+ rate: 25
+ }
}
}
}
diff --git a/addon/macros/affinity-engine/configurable.js b/addon/macros/affinity-engine/configurable.js
index <HASH>..<HASH> 100644
--- a/addon/macros/affinity-engine/configurable.js
+++ b/addon/macros/affinity-engine/configurable.js
@@ -12,6 +12,7 @@ const createKeyPriorityPairs = function createKeyPriorityPairs(priorities, ...ke
return keys.reduce((props, key) => {
props.push(`configuration.${key}`);
priorities.forEach((priority) => props.push(`config.attrs.${priority}.attrs.${key}`));
+ priorities.forEach((priority) => props.push(`config.attrs.default.${priority}.attrs.${key}`));
return props;
}, []);
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "affinity-engine",
- "version": "0.2.3",
+ "version": "0.2.4",
"description": "make games you'll love",
"keywords": [
"ember-addon"
|
prevent default config conflicts with user config
|
affinity-engine_affinity-engine
|
train
|
3fedd51e290d7ea9410c804b48f68fa3b1f41e9c
|
diff --git a/lib/https/index.js b/lib/https/index.js
index <HASH>..<HASH> 100644
--- a/lib/https/index.js
+++ b/lib/https/index.js
@@ -173,6 +173,10 @@ function _handleWebsocket(socket, clientIp, clientPort, callback, wss) {
}
data.realUrl = fullUrl = matchedUrl = util.encodeNonAsciiChar(ruleUrlValue);
}
+ if (_rules.ua) {
+ var ua = util.getMatcherValue(_rules.ua);
+ headers['user-agent'] = ua;
+ }
rules.getProxy(fullUrl, plugin ? null : socket, function(err, hostIp, hostPort) {
var proxyUrl = !plugin && _rules.proxy ? _rules.proxy.matcher : null;
options = util.parseUrl(fullUrl);
@@ -378,6 +382,7 @@ function _handleWebsocket(socket, clientIp, clientPort, callback, wss) {
if (_rules.hostname) {
headers.host = util.getMatcherValue(_rules.hostname);
}
+
util.parseRuleJson([_rules.reqHeaders, _rules.reqCors, _rules.reqCookies, _rules.params],
function(reqHeaders, reqCors, reqCookies, params) {
extend(headers, reqHeaders);
|
refactor: websocket
|
avwo_whistle
|
train
|
b2154dd95a470d38fe7f98ecbd04a2a0aa5aa3d5
|
diff --git a/lib/hako/schedulers/ecs.rb b/lib/hako/schedulers/ecs.rb
index <HASH>..<HASH> 100644
--- a/lib/hako/schedulers/ecs.rb
+++ b/lib/hako/schedulers/ecs.rb
@@ -500,6 +500,7 @@ module Hako
],
},
count: 1,
+ placement_constraints: @placement_constraints,
started_by: 'hako oneshot',
)
result.failures.each do |failure|
|
support placement_constraints to run_task
|
eagletmt_hako
|
train
|
ffee2c5abc5231b0b7fa6f3e10e38de6fdda3c66
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@
# html-validator
-A [Node.js](https://nodejs.org/) module for validating html using [validator.w3.org/nu](http://validator.w3.org/nu/)
+A [Node.js](https://nodejs.org/) module for validating html using [validator.w3.org/nu](https://validator.w3.org/nu/)
## Module
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -1,5 +1,3 @@
-'use strict'
-
const request = require('request')
const validUrl = require('valid-url')
const setupOptions = require('./lib/setup-options')
diff --git a/lib/filter-data.js b/lib/filter-data.js
index <HASH>..<HASH> 100644
--- a/lib/filter-data.js
+++ b/lib/filter-data.js
@@ -1,5 +1,3 @@
-'use strict'
-
module.exports = (data, ignore) => {
const list = data.split('\n')
const filters = Array.isArray(ignore) ? ignore : [ignore]
diff --git a/lib/setup-options.js b/lib/setup-options.js
index <HASH>..<HASH> 100644
--- a/lib/setup-options.js
+++ b/lib/setup-options.js
@@ -1,12 +1,10 @@
-'use strict'
-
module.exports = (options) => {
const pkg = require('../package.json')
const userAgent = `${pkg.name} v ${pkg.version}`
const ignore = options.ignore
const format = ignore ? 'text' : options.format || 'json'
let newOpts = {
- uri: 'http://validator.w3.org/nu/',
+ uri: 'https://validator.w3.org/nu/',
headers: {
'User-Agent': userAgent
},
|
Removes use strict. Switches to https (patch)
|
zrrrzzt_html-validator
|
train
|
7e6fa4a7d217d8e5f6d80d41c15e67abc8845e39
|
diff --git a/server-coreless/src/main/java/org/openqa/selenium/server/HtmlIdentifier.java b/server-coreless/src/main/java/org/openqa/selenium/server/HtmlIdentifier.java
index <HASH>..<HASH> 100644
--- a/server-coreless/src/main/java/org/openqa/selenium/server/HtmlIdentifier.java
+++ b/server-coreless/src/main/java/org/openqa/selenium/server/HtmlIdentifier.java
@@ -48,6 +48,7 @@ public class HtmlIdentifier {
// ebay dll contains HTML snippets which fool InjectionHelper. -nas
rules.add(new ExtensionRule(new String[]{"dll", "gif", "ico", "jpg", "jpeg", "png", "dwr", "js"}, -1000));
rules.add(new ContentRule("<html", 1000, -100));
+ rules.add(new ContentRule("<head", 500, -100)); // http://drudgereport.com doesn't have <html>, but rather starts with <head>
rules.add(new ContentRule("<!DOCTYPE html", 1000, -100));
rules.add(new ContentTypeRule("text/html", 100, -1000));
rules.add(new Rule("dojo catcher", -100000, 0) {
|
fix for drudgereport.com: apparently conservatives don't believe in valid HTML. this rule should help without hurting things too much
r<I>
|
SeleniumHQ_selenium
|
train
|
0e710ffbd4d8e119f7cdbcfe1024dd0e01950d3c
|
diff --git a/test/filter.js b/test/filter.js
index <HASH>..<HASH> 100644
--- a/test/filter.js
+++ b/test/filter.js
@@ -523,6 +523,14 @@ test('with a between query', t => {
run('permits', options, 211, t)
})
+test('with a OBJECTID query on data that requires dynamic OBJECTID generation', t => {
+ const options = {
+ where: 'OBJECTID=1138516379',
+ toEsri: true
+ }
+ run('snow', options, 1, t)
+})
+
function run (data, options, expected, t) {
t.plan(1)
const fixtures = _.cloneDeep(require(`./fixtures/${data}.json`))
|
Add test to filter.js that tests where parameter with OBJECTID on data without a predefined OBJECTID property.
|
koopjs_winnow
|
train
|
52c9fe3340f540d793289952f14190b97bc53b8f
|
diff --git a/samples/core/src/test/java/io/oasp/gastronomy/restaurant/general/common/RestTestClientBuilder.java b/samples/core/src/test/java/io/oasp/gastronomy/restaurant/general/common/RestTestClientBuilder.java
index <HASH>..<HASH> 100644
--- a/samples/core/src/test/java/io/oasp/gastronomy/restaurant/general/common/RestTestClientBuilder.java
+++ b/samples/core/src/test/java/io/oasp/gastronomy/restaurant/general/common/RestTestClientBuilder.java
@@ -26,11 +26,11 @@ public class RestTestClientBuilder {
/*
* The user used for authentication during testing.
*/
- private String user;
+ private String login;
/**
- * This method creates a proxy for the specified {@code RestService} interface. Properties
- * {@code server.rest.test.user} and {@code server.rest.test.password} are used by default for authentication.
+ * This method creates a proxy for the specified {@code RestService} interface. Use {@code #setLogin(String)} to set
+ * login ID which will be used as both user name and pasword for authentication.
*
* @param <T> The generic type for which a proxy must be created.
* @param clazz The interface specifying the generic type.
@@ -38,12 +38,15 @@ public class RestTestClientBuilder {
*/
public <T extends RestService> T build(Class<T> clazz) {
- return this.build(clazz, this.user, this.user, createRestServiceUrl());
+ if (this.login == null) {
+ throw new IllegalStateException("RestTestClientBuilder not properly initialized. No login provided.");
+ }
+ return this.build(clazz, this.login, this.login, createRestServiceUrl());
}
/**
* This method creates a proxy for the specified {@code RestService} interface. The provided {@code String login} is
- * used as both username and password for authentication. The method {@code setLocalServerPort} MUST be called in
+ * used as both user name and password for authentication. The method {@code setLocalServerPort} MUST be called in
* advance. The method {@code setLocalServerPort} MUST be called in advance.
*
* @param <T> The generic type for which a proxy must be created.
@@ -114,13 +117,13 @@ public class RestTestClientBuilder {
}
/**
- * Sets the {@code user}.
+ * Sets the {@code login}.
*
- * @param user Used for authentication.
+ * @param login Used for authentication.
*/
- public void setUser(String user) {
+ public void setLogin(String login) {
- this.user = user;
+ this.login = login;
}
}
diff --git a/samples/core/src/test/java/io/oasp/gastronomy/restaurant/general/common/base/AbstractRestServiceTest.java b/samples/core/src/test/java/io/oasp/gastronomy/restaurant/general/common/base/AbstractRestServiceTest.java
index <HASH>..<HASH> 100644
--- a/samples/core/src/test/java/io/oasp/gastronomy/restaurant/general/common/base/AbstractRestServiceTest.java
+++ b/samples/core/src/test/java/io/oasp/gastronomy/restaurant/general/common/base/AbstractRestServiceTest.java
@@ -37,7 +37,6 @@ public abstract class AbstractRestServiceTest extends SubsystemTest {
/**
* The user name used during the test.
*/
- @Value("${server.rest.test.user}")
private String user;
/**
@@ -81,7 +80,7 @@ public abstract class AbstractRestServiceTest extends SubsystemTest {
super.doSetUp();
this.restTestClientBuilder.setLocalServerPort(this.port);
- this.restTestClientBuilder.setUser(this.user);
+ this.restTestClientBuilder.setLogin(this.user);
this.restTestClientBuilder.setJacksonJsonProvider(this.jacksonJsonProvider);
if (this.migration != null && !"".equals(this.migration)) {
diff --git a/samples/core/src/test/java/io/oasp/gastronomy/restaurant/tablemanagement/service/impl/rest/TablemanagementRestServiceTest.java b/samples/core/src/test/java/io/oasp/gastronomy/restaurant/tablemanagement/service/impl/rest/TablemanagementRestServiceTest.java
index <HASH>..<HASH> 100644
--- a/samples/core/src/test/java/io/oasp/gastronomy/restaurant/tablemanagement/service/impl/rest/TablemanagementRestServiceTest.java
+++ b/samples/core/src/test/java/io/oasp/gastronomy/restaurant/tablemanagement/service/impl/rest/TablemanagementRestServiceTest.java
@@ -80,7 +80,7 @@ public class TablemanagementRestServiceTest extends AbstractRestServiceTest {
public void testDeleteTable() {
// setup
- getRestTestClientBuilder().setUser("chief");
+ getRestTestClientBuilder().setLogin("chief");
this.service = getRestTestClientBuilder().build(TablemanagementRestService.class);
// given
@@ -106,7 +106,7 @@ public class TablemanagementRestServiceTest extends AbstractRestServiceTest {
// given
long tableNumber = 7L;
long waiterId = 2L;
- getRestTestClientBuilder().setUser("chief");
+ getRestTestClientBuilder().setLogin("chief");
this.service = getRestTestClientBuilder().build(TablemanagementRestService.class);
TableEto table = new TableEtoBuilder().number(tableNumber).waiterId(waiterId).createNew();
assertThat(table.getId()).isNull();
|
added status check in constructor of RestTestClientBuilder. Renamed 'user' property to 'lign'. Removed possibility to set centralized 'login' in application.properties
|
oasp_oasp4j
|
train
|
bc05c19ae4be308b6b8169a3af676bdc03033feb
|
diff --git a/resources/pages/AppContainer.js b/resources/pages/AppContainer.js
index <HASH>..<HASH> 100644
--- a/resources/pages/AppContainer.js
+++ b/resources/pages/AppContainer.js
@@ -4,32 +4,31 @@ import {hot} from 'react-hot-loader';
import App from 'vendor/miaoxing/app/modules/app';
class AppContainer extends React.Component {
- render() {
- return <App importPage={(plugin, controller, action) => {
- return import(
- /* webpackChunkName: "[request]" */
- /* webpackInclude: /resources\/pages\/admin/ */
- `vendor/miaoxing/pas/resources/pages/admin/${controller}/${action}.js`
- )
- }}/>
+ importPage(plugin, controller, action) {
+ // return import(
+ // /* webpackChunkName: "[request]" */
+ // /* webpackInclude: /resources\/pages/\/admin/ */
+ // /* webpackExclude: /loader-runner/ */
+ // `vendor/miaoxing/${plugin}/resources/pages/admin/${controller}/${action}.js`
+ // );
+ return import(
+ /* webpackChunkName: "[request]" */
+ /* webpackInclude: /resources\/pages\/admin/ */
+ `vendor/miaoxing/pas/resources/pages/admin/${controller}/${action}.js`
+ );
}
-}
-
-
-//
-// const app = new App({
-// importPage(plugin, controller, action) {
-// // return import(
-// // /* webpackChunkName: "[request]" */
-// // /* webpackInclude: /resources\/pages/\/admin/ */
-// // /* webpackExclude: /loader-runner/ */
-// // `vendor/miaoxing/${plugin}/resources/pages/admin/${controller}/${action}.js`
-// // );
-// },
-// pages: require.context('vendor/miaoxing', true, /^\.\/.*\/resources\/pages\/admin\/(.+?)\/(.+?)\.js$/, 'lazy')
-// });
+ pages() {
+ return require.context('vendor/miaoxing', true, /^\.\/.*\/resources\/pages\/admin\/(.+?)\/(.+?)\.js$/, 'lazy');
+ }
+ render() {
+ return <App
+ importPage={this.importPage}
+ pages={this.pages()}
+ />
+ }
+}
export default hot(module)(AppContainer);
|
feat: 完善AppContainer
|
miaoxing_admin
|
train
|
37d29a7ab1df8d3bc21fcdbb6b07e66cc3dd0393
|
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index <HASH>..<HASH> 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -6,8 +6,6 @@ variables:
WEB_DOCUMENT_ROOT: $CI_PROJECT_DIR/development/public
GIT_STRATEGY: clone
LOG_STDOUT: $CI_PROJECT_DIR/stdout.log
- PERCY_BRANCH: $CI_DEV_BRANCH
- PERCY_TARGET_BRANCH: $CI_TARGET_BRANCH_NAME
MYSQL_CMD: mysqld
stages:
@@ -329,7 +327,7 @@ E2E:
- chown -R 1000:1000 .
- CYPRESS_CMD="cypress run"
- if [[ $cypress_usePercy = "true" ]]; then export CYPRESS_CMD="npx percy exec -- cypress run"; npm install --save-dev @percy/cypress; fi
- - FULL_CYPRESS_CMD="npm install --production --prefix /e2e && export PERCY_TOKEN=$PERCY_TOKEN && $CYPRESS_CMD --browser chrome --headless --project /e2e --config baseUrl=http://docker.vm:8000 $CYPRESS_PARAMS --spec $TEST_DIRECTORY"
+ - FULL_CYPRESS_CMD="npm install --production --prefix /e2e && export PERCY_TOKEN=$PERCY_TOKEN && $CYPRESS_CMD --browser chrome --project /e2e --config baseUrl=http://docker.vm:8000 $CYPRESS_PARAMS --spec $TEST_DIRECTORY"
- echo $FULL_CYPRESS_CMD
- docker run --shm-size=2g --name cypress --add-host="docker.vm:$(hostname -I)" -e cypress_grep -e cypress_usePercy -e CYPRESS_baseUrl=http://docker.vm:8000 -v $(pwd)/${E2E_BASE_PATH}:/e2e -v $(pwd):/app -w /e2e --entrypoint "sh" cypress/included:5.6.0 -c "$FULL_CYPRESS_CMD"
after_script:
diff --git a/src/Administration/Resources/app/administration/test/e2e/cypress/integration/visual/storefront/edit-order.spec.js b/src/Administration/Resources/app/administration/test/e2e/cypress/integration/visual/storefront/edit-order.spec.js
index <HASH>..<HASH> 100644
--- a/src/Administration/Resources/app/administration/test/e2e/cypress/integration/visual/storefront/edit-order.spec.js
+++ b/src/Administration/Resources/app/administration/test/e2e/cypress/integration/visual/storefront/edit-order.spec.js
@@ -36,7 +36,8 @@ describe('Account - Order: Visual tests', () => {
cy.get('.login-submit [type="submit"]').click();
// Take snapshot for visual testing
- cy.changeElementStyling('.order-table-header-heading', 'color : #fff');
+ cy.changeElementStyling('.order-table-header-heading', 'color: #fff');
+ cy.changeElementStyling('.order-table-header-order-status', 'visibility: hidden');
cy.takeSnapshot('Account overview', '.order-table', { widths: [375, 1920] });
});
});
diff --git a/src/Recovery/Test/e2e/cypress/support/commands/commands.js b/src/Recovery/Test/e2e/cypress/support/commands/commands.js
index <HASH>..<HASH> 100644
--- a/src/Recovery/Test/e2e/cypress/support/commands/commands.js
+++ b/src/Recovery/Test/e2e/cypress/support/commands/commands.js
@@ -117,6 +117,10 @@ Cypress.Commands.add('prepareAdminForScreenshot', () => {
'.sw-version__info',
'visibility: hidden'
);
+ cy.changeElementStyling(
+ '.sw-alert',
+ 'display: none'
+ );
});
/**
|
NEXT-<I> - Improve cypress percy integration in platform
|
shopware_platform
|
train
|
20ca67d1926e6af2e6dd81a268fdfa973ba4d7ff
|
diff --git a/src/main/java/org/vesalainen/grammar/state/DFA.java b/src/main/java/org/vesalainen/grammar/state/DFA.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/vesalainen/grammar/state/DFA.java
+++ b/src/main/java/org/vesalainen/grammar/state/DFA.java
@@ -26,6 +26,7 @@ import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
+import org.vesalainen.graph.Vertex;
import org.vesalainen.parser.util.NumMap;
import org.vesalainen.regex.Range;
@@ -365,7 +366,7 @@ public final class DFA<T> implements Iterable<DFAState<T>>
@Override
public Iterator<DFAState<T>> iterator()
{
- return new DiGraphIterator<>(root);
+ return new DiGraphIterator<>(root, Vertex::edges);
}
public void dump(PrintStream p)
diff --git a/src/main/java/org/vesalainen/grammar/state/DFADistributor.java b/src/main/java/org/vesalainen/grammar/state/DFADistributor.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/vesalainen/grammar/state/DFADistributor.java
+++ b/src/main/java/org/vesalainen/grammar/state/DFADistributor.java
@@ -23,6 +23,7 @@ import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import org.vesalainen.graph.Vertex;
import org.vesalainen.parser.util.NumMap;
import org.vesalainen.parser.util.VisitSet;
import org.vesalainen.regex.Regex;
@@ -66,7 +67,7 @@ public class DFADistributor<T> extends DiGraph<DFAState<T>>
incomingSet.clear();
closure.clear();
reset();
- traverse(s);
+ traverse(s, Vertex::edges);
Collections.sort(candidateList, comp);
if (!candidateList.isEmpty())
{
diff --git a/src/main/java/org/vesalainen/grammar/state/DFAState.java b/src/main/java/org/vesalainen/grammar/state/DFAState.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/vesalainen/grammar/state/DFAState.java
+++ b/src/main/java/org/vesalainen/grammar/state/DFAState.java
@@ -386,7 +386,7 @@ public final class DFAState<T> extends State<T> implements Vertex<DFAState<T>>,
@Override
public Iterator<DFAState<T>> iterator()
{
- return new DiGraphIterator<>(this);
+ return new DiGraphIterator<>(this, Vertex::edges);
}
}
diff --git a/src/main/java/org/vesalainen/grammar/state/NFA.java b/src/main/java/org/vesalainen/grammar/state/NFA.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/vesalainen/grammar/state/NFA.java
+++ b/src/main/java/org/vesalainen/grammar/state/NFA.java
@@ -26,6 +26,7 @@ import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.vesalainen.graph.Vertex;
import org.vesalainen.parser.util.NumMap;
import org.vesalainen.parser.util.NumSet;
@@ -415,7 +416,7 @@ public final class NFA<T> implements Iterable<NFAState<T>>
@Override
public Iterator<NFAState<T>> iterator()
{
- return new DiGraphIterator<>(first);
+ return new DiGraphIterator<>(first, Vertex::edges);
}
}
diff --git a/src/main/java/org/vesalainen/grammar/state/NFAState.java b/src/main/java/org/vesalainen/grammar/state/NFAState.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/vesalainen/grammar/state/NFAState.java
+++ b/src/main/java/org/vesalainen/grammar/state/NFAState.java
@@ -612,7 +612,7 @@ public final class NFAState<T> extends State<T> implements Vertex<NFAState<T>>,
@Override
public Iterator<NFAState<T>> iterator()
{
- return new DiGraphIterator<>(this);
+ return new DiGraphIterator<>(this, Vertex::edges);
}
}
|
Changing to new DiGraph(Iterator) interface.
|
tvesalainen_lpg
|
train
|
b2f3e83754916013f4f1f88a1e06d5ca4fe5ba01
|
diff --git a/eventbinder/src/main/java/com/google/web/bindery/event/gwt/rebind/binder/EventBinderGenerator.java b/eventbinder/src/main/java/com/google/web/bindery/event/gwt/rebind/binder/EventBinderGenerator.java
index <HASH>..<HASH> 100644
--- a/eventbinder/src/main/java/com/google/web/bindery/event/gwt/rebind/binder/EventBinderGenerator.java
+++ b/eventbinder/src/main/java/com/google/web/bindery/event/gwt/rebind/binder/EventBinderGenerator.java
@@ -15,8 +15,6 @@
*/
package com.google.web.bindery.event.gwt.rebind.binder;
-import static com.google.gwt.dev.util.Preconditions.checkArgument;
-
import com.google.gwt.core.ext.Generator;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
@@ -70,11 +68,13 @@ public class EventBinderGenerator extends Generator {
private JClassType getTargetType(JClassType interfaceType, TypeOracle typeOracle) {
JClassType[] superTypes = interfaceType.getImplementedInterfaces();
- checkArgument(
- superTypes.length == 1
- && superTypes[0].isAssignableFrom(typeOracle.findType(EventBinder.class.getCanonicalName()))
- && superTypes[0].isParameterized() != null,
- interfaceType + " must extend EventBinder with a type parameter");
+ JClassType eventBinderType = typeOracle.findType(EventBinder.class.getCanonicalName());
+ if (superTypes.length != 1
+ || !superTypes[0].isAssignableFrom(eventBinderType)
+ || superTypes[0].isParameterized() == null) {
+ throw new IllegalArgumentException(
+ interfaceType + " must extend EventBinder with a type parameter");
+ }
return superTypes[0].isParameterized().getTypeArgs()[0];
}
|
Remove dependency on the Preconditions class, which is being remove in GWT <I>.
|
google_gwteventbinder
|
train
|
7bbf56be5119ec801a44e39fcc7b9bd761bccb65
|
diff --git a/presto-main/src/main/java/com/facebook/presto/operator/TaskContext.java b/presto-main/src/main/java/com/facebook/presto/operator/TaskContext.java
index <HASH>..<HASH> 100644
--- a/presto-main/src/main/java/com/facebook/presto/operator/TaskContext.java
+++ b/presto-main/src/main/java/com/facebook/presto/operator/TaskContext.java
@@ -129,12 +129,7 @@ public class TaskContext
// another thread, which will cause unsafe publication of this instance.
private void initialize()
{
- taskStateMachine.addStateChangeListener(newState -> {
- if (newState.isDone()) {
- executionEndTime.set(DateTime.now());
- endNanos.set(System.nanoTime());
- }
- });
+ taskStateMachine.addStateChangeListener(this::updateStatsIfDone);
}
public TaskId getTaskId()
@@ -171,6 +166,25 @@ public class TaskContext
lastExecutionStartTime.set(now);
}
+ private void updateStatsIfDone(TaskState newState)
+ {
+ if (newState.isDone()) {
+ DateTime now = DateTime.now();
+
+ // before setting the end times, make sure a start has been recorded
+ executionStartTime.compareAndSet(null, now);
+ startNanos.compareAndSet(0, System.nanoTime());
+
+ // Only update last start time, if the nothing was started
+ lastExecutionStartTime.compareAndSet(null, now);
+
+ // use compare and set from initial value to avoid overwriting if there
+ // were a duplicate notification, which shouldn't happen
+ executionEndTime.compareAndSet(null, now);
+ endNanos.compareAndSet(0, System.nanoTime());
+ }
+ }
+
public void failed(Throwable cause)
{
taskStateMachine.failed(cause);
@@ -308,13 +322,7 @@ public class TaskContext
public TaskStats getTaskStats()
{
// check for end state to avoid callback ordering problems
- if (taskStateMachine.getState().isDone()) {
- DateTime now = DateTime.now();
- if (executionEndTime.compareAndSet(null, now)) {
- lastExecutionStartTime.compareAndSet(null, now);
- endNanos.set(System.nanoTime());
- }
- }
+ updateStatsIfDone(taskStateMachine.getState());
List<PipelineStats> pipelineStats = ImmutableList.copyOf(transform(pipelineContexts, PipelineContext::getPipelineStats));
|
Simplify recording of task start and end time stats
|
prestodb_presto
|
train
|
c60b6d3cbf20b7fb274051a9b0a56cf4e53b0e0e
|
diff --git a/providence-generator-java/src/main/java/net/morimekta/providence/generator/format/java/messages/BuilderCommonMemberFormatter.java b/providence-generator-java/src/main/java/net/morimekta/providence/generator/format/java/messages/BuilderCommonMemberFormatter.java
index <HASH>..<HASH> 100644
--- a/providence-generator-java/src/main/java/net/morimekta/providence/generator/format/java/messages/BuilderCommonMemberFormatter.java
+++ b/providence-generator-java/src/main/java/net/morimekta/providence/generator/format/java/messages/BuilderCommonMemberFormatter.java
@@ -470,7 +470,7 @@ public class BuilderCommonMemberFormatter implements MessageMemberFormatter {
}
}
comment.finish();
- writer.appendln(JAnnotation.NULLABLE);
+ writer.appendln(JAnnotation.NON_NULL);
writer.formatln("public _Builder %s(%s value) {", field.setter(), helper.getValueType(enumType))
.begin()
.formatln("if (value == null) return %s();", field.resetter())
|
Correct use @NonNull not @Nullable for ref enum setter.
|
morimekta_providence
|
train
|
b7bb3c3ba92945688f07056f4905a69d3cab9ef2
|
diff --git a/lib/rubycritic/smell.rb b/lib/rubycritic/smell.rb
index <HASH>..<HASH> 100644
--- a/lib/rubycritic/smell.rb
+++ b/lib/rubycritic/smell.rb
@@ -11,6 +11,10 @@ module Rubycritic
attribute :message
attribute :score
attribute :type
+
+ def paths
+ locations.map(&:path)
+ end
end
end
diff --git a/test/lib/rubycritic/smell_test.rb b/test/lib/rubycritic/smell_test.rb
index <HASH>..<HASH> 100644
--- a/test/lib/rubycritic/smell_test.rb
+++ b/test/lib/rubycritic/smell_test.rb
@@ -14,6 +14,14 @@ describe Rubycritic::Smell do
smell.locations.must_equal [location]
end
+ it "has a paths reader" do
+ path = "./foo"
+ line = "42"
+ location = Rubycritic::Location.new("./foo", "42")
+ smell = Rubycritic::Smell.new(:locations => [location])
+ smell.paths.must_equal [path]
+ end
+
it "has a message reader" do
message = "This smells"
smell = Rubycritic::Smell.new(:message => message)
|
Add a paths reader to Smell
|
whitesmith_rubycritic
|
train
|
88c008970ba447498d646c1072dc5a90e7b3c42e
|
diff --git a/bag.go b/bag.go
index <HASH>..<HASH> 100644
--- a/bag.go
+++ b/bag.go
@@ -126,11 +126,19 @@ func (b *Bag) Manifest() (*Manifest, error) {
// METHODS FOR MANAGING BAG TAG FILES
func (b *Bag) AddTagfile(name string) error {
- tf, err := NewTagFile(filepath.Join(b.Path(), name))
- if tf != nil {
- b.tagfiles[name] = tf
+ tagPath := filepath.Join(b.Path(), name)
+ if err := os.MkdirAll(filepath.Dir(tagPath), 0766); err != nil {
+ return err
}
- return err
+ tf, err := NewTagFile(tagPath)
+ if err != nil {
+ return err
+ }
+ b.tagfiles[name] = tf
+ if err := tf.Create(); err != nil {
+ return err
+ }
+ return nil
}
func (b *Bag) TagFile(name string) (*TagFile, error) {
@@ -163,7 +171,6 @@ func (b *Bag) Path() string {
// This method writes all the relevant tag and manifest files to finish off the
// bag.
func (b *Bag) Close() (errs []error) {
-
// Write all the manifest files.
for _, mf := range b.manifests {
if err := mf.Create(); err != nil {
@@ -172,13 +179,12 @@ func (b *Bag) Close() (errs []error) {
}
// TODO Write all the tag files.
- for key := range b.tagfiles {
- if tf, err := b.TagFile(key); err != nil {
+ for _, tf := range b.tagfiles {
+ if err := os.MkdirAll(filepath.Dir(tf.Name()), 0766); err != nil {
+ errs = append(errs, err)
+ }
+ if err := tf.Create(); err != nil {
errs = append(errs, err)
- } else {
- if err = tf.Create(); err != nil {
- errs = append(errs, err)
- }
}
}
return
diff --git a/bag_test.go b/bag_test.go
index <HASH>..<HASH> 100644
--- a/bag_test.go
+++ b/bag_test.go
@@ -10,12 +10,12 @@ import (
"testing"
)
-func setupTestBag() (*bagins.Bag, error) {
+func setupTestBag(bagName string) (*bagins.Bag, error) {
algo := "sha1"
hsh, _ := bagutil.LookupHashFunc(algo)
cs := bagutil.NewChecksumAlgorithm(algo, hsh)
- bag, err := bagins.NewBag(os.TempDir(), "_GOTESTBAG_", cs)
+ bag, err := bagins.NewBag(os.TempDir(), bagName, cs)
if err != nil {
return nil, err
}
@@ -46,7 +46,7 @@ func TestNewBag(t *testing.T) {
}
// It should create a bag without any errors.
- bag, err := setupTestBag()
+ bag, err := setupTestBag("_GOTEST_NEWBAG_")
defer os.RemoveAll(bag.Path())
// It should find all of the following files and directories.
@@ -77,7 +77,7 @@ func TestAddFile(t *testing.T) {
defer os.Remove(fi.Name())
// Setup the Test Bag
- bag, _ := setupTestBag()
+ bag, _ := setupTestBag("_GOTEST_ADDFILE_")
defer os.RemoveAll(bag.Path())
// It should return an error when trying to add a file that doesn't exist.
@@ -121,7 +121,7 @@ func TestAddDir(t *testing.T) {
defer os.RemoveAll(srcDir)
// Setup the test bag
- bag, _ := setupTestBag()
+ bag, _ := setupTestBag("_GOTEST_ADDDIR_")
defer os.RemoveAll(bag.Path())
// It should produce no errors
@@ -155,7 +155,7 @@ func TestAddDir(t *testing.T) {
func TestManifest(t *testing.T) {
// Setup the test bag
- bag, _ := setupTestBag()
+ bag, _ := setupTestBag("_GOTEST_MANIFEST_")
defer os.RemoveAll(bag.Path())
// It should have the expected name and return no error.
@@ -172,4 +172,31 @@ func TestManifest(t *testing.T) {
func TestAddTagFile(t *testing.T) {
// Setup the test bag
+ bag, err := setupTestBag("_GOTEST_ADDTAGFILE_")
+ if err != nil {
+ t.Error("Test bag already exists, remove to continue testing.")
+ }
+ defer os.RemoveAll(bag.Path())
+
+ // It should throw an error when a bag tagfilename is passed.
+ badTagName := "customtag/directory/tag"
+ if err := bag.AddTagfile(badTagName); err == nil {
+ t.Error("Did not generate an error when trying to add bag tagname:", badTagName)
+ }
+
+ // It should not throw an error.
+ newTagName := "customtag/directory/tag.txt"
+ if err := bag.AddTagfile(newTagName); err != nil {
+ t.Error(err)
+ }
+
+ // It should be able to lookup the tagfile by name.
+ if _, err := bag.TagFile(newTagName); err != nil {
+ t.Error(err)
+ }
+
+ // It should find the file inside the bag.
+ if _, err := os.Stat(filepath.Join(bag.Path(), newTagName)); err != nil {
+ t.Error(err)
+ }
}
|
Adding tag files to subdirectories now works.
|
APTrust_bagins
|
train
|
a113acdda8f752cfbf8b15449eb76b21527bebfc
|
diff --git a/mod/forum/view.php b/mod/forum/view.php
index <HASH>..<HASH> 100644
--- a/mod/forum/view.php
+++ b/mod/forum/view.php
@@ -154,7 +154,7 @@
}
if (($forum->trackingtype == FORUM_TRACKING_OPTIONAL) && forum_tp_can_track_forums($forum)) {
- echo '<div class="helplink" id="trackinglink">'. forum_get_tracking_link($forum). '</div';
+ echo '<div class="helplink" id="trackinglink">'. forum_get_tracking_link($forum). '</div>';
}
}
|
merged from <I> :: MDL-<I> :: added closing '>' in line <I>.
|
moodle_moodle
|
train
|
19e8a822bcae958e36517f74366f375499c5826c
|
diff --git a/lib/supervisor.js b/lib/supervisor.js
index <HASH>..<HASH> 100644
--- a/lib/supervisor.js
+++ b/lib/supervisor.js
@@ -148,7 +148,7 @@ function run(
var headline = "elm-test " + elmTestVersion;
var bar = _.repeat("-", headline.length);
- console.log("\n" + headline + "\n" + bar + "\n\n");
+ console.log("\n" + headline + "\n" + bar + "\n");
}
printResult(result.message);
|
Remove a spurious newline.
|
rtfeldman_node-test-runner
|
train
|
6fec25b0d317a496e7669708192a09dd6d403eac
|
diff --git a/src/Middleware/RequestBodyBufferMiddleware.php b/src/Middleware/RequestBodyBufferMiddleware.php
index <HASH>..<HASH> 100644
--- a/src/Middleware/RequestBodyBufferMiddleware.php
+++ b/src/Middleware/RequestBodyBufferMiddleware.php
@@ -4,10 +4,10 @@ namespace React\Http\Middleware;
use OverflowException;
use Psr\Http\Message\ServerRequestInterface;
+use React\Http\Io\BufferedBody;
use React\Http\Io\IniUtil;
use React\Promise\Stream;
use React\Stream\ReadableStreamInterface;
-use RingCentral\Psr7\BufferStream;
final class RequestBodyBufferMiddleware
{
@@ -38,7 +38,7 @@ final class RequestBodyBufferMiddleware
if ($size === 0 || !$body instanceof ReadableStreamInterface) {
// replace with empty body if body is streaming (or buffered size exceeds limit)
if ($body instanceof ReadableStreamInterface || $size > $this->sizeLimit) {
- $request = $request->withBody(new BufferStream(0));
+ $request = $request->withBody(new BufferedBody(''));
}
return $stack($request);
@@ -51,9 +51,7 @@ final class RequestBodyBufferMiddleware
}
return Stream\buffer($body, $sizeLimit)->then(function ($buffer) use ($request, $stack) {
- $stream = new BufferStream(\strlen($buffer));
- $stream->write($buffer);
- $request = $request->withBody($stream);
+ $request = $request->withBody(new BufferedBody($buffer));
return $stack($request);
}, function ($error) use ($stack, $request, $body) {
diff --git a/tests/ServerTest.php b/tests/ServerTest.php
index <HASH>..<HASH> 100644
--- a/tests/ServerTest.php
+++ b/tests/ServerTest.php
@@ -110,6 +110,35 @@ final class ServerTest extends TestCase
$this->assertSame('beforeokafter', $called);
}
+ public function testPostFormData()
+ {
+ $loop = Factory::create();
+ $deferred = new Deferred();
+ $server = new Server($loop, function (ServerRequestInterface $request) use ($deferred) {
+ $deferred->resolve($request);
+ });
+
+ $server->listen($this->socket);
+ $this->socket->emit('connection', array($this->connection));
+ $this->connection->emit('data', array("POST / HTTP/1.0\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 7\r\n\r\nfoo=bar"));
+
+ $request = Block\await($deferred->promise(), $loop);
+ assert($request instanceof ServerRequestInterface);
+
+ $form = $request->getParsedBody();
+
+ $this->assertTrue(isset($form['foo']));
+ $this->assertEquals('bar', $form['foo']);
+
+ $this->assertEquals(array(), $request->getUploadedFiles());
+
+ $body = $request->getBody();
+
+ $this->assertSame(7, $body->getSize());
+ $this->assertSame(7, $body->tell());
+ $this->assertSame('foo=bar', (string) $body);
+ }
+
public function testPostFileUpload()
{
$loop = Factory::create();
@@ -132,11 +161,14 @@ final class ServerTest extends TestCase
}
});
- $parsedRequest = Block\await($deferred->promise(), $loop);
- $this->assertNotEmpty($parsedRequest->getUploadedFiles());
- $this->assertEmpty($parsedRequest->getParsedBody());
+ $request = Block\await($deferred->promise(), $loop);
+ assert($request instanceof ServerRequestInterface);
+
+ $this->assertEmpty($request->getParsedBody());
+
+ $this->assertNotEmpty($request->getUploadedFiles());
- $files = $parsedRequest->getUploadedFiles();
+ $files = $request->getUploadedFiles();
$this->assertTrue(isset($files['file']));
$this->assertCount(1, $files);
@@ -144,6 +176,37 @@ final class ServerTest extends TestCase
$this->assertSame('hello.txt', $files['file']->getClientFilename());
$this->assertSame('text/plain', $files['file']->getClientMediaType());
$this->assertSame("hello\r\n", (string)$files['file']->getStream());
+
+ $body = $request->getBody();
+
+ $this->assertSame(220, $body->getSize());
+ $this->assertSame(220, $body->tell());
+ }
+
+ public function testPostJsonWillNotBeParsedByDefault()
+ {
+ $loop = Factory::create();
+ $deferred = new Deferred();
+ $server = new Server($loop, function (ServerRequestInterface $request) use ($deferred) {
+ $deferred->resolve($request);
+ });
+
+ $server->listen($this->socket);
+ $this->socket->emit('connection', array($this->connection));
+ $this->connection->emit('data', array("POST / HTTP/1.0\r\nContent-Type: application/json\r\nContent-Length: 6\r\n\r\n[true]"));
+
+ $request = Block\await($deferred->promise(), $loop);
+ assert($request instanceof ServerRequestInterface);
+
+ $this->assertNull($request->getParsedBody());
+
+ $this->assertSame(array(), $request->getUploadedFiles());
+
+ $body = $request->getBody();
+
+ $this->assertSame(6, $body->getSize());
+ $this->assertSame(0, $body->tell());
+ $this->assertSame('[true]', (string) $body);
}
public function testServerReceivesBufferedRequestByDefault()
|
Keep request body in memory also after consuming request body
|
reactphp_http
|
train
|
448a747566d648260a2877c1019ed1a07fc02fa0
|
diff --git a/addon/components/week-glance.js b/addon/components/week-glance.js
index <HASH>..<HASH> 100644
--- a/addon/components/week-glance.js
+++ b/addon/components/week-glance.js
@@ -26,16 +26,22 @@ export default Component.extend({
const year = this.get('year');
const week = this.get('week');
const startOfWeek = this.get('startOfWeek');
- const targetDate = moment().year(year).isoWeek(week);
- return targetDate.day(startOfWeek).hour(0).minute(0);
+ const targetDate = moment();
+ targetDate.year(year);
+ targetDate.isoWeek(week);
+ targetDate.day(startOfWeek);
+ return targetDate.hour(0).minute(0);
}),
midnightAtTheEndOfThisWeek: computed('i18n.locale', 'year', 'week', 'endOfWeek', async function(){
this.get('i18n'); //we need to use the service so the CP will re-fire
const year = this.get('year');
const week = this.get('week');
const endOfWeek = this.get('endOfWeek');
- const targetDate = moment().year(year).isoWeek(week);
- return targetDate.day(endOfWeek).hour(23).minute(59).second(59);
+ const targetDate = moment();
+ targetDate.year(year);
+ targetDate.isoWeek(week);
+ targetDate.day(endOfWeek);
+ return targetDate.hour(23).minute(59).second(59);
}),
title: computed('midnightAtTheStartOfThisWeek', 'midnightAtTheEndOfThisWeek', async function(){
const midnightAtTheStartOfThisWeek = await this.get('midnightAtTheStartOfThisWeek');
@@ -52,8 +58,6 @@ export default Component.extend({
return `${from}-${to}`;
}
-
-
}),
weekEvents: computed('midnightAtTheStartOfThisWeek', 'midnightAtTheEndOfThisWeek', async function() {
|
accomodate for null value year and dual nature of moment attribute accessors.
|
ilios_common
|
train
|
f7c5b76f24d88a389af31f2fcb90ed4bffe1c8d9
|
diff --git a/lib/redis/connection/memory.rb b/lib/redis/connection/memory.rb
index <HASH>..<HASH> 100644
--- a/lib/redis/connection/memory.rb
+++ b/lib/redis/connection/memory.rb
@@ -976,14 +976,7 @@ class Redis
data_type_check(key, ZSet)
return [] unless data[key]
- # Sort by score, or if scores are equal, key alphanum
- results = data[key].sort do |(k1, v1), (k2, v2)|
- if v1 == v2
- k1 <=> k2
- else
- v1 <=> v2
- end
- end
+ results = sort_keys(data[key])
# Select just the keys unless we want scores
results = results.map(&:first) unless with_scores
results[start..stop].flatten.map(&:to_s)
@@ -1077,7 +1070,7 @@ class Redis
count = 10
if args.size.odd?
- raise_argument_error('scan')
+ raise_argument_error('zscan')
end
if idx = args.index("MATCH")
@@ -1094,13 +1087,7 @@ class Redis
cursor = start_cursor
next_keys = []
- sorted_keys = data[key].sort do |(k1, v1), (k2, v2)|
- if v1 == v2
- k1 <=> k2
- else
- v1 <=> v2
- end
- end
+ sorted_keys = sort_keys(data[key])
if start_cursor + count >= sorted_keys.length
next_keys = sorted_keys.to_a.select { |k| File.fnmatch(match, k[0]) } [start_cursor..-1]
@@ -1173,6 +1160,17 @@ class Redis
(1..-number).map { data[key].to_a[rand(data[key].size)] }.flatten
end
end
+
+ def sort_keys(arr)
+ # Sort by score, or if scores are equal, key alphanum
+ sorted_keys = arr.sort do |(k1, v1), (k2, v2)|
+ if v1 == v2
+ k1 <=> k2
+ else
+ v1 <=> v2
+ end
+ end
+ end
end
end
end
|
refactor key-value sorting into method
|
guilleiguaran_fakeredis
|
train
|
20a9e10aa1346ce48ab5ca4eff03ac52d9210d0a
|
diff --git a/molgenis-data-mysql/src/main/java/org/molgenis/data/mysql/MySqlConfiguration.java b/molgenis-data-mysql/src/main/java/org/molgenis/data/mysql/MySqlConfiguration.java
index <HASH>..<HASH> 100644
--- a/molgenis-data-mysql/src/main/java/org/molgenis/data/mysql/MySqlConfiguration.java
+++ b/molgenis-data-mysql/src/main/java/org/molgenis/data/mysql/MySqlConfiguration.java
@@ -14,6 +14,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
+import org.springframework.jdbc.core.JdbcTemplate;
@Configuration
public class MySqlConfiguration
@@ -34,10 +35,16 @@ public class MySqlConfiguration
private MetaDataServiceImpl writableMetaDataService;
@Bean
+ public AsyncJdbcTemplate asyncJdbcTemplate()
+ {
+ return new AsyncJdbcTemplate(new JdbcTemplate(dataSource));
+ }
+
+ @Bean
@Scope("prototype")
public MysqlRepository mysqlRepository()
{
- return new MysqlRepository(dataSource);
+ return new MysqlRepository(dataSource, asyncJdbcTemplate());
}
@Bean
diff --git a/molgenis-data-mysql/src/main/java/org/molgenis/data/mysql/MysqlRepository.java b/molgenis-data-mysql/src/main/java/org/molgenis/data/mysql/MysqlRepository.java
index <HASH>..<HASH> 100644
--- a/molgenis-data-mysql/src/main/java/org/molgenis/data/mysql/MysqlRepository.java
+++ b/molgenis-data-mysql/src/main/java/org/molgenis/data/mysql/MysqlRepository.java
@@ -61,12 +61,21 @@ public class MysqlRepository extends AbstractCrudRepository implements Manageabl
private MysqlRepositoryCollection repositoryCollection;
private DataSource dataSource;
- public MysqlRepository(DataSource dataSource)
+ /**
+ * Creates a new MysqlRepository.
+ *
+ * @param dataSource
+ * the datasource to use to execute statements on the Mysql database
+ * @param asyncJdbcTemplate
+ * {@link AsyncJdbcTemplate} to use to execute DDL statements in an isolated transaction on the Mysql
+ * database
+ */
+ public MysqlRepository(DataSource dataSource, AsyncJdbcTemplate asyncJdbcTemplate)
{
super(null);// TODO url
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);
- this.asyncJdbcTemplate = new AsyncJdbcTemplate(jdbcTemplate);
+ this.asyncJdbcTemplate = asyncJdbcTemplate;
}
public void setMetaData(EntityMetaData metaData)
diff --git a/molgenis-data-mysql/src/test/java/org/molgenis/AppConfig.java b/molgenis-data-mysql/src/test/java/org/molgenis/AppConfig.java
index <HASH>..<HASH> 100644
--- a/molgenis-data-mysql/src/test/java/org/molgenis/AppConfig.java
+++ b/molgenis-data-mysql/src/test/java/org/molgenis/AppConfig.java
@@ -9,6 +9,7 @@ import org.molgenis.data.RepositoryDecoratorFactory;
import org.molgenis.data.meta.MetaDataServiceImpl;
import org.molgenis.data.meta.WritableMetaDataService;
import org.molgenis.data.meta.WritableMetaDataServiceDecorator;
+import org.molgenis.data.mysql.AsyncJdbcTemplate;
import org.molgenis.data.mysql.EmbeddedMysqlDatabaseBuilder;
import org.molgenis.data.mysql.MysqlRepository;
import org.molgenis.data.mysql.MysqlRepositoryCollection;
@@ -20,6 +21,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
+import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
@@ -62,10 +64,16 @@ public class AppConfig
}
@Bean
+ public AsyncJdbcTemplate asyncJdbcTemplate()
+ {
+ return new AsyncJdbcTemplate(new JdbcTemplate(dataSource()));
+ }
+
+ @Bean
@Scope("prototype")
public MysqlRepository mysqlRepository()
{
- return new MysqlRepository(dataSource());
+ return new MysqlRepository(dataSource(), asyncJdbcTemplate());
}
@Bean
|
share the async jdbc template to keep the total number of threads in check
|
molgenis_molgenis
|
train
|
8da28dc20a84517e42eb3499a6b3bd663073e3d0
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -36,7 +36,7 @@ setup_requires = [
]
install_requires = [
- 'inspire-schemas~=61.1.3',
+ 'inspire-schemas~=61.0',
'inspire-utils~=3.0,>=3.0.0',
'pypeg2~=2.0,>=2.15.2',
'python-dateutil~=2.0,>=2.6.1',
|
setup: revert unnecessary upgrade of inspire-schemas
|
inspirehep_inspire-query-parser
|
train
|
2c102b83df04cf5ce1cf3a59a20533e1636d7fe7
|
diff --git a/.gitignore b/.gitignore
index <HASH>..<HASH> 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,3 @@
*.pyc
-docs/_build
\ No newline at end of file
+docs/_build
+pyes/tests/.noseids
diff --git a/pyes/convert_errors.py b/pyes/convert_errors.py
index <HASH>..<HASH> 100644
--- a/pyes/convert_errors.py
+++ b/pyes/convert_errors.py
@@ -37,7 +37,7 @@ exception_patterns_trailing = {
'] Already exists': pyes.exceptions.AlreadyExistsException,
}
-def raise_if_error(status, result):
+def raise_if_error(status, result, request=None):
"""Raise an appropriate exception if the result is an error.
Any result with a status code of 400 or higher is considered an error.
@@ -48,6 +48,9 @@ def raise_if_error(status, result):
The status code and result can be retrieved from the exception by accessing its
status and result properties.
+ Optionally, this can take the original RestRequest instance which generate this
+ error, which will then get included in the exception.
+
"""
assert isinstance(status, int)
@@ -55,10 +58,10 @@ def raise_if_error(status, result):
return
if status == 404 and isinstance(result, dict) and 'error' not in result:
- raise pyes.exceptions.NotFoundException("Item not found", status, result)
+ raise pyes.exceptions.NotFoundException("Item not found", status, result, request)
if not isinstance(result, dict) or 'error' not in result:
- raise pyes.exceptions.ElasticSearchException("Unknown exception type", status, result)
+ raise pyes.exceptions.ElasticSearchException("Unknown exception type", status, result, request)
error = result['error']
if '; nested: ' in error:
@@ -72,13 +75,15 @@ def raise_if_error(status, result):
msg = bits[1]
if msg.endswith(']'):
msg = msg[:-1]
- raise excClass(msg, status, result)
+ if request:
+ msg += ' (' + str(request) + ')'
+ raise excClass(msg, status, result, request)
for pattern, excClass in exception_patterns_trailing.iteritems():
if not error.endswith(pattern):
continue
# For these exceptions, the returned value is the whole descriptive
# message.
- raise excClass(error, status, result)
+ raise excClass(error, status, result, request)
- raise pyes.exceptions.ElasticSearchException(error, status, result)
+ raise pyes.exceptions.ElasticSearchException(error, status, result, request)
diff --git a/pyes/es.py b/pyes/es.py
index <HASH>..<HASH> 100644
--- a/pyes/es.py
+++ b/pyes/es.py
@@ -327,7 +327,7 @@ class ES(object):
# in the exception.
raise ElasticSearchException(response.body, response.status, response.body)
if response.status != 200:
- raise_if_error(response.status, decoded)
+ raise_if_error(response.status, decoded, request)
if isinstance(decoded, dict):
decoded = DotDict(decoded)
return decoded
diff --git a/pyes/exceptions.py b/pyes/exceptions.py
index <HASH>..<HASH> 100644
--- a/pyes/exceptions.py
+++ b/pyes/exceptions.py
@@ -54,10 +54,14 @@ class ElasticSearchException(Exception):
appropriate.
"""
- def __init__(self, error, status=None, result=None):
+ def __init__(self, error, status=None, result=None, request=None):
super(ElasticSearchException, self).__init__(error)
self.status = status
- self.result = result
+ if request:
+ self.result = str(result) + str(request)
+ else:
+ self.result = result
+ self.request = request
class ElasticSearchIllegalArgumentException(ElasticSearchException):
pass
diff --git a/pyes/fakettypes.py b/pyes/fakettypes.py
index <HASH>..<HASH> 100644
--- a/pyes/fakettypes.py
+++ b/pyes/fakettypes.py
@@ -190,6 +190,19 @@ class RestRequest(object):
self.headers = headers
self.body = body
+ def __repr__(self):
+ full_url = 'http://localhost:9200' + self.uri
+ if len(self.parameters) > 0:
+ full_url += '?'
+ for k, v in self.parameters:
+ full_url += k + '&' + v
+
+ return "curl -X%s %s -d '%s'" % (
+ Method._VALUES_TO_NAMES[self.method],
+ full_url,
+ self.body,
+ )
+
class RestResponse:
"""
Attributes:
|
hacked in a nice curl message to exceptions, for easier debugging
|
aparo_pyes
|
train
|
fbf5b4353df1ffe48061d147973b7fda7e8fce63
|
diff --git a/src/kba/pipeline/_clean_visible.py b/src/kba/pipeline/_clean_visible.py
index <HASH>..<HASH> 100644
--- a/src/kba/pipeline/_clean_visible.py
+++ b/src/kba/pipeline/_clean_visible.py
@@ -17,6 +17,7 @@ import logging
import itertools
import traceback
import lxml.etree
+from _clean_html import drop_invalid_and_upper_utf8_chars
logger = logging.getLogger(__name__)
@@ -139,6 +140,8 @@ def make_clean_visible_file(i_chunk, clean_visible_path):
try:
## is UTF-8, and etree wants .text to be unicode
doc.text = si.body.clean_visible.decode('utf8')
+ except ValueError:
+ doc.text = drop_invalid_and_upper_utf8_chars(si.body.clean_visible.decode('utf8'))
except Exception, exc:
## this should never ever fail, because if it does,
## then it means that clean_visible (or more likely
|
catching a rare error in clean_visible: a tiny tiny
fraction of the kba-<I> "social" stream apparently has control characters or other invalid UTF8
chars, and we were treating this as text/plain which does not go through clean_html, so they
were not getting caught before reaching serialization by lxml for tagging.
|
trec-kba_streamcorpus-pipeline
|
train
|
90768f341030efa8e1ce253172bda37e324ae3fc
|
diff --git a/lib/dynamoid/adapter.rb b/lib/dynamoid/adapter.rb
index <HASH>..<HASH> 100644
--- a/lib/dynamoid/adapter.rb
+++ b/lib/dynamoid/adapter.rb
@@ -179,9 +179,7 @@ module Dynamoid
end
def self.adapter_plugin_class
- unless Dynamoid.const_defined?(:AdapterPlugin) && Dynamoid::AdapterPlugin.const_defined?(Dynamoid::Config.adapter.camelcase)
- require "dynamoid/adapter_plugin/#{Dynamoid::Config.adapter}"
- end
+ require "dynamoid/adapter_plugin/#{Dynamoid::Config.adapter}"
Dynamoid::AdapterPlugin.const_get(Dynamoid::Config.adapter.camelcase)
end
|
Fix threadsafety of Dynamoid::Adapter
|
Dynamoid_dynamoid
|
train
|
491ba3adb4ec11b3ad216b1c8d7d71e7e8a03108
|
diff --git a/qualysapi/config.py b/qualysapi/config.py
index <HASH>..<HASH> 100644
--- a/qualysapi/config.py
+++ b/qualysapi/config.py
@@ -5,7 +5,7 @@ import getpass
import logging
import os
import stat
-from configparser import ConfigParser
+from configparser import RawConfigParser
import qualysapi.settings as qcs
@@ -25,7 +25,7 @@ __license__ = "BSD-new"
class QualysConnectConfig:
- """ Class to create a ConfigParser and read user/password details
+ """ Class to create a RawConfigParser and read user/password details
from an ini file.
"""
@@ -50,8 +50,8 @@ class QualysConnectConfig:
# Set home path for file.
self._cfgfile = os.path.join(os.path.expanduser("~"), filename)
- # create ConfigParser to combine defaults and input from config file.
- self._cfgparse = ConfigParser(qcs.defaults)
+ # create RawConfigParser to combine defaults and input from config file.
+ self._cfgparse = RawConfigParser(qcs.defaults)
if self._cfgfile:
self._cfgfile = os.path.realpath(self._cfgfile)
|
Read configuration values as literal strings
Configuration values were read using ConfigParser, which does string interpolation, for instance making it impossible to use "%". This commit switches to RawConfigParser to avoid any special treatment of configuration values.
|
paragbaxi_qualysapi
|
train
|
c315afc242d3bef4431d27af601760d81a9d2179
|
diff --git a/amd/object-store/ReadOnlyObjectStore.js b/amd/object-store/ReadOnlyObjectStore.js
index <HASH>..<HASH> 100644
--- a/amd/object-store/ReadOnlyObjectStore.js
+++ b/amd/object-store/ReadOnlyObjectStore.js
@@ -63,7 +63,8 @@ define(["./AbstractReadOnlyStorage", "./CursorDirection", "./ReadOnlyIndex", "./
var direction;
var comparator = null;
var storage = this;
- if (CURSOR_DIRECTIONS.indexOf(order) > -1) {
+ var isCursorDirection = ((typeof order === "string") && (CURSOR_DIRECTIONS.indexOf(order.toUpperCase()) > -1)) || (CURSOR_DIRECTIONS.indexOf(order) > -1);
+ if (isCursorDirection) {
direction = order;
} else if (order === null) {
direction = CursorDirection.NEXT;
diff --git a/es6/object-store/ReadOnlyObjectStore.js b/es6/object-store/ReadOnlyObjectStore.js
index <HASH>..<HASH> 100644
--- a/es6/object-store/ReadOnlyObjectStore.js
+++ b/es6/object-store/ReadOnlyObjectStore.js
@@ -220,7 +220,10 @@ export default class ReadOnlyObjectStore extends AbstractReadOnlyStorage {
let direction
let comparator = null
let storage = this
- if (CURSOR_DIRECTIONS.indexOf(order) > -1) {
+ let isCursorDirection = ((typeof order === "string") &&
+ (CURSOR_DIRECTIONS.indexOf(order.toUpperCase()) > -1)) ||
+ (CURSOR_DIRECTIONS.indexOf(order) > -1)
+ if (isCursorDirection) {
direction = order
} else if (order === null) {
direction = CursorDirection.NEXT
|
fixed support for case-insensitive cursor direction strings
|
jurca_indexed-db.es6
|
train
|
d233be704191e6dd72a93548efc4b42bb29c29c9
|
diff --git a/transport/src/main/java/io/netty/channel/socket/aio/AioSocketChannel.java b/transport/src/main/java/io/netty/channel/socket/aio/AioSocketChannel.java
index <HASH>..<HASH> 100644
--- a/transport/src/main/java/io/netty/channel/socket/aio/AioSocketChannel.java
+++ b/transport/src/main/java/io/netty/channel/socket/aio/AioSocketChannel.java
@@ -224,7 +224,7 @@ public class AioSocketChannel extends AbstractAioChannel implements SocketChanne
channel.notifyFlushFutures(cause);
channel.pipeline().fireExceptionCaught(cause);
- ByteBuf buf = channel.pipeline().outboundByteBuffer();
+ ByteBuf buf = channel.unsafe().directOutboundContext().outboundByteBuffer();
if (!buf.readable()) {
buf.discardReadBytes();
}
|
AIO: Act on the right ByteBuf when a exception was caught during write
|
netty_netty
|
train
|
f0aab3749f74ee6628e0c7e0e4ec30383dd51016
|
diff --git a/bin/importjs.js b/bin/importjs.js
index <HASH>..<HASH> 100755
--- a/bin/importjs.js
+++ b/bin/importjs.js
@@ -83,88 +83,3 @@ program.command('goto <word> <pathToFile>')
});
program.parse(process.argv);
-// require 'import_js'
-// require 'slop'
-// require 'json'
-//
-// opts = Slop.parse do |o|
-// o.banner = 'Usage: import-js [<path-to-file>] [options] ...'
-// o.string '-w', '--word', 'A word/variable to import'
-// o.bool '--goto', 'Instead of importing, just print the path to a module'
-// o.array '--selections', 'A list of resolved selections, e.g. Foo:0,Bar:1'
-// o.string '--stdin-file-path',
-// 'A path to the file whose content is being passed in as stdin. ' \
-// 'This is used as a way to make sure that the right configuration ' \
-// 'is applied.'
-// o.bool '--overwrite',
-// 'Overwrite the file with the result after importing (the default ' \
-// 'behavior is to print to stdout). This only applies if you are ' \
-// 'passing in a file (<path-to-file>) as the first positional argument.'
-// o.string '--filename', '(deprecated) Alias for --stdin-file-path'
-// o.bool '--rewrite',
-// 'Rewrite all current imports to match Import-JS configuration. ' \
-// 'This does not add missing imports or remove unused imports.'
-//
-// o.on '-v', '--version', 'Prints the current version' do
-// puts ImportJS::VERSION
-// exit
-// end
-// o.on '-h', '--help', 'Prints help' do
-// puts o
-// exit
-// end
-// end
-//
-// path_to_file = opts.arguments[0] || opts['stdin-file-path'] || opts[:filename]
-//
-// file_contents = if STDIN.tty?
-// unless path_to_file
-// puts 'Error: missing <path-to-file>'
-// puts opts
-// exit 1
-// end
-// File.read(path_to_file).split("\n")
-// else
-// STDIN.read.split("\n")
-// end
-//
-// if opts[:selections]
-// # Convert array of string tuples to hash, `word` => `selectedIndex`
-// opts[:selections] = Hash[opts[:selections].map do |str|
-// tuple = str.split(':')
-// [tuple.first, tuple[1].to_i]
-// end]
-// end
-//
-// editor = ImportJS::CommandLineEditor.new(
-// file_contents, opts.to_hash.merge(path_to_file: path_to_file))
-// importer = ImportJS::Importer.new(editor)
-// if opts.goto?
-// importer.goto
-// elsif opts[:word]
-// importer.import
-// elsif opts[:rewrite]
-// importer.rewrite_imports
-// else
-// importer.fix_imports
-// end
-//
-// if opts.goto?
-// # Print the path to the module to go to
-// puts editor.goto
-// elsif opts[:overwrite]
-// File.open(path_to_file, 'w') do |f|
-// f.write editor.current_file_content + "\n"
-// end
-// else
-// # Print resulting file to stdout
-// puts editor.current_file_content
-// end
-//
-// # Print messages to stderr
-// meta = {
-// messages: editor.messages,
-// }
-// ask = editor.ask_for_selections
-// meta[:ask_for_selections] = ask unless ask.empty?
-// STDERR.puts meta.to_json
|
Remove old CLI code (commented out)
I believe we now support roughly the same feature set as the old tool.
So we don't need this lying around anymore.
|
Galooshi_import-js
|
train
|
967abc53ae7f03fe6cb22aa1969bb0909960dcb6
|
diff --git a/src/test/java/com/profesorfalken/wmi4java/WMI4JavaTest.java b/src/test/java/com/profesorfalken/wmi4java/WMI4JavaTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/com/profesorfalken/wmi4java/WMI4JavaTest.java
+++ b/src/test/java/com/profesorfalken/wmi4java/WMI4JavaTest.java
@@ -184,31 +184,35 @@ public class WMI4JavaTest {
*/
@Test
public void testQueryWMIObject() {
- String queryResultPS =WMI4Java.get().PowerShellEngine()
- .queryWMIObject(WMIClass.WIN32_PROCESS, Arrays.asList("Name", "CommandLine", "ProcessId"),
- Arrays.asList("$_.Name -eq \"java.exe\""));
- assertNotNull("Query result should not be null!", queryResultPS);
- assertTrue("Query result should not be empty! ",
- !queryResultPS.isEmpty());
-
- String queryResultVBS = WMI4Java.get().VBSEngine()
- .queryWMIObject(WMIClass.WIN32_PROCESS, Arrays.asList("Name", "CommandLine", "ProcessId"),
- Arrays.asList("Name = 'java.exe'"));
- assertNotNull("Query result should not be null!", queryResultVBS);
- assertTrue("Query result should not be empty! ",
- !queryResultVBS.isEmpty());
-
- System.out.println(queryResultPS);
- System.out.println(queryResultVBS);
-
- String[] queryResultPSLines = queryResultPS.split("\\r?\\n");
- String[] queryResultVBSLines = queryResultVBS.split("\\r?\\n");
-
- //Compare first and last line ignoring spaces
- assertTrue("PS and VBS query result are different!", CharMatcher.WHITESPACE.removeFrom(queryResultPSLines[0])
- .equals(CharMatcher.WHITESPACE.removeFrom(queryResultVBSLines[0])));
- assertTrue("PS and VBS query result are different!",
- CharMatcher.WHITESPACE.removeFrom(queryResultPSLines[queryResultPSLines.length-1])
- .equals(CharMatcher.WHITESPACE.removeFrom(queryResultVBSLines[queryResultVBSLines.length-1])));
+ System.out.println("testQueryWMIObject");
+
+ if (OSDetector.isWindows()) {
+ String queryResultPS = WMI4Java.get().PowerShellEngine()
+ .queryWMIObject(WMIClass.WIN32_PROCESS, Arrays.asList("Name", "CommandLine", "ProcessId"),
+ Arrays.asList("$_.Name -eq \"java.exe\""));
+ assertNotNull("Query result should not be null!", queryResultPS);
+ assertTrue("Query result should not be empty! ",
+ !queryResultPS.isEmpty());
+
+ String queryResultVBS = WMI4Java.get().VBSEngine()
+ .queryWMIObject(WMIClass.WIN32_PROCESS, Arrays.asList("Name", "CommandLine", "ProcessId"),
+ Arrays.asList("Name = 'java.exe'"));
+ assertNotNull("Query result should not be null!", queryResultVBS);
+ assertTrue("Query result should not be empty! ",
+ !queryResultVBS.isEmpty());
+
+ System.out.println(queryResultPS);
+ System.out.println(queryResultVBS);
+
+ String[] queryResultPSLines = queryResultPS.split("\\r?\\n");
+ String[] queryResultVBSLines = queryResultVBS.split("\\r?\\n");
+
+ //Compare first and last line ignoring spaces
+ assertTrue("PS and VBS query result are different!", CharMatcher.WHITESPACE.removeFrom(queryResultPSLines[0])
+ .equals(CharMatcher.WHITESPACE.removeFrom(queryResultVBSLines[0])));
+ assertTrue("PS and VBS query result are different!",
+ CharMatcher.WHITESPACE.removeFrom(queryResultPSLines[queryResultPSLines.length - 1])
+ .equals(CharMatcher.WHITESPACE.removeFrom(queryResultVBSLines[queryResultVBSLines.length - 1])));
+ }
}
}
|
Avoid to execute new test in a no-Windows environment
|
profesorfalken_WMI4Java
|
train
|
9d37a83a79e346312d0f93cdff346a8c9ca56d8a
|
diff --git a/test/general/openpgp.js b/test/general/openpgp.js
index <HASH>..<HASH> 100644
--- a/test/general/openpgp.js
+++ b/test/general/openpgp.js
@@ -365,7 +365,11 @@ describe('OpenPGP.js public api tests', function() {
openpgp.initWorker({ path:'../dist/openpgp.worker.js' });
});
- tests();
+ if (openpgp.getWorker()) {
+ tests();
+ } else {
+ it.skip('No Web Worker support --> skipping tests.');
+ }
after(function() {
openpgp.destroyWorker(); // cleanup worker in case of failure
|
Api tests work under node.js
|
openpgpjs_openpgpjs
|
train
|
fa2e4cac8952f52ce69a10fc846dd4e2fb48ae01
|
diff --git a/lib/artifactory/resources/base.rb b/lib/artifactory/resources/base.rb
index <HASH>..<HASH> 100644
--- a/lib/artifactory/resources/base.rb
+++ b/lib/artifactory/resources/base.rb
@@ -91,6 +91,30 @@ module Artifactory
from_hash(client.get(url), client: client)
end
+ #
+ # List all the child text elements in the Artifactory configuration file
+ # of a node matching the specified xpath
+ #
+ # @param [String] xpath
+ # xpath expression for the parent element whose children are to be listed
+ #
+ # @param [REXML] config
+ # Artifactory config as an REXML file
+ #
+ # @param [Hash] options
+ # the list of options
+ #
+ def list_from_config(xpath, config, options = {})
+ REXML::XPath.match(config, xpath).map do |r|
+ hash = {}
+
+ r.each_element_with_text do |l|
+ hash[l.name] = l.get_text
+ end
+ from_hash(hash, options)
+ end
+ end
+
#
# Construct a new object from the hash.
#
diff --git a/lib/artifactory/resources/layout.rb b/lib/artifactory/resources/layout.rb
index <HASH>..<HASH> 100644
--- a/lib/artifactory/resources/layout.rb
+++ b/lib/artifactory/resources/layout.rb
@@ -48,30 +48,6 @@ module Artifactory
private
#
- # List all the child text elements in the Artifactory configuration file
- # of a node matching the specified xpath
- #
- # @param [String] xpath
- # xpath expression for the parent element whose children are to be listed
- #
- # @param [REXML] config
- # Artifactory config as an REXML file
- #
- # @param [Hash] options
- # the list of options
- #
- def list_from_config(xpath, config, options = {})
- REXML::XPath.match(config, xpath).map do |r|
- hash = {}
-
- r.each_element_with_text do |l|
- hash[l.name] = l.get_text
- end
- from_hash(hash, options)
- end
- end
-
- #
# Find all the sibling text elements in the Artifactory configuration file
# of a node matching the specified xpath
#
diff --git a/lib/artifactory/resources/mail_server.rb b/lib/artifactory/resources/mail_server.rb
index <HASH>..<HASH> 100644
--- a/lib/artifactory/resources/mail_server.rb
+++ b/lib/artifactory/resources/mail_server.rb
@@ -47,29 +47,6 @@ module Artifactory
end
private
- #
- # List all the child text elements in the Artifactory configuration file
- # of a node matching the specified xpath
- #
- # @param [String] xpath
- # xpath expression for the parent element whose children are to be listed
- #
- # @param [REXML] config
- # Artifactory config as an REXML file
- #
- # @param [Hash] options
- # the list of options
- #
- def list_from_config(xpath, config, options = {})
- REXML::XPath.match(config, xpath).map do |r|
- hash = {}
-
- r.each_element_with_text do |l|
- hash[l.name] = l.get_text
- end
- from_hash(hash, options)
- end
- end
#
# Find all the sibling text elements in the Artifactory configuration file
|
Move shared 'list_from_config' method to base class.
|
chef_artifactory-client
|
train
|
3280f7b0111b705d2218096121a20f6471f1f4e8
|
diff --git a/sockeye/utils.py b/sockeye/utils.py
index <HASH>..<HASH> 100644
--- a/sockeye/utils.py
+++ b/sockeye/utils.py
@@ -629,7 +629,7 @@ def acquire_gpus(requested_device_ids: List[int], lock_dir: str = "/tmp",
if master_lock is not None and not any_failed:
try:
yield acquired_gpus
- except:
+ except: # pylint: disable=try-except-raise
raise
return
|
Ignore pylint warning about bare except statement (#<I>)
|
awslabs_sockeye
|
train
|
a9f87dbf95feb2d73a7028bc1ac21f6868f6ac67
|
diff --git a/tests/PresenceChannelTest.php b/tests/PresenceChannelTest.php
index <HASH>..<HASH> 100644
--- a/tests/PresenceChannelTest.php
+++ b/tests/PresenceChannelTest.php
@@ -4,7 +4,6 @@ namespace BeyondCode\LaravelWebSockets\Test;
use BeyondCode\LaravelWebSockets\API\TriggerEvent;
use BeyondCode\LaravelWebSockets\Server\Exceptions\InvalidSignature;
-use Carbon\Carbon;
use GuzzleHttp\Psr7\Request;
use Illuminate\Http\JsonResponse;
use Pusher\Pusher;
diff --git a/tests/PrivateChannelTest.php b/tests/PrivateChannelTest.php
index <HASH>..<HASH> 100644
--- a/tests/PrivateChannelTest.php
+++ b/tests/PrivateChannelTest.php
@@ -4,7 +4,6 @@ namespace BeyondCode\LaravelWebSockets\Test;
use BeyondCode\LaravelWebSockets\API\TriggerEvent;
use BeyondCode\LaravelWebSockets\Server\Exceptions\InvalidSignature;
-use Carbon\Carbon;
use GuzzleHttp\Psr7\Request;
use Illuminate\Http\JsonResponse;
use Pusher\Pusher;
diff --git a/tests/PublicChannelTest.php b/tests/PublicChannelTest.php
index <HASH>..<HASH> 100644
--- a/tests/PublicChannelTest.php
+++ b/tests/PublicChannelTest.php
@@ -3,7 +3,6 @@
namespace BeyondCode\LaravelWebSockets\Test;
use BeyondCode\LaravelWebSockets\API\TriggerEvent;
-use Carbon\Carbon;
use GuzzleHttp\Psr7\Request;
use Illuminate\Http\JsonResponse;
use Pusher\Pusher;
|
Apply fixes from StyleCI (#<I>)
|
beyondcode_laravel-websockets
|
train
|
547ad921d8f26b6cd3e0b8c727bfee13e7e6277c
|
diff --git a/lib/pluginManager/index.js b/lib/pluginManager/index.js
index <HASH>..<HASH> 100644
--- a/lib/pluginManager/index.js
+++ b/lib/pluginManager/index.js
@@ -31,6 +31,28 @@ var pluginManager = {
// load one plugin running related plugin.js file
loadPlugin: function loadPlugin(pluginFile, npmModuleName, projectPath) {
pluginManager.plugins[npmModuleName] = require(pluginFile)( projectPath , Plugin);
+ },
+
+ /**
+ * Get plugin list from config or from npm_modules folder
+ *
+ * @param {Object} we we.js
+ * @param {Function} done callback
+ * @return {Array} Plugin names list
+ */
+ getPluginsList: function getPluginsList(we, done) {
+ if (we.config.plugins) {
+ return done(null, Object.keys(we.config.plugins));
+ }
+
+ fs.readdir(nodeModulesPath, function (err, folders) {
+ if (err) return done(err);
+
+ done(null, folders.filter(function (f) {
+ if (f.substring(0, 3) === 'we-') return true;
+ return false;
+ }));
+ });
}
};
@@ -45,7 +67,7 @@ pluginManager.loadPlugins = function loadPlugins(we, done) {
if (! _.isEmpty(pluginManager.plugins) )
return pluginManager.plugins;
- fs.readdir(nodeModulesPath, function (err, folders) {
+ this.getPluginsList(we, function (err, folders) {
if (err) return done(err);
var npmModuleName, pluginPath, pluginFile;
@@ -85,7 +107,7 @@ pluginManager.loadPlugins = function loadPlugins(we, done) {
}
}
- // check if is plugin
+ // check if project is plugin
if (pluginManager.isPlugin(projectPath) ) {
// save plugin name
pluginManager.pluginNames.push('project');
@@ -117,6 +139,10 @@ pluginManager.isInstalled = function isInstalled(name) {
return false;
}
+/**
+ * Get the plugin install.js script if is avaible
+ * @param {String} name plugin name
+ */
pluginManager.getPluginInstallScript = function getPluginInstallScript(name) {
var pluginFolder;
// get folder, for suport with project plugin
diff --git a/lib/staticConfig/index.js b/lib/staticConfig/index.js
index <HASH>..<HASH> 100644
--- a/lib/staticConfig/index.js
+++ b/lib/staticConfig/index.js
@@ -11,13 +11,7 @@ var log = require('../log')();
* Config cache
* @type {Object}
*/
-var configs = {
- plugin: {
- // if set enableAll to true we.js ignore the enabled config and will load all plugins on npm_module folder
- enableAll: false,
- enabled: []
- }
-};
+var configs = {};
var configsIsLoad = false;
diff --git a/plugin.js b/plugin.js
index <HASH>..<HASH> 100644
--- a/plugin.js
+++ b/plugin.js
@@ -7,6 +7,8 @@ module.exports = function loadPlugin(projectPath, Plugin) {
var plugin = new Plugin(__dirname);
// set plugin configs
plugin.setConfigs({
+ // plugins to load, default is null for auto load all npm modules starting with we- prefix
+ plugins: null,
// // flag to skip project and plugin install methods
// skipInstall: false,
|
update plugin load to split get plugins method
|
wejs_we-core
|
train
|
683eb77197f62be6a62838d3a76e1332a4f9e694
|
diff --git a/Changelog b/Changelog
index <HASH>..<HASH> 100644
--- a/Changelog
+++ b/Changelog
@@ -23,6 +23,10 @@ Releases
First release that requires Python 3.
+ * Fixed issue where Delocate would attempt to modify the install names of a
+ non-copied library which dynamically links to a copied library.
+ [#120](https://github.com/matthew-brett/delocate/pull/120)
+
* 0.9.0 (Saturday July 17th 2021)
Refactoring, updating and `arm64` (M1) support.
diff --git a/delocate/delocating.py b/delocate/delocating.py
index <HASH>..<HASH> 100644
--- a/delocate/delocating.py
+++ b/delocate/delocating.py
@@ -382,6 +382,7 @@ def delocate_path(
Default is callable rejecting only libraries beginning with
``/usr/lib`` or ``/System``. None means copy all libraries. This will
usually end up copying large parts of the system run-time.
+ Libraries which won't be copied will not be inspected for dependencies.
executable_path : None or str, optional
If not None, an alternative path to use for resolving
`@executable_path`.
@@ -410,23 +411,26 @@ def delocate_path(
raise TypeError('lib_filt_func string can only be "dylibs-only"')
if lib_filt_func is None:
lib_filt_func = (lambda _: True)
+ if copy_filt_func is None:
+ copy_filt_func = (lambda _: True)
if not exists(lib_path):
os.makedirs(lib_path)
+ filt_func = (lambda path: lib_filt_func(path) and copy_filt_func(path))
lib_dict = {} # type: Dict[Text, Dict[Text, Text]]
missing_libs = False
for library_path in walk_directory(
- tree_path, lib_filt_func, executable_path=executable_path
+ tree_path, filt_func, executable_path=executable_path
):
for depending_path, install_name in get_dependencies(
library_path,
executable_path=executable_path,
- filt_func=lib_filt_func,
+ filt_func=filt_func,
):
if depending_path is None:
missing_libs = True
continue
- if copy_filt_func and not copy_filt_func(depending_path):
+ if not filt_func(depending_path):
continue
lib_dict.setdefault(depending_path, {})
lib_dict[depending_path][library_path] = install_name
diff --git a/delocate/tests/test_wheelies.py b/delocate/tests/test_wheelies.py
index <HASH>..<HASH> 100644
--- a/delocate/tests/test_wheelies.py
+++ b/delocate/tests/test_wheelies.py
@@ -188,13 +188,6 @@ def test_fix_plat_dylibs():
dep_mod = pjoin('fakepkg1', 'subpkg', 'module.other')
assert_equal(delocate_wheel('test.whl'),
{realpath(stray_lib): {dep_mod: stray_lib}})
- # With func that does find the module
-
- def func(fn):
- return fn.endswith('.other')
-
- assert_equal(delocate_wheel('test2.whl', lib_filt_func=func),
- {realpath(stray_lib): {dep_mod: stray_lib}})
def _thin_lib(stray_lib, arch):
|
Don't follow libraries which won't be copied.
Combines lib_flit_func and copy_flit_func behavior into one function.
This makes sure that a file which won't be copied will not have its
dependencies analyzed.
Fixes #<I>
Since the previous behavior is assumed to be wrong the tests have been updated.
|
matthew-brett_delocate
|
train
|
20e7cdb3fefc756d50116cbc247379bb26a2ced1
|
diff --git a/benchmark/parse_json_and_marshal.rb b/benchmark/parse_json_and_marshal.rb
index <HASH>..<HASH> 100644
--- a/benchmark/parse_json_and_marshal.rb
+++ b/benchmark/parse_json_and_marshal.rb
@@ -13,6 +13,8 @@ marshal_file = File.new(marshal_filename, 'r')
# warm up the filesystem
json.read
json.rewind
+marshal_file.read
+marshal_file.rewind
hash = {}
|
warming up marshal file pointer too
|
brianmario_yajl-ruby
|
train
|
530ae009a8edfb30b3aa9ff98c0787c72080087f
|
diff --git a/activejdbc/src/main/java/org/javalite/activejdbc/LazyList.java b/activejdbc/src/main/java/org/javalite/activejdbc/LazyList.java
index <HASH>..<HASH> 100644
--- a/activejdbc/src/main/java/org/javalite/activejdbc/LazyList.java
+++ b/activejdbc/src/main/java/org/javalite/activejdbc/LazyList.java
@@ -365,29 +365,30 @@ public class LazyList<T extends Model> extends UnmodifiableLazyList<T> {
* @author Evan Leonard
*/
private void processPolymorphicParent(BelongsToPolymorphicAssociation association) {
- if(delegate.isEmpty()){//no need to process children if no models selected.
+ if (delegate.isEmpty()) { // no need to process children if no models selected.
+ return;
+ }
+ //need to remove duplicates because more than one child can belong to the same parent.
+ Set<Object> distinctParentIds = collectDistinct("parent_id", "parent_type", association.getParentClassName());
+ distinctParentIds.remove(null); // remove null parent id
+ if (distinctParentIds.isEmpty()) {
return;
}
-
final MetaModel parentMetaModel = Registry.instance().getMetaModel(association.getTarget());
- final Map<Object, Model> parentsHasByIds = new HashMap<Object, Model>();
-
- String parentClassName = association.getParentClassName();
+ final Map<Object, Model> parentById = new HashMap<Object, Model>();
- //need to remove duplicates because more than one child can belong to the same parent.
- Object[] noDuplicateArray = new HashSet(collect("parent_id", "parent_type", parentClassName)).toArray();
StringBuilder query = new StringBuilder().append(parentMetaModel.getIdName()).append(" IN (");
- appendQuestions(query, noDuplicateArray.length);
+ appendQuestions(query, distinctParentIds.size());
query.append(')');
- for (Model parent : new LazyList<Model>(query.toString(), parentMetaModel, noDuplicateArray)) {
- parentsHasByIds.put(parentClassName + ":" + parent.getId(), parent);
+ for (Model parent : new LazyList<Model>(query.toString(), parentMetaModel, distinctParentIds.toArray())) {
+ parentById.put(association.getParentClassName() + ":" + parent.getId(), parent);
}
//now that we have the parents in the has, we need to distribute them into list of children that are
//stored in the delegate.
for (Model child : delegate) {
- Model parent = parentsHasByIds.get(parentClassName + ":" + child.get("parent_id"));
- child.setCachedParent(parent); //this could be null, which is fine
+ // parent could be null, which is fine
+ child.setCachedParent(parentById.get(association.getParentClassName() + ":" + child.get("parent_id")));
}
}
@@ -436,32 +437,43 @@ public class LazyList<T extends Model> extends UnmodifiableLazyList<T> {
* @return list of collected values for a column.
*/
public List<Object> collect(String attributeName) {
- hydrate();
List<Object> results = new ArrayList<Object>();
- for (Model model : delegate) {
- results.add(model.get(attributeName));
- }
+ collect(results, attributeName);
return results;
}
public Set<Object> collectDistinct(String attributeName) {
- hydrate();
Set<Object> results = new LinkedHashSet<Object>();
+ collect(results, attributeName);
+ return results;
+ }
+
+ private void collect(Collection<Object> results, String attributeName) {
+ hydrate();
for (Model model : delegate) {
results.add(model.get(attributeName));
}
- return results;
}
public List<Object> collect(String attributeName, String filterAttribute, Object filterValue) {
- hydrate();
List<Object> results = new ArrayList<Object>();
+ collect(results, attributeName, filterAttribute, filterValue);
+ return results;
+ }
+
+ public Set<Object> collectDistinct(String attributeName, String filterAttribute, Object filterValue) {
+ Set<Object> results = new LinkedHashSet<Object>();
+ collect(results, attributeName, filterAttribute, filterValue);
+ return results;
+ }
+
+ private void collect(Collection<Object> results, String attributeName, String filterAttribute, Object filterValue) {
+ hydrate();
for (Model model : delegate) {
if (model.get(filterAttribute).equals(filterValue)) {
results.add(model.get(attributeName));
}
}
- return results;
}
private void appendQuestions(StringBuilder sb, int count) {
|
#<I> Added LazyList.collectDistinct()
|
javalite_activejdbc
|
train
|
dc57a7a5a7670b3103f1882845bfdb07138422db
|
diff --git a/src/Symfony/Component/DomCrawler/Crawler.php b/src/Symfony/Component/DomCrawler/Crawler.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/DomCrawler/Crawler.php
+++ b/src/Symfony/Component/DomCrawler/Crawler.php
@@ -755,7 +755,7 @@ class Crawler extends \SplObjectStorage
throw new \InvalidArgumentException('The current node list is empty.');
}
- $form = new Form($this->getNode(0), $this->uri, $method);
+ $form = new Form($this->getNode(0), $this->uri, $method, $this->baseHref);
if (null !== $values) {
$form->setValues($values);
diff --git a/src/Symfony/Component/DomCrawler/Form.php b/src/Symfony/Component/DomCrawler/Form.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/DomCrawler/Form.php
+++ b/src/Symfony/Component/DomCrawler/Form.php
@@ -34,19 +34,26 @@ class Form extends Link implements \ArrayAccess
private $fields;
/**
+ * @var string
+ */
+ private $baseHref;
+
+ /**
* Constructor.
*
* @param \DOMNode $node A \DOMNode instance
* @param string $currentUri The URI of the page where the form is embedded
* @param string $method The method to use for the link (if null, it defaults to the method defined by the form)
+ * @param string $baseHref The URI of the <base> used for relative links, but not for empty action
*
* @throws \LogicException if the node is not a button inside a form tag
*
* @api
*/
- public function __construct(\DOMNode $node, $currentUri, $method = null)
+ public function __construct(\DOMNode $node, $currentUri, $method = null, $baseHref = null)
{
parent::__construct($node, $currentUri, $method);
+ $this->baseHref = $baseHref;
$this->initialize();
}
@@ -442,6 +449,10 @@ class Form extends Link implements \ArrayAccess
$this->addField($node);
}
}
+
+ if ($this->baseHref && '' !== $this->node->getAttribute('action')) {
+ $this->currentUri = $this->baseHref;
+ }
}
private function addField(\DOMNode $node)
diff --git a/src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php b/src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php
+++ b/src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php
@@ -853,9 +853,12 @@ HTML;
public function getBaseTagWithFormData()
{
return array(
+ array('https://base.com/', 'link/', 'https://base.com/link/', 'https://base.com/link/', '<base> tag does work with a path and relative form action'),
array('/basepath', '/registration', 'http://domain.com/registration', 'http://domain.com/registration', '<base> tag does work with a path and form action'),
array('/basepath', '', 'http://domain.com/registration', 'http://domain.com/registration', '<base> tag does work with a path and empty form action'),
+ array('http://base.com/', '/registration', 'http://base.com/registration', 'http://domain.com/registration', '<base> tag does work with a URL and form action'),
array('http://base.com', '', 'http://domain.com/path/form', 'http://domain.com/path/form', '<base> tag does work with a URL and an empty form action'),
+ array('http://base.com/path', '/registration', 'http://base.com/registration', 'http://domain.com/path/form', '<base> tag does work with a URL and form action'),
);
}
|
[DomCrawler] Invalid uri created from forms if base tag present
|
symfony_symfony
|
train
|
0716732371c8f8d2c53f2a225b426788e5f291d4
|
diff --git a/budget/transactions.py b/budget/transactions.py
index <HASH>..<HASH> 100644
--- a/budget/transactions.py
+++ b/budget/transactions.py
@@ -606,16 +606,16 @@ class Transactions():
self.filter_range(i)
# If selected category item is "Income" or "Expenses"
elif self.selected_category_index == self.ALL_INCOME_UNIQUE_ID or self.selected_category_index == self.ALL_EXPENSES_UNIQUE_ID:
- if self.selected_category == self.entryRows[i][5]:
+ if self.selected_category == self.entryRows[i][self.ENTRY_ROW_TYPE_INDEX]:
self.filter_range(i)
- elif self.selected_category != self.entryRows[i][5]:
+ elif self.selected_category != self.entryRows[i][self.ENTRY_ROW_TYPE_INDEX]:
self.hide_entry(i)
# If selected category item is "Uncategorized"
elif (self.selected_category_index == self.UNCATEGORIZED_INCOME_UNIQUE_ID or self.selected_category_index == self.UNCATEGORIZED_EXPENSES_UNIQUE_ID):
- if (self.selected_category == self.entryRows[i][5] and self.entryRows[i][self.ENTRY_ROW_LAYOUT_WIDGET_INDEX][self.ENTRY_ROW_CATEGORY_LABEL_INDEX].get_label() == "Uncategorized"):
+ if (self.selected_category == self.entryRows[i][self.ENTRY_ROW_TYPE_INDEX] and self.entryRows[i][self.ENTRY_ROW_LAYOUT_WIDGET_INDEX][self.ENTRY_ROW_CATEGORY_LABEL_INDEX].get_label() == "Uncategorized"):
self.filter_range(i)
- elif (self.selected_category != self.entryRows[i][5] or self.entryRows[i][self.ENTRY_ROW_LAYOUT_WIDGET_INDEX][self.ENTRY_ROW_CATEGORY_LABEL_INDEX].get_label() != "Uncategorized"):
+ elif (self.selected_category != self.entryRows[i][self.ENTRY_ROW_TYPE_INDEX] or self.entryRows[i][self.ENTRY_ROW_LAYOUT_WIDGET_INDEX][self.ENTRY_ROW_CATEGORY_LABEL_INDEX].get_label() != "Uncategorized"):
self.hide_entry(i)
# If selected menu item is not "All"
|
And mroe refactoring
|
mthxx_Budget
|
train
|
51185e2712fc0a773d103dbac467e4c95da93096
|
diff --git a/lib/wechat/responder.rb b/lib/wechat/responder.rb
index <HASH>..<HASH> 100644
--- a/lib/wechat/responder.rb
+++ b/lib/wechat/responder.rb
@@ -189,7 +189,7 @@ module Wechat
render text: process_response(response_msg)
end
else
- render nothing: true, status: 200, content_type: 'text/html'
+ head :ok, content_type: 'text/html'
end
response_msg.save_session if response_msg.is_a?(Wechat::Message) && Wechat.config.have_session_class
|
Rails 5 prefer head instead of render nothing
|
Eric-Guo_wechat
|
train
|
4601fb4f3c90669d89632f8879e4ec5d3f759f02
|
diff --git a/lib/dotenv/rails.rb b/lib/dotenv/rails.rb
index <HASH>..<HASH> 100644
--- a/lib/dotenv/rails.rb
+++ b/lib/dotenv/rails.rb
@@ -9,7 +9,7 @@ require "dotenv"
#
# See https://github.com/bkeepers/dotenv/issues/219
if defined?(Rake.application)
- is_running_specs = Rake.application.top_level_tasks.grep(/^spec(:|$)/).any?
+ is_running_specs = Rake.application.top_level_tasks.grep(/^(parallel:spec|spec(:|$))/).any?
Rails.env = ENV["RAILS_ENV"] ||= "test" if is_running_specs
end
|
fix for parallel spec tasks initializing in development
|
bkeepers_dotenv
|
train
|
a274e0ad2b0d36f24b48c15ceeeb912b77a59264
|
diff --git a/gputools/core/ocltypes.py b/gputools/core/ocltypes.py
index <HASH>..<HASH> 100644
--- a/gputools/core/ocltypes.py
+++ b/gputools/core/ocltypes.py
@@ -91,13 +91,13 @@ def _wrap_OCLArray(cls):
def write_array(self, data, **kwargs):
queue = get_device().queue
- return cl.enqueue_write_buffer(queue, self.data, prepare(data),
+ return cl.enqueue_copy(queue, self.data, prepare(data),
**kwargs)
def copy_image(self, img, **kwargs):
queue = get_device().queue
return cl.enqueue_copy(queue, self.data, img, offset=0,
- origin=(0, 0), region=img.shape,
+ origin=(0,)*len(img.shape), region=img.shape,
**kwargs)
def copy_image_resampled(self, img, **kwargs):
@@ -153,6 +153,16 @@ def _wrap_OCLImage(cls):
def prepare(arr):
return np.require(arr, None, "C")
+
+ def imshape(self):
+ # 1d images dont have a shape but only a width
+ if hasattr(self, "shape"):
+ imshape = self.shape
+ else:
+ imshape = (self.width,)
+ return imshape
+
+
@classmethod
def from_array(cls, arr, *args, **kwargs):
@@ -243,13 +253,13 @@ def _wrap_OCLImage(cls):
queue = get_device().queue
self.dtype = buf.dtype
return cl.enqueue_copy(queue, self, buf.data, offset=0,
- origin=(0, 0), region=self.shape, **kwargs)
+ origin=(0,)*len(self.imshape()), region=self.imshape(), **kwargs)
def copy_image(self, img, **kwargs):
queue = get_device().queue
return cl.enqueue_copy(queue, self, img,
- src_origin=(0, 0),
- dest_origin=(0, 0),
+ src_origin=(0,)*len(self.imshape()),
+ dest_origin=(0,)*len(self.imshape()),
region=self.shape,
**kwargs)
@@ -260,18 +270,13 @@ def _wrap_OCLImage(cls):
kern_str = "img%dd_to_img" % len(img.shape)
OCLArray._resample_prog.run_kernel(kern_str,
- self.shape, None,
+ self.imshape(), None,
img, self)
def write_array(self, data):
queue = get_device().queue
- # 1d images dont have a shape but only a width
- if hasattr(self, "shape"):
- imshape = self.shape
- else:
- imshape = (self.width,)
-
+ imshape = self.imshape()
ndim = len(imshape)
dshape = data.shape
# if clImg.format.channel_order in [cl.channel_order.RGBA,
@@ -290,15 +295,13 @@ def _wrap_OCLImage(cls):
# origin = (0,)*ndim,
# region = imshape)
+
def copy_buffer(self, buf):
"""
copy content of buf into im
"""
queue = get_device().queue
- if hasattr(self, "shape"):
- imshape = self.shape
- else:
- imshape = (self.width,)
+ imshape = self.imshape()
assert imshape == buf.shape[::-1]
ndim = len(imshape)
@@ -310,18 +313,16 @@ def _wrap_OCLImage(cls):
def get(self, **kwargs):
queue = get_device().queue
- if hasattr(self, "shape"):
- imshape = self.shape
- else:
- imshape = (self.width,)
+ imshape = self.imshape()
dshape = imshape[::-1]
ndim = len(imshape)
if self.num_channels > 1:
dshape += (self.num_channels,)
# dshape = (self.num_channels,) + dshape
out = np.empty(dshape, dtype=self.dtype)
- cl.enqueue_read_image(queue, self, [0] * ndim, imshape, out)
+ #cl.enqueue_read_image(queue, self, [0] * ndim, imshape, out)
+ cl.enqueue_copy(queue, out, self, origin = (0,)*ndim, region = imshape)
return out
# return out.reshape(dshape)
@@ -329,6 +330,7 @@ def _wrap_OCLImage(cls):
cls.from_array = from_array
cls.empty = empty
cls.empty_like = empty_like
+ cls.imshape = imshape
cls.copy_buffer = copy_buffer
cls.copy_image = copy_image
diff --git a/tests/utils/test_histogram.py b/tests/utils/test_histogram.py
index <HASH>..<HASH> 100644
--- a/tests/utils/test_histogram.py
+++ b/tests/utils/test_histogram.py
@@ -1,7 +1,9 @@
import numpy as np
from gputools.utils.histogram import histogram
from time import time
+import pytest
+@pytest.mark.skip(reason="WIP")
def test_histograms(return_if_fail=False):
np.random.seed(0)
|
Remove deprecated enqueue_write/read functions
|
maweigert_gputools
|
train
|
7d0f1f11cb7a9c6dfcf654298777b88cb6a1e680
|
diff --git a/salt/modules/rh_service.py b/salt/modules/rh_service.py
index <HASH>..<HASH> 100644
--- a/salt/modules/rh_service.py
+++ b/salt/modules/rh_service.py
@@ -44,6 +44,7 @@ def __virtual__():
'''
# Enable on these platforms only.
enable = set((
+ 'XenServer',
'RedHat',
'CentOS',
'ScientificLinux',
@@ -57,6 +58,8 @@ def __virtual__():
'McAfee OS Server'
))
if __grains__['os'] in enable:
+ if __grains__['os'] == 'XenServer':
+ return __virtualname__
if __grains__['os'] == 'SUSE':
if str(__grains__['osrelease']).startswith('11'):
return __virtualname__
|
fix for: service.enabled fails on xen server #<I>
|
saltstack_salt
|
train
|
888c48ec232d36998e5fcf85606a4cecd1165632
|
diff --git a/lib/nodes/lib.js b/lib/nodes/lib.js
index <HASH>..<HASH> 100644
--- a/lib/nodes/lib.js
+++ b/lib/nodes/lib.js
@@ -319,19 +319,21 @@ registry.decl(GitLibraryNodeName, ScmLibraryNodeName, /** @lends GitLibraryNode.
* @param {String} o.target Library path.
* @param {String} o.url Repository URL.
* @param {String[]} [o.paths=['']] Paths to checkout.
- * @param {String} [o.treeish='master'] Treeish to checkout.
+ * @param {String} [o.treeish] Treeish (commit hash or tag) to checkout.
+ * @param {String} [o.branch='master'] Branch to checkout.
*/
__constructor: function(o) {
this.__base(o);
- this.treeish = o.treeish || 'master';
+ this.treeish = o.treeish;
+ this.branch = o.branch || 'master';
},
getInitialCheckoutCmd: function(url, target) {
- return UTIL.format('git clone --progress %s %s && cd %s && git checkout %s', url, target, target, this.treeish);
+ return UTIL.format('git clone --progress %s %s && cd %s && git checkout %s', url, target, target, this.treeish || this.branch);
},
getUpdateCmd: function(url, target) {
- return UTIL.format('cd %s && git checkout HEAD~ && git branch -D %s ; git fetch origin && git checkout --track -b %s origin/%s', target, this.treeish, this.treeish, this.treeish);
+ return UTIL.format('cd %s && git fetch origin && git reset --hard %s', target, this.treeish || 'origin/' + this.branch);
}
});
|
Git library checkout fixed to work with commit hashes (close #<I>)
Parameter branch is added to specify branch name. Use treeish to specify
commit or tag.
|
bem-archive_bem-tools
|
train
|
0e82fc2485d97a3f5f7e424e03dad486aaff0941
|
diff --git a/furious/_pkg_meta.py b/furious/_pkg_meta.py
index <HASH>..<HASH> 100644
--- a/furious/_pkg_meta.py
+++ b/furious/_pkg_meta.py
@@ -1,2 +1,2 @@
-version_info = (1, 1, 0)
+version_info = (1, 2, 0)
version = '.'.join(map(str, version_info))
|
Updating to <I>
Incrementing a minor version to <I>
|
Workiva_furious
|
train
|
689b72607e9639261c21fb39cfc2072ee3e741d9
|
diff --git a/caffeine/src/main/java/com/github/benmanes/caffeine/cache/stats/StatsCounter.java b/caffeine/src/main/java/com/github/benmanes/caffeine/cache/stats/StatsCounter.java
index <HASH>..<HASH> 100644
--- a/caffeine/src/main/java/com/github/benmanes/caffeine/cache/stats/StatsCounter.java
+++ b/caffeine/src/main/java/com/github/benmanes/caffeine/cache/stats/StatsCounter.java
@@ -15,6 +15,8 @@
*/
package com.github.benmanes.caffeine.cache.stats;
+import java.util.Map;
+
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.ThreadSafe;
@@ -50,19 +52,20 @@ public interface StatsCounter {
void recordMisses(@Nonnegative int count);
/**
- * Records the successful load of a new entry. This should be called when a cache request causes
- * an entry to be loaded, and the loading completes successfully. In contrast to
- * {@link #recordMisses}, this method should only be called by the loading thread.
+ * Records the successful load of a new entry. This method should be called when a cache request
+ * causes an entry to be loaded (such as by {@link Cache#get} or {@link Map#computeIfAbsent}) and
+ * the loading completes successfully. In contrast to {@link #recordMisses}, this method should
+ * only be called by the loading thread.
*
* @param loadTime the number of nanoseconds the cache spent computing or retrieving the new value
*/
void recordLoadSuccess(@Nonnegative long loadTime);
/**
- * Records the failed load of a new entry. This should be called when a cache request causes an
- * entry to be loaded, but either no value is found or an exception is thrown while loading the
- * entry. In contrast to {@link #recordMisses}, this method should only be called by the loading
- * thread.
+ * Records the failed load of a new entry. This method should be called when a cache request
+ * causes an entry to be loaded (such as by {@link Cache#get} or {@link Map#computeIfAbsent}), but
+ * an exception is thrown while loading the entry or the loading function returns null. In
+ * contrast to {@link #recordMisses}, this method should only be called by the loading thread.
*
* @param loadTime the number of nanoseconds the cache spent computing or retrieving the new value
* prior to discovering the value doesn't exist or an exception being thrown
|
Specify when and how StatsCounter#recordLoadSuccess and recordLoadFailure events are recorded more precisely
|
ben-manes_caffeine
|
train
|
31b56cc67f1f4489119409fbc1f2470e6b850e44
|
diff --git a/teslajsonpy/teslaproxy.py b/teslajsonpy/teslaproxy.py
index <HASH>..<HASH> 100644
--- a/teslajsonpy/teslaproxy.py
+++ b/teslajsonpy/teslaproxy.py
@@ -100,8 +100,9 @@ class TeslaProxy(AuthCaptureProxy):
return return_timer_countdown_refresh_html(
max(30 * (self.waf_retry - self.waf_limit), 120)
if self.waf_retry > self.waf_limit
- else random.random() * self.waf_retry + 5,
+ else random.random() * self.waf_retry + 10,
f"Detected Tesla web application firewall block #{self.waf_retry}. Please wait and then reload the page or wait for the auto reload.",
+ False,
)
self.waf_retry = 0
if resp.content_type == "application/json":
|
fix: increase time for waf retry
|
zabuldon_teslajsonpy
|
train
|
07fb9e754ef6ab10c92b647883b29caad116c76d
|
diff --git a/CMSSeeder.php b/CMSSeeder.php
index <HASH>..<HASH> 100644
--- a/CMSSeeder.php
+++ b/CMSSeeder.php
@@ -271,20 +271,23 @@ class CMSSeeder extends Seeder {
{
// gzero config options
$options = [
- 'main' => [
- 'siteName' => [],
- 'defaultPageSize' => [],
- 'seoTitleAlternativeField' => [],
- 'seoDescriptionAlternativeField' => [],
+ 'general' => [
+ 'siteName' => [],
+ 'siteDesc' => [],
+ 'defaultPageSize' => [],
+ ],
+ 'seo' => [
'seoDescLength' => [],
- 'siteDesc' => [],
+ 'googleAnalyticsId' => [],
]
];
// Propagate Lang options based on gzero config
- foreach ($options['main'] as $key => $option) {
- foreach ($langs as $code => $lang) {
- $options['main'][$key][$code] = config('gzero.' . $key);
+ foreach ($options as $categoryKey => $category) {
+ foreach ($options[$categoryKey] as $key => $option) {
+ foreach ($langs as $code => $lang) {
+ $options[$categoryKey][$key][$code] = config('gzero.' . $key);
+ }
}
}
|
Options seeds and repository fixes KMS-<I>
|
GrupaZero_core
|
train
|
b3acf6a96c8d8da23838b738586a4d20c558f9b2
|
diff --git a/tests/e2e/kubetest2-kops/deployer/common.go b/tests/e2e/kubetest2-kops/deployer/common.go
index <HASH>..<HASH> 100644
--- a/tests/e2e/kubetest2-kops/deployer/common.go
+++ b/tests/e2e/kubetest2-kops/deployer/common.go
@@ -70,10 +70,6 @@ func (d *deployer) verifyKopsFlags() error {
return errors.New("missing required --kops-binary-path")
}
}
- _, err := os.Stat(d.KopsBinaryPath)
- if err != nil {
- return err
- }
switch d.CloudProvider {
case "aws":
|
Don't check for existence of binary path before the build stage has occurred
|
kubernetes_kops
|
train
|
78a35d9a5fff0d93fd92e2973defee4c13ba165d
|
diff --git a/bundles/org.eclipse.orion.client.cf/web/cfui/cfUtil.js b/bundles/org.eclipse.orion.client.cf/web/cfui/cfUtil.js
index <HASH>..<HASH> 100644
--- a/bundles/org.eclipse.orion.client.cf/web/cfui/cfUtil.js
+++ b/bundles/org.eclipse.orion.client.cf/web/cfui/cfUtil.js
@@ -50,6 +50,8 @@ define(['i18n!cfui/nls/messages', 'orion/Deferred', 'orion/i18nUtil', 'orion/URI
},
prepareLaunchConfigurationContent : function(resp, appPath, editLocation){
+ var deferred = new Deferred();
+
var appName = resp.App.name || resp.App.entity.name;
var launchConfName = appName + " on " + resp.Target.Space.Name + " / " + resp.Target.Org.Name;
@@ -59,7 +61,7 @@ define(['i18n!cfui/nls/messages', 'orion/Deferred', 'orion/i18nUtil', 'orion/URI
url = "http://" + host + "." + resp.Domain;
}
- return {
+ deferred.resolve({
CheckState: true,
ToSave: {
ConfigurationName: launchConfName,
@@ -78,7 +80,9 @@ define(['i18n!cfui/nls/messages', 'orion/Deferred', 'orion/i18nUtil', 'orion/URI
Path: appPath
},
Message: "See Manual Deployment Information in the [root folder page](" + editLocation.href + ") to view and manage [" + launchConfName + "](" + resp.ManageUrl + ")"
- };
+ });
+
+ return deferred;
},
/**
diff --git a/bundles/org.eclipse.orion.client.cf/web/cfui/plugins/cFDeployService.js b/bundles/org.eclipse.orion.client.cf/web/cfui/plugins/cFDeployService.js
index <HASH>..<HASH> 100644
--- a/bundles/org.eclipse.orion.client.cf/web/cfui/plugins/cFDeployService.js
+++ b/bundles/org.eclipse.orion.client.cf/web/cfui/plugins/cFDeployService.js
@@ -141,10 +141,14 @@ define(['orion/bootstrap', 'orion/Deferred', 'orion/cfui/cFClient', 'cfui/cfUtil
if (target && appName){
cFService.pushApp(target, appName, decodeURIComponent(project.ContentLocation + appPath)).then(
function(result){
-
var editLocation = new URL("../edit/edit.html#" + project.ContentLocation, window.location.href);
- deferred.resolve(mCfUtil.prepareLaunchConfigurationContent(result, appPath, editLocation));
-
+ mCfUtil.prepareLaunchConfigurationContent(result, appPath, editLocation).then(
+ function(launchConfigurationContent){
+ deferred.resolve(launchConfigurationContent);
+ }, function(error){
+ deferred.reject(error);
+ }
+ );
}, function(error){
if (error.HttpCode === 404){
deferred.resolve({
diff --git a/bundles/org.eclipse.orion.client.cf/web/cfui/plugins/wizards/common/deploymentLogic.js b/bundles/org.eclipse.orion.client.cf/web/cfui/plugins/wizards/common/deploymentLogic.js
index <HASH>..<HASH> 100644
--- a/bundles/org.eclipse.orion.client.cf/web/cfui/plugins/wizards/common/deploymentLogic.js
+++ b/bundles/org.eclipse.orion.client.cf/web/cfui/plugins/wizards/common/deploymentLogic.js
@@ -115,14 +115,19 @@ define(['orion/objects', 'cfui/cfUtil'], function(objects, mCfUtil){
var packager = options.getPackager ? options.getPackager() : null;
var editLocation = new URL("../edit/edit.html#" + contentLocation, window.location.href);
- cfService.pushApp(selection, null, decodeURIComponent(contentLocation + appPath), manifest, saveManifest, packager, instrumentation).then(function(result){
-
- var launchConfigurationContent = mCfUtil.prepareLaunchConfigurationContent(result, appPath, editLocation);
- postMsg(launchConfigurationContent);
-
- }, function(error){
- postError(error, selection);
- });
+ cfService.pushApp(selection, null, decodeURIComponent(contentLocation + appPath), manifest, saveManifest, packager, instrumentation).then(
+ function(result){
+ mCfUtil.prepareLaunchConfigurationContent(result, appPath, editLocation).then(
+ function(launchConfigurationContent){
+ postMsg(launchConfigurationContent);
+ }, function(error){
+ postError(error, selection);
+ }
+ );
+ }, function(error){
+ postError(error, selection);
+ }
+ );
}, postError);
};
|
prepareLaunchConfigurationContent in cfUtil should return deferred
|
eclipse_orion.client
|
train
|
986f15d6e0ac68142219acd1d0e0b1eeb59fb336
|
diff --git a/lib/compile.js b/lib/compile.js
index <HASH>..<HASH> 100644
--- a/lib/compile.js
+++ b/lib/compile.js
@@ -14,7 +14,12 @@ module.exports = {
.fromCallback(cb => compiler.run(cb))
.then(stats => {
- let consoleStats = {
+ if (!this.multiCompile) {
+ stats = { stats: [stats] };
+ }
+
+ const compileOutputPaths = [];
+ const consoleStats = this.webpackConfig.stats || _.get(this, 'webpackConfig[0].stats') || {
colors: true,
hash: false,
version: false,
@@ -22,19 +27,6 @@ module.exports = {
children: false
};
- if (!this.multiCompile) {
- stats = { stats: [stats] };
- if (_.has(this.webpackConfig, 'stats')) {
- consoleStats = this.webpackConfig.stats;
- }
- } else {
- if (_.has(this.webpackConfig, '0.stats')) {
- consoleStats = this.webpackConfig[0].stats;
- }
- }
-
- const compileOutputPaths = [];
-
_.forEach(stats.stats, compileStats => {
this.serverless.cli.consoleLog(compileStats.toString(consoleStats));
diff --git a/tests/compile.test.js b/tests/compile.test.js
index <HASH>..<HASH> 100644
--- a/tests/compile.test.js
+++ b/tests/compile.test.js
@@ -99,4 +99,31 @@ describe('compile', () => {
return null;
});
});
+
+ it('should use correct stats option', () => {
+ const testWebpackConfig = {
+ stats: 'minimal'
+ };
+ let mockStats = {
+ compilation: {
+ errors: [],
+ compiler: {
+ outputPath: 'statsMock-outputPath'
+ }
+ },
+ toString: sandbox.stub().returns('testStats')
+ };
+
+ module.webpackConfig = testWebpackConfig;
+ webpackMock.compilerMock.run.reset();
+ webpackMock.compilerMock.run.yields(null, mockStats);
+ return (expect(module.compile()).to.be.fulfilled)
+ .then(() => {
+ module.webpackConfig = [testWebpackConfig];
+ return (expect(module.compile()).to.be.fulfilled);
+ })
+ .then(() => {
+ expect(mockStats.toString.args).to.eql([[testWebpackConfig.stats], [testWebpackConfig.stats]]);
+ });
+ });
});
|
use one liner solution and update unit test
|
serverless-heaven_serverless-webpack
|
train
|
fcffd20611b05fd9c7751d70bffd7c778cd8c7c9
|
diff --git a/src/Charcoal/Ui/ConditionalizableTrait.php b/src/Charcoal/Ui/ConditionalizableTrait.php
index <HASH>..<HASH> 100644
--- a/src/Charcoal/Ui/ConditionalizableTrait.php
+++ b/src/Charcoal/Ui/ConditionalizableTrait.php
@@ -68,7 +68,7 @@ trait ConditionalizableTrait
);
}
- unset($this->resolvedCondition);
+ $this->resolvedCondition = null;
$this->condition = $condition;
return $this;
}
@@ -105,6 +105,8 @@ trait ConditionalizableTrait
/**
* Parse the widget's conditional logic.
*
+ * @todo Simplify logic by moving `form()` method lookup to relevant form widget.
+ *
* @param callable|string $condition The callable or renderable condition.
* @return boolean
*/
|
Fix ConditionalizableTrait
Replaced `unset()` with NULL assignment to preserve the class property.
|
locomotivemtl_charcoal-ui
|
train
|
1bb1a941a0ec4325b29186f75f86718b36de8c09
|
diff --git a/lib/hawkular/inventory/entities.rb b/lib/hawkular/inventory/entities.rb
index <HASH>..<HASH> 100644
--- a/lib/hawkular/inventory/entities.rb
+++ b/lib/hawkular/inventory/entities.rb
@@ -35,18 +35,6 @@ module Hawkular::Inventory
def to_h
@_hash.dup
end
-
- def to_h
- metric_hash = {}
- metric_hash['name'] = @name
- metric_hash['displayName'] = @display_name
- metric_hash['family'] = @family
- metric_hash['expression'] = @expression
- metric_hash['unit'] = @unit
- metric_hash['labels'] = @labels
- metric_hash['properties'] = @properties
- metric_hash
- end
end
class Operation
diff --git a/lib/hawkular/prometheus/prometheus_api.rb b/lib/hawkular/prometheus/prometheus_api.rb
index <HASH>..<HASH> 100644
--- a/lib/hawkular/prometheus/prometheus_api.rb
+++ b/lib/hawkular/prometheus/prometheus_api.rb
@@ -27,13 +27,11 @@ module Hawkular::Prometheus
results = []
metrics.each do |metric|
query = metric['expression']
- puts("DELETEME p8s - /query?time=#{time}&query=#{query}")
response = http_get "/query?start=#{time}&query=#{query}"
result = response['data']['result'].empty? ? {} : response['data']['result'].first
result['metric'] = metric
results << result
end
- puts("DELETEME p8s - query #{results}")
results
end
@@ -41,23 +39,17 @@ module Hawkular::Prometheus
results = []
metrics.each do |metric|
query = metric['expression']
- puts("DELETEME p8s - /query_range?start=#{starts}&end=#{ends}&step=#{step}&query=#{query}")
response = http_get "/query_range?start=#{starts}&end=#{ends}&step=#{step}&query=#{query}"
result = response['data']['result'].empty? ? {} : response['data']['result'].first
result['metric'] = metric
- # DELETEME this, it's to have this info, as a worker can't show the stdout correctly
- # result['query'] = "/query_range?start=#{starts}&end=#{ends}&step=#{step}&query=#{query}"
results << result
end
- puts("DELETEME p8s - query_range #{results}")
results
end
def up_time(feed_id: nil, starts: nil, ends: nil, step: nil)
query = "up{feed_id=\"#{feed_id}\"}"
- puts("DELETEME p8s - up_time /query_range?start=#{starts}&end=#{ends}&step=#{step}&query=#{query}")
response = http_get "/query_range?start=#{starts}&end=#{ends}&step=#{step}&query=#{query}"
- puts("DELETEME p8s - up_time feed_id #{feed_id} #{response['data']['result']}")
if response['data']['result'].empty?
[]
else
|
HAWKULAR-<I> Minor fixes after merging alerting work
|
hawkular_hawkular-client-ruby
|
train
|
52d598f6fbba74133f0d8c165afcfbc82517728a
|
diff --git a/addon/initializers/component-styles.js b/addon/initializers/component-styles.js
index <HASH>..<HASH> 100644
--- a/addon/initializers/component-styles.js
+++ b/addon/initializers/component-styles.js
@@ -6,29 +6,28 @@ const {
ComponentLookup,
} = Ember;
-export function initialize() {
-
- ComponentLookup.reopen({
- componentFor(name, owner) {
- if (podNames[name] && !owner.application.hasRegistration('component:' + name)) {
- owner.application.register('component:' + name, Component);
- }
- return this._super(...arguments);
+ComponentLookup.reopen({
+ componentFor(name, owner) {
+ if (podNames[name] && !owner.application.hasRegistration('component:' + name)) {
+ owner.application.register('component:' + name, Component);
}
- });
+ return this._super(...arguments);
+ }
+});
- Component.reopen({
- init() {
- this._super(...arguments);
- if (this.get('tagName') !== '' && this._debugContainerKey) {
- const name = this._debugContainerKey.replace('component:', '');
- if (podNames[name]) {
- this.classNames.push(podNames[name]);
- }
+Component.reopen({
+ init() {
+ this._super(...arguments);
+ if (this.get('tagName') !== '' && this._debugContainerKey) {
+ const name = this._debugContainerKey.replace('component:', '');
+ if (podNames[name]) {
+ this.classNames.push(podNames[name]);
}
}
- });
-}
+ }
+});
+
+export function initialize() {}
export default {
name: 'component-styles',
|
moved the componentlookup and compont repoens out of the initialize method so that they will be done before application instatiation rather then after and only ran once for all tests per @rwjblue suggestion
|
ebryn_ember-component-css
|
train
|
f832f0443a780aa95324df5bc9f8426aef74c9ae
|
diff --git a/src/FINDOLOGIC/Export/CSV/CSVExporter.php b/src/FINDOLOGIC/Export/CSV/CSVExporter.php
index <HASH>..<HASH> 100644
--- a/src/FINDOLOGIC/Export/CSV/CSVExporter.php
+++ b/src/FINDOLOGIC/Export/CSV/CSVExporter.php
@@ -32,14 +32,14 @@ class CSVExporter extends Exporter
// To enable pagination, don't write the heading if it's anything but the first page.
if ($start === 0) {
$export = self::HEADING;
- }
- foreach ($this->propertyKeys as $propertyKey) {
- DataHelper::checkForIllegalCsvPropertyKeys($propertyKey);
+ foreach ($this->propertyKeys as $propertyKey) {
+ DataHelper::checkForIllegalCsvPropertyKeys($propertyKey);
- $export .= "\t" . $propertyKey;
+ $export .= "\t" . $propertyKey;
+ }
+ $export .= "\n";
}
- $export .= "\n";
/** @var CSVItem $item */
foreach ($items as $item) {
diff --git a/tests/FINDOLOGIC/Export/Tests/ExporterTest.php b/tests/FINDOLOGIC/Export/Tests/ExporterTest.php
index <HASH>..<HASH> 100644
--- a/tests/FINDOLOGIC/Export/Tests/ExporterTest.php
+++ b/tests/FINDOLOGIC/Export/Tests/ExporterTest.php
@@ -26,4 +26,13 @@ class ExporterTest extends TestCase
$this->assertEquals('Unsupported exporter type.', $e->getMessage());
}
}
+
+ public function testCsvHeadingIsNotWrittenToOutputWhenStartIsNonZero()
+ {
+ $exporter = Exporter::create(Exporter::TYPE_CSV);
+
+ $output = $exporter->serializeItems([], 1, 1, 1);
+
+ $this->assertEquals('', $output);
+ }
}
|
Make sure property column headings are only written to CSV if it's the heading (#<I>)
|
findologic_libflexport
|
train
|
d7b6866c4605bb96e7d4e77002aa2f61ee1fe158
|
diff --git a/maintenancemode/tests/settings.py b/maintenancemode/tests/settings.py
index <HASH>..<HASH> 100644
--- a/maintenancemode/tests/settings.py
+++ b/maintenancemode/tests/settings.py
@@ -54,3 +54,6 @@ SITE_ID = 1
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}}
+
+
+MAINTENANCE_IGNORE_URLS = (re.compile(r"^/ignored.*"),)
diff --git a/maintenancemode/tests/test_middleware.py b/maintenancemode/tests/test_middleware.py
index <HASH>..<HASH> 100644
--- a/maintenancemode/tests/test_middleware.py
+++ b/maintenancemode/tests/test_middleware.py
@@ -127,8 +127,11 @@ class MaintenanceModeMiddlewareTestCase(TestCase):
# A path is ignored when applying the maintanance mode and
# should be reachable normally
with self.settings(MAINTENANCE_MODE=True):
- with self.settings(IGNORE_URLS=(re.compile(r"^/ignored.*"),)):
- response = self.client.get("/ignored/")
+ # Note that we cannot override the settings here, since they are
+ # ONLY used when the middleware starts up.
+ # For this reason, MAINTENANCE_IGNORE_URLS is set in the base
+ # settings file.
+ response = self.client.get("/ignored/")
self.assertContains(response, text="Rendered response page", count=1, status_code=200)
def test_management_command(self):
|
Adjust test setup to work with Django 3
IGNORE_URLS is now based on MAINTENANCE_IGNORE_URLS, but IGNORE_URLS was
still used.
|
shanx_django-maintenancemode
|
train
|
d933a0d974abe0b4c486efd9d47d235b579c5820
|
diff --git a/tools/kevoree-kevscript/lib/elements/sets.js b/tools/kevoree-kevscript/lib/elements/sets.js
index <HASH>..<HASH> 100644
--- a/tools/kevoree-kevscript/lib/elements/sets.js
+++ b/tools/kevoree-kevscript/lib/elements/sets.js
@@ -11,17 +11,10 @@ module.exports = function (model) {
str += '\n';
}
- var value = '';
- if (val.value.indexOf('"') === 0) {
- value = '"'+val.value+'"';
- } else if (val.value.indexOf('\'') === 0) {
- value = '\''+val.value+'\'';
- }
-
if (fragName) {
- str += 'set '+instanceName+'.'+val.name+'/'+fragName+' = '+value;
+ str += 'set '+instanceName+'.'+val.name+'/'+fragName+' = "'+val.value+'"';
} else {
- str += 'set '+instanceName+'.'+val.name+' = '+value;
+ str += 'set '+instanceName+'.'+val.name+' = "'+val.value+'"';
}
}
}
|
rollback attribute value checks (known issue: "" & '' aren't processed properly yet)
|
kevoree_kevoree-js
|
train
|
6e10c463f25581e31622adbe07420aa8f397e10a
|
diff --git a/lib/flapjack/patches.rb b/lib/flapjack/patches.rb
index <HASH>..<HASH> 100644
--- a/lib/flapjack/patches.rb
+++ b/lib/flapjack/patches.rb
@@ -116,3 +116,73 @@ class Redis
end
end
end
+
+module GLI
+ class Command
+ attr_accessor :passthrough
+ def _action
+ @action
+ end
+ end
+
+ class GLIOptionParser
+ class NormalCommandOptionParser
+ def parse!(parsing_result)
+ parsed_command_options = {}
+ command = parsing_result.command
+ arguments = nil
+
+ loop do
+ command._action.call if command.passthrough
+
+ option_parser_factory = OptionParserFactory.for_command(command,@accepts)
+ option_block_parser = CommandOptionBlockParser.new(option_parser_factory, self.error_handler)
+ option_block_parser.command = command
+ arguments = parsing_result.arguments
+
+ arguments = option_block_parser.parse!(arguments)
+
+ parsed_command_options[command] = option_parser_factory.options_hash_with_defaults_set!
+ command_finder = CommandFinder.new(command.commands,command.get_default_command)
+ next_command_name = arguments.shift
+
+ verify_required_options!(command.flags,parsed_command_options[command])
+
+ begin
+ command = command_finder.find_command(next_command_name)
+ rescue AmbiguousCommand
+ arguments.unshift(next_command_name)
+ break
+ rescue UnknownCommand
+ arguments.unshift(next_command_name)
+ # Although command finder could certainy know if it should use
+ # the default command, it has no way to put the "unknown command"
+ # back into the argument stack. UGH.
+ unless command.get_default_command.nil?
+ command = command_finder.find_command(command.get_default_command)
+ end
+ break
+ end
+ end
+
+ parsed_command_options[command] ||= {}
+ command_options = parsed_command_options[command]
+
+ this_command = command.parent
+ child_command_options = command_options
+
+ while this_command.kind_of?(command.class)
+ this_command_options = parsed_command_options[this_command] || {}
+ child_command_options[GLI::Command::PARENT] = this_command_options
+ this_command = this_command.parent
+ child_command_options = this_command_options
+ end
+
+ parsing_result.command_options = command_options
+ parsing_result.command = command
+ parsing_result.arguments = Array(arguments.compact)
+ parsing_result
+ end
+ end
+ end
+end
|
Duckpunch the fuck out of GLI to allow passthrough of args to non-Ruby subcommands
|
flapjack_flapjack
|
train
|
44711f573d0787424e87634b36b76b98065c33ae
|
diff --git a/applications/default/extensions/user/user.js b/applications/default/extensions/user/user.js
index <HASH>..<HASH> 100644
--- a/applications/default/extensions/user/user.js
+++ b/applications/default/extensions/user/user.js
@@ -312,7 +312,6 @@ user.route = function(routes, callback) {
var data = request.body;
var User = application.type('user');
-
User.load(data.username, function(error, account) {
if (error) {
return callback(error);
@@ -328,8 +327,7 @@ user.route = function(routes, callback) {
data.roles = [];
// Create new user resource and save it.
- var newAccount = new User(data);
- newAccount.validateAndSave(function(error, newAccount, errors) {
+ var newAccount = User.create(data).exec(function(error, newAccount, errors) {
if (error) {
return callback(error);
}
|
Fixing creating users. #<I>
|
recidive_choko
|
train
|
8786a0f3f042da50983021499c562ce0f7f13a75
|
diff --git a/lib/cf/cli/app/push.rb b/lib/cf/cli/app/push.rb
index <HASH>..<HASH> 100644
--- a/lib/cf/cli/app/push.rb
+++ b/lib/cf/cli/app/push.rb
@@ -24,7 +24,7 @@ module CF::App
}
input :memory, :desc => "Memory limit"
input :instances, :desc => "Number of instances to run", :type => :integer
- input :command, :desc => "Startup command"
+ input :command, :desc => "Startup command", :default => nil
input :plan, :desc => "Application plan"
input :start, :desc => "Start app after pushing?", :default => true
input :restart, :desc => "Restart app after updating?", :default => true
diff --git a/spec/cf/cli/app/push/create_spec.rb b/spec/cf/cli/app/push/create_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/cf/cli/app/push/create_spec.rb
+++ b/spec/cf/cli/app/push/create_spec.rb
@@ -90,28 +90,10 @@ module CF
context "when the command is not given" do
before { given.delete(:command) }
- shared_examples "an app that can have a custom start command" do
- it "asks for a start command with a default as 'none'" do
- should_ask("Custom startup command", :default => "none") do
- "abcd"
- end
-
- expect(subject[:command]).to eq "abcd"
- end
-
- context "when the user enters 'none'" do
- it "has the command as nil" do
- stub_ask("Custom startup command", :default => "none") do
- "none"
- end
-
- expect(subject[:command]).to be_nil
- end
- end
+ it "defaults to nil" do
+ expect(subject[:command]).to be_nil
end
- include_examples "an app that can have a custom start command"
-
describe "getting the start command" do
before do
FakeFS.activate!
@@ -137,9 +119,8 @@ module CF
end
context "when there is no Procfile in the app's root" do
- it "asks for a start command" do
- should_ask("Custom startup command", :default => "none")
- subject
+ it "is nil" do
+ expect(subject[:command]).to be_nil
end
end
end
diff --git a/spec/cf/cli/app/push_spec.rb b/spec/cf/cli/app/push_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/cf/cli/app/push_spec.rb
+++ b/spec/cf/cli/app/push_spec.rb
@@ -242,7 +242,7 @@ module CF
let(:host) { "" }
let(:domain) { build(:domain) }
let(:inputs) do
- {:name => "some-app",
+ { :name => "some-app",
:instances => 2,
:memory => 1024,
:host => host,
diff --git a/spec/features/push_flow_spec.rb b/spec/features/push_flow_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/features/push_flow_spec.rb
+++ b/spec/features/push_flow_spec.rb
@@ -37,8 +37,7 @@ if ENV['CF_V2_RUN_INTEGRATION']
expect(runner).to say "Instances> 1"
runner.send_return
- expect(runner).to say "Custom startup command> "
- runner.send_return
+ expect(runner).to_not say "Custom startup command> "
expect(runner).to say "Memory Limit>"
runner.send_keys "128M"
diff --git a/spec/support/features_helper.rb b/spec/support/features_helper.rb
index <HASH>..<HASH> 100644
--- a/spec/support/features_helper.rb
+++ b/spec/support/features_helper.rb
@@ -37,9 +37,6 @@ module FeaturesHelper
expect(runner).to say "Instances> 1", 15
runner.send_return
- expect(runner).to say "Custom startup command> "
- runner.send_return
-
expect(runner).to say "Memory Limit>"
runner.send_keys "128M"
|
do not prompt for a start command during push
[Finishes #<I>]
|
cloudfoundry-attic_cf
|
train
|
03a8a4473f6dbcc834301e7c2f0e0edadb23c9b6
|
diff --git a/components/connection_protocols/websocket.js b/components/connection_protocols/websocket.js
index <HASH>..<HASH> 100644
--- a/components/connection_protocols/websocket.js
+++ b/components/connection_protocols/websocket.js
@@ -90,11 +90,21 @@ WebSocketConnection.prototype._chooseAndConnect = function() {
this.stream.on('message', this._readMessage.bind(this));
this.stream.on('disconnected', (code, reason) => {
+ if (this._disconnected) {
+ return;
+ }
+
+ this._disconnected = true;
this.user.emit('debug', 'WebSocket disconnected with code ' + code + ' and reason: ' + reason);
this.user._handleConnectionClose();
});
this.stream.on('error', (err) => {
+ if (this._disconnected) {
+ return;
+ }
+
+ this._disconnected = true;
this.user.emit('debug', 'WebSocket disconnected with error: ' + err.message);
this.user._handleConnectionClose();
});
@@ -106,6 +116,11 @@ WebSocketConnection.prototype._chooseAndConnect = function() {
});
this.stream.on('timeout', () => {
+ if (this._disconnected) {
+ return;
+ }
+
+ this._disconnected = true;
this.user.emit('debug', 'WS connection timed out');
this.user._connectTimeout = Math.min(this.user._connectTimeout * 2, 10000); // 10 seconds max
this.stream.disconnect();
|
Fix issue where a new connection can be attempted twice
|
DoctorMcKay_node-steam-user
|
train
|
fa33f84f6f24e219a0a666dc779c60cc20879fc9
|
diff --git a/src/me/corsin/javatools/misc/PoolableImpl.java b/src/me/corsin/javatools/misc/PoolableImpl.java
index <HASH>..<HASH> 100644
--- a/src/me/corsin/javatools/misc/PoolableImpl.java
+++ b/src/me/corsin/javatools/misc/PoolableImpl.java
@@ -35,8 +35,6 @@ public class PoolableImpl implements Poolable {
if (this.pool != null) {
this.pool.release(this);
this.pool = null;
- } else {
- throw new RuntimeException("Too many releases on " + this.getClass().getSimpleName());
}
}
|
Removed the runtime exception when releasing a PoolableImpl that has not pool
|
rFlex_SCJavaTools
|
train
|
5e679cf6c3989a96a970f7fae05ecb516690b26a
|
diff --git a/lib/redfish/definition.rb b/lib/redfish/definition.rb
index <HASH>..<HASH> 100644
--- a/lib/redfish/definition.rb
+++ b/lib/redfish/definition.rb
@@ -96,5 +96,13 @@ module Redfish
:domains_directory => self.domains_directory
})
end
+
+ def export_to_file(filename)
+ dir = File.dirname(filename)
+ FileUtils.mkdir_p dir
+ File.open(filename, 'wb') do |f|
+ f.write JSON.pretty_generate(self.resolved_data)
+ end
+ end
end
end
diff --git a/test/test_definition.rb b/test/test_definition.rb
index <HASH>..<HASH> 100644
--- a/test/test_definition.rb
+++ b/test/test_definition.rb
@@ -73,4 +73,27 @@ class Redfish::TestDefinition < Redfish::TestCase
assert_equal context.terse?, true
assert_equal context.echo?, true
end
+
+ def test_export_to_file
+ definition = Redfish::DomainDefinition.new('appserver')
+
+ filename2 = "#{temp_dir}/export1.json"
+ definition.export_to_file(filename2)
+ assert File.exist?(filename2)
+ assert_equal JSON.load(File.new(filename2)).to_h, {}
+
+ definition.data['b']['c'] = 1
+ definition.data['a'] = true
+ definition.data['2'] = 1.0
+ definition.data['1'] = false
+ definition.data['4'] = nil
+ definition.data['3'] = 'sdsada'
+
+ filename2 = "#{temp_dir}/export2.json"
+ definition.export_to_file(filename2)
+ assert File.exist?(filename2)
+ data2 = JSON.load(File.new(filename2)).to_h
+ assert_equal data2, {'1' => false, '2' => 1.0, '3' => 'sdsada', '4' => nil, 'a' => true, 'b' => {'c' => 1}}
+ assert_equal data2.keys, %w(1 2 3 4 a b)
+ end
end
|
Start to support exporting to a file
|
realityforge_redfish
|
train
|
09f72464a591b2b094c00a709f0235137e5ff96a
|
diff --git a/src/ServiceManager.php b/src/ServiceManager.php
index <HASH>..<HASH> 100644
--- a/src/ServiceManager.php
+++ b/src/ServiceManager.php
@@ -99,6 +99,11 @@ class ServiceManager implements ServiceLocatorInterface
protected $throwExceptionInCreate = true;
/**
+ * @var array map of characters to be replaced through strtr
+ */
+ protected $canonicalNamesReplacements = array('-' => '', '_' => '', ' ' => '', '\\' => '', '/' => '');
+
+ /**
* @param ConfigInterface $config
*/
public function __construct(ConfigInterface $config = null)
@@ -651,10 +656,12 @@ class ServiceManager implements ServiceLocatorInterface
*/
protected function canonicalizeName($name)
{
- if (!isset($this->canonicalNames[$name])) {
- $this->canonicalNames[$name] = strtolower(str_replace(array('-', '_', ' ', '\\', '/'), '', $name));
+ if (isset($this->canonicalNames[$name])) {
+ return $this->canonicalNames[$name];
}
- return $this->canonicalNames[$name];
+
+ // this is just for performance instead of using str_replace
+ return $this->canonicalNames[$name] = strtolower(strtr($name, $this->canonicalNamesReplacements));
}
/**
|
Micro (Really micro) optimization for canonicalizeName
|
mxc-commons_mxc-servicemanager
|
train
|
400db8b93a06b06c1bc28e00784d84ed99bfef7e
|
diff --git a/structurizr-client/src/com/structurizr/api/StructurizrClient.java b/structurizr-client/src/com/structurizr/api/StructurizrClient.java
index <HASH>..<HASH> 100644
--- a/structurizr-client/src/com/structurizr/api/StructurizrClient.java
+++ b/structurizr-client/src/com/structurizr/api/StructurizrClient.java
@@ -262,6 +262,7 @@ public final class StructurizrClient {
}
workspace.setId(workspaceId);
+ workspace.setThumbnail(null);
workspace.countAndLogWarnings();
CloseableHttpClient httpClient = HttpClients.createSystem();
diff --git a/structurizr-client/src/com/structurizr/encryption/EncryptedWorkspace.java b/structurizr-client/src/com/structurizr/encryption/EncryptedWorkspace.java
index <HASH>..<HASH> 100644
--- a/structurizr-client/src/com/structurizr/encryption/EncryptedWorkspace.java
+++ b/structurizr-client/src/com/structurizr/encryption/EncryptedWorkspace.java
@@ -49,7 +49,6 @@ public final class EncryptedWorkspace extends AbstractWorkspace {
setName(workspace.getName());
setDescription(workspace.getDescription());
setVersion(workspace.getVersion());
- setThumbnail(workspace.getThumbnail());
this.plaintext = plaintext;
this.ciphertext = encryptionStrategy.encrypt(plaintext);
diff --git a/structurizr-client/test/unit/com/structurizr/encryption/EncryptedWorkspaceTests.java b/structurizr-client/test/unit/com/structurizr/encryption/EncryptedWorkspaceTests.java
index <HASH>..<HASH> 100644
--- a/structurizr-client/test/unit/com/structurizr/encryption/EncryptedWorkspaceTests.java
+++ b/structurizr-client/test/unit/com/structurizr/encryption/EncryptedWorkspaceTests.java
@@ -20,7 +20,6 @@ public class EncryptedWorkspaceTests {
public void setUp() throws Exception {
workspace = new Workspace("Name", "Description");
workspace.setVersion("1.2.3");
- workspace.setThumbnail("thumbnail data");
workspace.setId(1234);
encryptionStrategy = new MockEncryptionStrategy();
@@ -34,7 +33,6 @@ public class EncryptedWorkspaceTests {
assertEquals("Name", encryptedWorkspace.getName());
assertEquals("Description", encryptedWorkspace.getDescription());
assertEquals("1.2.3", encryptedWorkspace.getVersion());
- assertEquals("thumbnail data", encryptedWorkspace.getThumbnail());
assertEquals(1234, encryptedWorkspace.getId());
assertSame(workspace, encryptedWorkspace.getWorkspace());
|
No need to send thumbnail data back to the server ... it's already stored there, outside of the workspace JSON document.
|
structurizr_java
|
train
|
f2ef3c4c9b62e49b49c2ef8dda6b7218927f9d3a
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -16,7 +16,7 @@ with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
short_description = 'Calculate RMSD using, translation and rotation, between molecules'
setup(name='rmsd',
- version='1.2.0',
+ version='1.2.2',
maintainer='Jimmy Kromann',
maintainer_email='jimmy@charnley.dk',
description=short_description,
@@ -24,7 +24,6 @@ setup(name='rmsd',
url='https://github.com/charnley/rmsd',
license='BSD-2-Clause',
install_requires=[
- 'argparse',
'numpy',
],
packages=['rmsd'],
@@ -35,7 +34,7 @@ setup(name='rmsd',
"Development Status :: 5 - Production/Stable",
"Environment :: Console",
"Intended Audience :: End Users/Desktop",
- "License :: OSI Approved :: BSD-2-Clause",
+ "License :: OSI Approved :: BSD License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 2.7"
])
|
changes to make it work on pypi
|
charnley_rmsd
|
train
|
3023c7f424d0d07fc5332a89269524681adff48d
|
diff --git a/base.php b/base.php
index <HASH>..<HASH> 100644
--- a/base.php
+++ b/base.php
@@ -184,14 +184,16 @@ class Base extends Prefab implements ArrayAccess {
'/(?<!\w)@(\w(?:[\w\.\[\]]|\->|::)*)/',
function($var) use($fw) {
return '$'.preg_replace_callback(
- '/\.(\w+)|\[((?:[^\[\]]*|(?R))*)\]/',
+ '/\.(\w+)(?!\(|\))|\[((?:[^\[\]]*|(?R))*)\]/',
function($expr) use($fw) {
- return '['.var_export(
- isset($expr[2])?
- $fw->compile($expr[2]):
- (ctype_digit($expr[1])?
- (int)$expr[1]:
- $expr[1]),TRUE).']';
+ return function_exists($expr[1])?
+ ('.'.$expr[1]):
+ ('['.var_export(
+ isset($expr[2])?
+ $fw->compile($expr[2]):
+ (ctype_digit($expr[1])?
+ (int)$expr[1]:
+ $expr[1]),TRUE).']');
},
$var[1]
);
|
Smart detection of PHP functions in template expressions
|
bcosca_fatfree-core
|
train
|
1828d14f59e32832ee25ea1dfb22eb530c27e8d5
|
diff --git a/lib/ORM/DataMapper.php b/lib/ORM/DataMapper.php
index <HASH>..<HASH> 100644
--- a/lib/ORM/DataMapper.php
+++ b/lib/ORM/DataMapper.php
@@ -214,14 +214,25 @@ class DataMapper
$casts = $this->mapper->getTypeCasts();
$setters = $this->mapper->getSetters();
+ if(isset($setters[$name])){
+ $value = $setters[$name]($value);
+ }
+
if(isset($casts[$name])){
$value = $this->castSet($value, $casts[$name]);
}
- if(isset($setters[$name])){
- $value = $setters[$name]($value);
- }
+ $this->modified[$name] = 1;
+ unset($this->columns[$name]);
+ $this->rawColumns[$name] = $value;
+ }
+ /**
+ * @param string $name
+ * @param $value
+ */
+ public function setRawColumn(string $name, $value)
+ {
$this->modified[$name] = 1;
unset($this->columns[$name]);
$this->rawColumns[$name] = $value;
|
Added 'setRawColumn'
|
opis_database
|
train
|
352a935be4eea1035f9f51eff280510f4d3a18e3
|
diff --git a/frontend/src/component/application/__tests__/application-edit-component-test.js b/frontend/src/component/application/__tests__/application-edit-component-test.js
index <HASH>..<HASH> 100644
--- a/frontend/src/component/application/__tests__/application-edit-component-test.js
+++ b/frontend/src/component/application/__tests__/application-edit-component-test.js
@@ -34,7 +34,7 @@ test('renders correctly without permission', () => {
{
instanceId: 'instance-1',
clientIp: '123.123.123.123',
- lastSeen: 1487861809466,
+ lastSeen: '2017-02-23T15:56:49',
sdkVersion: '4.0',
},
],
@@ -88,7 +88,7 @@ test('renders correctly with permissions', () => {
{
instanceId: 'instance-1',
clientIp: '123.123.123.123',
- lastSeen: 1487861809466,
+ lastSeen: '2017-02-23T15:56:49',
sdkVersion: '4.0',
},
],
|
fixed timezone in test timestamp
|
Unleash_unleash
|
train
|
8c2f9e1d2bd0ac0f8b7918d409a32824576e3089
|
diff --git a/cake/libs/router.php b/cake/libs/router.php
index <HASH>..<HASH> 100644
--- a/cake/libs/router.php
+++ b/cake/libs/router.php
@@ -506,7 +506,7 @@ class Router {
* @return array Returns an array containing the altered URL and the parsed extension.
* @access private
*/
- function __parseExtension($url) {
+ private static function __parseExtension($url) {
$ext = null;
if (self::$_parseExtensions) {
@@ -563,7 +563,7 @@ class Router {
* @return void
* @access private
*/
- function __connectDefaultRoutes() {
+ private static function __connectDefaultRoutes() {
if ($plugins = App::objects('plugin')) {
App::import('Core', 'route/PluginShortRoute');
foreach ($plugins as $key => $value) {
|
Removing E_STRICT errors from router
|
cakephp_cakephp
|
train
|
70d3625760aac9994790bd023f1b5060fe1d06c5
|
diff --git a/activerecord/lib/active_record/errors.rb b/activerecord/lib/active_record/errors.rb
index <HASH>..<HASH> 100644
--- a/activerecord/lib/active_record/errors.rb
+++ b/activerecord/lib/active_record/errors.rb
@@ -196,4 +196,7 @@ module ActiveRecord
"Unknown primary key for table #{model.table_name} in model #{model}."
end
end
+
+ class ImmutableRelation < ActiveRecordError
+ end
end
diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb
index <HASH>..<HASH> 100644
--- a/activerecord/lib/active_record/relation/query_methods.rb
+++ b/activerecord/lib/active_record/relation/query_methods.rb
@@ -7,34 +7,36 @@ module ActiveRecord
Relation::MULTI_VALUE_METHODS.each do |name|
class_eval <<-CODE, __FILE__, __LINE__ + 1
- def #{name}_values # def select_values
- @values[:#{name}] || [] # @values[:select] || []
- end # end
- #
- def #{name}_values=(values) # def select_values=(values)
- @values[:#{name}] = values # @values[:select] = values
- end # end
+ def #{name}_values # def select_values
+ @values[:#{name}] || [] # @values[:select] || []
+ end # end
+ #
+ def #{name}_values=(values) # def select_values=(values)
+ raise ImmutableRelation if @loaded # raise ImmutableRelation if @loaded
+ @values[:#{name}] = values # @values[:select] = values
+ end # end
CODE
end
(Relation::SINGLE_VALUE_METHODS - [:create_with]).each do |name|
class_eval <<-CODE, __FILE__, __LINE__ + 1
- def #{name}_value # def readonly_value
- @values[:#{name}] # @values[:readonly]
- end # end
- #
- def #{name}_value=(value) # def readonly_value=(value)
- @values[:#{name}] = value # @values[:readonly] = value
- end # end
+ def #{name}_value # def readonly_value
+ @values[:#{name}] # @values[:readonly]
+ end # end
CODE
end
- def create_with_value
- @values[:create_with] || {}
+ Relation::SINGLE_VALUE_METHODS.each do |name|
+ class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def #{name}_value=(value) # def readonly_value=(value)
+ raise ImmutableRelation if @loaded # raise ImmutableRelation if @loaded
+ @values[:#{name}] = value # @values[:readonly] = value
+ end # end
+ CODE
end
- def create_with_value=(value)
- @values[:create_with] = value
+ def create_with_value
+ @values[:create_with] || {}
end
alias extensions extending_values
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index <HASH>..<HASH> 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -1284,4 +1284,31 @@ class RelationTest < ActiveRecord::TestCase
Post.scoped.find_by!("1 = 0")
end
end
+
+ test "loaded relations cannot be mutated by multi value methods" do
+ relation = Post.scoped
+ relation.to_a
+
+ assert_raises(ActiveRecord::ImmutableRelation) do
+ relation.where! 'foo'
+ end
+ end
+
+ test "loaded relations cannot be mutated by single value methods" do
+ relation = Post.scoped
+ relation.to_a
+
+ assert_raises(ActiveRecord::ImmutableRelation) do
+ relation.limit! 5
+ end
+ end
+
+ test "loaded relations cannot be mutated by merge!" do
+ relation = Post.scoped
+ relation.to_a
+
+ assert_raises(ActiveRecord::ImmutableRelation) do
+ relation.merge! where: 'foo'
+ end
+ end
end
|
disallow mutating a relation once loaded
|
rails_rails
|
train
|
e4c2bea2a74a428b9fdf7bf350e218c8cd71fdc5
|
diff --git a/flag/__init__.py b/flag/__init__.py
index <HASH>..<HASH> 100644
--- a/flag/__init__.py
+++ b/flag/__init__.py
@@ -13,4 +13,4 @@ __all__ = [
'int', 'string'
]
-__version__ = '0.1.1'
+__version__ = '0.3.1'
diff --git a/flag/core.py b/flag/core.py
index <HASH>..<HASH> 100644
--- a/flag/core.py
+++ b/flag/core.py
@@ -10,19 +10,19 @@ from . import registry
class Flag(object):
type = None
- def __init__(self, name, default, help):
+ def __init__(self, name, default=None, help=None, required=False):
self.parsed = False
self.name = name
self.default = default
self.help = help
self.value = None
- self.required = False
+ self.required = required
def val(self):
if not self.parsed:
raise Exception("Cannot read flag before parsing")
- if self.value:
+ if self.value is not None:
return self.value
else:
return self.default
@@ -39,6 +39,17 @@ class Flag(object):
type=self.type, required=self.required)
+class BaseMethods(object):
+ def __getattr__(self, attr):
+ val = self.type(self.val())
+ if hasattr(val, attr):
+ return getattr(val, attr)
+ raise AttributeError(attr)
+
+ def __hash__(self):
+ return self.val().__hash__()
+
+
class ComparisonOperators(object):
def __lt__(self, other):
return self.type(self) < other
@@ -73,42 +84,20 @@ class ArithmeticOperators(object):
return other * self.type(self)
-class IntFlag(Flag, ComparisonOperators, ArithmeticOperators):
+class IntFlag(Flag, ComparisonOperators, ArithmeticOperators, BaseMethods):
""" IntFlag is a flag that tries to behave like an int"""
type = int
def __str__(self):
return self.val().__str__()
- def __init__(self, *args, **kwargs):
- Flag.__init__(self, *args, **kwargs)
-
- def __getattr__(self, attr):
- """
- Forwards any non-magic methods to the resulting int's class.
- """
- val = self.type(self.val())
- if hasattr(val, attr):
- return getattr(val, attr)
- raise AttributeError(attr)
-
-class StringFlag(Flag, ComparisonOperators, ArithmeticOperators):
+class StringFlag(Flag, ComparisonOperators, ArithmeticOperators, BaseMethods):
""" StringFlag is a flag that tries to behave like a string"""
def __str__(self):
return self.val()
- def __getattr__(self, attr):
- """
- Forwards any non-magic methods to the resulting string's class. This
- allows support for string methods like `upper()`, `lower()`, etc.
- """
- string = self.type(self)
- if hasattr(string, attr):
- return getattr(string, attr)
- raise AttributeError(attr)
-
def __len__(self):
return len(self.type(self))
@@ -126,13 +115,13 @@ class StringFlag(Flag, ComparisonOperators, ArithmeticOperators):
return text_type
-def int(name, default, help):
- flag = IntFlag(name, default, help)
+def int(name, *args, **kwargs):
+ flag = IntFlag(name, *args, **kwargs)
registry.add(flag)
return flag
-def string(name, default, help):
- flag = StringFlag(name, default, help)
+def string(name, *args, **kwargs):
+ flag = StringFlag(name, *args, **kwargs)
registry.add(flag)
return flag
|
Added __hash__ magic method
|
danielchatfield_flag
|
train
|
1b20b24a1b549fb58c69ad1ddd66f423d5bb38cf
|
diff --git a/lib/identity_cache.rb b/lib/identity_cache.rb
index <HASH>..<HASH> 100644
--- a/lib/identity_cache.rb
+++ b/lib/identity_cache.rb
@@ -30,7 +30,7 @@ module IdentityCache
@logger || Rails.logger
end
- def should_cache?
+ def should_cache? # :nodoc:
!readonly && ActiveRecord::Base.connection.open_transactions == 0
end
@@ -50,7 +50,7 @@ module IdentityCache
result = yield
end
result = map_cached_nil_for(result)
-
+
if should_cache?
cache.write(key, result)
end
@@ -605,16 +605,26 @@ module IdentityCache
end
def populate_denormalized_cached_association(ivar_name, association_name) # :nodoc:
+ reflection = association(association_name)
+ current_schema_hash = IdentityCache.memcache_hash(self.class.colums_to_string(reflection.klass.columns))
+
ivar_full_name = :"@#{ivar_name}"
+ schema_hash_ivar = :"@#{ivar_name}_schema_hash"
- value = instance_variable_get(ivar_full_name)
- return value unless value.nil?
- reflection = association(association_name)
- reflection.load_target unless reflection.loaded?
+ saved_schema_hash = instance_variable_get(schema_hash_ivar)
+ schema_changed = saved_schema_hash && saved_schema_hash != current_schema_hash
+
+ if !schema_changed
+ value = instance_variable_get(ivar_full_name)
+ return value unless value.nil?
+ end
+
+ reflection.load_target unless reflection.loaded?
loaded_association = send(association_name)
instance_variable_set(ivar_full_name, IdentityCache.map_cached_nil_for(loaded_association))
+ instance_variable_set(schema_hash_ivar, current_schema_hash)
end
def primary_cache_index_key # :nodoc:
|
WIP: dealing with schema changes for embeded associations
|
Shopify_identity_cache
|
train
|
8d8d5cc9dbdde363b30872418c453060310101d8
|
diff --git a/text/text.go b/text/text.go
index <HASH>..<HASH> 100644
--- a/text/text.go
+++ b/text/text.go
@@ -61,10 +61,7 @@ func RangeTable(table *unicode.RangeTable) []rune {
// Text exports two important fields: Orig and Dot. Dot is the position where the next character
// will be written. Dot is automatically moved when writing to a Text object, but you can also
// manipulate it manually. Orig specifies the text origin, usually the top-left dot position. Dot is
-// always aligned to Orig when writing newlines.
-//
-// To reset the Dot to the Orig, just assign it:
-// txt.Dot = txt.Orig
+// always aligned to Orig when writing newlines. The Clear method resets the Dot to Orig.
type Text struct {
// Orig specifies the text origin, usually the top-left dot position. Dot is always aligned
// to Orig when writing newlines.
@@ -184,7 +181,7 @@ func (txt *Text) BoundsOf(s string) pixel.Rect {
return bounds
}
-// Clear removes all written text from the Text.
+// Clear removes all written text from the Text. The Dot field is reset to Orig.
func (txt *Text) Clear() {
txt.prevR = -1
txt.bounds = pixel.Rect{}
|
Document that Clear resets the Dot to Orig
Remove note on how to reset Dot to the Orig
|
faiface_pixel
|
train
|
58837285bd1ad0f77a5b733078663fc338ab07a8
|
diff --git a/provision/juju/stubs_test.go b/provision/juju/stubs_test.go
index <HASH>..<HASH> 100644
--- a/provision/juju/stubs_test.go
+++ b/provision/juju/stubs_test.go
@@ -1,4 +1,4 @@
-// Copyright 2012 tsuru authors. All rights reserved.
+// Copyright 2013 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
|
provision/juju: update copyright header in stubs_test.go
|
tsuru_tsuru
|
train
|
798c49ad856f87cde483432f842361b39484453c
|
diff --git a/cdi/src/main/java/javax/enterprise/inject/spi/Annotated.java b/cdi/src/main/java/javax/enterprise/inject/spi/Annotated.java
index <HASH>..<HASH> 100644
--- a/cdi/src/main/java/javax/enterprise/inject/spi/Annotated.java
+++ b/cdi/src/main/java/javax/enterprise/inject/spi/Annotated.java
@@ -51,7 +51,7 @@ public interface Annotated
public Set<Type> getTypeClosure();
/**
- * Get the annotation instance on the annoated element for a given annotation
+ * Get the annotation instance on the annotated element for a given annotation
* type.
*
* @param <T> the type of the annotation
diff --git a/cdi/src/main/java/javax/enterprise/inject/spi/InjectionTarget.java b/cdi/src/main/java/javax/enterprise/inject/spi/InjectionTarget.java
index <HASH>..<HASH> 100644
--- a/cdi/src/main/java/javax/enterprise/inject/spi/InjectionTarget.java
+++ b/cdi/src/main/java/javax/enterprise/inject/spi/InjectionTarget.java
@@ -47,22 +47,23 @@ public interface InjectionTarget<T> extends Producer<T>
/**
* <p>
- * Calls the {@link javax.annotation.PostConstruct} callback, if it exists,
+ * Calls the {@code PostConstruct} callback, if it exists,
* according to the semantics required by the Java EE platform specification.
* </p>
- *
- * @param instance
+ * @see javax.annotation.PostConstruct
+ * @param instance The instance on which to invoke the
+ * {@code PostConstruct} method
*/
public void postConstruct(T instance);
/**
* <p>
- * Calls the {@link javax.annotation.PreDestroy} callback, if it exists,
+ * Calls the {@code PreDestroy} callback, if it exists,
* according to the semantics required by the Java EE platform specification.
* </p>
- *
+ * @see javax.annotation.PreDestroy
* @param instance The instance on which to invoke the
- * {@link javax.annotation.PreDestroy} method
+ * {@code PreDestroy} method
*/
public void preDestroy(T instance);
diff --git a/cdi/src/main/java/javax/enterprise/inject/spi/Producer.java b/cdi/src/main/java/javax/enterprise/inject/spi/Producer.java
index <HASH>..<HASH> 100644
--- a/cdi/src/main/java/javax/enterprise/inject/spi/Producer.java
+++ b/cdi/src/main/java/javax/enterprise/inject/spi/Producer.java
@@ -65,6 +65,7 @@ public interface Producer<T>
* contextual instance of the bean that declares the disposer method or
* performs any additional required cleanup, if any, to destroy state
* associated with a resource.
+ * </p>
*
* @param instance The instance to dispose
*/
|
A few fixes to JavaDocs
|
weld_api
|
train
|
15be4c04f1e802d79e35089902cb9be07c66005f
|
diff --git a/pyneuroml/tune/NeuroMLController.py b/pyneuroml/tune/NeuroMLController.py
index <HASH>..<HASH> 100644
--- a/pyneuroml/tune/NeuroMLController.py
+++ b/pyneuroml/tune/NeuroMLController.py
@@ -99,8 +99,28 @@ class NeuroMLController():
chanDens = cd
chanDens.cond_density = '%s %s'%(value, units)
+
+ elif variable == 'erev_id': # change all values of erev in channelDensity elements with only this id
+
+ chanDens = None
+ for cd in cell.biophysical_properties.membrane_properties.channel_densities:
+ if cd.id == id2:
+ chanDens = cd
+
+ chanDens.erev = '%s %s'%(value, units)
+
+ elif variable == 'erev_ion': # change all values of erev in channelDensity elements with this ion
+
+ chanDens = None
+ for cd in cell.biophysical_properties.membrane_properties.channel_densities:
+ if cd.ion == id2:
+ chanDens = cd
+
+ chanDens.erev = '%s %s'%(value, units)
+
else:
print_comment_v('Unknown variable (%s) in variable expression: %s'%(variable, var_name))
+ exit()
else:
print_comment_v('Unknown type (%s) in variable expression: %s'%(type, var_name))
|
Option to tune reversal potentials
|
NeuroML_pyNeuroML
|
train
|
138cd87d7e911c82bd8fc83b9476fdbd2f62cdeb
|
diff --git a/README b/README
index <HASH>..<HASH> 100644
--- a/README
+++ b/README
@@ -0,0 +1,26 @@
+To use:
+
+ gem install saucelabs-adapter --source gems.pivotallabs.com
+
+ cd your_project
+
+ script/generate saucelabs_adapter
+
+Install the python script dependencies with:
+
+ easy_install ...
+
+Then
+
+ rake selenium2:local
+
+ or
+
+ rake selenium2:sauce
+
+
+TODO
+
+ Refactor Polonium::NewTestCase and Polonium::TrackerSeleniumTestCase into ActiveSupport::TestCase
+
+ Reconcile rake namespaces 'selenium' (from Pivotal Core Bundle) and 'selenium2'
diff --git a/lib/sauce_tunnel.rb b/lib/sauce_tunnel.rb
index <HASH>..<HASH> 100644
--- a/lib/sauce_tunnel.rb
+++ b/lib/sauce_tunnel.rb
@@ -11,7 +11,7 @@ class SauceTunnel
def start_tunnel
boot_tunnel_machine
- Timeout::timeout(2.minutes) do
+ Timeout::timeout(120) do
while !tunnel_is_up?
sleep 10
end
@@ -43,7 +43,7 @@ class SauceTunnel
raise "#{tunnel_script} is missing, have you installed saucerest-python?"
end
tunnel_command = "python #{tunnel_script} --shutdown #{@se_config[:username]} #{@se_config[:'access-key']} " +
- "localhost 4000:#{@se_config['application_port']} #{@se_config['application_address']} &"
+ "localhost #{@se_config.local_port}:#{@se_config['application_port']} #{@se_config['application_address']} &"
puts tunnel_command
system(tunnel_command)
end
@@ -59,7 +59,7 @@ class SauceTunnel
end
def shutdown_tunnel_machine
- Timeout::timeout(2.minutes) do
+ Timeout::timeout(120) do
@sauce_api_endpoint.delete :tunnel, @tunnel_id
while tunnel_info
sleep 10
@@ -68,4 +68,4 @@ class SauceTunnel
rescue Timeout::Error
raise "Sauce Tunnel failed to shut down! Go visit http://saucelabs.com/tunnels and shut down the tunnel for #{@se_config['application_address']}"
end
-end
\ No newline at end of file
+end
diff --git a/lib/selenium_config.rb b/lib/selenium_config.rb
index <HASH>..<HASH> 100644
--- a/lib/selenium_config.rb
+++ b/lib/selenium_config.rb
@@ -1,10 +1,13 @@
class SeleniumConfig
+ attr_reader :local_port
- def initialize(config_name = nil)
+ def initialize(config_name = nil, selenium_yml = nil, local_port = 4000)
if defined?(@@configuration_name) && @@configuration_name != config_name
@@configuration == nil
end
@@configuration_name = config_name
+ @selenium_yml = selenium_yml || File.join(RAILS_ROOT, 'config', 'selenium.yml')
+ @local_port = local_port
end
def configuration
@@ -47,8 +50,7 @@ class SeleniumConfig
private
def read_configuration(configuration_name)
- selenium_yml = File.join(Rails.root, 'config', 'selenium.yml')
- selenium_configs = YAML.load_file(selenium_yml)
+ selenium_configs = YAML.load_file(@selenium_yml)
configuration = selenium_configs[configuration_name]
raise "Configuration #{configuration_name} not found in #{selenium_yml}" unless configuration
@@ -56,8 +58,9 @@ class SeleniumConfig
# We are using Sauce Labs and therefore the Sauce Tunnel.
# We need to use a masquerade hostname on the EC2 end of the tunnel that will be unique within the scope of
# this account (e.g. pivotallabs). Therefore we mint a fairly unique hostname here.
- configuration['application_address'] = "#{Socket.gethostname}-#{Process.pid}.com"
+ hostname = Socket.gethostname.split(".").first
+ configuration['application_address'] = "#{hostname}-#{Process.pid}.com"
end
configuration
end
-end
\ No newline at end of file
+end
|
removes dependencies on Rails
adds options for user to set the location of the configuration yaml file
adds options for user to set the local application server port (defaults to <I>)
|
pivotal-legacy_saucelabs-adapter
|
train
|
6bf9fe08efda6456d4223b7291dc286d5a52c4ac
|
diff --git a/pyp2rpm/filters.py b/pyp2rpm/filters.py
index <HASH>..<HASH> 100644
--- a/pyp2rpm/filters.py
+++ b/pyp2rpm/filters.py
@@ -34,12 +34,11 @@ def python_bin_for_python_version(name, version, default_string='__python2'):
def macroed_pkg_name(pkg_name, srcname):
- if srcname:
- return 'python-%{srcname}'
- elif pkg_name.startswith('python-'):
- return 'python-%{pypi_name}'
+ macro = '%{srcname}' if srcname else '%{pypi_name}'
+ if pkg_name.startswith('python-'):
+ return 'python-{0}'.format(macro)
else:
- return '%{pypi_name}'
+ return macro
def module_to_path(name, module):
diff --git a/pyp2rpm/metadata_extractors.py b/pyp2rpm/metadata_extractors.py
index <HASH>..<HASH> 100644
--- a/pyp2rpm/metadata_extractors.py
+++ b/pyp2rpm/metadata_extractors.py
@@ -148,6 +148,17 @@ class LocalMetadataExtractor(object):
"""
return self.archive.has_file_with_suffix(settings.EXTENSION_SUFFIXES)
+ @property
+ def srcname(self):
+ """Return srcname for the macro if the pypi name should be changed.
+
+ Those cases are:
+ - name was provided with -r option
+ - pypi name is like python-<name>
+ """
+ if self.rpm_name or self.name.startswith('python'):
+ return self.name_convertor.base_name(self.rpm_name or self.name)
+
@pypi_metadata_extension
@venv_metadata_extension
def extract_data(self):
@@ -160,10 +171,7 @@ class LocalMetadataExtractor(object):
name=self.name,
pkg_name=self.rpm_name or self.name_convertor.rpm_name(self.name),
version=self.version,
- # Provide srcname if provided with -r or
- # if pypi name is like python-<name>.
- srcname=self.name_convertor.base_name(self.rpm_name or self.name)
- if self.rpm_name or self.name.startswith('python') else None)
+ srcname=self.srcname)
with self.archive:
data.set_from(self.data_from_archive)
@@ -176,7 +184,6 @@ class LocalMetadataExtractor(object):
if virtualenv is None and getattr(data, "packages") == set():
data.packages = set([data.name])
-
return data
@staticmethod
|
Rename option: handle the case when the provided name is without python-prefix
|
fedora-python_pyp2rpm
|
train
|
8a401da09b253029c9152fc349050f4b721cd34f
|
diff --git a/shardingsphere-scaling/shardingsphere-scaling-core/src/main/java/org/apache/shardingsphere/scaling/core/execute/executor/channel/MemoryChannel.java b/shardingsphere-scaling/shardingsphere-scaling-core/src/main/java/org/apache/shardingsphere/scaling/core/execute/executor/channel/MemoryChannel.java
index <HASH>..<HASH> 100755
--- a/shardingsphere-scaling/shardingsphere-scaling-core/src/main/java/org/apache/shardingsphere/scaling/core/execute/executor/channel/MemoryChannel.java
+++ b/shardingsphere-scaling/shardingsphere-scaling-core/src/main/java/org/apache/shardingsphere/scaling/core/execute/executor/channel/MemoryChannel.java
@@ -31,8 +31,6 @@ import java.util.concurrent.BlockingQueue;
*/
public final class MemoryChannel implements Channel {
- private static final int PUSH_TIMEOUT = ScalingContext.getInstance().getServerConfiguration().getPushTimeout();
-
private final BlockingQueue<Record> queue = new ArrayBlockingQueue<>(ScalingContext.getInstance().getServerConfiguration().getBlockQueueSize());
private final AckCallback ackCallback;
|
remove unused field. (#<I>)
Co-authored-by: qiulu3 <Lucas<I>>
|
apache_incubator-shardingsphere
|
train
|
da620ddaa875676f87e818fbd8c870da3243de8e
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -13,7 +13,7 @@ import os
MAJOR = 0
MINOR = 2
-MICRO = 5
+MICRO = 7
VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO)
|
Finally get setup.py working with pypi
|
capnproto_pycapnp
|
train
|
6200ed98499429f2d655ff6cffe63ca6152c1a89
|
diff --git a/PhpAmqpLib/Wire/IO/StreamIO.php b/PhpAmqpLib/Wire/IO/StreamIO.php
index <HASH>..<HASH> 100644
--- a/PhpAmqpLib/Wire/IO/StreamIO.php
+++ b/PhpAmqpLib/Wire/IO/StreamIO.php
@@ -405,6 +405,8 @@ class StreamIO extends AbstractIO
$write = null;
$except = null;
$result = false;
+ $sec = is_int($sec) ? $sec : 0;
+ $usec = is_int($usec) ? $usec : 0;
set_error_handler(array($this, 'error_handler'));
try {
|
Ensure integer values are actually integers for HHVM compatibility
|
php-amqplib_php-amqplib
|
train
|
b5ae5f426fc321b840d4115803937f9e07034174
|
diff --git a/src/u2flib_server/U2F.php b/src/u2flib_server/U2F.php
index <HASH>..<HASH> 100644
--- a/src/u2flib_server/U2F.php
+++ b/src/u2flib_server/U2F.php
@@ -80,7 +80,8 @@ class U2F {
$x509 = new File_X509();
$registration->certificate = base64_encode(substr($rawReg, 67 + $khLen, $certLen));
$cert = $x509->loadX509($registration->certificate);
- $rawKey = base64_decode($cert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey']);
+ $encodedKey = $cert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'];
+ $rawKey = base64_decode($encodedKey);
$signing_key = U2F::pubkey_decode(substr(bin2hex($rawKey), 2));
$signature = substr($rawReg, 67 + $khLen + $certLen);
$sig = U2F::sig_decode($signature);
|
php <I> doesn't support array dereferencing
|
Yubico_php-u2flib-server
|
train
|
d2c2f9385ea5679cb1197d3fc04050925f55314d
|
diff --git a/js/kraken.js b/js/kraken.js
index <HASH>..<HASH> 100644
--- a/js/kraken.js
+++ b/js/kraken.js
@@ -630,17 +630,14 @@ module.exports = class kraken extends Exchange {
return this.parseLedger (data, currency, since, limit);
}
- async fetchLedgerItem (id, code = undefined, params = {}) {
+ async fetchLedgerItemsByIds (ids, code = undefined, params = {}) {
// https://www.kraken.com/features/api#query-ledgers
- if (id === undefined) {
- throw new ArgumentsRequired (this.id + ' fetchLedgerItem requires a ledger item id argument');
- }
await this.loadMarkets ();
- if (Array.isArray (id)) {
- id = id.slice (0, 20).join (',');
+ if (Array.isArray (ids)) {
+ ids = ids.slice (0, 20).join (',');
}
let request = this.extend ({
- 'id': id,
+ 'id': ids,
}, params);
let response = await this.privatePostQueryLedgers (request);
// { error: [],
@@ -664,6 +661,11 @@ module.exports = class kraken extends Exchange {
return this.parseLedger (data);
}
+ async fetchLedgerItem (id, code = undefined, params = {}) {
+ let items = await this.fetchLedgerItemsByIds (id, code, params);
+ return items[0];
+ }
+
parseTrade (trade, market = undefined) {
let timestamp = undefined;
let side = undefined;
|
added kraken fetchLedgerItemsByIds
|
ccxt_ccxt
|
train
|
7211ec56b19efcaeacb73211a37b532c7b2a6309
|
diff --git a/closure/goog/debug/logger.js b/closure/goog/debug/logger.js
index <HASH>..<HASH> 100644
--- a/closure/goog/debug/logger.js
+++ b/closure/goog/debug/logger.js
@@ -97,6 +97,10 @@ goog.debug.Logger = function(name) {
};
+/** @const */
+goog.debug.Logger.ROOT_LOGGER_NAME = '';
+
+
/**
* @define {boolean} Toggles whether loggers other than the root logger can have
* log handlers attached to them and whether they can have their log level
@@ -793,8 +797,10 @@ goog.debug.LogManager.rootLogger_ = null;
*/
goog.debug.LogManager.initialize = function() {
if (!goog.debug.LogManager.rootLogger_) {
- goog.debug.LogManager.rootLogger_ = new goog.debug.Logger('');
- goog.debug.LogManager.loggers_[''] = goog.debug.LogManager.rootLogger_;
+ goog.debug.LogManager.rootLogger_ = new goog.debug.Logger(
+ goog.debug.Logger.ROOT_LOGGER_NAME);
+ goog.debug.LogManager.loggers_[goog.debug.Logger.ROOT_LOGGER_NAME] =
+ goog.debug.LogManager.rootLogger_;
goog.debug.LogManager.rootLogger_.setLevel(goog.debug.Logger.Level.CONFIG);
}
};
diff --git a/closure/goog/log/log.js b/closure/goog/log/log.js
index <HASH>..<HASH> 100644
--- a/closure/goog/log/log.js
+++ b/closure/goog/log/log.js
@@ -34,6 +34,10 @@ goog.require('goog.debug.Logger');
goog.define('goog.log.ENABLED', goog.debug.LOGGING_ENABLED);
+/** @const */
+goog.log.ROOT_LOGGER_NAME = goog.debug.Logger.ROOT_LOGGER_NAME;
+
+
/**
* @constructor
|
Add a constant for the root logger name.
-------------
Created by MOE: <URL>
|
google_closure-library
|
train
|
212297ef02c14112349e38e1d06aab3be4c6e1fd
|
diff --git a/tests/test_pkey.py b/tests/test_pkey.py
index <HASH>..<HASH> 100644
--- a/tests/test_pkey.py
+++ b/tests/test_pkey.py
@@ -470,7 +470,7 @@ class KeyTest(unittest.TestCase):
def test_ed25519_nonbytes_password(self):
# https://github.com/paramiko/paramiko/issues/1039
key = Ed25519Key.from_private_key_file(
- test_path('test_ed25519_password.key'),
+ _support('test_ed25519_password.key'),
# NOTE: not a bytes. Amusingly, the test above for same key DOES
# explicitly cast to bytes...code smell!
'abc123',
|
Uncaught typo in test suite
Was limited to the <I> branch, master either never got it or fixed it
without a backport.
|
paramiko_paramiko
|
train
|
9abf222ca9dd20f8babf7afd4db173766dd97384
|
diff --git a/src/client/pkg/grpcutil/dialer.go b/src/client/pkg/grpcutil/dialer.go
index <HASH>..<HASH> 100644
--- a/src/client/pkg/grpcutil/dialer.go
+++ b/src/client/pkg/grpcutil/dialer.go
@@ -44,7 +44,7 @@ func (d *dialer) Dial(addr string) (*grpc.ClientConn, error) {
grpc.WithUnaryInterceptor(tracing.UnaryClientInterceptor()),
grpc.WithStreamInterceptor(tracing.StreamClientInterceptor()),
)
- if strings.Index(addr, "dns:///") == -1 {
+ if !strings.HasPrefix(addr, "dns:///") {
addr = "dns:///" + addr
}
conn, err := grpc.Dial(addr, opts...)
|
Fix lint issues with string.Index
|
pachyderm_pachyderm
|
train
|
47becf803c2fa45466a391a60d2ae598ad562ee6
|
diff --git a/oz/core/actions.py b/oz/core/actions.py
index <HASH>..<HASH> 100644
--- a/oz/core/actions.py
+++ b/oz/core/actions.py
@@ -77,7 +77,7 @@ def server():
else:
ssl_options = None
- srv = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options)
+ srv = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options, xheaders=True)
srv.bind(oz.settings["port"])
if oz.settings["debug"]:
|
Add xheaders=True option to the HTTPServer instance
This instructs Tornado to pass on the value of the X-Real-Ip/X-Forwared-For headers to the remote_ip field.
This is useful when running behind a reverse proxy or load balancer (which most sites do these days).
|
dailymuse_oz
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.