hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
de91fc26d24d3e639830ccca7fe9fe5e271cf801
|
diff --git a/src/Arn/S3/RegionalBucketArn.php b/src/Arn/S3/RegionalBucketArn.php
index <HASH>..<HASH> 100644
--- a/src/Arn/S3/RegionalBucketArn.php
+++ b/src/Arn/S3/RegionalBucketArn.php
@@ -61,7 +61,7 @@ class RegionalBucketArn extends Arn implements ArnInterface
Arn::validate($data);
if (($data['service'] !== 's3')) {
- throw new InvalidArnException("The 3rd component of an S3 regional"
+ throw new InvalidArnException("The 3rd component of an S3"
. " bucket ARN represents the service and must be 's3'.");
}
@@ -71,19 +71,19 @@ class RegionalBucketArn extends Arn implements ArnInterface
}
if (!self::isValidHostLabel($data['account_id'])) {
- throw new InvalidArnException("The 5th component of an S3 regional"
+ throw new InvalidArnException("The 5th component of an S3"
. " bucket ARN is required, represents the account ID, and"
. " must be a valid host label.");
}
if (($data['resource_type'] !== 'bucket')) {
- throw new InvalidArnException("The 6th component of an S3 regional"
+ throw new InvalidArnException("The 6th component of an S3"
. " bucket ARN represents the resource type and must be"
. " 'bucket'.");
}
if (empty($data['bucket_name'])) {
- throw new InvalidArnException("The 7th component of an S3 regional"
+ throw new InvalidArnException("The 7th component of an S3"
. " bucket ARN represents the bucket name and must not be empty.");
}
}
diff --git a/tests/Arn/S3/RegionalBucketArnTest.php b/tests/Arn/S3/RegionalBucketArnTest.php
index <HASH>..<HASH> 100644
--- a/tests/Arn/S3/RegionalBucketArnTest.php
+++ b/tests/Arn/S3/RegionalBucketArnTest.php
@@ -36,9 +36,54 @@ class RegionalBucketArnTest extends TestCase
public function parsedArnProvider()
{
return [
+ // Colon delimiters
[
-
- ]
+ 'arn:aws:s3:us-west-2:123456789012:bucket:mybucket',
+ [
+ 'arn' => 'arn',
+ 'partition' => 'aws',
+ 'service' => 's3',
+ 'region' => 'us-west-2',
+ 'account_id' => '123456789012',
+ 'resource_type' => 'bucket',
+ 'resource_id' => 'mybucket',
+ 'resource' => 'bucket:mybucket',
+ 'bucket_name' => 'mybucket',
+ ],
+ 'arn:aws:s3:us-west-2:123456789012:bucket:mybucket',
+ ],
+ // Slash delimiter
+ [
+ 'arn:aws:s3:us-west-2:123456789012:bucket/mybucket',
+ [
+ 'arn' => 'arn',
+ 'partition' => 'aws',
+ 'service' => 's3',
+ 'region' => 'us-west-2',
+ 'account_id' => '123456789012',
+ 'resource_type' => 'bucket',
+ 'resource_id' => 'mybucket',
+ 'resource' => 'bucket/mybucket',
+ 'bucket_name' => 'mybucket',
+ ],
+ 'arn:aws:s3:us-west-2:123456789012:bucket/mybucket',
+ ],
+ // Minimum inputs
+ [
+ 'arn:aws:s3:us-west-2:1:bucket:b',
+ [
+ 'arn' => 'arn',
+ 'partition' => 'aws',
+ 'service' => 's3',
+ 'region' => 'us-west-2',
+ 'account_id' => '1',
+ 'resource_type' => 'bucket',
+ 'resource_id' => 'b',
+ 'resource' => 'bucket:b',
+ 'bucket_name' => 'b',
+ ],
+ 'arn:aws:s3:us-west-2:1:bucket:b',
+ ],
];
}
@@ -51,7 +96,7 @@ class RegionalBucketArnTest extends TestCase
public function testThrowsForBadArn($string, \Exception $expected)
{
try {
- $arn = new RegionalBucketArn($string);
+ new RegionalBucketArn($string);
$this->fail('This was expected to fail with: ' . $expected->getMessage());
} catch (\Exception $e) {
$this->assertTrue($e instanceof $expected);
@@ -66,7 +111,32 @@ class RegionalBucketArnTest extends TestCase
{
return [
[
-
+ 'arn:aws:someservice:us-west-2:123456789012:bucket:mybucket',
+ new InvalidArnException("The 3rd component of an S3 bucket ARN"
+ . " represents the service and must be 's3'.")
+ ],
+ [
+ 'arn:aws:s3::123456789012:bucket:mybucket',
+ new InvalidArnException("The 4th component of an S3 regional"
+ . " bucket ARN represents the region and must not be empty.")
+ ],
+ [
+ 'arn:aws:s3:us-west-2:*#$:bucket:mybucket',
+ new InvalidArnException("The 5th component of an S3"
+ . " bucket ARN is required, represents the account ID, and"
+ . " must be a valid host label.")
+ ],
+ [
+ 'arn:aws:s3:us-west-2:123456789012:someresource:mybucket',
+ new InvalidArnException("The 6th component of an S3"
+ . " bucket ARN represents the resource type and must be"
+ . " 'bucket'.")
+ ],
+ [
+ 'arn:aws:s3:us-west-2:123456789012:bucket:',
+ new InvalidArnException("The 7th component of an S3"
+ . " bucket ARN represents the bucket name and must not be"
+ . " empty.")
],
];
}
|
Add tests for RegionalBucketArn
|
aws_aws-sdk-php
|
train
|
ee2ab0d5b0d7a5dba6ef494b9bc0fb49a1378a7e
|
diff --git a/src/org/jgroups/protocols/TP.java b/src/org/jgroups/protocols/TP.java
index <HASH>..<HASH> 100644
--- a/src/org/jgroups/protocols/TP.java
+++ b/src/org/jgroups/protocols/TP.java
@@ -43,7 +43,7 @@ import java.util.concurrent.locks.ReentrantLock;
* The {@link #receive(Address, Address, byte[], int, int)} method must
* be called by subclasses when a unicast or multicast message has been received.
* @author Bela Ban
- * @version $Id: TP.java,v 1.136 2007/05/04 06:46:47 belaban Exp $
+ * @version $Id: TP.java,v 1.137 2007/05/04 06:52:00 belaban Exp $
*/
public abstract class TP extends Protocol {
@@ -1781,11 +1781,7 @@ public abstract class TP extends Protocol {
"). Set the fragmentation/bundle size in FRAG and TP correctly");
}
- private class BundlingTimer implements TimeScheduler.Task {
-
- public long nextInterval() {
- return max_bundle_timeout;
- }
+ private class BundlingTimer implements Runnable {
public void run() {
Map<Address,List<Message>> msgs=null;
|
Changed BundlingTimer from Task to Runnable
|
belaban_JGroups
|
train
|
b65b44cb27660c77d8ae95abeabf87f5cb7a767f
|
diff --git a/lib/driver.js b/lib/driver.js
index <HASH>..<HASH> 100644
--- a/lib/driver.js
+++ b/lib/driver.js
@@ -289,7 +289,7 @@ class EspressoDriver extends BaseDriver {
}
logger.debug('No app capability. Assuming it is already on the device');
if (this.opts.fastReset) {
- await helpers.resetApp(this.adb, this.opts.app, this.opts.appPackage, this.opts.fastReset);
+ await helpers.resetApp(this.adb, this.opts);
}
}
@@ -303,23 +303,11 @@ class EspressoDriver extends BaseDriver {
}
}
if (this.opts.app) {
- await helpers.installApkRemotely(this.adb, this.opts);
+ await helpers.installApk(this.adb, this.opts);
}
- await this.grantPermissions();
await this.espresso.installTestApk();
}
- // TODO this method is fully duplicated from uiautomator2
- async grantPermissions () {
- if (this.opts.autoGrantPermissions) {
- try {
- await this.adb.grantAllPermissions(this.opts.appPackage, this.opts.app);
- } catch (error) {
- logger.error(`Unable to grant permissions requested. Original error: ${error.message}`);
- }
- }
- }
-
async deleteSession () {
logger.debug('Deleting espresso session');
if (this.espresso) {
diff --git a/lib/espresso-runner.js b/lib/espresso-runner.js
index <HASH>..<HASH> 100644
--- a/lib/espresso-runner.js
+++ b/lib/espresso-runner.js
@@ -34,11 +34,12 @@ class EspressoRunner {
if (!(await fs.exists(this.modServerPath))) {
await this.buildNewModServer();
}
- if (await this.checkAndSignCert(this.modServerPath)) {
+ await this.checkAndSignCert(this.modServerPath);
+ if (this.forceEspressoRebuild) {
logger.info("New server was built, uninstalling any instances of it");
await this.adb.uninstallApk(TEST_APK_PKG);
}
- await this.adb.install(this.modServerPath);
+ await this.adb.installOrUpgrade(this.modServerPath, TEST_APK_PKG);
logger.info(`Installed Espresso Test Server apk '${this.modServerPath}' (pkg: '${TEST_APK_PKG}')`);
}
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -26,8 +26,8 @@
"lib": "lib"
},
"dependencies": {
- "appium-adb": "^5.0.0",
- "appium-android-driver": "^1.32.0",
+ "appium-adb": "^6.0.1",
+ "appium-android-driver": "^1.40.0",
"appium-base-driver": "^2.8.1",
"appium-support": "^2.8.2",
"asyncbox": "^2.3.1",
|
Update appium-adb to version <I> (#<I>)
* Update appium-adb to version <I>
* Add package name for faster install
* force uninstall if forceEspressoRebuild option is set
|
appium_appium-espresso-driver
|
train
|
e392560a2cba7739fff1f0995c3d2ae0ec07bdff
|
diff --git a/src/Datagrid/Action/DatagridAbstractAction.php b/src/Datagrid/Action/DatagridAbstractAction.php
index <HASH>..<HASH> 100644
--- a/src/Datagrid/Action/DatagridAbstractAction.php
+++ b/src/Datagrid/Action/DatagridAbstractAction.php
@@ -24,7 +24,7 @@ abstract class DatagridAbstractAction implements DatagridActionInterface
* @param string $route
* @param array $options
*/
- function __construct($route, $options = array())
+ public function __construct($route, $options = array())
{
$this->route = $route;
diff --git a/src/Datagrid/Field/DatagridField.php b/src/Datagrid/Field/DatagridField.php
index <HASH>..<HASH> 100644
--- a/src/Datagrid/Field/DatagridField.php
+++ b/src/Datagrid/Field/DatagridField.php
@@ -32,7 +32,7 @@ class DatagridField implements DatagridFieldInterface
* @param \Wanjee\Shuwee\AdminBundle\Datagrid\Field\Type\DatagridFieldTypeInterface $type
* @param array $options
*/
- function __construct($name, $type, $options = array())
+ public function __construct($name, $type, $options = array())
{
$this->name = $name;
$this->type = $type;
|
Fix "Methods and properties visibility should always be explicitely defined"
|
wanjee_ShuweeAdminBundle
|
train
|
04a26fdf44ed271c898494fc131692402ae03a2e
|
diff --git a/c1218/connection.py b/c1218/connection.py
index <HASH>..<HASH> 100644
--- a/c1218/connection.py
+++ b/c1218/connection.py
@@ -29,7 +29,7 @@ from c1218.errors import C1218NegotiateError, C1218IOError, C1218ReadTableError,
from c1219.data import C1219ProcedureInit
from c1219.errors import C1219ProcedureError
-if not 'c1218.urlhandler' in serial.protocol_handler_packages:
+if hasattr(serial, 'protocol_handler_packages') and not 'c1218.urlhandler' in serial.protocol_handler_packages:
serial.protocol_handler_packages.append('c1218.urlhandler')
if hasattr(logging, 'NullHandler'):
|
Fix a bug that affected older pyserial versions
|
securestate_termineter
|
train
|
8e93919befbf51fbbdc10994b54812fc1a24c0b8
|
diff --git a/lib/guard/less.rb b/lib/guard/less.rb
index <HASH>..<HASH> 100644
--- a/lib/guard/less.rb
+++ b/lib/guard/less.rb
@@ -2,6 +2,8 @@ require 'guard'
require 'guard/guard'
require 'less'
+require File.dirname(__FILE__) + "/less/version"
+
module Guard
class Less < Guard
@@ -10,7 +12,7 @@ module Guard
# ================
def start
- UI.info "Guard::Less #{VERSION} is on the job!\n"
+ UI.info "Guard::Less #{LessVersion::VERSION} is on the job!"
end
# Call with Ctrl-/ signal
|
Use the version from the conventional version.rb file.
|
guard_guard-less
|
train
|
3a359fd892cf6ad0c22d7376535899aa1743416c
|
diff --git a/superset/migrations/versions/7f2635b51f5d_update_base_columns.py b/superset/migrations/versions/7f2635b51f5d_update_base_columns.py
index <HASH>..<HASH> 100644
--- a/superset/migrations/versions/7f2635b51f5d_update_base_columns.py
+++ b/superset/migrations/versions/7f2635b51f5d_update_base_columns.py
@@ -30,7 +30,7 @@ revision = '7f2635b51f5d'
down_revision = '937d04c16b64'
from alembic import op
-from sqlalchemy import Column, engine, ForeignKey, Integer, String
+from sqlalchemy import Column, engine, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from superset import db
@@ -43,20 +43,20 @@ conv = {
}
-class BaseColumnMixin(object):
+class BaseColumnMixin:
id = Column(Integer, primary_key=True)
class DruidColumn(BaseColumnMixin, Base):
__tablename__ = 'columns'
- datasource_id = Column(Integer, ForeignKey('datasources.id'))
+ datasource_id = Column(Integer)
class TableColumn(BaseColumnMixin, Base):
__tablename__ = 'table_columns'
- table_id = Column(Integer, ForeignKey('tables.id'))
+ table_id = Column(Integer)
def upgrade():
@@ -68,7 +68,9 @@ def upgrade():
if record.datasource_id is None:
session.delete(record)
- # Enforce that the columns.column_name be non-nullable.
+ session.commit()
+
+ # Enforce that the columns.column_name column be non-nullable.
with op.batch_alter_table('columns') as batch_op:
batch_op.alter_column(
'column_name',
@@ -81,6 +83,8 @@ def upgrade():
if record.table_id is None:
session.delete(record)
+ session.commit()
+
# Reduce the size of the table_columns.column_name column for constraint
# viability and enforce that it be non-nullable.
with op.batch_alter_table('table_columns') as batch_op:
|
[schema] Adding commits and removing unnecessary foreign-key definitions (#<I>)
|
apache_incubator-superset
|
train
|
12f1fb932ddfe124a0dc68481560505a1041074a
|
diff --git a/bcbio/variation/effects.py b/bcbio/variation/effects.py
index <HASH>..<HASH> 100644
--- a/bcbio/variation/effects.py
+++ b/bcbio/variation/effects.py
@@ -101,11 +101,8 @@ def prep_vep_cache(dbkey, ref_file, tooldir=None, config=None):
vep_path = "%s/bin/" % tooldir if tooldir else ""
perl_exports = utils.get_perl_exports()
cmd = ["%svep_install" % vep_path, "-a", "c", "-s", ensembl_name,
- "-c", vep_dir, "-u", tmp_dir]
- do.run("%s && %s" % (perl_exports, " ".join(cmd)), "Prepare VEP directory for %s" % ensembl_name)
- cmd = ["%svep_convert_cache" % vep_path, "-species", species, "-version", vepv,
- "-d", vep_dir]
- do.run("%s && %s" % (perl_exports, " ".join(cmd)), "Convert VEP cache to tabix %s" % ensembl_name)
+ "-c", vep_dir, "-u", tmp_dir, "--CONVERT"]
+ do.run("%s && %s" % (perl_exports, " ".join(cmd)), "Prepare VEP directory for %s and covert cache to tabix" % ensembl_name)
for tmp_fname in os.listdir(tmp_dir):
os.remove(os.path.join(tmp_dir, tmp_fname))
os.rmdir(tmp_dir)
@@ -131,7 +128,7 @@ def run_vep(in_file, data):
fork_args = ["--fork", str(cores)] if cores > 1 else []
vep = config_utils.get_program("vep", data["config"])
is_human = tz.get_in(["genome_resources", "aliases", "human"], data, False)
- config_args = []
+ config_args = ["--fasta", dd.get_ref_file(data)]
if is_human:
plugin_fns = { "loftee": _get_loftee, "maxentscan": _get_maxentscan, "genesplicer": _get_genesplicer}
plugins = ["loftee"]
@@ -143,7 +140,7 @@ def run_vep(in_file, data):
config_args += ["--sift", "b", "--polyphen", "b"]
# XXX HGVS very slow so turned off for now, need to investigate
# Use HGVS by default, requires indexing the reference genome
- #config_args += ["--hgvs", "--shift_hgvs", "1", "--fasta", dd.get_ref_file(data)]
+ #config_args += ["--hgvs", "--shift_hgvs", "1"]
if (dd.get_effects_transcripts(data).startswith("canonical")
or tz.get_in(("config", "algorithm", "clinical_reporting"), data)):
config_args += ["--pick"]
|
updated vep cache install command, added fasta flag to defaults
|
bcbio_bcbio-nextgen
|
train
|
4cb2ba2cab1dcf3e6fb9e8a24a2b7198c1ab9ee0
|
diff --git a/min/lib/Minify/Controller/MinApp.php b/min/lib/Minify/Controller/MinApp.php
index <HASH>..<HASH> 100644
--- a/min/lib/Minify/Controller/MinApp.php
+++ b/min/lib/Minify/Controller/MinApp.php
@@ -104,16 +104,23 @@ class Minify_Controller_MinApp extends Minify_Controller_Base {
}
$allowDirs = array();
foreach ((array)$cOptions['allowDirs'] as $allowDir) {
- $allowDirs[] = realpath(str_replace('//', $_SERVER['DOCUMENT_ROOT'] . '/', $allowDir));
+ $allowDir = str_replace('//', $_SERVER['DOCUMENT_ROOT'] . '/', $allowDir);
+ $realAllowDir = realpath($allowDir);
+ if (false === $realAllowDir) {
+ $this->log("AllowDir path '{$allowDir}' failed realpath()");
+ } else {
+ $allowDirs[] = $realAllowDir;
+ }
}
foreach ($files as $file) {
$path = $_SERVER['DOCUMENT_ROOT'] . $base . $file;
$file = realpath($path);
if (false === $file) {
- $this->log("Path \"{$path}\" failed realpath()");
+ $this->log("Path '{$path}' failed realpath()");
return $options;
} elseif (! parent::_fileIsSafe($file, $allowDirs)) {
- $this->log("Path \"{$path}\" failed Minify_Controller_Base::_fileIsSafe()");
+ $this->log("File '{$file}' was not found, or not located"
+ . " inside the 'allowDirs': " . var_export($allowDirs, 1));
return $options;
} else {
$sources[] = new Minify_Source(array(
|
MinApp.php : Log problems involving 'allowDirs' option
|
mrclay_minify
|
train
|
031b99fa23d1f102ed8de4282b1335f078edca0d
|
diff --git a/ckanext/oauth2/repozewho.py b/ckanext/oauth2/repozewho.py
index <HASH>..<HASH> 100644
--- a/ckanext/oauth2/repozewho.py
+++ b/ckanext/oauth2/repozewho.py
@@ -7,6 +7,7 @@ import logging
from base64 import b64decode, b64encode
from repoze.who.interfaces import IIdentifier, IAuthenticator, IChallenger
from requests_oauthlib import OAuth2Session
+from urlparse import urlparse
from webob import Request, Response
from zope.interface import implements
@@ -84,7 +85,13 @@ class OAuth2Plugin(object):
log.debug("Challenge: Redirecting challenge to page {0}".format(auth_url))
else:
location = request.headers.get('Referer', '/')
- location = '/' if location != '/' and location == request.url else location
+ url_parsed = urlparse(location)
+
+ if url_parsed.netloc != request.host or location == request.url:
+ # When the referer is another web site, the user must be redirected to the home page
+ # When the referer is the same than the requested page, the user must be redirected to the home page
+ location = '/'
+
log.debug('User is trying to access to an Unauthorized function %r' % request.path)
response = Response()
diff --git a/ckanext/oauth2/tests/test_repozewho_plugin.py b/ckanext/oauth2/tests/test_repozewho_plugin.py
index <HASH>..<HASH> 100644
--- a/ckanext/oauth2/tests/test_repozewho_plugin.py
+++ b/ckanext/oauth2/tests/test_repozewho_plugin.py
@@ -169,7 +169,8 @@ class OAuth2PluginTest(unittest.TestCase):
('/user/login', False),
('/ckan-admin', True, '/', '/'),
('/ckan-admin', False, '/', '/'),
- ('/ckan-admin', False, '/ckan-admin', '/')
+ ('/ckan-admin', False, '/ckan-admin', '/'),
+ ('/ckan-admin', True, 'http://google.es/', '/')
])
def test_challenge(self, path, include_referer=True, referer='/', expected_url=None):
|
Users comming from others sites are redirected to the home page when they don't have grants to use a function
|
conwetlab_ckanext-oauth2
|
train
|
d81a6f02da64fa3379487c1ca9543cc7f1a291f2
|
diff --git a/includes/ShipmentDetails.php b/includes/ShipmentDetails.php
index <HASH>..<HASH> 100644
--- a/includes/ShipmentDetails.php
+++ b/includes/ShipmentDetails.php
@@ -152,6 +152,15 @@ class ShipmentDetails {
private $packageType = self::PACKAGE;
/**
+ * E-mail address for shipping notification
+ *
+ * Note: Optional
+ *
+ * @var string|null $notificationEmail - Notification E-Mail
+ */
+ private $notificationEmail;
+
+ /**
* ShipmentDetails constructor.
*
* @param string $accountNumber - Account-Number
@@ -345,6 +354,20 @@ class ShipmentDetails {
}
/**
+ * @return string|null
+ */
+ public function getNotificationEmail() {
+ return $this->notificationEmail;
+ }
+
+ /**
+ * @param string|null $notificationEmail
+ */
+ public function setNotificationEmail($notificationEmail) {
+ $this->notificationEmail = $notificationEmail;
+ }
+
+ /**
* Creates a Default Shipment-Date (Today or if Sunday the next Day)
*
* @return string - Default-Date
@@ -395,6 +418,11 @@ class ShipmentDetails {
if($this->getHeight() !== null)
$class->ShipmentItem->heightInCM = $this->getHeight();
+ if($this->notificationEmail) {
+ $class->Notification = new StdClass;
+ $class->Notification->recipientEmailAddress = $this->notificationEmail;
+ }
+
return $class;
}
}
|
Added support for notification e-mail
See ShipmentOrder.Shipment.ShipmentDetails.Notification.recipientEmailAddress
|
Petschko_dhl-php-sdk
|
train
|
9b6035bfccb86fee3405baef9702837c115d7207
|
diff --git a/nodejs/lib/checkVersion.js b/nodejs/lib/checkVersion.js
index <HASH>..<HASH> 100644
--- a/nodejs/lib/checkVersion.js
+++ b/nodejs/lib/checkVersion.js
@@ -15,7 +15,7 @@ module.exports = function(callback) {
callback();
}, 5000);
- exec('npm info calvin-network-tools', {},
+ exec('npm view --json calvin-network-tools', {},
function (error, stdout, stderr) {
if( cancel ) {
return;
|
Fix NPM command that was failing and breaking code
May not handle all cases, but at least it's not broken anymore
|
ucd-cws_calvin-network-tools
|
train
|
a98421f95317dae5b621a7774df86baeabd4fb93
|
diff --git a/example_plugin/main.go b/example_plugin/main.go
index <HASH>..<HASH> 100644
--- a/example_plugin/main.go
+++ b/example_plugin/main.go
@@ -1,16 +1,22 @@
package main
import (
+ "log"
+
"github.com/natefinch/plugin"
)
func main() {
+ log.SetPrefix("[plugin log] ")
+
plugin.Provide("Plugin", api{})
}
type api struct{}
func (api) SayHi(name string, response *string) error {
+ log.Printf("got call for SayHi with name %q", name)
+
*response = "Hi " + name
return nil
}
|
show how to use stderr for logging
|
natefinch_pie
|
train
|
93cffbab1f101f79ccbeee2834a54ca8d04f86e9
|
diff --git a/lib/ruboto/util/setup.rb b/lib/ruboto/util/setup.rb
index <HASH>..<HASH> 100644
--- a/lib/ruboto/util/setup.rb
+++ b/lib/ruboto/util/setup.rb
@@ -139,19 +139,17 @@ module Ruboto
regex = '(\>android-sdk.*.tgz)'
when WINDOWS
regex = '(\>installer_.*.exe)'
- else #Error
- nil
+ else
+ raise "Unknown host os: #{android_package_os_id}"
end
- link = page_content.scan(/#{regex}/).to_s
- version = link.match(/r(\d+.)?(\d+.)?(\d+)/)[0]
-
- if version.nil?
- puts "File version cannot be determined "
- else
- version.delete! 'r'
- end
+ link = page_content.scan(/#{regex}/)
+ raise "SDK link cannot be found on download page: #{SDK_DOWNLOAD_PAGE}" if link.nil?
+
+ version = link.to_s.match(/r(\d+.)?(\d+.)?(\d+)/)[0]
+ raise "SDK version cannot be determined from download page: #{SDK_DOWNLOAD_PAGE}" if version.nil?
+ version.delete! 'r'
end
#########################################
@@ -289,7 +287,7 @@ module Ruboto
end
if accept_all || a == 'Y' || a.empty?
puts "sudo #{installer} install -y #{package_name}"
- `sudo #{installer} install -y #{package_name}`
+ IO.popen("sudo #{installer} install -y #{package_name}") {|io| while (l = io.gets) do; puts l; end }
else
puts
puts "You can install #{pretty_name} manually by:"
|
(#<I>) Display progress during Linux package installs; Additional error checking on SDK version determination
|
ruboto_ruboto
|
train
|
d1734a3e5d87996f52562859029c70a9bc994f7a
|
diff --git a/theanets/graph.py b/theanets/graph.py
index <HASH>..<HASH> 100644
--- a/theanets/graph.py
+++ b/theanets/graph.py
@@ -556,6 +556,8 @@ class Network(object):
def __setstate__(self, state):
self.layers, self.loss = state
+ self._graphs = {}
+ self._functions = {}
def save(self, filename):
'''Save the state of this network to a pickle file on disk.
|
Create empty cache dictionaries on load.
Closes #<I>.
|
lmjohns3_theanets
|
train
|
b123f046e7b616fa682454deca4adcb17ae66f56
|
diff --git a/lib/typhoeus/response.rb b/lib/typhoeus/response.rb
index <HASH>..<HASH> 100644
--- a/lib/typhoeus/response.rb
+++ b/lib/typhoeus/response.rb
@@ -10,7 +10,7 @@ module Typhoeus
def initialize(params = {})
@code = params[:code]
@status_message = params[:status_message]
- @headers = params[:headers]
+ @headers = params[:headers] || ''
@body = params[:body]
@time = params[:time]
@requested_url = params[:requested_url]
diff --git a/spec/typhoeus/response_spec.rb b/spec/typhoeus/response_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/typhoeus/response_spec.rb
+++ b/spec/typhoeus/response_spec.rb
@@ -61,6 +61,10 @@ describe Typhoeus::Response do
end
describe "headers" do
+ it 'should return an empty hash from #headers_hash when no headers string is given' do
+ response = Typhoeus::Response.new.headers_hash.should == {}
+ end
+
describe "basic parsing" do
before(:all) do
@response = Typhoeus::Response.new(:headers => "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nConnection: close\r\nStatus: 200\r\nX-Powered-By: Phusion Passenger (mod_rails/mod_rack) 2.2.9\r\nX-Cache: miss\r\nX-Runtime: 184\r\nETag: e001d08d9354ab7bc7c27a00163a3afa\r\nCache-Control: private, max-age=0, must-revalidate\r\nContent-Length: 4725\r\nSet-Cookie: _some_session=BAh7CDoGciIAOg9zZXNzaW9uX2lkIiU1OTQ2OTcwMjljMWM5ZTQwODU1NjQwYTViMmQxMTkxMjoGcyIKL2NhcnQ%3D--b4c4663932243090c961bb93d4ad5e4327064730; path=/; HttpOnly\r\nServer: nginx/0.6.37 + Phusion Passenger 2.2.4 (mod_rails/mod_rack)\r\nSet-Cookie: foo=bar; path=/;\r\nP3P: CP=\"NOI DSP COR NID ADMa OPTa OUR NOR\"\r\n\r\n")
|
Prevent NoMethodErrors when no :headers is passed to Typhoeus::Response.
|
typhoeus_typhoeus
|
train
|
7fe42c4c4ff70b1732799589a177fdda5deeb497
|
diff --git a/src/test/java/org/jboss/netty/bootstrap/AbstractSocketServerBootstrapTest.java b/src/test/java/org/jboss/netty/bootstrap/AbstractSocketServerBootstrapTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/org/jboss/netty/bootstrap/AbstractSocketServerBootstrapTest.java
+++ b/src/test/java/org/jboss/netty/bootstrap/AbstractSocketServerBootstrapTest.java
@@ -82,7 +82,7 @@ public abstract class AbstractSocketServerBootstrapTest {
protected abstract ChannelFactory newServerSocketChannelFactory(Executor executor);
- @Test(timeout = 10000, expected = ChannelException.class)
+ @Test(timeout = 30000, expected = ChannelException.class)
public void testFailedBindAttempt() throws Exception {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.setFactory(newServerSocketChannelFactory(executor));
@@ -90,7 +90,7 @@ public abstract class AbstractSocketServerBootstrapTest {
bootstrap.bind();
}
- @Test(timeout = 10000)
+ @Test(timeout = 30000)
public void testSuccessfulBindAttempt() throws Exception {
ServerBootstrap bootstrap = new ServerBootstrap(
newServerSocketChannelFactory(executor));
|
Increased test timeout to avoid Hudson false alarm
|
netty_netty
|
train
|
234f5763e21d5d01e8d63aad68aef50a69055513
|
diff --git a/lib/nagios_analyzer/section.rb b/lib/nagios_analyzer/section.rb
index <HASH>..<HASH> 100644
--- a/lib/nagios_analyzer/section.rb
+++ b/lib/nagios_analyzer/section.rb
@@ -10,6 +10,11 @@ module NagiosAnalyzer
self[$1.to_sym] = ($2 == "#{$2.to_i}" ? $2.to_i : $2)
end
end
+ if self[:type] == "servicestatus"
+ self[:status] = NagiosAnalyzer::Status::STATES[self[:current_state]]
+ else
+ self[:status] = (self[:current_state] == NagiosAnalyzer::Status::STATE_OK ? "OK" : "CRITICAL")
+ end
end
end
end
diff --git a/spec/nagios_analyzer_section_spec.rb b/spec/nagios_analyzer_section_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/nagios_analyzer_section_spec.rb
+++ b/spec/nagios_analyzer_section_spec.rb
@@ -24,4 +24,13 @@ describe NagiosAnalyzer::Section do
@section[:max_attempts].should be_a(Integer)
@section[:max_attempts].should == 3
end
+
+ it "provides a :status key to know the status" do
+ @section[:status].should == "WARNING"
+ Section.new("servicestatus {\ncurrent_state=0\n}")[:status].should == "OK"
+ Section.new("servicestatus {\ncurrent_state=2\n}")[:status].should == "CRITICAL"
+ Section.new("servicestatus {\ncurrent_state=3\n}")[:status].should == "UNKNOWN"
+ Section.new("hoststatus {\ncurrent_state=0\n}")[:status].should == "OK"
+ Section.new("hoststatus {\ncurrent_state=42\n}")[:status].should == "CRITICAL"
+ end
end
|
Added a ':status' key to Section, which is a string like OK, WARNING, CRITICAL, etc.
|
jbbarth_nagios_analyzer
|
train
|
3586000aa7463753e0faefe15bf5149e930dace8
|
diff --git a/lib/octokit/error.rb b/lib/octokit/error.rb
index <HASH>..<HASH> 100644
--- a/lib/octokit/error.rb
+++ b/lib/octokit/error.rb
@@ -15,7 +15,7 @@ module Octokit
if klass = case status
when 400 then Octokit::BadRequest
when 401
- if headers["X-GitHub-OTP"].to_s =~ /required/i
+ if Octokit::OneTimePasswordRequired.required_header(headers)
Octokit::OneTimePasswordRequired
else
Octokit::Unauthorized
@@ -108,7 +108,17 @@ module Octokit
# Raised when GitHub returns a 401 HTTP status code
# and headers include "X-GitHub-OTP"
- class OneTimePasswordRequired < Error; end
+ class OneTimePasswordRequired < Error
+ HEADER = /required; (?<delivery>\w+)/i
+
+ def self.required_header(headers)
+ HEADER.match headers['X-GitHub-OTP'].to_s
+ end
+
+ def password_delivery
+ @password_delivery ||= self.class.required_header(@response[:response_headers])[:delivery]
+ end
+ end
# Raised when GitHub returns a 403 HTTP status code
class Forbidden < Error; end
diff --git a/spec/octokit/client_spec.rb b/spec/octokit/client_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/octokit/client_spec.rb
+++ b/spec/octokit/client_spec.rb
@@ -494,4 +494,20 @@ describe Octokit::Client do
expect { Octokit.get('/authorizations/1') }.to raise_error Octokit::OneTimePasswordRequired
end
+ it "knows the password delivery mechanism when needs OTP" do
+ stub_get('/authorizations/1').to_return \
+ :status => 401,
+ :headers => {
+ :content_type => "application/json",
+ "X-GitHub-OTP" => "required; app"
+ },
+ :body => {:message => "Must specify two-factor authentication OTP code."}.to_json
+
+ begin
+ Octokit.get('/authorizations/1')
+ rescue Octokit::OneTimePasswordRequired => otp_error
+ expect(otp_error.password_delivery).to eql 'app'
+ end
+ end
+
end
|
Add #password_delivery to OneTimePasswordRequired
|
octokit_octokit.rb
|
train
|
fb864dc3f2c1fc484f5ca4aee952446ad321332b
|
diff --git a/lib/pdf_forms/field.rb b/lib/pdf_forms/field.rb
index <HASH>..<HASH> 100644
--- a/lib/pdf_forms/field.rb
+++ b/lib/pdf_forms/field.rb
@@ -16,14 +16,17 @@ module PdfForms
when /FieldStateOption:\s*(.*?)\s*$/
(@options ||= []) << $1
else
- if match = line.match(/^\s*(?<key>[^:]+):\s*(?<value>.*)$/)
- key = match[:key].to_s.strip
- value = match[:value].to_s
- var_name = key.gsub(/Field/, '').downcase
- unless self.respond_to?(var_name)
- self.class.send(:define_method, var_name.to_sym, Proc.new{ instance_variable_get("@#{var_name}".to_sym) } ) # in case new or unknown fields crop up...
- end
- instance_variable_set("@#{key.gsub(/Field/, '').downcase}".to_sym, value)
+ line.strip!
+ key, value = line.split(": ")
+ key.gsub!(/Field/, "")
+ key = key.split(/(?=[A-Z])/).map(&:downcase).join('_').split(":")[0]
+
+ instance_variable_set("@#{key}", value)
+
+ # dynamically add in fields that we didn't anticipate in ATTRS
+ unless self.respond_to?(key.to_sym)
+ proc = Proc.new { instance_variable_get("@#{key}".to_sym) }
+ self.class.send(:define_method, key.to_sym, proc)
end
end
end
@@ -39,7 +42,7 @@ module PdfForms
end
# Common Fields
- ATTRS = [:name, :type, :options, :flags, :justification, :value, :valuedefault, :namealt]
+ ATTRS = [:name, :type, :options, :flags, :justification, :value, :value_default, :name_alt, :max_length]
ATTRS.each {|attribute| attr_reader attribute}
end
end
diff --git a/test/field_test.rb b/test/field_test.rb
index <HASH>..<HASH> 100644
--- a/test/field_test.rb
+++ b/test/field_test.rb
@@ -25,8 +25,8 @@ END
assert_equal 'SomeChoiceField', f.name
assert_equal ['', '010 Foo Bar', 'Another option (xyz)'], f.options
- assert_equal "http://github.com foo ", f.value
- assert_equal "", f.valuedefault
+ assert_equal "http://github.com foo", f.value
+ assert_equal nil, f.value_default
assert_equal "Left", f.justification
assert_equal "71696384", f.flags
end
|
Simplified field name parsing
|
jkraemer_pdf-forms
|
train
|
04d9bb65b6ad9ec7c8a08615ceb6e263dad6d9ce
|
diff --git a/src/Ui/Renderer/Renderer.php b/src/Ui/Renderer/Renderer.php
index <HASH>..<HASH> 100644
--- a/src/Ui/Renderer/Renderer.php
+++ b/src/Ui/Renderer/Renderer.php
@@ -91,8 +91,6 @@ abstract class Renderer implements RendererInterface
$output = $this->doRender();
- $this->tearDown();
-
return $output;
}
|
removed teardown method invocation to prevent nested calls to the renderer instance stepping on each others state
|
honeybee_honeybee
|
train
|
980343742ce710179564feddfd1f949885536e5e
|
diff --git a/treeherder/workers/task.py b/treeherder/workers/task.py
index <HASH>..<HASH> 100644
--- a/treeherder/workers/task.py
+++ b/treeherder/workers/task.py
@@ -14,6 +14,7 @@ class retryable_task(object):
NON_RETRYABLE_EXCEPTIONS = (
TypeError,
+ ValueError,
IntegrityError,
ProgrammingError,
UnicodeDecodeError,
|
Bug <I> - Don't retry tasks on ValueError
Since retries are not going to succeed either.
|
mozilla_treeherder
|
train
|
5a2500f0f74321fffa02ab405f1b440874f2309e
|
diff --git a/tools/licensescheck.py b/tools/licensescheck.py
index <HASH>..<HASH> 100644
--- a/tools/licensescheck.py
+++ b/tools/licensescheck.py
@@ -23,7 +23,8 @@ prunelist = ('hsqldb19b3',
'deploymentfile',
'xml',
'helloworld',
- 'CSVReader.java')
+ 'CSVReader.java',
+ 'jaxb')
def verifyLicense(f, content, approvedLicensesJavaC, approvedLicensesPython):
if f.endswith('.py'):
|
Add jaxb directory as license check exception.
|
VoltDB_voltdb
|
train
|
97948900f5e7d69fe081ab8f0031e28d10f62117
|
diff --git a/lib/builder.js b/lib/builder.js
index <HASH>..<HASH> 100644
--- a/lib/builder.js
+++ b/lib/builder.js
@@ -72,7 +72,7 @@ builder.getSwaggerJSON = function (settings, request, callback) {
if (settings.connectionLabel) {
connection = namedConnection = request.server.select(settings.connectionLabel).connections[0];
- if (request.server.select(settings.connectionLabel).connections.length === 1) {
+ if (request.server.select(settings.connectionLabel).connections.length !== 1) {
request.server.log(['error'], 'connectionLabel should only define one connection to document');
}
}
|
allow connectionLabel if it matches a single connection
|
reptilbud_hapi-swagger
|
train
|
10ec2cc604780a2d6ad3d0958cd9e382f7861432
|
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -4,7 +4,7 @@
"description": "Simple Validation Mixin for React.",
"main": "./lib/index.js",
"scripts": {
- "build": "npm run build:lib && npm run build:demo",
+ "build": "npm run lint && npm run build:lib && npm run build:demo",
"build:lib": "babel src --out-dir lib",
"build:demo": "mkdirp lib/spec && browserify ./spec/demo.js -t babelify --outfile ./lib/spec/demo.js",
"test": "karma start karma.conf.js --single-run",
diff --git a/spec/demo.js b/spec/demo.js
index <HASH>..<HASH> 100644
--- a/spec/demo.js
+++ b/spec/demo.js
@@ -1,4 +1,5 @@
import React from 'react';
+import {render} from 'react-dom';
import Signup from './components/Signup';
-React.render(<Signup />, document.getElementById('app'));
+render(<Signup />, document.getElementById('app'));
diff --git a/src/components/validationMixin.js b/src/components/validationMixin.js
index <HASH>..<HASH> 100755
--- a/src/components/validationMixin.js
+++ b/src/components/validationMixin.js
@@ -6,6 +6,7 @@ import result from '../utils/result';
export default function(strategy) {
const validator = factory(strategy);
return function(WrappedComponent) {
+ invariant(WrappedComponent !== null && WrappedComponent !== undefined, 'Component was not provided to the Validator. Export you Component with "export default validator(strategy)(Component);"');
function getDisplayName(Component) {
return Component.displayName || Component.name || 'Component';
}
|
Added invariant when no Component is supplied to Validator. ensure lint is called before build chain.
|
jurassix_react-validation-mixin
|
train
|
9583ef4e196b056150298502cdc89e308d7128eb
|
diff --git a/wsapi.go b/wsapi.go
index <HASH>..<HASH> 100644
--- a/wsapi.go
+++ b/wsapi.go
@@ -24,6 +24,9 @@ func (s *Session) Open() (err error) {
// Get the gateway to use for the Websocket connection
g, err := s.Gateway()
+ if err != nil {
+ return
+ }
// TODO: See if there's a use for the http response.
// conn, response, err := websocket.DefaultDialer.Dial(session.Gateway, nil)
|
Return immediately if err getting gateway.
|
bwmarrin_discordgo
|
train
|
20e8a26b89bdd654a1ac5090330b8ea1d3da1e27
|
diff --git a/test/rendering/ol/style/text.test.js b/test/rendering/ol/style/text.test.js
index <HASH>..<HASH> 100644
--- a/test/rendering/ol/style/text.test.js
+++ b/test/rendering/ol/style/text.test.js
@@ -142,7 +142,7 @@ describe('ol.rendering.style.Text', function() {
})
}));
vectorSource.addFeature(feature);
- expectResemble(map, 'rendering/ol/style/expected/text-align-offset-canvas.png', 5, done);
+ expectResemble(map, 'rendering/ol/style/expected/text-align-offset-canvas.png', 6, done);
});
it('renders multiline text with positioning options', function(done) {
@@ -188,7 +188,7 @@ describe('ol.rendering.style.Text', function() {
})
}));
vectorSource.addFeature(feature);
- expectResemble(map, 'rendering/ol/style/expected/text-align-offset-canvas.png', 5, done);
+ expectResemble(map, 'rendering/ol/style/expected/text-align-offset-canvas.png', 6, done);
});
where('WebGL').it('tests the webgl renderer without rotation', function(done) {
|
Raise tolerance of rendering tests to pass on Firefox <I> (GNU/Linux)
|
openlayers_openlayers
|
train
|
bc797eed4633e6613ef2572531b3be65bcdf6521
|
diff --git a/scripts/trigger-mobile-metrics.py b/scripts/trigger-mobile-metrics.py
index <HASH>..<HASH> 100644
--- a/scripts/trigger-mobile-metrics.py
+++ b/scripts/trigger-mobile-metrics.py
@@ -73,12 +73,10 @@ def Main():
publishResults = os.getenv("CIRCLE_BRANCH") == "main"
TriggerWorkflow(token, commit, publishResults)
- # These jobs need to be refactored into workflows.
if publishResults:
TriggerJob(token, commit, "android-navigation-benchmark")
- # "android-navigation-code-coverage" and "android-navigation-binary-size" are not no supported yet
- # TriggerJob(token, commit, "android-navigation-code-coverage")
- # TriggerJob(token, commit, "android-navigation-binary-size")
+ TriggerJob(token, commit, "android-navigation-code-coverage")
+ TriggerJob(token, commit, "android-navigation-binary-size")
else:
TriggerJob(token, commit, "android-navigation-code-coverage-ci")
TriggerJob(token, commit, "android-navigation-binary-size-ci")
|
Mobile metrics: enable binary size and code coverage
|
mapbox_mapbox-navigation-android
|
train
|
b564c4ca275112b98f0b4258c089cdd8fca89a73
|
diff --git a/lib/jwt/algos/ps.rb b/lib/jwt/algos/ps.rb
index <HASH>..<HASH> 100644
--- a/lib/jwt/algos/ps.rb
+++ b/lib/jwt/algos/ps.rb
@@ -18,7 +18,7 @@ module JWT
translated_algorithm = algorithm.sub('PS', 'sha')
- key.sign_pss(translated_algorithm, msg, salt_length: :max, mgf1_hash: translated_algorithm)
+ key.sign_pss(translated_algorithm, msg, salt_length: :digest, mgf1_hash: translated_algorithm)
end
def verify(to_verify)
|
Fix Salt length for conformance with PS<I>
|
jwt_ruby-jwt
|
train
|
6daf1661d77c2f89d77a73f817268a6f39a91e76
|
diff --git a/eval.js b/eval.js
index <HASH>..<HASH> 100644
--- a/eval.js
+++ b/eval.js
@@ -21,11 +21,11 @@ module.exports = function (content, filename, scope, includeGlobals) {
if (typeof filename === 'object') {
includeGlobals = scope
scope = filename
- filename = null
+ filename = ''
} else if (typeof filename === 'boolean') {
includeGlobals = filename
scope = {}
- filename = null
+ filename = ''
}
}
|
fix vm.Script usage on node@<I>
|
pierrec_node-eval
|
train
|
77299d3b138f8199023d631cc1eabe51cc74ede1
|
diff --git a/src/main/com/mongodb/BasicDBObject.java b/src/main/com/mongodb/BasicDBObject.java
index <HASH>..<HASH> 100644
--- a/src/main/com/mongodb/BasicDBObject.java
+++ b/src/main/com/mongodb/BasicDBObject.java
@@ -32,13 +32,16 @@ import com.mongodb.util.*;
*/
public class BasicDBObject extends HashMap<String,Object> implements DBObject {
- /** Creates an empty object. */
+ /**
+ * Creates an empty object.
+ */
public BasicDBObject(){
}
-
/**
* Convenience CTOR
+ * @param key key under which to store
+ * @param value value to stor
*/
public BasicDBObject(String key, Object value){
put(key, value);
@@ -64,7 +67,7 @@ public class BasicDBObject extends HashMap<String,Object> implements DBObject {
* @return if the field exists
*/
public boolean containsKey( String key ){
- return super.containsKey( (Object)key );
+ return super.containsKey(key);
}
/** Gets a value from this object
@@ -72,7 +75,7 @@ public class BasicDBObject extends HashMap<String,Object> implements DBObject {
* @return the value
*/
public Object get( String key ){
- return super.get( (Object)key );
+ return super.get(key);
}
/** Returns the value of a field as an <code>int</code>.
|
Javadoc and non-functional code cleanup
|
mongodb_mongo-java-driver
|
train
|
4da32942a162f423c8a72f13637e1f71ffd8265e
|
diff --git a/mockito/mockito.py b/mockito/mockito.py
index <HASH>..<HASH> 100644
--- a/mockito/mockito.py
+++ b/mockito/mockito.py
@@ -136,7 +136,6 @@ def verify(obj, times=1, atleast=None, atmost=None, between=None,
if inorder:
verification_fn = verification.InOrder(verification_fn)
- # FIXME?: Catch error if obj is neither a Mock nor a known stubbed obj
theMock = _get_mock_or_raise(obj)
class Verify(object):
|
Delete obsolete FIXME comment
|
kaste_mockito-python
|
train
|
9f7555ab259c1cb4ebab38f88a65b4e96e53475e
|
diff --git a/boing/main.py b/boing/main.py
index <HASH>..<HASH> 100644
--- a/boing/main.py
+++ b/boing/main.py
@@ -217,7 +217,11 @@ class Boing(object ):
self.prune_session_download_records()
self.prune_session_log_records()
self.prune_session_recordings()
+
+
+def main():
+ b = Boing()
+ b.main()
if __name__ == '__main__':
- b = Boing()
- b.main()
\ No newline at end of file
+ main()
\ No newline at end of file
|
Added main() to main.py
|
tonyrein_pogo
|
train
|
60686a1ccb8be886fe3963f4eb2e07d5ab41739a
|
diff --git a/src/main/java/com/librato/metrics/MultiSampleGaugeMeasurementBuilder.java b/src/main/java/com/librato/metrics/MultiSampleGaugeMeasurementBuilder.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/librato/metrics/MultiSampleGaugeMeasurementBuilder.java
+++ b/src/main/java/com/librato/metrics/MultiSampleGaugeMeasurementBuilder.java
@@ -1,5 +1,6 @@
package com.librato.metrics;
+import java.util.HashMap;
import java.util.Map;
public class MultiSampleGaugeMeasurementBuilder {
@@ -11,7 +12,7 @@ public class MultiSampleGaugeMeasurementBuilder {
private Number max;
private Number min;
private Number sumSquares;
- private Map<String, Object> metricAttributes;
+ private Map<String, Object> metricAttributes = new HashMap<String, Object>();
public MultiSampleGaugeMeasurementBuilder(String name) {
this.name = name;
diff --git a/src/test/java/com/librato/metrics/Gauge.java b/src/test/java/com/librato/metrics/Gauge.java
index <HASH>..<HASH> 100644
--- a/src/test/java/com/librato/metrics/Gauge.java
+++ b/src/test/java/com/librato/metrics/Gauge.java
@@ -16,6 +16,10 @@ public class Gauge {
Number value;
@JsonProperty
Map<String, Object> attributes = Collections.emptyMap();
+ @JsonProperty
+ Long count;
+ @JsonProperty
+ Number sum;
public Gauge() {
// jackson
@@ -75,9 +79,12 @@ public class Gauge {
Gauge gauge = (Gauge) o;
- if (source != null ? !source.equals(gauge.source) : gauge.source != null) return false;
- if (period != null ? !period.equals(gauge.period) : gauge.period != null) return false;
+ if (attributes != null ? !attributes.equals(gauge.attributes) : gauge.attributes != null) return false;
+ if (count != null ? !count.equals(gauge.count) : gauge.count != null) return false;
if (name != null ? !name.equals(gauge.name) : gauge.name != null) return false;
+ if (period != null ? !period.equals(gauge.period) : gauge.period != null) return false;
+ if (source != null ? !source.equals(gauge.source) : gauge.source != null) return false;
+ if (sum != null ? !sum.equals(gauge.sum) : gauge.sum != null) return false;
if (value != null ? !value.equals(gauge.value) : gauge.value != null) return false;
return true;
@@ -85,10 +92,13 @@ public class Gauge {
@Override
public int hashCode() {
- int result = name != null ? name.hashCode() : 0;
- result = 31 * result + (source != null ? source.hashCode() : 0);
+ int result = source != null ? source.hashCode() : 0;
result = 31 * result + (period != null ? period.hashCode() : 0);
+ result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (value != null ? value.hashCode() : 0);
+ result = 31 * result + (attributes != null ? attributes.hashCode() : 0);
+ result = 31 * result + (count != null ? count.hashCode() : 0);
+ result = 31 * result + (sum != null ? sum.hashCode() : 0);
return result;
}
diff --git a/src/test/java/com/librato/metrics/LibratoBatchTest.java b/src/test/java/com/librato/metrics/LibratoBatchTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/com/librato/metrics/LibratoBatchTest.java
+++ b/src/test/java/com/librato/metrics/LibratoBatchTest.java
@@ -170,6 +170,33 @@ public class LibratoBatchTest {
}
@Test
+ public void testPostsAnAggregatedMultiSampleGauge() throws Exception {
+ final Response response = new FakeResponse(200);
+ final Future<Response> future = ReturningFuture.of(response);
+ Mockito.when(poster.post(anyString(), anyString())).thenReturn(future);
+ final long epoch = System.currentTimeMillis();
+ final LibratoBatch batch = new LibratoBatch(1, Sanitizer.NO_OP, 1, TimeUnit.SECONDS, agent, poster);
+ batch.addMeasurement(MultiSampleGaugeMeasurement
+ .builder("farm")
+ .setCount(1L)
+ .setSum(50L)
+ .setMetricAttribute("aggregate", true) // add the metric attribute
+ .build());
+ batch.post(source, epoch);
+
+ ArgumentCaptor<String> payloadCapture = ArgumentCaptor.forClass(String.class);
+ Mockito.verify(poster).post(Matchers.eq("test-agent librato-java/unknown"), payloadCapture.capture());
+ final Payload payload = Payload.parse(payloadCapture.getValue());
+ assertEquals(source, payload.getSource());
+ assertEquals(0, payload.getCounters().size());
+ assertEquals(1, payload.getGauges().size());
+ Gauge gauge = payload.getGauges().iterator().next();
+ assertEquals(1, gauge.attributes.size());
+ assertEquals(true, gauge.attributes.get("aggregate"));
+ assertEquals(epoch, payload.getMeasureTime());
+ }
+
+ @Test
public void testPostsAnAggregatedCounter() throws Exception {
final Response response = new FakeResponse(200);
final Future<Response> future = ReturningFuture.of(response);
|
Add test for aggregated multi-sample gauge measurements
|
librato_librato-java
|
train
|
2ba6b0925b65e1a6934f9c5b83463be4273f0861
|
diff --git a/examples/bot-with-card-example-flask.py b/examples/bot-with-card-example-flask.py
index <HASH>..<HASH> 100755
--- a/examples/bot-with-card-example-flask.py
+++ b/examples/bot-with-card-example-flask.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""A simple bot script, built on Flask, that demonstrates posting a
card, and handling the events generated when a user hits the Submit button.
@@ -29,7 +29,7 @@ response to any messages it will post a simple form filling card. In response
to a user submitting a form, the details of that response will be posted in
the space.
-This script should support Python versions 3 only.
+This script should support Python versions 3.6+ only.
Copyright (c) 2016-2020 Cisco and/or its affiliates.
|
Update bot-with-card-example-flask.py
Use of f-strings means this example will only work with Python versions <I>+
|
CiscoDevNet_webexteamssdk
|
train
|
e836c2942336a3201895a2109e8896ef50dc86b5
|
diff --git a/server/lib/commands/content/contentClear.js b/server/lib/commands/content/contentClear.js
index <HASH>..<HASH> 100644
--- a/server/lib/commands/content/contentClear.js
+++ b/server/lib/commands/content/contentClear.js
@@ -5,6 +5,7 @@ const process = (context, action) => {
context.ui.apiBox.setContent('')
context.ui.reduxBox.setContent('')
context.ui.reduxActionBox.setContent('')
+ context.ui.reduxWatchBox.setContent('')
context.ui.screen.render()
}
diff --git a/server/lib/commands/content/contentScore.js b/server/lib/commands/content/contentScore.js
index <HASH>..<HASH> 100644
--- a/server/lib/commands/content/contentScore.js
+++ b/server/lib/commands/content/contentScore.js
@@ -6,6 +6,7 @@ const process = (context, action) => {
context.ui.apiBox.log(SCORE)
context.ui.reduxBox.log(SCORE)
context.ui.reduxActionBox.log(SCORE)
+ context.ui.reduxWatchBox.log(SCORE)
context.ui.screen.render()
}
|
Adds score & clear to the new reduxWatchBox.
|
infinitered_reactotron
|
train
|
9a5bd6d6c8a2f8284de8806c03a3dc07e2a89946
|
diff --git a/examples/breadcrumbs/src/index.js b/examples/breadcrumbs/src/index.js
index <HASH>..<HASH> 100644
--- a/examples/breadcrumbs/src/index.js
+++ b/examples/breadcrumbs/src/index.js
@@ -15,13 +15,13 @@ import renderFunction from './renderFunction';
* a string. This is most likely route params, but you can pass
* an object containing any values that you want.
*/
-function createTitleAddon() {
+function createTitleTextAddon() {
let routes = {};
return {
name: 'title',
register: (route) => {
- let { name, title } = route;
- routes[name] = title;
+ let { name, extra } = route;
+ routes[name] = extra && extra.title;
},
get: (name, params) => {
const titleFn = routes[name];
@@ -36,7 +36,7 @@ function createTitleAddon() {
const history = Browser();
const config = createConfig(history, routes, {
- addons: [createAncestorsAddon(), createTitleAddon()]
+ addons: [createAncestorsAddon(), createTitleTextAddon()]
});
ReactDOM.render((
diff --git a/examples/breadcrumbs/src/routes.js b/examples/breadcrumbs/src/routes.js
index <HASH>..<HASH> 100644
--- a/examples/breadcrumbs/src/routes.js
+++ b/examples/breadcrumbs/src/routes.js
@@ -34,7 +34,9 @@ export default [
}
mods.setData(products);
},
- title: (params) => `${params.category || 'Category'}`,
+ extra: {
+ title: (params) => `${params.category || 'Category'}`
+ },
children: [
{
name: 'Product',
@@ -47,7 +49,9 @@ export default [
}
mods.setData(product);
},
- title: (params) => `${params.name || 'Product'}`
+ extra: {
+ title: (params) => `${params.name || 'Product'}`
+ }
}
]
}
|
(examples) Use route.extra in breadcrumbs [ci skip]
|
pshrmn_curi
|
train
|
e89aa9c84c5714f7a8bd8c30cc263b741d8c74c6
|
diff --git a/lib/client.js b/lib/client.js
index <HASH>..<HASH> 100644
--- a/lib/client.js
+++ b/lib/client.js
@@ -44,14 +44,14 @@ p.connect = function() {
});
con.on('authenticationCleartextPassword', function() {
- con.passwordMessage(self.password);
+ con.password(self.password);
});
con.on('authenticationMD5Password', function(msg) {
var inner = Client.md5(self.password + self.user);
var outer = Client.md5(inner + msg.salt.toString('binary'));
var md5password = "md5" + outer;
- con.passwordMessage(md5password);
+ con.password(md5password);
});
};
diff --git a/lib/connection.js b/lib/connection.js
index <HASH>..<HASH> 100644
--- a/lib/connection.js
+++ b/lib/connection.js
@@ -59,7 +59,7 @@ p.startupMessage = function(config) {
this.send(false, buffer.join());
};
-p.passwordMessage = function(password) {
+p.password = function(password) {
this.send('p', Buffer(password + '\0', this.encoding));
};
diff --git a/test/integration/connection/cleartext-password-tests.js b/test/integration/connection/cleartext-password-tests.js
index <HASH>..<HASH> 100644
--- a/test/integration/connection/cleartext-password-tests.js
+++ b/test/integration/connection/cleartext-password-tests.js
@@ -2,7 +2,7 @@ var helper = require(__dirname + '/test-helper');
test('can log in with clear text password', function() {
helper.authConnect('user_pw', 'postgres', function(con) {
assert.raises(con, 'authenticationCleartextPassword', function() {
- con.passwordMessage('pass');
+ con.password('pass');
});
assert.raises(con, 'readyForQuery', function() {
con.end();
diff --git a/test/integration/connection/md5-password-tests.js b/test/integration/connection/md5-password-tests.js
index <HASH>..<HASH> 100644
--- a/test/integration/connection/md5-password-tests.js
+++ b/test/integration/connection/md5-password-tests.js
@@ -7,7 +7,7 @@ test('can log in with md5 password', function() {
assert.ok(msg.salt);
var enc = Client.md5('ssap' + 'user_md5');
enc = Client.md5(enc + msg.salt.toString('binary'));
- con.passwordMessage('md5'+enc);
+ con.password('md5'+enc);
});
assert.raises(con, 'readyForQuery', function() {
con.end();
diff --git a/test/unit/connection/outbound-sending-tests.js b/test/unit/connection/outbound-sending-tests.js
index <HASH>..<HASH> 100644
--- a/test/unit/connection/outbound-sending-tests.js
+++ b/test/unit/connection/outbound-sending-tests.js
@@ -25,8 +25,8 @@ test("sends startup message", function() {
.addCString('').join(true))
});
-test('sends passwordMessage', function() {
- con.passwordMessage("!");
+test('sends password message', function() {
+ con.password("!");
assert.recieved(stream, new BufferList().addCString("!").join(true,'p'));
});
|
changed Connection#passwordMessage to Connection#password
|
brianc_node-postgres
|
train
|
1cab8eda24e70c60061e34adc4a19c1aeb5ad90c
|
diff --git a/daemon/network.go b/daemon/network.go
index <HASH>..<HASH> 100644
--- a/daemon/network.go
+++ b/daemon/network.go
@@ -365,7 +365,7 @@ func (daemon *Daemon) createNetwork(create types.NetworkCreateRequest, id string
n, err := c.NewNetwork(driver, create.Name, id, nwOptions...)
if err != nil {
if _, ok := err.(libnetwork.ErrDataStoreNotInitialized); ok {
- //nolint: golint
+ //nolint: revive
return nil, errors.New("This node is not a swarm manager. Use \"docker swarm init\" or \"docker swarm join\" to connect this node to swarm and try again.")
}
return nil, err
diff --git a/hack/validate/golangci-lint.yml b/hack/validate/golangci-lint.yml
index <HASH>..<HASH> 100644
--- a/hack/validate/golangci-lint.yml
+++ b/hack/validate/golangci-lint.yml
@@ -3,12 +3,12 @@ linters:
- deadcode
- depguard
- goimports
- - golint
- gosec
- gosimple
- govet
- ineffassign
- misspell
+ - revive
- staticcheck
- structcheck
- typecheck
@@ -55,10 +55,6 @@ issues:
- text: "Error return value of .((os\\.)?std(out|err)\\..*|.*Close|.*Flush|os\\.Remove(All)?|.*print(f|ln)?|os\\.(Un)?Setenv). is not checked"
linters:
- errcheck
- # EXC0003
- - text: "func name will be used as test\\.Test.* by other packages, and that stutters; consider calling this"
- linters:
- - golint
# EXC0006
- text: "Use of unsafe calls should be audited"
linters:
@@ -102,7 +98,7 @@ issues:
- text: "type name will be used as (container|volume)\\.(Container|Volume).* by other packages, and that stutters; consider calling this"
path: "api/types/(volume|container)/"
linters:
- - golint
+ - revive
# FIXME temporarily suppress these. See #39924
- text: "SA1019: .*\\.Xattrs has been deprecated since Go 1.10: Use PAXRecords instead"
linters:
diff --git a/integration/internal/network/network.go b/integration/internal/network/network.go
index <HASH>..<HASH> 100644
--- a/integration/internal/network/network.go
+++ b/integration/internal/network/network.go
@@ -26,7 +26,7 @@ func Create(ctx context.Context, client client.APIClient, name string, ops ...fu
}
// CreateNoError creates a network with the specified options and verifies there were no errors
-func CreateNoError(ctx context.Context, t *testing.T, client client.APIClient, name string, ops ...func(*types.NetworkCreate)) string { //nolint: golint
+func CreateNoError(ctx context.Context, t *testing.T, client client.APIClient, name string, ops ...func(*types.NetworkCreate)) string {
t.Helper()
name, err := createNetwork(ctx, client, name, ops...)
|
replace golint with revive, as it's deprecated
WARN [runner] The linter 'golint' is deprecated (since <I>) due to: The repository of the linter has been archived by the owner. Replaced by revive.
|
moby_moby
|
train
|
e4ab0531c4e44c23494c6a802aa2329d15ac90e5
|
diff --git a/docs/rules/valid-typeof.md b/docs/rules/valid-typeof.md
index <HASH>..<HASH> 100644
--- a/docs/rules/valid-typeof.md
+++ b/docs/rules/valid-typeof.md
@@ -1,6 +1,6 @@
# enforce comparing `typeof` expressions against valid strings (valid-typeof)
-For a vast majority of use cases, the result of the `typeof` operator is one of the following string literals: `"undefined"`, `"object"`, `"boolean"`, `"number"`, `"string"`, `"function"` and `"symbol"`. It is usually a typing mistake to compare the result of a `typeof` operator to other string literals.
+For a vast majority of use cases, the result of the `typeof` operator is one of the following string literals: `"undefined"`, `"object"`, `"boolean"`, `"number"`, `"string"`, `"function"`, `"symbol"`, and `"bigint"`. It is usually a typing mistake to compare the result of a `typeof` operator to other string literals.
## Rule Details
@@ -57,3 +57,7 @@ typeof bar === typeof qux
## When Not To Use It
You may want to turn this rule off if you will be using the `typeof` operator on host objects.
+
+## Further Reading
+
+* [MDN: `typeof` documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof)
diff --git a/lib/rules/valid-typeof.js b/lib/rules/valid-typeof.js
index <HASH>..<HASH> 100644
--- a/lib/rules/valid-typeof.js
+++ b/lib/rules/valid-typeof.js
@@ -39,7 +39,7 @@ module.exports = {
create(context) {
- const VALID_TYPES = ["symbol", "undefined", "object", "boolean", "number", "string", "function"],
+ const VALID_TYPES = ["symbol", "undefined", "object", "boolean", "number", "string", "function", "bigint"],
OPERATORS = ["==", "===", "!=", "!=="];
const requireStringLiterals = context.options[0] && context.options[0].requireStringLiterals;
diff --git a/tests/lib/rules/valid-typeof.js b/tests/lib/rules/valid-typeof.js
index <HASH>..<HASH> 100644
--- a/tests/lib/rules/valid-typeof.js
+++ b/tests/lib/rules/valid-typeof.js
@@ -26,6 +26,7 @@ ruleTester.run("valid-typeof", rule, {
"typeof foo === 'undefined'",
"typeof foo === 'boolean'",
"typeof foo === 'number'",
+ "typeof foo === 'bigint'",
"'string' === typeof foo",
"'object' === typeof foo",
"'function' === typeof foo",
|
Update: support "bigint" in valid-typeof rule (#<I>)
* Update: support "bigint" in valid-typeof rule
BigInt just moved to Stage 4, so add support for it to
the valid-typeof rule.
* Docs: add Further Reading to valid-typeof rule
This commit adds a Further Reading section to the
valid-typeof rule documentation.
|
eslint_eslint
|
train
|
41ec04a2a440bdee972eebc76efdf657655ee0e9
|
diff --git a/lib/lebowski/foundation/mixins/positioned_element.rb b/lib/lebowski/foundation/mixins/positioned_element.rb
index <HASH>..<HASH> 100644
--- a/lib/lebowski/foundation/mixins/positioned_element.rb
+++ b/lib/lebowski/foundation/mixins/positioned_element.rb
@@ -16,6 +16,17 @@ module Lebowski
return 0
end
+ def position_relative_to(obj)
+ if not obj.kind_of? PositionedElement
+ raise ArgumentInvalidTypeError.new "obj", obj, PositionedElement
+ end
+
+ x = position.x - obj.position.x
+ y = position.y - obj.position.y
+
+ return Coords.new(x, y)
+ end
+
def scroll_to_visible()
end
|
Added method position_relative_to to the PositionedElement mixin
|
FrozenCanuck_Lebowski
|
train
|
890c166bd086e4fbd4ba61bad72e2687020ce8fe
|
diff --git a/lib/coolie/worker.rb b/lib/coolie/worker.rb
index <HASH>..<HASH> 100644
--- a/lib/coolie/worker.rb
+++ b/lib/coolie/worker.rb
@@ -13,7 +13,11 @@ module Coolie
loop do
break if stopped?
- perform_job
+ begin
+ perform_job
+ rescue Exception
+ # Ignore
+ end
end
exit 0
@@ -28,9 +32,6 @@ module Coolie
@output.write UNCAUGHT_ERROR unless status.success? || stopped?
rescue Errno::EAGAIN, Errno::EINTR
# Ignore
- rescue Exception => e
- puts e
- raise
end
else
self.process_name = "Child of worker #{Process.ppid}"
|
Making sure the worker never raises when performing
|
rbgrouleff_sisyphus
|
train
|
246eed2f10de1cd32b871ad5b383f34819e40c0c
|
diff --git a/rundeckapp/web-app/js/workflow.js b/rundeckapp/web-app/js/workflow.js
index <HASH>..<HASH> 100644
--- a/rundeckapp/web-app/js/workflow.js
+++ b/rundeckapp/web-app/js/workflow.js
@@ -71,7 +71,9 @@ var RDWorkflow = Class.create({
var string = "";
var step = this.workflow[this.workflowIndexForContextId(ctx[0])];
if (typeof(step) != 'undefined') {
- if (step['exec']) {
+ if(step['description']){
+ string+=step['description'];
+ }else if (step['exec']) {
// string+=' $ '+step['exec'];
string += 'Command';
} else if (step['jobref']) {
|
Use step description in workflow javascript
|
rundeck_rundeck
|
train
|
a8f168ebb17a12cca5b841a49fdbedb700bf3cdd
|
diff --git a/Client/RestClient.php b/Client/RestClient.php
index <HASH>..<HASH> 100644
--- a/Client/RestClient.php
+++ b/Client/RestClient.php
@@ -147,7 +147,7 @@ class RestClient
* @return GuzzleRequest
* @throws UserException
*/
- protected function getGuzzleRequest(RestRequest $request)
+ public function getGuzzleRequest(RestRequest $request)
{
switch ($request->getMethod()) {
case 'GET':
|
fix: need getGuzzleRequest public in gex
|
keboola_juicer
|
train
|
e95001bf3c9c8bb76286949b12e5bdbb31f71080
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -29,6 +29,11 @@ pkgversion = couchbase_version.get_version()
LCB_NAME = None
if sys.platform != 'win32':
extoptions['libraries'] = ['couchbase']
+ if sys.platform == 'darwin' and sys.executable == '/usr/bin/python':
+ warnings.warn("Compiling on Mac Python. Using homebrew's Python is strongly recommended. Manually adding /usr/local prefix")
+ # Forcefully add library_dirs and include_dirs:
+ extoptions['library_dirs'] = ['/usr/local/lib']
+ extoptions['include_dirs'] = ['/usr/local/include']
else:
warnings.warn("I'm detecting you're running windows."
"You might want to modify "
|
Manually add /usr/local when Apple's python is being used.
Change-Id: I8dc5fab<I>cdaf<I>e<I>cef4ba7a<I>a<I>ade6
Reviewed-on: <URL>
|
couchbase_couchbase-python-client
|
train
|
20df6147ad7eb33fc2dd7f521985c698d2feb83a
|
diff --git a/lib/travis/services/find_repos.rb b/lib/travis/services/find_repos.rb
index <HASH>..<HASH> 100644
--- a/lib/travis/services/find_repos.rb
+++ b/lib/travis/services/find_repos.rb
@@ -18,7 +18,8 @@ module Travis
end
def by_params
- scope = self.scope(:repository).timeline.recent
+ scope = self.scope(:repository)
+ scope = scope.timeline.recent if timeline?
scope = scope.by_member(params[:member]) if params[:member]
scope = scope.by_owner_name(params[:owner_name]) if params[:owner_name]
scope = scope.by_slug(params[:slug]) if params[:slug]
@@ -31,6 +32,10 @@ module Travis
scope
end
+
+ def timeline?
+ not [:member, :owner_name, :slug, :search].any? { |key| params[key] }
+ end
end
end
end
|
only use the timeline scope unless other params are present
|
travis-ci_travis-core
|
train
|
c0fb93008aebcfa203b616e8cc9bcf3bcc5c8b78
|
diff --git a/h2o-extensions/xgboost/src/main/java/hex/tree/xgboost/rabit/RabitTrackerH2O.java b/h2o-extensions/xgboost/src/main/java/hex/tree/xgboost/rabit/RabitTrackerH2O.java
index <HASH>..<HASH> 100644
--- a/h2o-extensions/xgboost/src/main/java/hex/tree/xgboost/rabit/RabitTrackerH2O.java
+++ b/h2o-extensions/xgboost/src/main/java/hex/tree/xgboost/rabit/RabitTrackerH2O.java
@@ -30,7 +30,6 @@ public class RabitTrackerH2O implements IRabitTracker {
}
this.workers = workers;
-
Log.debug("Rabit tracker started on port ", this.port);
}
@@ -57,6 +56,11 @@ public class RabitTrackerH2O implements IRabitTracker {
tryToBind = false;
} catch (java.io.IOException e) {
this.port++;
+ try {
+ this.sock.close();
+ } catch (IOException socketCloseException) {
+ Log.warn("Failed to close Rabit Tracker socket on port ", sock.socket().getLocalPort());
+ }
if(this.port > 9999) {
throw new RuntimeException("Failed to bind Rabit tracker to a socket in range 9091-9999", e);
}
@@ -77,7 +81,9 @@ public class RabitTrackerH2O implements IRabitTracker {
public void stop() {
if(null != this.trackerThread) {
this.trackerThread.interrupt();
+ this.trackerThread.terminateSocketChannels();
this.trackerThread = null;
+
try {
this.sock.close();
} catch (IOException e) {
@@ -93,6 +99,7 @@ public class RabitTrackerH2O implements IRabitTracker {
private LinkMap linkMap;
private Map<String, Integer> jobToRankMap = new HashMap<>();
+ private final List<SocketChannel> socketChannels = new ArrayList<>();
private RabitTrackerH2OThread(RabitTrackerH2O tracker) {
setPriority(MAX_PRIORITY-1);
@@ -100,6 +107,16 @@ public class RabitTrackerH2O implements IRabitTracker {
this.tracker = tracker;
}
+ private final void terminateSocketChannels(){
+ for (SocketChannel channel : socketChannels) {
+ try {
+ channel.close();
+ } catch (IOException e) {
+ Log.warn("Unable to close RabitTracerH2O SocketChannel on port ", channel.socket().getPort());
+ }
+ }
+ }
+
private static final String PRINT_CMD = "print";
private static final String SHUTDOWN_CMD = "shutdown";
private static final String START_CMD = "start";
@@ -113,9 +130,10 @@ public class RabitTrackerH2O implements IRabitTracker {
List<RabitWorker> pending = new ArrayList<>();
Queue<Integer> todoNodes = new ArrayDeque<>(tracker.workers);
while (!interrupted() && shutdown.size() != tracker.workers) {
- try {
- SocketChannel channel = tracker.sock.accept();
- RabitWorker worker = new RabitWorker(channel);
+ try{
+ final SocketChannel channel = tracker.sock.accept(); // Does not proceed when interrupt() is called.
+ socketChannels.add(channel);
+ final RabitWorker worker = new RabitWorker(channel);
if (PRINT_CMD.equals(worker.cmd)) {
String msg = worker.receiver().getStr();
@@ -125,6 +143,7 @@ public class RabitTrackerH2O implements IRabitTracker {
assert worker.rank >= 0 && !shutdown.contains(worker.rank);
assert !waitConn.containsKey(worker);
shutdown.add(worker.rank);
+ channel.socket().close();
Log.debug("Received ", worker.cmd, " signal from ", worker.rank);
continue;
}
@@ -177,7 +196,7 @@ public class RabitTrackerH2O implements IRabitTracker {
}
}
} catch (IOException e) {
- Log.debug("Exception in Rabit tracker.", e);
+ Log.err("Exception in Rabit tracker.", e);
}
}
Log.debug("All Rabit nodes finished.");
|
PUBDEV-<I> - Closing Rabit connection after communication ends (#<I>)
* PUBDEV-<I> - Closing Rabit connection after communication ends
* Overridden interrupt() method of RabitTrackerH2OThread calls super.interrupt()
* Move socketChannel cleanup logic to RabitTracker's stop method.
* Log level of RabitTracker's startup exception changed from info to err.
|
h2oai_h2o-3
|
train
|
812d2171b2e76eb7101d58000be1d0dfb42f499e
|
diff --git a/lib/CodeCooker/Generator/DtoGenerator.php b/lib/CodeCooker/Generator/DtoGenerator.php
index <HASH>..<HASH> 100644
--- a/lib/CodeCooker/Generator/DtoGenerator.php
+++ b/lib/CodeCooker/Generator/DtoGenerator.php
@@ -426,6 +426,18 @@ class DtoGenerator
}
break;
+ case 'array':
+ // TODO: Implement proper SQL to Object mapping.
+ if ($type->allowsNull()) {
+ $w->writeln("\$t->$propertyName = isset(\$source[%s])"
+ . " ? (is_string(\$source[%s]) ? json_decode(\$source[%s], TRUE) : \$source[%s])"
+ . " : null;", $propertyName, $propertyName, $propertyName, $propertyName);
+ } else {
+ $w->writeln("\$t->$propertyName = is_string(\$source[%s]) ? json_decode(\$source[%s], TRUE) : (array) \$source[%s];",
+ $propertyName, $propertyName, $propertyName);
+ }
+ break;
+
default:
if ($typehint && class_exists($typehint)) {
$c = $w->useClass($typehint);
diff --git a/test/Example/SupervisorProcess/SupervisorProcessData/SupervisorProcessDataImmutable.php b/test/Example/SupervisorProcess/SupervisorProcessData/SupervisorProcessDataImmutable.php
index <HASH>..<HASH> 100644
--- a/test/Example/SupervisorProcess/SupervisorProcessData/SupervisorProcessDataImmutable.php
+++ b/test/Example/SupervisorProcess/SupervisorProcessData/SupervisorProcessDataImmutable.php
@@ -55,7 +55,7 @@ class SupervisorProcessDataImmutable extends Source_SupervisorProcessProperties
$t->createdAt = ($v = $source['createdAt'] ?? null) instanceof DateTimeImmutable || $v === null ? $v : new DateTimeImmutable($v);
$t->modifiedAt = ($v = $source['modifiedAt'] ?? null) instanceof DateTimeImmutable || $v === null ? $v : new DateTimeImmutable($v);
$t->memoryLimit = isset($source['memoryLimit']) ? (int) $source['memoryLimit'] : null;
- $t->args = $source['args'] ?? null;
+ $t->args = isset($source['args']) ? (is_string($source['args']) ? json_decode($source['args'], TRUE) : $source['args']) : null;
return $t;
}
diff --git a/test/Example/SupervisorProcess/SupervisorProcessData/SupervisorProcessDataMutable.php b/test/Example/SupervisorProcess/SupervisorProcessData/SupervisorProcessDataMutable.php
index <HASH>..<HASH> 100644
--- a/test/Example/SupervisorProcess/SupervisorProcessData/SupervisorProcessDataMutable.php
+++ b/test/Example/SupervisorProcess/SupervisorProcessData/SupervisorProcessDataMutable.php
@@ -55,7 +55,7 @@ class SupervisorProcessDataMutable extends Source_SupervisorProcessProperties im
$t->createdAt = ($v = $source['createdAt'] ?? null) instanceof DateTimeImmutable || $v === null ? $v : new DateTimeImmutable($v);
$t->modifiedAt = ($v = $source['modifiedAt'] ?? null) instanceof DateTimeImmutable || $v === null ? $v : new DateTimeImmutable($v);
$t->memoryLimit = isset($source['memoryLimit']) ? (int) $source['memoryLimit'] : null;
- $t->args = $source['args'] ?? null;
+ $t->args = isset($source['args']) ? (is_string($source['args']) ? json_decode($source['args'], TRUE) : $source['args']) : null;
return $t;
}
diff --git a/test/Example/User/UserData/UserDataImmutable.php b/test/Example/User/UserData/UserDataImmutable.php
index <HASH>..<HASH> 100644
--- a/test/Example/User/UserData/UserDataImmutable.php
+++ b/test/Example/User/UserData/UserDataImmutable.php
@@ -51,7 +51,7 @@ class UserDataImmutable extends Source_UserProperties implements UserData
$t->username = (string) $source['username'];
$t->email = (string) $source['email'];
$t->password = (string) $source['password'];
- $t->roles = $source['roles'] ?? null;
+ $t->roles = is_string($source['roles']) ? json_decode($source['roles'], TRUE) : (array) $source['roles'];
return $t;
}
diff --git a/test/Example/User/UserData/UserDataMutable.php b/test/Example/User/UserData/UserDataMutable.php
index <HASH>..<HASH> 100644
--- a/test/Example/User/UserData/UserDataMutable.php
+++ b/test/Example/User/UserData/UserDataMutable.php
@@ -51,7 +51,7 @@ class UserDataMutable extends Source_UserProperties implements UserData
$t->username = (string) $source['username'];
$t->email = (string) $source['email'];
$t->password = (string) $source['password'];
- $t->roles = $source['roles'] ?? null;
+ $t->roles = is_string($source['roles']) ? json_decode($source['roles'], TRUE) : (array) $source['roles'];
return $t;
}
|
DtoGenerator: Temporarily treat string to array conversion as JSON deserialization
|
smalldb_libSmalldb
|
train
|
bac1570fe911334f46b9b806b11fa93e85db601f
|
diff --git a/mu/ghu-loader.php b/mu/ghu-loader.php
index <HASH>..<HASH> 100644
--- a/mu/ghu-loader.php
+++ b/mu/ghu-loader.php
@@ -34,3 +34,6 @@ function ghu_deactivate() {
//deactivate normal plugin as it's loaded as mu-plugin
add_action( 'admin_init', 'ghu_deactivate' );
+//remove links from plugins.php so user can't delete main plugin
+add_filter( 'network_admin_plugin_action_links_github-updater/github-updater.php', '__return_false' );
+add_filter( 'plugin_action_links_github-updater/github-updater.php', '__return_false' );
\ No newline at end of file
|
remove links so can't activate/delete/etc
|
afragen_github-updater
|
train
|
acdee3c1b779313a0676f0ac1c322359bd5069bd
|
diff --git a/lang/nl/lang.php b/lang/nl/lang.php
index <HASH>..<HASH> 100644
--- a/lang/nl/lang.php
+++ b/lang/nl/lang.php
@@ -108,6 +108,8 @@ return [
'code_param_desc' => 'De pagina URL parameter die gebruikt wordt voor de registratie activatie code.',
'invalid_activation_code' => 'Onjuiste activatie code',
'invalid_user' => 'Geen gebruiker gevonden.',
+ 'invalid_deactivation_pass' => 'Het ingevoerde wachtwoord is ongelding.',
+ 'invalid_current_pass' => 'Het ingevoerde huidige wachtwoord is ongeldig.',
'success_activation' => 'Uw account is succesvol geactiveerd.',
'success_saved' => 'Instellingen zijn opgeslagen.',
'login_first' => 'U moet ingelogd zijn om deze pagina te bekijken.',
|
Update Dutch translations (#<I>)
|
rainlab_user-plugin
|
train
|
c91c9ec802ab81bdac510499975c7da9b83cc6f7
|
diff --git a/lib/access_control_config.py b/lib/access_control_config.py
index <HASH>..<HASH> 100644
--- a/lib/access_control_config.py
+++ b/lib/access_control_config.py
@@ -163,6 +163,8 @@ DEF_ACTIONS = (
('viewcomment', 'view comments', 'collection', 'no'),
('sendcomment', 'send comments', 'collection', 'no'),
('attachcommentfile', 'attach files to comments', 'collection', 'no'),
+ ('cfgbibexport', 'configure BibExport', '', 'no'),
+ ('runbibexport', 'run BibExport', '', 'no'),
)
# Default authorizations
|
Preliminary release of the BibExport module, featuring general
infrastructure and the 'sitemap' and 'googlescholar' export methods.
The sitemap export method was written by Gregory Favre and is slightly
modified here (collection name quoting). There are several FIXMEs
left for parts that still need completion, to come within a few days.
The skeleton is ready to host the Google Scholar output method.
|
inveniosoftware_invenio-access
|
train
|
42cebcfe2bb48461613e9d61aa73ef484962250a
|
diff --git a/rpcserver.go b/rpcserver.go
index <HASH>..<HASH> 100644
--- a/rpcserver.go
+++ b/rpcserver.go
@@ -3804,8 +3804,6 @@ func (r *rpcServer) ListChannels(ctx context.Context,
resp := &lnrpc.ListChannelsResponse{}
- graph := r.server.graphDB
-
dbChannels, err := r.server.chanStateDB.FetchAllOpenChannels()
if err != nil {
return nil, err
@@ -3842,7 +3840,7 @@ func (r *rpcServer) ListChannels(ctx context.Context,
// Next, we'll determine whether we should add this channel to
// our list depending on the type of channels requested to us.
isActive := peerOnline && linkActive
- channel, err := createRPCOpenChannel(r, graph, dbChannel, isActive)
+ channel, err := createRPCOpenChannel(r, dbChannel, isActive)
if err != nil {
return nil, err
}
@@ -3903,8 +3901,8 @@ func createChannelConstraint(
}
// createRPCOpenChannel creates an *lnrpc.Channel from the *channeldb.Channel.
-func createRPCOpenChannel(r *rpcServer, graph *channeldb.ChannelGraph,
- dbChannel *channeldb.OpenChannel, isActive bool) (*lnrpc.Channel, error) {
+func createRPCOpenChannel(r *rpcServer, dbChannel *channeldb.OpenChannel,
+ isActive bool) (*lnrpc.Channel, error) {
nodePub := dbChannel.IdentityPub
nodeID := hex.EncodeToString(nodePub.SerializeCompressed())
@@ -4330,8 +4328,6 @@ func (r *rpcServer) SubscribeChannelEvents(req *lnrpc.ChannelEventSubscription,
// the server, or client exits.
defer channelEventSub.Cancel()
- graph := r.server.graphDB
-
for {
select {
// A new update has been sent by the channel router, we'll
@@ -4351,8 +4347,9 @@ func (r *rpcServer) SubscribeChannelEvents(req *lnrpc.ChannelEventSubscription,
},
}
case channelnotifier.OpenChannelEvent:
- channel, err := createRPCOpenChannel(r, graph,
- event.Channel, true)
+ channel, err := createRPCOpenChannel(
+ r, event.Channel, true,
+ )
if err != nil {
return err
}
|
lnd: remove unused graph param from createRPCOpenChannel
|
lightningnetwork_lnd
|
train
|
a3e353622a979ff3a42a6eb972fb287e5d60a645
|
diff --git a/src/PessimisticLock.php b/src/PessimisticLock.php
index <HASH>..<HASH> 100644
--- a/src/PessimisticLock.php
+++ b/src/PessimisticLock.php
@@ -161,4 +161,12 @@ class PessimisticLock
$this->collection->createIndex(['sessionId' => 1], ['unique' => false, 'name' => 'sessionId']);
}
}
+
+ /**
+ * @return Collection
+ */
+ public function getCollection(): Collection
+ {
+ return $this->collection;
+ }
}
|
add getter for lock's collection.
|
formapro_yadm
|
train
|
bd66235ecfbf4a8dad9c384ff6947f8bc6b685ac
|
diff --git a/provider/azure/environ.go b/provider/azure/environ.go
index <HASH>..<HASH> 100644
--- a/provider/azure/environ.go
+++ b/provider/azure/environ.go
@@ -1302,3 +1302,11 @@ func (env *azureEnviron) SupportsUnitPlacement() error {
}
return nil
}
+
+func getCustomImageSource(env environs.Environ) (simplestreams.DataSource, error) {
+ _, ok := env.(*azureEnviron)
+ if !ok {
+ return nil, errors.NotSupportedf("non-azure environment")
+ }
+ return common.GetCustomImageSource(env)
+}
diff --git a/provider/azure/init.go b/provider/azure/init.go
index <HASH>..<HASH> 100644
--- a/provider/azure/init.go
+++ b/provider/azure/init.go
@@ -19,5 +19,5 @@ func init() {
registry.RegisterEnvironStorageProviders(providerType)
// Register cloud local storage as data source
- environs.RegisterImageDataSourceFunc(common.CloudLocalStorageDesc, common.GetCustomImageSource)
+ environs.RegisterImageDataSourceFunc(common.CloudLocalStorageDesc, getCustomImageSource)
}
diff --git a/provider/ec2/environ.go b/provider/ec2/environ.go
index <HASH>..<HASH> 100644
--- a/provider/ec2/environ.go
+++ b/provider/ec2/environ.go
@@ -1298,6 +1298,14 @@ func (e *environ) ensureGroup(name string, perms []ec2.IPPerm) (g ec2.SecurityGr
return g, nil
}
+func getCustomImageSource(env environs.Environ) (simplestreams.DataSource, error) {
+ _, ok := env.(*environ)
+ if !ok {
+ return nil, errors.NotSupportedf("non-ec2 environment")
+ }
+ return common.GetCustomImageSource(env)
+}
+
// permKey represents a permission for a group or an ip address range
// to access the given range of ports. Only one of groupName or ipAddr
// should be non-empty.
diff --git a/provider/ec2/init.go b/provider/ec2/init.go
index <HASH>..<HASH> 100644
--- a/provider/ec2/init.go
+++ b/provider/ec2/init.go
@@ -23,5 +23,5 @@ func init() {
registry.RegisterEnvironStorageProviders(providerType, EBS_ProviderType)
// Register cloud local storage as data source
- environs.RegisterImageDataSourceFunc(common.CloudLocalStorageDesc, common.GetCustomImageSource)
+ environs.RegisterImageDataSourceFunc(common.CloudLocalStorageDesc, getCustomImageSource)
}
diff --git a/provider/joyent/environ.go b/provider/joyent/environ.go
index <HASH>..<HASH> 100644
--- a/provider/joyent/environ.go
+++ b/provider/joyent/environ.go
@@ -182,3 +182,11 @@ func (env *joyentEnviron) Region() (simplestreams.CloudSpec, error) {
Endpoint: env.Ecfg().sdcUrl(),
}, nil
}
+
+func getCustomImageSource(env environs.Environ) (simplestreams.DataSource, error) {
+ _, ok := env.(*joyentEnviron)
+ if !ok {
+ return nil, errors.NotSupportedf("non-joyent environment")
+ }
+ return common.GetCustomImageSource(env)
+}
diff --git a/provider/joyent/init.go b/provider/joyent/init.go
index <HASH>..<HASH> 100644
--- a/provider/joyent/init.go
+++ b/provider/joyent/init.go
@@ -19,5 +19,5 @@ func init() {
registry.RegisterEnvironStorageProviders(providerType)
// Register cloud local storage as data source
- environs.RegisterImageDataSourceFunc(common.CloudLocalStorageDesc, common.GetCustomImageSource)
+ environs.RegisterImageDataSourceFunc(common.CloudLocalStorageDesc, getCustomImageSource)
}
diff --git a/provider/openstack/init.go b/provider/openstack/init.go
index <HASH>..<HASH> 100644
--- a/provider/openstack/init.go
+++ b/provider/openstack/init.go
@@ -18,7 +18,7 @@ func init() {
environs.RegisterProvider(providerType, environProvider{})
// Register cloud local storage as data source
- environs.RegisterImageDataSourceFunc(common.CloudLocalStorageDesc, common.GetCustomImageSource)
+ environs.RegisterImageDataSourceFunc(common.CloudLocalStorageDesc, getCustomImageSource)
environs.RegisterImageDataSourceFunc("keystone catalog", getKeystoneImageSource)
tools.RegisterToolsDataSourceFunc("keystone catalog", getKeystoneToolsSource)
diff --git a/provider/openstack/provider.go b/provider/openstack/provider.go
index <HASH>..<HASH> 100644
--- a/provider/openstack/provider.go
+++ b/provider/openstack/provider.go
@@ -1657,3 +1657,11 @@ func (e *environ) cloudSpec(region string) (simplestreams.CloudSpec, error) {
Endpoint: e.ecfg().authURL(),
}, nil
}
+
+func getCustomImageSource(env environs.Environ) (simplestreams.DataSource, error) {
+ _, ok := env.(*environ)
+ if !ok {
+ return nil, errors.NotSupportedf("non-openstack environment")
+ }
+ return common.GetCustomImageSource(env)
+}
|
Added environment specific data source registration.
|
juju_juju
|
train
|
b54ed1c9a9b66f8b18bf552d759636d6a14299cc
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -19,7 +19,7 @@ setup(
package_dir = {'': 'src'},
package_data={'':['*.txt', '*.js', '*.html', '*.*']},
- install_requires = ['setuptools'],
+ install_requires = ['setuptools','django-countries','django-piston'],
classifiers = [
'Development Status :: 3 - Alpha',
|
add django-countries and django-piston to install requires
|
mthornhill_django-postal
|
train
|
c7d13e62c7eea1369eaa65d9b3a7d109e2701d63
|
diff --git a/plugins/commands/serve/mappers.rb b/plugins/commands/serve/mappers.rb
index <HASH>..<HASH> 100644
--- a/plugins/commands/serve/mappers.rb
+++ b/plugins/commands/serve/mappers.rb
@@ -85,7 +85,7 @@ module VagrantPlugins
def map(value, *extra_args, to: nil)
# If we don't have a destination type provided, attempt
# to set it using our default maps
- to = DEFAULT_MAP[value.class] if to.nil?
+ to = DEFAULT_MAPS[value.class] if to.nil?
logger.debug("starting the value mapping process #{value} => #{to.nil? ? 'unknown' : to.inspect}")
if value.nil? && to
@@ -236,17 +236,20 @@ module VagrantPlugins
def unfuncspec(v)
m = mappers.find_all { |map|
map.inputs.size == 1 &&
+ map.output.ancestors.include?(Google::Protobuf::MessageExts) &&
map.inputs.first.valid?(v)
}
if m.size > 1
raise TypeError,
- "FuncSpec value of type `#{v.class}' matches more than one mapper"
+ "FuncSpec value of type `#{v.class}' matches more than one mapper (#{v})"
end
if m.empty?
raise ArgumentError,
"FuncSpec value of type `#{v.class}' has no valid mappers"
end
- m.first.call(v)
+ result = m.first.call(v)
+ logger.debug("converted funcspec argument #{v} -> #{result}")
+ result
end
end
end
|
Ensure output of mapper to unpack funcspec is a proto
|
hashicorp_vagrant
|
train
|
6d1d9ae74ca7929b72831d4f5517ade035af3e3c
|
diff --git a/colorspacious/gold_values.py b/colorspacious/gold_values.py
index <HASH>..<HASH> 100644
--- a/colorspacious/gold_values.py
+++ b/colorspacious/gold_values.py
@@ -196,16 +196,16 @@ JMh_to_CAM02UCS_silver = [
JMh_to_CAM02LCD_silver = [
([50, 20, 10],
- [ 50.77658303, 14.80756375, 2.61097301]),
+ [ 81.77008177, 18.72061994, 3.30095039]),
([10, 60, 100],
- [ 12.81278263, -5.5311588 , 31.36876036]),
+ [ 20.63357204, -9.04659289, 51.30577777]),
]
JMh_to_CAM02SCD_silver = [
([50, 20, 10],
- [ 81.77008177, 18.72061994, 3.30095039]),
+ [ 50.77658303, 14.80756375, 2.61097301]),
([10, 60, 100],
- [ 20.63357204, -9.04659289, 51.30577777]),
+ [ 12.81278263, -5.5311588 , 31.36876036]),
]
################################################################
diff --git a/colorspacious/luoetal2006.py b/colorspacious/luoetal2006.py
index <HASH>..<HASH> 100644
--- a/colorspacious/luoetal2006.py
+++ b/colorspacious/luoetal2006.py
@@ -52,8 +52,8 @@ class LuoEtAl2006UniformSpace(object):
return stacklast(J, M, h)
CAM02UCS = LuoEtAl2006UniformSpace(1.00, 0.007, 0.0228)
-CAM02LCD = LuoEtAl2006UniformSpace(1.24, 0.007, 0.0363)
-CAM02SCD = LuoEtAl2006UniformSpace(0.77, 0.007, 0.0053)
+CAM02LCD = LuoEtAl2006UniformSpace(0.77, 0.007, 0.0053)
+CAM02SCD = LuoEtAl2006UniformSpace(1.24, 0.007, 0.0363)
def test_repr():
# smoke test
|
The coefficients for CAM<I>-LCD and CAM<I>-SCD should be the other way around.
|
njsmith_colorspacious
|
train
|
4684502ec75d4a08a1f7627798f30daaffcd1547
|
diff --git a/test/j_manual_approval_transfer_manager.js b/test/j_manual_approval_transfer_manager.js
index <HASH>..<HASH> 100644
--- a/test/j_manual_approval_transfer_manager.js
+++ b/test/j_manual_approval_transfer_manager.js
@@ -1000,7 +1000,7 @@ contract("ManualApprovalTransferManager", accounts => {
assert.equal(desc, "Manage transfers using single approvals", "Wrong Module added");
let title = await I_ManualApprovalTransferManagerFactory.title.call();
assert.equal(title, "Manual Approval Transfer Manager", "Wrong Module added");
- assert.equal(await I_ManualApprovalTransferManagerFactory.version.call(), "3.0.0");
+ assert.equal(await I_ManualApprovalTransferManagerFactory.version.call(), "3.0.1");
});
it("Should get the tags of the factory", async () => {
|
Bump MATM version in the coresponding test
|
PolymathNetwork_polymath-core
|
train
|
43f7ab66f7748fd7bb0c435f20b99b76760953c4
|
diff --git a/lib/client/signalflow/websocket_message_parser.js b/lib/client/signalflow/websocket_message_parser.js
index <HASH>..<HASH> 100644
--- a/lib/client/signalflow/websocket_message_parser.js
+++ b/lib/client/signalflow/websocket_message_parser.js
@@ -7,6 +7,43 @@ var BigNumber = require('bignumber.js');
BigNumber.config({ ERRORS: false });
var hiMult = Math.pow(2, 32);
+
+var msgFormat = [
+ {
+ label: 'version',
+ type: 'Uint',
+ size: 1
+ },
+ {
+ label: 'messageType',
+ type: 'Uint',
+ size: 1
+ },
+ {
+ label: null,
+ size: 2
+ },
+ {
+ label: null,
+ size: 16
+ },
+ {
+ label: 'timestampMs1',
+ type: 'Uint',
+ size: 4
+ },
+ {
+ label: 'timestampMs2',
+ type: 'Uint',
+ size: 4
+ },
+ {
+ label: 'count',
+ type: 'Uint',
+ size: 4
+ }
+];
+
function getSnowflakeIdFromUint8Array(Uint8Arr) {
//packaged lib uses base64 not base64URL, so swap the different chars
return base64js.fromByteArray(Uint8Arr).substring(0, 11).replace(/\+/g, '-').replace(/\//g, '_');
@@ -42,41 +79,6 @@ function parseWebSocketMessage(msg) {
//| Payload data continued ... |
//+---------------------------------------------------------------+
var view = new DataView(msg.data);
- var msgFormat = [
- {
- label: 'version',
- type: 'Uint',
- size: 1
- },
- {
- label: 'messageType',
- type: 'Uint',
- size: 1
- },
- {
- label: null,
- size: 2
- },
- {
- label: null,
- size: 16
- },
- {
- label: 'timestampMs1',
- type: 'Uint',
- size: 4
- },
- {
- label: 'timestampMs2',
- type: 'Uint',
- size: 4
- },
- {
- label: 'count',
- type: 'Uint',
- size: 4
- }
- ];
var offset = 0;
var msgObject = {
|
stop declaring the binary msgFmt in parseWebSocketMessage to prevent excessive GCs
|
signalfx_signalfx-nodejs
|
train
|
19c22d272e5a88db26955e5632910781e1dcafe4
|
diff --git a/spi/src/main/java/org/jboss/arquillian/spi/DeploymentAppender.java b/spi/src/main/java/org/jboss/arquillian/spi/DeploymentAppender.java
index <HASH>..<HASH> 100644
--- a/spi/src/main/java/org/jboss/arquillian/spi/DeploymentAppender.java
+++ b/spi/src/main/java/org/jboss/arquillian/spi/DeploymentAppender.java
@@ -29,6 +29,12 @@ import org.jboss.shrinkwrap.api.Archive;
public interface DeploymentAppender
{
+ /**
+ * Create a archive containing the needed resources for this extension
+ * to run in-container.
+ *
+ * @return A Archive of any type
+ */
Archive<?> createArchive();
}
diff --git a/spi/src/main/java/org/jboss/arquillian/spi/util/DeploymentAppenders.java b/spi/src/main/java/org/jboss/arquillian/spi/util/DeploymentAppenders.java
index <HASH>..<HASH> 100644
--- a/spi/src/main/java/org/jboss/arquillian/spi/util/DeploymentAppenders.java
+++ b/spi/src/main/java/org/jboss/arquillian/spi/util/DeploymentAppenders.java
@@ -30,15 +30,16 @@ import org.jboss.shrinkwrap.api.Archive;
* @author <a href="mailto:aslak@conduct.no">Aslak Knutsen</a>
* @version $Revision: $
*/
-public class DeploymentAppenders
+public final class DeploymentAppenders
{
-
+ private DeploymentAppenders() { }
+
/**
* Load/Create all Archives provided by the different modules.
*
* @return A List of all archives
*/
- public List<Archive<?>> getArchives()
+ public static List<Archive<?>> getArchives()
{
List<Archive<?>> archives = new ArrayList<Archive<?>>();
DefaultServiceLoader<DeploymentAppender> serviceLoader = DefaultServiceLoader.load(
|
ARQ-<I> SPI for adding Archives to the deployment
|
arquillian_arquillian-core
|
train
|
8dac1453c32e50a54996d6280ba7f78fbdaef636
|
diff --git a/MAVProxy/tools/mavflightview.py b/MAVProxy/tools/mavflightview.py
index <HASH>..<HASH> 100755
--- a/MAVProxy/tools/mavflightview.py
+++ b/MAVProxy/tools/mavflightview.py
@@ -99,8 +99,11 @@ def mavflightview(filename):
types.extend(['GPS','GLOBAL_POSITION_INT'])
print("Looking for types %s" % str(types))
while True:
- m = mlog.recv_match(type=types)
- if m is None:
+ try:
+ m = mlog.recv_match(type=types)
+ if m is None:
+ break
+ except Exception:
break
if m.get_type() == 'MISSION_ITEM':
wp.set(m, m.seq)
|
mavflightview: cope with bad data at end of log
|
ArduPilot_MAVProxy
|
train
|
a6bc5be83cd82db53d03093a798625e4f470ed09
|
diff --git a/src/main/java/nl/hsac/fitnesse/fixture/slim/web/NgBrowserTest.java b/src/main/java/nl/hsac/fitnesse/fixture/slim/web/NgBrowserTest.java
index <HASH>..<HASH> 100644
--- a/src/main/java/nl/hsac/fitnesse/fixture/slim/web/NgBrowserTest.java
+++ b/src/main/java/nl/hsac/fitnesse/fixture/slim/web/NgBrowserTest.java
@@ -126,7 +126,7 @@ public class NgBrowserTest extends BrowserTest {
params.add(getAngularRoot());
params.addAll(Arrays.asList(parameters));
- return findByJavascript(script, parameters);
+ return findByJavascript(script, params.toArray());
}
public String getAngularRoot() {
|
Oops, should pass parameters including root element to script
|
fhoeben_hsac-fitnesse-fixtures
|
train
|
31f0bfc248ae6c3f6a080cd569e396d7aebffdd4
|
diff --git a/shell/src/test/java/tachyon/shell/TFsShellUtilsTest.java b/shell/src/test/java/tachyon/shell/TFsShellUtilsTest.java
index <HASH>..<HASH> 100644
--- a/shell/src/test/java/tachyon/shell/TFsShellUtilsTest.java
+++ b/shell/src/test/java/tachyon/shell/TFsShellUtilsTest.java
@@ -95,6 +95,10 @@ public class TFsShellUtilsTest {
}
public String resetTachyonFileHierarchy() throws IOException {
+ return resetTachyonFileHierarchy(mTfs);
+ }
+
+ public static String resetTachyonFileHierarchy(TachyonFS tfs) throws IOException {
/**
* Generate such local structure
* /testWildCards
@@ -105,20 +109,25 @@ public class TFsShellUtilsTest {
* | └── foobar3
* └── foobar4
*/
- mTfs.delete(new TachyonURI("/testWildCards"), true);
- mTfs.mkdir(new TachyonURI("/testWildCards"));
- mTfs.mkdir(new TachyonURI("/testWildCards/foo"));
- mTfs.mkdir(new TachyonURI("/testWildCards/bar"));
+ tfs.delete(new TachyonURI("/testWildCards"), true);
+ tfs.mkdir(new TachyonURI("/testWildCards"));
+ tfs.mkdir(new TachyonURI("/testWildCards/foo"));
+ tfs.mkdir(new TachyonURI("/testWildCards/bar"));
- TachyonFSTestUtils.createByteFile(mTfs, "/testWildCards/foo/foobar1", WriteType.MUST_CACHE, 10);
- TachyonFSTestUtils.createByteFile(mTfs, "/testWildCards/foo/foobar2", WriteType.MUST_CACHE, 20);
- TachyonFSTestUtils.createByteFile(mTfs, "/testWildCards/bar/foobar3", WriteType.MUST_CACHE, 30);
- TachyonFSTestUtils.createByteFile(mTfs, "/testWildCards/foobar4", WriteType.MUST_CACHE, 40);
+ TachyonFSTestUtils.createByteFile(tfs, "/testWildCards/foo/foobar1", WriteType.MUST_CACHE, 10);
+ TachyonFSTestUtils.createByteFile(tfs, "/testWildCards/foo/foobar2", WriteType.MUST_CACHE, 20);
+ TachyonFSTestUtils.createByteFile(tfs, "/testWildCards/bar/foobar3", WriteType.MUST_CACHE, 30);
+ TachyonFSTestUtils.createByteFile(tfs, "/testWildCards/foobar4", WriteType.MUST_CACHE, 40);
return "/testWildCards";
}
public String resetLocalFileHierarchy() throws IOException {
+ return resetLocalFileHierarchy(mLocalTachyonCluster);
+ }
+
+ public static String resetLocalFileHierarchy(LocalTachyonCluster localTachyonCluster)
+ throws IOException {
/**
* Generate such local structure
* /testWildCards
@@ -129,17 +138,17 @@ public class TFsShellUtilsTest {
* | └── foobar3
* └── foobar4
*/
- FileUtils.deleteDirectory(new File(mLocalTachyonCluster.getTachyonHome() + "/testWildCards"));
- new File(mLocalTachyonCluster.getTachyonHome() + "/testWildCards").mkdir();
- new File(mLocalTachyonCluster.getTachyonHome() + "/testWildCards/foo").mkdir();
- new File(mLocalTachyonCluster.getTachyonHome() + "/testWildCards/bar").mkdir();
+ FileUtils.deleteDirectory(new File(localTachyonCluster.getTachyonHome() + "/testWildCards"));
+ new File(localTachyonCluster.getTachyonHome() + "/testWildCards").mkdir();
+ new File(localTachyonCluster.getTachyonHome() + "/testWildCards/foo").mkdir();
+ new File(localTachyonCluster.getTachyonHome() + "/testWildCards/bar").mkdir();
- new File(mLocalTachyonCluster.getTachyonHome() + "/testWildCards/foo/foobar1").createNewFile();
- new File(mLocalTachyonCluster.getTachyonHome() + "/testWildCards/foo/foobar2").createNewFile();
- new File(mLocalTachyonCluster.getTachyonHome() + "/testWildCards/bar/foobar3").createNewFile();
- new File(mLocalTachyonCluster.getTachyonHome() + "/testWildCards/foobar4").createNewFile();
+ new File(localTachyonCluster.getTachyonHome() + "/testWildCards/foo/foobar1").createNewFile();
+ new File(localTachyonCluster.getTachyonHome() + "/testWildCards/foo/foobar2").createNewFile();
+ new File(localTachyonCluster.getTachyonHome() + "/testWildCards/bar/foobar3").createNewFile();
+ new File(localTachyonCluster.getTachyonHome() + "/testWildCards/foobar4").createNewFile();
- return mLocalTachyonCluster.getTachyonHome() + "/testWildCards";
+ return localTachyonCluster.getTachyonHome() + "/testWildCards";
}
public List<String> getPaths(String path, FsType fsType) throws IOException {
|
[TACHYON-<I>] Refactor the utility functions resetTachyonFileHierarchy and resetLocalFileHierarchy and make them static, so that they can be used in TFsShellTest
|
Alluxio_alluxio
|
train
|
07f13af81a12193989acf6a1d1182d5e9e626d7f
|
diff --git a/lib/getData.js b/lib/getData.js
index <HASH>..<HASH> 100644
--- a/lib/getData.js
+++ b/lib/getData.js
@@ -41,15 +41,18 @@ module.exports = function(req, callback) {
var newTimestamp = new Date().getTime();
query["timestamp"] = { $gt : moment(newTimestamp).toISOString()}
+ require('./logEvent')(701, query);
var cursor = events.find(query, {}, {tailable:true, timeout:false});
return cursor;
} else {
+ // console.log('QUERY>', query);
data.find(query).limit(limit).sort({
$natural: -1
}, function(err, eventdata) {
+ // console.log('DATA>', eventdata);
if(err || eventdata.length < 1) {
@@ -72,6 +75,7 @@ module.exports = function(req, callback) {
delete eventdata[i]._id;
}
console.log('Data: ' + JSON.stringify(eventdata));
+ require('./logEvent')(701, query);
callback({"data": eventdata});
}
diff --git a/lib/socketLogic.js b/lib/socketLogic.js
index <HASH>..<HASH> 100644
--- a/lib/socketLogic.js
+++ b/lib/socketLogic.js
@@ -1,5 +1,6 @@
var whoAmI = require('./whoAmI');
var config = require('../config');
+var getData = require('./getData');
var logData = require('./logData');
var logEvent = require('./logEvent');
var register = require('./register');
@@ -619,6 +620,60 @@ function socketLogic (socket, secure, skynet){
});
});
+ socket.on('getdata', function (data, fn) {
+ skynet.throttles.query.rateLimit(socket.id, function (err, limited) {
+ if(limited){
+ console.log('query throttled', socket.id);
+ }else{
+
+ authDevice(data.uuid, data.token, function(auth){
+
+ if (auth.authenticate){
+
+ if(!data || (typeof data != 'object')){
+ data = {};
+ }
+ data.params = {};
+ data.query = {};
+
+ data.params.uuid = data.uuid;
+ data.query.start = data.start; // time to start from
+ data.query.finish = data.finish; // time to end
+ data.query.limit = data.limit; // 0 bypasses the limit
+
+ getData(data, function(results){
+ // if(err){ return; }
+
+ results.fromUuid = socket.skynetDevice.uuid;
+ console.log(results);
+
+ try{
+ fn(results);
+
+ } catch (e){
+ console.log(e);
+ }
+
+ });
+
+ } else {
+ console.log('UUID not found or invalid token ', data.uuid);
+
+ var results = {"api": "getdata", "result": false};
+
+ console.log(results);
+ try{
+ fn(results);
+ } catch (e){
+ console.log(e);
+ }
+ }
+
+ });
+
+ }
+ });
+ });
socket.on('gatewayConfig', function(data, fn) {
diff --git a/readme.md b/readme.md
index <HASH>..<HASH> 100644
--- a/readme.md
+++ b/readme.md
@@ -393,6 +393,7 @@ Event Codes
* 500 = WhoAmI
* 600 = Gateway Config API call
* 700 = Write sensor data
+* 701 = Read sensor data
FOLLOW US!
----------
|
added getdata api to websockets
|
octoblu_meshblu
|
train
|
4d18be2e0968ac2911caf7bcc06ede1932be4f8a
|
diff --git a/salt/fileserver/gitfs.py b/salt/fileserver/gitfs.py
index <HASH>..<HASH> 100644
--- a/salt/fileserver/gitfs.py
+++ b/salt/fileserver/gitfs.py
@@ -53,7 +53,7 @@ import re
import shutil
import subprocess
from datetime import datetime
-from six import text_type as _text_type
+from salt.utils.six import text_type as _text_type
VALID_PROVIDERS = ('gitpython', 'pygit2', 'dulwich')
PER_REMOTE_PARAMS = ('base', 'mountpoint', 'root')
@@ -90,7 +90,7 @@ _INVALID_REPO = (
# Import salt libs
import salt.utils
import salt.fileserver
-from six import string_types
+from salt.utils.six import string_types
from salt.exceptions import SaltException
from salt.utils.event import tagify
|
Replaced module six in file /salt/fileserver/gitfs.py
|
saltstack_salt
|
train
|
92c94011f107a2498596105b3f489e2eba2be36c
|
diff --git a/cmd/net.go b/cmd/net.go
index <HASH>..<HASH> 100644
--- a/cmd/net.go
+++ b/cmd/net.go
@@ -22,6 +22,7 @@ import (
"fmt"
"net"
"net/url"
+ "runtime"
"sort"
"strings"
@@ -46,20 +47,30 @@ func mustSplitHostPort(hostPort string) (host, port string) {
// mustGetLocalIP4 returns IPv4 addresses of localhost. It panics on error.
func mustGetLocalIP4() (ipList set.StringSet) {
ipList = set.NewStringSet()
- addrs, err := net.InterfaceAddrs()
+ ifs, err := net.Interfaces()
logger.FatalIf(err, "Unable to get IP addresses of this host")
- for _, addr := range addrs {
- var ip net.IP
- switch v := addr.(type) {
- case *net.IPNet:
- ip = v.IP
- case *net.IPAddr:
- ip = v.IP
+ for _, interf := range ifs {
+ addrs, err := interf.Addrs()
+ if err != nil {
+ continue
+ }
+ if runtime.GOOS == "windows" && interf.Flags&net.FlagUp == 0 {
+ continue
}
- if ip.To4() != nil {
- ipList.Add(ip.String())
+ for _, addr := range addrs {
+ var ip net.IP
+ switch v := addr.(type) {
+ case *net.IPNet:
+ ip = v.IP
+ case *net.IPAddr:
+ ip = v.IP
+ }
+
+ if ip.To4() != nil {
+ ipList.Add(ip.String())
+ }
}
}
|
Skip downed interfaces on Windows (#<I>)
Disregard interfaces that are down when selecting bind addresses
Windows often has a number of disabled NICs used for VPN and other services.
This often causes minio to select an address for contacting the console that is on a disabled (virtual) NIC.
This checks if the interface is up before adding it to the pool on Windows.
|
minio_minio
|
train
|
5404dddcea7d731509a880923deff0571a70cf83
|
diff --git a/cmd/bucket-handlers.go b/cmd/bucket-handlers.go
index <HASH>..<HASH> 100644
--- a/cmd/bucket-handlers.go
+++ b/cmd/bucket-handlers.go
@@ -429,9 +429,8 @@ func (api objectAPIHandlers) PostPolicyBucketHandler(w http.ResponseWriter, r *h
}
}
- // Save metadata.
- metadata := make(map[string]string)
- // Nothing to store right now.
+ // Extract metadata to be saved from received Form.
+ metadata := extractMetadataFromForm(formValues)
sha256sum := ""
diff --git a/cmd/handler-utils.go b/cmd/handler-utils.go
index <HASH>..<HASH> 100644
--- a/cmd/handler-utils.go
+++ b/cmd/handler-utils.go
@@ -92,6 +92,32 @@ func extractMetadataFromHeader(header http.Header) map[string]string {
return metadata
}
+// extractMetadataFromForm extracts metadata from Post Form.
+func extractMetadataFromForm(formValues map[string]string) map[string]string {
+ metadata := make(map[string]string)
+ // Save standard supported headers.
+ for _, supportedHeader := range supportedHeaders {
+ canonicalHeader := http.CanonicalHeaderKey(supportedHeader)
+ // Form field names are case insensitive, look for both canonical
+ // and non canonical entries.
+ if _, ok := formValues[canonicalHeader]; ok {
+ metadata[supportedHeader] = formValues[canonicalHeader]
+ } else if _, ok := formValues[supportedHeader]; ok {
+ metadata[supportedHeader] = formValues[canonicalHeader]
+ }
+ }
+ // Go through all other form values for any additional headers that needs to be saved.
+ for key := range formValues {
+ cKey := http.CanonicalHeaderKey(key)
+ if strings.HasPrefix(cKey, "X-Amz-Meta-") {
+ metadata[cKey] = formValues[key]
+ } else if strings.HasPrefix(cKey, "X-Minio-Meta-") {
+ metadata[cKey] = formValues[key]
+ }
+ }
+ return metadata
+}
+
// Extract form fields and file data from a HTTP POST Policy
func extractPostPolicyFormValues(reader *multipart.Reader) (filePart io.Reader, fileName string, formValues map[string]string, err error) {
/// HTML Form values
diff --git a/cmd/post-policy_test.go b/cmd/post-policy_test.go
index <HASH>..<HASH> 100644
--- a/cmd/post-policy_test.go
+++ b/cmd/post-policy_test.go
@@ -178,6 +178,7 @@ func testPostPolicyBucketHandler(obj ObjectLayer, instanceType string, t TestErr
testCasesV4 := []struct {
objectName string
data []byte
+ expectedHeaders map[string]string
expectedRespStatus int
accessKey string
secretKey string
@@ -188,6 +189,7 @@ func testPostPolicyBucketHandler(obj ObjectLayer, instanceType string, t TestErr
objectName: "test",
data: []byte("Hello, World"),
expectedRespStatus: http.StatusNoContent,
+ expectedHeaders: map[string]string{"X-Amz-Meta-Uuid": "1234"},
accessKey: credentials.AccessKeyID,
secretKey: credentials.SecretAccessKey,
malformedBody: false,
@@ -229,6 +231,18 @@ func testPostPolicyBucketHandler(obj ObjectLayer, instanceType string, t TestErr
if rec.Code != testCase.expectedRespStatus {
t.Errorf("Test %d: %s: Expected the response status to be `%d`, but instead found `%d`", i+1, instanceType, testCase.expectedRespStatus, rec.Code)
}
+ // When the operation is successful, check if sending metadata is successful too
+ if rec.Code == http.StatusNoContent {
+ objInfo, err := obj.GetObjectInfo(bucketName, testCase.objectName+"/upload.txt")
+ if err != nil {
+ t.Error("Unexpected error: ", err)
+ }
+ for k, v := range testCase.expectedHeaders {
+ if objInfo.UserDefined[k] != v {
+ t.Errorf("Expected to have header %s with value %s, but found value `%s` instead", k, v, objInfo.UserDefined[k])
+ }
+ }
+ }
}
// Test cases for signature-V4.
@@ -475,6 +489,8 @@ func newPostRequestV4Generic(endPoint, bucketName, objectName string, objData []
"x-amz-signature": signature,
"x-amz-date": t.Format(iso8601DateFormat),
"x-amz-algorithm": "AWS4-HMAC-SHA256",
+ "x-amz-meta-uuid": "1234",
+ "Content-Encoding": "gzip",
}
// Create the multipart form.
|
PostForm: Save supported headers in obj metadata (#<I>)
Supported Headers like Content-Type, Cache-Control, Content-Encoding, X-Amz-* , etc.. are now saved in object metadata
|
minio_minio
|
train
|
e169172fedd8d1d8aa320e91bf890b9e6025b2df
|
diff --git a/foursquare.go b/foursquare.go
index <HASH>..<HASH> 100644
--- a/foursquare.go
+++ b/foursquare.go
@@ -47,6 +47,14 @@ func newClient(httpClient *http.Client, mode, clientID, clientSecret, accessToke
}
}
+// RawRequest allows you to make any request you want. This will automatically add
+// the client/user tokens. Gives back exactly the response from foursquare.
+func (c *Client) RawRequest(url string) (*Response, *http.Response, error) {
+ response := new(Response)
+ resp, err := c.sling.New().Get(url).Receive(response, response)
+ return response, resp, relevantError(err, *response)
+}
+
// Response is a typical foursquare response
// https://developer.foursquare.com/overview/responses
type Response struct {
|
add rawrequest to ask for any endpoint
This sends back a full foursquare response.
|
peppage_foursquarego
|
train
|
ec55a34430b7ae3b8899955bac9affd4e6d344d0
|
diff --git a/builtin/providers/aws/resource_aws_rds_cluster_parameter_group_test.go b/builtin/providers/aws/resource_aws_rds_cluster_parameter_group_test.go
index <HASH>..<HASH> 100644
--- a/builtin/providers/aws/resource_aws_rds_cluster_parameter_group_test.go
+++ b/builtin/providers/aws/resource_aws_rds_cluster_parameter_group_test.go
@@ -3,6 +3,7 @@ package aws
import (
"fmt"
"testing"
+ "time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
@@ -85,6 +86,26 @@ func TestAccAWSDBClusterParameterGroup_basic(t *testing.T) {
})
}
+func TestAccAWSDBClusterParameterGroup_disappears(t *testing.T) {
+ var v rds.DBClusterParameterGroup
+
+ resource.Test(t, resource.TestCase{
+ PreCheck: func() { testAccPreCheck(t) },
+ Providers: testAccProviders,
+ CheckDestroy: testAccCheckAWSDBClusterParameterGroupDestroy,
+ Steps: []resource.TestStep{
+ resource.TestStep{
+ Config: testAccAWSDBClusterParameterGroupConfig,
+ Check: resource.ComposeTestCheckFunc(
+ testAccCheckAWSDBClusterParameterGroupExists("aws_rds_cluster_parameter_group.bar", &v),
+ testAccAWSDBClusterParameterGroupDisappears(&v),
+ ),
+ ExpectNonEmptyPlan: true,
+ },
+ },
+ })
+}
+
func TestAccAWSDBClusterParameterGroupOnly(t *testing.T) {
var v rds.DBClusterParameterGroup
@@ -203,6 +224,34 @@ func testAccCheckAWSDBClusterParameterGroupAttributes(v *rds.DBClusterParameterG
}
}
+func testAccAWSDBClusterParameterGroupDisappears(v *rds.DBClusterParameterGroup) resource.TestCheckFunc {
+ return func(s *terraform.State) error {
+ conn := testAccProvider.Meta().(*AWSClient).rdsconn
+ opts := &rds.DeleteDBClusterParameterGroupInput{
+ DBClusterParameterGroupName: v.DBClusterParameterGroupName,
+ }
+ if _, err := conn.DeleteDBClusterParameterGroup(opts); err != nil {
+ return err
+ }
+ return resource.Retry(40*time.Minute, func() *resource.RetryError {
+ opts := &rds.DescribeDBClusterParameterGroupsInput{
+ DBClusterParameterGroupName: v.DBClusterParameterGroupName,
+ }
+ _, err := conn.DescribeDBClusterParameterGroups(opts)
+ if err != nil {
+ dbparamgrouperr, ok := err.(awserr.Error)
+ if ok && dbparamgrouperr.Code() == "DBParameterGroupNotFound" {
+ return nil
+ }
+ return resource.NonRetryableError(
+ fmt.Errorf("Error retrieving DB Cluster Parameter Groups: %s", err))
+ }
+ return resource.RetryableError(fmt.Errorf(
+ "Waiting for cluster parameter group to be deleted: %v", v.DBClusterParameterGroupName))
+ })
+ }
+}
+
func testAccCheckAWSDBClusterParameterGroupExists(n string, v *rds.DBClusterParameterGroup) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
|
_disappears test
|
hashicorp_terraform
|
train
|
c50d0fccd5b0b47dea162b4dac2fd94ae21e522f
|
diff --git a/torchvision/models/detection/faster_rcnn.py b/torchvision/models/detection/faster_rcnn.py
index <HASH>..<HASH> 100644
--- a/torchvision/models/detection/faster_rcnn.py
+++ b/torchvision/models/detection/faster_rcnn.py
@@ -300,6 +300,9 @@ def fasterrcnn_resnet50_fpn(pretrained=False, progress=True,
"""
Constructs a Faster R-CNN model with a ResNet-50-FPN backbone.
+ Reference: `"Faster R-CNN: Towards Real-Time Object Detection with
+ Region Proposal Networks" <https://arxiv.org/abs/1506.01497>`_.
+
The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each
image, and should be in ``0-1`` range. Different images can have different sizes.
diff --git a/torchvision/models/detection/keypoint_rcnn.py b/torchvision/models/detection/keypoint_rcnn.py
index <HASH>..<HASH> 100644
--- a/torchvision/models/detection/keypoint_rcnn.py
+++ b/torchvision/models/detection/keypoint_rcnn.py
@@ -278,6 +278,8 @@ def keypointrcnn_resnet50_fpn(pretrained=False, progress=True,
"""
Constructs a Keypoint R-CNN model with a ResNet-50-FPN backbone.
+ Reference: `"Mask R-CNN" <https://arxiv.org/abs/1703.06870>`_.
+
The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each
image, and should be in ``0-1`` range. Different images can have different sizes.
diff --git a/torchvision/models/detection/mask_rcnn.py b/torchvision/models/detection/mask_rcnn.py
index <HASH>..<HASH> 100644
--- a/torchvision/models/detection/mask_rcnn.py
+++ b/torchvision/models/detection/mask_rcnn.py
@@ -271,6 +271,8 @@ def maskrcnn_resnet50_fpn(pretrained=False, progress=True,
"""
Constructs a Mask R-CNN model with a ResNet-50-FPN backbone.
+ Reference: `"Mask R-CNN" <https://arxiv.org/abs/1703.06870>`_.
+
The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each
image, and should be in ``0-1`` range. Different images can have different sizes.
diff --git a/torchvision/models/detection/retinanet.py b/torchvision/models/detection/retinanet.py
index <HASH>..<HASH> 100644
--- a/torchvision/models/detection/retinanet.py
+++ b/torchvision/models/detection/retinanet.py
@@ -569,6 +569,8 @@ def retinanet_resnet50_fpn(pretrained=False, progress=True,
"""
Constructs a RetinaNet model with a ResNet-50-FPN backbone.
+ Reference: `"Focal Loss for Dense Object Detection" <https://arxiv.org/abs/1708.02002>`_.
+
The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each
image, and should be in ``0-1`` range. Different images can have different sizes.
|
Added paper references to detection models (#<I>)
* Added paper references to detection models
* Ignore linter warning
* Break long line into two
|
pytorch_vision
|
train
|
1a039781c608c3ea8934fc4d9c5c24afcb423cf0
|
diff --git a/code/libraries/koowa/components/com_activities/activity/object/interface.php b/code/libraries/koowa/components/com_activities/activity/object/interface.php
index <HASH>..<HASH> 100644
--- a/code/libraries/koowa/components/com_activities/activity/object/interface.php
+++ b/code/libraries/koowa/components/com_activities/activity/object/interface.php
@@ -261,4 +261,36 @@ interface ComActivitiesActivityObjectInterface
* @return bool True if the object has been deleted, false otherwise.
*/
public function isDeleted();
+
+ /**
+ * Atrributes setter.
+ *
+ * @param array $attribs An array containing object attributes.
+ *
+ * @return ComActivitiesActivityObjectInterface
+ */
+ public function setAttributes(array $attribs = array());
+
+ /**
+ * Attributes getter.
+ *
+ * @return array An array containing object attributes.
+ */
+ public function getAttributes();
+
+ /**
+ * Value setter.
+ *
+ * @param string $value The value.
+ *
+ * @return ComActivitiesActivityObjectInterface
+ */
+ public function setValue($value);
+
+ /**
+ * Value getter.
+ *
+ * @return string|null The value, null if the object has no value.
+ */
+ public function getValue();
}
\ No newline at end of file
|
re #<I> Added attributes and value getters and setters.
These are the methods that got merged from the parameter interface so far.
|
joomlatools_joomlatools-framework-activities
|
train
|
53b55569cda4443c22e255666557f5dfe950689c
|
diff --git a/src/EioAdapter.php b/src/EioAdapter.php
index <HASH>..<HASH> 100644
--- a/src/EioAdapter.php
+++ b/src/EioAdapter.php
@@ -56,16 +56,52 @@ class EioAdapter implements AdapterInterface
protected $openFileLimiter;
- public function __construct(LoopInterface $loop)
+ public function __construct(LoopInterface $loop, array $options = [])
{
eio_init();
$this->loop = $loop;
$this->fd = eio_get_event_stream();
$this->openFlagResolver = new Eio\OpenFlagResolver();
$this->permissionFlagResolver = new Eio\PermissionFlagResolver();
- $this->invoker = new PooledInvoker($this);
- $this->readDirInvoker = new QueuedInvoker($this);
- $this->openFileLimiter = new OpenFileLimiter();
+
+ $this->applyConfiguration($options);
+ }
+
+ /**
+ * @param array $options
+ */
+ protected function applyConfiguration(array $options)
+ {
+ $this->invoker = $this->getInvoker($options, 'invoker', 'React\Filesystem\PooledInvoker');
+ $this->readDirInvoker = $this->getInvoker($options, 'read_dir_invoker', 'React\Filesystem\QueuedInvoker');
+ $this->openFileLimiter = new OpenFileLimiter($this->getOpenFileLimit($options));
+ }
+
+ /**
+ * @param array $options
+ * @param string $fallback
+ * @return CallInvokerInterface
+ */
+ protected function getInvoker(array $options, $key, $fallback)
+ {
+ if (isset($options[$key]) && $options[$key] instanceof CallInvokerInterface) {
+ return $options[$key];
+ }
+
+ return new $fallback($this);
+ }
+
+ /**
+ * @param array $options
+ * @return int
+ */
+ protected function getOpenFileLimit(array $options)
+ {
+ if (isset($options['open_file_limit'])) {
+ return (int)$options['open_file_limit'];
+ }
+
+ return OpenFileLimiter::DEFAULT_LIMIT;
}
/**
|
Invokers and open file limiter are now configurable
|
reactphp_filesystem
|
train
|
2bd4b8ad5a82609162d075160381ad3e510c297a
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -119,12 +119,13 @@ class InstallLib(install_lib):
for package in subprocess.check_output(["pip", "freeze"]) \
.decode('utf-8'). \
splitlines():
- if "==" in package:
- # installed package names usually look like Pillow==2.8.1
- # ignore others, like external packages that pip show
- # won't understand
- name = package.partition("==")[0]
- packages.append(name)
+ for comparator in ["==", ">=", "<=", "<", ">"]:
+ if comparator in package:
+ # installed package names usually look like Pillow==2.8.1
+ # ignore others, like external packages that pip show
+ # won't understand
+ name = package.partition(comparator)[0]
+ packages.append(name)
return packages
def package_info(self):
|
Check all comparators when looking for a package.
|
stuaxo_vext
|
train
|
6e8ba546453fcf02096532ae9808d61a08b5cc70
|
diff --git a/app/helpers/no_cms/menus/menu_helper.rb b/app/helpers/no_cms/menus/menu_helper.rb
index <HASH>..<HASH> 100644
--- a/app/helpers/no_cms/menus/menu_helper.rb
+++ b/app/helpers/no_cms/menus/menu_helper.rb
@@ -4,17 +4,19 @@ module NoCms::Menus::MenuHelper
menu = NoCms::Menus::Menu.find_by(uid: uid)
return '' if menu.nil?
- content_tag(:ul, class: 'menu') do
+ options.reverse_merge! menu_class: 'menu', current_class: 'active'
+
+ content_tag(:ul, class: options[:menu_class]) do
raw menu.menu_items.roots.no_drafts.reorder(position: :asc).map{|r| show_submenu r, options }.join
end
end
def show_submenu menu_item, options = {}
- item_class = 'menu_item'
+ item_classes = ['menu_item']
- item_class += ' active' if menu_item.active_for?(menu_activation_params) || menu_item.children.active_for(menu_activation_params).exists?
+ item_classes << options[:current_class] if menu_item.active_for?(menu_activation_params) || menu_item.children.active_for(menu_activation_params).exists?
- content_tag(:li, class: item_class) do
+ content_tag(:li, class: item_classes.join(' ')) do
content = link_to menu_item.name, url_for(menu_item.url_for)
content += content_tag(:ul) do
raw menu_item.children.no_drafts.reorder(position: :asc).map{|c| show_submenu c, options }.join
|
'Active' class for menu items in menu helper
|
simplelogica_nocms-menus
|
train
|
a8c532bc5461fbc41f1a6815efea46cd67e9a0d0
|
diff --git a/src/session.js b/src/session.js
index <HASH>..<HASH> 100644
--- a/src/session.js
+++ b/src/session.js
@@ -28,11 +28,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
var ghostdriver = ghostdriver || {};
ghostdriver.Session = function(desiredCapabilities) {
- // TODO - Actually try to match the "desiredCapabilities" instead of ignoring them
-
// private:
var
- _defaultCapabilities = {
+ _defaultCapabilities = { // TODO - Actually try to match the "desiredCapabilities" instead of ignoring them
"browserName" : "phantomjs",
"version" : phantom.version.major + '.' + phantom.version.minor + '.' + phantom.version.patch,
"platform" : phantom.defaultPageSettings.userAgent,
@@ -149,11 +147,11 @@ ghostdriver.Session = function(desiredCapabilities) {
},
_setTimeout = function(type, ms) {
- _timeoutsAmount[type] = ms;
+ _timeouts[type] = ms;
},
_getTimeout = function(type) {
- return _timeoutsAmount[type];
+ return _timeouts[type];
},
_timeoutNames = function() {
|
Fixing typo in "session" object
|
detro_ghostdriver
|
train
|
f87c437c01c41a907b480f588af0eed7fb299cc6
|
diff --git a/synergy/mx/managed_action_handler.py b/synergy/mx/managed_action_handler.py
index <HASH>..<HASH> 100644
--- a/synergy/mx/managed_action_handler.py
+++ b/synergy/mx/managed_action_handler.py
@@ -66,8 +66,12 @@ class ManagedActionHandler(AbstractActionHandler):
self.scheduler.timetable.add_log_entry(self.process_name, self.timeperiod, msg)
self.logger.info(msg + ' {')
- self.scheduler.timetable.skip_tree_node(node)
- resp = {node.timeperiod: TreeNodeDetails.get_details(node)}
+ tx_context = self.scheduler.timetable.skip_tree_node(node)
+
+ resp = collections.defaultdict(dict)
+ for process_name, nodes_context in tx_context.items():
+ for timeperiod, node in nodes_context.items():
+ resp[process_name][timeperiod] = TreeNodeDetails.get_details(node)
self.logger.info('MX }')
return resp
diff --git a/synergy/mx/tree_node_details.py b/synergy/mx/tree_node_details.py
index <HASH>..<HASH> 100644
--- a/synergy/mx/tree_node_details.py
+++ b/synergy/mx/tree_node_details.py
@@ -53,8 +53,7 @@ class TreeNodeDetails(BaseRequestHandler):
self.timeperiod = time_helper.cast_to_time_qualifier(time_qualifier, self.timeperiod)
node = self.tree.get_node(self.process_name, self.timeperiod)
rest_node.node = TreeNodeDetails.get_details(node, as_model=True)
- for key in node.children:
- child = node.children[key]
+ for key, child in node.children.items():
rest_node.children[key] = TreeNodeDetails.get_details(child)
return rest_node.document
diff --git a/synergy/scheduler/timetable.py b/synergy/scheduler/timetable.py
index <HASH>..<HASH> 100644
--- a/synergy/scheduler/timetable.py
+++ b/synergy/scheduler/timetable.py
@@ -142,7 +142,7 @@ class Timetable(object):
state_machine.skip_job(tree_node.job_record)
tx_context[tree_node.process_name][tree_node.timeperiod] = tree_node
- for timeperiod, node in tree_node.children:
+ for timeperiod, node in tree_node.children.items():
self.skip_tree_node(node, tx_context)
dependant_nodes = self._find_dependant_tree_nodes(tree_node)
diff --git a/synergy/scheduler/tree.py b/synergy/scheduler/tree.py
index <HASH>..<HASH> 100644
--- a/synergy/scheduler/tree.py
+++ b/synergy/scheduler/tree.py
@@ -165,8 +165,7 @@ class MultiLevelTree(AbstractTree):
# if any is still in processing (i.e. has produced some data) - then we can not skip parent of the child node
# case 3': consider parent as worth processing (i.e. do not skip) if child's job_record is None
all_children_spoiled = True
- for key in node.children.keys():
- child = node.children[key]
+ for key, child in node.children.items():
if child.job_record is None or \
(child.job_record.number_of_failures <= MAX_NUMBER_OF_RETRIES
and not child.job_record.is_skipped):
@@ -224,7 +223,6 @@ class MultiLevelTree(AbstractTree):
def validate(self):
"""method starts validation of the tree.
@see TreeNode.validate"""
- for timeperiod in self.root.children:
- child = self.root.children[timeperiod]
+ for timeperiod, child in self.root.children.items():
child.validate()
self.validation_timestamp = datetime.utcnow()
diff --git a/synergy/scheduler/tree_node.py b/synergy/scheduler/tree_node.py
index <HASH>..<HASH> 100644
--- a/synergy/scheduler/tree_node.py
+++ b/synergy/scheduler/tree_node.py
@@ -82,8 +82,7 @@ class AbstractTreeNode(object):
# step 2: define if all children are done and if perhaps they all are in STATE_SKIPPED
all_children_skipped = True
all_children_finished = True
- for timeperiod in self.children:
- child = self.children[timeperiod]
+ for timeperiod, child in self.children.items():
child.validate()
if child.job_record.is_active:
diff --git a/tests/test_tree_node.py b/tests/test_tree_node.py
index <HASH>..<HASH> 100644
--- a/tests/test_tree_node.py
+++ b/tests/test_tree_node.py
@@ -128,8 +128,8 @@ class TestTreeNode(unittest.TestCase):
self.time_table_mocked.reprocess_tree_node.assert_called_once_with(self.the_node)
self.assertEqual(len(self.time_table_mocked.skip_tree_node.call_args_list), 0)
- for _, child in self.the_node.children.items():
- child.validate.assert_called_once_with()
+ for _, child_node in self.the_node.children.items():
+ child_node.validate.assert_called_once_with()
def test_validate_2(self):
"""
|
- styling, addressing SKIP children iteration issue
|
mushkevych_scheduler
|
train
|
3d0d3120ce892cee4cad502ec259e5da0e2b4ad1
|
diff --git a/lib/cf/version.rb b/lib/cf/version.rb
index <HASH>..<HASH> 100644
--- a/lib/cf/version.rb
+++ b/lib/cf/version.rb
@@ -1,3 +1,3 @@
module CF
- VERSION = "0.6.1.rc7".freeze
+ VERSION = "0.6.1.rc8".freeze
end
|
Bump to <I>.rc8
|
cloudfoundry-attic_cf
|
train
|
fc937db0778130eea6ef66b9c5678f007345af5d
|
diff --git a/app/views/uss/info.php b/app/views/uss/info.php
index <HASH>..<HASH> 100644
--- a/app/views/uss/info.php
+++ b/app/views/uss/info.php
@@ -4,28 +4,82 @@
* prawee@hotmail.com
*/
+use yii\widgets\DetailView;
//use yii\helpers\Html;
//use yii\grid\GridView;
use yii\bootstrap\Modal;
use kartik\icons\Icon;
Icon::map($this);
+
+
$this->title = 'Source Items';
$this->params['breadcrumbs'][] = $this->title;
-Modal::begin([
- 'id' =>'content-modal',
+/*Modal::begin([
+ 'id' => 'content-modal',
'header' => Icon::show('cog') . '<b>Info</b>',
- 'closeButton'=>[
- 'aria-hidden' =>'true',
- 'class'=>'hide',
+ 'closeButton' => [
+ 'aria-hidden' => 'true',
+ 'class' => 'hide',
],
- 'size'=>'MODAL_LG'
-]);
+]);*/
?>
<div class="source-item-index">
-
+ <div class="row">
+ <div class="col-xs-6">
+ <?=
+ DetailView::widget([
+ 'model' => $model,
+ 'attributes' => [
+ 'id',
+ 'aoi_id',
+ 'order_id',
+ 'order_doc_no',
+ 'order_doc_year',
+ 'order_doc_prefix',
+ 'order_status',
+ 'aoi_name',
+ 'satellite_id',
+ 'acq_date_start',
+ 'acq_date_end',
+ 'quantity',
+ 'unit',
+ 'remark:ntext',
+ 'attr_ta',
+ 'attr_tl',
+ 'attr_s',
+ 'attr_pt',
+ 'attr_ct',
+ 'attr_ta_id',
+ 'attr_tl_id',
+ 'attr_s_id',
+ 'attr_pt_id',
+ 'attr_ct_id',
+ 'is_ortho',
+ 'is_rush',
+ 'is_dem',
+ 'created',
+ 'modified',
+ 'wo_doc_name',
+ 'wo_doc_year',
+ 'wo_doc_no',
+ 'wo_created',
+ 'wo_modified',
+ 'tpt_status',
+ 'tpt_user_id',
+ 'tpt_user_name',
+ 'customer_id',
+ 'customer_name',
+ 'customer_name_th',
+ 'project_name',
+ ],
+ ])
+ ?>
+ </div>
+ <div class="col-xs-6"></div>
+ </div>
</div>
<?php
-Modal::end();
\ No newline at end of file
+//Modal::end();
|
added content with left side of info.
|
prawee_yii2-grid
|
train
|
36313aeb8432acbe3b4e2bc01572c1a29f2f9b9e
|
diff --git a/src/runez/file.py b/src/runez/file.py
index <HASH>..<HASH> 100644
--- a/src/runez/file.py
+++ b/src/runez/file.py
@@ -137,7 +137,8 @@ def ini_to_dict(data, keep_empty=False, default=None):
def readlines(data, max_size=TEXT_THRESHOLD_SIZE, default=None):
- """
+ """Tentatively read lines from `data`, if not possible, simply return `default`
+
Args:
data (str | file | list | None): Path to file, or file object to return lines from
max_size (int | None): Return contents only for files smaller than 'max_size' bytes
@@ -160,8 +161,12 @@ def readlines(data, max_size=TEXT_THRESHOLD_SIZE, default=None):
# Intended for small text files, pretend no contents for binaries
return default
- with io.open(path) as fh:
- return fh.readlines()
+ try:
+ with io.open(path) as fh:
+ return fh.readlines()
+
+ except Exception:
+ return default
def move(source, destination, adapter=None, fatal=True, logger=LOG.debug):
|
Silently ignore errors in readlines(), the function is just there to "read lines if possible"
|
zsimic_runez
|
train
|
d55132a76912d9e478cc0cb03ebce07aad7da5ad
|
diff --git a/lib/dml/pgsql_native_moodle_database.php b/lib/dml/pgsql_native_moodle_database.php
index <HASH>..<HASH> 100644
--- a/lib/dml/pgsql_native_moodle_database.php
+++ b/lib/dml/pgsql_native_moodle_database.php
@@ -674,7 +674,7 @@ class pgsql_native_moodle_database extends moodle_database {
unset($params['id']);
} else {
//ugly workaround for pg < 8.2
- $seqsql = "SELECT NEXTVAL({$this->prefix}{$table}_id_seq) AS id";
+ $seqsql = "SELECT NEXTVAL('{$this->prefix}{$table}_id_seq') AS id";
$this->query_start($seqsql, NULL, SQL_QUERY_AUX);
$result = pg_query($this->pgsql, $seqsql);
$this->query_end($result);
|
MDL-<I> DML: fixed pg < <I> regression - found by sam, thanks
|
moodle_moodle
|
train
|
11482cbf8fd8768c71c86efa53500c9f948e0c6d
|
diff --git a/ppb/systems/sound.py b/ppb/systems/sound.py
index <HASH>..<HASH> 100644
--- a/ppb/systems/sound.py
+++ b/ppb/systems/sound.py
@@ -85,7 +85,6 @@ class SoundController(SdlSubSystem, LoggingMixin):
def __enter__(self):
super().__enter__()
- mix_call(Mix_Init, MIX_INIT_FLAC | MIX_INIT_MOD | MIX_INIT_MP3 | MIX_INIT_OGG)
mix_call(
Mix_OpenAudio,
44100, # Sample frequency, 44.1 kHz is CD quality
@@ -97,6 +96,7 @@ class SoundController(SdlSubSystem, LoggingMixin):
# not sure how much difference it makes.
_check_error=lambda rv: rv == -1
)
+ mix_call(Mix_Init, MIX_INIT_FLAC | MIX_INIT_MOD | MIX_INIT_MP3 | MIX_INIT_OGG)
self.allocated_channels = 16
# Register callback, keeping reference for later cleanup
|
Re-ordered call to avoid OGG problem (possibly: <URL>)
|
ppb_pursuedpybear
|
train
|
c1f1d6b8ce98fee8d3170c4c63261fba7491b19e
|
diff --git a/lib/core/client.js b/lib/core/client.js
index <HASH>..<HASH> 100644
--- a/lib/core/client.js
+++ b/lib/core/client.js
@@ -156,10 +156,10 @@ class Client extends EventEmitter {
this[kOnDestroyed] = []
this[kWriting] = false
this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming
- this[kNeedDrain] = false
+ this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming
this[kResume] = () => {
if (this[kResuming] === 0) {
- resume(this)
+ resume(this, true)
}
}
this[kTLSSession] = null
@@ -185,7 +185,7 @@ class Client extends EventEmitter {
set pipelining (value) {
this[kPipelining] = value
- resume(this)
+ resume(this, true)
}
get connected () {
@@ -249,7 +249,7 @@ class Client extends EventEmitter {
this[kResuming] = 1
process.nextTick(resume, this)
} else {
- resume(this)
+ resume(this, true)
}
} catch (err) {
handler.onError(err)
@@ -761,13 +761,18 @@ function connect (client) {
.on('close', onSocketClose)
}
-function resume (client) {
+function emitDrain (client) {
+ client[kNeedDrain] = 0
+ client.emit('drain')
+}
+
+function resume (client, sync) {
if (client[kResuming] === 2) {
return
}
client[kResuming] = 2
- _resume(client)
+ _resume(client, sync)
client[kResuming] = 0
if (client[kRunningIdx] > 256) {
@@ -777,7 +782,7 @@ function resume (client) {
}
}
-function _resume (client) {
+function _resume (client, sync) {
while (true) {
if (client[kDestroyed]) {
assert(!client.pending)
@@ -808,14 +813,18 @@ function _resume (client) {
}
if (!client.pending) {
- if (client[kNeedDrain] && !client.busy) {
- client[kNeedDrain] = false
- client.emit('drain')
+ if (client[kNeedDrain] === 2 && !client.busy) {
+ if (sync) {
+ client[kNeedDrain] = 1
+ process.nextTick(emitDrain, client)
+ } else {
+ emitDrain(client)
+ }
continue
}
return
} else {
- client[kNeedDrain] = true
+ client[kNeedDrain] = 2
}
if (client.running >= client[kPipelining]) {
|
fix: always resume in next tick (#<I>)
|
mcollina_undici
|
train
|
b82f573deea08858724d8c10d66f8c302ea79086
|
diff --git a/hystrix-contrib/hystrix-yammer-metrics-publisher/src/main/java/com/netflix/hystrix/contrib/yammermetricspublisher/HystrixYammerMetricsPublisherCommand.java b/hystrix-contrib/hystrix-yammer-metrics-publisher/src/main/java/com/netflix/hystrix/contrib/yammermetricspublisher/HystrixYammerMetricsPublisherCommand.java
index <HASH>..<HASH> 100644
--- a/hystrix-contrib/hystrix-yammer-metrics-publisher/src/main/java/com/netflix/hystrix/contrib/yammermetricspublisher/HystrixYammerMetricsPublisherCommand.java
+++ b/hystrix-contrib/hystrix-yammer-metrics-publisher/src/main/java/com/netflix/hystrix/contrib/yammermetricspublisher/HystrixYammerMetricsPublisherCommand.java
@@ -75,6 +75,7 @@ public class HystrixYammerMetricsPublisherCommand implements HystrixMetricsPubli
createCumulativeCountForEvent("countFailure", HystrixRollingNumberEvent.FAILURE);
createCumulativeCountForEvent("countFallbackEmit", HystrixRollingNumberEvent.FALLBACK_EMIT);
createCumulativeCountForEvent("countFallbackFailure", HystrixRollingNumberEvent.FALLBACK_FAILURE);
+ createCumulativeCountForEvent("countFallbackMissing", HystrixRollingNumberEvent.FALLBACK_MISSING);
createCumulativeCountForEvent("countFallbackRejection", HystrixRollingNumberEvent.FALLBACK_REJECTION);
createCumulativeCountForEvent("countFallbackSuccess", HystrixRollingNumberEvent.FALLBACK_SUCCESS);
createCumulativeCountForEvent("countResponsesFromCache", HystrixRollingNumberEvent.RESPONSE_FROM_CACHE);
@@ -90,6 +91,7 @@ public class HystrixYammerMetricsPublisherCommand implements HystrixMetricsPubli
createRollingCountForEvent("rollingCountExceptionsThrown", HystrixRollingNumberEvent.EXCEPTION_THROWN);
createRollingCountForEvent("rollingCountFailure", HystrixRollingNumberEvent.FAILURE);
createRollingCountForEvent("rollingCountFallbackFailure", HystrixRollingNumberEvent.FALLBACK_FAILURE);
+ createRollingCountForEvent("rollingCountFallbackMissing", HystrixRollingNumberEvent.FALLBACK_MISSING);
createRollingCountForEvent("rollingCountFallbackRejection", HystrixRollingNumberEvent.FALLBACK_REJECTION);
createRollingCountForEvent("rollingCountFallbackSuccess", HystrixRollingNumberEvent.FALLBACK_SUCCESS);
createRollingCountForEvent("rollingCountResponsesFromCache", HystrixRollingNumberEvent.RESPONSE_FROM_CACHE);
|
Added FALLBACK_MISSING to hystrix-yammer-metrics-publisher
|
Netflix_Hystrix
|
train
|
99c1043aa9a1ff81aa1eef6e957f7ebe89ff25f1
|
diff --git a/activesupport/lib/active_support/file_evented_update_checker.rb b/activesupport/lib/active_support/file_evented_update_checker.rb
index <HASH>..<HASH> 100644
--- a/activesupport/lib/active_support/file_evented_update_checker.rb
+++ b/activesupport/lib/active_support/file_evented_update_checker.rb
@@ -79,13 +79,8 @@ module ActiveSupport
using Module.new {
refine Pathname do
def ascendant_of?(other)
- if self != other && other.to_s.start_with?(to_s)
- # On Windows each_filename does not include the drive letter,
- # but the test above already detects if they differ.
- parts = each_filename.to_a
- other_parts = other.each_filename.to_a
-
- other_parts[0, parts.length] == parts
+ self != other && other.ascend do |ascendant|
+ break true if self == ascendant
end
end
end
|
base (refined) Pathname#ascendant_of? also on Pathname#ascend
A small rewrite in a last attempt at writing obvious and portable code
without manual string manipulation.
Note that Pathname#== uses string comparison on Windows, so if client
code passes "C:\foo" and "c:/foo/bar" the predicate won't see the
former is an ascendant of the latter. Risky business.
|
rails_rails
|
train
|
1ba09addbd4ea3bd1201864f7daa330e35e76838
|
diff --git a/lib/combined_stream.js b/lib/combined_stream.js
index <HASH>..<HASH> 100644
--- a/lib/combined_stream.js
+++ b/lib/combined_stream.js
@@ -40,12 +40,12 @@ CombinedStream.prototype.append = function(stream) {
if (isStreamLike) {
if (!(stream instanceof DelayedStream)) {
- stream.on('data', this._checkDataSize.bind(this));
-
- stream = DelayedStream.create(stream, {
+ var newStream = DelayedStream.create(stream, {
maxDataSize: Infinity,
pauseStream: this.pauseStreams,
});
+ stream.on('data', this._checkDataSize.bind(this));
+ stream = newStream;
}
this._handleErrors(stream);
|
Prevent data loss when input stream has already finished writing
Closes #<I>.
|
felixge_node-combined-stream
|
train
|
dd14a0829e3563fea14cc6b787c9190b4c68be71
|
diff --git a/lib/tus/info.rb b/lib/tus/info.rb
index <HASH>..<HASH> 100644
--- a/lib/tus/info.rb
+++ b/lib/tus/info.rb
@@ -20,7 +20,7 @@ module Tus
end
def length
- Integer(@hash["Upload-Length"])
+ Integer(@hash["Upload-Length"]) if @hash["Upload-Length"]
end
def offset
diff --git a/lib/tus/server.rb b/lib/tus/server.rb
index <HASH>..<HASH> 100644
--- a/lib/tus/server.rb
+++ b/lib/tus/server.rb
@@ -150,16 +150,14 @@ module Tus
info = Tus::Info.new(storage.read_info(uid))
input = Tus::Input.new(request.body)
- if info.defer_length?
+ if info.defer_length? && request.headers["Upload-Length"]
validate_upload_length!
info["Upload-Length"] = request.headers["Upload-Length"]
info["Upload-Defer-Length"] = nil
-
- storage.update_info(uid, info.to_h)
end
- validate_content_length!(info.remaining_length)
+ validate_content_length!(info.offset, info.length)
validate_upload_offset!(info.offset)
validate_upload_checksum!(input) if request.headers["Upload-Checksum"]
@@ -219,9 +217,13 @@ module Tus
end
end
- def validate_content_length!(remaining_length)
- error!(403, "Cannot modify completed upload") if remaining_length == 0
- error!(413, "Size of this chunk surpasses Upload-Length") if Integer(request.content_length) > remaining_length
+ def validate_content_length!(current_offset, length)
+ if length
+ error!(403, "Cannot modify completed upload") if current_offset == length
+ error!(413, "Size of this chunk surpasses Upload-Length") if Integer(request.content_length) + current_offset > length
+ else
+ error!(413, "Size of this chunk surpasses Tus-Max-Size") if Integer(request.content_length) + current_offset > max_size
+ end
end
def validate_upload_metadata!
diff --git a/test/server_test.rb b/test/server_test.rb
index <HASH>..<HASH> 100644
--- a/test/server_test.rb
+++ b/test/server_test.rb
@@ -198,18 +198,40 @@ describe Tus::Server do
assert_equal "1", response.headers["Upload-Defer-Length"]
response = @app.patch file_path, options(
+ input: "a" * 50,
headers: {"Upload-Offset" => "0",
"Content-Type" => "application/offset+octet-stream"}
)
- assert_equal 400, response.status
+ assert_equal 204, response.status
+ assert_equal "50", response.headers["Upload-Offset"]
+ assert_equal "1", response.headers["Upload-Defer-Length"]
+ refute response.headers.key?("Upload-Length")
+
+ @server.opts[:max_size] = 100
+ response = @app.patch file_path, options(
+ input: "a" * 100,
+ headers: {"Upload-Offset" => "50",
+ "Content-Type" => "application/offset+octet-stream"}
+ )
+ assert_equal 413, response.status
+
+ response = @app.patch file_path, options(
+ input: "a" * 50,
+ headers: {"Upload-Length" => "150",
+ "Upload-Offset" => "50",
+ "Content-Type" => "application/offset+octet-stream"}
+ )
+ assert_equal 413, response.status
response = @app.patch file_path, options(
+ input: "a" * 50,
headers: {"Upload-Length" => "100",
- "Upload-Offset" => "0",
+ "Upload-Offset" => "50",
"Content-Type" => "application/offset+octet-stream"}
)
assert_equal 204, response.status
assert_equal "100", response.headers["Upload-Length"]
+ assert_equal "100", response.headers["Upload-Offset"]
refute response.headers.key?("Upload-Defer-Length")
end
|
Don't require Upload-Length to be specified on first PATCH request when deferring length
The protocol specifies the following:
Once it is known the Client MUST set the Upload-Length header in the
next PATCH request
It doesn't require that the upload length needs to be sent on the
*first* PATCH request, it rather suggests that it can be passed in *any*
PATCH request.
|
janko_tus-ruby-server
|
train
|
399aa922a7552f5c06069002732ca7b7dc9896f7
|
diff --git a/lib/scorpio/schema.rb b/lib/scorpio/schema.rb
index <HASH>..<HASH> 100644
--- a/lib/scorpio/schema.rb
+++ b/lib/scorpio/schema.rb
@@ -27,16 +27,21 @@ module Scorpio
end
def match_to_object(object)
- object = object.content if object.is_a?(Scorpio::JSON::Node)
- if schema_node && schema_node['oneOf']
- matched = schema_node['oneOf'].map(&:deref).map do |oneof|
- oneof_matched = self.class.new(oneof).match_to_object(object)
- if oneof_matched.validate(object)
- oneof_matched
+ # matching oneOf is good here. one schema for one object.
+ # matching anyOf is okay. there could be more than one schema matched. it's often just one. if more
+ # than one is a match, the problems of allOf occur.
+ # matching allOf is questionable. all of the schemas must be matched but we just return the first match.
+ # there isn't really a better answer with the current implementation. merging the schemas together
+ # is a thought but is not practical.
+ %w(oneOf allOf anyOf).select { |k| schema_node[k].respond_to?(:to_ary) }.each do |someof_key|
+ schema_node[someof_key].map(&:deref).map do |someof_node|
+ someof_schema = self.class.new(someof_node)
+ if someof_schema.validate(object)
+ return someof_schema.match_to_object(object)
end
- end.compact.first
+ end
end
- matched || self
+ return self
end
def subschema_for_index(index)
|
better Scorpio::Schema#match_to_object. considers oneOf, allOf, anyOf and returns faster.
|
notEthan_jsi
|
train
|
66fb07f28c10ec4d68c0b308129189f28b1ec13f
|
diff --git a/environment/src/test/java/jetbrains/exodus/env/TransactionTest.java b/environment/src/test/java/jetbrains/exodus/env/TransactionTest.java
index <HASH>..<HASH> 100644
--- a/environment/src/test/java/jetbrains/exodus/env/TransactionTest.java
+++ b/environment/src/test/java/jetbrains/exodus/env/TransactionTest.java
@@ -15,10 +15,7 @@
*/
package jetbrains.exodus.env;
-import jetbrains.exodus.ArrayByteIterable;
-import jetbrains.exodus.ByteIterable;
-import jetbrains.exodus.ExodusException;
-import jetbrains.exodus.TestUtil;
+import jetbrains.exodus.*;
import jetbrains.exodus.bindings.IntegerBinding;
import jetbrains.exodus.bindings.StringBinding;
import jetbrains.exodus.core.execution.LatchJob;
@@ -468,4 +465,33 @@ public class TransactionTest extends EnvironmentTestsBase {
txn.commit();
Assert.fail();
}
+
+ @Test
+ @TestFor(issues = "XD-477")
+ public void testXD_471() {
+ getEnvironment().getEnvironmentConfig().setEnvTxnReplayTimeout(500L);
+ getEnvironment().executeInTransaction(new TransactionalExecutable() {
+ @Override
+ public void execute(@NotNull Transaction txn) {
+ env.openStore("new store", StoreConfig.WITHOUT_DUPLICATES, txn);
+ getEnvironment().executeInTransaction(new TransactionalExecutable() {
+ @Override
+ public void execute(@NotNull Transaction txn) {
+ env.openStore("new store 2", StoreConfig.WITHOUT_DUPLICATES, txn);
+ }
+ });
+ txn.flush();
+ Assert.assertFalse(txn.isExclusive());
+ txn.revert();
+ Assert.assertFalse(txn.isExclusive());
+ // here transaction is idempotent and not exclusive
+ try {
+ Thread.sleep(600);
+ } catch (InterruptedException ignore) {
+ }
+ txn.revert();
+ Assert.assertFalse(txn.isExclusive());
+ }
+ });
+ }
}
|
#XD-<I> reproduced
|
JetBrains_xodus
|
train
|
34d53087987404438bfc79fbde85ce1aa3579bba
|
diff --git a/gruntfile.js b/gruntfile.js
index <HASH>..<HASH> 100644
--- a/gruntfile.js
+++ b/gruntfile.js
@@ -84,7 +84,7 @@ module.exports = function(grunt) {
options: {
commitMessage: 'chore: Bump for release (v%VERSION%)',
files: ['package.json', 'bower.json'],
- commitFiles: ['-a'],
+ commitFiles: ['package.json', 'bower.json'],
push: false
}
}
|
chore: Commit explicit files in bump task
|
iVantage_angular-ivh-treeview
|
train
|
212d9be45d2e716fea8cf73b47bbfe32170dc739
|
diff --git a/src/web/to-img/ToImg.js b/src/web/to-img/ToImg.js
index <HASH>..<HASH> 100644
--- a/src/web/to-img/ToImg.js
+++ b/src/web/to-img/ToImg.js
@@ -4,19 +4,19 @@ import { getCroppedImg } from '../utils/utils';
class ToImg extends Component {
constructor(props, context) {
- super(props, context);
+ super(props, context);
}
getImg = async (fileName = 'image', getFile = true) => {
try {
let html2canvas = await import('html2canvas');
- // 兼容webpack 3.0/4.0 写法
+ // 兼容webpack 3.0/4.0 写法
html2canvas = html2canvas.hasOwnProperty('default') ? html2canvas.default : html2canvas;
- const canvas = await html2canvas(this.refs.img);
+ const canvas = await html2canvas(this.refs.img, { allowTaint: false, useCORS: true });
const { file, base64Image } = await getCroppedImg(canvas, fileName, getFile);
return {
- file,
+ file,
base64Image
};
} catch (e) {
@@ -36,15 +36,15 @@ class ToImg extends Component {
$this.download = fileName;
$this.href = URL.createObjectURL(file);
$this.click();
- return {
- file,
- base64Image
+ return {
+ file,
+ base64Image
};
} catch (e) {
console.log(e);
return false;
}
-
+
}
render() {
return (
@@ -60,4 +60,4 @@ ToImg.propTypes = {
};
ToImg.defaultProps = {
};
-export default ToImg;
\ No newline at end of file
+export default ToImg;
|
ToImg support `cors`
|
wya-team_wya-rc
|
train
|
a9faf54b11bb89a2e77a9ad9979b1ce4dada8f90
|
diff --git a/cmd/cmd.go b/cmd/cmd.go
index <HASH>..<HASH> 100644
--- a/cmd/cmd.go
+++ b/cmd/cmd.go
@@ -312,10 +312,10 @@ func Setup(app *ccli.App, options ...micro.Option) {
} else {
log.Info("Setting global network")
- if v := os.Getenv("MICRO_NETWORK_RESOLVER"); len(v) == 0 {
+ if v := os.Getenv("MICRO_NETWORK_NODES"); len(v) == 0 {
// set the resolver to use https://micro.mu/network
- env = append(env, "MICRO_NETWORK_RESOLVER=http")
- log.Log("Setting default network resolver")
+ env = append(env, "MICRO_NETWORK_NODES=network.micro.mu")
+ log.Log("Setting default network micro.mu")
}
if v := os.Getenv("MICRO_NETWORK_TOKEN"); len(v) == 0 {
// set the network token
|
Change from http resolver to setting network nodes to network.micro.mu (#<I>)
|
micro_micro
|
train
|
451044eca5a80a7e043940255a78fd94debb9a46
|
diff --git a/cli/src/main/java/org/jboss/as/cli/gui/JConsoleCLIPlugin.java b/cli/src/main/java/org/jboss/as/cli/gui/JConsoleCLIPlugin.java
index <HASH>..<HASH> 100644
--- a/cli/src/main/java/org/jboss/as/cli/gui/JConsoleCLIPlugin.java
+++ b/cli/src/main/java/org/jboss/as/cli/gui/JConsoleCLIPlugin.java
@@ -99,14 +99,14 @@ public class JConsoleCLIPlugin extends JConsolePlugin {
return connectUsingRemoting(cmdCtx, (RemotingMBeanServerConnection)mbeanServerConn);
} else {
try {
- connectUsingDefaults(cmdCtx);
+ cmdCtx.connectController("localhost", 9999);
} catch (Exception e) {
- String message = "Unable to connect to JBoss AS. \n";
+ String message = "CLI GUI unable to connect to JBoss AS with localhost:9999 \n";
message += "Go to Connection -> New Connection and enter a Remote Process \n";
message += "of the form service:jmx:remoting-jmx://{host_name}:{port} where \n";
message += "{host_name} and {port} are the address of the native management \n";
message += "interface of the AS7 installation being monitored.";
- JOptionPane.showMessageDialog(cliGuiCtx.getMainWindow(), message);
+ JOptionPane.showMessageDialog(null, message);
return false;
}
}
@@ -138,10 +138,6 @@ public class JConsoleCLIPlugin extends JConsolePlugin {
return new ThreadPoolExecutor(2, DEFAULT_MAX_THREADS, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory);
}
- private void connectUsingDefaults(CommandContext cmdCtx) throws Exception {
- cmdCtx.connectController("localhost", 9999);
- }
-
@Override
public SwingWorker<?, ?> newSwingWorker() {
if (!initComplete && isConnected) {
|
AS7-<I> jconsole fails if trying to connect to a standalone EAP instance running with offset ports
was: 0d<I>af<I>ec<I>c4fa<I>a<I>b4b4c2eafddd<I>
|
wildfly_wildfly-core
|
train
|
45af98d2c30167bfe048f630aa0dd6d2bd6c6505
|
diff --git a/src/consumer/offsetManager/isInvalidOffset.js b/src/consumer/offsetManager/isInvalidOffset.js
index <HASH>..<HASH> 100644
--- a/src/consumer/offsetManager/isInvalidOffset.js
+++ b/src/consumer/offsetManager/isInvalidOffset.js
@@ -1,3 +1,3 @@
const Long = require('long')
-module.exports = offset => !offset || Long.fromValue(offset).compare(0) === -1
+module.exports = offset => !offset || Long.fromValue(offset).isNegative()
|
Check for "offset is negative" directly
Long.compare does a lot more than what we need here: We just want to know whether
the offset is negative (-1 for undefined, or potentially one of the special values).
|
tulios_kafkajs
|
train
|
41982b1570ba5e6ef7f065a83d5038fa1ffc802c
|
diff --git a/sentry-ruby/lib/sentry/client.rb b/sentry-ruby/lib/sentry/client.rb
index <HASH>..<HASH> 100644
--- a/sentry-ruby/lib/sentry/client.rb
+++ b/sentry-ruby/lib/sentry/client.rb
@@ -21,7 +21,7 @@ module Sentry
end
def capture_event(event, scope, hint = {})
- return false unless configuration.sending_allowed?
+ return unless configuration.sending_allowed?
scope.apply_to_event(event, hint)
diff --git a/sentry-ruby/lib/sentry/hub.rb b/sentry-ruby/lib/sentry/hub.rb
index <HASH>..<HASH> 100644
--- a/sentry-ruby/lib/sentry/hub.rb
+++ b/sentry-ruby/lib/sentry/hub.rb
@@ -110,7 +110,7 @@ module Sentry
event = current_client.capture_event(event, scope, hint)
- @last_event_id = event.event_id
+ @last_event_id = event&.event_id
event
end
diff --git a/sentry-ruby/spec/sentry/client_spec.rb b/sentry-ruby/spec/sentry/client_spec.rb
index <HASH>..<HASH> 100644
--- a/sentry-ruby/spec/sentry/client_spec.rb
+++ b/sentry-ruby/spec/sentry/client_spec.rb
@@ -55,7 +55,7 @@ RSpec.describe Sentry::Client do
returned = subject.capture_event(event, scope)
- expect(returned).to eq(false)
+ expect(returned).to eq(nil)
end
context "when async raises an exception" do
diff --git a/sentry-ruby/spec/sentry/hub_spec.rb b/sentry-ruby/spec/sentry/hub_spec.rb
index <HASH>..<HASH> 100644
--- a/sentry-ruby/spec/sentry/hub_spec.rb
+++ b/sentry-ruby/spec/sentry/hub_spec.rb
@@ -19,6 +19,19 @@ RSpec.describe Sentry::Hub do
subject { described_class.new(client, scope) }
shared_examples "capture_helper" do
+ context "with sending_allowed? condition" do
+ before do
+ expect(configuration).to receive(:sending_allowed?).and_return(false)
+ end
+
+ it "doesn't send the event nor assign last_event_id" do
+ subject.send(capture_helper, capture_subject)
+
+ expect(transport.events).to be_empty
+ expect(subject.last_event_id).to eq(nil)
+ end
+ end
+
context "with custom attributes" do
it "updates the event with custom attributes" do
subject.send(capture_helper, capture_subject, tags: { foo: "bar" })
@@ -147,7 +160,7 @@ RSpec.describe Sentry::Hub do
describe '#capture_event' do
let(:exception) { ZeroDivisionError.new("divided by 0") }
let!(:event) do
- subject.capture_exception(exception)
+ client.event_from_exception(exception)
end
it "returns an Event instance" do
|
Fix NoMethodError when sending is not allowed (#<I>)
Here's a full description on the issue
<URL>
|
getsentry_raven-ruby
|
train
|
87da9b954140605773ec7e10abbeff4c727b78e3
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -1864,6 +1864,7 @@ Driver.prototype.receiveMsg = function (buf, senderInfo) {
addressesTo: [self.wallet.addressString],
// txData: msg.txData,
txType: msg.txType,
+ data: msg.data,
encryptedData: msg.encryptedData,
encryptedPermission: msg.encryptedPermission
}
@@ -1877,27 +1878,13 @@ Driver.prototype.receiveMsg = function (buf, senderInfo) {
})
.then(function (info) {
extend(chainedObj, info)
- return Q.ninvoke(Permission, 'recover', msg.encryptedPermission, chainedObj.sharedKey)
- })
- .then(function (permission) {
- chainedObj.permission = permission
- if (!chainedObj.permissionKey) {
- return derivePermissionKey(chainedObj)
+ if (info.txType === TxData.types.public) {
+ return loadPublicMessage()
+ } else {
+ return loadPrivateMessage()
}
})
.then(function () {
- return self.keeper.putMany([
- {
- key: chainedObj.permissionKey.toString('hex'),
- value: msg.encryptedPermission
- },
- {
- key: chainedObj.permission.fileKeyString(),
- value: msg.encryptedData
- }
- ])
- })
- .then(function () {
return self.lookupObject(chainedObj, true)
})
.then(function (obj) {
@@ -1927,6 +1914,36 @@ Driver.prototype.receiveMsg = function (buf, senderInfo) {
self._debug('processed received msg')
return self.log(entry)
})
+
+ function loadPublicMessage () {
+ // nothing to do here
+ return self.keeper.putOne({
+ key: chainedObj.key,
+ value: chainedObj.data
+ })
+ }
+
+ function loadPrivateMessage () {
+ return Q.ninvoke(Permission, 'recover', msg.encryptedPermission, chainedObj.sharedKey)
+ .then(function (permission) {
+ chainedObj.permission = permission
+ if (!chainedObj.permissionKey) {
+ return derivePermissionKey(chainedObj)
+ }
+ })
+ .then(function () {
+ return self.keeper.putMany([
+ {
+ key: chainedObj.permissionKey.toString('hex'),
+ value: msg.encryptedPermission
+ },
+ {
+ key: chainedObj.permission.fileKeyString(),
+ value: msg.encryptedData
+ }
+ ])
+ })
+ }
}
Driver.prototype.myRootHash = function () {
diff --git a/lib/utils.js b/lib/utils.js
index <HASH>..<HASH> 100644
--- a/lib/utils.js
+++ b/lib/utils.js
@@ -23,14 +23,14 @@ var PRIVATE_MSG_SCHEMA = {
txType: 'Number',
encryptedPermission: 'Buffer',
encryptedData: 'Buffer',
- txData: '?Buffer',
+ // txData: '?Buffer',
v: '?String'
}
var PUBLIC_MSG_SCHEMA = {
txType: 'Number',
data: 'Buffer',
- txData: '?Buffer',
+ // txData: '?Buffer',
v: '?String'
}
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -32,7 +32,7 @@
"@tradle/bitjoe-js": "^1.0.3",
"@tradle/bittorrent-dht": "^3.2.1",
"@tradle/chained-obj": "^2.0.4",
- "@tradle/chainloader": "^2.2.0",
+ "@tradle/chainloader": "^2.2.1",
"@tradle/constants": "^1.1.3",
"@tradle/identity": "^1.2.2",
"@tradle/kiki": "^1.1.13",
|
handle public msgs better
|
tradle_tim-old-engine
|
train
|
a719dee20fabc1ac9f5e1d00becbb634207fc7f7
|
diff --git a/db/seeds.rb b/db/seeds.rb
index <HASH>..<HASH> 100644
--- a/db/seeds.rb
+++ b/db/seeds.rb
@@ -14,6 +14,11 @@ def get_stdin(msg)
STDIN.gets.strip
end
+log 'Creating Roles...'
+super_admin_role = Role.find_or_create_by!(name: :super_admin)
+Role.find_or_create_by!(name: :admin)
+Role.find_or_create_by!(name: :clinician)
+
log 'Adding Superuser...'
email = get_stdin('Superuser email:')
@@ -24,6 +29,7 @@ if password == confirm_password
User.find_or_create_by!(email: email) do |u|
u.password = password
u.approved = true
+ u.roles = [super_admin_role]
end
else
raise 'Passwords do not match'
|
Seed a user with the :super_admin Role
|
airslie_renalware-core
|
train
|
9522bd36a3fc623ca61002f8e2811a29e2b3fe19
|
diff --git a/config/laravel-uptime-monitor.php b/config/laravel-uptime-monitor.php
index <HASH>..<HASH> 100644
--- a/config/laravel-uptime-monitor.php
+++ b/config/laravel-uptime-monitor.php
@@ -54,7 +54,7 @@ return [
/*
* The location from where you are running the uptime checks. This location will be mentioned
- * in all notifications that will be sent
+ * in all notifications that will be sent.
*/
'location' => '',
|
Update laravel-uptime-monitor.php
|
spatie_laravel-uptime-monitor
|
train
|
9a3e1e47df0614e0b52f4166b8558fe39a57f4fe
|
diff --git a/airflow/cli/commands/provider_command.py b/airflow/cli/commands/provider_command.py
index <HASH>..<HASH> 100644
--- a/airflow/cli/commands/provider_command.py
+++ b/airflow/cli/commands/provider_command.py
@@ -82,7 +82,7 @@ def hooks_list(args):
def connection_form_widget_list(args):
"""Lists all custom connection form fields at the command line"""
AirflowConsole().print_as(
- data=list(ProvidersManager().connection_form_widgets.items()),
+ data=list(sorted(ProvidersManager().connection_form_widgets.items())),
output=args.output,
mapper=lambda x: {
"connection_parameter_name": x[0],
diff --git a/airflow/providers_manager.py b/airflow/providers_manager.py
index <HASH>..<HASH> 100644
--- a/airflow/providers_manager.py
+++ b/airflow/providers_manager.py
@@ -651,9 +651,15 @@ class ProvidersManager(LoggingMixin):
"""Force-import all hooks and initialize the connections/fields"""
# Retrieve all hooks to make sure that all of them are imported
_ = list(self._hooks_lazy_dict.values())
- self._connection_form_widgets = OrderedDict(sorted(self._connection_form_widgets.items()))
self._field_behaviours = OrderedDict(sorted(self._field_behaviours.items()))
+ # Widgets for connection forms are currently used in two places:
+ # 1. In the UI Connections, expected same order that it defined in Hook.
+ # 2. cli command - `airflow providers widgets` and expected that it in alphabetical order.
+ # It is not possible to recover original ordering after sorting,
+ # that the main reason why original sorting moved to cli part:
+ # self._connection_form_widgets = OrderedDict(sorted(self._connection_form_widgets.items()))
+
def _discover_taskflow_decorators(self) -> None:
for name, info in self._provider_dict.items():
for taskflow_decorator in info.data.get("task-decorators", []):
@@ -900,7 +906,10 @@ class ProvidersManager(LoggingMixin):
@property
def connection_form_widgets(self) -> Dict[str, ConnectionFormWidgetInfo]:
- """Returns widgets for connection forms."""
+ """
+ Returns widgets for connection forms.
+ Dictionary keys in the same order that it defined in Hook.
+ """
self.initialize_providers_hooks()
self._import_info_from_all_hooks()
return self._connection_form_widgets
diff --git a/tests/core/test_providers_manager.py b/tests/core/test_providers_manager.py
index <HASH>..<HASH> 100644
--- a/tests/core/test_providers_manager.py
+++ b/tests/core/test_providers_manager.py
@@ -188,6 +188,70 @@ class TestProviderManager:
)
assert provider_manager.connection_form_widgets['extra__test__my_param'].field == widget_field
+ def test_connection_form_widgets_fields_order(self):
+ """Check that order of connection for widgets preserved by original Hook order."""
+ test_conn_type = 'test'
+ field_prefix = f'extra__{test_conn_type}__'
+ field_names = ("yyy_param", "aaa_param", "000_param", "foo", "bar", "spam", "egg")
+
+ expected_field_names_order = tuple(f"{field_prefix}{f}" for f in field_names)
+
+ class TestHook:
+ conn_type = test_conn_type
+
+ provider_manager = ProvidersManager()
+ provider_manager._connection_form_widgets = {}
+ provider_manager._add_widgets(
+ package_name='mock',
+ hook_class=TestHook,
+ widgets={f: BooleanField(lazy_gettext('Dummy param')) for f in expected_field_names_order},
+ )
+ actual_field_names_order = tuple(
+ key for key in provider_manager.connection_form_widgets.keys() if key.startswith(field_prefix)
+ )
+ assert actual_field_names_order == expected_field_names_order, "Not keeping original fields order"
+
+ def test_connection_form_widgets_fields_order_multiple_hooks(self):
+ """
+ Check that order of connection for widgets preserved by original Hooks order.
+ Even if different hooks specified field with the same connection type.
+ """
+ test_conn_type = 'test'
+ field_prefix = f'extra__{test_conn_type}__'
+ field_names_hook_1 = ("foo", "bar", "spam", "egg")
+ field_names_hook_2 = ("yyy_param", "aaa_param", "000_param")
+
+ expected_field_names_order = tuple(
+ f"{field_prefix}{f}" for f in [*field_names_hook_1, *field_names_hook_2]
+ )
+
+ class TestHook1:
+ conn_type = test_conn_type
+
+ class TestHook2:
+ conn_type = 'another'
+
+ provider_manager = ProvidersManager()
+ provider_manager._connection_form_widgets = {}
+ provider_manager._add_widgets(
+ package_name='mock',
+ hook_class=TestHook1,
+ widgets={
+ f"{field_prefix}{f}": BooleanField(lazy_gettext('Dummy param')) for f in field_names_hook_1
+ },
+ )
+ provider_manager._add_widgets(
+ package_name='another_mock',
+ hook_class=TestHook2,
+ widgets={
+ f"{field_prefix}{f}": BooleanField(lazy_gettext('Dummy param')) for f in field_names_hook_2
+ },
+ )
+ actual_field_names_order = tuple(
+ key for key in provider_manager.connection_form_widgets.keys() if key.startswith(field_prefix)
+ )
+ assert actual_field_names_order == expected_field_names_order, "Not keeping original fields order"
+
def test_field_behaviours(self):
provider_manager = ProvidersManager()
connections_with_field_behaviours = list(provider_manager.field_behaviours.keys())
|
Preserve original order of providers' connection extra fields in UI (#<I>)
* Preserve original order of providers' connection extra fields
* Sort widgets before printed in cli command `airflow providers widgets`
|
apache_airflow
|
train
|
d4624308dba2972d757758490f5981bb08cdc067
|
diff --git a/test/unit/reducers/dataReducer.spec.js b/test/unit/reducers/dataReducer.spec.js
index <HASH>..<HASH> 100644
--- a/test/unit/reducers/dataReducer.spec.js
+++ b/test/unit/reducers/dataReducer.spec.js
@@ -6,8 +6,13 @@ let collection = 'test'; // eslint-disable-line prefer-const
let action = {};
let payload = {};
let meta = {};
+let result;
describe('dataReducer', () => {
+ beforeEach(() => {
+ result = undefined;
+ });
+
it('is exported', () => {
expect(dataReducer).to.exist;
});
@@ -48,6 +53,29 @@ describe('dataReducer', () => {
);
});
+ it('merges new state with existing state', () => {
+ const doc = 'someDoc';
+ const data = { [doc]: { newData: { field: 'test' } } };
+ payload = { data };
+ meta = {
+ collection,
+ doc,
+ };
+ const existingState = {
+ [collection]: { [doc]: { originalData: { some: {} } } },
+ };
+ action = { meta, payload, type: actionTypes.LISTENER_RESPONSE };
+ result = dataReducer(existingState, action);
+ expect(result).to.have.nested.property(
+ `${collection}.${doc}.newData.field`,
+ data[doc].newData.field,
+ );
+ expect(result).to.have.nested.property(
+ `${collection}.${doc}.originalData.some`,
+ existingState[collection][doc].originalData.some,
+ );
+ });
+
describe('with subcollections parameter', () => {
it('updates empty state', () => {
const data = { abc: { field: 'test' } };
@@ -202,5 +230,67 @@ describe('dataReducer', () => {
expect(dataReducer(data, action)).to.have.property('some', data.some);
});
});
+
+ describe('LISTENER_ERROR', () => {
+ it('sets state to null for collection', () => {
+ const data = { testing: { field: 'test' } };
+ action = {
+ meta: { collection },
+ payload: { data },
+ type: actionTypes.LISTENER_ERROR,
+ };
+ result = dataReducer(state, action);
+ expect(result).to.have.property(collection);
+ expect(result[collection]).to.be.null;
+ });
+
+ it('preserves existing state (to not run over existing data)', () => {
+ const data = { testing: { field: 'test' } };
+ action = {
+ meta: { collection },
+ payload: { data },
+ type: actionTypes.LISTENER_ERROR,
+ };
+ result = dataReducer({ [collection]: {} }, action);
+ expect(result).to.have.property(collection);
+ expect(result[collection]).to.be.an('object');
+ });
+
+ it('throws if meta does not contain collection', () => {
+ payload = {};
+ action = { meta: {}, payload, type: actionTypes.LISTENER_ERROR };
+ expect(() => dataReducer(state, action)).to.throw(
+ 'Collection is required to construct reducer path.',
+ );
+ });
+
+ describe('preserve parameter', () => {
+ it('list of keys preserve state', () => {
+ const data = { testing: { field: 'test' } };
+ action = {
+ meta: { collection },
+ payload: { data },
+ preserve: { data: [collection] },
+ type: actionTypes.LISTENER_ERROR,
+ };
+ result = dataReducer({ [collection]: {} }, action);
+ expect(result).to.have.property(collection);
+ expect(result[collection]).to.be.an('object');
+ });
+
+ it('list of keys preserve state', () => {
+ const data = { testing: { field: 'test' } };
+ action = {
+ meta: { collection },
+ payload: { data },
+ preserve: { data: currentState => currentState },
+ type: actionTypes.LISTENER_ERROR,
+ };
+ result = dataReducer({ [collection]: {} }, action);
+ expect(result).to.have.property(collection);
+ expect(result[collection]).to.be.an('object');
+ });
+ });
+ });
});
});
|
feat(dataReducer): LISTENER_ERROR case now has unit tests
|
prescottprue_redux-firestore
|
train
|
97360c71111e452cb3f8473880d64f685eb9ea82
|
diff --git a/lib/hello_sign/parameters/unclaimed_draft.rb b/lib/hello_sign/parameters/unclaimed_draft.rb
index <HASH>..<HASH> 100644
--- a/lib/hello_sign/parameters/unclaimed_draft.rb
+++ b/lib/hello_sign/parameters/unclaimed_draft.rb
@@ -3,7 +3,7 @@ require 'hello_sign/file'
module HelloSign
module Parameters
class UnclaimedDraft
- attr_writer :files, :upload_io_source
+ attr_writer :files
def formatted
{file: files}
diff --git a/lib/hello_sign/proxy/account.rb b/lib/hello_sign/proxy/account.rb
index <HASH>..<HASH> 100644
--- a/lib/hello_sign/proxy/account.rb
+++ b/lib/hello_sign/proxy/account.rb
@@ -4,7 +4,6 @@ module HelloSign
module Proxy
class Account
attr_reader :client
- attr_writer :settings_proxy_source
def initialize(client)
@client = client
|
Remove unnecessary attr_writers
|
craiglittle_hello_sign
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.