hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
f5ba99fd24ce2e7cdba7c81153c46df14811d193
|
diff --git a/lib/puppet/indirector/request.rb b/lib/puppet/indirector/request.rb
index <HASH>..<HASH> 100644
--- a/lib/puppet/indirector/request.rb
+++ b/lib/puppet/indirector/request.rb
@@ -60,6 +60,13 @@ class Puppet::Indirector::Request
rescue => detail
raise ArgumentError, "Could not understand URL %s: %s" % [source, detail.to_s]
end
+
+ # Just short-circuit these to full paths
+ if uri.scheme == "file"
+ @key = uri.path
+ return
+ end
+
@server = uri.host if uri.host
# If the URI class can look up the scheme, it will provide a port,
diff --git a/spec/unit/indirector/request.rb b/spec/unit/indirector/request.rb
index <HASH>..<HASH> 100755
--- a/spec/unit/indirector/request.rb
+++ b/spec/unit/indirector/request.rb
@@ -77,6 +77,26 @@ describe Puppet::Indirector::Request do
end
describe "and the request key is a URI" do
+ describe "and the URI is a 'file' URI" do
+ before do
+ @request = Puppet::Indirector::Request.new(:ind, :method, "file:///my/file")
+ end
+
+ it "should set the request key to the full file path" do @request.key.should == "/my/file" end
+
+ it "should not set the protocol" do
+ @request.protocol.should be_nil
+ end
+
+ it "should not set the port" do
+ @request.port.should be_nil
+ end
+
+ it "should not set the server" do
+ @request.server.should be_nil
+ end
+ end
+
it "should set the protocol to the URI scheme" do
Puppet::Indirector::Request.new(:ind, :method, "http://host/stuff").protocol.should == "http"
end
@@ -98,7 +118,7 @@ describe Puppet::Indirector::Request do
Puppet::Indirector::Request.new(:ind, :method, "http://host/stuff").port.should == 80
end
- it "should set the request key to the path from the URI" do
+ it "should set the request key to the unqualified path from the URI" do
Puppet::Indirector::Request.new(:ind, :method, "http:///stuff").key.should == "stuff"
end
|
Special-casing 'file' URIs in the indirection requests.
These just get converted to full file paths, since
we know they will never pass over the wire.
|
puppetlabs_puppet
|
train
|
6d4b61007bddd46d2cdcfaad4ad5f57484f31c1c
|
diff --git a/integration/client/export_test.go b/integration/client/export_test.go
index <HASH>..<HASH> 100644
--- a/integration/client/export_test.go
+++ b/integration/client/export_test.go
@@ -60,7 +60,7 @@ func TestExport(t *testing.T) {
t.Fatal(err)
}
- // Seet to begining of file before passing it to assertOCITar()
+ // Seek to beginning of file before passing it to assertOCITar()
dstFile.Seek(0, 0)
assertOCITar(t, dstFile)
}
|
integration/client: fix typo in export_test.go
Seet -> Seek
begining -> beginning
|
containerd_containerd
|
train
|
7adcb69aee78b9f271f77c797e8ac0e78995195a
|
diff --git a/zzk/virtualips/virtualips.go b/zzk/virtualips/virtualips.go
index <HASH>..<HASH> 100644
--- a/zzk/virtualips/virtualips.go
+++ b/zzk/virtualips/virtualips.go
@@ -30,7 +30,7 @@ RemoveAllVirtualIPs removes (unbinds) all virtual IPs on the agent
*/
func RemoveAllVirtualIPs() error {
// confirm the virtual IP is on this host and remove it
- err, interfaceMap := createVirtualInterfaceMap()
+ interfaceMap, err := createVirtualInterfaceMap()
if err != nil {
glog.Warningf("Creating virtual interface map failed")
return err
@@ -364,14 +364,14 @@ func generateInterfaceName(virtualIP pool.VirtualIP, virtualInterfaceIndex int)
}
// create an interface map of virtual interfaces configured on the agent
-func createVirtualInterfaceMap() (error, map[string]pool.VirtualIP) {
+func createVirtualInterfaceMap() (map[string]pool.VirtualIP, error) {
interfaceMap := make(map[string]pool.VirtualIP)
//ip addr show | awk '/zvip/{print $NF}'
virtualInterfaceNames, err := exec.Command("bash", "-c", "ip addr show | awk '/"+virtualInterfacePrefix+"/{print $NF}'").CombinedOutput()
if err != nil {
glog.Warningf("Determining virtual interfaces failed: %v", err)
- return err, interfaceMap
+ return interfaceMap, err
}
glog.V(2).Infof("Control plane virtual interfaces: %v", string(virtualInterfaceNames))
@@ -379,7 +379,7 @@ func createVirtualInterfaceMap() (error, map[string]pool.VirtualIP) {
bindInterfaceAndIndex := strings.Split(virtualInterfaceName, virtualInterfacePrefix)
if len(bindInterfaceAndIndex) != 2 {
err := fmt.Errorf("Unexpected interface format: %v", bindInterfaceAndIndex)
- return err, interfaceMap
+ return interfaceMap, err
}
bindInterface := strings.TrimSpace(string(bindInterfaceAndIndex[0]))
@@ -387,26 +387,26 @@ func createVirtualInterfaceMap() (error, map[string]pool.VirtualIP) {
virtualIPAddressAndCIDR, err := exec.Command("bash", "-c", "ip addr show | awk '/"+virtualInterfaceName+"/ {print $2}'").CombinedOutput()
if err != nil {
glog.Warningf("Determining IP address of interface %v failed: %v", virtualInterfaceName, err)
- return err, interfaceMap
+ return interfaceMap, err
}
virtualIPAddress, network, err := net.ParseCIDR(strings.TrimSpace(string(virtualIPAddressAndCIDR)))
if err != nil {
- return err, interfaceMap
+ return interfaceMap, err
}
netmask := net.IP(network.Mask)
interfaceMap[virtualInterfaceName] = pool.VirtualIP{PoolID: "", IP: virtualIPAddress.String(), Netmask: netmask.String(), BindInterface: bindInterface}
}
- return nil, interfaceMap
+ return interfaceMap, nil
}
// add (bind) a virtual IP on the agent
func addVirtualIP(virtualIPToAdd pool.VirtualIP, virtualInterfaceIndex int) error {
// confirm the virtual IP is not already on this host
virtualIPAlreadyHere := false
- err, interfaceMap := createVirtualInterfaceMap()
+ interfaceMap, err := createVirtualInterfaceMap()
if err != nil {
glog.Warningf("Creating virtual interface map failed")
return err
@@ -436,7 +436,7 @@ func addVirtualIP(virtualIPToAdd pool.VirtualIP, virtualInterfaceIndex int) erro
// remove (unbind) a virtual IP from the agent
func removeVirtualIP(virtualIPAddress string) error {
// confirm the VIP is on this host and remove it
- err, interfaceMap := createVirtualInterfaceMap()
+ interfaceMap, err := createVirtualInterfaceMap()
if err != nil {
glog.Warningf("Creating virtual interface map failed")
return err
|
switch return order... error is always last
|
control-center_serviced
|
train
|
d75db0ea1a6f56294b7e69bcc4a1002f8909ab8b
|
diff --git a/spec/api-browser-window-spec.js b/spec/api-browser-window-spec.js
index <HASH>..<HASH> 100644
--- a/spec/api-browser-window-spec.js
+++ b/spec/api-browser-window-spec.js
@@ -256,7 +256,6 @@ describe('BrowserWindow module', function () {
w.loadURL(server.url)
})
-
it('sets the content type header on multi part forms', function (done) {
w.webContents.on('did-finish-load', () => {
w.webContents.session.webRequest.onBeforeSendHeaders((details, callback) => {
@@ -279,7 +278,7 @@ describe('BrowserWindow module', function () {
w.loadURL(server.url)
})
})
-
+
it('should support support base url for data urls', (done) => {
ipcMain.once('answer', function (event, test) {
assert.equal(test, 'test')
|
Fixed js lint issues.
|
electron_electron
|
train
|
94c92455ea9c717bb98bfee45188dfea6065beb3
|
diff --git a/eZ/Publish/Core/MVC/Symfony/Templating/Twig/Extension/ContentExtension.php b/eZ/Publish/Core/MVC/Symfony/Templating/Twig/Extension/ContentExtension.php
index <HASH>..<HASH> 100644
--- a/eZ/Publish/Core/MVC/Symfony/Templating/Twig/Extension/ContentExtension.php
+++ b/eZ/Publish/Core/MVC/Symfony/Templating/Twig/Extension/ContentExtension.php
@@ -158,6 +158,10 @@ class ContentExtension extends Twig_Extension
new Twig_SimpleFunction(
'ez_content_name',
array( $this, 'getContentNameTranslated' )
+ ),
+ new Twig_SimpleFunction(
+ 'ez_field_value',
+ array( $this, 'getTranslatedFieldValue' )
)
);
}
@@ -526,4 +530,16 @@ class ContentExtension extends Twig_Extension
{
return $this->contentHelper->getTranslatedName( $content, $forcedLanguage );
}
+
+ /**
+ * @param \eZ\Publish\Core\Repository\Values\Content\Content $content
+ * @param string $fieldDefIdentifier Identifier for the field we want to get the value from.
+ * @param string $forcedLanguage Locale we want the content name translation in (e.g. "fre-FR"). Null by default (takes current locale).
+ *
+ * @return mixed A primitive type or a field type Value object depending on the field type.
+ */
+ public function getTranslatedFieldValue( Content $content, $fieldDefIdentifier, $forcedLanguage = null )
+ {
+ return $this->contentHelper->getTranslatedField( $content, $fieldDefIdentifier, $forcedLanguage )->value;
+ }
}
|
Fix EZP-<I>: As a developer, I want to access a field value in the current locale in a Twig template
|
ezsystems_ezpublish-kernel
|
train
|
c8c4832794c42ae67f0d57590fdb90a458653d51
|
diff --git a/rllib/evaluation/worker_set.py b/rllib/evaluation/worker_set.py
index <HASH>..<HASH> 100644
--- a/rllib/evaluation/worker_set.py
+++ b/rllib/evaluation/worker_set.py
@@ -64,15 +64,15 @@ class WorkerSet:
trainer_config,
{"tf_session_args": trainer_config["local_tf_session_args"]})
+ # Create a number of remote workers
+ self._remote_workers = []
+ self.add_workers(num_workers)
+
# Always create a local worker
self._local_worker = self._make_worker(RolloutWorker, env_creator,
self._policy_class, 0,
self._local_config)
- # Create a number of remote workers
- self._remote_workers = []
- self.add_workers(num_workers)
-
def local_worker(self) -> RolloutWorker:
"""Return the local rollout worker."""
return self._local_worker
|
Prevent Local Worker creation from blocking remote worker creation by creating remote workers before local worker (#<I>)
* create remote workers before local worker
* reformatted
|
ray-project_ray
|
train
|
277b1ca32e605c694a78b81befee0b38e5ab1705
|
diff --git a/atomic_reactor/plugin.py b/atomic_reactor/plugin.py
index <HASH>..<HASH> 100644
--- a/atomic_reactor/plugin.py
+++ b/atomic_reactor/plugin.py
@@ -204,11 +204,10 @@ class PluginsRunner(object):
logger.debug("running plugin '%s'", plugin_name)
- plugin_instance = self.create_instance_from_plugin(plugin_class, plugin_conf)
- start_time = datetime.datetime.now()
- self.save_plugin_timestamp(plugin_instance.key, start_time)
-
try:
+ plugin_instance = self.create_instance_from_plugin(plugin_class, plugin_conf)
+ start_time = datetime.datetime.now()
+ self.save_plugin_timestamp(plugin_class.key, start_time)
plugin_response = plugin_instance.run()
except AutoRebuildCanceledException as ex:
# if auto rebuild is canceled, then just reraise
@@ -218,7 +217,7 @@ class PluginsRunner(object):
# AutoRebuildCanceledException was raised here)
raise
except Exception as ex:
- msg = "plugin '%s' raised an exception: %r" % (plugin_instance.key, ex)
+ msg = "plugin '%s' raised an exception: %r" % (plugin_class.key, ex)
logger.debug(traceback.format_exc())
if plugin_is_allowed_to_fail or keep_going:
logger.warning(msg)
@@ -226,7 +225,7 @@ class PluginsRunner(object):
if not plugin_is_allowed_to_fail:
failed_msgs.append(msg)
else:
- self.on_plugin_failed(plugin_instance.key, ex)
+ self.on_plugin_failed(plugin_class.key, ex)
logger.error(msg)
raise PluginFailedException(msg)
@@ -237,11 +236,11 @@ class PluginsRunner(object):
duration = finish_time - start_time
seconds = duration.total_seconds()
logger.debug("plugin '%s' finished in %ds", plugin_name, seconds)
- self.save_plugin_duration(plugin_instance.key, seconds)
+ self.save_plugin_duration(plugin_class.key, seconds)
except Exception:
- logger.exception("failed to save plugin duration")
+ logger.error("failed to save plugin duration")
- self.plugins_results[plugin_instance.key] = plugin_response
+ self.plugins_results[plugin_class.key] = plugin_response
if len(failed_msgs) == 1:
raise PluginFailedException(failed_msgs[0])
elif len(failed_msgs) > 1:
|
Mark plugin as failed if plugin crashed on init
|
projectatomic_atomic-reactor
|
train
|
f82684d56b38532b983f1b8f8e7e0bd324ca7c17
|
diff --git a/src/main/php/serializer/delegate/Fragment.php b/src/main/php/serializer/delegate/Fragment.php
index <HASH>..<HASH> 100644
--- a/src/main/php/serializer/delegate/Fragment.php
+++ b/src/main/php/serializer/delegate/Fragment.php
@@ -19,7 +19,7 @@ class Fragment implements XmlSerializerDelegate
/**
* name of tag
*
- * @var string
+ * @var string|null
*/
protected $tagName;
/**
diff --git a/src/main/php/serializer/delegate/Tag.php b/src/main/php/serializer/delegate/Tag.php
index <HASH>..<HASH> 100644
--- a/src/main/php/serializer/delegate/Tag.php
+++ b/src/main/php/serializer/delegate/Tag.php
@@ -19,13 +19,13 @@ class Tag implements XmlSerializerDelegate
/**
* name of tag
*
- * @var string
+ * @var string|null
*/
protected $tagName;
/**
* recurring element tag name for lists
*
- * @var string
+ * @var string|null
*/
protected $elementTagName;
|
describe as null what may be null
|
stubbles_stubbles-xml
|
train
|
eb5154c1f60ab03ccb5439e54e577de3321ba873
|
diff --git a/lib/rack/cerberus.rb b/lib/rack/cerberus.rb
index <HASH>..<HASH> 100644
--- a/lib/rack/cerberus.rb
+++ b/lib/rack/cerberus.rb
@@ -106,7 +106,7 @@ module Rack
[
401, {'Content-Type' => 'text/html'},
[AUTH_PAGE % @options.merge({
- error: error, submit_path: req.env['REQUEST_URI'],
+ error: error, submit_path: h(req.env['REQUEST_URI']),
request_method: req.request_method,
login: h(login(req)),
pass: h(pass(req))
|
Update cerberus.rb
This should fix a small reflected XSS which is present in the current version.
|
mig-hub_cerberus
|
train
|
fc30a49922295d1cf58ed69eb2d8caa8a8b7fb59
|
diff --git a/src/Sulu/Bundle/CoreBundle/DependencyInjection/Compiler/RequestAnalyzerCompilerPass.php b/src/Sulu/Bundle/CoreBundle/DependencyInjection/Compiler/RequestAnalyzerCompilerPass.php
index <HASH>..<HASH> 100644
--- a/src/Sulu/Bundle/CoreBundle/DependencyInjection/Compiler/RequestAnalyzerCompilerPass.php
+++ b/src/Sulu/Bundle/CoreBundle/DependencyInjection/Compiler/RequestAnalyzerCompilerPass.php
@@ -55,7 +55,7 @@ class RequestAnalyzerCompilerPass implements CompilerPassInterface
);
// add listener to event dispatcher
- $eventDispatcher = $container->getDefinition('event_dispatcher');
+ $eventDispatcher = $container->findDefinition('event_dispatcher');
$eventDispatcher->addMethodCall(
'addListenerService',
array(
|
changed getDefinition to findDefinition
|
sulu_sulu
|
train
|
b1cb8e0981cde6c89b0a0f88ea8f5d75b0827b60
|
diff --git a/javascript/atoms/events.js b/javascript/atoms/events.js
index <HASH>..<HASH> 100644
--- a/javascript/atoms/events.js
+++ b/javascript/atoms/events.js
@@ -19,7 +19,12 @@
goog.provide('bot.events');
+goog.provide('bot.events.EventArgs');
goog.provide('bot.events.EventType');
+goog.provide('bot.events.KeyboardArgs');
+goog.provide('bot.events.MouseArgs');
+goog.provide('bot.events.Touch');
+goog.provide('bot.events.TouchArgs');
goog.require('bot.Error');
goog.require('bot.ErrorCode');
|
DanielWagnerHall: Export types - not sure how I missed this file some number of commits ago
r<I>
|
SeleniumHQ_selenium
|
train
|
b2c9b7088c933731795f4750bc8f8845b0e6313a
|
diff --git a/core-bundle/tests/Session/Attribute/AttributeBagMirrorTest.php b/core-bundle/tests/Session/Attribute/AttributeBagMirrorTest.php
index <HASH>..<HASH> 100644
--- a/core-bundle/tests/Session/Attribute/AttributeBagMirrorTest.php
+++ b/core-bundle/tests/Session/Attribute/AttributeBagMirrorTest.php
@@ -26,10 +26,10 @@ class AttributeBagAdapterTest extends \PHPUnit_Framework_TestCase
public function testInstantiation()
{
$attributeBag = new AttributeBag('foobar_storageKey');
- $mirror = new AttributeBagAdapter($attributeBag);
+ $adapter = new AttributeBagAdapter($attributeBag);
- $this->assertInstanceOf('Contao\CoreBundle\Session\Attribute\AttributeBagAdapter', $mirror);
- $this->assertInstanceOf('ArrayAccess', $mirror);
+ $this->assertInstanceOf('Contao\CoreBundle\Session\Attribute\AttributeBagAdapter', $adapter);
+ $this->assertInstanceOf('ArrayAccess', $adapter);
}
/**
@@ -38,9 +38,9 @@ class AttributeBagAdapterTest extends \PHPUnit_Framework_TestCase
public function testOffsetSet()
{
$attributeBag = new AttributeBag('foobar_storageKey');
- $mirror = new AttributeBagAdapter($attributeBag);
+ $adapter = new AttributeBagAdapter($attributeBag);
- $mirror['foo'] = 'bar';
+ $adapter['foo'] = 'bar';
$this->assertSame('bar', $attributeBag->get('foo'));
}
@@ -51,11 +51,11 @@ class AttributeBagAdapterTest extends \PHPUnit_Framework_TestCase
public function testOffsetExists()
{
$attributeBag = new AttributeBag('foobar_storageKey');
- $mirror = new AttributeBagAdapter($attributeBag);
+ $adapter = new AttributeBagAdapter($attributeBag);
- $mirror['foo'] = 'bar';
+ $adapter['foo'] = 'bar';
- $this->assertTrue(isset($mirror['foo']));
+ $this->assertTrue(isset($adapter['foo']));
}
/**
@@ -64,11 +64,11 @@ class AttributeBagAdapterTest extends \PHPUnit_Framework_TestCase
public function testOffsetGet()
{
$attributeBag = new AttributeBag('foobar_storageKey');
- $mirror = new AttributeBagAdapter($attributeBag);
+ $adapter = new AttributeBagAdapter($attributeBag);
$attributeBag->set('foo', 'bar');
- $this->assertSame('bar', $mirror['foo']);
+ $this->assertSame('bar', $adapter['foo']);
}
/**
@@ -77,11 +77,11 @@ class AttributeBagAdapterTest extends \PHPUnit_Framework_TestCase
public function testOffsetUnset()
{
$attributeBag = new AttributeBag('foobar_storageKey');
- $mirror = new AttributeBagAdapter($attributeBag);
+ $adapter = new AttributeBagAdapter($attributeBag);
$attributeBag->set('foo', 'bar');
- unset($mirror['foo']);
+ unset($adapter['foo']);
$this->assertFalse($attributeBag->has('foo'));
}
|
[Core] Also adjusted variable names¨
|
contao_contao
|
train
|
6d96299fddf00df8d799876a99783daa5c21107c
|
diff --git a/bootstrap/bootstrap.php b/bootstrap/bootstrap.php
index <HASH>..<HASH> 100644
--- a/bootstrap/bootstrap.php
+++ b/bootstrap/bootstrap.php
@@ -9,6 +9,7 @@ if ( ! extension_loaded('mongo')) {
exit(1);
}
+use Mongolid\Mongolid\Container\Ioc;
use Illuminate\Container\Container;
$container = new Container;
@@ -25,4 +26,4 @@ $requiredResources = array(
$container->bind($requiredResources);
-\Mongolid\Mongolid\Container\IOC::setContainer($container);
+Ioc::setContainer($container);
diff --git a/src/Mongolid/Mongolid/Connection/Connection.php b/src/Mongolid/Mongolid/Connection/Connection.php
index <HASH>..<HASH> 100644
--- a/src/Mongolid/Mongolid/Connection/Connection.php
+++ b/src/Mongolid/Mongolid/Connection/Connection.php
@@ -1,7 +1,7 @@
<?php namespace Mongolid\Mongolid\Connection;
use MongoConnectionException;
-use Mongolid\Mongolid\Container\IOC;
+use Mongolid\Mongolid\Container\Ioc;
/**
* Responsable for creates a new or reuse a connection with DB.
@@ -28,7 +28,7 @@ class Connection
}
try {
- $connection = IOC::make('MongoClient', [$connectionString, []]);
+ $connection = Ioc::make('MongoClient', [$connectionString, []]);
static::$sharedConnection = $connection;
} catch (MongoConnectionException $e) {
throw new MongoConnectionException("Failed to connect with string: $connectionString", 1, $e);
diff --git a/src/Mongolid/Mongolid/Container/Ioc.php b/src/Mongolid/Mongolid/Container/Ioc.php
index <HASH>..<HASH> 100644
--- a/src/Mongolid/Mongolid/Container/Ioc.php
+++ b/src/Mongolid/Mongolid/Container/Ioc.php
@@ -5,7 +5,7 @@ use Illuminate\Container\Container as IlluminateContainer;
/**
* This class is a simple Facade for a Illuminate\Container\Container.
*/
-class IOC
+class Ioc
{
/**
* Illuminate instance.
diff --git a/tests/Mongolid/Connection/ConnectionTest.php b/tests/Mongolid/Connection/ConnectionTest.php
index <HASH>..<HASH> 100644
--- a/tests/Mongolid/Connection/ConnectionTest.php
+++ b/tests/Mongolid/Connection/ConnectionTest.php
@@ -2,7 +2,7 @@
use TestCase;
use Mockery as m;
-use Mongolid\Mongolid\Container\IOC;
+use Mongolid\Mongolid\Container\Ioc;
class ConnectionTest extends TestCase
{
@@ -19,9 +19,9 @@ class ConnectionTest extends TestCase
{
// Arrange
$mongoClientMock = m::mock('MongoClient');
- $connector = IOC::make('Mongolid\Mongolid\Connection\Connection');
+ $connector = Ioc::make('Mongolid\Mongolid\Connection\Connection');
- IOC::instance('MongoClient', $mongoClientMock);
+ Ioc::instance('MongoClient', $mongoClientMock);
// Act
$connector->createConnection();
@@ -33,7 +33,7 @@ class ConnectionTest extends TestCase
public function testShouldNotCreateAConnectionWithAlreadyCreatedOne()
{
// Arrange
- $connector = IOC::make('Mongolid\Mongolid\Connection\Connection');
+ $connector = Ioc::make('Mongolid\Mongolid\Connection\Connection');
$mock = m::mock('MongoClient');
$connector::$sharedConnection = $mock;
@@ -50,7 +50,7 @@ class ConnectionTest extends TestCase
public function testShouldRaiseExceptionForAConnectionStringInvalid()
{
// Arrange
- $connector = IOC::make('Mongolid\Mongolid\Connection\Connection');
+ $connector = Ioc::make('Mongolid\Mongolid\Connection\Connection');
// Act
$connector->createConnection();
|
renamed IOC to Ioc
|
leroy-merlin-br_mongolid
|
train
|
f835ed8d8c7db511612f4bb5ded42fda41778de6
|
diff --git a/lib/checks/aria/valid-attr-value.js b/lib/checks/aria/valid-attr-value.js
index <HASH>..<HASH> 100644
--- a/lib/checks/aria/valid-attr-value.js
+++ b/lib/checks/aria/valid-attr-value.js
@@ -15,6 +15,12 @@ const preChecks = {
node.getAttribute('aria-expanded') !== 'false' &&
node.getAttribute('aria-selected') !== 'false'
);
+ },
+ // aria-owns should only check if element exists if the element
+ // doesn't have aria-expanded=false (combobox)
+ // @see https://github.com/dequelabs/axe-core/issues/1524
+ 'aria-owns': function() {
+ return node.getAttribute('aria-expanded') !== 'false';
}
};
diff --git a/test/checks/aria/valid-attr-value.js b/test/checks/aria/valid-attr-value.js
index <HASH>..<HASH> 100644
--- a/test/checks/aria/valid-attr-value.js
+++ b/test/checks/aria/valid-attr-value.js
@@ -177,6 +177,34 @@ describe('aria-valid-attr-value', function() {
);
});
+ it('should pass on aria-owns and aria-expanded=false when the element is not in the DOM', function() {
+ fixtureSetup(
+ '<button aria-owns="test" aria-expanded="false">Button</button>'
+ );
+ var passing1 = fixture.querySelector('button');
+ assert.isTrue(
+ checks['aria-valid-attr-value'].evaluate.call(checkContext, passing1)
+ );
+ });
+
+ it('should fail on aria-owns and aria-expanded=true when the element is not in the DOM', function() {
+ fixtureSetup(
+ '<button aria-owns="test" aria-expanded="true">Button</button>'
+ );
+ var failing1 = fixture.querySelector('button');
+ assert.isFalse(
+ checks['aria-valid-attr-value'].evaluate.call(checkContext, failing1)
+ );
+ });
+
+ it('should fail on aria-owns when the element is not in the DOM', function() {
+ fixtureSetup('<button aria-owns="test">Button</button>');
+ var failing1 = fixture.querySelector('button');
+ assert.isFalse(
+ checks['aria-valid-attr-value'].evaluate.call(checkContext, failing1)
+ );
+ });
+
describe('options', function() {
it('should exclude supplied attributes', function() {
fixture.innerHTML =
|
fix(aria-valid-attr-value): allow aria-owns to pass when element is not in the DOM (#<I>)
* fix(aria-valid-attr-value): allow aria-owns to pass when element is not in the DOM
* add missing test
|
dequelabs_axe-core
|
train
|
303cd4be64d6a5027eb80b7c13000fb3877e83d1
|
diff --git a/client/post-editor/controller.js b/client/post-editor/controller.js
index <HASH>..<HASH> 100644
--- a/client/post-editor/controller.js
+++ b/client/post-editor/controller.js
@@ -110,11 +110,9 @@ module.exports = {
const postType = determinePostType( context );
const postID = getPostID( context );
- function startEditing() {
- const site = sites.getSite( route.getSiteFragment( context.path ) );
-
+ function startEditing( siteId ) {
context.store.dispatch( setEditorPostId( postID ) );
- context.store.dispatch( editPost( { type: postType }, site.ID, postID ) );
+ context.store.dispatch( editPost( { type: postType }, siteId, postID ) );
if ( maybeRedirect( context ) ) {
return;
@@ -132,7 +130,7 @@ module.exports = {
// in the view components
if ( postID ) {
// TODO: REDUX - remove flux actions when whole post-editor is reduxified
- actions.startEditingExisting( site.ID, postID );
+ actions.startEditingExisting( siteId, postID );
analytics.pageView.record( '/' + postType + '/:blogid/:postid', gaTitle + ' > Edit' );
} else {
let postOptions = { type: postType };
@@ -148,28 +146,30 @@ module.exports = {
}
// TODO: REDUX - remove flux actions when whole post-editor is reduxified
- actions.startEditingNew( site.ID, postOptions );
+ actions.startEditingNew( siteId, postOptions );
analytics.pageView.record( '/' + postType, gaTitle + ' > New' );
}
}
- if ( sites.initialized ) {
- startEditing();
- } else {
- // The site selection flow in the siteSelection route middleware
- // will cause the change handler here to be invoked before site is
- // set in Redux store. To account for this, we continue to check
- // state for site ID to have been set.
- function startEditingOnSitesInitialized() {
- if ( getSelectedSiteId( context.store.getState() ) ) {
- startEditing();
- } else {
- sites.once( 'change', startEditingOnSitesInitialized );
- }
+ // Before starting to edit, we want to be sure that we have a valid
+ // selected site to work with. Therefore, we wait on the following
+ // conditions:
+ // - Sites have not yet been initialized (no localStorage available)
+ // - Sites are initialized, but the site ID is unknown, so we wait for
+ // the sites list to be refreshed (for example, if the user does not
+ // have permission to view the site)
+ // - Sites are initialized _and_ fetched, but the selected site has
+ // not yet been selected, so is not available in global state yet
+ function startEditingOnSiteSelected() {
+ const siteId = getSelectedSiteId( context.store.getState() );
+
+ if ( siteId ) {
+ startEditing( siteId );
+ } else {
+ sites.once( 'change', startEditingOnSiteSelected );
}
-
- sites.once( 'change', startEditingOnSitesInitialized );
}
+ startEditingOnSiteSelected();
renderEditor( context, postType );
},
|
Editor: Harden routing against users without site visibility
|
Automattic_wp-calypso
|
train
|
e6770dfdc3247caf0ef5c9911e431ca3025d4b3d
|
diff --git a/Request/Base.php b/Request/Base.php
index <HASH>..<HASH> 100644
--- a/Request/Base.php
+++ b/Request/Base.php
@@ -112,17 +112,13 @@ class Base
*/
public function __construct(?array $data = [])
{
- $this->data = $data = array_merge($_POST, $_FILES);;
-
- if (
- isset(getallheaders()['Content-Type']) &&
- (
- str_contains(strtolower(getallheaders()['Content-Type']), 'json') ||
- str_contains(strtolower(getallheaders()['Content-Type']), 'javascript')
- )
- ) {
+ $this->data = $data = array_merge($_POST, $_FILES);
+
+ try {
$json = json_decode(file_get_contents("php://input"), true);
$this->data = array_merge($this->data, is_array($json) ? $json : []);
+ } catch (Exception $e) {
+ // do nothing
}
if ($this->data !== []) {
@@ -149,6 +145,10 @@ class Base
$this->rules = $this->rules();
}
+ if ($this->messages == [] && count(is_array($this->messages()) ? $this->messages() : []) > 0) {
+ $this->messages = $this->messages();
+ }
+
/**
* Run the validate method if request has rules
*/
|
feat: try to convert input data into an array
|
modulusphp_http
|
train
|
a4c9d720fd96417a85fe766e8fa766b9b71c9d18
|
diff --git a/src/server/auth/server/api_server.go b/src/server/auth/server/api_server.go
index <HASH>..<HASH> 100644
--- a/src/server/auth/server/api_server.go
+++ b/src/server/auth/server/api_server.go
@@ -179,6 +179,7 @@ func NewAuthServer(pachdAddress string, etcdAddress string, etcdPrefix string) (
nil,
&authclient.Groups{},
nil,
+ nil,
),
groups: col.NewCollection(
etcdClient,
@@ -186,6 +187,7 @@ func NewAuthServer(pachdAddress string, etcdAddress string, etcdPrefix string) (
nil,
&authclient.Users{},
nil,
+ nil,
),
}
go s.getPachClient() // initialize connection to Pachd
@@ -1286,7 +1288,7 @@ func (a *apiServer) RevokeAuthToken(ctx context.Context, req *authclient.RevokeA
func (a *apiServer) SetGroupsForUser(ctx context.Context, req *authclient.SetGroupsForUserRequest) (resp *authclient.SetGroupsForUserResponse, retErr error) {
a.LogReq(req)
defer func(start time.Time) { a.LogResp(req, resp, retErr, time.Since(start)) }(time.Now())
- if !a.isActivated() {
+ if a.activationState() != full {
return nil, authclient.ErrNotActivated
}
@@ -1362,7 +1364,7 @@ func (a *apiServer) SetGroupsForUser(ctx context.Context, req *authclient.SetGro
func (a *apiServer) ModifyMembers(ctx context.Context, req *authclient.ModifyMembersRequest) (resp *authclient.ModifyMembersResponse, retErr error) {
a.LogReq(req)
defer func(start time.Time) { a.LogResp(req, resp, retErr, time.Since(start)) }(time.Now())
- if !a.isActivated() {
+ if a.activationState() != full {
return nil, authclient.ErrNotActivated
}
@@ -1450,7 +1452,7 @@ func removeFromSet(set map[string]bool, elems ...string) map[string]bool {
func (a *apiServer) GetGroups(ctx context.Context, req *authclient.GetGroupsRequest) (resp *authclient.GetGroupsResponse, retErr error) {
a.LogReq(req)
defer func(start time.Time) { a.LogResp(req, resp, retErr, time.Since(start)) }(time.Now())
- if !a.isActivated() {
+ if a.activationState() != full {
return nil, authclient.ErrNotActivated
}
@@ -1512,7 +1514,7 @@ func (a *apiServer) GetGroups(ctx context.Context, req *authclient.GetGroupsRequ
func (a *apiServer) GetUsers(ctx context.Context, req *authclient.GetUsersRequest) (resp *authclient.GetUsersResponse, retErr error) {
a.LogReq(req)
defer func(start time.Time) { a.LogResp(req, resp, retErr, time.Since(start)) }(time.Now())
- if !a.isActivated() {
+ if a.activationState() != full {
return nil, authclient.ErrNotActivated
}
|
Add nil checker to collection creation and use the new auth activation check
|
pachyderm_pachyderm
|
train
|
054fe240ed2933a288f0e106bd7e8395dedf8311
|
diff --git a/underfs/swift/src/main/java/alluxio/underfs/swift/SwiftUnderFileSystem.java b/underfs/swift/src/main/java/alluxio/underfs/swift/SwiftUnderFileSystem.java
index <HASH>..<HASH> 100644
--- a/underfs/swift/src/main/java/alluxio/underfs/swift/SwiftUnderFileSystem.java
+++ b/underfs/swift/src/main/java/alluxio/underfs/swift/SwiftUnderFileSystem.java
@@ -129,6 +129,11 @@ public class SwiftUnderFileSystem extends UnderFileSystem {
// swiftauth authenticates directly against swift
// note: this method is supported in swift object storage api v1
config.setAuthenticationMethod(AuthenticationMethod.BASIC);
+ // swiftauth requires authentication header to be of the form tenant:user.
+ // JOSS however generates header of the form user:tenant.
+ // To resolve this, we switch user with tenant
+ config.setTenantName(Configuration.get(Constants.SWIFT_USER_KEY));
+ config.setUsername(Configuration.get(Constants.SWIFT_TENANT_KEY));
break;
default:
config.setAuthenticationMethod(AuthenticationMethod.TEMPAUTH);
|
Switch tenant and user order for swiftauth.
|
Alluxio_alluxio
|
train
|
8ec5689550224792fe904f5cc347a414ebbcd3b0
|
diff --git a/app/src/Bolt/Database/IntegrityChecker.php b/app/src/Bolt/Database/IntegrityChecker.php
index <HASH>..<HASH> 100644
--- a/app/src/Bolt/Database/IntegrityChecker.php
+++ b/app/src/Bolt/Database/IntegrityChecker.php
@@ -340,7 +340,7 @@ class IntegrityChecker
/**
* This method allows extensions to register their own tables.
* @param Callable $generator A generator function that takes the Schema
- * instance and returns a table or an array of tables.
+ * instance and returns a table or an array of tables.
*/
public function registerExtensionTable($generator)
{
@@ -565,7 +565,7 @@ class IntegrityChecker
$this->app['session']->getFlashBag()->set('error', $error);
continue;
}
-
+
$handler = $this->app['config']->getFields()->getField($values['type']);
switch ($values['type']) {
|
PSR-2 clean up of Database/IntegrityChecker.php
|
bolt_bolt
|
train
|
86753c5090579fc9c842de37b759ee2da1b70d00
|
diff --git a/lib/api/src/tests/stories.test.js b/lib/api/src/tests/stories.test.js
index <HASH>..<HASH> 100644
--- a/lib/api/src/tests/stories.test.js
+++ b/lib/api/src/tests/stories.test.js
@@ -295,24 +295,35 @@ describe('stories API', () => {
expect(navigate).toHaveBeenCalledWith('/story/a--1');
});
- it(
- 'navigates to the first child story of the parent story if a ' +
- 'story exsits but child was not specified',
- () => {
- const navigate = jest.fn();
- const store = {
- getState: () => ({ viewMode: 'story', storyId: 'b-c' }),
- setState: jest.fn(),
- };
+ it('navigates to the first leaf story if a story exsits but it is not a leaf story(1)', () => {
+ const navigate = jest.fn();
+ const store = {
+ getState: () => ({ viewMode: 'story', storyId: 'b' }),
+ setState: jest.fn(),
+ };
- const {
- api: { setStories },
- } = initStories({ store, navigate });
+ const {
+ api: { setStories },
+ } = initStories({ store, navigate });
- setStories(storiesHash);
- expect(navigate).toHaveBeenCalledWith('/story/b-c--1');
- }
- );
+ setStories(storiesHash);
+ expect(navigate).toHaveBeenCalledWith('/story/b-c--1');
+ });
+
+ it('navigates to the first leaf story if a story exsits but it is not a leaf story(2)', () => {
+ const navigate = jest.fn();
+ const store = {
+ getState: () => ({ viewMode: 'story', storyId: 'b-d' }),
+ setState: jest.fn(),
+ };
+
+ const {
+ api: { setStories },
+ } = initStories({ store, navigate });
+
+ setStories(storiesHash);
+ expect(navigate).toHaveBeenCalledWith('/story/b-d--1');
+ });
it('does not navigate if a existing story was selected', () => {
const navigate = jest.fn();
|
test: add test cases of different depth
|
storybooks_storybook
|
train
|
e1705f0c454e2c2b2a3794e63ff7ba7f5dc6e126
|
diff --git a/cumulusci/tasks/salesforce/Deploy.py b/cumulusci/tasks/salesforce/Deploy.py
index <HASH>..<HASH> 100644
--- a/cumulusci/tasks/salesforce/Deploy.py
+++ b/cumulusci/tasks/salesforce/Deploy.py
@@ -41,6 +41,14 @@ class Deploy(BaseSalesforceMetadataApiTask):
},
}
+ def _get_api(self, path=None):
+ if not path:
+ path = self.task_config.options__path
+
+ package_zip = self._get_package_zip(path)
+ self.logger.info("Payload size: {} bytes".format(len(package_zip)))
+ return self.api_class(self, package_zip, purge_on_delete=False)
+
def _get_package_zip(self, path):
# Build the zip file
zip_bytes = io.BytesIO()
@@ -56,14 +64,6 @@ class Deploy(BaseSalesforceMetadataApiTask):
zipf_processed.close()
return bytes_to_native_str(base64.b64encode(fp.getvalue()))
- def _get_api(self, path=None):
- if not path:
- path = self.task_config.options__path
-
- package_zip = self._get_package_zip(path)
- self.logger.info("Payload size: {} bytes".format(len(package_zip)))
- return self.api_class(self, package_zip, purge_on_delete=False)
-
def _process_zip_file(self, zipf):
zipf = self._process_namespace(zipf)
zipf = self._process_meta_xml(zipf)
|
Moved _get_api definition to top because its called first in _run_task
|
SFDO-Tooling_CumulusCI
|
train
|
a7c823e0d03569cb770eaf33ef34c5b2fc48b2c2
|
diff --git a/src/main/java/org/plumelib/options/OptionsDoclet.java b/src/main/java/org/plumelib/options/OptionsDoclet.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/plumelib/options/OptionsDoclet.java
+++ b/src/main/java/org/plumelib/options/OptionsDoclet.java
@@ -54,6 +54,9 @@ import org.checkerframework.common.value.qual.*;
* <pre>javadoc -quiet -doclet org.plumelib.options.OptionsDoclet [doclet options] [java files]
* </pre>
*
+ * You must specify a docletpath to Javadoc, and it needs to include the class files for the
+ * documented classes.
+ *
* <p><b>Doclet Options</b>
*
* <p>The following doclet options are supported:
|
Document need to set docletpath
|
plume-lib_options
|
train
|
215604c5ed3d517a7493c934b253559f0140c6de
|
diff --git a/fireplace/card.py b/fireplace/card.py
index <HASH>..<HASH> 100644
--- a/fireplace/card.py
+++ b/fireplace/card.py
@@ -239,6 +239,9 @@ class Card(Entity):
def summon(self):
if self.aura:
+ if self.aura == 1:
+ logging.warning("Undefined aura for %r", self)
+ return
self._aura = Aura(self.aura)
self._aura.source = self
self._aura.controller = self.controller
|
Gracefully handle undefined auras (unimplemented definitions)
|
jleclanche_fireplace
|
train
|
791a0b2aa521926f83bb26dbec3ce0ffc63e1014
|
diff --git a/src/views/boom/account/login.php b/src/views/boom/account/login.php
index <HASH>..<HASH> 100644
--- a/src/views/boom/account/login.php
+++ b/src/views/boom/account/login.php
@@ -12,9 +12,9 @@
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
<fieldset>
- <? if (isset($login_error)): ?>
+ <?php if (isset($login_error)): ?>
<p class="b-error"><?= $login_error ?></p>
- <? endif ?>
+ <?php endif ?>
<p>
<label for="email">
<?= Lang::get('Email address') ?>
|
Removed PHP short tags in login form view
|
boomcms_boom-core
|
train
|
84357664a37df98ec2b78d3338fa79ec1eca56c6
|
diff --git a/test/Unit/DataProvider/StringProviderTest.php b/test/Unit/DataProvider/StringProviderTest.php
index <HASH>..<HASH> 100644
--- a/test/Unit/DataProvider/StringProviderTest.php
+++ b/test/Unit/DataProvider/StringProviderTest.php
@@ -26,11 +26,11 @@ final class StringProviderTest extends AbstractProviderTestCase
/**
* @dataProvider \Ergebnis\Test\Util\DataProvider\StringProvider::arbitrary()
*
- * @param string $value
+ * @param mixed $value
*/
- public function testArbitraryProvidesString(string $value): void
+ public function testArbitraryProvidesString($value): void
{
- self::assertNotSame('', \trim($value));
+ self::assertIsString($value);
}
public function testArbitraryReturnsGeneratorThatProvidesStringsThatAreNeitherEmptyNorBlank(): void
@@ -42,6 +42,11 @@ final class StringProviderTest extends AbstractProviderTestCase
'string-arbitrary-word' => Util\DataProvider\Specification\Closure::create(static function (string $value): bool {
return '' !== $value && '' !== \trim($value);
}),
+ 'string-blank-carriage-return' => Util\DataProvider\Specification\Identical::create("\r"),
+ 'string-blank-line-feed' => Util\DataProvider\Specification\Identical::create("\n"),
+ 'string-blank-space' => Util\DataProvider\Specification\Identical::create(' '),
+ 'string-blank-tab' => Util\DataProvider\Specification\Identical::create("\t"),
+ 'string-empty' => Util\DataProvider\Specification\Identical::create(''),
'string-untrimmed-carriage-return' => Util\DataProvider\Specification\Pattern::create('/^\r{1,5}\w+\r{1,5}$/'),
'string-untrimmed-line-feed' => Util\DataProvider\Specification\Pattern::create('/^\n{1,5}\w+\n{1,5}$/'),
'string-untrimmed-space' => Util\DataProvider\Specification\Pattern::create('/^\s{1,5}\w+\s{1,5}$/'),
|
Enhancement: Assert that StringProvider::arbitrary() provides all kinds of values
|
localheinz_test-util
|
train
|
f5e9a80fad9cc3c9871468367e3cb46ad516e1db
|
diff --git a/bundles/org.eclipse.orion.client.ui/web/orion/editorPreferences.js b/bundles/org.eclipse.orion.client.ui/web/orion/editorPreferences.js
index <HASH>..<HASH> 100644
--- a/bundles/org.eclipse.orion.client.ui/web/orion/editorPreferences.js
+++ b/bundles/org.eclipse.orion.client.ui/web/orion/editorPreferences.js
@@ -19,7 +19,7 @@ define([], function() {
autoSave: false,
autoSaveVisible: true,
autoSaveLocalVisible: true,
- autoSaveTimeout: 1000,
+ autoSaveTimeout: 250,
autoSaveTimeoutVisible: true,
themeVisible: true,
themeLocalVisible: true,
diff --git a/bundles/org.eclipse.orion.client.ui/web/orion/inputManager.js b/bundles/org.eclipse.orion.client.ui/web/orion/inputManager.js
index <HASH>..<HASH> 100644
--- a/bundles/org.eclipse.orion.client.ui/web/orion/inputManager.js
+++ b/bundles/org.eclipse.orion.client.ui/web/orion/inputManager.js
@@ -27,7 +27,7 @@ define([
this._timeout = options.timeout;
//TODO: remove listeners if there are no clients
//TODO: add support for multiple clients with different timeouts
- var events = ["keypress","keydown","keyup","mousemove","mousedown","mousemove"]; //$NON-NLS-0$ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ var events = ["keypress","keydown","keyup"]; //$NON-NLS-0$ //$NON-NLS-1$ //$NON-NLS-2$
var reset = function (e) { this._resetTimer(); }.bind(this);
for (var i = 0; i < events.length; i++) {
var event = events[i];
|
Bug <I> - Editor does not auto save while mouse is moving
|
eclipse_orion.client
|
train
|
85891ab6e3e61e1b04241091714442f89c9e5f92
|
diff --git a/src/org/opencms/ui/apps/CmsFileExplorer.java b/src/org/opencms/ui/apps/CmsFileExplorer.java
index <HASH>..<HASH> 100644
--- a/src/org/opencms/ui/apps/CmsFileExplorer.java
+++ b/src/org/opencms/ui/apps/CmsFileExplorer.java
@@ -44,6 +44,7 @@ import org.opencms.ui.components.CmsErrorDialog;
import org.opencms.ui.components.CmsFileTable;
import org.opencms.ui.components.CmsResourceInfo;
import org.opencms.ui.components.CmsToolBar;
+import org.opencms.ui.components.I_CmsWindowCloseListener;
import org.opencms.ui.dialogs.CmsTouchDialog;
import org.opencms.ui.dialogs.availability.CmsAvailabilityDialog;
import org.opencms.util.CmsStringUtil;
@@ -94,7 +95,7 @@ import com.vaadin.ui.VerticalLayout;
/**
* The file explorer app.<p>
*/
-public class CmsFileExplorer implements I_CmsWorkplaceApp, ViewChangeListener {
+public class CmsFileExplorer implements I_CmsWorkplaceApp, ViewChangeListener, I_CmsWindowCloseListener {
/**
* Context menu click handler which opens a custom dialog.<p>
@@ -214,6 +215,9 @@ public class CmsFileExplorer implements I_CmsWorkplaceApp, ViewChangeListener {
/** The UI context. */
protected I_CmsAppUIContext m_appContext;
+ /** The currently viewed folder. */
+ private CmsUUID m_currentFolder;
+
/** The current app state. */
private String m_currentState;
@@ -235,9 +239,6 @@ public class CmsFileExplorer implements I_CmsWorkplaceApp, ViewChangeListener {
/** The search field. */
private TextField m_searchField;
- /** The currently viewed folder. */
- private CmsUUID m_currentFolder;
-
/**
* Constructor.<p>
*/
@@ -372,8 +373,7 @@ public class CmsFileExplorer implements I_CmsWorkplaceApp, ViewChangeListener {
m_fileTable.setTableState(settings);
} catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
+ LOG.error("Error while reading file explorer settings from user.", e);
}
sp.setSecondComponent(m_fileTable);
sp.setSplitPosition(400 - 1, Unit.PIXELS);
@@ -398,6 +398,17 @@ public class CmsFileExplorer implements I_CmsWorkplaceApp, ViewChangeListener {
}
/**
+ * @see org.opencms.ui.components.I_CmsWindowCloseListener#onWindowClose()
+ */
+ public void onWindowClose() {
+
+ OpenCms.getWorkplaceAppManager().storeAppSettings(
+ A_CmsUI.getCmsObject(),
+ CmsFileExplorerSettings.class,
+ m_fileTable.getTableSettings());
+ }
+
+ /**
* Fills the file table with the resources from the given path.<p>
*
* @param sitePath a folder site path
@@ -433,8 +444,7 @@ public class CmsFileExplorer implements I_CmsWorkplaceApp, ViewChangeListener {
m_fileTree.setContainerDataSource(container);
m_fileTree.expandItem(siteRoot.getStructureId());
} catch (CmsException e) {
- // TODO: Auto-generated catch block
- e.printStackTrace();
+ LOG.error("Error while populating file explorer tree", e);
}
}
|
Saving file explorer settings also on window close.
|
alkacon_opencms-core
|
train
|
c9cc560280e96593c64087bea69b082fd7460156
|
diff --git a/mockgen/mockgen.go b/mockgen/mockgen.go
index <HASH>..<HASH> 100644
--- a/mockgen/mockgen.go
+++ b/mockgen/mockgen.go
@@ -182,7 +182,7 @@ func sanitize(s string) string {
}
func (g *generator) Generate(pkg *model.Package, pkgName string) error {
- g.p("// Automatically generated by MockGen. DO NOT EDIT!")
+ g.p("// Code generated by MockGen. DO NOT EDIT.")
if g.filename != "" {
g.p("// Source: %v", g.filename)
} else {
|
Change header to conform with standard for generated code: <URL>
|
golang_mock
|
train
|
92f266d3b00b1f55f17235fed8058c2070238e73
|
diff --git a/lxd/storage/drivers/driver_zfs_volumes.go b/lxd/storage/drivers/driver_zfs_volumes.go
index <HASH>..<HASH> 100644
--- a/lxd/storage/drivers/driver_zfs_volumes.go
+++ b/lxd/storage/drivers/driver_zfs_volumes.go
@@ -1121,6 +1121,32 @@ func (d *zfs) RenameVolume(vol Volume, newVolName string, op *operations.Operati
func (d *zfs) MigrateVolume(vol Volume, conn io.ReadWriteCloser, volSrcArgs *migration.VolumeSourceArgs, op *operations.Operation) error {
// Handle simple rsync and block_and_rsync through generic.
if volSrcArgs.MigrationType.FSType == migration.MigrationFSType_RSYNC || volSrcArgs.MigrationType.FSType == migration.MigrationFSType_BLOCK_AND_RSYNC {
+ // We need to mount the parent volume before calling genericVFSMigrateVolume for two reasons.
+ // 1. In order to get the block device disk path to read from the device must be activated.
+ // 2. If copying snapshots the parent volume must be activated before the snapshot volume's block
+ // device can be made visible.
+ parent, _, _ := shared.InstanceGetParentAndSnapshotName(vol.Name())
+ parentVol := NewVolume(d, d.Name(), vol.volType, vol.contentType, parent, vol.config, vol.poolConfig)
+ ourMount, err := d.MountVolume(parentVol, op)
+ if err != nil {
+ return err
+ }
+ if ourMount {
+ defer d.UnmountVolume(parentVol, op)
+ }
+
+ // In addition to above, if the volume we are sending is a snapshot, we also need to mount that
+ // so that genericVFSMigrateVolume can discover its block device (same reason as 1. above).
+ if vol.IsSnapshot() {
+ ourMount, err = d.MountVolumeSnapshot(vol, op)
+ if err != nil {
+ return err
+ }
+ if ourMount {
+ defer d.UnmountVolumeSnapshot(vol, op)
+ }
+ }
+
return genericVFSMigrateVolume(d, d.state, vol, conn, volSrcArgs, op)
} else if volSrcArgs.MigrationType.FSType != migration.MigrationFSType_ZFS {
return ErrNotSupported
|
lxd/storage/drivers/driver/zfs/volumes: Fix migrating VM block volumes in MigrateVolume
|
lxc_lxd
|
train
|
a15679f5af8302491aeafb3281072dd35daa9f5a
|
diff --git a/examples/hybrid_simple/tests.js b/examples/hybrid_simple/tests.js
index <HASH>..<HASH> 100644
--- a/examples/hybrid_simple/tests.js
+++ b/examples/hybrid_simple/tests.js
@@ -13,7 +13,7 @@ describe('hello', function(){
});
it('should say hello to person', function(){
- expect(hello('Bob')).to.equal('hello Bob')
+ expect(hello('Bob')).to.equal('hello Bob');
});
});
\ No newline at end of file
|
Added a semicolon;
|
testem_testem
|
train
|
891ba1722745304f345ef05c363bebb61da51690
|
diff --git a/intranet/apps/eighth/models.py b/intranet/apps/eighth/models.py
index <HASH>..<HASH> 100644
--- a/intranet/apps/eighth/models.py
+++ b/intranet/apps/eighth/models.py
@@ -59,6 +59,11 @@ class EighthRoom(models.Model):
return "{} ({})".format(self.name, self.capacity)
+class EighthActivityExcludeDeletedManager(models.Manager):
+ def get_query_set(self):
+ return super(EighthActivityExcludeDeletedManager, self).get_query_set().exclude(deleted=True)
+
+
class EighthActivity(models.Model):
"""Represents an eighth period activity.
@@ -67,6 +72,8 @@ class EighthActivity(models.Model):
- sponsors -- The :class:`EighthSponsor`s for the activity.
"""
+ objects = models.Manager()
+ undeleted_objects = EighthActivityExcludeDeletedManager()
name = models.CharField(max_length=63, unique=True)
description = models.CharField(max_length=255, blank=True)
@@ -151,6 +158,9 @@ class EighthBlock(models.Model):
:class:`EighthScheduledActivity`s for the block.
"""
+
+ objects = EighthBlockManager()
+
date = models.DateField(null=False)
block_letter = models.CharField(max_length=1)
locked = models.BooleanField(default=False)
@@ -158,8 +168,6 @@ class EighthBlock(models.Model):
through="EighthScheduledActivity",
blank=True)
- objects = EighthBlockManager()
-
def save(self, *args, **kwargs):
letter = getattr(self, "block_letter", None)
if letter:
|
Add model manager for excluding deleted activities
|
tjcsl_ion
|
train
|
3a969af73df12ed45d1e84ac5de867214738d8ec
|
diff --git a/dwave/system/composites/embedding.py b/dwave/system/composites/embedding.py
index <HASH>..<HASH> 100644
--- a/dwave/system/composites/embedding.py
+++ b/dwave/system/composites/embedding.py
@@ -177,7 +177,7 @@ class EmbeddingComposite(dimod.Sampler, dimod.Composite):
__, target_edgelist, target_adjacency = child.structure
# get the embedding
- embedding = minorminer.find_embedding(bqm.quadratic, target_edgelist)
+ embedding = minorminer.find_embedding(bqm.to_qubo()[0], target_edgelist)
if bqm and not embedding:
raise ValueError("no embedding found")
|
Send qubo representation to minorminer
Represents singleton (along with all other) variables `x` as `(x, x)`
|
dwavesystems_dwave-system
|
train
|
6cb13e5cf1e1541d84ef08b1ae0dc9dafd987fd3
|
diff --git a/pygsp/graphs/nngraphs/bunny.py b/pygsp/graphs/nngraphs/bunny.py
index <HASH>..<HASH> 100644
--- a/pygsp/graphs/nngraphs/bunny.py
+++ b/pygsp/graphs/nngraphs/bunny.py
@@ -31,9 +31,10 @@ class Bunny(NNGraph):
'vertex_size': 10,
'elevation': -90,
'azimuth': 90,
- 'distance': 7,
+ 'distance': 8,
}
- super(Bunny, self).__init__(Xin=data['bunny'], epsilon=0.2,
- NNtype='radius', plotting=plotting,
- **kwargs)
+ super(Bunny, self).__init__(Xin=data['bunny'],
+ epsilon=0.02, NNtype='radius',
+ center=False, rescale=False,
+ plotting=plotting, **kwargs)
diff --git a/pygsp/graphs/nngraphs/cube.py b/pygsp/graphs/nngraphs/cube.py
index <HASH>..<HASH> 100644
--- a/pygsp/graphs/nngraphs/cube.py
+++ b/pygsp/graphs/nngraphs/cube.py
@@ -86,10 +86,12 @@ class Cube(NNGraph):
'vertex_size': 80,
'elevation': 15,
'azimuth': 0,
- 'distance': 7,
+ 'distance': 9,
}
- super(Cube, self).__init__(Xin=pts, k=10, plotting=plotting, **kwargs)
+ super(Cube, self).__init__(Xin=pts, k=10,
+ center=False, rescale=False,
+ plotting=plotting, **kwargs)
def _get_extra_repr(self):
attrs = {'radius': '{:.2f}'.format(self.radius),
diff --git a/pygsp/graphs/nngraphs/sphere.py b/pygsp/graphs/nngraphs/sphere.py
index <HASH>..<HASH> 100644
--- a/pygsp/graphs/nngraphs/sphere.py
+++ b/pygsp/graphs/nngraphs/sphere.py
@@ -65,6 +65,7 @@ class Sphere(NNGraph):
}
super(Sphere, self).__init__(Xin=pts, k=10,
+ center=False, rescale=False,
plotting=plotting, **kwargs)
def _get_extra_repr(self):
diff --git a/pygsp/graphs/nngraphs/twomoons.py b/pygsp/graphs/nngraphs/twomoons.py
index <HASH>..<HASH> 100644
--- a/pygsp/graphs/nngraphs/twomoons.py
+++ b/pygsp/graphs/nngraphs/twomoons.py
@@ -97,6 +97,7 @@ class TwoMoons(NNGraph):
}
super(TwoMoons, self).__init__(Xin=Xin, sigma=sigmag, k=5,
+ center=False, rescale=False,
plotting=plotting, **kwargs)
def _get_extra_repr(self):
|
don't rescale fixed graphs
|
epfl-lts2_pygsp
|
train
|
6071fc63eb13c1c7ced0efbf7912df2df465f2c1
|
diff --git a/doxypypy/doxypypy.py b/doxypypy/doxypypy.py
index <HASH>..<HASH> 100755
--- a/doxypypy/doxypypy.py
+++ b/doxypypy/doxypypy.py
@@ -211,8 +211,9 @@ class AstWalker(NodeVisitor):
match = tagRE.search(line)
if match:
# We've got a simple one-line Doxygen command
- lines[-1], inCodeBlock = self._endCodeIfNeeded(
- lines[-1], inCodeBlock)
+ if lines:
+ lines[-1], inCodeBlock = self._endCodeIfNeeded(
+ lines[-1], inCodeBlock)
inCodeBlockObj[0] = inCodeBlock
writer.send((firstLineNum, lineNum - 1, lines))
lines = []
diff --git a/doxypypy/test/sample_google.out.py b/doxypypy/test/sample_google.out.py
index <HASH>..<HASH> 100644
--- a/doxypypy/test/sample_google.out.py
+++ b/doxypypy/test/sample_google.out.py
@@ -3,6 +3,8 @@
#
#This is basically as close a copy of the Python examples in the Google
#Python Style Guide as possible while still being valid code.
+# @note this is a note
+# @note this is also a note
#
#http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=Comments#Comments
#
diff --git a/doxypypy/test/sample_google.outbare.py b/doxypypy/test/sample_google.outbare.py
index <HASH>..<HASH> 100644
--- a/doxypypy/test/sample_google.outbare.py
+++ b/doxypypy/test/sample_google.outbare.py
@@ -4,6 +4,8 @@
#
#This is basically as close a copy of the Python examples in the Google
#Python Style Guide as possible while still being valid code.
+#NOTE: this is a note
+#NOTE: this is also a note
#
#http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=Comments#Comments
#
diff --git a/doxypypy/test/sample_google.outnc.py b/doxypypy/test/sample_google.outnc.py
index <HASH>..<HASH> 100644
--- a/doxypypy/test/sample_google.outnc.py
+++ b/doxypypy/test/sample_google.outnc.py
@@ -3,6 +3,8 @@
#
#This is basically as close a copy of the Python examples in the Google
#Python Style Guide as possible while still being valid code.
+# @note this is a note
+# @note this is also a note
#
#http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=Comments#Comments
#
diff --git a/doxypypy/test/sample_google.outnn.py b/doxypypy/test/sample_google.outnn.py
index <HASH>..<HASH> 100644
--- a/doxypypy/test/sample_google.outnn.py
+++ b/doxypypy/test/sample_google.outnn.py
@@ -3,6 +3,8 @@
#
#This is basically as close a copy of the Python examples in the Google
#Python Style Guide as possible while still being valid code.
+# @note this is a note
+# @note this is also a note
#
#http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=Comments#Comments
#
diff --git a/doxypypy/test/sample_google.py b/doxypypy/test/sample_google.py
index <HASH>..<HASH> 100644
--- a/doxypypy/test/sample_google.py
+++ b/doxypypy/test/sample_google.py
@@ -4,6 +4,8 @@ Google Python Style Guide SampleClass
This is basically as close a copy of the Python examples in the Google
Python Style Guide as possible while still being valid code.
+NOTE: this is a note
+NOTE: this is also a note
http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=Comments#Comments
"""
|
Avoid index-out-of-range exception with back-to-back notes.
Also modified a test case.
|
Feneric_doxypypy
|
train
|
32c25c0311ced14ab10161a2c2b1556e86b09b6c
|
diff --git a/core/codegen/platform/src/main/java/org/overture/codegen/merging/TemplateManager.java b/core/codegen/platform/src/main/java/org/overture/codegen/merging/TemplateManager.java
index <HASH>..<HASH> 100644
--- a/core/codegen/platform/src/main/java/org/overture/codegen/merging/TemplateManager.java
+++ b/core/codegen/platform/src/main/java/org/overture/codegen/merging/TemplateManager.java
@@ -32,19 +32,19 @@ import org.apache.velocity.runtime.RuntimeSingleton;
import org.apache.velocity.runtime.parser.ParseException;
import org.apache.velocity.runtime.parser.node.SimpleNode;
import org.overture.codegen.cgast.INode;
-import org.overture.codegen.cgast.expressions.ACardUnaryExpCG;
-import org.overture.codegen.cgast.expressions.ALenUnaryExpCG;
import org.overture.codegen.utils.GeneralUtils;
public class TemplateManager
{
public static final String TEMPLATE_FILE_EXTENSION = ".vm";
- protected HashMap<Class<? extends INode>, Class<? extends INode>> reuses;
+ /**
+ * Relative paths for user-defined template files
+ */
+ protected HashMap<Class<? extends INode>, String> userDefinedPaths;
protected String root;
- private boolean isBase;
private Class<?> templateLoadRef = null;
/**
@@ -54,9 +54,7 @@ public class TemplateManager
*/
public TemplateManager(String root)
{
- this.root = root;
- initNodeTemplateFileNames();
- isBase = true;
+ this(root, null);
}
/**
@@ -72,9 +70,8 @@ public class TemplateManager
public TemplateManager(String root, Class<?> templateLoadRef)
{
this.root = root;
- initNodeTemplateFileNames();
- isBase = false;
this.templateLoadRef = templateLoadRef;
+ initNodeTemplateFileNames();
}
/**
@@ -82,20 +79,31 @@ public class TemplateManager
*/
protected void initNodeTemplateFileNames()
{
- this.reuses = new HashMap<>();
+ this.userDefinedPaths = new HashMap<>();
}
public Template getTemplate(Class<? extends INode> nodeClass) throws ParseException
{
try
{
+ String relPath;
+
+ if (isUserDefined(nodeClass))
+ {
+ relPath = userDefinedPaths.get(nodeClass);
+ } else
+ {
+ relPath = derivePath(nodeClass);
+ }
+
StringBuffer buffer;
- if (isBase)
+
+ if (templateLoadRef != null)
{
- buffer = GeneralUtils.readFromFile(getTemplateFileRelativePath(nodeClass));
+ buffer = GeneralUtils.readFromFile(relPath, templateLoadRef);
} else
{
- buffer = GeneralUtils.readFromFile(getTemplateFileRelativePath(nodeClass), templateLoadRef);
+ buffer = GeneralUtils.readFromFile(relPath);
}
if (buffer == null)
@@ -125,35 +133,30 @@ public class TemplateManager
return template;
}
-
- /**
- * Enables an IR node to reuse the template of another IR node
- *
- * @param templateOwner The IR node which owns the template subject to reuse
- * @param reuser The IR node that reuses the template
- */
- protected void reuseTemplate(Class<ACardUnaryExpCG> templateOwner, Class<ALenUnaryExpCG> reuser)
- {
- reuses.put(reuser, templateOwner);
- }
-
- protected boolean reuses(Class<? extends INode> nodeClass)
+
+ public void setUserDefinedPath(Class<? extends INode> nodeClass, String relativePath)
{
- return reuses.containsKey(nodeClass);
+ userDefinedPaths.put(nodeClass, relativePath);
}
- protected Class<? extends INode> getTemplateOwner(Class<? extends INode> nodeClass)
+ public boolean isUserDefined(Class<? extends INode> nodeClass)
{
- return reuses.get(nodeClass);
+ return userDefinedPaths.containsKey(nodeClass);
}
- protected String getTemplateFileRelativePath(Class<? extends INode> nodeClass)
+ public String getRelativePath(Class<? extends INode> templateOwner)
{
- if (reuses(nodeClass))
+ if (isUserDefined(templateOwner))
+ {
+ return userDefinedPaths.get(templateOwner);
+ } else
{
- nodeClass = getTemplateOwner(nodeClass);
+ return derivePath(templateOwner);
}
-
+ }
+
+ public String derivePath(Class<? extends INode> nodeClass)
+ {
return root + File.separatorChar + nodeClass.getName().replaceAll("\\.", File.separator)
+ TEMPLATE_FILE_EXTENSION;
}
|
Update 'TemplateManager' to allow the paths of templates to be user-defined
Issue #<I>
|
overturetool_overture
|
train
|
71ae589b9a21b5e1b03334973a76cfa7607118a3
|
diff --git a/numina/core/pipeline.py b/numina/core/pipeline.py
index <HASH>..<HASH> 100644
--- a/numina/core/pipeline.py
+++ b/numina/core/pipeline.py
@@ -97,11 +97,12 @@ def get_recipe(name, mode):
def init_pipeline_system():
'''Load all available pipelines.'''
- for i in pkgutil.walk_packages(namespace.__path__, namespace.__name__ + '.'):
- imp, name, _is_pkg = i
- loader = imp.find_module(name)
- _mod = loader.load_module(name)
-
+ for imp, name, _is_pkg in pkgutil.walk_packages(namespace.__path__, namespace.__name__ + '.'):
+ try:
+ loader = imp.find_module(name)
+ _mod = loader.load_module(name)
+ except ImportError as error:
+ _logger.warning('Problem importing %s, error was "%s"', name, error)
# Loaded all DRP modules
|
Program does not end abruptly if there is a problem during pipeline import
|
guaix-ucm_numina
|
train
|
c4f1ae925abe441304c27d205170f8edcb4d94a2
|
diff --git a/src/Illuminate/Exception/Handler.php b/src/Illuminate/Exception/Handler.php
index <HASH>..<HASH> 100755
--- a/src/Illuminate/Exception/Handler.php
+++ b/src/Illuminate/Exception/Handler.php
@@ -149,7 +149,7 @@ class Handler {
// type of exceptions to handled by a Closure giving great flexibility.
if ( ! is_null($response))
{
- return $this->prepareResponse($response);
+ $response = $this->prepareResponse($response);
}
// If no response was sent by this custom exception handler, we will call the
@@ -157,8 +157,12 @@ class Handler {
// it show the exception to the user / developer based on the situation.
else
{
- return $this->displayException($exception);
+ $response = $this->displayException($exception);
}
+
+ return $this->responsePreparer->readyForResponses()
+ ? $response
+ : $response->send();
}
/**
diff --git a/src/Illuminate/Foundation/Application.php b/src/Illuminate/Foundation/Application.php
index <HASH>..<HASH> 100755
--- a/src/Illuminate/Foundation/Application.php
+++ b/src/Illuminate/Foundation/Application.php
@@ -762,6 +762,16 @@ class Application extends Container implements HttpKernelInterface, TerminableIn
}
/**
+ * Determine if the application is ready for responses.
+ *
+ * @return bool
+ */
+ public function readyForResponses()
+ {
+ return $this->booted;
+ }
+
+ /**
* Determine if the application is currently down for maintenance.
*
* @return bool
diff --git a/src/Illuminate/Support/Contracts/ResponsePreparerInterface.php b/src/Illuminate/Support/Contracts/ResponsePreparerInterface.php
index <HASH>..<HASH> 100755
--- a/src/Illuminate/Support/Contracts/ResponsePreparerInterface.php
+++ b/src/Illuminate/Support/Contracts/ResponsePreparerInterface.php
@@ -10,4 +10,11 @@ interface ResponsePreparerInterface {
*/
public function prepareResponse($value);
+ /**
+ * Determine if provider is ready to return responses.
+ *
+ * @return bool
+ */
+ public function readyForResponses();
+
}
\ No newline at end of file
|
Fix a WSOD issue if application isn't ready for repsonses.
|
laravel_framework
|
train
|
a6d249a87840f7283b609b4669fbeb2a6ad57d6d
|
diff --git a/src/Routing/Assets/DispatcherInterface.php b/src/Routing/Assets/DispatcherInterface.php
index <HASH>..<HASH> 100644
--- a/src/Routing/Assets/DispatcherInterface.php
+++ b/src/Routing/Assets/DispatcherInterface.php
@@ -2,9 +2,7 @@
namespace Nova\Routing\Assets;
-use Nova\Http\Request;
-
-use Symfony\Component\HttpFoundation\Response;
+use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
interface DispatcherInterface
@@ -15,7 +13,7 @@ interface DispatcherInterface
*
* @return \Symfony\Component\HttpFoundation\Response|null
*/
- public function dispatch(Request $request);
+ public function dispatch(SymfonyRequest $request);
/**
* Serve a File.
@@ -24,6 +22,6 @@ interface DispatcherInterface
*
* @return \Symfony\Component\HttpFoundation\Response
*/
- public function serve($path, Request $request);
+ public function serve($path, SymfonyRequest $request);
}
|
Improve Nova\Routing\Assets\DispatcherInterface
|
nova-framework_system
|
train
|
bf1be94fe3f47232205a5a0aa4e177b70ea48802
|
diff --git a/test/base58.js b/test/base58.js
index <HASH>..<HASH> 100644
--- a/test/base58.js
+++ b/test/base58.js
@@ -19,4 +19,31 @@ describe('base58', function() {
assert.equal(base58.encode(conv.hexToBytes(hex)), enc);
})
})
+
+ describe('checkEncode', function() {
+ it('handles known examples', function() {
+ var input = [
+ 171, 210, 178, 125, 2, 16, 86, 184, 248, 88, 235,
+ 163, 244, 160, 83, 156, 184, 186, 45, 167, 169, 164,
+ 67, 125, 163, 89, 106, 243, 207, 193, 149, 206
+ ]
+ var vbyte = 239
+
+ assert.equal(base58.checkEncode(input, vbyte),
+ '92tb9mjz6q9eKZjYvLsgk87kPrMoh7BGRumSzPeUGhmigtsfrbP');
+ })
+ })
+
+ describe('checkDecode', function() {
+ it('handles known examples', function() {
+ var input = '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa'
+ var expected = [
+ 98, 233, 7, 177, 92, 191, 39, 213, 66, 83,
+ 153, 235, 246, 240, 251, 80, 235, 184, 143, 24
+ ];
+ expected.version = 0
+
+ assert.deepEqual(base58.checkDecode(input), expected);
+ })
+ })
})
|
add tests for checkEncode and checkDecode
|
BitGo_bitgo-utxo-lib
|
train
|
b235cf800c81e937442017a13078803da342cc4e
|
diff --git a/src/git.js b/src/git.js
index <HASH>..<HASH> 100644
--- a/src/git.js
+++ b/src/git.js
@@ -839,7 +839,7 @@
}
};
- var fileUpdateRegex = /^\s*(.+)\s\|\s+(\d+)\s([+\-]+)/;
+ var fileUpdateRegex = /^\s*(.+?)\s+\|\s+(\d+)\s([+\-]+)/;
for (var lines = pull.split('\n'), i = 0, l = lines.length; i < l; i++) {
var update = fileUpdateRegex.exec(lines[i]);
|
Pull parsing regex now does not capture the extra spaces in the file names
|
steveukx_git-js
|
train
|
321d2af1922ef0643fd4e5868ef91daca0493ff3
|
diff --git a/src/frontend/org/voltdb/TheHashinator.java b/src/frontend/org/voltdb/TheHashinator.java
index <HASH>..<HASH> 100644
--- a/src/frontend/org/voltdb/TheHashinator.java
+++ b/src/frontend/org/voltdb/TheHashinator.java
@@ -76,7 +76,7 @@ public abstract class TheHashinator {
*/
public static TheHashinator getHashinator(Class<? extends TheHashinator> hashinatorImplementation,
byte config[]) {
- return constructHashinator(hashinatorImplementation, config);
+ return constructHashinator(hashinatorImplementation, config, false);
}
/**
|
Update non-static hashinator to use new cooked.
|
VoltDB_voltdb
|
train
|
cfd26e612b4dc88865596790f6d3e47f756a0f68
|
diff --git a/packages/outputs/src/components/media/javascript.js b/packages/outputs/src/components/media/javascript.js
index <HASH>..<HASH> 100644
--- a/packages/outputs/src/components/media/javascript.js
+++ b/packages/outputs/src/components/media/javascript.js
@@ -3,10 +3,9 @@ import React from "react";
type Props = {
/**
- * The media type associated with our component. This should be set to
- * application/javascript.
+ * The media type associated with our component.
*/
- mediaType: string,
+ mediaType: "text/javascript",
/**
* The JavaScript code that we would like to execute.
*/
@@ -40,14 +39,6 @@ export class JavaScript extends React.Component<Props> {
data: ""
};
- static handles(mimetype: string) {
- return (
- mimetype.startsWith("text/") ||
- mimetype.startsWith("application/javascript") ||
- mimetype.startsWith("application/json")
- );
- }
-
componentDidMount(): void {
runCodeHere(this.el, this.props.data);
}
|
Remove unused handles method and declare media type
|
nteract_nteract
|
train
|
d5883a667ec5cd10fa93cbc081157712da85f1d5
|
diff --git a/findbugs/src/java/edu/umd/cs/findbugs/detect/CloneIdiom.java b/findbugs/src/java/edu/umd/cs/findbugs/detect/CloneIdiom.java
index <HASH>..<HASH> 100644
--- a/findbugs/src/java/edu/umd/cs/findbugs/detect/CloneIdiom.java
+++ b/findbugs/src/java/edu/umd/cs/findbugs/detect/CloneIdiom.java
@@ -117,7 +117,7 @@ public class CloneIdiom extends DismantleBytecode implements Detector, Constants
.addClass(this));
}
- if (hasCloneMethod && !invokesSuperClone && !isFinal) {
+ if (hasCloneMethod && !invokesSuperClone && !isFinal && obj.isPublic()) {
bugReporter.reportBug(new BugInstance("CN_IDIOM_NO_SUPER_CALL", NORMAL_PRIORITY)
.addClass(this)
.addMethod(cloneMethodAnnotation)
|
Don't report errors about classes with clone methods
that aren't safe for extension if the classes are not public.
git-svn-id: <URL>
|
spotbugs_spotbugs
|
train
|
b79eca3e0f415362fac200c8b7b711355c181c7d
|
diff --git a/eZ/Publish/Core/Search/Elasticsearch/Content/SortClauseVisitor/Field/Field.php b/eZ/Publish/Core/Search/Elasticsearch/Content/SortClauseVisitor/Field/Field.php
index <HASH>..<HASH> 100644
--- a/eZ/Publish/Core/Search/Elasticsearch/Content/SortClauseVisitor/Field/Field.php
+++ b/eZ/Publish/Core/Search/Elasticsearch/Content/SortClauseVisitor/Field/Field.php
@@ -58,13 +58,10 @@ class Field extends FieldBase
);
}
- /** @var \eZ\Publish\API\Repository\Values\Content\Query\SortClause\Target\FieldTarget $target */
- $target = $sortClause->targetData;
-
return array(
"fields_doc.{$fieldName}" => array(
'nested_filter' => array(
- 'term' => $this->getNestedFilterTerm($target->languageCode),
+ 'term' => $this->getNestedFilterTerm(null),
),
'order' => $this->getDirection($sortClause),
),
diff --git a/eZ/Publish/Core/Search/Elasticsearch/Content/SortClauseVisitor/Field/MapLocationDistance.php b/eZ/Publish/Core/Search/Elasticsearch/Content/SortClauseVisitor/Field/MapLocationDistance.php
index <HASH>..<HASH> 100644
--- a/eZ/Publish/Core/Search/Elasticsearch/Content/SortClauseVisitor/Field/MapLocationDistance.php
+++ b/eZ/Publish/Core/Search/Elasticsearch/Content/SortClauseVisitor/Field/MapLocationDistance.php
@@ -86,7 +86,7 @@ class MapLocationDistance extends FieldBase
'_geo_distance' => array(
'nested_path' => 'fields_doc',
'nested_filter' => array(
- 'term' => $this->getNestedFilterTerm($target->languageCode),
+ 'term' => $this->getNestedFilterTerm(null),
),
'order' => $this->getDirection($sortClause),
"fields_doc.{$fieldName}" => array(
|
EZP-<I>: adapt Elasticsearch engine for removal of language from sort clause
|
ezsystems_ezpublish-kernel
|
train
|
c08dcbd1ca7c97a79c9bc5637dd5a2935c44f511
|
diff --git a/doxytag2zealdb/doxytag.py b/doxytag2zealdb/doxytag.py
index <HASH>..<HASH> 100644
--- a/doxytag2zealdb/doxytag.py
+++ b/doxytag2zealdb/doxytag.py
@@ -267,7 +267,7 @@ class fileTagProcessor(TagProcessorWithAutoStuffAndCompoundTagName):
A string containing the correct documentation filename from the
tag.
'''
- return super(fileTagProcessor, self).get_filename(tag) + '.html'
+ return super(fileTagProcessor, self).get_filename(tag)
class namespaceTagProcessor(TagProcessorWithAutoStuffAndCompoundTagName):
|
Don't add .html extension to filename
|
vedvyas_doxytag2zealdb
|
train
|
989a35ecc2e7471109e5c4f615ec259e9b36022d
|
diff --git a/xod-client/src/project/reducer/index.js b/xod-client/src/project/reducer/index.js
index <HASH>..<HASH> 100644
--- a/xod-client/src/project/reducer/index.js
+++ b/xod-client/src/project/reducer/index.js
@@ -6,7 +6,7 @@ import { nodeTypes } from './nodetypes';
import { counterReducer } from './counter';
import { foldersReducer } from './folders';
-import { ApiHelpers, ApiActionTypes } from 'xod/client/api';
+import { ApiHelpers, ApiActionTypes } from 'xod-client/api';
import {
PROJECT_LOAD_DATA,
|
fix(projectReducer): fix a merge bug
|
xodio_xod
|
train
|
33428d86230064d70ec6b2a638f947d0cdb31968
|
diff --git a/lib/checks/navigation/heading-order-after.js b/lib/checks/navigation/heading-order-after.js
index <HASH>..<HASH> 100644
--- a/lib/checks/navigation/heading-order-after.js
+++ b/lib/checks/navigation/heading-order-after.js
@@ -34,10 +34,11 @@ function headingOrderAfter(results) {
// start by replacing all array ancestry paths with a flat string
// path
- let headingOrder = results[0].data.headingOrder.map(heading => {
+ const pageResult = results.find(result => !result.node._fromFrame);
+ let headingOrder = pageResult.data.headingOrder.map(heading => {
return {
...heading,
- ancestry: getFramePath(results[0].node.ancestry, heading.ancestry)
+ ancestry: getFramePath(pageResult.node.ancestry, heading.ancestry)
};
});
diff --git a/test/checks/navigation/heading-order.js b/test/checks/navigation/heading-order.js
index <HASH>..<HASH> 100644
--- a/test/checks/navigation/heading-order.js
+++ b/test/checks/navigation/heading-order.js
@@ -522,5 +522,58 @@ describe('heading-order', function() {
checks['heading-order'].after(results);
});
});
+
+ it('should not error if iframe is first result', function() {
+ var results = [
+ {
+ data: {
+ headingOrder: [
+ {
+ ancestry: 'path2',
+ level: 1
+ }
+ ]
+ },
+ node: {
+ _fromFrame: true,
+ ancestry: ['iframe', 'path2']
+ },
+ result: true
+ },
+ {
+ data: {
+ headingOrder: [
+ {
+ ancestry: 'iframe',
+ level: -1
+ },
+ {
+ ancestry: 'path1',
+ level: 2
+ },
+ {
+ ancestry: 'path3',
+ level: 3
+ }
+ ]
+ },
+ node: {
+ _fromFrame: false,
+ ancestry: ['path1']
+ },
+ result: true
+ },
+ {
+ node: {
+ _fromFrame: false,
+ ancestry: ['path3']
+ },
+ result: true
+ }
+ ];
+ var afterResults = checks['heading-order'].after(results);
+ assert.isTrue(afterResults[1].result);
+ assert.isTrue(afterResults[2].result);
+ });
});
});
|
fix(heading-order): handle iframe as first result (#<I>)
|
dequelabs_axe-core
|
train
|
a3c2a8ef9f7d5e3b4dcdff32864baebe19ad3271
|
diff --git a/language/dates.js b/language/dates.js
index <HASH>..<HASH> 100644
--- a/language/dates.js
+++ b/language/dates.js
@@ -7,7 +7,9 @@ const addWeeks = require('date-fns/add_weeks');
const addDays = require('date-fns/add_days')
const addHours = require('date-fns/add_hours')
const addSeconds = require('date-fns/add_seconds')
+const addYears = require('date-fns/add_years');
+const setDate = require('date-fns/set_date');
const setISODay = require('date-fns/set_iso_day');
const getISODay = require('date-fns/get_iso_day');
const setHours = require('date-fns/set_hours')
@@ -16,6 +18,9 @@ const setSeconds = require('date-fns/set_seconds')
const isSameDay = require('date-fns/is_same_day');
+const lastDayOfMonth = require('date-fns/last_day_of_month');
+const lastDayOfYear = require('date-fns/last_day_of_year')
+
module.exports.isRelative = function isRelative(v) {
return v && (v.relativeMonths >= 0 || v.relativeWeeks >= 0 || v.relativeDays >= 0 || v.relative >= 0);
};
@@ -78,10 +83,12 @@ module.exports.toAM = function(time) {
module.exports.combine = function(a, b) {
const result = cloneDeep(a);
- Object.keys(b).forEach(key => result[key] = b[key]);
-
- if(a.relative >= 0) {
- result.relative += a.relative;
+ for(const key of Object.keys(b)) {
+ if(key === 'relative' && typeof result[key] === 'number') {
+ result[key] += b[key];
+ } else {
+ result[key] = b[key];
+ }
}
return result;
@@ -138,18 +145,19 @@ function mapYear(r, e) {
module.exports.mapYear = mapYear;
module.exports.mapMonth = mapYear;
-function resolveDate(r, e) {
- const result = mapYear(r, e);
-
- const now = toDate(result, currentTime(e));
-
- if(typeof result.year === 'undefined') {
- result.year = now.getFullYear();
+function resolveDate(r, e, options) {
+ if(r instanceof Date) {
+ // Special case to turn a Date into a DateValue
+ const result = new DateValue(e.language);
+ result.year = r.getFullYear();
+ result.month = r.getMonth();
+ result.day = r.getDate();
+ return result;
}
- if(typeof result.month === 'undefined') {
- result.month = now.getMonth();
- }
+ const result = mapYear(r, e);
+
+ const now = toDate(result, (options && options.base) || currentTime(e));
if(typeof r.relativeDays !== 'undefined') {
const date = addDays(toDate(result, now), r.relativeDays);
@@ -159,19 +167,17 @@ function resolveDate(r, e) {
} else {
if(typeof r.day !== 'undefined') {
result.day = r.day;
- } else {
- result.day = now.getDate();
}
}
if(typeof r.dayOfWeek !== 'undefined') {
- if(typeof r.month === 'undefined') {
+ if(typeof result.month === 'undefined') {
// Reset to first month
result.month = 0;
}
- if(typeof r.day === 'undefined') {
+ if(typeof result.day === 'undefined') {
// Reset to first day
result.day = 1;
}
@@ -193,6 +199,38 @@ function resolveDate(r, e) {
result.day = date.getDate();
}
+ if(typeof r.year !== 'undefined') {
+ if(typeof result.month === 'undefined') {
+ result.month = 0;
+
+ if(options && options.end) {
+ result.month = 11;
+ }
+ }
+ }
+
+ if(typeof result.year === 'undefined') {
+ result.year = now.getFullYear();
+ }
+
+ if(typeof result.month !== 'undefined') {
+ if(typeof result.day === 'undefined') {
+ result.day = 1;
+
+ if(options && options.end) {
+ result.day = lastDayOfMonth(result.toDate()).getDate();
+ }
+ }
+ }
+
+ if(typeof result.month === 'undefined') {
+ result.month = now.getMonth();
+ }
+
+ if(typeof result.day === 'undefined') {
+ result.day = now.getDate();
+ }
+
return result;
}
|
feat(language): Improve date resolving for relative dates and date + time
|
aholstenson_ecolect-js
|
train
|
ac2b7058339ed442eefafa5e31cb9fdba4f797ae
|
diff --git a/arviz/tests/helpers.py b/arviz/tests/helpers.py
index <HASH>..<HASH> 100644
--- a/arviz/tests/helpers.py
+++ b/arviz/tests/helpers.py
@@ -261,3 +261,16 @@ def pystan_extract_unpermuted(fit, var_names=None):
ary = ary.reshape((-1, nchain, *ary_shape), order="F")
extract[key] = ary
return extract
+
+
+def pystan_extract_normal(fit, var_names=None):
+ """Extract PyStan samples unpermuted.
+
+ Function return everything as a float.
+ """
+ if var_names is None:
+ var_names = fit.model_pars
+ extract = fit.extract(var_names, permuted=False)
+ if not isinstance(extract, dict):
+ extract = fit.extract(var_names, permuted=True)
+ return extract
diff --git a/arviz/tests/test_data.py b/arviz/tests/test_data.py
index <HASH>..<HASH> 100644
--- a/arviz/tests/test_data.py
+++ b/arviz/tests/test_data.py
@@ -17,6 +17,7 @@ from .helpers import (
load_cached_models,
BaseArvizTest,
pystan_extract_unpermuted,
+ pystan_extract_normal,
)
@@ -285,7 +286,7 @@ class TestPyStanNetCDFUtils(BaseArvizTest):
# dictionary
observed_data = {"y_hat": self.data["y"]}
# ndarray
- log_likelihood = pystan_extract_unpermuted(self.obj, "log_lik")["log_lik"]
+ log_likelihood = pystan_extract_normal(self.obj, "log_lik")["log_lik"]
return from_pystan(
fit=self.obj,
posterior_predictive=["y_hat"],
@@ -304,7 +305,7 @@ class TestPyStanNetCDFUtils(BaseArvizTest):
def get_inference_data3(self):
"""log_likelihood as a ndarray."""
# ndarray
- log_likelihood = pystan_extract_unpermuted(self.obj, "log_lik")["log_lik"]
+ log_likelihood = pystan_extract_normal(self.obj, "log_lik")["log_lik"]
return from_pystan(
fit=self.obj,
posterior_predictive=["y_hat"],
|
Fix permuted loglik for PyStan tests (#<I>)
* update tests
* fix tests
* fix permuted vs unpermuted
* Add pystan_extract_normal
|
arviz-devs_arviz
|
train
|
1cfbb40f750e91698bad4bae36ea379cec03bf52
|
diff --git a/provision/kubernetes/nodecontainer.go b/provision/kubernetes/nodecontainer.go
index <HASH>..<HASH> 100644
--- a/provision/kubernetes/nodecontainer.go
+++ b/provision/kubernetes/nodecontainer.go
@@ -188,6 +188,7 @@ func (m *nodeContainerManager) deployNodeContainerForCluster(client *ClusterClie
Labels: ls.ToLabels(),
},
Spec: apiv1.PodSpec{
+ HostPID: config.HostConfig.PidMode == "host",
ImagePullSecrets: pullSecrets,
ServiceAccountName: serviceAccountName,
Affinity: affinity,
|
provision/kubernetes: allow setting hostpid in daemonset spec
|
tsuru_tsuru
|
train
|
ed7a9adadb92d0b149140fcc5de5b6f024cef2c5
|
diff --git a/src/validator.js b/src/validator.js
index <HASH>..<HASH> 100644
--- a/src/validator.js
+++ b/src/validator.js
@@ -782,7 +782,7 @@
Range: function ( min, max ) {
this.__class__ = 'Range';
- if ( min === undefined || max === undefined )
+ if ( typeof(min) === undefined || typeof(max) === undefined )
throw new Error( 'Range assert expects min and max values' );
this.min = min;
diff --git a/tests/tests.js b/tests/tests.js
index <HASH>..<HASH> 100644
--- a/tests/tests.js
+++ b/tests/tests.js
@@ -433,6 +433,7 @@ var Suite = function ( Validator, expect ) {
it( 'Range', function () {
assert = new Assert().Range( 5, 10 );
+ var assertZero = new Assert().Range( 0, 10 );
// with strings
expect( validate( 'foo', assert ) ).not.to.be( true );
@@ -450,6 +451,11 @@ var Suite = function ( Validator, expect ) {
expect( validate( 7, assert ) ).to.be( true );
expect( validate( 15, assert ) ).not.to.be( true );
+ expect( validate( -1, assertZero ) ).not.to.be( true );
+ expect( validate( 3, assertZero ) ).to.be( true );
+ expect( validate( 7, assertZero ) ).to.be( true );
+ expect( validate( 15, assertZero ) ).not.to.be( true );
+
// numbers typed strings are considered as number
expect( validate( '7', assert ) ).to.be( true );
} )
|
Better undefined check for range, add test.
|
guillaumepotier_validator.js
|
train
|
32384ef9fb4bf35ba74c859d7aeea172f62db744
|
diff --git a/header.go b/header.go
index <HASH>..<HASH> 100644
--- a/header.go
+++ b/header.go
@@ -514,8 +514,10 @@ func rfc2047AttributeName(s string) string {
// then the attribute value should be quoted
keyValuePair := strings.SplitAfter(decodeHeader(pair[0]), "=")
// only quote the parameter value if it isn't already quoted
- if !strings.HasPrefix(keyValuePair[1], "\"") {
- keyValuePair[1] = fmt.Sprintf("\"%s", keyValuePair[1])
+ if len(keyValuePair) > 1 {
+ if !strings.HasPrefix(keyValuePair[1], "\"") {
+ keyValuePair[1] = fmt.Sprintf("\"%s", keyValuePair[1])
+ }
}
pair[0] = strings.Join(keyValuePair, "")
return strings.Join(pair, "")
|
guard for index out of bounds in rfc<I>AttributeName (#<I>)
|
jhillyerd_enmime
|
train
|
a81fe58eb683297f9e6a2eba4ad99820c76467f3
|
diff --git a/lib/ews/types.rb b/lib/ews/types.rb
index <HASH>..<HASH> 100644
--- a/lib/ews/types.rb
+++ b/lib/ews/types.rb
@@ -112,12 +112,15 @@ module Viewpoint::EWS
end
def type_convert(key,str)
- return nil if str.nil?
- key = key_alias[key] || key
- if key_types[key]
- key_types[key].is_a?(Symbol) ? method(key_types[key]).call(str) : key_types[key].call(str)
- else
- str
+ begin
+ key = key_alias[key] || key
+ if key_types[key]
+ key_types[key].is_a?(Symbol) ? method(key_types[key]).call(str) : key_types[key].call(str)
+ else
+ str
+ end
+ rescue
+ nil
end
end
diff --git a/lib/ews/types/item.rb b/lib/ews/types/item.rb
index <HASH>..<HASH> 100644
--- a/lib/ews/types/item.rb
+++ b/lib/ews/types/item.rb
@@ -368,10 +368,12 @@ module Viewpoint::EWS::Types
end
def build_mailbox_users(users)
+ return [] if users.nil?
users.collect{|u| build_mailbox_user(u[:mailbox][:elems])}
end
def build_attendees_users(users)
+ return [] if users.nil?
users.collect do |u|
u[:attendee][:elems].collect do |a|
build_mailbox_user(a[:mailbox][:elems]) if a[:mailbox]
@@ -380,6 +382,7 @@ module Viewpoint::EWS::Types
end
def build_attachments(attachments)
+ return [] if users.nil?
attachments.collect do |att|
key = att.keys.first
class_by_name(key).new(self, att[key])
|
Add better default types to collections. i.e. [] instead of nil
|
WinRb_Viewpoint
|
train
|
56ab6159e6fa8746deb0ef3d8d265e48e7cc0d4b
|
diff --git a/lib/mongoid/atomic.rb b/lib/mongoid/atomic.rb
index <HASH>..<HASH> 100644
--- a/lib/mongoid/atomic.rb
+++ b/lib/mongoid/atomic.rb
@@ -344,11 +344,35 @@ module Mongoid
updates = atomic_updates
return {} unless atomic_updates.key?("$set")
touches = {}
+ wanted_keys = %w(updated_at u_at)
+ # TODO this permits field to be passed as an empty string in which case
+ # it is ignored, get rid of this behavior.
+ if field.present?
+ wanted_keys << field.to_s
+ end
updates["$set"].each_pair do |key, value|
- key_regex = /updated_at|u_at#{"|" + field if field.present?}/
- touches.merge!({ key => value }) if key =~ key_regex
+ if wanted_keys.include?(key.split('.').last)
+ touches.update(key => value)
+ end
end
{ "$set" => touches }
end
+
+ # Returns the $set atomic updates affecting the specified field.
+ #
+ # @param [ String ] field The field name.
+ #
+ # @api private
+ def set_field_atomic_updates(field)
+ updates = atomic_updates
+ return {} unless atomic_updates.key?("$set")
+ sets = {}
+ updates["$set"].each_pair do |key, value|
+ if key.split('.').last == field
+ sets.update(key => value)
+ end
+ end
+ { "$set" => sets }
+ end
end
end
diff --git a/lib/mongoid/touchable.rb b/lib/mongoid/touchable.rb
index <HASH>..<HASH> 100644
--- a/lib/mongoid/touchable.rb
+++ b/lib/mongoid/touchable.rb
@@ -38,6 +38,16 @@ module Mongoid
# _association.inverse_association.options but inverse_association
# seems to not always/ever be set here. See MONGOID-5014.
_parent.touch
+
+ if field
+ # If we are told to also touch a field, perform a separate write
+ # for that field. See MONGOID-5136.
+ # In theory we should combine the writes, which would require
+ # passing the fields to be updated to the parents - MONGOID-5142.
+ sets = set_field_atomic_updates(field)
+ selector = atomic_selector
+ _root.collection.find(selector).update_one(positionally(selector, sets), session: _session)
+ end
else
# If the current document is not embedded, it is composition root
# and we need to persist the write here.
diff --git a/spec/mongoid/touchable_spec.rb b/spec/mongoid/touchable_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/mongoid/touchable_spec.rb
+++ b/spec/mongoid/touchable_spec.rb
@@ -131,6 +131,24 @@ describe Mongoid::Touchable do
include_examples 'updates the child'
include_examples 'updates the parent when :touch is true'
include_examples 'updates the parent when :touch is not set'
+
+ context 'when also updating an additional field' do
+ it 'persists the update to the additional field' do
+ entrance
+ update_time
+ entrance.touch(:last_used_at)
+
+ entrance.reload
+ building.reload
+
+ # This is the assertion we want.
+ entrance.last_used_at.should == update_time
+
+ # Check other timestamps for good measure.
+ entrance.updated_at.should == update_time
+ building.updated_at.should == update_time
+ end
+ end
end
context "when the document is referenced" do
diff --git a/spec/mongoid/touchable_spec_models.rb b/spec/mongoid/touchable_spec_models.rb
index <HASH>..<HASH> 100644
--- a/spec/mongoid/touchable_spec_models.rb
+++ b/spec/mongoid/touchable_spec_models.rb
@@ -15,6 +15,8 @@ module TouchableSpec
include Mongoid::Timestamps
embedded_in :building
+
+ field :last_used_at, type: Time
end
class Floor
|
Fix MONGOID-<I> .touch with custom field is broken for embedded documents (#<I>)
|
mongodb_mongoid
|
train
|
fb66527548ed09e4c9b2869f24c8a7ed376e2ba5
|
diff --git a/lib/sub_diff/diff.rb b/lib/sub_diff/diff.rb
index <HASH>..<HASH> 100644
--- a/lib/sub_diff/diff.rb
+++ b/lib/sub_diff/diff.rb
@@ -1,4 +1,4 @@
-require "delegate"
+require 'delegate'
module SubDiff
class Diff < SimpleDelegator
@@ -15,5 +15,9 @@ module SubDiff
def changed?
value != value_was
end
+
+ def enumerable?
+ changed? || !empty?
+ end
end
end
diff --git a/test/diff_test.rb b/test/diff_test.rb
index <HASH>..<HASH> 100644
--- a/test/diff_test.rb
+++ b/test/diff_test.rb
@@ -25,6 +25,12 @@ module SubDiff
assert !Diff.new('test', 'test').changed?
end
+ def test_enumerable?
+ assert @diff.enumerable?
+ assert @diff_without_value_was.enumerable?
+ assert !Diff.new('', '').enumerable?
+ end
+
def test_to_s
assert_equal @diff.value, @diff.to_s
end
|
Introduce `Diff#enumerable?` method
This will be used by `DiffCollection` in the next commit.
|
shuber_sub_diff
|
train
|
d11c66725d63467fd8d53888a656e99a66460477
|
diff --git a/src/test/java/net/spy/memcached/BinaryClientTest.java b/src/test/java/net/spy/memcached/BinaryClientTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/net/spy/memcached/BinaryClientTest.java
+++ b/src/test/java/net/spy/memcached/BinaryClientTest.java
@@ -52,12 +52,6 @@ public class BinaryClientTest extends ProtocolBaseCase {
TestConfig.PORT_NUMBER));
}
- @Override
- public void testGetStatsCacheDump() throws Exception {
- // XXX: Cachedump isn't returning anything from the server in binprot
- assertTrue(true);
- }
-
public void testCASAppendFail() throws Exception {
final String key = "append.key";
assertTrue(client.set(key, 5, "test").get());
|
Complete the removal of stats cachedump.
Unfortunately, late night coding means I put up a change and
marked it verified, but it makes the project not compile. Not
worth rewriting history for these 5 commits or so, but need
to fix it.
See also <URL>
|
dustin_java-memcached-client
|
train
|
4a7a2d042e8493a4992b3ece2f8b5ee5b80a0693
|
diff --git a/Tests/Controller/DefaultControllerTest.php b/Tests/Controller/DefaultControllerTest.php
index <HASH>..<HASH> 100644
--- a/Tests/Controller/DefaultControllerTest.php
+++ b/Tests/Controller/DefaultControllerTest.php
@@ -41,6 +41,7 @@ class DefaultControllerTest extends WebTestCase
{
$client = static::createClient();
$client->request('GET', '/example/en/pdf');
+ $this->assertEquals(404, $client->getResponse()->getStatusCode());
}
/**
@@ -50,6 +51,7 @@ class DefaultControllerTest extends WebTestCase
{
$client = static::createClient();
$client->request('GET', '/nofile');
+ $this->assertEquals(404, $client->getResponse()->getStatusCode());
}
/**
@@ -59,6 +61,7 @@ class DefaultControllerTest extends WebTestCase
{
$client = static::createClient();
$client->request('GET', '/example/XX');
+ $this->assertEquals(404, $client->getResponse()->getStatusCode());
}
private $curriculumVitae;
|
Add assertions in DefaultControllerTest
|
fabiencrassat_CurriculumVitaeBundle
|
train
|
dc6dc017e706840a9681bef1a75391a91ab6a2e0
|
diff --git a/lib/chef/provider/env.rb b/lib/chef/provider/env.rb
index <HASH>..<HASH> 100644
--- a/lib/chef/provider/env.rb
+++ b/lib/chef/provider/env.rb
@@ -61,8 +61,9 @@ class Chef
def compare_value
if @new_resource.delim
#e.g. check for existing value within PATH
- not @current_resource.value.split(@new_resource.delim).any? do |val|
- val == @new_resource.value
+ current_values = @current_resource.value.split(@new_resource.delim)
+ not @new_resource.value.split(@new_resource.delim).all? do |val|
+ current_values.include? val
end
else
@new_resource.value != @current_resource.value
@@ -91,13 +92,16 @@ class Chef
# after we removed the element.
def delete_element
return false unless @new_resource.delim #no delim: delete the key
- if compare_value
+ values = @new_resource.value.split(@new_resource.delim)
+ current_values = @current_resource.value.split(@new_resource.delim)
+ needs_delete = values.any? { |v| current_values.include?(v) }
+ if not needs_delete
Chef::Log.debug("#{@new_resource} element '#{@new_resource.value}' does not exist")
return true #do not delete the key
else
new_value =
@current_resource.value.split(@new_resource.delim).select { |item|
- item != @new_resource.value
+ values.include?(item)
}.join(@new_resource.delim)
if new_value.empty?
@@ -142,8 +146,11 @@ class Chef
def modify_env
if @new_resource.delim
- #e.g. add to PATH
- @new_resource.value(@new_resource.value + @new_resource.delim + @current_resource.value)
+ current_values = @current_resource.value.split(@new_resource.delim)
+ values = @new_resource.value.split(@new_resource.delim).reject do |v|
+ current_values.include?(v)
+ end
+ @new_resource.value((values + [@current_resource.value]).join(@new_resource.delim))
end
create_env
end
|
Modified env resource to break values up by delimiter before comparing.
For example, if someone were to do before this patch,
```ruby
windows_path 'C:\foo;C:\bar' do
action :create
...
end
```
the path would grow each time this recipe was executed. This is because
compare_path would break up the current path with ;, but would not do
the same for the value being added.
|
chef_chef
|
train
|
45d0f19b7525a8fa1a695cb1ad83eb7bf7559a7c
|
diff --git a/src/Propel/Runtime/Map/ColumnMap.php b/src/Propel/Runtime/Map/ColumnMap.php
index <HASH>..<HASH> 100644
--- a/src/Propel/Runtime/Map/ColumnMap.php
+++ b/src/Propel/Runtime/Map/ColumnMap.php
@@ -348,11 +348,7 @@ class ColumnMap
*/
public function isForeignKey()
{
- if ($this->relatedTableName) {
- return true;
- } else {
- return false;
- }
+ return !empty($this->relatedTableName);
}
/**
@@ -360,16 +356,16 @@ class ColumnMap
*/
public function getRelation()
{
- if(!$this->relatedTableName) {
+ if (!$this->relatedTableName) {
return null;
}
- foreach ($this->getTable()->getRelations() as $name => $relation) {
- if($relation->getType() == RelationMap::MANY_TO_ONE) {
- if ($relation->getForeignTable()->getName() == $this->getRelatedTableName() &&
- array_key_exists($this->getFullyQualifiedName(), $relation->getColumnMappings())) {
- return $relation;
- }
+ foreach ($this->getTable()->getRelations() as $relation) {
+ if ($relation->getType() == RelationMap::MANY_TO_ONE) {
+ if ($relation->getForeignTable()->getName() == $this->getRelatedTableName()
+ && array_key_exists($this->getFullyQualifiedName(), $relation->getColumnMappings())) {
+ return $relation;
+ }
}
}
}
@@ -485,9 +481,9 @@ class ColumnMap
{
if ($this->isText()) {
return $db->ignoreCase($str);
- } else {
- return $str;
}
+
+ return $str;
}
/**
|
[Runtime] [Map] removed some dead code and fixed CS.
|
propelorm_Propel2
|
train
|
097d7ee6d30f91c88135d8398933d1ab72b7534b
|
diff --git a/admin/javascript/src/boot/index.js b/admin/javascript/src/boot/index.js
index <HASH>..<HASH> 100644
--- a/admin/javascript/src/boot/index.js
+++ b/admin/javascript/src/boot/index.js
@@ -26,7 +26,7 @@ function appBoot() {
window.store = createStoreWithMiddleware(rootReducer, initialState);
// Set the initial config state.
- configActions.setConfig(window.ss.config)(window.store.dispatch);
+ window.store.dispatch(configActions.setConfig(window.ss.config));
}
// TODO: This should be using `window.onload` but isn't because
diff --git a/admin/javascript/src/state/config/actions.js b/admin/javascript/src/state/config/actions.js
index <HASH>..<HASH> 100644
--- a/admin/javascript/src/state/config/actions.js
+++ b/admin/javascript/src/state/config/actions.js
@@ -6,9 +6,8 @@ import ACTION_TYPES from './action-types';
* @param object config
*/
export function setConfig(config) {
- return (dispatch) =>
- dispatch({
- type: ACTION_TYPES.SET_CONFIG,
- payload: { config },
- });
+ return {
+ type: ACTION_TYPES.SET_CONFIG,
+ payload: { config },
+ };
}
diff --git a/admin/javascript/src/state/schema/actions.js b/admin/javascript/src/state/schema/actions.js
index <HASH>..<HASH> 100644
--- a/admin/javascript/src/state/schema/actions.js
+++ b/admin/javascript/src/state/schema/actions.js
@@ -6,9 +6,8 @@ import ACTION_TYPES from './action-types';
* @param string schema - JSON schema for the layout.
*/
export function setSchema(schema) {
- return (dispatch) =>
- dispatch({
- type: ACTION_TYPES.SET_SCHEMA,
- payload: schema,
- });
+ return {
+ type: ACTION_TYPES.SET_SCHEMA,
+ payload: schema,
+ };
}
|
Removed unnecessary thunk wrapper in actions
|
silverstripe_silverstripe-framework
|
train
|
872c167f8f5045ef8d5b13316b83ecb28efcc3a3
|
diff --git a/src/Ftp/FtpAdapterTest.php b/src/Ftp/FtpAdapterTest.php
index <HASH>..<HASH> 100644
--- a/src/Ftp/FtpAdapterTest.php
+++ b/src/Ftp/FtpAdapterTest.php
@@ -11,12 +11,6 @@ use League\Flysystem\FilesystemAdapter;
*/
class FtpAdapterTest extends FtpAdapterTestCase
{
- protected function setUp(): void
- {
- parent::setUp();
- $this->retryOnException(UnableToConnectToFtpHost::class);
- }
-
protected static function createFilesystemAdapter(): FilesystemAdapter
{
$options = FtpConnectionOptions::fromArray([
diff --git a/src/Ftp/FtpAdapterTestCase.php b/src/Ftp/FtpAdapterTestCase.php
index <HASH>..<HASH> 100644
--- a/src/Ftp/FtpAdapterTestCase.php
+++ b/src/Ftp/FtpAdapterTestCase.php
@@ -16,7 +16,6 @@ use League\Flysystem\UnableToMoveFile;
use League\Flysystem\UnableToRetrieveMetadata;
use League\Flysystem\UnableToWriteFile;
use League\Flysystem\Visibility;
-use Throwable;
/**
* @group ftp
@@ -24,25 +23,10 @@ use Throwable;
*/
abstract class FtpAdapterTestCase extends FilesystemAdapterTestCase
{
- protected function runScenario(callable $callable): void
+ protected function setUp(): void
{
- $exception = null;
- $tries = 0;
-
- while ($tries < 10) {
- try {
- $callable();
-
- return;
- } catch (FtpConnectionException $exception) {
- sleep(1);
- $tries++;
- }
- }
-
- if ($exception instanceof Throwable) {
- throw $exception;
- }
+ parent::setUp();
+ $this->retryOnException(UnableToConnectToFtpHost::class);
}
/**
|
Retry on all ftp cases
|
thephpleague_flysystem
|
train
|
af21d970a604a64a8ebf7be70586dd85bc82f611
|
diff --git a/src/value.js b/src/value.js
index <HASH>..<HASH> 100644
--- a/src/value.js
+++ b/src/value.js
@@ -6,14 +6,29 @@ function removeFlags(value) {
return value.replace(/\!\w+/g, '');
}
+function removeInlineComments(value) {
+ var transformedValue = value;
+ var commentIndex = value.indexOf('//');
+
+ if (commentIndex > -1) {
+ transformedValue = transformedValue.substring(0, commentIndex - 1);
+ }
+
+ return transformedValue;
+}
+
+function transforms(value) {
+ return removeInlineComments(removeFlags(value));
+}
+
function Value(scssString) {
this._parse(scssString);
}
Value.prototype = {
_parse: function(scssString) {
- var deflagged = removeFlags(scssString);
- var compiled = compile.fromString(deflagged);
+ var transformed = transforms(scssString);
+ var compiled = compile.fromString(transformed);
this.value = compiled.trim();
}
};
|
making failing tests pass with inline comments
|
ryanbahniuk_scss-to-json
|
train
|
c7c849a174914f95d132dfb498c793b449ca9b25
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -47,6 +47,7 @@
* request broker now supports turning param values into instances of `stubbles\lang\SecureString` with `@Request[SecureString]`
* added `net\stubbles\input\filter\PasswordChecker`
* request broker annotation `@Request[Password]` now supports `minLength` attribute, default value is 8
+ * request broker annotation `@Request[OneOf]` now throws an exception when list of allowed values is missing in annotation
2.5.1 (2014-05-07)
diff --git a/src/main/php/broker/param/OneOfParamBroker.php b/src/main/php/broker/param/OneOfParamBroker.php
index <HASH>..<HASH> 100644
--- a/src/main/php/broker/param/OneOfParamBroker.php
+++ b/src/main/php/broker/param/OneOfParamBroker.php
@@ -9,6 +9,7 @@
*/
namespace stubbles\input\broker\param;
use stubbles\input\valuereader\CommonValueReader;
+use stubbles\lang\exception\RuntimeException;
use stubbles\lang\reflect\annotation\Annotation;
/**
* Filter values based on a @Request[OneOf] annotation.
@@ -31,7 +32,8 @@ class OneOfParamBroker extends MultipleSourceParamBroker
* reads default value
*
* @param Annotation $annotation
- * @return array
+ * @return string[]
+ * @throws RuntimeException
*/
private function getAllowedValues(Annotation $annotation)
{
@@ -39,6 +41,6 @@ class OneOfParamBroker extends MultipleSourceParamBroker
return array_map('trim', explode('|', $annotation->getAllowed()));
}
- return [];
+ throw new RuntimeException('No list of allowed values in annotation @Request[OneOf]');
}
}
diff --git a/src/test/php/broker/param/OneOfParamBrokerTest.php b/src/test/php/broker/param/OneOfParamBrokerTest.php
index <HASH>..<HASH> 100644
--- a/src/test/php/broker/param/OneOfParamBrokerTest.php
+++ b/src/test/php/broker/param/OneOfParamBrokerTest.php
@@ -165,4 +165,16 @@ class OneOfParamBrokerTest extends MultipleSourceParamBrokerTest
)
);
}
+
+ /**
+ * @test
+ * @expectedException stubbles\lang\exception\RuntimeException
+ * @since 3.0.0
+ */
+ public function throwsRuntimeAnnotationWhenListOfAllowedValuesIsMissing()
+ {
+ $this->paramBroker->procure($this->mockRequest(((string) $this->getExpectedValue())),
+ $this->createRequestAnnotation()
+ );
+ }
}
|
request broker annotation @Request[OneOf now throws an exception when list of allowed values is missing in annotation
|
stubbles_stubbles-input
|
train
|
244dbf2313f64b79a520ec4eb4ec11304df1e675
|
diff --git a/spec/generic/remove.spec.js b/spec/generic/remove.spec.js
index <HASH>..<HASH> 100644
--- a/spec/generic/remove.spec.js
+++ b/spec/generic/remove.spec.js
@@ -66,4 +66,25 @@ describe('remove', function () {
users.insert(bar);
expect(users.data.length).toEqual(1);
});
+
+ it('removes with unique index', function () {
+ var db = new loki();
+ var users1 = db.addCollection('userswithunique', {
+ unique: ['username']
+ });
+
+ var joe = users1.insert({
+ username: 'joe',
+ name: 'joe',
+ age: 39
+ });
+ var jack = users1.insert({
+ username: 'jack',
+ name: 'jack',
+ age: 20
+ });
+ expect(users1.data.length).toEqual(2);
+ users1.removeDataOnly();
+ expect(users1.data.length).toEqual(0);
+ });
});
|
Added test to prove remove with unique index is broken. Test Fails
|
techfort_LokiJS
|
train
|
e8495135550210f8a7634a9043122abaa43df96c
|
diff --git a/lib/gir_ffi/arg_helper.rb b/lib/gir_ffi/arg_helper.rb
index <HASH>..<HASH> 100644
--- a/lib/gir_ffi/arg_helper.rb
+++ b/lib/gir_ffi/arg_helper.rb
@@ -8,48 +8,43 @@ module GirFFI
FFI::Pointer.new(obj.object_id)
end
- def self.int32_array_to_inptr ary
+ def self.typed_array_to_inptr type, ary
return nil if ary.nil?
- block = allocate_array_of_type :int32, ary.length
- block.write_array_of_int32 ary
+ block = allocate_array_of_type type, ary.length
+ block.send "put_array_of_#{type}", 0, ary
block
end
+ def self.int32_array_to_inptr ary
+ typed_array_to_inptr :int32, ary
+ end
+
# TODO: Use alias.
def self.int_array_to_inptr ary
int32_array_to_inptr ary
end
def self.int16_array_to_inptr ary
- block = allocate_array_of_type :int16, ary.length
- block.write_array_of_int16 ary
- block
+ typed_array_to_inptr :int16, ary
end
def self.int64_array_to_inptr ary
- block = allocate_array_of_type :int64, ary.length
- block.write_array_of_int64 ary
- block
+ typed_array_to_inptr :int64, ary
end
def self.int8_array_to_inptr ary
- block = allocate_array_of_type :int8, ary.length
- block.write_array_of_int8 ary
- block
+ typed_array_to_inptr :int8, ary
end
def self.GType_array_to_inptr ary
case FFI.type_size(:size_t)
when 4
- block = allocate_array_of_type :uint32, ary.length
- block.write_array_of_uint32 ary
+ int32_array_to_inptr ary
when 8
- block = allocate_array_of_type :uint64, ary.length
- block.write_array_of_uint64 ary
+ int64_array_to_inptr ary
else
raise RuntimeError, "Unexpected size of :size_t"
end
- block
end
def self.cleanup_ptr ptr
|
Use more bare-metal memory writer methods, so things work with JRuby.
|
mvz_gir_ffi
|
train
|
2dbc08e3221e07a9e618eaa025d98ed197d28e31
|
diff --git a/bittrex/bittrex.py b/bittrex/bittrex.py
index <HASH>..<HASH> 100644
--- a/bittrex/bittrex.py
+++ b/bittrex/bittrex.py
@@ -5,7 +5,7 @@
import time
import hmac
import hashlib
-
+import sys
try:
from urllib import urlencode
except ImportError:
@@ -147,9 +147,17 @@ class Bittrex(object):
request_url += urlencode(options)
try:
- apisign = hmac.new(self.api_secret.encode(),
- request_url.encode(),
- hashlib.sha512).hexdigest()
+ if sys.version_info >= (3, 0) and protection != PROTECTION_PUB:
+
+ apisign = hmac.new(bytearray(self.api_secret, 'ascii'),
+ bytearray(request_url, 'ascii'),
+ hashlib.sha512).hexdigest()
+
+ else:
+
+ apisign = hmac.new(self.api_secret.encode(),
+ request_url.encode(),
+ hashlib.sha512).hexdigest()
self.wait()
|
Fix for INVALID_SIGNATURE in python3.x.x (#<I>)
|
ericsomdahl_python-bittrex
|
train
|
c502128c50ac4085127bd195bc128ca8b2d60562
|
diff --git a/pkg/cmd/openshift-kube-apiserver/kubeadmission/register.go b/pkg/cmd/openshift-kube-apiserver/kubeadmission/register.go
index <HASH>..<HASH> 100644
--- a/pkg/cmd/openshift-kube-apiserver/kubeadmission/register.go
+++ b/pkg/cmd/openshift-kube-apiserver/kubeadmission/register.go
@@ -96,6 +96,8 @@ func NewDefaultOffPluginsFunc(kubeDefaultOffAdmission sets.String) func() sets.S
kubeOff.Delete(additionalDefaultOnPlugins.List()...)
kubeOff.Delete(openshiftAdmissionPluginsForKube...)
kubeOff.Delete(customresourcevalidationregistration.AllCustomResourceValidators...)
+ // temporarily disable RBR until we move it to a CRD (it is causing install timeout failures)
+ kubeOff.Insert("authorization.openshift.io/RestrictSubjectBindings")
return kubeOff
}
}
|
Temporarily disable RBR until we move it to a CRD
|
openshift_origin
|
train
|
610716d3d1ca661a9487bac774992fb532c6a8e0
|
diff --git a/pre_commit/clientlib.py b/pre_commit/clientlib.py
index <HASH>..<HASH> 100644
--- a/pre_commit/clientlib.py
+++ b/pre_commit/clientlib.py
@@ -112,6 +112,18 @@ LOCAL = 'local'
META = 'meta'
+class OptionalSensibleRegex(cfgv.OptionalNoDefault):
+ def check(self, dct: Dict[str, Any]) -> None:
+ super().check(dct)
+
+ if '/*' in dct.get(self.key, ''):
+ logger.warning(
+ f'The {self.key!r} field in hook {dct.get("id")!r} is a '
+ f"regex, not a glob -- matching '/*' probably isn't what you "
+ f'want here',
+ )
+
+
class MigrateShaToRev:
key = 'rev'
@@ -227,6 +239,8 @@ CONFIG_HOOK_DICT = cfgv.Map(
for item in MANIFEST_HOOK_DICT.items
if item.key != 'id'
),
+ OptionalSensibleRegex('files', cfgv.check_string),
+ OptionalSensibleRegex('exclude', cfgv.check_string),
)
CONFIG_REPO_DICT = cfgv.Map(
'Repository', 'repo',
diff --git a/tests/clientlib_test.py b/tests/clientlib_test.py
index <HASH>..<HASH> 100644
--- a/tests/clientlib_test.py
+++ b/tests/clientlib_test.py
@@ -166,6 +166,23 @@ def test_validate_warn_on_unknown_keys_at_top_level(tmpdir, caplog):
]
+def test_validate_optional_sensible_regex(caplog):
+ config_obj = {
+ 'id': 'flake8',
+ 'files': 'dir/*.py',
+ }
+ cfgv.validate(config_obj, CONFIG_HOOK_DICT)
+
+ assert caplog.record_tuples == [
+ (
+ 'pre_commit',
+ logging.WARNING,
+ "The 'files' field in hook 'flake8' is a regex, not a glob -- "
+ "matching '/*' probably isn't what you want here",
+ ),
+ ]
+
+
@pytest.mark.parametrize('fn', (validate_config_main, validate_manifest_main))
def test_mains_not_ok(tmpdir, fn):
not_yaml = tmpdir.join('f.notyaml')
|
added warning if globs are used instead of regex
|
pre-commit_pre-commit
|
train
|
94cd315f21937bb839fb433638e4757c4d68660c
|
diff --git a/client.go b/client.go
index <HASH>..<HASH> 100644
--- a/client.go
+++ b/client.go
@@ -33,6 +33,7 @@ func main() {
flag.Parse()
log.SetFlags(log.Ltime | log.Lshortfile)
api.Domain = *eshost
+ core.VerboseLogging = true
response, _ := core.Index("twitter", "tweet", "1", nil, NewTweet("kimchy", "Search is cool"))
indices.Flush()
log.Printf("Index OK: %v", response.Ok)
diff --git a/core/index.go b/core/index.go
index <HASH>..<HASH> 100644
--- a/core/index.go
+++ b/core/index.go
@@ -22,6 +22,10 @@ import (
"github.com/mattbaird/elastigo/api"
)
+// VerboseLogging controls whether elastigo will log more information
+// about its actions. Set it to false for less logging.
+var VerboseLogging bool = true;
+
// Index adds or updates a typed JSON document in a specific index, making it searchable, creating an index
// if it did not exist.
// if id is omited, op_type 'create' will be passed and http method will default to "POST"
@@ -56,7 +60,9 @@ func IndexWithParameters(index string, _type string, id string, parentId string,
} else {
method = "PUT"
}
- log.Printf("about to :%v %v %s", url, args, data)
+ if VerboseLogging {
+ log.Printf("about to :%v %v %s", url, args, data)
+ }
body, err := api.DoCommand(method, url, args, data)
if err != nil {
return retval, err
|
Make it logging verbosity configurable.
Don't log every indexing event if `VerboseLogging` is set to `false`.
|
mattbaird_elastigo
|
train
|
932ce1e531a9da74a4ee36aa769311aaa72e36db
|
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -8,13 +8,14 @@
"test": "mocha"
},
"dependencies" : {
- "cradle": ">=0.6",
- "object_utils": ">=0.1.0"
+ "cradle": "^0.6.7",
+ "object_utils": ">=0.1.0",
+ "async": "^0.9.0"
},
"analyze": false,
"devDependencies": {
- "mocha": "*",
- "should": "*"
+ "mocha": "^1.20.1",
+ "should": "^4.0.4"
},
"repository": {
"type": "git",
diff --git a/src/cradle_security.js b/src/cradle_security.js
index <HASH>..<HASH> 100644
--- a/src/cradle_security.js
+++ b/src/cradle_security.js
@@ -37,6 +37,7 @@ module.exports = function (config) {
var utils = require('object_utils');
var util = require('util');
var couchDB = require('cradle');
+ var async = require('async');
// namespace
var my = {};
@@ -289,36 +290,9 @@ module.exports = function (config) {
couchDB.Database.prototype.createWithUser = function (username, password, roles, callback) {
// create new database
var self = this;
- var err,
- res,
- resDbCreated,
- totalCallbacks = 0,
- maxCallbacks = 3;
-
- function callbackManager(taskErr, taskRes) {
- err = taskErr || err;
- res = taskRes || err;
- totalCallbacks++;
- if (totalCallbacks === maxCallbacks) {
- if (logger) {
- logger.info(res);
- if (err) {
- logger.error(util.format('Error during %s database creation', self.name), err);
- } else {
- logger.info(util.format('Database %s created', self.name));
- }
- }
- if (err) {
- callback(err, res);
- } else {
- callback(err, resDbCreated);
- }
- }
- }
self.create(function (errDb, resDb) {
if (logger) {
- logger.info(resDb);
if (errDb) {
logger.error(util.format('Error during %s database creation', self.name), errDb);
}
@@ -326,14 +300,46 @@ module.exports = function (config) {
if (errDb) {
callback(errDb, resDb);
} else {
- resDbCreated = resDb;
- totalCallbacks = 0;
- // add user to couchdb users
- self.addUser(username, password, roles, callbackManager);
- // add roles
- self.addRoles(my.config.adminRoles, my.config.memberRoles, callbackManager);
- // add authorization
- self.addAuthorization(callbackManager);
+ async.parallel({
+ roles: function (cb) {
+ // add roles
+ self.addRoles(my.config.adminRoles, my.config.memberRoles, cb);
+ },
+ user: function (cb) {
+ var userDb = self.connection.database('_users');
+ // add user if it does not exists
+ var realName = util.format('%s%s', userPrefix, username);
+ userDb.get(realName, function (userErr, userDoc) {
+ if (!userDoc) {
+ // add user to couchdb users
+ self.addUser(username, password, roles, cb);
+ } else {
+ cb(null, {
+ ok: true,
+ id: userDoc._id,
+ rev: userDoc._rev
+ });
+ }
+ });
+ },
+ auth: function (cb) {
+ // add authorization
+ self.addAuthorization(cb);
+ }
+ }, function (err, res) {
+ if (logger) {
+ if (err) {
+ logger.error(util.format('Error during %s database creation', self.name), err);
+ } else {
+ logger.info(util.format('Database %s created', self.name));
+ }
+ }
+ if (err) {
+ callback(err, res);
+ } else {
+ callback(err, {ok: true});
+ }
+ });
}
});
};
diff --git a/test/test.js b/test/test.js
index <HASH>..<HASH> 100644
--- a/test/test.js
+++ b/test/test.js
@@ -75,6 +75,25 @@ describe('Cradle Security test', function () {
}
});
});
+ it('should delete database', function (done) {
+ db = conn.database(dbName);
+ db.destroy(done);
+ });
+ it('should create a new database with existing user', function (done) {
+ db = conn.database(dbName);
+ db.exists(function (err, exists) {
+ if (!exists) {
+ db.createWithUser(dbUsername, dbUserPassword, [ "admins" ], function (err, res) {
+ res.ok.should.true;
+ done();
+ });
+ }
+ });
+ });
+ it('should delete database', function (done) {
+ db = conn.database(dbName);
+ db.destroy(done);
+ });
it('should delete user', function (done) {
db = conn.database(dbName);
db.delUser(dbUsername, function (err, res) {
@@ -82,9 +101,4 @@ describe('Cradle Security test', function () {
done();
});
});
- it('should delete database', function (done) {
- db = conn.database(dbName);
- db.destroy(dbName);
- done();
- });
});
\ No newline at end of file
|
Parallel creation of database with user, roles and authorization
|
mgesmundo_cradle_security
|
train
|
6ba87e2ced666b6a3d7dde5955589945c5869a01
|
diff --git a/src/Entities/GatewayAccount.php b/src/Entities/GatewayAccount.php
index <HASH>..<HASH> 100644
--- a/src/Entities/GatewayAccount.php
+++ b/src/Entities/GatewayAccount.php
@@ -20,17 +20,20 @@ use Rebilly\Rest\Entity;
* {
* "id"
* "gatewayName",
+ * "gatewayConfig",
* "merchantCategoryCode",
- * "descriptor",
- * "city",
+ * "acquirerName'"
* "organizationId",
* "websites",
- * "acquirerName'"
+ * "paymentMethods"
+ * "descriptor",
+ * "city",
+ * "dynamicDescriptor"
+ * "can3DSecure"
* "monthlyLimit",
* "acceptedCurrencies",
* "downtimeStart",
* "downtimeEnd",
- * "gatewayConfig",
* }
* ```
*
@@ -39,6 +42,42 @@ use Rebilly\Rest\Entity;
*/
final class GatewayAccount extends Entity
{
+ const PAYMENT_METHOD_VISA = 'Visa';
+ const PAYMENT_METHOD_MASTERCARD = 'Mastercard';
+ const PAYMENT_METHOD_AMERICAN_EXPRESS = 'American_Express';
+ const PAYMENT_METHOD_DISCOVER = 'Discover';
+ const PAYMENT_METHOD_MAESTRO = 'Maestro';
+ const PAYMENT_METHOD_SOLO = 'Solo';
+ const PAYMENT_METHOD_ELECTRON = 'Electron';
+ const PAYMENT_METHOD_JCB = 'JCB';
+ const PAYMENT_METHOD_VOYAGER = 'Voyager';
+ const PAYMENT_METHOD_DINERS_CLUB = 'Diners_Club';
+ const PAYMENT_METHOD_SWITCH = 'Switch';
+ const PAYMENT_METHOD_LASER = 'Laser';
+
+ const MSG_UNEXPECTED_TYPE = 'Unexpected payment method. Only %s methods support';
+
+ /**
+ * @return array
+ */
+ public static function allowedPaymentMethods()
+ {
+ return [
+ self::PAYMENT_METHOD_VISA,
+ self::PAYMENT_METHOD_MASTERCARD,
+ self::PAYMENT_METHOD_AMERICAN_EXPRESS,
+ self::PAYMENT_METHOD_DISCOVER,
+ self::PAYMENT_METHOD_MAESTRO,
+ self::PAYMENT_METHOD_SOLO,
+ self::PAYMENT_METHOD_ELECTRON,
+ self::PAYMENT_METHOD_JCB,
+ self::PAYMENT_METHOD_VOYAGER,
+ self::PAYMENT_METHOD_DINERS_CLUB,
+ self::PAYMENT_METHOD_SWITCH,
+ self::PAYMENT_METHOD_LASER
+ ];
+ }
+
/**
* @return string
*/
@@ -261,4 +300,64 @@ final class GatewayAccount extends Entity
{
return $this->setAttribute('gatewayConfig', $value);
}
+
+ /**
+ * @return bool
+ */
+ public function getDynamicDescriptor()
+ {
+ return $this->getAttribute('dynamicDescriptor');
+ }
+
+ /**
+ * @param bool $value
+ *
+ * @return $this
+ */
+ public function setDynamicDescriptor($value)
+ {
+ return $this->setAttribute('dynamicDescriptor', $value);
+ }
+
+ /**
+ * @return bool
+ */
+ public function getCan3DSecure()
+ {
+ return $this->getAttribute('can3DSecure');
+ }
+
+ /**
+ * @param bool $value
+ *
+ * @return $this
+ */
+ public function setCan3DSecure($value)
+ {
+ return $this->setAttribute('can3DSecure', $value);
+ }
+
+ /**
+ * @return array
+ */
+ public function getPaymentMethods()
+ {
+ return $this->getAttribute('paymentMethods');
+ }
+
+ /**
+ * @param array $value
+ *
+ * @return $this
+ */
+ public function setPaymentMethods($value)
+ {
+ foreach ($value as $paymentMethod) {
+ if (!in_array($paymentMethod, self::allowedPaymentMethods())) {
+ throw new DomainException(sprintf(self::MSG_UNEXPECTED_TYPE, implode(', ', self::allowedPaymentMethods())));
+ }
+ }
+
+ return $this->setAttribute('paymentMethods', $value);
+ }
}
|
paymentMethods, can3DSecure, dynamicDescriptor refactor
|
Rebilly_rebilly-php
|
train
|
7b36f7a8f398046561615a4b9a0d355135664fa0
|
diff --git a/web/concrete/core/models/block_types.php b/web/concrete/core/models/block_types.php
index <HASH>..<HASH> 100644
--- a/web/concrete/core/models/block_types.php
+++ b/web/concrete/core/models/block_types.php
@@ -532,6 +532,7 @@ defined('C5_EXECUTE') or die("Access Denied.");
}
$templates = array_unique($templates);
+ asort($templates);
return $templates;
}
|
Sort the list of custom templates for a block
The list of custom templates for a block can become unwieldy when a block has many custom templates. Sorting them by name makes it a lot easier to find a template.
Should this also apply a t() to the names so they are translated?
Former-commit-id: <I>b<I>d<I>f2c<I>b<I>ebf4edd3a<I>
|
concrete5_concrete5
|
train
|
71c08d28b9706baa9484b7d5e322da18f11e2aaa
|
diff --git a/spyderlib/widgets/externalshell/startup.py b/spyderlib/widgets/externalshell/startup.py
index <HASH>..<HASH> 100644
--- a/spyderlib/widgets/externalshell/startup.py
+++ b/spyderlib/widgets/externalshell/startup.py
@@ -276,6 +276,7 @@ on Windows platforms (only IPython v0.10 is fully supported).
'runfile': runfile,
'debugfile': debugfile})
__ipythonshell__.IP.stdin_encoding = os.environ['SPYDER_ENCODING']
+ __ipythonshell__.IP.autoindent = 0
# Workaround #2 to make the HDF5 I/O variable explorer plugin work:
# we import h5py only after initializing IPython in order to avoid
|
(Fixes Issue <I>) Console/IPython Interpreter: Turn off autoindent magic to avoid indentation errors with code with inline comments
Special thanks to jorisvandenbossche<at>gmail<dot>com for discovering the solution
|
spyder-ide_spyder
|
train
|
c7f9a0d2e3f0040c26102a33590d958d2018aac2
|
diff --git a/andes/models/renewable/wtdta1.py b/andes/models/renewable/wtdta1.py
index <HASH>..<HASH> 100644
--- a/andes/models/renewable/wtdta1.py
+++ b/andes/models/renewable/wtdta1.py
@@ -121,7 +121,7 @@ class WTDTA1Model(Model):
self.wg = AliasState(self.s2_y, tex_name=r'\omega_g')
- # TODO: `s3_y` needs to be properly reinitialized with the new `wr0`
+ # `s3_y` gets reinitialized in `WTTQA1`
self.s3 = Integrator(u='s1_y - s2_y',
T=1.0,
K=self.Kshaft,
diff --git a/andes/models/renewable/wttqa1.py b/andes/models/renewable/wttqa1.py
index <HASH>..<HASH> 100644
--- a/andes/models/renewable/wttqa1.py
+++ b/andes/models/renewable/wttqa1.py
@@ -130,9 +130,10 @@ class WTTQA1Model(Model):
self.reg = ExtParam(model='RenExciter', src='reg', indexer=self.ree,
export=False,)
- self.Sngo = ExtParam(model='RenGovernor', src='Sn', indexer=self.rego,
+ self.Sngo = ExtParam(model='RenGen', src='Sn', indexer=self.reg,
tex_name='S_{n,go}', export=False,
)
+
self.Sn = NumSelect(self.Tn,
fallback=self.Sngo,
tex_name='S_n',
@@ -173,7 +174,7 @@ class WTTQA1Model(Model):
self.s3_y = ExtState(model='RenGovernor', src='s3_y', indexer=self.rego,
tex_name='y_{s3}', export=False,
- v_str='Pref0 / wg / Kshaft',
+ v_str='Pref0 / wg',
v_setter=True,
)
|
[WIP] Fix WTDTA1's initialization due to WTTQA1.
|
cuihantao_andes
|
train
|
42e0cf4dff531ec5d754e75276c3821d169ed977
|
diff --git a/lib/plugins/aws/invokeLocal/fixture/handlerWithSuccess.js b/lib/plugins/aws/invokeLocal/fixture/handlerWithSuccess.js
index <HASH>..<HASH> 100644
--- a/lib/plugins/aws/invokeLocal/fixture/handlerWithSuccess.js
+++ b/lib/plugins/aws/invokeLocal/fixture/handlerWithSuccess.js
@@ -4,6 +4,8 @@ module.exports.withErrorByDone = (event, context) => {
context.done(new Error('failed'));
};
+module.exports.withMessageByReturn = () => 'Succeed';
+
module.exports.withMessageByDone = (event, context) => {
context.done(null, 'Succeed');
};
diff --git a/lib/plugins/aws/invokeLocal/index.js b/lib/plugins/aws/invokeLocal/index.js
index <HASH>..<HASH> 100644
--- a/lib/plugins/aws/invokeLocal/index.js
+++ b/lib/plugins/aws/invokeLocal/index.js
@@ -359,8 +359,8 @@ class AwsInvokeLocal {
}
const maybeThennable = lambda(event, context, callback);
- if (!_.isUndefined(maybeThennable) && _.isFunction(maybeThennable.then)) {
- return maybeThennable
+ if (!_.isUndefined(maybeThennable)) {
+ return Promise.resolve(maybeThennable)
.then(
callback.bind(this, null),
callback.bind(this)
diff --git a/lib/plugins/aws/invokeLocal/index.test.js b/lib/plugins/aws/invokeLocal/index.test.js
index <HASH>..<HASH> 100644
--- a/lib/plugins/aws/invokeLocal/index.test.js
+++ b/lib/plugins/aws/invokeLocal/index.test.js
@@ -433,6 +433,15 @@ describe('AwsInvokeLocal', () => {
serverless.cli.consoleLog.restore();
});
+ describe('with sync return value', () => {
+ it('should succeed if succeed', () => {
+ awsInvokeLocal.serverless.config.servicePath = __dirname;
+
+ return awsInvokeLocal.invokeLocalNodeJs('fixture/handlerWithSuccess', 'withMessageByReturn')
+ .then(() => expect(serverless.cli.consoleLog.lastCall.args[0]).to.contain('"Succeed"'));
+ });
+ });
+
describe('with done method', () => {
it('should exit with error exit code', () => {
awsInvokeLocal.serverless.config.servicePath = __dirname;
|
test invoke local support for returning value directly and fix it
|
serverless_serverless
|
train
|
799c616a7855479c5276848605f5555c1b991198
|
diff --git a/src/FormComponents/index.js b/src/FormComponents/index.js
index <HASH>..<HASH> 100644
--- a/src/FormComponents/index.js
+++ b/src/FormComponents/index.js
@@ -363,7 +363,7 @@ export const renderReactSelect = props => {
? valueToUse.filter(val => !!val).map(function(val) {
return val.value;
})
- : valueToUse ? valueToUse.value : "";
+ : valueToUse;
if (rest.submitOnBlur) {
onFieldSubmit(valToPass);
}
diff --git a/src/showConfirmationDialog/index.js b/src/showConfirmationDialog/index.js
index <HASH>..<HASH> 100644
--- a/src/showConfirmationDialog/index.js
+++ b/src/showConfirmationDialog/index.js
@@ -3,23 +3,23 @@ import React, { Component } from "react";
import { Alert, Intent } from "@blueprintjs/core";
import ReactDOM from "react-dom";
-export function renderOnDoc(fn) {
- const elemDiv = document.createElement("div");
- elemDiv.style.cssText =
- "position:absolute;width:100%;height:100%;top:0px;opacity:0.3;z-index:100;";
- document.body.appendChild(elemDiv);
- const handleClose = () => {
- setTimeout(() => {
- ReactDOM.unmountComponentAtNode(elemDiv);
- document.body.removeChild(elemDiv);
- });
- };
- return ReactDOM.render(fn(handleClose), elemDiv);
-}
-
+// usage
+// showConfirmationDialog({
+// text:
+// "Are you sure you want to re-run this tool? Downstream tools with linked outputs will need to be re-run as well!",
+// onConfirm: async () => {
+// //confirm stuff
+// },
+// onCancel: () => {
+// //cancel Stuff
+// }
+// });
+//returns a promise that resolves with true or false depending on if the user cancels or not!
export default function showConfirmationDialog(opts) {
- return renderOnDoc(handleClose => {
- return <AlertWrapper {...{ ...opts, handleClose }} />;
+ return new Promise(resolve => {
+ renderOnDoc(handleClose => {
+ return <AlertWrapper {...{ ...opts, handleClose, resolve }} />;
+ });
});
}
@@ -30,31 +30,41 @@ class AlertWrapper extends Component {
handleClose,
children,
text = "customize like -- {text: 'your text here'} ",
- onCancel = () => {},
+ resolve,
cancelButtonText = "Cancel",
- onConfirm = () => {},
intent = Intent.PRIMARY,
...rest
} = this.props;
+ const doClose = confirm => {
+ handleClose();
+ this.setState({ isOpen: false });
+ resolve(confirm);
+ };
return (
<Alert
isOpen={this.state.isOpen}
intent={intent}
- onCancel={(...args) => {
- handleClose();
- this.setState({ isOpen: false });
- onCancel(...args);
- }}
cancelButtonText={cancelButtonText}
- onConfirm={(...args) => {
- handleClose();
- this.setState({ isOpen: false });
- onConfirm(...args);
- }}
+ onCancel={() => doClose(false)}
+ onConfirm={() => doClose(true)}
{...rest}
>
- {children || text}{" "}
+ {children || text}
</Alert>
);
}
}
+
+export function renderOnDoc(fn) {
+ const elemDiv = document.createElement("div");
+ elemDiv.style.cssText =
+ "position:absolute;width:100%;height:100%;top:0px;opacity:0.3;z-index:100;";
+ document.body.appendChild(elemDiv);
+ const handleClose = () => {
+ setTimeout(() => {
+ ReactDOM.unmountComponentAtNode(elemDiv);
+ document.body.removeChild(elemDiv);
+ });
+ };
+ return ReactDOM.render(fn(handleClose), elemDiv);
+}
|
Update showConfirmationDialog to be promise based
|
TeselaGen_teselagen-react-components
|
train
|
cad33bb3f8313df308deafd3fdf7e38d3114bfcc
|
diff --git a/CHANGELOG b/CHANGELOG
index <HASH>..<HASH> 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,4 +1,5 @@
August 2017
+ 1.56 Transaction timeout support
1.55 Transaction <STAN></STAN> support
1.54 PIN Change transaction support (processing code 760000)
1.53 PostBridge2 interface support
diff --git a/bpc8583/transaction.py b/bpc8583/transaction.py
index <HASH>..<HASH> 100644
--- a/bpc8583/transaction.py
+++ b/bpc8583/transaction.py
@@ -8,7 +8,7 @@ from bpc8583.spec import IsoSpec, IsoSpec1987BPC
from pytlv.TLV import TLV
class Transaction():
- def __init__(self, type, card, term, icc_trxn=None):
+ def __init__(self, type, card, term, icc_trxn=None, timeout=None):
"""
"""
self.TLV = TLV()
@@ -24,6 +24,7 @@ class Transaction():
self.PIN = None
self._set_icc_trxn(icc_trxn)
self.field48 = {}
+ self.timeout = int(timeout) if timeout else 0
if self.type in ['logon', 'echo']:
"""
@@ -196,6 +197,13 @@ class Transaction():
self.IsoMessage.FieldData(52, encrypted_pinblock)
self.rebuild()
+
+ def get_PIN(self):
+ """
+ """
+ return self.PIN
+
+
def set_STAN(self, STAN):
"""
"""
@@ -206,10 +214,10 @@ class Transaction():
raise ValueError('Invalid STAN')
- def get_PIN(self):
+ def get_timeout(self):
"""
"""
- return self.PIN
+ return self.timeout
def set_amount(self, amount):
diff --git a/examples/isoClient.py b/examples/isoClient.py
index <HASH>..<HASH> 100755
--- a/examples/isoClient.py
+++ b/examples/isoClient.py
@@ -40,6 +40,8 @@ class isoClient:
"""
self.term.connect()
for trxn in self.transactions:
+ time.sleep(trxn.get_timeout())
+
# Re-encrypt PIN block if terminal key has changed
PIN = trxn.get_PIN()
if PIN:
@@ -143,6 +145,7 @@ def parse_transaction_item(trxn, term, cards):
card = None
card_description = None
icc_trxn = None
+ timeout = None
#card = cards[trxn.attrib['card']]
try:
@@ -163,7 +166,12 @@ def parse_transaction_item(trxn, term, cards):
pass
try:
- t = Transaction(trxn.attrib['type'], card, term, icc_trxn=icc_trxn)
+ timeout = trxn.attrib['timeout']
+ except KeyError:
+ pass
+
+ try:
+ t = Transaction(trxn.attrib['type'], card, term, icc_trxn, timeout)
except KeyError:
print('Error parsing {}: transaction type is not set'.format(filename))
sys.exit()
diff --git a/examples/transactions.xml b/examples/transactions.xml
index <HASH>..<HASH> 100644
--- a/examples/transactions.xml
+++ b/examples/transactions.xml
@@ -72,7 +72,7 @@
<PIN>1234</PIN>
<STAN>744321</STAN>
</trxn>
- <trxn type='pin change reversal' description='PIN change reversal' card='8990011234567890' icc='false'>
+ <trxn type='pin change reversal' description='PIN change reversal' card='8990011234567890' icc='false' timeout='5'>
<PIN>1234</PIN>
<STAN>744321</STAN>
</trxn>
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -1,7 +1,7 @@
from setuptools import setup
setup(name='bpc8583',
- version='1.55',
+ version='1.56',
description='ISO8583 library and tools (BPC\'s flavour)',
long_description=open('README.rst').read(),
|
<I> Transaction timeout support
|
timgabets_bpc8583
|
train
|
40e28de36659ceb21d4f884160461e0d9f2b1eac
|
diff --git a/app/assets/javascripts/IndividualResult.js b/app/assets/javascripts/IndividualResult.js
index <HASH>..<HASH> 100644
--- a/app/assets/javascripts/IndividualResult.js
+++ b/app/assets/javascripts/IndividualResult.js
@@ -24,12 +24,14 @@ const IndividualResultSchema = mongoose.Schema(
// Result Attributes
clause_results: Mixed,
episode_results: Mixed,
- population_relevance: Mixed,
- statement_relevance: Mixed,
statement_results: Mixed,
// Calculation State attributes
- state: String,
+ state: {
+ type: String,
+ enum: ['queued', 'running', 'complete', 'cancelled', 'failed'],
+ default: 'queued',
+ },
// Relations to other model classes
measure: { type: ObjectId, ref: 'Measure' },
diff --git a/app/models/qdm/tacoma/individual_result.rb b/app/models/qdm/tacoma/individual_result.rb
index <HASH>..<HASH> 100644
--- a/app/models/qdm/tacoma/individual_result.rb
+++ b/app/models/qdm/tacoma/individual_result.rb
@@ -4,6 +4,9 @@ module QDM
include Mongoid::Document
include Mongoid::Timestamps
+ # This is the Mongoid equivalent of the Mongoose "enum" attribute for :state. Throws an error if you try to assign a value that's not in this array.
+ validates_inclusion_of :state, in: %w[queued running complete cancelled failed]
+
# Population Attributes
field :STRAT, type: Integer
field :IPP, type: Integer
@@ -19,12 +22,10 @@ module QDM
# Result Attributes
field :clause_results, type: Hash
field :episode_results, type: Hash
- filed :population_relevance, type: Hash
- field :statement_relevance, type: Hash
field :statement_results, type: Hash
# Calculation state attributes
- field :state, type: String
+ field :state, type: String, default: 'queued'
# Relations to other model classes
belongs_to :measure
|
Added state enum, removed some unused fields
|
projecttacoma_cqm-models
|
train
|
5210099f3e2cc4170cea097ee2ea1df9783ca3b9
|
diff --git a/lib/active_record/connection_adapters/cockroachdb/database_statements.rb b/lib/active_record/connection_adapters/cockroachdb/database_statements.rb
index <HASH>..<HASH> 100644
--- a/lib/active_record/connection_adapters/cockroachdb/database_statements.rb
+++ b/lib/active_record/connection_adapters/cockroachdb/database_statements.rb
@@ -12,7 +12,8 @@ module ActiveRecord
{
read_committed: "READ COMMITTED",
repeatable_read: "REPEATABLE READ",
- serializable: "SERIALIZABLE"
+ serializable: "SERIALIZABLE",
+ read_uncommitted: "SERIALIZABLE"
}
end
|
Handle read_uncommitted transaction isolations
|
cockroachdb_activerecord-cockroachdb-adapter
|
train
|
f4642d7040aececb686e8ac92def2b7140585ea4
|
diff --git a/src/Rocketeer/Binaries/Scm/Git.php b/src/Rocketeer/Binaries/Scm/Git.php
index <HASH>..<HASH> 100644
--- a/src/Rocketeer/Binaries/Scm/Git.php
+++ b/src/Rocketeer/Binaries/Scm/Git.php
@@ -62,6 +62,14 @@ class Git extends AbstractBinary implements ScmInterface
return $this->revParse('--abbrev-ref HEAD');
}
+ /**
+ * @return string
+ */
+ public function currentEndpoint()
+ {
+ return $this->getCommand('remote get-url origin');
+ }
+
////////////////////////////////////////////////////////////////////
/////////////////////////////// ACTIONS ////////////////////////////
////////////////////////////////////////////////////////////////////
diff --git a/src/Rocketeer/Binaries/Scm/Hg.php b/src/Rocketeer/Binaries/Scm/Hg.php
index <HASH>..<HASH> 100644
--- a/src/Rocketeer/Binaries/Scm/Hg.php
+++ b/src/Rocketeer/Binaries/Scm/Hg.php
@@ -59,6 +59,14 @@ class Hg extends AbstractBinary implements ScmInterface
}
/**
+ * @return string
+ */
+ public function currentEndpoint()
+ {
+ return $this->getCommand('paths default');
+ }
+
+ /**
* Clone a repository.
*
* @param string $destination
diff --git a/src/Rocketeer/Binaries/Scm/ScmInterface.php b/src/Rocketeer/Binaries/Scm/ScmInterface.php
index <HASH>..<HASH> 100644
--- a/src/Rocketeer/Binaries/Scm/ScmInterface.php
+++ b/src/Rocketeer/Binaries/Scm/ScmInterface.php
@@ -48,6 +48,11 @@ interface ScmInterface
public function currentBranch();
/**
+ * @return string
+ */
+ public function currentEndpoint();
+
+ /**
* Clone a repository.
*
* @param string $destination
diff --git a/src/Rocketeer/Binaries/Scm/Svn.php b/src/Rocketeer/Binaries/Scm/Svn.php
index <HASH>..<HASH> 100644
--- a/src/Rocketeer/Binaries/Scm/Svn.php
+++ b/src/Rocketeer/Binaries/Scm/Svn.php
@@ -54,6 +54,14 @@ class Svn extends AbstractBinary implements ScmInterface
}
/**
+ * @return string
+ */
+ public function currentEndpoint()
+ {
+ return $this->getCommand("info | grep '^URL' | awk '{print \$NF}'");
+ }
+
+ /**
* Get the current branch.
*
* @return string
|
Add currentEndpoint method to SCMs
|
rocketeers_rocketeer
|
train
|
7fc17cc9e4c16639776de27cb55b9930eace92da
|
diff --git a/src/component/toolbox/feature/SaveAsImage.js b/src/component/toolbox/feature/SaveAsImage.js
index <HASH>..<HASH> 100644
--- a/src/component/toolbox/feature/SaveAsImage.js
+++ b/src/component/toolbox/feature/SaveAsImage.js
@@ -49,10 +49,7 @@ var proto = SaveAsImage.prototype;
proto.onclick = function (ecModel, api) {
var model = this.model;
var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
- var $a = document.createElement('a');
var type = model.get('type', true) || 'png';
- $a.download = title + '.' + type;
- $a.target = '_blank';
var url = api.getConnectedDataURL({
type: type,
backgroundColor: model.get('backgroundColor', true)
@@ -60,9 +57,12 @@ proto.onclick = function (ecModel, api) {
excludeComponents: model.get('excludeComponents'),
pixelRatio: model.get('pixelRatio')
});
- $a.href = url;
// Chrome and Firefox
if (typeof MouseEvent === 'function' && !env.browser.ie && !env.browser.edge) {
+ var $a = document.createElement('a');
+ $a.download = title + '.' + type;
+ $a.target = '_blank';
+ $a.href = url;
var evt = new MouseEvent('click', {
view: window,
bubbles: true,
@@ -98,4 +98,4 @@ featureManager.register(
'saveAsImage', SaveAsImage
);
-export default SaveAsImage;
\ No newline at end of file
+export default SaveAsImage;
|
fix(SaveAsImage): don't create an anchor element if you don't need to
|
apache_incubator-echarts
|
train
|
c2c249b8da891db11623917703c4660d284079da
|
diff --git a/backtrader/analyzers/sharpe.py b/backtrader/analyzers/sharpe.py
index <HASH>..<HASH> 100644
--- a/backtrader/analyzers/sharpe.py
+++ b/backtrader/analyzers/sharpe.py
@@ -169,8 +169,10 @@ class SharpeRatio(Analyzer):
returns = [pow(1.0 + x, factor) - 1.0 for x in returns]
# Get the excess returns - arithmetic mean - original sharpe
- ret_free_avg = average([r - rate for r in returns])
- retdev = standarddev(returns, bessel=self.p.stddev_sample)
+ ret_free = [r - rate for r in returns]
+ ret_free_avg = average(ret_free)
+ retdev = standarddev(ret_free, avgx=ret_free_avg,
+ bessel=self.p.stddev_sample)
ratio = ret_free_avg / retdev
|
Use the excess returns for the standard deviation calculation
|
backtrader_backtrader
|
train
|
52bd13a306a702c1c361368b6e3e82ac43138914
|
diff --git a/lib/graph_matching/graph/weighted.rb b/lib/graph_matching/graph/weighted.rb
index <HASH>..<HASH> 100644
--- a/lib/graph_matching/graph/weighted.rb
+++ b/lib/graph_matching/graph/weighted.rb
@@ -68,7 +68,7 @@ module GraphMatching
e.is_a?(Array) &&
e.length == 3 &&
e[0, 2].all? { |i| i.is_a?(Integer) } &&
- e[2].is_a?(Integer) || e[2].is_a?(Float)
+ e[2].is_a?(Numeric)
end
end
|
Fix weighted graph not working with Numerics other than integers and floats
|
jaredbeck_graph_matching
|
train
|
3d77b6a6f838cda05a2b8946f5ef13db4db0a70f
|
diff --git a/lib/classes/Swift/Mime/Attachment.php b/lib/classes/Swift/Mime/Attachment.php
index <HASH>..<HASH> 100644
--- a/lib/classes/Swift/Mime/Attachment.php
+++ b/lib/classes/Swift/Mime/Attachment.php
@@ -33,6 +33,12 @@
class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity
{
+ /**
+ * Create a new Attachment with $headers, $encoder and $cache.
+ * @param Swift_Mime_HeaderSet $headers
+ * @param Swift_Mime_ContentEncoder $encoder
+ * @param Swift_KeyCache $cache
+ */
public function __construct(Swift_Mime_HeaderSet $headers,
Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache)
{
@@ -41,16 +47,30 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity
$this->setContentType('application/octet-stream');
}
+ /**
+ * Get the nesting level used for this attachment.
+ * Always returns {@link LEVEL_MIXED}.
+ * @return int
+ */
public function getNestingLevel()
{
return self::LEVEL_MIXED;
}
+ /**
+ * Get the Content-Disposition of this attachment.
+ * By default attachments have a disposition of "attachment".
+ * @return string
+ */
public function getDisposition()
{
return $this->_getHeaderFieldModel('Content-Disposition');
}
+ /**
+ * Set the Content-Disposition of this attachment.
+ * @param string $disposition
+ */
public function setDisposition($disposition)
{
if (!$this->_setHeaderFieldModel('Content-Disposition', $disposition))
@@ -62,11 +82,19 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity
return $this;
}
+ /**
+ * Get the filename of this attachment when downloaded.
+ * @return string
+ */
public function getFilename()
{
return $this->_getHeaderParameter('Content-Disposition', 'filename');
}
+ /**
+ * Set the filename of this attachment.
+ * @param string $filename
+ */
public function setFilename($filename)
{
$this->_setHeaderParameter('Content-Disposition', 'filename', $filename);
@@ -74,17 +102,29 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity
return $this;
}
+ /**
+ * Get the file size of this attachment.
+ * @return int
+ */
public function getSize()
{
return $this->_getHeaderParameter('Content-Disposition', 'size');
}
+ /**
+ * Set the file size of this attachment.
+ * @param int $size
+ */
public function setSize($size)
{
$this->_setHeaderParameter('Content-Disposition', 'size', $size);
return $this;
}
+ /**
+ * Set the file that this attachment is for.
+ * @param Swift_FileStream $file
+ */
public function setFile(Swift_FileStream $file)
{
$this->setFilename(basename($file->getPath()));
|
Added doc comments to Attachment
|
swiftmailer_swiftmailer
|
train
|
0481a2db910d1f4721081cc4804e8893a16adff4
|
diff --git a/djoser/utils.py b/djoser/utils.py
index <HASH>..<HASH> 100644
--- a/djoser/utils.py
+++ b/djoser/utils.py
@@ -1,3 +1,6 @@
+from rest_framework import response, status
+
+
def encode_uid(pk):
try:
from django.utils.http import urlsafe_base64_encode
@@ -14,4 +17,17 @@ def decode_uid(pk):
return urlsafe_base64_decode(pk)
except ImportError:
from django.utils.http import base36_to_int
- return base36_to_int(pk)
\ No newline at end of file
+ return base36_to_int(pk)
+
+
+class ActionViewMixin(object):
+
+ def post(self, request):
+ serializer = self.get_serializer(data=request.DATA)
+ if serializer.is_valid():
+ return self.action(serializer)
+ else:
+ return response.Response(
+ data=serializer.errors,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
\ No newline at end of file
diff --git a/djoser/views.py b/djoser/views.py
index <HASH>..<HASH> 100644
--- a/djoser/views.py
+++ b/djoser/views.py
@@ -46,19 +46,6 @@ class SendEmailViewMixin(object):
}
-class PostActionViewMixin(object):
-
- def post(self, request):
- serializer = self.get_serializer(data=request.DATA)
- if serializer.is_valid():
- return self.action(serializer)
- else:
- return response.Response(
- data=serializer.errors,
- status=status.HTTP_400_BAD_REQUEST,
- )
-
-
class RegistrationView(SendEmailViewMixin, generics.CreateAPIView):
permission_classes = (
permissions.AllowAny,
@@ -90,7 +77,7 @@ class RegistrationView(SendEmailViewMixin, generics.CreateAPIView):
return context
-class LoginView(PostActionViewMixin, generics.GenericAPIView):
+class LoginView(ActionViewMixin, generics.GenericAPIView):
serializer_class = serializers.UserLoginSerializer
permission_classes = (
permissions.AllowAny,
@@ -144,7 +131,7 @@ class PasswordResetView(SendEmailViewMixin, generics.GenericAPIView):
return context
-class SetPasswordView(PostActionViewMixin, generics.GenericAPIView):
+class SetPasswordView(utils.ActionViewMixin, generics.GenericAPIView):
permission_classes = (
permissions.IsAuthenticated,
)
@@ -160,7 +147,7 @@ class SetPasswordView(PostActionViewMixin, generics.GenericAPIView):
return response.Response(status=status.HTTP_200_OK)
-class PasswordResetConfirmView(PostActionViewMixin, generics.GenericAPIView):
+class PasswordResetConfirmView(utils.ActionViewMixin, generics.GenericAPIView):
permission_classes = (
permissions.AllowAny,
)
@@ -177,7 +164,7 @@ class PasswordResetConfirmView(PostActionViewMixin, generics.GenericAPIView):
return response.Response(status=status.HTTP_200_OK)
-class ActivationView(PostActionViewMixin, generics.GenericAPIView):
+class ActivationView(utils.ActionViewMixin, generics.GenericAPIView):
serializer_class = serializers.UidAndTokenSerializer
permission_classes = (
permissions.AllowAny,
@@ -195,7 +182,7 @@ class ActivationView(PostActionViewMixin, generics.GenericAPIView):
return Response(data=data, status=status.HTTP_200_OK)
-class SetUsernameView(PostActionViewMixin, generics.GenericAPIView):
+class SetUsernameView(utils.ActionViewMixin, generics.GenericAPIView):
serializer_class = serializers.SetUsernameSerializer
permission_classes = (
permissions.IsAuthenticated,
|
Move action view mixin to utils.
|
sunscrapers_djoser
|
train
|
3c36ce73f67b285282d01d20d0fbbea72cb6375b
|
diff --git a/seaglass/trunk/seaglass/src/main/java/com/seaglasslookandfeel/painter/SliderThumbPainter.java b/seaglass/trunk/seaglass/src/main/java/com/seaglasslookandfeel/painter/SliderThumbPainter.java
index <HASH>..<HASH> 100644
--- a/seaglass/trunk/seaglass/src/main/java/com/seaglasslookandfeel/painter/SliderThumbPainter.java
+++ b/seaglass/trunk/seaglass/src/main/java/com/seaglasslookandfeel/painter/SliderThumbPainter.java
@@ -55,22 +55,24 @@ public final class SliderThumbPainter extends AbstractRegionPainter {
BACKGROUND_FOCUSED_PRESSED_ARROWSHAPE,
}
- private static final ColorSet disabled = new ColorSet(new Color(0x8088ade0, true), new Color(0x805785bf, true), new Color(
- 0x80fbfdfe, true), new Color(0x80d6eaf9, true), new Color(0x80d2e8f8, true),
- new Color(0x80f5fafd, true));
- private static final ColorSet enabled = new ColorSet(new Color(0x88ade0), new Color(0x5785bf), new Color(0xfbfdfe),
- new Color(0xd6eaf9), new Color(0xd2e8f8), new Color(0xf5fafd));
- private static final ColorSet pressed = new ColorSet(new Color(0x4f7bbf), new Color(0x3f76bf), new Color(0xacbdd0),
- new Color(0x688db3), new Color(0x6d93ba), new Color(0xa4cbe4));
+ private static final ColorSet disabled = new ColorSet(new Color(0x8088ade0, true), new Color(0x805785bf, true),
+ new Color(0x80fbfdfe, true), new Color(0x80d6eaf9, true), new Color(
+ 0x80d2e8f8, true), new Color(0x80f5fafd, true));
+ private static final ColorSet enabled = new ColorSet(new Color(0x88ade0), new Color(0x5785bf), new Color(0xfbfdfe),
+ new Color(0xd6eaf9), new Color(0xd2e8f8), new Color(0xf5fafd));
+ private static final ColorSet pressed = new ColorSet(new Color(0x4f7bbf), new Color(0x3f76bf), new Color(0xacbdd0),
+ new Color(0x688db3), new Color(0x6d93ba), new Color(0xa4cbe4));
- private static final Color OUTER_FOCUS_COLOR = new Color(0x8072a5d2, true);
- private static final Color INNER_FOCUS_COLOR = new Color(0x73a4d1);
+ private Color outerFocusColor = decodeColor("seaGlassOuterFocus");
+ private Color innerFocusColor = decodeColor("seaGlassFocus");
+ private Color outerToolBarFocusColor = decodeColor("seaGlassToolBarOuterFocus");
+ private Color innerToolBarFocusColor = decodeColor("seaGlassToolBarFocus");
- private static final Color shadowColor = Color.black;
- private static final Effect dropShadow = new SeaGlassDropShadowEffect();
+ private static final Color shadowColor = Color.black;
+ private static final Effect dropShadow = new SeaGlassDropShadowEffect();
- private Ellipse2D ellipse = new Ellipse2D.Double();
- private Path2D path = new Path2D.Double();
+ private Ellipse2D ellipse = new Ellipse2D.Double();
+ private Path2D path = new Path2D.Double();
private Which state;
private PaintContext ctx;
@@ -151,13 +153,14 @@ public final class SliderThumbPainter extends AbstractRegionPainter {
}
private void paintDiscrete(Graphics2D g, JComponent c, int width, int height, boolean focused, ColorSet colors) {
+ boolean useToolBarColors = useToolBarFocus(c);
Shape s;
if (focused) {
s = decodeDiscreteOuterFocus(width, height);
- g.setColor(OUTER_FOCUS_COLOR);
+ g.setColor(useToolBarColors ? outerToolBarFocusColor : outerFocusColor);
g.fill(s);
s = decodeDiscreteInnerFocus(width, height);
- g.setColor(INNER_FOCUS_COLOR);
+ g.setColor(useToolBarColors ? innerToolBarFocusColor : innerFocusColor);
g.fill(s);
}
s = decodeDiscreteBorder(width, height);
@@ -172,13 +175,14 @@ public final class SliderThumbPainter extends AbstractRegionPainter {
}
private void paintContinuous(Graphics2D g, JComponent c, int width, int height, boolean focused, ColorSet colors) {
+ boolean useToolBarColors = useToolBarFocus(c);
Shape s;
if (focused) {
s = decodeContinuousOuterFocus(width, height);
- g.setColor(OUTER_FOCUS_COLOR);
+ g.setColor(useToolBarColors ? outerToolBarFocusColor : outerFocusColor);
g.fill(s);
s = decodeContinuousInnerFocus(width, height);
- g.setColor(INNER_FOCUS_COLOR);
+ g.setColor(useToolBarColors ? innerToolBarFocusColor : innerFocusColor);
g.fill(s);
}
s = decodeContinuousBorder(width, height);
|
Use common focus colors. Support toolbar focus colors.
|
khuxtable_seaglass
|
train
|
57b0623a6c217a6543d8cf9183b041d97e233b97
|
diff --git a/packages/core/src/textures/BaseTexture.js b/packages/core/src/textures/BaseTexture.js
index <HASH>..<HASH> 100644
--- a/packages/core/src/textures/BaseTexture.js
+++ b/packages/core/src/textures/BaseTexture.js
@@ -310,7 +310,9 @@ export default class BaseTexture extends EventEmitter
/**
* Helper function that creates a base texture based on the source you provide.
- * The source can be - image url, image element, canvas element.
+ * The source can be - image url, image element, canvas element. If the
+ * source is an image url or an image element and not in the base texture
+ * cache, it will be created and loaded.
*
* @static
* @param {string|HTMLImageElement|HTMLCanvasElement} source - The source to create base texture from.
|
Document caching behavior of BaseTexture.from (#<I>)
|
pixijs_pixi.js
|
train
|
819799d90a55313d92946fc90a77d01e0030467b
|
diff --git a/src/com/google/javascript/jscomp/ClosureRewriteModule.java b/src/com/google/javascript/jscomp/ClosureRewriteModule.java
index <HASH>..<HASH> 100644
--- a/src/com/google/javascript/jscomp/ClosureRewriteModule.java
+++ b/src/com/google/javascript/jscomp/ClosureRewriteModule.java
@@ -77,6 +77,7 @@ import javax.annotation.Nullable;
* </pre>
*
* @author johnlenz@google.com (John Lenz)
+ * @author stalcup@google.com (John Stalcup)
*/
final class ClosureRewriteModule implements HotSwapCompilerPass {
diff --git a/src/com/google/javascript/jscomp/deps/Es6SortedDependencies.java b/src/com/google/javascript/jscomp/deps/Es6SortedDependencies.java
index <HASH>..<HASH> 100644
--- a/src/com/google/javascript/jscomp/deps/Es6SortedDependencies.java
+++ b/src/com/google/javascript/jscomp/deps/Es6SortedDependencies.java
@@ -48,6 +48,7 @@ import java.util.Set;
* Also exposes other information about the inputs, like which inputs
* do not provide symbols.
*
+ * @author stalcup@google.com (John Stalcup)
*/
public final class Es6SortedDependencies<INPUT extends DependencyInfo>
implements SortedDependencies<INPUT> {
diff --git a/test/com/google/javascript/jscomp/ClosureRewriteModuleTest.java b/test/com/google/javascript/jscomp/ClosureRewriteModuleTest.java
index <HASH>..<HASH> 100644
--- a/test/com/google/javascript/jscomp/ClosureRewriteModuleTest.java
+++ b/test/com/google/javascript/jscomp/ClosureRewriteModuleTest.java
@@ -36,6 +36,7 @@ import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
/**
* Unit tests for ClosureRewriteModule
* @author johnlenz@google.com (John Lenz)
+ * @author stalcup@google.com (John Stalcup)
*/
public final class ClosureRewriteModuleTest extends Es6CompilerTestCase {
diff --git a/test/com/google/javascript/jscomp/MissingProvideTest.java b/test/com/google/javascript/jscomp/MissingProvideTest.java
index <HASH>..<HASH> 100644
--- a/test/com/google/javascript/jscomp/MissingProvideTest.java
+++ b/test/com/google/javascript/jscomp/MissingProvideTest.java
@@ -24,6 +24,7 @@ import com.google.javascript.rhino.Node;
* Tests for the "missing provides" checks in {@link ProcessClosurePrimitives} and {@link
* ClosureRewriteModule}.
*
+ * @author stalcup@google.com (John Stalcup)
*/
public final class MissingProvideTest extends Es6CompilerTestCase {
diff --git a/test/com/google/javascript/jscomp/deps/Es6SortedDependenciesTest.java b/test/com/google/javascript/jscomp/deps/Es6SortedDependenciesTest.java
index <HASH>..<HASH> 100644
--- a/test/com/google/javascript/jscomp/deps/Es6SortedDependenciesTest.java
+++ b/test/com/google/javascript/jscomp/deps/Es6SortedDependenciesTest.java
@@ -24,6 +24,7 @@ import junit.framework.TestCase;
/**
* Tests for {@link Es6SortedDependencies}
* @author nicksantos@google.com (Nick Santos)
+ * @author stalcup@google.com (John Stalcup)
*/
public class Es6SortedDependenciesTest extends TestCase {
private static SortedDependencies<SimpleDependencyInfo> createSortedDependencies(
|
Fixes change tracking in some passes and reenables tests.
-------------
Created by MOE: <URL>
|
google_closure-compiler
|
train
|
acf5fb1ec70b7de4902daf75301356702a26e6da
|
diff --git a/src/Mink.php b/src/Mink.php
index <HASH>..<HASH> 100644
--- a/src/Mink.php
+++ b/src/Mink.php
@@ -100,7 +100,7 @@ class Mink
}
/**
- * Returns registered session by it's name or active one and automatically starts it if required.
+ * Returns registered session by it's name or default one.
*
* @param string $name session name
*
@@ -110,14 +110,7 @@ class Mink
*/
public function getSession($name = null)
{
- $session = $this->locateSession($name);
-
- // start session if needed
- if (!$session->isStarted()) {
- $session->start();
- }
-
- return $session;
+ return $this->locateSession($name);
}
/**
diff --git a/src/Session.php b/src/Session.php
index <HASH>..<HASH> 100644
--- a/src/Session.php
+++ b/src/Session.php
@@ -134,12 +134,17 @@ class Session
}
/**
- * Visit specified URL.
+ * Visit specified URL and automatically start session if not already running.
*
* @param string $url url of the page
*/
public function visit($url)
{
+ // start session if needed
+ if (!$this->isStarted()) {
+ $this->start();
+ }
+
$this->driver->visit($url);
}
diff --git a/tests/MinkTest.php b/tests/MinkTest.php
index <HASH>..<HASH> 100644
--- a/tests/MinkTest.php
+++ b/tests/MinkTest.php
@@ -67,14 +67,6 @@ class MinkTest extends \PHPUnit_Framework_TestCase
{
$session = $this->getSessionMock();
- $session
- ->expects($this->once())
- ->method('isStarted')
- ->will($this->returnValue(false));
- $session
- ->expects($this->once())
- ->method('start');
-
$this->mink->registerSession('mock_session', $session);
$this->assertSame($session, $this->mink->getSession('mock_session'));
@@ -83,22 +75,6 @@ class MinkTest extends \PHPUnit_Framework_TestCase
$this->mink->getSession('not_registered');
}
- public function testGetAlreadyStartedSession()
- {
- $session = $this->getSessionMock();
-
- $session
- ->expects($this->once())
- ->method('isStarted')
- ->will($this->returnValue(true));
- $session
- ->expects($this->never())
- ->method('start');
-
- $this->mink->registerSession('mock_session', $session);
- $this->assertSame($session, $this->mink->getSession('mock_session'));
- }
-
public function testSetDefaultSessionName()
{
$this->assertNull($this->mink->getDefaultSessionName());
diff --git a/tests/SessionTest.php b/tests/SessionTest.php
index <HASH>..<HASH> 100644
--- a/tests/SessionTest.php
+++ b/tests/SessionTest.php
@@ -83,10 +83,38 @@ class SessionTest extends \PHPUnit_Framework_TestCase
$this->session->restart();
}
- public function testVisit()
+ public function testVisitWithoutRunningSession()
{
$this->driver
->expects($this->once())
+ ->method('isStarted')
+ ->willReturn(false);
+
+ $this->driver
+ ->expects($this->once())
+ ->method('start');
+
+ $this->driver
+ ->expects($this->once())
+ ->method('visit')
+ ->with($url = 'some_url');
+
+ $this->session->visit($url);
+ }
+
+ public function testVisitWithRunningSession()
+ {
+ $this->driver
+ ->expects($this->once())
+ ->method('isStarted')
+ ->willReturn(true);
+
+ $this->driver
+ ->expects($this->never())
+ ->method('start');
+
+ $this->driver
+ ->expects($this->once())
->method('visit')
->with($url = 'some_url');
|
Auto-start session only upon 1st "->visit(...)" method call
|
minkphp_Mink
|
train
|
34e9a04cf8d7072afb464b7446c8ba6658810b03
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -24,6 +24,7 @@ setup(
],
install_requires=[
+ 'sqlite-framework',
'requests',
'pytz',
'psutil'
|
Add sqlite-framework as dependency
|
alvarogzp_telegram-bot-framework
|
train
|
d0846bbc8de210eb84cd1dd7469b27cf2f319f95
|
diff --git a/flink-core/src/main/java/org/apache/flink/api/common/operators/ResourceSpec.java b/flink-core/src/main/java/org/apache/flink/api/common/operators/ResourceSpec.java
index <HASH>..<HASH> 100755
--- a/flink-core/src/main/java/org/apache/flink/api/common/operators/ResourceSpec.java
+++ b/flink-core/src/main/java/org/apache/flink/api/common/operators/ResourceSpec.java
@@ -359,7 +359,7 @@ public final class ResourceSpec implements Serializable {
return this;
}
- public Builder setOffTaskHeapMemoryMB(int taskOffHeapMemoryMB) {
+ public Builder setTaskOffHeapMemoryMB(int taskOffHeapMemoryMB) {
this.taskOffHeapMemory = MemorySize.ofMebiBytes(taskOffHeapMemoryMB);
return this;
}
|
[hotfix][core] Fix typo in the Builder of ResourceSpec
|
apache_flink
|
train
|
00cf10d360de3fbe440789ee51662c2894e041ce
|
diff --git a/pkg/storage/storage.go b/pkg/storage/storage.go
index <HASH>..<HASH> 100644
--- a/pkg/storage/storage.go
+++ b/pkg/storage/storage.go
@@ -61,7 +61,10 @@ func (s *Storage) Create(rls *rspb.Release) error {
s.Log("creating release %q", makeKey(rls.Name, rls.Version))
if s.MaxHistory > 0 {
// Want to make space for one more release.
- s.removeLeastRecent(rls.Name, s.MaxHistory-1)
+ if err := s.removeLeastRecent(rls.Name, s.MaxHistory-1); err != nil &&
+ !errors.Is(err, driver.ErrReleaseNotFound) {
+ return err
+ }
}
return s.Driver.Create(makeKey(rls.Name, rls.Version), rls)
}
|
fix(pkg/storage): If storage.Create fails to clean up recent release versions, return an error
Previously, storage.Create was ignoring the error. This meant that a user that
relied on the recent release version cleanup would not be notified if that
cleanup failed, and release versions could grow without bound.
Closes #<I>
|
helm_helm
|
train
|
fe5fc502caa5515391ab49ea884e3e39e7856175
|
diff --git a/atrcopy/ataridos.py b/atrcopy/ataridos.py
index <HASH>..<HASH> 100644
--- a/atrcopy/ataridos.py
+++ b/atrcopy/ataridos.py
@@ -169,7 +169,7 @@ class AtariDosDirent(object):
return False
return True
- def get_sector_list(self, image):
+ def get_sectors_in_vtoc(self, image):
sector_list = BaseSectorList(image.header.sector_size)
self.start_read(image)
while True:
diff --git a/atrcopy/diskimages.py b/atrcopy/diskimages.py
index <HASH>..<HASH> 100644
--- a/atrcopy/diskimages.py
+++ b/atrcopy/diskimages.py
@@ -360,11 +360,10 @@ class DiskImageBase(object):
directory = self.directory_class(self.header)
self.get_directory(directory)
dirent = directory.find_dirent(filename)
- sector_list = dirent.get_sector_list(self)
+ sector_list = dirent.get_sectors_in_vtoc(self)
vtoc_segments = self.get_vtoc_segments()
vtoc = self.vtoc_class(self.header, vtoc_segments)
directory.remove_dirent(self, dirent, vtoc, sector_list)
- self.write_sector_list(sector_list)
self.write_sector_list(vtoc)
self.write_sector_list(directory)
self.get_metadata()
diff --git a/atrcopy/dos33.py b/atrcopy/dos33.py
index <HASH>..<HASH> 100644
--- a/atrcopy/dos33.py
+++ b/atrcopy/dos33.py
@@ -9,11 +9,12 @@ log = logging.getLogger(__name__)
class Dos33TSSector(WriteableSector):
- def __init__(self, header, sector_list, start, end):
- WriteableSector.__init__(self, header.sector_size)
+ def __init__(self, header, sector_list=None, start=None, end=None, data=None):
+ WriteableSector.__init__(self, header.sector_size, data)
self.header = header
self.used = header.sector_size
- self.set_tslist(sector_list, start, end)
+ if data is None:
+ self.set_tslist(sector_list, start, end)
def set_tslist(self, sector_list, start, end):
index = 0xc
@@ -25,9 +26,21 @@ class Dos33TSSector(WriteableSector):
log.debug("tslist entry #%d: %d, %d" % (index, t, s))
index += 2
+ def get_tslist(self):
+ index = 0xc
+ sector_list = []
+ while index < self.header.sector_size:
+ t = self.data[index]
+ s = self.data[index + 1]
+ sector_list.append(self.header.sector_from_track(t, s))
+ index += 2
+ return sector_list
+
@property
def next_sector_num(self):
- return self._next_sector_num
+ t = self.data[1]
+ s = self.data[2]
+ return self.header.sector_from_track(t, s)
@next_sector_num.setter
def next_sector_num(self, value):
@@ -225,7 +238,6 @@ class Dos33Dirent(object):
def mark_deleted(self):
self.deleted = True
- self.in_use = False
def update_sector_info(self, sector_list):
self.num_sectors = sector_list.num_sectors
@@ -260,37 +272,28 @@ class Dos33Dirent(object):
return True
def get_track_sector_list(self, image):
- sector = image.header.sector_from_track(self.track, self.sector)
- sector_list = []
- while sector > 0:
- image.assert_valid_sector(sector)
- print "reading track/sector list", sector
- values, style = image.get_sectors(sector)
- sector = image.header.sector_from_track(values[1], values[2])
- i = 0x0c
- while i < 256:
- t = values[i]
- s = values[i + 1]
- i += 2
- if t == 0:
- sector = 0
- break
- sector_list.append(image.header.sector_from_track(t, s))
- self.sector_map = sector_list
-
- def get_sector_list(self, image):
- sector_list = BaseSectorList(image.header.sector_size)
- self.start_read(image)
+ tslist = BaseSectorList(image.header.sector_size)
sector_num = image.header.sector_from_track(self.track, self.sector)
+ sector_map = []
while sector_num > 0:
+ image.assert_valid_sector(sector_num)
+ print "reading track/sector list", sector_num
+ data, _ = image.get_sectors(sector_num)
+ sector = Dos33TSSector(image.header, data=data)
+ sector_map.extend(sector.get_tslist())
+ tslist.append(sector)
+ sector_num = sector.next_sector_num
+ self.sector_map = sector_map
+ self.track_sector_list = tslist
+
+ def get_sectors_in_vtoc(self, image):
+ self.get_track_sector_list(image)
+ sectors = []
+ sectors.extend(self.track_sector_list)
+ for sector_num in self.sector_map:
sector = WriteableSector(image.header.sector_size, None, sector_num)
- sector_list.append(sector)
- values, style = image.get_sectors(sector_num)
- sector = image.header.sector_from_track(values[1], values[2])
- for sector_num in sector_list:
- sector = WriteableSector(image.header.sector_size, None, sector_num)
- sector_list.append(sector)
- return sector_list
+ sectors.append(sector)
+ return sectors
def start_read(self, image):
if not self.is_sane:
|
Progress in deleting DOS <I> files
|
robmcmullen_atrcopy
|
train
|
14379b7ac9b2dee5e10fd37f33ca3e9a9b3e3ab1
|
diff --git a/lib/VeresOneClient.js b/lib/VeresOneClient.js
index <HASH>..<HASH> 100644
--- a/lib/VeresOneClient.js
+++ b/lib/VeresOneClient.js
@@ -85,7 +85,8 @@ class VeresOneClient {
};
// errors in this range might contain response data
if(response.status > 399 && response.status < 500) {
- error.details.error = response.data || e;
+ // httpClient puts the error on the data object
+ error.details.error = e.data || response.data || e;
}
throw error;
}
@@ -151,7 +152,8 @@ class VeresOneClient {
};
// errors in this range might contain response data
if(response.status > 399 && response.status < 500) {
- error.details.error = response.data || e;
+ // httpClient puts the data directly on the error
+ error.details.error = e.data || response.data || e;
}
throw error;
}
|
Look for data on error object first.
|
veres-one_did-veres-one
|
train
|
67de5c6b2ae5d6b48dc7d7e969d93a8a0a462248
|
diff --git a/raiden/api/rest.py b/raiden/api/rest.py
index <HASH>..<HASH> 100644
--- a/raiden/api/rest.py
+++ b/raiden/api/rest.py
@@ -41,6 +41,7 @@ from raiden.api.v1.encoding import (
KeccakConverter,
PartnersPerTokenListSchema,
TransferSchema,
+ InvalidEndpoint,
)
from raiden.api.v1.resources import (
create_blueprint,
@@ -154,7 +155,10 @@ def handle_request_parsing_error(err):
def endpoint_not_found(e):
- return api_error('invalid endpoint', HTTPStatus.NOT_FOUND)
+ errors = ['invalid endpoint']
+ if isinstance(e, InvalidEndpoint):
+ errors.append(e.description)
+ return api_error(errors, HTTPStatus.NOT_FOUND)
def normalize_events_list(old_list):
diff --git a/raiden/api/v1/encoding.py b/raiden/api/v1/encoding.py
index <HASH>..<HASH> 100644
--- a/raiden/api/v1/encoding.py
+++ b/raiden/api/v1/encoding.py
@@ -10,6 +10,7 @@ from marshmallow import (
SchemaOpts,
)
from webargs import validate
+from werkzeug.exceptions import NotFound
from werkzeug.routing import (
BaseConverter,
ValidationError,
@@ -44,21 +45,25 @@ from raiden.transfer.state import (
from raiden.utils import data_encoder, data_decoder
+class InvalidEndpoint(NotFound):
+ """
+ Exception to be raised instead of ValidationError if we want to skip the remaining
+ endpoint matching rules and give a reason why the endpoint is invalid.
+ """
+
+
class HexAddressConverter(BaseConverter):
def to_python(self, value):
if value[:2] != '0x':
- raise ValidationError()
+ raise InvalidEndpoint('Not a valid hex address, 0x prefix missing.')
if not is_checksum_address(value):
- raise ValidationError()
+ raise InvalidEndpoint('Not a valid EIP55 encoded address.')
try:
value = unhexlify(value[2:])
except TypeError:
- raise ValidationError()
-
- if len(value) != 20:
- raise ValidationError()
+ raise InvalidEndpoint('Could not decode hex.')
return value
|
Add error messages for the case of invalid addresses in REST api queries
|
raiden-network_raiden
|
train
|
70ca4c0b669f2cfd1fad07f50d830bb18a2abea6
|
diff --git a/solidity/test/BancorFormula.js b/solidity/test/BancorFormula.js
index <HASH>..<HASH> 100644
--- a/solidity/test/BancorFormula.js
+++ b/solidity/test/BancorFormula.js
@@ -15,12 +15,13 @@ contract('BancorFormula', () => {
let ILLEGAL_VALUE = web3.toBigNumber(2).toPower(256);
let MAX_NUMERATOR = web3.toBigNumber(2).toPower(256 - constants.MAX_PRECISION).minus(1);
let MIN_DENOMINATOR = web3.toBigNumber(1);
+ let MAX_EXPONENT = 1000000;
for (let percent = 1; percent <= 100; percent++) {
let baseN = MAX_NUMERATOR;
let baseD = MAX_NUMERATOR.minus(1);
- let expN = percent * 10000;
- let expD = 1000000;
+ let expN = MAX_EXPONENT * percent / 100;
+ let expD = MAX_EXPONENT;
let test = `Function power(0x${baseN.toString(16)}, 0x${baseD.toString(16)}, ${expN}, ${expD})`;
it(`${test}:`, async () => {
@@ -37,8 +38,8 @@ contract('BancorFormula', () => {
for (let percent = 1; percent <= 100; percent++) {
let baseN = MAX_NUMERATOR;
let baseD = MAX_NUMERATOR.minus(1);
- let expN = 1000000;
- let expD = percent * 10000;
+ let expN = MAX_EXPONENT;
+ let expD = MAX_EXPONENT * percent / 100;
let test = `Function power(0x${baseN.toString(16)}, 0x${baseD.toString(16)}, ${expN}, ${expD})`;
it(`${test}:`, async () => {
@@ -55,8 +56,8 @@ contract('BancorFormula', () => {
for (let percent = 1; percent <= 100; percent++) {
let baseN = MAX_NUMERATOR;
let baseD = MIN_DENOMINATOR;
- let expN = percent * 10000;
- let expD = 1000000;
+ let expN = MAX_EXPONENT * percent / 100;
+ let expD = MAX_EXPONENT;
let test = `Function power(0x${baseN.toString(16)}, 0x${baseD.toString(16)}, ${expN}, ${expD})`;
it(`${test}:`, async () => {
@@ -73,8 +74,8 @@ contract('BancorFormula', () => {
for (let percent = 1; percent <= 100; percent++) {
let baseN = MAX_NUMERATOR;
let baseD = MIN_DENOMINATOR;
- let expN = 1000000;
- let expD = percent * 10000;
+ let expN = MAX_EXPONENT;
+ let expD = MAX_EXPONENT * percent / 100;
let test = `Function power(0x${baseN.toString(16)}, 0x${baseD.toString(16)}, ${expN}, ${expD})`;
it(`${test}:`, async () => {
@@ -103,7 +104,7 @@ contract('BancorFormula', () => {
it(`${test}:`, async () => {
try {
let retVal = await formula.lnTest.call(numerator, denominator);
- assert(retVal.times(1000000).lessThan(ILLEGAL_VALUE), `${test}: output is too large`);
+ assert(retVal.times(MAX_EXPONENT).lessThan(ILLEGAL_VALUE), `${test}: output is too large`);
assert(assertion, `${test} failed when it should have passed`);
}
catch (error) {
|
Cosmetic (replace '<I>' with a 'MAX_EXPONENT').
|
bancorprotocol_contracts
|
train
|
83d16be34d3ecd398968fcbbfb82f0774b04da0e
|
diff --git a/pysat/tests/test_meta.py b/pysat/tests/test_meta.py
index <HASH>..<HASH> 100644
--- a/pysat/tests/test_meta.py
+++ b/pysat/tests/test_meta.py
@@ -1142,29 +1142,6 @@ class TestMeta(object):
assert self.dval.upper() in self.meta
return
- def test_ho_data_retrieval_case_insensitive(self):
- """Test that higher order data variables are case insensitive."""
-
- # Initalize the meta data
- self.dval = "test_val"
- self.meta[self.dval] = self.default_val
-
- cmeta = pysat.Meta()
- cval = '_'.join([self.dval, 'child'])
- cmeta[cval] = self.default_val
- self.meta[self.dval] = cmeta
-
- # Test that the data value is present using real key and upper-case
- # version of that key
- assert self.dval in self.meta.keys()
-
- # Test the child variable, which should only be present through the
- # children attribute. Cannot specify keys for case-insensitive look-up.
- assert cval not in self.meta.keys()
- assert cval in self.meta[self.dval].children.keys()
- assert cval.upper() in self.meta[self.dval].children
- return
-
@pytest.mark.parametrize("data_val", ['test_val', 'TEST_VAL', 'Test_Val',
'TeSt_vAl'])
def test_var_case_name(self, data_val):
@@ -1245,41 +1222,6 @@ class TestMeta(object):
@pytest.mark.parametrize("label", ['meta_label', 'META_LABEL', 'Meta_Label',
'MeTa_lAbEl'])
- def test_get_attribute_name_case_preservation_w_higher_order_list_in(self,
- label):
- """Test that get attribute names preserves the case with ho metadata."""
-
- # Set a meta data variable
- self.dval = 'test_val'
- self.meta[self.dval] = self.default_val
-
- # Set an attribute with case in `label`
- cval = ''.join([self.dval, '21'])
- meta2 = pysat.Meta()
- meta2[cval] = {label: 'Test meta data for meta label'}
-
- # Attach child metadata to root meta
- dval2 = ''.join([self.dval, '2'])
- self.meta[dval2] = meta2
-
- # Attempt to assign to same label at root but potentially different
- # case.
- self.meta[self.dval] = {label.lower(): 'Test meta data for meta label'}
-
- # Create inputs and get the attribute case names
- ins = [label.upper(), label.lower(), label.capitalize(),
- label]
- outputs = self.meta.attr_case_name(ins)
-
- targets = [label] * len(ins)
-
- # Confirm original input case retained.
- assert np.all(outputs == targets)
-
- return
-
- @pytest.mark.parametrize("label", ['meta_label', 'META_LABEL', 'Meta_Label',
- 'MeTa_lAbEl'])
def test_hasattr_case_neutral(self, label):
"""Test `meta.hasattr_case_neutral` identifies the label name.
@@ -1756,6 +1698,64 @@ class TestMeta(object):
repr(cvar), repr(mvar))
return
+ @pytest.mark.parametrize("label", ['meta_label', 'META_LABEL', 'Meta_Label',
+ 'MeTa_lAbEl'])
+ def test_get_attribute_name_case_preservation_w_higher_order_list_in(self,
+ label):
+ """Test that get attribute names preserves the case with ho metadata."""
+
+ # Set a meta data variable
+ self.dval = 'test_val'
+ self.meta[self.dval] = self.default_val
+
+ # Set an attribute with case in `label`
+ cval = ''.join([self.dval, '21'])
+ meta2 = pysat.Meta()
+ meta2[cval] = {label: 'Test meta data for meta label'}
+
+ # Attach child metadata to root meta
+ dval2 = ''.join([self.dval, '2'])
+ self.meta[dval2] = meta2
+
+ # Attempt to assign to same label at root but potentially different
+ # case.
+ self.meta[self.dval] = {label.lower(): 'Test meta data for meta label'}
+
+ # Create inputs and get the attribute case names
+ ins = [label.upper(), label.lower(), label.capitalize(),
+ label]
+ outputs = self.meta.attr_case_name(ins)
+
+ targets = [label] * len(ins)
+
+ # Confirm original input case retained.
+ assert np.all(outputs == targets)
+
+ return
+
+ def test_ho_data_retrieval_case_insensitive(self):
+ """Test that higher order data variables are case insensitive."""
+
+ # Initalize the meta data
+ self.dval = "test_val"
+ self.meta[self.dval] = self.default_val
+
+ cmeta = pysat.Meta()
+ cval = '_'.join([self.dval, 'child'])
+ cmeta[cval] = self.default_val
+ self.meta[self.dval] = cmeta
+
+ # Test that the data value is present using real key and upper-case
+ # version of that key
+ assert self.dval in self.meta.keys()
+
+ # Test the child variable, which should only be present through the
+ # children attribute. Cannot specify keys for case-insensitive look-up.
+ assert cval not in self.meta.keys()
+ assert cval in self.meta[self.dval].children.keys()
+ assert cval.upper() in self.meta[self.dval].children
+ return
+
class TestMetaImmutable(TestMeta):
"""Unit tests for immutable metadata."""
|
STY: Moved HO tests
|
rstoneback_pysat
|
train
|
09447f682020b49a025cf54d24d5cd66e08cd79b
|
diff --git a/DependencyInjection/BugsnagExtension.php b/DependencyInjection/BugsnagExtension.php
index <HASH>..<HASH> 100644
--- a/DependencyInjection/BugsnagExtension.php
+++ b/DependencyInjection/BugsnagExtension.php
@@ -38,8 +38,8 @@ class BugsnagExtension extends Extension
}
$container->setParameter('bugsnag.api_key', $config['api_key']);
- // Enabled stages, default is prod
- $container->setParameter('bugsnag.enabled_stages', $config['enabled_stages']);
+ // Enabled stages, default is prod
+ $container->setParameter('bugsnag.enabled_stages', $config['enabled_stages']);
// Notify stages, default is staging and production
$container->setParameter('bugsnag.notify_stages', $config['notify_stages']);
diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php
index <HASH>..<HASH> 100644
--- a/DependencyInjection/Configuration.php
+++ b/DependencyInjection/Configuration.php
@@ -31,10 +31,10 @@ class Configuration implements ConfigurationInterface
->children()
->scalarNode('api_key')->end()
->scalarNode('app_version')->end()
- ->arrayNode('enabled_stages')
- ->defaultValue(array('prod'))
- ->prototype('scalar')->end()
- ->end()
+ ->arrayNode('enabled_stages')
+ ->defaultValue(array('prod'))
+ ->prototype('scalar')->end()
+ ->end()
->arrayNode('notify_stages')
->defaultValue(array('staging', 'production'))
->prototype('scalar')->end()
|
Replaced tabs with 4 spaces as per PSR-2
|
evolution7_Evolution7BugsnagBundle
|
train
|
ae17202a4aa6586831ada4b9b0f867847317d59f
|
diff --git a/src/TransformBuilder.php b/src/TransformBuilder.php
index <HASH>..<HASH> 100644
--- a/src/TransformBuilder.php
+++ b/src/TransformBuilder.php
@@ -251,7 +251,7 @@ class TransformBuilder
}
if ($data instanceof Model || $data instanceof Collection) {
- $data->load($this->relationsWithoutParameters());
+ $data->load($this->prepareEagerLoadableRelations($this->with, $transformer));
}
$this->with = $this->stripEagerLoadConstraints($this->with);
@@ -289,22 +289,32 @@ class TransformBuilder
}
/**
- * Remove parameters from relations that must be loaded.
+ * Remove parameters from relations that must be eager loaded and
+ * filter out the relations which have an includeXxx method.
*
+ * @param array $relations
+ * @param \Flugg\Responder\Transformers\Transformer|callable|string|null $transformer
* @return array
*/
- protected function relationsWithoutParameters(): array
+ protected function prepareEagerLoadableRelations(array $relations, $transformer): array
{
$cleanedRelations = [];
- foreach ($this->with as $key => $value) {
- // If the key is numeric, value is the relation name:
- // we remove parameters from the value and return the relation name
+ foreach ($relations as $key => $value) {
+ // Strip out parameters from relation name
+ $relationName = explode(':', is_numeric($key) ? $value : $key)[0];
+ // Ignores all relation which have a includeXxx method
+ // method_exists does not care if the $transformer is actually an object or not
+ if (method_exists($transformer, 'include' . ucfirst($relationName))) {
+ continue;
+ }
+
+ // If the key is numeric, value is the relation name: return it
// Otherwise the key is the relation name and the value is a custom scope:
- // we remove parameters from the key and return the relation with the value untouched
+ // return the relation with the value untouched
if(is_numeric($key)) {
- $cleanedRelations[$key] = explode(':', $value)[0];
+ $cleanedRelations[$key] = $relationName;
} else {
- $cleanedRelations[explode(':', $key)[0]] = $value;
+ $cleanedRelations[$relationName] = $value;
}
}
diff --git a/tests/Unit/TransformBuilderTest.php b/tests/Unit/TransformBuilderTest.php
index <HASH>..<HASH> 100644
--- a/tests/Unit/TransformBuilderTest.php
+++ b/tests/Unit/TransformBuilderTest.php
@@ -346,6 +346,27 @@ class TransformBuilderTest extends TestCase
}
/**
+ * Assert that the [transform] method do not eager load relations for which is present an include method.
+ */
+ public function testTransformMethodDoNotEagerLoadsRelationsForWhichAnIncludeMethodExists()
+ {
+ $this->transformFactory->shouldReceive('make')->andReturn([]);
+ $this->resource->shouldReceive('getData')->andReturn($model = Mockery::mock(Model::class));
+ $model->shouldReceive('load')->andReturnSelf();
+ // It's not possible to easily mock method_exists with mockery so we must rely on a stub
+ $this->resource->shouldReceive('getTransformer')->andReturn(new TransformerWithIncludeMethods());
+
+ $this->builder->resource()->with($relations = ['foo', 'bar'])->transform();
+
+ $model->shouldHaveReceived('load')->with(['foo'])->once();
+ $this->transformFactory->shouldHaveReceived('make')->with($this->resource, $this->serializer, [
+ 'includes' => ['foo', 'bar', 'baz'],
+ 'excludes' => [],
+ 'fieldsets' => [],
+ ])->once();
+ }
+
+ /**
* Assert that the [only] method sets the filtered fields that are sent to the
* [TransformFactory].
*/
@@ -378,4 +399,18 @@ class TransformBuilderTest extends TestCase
'fieldsets' => ['foo', 'bar', 'baz'],
])->once();
}
+}
+
+class TransformerWithIncludeMethods extends Transformer {
+ protected $relations = ['foo', 'bar'];
+
+ protected $load = ['baz'];
+
+ public function includeBar() {
+ //
+ }
+
+ public function includeBaz() {
+ //
+ }
}
\ No newline at end of file
|
Relations with an includeXxx method won't be eager loaded anymore, this opens up scenarios where there is a need to consider as a relation what in fact is just a method returning a Model or a Collection.
|
flugger_laravel-responder
|
train
|
eaa04959272c819202d8392ec3e5262b22322504
|
diff --git a/kubernetes_asyncio/config/kube_config.py b/kubernetes_asyncio/config/kube_config.py
index <HASH>..<HASH> 100644
--- a/kubernetes_asyncio/config/kube_config.py
+++ b/kubernetes_asyncio/config/kube_config.py
@@ -17,6 +17,7 @@ import atexit
import base64
import datetime
import json
+import logging
import os
import tempfile
@@ -161,6 +162,12 @@ class KubeConfigLoader(object):
if self._user is not None and 'auth-provider' in self._user and 'name' in self._user['auth-provider']:
self.provider = self._user['auth-provider']['name']
+ logging.debug('kubeconfig loader - current-context %s, cluster %s, user %s, provider %s',
+ context_name,
+ self._current_context['context']['cluster'],
+ self._current_context['context'].safe_get('user'),
+ self.provider)
+
async def _load_authentication(self):
"""Read authentication from kube-config user section if exists.
@@ -176,6 +183,7 @@ class KubeConfigLoader(object):
"""
if not self._user:
+ logging.debug('No user section in current context.')
return
if self.provider == 'gcp':
@@ -187,13 +195,16 @@ class KubeConfigLoader(object):
return
if 'exec' in self._user:
+ logging.debug('Try to use exec provider')
res_exec_plugin = await self._load_from_exec_plugin()
if res_exec_plugin:
return
+ logging.debug('Try to load user token')
if self._load_user_token():
return
+ logging.debug('Try to use username and password')
self._load_user_pass_token()
async def load_gcp_token(self):
|
feat: add debug logs to KubeConfigLoader (#<I>)
|
tomplus_kubernetes_asyncio
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.