hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
948297a4680d463e9b1b5aa59073b7f1f9cb1a5a
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -92,6 +92,11 @@ module.exports = function (onSelect) {
var _display
d.fullscreen = function (full) {
menu.style.display = full ? 'none' : null
+ return full
+ }
+
+ d.isFullscreen = function () {
+ return menu.style.display === 'none'
}
return d
@@ -99,3 +104,6 @@ module.exports = function (onSelect) {
+
+
+
|
isFullscreen to get current state
|
hyperhype_hypertabs
|
train
|
90454c12b8bc314b77278aa963b85985791a6377
|
diff --git a/sklearn2pmml/pipeline/__init__.py b/sklearn2pmml/pipeline/__init__.py
index <HASH>..<HASH> 100644
--- a/sklearn2pmml/pipeline/__init__.py
+++ b/sklearn2pmml/pipeline/__init__.py
@@ -37,9 +37,10 @@ def _get_values(X):
class PMMLPipeline(Pipeline):
- def __init__(self, steps, predict_transformer = None):
+ def __init__(self, steps, predict_transformer = None, predict_proba_transformer = None):
super(PMMLPipeline, self).__init__(steps = steps)
self.predict_transformer = predict_transformer
+ self.predict_proba_transformer = predict_proba_transformer
def __repr__(self):
class_name = self.__class__.__name__
@@ -65,6 +66,13 @@ class PMMLPipeline(Pipeline):
return numpy.hstack((y_pred, y_predt))
return y_pred
+ def predict_proba_transform(self, X):
+ y_proba = self.predict_proba(X)
+ if self.predict_proba_transformer is not None:
+ y_probat = self.predict_proba_transformer.transform(y_proba)
+ return numpy.hstack((y_proba, y_probat))
+ return y_proba
+
def configure(self, **pmml_options):
if len(pmml_options) > 0:
estimator = self._final_estimator
diff --git a/sklearn2pmml/pipeline/tests/__init__.py b/sklearn2pmml/pipeline/tests/__init__.py
index <HASH>..<HASH> 100644
--- a/sklearn2pmml/pipeline/tests/__init__.py
+++ b/sklearn2pmml/pipeline/tests/__init__.py
@@ -1,5 +1,5 @@
from pandas import DataFrame, Series
-from sklearn.dummy import DummyRegressor
+from sklearn.dummy import DummyClassifier, DummyRegressor
from sklearn.pipeline import FeatureUnion
from sklearn.preprocessing import FunctionTransformer
from sklearn.tree import DecisionTreeRegressor
@@ -34,6 +34,18 @@ class PMMLPipelineTest(TestCase):
self.assertEquals(y_pred, pipeline.predict(X).tolist())
self.assertEquals([y_predt for i in range(0, 3)], pipeline.predict_transform(X).tolist())
+ def test_predict_proba_transform(self):
+ predict_proba_transformer = FunctionTransformer(numpy.log)
+ pipeline = PMMLPipeline([("estimator", DummyClassifier(strategy = "prior"))], predict_proba_transformer = predict_proba_transformer)
+ X = DataFrame([1.0, 1.0, 1.0, 1.0, 1.0, 1.0], columns = ["x"])
+ y = Series(["green", "red", "yellow", "green", "red", "green"], name = "y")
+ pipeline.fit(X, y)
+ self.assertEquals(["green", "red", "yellow"], pipeline._final_estimator.classes_.tolist())
+ y_proba = [3 / 6.0, 2 / 6.0, 1 / 6.0]
+ y_probat = [numpy.log(x) for x in y_proba]
+ self.assertEquals([y_proba for i in range(0, 6)], pipeline.predict_proba(X).tolist())
+ self.assertEquals([y_proba + y_probat for i in range(0, 6)], pipeline.predict_proba_transform(X).tolist())
+
def test_configure(self):
regressor = DecisionTreeRegressor()
pipeline = PMMLPipeline([("regressor", regressor)])
|
Added 'PMMLPipeline.predict_proba_transformer' attribute
|
jpmml_sklearn2pmml
|
train
|
1dcf018df7a860f67f255bef347eb024d007348e
|
diff --git a/salt/utils/aws.py b/salt/utils/aws.py
index <HASH>..<HASH> 100644
--- a/salt/utils/aws.py
+++ b/salt/utils/aws.py
@@ -87,7 +87,9 @@ def creds(provider):
proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT,
)
result.raise_for_status()
- role = result.text.encode(result.encoding or 'utf-8')
+ role = result.text.encode(
+ result.encoding if result.encoding else 'utf-8'
+ )
except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError):
return provider['id'], provider['key'], ''
@@ -460,7 +462,9 @@ def query(params=None, setname=None, requesturl=None, location=None,
)
LOG.trace(
'AWS Response Text: {0}'.format(
- result.text.encode(result.encoding or 'utf-8')
+ result.text.encode(
+ result.encoding if result.encoding else 'utf-8'
+ )
)
)
result.raise_for_status()
@@ -501,7 +505,9 @@ def query(params=None, setname=None, requesturl=None, location=None,
return {'error': data}, requesturl
return {'error': data}
- response = result.text.encode(result.encoding or 'utf-8')
+ response = result.text.encode(
+ result.encoding if result.encoding else 'utf-8'
+ )
root = ET.fromstring(response)
items = root[1]
|
requests api says Response.encoding can sometimes be None <URL> doesn't accept None and expects a string.
this change prevents wrong-type runtime exceptions and defaults the encoding back to 'utf-8' (the default prior to PR#<I>
|
saltstack_salt
|
train
|
fa31e12a3c6d25cc8a545b9d3776701d1bfa9658
|
diff --git a/generators/app/conf.js b/generators/app/conf.js
index <HASH>..<HASH> 100644
--- a/generators/app/conf.js
+++ b/generators/app/conf.js
@@ -8,7 +8,7 @@ module.exports = function systemConf(options) {
};
if (options.js === 'typescript') {
- conf.transpiler = 'typescript';
+ conf.transpiler = 'ts';
conf.typescriptOptions = {
sourceMap: true,
emitDecoratorMetadata: true,
diff --git a/generators/app/index.js b/generators/app/index.js
index <HASH>..<HASH> 100644
--- a/generators/app/index.js
+++ b/generators/app/index.js
@@ -42,7 +42,7 @@ module.exports = fountain.Base.extend({
}
}
if (this.options.js === 'typescript') {
- packageJson.jspm.dependencies.typescript = 'npm:typescript@^1.8.7';
+ packageJson.jspm.dependencies.ts = 'github:frankwallis/plugin-typescript@4.0.16';
}
return packageJson;
diff --git a/test/app/conf.js b/test/app/conf.js
index <HASH>..<HASH> 100644
--- a/test/app/conf.js
+++ b/test/app/conf.js
@@ -12,7 +12,7 @@ const conf = {
};
const typescriptBase = {
- transpiler: 'typescript',
+ transpiler: 'ts',
typescriptOptions: {
sourceMap: true,
emitDecoratorMetadata: true,
diff --git a/test/app/index.js b/test/app/index.js
index <HASH>..<HASH> 100644
--- a/test/app/index.js
+++ b/test/app/index.js
@@ -39,7 +39,7 @@ test(`Move dependencies to jspm from 'package.json'`, t => {
jspm: {
dependencies: {
angular: 'npm:angular@^1.5.0',
- typescript: 'npm:typescript@^1.8.7'
+ ts: 'github:frankwallis/plugin-typescript@4.0.16'
},
devDependencies: {'angular-mocks': 'npm:angular-mocks@^1.5.0'}
}
|
Use plugin-typescript instead of microsoft typescript (recommended since jspm <I>)
|
FountainJS_generator-fountain-systemjs
|
train
|
28650555320a7df2e92c8a3d64786e27b50b8354
|
diff --git a/openstack_dashboard/dashboards/project/loadbalancers/tables.py b/openstack_dashboard/dashboards/project/loadbalancers/tables.py
index <HASH>..<HASH> 100644
--- a/openstack_dashboard/dashboards/project/loadbalancers/tables.py
+++ b/openstack_dashboard/dashboards/project/loadbalancers/tables.py
@@ -312,6 +312,15 @@ STATUS_DISPLAY_CHOICES = (
class PoolsTable(tables.DataTable):
+ METHOD_DISPLAY_CHOICES = (
+ ("round_robin", pgettext_lazy("load balancing method",
+ u"Round Robin")),
+ ("least_connections", pgettext_lazy("load balancing method",
+ u"Least Connections")),
+ ("source_ip", pgettext_lazy("load balancing method",
+ u"Source IP")),
+ )
+
name = tables.Column("name_or_id",
verbose_name=_("Name"),
link="horizon:project:loadbalancers:pooldetails")
@@ -320,6 +329,9 @@ class PoolsTable(tables.DataTable):
filters=(lambda v: filters.default(v, _('N/A')),))
subnet_name = tables.Column('subnet_name', verbose_name=_("Subnet"))
protocol = tables.Column('protocol', verbose_name=_("Protocol"))
+ method = tables.Column('lb_method',
+ verbose_name=_("LB Method"),
+ display_choices=METHOD_DISPLAY_CHOICES)
status = tables.Column('status',
verbose_name=_("Status"),
status=True,
|
LB method column is added in pools table
In load balancer pools table load balancing method column missing.
This patch adding the LB method column in pools table.
Change-Id: I<I>bd<I>d<I>f1bb3f<I>c8e8ddec<I>defc8b<I>e0
Closes-Bug: #<I>
|
openstack_horizon
|
train
|
3cf20e81f652e15768597610229915632e44a521
|
diff --git a/user_sessions/admin.py b/user_sessions/admin.py
index <HASH>..<HASH> 100644
--- a/user_sessions/admin.py
+++ b/user_sessions/admin.py
@@ -51,6 +51,7 @@ class SessionAdmin(admin.ModelAdmin):
list_display = 'ip', 'user', 'is_valid', 'location', 'device',
search_fields = ()
list_filter = ExpiredFilter, OwnerFilter
+ raw_id_fields = 'user',
def __init__(self, *args, **kwargs):
super(SessionAdmin, self).__init__(*args, **kwargs)
|
Fixed #<I> -- Use raw_id_fields for foreign key to user
|
Bouke_django-user-sessions
|
train
|
650ff593940fcd52ab8052199f931a87bac09b8d
|
diff --git a/Makefile b/Makefile
index <HASH>..<HASH> 100644
--- a/Makefile
+++ b/Makefile
@@ -59,6 +59,9 @@ deps/glyphicons_free:
unzip glyphicons_free.zip
touch $@
+external/fast_backward.png: external deps/glyphicons_free
+ cp deps/glyphicons_free/glyphicons/png/glyphicons_171_fast_backward.png external/fast_backward.png
+
external/fast_forward.png: external deps/glyphicons_free
cp deps/glyphicons_free/glyphicons/png/glyphicons_177_fast_forward.png external/fast_forward.png
@@ -80,6 +83,7 @@ download_deps: external/jsnes.src.js \
external/codemirror.js \
external/codemirror.css \
external/jquery-1.7.2.min.js \
+ external/fast_backward.png \
external/fast_forward.png
#TODO add bootstrap that way
diff --git a/src/init.js b/src/init.js
index <HASH>..<HASH> 100644
--- a/src/init.js
+++ b/src/init.js
@@ -144,8 +144,8 @@ palette.addColorChangeListener(pixel_editor);
color_picker.addColorChangeListener(palette);
-selector.addNextPageButton("fast_forward.png", 440,310);
-
+selector.addPreviousPageButton("fast_backward.png", 440,315);
+selector.addNextPageButton("fast_forward.png", 475,315);
function getCursorPosition(canvas, event) {
var totalOffsetX = 0;
diff --git a/src/ui.js b/src/ui.js
index <HASH>..<HASH> 100644
--- a/src/ui.js
+++ b/src/ui.js
@@ -200,7 +200,12 @@ exports.SpriteSelector.prototype.previousPage = function(){
};
exports.SpriteSelector.prototype.click = function (x, y){
- if (this.nextPageButton !== undefined &&
+ if (this.previousPageButton !== undefined &&
+ x >= this.previousPageButton.position_x && x <= this.previousPageButton.position_x + this.previousPageButton.width &&
+ y >= this.previousPageButton.position_y && y <= this.previousPageButton.position_y + this.previousPageButton.height){
+ this.previousPage();
+ this.render();
+ } else if (this.nextPageButton !== undefined &&
x >= this.nextPageButton.position_x && x <= this.nextPageButton.position_x + this.nextPageButton.width &&
y >= this.nextPageButton.position_y && y <= this.nextPageButton.position_y + this.nextPageButton.height){
this.nextPage();
@@ -216,7 +221,7 @@ exports.SpriteSelector.prototype.click = function (x, y){
exports.SpriteSelector.prototype.render = function(){
- var sprite_id = this.page + (this.sprite_x + this.sprite_y);
+ var sprite_id = this.page * (this.sprite_x * this.sprite_y);
var canvasContext = this.canvas.getContext('2d');
for (var y=0; y < this.sprite_y; y++){
for (var x=0; x < this.sprite_x; x++){
@@ -240,6 +245,17 @@ exports.SpriteSelector.prototype.onColorChanged = function(widget){
this.render();
};
+exports.SpriteSelector.prototype.addPreviousPageButton = function(img_src, x, y){
+ this.previousPageButton = new Image();
+ this.previousPageButton.context = this.canvas.getContext('2d');
+ this.previousPageButton.position_x = x;
+ this.previousPageButton.position_y = y;
+ this.previousPageButton.onload = function(){
+ this.context.drawImage(this, this.position_x, this.position_y);
+ };
+ this.previousPageButton.src = img_src;
+};
+
exports.SpriteSelector.prototype.addNextPageButton = function(img_src, x, y){
this.nextPageButton = new Image();
this.nextPageButton.context = this.canvas.getContext('2d');
@@ -253,7 +269,11 @@ exports.SpriteSelector.prototype.addNextPageButton = function(img_src, x, y){
exports.SpriteSelector.prototype.was_clicked = function(x, y){
- if (this.nextPageButton !== undefined &&
+ if (this.previousPageButton !== undefined &&
+ x >= this.previousPageButton.position_x && x <= this.previousPageButton.position_x + this.previousPageButton.width &&
+ y >= this.previousPageButton.position_y && y <= this.previousPageButton.position_y + this.previousPageButton.height){
+ return true;
+ } else if (this.nextPageButton !== undefined &&
x >= this.nextPageButton.position_x && x <= this.nextPageButton.position_x + this.nextPageButton.width &&
y >= this.nextPageButton.position_y && y <= this.nextPageButton.position_y + this.nextPageButton.height){
return true;
|
added the previousPageButton on selector and all behavior stuff
|
gutomaia_nodeNES
|
train
|
1bbbd0c92b870a835353f7748aeb625c290f3e46
|
diff --git a/Service/Paybox.php b/Service/Paybox.php
index <HASH>..<HASH> 100644
--- a/Service/Paybox.php
+++ b/Service/Paybox.php
@@ -198,4 +198,24 @@ abstract class Paybox
throw new RuntimeException('No server available.');
}
+
+ /**
+ * Returns the content of a web resource.
+ *
+ * @param string $url
+ * @return string
+ */
+ protected function getWebPage($url)
+ {
+ $curl = curl_init();
+
+ curl_setopt($curl, CURLOPT_URL, $url);
+ curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
+ curl_setopt($curl, CURLOPT_HEADER, false);
+ curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
+ $output = curl_exec($curl);
+ curl_close($curl);
+
+ return (string) $output;
+ }
}
diff --git a/Service/PayboxSystemRequest.php b/Service/PayboxSystemRequest.php
index <HASH>..<HASH> 100644
--- a/Service/PayboxSystemRequest.php
+++ b/Service/PayboxSystemRequest.php
@@ -145,24 +145,4 @@ class PayboxSystemRequest extends Paybox
$server['system_path']
);
}
-
- /**
- * Returns the content of a web resource.
- *
- * @param string $url
- * @return string
- */
- protected function getWebPage($url)
- {
- $curl = curl_init();
-
- curl_setopt($curl, CURLOPT_URL, $url);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($curl, CURLOPT_HEADER, false);
- curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
- $output = curl_exec($curl);
- curl_close($curl);
-
- return (string) $output;
- }
}
|
Method getWebPage() moved from PayboxSystemRequest to Paybox class.
|
lexik_LexikPayboxBundle
|
train
|
87c099a6e305f012271d95ad16595a170e579eac
|
diff --git a/jbpm-flow/src/main/java/org/jbpm/process/instance/impl/XPATHExpressionModifier.java b/jbpm-flow/src/main/java/org/jbpm/process/instance/impl/XPATHExpressionModifier.java
index <HASH>..<HASH> 100644
--- a/jbpm-flow/src/main/java/org/jbpm/process/instance/impl/XPATHExpressionModifier.java
+++ b/jbpm-flow/src/main/java/org/jbpm/process/instance/impl/XPATHExpressionModifier.java
@@ -86,6 +86,10 @@ public class XPATHExpressionModifier {
xpath = xpath.substring(1);
}
Node rootNode = contextNode;
+ if (contextNode != null) {
+ contextNode = contextNode.getOwnerDocument();
+ }
+
XPathFactory xpf = new XPathFactoryImpl();
XPath xpe = xpf.newXPath();
XPathExpression xpathExpr = xpe.compile(xpath);
@@ -136,12 +140,21 @@ public class XPATHExpressionModifier {
document.appendChild(contextNode);
rootNode = contextNode;
} else {
- NodeList children = ((Element) contextNode).getElementsByTagNameNS(childName.getNamespaceURI(),
+
+ NodeList children = null;
+ if (contextNode instanceof Element) {
+ children = ((Element) contextNode).getElementsByTagNameNS(childName.getNamespaceURI(),
childName.getLocalPart());
+ } else if (contextNode instanceof Document) {
+ children = ((Document) contextNode).getElementsByTagNameNS(childName.getNamespaceURI(),
+ childName.getLocalPart());
+ } else {
+ throw new IllegalArgumentException(contextNode + " is of unsupported type");
+ }
if ((children == null) || (children.getLength() == 0)) {
Node child = document.createElementNS(childName.getNamespaceURI(),
getQualifiedName(childName));
- contextNode.appendChild(child);
+ contextNode.appendChild(contextNode.getOwnerDocument().importNode(child, true));
contextNode = child;
} else if (children.getLength() == 1) {
contextNode = children.item(0);
@@ -231,7 +244,7 @@ public class XPATHExpressionModifier {
public static Document toDOMDocument(Node node) throws TransformerException {
// If the node is the document, just cast it
if (node instanceof Document) {
- return (Document) node;
+ return newDocument();
// If the node is an element
} else if (node instanceof Element) {
Element elem = (Element) node;
diff --git a/jbpm-flow/src/main/java/org/jbpm/workflow/instance/node/WorkItemNodeInstance.java b/jbpm-flow/src/main/java/org/jbpm/workflow/instance/node/WorkItemNodeInstance.java
index <HASH>..<HASH> 100644
--- a/jbpm-flow/src/main/java/org/jbpm/workflow/instance/node/WorkItemNodeInstance.java
+++ b/jbpm-flow/src/main/java/org/jbpm/workflow/instance/node/WorkItemNodeInstance.java
@@ -16,6 +16,8 @@
package org.jbpm.workflow.instance.node;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@@ -43,6 +45,10 @@ import org.jbpm.workflow.instance.impl.NodeInstanceResolverFactory;
import org.jbpm.workflow.instance.impl.WorkItemResolverFactory;
import org.mvel2.MVEL;
+import com.sun.org.apache.xml.internal.serialize.OutputFormat;
+import com.sun.org.apache.xml.internal.serialize.XML11Serializer;
+import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
+
/**
* Runtime counterpart of a work item node.
*
@@ -221,6 +227,7 @@ public class WorkItemNodeInstance extends StateBasedNodeInstance implements Even
System.out.println("when trying to complete Work Item " + workItem.getName());
System.out.println("Continuing without setting variable.");
}
+
} else {
try {
for (Iterator<Assignment> it = association.getAssignments().iterator(); it.hasNext(); ) {
|
fix the two-assign test case
|
kiegroup_jbpm
|
train
|
7182375a8efb6f398f755de36a75f41162349b2d
|
diff --git a/src/js/Luminous.js b/src/js/Luminous.js
index <HASH>..<HASH> 100644
--- a/src/js/Luminous.js
+++ b/src/js/Luminous.js
@@ -12,7 +12,7 @@ export default class Luminous {
* @param {Object=} options Luminous options
*/
constructor(trigger, options = {}) {
- this.VERSION = "2.3.3";
+ this.VERSION = "2.3.4";
this.destroy = this.destroy.bind(this);
this.open = this.open.bind(this);
this.close = this.close.bind(this);
|
fix: bring version number back in sync
This commit fixes an issue where the lib verison and the package json
version were mismatched.
|
imgix_luminous
|
train
|
ce0c58a3964665e8022d3b89b9043f1430f16250
|
diff --git a/lib/switch_point/model.rb b/lib/switch_point/model.rb
index <HASH>..<HASH> 100644
--- a/lib/switch_point/model.rb
+++ b/lib/switch_point/model.rb
@@ -42,8 +42,10 @@ module SwitchPoint
def switch_point_proxy
if @switch_point_name
ProxyRepository.checkout(@switch_point_name)
- else
+ elsif self == ActiveRecord::Base
nil
+ else
+ superclass.switch_point_proxy
end
end
diff --git a/spec/models.rb b/spec/models.rb
index <HASH>..<HASH> 100644
--- a/spec/models.rb
+++ b/spec/models.rb
@@ -73,6 +73,18 @@ class Nanika3 < ActiveRecord::Base
use_switch_point :nanika3
end
+class AbstractNanika < ActiveRecord::Base
+ use_switch_point :main
+ self.abstract_class = true
+end
+
+class DerivedNanika1 < AbstractNanika
+end
+
+class DerivedNanika2 < AbstractNanika
+ use_switch_point :main2
+end
+
base = { adapter: 'sqlite3' }
ActiveRecord::Base.configurations = {
'main_readonly' => base.merge(database: 'main_readonly.sqlite3'),
diff --git a/spec/switch_point/model_spec.rb b/spec/switch_point/model_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/switch_point/model_spec.rb
+++ b/spec/switch_point/model_spec.rb
@@ -101,6 +101,35 @@ RSpec.describe SwitchPoint::Model do
end
end
+ context 'when superclass uses use_switch_point' do
+ context 'without use_switch_point in derived class' do
+ it 'inherits switch_point configuration' do
+ expect(DerivedNanika1).to connect_to('main_readonly.sqlite3')
+ end
+
+ it 'shares connection with superclass' do
+ expect(DerivedNanika1.connection).to equal(AbstractNanika.connection)
+ end
+ end
+
+ context 'with use_switch_point in derived class' do
+ it 'overrides superclass' do
+ expect(DerivedNanika2).to connect_to('main2_readonly.sqlite3')
+ end
+ end
+
+ context 'when superclass changes switch_point' do
+ after do
+ AbstractNanika.use_switch_point :main
+ end
+
+ it 'follows' do
+ AbstractNanika.use_switch_point :main2
+ expect(DerivedNanika1).to connect_to('main2_readonly.sqlite3')
+ end
+ end
+ end
+
context 'without :writable' do
it 'sends destructive queries to ActiveRecord::Base' do
expect(Nanika1).to connect_to('main_readonly.sqlite3')
|
Inherit superclass' switch_point configuration
|
eagletmt_switch_point
|
train
|
8942b20976753280ba0ae17d324e89a3965c1bd1
|
diff --git a/kubetest/azure.go b/kubetest/azure.go
index <HASH>..<HASH> 100644
--- a/kubetest/azure.go
+++ b/kubetest/azure.go
@@ -210,6 +210,10 @@ func (c *Cluster) generateTemplate() error {
OSType: *acsAgentOSType,
AvailabilityProfile: "AvailabilitySet",
IPAddressCount: 200,
+ PreProvisionExtension: map[string]string{
+ "name": "node_setup",
+ "singleOrAll": "all",
+ },
},
},
LinuxProfile: &LinuxProfile{
@@ -229,6 +233,14 @@ func (c *Cluster) generateTemplate() error {
ClientID: c.credentials.ClientID,
Secret: c.credentials.ClientSecret,
},
+ ExtensionProfiles: []map[string]string{
+ {
+ "name": "node_setup",
+ "version": "v1",
+ "rootURL": "https://k8swin.blob.core.windows.net/k8s-windows/preprovision_extensions/",
+ "script": "node_setup.ps1",
+ },
+ },
},
}
if *acsHyperKubeURL != "" {
diff --git a/kubetest/azure_helpers.go b/kubetest/azure_helpers.go
index <HASH>..<HASH> 100644
--- a/kubetest/azure_helpers.go
+++ b/kubetest/azure_helpers.go
@@ -43,6 +43,7 @@ type Properties struct {
LinuxProfile *LinuxProfile `json:"linuxProfile,omitempty"`
WindowsProfile *WindowsProfile `json:"windowsProfile,omitempty"`
ServicePrincipalProfile *ServicePrincipalProfile `json:"servicePrincipalProfile,omitempty"`
+ ExtensionProfiles []map[string]string `json:"extensionProfiles,omitempty"`
}
type ServicePrincipalProfile struct {
@@ -87,12 +88,13 @@ type MasterProfile struct {
}
type AgentPoolProfile struct {
- Name string `json:"name"`
- Count int `json:"count"`
- VMSize string `json:"vmSize"`
- OSType string `json:"osType,omitempty"`
- AvailabilityProfile string `json:"availabilityProfile"`
- IPAddressCount int `json:"ipAddressCount,omitempty"`
+ Name string `json:"name"`
+ Count int `json:"count"`
+ VMSize string `json:"vmSize"`
+ OSType string `json:"osType,omitempty"`
+ AvailabilityProfile string `json:"availabilityProfile"`
+ IPAddressCount int `json:"ipAddressCount,omitempty"`
+ PreProvisionExtension map[string]string `json:"preProvisionExtension,omitempty"`
}
type AzureClient struct {
|
Add preprovision extension to agent nodes
|
kubernetes_test-infra
|
train
|
93eaba588bd6a19d6bcf123fe9f9368e7fd6fe84
|
diff --git a/django_libs/templatetags/libs_tags.py b/django_libs/templatetags/libs_tags.py
index <HASH>..<HASH> 100644
--- a/django_libs/templatetags/libs_tags.py
+++ b/django_libs/templatetags/libs_tags.py
@@ -59,6 +59,11 @@ def get_verbose(obj, field_name=""):
@register.assignment_tag
def get_profile_for(user):
+ """
+ Allows to call the get_profile utility function from django-libs in a
+ template.
+
+ """
return utils.get_profile(user)
@@ -76,6 +81,7 @@ class LoadContextNode(template.Node):
@register.tag
def load_context(parser, token):
+ # TODO Docstring!
try:
# split_contents() knows not to split quoted strings.
tag_name, fqn = token.split_contents()
diff --git a/django_libs/tests/libs_tags_tests.py b/django_libs/tests/libs_tags_tests.py
index <HASH>..<HASH> 100644
--- a/django_libs/tests/libs_tags_tests.py
+++ b/django_libs/tests/libs_tags_tests.py
@@ -1,10 +1,11 @@
"""Tests for the templatetags of the ``project-kairos`` project."""
-import mock
+from mock import Mock
from django.template import Context, Template
from django.test import RequestFactory, TestCase
from django_libs.templatetags.libs_tags import * # NOQA
+from .test_app.factories import DummyProfileFactory
class CalculateDimensionsTestCase(TestCase):
@@ -12,7 +13,7 @@ class CalculateDimensionsTestCase(TestCase):
longMessage = True
def test_tag(self):
- image = mock.Mock()
+ image = Mock()
image.width = 1
image.height = 2
result = calculate_dimensions(image, 20, 10)
@@ -35,14 +36,44 @@ class CalculateDimensionsTestCase(TestCase):
' be in landscape format.'))
-class GetRangeTestCase(TestCase):
- """Tests for the ``get_range`` filter."""
+class CallTestCase(TestCase):
+ """Tests for the ``call`` templatetag."""
longMessage = True
- def test_filter(self):
- result = get_range(5)
- self.assertEqual(result, range(5), msg=(
- "Filter should behave exactly like Python's range function"))
+ def setUp(self):
+ self.func = lambda args: args
+ self.obj = Mock(func=self.func)
+
+ def test_tag(self):
+ self.assertEqual(call(self.obj, 'func', 'test_string'), 'test_string')
+
+
+class GetVerboseTestCase(TestCase):
+ """Tests for the ``get_verbose`` templatetag."""
+ longMessage = True
+
+ def setUp(self):
+ self.profile = DummyProfileFactory()
+
+ def test_tag(self):
+ self.assertEqual(
+ get_verbose(self.profile, 'dummy_field'), 'Dummy Field',
+ msg='Returned the wrong verbose name for the "dummy_field".')
+ self.assertEqual(
+ get_verbose(self.profile, 'non_existant_field'), '', msg=(
+ 'Should return "" for a non-existant field.'))
+
+
+class GetProfileForTestCase(TestCase):
+ """Tests for the ``get_profile_for`` templatetag."""
+ longMessage = True
+
+ def setUp(self):
+ self.profile = DummyProfileFactory()
+ self.user = self.profile.user
+
+ def test_tag(self):
+ self.assertEqual(get_profile_for(self.user), self.profile)
class LoadContextNodeTestCase(TestCase):
@@ -98,6 +129,16 @@ class NavactiveTestCase(TestCase):
" '', if it matches the path, but returned %s" % result))
+class GetRangeTestCase(TestCase):
+ """Tests for the ``get_range`` filter."""
+ longMessage = True
+
+ def test_filter(self):
+ result = get_range(5)
+ self.assertEqual(result, range(5), msg=(
+ "Filter should behave exactly like Python's range function"))
+
+
class RenderAnalyticsCodeTestCase(TestCase):
"""Tests for the ``render_analytics_code`` templatetag."""
longMessage = True
diff --git a/django_libs/tests/test_app/models.py b/django_libs/tests/test_app/models.py
index <HASH>..<HASH> 100644
--- a/django_libs/tests/test_app/models.py
+++ b/django_libs/tests/test_app/models.py
@@ -1,5 +1,6 @@
"""Models for the ``test_app`` app."""
from django.db import models
+from django.utils.translation import ugettext_lazy as _
from simple_translation.translation_pool import translation_pool
@@ -12,7 +13,10 @@ from ...models_mixins import (
class DummyProfile(SimpleTranslationMixin, models.Model):
"""Just a dummy profile model for testing purposes."""
user = models.ForeignKey('auth.User')
- dummy_field = models.CharField(max_length=128)
+ dummy_field = models.CharField(
+ verbose_name=_('Dummy Field'),
+ max_length=128,
+ )
objects = SimpleTranslationPublishedManager()
diff --git a/django_libs/tests/test_settings.py b/django_libs/tests/test_settings.py
index <HASH>..<HASH> 100644
--- a/django_libs/tests/test_settings.py
+++ b/django_libs/tests/test_settings.py
@@ -55,3 +55,5 @@ INSTALLED_APPS = EXTERNAL_APPS + INTERNAL_APPS
COVERAGE_MODULE_EXCLUDES += EXTERNAL_APPS
TEST_LOAD_MEMBER = 'django_libs.loaders.load_member'
+
+AUTH_PROFILE_MODULE = 'test_app.DummyProfile'
|
Increased coverage of the libs_tags.
|
bitlabstudio_django-libs
|
train
|
fb79485375c26ef9cf2c72f051aba3d56948d79e
|
diff --git a/lib/inherited_resources/url_helpers.rb b/lib/inherited_resources/url_helpers.rb
index <HASH>..<HASH> 100644
--- a/lib/inherited_resources/url_helpers.rb
+++ b/lib/inherited_resources/url_helpers.rb
@@ -208,7 +208,10 @@ module InheritedResources
undef_method params_method_name if method_defined? params_method_name
- define_method params_method_name do |given_args, given_options, *args|
+ define_method params_method_name do |given_args, *args|
+ given_args = given_args.collect { |arg| arg.respond_to?(:permitted?) ? arg.to_h : arg }
+ given_options = given_args.extract_options!
+
if !(singleton && name != :parent) && args.present? && name != :collection && prefix != :new
resource = args.pop
args.push(given_args.first || resource)
@@ -231,9 +234,7 @@ module InheritedResources
class_eval <<-URL_HELPERS, __FILE__, __LINE__
def #{method_name}(*given_args)
- given_args = given_args.collect { |arg| arg.respond_to?(:permitted?) ? arg.to_h : arg }
- given_options = given_args.extract_options!
- #{segments_method}(*#{params_method_name}(given_args, given_options, #{ivars.join(?,)}))
+ #{segments_method}(*#{params_method_name}(given_args, #{ivars.join(?,)}))
end
URL_HELPERS
protected method_name
|
Move extraction of given_options to params helper.
|
activeadmin_inherited_resources
|
train
|
3c9cba86ff7ee7621b084e5fe4f543f049df0b8e
|
diff --git a/src/pymlab/sensors/altimet.py b/src/pymlab/sensors/altimet.py
index <HASH>..<HASH> 100644
--- a/src/pymlab/sensors/altimet.py
+++ b/src/pymlab/sensors/altimet.py
@@ -65,14 +65,15 @@ class ALTIMET01(Device):
t_MSB = self.bus.read_byte_data(self.address,0x04)
t_LSB = self.bus.read_byte_data(self.address,0x05)
+ # conversion of register values to measured values according to sensor datasheet
#Determine sign and output
if (t_MSB > 0x7F):
- t_MSB = ~t_MSB + 1
- sign = -1
+ print "minus"
+ t = float(((~(t_MSB << 8 | t_LSB) + 1) >> 4) /256.0)
else:
- sign = 1
- # conversion of register values to measured values according to sensor datasheet
- t = sign * float(t_MSB + (t_LSB >> 4)/16.0)
+ print "plus"
+ t = float(t_MSB + (t_LSB >> 4)/16.0)
+
p = float((p_MSB << 10)|(p_CSB << 2)|(p_LSB >> 6)) + float((p_LSB >> 4)/4.0)
return (t, p);
|
FIX: wrong temperature data readout from ALTIMET sensor bellow zero.
|
MLAB-project_pymlab
|
train
|
f5e7707953aed78def2c2ff015a489419ac18f0a
|
diff --git a/lib/chars/char_set.rb b/lib/chars/char_set.rb
index <HASH>..<HASH> 100644
--- a/lib/chars/char_set.rb
+++ b/lib/chars/char_set.rb
@@ -120,9 +120,9 @@ module Chars
def random_distinct_bytes(length)
if (length.kind_of?(Array) || length.kind_of?(Range))
#return Array.new(length.sort_by { rand }.first) { random_byte }
- self.entries.sort_by { rand }.slice(0..(length.sort_by { rand }.first))
+ self.entries.sort_by { rand }.slice(0...(length.sort_by { rand }.first))
else
- self.entries.sort_by { rand }.slice(0..length)
+ self.entries.sort_by { rand }.slice(0...length)
end
end
|
fixed fencepost error in random_distinct_bytes
|
postmodern_chars
|
train
|
f5d10fe2b867585d9bfeff22347add9474ba412f
|
diff --git a/gulpfile.js b/gulpfile.js
index <HASH>..<HASH> 100644
--- a/gulpfile.js
+++ b/gulpfile.js
@@ -16,7 +16,7 @@ gulp.task("lint", function() {
.pipe(eslint.failAfterError());
});
-gulp.task("test", function() {
+gulp.task("test", ["lint"], function() {
const tests = [
"test/*.js"
];
diff --git a/test/location.js b/test/location.js
index <HASH>..<HASH> 100644
--- a/test/location.js
+++ b/test/location.js
@@ -1,5 +1,6 @@
"use strict";
+const _ = require("lodash");
let mongoose = require("mongoose");
mongoose.Promise = require("bluebird");
let models = require("../index");
@@ -29,7 +30,7 @@ describe("Location", function() {
});
it("is saved", function(done) {
- var item = new models.Location(testData);
+ const item = new models.Location(testData);
item.save(function(err, sut) {
assert.isNull(err, "Should not err");
@@ -40,7 +41,7 @@ describe("Location", function() {
assert.equal(testData.username, sut.username);
assert.equal(testData.modified_unix_date, sut.modified_unix_date);
assert.equal(testData.device_type, sut.device_type);
- assert.equal(testData.request_time, sut.request_time);
+ assert.equal(testData.session, sut.session);
assert.equal(testData.active, sut.active);
assert.equal(testData.location.longitude, sut.location.longitude);
assert.equal(testData.location.latitude, sut.location.latitude);
@@ -49,4 +50,42 @@ describe("Location", function() {
return done();
});
});
+
+ it("propagateToObject with object", function(done) {
+ let nextUpdate = _.clone(testData);
+ nextUpdate.username = "abc";
+ nextUpdate.session = "def";
+ nextUpdate.active = false;
+
+ const item1 = new models.Location(testData);
+ item1.save(function(err, sut) {
+ assert.isNull(err, "Should not err");
+ assert.isNotNull(testData._id);
+ assert.equal(testData.uuid, sut.uuid);
+ assert.equal(testData.username, sut.username);
+ assert.equal(testData.session, sut.session);
+ assert.equal(testData.active, sut.active);
+
+ const item2 = new models.Location(nextUpdate);
+ item2.propagateToObject(sut, function(itemToSave) {
+ assert.equal(item1._id, itemToSave._id);
+ assert.equal(itemToSave.username, nextUpdate.username);
+ assert.equal(itemToSave.session, nextUpdate.session);
+ assert.equal(itemToSave.active, nextUpdate.active);
+ return done();
+ });
+ });
+ });
+
+ it("propagateToObject with null", function(done) {
+ let item = new models.Location(testData);
+ item.propagateToObject(null, function(sut) {
+ assert.equal(testData.uuid, sut.uuid);
+ assert.equal(testData.username, sut.username);
+ assert.equal(testData.session, sut.session);
+ assert.equal(testData.active, sut.active);
+
+ return done();
+ });
+ });
});
diff --git a/test/mock.js b/test/mock.js
index <HASH>..<HASH> 100644
--- a/test/mock.js
+++ b/test/mock.js
@@ -61,7 +61,8 @@ module.exports = function(dependencies) {
location: {
longitude: -122.304804409037,
latitude: 37.5419679656974
- }
+ },
+ session: "abcd"
};
const rateLimit = {
|
Added location propagateToObject test
|
TabletCommand_tabletcommand-backend-models
|
train
|
51b97783207b6b7ca2bda503f736a30bf2fc7fdd
|
diff --git a/hawkular-inventory-impl-tinkerpop-parent/hawkular-inventory-impl-tinkerpop/src/main/java/org/hawkular/inventory/impl/tinkerpop/FilterVisitor.java b/hawkular-inventory-impl-tinkerpop-parent/hawkular-inventory-impl-tinkerpop/src/main/java/org/hawkular/inventory/impl/tinkerpop/FilterVisitor.java
index <HASH>..<HASH> 100644
--- a/hawkular-inventory-impl-tinkerpop-parent/hawkular-inventory-impl-tinkerpop/src/main/java/org/hawkular/inventory/impl/tinkerpop/FilterVisitor.java
+++ b/hawkular-inventory-impl-tinkerpop-parent/hawkular-inventory-impl-tinkerpop/src/main/java/org/hawkular/inventory/impl/tinkerpop/FilterVisitor.java
@@ -153,22 +153,28 @@ class FilterVisitor {
public void visit(GraphTraversal<?, ?> query, With.Types types, QueryTranslationState state) {
String prop = propertyNameBasedOnState(__type, state);
+ String typeName = null;
+ String[] typeNames = null;
+
if (types.getTypes().length == 1) {
Constants.Type type = Constants.Type.of(types.getTypes()[0]);
- query.has(prop, type.name());
- return;
+ typeName = type.name();
+ query.has(prop, typeName);
+ } else {
+ typeNames =
+ Stream.of(types.getTypes()).map(st -> Constants.Type.of(st).name()).toArray(String[]::new);
+ query.has(prop, P.within(typeNames));
}
- GraphTraversal<?, ?>[] typeChecks = new GraphTraversal<?, ?>[types.getTypes().length];
-
- Arrays.setAll(typeChecks, i -> {
- Constants.Type type = Constants.Type.of(types.getTypes()[i]);
- return __.has(prop, type.name());
- });
-
- query.or((Traversal<?, ?>[]) typeChecks);
-
goBackFromEdges(query, state);
+
+ //another optimization - we know what label the target entity should have, which helps in limiting the "reach"
+ //of the query
+ if (typeNames == null) {
+ query.hasLabel(typeName);
+ } else {
+ query.hasLabel(P.within(typeNames));
+ }
}
@SuppressWarnings("unchecked")
@@ -337,20 +343,15 @@ class FilterVisitor {
public void visit(GraphTraversal<?, ?> query, With.CanonicalPaths filter, QueryTranslationState state) {
String prop = chooseBasedOnDirection(__cp, __targetCp, __sourceCp, state.getComingFrom()).name();
- if (filter.getPaths().length == 1) {
- //this only works if we are on vertices, so check for that
- if (prop.equals(__cp.name())) {
- query.has(T.label, Constants.Type.of(filter.getPaths()[0].getSegment().getElementType()).name());
- }
+ String typeName = null;
+ String[] typeNames = null;
+ if (filter.getPaths().length == 1) {
+ typeName = Constants.Type.of(filter.getPaths()[0].getSegment().getElementType()).name();
query.has(prop, filter.getPaths()[0].toString());
} else {
- if (prop.equals(__cp.name())) {
- String[] labels = Stream.of(filter.getPaths()).map(p -> p.getSegment().getElementType())
- .toArray(String[]::new);
-
- query.has(T.label, P.within(labels));
- }
+ typeNames = Stream.of(filter.getPaths()).map(p -> p.getSegment().getElementType())
+ .toArray(String[]::new);
String[] paths = Stream.of(filter.getPaths()).map(Object::toString).toArray(String[]::new);
@@ -358,6 +359,12 @@ class FilterVisitor {
}
goBackFromEdges(query, state);
+
+ if (typeNames == null) {
+ query.hasLabel(typeName);
+ } else {
+ query.hasLabel(P.within(typeNames));
+ }
}
@SuppressWarnings("unchecked")
|
Optimization of type and canonical path filters by restricting to the known
vertex labels.
This helps sqlg limit the number of queries required.
|
hawkular_hawkular-inventory
|
train
|
4fa539d2e28210b7a80ecbca4b7bc06f8a3d796a
|
diff --git a/Vpc/Abstract.php b/Vpc/Abstract.php
index <HASH>..<HASH> 100644
--- a/Vpc/Abstract.php
+++ b/Vpc/Abstract.php
@@ -276,8 +276,13 @@ abstract class Vpc_Abstract extends Vps_Component_Abstract
protected function _callProcessInput()
{
+ $showInvisible = Vps_Config_Web::getValue('showInvisible');
+
$cacheId = 'procI-'.$this->getData()->getPageOrRoot()->componentId;
- $processCached = Vps_Cache_Simple::fetch($cacheId, $success);
+ $success = false;
+ if (!$showInvisible) { //don't cache in preview
+ $processCached = Vps_Cache_Simple::fetch($cacheId, $success);
+ }
if (!$success) {
$process = $this->getData()
->getRecursiveChildComponents(array(
@@ -299,11 +304,13 @@ abstract class Vpc_Abstract extends Vps_Component_Abstract
$process[] = $this->getData();
}
}
- $datas = array();
- foreach ($process as $p) {
- $datas[] = $p->vpsSerialize();
+ if (!$showInvisible) {
+ $datas = array();
+ foreach ($process as $p) {
+ $datas[] = $p->vpsSerialize();
+ }
+ Vps_Cache_Simple::add($cacheId, $datas);
}
- Vps_Cache_Simple::add($cacheId, $datas);
} else {
$process = array();
foreach ($processCached as $d) {
@@ -347,7 +354,13 @@ abstract class Vpc_Abstract extends Vps_Component_Abstract
header('Content-Type: text/html; charset=utf-8');
$process = $this->_callProcessInput();
Vps_Benchmark::checkpoint('processInput');
- echo $this->getData()->render(null, $renderMaster);
+ $cacheId = 'page-'.$this->getData()->componentId;
+ $out = Vps_Cache_Simple::fetch($cacheId);
+ if (!$out) {
+ $out = $this->getData()->render(null, $renderMaster);
+ Vps_Cache_Simple::add($cacheId, $out);
+ }
+ echo $out;
Vps_Benchmark::checkpoint('render');
$this->_callPostProcessInput($process);
Vps_Benchmark::checkpoint('postProcessInput');
|
don't cache processInput in preview as the result can be different
|
koala-framework_koala-framework
|
train
|
9de4afa8974b5afbaf61c41c4186eef6546932d4
|
diff --git a/src/transformers/trainer.py b/src/transformers/trainer.py
index <HASH>..<HASH> 100644
--- a/src/transformers/trainer.py
+++ b/src/transformers/trainer.py
@@ -10,6 +10,7 @@ from typing import Callable, Dict, List, Optional, Tuple, Union
import numpy as np
import torch
+from packaging import version
from torch import nn
from torch.utils.data.dataloader import DataLoader
from torch.utils.data.dataset import Dataset
@@ -440,7 +441,14 @@ class Trainer:
):
logs: Dict[str, float] = {}
logs["loss"] = (tr_loss - logging_loss) / self.args.logging_steps
- logs["learning_rate"] = scheduler.get_last_lr()[0]
+ # maintaining backward compatibility.
+ # could use "scheduler.get_last_lr()[0]" instead for pytorch >= 1.4.0
+ logs["learning_rate"] = (
+ scheduler.get_last_lr()[0]
+ if version.parse(torch.__version__) >= version.parse("1.4")
+ else scheduler.get_lr()[0]
+ )
+
logging_loss = tr_loss
self._log(logs)
|
Make get_last_lr in trainer backward compatible (#<I>)
* makes fetching last learning late in trainer backward compatible
* split comment to multiple lines
* fixes black styling issue
* uses version to create a more explicit logic
|
huggingface_pytorch-pretrained-BERT
|
train
|
a5db6e07d828e51101bef6f4e582088ffc5c1f2e
|
diff --git a/src/main/java/de/dfki/km/json/jsonld/JSONLDProcessor.java b/src/main/java/de/dfki/km/json/jsonld/JSONLDProcessor.java
index <HASH>..<HASH> 100644
--- a/src/main/java/de/dfki/km/json/jsonld/JSONLDProcessor.java
+++ b/src/main/java/de/dfki/km/json/jsonld/JSONLDProcessor.java
@@ -1,12 +1,14 @@
package de.dfki.km.json.jsonld;
import java.text.DecimalFormat;
+import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
@@ -111,7 +113,7 @@ public class JSONLDProcessor {
} else {
((Map<String, Object>) rval).put("@type", coerce);
if (coerce.equals(JSONLDConsts.XSD_DOUBLE)) {
- DecimalFormat decimalFormat = new DecimalFormat("0.000000E0");
+ DecimalFormat decimalFormat = new DecimalFormat("0.000000E0", new DecimalFormatSymbols(Locale.US));
Double v = null;
if (value instanceof String) {
v = Double.parseDouble((String) value);
|
fixed locale problem when working with doubles
|
jsonld-java_jsonld-java
|
train
|
b4746bf67faceee4b50530b7d66b10d94dddc6b1
|
diff --git a/lib/buffer.rb b/lib/buffer.rb
index <HASH>..<HASH> 100644
--- a/lib/buffer.rb
+++ b/lib/buffer.rb
@@ -33,6 +33,33 @@ module WaveFile
private
def convert_buffer(samples, old_format, new_format)
+ new_samples = samples.dup
+
+ new_samples = convert_buffer_channels(new_samples, old_format.channels, new_format.channels)
+
+ @format = new_format
+
+ return new_samples
+ end
+
+ def convert_buffer_channels(samples, old_channels, new_channels)
+ # The cases of mono -> stereo and vice-versa are handled specially,
+ # because those conversion methods are faster than the general methods,
+ # and the large majority of wave files are expected to be either mono or stereo.
+ if old_channels == 1 && new_channels == 2
+ samples.map! {|sample| [sample, sample]}
+ elsif old_channels == 2 && new_channels == 1
+ samples.map! {|sample| (sample[0] + sample[1]) / 2}
+ elsif old_channels == 1 && new_channels >= 2
+ samples.map! {|sample| [].fill(sample, 0, new_channels)}
+ elsif old_channels >= 2 && new_channels == 1
+ samples.map! {|sample| sample.inject(0) {|sub_sample, sum| sum + sub_sample } / old_channels }
+ elsif old_channels > 2 && new_channels == 2
+ samples.map! {|sample| [sample[0], sample[1]]}
+ else
+ raise StandardError "Conversion of sample data from #{old_channels} channels to #{new_channels} channels is unsupported"
+ end
+
return samples
end
end
diff --git a/test/buffer_test.rb b/test/buffer_test.rb
index <HASH>..<HASH> 100644
--- a/test/buffer_test.rb
+++ b/test/buffer_test.rb
@@ -6,4 +6,31 @@ require 'wavefile.rb'
include WaveFile
class WaveFileBufferTest < Test::Unit::TestCase
+ def test_convert_buffer_channels
+ b = WaveFileBuffer.new([-32768, -24576, -16384, -8192, 0, 8256, 16513, 24511, 32767], WaveFileFormat.new(1, 16, 44100))
+ b.convert!(WaveFileFormat.new(2, 16, 44100))
+ assert_equal([[-32768, -32768], [-24576, -24576], [-16384, -16384], [-8192, -8192], [0, 0],
+ [8256, 8256], [16513, 16513], [24511, 24511], [32767, 32767]],
+ b.samples)
+
+ b = WaveFileBuffer.new([-32768, -24576, -16384, -8192, 0, 8256, 16513, 24511, 32767], WaveFileFormat.new(1, 16, 44100))
+ b.convert!(WaveFileFormat.new(3, 16, 44100))
+ assert_equal([[-32768, -32768, -32768], [-24576, -24576, -24576], [-16384, -16384, -16384], [-8192, -8192, -8192], [0, 0, 0],
+ [8256, 8256, 8256], [16513, 16513, 16513], [24511, 24511, 24511], [32767, 32767, 32767]],
+ b.samples)
+
+ b = WaveFileBuffer.new([[-32768, -32768], [-24576, -24576], [-16384, -16384], [-8192, -8192], [0, 0],
+ [8256, 8256], [16513, 16513], [24511, 24511], [32767, 32767]],
+ WaveFileFormat.new(2, 16, 44100))
+ b.convert!(WaveFileFormat.new(1, 16, 44100))
+ assert_equal([-32768, -24576, -16384, -8192, 0, 8256, 16513, 24511, 32767],
+ b.samples)
+
+ b = WaveFileBuffer.new([[-32768, -32768, -32768], [-24576, -24576, -24576], [-16384, -16384, -16384], [-8192, -8192, -8192], [0, 0, 0],
+ [8256, 8256, 8256], [16513, 16513, 16513], [24511, 24511, 24511], [32767, 32767, 32767]],
+ WaveFileFormat.new(3, 16, 44100))
+ b.convert!(WaveFileFormat.new(1, 16, 44100))
+ assert_equal([-32768, -24576, -16384, -8192, 0, 8256, 16513, 24511, 32767],
+ b.samples)
+ end
end
|
Adding ability to convert a buffer's number of channels.
|
jstrait_wavefile
|
train
|
7563fc718acaf13a52f58cf81386a40c234b5f1c
|
diff --git a/webroot/css/frontend.css b/webroot/css/frontend.css
index <HASH>..<HASH> 100644
--- a/webroot/css/frontend.css
+++ b/webroot/css/frontend.css
@@ -635,7 +635,7 @@ body.manufacturers.detail .imprint {
margin-top: -148px;
}
#right .inner-right {
- margin-top: 3px;
+ margin-top: 2px;
position: fixed;
}
.box {
diff --git a/webroot/js/cart.js b/webroot/js/cart.js
index <HASH>..<HASH> 100644
--- a/webroot/js/cart.js
+++ b/webroot/js/cart.js
@@ -49,6 +49,7 @@ foodcoopshop.Cart = {
$('.cart p.products').show();
foodcoopshop.AppFeatherlight.initLightboxForImages('.cart .products a.image');
+ foodcoopshop.Helper.onWindowScroll();
},
diff --git a/webroot/js/helper.js b/webroot/js/helper.js
index <HASH>..<HASH> 100644
--- a/webroot/js/helper.js
+++ b/webroot/js/helper.js
@@ -195,7 +195,12 @@ foodcoopshop.Helper = {
$('.inner-right').css('left', newLeft);
// adapt height of cart
- $('#cart p.products').css('max-height', parseInt($(window).height()) - 145);
+ var difference = 150;
+ var loadLastOrderDetailsDropdown = $('#cart #load-last-order-details');
+ if (loadLastOrderDetailsDropdown.length > 0) {
+ difference += loadLastOrderDetailsDropdown.closest('.input').height();
+ }
+ $('#cart p.products').css('max-height', parseInt($(window).height()) - difference);
},
|
show cart button with many products was not visible on small screens
|
foodcoopshop_foodcoopshop
|
train
|
c1e27cc84de349f91c8c7603e6372ea62de0ddd1
|
diff --git a/markovify/text.py b/markovify/text.py
index <HASH>..<HASH> 100644
--- a/markovify/text.py
+++ b/markovify/text.py
@@ -93,9 +93,9 @@ class Text(object):
"""
reject_pat = re.compile(r"(^')|('$)|\s'|'\s|[\"(\(\)\[\])]")
# Decode unicode, mainly to normalize fancy quotation marks
- if sentence.__class__.__name__ == "str":
+ if sentence.__class__.__name__ == "str": # pragma: no cover
decoded = sentence
- else:
+ else: # pragma: no cover
decoded = unidecode(sentence)
# Sentence shouldn't contain problematic characters
if re.search(reject_pat, decoded): return False
|
Add pragma: no cover to py2/3 conditional
|
jsvine_markovify
|
train
|
87f55c67b0d1260360af3f3cf2a9d220d2c9882d
|
diff --git a/chrome/src/extension/background.js b/chrome/src/extension/background.js
index <HASH>..<HASH> 100644
--- a/chrome/src/extension/background.js
+++ b/chrome/src/extension/background.js
@@ -7,7 +7,7 @@ ChromeDriver.ports = [];
ChromeDriver.activePort = null;
//ID of the currently active tab
ChromeDriver.activeTabId = null;
-//TODO(danielwh): Grab the window ID too, and handle toolstrip notifying better
+ChromeDriver.activeWindowId = null;
//Whether the plugin has the OS-specific window handle for the active tab
//Called HWND rather than window handle to avoid confusion with the other
//use of window handle to mean 'name of window'
@@ -117,12 +117,7 @@ function sendResponseToParsedRequest(toSend, wait) {
}
ChromeDriver.isBlockedWaitingForResponse = false;
sendResponseByXHR(toSend, wait);
- var views = chrome.self.getViews();
- for (var view in views) {
- if (views[view].setWebdriverToolstripFree) {
- views[view].setWebdriverToolstripFree();
- }
- }
+ setToolstripsBusy(false);
}
/**
@@ -164,12 +159,7 @@ function parseRequest(request) {
return;
}
ChromeDriver.isBlockedWaitingForResponse = true;
- var views = chrome.self.getViews();
- for (var view in views) {
- if (views[view].setWebdriverToolstripBusy) {
- views[view].setWebdriverToolstripBusy();
- }
- }
+ setToolstripsBusy(true);
switch (request.request) {
case "url":
@@ -354,6 +344,7 @@ function getUrlCallback(tab) {
ChromeDriver.getUrlRequestSequenceNumber++;
ChromeDriver.isLoadingTabAtTheMomentAndMaybeWillNotSucceed = false;
ChromeDriver.activeTabId = tab.id;
+ ChromeDriver.activeWindowId = tab.windowId;
setActivePortByTabId(tab.id);
ChromeDriver.requestSequenceNumber = 0;
if (ChromeDriver.activePort == null) {
@@ -371,6 +362,20 @@ function getUrlCallbackById(tabId) {
chrome.tabs.get(tabId, getUrlCallback);
}
+function setToolstripsBusy(busy) {
+ var toolstrips = chrome.self.getToolstrips(ChromeDriver.activeWindowId);
+ for (var toolstrip in toolstrips) {
+ if (toolstrips[toolstrip].setWebdriverToolstripBusy &&
+ toolstrips[toolstrip].setWebdriverToolstripFree) {
+ if (busy) {
+ toolstrips[toolstrip].setWebdriverToolstripBusy();
+ } else {
+ toolstrips[toolstrip].setWebdriverToolstripFree();
+ }
+ }
+ }
+}
+
function pushPort(port) {
//It would be nice to only have one port per name, so we enforce this
removePort(port);
|
DanielWagnerHall: Nicer handling of toolstrip busyifying
r<I>
|
SeleniumHQ_selenium
|
train
|
703415ab2e9163c787a760835f22874e9cd38e7b
|
diff --git a/lib/Sabre/DAV/Server.php b/lib/Sabre/DAV/Server.php
index <HASH>..<HASH> 100644
--- a/lib/Sabre/DAV/Server.php
+++ b/lib/Sabre/DAV/Server.php
@@ -26,9 +26,6 @@ class Sabre_DAV_Server {
*/
const NODE_DIRECTORY = 2;
- const PROP_SET = 1;
- const PROP_REMOVE = 2;
-
/**
* XML namespace for all SabreDAV related elements
*/
|
Removed some constants that may not have been used for 2 years.
|
sabre-io_dav
|
train
|
ba0967102b66ceab0ec9f3df6a9081b5dc121549
|
diff --git a/usage/src/main/java/com/ning/billing/usage/timeline/chunks/TimeBytesAndSampleBytes.java b/usage/src/main/java/com/ning/billing/usage/timeline/chunks/TimeBytesAndSampleBytes.java
index <HASH>..<HASH> 100644
--- a/usage/src/main/java/com/ning/billing/usage/timeline/chunks/TimeBytesAndSampleBytes.java
+++ b/usage/src/main/java/com/ning/billing/usage/timeline/chunks/TimeBytesAndSampleBytes.java
@@ -26,7 +26,7 @@ public class TimeBytesAndSampleBytes {
private final byte[] timeBytes;
private final byte[] sampleBytes;
- public TimeBytesAndSampleBytes(byte[] timeBytes, byte[] sampleBytes) {
+ public TimeBytesAndSampleBytes(final byte[] timeBytes, final byte[] sampleBytes) {
this.timeBytes = timeBytes;
this.sampleBytes = sampleBytes;
}
@@ -57,13 +57,21 @@ public class TimeBytesAndSampleBytes {
@Override
public boolean equals(final Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
final TimeBytesAndSampleBytes that = (TimeBytesAndSampleBytes) o;
- if (!Arrays.equals(sampleBytes, that.sampleBytes)) return false;
- if (!Arrays.equals(timeBytes, that.timeBytes)) return false;
+ if (!Arrays.equals(sampleBytes, that.sampleBytes)) {
+ return false;
+ }
+ if (!Arrays.equals(timeBytes, that.timeBytes)) {
+ return false;
+ }
return true;
}
diff --git a/usage/src/main/java/com/ning/billing/usage/timeline/chunks/TimelineChunkBinder.java b/usage/src/main/java/com/ning/billing/usage/timeline/chunks/TimelineChunkBinder.java
index <HASH>..<HASH> 100644
--- a/usage/src/main/java/com/ning/billing/usage/timeline/chunks/TimelineChunkBinder.java
+++ b/usage/src/main/java/com/ning/billing/usage/timeline/chunks/TimelineChunkBinder.java
@@ -30,7 +30,7 @@ import org.skife.jdbi.v2.sqlobject.BindingAnnotation;
import com.ning.billing.usage.timeline.DateTimeUtils;
import com.ning.billing.usage.timeline.chunks.TimelineChunkBinder.TimelineChunkBinderFactory;
-import com.ning.billing.usage.timeline.times.TimesAndSamplesCoder;
+import com.ning.billing.usage.timeline.codec.TimesAndSamplesCoder;
/**
* jdbi binder for TimelineChunk
diff --git a/usage/src/main/java/com/ning/billing/usage/timeline/chunks/TimelineChunkMapper.java b/usage/src/main/java/com/ning/billing/usage/timeline/chunks/TimelineChunkMapper.java
index <HASH>..<HASH> 100644
--- a/usage/src/main/java/com/ning/billing/usage/timeline/chunks/TimelineChunkMapper.java
+++ b/usage/src/main/java/com/ning/billing/usage/timeline/chunks/TimelineChunkMapper.java
@@ -25,7 +25,7 @@ import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper;
import com.ning.billing.usage.timeline.DateTimeUtils;
-import com.ning.billing.usage.timeline.times.TimesAndSamplesCoder;
+import com.ning.billing.usage.timeline.codec.TimesAndSamplesCoder;
/**
* jdbi mapper for TimelineChunk
|
chunks: fix imports and style issues
|
killbill_killbill
|
train
|
68b252cdd015806a02c2e2c6ae2685c70c4b4d47
|
diff --git a/ella/newman/utils.py b/ella/newman/utils.py
index <HASH>..<HASH> 100644
--- a/ella/newman/utils.py
+++ b/ella/newman/utils.py
@@ -136,7 +136,9 @@ def JsonResponseRedirect(location):
'redirect_to': location
}
out = json_encode(out_dict)
- return HttpResponse(out, mimetype='text/plain;charset=utf-8', status=HTTP_OK)
+ response = HttpResponse(out, mimetype='text/plain;charset=utf-8', status=HTTP_OK)
+ response['Redirect-To'] = location
+ return response
def decode_category_filter_json(data):
decoded = json_decode(data)
|
HTTP header added for JsonResponseRedirect.
|
ella_ella
|
train
|
aca765d59058d5083d5f9b7204e3055d21708da0
|
diff --git a/src/Sql/Sql.php b/src/Sql/Sql.php
index <HASH>..<HASH> 100644
--- a/src/Sql/Sql.php
+++ b/src/Sql/Sql.php
@@ -93,7 +93,7 @@ class Sql
/**
* @param Where $where
* @param string|null $andOr
- * @return Sql
+ * @return $this
*/
public function where( $where, $andOr=null )
{
@@ -107,7 +107,7 @@ class Sql
/**
* @param $where
- * @return Sql
+ * @return $this
*/
public function whereOr( $where )
{
@@ -128,7 +128,7 @@ class Sql
/**
* @param string $table
* @param string $alias
- * @return Sql
+ * @return $this
*/
public function table( $table, $alias = null )
{
@@ -156,7 +156,7 @@ class Sql
/**
* @param string $column
* @param null|string $as
- * @return Sql
+ * @return $this
*/
public function column( $column, $as = null )
{
@@ -257,7 +257,7 @@ class Sql
/**
* creates SELECT DISTINCT statement.
- * @return Sql
+ * @return $this
*/
public function distinct()
{
@@ -266,7 +266,7 @@ class Sql
/**
* @param bool $for
- * @return Sql
+ * @return $this
*/
public function forUpdate( $for = true )
{
|
@return $this for Sql maybe extended by other class.
|
asaokamei_ScoreSql
|
train
|
ffeff0d659fcca2589c8489ccba646adb6ed4cf6
|
diff --git a/lib/actions/ResourcesDeploy.js b/lib/actions/ResourcesDeploy.js
index <HASH>..<HASH> 100644
--- a/lib/actions/ResourcesDeploy.js
+++ b/lib/actions/ResourcesDeploy.js
@@ -248,7 +248,11 @@ usage: serverless resources deploy`,
});
} else {
- return BbPromise.reject(new SError(e));
+ if( e.message.indexOf('No updates are to be performed.') !== -1) {
+ return BbPromise.resolve({});
+ } else {
+ return BbPromise.reject(new SError(e));
+ }
}
});
}
|
'No updates to be performed' in resources deploy is not an error.
|
serverless_serverless
|
train
|
8ffca1dc6f05bf6da99605575d632318c9dc1907
|
diff --git a/eZ/Bundle/EzPublishCoreBundle/Fragment/FragmentUriGenerator.php b/eZ/Bundle/EzPublishCoreBundle/Fragment/FragmentUriGenerator.php
index <HASH>..<HASH> 100644
--- a/eZ/Bundle/EzPublishCoreBundle/Fragment/FragmentUriGenerator.php
+++ b/eZ/Bundle/EzPublishCoreBundle/Fragment/FragmentUriGenerator.php
@@ -29,11 +29,5 @@ class FragmentUriGenerator
// @see eZ\Publish\Core\MVC\Symfony\EventListener\SiteAccessMatchListener
if ( $request->attributes->has( 'siteaccess' ) )
$reference->attributes['serialized_siteaccess'] = serialize( $request->attributes->get( 'siteaccess' ) );
-
- if ( $request->attributes->has( 'semanticPathinfo' ) )
- $reference->attributes['semanticPathinfo'] = $request->attributes->get( 'semanticPathinfo' );
-
- if ( $request->attributes->has( 'viewParametersString' ) )
- $reference->attributes['viewParametersString'] = $request->attributes->get( 'viewParametersString' );
}
}
diff --git a/eZ/Bundle/EzPublishCoreBundle/Fragment/InlineFragmentRenderer.php b/eZ/Bundle/EzPublishCoreBundle/Fragment/InlineFragmentRenderer.php
index <HASH>..<HASH> 100644
--- a/eZ/Bundle/EzPublishCoreBundle/Fragment/InlineFragmentRenderer.php
+++ b/eZ/Bundle/EzPublishCoreBundle/Fragment/InlineFragmentRenderer.php
@@ -27,7 +27,13 @@ class InlineFragmentRenderer extends BaseRenderer
$this->fragmentUriGenerator = new FragmentUriGenerator;
}
+ // Generate base fragment URI and add other needed attributes
$this->fragmentUriGenerator->generateFragmentUri( $reference, $request, $absolute );
+ if ( $request->attributes->has( 'semanticPathinfo' ) )
+ $reference->attributes['semanticPathinfo'] = $request->attributes->get( 'semanticPathinfo' );
+ if ( $request->attributes->has( 'viewParametersString' ) )
+ $reference->attributes['viewParametersString'] = $request->attributes->get( 'viewParametersString' );
+
return parent::generateFragmentUri( $reference, $request, $absolute );
}
}
|
Fix EZP-<I>: Cached ESI can not be shared among pages
|
ezsystems_ezpublish-kernel
|
train
|
be0bf584138389c43cefeb2e313d4cc3b08ccc5b
|
diff --git a/lib/api.js b/lib/api.js
index <HASH>..<HASH> 100755
--- a/lib/api.js
+++ b/lib/api.js
@@ -37,13 +37,31 @@ Api.prototype.createClient = function(key, object, dummy) {
if (dummy) {
this._keepOpen;
- setInterval(function() {}, 3,600,000);
+ setInterval(function() {}, 3600000);
}
// we've been told to open a dummy so lets keep the script hanging around
// XXX - not sure if this is a good approach tbh
return ret;
};
+
+Api.prototype.destroyClient = function(key) {
+ if (!key in this._clients) {
+ return false;
+ }
+ // no client exists, lets bail
+
+ var client = this._clients[key];
+ // find the client in our clients object
+
+ client.irc.disconnect();
+ // send a disconnect to be nice
+
+ delete this._clients[key];
+ // delete the object completely.
+
+ return true;
+};
// ========================================
// ========================================
diff --git a/lib/irc.js b/lib/irc.js
index <HASH>..<HASH> 100755
--- a/lib/irc.js
+++ b/lib/irc.js
@@ -611,6 +611,15 @@ Client.prototype._ircEvents = {
Client.prototype.raw = function(data) {
this.connection.raw(data);
};
+
+Client.prototype.disconnect = function(message) {
+ if (this.connection.isConnected()) {
+ this.raw(['QUIT', message || 'Disconnecting']);
+ // are we still event connected? if so send QUIT
+ } else {
+ Events.emit([this.key, 'close']);
+ }
+};
// ========================================
// ========================================
diff --git a/lib/main.js b/lib/main.js
index <HASH>..<HASH> 100755
--- a/lib/main.js
+++ b/lib/main.js
@@ -1,6 +1,6 @@
var api = require(__dirname + '/api').api;
-var cli = api.createClient('unique-key', {
+/*var cli = api.createClient('unique-key', {
server: 'irc.freenode.net',
nick: 'simpleircsocket',
user: 'node',
@@ -31,4 +31,4 @@ rl.on('line', function(line) {
rl.on('close', function() {
// do something on finish here
-});
\ No newline at end of file
+});*/
\ No newline at end of file
diff --git a/test/irc.js b/test/irc.js
index <HASH>..<HASH> 100755
--- a/test/irc.js
+++ b/test/irc.js
@@ -101,10 +101,10 @@ describe('motd event', function () {
it('motd should be correct', function (done) {
Events.once('key.motd', function(o) {
- o.should.eql(['- sendak.freenode.net Message of the Day -',
+ o.should.eql({motd: ['- sendak.freenode.net Message of the Day -',
'- Welcome to moorcock.freenode.net in Texas, USA. Thanks to',
'- Kodingen (http://kodingen.com) for sponsoring this server!',
- 'End of /MOTD command.']);
+ 'End of /MOTD command.']});
done();
});
});
|
Added destroyClient and a disconnect function, also updated motd event tests
|
ircanywhere_irc-factory
|
train
|
a34e8ba4e314bdf20cd228b992d2fca2730c397e
|
diff --git a/lib/by_star.rb b/lib/by_star.rb
index <HASH>..<HASH> 100644
--- a/lib/by_star.rb
+++ b/lib/by_star.rb
@@ -192,6 +192,8 @@ module ByStar
start_time = parse(start_time)
end_time = parse(end_time)
+ raise ParseError, "End time is before start time, searching like this will return no results." if end_time < start_time
+
field = options[:field] || "created_at"
with_scope(:find => { :conditions => { field => start_time.utc..end_time.utc } }) do
if block_given?
@@ -240,7 +242,7 @@ module ByStar
else
object
end
- raise "Chronic couldn't work out #{o.inspect}; please be more precise." if object.nil?
+ raise ParseError, "Chronic couldn't work out #{o.inspect}; please be more precise." if object.nil?
object
end
diff --git a/spec/by_star_spec.rb b/spec/by_star_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/by_star_spec.rb
+++ b/spec/by_star_spec.rb
@@ -25,7 +25,7 @@ describe Post do
end
it "should be able to find if given a string" do
- size(Time.now.year.to_s).should eql(Post.count - 1)
+ size(Time.zone.now.year.to_s).should eql(Post.count - 1)
end
it "should be able to find a single post from last year" do
@@ -244,7 +244,7 @@ describe Post do
end
it "should find for a given time" do
- size(Time.now - 2.days).should eql(16)
+ size(Time.zone.now - 2.days).should eql(16)
end
it "should find for a given date" do
@@ -256,7 +256,7 @@ describe Post do
end
it "should be able to find all events before Ryan's birthday using a non-standard field" do
- Event.past("04-12-#{Time.now.year}".to_time, :field => "start_time").size.should eql(6)
+ Event.past("04-12-#{Time.zone.now.year}".to_time, :field => "start_time").size.should eql(6)
end
end
@@ -279,19 +279,27 @@ describe Post do
end
it "should be able to find all events after Dad's birthday using a non-standard field" do
- Event.past("05-07-#{Time.now.year}".to_time, :field => "start_time").size.should eql(3)
+ Event.past("05-07-#{Time.zone.now.year}".to_time, :field => "start_time").size.should eql(3)
end
end
describe "as of" do
it "should be able to find posts as of 2 weeks ago" do
- year = Time.zone.now.year
- Time.stub!(:now).and_return("15-05-#{year}".to_time)
+ stub_time
Post.as_of_2_weeks_ago.size.should eql(7)
end
+ it "should be able to find posts as of 2 weeks before a given time" do
+ stub_time
+ Post.as_of_2_weeks_ago(Time.zone.now + 1.month).size.should eql(14)
+ end
+
+ it "should error if given a date in the past far enough back" do
+ lambda { Post.as_of_6_weeks_ago(Time.zone.now - 2.months) }.should raise_error(ByStar::ParseError, "End time is before start time, searching like this will return no results.")
+ end
+
it "should not do anything if given an invalid date" do
- lambda { Post.as_of_ryans_birthday }.should raise_error(RuntimeError, "Chronic couldn't work out \"Ryans birthday\"; please be more precise.")
+ lambda { Post.as_of_ryans_birthday }.should raise_error(ByStar::ParseError, "Chronic couldn't work out \"Ryans birthday\"; please be more precise.")
end
end
@@ -303,7 +311,7 @@ describe Post do
it "should find between two times" do
stub_time
- size(Time.now - 5.days, Time.now + 5.days).should eql(3)
+ size(Time.zone.now - 5.days, Time.zone.now + 5.days).should eql(3)
end
it "should find between two dates" do
@@ -314,13 +322,21 @@ describe Post do
describe "up to" do
it "should be able to find posts up to 2 weeks from now" do
- year = Time.zone.now.year
- Time.stub!(:now).and_return("15-05-#{year}".to_time)
+ stub_time
Post.up_to_6_weeks_from_now.size.should eql(9)
end
+ it "should be able to find posts up to 2 weeks from a given time" do
+ stub_time
+ Post.up_to_6_weeks_from_now(Time.zone.now - 1.month).size.should eql(14)
+ end
+
+ it "should error if given a date in the past" do
+ lambda { Post.up_to_6_weeks_from_now(Time.zone.now + 2.months) }.should raise_error(ByStar::ParseError, "End time is before start time, searching like this will return no results.")
+ end
+
it "should not do anything if given an invalid date" do
- lambda { Post.up_to_ryans_birthday }.should raise_error(RuntimeError, "Chronic couldn't work out \"Ryans birthday\"; please be more precise.")
+ lambda { Post.up_to_ryans_birthday }.should raise_error(ByStar::ParseError, "Chronic couldn't work out \"Ryans birthday\"; please be more precise.")
end
end
|
by_star will now raise an error if given an end_time less than the start_time
|
radar_by_star
|
train
|
ee819052ee5d4f34b4c29abd72e27a7ab9873d58
|
diff --git a/consul/base.py b/consul/base.py
index <HASH>..<HASH> 100644
--- a/consul/base.py
+++ b/consul/base.py
@@ -1490,7 +1490,7 @@ class Consul(object):
when *ttl* is provided, the session is invalidated if it is not
renewed before the TTL expires. If specified, it is an integer of
- seconds. Currently it must be between 10 and 3600 seconds.
+ seconds. Currently it must be between 10 and 86400 seconds.
By default the session will be created in the current datacenter
but an optional *dc* can be provided.
@@ -1515,7 +1515,7 @@ class Consul(object):
if behavior != 'release':
data['behavior'] = behavior
if ttl:
- assert 10 <= ttl <= 3600
+ assert 10 <= ttl <= 86400
data['ttl'] = '%ss' % ttl
if data:
data = json.dumps(data)
|
fix #<I>: update max ttl to <I> to conform to consul
|
cablehead_python-consul
|
train
|
a828a246e5c11900326c294a5d4a8317735491a8
|
diff --git a/system/HTTP/ResponseInterface.php b/system/HTTP/ResponseInterface.php
index <HASH>..<HASH> 100644
--- a/system/HTTP/ResponseInterface.php
+++ b/system/HTTP/ResponseInterface.php
@@ -221,7 +221,7 @@ interface ResponseInterface
*
* @param array $options
*
- * @return $this
+ * @return Response
*/
public function setCache(array $options = []);
@@ -233,7 +233,7 @@ interface ResponseInterface
* $date can be either a string representation of the date or,
* preferably, an instance of DateTime.
*
- * @param $date
+ * @param string|\DateTime $date
*/
public function setLastModified($date);
|
Update HTTP ResponseInterface doc types
|
codeigniter4_CodeIgniter4
|
train
|
4c3fba3ce641027c433ebdefe7657959ad736bd4
|
diff --git a/src/eXpansion/Framework/GameManiaplanet/DataProviders/MapListDataProvider.php b/src/eXpansion/Framework/GameManiaplanet/DataProviders/MapListDataProvider.php
index <HASH>..<HASH> 100644
--- a/src/eXpansion/Framework/GameManiaplanet/DataProviders/MapListDataProvider.php
+++ b/src/eXpansion/Framework/GameManiaplanet/DataProviders/MapListDataProvider.php
@@ -64,6 +64,7 @@ class MapListDataProvider extends AbstractDataProvider
if (!empty($maps)) {
foreach ($maps as $map) {
+ $map = $this->connection->getMapInfo($map->fileName);
$this->mapStorage->addMap($map);
}
}
|
Fixed issue with map objects having missing data at some instances.
|
eXpansionPluginPack_eXpansion2
|
train
|
7fc598b73f4ec5ee57c6f7a76dd3a72513bb835a
|
diff --git a/cmd/globals.go b/cmd/globals.go
index <HASH>..<HASH> 100644
--- a/cmd/globals.go
+++ b/cmd/globals.go
@@ -25,7 +25,7 @@ import (
// Global constants for Minio.
const (
- minGoVersion = ">= 1.7.1" // minimum Go runtime version
+ minGoVersion = ">= 1.7" // Minio requires at least Go v1.7
)
// minio configuration related constants.
diff --git a/cmd/update-main.go b/cmd/update-main.go
index <HASH>..<HASH> 100644
--- a/cmd/update-main.go
+++ b/cmd/update-main.go
@@ -20,7 +20,6 @@ import (
"bytes"
"encoding/json"
"errors"
- "fmt"
"io/ioutil"
"net/http"
"os"
@@ -138,8 +137,6 @@ func parseReleaseData(data string) (time.Time, error) {
// Minio (OS; ARCH) APP/VER APP/VER
var (
userAgentSuffix = "Minio/" + Version + " " + "Minio/" + ReleaseTag + " " + "Minio/" + CommitID
- userAgentPrefix = "Minio (" + runtime.GOOS + "; " + runtime.GOARCH + ") "
- userAgent = userAgentPrefix + userAgentSuffix
)
// Check if the operating system is a docker container.
@@ -200,8 +197,15 @@ func getReleaseUpdate(updateURL string, duration time.Duration) (updateMsg updat
return
}
+ userAgentPrefix := func() string {
+ if isDocker() {
+ return "Minio (" + runtime.GOOS + "; " + runtime.GOARCH + "; " + "docker) "
+ }
+ return "Minio (" + runtime.GOOS + "; " + runtime.GOARCH + ") "
+ }()
+
// Set user agent.
- req.Header.Set("User-Agent", userAgent+" "+fmt.Sprintf("Docker/%t", isDocker()))
+ req.Header.Set("User-Agent", userAgentPrefix+" "+userAgentSuffix)
// Fetch new update.
resp, err := client.Do(req)
diff --git a/cmd/update-main_nix_test.go b/cmd/update-main_nix_test.go
index <HASH>..<HASH> 100644
--- a/cmd/update-main_nix_test.go
+++ b/cmd/update-main_nix_test.go
@@ -37,8 +37,6 @@ func TestReleaseUpdateVersion(t *testing.T) {
fmt.Fprintln(w, "fbe246edbd382902db9a4035df7dce8cb441357d minio.RELEASE.2016-10-07T01-16-39Z")
}))
userAgentSuffix = "Minio/" + Version + " " + "Minio/" + ReleaseTag + " " + "Minio/" + CommitID
- userAgentPrefix = "Minio (" + runtime.GOOS + "; " + runtime.GOARCH + ") "
- userAgent = userAgentPrefix + userAgentSuffix
defer ts.Close()
testCases := []struct {
updateURL string
diff --git a/cmd/update-main_windows_test.go b/cmd/update-main_windows_test.go
index <HASH>..<HASH> 100644
--- a/cmd/update-main_windows_test.go
+++ b/cmd/update-main_windows_test.go
@@ -37,8 +37,6 @@ func TestReleaseUpdateVersion(t *testing.T) {
fmt.Fprintln(w, "fbe246edbd382902db9a4035df7dce8cb441357d minio.RELEASE.2016-10-07T01-16-39Z")
}))
userAgentSuffix = "Minio/" + Version + " " + "Minio/" + ReleaseTag + " " + "Minio/" + CommitID
- userAgentPrefix = "Minio (" + runtime.GOOS + "; " + runtime.GOARCH + ") "
- userAgent = userAgentPrefix + userAgentSuffix
defer ts.Close()
testCases := []struct {
updateURL string
|
Fix user-agent prefix to have docker instead of suffix. (#<I>)
|
minio_minio
|
train
|
50447e23c1de0236aaab34ebbf1bf182924c6bde
|
diff --git a/gwtbootstrap3/src/main/java/org/gwtbootstrap3/client/ui/form/validator/BlankValidator.java b/gwtbootstrap3/src/main/java/org/gwtbootstrap3/client/ui/form/validator/BlankValidator.java
index <HASH>..<HASH> 100644
--- a/gwtbootstrap3/src/main/java/org/gwtbootstrap3/client/ui/form/validator/BlankValidator.java
+++ b/gwtbootstrap3/src/main/java/org/gwtbootstrap3/client/ui/form/validator/BlankValidator.java
@@ -51,7 +51,7 @@ public class BlankValidator<T> extends AbstractValidator<T> {
/** {@inheritDoc} */
@Override
public int getPriority() {
- return Priority.HIGHEST;
+ return Priority.LOWEST;
}
/** {@inheritDoc} */
diff --git a/gwtbootstrap3/src/main/java/org/gwtbootstrap3/client/ui/form/validator/ValidatorWrapper.java b/gwtbootstrap3/src/main/java/org/gwtbootstrap3/client/ui/form/validator/ValidatorWrapper.java
index <HASH>..<HASH> 100644
--- a/gwtbootstrap3/src/main/java/org/gwtbootstrap3/client/ui/form/validator/ValidatorWrapper.java
+++ b/gwtbootstrap3/src/main/java/org/gwtbootstrap3/client/ui/form/validator/ValidatorWrapper.java
@@ -54,7 +54,7 @@ public class ValidatorWrapper<T> implements Comparable<ValidatorWrapper<T>> {
/** {@inheritDoc} */
@Override
public int compareTo(ValidatorWrapper<T> other) {
- if (getName().equals(other.getName())) { return 0; }
+ if (this == other || getName().equals(other.getName())) { return 0; }
int result = getPriority().compareTo(other.getPriority());
if (result == 0) {
result = getInsertionOrder().compareTo(other.getInsertionOrder());
|
Validators are validated from highest priority to lowest priority.
|
gwtbootstrap3_gwtbootstrap3
|
train
|
998f8f2409509f82c4c8393f1401fa78a0243a61
|
diff --git a/examples/basic_usage.py b/examples/basic_usage.py
index <HASH>..<HASH> 100644
--- a/examples/basic_usage.py
+++ b/examples/basic_usage.py
@@ -58,11 +58,9 @@ def main():
reports = ts.get_latest_reports(token)
for report in reports:
- break;
-
- result = ts.get_report_details(token, report['id'])
- print("Getting Report Details using '%s': \n\t%s" % (report['id'], json.dumps(result, indent=4)))
- print()
+ result = ts.get_report_details(token, report['id'])
+ print("Getting Report Details using '%s': \n%s" % (report['id'], json.dumps(result, indent=4)))
+ print()
if do_query_indicators:
print("Querying correlated indicators with search string '%s' (first 100)" % search_string)
|
Change do_report_details in basic_usage to get details of 5 different reports
|
trustar_trustar-python
|
train
|
0bac1c02b1f07862a0affa1646f586c8ae877b14
|
diff --git a/lib/state_machine/integrations/mongo_mapper.rb b/lib/state_machine/integrations/mongo_mapper.rb
index <HASH>..<HASH> 100644
--- a/lib/state_machine/integrations/mongo_mapper.rb
+++ b/lib/state_machine/integrations/mongo_mapper.rb
@@ -229,7 +229,9 @@ module StateMachine
def define_state_initializer
@instance_helper_module.class_eval <<-end_eval, __FILE__, __LINE__
def initialize(attrs = {}, *args)
- if args.first || !attrs || !attrs.stringify_keys.key?('_id')
+ from_database = args.first
+
+ if !from_database && (!attrs || !attrs.stringify_keys.key?('_id'))
filtered = respond_to?(:filter_protected_attrs) ? filter_protected_attrs(attrs) : attrs
ignore = filtered ? filtered.keys : []
|
Fix from_database param in #initialize not being respected properly for MongoMapper <I>+ documents
|
pluginaweek_state_machine
|
train
|
a54480b727b32af66fd22da5194ebfbfe0bfee03
|
diff --git a/js/feature/segTrack.js b/js/feature/segTrack.js
index <HASH>..<HASH> 100755
--- a/js/feature/segTrack.js
+++ b/js/feature/segTrack.js
@@ -45,7 +45,7 @@ class SegTrack extends TrackBase {
this.type = config.type || "seg";
if (this.type === 'maf') this.type = 'mut';
this.isLog = config.isLog;
- this.displayMode = config.displayMode || "EXPANDED"; // EXPANDED | SQUISHED -- TODO perhaps set his based on sample count
+ this.displayMode = config.displayMode || "EXPANDED"; // EXPANDED | SQUISHED
this.height = config.height || 300;
this.maxHeight = config.maxHeight || 500;
this.squishedRowHeight = config.sampleSquishHeight || config.squishedRowHeight || 2;
@@ -119,11 +119,11 @@ class SegTrack extends TrackBase {
{
"SQUISHED": "Squish",
"EXPANDED": "Expand",
- "FILL": "Fill",
+ "FILL": "Fill"
};
menuItems.push('<hr/>');
- menuItems.push("Sample Height:");
+ menuItems.push("DisplayMode:");
const displayOptions = this.type === 'seg' ? ["SQUISHED", "EXPANDED", "FILL"] : ["SQUISHED", "EXPANDED"];
@@ -198,7 +198,6 @@ class SegTrack extends TrackBase {
this.sampleHeight = this.squishedRowHeight;
border = 0;
break;
-
default: // EXPANDED
this.sampleHeight = this.expandedRowHeight;
border = 1;
@@ -315,13 +314,13 @@ class SegTrack extends TrackBase {
* Optional method to compute pixel height to accomodate the list of features. The implementation below
* has side effects (modifiying the samples hash). This is unfortunate, but harmless.
*
+ * Note displayMode "FILL" is handled by the viewport
+ *
* @param features
* @returns {number}
*/
computePixelHeight(features) {
-
if (!features) return 0;
-
const sampleHeight = ("SQUISHED" === this.displayMode) ? this.squishedRowHeight : this.expandedRowHeight;
this.updateSampleKeys(features);
return this.sampleKeys.length * sampleHeight;
@@ -399,16 +398,12 @@ class SegTrack extends TrackBase {
clickedFeatures(clickState, features) {
const allFeatures = super.clickedFeatures(clickState, features);
- return filterByRow(allFeatures, clickState.y);
+ const y = clickState.y;
+ return allFeatures.filter(function (feature) {
+ const rect = feature.pixelRect;
+ return rect && y >= rect.y && y <= (rect.y + rect.h);
+ })
- function filterByRow(features, y) {
-
- return features.filter(function (feature) {
- const rect = feature.pixelRect;
- return rect && y >= rect.y && y <= (rect.y + rect.h);
- });
-
- }
}
popupData(clickState, featureList) {
|
Rename "sampleHeight" option for seg/mut tracks to "displayMode" for consistency with other track types. Also sample height: implies you can set the sample height, which you can't.
|
igvteam_igv.js
|
train
|
fbedce34d736fcb4c38168c67a1f7b171d9bde9f
|
diff --git a/src/PhpParser/Node/Value/ValueResolver.php b/src/PhpParser/Node/Value/ValueResolver.php
index <HASH>..<HASH> 100644
--- a/src/PhpParser/Node/Value/ValueResolver.php
+++ b/src/PhpParser/Node/Value/ValueResolver.php
@@ -191,7 +191,10 @@ final class ValueResolver
return $fileInfo->getPathname();
}
- private function resolveClassConstFetch(ClassConstFetch $classConstFetch): string
+ /**
+ * @return mixed
+ */
+ private function resolveClassConstFetch(ClassConstFetch $classConstFetch)
{
$class = $this->nodeNameResolver->getName($classConstFetch->class);
$constant = $this->nodeNameResolver->getName($classConstFetch->name);
|
change return type of resolveClassConstFetch to mixed (#<I>)
|
rectorphp_rector
|
train
|
f33b173873f09e7ecb3cf117359a0186e11676a8
|
diff --git a/src/test/java/com/p6spy/engine/spy/P6TestPreparedStatement.java b/src/test/java/com/p6spy/engine/spy/P6TestPreparedStatement.java
index <HASH>..<HASH> 100644
--- a/src/test/java/com/p6spy/engine/spy/P6TestPreparedStatement.java
+++ b/src/test/java/com/p6spy/engine/spy/P6TestPreparedStatement.java
@@ -19,28 +19,22 @@
*/
package com.p6spy.engine.spy;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.io.IOException;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-
+import com.p6spy.engine.logging.P6LogOptions;
+import com.p6spy.engine.test.P6TestFramework;
import net.sf.cglib.proxy.Proxy;
-
import org.junit.After;
import org.junit.Before;
-import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
-import com.p6spy.engine.logging.P6LogOptions;
-import com.p6spy.engine.test.P6TestFramework;
+import java.io.IOException;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+import static org.junit.Assert.*;
@RunWith(Parameterized.class)
public class P6TestPreparedStatement extends P6TestFramework {
@@ -100,9 +94,11 @@ public class P6TestPreparedStatement extends P6TestFramework {
public void testSameColumnNameInMultipleTables() throws SQLException {
// fix pending uncomment for tesing of the:
+/*
if ("Oracle".equals(db)) {
return;
}
+*/
try {
// insert test data
|
uncomment failing test on oracle
|
p6spy_p6spy
|
train
|
10c7f9ecbd64bb87b5410c4978c5bbf326f23bca
|
diff --git a/tests/GoogleCloudStorageAdapterTest.php b/tests/GoogleCloudStorageAdapterTest.php
index <HASH>..<HASH> 100644
--- a/tests/GoogleCloudStorageAdapterTest.php
+++ b/tests/GoogleCloudStorageAdapterTest.php
@@ -117,7 +117,7 @@ class GoogleCloudStorageAdapterTest extends \PHPUnit_Framework_TestCase
public function canCreateDirectories()
{
$testId = uniqid('', true);
- $destinationPath = "/test_content{$testId}";
+ $destinationPath = "/test_content-canCreateDirectories-{$testId}";
$minimalConfig = [
'bucket' => $this->bucket,
@@ -137,8 +137,8 @@ class GoogleCloudStorageAdapterTest extends \PHPUnit_Framework_TestCase
public function testAFileCanBeRead()
{
$testId = uniqid('', true);
- $destinationPath = "/test_{$testId}_text.txt";
- $content = 'TestContent';
+ $destinationPath = "/test_testAFileCanBeRead-{$testId}_text.txt";
+ $content = 'testAFileCanBeRead';
$minimalConfig = [
'bucket' => $this->bucket,
@@ -167,7 +167,7 @@ class GoogleCloudStorageAdapterTest extends \PHPUnit_Framework_TestCase
'The mime type is available'
);
$this->assertEquals(
- 11,
+ strlen($content),
$adapter->getSize($destinationPath)['size'],
'The size from the metadata matches the input'
);
@@ -206,7 +206,7 @@ class GoogleCloudStorageAdapterTest extends \PHPUnit_Framework_TestCase
public function testPrefixesCanBeUsed()
{
$testId = uniqid();
- $testPrefix = "my/prefix/{$testId}/";
+ $testPrefix = "my/prefix/testPrefixesCanBeUsed-{$testId}/";
$simpleConfig = new Config([]);
$prefixedAdapterConfig = [
@@ -242,7 +242,7 @@ class GoogleCloudStorageAdapterTest extends \PHPUnit_Framework_TestCase
public function testCanBeWrappedWithAFilesystem()
{
$testId = uniqid('', true);
- $destinationPath = "/test_content{$testId}/test.txt";
+ $destinationPath = "/test_content-testCanBeWrappedWithAFilesystem-{$testId}/test.txt";
$adapterConfig = [
'bucket' => $this->bucket,
@@ -271,8 +271,8 @@ class GoogleCloudStorageAdapterTest extends \PHPUnit_Framework_TestCase
public function testVisibilityCanBeSetOnWrite()
{
$testId = uniqid('', true);
- $destinationPathPrivate = "/test_content{$testId}/test-private.txt";
- $destinationPathPublic = "/test_content{$testId}/test-public.txt";
+ $destinationPathPrivate = "/test_content-testVisibilityCanBeSetOnWrite-{$testId}/test-private.txt";
+ $destinationPathPublic = "/test_content-testVisibilityCanBeSetOnWrite-{$testId}/test-public.txt";
$adapterConfig = [
'bucket' => $this->bucket,
@@ -324,9 +324,9 @@ class GoogleCloudStorageAdapterTest extends \PHPUnit_Framework_TestCase
public function testCanUpdateAFile()
{
$testId = uniqid('', true);
- $destination = "/test_content{$testId}/test.txt";
- $initialContent = 'Foo';
- $updatedContent = 'Bar';
+ $destination = "/test_content-testCanUpdateAFile-{$testId}/test.txt";
+ $initialContent = 'testCanUpdateAFile';
+ $updatedContent = 'testCanUpdateAFile-update';
$adapterConfig = [
'bucket' => $this->bucket,
@@ -347,9 +347,9 @@ class GoogleCloudStorageAdapterTest extends \PHPUnit_Framework_TestCase
public function testCanCopyObject()
{
$testId = uniqid('', true);
- $destination = "/test_content{$testId}/test.txt";
- $copyDestination = "/test_content{$testId}/test-copy.txt";
- $initialContent = 'Foo';
+ $destination = "/test_content-testCanCopyObject-{$testId}/test.txt";
+ $copyDestination = "/test_content-testCanCopyObject-{$testId}/test-copy.txt";
+ $initialContent = 'testCanCopyObject';
$adapterConfig = [
'bucket' => $this->bucket,
@@ -372,9 +372,9 @@ class GoogleCloudStorageAdapterTest extends \PHPUnit_Framework_TestCase
public function testCanRenameObject()
{
$testId = uniqid('', true);
- $originalDestination = "/test_content{$testId}/test.txt";
- $renameDestination = "/test_content{$testId}/test-rename.txt";
- $initialContent = 'Foo';
+ $originalDestination = "/test_content-testCanRenameObject-{$testId}/test.txt";
+ $renameDestination = "/test_content-testCanRenameObject-{$testId}/test-rename.txt";
+ $initialContent = 'testCanRenameObject';
$adapterConfig = [
'bucket' => $this->bucket,
|
Append and prepend test-specific names to objects
|
cedricziel_flysystem-gcs
|
train
|
61ae9f1d978d6f5ff6742aead1e1701868271df0
|
diff --git a/src/shogun2-core/shogun2-model/src/main/java/de/terrestris/shogun2/model/module/WfsSearch.java b/src/shogun2-core/shogun2-model/src/main/java/de/terrestris/shogun2/model/module/WfsSearch.java
index <HASH>..<HASH> 100644
--- a/src/shogun2-core/shogun2-model/src/main/java/de/terrestris/shogun2/model/module/WfsSearch.java
+++ b/src/shogun2-core/shogun2-model/src/main/java/de/terrestris/shogun2/model/module/WfsSearch.java
@@ -20,6 +20,12 @@ import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
+import com.fasterxml.jackson.annotation.JsonIdentityInfo;
+import com.fasterxml.jackson.annotation.JsonIdentityReference;
+import com.fasterxml.jackson.annotation.ObjectIdGenerators;
+
+import de.terrestris.shogun2.model.layer.Layer;
+
/**
* A module to search features of a WFS.
*
@@ -35,18 +41,27 @@ public class WfsSearch extends Module {
*/
private static final long serialVersionUID = 1L;
-// /**
-// * A list of EPSG-Codes the should be available in the module.
-// */
-// @ElementCollection(fetch = FetchType.EAGER)
-// @CollectionTable(name = "WfsSearch_Layers", joinColumns = @JoinColumn(name = "WfsSearch_ID") )
-// @Column(name = "Layer")
-// @OrderColumn(name = "INDEX")
-// private List<Layer> layers = new ArrayList<Layer>();
+ /**
+ * The layers to search in.
+ */
+ @ElementCollection(fetch = FetchType.EAGER)
+ @CollectionTable(name = "WFSSEARCH_LAYERS", joinColumns = @JoinColumn(name = "WFSSEARCH_ID") )
+ @Column(name = "LAYER")
+ @OrderColumn(name = "INDEX")
+ // The List of layers will be serialized (JSON) as an array of ID values
+ @JsonIdentityInfo(
+ generator = ObjectIdGenerators.PropertyGenerator.class,
+ property = "id"
+ )
+ @JsonIdentityReference(alwaysAsId = true)
+ private List<Layer> layers = new ArrayList<Layer>();
+ /**
+ * The WFS server URL
+ */
private String wfsServerUrl;
- /*
+ /**
* Characters needed to send a request.
*/
private Integer minSearchTextChars;
@@ -57,7 +72,8 @@ public class WfsSearch extends Module {
private Integer typeDelay;
/**
- * A list of EPSG-Codes the should be available in the module.
+ * The allowed data-types to match against in the describefeaturetype
+ * response
*/
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "WFSSEARCH_FEATUREDATATYPES", joinColumns = @JoinColumn(name = "WFSSEARCH_ID") )
@@ -79,6 +95,20 @@ public class WfsSearch extends Module {
}
/**
+ * @return the layers
+ */
+ public List<Layer> getLayers() {
+ return layers;
+ }
+
+ /**
+ * @param layers the layers to set
+ */
+ public void setLayers(List<Layer> layers) {
+ this.layers = layers;
+ }
+
+ /**
* @return the wfsServerUrl
*/
public String getWfsServerUrl() {
|
Enable the layers property of the WfsSearch module
At the time of the modeling of the WfsSearch class, the Layer model was not yet existing. This commit enables this property. The List of layers will be serialized by Jackson as an array of ID values as we don't want the whole layer objects to be serialized here.
|
terrestris_shogun-core
|
train
|
8a7c76af911d87be60135eabc057d87f8321027c
|
diff --git a/src/phpDocumentor/Application.php b/src/phpDocumentor/Application.php
index <HASH>..<HASH> 100644
--- a/src/phpDocumentor/Application.php
+++ b/src/phpDocumentor/Application.php
@@ -12,13 +12,12 @@
namespace phpDocumentor;
-use \Symfony\Component\Console\Input\InputInterface;
+/**
+ * Finds and activates the autoloader.
+ */
+require_once findAutoloader();
-if (file_exists(__DIR__ . '/../../vendor/autoload.php')) {
- require_once __DIR__ . '/../../vendor/autoload.php';
-} else if (file_exists(__DIR__ . '/../../../../../vendor/autoload.php')) {
- require_once __DIR__ . '/../../../../../vendor/autoload.php';
-}
+use \Symfony\Component\Console\Input\InputInterface;
/**
* Application class for phpDocumentor.
@@ -114,11 +113,7 @@ class Application extends \Cilex\Application
*/
protected function addAutoloader()
{
- if (file_exists(__DIR__ . '/../../vendor/autoload.php')) {
- $this['autoloader'] = __DIR__ . '/../../vendor/autoload.php';
- } else if (file_exists(__DIR__ . '/../../../../../vendor/autoload.php')) {
- $this['autoloader'] = __DIR__ . '/../../../../../vendor/autoload.php';
- }
+ $this['autoloader'] = include findAutoloader();
}
/**
@@ -223,3 +218,28 @@ class Application extends \Cilex\Application
$this['plugin_manager']->loadFromConfiguration();
}
}
+
+/**
+ * Tries to find the autoloader relative to ththis file and return its path.
+ *
+ * @throws \RuntimeException if the autoloader could not be found.
+ *
+ * @return string the path of the autoloader.
+ */
+function findAutoloader()
+{
+ $autoloader_base_path = '/../../vendor/autoload.php';
+
+ // if the file does not exist from a base path it is included as vendor
+ $autoloader_location = file_exists(__DIR__ . $autoloader_base_path)
+ ? __DIR__ . $autoloader_base_path
+ : __DIR__ . '/../../..' . $autoloader_base_path;
+
+ if (!file_exists($autoloader_location)) {
+ throw new \RuntimeException(
+ 'Unable to find autoloader at ' . $autoloader_location
+ );
+ }
+
+ return $autoloader_location;
+}
|
Fix comment of revision 1ec1fa3d
The Autoloader in the DIC is not properly initialized. Only the path to the autoloader is stored.
Also remove the duplication between the top of the file and the inclusion of the autoloader since
the code required to find the autoloader has become more complex.
|
phpDocumentor_phpDocumentor2
|
train
|
54a680960674adef74fea95b8185d83ccfbe1bb2
|
diff --git a/flake8_filename/__init__.py b/flake8_filename/__init__.py
index <HASH>..<HASH> 100644
--- a/flake8_filename/__init__.py
+++ b/flake8_filename/__init__.py
@@ -45,7 +45,7 @@ class FilenameChecker(object):
for single_line in filename_data:
a = [s.strip() for s in single_line.split('=')]
# whitelist the acceptable params
- if a[0] in ['filter_regex', 'filename_regex']:
+ if a[0] in ['filter_regex', 'filename_regex', 'filter_with_ext']:
parsed_params[a[0]] = a[1]
d[filename_check] = parsed_params
cls.filename_checks.update(d)
diff --git a/flake8_filename/rules.py b/flake8_filename/rules.py
index <HASH>..<HASH> 100644
--- a/flake8_filename/rules.py
+++ b/flake8_filename/rules.py
@@ -35,7 +35,9 @@ def rule_n5xx(filename, rule_name, rule_conf, class_type):
code = _generate_mark_code(rule_name)
message = "N5{} filename failed regex validation '{}'".format(code, rule_conf['filename_regex'])
- sanitized_filename = splitext(basename(filename))[0] # Strip path and extension
+ sanitized_filename = basename(filename) # Strip path
+ if not rule_conf.get("filter_with_ext"):
+ sanitized_filename = splitext(sanitized_filename)[0] # Strip extension
if re.match(rule_conf['filter_regex'], sanitized_filename):
if not re.match(rule_conf['filename_regex'], sanitized_filename):
|
Add config to include extension in filter_regex
|
rcbops_flake8-filename
|
train
|
92d7f2e706cecefb237ba5ca0a1b550efcaa71ae
|
diff --git a/src/Console/ModelsCommand.php b/src/Console/ModelsCommand.php
index <HASH>..<HASH> 100644
--- a/src/Console/ModelsCommand.php
+++ b/src/Console/ModelsCommand.php
@@ -1097,7 +1097,14 @@ class ModelsCommand extends Command
}
$modelName = get_class($model);
- $factory = get_class($modelName::factory());
+ $modelBaseName = class_basename($modelName);
+
+ $factory = "\Database\Factories\\{$modelBaseName}Factory";
+
+ if ($modelName::newFactory()) {
+ $factory = get_class($modelName::newFactory());
+ }
+
$factory = '\\' . trim($factory, '\\');
if (!class_exists($factory)) {
|
fix ide-helper:models error if model doesn't have factory
|
barryvdh_laravel-ide-helper
|
train
|
9146ace1cbc8e8e4cfebe93daeb26808e409ff7a
|
diff --git a/platform/net/firewall_provider_linux.go b/platform/net/firewall_provider_linux.go
index <HASH>..<HASH> 100644
--- a/platform/net/firewall_provider_linux.go
+++ b/platform/net/firewall_provider_linux.go
@@ -47,9 +47,8 @@ func SetupNatsFirewall(mbus string) error {
if err != nil {
if errors.Is(err, cgroups.ErrMountPointNotExist) {
return nil // v1cgroups are not mounted (warden stemcells)
- } else {
- return bosherr.WrapError(err, "Error retrieving cgroups mount point")
}
+ return bosherr.WrapError(err, "Error retrieving cgroups mount point")
}
mbusURL, err := gonetURL.Parse(mbus)
if err != nil || mbusURL.Hostname() == "" {
|
Fix golint issues to unblock ci
```
platform/net/firewall_provider_linux.go:<I>:<I>: if block ends with a return statement, so drop this else and outdent its block
```
|
cloudfoundry_bosh-agent
|
train
|
0de805b419c218ca606a03eaa674fa62e2062e8a
|
diff --git a/lib/DB/dsql/mysql.php b/lib/DB/dsql/mysql.php
index <HASH>..<HASH> 100644
--- a/lib/DB/dsql/mysql.php
+++ b/lib/DB/dsql/mysql.php
@@ -5,6 +5,10 @@
* rendering methods which appear differently on your database.
*/
class DB_dsql_mysql extends DB_dsql {
+ function init(){
+ parent::init();
+ $this->sql_templates['update']="update [table] set [set] [where]";
+ }
function calc_found_rows(){
return $this->option('SQL_CALC_FOUND_ROWS');
}
|
MySQL supports alias in "update" which are needed for addCondition() in models
|
atk4_atk4
|
train
|
d7bb1f733352399aba88e0178203ba4077ac954a
|
diff --git a/master/buildbot/process/buildrequestdistributor.py b/master/buildbot/process/buildrequestdistributor.py
index <HASH>..<HASH> 100644
--- a/master/buildbot/process/buildrequestdistributor.py
+++ b/master/buildbot/process/buildrequestdistributor.py
@@ -65,7 +65,7 @@ class BuildChooserBase(object):
worker, breq = yield self.popNextBuild()
if not worker or not breq:
defer.returnValue((None, None))
- return
+ return # pragma: no cover
defer.returnValue((worker, [breq]))
@@ -229,7 +229,7 @@ class BasicBuildChooser(BuildChooserBase):
yield self._fetchUnclaimedBrdicts()
if not self.unclaimedBrdicts:
defer.returnValue(None)
- return
+ return # pragma: no cover
if self.nextBuild:
# nextBuild expects BuildRequest objects
@@ -255,7 +255,7 @@ class BasicBuildChooser(BuildChooserBase):
if self.preferredWorkers:
worker = self.preferredWorkers.pop(0)
defer.returnValue(worker)
- return
+ return # pragma: no cover
while self.workerpool:
try:
@@ -274,7 +274,7 @@ class BasicBuildChooser(BuildChooserBase):
canStart = yield self.bldr.canStartWithWorkerForBuilder(worker, [buildrequest])
if canStart:
defer.returnValue(worker)
- return
+ return # pragma: no cover
# save as a last resort, just in case we need them later
if self.rejectedWorkers is not None:
@@ -284,7 +284,7 @@ class BasicBuildChooser(BuildChooserBase):
if self.rejectedWorkers:
worker = self.rejectedWorkers.pop(0)
defer.returnValue(worker)
- return
+ return # pragma: no cover
defer.returnValue(None)
@@ -373,7 +373,7 @@ class BuildRequestDistributor(service.AsyncMultiService):
# if we won't add any builders, there's nothing to do
if new_builders < existing_pending:
defer.returnValue(None)
- return
+ return # pragma: no cover
# reset the list of pending builders
@defer.inlineCallbacks
|
buildrequestdistributor: Disable coverage on return after returnValue
|
buildbot_buildbot
|
train
|
424b23033f2f9ef4b5907fedcf8f8f36861c5d5c
|
diff --git a/src/Rcm/Controller/PageSearchApiController.php b/src/Rcm/Controller/PageSearchApiController.php
index <HASH>..<HASH> 100644
--- a/src/Rcm/Controller/PageSearchApiController.php
+++ b/src/Rcm/Controller/PageSearchApiController.php
@@ -2,16 +2,21 @@
namespace Rcm\Controller;
+use Rcm\Plugin\BaseController;
use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\View\Model\JsonModel;
use Zend\Http\Response;
use Rcm\Entity\Site;
use Rcm\Service\PageManager;
+use Rcm\Controller\PageCheckController;
-class PageSearchApiController extends AbstractRestfulController
+class PageSearchApiController extends PageManager
{
function siteTitleSearchAction()
{
+
+
+
$query = $this->getEvent()->getRouteMatch()->getParam('query');
$em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
$sm = $this->getServiceLocator()->get(
|
got dialog box to pop up for navigation.
|
reliv_Rcm
|
train
|
4fbbbe7d1f6c4951a466b96183b9291e2401a9c5
|
diff --git a/sharding-jdbc-core/src/main/java/com/dangdang/ddframe/rdb/sharding/parsing/parser/statement/dql/select/SelectStatement.java b/sharding-jdbc-core/src/main/java/com/dangdang/ddframe/rdb/sharding/parsing/parser/statement/dql/select/SelectStatement.java
index <HASH>..<HASH> 100644
--- a/sharding-jdbc-core/src/main/java/com/dangdang/ddframe/rdb/sharding/parsing/parser/statement/dql/select/SelectStatement.java
+++ b/sharding-jdbc-core/src/main/java/com/dangdang/ddframe/rdb/sharding/parsing/parser/statement/dql/select/SelectStatement.java
@@ -141,8 +141,13 @@ public final class SelectStatement extends DQLStatement {
* @return 子查询的Select SQL语句对象
*/
public SelectStatement getSubQueryStatement() {
+ SelectStatement result = processLimitForSubQuery();
+ processOrderByItems(result);
+ return result;
+ }
+
+ private SelectStatement processLimitForSubQuery() {
SelectStatement result = this;
- boolean isRootQueryContainsStar = result.isContainStar();
Limit limit = result.getLimit();
List<SQLToken> limitSQLTokens = new LinkedList<>();
for (SQLToken each : result.getSqlTokens()) {
@@ -167,10 +172,6 @@ public final class SelectStatement extends DQLStatement {
}
}
}
- if (!isRootQueryContainsStar) {
- result.getOrderByItems().clear();
- result.getGroupByItems().clear();
- }
result.setLimit(limit);
int count = 0;
List<Integer> toBeRemovedIndexes = new LinkedList<>();
@@ -186,4 +187,11 @@ public final class SelectStatement extends DQLStatement {
result.getSqlTokens().addAll(limitSQLTokens);
return result;
}
+
+ private void processOrderByItems(final SelectStatement result) {
+ if (!containStar) {
+ result.getOrderByItems().clear();
+ result.getGroupByItems().clear();
+ }
+ }
}
|
refactor select sub query 3rd version
|
apache_incubator-shardingsphere
|
train
|
e5fdbfb48a9b8f010aecf450f99281283bab22af
|
diff --git a/recovery_test.go b/recovery_test.go
index <HASH>..<HASH> 100644
--- a/recovery_test.go
+++ b/recovery_test.go
@@ -91,7 +91,7 @@ func TestRecovery_formatter(t *testing.T) {
recorder := httptest.NewRecorder()
formatter := newTestOutput()
- req, _ := http.NewRequest("GET", "http://localhost:3003/somePath?element=true", http.NoBody)
+ req, _ := http.NewRequest("GET", "http://localhost:3003/somePath?element=true", nil)
var element interface{} = "here is a panic!"
expectedInfos := &PanicInformations{RecoveredElement: element, Request: req}
@@ -110,14 +110,14 @@ func TestRecovery_formatter(t *testing.T) {
func TestRecovery_PanicInformations(t *testing.T) {
// Request with query
- req, _ := http.NewRequest("GET", "http://localhost:3003/somePath?element=true", http.NoBody)
+ req, _ := http.NewRequest("GET", "http://localhost:3003/somePath?element=true", nil)
var element interface{} = "here is a panic!"
expectedInfos := &PanicInformations{RecoveredElement: element, Request: req}
expect(t, expectedInfos.RequestDescription(), "GET /somePath?element=true")
// Request without Query
- req, _ = http.NewRequest("POST", "http://localhost:3003/somePath", http.NoBody)
+ req, _ = http.NewRequest("POST", "http://localhost:3003/somePath", nil)
element = "here is a panic!"
expectedInfos = &PanicInformations{RecoveredElement: element, Request: req}
|
Attempt to fix CI
Apparently, http.NoBody was not the best choice.
|
urfave_negroni
|
train
|
f40576d06b9b1add07054c9c33c306af75f524c3
|
diff --git a/lib/demeteorizer.js b/lib/demeteorizer.js
index <HASH>..<HASH> 100644
--- a/lib/demeteorizer.js
+++ b/lib/demeteorizer.js
@@ -219,7 +219,7 @@ Demeteorizer.prototype.createPackageJSON = function(dependencies, input, output,
// Remove spaces.
name = name.replace(/' '/g, '');
- var nodeVersionJSON = {"node": nodeVersion};
+ var nodeVersionJSON = { "node": nodeVersion.replace('v', '') };
var packageJSON = {};
packageJSON.name = name;
|
Removed leading v from node version added to package.json.
|
XervoIO_demeteorizer
|
train
|
3975208552f2ae7813cd4a19380e3ab81847a1ad
|
diff --git a/js/bitmax.js b/js/bitmax.js
index <HASH>..<HASH> 100644
--- a/js/bitmax.js
+++ b/js/bitmax.js
@@ -312,12 +312,26 @@ module.exports = class bitmax extends Exchange {
request['n'] = limit; // default = maximum = 100
}
const response = await this.publicGetDepth (this.extend (request, params));
- const orderbook = this.parseOrderBook (response);
+ //
+ // {
+ // "m":"depth",
+ // "ts":1570866464777,
+ // "seqnum":5124140078,
+ // "s":"ETH/USDT",
+ // "asks":[
+ // ["183.57","5.92"],
+ // ["183.6","10.185"]
+ // ],
+ // "bids":[
+ // ["183.54","0.16"],
+ // ["183.53","10.8"],
+ // ]
+ // }
+ //
const timestamp = this.safeInteger (response, 'ts');
- orderbook['nonce'] = timestamp;
- orderbook['timestamp'] = timestamp;
- orderbook['datetime'] = this.iso8601 (timestamp);
- return orderbook;
+ const result = this.parseOrderBook (response, timestamp);
+ result['nonce'] = this.safeInteger (response, 'seqnum');
+ return result;
}
parseTicker (ticker, market = undefined) {
|
bitmax fetchOrderBook edits
|
ccxt_ccxt
|
train
|
5ede387a70e56eb6b89c18acf00abdbf16908d20
|
diff --git a/client/driver/executor/executor.go b/client/driver/executor/executor.go
index <HASH>..<HASH> 100644
--- a/client/driver/executor/executor.go
+++ b/client/driver/executor/executor.go
@@ -247,14 +247,15 @@ func (e *UniversalExecutor) LaunchCmd(command *ExecCommand, ctx *ExecutorContext
}
e.ctx.TaskEnv.Build()
- // configuring the chroot, cgroup and enter the plugin process in the
- // chroot
+ // configuring the chroot, resource container, and start the plugin
+ // process in the chroot.
if err := e.configureIsolation(); err != nil {
return nil, err
}
- // Apply ourselves into the cgroup. The executor MUST be in the cgroup
- // before the user task is started, otherwise we are subject to a fork
- // attack in which a process escapes isolation by immediately forking.
+ // Apply ourselves into the resource container. The executor MUST be in
+ // the resource container before the user task is started, otherwise we
+ // are subject to a fork attack in which a process escapes isolation by
+ // immediately forking.
if err := e.applyLimits(os.Getpid()); err != nil {
return nil, err
}
@@ -428,8 +429,8 @@ func ClientCleanup(ic *dstructs.IsolationConfig, pid int) error {
return clientCleanup(ic, pid)
}
-// Exit cleans up the alloc directory, destroys cgroups and kills the user
-// process
+// Exit cleans up the alloc directory, destroys resource container and kills the
+// user process
func (e *UniversalExecutor) Exit() error {
var merr multierror.Error
if e.syslogServer != nil {
@@ -447,7 +448,7 @@ func (e *UniversalExecutor) Exit() error {
return nil
}
- // Prefer killing the process via cgroups.
+ // Prefer killing the process via the resource container.
if e.cmd.Process != nil && !e.command.ResourceLimits {
proc, err := os.FindProcess(e.cmd.Process.Pid)
if err != nil {
diff --git a/client/driver/executor/executor_linux.go b/client/driver/executor/executor_linux.go
index <HASH>..<HASH> 100644
--- a/client/driver/executor/executor_linux.go
+++ b/client/driver/executor/executor_linux.go
@@ -255,8 +255,8 @@ func (e *UniversalExecutor) configureChroot() error {
// should be called when tearing down the task.
func (e *UniversalExecutor) removeChrootMounts() error {
// Prevent a race between Wait/ForceStop
- e.cgLock.Lock()
- defer e.cgLock.Unlock()
+ e.resCon.cgLock.Lock()
+ defer e.resCon.cgLock.Unlock()
return e.ctx.AllocDir.UnmountAll()
}
|
Update comments and pushdown a lock into the resource container
|
hashicorp_nomad
|
train
|
0ab12c3db02c7f559c85b8e37cde3a09332018da
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -3,7 +3,7 @@
from setuptools import setup, find_packages
setup(
- name='model_script',
+ name='psamm',
version='0.7',
description='Metabolic modelling tools',
maintainer='Jon Lund Steffensen',
|
setup.py: Change name of package to "psamm"
|
zhanglab_psamm
|
train
|
ab05230b08afe5388e99fa45b7e115f65219fcd3
|
diff --git a/lib/components/app/batch-routing-panel.js b/lib/components/app/batch-routing-panel.js
index <HASH>..<HASH> 100644
--- a/lib/components/app/batch-routing-panel.js
+++ b/lib/components/app/batch-routing-panel.js
@@ -51,7 +51,7 @@ class BatchRoutingPanel extends Component {
<BatchSettings />
</div>
{!activeSearch && showUserSettings && (
- <UserSettings style={{ margin: '10px 0 0' }} />
+ <UserSettings style={{ margin: '0 10px', overflowY: 'auto' }} />
)}
<div
className="desktop-narrative-container"
diff --git a/lib/components/app/call-taker-panel.js b/lib/components/app/call-taker-panel.js
index <HASH>..<HASH> 100644
--- a/lib/components/app/call-taker-panel.js
+++ b/lib/components/app/call-taker-panel.js
@@ -275,7 +275,7 @@ class CallTakerPanel extends Component {
</div>
</div>
{!activeSearch && !showPlanTripButton && showUserSettings && (
- <UserSettings />
+ <UserSettings style={{ margin: '0 0 0 10px', overflowY: 'auto' }} />
)}
<div
className="desktop-narrative-container"
diff --git a/lib/components/form/user-settings.js b/lib/components/form/user-settings.js
index <HASH>..<HASH> 100644
--- a/lib/components/form/user-settings.js
+++ b/lib/components/form/user-settings.js
@@ -222,7 +222,7 @@ class UserSettings extends Component {
render() {
const {
- className,
+ className = '',
forgetSearch,
intl,
isUsingOtpMiddleware,
|
improvement(UserSettings): Add scrolling for batch/calltaker UIs.
|
opentripplanner_otp-react-redux
|
train
|
50dd38db434ef702a3fedf59f3cda63fa0d6b489
|
diff --git a/api/src/main/java/javax/enterprise/util/AnnotationLiteral.java b/api/src/main/java/javax/enterprise/util/AnnotationLiteral.java
index <HASH>..<HASH> 100644
--- a/api/src/main/java/javax/enterprise/util/AnnotationLiteral.java
+++ b/api/src/main/java/javax/enterprise/util/AnnotationLiteral.java
@@ -253,7 +253,10 @@ public abstract class AnnotationLiteral<T extends Annotation> implements Annotat
private static Object getMemberValue(Method member, Annotation instance) {
Object value = invoke(member, instance);
- assertMemberValueNotNull(member, instance, value);
+ if (value == null) {
+ throw new IllegalArgumentException("Annotation member value " + instance.getClass().getName() + "." + member.getName()
+ + " must not be null");
+ }
return value;
}
@@ -274,11 +277,4 @@ public abstract class AnnotationLiteral<T extends Annotation> implements Annotat
}
}
- private static void assertMemberValueNotNull(Method member, Annotation instance, Object value) {
- if (value == null) {
- throw new IllegalArgumentException("Annotation member " + instance.getClass().getName() + "." + member.getName()
- + " must not be null");
- }
- }
-
}
|
Inline method used only once on AnnotationLiteral
|
cdi-spec_cdi
|
train
|
add8de39cfb971d1947c25506d886e0b938847a5
|
diff --git a/android/src/main/java/com/swmansion/rnscreens/ScreenStackHeaderConfig.java b/android/src/main/java/com/swmansion/rnscreens/ScreenStackHeaderConfig.java
index <HASH>..<HASH> 100644
--- a/android/src/main/java/com/swmansion/rnscreens/ScreenStackHeaderConfig.java
+++ b/android/src/main/java/com/swmansion/rnscreens/ScreenStackHeaderConfig.java
@@ -76,6 +76,7 @@ public class ScreenStackHeaderConfig extends ViewGroup {
if (context.getTheme().resolveAttribute(android.R.attr.colorPrimary, tv, true)) {
mToolbar.setBackgroundColor(tv.data);
}
+ mToolbar.setClipChildren(false);
}
@Override
|
Don't clip custom header subviews on Android (#<I>)
This is most noticeable when using icons with ripple overflow.
|
kmagiera_react-native-screens
|
train
|
88aa28780ee3367e1815ec878336f2cb7f451825
|
diff --git a/ddl/db_integration_test.go b/ddl/db_integration_test.go
index <HASH>..<HASH> 100644
--- a/ddl/db_integration_test.go
+++ b/ddl/db_integration_test.go
@@ -2290,6 +2290,11 @@ func (s *testSerialDBSuite1) TestAddExpressionIndex(c *C) {
tk.MustQuery("select * from t;").Check(testkit.Rows("1 2.1"))
+ // Issue #26371
+ tk.MustExec("drop table if exists t1")
+ tk.MustExec("create table t1(a int, b int, primary key(a, b) clustered)")
+ tk.MustExec("alter table t1 add index idx((a+1))")
+
// Issue #17111
tk.MustExec("drop table if exists t1")
tk.MustExec("create table t1 (a varchar(10), b varchar(10));")
diff --git a/ddl/ddl_api.go b/ddl/ddl_api.go
index <HASH>..<HASH> 100644
--- a/ddl/ddl_api.go
+++ b/ddl/ddl_api.go
@@ -5140,13 +5140,16 @@ func (d *ddl) CreateIndex(ctx sessionctx.Context, ti ast.Ident, keyType ast.Inde
return errors.Trace(err)
}
+ finalColumns := make([]*model.ColumnInfo, len(tblInfo.Columns), len(tblInfo.Columns)+len(hiddenCols))
+ copy(finalColumns, tblInfo.Columns)
+ finalColumns = append(finalColumns, hiddenCols...)
// Check before the job is put to the queue.
// This check is redundant, but useful. If DDL check fail before the job is put
// to job queue, the fail path logic is super fast.
// After DDL job is put to the queue, and if the check fail, TiDB will run the DDL cancel logic.
// The recover step causes DDL wait a few seconds, makes the unit test painfully slow.
// For same reason, decide whether index is global here.
- indexColumns, err := buildIndexColumns(append(tblInfo.Columns, hiddenCols...), indexPartSpecifications)
+ indexColumns, err := buildIndexColumns(finalColumns, indexPartSpecifications)
if err != nil {
return errors.Trace(err)
}
@@ -5158,7 +5161,7 @@ func (d *ddl) CreateIndex(ctx sessionctx.Context, ti ast.Ident, keyType ast.Inde
if err != nil {
return err
}
- idxLen, err = indexColumnsLen(tblInfo.Columns, indexColumns)
+ idxLen, err = indexColumnsLen(finalColumns, indexColumns)
if err != nil {
return err
}
|
ddl: fix creating expression in clustered index table (#<I>)
|
pingcap_tidb
|
train
|
252aee8c34986d2fab5ae3ea28c1e7e7c47048b0
|
diff --git a/multiqc/modules/custom_content/custom_content.py b/multiqc/modules/custom_content/custom_content.py
index <HASH>..<HASH> 100644
--- a/multiqc/modules/custom_content/custom_content.py
+++ b/multiqc/modules/custom_content/custom_content.py
@@ -108,7 +108,7 @@ def custom_module_classes():
s_name = m_config.get('sample_name')
else:
c_id = k
- m_config = cust_mods[c_id]['config']
+ m_config = dict(cust_mods[c_id]['config'])
# Guess sample name if not given
if s_name is None:
|
Custom Content: Fixed newly introduced dict immutibility bug
|
ewels_MultiQC
|
train
|
0275262a5ed592b23e269623d2e6f509f4cf04bc
|
diff --git a/h2o-algos/src/test/java/hex/deeplearning/DeepLearningProstateTest.java b/h2o-algos/src/test/java/hex/deeplearning/DeepLearningProstateTest.java
index <HASH>..<HASH> 100755
--- a/h2o-algos/src/test/java/hex/deeplearning/DeepLearningProstateTest.java
+++ b/h2o-algos/src/test/java/hex/deeplearning/DeepLearningProstateTest.java
@@ -13,8 +13,6 @@ import water.fvec.Frame;
import water.fvec.NFSFileVec;
import water.fvec.Vec;
import water.parser.ParseDataset;
-import water.rapids.Env;
-import water.rapids.Exec;
import water.util.Log;
import java.util.Arrays;
@@ -345,7 +343,7 @@ public class DeepLearningProstateTest extends TestUtil {
if (valid == null) valid = frame;
double threshold;
if (model2._output.isClassifier()) {
- Frame pred = null, pred2 = null;
+ Frame pred = null;
Vec labels, predlabels, pred2labels;
try {
pred = model2.score(valid);
@@ -372,20 +370,11 @@ public class DeepLearningProstateTest extends TestUtil {
Log.info(cm.toASCII());
// Assert.assertEquals(cm.err(), error, 1e-4); //FIXME
- // manually make labels with AUC-given default threshold
- String ast = "(= ([ %pred2 \"null\" #0) (G ([ %pred2 \"null\" #2) #"+threshold+"))";
// confirm that orig CM was made with threshold 0.5
- // put pred2 into DKV, and allow access
- pred2 = new Frame(Key.make("pred2"), pred.names(), pred.vecs());
- pred2.delete_and_lock(null);
- pred2.unlock(null);
- Env ev = Exec.exec(ast);
- try {
- pred2 = ev.popAry(); // pop0 pops w/o lowering refs, let remove_and_unlock handle cleanup
- } finally {
- if (ev != null) ev.remove_and_unlock();
- }
- pred2labels = pred2.vecs()[0];
+ // manually make labels with AUC-given default threshold
+ String ast = "(= pred (> ([] pred 2) #"+threshold+") [0] [])";
+ Frame tmp = water.rapids.Exec.exec(ast).getFrame();
+ pred2labels = tmp.vecs()[0];
cm = buildCM(labels, pred2labels);
Log.info("CM from self-made labels:");
Log.info(cm.toASCII());
@@ -393,7 +382,6 @@ public class DeepLearningProstateTest extends TestUtil {
}
} finally {
if (pred != null) pred.delete();
- if (pred2 != null) pred2.delete();
}
} //classifier
else {
diff --git a/h2o-core/src/test/java/water/rapids/RapidsTest.java b/h2o-core/src/test/java/water/rapids/RapidsTest.java
index <HASH>..<HASH> 100644
--- a/h2o-core/src/test/java/water/rapids/RapidsTest.java
+++ b/h2o-core/src/test/java/water/rapids/RapidsTest.java
@@ -1,4 +1,4 @@
-package water.currents;
+package water.rapids;
import org.junit.Assert;
import org.junit.BeforeClass;
@@ -13,7 +13,7 @@ import water.parser.ParseSetup;
import java.io.File;
import java.util.Arrays;
-public class CurrentsTest extends TestUtil {
+public class RapidsTest extends TestUtil {
@BeforeClass public static void setup() { stall_till_cloudsize(1); }
@Test public void bigSlice() {
|
rename currents rapids
DL test uses new syntax and tmp lifetime
|
h2oai_h2o-3
|
train
|
6418486c69bab95386752172d12ef79bb4f54681
|
diff --git a/install/lang/de_utf8/installer.php b/install/lang/de_utf8/installer.php
index <HASH>..<HASH> 100644
--- a/install/lang/de_utf8/installer.php
+++ b/install/lang/de_utf8/installer.php
@@ -155,7 +155,7 @@ $string['memorylimithelp'] = '<p>Die PHP-Einstellung memory_limit für Ihren Ser
<p>Wir empfehlen die Einstellung zu erhöhen. Empfohlen werden 16M oder mehr. Dies können Sie auf verschiedene Arten machen:</p>
<ol>
<li>Wenn Sie PHP neu kompilieren können, nehmen Sie die Einstellung <i>--enable-memory-limit</i>. Dann kann Moodle die Einstellung selber vornehmen.
-<li>Wenn Sie Zugriff auf die Datei php.ini haben, können Sie die Einstellung <b>memory_limit</b> selber auf z.B. 16M anpassen. Wenn Sie selber keinen Zugriff haben, fragen Sie den/die Administrator/in, dies für Sie zu tun.
+<li>Wenn Sie Zugriff auf die Datei php.ini haben, können Sie die Einstellung <b>memory_limit</b> selber auf z.B. 16M anpassen. Wenn Sie selber keinen Zugriff haben, fragen Sie den Server-Admin, dies für Sie zu tun.
<li>Auf einigen PHP-Servern können Sie eine .htaccess-Datei im Moodle-Verzeichnis einrichten. Tragen Sie darin die folgende Zeile ein: <p><blockquote>php_value memory_limit 16M</blockquote></p>
<p>Achtung: auf einigen Servern hindert diese Einstellung <b>alle</b> PHP-Seiten und Sie erhalten Fehlermeldungen. Entfernen Sie dann den Eintrag in der .htaccess-Datei wieder.</p></li>
</ol>';
@@ -199,7 +199,8 @@ $string['skipdbencodingtest'] = 'Prüfung der Datenbank-Verschlüsselung übersp
$string['status'] = 'Status';
$string['thischarset'] = 'UTF-8';
$string['thislanguage'] = 'Deutsch';
-$string['user'] = 'Nutzer/in';
+$string['unicoderecommended'] = 'Es wird empfohlen, alle Daten im Format Unicode UTF-8 zu speichern. Neuinstallationen sollten mit Datenbanken vorgenommen werden, die als Standardzeichensatz UTF-8 benutzen. Wenn Sie ein Upgrade durchführen, sollten Sie die UTF-8-Migration starten (Admin-Seite).';
+$string['user'] = 'Nutzer';
$string['welcomep10'] = '$a->installername ($a->installerversion)';
$string['welcomep20'] = 'Sie haben das Paket <strong>$a->packname $a->packversion</strong> erfolgreich auf Ihrem Computer installiert.';
$string['welcomep30'] = 'Diese Version von <strong>$a->installername</strong> enthält folgende Anwendungen, mit denen Sie <strong>Moodle</strong> ausführen können:';
|
Automatic installer.php lang files by installer_builder (<I>)
|
moodle_moodle
|
train
|
96953fafc079c6cf3e39c6d4f97693d86b7274b0
|
diff --git a/src/set-core.js b/src/set-core.js
index <HASH>..<HASH> 100644
--- a/src/set-core.js
+++ b/src/set-core.js
@@ -445,7 +445,7 @@ assign(Algebra.prototype, {
return this.evaluateOperator(compare.intersection, a, b);
},
/**
- * @function can-set.Algebra.prototype.intersection intersection
+ * @function can-set.Algebra.prototype.count count
* @parent can-set.Algebra.prototype
*
* @signature `algebra.count(set)`
|
fixing intersection vs count docs
|
canjs_can-set
|
train
|
56628c7adffb4b5436257255f55e31b85b58aa8f
|
diff --git a/src/core.js b/src/core.js
index <HASH>..<HASH> 100644
--- a/src/core.js
+++ b/src/core.js
@@ -800,12 +800,14 @@ jQuery.extend({
deferred = {
// then( f1, f2, ...)
- then: function() {
+ then: function then() {
if ( ! cancelled ) {
var args = arguments,
i,
+ length,
+ elem,
type,
_fired;
@@ -814,13 +816,13 @@ jQuery.extend({
fired = 0;
}
- for ( i in args ) {
- i = args[ i ];
- type = jQuery.type( i );
+ for ( i = 0, length = args.length ; i < length ; i++ ) {
+ elem = args[ i ];
+ type = jQuery.type( elem );
if ( type === "array" ) {
- this.then.apply( this , i );
+ then.apply( this , elem );
} else if ( type === "function" ) {
- callbacks.push( i );
+ callbacks.push( elem );
}
}
|
Fixed a loop that only worked in webkit.
|
jquery_jquery
|
train
|
bc879896a15721f2b963e3a56b161273136119dd
|
diff --git a/structr-modules/structr-messaging-engine-module/src/main/java/org/structr/messaging/implementation/kafka/entity/KafkaClient.java b/structr-modules/structr-messaging-engine-module/src/main/java/org/structr/messaging/implementation/kafka/entity/KafkaClient.java
index <HASH>..<HASH> 100644
--- a/structr-modules/structr-messaging-engine-module/src/main/java/org/structr/messaging/implementation/kafka/entity/KafkaClient.java
+++ b/structr-modules/structr-messaging-engine-module/src/main/java/org/structr/messaging/implementation/kafka/entity/KafkaClient.java
@@ -67,9 +67,12 @@ public interface KafkaClient extends MessageClient {
type.addStringArrayProperty("servers", PropertyView.Public, PropertyView.Ui);
type.addStringProperty("groupId", PropertyView.Public, PropertyView.Ui);
+ type.addBooleanProperty("enabled", PropertyView.Public, PropertyView.Ui).setDefaultValue("false");
type.addPropertyGetter("groupId", String.class);
type.addPropertyGetter("subscribers", Iterable.class);
+ type.addPropertyGetter("enabled", Boolean.class);
+
type.addMethod("setServers")
.setReturnType("void")
@@ -123,6 +126,7 @@ public interface KafkaClient extends MessageClient {
String getGroupId();
String[] getServers();
+ Boolean getEnabled();
void setServers(String[] servers) throws FrameworkException;
Iterable<MessageSubscriber> getSubscribers();
@@ -296,7 +300,7 @@ public interface KafkaClient extends MessageClient {
} catch (KafkaException ex) {
- logger.error("Could not setup consumer for KafkaClient " + client.getUuid() + ", triggered by ConsumerWorker Thread. " + ex.getLocalizedMessage());
+ logger.info("Could not setup consumer for KafkaClient " + client.getUuid() + ", triggered by ConsumerWorker Thread. Check for configuration faults. " + ex.getLocalizedMessage());
try {Thread.sleep(1000);} catch (InterruptedException iex) {}
} catch (FrameworkException ex) {
@@ -315,9 +319,7 @@ public interface KafkaClient extends MessageClient {
cId = client.getGroupId();
}
- return (currentGroupId == null && cId != null) ||
- (currentGroupId != null && cId == null) ||
- (!(currentGroupId == null && cId == null) && !currentGroupId.equals(cId));
+ return !currentGroupId.equals(cId);
} catch (FrameworkException ex) {
@@ -330,34 +332,37 @@ public interface KafkaClient extends MessageClient {
List<String> newTopics = new ArrayList<>();
- try {
- client.getSubscribers().forEach((MessageSubscriber sub) -> {
- String topic = sub.getProperty(StructrApp.key(MessageSubscriber.class, "topic"));
- if (topic != null) {
- newTopics.add(topic);
- }
- });
+ if (this.consumer != null) {
+ try {
+ client.getSubscribers().forEach((MessageSubscriber sub) -> {
+ String topic = sub.getProperty(StructrApp.key(MessageSubscriber.class, "topic"));
+ if (topic != null) {
+ newTopics.add(topic);
+ }
+ });
- if (!forceUpdate && currentlySubscribedTopics != null && !currentlySubscribedTopics.equals(newTopics)) {
- if (this.consumer.subscription().size() > 0) {
- this.consumer.unsubscribe();
- }
+ if (!forceUpdate && currentlySubscribedTopics != null && !currentlySubscribedTopics.equals(newTopics)) {
+ if (this.consumer.subscription().size() > 0) {
+ this.consumer.unsubscribe();
+ }
+
+ this.consumer.subscribe(newTopics);
+ this.currentlySubscribedTopics = newTopics;
+ } else if (forceUpdate || currentlySubscribedTopics == null) {
+ if (this.consumer.subscription().size() > 0) {
+ this.consumer.unsubscribe();
+ }
- this.consumer.subscribe(newTopics);
- this.currentlySubscribedTopics = newTopics;
- } else if (forceUpdate || currentlySubscribedTopics == null) {
- if (this.consumer.subscription().size() > 0) {
- this.consumer.unsubscribe();
+ this.consumer.subscribe(newTopics);
+ this.currentlySubscribedTopics = newTopics;
}
- this.consumer.subscribe(newTopics);
- this.currentlySubscribedTopics = newTopics;
+ } catch (KafkaException ex) {
+ logger.error("Could not update consumer subscriptions for KafkaClient " + client.getUuid() + ", triggered by ConsumerWorker Thread. " + ex.getLocalizedMessage());
}
-
- } catch (KafkaException ex) {
- logger.error("Could not update consumer subscriptions for KafkaClient " + client.getUuid() + ", triggered by ConsumerWorker Thread. " + ex.getLocalizedMessage());
}
+
}
@Override
@@ -380,10 +385,11 @@ public interface KafkaClient extends MessageClient {
try (final Tx tx = app.tx()) {
if (this.client == null || Thread.currentThread().isInterrupted()) {
+ running = false;
break;
}
- if (this.client.getServers() != null && this.client.getServers().length > 0) {
+ if (this.client.getServers() != null && this.client.getServers().length > 0 && this.client.getEnabled()) {
if (this.consumer == null) {
this.refreshConsumer();
this.updateSubscriptions(true);
|
Fixes bug in KafkaClient that lead to it's worker thread to crash. Fixed group id updates within worker thread.
|
structr_structr
|
train
|
e4a5af8e90d20d8e956f4946deef1bd2e085c947
|
diff --git a/tests/TestCase/ORM/DomainRulesIntegrationTest.php b/tests/TestCase/ORM/DomainRulesIntegrationTest.php
index <HASH>..<HASH> 100644
--- a/tests/TestCase/ORM/DomainRulesIntegrationTest.php
+++ b/tests/TestCase/ORM/DomainRulesIntegrationTest.php
@@ -297,6 +297,32 @@ class DomainRulesIntegrationTest extends TestCase {
$entity->name = 'jose';
$this->assertSame($entity, $table->save($entity));
+
+ $entity = $table->get(1);
+ $entity->dirty('name', true);
+ $this->assertSame($entity, $table->save($entity));
+ }
+
+/**
+ * Tests isUnique with multiple fields
+ *
+ * @group save
+ * @return void
+ */
+ public function testIsUniqueMultipleFields() {
+ $entity = new Entity([
+ 'author_id' => 1,
+ 'title' => 'First Article'
+ ]);
+
+ $table = TableRegistry::get('Articles');
+ $rules = $table->domainRules();
+ $rules->add($rules->isUnique(['author_id', 'title']));
+
+ $this->assertFalse($table->save($entity));
+
+ $entity->author_id = 2;
+ $this->assertSame($entity, $table->save($entity));
}
}
|
Adding another test for the IsUnique rule
|
cakephp_cakephp
|
train
|
2088bc3e1520f1e28cd47f5bc6e13e1b5f8b211d
|
diff --git a/src/metpy/calc/thermo.py b/src/metpy/calc/thermo.py
index <HASH>..<HASH> 100644
--- a/src/metpy/calc/thermo.py
+++ b/src/metpy/calc/thermo.py
@@ -3566,4 +3566,4 @@ def cross_totals(pressure, temperature, dewpoint):
# Calculate vertical totals.
ct = td850 - t500
- return ct
\ No newline at end of file
+ return ct
diff --git a/tests/calc/test_thermo.py b/tests/calc/test_thermo.py
index <HASH>..<HASH> 100644
--- a/tests/calc/test_thermo.py
+++ b/tests/calc/test_thermo.py
@@ -2018,4 +2018,4 @@ def test_cross_totals():
-58.6, -61.9, -68.4, -71.2, -71.6, -77.2]) * units.degC
ct = cross_totals(pressure, temperature, dewpoint)
- assert_almost_equal(ct, 21.40 * units.delta_degC, 2)
\ No newline at end of file
+ assert_almost_equal(ct, 21.40 * units.delta_degC, 2)
|
Fix no newline at end of file.
|
Unidata_MetPy
|
train
|
c5006d09aafbeb455dad6aa4b776c8071f1dac8a
|
diff --git a/jarn/mkrelease/scm.py b/jarn/mkrelease/scm.py
index <HASH>..<HASH> 100644
--- a/jarn/mkrelease/scm.py
+++ b/jarn/mkrelease/scm.py
@@ -13,13 +13,12 @@ from chdir import DirStack, chdir
from exit import err_exit, warn
from lazy import lazy
-version_re = re.compile(r'version ([0-9.]+)', re.IGNORECASE)
-
class SCM(object):
"""Interface to source code management systems."""
name = ''
+ version_re = re.compile(r'version ([0-9.]+)', re.IGNORECASE)
def __init__(self, process=None, urlparser=None):
self.process = process or Process(env=self.get_env())
@@ -118,7 +117,7 @@ class Subversion(SCM):
rc, lines = self.process.popen(
'svn --version', echo=False)
if rc == 0 and lines:
- match = version_re.search(lines[0])
+ match = self.version_re.search(lines[0])
if match is not None:
return match.group(1)
return ''
@@ -292,7 +291,7 @@ class Mercurial(SCM):
rc, lines = self.process.popen(
'hg --version', echo=False)
if rc == 0 and lines:
- match = version_re.search(lines[0])
+ match = self.version_re.search(lines[0])
if match is not None:
return match.group(1)
return ''
@@ -433,7 +432,7 @@ class Git(SCM):
rc, lines = self.process.popen(
'git --version', echo=False)
if rc == 0 and lines:
- match = version_re.search(lines[0])
+ match = self.version_re.search(lines[0])
if match is not None:
return match.group(1)
return ''
|
Move regex into SCM class.
|
Jarn_jarn.mkrelease
|
train
|
25757049d3a51df58de1b9f8cc6e5db64488e598
|
diff --git a/builtin/logical/totp/backend.go b/builtin/logical/totp/backend.go
index <HASH>..<HASH> 100644
--- a/builtin/logical/totp/backend.go
+++ b/builtin/logical/totp/backend.go
@@ -2,9 +2,11 @@ package totp
import (
"strings"
+ "time"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
+ cache "github.com/patrickmn/go-cache"
)
func Factory(conf *logical.BackendConfig) (logical.Backend, error) {
@@ -25,11 +27,15 @@ func Backend(conf *logical.BackendConfig) *backend {
Secrets: []*framework.Secret{},
}
+ b.usedCodes = cache.New(0, 30*time.Second)
+
return &b
}
type backend struct {
*framework.Backend
+
+ usedCodes *cache.Cache
}
const backendHelp = `
diff --git a/builtin/logical/totp/backend_test.go b/builtin/logical/totp/backend_test.go
index <HASH>..<HASH> 100644
--- a/builtin/logical/totp/backend_test.go
+++ b/builtin/logical/totp/backend_test.go
@@ -258,8 +258,10 @@ func TestBackend_keyCrudDefaultValues(t *testing.T) {
Steps: []logicaltest.TestStep{
testAccStepCreateKey(t, "test", keyData, false),
testAccStepReadKey(t, "test", expected),
- testAccStepValidateCode(t, "test", code, true),
- testAccStepValidateCode(t, "test", invalidCode, false),
+ testAccStepValidateCode(t, "test", code, true, false),
+ // Next step should fail because it should be in the used cache
+ testAccStepValidateCode(t, "test", code, false, true),
+ testAccStepValidateCode(t, "test", invalidCode, false, false),
testAccStepDeleteKey(t, "test"),
testAccStepReadKey(t, "test", nil),
},
@@ -1091,13 +1093,14 @@ func testAccStepReadKey(t *testing.T, name string, expected map[string]interface
}
}
-func testAccStepValidateCode(t *testing.T, name string, code string, valid bool) logicaltest.TestStep {
+func testAccStepValidateCode(t *testing.T, name string, code string, valid, expectError bool) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.UpdateOperation,
Path: "code/" + name,
Data: map[string]interface{}{
"code": code,
},
+ ErrorOk: expectError,
Check: func(resp *logical.Response) error {
if resp == nil {
return fmt.Errorf("bad: %#v", resp)
diff --git a/builtin/logical/totp/path_code.go b/builtin/logical/totp/path_code.go
index <HASH>..<HASH> 100644
--- a/builtin/logical/totp/path_code.go
+++ b/builtin/logical/totp/path_code.go
@@ -4,6 +4,7 @@ import (
"fmt"
"time"
+ "github.com/hashicorp/errwrap"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
otplib "github.com/pquerna/otp"
@@ -84,6 +85,13 @@ func (b *backend) pathValidateCode(
return logical.ErrorResponse(fmt.Sprintf("unknown key: %s", name)), nil
}
+ usedName := fmt.Sprintf("%s_%s", name, code)
+
+ _, ok := b.usedCodes.Get(usedName)
+ if ok {
+ return logical.ErrorResponse("code already used; wait until the next time period"), nil
+ }
+
valid, err := totplib.ValidateCustom(code, key.Key, time.Now(), totplib.ValidateOpts{
Period: key.Period,
Skew: key.Skew,
@@ -94,6 +102,16 @@ func (b *backend) pathValidateCode(
return logical.ErrorResponse("an error occured while validating the code"), err
}
+ // Take the key skew, add two for behind and in front, and multiple that by
+ // the period to cover the full possibility of the validity of the key
+ err = b.usedCodes.Add(usedName, nil, time.Duration(
+ int64(time.Second)*
+ int64(key.Period)*
+ int64((2+key.Skew))))
+ if err != nil {
+ return nil, errwrap.Wrapf("error adding code to used cache: {{err}}", err)
+ }
+
return &logical.Response{
Data: map[string]interface{}{
"valid": valid,
|
Ensure TOTP codes cannot be reused. (#<I>)
|
hashicorp_vault
|
train
|
6f22ba5ee15782ed6a1fa1b6cd4de47d60e8d05b
|
diff --git a/lib/link.js b/lib/link.js
index <HASH>..<HASH> 100644
--- a/lib/link.js
+++ b/lib/link.js
@@ -244,13 +244,15 @@ exports.close = function(socket, data) { // {{{2
}
doIt(socket);
- mate && doIt(mate);
+ doIt(mate);
return;
}
- throw Ose.error('invalidArgs', arguments);
+ throw Ose.error('INVALID_ARGS', 'Invalid socket', typeof socket);
function doIt(s) {
+ if (! s) return;
+
var o = s._state;
s._state = 'CLOSING';
@@ -268,7 +270,7 @@ exports.close = function(socket, data) { // {{{2
}
s._state = 'CLOSED';
- M.log.error(s, 'INVALID_ARGS', 'Socket state should be "OPEN" or "WAIT" for close', o);
+ M.log.error(Ose.error(s, 'INVALID_ARGS', 'Socket state should be "OPEN" or "WAIT" for close', o));
return;
}
};
@@ -310,13 +312,15 @@ exports.error = function(socket, err, timeout) { // {{{2
}
doIt(socket);
- mate && doIt(mate);
+ doIt(mate);
return;
}
- throw Ose.error('invalidArgs', arguments);
+ throw Ose.error('INVALID_ARGS', 'Invalid socket', typeof socket);
function doIt(s) {
+ if (! s) return;
+
var o = s._state;
s._state = 'ERROR';
@@ -333,7 +337,7 @@ exports.error = function(socket, err, timeout) { // {{{2
return;
}
- M.log.error(s, 'INVALID_ARGS', 'Socket state should be "OPEN" or "WAIT" for error', o);
+ M.log.error(Ose.error(s, 'INVALID_ARGS', 'Socket state should be "OPEN" or "WAIT" for error', o));
return;
}
};
|
Change: Error logging of links
|
OpenSmartEnvironment_ose
|
train
|
2be3228294ca53d73cbfe0f4eda4591e4dd8eef6
|
diff --git a/py3status/modules/insync.py b/py3status/modules/insync.py
index <HASH>..<HASH> 100644
--- a/py3status/modules/insync.py
+++ b/py3status/modules/insync.py
@@ -31,9 +31,7 @@ class Py3status:
format = '{status} {queued}'
def check_insync(self, i3s_output_list, i3s_config):
- status = check_output(["insync", "get_status"]).decode()
- if len(status) > 2:
- status = status[:-2]
+ status = check_output(["insync", "get_status"]).decode().strip()
color = i3s_config.get('color_degraded', '')
if status == "OFFLINE":
color = i3s_config.get('color_bad', '')
@@ -42,9 +40,9 @@ class Py3status:
status = "INSYNC"
queued = check_output(["insync", "get_sync_progress"]).decode()
- queued = queued.split("\\n")
- if len(queued) > 2 and "queued" in queued[-2]:
- queued = queued[-2]
+ queued = [q for q in queued.split("\n") if q != '']
+ if len(queued) > 0 and "queued" in queued[-1]:
+ queued = queued[-1]
queued = queued.split(" ")[0]
else:
queued = ""
|
Insync fixes from @Cpher1
|
ultrabug_py3status
|
train
|
f66c721e79fec9e51bd76841969db92a830cc6e7
|
diff --git a/website/data/docs-navigation.js b/website/data/docs-navigation.js
index <HASH>..<HASH> 100644
--- a/website/data/docs-navigation.js
+++ b/website/data/docs-navigation.js
@@ -40,7 +40,8 @@ export default [
'pgp-gpg-keybase',
'recovery-mode',
'resource-quotas',
- 'client-count'
+ 'client-count',
+ 'transform'
],
},
{
|
Link to transform concepts page in sidebar. (#<I>)
* Link to transform concepts page in sidebar
* ,
|
hashicorp_vault
|
train
|
c9003dd775935dff95d42030d59aba58d395d7cf
|
diff --git a/RULES.md b/RULES.md
index <HASH>..<HASH> 100644
--- a/RULES.md
+++ b/RULES.md
@@ -407,3 +407,31 @@ space:
Note: this rule will fire if either side of the header contains multiple
spaces.
+
+## MD022 - Headers should be surrounded by blank lines
+
+Tags: headers, blank_lines
+
+This rule is triggered when headers (any style) are either not preceded or not
+followed by a blank line:
+
+ # Header 1
+ Some text
+
+ Some more text
+ ## Header 2
+
+To fix this, ensure that all headers have a blank line both before and after
+(except where the header is at the beginning or end of the document):
+
+ # Header 1
+
+ Some text
+
+ Some more text
+
+ ## Header 2
+
+Rationale: Aside from asthetic reasons, some parsers, including kramdown, will
+not parse headers that don't have a blank line before, and will parse them as
+regular text.
diff --git a/lib/mdl/rules.rb b/lib/mdl/rules.rb
index <HASH>..<HASH> 100644
--- a/lib/mdl/rules.rb
+++ b/lib/mdl/rules.rb
@@ -254,3 +254,46 @@ rule "MD021", "Multiple spaces inside hashes on closed atx style header" do
end.map { |h| doc.element_linenumber(h) }
end
end
+
+rule "MD022", "Headers should be surrounded by blank lines" do
+ tags :headers, :blank_lines
+ check do |doc|
+ errors = []
+ doc.find_type_elements(:header).each do |h|
+ header_bad = false
+ linenum = doc.element_linenumber(h)
+ # Check previous line
+ if linenum > 1 and not doc.lines[linenum - 2].empty?
+ header_bad = true
+ end
+ # Check next line
+ next_line_idx = doc.header_style(h) == :setext ? linenum + 1 : linenum
+ next_line = doc.lines[next_line_idx]
+ header_bad = true if not next_line.nil? and not next_line.empty?
+ errors << linenum if header_bad
+ end
+ # Kramdown requires that headers start on a block boundary, so in most
+ # cases it won't pick up a header without a blank line before it. We need
+ # to check regular text and pick out headers ourselves too
+ doc.find_type_elements(:p).each do |p|
+ linenum = doc.element_linenumber(p)
+ text = p.children[0].value # Paragraphs will contain a single text child
+ lines = text.split("\n")
+ prev_lines = ["", ""]
+ lines.each do |line|
+ # First look for ATX style headers without blank lines before
+ if line.match(/^\#{1,6}/) and not prev_lines[1].empty?
+ errors << linenum
+ end
+ # Next, look for setext style
+ if line.match(/^(-+|=+)\s*$/) and not prev_lines[0].empty?
+ errors << linenum - 1
+ end
+ linenum += 1
+ prev_lines << line
+ prev_lines.shift
+ end
+ end
+ errors
+ end
+end
diff --git a/test/test_rules.rb b/test/test_rules.rb
index <HASH>..<HASH> 100644
--- a/test/test_rules.rb
+++ b/test/test_rules.rb
@@ -129,6 +129,34 @@ class TestRules < Minitest::Test
# Header 1 {MD021} {MD015} {MD017} #
),
+ 'headers_surrounding_space_atx' => %(
+ # Header 1 {MD016} {MD017}
+
+ # Header 1 {MD022} {MD016} {MD017}
+ Some text
+ # Header 1 {MD022}
+ Some text
+ # Header 1 {MD022}
+
+ # Header 1 {MD016} {MD017}
+ ),
+ 'headers_surrounding_space_setext' => %(
+ Header 1 {MD015} {MD016}
+ ========================
+
+ Header 1 {MD022} {MD015} {MD016}
+ ================================
+ Some text
+ Header 1 {MD022}
+ ================
+ Some text
+ Header 1 {MD022}
+ ================
+ Some text
+
+ Header 1 {MD015} {MD016}
+ ========================
+ ),
'consistent_bullet_styles_asterisk' => %(
* Item
* Item {MD007}
|
MD<I> - Headers should be surrounded by blank lines
Fixes #9
Because kramdown doesn't parse headers that don't start on a block boundary,
there is some code to manually check text blocks for things that look like
headers, and it checks to see if they have blank lines before.
|
markdownlint_markdownlint
|
train
|
c22cb63b6ede241f70eec08ad9f83571144b7fab
|
diff --git a/lib/es8/Tab.js b/lib/es8/Tab.js
index <HASH>..<HASH> 100644
--- a/lib/es8/Tab.js
+++ b/lib/es8/Tab.js
@@ -95,38 +95,28 @@ class Tab {
return this._callToTabDriver((callback) => { this._tabDriver._open(url, options, callback) }, callback, true) // use multiArgs
}
- // TODO re-factor, merge this with isPresent
isVisible(selectors, operator = null, callback = null) {
- if (typeof operator === 'function') {
- callback = operator
- operator = null
- }
- const f = (callback) => {
- this.waitUntilVisible(selectors, 1, operator, (err) => {
- callback(null, !Boolean(err))
- })
- }
- if (callback) {
- f(callback)
- } else {
- return Promise.fromCallback((callback) => { f(callback) } )
- }
+ this._isVisibleOrPresent("_waitUntilVisible", selectors, operator, callback)
+ }
+
+ isPresent(selectors, operator, callback) {
+ this._isVisibleOrPresent("_waitUntilPresent", selectors, operator, callback)
}
- isPresent(selectors, operator = null, callback = null) {
+ _isVisibleOrPresent(method, selectors, operator = null, callback = null) {
if (typeof operator === 'function') {
callback = operator
operator = null
}
const f = (callback) => {
- this.waitUntilPresent(selectors, 1, operator, (err) => {
+ this._callTabDriverWaitMethod(method, selectors, 1, operator, (err) => {
callback(null, !Boolean(err))
})
}
if (callback) {
f(callback)
} else {
- return Promise.fromCallback((callback) => { f(callback) } )
+ return Promise.fromCallback((callback) => { f(callback) })
}
}
@@ -373,7 +363,7 @@ class Tab {
return this._callToTabDriver((callback) => { this._tabDriver._setCookie(cookie, callback) }, callback)
}
- scrollTo(x, y, callback = null) {
+ scrollTo(x, y, callback) {
return this.scroll(x, y, callback)
}
|
isPresent, isVisible re-factored, merged
|
phantombuster_nickjs
|
train
|
0a2751ce9fd99241662fe7936964fc2f4158950b
|
diff --git a/spec/physical_volume_spec.rb b/spec/physical_volume_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/physical_volume_spec.rb
+++ b/spec/physical_volume_spec.rb
@@ -47,8 +47,14 @@ eos
end
describe "#create" do
+ before do
+ @disk = LinuxAdmin::Disk.new :path => '/dev/hda'
+ @disk.stub(:size)
+ end
+
+ let(:disk) {@disk}
+
it "uses pvcreate" do
- disk = LinuxAdmin::Disk.new :path => '/dev/hda'
described_class.instance_variable_set(:@pvs, [])
described_class.should_receive(:run).
with(LinuxAdmin.cmd(:pvcreate),
@@ -57,7 +63,6 @@ eos
end
it "returns new physical volume" do
- disk = LinuxAdmin::Disk.new :path => '/dev/hda'
LinuxAdmin::VolumeGroup.stub(:run => "")
described_class.stub(:run => "")
pv = described_class.create disk
@@ -66,7 +71,6 @@ eos
end
it "adds physical volume to local registry" do
- disk = LinuxAdmin::Disk.new :path => '/dev/hda'
LinuxAdmin::VolumeGroup.stub(:run => "")
described_class.stub(:run => "")
pv = described_class.create disk
|
Stub Disk#size to prevent shelling out on PhysicalVolume.create
Resolves "No such file or directory - /sbin/fdisk -l" failures on a Mac.
|
ManageIQ_linux_admin
|
train
|
cf01f7093fa3724c9461a18c0308de17e21096e4
|
diff --git a/js/bam.js b/js/bam.js
index <HASH>..<HASH> 100644
--- a/js/bam.js
+++ b/js/bam.js
@@ -379,7 +379,7 @@ BamFile.prototype.readBamRecords = function(ba, offset, sink, min, max, chrId, o
while (true) {
var blockSize = readInt(ba, offset);
var blockEnd = offset + blockSize + 4;
- if (blockEnd >= ba.length) {
+ if (blockEnd > ba.length) {
return false;
}
diff --git a/test/bam-test.js b/test/bam-test.js
index <HASH>..<HASH> 100644
--- a/test/bam-test.js
+++ b/test/bam-test.js
@@ -80,3 +80,28 @@ describe('BAM files', function() {
});
}); */
});
+
+describe('Tiny BAM files', function() {
+ var bamURI = 'http://www.biodalliance.org/datasets/tiny.bam';
+ var bam;
+
+ it('can be created by connecting to a URI', function(done) {
+ makeBam(new URLFetchable(bamURI), new URLFetchable(bamURI + '.bai'), null,
+ function(_bam, _err) {
+ bam = _bam;
+ err = _err;
+ expect(err).toBeFalsy();
+ expect(bam).not.toBeNull();
+ done();
+ });
+ });
+
+ it('can retrieve reads from a genomic interval', function(done) {
+ bam.fetch('22', 30000000, 30010000, function(features, err) {
+ expect(err).toBeFalsy();
+ expect(features).toBeTruthy();
+ expect(features.length == 2).toBeTruthy();
+ done();
+ });
+ });
+});
|
Pick up final BAM read in a block.
|
dasmoth_dalliance
|
train
|
e64445e351b4f5074007c0b3a9aa7cb49fcf084a
|
diff --git a/server/webapp/WEB-INF/rails.new/spec/controllers/api_v1/admin/packages_controller_spec.rb b/server/webapp/WEB-INF/rails.new/spec/controllers/api_v1/admin/packages_controller_spec.rb
index <HASH>..<HASH> 100644
--- a/server/webapp/WEB-INF/rails.new/spec/controllers/api_v1/admin/packages_controller_spec.rb
+++ b/server/webapp/WEB-INF/rails.new/spec/controllers/api_v1/admin/packages_controller_spec.rb
@@ -441,12 +441,12 @@ describe ApiV1::Admin::PackagesController do
it 'should allow admin users, with security enabled' do
login_as_admin
- expect(controller).to allow_action(:put, :update)
+ expect(controller).to allow_action(:put, :update, package_id: @package_id)
end
it 'should allow pipeline group admin users, with security enabled' do
login_as_group_admin
- expect(controller).to allow_action(:put, :update)
+ expect(controller).to allow_action(:put, :update, package_id: @package_id)
end
end
|
Fix specs that broke because of missing param
|
gocd_gocd
|
train
|
27c430a89d0b98f170ddf873fd26684907c98e7c
|
diff --git a/higlass/server.py b/higlass/server.py
index <HASH>..<HASH> 100644
--- a/higlass/server.py
+++ b/higlass/server.py
@@ -358,7 +358,7 @@ class Server:
# we're going to assign a uuid to each server process so that if anything
# goes wrong, the variable referencing the process doesn't get lost
- uuid = slugid.nice().decode("utf8")
+ uuid = slugid.nice()
if self.port is None:
self.port = get_open_port()
target = partial(
|
Make compatible with Python <I>
|
higlass_higlass-python
|
train
|
2485a37f4cb1e8eb979897ce8bae5fe29240200c
|
diff --git a/traces/histogram.py b/traces/histogram.py
index <HASH>..<HASH> 100644
--- a/traces/histogram.py
+++ b/traces/histogram.py
@@ -120,11 +120,11 @@ class Histogram(sortedcontainers.SortedDict):
def max(self):
"""Maximum observed value."""
- return self.iloc[-1]
+ return self.keys()[-1]
def min(self):
"""Minimum observed value."""
- return self.iloc[0]
+ return self.keys()[0]
def _quantile_function(self, alpha=0.5, smallest_count=None):
"""Return a function that returns the quantile values for this
@@ -152,8 +152,8 @@ class Histogram(sortedcontainers.SortedDict):
debug_plot.append((cumulative_sum / total, value))
# get maximum and minumum q values
- q_min = inverse.iloc[0]
- q_max = inverse.iloc[-1]
+ q_min = inverse.keys()[0]
+ q_max = inverse.keys()[-1]
# this stuff if helpful for debugging -- keep it in here
# for i, j in debug_plot:
@@ -179,8 +179,8 @@ class Histogram(sortedcontainers.SortedDict):
result = inverse[q]
else:
previous_index = inverse.bisect_left(q) - 1
- x1 = inverse.iloc[previous_index]
- x2 = inverse.iloc[previous_index + 1]
+ x1 = inverse.keys()[previous_index]
+ x2 = inverse.keys()[previous_index + 1]
y1 = inverse[x1]
y2 = inverse[x2]
result = (y2 - y1) * (q - x1) / float(x2 - x1) + y1
@@ -188,14 +188,14 @@ class Histogram(sortedcontainers.SortedDict):
else:
if q in inverse:
previous_index = inverse.bisect_left(q) - 1
- x1 = inverse.iloc[previous_index]
- x2 = inverse.iloc[previous_index + 1]
+ x1 = inverse.keys()[previous_index]
+ x2 = inverse.keys()[previous_index + 1]
y1 = inverse[x1]
y2 = inverse[x2]
result = 0.5 * (y1 + y2)
else:
previous_index = inverse.bisect_left(q) - 1
- x1 = inverse.iloc[previous_index]
+ x1 = inverse.keys()[previous_index]
result = inverse[x1]
return float(result)
diff --git a/traces/timeseries.py b/traces/timeseries.py
index <HASH>..<HASH> 100644
--- a/traces/timeseries.py
+++ b/traces/timeseries.py
@@ -121,10 +121,8 @@ class TimeSeries(object):
# right of last measurement
return self.last_item()[1]
else:
- left_time = self._d.iloc[left_index]
- left_value = self._d[left_time]
- right_time = self._d.iloc[right_index]
- right_value = self._d[right_time]
+ left_time, left_value = self._d.peekitem(left_index)
+ right_time, right_value = self._d.peekitem(right_index)
dt_interval = right_time - left_time
dt_start = time - left_time
if isinstance(dt_interval, datetime.timedelta):
@@ -138,8 +136,7 @@ class TimeSeries(object):
right_index = self._d.bisect_right(time)
left_index = right_index - 1
if right_index > 0:
- left_time = self._d.iloc[left_index]
- left_value = self._d[left_time]
+ left_time, left_value = self._d.peekitem(left_index)
return left_value
elif right_index == 0:
return self.default
@@ -343,7 +340,7 @@ class TimeSeries(object):
# get start index and value
start_index = self._d.bisect_right(start)
if start_index:
- start_value = self._d[self._d.iloc[start_index - 1]]
+ _, start_value = self._d.peekitem(start_index - 1)
else:
start_value = self.default
|
got rid of deprecated calls to iloc
|
datascopeanalytics_traces
|
train
|
e3e80997b1d90132ec456cf72bdf3ff2050dadb1
|
diff --git a/lib/twingly/url/null_url.rb b/lib/twingly/url/null_url.rb
index <HASH>..<HASH> 100644
--- a/lib/twingly/url/null_url.rb
+++ b/lib/twingly/url/null_url.rb
@@ -1,4 +1,4 @@
-require "twingly/url"
+require_relative "../url"
module Twingly
class URL
|
OCD change
We seem to use “require_relative” in /lib and “require” in /spec
|
twingly_twingly-url
|
train
|
747e28cfb62d739c0f11c0301e5272919e705711
|
diff --git a/autopep8.py b/autopep8.py
index <HASH>..<HASH> 100755
--- a/autopep8.py
+++ b/autopep8.py
@@ -236,6 +236,7 @@ class FixPEP8(object):
self.source[result['line'] - 1] = fixed
def fix_e261(self, result):
+ """Fix spacing before comment hash."""
target = self.source[result['line'] - 1]
c = result['column']
@@ -251,13 +252,15 @@ class FixPEP8(object):
self.source[result['line'] - 1] = fixed
def fix_e262(self, result):
+ """Fix spacing after comment hash."""
target = self.source[result['line'] - 1]
- split = target.rsplit('#', 1)
+ offset = result['column']
+
+ code = target[:offset].rstrip(' \t#')
+ comment = target[offset:].lstrip('#').strip()
- assert len(split) == 2
- comment = split[1].lstrip()
- fixed = split[0].rstrip(' \t#') + (' # ' + comment if comment
- else self.newline)
+ fixed = code + (' # ' + comment if comment
+ else self.newline)
self.source[result['line'] - 1] = fixed
diff --git a/test/test_autopep8.py b/test/test_autopep8.py
index <HASH>..<HASH> 100644
--- a/test/test_autopep8.py
+++ b/test/test_autopep8.py
@@ -376,6 +376,12 @@ class Foo():
self._inner_setup(line)
self.assertEqual(self.result, fixed)
+ def test_e262_hash_in_string_and_multiple_hashes(self):
+ line = "print 'a b #string' #comment #comment\n"
+ fixed = "print 'a b #string' # comment #comment\n"
+ self._inner_setup(line)
+ self.assertEqual(self.result, fixed)
+
def test_e262_empty_comment(self):
line = "print 'a b' #\n"
fixed = "print 'a b'\n"
|
Improve fix_e<I>()
It now handles cases like
'abc' #comment #comment again
|
hhatto_autopep8
|
train
|
0ef89c8e47f8a85421f29314b1446930511961c2
|
diff --git a/AUTHORS b/AUTHORS
index <HASH>..<HASH> 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -13,3 +13,4 @@ Gerrit Renker <Gerrit.Renker@ctl.io>
Rene Kaufmann <kaufmann.r@gmail.com>
Ben Krieger <blitzrk@gmail.com>
Hasan Pekdemir <hpekdemir.smart@googlemail.com>
+Sega Okhiria <sega.okhiria@gmail.com>
diff --git a/conn.go b/conn.go
index <HASH>..<HASH> 100644
--- a/conn.go
+++ b/conn.go
@@ -1,4 +1,4 @@
-// Copyright 2016 The Mangos Authors
+// Copyright 2017 The Mangos Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use file except in compliance with the License.
@@ -18,6 +18,7 @@ import (
"encoding/binary"
"io"
"net"
+ "sync"
)
// conn implements the Pipe interface on top of net.Conn. The
@@ -30,6 +31,7 @@ type conn struct {
open bool
props map[string]interface{}
maxrx int64
+ sync.Mutex
}
// connipc is *almost* like a regular conn, but the IPC protocol insists
@@ -103,8 +105,13 @@ func (p *conn) RemoteProtocol() uint16 {
// Close implements the Pipe Close method.
func (p *conn) Close() error {
- p.open = false
- return p.c.Close()
+ p.Lock()
+ defer p.Unlock()
+ if p.IsOpen() {
+ p.open = false
+ return p.c.Close()
+ }
+ return nil
}
// IsOpen implements the PipeIsOpen method.
diff --git a/core.go b/core.go
index <HASH>..<HASH> 100644
--- a/core.go
+++ b/core.go
@@ -1,4 +1,4 @@
-// Copyright 2016 The Mangos Authors
+// Copyright 2017 The Mangos Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use file except in compliance with the License.
@@ -620,6 +620,7 @@ func (d *dialer) dialer() {
rtime = d.sock.reconntime
d.sock.Lock()
if d.closed {
+ d.sock.Unlock()
p.Close()
return
}
@@ -636,8 +637,14 @@ func (d *dialer) dialer() {
// we're redialing here
select {
case <-d.closeq: // dialer closed
+ if p != nil {
+ p.Close()
+ }
return
case <-d.sock.closeq: // exit if parent socket closed
+ if p != nil {
+ p.Close()
+ }
return
case <-time.After(rtime):
if rtmax > 0 {
diff --git a/transport/inproc/inproc.go b/transport/inproc/inproc.go
index <HASH>..<HASH> 100644
--- a/transport/inproc/inproc.go
+++ b/transport/inproc/inproc.go
@@ -1,4 +1,4 @@
-// Copyright 2015 The Mangos Authors
+// Copyright 2017 The Mangos Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use file except in compliance with the License.
@@ -31,6 +31,7 @@ type inproc struct {
proto mangos.Protocol
addr addr
peer *inproc
+ sync.Mutex
}
type addr string
@@ -122,7 +123,11 @@ func (p *inproc) RemoteProtocol() uint16 {
}
func (p *inproc) Close() error {
- close(p.closeq)
+ p.Lock()
+ defer p.Unlock()
+ if p.IsOpen() {
+ close(p.closeq)
+ }
return nil
}
diff --git a/transport/ws/ws.go b/transport/ws/ws.go
index <HASH>..<HASH> 100644
--- a/transport/ws/ws.go
+++ b/transport/ws/ws.go
@@ -1,4 +1,4 @@
-// Copyright 2016 The Mangos Authors
+// Copyright 2017 The Mangos Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use file except in compliance with the License.
@@ -130,6 +130,7 @@ type wsPipe struct {
props map[string]interface{}
iswss bool
dtype int
+ sync.Mutex
}
type wsTran int
@@ -177,9 +178,13 @@ func (w *wsPipe) RemoteProtocol() uint16 {
}
func (w *wsPipe) Close() error {
- w.open = false
- w.ws.Close()
- w.wg.Done()
+ w.Lock()
+ defer w.Unlock()
+ if w.IsOpen() {
+ w.open = false
+ w.ws.Close()
+ w.wg.Done()
+ }
return nil
}
|
Fix deadlock when Dialing and closing multiple times for a socket. Also Fix for leaking connections when calling dialer.Close() and not socket.Close() (#<I>)
|
nanomsg_mangos-v1
|
train
|
59de82ccd58b039678eb466a01da36bf6cd92fb0
|
diff --git a/sacad/recurse.py b/sacad/recurse.py
index <HASH>..<HASH> 100755
--- a/sacad/recurse.py
+++ b/sacad/recurse.py
@@ -152,18 +152,21 @@ def embed_album_art(cover_filepath, path):
if ext in AUDIO_EXTENSIONS:
filepath = os.path.join(path, filename)
mf = mutagen.File(filepath)
- if isinstance(mf, mutagen.ogg.OggFileType):
+ if (isinstance(mf.tags, mutagen._vorbis.VComment) or
+ isinstance(mf, mutagen.ogg.OggFileType)):
picture = mutagen.flac.Picture()
picture.data = cover_data
picture.type = mutagen.id3.PictureType.COVER_FRONT
picture.mime = "image/jpeg"
encoded_data = base64.b64encode(picture.write())
mf["metadata_block_picture"] = encoded_data.decode("ascii")
- elif isinstance(mf, mutagen.mp3.MP3):
+ elif (isinstance(mf.tags, mutagen.id3.ID3) or
+ isinstance(mf, mutagen.id3.ID3FileType)):
mf.tags.add(mutagen.id3.APIC(mime="image/jpeg",
type=mutagen.id3.PictureType.COVER_FRONT,
data=cover_data))
- elif isinstance(mf, mutagen.mp4.MP4):
+ elif (isinstance(mf.tags, mutagen.mp4.MP4Tags) or
+ isinstance(mf, mutagen.mp4.MP4)):
mf["covr"] = [mutagen.mp4.MP4Cover(cover_data,
imageformat=mutagen.mp4.AtomDataType.JPEG)]
mf.save()
|
Recurse: Improve tag type detection when embedding cover
|
desbma_sacad
|
train
|
83d9544c893697ae33f94c79b78602f02153ffd4
|
diff --git a/src/main/java/org/cp/elements/lang/factory/ObjectFactory.java b/src/main/java/org/cp/elements/lang/factory/ObjectFactory.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/cp/elements/lang/factory/ObjectFactory.java
+++ b/src/main/java/org/cp/elements/lang/factory/ObjectFactory.java
@@ -21,13 +21,14 @@ import org.cp.elements.lang.ClassUtils;
import org.cp.elements.lang.reflect.ReflectionUtils;
/**
- * Interface that defines a contract for components capable of creating instances of other {@link Object objects}.
+ * Interface that defines a contract for components capable of creating instances of other {@link Object Objects}.
*
* @author John J. Blum
* @see java.lang.Object
* @see org.cp.elements.context.configure.ConfigurationAware
* @see org.cp.elements.data.conversion.ConversionServiceAware
* @see org.cp.elements.lang.factory.AbstractObjectFactory
+ * @see <a href="https://en.wikipedia.org/wiki/Abstract_factory_pattern">Abstract Factory Software Design Pattern</a>
* @since 1.0.0
*/
@SuppressWarnings("unused")
|
Refer to the Abstract Factory Software Design Pattern in the ObjectFactory interface.
|
codeprimate-software_cp-elements
|
train
|
1c42b28d28239e23c5d7fcddc5dbfc6286de5600
|
diff --git a/src/Routing/Filter/ThrottleFilter.php b/src/Routing/Filter/ThrottleFilter.php
index <HASH>..<HASH> 100644
--- a/src/Routing/Filter/ThrottleFilter.php
+++ b/src/Routing/Filter/ThrottleFilter.php
@@ -86,11 +86,22 @@ class ThrottleFilter extends DispatcherFilter
$response = new Response(['body' => $this->config('message')]);
$response->httpCodes([429 => 'Too Many Requests']);
$response->statusCode(429);
- $this->_setHeaders($response);
return $response;
}
/**
+ * afterDispatch.
+ *
+ * @param Cake\Event\Event $event Event instance
+ * @return Cake\Network\Response Response instance
+ */
+ public function afterDispatch(Event $event)
+ {
+ $this->_setHeaders($event->data['response']);
+ return $event->data['response'];
+ }
+
+ /**
* Sets the identifier class property. Uses Throttle default IP address
* based identifier unless a callable alternative is passed.
*
diff --git a/tests/TestCase/Routing/Filter/ThrottleFilterTest.php b/tests/TestCase/Routing/Filter/ThrottleFilterTest.php
index <HASH>..<HASH> 100644
--- a/tests/TestCase/Routing/Filter/ThrottleFilterTest.php
+++ b/tests/TestCase/Routing/Filter/ThrottleFilterTest.php
@@ -65,6 +65,31 @@ class ThrottleFilterTest extends TestCase
}
/**
+ * Test afterDispatch
+ */
+ public function testAfterDispatch()
+ {
+ Cache::drop('throttle');
+ Cache::config('throttle', [
+ 'className' => 'Cake\Cache\Engine\ApcEngine',
+ 'prefix' => 'throttle_'
+ ]);
+
+ $filter = new ThrottleFilter([
+ 'limit' => 1
+ ]);
+ $response = new Response();
+ $request = new Request([
+ 'environment' => [
+ 'HTTP_CLIENT_IP' => '192.168.1.2'
+ ]
+ ]);
+
+ $event = new Event('Dispatcher.beforeDispatch', $this, compact('request', 'response'));
+ $result = $filter->afterDispatch($event);
+ $this->assertInstanceOf('Cake\Network\Response', $result);
+ }
+ /**
* Using the File Storage cache engine should throw a LogicException.
*
* @expectedException \LogicException
|
Moves header logic to afterDispatch to support exceptions etc
Adds tests
|
UseMuffin_Throttle
|
train
|
eac9a42b0a55e28a5bd8fd524e22e4a7e05c5c64
|
diff --git a/websockets/src/main/java/io/undertow/websockets/StreamSinkFrameChannel.java b/websockets/src/main/java/io/undertow/websockets/StreamSinkFrameChannel.java
index <HASH>..<HASH> 100644
--- a/websockets/src/main/java/io/undertow/websockets/StreamSinkFrameChannel.java
+++ b/websockets/src/main/java/io/undertow/websockets/StreamSinkFrameChannel.java
@@ -107,6 +107,9 @@ public abstract class StreamSinkFrameChannel implements StreamSinkChannel {
@Override
public final long write(ByteBuffer[] srcs, int offset, int length) throws IOException {
checkClosed();
+ if (!isInUse()) {
+ return 0;
+ }
return write0(srcs, offset, length);
}
@@ -115,6 +118,9 @@ public abstract class StreamSinkFrameChannel implements StreamSinkChannel {
@Override
public final long write(ByteBuffer[] srcs) throws IOException {
checkClosed();
+ if (!isInUse()) {
+ return 0;
+ }
return write0(srcs);
}
@@ -123,6 +129,9 @@ public abstract class StreamSinkFrameChannel implements StreamSinkChannel {
@Override
public final int write(ByteBuffer src) throws IOException {
checkClosed();
+ if (!isInUse()) {
+ return 0;
+ }
return write0(src);
}
@@ -132,6 +141,9 @@ public abstract class StreamSinkFrameChannel implements StreamSinkChannel {
@Override
public final long transferFrom(FileChannel src, long position, long count) throws IOException {
checkClosed();
+ if (!isInUse()) {
+ return 0;
+ }
return transferFrom0(src, position, count);
}
@@ -141,6 +153,9 @@ public abstract class StreamSinkFrameChannel implements StreamSinkChannel {
@Override
public long transferFrom(StreamSourceChannel source, long count, ByteBuffer throughBuffer) throws IOException {
checkClosed();
+ if (!isInUse()) {
+ return 0;
+ }
return transferFrom0(source, count, throughBuffer);
}
|
Check if the StreamSinkFrameChannel is currently in use if not return 0 on all write(..) and transfer*(..) methods
|
undertow-io_undertow
|
train
|
22c8363ba2781765c46f8b86feddb4e5c770a138
|
diff --git a/core/lib/refinery/menu_item.rb b/core/lib/refinery/menu_item.rb
index <HASH>..<HASH> 100644
--- a/core/lib/refinery/menu_item.rb
+++ b/core/lib/refinery/menu_item.rb
@@ -13,6 +13,15 @@ module Refinery
}
end
+ def ancestors
+ return @ancestors if @ancestors
+ @ancestors = []
+ p = self
+ @ancestors << p until(p = p.parent).nil?
+
+ @ancestors
+ end
+
def children
@children ||= if has_children?
menu.select{|item| item.type == type && item.parent_id == id}
|
Added .ancestors to menu items.
|
refinery_refinerycms
|
train
|
1cd27cbc3ed004fa82c9cfcd1d5c51fb361df150
|
diff --git a/environment/src/main/java/jetbrains/exodus/io/FileDataReader.java b/environment/src/main/java/jetbrains/exodus/io/FileDataReader.java
index <HASH>..<HASH> 100644
--- a/environment/src/main/java/jetbrains/exodus/io/FileDataReader.java
+++ b/environment/src/main/java/jetbrains/exodus/io/FileDataReader.java
@@ -56,7 +56,7 @@ public class FileDataReader implements DataReader {
this.useNio = useNio;
SharedOpenFilesCache.setSize(openFiles);
if (useNio) {
- SharedMappedFilesCache.setFreePhysicalMemoryThreshold(freePhysicalMemoryThreshold);
+ SharedMappedFilesCache.createInstance(freePhysicalMemoryThreshold);
}
}
diff --git a/environment/src/main/java/jetbrains/exodus/io/SharedMappedByteBuffer.java b/environment/src/main/java/jetbrains/exodus/io/SharedMappedByteBuffer.java
index <HASH>..<HASH> 100644
--- a/environment/src/main/java/jetbrains/exodus/io/SharedMappedByteBuffer.java
+++ b/environment/src/main/java/jetbrains/exodus/io/SharedMappedByteBuffer.java
@@ -48,7 +48,7 @@ final class SharedMappedByteBuffer implements AutoCloseable {
@Override
public void close() {
if (clients.decrementAndGet() < 0) {
- // TODO: implement more platform-independent code
+ // TODO: implement more platform-independent buffer cleaning
if (buffer instanceof DirectBuffer) {
final Cleaner cleaner = ((DirectBuffer) buffer).cleaner();
if (cleaner != null) {
diff --git a/environment/src/main/java/jetbrains/exodus/io/SharedMappedFilesCache.java b/environment/src/main/java/jetbrains/exodus/io/SharedMappedFilesCache.java
index <HASH>..<HASH> 100644
--- a/environment/src/main/java/jetbrains/exodus/io/SharedMappedFilesCache.java
+++ b/environment/src/main/java/jetbrains/exodus/io/SharedMappedFilesCache.java
@@ -20,6 +20,7 @@ import jetbrains.exodus.core.dataStructures.hash.LinkedHashMap;
import jetbrains.exodus.system.OperatingSystem;
import jetbrains.exodus.util.SharedRandomAccessFile;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
@@ -28,14 +29,16 @@ import java.util.concurrent.ConcurrentLinkedQueue;
final class SharedMappedFilesCache {
- private static long freePhysicalMemoryThreshold = 0L;
private static final Object syncObject = new Object();
+ @Nullable
private static volatile SharedMappedFilesCache theCache = null;
+ private final long freePhysicalMemoryThreshold;
private final ConcurrentLinkedQueue<SharedMappedByteBuffer> obsoleteQueue;
private final LinkedHashMap<File, SharedMappedByteBuffer> cache;
- private SharedMappedFilesCache() {
+ private SharedMappedFilesCache(final long freePhysicalMemoryThreshold) {
+ this.freePhysicalMemoryThreshold = freePhysicalMemoryThreshold;
obsoleteQueue = new ConcurrentLinkedQueue<>();
cache = new LinkedHashMap<File, SharedMappedByteBuffer>() {
@Override
@@ -54,22 +57,21 @@ final class SharedMappedFilesCache {
};
}
- static void setFreePhysicalMemoryThreshold(final long freePhysicalMemoryThreshold) {
- SharedMappedFilesCache.freePhysicalMemoryThreshold = freePhysicalMemoryThreshold;
+ static void createInstance(final long freePhysicalMemoryThreshold) {
+ if (theCache == null) {
+ synchronized (syncObject) {
+ if (theCache == null) {
+ theCache = new SharedMappedFilesCache(freePhysicalMemoryThreshold);
+ }
+ }
+ }
}
+ @NotNull
static SharedMappedFilesCache getInstance() {
- if (freePhysicalMemoryThreshold <= 0L) {
- throw new ExodusException("Free physical memory threshold is not set (should be a positive value)");
- }
SharedMappedFilesCache result = theCache;
if (result == null) {
- synchronized (syncObject) {
- result = theCache;
- if (result == null) {
- result = theCache = new SharedMappedFilesCache();
- }
- }
+ throw new ExodusException("SharedMappedFilesCache instance should be created explicitly");
}
return result;
}
@@ -147,7 +149,7 @@ final class SharedMappedFilesCache {
}
}
- private static boolean isOSOverloaded() {
+ private boolean isOSOverloaded() {
return OperatingSystem.getFreePhysicalMemorySize() < freePhysicalMemoryThreshold;
}
}
|
XODUS-CR-<I>: explicit creation of SharedMappedFilesCache
|
JetBrains_xodus
|
train
|
af8c973060b072d945d93c49ff13bb10740721a1
|
diff --git a/flat/style/flat.viewer.js b/flat/style/flat.viewer.js
index <HASH>..<HASH> 100644
--- a/flat/style/flat.viewer.js
+++ b/flat/style/flat.viewer.js
@@ -410,11 +410,10 @@ function rendercorrection(correctionid, addlabels, explicitnew) {
function checkparentincorrection(annotation, correctionid) {
var parentincorrection = false;
annotation.scope.forEach(function(structure_id){
- forannotations(structure_id,function(a){
- if ((a.incorrection) && (a.incorrection == annotation.incorrection)) {
- parentincorrection = structure_id;
- }
- });
+ var structureelement = structure[structure_id];
+ if ((structureelement.incorrection) && (structureelement.incorrection == annotation.incorrection)) {
+ parentincorrection = structure_id;
+ }
});
return parentincorrection;
}
@@ -499,7 +498,7 @@ function renderannotation(annotation, norecurse) {
}
}
var renderedcorrections = []; //buffer of corrections rendered, to prevent duplicates
- if ( (annotation.incorrection) && (annotation.incorrection.length > 0) && (!norecurse)) {
+ if ( (annotation.incorrection) && (!norecurse)) {
//is this item part of a correction? if so, deal with it
//
//is it really this item or is the entire parent part of the
@@ -507,7 +506,7 @@ function renderannotation(annotation, norecurse) {
//here
if (!checkparentincorrection(annotation, annotation.incorrection)) {
renderedcorrections.push(annotation.incorrection);
- if (annotations[correctionid]) {
+ if (annotations[annotation.incorrection]) {
s = s + rendercorrection( annotation.incorrection, true);
}
}
@@ -545,7 +544,7 @@ function showinfo(element) {
var renderedannotations = [];
forannotations(element.id,function(annotation){
if ((annotation.type != 'str') || ((annotation.type == 'str') && (annotation.id == hoverstr))) { //show strings too but only if they are hovered over
- if ((viewannotations[annotation.type+"/" + annotation.set]) ) {
+ if ((viewannotations[annotation.type+"/" + annotation.set]) && (annotation.type != "correction" )) { //non-structural corrections are handled by renderannotation() itself, structural corrections are handled separately after this section
var s = "";
var label = folia_label(annotation.type, annotation.set);
var setname = "";
@@ -553,15 +552,9 @@ function showinfo(element) {
setname = annotation.set;
}
if (setname === "undefined") setname = "";
- if (annotation.type == "correction") {
- s = "<tr><th>" + label + "<br /><span class=\"setname\">" + setname + "</span></th><td>";
- s = s + rendercorrection( annotation.id, true);
- s = s + "</td></tr>";
- } else {
- s = "<tr><th>" + label + "<br /><span class=\"setname\">" + setname + "</span></th><td>";
- s = s + renderannotation(annotation);
- s = s + "</td></tr>";
- }
+ s = "<tr><th>" + label + "<br /><span class=\"setname\">" + setname + "</span></th><td>";
+ s = s + renderannotation(annotation);
+ s = s + "</td></tr>";
renderedannotations.push([annotation.type,s]);
}
}
|
reverting most of the previous commit in favour of a better solution in line with how it was prior to refactor #<I> #<I>
|
proycon_flat
|
train
|
2f3961d65f48aeba55552f96dbefde7cd771d08f
|
diff --git a/src/Form/Fields/Formatters/AutocompleteFormatter.php b/src/Form/Fields/Formatters/AutocompleteFormatter.php
index <HASH>..<HASH> 100644
--- a/src/Form/Fields/Formatters/AutocompleteFormatter.php
+++ b/src/Form/Fields/Formatters/AutocompleteFormatter.php
@@ -3,6 +3,7 @@
namespace Code16\Sharp\Form\Fields\Formatters;
use Code16\Sharp\Form\Fields\SharpFormField;
+use Code16\Sharp\Utils\Transformers\ArrayConverter;
class AutocompleteFormatter extends SharpFieldFormatter
{
@@ -14,6 +15,8 @@ class AutocompleteFormatter extends SharpFieldFormatter
*/
function toFront(SharpFormField $field, $value)
{
+ $value = ArrayConverter::modelToArray($value);
+
return is_null($value) || is_array($value)
? $value
: [$field->itemIdAttribute() => $value];
diff --git a/tests/Unit/Form/Fields/Formatters/AutocompleteFormatterTest.php b/tests/Unit/Form/Fields/Formatters/AutocompleteFormatterTest.php
index <HASH>..<HASH> 100644
--- a/tests/Unit/Form/Fields/Formatters/AutocompleteFormatterTest.php
+++ b/tests/Unit/Form/Fields/Formatters/AutocompleteFormatterTest.php
@@ -25,6 +25,28 @@ class AutocompleteFormatterTest extends SharpTestCase
SharpFormAutocompleteField::make("text", "local")->setItemIdAttribute("num"),
$value
));
+
+ $this->assertEquals(["id" => $value], (new AutocompleteFormatter)->toFront(
+ SharpFormAutocompleteField::make("text", "local"),
+ ["id" => $value]
+ ));
+
+ $this->assertEquals(["id" => $value], (new AutocompleteFormatter)->toFront(
+ SharpFormAutocompleteField::make("text", "local"),
+ (object)["id" => $value]
+ ));
+
+ $this->assertEquals(["id" => $value], (new AutocompleteFormatter)->toFront(
+ SharpFormAutocompleteField::make("text", "local"),
+ new class($value) {
+ function __construct($value) {
+ $this->value = $value;
+ }
+ function toArray() {
+ return ["id" => $this->value];
+ }
+ }
+ ));
}
/** @test */
|
Generalize ArrayConverter to Autocomplete
|
code16_sharp
|
train
|
1cde9091d72eea79ccabbb33d861746b8045f8a3
|
diff --git a/plugins/org.eclipse.xtext/src/org/eclipse/xtext/nodemodel/impl/SerializableNodeModel.java b/plugins/org.eclipse.xtext/src/org/eclipse/xtext/nodemodel/impl/SerializableNodeModel.java
index <HASH>..<HASH> 100644
--- a/plugins/org.eclipse.xtext/src/org/eclipse/xtext/nodemodel/impl/SerializableNodeModel.java
+++ b/plugins/org.eclipse.xtext/src/org/eclipse/xtext/nodemodel/impl/SerializableNodeModel.java
@@ -14,6 +14,7 @@ import java.util.Date;
import org.eclipse.xtext.nodemodel.ICompositeNode;
import org.eclipse.xtext.nodemodel.serialization.DeserializationConversionContext;
import org.eclipse.xtext.nodemodel.serialization.SerializationConversionContext;
+import org.eclipse.xtext.parser.IParseResult;
import org.eclipse.xtext.resource.XtextResource;
/**
@@ -29,12 +30,11 @@ public class SerializableNodeModel {
public RootNode root;
public SerializableNodeModel(XtextResource resource) {
- ICompositeNode rootNode = resource.getParseResult().getRootNode();
-
- if (rootNode != null) {
+ IParseResult parseResult = resource.getParseResult();
+ if (parseResult != null) {
+ ICompositeNode rootNode = parseResult.getRootNode();
root = (RootNode) rootNode;
}
-
formatVersion = 1;
date = new Date();
}
diff --git a/plugins/org.eclipse.xtext/src/org/eclipse/xtext/nodemodel/serialization/SerializationConversionContext.java b/plugins/org.eclipse.xtext/src/org/eclipse/xtext/nodemodel/serialization/SerializationConversionContext.java
index <HASH>..<HASH> 100644
--- a/plugins/org.eclipse.xtext/src/org/eclipse/xtext/nodemodel/serialization/SerializationConversionContext.java
+++ b/plugins/org.eclipse.xtext/src/org/eclipse/xtext/nodemodel/serialization/SerializationConversionContext.java
@@ -13,6 +13,7 @@ import java.util.Map;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtext.nodemodel.impl.RootNode;
+import org.eclipse.xtext.parser.IParseResult;
import org.eclipse.xtext.resource.XtextResource;
/**
@@ -20,7 +21,6 @@ import org.eclipse.xtext.resource.XtextResource;
*
* @since 2.3
*/
-
public class SerializationConversionContext {
final private Map<EObject, Integer> grammarElementToIdMap;
final private ArrayList<String> grammarIdToURIMap;
@@ -57,8 +57,11 @@ public class SerializationConversionContext {
}
protected void fillGrammarElementToIdMap(XtextResource r) {
- RootNode it = (RootNode) r.getParseResult().getRootNode();
- it.fillGrammarElementToIdMap(grammarElementToIdMap, grammarIdToURIMap);
+ IParseResult parseResult = r.getParseResult();
+ if (parseResult != null) {
+ RootNode it = (RootNode) parseResult.getRootNode();
+ it.fillGrammarElementToIdMap(grammarElementToIdMap, grammarIdToURIMap);
+ }
}
public Integer getEObjectId(EObject eObject) {
|
[nodemodel][minor] Fixed NPE warnings in serialization code
|
eclipse_xtext-core
|
train
|
91764b3aa9ea039b832361f3bc739181ee98dac5
|
diff --git a/docs/release_notes.rst b/docs/release_notes.rst
index <HASH>..<HASH> 100644
--- a/docs/release_notes.rst
+++ b/docs/release_notes.rst
@@ -14,6 +14,7 @@ New Features
Bug Fixes
* Update convention support documentation (#386, #393)
+* Detect inner asynchronous functions for D202 (#467)
5.0.2 - January 8th, 2020
---------------------------
diff --git a/src/pydocstyle/checker.py b/src/pydocstyle/checker.py
index <HASH>..<HASH> 100644
--- a/src/pydocstyle/checker.py
+++ b/src/pydocstyle/checker.py
@@ -203,7 +203,7 @@ class ConventionChecker:
# class.
if not (
blanks_after_count == 1 and
- re(r"\s+(?:(?:class|def)\s|@)").match(after)
+ re(r"\s+(?:(?:class|def|async def)\s|@)").match(after)
):
yield violations.D202(blanks_after_count)
diff --git a/src/tests/test_cases/functions.py b/src/tests/test_cases/functions.py
index <HASH>..<HASH> 100644
--- a/src/tests/test_cases/functions.py
+++ b/src/tests/test_cases/functions.py
@@ -29,6 +29,15 @@ def func_with_inner_func_after():
pass
+def func_with_inner_async_func_after():
+ """Test a function with inner async function after docstring."""
+
+ async def inner():
+ pass
+
+ pass
+
+
def fake_decorator(decorated):
"""Fake decorator used to test decorated inner func."""
return decorated
@@ -44,6 +53,16 @@ def func_with_inner_decorated_func_after():
pass
+def func_with_inner_decorated_async_func_after():
+ """Test a function with inner decorated async function after docstring."""
+
+ @fake_decorator
+ async def inner():
+ pass
+
+ pass
+
+
def func_with_inner_class_after():
"""Test a function with inner class after docstring."""
|
Detect inner asynchronous functions for D<I> exemption (#<I>)
* fix: regex to catch inner functions doesn't catch asynchronous ones
* add release note
* release notes: add D<I> precision
|
PyCQA_pydocstyle
|
train
|
718843809b28ebdbf50b470cfc0dc16a703265ab
|
diff --git a/openquake/hazardlib/gsim/bommer_2009.py b/openquake/hazardlib/gsim/bommer_2009.py
index <HASH>..<HASH> 100644
--- a/openquake/hazardlib/gsim/bommer_2009.py
+++ b/openquake/hazardlib/gsim/bommer_2009.py
@@ -55,21 +55,11 @@ def get_site_amplification(C, vs30):
return C["v1"] * np.log(vs30)
-def get_stddevs(C, nsites, stddev_types):
+def get_stddevs(C):
"""
Returns the standard deviations
"""
- stddevs = []
- zeros_array = np.zeros(nsites)
- for stddev in stddev_types:
- if stddev == const.StdDev.TOTAL:
- stddevs.append(np.sqrt(C["tau"] ** 2. + C["phi"] ** 2.) +
- zeros_array)
- elif stddev == const.StdDev.INTER_EVENT:
- stddevs.append(C["tau"] + zeros_array)
- elif stddev == const.StdDev.INTRA_EVENT:
- stddevs.append(C["phi"] + zeros_array)
- return stddevs
+ return [np.sqrt(C["tau"] ** 2. + C["phi"] ** 2.), C["tau"], C["phi"]]
class BommerEtAl2009RSD(GMPE):
@@ -101,20 +91,20 @@ class BommerEtAl2009RSD(GMPE):
#: Required distance measure is closest distance to rupture
REQUIRES_DISTANCES = {'rrup'}
- def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
+ def compute(self, ctx, imts, mean, sig, tau, phi):
"""
See :meth:`superclass method
- <.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
+ <.base.GroundShakingIntensityModel.compute>`
for spec of input and result values.
"""
- C = self.COEFFS[imt]
- mean = (get_magnitude_term(C, rup.mag) +
- get_distance_term(C, dists.rrup, rup.mag) +
- get_ztor_term(C, rup.ztor) +
- get_site_amplification(C, sites.vs30))
-
- stddevs = get_stddevs(C, dists.rrup.shape, stddev_types)
- return mean, stddevs
+ for m, imt in enumerate(imts):
+ C = self.COEFFS[imt]
+ mean[m] = (get_magnitude_term(C, ctx.mag) +
+ get_distance_term(C, ctx.rrup, ctx.mag) +
+ get_ztor_term(C, ctx.ztor) +
+ get_site_amplification(C, ctx.vs30))
+
+ sig[m], tau[m], phi[m] = get_stddevs(C)
COEFFS = CoeffsTable(sa_damping=5, table="""\
imt c0 m1 r1 r2 h1 v1 z1 tau phi
|
Ported more GMPEs
|
gem_oq-engine
|
train
|
1903d8cd59afdb035078b809d226e94f41e3237a
|
diff --git a/python/sdss_access/path/path.py b/python/sdss_access/path/path.py
index <HASH>..<HASH> 100644
--- a/python/sdss_access/path/path.py
+++ b/python/sdss_access/path/path.py
@@ -685,7 +685,8 @@ class BasePath(object):
for c in alternates if re.search(self._comp_regex, c)]))
if suffixes:
assert len(suffixes) == 1, 'should only be one suffix per file template '
- template = template + suffixes[0]
+ if not template.endswith(suffixes[0]):
+ template = template + suffixes[0]
return template
diff --git a/tests/conftest.py b/tests/conftest.py
index <HASH>..<HASH> 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -9,6 +9,7 @@
# @Last Modified time: 2019-08-07 12:30:00
from __future__ import print_function, division, absolute_import
+import glob
import gzip
import os
import pytest
@@ -195,7 +196,6 @@ def monkeysas(tmpdir, monkeypatch, path):
path.replant_tree()
-
@pytest.fixture()
def copydata(tmpdir, request):
''' fixture to copy a file into a temporary directory '''
@@ -210,6 +210,21 @@ def copydata(tmpdir, request):
yield destpath
+@pytest.fixture()
+def copymulti(tmpdir, request):
+ ''' Fixture to copy multiple files into a temporary directory '''
+ srcpath = os.path.join(os.getenv("SAS_BASE_DIR"), request.param)
+ files = glob.glob(srcpath)
+ if not files:
+ pytest.skip('Files do not exist, cannot copy')
+ for item in files:
+ loc = item.split(os.getenv("SAS_BASE_DIR") + '/')[-1]
+ sasdir = tmpdir / 'sas'
+ destpath = sasdir / loc
+ os.makedirs(os.path.dirname(destpath), exist_ok=True)
+ shutil.copy(item, destpath)
+
+
@contextlib.contextmanager
def gzuncompress(filename):
''' Context manager than gunzips a file temporarily. '''
diff --git a/tests/path/test_path.py b/tests/path/test_path.py
index <HASH>..<HASH> 100644
--- a/tests/path/test_path.py
+++ b/tests/path/test_path.py
@@ -152,9 +152,11 @@ class TestPath(object):
def test_uncompress(self, copydata, monkeysas, path):
''' test to find unzipped files with zipped path templates '''
assert path.templates['mangacube'].endswith('.gz')
+ assert path.templates['mangacube'].count('.gz') == 1
with gzuncompress(copydata) as f:
full = path.full('mangacube', drpver='v2_4_3', plate=8485, ifu=1901, wave='LOG')
assert not full.endswith('.gz')
+ assert full.count('.gz') == 0
assert full.endswith('.fits')
@pytest.mark.parametrize('copydata',
@@ -163,16 +165,31 @@ class TestPath(object):
def test_compress(self, copydata, monkeysas, path):
''' test to find zipped files with non-zipped path templates '''
assert not path.templates['mangaimage'].endswith('.gz')
+ assert path.templates['mangaimage'].count('.gz') == 0
with gzcompress(copydata) as f:
full = path.full('mangaimage', drpver='v2_5_3', plate=8485, ifu=1901)
assert not full.endswith('.png')
assert full.endswith('.gz')
+ assert full.count('.gz') == 1
def test_uncompress_nofileexists(self, monkeysas, path):
''' test if no file exists, full returns original template path '''
assert path.templates['mangacube'].endswith('.gz')
- full = path.full('mangacube', drpver='v2_4_3', plate=8485, ifu=1901, wave='LOG')
+ full = path.full('mangacube', drpver='v2_4_3', plate=8888, ifu=12345, wave='LOG')
assert full.endswith('.gz')
+ assert full.count('.gz') == 1
+
+ @pytest.mark.parametrize('copymulti',
+ [('mangawork/manga/spectro/redux/v2_4_3/8485/stack/manga-8485-*-LOGCUBE.fits.gz')],
+ indirect=True, ids=['data'])
+ @pytest.mark.parametrize('plate, ifu', [(8888, '*'), (8888, 12345),
+ (8485, 1901), (8485, '*')],
+ ids=['nodata-wild', 'nodata', 'glob', 'glob-wild'])
+ def test_compression_wildcards(self, copymulti, monkeysas, path, plate, ifu):
+ assert path.templates['mangacube'].endswith('.gz')
+ full = path.full('mangacube', drpver='v2_4_3', plate=plate, ifu=ifu, wave='LOG')
+ assert full.endswith('.gz')
+ assert full.count('.gz') == 1
@pytest.mark.parametrize('mirror', [(True), (False)])
def test_netloc(self, mirror):
|
bug fix with wildcard and compressions
|
sdss_sdss_access
|
train
|
f006162cf326dd552535a58ffc62ff8acc9121bf
|
diff --git a/bin/release.py b/bin/release.py
index <HASH>..<HASH> 100755
--- a/bin/release.py
+++ b/bin/release.py
@@ -348,7 +348,8 @@ def release():
prettyprint("Step 7: Uploading Artifacts", Levels.INFO)
do_task(upload_artifacts, [base_dir, version], async_processes)
- do_task(upload_artifacts, [base_dir + "/as-modules", version], async_processes)
+ do_task(upload_artifacts, [base_dir + "/as-modules/client", version], async_processes)
+ do_task(upload_artifacts, [base_dir + "/as-modules/embedded", version], async_processes)
do_task(upload_artifacts, [base_dir + "/server/integration", version], async_processes)
prettyprint("Step 7: Complete", Levels.INFO)
|
ISPN-<I> release.py script fails due to as-modules split
|
infinispan_infinispan
|
train
|
1c4da54d7d86ba442762da7701a10a4fe0d879cc
|
diff --git a/twitter4j-media-support/src/main/java/twitter4j/media/PlixiUpload.java b/twitter4j-media-support/src/main/java/twitter4j/media/PlixiUpload.java
index <HASH>..<HASH> 100644
--- a/twitter4j-media-support/src/main/java/twitter4j/media/PlixiUpload.java
+++ b/twitter4j-media-support/src/main/java/twitter4j/media/PlixiUpload.java
@@ -71,6 +71,9 @@ class PlixiUpload extends AbstractImageUploadImpl {
headers.put("X-Auth-Service-Provider", TWITTER_VERIFY_CREDENTIALS_XML);
headers.put("X-Verify-Credentials-Authorization", verifyCredentialsAuthorizationHeader);
+ if (null == apiKey) {
+ throw new IllegalStateException("No API Key for Plixi specified. put media.providerAPIKey in twitter4j.properties.");
+ }
HttpParameter[] params = {
new HttpParameter("api_key", apiKey),
this.image
diff --git a/twitter4j-media-support/src/main/java/twitter4j/media/TwitpicUpload.java b/twitter4j-media-support/src/main/java/twitter4j/media/TwitpicUpload.java
index <HASH>..<HASH> 100644
--- a/twitter4j-media-support/src/main/java/twitter4j/media/TwitpicUpload.java
+++ b/twitter4j-media-support/src/main/java/twitter4j/media/TwitpicUpload.java
@@ -73,6 +73,9 @@ class TwitpicUpload extends AbstractImageUploadImpl {
headers.put("X-Auth-Service-Provider", TWITTER_VERIFY_CREDENTIALS_JSON);
headers.put("X-Verify-Credentials-Authorization", verifyCredentialsAuthorizationHeader);
+ if (null == apiKey) {
+ throw new IllegalStateException("No API Key for Twitpic specified. put media.providerAPIKey in twitter4j.properties.");
+ }
HttpParameter[] params = {
new HttpParameter("key", apiKey),
this.image};
diff --git a/twitter4j-media-support/src/test/java/twitter4j/media/MediaUploadTest.java b/twitter4j-media-support/src/test/java/twitter4j/media/MediaUploadTest.java
index <HASH>..<HASH> 100644
--- a/twitter4j-media-support/src/test/java/twitter4j/media/MediaUploadTest.java
+++ b/twitter4j-media-support/src/test/java/twitter4j/media/MediaUploadTest.java
@@ -45,6 +45,7 @@ public class MediaUploadTest extends TestCase {
super(name);
}
+
private String fileName = "t4j.jpeg";
private String message = "Twitter4J image upload test";
@@ -52,11 +53,12 @@ public class MediaUploadTest extends TestCase {
protected void setUp() throws Exception {
super.setUp();
}
- private Configuration getConfiguration(String apiKey){
+
+ private Configuration getConfiguration(String apiKey) {
return new ConfigurationBuilder().setMediaProviderAPIKey(apiKey).build();
}
- public void testProviders() throws Exception{
+ public void testProviders() throws Exception {
Configuration conf;
ImageUploaderFactory factory;
conf = new ConfigurationBuilder().setMediaProvider(MediaProvider.IMG_LY.getName()).build();
@@ -80,7 +82,7 @@ public class MediaUploadTest extends TestCase {
try {
String url = upload.upload(new File("foobar"));
} catch (TwitterException te) {
- if(!(te.getCause() instanceof FileNotFoundException)){
+ if (!(te.getCause() instanceof FileNotFoundException)) {
fail("expecting FileNotFoundException");
}
}
@@ -163,6 +165,7 @@ public class MediaUploadTest extends TestCase {
try {
ImageUploaderFactory factory = new ImageUploaderFactory();
ImageUpload upload = factory.getInstance();
+ System.out.println(upload);
String url = upload.upload(fileName, is);
assertTrue(url.length() > 0);
} finally {
diff --git a/twitter4j-media-support/src/test/resources/twitter4j.properties-template b/twitter4j-media-support/src/test/resources/twitter4j.properties-template
index <HASH>..<HASH> 100644
--- a/twitter4j-media-support/src/test/resources/twitter4j.properties-template
+++ b/twitter4j-media-support/src/test/resources/twitter4j.properties-template
@@ -7,3 +7,4 @@ oauth.consumerSecret=
media.provider=Twitpic
media.providerParameter=foo=bar&fizz=bazz
+media.providerAPIKey=***twitpic api key***
|
TFJ-<I> Twitpic/PlixiUpload now throws IllegalStateException if no API key is specified.
|
Twitter4J_Twitter4J
|
train
|
570e02c96a12ad06888b4ba8d6d8bd3262705dcf
|
diff --git a/actionpack/lib/action_view/helpers/javascript_helper.rb b/actionpack/lib/action_view/helpers/javascript_helper.rb
index <HASH>..<HASH> 100644
--- a/actionpack/lib/action_view/helpers/javascript_helper.rb
+++ b/actionpack/lib/action_view/helpers/javascript_helper.rb
@@ -37,39 +37,6 @@ module ActionView
module JavaScriptHelper
include PrototypeHelper
- # Returns a button with the given +name+ text that'll trigger a JavaScript +function+ using the
- # onclick handler.
- #
- # The first argument +name+ is used as the button's value or display text.
- #
- # The next arguments are optional and may include the javascript function definition and a hash of html_options.
- #
- # The +function+ argument can be omitted in favor of an +update_page+
- # block, which evaluates to a string when the template is rendered
- # (instead of making an Ajax request first).
- #
- # The +html_options+ will accept a hash of html attributes for the link tag. Some examples are :class => "nav_button", :id => "articles_nav_button"
- #
- # Note: if you choose to specify the javascript function in a block, but would like to pass html_options, set the +function+ parameter to nil
- #
- # Examples:
- # button_to_function "Greeting", "alert('Hello world!')"
- # button_to_function "Delete", "if (confirm('Really?')) do_delete()"
- # button_to_function "Details" do |page|
- # page[:details].visual_effect :toggle_slide
- # end
- # button_to_function "Details", :class => "details_button" do |page|
- # page[:details].visual_effect :toggle_slide
- # end
- def button_to_function(name, *args, &block)
- html_options = args.extract_options!.symbolize_keys
-
- function = block_given? ? update_page(&block) : args[0] || ''
- onclick = "#{"#{html_options[:onclick]}; " if html_options[:onclick]}#{function};"
-
- tag(:input, html_options.merge(:type => 'button', :value => name, :onclick => onclick))
- end
-
JS_ESCAPE_MAP = {
'\\' => '\\\\',
'</' => '<\/',
diff --git a/actionpack/lib/action_view/helpers/prototype_helper.rb b/actionpack/lib/action_view/helpers/prototype_helper.rb
index <HASH>..<HASH> 100644
--- a/actionpack/lib/action_view/helpers/prototype_helper.rb
+++ b/actionpack/lib/action_view/helpers/prototype_helper.rb
@@ -102,6 +102,39 @@ module ActionView
:form, :with, :update, :script, :type ]).merge(CALLBACKS)
end
+ # Returns a button with the given +name+ text that'll trigger a JavaScript +function+ using the
+ # onclick handler.
+ #
+ # The first argument +name+ is used as the button's value or display text.
+ #
+ # The next arguments are optional and may include the javascript function definition and a hash of html_options.
+ #
+ # The +function+ argument can be omitted in favor of an +update_page+
+ # block, which evaluates to a string when the template is rendered
+ # (instead of making an Ajax request first).
+ #
+ # The +html_options+ will accept a hash of html attributes for the link tag. Some examples are :class => "nav_button", :id => "articles_nav_button"
+ #
+ # Note: if you choose to specify the javascript function in a block, but would like to pass html_options, set the +function+ parameter to nil
+ #
+ # Examples:
+ # button_to_function "Greeting", "alert('Hello world!')"
+ # button_to_function "Delete", "if (confirm('Really?')) do_delete()"
+ # button_to_function "Details" do |page|
+ # page[:details].visual_effect :toggle_slide
+ # end
+ # button_to_function "Details", :class => "details_button" do |page|
+ # page[:details].visual_effect :toggle_slide
+ # end
+ def button_to_function(name, *args, &block)
+ html_options = args.extract_options!.symbolize_keys
+
+ function = block_given? ? update_page(&block) : args[0] || ''
+ onclick = "#{"#{html_options[:onclick]}; " if html_options[:onclick]}#{function};"
+
+ tag(:input, html_options.merge(:type => 'button', :value => name, :onclick => onclick))
+ end
+
# Returns the JavaScript needed for a remote function.
# Takes the same arguments as link_to_remote.
#
|
Move button_to_function to prototype helper
|
rails_rails
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.