hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
---|---|---|---|---|
51d2a90816e2369b97a11ebce234a33ec0f067f1 | diff --git a/endless_pagination/__init__.py b/endless_pagination/__init__.py
index <HASH>..<HASH> 100644
--- a/endless_pagination/__init__.py
+++ b/endless_pagination/__init__.py
@@ -5,7 +5,7 @@ Twitter-style and Digg-style pagination.
from __future__ import unicode_literals
-VERSION = (1, 1)
+VERSION = (1, 2)
def get_version():
diff --git a/endless_pagination/static/endless_pagination/js/module.endless.js b/endless_pagination/static/endless_pagination/js/module.endless.js
index <HASH>..<HASH> 100644
--- a/endless_pagination/static/endless_pagination/js/module.endless.js
+++ b/endless_pagination/static/endless_pagination/js/module.endless.js
@@ -4,6 +4,15 @@
*/
Vue.directive('endlessPagination', {
bind: function (el, binding, arg) {
+ // Execute tag scripts after ajax
+ function evalScripts(e) {
+ var scripts = e.getElementsByTagName("script");
+ for (var i = 0; i < scripts.length; ++i) {
+ var script = scripts[i];
+ eval(script.innerHTML);
+ }
+ }
+
// Vanilla Ajax
function getAjax(url, params, callback) {
var request = new XMLHttpRequest();
@@ -175,6 +184,8 @@ Vue.directive('endlessPagination', {
getAjax(context.url, {querystring_key: context.key}, function(fragment) {
var e = document.createElement('div');
e.innerHTML = fragment;
+ evalScripts(e);
+
if (container.parentElement != null ){
container.parentElement.appendChild(e);
container.remove();
@@ -232,6 +243,7 @@ Vue.directive('endlessPagination', {
// Send the Ajax request.
getAjax(context.url, {querystring_key: context.key}, function(fragment) {
page_template.innerHTML = fragment;
+ evalScripts(page_template);
onCompleted.apply(link, [context, fragment.trim()]);
});
} | New version with eval tag scripts in ajax | mapeveri_django-endless-pagination-vue | train |
60d49671a802de5452dabe86e34a9c48569d595b | diff --git a/lib/teleterm/gateway/config.go b/lib/teleterm/gateway/config.go
index <HASH>..<HASH> 100644
--- a/lib/teleterm/gateway/config.go
+++ b/lib/teleterm/gateway/config.go
@@ -17,11 +17,14 @@ limitations under the License.
package gateway
import (
- "github.com/google/uuid"
- "github.com/gravitational/teleport/lib/teleterm/api/uri"
+ "runtime"
+ "github.com/gravitational/teleport/api/constants"
+ "github.com/gravitational/teleport/lib/defaults"
+ "github.com/gravitational/teleport/lib/teleterm/api/uri"
"github.com/gravitational/trace"
+ "github.com/google/uuid"
"github.com/sirupsen/logrus"
)
@@ -70,6 +73,10 @@ func (c *Config) CheckAndSetDefaults() error {
if c.LocalAddress == "" {
c.LocalAddress = "localhost"
+ // SQL Server Management Studio won't connect to localhost:12345, so use 127.0.0.1:12345 instead.
+ if runtime.GOOS == constants.WindowsOS && c.Protocol == defaults.ProtocolSQLServer {
+ c.LocalAddress = "127.0.0.1"
+ }
}
if c.LocalPort == "" { | Use IP as `LocalAddress` when gateway is created on Windows for SQL Server (#<I>) | gravitational_teleport | train |
dff1df22b06497742cb57a61f1e664c1bac4b68a | diff --git a/lib/ronin/ui/command_line/commands/add.rb b/lib/ronin/ui/command_line/commands/add.rb
index <HASH>..<HASH> 100644
--- a/lib/ronin/ui/command_line/commands/add.rb
+++ b/lib/ronin/ui/command_line/commands/add.rb
@@ -30,12 +30,10 @@ module Ronin
module Commands
class Add < Command
- def initialize(name)
+ def setup
@cache = nil
@media = nil
@uri = nil
-
- super(name)
end
def define_options(opts)
diff --git a/lib/ronin/ui/command_line/commands/ext.rb b/lib/ronin/ui/command_line/commands/ext.rb
index <HASH>..<HASH> 100644
--- a/lib/ronin/ui/command_line/commands/ext.rb
+++ b/lib/ronin/ui/command_line/commands/ext.rb
@@ -34,10 +34,8 @@ module Ronin
module Commands
class Ext < Command
- def initialize(name)
+ def setup
@uses = []
-
- super(name)
end
def define_options(opts)
diff --git a/lib/ronin/ui/command_line/commands/install.rb b/lib/ronin/ui/command_line/commands/install.rb
index <HASH>..<HASH> 100644
--- a/lib/ronin/ui/command_line/commands/install.rb
+++ b/lib/ronin/ui/command_line/commands/install.rb
@@ -30,11 +30,9 @@ module Ronin
module Commands
class Install < Command
- def initialize(name)
+ def setup
@cache = nil
@media = nil
-
- super(name)
end
def define_options(opts)
diff --git a/lib/ronin/ui/command_line/commands/ls.rb b/lib/ronin/ui/command_line/commands/ls.rb
index <HASH>..<HASH> 100644
--- a/lib/ronin/ui/command_line/commands/ls.rb
+++ b/lib/ronin/ui/command_line/commands/ls.rb
@@ -30,11 +30,9 @@ module Ronin
module Commands
class LS < Command
- def initialize(name)
+ def setup
@cache = nil
@verbose = false
-
- super(name)
end
def define_options(opts)
diff --git a/lib/ronin/ui/command_line/commands/overlay.rb b/lib/ronin/ui/command_line/commands/overlay.rb
index <HASH>..<HASH> 100644
--- a/lib/ronin/ui/command_line/commands/overlay.rb
+++ b/lib/ronin/ui/command_line/commands/overlay.rb
@@ -36,7 +36,7 @@ module Ronin
include REXML
- def initialize(name)
+ def setup
@title = nil
@source = nil
@source_view = nil
@@ -44,8 +44,6 @@ module Ronin
@license = nil
@maintainers = []
@description = nil
-
- super(name)
end
def define_options(opts)
diff --git a/lib/ronin/ui/command_line/commands/rm.rb b/lib/ronin/ui/command_line/commands/rm.rb
index <HASH>..<HASH> 100644
--- a/lib/ronin/ui/command_line/commands/rm.rb
+++ b/lib/ronin/ui/command_line/commands/rm.rb
@@ -30,11 +30,9 @@ module Ronin
module Commands
class RM < Command
- def initialize(name)
+ def setup
@cache = nil
@verbose = false
-
- super(name)
end
def define_options(opts)
diff --git a/lib/ronin/ui/command_line/commands/uninstall.rb b/lib/ronin/ui/command_line/commands/uninstall.rb
index <HASH>..<HASH> 100644
--- a/lib/ronin/ui/command_line/commands/uninstall.rb
+++ b/lib/ronin/ui/command_line/commands/uninstall.rb
@@ -30,11 +30,9 @@ module Ronin
module Commands
class Uninstall < Command
- def initialize(name)
+ def setup
@cache = nil
@verbose = false
-
- super(name)
end
def define_options(opts)
diff --git a/lib/ronin/ui/command_line/commands/update.rb b/lib/ronin/ui/command_line/commands/update.rb
index <HASH>..<HASH> 100644
--- a/lib/ronin/ui/command_line/commands/update.rb
+++ b/lib/ronin/ui/command_line/commands/update.rb
@@ -30,11 +30,9 @@ module Ronin
module Commands
class Update < Command
- def initialize(name)
+ def setup
@cache = nil
@verbose = false
-
- super(name)
end
def define_options(opts) | Convert old initialize methods to setup methods. | ronin-ruby_ronin | train |
f7ddfdb75468f1b9e84bfcc4fb63b1d70ebbfbb7 | diff --git a/metrics-core/src/main/java/com/yammer/metrics/MetricRegistry.java b/metrics-core/src/main/java/com/yammer/metrics/MetricRegistry.java
index <HASH>..<HASH> 100644
--- a/metrics-core/src/main/java/com/yammer/metrics/MetricRegistry.java
+++ b/metrics-core/src/main/java/com/yammer/metrics/MetricRegistry.java
@@ -87,11 +87,15 @@ public class MetricRegistry {
*/
@SuppressWarnings("unchecked")
public <T extends Metric> T register(String name, T metric) throws IllegalArgumentException {
- final Metric existing = metrics.putIfAbsent(name, metric);
- if (existing == null) {
- onMetricAdded(name, metric);
+ if (metric instanceof MetricSet) {
+ registerAll(name, (MetricSet) metric);
} else {
- throw new IllegalArgumentException("A metric named " + name + " already exists");
+ final Metric existing = metrics.putIfAbsent(name, metric);
+ if (existing == null) {
+ onMetricAdded(name, metric);
+ } else {
+ throw new IllegalArgumentException("A metric named " + name + " already exists");
+ }
}
return metric;
}
@@ -107,19 +111,6 @@ public class MetricRegistry {
}
/**
- * Given a metric set, registers them using a prefix.
- *
- * @param prefix the prefix for all the names
- * @param metrics a set of metrics
- * @throws IllegalArgumentException if any of the names are already registered
- */
- public void registerAll(String prefix, MetricSet metrics) throws IllegalArgumentException {
- for (Map.Entry<String, Metric> entry : metrics.getMetrics().entrySet()) {
- register(name(prefix, entry.getKey()), entry.getValue());
- }
- }
-
- /**
* Creates a new {@link Counter} and registers it under the given name.
*
* @param name the name of the metric
@@ -392,6 +383,16 @@ public class MetricRegistry {
}
}
+ private void registerAll(String prefix, MetricSet metrics) throws IllegalArgumentException {
+ for (Map.Entry<String, Metric> entry : metrics.getMetrics().entrySet()) {
+ if (entry.getValue() instanceof MetricSet) {
+ registerAll(name(prefix, entry.getKey()), (MetricSet) entry.getValue());
+ } else {
+ register(name(prefix, entry.getKey()), entry.getValue());
+ }
+ }
+ }
+
/**
* A quick and easy way of capturing the notion of default metrics.
*/
diff --git a/metrics-core/src/main/java/com/yammer/metrics/MetricSet.java b/metrics-core/src/main/java/com/yammer/metrics/MetricSet.java
index <HASH>..<HASH> 100644
--- a/metrics-core/src/main/java/com/yammer/metrics/MetricSet.java
+++ b/metrics-core/src/main/java/com/yammer/metrics/MetricSet.java
@@ -6,9 +6,8 @@ import java.util.Map;
* A set of named metrics.
*
* @see MetricRegistry#registerAll(MetricSet)
- * @see MetricRegistry#registerAll(String,MetricSet)
*/
-public interface MetricSet {
+public interface MetricSet extends Metric {
/**
* A map of metric names to metrics.
*
diff --git a/metrics-core/src/test/java/com/yammer/metrics/tests/MetricRegistryTest.java b/metrics-core/src/test/java/com/yammer/metrics/tests/MetricRegistryTest.java
index <HASH>..<HASH> 100644
--- a/metrics-core/src/test/java/com/yammer/metrics/tests/MetricRegistryTest.java
+++ b/metrics-core/src/test/java/com/yammer/metrics/tests/MetricRegistryTest.java
@@ -276,13 +276,40 @@ public class MetricRegistryTest {
}
};
- registry.registerAll("my", metrics);
+ registry.register("my", metrics);
assertThat(registry.getNames())
.containsOnly("my.gauge", "my.counter");
}
@Test
+ public void registersRecursiveMetricSets() throws Exception {
+ final MetricSet inner = new MetricSet() {
+ @Override
+ public Map<String, Metric> getMetrics() {
+ final Map<String, Metric> metrics = new HashMap<String, Metric>();
+ metrics.put("gauge", gauge);
+ return metrics;
+ }
+ };
+
+ final MetricSet outer = new MetricSet() {
+ @Override
+ public Map<String, Metric> getMetrics() {
+ final Map<String, Metric> metrics = new HashMap<String, Metric>();
+ metrics.put("inner", inner);
+ metrics.put("counter", counter);
+ return metrics;
+ }
+ };
+
+ registry.register("my", outer);
+
+ assertThat(registry.getNames())
+ .containsOnly("my.inner.gauge", "my.counter");
+ }
+
+ @Test
public void concatenatesStringsToFormADottedName() throws Exception {
assertThat(name("one", "two", "three"))
.isEqualTo("one.two.three");
@@ -316,6 +343,6 @@ public class MetricRegistryTest {
};
assertThat(name(g.getClass(), "one", "two"))
- .isEqualTo("com.yammer.metrics.tests.MetricRegistryTest$3.one.two");
+ .isEqualTo("com.yammer.metrics.tests.MetricRegistryTest$5.one.two");
}
} | Make MetricSet a Metric.
This allows you to have nested metric sets. | dropwizard_metrics | train |
3c78ec97a18e2dc62cddb3d6f4dc7a8f80a966b6 | diff --git a/IPAddress/src/inet.ipaddr/inet/ipaddr/format/AddressDivisionSeries.java b/IPAddress/src/inet.ipaddr/inet/ipaddr/format/AddressDivisionSeries.java
index <HASH>..<HASH> 100644
--- a/IPAddress/src/inet.ipaddr/inet/ipaddr/format/AddressDivisionSeries.java
+++ b/IPAddress/src/inet.ipaddr/inet/ipaddr/format/AddressDivisionSeries.java
@@ -162,7 +162,7 @@ public interface AddressDivisionSeries extends AddressItem, AddressStringDivisio
for(int i = 0; i < count; i++) {
AddressGenericDivision div = getDivision(i);
if(div.isMultiple()) {
- BigInteger divCount = getDivision(i).getCount();
+ BigInteger divCount = div.getCount();
result = result.multiply(divCount);
}
} | small improvement, don't get division twice | seancfoley_IPAddress | train |
6b506a545814bebac2e799f34c5d4ca13a8fa011 | diff --git a/src/main/java/com/iyzipay/model/CardManagementPageCard.java b/src/main/java/com/iyzipay/model/CardManagementPageCard.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/iyzipay/model/CardManagementPageCard.java
+++ b/src/main/java/com/iyzipay/model/CardManagementPageCard.java
@@ -9,6 +9,7 @@ import java.util.List;
public class CardManagementPageCard extends IyzipayResource {
+ private String externalId;
private String cardUserKey;
private List<Card> cardDetails;
@@ -19,6 +20,14 @@ public class CardManagementPageCard extends IyzipayResource {
CardManagementPageCard.class);
}
+ public String getExternalId() {
+ return externalId;
+ }
+
+ public void setExternalId(String externalId) {
+ this.externalId = externalId;
+ }
+
public String getCardUserKey() {
return cardUserKey;
}
diff --git a/src/main/java/com/iyzipay/request/CreateCheckoutFormInitializeRequest.java b/src/main/java/com/iyzipay/request/CreateCheckoutFormInitializeRequest.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/iyzipay/request/CreateCheckoutFormInitializeRequest.java
+++ b/src/main/java/com/iyzipay/request/CreateCheckoutFormInitializeRequest.java
@@ -27,6 +27,7 @@ public class CreateCheckoutFormInitializeRequest extends Request {
private String posOrderId;
private List<Integer> enabledInstallments;
private Boolean paymentWithNewCardEnabled;
+ private Boolean debitCardAllowed;
public BigDecimal getPrice() {
return price;
@@ -156,6 +157,14 @@ public class CreateCheckoutFormInitializeRequest extends Request {
this.paymentWithNewCardEnabled = paymentWithNewCardEnabled;
}
+ public Boolean getDebitCardAllowed() {
+ return debitCardAllowed;
+ }
+
+ public void setDebitCardAllowed(Boolean debitCardAllowed) {
+ this.debitCardAllowed = debitCardAllowed;
+ }
+
@Override
public String toString() {
return new ToStringRequestBuilder(this)
@@ -176,6 +185,7 @@ public class CreateCheckoutFormInitializeRequest extends Request {
.append("cardUserKey", cardUserKey)
.append("enabledInstallments", enabledInstallments)
.append("paymentWithNewCardEnabled", paymentWithNewCardEnabled)
+ .append("debitCardAllowed", debitCardAllowed)
.toString();
}
}
diff --git a/src/test/java/com/iyzipay/sample/CardManagementPageSample.java b/src/test/java/com/iyzipay/sample/CardManagementPageSample.java
index <HASH>..<HASH> 100644
--- a/src/test/java/com/iyzipay/sample/CardManagementPageSample.java
+++ b/src/test/java/com/iyzipay/sample/CardManagementPageSample.java
@@ -21,6 +21,7 @@ public class CardManagementPageSample extends Sample {
request.setValidateNewCard(Boolean.FALSE);
request.setDebitCardAllowed(Boolean.FALSE);
request.setCardUserKey("card user key");
+ request.setDebitCardAllowed(Boolean.TRUE);
request.setLocale(Locale.TR.getValue());
CardManagementPageInitialize cardManagementPageInitialize = CardManagementPageInitialize.create(request, options);
diff --git a/src/test/java/com/iyzipay/sample/CheckoutFormSample.java b/src/test/java/com/iyzipay/sample/CheckoutFormSample.java
index <HASH>..<HASH> 100644
--- a/src/test/java/com/iyzipay/sample/CheckoutFormSample.java
+++ b/src/test/java/com/iyzipay/sample/CheckoutFormSample.java
@@ -24,6 +24,7 @@ public class CheckoutFormSample extends Sample {
request.setBasketId("B67832");
request.setPaymentGroup(PaymentGroup.PRODUCT.name());
request.setCallbackUrl("https://www.merchant.com/callback");
+ request.setDebitCardAllowed(Boolean.TRUE);
List<Integer> enabledInstallments = new ArrayList<Integer>();
enabledInstallments.add(2); | Adds new fields to request and response for checkout form and card management. (#<I>)
* adds card metadata to card management retrieve card.
* adds external id for retrieve card while storing card in card management.
* adds debit card allowed to checkout form initialize request. | iyzico_iyzipay-java | train |
ae6f60adebe65b8c0a3c2b1c90c37525bf4549ec | diff --git a/lib/vehicle.js b/lib/vehicle.js
index <HASH>..<HASH> 100644
--- a/lib/vehicle.js
+++ b/lib/vehicle.js
@@ -11,44 +11,37 @@ const util = require('./util');
* Initializes a new Vehicle to use for making requests to the Smartcar API.
*
* @constructor
- * @param {String} vid - the vehicle's unique identifier
+ * @param {String} id - the vehicle's unique identifier
* @param {String} token - a valid access token
* @param {String} [unitSystem=metric] - the unit system to use for vehicle data
* (metric/imperial)
*/
-function Vehicle(vid, token, unitSystem) {
+function Vehicle(id, token, unitSystem) {
if (!(this instanceof Vehicle)) {
// eslint-disable-next-line max-len
- throw new errors.SmartcarError('Vehicle is a constructor. Usage: new Vehicle(vid, token)');
+ throw new TypeError("Class constructor Vehicle cannot be invoked without 'new'");
}
- unitSystem = unitSystem || 'metric';
- validateUnitSystem(unitSystem);
- this.vid = vid;
- this.token = token;
- this.unitSystem = unitSystem;
- this.request = createDefaultRequest(this.vid, this.token, this.unitSystem);
-}
+ this.id = id;
+ this.token = token;
+ this.request = request.defaults();
+ this.setUnitSystem(unitSystem || 'metric');
-function createDefaultRequest(vid, token, unitSystem) {
- return request.defaults({
- baseUrl: util.getUrl(vid),
+ this.updateRequest({
+ baseUrl: util.getUrl(this.id),
auth: {
- bearer: token,
+ bearer: this.token,
},
headers: {
'User-Agent': `smartcar-node-sdk:${config.version}`,
- 'sc-unit-system': unitSystem,
},
json: true,
});
}
-function validateUnitSystem(unitSystem) {
- if (['imperial', 'metric'].indexOf(unitSystem) < 0) {
- throw new TypeError('unit system must be one of: \'imperial\', \'metric\'');
- }
-}
+Vehicle.prototype.updateRequest = function(options) {
+ this.request = this.request.defaults(options);
+};
/**
* Update the unit system to use in requests to the Smartcar API.
@@ -56,10 +49,18 @@ function validateUnitSystem(unitSystem) {
* @param {String} unitSystem - the unit system to use (metric/imperial)
*/
Vehicle.prototype.setUnitSystem = function(unitSystem) {
- validateUnitSystem(unitSystem);
+
+ if (['imperial', 'metric'].indexOf(unitSystem) < 0) {
+ throw new TypeError('unit system must be one of: \'imperial\', \'metric\'');
+ }
this.unitSystem = unitSystem;
- this.request = createDefaultRequest(this.vid, this.token, this.unitSystem);
+ this.updateRequest({
+ headers: {
+ 'sc-unit-system': this.unitSystem,
+ },
+ });
+
};
/**
@@ -72,13 +73,7 @@ Vehicle.prototype.setUnitSystem = function(unitSystem) {
* @return {Promise} // TODO document return type more throughly
*/
Vehicle.prototype.disconnect = function() {
- return this.request({
- uri: 'application',
- method: 'DELETE',
- auth: {
- bearer: this.token,
- },
- });
+ return this.request.delete('application');
};
/**
@@ -87,14 +82,7 @@ Vehicle.prototype.disconnect = function() {
* @return {Promise} // TODO document return type more throughly
*/
Vehicle.prototype.permissions = function() {
- const options = {
- uri: 'permissions',
- method: 'GET',
- auth: {
- bearer: this.token,
- },
- };
- return this.request(options);
+ return this.request.get('permissions');
};
/* VEHICLE API METHODS */
diff --git a/test/test_vehicle.js b/test/test_vehicle.js
index <HASH>..<HASH> 100644
--- a/test/test_vehicle.js
+++ b/test/test_vehicle.js
@@ -175,7 +175,7 @@ suite('Vehicle', function() {
const badConstruct = function() {
Vehicle(VALID_VID, VALID_TOKEN);
};
- expect(badConstruct).to.throw(Error, /new Vehicle/);
+ expect(badConstruct).to.throw(Error, /cannot be invoked without 'new'/);
});
test('disconnect', function() {
diff --git a/test/test_vehicle_methods_no_params.js b/test/test_vehicle_methods_no_params.js
index <HASH>..<HASH> 100644
--- a/test/test_vehicle_methods_no_params.js
+++ b/test/test_vehicle_methods_no_params.js
@@ -44,7 +44,8 @@ suite('Vehicle prototype', function() {
for (const method in Vehicle.prototype) {
if (Vehicle.prototype.hasOwnProperty(method)
- && methodsRequiringParams.indexOf(method) < 0) {
+ && methodsRequiringParams.indexOf(method) < 0
+ && method !== 'updateRequest') {
methodsNotRequiringParams.push(method);
}
} | refactor(vehicle): clean up vehicle constructor | smartcar_node-sdk | train |
c4355039955893a4ca4f729cca8734681e202fec | diff --git a/src/Utils/DOMUtils.php b/src/Utils/DOMUtils.php
index <HASH>..<HASH> 100644
--- a/src/Utils/DOMUtils.php
+++ b/src/Utils/DOMUtils.php
@@ -190,7 +190,7 @@ class DOMUtils {
* @param DOMNode|null $ancestor
* $ancestor should be an ancestor of $node.
* If null, we'll walk to the document root.
- * @return DOMNode
+ * @return DOMNode[]
*/
public static function pathToAncestor( DOMNode $node, DOMNode $ancestor = null ) {
$path = [];
diff --git a/src/Utils/TokenUtils.php b/src/Utils/TokenUtils.php
index <HASH>..<HASH> 100644
--- a/src/Utils/TokenUtils.php
+++ b/src/Utils/TokenUtils.php
@@ -9,8 +9,6 @@
namespace Parsoid\Utils;
-require_once __DIR__ . '/../vendor/autoload.php';
-
use Parsoid\Config\WikitextConstants as Consts;
use Parsoid\Tokens\Token;
use Parsoid\Tokens\TagTk;
@@ -72,14 +70,21 @@ class TokenUtils {
( $token instanceof TagTk ||
$token instanceof EndTagTk ||
$token instanceof SelfClosingTagTk ) &&
- ( $token->dataAttribs['stx'] === 'html' );
+ isset( $token->dataAttribs['stx'] ) &&
+ $token->dataAttribs['stx'] === 'html';
}
-/*---------------
- public static function isDOMFragmentType(typeOf) {
- return /(?:^|\s)mw:DOMFragment(\/sealed\/\w+)?(?=$|\s)/.test(typeOf);
+ /**
+ * Is the typeof a DOMFragment type value?
+ *
+ * @param string $typeOf
+ * @return bool
+ */
+ public static function isDOMFragmentType( $typeOf ) {
+ return preg_match( '#(?:^|\s)mw:DOMFragment(/sealed/\w+)?(?=$|\s)#', $typeOf );
}
+/*---------------
public static function isTableTag(token) {
var tc = token.constructor;
return (tc === TagTk || tc === EndTagTk) &&
diff --git a/src/Utils/Util.php b/src/Utils/Util.php
index <HASH>..<HASH> 100644
--- a/src/Utils/Util.php
+++ b/src/Utils/Util.php
@@ -5,8 +5,6 @@
// Not tested, all code that is not ported throws exceptions or has a PORT-FIXME comment.
namespace Parsoid\Utils;
-require_once __DIR__ . '/../vendor/autoload.php';
-
use Parsoid\Config\WikitextConstants as Consts;
/** | Bunch of unrelated tweaks to previously ported Utils
* Most of the fixes are based on trying to reverify previously
verified dsr computation code.
Change-Id: Ia<I>bce<I>e2df<I>d<I>d<I>b5db1af<I>ffb<I>e | wikimedia_parsoid | train |
c9cd89f489502c6eec31902c37325a5a05d5dcb5 | diff --git a/src/GitElephant/Command/MainCommand.php b/src/GitElephant/Command/MainCommand.php
index <HASH>..<HASH> 100644
--- a/src/GitElephant/Command/MainCommand.php
+++ b/src/GitElephant/Command/MainCommand.php
@@ -95,6 +95,7 @@ class MainCommand extends BaseCommand
{
$this->clearAll();
$this->addCommandName(self::GIT_ADD);
+ $this->addCommandArgument('--all');
$this->addCommandSubject($what);
return $this->getCommand();
diff --git a/tests/GitElephant/Command/MainCommandTest.php b/tests/GitElephant/Command/MainCommandTest.php
index <HASH>..<HASH> 100644
--- a/tests/GitElephant/Command/MainCommandTest.php
+++ b/tests/GitElephant/Command/MainCommandTest.php
@@ -62,8 +62,8 @@ class MainCommandTest extends TestCase
*/
public function testAdd()
{
- $this->assertEquals(MainCommand::GIT_ADD." '.'", $this->mainCommand->add());
- $this->assertEquals(MainCommand::GIT_ADD." 'foo'", $this->mainCommand->add('foo'));
+ $this->assertEquals(MainCommand::GIT_ADD." '--all' '.'", $this->mainCommand->add());
+ $this->assertEquals(MainCommand::GIT_ADD." '--all' 'foo'", $this->mainCommand->add('foo'));
}
/** | added --all to git add command to add also deleted path by default | matteosister_GitElephant | train |
3f3d4b230077762c362520be9816ebc003a29877 | diff --git a/homie/device.py b/homie/device.py
index <HASH>..<HASH> 100644
--- a/homie/device.py
+++ b/homie/device.py
@@ -40,6 +40,7 @@ class HomieDevice:
"""MicroPython implementation of the Homie MQTT convention for IoT."""
def __init__(self, settings):
+ self.debug = getattr(settings, "DEBUG", False)
self._state = STATE_INIT
self._extensions = getattr(settings, "EXTENSIONS", [])
self._first_start = True
@@ -148,7 +149,7 @@ class HomieDevice:
self._first_start = False
# activate WDT
- if LINUX is False:
+ if LINUX is False and self.debug is False:
loop = get_event_loop()
loop.create_task(self.wdt())
diff --git a/settings.example.py b/settings.example.py
index <HASH>..<HASH> 100644
--- a/settings.example.py
+++ b/settings.example.py
@@ -1,3 +1,6 @@
+# Debug mode disables WDT
+# DEBUG = False
+
###
# Wifi settings
###
@@ -54,8 +57,7 @@ MQTT_BROKER = "10.0.0.1"
# Time in seconds the device updates device properties
# DEVICE_STATS_INTERVAL = 60
-# Legacy extensions, for now we only have support for the two legacy extensions.
-# Later we will implement the posibility to add extensions.
+# Legacy extensions, for now have support for the two legacy extensions.
# No extensions will be loaded per default
# EXTENSIONS = []
# EXTENSIONS = [ | Add debug option to disable WDT. #<I> | microhomie_microhomie | train |
46d4780a76fe580be61bfcfe171d59c06bf6c4f9 | diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -308,7 +308,7 @@ by [environment variables]:
You can also specify different browser queries for various environments.
Browserslist will choose query according to `BROWSERSLIST_ENV` or `NODE_ENV`
variables. If none of them is declared, Browserslist will firstly look
-for `development` queries and then use defaults.
+for `production` queries and then use defaults.
In `package.json`:
diff --git a/node.js b/node.js
index <HASH>..<HASH> 100644
--- a/node.js
+++ b/node.js
@@ -58,7 +58,7 @@ function pickEnv (config, opts) {
} else if (process.env.NODE_ENV) {
name = process.env.NODE_ENV
} else {
- name = 'development'
+ name = 'production'
}
return config[name] || config.defaults
diff --git a/test/main.test.js b/test/main.test.js
index <HASH>..<HASH> 100644
--- a/test/main.test.js
+++ b/test/main.test.js
@@ -197,8 +197,8 @@ it('uses BROWSERSLIST_ENV to get environment', () => {
.toEqual(['chrome 55', 'firefox 50'])
})
-it('uses development environment by default', () => {
+it('uses production environment by default', () => {
delete process.env.NODE_ENV
expect(browserslist(null, { path: CONFIG }))
- .toEqual(['chrome 55', 'firefox 50'])
+ .toEqual(['ie 9', 'opera 41'])
}) | Change default environment to production, fixes #<I> (#<I>) | browserslist_browserslist | train |
e2eacb899ed158c471ccb05d2c12f76231ad21d0 | diff --git a/Kwc/Directories/Item/Directory/Controller.php b/Kwc/Directories/Item/Directory/Controller.php
index <HASH>..<HASH> 100644
--- a/Kwc/Directories/Item/Directory/Controller.php
+++ b/Kwc/Directories/Item/Directory/Controller.php
@@ -53,7 +53,7 @@ class Kwc_Directories_Item_Directory_Controller extends Kwf_Controller_Action_Au
}
$i=0;
foreach ($extConfig['contentEditComponents'] as $ec) {
- $name = Kwc_Abstract::getSetting($ec['componentClass'], 'componentName');
+ $name = Kwf_Trl::getInstance()->trlStaticExecute(Kwc_Abstract::getSetting($ec['componentClass'], 'componentName'));
$icon = Kwc_Abstract::getSetting($ec['componentClass'], 'componentIcon');
$this->_columns->add(new Kwc_Directories_Item_Directory_ControllerEditButton('edit_'.$i, ' ', 20))
->setColumnType('editContent')
diff --git a/Kwc/Directories/Item/Directory/Trl/Controller.php b/Kwc/Directories/Item/Directory/Trl/Controller.php
index <HASH>..<HASH> 100644
--- a/Kwc/Directories/Item/Directory/Trl/Controller.php
+++ b/Kwc/Directories/Item/Directory/Trl/Controller.php
@@ -56,7 +56,7 @@ class Kwc_Directories_Item_Directory_Trl_Controller extends Kwf_Controller_Actio
$i=0;
foreach ($extConfig['contentEditComponents'] as $ec) {
- $name = Kwc_Abstract::getSetting($ec['componentClass'], 'componentName');
+ $name = Kwf_Trl::getInstance()->trlStaticExecute(Kwc_Abstract::getSetting($ec['componentClass'], 'componentName'));
$icon = Kwc_Abstract::getSetting($ec['componentClass'], 'componentIcon');
$this->_columns->add(new Kwf_Grid_Column_Button('edit_'.$i, ' ', 20))
->setColumnType('editContent') | add missing trlStaticExecute for componentName | koala-framework_koala-framework | train |
3a695ab93ff9416f318591d5c4cbc0c89efacfe8 | diff --git a/lib/crtomo/status.py b/lib/crtomo/status.py
index <HASH>..<HASH> 100644
--- a/lib/crtomo/status.py
+++ b/lib/crtomo/status.py
@@ -20,14 +20,15 @@ def is_tomodir(directory):
True if the supplied directory is a tomodir directory
"""
if os.path.isdir(directory):
- if(os.path.isdir(directory + "/exe") and
- os.path.isdir(directory + "/config") and
- os.path.isdir(directory + "/rho") and
- os.path.isdir(directory + "/inv") and
- os.path.isdir(directory + "/mod")):
- return True
+ if(os.path.isdir(
+ directory + "/exe") and os.path.isdir(
+ directory + "/config") and os.path.isdir(
+ directory + "/rho") and os.path.isdir(
+ directory + "/inv") and os.path.isdir(
+ directory + "/mod")):
+ return True
else:
- return False
+ return False
else:
return False
@@ -39,15 +40,15 @@ def td_is_finished(tomodir):
Parameters
----------
- tomodir: string
+ tomodir : string
Directory to check
Returns
-------
- crmod_is_finished: bool
+ crmod_is_finished : bool
True if a successful CRMod result is contained in the tomodir
directory.
- crtomo_is_finished: bool
+ crtomo_is_finished : bool
True if a successful CRTomo inversion results is contained in the
tomodir directory.
""" | small doc and pep8 fixes | geophysics-ubonn_crtomo_tools | train |
28b2891e4ca6669d1f0fa182e5172a711d5c7a3c | diff --git a/user/policy.php b/user/policy.php
index <HASH>..<HASH> 100644
--- a/user/policy.php
+++ b/user/policy.php
@@ -44,11 +44,20 @@
500, 500, 'Popup window', 'none', true);
echo '</object></div>';
- $linkyes = 'policy.php';
+ // see MDL-9798
+/* $linkyes = 'policy.php';
$optionsyes = array('agree'=>1, 'sesskey'=>sesskey());
$linkno = $CFG->wwwroot.'/login/logout.php';
$optionsno = array('sesskey'=>sesskey());
- notice_yesno($strpolicyagree, $linkyes, $linkno, $optionsyes, $optionsno);
+ notice_yesno($strpolicyagree, $linkyes, $linkno, $optionsyes, $optionsno);*/
+
+ print_box_start('generalbox', 'notice');
+ echo '<p>'. $strpolicyagree .'</p>';
+ echo '<div class="buttons">';
+ echo '<div class="singlebutton"><a href="policy.php?agree=1&sesskey='.sesskey().'">'.get_string('yes').'</a></div>';
+ echo '<div class="singlebutton"><a href="../login/logout.php?sesskey='.sesskey().'">'.get_string('no').'</a></div>';
+ echo '</div>';
+ print_box_end();
print_footer(); | MDL-<I> workaround for handling of object tag in buggy IE; merged from MOODLE_<I>_STABLE | moodle_moodle | train |
b4499998cbe18a065988c0a20b3a2129aec35280 | diff --git a/src/main/java/com/feedzai/commons/sql/abstraction/engine/AbstractDatabaseEngine.java b/src/main/java/com/feedzai/commons/sql/abstraction/engine/AbstractDatabaseEngine.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/feedzai/commons/sql/abstraction/engine/AbstractDatabaseEngine.java
+++ b/src/main/java/com/feedzai/commons/sql/abstraction/engine/AbstractDatabaseEngine.java
@@ -402,8 +402,7 @@ public abstract class AbstractDatabaseEngine implements DatabaseEngine {
try {
me.getValue().close();
} catch (Exception e) {
- // Should never be thrown
- logger.trace("Could not close insert statements.", e);
+ logger.warn("Could not close insert statements from mapped entity.", e);
}
} | ref PULSEDEV-<I> pdb: Log warning when failing to close insert statements | feedzai_pdb | train |
3ff8e9a449be4118d53682cd7fb188a3f0e7ee1c | diff --git a/lib/fluent/plugin/out_record_reformer.rb b/lib/fluent/plugin/out_record_reformer.rb
index <HASH>..<HASH> 100644
--- a/lib/fluent/plugin/out_record_reformer.rb
+++ b/lib/fluent/plugin/out_record_reformer.rb
@@ -155,7 +155,7 @@ module Fluent
end
def expand(str)
- str.gsub(/(\${[a-z_]+(\[-?[0-9]+\])?}|__[A-Z_]+__)/) {
+ str.gsub(/(\${[a-zA-Z_]+(\[-?[0-9]+\])?}|__[A-Z_]+__)/) {
log.warn "record_reformer: unknown placeholder `#{$1}` found" unless @placeholders.include?($1)
@placeholders[$1]
}
diff --git a/spec/out_record_reformer_spec.rb b/spec/out_record_reformer_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/out_record_reformer_spec.rb
+++ b/spec/out_record_reformer_spec.rb
@@ -259,21 +259,23 @@ describe Fluent::RecordReformerOutput do
context "record with enable_ruby #{enable_ruby}" do
let(:emit) do
driver.run do
- driver.emit({'message' => '1'}, time.to_i)
- driver.emit({'message' => '2'}, time.to_i)
+ driver.emit({'message' => '1', 'eventType' => 'foo'}, time.to_i)
+ driver.emit({'message' => '2', 'eventType' => 'foo'}, time.to_i)
end
end
let(:config) {%[
tag tag
enable_ruby #{enable_ruby}
message bar ${message}
+ eventtype ${eventType}
+ remove_keys eventType
]}
let(:tag) { 'prefix.test.tag.suffix' }
let(:tag_parts) { tag.split('.') }
before do
Fluent::Engine.stub(:now).and_return(time)
- Fluent::Engine.should_receive(:emit).with("tag", time.to_i, { 'message' => "bar 1", })
- Fluent::Engine.should_receive(:emit).with("tag", time.to_i, { 'message' => "bar 2", })
+ Fluent::Engine.should_receive(:emit).with("tag", time.to_i, { 'message' => "bar 1", 'eventtype' => 'foo'})
+ Fluent::Engine.should_receive(:emit).with("tag", time.to_i, { 'message' => "bar 2", 'eventtype' => 'foo'})
end
it { emit }
end | fix to support camelCase key name | sonots_fluent-plugin-record-reformer | train |
a7dd74a2c50696625a7d0a81508b83e90e27ccee | diff --git a/lib/redfish.rb b/lib/redfish.rb
index <HASH>..<HASH> 100644
--- a/lib/redfish.rb
+++ b/lib/redfish.rb
@@ -24,21 +24,25 @@ require 'redfish/core'
require 'redfish/mash'
require 'redfish/util'
require 'redfish/config'
-require 'redfish/property_cache'
-require 'redfish/context'
-require 'redfish/executor'
require 'redfish/task_manager'
require 'redfish/task'
require 'redfish/task_execution_record'
+require 'redfish/listener'
require 'redfish/run_context'
+
+#
+# GlassFish specific parts
+#
+
+require 'redfish/property_cache'
+require 'redfish/context'
+require 'redfish/executor'
require 'redfish/interpreter/pre_interpreter'
require 'redfish/interpreter/interpolater'
require 'redfish/interpreter/interpreter'
require 'redfish/model'
require 'redfish/definition'
require 'redfish/driver'
-require 'redfish/listener'
-
require 'redfish/buildr_integration'
require 'redfish/glassfish/versions/version_manager' | Restructure requires so that GlassFish specific components are grouped | realityforge_redfish | train |
9388fca3b7022d760e786783a3e3baff7454e3ef | diff --git a/java/src/main/java/gherkin/formatter/JSONFormatter.java b/java/src/main/java/gherkin/formatter/JSONFormatter.java
index <HASH>..<HASH> 100644
--- a/java/src/main/java/gherkin/formatter/JSONFormatter.java
+++ b/java/src/main/java/gherkin/formatter/JSONFormatter.java
@@ -81,7 +81,7 @@ public class JSONFormatter implements Reporter, Formatter {
@Override
public void embedding(String mimeType, InputStream data) {
final Map<String, String> embedding = new HashMap<String, String>();
- embedding.put("mime_type", mimeType);
+ embedding.put("mime_qtype", mimeType);
embedding.put("data", Base64.encodeBytes(readStream(data)));
getEmbeddings().add(embedding);
}
@@ -93,15 +93,8 @@ public class JSONFormatter implements Reporter, Formatter {
@Override
public void result(Result result) {
- if (getFeatureElements().size() > 0) {
- getStepAt(stepIndex).put("result", result.toMap());
- stepIndex++;
- } else {
- //A result was offered before any steps have been offered
- //Lets just add a failed result directly to the feature
- //TODO: this gets the exception down, but makes a mess of the JSON
- getFeatureElements().add(result.toMap());
- }
+ getStepAt(stepIndex).put("result", result.toMap());
+ stepIndex++;
}
@Override
@@ -122,7 +115,7 @@ public class JSONFormatter implements Reporter, Formatter {
public void after(HookResult result) {
handleHooks(result, false);
}
-
+
private void handleHooks(HookResult result, boolean isBefore) {
String hook = isBefore ? "before" : "after"; | Restoring method to it's previous non-convoluted state | cucumber-attic_gherkin2 | train |
234c227fd5907f09ffd5973ec3bab6981fb114b5 | diff --git a/lib/models/room.js b/lib/models/room.js
index <HASH>..<HASH> 100644
--- a/lib/models/room.js
+++ b/lib/models/room.js
@@ -467,16 +467,26 @@ Room.prototype.addEventsToTimeline = function(events, toStartOfTimeline,
// contained the event we knew about (steps 3, 5, 6).
//
//
- // Finally, consider what we want to do with the pagination token. In the
- // case above, we will be given a pagination token which tells us how to
+ // So much for adding events to the timeline. But what do we want to do
+ // with the pagination token?
+ //
+ // In the case above, we will be given a pagination token which tells us how to
// get events beyond 'U' - in this case, it makes sense to store this
// against timeline4. But what if timeline4 already had 'U' and beyond? in
// that case, our best bet is to throw away the pagination token we were
// given and stick with whatever token timeline4 had previously. In short,
// we want to only store the pagination token if the last event we receive
// is one we didn't previously know about.
-
- var updateToken = false;
+ //
+ // We make an exception for this if it turns out that we already knew about
+ // *all* of the events, and we weren't able to join up any timelines. When
+ // that happens, it means our existing pagination token is faulty, since it
+ // is only telling us what we already know. Rather than repeatedly
+ // paginating with the same token, we might as well use the new pagination
+ // token in the hope that we eventually work our way out of the mess.
+
+ var didUpdate = false;
+ var lastEventWasNew = false;
for (var i = 0; i < events.length; i++) {
var event = events[i];
var eventId = event.getId();
@@ -486,13 +496,12 @@ Room.prototype.addEventsToTimeline = function(events, toStartOfTimeline,
if (!existingTimeline) {
// we don't know about this event yet. Just add it to the timeline.
this._addEventToTimeline(event, timeline, toStartOfTimeline);
- updateToken = true;
+ lastEventWasNew = true;
+ didUpdate = true;
continue;
}
- // we already know about this event. We don't want to use the pagination
- // token if this is the last event, as per the text above.
- updateToken = false;
+ lastEventWasNew = false;
if (existingTimeline == timeline) {
console.log("Event " + eventId + " already in timeline " + timeline);
@@ -528,9 +537,13 @@ Room.prototype.addEventsToTimeline = function(events, toStartOfTimeline,
timeline.setNeighbouringTimeline(existingTimeline, direction);
existingTimeline.setNeighbouringTimeline(timeline, inverseDirection);
timeline = existingTimeline;
+ didUpdate = true;
}
- if (updateToken) {
+ // see above - if the last event was new to us, or if we didn't find any
+ // new information, we update the pagination token for whatever
+ // timeline we ended up on.
+ if (lastEventWasNew || !didUpdate) {
timeline.setPaginationToken(paginationToken, direction);
}
}; | Work around confused timelines causing pagination loops
Look out for us getting stuck in a loop of using the same pagination token,
and use something else next time.
Hopefully this will fix <URL> | matrix-org_matrix-js-sdk | train |
929b8c0c1e9fc5ba485ea8ef9e13af582548c5eb | diff --git a/src/IlluminateRegistry.php b/src/IlluminateRegistry.php
index <HASH>..<HASH> 100644
--- a/src/IlluminateRegistry.php
+++ b/src/IlluminateRegistry.php
@@ -246,21 +246,10 @@ final class IlluminateRegistry implements ManagerRegistry
}
/**
- * Resets a named object manager.
- * This method is useful when an object manager has been closed
- * because of a rollbacked transaction AND when you think that
- * it makes sense to get a new one to replace the closed one.
- * Be warned that you will get a brand new object manager as
- * the existing one is not useable anymore. This means that any
- * other object with a dependency on this object manager will
- * hold an obsolete reference. You can inject the registry instead
- * to avoid this problem.
- *
+ * Close an existing object manager.
* @param string|null $name The object manager name (null for the default one).
- *
- * @return \Doctrine\Common\Persistence\ObjectManager
*/
- public function resetManager($name = null)
+ public function closeManager($name = null)
{
$name = $name ?: $this->getDefaultManagerName();
@@ -280,7 +269,43 @@ final class IlluminateRegistry implements ManagerRegistry
unset($this->managersMap[$name]);
unset($this->connectionsMap[$name]);
+ }
+
+ /**
+ * Purge a named object manager.
+ *
+ * This method can be used if you wish to close an object manager manually, without opening a new one.
+ * This can be useful if you wish to open a new manager later (but maybe with different settings).
+ *
+ * @param string|null $name The object manager name (null for the default one).
+ */
+ public function purgeManager($name = null)
+ {
+ $name = $name ?: $this->getDefaultManagerName();
+ $this->closeManager($name);
+
+ unset($this->managers[$name]);
+ unset($this->connections[$name]);
+ }
+ /**
+ * Resets a named object manager.
+ * This method is useful when an object manager has been closed
+ * because of a rollbacked transaction AND when you think that
+ * it makes sense to get a new one to replace the closed one.
+ * Be warned that you will get a brand new object manager as
+ * the existing one is not useable anymore. This means that any
+ * other object with a dependency on this object manager will
+ * hold an obsolete reference. You can inject the registry instead
+ * to avoid this problem.
+ *
+ * @param string|null $name The object manager name (null for the default one).
+ *
+ * @return \Doctrine\Common\Persistence\ObjectManager
+ */
+ public function resetManager($name = null)
+ {
+ $this->closeManager($name);
return $this->getManager($name);
}
diff --git a/tests/IlluminateRegistryTest.php b/tests/IlluminateRegistryTest.php
index <HASH>..<HASH> 100644
--- a/tests/IlluminateRegistryTest.php
+++ b/tests/IlluminateRegistryTest.php
@@ -271,6 +271,20 @@ class IlluminateRegistryTest extends PHPUnit_Framework_TestCase
$this->assertContains('manager2', $managers);
}
+ public function test_can_purge_default_manager()
+ {
+ $this->container->shouldReceive('singleton');
+ $this->registry->addManager('default');
+
+ $this->container->shouldReceive('forgetInstance', 'doctrine.managers.default');
+ $this->container->shouldReceive('make')
+ ->with('doctrine.managers.default')
+ ->andReturn(m::mock(\Doctrine\Common\Persistence\ObjectManager::class));
+
+ $this->registry->purgeManager();
+ $this->assertFalse($this->registry->managerExists('default'));
+ }
+
public function test_can_reset_default_manager()
{
$this->container->shouldReceive('singleton');
@@ -287,6 +301,20 @@ class IlluminateRegistryTest extends PHPUnit_Framework_TestCase
$this->assertSame($manager, $this->registry->getManager());
}
+ public function test_can_purge_custom_manager()
+ {
+ $this->container->shouldReceive('singleton');
+ $this->registry->addManager('custom');
+
+ $this->container->shouldReceive('forgetInstance', 'doctrine.managers.custom');
+ $this->container->shouldReceive('make')
+ ->with('doctrine.managers.custom')
+ ->andReturn(m::mock(\Doctrine\Common\Persistence\ObjectManager::class));
+
+ $this->registry->purgeManager();
+ $this->assertFalse($this->registry->managerExists('custom'));
+ }
+
public function test_can_reset_custom_manager()
{
$this->container->shouldReceive('singleton');
@@ -303,6 +331,16 @@ class IlluminateRegistryTest extends PHPUnit_Framework_TestCase
$this->assertSame($manager, $this->registry->getManager('custom'));
}
+ public function test_cannot_purge_non_existing_managers()
+ {
+ $this->setExpectedException(
+ InvalidArgumentException::class,
+ 'Doctrine Manager named "non-existing" does not exist.'
+ );
+
+ $this->registry->purgeManager('non-existing');
+ }
+
public function test_cannot_reset_non_existing_managers()
{
$this->setExpectedException( | [FEATURE] Added closeManager() and purgeManager() to IlluminateRegistry (#<I>)
* Added closeManager() and purgeManager() functions
* Added tests for purgeManager function() | laravel-doctrine_orm | train |
c8a68279c2043d7b3d3789a881826d52074af04e | diff --git a/juju/model.py b/juju/model.py
index <HASH>..<HASH> 100644
--- a/juju/model.py
+++ b/juju/model.py
@@ -230,7 +230,14 @@ class ModelEntity(object):
model.
"""
- return self.safe_data[name]
+ try:
+ return self.safe_data[name]
+ except KeyError:
+ name = name.replace('_', '-')
+ if name in self.safe_data:
+ return self.safe_data[name]
+ else:
+ raise
def __bool__(self):
return bool(self.data) | Allow underscore to dash translation when accessing model attributes (#<I>) | juju_python-libjuju | train |
6e72a3b9d71f450af72cca15b7e8eed5729bcb90 | diff --git a/src/cqparts/display/web.py b/src/cqparts/display/web.py
index <HASH>..<HASH> 100644
--- a/src/cqparts/display/web.py
+++ b/src/cqparts/display/web.py
@@ -43,9 +43,13 @@ SocketServer.TCPServer.allow_reuse_address = True # stops crash on re-use of po
@map_environment(
- name='web',
+ # named 'cmdline'?
+ # This is a fallback display environment if no other method is available.
+ # Therefore it's assumed that the environment that's been detected is a
+ # no-frills command line.
+ name='cmdline',
order=99,
- condition=lambda: True,
+ condition=lambda: True, # fallback
)
class WebDisplayEnv(DisplayEnvironment):
""" | changed 'web' to 'cmdline' for clairty | cqparts_cqparts | train |
196042fbbe2ed6092dba5246c08ad27cb1389f09 | diff --git a/lib/ransack/nodes/grouping.rb b/lib/ransack/nodes/grouping.rb
index <HASH>..<HASH> 100644
--- a/lib/ransack/nodes/grouping.rb
+++ b/lib/ransack/nodes/grouping.rb
@@ -161,7 +161,7 @@ module Ransack
end
def inspect
- data = [[CONDITIONS, conditions], [COMBINATOR, combinator]]
+ data = [['conditions'.freeze, conditions], [COMBINATOR, combinator]]
.reject { |e| e[1].blank? }
.map { |v| "#{v[0]}: #{v[1]}" }
.join(COMMA_SPACE) | Conditions constant only used once, so not needed. | activerecord-hackery_ransack | train |
749d9790e131338bbe3f046b044287fa18c50876 | diff --git a/spec/controllers/articles_controller_spec.rb b/spec/controllers/articles_controller_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/controllers/articles_controller_spec.rb
+++ b/spec/controllers/articles_controller_spec.rb
@@ -295,7 +295,7 @@ describe ArticlesController, "redirecting" do
Factory(:redirect)
get :redirect, :from => ["foo", "bar"]
assert_response 301
- assert_redirected_to "http://test.host/someplace/else"
+ response.should redirect_to("http://test.host/someplace/else")
end
it 'should not redirect from unknown URL' do
@@ -313,14 +313,14 @@ describe ArticlesController, "redirecting" do
Factory(:redirect, :from_path => 'foo/bar')
get :redirect, :from => ["foo", "bar"]
assert_response 301
- assert_redirected_to "http://test.host/blog/someplace/else"
+ response.should redirect_to("http://test.host/blog/someplace/else")
end
it 'should redirect if to_path includes relative_url_root' do
Factory(:redirect, :from_path => 'bar/foo', :to_path => '/blog/someplace/else')
get :redirect, :from => ["bar", "foo"]
assert_response 301
- assert_redirected_to "http://test.host/blog/someplace/else"
+ response.should redirect_to("http://test.host/blog/someplace/else")
end
end
end
@@ -334,7 +334,7 @@ describe ArticlesController, "redirecting" do
it 'should redirect to article' do
get :redirect, :from => ["articles", "2004", "04", "01", "second-blog-article"]
assert_response 301
- assert_redirected_to "http://myblog.net/2004/04/01/second-blog-article"
+ response.should redirect_to("http://myblog.net/2004/04/01/second-blog-article")
end
it 'should redirect to article with url_root' do
@@ -343,7 +343,7 @@ describe ArticlesController, "redirecting" do
b.save
get :redirect, :from => ["articles", "2004", "04", "01", "second-blog-article"]
assert_response 301
- assert_redirected_to "http://test.host/blog/2004/04/01/second-blog-article"
+ response.should redirect_to("http://test.host/blog/2004/04/01/second-blog-article")
end
it 'should redirect to article when url_root is articles' do
@@ -352,7 +352,7 @@ describe ArticlesController, "redirecting" do
b.save
get :redirect, :from => ["articles", "2004", "04", "01", "second-blog-article"]
assert_response 301
- assert_redirected_to "http://test.host/articles/2004/04/01/second-blog-article"
+ response.should redirect_to("http://test.host/articles/2004/04/01/second-blog-article")
end
it 'should redirect to article with articles in url_root' do
@@ -362,7 +362,7 @@ describe ArticlesController, "redirecting" do
get :redirect, :from => ["articles", "2004", "04", "01", "second-blog-article"]
assert_response 301
- assert_redirected_to "http://test.host/aaa/articles/bbb/2004/04/01/second-blog-article"
+ response.should redirect_to("http://test.host/aaa/articles/bbb/2004/04/01/second-blog-article")
end
end
@@ -378,13 +378,13 @@ describe ArticlesController, "redirecting" do
it 'should redirect from default URL format' do
get :redirect, :from => ["2004", "04", "01", "second-blog-article"]
assert_response 301
- assert_redirected_to "http://myblog.net/second-blog-article.html"
+ response.should redirect_to("http://myblog.net/second-blog-article.html")
end
it 'should redirect from old-style URL format with "articles" part' do
get :redirect, :from => ["articles", "2004", "04", "01", "second-blog-article"]
assert_response 301
- assert_redirected_to "http://myblog.net/second-blog-article.html"
+ response.should redirect_to("http://myblog.net/second-blog-article.html")
end
describe 'render article' do | Replace assert_redirected_to with response.should redirect_to. | publify_publify | train |
211f60617ad33876ece1ec65c51ef80f5be6dae0 | diff --git a/libgit/repo.go b/libgit/repo.go
index <HASH>..<HASH> 100644
--- a/libgit/repo.go
+++ b/libgit/repo.go
@@ -30,7 +30,7 @@ const (
// internal reason to be so restrictive, but it probably makes sense
// to start off more restrictive and then relax things later as we
// test.
-var repoNameRE = regexp.MustCompile(`^([a-zA-Z0-9][a-zA-Z0-9_.-]+)$`)
+var repoNameRE = regexp.MustCompile(`^([a-zA-Z0-9][a-zA-Z0-9_\.-]*)$`)
func checkValidRepoName(repoName string, config libkbfs.Config) bool {
return len(repoName) >= 1 &&
diff --git a/libgit/repo_test.go b/libgit/repo_test.go
index <HASH>..<HASH> 100644
--- a/libgit/repo_test.go
+++ b/libgit/repo_test.go
@@ -61,6 +61,10 @@ func TestRepo(t *testing.T) {
require.NoError(t, err)
require.Equal(t, id1, id3)
+ // A one letter repo name is ok.
+ _, _, err = GetOrCreateRepoAndID(ctx, config, h, "r", "")
+ require.NoError(t, err)
+
// Invalid names.
_, _, err = GetOrCreateRepoAndID(ctx, config, h, ".repo2", "")
require.NotNil(t, err) | libgit: fix repo name regex
Suggested by songgao.
Issue: #<I> | keybase_client | train |
e9f36b3617ebc2ce8aac43ec93b10e0b6bdabaff | diff --git a/pygal/_compat.py b/pygal/_compat.py
index <HASH>..<HASH> 100644
--- a/pygal/_compat.py
+++ b/pygal/_compat.py
@@ -17,7 +17,7 @@
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
import sys
-
+from collections import Iterable
if sys.version_info[0] == 3:
base = (str, bytes)
@@ -27,8 +27,16 @@ else:
coerce = unicode
+def is_list_like(value):
+ return isinstance(value, Iterable) and not isinstance(value, (base, dict))
+
+
+def is_str(string):
+ return isinstance(string, base)
+
+
def to_str(string):
- if not isinstance(string, base):
+ if not is_str(string):
return coerce(string)
return string
diff --git a/pygal/ghost.py b/pygal/ghost.py
index <HASH>..<HASH> 100644
--- a/pygal/ghost.py
+++ b/pygal/ghost.py
@@ -27,7 +27,7 @@ from __future__ import division
import io
import sys
from pygal.config import Config
-from pygal._compat import u
+from pygal._compat import u, is_list_like
from pygal.graph import CHARTS_NAMES
from pygal.util import prepare_values
from uuid import uuid4
@@ -63,7 +63,7 @@ class Ghost(object):
def add(self, title, values, secondary=False):
"""Add a serie to this graph"""
- if not hasattr(values, '__iter__') and not isinstance(values, dict):
+ if not is_list_like(values):
values = [values]
if secondary:
self.raw_series2.append((title, values))
diff --git a/pygal/util.py b/pygal/util.py
index <HASH>..<HASH> 100644
--- a/pygal/util.py
+++ b/pygal/util.py
@@ -21,7 +21,7 @@ Various utils
"""
from __future__ import division
-from pygal._compat import to_str, u
+from pygal._compat import to_str, u, is_list_like
import re
from decimal import Decimal
from math import floor, pi, log, log10, ceil
@@ -355,13 +355,13 @@ def prepare_values(raw, config, cls):
if issubclass(cls, Histogram):
if value is None:
value = (None, None, None)
- elif not hasattr(value, '__iter__'):
+ elif not is_list_like(value):
value = (value, config.zero, config.zero)
value = list(map(adapter, value))
elif cls._dual:
if value is None:
value = (None, None)
- elif not hasattr(value, '__iter__'):
+ elif not is_list_like(value):
value = (value, config.zero)
if issubclass(cls, DateY) or issubclass(cls, Worldmap):
value = (adapter(value[0]), value[1])
@@ -369,7 +369,6 @@ def prepare_values(raw, config, cls):
value = list(map(adapter, value))
else:
value = adapter(value)
-
values.append(value)
series.append(Serie(title, values, metadata))
return series | Change list like check (which did not worked in python 3) | Kozea_pygal | train |
0cd69fca2cbfa677601826828f76b21caea1f2cc | diff --git a/packages/react-router-website/modules/components/WebExample.js b/packages/react-router-website/modules/components/WebExample.js
index <HASH>..<HASH> 100644
--- a/packages/react-router-website/modules/components/WebExample.js
+++ b/packages/react-router-website/modules/components/WebExample.js
@@ -1,6 +1,7 @@
import React, { PropTypes } from 'react'
import Media from 'react-media'
import { Block } from 'jsxstyle'
+import { Route } from 'react-router-dom'
import Bundle from './Bundle'
import FakeBrowser from './FakeBrowser'
import SourceViewer from './SourceViewer'
@@ -18,17 +19,19 @@ const WebExample = ({ example }) => (
background="rgb(45, 45, 45)"
padding="40px"
>
- <FakeBrowser
- key={location.key /*force new instance*/}
- position={largeScreen ? 'fixed' : 'static'}
- width={largeScreen ? '400px' : 'auto'}
- height={largeScreen ? 'auto' : '70vh'}
- left="290px"
- top="40px"
- bottom="40px"
- >
- <Example/>
- </FakeBrowser>
+ <Route render={({ location }) => (
+ <FakeBrowser
+ key={location.key /*force new instance*/}
+ position={largeScreen ? 'fixed' : 'static'}
+ width={largeScreen ? '400px' : 'auto'}
+ height={largeScreen ? 'auto' : '70vh'}
+ left="290px"
+ top="40px"
+ bottom="40px"
+ >
+ <Example/>
+ </FakeBrowser>
+ )}/>
<SourceViewer
code={src}
fontSize="11px" | Provide location object to <FakeBrowser> (#<I>) | ReactTraining_react-router | train |
f97c049bcc212750bbaa1730d7d1fdff9123ca0f | diff --git a/bundles/org.eclipse.orion.client.core/static/js/globalCommands.js b/bundles/org.eclipse.orion.client.core/static/js/globalCommands.js
index <HASH>..<HASH> 100644
--- a/bundles/org.eclipse.orion.client.core/static/js/globalCommands.js
+++ b/bundles/org.eclipse.orion.client.core/static/js/globalCommands.js
@@ -19,7 +19,7 @@ var eclipse = eclipse || {};
// begin HTML fragment for top area.
var topHTMLFragment =
-'<table style="border-spacing: 0px; width: 100%; height: 61px">' + // a table?!!? Couldn't get bottom bar to float right and pin to bottom while also spanning entire page. Can't mix floats and absolutes.
+'<table style="border-spacing: 0px; border-collapse: collapse; width: 100%; height: 61px">' + // a table?!!? Couldn't get bottom bar to float right and pin to bottom while also spanning entire page. Can't mix floats and absolutes.
'<tr class="topRowBanner">' +
'<td width=93px rowspan=2><a id="home" href="/navigate-table.html"><img class="toolbarLabel" src="/images/headerlogo.gif" alt="Orion Logo" align="top"></a></td>' +
'<td class="leftGlobalToolbar">' +
@@ -27,14 +27,14 @@ var topHTMLFragment =
'<span id="pageTitle" class="statuspane"></span>' +
'<span class="bannerSeparator"> </span>' + // empty space between title and status
'<span class="statuspane" id="statusPane"></span>' +
- '</td>' +
+ '</td>' +
'<td class="rightGlobalToolbar">' +
'<span id="primaryNav"></span>' +
'<span id="globalActions"></span>' +
'<input type="search" id="search" class="searchbox">' +
'<span class="bannerSeparator">|</span>' +
'<span id="userInfo" class="statuspane"></span>' +
- '</td>' +
+ '</td>' +
'</tr>' +
'<tr class="bottomRowBanner">' +
'<td colspan=2 id="pageToolbar" class="pageToolbar">' + | set border collapse (no observed improvement) | eclipse_orion.client | train |
be07ede6bb0f7f4944d17b1ef07933807d64d9f2 | diff --git a/.travis.yml b/.travis.yml
index <HASH>..<HASH> 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,6 +1,6 @@
dist: trusty
language: go
-go_import_path: github.com/coreos/gofail
+go_import_path: github.com/etcd-io/gofail
sudo: false
go:
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# gofail
-[](https://travis-ci.org/coreos/gofail)
+[](https://travis-ci.org/etcd-io/gofail)
An implementation of [failpoints][failpoint] for golang.
@@ -101,7 +101,7 @@ From a unit test,
import (
"testing"
- gofail "github.com/coreos/gofail/runtime"
+ gofail "github.com/etcd-io/gofail/runtime"
)
func TestWhatever(t *testing.T) {
diff --git a/code/binding.go b/code/binding.go
index <HASH>..<HASH> 100644
--- a/code/binding.go
+++ b/code/binding.go
@@ -33,7 +33,7 @@ func NewBinding(pkg string, fppath string, fps []*Failpoint) *Binding {
func (b *Binding) Write(dst io.Writer) error {
hdr := "// GENERATED BY GOFAIL. DO NOT EDIT.\n\n" +
"package " + b.pkg +
- "\n\nimport \"github.com/coreos/gofail/runtime\"\n\n"
+ "\n\nimport \"github.com/etcd-io/gofail/runtime\"\n\n"
if _, err := fmt.Fprint(dst, hdr); err != nil {
return err
}
diff --git a/examples/cmd/cmd.go b/examples/cmd/cmd.go
index <HASH>..<HASH> 100644
--- a/examples/cmd/cmd.go
+++ b/examples/cmd/cmd.go
@@ -18,7 +18,7 @@ import (
"log"
"time"
- "github.com/coreos/gofail/examples"
+ "github.com/etcd-io/gofail/examples"
)
func main() {
diff --git a/gofail.go b/gofail.go
index <HASH>..<HASH> 100644
--- a/gofail.go
+++ b/gofail.go
@@ -24,7 +24,7 @@ import (
"path/filepath"
"strings"
- "github.com/coreos/gofail/code"
+ "github.com/etcd-io/gofail/code"
)
type xfrmFunc func(io.Writer, io.Reader) ([]*code.Failpoint, error) | *: update import paths to "etcd-io" | etcd-io_gofail | train |
ab33ef8f6ba312039617ef15ebf4f3da86593442 | diff --git a/eZ/Publish/API/Repository/Tests/UserServiceTest.php b/eZ/Publish/API/Repository/Tests/UserServiceTest.php
index <HASH>..<HASH> 100644
--- a/eZ/Publish/API/Repository/Tests/UserServiceTest.php
+++ b/eZ/Publish/API/Repository/Tests/UserServiceTest.php
@@ -1160,7 +1160,7 @@ class UserServiceTest extends BaseTest
// This call will fail with a "NotFoundException", because the given
// login/password combination does not exist.
- $userService->loadUserByCredentials('USER', 'secret');
+ $userService->loadUserByCredentials('üser', 'secret');
/* END: Use Case */
}
@@ -1245,6 +1245,42 @@ class UserServiceTest extends BaseTest
}
/**
+ * Test for the loadUserByLogin() method.
+ *
+ * @see \eZ\Publish\API\Repository\UserService::loadUserByLogin()
+ * @depends eZ\Publish\API\Repository\Tests\UserServiceTest::testLoadUserByLogin
+ */
+ public function testLoadUserByLoginWorksForLoginWithWrongCase()
+ {
+ $repository = $this->getRepository();
+
+ $userService = $repository->getUserService();
+
+ /* BEGIN: Use Case */
+ $user = $this->createUserVersion1();
+
+ // Lookup by user login should ignore casing
+ $userReloaded = $userService->loadUserByLogin('USER');
+ /* END: Use Case */
+
+ $this->assertPropertiesCorrect(
+ array(
+ 'login' => $user->login,
+ 'email' => $user->email,
+ 'passwordHash' => $user->passwordHash,
+ 'hashAlgorithm' => $user->hashAlgorithm,
+ 'enabled' => $user->enabled,
+ 'maxLogin' => $user->maxLogin,
+ 'id' => $user->id,
+ 'contentInfo' => $user->contentInfo,
+ 'versionInfo' => $user->versionInfo,
+ 'fields' => $user->fields,
+ ),
+ $userReloaded
+ );
+ }
+
+ /**
* Test for the loadUsersByEmail() method.
*
* @see \eZ\Publish\API\Repository\UserService::loadUsersByEmail() | [TEST] Add integration test for login case insensitivity | ezsystems_ezpublish-kernel | train |
df05b844f6d2751457897a28e5c915281b4b3ce8 | diff --git a/enrol/guest/lib.php b/enrol/guest/lib.php
index <HASH>..<HASH> 100644
--- a/enrol/guest/lib.php
+++ b/enrol/guest/lib.php
@@ -328,6 +328,22 @@ class enrol_guest_plugin extends enrol_plugin {
}
/**
+ * Add new instance of enrol plugin.
+ * @param object $course
+ * @param array instance fields
+ * @return int id of new instance, null if can not be created
+ */
+ public function add_instance($course, array $fields = NULL) {
+ $fields = (array)$fields;
+
+ if (!isset($fields['password'])) {
+ $fields['password'] = '';
+ }
+
+ return parent::add_instance($course, $fields);
+ }
+
+ /**
* Add new instance of enrol plugin with default settings.
* @param object $course
* @return int id of new instance | MDL-<I> make sure guest password field is not null | moodle_moodle | train |
b5c9650b5aec44cd7f2fb5c80cf16bd416ca0556 | diff --git a/server/driver.go b/server/driver.go
index <HASH>..<HASH> 100644
--- a/server/driver.go
+++ b/server/driver.go
@@ -61,10 +61,10 @@ type QueryCtx interface {
SetClientCapability(uint32)
// Prepare prepares a statement.
- Prepare(sql string) (statement IStatement, columns, params []*ColumnInfo, err error)
+ Prepare(sql string) (statement PreparedStatement, columns, params []*ColumnInfo, err error)
- // GetStatement gets IStatement by statement ID.
- GetStatement(stmtID int) IStatement
+ // GetStatement gets PreparedStatement by statement ID.
+ GetStatement(stmtID int) PreparedStatement
// FieldList returns columns of a table.
FieldList(tableName string) (columns []*ColumnInfo, err error)
@@ -76,8 +76,8 @@ type QueryCtx interface {
Auth(user string, auth []byte, salt []byte) bool
}
-// IStatement is the interface to use a prepared statement.
-type IStatement interface {
+// PreparedStatement is the interface to use a prepared statement.
+type PreparedStatement interface {
// ID returns statement ID
ID() int
diff --git a/server/driver_tidb.go b/server/driver_tidb.go
index <HASH>..<HASH> 100644
--- a/server/driver_tidb.go
+++ b/server/driver_tidb.go
@@ -45,7 +45,7 @@ type TiDBContext struct {
stmts map[int]*TiDBStatement
}
-// TiDBStatement implements IStatement.
+// TiDBStatement implements PreparedStatement.
type TiDBStatement struct {
id uint32
numParams int
@@ -54,12 +54,12 @@ type TiDBStatement struct {
ctx *TiDBContext
}
-// ID implements IStatement ID method.
+// ID implements PreparedStatement ID method.
func (ts *TiDBStatement) ID() int {
return int(ts.id)
}
-// Execute implements IStatement Execute method.
+// Execute implements PreparedStatement Execute method.
func (ts *TiDBStatement) Execute(args ...interface{}) (rs ResultSet, err error) {
tidbRecordset, err := ts.ctx.session.ExecutePreparedStmt(ts.id, args...)
if err != nil {
@@ -74,7 +74,7 @@ func (ts *TiDBStatement) Execute(args ...interface{}) (rs ResultSet, err error)
return
}
-// AppendParam implements IStatement AppendParam method.
+// AppendParam implements PreparedStatement AppendParam method.
func (ts *TiDBStatement) AppendParam(paramID int, data []byte) error {
if paramID >= len(ts.boundParams) {
return mysql.NewErr(mysql.ErrWrongArguments, "stmt_send_longdata")
@@ -83,34 +83,34 @@ func (ts *TiDBStatement) AppendParam(paramID int, data []byte) error {
return nil
}
-// NumParams implements IStatement NumParams method.
+// NumParams implements PreparedStatement NumParams method.
func (ts *TiDBStatement) NumParams() int {
return ts.numParams
}
-// BoundParams implements IStatement BoundParams method.
+// BoundParams implements PreparedStatement BoundParams method.
func (ts *TiDBStatement) BoundParams() [][]byte {
return ts.boundParams
}
-// SetParamsType implements IStatement SetParamsType method.
+// SetParamsType implements PreparedStatement SetParamsType method.
func (ts *TiDBStatement) SetParamsType(paramsType []byte) {
ts.paramsType = paramsType
}
-// GetParamsType implements IStatement GetParamsType method.
+// GetParamsType implements PreparedStatement GetParamsType method.
func (ts *TiDBStatement) GetParamsType() []byte {
return ts.paramsType
}
-// Reset implements IStatement Reset method.
+// Reset implements PreparedStatement Reset method.
func (ts *TiDBStatement) Reset() {
for i := range ts.boundParams {
ts.boundParams[i] = nil
}
}
-// Close implements IStatement Close method.
+// Close implements PreparedStatement Close method.
func (ts *TiDBStatement) Close() error {
//TODO close at tidb level
err := ts.ctx.session.DropPreparedStmt(ts.id)
@@ -235,7 +235,7 @@ func (tc *TiDBContext) FieldList(table string) (colums []*ColumnInfo, err error)
}
// GetStatement implements QueryCtx GetStatement method.
-func (tc *TiDBContext) GetStatement(stmtID int) IStatement {
+func (tc *TiDBContext) GetStatement(stmtID int) PreparedStatement {
tcStmt := tc.stmts[stmtID]
if tcStmt != nil {
return tcStmt
@@ -244,7 +244,7 @@ func (tc *TiDBContext) GetStatement(stmtID int) IStatement {
}
// Prepare implements QueryCtx Prepare method.
-func (tc *TiDBContext) Prepare(sql string) (statement IStatement, columns, params []*ColumnInfo, err error) {
+func (tc *TiDBContext) Prepare(sql string) (statement PreparedStatement, columns, params []*ColumnInfo, err error) {
stmtID, paramCount, fields, err := tc.session.PrepareStmt(sql)
if err != nil {
return | server: rename IStatement to PreparedStatement (#<I>) | pingcap_tidb | train |
f57c624262f34ba0a659576b784ec19667a296eb | diff --git a/question/type/random/questiontype.php b/question/type/random/questiontype.php
index <HASH>..<HASH> 100644
--- a/question/type/random/questiontype.php
+++ b/question/type/random/questiontype.php
@@ -134,7 +134,7 @@ class random_qtype extends default_questiontype {
$wrappedquestion = clone($question);
$wrappedquestion->id = $answerregs[1];
$wrappedquestion->questiontext = get_string('questiondeleted', 'quiz');
- $wrappedquestion->qtype = 'description';
+ $wrappedquestion->qtype = 'missingtype';
}
$state->responses[''] = (false === $answerregs[2]) ? '' : $answerregs[2];
} | Use the missingtype question type to print the explanation message when a random question is missing | moodle_moodle | train |
f870762e2d71d220f7075b58e3d22daa62140f1e | diff --git a/themes/colors/header.php b/themes/colors/header.php
index <HASH>..<HASH> 100644
--- a/themes/colors/header.php
+++ b/themes/colors/header.php
@@ -147,8 +147,4 @@ if ($view!='simple') { // Use "simple" headers for popup windows
echo '</div>'; // <div id="flash-messages">
}
-// Remove label from menus with no submenus. This is a contentious issue, as
-// some feel that icons without labels are confusing.
-$this->addInlineJavascript('jQuery("#main-menu > li > ul").each(function(){if (jQuery(this).children().size()==1){jQuery(this).remove()};});');
-
echo $javascript, '<div id="content">';
diff --git a/themes/colors/theme.php b/themes/colors/theme.php
index <HASH>..<HASH> 100644
--- a/themes/colors/theme.php
+++ b/themes/colors/theme.php
@@ -30,13 +30,15 @@ if (!defined('WT_WEBTREES')) {
}
// Convert a menu into our theme-specific format
function getMenuAsCustomList($menu) {
- // Create a inert menu - to use as a label
- $tmp=new WT_Menu(strip_tags($menu->label), '');
- // Insert the label into the submenu
- if ($menu->submenus) {
- array_unshift($menu->submenus, $tmp);
- } else {
- $menu->addSubmenu($tmp);
+ // Insert the label into the submenu, except for menus with only one item.
+ if (count($menu->submenus)>1) {
+ // Create a inert menu - to use as a label
+ $tmp=new WT_Menu(strip_tags($menu->label), '');
+ if ($menu->submenus) {
+ array_unshift($menu->submenus, $tmp);
+ } else {
+ $menu->addSubmenu($tmp);
+ }
}
// Neutralise the top-level menu
$menu->label=''; | Better solution for "Replace hard-coded list of menus with generic code." | fisharebest_webtrees | train |
7efe28dd39018e0a61f46754bf7c618822306f8e | diff --git a/neomodel/util.py b/neomodel/util.py
index <HASH>..<HASH> 100644
--- a/neomodel/util.py
+++ b/neomodel/util.py
@@ -97,7 +97,7 @@ class Database(local):
u = urlparse(_url)
if u.netloc.find('@') > -1:
- credentials, self.host = u.netloc.split('@')
+ credentials, self.host = u.netloc.rsplit('@')
self.user, self.password, = credentials.split(':')
self.url = ''.join([u.scheme, '://', self.host, u.path, u.query])
neo4j.authenticate(self.host, self.user, self.password) | rsplit on @ char, this allows passing passwords that contain the char "@" otherwise the split is done in the wrong place | neo4j-contrib_neomodel | train |
e06759ccccf11730b6a1af130c13895ce4653bb3 | diff --git a/lib/preprocessor.lib.php b/lib/preprocessor.lib.php
index <HASH>..<HASH> 100644
--- a/lib/preprocessor.lib.php
+++ b/lib/preprocessor.lib.php
@@ -254,7 +254,7 @@ class jPreProcessor{
}elseif(preg_match('/^\#include(php)?\s+([\w\/\.\:]+)\s*$/m',$sline,$m)){
if($isOpen){
$path = $m[2];
- if(!($path{0} == '/' || preg_match('/^\w\:\\.+$/',$path))){
+ if(!($path[0] == '/' || preg_match('/^\w\:\\.+$/',$path))){
$path = realpath(dirname($filename).'/'.$path);
if($path == ''){
throw new jExceptionPreProc($filename,$nb,self::ERR_INVALID_FILENAME, $m[2]);
@@ -281,8 +281,8 @@ class jPreProcessor{
}else{
$tline=false;
}
- }elseif(strlen($sline) && $sline{0} == '#'){
- if(strlen($sline)>1 && $sline{1} == '#'){
+ }elseif(strlen($sline) && $sline[0] == '#'){
+ if(strlen($sline)>1 && $sline[1] == '#'){
if(!$isOpen){
$tline=false;
}else{ | worked on ticket #<I>: better compatibility with PHP <I>: replaced braces by square brackets in instruction which get characters of string. trunk<I>.x | jelix_BuildTools | train |
7556d290eee9b1cd414629c218ba5a8072c03065 | diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py
index <HASH>..<HASH> 100644
--- a/pandas/tests/reshape/merge/test_merge.py
+++ b/pandas/tests/reshape/merge/test_merge.py
@@ -1813,6 +1813,35 @@ class TestMergeCategorical:
)
tm.assert_frame_equal(result, expected)
+ @pytest.mark.parametrize("ordered", [True, False])
+ def test_multiindex_merge_with_unordered_categoricalindex(self, ordered):
+ # GH 36973
+ pcat = CategoricalDtype(categories=["P2", "P1"], ordered=ordered)
+ df1 = DataFrame(
+ {
+ "id": ["C", "C", "D"],
+ "p": Categorical(["P2", "P1", "P2"], dtype=pcat),
+ "a": [0, 1, 2],
+ }
+ ).set_index(["id", "p"])
+ df2 = DataFrame(
+ {
+ "id": ["A", "C", "C"],
+ "p": Categorical(["P2", "P2", "P1"], dtype=pcat),
+ "d1": [10, 11, 12],
+ }
+ ).set_index(["id", "p"])
+ result = merge(df1, df2, how="left", left_index=True, right_index=True)
+ expected = DataFrame(
+ {
+ "id": ["C", "C", "D"],
+ "p": Categorical(["P2", "P1", "P2"], dtype=pcat),
+ "a": [0, 1, 2],
+ "d1": [11.0, 12.0, np.nan],
+ }
+ ).set_index(["id", "p"])
+ tm.assert_frame_equal(result, expected)
+
def test_other_columns(self, left, right):
# non-merge columns should preserve if possible
right = right.assign(Z=right.Z.astype("category")) | TST: Test for MultiIndex merge with CategoricalIndex (#<I>) (#<I>) | pandas-dev_pandas | train |
28462cab25c13ece7bf82bf65caa1a98d30e1c1f | diff --git a/src/ORM/Table.php b/src/ORM/Table.php
index <HASH>..<HASH> 100644
--- a/src/ORM/Table.php
+++ b/src/ORM/Table.php
@@ -1961,11 +1961,15 @@ class Table implements RepositoryInterface, EventListenerInterface
* the data to be validated.
*
* @param mixed $value The value of column to be checked for uniqueness
- * @param array $options The options array, optionally containing the 'scope' key
+ * @param array $context Either the options or validation context.
+ * @param array|null $options The options array, optionally containing the 'scope' key
* @return bool true if the value is unique
*/
- public function validateUnique($value, array $options)
+ public function validateUnique($value, array $context, array $options = null)
{
+ if ($options === null) {
+ $options = $context;
+ }
$entity = new Entity(
$options['data'],
['useSetters' => false, 'markNew' => $options['newRecord']]
diff --git a/tests/TestCase/ORM/TableTest.php b/tests/TestCase/ORM/TableTest.php
index <HASH>..<HASH> 100644
--- a/tests/TestCase/ORM/TableTest.php
+++ b/tests/TestCase/ORM/TableTest.php
@@ -3338,4 +3338,25 @@ class TableTest extends TestCase
$data = ['username' => 'larry'];
$this->assertNotEmpty($validator->errors($data, false));
}
+
+ /**
+ * Tests the validateUnique method with scope
+ *
+ * @return void
+ */
+ public function testValidateUniqueScope()
+ {
+ $table = TableRegistry::get('Users');
+ $validator = new Validator;
+ $validator->add('username', 'unique', [
+ 'rule' => ['validateUnique', ['scope' => 'id']],
+ 'provider' => 'table'
+ ]);
+ $validator->provider('table', $table);
+ $data = ['username' => 'larry'];
+ $this->assertNotEmpty($validator->errors($data));
+
+ $data = ['username' => 'jose'];
+ $this->assertEmpty($validator->errors($data));
+ }
} | Fix errors when validateUnique is used with scope.
Fix validateUnique() causing errors when used as a validator with
additional scope.
Fixes #<I> | cakephp_cakephp | train |
a3432e0b010ea58c8073c237ec6b58af119f0e8b | diff --git a/lib/render.js b/lib/render.js
index <HASH>..<HASH> 100644
--- a/lib/render.js
+++ b/lib/render.js
@@ -16,8 +16,9 @@ function render() {
preProcessGraph(g);
- var nodes = drawNodes(createOrSelect(svg, "nodes"), g),
- edgeLabels = drawEdgeLabels(createOrSelect(svg, "edgeLabels"), g);
+ var edgePathsGroup = createOrSelect(svg, "edgePaths"),
+ edgeLabels = drawEdgeLabels(createOrSelect(svg, "edgeLabels"), g),
+ nodes = drawNodes(createOrSelect(svg, "nodes"), g);
nodes.each(function(v) { updateDimensions(this, g.node(v)); });
edgeLabels.each(function(e) { updateDimensions(this, g.edge(e)); });
@@ -26,7 +27,7 @@ function render() {
positionNodes(nodes, g);
positionEdgeLabels(edgeLabels, g);
- drawEdgePaths(createOrSelect(svg, "edgePaths"), g);
+ drawEdgePaths(edgePathsGroup, g);
};
fn.drawNodes = function(value) { | Reorder groups to put edge paths behind nodes | dagrejs_dagre-d3 | train |
a460b778ae88477baf3e4361a1dceb3455c2ef5c | diff --git a/example/basic/multi-layer-carto.html b/example/basic/multi-layer-carto.html
index <HASH>..<HASH> 100644
--- a/example/basic/multi-layer-carto.html
+++ b/example/basic/multi-layer-carto.html
@@ -26,16 +26,16 @@
const source0 = new carto.source.Dataset('ne_10m_populated_places_simple');
const style0 = new carto.Style(`
- color: rgba(0,0,0,1)
+ color: rgba(1,0,0,0.5)
`);
const layer0 = new carto.Layer('layer0', source0, style0);
layer0.addTo(map);
-
+
const source1 = new carto.source.SQL('SELECT * FROM world_borders');
const style1 = new carto.Style();
const layer1 = new carto.Layer('layer1', source1, style1);
- layer1.addTo(map);
+ layer1.addTo(map, 'layer0');
</script>
</html>
diff --git a/src/api/integrator/mapbox-gl.js b/src/api/integrator/mapbox-gl.js
index <HASH>..<HASH> 100644
--- a/src/api/integrator/mapbox-gl.js
+++ b/src/api/integrator/mapbox-gl.js
@@ -43,7 +43,7 @@ class MGLIntegrator {
}
addLayer(layer, beforeLayerID) {
const callbackID = `_cartoGL_${uid++}`;
- this._registerMoveObserver(callbackID, layer.getData.bind(layer));
+ this._registerMoveObserver(callbackID, layer.requestData.bind(layer));
this.map.repaint = true; // FIXME: add logic to manage repaint flag
this.map.setCustomWebGLDrawCallback(layer.id, (gl, invalidate) => {
if (!this.invalidateWebGLState) {
diff --git a/src/api/layer.js b/src/api/layer.js
index <HASH>..<HASH> 100644
--- a/src/api/layer.js
+++ b/src/api/layer.js
@@ -119,7 +119,7 @@ export default class Layer {
*/
addTo(map, beforeLayerID) {
if (this._isCartoMap(map)) {
- this._addToCartoMap(map);
+ this._addToCartoMap(map, beforeLayerID);
} else if (this._isMGLMap(map)) {
this._addToMGLMap(map, beforeLayerID);
} else {
@@ -140,9 +140,9 @@ export default class Layer {
return true;
}
- _addToCartoMap(map) {
+ _addToCartoMap(map, beforeLayerID) {
this._integrator = getCMIntegrator(map);
- this._integrator.addLayer(this);
+ this._integrator.addLayer(this, beforeLayerID);
}
_addToMGLMap(map, beforeLayerID) {
@@ -156,7 +156,7 @@ export default class Layer {
if (!(this._integrator && this._integrator.invalidateWebGLState)) {
return;
}
- this.getData();
+ this.requestData();
const originalPromise = this.metadataPromise;
this.metadataPromise.then(metadata => {
// We should only compile the shaders if the metadata came from the original promise
@@ -207,7 +207,7 @@ export default class Layer {
throw new Error('?');
}
- getData() {
+ requestData() {
if (!this._integrator.invalidateWebGLState) {
return;
}
diff --git a/src/api/map.js b/src/api/map.js
index <HASH>..<HASH> 100644
--- a/src/api/map.js
+++ b/src/api/map.js
@@ -34,16 +34,24 @@ export default class Map {
this._resizeCanvas(this._containerDimensions());
}
- addLayer(layer) {
- layer.getData();
- this._layers.push(layer);
+ addLayer(layer, beforeLayerID) {
+ layer.requestData();
+
+ let index;
+ for (index = 0; index < this._layers.length; index++) {
+ if (this._layers[index].id === beforeLayerID) {
+ break;
+ }
+ }
+ this._layers.splice(index, 0, layer);
+
window.requestAnimationFrame(this.update.bind(this));
}
update() {
// Draw background
- this._gl.clearColor(0.5, 0.5, 0.5, 1.0);
- this._gl.clear(this._gl.COLOR_BUFFER_BIT);
+ // this._gl.clearColor(0.5, 0.5, 0.5, 1.0);
+ // this._gl.clear(this._gl.COLOR_BUFFER_BIT);
let loaded = true;
this._layers.forEach((layer) => {
diff --git a/test/unit/api/layer.test.js b/test/unit/api/layer.test.js
index <HASH>..<HASH> 100644
--- a/test/unit/api/layer.test.js
+++ b/test/unit/api/layer.test.js
@@ -17,7 +17,7 @@ describe('api/layer', () => {
describe('constructor', () => {
it('should build a new Layer with (id, source, style)', () => {
const layer = new Layer('layer0', source, style);
- expect(layer._id).toEqual('layer0');
+ expect(layer.id).toEqual('layer0');
expect(layer._source).toEqual(source);
expect(layer._style).toEqual(style);
}); | Add layers with beforeId in simple map | CartoDB_carto-vl | train |
bedfb828d81919b60b9bfb31975365053d371954 | diff --git a/src/ol/renderer/canvas/canvasvectorlayerrenderer.js b/src/ol/renderer/canvas/canvasvectorlayerrenderer.js
index <HASH>..<HASH> 100644
--- a/src/ol/renderer/canvas/canvasvectorlayerrenderer.js
+++ b/src/ol/renderer/canvas/canvasvectorlayerrenderer.js
@@ -164,15 +164,20 @@ ol.renderer.canvas.VectorLayer.prototype.handleImageStyleChange_ =
ol.renderer.canvas.VectorLayer.prototype.prepareFrame =
function(frameState, layerState) {
+ var vectorLayer = this.getLayer();
+ goog.asserts.assertInstanceof(vectorLayer, ol.layer.Vector);
+ var vectorSource = vectorLayer.getSource();
+ goog.asserts.assertInstanceof(vectorSource, ol.source.Vector);
+
+ this.updateAttributions(
+ frameState.attributions, vectorSource.getAttributions());
+ this.updateLogos(frameState, vectorSource);
+
if (!this.dirty_ && (frameState.viewHints[ol.ViewHint.ANIMATING] ||
frameState.viewHints[ol.ViewHint.INTERACTING])) {
return;
}
- var vectorLayer = this.getLayer();
- goog.asserts.assertInstanceof(vectorLayer, ol.layer.Vector);
- var vectorSource = vectorLayer.getSource();
- goog.asserts.assertInstanceof(vectorSource, ol.source.Vector);
var frameStateExtent = frameState.extent;
var frameStateResolution = frameState.view2DState.resolution;
var pixelRatio = frameState.devicePixelRatio; | Display attributions and logos for vector sources | openlayers_openlayers | train |
9a02d5ea89e6d9084069cdf52cdffc111ec6f220 | diff --git a/lib/punchblock/call.rb b/lib/punchblock/call.rb
index <HASH>..<HASH> 100644
--- a/lib/punchblock/call.rb
+++ b/lib/punchblock/call.rb
@@ -10,7 +10,7 @@ module Punchblock
@call_id, @to = call_id, to
# Ensure all our headers have lowercase names and convert to symbols
@headers = headers.inject({}) do |headers,pair|
- headers[pair.shift.downcase.to_sym] = pair.shift
+ headers[pair.shift.to_s.downcase.to_sym] = pair.shift
headers
end
end | Headers were not being downcased properly for a call object | adhearsion_punchblock | train |
4f1dc7ea98ae9df969139da3f4ba663a9c4fe80f | diff --git a/mod/chat/view.php b/mod/chat/view.php
index <HASH>..<HASH> 100644
--- a/mod/chat/view.php
+++ b/mod/chat/view.php
@@ -45,6 +45,29 @@
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
+ // show some info for guests
+ if (isguestuser()) {
+ $navigation = build_navigation('', $cm);
+ print_header_simple(format_string($chat->name), '', $navigation,
+ '', '', true, '', navmenu($course, $cm));
+ $wwwroot = $CFG->wwwroot.'/login/index.php';
+ if (!empty($CFG->loginhttps)) {
+ $wwwroot = str_replace('http:','https:', $wwwroot);
+ }
+
+ notice_yesno(get_string('noguests', 'chat').'<br /><br />'.get_string('liketologin'),
+ $wwwroot, $CFG->wwwroot.'/course/view.php?id='.$course->id);
+
+ print_footer($course);
+ exit;
+
+ } else {
+ $navigation = build_navigation('', $cm);
+ print_header_simple(format_string($chat->name), '', $navigation,
+ '', '', true, '', navmenu($course, $cm));
+ require_capability('mod/chat:chat', $context);
+ }
+
add_to_log($course->id, 'chat', 'view', "view.php?id=$cm->id", $chat->id, $cm->id);
// Initialize $PAGE, compute blocks
@@ -111,50 +134,31 @@
print_heading(format_string($chat->name));
/// Print the main part of the page
-
- if (has_capability('mod/chat:chat',$context)) {
- print_box_start('generalbox', 'enterlink');
- // users with screenreader set, will only see 1 link, to the manual refresh page
- // for better accessibility
- if (!empty($USER->screenreader)) {
- $chattarget = "/mod/chat/gui_basic/index.php?id=$chat->id$groupparam";
- } else {
- $chattarget = "/mod/chat/gui_$CFG->chat_method/index.php?id=$chat->id$groupparam";
- }
-
- echo '<p>';
- link_to_popup_window ($chattarget,
- "chat$course->id$chat->id$groupparam", "$strenterchat", 500, 700, get_string('modulename', 'chat'));
- echo '</p>';
-
- // if user is using screen reader, then there is no need to display this link again
- if ($CFG->chat_method == 'header_js' && empty($USER->screenreader)) {
- // show frame/js-less alternative
- echo '<p>(';
- link_to_popup_window ("/mod/chat/gui_basic/index.php?id=$chat->id$groupparam",
- "chat$course->id$chat->id$groupparam", get_string('noframesjs', 'message'), 500, 700, get_string('modulename', 'chat'));
- echo ')</p>';
- }
-
- print_box_end();
-
- } else if (isguestuser()) {
- $wwwroot = $CFG->wwwroot.'/login/index.php';
- if (!empty($CFG->loginhttps)) {
- $wwwroot = str_replace('http:','https:', $wwwroot);
- }
-
- notice_yesno(get_string('noguests', 'chat').'<br /><br />'.get_string('liketologin'),
- $wwwroot, $CFG->wwwroot.'/course/view.php?id='.$course->id);
-
- print_footer($course);
- exit;
-
+ print_box_start('generalbox', 'enterlink');
+ // users with screenreader set, will only see 1 link, to the manual refresh page
+ // for better accessibility
+ if (!empty($USER->screenreader)) {
+ $chattarget = "/mod/chat/gui_basic/index.php?id=$chat->id$groupparam";
} else {
- // show some error message
- require_capability('mod/chat:chat', $context);
+ $chattarget = "/mod/chat/gui_$CFG->chat_method/index.php?id=$chat->id$groupparam";
}
+ echo '<p>';
+ link_to_popup_window ($chattarget,
+ "chat$course->id$chat->id$groupparam", "$strenterchat", 500, 700, get_string('modulename', 'chat'));
+ echo '</p>';
+
+ // if user is using screen reader, then there is no need to display this link again
+ if ($CFG->chat_method == 'header_js' && empty($USER->screenreader)) {
+ // show frame/js-less alternative
+ echo '<p>(';
+ link_to_popup_window ("/mod/chat/gui_basic/index.php?id=$chat->id$groupparam",
+ "chat$course->id$chat->id$groupparam", get_string('noframesjs', 'message'), 500, 700, get_string('modulename', 'chat'));
+ echo ')</p>';
+ }
+
+ print_box_end();
+
if ($chat->chattime and $chat->schedule) { // A chat is scheduled
echo "<p class=\"nextchatsession\">$strnextsession: ".userdate($chat->chattime).' ('.usertimezone($USER->timezone).')</p>'; | MDL-<I> , MDL-<I> - rewritten permission tests to be xhtml strict compatible; merged from MOODLE_<I>_STABLE | moodle_moodle | train |
2074abf904a84d0c9293e15b329003ff4ae9a231 | diff --git a/src/Unirest/Request.php b/src/Unirest/Request.php
index <HASH>..<HASH> 100644
--- a/src/Unirest/Request.php
+++ b/src/Unirest/Request.php
@@ -12,7 +12,7 @@ class Request
private static $socketTimeout = null;
private static $defaultHeaders = array();
- private static $auth => array (
+ private static $auth = array (
'user' => '',
'pass' => '',
'method' => CURLAUTH_BASIC
@@ -342,7 +342,14 @@ class Request
curl_setopt($ch, CURLOPT_TIMEOUT, self::$socketTimeout);
}
- if (!empty($self::auth['user'])) {
+ // supporting deprecated http auth method
+ if (!empty($username)) {
+ curl_setopt($ch, CURLOPT_USERNAME, $username);
+ curl_setopt($ch, CURLOPT_PASSWORD, $password);
+ curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
+ }
+
+ if (!empty(self::$auth['user'])) {
curl_setopt($ch, CURLOPT_USERNAME, self::$auth['user']);
curl_setopt($ch, CURLOPT_PASSWORD, self::$auth['pass']);
curl_setopt($ch, CURLOPT_HTTPAUTH, self::$auth['method']); | keeping deprecated auth method functional | Kong_unirest-php | train |
838f2c48ad5dc13372aad1b0c5fa930778a4dc1e | diff --git a/lol_scraper/match_downloader.py b/lol_scraper/match_downloader.py
index <HASH>..<HASH> 100644
--- a/lol_scraper/match_downloader.py
+++ b/lol_scraper/match_downloader.py
@@ -37,12 +37,13 @@ def download_matches(match_downloaded_callback, end_of_time_slice_callback, conf
if end_of_time_slice_callback:
end_of_time_slice_callback(players_to_analyze, analyzed_players, matches_to_download_by_tier, downloaded_matches, total_matches, max_match_id)
- players_to_analyze = TierSeed(tiers=conf['seed_players_by_tier']._tiers)
+ players_to_analyze = TierSeed(tiers=conf['seed_players_by_tier'])
total_matches = 0
conf['maximum_downloaded_match_id'] = 0
- downloaded_matches = set()
- matches_to_download_by_tier = TierSet()
+ downloaded_matches = set(conf['downloaded_matches'])
+
+ matches_to_download_by_tier = conf['matches_to_download_by_tier']
analyzed_players = TierSeed()
try:
while (players_to_analyze or matches_to_download_by_tier) and\
@@ -54,6 +55,7 @@ def download_matches(match_downloaded_callback, end_of_time_slice_callback, conf
if conf.get('exit', False):
# Check exit condition
break
+
if conf['prints_on']:
print("{} - Starting player matchlist download for tier {}. Players in queue: {}. Downloads in queue: {}. Downloaded: {}"
.format(datetime.datetime.now().strftime("%m-%d %H:%M:%S"), tier.name, len(players_to_analyze),
@@ -70,6 +72,7 @@ def download_matches(match_downloaded_callback, end_of_time_slice_callback, conf
if conf.get('exit', False):
# Check exit condition
break
+
if conf['prints_on']:
print("{} - Starting matches download for tier {}. Players in queue: {}. Downloads in queue: {}. Downloaded: {}"
.format(datetime.datetime.now().strftime("%m-%d %H:%M:%S"), tier.name, len(players_to_analyze),
@@ -85,6 +88,7 @@ def download_matches(match_downloaded_callback, end_of_time_slice_callback, conf
conf['maximum_downloaded_match_id'] = max(match_id, conf['maximum_downloaded_match_id'])
match_downloaded_callback(match, match_min_tier.name)
total_matches += 1
+
downloaded_matches.add(match_id)
players_to_analyze -= analyzed_players
@@ -124,24 +128,18 @@ def prepare_config(config):
runtime_config['include_timeline'] = config.get('include_timeline', True)
runtime_config['minimum_match_id'] = config.get('minimum_match_id', 0)
- seed_players = list(summoner_names_to_id(config['seed_players']).values())
- seed_players_by_tier = TierSeed(tiers=leagues_by_summoner_ids(seed_players, Queue[runtime_config['queue']]))
- checkpoint_players = config.get('checkpoint_players', None)
+ runtime_config['downloaded_matches'] = config.get('downloaded_matches', [])
- if checkpoint_players:
- checkpoint_players_by_tier = TierSeed().from_json(checkpoint_players)
- seed_players_by_tier.update(checkpoint_players_by_tier)
- if runtime_config['prints_on']:
- print("Loaded {} players from the checkpoint".format(len(checkpoint_players_by_tier)))
+ runtime_config['matches_to_download_by_tier'] = config.get('matches_to_download_by_tier', TierSet())
- seed_players_by_tier.remove_players_below_tier(Tier.parse(runtime_config['minimum_tier']))
-
- runtime_config['seed_players_by_tier'] = seed_players_by_tier
-
- runtime_config['minimum_match_id'] = config.get('minimum_match_id', 0)
+ runtime_config['seed_players_by_tier'] = config.get('seed_players_by_tier', None)
- runtime_config['seed_players_by_tier'] = seed_players_by_tier
+ if not runtime_config['seed_players_by_tier']:
+ seed_players = list(summoner_names_to_id(config['seed_players']).values())
+ seed_players_by_tier = TierSeed(tiers=leagues_by_summoner_ids(seed_players, Queue[runtime_config['queue']]))
+ seed_players_by_tier.remove_players_below_tier(Tier.parse(runtime_config['minimum_tier']))
+ runtime_config['seed_players_by_tier'] = seed_players_by_tier._tiers
return runtime_config | Reorganized the structure of the runtime configuration | MakersF_LoLScraper | train |
a67f62b18976103866b34727a30b4308c64eda93 | diff --git a/Worker.php b/Worker.php
index <HASH>..<HASH> 100644
--- a/Worker.php
+++ b/Worker.php
@@ -34,7 +34,7 @@ class Worker
* 版本号
* @var string
*/
- const VERSION = '3.2.1';
+ const VERSION = '3.2.2';
/**
* 状态 启动中
@@ -108,6 +108,12 @@ class Worker
* @var bool
*/
public $reloadable = true;
+
+ /**
+ * reuse port
+ * @var bool
+ */
+ public $reusePort = false;
/**
* 当worker进程启动时,如果设置了$onWorkerStart回调函数,则运行
@@ -416,8 +422,12 @@ class Worker
{
self::$_maxUserNameLength = $user_name_length;
}
- // 监听端口
- $worker->listen();
+ // 如果端口不可复用,则直接在主进程就监听
+ if(!$worker->reusePort)
+ {
+ // 监听端口
+ $worker->listen();
+ }
}
}
@@ -800,6 +810,11 @@ class Worker
// 子进程运行
elseif(0 === $pid)
{
+ // 如果设置了端口复用,则在子进程执行监听
+ if($worker->reusePort)
+ {
+ $worker->listen();
+ }
// 启动过程中尝试重定向标准输出
if(self::$_status === self::STATUS_STARTING)
{
@@ -1228,13 +1243,14 @@ class Worker
*/
public function listen()
{
- // 设置自动加载根目录
- Autoloader::setRootPath($this->_appInitPath);
-
- if(!$this->_socketName)
+ if(!$this->_socketName || $this->_mainSocket)
{
return;
}
+
+ // 设置自动加载根目录
+ Autoloader::setRootPath($this->_appInitPath);
+
// 获得应用层通讯协议以及监听的地址
list($scheme, $address) = explode(':', $this->_socketName, 2);
// 如果有指定应用层协议,则检查对应的协议类是否存在
@@ -1260,6 +1276,11 @@ class Worker
$flags = $this->transport === 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
$errno = 0;
$errmsg = '';
+ // 如果设置了端口复用,则设置SO_REUSEPORT选项为1
+ if($this->reusePort)
+ {
+ stream_context_set_option($this->_context, 'socket', 'so_reuseport', 1);
+ }
$this->_mainSocket = stream_socket_server($this->transport.":".$address, $errno, $errmsg, $flags, $this->_context);
if(!$this->_mainSocket)
{ | support SO_REUSEPORT for php7 | walkor_Workerman | train |
fcef1e0ec8b3062426178d34a206af78b983b314 | diff --git a/test-common/src/test/java/de/bwaldvogel/mongo/RealMongoAggregationTest.java b/test-common/src/test/java/de/bwaldvogel/mongo/RealMongoAggregationTest.java
index <HASH>..<HASH> 100644
--- a/test-common/src/test/java/de/bwaldvogel/mongo/RealMongoAggregationTest.java
+++ b/test-common/src/test/java/de/bwaldvogel/mongo/RealMongoAggregationTest.java
@@ -1,6 +1,7 @@
package de.bwaldvogel.mongo;
-import org.junit.Assume;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
+
import org.junit.jupiter.api.extension.RegisterExtension;
import de.bwaldvogel.mongo.backend.AbstractAggregationTest;
@@ -22,7 +23,7 @@ public class RealMongoAggregationTest extends AbstractAggregationTest {
@Override
public void testAggregateWithGeoNear() throws Exception {
- Assume.assumeTrue(false);
+ assumeTrue(false);
super.testAggregateWithGeoNear();
}
} | Use assumeTrue from JUnit5 | bwaldvogel_mongo-java-server | train |
dcf7bc13d6090a31c6cb928abfc5eb8b3d5641f1 | diff --git a/ptpython/python_input.py b/ptpython/python_input.py
index <HASH>..<HASH> 100644
--- a/ptpython/python_input.py
+++ b/ptpython/python_input.py
@@ -96,7 +96,9 @@ class PythonCommandLineInterface(object):
self._extra_sidebars = _extra_sidebars or []
# Use a KeyBindingManager for loading the key bindings.
- self.key_bindings_manager = KeyBindingManager(enable_vi_mode=vi_mode, enable_system_prompt=True)
+ self.key_bindings_manager = KeyBindingManager(enable_vi_mode=vi_mode,
+ enable_open_in_editor=True,
+ enable_system_prompt=True)
load_python_bindings(self.key_bindings_manager, self.settings,
add_buffer=self.add_new_python_buffer,
close_current_buffer=self.close_current_python_buffer) | Enable open-in-editor bindings. | prompt-toolkit_ptpython | train |
83184c99da97a14da9d28cd25e197291077c7626 | diff --git a/lib/Cake/Test/Case/View/Helper/FormHelperTest.php b/lib/Cake/Test/Case/View/Helper/FormHelperTest.php
index <HASH>..<HASH> 100644
--- a/lib/Cake/Test/Case/View/Helper/FormHelperTest.php
+++ b/lib/Cake/Test/Case/View/Helper/FormHelperTest.php
@@ -1051,6 +1051,7 @@ class FormHelperTest extends CakeTestCase {
'disabledFields' => array('first_name', 'address')
);
$this->Form->create();
+ $this->assertEquals($this->Form->request['_Token']['disabledFields'], $this->Form->disableField());
$this->Form->hidden('Addresses.id', array('value' => '123456'));
$this->Form->input('Addresses.title');
@@ -1283,12 +1284,52 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertEqual($expected, $result);
}
+
+/**
+ * test disableField
+ *
+ * @return void
+ */
+ public function testDisableFieldAddsToList() {
+ $this->Form->request['_Token'] = array(
+ 'key' => 'testKey',
+ 'disabledFields' => array()
+ );
+ $this->Form->create('Contact');
+ $this->Form->disableField('Contact.name');
+ $this->Form->text('Contact.name');
+
+ $this->assertEquals(array('Contact.name'), $this->Form->disableField());
+ $this->assertEquals(array(), $this->Form->fields);
+ }
+
+/**
+ * test disableField removing from fields array.
+ *
+ * @return void
+ */
+ public function testDisableFieldRemovingFromFields() {
+ $this->Form->request['_Token'] = array(
+ 'key' => 'testKey',
+ 'disabledFields' => array()
+ );
+ $this->Form->create('Contact');
+ $this->Form->hidden('Contact.id', array('value' => 1));
+ $this->Form->text('Contact.name');
+
+ $this->assertEquals(1, $this->Form->fields['Contact.id'], 'Hidden input should be secured.');
+ $this->assertTrue(in_array('Contact.name', $this->Form->fields), 'Field should be secured.');
+
+ $this->Form->disableField('Contact.name');
+ $this->Form->disableField('Contact.id');
+ $this->assertEquals(array(), $this->Form->fields);
+ }
+
/**
* testPasswordValidation method
*
* test validation errors on password input.
*
- * @access public
* @return void
*/
public function testPasswordValidation() {
@@ -7127,4 +7168,5 @@ class FormHelperTest extends CakeTestCase {
public function testHtml5InputException() {
$this->Form->email();
}
+
}
diff --git a/lib/Cake/View/Helper/FormHelper.php b/lib/Cake/View/Helper/FormHelper.php
index <HASH>..<HASH> 100644
--- a/lib/Cake/View/Helper/FormHelper.php
+++ b/lib/Cake/View/Helper/FormHelper.php
@@ -439,6 +439,29 @@ class FormHelper extends AppHelper {
}
/**
+ * Add to or get the list of fields that are currently disabled.
+ * Disabled fields are not included in the field hash used by SecurityComponent
+ * disabling a field once its been added to the list of secured fields will remove
+ * it from the list of fields.
+ *
+ * @param string $name The dot separated name for the field.
+ * @return mixed Either null, or the list of fields.
+ */
+ public function disableField($name = null) {
+ if ($name === null) {
+ return $this->_disabledFields;
+ }
+ if (!in_array($name, $this->_disabledFields)) {
+ $this->_disabledFields[] = $name;
+ }
+ $index = array_search($name, $this->fields);
+ if ($index !== false) {
+ unset($this->fields[$index]);
+ }
+ unset($this->fields[$name]);
+ }
+
+/**
* Determine which fields of a form should be used for hash.
* Populates $this->fields
*
@@ -472,9 +495,7 @@ class FormHelper extends AppHelper {
$this->fields[] = $field;
}
} else {
- if (!in_array($field, $this->_disabledFields)) {
- $this->_disabledFields[] = $field;
- }
+ $this->disableField($field);
}
} | Adding disableField() to start allowing disabled fields to be manipulated
from the view/helper. | cakephp_cakephp | train |
c9e0e8891fe677841a48b38f4e8b3f205e072648 | diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfiguration.java
index <HASH>..<HASH> 100644
--- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfiguration.java
+++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfiguration.java
@@ -37,6 +37,7 @@ import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.rsocket.annotation.support.RSocketMessageHandler;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
+import org.springframework.security.authentication.ReactiveAuthenticationManagerResolver;
import org.springframework.security.core.userdetails.MapReactiveUserDetailsService;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
@@ -48,14 +49,17 @@ import org.springframework.util.StringUtils;
* Default user {@link Configuration @Configuration} for a reactive web application.
* Configures a {@link ReactiveUserDetailsService} with a default user and generated
* password. This backs-off completely if there is a bean of type
- * {@link ReactiveUserDetailsService} or {@link ReactiveAuthenticationManager}.
+ * {@link ReactiveUserDetailsService}, {@link ReactiveAuthenticationManager}, or
+ * {@link ReactiveAuthenticationManagerResolver}.
*
* @author Madhura Bhave
* @since 2.0.0
*/
@AutoConfiguration(after = RSocketMessagingAutoConfiguration.class)
@ConditionalOnClass({ ReactiveAuthenticationManager.class })
-@ConditionalOnMissingBean(value = { ReactiveAuthenticationManager.class, ReactiveUserDetailsService.class },
+@ConditionalOnMissingBean(
+ value = { ReactiveAuthenticationManager.class, ReactiveUserDetailsService.class,
+ ReactiveAuthenticationManagerResolver.class },
type = { "org.springframework.security.oauth2.jwt.ReactiveJwtDecoder",
"org.springframework.security.oauth2.server.resource.introspection.ReactiveOpaqueTokenIntrospector" })
@Conditional(ReactiveUserDetailsServiceAutoConfiguration.ReactiveUserDetailsServiceCondition.class)
diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfigurationTests.java
index <HASH>..<HASH> 100644
--- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfigurationTests.java
+++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfigurationTests.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2012-2019 the original author or authors.
+ * Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,6 +31,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
+import org.springframework.security.authentication.ReactiveAuthenticationManagerResolver;
import org.springframework.security.config.annotation.rsocket.EnableRSocketSecurity;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.core.userdetails.MapReactiveUserDetailsService;
@@ -92,6 +93,13 @@ class ReactiveUserDetailsServiceAutoConfigurationTests {
}
@Test
+ void doesNotConfigureDefaultUserIfAuthenticationManagerResolverAvailable() {
+ this.contextRunner.withUserConfiguration(AuthenticationManagerResolverConfig.class)
+ .run((context) -> assertThat(context).hasSingleBean(ReactiveAuthenticationManagerResolver.class)
+ .doesNotHaveBean(ReactiveUserDetailsService.class));
+ }
+
+ @Test
void doesNotConfigureDefaultUserIfResourceServerWithJWTIsUsed() {
this.contextRunner.withUserConfiguration(JwtDecoderConfiguration.class).run((context) -> {
assertThat(context).hasSingleBean(ReactiveJwtDecoder.class);
@@ -180,6 +188,16 @@ class ReactiveUserDetailsServiceAutoConfigurationTests {
}
@Configuration(proxyBeanMethods = false)
+ static class AuthenticationManagerResolverConfig {
+
+ @Bean
+ ReactiveAuthenticationManagerResolver<?> reactiveAuthenticationManagerResolver() {
+ return mock(ReactiveAuthenticationManagerResolver.class);
+ }
+
+ }
+
+ @Configuration(proxyBeanMethods = false)
@Import(TestSecurityConfiguration.class)
static class TestConfigWithPasswordEncoder { | Make reactive user details back off with Auth Manager Resolver bean
Closes gh-<I> | spring-projects_spring-boot | train |
85bb0a100dea4208acf86bd023fbbf6177dd9dbd | diff --git a/core/src/main/java/io/grpc/Contexts.java b/core/src/main/java/io/grpc/Contexts.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/io/grpc/Contexts.java
+++ b/core/src/main/java/io/grpc/Contexts.java
@@ -38,7 +38,7 @@ import java.util.concurrent.TimeoutException;
/**
* Utility methods for working with {@link Context}s in GRPC.
*/
-public class Contexts {
+public final class Contexts {
private Contexts() {
}
diff --git a/core/src/main/java/io/grpc/ResolvedServerInfoGroup.java b/core/src/main/java/io/grpc/ResolvedServerInfoGroup.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/io/grpc/ResolvedServerInfoGroup.java
+++ b/core/src/main/java/io/grpc/ResolvedServerInfoGroup.java
@@ -147,7 +147,7 @@ public final class ResolvedServerInfoGroup {
return "[servers=" + resolvedServerInfoList + ", attrs=" + attributes + "]";
}
- public static class Builder {
+ public static final class Builder {
private final List<ResolvedServerInfo> group = new ArrayList<ResolvedServerInfo>();
private final Attributes attributes;
diff --git a/core/src/main/java/io/grpc/ServerInterceptors.java b/core/src/main/java/io/grpc/ServerInterceptors.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/io/grpc/ServerInterceptors.java
+++ b/core/src/main/java/io/grpc/ServerInterceptors.java
@@ -43,7 +43,7 @@ import java.util.List;
/**
* Utility methods for working with {@link ServerInterceptor}s.
*/
-public class ServerInterceptors {
+public final class ServerInterceptors {
// Prevent instantiation
private ServerInterceptors() {} | core: make Contexts, ResolvedServerInfoGroup, and ServerInterceptors final | grpc_grpc-java | train |
c029ad48405cd90cf9a5d7ad6cdfaa646cf2605f | diff --git a/salt/states/module.py b/salt/states/module.py
index <HASH>..<HASH> 100644
--- a/salt/states/module.py
+++ b/salt/states/module.py
@@ -197,7 +197,7 @@ def run(name, **kwargs):
ret['result'] = False
return ret
else:
- if mret:
+ if mret is not None:
ret['changes']['ret'] = mret
if 'returner' in kwargs: | Make module state to save mret also if mret is false | saltstack_salt | train |
5fd5c67d4c8f8cbc1fa00aa96b2b0bf2ad73f16b | diff --git a/src/main/java/net/sf/jabb/util/stat/AtomicLongStatistics.java b/src/main/java/net/sf/jabb/util/stat/AtomicLongStatistics.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/sf/jabb/util/stat/AtomicLongStatistics.java
+++ b/src/main/java/net/sf/jabb/util/stat/AtomicLongStatistics.java
@@ -153,10 +153,8 @@ public class AtomicLongStatistics implements NumberStatistics<Long>, Serializabl
@Override
public void merge(NumberStatistics<? extends Number> other){
- if (other != null){
- if (other.getCount() > 0){
- merge(other.getCount(), other.getSum().longValue(), other.getMin().longValue(), other.getMax().longValue());
- }
+ if (other != null && other.getCount() > 0){
+ merge(other.getCount(), other.getSum().longValue(), other.getMin().longValue(), other.getMax().longValue());
}
}
diff --git a/src/main/java/net/sf/jabb/util/stat/SimpleBigIntegerStatistics.java b/src/main/java/net/sf/jabb/util/stat/SimpleBigIntegerStatistics.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/sf/jabb/util/stat/SimpleBigIntegerStatistics.java
+++ b/src/main/java/net/sf/jabb/util/stat/SimpleBigIntegerStatistics.java
@@ -44,7 +44,7 @@ public class SimpleBigIntegerStatistics implements NumberStatistics<BigInteger>,
@SuppressWarnings("unchecked")
@Override
public void merge(NumberStatistics<? extends Number> other) {
- if (other != null){
+ if (other != null && other.getCount() > 0){
if (other.getSum() instanceof BigInteger){
mergeBigInteger((NumberStatistics<? extends BigInteger>)other);
}else{
diff --git a/src/main/java/net/sf/jabb/util/stat/SimpleLongStatistics.java b/src/main/java/net/sf/jabb/util/stat/SimpleLongStatistics.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/sf/jabb/util/stat/SimpleLongStatistics.java
+++ b/src/main/java/net/sf/jabb/util/stat/SimpleLongStatistics.java
@@ -35,7 +35,7 @@ public class SimpleLongStatistics implements NumberStatistics<Long>, Serializabl
@Override
public void merge(NumberStatistics<? extends Number> other) {
- if (other != null){
+ if (other != null && other.getCount() > 0){
merge(other.getCount(), other.getSum().longValue(), other.getMin().longValue(), other.getMax().longValue());
}
} | add checking about other.getCount() > 0 | james-hu_jabb-core | train |
c367c64475b3e7e38e7b289ed410bd4730882050 | diff --git a/extensions/helper/Assets.php b/extensions/helper/Assets.php
index <HASH>..<HASH> 100644
--- a/extensions/helper/Assets.php
+++ b/extensions/helper/Assets.php
@@ -53,6 +53,18 @@ class Assets extends \lithium\template\Helper {
$base = AssetsModel::base('http');
return $base . '/v:' . $version . $path . $suffix;
}
+
+ public function urls($pattern) {
+ $fileBase = parse_url(AssetsModel::base('file'), PHP_URL_PATH);
+ $httpBase = AssetsModel::base('http');
+
+ $results = glob($fileBase . $pattern);
+
+ foreach ($results as &$result) {
+ $result = str_replace($fileBase, $httpBase, $result);
+ }
+ return $results;
+ }
}
?>
\ No newline at end of file | Adding urls globbing to assets helper. | bseries_cms_core | train |
e866dbcd1dc814816717e065574d4bee8beb2079 | diff --git a/guacamole-common-js/src/main/resources/oskeyboard.js b/guacamole-common-js/src/main/resources/oskeyboard.js
index <HASH>..<HASH> 100644
--- a/guacamole-common-js/src/main/resources/oskeyboard.js
+++ b/guacamole-common-js/src/main/resources/oskeyboard.js
@@ -55,6 +55,55 @@ Guacamole.OnScreenKeyboard = function(url) {
var modifiers = {};
var currentModifier = 1;
+ // Function for adding a class to an element
+ var addClass;
+
+ // Function for removing a class from an element
+ var removeClass;
+
+ // If Node.classList is supported, implement addClass/removeClass using that
+ if (Node.classList) {
+
+ addClass = function(element, classname) {
+ element.classList.add(classname);
+ };
+
+ removeClass = function(element, classname) {
+ element.classList.remove(classname);
+ };
+
+ }
+
+ // Otherwise, implement own
+ else {
+
+ addClass = function(element, classname) {
+
+ // Simply add new class
+ element.className += " " + classname;
+
+ };
+
+ removeClass = function(element, classname) {
+
+ // Filter out classes with given name
+ element.className = element.className.replace(/([^ ]+)[ ]*/g,
+ function(match, testClassname, spaces, offset, string) {
+
+ // If same class, remove
+ if (testClassname == classname)
+ return "";
+
+ // Otherwise, allow
+ return match;
+
+ }
+ );
+
+ };
+
+ }
+
// Returns a unique power-of-two value for the modifier with the
// given name. The same value will be returned for the same modifier.
function getModifier(name) {
@@ -249,8 +298,8 @@ Guacamole.OnScreenKeyboard = function(url) {
var requirements = required.value.split(",");
for (var i=0; i<requirements.length; i++) {
modifierValue |= getModifier(requirements[i]);
- cap_element.classList.add("guac-keyboard-requires-" + requirements[i]);
- key_element.classList.add("guac-keyboard-uses-" + requirements[i]);
+ addClass(cap_element, "guac-keyboard-requires-" + requirements[i]);
+ addClass(key_element, "guac-keyboard-uses-" + requirements[i]);
}
}
@@ -271,7 +320,7 @@ Guacamole.OnScreenKeyboard = function(url) {
// Press key if not yet pressed
if (!key.pressed) {
- key_element.classList.add("guac-keyboard-pressed");
+ addClass(key_element, "guac-keyboard-pressed");
// Get current cap based on modifier state
var cap = key.getCap(on_screen_keyboard.modifiers);
@@ -288,11 +337,11 @@ Guacamole.OnScreenKeyboard = function(url) {
// Activate modifier if pressed
if (on_screen_keyboard.modifiers & modifierFlag)
- keyboard.classList.add(modifierClass);
+ addClass(keyboard, modifierClass);
// Deactivate if not pressed
else
- keyboard.classList.remove(modifierClass);
+ removeClass(keyboard, modifierClass);
}
@@ -320,7 +369,7 @@ Guacamole.OnScreenKeyboard = function(url) {
// Get current cap based on modifier state
var cap = key.getCap(on_screen_keyboard.modifiers);
- key_element.classList.remove("guac-keyboard-pressed");
+ removeClass(key_element, "guac-keyboard-pressed");
// Send key event
if (on_screen_keyboard.onkeyup && cap.keysym) | Only use classList.add() and classList.remove() if classList is supported. | glyptodon_guacamole-client | train |
b93dcb46b97a84e7d37af23639c6d43fa0aa4eb1 | diff --git a/glances/glances.py b/glances/glances.py
index <HASH>..<HASH> 100755
--- a/glances/glances.py
+++ b/glances/glances.py
@@ -22,7 +22,7 @@
from __future__ import generators
__appname__ = 'glances'
-__version__ = "1.4.1"
+__version__ = "1.4"
__author__ = "Nicolas Hennion <[email protected]>"
__licence__ = "LGPL" | Solve the issue #<I> with Python 2.x | nicolargo_glances | train |
e7ced967bb3e87a39e6cb1e97b702144f89975dc | diff --git a/Image/AliasGenerator.php b/Image/AliasGenerator.php
index <HASH>..<HASH> 100644
--- a/Image/AliasGenerator.php
+++ b/Image/AliasGenerator.php
@@ -26,11 +26,6 @@ class AliasGenerator implements VariationHandlerInterface
private $kernelClosure;
/**
- * @var \eZ\Publish\Core\MVC\ConfigResolverInterface
- */
- private $configResolver;
-
- /**
* @var \eZImageAliasHandler[]
*/
private $aliasHandlers;
@@ -43,10 +38,9 @@ class AliasGenerator implements VariationHandlerInterface
*/
private $variations;
- public function __construct( \Closure $legacyKernelClosure, ConfigResolverInterface $configResolver )
+ public function __construct( \Closure $legacyKernelClosure )
{
$this->kernelClosure = $legacyKernelClosure;
- $this->configResolver = $configResolver;
}
/**
@@ -75,13 +69,12 @@ class AliasGenerator implements VariationHandlerInterface
if ( isset( $this->variations[$variationIdentifier] ) )
return $this->variations[$variationIdentifier];
- $configResolver = $this->configResolver;
// Assigning by reference to be able to modify those arrays within the closure (due to PHP 5.3 limitation with access to $this)
$allAliasHandlers = &$this->aliasHandlers;
$allVariations = &$this->variations;
return $this->getLegacyKernel()->runCallback(
- function () use ( $field, $versionInfo, $variationName, $configResolver, $allAliasHandlers, $allVariations, $variationIdentifier )
+ function () use ( $field, $versionInfo, $variationName, $allAliasHandlers, $allVariations, $variationIdentifier )
{
$aliasHandlerIdentifier = "$field->id-$versionInfo->versionNo";
if ( !isset( $allAliasHandlers[$aliasHandlerIdentifier] ) ) | Removed unused dependency on ConfigResolver for AliasGenerator | ezsystems_LegacyBridge | train |
15d57c6e684deceb72fd88e9693c2f344f82824f | diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -6,9 +6,9 @@ of them are holding you up from porting to Python 3.
You can specify your dependencies in multiple ways::
- python3 -m caniusepython3 -r requirements.txt
- python3 -m caniusepython3 -m PKG-INFO
- python3 -m caniusepython3 -p numpy,scipy,ipython
+ caniusepython3 -r requirements.txt
+ caniusepython3 -m PKG-INFO
+ caniusepython3 -p numpy,scipy,ipython
The output of the script will list which projects are directly holding up some
(implicit) dependency from working on Python 3.
diff --git a/caniusepython3.py b/caniusepython3.py
index <HASH>..<HASH> 100644
--- a/caniusepython3.py
+++ b/caniusepython3.py
@@ -184,7 +184,7 @@ def projects_from_cli(args):
return projects
-if __name__ == '__main__':
+def main():
projects = projects_from_cli(sys.argv[1:])
logging.info('{} top-level projects to check'.format(len(projects)))
print('Finding and checking dependencies ...')
@@ -198,3 +198,7 @@ if __name__ == '__main__':
print('{} dependencies have no other dependencies blocking a port to Python 3:'.format(len(blocking)))
for blocker in sorted(blocking, key=lambda x: tuple(reversed(x))):
print(' <- '.join(blocker))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -1,4 +1,4 @@
-from distutils.core import setup
+from setuptools import setup
with open('README.md') as file:
# Try my best to have at least the intro in Markdown/reST.
@@ -16,7 +16,7 @@ setup(name='caniusepython3',
author_email='[email protected]',
url='https://github.com/brettcannon/caniusepython3',
py_modules=['caniusepython3'],
- requires=requires,
+ install_requires=requires,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
@@ -24,4 +24,9 @@ setup(name='caniusepython3',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 3',
],
+ entry_points={
+ 'console_scripts': [
+ 'caniusepython3=caniusepython3:main',
+ ]
+ },
) | Made caniusepython3 as script. Fix #2.
This uses setuptools since it's the best option for making this work cross platform. This also actually tells pip/easy_install/etc to install the dependencies. | brettcannon_caniusepython3 | train |
3d607d6058dcc377fd2fa8a1aa51ec67889af0c9 | diff --git a/lib/unexpectedMitm.js b/lib/unexpectedMitm.js
index <HASH>..<HASH> 100644
--- a/lib/unexpectedMitm.js
+++ b/lib/unexpectedMitm.js
@@ -779,7 +779,7 @@ module.exports = {
expect.promise(function () {
return expect.shift();
- }).caught(reject).then(function () {
+ }).caught(reject).then(function (fulfilmentValue) {
/*
* Handle the case of specified but unprocessed mocks.
* If there were none remaining immediately complete.
@@ -813,14 +813,13 @@ module.exports = {
}
})();
} else {
- resolve([httpConversation, httpConversationSatisfySpec]);
+ resolve([httpConversation, httpConversationSatisfySpec, fulfilmentValue]);
}
});
- }).spread(function (httpConversation, httpConversationSatisfySpec) {
+ }).spread(function (httpConversation, httpConversationSatisfySpec, fulfilmentValue) {
expect.errorMode = 'default';
return expect(httpConversation, 'to satisfy', httpConversationSatisfySpec).then(function () {
- // always resolve "with http mocked out" with exchanges
- return [ httpConversation, httpConversationSatisfySpec ];
+ return fulfilmentValue;
});
}).finally(function () {
mitm.disable();
diff --git a/test/unexpectedMitm.js b/test/unexpectedMitm.js
index <HASH>..<HASH> 100644
--- a/test/unexpectedMitm.js
+++ b/test/unexpectedMitm.js
@@ -4,7 +4,6 @@ var pathModule = require('path'),
fs = require('fs'),
http = require('http'),
https = require('https'),
- messy = require('messy'),
pem = require('pem'),
stream = require('stream'),
semver = require('semver'),
@@ -1382,17 +1381,9 @@ describe('unexpectedMitm', function () {
});
});
- it('should resolve with the compared exchanges', function () {
- return expect(
- expect('GET /', 'with http mocked out', {
- request: 'GET /',
- response: 200
- }, 'to yield response', 200),
- 'when fulfilled',
- 'to satisfy', [
- new messy.HttpExchange(),
- expect.it('to be an object')
- ]
- );
+ it('should preserve the fulfilment value of the promise returned by the assertion being delegated to', function () {
+ return expect([1, 2], 'with http mocked out', [], 'when passed as parameters to', Math.max).then(function (value) {
+ expect(value, 'to equal', 2);
+ });
});
}); | with http mocked out: Resolve the promise with the same value as the assertion being delegated to. | unexpectedjs_unexpected-mitm | train |
64b51e871de7929c65f64a9e65d77b058e98e017 | diff --git a/src/java/ognl/OgnlContext.java b/src/java/ognl/OgnlContext.java
index <HASH>..<HASH> 100644
--- a/src/java/ognl/OgnlContext.java
+++ b/src/java/ognl/OgnlContext.java
@@ -54,11 +54,7 @@ public class OgnlContext extends Object implements Map
private static boolean DEFAULT_TRACE_EVALUATIONS = false;
private static boolean DEFAULT_KEEP_LAST_EVALUATION = false;
- public static final ClassResolver DEFAULT_CLASS_RESOLVER = new DefaultClassResolver();
- public static final TypeConverter DEFAULT_TYPE_CONVERTER = new DefaultTypeConverter();
- public static final MemberAccess DEFAULT_MEMBER_ACCESS = new DefaultMemberAccess(false);
-
- private static Map RESERVED_KEYS = new HashMap(11);
+ private static final Map<String, Object> RESERVED_KEYS = new HashMap<>(6);
private Object _root;
private Object _currentObject;
@@ -71,13 +67,13 @@ public class OgnlContext extends Object implements Map
private final Map _values;
- private ClassResolver _classResolver = DEFAULT_CLASS_RESOLVER;
- private TypeConverter _typeConverter = DEFAULT_TYPE_CONVERTER;
- private MemberAccess _memberAccess = DEFAULT_MEMBER_ACCESS;
+ private final ClassResolver _classResolver;
+ private final TypeConverter _typeConverter;
+ private final MemberAccess _memberAccess;
static {
String s;
-
+
RESERVED_KEYS.put(ROOT_CONTEXT_KEY, null);
RESERVED_KEYS.put(THIS_CONTEXT_KEY, null);
RESERVED_KEYS.put(TRACE_EVALUATIONS_CONTEXT_KEY, null);
@@ -104,16 +100,6 @@ public class OgnlContext extends Object implements Map
private Map _localReferenceMap = null;
/**
- * Constructs a new OgnlContext with the default class resolver, type converter and member
- * access.
- */
- public OgnlContext()
- {
- // nulls will prevent overriding the default class resolver, type converter and member access
- this(null, null, null);
- }
-
- /**
* Constructs a new OgnlContext with the given class resolver, type converter and member access.
* If any of these parameters is null the default will be used.
*/
@@ -135,12 +121,18 @@ public class OgnlContext extends Object implements Map
this._values = values;
if (classResolver != null) {
this._classResolver = classResolver;
+ } else {
+ this._classResolver = new DefaultClassResolver();
}
if (typeConverter != null) {
this._typeConverter = typeConverter;
+ } else {
+ this._typeConverter = new DefaultTypeConverter();
}
if (memberAccess != null) {
this._memberAccess = memberAccess;
+ } else {
+ this._memberAccess = new DefaultMemberAccess(false);
}
}
@@ -158,10 +150,9 @@ public class OgnlContext extends Object implements Map
return _values;
}
- public void setClassResolver(ClassResolver value)
- {
- if (value == null) { throw new IllegalArgumentException("cannot set ClassResolver to null"); }
- _classResolver = value;
+ @Deprecated
+ public void setClassResolver(ClassResolver ignore) {
+ // no-op
}
public ClassResolver getClassResolver()
@@ -169,10 +160,10 @@ public class OgnlContext extends Object implements Map
return _classResolver;
}
- public void setTypeConverter(TypeConverter value)
+ @Deprecated
+ public void setTypeConverter(TypeConverter ignore)
{
- if (value == null) { throw new IllegalArgumentException("cannot set TypeConverter to null"); }
- _typeConverter = value;
+ // no-op
}
public TypeConverter getTypeConverter()
@@ -180,10 +171,10 @@ public class OgnlContext extends Object implements Map
return _typeConverter;
}
- public void setMemberAccess(MemberAccess value)
+ @Deprecated
+ public void setMemberAccess(MemberAccess ignore)
{
- if (value == null) { throw new IllegalArgumentException("cannot set MemberAccess to null"); }
- _memberAccess = value;
+ // no-op
}
public MemberAccess getMemberAccess()
@@ -542,12 +533,7 @@ public class OgnlContext extends Object implements Map
result = getKeepLastEvaluation() ? Boolean.TRUE : Boolean.FALSE;
setKeepLastEvaluation(OgnlOps.booleanValue(value));
} else {
- if (key.equals(OgnlContext.TYPE_CONVERTER_CONTEXT_KEY)) {
- result = getTypeConverter();
- setTypeConverter((TypeConverter) value);
- } else {
- throw new IllegalArgumentException("unknown reserved key '" + key + "'");
- }
+ throw new IllegalArgumentException("unknown reserved key '" + key + "'");
}
}
}
@@ -585,12 +571,7 @@ public class OgnlContext extends Object implements Map
throw new IllegalArgumentException("can't remove "
+ OgnlContext.KEEP_LAST_EVALUATION_CONTEXT_KEY + " from context");
} else {
- if (key.equals(OgnlContext.TYPE_CONVERTER_CONTEXT_KEY)) {
- result = getTypeConverter();
- setTypeConverter(null);
- } else {
- throw new IllegalArgumentException("unknown reserved key '" + key + "'");
- }
+ throw new IllegalArgumentException("unknown reserved key '" + key + "'");
}
}
}
@@ -629,9 +610,6 @@ public class OgnlContext extends Object implements Map
setCurrentEvaluation(null);
setLastEvaluation(null);
setCurrentNode(null);
- setClassResolver(DEFAULT_CLASS_RESOLVER);
- setTypeConverter(DEFAULT_TYPE_CONVERTER);
- setMemberAccess(DEFAULT_MEMBER_ACCESS);
}
public Set keySet() | Makes context a bit more immutable | jkuhnert_ognl | train |
3ef318bc6501541b7fe132bef20661be83025aee | diff --git a/ast_test.go b/ast_test.go
index <HASH>..<HASH> 100644
--- a/ast_test.go
+++ b/ast_test.go
@@ -547,7 +547,7 @@ var astTests = []testCase{
}},
},
{
- []string{`echo "$(foo bar)"`},
+ []string{`echo "$(foo bar)"`, `echo "$(foo bar)"`},
Command{Args: []Word{
litWord("echo"),
word(dblQuoted(cmdSubst(litStmt("foo", "bar")))),
@@ -561,7 +561,7 @@ var astTests = []testCase{
}},
},
{
- []string{"echo \"`foo bar`\""},
+ []string{"echo \"`foo bar`\"", "echo \"`foo bar`\""},
Command{Args: []Word{
litWord("echo"),
word(dblQuoted(bckQuoted(litStmt("foo", "bar")))),
diff --git a/invalid_test.go b/invalid_test.go
index <HASH>..<HASH> 100644
--- a/invalid_test.go
+++ b/invalid_test.go
@@ -322,7 +322,7 @@ var errTests = []struct {
},
{
"\"`\"",
- "1:2: reached \" without closing quote `",
+ `1:3: reached EOF without closing quote "`,
},
{
"`\"`",
diff --git a/parse.go b/parse.go
index <HASH>..<HASH> 100644
--- a/parse.go
+++ b/parse.go
@@ -50,8 +50,11 @@ type parser struct {
}
func (p *parser) curStops() []Token { return p.stops[len(p.stops)-1] }
-func (p *parser) pushStops(stop ...Token) {
- p.stops = append(p.stops, append(p.curStops(), stop...))
+func (p *parser) newStops(stop ...Token) {
+ p.stops = append(p.stops, stop)
+}
+func (p *parser) addStops(stop ...Token) {
+ p.newStops(append(p.curStops(), stop...)...)
}
func (p *parser) popStops() { p.stops = p.stops[:len(p.stops)-1] }
@@ -64,7 +67,7 @@ func (p *parser) curQuote() byte {
func (p *parser) pushQuote(b byte) {
p.quotes = append(p.quotes, b)
- p.pushStops(Token(b))
+ p.addStops(Token(b))
}
func (p *parser) popQuote() {
@@ -457,7 +460,14 @@ func (p *parser) invalidStmtStart() {
}
func (p *parser) stmtsLimited(sts *[]Stmt, stop ...Token) int {
- p.pushStops(stop...)
+ p.addStops(stop...)
+ count := p.stmts(sts, p.curStops()...)
+ p.popStops()
+ return count
+}
+
+func (p *parser) stmtsNested(sts *[]Stmt, stop Token) int {
+ p.newStops(stop)
count := p.stmts(sts, p.curStops()...)
p.popStops()
return count
@@ -498,7 +508,7 @@ func (p *parser) readParts(ns *[]Node) (count int) {
p.pushQuote('`')
bq.Quote = p.pos
p.next()
- p.stmtsLimited(&bq.Stmts, '`')
+ p.stmtsNested(&bq.Stmts, '`')
p.popQuote()
p.wantQuote(bq.Quote, '`')
n = bq
@@ -534,7 +544,7 @@ func (p *parser) exp() Node {
p.pushQuote('`')
p.next()
cs.Exp = p.lpos
- p.stmtsLimited(&cs.Stmts, RPAREN)
+ p.stmtsNested(&cs.Stmts, RPAREN)
p.popQuote()
p.wantMatched(cs.Exp, LPAREN)
return cs | Make nested stmts reset quotes | mvdan_sh | train |
5f70c9a3257c983d2d252f14f22d26b6cf571ff1 | diff --git a/provider/ec2/environ.go b/provider/ec2/environ.go
index <HASH>..<HASH> 100644
--- a/provider/ec2/environ.go
+++ b/provider/ec2/environ.go
@@ -531,12 +531,20 @@ func (e *environ) StartInstance(args environs.StartInstanceParams) (_ *environs.
subnetIDsForZone, subnetErr = findSubnetIDsForAvailabilityZone(zone, args.SubnetsToZones)
}
- if len(subnetIDsForZone) > 0 {
+ if len(subnetIDsForZone) > 1 {
+ // With multiple equally suitable subnets, picking one at random
+ // will allow for better instance spread within the same zone, and
+ // still work correctly if we happen to pick a constrained subnet
+ // (we'll just treat this the same way we treat constrained zones
+ // and retry).
runArgs.SubnetId = subnetIDsForZone[rand.Intn(len(subnetIDsForZone))]
logger.Infof(
"selected random subnet %q from all matching in zone %q: %v",
runArgs.SubnetId, zone, subnetIDsForZone,
)
+ } else if len(subnetIDsForZone) == 1 {
+ runArgs.SubnetId = subnetIDsForZone[0]
+ logger.Infof("selected subnet %q in zone %q", runArgs.SubnetId, zone)
} else if errors.IsNotFound(subnetErr) {
logger.Infof("no matching subnets in zone %q; assuming zone is constrained and trying another", zone)
continue | Clarified the reason for picking a random subnet in a zone when >1 subnets match | juju_juju | train |
bc0ccbda9904f0c0f4a249fb8309c1af60a402d0 | diff --git a/src/Psalm/Internal/Analyzer/Statements/Expression/BinaryOpAnalyzer.php b/src/Psalm/Internal/Analyzer/Statements/Expression/BinaryOpAnalyzer.php
index <HASH>..<HASH> 100644
--- a/src/Psalm/Internal/Analyzer/Statements/Expression/BinaryOpAnalyzer.php
+++ b/src/Psalm/Internal/Analyzer/Statements/Expression/BinaryOpAnalyzer.php
@@ -1878,15 +1878,32 @@ class BinaryOpAnalyzer
} else {
if ($left_type
&& $right_type
- && ($left_type->getId() === 'non-empty-string'
- || $right_type->getId() === 'non-empty-string'
- || ($left_type->isSingleStringLiteral()
- && $left_type->getSingleStringLiteral()->value)
- || ($right_type->isSingleStringLiteral()
- && $right_type->getSingleStringLiteral()->value))
) {
- $result_type = new Type\Union([new Type\Atomic\TNonEmptyString()]);
+ $left_type_literal_value = $left_type->isSingleStringLiteral()
+ ? $left_type->getSingleStringLiteral()->value
+ : null;
+
+ $right_type_literal_value = $right_type->isSingleStringLiteral()
+ ? $right_type->getSingleStringLiteral()->value
+ : null;
+
+ if (($left_type->getId() === 'lowercase-string'
+ || ($left_type_literal_value !== null
+ && strtolower($left_type_literal_value) === $left_type_literal_value))
+ && ($right_type->getId() === 'lowercase-string'
+ || ($right_type_literal_value !== null
+ && strtolower($right_type_literal_value) === $right_type_literal_value))
+ ) {
+ $result_type = new Type\Union([new Type\Atomic\TLowercaseString()]);
+ } elseif ($left_type->getId() === 'non-empty-string'
+ || $right_type->getId() === 'non-empty-string'
+ || $left_type_literal_value
+ || $right_type_literal_value
+ ) {
+ $result_type = new Type\Union([new Type\Atomic\TNonEmptyString()]);
+ }
}
+
}
if ($codebase->taint && $result_type) { | Add better inference for lower-cased methods | vimeo_psalm | train |
8f56fff9148b3d6f9b2ff5704f9633fa13eae80b | diff --git a/openquake/calculators/classical.py b/openquake/calculators/classical.py
index <HASH>..<HASH> 100644
--- a/openquake/calculators/classical.py
+++ b/openquake/calculators/classical.py
@@ -37,7 +37,7 @@ from openquake.commonlib import parallel, datastore, source, calc
from openquake.calculators import base
U16 = numpy.uint16
-F32 = numpy.float32
+F64 = numpy.float64
HazardCurve = collections.namedtuple('HazardCurve', 'location poes')
@@ -46,9 +46,9 @@ class BBdict(AccumDict):
A serializable dictionary containing bounding box information
"""
dt = numpy.dtype([('lt_model_id', U16), ('site_id', U16),
- ('min_dist', F32), ('max_dist', F32),
- ('east', F32), ('west', F32),
- ('south', F32), ('north', F32)])
+ ('min_dist', F64), ('max_dist', F64),
+ ('east', F64), ('west', F64),
+ ('south', F64), ('north', F64)])
def __toh5__(self):
rows = []
diff --git a/openquake/calculators/disaggregation.py b/openquake/calculators/disaggregation.py
index <HASH>..<HASH> 100644
--- a/openquake/calculators/disaggregation.py
+++ b/openquake/calculators/disaggregation.py
@@ -250,6 +250,9 @@ class DisaggregationCalculator(classical.ClassicalCalculator):
"""
oq = self.oqparam
tl = self.oqparam.truncation_level
+ bb_dict = self.datastore['bb_dict']
+ bbd = curves_by_trt_gsim.bb_dict
+ #import pdb; pdb.set_trace()
sitecol = self.sitecol
mag_bin_width = self.oqparam.mag_bin_width
eps_edges = numpy.linspace(-tl, tl, self.oqparam.num_epsilon_bins + 1)
@@ -276,7 +279,7 @@ class DisaggregationCalculator(classical.ClassicalCalculator):
curves = curves_dict[sid]
if not curves:
continue # skip zero-valued hazard curves
- bb = curves_by_trt_gsim.bb_dict[sm_id, sid]
+ bb = bb_dict[sm_id, sid]
if not bb:
logging.info(
'location %s was too far, skipping disaggregation', | Fixed precision breaking the disagg tests | gem_oq-engine | train |
7597d2029c757c12e07a93ff8399856f2cf18b3c | diff --git a/pyhomematic/devicetypes/generic.py b/pyhomematic/devicetypes/generic.py
index <HASH>..<HASH> 100644
--- a/pyhomematic/devicetypes/generic.py
+++ b/pyhomematic/devicetypes/generic.py
@@ -213,7 +213,7 @@ class HMDevice(HMGeneric):
# - 0...n / getValue from channel (fix)
self._SENSORNODE = {}
self._BINARYNODE = {}
- self._ATTRIBUTENODE = {"RSSI_PEER": [0]}
+ self._ATTRIBUTENODE = {}
self._WRITENODE = {}
self._EVENTNODE = {}
self._ACTIONNODE = {}
@@ -334,7 +334,13 @@ class HMDevice(HMGeneric):
return False
def get_rssi(self, channel=0):
- return self.getAttributeData("RSSI_PEER", channel)
+ """
+ This is a stub method which is implemented by the helpers
+ HelperRssiPeer/HelperRssiDevice in order to provide a suitable
+ implementation for the device.
+ """
+ #pylint: disable=unused-argument
+ return 0
@property
def ELEMENT(self):
diff --git a/pyhomematic/devicetypes/helper.py b/pyhomematic/devicetypes/helper.py
index <HASH>..<HASH> 100644
--- a/pyhomematic/devicetypes/helper.py
+++ b/pyhomematic/devicetypes/helper.py
@@ -238,8 +238,28 @@ class HelperEventRemote(HMDevice):
"PRESS_LONG_RELEASE": self.ELEMENT})
class HelperWired(HMDevice):
- """Remove the RSSI_PEER attribute"""
+ """Remove the RSSI-related attributes"""
def __init__(self, device_description, proxy, resolveparamsets=False):
super().__init__(device_description, proxy, resolveparamsets)
-
self.ATTRIBUTENODE.pop("RSSI_PEER", None)
+ self.ATTRIBUTENODE.pop("RSSI_DEVICE", None)
+
+
+class HelperRssiDevice(HMDevice):
+ """Used for devices which report their RSSI value through RSSI_DEVICE"""
+ def __init__(self, device_description, proxy, resolveparamsets=False):
+ super().__init__(device_description, proxy, resolveparamsets)
+ self.ATTRIBUTENODE["RSSI_DEVICE"] = [0]
+
+ def get_rssi(self, channel=0):
+ return self.getAttributeData("RSSI_DEVICE", channel)
+
+
+class HelperRssiPeer(HMDevice):
+ """Used for devices which report their RSSI value through RSSI_PEER"""
+ def __init__(self, device_description, proxy, resolveparamsets=False):
+ super().__init__(device_description, proxy, resolveparamsets)
+ self.ATTRIBUTENODE["RSSI_PEER"] = [0]
+
+ def get_rssi(self, channel=0):
+ return self.getAttributeData("RSSI_PEER", channel) | Move RSSI handling to helper class
Apparently some devices use RSSI_PEER and some use RSSI_DEVICE, so we
need to use the appropriate helper in the actual device class.
See danielperna<I>/pyhomematic#<I> | danielperna84_pyhomematic | train |
388de316e4d9aed2926534585beada94ed0a1793 | diff --git a/apptentive-android-sdk/src/com/apptentive/android/sdk/Apptentive.java b/apptentive-android-sdk/src/com/apptentive/android/sdk/Apptentive.java
index <HASH>..<HASH> 100755
--- a/apptentive-android-sdk/src/com/apptentive/android/sdk/Apptentive.java
+++ b/apptentive-android-sdk/src/com/apptentive/android/sdk/Apptentive.java
@@ -126,11 +126,42 @@ public class Apptentive {
/**
* Allows you to pass arbitrary string data to the server along with this device's info.
* @param customData A Map of key/value pairs to send to the server.
+ * @deprecated in favor of {@link #setCustomDeviceData(Map)}
*/
public static void setCustomData(Map<String, String> customData) {
Apptentive.customData = customData;
}
+ /**
+ * Allows you to pass arbitrary string data to the server along with this device's info.
+ * @param customDeviceData A Map of key/value pairs to send to the server.
+ */
+ public static void setCustomDeviceData(Map<String, String> customDeviceData) {
+ Apptentive.customData = customData;
+ }
+
+ /**
+ * Add a piece of custom data to the device's info. This info will be sent to the server.
+ * @param key The key to store the data under.
+ * @param value The value of the data.
+ */
+ public static void addCustomDeviceData(String key, String value) {
+ if(Apptentive.customData == null) {
+ Apptentive.customData = new HashMap<String, String>();
+ }
+ Apptentive.customData.put(key, value);
+ }
+
+ /**
+ * Remove a piece of custom data to the device's info.
+ * @param key The key to store the data under.
+ */
+ public static void removeCustomDeviceData(String key) {
+ if(Apptentive.customData != null) {
+ Apptentive.customData.remove(key);
+ }
+ }
+
// ****************************************************************************************
// RATINGS | Add ability to ad and remove individual pieces of device data. | apptentive_apptentive-android | train |
93dc2ab9e10e886c7753232567bdc05df7597127 | diff --git a/devices.js b/devices.js
index <HASH>..<HASH> 100755
--- a/devices.js
+++ b/devices.js
@@ -5797,6 +5797,13 @@ const devices = [
toZigbee: [tz.on_off],
},
{
+ zigbeeModel: ['Micro Smart Dimmer'],
+ model: 'ZG2835RAC',
+ vendor: 'Sunricher',
+ description: 'ZigBee knob smart dimmer',
+ extend: generic.light_onoff_brightness,
+ },
+ {
zigbeeModel: ['ZG2833K4_EU06'],
model: 'SR-ZG9001K4-DIM2',
vendor: 'Sunricher', | Add ZG<I>RAC (#<I>) | Koenkk_zigbee-shepherd-converters | train |
4de3a60ab6c79692990d3a95858ddbb5cbd654b1 | diff --git a/modules/pubmaticBidAdapter.js b/modules/pubmaticBidAdapter.js
index <HASH>..<HASH> 100644
--- a/modules/pubmaticBidAdapter.js
+++ b/modules/pubmaticBidAdapter.js
@@ -12,6 +12,7 @@ const USER_SYNC_URL_IMAGE = 'https://image8.pubmatic.com/AdServer/ImgSync?p=';
const DEFAULT_CURRENCY = 'USD';
const AUCTION_TYPE = 1;
const GROUPM_ALIAS = {code: 'groupm', gvlid: 98};
+const MARKETPLACE_PARTNERS = ['groupm']
const UNDEFINED = undefined;
const DEFAULT_WIDTH = 0;
const DEFAULT_HEIGHT = 0;
@@ -1065,6 +1066,12 @@ export const spec = {
* @return ServerRequest Info describing the request to the server.
*/
buildRequests: (validBidRequests, bidderRequest) => {
+ if (bidderRequest && MARKETPLACE_PARTNERS.includes(bidderRequest.bidderCode)) {
+ // We have got the buildRequests function call for Marketplace Partners
+ logInfo('For all publishers using ' + bidderRequest.bidderCode + ' bidder, the PubMatic bidder will also be enabled so PubMatic server will respond back with the bids that needs to be submitted for PubMatic and ' + bidderRequest.bidderCode + ' in the network call sent by PubMatic bidder. Hence we do not want to create a network call for ' + bidderRequest.bidderCode + '. This way we are trying to save a network call from browser.');
+ return;
+ }
+
var refererInfo;
if (bidderRequest && bidderRequest.refererInfo) {
refererInfo = bidderRequest.refererInfo;
@@ -1287,6 +1294,13 @@ export const spec = {
};
}
+ // if from the server-response the bid.ext.marketplace is set then
+ // submit the bid to Prebid as marketplace name
+ if (bid.ext && !!bid.ext.marketplace && MARKETPLACE_PARTNERS.includes(bid.ext.marketplace)) {
+ newBid.bidderCode = bid.ext.marketplace;
+ newBid.bidder = bid.ext.marketplace;
+ }
+
bidResponses.push(newBid);
});
});
diff --git a/test/spec/modules/pubmaticBidAdapter_spec.js b/test/spec/modules/pubmaticBidAdapter_spec.js
index <HASH>..<HASH> 100644
--- a/test/spec/modules/pubmaticBidAdapter_spec.js
+++ b/test/spec/modules/pubmaticBidAdapter_spec.js
@@ -3901,4 +3901,40 @@ describe('PubMatic adapter', function () {
expect(data.imp[0]['video']['battr']).to.equal(undefined);
});
});
+
+ describe('GroupM params', function() {
+ let sandbox, utilsMock, newBidRequests, newBidResponses;
+ beforeEach(() => {
+ utilsMock = sinon.mock(utils);
+ sandbox = sinon.sandbox.create();
+ sandbox.spy(utils, 'logInfo');
+ newBidRequests = utils.deepClone(bidRequests)
+ newBidRequests[0].bidder = 'groupm';
+ newBidResponses = utils.deepClone(bidResponses);
+ newBidResponses.body.seatbid[0].bid[0].ext.marketplace = 'groupm'
+ });
+
+ afterEach(() => {
+ utilsMock.restore();
+ sandbox.restore();
+ })
+
+ it('Should log info when bidder is groupm and return', function () {
+ let request = spec.buildRequests(newBidRequests, {bidderCode: 'groupm',
+ auctionId: 'new-auction-id'
+ });
+ sinon.assert.calledOnce(utils.logInfo);
+ expect(request).to.equal(undefined);
+ });
+
+ it('Should add bidder code & bidder as groupm for marketplace groupm response', function () {
+ let request = spec.buildRequests(newBidRequests, {
+ auctionId: 'new-auction-id'
+ });
+ let response = spec.interpretResponse(newBidResponses, request);
+ expect(response).to.be.an('array').with.length.above(0);
+ expect(response[0].bidderCode).to.equal('groupm');
+ expect(response[0].bidder).to.equal('groupm');
+ });
+ });
}); | PubMatic Bid Adapter: Added multibid support for GroupM (#<I>)
* Changed net revenue to True
* Added miltibid support for GroupM
* Added marketplace array to check for values
* Added marketplace check while requesting too | prebid_Prebid.js | train |
4d0b92061f82ef494b23a69b6d715c575019f365 | diff --git a/examples/js/cli.js b/examples/js/cli.js
index <HASH>..<HASH> 100644
--- a/examples/js/cli.js
+++ b/examples/js/cli.js
@@ -257,7 +257,7 @@ async function main () {
try {
const result = await exchange[methodName] (... args)
end = exchange.milliseconds ()
- console.log (exchange.iso8601 (end), 'iteration', i++, 'passed in', end - start, 'ms')
+ console.log (exchange.iso8601 (end), 'iteration', i++, 'passed in', end - start, 'ms\n')
start = end
printHumanReadable (exchange, result)
} catch (e) { | examples/js/cli newline for readability | ccxt_ccxt | train |
d97aac8d83116d73a440d19ac5593772925a64b4 | diff --git a/validation.py b/validation.py
index <HASH>..<HASH> 100644
--- a/validation.py
+++ b/validation.py
@@ -58,7 +58,8 @@ TERMINAL_VOWELS = {
STRIPPED_VOWELS = set(map(mark.strip, VOWELS))
# 'uo' may clash with 'ươ' and prevent typing 'thương'
-STRIPPED_TERMINAL_VOWELS = set(map(mark.strip, TERMINAL_VOWELS)) - {'uo'}
+# 'ua' may clash with 'uâ' and prevent typing 'luật'
+STRIPPED_TERMINAL_VOWELS = set(map(mark.strip, TERMINAL_VOWELS)) - {'uo', 'ua'}
SoundTuple = \ | Remvove 'ua' from STRIPPED_TERMINAL_VOWELS
It may clash with 'uâ' and prevent typing 'luật'. | BoGoEngine_bogo-python | train |
76d0e41bf8e394d43b4a6e7a2d8593223ae11634 | diff --git a/sonar-batch-protocol/src/main/java/org/sonar/batch/protocol/ReportStream.java b/sonar-batch-protocol/src/main/java/org/sonar/batch/protocol/ReportStream.java
index <HASH>..<HASH> 100644
--- a/sonar-batch-protocol/src/main/java/org/sonar/batch/protocol/ReportStream.java
+++ b/sonar-batch-protocol/src/main/java/org/sonar/batch/protocol/ReportStream.java
@@ -34,35 +34,30 @@ import java.util.NoSuchElementException;
* An object to iterate over protobuf messages in a file.
* A ReportStream is opened upon creation and is closed by invoking the close method.
*
- * Warning, while it extends Iterable, it is not a general-purpose Iterable as it supports only a single Iterator;
- * invoking the iterator method to obtain a second or subsequent iterator throws IllegalStateException.
- *
* Inspired by {@link java.nio.file.DirectoryStream}
*/
public class ReportStream<R extends Message> implements Closeable, Iterable<R> {
+ private final File file;
private final Parser<R> parser;
private InputStream inputStream;
- private ReportIterator<R> iterator;
public ReportStream(File file, Parser<R> parser) {
+ this.file = file;
this.parser = parser;
- this.inputStream = ProtobufUtil.createInputStream(file);
}
@Override
public Iterator<R> iterator() {
- if (this.iterator != null) {
- throw new IllegalStateException("Iterator already obtained");
- } else {
- this.iterator = new ReportIterator<>(inputStream, parser);
- return this.iterator;
- }
+ this.inputStream = ProtobufUtil.createInputStream(file);
+ return new ReportIterator<>(inputStream, parser);
}
@Override
public void close() throws IOException {
- inputStream.close();
+ if (inputStream != null) {
+ inputStream.close();
+ }
}
public static class ReportIterator<R extends Message> implements Iterator<R> {
diff --git a/sonar-batch-protocol/src/test/java/org/sonar/batch/protocol/ReportStreamTest.java b/sonar-batch-protocol/src/test/java/org/sonar/batch/protocol/ReportStreamTest.java
index <HASH>..<HASH> 100644
--- a/sonar-batch-protocol/src/test/java/org/sonar/batch/protocol/ReportStreamTest.java
+++ b/sonar-batch-protocol/src/test/java/org/sonar/batch/protocol/ReportStreamTest.java
@@ -36,6 +36,7 @@ import java.util.Iterator;
import java.util.NoSuchElementException;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.util.Lists.newArrayList;
public class ReportStreamTest {
@@ -68,17 +69,20 @@ public class ReportStreamTest {
@Test
public void read_report() throws Exception {
sut = new ReportStream<>(file, BatchReport.Coverage.PARSER);
- assertThat(sut).hasSize(1);
- sut.close();
+ assertThat(newArrayList(sut)).hasSize(1);
+
+ assertThat(sut.iterator().next()).isNotNull();
+ // Shoudl not be null as it should return the first element
+ assertThat(sut.iterator().next()).isNotNull();
}
- @Test(expected = IllegalStateException.class)
- public void fail_to_get_iterator_twice() throws Exception {
+ @Test
+ public void next_should_be_reentrant() throws Exception {
sut = new ReportStream<>(file, BatchReport.Coverage.PARSER);
- sut.iterator();
+ assertThat(sut).hasSize(1);
- // Fail !
- sut.iterator();
+ assertThat(sut.iterator().next()).isNotNull();
+ assertThat(sut.iterator().next()).isNotNull();
}
@Test(expected = NoSuchElementException.class)
@@ -101,4 +105,10 @@ public class ReportStreamTest {
iterator.remove();
}
+ @Test
+ public void not_fail_when_close_without_calling_iterator() throws Exception {
+ sut = new ReportStream<>(file, BatchReport.Coverage.PARSER);
+ sut.close();
+ }
+
} | Allow ReportStream to call iterator() multiple times | SonarSource_sonarqube | train |
bddce1e075ca735e98d8b14d8e1a4dea02a32e7b | diff --git a/lib/emoji.js b/lib/emoji.js
index <HASH>..<HASH> 100644
--- a/lib/emoji.js
+++ b/lib/emoji.js
@@ -128,15 +128,9 @@ Emoji.search = function search(str) {
});
}
-function getKeyByValue(object, value) {
- for (var prop in object) {
- if (object.hasOwnProperty(prop)) {
- if (object[prop] === value) {
- return prop;
- }
- }
- }
-}
+var emojiToCode = Object.keys(Emoji.emoji).reduce(function(h,k) {
+ return h[Emoji.emoji[k]] = k, h;
+}, {});
/**
* unemojify a string (replace emoji with :emoji:)
@@ -146,8 +140,9 @@ function getKeyByValue(object, value) {
Emoji.unemojify = function unemojify(str) {
if (!str) return '';
var words = toArray(str);
+
return words.map(function(word) {
- var emoji_text = getKeyByValue(Emoji.emoji, word);
+ var emoji_text = emojiToCode[word];
if (emoji_text) {
return ':'+emoji_text+':';
}
diff --git a/test/emoji.js b/test/emoji.js
index <HASH>..<HASH> 100644
--- a/test/emoji.js
+++ b/test/emoji.js
@@ -115,7 +115,7 @@ describe("emoji.js", function () {
it("should parse emoji and replace them with :emoji:", function() {
var coffee = emoji.unemojify('I ❤️ ☕️! - 😯⭐️😍 ::: test : : 👍+');
should.exist(coffee);
- coffee.should.be.exactly('I :heart: :coffee:! - :hushed::star::heart_eyes: ::: test : : :+1:+');
+ coffee.should.be.exactly('I :heart: :coffee:! - :hushed::star::heart_eyes: ::: test : : :thumbsup:+');
})
it("should leave unknown emoji", function () { | refactor: change O(N*M) performance to O(N) | omnidan_node-emoji | train |
3dabd8f03d8cb58e7fea1af54b0462f700ec53f3 | diff --git a/airflow/operators/hive_to_druid.py b/airflow/operators/hive_to_druid.py
index <HASH>..<HASH> 100644
--- a/airflow/operators/hive_to_druid.py
+++ b/airflow/operators/hive_to_druid.py
@@ -129,9 +129,7 @@ class HiveToDruidTransfer(BaseOperator):
columns = [col.name for col in t.sd.cols]
# Get the path on hdfs
- hdfs_uri = m.get_table(hive_table).sd.location
- pos = hdfs_uri.find('/user')
- static_path = hdfs_uri[pos:]
+ static_path = m.get_table(hive_table).sd.location
schema, table = hive_table.split('.') | [AIRFLOW-<I>] Fix invalid static path in case of using HDP.
Closes #<I> from happyjulie/AIRFLOW-<I> | apache_airflow | train |
ea977403923b9f751f4d08b17a8be644ffc1f293 | diff --git a/lib/montrose/recurrence.rb b/lib/montrose/recurrence.rb
index <HASH>..<HASH> 100644
--- a/lib/montrose/recurrence.rb
+++ b/lib/montrose/recurrence.rb
@@ -322,8 +322,8 @@ module Montrose
#
# @return [Hash] json of recurrence options
#
- def as_json
- to_hash.as_json
+ def as_json(*args)
+ to_hash.as_json(*args)
end
# Returns options used to create the recurrence in YAML format | Add optional args to Recurrence#as_json
This method delegates to Hash#as_json which can accept options | rossta_montrose | train |
b3b00a67ce2975d4b3271acb99de8064035845ae | diff --git a/eZ/Publish/API/Repository/Tests/BaseTest.php b/eZ/Publish/API/Repository/Tests/BaseTest.php
index <HASH>..<HASH> 100644
--- a/eZ/Publish/API/Repository/Tests/BaseTest.php
+++ b/eZ/Publish/API/Repository/Tests/BaseTest.php
@@ -66,6 +66,33 @@ abstract class BaseTest extends PHPUnit_Framework_TestCase
}
/**
+ * Catch TODO exceptions and converts them to incomplete tests markers
+ *
+ * This is only a temporary solution to better distinguish errors and
+ * missing implementations.
+ *
+ * @return void
+ */
+ protected function runTest()
+ {
+ try
+ {
+ parent::runTest();
+ }
+ catch ( \Exception $e )
+ {
+ if ( stripos( $e->getMessage(), 'todo' ) !== false )
+ {
+ $this->markTestIncomplete( 'Missing implementation: ' . $e->getMessage() );
+ }
+ else
+ {
+ throw $e;
+ }
+ }
+ }
+
+ /**
* Resets the temporary used repository between each test run.
*
* @return void | Implemented: Temporary detection of incomplete implementations.
This converts exceptions which contain "TODO" into tests marked as being
"incomplete". This is just a temporary solution for better overview. | ezsystems_ezpublish-kernel | train |
46d4f817e3f6e0e7ca39027b155d084d14dd2d8a | diff --git a/pkg/tsdb/graphite/graphite.go b/pkg/tsdb/graphite/graphite.go
index <HASH>..<HASH> 100644
--- a/pkg/tsdb/graphite/graphite.go
+++ b/pkg/tsdb/graphite/graphite.go
@@ -102,9 +102,9 @@ func (e *GraphiteExecutor) parseResponse(res *http.Response) ([]TargetResponseDT
return nil, err
}
- if res.StatusCode == http.StatusUnauthorized {
- glog.Info("Request is Unauthorized", "status", res.Status, "body", string(body))
- return nil, fmt.Errorf("Request is Unauthorized status: %v body: %s", res.Status, string(body))
+ if res.StatusCode/100 != 200 {
+ glog.Info("Request failed", "status", res.Status, "body", string(body))
+ return nil, fmt.Errorf("Request failed status: %v", res.Status)
}
var data []TargetResponseDTO | tech(graphite): return error if statuscode is not ok | grafana_grafana | train |
15b9432717b7e7d152b6369e12d4dc7ea5e94c1a | diff --git a/vault/core.go b/vault/core.go
index <HASH>..<HASH> 100644
--- a/vault/core.go
+++ b/vault/core.go
@@ -1494,7 +1494,7 @@ func (c *Core) unsealInternal(ctx context.Context, masterKey []byte) (bool, erro
} else {
// Go to standby mode, wait until we are active to unseal
c.standbyDoneCh = make(chan struct{})
- c.manualStepDownCh = make(chan struct{})
+ c.manualStepDownCh = make(chan struct{}, 1)
c.standbyStopCh.Store(make(chan struct{}))
go c.runStandby(c.standbyDoneCh, c.manualStepDownCh, c.standbyStopCh.Load().(chan struct{}))
}
diff --git a/vault/core_test.go b/vault/core_test.go
index <HASH>..<HASH> 100644
--- a/vault/core_test.go
+++ b/vault/core_test.go
@@ -1250,7 +1250,7 @@ func TestCore_Standby_Seal(t *testing.T) {
func TestCore_StepDown(t *testing.T) {
// Create the first core and initialize it
- logger = logging.NewVaultLogger(log.Trace)
+ logger = logging.NewVaultLogger(log.Trace).Named(t.Name())
inm, err := inmem.NewInmemHA(nil, logger)
if err != nil {
@@ -1267,6 +1267,7 @@ func TestCore_StepDown(t *testing.T) {
HAPhysical: inmha.(physical.HABackend),
RedirectAddr: redirectOriginal,
DisableMlock: true,
+ Logger: logger.Named("core1"),
})
if err != nil {
t.Fatalf("err: %v", err)
@@ -1305,6 +1306,7 @@ func TestCore_StepDown(t *testing.T) {
HAPhysical: inmha.(physical.HABackend),
RedirectAddr: redirectOriginal2,
DisableMlock: true,
+ Logger: logger.Named("core2"),
})
if err != nil {
t.Fatalf("err: %v", err) | Make manualStepDownCh a 1-buffered channel to ensure StepDown actually steps down in tests. (#<I>) | hashicorp_vault | train |
ad46f07aa09232b31b9561bce115f962ba203884 | diff --git a/lib/util.js b/lib/util.js
index <HASH>..<HASH> 100644
--- a/lib/util.js
+++ b/lib/util.js
@@ -75,7 +75,7 @@ util.catch = function(caught) {
const options = caught.options;
const body = _.get(caught, 'response.body', {});
- if (options.uri.includes('/v2.0/')) {
+ if (caught.response.request.uri.href.includes('/v2.0/')) {
throw new errors.SmartcarErrorV2(body);
} | fix(SmartcarErrorV2): use `request.uri` to determine version (#<I>)
`options.uri` does not contain any portions of the uri that are in the `baseUrl` | smartcar_node-sdk | train |
14e745ddfac155df8a9e942f0b94ed9de80d93d6 | diff --git a/lib/tty/prompt/list.rb b/lib/tty/prompt/list.rb
index <HASH>..<HASH> 100644
--- a/lib/tty/prompt/list.rb
+++ b/lib/tty/prompt/list.rb
@@ -282,16 +282,20 @@ module TTY
# adjust it to the last item, otherwise leave unchanged.
def keyright(*)
if (@active + page_size) <= @choices.size
- @active += page_size
+ searchable = ((@active + page_size)..choices.length)
+ @active = search_choice_in(searchable)
elsif @active <= @choices.size # last page shorter
current = @active % page_size
remaining = @choices.size % page_size
if current.zero? || (remaining > 0 && current > remaining)
- @active = @choices.size
+ searchable = @choices.size.downto(0).to_a
+ @active = search_choice_in(searchable)
elsif @cycle
- @active = current.zero? ? page_size : current
+ searchable = ((current.zero? ? page_size : current)..choices.length)
+ @active = search_choice_in(searchable)
end
end
+
@paging_changed = !@by_page
@by_page = true
end
@@ -299,9 +303,11 @@ module TTY
def keyleft(*)
if (@active - page_size) > 0
- @active -= page_size
+ searchable = ((@active - page_size)..choices.length)
+ @active = search_choice_in(searchable)
elsif @cycle
- @active = @choices.size
+ searchable = @choices.size.downto(1).to_a
+ @active = search_choice_in(searchable)
end
@paging_changed = !@by_page
@by_page = true
diff --git a/spec/unit/select_spec.rb b/spec/unit/select_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/select_spec.rb
+++ b/spec/unit/select_spec.rb
@@ -509,6 +509,47 @@ RSpec.describe TTY::Prompt, '#select' do
expect(prompt.output.string).to eq(expected_output)
end
+
+ it "navigates pages left/right with disabled items" do
+ prompt = TTY::TestPrompt.new
+ prompt.on(:keypress) { |e|
+ prompt.trigger(:keyright) if e.value == "l"
+ prompt.trigger(:keyleft) if e.value == "h"
+ }
+ choices = [
+ {name: '1', disabled: 'out'},
+ '2',
+ {name: '3', disabled: 'out'},
+ '4',
+ '5',
+ {name: '6', disabled: 'out'},
+ '7',
+ '8',
+ '9',
+ {name: '10', disabled: 'out'}
+ ]
+
+ prompt.input << "l" << "l" << "l" << "h" << "h" << "h" << "\r"
+ prompt.input.rewind
+
+ answer = prompt.select("What number?", choices, per_page: 4)
+
+ expect(answer).to eq('2')
+
+ expected_output = [
+ output_helper('What number?', choices[0..3], "2", init: true,
+ hint: 'Use arrow keys, press Enter to select', nav: true),
+ output_helper('What number?', choices[4..7], "7", nav: true),
+ output_helper('What number?', choices[8..9], "9", nav: true),
+ output_helper('What number?', choices[8..9], "9", nav: true),
+ output_helper('What number?', choices[4..7], "5", nav: true),
+ output_helper('What number?', choices[0..3], "2", nav: true),
+ output_helper('What number?', choices[0..3], "2", nav: true),
+ "What number? \e[32m2\e[0m\n\e[?25h"
+ ].join('')
+
+ expect(prompt.output.string).to eq(expected_output)
+ end
end
context 'with :cycle option' do
@@ -606,6 +647,47 @@ RSpec.describe TTY::Prompt, '#select' do
expect(prompt.output.string).to eq(expected_output)
end
+
+ it "cycles pages left/right with disabled items" do
+ prompt = TTY::TestPrompt.new
+ prompt.on(:keypress) { |e|
+ prompt.trigger(:keyright) if e.value == "l"
+ prompt.trigger(:keyleft) if e.value == "h"
+ }
+ choices = [
+ {name: '1', disabled: 'out'},
+ '2',
+ {name: '3', disabled: 'out'},
+ '4',
+ '5',
+ {name: '6', disabled: 'out'},
+ '7',
+ '8',
+ '9',
+ {name: '10', disabled: 'out'}
+ ]
+
+ prompt.input << "l" << "l" << "l" << "h" << "h" << "h" << "\r"
+ prompt.input.rewind
+
+ answer = prompt.select("What number?", choices, per_page: 4, cycle: true)
+
+ expect(answer).to eq('2')
+
+ expected_output = [
+ output_helper('What number?', choices[0..3], "2", init: true,
+ hint: 'Use arrow keys, press Enter to select', nav: true),
+ output_helper('What number?', choices[4..7], "7", nav: true),
+ output_helper('What number?', choices[8..9], "9", nav: true),
+ output_helper('What number?', choices[0..3], "2", nav: true),
+ output_helper('What number?', choices[8..9], "9", nav: true),
+ output_helper('What number?', choices[4..7], "5", nav: true),
+ output_helper('What number?', choices[0..3], "2", nav: true),
+ "What number? \e[32m2\e[0m\n\e[?25h"
+ ].join('')
+
+ expect(prompt.output.string).to eq(expected_output)
+ end
end
it "verifies default index format" do | Change select prompt to navigate left/right around disabled items | piotrmurach_tty-prompt | train |
e740a59ce522dcba8441ebcb59eaae071eb1c6a6 | diff --git a/resmix.js b/resmix.js
index <HASH>..<HASH> 100644
--- a/resmix.js
+++ b/resmix.js
@@ -24,7 +24,8 @@ const reducerFor = (blueprint) => {
const value = parent[k];
const pairs = value && value.pairs;
let matched = false;
- pairs && pairs.forEach(([pattern, reducer]) => {
+ if (pairs) for (let i = 0; i < pairs.length; i++) {
+ let [pattern, reducer] = pairs[i];
if (matched)
return;
if (typeof pattern == 'string')
@@ -56,7 +57,7 @@ const reducerFor = (blueprint) => {
}
matched = true;
}
- });
+ }
if (value && !(value instanceof Recipe) && !value[symbolObservable] && typeof value == 'object') {
const deeperUpdates = updates[k] || (updates[k] = {});
for (let key in value) { | optimization: for loop instead of forEach | hex13_feedbacks | train |
3d803b57ad373feb6be21041a28d99a2c500f5f8 | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -59,13 +59,13 @@ INSTALL_REQUIRES = [
EXTRAS_REQUIRE = {
'all':[
- # for lcdb
+ # for lcdb
'psycopg2-binary',
# for lcfit.mandelagol_fit_magseries
- 'emcee>=3.0',
+ 'emcee==3.0rc1',
'h5py',
- 'batman',
- 'corner'
+ 'batman-package',
+ 'corner',
]
} | setup.py: fix emcee dep, BATMAN is "batman-package" on PyPI not "batman" | waqasbhatti_astrobase | train |
7e79b3521c5e7938b88157b87a51fd25c4b0c6dc | diff --git a/src/Form/Type/BaseStatusType.php b/src/Form/Type/BaseStatusType.php
index <HASH>..<HASH> 100644
--- a/src/Form/Type/BaseStatusType.php
+++ b/src/Form/Type/BaseStatusType.php
@@ -44,8 +44,17 @@ abstract class BaseStatusType extends AbstractType
* @param string $name
* @param bool $flip reverse key/value to match sf2.8 and sf3.0 change
*/
- public function __construct($class, $getter, $name, $flip = false)
+ public function __construct($class, $getter, $name, $flip = null)
{
+ if (null === $flip) {
+ $flip = true;
+ } else {
+ @trigger_error(
+ 'Calling '.__CLASS__.' class with a flip parameter is deprecated since 3.x, to be removed with 4.0',
+ E_USER_DEPRECATED
+ );
+ }
+
$this->class = $class;
$this->getter = $getter;
$this->name = $name;
@@ -81,6 +90,12 @@ abstract class BaseStatusType extends AbstractType
{
$choices = call_user_func([$this->class, $this->getter]);
+ // choice_as_value options is not needed in SF 3.0+
+ if ($resolver->isDefined('choices_as_values')) {
+ $resolver->setDefault('choices_as_values', true);
+ }
+
+ // NEXT_MAJOR: remove this property
if ($this->flip) {
$count = count($choices);
diff --git a/tests/Form/Type/StatusTypeTest.php b/tests/Form/Type/StatusTypeTest.php
index <HASH>..<HASH> 100644
--- a/tests/Form/Type/StatusTypeTest.php
+++ b/tests/Form/Type/StatusTypeTest.php
@@ -61,6 +61,29 @@ class StatusTypeTest extends TypeTestCase
$this->assertTrue(class_exists($parentRef), sprintf('Unable to ensure %s is a FQCN', $parentRef));
}
+ /**
+ * @group legacy
+ */
+ public function testGetDefaultOptionsLegacy()
+ {
+ Choice::$list = [
+ 1 => 'salut',
+ ];
+
+ $type = new StatusType(Choice::class, 'getList', 'choice_type', false);
+
+ $this->assertSame('choice_type', $type->getName());
+
+ $this->assertSame(ChoiceType::class, $type->getParent());
+
+ FormHelper::configureOptions($type, $resolver = new OptionsResolver());
+
+ $options = $resolver->resolve([]);
+
+ $this->assertArrayHasKey('choices', $options);
+ $this->assertSame($options['choices'], [1 => 'salut']);
+ }
+
public function testGetDefaultOptions()
{
Choice::$list = [
@@ -78,7 +101,7 @@ class StatusTypeTest extends TypeTestCase
$options = $resolver->resolve([]);
$this->assertArrayHasKey('choices', $options);
- $this->assertSame($options['choices'], [1 => 'salut']);
+ $this->assertSame($options['choices'], ['salut' => 1]);
}
public function testGetDefaultOptionsWithValidFlip()
@@ -88,7 +111,7 @@ class StatusTypeTest extends TypeTestCase
2 => 'toi!',
];
- $type = new StatusType(Choice::class, 'getList', 'choice_type', true);
+ $type = new StatusType(Choice::class, 'getList', 'choice_type');
$this->assertSame('choice_type', $type->getName());
$this->assertSame(ChoiceType::class, $type->getParent());
@@ -110,13 +133,13 @@ class StatusTypeTest extends TypeTestCase
2 => 'error',
];
- $type = new StatusType(Choice::class, 'getList', 'choice_type', true);
+ $type = new StatusType(Choice::class, 'getList', 'choice_type');
$this->assertSame('choice_type', $type->getName());
$this->assertSame(ChoiceType::class, $type->getParent());
FormHelper::configureOptions($type, $resolver = new OptionsResolver());
- $options = $resolver->resolve([]);
+ $resolver->resolve([]);
}
} | Always flip choices in BaseStatusType (#<I>)
* Always flip choices in BaseStatusType
* Better check for choices_as_values | sonata-project_SonataCoreBundle | train |
3068401315fe42169325c61e0819b815e4df8fef | diff --git a/ansigenome/init.py b/ansigenome/init.py
index <HASH>..<HASH> 100644
--- a/ansigenome/init.py
+++ b/ansigenome/init.py
@@ -7,6 +7,8 @@ import utils as utils
default_mainyml_template = """---
+# role: %repo_name
+
# %values go here
"""
@@ -74,11 +76,15 @@ class Init(object):
create_folder_path = os.path.join(self.output_path, folder)
utils.mkdir_p(create_folder_path)
+ mainyml_template = default_mainyml_template.replace(
+ "%repo_name", self.repo_name)
+ mainyml_template = mainyml_template.replace(
+ "%values", folder)
+
if not folder == "templates" and not folder == "meta":
utils.string_to_file(os.path.join(create_folder_path,
"main.yml"),
- default_mainyml_template.replace(
- "%values", folder))
+ mainyml_template)
def create_tests(self):
"""
diff --git a/test/integration/test_scan.py b/test/integration/test_scan.py
index <HASH>..<HASH> 100644
--- a/test/integration/test_scan.py
+++ b/test/integration/test_scan.py
@@ -54,8 +54,8 @@ class TestScan(unittest.TestCase):
self.assertIn("6 facts", out)
self.assertIn("8 files", out)
self.assertIn("23 files", out)
- self.assertIn("56 lines", out)
- self.assertIn("170 lines", out)
+ self.assertIn("60 lines", out)
+ self.assertIn("182 lines", out)
self.assertEqual(err, "")
if __name__ == "__main__": | Add the role name to the top of the defaults | nickjj_ansigenome | train |
f047b4e1de2061d1de6df3ea12345a19a7a5af88 | diff --git a/iptools/__init__.py b/iptools/__init__.py
index <HASH>..<HASH> 100644
--- a/iptools/__init__.py
+++ b/iptools/__init__.py
@@ -517,6 +517,38 @@ class IpRangeList (object):
"""
return sum(r.__len__() for r in self.ips)
# end __len__
+
+ def __hash__(self):
+ """
+ Return correct hash for IpRangeList object
+
+ >>> a = IpRange('127.0.0.0/8')
+ >>> b = IpRange('127.0.0.0', '127.255.255.255')
+ >>> IpRangeList(a, b).__hash__() == IpRangeList(a, b).__hash__()
+ True
+ >>> IpRangeList(a, b).__hash__() == IpRangeList(b, a).__hash__()
+ True
+ >>> c = IpRange('10.0.0.0/8')
+ >>> IpRangeList(a, c).__hash__() == IpRangeList(c, a).__hash__()
+ False
+ """
+ return hash(self.ips)
+ # end __hash__
+
+ def __eq__(self, other):
+ """
+ >>> a = IpRange('127.0.0.0/8')
+ >>> b = IpRange('127.0.0.0', '127.255.255.255')
+ >>> IpRangeList(a, b) == IpRangeList(a, b)
+ True
+ >>> IpRangeList(a, b) == IpRangeList(b, a)
+ True
+ >>> c = IpRange('10.0.0.0/8')
+ >>> IpRangeList(a, c) == IpRangeList(c, a)
+ False
+ """
+ return hash(self) == hash(other)
+ # end __eq__
# end class IpRangeList
# vim: set sw=4 ts=4 sts=4 et : | Provide methods for comparison of IpRangeList objects | bd808_python-iptools | train |
5fa74f4408bf51b7fc432442e8249c515330f8f8 | diff --git a/salt/fileclient.py b/salt/fileclient.py
index <HASH>..<HASH> 100644
--- a/salt/fileclient.py
+++ b/salt/fileclient.py
@@ -365,11 +365,14 @@ class Client(object):
self.opts['cachedir'], 'localfiles', path.lstrip('|/'))
filesdest = os.path.join(
self.opts['cachedir'], 'files', saltenv, path.lstrip('|/'))
+ extrndest = self._extrn_path(path, saltenv)
if os.path.exists(filesdest):
return salt.utils.url.escape(filesdest) if escaped else filesdest
elif os.path.exists(localsfilesdest):
return salt.utils.url.escape(localsfilesdest) if escaped else localsfilesdest
+ elif os.path.exists(extrndest):
+ return extrndest
return '' | Add back in the extrndest stuff (which is now in develop) | saltstack_salt | train |
eb0c9ac3ec050cf739708d22bdcc1562fc8b0289 | diff --git a/niworkflows/anat/skullstrip.py b/niworkflows/anat/skullstrip.py
index <HASH>..<HASH> 100644
--- a/niworkflows/anat/skullstrip.py
+++ b/niworkflows/anat/skullstrip.py
@@ -6,7 +6,7 @@ from nipype.interfaces import fsl
from nipype.interfaces import utility as niu
from nipype.pipeline import engine as pe
-def afni_wf(name='AFNISkullStripWorkflow'):
+def afni_wf(name='AFNISkullStripWorkflow', n4_nthreads=1):
"""
Skull-stripping workflow
@@ -23,7 +23,8 @@ quality-assessment-protocol/blob/master/qap/anatomical_preproc.py#L105
outputnode = pe.Node(niu.IdentityInterface(
fields=['bias_corrected', 'out_file', 'out_mask', 'bias_image']), name='outputnode')
- inu_n4 = pe.Node(ants.N4BiasFieldCorrection(dimension=3, save_bias=True),
+ inu_n4 = pe.Node(ants.N4BiasFieldCorrection(
+ dimension=3, save_bias=True, num_threads=n4_nthreads), num_threads=n4_nthreads,
name='CorrectINU')
sstrip = pe.Node(afni.SkullStrip(outputtype='NIFTI_GZ'), name='skullstrip') | [ENH] Give access to num_threads of N4BiasFieldCorrection
Defaults to 1 (keep current behavior). N4BiasFieldCorrection is part
of ANTs and the number of threads are controlled in the same way you'd
do with antsRegistration. | poldracklab_niworkflows | train |
a996fd198608cf0daeed36f979fe44af2b400871 | diff --git a/src/tools/agepyramid/agepyramid-component.js b/src/tools/agepyramid/agepyramid-component.js
index <HASH>..<HASH> 100644
--- a/src/tools/agepyramid/agepyramid-component.js
+++ b/src/tools/agepyramid/agepyramid-component.js
@@ -790,7 +790,7 @@ var AgePyramid = Component.extend({
}
};
- var presentationProfileChanges = {
+ this.presentationProfileChanges = {
medium: {
margin: { right: 80, bottom: 80 },
infoElHeight: 32 | Make agepyramid presentationProfileChanges editable from outside | vizabi_vizabi | train |
3d77a06fadedf1fede54666c9531c1b77612ef5b | diff --git a/src/pybel/constants.py b/src/pybel/constants.py
index <HASH>..<HASH> 100644
--- a/src/pybel/constants.py
+++ b/src/pybel/constants.py
@@ -149,6 +149,19 @@ CITATION_AUTHORS = 'authors'
#: Represents the key for the citation comment in a citation dictionary
CITATION_COMMENTS = 'comments'
+#: Represents the key for the optional PyBEL citation title entry in a citation dictionary
+CITATION_TITLE = 'title'
+#: Represents the key for the optional PyBEL citation volume entry in a citation dictionary
+CITATION_VOLUME = 'volume'
+#: Represents the key for the optional PyBEL citation issue entry in a citation dictionary
+CITATION_ISSUE = 'issue'
+#: Represents the key for the optional PyBEL citation pages entry in a citation dictionary
+CITATION_PAGES = 'pages'
+#: Represents the key for the optional PyBEL citation first author entry in a citation dictionary
+CITATION_FIRST_AUTHOR = 'first'
+#: Represents the key for the optional PyBEL citation last author entry in a citation dictionary
+CITATION_LAST_AUTHOR = 'last'
+
#: Represents the ordering of the citation entries in a control statement (SET Citation = ...)
CITATION_ENTRIES = CITATION_TYPE, CITATION_NAME, CITATION_REFERENCE, CITATION_DATE, CITATION_AUTHORS, CITATION_COMMENTS
diff --git a/src/pybel/manager/models.py b/src/pybel/manager/models.py
index <HASH>..<HASH> 100644
--- a/src/pybel/manager/models.py
+++ b/src/pybel/manager/models.py
@@ -637,7 +637,7 @@ class Author(Base):
__tablename__ = AUTHOR_TABLE_NAME
id = Column(Integer, primary_key=True)
- name = Column(String(255), nullable=False, index=True)
+ name = Column(String(255), nullable=False, unique=True, index=True)
def __str__(self):
return self.name
@@ -689,15 +689,30 @@ class Citation(Base):
if self.name:
result[CITATION_NAME] = self.name
+ if self.title:
+ result[CITATION_TITLE] = self.title
+
+ if self.volume:
+ result[CITATION_VOLUME] = self.volume
+
+ if self.pages:
+ result[CITATION_PAGES] = self.pages
+
+ if self.date:
+ result[CITATION_DATE] = self.date.strftime('%Y-%m-%d')
+
+ if self.first:
+ result[CITATION_FIRST_AUTHOR] = self.first
+
+ if self.last:
+ result[CITATION_LAST_AUTHOR] = self.last
+
if self.authors:
result[CITATION_AUTHORS] = "|".join(sorted(
author.name
for author in self.authors
))
- if self.date:
- result[CITATION_DATE] = self.date.strftime('%Y-%m-%d')
-
return result | Update author model
- update to_json
- Make author name unique
- add constants | pybel_pybel | train |
99cd56c1bcd7aa435d103b7910c1b8fb1d0d9ebb | diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -29,6 +29,7 @@ export { Map };
export { MapTool, DrawTool, AreaTool, DistanceTool } from './map/tool';
export { default as SpatialReference } from './map/spatial-reference/SpatialReference';
import './map/spatial-reference/SpatialReference.Arc';
+import './map/spatial-reference/SpatialReference.WMTS';
/** @namespace ui */
import * as ui from './ui'; | wmts append to export | maptalks_maptalks.js | train |
b617f79ad73038fc06611632e3b9f7c139abf302 | diff --git a/phoebe-testlib/1to2/1to2.py b/phoebe-testlib/1to2/1to2.py
index <HASH>..<HASH> 100644
--- a/phoebe-testlib/1to2/1to2.py
+++ b/phoebe-testlib/1to2/1to2.py
@@ -1,7 +1,9 @@
import phoebeBackend as phb
import scipy.stats as st
import numpy as np
+import time
import phoebe as phb2
+from phoebe.io import parsers
# Initialize Phoebe1 and Phoebe2
@@ -37,19 +39,23 @@ mybundle.set_value('teff@secondary', phb.getpar('phoebe_teff2'))
# Report
print("# Qual = Phoebe1 -- Phoebe2")
-print("# pot1 = %f -- %f" % phb.getpar("phoebe_pot1"),mybundle.get_value('pot@primary'))
-print("# pot2 = %f -- %f" % phb.getpar("phoebe_pot2"),mybundle.get_value('pot@secondary'))
-print("# incl = %f -- %f" % phb.getpar("phoebe_incl"),mybundle.get_value('incl'))
-print("# ecc = %f -- %f" % phb.getpar("phoebe_ecc"),mybundle.get_value('ecc'))
-print("# per0 = %f -- %f" % phb.getpar("phoebe_perr0"),mybundle.get_value('perr0'))
-print("# rm = %f -- %f" % phb.getpar("phoebe_rm"),mybundle.get_value('rm'))
-print("# T2 = %f -- %f" % phb.getpar("phoebe_teff2"),mybundle.get_value('teff@secondary'))
+print("# pot1 = %f -- %f" % (phb.getpar("phoebe_pot1"), mybundle.get_value('pot@primary')))
+print("# pot2 = %f -- %f" % (phb.getpar("phoebe_pot2"), mybundle.get_value('pot@secondary')))
+print("# incl = %f -- %f" % (phb.getpar("phoebe_incl"), mybundle.get_value('incl')))
+print("# ecc = %f -- %f" % (phb.getpar("phoebe_ecc"), mybundle.get_value('ecc')))
+print("# per0 = %f -- %f" % (phb.getpar("phoebe_perr0"), mybundle.get_value('per0')))
+print("# rm = %f -- %f" % (phb.getpar("phoebe_rm"), mybundle.get_value('q')))
+print("# T2 = %f -- %f" % (phb.getpar("phoebe_teff2"), mybundle.get_value('teff@secondary')))
# Template phases
ph = np.linspace(-0.5, 0.5, 201)
# Compute a phase curve with Phoebe1
+print("# Computing phoebe 1 light curve.")
+ts = time.time()
lc_ph1 = phb.lc(tuple(ph.tolist()), 0)
+te = time.time()
+print("# Execution time: %3.3f seconds" % ((te-ts)))
# Compute a phase curve with Phoebe2
mybundle.create_syn(category='lc', phase=ph) | Fixed print() statements, and implemented quick'n'dirty timing. | phoebe-project_phoebe2 | train |
7320154652870adc560ca0524ff05373d5d359cd | diff --git a/lib/modules/apostrophe-schemas/public/js/array-modal.js b/lib/modules/apostrophe-schemas/public/js/array-modal.js
index <HASH>..<HASH> 100644
--- a/lib/modules/apostrophe-schemas/public/js/array-modal.js
+++ b/lib/modules/apostrophe-schemas/public/js/array-modal.js
@@ -259,7 +259,7 @@ apos.define('apostrophe-array-editor-modal', {
// This method removes the item with the specified `id` property from the
// array.
- self.remove = function(_id) {
+ self.remove = function(id) {
self.arrayItems = _.filter(self.arrayItems, function(choice) {
return choice.id !== id;
}); | oops fixed typo, remove works again in this PR | apostrophecms_apostrophe | train |
35f2655a64375b2e6dabd2699978f601452a63d5 | diff --git a/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/simple/rfc5626/RFC5626KeepAliveSipServletTest.java b/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/simple/rfc5626/RFC5626KeepAliveSipServletTest.java
index <HASH>..<HASH> 100644
--- a/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/simple/rfc5626/RFC5626KeepAliveSipServletTest.java
+++ b/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/simple/rfc5626/RFC5626KeepAliveSipServletTest.java
@@ -223,6 +223,32 @@ public class RFC5626KeepAliveSipServletTest extends SipServletTestCase {
assertEquals(1, receiver.getAllMessagesContent().size());
}
+ // making sure that we don't receive one timeout per Connection Based Transport Connector
+ public void testShootistTimeoutMultipleListeningPoints() throws Exception {
+ ((SIPTransactionStack)tomcat.getSipService().getSipStack()).setReliableConnectionKeepAliveTimeout(2200);
+ ((SIPTransactionStack)tomcatShootist.getSipService().getSipStack()).setReliableConnectionKeepAliveTimeout(2200);
+
+ tomcat.addSipConnector(serverName, "" + System.getProperty("org.mobicents.testsuite.testhostaddr"), 6090, ListeningPoint.TLS);
+ tomcatShootist.addSipConnector(serverName, "" + System.getProperty("org.mobicents.testsuite.testhostaddr"), 6091, ListeningPoint.TLS);
+ Map<String, String> params = new HashMap<String, String>();
+ deployShootme(params);
+ params = new HashMap<String, String>();
+ params.put("host", "" + System.getProperty("org.mobicents.testsuite.testhostaddr") + ":" + sipConnector.getPort()+";transport=tcp;");
+ params.put("noBye", "true");
+ params.put("testKeepAlive", "100");
+ deployShootist(params);
+ Thread.sleep(TIMEOUT);
+ tomcat.stopTomcat();
+ Thread.sleep(TIMEOUT/2);
+ Iterator<String> allMessagesIterator = receiver.getAllMessagesContent().iterator();
+ while (allMessagesIterator.hasNext()) {
+ String message = (String) allMessagesIterator.next();
+ logger.info(message);
+ }
+ assertTrue("shootist onKeepAliveTimeout", receiver.getAllMessagesContent().contains("shootist onKeepAliveTimeout"));
+ assertEquals(1, receiver.getAllMessagesContent().size());
+ }
+
public void testShootistModifyKeepAliveTimeout() throws InterruptedException, SipException, ParseException, InvalidArgumentException {
((SIPTransactionStack)tomcat.getSipService().getSipStack()).setReliableConnectionKeepAliveTimeout(2200);
((SIPTransactionStack)tomcatShootist.getSipService().getSipStack()).setReliableConnectionKeepAliveTimeout(2200); | Adding non regression test for multiple LP Notifications
(cherry picked from commit e<I>cdc<I>e<I>e<I>b<I>b5c<I>aa<I>e9e<I>cf) | RestComm_sip-servlets | train |
ce5e9d62b80496327397e814478ce902b414a895 | diff --git a/lib/client.js b/lib/client.js
index <HASH>..<HASH> 100644
--- a/lib/client.js
+++ b/lib/client.js
@@ -38,7 +38,7 @@ class Parser extends HTTPParser {
this.client = client
this.socket = socket
- this.resume = () => socket.resume()
+ this.resumeSocket = () => socket.resume()
this.read = 0
this.body = null
}
@@ -99,7 +99,7 @@ class Parser extends HTTPParser {
}
dispatch (request, statusCode, headers) {
- const { resume } = this
+ const { resumeSocket } = this
const { callback, factory } = request
request.callback = null
request.factory = null
@@ -109,14 +109,14 @@ class Parser extends HTTPParser {
try {
body = factory({ statusCode, headers })
if (body) {
- body.on('drain', resume)
+ body.on('drain', resumeSocket)
finished(body, { readable: false }, (err) => {
if (!body.destroyed) {
body.destroy(err)
assert(body.destroyed)
}
if (err) {
- process.nextTick(resume)
+ process.nextTick(resumeSocket)
}
callback(err, null)
})
@@ -137,13 +137,13 @@ class Parser extends HTTPParser {
} else {
body = new Readable({
autoDestroy: true,
- read: resume,
+ read: resumeSocket,
destroy (err, cb) {
if (!err && !this._readableState.endEmitted) {
err = new Error('aborted')
}
if (err) {
- process.nextTick(resume)
+ process.nextTick(resumeSocket)
}
cb(err, null)
}
@@ -156,9 +156,9 @@ class Parser extends HTTPParser {
}
next () {
- const { client, socket } = this
+ const { client, resumeSocket } = this
- socket.resume()
+ resumeSocket()
client[kQueue][client[kComplete]++] = null | refactor: avoid confusion between resume(client) and socket.resume | mcollina_undici | train |
19bdedbe9f13d94c092e94829f6ef9f6232292be | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index <HASH>..<HASH> 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -18,6 +18,7 @@ Added
(#63).
* Add support for ``yesterday`` and ``today`` values for date options.
* Add support for partial ranges for date options.
+* Add argument to ``edit`` command to set which file should be edited (#49).
Changed
-------
diff --git a/taxi/commands/edit.py b/taxi/commands/edit.py
index <HASH>..<HASH> 100644
--- a/taxi/commands/edit.py
+++ b/taxi/commands/edit.py
@@ -4,39 +4,55 @@ import click
from ..settings import Settings
from ..timesheet.parser import ParseError
+from ..timesheet.utils import get_files
from .base import cli, get_timesheet_collection_for_context
@cli.command(short_help="Open the entries file in your editor.")
[email protected]('-f', '--file', 'f', type=click.Path(dir_okay=False),
[email protected]('-f', '--file', 'file_to_edit', type=click.Path(dir_okay=False),
help="Path to the file to edit.")
[email protected]('previous_file', default=0, type=click.IntRange(min=0))
@click.pass_context
-def edit(ctx, f):
+def edit(ctx, file_to_edit, previous_file):
"""
Usage: edit
Opens your zebra file in your favourite editor.
+ The PREVIOUS_FILE argument can be used to specify which nth previous file
+ to edit. A value of 1 will edit the previous file, 2 will edit the
+ second-previous file, etc.
+
+ If the --file option is used, it will take precedence on the PREVIOUS_FILE
+ argument.
+
"""
timesheet_collection = None
+ forced_file = bool(file_to_edit) or previous_file != 0
- try:
- timesheet_collection = get_timesheet_collection_for_context(ctx, f)
- except ParseError:
- pass
+ # If the file was not specified and if it's the current file, autofill it
+ if not forced_file:
+ try:
+ timesheet_collection = get_timesheet_collection_for_context(ctx)
+ except ParseError:
+ pass
+ else:
+ t = timesheet_collection.timesheets[0]
- if timesheet_collection:
- t = timesheet_collection.timesheets[0]
+ if (ctx.obj['settings'].get('auto_add') !=
+ Settings.AUTO_ADD_OPTIONS['NO']):
+ auto_fill_days = ctx.obj['settings'].get_auto_fill_days()
+ if auto_fill_days:
+ t.prefill(auto_fill_days, limit=None)
- if (ctx.obj['settings'].get('auto_add') !=
- Settings.AUTO_ADD_OPTIONS['NO'] and not f):
- auto_fill_days = ctx.obj['settings'].get_auto_fill_days()
- if auto_fill_days:
- t.prefill(auto_fill_days, limit=None)
+ t.file.write(t.entries)
- t.file.write(t.entries)
+ # Get the path to the file we should open in the editor
+ if not file_to_edit:
+ timesheet_files = get_files(ctx.obj['settings'].get('file'),
+ previous_file)
+ file_to_edit = list(timesheet_files)[previous_file]
- file_to_edit = f if f else ctx.obj['settings'].get_entries_file_path()
editor = ctx.obj['settings'].get('editor', default_value='')
edit_kwargs = {
'filename': file_to_edit,
@@ -48,7 +64,11 @@ def edit(ctx, f):
click.edit(**edit_kwargs)
try:
- timesheet_collection = get_timesheet_collection_for_context(ctx, f)
+ # Show the status only for the given file if it was specified with the
+ # --file option, or for the files specified in the settings otherwise
+ timesheet_collection = get_timesheet_collection_for_context(
+ ctx, file_to_edit if forced_file else None
+ )
except ParseError as e:
ctx.obj['view'].err(e)
else:
diff --git a/tests/commands/test_edit.py b/tests/commands/test_edit.py
index <HASH>..<HASH> 100644
--- a/tests/commands/test_edit.py
+++ b/tests/commands/test_edit.py
@@ -83,3 +83,30 @@ alias_1 2 hello world
self.assertEqual('20/02/2014\n', lines[0])
self.assertEqual('21/02/2014\n', lines[3])
+
+ def test_previous_file_argument(self):
+ config = self.default_config.copy()
+ tmp_entries_dir = tempfile.mkdtemp()
+ os.remove(self.entries_file)
+
+ self.entries_file = os.path.join(tmp_entries_dir, '%m_%Y.txt')
+ config['default']['file'] = self.entries_file
+
+ with freeze_time('2014-01-21'):
+ self.write_entries("""20/01/2014
+alias_1 2 hello world
+
+21/01/2014
+alias_1 1 foo bar
+""")
+
+ with freeze_time('2014-02-21'):
+ self.write_entries("""20/02/2014
+alias_1 2 hello world
+""")
+ self.run_command('edit', args=['1'], config_options=config)
+
+ with open(expand_filename(self.entries_file), 'r') as f:
+ lines = f.readlines()
+
+ self.assertNotIn('20/20/2014\n', lines) | Add argument to edit command to edit previous files (fixes #<I>) | liip_taxi | train |
576e8bc4c999357e18974379d93b3ff2004e04f7 | diff --git a/lib/ddr/antivirus/version.rb b/lib/ddr/antivirus/version.rb
index <HASH>..<HASH> 100644
--- a/lib/ddr/antivirus/version.rb
+++ b/lib/ddr/antivirus/version.rb
@@ -1,5 +1,5 @@
module Ddr
module Antivirus
- VERSION = "1.0.1"
+ VERSION = "1.0.2"
end
end | Bumped version to <I> | duke-libraries_ddr-antivirus | train |
5cb304d80aa7dc98922b8011ed93d68152148e42 | diff --git a/src/lightncandy.php b/src/lightncandy.php
index <HASH>..<HASH> 100644
--- a/src/lightncandy.php
+++ b/src/lightncandy.php
@@ -438,35 +438,47 @@ $libstr
*
* @codeCoverageIgnore
*/
- public static function readPartial($name, &$context) {
+ protected static function readPartial($name, &$context) {
$context['usedFeature']['partial']++;
if (isset($context['usedPartial'][$name])) {
return;
}
+ $fn = self::resolvePartial($name, $context);
+
+ if ($fn) {
+ $code = self::compilePartial($name, $context, $fn);
+ return;
+ }
+
+ if (!$context['flags']['skippartial']) {
+ $context['error'][] = "can not find partial file for '$name', you should set correct basedir and fileext in options";
+ }
+ }
+
+ protected static function resolvePartial(&$name, &$context) {
foreach ($context['basedir'] as $dir) {
foreach ($context['fileext'] as $ext) {
$fn = "$dir/$name$ext";
if (file_exists($fn)) {
- $context['usedPartial'][$name] = addcslashes(file_get_contents($fn), "'");
- if ($context['flags']['runpart']) {
- $code = self::compileTemplate($context, $context['usedPartial'][$name], $name);
- if ($context['flags']['mustpi']) {
- $sp = ', $sp';
- $code = preg_replace('/\n\r?([^\r\n])/s', "\n'{$context['ops']['seperator']}\$sp{$context['ops']['seperator']}'\$1", $code);
- } else {
- $sp = '';
- }
- $context['partialCode'] .= "'$name' => function (\$cx, \$in{$sp}) {{$context['ops']['op_start']}'$code'{$context['ops']['op_end']}},";
- }
- return;
+ return $fn;
}
}
}
+ }
- if (!$context['flags']['skippartial']) {
- $context['error'][] = "can not find partial file for '$name', you should set correct basedir and fileext in options";
+ protected static function compilePartial(&$name, &$context, $filename) {
+ $context['usedPartial'][$name] = addcslashes(file_get_contents($filename), "'");
+ if ($context['flags']['runpart']) {
+ $code = self::compileTemplate($context, $context['usedPartial'][$name], $name);
+ if ($context['flags']['mustpi']) {
+ $sp = ', $sp';
+ $code = preg_replace('/\n\r?([^\r\n])/s', "\n'{$context['ops']['seperator']}\$sp{$context['ops']['seperator']}'\$1", $code);
+ } else {
+ $sp = '';
+ }
+ $context['partialCode'] .= "'$name' => function (\$cx, \$in{$sp}) {{$context['ops']['op_start']}'$code'{$context['ops']['op_end']}},";
}
} | start to implement #<I> . not documented now | zordius_lightncandy | train |
3a23bd0460d34383538d687120377a102b0a2200 | diff --git a/src/org/danann/cernunnos/runtime/web/CernunnosPortlet.java b/src/org/danann/cernunnos/runtime/web/CernunnosPortlet.java
index <HASH>..<HASH> 100644
--- a/src/org/danann/cernunnos/runtime/web/CernunnosPortlet.java
+++ b/src/org/danann/cernunnos/runtime/web/CernunnosPortlet.java
@@ -187,7 +187,7 @@ public class CernunnosPortlet extends GenericPortlet {
rrr.setAttribute(WebAttributes.RESPONSE, res);
// Anything that should be included from the spring_context?
- if (spring_context != null) {
+ if (spring_context != null && spring_context.containsBean("requestAttributes")) {
Map<String,Object> requestAttributes = (Map<String,Object>) spring_context.getBean("requestAttributes");
for (Map.Entry entry : requestAttributes.entrySet()) {
rrr.setAttribute((String) entry.getKey(), entry.getValue()); | Fix bug that occurs when there is no 'requestAttributes' bean defined.
git-svn-id: <URL> | drewwills_cernunnos | train |
550823e000d87c96b51e262872a930d8987112e4 | diff --git a/tests/phpunit/unit/Filesystem/Plugin/ThumbnailUrlTest.php b/tests/phpunit/unit/Filesystem/Plugin/ThumbnailUrlTest.php
index <HASH>..<HASH> 100644
--- a/tests/phpunit/unit/Filesystem/Plugin/ThumbnailUrlTest.php
+++ b/tests/phpunit/unit/Filesystem/Plugin/ThumbnailUrlTest.php
@@ -1,11 +1,12 @@
<?php
+
namespace Bolt\Tests\Filesystem\Plugin;
+use Bolt\Filesystem\Adapter\Local;
+use Bolt\Filesystem\Filesystem;
use Bolt\Filesystem\Manager;
use Bolt\Filesystem\Plugin;
use Bolt\Tests\BoltUnitTest;
-use League\Flysystem\Adapter\Local;
-use League\Flysystem\Filesystem;
class ThumbnailUrlTest extends BoltUnitTest
{
@@ -16,7 +17,7 @@ class ThumbnailUrlTest extends BoltUnitTest
$adapter = new Local(PHPUNIT_ROOT . '/resources');
$fs = new Filesystem($adapter);
- $manager = new Manager($app);
+ $manager = new Manager([]);
$manager->mountFilesystem('files', $fs);
$manager->addPlugin(new Plugin\ThumbnailUrl($app)); | [Tests] Update ThumbnailUrlTest | bolt_bolt | train |
e222275451194b856a6ffdd4085241bd795a89ef | diff --git a/gwpy/plotter/segments.py b/gwpy/plotter/segments.py
index <HASH>..<HASH> 100644
--- a/gwpy/plotter/segments.py
+++ b/gwpy/plotter/segments.py
@@ -293,7 +293,7 @@ class SegmentAxes(TimeSeriesAxes):
else:
coll._ignore = False
coll._ypos = y
- return self.add_collection(coll)
+ out = self.add_collection(coll)
else:
out = []
for p in patches:
@@ -301,7 +301,8 @@ class SegmentAxes(TimeSeriesAxes):
p.set_rasterized(rasterized)
label = ''
out.append(self.add_patch(p))
- return out
+ self.autoscale(axis='y')
+ return out
@auto_refresh
def plot_segmentlistdict(self, segmentlistdict, y=None, dy=1, **kwargs): | SegmentAxes: added autoscale | gwpy_gwpy | train |
6daeb1687004c083d4e3cc72e883b0cab328eae2 | diff --git a/spec/unit/application/agent_spec.rb b/spec/unit/application/agent_spec.rb
index <HASH>..<HASH> 100755
--- a/spec/unit/application/agent_spec.rb
+++ b/spec/unit/application/agent_spec.rb
@@ -5,6 +5,7 @@ require File.dirname(__FILE__) + '/../../spec_helper'
require 'puppet/agent'
require 'puppet/application/agent'
require 'puppet/network/server'
+require 'puppet/network/handler'
require 'puppet/daemon'
describe Puppet::Application::Agent do
diff --git a/spec/unit/network/xmlrpc/client_spec.rb b/spec/unit/network/xmlrpc/client_spec.rb
index <HASH>..<HASH> 100755
--- a/spec/unit/network/xmlrpc/client_spec.rb
+++ b/spec/unit/network/xmlrpc/client_spec.rb
@@ -1,4 +1,5 @@
#!/usr/bin/env ruby
+require 'puppet/network/client'
Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } | maint: Fix a test that was missing a require
Paired-with: Nick Lewis | puppetlabs_puppet | train |
Subsets and Splits