hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
fd6778d7a5e18a02cecc440857360d80a4ddf864
|
diff --git a/app/models/alchemy/message.rb b/app/models/alchemy/message.rb
index <HASH>..<HASH> 100644
--- a/app/models/alchemy/message.rb
+++ b/app/models/alchemy/message.rb
@@ -12,13 +12,27 @@
module Alchemy
class Message
- @@config = Config.get(:mailer)
-
extend ::ActiveModel::Naming
include ::ActiveModel::Validations
include ::ActiveModel::Conversion
include ::ActiveModel::MassAssignmentSecurity
+ def self.attr_accessor(*vars)
+ @attributes ||= {}
+ vars.map { |v| @attributes[v] = nil}
+ super(*vars)
+ end
+
+ def self.attributes
+ @attributes
+ end
+
+ def attributes
+ self.class.attributes
+ end
+
+ @@config = Config.get(:mailer)
+
attr_accessor :contact_form_id, :ip
attr_accessible :contact_form_id
@@ -39,8 +53,10 @@ module Alchemy
end
def initialize(attributes = {})
+ @attributes ||= {}
attributes.keys.each do |a|
send("#{a}=", attributes[a])
+ @attributes[a] = attributes[a]
end
end
@@ -48,7 +64,7 @@ module Alchemy
false
end
- private
+ private
def email_is_filled #:nodoc:
!email.blank?
|
Adding attributes getter method for mail model.
|
AlchemyCMS_alchemy_cms
|
train
|
b052f2229c6cd9a151e47084d2f7b349f5c04382
|
diff --git a/lib/modules/apostrophe-attachments/lib/routes.js b/lib/modules/apostrophe-attachments/lib/routes.js
index <HASH>..<HASH> 100644
--- a/lib/modules/apostrophe-attachments/lib/routes.js
+++ b/lib/modules/apostrophe-attachments/lib/routes.js
@@ -15,7 +15,7 @@ module.exports = function(self, options) {
return self.accept(req, file, function(err, file) {
if (err) {
self.apos.utils.error(err);
- return res.send({ status: 'err' });
+ return res.send({ status: err });
}
if (req.query.html) {
res.setHeader('Content-Type', 'text/html');
|
Fix for error message sent by attachments module
This fixes the static 'err' message when uploading unsupported file via apostrophe-attachments. The change renders a meaningful message in the frontend in case of error.
|
apostrophecms_apostrophe
|
train
|
c2dc4e181f799350cc75bfc069c134c7bf7f83e3
|
diff --git a/dwave_networkx/drawing/qubit_layout.py b/dwave_networkx/drawing/qubit_layout.py
index <HASH>..<HASH> 100644
--- a/dwave_networkx/drawing/qubit_layout.py
+++ b/dwave_networkx/drawing/qubit_layout.py
@@ -43,7 +43,7 @@ __all__ = ['draw_qubit_graph']
def draw_qubit_graph(G, layout, linear_biases={}, quadratic_biases={},
nodelist=None, edgelist=None, cmap=None, edge_cmap=None, vmin=None, vmax=None,
- edge_vmin=None, edge_vmax=None,
+ edge_vmin=None, edge_vmax=None, midpoint=None,
**kwargs):
"""Draws graph G according to layout.
@@ -163,17 +163,20 @@ def draw_qubit_graph(G, layout, linear_biases={}, quadratic_biases={},
# if the biases are provided, then add a legend explaining the color map
if linear_biases:
+ if midpoint is None:
+ midpoint = (vmax+vmin)/2.0
mpl.colorbar.ColorbarBase(cax, cmap=cmap,
- norm=mpl.colors.Normalize(vmin=vmin, vmax=vmax, clip=False),
+ norm = mpl.colors.DivergingNorm(midpoint,vmin=vmin,vmax=vmax),
orientation='vertical')
if quadratic_biases:
+ if midpoint is None:
+ midpoint = (edge_vmax+edge_vmin)/2.0
mpl.colorbar.ColorbarBase(cax, cmap=edge_cmap,
- norm=mpl.colors.Normalize(vmin=edge_vmin, vmax=edge_vmax, clip=False),
+ norm = mpl.colors.DivergingNorm(midpoint,vmin=edge_vmin,vmax=edge_vmax),
orientation='vertical')
-
def draw_embedding(G, layout, emb, embedded_graph=None, interaction_edges=None,
chain_color=None, unused_color=(0.9,0.9,0.9,1.0), cmap=None,
show_labels=False, **kwargs):
|
change the way colormaps created for graph drawing
instead of using only the minimum and maximum values of a given dataset (linear or quadratic biases in this case), if midpoint is provided the colormap will have its middle value at the midpoint
|
dwavesystems_dwave_networkx
|
train
|
efccd69631a09f3637ba7a61a68c51a451de9b2d
|
diff --git a/src/tuwien/auto/calimero/knxnetip/SecureConnection.java b/src/tuwien/auto/calimero/knxnetip/SecureConnection.java
index <HASH>..<HASH> 100644
--- a/src/tuwien/auto/calimero/knxnetip/SecureConnection.java
+++ b/src/tuwien/auto/calimero/knxnetip/SecureConnection.java
@@ -560,7 +560,7 @@ public final class SecureConnection extends KNXnetIPRouting {
if (svc == SecureSessionResponse) {
try {
- final Object[] res = newSessionResponse(h, data, offset);
+ final Object[] res = newSessionResponse(h, data, offset, src, port);
final byte[] serverPublicKey = (byte[]) res[1];
final byte[] auth = newSessionAuth(serverPublicKey);
@@ -926,7 +926,8 @@ public final class SecureConnection extends KNXnetIPRouting {
return new Object[] { sid, seq, sno, tag, knxipPacket };
}
- private Object[] newSessionResponse(final KNXnetIPHeader h, final byte[] data, final int offset)
+ private Object[] newSessionResponse(final KNXnetIPHeader h, final byte[] data, final int offset,
+ final InetAddress src, final int port)
throws KNXFormatException {
if (h.getServiceType() != SecureSessionResponse)
@@ -960,7 +961,7 @@ public final class SecureConnection extends KNXnetIPRouting {
final boolean skipDeviceAuth = Arrays.equals(deviceAuthKey.getEncoded(), new byte[16]);
if (skipDeviceAuth) {
- logger.warn("skipping device authentication for session {}", sessionId);
+ logger.warn("skipping device authentication of {}:{} (no device key)", src.getHostAddress(), port);
}
else {
final ByteBuffer mac = decrypt(buffer, deviceAuthKey, securityInfo(new byte[16], 0, 0xff00));
|
Log remote endpoint (and not session) when device auth is skipped
|
calimero-project_calimero-core
|
train
|
84014f7e4bb5f0bb493111af723a6aaeb01aafad
|
diff --git a/src/utils.js b/src/utils.js
index <HASH>..<HASH> 100644
--- a/src/utils.js
+++ b/src/utils.js
@@ -295,6 +295,8 @@ vglModule.utils.createBlinnPhongVertexShader = function(context) {
*
* Helper function to create Blinn-Phong fragment shader
*
+ * NOTE: Shader assumes directional light
+ *
* @param context
* @returns {vglModule.shader}
*/
@@ -306,27 +308,27 @@ vglModule.utils.createBlinnPhongFragmentShader = function(context) {
'varying vec3 varNormal;',
'varying vec4 varPosition;',
'varying mediump vec3 iVertexColor;',
- 'const vec3 lightPos = vec3(0.0,0.0,1000.0);',
- 'const vec3 ambientColor = vec3(0.3, 0.0, 0.0);',
+ 'const vec3 lightPos = vec3(0.0, 0.0,10000.0);',
+ 'const vec3 ambientColor = vec3(0.01, 0.01, 0.01);',
'const vec3 specColor = vec3(1.0, 1.0, 1.0);',
'void main() {',
'vec3 normal = normalize(varNormal);',
- 'vec3 lightDir = normalize(lightPos - varPosition.xyz);',
- 'vec3 reflectDir = reflect(-lightDir, normal);',
- 'vec3 viewDir = normalize(varPosition.xyz);',
+ 'vec3 lightDir = normalize(lightPos);',
+ 'vec3 reflectDir = -reflect(lightDir, normal);',
+ 'vec3 viewDir = normalize(-varPosition.xyz);',
'float lambertian = max(dot(lightDir,normal), 0.0);',
'float specular = 0.0;',
'if(lambertian > 0.0) {',
'float specAngle = max(dot(reflectDir, viewDir), 0.0);',
- 'specular = pow(specAngle, 4.0);',
+ 'specular = pow(specAngle, 64.0);',
'}',
'gl_FragColor = vec4(ambientColor +',
'lambertian*iVertexColor +',
'specular*specColor, 1.0);',
- // 'gl_FragColor = vec4(viewDir,1.0);',
+// 'gl_FragColor = vec4(viewDir,1.0);',
'}' ].join('\n'),
shader = new vglModule.shader(gl.FRAGMENT_SHADER);
|
Tweaked shader parameters and added special note on lighting
|
OpenGeoscience_vgl
|
train
|
0172f01f691dd25f5bee8d1080204adc092408e1
|
diff --git a/lib/ice_cube/validated_rule.rb b/lib/ice_cube/validated_rule.rb
index <HASH>..<HASH> 100644
--- a/lib/ice_cube/validated_rule.rb
+++ b/lib/ice_cube/validated_rule.rb
@@ -16,6 +16,20 @@ module IceCube
include Validations::Count
include Validations::Until
+ # Validations ordered for efficiency in sequence of:
+ # * descending intervals
+ # * boundary limits
+ # * base values by cardinality (n = 60, 60, 31, 24, 12, 7)
+ # * locks by cardinality (n = 365, 60, 60, 31, 24, 12, 7)
+ # * interval multiplier
+ VALIDATION_ORDER = [
+ :year, :month, :day, :wday, :hour, :min, :sec, :count, :until,
+ :base_sec, :base_min, :base_day, :base_hour, :base_month, :base_wday,
+ :day_of_year, :second_of_minute, :minute_of_hour, :day_of_month,
+ :hour_of_day, :month_of_year, :day_of_week,
+ :interval
+ ]
+
# Compute the next time after (or including) the specified time in respect
# to the given schedule
def next_time(time, schedule, closing_time)
@@ -82,11 +96,9 @@ module IceCube
private
- # NOTE: optimization target, sort the rules by their type, year first
- # so we can make bigger jumps more often
def finds_acceptable_time?
- @validations.all? do |name, validations_for_type|
- validation_accepts_or_updates_time?(validations_for_type)
+ validation_names.all? do |type|
+ validation_accepts_or_updates_time?(@validations[type])
end
end
@@ -140,6 +152,10 @@ module IceCube
closing_time && @time > closing_time
end
+ def validation_names
+ VALIDATION_ORDER & @validations.keys
+ end
+
end
end
|
Run validations in order of significance
Rough benchmark shows an improvement of ~<I>% for the
`finds_acceptable_time?` validation method.
|
seejohnrun_ice_cube
|
train
|
adf70b6d9d18dc3bb4dd1f58e8d99b01a10a7664
|
diff --git a/spython/tests/test_oci.py b/spython/tests/test_oci.py
index <HASH>..<HASH> 100644
--- a/spython/tests/test_oci.py
+++ b/spython/tests/test_oci.py
@@ -70,7 +70,7 @@ class TestOci(unittest.TestCase):
print(result)
print(self.cli.version_info())
- if self.cli.version_info() >= VersionInfo(3, 2, 0):
+ if self.cli.version_info() >= VersionInfo(3, 2, 1, "1"):
self.assertTrue(result['return_code'] == 255)
else:
self.assertTrue('bin' in result)
@@ -96,7 +96,7 @@ class TestOci(unittest.TestCase):
self.assertEqual(state, 0)
# State was still reported as running
- if self.cli.version_info() >= VersionInfo(3, 2, 0):
+ if self.cli.version_info() >= VersionInfo(3, 2, 1, "1"):
print('...check status of paused bundle.')
state = self.cli.oci.state(self.name, sudo=True)
self.assertEqual(state['status'], 'paused')
|
trying <I>-1 with string for pre-release
|
singularityhub_singularity-cli
|
train
|
38358196bce982c809e99d0029271f28a5f60867
|
diff --git a/config/environments/test.rb b/config/environments/test.rb
index <HASH>..<HASH> 100644
--- a/config/environments/test.rb
+++ b/config/environments/test.rb
@@ -38,5 +38,5 @@ Rails.application.configure do
config.active_support.deprecation = :stderr
# Raises error for missing translations
- # config.action_view.raise_on_missing_translations = true
+ config.action_view.raise_on_missing_translations = true
end
|
Raise on missing translations in test
|
publify_publify
|
train
|
a63123e2068bf7a9fcc91bd0dc13a6981e800688
|
diff --git a/src/providers/sh/commands/deploy.js b/src/providers/sh/commands/deploy.js
index <HASH>..<HASH> 100644
--- a/src/providers/sh/commands/deploy.js
+++ b/src/providers/sh/commands/deploy.js
@@ -192,6 +192,10 @@ const stopDeployment = async msg => {
}
const envFields = async list => {
+ if (list.length === 0) {
+ return {}
+ }
+
const questions = []
for (const field of list) {
@@ -209,11 +213,7 @@ const envFields = async list => {
)
const answers = await inquirer.prompt(questions)
- for (const answer in answers) {
- if (!{}.hasOwnProperty.call(answers, answer)) {
- continue
- }
-
+ for (const answer of Object.keys(answers)) {
const content = answers[answer]
if (content === '') {
|
Return an empty object early when nothing to prompt (#<I>)
* Return an empty object early when nothing to prompt
So that the `console.log()` a few lines down does
not get invoked
* Use `Object.keys()` to iterate over the answers
|
zeit_now-cli
|
train
|
1bd8d4a6086b8435fa43f87b620dd6a58430d1e6
|
diff --git a/tests/common/test_meta_model.py b/tests/common/test_meta_model.py
index <HASH>..<HASH> 100644
--- a/tests/common/test_meta_model.py
+++ b/tests/common/test_meta_model.py
@@ -31,7 +31,7 @@ def test_meta_setter_return_value():
@pytest.mark.parametrize("use_gaphas", [False, True])
-def test_state_element(use_gaphas):
+def test_editor_setter_getter(use_gaphas):
meta_m = MetaModel()
meta_data = meta_m.get_meta_data_editor(for_gaphas=use_gaphas)
@@ -53,7 +53,7 @@ def test_state_element(use_gaphas):
@pytest.mark.parametrize("use_gaphas", [False, True])
-def test_state_element_conversion(use_gaphas):
+def test_editor_setter_getter_conversion(use_gaphas):
meta_m = MetaModel()
meta_m.meta["gui"]["editor_opengl" if use_gaphas else "editor_gaphas"]["test"] = (1, 2)
meta_data = meta_m.get_meta_data_editor(for_gaphas=use_gaphas)
|
Tests: rename test functions
|
DLR-RM_RAFCON
|
train
|
168bdc18a50f44d34f1b88dbe1fdcbe2d95d7ade
|
diff --git a/src/main/java/org/primefaces/component/datatable/DataTableRenderer.java b/src/main/java/org/primefaces/component/datatable/DataTableRenderer.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/primefaces/component/datatable/DataTableRenderer.java
+++ b/src/main/java/org/primefaces/component/datatable/DataTableRenderer.java
@@ -127,7 +127,7 @@ public class DataTableRenderer extends DataRenderer {
String widgetClass = (table.getFrozenColumns() == Integer.MIN_VALUE) ? "DataTable" : "FrozenDataTable";
WidgetBuilder wb = getWidgetBuilder(context);
- wb.init(widgetClass, table.resolveWidgetVar(), clientId);
+ wb.initWithDomReady(widgetClass, table.resolveWidgetVar(), clientId);
//Pagination
if(table.isPaginator()) {
diff --git a/src/main/resources/META-INF/resources/primefaces/datatable/datatable.js b/src/main/resources/META-INF/resources/primefaces/datatable/datatable.js
index <HASH>..<HASH> 100644
--- a/src/main/resources/META-INF/resources/primefaces/datatable/datatable.js
+++ b/src/main/resources/META-INF/resources/primefaces/datatable/datatable.js
@@ -42,14 +42,7 @@ PrimeFaces.widget.DataTable = PrimeFaces.widget.DeferredWidget.extend({
this.makeRowsDraggable();
}
- var $this = this;
- if(this.jq.is(':visible')) {
- this._render();
- } else {
- $(function() {
- $this.renderDeferred();
- });
- }
+ this.renderDeferred();
},
_render: function() {
|
revert init impl change
|
primefaces_primefaces
|
train
|
2f52db65ffe663fee643daf8cc9d9db0dafa1d7a
|
diff --git a/arangodb/datadog_checks/arangodb/metrics.py b/arangodb/datadog_checks/arangodb/metrics.py
index <HASH>..<HASH> 100644
--- a/arangodb/datadog_checks/arangodb/metrics.py
+++ b/arangodb/datadog_checks/arangodb/metrics.py
@@ -120,5 +120,13 @@ METRIC_MAP = [
'arangodb_dropped_followers': {'name': 'health.dropped_followers'},
'arangodb_heartbeat_failures': {'name': 'health.heartbeat_failures'},
'arangodb_heartbeat_send_time_msec': {'name': 'health.heartbeat.sent.time'},
+ # connectivity
+ 'arangodb_connection_pool_connections_created': {'name': 'connection_pool.connections.created'},
+ 'arangodb_connection_pool_connections_current': {'name': 'connection_pool.connections.current'},
+ 'arangodb_connection_pool_lease_time_hist': {'name': 'connection_pool.lease_time'},
+ 'arangodb_connection_pool_leases_failed': {'name': 'connection_pool.leases.failed'},
+ 'arangodb_connection_pool_leases_successful': {'name': 'connection_pool.leases.successful'},
+ 'arangodb_http2_connections': {'name': 'http2.connections'},
+ 'arangodb_vst_connections': {'name': 'vst.connections'},
}
]
diff --git a/arangodb/metadata.csv b/arangodb/metadata.csv
index <HASH>..<HASH> 100644
--- a/arangodb/metadata.csv
+++ b/arangodb/metadata.csv
@@ -137,3 +137,12 @@ arangodb.health.heartbeat_failures.count,count,,,,Total number of failed heartbe
arangodb.health.heartbeat.sent.time.bucket,count,,millisecond,,Count of times required to send heartbeats.,0,arangodb,health heartbeat sent time bucket,
arangodb.health.heartbeat.sent.time.count,count,,millisecond,,Count of times required to send heartbeats.,0,arangodb,health heartbeat sent time count,
arangodb.health.heartbeat.sent.time.sum,count,,millisecond,,Count of times required to send heartbeats.,0,arangodb,health heartbeat sent time sum,
+arangodb.connection_pool.connections.created.count,count,,,,Total number of connections created for connection pool.,0,arangodb,connection pool connections created count,
+arangodb.connection_pool.connections.current,gauge,,,,Current number of connections in pool.,0,arangodb,connection pool connections current,
+arangodb.connection_pool.lease_time.bucket,count,,millisecond,,Count of time to lease a connection from the connection pool.,0,arangodb,connection pool lease time bucket,
+arangodb.connection_pool.lease_time.count,count,,millisecond,,Count of time to lease a connection from the connection pool.,0,arangodb,connection pool lease time count,
+arangodb.connection_pool.lease_time.sum,count,,millisecond,,Count of time to lease a connection from the connection pool.,0,arangodb,connection pool lease time sum,
+arangodb.connection_pool.leases.failed.count,count,,,,Total number of failed connection leases.,0,arangodb,connection pool leases failed count,
+arangodb.connection_pool.leases.successful.count,count,,,,Total number of successful connection leases from connection pool.,0,arangodb,connection pool leases successful count,
+arangodb.http2.connections.count,count,,,,Total number of connections accepted for HTTP/2.,0,arangodb,http2 connections count,
+arangodb.vst.connections.count,count,,,,Total number of connections accepted for VST.,0,arangodb,vst connections count,
\ No newline at end of file
diff --git a/arangodb/tests/common.py b/arangodb/tests/common.py
index <HASH>..<HASH> 100644
--- a/arangodb/tests/common.py
+++ b/arangodb/tests/common.py
@@ -128,6 +128,15 @@ METRICS = [
'arangodb.health.heartbeat.sent.time.bucket',
'arangodb.health.heartbeat.sent.time.count',
'arangodb.health.heartbeat.sent.time.sum',
+ 'arangodb.connection_pool.connections.created.count',
+ 'arangodb.connection_pool.connections.current',
+ 'arangodb.connection_pool.lease_time.bucket',
+ 'arangodb.connection_pool.lease_time.count',
+ 'arangodb.connection_pool.lease_time.sum',
+ 'arangodb.connection_pool.leases.failed.count',
+ 'arangodb.connection_pool.leases.successful.count',
+ 'arangodb.http2.connections.count',
+ 'arangodb.vst.connections.count',
]
OPTIONAL_METRICS = [
|
add connectivity metrics (#<I>)
|
DataDog_integrations-core
|
train
|
5869bab296a5acedfb1ce68d56b7edca9da35660
|
diff --git a/katcp/test/test_server.py b/katcp/test/test_server.py
index <HASH>..<HASH> 100644
--- a/katcp/test/test_server.py
+++ b/katcp/test/test_server.py
@@ -1049,10 +1049,15 @@ class TestDeviceServerClientIntegrated(unittest.TestCase, TestUtilMixin):
self.client.test_sensor_list(byte_sensors)
str_sensors = {("a.discrete", "A Discrete.", "", "discrete", "one", "two", "three"),
- ("a.float", b"A Float.", "", "float", "-123.4", "123.4"),
- ("an.int", b"An Integer.", "count", "integer", "-5", "5")}
+ ("a.float", "A Float.", "", "float", "-123.4", "123.4"),
+ ("an.int", "An Integer.", "count", "integer", "-5", "5")}
self.client.test_sensor_list(str_sensors)
+ mix_sensors = {("a.discrete", "A Discrete.", "", "discrete", b"one", b"two", b"three"),
+ ("a.float", b"A Float.", "", b"float", "-123.4", "123.4"),
+ ("an.int", b"An Integer.", "count", "integer", "-5", b"5")}
+ self.client.test_sensor_list(mix_sensors)
+
def test_assert_request_succeeds(self):
"""Test exercises assert_request_succeeds"""
|
added mixed str and byte in string
|
ska-sa_katcp-python
|
train
|
9d2f7e94b94b6ae973916fd5c8b6e7083a886803
|
diff --git a/src/main/resources/set-value.js b/src/main/resources/set-value.js
index <HASH>..<HASH> 100644
--- a/src/main/resources/set-value.js
+++ b/src/main/resources/set-value.js
@@ -1,11 +1,21 @@
(function(webelement, text) {
- function trigger(target, ...eventNames) {
+ function triggerEvent(target, eventName) {
+ if (document.createEventObject) {
+ let event = document.createEventObject();
+ target.fireEvent('on' + eventName, event);
+ }
+ else {
+ let event = document.createEvent('HTMLEvents');
+ event.initEvent(eventName, true, true);
+ target.dispatchEvent(event);
+ }
+ }
+
+ function trigger(target, eventNames) {
for (const i in eventNames) {
try {
- const event = document.createEvent('HTMLEvents');
- event.initEvent(eventNames[i], true, true);
- target.dispatchEvent(event);
+ triggerEvent(target, eventNames[i]);
}
catch (staleElementException) {
console.log('failed to trigger event', eventNames[i])
@@ -16,11 +26,11 @@
if (webelement.getAttribute('readonly') !== null) return 'Cannot change value of readonly element';
if (webelement.getAttribute('disabled') !== null) return 'Cannot change value of disabled element';
- trigger(document.activeElement, 'blur');
+ trigger(document.activeElement, ['blur']);
webelement.focus();
const maxlength = webelement.getAttribute('maxlength') == null ? -1 : parseInt(webelement.getAttribute('maxlength'));
webelement.value = maxlength === -1 ? text : text.length <= maxlength ? text : text.substring(0, maxlength);
- trigger(webelement, 'focus', 'keydown', 'keypress', 'input', 'keyup', 'change');
+ trigger(webelement, ['focus', 'keydown', 'keypress', 'input', 'keyup', 'change']);
return "";
})(arguments[0], arguments[1]);
|
restore IE support in setValue (#<I>)
* restore IE support in setValue
it was occasionally removed in Selenide <I>
|
selenide_selenide
|
train
|
ff80ee0c6e5320f157f533ce7368211e7e67a0c4
|
diff --git a/src/base/Application.php b/src/base/Application.php
index <HASH>..<HASH> 100644
--- a/src/base/Application.php
+++ b/src/base/Application.php
@@ -43,12 +43,8 @@ class Application extends \yii\console\Application implements ViewContextInterfa
public static function main(array $config)
{
try {
- Yii::setLogger(Yii::createObject('hidev\base\Logger'));
- $config = ArrayHelper::merge(
- static::readExtraVendor($config['vendorPath']),
- $config
- );
- $exitCode = (new static($config))->run();
+ $app = static::create($config);
+ $exitCode = $app->run();
} catch (Exception $e) {
/*if ($e instanceof InvalidParamException || $e instanceof ConsoleException) {
Yii::error($e->getMessage());
@@ -62,6 +58,16 @@ class Application extends \yii\console\Application implements ViewContextInterfa
return $exitCode;
}
+ public static function create(array $config)
+ {
+ Yii::setLogger(Yii::createObject('hidev\base\Logger'));
+ $config = ArrayHelper::merge(
+ static::readExtraVendor($config['vendorPath']),
+ $config
+ );
+ return new static($config);
+ }
+
public static function readExtraVendor($dir)
{
return static::readExtraConfig($dir . '/hiqdev/hidev-config.php');
@@ -69,6 +75,7 @@ class Application extends \yii\console\Application implements ViewContextInterfa
public static function readExtraConfig($path)
{
+ $path = Yii::getAlias($path);
return file_exists($path) ? require $path : [];
}
@@ -93,12 +100,16 @@ class Application extends \yii\console\Application implements ViewContextInterfa
public function setExtraConfig($config)
{
$this->_config = $config = ArrayHelper::merge($config, $this->_config);
+ $backup = $this->get('config')->getItems();
+ $this->clear('config');
foreach (['params', 'aliases', 'modules', 'components'] as $key) {
if (isset($config[$key])) {
$this->{'setExtra' . ucfirst($key)}($config[$key]);
}
}
+
+ $this->get('config')->mergeItems($backup);
}
/**
@@ -157,7 +168,7 @@ class Application extends \yii\console\Application implements ViewContextInterfa
if ($this->_first) {
$this->_first = false;
static $skips = ['init' => 1, 'clone' => 1, '--version' => 1];
- if (!$skips[$id]) {
+ if (!isset($skips[$id])) {
$this->runRequest('start');
}
}
@@ -172,11 +183,16 @@ class Application extends \yii\console\Application implements ViewContextInterfa
return $controller;
}
- public function runRequest($string)
+ /**
+ * Run request.
+ * @param string|array $query
+ * @return Response
+ */
+ public function runRequest($query)
{
$request = Yii::createObject([
'class' => 'hidev\base\Request',
- 'params' => array_filter(explode(' ', $string)),
+ 'params' => is_array($query) ? $query : array_filter(explode(' ', $query)),
]);
return $this->handleRequest($request);
|
changed setExtraConfig to force setting config component
|
hiqdev_hidev
|
train
|
b58de900ac076b3678dae7ec3a842baeb55241df
|
diff --git a/rejected.py b/rejected.py
index <HASH>..<HASH> 100755
--- a/rejected.py
+++ b/rejected.py
@@ -91,8 +91,8 @@ class ConsumerThread( threading.Thread ):
return connection
# amqp lib is only raising a generic exception which is odd since it has a AMQPConnectionException class
- except Exception as (errno, strerror):
- logging.error( 'Connection error #%i: %s' % (errno, strerror) )
+ except IOError, e:
+ logging.error( 'Connection error #%i: %s' % (e.errno, e.message) )
raise ConnectionException
def get_information(self):
@@ -275,18 +275,20 @@ class ConsumerThread( threading.Thread ):
self.running = False
"""
- This is hanging for me at times, non-predictably, I wonder if this has to
- with the bug in 1.6.0 that was fixed in 1.7.0
- http://lists.rabbitmq.com/pipermail/rabbitmq-discuss/attachments/20091007/3aaed239/attachment.txt
- - remove channel closing timeout since it can cause a protocol
- violation
- Ideally we'd add this back at some point
+ This hangs because channel.wait in the thread is blocking on socket.recv.
+ channel.close sends the close message, then enters ultimately into
+ socket.recv to get the close_ok response. Depending on the timing,
+ the channel.wait has picked up the close_ok after channel.close (on main
+ thread) entered socket.recv.
+
+ I was looking at a nonblocking method to deal with this properly:
+ http://www.lshift.net/blog/2009/02/18/evserver-part2-rabbit-and-comet
"""
#self.channel.close()
if self.connection:
try:
self.connection.close()
- except IOError:
+ except IOError, e:
# We're already closed
pass
@@ -351,7 +353,7 @@ class MasterControlProgram:
for thread_name, thread in binding['threads'].items():
# Make sure the thread is still alive, otherwise remove it and move on
- if not thread.is_alive():
+ if not thread.isAlive():
logging.error( 'Encountered a dead thread: %s, removing it from the stack' % thread_name )
del binding['threads'][thread_name]
continue
@@ -561,7 +563,7 @@ class MasterControlProgram:
thread.start()
# Check to see if the thread is alive before adding it to our stack
- if thread.is_alive():
+ if thread.isAlive():
# Add to our dictionary of active threads
binding['threads'][thread_name] = thread
@@ -618,9 +620,9 @@ def main():
configuration data such as the user credentials and \
exchange will be derived from the configuration file.")
- parser.add_option("-f", "--foreground",
- action="store_true", dest="foreground", default=False,
- help="Do not fork and stay in foreground")
+ parser.add_option("-d", "--detached",
+ action="store_true", dest="detached", default=False,
+ help="Run in daemon mode")
parser.add_option("-m", "--monitor",
action="store_true", dest="monitor",
@@ -700,7 +702,7 @@ def main():
config['Monitor']['enabled'] = True
# Fork our process to detach if not told to stay in foreground
- if not options.foreground:
+ if options.detached:
try:
pid = os.fork()
if pid > 0:
@@ -751,12 +753,13 @@ def main():
mcp.start()
# Loop until someone wants us to stop
+ do_poll = options.monitor and not options.single_thread
while 1:
# Have the Master Control Process poll
try:
# Check to see if we need to adjust our threads
- if options.single_thread is not True:
+ if do_poll:
mcp.poll()
# Sleep is so much more CPU friendly than pass
|
Trying to merge in mixedpuppys changeset since github seemed to break when I tried. Changeset e<I>cf<I>b0fccfc7e0eb6f<I>a<I>bed<I>f3cc
|
gmr_rejected
|
train
|
74127c0ee2dd8af62e412703e61338811388344d
|
diff --git a/gulpfile.js b/gulpfile.js
index <HASH>..<HASH> 100644
--- a/gulpfile.js
+++ b/gulpfile.js
@@ -8,5 +8,5 @@ gulp.task('default', function() {
gulp.task('test', function() {
gulp.src('test/test.ts', {read: false})
- .pipe(checkFormat({BasedOnStyle: 'Google', ColumnLimit: 120}));
+ .pipe(checkFormat({BasedOnStyle: 'Google', ColumnLimit: 120}, clangFormat, {verbose: true}));
});
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -23,7 +23,7 @@ function format(opt_clangOptions, opt_clangFormat) {
function formatFilter(file, enc, done) {
function onClangFormatFinished() {
- file.contents = new Buffer(formatted);
+ file.contents = Buffer.from(formatted, 'utf-8');
done(null, file);
}
var formatted = '';
|
Replace a `new Buffer` usage with Buffer.from.
|
angular_gulp-clang-format
|
train
|
64139ba32743023701e7d9d2fa79a05325d0d627
|
diff --git a/src/Composer/Command/ShowCommand.php b/src/Composer/Command/ShowCommand.php
index <HASH>..<HASH> 100644
--- a/src/Composer/Command/ShowCommand.php
+++ b/src/Composer/Command/ShowCommand.php
@@ -232,6 +232,21 @@ EOT
$packageListFilter = $this->getRootRequires();
}
+ list($width) = $this->getApplication()->getTerminalDimensions();
+ if (null === $width) {
+ // In case the width is not detected, we're probably running the command
+ // outside of a real terminal, use space without a limit
+ $width = PHP_INT_MAX;
+ }
+ if (Platform::isWindows()) {
+ $width--;
+ }
+
+ if ($input->getOption('path') && null === $composer) {
+ $io->writeError('No composer.json found in the current directory, disabling "path" option');
+ $input->setOption('path', false);
+ }
+
foreach ($repos as $repo) {
if ($repo === $platformRepo) {
$type = 'platform';
@@ -296,20 +311,6 @@ EOT
$nameLength = max($nameLength, strlen($package));
}
}
- list($width) = $this->getApplication()->getTerminalDimensions();
- if (null === $width) {
- // In case the width is not detected, we're probably running the command
- // outside of a real terminal, use space without a limit
- $width = PHP_INT_MAX;
- }
- if (Platform::isWindows()) {
- $width--;
- }
-
- if ($input->getOption('path') && null === $composer) {
- $io->writeError('No composer.json found in the current directory, disabling "path" option');
- $input->setOption('path', false);
- }
$writePath = !$input->getOption('name-only') && $input->getOption('path');
$writeVersion = !$input->getOption('name-only') && !$input->getOption('path') && $showVersion && ($nameLength + $versionLength + 3 <= $width);
|
Move loop-independent code outside of loop
|
composer_composer
|
train
|
8ff0e4beec0b0adc2c8837458b4f3931ce51ba1e
|
diff --git a/src/Stichoza/GoogleTranslate/TranslateClient.php b/src/Stichoza/GoogleTranslate/TranslateClient.php
index <HASH>..<HASH> 100644
--- a/src/Stichoza/GoogleTranslate/TranslateClient.php
+++ b/src/Stichoza/GoogleTranslate/TranslateClient.php
@@ -186,7 +186,7 @@ class TranslateClient {
]);
try {
- $response = $this->httpClient->get($this->urlBase, ['query' => $queryArray]);
+ $response = $this->httpClient->post($this->urlBase, ['query' => $queryArray]);
} catch (GuzzleRequestException $e) {
throw new ErrorException("Error processing request");
}
|
Change GET to POST, ref #<I>
Google translate itself uses POST request for larger amounts of data
|
Stichoza_google-translate-php
|
train
|
89134c04f6d1a7141f4639fccd067f6f2f10f53f
|
diff --git a/src/test/moment/create.js b/src/test/moment/create.js
index <HASH>..<HASH> 100644
--- a/src/test/moment/create.js
+++ b/src/test/moment/create.js
@@ -434,7 +434,6 @@ test('parsing iso', function (assert) {
minute = pad(4 + minOffset),
formats = [
- ['2011-10', '2011-10-01T00:00:00.000' + tz],
['2011-10-08', '2011-10-08T00:00:00.000' + tz],
['2011-10-08T18', '2011-10-08T18:00:00.000' + tz],
['2011-10-08T18:04', '2011-10-08T18:04:00.000' + tz],
|
Remove northern hemisphere dependent tests
|
moment_moment
|
train
|
d23c48b0f09e8685ca8eb6a308bbb3ed8d84877f
|
diff --git a/lib/conceptql/nodes/occurrence.rb b/lib/conceptql/nodes/occurrence.rb
index <HASH>..<HASH> 100644
--- a/lib/conceptql/nodes/occurrence.rb
+++ b/lib/conceptql/nodes/occurrence.rb
@@ -23,10 +23,11 @@ module ConceptQL
# occurrence, this node returns nothing for that person
class Occurrence < Node
def query(db)
- stream.evaluate(db)
- .from_self
- .select_append { |o| o.row_number(:over, partition: :person_id, order: ordered_columns){}.as(:rn) }
- .from_self
+ db[:occurrences]
+ .with(:occurrences,
+ stream.evaluate(db)
+ .from_self
+ .select_append { |o| o.row_number(:over, partition: :person_id, order: ordered_columns){}.as(:rn) })
.where(rn: occurrence.abs)
end
|
Occurrence: use CTE in query
|
outcomesinsights_conceptql
|
train
|
ee8cd750d13fe305f9f6ee44663b684f49b3ed2d
|
diff --git a/src/Repository/Adecco/AdeccoMemberApiRepository.php b/src/Repository/Adecco/AdeccoMemberApiRepository.php
index <HASH>..<HASH> 100644
--- a/src/Repository/Adecco/AdeccoMemberApiRepository.php
+++ b/src/Repository/Adecco/AdeccoMemberApiRepository.php
@@ -16,6 +16,34 @@ class AdeccoMemberApiRepository extends BaseRepository {
$this->credentials = $credentials;
}
+ public function get_member_role_type(
+ VO\Token $token
+ ) {
+ $request = new Request(
+ new GuzzleClient,
+ $this->credentials,
+ VO\HTTP\Url::fromNative($this->base_url.'/onscensus/get/member/role'),
+ new VO\HTTP\Method('GET')
+ );
+
+ $header_parameters = array('Authorization' => $token->__toEncodedString());
+
+ // $request_parameters = array(
+ // 'first_name' => $name->get_first_name()->__toString(),
+ // 'last_name' => $name->get_last_name()->__toString(),
+ // 'email' => $email->__toEncodedString(),
+ // 'team' => $team->__toString()
+ // );
+
+ $request_parameters = array();
+ $response = $request->send($request_parameters, $header_parameters);
+
+
+ $data = $response->get_data();
+
+ return $data;
+ }
+
public function register_member_with_email(
VO\Token $token,
VO\Name $name,
|
adecco get loggedin user role type api feature added
|
OliveMedia_academyhq-api-client
|
train
|
5e31240f5093fa223fb275e5f0e664e328137ca5
|
diff --git a/aioasuswrt/asuswrt.py b/aioasuswrt/asuswrt.py
index <HASH>..<HASH> 100644
--- a/aioasuswrt/asuswrt.py
+++ b/aioasuswrt/asuswrt.py
@@ -67,8 +67,6 @@ async def _parse_lines(lines, regex):
if line:
match = regex.search(line)
if not match:
- _LOGGER.debug("Could not parse row: %s", line)
- _LOGGER.debug(type(line))
continue
results.append(match.groupdict())
return results
@@ -89,6 +87,7 @@ class AsusWrt:
self._cache_time = time_cache
self._trans_cache_timer = None
self._transfer_rates_cache = None
+ self._latest_transfer_data = 0, 0
if use_telnet:
self.connection = TelnetConnection(
@@ -187,8 +186,12 @@ class AsusWrt:
data = await self.connection.async_run_command(_IFCONFIG_CMD)
_LOGGER.info(data)
- match = await _parse_lines(data, _IFCONFIG_REGEX)
- return match
+ result = _IFCONFIG_REGEX.findall(data[0])
+ _LOGGER.info(result)
+ ret = [int(value) for value in result]
+ self._transfer_rates_cache = ret
+ self._trans_cache_timer = now
+ return ret
async def async_get_rx(self, use_cache=True):
"""Get current RX total given in bytes."""
@@ -208,17 +211,11 @@ class AsusWrt:
self._latest_transfer_check = now
self._rx_latest = data[0]
self._tx_latest = data[1]
- return
+ return self._latest_transfer_data
time_diff = now - self._latest_transfer_check
if time_diff.total_seconds() < 30:
- return (
- math.ceil(
- self._rx_latest / time_diff.total_seconds()
- ) if self._rx_latest > 0 else 0,
- math.ceil(
- self._tx_latest / time_diff.total_seconds()
- ) if self._tx_latest > 0 else 0)
+ return self._latest_transfer_data
if data[0] < self._rx_latest:
rx = data[0]
@@ -233,9 +230,10 @@ class AsusWrt:
self._rx_latest = data[0]
self._tx_latest = data[1]
- return (
+ self._latest_transfer_data = (
math.ceil(rx / time_diff.total_seconds()) if rx > 0 else 0,
math.ceil(tx / time_diff.total_seconds()) if tx > 0 else 0)
+ return self._latest_transfer_data
async def async_current_transfer_human_readable(
self, use_cache=True):
|
Reworked the sensor again.
|
kennedyshead_aioasuswrt
|
train
|
0bb3081fea56dea5fee5d052036dfe0053dfa3ed
|
diff --git a/src/http-auth-interceptor.js b/src/http-auth-interceptor.js
index <HASH>..<HASH> 100644
--- a/src/http-auth-interceptor.js
+++ b/src/http-auth-interceptor.js
@@ -12,8 +12,8 @@
.factory('authService', ['$rootScope','httpBuffer', function($rootScope, httpBuffer) {
return {
- loginConfirmed: function() {
- $rootScope.$broadcast('event:auth-loginConfirmed');
+ loginConfirmed: function(data) {
+ $rootScope.$broadcast('event:auth-loginConfirmed', data);
httpBuffer.retryAll();
}
};
|
cherry-pick: Added ability to pass data along with login confirmation
This is quite useful if you want to listen out for login confirmation
and have access to *who* logged in (for presentation purposes)
Conflicts:
src/angular-http-auth.js
|
witoldsz_angular-http-auth
|
train
|
c18e144ab674fe7cb08ac22a653ab43aa7f0b44d
|
diff --git a/lib/active_model/hints.rb b/lib/active_model/hints.rb
index <HASH>..<HASH> 100644
--- a/lib/active_model/hints.rb
+++ b/lib/active_model/hints.rb
@@ -66,6 +66,10 @@ module ActiveModel
result
end
+ def full_messages_for(attribute)
+ hints_for(attribute).map { |message| full_message(attribute, message) }
+ end
+
def initialize_dup(other)
@messages = other.messages.dup
end
diff --git a/lib/validation_hints.rb b/lib/validation_hints.rb
index <HASH>..<HASH> 100644
--- a/lib/validation_hints.rb
+++ b/lib/validation_hints.rb
@@ -7,16 +7,28 @@ module ActiveModel
module Validations
+ module ClassMethods
+
+ def has_validations?
+ ! self.validators.empty?
+ end
+
+ def has_validations_for?(attribute)
+ ! self.validators_on(attribute).empty?
+ end
+
+ end
+
def has_validations?
- ! self.class.validators.empty?
+ self.class.has_validations?
end
- def hints
- @hints ||= Hints.new(self)
+ def has_validations_for?(attribute)
+ self.class.has_validations_for?(attribute)
end
- def hints_for(attribute)
- hints.validation_hints_for(attribute)
+ def hints
+ @hints ||= Hints.new(self)
end
end
diff --git a/lib/validation_hints/version.rb b/lib/validation_hints/version.rb
index <HASH>..<HASH> 100644
--- a/lib/validation_hints/version.rb
+++ b/lib/validation_hints/version.rb
@@ -1,4 +1,4 @@
# -*- encoding : utf-8 -*-
module ValidationHints
- VERSION = "0.1.3"
+ VERSION = "0.2.0"
end
|
added some classmethods like hints_for(attribute) and has_validations_for(attribute)
|
acesuares_validation_hints
|
train
|
89968b5e25f8aa9afd4cec793a93e40781c77682
|
diff --git a/snippets/bind-demo-transition.js b/snippets/bind-demo-transition.js
index <HASH>..<HASH> 100644
--- a/snippets/bind-demo-transition.js
+++ b/snippets/bind-demo-transition.js
@@ -1,4 +1,4 @@
-// Relevant entry from app/transistions.js
+// Relevant entry from app/transitions.js
this.transition(
this.between({childOf: '#liquid-bind-demo > div'}),
this.use('toUp')
|
Fix typo transistions -> transitions
|
ember-animation_liquid-fire
|
train
|
309a88cbc79138e8bf06930fa1bfaf1ce7e492f0
|
diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/login/LoginInfoEndpoint.java b/server/src/main/java/org/cloudfoundry/identity/uaa/login/LoginInfoEndpoint.java
index <HASH>..<HASH> 100755
--- a/server/src/main/java/org/cloudfoundry/identity/uaa/login/LoginInfoEndpoint.java
+++ b/server/src/main/java/org/cloudfoundry/identity/uaa/login/LoginInfoEndpoint.java
@@ -184,7 +184,10 @@ public class LoginInfoEndpoint {
}
static class SavedAccountOptionModel extends SavedAccountOption {
- int red, green, blue;
+ /**
+ * These must be public. It's accessed in templates.
+ */
+ public int red, green, blue;
void assignColors(Color color) {
red = color.getRed();
|
Fixer - Colors must be public
- They're used in templates
[#<I>]
|
cloudfoundry_uaa
|
train
|
05bbfc5eabe426fe6098c9e393a7254813831185
|
diff --git a/actionview/package.json b/actionview/package.json
index <HASH>..<HASH> 100644
--- a/actionview/package.json
+++ b/actionview/package.json
@@ -12,7 +12,7 @@
"scripts": {
"build": "bundle exec blade build",
"test": "echo \"See the README: https://github.com/rails/rails/blob/master/actionview/app/assets/javascripts#how-to-run-tests\" && exit 1",
- "lint": "coffeelint app/assets/javascripts && eslint test/public/test"
+ "lint": "coffeelint app/assets/javascripts && eslint test/ujs/public/test"
},
"repository": {
"type": "git",
diff --git a/actionview/test/ujs/public/test/data-confirm.js b/actionview/test/ujs/public/test/data-confirm.js
index <HASH>..<HASH> 100644
--- a/actionview/test/ujs/public/test/data-confirm.js
+++ b/actionview/test/ujs/public/test/data-confirm.js
@@ -300,7 +300,7 @@ asyncTest('clicking on the children of a disabled button should not trigger a co
window.confirm = function(msg) { message = msg; return false }
$('button[data-confirm][disabled]')
- .html("<strong>Click me</strong>")
+ .html('<strong>Click me</strong>')
.bindNative('confirm', function() {
App.assertCallbackNotInvoked('confirm')
})
diff --git a/actionview/test/ujs/public/test/data-remote.js b/actionview/test/ujs/public/test/data-remote.js
index <HASH>..<HASH> 100644
--- a/actionview/test/ujs/public/test/data-remote.js
+++ b/actionview/test/ujs/public/test/data-remote.js
@@ -411,7 +411,7 @@ asyncTest('form buttons should only be serialized when clicked', 4, function() {
asyncTest('changing a select option without "data-url" attribute still fires ajax request to current location', 1, function() {
var currentLocation, ajaxLocation
- buildSelect({'data-url': ''});
+ buildSelect({'data-url': ''})
$('select[data-remote]')
.bindNative('ajax:beforeSend', function(e, xhr, settings) {
|
Fix test directory to correct path
Together, fix to the following lint violation.
```
rails/actionview/test/ujs/public/test/data-confirm.js
<I>:<I> error Strings must use singlequote quotes
rails/actionview/test/ujs/public/test/data-remote.js
<I>:<I> error Extra semicolon semi
✖ 2 problems (2 errors, 0 warnings)
```
|
rails_rails
|
train
|
4b21b06f46bbd846a5ce2ddc2dd717dd721f6cc1
|
diff --git a/src/main/java/org/jboss/pressgang/ccms/contentspec/utils/ContentSpecUtilities.java b/src/main/java/org/jboss/pressgang/ccms/contentspec/utils/ContentSpecUtilities.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/jboss/pressgang/ccms/contentspec/utils/ContentSpecUtilities.java
+++ b/src/main/java/org/jboss/pressgang/ccms/contentspec/utils/ContentSpecUtilities.java
@@ -28,7 +28,7 @@ import org.jboss.pressgang.ccms.wrapper.collection.CollectionWrapper;
public class ContentSpecUtilities {
- public static Pattern CS_CHECKSUM_PATTERN = Pattern.compile("CHECKSUM[ ]*=[ ]*(?<Checksum>[A-Za-z0-9]+)");
+ public static final Pattern CS_CHECKSUM_PATTERN = Pattern.compile("CHECKSUM[ ]*=[ ]*(?<Checksum>[A-Za-z0-9]+)");
private static final List<String> translatableMetaData = CollectionUtilities.toArrayList(
new String[]{CSConstants.TITLE_TITLE, CSConstants.PRODUCT_TITLE, CSConstants.SUBTITLE_TITLE, CSConstants.ABSTRACT_TITLE,
CSConstants.COPYRIGHT_HOLDER_TITLE, CSConstants.VERSION_TITLE, CSConstants.EDITION_TITLE});
|
Minor fix to set constant as final.
|
pressgang-ccms_PressGangCCMSContentSpec
|
train
|
4754f77af02935ee9aaf53d85f2fdb741222e347
|
diff --git a/test/db/mssql/simple_test.rb b/test/db/mssql/simple_test.rb
index <HASH>..<HASH> 100644
--- a/test/db/mssql/simple_test.rb
+++ b/test/db/mssql/simple_test.rb
@@ -155,6 +155,53 @@ class MSSQLSimpleTest < Test::Unit::TestCase
assert ! columns.find { |col| col.name == 'another_column' }
end
+ # from include DirtyAttributeTests :
+
+# ActiveRecord::AttributeMethods.class_eval do
+#
+# # Filters the primary keys and readonly attributes from the attribute names.
+# def attributes_for_update(attribute_names)
+# result = attribute_names.reject do |name|
+# readonly_attribute?(name)
+# end
+# puts "attributes_for_update(attribute_names) #{attribute_names.inspect}\n result = #{result.inspect}"
+# result
+# end
+#
+# end
+
+ def test_partial_update_with_updated_at
+ # NOTE: partial updates won't work on MS-SQL :
+ # with_partial_updates User, false do
+ # assert_queries(1) { user.save! }
+ # end
+ # ActiveRecord::JDBCError: Cannot update identity column 'id'.: UPDATE [entries] SET [title] = N'foo', [id] = 1, [updated_on] = '2015-09-11 11:11:55.182', [content] = NULL, [status] = N'unknown', [rating] = NULL, [user_id] = NULL WHERE [entries].[id] = 1
+ # since ActiveRecord::AttributeMethods#attributes_for_update only checks for
+ # readonly_attribute? and not pk_attribute?(name) as well ...
+ # other adapters such as MySQL simply accept/ignore similar UPDATE as valid
+ #
+ return super unless ar_version('4.0')
+ begin
+ ro_attrs = User.readonly_attributes.dup
+ User.readonly_attributes << 'id'
+ super
+ ensure
+ User.readonly_attributes.replace(ro_attrs)
+ end
+ end
+
+ def test_partial_update_with_updated_on
+ return super unless ar_version('4.0')
+ begin
+ ro_attrs = User.readonly_attributes.dup
+ User.readonly_attributes << 'id'
+ super
+ ensure
+ User.readonly_attributes.replace(ro_attrs)
+ end
+ end
+
+
def test_find_by_sql_WITH_statement
user = User.create! :login => 'ferko'
Entry.create! :title => 'aaa', :user_id => user.id
|
handle id updatting with partial updates disabled test on AR >= <I>
|
jruby_activerecord-jdbc-adapter
|
train
|
00db782344bbfc0827444d49bdf65f0ce42de4d9
|
diff --git a/cache.py b/cache.py
index <HASH>..<HASH> 100644
--- a/cache.py
+++ b/cache.py
@@ -105,6 +105,10 @@ class CachedFunction(object):
def __repr__(self):
return '<%s of %s via %s>' % (self.__class__.__name__, self.func, self.cache)
+ def _expand_opts(self, opts):
+ for k, v in self.opts.iteritems():
+ opts.setdefault(k, v)
+
def get_key(self, args, kwargs):
# We need to normalize the signature of the function. This is only
# really possible if we wrap the "real" function.
@@ -139,19 +143,28 @@ class CachedFunction(object):
def __call__(self, *args, **kwargs):
return self.cache.get(self.get_key(args, kwargs), self.func, args, kwargs, **self.opts)
- def delete(self, args=(), kwargs={}):
+ def get(self, args=(), kwargs={}, **opts):
+ self._expand_opts(opts)
+ return self.cache.get(self.get_key(args, kwargs), self.func, args, kwargs, **opts)
+
+ def delete(self, args=(), kwargs={}, **opts):
+ self._expand_opts(opts)
self.cache.delete(self.get_key(args, kwargs))
- def expire(self, maxage, args=(), kwargs={}):
+ def expire(self, maxage, args=(), kwargs={}, **opts):
+ self._expand_opts(opts)
self.cache.expire(self.get_key(args, kwargs), maxage)
- def expire_at(self, maxage, args=(), kwargs={}):
+ def expire_at(self, maxage, args=(), kwargs={}, **opts):
+ self._expand_opts(opts)
self.cache.expire_at(self.get_key(args, kwargs), maxage)
- def ttl(self, args=(), kwargs={}):
+ def ttl(self, args=(), kwargs={}, **opts):
+ self._expand_opts(opts)
return self.cache.ttl(self.get_key(args, kwargs))
- def exists(self, args=(), kwargs={}):
+ def exists(self, args=(), kwargs={}, **opts):
+ self._expand_opts(opts)
return self.cache.exists(self.get_key(args, kwargs))
|
Methods of decorated function support opts.
|
mikeboers_PyMemoize
|
train
|
1f44797b13fe38224cdbb0e1d7bd71d4d173487c
|
diff --git a/bin/oref0-determine-basal.js b/bin/oref0-determine-basal.js
index <HASH>..<HASH> 100755
--- a/bin/oref0-determine-basal.js
+++ b/bin/oref0-determine-basal.js
@@ -69,38 +69,40 @@ function init() {
};
determinebasal.getLastGlucose = function getLastGlucose(data) {
-
- var now = data[0];
- var last = data[1];
+
+ function prepGlucose (obj) {
+ //Support the NS sgv field to avoid having to convert in a custom way
+ obj.glucose = obj.glucose || obj.sgv;
+ return obj;
+ }
+
+ var now = prepGlucose(data[0]);
+ var last = prepGlucose(data[1]);
+ var old = prepGlucose(data[2]);
+ var oldold = prepGlucose(data[3]);
var minutes;
var change;
var avg;
- //Support the NS sgv field to avoid having to convert in a custom way
- now.glucose = now.glucose || now.sgv;
- last.glucose = last.glucose || last.sgv;
-
//TODO: calculate average using system_time instead of assuming 1 data point every 5m
- if (typeof data[3] !== 'undefined' && data[3].glucose > 30) {
+ if (typeof oldold !== 'undefined' && oldold.glucose > 30) {
minutes = 3*5;
- change = now.glucose - data[3].glucose;
- } else if (typeof data[2] !== 'undefined' && data[2].glucose > 30) {
+ change = now.glucose - oldold.glucose;
+ } else if (old !== 'undefined' && old.glucose > 30) {
minutes = 2*5;
- change = now.glucose - data[2].glucose;
- } else if (typeof data[1] !== 'undefined' && data[1].glucose > 30) {
- minutes = 1*5;
- change = now.glucose - data[1].glucose;
+ change = now.glucose - old.glucose;
+ } else if (typeof last !== 'undefined' && last.glucose > 30) {
+ minutes = 5;
+ change = now.glucose - last.glucose;
} else { change = 0; }
// multiply by 5 to get the same units as delta, i.e. mg/dL/5m
avg = change/minutes * 5;
- var o = {
+
+ return {
delta: now.glucose - last.glucose
, glucose: now.glucose
, avgdelta: avg
};
-
- return o;
-
};
|
also handle the 3rd and 4th points, needs more fixing
|
openaps_oref0
|
train
|
0492a500f280c43a0eb4a52d50c4d9218b3b802f
|
diff --git a/Model/ResourceModel/Menu/Collection.php b/Model/ResourceModel/Menu/Collection.php
index <HASH>..<HASH> 100644
--- a/Model/ResourceModel/Menu/Collection.php
+++ b/Model/ResourceModel/Menu/Collection.php
@@ -12,4 +12,13 @@ class Collection extends AbstractCollection
\Snowdog\Menu\Model\ResourceModel\Menu::class
);
}
+
+ public function addStoresData()
+ {
+ foreach ($this->getItems() as $menu) {
+ $menu->addData(['stores' => $menu->getStores()]);
+ }
+
+ return $this;
+ }
}
diff --git a/Ui/DataProvider/Menu/Form/MenuDataProvider.php b/Ui/DataProvider/Menu/Form/MenuDataProvider.php
index <HASH>..<HASH> 100644
--- a/Ui/DataProvider/Menu/Form/MenuDataProvider.php
+++ b/Ui/DataProvider/Menu/Form/MenuDataProvider.php
@@ -11,7 +11,7 @@ use Snowdog\Menu\Model\Menu;
class MenuDataProvider extends AbstractDataProvider
{
/** @var array */
- private $loadedData = [];
+ private $loadedData;
public function __construct(
$name,
@@ -21,7 +21,7 @@ class MenuDataProvider extends AbstractDataProvider
array $meta = [],
array $data = []
) {
- $this->collection = $collectionFactory->create();
+ $this->collection = $collectionFactory->create()->addStoresData();
parent::__construct(
$name,
$primaryFieldName,
@@ -33,14 +33,13 @@ class MenuDataProvider extends AbstractDataProvider
public function getData(): array
{
- if (!empty($this->loadedData)) {
+ if ($this->loadedData !== null) {
return $this->loadedData;
}
$items = $this->collection->getItems();
/** @var Menu $menu */
foreach ($items as $menu) {
- $menu->addData(['stores' => $menu->getStores()]);
$this->loadedData[$menu->getId()] = $menu->getData();
}
|
DEV-<I>: added addStoresData in menu collection class
|
SnowdogApps_magento2-menu
|
train
|
52df0ec8a8ce4b0f580b5224ea099318a93693c6
|
diff --git a/modules/custom/social_demo/src/DemoGroup.php b/modules/custom/social_demo/src/DemoGroup.php
index <HASH>..<HASH> 100644
--- a/modules/custom/social_demo/src/DemoGroup.php
+++ b/modules/custom/social_demo/src/DemoGroup.php
@@ -86,8 +86,6 @@ abstract class DemoGroup extends DemoContent {
continue;
}
- $account = current($accounts);
-
// Create array with data of a group.
$item['uid'] = $account->id();
$item['created'] = $item['changed'] = $this->createDate($item['created']);
|
Issue #<I> by alex.ksis: Fix undefined method
|
goalgorilla_open_social
|
train
|
eccee5a077c29691ade0cdb3d20d8112ddd5ecd6
|
diff --git a/lib/ronin/extensions/resolv.rb b/lib/ronin/extensions/resolv.rb
index <HASH>..<HASH> 100644
--- a/lib/ronin/extensions/resolv.rb
+++ b/lib/ronin/extensions/resolv.rb
@@ -21,6 +21,38 @@ require 'resolv'
class Resolv
+ # List of valid Top-Level-Domains
+ TLDS = %w[
+ aero arpa asia biz cat com coop edu gov info int jobs mil mobi museum net
+ org pro tel travel xxx
+
+ ac ad ae af ag ai al am an ao aq ar as at au aw ax az
+ ba bb bd be bf bg bh bi bj bm bn bo br bs bt bv bw by bz
+ ca cc cd cf cg ch ci ck cl cm cn co cr cs cu cv cx cy cz
+ dd de dj dk dm do dz
+ ec ee eg eh er es et eu
+ fi fj fk fm fo fr
+ ga gb gd ge gf gg gh gi gl gm gn gp gq gr gs gt gu gw gy
+ hk hm hn hr ht hu
+ id ie il im in io iq ir is it
+ je jm jo jp
+ ke kg kh ki km kn kp kr kw ky kz
+ la lb lc li lk lr ls lt lu lv ly
+ ma mc md me mg mh mk ml mm mn mo mp mq mr ms mt mu mv mw mx my mz
+ na nc ne nf ng ni nl no np nr nu nz
+ om
+ pa pe pf pg ph pk pl pm pn pr ps pt pw py
+ qa
+ re ro rs ru rw
+ sa sb sc sd se sg sh si sj sk sl sm sn so sr ss st su sv sy sz
+ tc td tf tg th tj tk tl tm tn to tp tr tt tv tw tz
+ ua ug ak us uy uz
+ va vc ve vg vi vn vu
+ wf ws
+ ye yt
+ za zm zw
+ ]
+
#
# Creates a new resolver.
#
|
Added Resolv::TLDS.
|
ronin-ruby_ronin-support
|
train
|
c4ce71c15e09abee4998bec2e9a083975eaa6cad
|
diff --git a/src/naarad/metrics/metric.py b/src/naarad/metrics/metric.py
index <HASH>..<HASH> 100644
--- a/src/naarad/metrics/metric.py
+++ b/src/naarad/metrics/metric.py
@@ -241,7 +241,7 @@ class Metric(object):
def calculate_stats(self):
stats_to_calculate = ['mean', 'std', 'min', 'max'] # TODO: get input from user
- percentiles_to_calculate = range(0, 100, 1) # TODO: get input from user
+ percentiles_to_calculate = range(0, 101, 1) # TODO: get input from user
headers = CONSTANTS.SUBMETRIC_HEADER + ',mean,std,p50,p75,p90,p95,p99,min,max\n' # TODO: This will be built from user input later on
metric_stats_csv_file = self.get_stats_csv()
imp_metric_stats_csv_file = self.get_important_sub_metrics_csv()
|
including <I>% percentile
|
linkedin_naarad
|
train
|
6acf1dfc2d03484de3e90147603d0b020f332cce
|
diff --git a/lib/halite/helper_base.rb b/lib/halite/helper_base.rb
index <HASH>..<HASH> 100644
--- a/lib/halite/helper_base.rb
+++ b/lib/halite/helper_base.rb
@@ -17,6 +17,7 @@
# Much inspiration from Bundler's GemHelper. Thanks!
require 'bundler'
+require 'thor'
require 'thor/shell'
require 'halite/error'
|
Make sure we pull in all of Thor so `shell.ask` works.
|
poise_halite
|
train
|
be125e30bedebf4e5917b63993325f71db018f1d
|
diff --git a/lib/surrounded/context.rb b/lib/surrounded/context.rb
index <HASH>..<HASH> 100644
--- a/lib/surrounded/context.rb
+++ b/lib/surrounded/context.rb
@@ -128,11 +128,14 @@ module Surrounded
end
def assign_role(role, obj)
- role_behavior_name = role.to_s.gsub(/(?:^|_)([a-z])/) { $1.upcase }
- role_map << [role, role_behavior_name, obj]
+ role_map << [role, role_behavior(role), obj]
instance_variable_set("@#{role}", obj)
self
end
+
+ def role_behavior(role)
+ role.to_s.gsub(/(?:^|_)([a-z])/) { $1.upcase }
+ end
end
end
end
\ No newline at end of file
|
extract method for finding constant name from role
|
saturnflyer_surrounded
|
train
|
8ee6401246a0a23540b831d46fc14287aabf44c6
|
diff --git a/cherrypy/test/test_iterator.py b/cherrypy/test/test_iterator.py
index <HASH>..<HASH> 100644
--- a/cherrypy/test/test_iterator.py
+++ b/cherrypy/test/test_iterator.py
@@ -4,7 +4,7 @@ from cherrypy._cpcompat import unicodestr
class IteratorBase(object):
created = 0
- datachunk = u'butternut squash' * 256
+ datachunk = 'butternut squash' * 256
@classmethod
def incr(cls):
|
Remove literal unicode to be able to execute the test_iterator.
|
cherrypy_cheroot
|
train
|
4a9384840207c4b99f6b89293334f18cd48eb58b
|
diff --git a/tests/core.js b/tests/core.js
index <HASH>..<HASH> 100644
--- a/tests/core.js
+++ b/tests/core.js
@@ -13,7 +13,7 @@ global.document = {
};
global.EventTarget = function () { };
-require("../src/core.js");
+require("../src/core.js")(this);
describe("DOMEventListener", function () {
var testObject;
|
begining understand nodejs context ;)
|
enbock_corejs-w3c
|
train
|
847e8dee354989920d86f8b61f997f2d60852a60
|
diff --git a/consensus/poet/core/sawtooth_poet/poet_consensus/poet_block_publisher.py b/consensus/poet/core/sawtooth_poet/poet_consensus/poet_block_publisher.py
index <HASH>..<HASH> 100644
--- a/consensus/poet/core/sawtooth_poet/poet_consensus/poet_block_publisher.py
+++ b/consensus/poet/core/sawtooth_poet/poet_consensus/poet_block_publisher.py
@@ -56,7 +56,6 @@ class PoetBlockPublisher(BlockPublisherInterface):
other consensus algorithms
"""
- _poet_public_key = None
_previous_block_id = None
_validator_registry_namespace = \
@@ -191,7 +190,8 @@ class PoetBlockPublisher(BlockPublisherInterface):
self._batch_publisher.send([transaction])
- # Store the key state so that we can look it up later if need be
+ # Store the key state so that we can look it up later if need be and
+ # set the new key as our active key
LOGGER.info(
'Save key state PPK=%s...%s => SSD=%s...%s',
signup_info.poet_public_key[:8],
@@ -202,10 +202,7 @@ class PoetBlockPublisher(BlockPublisherInterface):
PoetKeyState(
sealed_signup_data=signup_info.sealed_signup_data,
has_been_refreshed=False)
-
- # Cache the PoET public key in a class to indicate that this is the
- # current public key for the PoET enclave
- PoetBlockPublisher._poet_public_key = signup_info.poet_public_key
+ self._poet_key_state_store.active_key = signup_info.poet_public_key
def initialize_block(self, block_header):
"""Do initialization necessary for the consensus to claim a block,
@@ -253,12 +250,13 @@ class PoetBlockPublisher(BlockPublisherInterface):
except KeyError:
pass
- # If we don't have a validator registry entry, then check our cached
- # PoET public key. If we don't have one, then we need to sign up.
+ # If we don't have a validator registry entry, then check the active
+ # key. If we don't have one, then we need to sign up.
# If we do have one, then our validator registry entry has not
# percolated through the system, so nothing to to but wait.
+ active_poet_public_key = self._poet_key_state_store.active_key
if validator_info is None:
- if PoetBlockPublisher._poet_public_key is None:
+ if active_poet_public_key is None:
LOGGER.debug(
'No public key found, so going to register new signup '
'information')
@@ -273,26 +271,28 @@ class PoetBlockPublisher(BlockPublisherInterface):
# other validators think we are using. If not, then we need to switch
# the PoET enclave to using the correct keys.
elif validator_info.signup_info.poet_public_key != \
- PoetBlockPublisher._poet_public_key:
+ active_poet_public_key:
# Retrieve the key state corresponding to the PoET public key and
- # use it to re-establish the key used by the enclave.
+ # use it to re-establish the key used by the enclave. Also update
+ # the active PoET public key.
poet_key_state = \
self._poet_key_state_store[
validator_info.signup_info.poet_public_key]
- PoetBlockPublisher._poet_public_key = \
+ active_poet_public_key = \
SignupInfo.unseal_signup_data(
poet_enclave_module=poet_enclave_module,
validator_address=block_header.signer_pubkey,
sealed_signup_data=poet_key_state.sealed_signup_data)
+ self._poet_key_state_store.active_key = active_poet_public_key
- assert PoetBlockPublisher._poet_public_key == \
+ assert active_poet_public_key == \
validator_info.signup_info.poet_public_key
LOGGER.debug(
'Switched to public key: %s...%s',
- PoetBlockPublisher._poet_public_key[:8],
- PoetBlockPublisher._poet_public_key[-8:])
+ active_poet_public_key[:8],
+ active_poet_public_key[-8:])
LOGGER.debug(
'Unseal signup data: %s...%s',
poet_key_state.sealed_signup_data[:8],
@@ -338,18 +338,15 @@ class PoetBlockPublisher(BlockPublisherInterface):
# hit the key block claim limit, we won't even bother initializing
# a block on this chain as it will be rejected by other
# validators.
- poet_key_state = \
- self._poet_key_state_store[
- PoetBlockPublisher._poet_public_key]
+ poet_key_state = self._poet_key_state_store[active_poet_public_key]
if not poet_key_state.has_been_refreshed:
LOGGER.info(
'Reached block claim limit for key: %s...%s',
- PoetBlockPublisher._poet_public_key[:8],
- PoetBlockPublisher._poet_public_key[-8:])
+ active_poet_public_key[:8],
+ active_poet_public_key[-8:])
sealed_signup_data = poet_key_state.sealed_signup_data
- self._poet_key_state_store[
- PoetBlockPublisher._poet_public_key] = \
+ self._poet_key_state_store[active_poet_public_key] = \
PoetKeyState(
sealed_signup_data=sealed_signup_data,
has_been_refreshed=True)
|
Update PoET block publisher to use key state store active key
The PoET block publisher uses/used a class variable to store the active PoET public key. This update changes the PoET block publisher to remove the class variable and instead use the PoET key store's active key property to keep track of the active PoET public key.
|
hyperledger_sawtooth-core
|
train
|
5232c29999cd0c32dcc403569e505c046cfdbbcd
|
diff --git a/vendor/Krystal/Autoloader/PSR4.php b/vendor/Krystal/Autoloader/PSR4.php
index <HASH>..<HASH> 100644
--- a/vendor/Krystal/Autoloader/PSR4.php
+++ b/vendor/Krystal/Autoloader/PSR4.php
@@ -118,7 +118,7 @@ final class PSR4 extends AbstractSplLoader
// replace the namespace prefix with the base directory,
// replace namespace separators with directory separators
// in the relative class name, append with .php
- $file = $base_dir . str_replace('\\', '/', $relative_class) .'.php';
+ $file = $base_dir . str_replace('\\', '/', $relative_class) .self::EXTENSTION;
// if the mapped file exists, require it
if ($this->includeClass($file)) {
|
Replaced an extension with the class constant
|
krystal-framework_krystal.framework
|
train
|
1b2d0198eaea92f92d14b6c848ed7e183f8cd973
|
diff --git a/test/liquid/tags/html_tag_test.rb b/test/liquid/tags/html_tag_test.rb
index <HASH>..<HASH> 100644
--- a/test/liquid/tags/html_tag_test.rb
+++ b/test/liquid/tags/html_tag_test.rb
@@ -29,6 +29,9 @@ class HtmlTagTest < Test::Unit::TestCase
def test_quoted_fragment
assert_template_result("<tr class=\"row1\">\n<td class=\"col1\"> 1 </td><td class=\"col2\"> 2 </td><td class=\"col3\"> 3 </td></tr>\n<tr class=\"row2\"><td class=\"col1\"> 4 </td><td class=\"col2\"> 5 </td><td class=\"col3\"> 6 </td></tr>\n",
+ "{% tablerow n in collections.frontpage cols:3%} {{n}} {% endtablerow %}",
+ 'collections' => {'frontpage' => [1,2,3,4,5,6]})
+ assert_template_result("<tr class=\"row1\">\n<td class=\"col1\"> 1 </td><td class=\"col2\"> 2 </td><td class=\"col3\"> 3 </td></tr>\n<tr class=\"row2\"><td class=\"col1\"> 4 </td><td class=\"col2\"> 5 </td><td class=\"col3\"> 6 </td></tr>\n",
"{% tablerow n in collections['frontpage'] cols:3%} {{n}} {% endtablerow %}",
'collections' => {'frontpage' => [1,2,3,4,5,6]})
|
Added backwards compatibility test for tablerow tag update
* Follow up to <I>d<I>
|
Shopify_liquid
|
train
|
208149a62e9a7f794eae72e2e4f3fa6fc5ebe8f2
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,9 @@
All notable changes to this project will be documented in this file. This change log follows the conventions of [keepachangelog.com](http://keepachangelog.com/).
## [Unreleased][unreleased]
+### Changed
+- Generators are configured with `direction` and not `choose`.
+
### Fixed
- The date format error message now contains the correct spelling of "ambiguous".
diff --git a/lib/upcoming/factory.rb b/lib/upcoming/factory.rb
index <HASH>..<HASH> 100644
--- a/lib/upcoming/factory.rb
+++ b/lib/upcoming/factory.rb
@@ -49,7 +49,7 @@ module Upcoming
def create_generator(name, direction)
class_name = name.to_s.classify + 'Generator'
generator_class = Upcoming.const_get class_name
- generator_class.new(choose: direction)
+ generator_class.new(direction: direction)
end
end
end
diff --git a/lib/upcoming/generators/generator.rb b/lib/upcoming/generators/generator.rb
index <HASH>..<HASH> 100644
--- a/lib/upcoming/generators/generator.rb
+++ b/lib/upcoming/generators/generator.rb
@@ -1,9 +1,9 @@
module Upcoming
class Generator
- attr_reader :choose
+ attr_reader :direction
def initialize(options = {})
- @choose = options.fetch(:choose, :upcoming)
+ @direction = options.fetch(:direction, :upcoming)
end
def step(from)
@@ -13,7 +13,7 @@ module Upcoming
private
def date_range(date)
- return date.downto(date.prev_year) if choose == :preceding
+ return date.downto(date.prev_year) if direction == :preceding
date.upto(date.next_year)
end
end
diff --git a/spec/generators/generator_spec.rb b/spec/generators/generator_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/generators/generator_spec.rb
+++ b/spec/generators/generator_spec.rb
@@ -30,7 +30,7 @@ describe Upcoming::Generator do
end
context 'forward in time' do
- Given(:subject) { Upcoming::FakeGenerator.new(choose: :upcoming) }
+ Given(:subject) { Upcoming::FakeGenerator.new(direction: :upcoming) }
returns_the_starting_date_if_it_is_valid
@@ -51,7 +51,7 @@ describe Upcoming::Generator do
end
context 'backward in time' do
- Given(:subject) { Upcoming::FakeGenerator.new(choose: :preceding) }
+ Given(:subject) { Upcoming::FakeGenerator.new(direction: :preceding) }
returns_the_starting_date_if_it_is_valid
|
Generators are configured with "direction"
The current configuration variable is name `choose`, which sounds like a
bad choice.
|
sldblog_upcoming
|
train
|
484d9b120f306af34f63c2bbfde9cd568de2b7bf
|
diff --git a/Console/OutputHandler/OutputHandler.php b/Console/OutputHandler/OutputHandler.php
index <HASH>..<HASH> 100644
--- a/Console/OutputHandler/OutputHandler.php
+++ b/Console/OutputHandler/OutputHandler.php
@@ -51,7 +51,6 @@ class OutputHandler implements OutputHandlerInterface
Assertion::integer($count);
Assertion::greaterThan($count, 0);
- $this->style->newLine();
$this->style->progressStart($count);
}
|
remove the additional newLine before a progressbar
|
plentymarkets_plentymarkets-shopware-connector
|
train
|
8143d397881867fb921332250f50ebf18b35d524
|
diff --git a/lib/Doctrine/Cache/Array.php b/lib/Doctrine/Cache/Array.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/Cache/Array.php
+++ b/lib/Doctrine/Cache/Array.php
@@ -52,7 +52,7 @@ class Doctrine_Cache_Array implements Countable, Doctrine_Cache_Interface
if (isset($this->data[$id])) {
return $this->data[$id];
}
- return null;
+ return false;
}
/**
* Test if a cache is available or not (for the given id)
diff --git a/lib/Doctrine/Hydrate.php b/lib/Doctrine/Hydrate.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/Hydrate.php
+++ b/lib/Doctrine/Hydrate.php
@@ -786,10 +786,10 @@ class Doctrine_Hydrate extends Doctrine_Object implements Serializable
// calculate hash for dql query
$hash = md5($dql . var_export($params, true));
- $cached = ($this->_expireCache) ? null : $cacheDriver->fetch($hash);
+ $cached = ($this->_expireCache) ? false : $cacheDriver->fetch($hash);
- if ($cached === null) {
+ if ($cached === false) {
// cache miss
$stmt = $this->_execute($params);
$array = $this->parseData2($stmt, Doctrine::HYDRATE_ARRAY);
|
fixed bug in Cache, made Array.php compliant to its/the interfaces documentation (returning false instead of null when nothing found) and changed if statement in Hydrate to react on false, not on null too
|
doctrine_orm
|
train
|
730cf1cee98e89180e338b24aa91b9860c3d7a05
|
diff --git a/src/client/windshaft.js b/src/client/windshaft.js
index <HASH>..<HASH> 100644
--- a/src/client/windshaft.js
+++ b/src/client/windshaft.js
@@ -252,6 +252,58 @@ export default class Windshaft {
});
}
+ _decodePolygons(geom, featureGeometries, mvt_extent){
+ let polygon = null;
+ let geometry = [];
+ /*
+ All this clockwise non-sense is needed because the MVT decoder dont decode the MVT fully.
+ It doesn't distinguish between internal polygon rings (which defines holes) or external ones, which defines more polygons (mulipolygons)
+ See:
+ https://github.com/mapbox/vector-tile-spec/tree/master/2.1
+ https://en.wikipedia.org/wiki/Shoelace_formula
+ */
+ for (let j = 0; j < geom.length; j++) {
+ //if exterior
+ // push current polygon & set new empty
+ //else=> add index to holes
+ if (isClockWise(geom[j])) {
+ if (polygon) {
+ geometry.push(polygon);
+ }
+ polygon = {
+ flat: [],
+ holes: []
+ };
+ } else {
+ if (j == 0) {
+ throw new Error('Invalid MVT tile: first polygon ring MUST be external');
+ }
+ polygon.holes.push(polygon.flat.length / 2);
+ }
+ for (let k = 0; k < geom[j].length; k++) {
+ polygon.flat.push(2 * geom[j][k].x / mvt_extent - 1.);
+ polygon.flat.push(2 * (1. - geom[j][k].y / mvt_extent) - 1.);
+ }
+ }
+ //if current polygon is not empty=> push it
+ if (polygon && polygon.flat.length > 0) {
+ geometry.push(polygon);
+ }
+ featureGeometries.push(geometry);
+ }
+
+ _decodeLines(geom, featureGeometries, mvt_extent){
+ let geometry = [];
+ geom.map(l => {
+ let line = [];
+ l.map(point => {
+ line.push(2 * point.x / mvt_extent - 1, 2 * (1 - point.y / mvt_extent) - 1);
+ });
+ geometry.push(line);
+ });
+ featureGeometries.push(geometry);
+ }
+
_decodeMVTLayer(mvtLayer, metadata, mvt_extent, catFields, catFieldsReal, numFields) {
var properties = [new Float32Array(mvtLayer.length + 1024), new Float32Array(mvtLayer.length + 1024), new Float32Array(mvtLayer.length + 1024), new Float32Array(mvtLayer.length + 1024)];
if (this.geomType == 'point') {
@@ -261,56 +313,13 @@ export default class Windshaft {
for (var i = 0; i < mvtLayer.length; i++) {
const f = mvtLayer.feature(i);
const geom = f.loadGeometry();
- let geometry = [];
if (this.geomType == 'point') {
points[2 * i + 0] = 2 * (geom[0][0].x) / mvt_extent - 1.;
points[2 * i + 1] = 2 * (1. - (geom[0][0].y) / mvt_extent) - 1.;
} else if (this.geomType == 'polygon') {
- let polygon = null;
- /*
- All this clockwise non-sense is needed because the MVT decoder dont decode the MVT fully.
- It doesn't distinguish between internal polygon rings (which defines holes) or external ones, which defines more polygons (mulipolygons)
- See:
- https://github.com/mapbox/vector-tile-spec/tree/master/2.1
- https://en.wikipedia.org/wiki/Shoelace_formula
- */
- for (let j = 0; j < geom.length; j++) {
- //if exterior
- // push current polygon & set new empty
- //else=> add index to holes
- if (isClockWise(geom[j])) {
- if (polygon) {
- geometry.push(polygon);
- }
- polygon = {
- flat: [],
- holes: []
- };
- } else {
- if (j == 0) {
- throw new Error('Invalid MVT tile: first polygon ring MUST be external');
- }
- polygon.holes.push(polygon.flat.length / 2);
- }
- for (let k = 0; k < geom[j].length; k++) {
- polygon.flat.push(2 * geom[j][k].x / mvt_extent - 1.);
- polygon.flat.push(2 * (1. - geom[j][k].y / mvt_extent) - 1.);
- }
- }
- //if current polygon is not empty=> push it
- if (polygon && polygon.flat.length > 0) {
- geometry.push(polygon);
- }
- featureGeometries.push(geometry);
+ this._decodePolygons(geom, featureGeometries, mvt_extent);
} else if (this.geomType == 'line') {
- geom.map(l => {
- let line = [];
- l.map(point => {
- line.push(2 * point.x / mvt_extent - 1, 2 * (1 - point.y / mvt_extent) - 1);
- });
- geometry.push(line);
- });
- featureGeometries.push(geometry);
+ this._decodeLines(geom, featureGeometries, mvt_extent);
} else {
throw new Error(`Unimplemented geometry type: '${this.geomType}'`);
}
|
Refactor mvt decoding
|
CartoDB_carto-vl
|
train
|
633bf7426d27e8d43826a9b1c7cbd20d02dd9ab8
|
diff --git a/climlab/domain/field.py b/climlab/domain/field.py
index <HASH>..<HASH> 100644
--- a/climlab/domain/field.py
+++ b/climlab/domain/field.py
@@ -317,12 +317,27 @@ def global_mean(field):
"""
try:
- lat = field.domain.axes['lat'].points
+ lat = field.domain.lat.points
except:
raise ValueError('No latitude axis in input field.')
- lat_radians = np.deg2rad(lat)
- return _global_mean(field.squeeze(), lat_radians)
+ try:
+ # Field is 2D latitude / longitude
+ lon = field.domain.lon.points
+ return _global_mean_latlon(field.squeeze())
+ except:
+ # Field is 1D latitude only (zonal average)
+ lat_radians = np.deg2rad(lat)
+ return _global_mean(field.squeeze(), lat_radians)
def _global_mean(array, lat_radians):
- return np.sum(array * np.cos(lat_radians)) / np.sum(np.cos(lat_radians))
+ return np.average(array, weights=np.cos(lat_radians))
+
+
+def _global_mean_latlon(field):
+ dom = field.domain
+ lon, lat = np.meshgrid(dom.lon.points, dom.lat.points)
+ dy = np.deg2rad(np.diff(dom.lat.bounds))
+ dx = np.deg2rad(np.diff(dom.lon.bounds))*np.cos(np.deg2rad(lat))
+ area = dx * dy[:,np.newaxis] # grid cell area in radians^2
+ return np.average(field, weights=area)
|
global_mean method now handles both 1D (latitude) and 2D (latitutde / longitude) field variables.
|
brian-rose_climlab
|
train
|
59e168d22526e5fc3b0d6a66e12188e6679901b9
|
diff --git a/obdalib-core/src/main/java/it/unibz/krdb/obda/model/impl/TermUtil.java b/obdalib-core/src/main/java/it/unibz/krdb/obda/model/impl/TermUtil.java
index <HASH>..<HASH> 100644
--- a/obdalib-core/src/main/java/it/unibz/krdb/obda/model/impl/TermUtil.java
+++ b/obdalib-core/src/main/java/it/unibz/krdb/obda/model/impl/TermUtil.java
@@ -29,45 +29,49 @@ public class TermUtil {
}
else if (term instanceof ValueConstant) {
ValueConstant constant = (ValueConstant) term;
- StringBuilder bf = new StringBuilder();
- bf.append("\"");
- bf.append(constant.getValue());
- bf.append("\"");
+ StringBuilder sb = new StringBuilder();
-
- final COL_TYPE datatype = constant.getType();
- if (datatype == COL_TYPE.LITERAL_LANG) {
- bf.append("@");
- bf.append(constant.getLanguage());
- } else if (datatype == COL_TYPE.LITERAL) {
- // NO-OP
- } else {
- bf.append("^^");
- bf.append(datatype);
+ String value = constant.getValue();
+ switch (constant.getType()) {
+ case STRING:
+ case DATETIME: sb.append(quoted(value)); break;
+ case INTEGER:
+ case DECIMAL:
+ case DOUBLE:
+ case BOOLEAN: sb.append(value); break;
+ case LITERAL:
+ case LITERAL_LANG:
+ String lang = constant.getLanguage();
+ if (lang != null && !lang.isEmpty()) {
+ value += "@" + lang;
+ }
+ sb.append(quoted(value)); break;
+ default:
+ sb.append(value);
}
- return bf.toString();
+ return sb.toString();
}
else if (term instanceof URIConstant) {
URIConstant constant = (URIConstant) term;
- return constant.getValue();
+ return "<" + constant.getValue() + ">";
}
else if (term instanceof Function) {
Function function = (Function) term;
Predicate functionSymbol = function.getFunctionSymbol();
- StringBuilder args = new StringBuilder();
- args.append(functionSymbol.toString());
- args.append("(");
+ StringBuilder sb = new StringBuilder();
+ sb.append(functionSymbol.toString());
+ sb.append("(");
boolean separator = false;
for (Term innerTerm : function.getTerms()) {
if (separator) {
- args.append(", ");
+ sb.append(",");
}
- args.append(toString(innerTerm));
+ sb.append(toString(innerTerm));
separator = true;
}
- args.append(")");
- return args.toString();
+ sb.append(")");
+ return sb.toString();
}
else if (term instanceof BNode) {
BNode bnode = (BNode) term;
@@ -75,4 +79,8 @@ public class TermUtil {
}
return term.toString(); // for other unknown term
}
+
+ private static String quoted(String value) {
+ return "\"" + value + "\"";
+ }
}
|
Update the string representation for Constant objects.
|
ontop_ontop
|
train
|
d49748325ad2e29e003af5ec8b82a87b3059536d
|
diff --git a/src/Composer/Application.php b/src/Composer/Application.php
index <HASH>..<HASH> 100644
--- a/src/Composer/Application.php
+++ b/src/Composer/Application.php
@@ -11,11 +11,7 @@ namespace sebastianfeldmann\CaptainHook\Composer;
use Composer\IO\IOInterface;
use sebastianfeldmann\CaptainHook\Console\Application\ConfigHandler;
-use sebastianfeldmann\CaptainHook\Console\Command\Configuration;
use sebastianfeldmann\CaptainHook\Console\IO\ComposerIO;
-use Symfony\Component\Console\Input\ArrayInput;
-use Symfony\Component\Console\Input\InputInterface;
-use Symfony\Component\Console\Output\OutputInterface;
/**
* Class Application
@@ -45,17 +41,12 @@ class Application extends ConfigHandler
}
/**
- * Execute hook.
+ * IO Getter.
*
- * @param \Symfony\Component\Console\Input\InputInterface $input
- * @param \Symfony\Component\Console\Output\OutputInterface $output
- * @return int
+ * @return \sebastianfeldmann\CaptainHook\Console\IO\ComposerIO
*/
- public function doRun(InputInterface $input, OutputInterface $output)
+ public function getIO()
{
- $input = new ArrayInput(['--configuration' => $this->getConfigFile()]);
- $command = new Configuration();
- $command->setIO($this->io);
- return $command->run($input, $output);
+ return $this->io;
}
}
diff --git a/src/Composer/Cmd.php b/src/Composer/Cmd.php
index <HASH>..<HASH> 100644
--- a/src/Composer/Cmd.php
+++ b/src/Composer/Cmd.php
@@ -10,6 +10,9 @@
namespace sebastianfeldmann\CaptainHook\Composer;
use Composer\Script\Event;
+use sebastianfeldmann\CaptainHook\Console\Command\Configuration;
+use sebastianfeldmann\CaptainHook\Console\Command\Install;
+use Symfony\Component\Console\Input\ArrayInput;
/**
* Class Cmd
@@ -29,10 +32,45 @@ abstract class Cmd
*/
public static function configure(Event $event, $config = null)
{
+ $app = self::createApplication($event, $config);
+ $configuration = new Configuration();
+ $configuration->setIO($app->getIO());
+ $input = new ArrayInput(
+ ['command' => 'configure', '--configuration' => $config, '-f' => '-f', '-e' => '-e']
+ );
+ $app->add($configuration);
+ $app->run($input);
+ }
+
+ /**
+ * Installs the hooks to your local repository
+ *
+ * @param \Composer\Script\Event $event
+ * @param string $config
+ */
+ public static function install(Event $event, $config = null)
+ {
+ $app = self::createApplication($event, $config);
+ $install = new Install();
+ $install->setIO($app->getIO());
+ $input = new ArrayInput(['command' => 'install', '--configuration' => $config, '-f' => '-f']);
+ $app->add($install);
+ $app->run($input);
+ }
+
+ /**
+ * Create a CaptainHook Composer application.
+ *
+ * @param \Composer\Script\Event $event
+ * @param string $config
+ * @return \sebastianfeldmann\CaptainHook\Composer\Application
+ */
+ private static function createApplication(Event $event, $config = null)
+ {
$app = new Application();
$app->setAutoExit(false);
$app->setConfigFile($config);
$app->setProxyIO($event->getIO());
- $app->run();
+ return $app;
}
}
diff --git a/tests/CaptainHook/Composer/CmdTest.php b/tests/CaptainHook/Composer/CmdTest.php
index <HASH>..<HASH> 100644
--- a/tests/CaptainHook/Composer/CmdTest.php
+++ b/tests/CaptainHook/Composer/CmdTest.php
@@ -10,6 +10,7 @@
namespace sebastianfeldmann\CaptainHook\Composer;
use Composer\IO\NullIO;
+use sebastianfeldmann\CaptainHook\Git\DummyRepo;
class CmdTest extends \PHPUnit_Framework_TestCase
{
@@ -29,4 +30,32 @@ class CmdTest extends \PHPUnit_Framework_TestCase
unlink($config);
}
+
+ /**
+ * Tests Cmd::configure
+ */
+ public function testInstall()
+ {
+ $event = $this->getMockBuilder('\\Composer\\Script\\Event')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $event->expects($this->once())->method('getIO')->willReturn(new NullIO());
+
+ $repo = new DummyRepo();
+ $repo->setup();
+
+ $config = $repo->getPath() . DIRECTORY_SEPARATOR . 'captainhook.json';
+ $old = getcwd();
+ chdir($repo->getPath());
+ file_put_contents($config, '{}');
+
+ Cmd::install($event);
+
+ $this->assertTrue(file_exists($repo->getHookDir() . DIRECTORY_SEPARATOR . 'pre-commit'), 'pre-commit');
+ $this->assertTrue(file_exists($repo->getHookDir() . DIRECTORY_SEPARATOR . 'pre-push'), 'pre-push');
+ $this->assertTrue(file_exists($repo->getHookDir() . DIRECTORY_SEPARATOR . 'commit-msg'), 'commit-msg');
+
+ $repo->cleanup();
+ chdir($old);
+ }
}
|
Add new composer post script method 'install'
This is used to force the activation of your git hooks if someone uses
composer to install your project.
This doesn't prevent anyone from using the '--no-verify' option,
but it's a step more someone has to do to bypass the configured hooks.
|
CaptainHookPhp_captainhook
|
train
|
2f913f0ebfaf9b6a433c8e9b26b33f1e4ac6557f
|
diff --git a/jruby-maven-plugin/src/main/java/de/saumya/mojo/jruby/AbstractJRubyMojo.java b/jruby-maven-plugin/src/main/java/de/saumya/mojo/jruby/AbstractJRubyMojo.java
index <HASH>..<HASH> 100644
--- a/jruby-maven-plugin/src/main/java/de/saumya/mojo/jruby/AbstractJRubyMojo.java
+++ b/jruby-maven-plugin/src/main/java/de/saumya/mojo/jruby/AbstractJRubyMojo.java
@@ -8,6 +8,7 @@ import org.apache.maven.artifact.DependencyResolutionRequiredException;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolutionRequest;
import org.apache.maven.model.Dependency;
+import org.apache.maven.model.Resource;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
@@ -21,83 +22,98 @@ import de.saumya.mojo.ruby.script.ScriptFactory;
/**
* Base for all JRuby mojos.
- *
+ *
* @requiresProject false
*/
public abstract class AbstractJRubyMojo extends AbstractMojo {
- private static String DEFAULT_JRUBY_VERSION = "1.5.6";
+ private static String DEFAULT_JRUBY_VERSION = "1.6.1";
public static final String GEM_RUBY_COMMAND = "META-INF/jruby.home/bin/gem";
- public static final String IRB_RUBY_COMMAND = "jirb";
-
- public static final String IRB_SWING_RUBY_COMMAND = "jirb_swing";
-
public static final String RAKE_RUBY_COMMAND = "META-INF/jruby.home/bin/rake";
/**
* common arguments
- *
+ *
* @parameter expression="${args}"
+ * <br/>
+ * Command line -Dargs=...
*/
protected String args;
/**
* arguments for the jruby command.
- *
- * @parameter default-value="${jruby.args}"
- */
- protected String jrubyArgs = null;
-
-
- /**
- * arguments for the jruby command.
- *
+ *
* @parameter expression="${jruby.jvmargs}"
+ * <br/>
+ * Command line -Djruby.jvmargs=...
*/
protected String jrubyJvmArgs;
/**
- * switches for the jruby command.
+ * switches for the jruby command, like '--1.9'
*
* @parameter expression="${jruby.switches}"
+ * <br/>
+ * Command line -Djruby.switches=...
*/
protected String jrubySwitches;
-
+
/**
* if the pom.xml has no runtime dependency to a jruby-complete.jar then
* this version is used to resolve the jruby-complete dependency from the
- * local/remote maven repository. defaults to "1.5.6".
- *
- * @parameter default-value="${jruby.version}"
+ * local/remote maven repository. it overwrites the jruby version from
+ * the dependencies if any. i.e. you can easily switch jruby version from the commandline !
+ * <br/>
+ * default: 1.6.1
+ *
+ * @parameter expression="${jruby.version}"
+ * <br/>
+ * Command line -Djruby.version=...
*/
protected String jrubyVersion;
/**
* fork the JRuby execution.
- *
+ *
* @parameter expression="${jruby.fork}" default-value="true"
+ * <br/>
+ * Command line -Djruby.fork=...
*/
protected boolean jrubyFork;
/**
* verbose jruby related output
- *
+ *
* @parameter expression="${jruby.verbose}" default-value="false"
+ * <br/>
+ * Command line -Djruby.verbose=...
*/
protected boolean jrubyVerbose;
+
+ /**
+ * the launch directory for the JRuby execution.
+ *
+ * @parameter expression="${jruby.sourceDirectory}" default-value="src/main/ruby"
+ * <br/>
+ * Command line -Djruby.soureDirectory=...
+ */
+ protected File rubySourceDirectory;
+
/**
* the launch directory for the JRuby execution.
- *
- * @parameter default-value="${launchDirectory}"
+ *
+ * @parameter default-value="${basedir}" expression="${jruby.launchDirectory}"
+ * <br/>
+ * Command line -Djruby.launchDirectory=...
*/
private File launchDirectory;
/**
* reference to maven project for internal use.
- *
+ *
* @parameter expression="${project}"
* @required
* @readOnly true
@@ -106,7 +122,7 @@ public abstract class AbstractJRubyMojo extends AbstractMojo {
/**
* local repository for internal use.
- *
+ *
* @parameter default-value="${localRepository}"
* @required
* @readonly
@@ -115,7 +131,7 @@ public abstract class AbstractJRubyMojo extends AbstractMojo {
/**
* classrealm for internal use.
- *
+ *
* @parameter expression="${dummyExpression}"
* @readonly
*/
@@ -155,9 +171,14 @@ public abstract class AbstractJRubyMojo extends AbstractMojo {
}
public void execute() throws MojoExecutionException, MojoFailureException {
+ if(rubySourceDirectory.exists()){
+ Resource resource = new Resource();
+ resource.setDirectory(rubySourceDirectory.getAbsolutePath());
+ project.getBuild().getResources().add(resource);
+ }
+
this.logger = new MojoLogger(this.jrubyVerbose, getLog());
this.factory = newScriptFactory();
- this.factory.addJavaArgs(this.jrubyArgs);
this.factory.addJvmArgs(this.jrubyJvmArgs);
this.factory.addSwitches(this.jrubySwitches);
|
added src/main/ruby to classpath if it exists. removed javaArgs since they are the same as jrubyJvmargs
|
torquebox_jruby-maven-plugins
|
train
|
9e0e4d5368bb096c81fa2685b50552051302e312
|
diff --git a/lib/active_hash/relation.rb b/lib/active_hash/relation.rb
index <HASH>..<HASH> 100644
--- a/lib/active_hash/relation.rb
+++ b/lib/active_hash/relation.rb
@@ -68,6 +68,10 @@ module ActiveHash
length
end
+ def size
+ length
+ end
+
def pluck(*column_names)
column_names.map { |column_name| all.map(&column_name.to_sym) }.inject(&:zip)
end
diff --git a/spec/active_hash/relation_spec.rb b/spec/active_hash/relation_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/active_hash/relation_spec.rb
+++ b/spec/active_hash/relation_spec.rb
@@ -9,7 +9,7 @@ RSpec.describe ActiveHash::Relation do
]
end
end
-
+
subject { model_class.all }
describe '#sample' do
@@ -24,18 +24,30 @@ RSpec.describe ActiveHash::Relation do
expect(records.sample(2).count).to eq(2)
end
end
-
+
describe '#to_ary' do
it 'returns an array' do
expect(subject.to_ary).to be_an(Array)
end
-
+
it 'contains the same items as the relation' do
array = subject.to_ary
-
+
expect(array.length).to eq(subject.count)
expect(array.first.id).to eq(1)
expect(array.second.id).to eq(2)
end
end
+
+ describe '#size' do
+ it 'returns an Integer' do
+ expect(subject.size).to be_an(Integer)
+ end
+
+ it 'returns the correct number of items of the relation' do
+ array = subject.to_ary
+
+ expect(array.size).to eq(2)
+ end
+ end
end
|
Add ActiveHash::Relation#size method for compatibily
With Rails <I> ActionView::Renderer::CollectionRenderer calls size
method over collections. Adding the size method makes ActiveHash
compatible with it
|
zilkey_active_hash
|
train
|
4a998e3eaaf5f05e227d8beb70c7467f420da57d
|
diff --git a/src/Iterator.php b/src/Iterator.php
index <HASH>..<HASH> 100644
--- a/src/Iterator.php
+++ b/src/Iterator.php
@@ -47,7 +47,7 @@ class Iterator {
* @return Iterator
*/
public function filter(\Closure $predicate) {
- return new FilterIterator($predicate, $this);
+ return new FilteredIterator($predicate, $this);
}
/**
|
FilterIterator -> FilteredIterator
|
lechimp-p_flightcontrol
|
train
|
38e3a6896a8a9d32fbae127a8b09af4d3565b7b4
|
diff --git a/mongo/mongo_test.go b/mongo/mongo_test.go
index <HASH>..<HASH> 100644
--- a/mongo/mongo_test.go
+++ b/mongo/mongo_test.go
@@ -635,14 +635,14 @@ func (s *MongoSuite) TestNoMongoDir(c *gc.C) {
func (s *MongoSuite) TestSelectPeerAddress(c *gc.C) {
addresses := []network.Address{{
- Value: "10.0.0.1",
- Type: network.IPv4Address,
- NetworkName: "cloud",
- Scope: network.ScopeCloudLocal}, {
- Value: "8.8.8.8",
- Type: network.IPv4Address,
- NetworkName: "public",
- Scope: network.ScopePublic}}
+ Value: "10.0.0.1",
+ Type: network.IPv4Address,
+ Scope: network.ScopeCloudLocal,
+ }, {
+ Value: "8.8.8.8",
+ Type: network.IPv4Address,
+ Scope: network.ScopePublic,
+ }}
address := mongo.SelectPeerAddress(addresses)
c.Assert(address, gc.Equals, "10.0.0.1")
@@ -652,17 +652,15 @@ func (s *MongoSuite) TestSelectPeerHostPort(c *gc.C) {
hostPorts := []network.HostPort{{
Address: network.Address{
- Value: "10.0.0.1",
- Type: network.IPv4Address,
- NetworkName: "cloud",
- Scope: network.ScopeCloudLocal,
+ Value: "10.0.0.1",
+ Type: network.IPv4Address,
+ Scope: network.ScopeCloudLocal,
},
Port: environs.DefaultStatePort}, {
Address: network.Address{
- Value: "8.8.8.8",
- Type: network.IPv4Address,
- NetworkName: "public",
- Scope: network.ScopePublic,
+ Value: "8.8.8.8",
+ Type: network.IPv4Address,
+ Scope: network.ScopePublic,
},
Port: environs.DefaultStatePort}}
|
mongo: Removed NetworkName from addresses
|
juju_juju
|
train
|
a0ac109980f447e7f5d92f3b01be8c094ee33889
|
diff --git a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java
index <HASH>..<HASH> 100644
--- a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java
+++ b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java
@@ -1944,7 +1944,8 @@ public final class CommandLineRunnerTest extends TestCase {
* @param expectedOutput string representation of expected output.
* @param entries entries of flags for zip and js files containing source to compile.
*/
- private void compileFiles(String expectedOutput, FlagEntry<JsSourceType>... entries)
+ @SafeVarargs
+ private final void compileFiles(String expectedOutput, FlagEntry<JsSourceType>... entries)
throws FlagUsageException {
for (FlagEntry<JsSourceType> entry : entries) {
args.add("--" + entry.flag.flagName + "=" + entry.value);
@@ -1957,7 +1958,8 @@ public final class CommandLineRunnerTest extends TestCase {
* @param expectedOutput string representation of expected output.
* @param entries entries of flags for js files containing source to compile.
*/
- private void compileJsFiles(String expectedOutput, FlagEntry<JsSourceType>... entries)
+ @SafeVarargs
+ private final void compileJsFiles(String expectedOutput, FlagEntry<JsSourceType>... entries)
throws FlagUsageException {
args.add("--js");
for (FlagEntry<JsSourceType> entry : entries) {
|
Add @SafeVarargs to methods that cause warnings
This removes multiple warnings about potentially unsafe operations
on varargs.
|
google_closure-compiler
|
train
|
c75ff4687a545f8e6a3d24eae085fddc1ed5b358
|
diff --git a/tests/test_optimize.py b/tests/test_optimize.py
index <HASH>..<HASH> 100644
--- a/tests/test_optimize.py
+++ b/tests/test_optimize.py
@@ -51,7 +51,7 @@ def test_mono_not_inverted(resources, outdir):
)
with Image.open(fspath(outdir / 'im.png')) as im:
- assert im.getpixel((0, 0)) == 255, "Expected white background"
+ assert im.getpixel((0, 0)) > 240, "Expected white background"
@needs_pngquant
|
Turning on Ghostscript interpolation changes this test
Seems acceptable. We don't normally use Ghostscript to downsample PDFs
like is happening in this test.
|
jbarlow83_OCRmyPDF
|
train
|
8cc708bccaf7f0eb1f2f31284b9fded19764e53e
|
diff --git a/packages/moleculer-db-adapter-couchdb-nano/src/index.js b/packages/moleculer-db-adapter-couchdb-nano/src/index.js
index <HASH>..<HASH> 100644
--- a/packages/moleculer-db-adapter-couchdb-nano/src/index.js
+++ b/packages/moleculer-db-adapter-couchdb-nano/src/index.js
@@ -162,11 +162,12 @@ class CouchDbNanoAdapter {
delete selector.fields;
}
- Object.entries(selector).forEach(([key, value]) => {
- if (typeof value !== "object") {
- selector[key] = {$eq: value};
+ Object.keys(selector).forEach(key => {
+ if (selector.hasOwnProperty(key) && typeof selector[key] !== "object") {
+ selector[key] = {$eq: selector[key]};
}
});
+
return Promise.resolve(this.db.find({selector, limit, skip, sort, fields}).then(result => result.docs));
}
|
changed Object.entries to Object.keys
|
moleculerjs_moleculer-db
|
train
|
2f986649ca96c099c485565c4d1eb7658fddb977
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,10 +3,10 @@
Full changelog for PHP Quill Renderer
-## v3.17.5 - 2019-11-24
+## v3.18.0 - 2019-11-24
* Custom attributes values which aren't strings are ignored.
-
+* Custom attributes which the parser should ignored can now be defined.
## v3.17.4 - 2019-05-01
diff --git a/Tests/Attributes/Html/TypographyTest.php b/Tests/Attributes/Html/TypographyTest.php
index <HASH>..<HASH> 100644
--- a/Tests/Attributes/Html/TypographyTest.php
+++ b/Tests/Attributes/Html/TypographyTest.php
@@ -61,6 +61,11 @@ final class TypographyTest extends \PHPUnit\Framework\TestCase
<br />
</p>
';
+ private $expected_custom_array_attribute_ignore_who = '<p><strong>world</strong>
+
+<br />
+</p>
+';
/**
* Test bold attribute
@@ -252,13 +257,14 @@ final class TypographyTest extends \PHPUnit\Framework\TestCase
try {
$quill = new QuillRender($this->delta_custom_array_attribute);
+ $quill->setIgnoredCustomAttributes(['who']);
$result = $quill->render();
} catch (\Exception $e) {
$this->fail(__METHOD__ . 'failure, ' . $e->getMessage());
}
$this->assertEquals(
- $this->expected_custom_array_attribute,
+ $this->expected_custom_array_attribute_ignore_who,
$result,
__METHOD__ . ' - Custom attribute which is an array'
);
diff --git a/src/Delta/Html/Compound.php b/src/Delta/Html/Compound.php
index <HASH>..<HASH> 100644
--- a/src/Delta/Html/Compound.php
+++ b/src/Delta/Html/Compound.php
@@ -83,7 +83,7 @@ class Compound extends Delta
break;
default:
- if (in_array($attribute, Settings::ignoredAttributes()) === false) {
+ if (in_array($attribute, Settings::ignoredCustomAttributes()) === false) {
$this->element_attributes[$attribute] = $value;
}
break;
diff --git a/src/Delta/Html/CompoundImage.php b/src/Delta/Html/CompoundImage.php
index <HASH>..<HASH> 100644
--- a/src/Delta/Html/CompoundImage.php
+++ b/src/Delta/Html/CompoundImage.php
@@ -52,7 +52,7 @@ class CompoundImage extends Delta
if (
is_string($attribute) &&
is_string($value) &&
- in_array($attribute, Settings::ignoredAttributes()) === false
+ in_array($attribute, Settings::ignoredCustomAttributes()) === false
) {
$image_attributes .= "{$attribute}=\"{$value}\" ";
}
diff --git a/src/Delta/Html/Insert.php b/src/Delta/Html/Insert.php
index <HASH>..<HASH> 100644
--- a/src/Delta/Html/Insert.php
+++ b/src/Delta/Html/Insert.php
@@ -55,7 +55,7 @@ class Insert extends Delta
if (
is_string($attribute) &&
is_string($value) &&
- in_array($attribute, Settings::ignoredAttributes()) === false
+ in_array($attribute, Settings::ignoredCustomAttributes()) === false
) {
$html .= " {$attribute}=\"{$value}\"";
}
diff --git a/src/Render.php b/src/Render.php
index <HASH>..<HASH> 100644
--- a/src/Render.php
+++ b/src/Render.php
@@ -61,6 +61,18 @@ class Render
}
/**
+ * Set the custom attributes which you would like the parser to ignore
+ *
+ * @param array $ignored_attributes
+ */
+ public function setIgnoredCustomAttributes(array $ignored_attributes = [])
+ {
+ if (count($ignored_attributes) > 0) {
+ Settings::setIgnoredCustomAttributes($ignored_attributes);
+ }
+ }
+
+ /**
* Pass the content array to the renderer and return the generated output
*
* @param boolean Optionally trim the output
diff --git a/src/Settings.php b/src/Settings.php
index <HASH>..<HASH> 100644
--- a/src/Settings.php
+++ b/src/Settings.php
@@ -12,7 +12,7 @@ namespace DBlackborough\Quill;
*/
class Settings
{
- private static $ignored_attributes = [];
+ private static $ignored_custom_attributes = [];
/**
* Set any attributes which you would like the parser to ignore, specifically
@@ -20,9 +20,9 @@ class Settings
*
* @param array $attributes
*/
- static public function setIgnoredAttributes(array $attributes)
+ static public function setIgnoredCustomAttributes(array $attributes)
{
- self::$ignored_attributes = $attributes;
+ self::$ignored_custom_attributes = $attributes;
}
/**
@@ -30,8 +30,8 @@ class Settings
*
* @return array
*/
- static public function ignoredAttributes(): array
+ static public function ignoredCustomAttributes(): array
{
- return self::$ignored_attributes;
+ return self::$ignored_custom_attributes;
}
}
|
Updated CHANGELOG and added test
- Renamed the method, needs to be clear it is for custom attributes only.
- Updated the CHANGELOG
- Added a test to ensure ignored attributes are ignored.
|
deanblackborough_php-quill-renderer
|
train
|
7e639d6c4bc91e72de83a0453cc8f543ea20534b
|
diff --git a/src/lib/InstantSearch.js b/src/lib/InstantSearch.js
index <HASH>..<HASH> 100644
--- a/src/lib/InstantSearch.js
+++ b/src/lib/InstantSearch.js
@@ -193,10 +193,16 @@ Usage: instantsearch({
}
});
- // no need to trigger a search if we don't have any widgets left
- if (this.widgets.length > 0) {
- this.helper.search();
- }
+ // If there's multiple call to `removeWidget()` let's wait until they are all made
+ // and then check for widgets.length & make a search on next tick
+ //
+ // This solves an issue where you unmount a page and removing widget by widget
+ setTimeout(() => {
+ // no need to trigger a search if we don't have any widgets left
+ if (this.widgets.length > 0) {
+ this.helper.search();
+ }
+ }, 0);
}
/**
|
fix(removeWidget): check for widgets.length on next tick (#<I>)
|
algolia_instantsearch.js
|
train
|
471ce379c5e0ee4b8938971e1e24e84ce0172572
|
diff --git a/src/server/config/webpack.config.js b/src/server/config/webpack.config.js
index <HASH>..<HASH> 100644
--- a/src/server/config/webpack.config.js
+++ b/src/server/config/webpack.config.js
@@ -9,7 +9,7 @@ import {
nodeModulesPaths,
loadEnv,
} from './utils';
-import babalLoaderConfig from './babel.js';
+import babelLoaderConfig from './babel.js';
export default function () {
const config = {
@@ -42,7 +42,7 @@ export default function () {
{
test: /\.jsx?$/,
loader: require.resolve('babel-loader'),
- query: babalLoaderConfig,
+ query: babelLoaderConfig,
include: includePaths,
exclude: excludePaths,
},
|
fix typo (#<I>)
|
storybooks_storybook
|
train
|
c7ef3e04fddc9dea60c33a2b4e89013ce12f11eb
|
diff --git a/constraints.go b/constraints.go
index <HASH>..<HASH> 100644
--- a/constraints.go
+++ b/constraints.go
@@ -165,9 +165,46 @@ func (noneConstraint) Intersect(Constraint) Constraint {
return none
}
+// A ProjectConstraint combines a ProjectIdentifier with a Constraint. It
+// indicates that, if packages contained in the ProjectIdentifier enter the
+// depgraph, they must do so at a version that is allowed by the Constraint.
+type ProjectConstraint struct {
+ Ident ProjectIdentifier
+ Constraint Constraint
+}
+
+type workingConstraint struct {
+ Ident ProjectIdentifier
+ Constraint Constraint
+ overrNet, overrConstraint bool
+}
+
type ProjectConstraints map[ProjectRoot]ProjectProperties
-//func mergePCSlices( ProjectConstraints, wother ProjectConstraints) {
-//final := make(ProjectConstraints)
+func mergePCSlices(l []ProjectConstraint, r []ProjectConstraint) ProjectConstraints {
+ final := make(ProjectConstraints)
+
+ for _, pc := range l {
+ final[pc.Ident.LocalName] = ProjectProperties{
+ NetworkName: pc.Ident.netName(),
+ Constraint: pc.Constraint,
+ }
+ }
+
+ for _, pc := range r {
+ if pp, exists := final[pc.Ident.LocalName]; exists {
+ // Technically this should be done through a bridge for
+ // cross-version-type matching...but this is a one off for root and
+ // that's just ridiculous for this.
+ pp.Constraint = pp.Constraint.Intersect(pc.Constraint)
+ final[pc.Ident.LocalName] = pp
+ } else {
+ final[pc.Ident.LocalName] = ProjectProperties{
+ NetworkName: pc.Ident.netName(),
+ Constraint: pc.Constraint,
+ }
+ }
+ }
-//}
+ return final
+}
diff --git a/types.go b/types.go
index <HASH>..<HASH> 100644
--- a/types.go
+++ b/types.go
@@ -75,14 +75,6 @@ type ProjectIdentifier struct {
NetworkName string
}
-// A ProjectConstraint combines a ProjectIdentifier with a Constraint. It
-// indicates that, if packages contained in the ProjectIdentifier enter the
-// depgraph, they must do so at a version that is allowed by the Constraint.
-type ProjectConstraint struct {
- Ident ProjectIdentifier
- Constraint Constraint
-}
-
func (i ProjectIdentifier) less(j ProjectIdentifier) bool {
if i.ProjectRoot < j.ProjectRoot {
return true
|
Func to mapify two []ProjectConstraint slices
Really just intended for root project's use.
|
sdboyer_gps
|
train
|
32af23b6eead8418d7e687775ccbf9280219406b
|
diff --git a/source/rafcon/core/start.py b/source/rafcon/core/start.py
index <HASH>..<HASH> 100755
--- a/source/rafcon/core/start.py
+++ b/source/rafcon/core/start.py
@@ -12,7 +12,7 @@
import os
import argparse
-from os.path import realpath, dirname, join, exists, isdir
+from os.path import realpath, dirname, join, exists
import signal
import time
from Queue import Empty
@@ -112,10 +112,7 @@ def setup_configuration(config_path):
:param config_path: Path to the core config file
"""
if config_path is not None:
- if isdir(config_path):
- config_file = None
- else:
- config_path, config_file = os.path.split(config_path)
+ config_path, config_file = filesystem.separate_folder_path_and_file_name(config_path)
global_config.load(config_file=config_file, path=config_path)
else:
global_config.load(path=config_path)
diff --git a/source/rafcon/gui/start.py b/source/rafcon/gui/start.py
index <HASH>..<HASH> 100755
--- a/source/rafcon/gui/start.py
+++ b/source/rafcon/gui/start.py
@@ -126,8 +126,10 @@ def setup_argument_parser():
def setup_mvc_configuration(core_config_path, gui_config_path, runtime_config_path):
setup_configuration(core_config_path)
- global_gui_config.load(gui_config_path)
- global_runtime_config.load(runtime_config_path)
+ gui_config_path, gui_config_file = filesystem.separate_folder_path_and_file_name(gui_config_path)
+ global_gui_config.load(gui_config_file, gui_config_path)
+ runtime_config_path, runtime_config_file = filesystem.separate_folder_path_and_file_name(runtime_config_path)
+ global_runtime_config.load(runtime_config_file, runtime_config_path)
def setup_gui():
diff --git a/source/rafcon/utils/filesystem.py b/source/rafcon/utils/filesystem.py
index <HASH>..<HASH> 100644
--- a/source/rafcon/utils/filesystem.py
+++ b/source/rafcon/utils/filesystem.py
@@ -103,3 +103,10 @@ def read_version_from_pt_file():
version = parts[1].strip()
return version
return 0
+
+
+def separate_folder_path_and_file_name(path):
+ if os.path.isdir(path):
+ return path, None
+ else:
+ return os.path.split(path)
|
fix config path in gui.start.setup_mvc_environment
- general support for folder path and file path as argument
- move function to separate folder path and file name if file path is handed to utils.filesystem
|
DLR-RM_RAFCON
|
train
|
1be477a6c7b6a93ef5a74a3df6b8ea28af3e2e32
|
diff --git a/lib/jss/composer.rb b/lib/jss/composer.rb
index <HASH>..<HASH> 100644
--- a/lib/jss/composer.rb
+++ b/lib/jss/composer.rb
@@ -147,7 +147,6 @@ module JSS
### now build the pkg
begin
- byebug
it_built = system "#{PKGBUILD} --identifier '#{pkg_id}' --version '#{version}' --ownership #{pkg_ownership} --install-location / --root '#{root}' #{signing} #{comp_plist_arg} '#{pkg_out}' "
raise 'There was an error building the .pkg' unless it_built
|
Removed debug insertion
Removed debug insertion
|
PixarAnimationStudios_ruby-jss
|
train
|
c6eaf6a68fc9fe6ecb2e5a772109dc1146e1f1c6
|
diff --git a/structr-core/src/main/java/org/structr/core/function/AbbrFunction.java b/structr-core/src/main/java/org/structr/core/function/AbbrFunction.java
index <HASH>..<HASH> 100644
--- a/structr-core/src/main/java/org/structr/core/function/AbbrFunction.java
+++ b/structr-core/src/main/java/org/structr/core/function/AbbrFunction.java
@@ -40,11 +40,18 @@ public class AbbrFunction extends Function<Object, Object> {
public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException {
try {
- if (!arrayHasLengthAndAllElementsNotNull(sources, 2)) {
-
+
+ if (sources == null || sources.length != 2 || sources[1] == null) {
+
+ logParameterError(entity, sources, ctx.isJavaScriptContext());
+ return usage(ctx.isJavaScriptContext());
+ }
+
+ if (sources[0] == null) {
+
return "";
}
-
+
int maxLength = Double.valueOf(sources[1].toString()).intValue();
if (sources[0].toString().length() > maxLength) {
|
Makes abbr() tolerant to null values (won't log an error anymore).
|
structr_structr
|
train
|
c3959cd6532d9455b3d686dc7caa3647c1f97776
|
diff --git a/cosmic_ray/commands/format.py b/cosmic_ray/commands/format.py
index <HASH>..<HASH> 100644
--- a/cosmic_ray/commands/format.py
+++ b/cosmic_ray/commands/format.py
@@ -73,13 +73,33 @@ def create_report(records, show_pending, full_report=False):
yield 'no jobs completed'
-def survival_rate(work_db):
- _, _, completed_jobs, kills = _base_stats(work_db)
+def survival_rate():
+ """cr-rate
+
+Usage: cr-rate
+
+Read JSON work-records from stdin and print the survival rate.
+"""
+ records = (WorkRecord(json.loads(line)) for line in sys.stdin)
+
+ total_jobs = 0
+ pending_jobs = 0
+ kills = 0
+ for item in records:
+ total_jobs += 1
+ if item.worker_outcome is None:
+ pending_jobs += 1
+ if is_killed(item):
+ kills += 1
+
+ completed_jobs = total_jobs - pending_jobs
if not completed_jobs:
- return 0
+ rate = 0
+ else:
+ rate = (1 - kills / completed_jobs) * 100
- return (1 - len(kills) / completed_jobs) * 100
+ print(rate)
def format():
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -106,6 +106,7 @@ setup(
'console_scripts': [
'cosmic-ray = cosmic_ray.cli:main',
'cr-format = cosmic_ray.commands.format:format',
+ 'cr-rate = cosmic_ray.commands.format:survival_rate',
],
'cosmic_ray.test_runners': [
'nose = cosmic_ray.testing.nose_runner:NoseRunner',
diff --git a/test_project/run_tests.sh b/test_project/run_tests.sh
index <HASH>..<HASH> 100644
--- a/test_project/run_tests.sh
+++ b/test_project/run_tests.sh
@@ -6,9 +6,9 @@ for CONFIG in $TEST_CONFIGS; do
echo $CONFIG
cosmic-ray load cosmic-ray.$CONFIG.conf
if [ $? != 0 ]; then exit 1; fi
- RESULT=`cosmic-ray survival-rate adam_tests.$CONFIG`
+ RESULT=`cosmic-ray dump adam_tests.$CONFIG | cr-rate`
if [ $RESULT != 0.00 ]; then
- cosmic-ray report adam_tests.$CONFIG
+ cosmic-ray dump adam_tests.$CONFIG | cr-report
exit 1
fi
done
@@ -16,18 +16,18 @@ done
# Run import tests
cosmic-ray load cosmic-ray.import.conf
if [ $? != 0 ]; then exit 1; fi
-RESULT=`cosmic-ray survival-rate import_tests`
+RESULT=`cosmic-ray dump import_tests | cr-rate`
if [ $RESULT != 0.00 ]; then
- cosmic-ray report import_tests
+ cosmic-ray dump import_tests | cr-report
exit 1
fi
# Run tests for empty __init__.py
cosmic-ray load cosmic-ray.empty.conf
if [ $? != 0 ]; then exit 1; fi
-RESULT=`cosmic-ray survival-rate empty.unittest`
+RESULT=`cosmic-ray dump empty.unittest | cr-rate`
if [ $RESULT != 0.00 ]; then
- cosmic-ray report empty.unittest
+ cosmic-ray dump empty.unittest | cr-report
exit 1
fi
|
WIP: Created new cr-rate command.
Also update travis config.
|
sixty-north_cosmic-ray
|
train
|
c286b03f26e368d149c32cc02d5ceee3da898f5a
|
diff --git a/src/main/java/com/semanticcms/openfile/servlet/OpenFile.java b/src/main/java/com/semanticcms/openfile/servlet/OpenFile.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/semanticcms/openfile/servlet/OpenFile.java
+++ b/src/main/java/com/semanticcms/openfile/servlet/OpenFile.java
@@ -1,6 +1,6 @@
/*
* semanticcms-openfile-servlet - SemanticCMS desktop integration mode for local content creation in a Servlet environment.
- * Copyright (C) 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021 AO Industries, Inc.
+ * Copyright (C) 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 AO Industries, Inc.
* support@aoindustries.com
* 7262 Bull Pen Cir
* Mobile, AL 36695
@@ -45,7 +45,7 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.SkipPageException;
-public abstract class OpenFile {
+public final class OpenFile {
/** Make no instances. */
private OpenFile() {throw new AssertionError();}
diff --git a/src/main/java/com/semanticcms/openfile/servlet/ajax/Maven.java b/src/main/java/com/semanticcms/openfile/servlet/ajax/Maven.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/semanticcms/openfile/servlet/ajax/Maven.java
+++ b/src/main/java/com/semanticcms/openfile/servlet/ajax/Maven.java
@@ -1,6 +1,6 @@
/*
* semanticcms-openfile-servlet - SemanticCMS desktop integration mode for local content creation in a Servlet environment.
- * Copyright (C) 2019, 2020, 2021 AO Industries, Inc.
+ * Copyright (C) 2019, 2020, 2021, 2022 AO Industries, Inc.
* support@aoindustries.com
* 7262 Bull Pen Cir
* Mobile, AL 36695
@@ -30,7 +30,7 @@ import java.util.Properties;
/**
* @author AO Industries, Inc.
*/
-abstract class Maven {
+final class Maven {
/** Make no instances. */
private Maven() {throw new AssertionError();}
|
Using final instead of abstract for static utility classes
NetBeans <I> is warning "Constructor is never used" when abstract, and
this cannot be suppressed with `@SuppressWarnings("unused")`.
|
aoindustries_semanticcms-openfile-servlet
|
train
|
ecc455ebb4d7e51ad37cf963f2f21c52d270b394
|
diff --git a/builtin/providers/aws/resource_aws_codedeploy_deployment_group.go b/builtin/providers/aws/resource_aws_codedeploy_deployment_group.go
index <HASH>..<HASH> 100644
--- a/builtin/providers/aws/resource_aws_codedeploy_deployment_group.go
+++ b/builtin/providers/aws/resource_aws_codedeploy_deployment_group.go
@@ -387,13 +387,13 @@ func ec2TagFiltersToMap(list []*codedeploy.EC2TagFilter) []map[string]string {
result := make([]map[string]string, 0, len(list))
for _, tf := range list {
l := make(map[string]string)
- if *tf.Key != "" {
+ if tf.Key != nil && *tf.Key != "" {
l["key"] = *tf.Key
}
- if *tf.Value != "" {
+ if tf.Value != nil && *tf.Value != "" {
l["value"] = *tf.Value
}
- if *tf.Type != "" {
+ if tf.Type != nil && *tf.Type != "" {
l["type"] = *tf.Type
}
result = append(result, l)
|
provider/aws: Guard against nil values in EC2 Tags
|
hashicorp_terraform
|
train
|
08c2f44e52d01573bf4cb1469de2119fb207c98c
|
diff --git a/promised-node-http.js b/promised-node-http.js
index <HASH>..<HASH> 100644
--- a/promised-node-http.js
+++ b/promised-node-http.js
@@ -20,7 +20,7 @@ define(function (require)
};
var maxRedirections = options.maxRedirections || 10;
-
+ try{
var req = http.request(options, function(res) {
response.status = res.statusCode;
response.headers = res.headers;
@@ -58,6 +58,7 @@ define(function (require)
});
res.on('error', function(e)
{
+ console.log("promised-node-http : error : ", error);
def.reject(e);
});
});
@@ -69,6 +70,13 @@ define(function (require)
if(datas)
req.write(JSON.stringify(datas));
req.end();
+
+ }
+ catch(e){
+ console.log("catche error in promised-node-http : error : ";, e);
+ if(!def.rejected)
+ def.reject(e);
+ }
return deep.promise(def);
}
return requester;
|
try catch strategy for avoiding rethrow that break autobahn
|
deepjs_autobahn
|
train
|
59a25a9dbd60d9d63d8e4ec637877d0ffac53b4b
|
diff --git a/lib/plugins/aws/deployFunction/index.js b/lib/plugins/aws/deployFunction/index.js
index <HASH>..<HASH> 100644
--- a/lib/plugins/aws/deployFunction/index.js
+++ b/lib/plugins/aws/deployFunction/index.js
@@ -66,9 +66,14 @@ class AwsDeployFunction {
}
deployFunction() {
- const artifactFileName = this.provider.naming
- .getFunctionArtifactName(this.options.function);
- const artifactFilePath = path.join(this.packagePath, artifactFileName);
+ const functionObject = this.serverless.service.getFunction(this.options.function);
+ let artifactFilePath = functionObject.artifact;
+ // if function artifact is not provided, derive the default artifact path
+ if (!artifactFilePath) {
+ const artifactFileName = this.provider.naming
+ .getFunctionArtifactName(this.options.function);
+ artifactFilePath = path.join(this.packagePath, artifactFileName);
+ }
const data = fs.readFileSync(artifactFilePath);
const params = {
diff --git a/lib/plugins/package/lib/packageService.js b/lib/plugins/package/lib/packageService.js
index <HASH>..<HASH> 100644
--- a/lib/plugins/package/lib/packageService.js
+++ b/lib/plugins/package/lib/packageService.js
@@ -1,6 +1,7 @@
'use strict';
const BbPromise = require('bluebird');
+const path = require('path');
const _ = require('lodash');
module.exports = {
@@ -70,6 +71,13 @@ module.exports = {
const functionObject = this.serverless.service.getFunction(functionName);
const funcPackageConfig = functionObject.package || {};
+ // use the artifact in function config if provided
+ if (funcPackageConfig.artifact) {
+ const filePath = path.join(this.serverless.config.servicePath, funcPackageConfig.artifact);
+ functionObject.artifact = filePath;
+ return filePath;
+ }
+
const exclude = this.getExcludes(funcPackageConfig.exclude);
const include = this.getIncludes(funcPackageConfig.include);
const zipFileName = `${functionName}.zip`;
|
Add function artifact check in deployFunction
- Adds check for function package artifact in packageFunction() and
avoids packing if a package artifact is found.
- Adds check for function artifact in deployFunction() and use the
provided artifact to deploy if available.
|
serverless_serverless
|
train
|
1e0968f02db314f9826a5008bada5e3434613952
|
diff --git a/lib/undercover/changeset.rb b/lib/undercover/changeset.rb
index <HASH>..<HASH> 100644
--- a/lib/undercover/changeset.rb
+++ b/lib/undercover/changeset.rb
@@ -73,7 +73,7 @@ module Undercover
def compare_base_obj
return nil unless compare_base
- repo.lookup(repo.merge_base(compare_base.to_s, head))
+ repo.rev_parse(compare_base.to_s)
end
def head
diff --git a/spec/changeset_spec.rb b/spec/changeset_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/changeset_spec.rb
+++ b/spec/changeset_spec.rb
@@ -24,7 +24,7 @@ describe Undercover::Changeset do
expect(changeset.file_paths).to eq(
%w[file_one file_three file_two staged_file]
)
- expect(changeset.files['file_two']).to eq([7, 10, 11])
+ expect(changeset.files['file_two']).to eq([4, 7, 10, 11])
expect(changeset.files['file_three']).to eq([1, 2, 3, 4, 5, 6])
end
|
simplify and correct compare_base_obj
|
grodowski_undercover
|
train
|
fb00fc8a041f01ce97b47ab0281bf76eed5c1a89
|
diff --git a/pybar/daq/readout_utils.py b/pybar/daq/readout_utils.py
index <HASH>..<HASH> 100644
--- a/pybar/daq/readout_utils.py
+++ b/pybar/daq/readout_utils.py
@@ -232,7 +232,7 @@ def logical_xor(f1, f2): # function factory
def is_trigger_word(value):
- return np.greater_equal(value, 0x80000000)
+ return np.equal(np.bitwise_and(value, 0x80000000), 0x80000000)
def is_tdc_word(value):
|
ENH: change selection of trigger words
|
SiLab-Bonn_pyBAR
|
train
|
3b5092ca6b1f9293f566bd7431287695565ab0d6
|
diff --git a/lib/Vespolina/Cart/Manager/CartManager.php b/lib/Vespolina/Cart/Manager/CartManager.php
index <HASH>..<HASH> 100644
--- a/lib/Vespolina/Cart/Manager/CartManager.php
+++ b/lib/Vespolina/Cart/Manager/CartManager.php
@@ -19,9 +19,7 @@ use Vespolina\Entity\Order\CartInterface;
use Vespolina\Entity\Order\ItemInterface;
use Vespolina\Entity\Order\OrderInterface;
use Vespolina\Entity\ProductInterface;
-use Vespolina\Entity\OrderInterface;
-use Vespolina\CartBundle\Model\CartManagerInterface;
-use Vespolina\CartBundle\Pricing\CartPricingProviderInterface;
+use Vespolina\EventDispatcher\NullDispatcher;
/**
* @author Daniel Kucharski <daniel@xerias.be>
@@ -31,14 +29,17 @@ class CartManager implements CartManagerInterface
{
protected $cartClass;
protected $cartItemClass;
- protected $dispatcher;
+ protected $eventDispatcher;
protected $pricingProvider;
- // todo: $recurringInterface should be handled in a handler
- function __construct(CartPricingProviderInterface $pricingProvider, $cartClass, $cartItemClass, $recurringInterface = 'Vespolina\ProductSubscriptionBundle\Model\RecurringInterface')
+ function __construct(CartPricingProviderInterface $pricingProvider, $cartClass, $cartItemClass, EventDispatcherInterface $eventDispatcher = null)
{
+ if (!$eventDispatcher) {
+ $eventDispatcher = new NullDispatcher();
+ }
$this->cartClass = $cartClass;
$this->cartItemClass = $cartItemClass;
+ $this->eventDispatcher = $eventDispatcher;
$this->pricingProvider = $pricingProvider;
}
|
update CartManager to use NullDispatcher
|
vespolina_commerce
|
train
|
2a9d1abf6f40525a514326cf12465767b1224716
|
diff --git a/conllu/tree_helpers.py b/conllu/tree_helpers.py
index <HASH>..<HASH> 100644
--- a/conllu/tree_helpers.py
+++ b/conllu/tree_helpers.py
@@ -1,3 +1,4 @@
+from __future__ import print_function, unicode_literals
from collections import namedtuple
TreeNode = namedtuple('TreeNode', ['data', 'children'])
@@ -9,12 +10,14 @@ def create_tree(node_children_mapping, start=0):
]
return subtree
-def print_tree(tree, depth=0):
- for child in tree.children:
- print "\t" * depth + "(deprel:{deprel}) form:{form}, tag:{tag} [{idx}]".format(
- deprel=child.data["deprel"],
- form=child.data["form"],
- tag=child.data["upostag"],
- idx=child.data["id"],
- )
- print_tree(child.children, depth + 1)
+def print_tree(node, depth=0):
+ assert isinstance(node, TreeNode), "node not TreeNode %s" % type(node)
+
+ print("\t" * depth + "(deprel:{deprel}) form:{form}, tag:{tag} [{idx}]".format(
+ deprel=node.data["deprel"],
+ form=node.data["form"],
+ tag=node.data["upostag"],
+ idx=node.data["id"],
+ ))
+ for child in node.children:
+ print_tree(child, depth + 1)
|
Simplify print_tree usage.
|
EmilStenstrom_conllu
|
train
|
c7fa8e575ae9e638432594045cd6ca57af414f9e
|
diff --git a/src/OAuth/OAuthRequest.php b/src/OAuth/OAuthRequest.php
index <HASH>..<HASH> 100644
--- a/src/OAuth/OAuthRequest.php
+++ b/src/OAuth/OAuthRequest.php
@@ -49,17 +49,8 @@ class OAuthRequest {
// Parse the query-string to find GET parameters
$parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
- $ourpost = $_POST;
- // Deal with magic_quotes
- // http://www.php.net/manual/en/security.magicquotes.disabling.php
- if ( get_magic_quotes_gpc() ) {
- $ourpost = array();
- foreach ($_POST as $k => $v) {
- $ourpost[$k] = $v;
- }
- }
- // Add POST Parameters if they exist
- $parameters = array_merge($parameters, $ourpost);
+ // Add POST Parameters if they exist
+ $parameters = array_merge($parameters, $_POST);
// We have a Authorization-header with OAuth data. Parse the header
// and add those overriding any duplicates from GET or POST
|
Remove any reference to gpc_magic_quotes
|
tsugiproject_tsugi-php
|
train
|
82296f8d722695ab006d94bb87cf2896ccb4cba8
|
diff --git a/src/vizceral.js b/src/vizceral.js
index <HASH>..<HASH> 100644
--- a/src/vizceral.js
+++ b/src/vizceral.js
@@ -395,12 +395,11 @@ class Vizceral extends EventEmitter {
} else if (difference === 1) {
this.zoomIntoNode(newGraph.name);
} else {
- this.selectGraph(newGraph);
+ this.selectGraph(newGraph, redirectedFrom);
}
this.currentView = newView;
this.calculateMouseOver();
- this.emit('viewChanged', { view: this.currentView, graph: this.currentGraph, redirectedFrom: redirectedFrom });
}
// If passed in an object to highlight, try to highlight.
@@ -505,10 +504,12 @@ class Vizceral extends EventEmitter {
Object.assign(this.renderers, renderers);
}
- setCurrentGraph (graph) {
+ setCurrentGraph (graph, redirectedFrom) {
graph.setFilters(this.filters);
this.currentGraph = graph;
this.currentGraph.setCurrent(true);
+
+ this.emit('viewChanged', { view: this.currentView, graph: this.currentGraph, redirectedFrom: redirectedFrom });
}
// Only necessary when global graph is present
@@ -615,13 +616,13 @@ class Vizceral extends EventEmitter {
}
// Needed for all graphs
- selectGraph (graph) {
+ selectGraph (graph, redirectedFrom) {
if (this.currentGraph !== undefined) {
this.scene.remove(this.currentGraph.getView().container);
this.currentGraph.setCurrent(false);
}
this.scene.add(graph.view.container);
- this.setCurrentGraph(graph);
+ this.setCurrentGraph(graph, redirectedFrom);
}
calculateMouseOver (immediate) {
|
Fix when to emit when the view changed, and the data contained in the update message.
|
Netflix_vizceral
|
train
|
adeea15b0a0e824587b61a5e3d6cb9f75f281918
|
diff --git a/quilt/db.py b/quilt/db.py
index <HASH>..<HASH> 100644
--- a/quilt/db.py
+++ b/quilt/db.py
@@ -133,7 +133,7 @@ class PatchSeries(object):
""" Saves current patches list in the series file """
with open(self.series_file, "w") as f:
for patchline in self.patchlines:
- f.write(patchline)
+ f.write(str(patchline))
def add_patch(self, patch):
""" Add a patch to the patches list """
|
Fix writing series file
The string representation of PatchLine must be written to the series
file.
|
bjoernricks_python-quilt
|
train
|
8eca1eaf7ecba7131e0525b7ae43f6678653f956
|
diff --git a/src/main/java/hu/kazocsaba/imageviewer/ImageComponent.java b/src/main/java/hu/kazocsaba/imageviewer/ImageComponent.java
index <HASH>..<HASH> 100644
--- a/src/main/java/hu/kazocsaba/imageviewer/ImageComponent.java
+++ b/src/main/java/hu/kazocsaba/imageviewer/ImageComponent.java
@@ -467,7 +467,12 @@ class ImageComponent extends JComponent {
* changed where the cursor is relative to the image.
*/
private void correctionalFire() {
- handleMouseAt(ImageComponent.this.getMousePosition(), null);
+ /**
+ * We use our parent, LayeredImageView, to locate the mouse. If the viewer has an overlay, then
+ * ImageComponent.getMousePosition will return null because the mouse is over the overlay and not the image
+ * component.
+ */
+ handleMouseAt(getParent().getMousePosition(true), null);
}
private void fireMouseAtPixel(int x, int y, MouseEvent ev) {
|
Fix synthetic mouse events when image has overlay.
Due to the presence of the overlay, the code used to think that the mouse exited the component because getMousePosition returned null for the image component. (The overlay basically covered up the image.) Now we use the parent container (which contains the image and all the overlays) to find the mouse cursor.
|
kazocsaba_imageviewer
|
train
|
bdbb331847e081e67264cad64c2b354666bea162
|
diff --git a/lib/Cake/Database/Schema/Table.php b/lib/Cake/Database/Schema/Table.php
index <HASH>..<HASH> 100644
--- a/lib/Cake/Database/Schema/Table.php
+++ b/lib/Cake/Database/Schema/Table.php
@@ -210,4 +210,32 @@ class Table {
return array_keys($this->_indexes);
}
+/**
+ * Read information about an index based on name.
+ *
+ * @param string $name The name of the index.
+ * @return array|null Array of index data, or null
+ */
+ public function index($name) {
+ if (!isset($this->_indexes[$name])) {
+ return null;
+ }
+ return $this->_indexes[$name];
+ }
+
+/**
+ * Get the column(s) used for the primary key.
+ *
+ * @return array|null Column name(s) for the primary key.
+ * Null will be returned if a table has no primary key.
+ */
+ public function primaryKey() {
+ foreach ($this->_indexes as $name => $data) {
+ if ($data['type'] === self::INDEX_PRIMARY) {
+ return $data['columns'];
+ }
+ }
+ return null;
+ }
+
}
diff --git a/lib/Cake/Test/TestCase/Database/Schema/TableTest.php b/lib/Cake/Test/TestCase/Database/Schema/TableTest.php
index <HASH>..<HASH> 100644
--- a/lib/Cake/Test/TestCase/Database/Schema/TableTest.php
+++ b/lib/Cake/Test/TestCase/Database/Schema/TableTest.php
@@ -119,6 +119,7 @@ class TableTest extends TestCase {
'columns' => ['author_id']
]);
}
+
/**
* Test that exceptions are raised when indexes
* are added with invalid types
@@ -142,13 +143,42 @@ class TableTest extends TestCase {
*/
public function testAddIndexTypes() {
$table = new Table('articles');
- $table->addColumn('title', 'string')
+ $table->addColumn('id', 'integer')
+ ->addColumn('title', 'string')
->addColumn('author_id', 'integer');
$table->addIndex('author_idx', [
- 'fields' => ['author_id'],
+ 'columns' => ['author_id'],
'type' => 'unique'
- ]);
+ ])->addIndex('primary', [
+ 'type' => 'primary',
+ 'columns' => ['id']
+ ]);
+
+ $this->assertEquals(
+ ['author_idx', 'primary'],
+ $table->indexes()
+ );
+ }
+
+/**
+ * Test getting the primary key.
+ *
+ * @return void
+ */
+ public function testPrimaryKey() {
+ $table = new Table('articles');
+ $table->addColumn('id', 'integer')
+ ->addColumn('title', 'string')
+ ->addColumn('author_id', 'integer')
+ ->addIndex('author_idx', [
+ 'columns' => ['author_id'],
+ 'type' => 'unique'
+ ])->addIndex('primary', [
+ 'type' => 'primary',
+ 'columns' => ['id']
+ ]);
+ $this->assertEquals(['id'], $table->primaryKey());
}
}
|
Add Table::primaryKey()
Since we often need easy access to the columns in a table's primary
key make that easy to get with a simple method.
|
cakephp_cakephp
|
train
|
ba0f79476fdeac9dbcad3987c6c791f1e95b722f
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -3,6 +3,7 @@
from setuptools import setup
import os
+
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
@@ -27,6 +28,7 @@ setup(name='tmc',
],
install_requires=[
"requests == 2.2.1",
- "argh == 0.24.1"
+ "argh == 0.24.1",
+ "peewee == 2.2.5"
],
-)
+ )
diff --git a/tmc/Files.py b/tmc/Files.py
index <HASH>..<HASH> 100644
--- a/tmc/Files.py
+++ b/tmc/Files.py
@@ -18,8 +18,13 @@ class Files:
exercise = tmc.db.get_exercise(id)
course = tmc.db.get_course(exercise["course_id"])
outpath = os.path.join(course["path"])
+ realoutpath = os.path.join(course["path"],
+ "/".join(exercise["name"].split("-")))
print("{0}exercises/{1}.zip -> {2}".format(
- tmc.api.server_url, exercise["id"], outpath))
+ tmc.api.server_url, exercise["id"], realoutpath))
+ if os.path.isdir(realoutpath):
+ print("Already downloaded, skipping.")
+ return
@tmc.Spinner.SpinnerDecorator("Done!")
def inner(id):
@@ -69,8 +74,8 @@ class Files:
def test(self, id):
exercise = tmc.db.get_exercise(id)
course = tmc.db.get_course(exercise["course_id"])
- outpath = os.path.join(
- course["path"], "/".join(exercise["name"].split("-")))
+ outpath = os.path.join(course["path"],
+ "/".join(exercise["name"].split("-")))
print("testing {0}".format(outpath))
if not os.path.isdir(outpath):
raise Exception("That exercise is not downloaded!")
diff --git a/tmc/__main__.py b/tmc/__main__.py
index <HASH>..<HASH> 100644
--- a/tmc/__main__.py
+++ b/tmc/__main__.py
@@ -19,8 +19,10 @@ def needs_a_course(func):
return inner
+@aliases("reset")
def resetdb():
- tmc.db.reset()
+ if tmc.Prompt.prompt_yn("Reset database", False):
+ tmc.db.reset()
@aliases("up")
@@ -46,11 +48,13 @@ def updatecourses():
@aliases("dl")
@needs_a_course
-def download(what):
+def download(what="all"):
what = what.upper()
if what == "ALL":
for exercise in tmc.db.get_exercises():
tmc.files.download_file(exercise["id"])
+ else:
+ tmc.files.download_file(int(what))
@aliases("te")
@@ -83,7 +87,7 @@ def submit(what=None):
@aliases("sel")
def select(what):
what = what.upper()
- if what == "COURSE":
+ if what == "COURSE" or what == "C":
og = tmc.db.selected_course()
start_index = 0
if og is not None:
@@ -95,11 +99,12 @@ def select(what):
update()
if tmc.db.selected_course()["path"] == "":
selpath()
- return True
+ next()
+ return
else:
print("You can select the course with `tmc select course`")
- return False
- elif what == "EXERCISE":
+ return
+ else:
og = tmc.db.selected_exercise()
start_index = 0
if og is not None:
@@ -108,7 +113,8 @@ def select(what):
"Select a exercise", tmc.db.get_exercises(), start_index)
if ret != -1:
tmc.db.select_exercise(ret)
- return True
+ print("Selected {}: {}".format(
+ ret, tmc.db.selected_exercise()["name"]))
@needs_a_course
@@ -152,9 +158,10 @@ def bts(val):
def btc(val):
- return "✔" if val == 1 else "✘"
+ return "\033[32m✔\033[0m" if val == 1 else "\033[31m✘\033[0m"
+@aliases("init")
@aliases("conf")
def configure():
if tmc.db.hasconf():
@@ -169,11 +176,12 @@ def configure():
username = input("Username: ")
password = getpass.getpass("Password: ")
# wow, such security
- token = base64.b64encode(
- bytes("{0}:{1}".format(username, password), 'utf-8')).decode("utf-8")
+ token = base64.b64encode(bytes("{0}:{1}".format(username, password),
+ 'utf-8')).decode("utf-8")
try:
tmc.api.configure(server, token)
- except Exception: # ToDo: Better exception
+ except Exception as e: # ToDo: Better exception
+ print(e)
if tmc.Prompt.prompt_yn("Retry authentication", True):
continue
exit()
|
better error message when configuration fails, won't override downloads
|
minttu_tmc.py
|
train
|
4b5c05c4e7482557eb16dcc1281981214ea27d08
|
diff --git a/graphcommons.py b/graphcommons.py
index <HASH>..<HASH> 100644
--- a/graphcommons.py
+++ b/graphcommons.py
@@ -119,6 +119,23 @@ class Graph(Entity):
def edges_to(self, node):
return self.edges_for(node, 'to')
+ def sync(self, graph_commons):
+ """Synchronize local and remote representations."""
+ if self['id'] is None:
+ return {}
+
+ remote_graph = graph_commons.graphs(self['id'])
+
+ # TODO: less forceful, more elegant
+ self.edges = remote_graph.edges
+ self.nodes = remote_graph.nodes
+ self.node_types = remote_graph.node_types
+ self.edge_types = remote_graph.edge_types
+ self._edges = dict((edge.id, edge) for edge in self.edges)
+ self._nodes = dict((node.id, node) for node in self.nodes)
+ self._node_types = dict((t.id, t) for t in self.node_types)
+ self._edge_types = dict((t.id, t) for t in self.edge_types)
+
class GraphCommonsException(Exception):
def __init__(self, status_code, message):
|
First pass at Graph.sync()
|
graphcommons_graphcommons-python
|
train
|
b2badf9b93ec82daea9f9fdbc16729e8ab9aa793
|
diff --git a/lib/build/webpack-config.js b/lib/build/webpack-config.js
index <HASH>..<HASH> 100644
--- a/lib/build/webpack-config.js
+++ b/lib/build/webpack-config.js
@@ -217,7 +217,7 @@ module.exports = function (cfg) {
}
: undefined,
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
- chunksSortMode: cfg.ctx.prod ? 'dependency' : 'none',
+ chunksSortMode: 'none',
// inject script tags for bundle
inject: true,
|
experiment: fix Cyclic error within html-webpack-plugin when using with Webpack 4
|
quasarframework_quasar-cli
|
train
|
d52b2e6d6331d31242ecc2599e00f2614523d3f7
|
diff --git a/product_files.go b/product_files.go
index <HASH>..<HASH> 100644
--- a/product_files.go
+++ b/product_files.go
@@ -233,7 +233,6 @@ func (p ProductFilesService) Update(productSlug string, productFile ProductFile)
body := createUpdateProductFileBody{
ProductFile: ProductFile{
Description: productFile.Description,
- FileType: productFile.FileType,
FileVersion: productFile.FileVersion,
MD5: productFile.MD5,
Name: productFile.Name,
diff --git a/product_files_test.go b/product_files_test.go
index <HASH>..<HASH> 100644
--- a/product_files_test.go
+++ b/product_files_test.go
@@ -581,7 +581,6 @@ var _ = Describe("PivnetClient - product files", func() {
ID: 1234,
Description: "some-description",
FileVersion: "some-file-version",
- FileType: "some-file-type",
MD5: "some-md5",
Name: "some-file-name",
}
@@ -589,7 +588,6 @@ var _ = Describe("PivnetClient - product files", func() {
expectedRequestBody = requestBody{
ProductFile: pivnet.ProductFile{
Description: productFile.Description,
- FileType: productFile.FileType,
FileVersion: productFile.FileVersion,
MD5: productFile.MD5,
Name: productFile.Name,
|
Remove ability to update file type on product file.
- pivnet no longer supports it.
[#<I>]
|
pivotal-cf_go-pivnet
|
train
|
d8d7defaa24f28d6e944e4c25478080fa2ca5aa2
|
diff --git a/mindmaps-graql/src/main/java/io/mindmaps/graql/internal/pattern/property/RelationProperty.java b/mindmaps-graql/src/main/java/io/mindmaps/graql/internal/pattern/property/RelationProperty.java
index <HASH>..<HASH> 100644
--- a/mindmaps-graql/src/main/java/io/mindmaps/graql/internal/pattern/property/RelationProperty.java
+++ b/mindmaps-graql/src/main/java/io/mindmaps/graql/internal/pattern/property/RelationProperty.java
@@ -19,6 +19,7 @@
package io.mindmaps.graql.internal.pattern.property;
import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Sets;
import io.mindmaps.MindmapsGraph;
import io.mindmaps.concept.*;
import io.mindmaps.graql.admin.UniqueVarProperty;
@@ -38,6 +39,7 @@ import static io.mindmaps.graql.internal.gremlin.FragmentPriority.DISTINCT_CASTI
import static io.mindmaps.graql.internal.gremlin.FragmentPriority.EDGE_BOUNDED;
import static io.mindmaps.graql.internal.gremlin.FragmentPriority.EDGE_UNBOUNDED;
import static io.mindmaps.graql.internal.gremlin.FragmentPriority.EDGE_UNIQUE;
+import static io.mindmaps.graql.internal.util.CommonUtil.toImmutableSet;
import static io.mindmaps.util.Schema.EdgeLabel.CASTING;
import static io.mindmaps.util.Schema.EdgeLabel.ISA;
import static io.mindmaps.util.Schema.EdgeLabel.ROLE_PLAYER;
@@ -85,19 +87,22 @@ public class RelationProperty extends AbstractVarProperty implements UniqueVarPr
public Collection<MultiTraversal> match(String start) {
Collection<String> castingNames = new HashSet<>();
- Stream<MultiTraversal> traversals = castings.stream().flatMap(casting -> {
+ ImmutableSet<MultiTraversal> traversals = castings.stream().flatMap(casting -> {
String castingName = UUID.randomUUID().toString();
castingNames.add(castingName);
return multiTraversalsFromCasting(start, castingName, casting);
- });
+ }).collect(toImmutableSet());
- Stream<MultiTraversal> distinctCastingTraversals = castingNames.stream().flatMap(
- castingName -> castingNames.stream().map(otherName -> makeDistinctCastingPattern(castingName, otherName))
- );
+ ImmutableSet<MultiTraversal> distinctCastingTraversals = castingNames.stream().flatMap(
+ castingName -> castingNames.stream()
+ .filter(otherName -> !otherName.equals(castingName))
+ .map(otherName -> makeDistinctCastingPattern(castingName, otherName)
+ )
+ ).collect(toImmutableSet());
- return Stream.concat(traversals, distinctCastingTraversals).collect(toSet());
+ return Sets.union(traversals, distinctCastingTraversals);
}
@Override
diff --git a/mindmaps-graql/src/test/java/io/mindmaps/graql/query/MatchQueryTest.java b/mindmaps-graql/src/test/java/io/mindmaps/graql/query/MatchQueryTest.java
index <HASH>..<HASH> 100644
--- a/mindmaps-graql/src/test/java/io/mindmaps/graql/query/MatchQueryTest.java
+++ b/mindmaps-graql/src/test/java/io/mindmaps/graql/query/MatchQueryTest.java
@@ -60,6 +60,7 @@ import static io.mindmaps.util.Schema.MetaType.RULE_TYPE;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
@SuppressWarnings("OptionalGetWithoutIsPresent")
@@ -485,6 +486,21 @@ public class MatchQueryTest {
assertEquals(list, query.parallelStream().collect(toList()));
}
+ @Test
+ public void testDistinctRoleplayers() {
+ MatchQuery query = qb.match(var().rel("x").rel("y").rel("z").isa("has-cast"));
+
+ assertNotEquals(0, query.stream().count());
+
+ // Make sure none of the resulting relationships have 3 role-players all the same
+ query.forEach(result -> {
+ Concept x = result.get("x");
+ Concept y = result.get("y");
+ Concept z = result.get("z");
+ assertFalse(x + " = " + y + " = " + z, x.equals(y) && x.equals(z));
+ });
+ }
+
@Test(expected = IllegalArgumentException.class)
public void testMatchEmpty() {
qb.match().execute();
|
FIx bug where roleplayers were not distinct (#<I>)
|
graknlabs_grakn
|
train
|
92a7feebd51b999f88d9d5648e3f26c57ef5c377
|
diff --git a/scriptcwl/library.py b/scriptcwl/library.py
index <HASH>..<HASH> 100644
--- a/scriptcwl/library.py
+++ b/scriptcwl/library.py
@@ -21,6 +21,22 @@ class StepsLibrary(object):
def get_step(self, name):
return self.steps.get(name)
+ def list_steps(self):
+ steps = []
+ workflows = []
+ template = u' {:.<25} {}'
+ for name, step in self.steps.items():
+ if step.is_workflow:
+ workflows.append(template.format(name, step))
+ else:
+ steps.append(template.format(name, step))
+
+ steps.sort()
+ workflows.sort()
+ result = [u'Steps\n', u'\n'.join(steps), u'\n\nWorkflows\n',
+ u'\n'.join(workflows)]
+ return u''.join(result)
+
def name_in_workflow(iri):
"""Extract the name of a step in a subworkflow.
diff --git a/scriptcwl/workflow.py b/scriptcwl/workflow.py
index <HASH>..<HASH> 100644
--- a/scriptcwl/workflow.py
+++ b/scriptcwl/workflow.py
@@ -171,20 +171,7 @@ class WorkflowGenerator(object):
"""
self._closed()
- steps = []
- workflows = []
- template = u' {:.<25} {}'
- for name, step in self.steps_library.items():
- if step.is_workflow:
- workflows.append(template.format(name, step))
- else:
- steps.append(template.format(name, step))
-
- steps.sort()
- workflows.sort()
- result = [u'Steps\n', u'\n'.join(steps), u'\n\nWorkflows\n',
- u'\n'.join(workflows)]
- return u''.join(result)
+ return self.steps_library.list_steps()
def _has_requirements(self):
"""Returns True if the workflow needs a requirements section.
|
Fix wf.list_steps()
Moved it to the StepsLibrary class.
|
NLeSC_scriptcwl
|
train
|
05580623a2574bb32b765ff16d6bc638ea5064ad
|
diff --git a/lib/validates_formatting_of/version.rb b/lib/validates_formatting_of/version.rb
index <HASH>..<HASH> 100644
--- a/lib/validates_formatting_of/version.rb
+++ b/lib/validates_formatting_of/version.rb
@@ -1,3 +1,3 @@
module ValidatesFormattingOf
- VERSION = "0.3.5.alpha"
+ VERSION = "0.3.5"
end
|
Bumped to version <I>
|
mdespuits_validates_formatting_of
|
train
|
71f4974ead243bdabd7178a5a6ac76de24c62be4
|
diff --git a/lib/rack/raw_upload.rb b/lib/rack/raw_upload.rb
index <HASH>..<HASH> 100644
--- a/lib/rack/raw_upload.rb
+++ b/lib/rack/raw_upload.rb
@@ -3,7 +3,7 @@ require 'tmpdir' # Needed in 1.8.7 to access Dir::tmpdir
module Rack
class RawUpload
- VERSION = '1.0.3'
+ VERSION = '1.0.4'
def initialize(app, opts = {})
@app = app
|
Forgot to change the version here...
|
New-Bamboo_rack-raw-upload
|
train
|
897ce0fb5067f277568a0cbaf78ee161a63e3a79
|
diff --git a/LeanMapper/Result.php b/LeanMapper/Result.php
index <HASH>..<HASH> 100644
--- a/LeanMapper/Result.php
+++ b/LeanMapper/Result.php
@@ -386,11 +386,15 @@ class Result implements \Iterator
$viaColumn = $this->mapper->getRelationshipColumn($table, $this->table);
}
$originKey = $referencingResult->getOriginKey();
- if (!isset($this->index[$originKey][$id])) {
+ if (!isset($this->index[$originKey])) {
+ $this->index[$originKey] = array();
foreach ($referencingResult as $key => $row) {
$this->index[$originKey][$row[$viaColumn]][] = new Row($referencingResult, $key);
}
}
+ if (!isset($this->index[$originKey][$id])) {
+ return array();
+ }
return $this->index[$originKey][$id];
}
|
Fixed issue with missing index initialization (thx to peter.z)
|
Tharos_LeanMapper
|
train
|
23255e533825d062fb5cf44977f335fe0776b289
|
diff --git a/lib/codelog/command/new.rb b/lib/codelog/command/new.rb
index <HASH>..<HASH> 100644
--- a/lib/codelog/command/new.rb
+++ b/lib/codelog/command/new.rb
@@ -11,7 +11,7 @@ module Codelog
end
def self.run(name, options)
- Codelog::Command::New.new(name, options).run
+ new(name, options).run
end
def run
|
Remove explict class name from method calling
|
codus_codelog
|
train
|
6e1ee03458f9ac81b9096f612da7b4904ea1e6df
|
diff --git a/src/Pingpong/Twitter/Twitter.php b/src/Pingpong/Twitter/Twitter.php
index <HASH>..<HASH> 100644
--- a/src/Pingpong/Twitter/Twitter.php
+++ b/src/Pingpong/Twitter/Twitter.php
@@ -478,7 +478,7 @@ class Twitter {
*/
public function getFallbackUrl()
{
- return $this->config->get("twitter::fallback_url");
+ return $this->fallbackUrl ?: $this->config->get("twitter::fallback_url");
}
/**
|
Allow get fallbackUrl from current instance
|
pingpong-labs_twitter
|
train
|
ac185fcc5bc74eb0f71ecf2e23cd83f557b22795
|
diff --git a/system/modules/generalDriver/DcGeneral/Panel/DefaultFilterElement.php b/system/modules/generalDriver/DcGeneral/Panel/DefaultFilterElement.php
index <HASH>..<HASH> 100644
--- a/system/modules/generalDriver/DcGeneral/Panel/DefaultFilterElement.php
+++ b/system/modules/generalDriver/DcGeneral/Panel/DefaultFilterElement.php
@@ -166,7 +166,7 @@ class DefaultFilterElement extends AbstractElement implements FilterElementInter
*/
public function render(ViewTemplateInterface $objTemplate)
{
- $arrLabel = $this->getEnvironment()->getDataDefinition()->getProperty($this->getPropertyName())->getName();
+ $arrLabel = $this->getEnvironment()->getDataDefinition()->getPropertiesSection()->getProperty($this->getPropertyName())->getName();
$arrOptions = array(
array(
diff --git a/system/modules/generalDriver/DcGeneral/Panel/DefaultSearchElement.php b/system/modules/generalDriver/DcGeneral/Panel/DefaultSearchElement.php
index <HASH>..<HASH> 100644
--- a/system/modules/generalDriver/DcGeneral/Panel/DefaultSearchElement.php
+++ b/system/modules/generalDriver/DcGeneral/Panel/DefaultSearchElement.php
@@ -151,7 +151,7 @@ class DefaultSearchElement extends AbstractElement implements SearchElementInter
foreach ($this->getPropertyNames() as $field)
{
- $arrLabel = $this->getEnvironment()->getDataDefinition()->getProperty($field)->getLabel();
+ $arrLabel = $this->getEnvironment()->getDataDefinition()->getPropertiesSection()->getProperty($field)->getLabel();
$arrOptions[] = array
(
'value' => $field,
diff --git a/system/modules/generalDriver/DcGeneral/Panel/DefaultSortElement.php b/system/modules/generalDriver/DcGeneral/Panel/DefaultSortElement.php
index <HASH>..<HASH> 100644
--- a/system/modules/generalDriver/DcGeneral/Panel/DefaultSortElement.php
+++ b/system/modules/generalDriver/DcGeneral/Panel/DefaultSortElement.php
@@ -188,7 +188,7 @@ class DefaultSortElement extends AbstractElement implements SortElementInterface
{
foreach ($this->getPropertyNames() as $field)
{
- $arrLabel = $this->getEnvironment()->getDataDefinition()->getProperty($field)->getLabel();
+ $arrLabel = $this->getEnvironment()->getDataDefinition()->getPropertiesSection()->getProperty($field)->getLabel();
$arrOptions[] = array(
'value' => specialchars($field),
|
Refactoring: Panel elements now use the PropertySection.
|
contao-community-alliance_dc-general
|
train
|
f7c0bf86215496a3e8aec04d95988af5f85e29b4
|
diff --git a/optalg/opt_solver/inlp.py b/optalg/opt_solver/inlp.py
index <HASH>..<HASH> 100644
--- a/optalg/opt_solver/inlp.py
+++ b/optalg/opt_solver/inlp.py
@@ -127,7 +127,7 @@ class OptSolverINLP(OptSolver):
# Header
if not quiet:
- print('\nSolver: INLP')
+ print('\nSolver: inlp')
print('------------')
# Outer
@@ -258,7 +258,10 @@ class OptSolverINLP(OptSolver):
assert(np.all(self.pi > 0))
except AssertionError:
raise OptSolverError_Infeasibility(self)
-
+
+ # Update iters
+ self.k += 1
+
def extract_components(self,y):
n = self.n
|
cleaned up output and iter cout of inlp
|
ttinoco_OPTALG
|
train
|
a39e47d1a246a55660dd86ee64e9b21f4a7d0bd2
|
diff --git a/js/fcoin.js b/js/fcoin.js
index <HASH>..<HASH> 100644
--- a/js/fcoin.js
+++ b/js/fcoin.js
@@ -231,32 +231,34 @@ module.exports = class fcoin extends Exchange {
}
parseTicker (ticker, market = undefined) {
- let timestamp = this.nonce (); // better to use server time, but fcoin server response 'seq'
+ let timestamp = undefined;
let symbol = undefined;
+ if (typeof market === 'undefined') {
+ symbol = market['symbol'];
+ } else {
+ let tickerType = this.safeString (ticker, 'type');
+ if (typeof tickerType !== 'undefined') {
+ let parts = tickerType.split ('.');
+ let id = parts[1];
+ if (id in this.markets_by_id) {
+ market = this.markets_by_id[id];
+ }
+ }
+ let values = ticker['ticker'];
+ let last = values[0];
if (typeof market !== 'undefined') {
symbol = market['symbol'];
- } else if ('pair' in ticker) {
- let idParts = ticker['type'].split ('.');
- let id = idParts[1];
- if (id in this.markets_by_id) {
- market = this.markets_by_id[id];
- }
- if (typeof market !== 'undefined') {
- symbol = market['symbol'];
- }
}
- let ts = ticker['data']['ticker'];
- let last = ts[0];
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
- 'high': ts[7],
- 'low': ts[8],
- 'bid': ts[2],
- 'bidVolume': ts[3],
- 'ask': ts[4],
- 'askVolume': ts[5],
+ 'high': values[7],
+ 'low': values[8],
+ 'bid': values[2],
+ 'bidVolume': values[3],
+ 'ask': values[4],
+ 'askVolume': values[5],
'vwap': undefined,
'open': undefined,
'close': last,
@@ -265,8 +267,8 @@ module.exports = class fcoin extends Exchange {
'change': undefined,
'percentage': undefined,
'average': undefined,
- 'baseVolume': ts[9],
- 'quoteVolume': ts[10],
+ 'baseVolume': values[9],
+ 'quoteVolume': values[10],
'info': ticker,
};
}
|
fcoin parseTicker cleanup + proper symbols and market ids
|
ccxt_ccxt
|
train
|
1540244933de9ff4c114d382b1da509760dac299
|
diff --git a/Lib/fontmake/instantiator.py b/Lib/fontmake/instantiator.py
index <HASH>..<HASH> 100644
--- a/Lib/fontmake/instantiator.py
+++ b/Lib/fontmake/instantiator.py
@@ -102,6 +102,9 @@ WDTH_VALUE_TO_OS2_WIDTH_CLASS = {
# - macintoshFONDFamilyID
# - macintoshFONDName
# - year
+#
+# This means we implicitly require the `stylename` attribute in the Designspace
+# `<instance>` element.
UFO_INFO_ATTRIBUTES_TO_COPY_TO_INSTANCES = {
"copyright",
"familyName",
@@ -371,9 +374,16 @@ class Instantiator:
# TODO: multilingual names to replace possibly existing name records.
if instance.familyName:
font.info.familyName = instance.familyName
- # styleName is implicitly required because it is not copied from the default
- # font.
- font.info.styleName = instance.styleName
+ if instance.styleName is None:
+ logger.warning(
+ "The given instance or instance at location %s is missing the "
+ "stylename attribute, which is required. Copying over the styleName "
+ "from the default font, which is probably wrong.",
+ location,
+ )
+ font.info.styleName = self.copy_info.styleName
+ else:
+ font.info.styleName = instance.styleName
if instance.postScriptFontName:
font.info.postscriptFontName = instance.postScriptFontName
if instance.styleMapFamilyName:
diff --git a/tests/test_instantiator.py b/tests/test_instantiator.py
index <HASH>..<HASH> 100644
--- a/tests/test_instantiator.py
+++ b/tests/test_instantiator.py
@@ -1,3 +1,5 @@
+import logging
+
import fontTools.designspaceLib as designspaceLib
import pytest
import ufoLib2
@@ -299,7 +301,7 @@ def test_instance_attributes(data_dir):
assert instance_font.info.styleMapStyleName == "xxx"
-def test_instance_no_attributes(data_dir):
+def test_instance_no_attributes(data_dir, caplog):
designspace = designspaceLib.DesignSpaceDocument.fromfile(
data_dir / "DesignspaceTest" / "DesignspaceTest-bare.designspace"
)
@@ -307,9 +309,12 @@ def test_instance_no_attributes(data_dir):
designspace, round_geometry=True
)
- instance_font = generator.generate_instance(designspace.instances[0])
+ with caplog.at_level(logging.WARNING):
+ instance_font = generator.generate_instance(designspace.instances[0])
+ assert "missing the stylename attribute" in caplog.text
+
assert instance_font.info.familyName == "MyFont"
- assert instance_font.info.styleName is None
+ assert instance_font.info.styleName == "Light"
assert instance_font.info.postscriptFontName is None
assert instance_font.info.styleMapFamilyName is None
assert instance_font.info.styleMapStyleName is None
|
Warn when an instance does not define a stylename attribute
|
googlefonts_fontmake
|
train
|
518253e15093bdc561d68c6186eba2bda38d0bd6
|
diff --git a/src/Composer/Command/ShowCommand.php b/src/Composer/Command/ShowCommand.php
index <HASH>..<HASH> 100644
--- a/src/Composer/Command/ShowCommand.php
+++ b/src/Composer/Command/ShowCommand.php
@@ -82,14 +82,20 @@ EOT
$repos = $installedRepo = $getRepositories($this->getComposer(), $input->getOption('dev'));
} elseif ($input->getOption('available')) {
$installedRepo = $platformRepo;
- $repos = new CompositeRepository(Factory::createDefaultRepositories($this->getIO()));
+ if ($composer = $this->getComposer(false)) {
+ $repos = new CompositeRepository($composer->getRepositoryManager()->getRepositories());
+ } else {
+ $defaultRepos = Factory::createDefaultRepositories($this->getIO());
+ $repos = new CompositeRepository($defaultRepos);
+ $output->writeln('No composer.json found in the current directory, showing available packages from ' . implode(', ', array_keys($defaultRepos)));
+ }
} elseif ($composer = $this->getComposer(false)) {
$localRepo = $getRepositories($composer, $input->getOption('dev'));
$installedRepo = new CompositeRepository(array($localRepo, $platformRepo));
$repos = new CompositeRepository(array_merge(array($installedRepo), $composer->getRepositoryManager()->getRepositories()));
} else {
$defaultRepos = Factory::createDefaultRepositories($this->getIO());
- $output->writeln('No composer.json found in the current directory, showing packages from ' . implode(', ', array_keys($defaultRepos)));
+ $output->writeln('No composer.json found in the current directory, showing available packages from ' . implode(', ', array_keys($defaultRepos)));
$installedRepo = $platformRepo;
$repos = new CompositeRepository(array_merge(array($installedRepo), $defaultRepos));
}
|
Show proper repo information and not always the default ones
|
mothership-ec_composer
|
train
|
a717e44bcd4564b74efded216d4f561b9afa834d
|
diff --git a/sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/ShardingProxy.java b/sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/ShardingProxy.java
index <HASH>..<HASH> 100644
--- a/sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/ShardingProxy.java
+++ b/sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/ShardingProxy.java
@@ -98,7 +98,7 @@ public final class ShardingProxy {
}
private void groupsEpoll(final ServerBootstrap bootstrap) {
- workerGroup = new EpollEventLoopGroup(RULE_REGISTRY.getAcceptorSize());
+ workerGroup = new EpollEventLoopGroup();
userGroup = new EpollEventLoopGroup(RULE_REGISTRY.getAcceptorSize());
bootstrap.group(bossGroup, workerGroup)
.channel(EpollServerSocketChannel.class)
@@ -111,7 +111,7 @@ public final class ShardingProxy {
}
private void groupsNio(final ServerBootstrap bootstrap) {
- workerGroup = new NioEventLoopGroup(RULE_REGISTRY.getAcceptorSize());
+ workerGroup = new NioEventLoopGroup();
userGroup = new NioEventLoopGroup(RULE_REGISTRY.getAcceptorSize());
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
|
#<I>, workerGroup use default thread pool size (core * 2)
|
apache_incubator-shardingsphere
|
train
|
77cc7c06e23de6d00dbbe61ad131661bcba0ce88
|
diff --git a/tests/test_expectation_decorators.py b/tests/test_expectation_decorators.py
index <HASH>..<HASH> 100644
--- a/tests/test_expectation_decorators.py
+++ b/tests/test_expectation_decorators.py
@@ -26,12 +26,12 @@ class TestExpectationDecorators(unittest.TestCase):
class CustomPandasDataSet(PandasDataSet):
@PandasDataSet.column_map_expectation
- def expect_column_values_to_be_odd(self, series):
- return series.map(lambda x: x % 2 )
+ def expect_column_values_to_be_odd(self, column):
+ return column.map(lambda x: x % 2 )
@PandasDataSet.column_map_expectation
- def expectation_that_crashes_on_sixes(self, series):
- return series.map(lambda x: (x-6)/0 != "duck")
+ def expectation_that_crashes_on_sixes(self, column):
+ return column.map(lambda x: (x-6)/0 != "duck")
df = CustomPandasDataSet({
@@ -143,8 +143,8 @@ class TestExpectationDecorators(unittest.TestCase):
class CustomPandasDataSet(PandasDataSet):
@PandasDataSet.column_aggregate_expectation
- def expect_column_median_to_be_odd(self, series):
- return series.median() % 2, series.median()
+ def expect_column_median_to_be_odd(self, column):
+ return {"success": column.median() % 2, "true_value": column.median(), "summary_obj": None}
df = CustomPandasDataSet({
'all_odd' : [1,3,5,7,9],
@@ -175,7 +175,8 @@ class TestExpectationDecorators(unittest.TestCase):
df.expect_column_median_to_be_odd("all_even", output_format="SUMMARY"),
{
'true_value': 6,
- 'success': False
+ 'success': False,
+ 'summary_obj': None
}
)
@@ -203,12 +204,12 @@ class TestExpectationDecorators(unittest.TestCase):
class CustomPandasDataSet(PandasDataSet):
@PandasDataSet.column_map_expectation
- def expect_column_values_to_be_odd(self, series):
- return series.map(lambda x: x % 2 )
+ def expect_column_values_to_be_odd(self, column):
+ return column.map(lambda x: x % 2 )
@PandasDataSet.column_map_expectation
- def expectation_that_crashes_on_sixes(self, series):
- return series.map(lambda x: 1/(x-6) != "duck")
+ def expectation_that_crashes_on_sixes(self, column):
+ return column.map(lambda x: 1/(x-6) != "duck")
df = CustomPandasDataSet({
@@ -287,7 +288,7 @@ class TestExpectationDecorators(unittest.TestCase):
self.assertEqual(
result_obj["exception_traceback"].split('\n')[-3],
- " return series.map(lambda x: 1/(x-6) != \"duck\")",
+ " return column.map(lambda x: 1/(x-6) != \"duck\")",
)
|
Modify CustomPandasDataSet tests to reflect new convention requirements
|
great-expectations_great_expectations
|
train
|
be5f86f76a36fb90ed2552597ab444bc5db47c4a
|
diff --git a/filterpy/stats/stats.py b/filterpy/stats/stats.py
index <HASH>..<HASH> 100644
--- a/filterpy/stats/stats.py
+++ b/filterpy/stats/stats.py
@@ -829,7 +829,8 @@ def _std_tuple_of(var=None, std=None, interval=None):
def plot_covariance(
mean, cov=None, variance=1.0, std=None, interval=None,
- ellipse=None, title=None, axis_equal=True, show_semiaxis=False,
+ ellipse=None, title=None, axis_equal=True,
+ show_semiaxis=False, show_center=True,
facecolor=None, edgecolor=None,
fc='none', ec='#004080',
alpha=1.0, xlim=None, ylim=None,
@@ -893,6 +894,9 @@ def plot_covariance(
show_semiaxis: bool, default=False
Draw the semiaxis of the ellipse
+ show_center: bool, default=True
+ Mark the center of the ellipse with a cross
+
facecolor, fc: color, default=None
If specified, fills the ellipse with the specified color. `fc` is an
allowed abbreviation
@@ -951,7 +955,9 @@ def plot_covariance(
lw=2, ls=ls)
ax.add_patch(e)
x, y = mean
- plt.scatter(x, y, marker='+', color=edgecolor) # mark the center
+ if show_center:
+ plt.scatter(x, y, marker='+', color=edgecolor)
+
if xlim is not None:
ax.set_xlim(xlim)
|
Optionally hide center cross in plot_covariance
|
rlabbe_filterpy
|
train
|
039b4515e2a8be126f64567bb8c3664facca43b1
|
diff --git a/src/HtmlServiceProvider.php b/src/HtmlServiceProvider.php
index <HASH>..<HASH> 100644
--- a/src/HtmlServiceProvider.php
+++ b/src/HtmlServiceProvider.php
@@ -2,16 +2,16 @@
namespace Styde\Html;
-use Collective\Html\HtmlServiceProvider as ServiceProvider;
-use Illuminate\Contracts\Auth\Access\Gate;
-use Illuminate\Foundation\AliasLoader;
+use Styde\Html\Menu\Menu;
+use Styde\Html\Menu\MenuGenerator;
use Styde\Html\Access\AccessHandler;
-use Styde\Html\Access\BasicAccessHandler;
+use Illuminate\Foundation\AliasLoader;
use Styde\Html\Alert\Container as Alert;
+use Styde\Html\Access\BasicAccessHandler;
+use Illuminate\Contracts\Auth\Access\Gate;
use Styde\Html\Alert\Middleware as AlertMiddleware;
use Styde\Html\Alert\SessionHandler as AlertSessionHandler;
-use Styde\Html\Menu\Menu;
-use Styde\Html\Menu\MenuGenerator;
+use Collective\Html\HtmlServiceProvider as ServiceProvider;
class HtmlServiceProvider extends ServiceProvider
{
@@ -134,7 +134,7 @@ class HtmlServiceProvider extends ServiceProvider
*/
protected function registerAccessHandler()
{
- $this->app[AccessHandler::class] = $this->app->share(function ($app) {
+ $this->app['access'] = $this->app->share(function ($app) {
$guard = $app['config']->get('html.guard', null);
$handler = new BasicAccessHandler($app['auth']->guard($guard));
@@ -145,6 +145,8 @@ class HtmlServiceProvider extends ServiceProvider
return $handler;
});
+
+ $this->app->alias('access', AccessHandler::class);
}
/**
@@ -259,6 +261,8 @@ class HtmlServiceProvider extends ServiceProvider
return $alert;
});
+
+ $this->app->alias('alert', Alert::class);
}
/**
|
Add aliases to the service container
|
StydeNet_html
|
train
|
9ba96f83dd623b09247dc3b303e6316999d98200
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -164,9 +164,9 @@ Assemble.prototype.getCollection = function(name) {
*/
Assemble.prototype.getFile = function(file, id) {
- // if (typeof file === 'object' || !file.hasOwnProperty('id')) {
- // throw new Error('Assemble.getFile expects file objects to have an `id` property.');
- // }
+ if (typeof file === 'object' || !file.hasOwnProperty('id')) {
+ throw new Error('Assemble.getFile expects file objects to have an `id` property.');
+ }
return this.getCollection(id)[file.id];
};
|
uncomment code for file error handling
|
assemble_assemble
|
train
|
d07efab6a9221ee2bd33c4b2d757dd7b4cc5c930
|
diff --git a/structr-ui/src/main/java/org/structr/websocket/command/ChunkCommand.java b/structr-ui/src/main/java/org/structr/websocket/command/ChunkCommand.java
index <HASH>..<HASH> 100644
--- a/structr-ui/src/main/java/org/structr/websocket/command/ChunkCommand.java
+++ b/structr-ui/src/main/java/org/structr/websocket/command/ChunkCommand.java
@@ -24,7 +24,6 @@ import org.slf4j.LoggerFactory;
import org.structr.common.Permission;
import org.structr.common.SecurityContext;
import org.structr.common.error.FrameworkException;
-import org.structr.core.property.PropertyMap;
import org.structr.util.Base64;
import org.structr.web.common.FileHelper;
import org.structr.web.entity.FileBase;
@@ -101,21 +100,13 @@ public class ChunkCommand extends AbstractCommand {
if (sequenceNumber+1 == chunks) {
- final long checksum = FileHelper.getChecksum(file);
- final long size = FileHelper.getSize(file);
-
- final PropertyMap changedProperties = new PropertyMap();
- changedProperties.put(FileBase.checksum, checksum);
- changedProperties.put(FileBase.size, size);
-
- file.unlockSystemPropertiesOnce();
- file.setProperties(securityContext, changedProperties);
+ FileHelper.updateMetadata(file);
file.increaseVersion();
getWebSocket().removeFileUploadHandler(uuid);
- logger.debug("File upload finished. Checksum: {}, size: {}", new Object[]{ checksum, size });
+ logger.debug("File upload finished. Checksum: {}, size: {}", new Object[]{ file.getChecksum(), file.getSize() });
}
diff --git a/structr-ui/src/main/java/org/structr/websocket/command/CreateCommand.java b/structr-ui/src/main/java/org/structr/websocket/command/CreateCommand.java
index <HASH>..<HASH> 100644
--- a/structr-ui/src/main/java/org/structr/websocket/command/CreateCommand.java
+++ b/structr-ui/src/main/java/org/structr/websocket/command/CreateCommand.java
@@ -31,6 +31,7 @@ import org.structr.core.graph.TransactionCommand;
import org.structr.core.property.PropertyMap;
import org.structr.dynamic.File;
import org.structr.schema.SchemaHelper;
+import org.structr.web.common.FileHelper;
import org.structr.web.entity.FileBase;
import org.structr.websocket.StructrWebSocket;
import org.structr.websocket.message.MessageBuilder;
@@ -73,17 +74,18 @@ public class CreateCommand extends AbstractCommand {
// check for File node and store in WebSocket to receive chunks
if (newNode instanceof FileBase) {
- Long size = (Long) webSocketData.getNodeData().get("size");
+ Long size = (Long) webSocketData.getNodeData().get("size");
String contentType = (String) webSocketData.getNodeData().get("contentType");
String name = (String) webSocketData.getNodeData().get("name");
FileBase fileNode = (FileBase) newNode;
-
+
final PropertyMap changedProperties = new PropertyMap();
changedProperties.put(File.size, size != null ? size : 0L);
changedProperties.put(File.contentType, contentType);
changedProperties.put(AbstractNode.name, name);
- fileNode.setProperties(securityContext, changedProperties);
+
+ FileHelper.updateMetadata(fileNode, changedProperties);
getWebSocket().createFileUploadHandler(fileNode);
|
Enhancement: Use FileHelper's unified updateMetadata method to update metadata for files uploaded via Websocket.
|
structr_structr
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.