hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
075864cd206ff1e04440da88dad55dd97a50aad9
|
diff --git a/lib/rules/jsx-closing-bracket-location.js b/lib/rules/jsx-closing-bracket-location.js
index <HASH>..<HASH> 100644
--- a/lib/rules/jsx-closing-bracket-location.js
+++ b/lib/rules/jsx-closing-bracket-location.js
@@ -202,17 +202,7 @@ module.exports = function(context) {
return fixer.replaceTextRange([cachedLastAttributeEndPos, node.end],
'\n' + tagSpaces.join(' ') + closingTag);
case 'line-aligned':
- var walkNode = node;
- var lineSpaces = 0;
- while ((walkNode = walkNode.parent)) {
- if (walkNode.type === 'VariableDeclaration' ||
- walkNode.type === 'ReturnStatement' ||
- walkNode.type === 'ExpressionStatement') {
- lineSpaces = walkNode.loc.start.column + 1;
- break;
- }
- }
- lineSpaces = new Array(lineSpaces);
+ var lineSpaces = new Array(+correctColumn + 1);
return fixer.replaceTextRange([cachedLastAttributeEndPos, node.end],
'\n' + lineSpaces.join(' ') + closingTag);
default:
|
Fix line-aligned jsx-closing-bracket-location fixer (#<I>)
Fix line-aligned jsx-closing-bracket-location fixer (fixes #<I>)
|
ytanruengsri_eslint-plugin-react-ssr
|
train
|
a6c4da4c0e6bd8a37f64544f7813fa027f5054ed
|
diff --git a/semantic_release/vcs_helpers.py b/semantic_release/vcs_helpers.py
index <HASH>..<HASH> 100644
--- a/semantic_release/vcs_helpers.py
+++ b/semantic_release/vcs_helpers.py
@@ -4,6 +4,7 @@ import os
import re
from pathlib import PurePath
from typing import Optional, Tuple
+from urllib.parse import urlsplit
import ndebug
from git import GitCommandError, InvalidGitRepositoryError, Repo, TagObject
@@ -90,7 +91,9 @@ def get_repository_owner_and_name() -> Tuple[str, str]:
check_repo()
url = repo.remote('origin').url
- parts = re.search(r'[:/]([^\.:]+)/([^/]*?)(.git)?$', url)
+ split_url = urlsplit(url)
+ path = split_url.netloc + split_url.path
+ parts = re.search(r'[:/]([^:]+)/([^/]*?)(.git)?$', path)
if not parts:
raise HvcsRepoParseError
debug('get_repository_owner_and_name', parts)
diff --git a/tests/test_vcs_helpers.py b/tests/test_vcs_helpers.py
index <HASH>..<HASH> 100644
--- a/tests/test_vcs_helpers.py
+++ b/tests/test_vcs_helpers.py
@@ -61,11 +61,19 @@ def test_push_new_version_with_custom_branch(mock_git):
("git@gitlab.example.com:group/project.git", ("group", "project")),
("git@gitlab.example.com:group/subgroup/project.git", ("group/subgroup", "project")),
("git@gitlab.example.com:group/subgroup/project", ("group/subgroup", "project")),
+ (
+ "git@gitlab.example.com:group/subgroup.with.dots/project",
+ ("group/subgroup.with.dots", "project")
+ ),
("https://github.com/group/project.git", ("group", "project")),
("https://gitlab.example.com/group/subgroup/project.git", ("group/subgroup", "project")),
("https://gitlab.example.com/group/subgroup/project", ("group/subgroup", "project")),
("https://gitlab.example.com/group/subgroup/pro.ject", ("group/subgroup", "pro.ject")),
("https://gitlab.example.com/group/subgroup/pro.ject.git", ("group/subgroup", "pro.ject")),
+ (
+ "https://gitlab.example.com/firstname.lastname/project.git",
+ ("firstname.lastname", "project")
+ ),
("bad_repo_url", HvcsRepoParseError),
])
def test_get_repository_owner_and_name(mocker, origin_url, expected_result):
|
fix: support repository owner names containing dots
Fixes #<I>
|
relekang_python-semantic-release
|
train
|
bd8de692ca37df2caf208a3fadd21abb6e5e9a6c
|
diff --git a/pumpp/task/base.py b/pumpp/task/base.py
index <HASH>..<HASH> 100644
--- a/pumpp/task/base.py
+++ b/pumpp/task/base.py
@@ -247,9 +247,9 @@ class BaseTaskTransformer(Scope):
# 1+ is fair here, because encode_intervals already pads
duration = 1 + encoded.shape[0]
else:
- duration = time_to_frames(duration,
- sr=self.sr,
- hop_length=self.hop_length)
+ duration = 1 + time_to_frames(duration,
+ sr=self.sr,
+ hop_length=self.hop_length)
# [0, duration] inclusive
times = frames_to_time(np.arange(duration+1),
|
fixed off-by-one in interval decoder
|
bmcfee_pumpp
|
train
|
b7cfb0247a712e6f580e0434571e1f80f631cc4d
|
diff --git a/core/client/src/main/java/alluxio/client/file/FileSystemMasterClient.java b/core/client/src/main/java/alluxio/client/file/FileSystemMasterClient.java
index <HASH>..<HASH> 100644
--- a/core/client/src/main/java/alluxio/client/file/FileSystemMasterClient.java
+++ b/core/client/src/main/java/alluxio/client/file/FileSystemMasterClient.java
@@ -82,8 +82,12 @@ public final class FileSystemMasterClient extends AbstractMasterClient {
return retryRPC(new RpcCallable<List<AlluxioURI>>() {
@Override
public List<AlluxioURI> call() throws AlluxioTException, TException {
- mClient.checkConsistency(path.getPath());
- return null;
+ List<String> inconsistentPaths = mClient.checkConsistency(path.getPath());
+ List<AlluxioURI> inconsistentUris = new ArrayList<>(inconsistentPaths.size());
+ for (String path : inconsistentPaths) {
+ inconsistentUris.add(new AlluxioURI(path));
+ }
+ return inconsistentUris;
}
});
}
diff --git a/core/common/src/thrift/file_system_master.thrift b/core/common/src/thrift/file_system_master.thrift
index <HASH>..<HASH> 100644
--- a/core/common/src/thrift/file_system_master.thrift
+++ b/core/common/src/thrift/file_system_master.thrift
@@ -114,7 +114,7 @@ service FileSystemMasterClientService extends common.AlluxioService {
* Checks the consistency of the files and directores with the path as the root of the subtree
*/
list<string> checkConsistency(/** the root of the subtree to check */ 1: string path)
- throws (1: exception.AlluxioTException e)
+ throws (1: exception.AlluxioTException e, 2: exception.ThriftIOException ioe)
/**
* Marks a file as completed.
diff --git a/core/server/src/main/java/alluxio/master/file/FileSystemMasterClientServiceHandler.java b/core/server/src/main/java/alluxio/master/file/FileSystemMasterClientServiceHandler.java
index <HASH>..<HASH> 100644
--- a/core/server/src/main/java/alluxio/master/file/FileSystemMasterClientServiceHandler.java
+++ b/core/server/src/main/java/alluxio/master/file/FileSystemMasterClientServiceHandler.java
@@ -71,15 +71,20 @@ public final class FileSystemMasterClientServiceHandler implements
}
@Override
- public List<String> checkConsistency(final String path) throws AlluxioTException {
+ public List<String> checkConsistency(final String path)
+ throws AlluxioTException, ThriftIOException {
return RpcUtils.call(new RpcCallableThrowsIOException<List<String>>() {
@Override
public List<String> call() throws AlluxioException, IOException {
List<AlluxioURI> inconsistentUris = mFileSystemMaster.checkConsistency(
new AlluxioURI(path), CheckConsistencyOptions.defaults());
- Lists.transform(inconsistentUris);
+ List<String> uris = new ArrayList<>(inconsistentUris.size());
+ for (AlluxioURI uri : inconsistentUris) {
+ uris.add(uri.getPath());
+ }
+ return uris;
}
- })
+ });
}
@Override
|
Update client/handler logic for check consistency.
|
Alluxio_alluxio
|
train
|
386e2c7357d8e15ab52f63c7d79101458561fbb1
|
diff --git a/activerecord/lib/arel/select_manager.rb b/activerecord/lib/arel/select_manager.rb
index <HASH>..<HASH> 100644
--- a/activerecord/lib/arel/select_manager.rb
+++ b/activerecord/lib/arel/select_manager.rb
@@ -237,18 +237,6 @@ module Arel # :nodoc: all
@ctx.source
end
- class Row < Struct.new(:data) # :nodoc:
- def id
- data["id"]
- end
-
- def method_missing(name, *args)
- name = name.to_s
- return data[name] if data.key?(name)
- super
- end
- end
-
private
def collapse(exprs)
exprs = exprs.compact
|
Remove unused `Row` class in `SelectManager`
The `Row` class is no longer used since d<I>b3c<I>d<I>ebcccd7c<I>e<I>ca0c<I>c.
|
rails_rails
|
train
|
4dfe3cf6c19e6ec99456b96745c85d4f26882d40
|
diff --git a/django_extensions/management/modelviz.py b/django_extensions/management/modelviz.py
index <HASH>..<HASH> 100644
--- a/django_extensions/management/modelviz.py
+++ b/django_extensions/management/modelviz.py
@@ -134,6 +134,8 @@ def generate_dot(app_labels, **kwargs):
def add_attributes(field):
if verbose_names and field.verbose_name:
label = field.verbose_name.decode("utf8")
+ if label.islower():
+ label = label.capitalize()
else:
label = field.name
|
Return the field's label with its first character capitalized and the rest lowercased if all characters in the label are lowercase, leave verbose_name attribute content otherwise. (as in the admin interface)
|
django-extensions_django-extensions
|
train
|
289bd2126a1aeec233e445f21c96888ec9b23b22
|
diff --git a/lib/ruby-lint/presenter/text.rb b/lib/ruby-lint/presenter/text.rb
index <HASH>..<HASH> 100644
--- a/lib/ruby-lint/presenter/text.rb
+++ b/lib/ruby-lint/presenter/text.rb
@@ -27,7 +27,13 @@ module RubyLint
entries = []
report.entries.sort.each do |entry|
- entries << @format % entry.attributes
+ entries << @format % {
+ :file => File.basename(entry.file),
+ :level => entry.level,
+ :line => entry.line,
+ :column => entry.column,
+ :message => entry.message
+ }
end
return entries.join("\n")
diff --git a/spec/ruby-lint/presenter/text.rb b/spec/ruby-lint/presenter/text.rb
index <HASH>..<HASH> 100644
--- a/spec/ruby-lint/presenter/text.rb
+++ b/spec/ruby-lint/presenter/text.rb
@@ -5,10 +5,10 @@ describe RubyLint::Presenter::Text do
report = RubyLint::Report.new
presenter = RubyLint::Presenter::Text.new
- report.error('error message', 1, 1, 'a.rb')
- report.error('error message 2', 2, 1, 'a.rb')
- report.warning('warning message', 1, 1, 'b.rb')
- report.info('info message', 1, 1, 'c.rb')
+ report.error('error message', 1, 1, '/foo/a.rb')
+ report.error('error message 2', 2, 1, '/foo/a.rb')
+ report.warning('warning message', 1, 1, '/foo/b.rb')
+ report.info('info message', 1, 1, '/foo/c.rb')
output = presenter.present(report)
|
Show the filenames only for the text presenter.
This reduces clutter and in turn makes it easier to read the report.
This commit fixes #<I>.
|
YorickPeterse_ruby-lint
|
train
|
a7ac00bcedcf90e112bfefdad3e394d429d756fb
|
diff --git a/includes/class-freemius.php b/includes/class-freemius.php
index <HASH>..<HASH> 100755
--- a/includes/class-freemius.php
+++ b/includes/class-freemius.php
@@ -2506,6 +2506,10 @@
true,
fs_request_get( 'blog_id', null )
);
+ } else if ( fs_request_is_action( 'delete_user' ) ) {
+ check_admin_referer( 'delete_user' );
+
+ self::delete_user( fs_request_get( 'user_id' ) );
} else if ( fs_request_is_action( 'download_logs' ) ) {
check_admin_referer( 'download_logs' );
diff --git a/templates/debug.php b/templates/debug.php
index <HASH>..<HASH> 100644
--- a/templates/debug.php
+++ b/templates/debug.php
@@ -434,6 +434,7 @@
<th><?php fs_esc_html_echo_inline( 'Verified' ) ?></th>
<th><?php fs_esc_html_echo_inline( 'Public Key' ) ?></th>
<th><?php fs_esc_html_echo_inline( 'Secret Key' ) ?></th>
+ <th><?php fs_esc_html_echo_inline( 'Actions' ) ?></th>
</tr>
</thead>
<tbody>
@@ -445,6 +446,13 @@
<td><?php echo json_encode( $user->is_verified ) ?></td>
<td><?php echo $user->public_key ?></td>
<td><?php echo $user->secret_key ?></td>
+ <td>
+ <form action="" method="POST">
+ <input type="hidden" name="fs_action" value="delete_user">
+ <?php wp_nonce_field( 'delete_user' ) ?>
+ <input type="hidden" name="user_id" value="<?php echo $user->id ?>">
+ <button type="submit" class="button"><?php fs_esc_html_echo_x_inline( 'Delete', 'verb', 'delete' ) ?></button>
+ </td>
</tr>
<?php endforeach ?>
</tbody>
@@ -516,7 +524,7 @@
<input name="logger" type="text" placeholder="<?php fs_esc_attr_echo_inline( 'Logger' ) ?>"/>
<input name="message" type="text" placeholder="<?php fs_esc_attr_echo_inline( 'Message' ) ?>"/>
<div style="margin: 10px 0">
- <button id="fs_filter" class="button" style="float: left"><i class="dashicons dashicons-filter"></i> <?php fs_esc_html_echo_inline( 'Filter', 'filter' ) ?>
+ <button id="fs_filter" class="button" style="float: left"><i class="dashicons dashicons-filter"></i> <?php fs_esc_html_echo_inline( 'Filter', 'filter' ) ?>
</button>
<form action="" method="POST" style="float: left; margin-left: 10px;">
@@ -524,7 +532,7 @@
<?php wp_nonce_field( 'download_logs' ) ?>
<div class="fs-filters"></div>
<button id="fs_download" class="button" type="submit"><i
- class="dashicons dashicons-download"></i> <?php fs_esc_html_echo_inline( 'Download' ) ?></button>
+ class="dashicons dashicons-download"></i> <?php fs_esc_html_echo_inline( 'Download' ) ?></button>
</form>
<div style="clear: both"></div>
</div>
|
[debug] [user-delete] Added an option to delete a user.
|
Freemius_wordpress-sdk
|
train
|
e553902d289094712c16de0872acda7ec0440e6a
|
diff --git a/python/herald/core.py b/python/herald/core.py
index <HASH>..<HASH> 100644
--- a/python/herald/core.py
+++ b/python/herald/core.py
@@ -152,7 +152,7 @@ class _WaitingPost(object):
:param herald_svc: Herald service instance
:param message: Received answer message
"""
- if self.__errback is not None:
+ if self.__callback is not None:
try:
# pylint: disable=W0703
self.__callback(herald_svc, message)
|
Corrected wrong validity check: callback instead of errback
|
cohorte_cohorte-herald
|
train
|
acd8e9c42e1d819c51e9e1cd3870ea4d94b167f5
|
diff --git a/testutil/testutil.go b/testutil/testutil.go
index <HASH>..<HASH> 100644
--- a/testutil/testutil.go
+++ b/testutil/testutil.go
@@ -5,6 +5,7 @@ import (
"github.com/tendermint/abci/server"
. "github.com/tendermint/go-common"
+ wire "github.com/tendermint/go-wire"
"github.com/tendermint/merkleeyes/app"
eyes "github.com/tendermint/merkleeyes/client"
)
@@ -30,3 +31,29 @@ func CreateEyes(t *testing.T) (svr Service, cli *eyes.Client) {
return svr, cli
}
+
+// MakeTxKV returns a text transaction, allong with expected key, value pair
+func MakeTxKV() ([]byte, []byte, []byte) {
+ k := []byte(RandStr(8))
+ v := []byte(RandStr(8))
+ return k, v, makeSet(k, v)
+}
+
+// blatently copied from merkleeyes/app/app_test.go
+// constructs a "set" transaction
+func makeSet(key, value []byte) []byte {
+ tx := make([]byte, 1+wire.ByteSliceSize(key)+wire.ByteSliceSize(value))
+ buf := tx
+ buf[0] = app.WriteSet // Set TypeByte
+ buf = buf[1:]
+ n, err := wire.PutByteSlice(buf, key)
+ if err != nil {
+ panic(err)
+ }
+ buf = buf[n:]
+ n, err = wire.PutByteSlice(buf, value)
+ if err != nil {
+ panic(err)
+ }
+ return tx
+}
|
Add testutil to create random transaction for people writing tests using merkleeyes
|
tendermint_iavl
|
train
|
b53ec50b0bc8d45a9eaa2457640b304c803c03ea
|
diff --git a/supplement/evaluator.py b/supplement/evaluator.py
index <HASH>..<HASH> 100644
--- a/supplement/evaluator.py
+++ b/supplement/evaluator.py
@@ -1,7 +1,7 @@
import ast
import logging
-from .objects import create_object
+from .objects import create_object, FakeInstanceObject
from .common import Value, UnknownObject, Object
from .names import RecursiveCallException
@@ -165,6 +165,9 @@ class Evaluator(ast.NodeVisitor):
def visit_BinOp(self, node):
self.visit(node.left)
+ def visit_Compare(self, node):
+ self.push(FakeInstanceObject(create_object(self.scope, bool)))
+
def process(self, tree, scope, skip_toplevel=True):
#from .tree import dump_tree; print '!!!', scope.filename; print dump_tree(tree); print
diff --git a/tests/test_evaluator.py b/tests/test_evaluator.py
index <HASH>..<HASH> 100644
--- a/tests/test_evaluator.py
+++ b/tests/test_evaluator.py
@@ -296,3 +296,6 @@ def test_function_call_with_starargs(project):
obj = infer("foo('name', [])", scope, 100)
assert 'append' in obj
+def test_compare_expression(scope):
+ obj = infer("5 in (1,2,3)", scope, 100)
+ assert 'bit_length' in obj
|
fix evaluation of comapre expressions
|
baverman_supplement
|
train
|
7976902d5bdb92c80400fc699bdbc106092bcd76
|
diff --git a/src/main/java/org/jdbdt/ColumnFiller.java b/src/main/java/org/jdbdt/ColumnFiller.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/jdbdt/ColumnFiller.java
+++ b/src/main/java/org/jdbdt/ColumnFiller.java
@@ -6,7 +6,7 @@ package org.jdbdt;
* <p>
* When convenient, custom column fillers can be set for data set builders
* using {@link DataSetBuilder#set(String, ColumnFiller)}.
- * The {@link DataSetBuilder} class already provides various
+ * Note that the {@link DataSetBuilder} class already provides various
* convenience methods that abstract the creation
* of commonly used column fillers.
* </p>
|
ColumnFiller: small Javadoc adjustment
|
JDBDT_jdbdt
|
train
|
2a4aada284fcd42ac03d035e1b97875775aee5e5
|
diff --git a/lib/xcode/install.rb b/lib/xcode/install.rb
index <HASH>..<HASH> 100644
--- a/lib/xcode/install.rb
+++ b/lib/xcode/install.rb
@@ -74,12 +74,26 @@ module XcodeInstall
def install_dmg(dmg_path, suffix = '', switch = true, clean = true)
archive_util = '/System/Library/CoreServices/Applications/Archive Utility.app/Contents/MacOS/Archive Utility'
prompt = "Please authenticate for Xcode installation.\nPassword: "
- xcode_beta_path = dmg_path.dirname + 'Xcode-beta.app'
xcode_path = "/Applications/Xcode#{suffix}.app"
if dmg_path.extname == '.xip'
`'#{archive_util}' #{dmg_path}`
- `sudo -p "#{prompt}" mv "#{xcode_beta_path}" "#{xcode_path}"`
+ xcode_orig_path = dmg_path.dirname + 'Xcode.app'
+ xcode_beta_path = dmg_path.dirname + 'Xcode-beta.app'
+ if Pathname.new(xcode_orig_path).exist?()
+ `sudo -p "#{prompt}" mv "#{xcode_orig_path}" "#{xcode_path}"`
+ elsif Pathname.new(xcode_beta_path).exist?()
+ `sudo -p "#{prompt}" mv "#{xcode_beta_path}" "#{xcode_path}"`
+ else
+ out = <<-HELP
+No `Xcode.app(or Xcode-beta.app)` found in DMG. Please remove #{dmg_path} if you
+suspect a corrupted download or run `xcversion update` to see if the version
+you tried to install has been pulled by Apple. If none of this is true,
+please open a new GH issue.
+HELP
+ $stderr.puts out.tr("\n", ' ')
+ return
+ end
else
mount_dir = mount(dmg_path)
source = Dir.glob(File.join(mount_dir, 'Xcode*.app')).first
|
Fix Xcode 8 GM install - xip file contains Xcode.app now
|
xcpretty_xcode-install
|
train
|
7be742d16e75e3f7d76fa957c2f2b282dec1d41e
|
diff --git a/GVRf/Framework/framework/src/main/java/org/gearvrf/GVRShader.java b/GVRf/Framework/framework/src/main/java/org/gearvrf/GVRShader.java
index <HASH>..<HASH> 100644
--- a/GVRf/Framework/framework/src/main/java/org/gearvrf/GVRShader.java
+++ b/GVRf/Framework/framework/src/main/java/org/gearvrf/GVRShader.java
@@ -464,7 +464,7 @@ public class GVRShader
}
- public native boolean isVulkanInstance();
+ public static native boolean isVulkanInstance();
public enum GLSLESVersion {
V100("100 es"),
|
Hotfix for gvrf-physics
|
Samsung_GearVRf
|
train
|
0f0b9dd272910dfc36fb463b4ccb6208dc2f9a53
|
diff --git a/sdk/go/common/apitype/stacks.go b/sdk/go/common/apitype/stacks.go
index <HASH>..<HASH> 100644
--- a/sdk/go/common/apitype/stacks.go
+++ b/sdk/go/common/apitype/stacks.go
@@ -33,6 +33,12 @@ type StackSummary struct {
// ListStacksResponse returns a set of stack summaries. This call is designed to be inexpensive.
type ListStacksResponse struct {
Stacks []StackSummary `json:"stacks"`
+
+ // ContinuationToken is an opaque value used to mark the end of the all stacks. If non-nil,
+ // pass it into a subsequent call in order to get the next batch of results.
+ //
+ // A value of nil means that all stacks have been returned.
+ ContinuationToken *string `json:"continuationToken,omitempty"`
}
// CreateStackRequest defines the request body for creating a new Stack
|
Add ContinuationToken to ListStacksResponse (#<I>)
|
pulumi_pulumi
|
train
|
bea850ba556f36df53e548714b394711ebef6d40
|
diff --git a/wisdom-openjpa-enhancer-plugin/src/main/java/org/wisdom/openjpa/enhancer/ProcessTestResourcesMojo.java b/wisdom-openjpa-enhancer-plugin/src/main/java/org/wisdom/openjpa/enhancer/ProcessTestResourcesMojo.java
index <HASH>..<HASH> 100644
--- a/wisdom-openjpa-enhancer-plugin/src/main/java/org/wisdom/openjpa/enhancer/ProcessTestResourcesMojo.java
+++ b/wisdom-openjpa-enhancer-plugin/src/main/java/org/wisdom/openjpa/enhancer/ProcessTestResourcesMojo.java
@@ -73,11 +73,12 @@ public class ProcessTestResourcesMojo extends AbstractWisdomMojo
FileUtils.copyFile(persistenceForTest, persistenceOLD);
if (ormMapping.isFile()){
- getLog().debug("Copy orm.xml test/resources/META-INF/ directory to classes/META-INF/ directory ");
+ getLog().info("Copy orm.xml test/resources/META-INF/ directory to classes/META-INF/ directory ");
FileUtils.copyFile(ormMapping, new File(buildDirectory, "classes/META-INF/orm.xml"));
}
} catch (IOException e) {
- e.printStackTrace();
+ getLog().warn("IOException when copying the original persistence.xml");
+ throw new MojoExecutionException("Cannot continue the copying of the persistence.xml", e);
}
}
diff --git a/wisdom-openjpa-enhancer-plugin/src/main/java/org/wisdom/openjpa/enhancer/RestoreOriginalResourcesMojo.java b/wisdom-openjpa-enhancer-plugin/src/main/java/org/wisdom/openjpa/enhancer/RestoreOriginalResourcesMojo.java
index <HASH>..<HASH> 100644
--- a/wisdom-openjpa-enhancer-plugin/src/main/java/org/wisdom/openjpa/enhancer/RestoreOriginalResourcesMojo.java
+++ b/wisdom-openjpa-enhancer-plugin/src/main/java/org/wisdom/openjpa/enhancer/RestoreOriginalResourcesMojo.java
@@ -72,7 +72,8 @@ public class RestoreOriginalResourcesMojo extends AbstractWisdomMojo {
FileUtils.deleteQuietly(ormMapping);
}
} catch (IOException e) {
- e.printStackTrace();
+ getLog().warn("IOException when restoring the original persistence.xml");
+ throw new MojoExecutionException("Cannot continue the restoring of the persistence.xml", e);
}
}
|
replace e.printStackTrace calls by a logger and an exception failing the build.
|
wisdom-framework_wisdom-jdbc
|
train
|
2952fbd556e1bc4b5fac70c727652b5419e8e096
|
diff --git a/pandas/tests/indexes/timedeltas/test_arithmetic.py b/pandas/tests/indexes/timedeltas/test_arithmetic.py
index <HASH>..<HASH> 100644
--- a/pandas/tests/indexes/timedeltas/test_arithmetic.py
+++ b/pandas/tests/indexes/timedeltas/test_arithmetic.py
@@ -442,39 +442,36 @@ class TestTimedeltaIndexArithmetic(object):
res = tdi // (scalar_td)
tm.assert_index_equal(res, expected)
- # TODO: Split by operation, better name
- def test_ops_compat(self):
+ def test_tdi_floordiv_tdlike_scalar(self, delta):
+ tdi = timedelta_range('1 days', '10 days', name='foo')
+ expected = Int64Index((np.arange(10) + 1) * 12, name='foo')
- offsets = [pd.offsets.Hour(2), timedelta(hours=2),
- np.timedelta64(2, 'h'), Timedelta(hours=2)]
+ result = tdi // delta
+ tm.assert_index_equal(result, expected, exact=False)
+ def test_tdi_mul_tdlike_scalar_raises(self, delta):
rng = timedelta_range('1 days', '10 days', name='foo')
+ with pytest.raises(TypeError):
+ rng * delta
- # multiply
- for offset in offsets:
- pytest.raises(TypeError, lambda: rng * offset)
+ def test_tdi_div_nat_raises(self):
+ # don't allow division by NaT (make could in the future)
+ rng = timedelta_range('1 days', '10 days', name='foo')
+ with pytest.raises(TypeError):
+ rng / pd.NaT
- # divide
+ def test_tdi_div_tdlike_scalar(self, delta):
+ rng = timedelta_range('1 days', '10 days', name='foo')
expected = Int64Index((np.arange(10) + 1) * 12, name='foo')
- for offset in offsets:
- result = rng / offset
- tm.assert_index_equal(result, expected, exact=False)
- # floor divide
- expected = Int64Index((np.arange(10) + 1) * 12, name='foo')
- for offset in offsets:
- result = rng // offset
- tm.assert_index_equal(result, expected, exact=False)
+ result = rng / delta
+ tm.assert_index_equal(result, expected, exact=False)
- # divide with nats
+ def test_tdi_div_tdlike_scalar_with_nat(self, delta):
rng = TimedeltaIndex(['1 days', pd.NaT, '2 days'], name='foo')
expected = Float64Index([12, np.nan, 24], name='foo')
- for offset in offsets:
- result = rng / offset
- tm.assert_index_equal(result, expected)
-
- # don't allow division by NaT (make could in the future)
- pytest.raises(TypeError, lambda: rng / pd.NaT)
+ result = rng / delta
+ tm.assert_index_equal(result, expected)
def test_subtraction_ops(self):
# with datetimes/timedelta and tdi/dti
|
split test_ops_compat into targeted tests (#<I>)
|
pandas-dev_pandas
|
train
|
dbd588fd3a35557a4cbb119e997516495328177f
|
diff --git a/lib/provider.js b/lib/provider.js
index <HASH>..<HASH> 100644
--- a/lib/provider.js
+++ b/lib/provider.js
@@ -14,7 +14,7 @@ function worker(id, plugin, striderjson, context, done) {
function defExtend(dest, src) {
for (var key in src) {
- if ('undefined' === typeof src[key]) continue;
+ if (!src[key]) continue;
dest[key] = src[key]
}
}
|
be more relaxed about what we consider unset keys
|
Strider-CD_strider-extension-loader
|
train
|
4354a66096913d2e9b12ee19d81b026100b0e4ea
|
diff --git a/gumble/handlers.go b/gumble/handlers.go
index <HASH>..<HASH> 100644
--- a/gumble/handlers.go
+++ b/gumble/handlers.go
@@ -452,19 +452,20 @@ func (c *Client) handleUserRemove(buffer []byte) error {
c.volatileLock.Unlock()
return errInvalidProtobuf
}
- event.User.client = nil
- if event.User.Channel != nil {
- delete(event.User.Channel.Users, session)
- }
- delete(c.Users, session)
-
if packet.Actor != nil {
event.Actor = c.Users[*packet.Actor]
if event.Actor == nil {
+ c.volatileLock.Unlock()
return errInvalidProtobuf
}
event.Type |= UserChangeKicked
}
+
+ event.User.client = nil
+ if event.User.Channel != nil {
+ delete(event.User.Channel.Users, session)
+ }
+ delete(c.Users, session)
if packet.Reason != nil {
event.String = *packet.Reason
}
|
handleUserRemove: Allow actor to be the same as the user being disconnected. handleUserRemove: Unlock the mutex if the actor cannot be found.
|
layeh_gumble
|
train
|
f1d62ace67a1543d57eb8a83aa8a715e62841af8
|
diff --git a/projects/samskivert/src/java/com/samskivert/jdbc/Repository.java b/projects/samskivert/src/java/com/samskivert/jdbc/Repository.java
index <HASH>..<HASH> 100644
--- a/projects/samskivert/src/java/com/samskivert/jdbc/Repository.java
+++ b/projects/samskivert/src/java/com/samskivert/jdbc/Repository.java
@@ -1,5 +1,5 @@
//
-// $Id: Repository.java,v 1.11 2001/09/21 03:01:46 mdb Exp $
+// $Id: Repository.java,v 1.12 2001/11/01 02:08:17 mdb Exp $
//
// samskivert library - useful routines for java programs
// Copyright (C) 2001 Michael Bayne
@@ -87,7 +87,7 @@ public class Repository
* as for it to automatically retry an operation if the connection
* failed for some transient reason.
*/
- protected interface Operation
+ public interface Operation
{
/**
* Invokes code that performs one or more database operations, all
|
Made Operation public because otherwise I can't do something like this:
public FooRepository
extends SimpleRepository implements SimpleRepository.Operation
{
}
which seems wacky to me but I can see how we may not have entered the
protected namespace of the extended class while we're processing our
interface implementation declarations. Seems a bit like a bug though.
git-svn-id: <URL>
|
samskivert_samskivert
|
train
|
d804d6e2e3d3ee0a354d0e4ee2ae1f31e5d22f93
|
diff --git a/lib/laser/analysis/annotations/scope_annotation.rb b/lib/laser/analysis/annotations/scope_annotation.rb
index <HASH>..<HASH> 100644
--- a/lib/laser/analysis/annotations/scope_annotation.rb
+++ b/lib/laser/analysis/annotations/scope_annotation.rb
@@ -41,6 +41,7 @@ module Laser
# Visits a class node and either creates or re-enters a corresponding scope, annotating the
# body with that scope.
+ # TODO(adgar): raise if this occurs within a method definition
add :class do |node, path_node, superclass_node, body|
# TODO(adgar): Make this do real lookup.
if superclass_node
@@ -118,6 +119,16 @@ module Laser
visit_with_scope(body, receiver.scope)
end
+ ######## Detecting includes - requires method call detection! ########
+ # TODO(adgar): Write a helper that matches method calls in the general case
+ add :command do |node, ident, args|
+ if ident[1] == 'include' && @current_scope.self_ptr.klass.ancestors.include?(ClassRegistry['Module'])
+ p "DID AN INCLUDE #{args.inspect}"
+ else
+ default_visit node
+ end
+ end
+
# Normal method definitions.
add :def do |node, (_, name), arglist, body|
receiver = @current_scope.self_ptr
|
Started on tracking calls to include. Need to do a lot of refactoring first though.
|
michaeledgar_laser
|
train
|
05b178085a2ad3bf3f2c0dcd1ea40fb5e8c8dc0d
|
diff --git a/activerecord/lib/active_record/associations/association.rb b/activerecord/lib/active_record/associations/association.rb
index <HASH>..<HASH> 100644
--- a/activerecord/lib/active_record/associations/association.rb
+++ b/activerecord/lib/active_record/associations/association.rb
@@ -42,6 +42,7 @@ module ActiveRecord
@loaded = false
@target = nil
@stale_state = nil
+ @inversed = false
end
# Reloads the \target and returns +self+ on success.
@@ -59,8 +60,9 @@ module ActiveRecord
# Asserts the \target has been loaded setting the \loaded flag to +true+.
def loaded!
- @loaded = true
+ @loaded = true
@stale_state = stale_state
+ @inversed = false
end
# The target is stale if the target no longer points to the record(s) that the
@@ -70,7 +72,7 @@ module ActiveRecord
#
# Note that if the target has not been loaded, it is not considered stale.
def stale_target?
- loaded? && @stale_state != stale_state
+ !@inversed && loaded? && @stale_state != stale_state
end
# Sets the target of this association to <tt>\target</tt>, and the \loaded flag to +true+.
@@ -104,6 +106,7 @@ module ActiveRecord
if record && invertible_for?(record)
inverse = record.association(inverse_reflection_for(record).name)
inverse.target = owner
+ inverse.instance_variable_set(:@inversed, true)
end
end
diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb
index <HASH>..<HASH> 100644
--- a/activerecord/test/cases/associations/inverse_associations_test.rb
+++ b/activerecord/test/cases/associations/inverse_associations_test.rb
@@ -603,6 +603,18 @@ class InversePolymorphicBelongsToTests < ActiveRecord::TestCase
assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same after changes to replaced-parent-owned instance"
end
+ def test_inversed_instance_should_not_be_reloaded_after_stale_state_changed
+ new_man = Man.new
+ face = Face.new
+ new_man.face = face
+
+ old_inversed_man = face.man
+ new_man.save!
+ new_inversed_man = face.man
+
+ assert_equal old_inversed_man.object_id, new_inversed_man.object_id
+ end
+
def test_should_not_try_to_set_inverse_instances_when_the_inverse_is_a_has_many
i = interests(:llama_wrangling)
m = i.polymorphic_man
|
inversed instance should not be reloaded after stale state was changed
check at association reader that record is inverted and should not be reloaded because of stale was changed at target record
|
rails_rails
|
train
|
18b9b6a719434f206c65771fb6cbabd7df3090f3
|
diff --git a/server/sonar-ce/src/main/java/org/sonar/ce/container/ComputeEngineContainerImpl.java b/server/sonar-ce/src/main/java/org/sonar/ce/container/ComputeEngineContainerImpl.java
index <HASH>..<HASH> 100644
--- a/server/sonar-ce/src/main/java/org/sonar/ce/container/ComputeEngineContainerImpl.java
+++ b/server/sonar-ce/src/main/java/org/sonar/ce/container/ComputeEngineContainerImpl.java
@@ -59,7 +59,6 @@ import org.sonar.ce.taskprocessor.CeProcessingScheduler;
import org.sonar.ce.taskprocessor.CeTaskProcessorModule;
import org.sonar.ce.user.CeUserSession;
import org.sonar.core.component.DefaultResourceTypes;
-import org.sonar.server.config.ConfigurationProvider;
import org.sonar.core.config.CorePropertyDefinitions;
import org.sonar.core.i18n.DefaultI18n;
import org.sonar.core.i18n.RuleI18nManager;
@@ -79,11 +78,15 @@ import org.sonar.process.NetworkUtilsImpl;
import org.sonar.process.Props;
import org.sonar.process.logging.LogbackHelper;
import org.sonar.server.component.ComponentFinder;
+import org.sonar.server.component.ComponentUpdater;
import org.sonar.server.component.index.ComponentIndexer;
import org.sonar.server.computation.task.projectanalysis.ProjectAnalysisTaskModule;
+import org.sonar.server.config.ConfigurationProvider;
import org.sonar.server.debt.DebtModelPluginRepository;
import org.sonar.server.debt.DebtRulesXMLImporter;
+import org.sonar.server.es.ProjectIndexersImpl;
import org.sonar.server.event.NewAlerts;
+import org.sonar.server.favorite.FavoriteUpdater;
import org.sonar.server.issue.IssueFieldsSetter;
import org.sonar.server.issue.index.IssueIndex;
import org.sonar.server.issue.index.IssueIndexer;
@@ -363,7 +366,10 @@ public class ComputeEngineContainerImpl implements ComputeEngineContainer {
UserPermissionChanger.class,
GroupPermissionChanger.class,
- // components
+ // components,
+ FavoriteUpdater.class,
+ ProjectIndexersImpl.class,
+ ComponentUpdater.class,
ComponentFinder.class, // used in ComponentService
NewAlerts.class,
NewAlerts.newMetadata(),
diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/container/ComputeEngineContainerImplTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/container/ComputeEngineContainerImplTest.java
index <HASH>..<HASH> 100644
--- a/server/sonar-ce/src/test/java/org/sonar/ce/container/ComputeEngineContainerImplTest.java
+++ b/server/sonar-ce/src/test/java/org/sonar/ce/container/ComputeEngineContainerImplTest.java
@@ -93,7 +93,7 @@ public class ComputeEngineContainerImplTest {
assertThat(picoContainer.getComponentAdapters())
.hasSize(
CONTAINER_ITSELF
- + 78 // level 4
+ + 81 // level 4
+ 21 // content of QualityGateModule
+ 6 // content of CeConfigurationModule
+ 4 // content of CeQueueModule
|
GOV-<I> add dependency in CE container required by Gov
for view refresh trigger at end of report processing
|
SonarSource_sonarqube
|
train
|
6f540f73411905d96538868b23eaf314f18b2273
|
diff --git a/datasift/output_mapper.py b/datasift/output_mapper.py
index <HASH>..<HASH> 100644
--- a/datasift/output_mapper.py
+++ b/datasift/output_mapper.py
@@ -1,36 +1,28 @@
from __future__ import print_function
from datetime import datetime
+from dateutil import parser
import six
+def float_handler(d):
+ return float(d)
-def date_handler_long(d, prefix, endpoint):
- if prefix == "historics" and isinstance(d, six.string_types) and not (" " in d): # historics sometimes returns string encoded unix timestamps
- d = int(d)
- if d is None:
- return None # special case for end=None coming out of push
- if isinstance(d, six.string_types):
- return datetime.strptime(d, "%a, %d %b %Y %H:%M:%S +0000") # rfc2822 email dates
- else:
- return datetime.fromtimestamp(d) # standard UNIX timestamp
-
-
-def date_handler_short(d, prefix, endpoint):
+def date(d):
+ if isinstance(d, list):
+ return map(parser.parse, d)
if isinstance(d, six.string_types):
- return datetime.strptime(d, "%Y-%m-%d %H:%M:%S") # short datetime with no timezone data
- elif isinstance(d, int):
- return datetime.fromtimestamp(d) # standard UNIX timestamp
-
-
-def float_handler(d, p, e):
- return float(d)
+ return parser.parse(d)
+ if isinstance(d, six.integer_types):
+ return datetime.fromtimestamp(d)
+ return d
output_map = {
- "created_at": date_handler_short,
+ "created_at": date,
"dpu": float_handler,
- "start": date_handler_long,
- "end": date_handler_long,
- "request_time": lambda d, p, e: datetime.fromtimestamp(d)
+ "start": date,
+ "end": date,
+ "request_time": date,
+ "last_success": date
}
@@ -53,6 +45,6 @@ def outputmapper(data, prefix, endpoint):
elif isinstance(data, dict):
for map_target in output_map:
if map_target in data:
- data[map_target] = output_map[map_target](data[map_target], prefix, endpoint)
+ data[map_target] = output_map[map_target](data[map_target])
for item in data.values():
- outputmapper(item, prefix, endpoint)
+ outputmapper(item, prefix, endpoint, recurse=recurse)
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -24,7 +24,8 @@ setup(
'autobahn <0.8.0, >=0.7.4',
'six <1.6.0, >=1.5.2',
'twisted <14.0.0, >=13.0.0',
- 'pyopenssl <0.14.0, >=0.13.1'
+ 'pyopenssl <0.14.0, >=0.13.1',
+ 'python-dateutil <2.3, >=2.1'
],
tests_require=[
'httmock >=1.1.1, < 2.0.0',
|
output mapper refactor to deal with dates better
|
datasift_datasift-python
|
train
|
dad769dab4eb3c301c013bb6df621501f865eaf7
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/record/ORecordAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/record/ORecordAbstract.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/record/ORecordAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/record/ORecordAbstract.java
@@ -176,7 +176,8 @@ public abstract class ORecordAbstract<T> implements ORecord<T>, ORecordInternal<
}
public <RET extends ORecord<T>> RET fromJSON(final String iSource, final String iOptions) {
- ORecordSerializerJSON.INSTANCE.fromString(iSource, this, null, iOptions);
+ //ORecordSerializerJSON.INSTANCE.fromString(iSource, this, null, iOptions);
+ ORecordSerializerJSON.INSTANCE.fromString(iSource, this, null, iOptions, false); //Add new parameter to accommodate new API, noting change
return (RET) this;
}
@@ -184,6 +185,11 @@ public abstract class ORecordAbstract<T> implements ORecord<T>, ORecordInternal<
ORecordSerializerJSON.INSTANCE.fromString(iSource, this, null);
return (RET) this;
}
+
+ //Add New API to load record if rid exist
+ public <RET extends ORecord<T>> RET fromJSON(final String iSource, boolean needReload) {
+ return (RET) ORecordSerializerJSON.INSTANCE.fromString(iSource, this, null, needReload);
+ }
public String toJSON() {
return toJSON("rid,version,class,type,attribSameRow,alwaysFetchEmbedded,fetchPlan:*:0");
|
Update core/src/main/java/com/orientechnologies/orient/core/record/ORecordAbstract.java
Load record if rid exist in request JSON
|
orientechnologies_orientdb
|
train
|
e23d60fb211845b0f0ddba5b7ebd4b33d277466b
|
diff --git a/mapsforge-map/src/main/java/org/mapsforge/map/layer/LayerManager.java b/mapsforge-map/src/main/java/org/mapsforge/map/layer/LayerManager.java
index <HASH>..<HASH> 100644
--- a/mapsforge-map/src/main/java/org/mapsforge/map/layer/LayerManager.java
+++ b/mapsforge-map/src/main/java/org/mapsforge/map/layer/LayerManager.java
@@ -15,9 +15,6 @@
*/
package org.mapsforge.map.layer;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
import org.mapsforge.core.graphics.Bitmap;
import org.mapsforge.core.graphics.Canvas;
import org.mapsforge.core.graphics.Color;
@@ -33,7 +30,6 @@ import org.mapsforge.map.view.FrameBuffer;
import org.mapsforge.map.view.MapView;
public class LayerManager extends PausableThread implements Redrawer {
- private static final Logger LOGGER = Logger.getLogger(LayerManager.class.getName());
private static final int MILLISECONDS_PER_FRAME = 30;
private final Canvas drawingCanvas;
@@ -110,9 +106,6 @@ public class LayerManager extends PausableThread implements Redrawer {
long timeSleep = MILLISECONDS_PER_FRAME - elapsedMilliseconds;
if (timeSleep > 1 && !isInterrupted()) {
- if (LOGGER.isLoggable(Level.FINE)) {
- LOGGER.log(Level.FINE, "sleeping (ms): " + timeSleep);
- }
sleep(timeSleep);
}
}
|
LayerManager: removed unneeded logging
|
mapsforge_mapsforge
|
train
|
b6d93ea8630859eb598c270a2427ef63cdef7185
|
diff --git a/src/Light.php b/src/Light.php
index <HASH>..<HASH> 100644
--- a/src/Light.php
+++ b/src/Light.php
@@ -40,7 +40,7 @@ class Light
$this->ct = @$data["state"]["ct"];
$this->alert = $data["state"]["alert"];
$this->effect = @$data["state"]["effect"];
- $this->colormode = $data["state"]["colormode"];
+ $this->colormode = @$data["state"]["colormode"];
}
}
|
colormode is not available for each light
|
muesli_huephp
|
train
|
c513e8da94746f22a0ff04e8ba0cf3f2fa1c4615
|
diff --git a/lib/dm-adjust/version.rb b/lib/dm-adjust/version.rb
index <HASH>..<HASH> 100644
--- a/lib/dm-adjust/version.rb
+++ b/lib/dm-adjust/version.rb
@@ -1,7 +1,7 @@
module DataMapper
module More
module Adjust
- VERSION = "0.9.3"
+ VERSION = "0.9.4"
end
end
end
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index <HASH>..<HASH> 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -8,7 +8,7 @@ def load_driver(name, default_uri)
lib = "do_#{name}"
begin
- gem lib, '=0.9.3'
+ gem lib, '=0.9.4'
require lib
DataMapper.setup(name, ENV["#{name.to_s.upcase}_SPEC_URI"] || default_uri)
DataMapper::Repository.adapters[:default] = DataMapper::Repository.adapters[name]
|
Updated Rakefile's CLEAN_GLOBS. Version Bump.
|
datamapper_dm-adjust
|
train
|
20f7d2b3ff7feef1059683ac8bd62396797348b5
|
diff --git a/src/BoomCMS/Http/Controllers/CMS/Auth/Account.php b/src/BoomCMS/Http/Controllers/CMS/Auth/Account.php
index <HASH>..<HASH> 100644
--- a/src/BoomCMS/Http/Controllers/CMS/Auth/Account.php
+++ b/src/BoomCMS/Http/Controllers/CMS/Auth/Account.php
@@ -19,7 +19,7 @@ class Account extends Controller
$this->provider = $provider;
}
- public function view()
+ public function getIndex()
{
return View::make('boom::account.account', [
'person' => $this->person,
@@ -28,7 +28,7 @@ class Account extends Controller
]);
}
- public function save()
+ public function postIndex()
{
$message = '';
diff --git a/src/routes.php b/src/routes.php
index <HASH>..<HASH> 100644
--- a/src/routes.php
+++ b/src/routes.php
@@ -26,9 +26,7 @@ Route::group(['middleware' => [
Route::group(['middleware' => ['BoomCMS\Http\Middleware\RequireLogin']], function () {
Route::controller('autocomplete', 'Autocomplete');
Route::controller('editor', 'Editor');
-
- Route::get('account', 'Auth\Account@view');
- Route::post('account', 'Auth\Account@save');
+ Route::controller('account', 'Auth\Account');
Route::group(['prefix' => 'assets', 'namespace' => 'Assets'], function () {
Route::get('', 'AssetManager@index');
|
Implicit controller for /cms/account
|
boomcms_boom-core
|
train
|
9c64fe79b09f04599bb2dc38a73ca7d62691d8c7
|
diff --git a/src/Console/ImportJsonDumpCommand.php b/src/Console/ImportJsonDumpCommand.php
index <HASH>..<HASH> 100644
--- a/src/Console/ImportJsonDumpCommand.php
+++ b/src/Console/ImportJsonDumpCommand.php
@@ -28,8 +28,11 @@ class ImportJsonDumpCommand extends Command {
$configurationBuilder = new EntityStoreFromConfigurationBuilder();
$store = $configurationBuilder->buildEntityStore( $input->getArgument( 'configuration' ) );
+ $output->writeln( 'Setup store.' );
$store->setupStore();
+ $output->writeln( 'Setup store done.' );
+ $output->writeln( 'Import data.' );
$entitySaver = $store->getEntityDocumentSaver();
$serialization = new EntitySerializationFactory();
@@ -47,7 +50,10 @@ class ImportJsonDumpCommand extends Command {
$output->write( '.' );
}
}
+ $output->writeln( 'Importation done.' );
- $output->writeln( 'Importation done' );
+ $output->writeln( 'Setup indexes.' );
+ $store->setupIndexes();
+ $output->writeln( 'Setup indexes done.' );
}
}
diff --git a/src/EntityStore.php b/src/EntityStore.php
index <HASH>..<HASH> 100644
--- a/src/EntityStore.php
+++ b/src/EntityStore.php
@@ -83,7 +83,7 @@ abstract class EntityStore {
}
/**
- * Setup the EntityStore if it has not been done yet (create database tables, query indexes...).
+ * Setup the EntityStore if it has not been done yet (create database tables...).
*
* It should not drop data if the store is already setup.
*/
@@ -91,6 +91,14 @@ abstract class EntityStore {
}
/**
+ * Setup the indexes if it has not been done yet.
+ *
+ * Often called after big importations to create again indexes.
+ */
+ public function setupIndexes() {
+ }
+
+ /**
* @return EntityStoreOptions
*/
protected function getOptions() {
diff --git a/src/MongoDB/MongoDBEntityStore.php b/src/MongoDB/MongoDBEntityStore.php
index <HASH>..<HASH> 100644
--- a/src/MongoDB/MongoDBEntityStore.php
+++ b/src/MongoDB/MongoDBEntityStore.php
@@ -114,9 +114,9 @@ class MongoDBEntityStore extends EntityStore {
}
/**
- * @see EntityStore::setupStore
+ * @see EntityStore::setupIndexes
*/
- public function setupStore() {
+ public function setupIndexes() {
$this->setupTermIndexes();
}
|
Setup indexes after big importations
|
ProjetPP_WikibaseEntityStore
|
train
|
9166468d7eaf413617d1040ffa0d716c5c1ddbc5
|
diff --git a/lib/rules/no-undef.js b/lib/rules/no-undef.js
index <HASH>..<HASH> 100644
--- a/lib/rules/no-undef.js
+++ b/lib/rules/no-undef.js
@@ -45,12 +45,50 @@ function hasTypeOfOperator(node) {
return parent.type === "UnaryExpression" && parent.operator === "typeof";
}
+/**
+ * Checks if a node name match the JSX tag convention.
+ * @param {String} name - Name of the node to check.
+ * @returns {boolean} Whether or not the node name match the JSX tag convention.
+ */
+var tagConvention = /^[a-z]|\-/;
+function isTagName(name) {
+ return tagConvention.test(name);
+}
+
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = function(context) {
+ var NOT_DEFINED_MESSAGE = "'{{name}}' is not defined.",
+ READ_ONLY_MESSAGE = "'{{name}}' is read only.";
+
+ /**
+ * Compare an identifier with the variables declared in the scope
+ * @param {ASTNode} node - Identifier or JSXIdentifier node
+ * @returns {void}
+ */
+ function checkIdentifierInJSX(node) {
+ var scope = context.getScope(),
+ variables = scope.variables,
+ i,
+ len;
+
+ while (scope.type !== "global") {
+ scope = scope.upper;
+ variables = scope.variables.concat(variables);
+ }
+
+ for (i = 0, len = variables.length; i < len; i++) {
+ if (variables[i].name === node.name) {
+ return;
+ }
+ }
+
+ context.report(node, NOT_DEFINED_MESSAGE, { name: node.name });
+ }
+
return {
"Program:exit": function(/*node*/) {
@@ -66,12 +104,25 @@ module.exports = function(context) {
}
if (!variable) {
- context.report(ref.identifier, "'{{name}}' is not defined.", { name: name });
+ context.report(ref.identifier, NOT_DEFINED_MESSAGE, { name: name });
} else if (ref.isWrite() && variable.writeable === false) {
- context.report(ref.identifier, "'{{name}}' is read only.", { name: name });
+ context.report(ref.identifier, READ_ONLY_MESSAGE, { name: name });
}
});
+ },
+
+ "JSXExpressionContainer": function(node) {
+ if (node.expression.type === "Identifier") {
+ checkIdentifierInJSX(node.expression);
+ }
+ },
+
+ "JSXOpeningElement": function(node) {
+ if (!isTagName(node.name.name)) {
+ checkIdentifierInJSX(node.name);
+ }
}
+
};
};
diff --git a/tests/lib/rules/no-undef.js b/tests/lib/rules/no-undef.js
index <HASH>..<HASH> 100644
--- a/tests/lib/rules/no-undef.js
+++ b/tests/lib/rules/no-undef.js
@@ -38,7 +38,11 @@ eslintTester.addRuleTest("lib/rules/no-undef", {
"typeof (a)",
"var b = typeof a",
"typeof a === 'undefined'",
- "if (typeof a === 'undefined') {}"
+ "if (typeof a === 'undefined') {}",
+ { code: "var React, App; React.render(<App />);", args: [1, {vars: "all"}], ecmaFeatures: { jsx: true } },
+ { code: "var React; React.render(<img />);", args: [1, {vars: "all"}], ecmaFeatures: { jsx: true } },
+ { code: "var React; React.render(<x-gif />);", args: [1, {vars: "all"}], ecmaFeatures: { jsx: true } },
+ { code: "var React, App, a=1; React.render(<App attr={a} />);", args: [1, {vars: "all"}], ecmaFeatures: { jsx: true } }
],
invalid: [
{ code: "a = 1;", errors: [{ message: "'a' is not defined.", type: "Identifier"}] },
@@ -51,6 +55,9 @@ eslintTester.addRuleTest("lib/rules/no-undef", {
{ code: "/*global b:false*/ var b = 1;", errors: [{ message: "'b' is read only.", type: "Identifier"}] },
{ code: "window;", errors: [{ message: "'window' is not defined.", type: "Identifier"}] },
{ code: "require(\"a\");", errors: [{ message: "'require' is not defined.", type: "Identifier"}] },
- { code: "Array = 1;", errors: [{ message: "'Array' is read only.", type: "Identifier"}] }
+ { code: "Array = 1;", errors: [{ message: "'Array' is read only.", type: "Identifier"}] },
+ { code: "var React; React.render(<App />);", args: [1, {vars: "all"}], errors: [{ message: "'App' is not defined." }], ecmaFeatures: { jsx: true } },
+ { code: "var React; React.render(<img attr={a} />);", args: [1, {vars: "all"}], errors: [{ message: "'a' is not defined." }], ecmaFeatures: { jsx: true } },
+ { code: "var React, App; React.render(<App attr={a} />);", args: [1, {vars: "all"}], errors: [{ message: "'a' is not defined." }], ecmaFeatures: { jsx: true } }
]
});
|
Fix: Missing undeclared variables in JSX (fixes #<I>)
|
eslint_eslint
|
train
|
2aca6aa25dd44e3ed7e1c3983fc7dd29be6f70f5
|
diff --git a/src/frontend/org/voltdb/ExecutionSite.java b/src/frontend/org/voltdb/ExecutionSite.java
index <HASH>..<HASH> 100644
--- a/src/frontend/org/voltdb/ExecutionSite.java
+++ b/src/frontend/org/voltdb/ExecutionSite.java
@@ -17,6 +17,7 @@
package org.voltdb;
+import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
@@ -666,7 +667,7 @@ implements Runnable, SiteTransactionConnection, SiteProcedureConnection
// initialize the DR gateway
int partitionId = m_context.siteTracker.getPartitionForSite(m_siteId);
- m_partitionDRGateway = PartitionDRGateway.getInstance(partitionId, false);
+ m_partitionDRGateway = PartitionDRGateway.getInstance(partitionId, false, new File("/tmp"));
}
ExecutionSite(VoltDBInterface voltdb, Mailbox mailbox,
@@ -697,7 +698,8 @@ implements Runnable, SiteTransactionConnection, SiteProcedureConnection
// initialize the DR gateway
int partitionId = m_context.siteTracker.getPartitionForSite(m_siteId);
- m_partitionDRGateway = PartitionDRGateway.getInstance(partitionId, m_recovering);
+ File overflowDir = new File(VoltDB.instance().getCatalogContext().cluster.getVoltroot(), "wan-overflow");
+ m_partitionDRGateway = PartitionDRGateway.getInstance(partitionId, m_recovering, overflowDir);
if (voltdb.getBackendTargetType() == BackendTarget.NONE) {
ee = new MockExecutionEngine();
diff --git a/src/frontend/org/voltdb/PartitionDRGateway.java b/src/frontend/org/voltdb/PartitionDRGateway.java
index <HASH>..<HASH> 100644
--- a/src/frontend/org/voltdb/PartitionDRGateway.java
+++ b/src/frontend/org/voltdb/PartitionDRGateway.java
@@ -17,6 +17,9 @@
package org.voltdb;
+import java.io.File;
+import java.io.IOException;
+
/**
* Stub class that provides a gateway to the InvocationBufferServer when
* WAN-based DR is enabled. If no DR, then it acts as a noop stub.
@@ -28,9 +31,10 @@ public class PartitionDRGateway {
* Load the full subclass if it should, otherwise load the
* noop stub.
* @param partitionId partition id
+ * @param overflowDir
* @return Instance of PartitionDRGateway
*/
- public static PartitionDRGateway getInstance(int partitionId, boolean rejoiningAtStartup) {
+ public static PartitionDRGateway getInstance(int partitionId, boolean rejoiningAtStartup, File overflowDir) {
PartitionDRGateway pdrg = null;
@@ -57,12 +61,16 @@ public class PartitionDRGateway {
}
// init the instance and return
- pdrg.init(partitionId, rejoiningAtStartup);
+ try {
+ pdrg.init(partitionId, rejoiningAtStartup, overflowDir);
+ } catch (IOException e) {
+ VoltDB.crashLocalVoltDB(e.getMessage(), false, e);
+ }
return pdrg;
}
// empty methods for community edition
- protected void init(int partitionId, boolean rejoiningAtStartup) {}
+ protected void init(int partitionId, boolean rejoiningAtStartup, File overflowDir) throws IOException {}
public void onSuccessfulProcedureCall(long txnId, StoredProcedureInvocation spi, ClientResponseImpl response) {}
public void tick(long txnId) {}
public void shutdown() {}
|
ENG-<I>: Overflow invocation buffers to disk when necessary.
This is paired with the commit in PRO.
|
VoltDB_voltdb
|
train
|
cd5c83a95d691a86c82b29a4d141338df9aab79f
|
diff --git a/pynspect/traversers.py b/pynspect/traversers.py
index <HASH>..<HASH> 100644
--- a/pynspect/traversers.py
+++ b/pynspect/traversers.py
@@ -469,7 +469,7 @@ class BaseFilteringTreeTraverser(BaseRuleTreeTraverser):
Evaluate given logical binary operation with given operands.
"""
if not operation in self.binops_logical:
- raise Exception("Invalid logical binary operation '{}'".format(operation))
+ raise ValueError("Invalid logical binary operation '{}'".format(operation))
result = self.binops_logical[operation](left, right)
return bool(result)
@@ -478,7 +478,7 @@ class BaseFilteringTreeTraverser(BaseRuleTreeTraverser):
Evaluate given comparison binary operation with given operands.
"""
if not operation in self.binops_comparison:
- raise Exception("Invalid comparison binary operation '{}'".format(operation))
+ raise ValueError("Invalid comparison binary operation '{}'".format(operation))
if left is None or right is None:
return None
if not isinstance(left, (list, ListIP)):
@@ -537,7 +537,7 @@ class BaseFilteringTreeTraverser(BaseRuleTreeTraverser):
Evaluate given mathematical binary operation with given operands.
"""
if not operation in self.binops_math:
- raise Exception("Invalid math binary operation '{}'".format(operation))
+ raise ValueError("Invalid math binary operation '{}'".format(operation))
if left is None or right is None:
return None
if not isinstance(left, (list, ListIP)):
@@ -559,7 +559,7 @@ class BaseFilteringTreeTraverser(BaseRuleTreeTraverser):
Evaluate given unary operation with given operand.
"""
if not operation in self.unops:
- raise Exception("Invalid unary operation '{}'".format(operation))
+ raise ValueError("Invalid unary operation '{}'".format(operation))
if right is None:
return None
return self.unops[operation](right)
|
Changed the BaseFilteringTreeTraverser to raise more specific ValueError instead of generic Exception in case of invalid operation name (both binary and unary).
|
honzamach_pynspect
|
train
|
6ea247692c86e6b16597bc43293dfbfc34899637
|
diff --git a/iserve-importer-owls/pom.xml b/iserve-importer-owls/pom.xml
index <HASH>..<HASH> 100644
--- a/iserve-importer-owls/pom.xml
+++ b/iserve-importer-owls/pom.xml
@@ -65,6 +65,22 @@
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>uk.ac.open.kmi.iserve.commons</groupId>
+ <artifactId>iserve-commons-io</artifactId>
+ <version>1.1.0-SNAPSHOT</version>
+ </dependency>
+ <dependency>
+ <groupId>uk.ac.open.kmi.iserve.commons</groupId>
+ <artifactId>iserve-commons-vocabulary</artifactId>
+ <version>1.1.0-SNAPSHOT</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.jena</groupId>
+ <artifactId>apache-jena-libs</artifactId>
+ <version>${jena.version}</version>
+ <type>pom</type>
+ </dependency>
<dependency>
<groupId>uk.ac.open.kmi.iserve.import</groupId>
<artifactId>iserve-importer-api</artifactId>
@@ -75,7 +91,6 @@
<artifactId>commons-cli</artifactId>
<version>1.2</version>
</dependency>
-
</dependencies>
<url>http://iserve.kmi.open.ac.uk/</url>
diff --git a/iserve-importer-owls/src/main/java/uk/ac/open/kmi/iserve/importer/owls/OwlsImporter.java b/iserve-importer-owls/src/main/java/uk/ac/open/kmi/iserve/importer/owls/OwlsImporter.java
index <HASH>..<HASH> 100644
--- a/iserve-importer-owls/src/main/java/uk/ac/open/kmi/iserve/importer/owls/OwlsImporter.java
+++ b/iserve-importer-owls/src/main/java/uk/ac/open/kmi/iserve/importer/owls/OwlsImporter.java
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package uk.ac.open.kmi.iserve.importer.owls;
import com.hp.hpl.jena.query.*;
@@ -382,8 +383,6 @@ public class OwlsImporter implements ServiceImporter {
log.debug("Querying model:");
log.debug(query.serialize());
- System.out.println(query.serialize());
-
try {
MessagePart mp = null;
QuerySolution solution;
diff --git a/iserve-importer-owls/src/test/java/uk/ac/open/kmi/iserve/importer/owls/OwlsImporterTest.java b/iserve-importer-owls/src/test/java/uk/ac/open/kmi/iserve/importer/owls/OwlsImporterTest.java
index <HASH>..<HASH> 100644
--- a/iserve-importer-owls/src/test/java/uk/ac/open/kmi/iserve/importer/owls/OwlsImporterTest.java
+++ b/iserve-importer-owls/src/test/java/uk/ac/open/kmi/iserve/importer/owls/OwlsImporterTest.java
@@ -28,6 +28,7 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.InputStream;
+import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@@ -41,14 +42,12 @@ import java.util.List;
*/
public class OwlsImporterTest {
- private static final boolean SAVE_FILES = false;
- private static final String TEST_RESOURCES_PATH = "/src/test/resources/";
- private static final String OWLS_TC3_SERVICES_1_1 = "OWLS-TC3/htdocs/services/1.1";
+ private static final String OWLS_TC3_SERVICES_1_1 = "/OWLS-TC3/htdocs/services/1.1/";
+ private static final String OWLS_TC3_SERVICES_1_0 = "/OWLS-TC3/htdocs/services/1.0/";
private OwlsImporter importer;
private ServiceWriter writer;
- private String workingDir;
- private List<String> testFolders;
+ private List<URI> testFolders;
private FilenameFilter owlsFilter;
@Before
@@ -56,9 +55,8 @@ public class OwlsImporterTest {
importer = new OwlsImporter();
writer = new ServiceWriterImpl();
- workingDir = System.getProperty("user.dir");
- testFolders = new ArrayList<String>();
- testFolders.add(workingDir + TEST_RESOURCES_PATH + OWLS_TC3_SERVICES_1_1);
+ testFolders = new ArrayList<URI>();
+ testFolders.add(OwlsImporterTest.class.getResource(OWLS_TC3_SERVICES_1_1).toURI());
owlsFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
@@ -72,7 +70,7 @@ public class OwlsImporterTest {
// Add all the test collections
System.out.println("Transforming test collections");
- for (String testFolder : testFolders) {
+ for (URI testFolder : testFolders) {
File dir = new File(testFolder);
System.out.println("Test collection: " + testFolder);
@@ -94,7 +92,7 @@ public class OwlsImporterTest {
// Add all the test collections
System.out.println("Transforming test collections");
- for (String testFolder : testFolders) {
+ for (URI testFolder : testFolders) {
File dir = new File(testFolder);
System.out.println("Test collection: " + testFolder);
|
Updated the means to obtain resources to be more independent from different configurations
|
kmi_iserve
|
train
|
95b2888a0518c00e472adc3070e2f115ad8bf22c
|
diff --git a/invenio_communities/config.py b/invenio_communities/config.py
index <HASH>..<HASH> 100644
--- a/invenio_communities/config.py
+++ b/invenio_communities/config.py
@@ -123,10 +123,30 @@ COMMUNITIES_REQUESTS_SEARCH = {
COMMUNITIES_MEMBERS_SEARCH = {
'facets': ['role', 'visibility'],
- 'sort': ['bestmatch', 'newest', 'oldest'],
+ 'sort': ['bestmatch', 'name', 'newest', 'oldest'],
}
"""Community requests search configuration (i.e list of community requests)"""
+COMMUNITIES_MEMBERS_SORT_OPTIONS = {
+ "bestmatch": dict(
+ title=_('Best match'),
+ fields=['_score'], # ES defaults to desc on `_score` field
+ ),
+ "name": dict(
+ title=_('Name'),
+ fields=['user.profile.full_name.keyword'],
+ ),
+ "newest": dict(
+ title=_('Newest'),
+ fields=['-created'],
+ ),
+ "oldest": dict(
+ title=_('Oldest'),
+ fields=['created'],
+ ),
+}
+"""Definitions of available record sort options."""
+
COMMUNITIES_MEMBERS_FACETS = {
'role': {
'facet': facets.role,
@@ -145,7 +165,7 @@ COMMUNITIES_MEMBERS_FACETS = {
COMMUNITIES_INVITATIONS_SEARCH = {
'facets': ['type', 'status'],
- 'sort': ['bestmatch', 'newest', 'oldest'],
+ 'sort': ['bestmatch', 'name', 'newest', 'oldest'],
}
"""Community invitations search configuration (i.e list of community invitations)"""
@@ -154,6 +174,10 @@ COMMUNITIES_INVITATIONS_SORT_OPTIONS = {
title=_('Best match'),
fields=['_score'], # ES defaults to desc on `_score` field
),
+ "name": dict(
+ title=_('Name'),
+ fields=['user.profile.full_name.keyword'],
+ ),
"newest": dict(
title=_('Newest'),
fields=['-created'],
@@ -162,7 +186,6 @@ COMMUNITIES_INVITATIONS_SORT_OPTIONS = {
title=_('Oldest'),
fields=['created'],
),
-
}
"""Definitions of available record sort options."""
diff --git a/invenio_communities/searchapp.py b/invenio_communities/searchapp.py
index <HASH>..<HASH> 100644
--- a/invenio_communities/searchapp.py
+++ b/invenio_communities/searchapp.py
@@ -38,7 +38,7 @@ def search_app_context():
search_app_config,
config_name='COMMUNITIES_MEMBERS_SEARCH',
available_facets=current_app.config['COMMUNITIES_MEMBERS_FACETS'],
- sort_options=current_app.config['RDM_SORT_OPTIONS'],
+ sort_options=current_app.config['COMMUNITIES_MEMBERS_SORT_OPTIONS'],
headers={"Accept": "application/json"},
default_size=25,
pagination_options=(25, 50, 75),
|
Searchapp: add invitations and members configuration
|
inveniosoftware_invenio-communities
|
train
|
d9d2dbb89e30a46aa36b602f6878bb34215905c7
|
diff --git a/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/model/OQueryModel.java b/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/model/OQueryModel.java
index <HASH>..<HASH> 100644
--- a/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/model/OQueryModel.java
+++ b/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/model/OQueryModel.java
@@ -133,14 +133,19 @@ public class OQueryModel<K> extends LoadableDetachableModel<List<K>>
protected String prepareSql(Integer first, Integer count)
{
- StringBuilder sb = new StringBuilder(sql);
+ StringBuilder sb = new StringBuilder(getSql());
if(first!=null) sb.append(" SKIP "+first);
if(count!=null && count>0) sb.append(" LIMIT "+count);
if(sortableParameter!=null) sb.append(" ORDER BY "+sortableParameter+(isAccessing?"":" desc"));
return sb.toString();
}
+
+ protected String getSql()
+ {
+ return sql;
+ }
- public String getCountSql()
+ protected String getCountSql()
{
return countSql;
}
diff --git a/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/model/SimpleNamingModel.java b/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/model/SimpleNamingModel.java
index <HASH>..<HASH> 100644
--- a/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/model/SimpleNamingModel.java
+++ b/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/model/SimpleNamingModel.java
@@ -2,29 +2,30 @@ package ru.ydn.wicket.wicketorientdb.model;
import org.apache.wicket.model.IModel;
-public class SimpleNamingModel extends AbstractNamingModel<String>
+public class SimpleNamingModel<T> extends AbstractNamingModel<T>
{
private String prefix;
- public SimpleNamingModel(IModel<String> objectModel)
+ public SimpleNamingModel(IModel<T> objectModel)
{
super(objectModel);
}
- public SimpleNamingModel(String object)
+ public SimpleNamingModel(T object)
{
super(object);
}
- public SimpleNamingModel(String prefix, IModel<String> objectModel)
+ public SimpleNamingModel(String prefix, IModel<T> objectModel)
{
super(objectModel);
this.prefix = prefix;
}
@Override
- public String getResourceKey(String object) {
- return prefix==null?object:prefix+"."+object;
+ public String getResourceKey(T object) {
+ String objectStr = object!=null?object.toString():"null";
+ return prefix==null?objectStr:prefix+"."+objectStr;
}
}
|
Making models more flexible: OQueryModel and SimpleNamingModel
|
OrienteerBAP_wicket-orientdb
|
train
|
1dc74cef1f6f214cbf043ecda00d107b3e81d0b3
|
diff --git a/src/bundle/Controller/ContentViewController.php b/src/bundle/Controller/ContentViewController.php
index <HASH>..<HASH> 100644
--- a/src/bundle/Controller/ContentViewController.php
+++ b/src/bundle/Controller/ContentViewController.php
@@ -18,6 +18,7 @@ use eZ\Publish\API\Repository\Values\Content\ContentInfo;
use eZ\Publish\API\Repository\Values\Content\VersionInfo;
use eZ\Publish\API\Repository\Values\Content\Language;
use eZ\Publish\API\Repository\UserService;
+use eZ\Publish\Core\MVC\Symfony\Locale\UserLanguagePreferenceProviderInterface;
use eZ\Publish\Core\MVC\Symfony\View\ContentView;
use EzSystems\EzPlatformAdminUi\Form\Data\Content\Draft\ContentCreateData;
use EzSystems\EzPlatformAdminUi\Form\Data\Content\Draft\ContentEditData;
@@ -87,6 +88,9 @@ class ContentViewController extends Controller
/** @var \eZ\Publish\API\Repository\LocationService */
private $locationService;
+ /** @var \eZ\Publish\Core\MVC\Symfony\Locale\UserLanguagePreferenceProviderInterface */
+ private $userLanguagePreferenceProvider;
+
/**
* @param \eZ\Publish\API\Repository\ContentTypeService $contentTypeService
* @param \eZ\Publish\API\Repository\LanguageService $languageService
@@ -97,6 +101,7 @@ class ContentViewController extends Controller
* @param \eZ\Publish\API\Repository\BookmarkService $bookmarkService
* @param \eZ\Publish\API\Repository\ContentService $contentService
* @param \eZ\Publish\API\Repository\LocationService $locationService
+ * @param \eZ\Publish\Core\MVC\Symfony\Locale\UserLanguagePreferenceProviderInterface $userLanguagePreferenceProvider
* @param int $defaultDraftPaginationLimit
* @param array $siteAccessLanguages
* @param int $defaultRolePaginationLimit
@@ -114,6 +119,7 @@ class ContentViewController extends Controller
BookmarkService $bookmarkService,
ContentService $contentService,
LocationService $locationService,
+ UserLanguagePreferenceProviderInterface $userLanguagePreferenceProvider,
int $defaultDraftPaginationLimit,
array $siteAccessLanguages,
int $defaultRolePaginationLimit,
@@ -136,6 +142,7 @@ class ContentViewController extends Controller
$this->defaultPolicyPaginationLimit = $defaultPolicyPaginationLimit;
$this->defaultSystemUrlPaginationLimit = $defaultSystemUrlPaginationLimit;
$this->defaultCustomUrlPaginationLimit = $defaultCustomUrlPaginationLimit;
+ $this->userLanguagePreferenceProvider = $userLanguagePreferenceProvider;
}
/**
@@ -210,7 +217,11 @@ class ContentViewController extends Controller
*/
private function supplyContentType(ContentView $view): void
{
- $view->addParameters(['contentType' => $view->getContent()->getContentType()]);
+ $contentType = $this->contentTypeService->loadContentType(
+ $view->getContent()->contentInfo->contentTypeId,
+ $this->userLanguagePreferenceProvider->getPreferredLanguages()
+ );
+ $view->addParameters(['contentType' => $contentType]);
}
/**
|
EZP-<I>: Injected user-preferred language into CT of Content View mode
|
ezsystems_ezplatform-admin-ui
|
train
|
718b1f0b9551306371ed2bc0ee35e29a5e2d6a5d
|
diff --git a/addon/components/vertical-collection/component.js b/addon/components/vertical-collection/component.js
index <HASH>..<HASH> 100644
--- a/addon/components/vertical-collection/component.js
+++ b/addon/components/vertical-collection/component.js
@@ -177,7 +177,7 @@ const VerticalCollection = Component.extend({
_radar.prepend(items, lenDiff);
} else if (isAppend(lenDiff, items, key, _prevFirstKey, _prevLastKey)) {
_radar.append(items, lenDiff);
- } else {
+ } else if (!isSameArray(lenDiff, items, key, _prevFirstKey, _prevLastKey)) {
_radar.resetItems(items);
}
@@ -345,4 +345,15 @@ function isAppend(lenDiff, newItems, key, oldFirstKey, oldLastKey) {
return oldFirstKey === newFirstKey && oldLastKey === newLastKey;
}
+function isSameArray(lenDiff, newItems, key, oldFirstKey, oldLastKey) {
+ if (lenDiff !== 0) {
+ return false;
+ }
+
+ const newFirstKey = keyForItem(newItems[0], key, 0);
+ const newLastKey = keyForItem(newItems[newItems.length - 1], key, newItems.length - 1);
+
+ return oldFirstKey === newFirstKey && oldLastKey === newLastKey;
+}
+
export default VerticalCollection;
diff --git a/tests/integration/mutation-test.js b/tests/integration/mutation-test.js
index <HASH>..<HASH> 100644
--- a/tests/integration/mutation-test.js
+++ b/tests/integration/mutation-test.js
@@ -234,3 +234,42 @@ test('Collection appends correctly if prepend would cause more VCs to be shown',
assert.equal(itemContainer.outerHeight(), 800, 'itemContainer height is correct after append');
});
});
+
+test('Collection maintains state if the same list is passed in twice', function(assert) {
+ assert.expect(4);
+ const items = getNumbers(0, 100);
+ this.set('items', items);
+
+ this.render(hbs`
+ <div style="height: 200px; width: 100px;" class="scrollable">
+ {{#vertical-collection ${'items'}
+ minHeight=20
+ alwaysRemeasure=true
+
+ as |item i|}}
+ <div style="height:40px;">
+ {{item.number}} {{i}}
+ </div>
+ {{/vertical-collection}}
+ </div>
+ `);
+
+ const scrollContainer = this.$('.scrollable');
+ const itemContainer = this.$('vertical-collection');
+
+ return wait().then(() => {
+ scrollContainer.scrollTop(541);
+
+ return wait();
+ }).then(() => {
+ assert.equal(scrollContainer.find('div:first').text().trim(), '1 1', 'first item rendered correctly after same items set');
+ assert.equal(itemContainer.css('padding-top'), '40px', 'itemContainer height is correct before append');
+
+ this.set('items', items.slice());
+
+ return wait();
+ }).then(() => {
+ assert.equal(scrollContainer.find('div:first').text().trim(), '1 1', 'first item rendered correctly after same items set');
+ assert.equal(itemContainer.css('padding-top'), '40px', 'itemContainer padding correct after same items set');
+ });
+});
|
bugfix(radar): Adds same array checker for radar computed (#<I>)
|
html-next_vertical-collection
|
train
|
c4c215a3f78b1f26696d058dc861b9908ccb7e35
|
diff --git a/src/Component/Encryption/Algorithm/KeyEncryptionAlgorithm.php b/src/Component/Encryption/Algorithm/KeyEncryptionAlgorithm.php
index <HASH>..<HASH> 100644
--- a/src/Component/Encryption/Algorithm/KeyEncryptionAlgorithm.php
+++ b/src/Component/Encryption/Algorithm/KeyEncryptionAlgorithm.php
@@ -21,8 +21,11 @@ use Jose\Component\Core\Algorithm;
interface KeyEncryptionAlgorithm extends Algorithm
{
public const MODE_DIRECT = 'dir';
+
public const MODE_ENCRYPT = 'enc';
+
public const MODE_WRAP = 'wrap';
+
public const MODE_AGREEMENT = 'agree';
/**
diff --git a/src/Component/KeyManagement/KeyAnalyzer/Message.php b/src/Component/KeyManagement/KeyAnalyzer/Message.php
index <HASH>..<HASH> 100644
--- a/src/Component/KeyManagement/KeyAnalyzer/Message.php
+++ b/src/Component/KeyManagement/KeyAnalyzer/Message.php
@@ -29,7 +29,9 @@ final class Message implements \JsonSerializable
private $severity;
public const SEVERITY_LOW = 'low';
+
public const SEVERITY_MEDIUM = 'medium';
+
public const SEVERITY_HIGH = 'high';
/**
|
Apply fixes from StyleCI (#<I>)
[ci skip] [skip ci]
|
web-token_jwt-framework
|
train
|
626b7a91d17434cf6ef07ddddd5bfcc49d70f912
|
diff --git a/src/type/__tests__/introspection-test.js b/src/type/__tests__/introspection-test.js
index <HASH>..<HASH> 100644
--- a/src/type/__tests__/introspection-test.js
+++ b/src/type/__tests__/introspection-test.js
@@ -698,51 +698,6 @@ describe('Introspection', () => {
isDeprecated: false,
deprecationReason: null,
},
- {
- name: 'onOperation',
- args: [],
- type: {
- kind: 'NON_NULL',
- name: null,
- ofType: {
- kind: 'SCALAR',
- name: 'Boolean',
- ofType: null,
- },
- },
- isDeprecated: true,
- deprecationReason: 'Use `locations`.',
- },
- {
- name: 'onFragment',
- args: [],
- type: {
- kind: 'NON_NULL',
- name: null,
- ofType: {
- kind: 'SCALAR',
- name: 'Boolean',
- ofType: null,
- },
- },
- isDeprecated: true,
- deprecationReason: 'Use `locations`.',
- },
- {
- name: 'onField',
- args: [],
- type: {
- kind: 'NON_NULL',
- name: null,
- ofType: {
- kind: 'SCALAR',
- name: 'Boolean',
- ofType: null,
- },
- },
- isDeprecated: true,
- deprecationReason: 'Use `locations`.',
- },
],
inputFields: null,
interfaces: [],
diff --git a/src/type/introspection.js b/src/type/introspection.js
index <HASH>..<HASH> 100644
--- a/src/type/introspection.js
+++ b/src/type/introspection.js
@@ -100,29 +100,6 @@ export const __Directive = new GraphQLObjectType({
type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__InputValue))),
resolve: directive => directive.args || [],
},
- // NOTE: the following three fields are deprecated and are no longer part
- // of the GraphQL specification.
- onOperation: {
- deprecationReason: 'Use `locations`.',
- type: GraphQLNonNull(GraphQLBoolean),
- resolve: d =>
- d.locations.indexOf(DirectiveLocation.QUERY) !== -1 ||
- d.locations.indexOf(DirectiveLocation.MUTATION) !== -1 ||
- d.locations.indexOf(DirectiveLocation.SUBSCRIPTION) !== -1,
- },
- onFragment: {
- deprecationReason: 'Use `locations`.',
- type: GraphQLNonNull(GraphQLBoolean),
- resolve: d =>
- d.locations.indexOf(DirectiveLocation.FRAGMENT_SPREAD) !== -1 ||
- d.locations.indexOf(DirectiveLocation.INLINE_FRAGMENT) !== -1 ||
- d.locations.indexOf(DirectiveLocation.FRAGMENT_DEFINITION) !== -1,
- },
- onField: {
- deprecationReason: 'Use `locations`.',
- type: GraphQLNonNull(GraphQLBoolean),
- resolve: d => d.locations.indexOf(DirectiveLocation.FIELD) !== -1,
- },
}),
});
diff --git a/src/utilities/__tests__/schemaPrinter-test.js b/src/utilities/__tests__/schemaPrinter-test.js
index <HASH>..<HASH> 100644
--- a/src/utilities/__tests__/schemaPrinter-test.js
+++ b/src/utilities/__tests__/schemaPrinter-test.js
@@ -648,9 +648,6 @@ describe('Type System Printer', () => {
description: String
locations: [__DirectiveLocation!]!
args: [__InputValue!]!
- onOperation: Boolean! @deprecated(reason: "Use \`locations\`.")
- onFragment: Boolean! @deprecated(reason: "Use \`locations\`.")
- onField: Boolean! @deprecated(reason: "Use \`locations\`.")
}
"""
@@ -881,9 +878,6 @@ describe('Type System Printer', () => {
description: String
locations: [__DirectiveLocation!]!
args: [__InputValue!]!
- onOperation: Boolean! @deprecated(reason: "Use \`locations\`.")
- onFragment: Boolean! @deprecated(reason: "Use \`locations\`.")
- onField: Boolean! @deprecated(reason: "Use \`locations\`.")
}
# A Directive can be adjacent to many parts of the GraphQL language, a
|
BREAKING: Remove deprecated introspection fields (#<I>)
These fields are holdovers from the first version of the spec, before directives had more control over their exact location and could be located in more places.
This is potentially breaking to any clients which relied on these fields, which will need to migrate to use the spec-compliant `locations` field before upgrading to a version including this patch
|
graphql_graphql-js
|
train
|
a390cbc4af63421732b13985125744ab3e3d68c1
|
diff --git a/d1_common_python/src/d1_common/const.py b/d1_common_python/src/d1_common/const.py
index <HASH>..<HASH> 100644
--- a/d1_common_python/src/d1_common/const.py
+++ b/d1_common_python/src/d1_common/const.py
@@ -32,7 +32,7 @@ import d1_common
# The root of all DataONE. Used to perform introspection on the system when
# no other node information is provided.
-URL_DATAONE_ROOT = 'http://cn.dataone.org/cn/'
+URL_DATAONE_ROOT = 'https://cn-dev.dataone.org/cn/'
# Version of this software.
VERSION = d1_common.__version__
|
- Updated the default d1 root to use https.
|
DataONEorg_d1_python
|
train
|
07b15faacc6e43765588d317087abe0961d020fd
|
diff --git a/paper/figures/astero_plot.py b/paper/figures/astero_plot.py
index <HASH>..<HASH> 100644
--- a/paper/figures/astero_plot.py
+++ b/paper/figures/astero_plot.py
@@ -7,6 +7,7 @@ import pickle
import corner
import numpy as np
import matplotlib.pyplot as plt
+from scipy.ndimage.filters import gaussian_filter
import emcee3
@@ -146,15 +147,14 @@ plt.close(fig)
fig, axes = plt.subplots(3, 1, sharex=True, sharey=True,
figsize=get_figsize(2.5, 2))
-factor = 1.
axes[0].plot(freq_uHz, power_all, "k", rasterized=True)
-# axes[0].plot(freq_uHz, gaussian_filter(power_all, 5) * factor, "k",
-# rasterized=True)
+axes[0].plot(freq_uHz, gaussian_filter(power_all, 5),
+ color=COLORS["MODEL_1"], rasterized=True)
axes[0].axhline(white_noise_all)
axes[1].plot(freq_uHz, power_some, "k", rasterized=True)
-# axes[1].plot(freq_uHz, gaussian_filter(power_some, 20) * factor, "k",
-# rasterized=True)
+axes[1].plot(freq_uHz, gaussian_filter(power_some, 20),
+ color=COLORS["MODEL_1"], rasterized=True)
axes[1].axhline(white_noise_some)
q = np.percentile(uHz_conv/(2*np.pi)*psds, [16, 50, 84], axis=0)
diff --git a/paper/figures/astero_sample.py b/paper/figures/astero_sample.py
index <HASH>..<HASH> 100644
--- a/paper/figures/astero_sample.py
+++ b/paper/figures/astero_sample.py
@@ -274,10 +274,14 @@ if os.path.exists("astero-{0}.h5".format(kicid)):
sys.exit(0)
# Define a custom proposal
+names = gp.get_parameter_names()
+ind_nu_max = names.index("kernel:log_nu_max")
+ind_delta_nu = names.index("kernel:log_delta_nu")
def astero_move(rng, x0):
x = np.array(x0)
f = 2.0 * (rng.rand(len(x)) < 0.5) - 1.0
- x[:, 3] = np.log(np.exp(x[:, 3]) + f * np.exp(x[:, 4]))
+ x[:, ind_nu_max] = np.log(np.exp(x[:, ind_nu_max]) +
+ f * np.exp(x[:, ind_delta_nu]))
return x, np.zeros(len(x))
# The sampler will use a mixture of proposals
|
old missing changes in astero example [ci skip]
|
dfm_celerite
|
train
|
93eb24cc39f6f8b17b61b07d51ad019613f9018e
|
diff --git a/util.js b/util.js
index <HASH>..<HASH> 100644
--- a/util.js
+++ b/util.js
@@ -6,7 +6,7 @@ var str = require('./dist/stringify')
exports.stringifyNumber = str.stringifyNumber
exports.stringifyString = str.stringifyString
exports.toJSON = require('./dist/toJSON').default
-exports.Type = require('./dist/cst/Node').Type
+exports.Type = require('./dist/constants').Type
var err = require('./dist/errors')
exports.YAMLReferenceError = err.YAMLReferenceError
|
Fix export of Type from "yaml/util"
|
eemeli_yaml
|
train
|
9e4e67a412c343ceba4b17c908e392d0b61873b9
|
diff --git a/src/rinoh/structure.py b/src/rinoh/structure.py
index <HASH>..<HASH> 100644
--- a/src/rinoh/structure.py
+++ b/src/rinoh/structure.py
@@ -145,7 +145,8 @@ class Heading(NumberedParagraph):
parent_id = self.section.parent.section.get_id(document)
parent_ref = document.get_reference(parent_id, 'number')
if parent_ref:
- label = parent_ref + separator + label
+ separator_string = separator.to_string(flowable_target)
+ label = parent_ref + separator_string + label
else:
label = None
title_string = self.content.to_string(flowable_target)
|
Fix crash if number_separator is a StyledText
Note: specific styling applied to the number separator is lost.
|
brechtm_rinohtype
|
train
|
8a6d5d150fa5ab1ffa9bf327a89dc5057c4577a5
|
diff --git a/ph-oton-basic/src/test/java/com/helger/photon/basic/config/MicroTypeConverterRegistrar_ph_oton_basic_Mock.java b/ph-oton-basic/src/test/java/com/helger/photon/basic/config/MicroTypeConverterRegistrar_ph_oton_basic_Mock.java
index <HASH>..<HASH> 100644
--- a/ph-oton-basic/src/test/java/com/helger/photon/basic/config/MicroTypeConverterRegistrar_ph_oton_basic_Mock.java
+++ b/ph-oton-basic/src/test/java/com/helger/photon/basic/config/MicroTypeConverterRegistrar_ph_oton_basic_Mock.java
@@ -38,14 +38,21 @@ public final class MicroTypeConverterRegistrar_ph_oton_basic_Mock implements IMi
{
public void registerMicroTypeConverter (@Nonnull final IMicroTypeConverterRegistry aRegistry)
{
- aRegistry.registerMicroElementTypeConverter (AccountingArea.class,
- new AccountingAreaMicroTypeConverter (new IClientResolver ()
- {
- @Nullable
- public IClient getClientOfID (@Nullable final String sID)
+ try
+ {
+ aRegistry.registerMicroElementTypeConverter (AccountingArea.class,
+ new AccountingAreaMicroTypeConverter (new IClientResolver ()
{
- return new Client (sID, "Dummy-" + sID);
- }
- }));
+ @Nullable
+ public IClient getClientOfID (@Nullable final String sID)
+ {
+ return new Client (sID, "Dummy-" + sID);
+ }
+ }));
+ }
+ catch (final IllegalArgumentException ex)
+ {
+ // Another micro element converter is already registered - ignore
+ }
}
}
|
Fixed rare bug if Eclipse m2e mixes classpathes up (again)
|
phax_ph-oton
|
train
|
82756addf99a09e02aa89bde69758d47706825b4
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -9,13 +9,22 @@ from setuptools import find_packages
import pyws
+short_description = 'Python SOAP server providing WSDL'
+long_description = \
+ '''
+ Pyws is a project, which purpuse is to help developers to expose some
+ functions of their systems as public APIs via SOAP with WSDL description.
+ The main idea is to let developers completely forget about SOAP itself and
+ make creating of APIs fast and painless.
+ '''
+
setup(
name='pyws',
version=pyws.VERSION,
package_dir={'': 'src'},
packages=find_packages('src'),
- description='Python SOAP server providing WSDL',
- long_description='Python SOAP server providing WSDL',
+ description=short_description,
+ long_description=long_description,
keywords=['soap', 'wsdl', 'server', 'xml', 'json'],
author='Stepan N. Kornyakov',
author_email='stepankk@gmail.com',
|
a little bit more of description in the installation script
|
stepank_pyws
|
train
|
b74cb748046248a78eb2758b4237e1b48e5c7682
|
diff --git a/ncpol2sdpa/sdp_relaxation.py b/ncpol2sdpa/sdp_relaxation.py
index <HASH>..<HASH> 100644
--- a/ncpol2sdpa/sdp_relaxation.py
+++ b/ncpol2sdpa/sdp_relaxation.py
@@ -20,10 +20,9 @@ else:
from .nc_utils import apply_substitutions, build_monomial, \
pick_monomials_up_to_degree, ncdegree, \
separate_scalar_factor, flatten, build_permutation_matrix, \
- simplify_polynomial, save_monomial_dictionary, get_monomials
+ simplify_polynomial, save_monomial_dictionary, get_monomials, unique
from .sdpa_utils import convert_row_to_sdpa_index
-
class SdpRelaxation(object):
"""Class for obtaining sparse SDP relaxation.
@@ -204,7 +203,7 @@ class SdpRelaxation(object):
block_index - initial_block_index - 1]
monomials = \
pick_monomials_up_to_degree(all_monomials, localization_order)
-
+ monomials = unique(monomials)
# Process M_y(gy)(u,w) entries
for row in range(len(monomials)):
for column in range(row, len(monomials)):
@@ -280,7 +279,7 @@ class SdpRelaxation(object):
localizing_monomials = \
pick_monomials_up_to_degree(flatten(monomial_sets),
localization_order)
- self.block_struct.append(len(localizing_monomials))
+ self.block_struct.append(len(localizing_monomials)/len(monomial_sets))
def get_relaxation(self, obj, inequalities, equalities,
monomial_substitutions, level,
|
Fixed some problems with the Nieto-Silleras hierarchy
|
peterwittek_ncpol2sdpa
|
train
|
fa014c12c26d10ba682fadb78f2a11c24c8118e1
|
diff --git a/vcs/nodes.py b/vcs/nodes.py
index <HASH>..<HASH> 100644
--- a/vcs/nodes.py
+++ b/vcs/nodes.py
@@ -188,8 +188,8 @@ class FileNode(Node):
else:
content = self._content
try:
- content = content.decode('utf-8')
- except UnicodeDecodeError:
+ content = content.encode('utf-8').decode('utf-8')
+ except (UnicodeDecodeError, UnicodeEncodeError):
pass
return content
|
Now before getting content of filenode vcs tries to encode to utf-8 first
|
codeinn_vcs
|
train
|
20b651258722973ec8dc4a8391808dab8bc335f0
|
diff --git a/lib/framework.js b/lib/framework.js
index <HASH>..<HASH> 100644
--- a/lib/framework.js
+++ b/lib/framework.js
@@ -2,6 +2,7 @@ const normalizer = require("@ui5/project").normalizer;
const ui5Fs = require("@ui5/fs");
const resourceFactory = ui5Fs.resourceFactory;
const ReaderCollectionPrioritized = ui5Fs.ReaderCollectionPrioritized;
+const http = require("http");
const httpProxy = require("http-proxy");
const fs = require("fs");
const path = require("path");
@@ -440,9 +441,11 @@ class Framework {
}
setupProxy({url}) {
+ const agent = new http.Agent({keepAlive: true});
const proxy = httpProxy.createProxyServer({
target: url,
- changeOrigin: true
+ changeOrigin: true,
+ agent
});
return {
diff --git a/test/unit/framework.test.js b/test/unit/framework.test.js
index <HASH>..<HASH> 100644
--- a/test/unit/framework.test.js
+++ b/test/unit/framework.test.js
@@ -147,9 +147,13 @@ describe("Proxy for UI5 ", () => {
const createProxyServer = require("http-proxy").createProxyServer;
- expect(createProxyServer).toBeCalledWith({
+ const lastCall = createProxyServer.mock.calls[createProxyServer.mock.calls.length - 1];
+ expect(lastCall[0]).toMatchObject({
target: "http://localhost",
- changeOrigin: true
+ changeOrigin: true,
+ agent: expect.objectContaining({
+ keepAlive: true
+ })
});
// const proxy = require("http-proxy").createProxyServer.mock.results[0].value;
|
[FIX] Improve performance when serving UI5 resources via URL
Using an agent with "keepAlive" improves performance when proxing
requests, especially on Windows.
|
SAP_karma-ui5
|
train
|
be7c37bf027cf88073b3f34a1915625cd540bd31
|
diff --git a/tests/specifications/googlefonts_test.py b/tests/specifications/googlefonts_test.py
index <HASH>..<HASH> 100644
--- a/tests/specifications/googlefonts_test.py
+++ b/tests/specifications/googlefonts_test.py
@@ -853,13 +853,13 @@ def test_check_085():
some_bad_values = ["APACHE", "Apache", "Ufl", "Ofl", "Open Font License"]
for good in good_licenses:
- print (f"Test PASS: ")
+ print("Test PASS: ".format(good))
md.license = good
status, message = list(check(md))[-1]
assert status == PASS
for bad in some_bad_values:
- print (f"Test FAIL: ")
+ print("Test FAIL: ".format(bad))
md.license = bad
status, message = list(check(md))[-1]
assert status == FAIL
@@ -888,14 +888,14 @@ def test_check_086():
]
for good in good_cases:
- print (f"Test PASS: ")
+ print("Test PASS: ".format(good))
del md.subsets[:]
md.subsets.extend(good)
status, message = list(check(md))[-1]
assert status == PASS
for bad in bad_cases:
- print (f"Test FAIL: ")
+ print("Test FAIL: ".format(bad))
del md.subsets[:]
md.subsets.extend(bad)
status, message = list(check(md))[-1]
@@ -924,14 +924,14 @@ def test_check_087():
]
for good in good_cases:
- print (f"Test PASS: ")
+ print("Test PASS: ".format(good))
del md.subsets[:]
md.subsets.extend(good)
status, message = list(check(md))[-1]
assert status == PASS
for bad in bad_cases:
- print (f"Test FAIL: ")
+ print("Test FAIL: ".format(bad))
del md.subsets[:]
md.subsets.extend(bad)
status, message = list(check(md))[-1]
|
Revert bad pyupgrade changes
|
googlefonts_fontbakery
|
train
|
97f9d4c5ef384fe56b2b9b97465d759ec06c33e4
|
diff --git a/lib/vagrant/busy.rb b/lib/vagrant/busy.rb
index <HASH>..<HASH> 100644
--- a/lib/vagrant/busy.rb
+++ b/lib/vagrant/busy.rb
@@ -12,6 +12,7 @@ module Vagrant
@@busy = false
@@mutex = Mutex.new
+ @@trap_thread = nil
class << self
def busy?
@@ -34,6 +35,9 @@ module Vagrant
# busy back to some sane state.
Busy.busy = false
+ # Make sure that the trap thread completes, if it is running
+ trap_thread.join if trap_thread
+
# And restore the INT trap to the default
Signal.trap("INT", "DEFAULT")
end
@@ -41,7 +45,7 @@ module Vagrant
end
def wait_for_not_busy(sleeptime=5)
- Thread.new do
+ @@trap_thread ||= Thread.new do
# Wait while the app is busy
loop do
break unless busy?
@@ -50,9 +54,20 @@ module Vagrant
end
# Exit out of the entire script
+ logger.info "Exiting vagrant..."
exit
end
end
+
+ # Used for testing
+ def reset_trap_thread!
+ @@trap_thread = nil
+ end
+
+ # Returns the trap thread
+ def trap_thread
+ @@trap_thread
+ end
end
end
end
diff --git a/test/vagrant/busy_test.rb b/test/vagrant/busy_test.rb
index <HASH>..<HASH> 100644
--- a/test/vagrant/busy_test.rb
+++ b/test/vagrant/busy_test.rb
@@ -2,7 +2,19 @@ require File.join(File.dirname(__FILE__), '..', 'test_helper')
class BusyTest < Test::Unit::TestCase
context "waiting for not busy" do
- # TODO: Need to test this method
+ setup do
+ Vagrant::Busy.reset_trap_thread!
+ end
+
+ should "run in a thread" do
+ Thread.expects(:new).once.returns(nil)
+ Vagrant::Busy.wait_for_not_busy
+ end
+
+ should "not start a thread multiple times" do
+ Thread.expects(:new).once.returns("foo")
+ Vagrant::Busy.wait_for_not_busy
+ end
end
context "during an action in a busy block" do
@@ -27,6 +39,18 @@ class BusyTest < Test::Unit::TestCase
assert !Vagrant.busy?
end
+ should "complete the trap thread even if an exception occurs" do
+ trap_thread = mock("trap_thread")
+ trap_thread.expects(:join).once
+ Vagrant::Busy.stubs(:trap_thread).returns(trap_thread)
+
+ assert_raise Exception do
+ Vagrant.busy do
+ raise Exception
+ end
+ end
+ end
+
should "report busy to the outside world regardless of thread" do
Thread.new do
Vagrant.busy do
|
Run only a single trap thread at any given time. Ensure that trap threads are joined after a busy block ends.
|
hashicorp_vagrant
|
train
|
404e336c289e8a53d43a8b55c746d2033aca7eef
|
diff --git a/prosper/common/__init__.py b/prosper/common/__init__.py
index <HASH>..<HASH> 100644
--- a/prosper/common/__init__.py
+++ b/prosper/common/__init__.py
@@ -0,0 +1 @@
+from .prosper_logging import DEFAULT_LOGGER
|
adding DEFAULT_LOGGER to prosper.common import
|
EVEprosper_ProsperCommon
|
train
|
48a4d33634e70e955eddb6906d92d501ef023ecc
|
diff --git a/lib/biceps/api_version.rb b/lib/biceps/api_version.rb
index <HASH>..<HASH> 100644
--- a/lib/biceps/api_version.rb
+++ b/lib/biceps/api_version.rb
@@ -22,7 +22,7 @@ module Biceps
end
def is_api_call?
- @is_api_call = accept.match(regex)
+ @is_api_call = accept ? accept.match(regex) : false
end
def regex
diff --git a/spec/api_version_spec.rb b/spec/api_version_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/api_version_spec.rb
+++ b/spec/api_version_spec.rb
@@ -50,4 +50,16 @@ describe Biceps::ApiVersion do
refute object.new(1).matches?(request)
end
end
+
+ describe "without any application name" do
+ let(:request) { ACTR.new }
+
+ it "should never match" do
+ refute object.new(1).matches?(request)
+ end
+
+ it "should match nil" do
+ assert object.new(nil).matches?(request)
+ end
+ end
end
|
do not fail if there is no api version provided
|
lyonrb_biceps
|
train
|
78213280d3bba01f7f2b0eca4c4f8008cd76587a
|
diff --git a/payment/src/test/java/org/killbill/billing/payment/api/TestPaymentApi.java b/payment/src/test/java/org/killbill/billing/payment/api/TestPaymentApi.java
index <HASH>..<HASH> 100644
--- a/payment/src/test/java/org/killbill/billing/payment/api/TestPaymentApi.java
+++ b/payment/src/test/java/org/killbill/billing/payment/api/TestPaymentApi.java
@@ -320,6 +320,23 @@ public class TestPaymentApi extends PaymentTestSuiteWithEmbeddedDB {
@Test(groups = "slow")
public void testCreatePurchaseWithControlPluginException() throws Exception {
+ mockPaymentControlProviderPlugin.throwsException(new PaymentControlApiException());
+
+ final BigDecimal requestedAmount = BigDecimal.TEN;
+ final String paymentExternalKey = "pay controle external key";;
+ final String transactionExternalKey = "txn control external key";
+ try {
+ paymentApi.createPurchaseWithPaymentControl(
+ account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED,
+ paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), CONTROL_PLUGIN_OPTIONS, callContext);
+ fail();
+ } catch (PaymentApiException e) {
+ assertTrue(e.getCause() instanceof PaymentControlApiException);
+ }
+ }
+
+ @Test(groups = "slow")
+ public void testCreatePurchaseWithControlPluginRuntimeException() throws Exception {
mockPaymentControlProviderPlugin.throwsException(new IllegalStateException());
final BigDecimal requestedAmount = BigDecimal.TEN;
|
Adds a test case for a control plugin raising a PaymentControlApiException
|
killbill_killbill
|
train
|
33c81429b4180a4696843e5f47bd2fa4c46372aa
|
diff --git a/src/Illuminate/Routing/ImplicitRouteBinding.php b/src/Illuminate/Routing/ImplicitRouteBinding.php
index <HASH>..<HASH> 100644
--- a/src/Illuminate/Routing/ImplicitRouteBinding.php
+++ b/src/Illuminate/Routing/ImplicitRouteBinding.php
@@ -14,6 +14,8 @@ class ImplicitRouteBinding
* @param \Illuminate\Container\Container $container
* @param \Illuminate\Routing\Route $route
* @return void
+ *
+ * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
*/
public static function resolveForRoute($container, $route)
{
diff --git a/src/Illuminate/Routing/Router.php b/src/Illuminate/Routing/Router.php
index <HASH>..<HASH> 100644
--- a/src/Illuminate/Routing/Router.php
+++ b/src/Illuminate/Routing/Router.php
@@ -757,6 +757,8 @@ class Router implements RegistrarContract, BindingRegistrar
*
* @param \Illuminate\Routing\Route $route
* @return \Illuminate\Routing\Route
+ *
+ * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
*/
public function substituteBindings($route)
{
@@ -774,6 +776,8 @@ class Router implements RegistrarContract, BindingRegistrar
*
* @param \Illuminate\Routing\Route $route
* @return void
+ *
+ * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
*/
public function substituteImplicitBindings($route)
{
|
Router substitute or ImplicitRouteBinding throws exception (#<I>)
|
laravel_framework
|
train
|
66a3340ca5a2aee251869210cc3bdef18dd25cb7
|
diff --git a/lib/wafflemix/engine.rb b/lib/wafflemix/engine.rb
index <HASH>..<HASH> 100644
--- a/lib/wafflemix/engine.rb
+++ b/lib/wafflemix/engine.rb
@@ -3,7 +3,7 @@ module Wafflemix
isolate_namespace Wafflemix
initializer 'ActiveAdmin precompile hook' do |app|
- app.config.assets.precompile += ['application.js', 'application.css']
+ app.config.assets.precompile += ['admin/admin_js.js', 'admin/admin.css']
end
end
end
|
precompile engine assets for the admin.
|
jrissler_wafflemix
|
train
|
58e6b29b85609731264dbccb07b74f8875424ee9
|
diff --git a/beeswarm/client/capabilities/smtp.py b/beeswarm/client/capabilities/smtp.py
index <HASH>..<HASH> 100644
--- a/beeswarm/client/capabilities/smtp.py
+++ b/beeswarm/client/capabilities/smtp.py
@@ -93,12 +93,16 @@ class smtp(ClientBase):
:return: Tuple containing From Address, To Address and the mail body.
"""
- mail_key = random.choice(self.mailbox.keys())
- mail = self.mailbox[mail_key]
- from_addr = mail.get_from()
- to_addr = mail['To']
- mail_body = mail.get_payload()
- return from_addr, to_addr, mail_body
+
+ while True:
+ mail_key = random.choice(self.mailbox.keys())
+ mail = self.mailbox[mail_key]
+ from_addr = mail.get_from()
+ to_addr = mail['To']
+ mail_body = mail.get_payload()
+ if not from_addr or not to_addr:
+ continue
+ return from_addr, to_addr, mail_body
def connect(self):
"""
|
make sure the data returned from the corpus has valid values
|
honeynet_beeswarm
|
train
|
82bd5888340f7a8a7dbbc1b60b98286008c0e106
|
diff --git a/lib/server.js b/lib/server.js
index <HASH>..<HASH> 100644
--- a/lib/server.js
+++ b/lib/server.js
@@ -1645,6 +1645,8 @@ WalletService.prototype._canCreateTx = function(cb) {
WalletService.prototype._validateOutputs = function(opts, wallet, cb) {
var dustThreshold = Math.max(Defaults.MIN_OUTPUT_AMOUNT, Bitcore.Transaction.DUST_AMOUNT);
+ if (_.isEmpty(opts.outputs)) return new ClientError('No outputs were specified');
+
for (var i = 0; i < opts.outputs.length; i++) {
var output = opts.outputs[i];
output.valid = false;
@@ -1753,8 +1755,6 @@ WalletService.prototype.createTx = function(opts, cb) {
opts = opts || {};
- if (!checkRequired(opts, ['outputs'], cb)) return;
-
function getChangeAddress(wallet, cb) {
if (wallet.singleAddress) {
self.storage.fetchAddresses(self.walletId, function(err, addresses) {
diff --git a/test/integration/server.js b/test/integration/server.js
index <HASH>..<HASH> 100644
--- a/test/integration/server.js
+++ b/test/integration/server.js
@@ -2294,17 +2294,16 @@ describe('Wallet service', function() {
});
});
});
- it('should fail to create a tx without outputs param', function(done) {
+ it('should fail to create a tx without outputs', function(done) {
helpers.stubUtxos(server, wallet, [1, 2], function() {
var txOpts = {
- toAddress: '18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7',
- amount: 0.8 * 1e8,
- message: 'some message',
+ outputs: [],
feePerKb: 123e2,
};
server.createTx(txOpts, function(err, tx) {
should.exist(err);
should.not.exist(tx);
+ err.message.should.equal('No outputs were specified');
done();
});
});
|
more robust validation of createTx params
|
bitpay_bitcore-wallet-service
|
train
|
1451074d668419bf8c8b2c3438908b2158498236
|
diff --git a/discord/embeds.py b/discord/embeds.py
index <HASH>..<HASH> 100644
--- a/discord/embeds.py
+++ b/discord/embeds.py
@@ -602,24 +602,39 @@ class Embed:
return self
- def clear_fields(self) -> None:
- """Removes all fields from this embed."""
+ def clear_fields(self) -> Self:
+ """Removes all fields from this embed.
+
+ This function returns the class instance to allow for fluent-style
+ chaining.
+
+ .. versionchanged:: 2.0
+ This function now returns the class instance.
+ """
try:
self._fields.clear()
except AttributeError:
self._fields = []
- def remove_field(self, index: int) -> None:
+ return self
+
+ def remove_field(self, index: int) -> Self:
"""Removes a field at a specified index.
If the index is invalid or out of bounds then the error is
silently swallowed.
+ This function returns the class instance to allow for fluent-style
+ chaining.
+
.. note::
When deleting a field by index, the index of the other fields
shift to fill the gap just like a regular list.
+ .. versionchanged:: 2.0
+ This function now returns the class instance.
+
Parameters
-----------
index: :class:`int`
@@ -630,6 +645,8 @@ class Embed:
except (AttributeError, IndexError):
pass
+ return self
+
def set_field_at(self, index: int, *, name: Any, value: Any, inline: bool = True) -> Self:
"""Modifies a field to the embed object.
|
Return embed from clear_fields and remove_field
|
Rapptz_discord.py
|
train
|
ed2e6fef9cca00303e28f7902c1c615a79d74181
|
diff --git a/cogen/core/coroutines.py b/cogen/core/coroutines.py
index <HASH>..<HASH> 100644
--- a/cogen/core/coroutines.py
+++ b/cogen/core/coroutines.py
@@ -141,20 +141,25 @@ class Coroutine(events.Operation):
self,
self._state_names[self.STATE_FINALIZED]
)
- if self.waiters:
- if sched.default_priority:
- sched.active.extendleft(self.waiters)
- else:
- sched.active.extend(self.waiters)
- self.waiters = []
- if self.caller:
- try:
- if self.exception:
- return events.CoroutineException(self.exception), self.caller
- else:
- return self, self.caller
- finally:
- self.caller = None
+ if self.state == self.STATE_NEED_INIT:
+ self.caller = coro
+ return None, self
+
+ else:
+ if self.waiters:
+ if sched.default_priority:
+ sched.active.extendleft(self.waiters)
+ else:
+ sched.active.extend(self.waiters)
+ self.waiters = []
+ if self.caller:
+ try:
+ if self.exception:
+ return events.CoroutineException(self.exception), self.caller
+ else:
+ return self, self.caller
+ finally:
+ self.caller = None
def run_op(self, op):
"""
diff --git a/cogen/core/events.py b/cogen/core/events.py
index <HASH>..<HASH> 100644
--- a/cogen/core/events.py
+++ b/cogen/core/events.py
@@ -246,8 +246,26 @@ class Signal(Operation):
sched.active.append((None, coro))
del sched.sigwait[self.name]
+
+def Call(coro, args=None, kwargs=None, **kws):
+ """
+ You don't need to use this. You can just yield the called coroutine:
+
+ .. sourcecode:: python
-class Call(Operation):
+ result = yield mycoro( [arguments] )
+
+
+ Compared to `OldCall <cogen.core.events.OldCall.html>`_,
+ instead of returning an Operation object it returns the
+ new Coroutine directly that will act as a Call operation in it's pre-init
+ state. This is faster for 2 reasons: avoids one Operation instatiation and
+ avoids pushing and poping the new coroutine on the active coros queue.
+ """
+
+ return coro(*(args or ()), **(kwargs or {}))
+
+class OldCall(Operation):
"""
This will pause the current coroutine, add a new coro in the scheduler and
resume the callee when it returns.
diff --git a/cogen/core/schedulers.py b/cogen/core/schedulers.py
index <HASH>..<HASH> 100644
--- a/cogen/core/schedulers.py
+++ b/cogen/core/schedulers.py
@@ -5,6 +5,15 @@ The scheduler handles the timeouts, run the operations and does very basic
management of coroutines. Most of the heavy logic is in each operation class.
See: `events <cogen.core.events.html>`_ and `sockets <cogen.core.sockets.html>`_.
Most of those operations work with attributes we set in the scheduler.
+
+`cogen` is multi-state. All the state related to coroutines and network is in
+the scheduler and it's associated reactor. That means you could run several
+cogen schedulers in the same process/thread/whatever.
+
+There is just one thing that uses global objects - the threadlocal-like local
+object in the coroutines module. It was actually aded for the wsgiserver
+factory that monkey patches the threadlocal module in order to make pylons run
+correctly (pylons relies heavily on threadlocals).
"""
__all__ = ['Scheduler']
import collections
@@ -67,7 +76,7 @@ class Timeout(object):
class Scheduler(object):
"""Basic deque-based scheduler with timeout support and primitive
- prioritisaiton parameters.
+ prioritisaiton parameters.
Usage:
|
changes the call operation schematics to be a bit faster
|
ionelmc_python-cogen
|
train
|
586a35661936c656c67c3ac0345cdb2d29de6162
|
diff --git a/okcupyd/filter.py b/okcupyd/filter.py
index <HASH>..<HASH> 100644
--- a/okcupyd/filter.py
+++ b/okcupyd/filter.py
@@ -16,12 +16,13 @@ class Filters(object):
requests to okcupid.com
"""
- def __init__(self):
+ def __init__(self, strict=True):
self.builders = []
self.keys = set()
self._key_to_type = {}
self._key_to_values = {}
self._key_to_string = {}
+ self._strict = strict
@util.cached_property
def filter_meta(filters_instance):
@@ -133,7 +134,7 @@ class Filters(object):
return builder.decide(builder.transform, kwargs, builder.keys)
def _validate_incoming(self, kwargs):
- if not self.keys.issuperset(kwargs.keys()):
+ if self._strict and not self.keys.issuperset(kwargs.keys()):
raise TypeError("build() got unexpected keyword arguments: "
"{0}".format(', '.join(
repr(k) for k in kwargs.keys()
diff --git a/okcupyd/json_search.py b/okcupyd/json_search.py
index <HASH>..<HASH> 100644
--- a/okcupyd/json_search.py
+++ b/okcupyd/json_search.py
@@ -12,7 +12,7 @@ from .session import Session
log = logging.getLogger(__name__)
-search_filters = filter.Filters()
+search_filters = filter.Filters(strict=False)
def SearchFetchable(session=None, **kwargs):
|
Temporarily relax incoming arg constraint on filters
|
IvanMalison_okcupyd
|
train
|
cea195c8c7704ee8ae094f1219544b0fffbd0468
|
diff --git a/shell/src/main/java/alluxio/shell/command/TestCommand.java b/shell/src/main/java/alluxio/shell/command/TestCommand.java
index <HASH>..<HASH> 100644
--- a/shell/src/main/java/alluxio/shell/command/TestCommand.java
+++ b/shell/src/main/java/alluxio/shell/command/TestCommand.java
@@ -21,7 +21,7 @@ import org.apache.commons.cli.Options;
import java.io.IOException;
-import net.jcip.annotations.ThreadSafe;
+import javax.annotation.concurrent.ThreadSafe;
/**
* Tests properties of the path specified in args.
@@ -58,9 +58,9 @@ public final class TestCommand extends AbstractShellCommand {
private void printResult(boolean testResult) {
if (testResult) {
- System.out.printf("%d\n", 0);
+ System.out.println(0);
} else {
- System.out.printf("%d\n", 1);
+ System.out.println(1);
}
}
@@ -95,7 +95,7 @@ public final class TestCommand extends AbstractShellCommand {
}
printResult(testResult);
} catch (AlluxioException | IOException e) {
- System.out.printf("%d\n", 1);
+ System.out.println(1);
}
}
diff --git a/tests/src/test/java/alluxio/shell/command/TestCommandTest.java b/tests/src/test/java/alluxio/shell/command/TestCommandTest.java
index <HASH>..<HASH> 100644
--- a/tests/src/test/java/alluxio/shell/command/TestCommandTest.java
+++ b/tests/src/test/java/alluxio/shell/command/TestCommandTest.java
@@ -14,10 +14,12 @@ package alluxio.shell.command;
import alluxio.client.FileSystemTestUtils;
import alluxio.client.WriteType;
import alluxio.shell.AbstractAlluxioShellTest;
-import java.io.IOException;
+
import org.junit.Assert;
import org.junit.Test;
+import java.io.IOException;
+
/**
* Tests for test command.
*/
|
[ALLUXIO-<I>] fix small bug in println
|
Alluxio_alluxio
|
train
|
8700d3ce7abf955dd9738bec157f342c6a685c6e
|
diff --git a/src/DataGrid.php b/src/DataGrid.php
index <HASH>..<HASH> 100644
--- a/src/DataGrid.php
+++ b/src/DataGrid.php
@@ -695,6 +695,7 @@ class DataGrid extends Nette\Application\UI\Control
* @param string $name
* @param string $href
* @param array|null $params
+ * @return Column\Action
*/
public function addAction($key, $name = '', $href = NULL, array $params = NULL)
{
@@ -759,6 +760,7 @@ class DataGrid extends Nette\Application\UI\Control
* @param string $key
* @param string $name
* @param array|string $columns
+ * @return Filter\FilterText
* @throws DataGridException
*/
public function addFilterText($key, $name, $columns = NULL)
@@ -781,6 +783,7 @@ class DataGrid extends Nette\Application\UI\Control
* @param string $name
* @param array $options
* @param string $column
+ * @return Filter\FilterSelect
* @throws DataGridException
*/
public function addFilterSelect($key, $name, $options, $column = NULL)
@@ -802,6 +805,7 @@ class DataGrid extends Nette\Application\UI\Control
* @param string $key
* @param string $name
* @param string $column
+ * @return Filter\FilterDate
* @throws DataGridException
*/
public function addFilterDate($key, $name, $column = NULL)
@@ -823,6 +827,7 @@ class DataGrid extends Nette\Application\UI\Control
* @param string $key
* @param string $name
* @param string $column
+ * @return Filter\FilterRange
* @throws DataGridException
*/
public function addFilterRange($key, $name, $column = NULL, $name_second = '-')
@@ -844,6 +849,7 @@ class DataGrid extends Nette\Application\UI\Control
* @param string $key
* @param string $name
* @param string $column
+ * @return Filter\FilterDateRange
* @throws DataGridException
*/
public function addFilterDateRange($key, $name, $column = NULL, $name_second = '-')
@@ -1165,6 +1171,7 @@ class DataGrid extends Nette\Application\UI\Control
* Add group actino
* @param string $title
* @param array $options
+ * @return GroupAction\GroupAction
*/
public function addGroupAction($title, $options = [])
{
|
added more annotation for return on DatGrid
|
contributte_datagrid
|
train
|
72f95283f576cc397e26759a95d61712bb6c6159
|
diff --git a/src/Utils/Query.php b/src/Utils/Query.php
index <HASH>..<HASH> 100644
--- a/src/Utils/Query.php
+++ b/src/Utils/Query.php
@@ -206,6 +206,81 @@ class Query
);
/**
+ * Gets an array with flags select statement has.
+ *
+ * @param Statement|null $statement the statement to be processed
+ * @param array $flagsi flags set so far
+ *
+ * @return array
+ */
+ private static function _getFlagsSelect($statement, $flags)
+ {
+ $flags['querytype'] = 'SELECT';
+ $flags['is_select'] = true;
+
+ if (!empty($statement->from)) {
+ $flags['select_from'] = true;
+ }
+
+ if ($statement->options->has('DISTINCT')) {
+ $flags['distinct'] = true;
+ }
+
+ if ((!empty($statement->group)) || (!empty($statement->having))) {
+ $flags['is_group'] = true;
+ }
+
+ if ((!empty($statement->into))
+ && ($statement->into->type === 'OUTFILE')
+ ) {
+ $flags['is_export'] = true;
+ }
+
+ $expressions = $statement->expr;
+ if (!empty($statement->join)) {
+ foreach ($statement->join as $join) {
+ $expressions[] = $join->expr;
+ }
+ }
+
+ foreach ($expressions as $expr) {
+ if (!empty($expr->function)) {
+ if ($expr->function === 'COUNT') {
+ $flags['is_count'] = true;
+ } elseif (in_array($expr->function, static::$FUNCTIONS)) {
+ $flags['is_func'] = true;
+ }
+ }
+ if (!empty($expr->subquery)) {
+ $flags['is_subquery'] = true;
+ }
+ }
+
+ if ((!empty($statement->procedure))
+ && ($statement->procedure->name === 'ANALYSE')
+ ) {
+ $flags['is_analyse'] = true;
+ }
+
+ if (!empty($statement->group)) {
+ $flags['group'] = true;
+ }
+
+ if (!empty($statement->having)) {
+ $flags['having'] = true;
+ }
+
+ if (!empty($statement->union)) {
+ $flags['union'] = true;
+ }
+
+ if (!empty($statement->join)) {
+ $flags['join'] = true;
+ }
+ return $flags;
+ }
+
+ /**
* Gets an array with flags this statement has.
*
* @param Statement|null $statement the statement to be processed
@@ -270,68 +345,7 @@ class Query
$flags['is_replace'] = true;
$flags['is_insert'] = true;
} elseif ($statement instanceof SelectStatement) {
- $flags['querytype'] = 'SELECT';
- $flags['is_select'] = true;
-
- if (!empty($statement->from)) {
- $flags['select_from'] = true;
- }
-
- if ($statement->options->has('DISTINCT')) {
- $flags['distinct'] = true;
- }
-
- if ((!empty($statement->group)) || (!empty($statement->having))) {
- $flags['is_group'] = true;
- }
-
- if ((!empty($statement->into))
- && ($statement->into->type === 'OUTFILE')
- ) {
- $flags['is_export'] = true;
- }
-
- $expressions = $statement->expr;
- if (!empty($statement->join)) {
- foreach ($statement->join as $join) {
- $expressions[] = $join->expr;
- }
- }
-
- foreach ($expressions as $expr) {
- if (!empty($expr->function)) {
- if ($expr->function === 'COUNT') {
- $flags['is_count'] = true;
- } elseif (in_array($expr->function, static::$FUNCTIONS)) {
- $flags['is_func'] = true;
- }
- }
- if (!empty($expr->subquery)) {
- $flags['is_subquery'] = true;
- }
- }
-
- if ((!empty($statement->procedure))
- && ($statement->procedure->name === 'ANALYSE')
- ) {
- $flags['is_analyse'] = true;
- }
-
- if (!empty($statement->group)) {
- $flags['group'] = true;
- }
-
- if (!empty($statement->having)) {
- $flags['having'] = true;
- }
-
- if (!empty($statement->union)) {
- $flags['union'] = true;
- }
-
- if (!empty($statement->join)) {
- $flags['join'] = true;
- }
+ $flags = self::_getFlagsSelect($statement, $flags);
} elseif ($statement instanceof ShowStatement) {
$flags['querytype'] = 'SHOW';
$flags['is_show'] = true;
|
Split select flags calculation to separate method
It's the most complex case right now, so let's separate it.
|
phpmyadmin_sql-parser
|
train
|
90b052b5a7d3563a231dfaa837b257d4770cf527
|
diff --git a/build/changelog.php b/build/changelog.php
index <HASH>..<HASH> 100755
--- a/build/changelog.php
+++ b/build/changelog.php
@@ -99,7 +99,7 @@ class Changelog extends JCli
// Prepare the link to the pull.
$doc->text('[');
$doc->startElement('link');
- $doc->writeAttribute('ns2:href', $issue->url);
+ $doc->writeAttribute('ns2:href', $issue->html_url);
$doc->writeAttribute('ns2:title', 'Closed '.$issue->closed_at);
$doc->text('#'.$issue->number);
$doc->endElement(); // ulink
@@ -107,7 +107,7 @@ class Changelog extends JCli
// Prepare the link to the author.
$doc->startElement('link');
- $doc->writeAttribute('ns2:href', $issue->user->url);
+ $doc->writeAttribute('ns2:href', 'https://github.com/'.$issue->user->login);
$doc->text($issue->user->login);
$doc->endElement(); // ulink
$doc->text(')');
@@ -136,7 +136,7 @@ class Changelog extends JCli
mkdir('./docs');
}
- file_put_contents('./docs/changelog.xml', $doc->outputMemory());
+ file_put_contents('./docs/xchangelog.xml', $doc->outputMemory());
}
catch (Exception $e)
{
|
Fixed wrong url in changelog generator
|
joomla_joomla-framework
|
train
|
7aa1d0f6aa144d04389eab2faab603c853b23909
|
diff --git a/gson/src/main/java/com/google/gson/JsonNull.java b/gson/src/main/java/com/google/gson/JsonNull.java
index <HASH>..<HASH> 100755
--- a/gson/src/main/java/com/google/gson/JsonNull.java
+++ b/gson/src/main/java/com/google/gson/JsonNull.java
@@ -25,6 +25,8 @@ package com.google.gson;
*/
public final class JsonNull extends JsonElement {
+ static final JsonNull INSTANCE = new JsonNull();
+
@Override
protected void toString(StringBuilder sb) {
sb.append("null");
diff --git a/gson/src/main/java/com/google/gson/JsonParser.java b/gson/src/main/java/com/google/gson/JsonParser.java
index <HASH>..<HASH> 100755
--- a/gson/src/main/java/com/google/gson/JsonParser.java
+++ b/gson/src/main/java/com/google/gson/JsonParser.java
@@ -51,7 +51,7 @@ final class JsonParser implements JsonParserConstants {
}
final private JsonNull JsonNull() throws ParseException {
- JsonNull json = new JsonNull();
+ JsonNull json = JsonNull.INSTANCE;
jj_consume_token(22);
{if (true) return json;}
throw new Error("Missing return statement in function");
diff --git a/gson/src/main/java/com/google/gson/JsonSerializationVisitor.java b/gson/src/main/java/com/google/gson/JsonSerializationVisitor.java
index <HASH>..<HASH> 100644
--- a/gson/src/main/java/com/google/gson/JsonSerializationVisitor.java
+++ b/gson/src/main/java/com/google/gson/JsonSerializationVisitor.java
@@ -82,7 +82,7 @@ final class JsonSerializationVisitor implements ObjectNavigator.Visitor {
public void visitArrayField(Field f, Type typeOfF, Object obj) {
if (isFieldNull(f, obj)) {
if (serializeNulls) {
- addChildAsElement(f, new JsonNull());
+ addChildAsElement(f, JsonNull.INSTANCE);
}
} else {
Object array = getFieldValue(f, obj);
@@ -93,7 +93,7 @@ final class JsonSerializationVisitor implements ObjectNavigator.Visitor {
public void visitCollectionField(Field f, Type typeOfF, Object obj) {
if (isFieldNull(f, obj)) {
if (serializeNulls) {
- addChildAsElement(f, new JsonNull());
+ addChildAsElement(f, JsonNull.INSTANCE);
}
} else {
if (typeOfF == null) {
@@ -120,7 +120,7 @@ final class JsonSerializationVisitor implements ObjectNavigator.Visitor {
public void visitObjectField(Field f, Type typeOfF, Object obj) {
if (isFieldNull(f, obj)) {
if (serializeNulls) {
- addChildAsElement(f, new JsonNull());
+ addChildAsElement(f, JsonNull.INSTANCE);
}
} else {
Object fieldValue = getFieldValue(f, obj);
@@ -167,7 +167,7 @@ final class JsonSerializationVisitor implements ObjectNavigator.Visitor {
public void visitPrimitiveField(Field f, Type typeOfF, Object obj) {
if (isFieldNull(f, obj)) {
if (serializeNulls) {
- addChildAsElement(f, new JsonNull());
+ addChildAsElement(f, JsonNull.INSTANCE);
}
} else {
TypeInfo typeInfo = new TypeInfo(typeOfF);
diff --git a/gson/src/main/javacc/JsonParser.jj b/gson/src/main/javacc/JsonParser.jj
index <HASH>..<HASH> 100755
--- a/gson/src/main/javacc/JsonParser.jj
+++ b/gson/src/main/javacc/JsonParser.jj
@@ -72,7 +72,7 @@ private JsonObject JsonObject() :
private JsonNull JsonNull() :
{
- JsonNull json = new JsonNull();
+ JsonNull json = JsonNull.INSTANCE;
}
{
"null"
|
Reusing the JsonNull instance everywhere instead of recreating it.
This is a minor optimization, which is possible because JsonNull is a stateless object.
|
google_gson
|
train
|
e519cb6a37ff68a930ab730f403def36ece0ce61
|
diff --git a/flake8_future_import.py b/flake8_future_import.py
index <HASH>..<HASH> 100755
--- a/flake8_future_import.py
+++ b/flake8_future_import.py
@@ -5,6 +5,8 @@ from __future__ import print_function
import sys
+from collections import namedtuple
+
try:
import argparse
except ImportError as e:
@@ -62,14 +64,7 @@ class Flake8Argparse(object):
pass
-class Feature(object):
-
- def __init__(self, index, name, optional, mandatory):
- self.index = index
- self.name = name
- self.optional = optional
- self.mandatory = mandatory
-
+Feature = namedtuple('Feature', 'index, name, optional, mandatory')
DIVISION = Feature(0, 'division', (2, 2, 0), (3, 0, 0))
ABSOLUTE_IMPORT = Feature(1, 'absolute_import', (2, 5, 0), (3, 0, 0))
|
Use namedtuple for Feature
The `Feature` class is very simplistic, so no need to define a normal class.
Instead it can just use `collections.namedtuple`.
|
xZise_flake8-future-import
|
train
|
f643cf610467ba0b74359a80b9bd209c1d406d00
|
diff --git a/salt/modules/virt.py b/salt/modules/virt.py
index <HASH>..<HASH> 100644
--- a/salt/modules/virt.py
+++ b/salt/modules/virt.py
@@ -2225,6 +2225,7 @@ def update(
live=True,
boot=None,
test=False,
+ boot_dev=None,
**kwargs
):
"""
@@ -2281,6 +2282,14 @@ def update(
.. versionadded:: 3000
+ :param boot_dev:
+ Space separated list of devices to boot from sorted by decreasing priority.
+ Values can be ``hd``, ``fd``, ``cdrom`` or ``network``.
+
+ By default, the value will ``"hd"``.
+
+ .. versionadded:: Magnesium
+
:param test: run in dry-run mode if set to True
.. versionadded:: 3001
@@ -2412,6 +2421,18 @@ def update(
need_update = True
+ # Check the os/boot tags
+ if boot_dev is not None:
+ boot_nodes = parent_tag.findall("boot")
+ old_boot_devs = [node.get("dev") for node in boot_nodes]
+ new_boot_devs = boot_dev.split()
+ if old_boot_devs != new_boot_devs:
+ for boot_node in boot_nodes:
+ parent_tag.remove(boot_node)
+ for dev in new_boot_devs:
+ ElementTree.SubElement(parent_tag, "boot", attrib={"dev": dev})
+ need_update = True
+
# Update the memory, note that libvirt outputs all memory sizes in KiB
for mem_node_name in ["memory", "currentMemory"]:
mem_node = desc.find(mem_node_name)
diff --git a/tests/unit/modules/test_virt.py b/tests/unit/modules/test_virt.py
index <HASH>..<HASH> 100644
--- a/tests/unit/modules/test_virt.py
+++ b/tests/unit/modules/test_virt.py
@@ -1700,6 +1700,7 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin):
<vcpu placement='auto'>1</vcpu>
<os>
<type arch='x86_64' machine='pc-i440fx-2.6'>hvm</type>
+ <boot dev="hd"/>
</os>
<devices>
<disk type='file' device='disk'>
@@ -1831,7 +1832,36 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin):
"initrd": "/root/f8-i386-initrd",
}
+ # Update boot devices case
+ define_mock.reset_mock()
+ self.assertEqual(
+ {
+ "definition": True,
+ "disk": {"attached": [], "detached": [], "updated": []},
+ "interface": {"attached": [], "detached": []},
+ },
+ virt.update("my_vm", boot_dev="cdrom network hd"),
+ )
+ setxml = ET.fromstring(define_mock.call_args[0][0])
+ self.assertEqual(
+ ["cdrom", "network", "hd"],
+ [node.get("dev") for node in setxml.findall("os/boot")],
+ )
+
+ # Update unchanged boot devices case
+ define_mock.reset_mock()
+ self.assertEqual(
+ {
+ "definition": False,
+ "disk": {"attached": [], "detached": [], "updated": []},
+ "interface": {"attached": [], "detached": []},
+ },
+ virt.update("my_vm", boot_dev="hd"),
+ )
+ define_mock.assert_not_called()
+
# Update with boot parameter case
+ define_mock.reset_mock()
self.assertEqual(
{
"definition": True,
|
virt: handle boot device in virt.update()
boot_dev parameter was hidden for a long time in the virt.init()
function but so nicely hidden that it never bubbled in the virt.update()
parameters. This commit is just reparing this mistake.
|
saltstack_salt
|
train
|
2abdc31e043f676fec4c442d97f5c6d020b038d2
|
diff --git a/pyrec/accuracy.py b/pyrec/accuracy.py
index <HASH>..<HASH> 100644
--- a/pyrec/accuracy.py
+++ b/pyrec/accuracy.py
@@ -16,7 +16,7 @@ from statistics import mean
from math import sqrt
from collections import defaultdict
-def rmse(predictions, output=True):
+def rmse(predictions, verbose=True):
"""Compute RMSE (Root Mean Squared Error).
.. math::
@@ -26,7 +26,7 @@ def rmse(predictions, output=True):
Args:
predictions (:obj:`list` of :obj:`Prediction`): The list on which to
compute the statistic.
- output: If True, will print computed value. Default is ``True``.
+ verbose: If True, will print computed value. Default is ``True``.
Returns:
@@ -42,13 +42,13 @@ def rmse(predictions, output=True):
mse = mean(float((true_r - est)**2) for (_, _, true_r, est, _) in predictions)
rmse_ = sqrt(mse)
- if output:
+ if verbose:
print('RMSE: {0:1.4f}'.format(rmse_))
return rmse_
-def mae(predictions, output=True):
+def mae(predictions, verbose=True):
"""Compute MAE (Mean Absolute Error).
.. math::
@@ -58,7 +58,7 @@ def mae(predictions, output=True):
Args:
predictions (:obj:`list` of :obj:`Prediction`): The list on which to
compute the statistic.
- output: If True, will print computed value. Default is ``True``.
+ verbose: If True, will print computed value. Default is ``True``.
Returns:
@@ -73,12 +73,12 @@ def mae(predictions, output=True):
mae_ = mean(float(abs(true_r - est)) for (_, _, true_r, est, _) in predictions)
- if output:
+ if verbose:
print('MAE: {0:1.4f}'.format(mae_))
return mae_
-def fcp(predictions, output=True):
+def fcp(predictions, verbose=True):
"""Compute FCP (Fraction of Concordant Pairs).
Computed as described in paper `Collaborative Filtering on Ordinal User
@@ -88,7 +88,7 @@ def fcp(predictions, output=True):
Args:
predictions (:obj:`list` of :obj:`Prediction`): The list on which to
compute the statistic.
- output: If True, will print computed value. Default is ``True``.
+ verbose: If True, will print computed value. Default is ``True``.
Returns:
@@ -125,7 +125,7 @@ def fcp(predictions, output=True):
raise ValueError('cannot compute fcp on this list of prediction. ' +
'Does every user have at least two predictions?')
- if output:
+ if verbose:
print('FCP: {0:1.4f}'.format(fcp))
return fcp
diff --git a/pyrec/prediction_algorithms/bases.py b/pyrec/prediction_algorithms/bases.py
index <HASH>..<HASH> 100644
--- a/pyrec/prediction_algorithms/bases.py
+++ b/pyrec/prediction_algorithms/bases.py
@@ -97,7 +97,7 @@ class AlgoBase:
self.x_biases = self.y_biases = None
self.sim = None
- def predict(self, u0, i0, r0=0, output=False):
+ def predict(self, u0, i0, r0=0, verbose=False):
"""Compute the rating prediction for user u0 and item i0.
The ``predict`` method calls the ``estimate`` method which is defined
@@ -111,7 +111,7 @@ class AlgoBase:
u0: (Inner) id of user.
i0: (Inner) id of item.
r0: The true rating :math:`r_{ui}`.
- output: If True, will print the error :math:`|r_{ui} -
+ verbose: If True, will print the error :math:`|r_{ui} -
\\hat{r}_{ui}|`. Default is ``False``.
Returns:
@@ -137,7 +137,7 @@ class AlgoBase:
est = min(self.trainset.r_max, est)
est = max(self.trainset.r_min, est)
- if output:
+ if verbose:
if impossible:
print(colors.FAIL + 'Impossible to predict' + colors.ENDC)
err = abs(est - r0)
|
changed param output to verbose
|
NicolasHug_Surprise
|
train
|
d9f61d443630cd7621e1e966a6ea43f23a9f0b6f
|
diff --git a/src/package/examples/UnusedFieldTransform.js b/src/package/examples/UnusedFieldTransform.js
index <HASH>..<HASH> 100644
--- a/src/package/examples/UnusedFieldTransform.js
+++ b/src/package/examples/UnusedFieldTransform.js
@@ -109,6 +109,18 @@ let createFieldUsagePipeline = () => {
};
});
+ pipeline.addStep('transformation', (jar) => {
+ pipeline
+ .stepResult('identification')
+ .unreferenced
+ .forEach(key => {
+ let [clazz, name, desc] = key.split(':');
+ let cls = jar[clazz];
+ let field = _.find(cls.fields, { name, desc });
+ _.remove(cls.fields, field);
+ });
+ });
+
// output
pipeline.afterStep('identification', (step, elapsed) => {
@@ -116,6 +128,10 @@ let createFieldUsagePipeline = () => {
console.log('Fields referenced: %s/%s', step.referenced, step.declared);
});
+ pipeline.afterStep('transformation', (step, elapsed) => {
+ console.log('Removed fields from classes in %ss', elapsed);
+ });
+
pipeline.after(elapsed => console.log('Unused Field Pipeline completed in %ss', elapsed));
return pipeline;
|
add step for field removal from classes in unused field transform
|
kylestev_jvm.js
|
train
|
bd2b3d114586c9269296fb219487438d9e9ab2e7
|
diff --git a/src/Acl/AccessChecker.php b/src/Acl/AccessChecker.php
index <HASH>..<HASH> 100644
--- a/src/Acl/AccessChecker.php
+++ b/src/Acl/AccessChecker.php
@@ -503,7 +503,7 @@ trait AccessChecker
if (request()->character_id) {
$character = CharacterInfo::find(request()->character_id);
- $corporation_id = $character->corporation_id;
+ $corporation_id = $character ? $character->corporation_id : null;
}
if (is_null($corporation_id))
|
fix(acl): avoid null exception if character not found
|
eveseat_web
|
train
|
38018121b11fdb2c70becf69a3094533025f6623
|
diff --git a/src/iterator.js b/src/iterator.js
index <HASH>..<HASH> 100644
--- a/src/iterator.js
+++ b/src/iterator.js
@@ -27,9 +27,8 @@ hub.iterator = function (array) {
if (index >= length) {
throw new Error("Iterator out of bounds.");
}
- var item = array[index++];
- iterator.hasNext = index < length;
- return item;
+ iterator.hasNext = index < length - 1;
+ return array[index++];
}
/**
* indicated whether more elements are available for iteration.
@@ -50,11 +49,7 @@ hub.iterator = function (array) {
var i;
if (type === "undefined") {
object = index;
- } else if (type === "number") {
- if (object < index) {
- index--;
- }
- } else {
+ } else if (type !== "number") {
for (i = array.length - 1; i >= 0; i--) {
if (array[i] === object) {
object = i;
@@ -69,6 +64,9 @@ hub.iterator = function (array) {
return false;
}
array.splice(object, 1);
+ if (object < index) {
+ index--;
+ }
iterator.hasNext = index < --length;
return true;
};
diff --git a/test/hub/iterator-test.js b/test/hub/iterator-test.js
index <HASH>..<HASH> 100644
--- a/test/hub/iterator-test.js
+++ b/test/hub/iterator-test.js
@@ -139,8 +139,19 @@ TestCase("IteratorHasNextTest", {
assertEquals(["a"], arr);
},
+
+ "test should not move next if value was found before position":
+ function () {
+ var arr = ["a", "b"];
+ var iterator = hub.iterator(arr);
+ iterator();
+
+ iterator.remove("a");
+
+ assertEquals("b", iterator());
+ },
- "test remove should return true if found": function () {
+ "test should return true if value was found": function () {
var iterator = hub.iterator(["a"]);
var result = iterator.remove("a");
@@ -148,7 +159,7 @@ TestCase("IteratorHasNextTest", {
assert(result);
},
- "test remove should return false if not found": function () {
+ "test should return false if value was not found": function () {
var iterator = hub.iterator(["a"]);
var result = iterator.remove("b");
@@ -156,7 +167,7 @@ TestCase("IteratorHasNextTest", {
assertFalse(result);
},
- "test remove should return false if no next": function () {
+ "test should return false if no next": function () {
var iterator = hub.iterator([]);
var result = iterator.remove();
|
Fixed iterator position if value was removed before current position.
|
mantoni_hub.js
|
train
|
6fbe17880131f0141bb87301ab4823c860aa94d1
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -4,7 +4,7 @@ from setuptools import setup, find_packages
setup(
name='django-disqus',
- version='0.4.1',
+ version='0.4.2',
description='Export comments and integrate DISQUS into your Django website',
author='Arthur Koziel',
author_email='arthur@arthurkoziel.com',
|
Bumped version to <I>.
|
arthurk_django-disqus
|
train
|
3907a8d92145ae6a8dea521c502281ca1fd2dbab
|
diff --git a/style.go b/style.go
index <HASH>..<HASH> 100644
--- a/style.go
+++ b/style.go
@@ -129,6 +129,9 @@ func (s Style) StrikeThrough(on bool) Style {
// Attributes returns a new style based on s, with its attributes set as
// specified.
func (s Style) Attributes(attrs AttrMask) Style {
- s.attrs = attrs
- return s
+ return Style{
+ fg: s.fg,
+ bg: s.fg,
+ attrs: attrs,
+ }
}
|
Improved the new Style.Attributes() function. (Should not modify the existing Style object.)
|
gdamore_tcell
|
train
|
5cf4d0b139a22fcca9231b6990368f5853ff4dfc
|
diff --git a/src/sorl/thumbnail/conf/defaults.py b/src/sorl/thumbnail/conf/defaults.py
index <HASH>..<HASH> 100644
--- a/src/sorl/thumbnail/conf/defaults.py
+++ b/src/sorl/thumbnail/conf/defaults.py
@@ -10,7 +10,7 @@ THUMBNAIL_DEBUG = False
THUMBNAIL_BACKEND = 'sorl.thumbnail.backends.cached_db.ThumbnailBackend'
# Thumbnail engine
-THUMBNAIL_ENGINE = 'sorl.thumbnail.engines.pgmagick.ThumbnailEngine'
+THUMBNAIL_ENGINE = 'sorl.thumbnail.engines.PIL.ThumbnailEngine'
# Default storage for the generated thumbnail
THUMBNAIL_STORAGE = settings.DEFAULT_FILE_STORAGE
@@ -20,8 +20,8 @@ THUMBNAIL_REDIS_HOST = 'localhost'
THUMBNAIL_REDIS_PORT = 6379
THUMBNAIL_REDIS_DB = 0
-# Cache timeout for `cached_db` backend. You should probably keep this at
-# maximum.
+# Cache timeout for ``cached_db`` backend. You should probably keep this at
+# maximum or ``None`` if your caching backend can handle that as infinate.
THUMBNAIL_CACHE_TIMEOUT = sys.maxint
# Thumbnail filename prefix
diff --git a/src/sorl/thumbnail/templatetags/thumbnail.py b/src/sorl/thumbnail/templatetags/thumbnail.py
index <HASH>..<HASH> 100644
--- a/src/sorl/thumbnail/templatetags/thumbnail.py
+++ b/src/sorl/thumbnail/templatetags/thumbnail.py
@@ -16,6 +16,17 @@ register = Library()
kw_pat = re.compile(r'^(?P<key>[\w]+)=(?P<value>.+)$')
+def get_image_file(file_):
+ """
+ Helper that returns and stores an ``ImageFile`` from a file input
+ """
+ image_file = ImageFile(file_)
+ backend = get_module_class(settings.THUMBNAIL_BACKEND)()
+ if not backend.store_get(image_file):
+ image_file = backend.store_set(image_file)
+ return image_file
+
+
def safe_filter(error_output=''):
"""
A safe filter decorator only raising errors when ``THUMBNAIL_DEBUG`` is
@@ -112,16 +123,14 @@ class ThumbnailNode(ThumbnailNodeBase):
yield node
+
@safe_filter(error_output='auto')
@register.filter
def is_portrait(file_):
"""
A very handy filter to determine if an image is portrait or landscape.
"""
- image_file = ImageFile(file_)
- backend = get_module_class(settings.THUMBNAIL_BACKEND)()
- if not backend.store_get(image_file):
- image_file = backend.store_set(image_file)
+ image_file = get_image_file(file_)
return image_file.is_portrait()
@@ -132,10 +141,7 @@ def margin(file_, geometry_string):
Returns the calculated margin for an image and geometry
"""
margin = [0, 0, 0, 0]
- image_file = ImageFile(file_)
- backend = get_module_class(settings.THUMBNAIL_BACKEND)()
- if not backend.store_get(image_file):
- image_file = backend.store_set(image_file)
+ image_file = get_image_file(file_)
x, y = parse_geometry(geometry_string)
if x is not None:
ex = x - image_file.x
|
breking out some duplication code
|
jazzband_sorl-thumbnail
|
train
|
c711c0049e5f12cae048d2b0e77bc70e68804ea5
|
diff --git a/py/makeversionhdr.py b/py/makeversionhdr.py
index <HASH>..<HASH> 100644
--- a/py/makeversionhdr.py
+++ b/py/makeversionhdr.py
@@ -23,7 +23,7 @@ def get_version_info_from_git():
# Note: git describe doesn't work if no tag is available
try:
git_tag = subprocess.check_output(
- ["git", "describe", "--dirty", "--always"],
+ ["git", "describe", "--dirty", "--always", "--match", "v[1-9].*"],
stderr=subprocess.STDOUT,
universal_newlines=True,
).strip()
|
py/makeversionhdr.py: Match only git tags which look like versions.
Some downstream projects may use tags in their repositories for more than
just designating MicroPython releases. In those cases, the
makeversionhdr.py script would end up using a different tag than intended.
So tell `git describe` to only match tags that look like a MicroPython
version tag, such as `<I>` or `<I>`.
|
micropython_micropython
|
train
|
6fa17caf42f4bb478aa9a5f27fbae353d8a85e33
|
diff --git a/actor.js b/actor.js
index <HASH>..<HASH> 100644
--- a/actor.js
+++ b/actor.js
@@ -2,6 +2,7 @@
var common = require('../saymon-common.js');
var P = require('bluebird');
+var _ = require('underscore');
/**
* A basic actor.
@@ -175,11 +176,11 @@ class Actor {
/**
* Returns child actors for this actor.
*
- * @returns {P} Operation promise, which yields an array of child actors.
+ * @returns {P[]} Array with child promises.
* @private
*/
_children() {
- return P.all(this.childPromises);
+ return _.clone(this.childPromises);
}
toString() {
diff --git a/standard/round-robin-balancer-actor.js b/standard/round-robin-balancer-actor.js
index <HASH>..<HASH> 100644
--- a/standard/round-robin-balancer-actor.js
+++ b/standard/round-robin-balancer-actor.js
@@ -1,6 +1,7 @@
'use strict';
var LocalActor = require('../local-actor.js');
+var P = require('bluebird');
var _ = require('underscore');
/**
@@ -39,19 +40,19 @@ class RoundRobinBalancerActor extends LocalActor {
* @private
*/
_forward(methodName, args) {
- return this._children().then(children => {
- if (_.isEmpty(children)) {
- throw new Error('No children to forward message to.');
- }
+ var childPromises = this._children();
- if (this.nextIdx > children.length - 1) {
- this.nextIdx = 0;
- }
+ if (_.isEmpty(childPromises)) {
+ return P.resolve().throw(new Error('No children to forward message to.'));
+ }
- var currentChild = children[this.nextIdx++];
+ if (this.nextIdx > childPromises.length - 1) {
+ this.nextIdx = 0;
+ }
- return currentChild[methodName].apply(currentChild, args);
- });
+ var currentChildPromise = childPromises[this.nextIdx++];
+
+ return currentChildPromise.then(child => child[methodName].apply(child, args));
}
}
|
(saymon) data-server-cluster: Reworked _children() method.
|
untu_comedy
|
train
|
42816d2f46c6b6ed5c465fc440b92b2730e26b3c
|
diff --git a/rest-org.go b/rest-org.go
index <HASH>..<HASH> 100644
--- a/rest-org.go
+++ b/rest-org.go
@@ -1,5 +1,3 @@
-// +build draft
-
package sdk
/*
|
Remove // +build draft
I don't know why but this file is ignored by the go compiler because of this // +build draft comment line
|
grafana-tools_sdk
|
train
|
ac36bcac75852e1382c9544250335ad01c3316bc
|
diff --git a/tests/opentrons_sdk/drivers/motor_test.py b/tests/opentrons_sdk/drivers/motor_test.py
index <HASH>..<HASH> 100644
--- a/tests/opentrons_sdk/drivers/motor_test.py
+++ b/tests/opentrons_sdk/drivers/motor_test.py
@@ -1,5 +1,7 @@
+import argparse
import sys
import unittest
+
from opentrons_sdk.drivers.motor import OpenTrons, GCodeLogger
@@ -46,9 +48,11 @@ class OpenTronsTest(SerialTestCase):
self.smoothie_connected = False
- if sys.argv[1]:
+ myport = '/dev/tty.usbmodem1421'
+
+ if myport:
self.smoothie_connected = True
- success = self.motor.connect(sys.argv[1])
+ success = self.motor.connect(myport)
self.assertTrue(success)
self.motor.resume()
else:
diff --git a/tests/opentrons_sdk/drivers/random_move.py b/tests/opentrons_sdk/drivers/random_move.py
index <HASH>..<HASH> 100644
--- a/tests/opentrons_sdk/drivers/random_move.py
+++ b/tests/opentrons_sdk/drivers/random_move.py
@@ -4,7 +4,9 @@ import sys
from opentrons_sdk.drivers.motor import OpenTrons, GCodeLogger
motor = OpenTrons()
-motor.connect(sys.argv[1])
+if not motor.connect(sys.argv[1]):
+ print('failed connecting to port {}'.format(sys.argv[1]))
+ sys.exit()
motor.resume()
try:
|
fixed passing port as arg to random test
|
Opentrons_opentrons
|
train
|
e4c34c7f119c0a5407eab2b05c5e24b9b2a69916
|
diff --git a/generators/server/templates/src/main/java/package/config/_MicroserviceSecurityConfiguration.java b/generators/server/templates/src/main/java/package/config/_MicroserviceSecurityConfiguration.java
index <HASH>..<HASH> 100644
--- a/generators/server/templates/src/main/java/package/config/_MicroserviceSecurityConfiguration.java
+++ b/generators/server/templates/src/main/java/package/config/_MicroserviceSecurityConfiguration.java
@@ -190,7 +190,7 @@ import <%=packageName%>.security.oauth2.SimplePrincipalExtractor;
<%_ if(applicationType === 'gateway') { _%>
import org.springframework.beans.factory.annotation.Qualifier;
<%_ } _%>
-import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.security.oauth2.resource.AuthoritiesExtractor;
import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
@@ -203,15 +203,16 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
-import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
+<%_ if(applicationType === 'gateway') { _%>
import org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
+<%_ } _%>
import org.springframework.web.client.RestTemplate;
import java.util.Map;
@@ -282,11 +283,13 @@ public class MicroserviceSecurityConfiguration extends ResourceServerConfigurerA
}
@Bean
+ @ConditionalOnProperty("security.oauth2.resource.jwt.key-uri")
public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
return new JwtTokenStore(jwtAccessTokenConverter);
}
@Bean
+ @ConditionalOnProperty("security.oauth2.resource.jwt.key-uri")
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setVerifierKey(getKeyFromAuthorizationServer());
|
Do not contact the OIDC server for a JWT signature key if it's not configured
See #<I>
|
jhipster_generator-jhipster
|
train
|
aa28a42ff164931ea37d49f0801d16a6c2da6593
|
diff --git a/spyder/plugins/plots/widgets/tests/test_plots_widgets.py b/spyder/plugins/plots/widgets/tests/test_plots_widgets.py
index <HASH>..<HASH> 100644
--- a/spyder/plugins/plots/widgets/tests/test_plots_widgets.py
+++ b/spyder/plugins/plots/widgets/tests/test_plots_widgets.py
@@ -247,8 +247,16 @@ def test_scroll_to_select_item(figbrowser, tmpdir, qtbot):
figbrowser.go_next_thumbnail()
qtbot.wait(500)
+ scene = figbrowser.thumbnails_sb.scene
+
+ spacing = scene.verticalSpacing()
+ height = scene.itemAt(0).sizeHint().height()
+ height_view = figbrowser.thumbnails_sb.scrollarea.viewport().height()
+
+ expected = (spacing * 5) + (height * 4) - ((height_view - height) // 2)
+
vsb = figbrowser.thumbnails_sb.scrollarea.verticalScrollBar()
- assert vsb.value() == 134
+ assert vsb.value() == expected
@pytest.mark.parametrize("fmt", ['image/png', 'image/svg+xml'])
|
change expected value of test_scroll_to_select_item.
|
spyder-ide_spyder
|
train
|
cada79a6d0adff5fae591e93a005fe233e77a8c1
|
diff --git a/src/Text.php b/src/Text.php
index <HASH>..<HASH> 100644
--- a/src/Text.php
+++ b/src/Text.php
@@ -28,7 +28,7 @@ class Text
return ucfirst(self::camelize($string, $separator));
}
- public static function deCamelize($string, $separator)
+ public static function deCamelize($string, $separator = '_')
{
return preg_replace_callback(
"/[A-Z][a-z]/",
|
Added a default decamelizing character
|
ntentan_utils
|
train
|
cceb0cde9ef6f78d11731ee6435f59bf5f66fa13
|
diff --git a/src/qtism/data/content/interactions/TextEntryInteraction.php b/src/qtism/data/content/interactions/TextEntryInteraction.php
index <HASH>..<HASH> 100644
--- a/src/qtism/data/content/interactions/TextEntryInteraction.php
+++ b/src/qtism/data/content/interactions/TextEntryInteraction.php
@@ -14,7 +14,7 @@
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
- * Copyright (c) 2013-2014 (original work) Open Assessment Technologies SA (under the project TAO-PRODUCT);
+ * Copyright (c) 2013-2016 (original work) Open Assessment Technologies SA (under the project TAO-PRODUCT);
*
* @author Jérôme Bogaerts <jerome@taotesting.com>
* @license GPLv2
@@ -23,6 +23,7 @@
namespace qtism\data\content\interactions;
use qtism\data\QtiComponentCollection;
+use qtism\data\state\ResponseValidityConstraint;
use qtism\common\utils\Format;
use \InvalidArgumentException;
@@ -311,6 +312,14 @@ class TextEntryInteraction extends InlineInteraction implements StringInteractio
}
/**
+ * @see qtism\data\content\interactions\Interaction::getResponseValidityConstraint()
+ */
+ public function getResponseValidityConstraint()
+ {
+ return new ResponseValidityConstraint(0, 1, $this->getPatternMask());
+ }
+
+ /**
* @see \qtism\data\QtiComponent::getComponents()
*/
public function getComponents()
|
ResponseValidityConstraint in TextEntryInteraction.
|
oat-sa_qti-sdk
|
train
|
8cf8b8a748086e33647a7f3c2235111a1a4223b1
|
diff --git a/cli/api/shell.go b/cli/api/shell.go
index <HASH>..<HASH> 100644
--- a/cli/api/shell.go
+++ b/cli/api/shell.go
@@ -152,7 +152,7 @@ func (a *api) RunShell(config ShellConfig, stopChan chan struct{}) (int, error)
if err := svc.EvaluateRunsTemplate(getSvc, findChild); err != nil {
return 1, fmt.Errorf("error evaluating service:%s Runs:%+v error:%s", svc.ID, svc.Runs, err)
}
- run, ok := svc.RunStructs[config.Command]
+ run, ok := svc.Commands[config.Command]
if !ok {
return 1, fmt.Errorf("command not found for service")
}
diff --git a/domain/common.go b/domain/common.go
index <HASH>..<HASH> 100644
--- a/domain/common.go
+++ b/domain/common.go
@@ -23,7 +23,7 @@ type MinMax struct {
Default int
}
-type Run struct {
+type Command struct {
Command string
CommitOnSuccess bool
}
diff --git a/domain/service/json.go b/domain/service/json.go
index <HASH>..<HASH> 100644
--- a/domain/service/json.go
+++ b/domain/service/json.go
@@ -30,14 +30,14 @@ func (s *Service) UnmarshalJSON(b []byte) error {
} else {
return err
}
- if len(s.RunStructs) > 0 {
+ if len(s.Commands) > 0 {
s.Runs = nil
return nil
}
if len(s.Runs) > 0 {
- s.RunStructs = make(map[string]domain.Run)
+ s.Commands = make(map[string]domain.Command)
for k, v := range s.Runs {
- s.RunStructs[k] = domain.Run{
+ s.Commands[k] = domain.Command{
Command: v,
CommitOnSuccess: false,
}
diff --git a/domain/service/service.go b/domain/service/service.go
index <HASH>..<HASH> 100644
--- a/domain/service/service.go
+++ b/domain/service/service.go
@@ -86,7 +86,7 @@ type Service struct {
LogConfigs []servicedefinition.LogConfig
Snapshot servicedefinition.SnapshotCommands
Runs map[string]string
- RunStructs map[string]domain.Run
+ Commands map[string]domain.Command
RAMCommitment utils.EngNotation
CPUCommitment uint64
Actions map[string]string
@@ -204,7 +204,7 @@ func BuildService(sd servicedefinition.ServiceDefinition, parentServiceID string
svc.Snapshot = sd.Snapshot
svc.RAMCommitment = sd.RAMCommitment
svc.Runs = sd.Runs
- svc.RunStructs = sd.RunStructs
+ svc.Commands = sd.Commands
svc.Actions = sd.Actions
svc.HealthChecks = sd.HealthChecks
svc.Prereqs = sd.Prereqs
diff --git a/domain/servicedefinition/servicedefinition.go b/domain/servicedefinition/servicedefinition.go
index <HASH>..<HASH> 100644
--- a/domain/servicedefinition/servicedefinition.go
+++ b/domain/servicedefinition/servicedefinition.go
@@ -51,7 +51,7 @@ type ServiceDefinition struct {
RAMCommitment utils.EngNotation // expected RAM commitment to use for scheduling
CPUCommitment uint64 // expected CPU commitment (#cores) to use for scheduling
Runs map[string]string // Map of commands that can be executed with 'serviced run ...'
- RunStructs map[string]domain.Run
+ Commands map[string]domain.Command
Actions map[string]string // Map of commands that can be executed with 'serviced action ...'
HealthChecks map[string]domain.HealthCheck // HealthChecks for a service.
Prereqs []domain.Prereq // Optional list of scripts that must be successfully run before kicking off the service command.
@@ -175,14 +175,14 @@ func (s *ServiceDefinition) UnmarshalJSON(b []byte) error {
} else {
return err
}
- if len(s.RunStructs) > 0 {
+ if len(s.Commands) > 0 {
s.Runs = nil
return nil
}
if len(s.Runs) > 0 {
- s.RunStructs = make(map[string]domain.Run)
+ s.Commands = make(map[string]domain.Command)
for k, v := range s.Runs {
- s.RunStructs[k] = domain.Run{
+ s.Commands[k] = domain.Command{
Command: v,
CommitOnSuccess: false,
}
|
Rename RunStructs to Commands.
|
control-center_serviced
|
train
|
e7e64d58c29afffabe89f69623757c9a38b725f8
|
diff --git a/mbuild/utils/io.py b/mbuild/utils/io.py
index <HASH>..<HASH> 100644
--- a/mbuild/utils/io.py
+++ b/mbuild/utils/io.py
@@ -36,7 +36,7 @@ The code at {filename}:{line_number} requires the "gsd" package
gsd can be installed with conda using:
-# conda install -c glotzer gsd
+# conda install -c conda-forge gsd
'''
MESSAGES['nglview'] = '''
|
Use conda-forge instead of the glotzer channel
Glotzer group doesn't maintain their conda channel and instead use `conda-forge`
|
mosdef-hub_mbuild
|
train
|
00bb48670a2f1b1cf1f29fe4096a060d0b8b71b9
|
diff --git a/lib/travis/notification/instrument.rb b/lib/travis/notification/instrument.rb
index <HASH>..<HASH> 100644
--- a/lib/travis/notification/instrument.rb
+++ b/lib/travis/notification/instrument.rb
@@ -43,7 +43,7 @@ module Travis
def serialize(object)
case object
- when NilClass, TrueClass, FalseClass, String, Symbol, Numeric, Array, Hash
+ when NilClass, TrueClass, FalseClass, String, Symbol, Numeric, Array, Hash, Mail::Message
object
else
Travis::Api.data(object, :for => 'notification', :version => 'v0')
|
this might not be the best way to fix instrumentation for emails, but sue me
|
travis-ci_travis-core
|
train
|
57a4fa54d749ce5d424885eba225e329e44bb2d5
|
diff --git a/turgles/renderer.py b/turgles/renderer.py
index <HASH>..<HASH> 100644
--- a/turgles/renderer.py
+++ b/turgles/renderer.py
@@ -4,11 +4,10 @@ import pyglet
from turgles.gles20 import * # NOQA
-from turgles.shader import Program, Buffer
+from turgles.shader import Program
from turgles.geometry import SHAPES
-from turgles.util import measure
-from turgles.shader import *
+from turgles.render.turtles import TurtleShapeVAO
class BaseRenderer(object):
@@ -29,7 +28,6 @@ class BaseRenderer(object):
self.fragment_shader = fragment_shader
# constant shape for now
- self.geometry = SHAPES[shape]
kwargs = dict(double_buffer=True)
if samples is not None:
kwargs['sample_buffers'] = 1
@@ -45,7 +43,7 @@ class BaseRenderer(object):
)
self.load_program()
- self.setup_program()
+ self.setup_program(shape)
self.set_background_color()
def set_background_color(self, color=None):
@@ -66,49 +64,11 @@ class Renderer(BaseRenderer):
vertex_shader = 'shaders/turtles1.vert'
fragment_shader = 'shaders/turtles.frag'
- def setup_program(self):
-
- self.vao = GLuint()
- glGenVertexArrays(1, self.vao)
- glBindVertexArray(self.vao)
-
- self.vertex_attr = glGetAttribLocation(self.program.id, b"vertex")
- self.turtle_attr1 = glGetAttribLocation(self.program.id, b"turtle1")
- self.turtle_attr2 = glGetAttribLocation(self.program.id, b"turtle2")
-
+ def setup_program(self, shape):
self.program.bind()
self.program.uniforms['scale'].set(self.half_width, self.half_height)
-
- # vertex buffer
- self.vertex_buffer = VertexBuffer(GLfloat, GL_STATIC_DRAW)
- self.vertex_buffer.load(self.geometry.vertices)
- self.vertex_buffer.set(self.vertex_attr)
-
- # index buffer
- self.index_buffer = Buffer(
- GL_ELEMENT_ARRAY_BUFFER, GLushort, GL_STATIC_DRAW
- )
- self.index_buffer.load(self.geometry.indices)
- self.index_buffer.bind()
-
- # model buffer
- self.turtle_buffer = VertexBuffer(GLfloat, GL_STREAM_DRAW)
- self.turtle_buffer.set(
- self.turtle_attr1, stride=32, offset=0, divisor=1)
- self.turtle_buffer.set(
- self.turtle_attr2, stride=32, offset=16, divisor=1)
+ self.vao = TurtleShapeVAO(shape, self.program, SHAPES[shape])
def render(self, turtle_data, num_turtles):
self.window.clear()
-
- with measure("load"):
- self.turtle_buffer.load(turtle_data)
-
- with measure("draw"):
- glDrawElementsInstanced(
- GL_TRIANGLES,
- self.geometry.num_vertex,
- GL_UNSIGNED_SHORT,
- 0,
- num_turtles
- )
+ self.vao.render(turtle_data, num_turtles)
diff --git a/turgles/shader.py b/turgles/shader.py
index <HASH>..<HASH> 100644
--- a/turgles/shader.py
+++ b/turgles/shader.py
@@ -164,13 +164,6 @@ class Program:
uniform = Uniform(self.id, index)
self.uniforms[uniform.name] = uniform
- # preload all attribute ids
- self.attributes = {}
- glGetProgramiv(self.id, GL_ACTIVE_ATTRIBUTES, count)
- for index in range(count[0]):
- size, type, name = load_attribute_data(self.id, index)
- self.attributes[name] = index
-
self.unbind()
def create_shader(self, src, type):
|
Removed auto-attribute data loading, as it didn't work as expected
|
AllTheWayDown_turgles
|
train
|
b13106406222cb27ab0bfcdb165ad913ce973eb1
|
diff --git a/lib/solr_wrapper.rb b/lib/solr_wrapper.rb
index <HASH>..<HASH> 100644
--- a/lib/solr_wrapper.rb
+++ b/lib/solr_wrapper.rb
@@ -8,7 +8,7 @@ require 'solr_wrapper/client'
module SolrWrapper
def self.default_solr_version
- '6.4.1'
+ '6.4.2'
end
def self.default_solr_port
diff --git a/spec/lib/solr_wrapper/instance_spec.rb b/spec/lib/solr_wrapper/instance_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lib/solr_wrapper/instance_spec.rb
+++ b/spec/lib/solr_wrapper/instance_spec.rb
@@ -151,8 +151,12 @@ describe SolrWrapper::Instance do
end
describe "#version" do
+ before do
+ allow(solr_instance.config).to receive(:version).and_return('solr-version-number')
+ end
+
subject { solr_instance.version }
- it { is_expected.to eq '6.4.1' }
+ it { is_expected.to eq 'solr-version-number' }
end
describe "#md5" do
|
Bump solr version to <I>
|
cbeer_solr_wrapper
|
train
|
3e0ce6de6c8acf678c16314c83b044fed13cf3f1
|
diff --git a/raiden/storage/migrations/v19_to_v20.py b/raiden/storage/migrations/v19_to_v20.py
index <HASH>..<HASH> 100644
--- a/raiden/storage/migrations/v19_to_v20.py
+++ b/raiden/storage/migrations/v19_to_v20.py
@@ -61,8 +61,8 @@ def _add_onchain_locksroot_to_channel_new_state_changes(
raiden: RaidenService,
storage: SQLiteStorage,
) -> None:
- """ Adds `our_onchain_locksroot` and `partner_onchain_locksroot` to
- ContractReceiveChannelNew. """
+ """ Adds `onchain_locksroot` to our_state/partner_state in
+ ContractReceiveChannelNew's channel_state object. """
batch_size = 50
batch_query = storage.batch_query_state_changes(
batch_size=batch_size,
|
Fix docstring for <I> migration
|
raiden-network_raiden
|
train
|
fde15ce1ae5540cc645cee4e2db4bc0dba896604
|
diff --git a/cmd.py b/cmd.py
index <HASH>..<HASH> 100755
--- a/cmd.py
+++ b/cmd.py
@@ -3,12 +3,12 @@ import binascii
import argparse
import json
-from bitkeylib.client import BitkeyClient
-from bitkeylib.debuglink import DebugLink
-from bitkeylib.protobuf_json import pb2json
+from trezorlib.client import TrezorClient
+from trezorlib.debuglink import DebugLink
+from trezorlib.protobuf_json import pb2json
def parse_args(commands):
- parser = argparse.ArgumentParser(description='Commandline tool for Bitkey devices.')
+ parser = argparse.ArgumentParser(description='Commandline tool for Trezor devices.')
parser.add_argument('-t', '--transport', dest='transport', choices=['usb', 'serial', 'pipe', 'socket'], default='usb', help="Transport used for talking with the device")
parser.add_argument('-p', '--path', dest='path', default='', help="Path used by the transport (usually serial port)")
parser.add_argument('-dt', '--debuglink-transport', dest='debuglink_transport', choices=['usb', 'serial', 'pipe', 'socket'], default='socket', help="Debuglink transport")
@@ -41,7 +41,7 @@ def parse_args(commands):
def get_transport(transport_string, path):
if transport_string == 'usb':
- from bitkeylib.transport_hid import HidTransport
+ from trezorlib.transport_hid import HidTransport
if path == '':
try:
@@ -52,19 +52,19 @@ def get_transport(transport_string, path):
return HidTransport(path)
if transport_string == 'serial':
- from bitkeylib.transport_serial import SerialTransport
+ from trezorlib.transport_serial import SerialTransport
return SerialTransport(path)
if transport_string == 'pipe':
- from bitkeylib.transport_pipe import PipeTransport
+ from trezorlib.transport_pipe import PipeTransport
return PipeTransport(path, is_device=False)
if transport_string == 'socket':
- from bitkeylib.transport_socket import SocketTransportClient
+ from trezorlib.transport_socket import SocketTransportClient
return SocketTransportClient(path)
if transport_string == 'fake':
- from bitkeylib.transport_fake import FakeTransport
+ from trezorlib.transport_fake import FakeTransport
return FakeTransport(path)
raise NotImplemented("Unknown transport")
@@ -149,7 +149,7 @@ class Commands(object):
)
def list_usb():
- from bitkeylib.transport_hid import HidTransport
+ from trezorlib.transport_hid import HidTransport
devices = HidTransport.enumerate()
return devices
@@ -172,7 +172,7 @@ def main():
else:
debuglink = None
- client = BitkeyClient(transport, debuglink=debuglink)
+ client = TrezorClient(transport, debuglink=debuglink)
client.setup_debuglink(button=True, pin_correct=True)
cmds = Commands(client)
|
Module renamed from bitkeylib to trezorlib
|
keepkey_python-keepkey
|
train
|
88b884378ecb7e0346b0bf74f7934a7e5c9facb4
|
diff --git a/cmd/minikube/cmd/docker-env.go b/cmd/minikube/cmd/docker-env.go
index <HASH>..<HASH> 100644
--- a/cmd/minikube/cmd/docker-env.go
+++ b/cmd/minikube/cmd/docker-env.go
@@ -249,7 +249,9 @@ var dockerEnvCmd = &cobra.Command{
exit.Error(reason.IfSSHClient, "Error with ssh-add", err)
}
- err = exec.Command(path, d.GetSSHKeyPath()).Run()
+ cmd := exec.Command(path, d.GetSSHKeyPath())
+ cmd.Stderr = os.Stderr
+ err = cmd.Run()
if err != nil {
exit.Error(reason.IfSSHClient, "Error with ssh-add", err)
}
|
Show result from running the ssh-add command
|
kubernetes_minikube
|
train
|
dbc81e0ede4a430d6ae9059eeae7007bb4c6ae81
|
diff --git a/va/validation-authority.go b/va/validation-authority.go
index <HASH>..<HASH> 100644
--- a/va/validation-authority.go
+++ b/va/validation-authority.go
@@ -331,7 +331,7 @@ func (va *ValidationAuthorityImpl) validateTLSWithZName(ctx context.Context, ide
va.log.Info(fmt.Sprintf("TLS-01 connection failure for %s. err=[%#v] errStr=[%s]", identifier, err, err))
return validationRecords, &probs.ProblemDetails{
Type: parseHTTPConnError(err),
- Detail: "Failed to connect to host for DVSNI challenge",
+ Detail: fmt.Sprintf("Failed to connect to %s for TLS-SNI-01 challenge", hostPort),
}
}
// close errors are not important here
@@ -357,8 +357,9 @@ func (va *ValidationAuthorityImpl) validateTLSWithZName(ctx context.Context, ide
va.log.Info(fmt.Sprintf("Remote host failed to give TLS-01 challenge name. host: %s", identifier))
return validationRecords, &probs.ProblemDetails{
Type: probs.UnauthorizedProblem,
- Detail: fmt.Sprintf("Correct zName not found for TLS SNI challenge. Found '%v'",
- strings.Join(certs[0].DNSNames, ", ")),
+ Detail: fmt.Sprintf("Incorrect validation certificate for TLS-SNI-01 challenge. "+
+ "Requested %s from %s. Received certificate containing '%s'",
+ zName, hostPort, strings.Join(certs[0].DNSNames, ", ")),
}
}
|
Improve error messages in validation cases. (#<I>)
* Improve error messages in validation cases.
* Add challenge type to error detail.
This makes the errors easier to search for.
* %v->%s
* Revert boulder-config to master.
|
letsencrypt_boulder
|
train
|
632680d130022b7c6f50bb06b432153a37962897
|
diff --git a/lib/stellar/client.rb b/lib/stellar/client.rb
index <HASH>..<HASH> 100644
--- a/lib/stellar/client.rb
+++ b/lib/stellar/client.rb
@@ -81,7 +81,7 @@ module Stellar
def create_account(options={})
funder = options[:funder]
sequence = options[:sequence] || (account_info(funder).sequence.to_i + 1)
- fee = options[:fee] || 100 * Stellar::ONE
+ fee = options[:fee] || 100
payment = Stellar::Transaction.create_account({
account: funder.keypair,
|
Update client to use sane fee
|
stellar_ruby-stellar-sdk
|
train
|
82cef2aae6baa37d092940c44cb7c4ccb30d7c45
|
diff --git a/http.go b/http.go
index <HASH>..<HASH> 100644
--- a/http.go
+++ b/http.go
@@ -364,16 +364,15 @@ func (s *httpService) getBackend() *httputil.ClientConn {
}
func (s *httpService) handle(req *http.Request, sc *httputil.ServerConn, tls bool) {
- req.Header.Set("X-Request-Start", strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10))
- backend := s.getBackend()
- if backend == nil {
- log.Println("no backend found")
- fail(sc, req, 503, "Service Unavailable")
- return
- }
- defer backend.Close()
-
for {
+ req.Header.Set("X-Request-Start", strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10))
+ backend := s.getBackend()
+ if backend == nil {
+ log.Println("no backend found")
+ fail(sc, req, 503, "Service Unavailable")
+ return
+ }
+
if req.Method != "GET" && req.Method != "POST" && req.Method != "HEAD" &&
req.Method != "OPTIONS" && req.Method != "PUT" && req.Method != "DELETE" && req.Method != "TRACE" {
fail(sc, req, 405, "Method not allowed")
@@ -431,6 +430,10 @@ func (s *httpService) handle(req *http.Request, sc *httputil.ServerConn, tls boo
return
}
+ // close the backend connection, so we don't accidently send to
+ // a closed socket on the backend
+ backend.Close()
+
// TODO: Proxy HTTP CONNECT? (example: Go RPC over HTTP)
if res.StatusCode == http.StatusSwitchingProtocols {
serverW, serverR := backend.Hijack()
@@ -456,7 +459,6 @@ func (s *httpService) handle(req *http.Request, sc *httputil.ServerConn, tls boo
}
return
}
- req.Header.Set("X-Request-Start", strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10))
}
}
diff --git a/http_test.go b/http_test.go
index <HASH>..<HASH> 100644
--- a/http_test.go
+++ b/http_test.go
@@ -171,3 +171,25 @@ func (s *S) TestHTTPInitialSync(c *C) {
assertGet(c, "http://"+l.Addr, "example.com", "1")
assertGet(c, "https://"+l.TLSAddr, "example.com", "1")
}
+
+// issue #26
+func (s *S) TestHTTPServiceHandlerBackendConnectionClosed(c *C) {
+ srv := httptest.NewServer(httpTestHandler("1"))
+
+ l, discoverd, err := newHTTPListener(nil)
+ c.Assert(err, IsNil)
+ defer l.Close()
+
+ discoverd.Register("test", srv.Listener.Addr().String())
+ defer discoverd.UnregisterAll()
+
+ addHTTPRoute(c, l)
+
+ // a single request is allowed to successfully get issued
+ assertGet(c, "http://"+l.Addr, "example.com", "1")
+
+ // the backend server's connection gets closed, but strowger
+ // is able to recover
+ srv.CloseClientConnections()
+ assertGet(c, "http://"+l.Addr, "example.com", "1")
+}
|
router: Fixed issue #<I>, by closing the connection with the backend on every routed request of strowger.
|
flynn_flynn
|
train
|
5784163878bdced154f7fb9f92f6467df490d0a8
|
diff --git a/tests/runner/iframe-fixture.js b/tests/runner/iframe-fixture.js
index <HASH>..<HASH> 100644
--- a/tests/runner/iframe-fixture.js
+++ b/tests/runner/iframe-fixture.js
@@ -2,9 +2,18 @@ define([
'$'
], function($) {
+ var $body = $(document.body);
+
var setUp = function(fixture, suite, done) {
var $frame = $('<iframe />').attr('src', '/tests/fixtures/' + fixture + '.html');
- $('#frameContainer').html($frame);
+
+ var $oldiFrame = $body.find('iframe');
+
+ if ($oldiFrame.length) {
+ $oldiFrame.replaceWith($frame);
+ } else {
+ $body.append($frame);
+ }
$(window).one('message', function() {
var frameWindow = $frame[0].contentWindow;
|
Changing iframe to append to body
|
mobify_pinny
|
train
|
15845f64830963c1e33fa2b5ab92974e4d800dc5
|
diff --git a/src/Zephyrus/Security/Cryptography.php b/src/Zephyrus/Security/Cryptography.php
index <HASH>..<HASH> 100644
--- a/src/Zephyrus/Security/Cryptography.php
+++ b/src/Zephyrus/Security/Cryptography.php
@@ -8,21 +8,14 @@ class Cryptography
* Cryptographically hash a specified string using the default PHP hashing
* algorithm. This method uses the default hash function included in the
* PHP core and thus automatically provides a cryptographically random
- * salt. Optionally, a user defined salt can be specified, but is strongly
- * discouraged. Throws exception if hashing failed.
+ * salt.
*
* @param string $string
- * @param string | null $salt
- * @throws \RuntimeException
* @return string
*/
- public static function hash(string $string, string $salt = null): string
+ public static function hash(string $string): string
{
- $hashOptions = [];
- if (!is_null($salt)) {
- $hashOptions['salt'] = $salt;
- }
- return password_hash($string, PASSWORD_DEFAULT, $hashOptions);
+ return password_hash($string, PASSWORD_DEFAULT);
}
/**
diff --git a/tests/security/CryptographyTest.php b/tests/security/CryptographyTest.php
index <HASH>..<HASH> 100644
--- a/tests/security/CryptographyTest.php
+++ b/tests/security/CryptographyTest.php
@@ -60,12 +60,6 @@ class CryptographyTest extends TestCase
self::assertTrue(Cryptography::verifyHash('test', $hash));
}
- public function testHashWithCustomSalt()
- {
- $hash = Cryptography::hash('test', '123456789012345678901234567890');
- self::assertTrue(Cryptography::verifyHash('test', $hash));
- }
-
public function testRehashNeeded()
{
$shaHash = '18EE24150DCB1D96752A4D6DD0F20DFD8BA8C38527E40AA8509B7ADECF78F9C6';
|
Removed salt argument for hashing method
|
dadajuice_zephyrus
|
train
|
6d8eaa414b293269426e66c9a8175a95e9f910c6
|
diff --git a/meepo/pub.py b/meepo/pub.py
index <HASH>..<HASH> 100644
--- a/meepo/pub.py
+++ b/meepo/pub.py
@@ -37,6 +37,7 @@ def mysql_pub(mysql_dsn, tables=None, blocking=True, server_id=None, **kwargs):
stream = pymysqlreplication.BinLogStreamReader(
connection_settings=mysql_settings,
blocking=blocking,
+ server_id=server_id,
only_events=[DeleteRowsEvent, UpdateRowsEvent, WriteRowsEvent],
**kwargs
)
|
server_id should be passed in
|
eleme_meepo
|
train
|
473affd01aa8fac5089720055bdbc7a34551f552
|
diff --git a/blob/rollup.config.js b/blob/rollup.config.js
index <HASH>..<HASH> 100644
--- a/blob/rollup.config.js
+++ b/blob/rollup.config.js
@@ -3,7 +3,7 @@ import { uglify } from "rollup-plugin-uglify";
import replace from "rollup-plugin-replace";
import commonjs from "rollup-plugin-commonjs";
import shim from "rollup-plugin-shim";
-import visualizer from "rollup-plugin-visualizer";
+// import visualizer from "rollup-plugin-visualizer";
const version = require("./package.json").version;
const banner = [
|
Comment visualizer from rollup to pass Node.jsv6 build
|
Azure_azure-storage-js
|
train
|
44f90f4e047e3b8768ea636a2f009fbe3c674c41
|
diff --git a/my/pagelib.php b/my/pagelib.php
index <HASH>..<HASH> 100644
--- a/my/pagelib.php
+++ b/my/pagelib.php
@@ -61,6 +61,10 @@ class page_my_moodle extends page_base {
return BLOCK_POS_LEFT;
}
+ function blocks_get_positions() {
+ return array(BLOCK_POS_LEFT, BLOCK_POS_RIGHT);
+ }
+
function blocks_move_position(&$instance, $move) {
if($instance->position == BLOCK_POS_LEFT && $move == BLOCK_MOVE_RIGHT) {
return BLOCK_POS_RIGHT;
|
Fixing another warning in my moodle blocks
|
moodle_moodle
|
train
|
d1913d492368ec9338619b72c90779d77c09b15a
|
diff --git a/lib/migrate.rb b/lib/migrate.rb
index <HASH>..<HASH> 100644
--- a/lib/migrate.rb
+++ b/lib/migrate.rb
@@ -4,7 +4,7 @@ require_relative 'migration_helpers'
# the pods table, but be independent of each other, we can
# run all trunk migrations first, then all others.
#
-migrate_to :trunk, version: 14
+migrate_to :trunk, version: 15
# These next few lines mark the current production migration versions.
#
|
[Migrate] Bump trunk version to <I>
|
CocoaPods_Humus
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.