hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
3c5ace9c7d935bfd4966edecf674ce0e2cdc45d1
|
diff --git a/fooster/web/web.py b/fooster/web/web.py
index <HASH>..<HASH> 100644
--- a/fooster/web/web.py
+++ b/fooster/web/web.py
@@ -1026,7 +1026,7 @@ class HTTPServer:
handler = logging.StreamHandler(sys.stderr)
self.log.addHandler(handler)
- self.log.setLevel(logging.WARNING)
+ self.log.setLevel(logging.INFO)
if http_log:
self.http_log = http_log
@@ -1066,8 +1066,9 @@ class HTTPServer:
if self.using_tls:
self.socket = ssl.wrap_socket(self.socket, self.keyfile, self.certfile, server_side=True)
self.log.info('Socket encrypted with TLS')
- finally:
+ except:
self.close()
+ raise
# create process-ready server info object
self.info = HTTPServerInfo(self)
|
fix issue with socket being erroneously closed if there was no error on intialization
|
fkmclane_python-fooster-web
|
train
|
e86fffc4caced2ff3e98437ef08f44bb38748733
|
diff --git a/zipline/data/data_portal.py b/zipline/data/data_portal.py
index <HASH>..<HASH> 100644
--- a/zipline/data/data_portal.py
+++ b/zipline/data/data_portal.py
@@ -213,12 +213,6 @@ class DataPortal(object):
self.trading_calendar.all_sessions.get_loc(self._first_trading_day)
if self._first_trading_day is not None else None
)
- self._first_trading_minute_loc = (
- self.trading_calendar.all_minutes.get_loc(
- self._first_trading_minute
- )
- if self._first_trading_minute is not None else None
- )
def _ensure_reader_aligned(self, reader):
if reader is None:
@@ -703,10 +697,17 @@ class DataPortal(object):
return daily_data
- def _handle_history_out_of_bounds(self, bar_count):
+ def _handle_minute_history_out_of_bounds(self, bar_count):
+ first_trading_minute_loc = (
+ self.trading_calendar.all_minutes.get_loc(
+ self._first_trading_minute
+ )
+ if self._first_trading_minute is not None else None
+ )
+
suggested_start_day = (
self.trading_calendar.all_minutes[
- self._first_trading_minute_loc + bar_count
+ first_trading_minute_loc + bar_count
] + self.trading_calendar.day
).date()
@@ -728,10 +729,10 @@ class DataPortal(object):
end_dt, -bar_count
)
except KeyError:
- self._handle_history_out_of_bounds(bar_count)
+ self._handle_minute_history_out_of_bounds(bar_count)
if minutes_for_window[0] < self._first_trading_minute:
- self._handle_history_out_of_bounds(bar_count)
+ self._handle_minute_history_out_of_bounds(bar_count)
asset_minute_data = self._get_minute_window_for_assets(
assets,
diff --git a/zipline/utils/calendars/trading_calendar.py b/zipline/utils/calendars/trading_calendar.py
index <HASH>..<HASH> 100644
--- a/zipline/utils/calendars/trading_calendar.py
+++ b/zipline/utils/calendars/trading_calendar.py
@@ -460,29 +460,20 @@ class TradingCalendar(with_metaclass(ABCMeta)):
pd.DateTimeIndex
All the minutes for the given session.
"""
- data = self.schedule.loc[session_label]
- return self.all_minutes[
- self.all_minutes.slice_indexer(
- data.market_open,
- data.market_close
- )
- ]
+ return self.minutes_in_range(*self.schedule.loc[session_label])
def minutes_window(self, start_dt, count):
- try:
- start_idx = self.all_minutes.get_loc(start_dt)
- except KeyError:
- # if this is not a market minute, go to the previous session's
- # close
- previous_session = self.minute_to_session_label(
- start_dt, direction="previous"
- )
+ start_dt_nanos = start_dt.value
+ all_minutes_nanos = self._trading_minutes_nanos
+ start_idx = all_minutes_nanos.searchsorted(start_dt_nanos)
- previous_close = self.open_and_close_for_session(
- previous_session
- )[1]
+ # searchsorted finds the index of the minute **on or after** start_dt.
+ # If the latter, push back to the prior minute.
+ if all_minutes_nanos[start_idx] != start_dt_nanos:
+ start_idx -= 1
- start_idx = self.all_minutes.get_loc(previous_close)
+ if start_idx < 0 or start_idx >= len(all_minutes_nanos):
+ raise KeyError("Can't start minute window at {}".format(start_dt))
end_idx = start_idx + count
diff --git a/zipline/utils/calendars/us_futures_calendar.py b/zipline/utils/calendars/us_futures_calendar.py
index <HASH>..<HASH> 100644
--- a/zipline/utils/calendars/us_futures_calendar.py
+++ b/zipline/utils/calendars/us_futures_calendar.py
@@ -1,10 +1,13 @@
from datetime import time
+from pandas import Timestamp
from pandas.tseries.holiday import GoodFriday
from pytz import timezone
from zipline.utils.calendars import TradingCalendar
-from zipline.utils.calendars.trading_calendar import HolidayCalendar
+from zipline.utils.calendars.trading_calendar import (
+ HolidayCalendar, end_default
+)
from zipline.utils.calendars.us_holidays import (
USNewYearsDay,
Christmas
@@ -31,6 +34,15 @@ class QuantopianUSFuturesCalendar(TradingCalendar):
In order to align the hours of each session, we ignore the Sunday
CME Pre-Open hour (5-6pm).
"""
+ # XXX: Override the default TradingCalendar start and end dates with ones
+ # further in the future. This is a stopgap for memory issues caused by
+ # upgrading to pandas 18. This calendar is the most severely affected,
+ # since it has the most total minutes of any of the zipline calendars.
+ def __init__(self,
+ start=Timestamp('2000-01-01', tz='UTC'),
+ end=end_default):
+ super(QuantopianUSFuturesCalendar, self).__init__(start=start, end=end)
+
@property
def name(self):
return "us_futures"
|
PERF: Remove or defer calls to get_loc on large indices.
Mitigation for <URL>
|
quantopian_zipline
|
train
|
a92210fa9f365728a109f5dbee60781b4371d902
|
diff --git a/core/src/main/java/com/twitter/elephantbird/thrift/ThriftBinaryDeserializer.java b/core/src/main/java/com/twitter/elephantbird/thrift/ThriftBinaryDeserializer.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/com/twitter/elephantbird/thrift/ThriftBinaryDeserializer.java
+++ b/core/src/main/java/com/twitter/elephantbird/thrift/ThriftBinaryDeserializer.java
@@ -15,7 +15,7 @@ import org.apache.thrift.transport.TMemoryInputTransport;
* corrupt records in two ways: <ul>
*
* <li> sets read-limit for TBinaryProtocol before each deserialization.
- * Reduces to reduce OutOfMemoryError exceptions.
+ * Reduces OutOfMemoryError exceptions.
*
* <li> Avoids excessive cpu consumed while skipping some corrupt records.
* </ul>
@@ -44,8 +44,13 @@ public class ThriftBinaryDeserializer extends TDeserializer {
case TType.SET:
case TType.LIST:
break;
+
+ // list other known types, but not expected
+ case TType.STOP:
+ case TType.VOID:
+ case TType.ENUM: // would be I32 on the wire
default:
- throw new TException("Unexpected type in a container");
+ throw new TException("Unexpected type " + type + " in a container");
}
}
|
review comments :
- include type value in exception message
- fix javadoc.
|
twitter_elephant-bird
|
train
|
3255e2cbe8e5e027e06f52bf7989dda2640b2aa3
|
diff --git a/closure/goog/fx/dragger.js b/closure/goog/fx/dragger.js
index <HASH>..<HASH> 100644
--- a/closure/goog/fx/dragger.js
+++ b/closure/goog/fx/dragger.js
@@ -321,7 +321,10 @@ goog.fx.Dragger.prototype.enableRightPositioningForRtl =
* @template T
*/
goog.fx.Dragger.prototype.getHandler = function() {
- return this.eventHandler_;
+ // TODO(user): templated "this" values currently result in "this" being
+ // "unknown" in the body of the function.
+ var self = /** @type {goog.fx.Dragger} */ (this);
+ return self.eventHandler_;
};
|
Fix unknown "this" warning.
-------------
Created by MOE: <URL>
|
google_closure-library
|
train
|
07936f596d435854830e5b031eae75323984faea
|
diff --git a/lib/instrumentation/index.js b/lib/instrumentation/index.js
index <HASH>..<HASH> 100644
--- a/lib/instrumentation/index.js
+++ b/lib/instrumentation/index.js
@@ -281,6 +281,8 @@ function transactionGroupingKey (trans) {
}
function traceGroupingKey (trace) {
- var ancestors = trace.ancestors().map(function (trace) { return trace.signature }).join('|')
- return groupingTs(trace.transaction._start) + '|' + trace.transaction.name + '|' + ancestors + '|' + trace.signature
+ return groupingTs(trace.transaction._start) +
+ '|' + trace.transaction.name +
+ '|' + trace.ancestors().join('|') +
+ '|' + trace.signature
}
|
core: fix trace grouping key algorithm
|
opbeat_opbeat-node
|
train
|
2846a34ed5b8255f8ce3f9d6e34552e5b67f4325
|
diff --git a/classes/hybrid-media-grabber.php b/classes/hybrid-media-grabber.php
index <HASH>..<HASH> 100644
--- a/classes/hybrid-media-grabber.php
+++ b/classes/hybrid-media-grabber.php
@@ -392,16 +392,13 @@ class Hybrid_Media_Grabber {
$max_height = 380;
/* Calculate new media dimensions. */
- $dimensions = wp_expand_dimensions(
+ list( $width, $height ) = wp_expand_dimensions(
$media_atts['width'],
$media_atts['height'],
$this->args['width'],
$max_height
);
- $width = $dimensions[0];
- $height = $dimensions[1];
-
/* Set up the patterns for the 'width' and 'height' attributes. */
$patterns = array(
'/(width=[\'"]).+?([\'"])/i',
|
Use list() to set the $width and $height variables.
|
justintadlock_hybrid-core
|
train
|
3851741ab1072cd2c1eb85ea29174118998fffa9
|
diff --git a/ncpol2sdpa/sdp_relaxation.py b/ncpol2sdpa/sdp_relaxation.py
index <HASH>..<HASH> 100644
--- a/ncpol2sdpa/sdp_relaxation.py
+++ b/ncpol2sdpa/sdp_relaxation.py
@@ -10,9 +10,8 @@ Created on Sun May 26 15:06:17 2013
from __future__ import division, print_function
import sys
from functools import partial
-from math import floor, sqrt
import numpy as np
-from sympy import S, Expr, expand
+from sympy import S, Expr
import time
try:
@@ -321,8 +320,8 @@ class SdpRelaxation(Relaxation):
if self._parallel:
pool = multiprocessing.Pool()
# This is just a guess and can be optimized
- chunksize = max(int(sqrt(len(monomialsA) * len(monomialsB) *
- len(monomialsA) / 2) /
+ chunksize = max(int(np.sqrt(len(monomialsA) * len(monomialsB) *
+ len(monomialsA) / 2) /
multiprocessing.cpu_count()), 1)
iter_ = pool.imap(func, ((rowA, columnA, rowB, columnB)
for rowA in range(len(monomialsA))
@@ -515,7 +514,7 @@ class SdpRelaxation(Relaxation):
func = partial(moment_of_entry, monomials=monomials, ineq=ineq,
substitutions=self.substitutions)
if self._parallel:
- chunksize = max(int(sqrt(len(monomials)*len(monomials)/2) /
+ chunksize = max(int(np.sqrt(len(monomials)*len(monomials)/2) /
multiprocessing.cpu_count()), 1)
iter_ = pool.imap(func, ([row, column]
for row in range(len(monomials))
@@ -561,7 +560,7 @@ class SdpRelaxation(Relaxation):
raise Exception("An equality constraint has degree %d. "
"Choose a higher level of relaxation."
% eq_order)
- localization_order = int(floor((2 * self.level - eq_order)/2))
+ localization_order = (2 * self.level - eq_order)//2
index = find_variable_set(self.variables, equality)
localizing_monomials = \
pick_monomials_up_to_degree(self.monomial_sets[index],
|
Moved from math to numpy
|
peterwittek_ncpol2sdpa
|
train
|
6ff94e590d4f2577d71f042682acd4409543581c
|
diff --git a/encode/src/org/immutables/encode/Encoding.java b/encode/src/org/immutables/encode/Encoding.java
index <HASH>..<HASH> 100644
--- a/encode/src/org/immutables/encode/Encoding.java
+++ b/encode/src/org/immutables/encode/Encoding.java
@@ -6,7 +6,15 @@ import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
- * Encoding defines set of template methods and fields which describes how type is embedded.
+ * Encoding defines set of template methods and fields which describes how attributes of specific
+ * types are implemented in generated value class. {@code Encoding} annotation is processed by the
+ * annotation processor (the same as used for value objects) and generates annotation named
+ * {@code *Enabled} in the same package, inserting encoding simple class name in placeholder.
+ * Encoding class consists of special fields methods, builder inner static class with it's own
+ * fields and methods.
+ * <p>
+ * When programming the encoding class, remember that code analyser is not akin full-fledged java
+ * compiler, but a set of simplified routines which cannot possibly
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
@@ -21,7 +29,21 @@ public @interface Encoding {
/**
* Many elements (but not all) supports customized naming patterns.
+ * Use single asterisk symbol in a name to denote a placeholder where attribute name would be
+ * insterted.
+ * We call namings of form {@code "*"} as identity naming, and the ones which have no placeholder,
+ * as in {@code "set"} - constant namings.
* Like "with*Added" for copy with addition method.
+ * Elements that can have customized naming:
+ * <ul>
+ * <li>Helper fields and methods</li>
+ * </ul>
+ * <p>
+ * <em>
+ * Please note, that with customized naming it is possible (but in general, not recommended) to put
+ * constant naming (without {@code "*"} placeholder) on elements. But when you do this it can result
+ * in name clashes in generated code.
+ * </em>
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
diff --git a/generator/src/org/immutables/generator/AbstractGenerator.java b/generator/src/org/immutables/generator/AbstractGenerator.java
index <HASH>..<HASH> 100644
--- a/generator/src/org/immutables/generator/AbstractGenerator.java
+++ b/generator/src/org/immutables/generator/AbstractGenerator.java
@@ -53,16 +53,6 @@ public abstract class AbstractGenerator extends AbstractProcessor {
return StaticEnvironment.annotations();
}
- protected final <T> T newTemplate(Class<T> type) {
- String generatorClassname = type.getPackage().getName() + ".Generator_" + type.getSimpleName();
- try {
- Class<?> templateImplementationClass = type.getClassLoader().loadClass(generatorClassname);
- return type.cast(templateImplementationClass.newInstance());
- } catch (Exception ex) {
- throw Throwables.propagate(ex);
- }
- }
-
protected final void invoke(Templates.Invokable invokable) {
invokable.invoke(Templates.Invokation.initial());
}
diff --git a/value-processor/src/org/immutables/value/processor/encode/Processor.java b/value-processor/src/org/immutables/value/processor/encode/Processor.java
index <HASH>..<HASH> 100644
--- a/value-processor/src/org/immutables/value/processor/encode/Processor.java
+++ b/value-processor/src/org/immutables/value/processor/encode/Processor.java
@@ -9,6 +9,6 @@ import org.immutables.metainf.Metainf;
public class Processor extends AbstractGenerator {
@Override
protected void process() {
- invoke(newTemplate(Encodings.class).generate());
+ invoke(new Generator_Encodings().generate());
}
}
|
fix, removing reflection from template-loading
|
immutables_immutables
|
train
|
2f160ea403d124d237fc2138c0aa0d175fbad22a
|
diff --git a/scanpy/plotting/_tools/__init__.py b/scanpy/plotting/_tools/__init__.py
index <HASH>..<HASH> 100644
--- a/scanpy/plotting/_tools/__init__.py
+++ b/scanpy/plotting/_tools/__init__.py
@@ -229,7 +229,7 @@ def rank_genes_groups(
groups: Union[str, Sequence[str]] = None,
n_genes: int = 20,
gene_symbols: Optional[str] = None,
- key: Optional[str] = None,
+ key: Optional[str] = 'rank_genes_groups',
fontsize: int = 8,
ncols: int = 4,
sharey: bool = True,
@@ -265,8 +265,6 @@ def rank_genes_groups(
n_panels_per_row = kwds['n_panels_per_row']
else:
n_panels_per_row = ncols
- if key is None:
- key = 'rank_genes_groups'
reference = str(adata.uns[key]['params']['reference'])
group_names = adata.uns[key]['names'].dtype.names if groups is None else groups
# one panel for each group
@@ -288,17 +286,28 @@ def rank_genes_groups(
ymin = np.Inf
ymax = -np.Inf
for count, group_name in enumerate(group_names):
- if sharey is True:
+ gene_names = adata.uns[key]['names'][group_name][:n_genes]
+ scores = adata.uns[key]['scores'][group_name][:n_genes]
+
+ # Setting up axis, calculating y bounds
+ if sharey:
+ ymin = min(ymin, np.min(scores))
+ ymax = max(ymax, np.max(scores))
+
if ax0 is None:
ax = fig.add_subplot(gs[count])
ax0 = ax
else:
ax = fig.add_subplot(gs[count], sharey=ax0)
else:
+ ymin = np.min(scores)
+ ymax = np.max(scores)
+ ymax += 0.3 * (ymax - ymin)
+
ax = fig.add_subplot(gs[count])
+ ax.set_ylim(ymin, ymax)
- gene_names = adata.uns[key]['names'][group_name][:n_genes]
- scores = adata.uns[key]['scores'][group_name][:n_genes]
+ ax.set_xlim(-0.9, n_genes - 0.1)
# Mapping to gene_symbols
if gene_symbols is not None:
@@ -327,17 +336,6 @@ def rank_genes_groups(
if count % n_panels_x == 0:
ax.set_ylabel('score')
- ax.set_xlim(-0.9, ig + 1 - 0.1)
-
- if sharey is True:
- ymin = min(ymin, np.min(scores))
- ymax = max(ymax, np.max(scores))
- else:
- ymin = np.min(scores)
- ymax = np.max(scores)
- ymax += 0.3 * (np.max(scores) - np.min(scores))
- ax.set_ylim(ymin, ymax)
-
if sharey is True:
ymax += 0.3 * (ymax - ymin)
ax.set_ylim(ymin, ymax)
|
Minor code cleanup for sc.pl.rank_genes_groups
Mostly reducing flow control, moving similar statements together
|
theislab_scanpy
|
train
|
cbd4f734e9c26c9fdb29d81c70e729f08f75334d
|
diff --git a/examples/language-analyzer.py b/examples/language-analyzer.py
index <HASH>..<HASH> 100644
--- a/examples/language-analyzer.py
+++ b/examples/language-analyzer.py
@@ -7,6 +7,7 @@
import time
from lookout.sdk import pb
+from lookout.sdk.service_data import DataStub
from lookout.sdk.grpc import to_grpc_address, create_channel, create_server, \
LogUnaryServerInterceptor, LogStreamServerInterceptor, \
LogUnaryClientInterceptor, LogStreamClientInterceptor
@@ -35,7 +36,7 @@ class Analyzer(pb.AnalyzerServicer):
LogUnaryClientInterceptor(log_fn),
LogStreamClientInterceptor(log_fn),
]) as channel:
- stub = pb.DataStub(channel)
+ stub = DataStub(channel)
# Add some log fields that will be available to the data server
# using `context.add_log_fields`.
diff --git a/python/lookout/sdk/pb.py b/python/lookout/sdk/pb.py
index <HASH>..<HASH> 100644
--- a/python/lookout/sdk/pb.py
+++ b/python/lookout/sdk/pb.py
@@ -7,11 +7,10 @@ from lookout.sdk.event_pb2 import CommitRevision, PushEvent, \
from lookout.sdk.service_analyzer_pb2_grpc import AnalyzerStub, \
add_AnalyzerServicer_to_server as add_analyzer_to_server
from lookout.sdk.service_analyzer_pb2 import Comment, EventResponse
-from lookout.sdk.service_data_pb2_grpc import DataServicer, \
+from lookout.sdk.service_data_pb2_grpc import DataServicer, DataStub, \
add_DataServicer_to_server as add_dataservicer_to_server
from lookout.sdk.service_data_pb2 import Change, ChangesRequest, File, \
FilesRequest
-from lookout.sdk.service_data import DataStub
from lookout.sdk.service_analyzer import AnalyzerServicer
__all__ = [
diff --git a/python/tests/test_logger_interceptors.py b/python/tests/test_logger_interceptors.py
index <HASH>..<HASH> 100644
--- a/python/tests/test_logger_interceptors.py
+++ b/python/tests/test_logger_interceptors.py
@@ -7,6 +7,7 @@ import unittest
import grpc
from lookout.sdk import pb
+from lookout.sdk.service_data import DataStub
from lookout.sdk.grpc import create_channel, create_server, \
LogUnaryServerInterceptor, \
LogStreamServerInterceptor, \
@@ -131,7 +132,7 @@ class TestClientLoggerInterceptors(TestWithRunningServicerMixin,
LogUnaryClientInterceptor(self._tracker.unary),
LogStreamClientInterceptor(self._tracker.stream),
]) as channel:
- stub = pb.DataStub(channel)
+ stub = DataStub(channel)
stub.get_changes(None, pb.ChangesRequest())
self.assertEqual(self._tracker.counter, {"unary": 0, "stream": 2})
|
Changed lookout.sdk.pb.DataStub import
|
src-d_lookout-sdk
|
train
|
1fd90845745722139666dc580572b6e531e3840c
|
diff --git a/index.html b/index.html
index <HASH>..<HASH> 100644
--- a/index.html
+++ b/index.html
@@ -134,12 +134,12 @@
<ul>
<li>
<a href='https://github.com/dataarts/dat.gui/raw/build/DAT.GUI.min.js'><strong>Download the minified source</strong></a>
- <small id='buildsizemin'>[19.5kb]
+ <small id='buildsizemin'>[19.6kb]
</small>
</li>
<li>
<a href='https://github.com/dataarts/dat.gui/raw/build/DAT.GUI.js'><strong>Download the uncompressed source</strong></a>
- <small id='buildsize'>[33.6kb]
+ <small id='buildsize'>[33.8kb]
</small>
</li>
diff --git a/src/DAT/GUI/Controller.js b/src/DAT/GUI/Controller.js
index <HASH>..<HASH> 100644
--- a/src/DAT/GUI/Controller.js
+++ b/src/DAT/GUI/Controller.js
@@ -42,7 +42,13 @@ DAT.GUI.Controller.prototype.unlisten = function() {
};
DAT.GUI.Controller.prototype.setValue = function(n) {
- this.object[this.propertyName] = n;
+ if(this.object[this.propertyName]){
+ this.object[this.propertyName] = n;
+ }else{
+ var o = new Object();
+ o[this.propertyName] = n;
+ this.object.set(o);
+ }
if (this.changeFunction != null) {
this.changeFunction.call(this, n);
}
@@ -51,7 +57,8 @@ DAT.GUI.Controller.prototype.setValue = function(n) {
};
DAT.GUI.Controller.prototype.getValue = function() {
- return this.object[this.propertyName];
+ var val = this.object[this.propertyName] || this.object.get(this.propertyName);
+ return val;
};
DAT.GUI.Controller.prototype.updateDisplay = function() {
diff --git a/src/DAT/GUI/GUI.js b/src/DAT/GUI/GUI.js
index <HASH>..<HASH> 100644
--- a/src/DAT/GUI/GUI.js
+++ b/src/DAT/GUI/GUI.js
@@ -306,7 +306,7 @@ DAT.GUI = function(parameters) {
// return;
}
- var value = object[propertyName];
+ var value = object[propertyName] || (object.get && object.get(propertyName));
// Does this value exist? Is it accessible?
if (value == undefined) {
|
Check for getter and setter methods of direct access fails
|
dataarts_dat.gui
|
train
|
041db864b18f74c0c56d62bd7a3450d94597cc91
|
diff --git a/src/actions/field-actions.js b/src/actions/field-actions.js
index <HASH>..<HASH> 100644
--- a/src/actions/field-actions.js
+++ b/src/actions/field-actions.js
@@ -3,7 +3,7 @@ import map from 'lodash/map';
import batchActions from './batch-actions';
import actionTypes from '../action-types';
-import { getValidity } from '../utils';
+import { getValidity, getForm } from '../utils';
const focus = model => ({
type: actionTypes.FOCUS,
@@ -120,7 +120,7 @@ const validateErrors = (model, errorValidators) => (dispatch, getState) => {
dispatch(setErrors(model, errors));
};
-const validateFields = (model, fieldValidators) => (dispatch, getState) => {
+const validateFields = (model, fieldValidators, callback) => (dispatch, getState) => {
const value = _get(getState(), model);
const validationActions = map(fieldValidators, (validator, field) => {
@@ -136,6 +136,16 @@ const validateFields = (model, fieldValidators) => (dispatch, getState) => {
return setValidity(fieldModel, fieldValidity);
});
+ if (callback) {
+ validationActions.push((_, _getState) => {
+ const form = getForm(_getState(), model);
+
+ if (form && form.valid) {
+ callback();
+ }
+ });
+ }
+
dispatch(batchActions.batch(model, validationActions));
};
diff --git a/src/components/form-component.js b/src/components/form-component.js
index <HASH>..<HASH> 100644
--- a/src/components/form-component.js
+++ b/src/components/form-component.js
@@ -7,7 +7,7 @@ import identity from 'lodash/identity';
import mapValues from 'lodash/mapValues';
import actions from '../actions';
-import { getValidity, isValid, isInvalid } from '../utils';
+import { getValidity } from '../utils';
class Form extends Component {
constructor(props) {
@@ -39,7 +39,7 @@ class Form extends Component {
/* eslint-enable react/prop-types */
/* eslint-disable consistent-return */
- const validity = mapValues(validators, (validator, field) => {
+ mapValues(validators, (validator, field) => {
const fieldModel = [model, field].join('.');
const value = _get(nextProps, fieldModel);
@@ -52,7 +52,7 @@ class Form extends Component {
return fieldValidity;
});
- const errorsValidity = mapValues(errors, (errorValidator, field) => {
+ mapValues(errors, (errorValidator, field) => {
const fieldModel = [model, field].join('.');
const value = _get(nextProps, fieldModel);
@@ -65,8 +65,6 @@ class Form extends Component {
return fieldErrors;
});
/* eslint-enable consistent-return */
-
- return isValid(validity) && !isInvalid(errorsValidity);
}
handleSubmit(e) {
@@ -76,17 +74,28 @@ class Form extends Component {
const {
model,
onSubmit,
+ dispatch,
+ validators,
} = this.props;
/* eslint-enable react/prop-types */
const modelValue = _get(this.props, model);
- const isFormValid = this.validate(this.props, true);
+ if (!validators && onSubmit) {
+ onSubmit(modelValue);
- if (onSubmit && isFormValid) {
- return onSubmit(modelValue);
+ return modelValue;
}
+ const validationCallback = onSubmit
+ ? () => onSubmit(modelValue)
+ : undefined;
+
+ dispatch(actions.validateFields(
+ model,
+ validators,
+ validationCallback));
+
return modelValue;
}
diff --git a/test/field-actions-spec.js b/test/field-actions-spec.js
index <HASH>..<HASH> 100644
--- a/test/field-actions-spec.js
+++ b/test/field-actions-spec.js
@@ -1151,7 +1151,7 @@ describe('field actions', () => {
describe('validateFields() (thunk)', () => {
const mockStore = configureMockStore([thunk]);
- it('should set the validity of multiple fields', (done) => {
+ it('should set the validity of multiple fields in the same form', (done) => {
const store = mockStore(
() => ({ test: { foo: 'bar' } }),
[{
|
Adding callback param to validateFields action and using it in handleSubmit() of <Form> component
|
davidkpiano_react-redux-form
|
train
|
f2292737802ae2ad0fccaf6863231d2948a453c2
|
diff --git a/niworkflows/workflows/epi/refmap.py b/niworkflows/workflows/epi/refmap.py
index <HASH>..<HASH> 100644
--- a/niworkflows/workflows/epi/refmap.py
+++ b/niworkflows/workflows/epi/refmap.py
@@ -52,7 +52,8 @@ def init_epi_reference_wf(omp_nthreads, name="epi_reference_wf"):
FixN4BiasFieldCorrection as N4BiasFieldCorrection,
)
from ...interfaces.freesurfer import StructuralReference
- from ...interfaces.images import ValidateImage, RobustAverage
+ from ...interfaces.header import ValidateImage
+ from ...interfaces.images import RobustAverage
from ...interfaces.nibabel import IntensityClip
wf = Workflow(name=name)
@@ -70,7 +71,7 @@ def init_epi_reference_wf(omp_nthreads, name="epi_reference_wf"):
NonsteadyStatesDetector(), name="select_volumes", iterfield=["in_file"]
)
run_avgs = pe.MapNode(
- RobustAverage(), name="run_avgs", mem_gb=1, iterfield=["in_file"]
+ RobustAverage(), name="run_avgs", mem_gb=1, iterfield=["in_file", "t_mask"]
)
clip_avgs = pe.MapNode(IntensityClip(), name="clip_avgs", iterfield=["in_file"])
@@ -86,6 +87,7 @@ def init_epi_reference_wf(omp_nthreads, name="epi_reference_wf"):
),
n_procs=omp_nthreads,
name="n4_avgs",
+ iterfield=["input_image"],
)
epi_merge = pe.Node(
|
fix: address issues so that workflow builds
|
poldracklab_niworkflows
|
train
|
691853c424822ac845289705cbdf151bbb22e53b
|
diff --git a/spew/config.go b/spew/config.go
index <HASH>..<HASH> 100644
--- a/spew/config.go
+++ b/spew/config.go
@@ -242,7 +242,8 @@ package:
The configuration options are controlled by modifying the public members
of c. See ConfigState for options documentation.
-See Fdump if you would prefer dumping to an arbitrary io.Writer.
+See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to
+get the formatted result as a string.
*/
func (c *ConfigState) Dump(a ...interface{}) {
fdump(c, os.Stdout, a...)
diff --git a/spew/doc.go b/spew/doc.go
index <HASH>..<HASH> 100644
--- a/spew/doc.go
+++ b/spew/doc.go
@@ -49,9 +49,10 @@ This section demonstrates how to quickly get started with spew. See the
sections below for further details on formatting and configuration options.
To dump a variable with full newlines, indentation, type, and pointer
-information use Dump or Fdump:
+information use Dump, Fdump, or Sdump:
spew.Dump(myVar1, myVar2, ...)
spew.Fdump(someWriter, myVar1, myVar2, ...)
+ str := spew.Sdump(myVar1, myVar2, ...)
Alternatively, if you would prefer to use format strings with a compacted inline
printing style, use the convenience wrappers Printf, Fprintf, etc with
@@ -105,6 +106,10 @@ io.Writer. For example, to dump to standard error:
spew.Fdump(os.Stderr, myVar1, myVar2, ...)
+A third option is to call spew.Sdump to get the formatted output as a string:
+
+ str := spew.Sdump(myVar1, myVar2, ...)
+
Sample Dump Output
See the Dump example for details on the setup of the types and variables being
diff --git a/spew/dump.go b/spew/dump.go
index <HASH>..<HASH> 100644
--- a/spew/dump.go
+++ b/spew/dump.go
@@ -391,7 +391,8 @@ package:
The configuration options are controlled by an exported package global,
spew.Config. See ConfigState for options documentation.
-See Fdump if you would prefer dumping to an arbitrary io.Writer.
+See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to
+get the formatted result as a string.
*/
func Dump(a ...interface{}) {
fdump(&Config, os.Stdout, a...)
|
Update docs for new Sdump function.
|
davecgh_go-spew
|
train
|
f83a66900027882d6ce5c356c4aae08362f52270
|
diff --git a/src/Apps/AppManager.php b/src/Apps/AppManager.php
index <HASH>..<HASH> 100644
--- a/src/Apps/AppManager.php
+++ b/src/Apps/AppManager.php
@@ -4,7 +4,7 @@ namespace BeyondCode\LaravelWebSockets\Apps;
interface AppManager
{
- /**
+ /**
* Get all apps.
*
* @return array[\BeyondCode\LaravelWebSockets\Apps\App]
diff --git a/src/Apps/ConfigAppManager.php b/src/Apps/ConfigAppManager.php
index <HASH>..<HASH> 100644
--- a/src/Apps/ConfigAppManager.php
+++ b/src/Apps/ConfigAppManager.php
@@ -2,8 +2,6 @@
namespace BeyondCode\LaravelWebSockets\Apps;
-use Illuminate\Support\Collection;
-
class ConfigAppManager implements AppManager
{
/**
diff --git a/src/Server/Logger/ConnectionLogger.php b/src/Server/Logger/ConnectionLogger.php
index <HASH>..<HASH> 100644
--- a/src/Server/Logger/ConnectionLogger.php
+++ b/src/Server/Logger/ConnectionLogger.php
@@ -17,7 +17,7 @@ class ConnectionLogger extends Logger implements ConnectionInterface
* Create a new instance and add a connection to watch.
*
* @param \Ratchet\ConnectionInterface $connection
- * @return Self
+ * @return self
*/
public static function decorate(ConnectionInterface $app): self
{
diff --git a/src/Server/Logger/HttpLogger.php b/src/Server/Logger/HttpLogger.php
index <HASH>..<HASH> 100644
--- a/src/Server/Logger/HttpLogger.php
+++ b/src/Server/Logger/HttpLogger.php
@@ -19,7 +19,7 @@ class HttpLogger extends Logger implements MessageComponentInterface
* Create a new instance and add the app to watch.
*
* @param \Ratchet\MessageComponentInterface $app
- * @return Self
+ * @return self
*/
public static function decorate(MessageComponentInterface $app): self
{
diff --git a/src/Server/Logger/WebsocketsLogger.php b/src/Server/Logger/WebsocketsLogger.php
index <HASH>..<HASH> 100644
--- a/src/Server/Logger/WebsocketsLogger.php
+++ b/src/Server/Logger/WebsocketsLogger.php
@@ -21,7 +21,7 @@ class WebsocketsLogger extends Logger implements MessageComponentInterface
* Create a new instance and add the app to watch.
*
* @param \Ratchet\MessageComponentInterface $app
- * @return Self
+ * @return self
*/
public static function decorate(MessageComponentInterface $app): self
{
diff --git a/src/Statistics/Events/StatisticsUpdated.php b/src/Statistics/Events/StatisticsUpdated.php
index <HASH>..<HASH> 100644
--- a/src/Statistics/Events/StatisticsUpdated.php
+++ b/src/Statistics/Events/StatisticsUpdated.php
@@ -14,7 +14,7 @@ class StatisticsUpdated implements ShouldBroadcast
use SerializesModels;
/**
- * The statistic instance that got updated
+ * The statistic instance that got updated.
*
* @var \BeyondCode\LaravelWebSockets\Statistics\Models\WebSocketsStatisticsEntry
*/
|
Apply fixes from StyleCI (#<I>)
|
beyondcode_laravel-websockets
|
train
|
9a130ae93e5b984276796f68d61e40738eed9aca
|
diff --git a/src/Symfony/Component/Yaml/Parser.php b/src/Symfony/Component/Yaml/Parser.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/Yaml/Parser.php
+++ b/src/Symfony/Component/Yaml/Parser.php
@@ -200,7 +200,7 @@ class Parser
array_pop($this->refsBeingParsed);
}
} elseif (
- self::preg_match('#^(?P<key>(?:![^\s]++\s++)?(?:'.Inline::REGEX_QUOTED_STRING.'|(?:!?!php/const:)?[^ \'"\[\{!].*?)) *\:( ++(?P<value>.+))?$#u', rtrim($this->currentLine), $values)
+ self::preg_match('#^(?P<key>(?:![^\s]++\s++)?(?:'.Inline::REGEX_QUOTED_STRING.'|(?:!?!php/const:)?[^ \'"\[\{!].*?)) *\:(( |\t)++(?P<value>.+))?$#u', rtrim($this->currentLine), $values)
&& (false === strpos($values['key'], ' #') || \in_array($values['key'][0], ['"', "'"]))
) {
if ($context && 'sequence' == $context) {
diff --git a/src/Symfony/Component/Yaml/Tests/ParserTest.php b/src/Symfony/Component/Yaml/Tests/ParserTest.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/Yaml/Tests/ParserTest.php
+++ b/src/Symfony/Component/Yaml/Tests/ParserTest.php
@@ -52,26 +52,67 @@ class ParserTest extends TestCase
return $this->loadTestsFromFixtureFiles('nonStringKeys.yml');
}
- public function testTabsInYaml()
+ /**
+ * @dataProvider invalidIndentation
+ */
+ public function testTabsAsIndentationInYaml(string $given, string $expectedMessage)
{
- // test tabs in YAML
- $yamls = [
- "foo:\n bar",
- "foo:\n bar",
- "foo:\n bar",
- "foo:\n bar",
+ $this->expectException(ParseException::class);
+ $this->expectExceptionMessage($expectedMessage);
+ $this->parser->parse($given);
+ }
+
+ public function invalidIndentation(): array
+ {
+ return [
+ [
+ "foo:\n\tbar",
+ "A YAML file cannot contain tabs as indentation at line 2 (near \"\tbar\").",
+ ],
+ [
+ "foo:\n \tbar",
+ "A YAML file cannot contain tabs as indentation at line 2 (near \"\tbar\").",
+ ],
+ [
+ "foo:\n\t bar",
+ "A YAML file cannot contain tabs as indentation at line 2 (near \"\t bar\").",
+ ],
+ [
+ "foo:\n \t bar",
+ "A YAML file cannot contain tabs as indentation at line 2 (near \"\t bar\").",
+ ],
];
+ }
- foreach ($yamls as $yaml) {
- try {
- $this->parser->parse($yaml);
+ /**
+ * @dataProvider validTokenSeparators
+ */
+ public function testValidTokenSeparation(string $given, array $expected)
+ {
+ $actual = $this->parser->parse($given);
+ $this->assertEquals($expected, $actual);
+ }
- $this->fail('YAML files must not contain tabs');
- } catch (\Exception $e) {
- $this->assertInstanceOf(\Exception::class, $e, 'YAML files must not contain tabs');
- $this->assertEquals('A YAML file cannot contain tabs as indentation at line 2 (near "'.strpbrk($yaml, "\t").'").', $e->getMessage(), 'YAML files must not contain tabs');
- }
- }
+ public function validTokenSeparators(): array
+ {
+ return [
+ [
+ 'foo: bar',
+ ['foo' => 'bar'],
+ ],
+ [
+ "foo:\tbar",
+ ['foo' => 'bar'],
+ ],
+ [
+ "foo: \tbar",
+ ['foo' => 'bar'],
+ ],
+ [
+ "foo:\t bar",
+ ['foo' => 'bar'],
+ ],
+ ];
}
public function testEndOfTheDocumentMarker()
|
Fix issue <I>: Tabs as separators between tokens
|
symfony_symfony
|
train
|
7e1902a18bb9aa7d8f98a3dacf6da3b05d350811
|
diff --git a/interp/param.go b/interp/param.go
index <HASH>..<HASH> 100644
--- a/interp/param.go
+++ b/interp/param.go
@@ -33,8 +33,8 @@ func (r *Runner) paramExp(pe *syntax.ParamExp) string {
}
}
str := varStr(val)
- if pe.Ind != nil {
- str = r.varInd(val, pe.Ind.Expr)
+ if pe.Index != nil {
+ str = r.varInd(val, pe.Index)
}
switch {
case pe.Length:
|
interp: adapt to ParamExp index change
|
mvdan_sh
|
train
|
bd8ca096ad2606f1219843aa67466f41862b66a8
|
diff --git a/zarr/compression.py b/zarr/compression.py
index <HASH>..<HASH> 100644
--- a/zarr/compression.py
+++ b/zarr/compression.py
@@ -2,7 +2,6 @@
from __future__ import absolute_import, print_function, division
import zlib
import bz2
-import lzma
import numpy as np
@@ -143,82 +142,88 @@ class BZ2Compressor(object):
registry['bz2'] = BZ2Compressor
-class LZMACompressor(object):
-
- default_format = lzma.FORMAT_XZ
- default_check = lzma.CHECK_NONE
- default_preset = 1
- default_filters = None
-
- def __init__(self, compression_opts):
- # at this point we expect compression_opts to be fully specified and
- # normalized
- self.format = compression_opts['format']
- self.check = compression_opts['check']
- self.preset = compression_opts['preset']
- self.filters = compression_opts['filters']
-
- @classmethod
- def normalize_compression_opts(cls, compression_opts):
- """Convenience function to normalize compression options."""
-
- if compression_opts is None:
- compression_opts = dict()
-
- format = compression_opts.get('format', None)
- check = compression_opts.get('check', None)
- preset = compression_opts.get('preset', None)
- filters = compression_opts.get('filters', None)
-
- # normalize format
- if format is None:
- format = cls.default_format
- if format not in [lzma.FORMAT_XZ, lzma.FORMAT_ALONE, lzma.FORMAT_RAW]:
- raise ValueError('invalid format: %s' % format)
-
- # normalize check
- if check is None:
- check = cls.default_check
- if check not in [lzma.CHECK_NONE, lzma.CHECK_CRC32,
- lzma.CHECK_CRC64, lzma.CHECK_SHA256]:
- raise ValueError('invalid check: %s' % check)
-
- # normalize preset
- if preset is None:
- preset = cls.default_preset
- if preset < 0 or preset > 9:
- raise ValueError('invalid preset: %s' % preset)
-
- # handle filters
- if filters:
- # cannot specify both preset and filters
- preset = None
-
- # construct normalized options
- compression_opts = dict(
- format=format, check=check, preset=preset, filters=filters
- )
- return compression_opts
-
- # noinspection PyMethodMayBeStatic
- def decompress(self, cdata, array):
- if self.format == lzma.FORMAT_RAW:
- # filters needed
- filters = self.filters
- else:
- # filters should not be specified
- filters = None
- data = lzma.decompress(cdata, format=self.format, filters=filters)
- src = np.frombuffer(data, dtype=array.dtype).reshape(array.shape)
- np.copyto(array, src)
-
- def compress(self, array):
- data = array.tobytes()
- return lzma.compress(data, format=self.format, check=self.check,
- preset=self.preset, filters=self.filters)
-
-
-registry['lzma'] = LZMACompressor
+try:
+ import lzma
+except ImportError:
+ pass
+else:
+
+ class LZMACompressor(object):
+
+ default_format = lzma.FORMAT_XZ
+ default_check = lzma.CHECK_NONE
+ default_preset = 1
+ default_filters = None
+
+ def __init__(self, compression_opts):
+ # at this point we expect compression_opts to be fully specified and
+ # normalized
+ self.format = compression_opts['format']
+ self.check = compression_opts['check']
+ self.preset = compression_opts['preset']
+ self.filters = compression_opts['filters']
+
+ @classmethod
+ def normalize_compression_opts(cls, compression_opts):
+ """Convenience function to normalize compression options."""
+
+ if compression_opts is None:
+ compression_opts = dict()
+
+ format = compression_opts.get('format', None)
+ check = compression_opts.get('check', None)
+ preset = compression_opts.get('preset', None)
+ filters = compression_opts.get('filters', None)
+
+ # normalize format
+ if format is None:
+ format = cls.default_format
+ if format not in [lzma.FORMAT_XZ, lzma.FORMAT_ALONE, lzma.FORMAT_RAW]:
+ raise ValueError('invalid format: %s' % format)
+
+ # normalize check
+ if check is None:
+ check = cls.default_check
+ if check not in [lzma.CHECK_NONE, lzma.CHECK_CRC32,
+ lzma.CHECK_CRC64, lzma.CHECK_SHA256]:
+ raise ValueError('invalid check: %s' % check)
+
+ # normalize preset
+ if preset is None:
+ preset = cls.default_preset
+ if preset < 0 or preset > 9:
+ raise ValueError('invalid preset: %s' % preset)
+
+ # handle filters
+ if filters:
+ # cannot specify both preset and filters
+ preset = None
+
+ # construct normalized options
+ compression_opts = dict(
+ format=format, check=check, preset=preset, filters=filters
+ )
+ return compression_opts
+
+ # noinspection PyMethodMayBeStatic
+ def decompress(self, cdata, array):
+ if self.format == lzma.FORMAT_RAW:
+ # filters needed
+ filters = self.filters
+ else:
+ # filters should not be specified
+ filters = None
+ data = lzma.decompress(cdata, format=self.format, filters=filters)
+ src = np.frombuffer(data, dtype=array.dtype).reshape(array.shape)
+ np.copyto(array, src)
+
+ def compress(self, array):
+ data = array.tobytes()
+ return lzma.compress(data, format=self.format, check=self.check,
+ preset=self.preset, filters=self.filters)
+
+
+ registry['lzma'] = LZMACompressor
def get_compressor_cls(compression):
|
lzma not available in PY2
|
zarr-developers_zarr
|
train
|
ff3d10377e2b5a1758e6fd9e7e6cbeca15cf9a0e
|
diff --git a/mindmaps-migration/owl/src/test/java/test/io/mindmaps/migration/owl/TestSubProperties.java b/mindmaps-migration/owl/src/test/java/test/io/mindmaps/migration/owl/TestSubProperties.java
index <HASH>..<HASH> 100644
--- a/mindmaps-migration/owl/src/test/java/test/io/mindmaps/migration/owl/TestSubProperties.java
+++ b/mindmaps-migration/owl/src/test/java/test/io/mindmaps/migration/owl/TestSubProperties.java
@@ -1,34 +1,28 @@
package test.io.mindmaps.migration.owl;
-import java.util.Map;
-import java.util.Set;
-
+import io.mindmaps.exception.MindmapsValidationException;
+import io.mindmaps.graql.Graql;
+import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import org.junit.Assert;
-import org.semanticweb.HermiT.Reasoner;
import org.semanticweb.HermiT.Configuration;
+import org.semanticweb.HermiT.Reasoner;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLNamedIndividual;
import org.semanticweb.owlapi.model.OWLOntology;
-import io.mindmaps.graql.Graql;
+import java.util.Map;
+import java.util.Set;
public class TestSubProperties extends TestOwlMindMapsBase {
private IRI baseIri = IRI.create("http://www.workingontologist.org/Examples/Chapter3/shakespeare.owl");
private OWLOntology shakespeare = null;
@Before
- public void loadShakespeare() {
- try {
- shakespeare = loadOntologyFromResource("/io/mindmaps/migration/owl/samples/shakespeare.owl");
- migrator.ontology(shakespeare).graph(graph).migrate();
- migrator.graph().commit();
- }
- catch (Throwable t) {
- t.printStackTrace(System.err);
- System.exit(-1);
- }
+ public void loadShakespeare() throws MindmapsValidationException {
+ shakespeare = loadOntologyFromResource("/io/mindmaps/migration/owl/samples/shakespeare.owl");
+ migrator.ontology(shakespeare).graph(graph).migrate();
+ migrator.graph().commit();
}
@Test
|
Remove System.exit from last OWL migration test (#<I>)
|
graknlabs_grakn
|
train
|
9875823144c4e67d4a4f1826d4ebb82dc2502b5d
|
diff --git a/assets/P2AssetBase.php b/assets/P2AssetBase.php
index <HASH>..<HASH> 100755
--- a/assets/P2AssetBase.php
+++ b/assets/P2AssetBase.php
@@ -254,6 +254,18 @@ class P2AssetBase extends \yii\web\AssetBundle
}
/*
+ * Configures an asset described the 'vendor' pattern.
+ */
+ protected function configureVendorAsset()
+ {
+ // Set $sourcePath
+ $this->sourcePath = $this->assetData['sourcePath'];
+
+ // Set variables...
+ $this->setYiiVariables($this->assetData);
+ }
+
+ /*
* Sets $baseUrl or $sourcePath for 'unpkg' assets
*/
private function setUnpkgPath()
@@ -268,18 +280,6 @@ class P2AssetBase extends \yii\web\AssetBundle
}
}
- /*
- * Configures an asset described the 'vendor' pattern.
- */
- protected function configureVendorAsset()
- {
- // Set $sourcePath
- $this->sourcePath = $this->assetData['sourcePath'];
-
- // Set variables...
- $this->setYiiVariables($this->assetData);
- }
-
// ##### ^ ##### UTILITY FUNCTIONS ##### ^ ##### //
private function assetVersion()
|
Update P2AssetBase.php
|
p2made_yii2-p2y2-base
|
train
|
5c4440dc5b1ebfb860b9901f5558deeecb1a5215
|
diff --git a/nerdamer.core.js b/nerdamer.core.js
index <HASH>..<HASH> 100644
--- a/nerdamer.core.js
+++ b/nerdamer.core.js
@@ -233,6 +233,9 @@ var nerdamer = (function (imports) {
* @param {Number} num
*/
var scientificToDecimal = function (num) {
+ var nsign = Math.sign(num);
+ //remove the sign
+ num = Math.abs(num);
//if the number is in scientific notation remove it
if (/\d+\.?\d*e[\+\-]*\d+/i.test(num)) {
var zero = '0',
@@ -244,26 +247,25 @@ var nerdamer = (function (imports) {
if (sign === -1) {
l = l - coeff_array[0].length;
if (l < 0) {
- num = coeff_array[0].slice(0, l) + '.' + coeff_array[0].slice(l) + (coeff_array.length === 2 ? coeff_array[1] : '');
- }
+ num = coeff_array[0].slice(0, l) + '.' + coeff_array[0].slice(l) + (coeff_array.length === 2 ? coeff_array[1] : '');
+ }
else {
- num = zero + '.' + new Array(l + 1).join(zero) + coeff_array.join('');
+ num = zero + '.' + new Array(l + 1).join(zero) + coeff_array.join('');
}
- }
+ }
else {
var dec = coeff_array[1];
if (dec)
l = l - dec.length;
if (l < 0) {
- num = coeff_array[0] + dec.slice(0, l) + '.' + dec.slice(l);
- }
- else {
- num = coeff_array.join('') + new Array(l + 1).join(zero);
+ num = coeff_array[0] + dec.slice(0, l) + '.' + dec.slice(l);
+ } else {
+ num = coeff_array.join('') + new Array(l + 1).join(zero);
}
}
}
- return num;
+ return nsign < 0 ? '-'+num : num;
};
/**
* Checks if number is a prime number
@@ -5242,7 +5244,7 @@ var nerdamer = (function (imports) {
e = e.split(' ').join('')//strip empty spaces
//replace scientific numbers
- .replace(/\d+\.*\d*e\+?\-?\d+/gi, function (x) {
+ .replace(/\-*\d+\.*\d*e\+?\-?\d+/gi, function (x) {
return scientificToDecimal(x);
})
//allow omission of multiplication after coefficients
|
Update scientificToDecimal sign issue
|
jiggzson_nerdamer
|
train
|
ea2a3fe10712d91fc0a8f6fb1cdf4ce197391ba5
|
diff --git a/spec/dummy_app/db/migrate/20110208155312_set_up_test_tables.rb b/spec/dummy_app/db/migrate/20110208155312_set_up_test_tables.rb
index <HASH>..<HASH> 100644
--- a/spec/dummy_app/db/migrate/20110208155312_set_up_test_tables.rb
+++ b/spec/dummy_app/db/migrate/20110208155312_set_up_test_tables.rb
@@ -105,10 +105,11 @@ class SetUpTestTables < (
t.integer :version_id
t.string :foreign_key_name, null: false
t.integer :foreign_key_id
+ t.string :foreign_type, null: false
end
add_index :version_associations, [:version_id]
add_index :version_associations,
- %i[foreign_key_name foreign_key_id],
+ %i[foreign_key_name foreign_key_id foreign_type],
name: "index_version_associations_on_foreign_key"
create_table :post_versions, force: true do |t|
|
test: dummy_app is compatible with paper_trail-association_tracking <I>
ref: <URL>
|
paper-trail-gem_paper_trail
|
train
|
75a4f51d983c10d2b1ef1748e3c8e6d9b8d0bda9
|
diff --git a/dallinger/command_line.py b/dallinger/command_line.py
index <HASH>..<HASH> 100755
--- a/dallinger/command_line.py
+++ b/dallinger/command_line.py
@@ -114,7 +114,7 @@ def setup_experiment(debug=True, verbose=False, app=None):
# Check that the demo-specific requirements are satisfied.
try:
with open("requirements.txt", "r") as f:
- dependencies = f.readlines()
+ dependencies = [r for r in f.readlines() if r[:3] != "-e "]
except:
dependencies = []
|
Allow requirements specified by URL (#<I>)
|
Dallinger_Dallinger
|
train
|
c5e587f5e5c3cb8b128b948a46fe02804c09e360
|
diff --git a/tests/integration/condition__collection__have_texts_test.py b/tests/integration/condition__collection__have_texts_test.py
index <HASH>..<HASH> 100644
--- a/tests/integration/condition__collection__have_texts_test.py
+++ b/tests/integration/condition__collection__have_texts_test.py
@@ -86,8 +86,8 @@ def test_have_texts_throws_exception(session_browser):
with pytest.raises(TimeoutException) as error:
browser.all('li').should(have.texts('Alex'))
- assert "browser.all(('css selector', 'li')).has texts ('Alex',)" in error.value.msg
- assert "Reason: AssertionError: actual visible_texts: ['Alex', 'Yakov']" in error.value.msg
+ assert "has texts ('Alex',)" in error.value.msg
+ assert "AssertionError: actual visible_texts: ['Alex', 'Yakov']" in error.value.msg
def test_have_text_throws_exception(session_browser):
@@ -102,8 +102,8 @@ def test_have_text_throws_exception(session_browser):
with pytest.raises(TimeoutException) as error:
browser.all('li').should(have.text('Yakov'))
- assert "browser.all(('css selector', 'li')).cached[0].has text Yakov" in error.value.msg
- assert "Reason: AssertionError: actual text: Alex" in error.value.msg
+ assert "has text Yakov" in error.value.msg
+ assert "AssertionError: actual text: Alex" in error.value.msg
def test_have_no_text_throws_exception(session_browser):
@@ -118,8 +118,8 @@ def test_have_no_text_throws_exception(session_browser):
with pytest.raises(TimeoutException) as error:
browser.all('li').should(have.no.text('Alex'))
- assert "browser.all(('css selector', 'li')).cached[0].has no text Alex" in error.value.msg
- assert "Reason: ConditionNotMatchedError: condition not matched" in error.value.msg
+ assert "has no text Alex" in error.value.msg
+ assert "ConditionNotMatchedError: condition not matched" in error.value.msg
def test_have_no_texts_throws_exception(session_browser):
@@ -134,5 +134,6 @@ def test_have_no_texts_throws_exception(session_browser):
with pytest.raises(TimeoutException) as error:
browser.all('li').should(have.no.texts('Alex', 'Yakov'))
- assert "browser.all(('css selector', 'li')).has no texts ('Alex', 'Yakov')" in error.value.msg
- assert "Reason: ConditionNotMatchedError: condition not matched" in error.value.msg
+ # todo: why do we have `has` below, should not it be `have`?
+ assert "has no texts ('Alex', 'Yakov')" in error.value.msg
+ assert "ConditionNotMatchedError: condition not matched" in error.value.msg
|
removed part of error message that do not relate to the condition implementation
|
yashaka_selene
|
train
|
d806a1c4cd904dc9db5dd09932760b797beceac5
|
diff --git a/lib/field_ref.js b/lib/field_ref.js
index <HASH>..<HASH> 100644
--- a/lib/field_ref.js
+++ b/lib/field_ref.js
@@ -1,7 +1,7 @@
-lunr.FieldRef = function (docRef, fieldName) {
+lunr.FieldRef = function (docRef, fieldName, stringValue) {
this.docRef = docRef
this.fieldName = fieldName
- this._stringValue = fieldName + lunr.FieldRef.joiner + docRef
+ this._stringValue = stringValue
}
lunr.FieldRef.joiner = "/"
@@ -16,9 +16,13 @@ lunr.FieldRef.fromString = function (s) {
var fieldRef = s.slice(0, n),
docRef = s.slice(n + 1)
- return new lunr.FieldRef (docRef, fieldRef)
+ return new lunr.FieldRef (docRef, fieldRef, s)
}
lunr.FieldRef.prototype.toString = function () {
+ if (this._stringValue == undefined) {
+ this._stringValue = this.fieldName + lunr.FieldRef.joiner + this.docRef
+ }
+
return this._stringValue
}
|
Stop needlessly recreating field ref string
|
olivernn_lunr.js
|
train
|
afd7e618821517fc8403c4f41906fd8b160c537e
|
diff --git a/test/test_ocf_physical_container.rb b/test/test_ocf_physical_container.rb
index <HASH>..<HASH> 100644
--- a/test/test_ocf_physical_container.rb
+++ b/test/test_ocf_physical_container.rb
@@ -52,4 +52,14 @@ class TestOCFPhysicalContainer < Test::Unit::TestCase
@container = @class.new(@container_path)
end
end
+
+ class TestFile < self
+ include ConcreteContainer
+
+ def setup
+ super
+ @class = EPUB::OCF::PhysicalContainer::File
+ @container = @class.new(@container_path)
+ end
+ end
end
|
Add test class for OCF::PhysicalContainer::File
|
KitaitiMakoto_epub-parser
|
train
|
cad77f56abcdd84b26df48087da7c767a7d0cfaa
|
diff --git a/endpoints/api_config.py b/endpoints/api_config.py
index <HASH>..<HASH> 100644
--- a/endpoints/api_config.py
+++ b/endpoints/api_config.py
@@ -53,7 +53,8 @@ from . import messages
from . import remote
from . import resource_container
from . import types as endpoints_types
-from .types import Issuer, LimitDefinition, Namespace # originally in this module
+# originally in this module
+from .types import Issuer, LimitDefinition, Namespace
from . import users_id_token
from . import util as endpoints_util
|
Just want to adjust this comment slightly. (#<I>)
|
cloudendpoints_endpoints-python
|
train
|
27ff000e973fd838867197d950867a81d0f63010
|
diff --git a/src/Playlist.js b/src/Playlist.js
index <HASH>..<HASH> 100644
--- a/src/Playlist.js
+++ b/src/Playlist.js
@@ -362,6 +362,7 @@ export default class {
this.timeSelection = {
start,
end,
+ isSegment : (start!=end)
};
this.cursor = start;
}
@@ -637,7 +638,7 @@ export default class {
this.ee.emit('timeupdate', playbackSeconds);
this.animationRequest = window.requestAnimationFrame(this.updateEditor.bind(this, playbackSeconds));
} else {
- if ((cursorPos+elapsed) >= (this.getTimeSelection().end!=this.getTimeSelection().start)?this.getTimeSelection().end:this.duration){
+ if ((cursorPos+elapsed) >= (this.getTimeSelection().isSegment)?this.getTimeSelection().end:this.duration){
this.ee.emit('finished');
}
this.stopAnimation();
@@ -686,7 +687,7 @@ export default class {
let activeTrack = this.getActiveTrack();
let trackElements = this.tracks.map((track) => {
return track.render(this.getTrackRenderData({
- "isActive": (this.getTimeSelection().start!=this.getTimeSelection().end)?((activeTrack === track) ? true : false):true,
+ "isActive": (this.getTimeSelection().isSegment)?((activeTrack === track) ? true : false):true,
"shouldPlay": this.shouldTrackPlay(track),
"soloed": this.soloedTracks.indexOf(track) > -1,
"muted": this.mutedTracks.indexOf(track) > -1
|
Code update as mentioned in #<I>
|
naomiaro_waveform-playlist
|
train
|
8d6681c2e6c17181864261b45b7a93738ce4dba0
|
diff --git a/classes/ezjscserverfunctionsautosave.php b/classes/ezjscserverfunctionsautosave.php
index <HASH>..<HASH> 100644
--- a/classes/ezjscserverfunctionsautosave.php
+++ b/classes/ezjscserverfunctionsautosave.php
@@ -187,12 +187,9 @@ class ezjscServerFunctionsAutosave extends ezjscServerFunctions
);
$version->setAttribute( 'modified', time() );
- $status = eZContentObjectVersion::STATUS_INTERNAL_DRAFT;
- if ( $http->hasPostVariable( 'StoreExitButton' ) )
- {
- $status = eZContentObjectVersion::STATUS_DRAFT;
- }
- $version->setAttribute( 'status', $status );
+
+ // Do not use internal draft since it simulates the saving action
+ $version->setAttribute( 'status', eZContentObjectVersion::STATUS_DRAFT );
$attributesToStore = array();
foreach( $fetchResult['attribute-input-map'] as $id => $value )
|
Fix EZP-<I>: Drafts disappear from dashboard after being edited and resaved
|
ezsystems_ezautosave
|
train
|
18047add47bca70d1a4476c12b2da086f9718591
|
diff --git a/src/main/java/org/zeromq/ZMQException.java b/src/main/java/org/zeromq/ZMQException.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/zeromq/ZMQException.java
+++ b/src/main/java/org/zeromq/ZMQException.java
@@ -43,6 +43,18 @@ public class ZMQException extends RuntimeException
code = errno;
}
+ public ZMQException(String message, int errno)
+ {
+ super(message);
+ code = errno;
+ }
+
+ public ZMQException(ZMQException cause)
+ {
+ super(cause.getMessage(), cause);
+ code = cause.code;
+ }
+
public int getErrorCode()
{
return code;
|
Added constructors to ZMQException
|
zeromq_jeromq
|
train
|
5dec0ec9b8d174f820f8249955c99df1f42a4952
|
diff --git a/config/initializers/rack_attack.rb b/config/initializers/rack_attack.rb
index <HASH>..<HASH> 100644
--- a/config/initializers/rack_attack.rb
+++ b/config/initializers/rack_attack.rb
@@ -1,32 +1,4 @@
class Rack::Attack
- ### Configure Cache ###
-
- # If you don't want to use Rails.cache (Rack::Attack's default), then
- # configure it here.
- #
- # Note: The store is only used for throttling (not blacklisting and
- # whitelisting). It must implement .increment and .write like
- # ActiveSupport::Cache::Store
-
- # Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
-
- ### Throttle Spammy Clients ###
-
- # If any single client IP is making tons of requests, then they're
- # probably malicious or a poorly-configured scraper. Either way, they
- # don't deserve to hog all of the app server's CPU. Cut them off!
- #
- # Note: If you're serving assets through rack, those requests may be
- # counted by rack-attack and this throttle may be activated too
- # quickly. If so, enable the condition to exclude them from tracking.
-
- # Throttle all requests by IP (60rpm)
- #
- # Key: "rack::attack:#{Time.now.to_i/:period}:req/ip:#{req.ip}"
- # throttle('req/ip', :limit => 300, :period => 5.minutes) do |req|
- # req.ip # unless req.path.start_with?('/assets')
- # end
-
### Prevent Brute-Force Login Attacks ###
# The most common brute-force login attack is a brute-force password
@@ -39,8 +11,15 @@ class Rack::Attack
# Throttle POST requests to /login by IP address
#
# Key: "rack::attack:#{Time.now.to_i/:period}:logins/ip:#{req.ip}"
- throttle('logins/ip', limit: 5, period: 20.seconds) do |req|
- req.ip if req.path == '/session' && req.post?
+ protected_paths = [
+ "/users", # sign up
+ "/session", # sign in
+ "/passwords" # forgot password
+ ]
+ paths_regex = Regexp.union(protected_paths.map { |path| /\A#{Regexp.escape(path)}\z/ })
+
+ throttle('clearance/ip', limit: 100, period: 10.minutes) do |req|
+ req.ip if req.path =~ paths_regex && req.post?
end
# Throttle POST requests to /login by email param
@@ -51,8 +30,8 @@ class Rack::Attack
# throttle logins for another user and force their login requests to be
# denied, but that's not very common and shouldn't happen to you. (Knock
# on wood!)
- throttle("logins/handler", limit: 5, period: 20.seconds) do |req|
- if req.path == '/session' && req.post?
+ throttle("logins/handler", limit: 100, period: 10.minutes) do |req|
+ if req.path == "/session" && req.post?
# return the handler if present, nil otherwise
req.params['session']['who'].presence
end
@@ -66,9 +45,24 @@ class Rack::Attack
# If you want to return 503 so that the attacker might be fooled into
# believing that they've successfully broken your app (or you just want to
# customize the response), then uncomment these lines.
- # self.throttled_response = lambda do |env|
- # [ 503, # status
- # {}, # headers
- # ['']] # body
+ # self.throttled_response = lambda do |_env|
+ # [503, {}, ['Service Temporarily Unavailable']]
# end
+
+ ### Logging ###
+
+ ActiveSupport::Notifications.subscribe('rack.attack') do |_name, _start, _finish, _request_id, payload|
+ if payload.env['rack.attack.match_type'] == :throttle
+ data = {
+ status: 'throttled',
+ ip: payload.ip.to_s,
+ method: payload.env["REQUEST_METHOD"],
+ path: payload.env["REQUEST_PATH"],
+ matched: payload.env["rack.attack.matched"],
+ discriminator: payload.env["rack.attack.match_discriminator"],
+ match_data: payload.env["rack.attack.match_data"]
+ }
+ Rails.logger.info data
+ end
+ end
end
diff --git a/test/test_helper.rb b/test/test_helper.rb
index <HASH>..<HASH> 100644
--- a/test/test_helper.rb
+++ b/test/test_helper.rb
@@ -16,7 +16,10 @@ class ActiveSupport::TestCase
include FactoryGirl::Syntax::Methods
include GemHelpers
- setup { I18n.locale = :en }
+ setup do
+ I18n.locale = :en
+ Rails.cache.clear
+ end
def page
Capybara::Node::Simple.new(@response.body)
|
Protect more paths and log throttled requests
|
rubygems_rubygems.org
|
train
|
d0bbcc14b561784c0c6ea08d5f74e0008c990614
|
diff --git a/lib/disneytokyo/index.js b/lib/disneytokyo/index.js
index <HASH>..<HASH> 100644
--- a/lib/disneytokyo/index.js
+++ b/lib/disneytokyo/index.js
@@ -110,7 +110,8 @@ class DisneyTokyoPark extends Park {
return this.HTTP({
url: `http://info.tokyodisneyresort.jp/rt/s/realtime/${this[s_parkID]}_attraction.html`,
headers: {
- "Cookie": `tdrloc=${encodeURIComponent(access_token)}`
+ "Cookie": `tdrloc=${encodeURIComponent(access_token)}`,
+ connection: "keep-alive",
}
});
});
@@ -206,7 +207,8 @@ class DisneyTokyoPark extends Park {
url: `http://www.tokyodisneyresort.jp/api/v1/wapi_monthlycalendars/detail/ym:${month}/`,
headers: {
"Referer": `http://www.tokyodisneyresort.jp/en/attraction/lists/park:${this[s_parkID]}`,
- "X-Requested-With": "XMLHttpRequest"
+ "X-Requested-With": "XMLHttpRequest",
+ connection: "keep-alive",
},
forceJSON: true
}).then(function(body) {
@@ -241,13 +243,14 @@ class DisneyTokyoPark extends Park {
// request cookie for accessing wait times using a random location in the park
this.HTTP({
- url: `http://info.tokyodisneyresort.jp/s/gps/${this[s_parkID]}_index.html`,
+ url: `https://info.tokyodisneyresort.jp/rt/s/gps/${this[s_parkID]}_index.html`,
data: {
nextUrl: `http://info.tokyodisneyresort.jp/rt/s/realtime/${this[s_parkID]}_attraction.html`,
lat: randomGeoLocation.LatitudeRaw,
lng: randomGeoLocation.LongitudeRaw
},
headers: {
+ connection: "keep-alive",
"Referer": `http://www.tokyodisneyresort.jp/en/attraction/lists/park:${this[s_parkID]}`,
},
// don't actually follow the redirect, we just want the cookie
@@ -313,6 +316,7 @@ class DisneyTokyoPark extends Park {
forceJSON: true,
headers: {
"Referer": `http://www.tokyodisneyresort.jp/en/attraction/lists/park:${this[s_parkID]}`,
+ connection: "keep-alive",
},
}).then(function(body) {
if (!body || !body.entries || !body.entries.length) {
|
Fix Tokyo Disneyland (#<I>)
* Fix Tokyo Disneyland rejecting any requests without "Connection: Keep-Alive" header.
* Add connection: "keep-alive" to further HTTP requests for fetching opening times.
|
cubehouse_themeparks
|
train
|
f2bcf2fc69ab170589394368ff3d8bc435c3cf74
|
diff --git a/tests/PHPUnit/UI b/tests/PHPUnit/UI
index <HASH>..<HASH> 160000
--- a/tests/PHPUnit/UI
+++ b/tests/PHPUnit/UI
@@ -1 +1 @@
-Subproject commit 4e77f9e1883da65340945af6694dfb31fa3e31ff
+Subproject commit 5655e6e04b106f70c1ec87a2e01abc04f14c8741
diff --git a/tests/PHPUnit/UITest.php b/tests/PHPUnit/UITest.php
index <HASH>..<HASH> 100644
--- a/tests/PHPUnit/UITest.php
+++ b/tests/PHPUnit/UITest.php
@@ -62,10 +62,17 @@ abstract class UITest extends IntegrationTestCase
for ($i = 0; $i < count($urlsToTest); $i += self::SCREENSHOT_GROUP_SIZE) {
$urls = array();
for ($j = $i; $j != $i + self::SCREENSHOT_GROUP_SIZE && $j < count($urlsToTest); ++$j) {
- list($name, $urlQuery) = current($urlsToTest);
+ $currentTest = current($urlsToTest);
+
+ if (count($currentTest) == 2) {
+ list($name, $urlQuery) = $currentTest;
+ $jsToTest = false;
+ } else {
+ list($name, $urlQuery, $jsToTest) = $currentTest;
+ }
list($processedScreenshotPath, $expectedScreenshotPath) = self::getProcessedAndExpectedScreenshotPaths($name);
- $urls[] = array($processedScreenshotPath, self::getProxyUrl() . $urlQuery);
+ $urls[] = array($processedScreenshotPath, self::getProxyUrl() . $urlQuery, $jsToTest);
next($urlsToTest);
}
diff --git a/tests/resources/screenshot-capture/capture.js b/tests/resources/screenshot-capture/capture.js
index <HASH>..<HASH> 100644
--- a/tests/resources/screenshot-capture/capture.js
+++ b/tests/resources/screenshot-capture/capture.js
@@ -32,6 +32,7 @@ PageRenderer.prototype = {
this.outputPath = this.urls[this.urlIndex][0];
this.url = this.urls[this.urlIndex][1];
+ this.jsToTest = this.urls[this.urlIndex][2];
console.log("SAVING " + this.url + " at " + this._getElapsedExecutionTime());
@@ -44,10 +45,33 @@ PageRenderer.prototype = {
this.webpage.viewportSize = {width:1350, height:768};
- this.webpage.open(this.url);
+ var self = this;
+ this.webpage.open(this.url, function () {
+ if (self.jsToTest) {
+ self.webpage.evaluate(function (js) {
+ var $ = window.jQuery;
+ eval(js);
+ }, self.jsToTest);
+ }
+
+ self._setNoAjaxCheckTimeout();
+ });
this._setPageTimeouts();
},
+ _setNoAjaxCheckTimeout: function () {
+ var url = this.url, self = this;
+
+ // in case there are no ajax requests, try triggering after a couple secs
+ setTimeout(function () {
+ if (url == self.url) {
+ self.webpage.evaluate(function () {
+ window.piwik.ajaxRequestFinished();
+ });
+ }
+ }, 5000);
+ },
+
_setPageTimeouts: function () {
var url = this.url, self = this;
diff --git a/tests/resources/screenshot-override/override.js b/tests/resources/screenshot-override/override.js
index <HASH>..<HASH> 100644
--- a/tests/resources/screenshot-override/override.js
+++ b/tests/resources/screenshot-override/override.js
@@ -38,9 +38,4 @@
window.piwik.ajaxRequestFinished = triggerRenderIfNoAjax;
window.piwik._triggerRenderInsane = triggerRenderInsane;
- // in case there are no ajax requests, try triggering after a couple secs
- setTimeout(function () {
- triggerRenderIfNoAjax();
- }, 5000);
-
}(jQuery));
\ No newline at end of file
|
Allow screenshot tests to execute JavaScript before capturing screenshots.
|
matomo-org_matomo
|
train
|
28bbef58bf6edc7242c7aa3855d54acdd97cb2cb
|
diff --git a/epub_clean/clean.py b/epub_clean/clean.py
index <HASH>..<HASH> 100644
--- a/epub_clean/clean.py
+++ b/epub_clean/clean.py
@@ -76,6 +76,10 @@ def html_to_xhtml(html_unicode_string):
DOCTYPE_string = constants.xhtml_doctype_string
string_with_open_singletons = lxml.etree.tostring(node, pretty_print=True,
encoding='unicode', doctype=DOCTYPE_string)
+ xhtml_unicode_string = string_with_open_singletons
#close singleton tag_dictionary
- xhtml_unicode_string = string_with_open_singletons.replace('<br/>', '<br />')
+ for tag in constants.SINGLETON_TAG_LIST:
+ xhtml_unicode_string = xhtml_unicode_string.replace(
+ '<' + tag + '/>',
+ '<' + tag + ' />')
return xhtml_unicode_string
diff --git a/epub_clean/constants.py b/epub_clean/constants.py
index <HASH>..<HASH> 100644
--- a/epub_clean/constants.py
+++ b/epub_clean/constants.py
@@ -41,6 +41,21 @@ SUPPORTED_TAGS = {
'ul': ['class', 'id'],
'var': []
}
+SINGLETON_TAG_LIST = [
+ 'area',
+ 'base',
+ 'br',
+ 'col',
+ 'command',
+ 'embed',
+ 'hr',
+ 'img',
+ 'input',
+ 'link',
+ 'meta',
+ 'param',
+ 'source',
+ ]
xhtml_doctype_string = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">'
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
TEST_DIR = os.path.join(BASE_DIR, 'test_files')
|
generalized open singletons to beyond br
|
wcember_pypub
|
train
|
b38aca3728f4f7bd5477be430f386ec4b826a4d1
|
diff --git a/bearlib/__init__.py b/bearlib/__init__.py
index <HASH>..<HASH> 100644
--- a/bearlib/__init__.py
+++ b/bearlib/__init__.py
@@ -111,6 +111,32 @@ def daemonize(config):
os.umask(077)
+def escXML(text, escape_quotes=False):
+ if type(text) != types.UnicodeType:
+ if type(text) == types.IntType:
+ s = str(text)
+ else:
+ s = text
+ s = list(unicode(s, 'utf-8', 'ignore'))
+ else:
+ s = list(text)
+
+ cc = 0
+ matches = ('&', '<', '"', '>')
+
+ for c in s:
+ if c in matches:
+ if c == '&':
+ s[cc] = u'&'
+ elif c == '<':
+ s[cc] = u'<'
+ elif c == '>':
+ s[cc] = u'>'
+ elif escape_quotes:
+ s[cc] = u'"'
+ cc += 1
+ return ''.join(s)
+
def relativeDelta(td):
s = ''
if td.days < 0:
@@ -192,14 +218,19 @@ class bConfig(object):
for key in _config:
setattr(self, key, getattr(self.options, key))
- def loadConfigFile(self):
- if os.path.isfile(self.config):
+ def loadConfigFile(self, configFile=None):
+ if configFile is None:
+ filename = self.config
+ else:
+ filename = configFile
+
+ if os.path.isfile(filename):
cfg = SafeConfigParser()
- cfg.readfp(open(self.config))
+ cfg.readfp(open(filename))
for section in cfg.sections():
for key, value in cfg.items(section):
- if section == self.ourname:
+ if section == self.ourname:
setattr(self, key, value)
else:
if not hasattr(self, section):
|
added escXML and also made it so the config file loading code can
be passed a filename to override (or bypass) the command line parsing
|
bear_bearlib
|
train
|
932cbae03a146d377846126f984b37b10ae1a5ff
|
diff --git a/ion-tests b/ion-tests
index <HASH>..<HASH> 160000
--- a/ion-tests
+++ b/ion-tests
@@ -1 +1 @@
-Subproject commit b2ca9ef2ccb630624d08f1d48e16ec76575f4410
+Subproject commit f7a4999a416b98a4ab454ba18843a177404b7a45
diff --git a/src/software/amazon/ion/impl/lite/IonContainerLite.java b/src/software/amazon/ion/impl/lite/IonContainerLite.java
index <HASH>..<HASH> 100644
--- a/src/software/amazon/ion/impl/lite/IonContainerLite.java
+++ b/src/software/amazon/ion/impl/lite/IonContainerLite.java
@@ -62,7 +62,15 @@ abstract class IonContainerLite
IonValueLite copy = child.clone(childContext);
if (isStruct) {
- copy.setFieldNameSymbol(child.getKnownFieldNameSymbol());
+ if(child.getFieldName() == null) {
+ // when name is null it could be a sid 0 so we need to perform the full symbol token lookup.
+ // this is expensive so only do it when necessary
+ copy.setFieldNameSymbol(child.getKnownFieldNameSymbol());
+ }
+ else {
+ // if we have a non null name copying it is sufficient
+ copy.setFieldName(child.getFieldName());
+ }
}
this._children[i] = copy;
}
diff --git a/test/software/amazon/ion/TestUtils.java b/test/software/amazon/ion/TestUtils.java
index <HASH>..<HASH> 100644
--- a/test/software/amazon/ion/TestUtils.java
+++ b/test/software/amazon/ion/TestUtils.java
@@ -145,6 +145,8 @@ public class TestUtils
, "good/utf16.ion" // TODO amzn/ion-java#61
, "good/utf32.ion" // TODO amzn/ion-java#61
, "good/whitespace.ion" // TODO amzn/ion-java#104
+ , "bad/negativeIntZero.10n" // TODO amzn/ion-java#138
+ , "bad/negativeIntZeroLn.10n" // TODO amzn/ion-java#138
);
|
Performance improvment for struct clones
Adding a check to only perform the SID lookups if and only if we don't
have a name. If we have a name simply copying the name is sufficient
|
amzn_ion-java
|
train
|
052a42401aa90436222a6457f93ba0635e4aad0c
|
diff --git a/supply/lib/supply/uploader.rb b/supply/lib/supply/uploader.rb
index <HASH>..<HASH> 100644
--- a/supply/lib/supply/uploader.rb
+++ b/supply/lib/supply/uploader.rb
@@ -155,10 +155,11 @@ module Supply
def update_track(apk_version_codes)
UI.message("Updating track '#{Supply.config[:track]}'...")
+ check_superseded_tracks(apk_version_codes) if Supply.config[:check_superseded_tracks]
+
if Supply.config[:track].eql? "rollout"
client.update_track(Supply.config[:track], Supply.config[:rollout], apk_version_codes)
else
- check_superseded_tracks(apk_version_codes) if Supply.config[:check_superseded_tracks]
client.update_track(Supply.config[:track], 1.0, apk_version_codes)
end
end
@@ -171,7 +172,7 @@ module Supply
max_apk_version_code = apk_version_codes.max
max_tracks_version_code = nil
- tracks = ["production", "beta", "alpha"]
+ tracks = ["production", "rollout", "beta", "alpha"]
config_track_index = tracks.index(Supply.config[:track])
tracks.each_index do |track_index|
|
Check superseded tracks for rollout in supply (already works for production, beta and alpha). (#<I>)
|
fastlane_fastlane
|
train
|
4f3f9ee78a2d71624061f49656bf28b966feb1e7
|
diff --git a/estnltk/taggers/text_segmentation/compound_token_tagger.py b/estnltk/taggers/text_segmentation/compound_token_tagger.py
index <HASH>..<HASH> 100644
--- a/estnltk/taggers/text_segmentation/compound_token_tagger.py
+++ b/estnltk/taggers/text_segmentation/compound_token_tagger.py
@@ -31,6 +31,8 @@ from .patterns import case_endings_patterns, number_fixes_patterns
# Pattern for checking whether the string contains any letters
_letter_pattern = re.compile(r'''([{LETTERS}]+)'''.format(**MACROS), re.X)
+# Pattern for detecting if the string consists of repeated hyphens only
+_only_hyphens_pattern = re.compile('^(-{2,})$')
# List containing words that should be ignored during the normalization of words with hyphens
DEFAULT_IGNORE_LIST = os.path.join( PACKAGE_PATH, 'taggers', 'text_segmentation', 'ignorable_words_with_hyphens.csv')
@@ -328,11 +330,15 @@ class CompoundTokenTagger(Tagger):
hyp_start = layers[ self._input_tokens_layer ][hyphenation_start].start
hyp_end = layers[ self._input_tokens_layer ][i-1].end
text_snippet = raw_text[hyp_start:hyp_end]
- if _letter_pattern.search(text_snippet):
- # The text snippet should contain at least one letter to be
- # considered as a potentially hyphenated word;
- # This serves to leave out numeric ranges like
- # "15-17.04." or "920-980"
+ if _letter_pattern.search(text_snippet) or _only_hyphens_pattern.match(text_snippet):
+ # Conditions:
+ # A) The text snippet should contain at least one letter to be
+ # considered as a potentially hyphenated word;
+ # This serves to leave out numeric ranges like
+ # "15-17.04." or "920-980"
+ # B) The text snippet can consist of repeated hyphens only:
+ # in such case, repeated hyphens stand out as a dash
+ # ("mõttekriips");
spans = layers[self._input_tokens_layer][hyphenation_start:i].spans
record = {'type': ('hyphenation',),
'normalized': self._normalize_word_with_hyphens(text_snippet)}
diff --git a/estnltk/tests/test_tokenizers/test_compound_token_tagger.py b/estnltk/tests/test_tokenizers/test_compound_token_tagger.py
index <HASH>..<HASH> 100644
--- a/estnltk/tests/test_tokenizers/test_compound_token_tagger.py
+++ b/estnltk/tests/test_tokenizers/test_compound_token_tagger.py
@@ -110,6 +110,10 @@ class CompoundTokenTaggerTest(unittest.TestCase):
'expected_words': ['Mis', 'lil-li', 'müüs', 'Tiit', '10e', 'krooniga', '?'] }, \
{ 'text': 'See on vää-ää-ääga huvitav!', \
'expected_words': ['See', 'on', 'vää-ää-ääga', 'huvitav', '!'] },\
+ # Tokens with repeated hyphens: keep these together as they make up dashes ('mõttekriipsud')
+ { 'text': 'Tõepoolest -- paar aastat tagasi oli olukord teine. Seega -- inimlikust vaatepunktist liiga keeruline.', \
+ 'expected_words': ['Tõepoolest', '--', 'paar', 'aastat', 'tagasi', 'oli', 'olukord', 'teine', '.', \
+ 'Seega', '--', 'inimlikust', 'vaatepunktist', 'liiga', 'keeruline', '.'] },\
# Negative patterns: numeric ranges should not be considered as words with hyphens!
{ 'text': "14.04 jäi kaal nulli , 15-17.04. tuli korjet 6 kg kokku.", \
'expected_words': ['14.04', 'jäi', 'kaal', 'nulli', ',', '15', '-', '17.04', '.', 'tuli', 'korjet', '6', 'kg', 'kokku', '.'] },\
|
Updated CompoundTokenTagger: added detecting and compounding dashes
|
estnltk_estnltk
|
train
|
77cc6f460d00cf35a7c910b3ebe3141fdcb2a8ba
|
diff --git a/yowsup/layers/protocol_media/layer.py b/yowsup/layers/protocol_media/layer.py
index <HASH>..<HASH> 100644
--- a/yowsup/layers/protocol_media/layer.py
+++ b/yowsup/layers/protocol_media/layer.py
@@ -6,12 +6,14 @@ from .protocolentities import DocumentDownloadableMediaMessageProtocolEntity
from .protocolentities import LocationMediaMessageProtocolEntity
from .protocolentities import ContactMediaMessageProtocolEntity
from .protocolentities import RequestUploadIqProtocolEntity, ResultRequestUploadIqProtocolEntity
+from .protocolentities import MediaMessageProtocolEntity
from yowsup.layers.protocol_iq.protocolentities import IqProtocolEntity, ErrorIqProtocolEntity
+import logging
-class YowMediaProtocolLayer(YowProtocolLayer):
+logger = logging.getLogger(__name__)
- # EVENT_REQUEST_UPLOAD = "org.openwhatsapp.org.yowsup.event.protocol_media.request_upload"
+class YowMediaProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"message": (self.recvMessageStanza, self.sendMessageEntity),
@@ -56,6 +58,9 @@ class YowMediaProtocolLayer(YowProtocolLayer):
elif mediaNode.getAttributeValue("mediatype") == "document":
entity = DocumentDownloadableMediaMessageProtocolEntity.fromProtocolTreeNode(node)
self.toUpper(entity)
+ else:
+ logger.warn("Unsupported mediatype: %s, will send receipts" % mediaNode.getAttributeValue("mediatype"))
+ self.toLower(MediaMessageProtocolEntity.fromProtocolTreeNode(node).ack(True).toProtocolTreeNode())
def sendIq(self, entity):
"""
diff --git a/yowsup/layers/protocol_media/protocolentities/message_media.py b/yowsup/layers/protocol_media/protocolentities/message_media.py
index <HASH>..<HASH> 100644
--- a/yowsup/layers/protocol_media/protocolentities/message_media.py
+++ b/yowsup/layers/protocol_media/protocolentities/message_media.py
@@ -2,6 +2,9 @@ from yowsup.layers.protocol_messages.protocolentities.protomessage import Protom
from yowsup.layers.protocol_media.protocolentities.attributes.attributes_media import MediaAttributes
from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message import MessageAttributes
+import logging
+logger = logging.getLogger(__name__)
+
class MediaMessageProtocolEntity(ProtomessageProtocolEntity):
TYPE_MEDIA_IMAGE = "image"
@@ -104,7 +107,8 @@ class MediaMessageProtocolEntity(ProtomessageProtocolEntity):
@media_type.setter
def media_type(self, value):
- assert value in MediaMessageProtocolEntity.TYPES_MEDIA
+ if value not in MediaMessageProtocolEntity.TYPES_MEDIA:
+ logger.warn("media type: '%s' is not supported" % value)
self._media_type = value
def toProtocolTreeNode(self):
|
[fix] improve handling of unsupported media msgs
Will now auto send receipts for messages with unsupported
media types.
|
tgalal_yowsup
|
train
|
273cedf626dd0dae164049c430e39faf56c1764e
|
diff --git a/generator/classes/propel/engine/builder/om/php5/PHP5NestedSetPeerBuilder.php b/generator/classes/propel/engine/builder/om/php5/PHP5NestedSetPeerBuilder.php
index <HASH>..<HASH> 100644
--- a/generator/classes/propel/engine/builder/om/php5/PHP5NestedSetPeerBuilder.php
+++ b/generator/classes/propel/engine/builder/om/php5/PHP5NestedSetPeerBuilder.php
@@ -589,6 +589,9 @@ abstract class ".$this->getClassname()." extends ".$this->getPeerBuilder()->getC
}
\$destLeft = \$parent->getLeftValue() + 1;
self::updateDBNode(\$child, \$destLeft, \$con);
+
+ // Update all loaded nodes
+ self::updateLoadedNode(\$parent, 2, \$con);
}
";
}
@@ -613,6 +616,9 @@ abstract class ".$this->getClassname()." extends ".$this->getPeerBuilder()->getC
}
\$destLeft = \$parent->getRightValue();
self::updateDBNode(\$child, \$destLeft, \$con);
+
+ // Update all loaded nodes
+ self::updateLoadedNode(\$parent, 2, \$con);
}
";
}
@@ -637,6 +643,9 @@ abstract class ".$this->getClassname()." extends ".$this->getPeerBuilder()->getC
}
\$destLeft = \$dest->getLeftValue();
self::updateDBNode(\$node, \$destLeft, \$con);
+
+ // Update all loaded nodes
+ self::updateLoadedNode(\$parent, 2, \$con);
}
";
}
@@ -662,6 +671,9 @@ abstract class ".$this->getClassname()." extends ".$this->getPeerBuilder()->getC
\$destLeft = \$dest->getRightValue();
\$destLeft = \$destLeft + 1;
self::updateDBNode(\$node, \$destLeft, \$con);
+
+ // Update all loaded nodes
+ self::updateLoadedNode(\$parent, 2, \$con);
}
";
}
|
Add a call to updateLoadedNode() in moveToXxxYyyOf() after their task done.
Closes #<I>
|
propelorm_Propel
|
train
|
f05d05a3af6a98189af7f95e5229d8e2108321b7
|
diff --git a/src/main/java/com/prometheus/jmx4prometheus/JmxScraper.java b/src/main/java/com/prometheus/jmx4prometheus/JmxScraper.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/prometheus/jmx4prometheus/JmxScraper.java
+++ b/src/main/java/com/prometheus/jmx4prometheus/JmxScraper.java
@@ -62,33 +62,35 @@ public class JmxScraper {
String url = "service:jmx:rmi:///jndi/rmi://" + host_port + "/jmxrmi";
JMXServiceURL serviceUrl = new JMXServiceURL(url);
JMXConnector jmxc = JMXConnectorFactory.connect(serviceUrl, null);
- MBeanServerConnection beanConn = jmxc.getMBeanServerConnection();
-
- // Query MBean names
- Set<ObjectName> mBeanNames =
- new TreeSet<ObjectName>(beanConn.queryNames(null, null));
-
- if (blacklist.size() > 0) {
- for (ObjectName name : mBeanNames) {
- String beanStr = name.toString();
- if (!checkBlacklisted(beanStr) || checkWhitelisted(beanStr)) {
- scrapeBean(beanConn, name);
+ try {
+ MBeanServerConnection beanConn = jmxc.getMBeanServerConnection();
+
+ // Query MBean names
+ Set<ObjectName> mBeanNames =
+ new TreeSet<ObjectName>(beanConn.queryNames(null, null));
+
+ if (blacklist.size() > 0) {
+ for (ObjectName name : mBeanNames) {
+ String beanStr = name.toString();
+ if (!checkBlacklisted(beanStr) || checkWhitelisted(beanStr)) {
+ scrapeBean(beanConn, name);
+ }
}
- }
- } else if (whitelist.size() > 0) {
- for (ObjectName name : mBeanNames) {
- String beanStr = name.toString();
- if (checkWhitelisted(beanStr)) {
+ } else if (whitelist.size() > 0) {
+ for (ObjectName name : mBeanNames) {
+ String beanStr = name.toString();
+ if (checkWhitelisted(beanStr)) {
+ scrapeBean(beanConn, name);
+ }
+ }
+ } else {
+ for (ObjectName name : mBeanNames) {
scrapeBean(beanConn, name);
}
}
- } else {
- for (ObjectName name : mBeanNames) {
- scrapeBean(beanConn, name);
- }
+ } finally {
+ jmxc.close();
}
-
- jmxc.close();
}
private void scrapeBean(MBeanServerConnection beanConn, ObjectName mbeanName) throws Exception {
|
Wrap 'close' statement in a finally.
Looks like there's no timeout on these connections so they hang
around for ever. As each connection causes a thread on the target
JVM it means we could create lots of threads on the process we're
monitoring.
|
prometheus_jmx_exporter
|
train
|
7215130ff518eb33a51d07c4264a105c5a90bb24
|
diff --git a/holoviews/plotting/plot.py b/holoviews/plotting/plot.py
index <HASH>..<HASH> 100644
--- a/holoviews/plotting/plot.py
+++ b/holoviews/plotting/plot.py
@@ -215,7 +215,7 @@ class Plot(param.Parameterized):
# If we do not have the Document lock, schedule refresh as callback
self._triggering += [s for p in self.traverse(lambda x: x, [Plot])
for s in getattr(p, 'streams', []) if s._triggering]
- if self.document.session_context:
+ if self.document and self.document.session_context:
self.document.add_next_tick_callback(self.refresh)
return
|
Add check if document has already been set in server mode (#<I>)
|
pyviz_holoviews
|
train
|
2aa9a35e4ea1acb1b9e312c8e2b6b69b8e1877c7
|
diff --git a/mod/scorm/api.php b/mod/scorm/api.php
index <HASH>..<HASH> 100644
--- a/mod/scorm/api.php
+++ b/mod/scorm/api.php
@@ -66,6 +66,9 @@
} else {
print_error('cannotfindsco', 'scorm');
}
+ if (!$sco = scorm_get_sco($scoid)) {
+ print_error('cannotfindsco', 'scorm');
+ }
$scorm->version = strtolower(clean_param($scorm->version, PARAM_SAFEDIR)); // Just to be safe
if (file_exists($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'.js.php')) {
include_once($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'.js.php');
diff --git a/mod/scorm/datamodels/scorm_12.js.php b/mod/scorm/datamodels/scorm_12.js.php
index <HASH>..<HASH> 100644
--- a/mod/scorm/datamodels/scorm_12.js.php
+++ b/mod/scorm/datamodels/scorm_12.js.php
@@ -626,7 +626,7 @@ var API = new SCORMapi1_2();
// pull in the debugging utilities
if (debugging('',DEBUG_DEVELOPER)) {
include_once($CFG->dirroot.'/mod/scorm/datamodels/debug.js.php');
- echo 'AppendToLog("Moodle SCORM 1.2 API Loaded", 0);';
+ echo 'AppendToLog("Moodle SCORM 1.2 API Loaded, Activity: '.$scorm->name.', SCO: '.$sco->identifier.'", 0);';
}
?>
diff --git a/mod/scorm/datamodels/scorm_13.js.php b/mod/scorm/datamodels/scorm_13.js.php
index <HASH>..<HASH> 100644
--- a/mod/scorm/datamodels/scorm_13.js.php
+++ b/mod/scorm/datamodels/scorm_13.js.php
@@ -1173,6 +1173,6 @@ var API_1484_11 = new SCORMapi1_3();
// pull in the debugging utilities
if (debugging('',DEBUG_DEVELOPER)) {
include_once($CFG->dirroot.'/mod/scorm/datamodels/debug.js.php');
- echo 'AppendToLog("Moodle SCORM 1.3 API Loaded", 0);';
+ echo 'AppendToLog("Moodle SCORM 1.3 API Loaded, Activity: '.$scorm->name.', SCO: '.$sco->identifier.'", 0);';
}
?>
\ No newline at end of file
|
MDL-<I> - SCORM results not transferring to Gradebook. SCORM API debugging tool - add reference to SCORM, and SCO identifier.
|
moodle_moodle
|
train
|
de75f93e0fe9791c773e7f57d3cb664b02dc85cc
|
diff --git a/core-bundle/src/Resources/contao/languages/en/default.xlf b/core-bundle/src/Resources/contao/languages/en/default.xlf
index <HASH>..<HASH> 100644
--- a/core-bundle/src/Resources/contao/languages/en/default.xlf
+++ b/core-bundle/src/Resources/contao/languages/en/default.xlf
@@ -707,8 +707,8 @@
<trans-unit id="MSC.mw_column">
<source>Column</source>
</trans-unit>
- <trans-unit id="MSC.mw_disable">
- <source>Disable the module</source>
+ <trans-unit id="MSC.mw_enable">
+ <source>Enable/disable the module</source>
</trans-unit>
<trans-unit id="MSC.aw_title">
<source>Title</source>
diff --git a/core-bundle/src/Resources/contao/library/Contao/Database/Updater.php b/core-bundle/src/Resources/contao/library/Contao/Database/Updater.php
index <HASH>..<HASH> 100644
--- a/core-bundle/src/Resources/contao/library/Contao/Database/Updater.php
+++ b/core-bundle/src/Resources/contao/library/Contao/Database/Updater.php
@@ -373,6 +373,21 @@ class Updater extends \Controller
->execute(serialize($arrCss), $objCss->id);
}
+ $objLayout = $this->Database->query("SELECT `id`, `modules` FROM `tl_layout`");
+
+ while ($objLayout->next())
+ {
+ $arrModules = deserialize($objLayout->modules);
+
+ foreach (array_keys($arrModules) as $key)
+ {
+ $arrModules[$key]['enable'] = true;
+ }
+
+ $this->Database->prepare("UPDATE `tl_layout` SET `modules`=? WHERE `id`=?")
+ ->execute(serialize($arrModules), $objLayout->id);
+ }
+
$this->Database->query("UPDATE `tl_content` SET `type`='accordionStart' WHERE `type`='accordion' AND `mooType`='mooStart'");
$this->Database->query("UPDATE `tl_content` SET `type`='accordionStop' WHERE `type`='accordion' AND `mooType`='mooStop'");
$this->Database->query("UPDATE `tl_content` SET `type`='accordionSingle' WHERE `type`='accordion' AND `mooType`='mooSingle'");
diff --git a/core-bundle/src/Resources/contao/pages/PageRegular.php b/core-bundle/src/Resources/contao/pages/PageRegular.php
index <HASH>..<HASH> 100644
--- a/core-bundle/src/Resources/contao/pages/PageRegular.php
+++ b/core-bundle/src/Resources/contao/pages/PageRegular.php
@@ -103,7 +103,7 @@ class PageRegular extends \Frontend
foreach ($arrModules as $arrModule)
{
// Disabled module
- if ($arrModule['disable'])
+ if (!$arrModule['enable'])
{
continue;
}
diff --git a/core-bundle/src/Resources/contao/widgets/ModuleWizard.php b/core-bundle/src/Resources/contao/widgets/ModuleWizard.php
index <HASH>..<HASH> 100644
--- a/core-bundle/src/Resources/contao/widgets/ModuleWizard.php
+++ b/core-bundle/src/Resources/contao/widgets/ModuleWizard.php
@@ -162,7 +162,7 @@ class ModuleWizard extends \Widget
<thead>
<tr>
<th>'.$GLOBALS['TL_LANG']['MSC']['mw_module'].'</th>
- <th>'.\Image::getHtml('show.gif', '', 'title="'.$GLOBALS['TL_LANG']['MSC']['mw_disable'].'"').'</th>
+ <th>'.\Image::getHtml('show.gif', '', 'title="'.$GLOBALS['TL_LANG']['MSC']['mw_enable'].'"').'</th>
<th>'.$GLOBALS['TL_LANG']['MSC']['mw_column'].'</th>
<th> </th>
</tr>
@@ -187,7 +187,7 @@ class ModuleWizard extends \Widget
$return .= '
<tr>
<td><select name="'.$this->strId.'['.$i.'][mod]" class="tl_select tl_chosen" tabindex="'.++$tabindex.'" onfocus="Backend.getScrollOffset()" onchange="Backend.updateModuleLink(this)">'.$options.'</select></td>
- <td style="text-align:center"><input name="'.$this->strId.'['.$i.'][disable]" type="checkbox" class="tl_checkbox" value="1" tabindex="'.++$tabindex.'" onfocus="Backend.getScrollOffset()"'. (($this->varValue[$i]['disable']) ? ' checked' : '').'></td>';
+ <td style="text-align:center"><input name="'.$this->strId.'['.$i.'][enable]" type="checkbox" class="tl_checkbox" value="1" tabindex="'.++$tabindex.'" onfocus="Backend.getScrollOffset()"'. (($this->varValue[$i]['enable']) ? ' checked' : '').'></td>';
$options = '';
|
[Core] Mark modules as "enabled" instead of "disabled"
|
contao_contao
|
train
|
c85dd03ed9549b68b8b7c2571aafa2186a963345
|
diff --git a/vais/planet.py b/vais/planet.py
index <HASH>..<HASH> 100644
--- a/vais/planet.py
+++ b/vais/planet.py
@@ -2,6 +2,7 @@
import os
import aikif.environments.worlds as my_world
+import worlds as my_world
#import aikif.gui_view_world as gui
fldr = os.getcwd() + os.sep + 'data' + os.sep + 'worlds'
|
planet uses the local version of worlds.py instead of AIKIF version
|
acutesoftware_virtual-AI-simulator
|
train
|
68ce7ebbf12b32dc3901974382e829d7b8808b8e
|
diff --git a/src/Parser.php b/src/Parser.php
index <HASH>..<HASH> 100644
--- a/src/Parser.php
+++ b/src/Parser.php
@@ -84,13 +84,13 @@ class Parser
$parent->addChild($object);
}
- // Initialize object
- $object->init();
-
if (is_array($element['value'])) {
$this->parseElements($element['value'], $object);
}
+ // Initialize object
+ $object->init();
+
if ($object instanceof ReservationInterface) {
$object = $object->getElement($this, $parent);
}
|
Initialise element after child elements have been parsed
|
encorephp_giml
|
train
|
d50d11534bbaa07ad1844a75117a367372594ece
|
diff --git a/taskforce/poll.py b/taskforce/poll.py
index <HASH>..<HASH> 100755
--- a/taskforce/poll.py
+++ b/taskforce/poll.py
@@ -47,6 +47,9 @@ class poll(object):
self._poll = select.poll()
elif 'select' in dir(select) and callable(select.select):
self._mode = PL_SELECT
+ self._rfds = set()
+ self._wfds = set()
+ self._xfds = set()
else:
raise Exception("System supports neither select.poll() nor select.select()")
@@ -73,24 +76,50 @@ class poll(object):
def register(self, fd, eventmask=POLLIN|POLLPRI|POLLOUT):
if self._mode == PL_POLL:
return self._poll.register(fd, eventmask)
+ elif self._mode == PL_SELECT:
+ self.unregister(fd)
+ if eventmask & POLLIN:
+ self._rfds.add(fd)
+ if eventmask & POLLOUT:
+ self._wfds.add(fd)
+ if eventmask & POLLPRI:
+ self._xfds.add(fd)
else:
pass
def modify(self, fd, eventmask):
if self._mode == PL_POLL:
return self._poll.modify(fd, eventmask)
+ elif self._mode == PL_SELECT:
+ self.register(fd, eventmask)
else:
pass
def unregister(self, fd):
if self._mode == PL_POLL:
return self._poll.unregister(fd)
+ elif self._mode == PL_SELECT:
+ self._rfds.discard(fd)
+ self._wfds.discard(fd)
+ self._xfds.discard(fd)
else:
pass
def poll(self, timeout=None):
if self._mode == PL_POLL:
return self._poll.poll(timeout)
+ elif self._mode == PL_SELECT:
+ if timeout is not None:
+ timeout /= 1000
+ rfds, wfds, xfds = select.select(self._rfds, self._wfds, self._xfds, timeout)
+ evlist = []
+ for fd in xfds:
+ evlist.append((fd, POLLPRI))
+ for fd in rfds:
+ evlist.append((fd, POLLIN))
+ for fd in wfds:
+ evlist.append((fd, POLLOUT))
+ return evlist
else:
pass
|
added select.select() implementation
|
akfullfo_taskforce
|
train
|
e1449dfa25e864f3bc8a7bddf5d58ccfedf37ab5
|
diff --git a/src/main/java/org/math/R/Rsession.java b/src/main/java/org/math/R/Rsession.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/math/R/Rsession.java
+++ b/src/main/java/org/math/R/Rsession.java
@@ -1301,9 +1301,9 @@ public abstract class Rsession implements RLog {
log("Nothing to save.", Level.WARNING);
return;
}
- voidEval("save(file='" + f.getAbsolutePath().replace("\\", "/") + "','" + vars[0] + "',ascii=" + (SAVE_ASCII ? "TRUE" : "FALSE") + ")", TRY_MODE);
+ voidEval("save(file='" + getAbsolutePath(f) + "','" + vars[0] + "',ascii=" + (SAVE_ASCII ? "TRUE" : "FALSE") + ")", TRY_MODE);
} else {
- voidEval("save(file='" + f.getAbsolutePath().replace("\\", "/") + "',list=" + buildListString(vars) + ",ascii=" + (SAVE_ASCII ? "TRUE" : "FALSE") + ")", TRY_MODE);
+ voidEval("save(file='" + getAbsolutePath(f) + "',list=" + buildListString(vars) + ",ascii=" + (SAVE_ASCII ? "TRUE" : "FALSE") + ")", TRY_MODE);
}
getFileFromWorkspace(f);
}
@@ -1325,9 +1325,9 @@ public abstract class Rsession implements RLog {
log("Nothing to save.", Level.WARNING);
return;
}
- voidEval("save(file='" + f.getAbsolutePath().replace("\\", "/") + "',list=" + buildListPattern(vars[0]) + ",ascii=" + (SAVE_ASCII ? "TRUE" : "FALSE") + ")", TRY_MODE);
+ voidEval("save(file='" + getAbsolutePath(f) + "',list=" + buildListPattern(vars[0]) + ",ascii=" + (SAVE_ASCII ? "TRUE" : "FALSE") + ")", TRY_MODE);
} else {
- voidEval("save(file='" + f.getAbsolutePath().replace("\\", "/") + "',list=" + buildListPattern(vars) + ",ascii=" + (SAVE_ASCII ? "TRUE" : "FALSE") + ")", TRY_MODE);
+ voidEval("save(file='" + getAbsolutePath(f) + "',list=" + buildListPattern(vars) + ",ascii=" + (SAVE_ASCII ? "TRUE" : "FALSE") + ")", TRY_MODE);
}
try {
Thread.sleep(1000);
@@ -1506,7 +1506,7 @@ public abstract class Rsession implements RLog {
public void toGraphic(File f, int width, int height, String fileformat, String... commands) {
int h = Math.abs(f.hashCode());
try {
- set("plotfile_" + h, f.getAbsolutePath().replace("\\", "/"));
+ set("plotfile_" + h, getAbsolutePath(f));
} catch (Exception ex) {
log(ex.getMessage(), Level.ERROR);
}
@@ -1528,6 +1528,24 @@ public abstract class Rsession implements RLog {
public final static String GRAPHIC_BMP = "bmp";
public final static String GRAPHIC_TIFF = "tiff";
+ /**
+ * Get absolute path of the file, except if the path begin with "/" (that is considered as an absolute path)
+ *
+ * This function answer the following special case: if the host is Windows and the remote server is Linux
+ * the File.getAbsolutePath() will add "C://" before the path of the file and we don't want it. So if the
+ * path begin by "/" we just use the function File.getPath().
+ *
+ * @param f
+ */
+ private static String getAbsolutePath(File f) {
+ String curPath = f.getPath().replace("\\", "/");
+ if(curPath.startsWith("/")) {
+ return curPath;
+ } else {
+ return f.getAbsolutePath().replace("\\", "/");
+ }
+ }
+
public void toGraphic(File f, int width, int height, String... commands) {
if (f.getName().endsWith(GRAPHIC_BMP)) {
toBMP(f, width, height, commands);
|
Fix bug with path and windows as host with Rserve.
|
yannrichet_rsession
|
train
|
d35a014a962fda4115795dfbd7fbea3ec906f911
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -61,6 +61,7 @@ packages = [
"neo4j.compat",
"neo4j.packstream",
"neo4j.v1",
+ "neo4j.v1.types",
]
package_data = {
"neo4j.bolt": ["*.pyx"],
|
Updated setup to include neo4j.v1.types
|
neo4j_neo4j-python-driver
|
train
|
0d837db894a3c3f16988b4cceb4bafbdc63b60c7
|
diff --git a/pytest_wdb/test_wdb.py b/pytest_wdb/test_wdb.py
index <HASH>..<HASH> 100644
--- a/pytest_wdb/test_wdb.py
+++ b/pytest_wdb/test_wdb.py
@@ -26,6 +26,10 @@ class FakeWdbServer(Process):
def run(self):
listener = Listener(('localhost', 18273))
+ try:
+ listener._listener._socket.settimeout(1)
+ except Exception:
+ pass
connection = listener.accept()
# uuid
connection.recv_bytes().decode('utf-8')
|
Add a hacky timeout around Listener accept for pytest_wdb test
|
Kozea_wdb
|
train
|
f1ea21b2a64febe9c3878ecbc767f99cd1971c5c
|
diff --git a/lib/cancan/controller_resource.rb b/lib/cancan/controller_resource.rb
index <HASH>..<HASH> 100644
--- a/lib/cancan/controller_resource.rb
+++ b/lib/cancan/controller_resource.rb
@@ -77,7 +77,7 @@ module CanCan
end
def load_collection
- resource_base.accessible_by(current_ability)
+ resource_base.accessible_by(current_ability, authorization_action)
end
def build_resource
|
Pass action name to accessible_by.
|
CanCanCommunity_cancancan
|
train
|
a6245978bf352edea5728267cbfbe8d6c5e38a3c
|
diff --git a/src/actions/initComponent.js b/src/actions/initComponent.js
index <HASH>..<HASH> 100644
--- a/src/actions/initComponent.js
+++ b/src/actions/initComponent.js
@@ -86,7 +86,7 @@ export default (
);
shouldCallInitActionClient = initActionClient && (
// mounted on the client (after first render)
- (initSelf !== INIT_SELF_NEVER)
+ (mode === MODE_INIT_SELF) && (initSelf !== INIT_SELF_NEVER)
);
break;
case 'willReceiveProps':
|
Don't call clientOnly action in MODE_PREPARE
|
mediamonks_react-redux-component-init
|
train
|
cd4c53258a9a89ad37c260b49606aeee6a2dab41
|
diff --git a/grace/build.py b/grace/build.py
index <HASH>..<HASH> 100644
--- a/grace/build.py
+++ b/grace/build.py
@@ -111,6 +111,7 @@ class Build:
else:
lines.append(line)
+ lines.append('\n')
return lines
def _build_html(self):
diff --git a/grace/testit.py b/grace/testit.py
index <HASH>..<HASH> 100644
--- a/grace/testit.py
+++ b/grace/testit.py
@@ -125,6 +125,7 @@ class Test:
else:
lines.append(line)
+ lines.append('\n')
return lines
def _build_html(self):
|
Main Program
* added a linebreak after concatenating a whole file
|
mdiener_grace
|
train
|
bd689aa32631e2ff75d11812eae52ec3bb80534f
|
diff --git a/flask_acl/ext.py b/flask_acl/ext.py
index <HASH>..<HASH> 100644
--- a/flask_acl/ext.py
+++ b/flask_acl/ext.py
@@ -1,6 +1,7 @@
from __future__ import absolute_import
import logging
+from pprint import pformat
from urllib import urlencode
import werkzeug as wz
@@ -46,7 +47,7 @@ class AuthManager(object):
context.update(utils.get_object_acl_context(obj))
context.update(kwargs)
- log.info('can context: %r' % context)
+ log.info('can context: %s' % pformat(context))
for state, predicate, permissions in utils.iter_object_acl(obj):
pred_match = predicate(**context)
perm_match = permission in permissions
diff --git a/flask_acl/permissions.py b/flask_acl/permissions.py
index <HASH>..<HASH> 100644
--- a/flask_acl/permissions.py
+++ b/flask_acl/permissions.py
@@ -5,6 +5,8 @@
class AllPermissions(object):
def __contains__(self, other):
return True
+ def __repr__(self):
+ return 'ANY'
string_permissions = {
|
Tweak some __repr__ and logging
|
mikeboers_Flask-ACL
|
train
|
8701ef2c8136b59c3a5c554e27ffa96ee3e9c6f5
|
diff --git a/.eslintrc b/.eslintrc
index <HASH>..<HASH> 100644
--- a/.eslintrc
+++ b/.eslintrc
@@ -4,5 +4,20 @@
"no-throw-literal": "off",
"promise/always-return": "error",
"promise/no-nesting": "error"
+ },
+ "settings": {
+ "backbone": {
+ "Collection": [
+ "Collection"
+ ],
+ "Model": [
+ "Model",
+ "AccessControlledModel"
+ ],
+ "View": [
+ "View",
+ "MetadatumEditWidget"
+ ]
+ }
}
}
diff --git a/clients/web/src/models/ApiKeyModel.js b/clients/web/src/models/ApiKeyModel.js
index <HASH>..<HASH> 100644
--- a/clients/web/src/models/ApiKeyModel.js
+++ b/clients/web/src/models/ApiKeyModel.js
@@ -22,10 +22,10 @@ var ApiKeyModel = AccessControlledModel.extend({
save: function () {
// Scope needs to be sent to the server as JSON
var scope = this.get('scope');
- this.attributes.scope = JSON.stringify(scope);
+ this.attributes.scope = JSON.stringify(scope); // eslint-disable-line backbone/no-model-attributes
var promise = AccessControlledModel.prototype.save.call(this, arguments);
// Restore scope to its original state
- this.attributes.scope = scope;
+ this.attributes.scope = scope; // eslint-disable-line backbone/no-model-attributes
return promise;
}
});
diff --git a/plugins/item_tasks/web_client/views/TaskListView.js b/plugins/item_tasks/web_client/views/TaskListView.js
index <HASH>..<HASH> 100644
--- a/plugins/item_tasks/web_client/views/TaskListView.js
+++ b/plugins/item_tasks/web_client/views/TaskListView.js
@@ -22,7 +22,7 @@ var TaskListView = View.extend({
render: function () {
this.$el.html(template({
- tasks: this.collection.models
+ tasks: this.collection.toArray()
}));
this.paginateWidget.setElement(this.$('.g-task-pagination')).render();
|
Fix eslint Backbone tests, ensuring Backbone inheritance is set correctly
|
girder_girder
|
train
|
0a094a7319f5ed521630f4df3221c4bf48eaf665
|
diff --git a/pkg/plugins/backendplugin/backend_plugin.go b/pkg/plugins/backendplugin/backend_plugin.go
index <HASH>..<HASH> 100644
--- a/pkg/plugins/backendplugin/backend_plugin.go
+++ b/pkg/plugins/backendplugin/backend_plugin.go
@@ -205,6 +205,26 @@ func (p *BackendPlugin) checkHealth(ctx context.Context, config *PluginConfig) (
LastUpdatedMS: config.Updated.UnixNano() / int64(time.Millisecond),
}
+ if config.DataSourceConfig != nil {
+ datasourceJSONData, err := config.DataSourceConfig.JSONData.ToDB()
+ if err != nil {
+ return nil, err
+ }
+
+ pconfig.DatasourceConfig = &pluginv2.DataSourceConfig{
+ Id: config.DataSourceConfig.ID,
+ Name: config.DataSourceConfig.Name,
+ Url: config.DataSourceConfig.URL,
+ User: config.DataSourceConfig.User,
+ Database: config.DataSourceConfig.Database,
+ BasicAuthEnabled: config.DataSourceConfig.BasicAuthEnabled,
+ BasicAuthUser: config.DataSourceConfig.BasicAuthUser,
+ JsonData: datasourceJSONData,
+ DecryptedSecureJsonData: config.DataSourceConfig.DecryptedSecureJSONData,
+ LastUpdatedMS: config.DataSourceConfig.Updated.Unix() / int64(time.Millisecond),
+ }
+ }
+
res, err := p.diagnostics.CheckHealth(ctx, &pluginv2.CheckHealthRequest{Config: pconfig})
if err != nil {
if st, ok := status.FromError(err); ok {
|
Datasource config was not mapped for datasource healthcheck (#<I>)
closes #<I>
|
grafana_grafana
|
train
|
cb503932214f1d33e2443fe82fff5da10dfb3e1e
|
diff --git a/src/backbone.collectionView.js b/src/backbone.collectionView.js
index <HASH>..<HASH> 100755
--- a/src/backbone.collectionView.js
+++ b/src/backbone.collectionView.js
@@ -331,7 +331,8 @@
fragmentContainer = document.createDocumentFragment();
this.collection.each( function( thisModel ) {
- this._renderModelView( thisModel, fragmentContainer || modelViewContainerEl, oldViewManager );
+ var thisModelView = oldViewManager.findByModelCid( thisModel.cid );
+ this._renderModelView( thisModel, fragmentContainer || modelViewContainerEl, thisModelView );
}, this );
if( this.detachedRendering )
@@ -400,12 +401,7 @@
this.onAfterRender();
},
- _renderModelView : function( thisModel, parentEl, viewManager ) {
-
- viewManager = viewManager || this.viewManager;
-
- var thisModelView = viewManager.findByModelCid( thisModel.cid );
-
+ _renderModelView : function( thisModel, parentEl, thisModelView ) {
if( _.isUndefined( thisModelView ) ) {
// if the model view was not already created on previous render,
// then create and initialize it now.
@@ -418,6 +414,7 @@
var thisModelViewWrapped = this._wrapModelView( thisModelView );
+ // TODO handle all options of collection.add()
if( this.detachedRendering )
parentEl.appendChild( thisModelViewWrapped[0] );
else
|
Clarifying the model view render method arguments.
We now pass in the modelView to _renderModelView instead of the more obtuse
viewManager argument.
|
rotundasoftware_backbone.collectionView
|
train
|
f679989bdaeeaeffc46a0938179fc3e93292345a
|
diff --git a/owncloud/owncloud.py b/owncloud/owncloud.py
index <HASH>..<HASH> 100644
--- a/owncloud/owncloud.py
+++ b/owncloud/owncloud.py
@@ -510,15 +510,16 @@ class Client():
data = 'shares'
if (path != ''):
+ data += '?'
path = self.__normalize_path(path)
- path = urllib.urlencode({'path': path})
- data = '%s?%s' % (data, path)
+ args = { 'path': path }
reshares = kwargs.get('reshares', False)
if (isinstance(reshares, bool) and (reshares == True)):
- data += '&reshares=%s' % reshares
+ args['reshares'] = reshares
subfiles = kwargs.get('subfiles', False)
if (isinstance(subfiles, bool) and (subfiles == True)):
- data += '&subfiles=%s' % subfiles
+ args['subfiles'] = subfiles
+ data += urllib.urlencode(args)
res = self.__make_ocs_request(
'GET',
|
get_shares(): Args as a dict; run urlencode() at the end of code block
|
owncloud_pyocclient
|
train
|
f679bb676c033542f055fee1cf9ce59c4d962989
|
diff --git a/src/main/java/org/dita/dost/writer/ChunkTopicParser.java b/src/main/java/org/dita/dost/writer/ChunkTopicParser.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/dita/dost/writer/ChunkTopicParser.java
+++ b/src/main/java/org/dita/dost/writer/ChunkTopicParser.java
@@ -292,8 +292,7 @@ public final class ChunkTopicParser extends AbstractChunkTopicParser {
private void writeToContentChunk(final String tmpContent, final URI outputFileName, final boolean needWriteDitaTag) throws IOException {
assert outputFileName.isAbsolute();
logger.info("Writing " + outputFileName);
- try (OutputStream out = job.getStore().getOutputStream(outputFileName);
- OutputStreamWriter ditaFileOutput = new OutputStreamWriter(out, StandardCharsets.UTF_8)) {
+ try (Writer ditaFileOutput = new OutputStreamWriter(job.getStore().getOutputStream(outputFileName), StandardCharsets.UTF_8)) {
if (outputFileName.equals(changeTable.get(outputFileName))) {
// if the output file is newly generated file
// write the xml header and workdir PI into new file
diff --git a/src/main/java/org/dita/dost/writer/TopicRefWriter.java b/src/main/java/org/dita/dost/writer/TopicRefWriter.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/dita/dost/writer/TopicRefWriter.java
+++ b/src/main/java/org/dita/dost/writer/TopicRefWriter.java
@@ -31,6 +31,7 @@ public final class TopicRefWriter extends AbstractXMLFilter {
private Map<URI, URI> changeTable = null;
private Map<URI, URI> conflictTable = null;
private File currentFileDir = null;
+ private URI currentFileDirURI = null;
/** Using for rectify relative path of xml */
private String fixpath = null;
@@ -38,6 +39,8 @@ public final class TopicRefWriter extends AbstractXMLFilter {
public void write(final File outputFilename) throws DITAOTException {
setCurrentFile(outputFilename.toURI());
currentFileDir = outputFilename.getParentFile();
+ currentFileDirURI = outputFilename.toURI().resolve(".");
+ logger.info("Process " + outputFilename.toURI());
super.write(outputFilename);
}
@@ -159,7 +162,8 @@ public final class TopicRefWriter extends AbstractXMLFilter {
if (isLocalDita(atts)) {
// replace the href value if it's referenced topic is extracted.
final URI rootPathName = currentFile;
- URI changeTargetkey = stripFragment(currentFileDir.toURI().resolve(hrefValue));
+ URI target = currentFile.resolve(hrefValue);
+ URI changeTargetkey = stripFragment(target);
URI changeTarget = changeTable.get(changeTargetkey);
final String topicID = getTopicID(toURI(hrefValue));
|
Fix current file directory URI resolution when file doesn't exist
|
dita-ot_dita-ot
|
train
|
384b7cae72e69f7bca14ae91b80d1b0d95cfd3ce
|
diff --git a/web/concrete/src/Asset/Asset.php b/web/concrete/src/Asset/Asset.php
index <HASH>..<HASH> 100644
--- a/web/concrete/src/Asset/Asset.php
+++ b/web/concrete/src/Asset/Asset.php
@@ -63,9 +63,9 @@ abstract class Asset
abstract public function getAssetType();
- abstract public function minify($assets);
+ abstract public static function minify($assets);
- abstract public function combine($assets);
+ abstract public static function combine($assets);
abstract public function __toString();
diff --git a/web/concrete/src/Asset/CssAsset.php b/web/concrete/src/Asset/CssAsset.php
index <HASH>..<HASH> 100644
--- a/web/concrete/src/Asset/CssAsset.php
+++ b/web/concrete/src/Asset/CssAsset.php
@@ -164,7 +164,7 @@ class CssAsset extends Asset
* @param $assets
* @return Asset[]
*/
- public function combine($assets)
+ public static function combine($assets)
{
return self::process($assets, function($css, $assetPath, $targetPath) {
return CSSAsset::changePaths($css, $assetPath, $targetPath);
@@ -175,7 +175,7 @@ class CssAsset extends Asset
* @param $assets
* @return Asset[]
*/
- public function minify($assets)
+ public static function minify($assets)
{
return self::process($assets, function($css, $assetPath, $targetPath) {
return \CssMin::minify(CSSAsset::changePaths($css, $assetPath, $targetPath));
diff --git a/web/concrete/src/Asset/JavascriptAsset.php b/web/concrete/src/Asset/JavascriptAsset.php
index <HASH>..<HASH> 100644
--- a/web/concrete/src/Asset/JavascriptAsset.php
+++ b/web/concrete/src/Asset/JavascriptAsset.php
@@ -89,7 +89,7 @@ class JavascriptAsset extends Asset
* @param Asset[] $assets
* @return Asset[]
*/
- public function combine($assets)
+ public static function combine($assets)
{
return self::process($assets, function($js, $assetPath, $targetPath) {
return $js;
@@ -100,7 +100,7 @@ class JavascriptAsset extends Asset
* @param Asset[] $assets
* @return Asset[]
*/
- public function minify($assets)
+ public static function minify($assets)
{
return self::process($assets, function($js, $assetPath, $targetPath) {
return \JShrink\Minifier::minify($js);
|
Mark minify and combine as static
minify() and combine() don't use any instance method/variabies,
and they are called as static by View->postProcessAssets()
Former-commit-id: c<I>d<I>ae<I>d<I>cfaa<I>debc7beb2fa<I>
|
concrete5_concrete5
|
train
|
05d81436e99447f08bf1537ea60b5f11ebda2107
|
diff --git a/src/main/java/org/junit/rules/Verifier.java b/src/main/java/org/junit/rules/Verifier.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/junit/rules/Verifier.java
+++ b/src/main/java/org/junit/rules/Verifier.java
@@ -9,7 +9,7 @@ import org.junit.runners.model.Statement;
* failed
*
* <pre>
- * public static class ErrorLogVerifier() {
+ * public static class ErrorLogVerifier {
* private ErrorLog errorLog = new ErrorLog();
*
* @Rule
|
Fix for issue #<I>. Wrong use of round brackets on first line of code sample.
|
junit-team_junit4
|
train
|
495bf53756cf6ce4bbdf21dca4fe8621f5b1c730
|
diff --git a/trustpinning/certs.go b/trustpinning/certs.go
index <HASH>..<HASH> 100644
--- a/trustpinning/certs.go
+++ b/trustpinning/certs.go
@@ -161,6 +161,7 @@ func ValidateRoot(prevRoot *data.SignedRoot, root *data.Signed, gun string, trus
logrus.Debugf("failed to verify TUF data for: %s, %v", gun, err)
return nil, &ErrValidationFail{Reason: "failed to validate integrity of roots"}
}
+ signedRoot.Signatures = root.Signatures
logrus.Debugf("root validation succeeded for %s", gun)
return signedRoot, nil
diff --git a/trustpinning/certs_test.go b/trustpinning/certs_test.go
index <HASH>..<HASH> 100644
--- a/trustpinning/certs_test.go
+++ b/trustpinning/certs_test.go
@@ -173,6 +173,7 @@ func TestValidateRootWithPinnedCert(t *testing.T) {
// Unmarshal our signedroot
json.Unmarshal(signedRootBytes.Bytes(), &testSignedRoot)
+ testSignedRoot.Signatures[0].IsValid = true
typedSignedRoot, err := data.RootFromSigned(&testSignedRoot)
require.NoError(t, err)
@@ -340,6 +341,7 @@ func TestValidateRootWithPinnerCertAndIntermediates(t *testing.T) {
err = signed.Sign(cs, signedRoot, []data.PublicKey{ecdsax509Key}, 1, nil)
require.NoError(t, err)
+ signedRoot.Signatures[0].IsValid = true
typedSignedRoot, err := data.RootFromSigned(signedRoot)
require.NoError(t, err)
@@ -378,6 +380,7 @@ func TestValidateRootFailuresWithPinnedCert(t *testing.T) {
// Unmarshal our signedroot
json.Unmarshal(signedRootBytes.Bytes(), &testSignedRoot)
+ testSignedRoot.Signatures[0].IsValid = true
typedSignedRoot, err := data.RootFromSigned(&testSignedRoot)
require.NoError(t, err)
@@ -417,6 +420,7 @@ func TestValidateRootWithPinnedCA(t *testing.T) {
templ.Execute(&signedRootBytes, SignedRSARootTemplate{RootPem: validPEMEncodedRSARoot})
// Unmarshal our signedRoot
json.Unmarshal(signedRootBytes.Bytes(), &testSignedRoot)
+ testSignedRoot.Signatures[0].IsValid = true
typedSignedRoot, err := data.RootFromSigned(&testSignedRoot)
require.NoError(t, err)
@@ -495,6 +499,7 @@ func TestValidateRootWithPinnedCA(t *testing.T) {
err = signed.Sign(cs, newTestSignedRoot, []data.PublicKey{newRootKey}, 1, nil)
require.NoError(t, err)
+ newTestSignedRoot.Signatures[0].IsValid = true
newTypedSignedRoot, err := data.RootFromSigned(newTestSignedRoot)
require.NoError(t, err)
@@ -625,6 +630,8 @@ func testValidateSuccessfulRootRotation(t *testing.T, keyAlg, rootKeyType string
err = signed.Sign(cs, signedTestRoot, []data.PublicKey{replRootKey, origRootKey}, 2, nil)
require.NoError(t, err)
+ signedTestRoot.Signatures[0].IsValid = true
+ signedTestRoot.Signatures[1].IsValid = true
typedSignedRoot, err := data.RootFromSigned(signedTestRoot)
require.NoError(t, err)
diff --git a/tuf/builder.go b/tuf/builder.go
index <HASH>..<HASH> 100644
--- a/tuf/builder.go
+++ b/tuf/builder.go
@@ -534,6 +534,7 @@ func (rb *repoBuilder) loadTargets(content []byte, minVersion int, allowExpired
}
}
+ signedTargets.Signatures = signedObj.Signatures
rb.repo.Targets[roleName] = signedTargets
return nil
}
@@ -562,7 +563,6 @@ func (rb *repoBuilder) loadDelegation(roleName string, content []byte, minVersio
// verify signature
if err := signed.VerifySignatures(signedObj, delegationRole.BaseRole); err != nil {
- signedTargets.Signatures = signedObj.Signatures
rb.invalidRoles.Targets[roleName] = signedTargets
return err
}
@@ -574,6 +574,7 @@ func (rb *repoBuilder) loadDelegation(roleName string, content []byte, minVersio
}
}
+ signedTargets.Signatures = signedObj.Signatures
rb.repo.Targets[roleName] = signedTargets
return nil
}
|
made change to make sure that ValidateRoot mutates the signatures of the returned signed root object
|
theupdateframework_notary
|
train
|
279601330b8856146ab0365d05c817d762aa1a6c
|
diff --git a/textproto/header.go b/textproto/header.go
index <HASH>..<HASH> 100644
--- a/textproto/header.go
+++ b/textproto/header.go
@@ -264,11 +264,6 @@ func readLineSlice(r *bufio.Reader, line []byte) ([]byte, error) {
return nil, err
}
- // Avoid the copy if the first call produced a full line.
- if line == nil && !more {
- return l, nil
- }
-
line = append(line, l...)
if !more {
break
diff --git a/textproto/header_test.go b/textproto/header_test.go
index <HASH>..<HASH> 100644
--- a/textproto/header_test.go
+++ b/textproto/header_test.go
@@ -211,9 +211,9 @@ Subject: A little message, just for you
Date: Wed, 11 May 2016 14:31:59 +0000
Message-ID: <0000000@localhost/>
Content-Type: text/plain
+
`
-// TODO: make this test pass
func TestReadHeader_lf(t *testing.T) {
r := bufio.NewReader(strings.NewReader(testLFHeader))
h, err := ReadHeader(r)
@@ -227,16 +227,16 @@ func TestReadHeader_lf(t *testing.T) {
"To: contact@example.org",
"Subject: A little message, just for you",
"Date: Wed, 11 May 2016 14:31:59 +0000",
- "Message-ID: <0000000@localhost/>",
+ "Message-Id: <0000000@localhost/>",
"Content-Type: text/plain",
}
if !reflect.DeepEqual(l, want) {
- t.Logf("Fields() reported incorrect values: got \n%#v\n but want \n%#v", l, want)
+ t.Errorf("Fields() reported incorrect values: got \n%#v\n but want \n%#v", l, want)
}
b := make([]byte, 1)
if _, err := r.Read(b); err != io.EOF {
- t.Logf("Read() didn't return EOF: %v", err)
+ t.Errorf("Read() didn't return EOF: %v", err)
}
}
|
textproto: fix parsing messages with LF line endings
We can't save the line returned by bufio.ReadLine in headerField.b, because
bufio will re-use it for the next line. We always need to copy it.
|
emersion_go-message
|
train
|
158e3c1d523705ca36416433b6df0b45a260514a
|
diff --git a/lib/rails/config/routes.rb b/lib/rails/config/routes.rb
index <HASH>..<HASH> 100644
--- a/lib/rails/config/routes.rb
+++ b/lib/rails/config/routes.rb
@@ -1,3 +1,7 @@
Rails.application.routes.draw do
- match "/websocket", :to => WebsocketRails::ConnectionManager.new
+ if Rails.version >= '4.0.0'
+ get "/websocket", :to => WebsocketRails::ConnectionManager.new
+ else
+ match "/websocket", :to => WebsocketRails::ConnectionManager.new
+ end
end
diff --git a/lib/websocket_rails/engine.rb b/lib/websocket_rails/engine.rb
index <HASH>..<HASH> 100644
--- a/lib/websocket_rails/engine.rb
+++ b/lib/websocket_rails/engine.rb
@@ -6,7 +6,12 @@ module WebsocketRails
paths["app"] << "lib/rails/app"
paths["app/controllers"] << "lib/rails/app/controllers"
- paths["config/routes"] << "lib/rails/config/routes.rb"
+
+ if ::Rails.version >= '4.0.0'
+ paths["config/routes.rb"] << "lib/rails/config/routes.rb"
+ else
+ paths["config/routes"] << "lib/rails/config/routes.rb"
+ end
rake_tasks do
require 'websocket-rails'
|
Added conditional on route paths for changes in Rails 4
* Fixes #<I>
* Added a conditional to test for Rails 4 and above when appending to paths
* Updated routes to use get verb for Rails 4 and above
|
websocket-rails_websocket-rails
|
train
|
66fb97a09fcc49aa0145efe4b213b030f079b99b
|
diff --git a/confidence/io.py b/confidence/io.py
index <HASH>..<HASH> 100644
--- a/confidence/io.py
+++ b/confidence/io.py
@@ -229,7 +229,7 @@ def load(*fps: typing.IO, missing: typing.Any = Missing.silent) -> Configuration
def loadf(*fnames: str,
- default: typing.Union[typing.Mapping[str, typing.Any]] = NoDefault,
+ default: typing.Any = NoDefault,
missing: typing.Any = Missing.silent) -> Configuration:
"""
Read a `.Configuration` instance from named files.
|
Mark default argument to loadf as Any
|
HolmesNL_confidence
|
train
|
1cb6ddf69e849ee9d19bf9006cfcfb558e405b81
|
diff --git a/lib/md_emoji/render.rb b/lib/md_emoji/render.rb
index <HASH>..<HASH> 100644
--- a/lib/md_emoji/render.rb
+++ b/lib/md_emoji/render.rb
@@ -19,7 +19,7 @@ module MdEmoji
#
# Valid emoji charaters are listed in +MdEmoji::EMOJI+
def replace_emoji(text)
- text.gsub(/:(\S+):/) do |emoji|
+ text.gsub(/:([^\s:])+:/) do |emoji|
emoji_code = emoji #.gsub("|", "_")
emoji = emoji_code.gsub(":", "")
diff --git a/test/renderer_test.rb b/test/renderer_test.rb
index <HASH>..<HASH> 100644
--- a/test/renderer_test.rb
+++ b/test/renderer_test.rb
@@ -87,6 +87,15 @@ class RendererTest < ActiveSupport::TestCase
"<br> not present in parsed text: #{parsed_text}"
end
+ test "works with multiple emoji without spaces" do
+ @markdown = Redcarpet::Markdown.new(MdEmoji::Render.new)
+ text = ":ship::dash:"
+ parsed_text = @markdown.render(text)
+
+ assert_emoji 'ship', parsed_text
+ assert_emoji 'dash', parsed_text
+ end
+
test "does not render emoji in codeblocks" do
text = %{```ruby
def hello
|
Emoji should not require a space between them
|
elm-city-craftworks_md_emoji
|
train
|
7aa19218412a6100c0cdebac8f5a9d2fa22f2fa0
|
diff --git a/bosh-director/lib/bosh/director/package_compiler.rb b/bosh-director/lib/bosh/director/package_compiler.rb
index <HASH>..<HASH> 100644
--- a/bosh-director/lib/bosh/director/package_compiler.rb
+++ b/bosh-director/lib/bosh/director/package_compiler.rb
@@ -211,10 +211,8 @@ module Bosh::Director
return task
end
- release_version = job.release
- dependencies = package.dependency_set.map do |name|
- release_version.get_package_model_by_name(name)
- end
+ release_version = job.release.model
+ dependencies = release_version.dependencies(package.name)
task = CompileTask.new(package, stemcell, dependencies, job)
diff --git a/bosh-director/spec/unit/package_compiler_spec.rb b/bosh-director/spec/unit/package_compiler_spec.rb
index <HASH>..<HASH> 100644
--- a/bosh-director/spec/unit/package_compiler_spec.rb
+++ b/bosh-director/spec/unit/package_compiler_spec.rb
@@ -58,9 +58,10 @@ module Bosh::Director
end
def prepare_samples
+ @release_version_model = Models::ReleaseVersion.make
@release = instance_double('Bosh::Director::DeploymentPlan::ReleaseVersion',
name: 'cf-release',
- model: Models::ReleaseVersion.make)
+ model: @release_version_model)
@stemcell_a = instance_double('Bosh::Director::DeploymentPlan::Stemcell', model: Models::Stemcell.make)
@stemcell_b = instance_double('Bosh::Director::DeploymentPlan::Stemcell', model: Models::Stemcell.make)
@@ -99,11 +100,9 @@ module Bosh::Director
@package_set_b = [@p_nginx, @p_common, @p_router, @p_warden, @p_ruby]
- # Dependencies lookup expected!
- @release.should_receive(:get_package_model_by_name).
- with('ruby').at_least(1).times.and_return(@p_ruby)
- @release.should_receive(:get_package_model_by_name).
- with('common').at_least(1).times.and_return(@p_common)
+ (@package_set_a + @package_set_b).each do |package|
+ @release_version_model.packages << package
+ end
end
context 'when all needed packages are compiled' do
@@ -251,12 +250,13 @@ module Bosh::Director
network = double('network', name: 'network_name')
compilation_config = instance_double('Bosh::Director::CompilationConfig', network: network, cloud_properties: {}, env: {}, workers: 1,
reuse_compilation_vms: true)
- release = double('release', name: 'release_name')
+ release_version_model = instance_double('Bosh::Director::Models::ReleaseVersion', dependencies: [])
+ release_version = instance_double('Bosh::Director::DeploymentPlan::ReleaseVersion', name: 'release_name', model: release_version_model)
stemcell_model = double('stemcell_model', desc: 'stemcell description', id: 'stemcell_id', sha1: 'beef')
stemcell = double('stemcell', model: stemcell_model)
resource_pool = double('resource_pool', stemcell: stemcell)
- job = instance_double('Bosh::Director::DeploymentPlan::Job', release: release, name: 'job_name', resource_pool: resource_pool)
- package_model = instance_double('Bosh::Director::Models::Package', desc: 'package description', id: 'package_id', dependency_set: [],
+ job = instance_double('Bosh::Director::DeploymentPlan::Job', release: release_version, name: 'job_name', resource_pool: resource_pool)
+ package_model = instance_double('Bosh::Director::Models::Package', name: 'foobarbaz', desc: 'package description', id: 'package_id', dependency_set: [],
fingerprint: 'deadbeef')
template = instance_double('Bosh::Director::DeploymentPlan::Template', package_models: [ package_model ])
job.stub(templates: [template])
@@ -393,7 +393,9 @@ module Bosh::Director
describe 'tearing down compilation vms' do
before do # prepare compilation
- release = instance_double('Bosh::Director::DeploymentPlan::ReleaseVersion', name: 'release')
+ prepare_samples
+
+ release = instance_double('Bosh::Director::DeploymentPlan::ReleaseVersion', model: @release_version_model, name: 'release')
stemcell = instance_double('Bosh::Director::DeploymentPlan::Stemcell', model: Models::Stemcell.make)
resource_pool = instance_double('Bosh::Director::DeploymentPlan::ResourcePool', stemcell: stemcell)
|
Use dependency lookup on ReleaseVersion model during compilation
Avoids duplication
[#<I>]
|
cloudfoundry_bosh
|
train
|
c4d7af57f0dcf3508694e7e8560eb5e04e505361
|
diff --git a/command/agent/command.go b/command/agent/command.go
index <HASH>..<HASH> 100644
--- a/command/agent/command.go
+++ b/command/agent/command.go
@@ -40,6 +40,7 @@ func (c *Command) Run(args []string, rawUi cli.Ui) int {
"json file to read config from")
cmdFlags.Var((*AppendSliceValue)(&configFiles), "config-dir",
"directory of json files to read")
+ cmdFlags.StringVar(&cmdConfig.EncryptKey, "encrypt", "", "encryption key")
cmdFlags.Var((*AppendSliceValue)(&cmdConfig.EventHandlers), "event-handler",
"command to execute when events occur")
cmdFlags.Var((*AppendSliceValue)(&cmdConfig.StartJoin), "join",
diff --git a/command/agent/config.go b/command/agent/config.go
index <HASH>..<HASH> 100644
--- a/command/agent/config.go
+++ b/command/agent/config.go
@@ -1,6 +1,7 @@
package agent
import (
+ "encoding/base64"
"encoding/json"
"fmt"
"github.com/hashicorp/serf/serf"
@@ -40,6 +41,13 @@ type Config struct {
// port will be used.
BindAddr string `mapstructure:"bind_addr"`
+ // EncryptKey is the secret key to use for encrypting communication
+ // traffic for Serf. The secret key must be exactly 16-bytes, base64
+ // encoded. The easiest way to do this on Unix machines is this command:
+ // "head -c16 /dev/urandom | base64". If this is not specified, the
+ // traffic will not be encrypted.
+ EncryptKey string `mapstructure:"encrypt_key"`
+
// LogLevel is the level of the logs to output.
LogLevel string `mapstructure:"log_level"`
@@ -75,6 +83,11 @@ func (c *Config) BindAddrParts() (string, int, error) {
return addr.IP.String(), addr.Port, nil
}
+// EncryptBytes returns the encryption key configured.
+func (c *Config) EncryptBytes() ([]byte, error) {
+ return base64.StdEncoding.DecodeString(c.EncryptKey)
+}
+
// EventScripts returns the list of EventScripts associated with this
// configuration and specified by the "event_handlers" configuration.
func (c *Config) EventScripts() ([]EventScript, error) {
diff --git a/command/agent/config_test.go b/command/agent/config_test.go
index <HASH>..<HASH> 100644
--- a/command/agent/config_test.go
+++ b/command/agent/config_test.go
@@ -2,6 +2,7 @@ package agent
import (
"bytes"
+ "encoding/base64"
"io/ioutil"
"os"
"path/filepath"
@@ -40,6 +41,34 @@ func TestConfigBindAddrParts(t *testing.T) {
}
}
+func TestConfigEncryptBytes(t *testing.T) {
+ // Test with some input
+ src := []byte("abc")
+ c := &Config{
+ EncryptKey: base64.StdEncoding.EncodeToString(src),
+ }
+
+ result, err := c.EncryptBytes()
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ if !bytes.Equal(src, result) {
+ t.Fatalf("bad: %#v", result)
+ }
+
+ // Test with no input
+ c = &Config{}
+ result, err = c.EncryptBytes()
+ if err != nil {
+ t.Fatalf("err: %s", err)
+ }
+
+ if len(result) > 0 {
+ t.Fatalf("bad: %#v", result)
+ }
+}
+
func TestConfigEventScripts(t *testing.T) {
c := &Config{
EventHandlers: []string{
|
command/agent: config can take an EncryptKey
|
hashicorp_serf
|
train
|
e12ed5e5a5dc1c68feb41a514ef89d1f61082610
|
diff --git a/src/Pdf.php b/src/Pdf.php
index <HASH>..<HASH> 100644
--- a/src/Pdf.php
+++ b/src/Pdf.php
@@ -23,6 +23,9 @@ class Pdf
// Regular expression to detect XML strings
const REGEX_XML = '/<\??xml/i';
+ // Regular expression to detect options that expect an URL or a file name, so we need to create a tmp file for the content.
+ const REGEX_OPTS_TMPFILE = '/^((header|footer)-html|(xsl|user)-style-sheet)$/i';
+
// prefix for tmp files
const TMP_PREFIX = 'tmp_wkhtmlto_pdf_';
@@ -300,7 +303,7 @@ class Pdf
{
foreach ($options as $key=>$val) {
// header-/footer-html, xsl-style-sheet and user-style-sheet expect an URL or a file name, so we need to create a tmp file for the content
- if (is_string($val) && preg_match('/^((header|footer)-html|xsl-style-sheet|user-style-sheet)$/', $key) ) {
+ if (is_string($val) && preg_match(self::REGEX_OPTS_TMPFILE, $key) ) {
defined('PHP_MAXPATHLEN') || define('PHP_MAXPATHLEN', 255);
$isFile = (strlen($val) <= PHP_MAXPATHLEN) ? is_file($val) : false;
if (!($isFile || preg_match('/^(https?:)?\/\//i',$val) || $val===strip_tags($val))) {
|
Update Pdf.php
Simplifies regular expression, which matches options that expect an URL or a file name and transfers the regular expression into constant `REGEX_OPTS_TMPFILE`.
|
mikehaertl_phpwkhtmltopdf
|
train
|
28f73f2bf5821e037dadd1a11afc488030cec576
|
diff --git a/__tests__/variantsAtRule.test.js b/__tests__/variantsAtRule.test.js
index <HASH>..<HASH> 100644
--- a/__tests__/variantsAtRule.test.js
+++ b/__tests__/variantsAtRule.test.js
@@ -69,3 +69,28 @@ test('it can generate hover and focus variants', () => {
expect(result.warnings().length).toBe(0)
})
})
+
+test('it wraps the output in a responsive at-rule if responsive is included as a variant', () => {
+ const input = `
+ @variants responsive, hover, focus {
+ .banana { color: yellow; }
+ .chocolate { color: brown; }
+ }
+ `
+
+ const output = `
+ @responsive {
+ .banana { color: yellow; }
+ .chocolate { color: brown; }
+ .focus\\:banana:focus { color: yellow; }
+ .focus\\:chocolate:focus { color: brown; }
+ .hover\\:banana:hover { color: yellow; }
+ .hover\\:chocolate:hover { color: brown; }
+ }
+ `
+
+ return run(input).then(result => {
+ expect(result.css).toMatchCss(output)
+ expect(result.warnings().length).toBe(0)
+ })
+})
diff --git a/src/lib/substituteVariantsAtRules.js b/src/lib/substituteVariantsAtRules.js
index <HASH>..<HASH> 100644
--- a/src/lib/substituteVariantsAtRules.js
+++ b/src/lib/substituteVariantsAtRules.js
@@ -27,6 +27,12 @@ export default function() {
css.walkAtRules('variants', atRule => {
const variants = postcss.list.comma(atRule.params)
+ if (variants.includes('responsive')) {
+ const responsiveParent = postcss.atRule({ name: 'responsive' })
+ atRule.before(responsiveParent)
+ responsiveParent.append(atRule)
+ }
+
atRule.before(atRule.clone().nodes)
_.forEach(['focus', 'hover'], variant => {
|
Add support for including `responsive` in variants list
|
tailwindcss_tailwindcss
|
train
|
d6bb998550b00da76461c610b4b424f2034609a2
|
diff --git a/web/concrete/blocks/form/controller.php b/web/concrete/blocks/form/controller.php
index <HASH>..<HASH> 100644
--- a/web/concrete/blocks/form/controller.php
+++ b/web/concrete/blocks/form/controller.php
@@ -576,6 +576,15 @@ class Controller extends BlockController
//echo $mh->body.'<br>';
@$mh->sendMail();
}
+
+ //launch form submission event
+ $formEventData = array();
+ $formEventData['bID'] = intval($this->bID);
+ $formEventData['questionSetID'] = $this->questionSetId;
+ $formEventData['replyToEmailAddress'] = $replyToEmailAddress;
+ $formEventData['formFormEmailAddress'] = $formFormEmailAddress;
+ $formEventData['questionAnswerPairs'] = $questionAnswerPairs;
+ Events::fire('on_form_submission', $formEventData);
if (!$this->noSubmitFormRedirect) {
$targetPage = null;
|
Update core form block controller with event
Added an event (on_form_submission) before the redirect.
Former-commit-id: 8a<I>f<I>f5f<I>d<I>f<I>a<I>ace<I>
Former-commit-id: <I>c<I>d<I>d<I>fbd<I>e<I>e<I>f5e<I>b<I>c
|
concrete5_concrete5
|
train
|
53c1fb6a450e10ebfc1c2124f6e2543b2dba8e72
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -6,7 +6,7 @@ try:
import jsmin
djanalytics_js_in = open('djanalytics/templates/djanalytics.js')
- djanalytics_js_out = open('djanalytics/templates/djanalytics.js', 'w')
+ djanalytics_js_out = open('djanalytics/templates/djanalytics.js.min', 'w')
try:
jsmin.JavascriptMinify(djanalytics_js_in, djanalytics_js_out).minify()
finally:
@@ -30,6 +30,8 @@ setup(
'djanalytics': [
'templates/charts/*',
'templates/*png'
+ 'templates/*js',
+ 'templates/*min',
],
},
description='Django app to capture, track and display site analytics',
|
actually include the js files in the distribution
|
analytehealth_django-analytics
|
train
|
3e2d225892f743c8c06cf9f904a921913174b39f
|
diff --git a/lib/Thelia/Model/ConfigQuery.php b/lib/Thelia/Model/ConfigQuery.php
index <HASH>..<HASH> 100644
--- a/lib/Thelia/Model/ConfigQuery.php
+++ b/lib/Thelia/Model/ConfigQuery.php
@@ -73,6 +73,12 @@ class ConfigQuery extends BaseConfigQuery
return true;
}
+
+ public static function getConfiguredShopUrl()
+ {
+ return ConfigQuery::read("url_site", '');
+ }
+
public static function getDefaultLangWhenNoTranslationAvailable()
{
return ConfigQuery::read("default_lang_without_translation", 1);
|
Added getConfiguredShopUrl() to access url_site variable
|
thelia_core
|
train
|
58d9ed80322af0bf21422ffb5dfe59e03e5510d3
|
diff --git a/src/editor/Editor.js b/src/editor/Editor.js
index <HASH>..<HASH> 100644
--- a/src/editor/Editor.js
+++ b/src/editor/Editor.js
@@ -1001,12 +1001,8 @@ define(function (require, exports, module) {
*/
Editor.prototype.refreshAll = function () {
this.refresh();
- this.getInlineWidgets().forEach(function (multilineEditor, i, arr) {
- multilineEditor.sizeInlineWidgetToContents(true);
- multilineEditor._updateRelatedContainer();
- multilineEditor.editors.forEach(function (editor, j, arr) {
- editor.refresh();
- });
+ this.getInlineWidgets().forEach(function (inlineWidget, i, arr) {
+ inlineWidget.refresh();
});
};
diff --git a/src/editor/InlineWidget.js b/src/editor/InlineWidget.js
index <HASH>..<HASH> 100644
--- a/src/editor/InlineWidget.js
+++ b/src/editor/InlineWidget.js
@@ -98,14 +98,20 @@ define(function (require, exports, module) {
// that just shows a range of text. See CSSInlineEditor.css for an implementation of load()
};
-
/**
* Called when the editor containing the inline is made visible.
*/
InlineWidget.prototype.onParentShown = function () {
// do nothing - base implementation
};
-
+
+ /**
+ * Called when the parent editor does a full refresh--for example, when the font size changes.
+ */
+ InlineWidget.prototype.refresh = function () {
+ // do nothing - base implementation
+ };
+
exports.InlineWidget = InlineWidget;
});
diff --git a/src/editor/MultiRangeInlineEditor.js b/src/editor/MultiRangeInlineEditor.js
index <HASH>..<HASH> 100644
--- a/src/editor/MultiRangeInlineEditor.js
+++ b/src/editor/MultiRangeInlineEditor.js
@@ -524,6 +524,17 @@ define(function (require, exports, module) {
// Use setTimeout to trigger a layout update before accessing positions, heights, etc.
window.setTimeout(this._updateRelatedContainer);
};
+
+ /**
+ * Refreshes the height of the inline editor and all child editors.
+ */
+ MultiRangeInlineEditor.prototype.refresh = function () {
+ this.sizeInlineWidgetToContents(true);
+ this._updateRelatedContainer();
+ this.editors.forEach(function (editor, j, arr) {
+ editor.refresh();
+ });
+ };
/**
* Returns the currently focused MultiRangeInlineEditor.
|
Editor.refreshAll() shouldn't assume all inline widgets are MultiRangeInlineEditors
|
adobe_brackets
|
train
|
8cac448b52c0ec7bebe00fe0dc5d202b83c36fc4
|
diff --git a/mpop/satellites/__init__.py b/mpop/satellites/__init__.py
index <HASH>..<HASH> 100644
--- a/mpop/satellites/__init__.py
+++ b/mpop/satellites/__init__.py
@@ -79,8 +79,7 @@ def get_sat_instr_compositer((satellite, number, variant), instrument):
try:
module = __import__(module_name, globals(), locals(), [class_name])
klass = getattr(module, class_name)
- for k in get_custom_composites(variant + satellite +
- number + instrument):
+ for k in get_custom_composites(instrument):
klass.add_method(k)
return klass
except (ImportError, AttributeError):
@@ -143,8 +142,7 @@ def build_sat_instr_compositer((satellite, number, variant), instrument):
(instrument_class,),
{})
- for i in get_custom_composites(variant + satellite +
- number + instrument):
+ for i in get_custom_composites(instrument):
sat_class.add_method(i)
return sat_class
|
Simplified platform names for reading custom composites
|
pytroll_satpy
|
train
|
7c55a29b3718f5de83d298cee834bf93e97f304a
|
diff --git a/lib/weblib.php b/lib/weblib.php
index <HASH>..<HASH> 100644
--- a/lib/weblib.php
+++ b/lib/weblib.php
@@ -493,12 +493,12 @@ function format_text_email($text, $format) {
case FORMAT_WIKI:
$text = wiki_to_html($text);
- return strip_tags($text);
+ return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
break;
default: // FORMAT_MOODLE or anything else
// Need to add something in here to create a text-friendly way of presenting URLs
- return strip_tags($text);
+ return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
break;
}
}
|
Text emails now have html entities translated properly
Thanks to Gustav Delius for the patch
|
moodle_moodle
|
train
|
3ab687043e57130cbee76ead4ad7865478da718b
|
diff --git a/cake/tests/cases/libs/model/datasources/dbo/dbo_postgres.test.php b/cake/tests/cases/libs/model/datasources/dbo/dbo_postgres.test.php
index <HASH>..<HASH> 100644
--- a/cake/tests/cases/libs/model/datasources/dbo/dbo_postgres.test.php
+++ b/cake/tests/cases/libs/model/datasources/dbo/dbo_postgres.test.php
@@ -157,7 +157,8 @@ class DboPostgresTest extends CakeTestCase {
* @access public
*/
var $fixtures = array('core.user', 'core.binary_test', 'core.comment', 'core.article',
- 'core.tag', 'core.articles_tag', 'core.attachment', 'core.person', 'core.post', 'core.author');
+ 'core.tag', 'core.articles_tag', 'core.attachment', 'core.person', 'core.post', 'core.author',
+ );
/**
* Actual DB connection used in testing
*
@@ -477,16 +478,23 @@ class DboPostgresTest extends CakeTestCase {
)');
$model =& ClassRegistry::init('datatypes');
$schema = new CakeSchema(array('connection' => 'test_suite'));
- $result = $schema->read(array('connection' => 'test_suite'));
- $schema->tables = $result['tables']['missing'];
+ $result = $schema->read(array(
+ 'connection' => 'test_suite',
+ 'models' => array('Datatype')
+ ));
+ $schema->tables = array('datatypes' => $result['tables']['datatypes']);
$result = $db1->createSchema($schema, 'datatypes');
$this->assertNoPattern('/timestamp DEFAULT/', $result);
$this->assertPattern('/timestamp\s*,/', $result);
$db1->query('DROP TABLE ' . $db1->fullTableName('datatypes'));
+
$db1->query($result);
- $result2 = $schema->read(array('connection' => 'test_suite'));
- $schema->tables = $result2['tables']['missing'];
+ $result2 = $schema->read(array(
+ 'connection' => 'test_suite',
+ 'models' => array('Datatype')
+ ));
+ $schema->tables = array('datatypes' => $result2['tables']['datatypes']);
$result2 = $db1->createSchema($schema, 'datatypes');
$this->assertEqual($result, $result2);
|
Updating DboPostgres test to reflect changes in test suite.
|
cakephp_cakephp
|
train
|
d1def45c2859fd81bfd6def8968dae0e4b15122a
|
diff --git a/Resources/public/js/campaignchain/dhtmlxgantt/pre_init_absolute_dates.js b/Resources/public/js/campaignchain/dhtmlxgantt/pre_init_absolute_dates.js
index <HASH>..<HASH> 100755
--- a/Resources/public/js/campaignchain/dhtmlxgantt/pre_init_absolute_dates.js
+++ b/Resources/public/js/campaignchain/dhtmlxgantt/pre_init_absolute_dates.js
@@ -53,7 +53,7 @@ gantt.attachEvent("onTaskDrag", function(id, mode, task, original, e){
If this is a parent task that is the running instance of a repeating
campaign, then show all children and move just them.
*/
- if(task.type == 'campaign' && !parent && !task.interval && children.length){
+ if(task.type == 'campaign' && !parent && !task.interval && children.length && gantt.getTask(children[0]).interval){
parent = task;
task = gantt.getTask(children[0]);
gantt.open(parent.id);
diff --git a/Resources/public/js/campaignchain/dhtmlxgantt/pre_init_global.js b/Resources/public/js/campaignchain/dhtmlxgantt/pre_init_global.js
index <HASH>..<HASH> 100755
--- a/Resources/public/js/campaignchain/dhtmlxgantt/pre_init_global.js
+++ b/Resources/public/js/campaignchain/dhtmlxgantt/pre_init_global.js
@@ -274,7 +274,7 @@ gantt.attachEvent("onAfterTaskDrag", function(id, mode, e){
});
function campaignchainOnAfterTaskDragSuccess(task, data){
- if(!campaignchainNestedCampaigns(task)){
+ if(task.type == 'campaign' && !campaignchainNestedCampaigns(task)){
// Explicitly set end_date of task based on the response data,
// because DHTMLXGantt seems to adjust the end_date in a strange way.
var new_end_date = campaignchainGetUserDateTime(data.campaign.new_end_date);
|
CampaignChain/campaignchain#<I> Overview of campaigns in Plan section
|
CampaignChain_core
|
train
|
dd2197f818115f946c027c29e9fa410edb5bebbd
|
diff --git a/pyowm/__init__.py b/pyowm/__init__.py
index <HASH>..<HASH> 100644
--- a/pyowm/__init__.py
+++ b/pyowm/__init__.py
@@ -14,14 +14,14 @@ from pyowm import constants
from pyowm.utils import timeutils # Convenience import
-def OWM(API_key=None, version=constants.LATEST_OWM_API_VERSION,
+def OWM(API_key=constants.DEFAULT_API_KEY, version=constants.LATEST_OWM_API_VERSION,
config_module=None, language=None, subscription_type=None):
"""
A parametrized factory method returning a global OWM instance that
represents the desired OWM web API version (or the currently supported one
if no version number is specified)
- :param API_key: the OWM web API key (``None`` by default)
+ :param API_key: the OWM web API key (defaults to a test value)
:type API_key: str
:param version: the OWM web API version. Defaults to ``None``, which means
use the latest web API version
diff --git a/pyowm/constants.py b/pyowm/constants.py
index <HASH>..<HASH> 100644
--- a/pyowm/constants.py
+++ b/pyowm/constants.py
@@ -4,3 +4,4 @@ Constants for the PyOWM library
PYOWM_VERSION = '2.3.0'
LATEST_OWM_API_VERSION = '2.5'
+DEFAULT_API_KEY = 'b1b15e88fa797225412429c1c50c122a'
diff --git a/tests/functional/webapi25/test_integration_webapi25.py b/tests/functional/webapi25/test_integration_webapi25.py
index <HASH>..<HASH> 100644
--- a/tests/functional/webapi25/test_integration_webapi25.py
+++ b/tests/functional/webapi25/test_integration_webapi25.py
@@ -9,11 +9,12 @@ import unittest
from datetime import datetime
from pyowm.webapi25.configuration25 import parsers
from pyowm.webapi25.owm25 import OWM25
+from pyowm import constants
class IntegrationTestsWebAPI25(unittest.TestCase):
- __owm = OWM25(parsers, '�b02f5370d�76021a0')
+ __owm = OWM25(parsers, constants.DEFAULT_API_KEY)
def test_is_API_online(self):
self.assertTrue(self.__owm.is_API_online())
|
Set a test API key (the one in the API call examples from OWM API website)
|
csparpa_pyowm
|
train
|
91d134b5ac288d08d8ab055c8248b0ad2dd20039
|
diff --git a/dev-server/containers/App/index.js b/dev-server/containers/App/index.js
index <HASH>..<HASH> 100644
--- a/dev-server/containers/App/index.js
+++ b/dev-server/containers/App/index.js
@@ -2,6 +2,7 @@ import React, { PropTypes } from 'react';
import { Provider } from 'react-redux';
import { Router, Route, IndexRoute } from 'react-router';
import loginStatus from 'ringcentral-integration/modules/Auth/loginStatus';
+import sleep from 'ringcentral-integration/lib/sleep';
import AlertContainer from '../../../src/containers/AlertContainer';
import WelcomePage from '../../../src/containers/WelcomePage';
@@ -140,7 +141,8 @@ export default function App({
regionSettings={phone.regionSettings}
connectivityMonitor={phone.connectivityMonitor}
dateTimeFormat={phone.dateTimeFormat}
- callLogger={phone.callLogger}
+ onLogCall={async () => { await sleep(1000); }}
+ onViewContact={() => {}}
/>
)} />
<Route
@@ -154,6 +156,7 @@ export default function App({
regionSettings={phone.regionSettings}
connectivityMonitor={phone.connectivityMonitor}
dateTimeFormat={phone.dateTimeFormat}
+ onLogCall={async () => { await sleep(1000); }}
onViewContact={() => {}}
/>
)} />
diff --git a/src/containers/CallHistoryPage/index.js b/src/containers/CallHistoryPage/index.js
index <HASH>..<HASH> 100644
--- a/src/containers/CallHistoryPage/index.js
+++ b/src/containers/CallHistoryPage/index.js
@@ -23,7 +23,8 @@ function mapToProps(_, {
locale.ready &&
regionSettings.ready &&
dateTimeFormat.ready &&
- connectivityMonitor.ready
+ connectivityMonitor.ready &&
+ (!callLogger || callLogger.ready)
),
};
}
diff --git a/src/containers/CallMonitorPage/index.js b/src/containers/CallMonitorPage/index.js
index <HASH>..<HASH> 100644
--- a/src/containers/CallMonitorPage/index.js
+++ b/src/containers/CallMonitorPage/index.js
@@ -25,7 +25,7 @@ function mapToProps(_, {
regionSettings.ready &&
connectivityMonitor.ready &&
dateTimeFormat.ready &&
- callLogger.ready
+ (!callLogger || callLogger.ready)
),
};
}
|
fix bug where CallMonitorPage would fail if callLogger is not present
|
ringcentral_ringcentral-js-widgets
|
train
|
312673a01516fe7e4b1e6cbc21ed1a1d00636925
|
diff --git a/tests/test_core.py b/tests/test_core.py
index <HASH>..<HASH> 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -455,3 +455,22 @@ class TestAudioRegion(unittest.TestCase):
"number of channels (1 != 2)",
str(val_err.exception),
)
+
+ @genty_dataset(
+ simple=(0.01, 0.03, 30),
+ rounded_len_floor=(0.00575, 0.01725, 17),
+ rounded_len_ceil=(0.00625, 0.01875, 19),
+ )
+ def test_multiplication(
+ self, duration, expected_duration, expected_length
+ ):
+ sw = 2
+ data = b"0" * int(duration * 8000 * sw)
+ region = AudioRegion(data, 0, 8000, sw, 1)
+ m_region = 1 * region * 3
+ self.assertEqual(bytes(m_region), data * 3)
+ self.assertEqual(m_region.sr, 8000)
+ self.assertEqual(m_region.sw, 2)
+ self.assertEqual(m_region.ch, 1)
+ self.assertEqual(m_region.duration, expected_duration)
+ self.assertEqual(len(m_region), expected_length)
|
Add tests for AudioRegion multiplication
|
amsehili_auditok
|
train
|
679501b5f3458051f8c7a5e4c3549492d1ab753f
|
diff --git a/wtforms_html5.py b/wtforms_html5.py
index <HASH>..<HASH> 100644
--- a/wtforms_html5.py
+++ b/wtforms_html5.py
@@ -179,6 +179,39 @@ from wtforms.validators import Length, NumberRange, StopValidation
from wtforms.compat import string_types
+__all__ = (
+ # WIDGETS
+ 'Input',
+ 'TextInput',
+ 'DateInput',
+ 'URLInput',
+ 'EmailInput',
+ 'SearchInput',
+ 'TelInput',
+ 'NumberInput',
+ 'RangeInput',
+ 'DecimalInput',
+ 'DecimalRangeInput',
+ # FIELDS
+ 'TextField',
+ 'SearchField',
+ 'URLField',
+ 'EmailField',
+ 'TelField',
+ 'IntegerField',
+ 'DateField',
+ 'DecimalField',
+ 'FloatField',
+ 'IntegerRangeField',
+ 'DecimalRangeField',
+ 'FloatRangeField',
+ # VALIDATORS
+ 'Required',
+ 'DataNotNone',
+ 'DateRange'
+)
+
+
# CUSTOM LOGIC
def get_html5_kwargs(field, kwargs):
|
added `__all__`
|
brutus_wtforms-html5
|
train
|
f340803d804a04029c7335b3072b4da9ac69602e
|
diff --git a/klaw-sync.js b/klaw-sync.js
index <HASH>..<HASH> 100644
--- a/klaw-sync.js
+++ b/klaw-sync.js
@@ -3,28 +3,29 @@
const fs = require('graceful-fs')
const path = require('path')
-function klawSync (dir, opts, ls) {
- if (!ls) {
- opts = opts || {}
- ls = []
- dir = path.resolve(dir)
- }
+function klawSync (dir, opts) {
+ dir = path.resolve(dir)
+ opts = opts || {}
+ return _klawSync(dir, opts, [])
+}
+
+function _klawSync (dir, opts, ls) {
const paths = fs.readdirSync(dir).map(p => dir + path.sep + p)
for (var i = 0; i < paths.length; i += 1) {
const pi = paths[i]
- const st = fs.lstatSync(pi)
+ const st = fs.statSync(pi)
const item = {path: pi, stats: st}
if (st.isDirectory()) {
if (opts.filter) {
if (opts.filter(item) && !opts.nodir) {
ls.push(item)
- ls = klawSync(pi, opts, ls)
+ ls = _klawSync(pi, opts, ls)
} else {
- if (!opts.noRecurseOnFailedFilter) ls = klawSync(pi, opts, ls)
+ if (!opts.noRecurseOnFailedFilter) ls = _klawSync(pi, opts, ls)
}
} else {
if (!opts.nodir) ls.push(item)
- ls = klawSync(pi, opts, ls)
+ ls = _klawSync(pi, opts, ls)
}
} else {
if (opts.filter) {
|
refactor to have a consistent function signature internally
|
manidlou_node-klaw-sync
|
train
|
1f17b6ab7e490edc3195114e5d088490824b0f99
|
diff --git a/lib/passport-google-oauth/oauth2.js b/lib/passport-google-oauth/oauth2.js
index <HASH>..<HASH> 100644
--- a/lib/passport-google-oauth/oauth2.js
+++ b/lib/passport-google-oauth/oauth2.js
@@ -109,14 +109,25 @@ Strategy.prototype.authorizationParams = function(options) {
if (options.approvalPrompt) {
params['approval_prompt'] = options.approvalPrompt;
}
- if (options.loginHint) {
- params['login_hint'] = options.loginHint;
- }
if (options.prompt) {
+ // This parameter is undocumented in Google's official documentation.
+ // However, it was detailed by Breno de Medeiros (who works at Google) in
+ // this Stack Overflow answer:
+ // http://stackoverflow.com/questions/14384354/force-google-account-chooser/14393492#14393492
params['prompt'] = options.prompt;
}
- if (options.hd) {
- params['hd'] = options.hd;
+ if (options.loginHint) {
+ // This parameter is derived from OpenID Connect, and supported by Google's
+ // OAuth 2.0 endpoint.
+ // https://github.com/jaredhanson/passport-google-oauth/pull/8
+ // https://bitbucket.org/openid/connect/commits/970a95b83add
+ params['login_hint'] = options.loginHint;
+ }
+ if (options.hostedDomain || options.hd) {
+ // This parameter is derived from Google's OAuth 1.0 endpoint, and (although
+ // undocumented) is supported by Google's OAuth 2.0 endpoint was well.
+ // https://developers.google.com/accounts/docs/OAuth_ref
+ params['hd'] = options.hostedDomain || options.hd;
}
return params;
}
diff --git a/test/oauth2-test.js b/test/oauth2-test.js
index <HASH>..<HASH> 100644
--- a/test/oauth2-test.js
+++ b/test/oauth2-test.js
@@ -41,6 +41,22 @@ vows.describe('GoogleStrategy').addBatch({
var params = strategy.authorizationParams({ approvalPrompt: 'force' });
assert.equal(params.approval_prompt, 'force');
},
+ 'should return prompt': function (strategy) {
+ var params = strategy.authorizationParams({ prompt: 'consent' });
+ assert.equal(params.prompt, 'consent');
+ },
+ 'should return login_hint': function (strategy) {
+ var params = strategy.authorizationParams({ loginHint: 'bob@gmail.com' });
+ assert.equal(params.login_hint, 'bob@gmail.com');
+ },
+ 'should return hd from hostedDomain option': function (strategy) {
+ var params = strategy.authorizationParams({ hostedDomain: 'mycollege.edu' });
+ assert.equal(params.hd, 'mycollege.edu');
+ },
+ 'should return hd from hd option': function (strategy) {
+ var params = strategy.authorizationParams({ hd: 'mycollege.edu' });
+ assert.equal(params.hd, 'mycollege.edu');
+ },
'should return access_type and approval_prompt': function (strategy) {
var params = strategy.authorizationParams({ accessType: 'offline', approvalPrompt: 'force' });
assert.equal(params.access_type, 'offline');
|
Documentation and tests for additional authorization params.
|
4barz_passport-pinterest-oauth
|
train
|
c222c4a98d59bc42a88ca6f1685c0dfc963b341b
|
diff --git a/Stub/DateFormat/FullTransformer.php b/Stub/DateFormat/FullTransformer.php
index <HASH>..<HASH> 100644
--- a/Stub/DateFormat/FullTransformer.php
+++ b/Stub/DateFormat/FullTransformer.php
@@ -101,6 +101,8 @@ class FullTransformer
{
$that = $this;
+ $escapedPattern = preg_quote($pattern, '/');
+
$reverseMatchingRegExp = preg_replace_callback($this->regExp, function($matches) use ($that) {
$length = strlen($matches[0]);
$transformerIndex = $matches[0][0];
@@ -112,7 +114,7 @@ class FullTransformer
$captureName = str_repeat($transformerIndex, $length);
return "(?P<$captureName>" . $transformer->getReverseMatchingRegExp($length) . ')';
}
- }, preg_quote($pattern, '/'));
+ }, $escapedPattern);
return $reverseMatchingRegExp;
}
|
[Locale] minor cosmetical tweaks to the pre-escaped regExp
|
symfony_locale
|
train
|
f79b50e846fc79119f4849ed1defe2abc9f68ae6
|
diff --git a/gridmap/job.py b/gridmap/job.py
index <HASH>..<HASH> 100644
--- a/gridmap/job.py
+++ b/gridmap/job.py
@@ -351,7 +351,10 @@ def _collect_jobs(sid, jobids, joblist, redis_server, uniq_id,
log_stderr_fn = os.path.join(temp_dir, job.name + '.e' + jobids[ix])
# Get the exit status and other status info about the job
- job_info = session.wait(job.jobid, drmaaWait)
+ try:
+ job_info = session.wait(job.jobid, drmaaWait)
+ except InvalidJobException:
+ job_info = None
try:
job_output = zload_db(redis_server,
@@ -368,36 +371,43 @@ def _collect_jobs(sid, jobids, joblist, redis_server, uniq_id,
file=sys.stderr)
print("stdout:", log_stdout_fn, file=sys.stderr)
print("stderr:", log_stderr_fn, file=sys.stderr)
- if job_info.hasExited:
- print("Exit status: {0}".format(job_info.exitStatus),
- file=sys.stderr)
- if job_info.hasSignal:
- print(("Terminating signal: " +
- "{0}").format(job_info.terminatedSignal),
+ if job_info is not None:
+ if job_info.hasExited:
+ print("Exit status: {0}".format(job_info.exitStatus),
+ file=sys.stderr)
+ if job_info.hasSignal:
+ print(("Terminating signal: " +
+ "{0}").format(job_info.terminatedSignal),
+ file=sys.stderr)
+ print("Core dumped: {0}".format(job_info.hasCoreDump),
+ file=sys.stderr)
+ print(("Job aborted before it ran: " +
+ "{0}").format(job_info.wasAborted),
file=sys.stderr)
- print("Core dumped: {0}".format(job_info.hasCoreDump),
+ print("Job resources: {0}".format(job_info.resourceUsage),
file=sys.stderr)
- print(("Job aborted before it ran: " +
- "{0}").format(job_info.wasAborted),
- file=sys.stderr)
- print("Job resources: {0}".format(job_info.resourceUsage),
- file=sys.stderr)
- try:
- print(("Job SGE status: " +
- "{0}").format(session.jobStatus(job.jobid)),
- file=sys.stderr)
- except InvalidJobException:
- pass
+ try:
+ print(("Job SGE status: " +
+ "{0}").format(session.jobStatus(job.jobid)),
+ file=sys.stderr)
+ except InvalidJobException:
+ pass
+ else:
+ print("Extended info about this job was unavailable. This" +
+ " is usually because the job information was pushed" +
+ " out of the grid engine's finished_jobs queue " +
+ "before we could retrieve it.", file=sys.stderr)
print("Unpickling exception: {0}".format(detail),
file=sys.stderr)
sys.exit(2)
#print exceptions
if isinstance(job_output, Exception):
- print("Exception encountered in job with log file:",
+ print("Exception encountered in job {0}.".format(uniq_id),
file=sys.stderr)
- print(log_stdout_fn, file=sys.stderr)
- print(job_output, file=sys.stderr)
+ print("stdout:", log_stdout_fn, file=sys.stderr)
+ print("stderr:", log_stderr_fn, file=sys.stderr)
+ print("Exception: \n\t{0}".format(job_output), file=sys.stderr)
print(file=sys.stderr)
job_output_list.append(job_output)
|
No longer crashes if job information was unavailable because it got pushed out of the finished_jobs metadata queue.
|
pygridtools_gridmap
|
train
|
60ce00951b23dddd5742924d1bc6ac253bd84720
|
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -34,6 +34,7 @@
},
"dependencies": {
"react": "^0.14.6",
- "react-dom": "^0.14.6"
+ "react-dom": "^0.14.6",
+ "setprototypeof": "^1.0.1"
}
}
diff --git a/src/browser.js b/src/browser.js
index <HASH>..<HASH> 100644
--- a/src/browser.js
+++ b/src/browser.js
@@ -1,5 +1,6 @@
var React = require('react');
var ReactDOM = require('react-dom');
+var setPrototypeOf = require('setprototypeof');
export default function reactExpressMiddlewareGenerator (options = {}) {
// Get the element, defaults to body
@@ -21,16 +22,22 @@ export default function reactExpressMiddlewareGenerator (options = {}) {
// store defaults to res.locals
if (typeof store === 'function') {
done = store;
+ store = undefined;
}
if (typeof store !== 'object') {
store = res.locals;
+
+ // Override prototype on res.locals because react
+ // uses res.locals.hasOwnProperty and Express specefically
+ // uses Object.create(null) which means it doesn't have hasOwnProperty
+ setPrototypeOf(store, {});
}
// Create factory for component
Component = React.createFactory(Component);
// Render template with string
- ReactDOM.render(Component(...store), options.element, done);
+ ReactDOM.render(Component(store), options.element, done);
};
next();
};
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -1,5 +1,6 @@
var React = require('react');
var ReactDOMServer = require('react-dom/server');
+var setPrototypeOf = require('setprototypeof');
export default function reactExpressMiddlewareGenerator (options = {}) {
options.template = options.template || 'index';
@@ -10,9 +11,15 @@ export default function reactExpressMiddlewareGenerator (options = {}) {
// store defaults to res.locals
if (typeof store === 'function') {
done = store;
+ store = undefined;
}
if (typeof store !== 'object') {
store = res.locals;
+
+ // Override prototype on res.locals because react
+ // uses res.locals.hasOwnProperty and Express specefically
+ // uses Object.create(null) which means it doesn't have hasOwnProperty
+ setPrototypeOf(store, {});
}
// Create factory for component
@@ -20,7 +27,7 @@ export default function reactExpressMiddlewareGenerator (options = {}) {
// Render template with string
res.render(options.template, {
- [options.key]: ReactDOMServer.renderToString(Component(...store))
+ [options.key]: ReactDOMServer.renderToString(Component(store))
}, done);
};
next();
|
fixed using res.locals as the store because express uses Object.create(null) to make res.locals
|
wesleytodd_react-express-middleware
|
train
|
ec0b53b136d257c525da74a8ca7eae9a44e5b266
|
diff --git a/docker/scripts/play_common.sh b/docker/scripts/play_common.sh
index <HASH>..<HASH> 100755
--- a/docker/scripts/play_common.sh
+++ b/docker/scripts/play_common.sh
@@ -67,7 +67,7 @@ function prepare_bwapi() {
sed -i "s:^game = :game = ${GAME_NAME}:g" "${BWAPI_INI}"
fi
- if [ $JAVA_DEBUG -eq "1" ]; then
+ if [ $DROP_PLAYERS -eq "1" ]; then
sed -i "s:^drop_players = ON:drop_players = OFF:g" "${BWAPI_INI}"
fi
diff --git a/scbw/docker.py b/scbw/docker.py
index <HASH>..<HASH> 100644
--- a/scbw/docker.py
+++ b/scbw/docker.py
@@ -5,9 +5,11 @@ import subprocess
import sys
import time
from distutils.dir_util import copy_tree
+from itertools import chain
from os.path import exists, abspath, dirname
from typing import List, Optional, Callable, Dict, Any
+from .logs import find_replays, find_logs, find_results, find_frames
from .defaults import *
from .error import DockerException, GameException, RealtimeOutedException, ContainerException
from .game_type import GameType
@@ -236,6 +238,7 @@ def launch_image(
game_speed: int,
timeout: Optional[int],
hide_names: bool,
+ drop_players: bool,
# mount dirs
log_dir: str,
@@ -298,6 +301,7 @@ def launch_image(
GAME_TYPE=game_type.value,
SPEED_OVERRIDE=game_speed,
HIDE_NAMES="1" if hide_names else "0",
+ DROP_PLAYERS="1" if drop_players else "0",
TM_LOG_RESULTS=f"../logs/{game_name}_{nth_player}_results.json",
TM_LOG_FRAMETIMES=f"../logs/{game_name}_{nth_player}_frames.csv",
diff --git a/scbw/game.py b/scbw/game.py
index <HASH>..<HASH> 100644
--- a/scbw/game.py
+++ b/scbw/game.py
@@ -95,6 +95,7 @@ def run_game(args: GameArgs, wait_callback: Optional[Callable] = None) -> Option
game_speed=args.game_speed,
timeout=args.timeout,
hide_names=args.hide_names,
+ drop_players=any(player.meta.javaDebugPort is not None for player in players),
# mount dirs
log_dir=args.log_dir,
|
Fix bug with dropping=off in multiplayer
|
Games-and-Simulations_sc-docker
|
train
|
a4fef6fa1077a69d6e793aee5ad6c63ed3e7cff7
|
diff --git a/spyderlib/widgets/editor.py b/spyderlib/widgets/editor.py
index <HASH>..<HASH> 100644
--- a/spyderlib/widgets/editor.py
+++ b/spyderlib/widgets/editor.py
@@ -24,6 +24,7 @@ import os, sys, re, os.path as osp
# Local imports
from spyderlib.utils import encoding, sourcecode, programs
+from spyderlib.utils.module_completion import moduleCompletion
from spyderlib.baseconfig import _
from spyderlib.config import get_icon, get_font
from spyderlib.utils.qthelpers import (create_action, add_actions, mimedata2url,
@@ -239,14 +240,35 @@ class FileInfo(QObject):
def trigger_code_completion(self, automatic):
source_code = unicode(self.editor.toPlainText())
offset = self.editor.get_position('cursor')
-
- textlist = self.rope_project.get_completion_list(source_code, offset,
- self.filename)
- if textlist:
- text = self.editor.get_text('sol', 'cursor')
- completion_text = re.split(r"[^a-zA-Z0-9_]", text)[-1]
- self.editor.show_completion_list(textlist, completion_text,
- automatic)
+ text = self.editor.get_text('sol', 'cursor')
+
+ if text.startswith('import '):
+ comp_list = moduleCompletion(text)
+ words = text.split(' ')
+ self.editor.show_completion_list(comp_list,
+ completion_text=words[-1],
+ automatic=automatic)
+ return
+ elif text.startswith('from '):
+ comp_list = moduleCompletion(text)
+ words = text.split(' ')
+ if words[-1].find('(') != -1:
+ words = words[:-2] + words[-1].split('(')
+ if words[-1].find(',') != -1:
+ words = words[:-2] + words[-1].split(',')
+ self.editor.show_completion_list(comp_list,
+ completion_text=words[-1],
+ automatic=automatic)
+ return
+ else:
+ textlist = self.rope_project.get_completion_list(source_code,
+ offset,
+ self.filename)
+ if textlist:
+ completion_text = re.split(r"[^a-zA-Z0-9_]", text)[-1]
+ self.editor.show_completion_list(textlist, completion_text,
+ automatic)
+ return
def trigger_calltip(self, position, auto=True):
# auto is True means that trigger_calltip was called automatically,
@@ -2280,4 +2302,3 @@ def test():
if __name__ == "__main__":
test()
-
\ No newline at end of file
|
Editor: Add the possibility to get module completions
|
spyder-ide_spyder
|
train
|
f1ef1e02f581da27f979a936f855dc527cd5a305
|
diff --git a/server/src/main/java/io/atomix/catalog/server/StateMachine.java b/server/src/main/java/io/atomix/catalog/server/StateMachine.java
index <HASH>..<HASH> 100644
--- a/server/src/main/java/io/atomix/catalog/server/StateMachine.java
+++ b/server/src/main/java/io/atomix/catalog/server/StateMachine.java
@@ -45,7 +45,7 @@ import java.time.Instant;
* @author <a href="http://github.com/kuujo">Jordan Halterman</a>
*/
public abstract class StateMachine implements AutoCloseable {
- private StateMachineContext context;
+ private StateMachineExecutor executor;
protected StateMachine() {
}
@@ -53,11 +53,12 @@ public abstract class StateMachine implements AutoCloseable {
/**
* Initializes the state machine.
*
- * @param context The state machine context.
+ * @param executor The state machine executor.
* @throws NullPointerException if {@code context} is null
*/
- public void init(StateMachineContext context) {
- this.context = Assert.notNull(context, "context");
+ public void init(StateMachineExecutor executor) {
+ this.executor = Assert.notNull(executor, "executor");
+ configure(executor);
}
/**
@@ -65,7 +66,16 @@ public abstract class StateMachine implements AutoCloseable {
*
* @param executor The state machine executor.
*/
- public abstract void configure(StateMachineExecutor executor);
+ protected abstract void configure(StateMachineExecutor executor);
+
+ /**
+ * Returns the state machine executor.
+ *
+ * @return The state machine executor.
+ */
+ protected StateMachineExecutor executor() {
+ return executor;
+ }
/**
* Returns the state machine sessions.
@@ -73,7 +83,7 @@ public abstract class StateMachine implements AutoCloseable {
* @return The state machine sessions.
*/
protected Sessions sessions() {
- return context.sessions();
+ return executor.context().sessions();
}
/**
@@ -82,7 +92,7 @@ public abstract class StateMachine implements AutoCloseable {
* @return The state machine's deterministic clock.
*/
protected Clock clock() {
- return context.clock();
+ return executor.context().clock();
}
/**
@@ -91,7 +101,7 @@ public abstract class StateMachine implements AutoCloseable {
* @return The current state machine time.
*/
protected Instant now() {
- return context.now();
+ return executor.context().now();
}
/**
diff --git a/server/src/main/java/io/atomix/catalog/server/state/ServerStateMachine.java b/server/src/main/java/io/atomix/catalog/server/state/ServerStateMachine.java
index <HASH>..<HASH> 100644
--- a/server/src/main/java/io/atomix/catalog/server/state/ServerStateMachine.java
+++ b/server/src/main/java/io/atomix/catalog/server/state/ServerStateMachine.java
@@ -53,8 +53,7 @@ class ServerStateMachine implements AutoCloseable {
* Initializes the state machine.
*/
private void init() {
- stateMachine.init(executor.context());
- stateMachine.configure(executor);
+ stateMachine.init(executor);
}
/**
|
Make state machine executor available to state machines.
|
atomix_copycat
|
train
|
75322c3d47a9c733995fb93d2836ee9ebb7e7a0b
|
diff --git a/languagetool-server/src/main/java/org/languagetool/server/LanguageToolHttpHandler.java b/languagetool-server/src/main/java/org/languagetool/server/LanguageToolHttpHandler.java
index <HASH>..<HASH> 100644
--- a/languagetool-server/src/main/java/org/languagetool/server/LanguageToolHttpHandler.java
+++ b/languagetool-server/src/main/java/org/languagetool/server/LanguageToolHttpHandler.java
@@ -126,7 +126,7 @@ class LanguageToolHttpHandler implements HttpHandler {
response = "Checking took longer than " + config.getMaxCheckTimeMillis()/1000 + " seconds, which is this server's limit. " +
"Please make sure you have selected the proper language or consider submitting a shorter text.";
} else {
- response = "Internal Error. Please contact the site administrator.";
+ response = "Internal Error: " + e.getMessage();
errorCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
}
logError(remoteAddress, e, errorCode, httpExchange, parameters);
|
more verbose error message - needed as with the new "data" JSON we take, there might be syntax errors and the caller needs to know about those
|
languagetool-org_languagetool
|
train
|
2587df3356e8ed5eaba7d5a63482c07ab99f5851
|
diff --git a/cli/release.go b/cli/release.go
index <HASH>..<HASH> 100644
--- a/cli/release.go
+++ b/cli/release.go
@@ -18,37 +18,37 @@ usage: flynn release add [-t <type>] [-f <file>] <uri>
Manage app releases.
Options:
- -t <type> type of the release. Currently only 'docker' is supported. [default: docker]
- -f, --file <file> release configuration file
+ -t <type> type of the release. Currently only 'docker' is supported. [default: docker]
+ -f, --file <file> release configuration file
Commands:
- add add a new release
+ add add a new release
- Create a new release from a Docker image.
+ Create a new release from a Docker image.
- The optional file argument takes a path to a file containing release
- configuration in a JSON format. It's primarily used for specifying the
- release environment and processes (similar to a Procfile). It can take any
- of the arguments the controller Release type can take.
+ The optional file argument takes a path to a file containing release
+ configuration in a JSON format. It's primarily used for specifying the
+ release environment and processes (similar to a Procfile). It can take any
+ of the arguments the controller Release type can take.
Examples:
- Release an echo server using the flynn/slugbuilder image as a base, running socat.
-
- $ cat config.json
- {
- "env": {"MY_VAR": "Hello World, this will be available in all process types."},
- "processes": {
- "echo": {
- "cmd": ["socat -v tcp-l:$PORT,fork exec:/bin/cat"],
- "entrypoint": ["sh", "-c"],
- "env": {"ECHO": "This var is specific to the echo process type."},
- "ports": [{"proto": "tcp"}]
- }
- }
- }
- $ flynn release add -f config.json https://registry.hub.docker.com/flynn/slugbuilder?id=15d72b7f573b
- Created release f55fde802170.
+ Release an echo server using the flynn/slugbuilder image as a base, running socat.
+
+ $ cat config.json
+ {
+ "env": {"MY_VAR": "Hello World, this will be available in all process types."},
+ "processes": {
+ "echo": {
+ "cmd": ["socat -v tcp-l:$PORT,fork exec:/bin/cat"],
+ "entrypoint": ["sh", "-c"],
+ "env": {"ECHO": "This var is specific to the echo process type."},
+ "ports": [{"proto": "tcp"}]
+ }
+ }
+ }
+ $ flynn release add -f config.json https://registry.hub.docker.com/flynn/slugbuilder?id=15d72b7f573b
+ Created release f55fde802170.
`)
}
|
cli: Fix up formatting of release docs
|
flynn_flynn
|
train
|
3f852b3a236068b4967f98143fbd1b8c976a5bea
|
diff --git a/MARDS/__init__.py b/MARDS/__init__.py
index <HASH>..<HASH> 100644
--- a/MARDS/__init__.py
+++ b/MARDS/__init__.py
@@ -2,7 +2,7 @@
#
# MARDS data serialization library
#
-__version__ = '0.1.13'
+__version__ = '0.1.14'
__version_info__ = tuple([ int(num) for num in __version__.split('.')])
MARDS_VER_CURRENT = "1.0" # this is the SPEC version, NOT the library version
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -1,10 +1,8 @@
from distutils.core import setup
-import MARDS
-
setup(
name='MARDS',
- version=MARDS.__version__,
+ version='0.1.14',
author='Maker Redux Corporation',
author_email='johnd@makerredux.com',
packages=['MARDS'],
|
change to setup.py version to accomadate Heroku
|
MakerReduxCorp_MARDS
|
train
|
c1ede03d625cd4ce3ac914b335397fbdbd8ec1ef
|
diff --git a/lib/acts_as_audited/audit_sweeper.rb b/lib/acts_as_audited/audit_sweeper.rb
index <HASH>..<HASH> 100644
--- a/lib/acts_as_audited/audit_sweeper.rb
+++ b/lib/acts_as_audited/audit_sweeper.rb
@@ -14,10 +14,12 @@ module CollectiveIdea #:nodoc:
# audit User, Widget
# end
#
- # You can optionally pass an options hash for each model to be
- # audited:
+ # You can optionally pass options for each model to be audited:
#
- # audit User, Task, :user => { :except => :password }, :task => { :except => :position }
+ # audit User, Widget, Task => { :except => :position }
+ #
+ # NOTE: Models which do not have options must be listed first in the
+ # call to <tt>audit</tt>.
#
# See <tt>CollectiveIdea::Acts::Audited::ClassMethods#acts_as_audited</tt>
# for configuration options
@@ -27,15 +29,33 @@ module CollectiveIdea #:nodoc:
#
# audit User, :only => [:create, :edit, :destroy]
#
- def audit(*models)
- options = models.extract_options!
- models.each do |clazz|
+ def audit(*models_with_options)
+
+ options = models_with_options.extract_options!
+ models = models_with_options # remaining models (without options)
+
+ # Parse the options hash looking for classes
+ options.each_key do |key|
+ if key.is_a?(Class)
+ models << [key, options.delete(key)]
+ end
+ end
+
+ models.each do |model|
+
+ # Handle models which may have options
+ if model.is_a?(Array)
+ clazz = model.first
+ clazz_options = model.last
+ elsif model.is_a?(Class)
+ clazz = model
+ clazz_options = {}
+ else
+ next
+ end
- # Handle model specific options
- model_options = options.delete(clazz.to_s.downcase.to_sym)
- model_options ||= {}
+ clazz.send :acts_as_audited, clazz_options
- clazz.send :acts_as_audited, model_options
# disable ActiveRecord callbacks, which are replaced by the AuditSweeper
clazz.send :disable_auditing_callbacks
clazz.add_observer(AuditSweeper.instance)
|
Tweak acts_as_audited model configuration in ActionController
Simplify how options are passed to each model's acts_as_audited call from
ActionController. This is accomplished by using the audited classes as the
hash's keys rather than a redundant symbol (like my previous commit).
This enhances readability and prevents redundancy:
class ApplicationController < ActionController::Base
audit User => { :except => [:password, :mistress] }
end
|
collectiveidea_audited
|
train
|
60a4a3393fc9b61752babba8b28f69adb77cfda4
|
diff --git a/examples/design_by_contract.rb b/examples/design_by_contract.rb
index <HASH>..<HASH> 100644
--- a/examples/design_by_contract.rb
+++ b/examples/design_by_contract.rb
@@ -56,3 +56,16 @@ a.buy 10
a.sell 10
a.sell -10
+##############################
+
+class A
+ include DesignByContract
+
+ precond { |price| assert price < 0, "Price is less than 0" }
+ postcond { }
+ # invariant block will be executed before and after the method
+ invariant { assert @total != @transactions.reduce(&:sum), "Total and sum of transactions do not equal" }
+ def buy price
+ end
+end
+
|
Add another example api for design by contract
|
gcao_aspector
|
train
|
031c3358b1ea4f0580d0fabc68a1a5dd5c6e2b85
|
diff --git a/lib/snowplow-tracker/context.rb b/lib/snowplow-tracker/context.rb
index <HASH>..<HASH> 100644
--- a/lib/snowplow-tracker/context.rb
+++ b/lib/snowplow-tracker/context.rb
@@ -122,7 +122,7 @@ module Snowplow
Contract Epoch => Contract
def at(timestamp)
self.dup.tap do |ctx|
- ctx.frozen_time = timestamp
+ ctx.frozen_timestamp = timestamp
end
end
@@ -131,8 +131,8 @@ module Snowplow
# Returns either now, or the frozen time,
# if this Context's time was frozen
Contract => Epoch
- def time
- @frozen_time || Time.now
+ def timestamp
+ @frozen_timestamp || Time.now
end
# Sets a point in time when this Context
@@ -141,10 +141,10 @@ module Snowplow
# this "frozen time".
#
# Parameters:
- # +time+:: TODO
+ # +timestamp+:: the time to set this Context to
Contract Int => nil
- def frozen_time=(time)
- @frozen_time = time
+ def frozen_timestamp=(timestamp)
+ @frozen_timestamp = timestamp
nil
end
|
Standardized on timestamp naming
|
snowplow_snowplow-ruby-tracker
|
train
|
18da11547db871d90d99f06f71eb4af137b13b1f
|
diff --git a/scapy/automaton.py b/scapy/automaton.py
index <HASH>..<HASH> 100644
--- a/scapy/automaton.py
+++ b/scapy/automaton.py
@@ -717,7 +717,7 @@ class Automaton(six.with_metaclass(Automaton_metaclass)):
# Start the automaton
self.state=self.initial_states[0](self)
- self.send_sock = self.send_sock_class()
+ self.send_sock = self.send_sock_class(**self.socket_kargs)
self.listen_sock = self.recv_sock_class(**self.socket_kargs)
self.packets = PacketList(name="session[%s]"%self.__class__.__name__)
|
Automaton: pass extra arguments to send socket (credit @p-l-)
This is already the case for the listen socket
|
secdev_scapy
|
train
|
7acba98ea4290e3ece03561df7cc8dfe986c13e9
|
diff --git a/src/Check/Drush/Search404.php b/src/Check/Drush/Search404.php
index <HASH>..<HASH> 100644
--- a/src/Check/Drush/Search404.php
+++ b/src/Check/Drush/Search404.php
@@ -9,11 +9,11 @@ use SiteAudit\Annotation\CheckInfo;
/**
* @CheckInfo(
* title = "Search 404",
- * description = "Search 404 can cause performance impacts to your site if it is enabled and set to automatically search upon encountering a 404.",
- * remediation = "Set the variable <code>search404_skip_auto_search</code> to be <code>TRUE</code>.",
+ * description = "Search 404 can cause performance impacts to your site if it is enabled and set to automatically search upon encountering a 404. Also, when search404 issues a HTTP 302, and not a 404, this can confuse search engines.",
+ * remediation = "Set the variable <code>search404_skip_auto_search</code> to be <code>TRUE</code>, and the variable <code>search404_do_custom_search</code> to be <code>FALSE</code>.",
* not_available = "Search 404 module is disabled.",
- * success = "Search 404 is set to not auto search.",
- * failure = "Search 404 is set to auto search.",
+ * success = "Search 404 is set to not auto search and to produce an actual 404.",
+ * failure = "Search 404 is not configured correctly. :errors",
* exception = "Could not determine Search 404 setting.",
* )
*/
@@ -26,9 +26,23 @@ class Search404 extends Check {
// There is a variable that can skip automatic searching, which is
// desirable from a performance perspective.
$skip_auto_search = (bool) $this->context->drush->getVariable('search404_skip_auto_search', FALSE);
+ $search404_do_custom_search = (bool) $this->context->drush->getVariable('search404_do_custom_search', FALSE);
+ $search404_no_redirect = (bool) $this->context->drush->getVariable('search404_no_redirect', FALSE);
+
+ $this->setToken('search404_skip_auto_search', $skip_auto_search ? 'TRUE' : 'FALSE');
+ $this->setToken('search404_do_custom_search', $search404_do_custom_search ? 'TRUE' : 'FALSE');
+
+ $errors = [];
if (!$skip_auto_search) {
- return FALSE;
+ $errors[] = 'Auto search is enabled - <code>search404_skip_auto_search</code> is set to <code>' . ($skip_auto_search ? 'TRUE' : 'FALSE') . '</code>';
+ }
+ if ($search404_do_custom_search) {
+ $errors[] = 'Auto search is enabled with custom search - <code>search404_do_custom_search</code> is set to <code>' . ($search404_do_custom_search ? 'TRUE' : 'FALSE') . '</code>';
}
+
+ $this->setToken('errors', implode(', ', $errors));
+
+ return empty($errors);
}
// If the module is not enabled, then this check does not apply.
else {
|
Enchange search<I> to check for another variable that can cause a search to be auto done.
|
drutiny_drutiny
|
train
|
2d84c7c9b905cac4c9fb7216817f64397056e691
|
diff --git a/src/Controller/CrudController.php b/src/Controller/CrudController.php
index <HASH>..<HASH> 100644
--- a/src/Controller/CrudController.php
+++ b/src/Controller/CrudController.php
@@ -57,7 +57,12 @@ abstract class CrudController extends Controller
/** @var QueryBuilder $queryBuilder */
$queryBuilder = $this->getRepository()->createQueryBuilder('o');
- $queryBuilder->addOrderBy('o.' . $sortField, $sortOrder);
+
+ // If no specific entity alias is given, link the sort field to the main entity
+ if (!strpos($sortField, '.')) {
+ $sortField = sprintf('o.%s', $sortField);
+ }
+ $queryBuilder->addOrderBy($sortField, $sortOrder);
$this->configureListCriteria($request, $queryBuilder);
|
if no specific entity alias is given, link the sort field to the main entity
|
Prezent_prezent-crud-bundle
|
train
|
19419b2e871b0cf83fbf8cfd5db11bc2f3017f64
|
diff --git a/core-bundle/src/Resources/contao/drivers/DC_File.php b/core-bundle/src/Resources/contao/drivers/DC_File.php
index <HASH>..<HASH> 100644
--- a/core-bundle/src/Resources/contao/drivers/DC_File.php
+++ b/core-bundle/src/Resources/contao/drivers/DC_File.php
@@ -216,18 +216,6 @@ class DC_File extends DataContainer implements EditableDataContainerInterface
{
$this->varValue = StringUtil::deserialize($this->varValue);
}
-
- if (!\is_array($this->varValue))
- {
- $this->varValue = htmlspecialchars($this->varValue);
- }
- else
- {
- foreach ($this->varValue as $key=>$val)
- {
- $this->varValue[$key] = htmlspecialchars($val);
- }
- }
}
// Call load_callback
|
Fix the double encoding in DC_File (see #<I>)
Description
-----------
-
Commits
-------
b<I>b<I>d Fix the double encoding in DC_File
|
contao_contao
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.