hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
692ff8823191319516ff42514851e9e91e2badcc
|
diff --git a/fhub_core/contrib.py b/fhub_core/contrib.py
index <HASH>..<HASH> 100644
--- a/fhub_core/contrib.py
+++ b/fhub_core/contrib.py
@@ -51,17 +51,17 @@ def get_contrib_features(contrib):
'Failed to import module {modname}'
.format(modname=modname))
continue
- features = _get_contrib_features_from_module(mod)
+ features = get_contrib_features_from_module(mod)
contrib_features.extend(features)
else:
- features = _get_contrib_features_from_module(contrib)
+ features = get_contrib_features_from_module(contrib)
contrib_features.extend(features)
return contrib_features
else:
raise ValueError('Input is not a module')
-def _get_contrib_features_from_module(mod):
+def get_contrib_features_from_module(mod):
contrib_features = []
logger.debug(
@@ -70,7 +70,7 @@ def _get_contrib_features_from_module(mod):
# case 1: file defines `features` variable
try:
- features = _import_contrib_feature_from_collection(mod)
+ features = import_contrib_feature_from_collection(mod)
contrib_features.extend(features)
logger.debug(
'Imported {n} feature(s) from {modname} from collection'
@@ -78,7 +78,7 @@ def _get_contrib_features_from_module(mod):
except ImportError:
# case 2: file has at least `input` and `transformer` defined
try:
- feature = _import_contrib_feature_from_components(mod)
+ feature = import_contrib_feature_from_components(mod)
contrib_features.append(feature)
logger.debug(
'Imported 1 feature from {modname} from components'
@@ -92,10 +92,10 @@ def _get_contrib_features_from_module(mod):
return contrib_features
-def _import_contrib_feature_from_components(mod):
+def import_contrib_feature_from_components(mod):
required = ['input', 'transformer']
optional = ['name', 'description', 'output', 'options']
- required_vars, optional_vars = _import_names_from_module(
+ required_vars, optional_vars = import_names_from_module(
mod, required, optional)
feature = Feature(
input=required_vars['input'],
@@ -105,10 +105,10 @@ def _import_contrib_feature_from_components(mod):
return feature
-def _import_contrib_feature_from_collection(mod):
+def import_contrib_feature_from_collection(mod):
required = 'features'
optional = None
- required_vars, _ = _import_names_from_module(
+ required_vars, _ = import_names_from_module(
mod, required, optional)
features = required_vars['features']
for feature in features:
@@ -116,7 +116,7 @@ def _import_contrib_feature_from_collection(mod):
return features
-def _import_names_from_module(mod, required, optional):
+def import_names_from_module(mod, required, optional):
msg = funcy.partial(
'Required variable {varname} not found in module {modname}'
|
Remove _ prefix from contrib functions
|
HDI-Project_ballet
|
train
|
413486ebd2facb79125c378324f5219f5c753cb1
|
diff --git a/src/Breaker.php b/src/Breaker.php
index <HASH>..<HASH> 100644
--- a/src/Breaker.php
+++ b/src/Breaker.php
@@ -171,7 +171,7 @@ class Breaker
protected function isClosed(Circuit $circuit)
{
if ($this->handler->isClosed($circuit)) {
- $this->dispatcher->dispatch(CircuitEvents::CLOSED, (new CircuitEvent($circuit)));
+ $this->dispatcher->dispatch(new CircuitEvent($circuit), CircuitEvents::CLOSED);
return true;
}
@@ -190,7 +190,7 @@ class Breaker
{
$open = false;
if ($this->handler->isOpen($circuit)) {
- $this->dispatcher->dispatch(CircuitEvents::OPEN, (new CircuitEvent($circuit)));
+ $this->dispatcher->dispatch(new CircuitEvent($circuit), CircuitEvents::OPEN);
$open = true;
}
@@ -208,7 +208,7 @@ class Breaker
protected function isHalfOpen(Circuit $circuit)
{
if ($this->handler->isHalfOpen($circuit)) {
- $this->dispatcher->dispatch(CircuitEvents::HALF_OPEN, (new CircuitEvent($circuit)));
+ $this->dispatcher->dispatch(new CircuitEvent($circuit), CircuitEvents::HALF_OPEN);
return true;
}
@@ -225,7 +225,7 @@ class Breaker
{
$circuit->resetFailure();
- $this->dispatcher->dispatch(CircuitEvents::SUCCESS, (new CircuitEvent($circuit)));
+ $this->dispatcher->dispatch(new CircuitEvent($circuit), CircuitEvents::SUCCESS);
$this->writeToStore($circuit);
}
@@ -239,7 +239,7 @@ class Breaker
$circuit->incrementFailure();
$circuit->setLastFailure(time());
- $this->dispatcher->dispatch(CircuitEvents::FAILURE, (new CircuitEvent($circuit)));
+ $this->dispatcher->dispatch(new CircuitEvent($circuit), CircuitEvents::FAILURE);
$this->writeToStore($circuit);
}
|
fix events (#<I>)
fix(event): fix event dispatcher method
|
eljam_circuit-breaker
|
train
|
df5d4efce4ea5dacae940c7c1fa23455027f3528
|
diff --git a/js/bleutrade.js b/js/bleutrade.js
index <HASH>..<HASH> 100644
--- a/js/bleutrade.js
+++ b/js/bleutrade.js
@@ -557,7 +557,7 @@ module.exports = class bleutrade extends Exchange {
'currency': code,
};
} else if (part.indexOf ('order id') === 0) {
- referenceId = part.replace ('order id', '');
+ referenceId = part.replace ('order id ', '');
}
//
// does not belong to Ledger, related to parseTransaction
|
[bleutrade] remove unwanted leading space on reference id
|
ccxt_ccxt
|
train
|
71095b7353e205a759bbe4eecd0803b689a49b79
|
diff --git a/lib/jrubyfx.rb b/lib/jrubyfx.rb
index <HASH>..<HASH> 100644
--- a/lib/jrubyfx.rb
+++ b/lib/jrubyfx.rb
@@ -39,6 +39,7 @@ module JRubyFX
java_import 'javafx.animation.RotateTransition'
java_import 'javafx.animation.ScaleTransition'
java_import 'javafx.animation.Timeline'
+ java_import 'javafx.application.Platform'
java_import 'javafx.beans.property.SimpleDoubleProperty'
java_import 'javafx.beans.value.ChangeListener'
java_import 'javafx.collections.FXCollections'
@@ -129,6 +130,13 @@ module JRubyFX
end
##
+ # Convenience method so anything can safely schedule to run on JavaFX
+ # main thread.
+ def run_later(&block)
+ Platform.run_later &block
+ end
+
+ ##
# Create "build" a new JavaFX instance with the provided class and
# set properties (e.g. setters) on that new instance plus also invoke
# any block passed against this new instance
|
Add run_later() to main JRubyFX module so we can easily communicate between normal Java threads and main JavaFX thread
|
jruby_jrubyfx
|
train
|
493a23809d6e0f339f45ad4b76e3d412e750af7a
|
diff --git a/control/src/main/java/org/kaazing/robot/control/TcpRobotControl.java b/control/src/main/java/org/kaazing/robot/control/TcpRobotControl.java
index <HASH>..<HASH> 100644
--- a/control/src/main/java/org/kaazing/robot/control/TcpRobotControl.java
+++ b/control/src/main/java/org/kaazing/robot/control/TcpRobotControl.java
@@ -59,8 +59,9 @@ public class TcpRobotControl implements RobotControl {
private final URL location;
private URLConnection connection;
+ BufferedReader textIn;
- public TcpRobotControl(URL location) {
+ public TcpRobotControl(URL location) throws Exception {
this.location = location;
}
@@ -68,6 +69,9 @@ public class TcpRobotControl implements RobotControl {
public void connect() throws Exception {
connection = location.openConnection();
connection.connect();
+ InputStream bytesIn = connection.getInputStream();
+ CharsetDecoder decoder = UTF_8.newDecoder();
+ textIn = new BufferedReader(new InputStreamReader(bytesIn, decoder));
}
@Override
@@ -129,30 +133,26 @@ public class TcpRobotControl implements RobotControl {
connection.setReadTimeout((int) unit.toMillis(timeout));
- InputStream bytesIn = connection.getInputStream();
- CharsetDecoder decoder = UTF_8.newDecoder();
- BufferedReader textIn = new BufferedReader(new InputStreamReader(bytesIn, decoder));
-
String eventType = textIn.readLine();
switch (eventType.charAt(0)) {
case 'P':
if ("PREPARED".equals(eventType)) {
- return readPreparedEvent(textIn);
+ return readPreparedEvent();
}
break;
case 'S':
if ("STARTED".equals(eventType)) {
- return readStartedEvent(textIn);
+ return readStartedEvent();
}
break;
case 'E':
if ("ERROR".equals(eventType)) {
- return readErrorEvent(textIn);
+ return readErrorEvent();
}
break;
case 'F':
if ("FINISHED".equals(eventType)) {
- return readFinishedEvent(textIn);
+ return readFinishedEvent();
}
break;
}
@@ -206,7 +206,7 @@ public class TcpRobotControl implements RobotControl {
textOut.flush();
}
- private PreparedEvent readPreparedEvent(BufferedReader textIn) throws IOException {
+ private PreparedEvent readPreparedEvent() throws IOException {
PreparedEvent prepared = new PreparedEvent();
String line;
do {
@@ -229,7 +229,7 @@ public class TcpRobotControl implements RobotControl {
return prepared;
}
- private StartedEvent readStartedEvent(BufferedReader textIn) throws IOException {
+ private StartedEvent readStartedEvent() throws IOException {
StartedEvent started = new StartedEvent();
String line;
do {
@@ -252,8 +252,7 @@ public class TcpRobotControl implements RobotControl {
return started;
}
- // TODO: fix
- private FinishedEvent readFinishedEvent(BufferedReader textIn) throws IOException {
+ private FinishedEvent readFinishedEvent() throws IOException {
FinishedEvent finished = new FinishedEvent();
String line;
int length = -1;
@@ -283,7 +282,7 @@ public class TcpRobotControl implements RobotControl {
// note: this assumes bytes-length == string-length (ASCII)
// note: zero-length script should be non-null
if (length >= 0) {
- finished.setExpectedScript(readContent(textIn, length));
+ finished.setExpectedScript(readContent(length));
}
do {
@@ -307,13 +306,13 @@ public class TcpRobotControl implements RobotControl {
// note: this assumes bytes-length == string-length (ASCII)
// note: zero-length script should be non-null
if (length >= 0) {
- finished.setObservedScript(readContent(textIn, length));
+ finished.setObservedScript(readContent(length));
}
return finished;
}
- private ErrorEvent readErrorEvent(BufferedReader textIn) throws IOException {
+ private ErrorEvent readErrorEvent() throws IOException {
ErrorEvent error = new ErrorEvent();
String line;
int length = 0;
@@ -347,13 +346,13 @@ public class TcpRobotControl implements RobotControl {
// note: this assumes bytes-length == string-length (ASCII)
if (length > 0) {
- error.setDescription(readContent(textIn, length));
+ error.setDescription(readContent(length));
}
return error;
}
- private String readContent(final BufferedReader textIn, final int length) throws IOException {
+ private String readContent(final int length) throws IOException {
final char[] content = new char[length];
int bytesRead = 0;
do {
|
KG-<I>:Resolve issue of data loss from input stream because of creation of new BufferedReader for each readEvent call. Appeared to occur when two events came back near simultaneously. Creates only a single BufferedReader instance now
|
k3po_k3po
|
train
|
98bcc2c35fb6362cfd29ab14b28910f226f2455d
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -166,12 +166,13 @@ module.exports = function (content) {
var format = formats[i];
var filename = fontConfig.fileName || options.fileName || '[chunkhash]-[fontname].[ext]';
var chunkHash = filename.indexOf('[chunkhash]') !== -1
- ? hashFiles(generatorOptions.files, options.hashLength) : '';
+ ? hashFiles(generatorOptions.files, options.hashLength)
+ : '';
filename = filename
- .replace('[chunkhash]', chunkHash)
- .replace('[fontname]', generatorOptions.fontName)
- .replace('[ext]', format);
+ .replace('[chunkhash]', chunkHash)
+ .replace('[fontname]', generatorOptions.fontName)
+ .replace('[ext]', format);
if (!embed) {
var formatFilename = loaderUtils.interpolateName(this,
|
Applied semistandard's syntax suggestions
|
jeerbl_webfonts-loader
|
train
|
7efad66ae83e5b6e2961cb174f0b0b76380baba3
|
diff --git a/test/e2e/storage/testsuites/provisioning.go b/test/e2e/storage/testsuites/provisioning.go
index <HASH>..<HASH> 100644
--- a/test/e2e/storage/testsuites/provisioning.go
+++ b/test/e2e/storage/testsuites/provisioning.go
@@ -173,7 +173,7 @@ type provisioningTestInput struct {
}
func testProvisioning(input *provisioningTestInput) {
- It("should provision storage", func() {
+ It("should provision storage with defaults", func() {
TestDynamicProvisioning(input.testCase, input.cs, input.pvc, input.sc)
})
|
e2e/storage: distinct test names for provisioning
A test name should not be the subset of another, because then it is
impossible to focus on it.
In this case, -ginkgo.focus=should.provision.storage ran both "should
provision storage" and "should provision storage with mount options"
without the ability to select just the former.
|
kubernetes_kubernetes
|
train
|
12d4efdbb02c440015e6fec2435e9f246cc9b8da
|
diff --git a/wro4j-extensions/src/main/java/ro/isdc/wro/extensions/processor/js/PackerJsProcessor.java b/wro4j-extensions/src/main/java/ro/isdc/wro/extensions/processor/js/PackerJsProcessor.java
index <HASH>..<HASH> 100644
--- a/wro4j-extensions/src/main/java/ro/isdc/wro/extensions/processor/js/PackerJsProcessor.java
+++ b/wro4j-extensions/src/main/java/ro/isdc/wro/extensions/processor/js/PackerJsProcessor.java
@@ -14,6 +14,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ro.isdc.wro.WroRuntimeException;
+import ro.isdc.wro.extensions.processor.support.ObjectPoolHelper;
import ro.isdc.wro.extensions.processor.support.packer.PackerJs;
import ro.isdc.wro.model.group.processor.Minimize;
import ro.isdc.wro.model.resource.Resource;
@@ -21,6 +22,7 @@ import ro.isdc.wro.model.resource.ResourceType;
import ro.isdc.wro.model.resource.SupportedResourceType;
import ro.isdc.wro.model.resource.processor.ResourcePostProcessor;
import ro.isdc.wro.model.resource.processor.ResourcePreProcessor;
+import ro.isdc.wro.util.ObjectFactory;
/**
@@ -35,10 +37,18 @@ public class PackerJsProcessor
implements ResourcePreProcessor, ResourcePostProcessor {
private static final Logger LOG = LoggerFactory.getLogger(PackerJsProcessor.class);
public static final String ALIAS = "packerJs";
- /**
- * Engine.
- */
- private PackerJs engine;
+ private ObjectPoolHelper<PackerJs> enginePool;
+
+
+ public PackerJsProcessor() {
+ enginePool = new ObjectPoolHelper<PackerJs>(new ObjectFactory<PackerJs>() {
+ @Override
+ public PackerJs create() {
+ return newPackerJs();
+ }
+ });
+ }
+
/**
* {@inheritDoc}
@@ -46,8 +56,9 @@ public class PackerJsProcessor
public void process(final Resource resource, final Reader reader, final Writer writer)
throws IOException {
final String content = IOUtils.toString(reader);
+ final PackerJs packerJs = enginePool.getObject();
try {
- writer.write(getEngine().pack(content));
+ writer.write(packerJs.pack(content));
} catch (final WroRuntimeException e) {
onException(e);
writer.write(content);
@@ -57,6 +68,7 @@ public class PackerJsProcessor
} finally {
reader.close();
writer.close();
+ enginePool.returnObject(packerJs);
}
}
@@ -69,11 +81,8 @@ public class PackerJsProcessor
/**
* @return PackerJs engine.
*/
- private PackerJs getEngine() {
- if (engine == null) {
- engine = new PackerJs();
- }
- return engine;
+ protected PackerJs newPackerJs() {
+ return new PackerJs();
}
|
make packerJs thread-safe
|
wro4j_wro4j
|
train
|
7dd1b52a29559da27cd9f3cc621eb39523acdeaa
|
diff --git a/lib/Doctrine/Common/Cache/CacheProvider.php b/lib/Doctrine/Common/Cache/CacheProvider.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/Common/Cache/CacheProvider.php
+++ b/lib/Doctrine/Common/Cache/CacheProvider.php
@@ -83,23 +83,20 @@ abstract class CacheProvider implements Cache, MultiGetCache
*/
public function fetchMultiple(array $keys)
{
- if (! $keys) {
- return array();
- }
-
- $queryKeys = array_map(array($this, 'getNamespacedId'), $keys);
-
- $items = $this->doFetchMultiple($queryKeys);
-
- foreach ($keys as $index => $key) {
- $queryKey = $queryKeys[$index];
- if (isset($items[$queryKey])) {
- $items[$key] = $items[$queryKey];
- unset ($items[$queryKey]);
+ // note: the array_combine() is in place to keep an association between our $keys and the $namespacedKeys
+ $namespacedKeys = array_combine($keys, array_map(array($this, 'getNamespacedId'), $keys));
+ $items = $this->doFetchMultiple($namespacedKeys);
+ $foundItems = array();
+
+ // no internal array function supports this sort of mapping: needs to be iterative
+ // this filters and combines keys in one pass
+ foreach ($namespacedKeys as $requestedKey => $namespacedKey) {
+ if (isset($items[$namespacedKey])) {
+ $foundItems[$requestedKey] = $items[$namespacedKey];
}
}
- return $items;
+ return $foundItems;
}
/**
|
#<I> - `getMultiple` will now filter out items not matching the requested keys
|
doctrine_cache
|
train
|
2ba4b32b2232d2d293ebf25103d7dad636fafd5c
|
diff --git a/salt/runner.py b/salt/runner.py
index <HASH>..<HASH> 100644
--- a/salt/runner.py
+++ b/salt/runner.py
@@ -49,76 +49,6 @@ class RunnerClient(mixins.SyncClientMixin, mixins.AsyncClientMixin, object):
self.outputters = salt.loader.outputters(opts)
self.event = salt.utils.event.get_master_event(self.opts, self.opts['sock_dir'])
- def cmd(self, fun, arg, pub_data=None, kwarg=None):
- '''
- Execute a runner function
-
- .. code-block:: python
-
- >>> opts = salt.config.master_config('/etc/salt/master')
- >>> runner = salt.runner.RunnerClient(opts)
- >>> runner.cmd('jobs.list_jobs', [])
- {
- '20131219215650131543': {
- 'Arguments': [300],
- 'Function': 'test.sleep',
- 'StartTime': '2013, Dec 19 21:56:50.131543',
- 'Target': '*',
- 'Target-type': 'glob',
- 'User': 'saltdev'
- },
- '20131219215921857715': {
- 'Arguments': [300],
- 'Function': 'test.sleep',
- 'StartTime': '2013, Dec 19 21:59:21.857715',
- 'Target': '*',
- 'Target-type': 'glob',
- 'User': 'saltdev'
- },
- }
-
- '''
- if pub_data is None:
- pub_data = {}
- if not isinstance(pub_data, dict):
- raise salt.exceptions.SaltInvocationError(
- 'pub_data must be formatted as a dictionary'
- )
- if kwarg is None:
- kwarg = {}
- if not isinstance(kwarg, dict):
- raise salt.exceptions.SaltInvocationError(
- 'kwarg must be formatted as a dictionary'
- )
- arglist = salt.utils.args.parse_input(arg)
-
- # if you were passed kwarg, add it to arglist
- if kwarg:
- kwarg['__kwarg__'] = True
- arglist.append(kwarg)
-
- args, kwargs = salt.minion.load_args_and_kwargs(
- self.functions[fun], arglist, pub_data
- )
- low = {'fun': fun,
- 'args': args,
- 'kwargs': kwargs}
- return self.low(fun, low)
-
- def master_call(self, **kwargs):
- '''
- Execute a runner function through the master network interface (eauth).
- '''
- load = kwargs
- load['cmd'] = 'runner'
- channel = salt.transport.Channel.factory(self.opts,
- crypt='clear',
- usage='master_call')
- ret = channel.send(load)
- if isinstance(ret, collections.Mapping):
- if 'error' in ret:
- raise_error(**ret['error'])
- return ret
def _reformat_low(self, low):
'''
@@ -154,7 +84,8 @@ class RunnerClient(mixins.SyncClientMixin, mixins.AsyncClientMixin, object):
})
'''
reformatted_low = self._reformat_low(low)
- return self.master_call(**reformatted_low)
+
+ return mixins.AsyncClientMixin.cmd_async(**reformatted_low)
def cmd_sync(self, low, timeout=None):
'''
@@ -173,18 +104,7 @@ class RunnerClient(mixins.SyncClientMixin, mixins.AsyncClientMixin, object):
})
'''
reformatted_low = self._reformat_low(low)
- job = self.master_call(**reformatted_low)
- ret_tag = salt.utils.event.tagify('ret', base=job['tag'])
-
- if timeout is None:
- timeout = 300
- ret = self.event.get_event(tag=ret_tag, full=True, wait=timeout)
- if ret is None:
- raise salt.exceptions.SaltClientTimeout(
- "RunnerClient job '{0}' timed out".format(job['jid']),
- jid=job['jid'])
-
- return ret['data']['return']
+ return mixins.SyncClientMixin.cmd_sync(**reformatted_low)
class Runner(RunnerClient):
@@ -230,21 +150,7 @@ class Runner(RunnerClient):
# output rets if you have some
if not self.opts.get('quiet', False):
- for suffix, ret in self.get_async_returns(async_pub['tag']):
- # TODO: clean up this event print out. We probably want something
- # more general, since this will get *really* messy as
- # people use more events that don't quite fit into this mold
- if suffix == 'new': # skip "new" events
- continue
- elif suffix == 'ret': # for "ret" just print out return
- salt.output.display_output(ret['return'], '', self.opts)
- # otherwise, if it specified an outputter, we assume it has "data" to print out
- elif isinstance(ret, dict) and 'outputter' in ret and ret['outputter'] is not None:
- print(self.outputters[ret['outputter']](ret['data']))
- # and if all else fails, just use the outputter
- else:
- salt.output.display_output(ret, '', self.opts)
-
+ self.print_async_returns(async_pub['tag'])
except salt.exceptions.SaltException as exc:
ret = str(exc)
|
Consolidate to mixins funcs
|
saltstack_salt
|
train
|
4527749dc9507ee677e1b1fefcd2d1929be542c1
|
diff --git a/bokeh/server/application_context.py b/bokeh/server/application_context.py
index <HASH>..<HASH> 100644
--- a/bokeh/server/application_context.py
+++ b/bokeh/server/application_context.py
@@ -186,7 +186,7 @@ class ApplicationContext(object):
def _discard_session(self, session, should_discard):
if session.connection_count > 0:
raise RuntimeError("Should not be discarding a session with open connections")
- log.debug("Discarding session %r last in use %r seconds ago", session.id, session.seconds_since_last_unsubscribe)
+ log.debug("Discarding session %r last in use %r milliseconds ago", session.id, session.milliseconds_since_last_unsubscribe)
session_context = self._session_contexts[session.id]
@@ -218,10 +218,10 @@ class ApplicationContext(object):
raise gen.Return(None)
@gen.coroutine
- def cleanup_sessions(self, unused_session_linger_seconds):
+ def cleanup_sessions(self, unused_session_linger_milliseconds):
def should_discard_ignoring_block(session):
return session.connection_count == 0 and \
- (session.seconds_since_last_unsubscribe > unused_session_linger_seconds or \
+ (session.milliseconds_since_last_unsubscribe > unused_session_linger_milliseconds or \
session.expiration_requested)
# build a temp list to avoid trouble from self._sessions changes
to_discard = []
diff --git a/bokeh/server/session.py b/bokeh/server/session.py
index <HASH>..<HASH> 100644
--- a/bokeh/server/session.py
+++ b/bokeh/server/session.py
@@ -12,12 +12,15 @@ from bokeh.util.tornado import _DocumentCallbackGroup, yield_for_all_futures
import time
def current_time():
+ '''Return the time in milliseconds since the epoch as a floating
+ point number.
+ '''
try:
# python >=3.3 only
- return time.monotonic()
+ return time.monotonic() * 1000
except:
# if your python is old, don't set your clock backward!
- return time.time()
+ return time.time() * 1000
def _needs_document_lock(func):
'''Decorator that adds the necessary locking and post-processing
@@ -136,7 +139,7 @@ class ServerSession(object):
return len(self._subscribed_connections)
@property
- def seconds_since_last_unsubscribe(self):
+ def milliseconds_since_last_unsubscribe(self):
return current_time() - self._last_unsubscribe_time
@_needs_document_lock
diff --git a/bokeh/server/tornado.py b/bokeh/server/tornado.py
index <HASH>..<HASH> 100644
--- a/bokeh/server/tornado.py
+++ b/bokeh/server/tornado.py
@@ -175,7 +175,7 @@ class BokehTornado(TornadoApplication):
self._stats_job = PeriodicCallback(self.log_stats,
stats_log_frequency_milliseconds,
io_loop=self._loop)
- self._unused_session_linger_seconds = unused_session_lifetime_milliseconds
+ self._unused_session_linger_milliseconds = unused_session_lifetime_milliseconds
self._cleanup_job = PeriodicCallback(self.cleanup_sessions,
check_unused_sessions_milliseconds,
io_loop=self._loop)
@@ -299,7 +299,7 @@ class BokehTornado(TornadoApplication):
@gen.coroutine
def cleanup_sessions(self):
for app in self._applications.values():
- yield app.cleanup_sessions(self._unused_session_linger_seconds)
+ yield app.cleanup_sessions(self._unused_session_linger_milliseconds)
raise gen.Return(None)
def log_stats(self):
|
Change units of unused session lifetime
Units were originally in seconds and are now in milliseconds.
Fixes #<I>.
|
bokeh_bokeh
|
train
|
f307fa2c90c95e925d57bbeb01cdf457656bd662
|
diff --git a/src/org/opencms/ui/actions/CmsDisplayAction.java b/src/org/opencms/ui/actions/CmsDisplayAction.java
index <HASH>..<HASH> 100644
--- a/src/org/opencms/ui/actions/CmsDisplayAction.java
+++ b/src/org/opencms/ui/actions/CmsDisplayAction.java
@@ -103,7 +103,9 @@ public class CmsDisplayAction extends A_CmsWorkplaceAction implements I_CmsDefau
*/
public CmsMenuItemVisibilityMode getVisibility(CmsObject cms, List<CmsResource> resources) {
- if ((resources.size() == 1) && !CmsResourceTypeXmlContainerPage.isContainerPage(resources.get(0))) {
+ if ((resources.size() == 1)
+ && resources.get(0).isFile()
+ && !CmsResourceTypeXmlContainerPage.isContainerPage(resources.get(0))) {
return CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE;
} else {
return CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE;
|
Fixing display action visibility for folders.
|
alkacon_opencms-core
|
train
|
a2b7950c52b5a11c202598d891225e381276b43a
|
diff --git a/lib/xmpp/client.js b/lib/xmpp/client.js
index <HASH>..<HASH> 100644
--- a/lib/xmpp/client.js
+++ b/lib/xmpp/client.js
@@ -35,6 +35,7 @@ var IQID_SESSION = 'sess',
* legacySSL: Boolean (optional) - connect to the legacy SSL port, requires at least the host to be specified
* credentials: Dictionary (optional) - TLS or SSL key and certificate credentials
* actAs: String (optional) - if admin user act on behalf of another user (just user)
+ * disallowTLS: Boolean (optional) - prevent upgrading the connection to a secure one via TLS
*
* Examples:
* var cl = new xmpp.Client({
@@ -55,15 +56,15 @@ var IQID_SESSION = 'sess',
* });
*
* Example SASL EXTERNAL:
- *
- * var myCredentials = {
+ *
+ * var myCredentials = {
* // These are necessary only if using the client certificate authentication
* key: fs.readFileSync('key.pem'),
* cert: fs.readFileSync('cert.pem'),
* // passphrase: 'optional'
* };
- * var cl = new xmppClient({jid: "me@example.com", credentials: myCredentials });
-
+ * var cl = new xmppClient({jid: "me@example.com", credentials: myCredentials });
+
*/
function Client(opts) {
var self = this;
diff --git a/lib/xmpp/session.js b/lib/xmpp/session.js
index <HASH>..<HASH> 100644
--- a/lib/xmpp/session.js
+++ b/lib/xmpp/session.js
@@ -24,7 +24,7 @@ function Session(opts) {
this.oauth2_token = opts.oauth2_token;
this.oauth2_auth = opts.oauth2_auth;
this.register = opts.register;
- if (typeof opts.actAs == 'string')
+ if (typeof opts.actAs == 'string')
this.actAs = new JID(opts.actAs);
else
this.actAs = opts.actAs;
@@ -65,8 +65,12 @@ function Session(opts) {
self.connection.emit('connect');
});
} else {
- if (opts.credentials)
- self.connection.credentials = crypto.createCredentials(opts.credentials)
+ if (opts.credentials) {
+ self.connection.credentials = crypto.createCredentials(opts.credentials);
+ }
+ if (opts.disallowTLS) {
+ self.connection.allowTLS = false;
+ }
self.connection.socket.connect(opts.port || 5222, opts.host)
}
} else if (!SRV) {
@@ -75,11 +79,12 @@ function Session(opts) {
if (opts.legacySSL) {
throw "LegacySSL mode does not support DNS lookups";
}
-
if (opts.credentials) {
self.connection.credentials = crypto.createCredentials(opts.credentials);
}
-
+ if (opts.disallowTLS) {
+ self.connection.allowTLS = false;
+ }
var attempt = SRV.connect(self.connection.socket,
['_xmpp-client._tcp'], self.jid.domain, 5222);
attempt.addListener('connect', function() {
|
Adding an option to allow prevention of TLS connection upgrading.
Adding an option to allow prevention of TLS connection upgrading for
situations where this may not be desirable (connecting with an OpenFire
server for example).
|
xmppjs_xmpp.js
|
train
|
8755a105db7eabdadda9add3e702543368fa9e72
|
diff --git a/consul/base.py b/consul/base.py
index <HASH>..<HASH> 100644
--- a/consul/base.py
+++ b/consul/base.py
@@ -536,7 +536,9 @@ class Consul(object):
ttl=None,
http=None,
timeout=None,
- notes=None):
+ notes=None,
+ service_id=None,
+ service_name=None):
"""
Register a new check with the local agent. More documentation
on checks can be found `here
@@ -590,7 +592,13 @@ class Consul(object):
if notes:
payload['notes'] = notes
+
+ if service_id:
+ payload['serviceid'] = service_id
+ if service_name:
+ payload['servicename'] = service_name
+
return self.agent.http.put(
lambda x: x.code == 200,
'/v1/agent/check/register',
|
Adding ability to register checks with services (ServiceID and
ServiceName respectively)
|
cablehead_python-consul
|
train
|
ef20f66b30ec0ba9095f8ef1e4fa6dc0f2b2afb4
|
diff --git a/state/model.go b/state/model.go
index <HASH>..<HASH> 100644
--- a/state/model.go
+++ b/state/model.go
@@ -1409,7 +1409,7 @@ func checkModelEntityRefsEmpty(doc *modelEntityRefsDoc) ([]txn.Op, error) {
isEmpty := func(attribute string) bson.DocElem {
// We consider it empty if the array has no entries, or if the attribute doesn't exist
return bson.DocElem{
- "$or", []bson.M{{
+ Name: "$or", Value: []bson.M{{
attribute: bson.M{"$exists": false},
}, {
attribute: bson.M{"$size": 0},
@@ -1512,7 +1512,7 @@ func noNewStorageModelEntityRefs(doc *modelEntityRefsDoc) []txn.Op {
// is a subset of the previously known set.
}
noNewFilesystems := bson.DocElem{
- "filesystems", bson.D{{
+ Name: "filesystems", Value: bson.D{{
"$not", bson.D{{
"$elemMatch", bson.D{{
"$nin", doc.Filesystems,
diff --git a/state/state.go b/state/state.go
index <HASH>..<HASH> 100644
--- a/state/state.go
+++ b/state/state.go
@@ -297,7 +297,7 @@ func (st *State) removeAllModelDocs(modelAssertion bson.D) error {
}
// Logs are in a separate database so don't get caught by that loop.
- removeModelLogs(st.MongoSession(), modelUUID)
+ _ = removeModelLogs(st.MongoSession(), modelUUID)
// Remove all user permissions for the model.
permPattern := bson.M{
diff --git a/state/testing/suite.go b/state/testing/suite.go
index <HASH>..<HASH> 100644
--- a/state/testing/suite.go
+++ b/state/testing/suite.go
@@ -13,7 +13,7 @@ import (
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
"gopkg.in/juju/names.v3"
- retry "gopkg.in/retry.v1"
+ "gopkg.in/retry.v1"
"github.com/juju/juju/cloud"
"github.com/juju/juju/environs/config"
@@ -98,7 +98,7 @@ func (s *StateSuite) SetUpTest(c *gc.C) {
Clock: s.Clock,
})
s.AddCleanup(func(*gc.C) {
- s.Controller.Close()
+ _ = s.Controller.Close()
close(s.txnSyncNotify)
})
s.StatePool = s.Controller.StatePool()
@@ -120,7 +120,7 @@ func (s *StateSuite) txnNotifyFunc() {
case s.txnSyncNotify <- struct{}{}:
// Try to send something down the channel.
default:
- // However don't get stressed if noone is listening.
+ // However don't get stressed if no one is listening.
}
}
|
Minor comment fixes, explicit struct members and error ignores in the
state package.
|
juju_juju
|
train
|
413b1f06eb27aca8547324c3f35808ef623722c8
|
diff --git a/modules/custom/activenet/src/ActivenetClient.php b/modules/custom/activenet/src/ActivenetClient.php
index <HASH>..<HASH> 100644
--- a/modules/custom/activenet/src/ActivenetClient.php
+++ b/modules/custom/activenet/src/ActivenetClient.php
@@ -2,21 +2,46 @@
namespace Drupal\activenet;
+use Drupal\Core\Config\ConfigFactoryInterface;
+use Drupal\Core\Config\ImmutableConfig;
use GuzzleHttp\Client;
-// use Drupal\activenet\ActivenetClientFactory;
/**
* Class ActivenetClient.
*
* @package Drupal\activenet
*
- * @method mixed getBranches(array $args)
- * @method mixed getSessions(array $args)
- * @method mixed getPrograms(array $args)
- * @method mixed getChildCarePrograms(array $args)
- * @method mixed getMembershipTypes(array $args)
+ * @method mixed getCenters(array $args)
+ * @method mixed getSites(array $args)
+ * @method mixed getActivities(array $args)
+ * @method mixed getActivityTypes(array $args)
+ * @method mixed getActivityOtherCategories(array $args)
+ * @method mixed getFlexRegPrograms(array $args)
+ * @method mixed getFlexRegProgramTypes(array $args)
+ * @method mixed getMembershipPackages(array $args)
+ * @method mixed getMembershipCategories(array $args)
+ * @method mixed getActivityDetail(integer $id)
*/
class ActivenetClient extends Client implements ActivenetClientInterface {
+
+ /**
+ * Settings
+ *
+ * @var array of settings from config
+ */
+ protected $api_settings;
+
+ /**
+ * ActivenetClient constructor
+ * @param array $api_settings
+ * The api config settings.
+ */
+
+ public function setApi(array $api_settings) {
+ $this->api_settings = $api_settings;
+ }
+
+
/**
* Wrapper for 'request' method.
@@ -34,7 +59,6 @@ class ActivenetClient extends Client implements ActivenetClientInterface {
* @throws \Drupal\activenet\ActivenetClientException
*/
private function makeRequest($method, $uri, array $parameters = []) {
-
try {
$response = $this->request($method, $uri, $parameters);
@@ -79,10 +103,10 @@ class ActivenetClient extends Client implements ActivenetClientInterface {
* @throws ActivenetClientException.
*/
public function __call($method, $args) {
- $settings = \Drupal::config('activenet.settings');
- $api_key = $settings->get('api_key');
- $base_uri = $settings->get('base_uri');
+ if(!$this->api_settings) throw new ActivenetClientException(sprintf('Please inject api settings using "$this->setAPI($api_settings)".'));
+ $api_key = $this->api_settings['api_key'];
+ $base_uri = $this->api_settings['base_uri'];
// Prepare suffix for the endpoint.
$suffix = '';
@@ -131,10 +155,11 @@ class ActivenetClient extends Client implements ActivenetClientInterface {
throw new ActivenetClientException(sprintf('Method %s not implemented yet.', $method));
}
- public function getActivityDetail($id){
- $settings = \Drupal::config('activenet.settings');
- $base_uri = $settings->get('base_uri');
- $suffix = '?api_key=' . $settings->get('api_key');
+ public function getActivityDetail(integer $id){
+ if(!$this->api_settings) throw new ActivenetClientException(sprintf('Please inject api settings using "$this->setAPI($api_settings)".'));
+
+ $base_uri = $this->api_settings['base_uri'];
+ $suffix = '?api_key=' . $this->api_settings['api_key'];
return $this->makeRequest('get', $base_uri . 'activities/' . $id . $suffix);
}
diff --git a/modules/custom/activenet/src/ActivenetClientFactory.php b/modules/custom/activenet/src/ActivenetClientFactory.php
index <HASH>..<HASH> 100644
--- a/modules/custom/activenet/src/ActivenetClientFactory.php
+++ b/modules/custom/activenet/src/ActivenetClientFactory.php
@@ -39,7 +39,13 @@ class ActivenetClientFactory implements ActivenetClientFactoryInterface {
'base_uri' => $settings->get('base_uri'),
'headers' => ['Accept' => 'application/json'],
];
- return new ActivenetClient($config);
+ $api_config = [
+ 'base_uri' => $settings->get('base_uri'),
+ 'api_key' => $settings->get('api_key'),
+ ];
+ $client = new ActivenetClient($config);
+ $client->setApi($api_config);
+ return $client;
}
}
|
Debug code removed. Using dependency injection for settings.
|
ymcatwincities_openy
|
train
|
1c89f3bf7d5e0ad5bacb8a4c93b9714cf11534f1
|
diff --git a/src/main/com/mongodb/util/JSON.java b/src/main/com/mongodb/util/JSON.java
index <HASH>..<HASH> 100644
--- a/src/main/com/mongodb/util/JSON.java
+++ b/src/main/com/mongodb/util/JSON.java
@@ -348,7 +348,7 @@ class JSONParser {
// string
case '\'':
case '\"':
- value = parseString();
+ value = parseString(true);
break;
// number
case '0': case '1': case '2': case '3': case '4': case '5':
@@ -395,7 +395,7 @@ class JSONParser {
read('{');
char current = get();
while(get() != '}') {
- String key = parseString();
+ String key = parseString(false);
read(':');
Object value = parse(key);
doCallback(key, value);
@@ -505,22 +505,31 @@ class JSONParser {
* @return the next string.
* @throws JSONParseException if invalid JSON is found
*/
- public String parseString() {
- char quot;
+ public String parseString(boolean needQuote) {
+ char quot = 0;
if(check('\''))
quot = '\'';
else if(check('\"'))
quot = '\"';
- else
+ else if (needQuote)
throw new JSONParseException(s, pos);
char current;
- read(quot);
+ if (quot > 0)
+ read(quot);
StringBuilder buf = new StringBuilder();
int start = pos;
- while(pos < s.length() &&
- (current = s.charAt(pos)) != quot) {
+ while(pos < s.length()) {
+ current = s.charAt(pos);
+ if (quot > 0) {
+ if (current == quot)
+ break;
+ } else {
+ if (current == ':' || current == ' ')
+ break;
+ }
+
if(current == '\\') {
pos++;
@@ -565,9 +574,9 @@ class JSONParser {
}
pos++;
}
- read(quot);
-
- buf.append(s.substring(start, pos-1));
+ buf.append(s.substring(start, pos));
+ if (quot > 0)
+ read(quot);
return buf.toString();
}
|
JAVA-<I>: improve JSON parser to not require quotes around keys
|
mongodb_mongo-java-driver
|
train
|
a5bd0ec7b18a52796dc2ab14d9fa73e950fd0b1b
|
diff --git a/angr/path.py b/angr/path.py
index <HASH>..<HASH> 100644
--- a/angr/path.py
+++ b/angr/path.py
@@ -290,16 +290,20 @@ class Path(object):
#
def _record_path(self, path):
- self.events.extend(path.events)
- self.actions.extend(path.actions)
self.last_events = list(path.last_events)
self.last_actions = list(path.last_actions)
+ self.events.extend(path.events)
+ self.actions.extend(path.actions)
+
self.backtrace.extend(path.backtrace)
self.addr_backtrace.extend(path.addr_backtrace)
self.callstack.callstack.extend(path.callstack.callstack)
+
self.guards.extend(path.guards)
self.sources.extend(path.sources)
self.jumpkinds.extend(path.jumpkinds)
+ self.targets.extend(path.targets)
+
self.length = path.length
self.extra_length = path.extra_length
self.previous_run = path.next_run
@@ -321,9 +325,9 @@ class Path(object):
self.last_events = list(state.log.events)
self.last_actions = list(e for e in state.log.events if isinstance(e, simuvex.SimAction))
-
self.events.extend(self.last_events)
self.actions.extend(self.last_actions)
+
self.jumpkinds.append(state.scratch.jumpkind)
self.targets.append(state.scratch.target)
self.guards.append(state.scratch.guard)
|
properly carry over targets of ancestor paths
|
angr_angr
|
train
|
395c9a1ca7f417813f2889061e32e8e08fa6e810
|
diff --git a/charms/reactive/decorators.py b/charms/reactive/decorators.py
index <HASH>..<HASH> 100644
--- a/charms/reactive/decorators.py
+++ b/charms/reactive/decorators.py
@@ -205,7 +205,7 @@ def not_unless(*desired_states):
return _decorator
-def only_once(action):
+def only_once(action=None):
"""
Ensure that the decorated function is only executed the first time it is called.
@@ -213,6 +213,9 @@ def only_once(action):
once, even if their conditions continue to match on subsequent calls, even
across hook invocations.
"""
+ if action is None:
+ # allow to be used as @only_once or @only_once()
+ return only_once
@wraps(action)
def wrapper(*args, **kwargs):
action_id = _action_id(action)
diff --git a/tests/test_decorators.py b/tests/test_decorators.py
index <HASH>..<HASH> 100644
--- a/tests/test_decorators.py
+++ b/tests/test_decorators.py
@@ -248,6 +248,17 @@ class TestReactiveDecorators(unittest.TestCase):
test(2)
self.assertEquals(calls, [1])
+ def test_only_once_parens(self):
+ calls = []
+
+ @reactive.decorators.only_once()
+ def test(num):
+ calls.append(num)
+
+ test(1)
+ test(2)
+ self.assertEquals(calls, [1])
+
def test_multi(self):
action1 = mock.Mock(name='action1')
action2 = mock.Mock(name='action2')
|
Allow @only_once to be used as @only_once()
Fixes #<I>
|
juju-solutions_charms.reactive
|
train
|
7ad338bfb2c4c3653fea6d50dfbaca15aaa2707e
|
diff --git a/closure/goog/ui/select.js b/closure/goog/ui/select.js
index <HASH>..<HASH> 100644
--- a/closure/goog/ui/select.js
+++ b/closure/goog/ui/select.js
@@ -25,10 +25,8 @@ goog.provide('goog.ui.Select');
goog.require('goog.a11y.aria');
goog.require('goog.a11y.aria.Role');
-goog.require('goog.a11y.aria.State');
goog.require('goog.events.EventType');
goog.require('goog.ui.Component');
-goog.require('goog.ui.IdGenerator');
goog.require('goog.ui.MenuButton');
goog.require('goog.ui.MenuItem');
goog.require('goog.ui.MenuRenderer');
@@ -444,22 +442,6 @@ goog.ui.Select.prototype.updateCaption = function() {
var itemElement = item ? item.getElement() : null;
goog.a11y.aria.setLabel(contentElement, itemElement ?
goog.a11y.aria.getLabel(itemElement) : this.initialAriaLabel_);
-
- var buttonElement = this.getElement();
- // In order for all screenreaders to correctly read the value of the select
- // we add the child containing the value text as the labelledby value
- // of the outer div. We need to be careful here because there may also
- // be other values in the labelledby attribute that need to be preserved.
- if (!contentElement.id && buttonElement) {
- contentElement.id = goog.ui.IdGenerator.getInstance().getNextUniqueId();
- var labelledBy = goog.a11y.aria.getState(buttonElement,
- goog.a11y.aria.State.LABELLEDBY);
- if (labelledBy.indexOf(contentElement.id) == -1) {
- labelledBy += ' ' + contentElement.id;
- goog.a11y.aria.setState(buttonElement, goog.a11y.aria.State.LABELLEDBY,
- labelledBy);
- }
- }
}
};
|
Automated g4 rollback of changelist <I>.
*** Reason for rollback ***
Labels applied to select buttons with aria-label are no longer announced: http://b/<I>
*** Original change description ***
Fixed goog.ui.select so screenreaders correctly read the label select value. Also fixed bug where select items had the wrong aria role so they weren't being read correctly by screenreaders.
***
-------------
Created by MOE: <URL>
|
google_closure-library
|
train
|
12561e85782d4cad363e5745197e15666cba62d1
|
diff --git a/src/main/java/com/monitorjbl/xlsx/impl/StreamingRow.java b/src/main/java/com/monitorjbl/xlsx/impl/StreamingRow.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/monitorjbl/xlsx/impl/StreamingRow.java
+++ b/src/main/java/com/monitorjbl/xlsx/impl/StreamingRow.java
@@ -139,7 +139,14 @@ public class StreamingRow implements Row {
*/
@Override
public Cell getCell(int cellnum, MissingCellPolicy policy) {
- throw new NotSupportedException();
+ StreamingCell cell = (StreamingCell) cellMap.get(cellnum);
+ if (policy == Row.CREATE_NULL_AS_BLANK) {
+ if (cell == null) return new StreamingCell(cellnum, rowIndex);
+
+ } else if (policy == Row.RETURN_BLANK_AS_NULL) {
+ if (cell.getCachedFormulaResultType() == Cell.CELL_TYPE_BLANK) return null;
+ }
+ return cell;
}
/**
|
Basic implementation for getCell with MissingCellPolicy.
|
monitorjbl_excel-streaming-reader
|
train
|
a6482a72c09df80058a634dac0527340300e4b84
|
diff --git a/lib/agent/providers/hardware/windows.js b/lib/agent/providers/hardware/windows.js
index <HASH>..<HASH> 100755
--- a/lib/agent/providers/hardware/windows.js
+++ b/lib/agent/providers/hardware/windows.js
@@ -75,8 +75,8 @@ exports.get_firmware_info = function(callback) {
var fetch = function(key, section, value){
wmic.get_value(section, value, null, function(err, res){
- if (!err && key == "device_type")
- res ? res = 'Laptop' : res = 'Desktop'
+ if (!err && key == 'device_type')
+ res = res ? 'Laptop' : 'Desktop'
if (!err && res)
data[key] = res;
|
Improve code syntax based on PR comment
|
prey_prey-node-client
|
train
|
1596c0db261c525f0e26974265637e1cb3e8657d
|
diff --git a/lib/util/model_util.rb b/lib/util/model_util.rb
index <HASH>..<HASH> 100644
--- a/lib/util/model_util.rb
+++ b/lib/util/model_util.rb
@@ -9,7 +9,6 @@
# NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should
# have received a copy of GPLv2 along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-require 'util/model_util'
module Katello
@@ -32,13 +31,13 @@ module Katello
# hardcoded model names (uses kp_ prefix)
@@table_to_model_hash = {
- "kt_environment" => KTEnvironment
+ "kt_environment" => "KTEnvironment"
}
# convert Rails Model name to Class or nil when no such table name exists
def self.table_to_class name
- return @@table_to_model_hash[name] if @@table_to_model_hash.key? name
- name.classify.constantize
+ class_name = @@table_to_model_hash[name] || name.classify
+ class_name.constantize
rescue NameError => e
# constantize throws NameError
return nil
|
build-fix - don't use model classes on require time
Otherwise it tries to connect to database which fails when generating
API documentation
|
Katello_katello
|
train
|
3a0b05559c1f9f3c5bda34920d4497dfd8b9290a
|
diff --git a/.gitignore b/.gitignore
index <HASH>..<HASH> 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,6 @@
dist
build
+.venv
.coverage
.eggs
.tox
diff --git a/cs/client.py b/cs/client.py
index <HASH>..<HASH> 100644
--- a/cs/client.py
+++ b/cs/client.py
@@ -10,6 +10,7 @@ import sys
import time
from datetime import datetime, timedelta
from distutils.util import strtobool
+from fnmatch import fnmatch
try:
from configparser import ConfigParser
@@ -54,7 +55,8 @@ EXPIRES_FORMAT = "%Y-%m-%dT%H:%M:%S%z"
REQUIRED_CONFIG_KEYS = {"endpoint", "key", "secret", "method", "timeout"}
ALLOWED_CONFIG_KEYS = {"verify", "cert", "retry", "theme", "expiration",
- "poll_interval", "trace", "dangerous_no_tls_verify"}
+ "poll_interval", "trace", "dangerous_no_tls_verify",
+ "header_*"}
DEFAULT_CONFIG = {
"timeout": 10,
"method": "get",
@@ -73,6 +75,22 @@ SUCCESS = 1
FAILURE = 2
+def check_key(key, allowed):
+ """
+ Validate that the specified key is allowed according the provided
+ list of patterns.
+ """
+
+ if key in allowed:
+ return True
+
+ for pattern in allowed:
+ if fnmatch(key, pattern):
+ return True
+
+ return False
+
+
def cs_encode(s):
"""Encode URI component like CloudStack would do before signing.
@@ -137,7 +155,7 @@ class CloudStack(object):
verify=None, cert=None, name=None, retry=0,
job_timeout=None, poll_interval=POLL_INTERVAL,
expiration=timedelta(minutes=10), trace=False,
- dangerous_no_tls_verify=False):
+ dangerous_no_tls_verify=False, headers=None):
self.endpoint = endpoint
self.key = key
self.secret = secret
@@ -147,7 +165,9 @@ class CloudStack(object):
self.verify = verify
else:
self.verify = not dangerous_no_tls_verify
-
+ if headers is None:
+ headers = {}
+ self.headers = headers
self.cert = cert
self.name = name
self.retry = int(retry)
@@ -191,6 +211,9 @@ class CloudStack(object):
fetch_result = params.pop('fetch_result', False)
kind, params = self._prepare_request(command, json, opcode_name,
fetch_list, **params)
+ if headers is None:
+ headers = {}
+ headers.update(self.headers)
done = False
max_retry = self.retry
@@ -432,11 +455,18 @@ def read_config_from_ini(ini_group=None):
if not conf.has_section(ini_group):
return dict(name=None)
- all_keys = REQUIRED_CONFIG_KEYS.union(ALLOWED_CONFIG_KEYS)
- ini_config = {k: v
- for k, v in conf.items(ini_group)
- if v and k in all_keys}
+ ini_config = {
+ k: v
+ for k, v in conf.items(ini_group)
+ if v and check_key(k, REQUIRED_CONFIG_KEYS.union(ALLOWED_CONFIG_KEYS))
+ }
ini_config["name"] = ini_group
+
+ # Convert individual header_* settings into a single dict
+ for k in list(ini_config):
+ if k.startswith("header_"):
+ ini_config.setdefault("headers", {})
+ ini_config["headers"][k[len("header_"):]] = ini_config.pop(k)
return ini_config
diff --git a/tests.py b/tests.py
index <HASH>..<HASH> 100644
--- a/tests.py
+++ b/tests.py
@@ -141,6 +141,8 @@ class ConfigTest(TestCase):
'dangerous_no_tls_verify = true\n'
'theme = monokai\n'
'other = please ignore me\n'
+ 'header_x-custom-header1 = foo\n'
+ 'header_x-custom-header2 = bar\n'
'timeout = 50')
self.addCleanup(partial(os.remove, '/tmp/cloudstack.ini'))
@@ -162,6 +164,10 @@ class ConfigTest(TestCase):
'retry': 0,
'method': 'get',
'cert': None,
+ 'headers': {
+ 'x-custom-header1': 'foo',
+ 'x-custom-header2': 'bar',
+ },
}, conf)
def test_incomplete_config(self):
|
Add support for custom HTTP request headers (#<I>)
This change adds support for user-defined arbitrary headers to be
injected to every outgoing HTTP request to the Exoscale API.
Configuration is done through a new `header_<NAME>` key in the
cloudstack.ini file:
```ini
[cloudstack]
endpoint = <URL>
|
exoscale_cs
|
train
|
5b36835515a6814b66d39b873cb04d36a1854cba
|
diff --git a/Command/GraphQLDumpSchemaCommand.php b/Command/GraphQLDumpSchemaCommand.php
index <HASH>..<HASH> 100644
--- a/Command/GraphQLDumpSchemaCommand.php
+++ b/Command/GraphQLDumpSchemaCommand.php
@@ -4,14 +4,35 @@ namespace Overblog\GraphQLBundle\Command;
use GraphQL\Type\Introspection;
use GraphQL\Utils\SchemaPrinter;
-use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
+use Overblog\GraphQLBundle\Request\Executor as RequestExecutor;
+use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
-class GraphQLDumpSchemaCommand extends ContainerAwareCommand
+class GraphQLDumpSchemaCommand extends Command
{
+ /** @var RequestExecutor */
+ private $requestExecutor;
+
+ /** @var string */
+ private $relayVersion;
+
+ /** @var string */
+ private $baseExportPath;
+
+ public function __construct(
+ RequestExecutor $requestExecutor,
+ $relayVersion,
+ $baseExportPath
+ ) {
+ parent::__construct();
+ $this->requestExecutor = $requestExecutor;
+ $this->relayVersion = $relayVersion;
+ $this->baseExportPath = $baseExportPath;
+ }
+
protected function configure()
{
$this
@@ -61,11 +82,10 @@ class GraphQLDumpSchemaCommand extends ContainerAwareCommand
private function createFile(InputInterface $input)
{
- $container = $this->getContainer();
$format = strtolower($input->getOption('format'));
$schemaName = $input->getOption('schema');
- $requestExecutor = $container->get('overblog_graphql.request_executor');
- $file = $input->getOption('file') ?: $container->getParameter('kernel.root_dir').sprintf('/../var/schema%s.%s', $schemaName ? '.'.$schemaName : '', $format);
+
+ $file = $input->getOption('file') ?: $this->baseExportPath.sprintf('/../var/schema%s.%s', $schemaName ? '.'.$schemaName : '', $format);
switch ($format) {
case 'json':
@@ -77,7 +97,7 @@ class GraphQLDumpSchemaCommand extends ContainerAwareCommand
$modern = $this->useModernJsonFormat($input);
- $result = $requestExecutor
+ $result = $this->requestExecutor
->execute($request, [], $schemaName)
->toArray();
@@ -85,7 +105,7 @@ class GraphQLDumpSchemaCommand extends ContainerAwareCommand
break;
case 'graphql':
- $content = SchemaPrinter::doPrint($requestExecutor->getSchema($schemaName));
+ $content = SchemaPrinter::doPrint($this->requestExecutor->getSchema($schemaName));
break;
default:
@@ -107,7 +127,7 @@ class GraphQLDumpSchemaCommand extends ContainerAwareCommand
// none chosen so fallback on default behavior
if (!$modern && !$classic) {
- return 'modern' === $this->getContainer()->getParameter('overblog_graphql.versions.relay');
+ return 'modern' === $this->relayVersion;
}
return $modern;
diff --git a/Resources/config/services.yml b/Resources/config/services.yml
index <HASH>..<HASH> 100644
--- a/Resources/config/services.yml
+++ b/Resources/config/services.yml
@@ -103,3 +103,13 @@ services:
- "@overblog_graphql.request_parser"
- "%overblog_graphql.handle_cors%"
- "%overblog_graphql.batching_method%"
+
+ overblog_graphql.command.dump_schema:
+ class: Overblog\GraphQLBundle\Command\GraphQLDumpSchemaCommand
+ public: false
+ arguments:
+ - "@overblog_graphql.request_executor"
+ - "%overblog_graphql.versions.relay%"
+ - "%kernel.root_dir%"
+ tags:
+ - { name: console.command }
diff --git a/Tests/Functional/Command/GraphDumpSchemaCommandTest.php b/Tests/Functional/Command/GraphDumpSchemaCommandTest.php
index <HASH>..<HASH> 100644
--- a/Tests/Functional/Command/GraphDumpSchemaCommandTest.php
+++ b/Tests/Functional/Command/GraphDumpSchemaCommandTest.php
@@ -2,7 +2,6 @@
namespace Overblog\GraphQLBundle\Tests\Functional\Command;
-use Overblog\GraphQLBundle\Command\GraphQLDumpSchemaCommand;
use Overblog\GraphQLBundle\Tests\Functional\TestCase;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Command\Command;
@@ -26,7 +25,6 @@ class GraphDumpSchemaCommandTest extends TestCase
$kernel = $client->getKernel();
$application = new Application($kernel);
- $application->add(new GraphQLDumpSchemaCommand());
$this->command = $application->find('graphql:dump-schema');
$this->commandTester = new CommandTester($this->command);
$this->cacheDir = $kernel->getCacheDir();
|
GraphQL Schema Dump command as a service
|
overblog_GraphQLBundle
|
train
|
45cc51edfea9102b98e8efb29dcd9397be18812d
|
diff --git a/influxql/functions.go b/influxql/functions.go
index <HASH>..<HASH> 100644
--- a/influxql/functions.go
+++ b/influxql/functions.go
@@ -949,6 +949,8 @@ func MapFirst(itr Iterator) interface{} {
if k < out.Time {
out.Time = k
out.Val = v
+ } else if k == out.Time && greaterThan(v, out.Val) {
+ out.Val = v
}
}
if pointsYielded {
@@ -976,6 +978,8 @@ func ReduceFirst(values []interface{}) interface{} {
if val.Time < out.Time {
out.Time = val.Time
out.Val = val.Val
+ } else if val.Time == out.Time && greaterThan(val.Val, out.Val) {
+ out.Val = val.Val
}
}
if pointsYielded {
@@ -999,6 +1003,8 @@ func MapLast(itr Iterator) interface{} {
if k > out.Time {
out.Time = k
out.Val = v
+ } else if k == out.Time && greaterThan(v, out.Val) {
+ out.Val = v
}
}
if pointsYielded {
@@ -1027,6 +1033,8 @@ func ReduceLast(values []interface{}) interface{} {
if val.Time > out.Time {
out.Time = val.Time
out.Val = val.Val
+ } else if val.Time == out.Time && greaterThan(val.Val, out.Val) {
+ out.Val = val.Val
}
}
if pointsYielded {
@@ -1112,3 +1120,17 @@ type rawOutputs []*rawQueryMapOutput
func (a rawOutputs) Len() int { return len(a) }
func (a rawOutputs) Less(i, j int) bool { return a[i].Time < a[j].Time }
func (a rawOutputs) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
+
+func greaterThan(a, b interface{}) bool {
+ switch t := a.(type) {
+ case int64:
+ return t > b.(int64)
+ case float64:
+ return t > b.(float64)
+ case string:
+ return t > b.(string)
+ case bool:
+ return t == true
+ }
+ return false
+}
|
During first() and last(), break any tie by value
If 2 or more points during this map-and-reduce share the same timestamp,
the tie is broken by looking at the value. This ensures that these
functions operate in a deterministic manner.
This solution due to @jwilder
|
influxdata_influxdb
|
train
|
f691449954488f445316a06150fa33ed9cc9d28d
|
diff --git a/test/AbstractJobTest.php b/test/AbstractJobTest.php
index <HASH>..<HASH> 100644
--- a/test/AbstractJobTest.php
+++ b/test/AbstractJobTest.php
@@ -80,13 +80,10 @@ class AbstractJobTest extends Test
$this->assertEquals(1, $workerFailed->get());
}
- /**
- * @expectedException \Resque\ResqueException
- */
- public function testInvalidJobThrowsException()
+ public function testInvalidJobReservesNull()
{
$this->resque->enqueue('jobs', 'Resque\Test\NoPerformJob');
$job = $this->worker->reserve();
- $job->perform();
+ $this->assertNull($job);
}
}
|
Change expectation on bad job class
Don't expect an uncaught exception. Instead, reserve to catch
the bad class and process it through the failure backend, eventually
returning null (no valid job to reserve).
|
vend_php-resque
|
train
|
84de9b55584091c6e1b43f447a945120738f4148
|
diff --git a/src/Karma/Command.php b/src/Karma/Command.php
index <HASH>..<HASH> 100644
--- a/src/Karma/Command.php
+++ b/src/Karma/Command.php
@@ -29,6 +29,7 @@ class Command extends \Symfony\Component\Console\Command\Command
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->setOutput($output);
+ $this->printHeader();
$profile = $this->app['profile'];
@@ -88,4 +89,33 @@ class Command extends \Symfony\Component\Console\Command\Command
return $value;
}
+
+ private function printHeader()
+ {
+ $this->output->writeln(sprintf(
+ '<comment>%s</comment>',
+ $this->getLogo()
+ ));
+ }
+
+ private function getLogo()
+ {
+ $logo = <<<ASCIIART
+ _ __
+ | |/ /__ _ _ __ _ __ ___ __ _
+ | ' // _` | '__| '_ ` _ \ / _` |
+ | . \ (_| | | | | | | | | (_| |
+ |_|\_\__,_|_| |_| |_| |_|\__,_|
+
+ASCIIART;
+
+ return sprintf(
+ "%s\n %s %s -\n",
+ $logo,
+ str_pad('', 30 - strlen(Application::VERSION), '-'),
+ Application::VERSION
+ );
+
+ }
+
}
\ No newline at end of file
|
#<I> Add logo and version to each commands
|
Niktux_karma
|
train
|
4168deb572c352ab0824056f8ddc3c35dd9694f7
|
diff --git a/spec/public/abstract_controller/filter_spec.rb b/spec/public/abstract_controller/filter_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/public/abstract_controller/filter_spec.rb
+++ b/spec/public/abstract_controller/filter_spec.rb
@@ -78,6 +78,15 @@ describe Merb::AbstractController, " should support before and after filters" do
running { dispatch_should_make_body("TestConditionalFilterWithNoProcOrSymbol", "") }.should raise_error(ArgumentError, /a Symbol or a Proc/)
end
+ it "should throw an error if an unknown option is passed to a filter" do
+ running { Merb::Test::Fixtures::Abstract.class_eval do
+
+ class TestErrorFilter < Merb::Test::Fixtures::Abstract::Testing
+ before :foo, :except => :index
+ end
+ end }.should raise_error(ArgumentError, /known filter options/)
+ end
+
it "should support passing an argument to a before filter method" do
dispatch_should_make_body("TestBeforeFilterWithArgument", "index action")
end
|
spec for ticket <I>
|
wycats_merb
|
train
|
8eee3e9e714523308e97211c83f1240e67c68667
|
diff --git a/.circleci/config.yml b/.circleci/config.yml
index <HASH>..<HASH> 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -126,6 +126,9 @@ workflows:
- "php-7.0-nginx"
- "php-7.1-nginx"
- coverage:
+ filters:
+ branches:
+ only: /^([0-9]+)\.x$/
requires:
- "php-7.0-apache"
- "php-7.1-apache"
diff --git a/src/Abstracts/Validator.php b/src/Abstracts/Validator.php
index <HASH>..<HASH> 100644
--- a/src/Abstracts/Validator.php
+++ b/src/Abstracts/Validator.php
@@ -94,7 +94,7 @@ abstract class Validator
/** @var Factory $validator */
$factory = app(Factory::class);
- $rules = $this->replaceVariables($rules);
+ $rules = $this->replaceVariables($rules, $model);
/** @var Native $validator */
$validator = $factory->make(
@@ -111,21 +111,24 @@ abstract class Validator
/**
* @param array $rules
+ * @param AbstractModel $model
* @return array
*/
- protected function replaceVariables(array $rules)
+ protected function replaceVariables(array $rules, AbstractModel $model)
{
/** @var Connection $connection */
$connection = app(Connection::class);
- return collect($rules)->map(function ($ruleSet) use ($connection) {
- return collect($ruleSet)->map(function ($rule) use ($connection) {
+ return collect($rules)->map(function ($ruleSet) use ($connection, $model) {
+ return collect($ruleSet)->map(function ($rule) use ($connection, $model) {
return str_replace([
'%system%',
- '%tenant%'
+ '%tenant%',
+ '%id%'
], [
$connection->systemName(),
- $connection->tenantName()
+ $connection->tenantName(),
+ $model->id
], $rule);
})->toArray();
})->toArray();
diff --git a/src/Validators/HostnameValidator.php b/src/Validators/HostnameValidator.php
index <HASH>..<HASH> 100644
--- a/src/Validators/HostnameValidator.php
+++ b/src/Validators/HostnameValidator.php
@@ -29,7 +29,7 @@ class HostnameValidator extends Validator
protected $update = [
'id' => ['required', 'integer'],
- 'fqdn' => ['required', 'string', 'unique:%system%.hostnames,fqdn'],
+ 'fqdn' => ['required', 'string', 'unique:%system%.hostnames,fqdn,%id%'],
'redirect_to' => ['nullable', 'string', 'url'],
'force_https' => ['boolean'],
'under_maintenance_since' => ['nullable', 'date'],
diff --git a/src/Validators/WebsiteValidator.php b/src/Validators/WebsiteValidator.php
index <HASH>..<HASH> 100644
--- a/src/Validators/WebsiteValidator.php
+++ b/src/Validators/WebsiteValidator.php
@@ -23,7 +23,7 @@ class WebsiteValidator extends Validator
'customer_id' => ['integer', 'exists:%system%.customers,id'],
];
protected $update = [
- 'uuid' => ['required', 'string', 'unique:%system%.websites,uuid'],
+ 'uuid' => ['required', 'string', 'unique:%system%.websites,uuid,%id%'],
'customer_id' => ['integer', 'exists:%system%.customers,id'],
];
}
diff --git a/tests/unit-tests/Repositories/HostnameRepositoryTest.php b/tests/unit-tests/Repositories/HostnameRepositoryTest.php
index <HASH>..<HASH> 100644
--- a/tests/unit-tests/Repositories/HostnameRepositoryTest.php
+++ b/tests/unit-tests/Repositories/HostnameRepositoryTest.php
@@ -119,6 +119,16 @@ class HostnameRepositoryTest extends Test
/**
* @test
*/
+ public function hostname_update()
+ {
+ $this->setUpHostnames(true);
+
+ $this->hostnames->update($this->hostname);
+ }
+
+ /**
+ * @test
+ */
public function hostname_delete()
{
$this->hostnames->delete($this->hostname, false);
diff --git a/tests/unit-tests/Repositories/WebsiteRepositoryTest.php b/tests/unit-tests/Repositories/WebsiteRepositoryTest.php
index <HASH>..<HASH> 100644
--- a/tests/unit-tests/Repositories/WebsiteRepositoryTest.php
+++ b/tests/unit-tests/Repositories/WebsiteRepositoryTest.php
@@ -31,6 +31,16 @@ class WebsiteRepositoryTest extends Test
/**
* @test
+ */
+ public function updates_website()
+ {
+ $this->setUpWebsites(true);
+
+ $this->websites->update($this->website);
+ }
+
+ /**
+ * @test
* @depends creates_website
*/
public function deletes_website()
|
<I> fixes validation (#<I>)
* allows %id% in validation rules
* missing model replacement
* fixing the update
* coverage only on version branches
|
tenancy_multi-tenant
|
train
|
4188e461df787cd93d1568f16ad036fbbf76bb25
|
diff --git a/commands.py b/commands.py
index <HASH>..<HASH> 100755
--- a/commands.py
+++ b/commands.py
@@ -369,6 +369,7 @@ def n_fn(srs):
srs.push(a)
def full_factor(n):
+ n=abs(n)
global primes
init_primes_up_to(n)
res=[]
diff --git a/commands.txt b/commands.txt
index <HASH>..<HASH> 100644
--- a/commands.txt
+++ b/commands.txt
@@ -117,9 +117,9 @@
74 (t): pop all elements from stack, flatten any lists and explode any strings, and push them in the same order they were popped (full stack flatten/explode)
75 (u): pop a: push a+1
76 (v): pop a: seed the RNG with a (random.seed(a))
-77 (w): pop a: push the full factorization of a (18 -> [[2,1],[3,2]])
+77 (w): pop a: push the full positive prime factorization of |a| (18 -> [[2,1],[3,2]], -5 -> [[5,1]])
78 (x): pop a,b: push [a,b) (range(a,b))
-79 (y): pop a: push the prime factors of a (18 -> [2,3])
+79 (y): pop a: push the positive prime factors of |a| (18 -> [2,3], -5 -> [5])
7A (z): pop a: repeat . a times (pop a times and print to stdout)
7B ({): pop a: rotate stack right a times
7C (|): pop a,b: push (a | b)
diff --git a/static/explanations.js b/static/explanations.js
index <HASH>..<HASH> 100644
--- a/static/explanations.js
+++ b/static/explanations.js
@@ -118,9 +118,9 @@ var explanations = {
"74":'pop all elements from stack, flatten any lists and explode any strings, and push them in the same order they were popped (full stack flatten/explode)',
"75":'pop a: push a+1',
"76":'pop a: seed the RNG with a (random.seed(a))',
-"77":'pop a: push the full factorization of a (18 -> [[2,1],[3,2]])',
+"77":'pop a: push the full positive prime factorization of |a| (18 -> [[2,1],[3,2]], -5 -> [[5,1]])',
"78":'pop a,b: push [a,b) (range(a,b))',
-"79":'pop a: push the prime factors of a (18 -> [2,3])',
+"79":'pop a: push the positive prime factors of |a| (18 -> [2,3], -5 -> [5])',
"7A":'pop a: repeat . a times (pop a times and print to stdout)',
"7B":'pop a: rotate stack right a times',
"7C":'pop a,b: push (a | b)',
|
factorization works with abs(a)
|
Mego_Seriously
|
train
|
5ba334fd8c984e99c67eb26d5482c01de04bac17
|
diff --git a/firenado/conf/__init__.py b/firenado/conf/__init__.py
index <HASH>..<HASH> 100644
--- a/firenado/conf/__init__.py
+++ b/firenado/conf/__init__.py
@@ -84,6 +84,7 @@ app['current_user_key'] = "__FIRENADO_CURRENT_USER_KEY__"
app['data'] = {}
app['data']['sources'] = []
app['debug'] = False
+app['id'] = None
app['pythonpath'] = None
app['port'] = 8888
app['login'] = {}
@@ -144,6 +145,9 @@ session['redis'] = {}
session['redis']['data'] = {}
session['redis']['data']['source'] = ''
session['redis']['prefix'] = 'firenado:session'
+# Default session scan intervail is 30 seconds
+# This is the time application will scan for expired sessions
+session['scan_interval'] = 60
session['type'] = ''
if HAS_LIB_CONFIG_FILE:
diff --git a/firenado/config.py b/firenado/config.py
index <HASH>..<HASH> 100644
--- a/firenado/config.py
+++ b/firenado/config.py
@@ -120,10 +120,10 @@ def process_app_config(config, config_data):
if 'app' in config_data:
process_app_config_section(config, config_data['app'])
-
+# TODO: This is being used for the multi app configuration
def process_apps_config_session(config, apps_config):
-
- print(apps_config)
+ pass
+ #print(apps_config)
def process_app_config_section(config, app_config):
@@ -142,6 +142,8 @@ def process_app_config_section(config, app_config):
config.app['data']['sources'] = app_config['data']['sources']
if 'debug' in app_config:
config.app['debug'] = app_config['debug']
+ if 'id' in app_config:
+ config.app['id'] = app_config['id']
if 'login' in app_config:
if 'urls' in app_config['login']:
for url in app_config['login']['urls']:
@@ -292,3 +294,5 @@ def process_session_config_section(config, session_config):
del config.session['id_generators'][generator['name']]['name']
if 'life_time' in session_config:
config.session['life_time'] = session_config['life_time']
+ if 'scan_interval' in session_config:
+ config.session['scan_interval'] = session_config['scan_interval']
diff --git a/firenado/test/resources/session/redis/conf/firenado.yml b/firenado/test/resources/session/redis/conf/firenado.yml
index <HASH>..<HASH> 100644
--- a/firenado/test/resources/session/redis/conf/firenado.yml
+++ b/firenado/test/resources/session/redis/conf/firenado.yml
@@ -31,6 +31,8 @@ components:
session:
type: redis
enabled: true
+ life_time: 1900
+ scan_interval: 40
# Redis session handler configuration
#data:
#source: session
diff --git a/firenado/test/session.py b/firenado/test/session.py
index <HASH>..<HASH> 100644
--- a/firenado/test/session.py
+++ b/firenado/test/session.py
@@ -43,6 +43,12 @@ class FileSessionTestCase(unittest.TestCase):
self.session_handler_class = get_class_from_config(
self.session_handler_config)
+ def test_defaults_session_parameters(self):
+ """ Checks default session parameters on the configuration
+ session section
+ """
+ self.assertEquals(firenado.conf.session['life_time'], 1800)
+ self.assertEquals(firenado.conf.session['scan_interval'], 60)
def test_application_session_handler(self):
""" Checks if the session handler loaded is the same the session
@@ -66,19 +72,31 @@ class FileSessionTestCase(unittest.TestCase):
self.assertEquals(app_session_handler_class, session_handler_class)
-class SessionTestCase(unittest.TestCase):
+class RedisSessionTestCase(unittest.TestCase):
""" Case that tests an Firenado application after being loaded from its
configuration file.
"""
+ def setUp(self):
+ """ Application configuration file will be read and components will be
+ loaded.
+ """
+ chdir_app('redis', 'session')
+
def test_session_type_redis(self):
""" Checks if test component was loaded correctly by the application
__init__ method.
"""
- chdir_app('redis', 'session')
self.assertEquals(firenado.conf.session['enabled'], True)
self.assertEquals(firenado.conf.session['type'], 'redis')
+ def test_custom_session_parameters(self):
+ """ Checks default session parameters on the configuration
+ session section
+ """
+ self.assertEquals(firenado.conf.session['life_time'], 1900)
+ self.assertEquals(firenado.conf.session['scan_interval'], 40)
+
def test_pickle_session_encoder(self):
""" Checks if the pickle session encoder will keep a dict structure
and values intact after encoding and decoding it.
|
Added id and scan_interval config parameter to the session.
The id will be used to compose the session key on redis.
The scan_interval will be used on the periodic call back that
clean expired sessions.
Refs: #<I>
|
candango_firenado
|
train
|
b7761c34862a4233a46d40112ad580aaa1d8c40f
|
diff --git a/lib/seahorse/client/http/response_body_buffer.rb b/lib/seahorse/client/http/response_body_buffer.rb
index <HASH>..<HASH> 100644
--- a/lib/seahorse/client/http/response_body_buffer.rb
+++ b/lib/seahorse/client/http/response_body_buffer.rb
@@ -20,7 +20,7 @@ module Seahorse::Client::Http
# @api private
def initialize
- @mutex = Mutex.new
+ @data_mutex = Mutex.new
@data = []
end
@@ -28,14 +28,14 @@ module Seahorse::Client::Http
# @return [String]
# @raise [BodyClosedError]
def write(chunk)
- @mutex.synchronize do
+ @data_mutex.synchronize do
@data << chunk
end
end
# @return [String]
def read
- @mutex.synchronize do
+ @data_mutex.synchronize do
if @read_called
@data
else
@@ -52,7 +52,7 @@ module Seahorse::Client::Http
# @return [Integer]
def size
- @mutex.synchronize do
+ @data_mutex.synchronize do
if @read_called
@data.bytesize
else
@@ -68,7 +68,7 @@ module Seahorse::Client::Http
# @return [void]
def reset!
- @mutex.synchronize do
+ @data_mutex.synchronize do
@read_called = false
@data = []
end
|
Renamed a mutex for clarity.
|
aws_aws-sdk-ruby
|
train
|
acd4a28316333afb313372f0c55127ae6e95e98d
|
diff --git a/proctor-consumer/src/test/java/com/indeed/proctor/consumer/spring/TestProctorConsumerUtils.java b/proctor-consumer/src/test/java/com/indeed/proctor/consumer/spring/TestProctorConsumerUtils.java
index <HASH>..<HASH> 100644
--- a/proctor-consumer/src/test/java/com/indeed/proctor/consumer/spring/TestProctorConsumerUtils.java
+++ b/proctor-consumer/src/test/java/com/indeed/proctor/consumer/spring/TestProctorConsumerUtils.java
@@ -1,8 +1,10 @@
package com.indeed.proctor.consumer.spring;
import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
import com.indeed.proctor.common.ForceGroupsOptions;
import com.indeed.proctor.common.Proctor;
+import com.indeed.proctor.common.model.Payload;
import com.indeed.proctor.common.model.TestType;
import com.indeed.proctor.consumer.ProctorConsumerUtils;
import org.junit.Test;
@@ -115,6 +117,23 @@ public class TestProctorConsumerUtils {
final Map<String, Integer> forcedGroups = ProctorConsumerUtils.parseForcedGroups(mockRequest, new HashSet<>());
assertThat(forcedGroups).isEmpty();
}
+
+ //force payload with valid tet
+ {
+ final MockHttpServletRequest mockRequest = new MockHttpServletRequest();
+ mockRequest.addHeader(ProctorConsumerUtils.FORCE_GROUPS_HEADER, "testing5;stringValue:\"forcePayload\"");
+ final ForceGroupsOptions forceGroupsOptions = ProctorConsumerUtils.parseForcedGroupsOptions(mockRequest, ImmutableSet.of("testing"));
+ assertThat(forceGroupsOptions.getForcePayloads()).hasSize(1);
+ assertThat(forceGroupsOptions.getForcePayloads()).containsEntry("testing", new Payload("forcePayload"));
+ }
+
+ //force payload with invalid test
+ {
+ final MockHttpServletRequest mockRequest = new MockHttpServletRequest();
+ mockRequest.addHeader(ProctorConsumerUtils.FORCE_GROUPS_HEADER, "wrongTestName5;stringValue:\"forcePayload\"");
+ final ForceGroupsOptions forceGroupsOptions = ProctorConsumerUtils.parseForcedGroupsOptions(mockRequest, ImmutableSet.of("testing"));
+ assertThat(forceGroupsOptions.getForcePayloads()).hasSize(0);
+ }
}
|
PROC-<I> Add more tests for parseForcedGroupsOptions
|
indeedeng_proctor
|
train
|
63470c763ce52f61c41f4f665d6858f41532eb52
|
diff --git a/build/moment-jalaali.js b/build/moment-jalaali.js
index <HASH>..<HASH> 100644
--- a/build/moment-jalaali.js
+++ b/build/moment-jalaali.js
@@ -1056,6 +1056,7 @@ jMoment.jDaysInMonth = function (year, month) {
jMoment.jIsLeapYear = jalaali.isLeapJalaaliYear
jMoment.loadPersian = function () {
+ moment.locale('fa', null)
moment.defineLocale('fa'
, { months: ('ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر').split('_')
, monthsShort: ('ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر').split('_')
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -745,6 +745,7 @@ jMoment.jDaysInMonth = function (year, month) {
jMoment.jIsLeapYear = jalaali.isLeapJalaaliYear
jMoment.loadPersian = function () {
+ moment.locale('fa', null)
moment.defineLocale('fa'
, { months: ('ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر').split('_')
, monthsShort: ('ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر').split('_')
|
Fix #<I> by first removing fa locale
|
fingerpich_jalali-moment
|
train
|
a82d153bdafbcb24fa56f5008d31d437923cc701
|
diff --git a/lib/client.js b/lib/client.js
index <HASH>..<HASH> 100644
--- a/lib/client.js
+++ b/lib/client.js
@@ -110,10 +110,8 @@ _.captureException = function captureError(err, kwargs, cb) {
if(!(err instanceof Error)) {
// This handles when someone does:
// throw "something awesome";
- // We just send the "Error" as a normal message
- // since there is no way to compute a stack trace
- // See: https://github.com/mattrobenolt/raven-node/issues/18
- return this.captureMessage('Error: ' + err, kwargs, cb);
+ // We synthesize an Error here so we can extract a (rough) stack trace.
+ var err = new Error(err);
}
var self = this;
diff --git a/test/raven.client.js b/test/raven.client.js
index <HASH>..<HASH> 100644
--- a/test/raven.client.js
+++ b/test/raven.client.js
@@ -190,14 +190,16 @@ describe('raven.Client', function(){
client.captureError(new Error('wtf?'));
});
- it('should send a plain text "error" as a Message instead', function(done){
- // See: https://github.com/mattrobenolt/raven-node/issues/18
- var old = client.captureMessage;
- client.captureMessage = function(message) {
- // I'm also appending "Error: " to the beginning to help hint
- message.should.equal('Error: wtf?');
+ it('should send a plain text "error" with a synthesized stack', function(done){
+ var old = client.send;
+ client.send = function(kwargs) {
+ client.send = old;
+
+ kwargs['message'].should.equal("Error: wtf?");
+ kwargs.should.have.property('sentry.interfaces.Stacktrace');
+ var stack = kwargs['sentry.interfaces.Stacktrace'];
+ stack.frames[0]['function'].should.equal('captureError');
done();
- client.captureMessage = old;
};
client.captureError('wtf?');
});
|
Capture stack traces via synthesized errors when required.
When captureError() is called without an Error object, synthesize
one so we can grab an approximate stack trace.
|
getsentry_raven-node
|
train
|
523957cace4d184ada11b40ccb58e45f118c33da
|
diff --git a/lib/index.js b/lib/index.js
index <HASH>..<HASH> 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -42,7 +42,6 @@ function Simulcast(options) {
this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
}
- this.layers = [];
// An IN-ORDER list of the simulcast ssrcs
this.ssrcCache = [];
}
|
remove uneeded this.layers
|
jitsi_sdp-simulcast
|
train
|
2f41e49c49f99d8466f5291e9d6abfb4db819862
|
diff --git a/cmd/utils.go b/cmd/utils.go
index <HASH>..<HASH> 100644
--- a/cmd/utils.go
+++ b/cmd/utils.go
@@ -9,16 +9,25 @@ import (
"errors"
"io/ioutil"
"os"
- "path"
+ "path/filepath"
"strings"
"launchpad.net/gnuflag"
)
+func getHome() string {
+ envs := []string{"HOME", "HOMEPATH"}
+ var home string
+ for i := 0; i < len(envs) && home == ""; i++ {
+ home = os.Getenv(envs[i])
+ }
+ return home
+}
+
func JoinWithUserDir(p ...string) string {
- paths := []string{os.ExpandEnv("$HOME")}
+ paths := []string{getHome()}
paths = append(paths, p...)
- return path.Join(paths...)
+ return filepath.Join(paths...)
}
func writeToken(token string) error {
diff --git a/cmd/utils_test.go b/cmd/utils_test.go
index <HASH>..<HASH> 100644
--- a/cmd/utils_test.go
+++ b/cmd/utils_test.go
@@ -6,12 +6,28 @@ package cmd
import (
"io/ioutil"
+ "os"
+ "path"
"github.com/tsuru/tsuru/fs/fstest"
"gopkg.in/check.v1"
"launchpad.net/gnuflag"
)
+func (s *S) TestJoinWithUserDir(c *check.C) {
+ expected := path.Join(os.Getenv("HOME"), "a", "b")
+ path := JoinWithUserDir("a", "b")
+ c.Assert(path, check.Equals, expected)
+}
+
+func (s *S) TestJoinWithUserDirHomePath(c *check.C) {
+ defer os.Setenv("HOME", os.Getenv("HOME"))
+ os.Setenv("HOME", "")
+ os.Setenv("HOMEPATH", "/wat")
+ path := JoinWithUserDir("a", "b")
+ c.Assert(path, check.Equals, "/wat/a/b")
+}
+
func (s *S) TestWriteToken(c *check.C) {
rfs := &fstest.RecordingFs{}
fsystem = rfs
|
cmd: fix JoinWithUserDir on Windows
Using the proper environment variable, and also filepath instead of
path.
Tested on Windows 8.
Fix #<I>.
|
tsuru_tsuru
|
train
|
750d9237ce6fe4c8d9a85d12589a7f5e71860d92
|
diff --git a/molgenis-data-index/src/main/java/org/molgenis/data/index/IndexActionRegisterServiceImpl.java b/molgenis-data-index/src/main/java/org/molgenis/data/index/IndexActionRegisterServiceImpl.java
index <HASH>..<HASH> 100644
--- a/molgenis-data-index/src/main/java/org/molgenis/data/index/IndexActionRegisterServiceImpl.java
+++ b/molgenis-data-index/src/main/java/org/molgenis/data/index/IndexActionRegisterServiceImpl.java
@@ -105,8 +105,8 @@ public class IndexActionRegisterServiceImpl implements TransactionInformation, I
}
else
{
- LOG.error("Transaction id is unknown, register of entityFullName [{}] dataType [{}], entityId [{}]",
- entityType.getId(), entityId);
+ LOG.error("Transaction id is unknown, register of entityFullName [{}], entityId [{}]", entityType.getId(),
+ entityId);
}
}
|
Fix: logging statement with missing argument
|
molgenis_molgenis
|
train
|
58afbc209d76392108089579a1bf00e2c56a9f48
|
diff --git a/ghost/admin/app/models/setting.js b/ghost/admin/app/models/setting.js
index <HASH>..<HASH> 100644
--- a/ghost/admin/app/models/setting.js
+++ b/ghost/admin/app/models/setting.js
@@ -14,8 +14,8 @@ export default Model.extend(ValidationEngine, {
defaultLocale: attr('string'),
forceI18n: attr('boolean'),
activeTimezone: attr('string', {defaultValue: 'Etc/UTC'}),
- ghostHead: attr('string'),
- ghostFoot: attr('string'),
+ codeinjectionHead: attr('string'),
+ codeinjectionFoot: attr('string'),
facebook: attr('facebook-url-user'),
twitter: attr('twitter-url-user'),
labs: attr('string'),
diff --git a/ghost/admin/app/templates/settings/code-injection.hbs b/ghost/admin/app/templates/settings/code-injection.hbs
index <HASH>..<HASH> 100644
--- a/ghost/admin/app/templates/settings/code-injection.hbs
+++ b/ghost/admin/app/templates/settings/code-injection.hbs
@@ -23,13 +23,13 @@
<div class="form-group settings-code">
<label for="ghost-head">Site Header</label>
<p>Code here will be injected into the <code>\{{ghost_head}}</code> tag on every page of the site</p>
- {{gh-cm-editor settings.ghostHead id="ghost-head" class="gh-input settings-code-editor" name="codeInjection[ghost_head]" type="text" update=(action (mut settings.ghostHead))}}
+ {{gh-cm-editor settings.codeinjectionHead id="ghost-head" class="gh-input settings-code-editor" name="codeInjection[ghost_head]" type="text" update=(action (mut settings.codeinjectionHead))}}
</div>
<div class="form-group settings-code">
<label for="ghost-foot">Site Footer</label>
<p>Code here will be injected into the <code>\{{ghost_foot}}</code> tag on every page of the site</p>
- {{gh-cm-editor settings.ghostFoot id="ghost-foot" class="gh-input settings-code-editor" name="codeInjection[ghost_foot]" type="text" update=(action (mut settings.ghostFoot))}}
+ {{gh-cm-editor settings.codeinjectionFoot id="ghost-foot" class="gh-input settings-code-editor" name="codeInjection[ghost_foot]" type="text" update=(action (mut settings.codeinjectionFoot))}}
</div>
</fieldset>
</form>
diff --git a/ghost/admin/mirage/fixtures/settings.js b/ghost/admin/mirage/fixtures/settings.js
index <HASH>..<HASH> 100644
--- a/ghost/admin/mirage/fixtures/settings.js
+++ b/ghost/admin/mirage/fixtures/settings.js
@@ -64,7 +64,7 @@ export default [
id: 10,
created_at: '2015-09-11T09:44:30.809Z',
created_by: 1,
- key: 'ghost_head',
+ key: 'codeinjection_head',
type: 'blog',
updated_at: '2015-09-23T13:32:49.858Z',
updated_by: 1,
@@ -74,7 +74,7 @@ export default [
id: 11,
created_at: '2015-09-11T09:44:30.809Z',
created_by: 1,
- key: 'ghost_foot',
+ key: 'codeinjection_foot',
type: 'blog',
updated_at: '2015-09-23T13:32:49.858Z',
updated_by: 1,
diff --git a/ghost/admin/tests/acceptance/settings/code-injection-test.js b/ghost/admin/tests/acceptance/settings/code-injection-test.js
index <HASH>..<HASH> 100644
--- a/ghost/admin/tests/acceptance/settings/code-injection-test.js
+++ b/ghost/admin/tests/acceptance/settings/code-injection-test.js
@@ -86,7 +86,7 @@ describe('Acceptance: Settings - Code-Injection', function () {
let [lastRequest] = this.server.pretender.handledRequests.slice(-1);
let params = JSON.parse(lastRequest.requestBody);
- expect(params.settings.findBy('key', 'ghost_head').value).to.equal('');
+ expect(params.settings.findBy('key', 'codeinjection_head').value).to.equal('');
expect(find('[data-test-save-button]').textContent.trim(), 'save button text').to.equal('Saved');
// CMD-S shortcut works
@@ -100,7 +100,7 @@ describe('Acceptance: Settings - Code-Injection', function () {
let [newRequest] = this.server.pretender.handledRequests.slice(-1);
params = JSON.parse(newRequest.requestBody);
- expect(params.settings.findBy('key', 'ghost_head').value).to.equal('');
+ expect(params.settings.findBy('key', 'codeinjection_head').value).to.equal('');
expect(find('[data-test-save-button]').textContent.trim(), 'save button text').to.equal('Saved');
});
});
|
Renamed ghostHead/Foot settings to codeinjectionHead/Foot (#<I>)
closes <URL>
|
TryGhost_Ghost
|
train
|
63eb9052185d4d353cdbd2cb0f659afcc01db782
|
diff --git a/saspy/sasbase.py b/saspy/sasbase.py
index <HASH>..<HASH> 100644
--- a/saspy/sasbase.py
+++ b/saspy/sasbase.py
@@ -1275,7 +1275,7 @@ class SASsession():
def file_info(self, filepath, results: str = 'dict', fileref: str = '_spfinfo'):
"""
- This method returns a dictionaty containing the file attributes for the file name provided
+ This method returns a dictionary containing the file attributes for the file name provided
If you would like a Pandas dataframe returned instead of a dictionary, specify results='pandas'
"""
|
fixing dictionaty typo (#<I>)
Thanks! Someontimes I cannnt typer :)
|
sassoftware_saspy
|
train
|
728f0f2d2f50f102223c5decdd60d28143d410a6
|
diff --git a/pyravendb/commands/raven_commands.py b/pyravendb/commands/raven_commands.py
index <HASH>..<HASH> 100644
--- a/pyravendb/commands/raven_commands.py
+++ b/pyravendb/commands/raven_commands.py
@@ -540,7 +540,11 @@ class QueryStreamCommand(RavenCommand):
self.data = self._index_query.to_json()
def set_response(self, response):
- return response
+ if response is None:
+ raise exceptions.ErrorResponseException("Invalid response")
+
+ if response.status_code == 200:
+ return response
# ------------------------SubscriptionCommands----------------------
diff --git a/pyravendb/store/document_session.py b/pyravendb/store/document_session.py
index <HASH>..<HASH> 100644
--- a/pyravendb/store/document_session.py
+++ b/pyravendb/store/document_session.py
@@ -396,16 +396,16 @@ class Advanced(object):
"streaming query with wait_for_non_stale_results is not supported.")
self.session.increment_requests_count()
command = QueryStreamCommand(index_query)
- response = self.session.requests_executor.execute(command)
- basic_parse = IncrementalJsonParser.basic_parse(response)
- parser = ijson.backend.common.parse(basic_parse)
-
- results = ijson.backend.common.items(parser, "Results")
- for result in next(results, None):
- document, metadata, _ = Utils.convert_to_entity(result, query.object_type, self.session.conventions,
- query.nested_object_types)
- yield {"document": document, "metadata": metadata, "id": metadata.get("@id", None),
- "change-vector": metadata.get("@change-vector", None)}
+ with self.session.requests_executor.execute(command) as response:
+ basic_parse = IncrementalJsonParser.basic_parse(response)
+ parser = ijson.backend.common.parse(basic_parse)
+
+ results = ijson.backend.common.items(parser, "Results")
+ for result in next(results, None):
+ document, metadata, _ = Utils.convert_to_entity(result, query.object_type, self.session.conventions,
+ query.nested_object_types)
+ yield {"document": document, "metadata": metadata, "id": metadata.get("@id", None),
+ "change-vector": metadata.get("@change-vector", None)}
def number_of_requests_in_session(self):
return self.session.number_of_requests_in_session
diff --git a/pyravendb/tryouts/program.py b/pyravendb/tryouts/program.py
index <HASH>..<HASH> 100644
--- a/pyravendb/tryouts/program.py
+++ b/pyravendb/tryouts/program.py
@@ -20,7 +20,7 @@ class Dog:
if __name__ == "__main__":
- with DocumentStore(urls=["http://localhost:8080"], database="Northwind") as store:
+ with DocumentStore(urls=["http://localhost.fiddler:8080"], database="Northwind") as store:
store.initialize()
# with store.open_session() as session:
# for i in range(0, 10000):
@@ -29,8 +29,9 @@ if __name__ == "__main__":
with store.open_session() as session:
query = session.query(object_type=User, index_name="UserByName")
+ count = 0
results = session.advanced.stream(query)
- result_counter = 0
for result in results:
- result_counter += 1
- print(result_counter)
+ # do something with this
+ user = result.get("document", None)
+ count += 1
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -3,7 +3,7 @@ from setuptools import setup, find_packages
setup(
name='pyravendb',
packages=find_packages(),
- version='4.0.3.0',
+ version='4.0.3.1',
description='This is the official python client for RavenDB v4.0 document database',
author='Idan Haim Shalom',
author_email='haimdude@gmail.com',
|
<I> update the way we handle responses for the QueryStreamCommand
- using the stream will automatically close the response after consume all the data
|
ravendb_ravendb-python-client
|
train
|
2cd91b64d053ef650f53144b367ee4e89729541a
|
diff --git a/extensions-contrib/azure-extensions/src/main/java/io/druid/storage/azure/AzureDataSegmentPuller.java b/extensions-contrib/azure-extensions/src/main/java/io/druid/storage/azure/AzureDataSegmentPuller.java
index <HASH>..<HASH> 100644
--- a/extensions-contrib/azure-extensions/src/main/java/io/druid/storage/azure/AzureDataSegmentPuller.java
+++ b/extensions-contrib/azure-extensions/src/main/java/io/druid/storage/azure/AzureDataSegmentPuller.java
@@ -63,7 +63,7 @@ public class AzureDataSegmentPuller implements DataSegmentPuller
byteSource,
outDir,
AzureUtils.AZURE_RETRY,
- true
+ false
);
log.info("Loaded %d bytes from [%s] to [%s]", result.size(), blobPath, outDir.getAbsolutePath());
diff --git a/extensions-contrib/cloudfiles-extensions/src/main/java/io/druid/storage/cloudfiles/CloudFilesDataSegmentPuller.java b/extensions-contrib/cloudfiles-extensions/src/main/java/io/druid/storage/cloudfiles/CloudFilesDataSegmentPuller.java
index <HASH>..<HASH> 100644
--- a/extensions-contrib/cloudfiles-extensions/src/main/java/io/druid/storage/cloudfiles/CloudFilesDataSegmentPuller.java
+++ b/extensions-contrib/cloudfiles-extensions/src/main/java/io/druid/storage/cloudfiles/CloudFilesDataSegmentPuller.java
@@ -69,7 +69,7 @@ public class CloudFilesDataSegmentPuller implements DataSegmentPuller
try {
final FileUtils.FileCopyResult result = CompressionUtils.unzip(
byteSource, outDir,
- CloudFilesUtils.CLOUDFILESRETRY, true
+ CloudFilesUtils.CLOUDFILESRETRY, false
);
log.info("Loaded %d bytes from [%s] to [%s]", result.size(), path, outDir.getAbsolutePath());
return result;
diff --git a/extensions-contrib/google-extensions/src/main/java/io/druid/storage/google/GoogleDataSegmentPuller.java b/extensions-contrib/google-extensions/src/main/java/io/druid/storage/google/GoogleDataSegmentPuller.java
index <HASH>..<HASH> 100644
--- a/extensions-contrib/google-extensions/src/main/java/io/druid/storage/google/GoogleDataSegmentPuller.java
+++ b/extensions-contrib/google-extensions/src/main/java/io/druid/storage/google/GoogleDataSegmentPuller.java
@@ -72,7 +72,7 @@ public class GoogleDataSegmentPuller implements DataSegmentPuller, URIDataPuller
byteSource,
outDir,
GoogleUtils.GOOGLE_RETRY,
- true
+ false
);
LOG.info("Loaded %d bytes from [%s] to [%s]", result.size(), path, outDir.getAbsolutePath());
return result;
diff --git a/extensions-core/s3-extensions/src/main/java/io/druid/storage/s3/S3DataSegmentPuller.java b/extensions-core/s3-extensions/src/main/java/io/druid/storage/s3/S3DataSegmentPuller.java
index <HASH>..<HASH> 100644
--- a/extensions-core/s3-extensions/src/main/java/io/druid/storage/s3/S3DataSegmentPuller.java
+++ b/extensions-core/s3-extensions/src/main/java/io/druid/storage/s3/S3DataSegmentPuller.java
@@ -202,7 +202,7 @@ public class S3DataSegmentPuller implements DataSegmentPuller, URIDataPuller
byteSource,
outDir,
S3Utils.S3RETRY,
- true
+ false
);
log.info("Loaded %d bytes from [%s] to [%s]", result.size(), s3Coords.toString(), outDir.getAbsolutePath());
return result;
|
Uncompress streams without having to download to tmp first (#<I>)
* Uncompress streams without having to download to tmp first
* Remove unused file
|
apache_incubator-druid
|
train
|
0b5133b2f3131e057d266e0fd3eb75f5e1ae9371
|
diff --git a/src/Sanitizer.php b/src/Sanitizer.php
index <HASH>..<HASH> 100644
--- a/src/Sanitizer.php
+++ b/src/Sanitizer.php
@@ -294,11 +294,11 @@ class Sanitizer
continue;
}
- $this->cleanAttributesOnWhitelist($currentElement);
+ $this->cleanHrefs($currentElement);
$this->cleanXlinkHrefs($currentElement);
- $this->cleanHrefs($currentElement);
+ $this->cleanAttributesOnWhitelist($currentElement);
if ($this->isTaggedInvalid($currentElement)) {
$currentElement->parentNode->removeChild($currentElement);
@@ -345,6 +345,22 @@ class Sanitizer
);
}
+ /**
+ * This is used for when a namespace isn't imported properly.
+ * Such as xlink:href when the xlink namespace isn't imported.
+ * We have to do this as the link is still ran in this case.
+ */
+ if (false !== strpos($attrName, 'href')) {
+ $href = $element->getAttribute($attrName);
+ if (false === $this->isHrefSafeValue($href)) {
+ $element->removeAttribute($attrName);
+ $this->xmlIssues[] = array(
+ 'message' => 'Suspicious attribute \'href\'',
+ 'line' => $element->getLineNo(),
+ );
+ }
+ }
+
// Do we want to strip remote references?
if($this->removeRemoteReferences) {
// Remove attribute if it has a remote reference
|
If a href is used without a properly included namespace import, we now catch it in this section.
cleanAttributesOnWhitelist and cleanHrefs switched around so that we’re not double running over links with an issue
|
darylldoyle_svg-sanitizer
|
train
|
c40803a63f8eedbdfb6cb76f06303e54e0421b9d
|
diff --git a/command/job_status.go b/command/job_status.go
index <HASH>..<HASH> 100644
--- a/command/job_status.go
+++ b/command/job_status.go
@@ -566,7 +566,7 @@ func (c *JobStatusCommand) outputReschedulingEvals(client *api.Client, allocList
var delayedEvalInfos []string
taskGroups := make([]string, 0, len(followUpEvalIds))
- for taskGroup, _ := range followUpEvalIds {
+ for taskGroup := range followUpEvalIds {
taskGroups = append(taskGroups, taskGroup)
}
sort.Strings(taskGroups)
diff --git a/command/job_status_test.go b/command/job_status_test.go
index <HASH>..<HASH> 100644
--- a/command/job_status_test.go
+++ b/command/job_status_test.go
@@ -1,15 +1,20 @@
package command
import (
+ "fmt"
"strings"
"testing"
+ "time"
"github.com/hashicorp/nomad/api"
"github.com/hashicorp/nomad/command/agent"
"github.com/hashicorp/nomad/nomad/mock"
+ "github.com/hashicorp/nomad/nomad/structs"
+ "github.com/hashicorp/nomad/testutil"
"github.com/mitchellh/cli"
"github.com/posener/complete"
"github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
)
func TestJobStatusCommand_Implements(t *testing.T) {
@@ -276,6 +281,59 @@ func TestJobStatusCommand_WithAccessPolicy(t *testing.T) {
}
}
+func TestJobStatusCommand_RescheduleEvals(t *testing.T) {
+ t.Parallel()
+ srv, client, url := testServer(t, true, nil)
+ defer srv.Shutdown()
+
+ // Wait for a node to be ready
+ testutil.WaitForResult(func() (bool, error) {
+ nodes, _, err := client.Nodes().List(nil)
+ if err != nil {
+ return false, err
+ }
+ for _, node := range nodes {
+ if node.Status == structs.NodeStatusReady {
+ return true, nil
+ }
+ }
+ return false, fmt.Errorf("no ready nodes")
+ }, func(err error) {
+ t.Fatalf("err: %v", err)
+ })
+
+ ui := new(cli.MockUi)
+ cmd := &JobStatusCommand{Meta: Meta{Ui: ui, flagAddress: url}}
+
+ require := require.New(t)
+ state := srv.Agent.Server().State()
+
+ // Create state store objects for job, alloc and followup eval with a future WaitUntil value
+ j := mock.Job()
+ require.Nil(state.UpsertJob(900, j))
+
+ e := mock.Eval()
+ e.WaitUntil = time.Now().Add(1 * time.Hour)
+ require.Nil(state.UpsertEvals(902, []*structs.Evaluation{e}))
+ a := mock.Alloc()
+ a.Job = j
+ a.JobID = j.ID
+ a.TaskGroup = j.TaskGroups[0].Name
+ a.FollowupEvalID = e.ID
+ a.Metrics = &structs.AllocMetric{}
+ a.DesiredStatus = structs.AllocDesiredStatusRun
+ a.ClientStatus = structs.AllocClientStatusRunning
+ require.Nil(state.UpsertAllocs(1000, []*structs.Allocation{a}))
+
+ // Query jobs with prefix match
+ if code := cmd.Run([]string{"-address=" + url, j.ID}); code != 0 {
+ t.Fatalf("expected exit 0, got: %d", code)
+ }
+ out := ui.OutputWriter.String()
+ require.Contains(out, "Upcoming Evaluations")
+ require.Contains(out, e.ID)
+}
+
func waitForSuccess(ui cli.Ui, client *api.Client, length int, t *testing.T, evalId string) int {
mon := newMonitor(ui, client, length)
monErr := mon.monitor(evalId, false)
|
Unit test and linting fix
|
hashicorp_nomad
|
train
|
fdad9b7666978c7948acfddbaf89c8d5b6ac08d5
|
diff --git a/firenado/management/management.py b/firenado/management/management.py
index <HASH>..<HASH> 100644
--- a/firenado/management/management.py
+++ b/firenado/management/management.py
@@ -75,7 +75,7 @@ def get_command_header(parser, usage_message="", usage=False):
firenado.conf.ROOT, 'management', 'templates', 'help'))
return loader.load("header.txt").generate(
parser=parser, usage_message=usage_message, usage=usage,
- firenado_version=".".join(map(str,firenado.__version__))).decode(
+ firenado_version=".".join(map(str, firenado.__version__))).decode(
sys.stdout.encoding)
@@ -161,7 +161,7 @@ class ManagementCommand(object):
return self.help
def match(self, command):
- return command in self.name
+ return command in self.commands
def run(self, args):
has_sub_commands = False
|
Fixed command match when name is provided with parenthesis.
Maching agains commands and not name.
Fixes: #<I>
|
candango_firenado
|
train
|
21dfc19b6a1212265125331ec2cda67421f3612d
|
diff --git a/ServiceProvider.php b/ServiceProvider.php
index <HASH>..<HASH> 100755
--- a/ServiceProvider.php
+++ b/ServiceProvider.php
@@ -149,7 +149,7 @@ abstract class ServiceProvider
/**
* Add a publish group / tag to the service provider.
*
- * @param string $path
+ * @param string $group
* @param array $paths
* @return void
*/
diff --git a/Testing/Fakes/QueueFake.php b/Testing/Fakes/QueueFake.php
index <HASH>..<HASH> 100644
--- a/Testing/Fakes/QueueFake.php
+++ b/Testing/Fakes/QueueFake.php
@@ -99,7 +99,7 @@ class QueueFake implements Queue
/**
* Resolve a queue connection instance.
*
- * @param string $name
+ * @param mixed $value
* @return \Illuminate\Contracts\Queue\Queue
*/
public function connection($value = null)
|
[<I>] Multiple docblocks and fixes (#<I>)
* Multiple docblocks and fixes
* fix
|
illuminate_support
|
train
|
1dc522d42eec2f78825cb3ec79dd7093ab357ef6
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -68,7 +68,7 @@ else:
setup(
name='nodeconductor',
- version='0.92.0',
+ version='0.93.0',
author='OpenNode Team',
author_email='info@opennodecloud.com',
url='https://github.com/opennode/nodeconductor',
|
Preparing new release: <I>
|
opennode_waldur-core
|
train
|
2a27a79e5f88fbd0c294bf288ad7a128205d45cf
|
diff --git a/lib/endpoint/tags/table.js b/lib/endpoint/tags/table.js
index <HASH>..<HASH> 100644
--- a/lib/endpoint/tags/table.js
+++ b/lib/endpoint/tags/table.js
@@ -51,7 +51,7 @@ function toParams ($table) {
}
function rowToParameter (i, el) {
- const [name, type, { description, defaultValue, enumValues, isRequired, allowNull }] = cheerio(el)
+ const [name, type, { description, defaultValue, enumValues, regex, isRequired, allowNull }] = cheerio(el)
.children()
.map((i, el) => {
if (i < 2) { // first two columns are simply name and type
@@ -102,12 +102,21 @@ function rowToParameter (i, el) {
enumValues = _.uniq((results || []).map(s => s.replace(/`/g, '')))
}
+ // Sometimes enum values contain placeholders in which we turn it into a
+ // regex pattern, see https://github.com/octokit/routes/issues/121
+ let regex
+ if (enumValues.find(value => /<.*>/.test(value))) {
+ regex = `^(${enumValues.map(v => v.replace(/<.*>/, '\\d+')).join('|')})$`
+ enumValues = []
+ }
+
const allowNull = ALLOW_NULL_REGEXP.test(description)
return {
description,
defaultValue,
enumValues,
+ regex,
isRequired,
allowNull
}
@@ -204,6 +213,11 @@ function rowToParameter (i, el) {
params.enum = enumValues
}
+ if (regex) {
+ params.type = 'string'
+ params.regex = regex
+ }
+
// 'true' / 'false' => true / false
if (params.type === 'boolean' && ['true', 'false'].includes(defaultValue)) {
params.default = defaultValue === 'true'
|
fix: turn enum values with placeholders into regex pattern
|
octokit_routes
|
train
|
7fc6f1c23f254156a60ce343df4ca6b5b73f3156
|
diff --git a/src/main/java/water/fvec/FrameCreator.java b/src/main/java/water/fvec/FrameCreator.java
index <HASH>..<HASH> 100644
--- a/src/main/java/water/fvec/FrameCreator.java
+++ b/src/main/java/water/fvec/FrameCreator.java
@@ -58,7 +58,7 @@ public class FrameCreator extends H2O.H2OCountedCompleter {
for (int i = 0; i < _createFrame.factors; ++i) {
_domain[c][i] = UUID.randomUUID().toString().subSequence(0,5).toString();
// make sure that there's no pure number-labels
- while (_domain[c][i].matches("^\\d+$")) {
+ while ( _domain[c][i].matches("^\\d+$") || _domain[c][i].matches("^\\d+e\\d+$") ) {
_domain[c][i] = UUID.randomUUID().toString().subSequence(0,5).toString();
}
}
|
Also exclude factors that contain lower-case UUIDs that look like they
in scientific notation with exponent: ^\d+e\d+$
|
h2oai_h2o-2
|
train
|
6ed7a20a8ec2a49dedfbcee29b8b68c550530619
|
diff --git a/database/Seeds/UsersTableSeeder.php b/database/Seeds/UsersTableSeeder.php
index <HASH>..<HASH> 100644
--- a/database/Seeds/UsersTableSeeder.php
+++ b/database/Seeds/UsersTableSeeder.php
@@ -2,7 +2,6 @@
use Carbon\Carbon;
use Illuminate\Database\Seeder;
-use jorenvanhocht\Blogify\Facades\Blogify;
use jorenvanhocht\Blogify\Models\Role;
use App\User;
use \Illuminate\Support\Facades\Hash;
@@ -23,9 +22,10 @@ class UsersTableSeeder extends Seeder {
public function run()
{
- User::create([
+ $user = app()->make(config(('auth.model')));
+ $user->create([
'hash' => blogify()->makeHash('users', 'hash', true),
- 'lastname' => $this->admin['name'],
+ 'lastname' => $this->admin['name'],
'firstname' => $this->admin['firstname'],
'username' => $this->admin['username'],
'email' => $this->admin['email'],
|
Fixed issue #8 Edit New issue Seed Fails If App Namespace Is Already Set
|
Blogify_Blogify
|
train
|
7491790820c1225501283092e555a18cb4400ebd
|
diff --git a/lib/passenger/application.rb b/lib/passenger/application.rb
index <HASH>..<HASH> 100644
--- a/lib/passenger/application.rb
+++ b/lib/passenger/application.rb
@@ -42,10 +42,21 @@ class Application
environment_rb = File.read("#{app_root}/config/environment.rb")
environment_rb =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*["']([!~<>=]*\s*[\d.]+)["']/
gem_version_spec = $1
+
found_version = Gem.cache.search('rails', gem_version_spec).map do |x|
x.version.version
end.sort.last
if found_version.nil?
+ # If this error was reported before, then the cache might be out of
+ # date because the Rails version may have been installed now.
+ # So we reload the cache and try again.
+ Gem.cache.refresh!
+ found_version = Gem.cache.search('rails', gem_version_spec).map do |x|
+ x.version.version
+ end.sort.last
+ end
+
+ if found_version.nil?
raise VersionNotFound.new("There is no Ruby on Rails version " <<
"installed that matches version \"#{gem_version_spec}\"",
gem_version_spec)
|
Clear RubyGems cache at appropriate times, so that newly installed Rails frameworks are correctly detected.
|
phusion_passenger
|
train
|
18363f3c6621a883d85e426fb3141b92a16b2d65
|
diff --git a/lib/core/utils/check-helper.js b/lib/core/utils/check-helper.js
index <HASH>..<HASH> 100644
--- a/lib/core/utils/check-helper.js
+++ b/lib/core/utils/check-helper.js
@@ -21,10 +21,10 @@ utils.checkHelper = function checkHelper(checkResult, callback) {
checkResult.data = data;
},
relatedNodes: function (nodes) {
- nodes = Array.isArray(nodes) ? nodes : [nodes];
+ nodes = nodes instanceof Node ? [nodes] : utils.toArray(nodes);
checkResult.relatedNodes = nodes.map(function (element) {
return new DqElement(element);
});
}
};
-};
\ No newline at end of file
+};
diff --git a/test/core/utils/check-helper.js b/test/core/utils/check-helper.js
index <HASH>..<HASH> 100644
--- a/test/core/utils/check-helper.js
+++ b/test/core/utils/check-helper.js
@@ -1,3 +1,4 @@
+/*global DqElement */
describe('utils.checkHelper', function () {
'use strict';
@@ -48,42 +49,59 @@ describe('utils.checkHelper', function () {
});
});
describe('relatedNodes', function () {
- it('should set relatedNodes property on target when called and pass each node into DqElement', function () {
- var orig = window.DqElement;
- var success = false;
- window.DqElement = function (n) {
- assert.equal(n, expected[0]);
- success = true;
- return n;
- };
- var target = {},
- expected = [{monkeys: 'bananas' }],
- helper = utils.checkHelper(target, noop);
-
- assert.notProperty(target, 'relatedNodes');
- helper.relatedNodes(expected);
- assert.deepEqual(target.relatedNodes, expected);
- assert.isTrue(success);
-
- window.DqElement = orig;
+ var fixture = document.getElementById('fixture');
+ afterEach(function () {
+ fixture.innerHTML = '';
});
- it('should cast the object to an array', function () {
- var orig = window.DqElement;
- window.DqElement = function (n) {
- return n;
- };
- var target = {},
- expected = [{monkeys: 'bananas' }],
- helper = utils.checkHelper(target, noop);
-
- helper.relatedNodes(expected[0]);
- assert.isArray(target.relatedNodes);
- assert.deepEqual(target.relatedNodes, expected);
-
- window.DqElement = orig;
+ it('should accept NodeList', function () {
+ fixture.innerHTML = '<div id="t1"></div><div id="t2"></div>';
+ var target = {},
+ helper = utils.checkHelper(target, noop);
+ helper.relatedNodes(fixture.children);
+ assert.lengthOf(target.relatedNodes, 2);
+ assert.instanceOf(target.relatedNodes[0], DqElement);
+ assert.instanceOf(target.relatedNodes[1], DqElement);
+ assert.equal(target.relatedNodes[0].element, fixture.children[0]);
+ assert.equal(target.relatedNodes[1].element, fixture.children[1]);
+ });
+ it('should accept a single Node', function () {
+ fixture.innerHTML = '<div id="t1"></div><div id="t2"></div>';
+ var target = {},
+ helper = utils.checkHelper(target, noop);
+ helper.relatedNodes(fixture.firstChild);
+ assert.lengthOf(target.relatedNodes, 1);
+ assert.instanceOf(target.relatedNodes[0], DqElement);
+ assert.equal(target.relatedNodes[0].element, fixture.firstChild);
+ });
+ it('should accept an Array', function () {
+ fixture.innerHTML = '<div id="t1"></div><div id="t2"></div>';
+ var target = {},
+ helper = utils.checkHelper(target, noop);
+ helper.relatedNodes(Array.prototype.slice.call(fixture.children));
+ assert.lengthOf(target.relatedNodes, 2);
+ assert.instanceOf(target.relatedNodes[0], DqElement);
+ assert.instanceOf(target.relatedNodes[1], DqElement);
+ assert.equal(target.relatedNodes[0].element, fixture.children[0]);
+ assert.equal(target.relatedNodes[1].element, fixture.children[1]);
+ });
+ it('should accept an array-like Object', function () {
+ fixture.innerHTML = '<div id="t1"></div><div id="t2"></div>';
+ var target = {},
+ helper = utils.checkHelper(target, noop);
+ var nodes = {
+ 0: fixture.children[0],
+ 1: fixture.children[1],
+ length: 2
+ };
+ helper.relatedNodes(nodes);
+ assert.lengthOf(target.relatedNodes, 2);
+ assert.instanceOf(target.relatedNodes[0], DqElement);
+ assert.instanceOf(target.relatedNodes[1], DqElement);
+ assert.equal(target.relatedNodes[0].element, fixture.children[0]);
+ assert.equal(target.relatedNodes[1].element, fixture.children[1]);
});
});
});
-});
\ No newline at end of file
+});
|
More defensive checks in relatedNodes
Resolves #8
|
dequelabs_axe-core
|
train
|
fc90f6736f288524b9fc82a97070570ec7ee565c
|
diff --git a/web/concrete/src/Package/Package.php b/web/concrete/src/Package/Package.php
index <HASH>..<HASH> 100644
--- a/web/concrete/src/Package/Package.php
+++ b/web/concrete/src/Package/Package.php
@@ -211,7 +211,6 @@ class Package extends Object
public function installDatabase()
{
$dbm = $this->getDatabaseStructureManager();
- $this->destroyProxyClasses();
if ($dbm->hasEntities()) {
$dbm->generateProxyClasses();
@@ -225,6 +224,39 @@ class Package extends Object
}
}
+ public function upgradeDatabase()
+ {
+ $dbm = $this->getDatabaseStructureManager();
+ $this->destroyProxyClasses();
+ if ($dbm->hasEntities()) {
+ $dbm->generateProxyClasses();
+ $dbm->dropObsoleteDatabaseTables(camelcase($this->getPackageHandle()));
+ $dbm->installDatabase();
+ }
+
+ if (file_exists($this->getPackagePath() . '/' . FILENAME_PACKAGE_DB)) {
+ // Legacy db.xml
+ // currently this is just done from xml
+ $db = Database::get();
+ $db->beginTransaction();
+
+ $parser = Schema::getSchemaParser(simplexml_load_file($this->getPackagePath() . '/' . FILENAME_PACKAGE_DB));
+ $parser->setIgnoreExistingTables(false);
+ $toSchema = $parser->parse($db);
+
+ $fromSchema = $db->getSchemaManager()->createSchema();
+ $comparator = new \Doctrine\DBAL\Schema\Comparator();
+ $schemaDiff = $comparator->compare($fromSchema, $toSchema);
+ $saveQueries = $schemaDiff->toSaveSql($db->getDatabasePlatform());
+
+ foreach($saveQueries as $query) {
+ $db->query($query);
+ }
+
+ $db->commit();
+ }
+ }
+
public static function installDB($xmlFile)
{
if (!file_exists($xmlFile)) {
@@ -906,7 +938,7 @@ class Package extends Object
public function upgrade()
{
- $this->installDatabase();
+ $this->refreshDatabase();
// now we refresh all blocks
$items = $this->getPackageItems();
|
fixing upgrade vs install
Former-commit-id: <I>c4bc<I>b4c7d9be<I>e4ec1bf0dfac1dfb
|
concrete5_concrete5
|
train
|
d716233e37c16c6896c19a1eeafbdf6abf401bac
|
diff --git a/hpcbench/benchmark/mdtest.py b/hpcbench/benchmark/mdtest.py
index <HASH>..<HASH> 100644
--- a/hpcbench/benchmark/mdtest.py
+++ b/hpcbench/benchmark/mdtest.py
@@ -97,7 +97,7 @@ class MDTest(Benchmark):
DEFAULT_ATTRIBUTES = dict(
executable='mdtest',
- options=['-N', '100000'],
+ options=['-N', '100000', '-i', 3],
)
def __init__(self):
|
mdtest: execute 3 iterations
|
BlueBrain_hpcbench
|
train
|
6d2b34af75ac28554cd6df933a7f502205ab7b35
|
diff --git a/doc/source/whatsnew/v0.19.2.txt b/doc/source/whatsnew/v0.19.2.txt
index <HASH>..<HASH> 100644
--- a/doc/source/whatsnew/v0.19.2.txt
+++ b/doc/source/whatsnew/v0.19.2.txt
@@ -39,7 +39,8 @@ Bug Fixes
- Bug in ``pd.cut`` with negative values and a single bin (:issue:`14652`)
- Bug in ``pd.to_numeric`` where a 0 was not unsigned on a ``downcast='unsigned'`` argument (:issue:`14401`)
-
+- Bug in plotting regular and irregular timeseries using shared axes
+ (``sharex=True`` or ``ax.twinx()``) (:issue:`13341`, :issue:`14322`).
diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py
index <HASH>..<HASH> 100644
--- a/pandas/tests/plotting/test_datetimelike.py
+++ b/pandas/tests/plotting/test_datetimelike.py
@@ -778,6 +778,41 @@ class TestTSPlot(TestPlotBase):
irreg.plot()
ps.plot()
+ def test_mixed_freq_shared_ax(self):
+
+ # GH13341, using sharex=True
+ idx1 = date_range('2015-01-01', periods=3, freq='M')
+ idx2 = idx1[:1].union(idx1[2:])
+ s1 = Series(range(len(idx1)), idx1)
+ s2 = Series(range(len(idx2)), idx2)
+
+ fig, (ax1, ax2) = self.plt.subplots(nrows=2, sharex=True)
+ s1.plot(ax=ax1)
+ s2.plot(ax=ax2)
+
+ self.assertEqual(ax1.freq, 'M')
+ self.assertEqual(ax2.freq, 'M')
+ self.assertEqual(ax1.lines[0].get_xydata()[0, 0],
+ ax2.lines[0].get_xydata()[0, 0])
+
+ # using twinx
+ fig, ax1 = self.plt.subplots()
+ ax2 = ax1.twinx()
+ s1.plot(ax=ax1)
+ s2.plot(ax=ax2)
+
+ self.assertEqual(ax1.lines[0].get_xydata()[0, 0],
+ ax2.lines[0].get_xydata()[0, 0])
+
+ # TODO (GH14330, GH14322)
+ # plotting the irregular first does not yet work
+ # fig, ax1 = plt.subplots()
+ # ax2 = ax1.twinx()
+ # s2.plot(ax=ax1)
+ # s1.plot(ax=ax2)
+ # self.assertEqual(ax1.lines[0].get_xydata()[0, 0],
+ # ax2.lines[0].get_xydata()[0, 0])
+
@slow
def test_to_weekly_resampling(self):
idxh = date_range('1/1/1999', periods=52, freq='W')
diff --git a/pandas/tseries/plotting.py b/pandas/tseries/plotting.py
index <HASH>..<HASH> 100644
--- a/pandas/tseries/plotting.py
+++ b/pandas/tseries/plotting.py
@@ -162,18 +162,37 @@ def _decorate_axes(ax, freq, kwargs):
ax.date_axis_info = None
-def _get_freq(ax, series):
- # get frequency from data
- freq = getattr(series.index, 'freq', None)
- if freq is None:
- freq = getattr(series.index, 'inferred_freq', None)
-
+def _get_ax_freq(ax):
+ """
+ Get the freq attribute of the ax object if set.
+ Also checks shared axes (eg when using secondary yaxis, sharex=True
+ or twinx)
+ """
ax_freq = getattr(ax, 'freq', None)
if ax_freq is None:
+ # check for left/right ax in case of secondary yaxis
if hasattr(ax, 'left_ax'):
ax_freq = getattr(ax.left_ax, 'freq', None)
elif hasattr(ax, 'right_ax'):
ax_freq = getattr(ax.right_ax, 'freq', None)
+ if ax_freq is None:
+ # check if a shared ax (sharex/twinx) has already freq set
+ shared_axes = ax.get_shared_x_axes().get_siblings(ax)
+ if len(shared_axes) > 1:
+ for shared_ax in shared_axes:
+ ax_freq = getattr(shared_ax, 'freq', None)
+ if ax_freq is not None:
+ break
+ return ax_freq
+
+
+def _get_freq(ax, series):
+ # get frequency from data
+ freq = getattr(series.index, 'freq', None)
+ if freq is None:
+ freq = getattr(series.index, 'inferred_freq', None)
+
+ ax_freq = _get_ax_freq(ax)
# use axes freq if no data freq
if freq is None:
@@ -191,7 +210,7 @@ def _get_freq(ax, series):
def _use_dynamic_x(ax, data):
freq = _get_index_freq(data)
- ax_freq = getattr(ax, 'freq', None)
+ ax_freq = _get_ax_freq(ax)
if freq is None: # convert irregular if axes has freq info
freq = ax_freq
@@ -244,7 +263,7 @@ def _maybe_convert_index(ax, data):
freq = freq.rule_code
if freq is None:
- freq = getattr(ax, 'freq', None)
+ freq = _get_ax_freq(ax)
if freq is None:
raise ValueError('Could not get frequency alias for plotting')
|
BUG: mixed freq timeseries plotting with shared axes (GH<I>) (#<I>)
|
pandas-dev_pandas
|
train
|
7d5d73ef26a587002200b1a4146398fc3809155e
|
diff --git a/src/Tags.php b/src/Tags.php
index <HASH>..<HASH> 100644
--- a/src/Tags.php
+++ b/src/Tags.php
@@ -54,7 +54,7 @@ class Tags
{
return collect(
[static::extractListener($job), static::extractEvent($job),
- ])->map(function ($job) {
+ ])->map(function ($job) {
return static::for($job);
})->collapse()->unique()->toArray();
}
|
Apply fixes from StyleCI (#<I>)
|
laravel_horizon
|
train
|
a6b2dee6fc51761481942e4b96ae748d4b020500
|
diff --git a/PBB_Core.py b/PBB_Core.py
index <HASH>..<HASH> 100755
--- a/PBB_Core.py
+++ b/PBB_Core.py
@@ -585,8 +585,12 @@ class WDItemEngine(object):
names = [x.lower() for x in names]
+ count = 0
+ if len(claim_values) - data_match_count > 0:
+ count = round((len(claim_values) - data_match_count) / 2)
+
# make decision if ManualInterventionReqException should be raised.
- if data_match_count < (count_existing_ids - data_match_count) and self.item_name.lower() not in names:
+ if data_match_count < count and self.item_name.lower() not in names:
raise ManualInterventionReqException('Retrieved name does not match provided item name or core IDs. '
'Matching count {}, nonmatching count {}'
.format(data_match_count, count_existing_ids - data_match_count), '', '')
|
improved estimation in __integrity_check()
|
SuLab_WikidataIntegrator
|
train
|
5b361b75c123cfd1e000e3e49ff31d0c8ce4560b
|
diff --git a/components/amorphic/lib/session/restoreSession.js b/components/amorphic/lib/session/restoreSession.js
index <HASH>..<HASH> 100644
--- a/components/amorphic/lib/session/restoreSession.js
+++ b/components/amorphic/lib/session/restoreSession.js
@@ -30,7 +30,7 @@ function restoreSession(path, session, controller, sessions) {
if (unserialized.serializationTimeStamp !== sessionData.serializationTimeStamp) {
ourObjectTemplate.logger.error({
component: 'amorphic',
- module: 'getController',
+ module: 'restoreSession',
activity: 'restore',
savedAs: sessionData.serializationTimeStamp,
foundToBe: unserialized.serializationTimeStamp
|
Merge pull request #<I> from nikmash/update-restore-session-logging
Updated module part of logging to log out the correct module
|
haven-life_amorphic
|
train
|
6ef7f02d79f516979c42fa27db9d50a6e7d9c2aa
|
diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/observer/upload/DefaultMultipartConfig.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/observer/upload/DefaultMultipartConfig.java
index <HASH>..<HASH> 100644
--- a/vraptor-core/src/main/java/br/com/caelum/vraptor/observer/upload/DefaultMultipartConfig.java
+++ b/vraptor-core/src/main/java/br/com/caelum/vraptor/observer/upload/DefaultMultipartConfig.java
@@ -44,16 +44,18 @@ import org.slf4j.LoggerFactory;
public class DefaultMultipartConfig implements MultipartConfig {
private final Logger logger = LoggerFactory.getLogger(DefaultMultipartConfig.class);
+
+ private static final int DEFAULT_SIZE_LIMIT = 2 * 1024 * 1024;
private Path tmpdir;
@Override
public long getSizeLimit() {
- return 2 * 1024 * 1024;
+ return DEFAULT_SIZE_LIMIT;
}
@Override
public long getFileSizeLimit() {
- return 2 * 1024 * 1024;
+ return DEFAULT_SIZE_LIMIT;
}
@Override
|
Extracting upload size to class constants
|
caelum_vraptor4
|
train
|
663667f298ceba650c9e1b4f92e32dabec41dceb
|
diff --git a/ariba/mic_plotter.py b/ariba/mic_plotter.py
index <HASH>..<HASH> 100644
--- a/ariba/mic_plotter.py
+++ b/ariba/mic_plotter.py
@@ -227,7 +227,7 @@ class MicPlotter:
except:
raise Error('Error opening R script for writing "' + r_script + '"')
- libraries = ['ggplot2', 'RColorBrewer', 'reshape2', 'cowplot']
+ libraries = ['ggplot2', 'RColorBrewer', 'reshape2']
for lib in libraries:
print('library(', lib, ')', sep='', file=f)
@@ -335,10 +335,20 @@ if (use.log){ final.mics <- log(range.mics) }else{ final.mics <- range.mics }
if self.no_combinations:
print('violinplot', file=f)
+ print('ggsave("', self.outprefix, '.pdf", useDingbats=FALSE, height=', self.plot_height, ', width=', self.plot_width, ')', sep='', file=f)
else:
- print('plot_grid(violinplot, dotplot, ncol=1, align="v", rel_heights=c(3,1))', file=f)
+ print(r'''library(gtable)
+library(grid)
+g1 <- ggplotGrob(violinplot)
+g2 <- ggplotGrob(dotplot)
+g <- rbind(g1, g2, size="first")
+g$widths <- unit.pmax(g1$widths, g2$widths)
+panels <- g$layout$t[grepl("panel", g$layout$name)]
+g$heights[panels][1] = unit(2,"null")
+grid.newpage()
+grid.draw(g)
+ggsave("''', self.outprefix, '.pdf", plot=g, useDingbats=FALSE, height=', self.plot_height, ', width=', self.plot_width, ')', sep='', file=f)
- print('ggsave("', self.outprefix, '.pdf", useDingbats=FALSE, height=', self.plot_height, ', width=', self.plot_width, ')', sep='', file=f)
f.close()
common.syscall('R CMD BATCH ' + r_script)
|
Remove dependency on R library cowplot
|
sanger-pathogens_ariba
|
train
|
8244eee121d14112e91674ff69c67ed2c7f8bc60
|
diff --git a/dpark/env.py b/dpark/env.py
index <HASH>..<HASH> 100644
--- a/dpark/env.py
+++ b/dpark/env.py
@@ -37,6 +37,8 @@ class DparkEnv:
root = '/home2/dpark'
elif os.path.exists('/mfs/tmp'):
root = '/mfs/tmp/dpark'
+ else:
+ root = '/tmp/dpark'
self.dfs = True
if not os.path.exists(root):
diff --git a/examples/kmeans.py b/examples/kmeans.py
index <HASH>..<HASH> 100644
--- a/examples/kmeans.py
+++ b/examples/kmeans.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python
import sys, os, os.path
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+sys.path.insert(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import random
from dpark import DparkContext
dpark = DparkContext()
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -2,7 +2,7 @@ from setuptools import setup
version = '0.1'
-setup(name='Dpark',
+setup(name='DPark',
version=version,
description="Python clone of Spark, MapReduce like "
+"computing framework supporting iterative algorithms.",
@@ -16,7 +16,7 @@ setup(name='Dpark',
author='Davies Liu',
author_email='davies.liu@gmail.com',
license= 'BSD License',
- packages=['dpark'],
+ packages=['dpark', 'dpark.moosefs'],
include_package_data=True,
zip_safe=False,
install_requires=[
|
bugfix: install dpark.moosefs, root and sys.path
|
douban_dpark
|
train
|
bf05a99da9661aa731c6938ec7e8443dd381d2eb
|
diff --git a/lib/dev_server.js b/lib/dev_server.js
index <HASH>..<HASH> 100644
--- a/lib/dev_server.js
+++ b/lib/dev_server.js
@@ -35,22 +35,15 @@ class DevServer extends Base {
const env = Object.assign({}, process.env, devServer.env);
env.PATH = `${this.app.config.baseDir}/node_modules/.bin:${env.PATH}`;
const opt = {
- stdio: 'pipe',
+ // disable stdout by default
+ stdio: [ 'inherit', 'ignore', 'inherit' ],
env,
};
if (devServer.cwd) opt.cwd = devServer.cwd;
+ if (devServer.debug) opt.stdio[1] = 'inherit';
const proc = this.proc = spawn(command, args, opt);
- let stderr = '';
- proc.stderr.on('data', data => {
- stderr += data;
- process.stderr.write(data);
- });
- proc.stdout.on('data', data => {
- if (devServer.debug) process.stdout.write(data);
- });
-
- proc.once('error', err => this.exit(err, stderr));
- proc.once('exit', code => this.exit(code, stderr));
+ proc.once('error', err => this.exit(err));
+ proc.once('exit', code => this.exit(code));
}
async checkPortExist() {
@@ -97,7 +90,7 @@ class DevServer extends Base {
this.proc = null;
}
- exit(codeOrError, stderr) {
+ exit(codeOrError) {
const logger = this.app.coreLogger;
this.proc = null;
@@ -113,7 +106,6 @@ class DevServer extends Base {
codeOrError = new Error(message);
}
- codeOrError.stderr = stderr;
logger.error(codeOrError);
}
}
|
refactor: use inherit instead of pipe (#<I>)
<!--
Thank you for your pull request. Please review below requirements.
Bug fixes and new features should include tests and possibly benchmarks.
Contributors guide: <URL>
<!-- Provide affected core subsystem(s). -->
##### Description of change
<!-- Provide a description of the change below this comment. -->
it can support tty
|
eggjs_egg-view-assets
|
train
|
1f700c3b8c39862fdb55c60cde9fb06c69067805
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -13,30 +13,6 @@ from glob import glob
import io
-# check availability of runtime dependencies
-def check_dependency(package, version):
- """Issue a warning if the package is not available."""
- try:
- import gi
- gi.require_version(package.rsplit('.')[-1], version)
- __import__(package)
- except ImportError as e:
- # caused by either of the imports, probably the first
- logging.warning("Missing runtime dependencies:\n\t" + str(e))
- except ValueError as e:
- # caused by the gi.require_version() statement
- logging.warning("Missing runtime dependencies:\n\t" + str(e))
- except RuntimeError as e:
- # caused by the final __import__() statement
- logging.warning("Bad runtime dependency:\n\t" + str(e))
-
-
-check_dependency('gi.repository.Gio', '2.0')
-check_dependency('gi.repository.GLib', '2.0')
-check_dependency('gi.repository.Gtk', '3.0')
-check_dependency('gi.repository.Notify', '0.7')
-
-
# read long_description from README.rst
long_description = None
try:
|
Don't check dependencies in setup.py
- no one would hardly notice anyway
- checking runtime dependencies at packaging time is waste of effort
- adds lot of code
|
coldfix_udiskie
|
train
|
ff9a7dad4271cacd7f6e4535ce1a6c0ff5bfc8c3
|
diff --git a/tests/test_land.py b/tests/test_land.py
index <HASH>..<HASH> 100644
--- a/tests/test_land.py
+++ b/tests/test_land.py
@@ -35,6 +35,13 @@ class Test_FA:
)
assert np.isnan(out.values[:, 0, 0]).all()
+ def test_too_short(self, q_series):
+ q = q_series(np.random.rand(10))
+ out = land.freq_analysis(
+ q, mode="max", t=2, dist="genextreme", window=6, freq="YS"
+ )
+ assert np.isnan(out.values[0])
+
class TestStats:
def test_simple(self, ndq_series):
diff --git a/xclim/core/indicator.py b/xclim/core/indicator.py
index <HASH>..<HASH> 100644
--- a/xclim/core/indicator.py
+++ b/xclim/core/indicator.py
@@ -238,7 +238,7 @@ class Indicator:
kls = MISSING_METHODS[self.missing]
self._missing = kls.execute
if self.missing_options:
- kls.validate(self.missing_options)
+ kls.validate(**self.missing_options)
# Default for output variable name
if self.var_name is None:
diff --git a/xclim/indicators/land/_streamflow.py b/xclim/indicators/land/_streamflow.py
index <HASH>..<HASH> 100644
--- a/xclim/indicators/land/_streamflow.py
+++ b/xclim/indicators/land/_streamflow.py
@@ -22,9 +22,11 @@ class Stats(Streamflow):
missing = "any"
-# Disable the missing value check because the output here is not a time series.
class FA(Streamflow):
- missing = "skip"
+ """Frequency analysis."""
+
+ missing = "at_least_n"
+ missing_options = {"n": 20}
# Disable the daily checks because the inputs are period extremas.
|
FA indicator now using at_least_n missing value algorith, with n=<I>. Fixed Indicator check for hard-coded options. Added test.
|
Ouranosinc_xclim
|
train
|
f29084f72aa06c2c87f80c124ac10f6451645f4c
|
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -112,7 +112,11 @@ module.exports = function (connect) {
options.mongooseConnection.once('open', () => this.handleNewConnectionAsync(options.mongooseConnection))
}
} else if (options.client) {
- this.handleNewConnectionAsync(options.client)
+ if (options.client.isConnected()) {
+ this.handleNewConnectionAsync(options.client)
+ } else {
+ options.client.once('open', () => this.handleNewConnectionAsync(options.client))
+ }
} else if (options.clientPromise) {
options.clientPromise
.then(client => this.handleNewConnectionAsync(client))
|
Wait for client open, before calling db. (#<I>)
|
jdesboeufs_connect-mongo
|
train
|
6bd8b2506878edf92038bc524aa7260b807882e2
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -43,7 +43,7 @@ function compileApp(callback, loader, sourcePath) {
function handleNormalClose(callback, loader) {
fs.readFile('elm.js', function (err, data) {
if (err) throw err;
- var output = '' + data + '\n' + 'module.exports = Elm;';
+ var output = '' + data;
callback(null, output);
});
}
|
remove CommonJS exporting of global Elm now that <I> bundles correctly
|
justinwoo_elm-simple-loader
|
train
|
18b27bde684ac4a4bd58f2341272767e8136a18b
|
diff --git a/lib/contract_interact/st_prime.js b/lib/contract_interact/st_prime.js
index <HASH>..<HASH> 100644
--- a/lib/contract_interact/st_prime.js
+++ b/lib/contract_interact/st_prime.js
@@ -1,4 +1,13 @@
"use strict";
+
+/**
+ *
+ * This is a utility file which would be used for executing all methods on STPrime Contract.<br><br>
+ *
+ * @module lib/contract_interact/st_prime
+ *
+ */
+
//All Module Requires.
const BigNumber = require('bignumber.js')
@@ -26,6 +35,12 @@ const contractName = 'stPrime'
//Some Executions.
currContract.setProvider( web3RpcProvider.currentProvider );
+/**
+ * @constructor
+ *
+ * @param {String} contractAddress - address where Contract has been deployed
+ *
+ */
const StPrimeContractInteract = module.exports = function (contractAddress) {
this.contractAddress = contractAddress;
if ( contractAddress ){
@@ -37,6 +52,15 @@ const StPrimeContractInteract = module.exports = function (contractAddress) {
StPrimeContractInteract.prototype = {
+ /**
+ * Initialize Transer of ST Prime
+ *
+ * @param {String} senderName - address who is initializing this transfer
+ * @param {Object} customOptions - custom params for this transaction
+ *
+ * @return {Result}
+ *
+ */
initialize_transfer: async function(senderName, customOptions) {
const encodedABI = currContract.methods.initialize().encodeABI();
@@ -61,6 +85,14 @@ StPrimeContractInteract.prototype = {
We can move the methods below to somewhere else.
*/
+ /**
+ * Get ST Prime Balance of an address
+ *
+ * @param {String} owner - address
+ *
+ * @return {Result}
+ *
+ */
, getBalanceOf: function ( owner ) {
if ( !helper.isAddressValid( owner ) ) {
return Promise.resolve( responseHelper.error('ci_stp_1', `Invalid blockchain address: ${owner}`) );
@@ -70,6 +102,17 @@ StPrimeContractInteract.prototype = {
});
}
+ /**
+ * Transfer ST Prime
+ *
+ * @param {String} sender - address of sender
+ * @param {String} recipient - address of recipient
+ * @param {String} amountInWei - amount in wei which is to be transferred
+ * @param {String} tag - additional data that goes into this tranasction's log
+ *
+ * @return {Result}
+ *
+ */
, transfer : function ( sender, recipient, amountInWei, tag ) {
var oThis = this;
logger.step("STPrime :: transfer initiated");
@@ -124,6 +167,9 @@ StPrimeContractInteract.prototype = {
})
}
+ /**
+ * @ignore
+ */
, _transferInChain: function ( transferParams ) {
logger.info("STPrime :: _transferInChain initiated");
const oThis = this
@@ -159,6 +205,15 @@ StPrimeContractInteract.prototype = {
;
}
+
+ /**
+ * Create a new managed account
+ *
+ * @param {String} passphrase - passphrase of this new account
+ *
+ * @return {Result}
+ *
+ */
, newManagedAccount: function ( passphrase ) {
return web3RpcProvider.eth.personal.newAccount( passphrase )
.then(address => {
@@ -171,6 +226,12 @@ StPrimeContractInteract.prototype = {
});
}
+ /**
+ * Create a new managed account for a Member Company
+ *
+ * @return {Result}
+ *
+ */
, newMemberManagedAccount: function () {
//STUB METHOD.
//Figure out various inputs required to generate passphrase.
@@ -182,6 +243,14 @@ StPrimeContractInteract.prototype = {
return this.newManagedAccount( passphrase );
}
+ /**
+ * Get passprhrase for a member company address
+ *
+ * @param {String} address - passphrase of this new account
+ *
+ * @return {Result}
+ *
+ */
, getMemberPassphrase: function ( address ) {
//STUB METHOD.
//Figure out various inputs (based on address), required to generate passphrase.
@@ -193,6 +262,12 @@ StPrimeContractInteract.prototype = {
return helper.generateManagedKeyPassphrase(input1, input2, input3);
}
+ /**
+ * Get UUID
+ *
+ * @return {Result}
+ *
+ */
, getUuid: function () {
const oThis = this;
@@ -221,6 +296,16 @@ StPrimeContractInteract.prototype = {
;
}
+ /**
+ * Get passprhrase for a member company address
+ *
+ * @param {String} senderAddress - address of sender
+ * @param {String} senderPassphrase - passphrase of senderAddress
+ * @param {String} beneficiaryAddress - address where funds would be credited
+ *
+ * @return {Result}
+ *
+ */
, claim: async function( senderAddress, senderPassphrase, beneficiaryAddress ) {
const oThis = this;
console.log("beneficiaryAddress", beneficiaryAddress);
|
added comments for st_prime.js
|
OpenSTFoundation_openst-platform
|
train
|
e55b022b57c5f03cf934ef20db54de48351a1666
|
diff --git a/src/commands/ProxyController.php b/src/commands/ProxyController.php
index <HASH>..<HASH> 100644
--- a/src/commands/ProxyController.php
+++ b/src/commands/ProxyController.php
@@ -124,6 +124,9 @@ class ProxyController extends Command
if (!$curl->error) {
$this->flushHasCache();
+
+ $this->verbosePrint($curl->response);
+
$response = Json::decode($curl->response);
$build = new ClientBuild($this, [
'optionStrict' => $this->strict,
@@ -144,9 +147,17 @@ class ProxyController extends Command
}
}
+ $this->clearConfig();
$this->output($curl->response);
return $this->outputError($curl->error_message);
}
+
+ private function clearConfig()
+ {
+ Config::remove(self::CONFIG_VAR_TOKEN);
+ Config::remove(self::CONFIG_VAR_URL);
+ Config::remove(self::CONFIG_VAR_IDENTIFIER);
+ }
/**
* Cleanup all stored Config Data.
@@ -155,9 +166,7 @@ class ProxyController extends Command
*/
public function actionClear()
{
- Config::remove(self::CONFIG_VAR_TOKEN);
- Config::remove(self::CONFIG_VAR_URL);
- Config::remove(self::CONFIG_VAR_IDENTIFIER);
+ $this->clearConfig();
return $this->outputSuccess('Config has been cleared.');
}
}
|
add verbose and flush issue
|
luyadev_luya-module-admin
|
train
|
7caf28ca11af45435496c60eda2896ce30611c07
|
diff --git a/dvc/ignore.py b/dvc/ignore.py
index <HASH>..<HASH> 100644
--- a/dvc/ignore.py
+++ b/dvc/ignore.py
@@ -6,6 +6,7 @@ import os
from pathspec import PathSpec
from pathspec.patterns import GitWildMatchPattern
+from dvc.utils import dvc_walk
from dvc.utils import relpath
from dvc.utils.compat import open
@@ -47,6 +48,9 @@ class DvcIgnorePatterns(DvcIgnore):
return hash(self.ignore_file_path)
def __eq__(self, other):
+ if not isinstance(other, DvcIgnorePatterns):
+ return NotImplemented
+
return self.ignore_file_path == other.ignore_file_path
@@ -59,12 +63,21 @@ class DvcIgnoreDirs(DvcIgnore):
return dirs, files
+ def __hash__(self):
+ return hash(tuple(self.basenames))
+
+ def __eq__(self, other):
+ if not isinstance(other, DvcIgnoreDirs):
+ return NotImplemented
+
+ return self.basenames == other.basenames
+
class DvcIgnoreFilter(object):
def __init__(self, root_dir):
self.ignores = {DvcIgnoreDirs([".git", ".hg", ".dvc"])}
self._update(root_dir)
- for root, dirs, _ in os.walk(root_dir):
+ for root, dirs, _ in dvc_walk(root_dir, self):
for d in dirs:
self._update(os.path.join(root, d))
diff --git a/tests/func/test_ignore.py b/tests/func/test_ignore.py
index <HASH>..<HASH> 100644
--- a/tests/func/test_ignore.py
+++ b/tests/func/test_ignore.py
@@ -5,6 +5,9 @@ import pytest
from dvc.exceptions import DvcIgnoreInCollectedDirError
from dvc.ignore import DvcIgnore
+from dvc.ignore import DvcIgnoreDirs
+from dvc.ignore import DvcIgnoreFilter
+from dvc.ignore import DvcIgnorePatterns
from dvc.utils.compat import cast_bytes
from dvc.utils.fs import get_mtime_and_size
from tests.basic_env import TestDvc
@@ -131,3 +134,21 @@ def test_should_raise_on_dvcignore_in_out_dir(dvc_repo, repo_dir):
with pytest.raises(DvcIgnoreInCollectedDirError):
dvc_repo.add(repo_dir.DATA_DIR)
+
+
+@pytest.mark.parametrize("dname", [TestDvc.DATA_DIR, TestDvc.DATA_SUB_DIR])
+def test_ignore_collecting_dvcignores(repo_dir, dname):
+ top_ignore_file = os.path.join(
+ repo_dir.root_dir, os.path.dirname(dname), DvcIgnore.DVCIGNORE_FILE
+ )
+ repo_dir.create(top_ignore_file, os.path.basename(dname))
+
+ ignore_file = os.path.join(
+ repo_dir.root_dir, dname, DvcIgnore.DVCIGNORE_FILE
+ )
+ repo_dir.create(ignore_file, repo_dir.FOO)
+
+ assert DvcIgnoreFilter(repo_dir.root_dir).ignores == {
+ DvcIgnoreDirs([".git", ".hg", ".dvc"]),
+ DvcIgnorePatterns(top_ignore_file),
+ }
|
dvcignore: don't forget to use dvcignore when collecting dvcignores
Fixes #<I>
|
iterative_dvc
|
train
|
e859fad650d01af5d721a25060d1ce1e1f5a593e
|
diff --git a/atrcopy.py b/atrcopy.py
index <HASH>..<HASH> 100755
--- a/atrcopy.py
+++ b/atrcopy.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python
-__version__ = "2.0.1"
+__version__ = "2.0.2"
import types
|
Updated version to <I>
|
robmcmullen_atrcopy
|
train
|
a9349fdd12e81c1202ee88266e778ef1320b5f79
|
diff --git a/.gitignore b/.gitignore
index <HASH>..<HASH> 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,3 @@
-vendor/
-composer.lock
-phpunit.xml
+/vendor
+/composer.lock
+/.phpunit.result.cache
diff --git a/composer.json b/composer.json
index <HASH>..<HASH> 100644
--- a/composer.json
+++ b/composer.json
@@ -21,7 +21,7 @@
"ext-pdo": "*"
},
"require-dev": {
- "phpunit/phpunit": "^7",
+ "phpunit/phpunit": "^8",
"symplify/easy-coding-standard": "^9"
},
"autoload": {
diff --git a/tests/Adapter/ConfigTest.php b/tests/Adapter/ConfigTest.php
index <HASH>..<HASH> 100644
--- a/tests/Adapter/ConfigTest.php
+++ b/tests/Adapter/ConfigTest.php
@@ -16,7 +16,7 @@ class ConfigTest extends TestCase
public function testGetDsn(array $dsnConfig, string $expectedElement): void
{
$config = new Config($dsnConfig);
- static::assertContains($dsnConfig[$expectedElement], $config->getDsn());
+ static::assertStringContainsString($dsnConfig[$expectedElement], $config->getDsn());
}
public function getDsnDataProvider(): array
diff --git a/tests/Adapter/ConnectionFactoryTest.php b/tests/Adapter/ConnectionFactoryTest.php
index <HASH>..<HASH> 100644
--- a/tests/Adapter/ConnectionFactoryTest.php
+++ b/tests/Adapter/ConnectionFactoryTest.php
@@ -62,7 +62,7 @@ class ConnectionFactoryTest extends TestCase
$pdoStatement = $this->createMock(\PDOStatement::class);
$pdoStatement->method('execute')
- ->with(static::contains($value));
+ ->with(static::containsIdentical($value));
$this->pdo->method('prepare')
->willReturn($pdoStatement);
diff --git a/tests/AdapterTest.php b/tests/AdapterTest.php
index <HASH>..<HASH> 100644
--- a/tests/AdapterTest.php
+++ b/tests/AdapterTest.php
@@ -175,7 +175,7 @@ class AdapterTest extends TestCase
$statement = $this->createMock(\PDOStatement::class);
$statement->expects(static::once())
->method('execute')
- ->with(static::contains($value));
+ ->with(static::containsIdentical($value));
$this->pdo->method('prepare')
->willReturn($statement);
|
Upgrade PHPUnit to v8
|
phlib_db
|
train
|
2712edc377cf62af26a5067e49024142007aeb0b
|
diff --git a/src/Admin/PlotEmbeddedAdmin.php b/src/Admin/PlotEmbeddedAdmin.php
index <HASH>..<HASH> 100644
--- a/src/Admin/PlotEmbeddedAdmin.php
+++ b/src/Admin/PlotEmbeddedAdmin.php
@@ -10,11 +10,11 @@
namespace Librinfo\SeedBatchBundle\Admin;
-use Blast\CoreBundle\Admin\Traits\EmbeddedAdmin;
+// use Blast\CoreBundle\Admin\Traits\EmbeddedAdmin;
class PlotEmbeddedAdmin extends PlotAdmin
{
- use EmbeddedAdmin;
+ // use EmbeddedAdmin;
protected $baseRouteName = 'admin_librinfo_seedbatch_plot_embedded';
protected $baseRoutePattern = 'librinfo/seedbatch/plot_embedded';
|
Revert uncommenting of plot embedded admin
|
sil-project_SeedBatchBundle
|
train
|
8b4247097a10939c799d9e425195b3ec3b087041
|
diff --git a/lib/ethel/migration.rb b/lib/ethel/migration.rb
index <HASH>..<HASH> 100644
--- a/lib/ethel/migration.rb
+++ b/lib/ethel/migration.rb
@@ -39,6 +39,7 @@ module Ethel
reader.each_row do |row|
row = op.transform(row)
+ next if row == :skip
@dataset.validate_row(row)
writer.add_row(row)
end
diff --git a/test/unit/ethel/test_migration.rb b/test/unit/ethel/test_migration.rb
index <HASH>..<HASH> 100644
--- a/test/unit/ethel/test_migration.rb
+++ b/test/unit/ethel/test_migration.rb
@@ -140,4 +140,29 @@ class TestMigration < Test::Unit::TestCase
seq << @writer.expects(:flush)
m.run
end
+
+ test "filtering fields" do
+ dataset = stub('dataset')
+ Ethel::Dataset.expects(:new).returns(dataset)
+ @reader.expects(:read).with(dataset)
+ m = Ethel::Migration.new(@reader, @writer)
+
+ filter_op = stub('filter operation')
+ m.add_operation(filter_op)
+
+ seq = SequenceHelper.new('run sequence')
+
+ seq << filter_op.expects(:setup).with(dataset)
+ seq << @writer.expects(:prepare).with(dataset)
+
+ row_1 = stub('row')
+ row_2 = stub('row')
+ seq << @reader.expects(:each_row).multiple_yields([row_1], [row_2])
+ seq << filter_op.expects(:transform).with(row_1).returns(:skip)
+ seq << filter_op.expects(:transform).with(row_2).returns(row_2)
+ seq << dataset.expects(:validate_row).with(row_2)
+ seq << @writer.expects(:add_row).with(row_2)
+ seq << @writer.expects(:flush)
+ m.run
+ end
end
|
Let operations skip rows by returning :skip during Migration#run
|
coupler_ethel
|
train
|
0dd840e3b9b88daa8c88f5fb890b397cfd2b2e76
|
diff --git a/examples/sqlite_example/sqlite_clustering.py b/examples/sqlite_example/sqlite_clustering.py
index <HASH>..<HASH> 100644
--- a/examples/sqlite_example/sqlite_clustering.py
+++ b/examples/sqlite_example/sqlite_clustering.py
@@ -17,6 +17,7 @@ t0 = time.time()
print 'selecting random sample from donors table...'
con = sqlite3.connect("examples/sqlite_example/illinois_contributions.db")
con.row_factory = sqlite3.Row
+con.execute("ATTACH DATABASE 'examples/sqlite_example/blocking_map.db' AS bm")
cur = con.cursor()
@@ -29,18 +30,18 @@ else:
cur.execute('select * from donors join '
- '(select key, donor_id from blocking_map '
- 'join (select key, count(donor_id) num_candidates from blocking_map '
+ '(select key, donor_id from bm.blocking_map '
+ 'join (select key, count(donor_id) num_candidates from bm.blocking_map '
'group by key having num_candidates > 1) '
'as bucket using (key)) as candidates using (donor_id)')
-block_keys = (row['key'] for row in con.execute('select key, count(donor_id) as num_candidates from blocking_map group by key having num_candidates > 1'))
+block_keys = (row['key'] for row in con.execute('select key, count(donor_id) as num_candidates from bm.blocking_map group by key having num_candidates > 1'))
def candidates_gen() :
candidate_set = set([])
for block_key in block_keys :
- block = set(itertools.combinations(((row['donor_id'], row) for row in con.execute('select * from donors inner join blocking_map using (donor_id) where key = ? order by donor_id', (block_key,))), 2))
+ block = set(itertools.combinations(((row['donor_id'], row) for row in con.execute('select * from donors inner join bm.blocking_map using (donor_id) where key = ? order by donor_id', (block_key,))), 2))
new = block - candidate_set
candidate_set |= new
for candidate_pair in new :
|
fix clustering to use attached blocking_map db
|
dedupeio_dedupe
|
train
|
d655df534f1b8ea0c0743360ebd893a56df26b7c
|
diff --git a/Rakefile b/Rakefile
index <HASH>..<HASH> 100644
--- a/Rakefile
+++ b/Rakefile
@@ -30,8 +30,3 @@ task :doc => 'db:environment' do
Rake::Task["db:schema:dump"].invoke
Rake::Task["yard"].invoke
end
-
-task :ci => ['db:migrate', 'db:seed'] do
- sh %{$(npm bin)/eslint client spec/client/}
- sh %{bundle exec lanes jest}
-end
diff --git a/lib/lanes/extension/definition.rb b/lib/lanes/extension/definition.rb
index <HASH>..<HASH> 100644
--- a/lib/lanes/extension/definition.rb
+++ b/lib/lanes/extension/definition.rb
@@ -127,6 +127,8 @@ module Lanes
end
end
+ def on_dev_console
+ end
end
end
diff --git a/lib/lanes/rake_tasks.rb b/lib/lanes/rake_tasks.rb
index <HASH>..<HASH> 100644
--- a/lib/lanes/rake_tasks.rb
+++ b/lib/lanes/rake_tasks.rb
@@ -66,3 +66,9 @@ end
task :test => [:spec] do
::Lanes::Command::Jest.new.configure.single_run
end
+
+task :ci => ['db:migrate', 'db:seed'] do
+ sh %{node node_modules/eslint/bin/eslint.js client spec/client/}
+ sh %{bundle exec lanes jest}
+ sh %{bundle exec rspec}
+end
|
move ci to commone rake tasks
|
argosity_hippo
|
train
|
2e8c0e030d4190bc8673914ca809171c70b52eba
|
diff --git a/ontrack-extension-svn/src/main/java/net/nemerosa/ontrack/extension/svn/support/BuildSvnRevisionLinkMigrationAction.java b/ontrack-extension-svn/src/main/java/net/nemerosa/ontrack/extension/svn/support/BuildSvnRevisionLinkMigrationAction.java
index <HASH>..<HASH> 100644
--- a/ontrack-extension-svn/src/main/java/net/nemerosa/ontrack/extension/svn/support/BuildSvnRevisionLinkMigrationAction.java
+++ b/ontrack-extension-svn/src/main/java/net/nemerosa/ontrack/extension/svn/support/BuildSvnRevisionLinkMigrationAction.java
@@ -2,6 +2,7 @@ package net.nemerosa.ontrack.extension.svn.support;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
+import net.nemerosa.ontrack.client.JsonClientMappingException;
import net.nemerosa.ontrack.extension.scm.support.TagPattern;
import net.nemerosa.ontrack.extension.svn.property.SVNBranchConfigurationPropertyType;
import net.nemerosa.ontrack.json.ObjectMapperFactory;
@@ -9,8 +10,12 @@ import net.nemerosa.ontrack.model.structure.ServiceConfiguration;
import net.nemerosa.ontrack.model.support.DBMigrationAction;
import net.nemerosa.ontrack.model.support.NoConfig;
import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
+import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@@ -24,11 +29,13 @@ import java.util.regex.Pattern;
@Component
public class BuildSvnRevisionLinkMigrationAction implements DBMigrationAction {
+ private final Logger logger = LoggerFactory.getLogger(BuildSvnRevisionLinkMigrationAction.class);
private final ObjectMapper objectMapper = ObjectMapperFactory.create();
private final RevisionSvnRevisionLink revisionLink;
private final TagNamePatternSvnRevisionLink tagPatternLink;
+ @Autowired
public BuildSvnRevisionLinkMigrationAction(RevisionSvnRevisionLink revisionLink, TagNamePatternSvnRevisionLink tagPatternLink) {
this.revisionLink = revisionLink;
this.tagPatternLink = tagPatternLink;
@@ -42,18 +49,18 @@ public class BuildSvnRevisionLinkMigrationAction implements DBMigrationAction {
@Override
public void migrate(Connection connection) throws Exception {
// For all Svn branch configurations
- try (PreparedStatement ps = connection.prepareStatement("SELECT * FROM CONFIGURATIONS WHERE TYPE = ?", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) {
+ try (PreparedStatement ps = connection.prepareStatement("SELECT * FROM PROPERTIES WHERE TYPE = ?", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) {
ps.setString(1, SVNBranchConfigurationPropertyType.class.getName());
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
// Configuration as JSON
- String json = rs.getString("CONTENT");
+ String json = rs.getString("JSON");
// Parses the configuration as JSON
ObjectNode node = (ObjectNode) objectMapper.readTree(json);
// Migrates the node
migrate(node);
// Updating
- rs.updateString("CONTENT", objectMapper.writeValueAsString(node));
+ rs.updateString("JSON", objectMapper.writeValueAsString(node));
rs.updateRow();
}
}
@@ -62,6 +69,7 @@ public class BuildSvnRevisionLinkMigrationAction implements DBMigrationAction {
protected void migrate(ObjectNode node) {
// Gets the build path & branch path
+ String branchPath = node.get("branchPath").asText();
String buildPath = node.get("buildPath").asText();
// Removes the build path property
node.remove("buildPath");
@@ -73,6 +81,17 @@ public class BuildSvnRevisionLinkMigrationAction implements DBMigrationAction {
ServiceConfiguration serviceConfiguration = configuredBuildSvnRevisionLink.toServiceConfiguration();
// As json...
node.put("buildRevisionLink", (ObjectNode) objectMapper.valueToTree(serviceConfiguration));
+ // Logging
+ try {
+ logger.info(
+ "SVN branch config for {} with build expression {} has been converted to {}",
+ branchPath,
+ buildPath,
+ objectMapper.writeValueAsString(serviceConfiguration)
+ );
+ } catch (IOException ex) {
+ throw new JsonClientMappingException(ex);
+ }
}
protected ConfiguredBuildSvnRevisionLink<?> toBuildSvnRevisionLinkConfiguration(String buildPath) {
|
#<I> SVN branch configuration migration - logging & correction
|
nemerosa_ontrack
|
train
|
5ce6fbdcb58205d40fe1d37d475527cb8421be0a
|
diff --git a/components/doc/skeleton/index.js b/components/doc/skeleton/index.js
index <HASH>..<HASH> 100644
--- a/components/doc/skeleton/index.js
+++ b/components/doc/skeleton/index.js
@@ -3,6 +3,7 @@ import Link from 'next/link';
import { TabView, TabPanel } from '../../lib/tabview/TabView';
import { useLiveEditorTabs } from '../common/liveeditor';
import { CodeHighlight } from '../common/codehighlight';
+import { DevelopmentSection } from '../common/developmentsection';
const SkeletonDoc = memo( () => {
@@ -719,6 +720,16 @@ import { Skeleton } from 'primereact/skeleton';
</table>
</div>
+ <h5>Accessibility</h5>
+ <DevelopmentSection>
+ <h6>Screen Reader</h6>
+ <p>Skeleton uses <i>aria-hidden</i> as "true" so that it gets ignored by screen readers, any valid attribute is passed to the root element so you may customize it further if required. If multiple skeletons are grouped inside a container,
+ you may use <i>aria-busy</i> on the container element as well to indicate the loading process.</p>
+
+ <h5>Keyboard Support</h5>
+ <p>Component does not include any interactive elements.</p>
+ </DevelopmentSection>
+
<h5>Dependencies</h5>
<p>None.</p>
</TabPanel>
|
a<I>y for Skeleton
|
primefaces_primereact
|
train
|
5d1fdceb98e0114cb09dbd7aecef6794604e92aa
|
diff --git a/gns3server/controller/project.py b/gns3server/controller/project.py
index <HASH>..<HASH> 100644
--- a/gns3server/controller/project.py
+++ b/gns3server/controller/project.py
@@ -174,6 +174,7 @@ class Project:
self._links = {}
self._drawings = {}
self._snapshots = {}
+ self._computes = []
# List the available snapshots
snapshot_dir = os.path.join(self.path, "snapshots")
@@ -564,6 +565,9 @@ class Project:
if node_id in self._nodes:
return self._nodes[node_id]
+ if compute.id not in self._computes:
+ self._computes.append(compute.id)
+
if node_type == "iou":
async with self._iou_id_lock:
# wait for a IOU node to be completely created before adding a new one
@@ -571,10 +575,10 @@ class Project:
# to generate MAC addresses) when creating multiple IOU node at the same time
if "properties" in kwargs.keys():
# allocate a new application id for nodes loaded from the project
- kwargs.get("properties")["application_id"] = get_next_application_id(self._controller.projects, compute)
+ kwargs.get("properties")["application_id"] = get_next_application_id(self._controller.projects, self._computes)
elif "application_id" not in kwargs.keys() and not kwargs.get("properties"):
# allocate a new application id for nodes added to the project
- kwargs["application_id"] = get_next_application_id(self._controller.projects, compute)
+ kwargs["application_id"] = get_next_application_id(self._controller.projects, self._computes)
node = await self._create_node(compute, name, node_id, node_type, **kwargs)
else:
node = await self._create_node(compute, name, node_id, node_type, **kwargs)
@@ -604,6 +608,8 @@ class Project:
self.remove_allocated_node_name(node.name)
del self._nodes[node.id]
await node.destroy()
+ # refresh the compute IDs list
+ self._computes = [n.compute.id for n in self.nodes.values()]
self.dump()
self.emit_notification("node.deleted", node.__json__())
@@ -931,6 +937,14 @@ class Project:
topology = project_data["topology"]
for compute in topology.get("computes", []):
await self.controller.add_compute(**compute)
+
+ # Get all compute used in the project
+ # used to allocate application IDs for IOU nodes.
+ for node in topology.get("nodes", []):
+ compute_id = node.get("compute_id")
+ if compute_id not in self._computes:
+ self._computes.append(compute_id)
+
for node in topology.get("nodes", []):
compute = self.controller.get_compute(node.pop("compute_id"))
name = node.pop("name")
diff --git a/gns3server/utils/application_id.py b/gns3server/utils/application_id.py
index <HASH>..<HASH> 100644
--- a/gns3server/utils/application_id.py
+++ b/gns3server/utils/application_id.py
@@ -21,26 +21,27 @@ import logging
log = logging.getLogger(__name__)
-def get_next_application_id(projects, compute):
+def get_next_application_id(projects, computes):
"""
Calculates free application_id from given nodes
:param projects: all projects managed by controller
- :param compute: Compute instance
+ :param computes: all computes used by the project
:raises HTTPConflict when exceeds number
:return: integer first free id
"""
nodes = []
- # look for application id for in all nodes across all opened projects that share the same compute
+ # look for application id for in all nodes across all opened projects that share the same computes
for project in projects.values():
- if project.status == "opened" and compute in project.computes:
+ if project.status == "opened":
nodes.extend(list(project.nodes.values()))
- used = set([n.properties["application_id"] for n in nodes if n.node_type == "iou"])
+ used = set([n.properties["application_id"] for n in nodes if n.node_type == "iou" and n.compute.id in computes])
pool = set(range(1, 512))
try:
- return (pool - used).pop()
+ application_id = (pool - used).pop()
+ return application_id
except KeyError:
- raise aiohttp.web.HTTPConflict(text="Cannot create a new IOU node (limit of 512 nodes across all opened projects using compute {} reached".format(compute.name))
+ raise aiohttp.web.HTTPConflict(text="Cannot create a new IOU node (limit of 512 nodes across all opened projects using the same computes)")
|
Fix bug with application id allocation for IOU nodes. Fixes #<I>
|
GNS3_gns3-server
|
train
|
0ffeeaf8fe959df352de656b778ee18efdc3b622
|
diff --git a/src-test/core/useragenttest.js b/src-test/core/useragenttest.js
index <HASH>..<HASH> 100644
--- a/src-test/core/useragenttest.js
+++ b/src-test/core/useragenttest.js
@@ -357,6 +357,22 @@ UserAgentTest.prototype.testBrowserIsIPadWithoutIPhone = function() {
assertTrue(userAgent.isSupportingWebFont());
};
+UserAgentTest.prototype.testBrowserIsIPadChrome = function() {
+ var userAgentParser = new webfont.UserAgentParser(
+ "Mozilla/5.0 (iPad; U; CPU OS 5_1_1 like Mac OS X; en-us) AppleWebKit/534.46.0 (KHTML, like Gecko) CriOS/19.0.1084.60 Mobile/9B206 Safari/7534.48.3",
+ this.defaultDocument_);
+ var userAgent = userAgentParser.parse();
+
+ assertEquals("Chrome", userAgent.getName());
+ assertEquals("19.0.1084.60", userAgent.getVersion());
+ assertEquals("iPad", userAgent.getPlatform());
+ assertEquals("5_1_1", userAgent.getPlatformVersion());
+ assertEquals("AppleWebKit", userAgent.getEngine());
+ assertEquals("534.46.0", userAgent.getEngineVersion());
+ assertEquals(undefined, userAgent.getDocumentMode());
+ assertTrue(userAgent.isSupportingWebFont());
+}
+
UserAgentTest.prototype.testBrowserIsIPod = function() {
var userAgentParser = new webfont.UserAgentParser(
"Mozilla/5.0 (iPod; U; CPU iPhone OS 2_2_1 like Mac OS X; en-us) AppleWebKit/525.18.1 (KHTML, like Gecko) Mobile/5H11a",
@@ -389,6 +405,22 @@ UserAgentTest.prototype.testBrowserIsIPodSafari = function() {
assertTrue(userAgent.isSupportingWebFont());
};
+UserAgentTest.prototype.testBrowserIsIPodChrome = function() {
+ var userAgentParser = new webfont.UserAgentParser(
+ "Mozilla/5.0 (iPod; U; CPU iPhone OS 5_1_1 like Mac OS X; en-us) AppleWebKit/534.46.0 (KHTML, like Gecko) CriOS/19.0.1084.60 Mobile/9B206 Safari/7534.48.3",
+ this.defaultDocument_);
+ var userAgent = userAgentParser.parse();
+
+ assertEquals("Chrome", userAgent.getName());
+ assertEquals("19.0.1084.60", userAgent.getVersion());
+ assertEquals("iPod", userAgent.getPlatform());
+ assertEquals("5_1_1", userAgent.getPlatformVersion());
+ assertEquals("AppleWebKit", userAgent.getEngine());
+ assertEquals("534.46.0", userAgent.getEngineVersion());
+ assertEquals(undefined, userAgent.getDocumentMode());
+ assertTrue(userAgent.isSupportingWebFont());
+}
+
UserAgentTest.prototype.testBrowserIsSafariWithPlusVersion = function() {
var userAgentParser = new webfont.UserAgentParser(
"Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_4_11; tr) AppleWebKit/528.4+ (KHTML, like Gecko) Version/4.0dp1 Safari/526.11.2",
diff --git a/src/core/useragentparser.js b/src/core/useragentparser.js
index <HASH>..<HASH> 100644
--- a/src/core/useragentparser.js
+++ b/src/core/useragentparser.js
@@ -195,7 +195,7 @@ webfont.UserAgentParser.prototype.parseWebKitUserAgentString_ = function() {
}
var name = webfont.UserAgentParser.UNKNOWN;
- if (this.userAgent_.indexOf("Chrome") != -1 || this.userAgent_.indexOf("CrMo") != -1) {
+ if (this.userAgent_.indexOf("Chrome") != -1 || this.userAgent_.indexOf("CrMo") != -1 || this.userAgent_.indexOf("CriOS") != -1) {
name = "Chrome";
} else if (this.userAgent_.indexOf("Safari") != -1) {
name = "Safari";
@@ -209,7 +209,7 @@ webfont.UserAgentParser.prototype.parseWebKitUserAgentString_ = function() {
/Version\/([\d\.\w]+)/, 1);
} else if (name == "Chrome") {
version = this.getMatchingGroup_(this.userAgent_,
- /(Chrome|CrMo)\/([\d\.]+)/, 2);
+ /(Chrome|CrMo|CriOS)\/([\d\.]+)/, 2);
} else if (name == "AdobeAIR") {
version = this.getMatchingGroup_(this.userAgent_,
/AdobeAIR\/([\d\.]+)/, 1);
|
Add the ability to detect Chrome for iOS as Chrome, not Safari
|
typekit_webfontloader
|
train
|
166ec2f29550bcc863813861314cf5709246e5b6
|
diff --git a/horizon/horizon/dashboards/nova/access_and_security/floating_ips/tables.py b/horizon/horizon/dashboards/nova/access_and_security/floating_ips/tables.py
index <HASH>..<HASH> 100644
--- a/horizon/horizon/dashboards/nova/access_and_security/floating_ips/tables.py
+++ b/horizon/horizon/dashboards/nova/access_and_security/floating_ips/tables.py
@@ -32,7 +32,7 @@ LOG = logging.getLogger(__name__)
class AllocateIP(tables.LinkAction):
name = "allocate"
verbose_name = _("Allocate IP To Tenant")
- attrs = {"class": "ajax-modal btn primary small"}
+ attrs = {"class": "ajax-modal btn small"}
url = "horizon:nova:access_and_security:floating_ips:allocate"
def single(self, data_table, request, *args):
diff --git a/horizon/horizon/dashboards/syspanel/users/tables.py b/horizon/horizon/dashboards/syspanel/users/tables.py
index <HASH>..<HASH> 100644
--- a/horizon/horizon/dashboards/syspanel/users/tables.py
+++ b/horizon/horizon/dashboards/syspanel/users/tables.py
@@ -17,7 +17,7 @@ class CreateUserLink(tables.LinkAction):
verbose_name = _("Create User")
url = "horizon:syspanel:users:create"
attrs = {
- "class": "ajax-modal btn primary small",
+ "class": "ajax-modal btn small",
}
diff --git a/horizon/horizon/tables/actions.py b/horizon/horizon/tables/actions.py
index <HASH>..<HASH> 100644
--- a/horizon/horizon/tables/actions.py
+++ b/horizon/horizon/tables/actions.py
@@ -42,7 +42,7 @@ class BaseAction(object):
def __init__(self):
self.attrs = getattr(self, "attrs", {})
- self.classes = []
+ self.classes = getattr(self, "classes", [])
def allowed(self, request, datum):
""" Determine whether this action is allowed for the current request.
diff --git a/openstack-dashboard/dashboard/static/dashboard/css/style.css b/openstack-dashboard/dashboard/static/dashboard/css/style.css
index <HASH>..<HASH> 100644
--- a/openstack-dashboard/dashboard/static/dashboard/css/style.css
+++ b/openstack-dashboard/dashboard/static/dashboard/css/style.css
@@ -754,6 +754,22 @@ td.actions_column {
min-height: 20px;
}
+td.actions_column .row_actions a,
+td.actions_column .row_actions input,
+td.actions_column .row_actions button {
+ background: none;
+ float: none;
+ display: block;
+ padding: 5px 10px;
+ color: black;
+ text-align: left;
+ border-radius: 0;
+ border: 0 none;
+ -webkit-box-shadow: none;
+ -moz-box-shadow: none;
+ box-shadow: none;
+}
+
/* Makes size consistent across browsers when mixing "btn-group" and "small" */
.btn-group > .btn.small {
height: 12px;
@@ -768,27 +784,32 @@ td.actions_column {
}
.dropdown-menu button {
line-height: 18px; /* Matches rule for ".dropdown-menu a" in bootstrap */
+ width: 100%;
}
-
-td.actions_column ul.row_actions li:hover {
- background-color: #cdcdcd;
+.btn-group .dropdown-menu .btn {
+ border-radius: 0;
}
-
-td.actions_column ul.row_actions a,
-td.actions_column ul.row_actions input,
-td.actions_column ul.row_actions button {
+.dropdown-menu .btn.danger,
+.dropdown-menu .btn.danger:hover,
+.dropdown-menu .btn.success,
+.dropdown-menu .btn.success:hover,
+.dropdown-menu .btn.info, .btn.info:hover {
+ text-shadow: none; /* remove default bootstrap shadowing from button text. */
+}
+.dropdown-menu li:hover {
background: none;
- float: none;
- display: block;
- padding: 5px 10px;
- color: black;
- text-align: left;
- border-radius: 0;
- border: 0 none;
- -webkit-box-shadow: none;
- -moz-box-shadow: none;
- box-shadow: none;
}
+td.actions_column .dropdown-menu a:hover,
+td.actions_column .dropdown-menu button:hover {
+ background-color: #CDCDCD;
+}
+.dropdown-menu .btn.danger {
+ color: #C43C35;
+}
+.dropdown-menu .btn.danger:hover {
+ background-color: #f6e0df;
+}
+
/* Overrides for single-action rows (no dropdown) */
|
Implements action colors as per style guide. Fixes bug <I>.
Change-Id: I<I>cfe9d4ed3c6ae<I>e<I>ec<I>bc5cc<I>fa9
|
openstack_horizon
|
train
|
741eb5015f7027bb9de64593f3dcd12199c6d948
|
diff --git a/lib/licensee/project_files/license_file.rb b/lib/licensee/project_files/license_file.rb
index <HASH>..<HASH> 100644
--- a/lib/licensee/project_files/license_file.rb
+++ b/lib/licensee/project_files/license_file.rb
@@ -34,8 +34,8 @@ module Licensee
/\A#{COPYING_REGEX}#{OTHER_EXT_REGEX}\z/ => 0.75, # COPYING.textile
/\A#{LICENSE_REGEX}[-_]/ => 0.70, # LICENSE-MIT
/\A#{COPYING_REGEX}[-_]/ => 0.65, # COPYING-MIT
- /[-_]#{LICENSE_REGEX}/ => 0.60, # MIT-LICENSE-MIT
- /[-_]#{COPYING_REGEX}/ => 0.55, # MIT-COPYING
+ /\A\w+[-_]#{LICENSE_REGEX}/ => 0.60, # MIT-LICENSE-MIT
+ /\A\w+[-_]#{COPYING_REGEX}/ => 0.55, # MIT-COPYING
/\A#{OFL_REGEX}#{PREFERRED_EXT_REGEX}/ => 0.50, # OFL.md
/\A#{OFL_REGEX}#{OTHER_EXT_REGEX}/ => 0.45, # OFL.textile
/\A#{OFL_REGEX}\z/ => 0.40, # OFL
diff --git a/spec/licensee/project_files/license_file_spec.rb b/spec/licensee/project_files/license_file_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/licensee/project_files/license_file_spec.rb
+++ b/spec/licensee/project_files/license_file_spec.rb
@@ -57,32 +57,33 @@ RSpec.describe Licensee::ProjectFiles::LicenseFile do
context 'filename scoring' do
{
- 'license' => 1.00,
- 'LICENCE' => 1.00,
- 'unLICENSE' => 1.00,
- 'unlicence' => 1.00,
- 'license.md' => 0.95,
- 'LICENSE.md' => 0.95,
- 'license.txt' => 0.95,
- 'COPYING' => 0.90,
- 'copyRIGHT' => 0.90,
- 'COPYRIGHT.txt' => 0.85,
- 'copying.txt' => 0.85,
- 'LICENSE.php' => 0.80,
- 'LICENCE.docs' => 0.80,
- 'copying.image' => 0.75,
- 'COPYRIGHT.go' => 0.75,
- 'LICENSE-MIT' => 0.70,
- 'LICENSE_1_0.txt' => 0.70,
- 'COPYING-GPL' => 0.65,
- 'COPYRIGHT-BSD' => 0.65,
- 'MIT-LICENSE.txt' => 0.60,
- 'mit-license-foo.md' => 0.60,
- 'OFL.md' => 0.50,
- 'ofl.textile' => 0.45,
- 'ofl' => 0.40,
- 'not-the-ofl' => 0.00,
- 'README.txt' => 0.00
+ 'license' => 1.00,
+ 'LICENCE' => 1.00,
+ 'unLICENSE' => 1.00,
+ 'unlicence' => 1.00,
+ 'license.md' => 0.95,
+ 'LICENSE.md' => 0.95,
+ 'license.txt' => 0.95,
+ 'COPYING' => 0.90,
+ 'copyRIGHT' => 0.90,
+ 'COPYRIGHT.txt' => 0.85,
+ 'copying.txt' => 0.85,
+ 'LICENSE.php' => 0.80,
+ 'LICENCE.docs' => 0.80,
+ 'copying.image' => 0.75,
+ 'COPYRIGHT.go' => 0.75,
+ 'LICENSE-MIT' => 0.70,
+ 'LICENSE_1_0.txt' => 0.70,
+ 'COPYING-GPL' => 0.65,
+ 'COPYRIGHT-BSD' => 0.65,
+ 'MIT-LICENSE.txt' => 0.60,
+ 'mit-license-foo.md' => 0.60,
+ 'OFL.md' => 0.50,
+ 'ofl.textile' => 0.45,
+ 'ofl' => 0.40,
+ 'not-the-ofl' => 0.00,
+ 'README.txt' => 0.00,
+ '.pip-license-ignore' => 0.00
}.each do |filename, expected|
context "a file named #{filename}" do
let(:score) { described_class.name_score(filename) }
|
Ignore dotfiles with 'license' and dashes
Fixes #<I>
|
licensee_licensee
|
train
|
da633b8bdbfeacad04a1e31971b3e3957f7af283
|
diff --git a/server/src/main/resources/assets/js/grapes-commons.js b/server/src/main/resources/assets/js/grapes-commons.js
index <HASH>..<HASH> 100644
--- a/server/src/main/resources/assets/js/grapes-commons.js
+++ b/server/src/main/resources/assets/js/grapes-commons.js
@@ -336,7 +336,9 @@ function getSearchResult(){
} else {
$.each(modulesData, function(i, module) {
var obj = getModuleNameAndVersion(module);
- html += "<tr><td><a href=\"/module/" + obj.name + "/" + obj.version + "\" >" + module + "</a><span></span><a class=\"secondAnchor\" href=\"javascript:void(0)\" onclick=\"navigateToDataBrowserModule(this); return false;\">Open in data browser</a></td></tr>";
+ html += "<tr><td>" +
+ getDataBrowserButton('navigateToDataBrowserModule') +
+ " <a href=\"/module/" + obj.name + "/" + obj.version + "\" >" + module + "</a><span></span></td></tr>";
});
}
}else {
@@ -358,7 +360,9 @@ function getSearchResult(){
html += "<tr><td style=\"color: red\">Too many results. Refine your search criteria!</td></tr>";
} else {
$.each(artifactsData, function(i, artifact) {
- html += "<tr><td><a href=\"/artifact/" + artifact + "\">" + artifact + "</a><span></span><a class=\"secondAnchor\" href=\"javascript:void(0)\" onclick=\"navigateToDataBrowserArtifact(this); return false;\">Open in data browser</a></td></tr>";
+ html += "<tr><td>"+
+ getDataBrowserButton('navigateToDataBrowserArtifact') +
+ " <a href=\"/artifact/" + artifact + "\">" + artifact + "</a><span></span></td></tr>";
});
}
} else {
@@ -375,6 +379,14 @@ function getSearchResult(){
});
}
+function getDataBrowserButton(fnName) {
+ return "<button class='btn btn-inverse' "+
+ " onclick=\"" + fnName + "(this); return false;\"" +
+ ">" +
+ "<span class='icon-list icon-white' title='Open in Data Browser'></span>" +
+ "</button>";
+}
+
/* Return encoded url with or without query params depending on checkbox selection */
function getEncodedUrl(searchText, queryParams) {
var url = "";
|
Added navigation using button to the data browser link.
|
Axway_Grapes
|
train
|
585ddcea27186cc33edfea522814a1645c3b7bb3
|
diff --git a/niftypet/nimpa/prc/regseg.py b/niftypet/nimpa/prc/regseg.py
index <HASH>..<HASH> 100644
--- a/niftypet/nimpa/prc/regseg.py
+++ b/niftypet/nimpa/prc/regseg.py
@@ -243,11 +243,11 @@ def affine_niftyreg(
if rmsk:
f_rmsk = os.path.join(fimdir, 'rmask_'+os.path.basename(fref).split('.nii')[0]+'.nii.gz')
- create_mask(fnii, fimout = f_rmsk, thrsh = rthrsh, fwhm = rfwhm)
+ create_mask(fref, fimout = f_rmsk, thrsh = rthrsh, fwhm = rfwhm)
if fmsk:
f_fmsk = os.path.join(fimdir, 'fmask_'+os.path.basename(fflo).split('.nii')[0]+'.nii.gz')
- create_mask(fnii, fimout = f_fmsk, thrsh = fthrsh, fwhm = ffwhm)
+ create_mask(fflo, fimout = f_fmsk, thrsh = fthrsh, fwhm = ffwhm)
# output in register with ref and text file for the affine transform
if fname_aff!='':
|
fixed bug in regseg.py with mask creation
|
pjmark_NIMPA
|
train
|
5a51a8e335bc166e1b6dcaa14c4045edfc3da771
|
diff --git a/pylatexenc/latex2text/_defaultspecs.py b/pylatexenc/latex2text/_defaultspecs.py
index <HASH>..<HASH> 100644
--- a/pylatexenc/latex2text/_defaultspecs.py
+++ b/pylatexenc/latex2text/_defaultspecs.py
@@ -170,10 +170,6 @@ _latex_specs_approximations = {
MacroTextSpec('textsl', discard=False),
MacroTextSpec('text', discard=False),
- MacroTextSpec('textcolor', simplify_repl='%(3)s'),
- MacroTextSpec('colorbox', simplify_repl='%(3)s'),
- MacroTextSpec('fcolorbox', simplify_repl='%(5)s'),
-
] + [ MacroTextSpec(x, simplify_repl=y) for x, y in (
('title', lambda n, l2tobj: \
@@ -220,6 +216,10 @@ _latex_specs_approximations = {
lambda n, l2tobj: u'\n\n {}\n'.format(
l2tobj.node_arg_to_text(n, 2))),
+ ('textcolor', '%(3)s'),
+ ('colorbox', '%(3)s'),
+ ('fcolorbox', '%(5)s'),
+
('hspace', ''),
('vspace', '\n'),
@@ -232,6 +232,29 @@ _latex_specs_approximations = {
('frac', '%s/%s'),
('nicefrac', '%s/%s'),
('textfrac', '%s/%s'),
+
+ ('overline', '%s'),
+ ('underline', '%s'),
+ ('widehat', '%s'),
+ ('widetilde', '%s'),
+ ('wideparen', '%s'),
+ ('overleftarrow', '%s'),
+ ('overrightarrow', '%s'),
+ ('overleftrightarrow', '%s'),
+ ('underleftarrow', '%s'),
+ ('underrightarrow', '%s'),
+ ('underleftrightarrow', '%s'),
+ ('overbrace', '%s'),
+ ('underbrace', '%s'),
+ ('overgroup', '%s'),
+ ('undergroup', '%s'),
+ ('overbracket', '%s'),
+ ('underbracket', '%s'),
+ ('overlinesegment', '%s'),
+ ('underlinesegment', '%s'),
+ ('overleftharpoon', '%s'),
+ ('overrightharpoon', '%s'),
+
)],
}
diff --git a/pylatexenc/latexwalker/_defaultspecs.py b/pylatexenc/latexwalker/_defaultspecs.py
index <HASH>..<HASH> 100644
--- a/pylatexenc/latexwalker/_defaultspecs.py
+++ b/pylatexenc/latexwalker/_defaultspecs.py
@@ -95,7 +95,6 @@ specs = [
std_macro('emph', False, 1),
- std_macro('underline', False, 1),
MacroSpec('textrm',
args_parser=MacroStandardArgsParser('{', args_math_mode=[False])),
MacroSpec('textit',
@@ -178,6 +177,31 @@ specs = [
std_macro('sqrt', True, 1),
+ MacroSpec('overline', '{'),
+ MacroSpec('underline', '{'),
+ MacroSpec('widehat', '{'),
+ MacroSpec('widetilde', '{'),
+ MacroSpec('wideparen', '{'),
+ MacroSpec('overleftarrow', '{'),
+ MacroSpec('overrightarrow', '{'),
+ MacroSpec('overleftrightarrow', '{'),
+ MacroSpec('underleftarrow', '{'),
+ MacroSpec('underrightarrow', '{'),
+ MacroSpec('underleftrightarrow', '{'),
+ MacroSpec('overbrace', '{'),
+ MacroSpec('underbrace', '{'),
+ MacroSpec('overgroup', '{'),
+ MacroSpec('undergroup', '{'),
+ MacroSpec('overbracket', '{'),
+ MacroSpec('underbracket', '{'),
+ MacroSpec('overlinesegment', '{'),
+ MacroSpec('underlinesegment', '{'),
+ MacroSpec('overleftharpoon', '{'),
+ MacroSpec('overrightharpoon', '{'),
+
+ MacroSpec('xleftarrow', '[{'),
+ MacroSpec('xrightarrow', '[{'),
+
std_macro('ket', False, 1),
std_macro('bra', False, 1),
std_macro('braket', False, 2),
|
parsing support for some symbols & arrows
|
phfaist_pylatexenc
|
train
|
2431f2a26897d23c5ee4c355d706f16da592e7f8
|
diff --git a/lib/hammer_cli_katello/associating_commands.rb b/lib/hammer_cli_katello/associating_commands.rb
index <HASH>..<HASH> 100644
--- a/lib/hammer_cli_katello/associating_commands.rb
+++ b/lib/hammer_cli_katello/associating_commands.rb
@@ -28,6 +28,11 @@ module HammerCLIKatello
command_name 'add-repository'
associated_resource :repositories
+ def validate_options
+ super
+ validator.any(:option_repository_id, :option_repository_name).required
+ end
+
success_message _("The repository has been associated")
failure_message _("Could not add repository")
end
@@ -38,6 +43,11 @@ module HammerCLIKatello
command_name 'remove-repository'
associated_resource :repositories
+ def validate_options
+ super
+ validator.any(:option_repository_id, :option_repository_name).required
+ end
+
success_message _("The repository has been removed")
failure_message _("Could not remove repository")
end
|
fixes #<I> - content-view add-repository should require user to provide repo info
This commit addresses the issue that if the user was attempting to add
a repository to a content view, but did not specify the repository parameters,
the command would succeed indicating "The repository has been associated".
The update behavior is:
hammer> content-view add-repository --name zoo2 --organization-id 3
Could not add repository:
Error: At least one of options --repository-id, --repository is required
|
Katello_hammer-cli-katello
|
train
|
85de57f4c965d04294627d6f30184c6c44d8205b
|
diff --git a/Parser/NativeTest.php b/Parser/NativeTest.php
index <HASH>..<HASH> 100644
--- a/Parser/NativeTest.php
+++ b/Parser/NativeTest.php
@@ -7,11 +7,6 @@
namespace Essence\Dom\Parser;
-if ( !defined( 'ESSENCE_BOOTSTRAPPED' )) {
- require_once dirname( dirname( dirname( dirname( __FILE__ ))))
- . DIRECTORY_SEPARATOR . 'bootstrap.php';
-}
-
/**
|
Removed ugly inclusions in test files
|
essence_dom
|
train
|
a5cc9ff302bb643918927d88dca91b549ac7cfbf
|
diff --git a/rbd/rbd_test.go b/rbd/rbd_test.go
index <HASH>..<HASH> 100644
--- a/rbd/rbd_test.go
+++ b/rbd/rbd_test.go
@@ -226,6 +226,63 @@ func TestGetImageNames(t *testing.T) {
conn.Shutdown()
}
+func TestImageProperties(t *testing.T) {
+ conn, _ := rados.NewConn()
+ conn.ReadDefaultConfigFile()
+ conn.Connect()
+
+ poolname := GetUUID()
+ err := conn.MakePool(poolname)
+ require.NoError(t, err)
+
+ ioctx, err := conn.OpenIOContext(poolname)
+ require.NoError(t, err)
+
+ name := GetUUID()
+ reqSize := uint64(1024 * 1024 * 4) // 4MB
+ img, err := Create3(ioctx, name, reqSize,
+ RbdFeatureLayering|RbdFeatureStripingV2, 22, 4096, 2)
+ require.NoError(t, err)
+
+ err = img.Open()
+ require.NoError(t, err)
+
+ format, err := img.IsOldFormat()
+ assert.NoError(t, err)
+ assert.Equal(t, format, false)
+
+ size, err := img.GetSize()
+ assert.NoError(t, err)
+ assert.Equal(t, size, reqSize)
+
+ features, err := img.GetFeatures()
+ assert.NoError(t, err)
+ // compare features with the two requested ones
+ assert.Equal(t, features&(RbdFeatureLayering|RbdFeatureStripingV2),
+ RbdFeatureLayering|RbdFeatureStripingV2)
+
+ stripeUnit, err := img.GetStripeUnit()
+ assert.NoError(t, err)
+ assert.Equal(t, stripeUnit, uint64(4096))
+
+ stripeCount, err := img.GetStripeCount()
+ assert.NoError(t, err)
+ assert.Equal(t, stripeCount, uint64(2))
+
+ _, err = img.GetOverlap()
+ assert.NoError(t, err)
+
+ err = img.Close()
+ assert.NoError(t, err)
+
+ err = img.Remove()
+ assert.NoError(t, err)
+
+ ioctx.Destroy()
+ conn.DeletePool(poolname)
+ conn.Shutdown()
+}
+
func TestImageRename(t *testing.T) {
conn, _ := rados.NewConn()
conn.ReadDefaultConfigFile()
|
test/rbd: add tests for getting image properties
|
ceph_go-ceph
|
train
|
429d77ad9fca8a75f86dc45050aafb148196740f
|
diff --git a/messages/utils.py b/messages/utils.py
index <HASH>..<HASH> 100644
--- a/messages/utils.py
+++ b/messages/utils.py
@@ -25,20 +25,25 @@ def format_quote(text):
def new_message_email(sender, instance, signal,
subject_prefix=_(u'New Message: %(subject)s'),
- template_name="messages/new_message.html", *args, **kwargs):
+ template_name="messages/new_message.html",
+ default_protocol=None,
+ *args, **kwargs):
"""
This function sends an email and is called via Django's signal framework.
Optional arguments:
``template_name``: the template to use
``subject_prefix``: prefix for the email subject.
+ ``default_protocol``: default protocol in site URL passed to template
"""
+ if default_protocol is None:
+ default_protocol = getattr(settings, 'DEFAULT_HTTP_PROTOCOL', 'http')
if 'created' in kwargs and kwargs['created']:
try:
current_domain = Site.objects.get_current().domain
subject = subject_prefix % {'subject': instance.subject}
message = render_to_string(template_name, {
- 'site_url': 'http://%s' % current_domain,
+ 'site_url': '%s://%s' % (default_protocol, current_domain),
'message': instance,
})
if instance.recipient.email != "":
|
Added ability to override the default protocol in the site URL that is passed to the new message email with the setting DEFAULT_HTTP_PROTOCOL
|
arneb_django-messages
|
train
|
94add44bc6a5f31f31f44511a7287fd2720f496e
|
diff --git a/src/hello.js b/src/hello.js
index <HASH>..<HASH> 100644
--- a/src/hello.js
+++ b/src/hello.js
@@ -1241,13 +1241,13 @@ hello.utils.extend(hello.utils, {
if (options.height) {
var dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;
var height = screen.height || window.innerHeight || documentElement.clientHeight;
- options.top = parseInt((height - options.height) / 2, 10) + dualScreenTop;
+ options.top = (options.top)?options.top:parseInt((height - options.height) / 2, 10) + dualScreenTop;
}
if (options.width) {
var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;
var width = screen.width || window.innerWidth || documentElement.clientWidth;
- options.left = parseInt((width - options.width) / 2, 10) + dualScreenLeft;
+ options.left = (options.left)?options.left:parseInt((width - options.width) / 2, 10) + dualScreenLeft;
}
// Convert options into an array
|
popup top and left can be defined from options
|
MrSwitch_hello.js
|
train
|
f106974ba9a4d9938897975c7f8f460e371accdc
|
diff --git a/Qt.py b/Qt.py
index <HASH>..<HASH> 100644
--- a/Qt.py
+++ b/Qt.py
@@ -621,6 +621,7 @@ _misplaced_members = {
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
+ "QtCore.qInstallMessageHandler": "QtCore.qInstallMessageHandler",
},
"PyQt5": {
"QtCore.pyqtProperty": "QtCore.Property",
@@ -631,6 +632,7 @@ _misplaced_members = {
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
+ "QtCore.qInstallMessageHandler": "QtCore.qInstallMessageHandler",
},
"PySide": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
@@ -641,7 +643,7 @@ _misplaced_members = {
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
-
+ "QtCore.qInstallMsgHandler": "QtCore.qInstallMessageHandler",
},
"PyQt4": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
@@ -652,6 +654,7 @@ _misplaced_members = {
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
+ "QtCore.qInstallMsgHandler": "QtCore.qInstallMessageHandler",
}
}
diff --git a/tests.py b/tests.py
index <HASH>..<HASH> 100644
--- a/tests.py
+++ b/tests.py
@@ -151,6 +151,26 @@ def binding(binding):
return os.getenv("QT_PREFERRED_BINDING") == binding
+if binding("PyQt4") or binding("PySide"):
+ def ignoreQtMessageHandlerFactory(msgs):
+ def ictxtMgr(level, msg):
+ if msg.decode() in msgs:
+ return
+ sys.stderr.write("{0}\n".format(msg))
+ return ictxtMgr
+
+
+if binding("PyQt5") or binding("PySide2"):
+ def ignoreQtMessageHandlerFactory(msgs):
+ def ictxtMgr(level, context, msg):
+ if binding("PySide2"):
+ msg = msg.decode()
+ if msg in msgs:
+ return
+ sys.stderr.write("{0}\n".format(msg))
+ return ictxtMgr
+
+
def test_environment():
"""Tests require all bindings to be installed (except PySide on py3.5+)"""
@@ -203,15 +223,8 @@ def test_load_ui_mainwindow():
import sys
from Qt import QtWidgets, QtCompat, QtCore
- # Install a custom Qt Message handler to silence the qWarning
- def customHandler(mode, context, msg):
- # explicitly skip this one message
- if msg == 'QMainWindowLayout::count: ?':
- return
- err = QtCore.qFormatLogMessage(mode, context, msg)
- sys.stderr.write('{0}\n'.format(err))
-
- QtCore.qInstallMessageHandler(customHandler)
+ handler = ignoreQtMessageHandlerFactory(['QMainWindowLayout::count: ?'])
+ QtCore.qInstallMessageHandler(handler)
app = QtWidgets.QApplication(sys.argv)
win = QtWidgets.QMainWindow()
|
Create/install qmessage handlers for dealing with QWarnings
|
mottosso_Qt.py
|
train
|
f98106a3ec072f9bf8bb0d026d196e8a271f856f
|
diff --git a/c3po/__init__.py b/c3po/__init__.py
index <HASH>..<HASH> 100644
--- a/c3po/__init__.py
+++ b/c3po/__init__.py
@@ -1,3 +1,3 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
-__VERSION__ = "0.1.4"
+__VERSION__ = "0.1.5"
diff --git a/c3po/converters/po_ods.py b/c3po/converters/po_ods.py
index <HASH>..<HASH> 100644
--- a/c3po/converters/po_ods.py
+++ b/c3po/converters/po_ods.py
@@ -33,7 +33,7 @@ def _prepare_ods_columns(ods, trans_title_row):
ods.content.getColumn(0).setWidth(settings.NOTES_COLUMN_WIDTH)
-def _write_trans_into_ods(ods, languages, locale_root, po_files_path, po_filename):
+def _write_trans_into_ods(ods, languages, locale_root, po_files_path, po_filename, start_row):
"""
Write translations from po files into ods one file.
Assumes a dictionary structure <locale_root>/<lang>/<po_files_path>/<filename>.
@@ -45,11 +45,12 @@ def _write_trans_into_ods(ods, languages, locale_root, po_files_path, po_filenam
po_file = polib.pofile(lang_po_path)
for j, entry in enumerate(po_file):
# start from 3 column, 1 row
- ods.content.getCell(i+3, j+1).stringValue(entry.msgstr)
+ row = j+start_row
+ ods.content.getCell(i+3, row).stringValue(entry.msgstr)
if i % 2 == 1:
- ods.content.getCell(i+3, j+1).setCellColor(settings.ODD_COLUMN_BG_COLOR)
+ ods.content.getCell(i+3, row).setCellColor(settings.ODD_COLUMN_BG_COLOR)
else:
- ods.content.getCell(i+3, j+1).setCellColor(settings.EVEN_COLUMN_BG_COLOR)
+ ods.content.getCell(i+3, row).setCellColor(settings.EVEN_COLUMN_BG_COLOR)
def _write_row_into_ods(ods, sheet_no, row_no, row):
@@ -83,13 +84,14 @@ def po_to_ods(languages, locale_root, po_files_path, temp_file_path):
po_files = _get_all_po_filenames(locale_root, languages[0], po_files_path)
- i = 0
+ i = 1
for po_filename in po_files:
po_file_path = os.path.join(locale_root, languages[0], po_files_path, po_filename)
+ start_row = i
+
po = polib.pofile(po_file_path)
for entry in po:
- i += 1
meta = dict(entry.__dict__)
meta.pop('msgid', None)
meta.pop('msgstr', None)
@@ -104,7 +106,9 @@ def po_to_ods(languages, locale_root, po_files_path, temp_file_path):
ods.content.getCell(1, i).stringValue("'" + entry.msgid).setCellColor(settings.EVEN_COLUMN_BG_COLOR)
ods.content.getCell(2, i).stringValue(entry.msgstr).setCellColor(settings.ODD_COLUMN_BG_COLOR)
- _write_trans_into_ods(ods, languages, locale_root, po_files_path, po_filename)
+ i += 1
+
+ _write_trans_into_ods(ods, languages, locale_root, po_files_path, po_filename, start_row)
ods.save(temp_file_path)
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -5,7 +5,7 @@ from setuptools import setup
setup(
name='C3PO',
- version='0.1.4',
+ version='0.1.5',
packages=['c3po', 'c3po.conf', 'c3po.mod', 'c3po.converters'],
url='https://github.com/VorskiImagineering/C3PO',
license='MIT',
|
Fix bug with multiple files msgstrs wrong row no
|
VorskiImagineering_C3PO
|
train
|
cbf9e41c2de34349d513e1899d51849093f02b13
|
diff --git a/message/classes/api.php b/message/classes/api.php
index <HASH>..<HASH> 100644
--- a/message/classes/api.php
+++ b/message/classes/api.php
@@ -1798,21 +1798,7 @@ class api {
$members[] = $member;
}
- $transaction = $DB->start_delegated_transaction();
-
$DB->insert_records('message_conversation_members', $members);
-
- // Hash is usefull only for 1-to-1 convs, so we don't update null conversation hashes.
- if (isset($conversation->convhash)) {
- // Getting all conversation members to create a new hash.
- $newuserids = array_values($DB->get_records_menu(
- 'message_conversation_members', ['conversationid' => $convid], 'id', 'id, userid')
- );
-
- $conversation->convhash = helper::get_conversation_hash($newuserids);
- $DB->update_record('message_conversations', $conversation);
- }
- $transaction->allow_commit();
}
/**
@@ -1835,22 +1821,8 @@ class api {
list($useridcondition, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
$params['convid'] = $convid;
- $transaction = $DB->start_delegated_transaction();
-
$DB->delete_records_select('message_conversation_members',
"conversationid = :convid AND userid $useridcondition", $params);
-
- // Hash is usefull only for 1-to-1 convs, so we don't update null conversation hashes.
- if (isset($conversation->convhash)) {
- // Getting all conversation members to create a new hash.
- $newuserids = array_values($DB->get_records_menu(
- 'message_conversation_members', ['conversationid' => $convid], 'id', 'id, userid')
- );
-
- $conversation->convhash = helper::get_conversation_hash($newuserids);
- $DB->update_record('message_conversations', $conversation);
- }
- $transaction->allow_commit();
}
/**
|
MDL-<I> core_message: remove no longer needed code
We only allow the functionality of adding/removing
members on group conversations, which will never have
a conversation hash.
|
moodle_moodle
|
train
|
fed46146dfbe91e0fd0bda758a27628ffc82618b
|
diff --git a/Tests/Functional/Drivers/Queue/PhpAmqpLibDriverTest.php b/Tests/Functional/Drivers/Queue/PhpAmqpLibDriverTest.php
index <HASH>..<HASH> 100644
--- a/Tests/Functional/Drivers/Queue/PhpAmqpLibDriverTest.php
+++ b/Tests/Functional/Drivers/Queue/PhpAmqpLibDriverTest.php
@@ -251,6 +251,7 @@ class PhpAmqpLibDriverTest extends AbstractQueueDriverTest
$queueMessage->setTTL(rand(60, 600));
$queueMessage->setPriority(rand(0, 255));
$queueMessage->setMessageType(md5(rand(0, 255)));
+ $queueMessage->setPersistent(true);
$this->driver->send($queueMessage);
$this->consumer = $this->createConsumer();
@@ -259,6 +260,7 @@ class PhpAmqpLibDriverTest extends AbstractQueueDriverTest
$this->assertEquals($amqpMessage->get('expiration'), $queueMessage->getHeader('expiration'));
$this->assertEquals($amqpMessage->get('priority'), $queueMessage->getPriority());
$this->assertEquals($amqpMessage->get('type'), $queueMessage->getMessageType());
+ $this->assertEquals($amqpMessage->get('delivery_mode'), QueueMessage::DELIVERY_MODE_PERSISTENT);
};
$this->driver->consume($this->consumer->getName(), $this->queueName, $callback);
|
AMQP: Add extra header to inspect
|
smartboxgroup_integration-framework-bundle
|
train
|
0d8bc594b9e7477893798fe371babebb910d2667
|
diff --git a/stdeb/__init__.py b/stdeb/__init__.py
index <HASH>..<HASH> 100644
--- a/stdeb/__init__.py
+++ b/stdeb/__init__.py
@@ -1,6 +1,4 @@
-# setuptools is required for distutils.commands plugin we use
import logging
-import setuptools
__version__ = '0.4.3+git' # keep in sync with ../setup.py
log = logging.getLogger('stdeb')
diff --git a/stdeb/command/sdist_dsc.py b/stdeb/command/sdist_dsc.py
index <HASH>..<HASH> 100644
--- a/stdeb/command/sdist_dsc.py
+++ b/stdeb/command/sdist_dsc.py
@@ -1,7 +1,6 @@
-import setuptools, sys, os, shutil
-from setuptools import Command
-import pkg_resources
-pkg_resources.require('setuptools>=0.6b2')
+import sys, os, shutil
+
+from distutils.core import Command
from stdeb import log
from stdeb.util import expand_sdist_file, recursive_hardlink
|
remove runtime dependency on setuptools
|
astraw_stdeb
|
train
|
c8989a8ed97ad680ac94d08a581827f29b881430
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -8,16 +8,13 @@
'use strict';
var assert = require('assert');
+var set = require('set-value');
/**
- * Create a question asking function that only asks a question
- * if the answer is not found in the store or options force
- * the question.
- *
- * ```js
- * var ask = require('ask-once')(questions, store);
- * ```
+ * Returns a question-asking function that only asks a question
+ * if the answer is not already stored.
*
+ * @name askOnce
* @param {Object} `questions` Pass your instance of [question-cache] on the `questions` parameter.
* @param {Object} `store` Pass your instance of [data-store] on the `store` parameter.
* @return {Function} Function to use when asking questions.
@@ -28,63 +25,79 @@ function askOnce(questions, store) {
assert(typeof questions === 'object', 'Expected `questions` to be an instance of [question-cache] but got ' + (typeof questions));
assert(typeof store === 'object', 'Expected `store` to be an instance of [data-store] but got ' + (typeof store));
+
/**
* Ask a question only if the answer is not stored.
*
- * ```js
- * ask('username', function (err, answer) {
- * if (err) return console.error(err);
- * console.log(answer);
- * //=> doowb
- * });
- * ```
- *
+ * @name ask
* @param {String} `question` Key of the question in the questions cache to ask.
* @param {Object} `options` Options to control re-initializing the answer or forcing the question.
* @param {Function} `cb` Callback function with the `err` and `answer` parameters.
* @api public
- * @name ask
*/
- return function ask (question, options, cb) {
+ return function ask (key, options, cb) {
if (typeof options === 'function') {
cb = options;
options || {}
}
+
options = options || {};
+ var answer, previousAnswer;
- // `init: true` clear the answer from the store
if (options.init === true) {
- store.del(question);
+ previousAnswer = store.get(key);
+ // delete the store
+ store.del({force: true});
+ } else if (options.force === true) {
+ previousAnswer = store.get(key);
+ // delete the last answer
+ store.del(key);
+ } else {
+ // check to see if the answer is in the store
+ answer = store.get(key);
}
- // check to see if the answer is in the store
- var answer = store.get(question);
+ // if an answer (still) exists, return it
+ if (typeof answer !== 'undefined') {
+ return cb(null, answer);
+ }
- // if no answer in the store or if `force: true`
- // ask the question
- if (typeof answer === 'undefined' || options.force === true) {
+ // override the default answer with the prev answer
+ if (previousAnswer && questions.has(key)) {
+ defaults(key, previousAnswer, questions.get(key));
+ }
- // reset the default to the last answer the user gave
- if (options.force === true) {
- var q = questions.get(question);
- q.default = answer;
- }
+ questions.ask(key, function (err, answers) {
+ if (err) return cb(err);
- // ask the question
- return questions.ask(question, function (err, answers) {
- if (err) return cb(err);
- answer = answers[question];
+ // save answer to store
+ store.set(answers);
+ cb(null, answers);
+ });
+ };
+}
- // save answer to store
- store.set(question, answer);
- cb(null, answer);
- });
- }
+/**
+ * Update the `default` property of the given question or questions
+ * to be the previously stored value - if one exists.
+ *
+ * @param {String} `prop` Question key, may use dot notation.
+ * @param {any} `stored` Any stored value
+ * @param {String} `questions` Question(s) object
+ */
- // otherwise, return the stored answer
- cb(null, answer);
- };
+function defaults(prop, stored, questions) {
+ if (typeof questions !== 'object') return;
+ if (typeof stored === 'string') {
+ questions.default = stored;
+ } else {
+ for (var key in questions) {
+ if (key in questions && key in stored) {
+ questions[key].default = stored[key];
+ }
+ }
+ }
}
/**
|
update for latest changes in question-cache
|
doowb_ask-once
|
train
|
b467de525c7702efcad20510cc79425c74803769
|
diff --git a/examples/d3Choropleth/main.js b/examples/d3Choropleth/main.js
index <HASH>..<HASH> 100644
--- a/examples/d3Choropleth/main.js
+++ b/examples/d3Choropleth/main.js
@@ -8,6 +8,13 @@ require(['d3', 'choropleth'], function (d3, Choropleth) {
d3.tsv('unemployment.tsv', function (err, unemployment) {
choropleth.set('unemployment', unemployment);
+
+ setInterval(function () {
+ unemployment.forEach(function (d) {
+ d.rate = Math.random();
+ });
+ choropleth.set('unemployment', unemployment);
+ }, 2000);
});
setSizeFromDiv();
|
Added random data changing to choropleth
|
curran_model
|
train
|
6b3df9de629734a3c94b7afeacac47079c8da28e
|
diff --git a/packages/reactotron-app/App/Dialogs/FilterTimelineDialog.js b/packages/reactotron-app/App/Dialogs/FilterTimelineDialog.js
index <HASH>..<HASH> 100644
--- a/packages/reactotron-app/App/Dialogs/FilterTimelineDialog.js
+++ b/packages/reactotron-app/App/Dialogs/FilterTimelineDialog.js
@@ -38,7 +38,7 @@ const GROUPS = [
items: [
{ value: 'state.action.complete', text: 'Action' },
{ value: 'saga.task.complete', text: 'Saga' },
- { value: 'state.values.response', text: 'Subscription Changed' }
+ { value: 'state.values.change', text: 'Subscription Changed' }
]
}
]
|
Fix timeline filtering for 'Subscriptions Changed' (#<I>)
|
infinitered_reactotron
|
train
|
550464f211dcf181795da9f0008be1ed16772c1e
|
diff --git a/lib/rester/client/response.rb b/lib/rester/client/response.rb
index <HASH>..<HASH> 100644
--- a/lib/rester/client/response.rb
+++ b/lib/rester/client/response.rb
@@ -3,8 +3,9 @@ module Rester
class Response
def initialize(status, hash={})
@_status = status
- @_data = hash || {}
- _deep_freeze
+ @_data = hash.dup || {}
+ Utils.deep_freeze(@_data)
+ freeze
end
def successful?
@@ -28,17 +29,6 @@ module Rester
super
end
end
-
- def _deep_freeze(value=@_data)
- value.freeze
-
- case value
- when Hash
- value.values.each { |v| _deep_freeze(v) }
- when Array
- value.each { |v| _deep_freeze(v) }
- end
- end
end # Response
end # Client
end # Rester
\ No newline at end of file
diff --git a/lib/rester/utils.rb b/lib/rester/utils.rb
index <HASH>..<HASH> 100644
--- a/lib/rester/utils.rb
+++ b/lib/rester/utils.rb
@@ -65,6 +65,17 @@ module Rester
def underscore(str)
str.scan(/[A-Z][a-z]*/).map(&:downcase).join('_')
end
+
+ def deep_freeze(value)
+ value.freeze
+
+ case value
+ when Hash
+ value.values.each { |v| deep_freeze(v) }
+ when Array
+ value.each { |v| deep_freeze(v) }
+ end
+ end
end # Class methods
end # Utils
end # Rester
diff --git a/spec/rester/client/response_spec.rb b/spec/rester/client/response_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/rester/client/response_spec.rb
+++ b/spec/rester/client/response_spec.rb
@@ -12,7 +12,7 @@ module Rester
describe '#initalize' do
def frozen?(object)
- expect(object.frozen?).to be true if object.respond_to?(:frozen)
+ expect(object.frozen?).to be true if object.respond_to?(:frozen?)
case object
when Hash
|
[#<I>] Changes made from review comments
|
payout_rester
|
train
|
fd46859d7da45f3e1921c7ce09ab56d8cf0a0c61
|
diff --git a/dist/index.js b/dist/index.js
index <HASH>..<HASH> 100755
--- a/dist/index.js
+++ b/dist/index.js
@@ -191,6 +191,7 @@ var app = {
/* instanbul ignore next */
try {
if (!fs.statSync(rcFile).isDirectory()) {
+ /* instanbul ignore next */
app.vorpal.execSync('source ' + rcFile);
}
} catch (e) {
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100755
--- a/src/index.js
+++ b/src/index.js
@@ -190,6 +190,7 @@ const app = {
/* instanbul ignore next */
try {
if (!fs.statSync(rcFile).isDirectory()) {
+ /* instanbul ignore next */
app.vorpal.execSync(`source ${rcFile}`);
}
} catch (e) {
diff --git a/test/source.js b/test/source.js
index <HASH>..<HASH> 100755
--- a/test/source.js
+++ b/test/source.js
@@ -48,7 +48,10 @@ describe('source', function () {
});
it('should print msg when given a nonreadable file', function () {
- cash.source({file: 'nonreadable.txt'}).should.equal('-cash: nonreadable.txt: Permission denied\n');
+ // ShellJS's $.chmod() doesn't have good Windows support, so skip this test for now
+ if (process.platform !== 'win32') {
+ cash.source({file: 'nonreadable.txt'}).should.equal('-cash: nonreadable.txt: Permission denied\n');
+ }
});
it('should modify current environment', function () {
|
Skip one test for appveyor, since it's hard to test.
|
dthree_cash
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.