hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
---|---|---|---|---|
d8973922ac6d3bee82255e2b9703ad8c9fa68f71 | diff --git a/commands/args.go b/commands/args.go
index <HASH>..<HASH> 100644
--- a/commands/args.go
+++ b/commands/args.go
@@ -59,13 +59,28 @@ func (a *Args) Replace(executable, command string, params ...string) {
}
func (a *Args) Commands() []*cmd.Cmd {
- result := a.beforeChain
+ result := []*cmd.Cmd{}
+ appendFromChain := func(c *cmd.Cmd) {
+ if c.Name == "git" {
+ ga := []string{c.Name}
+ ga = append(ga, a.GlobalFlags...)
+ ga = append(ga, c.Args...)
+ result = append(result, cmd.NewWithArray(ga))
+ } else {
+ result = append(result, c)
+ }
+ }
+ for _, c := range a.beforeChain {
+ appendFromChain(c)
+ }
if !a.noForward {
result = append(result, a.ToCmd())
}
+ for _, c := range a.afterChain {
+ appendFromChain(c)
+ }
- result = append(result, a.afterChain...)
return result
}
diff --git a/commands/args_test.go b/commands/args_test.go
index <HASH>..<HASH> 100644
--- a/commands/args_test.go
+++ b/commands/args_test.go
@@ -119,3 +119,16 @@ func TestArgs_GlobalFlags_Replaced(t *testing.T) {
assert.Equal(t, "open", cmd.Name)
assert.Equal(t, []string{"-a", "http://example.com"}, cmd.Args)
}
+
+func TestArgs_GlobalFlags_BeforeAfterChain(t *testing.T) {
+ args := NewArgs([]string{"-c", "key=value", "-C", "dir", "status"})
+ args.Before("git", "remote", "add")
+ args.After("git", "clean")
+ args.After("echo", "done!")
+ cmds := args.Commands()
+ assert.Equal(t, 4, len(cmds))
+ assert.Equal(t, "git -c key=value -C dir remote add", cmds[0].String())
+ assert.Equal(t, "git -c key=value -C dir status", cmds[1].String())
+ assert.Equal(t, "git -c key=value -C dir clean", cmds[2].String())
+ assert.Equal(t, "echo done!", cmds[3].String())
+} | Propagate global git arguments to Before/After chains
This fixes `hub -C mydir merge <URL>` and other commands that might be
invoked with git global arguments by ensuring that those global
arguments are also fowarded to any accompanying `git` commands within
`Before()` and `After()` chains. | github_hub | train |
476da848fa7e601175bf2f3a49ecd59fa298c211 | diff --git a/src/Definition/Plugin/MutationFormResolverPlugin.php b/src/Definition/Plugin/MutationFormResolverPlugin.php
index <HASH>..<HASH> 100644
--- a/src/Definition/Plugin/MutationFormResolverPlugin.php
+++ b/src/Definition/Plugin/MutationFormResolverPlugin.php
@@ -116,7 +116,7 @@ class MutationFormResolverPlugin extends AbstractDefinitionPlugin
}
//try find the form using a related class
- if ($relatedClass && (!$formType || true === $formType)) {
+ if ($relatedClass && (!$formType || true === $formType) && $definition->getNode()) {
$bundleNamespace = ClassUtils::relatedBundleNamespace($relatedClass);
$nodeName = $endpoint->getType($definition->getNode())->getName();
$formClass = ClassUtils::applyNamingConvention( | Fix mutation form resolver for mutation not related to specific node | ynloultratech_graphql-bundle | train |
7f0ea55d67f07b20dda5e7591e6b348bf5c7c3fd | diff --git a/master/buildbot/process/buildstep.py b/master/buildbot/process/buildstep.py
index <HASH>..<HASH> 100644
--- a/master/buildbot/process/buildstep.py
+++ b/master/buildbot/process/buildstep.py
@@ -123,9 +123,6 @@ class RemoteCommand(pb.Referenceable):
# Allow use of WithProperties in logfile path names.
cmd_args = self.args
- if cmd_args.has_key("logfiles") and cmd_args["logfiles"]:
- cmd_args = cmd_args.copy()
- cmd_args["logfiles"] = self.step.build.render(cmd_args["logfiles"])
# This method only initiates the remote command.
# We will receive remote_update messages as the command runs.
@@ -1089,6 +1086,8 @@ class LoggingBuildStep(BuildStep):
parms = BuildStep.parms + ['logfiles', 'lazylogfiles', 'log_eval_func']
cmd = None
+ renderables = [ 'logfiles', 'lazylogfiles' ]
+
def __init__(self, logfiles={}, lazylogfiles=False, log_eval_func=None,
*args, **kwargs):
BuildStep.__init__(self, *args, **kwargs) | Properly handle rendering of logfiles. | buildbot_buildbot | train |
932617495d67d3d24bfcc4d14409d1a5f677206a | diff --git a/packages/driver/src/cypress/browser.js b/packages/driver/src/cypress/browser.js
index <HASH>..<HASH> 100644
--- a/packages/driver/src/cypress/browser.js
+++ b/packages/driver/src/cypress/browser.js
@@ -1,29 +1,26 @@
-/*
- * decaffeinate suggestions:
- * DS102: Remove unnecessary code created because of implicit returns
- * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
- */
-const _ = require("lodash");
-const $utils = require("./utils");
+const _ = require('lodash')
+const $utils = require('./utils')
-const isBrowser = function(config, obj='') {
+const isBrowser = function (config, obj = '') {
if (_.isString(obj)) {
- const name = obj.toLowerCase();
- const currentName = config.browser.name.toLowerCase();
+ const name = obj.toLowerCase()
+ const currentName = config.browser.name.toLowerCase()
- return name === currentName;
+ return name === currentName
}
if (_.isObject(obj)) {
- return _.isMatch(config.browser, obj);
+ return _.isMatch(config.browser, obj)
}
- return $utils.throwErrByPath("browser.invalid_arg", {
- args: { method: 'isBrowser', obj: $utils.stringify(obj) }
- });
-};
+ $utils.throwErrByPath('browser.invalid_arg', {
+ args: { method: 'isBrowser', obj: $utils.stringify(obj) },
+ })
+}
-module.exports = config => ({
- browser: config.browser,
- isBrowser: _.partial(isBrowser, config)
-});
+module.exports = (config) => {
+ return {
+ browser: config.browser,
+ isBrowser: _.partial(isBrowser, config),
+ }
+} | decaffeinate: Run post-processing cleanups on browser.coffee | cypress-io_cypress | train |
009098e1c1dab11529ab4d9c1c85cdac106dfa97 | diff --git a/src/Log/Handler/SlackHandler.php b/src/Log/Handler/SlackHandler.php
index <HASH>..<HASH> 100644
--- a/src/Log/Handler/SlackHandler.php
+++ b/src/Log/Handler/SlackHandler.php
@@ -3,6 +3,7 @@ namespace GMO\Common\Log\Handler;
use GMO\Common\Log\Formatter\SlackFormatter;
use GMO\Common\Str;
+use Monolog\Formatter\LineFormatter;
use Monolog\Handler\SlackHandler as SlackHandlerBase;
use Monolog\Logger;
@@ -13,6 +14,9 @@ use Monolog\Logger;
*/
class SlackHandler extends SlackHandlerBase {
+ /** @var LineFormatter */
+ private $lineFormatter;
+
/**
* @param string $token Slack API token
* @param string $channel Slack channel/user (encoded ID or name)
@@ -46,6 +50,7 @@ class SlackHandler extends SlackHandlerBase {
$useShortAttachment,
$includeContextAndExtra
);
+ $this->lineFormatter = new LineFormatter();
}
/**
@@ -114,4 +119,22 @@ class SlackHandler extends SlackHandlerBase {
$data['attachments'] = json_encode($data['attachments']);
return $data;
}
+
+ /**
+ * Stringifies an array of key/value pairs to be used in attachment fields
+ *
+ * @param array $fields
+ * @return string
+ */
+ protected function stringify($fields)
+ {
+ $string = '';
+ foreach ($fields as $var => $val) {
+ $string .= $var.': '.$this->lineFormatter->stringify($val)." | ";
+ }
+
+ $string = rtrim($string, " |");
+
+ return $string;
+ }
} | Fix slack handler having object conditionally defined on parent | gmo_common | train |
3c3a2e680796e84c6229b9a6115e9e07e10437c1 | diff --git a/irc3/plugins/storage.py b/irc3/plugins/storage.py
index <HASH>..<HASH> 100644
--- a/irc3/plugins/storage.py
+++ b/irc3/plugins/storage.py
@@ -35,6 +35,8 @@ Usage::
Then use it::
>>> bot.db['mykey'] = dict(key='value')
+ >>> 'mykey' in bot.db
+ True
>>> bot.db['mykey']
{'key': 'value'}
>>> bot.db.setdefault('mykey', key='default')
@@ -47,6 +49,8 @@ Then use it::
>>> del bot.db['mykey']
>>> bot.db['mykey']
{}
+ >>> 'mykey' in bot.db
+ False
You can use an instance as key::
@@ -109,7 +113,7 @@ Api
===
.. autoclass:: Storage
- :members: __getitem__, __setitem__, set, setdefault
+ :members: __getitem__, __setitem__, __contains__, set, setdefault
'''
@@ -131,6 +135,9 @@ class Shelve(object):
del self.db[key]
self.sync()
+ def contains(self, key):
+ return key in self.db
+
def sync(self):
self.db.sync()
@@ -159,6 +166,9 @@ class JSON(object):
del self.db[key]
self.sync()
+ def contains(self, key):
+ return key in self.db
+
def sync(self):
with open(self.filename, 'w') as fd:
json.dump(self.db, fd, indent=2, sort_keys=True)
@@ -193,6 +203,9 @@ class Redis(object):
def delete(self, key):
self.db.delete(key)
+ def contains(self, key):
+ return self.db.exists(key)
+
def flushdb(self):
self.db.flushdb()
@@ -280,5 +293,13 @@ class Storage(object):
self.context.log.exception(e)
raise
+ def __contains__(self, key):
+ key = getattr(key, '__module___', key)
+ try:
+ return self.backend.contains(key)
+ except Exception as e: # pragma: no cover
+ self.context.log.exception(e)
+ raise
+
def SIGINT(self):
self.backend.close() | improve storage: can test the existence of a key | gawel_irc3 | train |
630503c12534cb2218c863f3a52b95dd1f936b80 | diff --git a/codenerix/models.py b/codenerix/models.py
index <HASH>..<HASH> 100644
--- a/codenerix/models.py
+++ b/codenerix/models.py
@@ -342,6 +342,10 @@ if not (hasattr(settings, "PQPRO_CASSANDRA") and settings.PQPRO_CASSANDRA):
class CodenerixMeta(CodenerixModel.CodenerixMeta):
log_full = False
+ def post_save(self, log):
+ # custom post save from application
+ pass
+
def save(self, **kwargs):
user = get_current_user()
if user:
@@ -415,7 +419,7 @@ if not (hasattr(settings, "PQPRO_CASSANDRA") and settings.PQPRO_CASSANDRA):
attrs[key] = (attrs_bd[key].pk, field, )
else:
attrs[key] = (attrs_bd[key], field, )
- except:
+ except Exception:
# If related, we don't do anything
if getattr(field, 'all', None) is None:
field = str(field)
@@ -473,6 +477,10 @@ if not (hasattr(settings, "PQPRO_CASSANDRA") and settings.PQPRO_CASSANDRA):
# if new element, get pk
log.object_id = self.pk
log.save()
+
+ # custom post save from application
+ self.post_save(log)
+
return aux
class GenLogFull(GenLog): | Custom post save from application in GenLog | codenerix_django-codenerix | train |
c4b7e47b921c56d1204b423838eb4482d73ebe55 | diff --git a/src/EventListener/GeneralListener.php b/src/EventListener/GeneralListener.php
index <HASH>..<HASH> 100644
--- a/src/EventListener/GeneralListener.php
+++ b/src/EventListener/GeneralListener.php
@@ -41,9 +41,15 @@ class GeneralListener implements EventSubscriberInterface
$request = $event->getRequest();
$this->resumeSession($request);
+ $this->updateWhoops($event);
$this->mailConfigCheck($request);
}
+ /**
+ * Kernel response listener callback.
+ *
+ * @param FilterResponseEvent $event
+ */
public function onResponse(FilterResponseEvent $event)
{
$request = $event->getRequest();
@@ -63,12 +69,31 @@ class GeneralListener implements EventSubscriberInterface
*/
protected function resumeSession(Request $request)
{
- if ($request->cookies->has('bolt_session')) {
+ if ($request->cookies->has('bolt_session') && !$this->app['session']->isStarted()) {
$this->app['session']->start();
}
}
/**
+ * Remove the listener for Whoops if not required.
+ *
+ * @param GetResponseEvent $event
+ */
+ protected function updateWhoops(GetResponseEvent $event)
+ {
+ if (!$event->isMasterRequest()) {
+ return;
+ }
+
+ $noUser = $this->app['session']->isStarted() && $this->app['session']->has('user') ? false : true;
+ $showAlways = $this->app['config']->get('general/debug_show_loggedoff', false);
+
+ if ($noUser && !$showAlways) {
+ $event->getDispatcher()->removeListener(KernelEvents::EXCEPTION, array($this->app['listener.whoops'], 'onKernelException'));
+ }
+ }
+
+ /**
* No Mail transport has been set. We should gently nudge the user to set
* the mail configuration.
* | Remove the Whoops exception event when the user isn't logged in and
debug_show_loggedoff is false | bolt_bolt | train |
53e275b237bfdca01782c338462ea4eff2576e4f | diff --git a/code/services/QueuedJobService.php b/code/services/QueuedJobService.php
index <HASH>..<HASH> 100644
--- a/code/services/QueuedJobService.php
+++ b/code/services/QueuedJobService.php
@@ -261,7 +261,6 @@ class QueuedJobService
$job->prepareForRestart();
}
-
// make sure the descriptor is up to date with anything changed
$this->copyJobToDescriptor($job, $jobDescriptor);
@@ -371,6 +370,7 @@ class QueuedJobService
// okay, we'll just catch this exception for now
SS_Log::log($e, SS_Log::ERR);
$jobDescriptor->JobStatus = QueuedJob::STATUS_BROKEN;
+ $jobDescriptor->write();
}
$errorHandler->clear(); | Added additional call to 'write' after setting broken job | symbiote_silverstripe-queuedjobs | train |
d701847ba4defaf215824e449f67a4a2df5769b3 | diff --git a/README.rst b/README.rst
index <HASH>..<HASH> 100644
--- a/README.rst
+++ b/README.rst
@@ -7,7 +7,6 @@ interface that queries the server and returns results based on the query.
.. _`Apache Solr`: http://lucene.apache.org/solr/
-
Status
======
@@ -64,12 +63,21 @@ Basic usage looks like:
{
"id": "doc_2",
"title": "The Banana: Tasty or Dangerous?",
+ "_doc": [
+ { "id": "child_doc_1", "title": "peel" },
+ { "id": "child_doc_2", "title": "seed" },
+ ]
},
])
# Note that the add method has commit=True by default, so this is
# immediately committed to your index.
+ # You can index a parent/child document relationship by
+ # associating a list of child documents with the special key '_doc'. This
+ # is helpful for queries that join together conditions on children and parent
+ # documents.
+
# Later, searching is easy. In the simple case, just a plain Lucene-style
# query is fine.
results = solr.search('bananas')
diff --git a/pysolr.py b/pysolr.py
index <HASH>..<HASH> 100644
--- a/pysolr.py
+++ b/pysolr.py
@@ -824,6 +824,11 @@ class Solr(object):
if self._is_null_value(bit):
continue
+ if key == '_doc':
+ child = self._build_doc(bit, boost)
+ doc_elem.append(child)
+ continue
+
attrs = {'name': key}
if fieldUpdates and key in fieldUpdates:
diff --git a/tests/test_client.py b/tests/test_client.py
index <HASH>..<HASH> 100644
--- a/tests/test_client.py
+++ b/tests/test_client.py
@@ -544,6 +544,37 @@ class SolrTestCase(unittest.TestCase):
self.assertTrue('<field name="id">doc_1</field>' in doc_xml)
self.assertEqual(len(doc_xml), 152)
+ def test__build_doc_with_sub_docs(self):
+ sub_docs = [
+ {
+ 'id': 'sub_doc_1',
+ 'title': 'Example sub doc ☃ 1',
+ 'price': 1.59,
+ 'popularity': 4
+ },
+ {
+ 'id': 'sub_doc_2',
+ 'title': 'Example sub doc ☃ 2',
+ 'price': 21.13,
+ 'popularity': 1
+ },
+ ]
+ doc = {
+ 'id': 'doc_1',
+ 'title': 'Example doc ☃ 1',
+ 'price': 12.59,
+ 'popularity': 10,
+ '_doc': sub_docs
+ }
+ doc_xml = self.solr._build_doc(doc)
+ self.assertEqual(doc_xml.find("*[@name='id']").text, doc['id'])
+
+ children_docs = doc_xml.findall('doc')
+ self.assertEqual(len(children_docs), len(sub_docs))
+
+ self.assertEqual(children_docs[0].find("*[@name='id']").text, sub_docs[0]['id'])
+ self.assertEqual(children_docs[1].find("*[@name='id']").text, sub_docs[1]['id'])
+
def test_add(self):
self.assertEqual(len(self.solr.search('doc')), 3)
self.assertEqual(len(self.solr.search('example')), 2) | Support for nested documents (closes #<I>) | django-haystack_pysolr | train |
524c274551215af01c2f4b53a50ceead6b1498e3 | diff --git a/climlab/model/ebm.py b/climlab/model/ebm.py
index <HASH>..<HASH> 100644
--- a/climlab/model/ebm.py
+++ b/climlab/model/ebm.py
@@ -30,18 +30,18 @@ def global_mean(field, lat_radians):
class NewEBM(EnergyBudget):
- def __init__(self,
+ def __init__(self,
num_points=90,
- A = 210.,
- B = 2.,
- D=0.555, # in W / m^2 / degC, same as B
- Tf = -10.0,
+ A=210.,
+ B=2.,
+ D=0.555, # in W / m^2 / degC, same as B
+ Tf=-10.0,
water_depth=10.0,
timestep=1. * const.seconds_per_day,
**kwargs):
super(NewEBM, self).__init__(timestep=timestep, **kwargs)
if not self.domains and not self.state: # no state vars or domains yet
- sfc = domain.zonal_mean_surface(num_points=num_points,
+ sfc = domain.zonal_mean_surface(num_points=num_points,
water_depth=water_depth)
lat = sfc.axes['lat'].points
initial = 12. - 40. * legendre.P2(np.sin(np.deg2rad(lat)))
@@ -65,8 +65,11 @@ class NewEBM(EnergyBudget):
def _compute_heating_rates(self):
'''Compute energy flux convergences to get heating rates in W / m**2.
This method should be over-ridden by daughter classes.'''
- self.heating_rate['Ts'] = self.subprocess['insolation'].diagnostics['insolation']
-
+ insolation = self.subprocess['insolation'].diagnostics['insolation']
+ albedo = self.subprocess['albedo'].diagnostics['albedo']
+ ASR = (1-albedo) * insolation
+ self.heating_rate['Ts'] = ASR
+ self.diagnostics['ASR'] = ASR
# lots of work to do here.
# need to figure out a better way to deal with params
diff --git a/climlab/radiation/insolation.py b/climlab/radiation/insolation.py
index <HASH>..<HASH> 100644
--- a/climlab/radiation/insolation.py
+++ b/climlab/radiation/insolation.py
@@ -1,4 +1,5 @@
from climlab.process.diagnostic import DiagnosticProcess
+from climlab.domain.field import Field
from climlab.utils.legendre import P2
from climlab import constants as const
import numpy as np
@@ -14,10 +15,10 @@ class _Insolation(DiagnosticProcess):
'''Parent class for insolation processes.
Calling compute() will update self.diagnostics['insolation']
with current insolation values.'''
-
+
def _get_current_insolation(self):
pass
-
+
def compute(self):
'''Update all diagnostic quantities using current model state.'''
self._get_current_insolation()
@@ -27,10 +28,12 @@ class FixedInsolation(_Insolation):
def __init__(self, **kwargs):
super(FixedInsolation, self).__init__(**kwargs)
self.diagnostics['insolation'] = self.param['Q']
+
def _get_current_insolation(self):
self.diagnostics['insolation'] = self.param['Q']
# since this is fixed, could also just assign it in __init__
+
class P2Insolation(_Insolation):
def __init__(self, S0=const.S0, s2=-0.48, **kwargs):
super(P2Insolation, self).__init__(**kwargs)
@@ -42,8 +45,11 @@ class P2Insolation(_Insolation):
self.param['s2'] = s2
lat = self.domains['default'].axes['lat'].points
phi = np.deg2rad(lat)
- self.diagnostics['insolation'] = self.param['S0'] / 4 * (1. +
- self.param['s2'] * P2(np.sin(phi)))
-
+ insolation = (self.param['S0'] / 4 *
+ (1. + self.param['s2'] * P2(np.sin(phi))))
+ # make sure that the diagnostic has the correct field dimensions.
+ dom = self.domains['default']
+ self.diagnostics['insolation'] = Field(insolation, domain=dom)
+
def _get_current_insolation(self):
pass
\ No newline at end of file
diff --git a/climlab/surface/albedo.py b/climlab/surface/albedo.py
index <HASH>..<HASH> 100644
--- a/climlab/surface/albedo.py
+++ b/climlab/surface/albedo.py
@@ -3,7 +3,7 @@ import numpy as np
class StepFunctionAlbedo(DiagnosticProcess):
- def __init__(self, Tf=-10., albedo_noice=0.3, albedo_ice=0.6, **kwargs):
+ def __init__(self, Tf=-10., albedo_noice=0.33, albedo_ice=0.6, **kwargs):
super(DiagnosticProcess, self).__init__(**kwargs)
self.param['Tf'] = Tf
self.time_type = 'diagnostic' | Fixed bug with P2Insolation (not returning correct field size). Now have a working EBM! | brian-rose_climlab | train |
ff6683d3197d9c38fef69387f75aa186b11fc77b | diff --git a/app/Console/Install.php b/app/Console/Install.php
index <HASH>..<HASH> 100644
--- a/app/Console/Install.php
+++ b/app/Console/Install.php
@@ -34,7 +34,7 @@ class Install extends Command
$this->comment('**********************************************');
$this->comment('');
- if ($this->option('force') || $this->confirm('Would you like to run your database migrations?', 'yes')) {
+ if ($this->option('force') || $this->confirm('Would you like to run your database migrations (make sure you have a database created)?', 'yes')) {
(new Process('php artisan migrate', base_path()))->setTimeout(null)->run();
} | - Menssage: database created for execute migration | alfredoem_ragnarok | train |
5a655d5a1380c24aae65085cd9b629942aa6cf8d | diff --git a/java/org/gem/hdf5/HDF5Util.java b/java/org/gem/hdf5/HDF5Util.java
index <HASH>..<HASH> 100644
--- a/java/org/gem/hdf5/HDF5Util.java
+++ b/java/org/gem/hdf5/HDF5Util.java
@@ -90,7 +90,11 @@ public class HDF5Util
long[] maxDims = dataset.getMaxDims();
long[] selectedDims = dataset.getSelectedDims();
- // copy maxDims to selectedDims, then read the data
+ // Copy maxDims to selectedDims, then read the data.
+ // Note: selectedDims is a reference to the dataset's `selectedDims`
+ // member. Changing the content selectedDims will have an affect
+ // on the subsequent dataset.getData() call. If we don't do this,
+ // we'll only extract a subset of the data.
for (int i = 0; i < maxDims.length; i++)
{
selectedDims[i] = maxDims[i]; | Added some comments to a slightly obscure bit of code | gem_oq-engine | train |
f66687eef948693acf9f77fa2b7e6889851af6a8 | diff --git a/common/src/main/java/com/groupbyinc/api/AbstractQuery.java b/common/src/main/java/com/groupbyinc/api/AbstractQuery.java
index <HASH>..<HASH> 100755
--- a/common/src/main/java/com/groupbyinc/api/AbstractQuery.java
+++ b/common/src/main/java/com/groupbyinc/api/AbstractQuery.java
@@ -245,8 +245,9 @@ public abstract class AbstractQuery<R extends AbstractRequest<R>, Q extends Abst
* <code>
* The collection to use. If you have uploaded additional data into collections apart from the default
* collection using the stream tool, you can access them by specifying them here.
- * You can also search across multiple collections. To search across FAQs and Manuals you would do
- * "FAQs|Manuals"
+ * You can also search across multiple collections. It is important to note that relevancy is affected across
+ * collections and it is recommended that collections be modeled so that cross-collection searching is not required.
+ * As an example, to search across FAQs and Manuals you would use "FAQs|Manuals".
* JSON Reference:
* { "collection": "FAQs" }
* { "collection": "FAQs|Manuals" } | update docs regarding cross-collection searching and relevancy | groupby_api-java | train |
0f071fd2dbbbb5eb7efccc16a8121eb22ebabf12 | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -17,7 +17,6 @@ with open("README.md") as readme_file:
long_description = readme_file.read()
tests_require = [
- "mock>=1.0.1",
"nose>=1.3.3",
"vcrpy>=1.10.3",
] | Remove mock from tests_require and test extra | tweepy_tweepy | train |
893cf78eeb6df36928b986eae5d6fab29ba6145f | diff --git a/src/model/RootModel.js b/src/model/RootModel.js
index <HASH>..<HASH> 100755
--- a/src/model/RootModel.js
+++ b/src/model/RootModel.js
@@ -160,7 +160,7 @@ function attachImplicits(model, fragment) {
// look for virtual children to relink and cascade
for (const k in model.childByKey) {
- if (k in model.value) {
+ if (model.value != null && k in model.value) {
attachImplicits(model.childByKey[k], fragment);
} else if (!model.childByKey[k]._link || model.childByKey[k]._link.isDetached()) {
const mdl = resolveReference(fragment, k);
diff --git a/tests/browser/methods/attachChild.js b/tests/browser/methods/attachChild.js
index <HASH>..<HASH> 100644
--- a/tests/browser/methods/attachChild.js
+++ b/tests/browser/methods/attachChild.js
@@ -607,4 +607,26 @@ export default function() {
}, 14);
}, 14);
});
+
+ test(`attaching a non-isolated child with undefined data should not throw (#3276)`, t => {
+ const r = new Ractive({
+ template: '<#anchor />',
+ target: fixture
+ });
+
+ const cmp = new Ractive({
+ template: '{{baz}}',
+ data: { foo: undefined },
+ computed: {
+ baz() {
+ return this.get('foo.bar');
+ }
+ },
+ isolated: false
+ });
+
+ r.attachChild(cmp, { target: 'anchor' });
+
+ t.equal(fixture.innerHTML, '');
+ });
} | verify model value exists before checking for keys when attaching implicits - fixes #<I> | ractivejs_ractive | train |
74a5a0a077b558501e83c8e9e070e637bbec23da | diff --git a/indra/assemblers/pysb_assembler.py b/indra/assemblers/pysb_assembler.py
index <HASH>..<HASH> 100644
--- a/indra/assemblers/pysb_assembler.py
+++ b/indra/assemblers/pysb_assembler.py
@@ -13,6 +13,7 @@ import pysb.export
from indra import statements as ist
from indra.databases import context_client
from indra.preassembler.hierarchy_manager import entity_hierarchy as enth
+from indra.tools.expand_families import _agent_from_uri
# Python 2
try:
@@ -250,7 +251,19 @@ mod_acttype_map = {
def get_binding_site_name(agent):
"""Return a binding site name from a given agent."""
- #component = enth.components.get(agent.name)
+ # Try to construct a binding site name based on parent
+ grounding = agent.get_grounding()
+ if grounding != (None, None):
+ uri = enth.get_uri(grounding[0], grounding[1])
+ # Get highest level parents in hierarchy
+ parents = enth.get_parents(uri, 'top')
+ if parents:
+ # Choose the first parent if there are more than one
+ parent_uri = sorted(list(parents))[0]
+ parent_agent = _agent_from_uri(parent_uri)
+ binding_site = _n(parent_agent.name).lower()
+ return binding_site
+ # Fall back to Agent's own name if one from parent can't be constructed
binding_site = _n(agent.name).lower()
return binding_site
@@ -1162,8 +1175,8 @@ def modification_monomers_two_step(stmt, agent_set):
stmt.residue, stmt.position))
# Create site for binding the substrate
- enz.create_site(get_binding_site_name(sub))
- sub.create_site(get_binding_site_name(enz))
+ enz.create_site(get_binding_site_name(stmt.sub))
+ sub.create_site(get_binding_site_name(stmt.enz))
def modification_assemble_interactions_only(stmt, model, agent_set):
@@ -1325,8 +1338,8 @@ def phosphorylation_monomers_atp_dependent(stmt, agent_set):
sub.create_mod_site(ist.ModCondition('phosphorylation',
stmt.residue, stmt.position))
# Create site for binding the substrate
- enz.create_site(get_binding_site_name(sub))
- sub.create_site(get_binding_site_name(enz))
+ enz.create_site(get_binding_site_name(stmt.sub))
+ sub.create_site(get_binding_site_name(stmt.enz))
# Make ATP base agent and create binding sites
atp = agent_set.get_create_base_agent(ist.Agent('ATP'))
@@ -1480,8 +1493,8 @@ def demodification_monomers_two_step(stmt, agent_set):
sub.create_mod_site(ist.ModCondition(mod_condition_name,
stmt.residue, stmt.position))
# Create site for binding the substrate
- enz.create_site(get_binding_site_name(sub))
- sub.create_site(get_binding_site_name(enz))
+ enz.create_site(get_binding_site_name(stmt.sub))
+ sub.create_site(get_binding_site_name(stmt.enz))
def demodification_assemble_interactions_only(stmt, model, agent_set):
@@ -2055,8 +2068,8 @@ def degradation_monomers_interactions_only(stmt, agent_set):
return
subj = agent_set.get_create_base_agent(stmt.subj)
obj = agent_set.get_create_base_agent(stmt.obj)
- subj.create_site(get_binding_site_name(obj))
- obj.create_site(get_binding_site_name(subj))
+ subj.create_site(get_binding_site_name(stmt.obj))
+ obj.create_site(get_binding_site_name(stmt.subj))
def degradation_monomers_one_step(stmt, agent_set):
obj = agent_set.get_create_base_agent(stmt.obj)
@@ -2076,13 +2089,13 @@ def degradation_assemble_interactions_only(stmt, model, agent_set):
rule_obj_str = get_agent_rule_str(stmt.obj)
rule_name = '%s_degrades_%s' % (rule_subj_str, rule_obj_str)
- subj_site_name = get_binding_site_name(obj_base_agent)
- obj_site_name = get_binding_site_name(subj_base_agent)
+ subj_site_name = get_binding_site_name(stmt.obj)
+ obj_site_name = get_binding_site_name(stmt.subj)
r = Rule(rule_name,
- subj(**{subj_site_name: None}) + obj(**{obj_site_name: None}) >>
- subj(**{subj_site_name: 1}) + obj(**{obj_site_name: 1}),
- kf_bind)
+ subj(**{subj_site_name: None}) + obj(**{obj_site_name: None}) >>
+ subj(**{subj_site_name: 1}) + obj(**{obj_site_name: 1}),
+ kf_bind)
add_rule_to_model(model, r)
def degradation_assemble_one_step(stmt, model, agent_set):
@@ -2133,8 +2146,8 @@ def synthesis_assemble_interactions_only(stmt, model, agent_set):
rule_obj_str = get_agent_rule_str(stmt.obj)
rule_name = '%s_synthesizes_%s' % (rule_subj_str, rule_obj_str)
- subj_site_name = get_binding_site_name(obj_base_agent)
- obj_site_name = get_binding_site_name(subj_base_agent)
+ subj_site_name = get_binding_site_name(stmt.obj)
+ obj_site_name = get_binding_site_name(stmt.subj)
r = Rule(rule_name,
subj(**{subj_site_name: None}) + obj(**{obj_site_name: None}) >> | Get top-level parent to construct binding site | sorgerlab_indra | train |
41cfabaa4aa3ff529a8bc2c6f50c5686b1430158 | diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -39,7 +39,7 @@ func main() {
IN nodes
FILTER n._key == %s
RETURN n
- `, key).Run(db)
+ `, key).Cache(true).Run(db) // The caching feature is unavailable prior to ArangoDB 2.7
if err != nil {
panic(err)
diff --git a/query.go b/query.go
index <HASH>..<HASH> 100644
--- a/query.go
+++ b/query.go
@@ -10,7 +10,8 @@ import (
// Query represents an AQL query.
type Query struct {
- aql string
+ aql string
+ cache bool
}
// NewQuery returns a new Query object.
@@ -21,6 +22,13 @@ func NewQuery(aql string, params ...interface{}) *Query {
return &Query{aql: aql}
}
+// Cache enables/disables the caching of the query.
+// Unavailable prior to ArangoDB 2.7
+func (q *Query) Cache(enable bool) *Query {
+ q.cache = enable
+ return q
+}
+
// Run executes the Query into the database passed as argument.
func (q *Query) Run(db *DB) ([]byte, error) {
if db == nil {
@@ -59,9 +67,10 @@ func (q *Query) Run(db *DB) ([]byte, error) {
func generateQuery(q *Query) []byte {
type QueryFmt struct {
Query string `json:"query"`
+ Cache bool `json:"cache"`
}
- jsonQuery, _ := json.Marshal(&QueryFmt{Query: q.aql})
+ jsonQuery, _ := json.Marshal(&QueryFmt{Query: q.aql, Cache: q.cache})
return jsonQuery
}
diff --git a/query_test.go b/query_test.go
index <HASH>..<HASH> 100644
--- a/query_test.go
+++ b/query_test.go
@@ -40,7 +40,7 @@ func TestQueryRun(t *testing.T) {
httpmock.RegisterResponder("POST", "http://arangodb:8000/_db/dbName/_api/cursor",
httpmock.NewStringResponder(200, `{"error": false, "errorMessage": "", "result": "[]"}`))
- result, err = NewQuery(shortQuery).Run(nil)
+ result, err = NewQuery(shortQuery).Cache(true).Run(nil)
r.Error(err)
a.Nil(result) | Caching feature added. Waiting for ArangoDB <I>... | solher_arangolite | train |
969fb6c8062859a7947271859af682d62cb776c8 | diff --git a/src/Listener/ApiListener.php b/src/Listener/ApiListener.php
index <HASH>..<HASH> 100644
--- a/src/Listener/ApiListener.php
+++ b/src/Listener/ApiListener.php
@@ -124,10 +124,13 @@ class ApiListener extends BaseListener
return null;
}
- $response = $this->render($event->subject())
- ->withStatus($apiConfig['code']);
+ $response = $this->render($event->subject());
- return $response;
+ if (empty($apiConfig['code'])) {
+ return $response;
+ }
+
+ return $response->withStatus($apiConfig['code']);
}
/**
diff --git a/tests/TestCase/Listener/ApiListenerTest.php b/tests/TestCase/Listener/ApiListenerTest.php
index <HASH>..<HASH> 100644
--- a/tests/TestCase/Listener/ApiListenerTest.php
+++ b/tests/TestCase/Listener/ApiListenerTest.php
@@ -168,6 +168,59 @@ class ApiListenerTest extends TestCase
}
/**
+ * testResponseWithStatusCodeNotSpecified
+ *
+ * @return void
+ * @see https://github.com/FriendsOfCake/crud/issues/572
+ */
+ public function testResponseWithStatusCodeNotSpecified()
+ {
+ $action = $this
+ ->getMockBuilder('\Crud\Action\ViewAction')
+ ->disableOriginalConstructor()
+ ->setMethods(['getConfig'])
+ ->getMock();
+
+ $response = $this
+ ->getMockBuilder(Response::class)
+ ->setMethods(['withStatus'])
+ ->getMock();
+
+ $subject = $this
+ ->getMockBuilder('\Crud\Event\Subject')
+ ->getMock();
+ $subject->success = true;
+
+ $event = new \Cake\Event\Event('Crud.afterSave', $subject);
+
+ $listener = $this
+ ->getMockBuilder('\Crud\Listener\ApiListener')
+ ->disableOriginalConstructor()
+ ->setMethods(['_action', 'render'])
+ ->getMock();
+ $listener
+ ->expects($this->next($listener))
+ ->method('_action')
+ ->with()
+ ->will($this->returnValue($action));
+ $action
+ ->expects($this->next($action))
+ ->method('getConfig')
+ ->with('api.success')
+ ->will($this->returnValue(null));
+ $listener
+ ->expects($this->next($listener))
+ ->method('render')
+ ->with($subject)
+ ->will($this->returnValue($response));
+ $response
+ ->expects($this->never())
+ ->method('withStatus');
+
+ $response = $listener->respond($event);
+ }
+
+ /**
* Test response method with exception config
*
* @return void | Ensure response's status code doesn't get set to null.
Closes #<I>. | FriendsOfCake_crud | train |
021abdc12a44631ec112c1e3f768caed183d6838 | diff --git a/internal/service/workspaces/tags_gen.go b/internal/service/workspaces/tags_gen.go
index <HASH>..<HASH> 100644
--- a/internal/service/workspaces/tags_gen.go
+++ b/internal/service/workspaces/tags_gen.go
@@ -6,13 +6,14 @@ import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/workspaces"
+ "github.com/aws/aws-sdk-go/service/workspaces/workspacesiface"
tftags "github.com/hashicorp/terraform-provider-aws/internal/tags"
)
// ListTags lists workspaces service tags.
// The identifier is typically the Amazon Resource Name (ARN), although
// it may also be a different identifier depending on the service.
-func ListTags(conn *workspaces.WorkSpaces, identifier string) (tftags.KeyValueTags, error) {
+func ListTags(conn workspacesiface.WorkSpacesAPI, identifier string) (tftags.KeyValueTags, error) {
input := &workspaces.DescribeTagsInput{
ResourceId: aws.String(identifier),
}
@@ -58,7 +59,7 @@ func KeyValueTags(tags []*workspaces.Tag) tftags.KeyValueTags {
// UpdateTags updates workspaces service tags.
// The identifier is typically the Amazon Resource Name (ARN), although
// it may also be a different identifier depending on the service.
-func UpdateTags(conn *workspaces.WorkSpaces, identifier string, oldTagsMap interface{}, newTagsMap interface{}) error {
+func UpdateTags(conn workspacesiface.WorkSpacesAPI, identifier string, oldTagsMap interface{}, newTagsMap interface{}) error {
oldTags := tftags.New(oldTagsMap)
newTags := tftags.New(newTagsMap) | gen/tags: Use interface type as generated AWS Go SDK v1 client type for workspaces. | terraform-providers_terraform-provider-aws | train |
d4071c557849e688483efcbcc829ea986027ba91 | diff --git a/lib/rio.js b/lib/rio.js
index <HASH>..<HASH> 100644
--- a/lib/rio.js
+++ b/lib/rio.js
@@ -222,7 +222,9 @@ function connect(host, port, callback) {
client.on("close", function (had_error) {
log("Closed from Rserve");
- callback(false); // hack for auth failed
+ if (had_error) {
+ callback(false); // hack for auth failed
+ }
});
client.on("error", function (e) { | Calling the callback in close event only if there is an error. | albertosantini_node-rio | train |
9839354d1bc61c91250d723d41515245e13f83f2 | diff --git a/shinken/misc/regenerator.py b/shinken/misc/regenerator.py
index <HASH>..<HASH> 100644
--- a/shinken/misc/regenerator.py
+++ b/shinken/misc/regenerator.py
@@ -461,7 +461,7 @@ class Regenerator:
print "Len after", len(hg.members)
for s in to_del_srv:
- print "Deleting", s.gt_dbg_name()
+ print "Deleting", s.get_full_name()
del self.services[s.id]
# Now clean service groups | Fix : (reported by Olivier Hanesse ) typo and WebUI crash. | Alignak-monitoring_alignak | train |
762cd0295eb99dcae10e730202cc3dce7150e8ea | diff --git a/tests/test_kerberos.py b/tests/test_kerberos.py
index <HASH>..<HASH> 100644
--- a/tests/test_kerberos.py
+++ b/tests/test_kerberos.py
@@ -65,7 +65,7 @@ def test_gssapi():
def test_http_endpoint():
service = "HTTP@%s" % hostname
- url = "http://%s:%d/" % (hostname, port)
+ url = "http://%s:%s/" % (hostname, port)
session = requests.Session() | because we parsing from the environment this is a string not int | apple_ccs-pykerberos | train |
27891e87a10d2156c415f6139a1121858ac96546 | diff --git a/src/CodeInspector/StatementsChecker.php b/src/CodeInspector/StatementsChecker.php
index <HASH>..<HASH> 100644
--- a/src/CodeInspector/StatementsChecker.php
+++ b/src/CodeInspector/StatementsChecker.php
@@ -208,7 +208,6 @@ class StatementsChecker
$this->_checkCondition($stmt->cond, $vars_in_scope, $vars_possibly_in_scope);
$if_types = $this->_type_checker->getTypeAssertions($stmt->cond, true);
- $elseif_types = [];
$can_negate_if_types = !($stmt->cond instanceof PhpParser\Node\Expr\BinaryOp\BooleanAnd);
@@ -279,6 +278,9 @@ class StatementsChecker
if (!($elseif->cond instanceof PhpParser\Node\Expr\BinaryOp\BooleanAnd)) {
$negated_types = array_merge($negated_types, TypeChecker::negateTypes($elseif_types));
}
+ else {
+ $elseif_vars = TypeChecker::reconcileTypes($elseif_types, $elseif_vars, true, $this->_file_name, $stmt->getLine());
+ }
$this->_checkElseIf($elseif, $elseif_vars, $elseif_vars_possibly_in_scope, $for_vars_possibly_in_scope); | Use elseif type assertions within body of elseif | vimeo_psalm | train |
c969cd3b7a704e7b3b4a0f888512d9e190ef93bc | diff --git a/quasar/src/components/pagination/QPagination.js b/quasar/src/components/pagination/QPagination.js
index <HASH>..<HASH> 100644
--- a/quasar/src/components/pagination/QPagination.js
+++ b/quasar/src/components/pagination/QPagination.js
@@ -3,6 +3,7 @@ import Vue from 'vue'
import QBtn from '../btn/QBtn.js'
import QInput from '../input/QInput.js'
+import { stop } from '../../utils/event.js'
import { between } from '../../utils/format.js'
export default Vue.extend({
@@ -196,7 +197,7 @@ export default Vue.extend({
}))
}
- if (this.input) {
+ if (this.input === true) {
contentMiddle.push(h(QInput, {
staticClass: 'inline',
style: {
@@ -340,7 +341,12 @@ export default Vue.extend({
}, [
contentStart,
- h('div', { staticClass: 'row justify-center' }, [
+ h('div', {
+ staticClass: 'row justify-center',
+ on: this.input === true
+ ? { input: stop }
+ : {}
+ }, [
contentMiddle
]), | fix(QPagination): [v1] QPagination - Error while entering page number #<I> | quasarframework_quasar | train |
4953fb542fd31fa8ad30b970fbd2d268dd3e14dc | diff --git a/assets/scss/admin/_themes.scss b/assets/scss/admin/_themes.scss
index <HASH>..<HASH> 100644
--- a/assets/scss/admin/_themes.scss
+++ b/assets/scss/admin/_themes.scss
@@ -4,9 +4,25 @@
{
.theme
{
- .fs-badge.fs-premium-theme-badge
- {
- font-size: 1.1em;
+ .fs-premium-theme-badge-container {
+ position: absolute;
+ right: 0;
+ top: 0;
+
+ .fs-badge {
+ position: relative;
+ top: 0;
+ margin-top: 10px;
+ text-align: center;
+
+ &.fs-premium-theme-badge {
+ font-size: 1.1em;
+ }
+
+ &.fs-beta-theme-badge {
+ background: #00a0d2;
+ }
+ }
}
}
}
\ No newline at end of file
diff --git a/includes/class-freemius.php b/includes/class-freemius.php
index <HASH>..<HASH> 100755
--- a/includes/class-freemius.php
+++ b/includes/class-freemius.php
@@ -1285,10 +1285,6 @@
add_action( 'admin_footer', array( 'Freemius', '_prepend_fs_allow_updater_and_dialog_flag_url_param' ) );
}
- if ( self::is_plugins_page() ) {
- add_action( 'admin_footer', array( 'Freemius', '_maybe_add_beta_label_to_plugin_titles' ) );
- }
-
$plugin_dir = dirname( $this->_plugin_dir_path ) . '/';
/**
@@ -1340,6 +1336,17 @@
add_action( 'admin_footer', array( &$this, '_style_premium_theme' ) );
}
+ if ( self::is_plugins_page() || self::is_themes_page() ) {
+ /**
+ * Specifically use this hook so that the JS event handlers will work properly on the "Themes"
+ * page.
+ *
+ * @author Leo Fajardo (@leorw)
+ * @since 2.2.4.7
+ */
+ add_action( 'admin_footer-' . self::get_current_page(), array( 'Freemius', '_maybe_add_beta_label_to_module_titles' ) );
+ }
+
/**
* Part of the mechanism to identify new plugin install vs. plugin update.
*
diff --git a/templates/js/style-premium-theme.php b/templates/js/style-premium-theme.php
index <HASH>..<HASH> 100644
--- a/templates/js/style-premium-theme.php
+++ b/templates/js/style-premium-theme.php
@@ -31,10 +31,18 @@
$theme = $('#<?php echo $slug ?>-premium-name').parents('.theme');
}
- if (0 === $theme.find('.fs-premium-theme-badge').length) {
+ if (0 === $theme.find('.fs-premium-theme-badge-container').length) {
$theme.addClass('fs-premium');
- $theme.append('<span class="fs-badge fs-premium-theme-badge">' + <?php echo json_encode( $fs->get_text_inline( 'Premium', 'premium' ) ) ?> +'</span>');
+ var $themeBadgeContainer = $( '<div class="fs-premium-theme-badge-container"></div>' );
+
+ $themeBadgeContainer.append( '<div class="fs-badge fs-premium-theme-badge">' + <?php echo json_encode( $fs->get_text_inline( 'Premium', 'premium' ) ) ?> + '</div>' );
+
+ <?php if ( $fs->is_beta() ) : ?>
+ $themeBadgeContainer.append( '<div class="fs-badge fs-beta-theme-badge">' + <?php echo json_encode( $fs->get_text_inline( 'Beta', 'beta' ) ) ?> + '</div>' );
+ <?php endif ?>
+
+ $theme.append( $themeBadgeContainer );
}
}; | [beta-list] [themes] Add a "Beta" badge on the "Themes" page to premium beta themes. | Freemius_wordpress-sdk | train |
0400fb1bdeba9f2d32b466d8a3348398140fca9e | diff --git a/src/browserbox.js b/src/browserbox.js
index <HASH>..<HASH> 100644
--- a/src/browserbox.js
+++ b/src/browserbox.js
@@ -1446,7 +1446,7 @@
curNode.parameters = {};
[].concat(node[i] || []).forEach(function(val, j) {
if (j % 2) {
- curNode.parameters[key] = (val && val.value || '').toString();
+ curNode.parameters[key] = mimefuncs.mimeWordsDecode((val && val.value || '').toString());
} else {
key = (val && val.value || '').toString().toLowerCase();
}
@@ -1466,7 +1466,7 @@
curNode.parameters = {};
[].concat(node[i] || []).forEach(function(val, j) {
if (j % 2) {
- curNode.parameters[key] = (val && val.value || '').toString();
+ curNode.parameters[key] = mimefuncs.mimeWordsDecode((val && val.value || '').toString());
} else {
key = (val && val.value || '').toString().toLowerCase();
}
@@ -1556,7 +1556,7 @@
curNode.dispositionParameters = {};
[].concat(node[i][1] || []).forEach(function(val, j) {
if (j % 2) {
- curNode.dispositionParameters[key] = (val && val.value || '').toString();
+ curNode.dispositionParameters[key] = mimefuncs.mimeWordsDecode((val && val.value || '').toString());
} else {
key = (val && val.value || '').toString().toLowerCase();
}
diff --git a/test/unit/browserbox-test.js b/test/unit/browserbox-test.js
index <HASH>..<HASH> 100644
--- a/test/unit/browserbox-test.js
+++ b/test/unit/browserbox-test.js
@@ -1354,6 +1354,72 @@
it('should parse bodystructure object', function() {
expect(br._parseBODYSTRUCTURE(mimeTorture.source)).to.deep.equal(mimeTorture.parsed);
});
+
+ it('should parse bodystructure with unicode filename', function() {
+ var input = [
+ [{
+ type: 'STRING',
+ value: 'APPLICATION'
+ }, {
+ type: 'STRING',
+ value: 'OCTET-STREAM'
+ },
+ null,
+ null,
+ null, {
+ type: 'STRING',
+ value: 'BASE64'
+ }, {
+ type: 'ATOM',
+ value: '40'
+ },
+ null, [{
+ type: 'STRING',
+ value: 'ATTACHMENT'
+ },
+ [{
+ type: 'STRING',
+ value: 'FILENAME'
+ }, {
+ type: 'STRING',
+ value: '=?ISO-8859-1?Q?BBR_Handel,_Gewerbe,_B=FCrobetriebe,?= =?ISO-8859-1?Q?_private_Bildungseinrichtungen.txt?='
+ }]
+ ],
+ null
+ ], {
+ type: 'STRING',
+ value: 'MIXED'
+ },
+ [{
+ type: 'STRING',
+ value: 'BOUNDARY'
+ }, {
+ type: 'STRING',
+ value: '----sinikael-?=_1-14105085265110.49903922458179295'
+ }],
+ null,
+ null
+ ];
+
+ var expected = {
+ childNodes: [{
+ part: '1',
+ type: 'application/octet-stream',
+ encoding: 'base64',
+ size: 40,
+ disposition: 'attachment',
+ dispositionParameters: {
+ filename: 'BBR Handel, Gewerbe, Bürobetriebe, private Bildungseinrichtungen.txt'
+ }
+ }],
+ type: 'multipart/mixed',
+ parameters: {
+ boundary: '----sinikael-?=_1-14105085265110.49903922458179295'
+ }
+ };
+
+ expect(br._parseBODYSTRUCTURE(input)).to.deep.equal(expected);
+ });
});
describe('#_buildSEARCHCommand', function() { | [WO-<I>] Decode filenames in bodystructure | emailjs_emailjs-imap-client | train |
36d20e834210f407812575f6784bc6d5dc312ecb | diff --git a/examples/middleware/main.go b/examples/middleware/main.go
index <HASH>..<HASH> 100644
--- a/examples/middleware/main.go
+++ b/examples/middleware/main.go
@@ -4,6 +4,7 @@ import (
"fmt"
"github.com/pilu/traffic"
"net/http"
+ "log"
)
type PingMiddleware struct {}
@@ -30,6 +31,9 @@ func (c *PingMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next
func root(w http.ResponseWriter, r *http.Request) {
arw := w.(*traffic.AppResponseWriter)
+ logger := arw.GetVar("logger").(*log.Logger)
+ logger.Printf("Hello")
+
fmt.Fprintf(w, "Global var foo: %v\n", arw.GetVar("foo"))
fmt.Fprintf(w, "Middleware var PING: %v\n", arw.GetVar("ping"))
}
diff --git a/router.go b/router.go
index <HASH>..<HASH> 100644
--- a/router.go
+++ b/router.go
@@ -125,18 +125,27 @@ func New() *Router {
routerMiddleware := &RouterMiddleware{ router }
router.AddMiddleware(routerMiddleware)
- loggerMiddleware := &LoggerMiddleware{
- router: router,
- logger: log.New(os.Stderr, "", log.LstdFlags),
- }
- router.AddMiddleware(loggerMiddleware)
+ // Logger
+ logger := log.New(os.Stderr, "", log.LstdFlags)
+ router.SetVar("logger", logger)
+ // Environment
env := os.Getenv("TRAFFIC_ENV")
if env == "" {
env = ENV_DEVELOPMENT
}
router.SetVar("env", env)
+ // Add useful middlewares for development
+ if env == ENV_DEVELOPMENT {
+ loggerMiddleware := &LoggerMiddleware{
+ router: router,
+ logger: logger,
+ }
+ router.AddMiddleware(loggerMiddleware)
+ }
+
+
return router
} | logger middleware only for development env | gravityblast_traffic | train |
dd60b9d5b8004397dda54cfb8a3eb46efd2417da | diff --git a/glfw/library.py b/glfw/library.py
index <HASH>..<HASH> 100644
--- a/glfw/library.py
+++ b/glfw/library.py
@@ -133,6 +133,7 @@ def _get_library_search_paths():
'/usr/lib64',
'/usr/local/lib64',
'/usr/lib', '/usr/local/lib',
+ '/opt/homebrew/lib',
'/run/current-system/sw/lib',
'/usr/lib/x86_64-linux-gnu/',
'/usr/lib/aarch64-linux-gnu/', | Update library search path for m1 Macs
The apple silicon homebrew installs libraries to `/opt/homebrew/lib` instead of `/usr/local/lib`. | FlorianRhiem_pyGLFW | train |
e06dd2381b65317586f1ca4f385bef7848a69d1c | diff --git a/hpcbench/api.py b/hpcbench/api.py
index <HASH>..<HASH> 100644
--- a/hpcbench/api.py
+++ b/hpcbench/api.py
@@ -246,6 +246,11 @@ class Benchmark(with_metaclass(ABCMeta, object)):
is considered as a shell command.
* *cwd* (optional):
directory where the command is executed.
+ * *expected_exit_statuses* (optional):
+ list or set of statuses the command is expected to exit
+ to consider it successful.
+ Metrics won't be extracted if command fails.
+ Default value is: {0}
Execution context: for every command, a dedicated output directory
is created and the current working directory changed to this directory
diff --git a/hpcbench/driver.py b/hpcbench/driver.py
index <HASH>..<HASH> 100644
--- a/hpcbench/driver.py
+++ b/hpcbench/driver.py
@@ -844,8 +844,9 @@ class FixedAttempts(Enumerator):
def _wrap(**kwargs):
driver = self.execution_layer()
driver(**kwargs)
- mdriver = MetricsDriver(self.campaign, self.benchmark)
- mdriver(**kwargs)
+ if self.report['command_succeeded']:
+ mdriver = MetricsDriver(self.campaign, self.benchmark)
+ mdriver(**kwargs)
return self.report
return _wrap
@@ -1068,6 +1069,12 @@ class ExecutionDriver(Leaf):
benchmark=self.benchmark.name,
executor=type(self).name,
)
+
+ expected_es = self.execution.get('expected_exit_statuses', {0})
+ report['command_succeeded'] = exit_status in expected_es
+ if not report['command_succeeded']:
+ self.logger.error('Command failed with exit status: %s',
+ exit_status)
report.update(self.execution)
report.update(command=self.command)
return report | Do not extract metrics if command fails
* New `expected_exit_statuses` optional key in result of
Benchmark.execution_matrix to provide list of valid
exit statuses (default is [0])
* New `command_succeeded` boolean key in report set to False
if command's exit status was unexpected.
* Do not extract metrics if `command_succeeded' is false. | BlueBrain_hpcbench | train |
03c4c335193e61d48ecb53b5351ac7eec3b4ac09 | diff --git a/app/assets/javascripts/releaf/include/common.js b/app/assets/javascripts/releaf/include/common.js
index <HASH>..<HASH> 100644
--- a/app/assets/javascripts/releaf/include/common.js
+++ b/app/assets/javascripts/releaf/include/common.js
@@ -139,7 +139,7 @@ jQuery(function(){
{
return;
}
-
+
var form = jQuery(event.target);
if (form.data( 'validator' ))
@@ -149,7 +149,7 @@ jQuery(function(){
return;
}
-
+
// selector for field input matching
var input_selector = 'input[type!="hidden"],textarea,select';
@@ -162,28 +162,26 @@ jQuery(function(){
// :TODO: show loader
});
-
- form.on( 'validationend', function( event, v, event_params )
+ form.on( 'validationclearerrors', function( event, v, event_params )
{
- // remove all errors left from earlier validations
- var last_validation_id = form.attr( 'data-validation-id' );
-
-
- if (event_params.validation_id != last_validation_id)
- {
- // do not go further if this is not the last validation
- return;
- }
-
-
- // remove old field errors
+ // trigger this to clear existing errors in form
+ // optional event_params.except_validation_id can be used
+ // to preserve errors created by that specific validation
+
+ var except_validation_id = (event_params && ('except_validation_id' in event_params)) ? event_params.except_validation_id : null;
+
+ // remove field errors
form.find('.field.has_error').each(function()
{
var field = jQuery(this);
- var error_box = field.find( '.error_box' );
+ var error_box = field.find( '.error_box' );
var error_node = error_box.find('.error');
- if (error_node.attr('data-validation-id') != last_validation_id)
+ if (
+ (!except_validation_id)
+ ||
+ (error_node.attr('data-validation-id') != except_validation_id)
+ )
{
error_box.remove();
field.removeClass('has_error');
@@ -192,10 +190,10 @@ jQuery(function(){
field.find('.localization').removeClass('has_error');
}
}
-
});
- // remove old form errors
+
+ // remove form errors
if (form.hasClass('has_error'))
{
var form_error_box = form.find('.form_error_box');
@@ -204,7 +202,11 @@ jQuery(function(){
form_error_box.find('.error').each(function()
{
var error_node = jQuery(this);
- if (error_node.attr('data-validation-id') != last_validation_id)
+ if (
+ (!except_validation_id)
+ ||
+ (error_node.attr('data-validation-id') != except_validation_id)
+ )
{
error_node.remove();
}
@@ -220,6 +222,25 @@ jQuery(function(){
form.removeClass('has_error');
}
}
+
+ });
+
+ form.on( 'validationend', function( event, v, event_params )
+ {
+ // remove all errors left from earlier validations
+
+ var last_validation_id = form.attr( 'data-validation-id' );
+
+ if (event_params.validation_id != last_validation_id)
+ {
+ // do not go further if this is not the last validation
+ return;
+ }
+
+ event_params.except_validation_id = last_validation_id;
+
+ form.trigger('validationclearerrors', [ v, event_params ]);
+
// if error fields still exist, focus to first visible | added clearerrors event to validation script | cubesystems_releaf | train |
4b34c3b7ede8d100e12d3465bcd0f3de62bb036c | diff --git a/geomet/tests/wkt_test.py b/geomet/tests/wkt_test.py
index <HASH>..<HASH> 100644
--- a/geomet/tests/wkt_test.py
+++ b/geomet/tests/wkt_test.py
@@ -157,8 +157,8 @@ class PolygonDumpsTestCase(unittest.TestCase):
poly = dict(type='Polygon', coordinates=[
[[100.001, 0.001], [101.001, 0.001], [101.001, 1.001],
[100.001, 0.001]],
- [[100.201, 0.201], [100.801, 0.201], [100.801, 0.801],
- [100.201, 0.201]],
+ [[100.201, 0.201], [100.801, 0.201], [100.801, 0.801],
+ [100.201, 0.201]],
])
expected = (
'POLYGON ((100.0010 0.0010, 101.0010 0.0010, 101.0010 1.0010, '
@@ -173,8 +173,8 @@ class PolygonDumpsTestCase(unittest.TestCase):
poly = dict(type='Polygon', coordinates=[
[[100.0, 0.0, 3.1], [101.0, 0.0, 2.1], [101.0, 1.0, 1.1],
[100.0, 0.0, 3.1]],
- [[100.2, 0.2, 3.1], [100.8, 0.2, 2.1], [100.8, 0.8, 1.1],
- [100.2, 0.2, 3.1]],
+ [[100.2, 0.2, 3.1], [100.8, 0.2, 2.1], [100.8, 0.8, 1.1],
+ [100.2, 0.2, 3.1]],
])
expected = (
'POLYGON ((100.0 0.0 3.1, 101.0 0.0 2.1, 101.0 1.0 1.1, ' | tests/wkt_test:
Indentation cleanup. | geomet_geomet | train |
da662275d0aa71e71b43949d207caab9bc29dd03 | diff --git a/build.py b/build.py
index <HASH>..<HASH> 100755
--- a/build.py
+++ b/build.py
@@ -850,7 +850,7 @@ def printHelp():
print " advice"
print ""
print "Tasks:"
- print " checkout -- Checks out the source from SVN"
+ print " checkout -- Checks out the sources"
print " dldeps -- Downloads missing dependency libraries and entities"
print " dltests -- Downloads the external test suite if missing"
print " build -- Build the source" | minor tweak to usage statement in build script | validator_validator | train |
b5882336d6d34897ef65929df192aff471ba1eb6 | diff --git a/test/accessibility.js b/test/accessibility.js
index <HASH>..<HASH> 100644
--- a/test/accessibility.js
+++ b/test/accessibility.js
@@ -3,8 +3,8 @@ import colorable from "colorable"
import themes from "../lib/themes"
-var foregrounds = ["foreground", "caret", "invisibles"]
-
+var foregrounds = ["foreground", "caret", "invisibles", "findHighlightForeground", "highlightForeground", "bracketContentsForeground", "bracketsForeground", "gutterForeground"]
+var ignore = ["selectionBorder", "guide", "activeGuide", "stackGuide"]
function colorTest(background, foreground, message) {
// Calculate contrast
@@ -35,6 +35,10 @@ themes.forEach(theme => {
return !setting.scope
}).pop()
+ ignore.forEach(i => {
+ delete bgColors.settings[i]
+ })
+
var themeForegrounds = foregrounds.map(foreground => {
return {
"scope": foreground,
@@ -56,16 +60,19 @@ themes.forEach(theme => {
if (setting.settings.background) {
// check against it's own background color
colorTest(setting.settings.background, foreground, theme.name + ": " + setting.scope + " (" + foreground + ") on " + setting.settings.background + " background")
- } else {
- // For each background color
- Object.keys(bgColors.settings).forEach( bg => {
- if(foregrounds.indexOf(bg) == -1) {
- // Get the background color
- var background = bgColors.settings[bg]
+ foreground = setting.settings.background
+ }
+
+ // For each background color
+ Object.keys(bgColors.settings).forEach( bg => {
+ if(foregrounds.indexOf(bg) == -1) {
+ // Get the background color
+ var background = bgColors.settings[bg]
+ if (background.indexOf("#") == 0) {
colorTest(background, foreground, theme.name + ": " + setting.scope + " (" + foreground + ") on " + bg + " (" + background + ") background")
}
- })
- }
+ }
+ })
}
})
}) | Updating accessibility tests
This updates for the new global settings backgrounds and fixes
comparing a scope background to the global background | primer_github-syntax-theme-generator | train |
c9c9d55b9357a7e698939f84c7659c5a4eafab5b | diff --git a/productmd/common.py b/productmd/common.py
index <HASH>..<HASH> 100644
--- a/productmd/common.py
+++ b/productmd/common.py
@@ -263,6 +263,13 @@ class MetadataBase(object):
class Header(MetadataBase):
+ """
+ This class represents the header used in serialized metadata files.
+
+ It consists of a type and a version. The type is meant purely for consumers
+ of the file to know what they are dealing with without having to check
+ filename. The version is used by productmd when parsing the file.
+ """
def __init__(self, parent, metadata_type):
self._section = "header" | Add docstring to Header class | release-engineering_productmd | train |
4d8903bfd3930174cb9d8312209238f0b5fa16e3 | diff --git a/resources/views/adminarea/pages/tag.blade.php b/resources/views/adminarea/pages/tag.blade.php
index <HASH>..<HASH> 100644
--- a/resources/views/adminarea/pages/tag.blade.php
+++ b/resources/views/adminarea/pages/tag.blade.php
@@ -26,7 +26,7 @@
<section class="content">
<div class="nav-tabs-custom">
- @if($tag->exists && $currentUser->can('delete', $tag)) <div class="pull-right"><a href="#" data-toggle="modal" data-target="#delete-confirmation" data-modal-action="{{ route('adminarea.tags.destroy', ['tag' => $tag]) }}" data-modal-title="{!! trans('cortex/foundation::messages.delete_confirmation_title') !!}" data-modal-body="{!! trans('cortex/foundation::messages.delete_confirmation_body', ['resource' => 'tag', 'identifier' => $tag->name]) !!}" title="{{ trans('cortex/foundation::common.delete') }}" class="btn btn-default" style="margin: 4px"><i class="fa fa-trash text-danger"></i></a></div> @endif
+ @if($tag->exists && $currentUser->can('delete', $tag)) <div class="pull-right"><a href="#" data-toggle="modal" data-target="#delete-confirmation" data-modal-action="{{ route('adminarea.tags.destroy', ['tag' => $tag]) }}" data-modal-title="{!! trans('cortex/foundation::messages.delete_confirmation_title') !!}" data-modal-body="{!! trans('cortex/foundation::messages.delete_confirmation_body', ['resource' => trans('cortex/tags::common.tag'), 'identifier' => $tag->name]) !!}" title="{{ trans('cortex/foundation::common.delete') }}" class="btn btn-default" style="margin: 4px"><i class="fa fa-trash text-danger"></i></a></div> @endif
{!! Menu::render('adminarea.tags.tabs', 'nav-tab') !!}
<div class="tab-content">
diff --git a/src/Http/Controllers/Adminarea/TagsController.php b/src/Http/Controllers/Adminarea/TagsController.php
index <HASH>..<HASH> 100644
--- a/src/Http/Controllers/Adminarea/TagsController.php
+++ b/src/Http/Controllers/Adminarea/TagsController.php
@@ -91,7 +91,7 @@ class TagsController extends AuthorizedController
public function importLogs(ImportLogsDataTable $importLogsDatatable)
{
return $importLogsDatatable->with([
- 'resource' => 'tag',
+ 'resource' => trans('cortex/tags::common.tag'),
'tabs' => 'adminarea.tags.tabs',
'id' => 'adminarea-tags-import-logs-table',
])->render('cortex/foundation::adminarea.pages.datatable-logs');
@@ -179,7 +179,7 @@ class TagsController extends AuthorizedController
return intend([
'url' => route('adminarea.tags.index'),
- 'with' => ['success' => trans('cortex/foundation::messages.resource_saved', ['resource' => 'tag', 'identifier' => $tag->name])],
+ 'with' => ['success' => trans('cortex/foundation::messages.resource_saved', ['resource' => trans('cortex/tags::common.tag'), 'identifier' => $tag->name])],
]);
}
@@ -196,7 +196,7 @@ class TagsController extends AuthorizedController
return intend([
'url' => route('adminarea.tags.index'),
- 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => 'tag', 'identifier' => $tag->name])],
+ 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/tags::common.tag'), 'identifier' => $tag->name])],
]);
}
} | Replace hardcoded resource name with language phrase | rinvex_cortex-tags | train |
797334f312a8e09f4803848d1b10be4a3706a449 | diff --git a/bin/spm-client-diagnostics.js b/bin/spm-client-diagnostics.js
index <HASH>..<HASH> 100755
--- a/bin/spm-client-diagnostics.js
+++ b/bin/spm-client-diagnostics.js
@@ -28,5 +28,5 @@ zip.folder(config.logger.dir)
var archFileName = path.join(os.tmpdir(), 'spm-diagnose.zip')
zip.writeToFile(archFileName)
console.log('SPM diagnostics info is in ' + archFileName)
-console.log('Please e-mail the file to [email protected]')
+console.log('Please e-mail the file to [email protected]')
fs.unlink(cfgDumpFileName, function () {}) | spm-support@ ==> support@ | sematext_spm-agent-nodejs | train |
d462df9f1f3fb4c0185fd13ec5490721555913f9 | diff --git a/geomdl/abstract.py b/geomdl/abstract.py
index <HASH>..<HASH> 100644
--- a/geomdl/abstract.py
+++ b/geomdl/abstract.py
@@ -143,6 +143,8 @@ class SplineGeometry(Geometry):
* :py:attr:`degree`
* :py:attr:`knotvector`
* :py:attr:`ctrlpts`
+ * :py:attr:`ctrlpts_size`
+ * :py:attr:`weights` (for completeness with the rational spline implementations)
* :py:attr:`evalpts`
* :py:attr:`bbox`
* :py:attr:`evaluator`
@@ -240,7 +242,7 @@ class SplineGeometry(Geometry):
@property
def ctrlpts(self):
- """ 1-dimensional array of control points.
+ """ Control points.
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
@@ -268,6 +270,22 @@ class SplineGeometry(Geometry):
return res
@property
+ def weights(self):
+ """ Weights.
+
+ Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
+ on using this class member.
+
+ :getter: Gets the weights
+ :setter: Sets the weights
+ """
+ return None
+
+ @weights.setter
+ def weights(self, value):
+ pass
+
+ @property
def bbox(self):
""" Bounding box. | Add weights property to abstract.SplineGeometry
Added for making the abstraction complete with the rational splines | orbingol_NURBS-Python | train |
e295e203115d1f024c30117bd7f6f1fd8bf21164 | diff --git a/darksky/data.py b/darksky/data.py
index <HASH>..<HASH> 100644
--- a/darksky/data.py
+++ b/darksky/data.py
@@ -27,8 +27,8 @@ class Data_point(object):
setval(Data_block(val) if 'data' in val.keys() else Data_point(val))
def __getattr__(self, name):
- # return none if attribute does not exist
- return
+ if not self.__dict__[name]:
+ return object.__getattribute__(self, name)
def __str__(self):
return self.summary
@@ -36,7 +36,9 @@ class Data_point(object):
class Data_block(Data_point):
def __call__(self, index=None):
- return self.__getitem__(index) if index else super().__call__()
+ if index is None:
+ return super().__call__()
+ return self.__getitem__(index)()
def __setattr__(self, name, value):
if name == 'data': | fixed data_block call with index returning super() | lukaskubis_darkskylib | train |
834186cd1de6b23743f2770b70931c94b0976f48 | diff --git a/src/Codeception/Configuration.php b/src/Codeception/Configuration.php
index <HASH>..<HASH> 100644
--- a/src/Codeception/Configuration.php
+++ b/src/Codeception/Configuration.php
@@ -135,7 +135,7 @@ class Configuration
$configDistFile = $dir . DIRECTORY_SEPARATOR . 'codeception.dist.yml';
if (!(file_exists($configDistFile) || file_exists($configFile))) {
- throw new ConfigurationException("Configuration file could not be found.\nRun `bootstrap` to initialize Codeception.");
+ throw new ConfigurationException("Configuration file could not be found.\nRun `bootstrap` to initialize Codeception.", 404);
}
$config = self::loadConfigFile($configDistFile, self::$defaultConfig); | Added a error code. In order to distinguish between not exist configration and wrong path. | Codeception_Codeception | train |
cfaf2808b860a26ecf45f828fa8e7d88be5fc496 | diff --git a/ui/Component.js b/ui/Component.js
index <HASH>..<HASH> 100644
--- a/ui/Component.js
+++ b/ui/Component.js
@@ -872,14 +872,27 @@ class Component extends EventEmitter {
}
}
+ // ATTENTION: we had problems here, that using
+ // component.el.empty() instead of component.empty()
+ // did cause the children not to dispose(), which is maybe
+ // impossible to achieve.
+ // TODO: Thus we may consider to rename it, or take
+ // other measure to warn the the user about this problem
empty() {
- if (this.el) {
+ this._clear()
+ return this
+ }
+
+ _clear() {
+ let el = this.el
+ if (el) {
this.getChildNodes().forEach(function(child) {
_disposeChild(child)
})
- this.el.empty()
+ el.empty()
}
- return this
+ this.refs = {}
+ this.__foreignRefs__ = {}
}
remove() { | Fix component.empty()
Clearing refs and __foreignRefs__ not relying on proper disposal of children. | substance_substance | train |
e81a8b333fd269b1f87cc665243caa43d8cdeba3 | diff --git a/spoon-runner/src/main/java/com/squareup/spoon/SpoonUtils.java b/spoon-runner/src/main/java/com/squareup/spoon/SpoonUtils.java
index <HASH>..<HASH> 100644
--- a/spoon-runner/src/main/java/com/squareup/spoon/SpoonUtils.java
+++ b/spoon-runner/src/main/java/com/squareup/spoon/SpoonUtils.java
@@ -18,6 +18,7 @@ import java.lang.reflect.InvocationTargetException;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
+import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
@@ -99,7 +100,7 @@ final class SpoonUtils {
static AndroidDebugBridge initAdb(File sdk) {
AndroidDebugBridge.initIfNeeded(false);
File adbPath = FileUtils.getFile(sdk, "platform-tools", "adb");
- AndroidDebugBridge adb = AndroidDebugBridge.createBridge(adbPath.getAbsolutePath(), true);
+ AndroidDebugBridge adb = AndroidDebugBridge.createBridge(adbPath.getAbsolutePath(), false);
waitForAdb(adb);
return adb;
}
@@ -129,17 +130,19 @@ final class SpoonUtils {
}
private static void waitForAdb(AndroidDebugBridge adb) {
- for (int i = 1; i < 10; i++) {
+ long timeOutMs = TimeUnit.SECONDS.toMillis(30);
+ long sleepTimeMs = TimeUnit.SECONDS.toMillis(1);
+ while (!adb.hasInitialDeviceList() && timeOutMs > 0) {
try {
- Thread.sleep(i * 100);
+ Thread.sleep(sleepTimeMs);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
- if (adb.isConnected()) {
- return;
- }
+ timeOutMs -= sleepTimeMs;
+ }
+ if (timeOutMs <= 0 && !adb.hasInitialDeviceList()) {
+ throw new RuntimeException("Timeout getting device list.", null);
}
- throw new RuntimeException("Unable to connect to adb.");
}
private SpoonUtils() { | Reuse ADB instance
When we force a new debug bridge, `kill-server` command will be sent to an existing instance.
There are some difficulties to proper start adb server after this.
This results in <URL> | square_spoon | train |
31189dbf321a943cdd778ea8a815d4a2ab24ffc2 | diff --git a/go/kbfs/libkbfs/md_ops.go b/go/kbfs/libkbfs/md_ops.go
index <HASH>..<HASH> 100644
--- a/go/kbfs/libkbfs/md_ops.go
+++ b/go/kbfs/libkbfs/md_ops.go
@@ -893,7 +893,7 @@ func (md *MDOpsStandard) getForHandle(ctx context.Context, handle *tlfhandle.Han
}
// Check for handle readership, to give a nice error early.
- if handle.Type() == tlf.Private {
+ if handle.Type() == tlf.Private && !handle.IsBackedByTeam() {
session, err := md.config.KBPKI().GetCurrentSession(ctx)
if err != nil {
return tlf.ID{}, ImmutableRootMetadata{}, err
@@ -930,6 +930,11 @@ func (md *MDOpsStandard) getForHandle(ctx context.Context, handle *tlfhandle.Han
if err != nil {
return tlf.ID{}, ImmutableRootMetadata{}, err
}
+ if handle.IsLocalConflict() {
+ md.log.CDebugf(ctx, "Stripping out local conflict info from %s "+
+ "before fetching the ID", handle.GetCanonicalPath())
+ bh.ConflictInfo = nil
+ }
id, rmds, err := mdserv.GetForHandle(ctx, bh, mStatus, lockBeforeGet)
if err != nil {
@@ -1006,9 +1011,11 @@ func (md *MDOpsStandard) GetIDForHandle(
default:
return tlf.NullID, err
}
- err = mdcache.PutIDForHandle(handle, id)
- if err != nil {
- return tlf.NullID, err
+ if !handle.IsLocalConflict() {
+ err = mdcache.PutIDForHandle(handle, id)
+ if err != nil {
+ return tlf.NullID, err
+ }
}
return id, nil
} | md_ops: strip local conflict suffix when fetching ID from server
If we need to get a TLF ID from the server, make sure we don't send
the server a local conflict suffix, because it won't know what to do
with it.
Issue: KBFS-<I> | keybase_client | train |
401c7dcae4f7cf4eee6dd2f9c1aff1b1757c01a3 | diff --git a/app/models/renalware/hd/sessions/auditable_sessions_by_period_query.rb b/app/models/renalware/hd/sessions/auditable_sessions_by_period_query.rb
index <HASH>..<HASH> 100644
--- a/app/models/renalware/hd/sessions/auditable_sessions_by_period_query.rb
+++ b/app/models/renalware/hd/sessions/auditable_sessions_by_period_query.rb
@@ -9,8 +9,8 @@ module Renalware
def call(patient:, starting_on:, ending_on:)
QueryableSession
- .not_ongoing
.for_patient(patient)
+ .not_ongoing
.within_period(starting_on, ending_on)
end
@@ -18,7 +18,9 @@ module Renalware
include PatientScope
scope :within_period, ->(starting_on, ending_on) {
-
+ where("performed_on >= ? and performed_on <= ?",
+ starting_on.beginning_of_day,
+ ending_on.end_of_day)
}
# We want Closed and DNA sessions but not open ones | Scopes for session auditing
Not tested yet and can’t integrate this til other PR merged | airslie_renalware-core | train |
86acb823c33789e7ce4849c2981be1b6daea8849 | diff --git a/archunit/src/main/java/com/tngtech/archunit/library/Architectures.java b/archunit/src/main/java/com/tngtech/archunit/library/Architectures.java
index <HASH>..<HASH> 100644
--- a/archunit/src/main/java/com/tngtech/archunit/library/Architectures.java
+++ b/archunit/src/main/java/com/tngtech/archunit/library/Architectures.java
@@ -226,12 +226,9 @@ public final class Architectures {
}
private EvaluationResult evaluateDependenciesShouldBeSatisfied(JavaClasses classes, LayerDependencySpecification specification) {
- ArchCondition<JavaClass> satisfyLayerDependenciesCondition =
- onlyHaveDependentsWhere(originMatchesIfDependencyIsRelevant(specification.layerName, specification.allowedAccessors));
- if (!specification.allowedTargets.isEmpty()) {
- satisfyLayerDependenciesCondition = satisfyLayerDependenciesCondition
- .and(onlyHaveDependenciesWhere(targetMatchesIfDependencyIsRelevant(specification.layerName, specification.allowedTargets)));
- }
+ ArchCondition<JavaClass> satisfyLayerDependenciesCondition = specification.constraint == LayerDependencyConstraint.ORIGIN
+ ? onlyHaveDependentsWhere(originMatchesIfDependencyIsRelevant(specification.layerName, specification.allowedLayers))
+ : onlyHaveDependenciesWhere(targetMatchesIfDependencyIsRelevant(specification.layerName, specification.allowedLayers));
return classes().that(layerDefinitions.containsPredicateFor(specification.layerName))
.should(satisfyLayerDependenciesCondition)
.evaluate(classes);
@@ -410,10 +407,15 @@ public final class Architectures {
}
}
+ private enum LayerDependencyConstraint {
+ ORIGIN,
+ TARGET
+ }
+
public final class LayerDependencySpecification {
private final String layerName;
- private final Set<String> allowedAccessors = new LinkedHashSet<>();
- private final Set<String> allowedTargets = new LinkedHashSet<>();
+ private final Set<String> allowedLayers = new LinkedHashSet<>();
+ private LayerDependencyConstraint constraint;
private String descriptionSuffix;
private LayerDependencySpecification(String layerName) {
@@ -422,26 +424,28 @@ public final class Architectures {
@PublicAPI(usage = ACCESS)
public LayeredArchitecture mayNotBeAccessedByAnyLayer() {
+ allowedLayers.clear();
+ constraint = LayerDependencyConstraint.ORIGIN;
descriptionSuffix = "may not be accessed by any layer";
return LayeredArchitecture.this.addDependencySpecification(this);
}
@PublicAPI(usage = ACCESS)
public LayeredArchitecture mayOnlyBeAccessedByLayers(String... layerNames) {
- checkLayerNamesExist(layerNames);
- allowedAccessors.addAll(asList(layerNames));
- descriptionSuffix = String.format("may only be accessed by layers ['%s']",
- Joiner.on("', '").join(allowedAccessors));
- return LayeredArchitecture.this.addDependencySpecification(this);
+ return restrictLayers(LayerDependencyConstraint.ORIGIN, layerNames, "may only be accessed by layers ['%s']");
}
@PublicAPI(usage = ACCESS)
public LayeredArchitecture mayOnlyAccessLayers(String... layerNames) {
- checkArgument(layerNames.length > 0, "At least 1 layer name should be provided.");
+ return restrictLayers(LayerDependencyConstraint.TARGET, layerNames, "may only access layers ['%s']");
+ }
+
+ private LayeredArchitecture restrictLayers(LayerDependencyConstraint constraint, String[] layerNames, String descriptionTemplate) {
+ checkArgument(layerNames.length > 0, "At least 1 layer name must be provided.");
checkLayerNamesExist(layerNames);
- allowedTargets.addAll(asList(layerNames));
- descriptionSuffix = String.format("may only access layers ['%s']",
- Joiner.on("', '").join(allowedTargets));
+ allowedLayers.addAll(asList(layerNames));
+ this.constraint = constraint;
+ descriptionSuffix = String.format(descriptionTemplate, Joiner.on("', '").join(layerNames));
return LayeredArchitecture.this.addDependencySpecification(this);
}
diff --git a/archunit/src/test/java/com/tngtech/archunit/library/testclasses/mayonlyaccesslayers/allowed/MayOnlyAccessLayersAllowedClass.java b/archunit/src/test/java/com/tngtech/archunit/library/testclasses/mayonlyaccesslayers/allowed/MayOnlyAccessLayersAllowedClass.java
index <HASH>..<HASH> 100644
--- a/archunit/src/test/java/com/tngtech/archunit/library/testclasses/mayonlyaccesslayers/allowed/MayOnlyAccessLayersAllowedClass.java
+++ b/archunit/src/test/java/com/tngtech/archunit/library/testclasses/mayonlyaccesslayers/allowed/MayOnlyAccessLayersAllowedClass.java
@@ -1,6 +1,9 @@
package com.tngtech.archunit.library.testclasses.mayonlyaccesslayers.allowed;
+import com.tngtech.archunit.library.testclasses.mayonlyaccesslayers.origin.MayOnlyAccessLayersOriginClass;
+
public class MayOnlyAccessLayersAllowedClass {
public void callMe() {
+ new MayOnlyAccessLayersOriginClass();
}
} | only constrain targets with `mayOnlyAccessLayers(..)`
The method previously constrained origins as well, which was unexpected. I.e. a call to `layeredArchitecture()...whereLayer("SomeLayer").mayOnlyAccessLayers("OtherLayer")` would suddenly cause violations like `SomeUnrelatedLayer -> SomeLayer`, because the method would implicitly forbid all other layers to access `SomeLayer`.
Issue: #<I> | TNG_ArchUnit | train |
929019989e77b753756ff2cbfdb02f2d7f218294 | diff --git a/gulpfile.js b/gulpfile.js
index <HASH>..<HASH> 100644
--- a/gulpfile.js
+++ b/gulpfile.js
@@ -37,8 +37,9 @@ gulp.task('scripts', function() {
});
gulp.task('styles', function() {
- return gulp.src('src/vModal/styles/*.scss')
+ return gulp.src('src/vModal/styles/vModal.scss')
.pipe(sass({style: 'expanded'}))
+ .pipe(rename({basename: 'v-modal'} ))
.pipe(autoprefixer('last 2 version'))
.pipe(header(banner, { pkg : pkg } ))
.pipe(gulp.dest('dist/'))
@@ -76,6 +77,6 @@ gulp.task('default', ['lint-src', 'test', 'scripts', 'styles']);
gulp.task('watch', function() {
gulp.watch('src/vModal/**/*.js', ['lint-src', 'scripts']);
gulp.watch('test/**/*.spec.js', ['lint-tests', 'test']);
-
+
gulp.watch('src/vModal/styles/**/*.scss', ['styles']);
-});
\ No newline at end of file
+}); | rename css file | LukaszWatroba_v-modal | train |
3e283e6db06d396a1c972f2fe7b9b8d3f2d1d983 | diff --git a/baseftapp.go b/baseftapp.go
index <HASH>..<HASH> 100644
--- a/baseftapp.go
+++ b/baseftapp.go
@@ -6,7 +6,6 @@ import (
"net"
"net/http"
"os"
- "os/signal"
"time"
"github.com/Financial-Times/go-fthealth/v1a"
@@ -25,7 +24,12 @@ import (
// Endpoints are wrapped in a metrics timer and request loggin including transactionID, which is generated
// if not found on the request as X-Request-Id header
func RunServer(engs map[string]Service, serviceName string, serviceDescription string, port int) {
- //TODO work out how to supply the v1a.Handler as a parameter (so can have several checks)
+ for path, eng := range engs {
+ err := eng.Initialise()
+ if err != nil {
+ log.Fatalf("Eng for path %s could not startup, err=%s", path, err)
+ }
+ }
m := mux.NewRouter()
http.Handle("/", m)
@@ -49,15 +53,8 @@ func RunServer(engs map[string]Service, serviceName string, serviceDescription s
m.HandleFunc("/__ping", pingHandler)
m.HandleFunc("/ping", pingHandler)
- go func() {
- log.Printf("listening on %d", port)
- http.ListenAndServe(fmt.Sprintf(":%d", port), HTTPMetricsHandler(TransactionAwareRequestLoggingHandler(os.Stdout, m)))
- }()
-
- // wait for ctrl-c
- c := make(chan os.Signal, 1)
- signal.Notify(c, os.Interrupt)
- <-c
+ log.Printf("listening on %d", port)
+ http.ListenAndServe(fmt.Sprintf(":%d", port), HTTPMetricsHandler(TransactionAwareRequestLoggingHandler(os.Stdout, m)))
log.Println("exiting")
}
diff --git a/service.go b/service.go
index <HASH>..<HASH> 100644
--- a/service.go
+++ b/service.go
@@ -12,5 +12,6 @@ type Service interface {
Read(uuid string) (thing interface{}, found bool, err error)
Delete(uuid string) (found bool, err error)
DecodeJSON(*json.Decoder) (thing interface{}, identity string, err error)
- Check() (check v1a.Check)
+ Check() (check v1a.Check) //TODO change this
+ Initialise() error
} | Refactor initialisation of each service to be handled by the service | Financial-Times_base-ft-rw-app-go | train |
dd8233430681aa55f2ebbd1899a641e400c551fb | diff --git a/decode.go b/decode.go
index <HASH>..<HASH> 100644
--- a/decode.go
+++ b/decode.go
@@ -96,29 +96,34 @@ func (de *decoder) message(buf []byte, sval reflect.Value) error {
for fieldi < len(fields) && fields[fieldi].ID < int64(fieldnum) {
fieldi++
}
- // For fields within embedded structs, ensure the embedded values aren't nil.
- if fieldi < len(fields) && fields[fieldi].ID == int64(fieldnum) {
- index := fields[fieldi].Index
- path := make([]int, 0, len(index))
- for _, id := range index {
- path = append(path, id)
- field = sval.FieldByIndex(path)
- if field.Kind() == reflect.Ptr && field.IsNil() {
- field.Set(reflect.New(field.Type().Elem()))
+
+ if fieldi < len(fields) {
+ // For fields within embedded structs, ensure the embedded values aren't nil.
+ if fields[fieldi].ID == int64(fieldnum) {
+ index := fields[fieldi].Index
+ path := make([]int, 0, len(index))
+ for _, id := range index {
+ path = append(path, id)
+ field = sval.FieldByIndex(path)
+ if field.Kind() == reflect.Ptr && field.IsNil() {
+ field.Set(reflect.New(field.Type().Elem()))
+ }
}
}
- }
- // Decode the field's value
- rem, err := de.value(wiretype, buf, field)
- if err != nil {
- if fieldi < len(fields) && fields[fieldi] != nil {
- return fmt.Errorf("Error while decoding FieldName %s: %v", fields[fieldi].Name, err)
- } else {
- return err
+ // Decode the field's value
+ // fmt.Printf("Decoding FieldName %+v\n", fields[fieldi].Field)
+ rem, err := de.value(wiretype, buf, field)
+ if err != nil {
+ if fields[fieldi] != nil {
+ return fmt.Errorf("Error while decoding FieldName %+v: %s\n", fields[fieldi].Field, err)
+ } else {
+ return err
+ }
}
+ buf = rem
}
- buf = rem
+
}
return nil
}
@@ -460,7 +465,7 @@ func (de *decoder) mapEntry(slval reflect.Value, vb []byte) error {
if !k.IsValid() || !v.IsValid() {
// We did not decode the key or the value in the map entry.
// Either way, it's an invalid map entry.
- return fmt.Errorf("proto: bad map data: missing key/val")
+ return errors.New("proto: bad map data: missing key/val")
}
slval.SetMapIndex(k, v) | Better error messages
Changed error messages and added a working debug-message to find out what's wrong
in decode.go:<I> | dedis_protobuf | train |
7910df2e1957d6dd99ba8ff260da7a3505be7a99 | diff --git a/src/Accompanist.php b/src/Accompanist.php
index <HASH>..<HASH> 100644
--- a/src/Accompanist.php
+++ b/src/Accompanist.php
@@ -83,6 +83,10 @@ class Accompanist implements JsonSerializable
'extra' => $this->extra,
];
+ if(!empty($this->version)) {
+ $json['version'] = $this->version;
+ }
+
if(!empty($this->keywords)) {
$json['keywords'] = $this->keywords;
}
@@ -104,7 +108,7 @@ class Accompanist implements JsonSerializable
}
if(!empty($this->support)) {
- $json['time'] = $this->time;
+ $json['support'] = $this->support;
}
if(!empty($this->extra)) { | fix bugs with time or version not being included | smmccabe_accompanist | train |
74d9c60b9ef0a06c047d1d9a383232b2b879ce8b | diff --git a/src/Types/MandateMethod.php b/src/Types/MandateMethod.php
index <HASH>..<HASH> 100644
--- a/src/Types/MandateMethod.php
+++ b/src/Types/MandateMethod.php
@@ -6,9 +6,14 @@ class MandateMethod
{
const DIRECTDEBIT = "directdebit";
const CREDITCARD = "creditcard";
+ const PAYPAL = "paypal";
public static function getForFirstPaymentMethod($firstPaymentMethod)
{
+ if ($firstPaymentMethod === PaymentMethod::PAYPAL) {
+ return static::PAYPAL;
+ }
+
if(in_array($firstPaymentMethod, [
PaymentMethod::APPLEPAY,
PaymentMethod::CREDITCARD,
diff --git a/tests/Mollie/API/Types/MandateMethodTest.php b/tests/Mollie/API/Types/MandateMethodTest.php
index <HASH>..<HASH> 100644
--- a/tests/Mollie/API/Types/MandateMethodTest.php
+++ b/tests/Mollie/API/Types/MandateMethodTest.php
@@ -32,6 +32,7 @@ class MandateMethodTest extends TestCase
[PaymentMethod::INGHOMEPAY, MandateMethod::DIRECTDEBIT],
[PaymentMethod::KBC, MandateMethod::DIRECTDEBIT],
[PaymentMethod::SOFORT, MandateMethod::DIRECTDEBIT],
+ [PaymentMethod::PAYPAL, MandateMethod::PAYPAL],
];
}
}
\ No newline at end of file | Add paypal to valid first payment methods | mollie_mollie-api-php | train |
942370c967e11e113021928ceadb214a5e35b06d | diff --git a/neomodel/match.py b/neomodel/match.py
index <HASH>..<HASH> 100644
--- a/neomodel/match.py
+++ b/neomodel/match.py
@@ -109,6 +109,9 @@ class NodeSet(object):
self.dont_match.update(dont_match)
return self
+ def run(self):
+ return QueryBuilder(self).execute()
+
class Traversal(object):
""" | Temporary helper to execute query | neo4j-contrib_neomodel | train |
1dfe0b5e33bb3490dbfd4ed7edb61bbddd19e90a | diff --git a/src/main/java/jcifs/smb/SmbTransportPoolImpl.java b/src/main/java/jcifs/smb/SmbTransportPoolImpl.java
index <HASH>..<HASH> 100644
--- a/src/main/java/jcifs/smb/SmbTransportPoolImpl.java
+++ b/src/main/java/jcifs/smb/SmbTransportPoolImpl.java
@@ -271,21 +271,23 @@ public class SmbTransportPoolImpl implements SmbTransportPool {
@Override
public boolean close () throws CIFSException {
boolean inUse = false;
+
+ List<SmbTransportImpl> toClose;
synchronized ( this.connections ) {
log.debug("Closing pool");
- List<SmbTransportImpl> toClose = new LinkedList<>(this.connections);
+ toClose = new LinkedList<>(this.connections);
toClose.addAll(this.nonPooledConnections);
- for ( SmbTransportImpl conn : toClose ) {
- try {
- inUse |= conn.disconnect(false, false);
- }
- catch ( IOException e ) {
- log.warn("Failed to close connection", e);
- }
- }
this.connections.clear();
this.nonPooledConnections.clear();
}
+ for ( SmbTransportImpl conn : toClose ) {
+ try {
+ inUse |= conn.disconnect(false, false);
+ }
+ catch ( IOException e ) {
+ log.warn("Failed to close connection", e);
+ }
+ }
return inUse;
} | fixed #<I> keep connections to be closed in a temporary list and process
outside synchronized block. | AgNO3_jcifs-ng | train |
064ef8da6a1d5e97af03a510d466f509b906cb6c | diff --git a/aeron-archiver/src/test/java/io/aeron/archiver/ReplaySessionTest.java b/aeron-archiver/src/test/java/io/aeron/archiver/ReplaySessionTest.java
index <HASH>..<HASH> 100644
--- a/aeron-archiver/src/test/java/io/aeron/archiver/ReplaySessionTest.java
+++ b/aeron-archiver/src/test/java/io/aeron/archiver/ReplaySessionTest.java
@@ -46,7 +46,7 @@ public class ReplaySessionTest
private MappedByteBuffer metaDataBuffer;
private ArchiveMetaFileFormatEncoder metaDataWriter;
private ArchiverConductor conductor;
- private int polled;
+ private int messageIndex = 0;
@Before
public void setup() throws Exception
@@ -136,7 +136,6 @@ public class ReplaySessionTest
IoUtil.delete(archiveFolder, true);
}
- private int messageIndex = 0;
@Test
public void shouldReplayDataFromFile()
{ | [Java] field ordering/redundant filed removal | real-logic_aeron | train |
6e79c5c2427afbc5ca2d7bf0e4cc6f90fe36d97c | diff --git a/lib/devise/models/confirmable.rb b/lib/devise/models/confirmable.rb
index <HASH>..<HASH> 100644
--- a/lib/devise/models/confirmable.rb
+++ b/lib/devise/models/confirmable.rb
@@ -50,6 +50,12 @@ module Devise
# add errors
def confirm!
pending_any_confirmation do
+ if confirmation_period_expired?
+ self.errors.add(:email, :confirmation_period_expired,
+ :period => Devise::TimeInflector.time_ago_in_words(self.class.confirm_within.ago))
+ return false
+ end
+
self.confirmation_token = nil
self.confirmed_at = Time.now.utc
@@ -86,7 +92,10 @@ module Devise
# Resend confirmation token. This method does not need to generate a new token.
def resend_confirmation_token
- pending_any_confirmation { send_confirmation_instructions }
+ pending_any_confirmation do
+ self.confirmation_token = nil if confirmation_period_expired?
+ send_confirmation_instructions
+ end
end
# Overwrites active_for_authentication? for confirmation
@@ -177,14 +186,8 @@ module Devise
# Checks whether the record requires any confirmation.
def pending_any_confirmation
- expired = confirmation_period_expired?
-
- if (!confirmed? || pending_reconfirmation?) && !expired
+ if (!confirmed? || pending_reconfirmation?)
yield
- elsif expired
- self.errors.add(:email, :confirmation_period_expired,
- :period => Devise::TimeInflector.time_ago_in_words(self.class.confirm_within.ago))
- false
else
self.errors.add(:email, :already_confirmed)
false
diff --git a/test/models/confirmable_test.rb b/test/models/confirmable_test.rb
index <HASH>..<HASH> 100644
--- a/test/models/confirmable_test.rb
+++ b/test/models/confirmable_test.rb
@@ -259,6 +259,16 @@ class ConfirmableTest < ActiveSupport::TestCase
assert_not confirm_user_by_token_with_confirmation_sent_at(4.days.ago)
end
end
+
+ test 'should generate a new token if the previous one has expired' do
+ swap Devise, :confirm_within => 3.days do
+ user = create_user
+ user.update_attribute(:confirmation_sent_at, 4.days.ago)
+ old = user.confirmation_token
+ user.resend_confirmation_token
+ assert_not_equal user.confirmation_token, old
+ end
+ end
end
class ReconfirmableTest < ActiveSupport::TestCase | Ensure a new token is generated if the previous one expired | plataformatec_devise | train |
c439905b72b2068a425dabe5c7ee7e1cff419dd2 | diff --git a/packages/bonde-admin-canary/src/services/i18n/index.js b/packages/bonde-admin-canary/src/services/i18n/index.js
index <HASH>..<HASH> 100644
--- a/packages/bonde-admin-canary/src/services/i18n/index.js
+++ b/packages/bonde-admin-canary/src/services/i18n/index.js
@@ -1,3 +1,3 @@
export { default as i18n } from './instance'
export { default as ProviderI18n } from './ProviderI18n'
-export { translate } from 'react-i18next'
+export { translate, Interpolate } from 'react-i18next' | fix(admin-canary): export Interpolate component from react-i<I>next | nossas_bonde-client | train |
3c7fe33760de5b5a314b4926590341b6ab46ca06 | diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -3,57 +3,62 @@
import { find } from './util'
import modalWrapperFactory from './dialogs-wrapper'
-let Vue = null
-let modalWrapper = null
-let modalFunctions = []
-
-function findModalByName (name) {
- return find(modalFunctions, item => item.name === name)
-}
-
-export var debug = process.env.NODE_ENV === 'development'
+class VueModalDialog {
+ constructor () {
+ this.Vue = null
+ this.debug = process.env.NODE_ENV === 'development'
+ this.modalWrapper = null
+ this.modalFunctions = []
+ }
-export function install (vue, options) {
- // export vue instance to global scope
- // so that we can easily modify its prototype
- Vue = vue
+ _findModalByName (name) {
+ return find(this.modalFunctions, item => item.name === name)
+ }
- // create an anchor element for modal dialogs' wrapper
- const anchor = document.createElement('div')
- document.body.insertBefore(anchor, document.body.childNodes[0])
+ install (vue, options) {
+ // export vue instance to global scope
+ // so that we can easily modify its prototype
+ this.Vue = vue
- // and mount the modal dialogs' wrapper on that anchor
- const ModalWrapper = modalWrapperFactory(options)
- modalWrapper = new ModalWrapper()
- modalWrapper.$mount(anchor)
-}
+ // create an anchor element for modal dialogs' wrapper
+ const anchor = document.createElement('div')
+ document.body.insertBefore(anchor, document.body.childNodes[0])
-/**
- * Add a modal function into Vue.prototype
- * so that you can access this function
- * via `this.$<name>` from a Vue component.
- */
-export function use (name, options) {
- name = name.toString().trim()
-
- // make sure 'name' is unique
- if (findModalByName(name)) {
- if (debug) console.warn(`[vue-modal] Another modal function ${name} is already exist.`)
- return
+ // and mount the modal dialogs' wrapper on that anchor
+ const ModalWrapper = modalWrapperFactory(options)
+ this.modalWrapper = new ModalWrapper()
+ this.modalWrapper.$mount(anchor)
}
- modalFunctions.push(options)
- Vue.prototype[`$${name}`] = show.bind(undefined, name)
-}
+ /**
+ * Add a modal function into Vue.prototype
+ * so that you can access this function
+ * via `this.$<name>` from a Vue component.
+ */
+ use (name, options) {
+ name = name.toString().trim()
-export function show (name, ...args) {
- return new Promise((resolve, reject) => {
- const modal = findModalByName(name)
- if (!modal) {
- if (debug) console.warn(`[vue-modal] Modal dialog ${name} is not found.`)
- return reject(new Error(`Modal dialog ${name} is not found.`))
+ // make sure 'name' is unique
+ if (this._findModalByName(name)) {
+ if (this.debug) console.warn(`[vue-modal] Another modal function ${name} is already exist.`)
+ return
}
- return modalWrapper.add(modal, ...args)
- })
+ this.modalFunctions.push(options)
+ this.Vue.prototype[`$${name}`] = this.show.bind(undefined, name)
+ }
+
+ show (name, ...args) {
+ return new Promise((resolve, reject) => {
+ const modal = this._findModalByName(name)
+ if (!modal) {
+ if (this.debug) console.warn(`[vue-modal] Modal dialog ${name} is not found.`)
+ return reject(new Error(`Modal dialog ${name} is not found.`))
+ }
+
+ return this.modalWrapper.add(modal, ...args)
+ })
+ }
}
+
+export default new VueModalDialog() | refactor: wrap methods from index.js into a class | hjkcai_vue-modal-dialogs | train |
c0f4f520b7b467e48c3547b3b527a8d53f0a12d4 | diff --git a/nomad/structs/structs.go b/nomad/structs/structs.go
index <HASH>..<HASH> 100644
--- a/nomad/structs/structs.go
+++ b/nomad/structs/structs.go
@@ -25,6 +25,7 @@ import (
"github.com/gorhill/cronexpr"
"github.com/hashicorp/consul/api"
multierror "github.com/hashicorp/go-multierror"
+ "github.com/hashicorp/go-version"
"github.com/hashicorp/nomad/acl"
"github.com/hashicorp/nomad/helper"
"github.com/hashicorp/nomad/helper/args"
@@ -1289,13 +1290,13 @@ func (r *Resources) MeetsMinResources() error {
var mErr multierror.Error
minResources := MinResources()
if r.CPU < minResources.CPU {
- mErr.Errors = append(mErr.Errors, fmt.Errorf("minimum CPU value is 20; got %d", r.CPU))
+ mErr.Errors = append(mErr.Errors, fmt.Errorf("minimum CPU value is %d; got %d", minResources.CPU, r.CPU))
}
if r.MemoryMB < minResources.MemoryMB {
- mErr.Errors = append(mErr.Errors, fmt.Errorf("minimum MemoryMB value is 10; got %d", r.MemoryMB))
+ mErr.Errors = append(mErr.Errors, fmt.Errorf("minimum MemoryMB value is %d; got %d", minResources.CPU, r.MemoryMB))
}
if r.IOPS < minResources.IOPS {
- mErr.Errors = append(mErr.Errors, fmt.Errorf("minimum IOPS value is 0; got %d", r.IOPS))
+ mErr.Errors = append(mErr.Errors, fmt.Errorf("minimum IOPS value is %d; got %d", minResources.CPU, r.IOPS))
}
for i, n := range r.Networks {
if err := n.MeetsMinResources(); err != nil { | Review feedback + re-add dropped import | hashicorp_nomad | train |
18391374f6006c118b9e33fc46de8b59cb7b7602 | diff --git a/tests/api/test_people.py b/tests/api/test_people.py
index <HASH>..<HASH> 100644
--- a/tests/api/test_people.py
+++ b/tests/api/test_people.py
@@ -17,12 +17,8 @@ __license__ = "MIT"
# Helper Functions
-def is_valid_person(obj):
- return isinstance(obj, ciscosparkapi.Person) and obj.id is not None
-
-
-def are_valid_people(iterable):
- return all([is_valid_person(obj) for obj in iterable])
+def create_person(api, emails, **person_attributes):
+ return api.people.create(emails, **person_attributes)
def get_person_by_id(api, id):
@@ -44,10 +40,6 @@ def get_person_by_email(api, email):
return None
-def create_person(api, emails, **person_attributes):
- return api.people.create(emails, **person_attributes)
-
-
def update_person(api, person, **person_attributes):
# Get a copy of the person's current attributes
new_attributes = person.json_data
@@ -63,6 +55,23 @@ def delete_person(api, person):
api.people.delete(person.id)
+def is_valid_person(obj):
+ return isinstance(obj, ciscosparkapi.Person) and obj.id is not None
+
+
+def are_valid_people(iterable):
+ return all([is_valid_person(obj) for obj in iterable])
+
+
+def person_exists(api, person):
+ try:
+ get_person_by_id(api, person.id)
+ except ciscosparkapi.SparkApiError:
+ return False
+ else:
+ return True
+
+
# pytest Fixtures
@pytest.fixture(scope="session")
@@ -70,7 +79,7 @@ def me(api):
return api.people.me()
@pytest.fixture(scope="session")
-def get_new_test_person(api, get_new_email_address, me, licenses_dict):
+def get_test_person(api, get_new_email_address, me, licenses_dict):
def inner_function():
person_email = get_new_email_address()
@@ -95,10 +104,10 @@ def get_new_test_person(api, get_new_email_address, me, licenses_dict):
class PeopleManager(object):
"""Creates, tracks and manages test accounts 'people' used by the tests."""
- def __init__(self, api, get_new_test_person):
+ def __init__(self, api, get_test_person):
super(PeopleManager, self).__init__()
self._api = api
- self._get_new_test_person = get_new_test_person
+ self._get_new_test_person = get_test_person
self.test_people = {}
def __getitem__(self, item):
@@ -133,17 +142,37 @@ class PeopleManager(object):
@pytest.fixture(scope="session")
-def test_people(api, get_new_test_person):
- test_people = PeopleManager(api, get_new_test_person)
+def test_people(api, get_test_person):
+ test_people = PeopleManager(api, get_test_person)
yield test_people
del test_people
@pytest.fixture()
-def temp_person(api, get_new_test_person):
- person = get_new_test_person()
+def temp_person(api, get_random_email_address, me, licenses_dict):
+ # Get an e-mail address not currently used on Cisco Spark
+ person_email = None
+ person = True
+ while person:
+ person_email = get_random_email_address()
+ person = get_person_by_email(api, person_email)
+
+ # Create the person
+ person = create_person(
+ api,
+ emails=[person_email],
+ displayName="ciscosparkapi",
+ firstName="ciscosparkapi",
+ lastName="ciscosparkapi",
+ orgId=me.orgId,
+ licenses=[licenses_dict["Messaging"].id],
+ )
+ assert is_valid_person(person)
+
yield person
- delete_person(api, person)
+
+ if person_exists(api, person):
+ delete_person(api, person)
@pytest.fixture()
diff --git a/tests/conftest.py b/tests/conftest.py
index <HASH>..<HASH> 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -3,6 +3,7 @@
import os
+import random
import string
import tempfile
@@ -32,6 +33,7 @@ pytest_plugins = [
TEST_DOMAIN = "cmlccie.com"
+TEST_ID_START = 91
TEST_FILE_URL = "https://developer.ciscospark.com/images/[email protected]"
@@ -40,7 +42,7 @@ email_template = string.Template("test${number}@" + TEST_DOMAIN)
# Helper Functions
def new_email_generator():
- i = 50
+ i = TEST_ID_START
while True:
email_address = email_template.substitute(number=i)
i += 1
@@ -75,3 +77,12 @@ def get_new_email_address():
return next(generator)
return inner_function
+
+
[email protected]()
+def get_random_email_address():
+ def inner_function():
+ i = random.randint(1000, 9999)
+ return email_template.substitute(number=i)
+
+ return inner_function | Update test suite to use new accounts
Tests have been failing because Spark is unable to "sideboard" the testing user accounts that are rapidly created (invited) but never logged into.
Create a new Spark organization for the ciscosparkapi package testing, and provision the users that are regularly used by the test suite.
Also, change the `temp_person` fixture to create users using random e-mail addresses created in a relatively large random range. | CiscoDevNet_webexteamssdk | train |
134e8e8e65cb3f5f11b4b575884fa9b0691f1d9f | diff --git a/client.js b/client.js
index <HASH>..<HASH> 100644
--- a/client.js
+++ b/client.js
@@ -9,13 +9,17 @@
var build_model = function (init_dict) {
want_file_pos = init_dict["want_file_pos"]
- want_file_pos.forEach( function(file_pos) {
+ want_file_pos.forEach( function(file_pos, i) {
files[file_pos] = {};
- var head_and_tail = init_dict["heads_and_tails"][file_pos];
- files[file_pos]["bitfield"] = '';
+ var head_and_tail = init_dict["heads_and_tails"][i];
+ files[file_pos]["bitfield"] = [];
for (var j = head_and_tail[0]; j <= head_and_tail[1]; j++) {
- files[file_pos]["bitfield"] = files[file_pos]["bitfield"] +
- init_dict["bitfield"][j];
+ var next_digit = init_dict["bitfield"][j];
+ if (next_digit === "1") {
+ files[file_pos]["bitfield"].push(1);
+ } else if (next_digit == "0") {
+ files[file_pos]["bitfield"].push(0);
+ }
}
files[file_pos]["path"] = init_dict["files"][file_pos]["path"];
files[file_pos]["relevant"] = [];
@@ -30,18 +34,17 @@
}
var vis_write = function (write_dict) {
- console.log(write_dict);
var piece_index = write_dict["piece"];
// Want to find which files care about piece_index
- files.forEach( function (afile) {
- var internal_index = afile["relevant"].indexOf(piece_index);
+ for (file_index in files) {
+ var internal_index = files[file_index]["relevant"].indexOf(piece_index);
console.log(internal_index);
if ( internal_index !== -1) {
- afile["bitfield"][internal_index] = 0;
+ files[file_index]["bitfield"][internal_index] = 0;
// TODO -- add transition code here
- console.log(afile["bitfield"]);
+ console.log(files[file_index]["bitfield"]);
}
- }
+ };
}
window.THEWEBSOCKET.onmessage = function (message) {
@@ -53,7 +56,7 @@
} else if (meat["kind"] === "write") {
vis_write(meat);
} else {
- throw "Data kind invalid"
+ throw "Data kind invalid";
}
var h = document.getElementsByTagName('h1')[0];
h.innerHTML = meat["kind"]; | Storing bitfields as arrays of ints instead of strings | jefflovejapan_drench | train |
c7242587e6f89b6235d1964801825b0a970eade9 | diff --git a/ChromeController/__init__.py b/ChromeController/__init__.py
index <HASH>..<HASH> 100644
--- a/ChromeController/__init__.py
+++ b/ChromeController/__init__.py
@@ -3,6 +3,7 @@ from .transport import ChromeSocketManager
from .manager import ChromeRemoteDebugInterface
from .Generator import gen
+from .cr_exceptions import ChromeNavigateTimedOut
from .cr_exceptions import ChromeControllerException
from .cr_exceptions import ChromeStartupException
from .cr_exceptions import ChromeConnectFailure
diff --git a/ChromeController/cr_exceptions.py b/ChromeController/cr_exceptions.py
index <HASH>..<HASH> 100644
--- a/ChromeController/cr_exceptions.py
+++ b/ChromeController/cr_exceptions.py
@@ -9,4 +9,7 @@ class ChromeConnectFailure(ChromeControllerException):
pass
class ChromeError(ChromeControllerException):
+ pass
+
+class ChromeNavigateTimedOut(ChromeError):
pass
\ No newline at end of file
diff --git a/ChromeController/manager.py b/ChromeController/manager.py
index <HASH>..<HASH> 100644
--- a/ChromeController/manager.py
+++ b/ChromeController/manager.py
@@ -12,6 +12,7 @@ import time
import http.cookiejar
import urllib.parse
+from ChromeController.cr_exceptions import ChromeNavigateTimedOut
from ChromeController.cr_exceptions import ChromeError
from ChromeController.resources import js
@@ -642,7 +643,7 @@ class ChromeRemoteDebugInterface(ChromeRemoteDebugInterfaceBase):
resp = self.transport.recv_filtered(network_response_recieved_for_url(url))
if resp is None:
- raise ChromeError("Blocking navigate timed out!")
+ raise ChromeNavigateTimedOut("Blocking navigate timed out!")
return resp['params'] | Add a timeout specific exceptions. | fake-name_ChromeController | train |
27e4f88e0868b03c505f998dfd353172504dd0e3 | diff --git a/lib/Browser.php b/lib/Browser.php
index <HASH>..<HASH> 100644
--- a/lib/Browser.php
+++ b/lib/Browser.php
@@ -906,8 +906,8 @@ class Browser
*/
protected function checkBrowserEdge()
{
- if (stripos($this->_agent, 'Edge/') !== false) {
- $aresult = explode('/', stristr($this->_agent, 'Edge'));
+ if ($name = stripos($this->_agent, 'Edge/') !== false ? 'Edge' : stripos($this->_agent, 'Edg/') !== false ? 'Edg' : false) {
+ $aresult = explode('/', stristr($this->_agent, $name));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]); | Support newer Edge version
In newer versions of Edge the user agent is "Edg/..." | cbschuld_Browser.php | train |
429d0f0eee0070b3bb7759d93cdffd80a095f498 | diff --git a/rllib/env/multi_agent_env.py b/rllib/env/multi_agent_env.py
index <HASH>..<HASH> 100644
--- a/rllib/env/multi_agent_env.py
+++ b/rllib/env/multi_agent_env.py
@@ -132,7 +132,20 @@ class MultiAgentEnv(gym.Env):
self._check_if_space_maps_agent_id_to_sub_space()
)
if self._spaces_in_preferred_format:
- return self.observation_space.contains(x)
+ for key, agent_obs in x.items():
+ if not self.observation_space[key].contains(agent_obs):
+ return False
+ if not all(k in self.observation_space for k in x):
+ if log_once("possibly_bad_multi_agent_dict_missing_agent_observations"):
+ logger.warning(
+ "You environment returns observations that are "
+ "MultiAgentDicts with incomplete information. "
+ "Meaning that they only contain information on a subset of"
+ " participating agents. Ignore this warning if this is "
+ "intended, for example if your environment is a turn-based "
+ "simulation."
+ )
+ return True
logger.warning("observation_space_contains() has not been implemented")
return True
diff --git a/rllib/utils/pre_checks/env.py b/rllib/utils/pre_checks/env.py
index <HASH>..<HASH> 100644
--- a/rllib/utils/pre_checks/env.py
+++ b/rllib/utils/pre_checks/env.py
@@ -60,9 +60,10 @@ def check_env(env: EnvType) -> None:
),
):
raise ValueError(
- "Env must be one of the supported types: BaseEnv, gym.Env, "
+ "Env must be of one of the following supported types: BaseEnv, "
+ "gym.Env, "
"MultiAgentEnv, VectorEnv, RemoteBaseEnv, ExternalMultiAgentEnv, "
- f"ExternalEnv, but instead was a {type(env)}"
+ f"ExternalEnv, but instead is of type {type(env)}."
)
if isinstance(env, MultiAgentEnv):
check_multiagent_environments(env)
@@ -73,8 +74,8 @@ def check_env(env: EnvType) -> None:
else:
logger.warning(
"Env checking isn't implemented for VectorEnvs, RemoteBaseEnvs, "
- "ExternalMultiAgentEnv,or ExternalEnvs or Environments that are "
- "Ray actors"
+ "ExternalMultiAgentEnv, ExternalEnvs or environments that are "
+ "Ray actors."
)
except Exception:
actual_error = traceback.format_exc()
@@ -84,7 +85,7 @@ def check_env(env: EnvType) -> None:
"We've added a module for checking your custom environments. It "
"may cause your experiment to fail if your environment is not set up"
"correctly. You can disable this behavior by setting "
- "`disable_env_checking=True` in your config "
+ "`disable_env_checking=True` in your environment config "
"dictionary. You can run the environment checking module "
"standalone by calling ray.rllib.utils.check_env([env])."
)
@@ -485,7 +486,7 @@ def _check_if_element_multi_agent_dict(env, element, function_string, base_env=F
if not isinstance(element, dict):
if base_env:
error = (
- f"The element returned by {function_string} has values "
+ f"The element returned by {function_string} contains values "
f"that are not MultiAgentDicts. Instead, they are of "
f"type: {type(element)}"
)
@@ -514,7 +515,7 @@ def _check_if_element_multi_agent_dict(env, element, function_string, base_env=F
f" that are not the names of the agents in the env. "
f"\nAgent_ids in this MultiAgentDict: "
f"{list(element.keys())}\nAgent_ids in this env:"
- f"{list(env.get_agent_ids())}. You likley need to add the private "
+ f"{list(env.get_agent_ids())}. You likely need to add the private "
f"attribute `_agent_ids` to your env, which is a set containing the "
f"ids of agents supported by your env."
) | [RLlib] Fix multi agent environment checks for observations that contain only some agents' obs each step. (#<I>) | ray-project_ray | train |
59438f4fffea6868081133c5cb7b62eeced504df | diff --git a/uritools/compose.py b/uritools/compose.py
index <HASH>..<HASH> 100644
--- a/uritools/compose.py
+++ b/uritools/compose.py
@@ -3,6 +3,7 @@ from __future__ import unicode_literals
import ipaddress
import itertools
import re
+import warnings
from collections import Iterable, Mapping
@@ -28,8 +29,10 @@ def ifnone(a, b):
def splitauth(authority, userinfo, host, port, encoding='utf-8'):
if isinstance(authority, type('')):
+ warnings.warn("authority as string is deprecated", DeprecationWarning)
parts = AUTHORITY_RE.match(authority).groups()
- elif isinstance(authority, String):
+ elif isinstance(authority, bytes):
+ warnings.warn("authority as bytes is deprecated", DeprecationWarning)
parts = AUTHORITY_RE.match(authority.decode(encoding)).groups()
elif isinstance(authority, Iterable):
_, _, _ = parts = authority
@@ -45,7 +48,7 @@ def ip_literal(address):
return b'[' + ipaddress.IPv6Address(address).compressed.encode() + b']'
-def hoststr(host, encoding):
+def hoststr(host):
if host.startswith('[') and host.endswith(']'):
return ip_literal(host[1:-1])
if host.startswith('[') or host.endswith(']'):
@@ -54,7 +57,7 @@ def hoststr(host, encoding):
# check for IPv6 addresses as returned by SplitResult.gethost()
return b'[' + ipaddress.IPv6Address(host).compressed.encode() + b']'
except ValueError:
- return uriencode(host, SUB_DELIMS, encoding).lower()
+ return uriencode(host, SUB_DELIMS).lower()
def querylist(items, delim, encoding):
@@ -133,9 +136,9 @@ def uricompose(scheme=None, authority=None, path='', query=None,
elif isinstance(host, ipaddress.IPv6Address):
authority += b'[' + host.compressed.encode() + b']'
elif isinstance(host, type('')):
- authority += hoststr(host, encoding)
+ authority += hoststr(host)
elif isinstance(host, String):
- authority += hoststr(host.decode(encoding), encoding)
+ authority += hoststr(host.decode('utf-8'))
else:
raise TypeError('Invalid host type') | Fix #<I>: Deprecate uricompose() support for string authority. | tkem_uritools | train |
079d2b7a324899e793c002df3a2ad111a6a65cd9 | diff --git a/openpnm/models/physics/diffusive_conductance.py b/openpnm/models/physics/diffusive_conductance.py
index <HASH>..<HASH> 100644
--- a/openpnm/models/physics/diffusive_conductance.py
+++ b/openpnm/models/physics/diffusive_conductance.py
@@ -138,7 +138,7 @@ def mixed_diffusion(target,
@_doctxt
def taylor_aris_diffusion(target,
pore_area="pore.area",
- throat_area="throat.area",
+ throat_area="throat.cross_sectional_area",
pore_diffusivity="pore.diffusivity",
throat_diffusivity="throat.diffusivity",
pore_pressure="pore.pressure",
diff --git a/openpnm/models/physics/hydraulic_conductance.py b/openpnm/models/physics/hydraulic_conductance.py
index <HASH>..<HASH> 100644
--- a/openpnm/models/physics/hydraulic_conductance.py
+++ b/openpnm/models/physics/hydraulic_conductance.py
@@ -193,7 +193,7 @@ def valvatne_blunt(
pore_shape_factor="pore.shape_factor",
throat_shape_factor="throat.shape_factor",
pore_area="pore.area",
- throat_area="throat.area",
+ throat_area="throat.cross_sectional_area",
conduit_lengths="throat.conduit_lengths",
):
r""" | updated throat.area name in valvante blunt and taylor aris models | PMEAL_OpenPNM | train |
f89846667d4902af7dbd131bff825e0d6017ce27 | diff --git a/nlpipe/tasks.py b/nlpipe/tasks.py
index <HASH>..<HASH> 100644
--- a/nlpipe/tasks.py
+++ b/nlpipe/tasks.py
@@ -7,7 +7,7 @@ from .celery import app
def morphosyntactic(text):
cmd = "$NEWSREADER_HOME/run_parser.sh"
p2 = Popen(cmd, stdin=PIPE, stdout=PIPE, shell=True)
- (out, err) = p2.communicate(text)
+ (out, err) = p2.communicate(text.encode("utf-8"))
if p2.returncode != 0:
raise Exception("Error on calling shell command: {cmd} (see logs)".format(**locals()))
return out | Send text as utf-8 | amcat_nlpipe | train |
205fe344c35ff8ef5943e3b52ba48c36498589c8 | diff --git a/parser/__init__.py b/parser/__init__.py
index <HASH>..<HASH> 100644
--- a/parser/__init__.py
+++ b/parser/__init__.py
@@ -1,2 +1,2 @@
from .element import Element
-from .common import schema, weighted_choice
\ No newline at end of file
+from .common import schema, weighted_choice, normalize
\ No newline at end of file
diff --git a/parser/common.py b/parser/common.py
index <HASH>..<HASH> 100644
--- a/parser/common.py
+++ b/parser/common.py
@@ -1,3 +1,4 @@
+import re
import random
from lxml import etree
@@ -28,3 +29,17 @@ def weighted_choice(choices):
if most + weight > rand:
return choice
most += weight
+
+def normalize(self, string):
+ """
+ Normalize input for comparison with other input
+ :param string: The string to normalize
+ :type string: str
+
+ :rtype: str
+ """
+ if not isinstance(string, str):
+ self._log.warn('Attempted to normalize a non-string')
+ return ''
+
+ return re.sub(r'([^\s\w]|_)+', '', string.strip().casefold())
\ No newline at end of file
diff --git a/parser/trigger/trigger.py b/parser/trigger/trigger.py
index <HASH>..<HASH> 100644
--- a/parser/trigger/trigger.py
+++ b/parser/trigger/trigger.py
@@ -1,5 +1,5 @@
import logging
-from parser import Element
+from parser import Element, normalize
from parser.trigger.response import Response
@@ -19,13 +19,27 @@ class Trigger(Element):
super().__init__(saml, element, file_path)
self._log = logging.getLogger('saml.trigger')
+ def match(self, message):
+ """
+ Returns a response message if a match is found, otherwise returns None
+
+ :param message: The message to test
+ :type message: str
+
+ :rtype: bool
+ """
+ message = normalize(message)
+
+ if message == self.pattern:
+ return message
+
def _parse_topic(self, element):
"""
Parse a topic element
:param element: The XML Element object
:type element: etree._Element
"""
- self.topic = self._normalize(element.text)
+ self.topic = normalize(element.text)
def _parse_emotion(self, element):
"""
@@ -33,7 +47,7 @@ class Trigger(Element):
:param element: The XML Element object
:type element: etree._Element
"""
- self.emotion = self._normalize(element.text)
+ self.emotion = normalize(element.text)
def _parse_pattern(self, element):
"""
@@ -41,7 +55,7 @@ class Trigger(Element):
:param element: The XML Element object
:type element: etree._Element
"""
- self.pattern = self._normalize(element.text)
+ self.pattern = normalize(element.text)
def _parse_response(self, element):
"""
@@ -94,10 +108,3 @@ class Trigger(Element):
:type element: etree._Element
"""
pass
-
- def _normalize(self, string):
- if not isinstance(string, str):
- self._log.warn('Attempted to normalize a non-string')
- return ''
-
- return string.strip().casefold()
\ No newline at end of file | Trigger match method, normalize moved to common | FujiMakoto_AgentML | train |
69f17ff384190704372cc353f090401ee87c9b3c | diff --git a/lib/github_api/constants.rb b/lib/github_api/constants.rb
index <HASH>..<HASH> 100644
--- a/lib/github_api/constants.rb
+++ b/lib/github_api/constants.rb
@@ -54,9 +54,6 @@ module Github
PARAM_START_PAGE = "start_page".freeze
- # URI parsing
- QUERY_STR_SEP = '?'.freeze
-
end # Constants
end # Github
diff --git a/lib/github_api/page_iterator.rb b/lib/github_api/page_iterator.rb
index <HASH>..<HASH> 100644
--- a/lib/github_api/page_iterator.rb
+++ b/lib/github_api/page_iterator.rb
@@ -28,7 +28,7 @@ module Github
return nil unless first_page_uri
response = if next_page < 1
- parsed_query = parse_query(first_page_uri.split(QUERY_STR_SEP).last)
+ parsed_query = parse_query(URI(first_page_uri).query)
params = {}
if parsed_query.keys.include?('sha')
params['sha'] = 'master'
@@ -49,12 +49,12 @@ module Github
return nil unless has_next?
response = if next_page < 1
- params = parse_query next_page_uri.split(QUERY_STR_SEP).last
+ params = parse_query URI(next_page_uri).query
params['sha'] = params['last_sha'] if params.keys.include?('last_sha')
params['per_page'] = parse_per_page_number(next_page_uri)
page_request URI(next_page_uri).path, params
else
- params = parse_query next_page_uri.split(QUERY_STR_SEP).last
+ params = parse_query URI(next_page_uri).query
params['page'] = parse_page_number(next_page_uri)
params['per_page'] = parse_per_page_number(next_page_uri)
page_request URI(next_page_uri).path, params
@@ -65,7 +65,7 @@ module Github
def prev
return nil unless prev_page_uri
- params = parse_query prev_page_uri.split(QUERY_STR_SEP).last
+ params = parse_query URI(prev_page_uri).query
params['page'] = parse_page_number(prev_page_uri)
params['per_page'] = parse_per_page_number(prev_page_uri)
response = page_request URI(prev_page_uri).path, params
@@ -76,7 +76,7 @@ module Github
def last
return nil unless last_page_uri
- params = parse_query last_page_uri.split(QUERY_STR_SEP).last
+ params = parse_query URI(last_page_uri).query
params['page'] = parse_page_number(last_page_uri)
params['per_page'] = parse_per_page_number(last_page_uri)
response = page_request URI(last_page_uri).path, params
@@ -91,7 +91,7 @@ module Github
# last page URI then there is only one page.
page_uri = first_page_uri || last_page_uri
return nil unless page_uri
- params = parse_query page_uri.split(QUERY_STR_SEP).last
+ params = parse_query URI(page_uri).query
params['page'] = page_number
params['per_page'] = parse_per_page_number(page_uri)
response = page_request URI(page_uri).path, params | also use the URI module to parse query strings | piotrmurach_github | train |
ab795506938ca943d2e1552fb0c48308c4d1db89 | diff --git a/raft/raft.go b/raft/raft.go
index <HASH>..<HASH> 100644
--- a/raft/raft.go
+++ b/raft/raft.go
@@ -305,7 +305,7 @@ func (sm *stateMachine) Step(m Message) {
sm.lead = sm.addr
sm.sendAppend()
case len(sm.votes) - gr:
- sm.state = stateFollower
+ sm.becomeFollower(sm.term, none)
}
}
case stateFollower: | raft: use becomeFollower in cadidate state | etcd-io_etcd | train |
a20d1ba7f524eb3aa4a1e4a30b2cf94c9d47581f | diff --git a/test/transport/test_algorithms.rb b/test/transport/test_algorithms.rb
index <HASH>..<HASH> 100644
--- a/test/transport/test_algorithms.rb
+++ b/test/transport/test_algorithms.rb
@@ -46,7 +46,9 @@ module Transport
end
def test_constructor_with_known_hosts_reporting_known_host_key_should_use_that_host_key_type
- Net::SSH::KnownHosts.expects(:search_for).with("net.ssh.test,127.0.0.1", {}).returns([stub("key", ssh_type: "ssh-dss")])
+ Net::SSH::KnownHosts.expects(:search_for).with("net.ssh.test,127.0.0.1", {
+ user_known_hosts_file: "/dev/null", global_known_hosts_file: "/dev/null"
+ }).returns([stub("key", ssh_type: "ssh-dss")])
assert_equal %w[ssh-dss] + ed_ec_host_keys + %w[[email protected] [email protected] ssh-rsa rsa-sha2-256 rsa-sha2-512], algorithms[:host_key]
end
@@ -438,7 +440,10 @@ module Transport
end
def transport(transport_options={})
- @transport ||= MockTransport.new(transport_options)
+ @transport ||= MockTransport.new(
+ {user_known_hosts_file: '/dev/null',
+ global_known_hosts_file: '/dev/null'}.merge(transport_options)
+ )
end
end
end | test_algorithm should not depeng on known host file contents | net-ssh_net-ssh | train |
137af244ee561bd350797c8ce6e159fbd46b6a02 | diff --git a/mount_test.go b/mount_test.go
index <HASH>..<HASH> 100644
--- a/mount_test.go
+++ b/mount_test.go
@@ -8,6 +8,41 @@ import (
"testing"
)
+// Look for inconsistencies in a store.
+func healthCheck(store *Store) error {
+ parents := make(map[string]bool)
+ paths, err := store.Paths()
+ if err != nil {
+ return err
+ }
+ for _, path := range paths {
+ images, err := store.List(path)
+ if err != nil {
+ return err
+ }
+ IDs := make(map[string]bool) // All IDs for this path
+ for _, img := range images {
+ // Check for duplicate IDs per path
+ if _, exists := IDs[img.Id]; exists {
+ return errors.New(fmt.Sprintf("Duplicate ID: %s", img.Id))
+ } else {
+ IDs[img.Id] = true
+ }
+ // Store parent for 2nd pass
+ if parent := img.Parent; parent != "" {
+ parents[parent] = true
+ }
+ }
+ }
+ // Check non-existing parents
+ for parent := range parents {
+ if _, exists := parents[parent]; !exists {
+ return errors.New("Reference to non-registered parent: " + parent)
+ }
+ }
+ return nil
+}
+
// Note: This test is in the docker package because he needs to be run as root
func TestMount(t *testing.T) {
dir, err := ioutil.TempDir("", "docker-fs-test-mount")
@@ -73,7 +108,7 @@ func TestMount(t *testing.T) {
t.Fatal("Wrong number of mountpoints registered (should be %d, not %d)", 0, len(mps))
}
// General health check
- // if err := healthCheck(store); err != nil {
- // t.Fatal(err)
- // }
+ if err := healthCheck(store); err != nil {
+ t.Fatal(err)
+ }
} | Add the health check to mount_test | containers_storage | train |
27f30ff6d5acaf267e031f87ebe15f96cd88d9c3 | diff --git a/translator/src/main/java/com/google/devtools/j2objc/translate/NilCheckResolver.java b/translator/src/main/java/com/google/devtools/j2objc/translate/NilCheckResolver.java
index <HASH>..<HASH> 100644
--- a/translator/src/main/java/com/google/devtools/j2objc/translate/NilCheckResolver.java
+++ b/translator/src/main/java/com/google/devtools/j2objc/translate/NilCheckResolver.java
@@ -119,6 +119,19 @@ public class NilCheckResolver extends ErrorReportingASTVisitor {
if (!needsNilCheck(node.getQualifier())) {
return true;
}
+
+ // Instance references to static fields don't need to be nil-checked.
+ // This is true in Java (surprisingly), where instance.FIELD returns
+ // FIELD even when instance is null.
+ IBinding binding = Types.getBinding(node);
+ if (binding instanceof IVariableBinding &&
+ BindingUtil.isStatic((IVariableBinding) binding)) {
+ IBinding qualifierBinding = Types.getBinding(node.getQualifier());
+ if (qualifierBinding instanceof IVariableBinding &&
+ !BindingUtil.isStatic((IVariableBinding) qualifierBinding))
+ return true;
+ }
+
// We can't substitute the qualifier with a nil_chk because it must have a
// Name type, so we have to convert to a FieldAccess node.
FieldAccess newNode = convertToFieldAccess(node);
diff --git a/translator/src/test/java/com/google/devtools/j2objc/gen/StatementGeneratorTest.java b/translator/src/test/java/com/google/devtools/j2objc/gen/StatementGeneratorTest.java
index <HASH>..<HASH> 100644
--- a/translator/src/test/java/com/google/devtools/j2objc/gen/StatementGeneratorTest.java
+++ b/translator/src/test/java/com/google/devtools/j2objc/gen/StatementGeneratorTest.java
@@ -782,6 +782,15 @@ public class StatementGeneratorTest extends GenerationTest {
assertEquals(result, "double d = JavaLangDouble_POSITIVE_INFINITY;");
}
+ public void testInstanceStaticConstants() throws IOException {
+ String translation = translateSourceFile(
+ "public class Test { Foo f; void test() { int i = f.DEFAULT; Object lock = f.LOCK; }} " +
+ "class Foo { public static final int DEFAULT = 1; " +
+ " public static final Object LOCK = null; }", "Test", "Test.m");
+ assertTranslation(translation, "int i = Foo_DEFAULT;");
+ assertTranslation(translation, "id lock = [Foo LOCK];");
+ }
+
public void testCastGenericReturnType() throws IOException {
String translation = translateSourceFile(
"class Test { " + | Skip nil-check generation for static field references from instances. | google_j2objc | train |
5e9889c3bb2b4e0d99899b1b58a3f3eb1f19c6a5 | diff --git a/tests/test_getters.py b/tests/test_getters.py
index <HASH>..<HASH> 100755
--- a/tests/test_getters.py
+++ b/tests/test_getters.py
@@ -12,10 +12,6 @@ from marcxml_parser import MARCXMLQuery
from test_parser import unix_file
-# Variables ===================================================================
-
-
-
# Functions & classes =========================================================
@pytest.fixture
def parsed(): | #7: Removed unused `Variables` field. | edeposit_marcxml_parser | train |
4a29094ccb96ecd75f52348e0f9c15df8ccda02f | diff --git a/spring-cloud-sleuth-instrumentation/src/main/java/org/springframework/cloud/sleuth/instrument/jdbc/TraceListenerStrategy.java b/spring-cloud-sleuth-instrumentation/src/main/java/org/springframework/cloud/sleuth/instrument/jdbc/TraceListenerStrategy.java
index <HASH>..<HASH> 100644
--- a/spring-cloud-sleuth-instrumentation/src/main/java/org/springframework/cloud/sleuth/instrument/jdbc/TraceListenerStrategy.java
+++ b/spring-cloud-sleuth-instrumentation/src/main/java/org/springframework/cloud/sleuth/instrument/jdbc/TraceListenerStrategy.java
@@ -20,6 +20,7 @@ import java.net.URI;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
+import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -73,6 +74,10 @@ class TraceListenerStrategy<CON, STMT, RS> {
// string.
private static final Pattern URL_SERVICE_NAME_FINDER = Pattern.compile("sleuthServiceName=(.*?)(?:&|$)");
+ private static final String DEFAULT_SPAN_NAME = "query";
+
+ private static final List<String> KNOWN_SPAN_NAMES = Arrays.asList("select", "insert", "update", "delete");
+
private final Map<CON, ConnectionInfo> openConnections = new ConcurrentHashMap<>();
private final ThreadLocal<ConnectionInfo> currentConnection = new ThreadLocal<>();
@@ -429,7 +434,15 @@ class TraceListenerStrategy<CON, STMT, RS> {
}
private String spanName(String sql) {
- return sql.substring(0, sql.indexOf(' ')).toLowerCase(Locale.ROOT);
+ String lowercaseSql = sql.toLowerCase(Locale.ROOT);
+ String spanName = DEFAULT_SPAN_NAME;
+ for (String spanNameCandidate : KNOWN_SPAN_NAMES) {
+ if (lowercaseSql.startsWith(spanNameCandidate)) {
+ spanName = spanNameCandidate;
+ break;
+ }
+ }
+ return spanName;
}
/** | fixing issue #<I> (#<I>) | spring-cloud_spring-cloud-sleuth | train |
7344693ca81add5098973753f701585c00a447f9 | diff --git a/plugins/inputs/dns_query/dns_query.go b/plugins/inputs/dns_query/dns_query.go
index <HASH>..<HASH> 100644
--- a/plugins/inputs/dns_query/dns_query.go
+++ b/plugins/inputs/dns_query/dns_query.go
@@ -97,6 +97,8 @@ func (d *DnsQuery) Gather(acc telegraf.Accumulator) error {
}
acc.AddFields("dns_query", fields, tags)
+
+ wg.Done()
}(domain, server)
}
} | Fix hang in dns_query plugin (#<I>) | influxdata_telegraf | train |
6a1d7ac9427f73293760256af78e2178bfcf3e40 | 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
setup(name="taskc",
- version="0.0.1a2",
+ version="0.0.2a1",
packages=["taskc"],
author="Jack Laxson",
author_email="[email protected]",
diff --git a/taskc/simple.py b/taskc/simple.py
index <HASH>..<HASH> 100644
--- a/taskc/simple.py
+++ b/taskc/simple.py
@@ -54,7 +54,7 @@ class TaskdConnection(object):
if 'code' in resp:
# print errors.Status(resp['code'])
if int(resp['code']) >= 400:
- raise errors.Error(resp['code'])
+ print resp['code']
if int(resp['code']) == 200:
print "Status Good!"
return resp
@@ -79,7 +79,7 @@ class TaskdConnection(object):
tasks - taskjson list
"""
msg = transaction.mk_message(self.group, self.username, self.uuid)
- msg['payload'] = tasks
+ msg.set_payload(tasks)
msg['type'] = 'sync'
tx_msg = transaction.prep_message(msg)
self.conn.sendall(tx_msg)
diff --git a/taskc/transaction.py b/taskc/transaction.py
index <HASH>..<HASH> 100644
--- a/taskc/transaction.py
+++ b/taskc/transaction.py
@@ -4,7 +4,7 @@ from errors import TaskdError
def mk_message(org, user, key):
m = Message()
- m['client'] = "taskc-py 0.0.1a1"
+ m['client'] = "taskc-py 0.0.2"
m['protocol'] = "v1"
m['org'] = org
m['user'] = user
@@ -18,12 +18,6 @@ def prep_message(msg):
return size+msg.as_string()
-class Transaction(object):
- """ Each transaction is a single incoming message, with a single response
- message. All communication therefore consists of a single 'send', followed
- by a single 'receive', then termination."""
- pass
-
class TaskdResponse(Message):
"""docstring for TaskdResponse""" | this version actually syncs :) version bump | jrabbit_taskd-client-py | train |
940f7351933ef3dc8178c7a93d07f1f55e298fff | diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@
### Bug fixes
* Fix false positive in `Style/TrailingCommaInArguments` & `Style/TrailingCommaInLiteral` cops with consistent_comma style. ([@meganemura][])
+* [#2861](https://github.com/bbatsov/rubocop/pull/2861): Fix false positive in `Style/SpaceAroundKeyword` for `rescue(...`. ([@rrosenblum][])
## 0.37.2 (11/02/2016)
diff --git a/lib/rubocop/cop/style/space_around_keyword.rb b/lib/rubocop/cop/style/space_around_keyword.rb
index <HASH>..<HASH> 100644
--- a/lib/rubocop/cop/style/space_around_keyword.rb
+++ b/lib/rubocop/cop/style/space_around_keyword.rb
@@ -31,7 +31,7 @@ module RuboCop
DO = 'do'.freeze
ACCEPT_LEFT_PAREN =
- %w(break next not return super yield defined?).freeze
+ %w(break defined? next not rescue return super yield).freeze
def on_and(node)
check(node, [:operator].freeze) if node.keyword?
diff --git a/spec/rubocop/cop/style/space_around_keyword_spec.rb b/spec/rubocop/cop/style/space_around_keyword_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/rubocop/cop/style/space_around_keyword_spec.rb
+++ b/spec/rubocop/cop/style/space_around_keyword_spec.rb
@@ -126,6 +126,8 @@ describe RuboCop::Cop::Style::SpaceAroundKeyword do
it_behaves_like 'missing before', 'rescue', '""rescue a', '"" rescue a'
it_behaves_like 'missing after', 'rescue', 'a rescue""', 'a rescue ""'
+ it_behaves_like 'accept after', 'rescue', 'begin; rescue(Error); end',
+ 'begin; rescue(Error); end'
it_behaves_like 'missing after', 'return', 'return""', 'return ""'
it_behaves_like 'accept after', '(', 'return(1)'
it_behaves_like 'missing after', 'super', 'super""', 'super ""' | Fix false positive in SpaceAroundKeyword for rescue with a parentheses | rubocop-hq_rubocop | train |
8e0be4d7ad7db1f5bd6dafa8333851a61350bbb2 | diff --git a/src/Gn36/OoPostingApi/post.php b/src/Gn36/OoPostingApi/post.php
index <HASH>..<HASH> 100644
--- a/src/Gn36/OoPostingApi/post.php
+++ b/src/Gn36/OoPostingApi/post.php
@@ -118,7 +118,10 @@ class post extends posting_base
$post->enable_sig = $post_data['enable_sig'];
$post->post_subject = $post_data['post_subject'];
- $post->post_attachment = $post_data['post_attachment'];
+ if(isset($post_data['post_attachment']))
+ {
+ $post->post_attachment = $post_data['post_attachment'];
+ }
$post->post_edit_time = $post_data['post_edit_time'];
$post->post_edit_reason = $post_data['post_edit_reason'];
@@ -335,8 +338,11 @@ class post extends posting_base
$post_data = $this->submit_post($mode, $this->post_subject, $this->post_username, $topic_type, $poll, $sql_data);
- // Re-Read all the post data so we have correct post_id, forum_id etc.
- $this->from_array($post_data);
+
+ // Re-Read topic_id and post_id:
+ $this->topic_id = $post_data['topic_id'];
+ $this->post_id = $post_data['post_id'];
+ echo "ich bin richtig!!!";
//TODO
foreach($this->attachments as $attachment) | from_array returns a post, doesn't update... | gn36_phpbb-oo-posting-api | train |
30d0c1c7f82af083edf73ec0649dbeac6f8152d3 | diff --git a/holoviews/core/pprint.py b/holoviews/core/pprint.py
index <HASH>..<HASH> 100644
--- a/holoviews/core/pprint.py
+++ b/holoviews/core/pprint.py
@@ -66,25 +66,45 @@ class InfoPrinter(object):
obj_info = cls.object_info(obj, ansi=ansi)
heading = '%s Information' % obj.__class__.__name__
heading_ul = '='*len(heading)
- prefix = '%s\n%s\n%s\n\n%s\n\n' % (heading_ul, heading, heading_ul, obj_info)
+ prefix = '%s\n%s\n%s\n\n%s\n' % (heading_ul, heading, heading_ul, obj_info)
if category == 'options':
info = cls.options_info(obj, plot_class, ansi)
elif category == 'indexing':
info = cls.indexing_info(obj, ansi)
elif category == 'object':
- info = cls.object_params(obj, ansi)
+ info = cls.object_params(obj, no_heading=True, ansi=ansi)
elif category == 'all':
info = "\n".join([cls.indexing_info(obj, ansi), '',
+ cls.object_params(obj, no_heading=False, ansi=ansi), '',
cls.options_info(obj, plot_class, ansi)])
return prefix + info
@classmethod
def indexing_info(cls, obj, ansi=False):
- return '\n'.join([cls.heading('Indexing Structure', ansi=ansi), '', repr(obj)])
+ return '\n'.join(['', cls.heading('Indexing', ansi=ansi), '', repr(obj)])
+
+ @classmethod
+ def object_params(cls, obj, no_heading=False, ansi=False):
+ obj_name = obj.__class__.__name__
+ element = not getattr(obj, '_deep_indexable', False)
+ url = ('https://ioam.github.io/holoviews/Tutorials/Elements.html#{obj}'
+ if element else 'https://ioam.github.io/holoviews/Tutorials/Containers.html#{obj}')
+ link = url.format(obj=obj_name)
+
+ msg = ("\nMore extensive reference may be accessed using help({obj})"
+ + " (or {obj}? in IPython)."
+ + '\n\nSee {link} for an example of how to use {obj}.\n')
+
+ param_info = cls.get_parameter_info(obj, ansi=ansi)
+ info = [ msg.format(obj=obj_name, link=link),
+ cls.heading('%s Parameters' % obj_name,
+ char='-', level=1, ansi=ansi),
+ '', param_info]
+ return '\n'.join(([] if no_heading else [cls.heading('%s Object' % obj_name, ansi=ansi)]) + info)
@classmethod
def object_info(cls, obj, ansi=False):
- (count, key_dims, val_dims) = ('N/A', [], [])
+ (count, key_dims, val_dims) = (1, [], [])
if hasattr(obj, 'key_dimensions'):
key_dims = [d.name for d in obj.key_dimensions]
if hasattr(obj, 'value_dimensions'):
@@ -110,7 +130,7 @@ class InfoPrinter(object):
param_info = cls.get_parameter_info(plot_class, ansi=ansi)
param_heading = '\nPlot options [%s]:' % plot_class.name
- return '\n'.join([ cls.heading('Options', ansi=ansi), '',
+ return '\n'.join([ '', cls.heading('Options', ansi=ansi), '',
cls.heading(style_heading, char=None, level=1, ansi=ansi),
style_msg,
cls.heading(param_heading, char=None, level=1, ansi=ansi),
diff --git a/holoviews/ipython/magics.py b/holoviews/ipython/magics.py
index <HASH>..<HASH> 100644
--- a/holoviews/ipython/magics.py
+++ b/holoviews/ipython/magics.py
@@ -174,7 +174,7 @@ class OutputMagic(OptionsMagic):
('dpi' , 72),
('charwidth' , 80),
('filename' , None),
- ('info' , 'disabled')])
+ ('info' , 'none')])
options = OrderedDict(defaults.items()) | Added 'object' option for info in OutputMagic | pyviz_holoviews | train |
90438fead8e3430ca012714d98c4298ec744a1f6 | diff --git a/Command/LoadDataFixturesDoctrineODMCommand.php b/Command/LoadDataFixturesDoctrineODMCommand.php
index <HASH>..<HASH> 100644
--- a/Command/LoadDataFixturesDoctrineODMCommand.php
+++ b/Command/LoadDataFixturesDoctrineODMCommand.php
@@ -72,6 +72,8 @@ EOT
}
}
+ $paths = array_filter($paths, 'is_dir');
+
$loader = new \Doctrine\Common\DataFixtures\Loader();
foreach ($paths as $path) {
$loader->loadFromDirectory($path); | [DoctrineMongoDBBundle] fixed merge problem | doctrine_DoctrineMongoDBBundle | train |
c326818ca6175dd88bdc904463c87a0dd7ec1f5f | diff --git a/raiden/tests/smart_contracts/netting_channel/test_withdraw.py b/raiden/tests/smart_contracts/netting_channel/test_withdraw.py
index <HASH>..<HASH> 100644
--- a/raiden/tests/smart_contracts/netting_channel/test_withdraw.py
+++ b/raiden/tests/smart_contracts/netting_channel/test_withdraw.py
@@ -362,6 +362,7 @@ def test_withdraw_fails_with_partial_merkle_proof(
direct_transfer = make_direct_transfer(
nonce=nonce,
locksroot=merkle_tree.merkleroot,
+ recipient=privatekey_to_address(pkey1)
)
address = privatekey_to_address(pkey0)
@@ -412,6 +413,7 @@ def test_withdraw_tampered_merkle_proof(tree, tester_channels, tester_state, set
direct_transfer = make_direct_transfer(
nonce=nonce,
locksroot=merkle_tree.merkleroot,
+ recipient=privatekey_to_address(pkey1)
)
address = privatekey_to_address(pkey0)
@@ -474,6 +476,7 @@ def test_withdraw_tampered_lock_amount(
nonce=nonce,
locksroot=merkle_tree.merkleroot,
token=tester_token.address,
+ recipient=privatekey_to_address(pkey1)
)
address = privatekey_to_address(pkey0) | Fix tests affected by adding the recipient check | raiden-network_raiden | train |
38962bcdefd16ce14f03125adae4ad677556f6e2 | diff --git a/js/forum/dist/extension.js b/js/forum/dist/extension.js
index <HASH>..<HASH> 100644
--- a/js/forum/dist/extension.js
+++ b/js/forum/dist/extension.js
@@ -1,7 +1,7 @@
'use strict';
-System.register('flarum/approval/main', ['flarum/extend', 'flarum/app', 'flarum/models/Discussion', 'flarum/models/Post', 'flarum/components/Badge', 'flarum/components/DiscussionListItem', 'flarum/components/CommentPost', 'flarum/components/Button', 'flarum/utils/PostControls'], function (_export, _context) {
- var extend, override, app, Discussion, Post, Badge, DiscussionListItem, CommentPost, Button, PostControls;
+System.register('flarum/approval/main', ['flarum/extend', 'flarum/app', 'flarum/models/Discussion', 'flarum/models/Post', 'flarum/components/Badge', 'flarum/components/DiscussionListItem', 'flarum/components/Post', 'flarum/components/CommentPost', 'flarum/components/Button', 'flarum/utils/PostControls'], function (_export, _context) {
+ var extend, override, app, Discussion, Post, Badge, DiscussionListItem, PostComponent, CommentPost, Button, PostControls;
return {
setters: [function (_flarumExtend) {
extend = _flarumExtend.extend;
@@ -16,6 +16,8 @@ System.register('flarum/approval/main', ['flarum/extend', 'flarum/app', 'flarum/
Badge = _flarumComponentsBadge.default;
}, function (_flarumComponentsDiscussionListItem) {
DiscussionListItem = _flarumComponentsDiscussionListItem.default;
+ }, function (_flarumComponentsPost) {
+ PostComponent = _flarumComponentsPost.default;
}, function (_flarumComponentsCommentPost) {
CommentPost = _flarumComponentsCommentPost.default;
}, function (_flarumComponentsButton) {
@@ -44,9 +46,9 @@ System.register('flarum/approval/main', ['flarum/extend', 'flarum/app', 'flarum/
}
});
- extend(CommentPost.prototype, 'attrs', function (attrs) {
- if (!this.props.post.isApproved() && !this.props.post.isHidden()) {
- attrs.className += ' CommentPost--unapproved';
+ extend(PostComponent.prototype, 'attrs', function (attrs) {
+ if (!this.props.post.isApproved()) {
+ attrs.className += ' Post--unapproved';
}
});
@@ -56,7 +58,7 @@ System.register('flarum/approval/main', ['flarum/extend', 'flarum/app', 'flarum/
}
});
- override(CommentPost.prototype, 'flagReason', function (original, flag) {
+ override(PostComponent.prototype, 'flagReason', function (original, flag) {
if (flag.type() === 'approval') {
return app.translator.trans('flarum-approval.forum.post.awaiting_approval_text');
}
diff --git a/js/forum/src/main.js b/js/forum/src/main.js
index <HASH>..<HASH> 100644
--- a/js/forum/src/main.js
+++ b/js/forum/src/main.js
@@ -4,6 +4,7 @@ import Discussion from 'flarum/models/Discussion';
import Post from 'flarum/models/Post';
import Badge from 'flarum/components/Badge';
import DiscussionListItem from 'flarum/components/DiscussionListItem';
+import PostComponent from 'flarum/components/Post';
import CommentPost from 'flarum/components/CommentPost';
import Button from 'flarum/components/Button';
import PostControls from 'flarum/utils/PostControls';
@@ -27,9 +28,9 @@ app.initializers.add('flarum-approval', () => {
}
});
- extend(CommentPost.prototype, 'attrs', function(attrs) {
- if (!this.props.post.isApproved() && !this.props.post.isHidden()) {
- attrs.className += ' CommentPost--unapproved';
+ extend(PostComponent.prototype, 'attrs', function(attrs) {
+ if (!this.props.post.isApproved()) {
+ attrs.className += ' Post--unapproved';
}
});
@@ -39,7 +40,7 @@ app.initializers.add('flarum-approval', () => {
}
});
- override(CommentPost.prototype, 'flagReason', function(original, flag) {
+ override(PostComponent.prototype, 'flagReason', function(original, flag) {
if (flag.type() === 'approval') {
return app.translator.trans('flarum-approval.forum.post.awaiting_approval_text');
}
diff --git a/less/forum/extension.less b/less/forum/extension.less
index <HASH>..<HASH> 100644
--- a/less/forum/extension.less
+++ b/less/forum/extension.less
@@ -1,7 +1,8 @@
-.CommentPost--unapproved {
+.Post--unapproved {
.Post-header,
.Post-body,
- .Post-footer {
+ .EventPost-icon,
+ .EventPost-info {
opacity: 0.5;
}
} | Generalise the potential for unapproved state to all posts, rather than just comments
This is just more future-proofing, in case any other extensions introduce new post types which can be queued for approval. | flarum_approval | train |
562ce349371bc34f5d2a287811a61587b27d6b6c | diff --git a/test/unit/einhorn/client.rb b/test/unit/einhorn/client.rb
index <HASH>..<HASH> 100644
--- a/test/unit/einhorn/client.rb
+++ b/test/unit/einhorn/client.rb
@@ -15,12 +15,18 @@ class ClientTest < EinhornTestCase
"---%0A:foo:%0A- ! '%25bar'%0A- ! '%25baz'%0A\n"
end
+ def serialized_2_1
+ "---%0A:foo:%0A- \"%25bar\"%0A- \"%25baz\"%0A\n"
+ end
+
+ def serialized_options
+ [serialized_1_8, serialized_1_9, serialized_2_1]
+ end
+
describe "when sending a message" do
it "writes a serialized line" do
socket = mock
- socket.expects(:write).with do |write|
- write == serialized_1_8 || write == serialized_1_9
- end
+ socket.expects(:write).with {|write| serialized_options.include?(write)}
Einhorn::Client::Transport.send_message(socket, unserialized_message)
end
end
@@ -44,7 +50,7 @@ class ClientTest < EinhornTestCase
describe "when {de,}serializing a message" do
it "serializes and escape a message as expected" do
actual = Einhorn::Client::Transport.serialize_message(unserialized_message)
- assert(actual == serialized_1_8 || actual == serialized_1_9, "Actual message is #{actual.inspect}")
+ assert(serialized_options.include?(actual), "Actual message is #{actual.inspect}")
end
it "deserializes and unescape a 1.8-style message as expected" do | Apparently YAML serialization changed again some time between <I> and <I> | stripe_einhorn | train |
3fbc935d896c18c0f6e9764860d3c03fa219f8d9 | diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/parser/OParenthesisExpression.java b/core/src/main/java/com/orientechnologies/orient/core/sql/parser/OParenthesisExpression.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/parser/OParenthesisExpression.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/parser/OParenthesisExpression.java
@@ -57,7 +57,7 @@ public class OParenthesisExpression extends OMathExpression {
return expression.execute(iCurrentRecord, ctx);
}
if (statement != null) {
- OInternalExecutionPlan execPlan = statement.createExecutionPlan(ctx, false);
+ OInternalExecutionPlan execPlan = statement.createExecutionPlanNoCache(ctx, false);
if (execPlan instanceof OInsertExecutionPlan) {
((OInsertExecutionPlan) execPlan).executeInternal();
}
diff --git a/graphdb/src/test/java/com/orientechnologies/orient/graph/sql/OCreateEdgeStatementExecutionTest.java b/graphdb/src/test/java/com/orientechnologies/orient/graph/sql/OCreateEdgeStatementExecutionTest.java
index <HASH>..<HASH> 100644
--- a/graphdb/src/test/java/com/orientechnologies/orient/graph/sql/OCreateEdgeStatementExecutionTest.java
+++ b/graphdb/src/test/java/com/orientechnologies/orient/graph/sql/OCreateEdgeStatementExecutionTest.java
@@ -334,4 +334,27 @@ public class OCreateEdgeStatementExecutionTest {
}
}
+
+ @Test
+ public void testPositionalParams() {
+
+ String vClass1 = "testPositionalParamsV";
+ db.createVertexClass(vClass1);
+
+ String eClass = "testPositionalParamsE";
+ db.createEdgeClass(eClass);
+
+ for (int i = 0; i < 2; i++) {
+ OVertex v1 = db.newVertex(vClass1);
+ v1.setProperty("name", "v" + i);
+ v1.save();
+ }
+
+ db.command("CREATE EDGE " + eClass + " from (select from " + vClass1 + " WHERE name = ? ) to (select from " + vClass1
+ + " WHERE name = ? )", "v0", "v1").close();
+
+ OResultSet result = db.query("select from " + eClass + " where out.name = 'v0' AND in.name = 'v1'");
+ Assert.assertTrue(result.hasNext());
+ result.close();
+ }
} | Fix usage of positional parameters in subqueries
(too much aggressive usage of the execution plan cache)
Resolves: #<I> | orientechnologies_orientdb | train |
f26af746e718fd04de92f22aa33bc81b0fb02838 | diff --git a/src/XeroPHP/Models/Accounting/Invoice.php b/src/XeroPHP/Models/Accounting/Invoice.php
index <HASH>..<HASH> 100644
--- a/src/XeroPHP/Models/Accounting/Invoice.php
+++ b/src/XeroPHP/Models/Accounting/Invoice.php
@@ -785,5 +785,46 @@ class Invoice extends Remote\Object
}
+ /**
+ * Retrieve the online invoice URL.
+ *
+ * @return string
+ * @throws \XeroPHP\Exception
+ */
+ public function getOnlineInvoiceUrl()
+ {
+ if (!$this->hasGUID()) {
+ throw new Exception('Unable to retrieve the online invoice URL as the invoice has no GUID');
+ }
+
+ return $this->onlineInvoiceRequest()
+ ->send()
+ ->getElements()[0]['OnlineInvoiceUrl'];
+ }
+
+ /**
+ * Build the online invoice request object.
+ *
+ * @return \XeroPHP\Remote\Request
+ */
+ protected function onlineInvoiceRequest()
+ {
+ return new Remote\Request(
+ $this->_application, $this->onlineInvoiceRemoteUrl()
+ );
+ }
+
+ /**
+ * Build the online invoice URL object.
+ *
+ * @return \XeroPHP\Remote\URL
+ */
+ protected function onlineInvoiceRemoteUrl()
+ {
+ return new Remote\URL(
+ $this->_application, 'Invoices/'.$this->getGUID().'/OnlineInvoice'
+ );
+ }
+
} | add ability to get the online invoice url [#<I>] | calcinai_xero-php | train |
59fddc446f9614605fe7b614a1db03a0450b3f44 | diff --git a/resource_aws_s3_bucket_object.go b/resource_aws_s3_bucket_object.go
index <HASH>..<HASH> 100644
--- a/resource_aws_s3_bucket_object.go
+++ b/resource_aws_s3_bucket_object.go
@@ -4,6 +4,8 @@ import (
"fmt"
"log"
"os"
+ "io"
+ "bytes"
"github.com/hashicorp/terraform/helper/schema"
@@ -34,10 +36,18 @@ func resourceAwsS3BucketObject() *schema.Resource {
"source": &schema.Schema{
Type: schema.TypeString,
- Required: true,
+ Optional: true,
ForceNew: true,
+ ConflictsWith: []string{"content"},
},
+ "content": &schema.Schema{
+ Type: schema.TypeString,
+ Optional: true,
+ ForceNew: true,
+ ConflictsWith: []string{"source"},
+ },
+
"etag": &schema.Schema{
Type: schema.TypeString,
Computed: true,
@@ -51,19 +61,28 @@ func resourceAwsS3BucketObjectPut(d *schema.ResourceData, meta interface{}) erro
bucket := d.Get("bucket").(string)
key := d.Get("key").(string)
- source := d.Get("source").(string)
+ var body io.ReadSeeker
- file, err := os.Open(source)
+ if v, ok := d.GetOk("source"); ok {
+ source := v.(string)
+ file, err := os.Open(source)
+ if err != nil {
+ return fmt.Errorf("Error opening S3 bucket object source (%s): %s", source, err)
+ }
- if err != nil {
- return fmt.Errorf("Error opening S3 bucket object source (%s): %s", source, err)
+ body = file
+ } else if v, ok := d.GetOk("content"); ok {
+ content := v.(string)
+ body = bytes.NewReader([]byte(content))
+ } else {
+ return fmt.Errorf("Must specify \"source\" or \"content\" field")
}
resp, err := s3conn.PutObject(
&s3.PutObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
- Body: file,
+ Body: body,
})
if err != nil {
diff --git a/resource_aws_s3_bucket_object_test.go b/resource_aws_s3_bucket_object_test.go
index <HASH>..<HASH> 100644
--- a/resource_aws_s3_bucket_object_test.go
+++ b/resource_aws_s3_bucket_object_test.go
@@ -15,7 +15,7 @@ import (
var tf, err = ioutil.TempFile("", "tf")
-func TestAccAWSS3BucketObject_basic(t *testing.T) {
+func TestAccAWSS3BucketObject_source(t *testing.T) {
// first write some data to the tempfile just so it's not 0 bytes.
ioutil.WriteFile(tf.Name(), []byte("{anything will do }"), 0644)
resource.Test(t, resource.TestCase{
@@ -29,7 +29,26 @@ func TestAccAWSS3BucketObject_basic(t *testing.T) {
CheckDestroy: testAccCheckAWSS3BucketObjectDestroy,
Steps: []resource.TestStep{
resource.TestStep{
- Config: testAccAWSS3BucketObjectConfig,
+ Config: testAccAWSS3BucketObjectConfigSource,
+ Check: testAccCheckAWSS3BucketObjectExists("aws_s3_bucket_object.object"),
+ },
+ },
+ })
+}
+
+func TestAccAWSS3BucketObject_content(t *testing.T) {
+ resource.Test(t, resource.TestCase{
+ PreCheck: func() {
+ if err != nil {
+ panic(err)
+ }
+ testAccPreCheck(t)
+ },
+ Providers: testAccProviders,
+ CheckDestroy: testAccCheckAWSS3BucketObjectDestroy,
+ Steps: []resource.TestStep{
+ resource.TestStep{
+ Config: testAccAWSS3BucketObjectConfigContent,
Check: testAccCheckAWSS3BucketObjectExists("aws_s3_bucket_object.object"),
},
},
@@ -86,7 +105,7 @@ func testAccCheckAWSS3BucketObjectExists(n string) resource.TestCheckFunc {
}
var randomBucket = randInt
-var testAccAWSS3BucketObjectConfig = fmt.Sprintf(`
+var testAccAWSS3BucketObjectConfigSource = fmt.Sprintf(`
resource "aws_s3_bucket" "object_bucket" {
bucket = "tf-object-test-bucket-%d"
}
@@ -97,3 +116,17 @@ resource "aws_s3_bucket_object" "object" {
source = "%s"
}
`, randomBucket, tf.Name())
+
+
+var testAccAWSS3BucketObjectConfigContent = fmt.Sprintf(`
+resource "aws_s3_bucket" "object_bucket" {
+ bucket = "tf-object-test-bucket-%d"
+}
+
+resource "aws_s3_bucket_object" "object" {
+ bucket = "${aws_s3_bucket.object_bucket.bucket}"
+ key = "test-key"
+ content = "some_bucket_content"
+}
+`, randomBucket)
+ | adding content field to s3_bucket_object | terraform-providers_terraform-provider-aws | train |
07fd293223905fdda7298b9330399fa0da365b41 | diff --git a/xmlnuke-php5/bin/com.xmlnuke/net.oauthclient.class.php b/xmlnuke-php5/bin/com.xmlnuke/net.oauthclient.class.php
index <HASH>..<HASH> 100644
--- a/xmlnuke-php5/bin/com.xmlnuke/net.oauthclient.class.php
+++ b/xmlnuke-php5/bin/com.xmlnuke/net.oauthclient.class.php
@@ -79,38 +79,62 @@ class OAuthClient
protected function getVar($name)
{
- $name = $this->_appName . '_' . $name;
-
- if (!$this->_saveToUser)
- {
- return $this->_context->getSession($name);
- }
- else
- {
- return $this->_user->getField($name);
- }
+ $name = $this->_appName . '_' . $name;
+ return $this->_context->getSession($name);
}
- protected function setVar($name, $value, $save = false)
+ protected function setVar($name, $value)
{
$name = $this->_appName . '_' . $name;
+ return $this->_context->setSession($name, $value);
+ }
- if (!$this->_saveToUser || !$save)
+ protected function getAccessToken()
+ {
+ if ($this->_saveToUser)
{
- return $this->_context->setSession($name, $value);
+ $names = array('oauth_access_token', 'oauth_access_token_secret');
+ $users = $this->_context->getUsersDatabase();
+
+ $this->_user = $users->getUserName($this->_saveToUser);
+
+ foreach ($names as $name)
+ {
+ $field = $this->_appName . '_' . $name;
+ $value = $this->_user->getField($field);
+ if ($value == "")
+ return; // Abort
+ $this->setVar($name, $value);
+ }
+
+ $this->setVar("oauth_state", "returned");
}
- else
+ }
+
+ protected function saveAccessToken()
+ {
+ if ($this->_saveToUser)
{
+ $names = array('oauth_access_token', 'oauth_access_token_secret');
$users = $this->_context->getUsersDatabase();
- $users->removePropertyValueFromUser($sr->getField($this->_UserTable->Id), null, $name);
- $users->addPropertyValueToUser($sr->getField($this->_UserTable->Id), $value, $name);
+
+ foreach ($names as $name)
+ {
+ $field = $this->_appName . '_' . $name;
+ $users->removePropertyValueFromUser($this->_user->getField($users->_UserTable->Id), null, $field);
+ $users->addPropertyValueToUser($this->_user->getField($users->_UserTable->Id), $this->getVar($name), $field);
+ }
+
+ $this->_user = $users->getUserName($this->_saveToUser);
}
}
public function handle()
{
+ $this->getAccessToken();
+
$state = $this->getVar('oauth_state');
-
+
/* If oauth_token is missing get it */
if ($this->_context->ContextValue('oauth_token') != "" && $state === 'start')
{/*{{{*/
@@ -151,8 +175,9 @@ class OAuthClient
$tok = $to->getAccessToken();
/* Save the access tokens. Normally these would be saved in a database for future use. */
- $this->setVar('oauth_access_token', $tok['oauth_token'], true);
- $this->setVar('oauth_access_token_secret', $tok['oauth_token_secret'], true);
+ $this->setVar('oauth_access_token', $tok['oauth_token']);
+ $this->setVar('oauth_access_token_secret', $tok['oauth_token_secret']);
+ $this->saveAccessToken();
}
/* Create TwitterOAuth with app key/secret and user access key/secret */ | Changes in OAuthClient to save the access token in the profile | byjg_xmlnuke | train |
f048c4f0c4502d95045f50b2313f429216001361 | diff --git a/tests.go b/tests.go
index <HASH>..<HASH> 100644
--- a/tests.go
+++ b/tests.go
@@ -7,6 +7,7 @@ import (
"net/http"
"net/url"
"strings"
+ "code.google.com/p/go.net/websocket"
)
type TestSuite struct {
@@ -23,14 +24,23 @@ func NewTestSuite() TestSuite {
return TestSuite{Client: &http.Client{}}
}
-// Return the base URL of the server, e.g. "http://127.0.0.1:8557"
-func (t *TestSuite) BaseUrl() string {
+// Return the address and port of the server, e.g. "127.0.0.1:8557"
+func (t *TestSuite) AddrAndPort() string {
if Server.Addr[0] == ':' {
- return "http://127.0.0.1" + Server.Addr
+ return "127.0.0.1" + Server.Addr
}
- return "http://" + Server.Addr
+ return Server.Addr
}
+// Return the base http URL of the server, e.g. "http://127.0.0.1:8557"
+func (t *TestSuite) BaseUrl() string {
+ return "http://" + t.AddrAndPort()
+}
+
+// Return the base websocket URL of the server, e.g. "ws://127.0.0.1:8557"
+func (t *TestSuite) WebSocketUrl() string {
+ return "ws://" + t.AddrAndPort()
+}
// Issue a GET request to the given path and store the result in Request and
// RequestBody.
func (t *TestSuite) Get(path string) {
@@ -70,6 +80,17 @@ func (t *TestSuite) MakeRequest(req *http.Request) {
}
}
+// Create a websocket connection to the given path and return the connection
+func (t *TestSuite) WebSocket(path string) *websocket.Conn{
+ origin := t.BaseUrl() + "/"
+ url := t.WebSocketUrl() + path
+ ws, err := websocket.Dial(url, "", origin)
+ if err != nil {
+ panic(err)
+ }
+ return ws
+}
+
func (t *TestSuite) AssertOk() {
t.AssertStatus(http.StatusOK)
} | adding a test method to create a websocket connection | revel_revel | train |
a0ce4c453c53ba9e9ee5b29e58f854fa48e516ea | diff --git a/src/Database/Schema/PostgresSchema.php b/src/Database/Schema/PostgresSchema.php
index <HASH>..<HASH> 100644
--- a/src/Database/Schema/PostgresSchema.php
+++ b/src/Database/Schema/PostgresSchema.php
@@ -46,6 +46,8 @@ class PostgresSchema extends BaseSchema
c.collation_name,
d.description as comment,
ordinal_position,
+ c.numeric_precision as column_precision,
+ c.numeric_scale as column_scale,
pg_get_serial_sequence(attr.attrelid::regclass::text, attr.attname) IS NOT NULL AS has_serial
FROM information_schema.columns c
INNER JOIN pg_catalog.pg_namespace ns ON (ns.nspname = table_schema)
@@ -158,6 +160,7 @@ class PostgresSchema extends BaseSchema
if (!empty($row['has_serial'])) {
$field['autoIncrement'] = true;
}
+
$field += [
'default' => $this->_defaultValue($row['default']),
'null' => $row['null'] === 'YES' ? true : false,
@@ -165,6 +168,11 @@ class PostgresSchema extends BaseSchema
'comment' => $row['comment']
];
$field['length'] = $row['char_length'] ?: $field['length'];
+
+ if ($field['type'] === 'numeric' || $field['type'] === 'decimal') {
+ $field['length'] = $row['column_precision'];
+ $field['precision'] = $row['column_scale'] ? $row['column_scale'] : null;
+ }
$table->addColumn($row['name'], $field);
}
diff --git a/tests/TestCase/Database/Schema/PostgresSchemaTest.php b/tests/TestCase/Database/Schema/PostgresSchemaTest.php
index <HASH>..<HASH> 100644
--- a/tests/TestCase/Database/Schema/PostgresSchemaTest.php
+++ b/tests/TestCase/Database/Schema/PostgresSchemaTest.php
@@ -75,6 +75,8 @@ published BOOLEAN DEFAULT false,
views SMALLINT DEFAULT 0,
readingtime TIME,
data JSONB,
+average_note DECIMAL(4,2),
+average_income NUMERIC(10,2),
created TIMESTAMP,
CONSTRAINT "content_idx" UNIQUE ("title", "body"),
CONSTRAINT "author_idx" FOREIGN KEY ("author_id") REFERENCES "schema_authors" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
@@ -139,11 +141,11 @@ SQL;
// Decimal
[
'NUMERIC',
- ['type' => 'decimal', 'length' => null]
+ ['type' => 'decimal', 'length' => null, 'precision' => null]
],
[
'DECIMAL(10,2)',
- ['type' => 'decimal', 'length' => null]
+ ['type' => 'decimal', 'length' => 10, 'precision' => 2]
],
// String
[
@@ -228,6 +230,8 @@ SQL;
'default' => 'Default value',
'comment' => 'Comment section',
'char_length' => null,
+ 'column_precision' => null,
+ 'column_scale' => null,
'collation_name' => 'ja_JP.utf8',
];
$expected += [
@@ -237,6 +241,11 @@ SQL;
'collate' => 'ja_JP.utf8',
];
+ if ($field['type'] === 'NUMERIC' || strpos($field['type'], 'DECIMAL') !== false) {
+ $field['column_precision'] = $expected['length'];
+ $field['column_scale'] = $expected['precision'];
+ }
+
$driver = $this->getMockBuilder('Cake\Database\Driver\Postgres')->getMock();
$dialect = new PostgresSchema($driver);
@@ -367,6 +376,24 @@ SQL;
'precision' => null,
'comment' => null,
],
+ 'average_note' => [
+ 'type' => 'decimal',
+ 'null' => true,
+ 'default' => null,
+ 'length' => 4,
+ 'precision' => 2,
+ 'unsigned' => null,
+ 'comment' => null,
+ ],
+ 'average_income' => [
+ 'type' => 'decimal',
+ 'null' => true,
+ 'default' => null,
+ 'length' => 10,
+ 'precision' => 2,
+ 'unsigned' => null,
+ 'comment' => null,
+ ],
'created' => [
'type' => 'timestamp',
'null' => true, | Improve support for `decimal` type in Postgres schema management | cakephp_cakephp | train |
af9f770146d7fe7783c610b2a6452f98168ac6fb | diff --git a/pefile.py b/pefile.py
index <HASH>..<HASH> 100644
--- a/pefile.py
+++ b/pefile.py
@@ -31,7 +31,7 @@ from builtins import str
from builtins import zip
__author__ = 'Ero Carrera'
-__version__ = '2017.8.1'
+__version__ = '2017.9.3'
__contact__ = '[email protected]'
import os
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -83,7 +83,7 @@ setup(name = 'pefile',
author = _read_attr('__author__'),
author_email = _read_attr('__contact__'),
url = 'https://github.com/erocarrera/pefile',
- download_url='https://github.com/erocarrera/pefile/releases/download/v2017.8.1/pefile-2017.8.1.tar.gz',
+ download_url='https://github.com/erocarrera/pefile/releases/download/v2017.9.3/pefile-2017.9.3.tar.gz',
keywords = ['pe', 'exe', 'dll', 'pefile', 'pecoff'],
classifiers = [
'Development Status :: 5 - Production/Stable', | Updated version, preparing for release. | erocarrera_pefile | train |
2bd3ed4d007cd3f9158a6652c3d28503141f0da7 | diff --git a/stdlib/source_map/map.rb b/stdlib/source_map/map.rb
index <HASH>..<HASH> 100644
--- a/stdlib/source_map/map.rb
+++ b/stdlib/source_map/map.rb
@@ -193,7 +193,7 @@ module SourceMap
sources_index = Hash[sources.each_with_index.to_a]
names_index = Hash[names.each_with_index.to_a]
- ary = (1..by_lines.keys.max).map do |line|
+ ary = (1..(by_lines.keys.max || 1)).map do |line|
generated_column = 0
(by_lines[line] || []).map do |mapping| | Backport maccman/sourcemap#<I> | opal_opal | train |
8b0031be778eb4fc5b77f595648e620ad438fc7b | diff --git a/python/dllib/src/bigdl/dllib/utils/nncontext.py b/python/dllib/src/bigdl/dllib/utils/nncontext.py
index <HASH>..<HASH> 100644
--- a/python/dllib/src/bigdl/dllib/utils/nncontext.py
+++ b/python/dllib/src/bigdl/dllib/utils/nncontext.py
@@ -335,10 +335,11 @@ def init_nncontext(conf=None, spark_log_level="WARN", redirect_spark_log=True):
:return: An instance of SparkContext.
"""
+ has_activate_sc = SparkContext._active_spark_context is not None
# The following code copied and modified from
# https://github.com/Valassis-Digital-Media/spylon-kernel/blob/master/
# spylon_kernel/scala_interpreter.py
- if ZooContext.log_output:
+ if ZooContext.log_output and not has_activate_sc:
import subprocess
import pyspark.java_gateway
spark_jvm_proc = None
@@ -367,7 +368,7 @@ def init_nncontext(conf=None, spark_log_level="WARN", redirect_spark_log=True):
sc = getOrCreateSparkContext(conf=conf)
sc.setLogLevel(spark_log_level)
- if ZooContext.log_output:
+ if ZooContext.log_output and not has_activate_sc:
if spark_jvm_proc.stdout is not None:
stdout_reader = threading.Thread(target=_read_stream,
daemon=True, | fix log_output logic called twice (#<I>) | intel-analytics_BigDL | train |
121ac88b45ba7469c48ad0071bbe27e7a6b0e176 | diff --git a/lib/mongoid/relations/embedded/one.rb b/lib/mongoid/relations/embedded/one.rb
index <HASH>..<HASH> 100644
--- a/lib/mongoid/relations/embedded/one.rb
+++ b/lib/mongoid/relations/embedded/one.rb
@@ -38,7 +38,7 @@ module Mongoid
def substitute(replacement)
if replacement != self
if _assigning?
- base.add_atomic_unset(target)
+ base.add_atomic_unset(target) unless replacement
else
target.destroy if persistable?
end
diff --git a/spec/mongoid/persistence_spec.rb b/spec/mongoid/persistence_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/mongoid/persistence_spec.rb
+++ b/spec/mongoid/persistence_spec.rb
@@ -1244,6 +1244,33 @@ describe Mongoid::Persistence do
context "when passing in a relation" do
+ context "when providing an embedded child" do
+
+ let!(:person) do
+ Person.create
+ end
+
+ let!(:name) do
+ person.create_name(first_name: "test", last_name: "user")
+ end
+
+ let(:new_name) do
+ Name.new(first_name: "Rupert", last_name: "Parkes")
+ end
+
+ before do
+ person.update_attributes(name: new_name)
+ end
+
+ it "updates the embedded document" do
+ person.name.should eq(new_name)
+ end
+
+ it "persists the changes" do
+ person.reload.name.should eq(new_name)
+ end
+ end
+
context "when providing a parent to a referenced in" do
let!(:person) do | No more duplicate $unset/$set with embeds_one.
[ fix mongoid/moped#<I> ] | mongodb_mongoid | train |
4c05d27bcf6031b424a00cdaf4b302a90cdfc1cb | diff --git a/src/ScaffoldPackageCommand.php b/src/ScaffoldPackageCommand.php
index <HASH>..<HASH> 100644
--- a/src/ScaffoldPackageCommand.php
+++ b/src/ScaffoldPackageCommand.php
@@ -228,7 +228,7 @@ EOT;
'package_name' => $composer_obj['name'],
'package_short_name' => $bits[1],
'package_name_border' => str_pad( '', strlen( $composer_obj['name'] ), '=' ),
- 'package_description' => $composer_obj['description'],
+ 'package_description' => isset( $composer_obj['description'] ) ? $composer_obj['description'] : '',
'required_wp_cli_version' => ! empty( $composer_obj['require']['wp-cli/wp-cli'] ) ? str_replace( array( '~', '^', '>=' ), 'v', $composer_obj['require']['wp-cli/wp-cli'] ) : 'v0.23.0',
'shields' => '',
'has_commands' => false,
@@ -334,7 +334,7 @@ EOT;
}
$readme_sections['package_description'] = array(
- 'body' => $composer_obj['description'],
+ 'body' => isset( $composer_obj['description'] ) ? $composer_obj['description'] : '',
);
$readme_args['quick_links'] = ''; | Check composer_obj['description'] set before using. | wp-cli_scaffold-package-command | train |
bf63ddfebe80eb47f9a5e560288cb0ed446a9a87 | diff --git a/src/ol/browserfeature.js b/src/ol/browserfeature.js
index <HASH>..<HASH> 100644
--- a/src/ol/browserfeature.js
+++ b/src/ol/browserfeature.js
@@ -15,5 +15,6 @@ ol.BrowserFeature = {
* @type {boolean} True if browser supports touch events
*/
HAS_TOUCH: ol.ASSUME_TOUCH ||
- (document && 'ontouchstart' in document.documentElement)
+ (document && 'ontouchstart' in document.documentElement) ||
+ !!(window.navigator.msPointerEnabled)
}; | Test if browser supports Windows Pointer events | openlayers_openlayers | train |
486362196e42efaac76d33ca3c6726dfa16f5667 | diff --git a/lib/dice_bag/project.rb b/lib/dice_bag/project.rb
index <HASH>..<HASH> 100644
--- a/lib/dice_bag/project.rb
+++ b/lib/dice_bag/project.rb
@@ -10,18 +10,25 @@ module DiceBag
end
def self.config_files(filename)
- File.join(Dir.pwd, filename)
+ File.join(self.config_dir, filename)
+ end
+
+ # dotNet apps do not have the templates in config/ but in the root of the project
+ # TODO: detect dotNet instead of detecting rails
+ def self.config_dir
+ defined?(Rails) ? File.join(Dir.pwd, 'config') : Dir.pwd
end
#local templates always takes preference over generated templates
def self.templates_to_generate
- generated_templates = Dir[Project.config_files("**/config/*.erb")]
- custom_templates = Dir[Project.config_files("**/config/*.erb.local")]
+ generated_templates = Dir[Project.config_files("**/*.erb")]
+ custom_templates = Dir[Project.config_files("**/*.erb.local")]
dotNetTemplates = Dir[Project.config_files("**/*.config.template")]
all_files = generated_templates + custom_templates
- templates = all_files.delete_if {|file| custom_templates.include?(file + '.local')}
+ cleaned_templates = all_files.delete_if {|file| custom_templates.include?(file + '.local')}
dotNetTemplates = dotNetTemplates.delete_if {|file| file.include?("/bin/")}
- all_files + dotNetTemplates
+ cleaned_templates + dotNetTemplates
end
+
end
end
diff --git a/lib/dice_bag/template_file.rb b/lib/dice_bag/template_file.rb
index <HASH>..<HASH> 100644
--- a/lib/dice_bag/template_file.rb
+++ b/lib/dice_bag/template_file.rb
@@ -32,7 +32,7 @@ module DiceBag
return unless config_file.should_write?(contents)
config_file.write(contents)
- puts "file #{config_file.file} created"
+ puts "file #{Project.config_dir}/#{config_file.file} created"
end
end | In rails our files should go into config/ | mdsol_dice_bag | train |
c9a1dc137993a80f844e8370ea5642d2bf1cbb75 | diff --git a/src/Engines/BaseEngine.php b/src/Engines/BaseEngine.php
index <HASH>..<HASH> 100644
--- a/src/Engines/BaseEngine.php
+++ b/src/Engines/BaseEngine.php
@@ -104,6 +104,14 @@ abstract class BaseEngine implements DataTableEngineContract
* @var bool
*/
protected $autoFilter = true;
+
+ /**
+ * Select trashed records in count function for models with soft deletes trait.
+ * By default we do not select soft deleted records
+ *
+ * @var bool
+ */
+ protected $withTrashed = false;
/**
* Callback to override global search.
@@ -393,6 +401,19 @@ abstract class BaseEngine implements DataTableEngineContract
return $this;
}
+
+ /**
+ * Change withTrashed flag value.
+ *
+ * @param bool $withTrashed
+ * @return $this
+ */
+ public function withTrashed($withTrashed = true)
+ {
+ $this->withTrashed = $withTrashed;
+
+ return $this;
+ }
/**
* Allows previous API calls where the methods were snake_case.
diff --git a/src/Engines/QueryBuilderEngine.php b/src/Engines/QueryBuilderEngine.php
index <HASH>..<HASH> 100644
--- a/src/Engines/QueryBuilderEngine.php
+++ b/src/Engines/QueryBuilderEngine.php
@@ -100,6 +100,11 @@ class QueryBuilderEngine extends BaseEngine
$row_count = $this->wrap('row_count');
$myQuery->select($this->connection->raw("'1' as {$row_count}"));
}
+
+ // check for select soft deleted records
+ if (!$this->withTrashed && $this->modelUseSoftDeletes()) {
+ $myQuery->whereNull($myQuery->getModel()->getTable().'.deleted_at');
+ }
return $this->connection->table($this->connection->raw('(' . $myQuery->toSql() . ') count_row_table'))
->setBindings($myQuery->getBindings())->count();
@@ -394,7 +399,28 @@ class QueryBuilderEngine extends BaseEngine
return $this->setupKeyword($keyword);
}
-
+
+ /**
+ * Check if model use SoftDeletes trait
+ *
+ * @return boolean
+ */
+ private function modelUseSoftDeletes()
+ {
+ $app = app();
+
+ //check for laravel version
+ //in 4 and 5 versions SoftDeletes trait has a different names
+ //we can check only first number
+ if (strpos($app::VERSION, '5') === 0) {
+ $class = 'Illuminate\Database\Eloquent\SoftDeletes';
+ } else {
+ $class = 'Illuminate\Database\Eloquent\SoftDeletingTrait';
+ }
+
+ return in_array($class, class_uses($this->query->getModel()));
+ }
+
/**
* Join eager loaded relation and get the related column name.
* | support of using soft deletes trait in models | yajra_laravel-datatables | train |
354e64f4274281c0a7ddcc0525c8009c597da93b | diff --git a/service.go b/service.go
index <HASH>..<HASH> 100644
--- a/service.go
+++ b/service.go
@@ -70,12 +70,14 @@ import (
)
const (
- optionKeepAlive = "KeepAlive"
- optionKeepAliveDefault = true
- optionRunAtLoad = "RunAtLoad"
- optionRunAtLoadDefault = false
- optionUserService = "UserService"
- optionUserServiceDefault = false
+ optionKeepAlive = "KeepAlive"
+ optionKeepAliveDefault = true
+ optionRunAtLoad = "RunAtLoad"
+ optionRunAtLoadDefault = false
+ optionUserService = "UserService"
+ optionUserServiceDefault = false
+ optionSessionCreate = "SessionCreate"
+ optionSessionCreateDefault = false
)
// Config provides the setup for a Service. The Name field is required.
diff --git a/service_darwin.go b/service_darwin.go
index <HASH>..<HASH> 100644
--- a/service_darwin.go
+++ b/service_darwin.go
@@ -5,6 +5,7 @@
package service
import (
+ "errors"
"fmt"
"os"
"os/signal"
@@ -13,7 +14,6 @@ import (
"syscall"
"text/template"
"time"
- "errors"
)
const maxPathSize = 32 * 1024
@@ -134,11 +134,13 @@ func (s *darwinLaunchdService) Install() error {
Path string
KeepAlive, RunAtLoad bool
+ SessionCreate bool
}{
- Config: s.Config,
- Path: path,
- KeepAlive: s.Option.bool(optionKeepAlive, optionKeepAliveDefault),
- RunAtLoad: s.Option.bool(optionRunAtLoad, optionRunAtLoadDefault),
+ Config: s.Config,
+ Path: path,
+ KeepAlive: s.Option.bool(optionKeepAlive, optionKeepAliveDefault),
+ RunAtLoad: s.Option.bool(optionRunAtLoad, optionRunAtLoadDefault),
+ SessionCreate: s.Option.bool(optionSessionCreate, optionSessionCreateDefault),
}
functions := template.FuncMap{
@@ -229,6 +231,7 @@ var launchdConfig = `<?xml version='1.0' encoding='UTF-8'?>
{{if .UserName}}<key>UserName</key><string>{{html .UserName}}</string>{{end}}
{{if .ChRoot}}<key>RootDirectory</key><string>{{html .ChRoot}}</string>{{end}}
{{if .WorkingDirectory}}<key>WorkingDirectory</key><string>{{html .WorkingDirectory}}</string>{{end}}
+<key>SessionCreate</key><{{bool .SessionCreate}}/>
<key>KeepAlive</key><{{bool .KeepAlive}}/>
<key>RunAtLoad</key><{{bool .RunAtLoad}}/>
<key>Disabled</key><false/> | service: on darwin add ServiceCreate option.
OS X launchd doesn't create a full session for most services.
This may be a performance or security decision. Regardless
in order to create a full user session for a service set
this option to true. Leaving as false as this is the os
and historical default. | kardianos_service | train |
1f10dfe63ce9d0cd63975013af820ec32fdfe5f9 | diff --git a/onecodex/lib/upload.py b/onecodex/lib/upload.py
index <HASH>..<HASH> 100644
--- a/onecodex/lib/upload.py
+++ b/onecodex/lib/upload.py
@@ -673,7 +673,7 @@ def _direct_upload(file_obj, file_name, fields, session, samples_resource):
except requests.exceptions.HTTPError as e:
raise_api_error(e.response, state="callback")
except requests.exceptions.ConnectionError:
- raise_connectivity_error()
+ raise_connectivity_error(file_name)
def upload_sequence_fileobj(file_obj, file_name, fields, retry_fields, session, samples_resource): | Fix bug handling connectivity exception during uploads | onecodex_onecodex | train |
17e455d415a88e607e245f5c507c12bc3ae96d9d | diff --git a/test_pytest_cov.py b/test_pytest_cov.py
index <HASH>..<HASH> 100644
--- a/test_pytest_cov.py
+++ b/test_pytest_cov.py
@@ -375,3 +375,50 @@ def test_cover_conftest_dist(testdir):
script)
assert result.ret == 0
result.stdout.fnmatch_lines([CONF_RESULT])
+
+
+COVERAGERC = '''
+[report]
+# Regexes for lines to exclude from consideration
+exclude_lines =
+ raise NotImplementedError
+
+'''
+
+EXCLUDED_TEST = '''
+
+def func():
+ raise NotImplementedError
+
+def test_basic():
+ assert True
+
+'''
+
+EXCLUDED_RESULT = '3 * 100% *'
+
+
+def test_coveragerc(testdir):
+ testdir.makefile('', coveragerc=COVERAGERC)
+ script = testdir.makepyfile(EXCLUDED_TEST)
+ result = testdir.runpytest('-v',
+ '--cov-config=coveragerc',
+ '--cov=%s' % script.dirpath(),
+ '--cov-report=term-missing',
+ script)
+ assert result.ret == 0
+ result.stdout.fnmatch_lines(['test_coveragerc * %s' % EXCLUDED_RESULT])
+
+
+def test_coveragerc_dist(testdir):
+ testdir.makefile('', coveragerc=COVERAGERC)
+ script = testdir.makepyfile(EXCLUDED_TEST)
+ result = testdir.runpytest('-v',
+ '--cov-config=coveragerc',
+ '--cov=%s' % script.dirpath(),
+ '--cov-report=term-missing',
+ '-n', '2',
+ script)
+ assert result.ret == 0
+ result.stdout.fnmatch_lines(
+ ['test_coveragerc_dist * %s' % EXCLUDED_RESULT]) | Added test for coveragerc handling. | pytest-dev_pytest-cov | train |
95022e80b4eb86df02b77a7122c33bc272c19eaf | diff --git a/patchwork/expect.py b/patchwork/expect.py
index <HASH>..<HASH> 100644
--- a/patchwork/expect.py
+++ b/patchwork/expect.py
@@ -114,5 +114,7 @@ class Expect():
Run command and expect specified return valud
'''
retval = connection.recv_exit_status(command, timeout)
+ if connection.output_shell:
+ sys.stdout.write("Run '%s', got %i return value\n" % (command, retval))
if retval != expected_status:
raise ExpectFailed("Got %s exit status (%s expected)" % (retval, expected_status)) | Report in expect_retval as well | RedHatQE_python-stitches | train |
Subsets and Splits