hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
4e0892b7a99ac5b5460f44c6e3634de944c10b9f
|
diff --git a/src/CacheableEloquent.php b/src/CacheableEloquent.php
index <HASH>..<HASH> 100644
--- a/src/CacheableEloquent.php
+++ b/src/CacheableEloquent.php
@@ -247,14 +247,14 @@ trait CacheableEloquent
/**
* Generate unique cache key.
*
- * @param \Illuminate\Database\Eloquent\Builder $builder
- * @param array $columns
+ * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder
+ * @param array $columns
*
* @return string
*/
- protected function generateCacheKey(Builder $builder, array $columns)
+ protected function generateCacheKey($builder, array $columns)
{
- $query = $builder->getQuery();
+ $query = $builder instanceof Builder ? $builder->getQuery() : $builder;
$vars = [
'aggregate' => $query->aggregate,
'columns' => $query->columns,
@@ -280,7 +280,7 @@ trait CacheableEloquent
static::class,
$this->getCacheDriver(),
$this->getCacheLifetime(),
- $builder->getEagerLoads(),
+ $builder instanceof Builder ? $builder->getEagerLoads() : null,
$builder->getBindings(),
$builder->toSql(),
]));
@@ -289,13 +289,13 @@ trait CacheableEloquent
/**
* Cache given callback.
*
- * @param \Illuminate\Database\Eloquent\Builder $builder
- * @param array $columns
- * @param \Closure $closure
+ * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder
+ * @param array $columns
+ * @param \Closure $closure
*
* @return mixed
*/
- public function cacheQuery(Builder $builder, array $columns, Closure $closure)
+ public function cacheQuery($builder, array $columns, Closure $closure)
{
$modelName = static::class;
$lifetime = $this->getCacheLifetime();
|
Support both eloquent and query builders
|
rinvex_laravel-cacheable
|
train
|
01a83cdabdfd337a2c48c85ddb170862f729bc70
|
diff --git a/mordred/task_panels.py b/mordred/task_panels.py
index <HASH>..<HASH> 100644
--- a/mordred/task_panels.py
+++ b/mordred/task_panels.py
@@ -132,8 +132,8 @@ class TaskPanels(Task):
for panel_file in self.panels[ds]:
try:
self.__create_dashboard(panel_file)
- except:
- logger.error("%s not correctly uploaded" % panel_file)
+ except Exception as ex:
+ logger.error("%s not correctly uploaded (%s)", panel_file, ex)
class TaskPanelsAliases(Task):
""" Create the aliases needed for the panels """
|
[task_panels] Improve the log of exceptions
|
chaoss_grimoirelab-sirmordred
|
train
|
1f5b76ac1825c4d62bf47d0ae2f0f21bdfd40e4a
|
diff --git a/merkledag/node.go b/merkledag/node.go
index <HASH>..<HASH> 100644
--- a/merkledag/node.go
+++ b/merkledag/node.go
@@ -76,11 +76,6 @@ func MakeLink(n *Node) (*Link, error) {
}, nil
}
-// GetCachedNode returns the MDAG Node that was cached, or nil
-func (l *Link) GetCachedNode() *Node {
- return l.node
-}
-
// GetNode returns the MDAG Node that this link points to
func (l *Link) GetNode(ctx context.Context, serv DAGService) (*Node, error) {
if l.node != nil {
|
Remove GetCachedNode()
License: MIT
|
ipfs_go-ipfs
|
train
|
d6d776f7080ba0f0c7d0eb899cd0c0f33245b715
|
diff --git a/src/ViKon/Auth/AuthSeederTrait.php b/src/ViKon/Auth/AuthSeederTrait.php
index <HASH>..<HASH> 100644
--- a/src/ViKon/Auth/AuthSeederTrait.php
+++ b/src/ViKon/Auth/AuthSeederTrait.php
@@ -28,8 +28,8 @@ trait AuthSeederTrait
protected function newUserModel($username, $password, array $options = [])
{
$user = new User();
- $user->username = strtolower($username);
- $user->password = bcrypt($password);
+ $user->username = $username;
+ $user->password = $password;
foreach ($options as $key => $value) {
$user->{$key} = $value;
diff --git a/src/ViKon/Auth/Factory/UserFactory.php b/src/ViKon/Auth/Factory/UserFactory.php
index <HASH>..<HASH> 100644
--- a/src/ViKon/Auth/Factory/UserFactory.php
+++ b/src/ViKon/Auth/Factory/UserFactory.php
@@ -4,9 +4,16 @@ namespace ViKon\Auth\Factory;
use Illuminate\Support\Arr;
use ViKon\Auth\Model\User;
-use ViKon\Support\Database\Repository\AbstractFactory;
+use ViKon\Support\Database\ModelFactory;
-class UserFactory extends AbstractFactory
+/**
+ * Class UserFactory
+ *
+ * @package ViKon\Auth\Factory
+ *
+ * @author Kovács Vince<vincekovacs@hotmail.com>
+ */
+class UserFactory extends ModelFactory
{
/**
* Create new user and return it
@@ -20,8 +27,8 @@ class UserFactory extends AbstractFactory
public function build($username, $password, array $optional = [])
{
$user = new User();
- $user->username = strtolower($username);
- $user->password = bcrypt($password);
+ $user->username = $username;
+ $user->password = $password;
$user->fill($optional);
return $user;
@@ -61,7 +68,7 @@ class UserFactory extends AbstractFactory
// Set password for user if provided in optional array
if (Arr::has($optional, User::FIELD_PASSWORD)) {
if ($optional[User::FIELD_PASSWORD] !== null || $optional[User::FIELD_PASSWORD] !== '') {
- $user->password = bcrypt($optional[User::FIELD_PASSWORD]);
+ $user->password = $optional[User::FIELD_PASSWORD];
}
Arr::forget($optional, User::FIELD_PASSWORD);
}
diff --git a/src/ViKon/Auth/Model/User.php b/src/ViKon/Auth/Model/User.php
index <HASH>..<HASH> 100644
--- a/src/ViKon/Auth/Model/User.php
+++ b/src/ViKon/Auth/Model/User.php
@@ -137,6 +137,30 @@ class User extends Model implements AuthenticatableContract, CanResetPasswordCon
}
/**
+ * Set username to lowercase
+ *
+ * @param string $username
+ *
+ * @return void
+ */
+ public function setUsernameAttribute($username)
+ {
+ $this->attributes[static::FIELD_USERNAME] = strtolower($username);
+ }
+
+ /**
+ * Hash password for user model
+ *
+ * @param string $password
+ *
+ * @return void
+ */
+ public function setPasswordAttribute($password)
+ {
+ $this->attributes[static::FIELD_PASSWORD] = bcrypt($password);
+ }
+
+ /**
* Check if user has given group
*
* @param string $group
|
Globally change username to lower and hash password
|
vi-kon_laravel-auth
|
train
|
2d2bde6574d47a5a6c43a73e7c72fd88239ce956
|
diff --git a/packages/cli/src/cli-hosting.js b/packages/cli/src/cli-hosting.js
index <HASH>..<HASH> 100755
--- a/packages/cli/src/cli-hosting.js
+++ b/packages/cli/src/cli-hosting.js
@@ -76,7 +76,7 @@ const setup = async () => {
.description('Configure hosting parameters')
.option('-c, --cname <domain_name>', 'add CNAME to hosting')
.option('-d, --remove-cname <domain_name>', 'remove CNAME from hosting')
- .option('-b, --browser_router', 'turn on BrowserRouter support')
+ .option('-b, --browser_router <true|false>', 'turn on/off the BrowserRouter support')
.action(async (...options) => {
session.isAuthenticated()
session.hasProject()
diff --git a/packages/cli/src/commands/hosting-config.js b/packages/cli/src/commands/hosting-config.js
index <HASH>..<HASH> 100644
--- a/packages/cli/src/commands/hosting-config.js
+++ b/packages/cli/src/commands/hosting-config.js
@@ -9,6 +9,12 @@ class HostingConfig {
this.hosting = null
}
+ static toggleBrowserRouter (command, responses) {
+ if (responses.browser_router) return responses.browser_router
+
+ return command === 'true'
+ }
+
async run ([hostingName, cmd]) {
this.cname = cmd.cname
this.fullPath = null
@@ -35,7 +41,7 @@ class HostingConfig {
const paramsToUpdate = {
cname: this.cname || responses.CNAME,
removeCNAME: cmd.removeCname,
- browser_router: cmd.browser_router || responses.browser_router
+ browser_router: HostingConfig.toggleBrowserRouter(cmd.browser_router, responses)
}
await this.hosting.configure(paramsToUpdate)
|
fix(hosting): Fix #<I>. The BrowserRouter option should accept true|false in hosting config
|
Syncano_syncano-node
|
train
|
29a14958049bedbdf5156d173bbb14aad44f296d
|
diff --git a/uproot/tree.py b/uproot/tree.py
index <HASH>..<HASH> 100644
--- a/uproot/tree.py
+++ b/uproot/tree.py
@@ -261,6 +261,9 @@ class TTreeMethods(object):
for branch in self._fBranches:
self._attachstreamer(branch, context.streamerinfosmap.get(getattr(branch, "_fClassName", None), None), context.streamerinfosmap)
+ self._branchlookup = {}
+ self._fill_branchlookup(self._branchlookup)
+
leaf2branch = {}
for branch in self.itervalues(recursive=True):
if len(branch._fLeaves) == 1:
@@ -277,6 +280,11 @@ class TTreeMethods(object):
else:
self.aliases = dict((alias._fName, alias._fTitle) for alias in self._fAliases)
+ def _fill_branchlookup(self, branchlookup):
+ for subbranch in self._fBranches:
+ subbranch._fill_branchlookup(branchlookup)
+ branchlookup[subbranch.name] = subbranch
+
@property
def name(self):
return self._fName
@@ -344,10 +352,14 @@ class TTreeMethods(object):
def get(self, name, recursive=True, filtername=nofilter, filtertitle=nofilter, aliases=True):
name = _bytesid(name)
- for n, b in self.iteritems(recursive=recursive, filtername=filtername, filtertitle=filtertitle, aliases=aliases):
- if n == name:
- return b
- raise KeyError("not found: {0}".format(repr(name)))
+ try:
+ return self._branchlookup[name]
+ except KeyError:
+ for n, b in self.iteritems(recursive=recursive, filtername=filtername, filtertitle=filtertitle, aliases=aliases):
+ if n == name:
+ self._branchlookup[name] = b
+ return b
+ raise KeyError("not found: {0}".format(repr(name)))
def __contains__(self, name):
try:
@@ -813,6 +825,7 @@ class TBranchMethods(object):
self._source = source
self._context = context
self._streamer = None
+ self._interpretation = None
self._numgoodbaskets = 0
for i, x in enumerate(self._fBasketSeek):
@@ -834,6 +847,11 @@ class TBranchMethods(object):
if hasattr(parent, "_fIOFeatures"):
self._tree_iofeatures = parent._fIOFeatures._fIOBits
+ def _fill_branchlookup(self, branchlookup):
+ for subbranch in self._fBranches:
+ subbranch._fill_branchlookup(branchlookup)
+ branchlookup[subbranch.name] = subbranch
+
@property
def name(self):
return self._fName
@@ -844,7 +862,9 @@ class TBranchMethods(object):
@property
def interpretation(self):
- return interpret(self)
+ if self._interpretation is None:
+ self._interpretation = interpret(self)
+ return self._interpretation
@property
def countbranch(self):
diff --git a/uproot/version.py b/uproot/version.py
index <HASH>..<HASH> 100644
--- a/uproot/version.py
+++ b/uproot/version.py
@@ -30,7 +30,7 @@
import re
-__version__ = "3.2.3"
+__version__ = "3.2.4"
version = __version__
version_info = tuple(re.split(r"[-\.]", __version__))
|
introduce a _branchlookup dict for faster lookups (one per TTree, NOT one per TBranch)
|
scikit-hep_uproot
|
train
|
2c3a4e9bdd1023fa3dfbd4a059102916a1ff9966
|
diff --git a/perceval/backend.py b/perceval/backend.py
index <HASH>..<HASH> 100644
--- a/perceval/backend.py
+++ b/perceval/backend.py
@@ -30,27 +30,39 @@ from .utils import DEFAULT_DATETIME
class Backend:
"""Abstract class for backends.
- Base class to fetch data from a repository. During the
- initialization, a `Cache` object can be provided for caching
- raw data from the repositories.
+ Base class to fetch data from a repository. This repository
+ will be named as 'origin'. During the initialization, a `Cache`
+ object can be provided for caching raw data from the repositories.
Derivated classes have to implement `fetch` and `fetch_from_cache`
methods. Otherwise, `NotImplementedError` exception will be raised.
+ To track which version of the backend was used during the fetching
+ process, this class provides a `version` attribute that each backend
+ may override.
+
+ :param origin: identifier of the repository
:param cache: object to cache raw data
:raises ValueError: raised when `cache` is not an instance of
`Cache` class
"""
- def __init__(self, cache=None):
+ version = '0.1'
+
+ def __init__(self, origin, cache=None):
if cache and not isinstance(cache, Cache):
msg = "cache is not an instance of Cache. %s object given" \
% (str(type(cache)))
raise ValueError(msg)
+ self._origin = origin
self.cache = cache
self.cache_queue = []
+ @property
+ def origin(self):
+ return self._origin
+
def fetch(self, from_date=DEFAULT_DATETIME):
raise NotImplementedError
diff --git a/tests/test_backend.py b/tests/test_backend.py
index <HASH>..<HASH> 100644
--- a/tests/test_backend.py
+++ b/tests/test_backend.py
@@ -35,11 +35,25 @@ from perceval.backend import Backend, BackendCommand
class TestBackend(unittest.TestCase):
"""Unit tests for Backend"""
+ def test_version(self):
+ """Test whether the backend version is initialized"""
+
+ self.assertEqual(Backend.version, '0.1')
+
+ b = Backend('test')
+ self.assertEqual(b.version, '0.1')
+
+ def test_origin(self):
+ """Test whether origin value is initialized"""
+
+ b = Backend('test')
+ self.assertEqual(b.origin, 'test')
+
def test_cache_value_error(self):
"""Test whether it raises a error on invalid cache istances"""
with self.assertRaises(ValueError):
- Backend(cache=8)
+ Backend('test', cache=8)
class TestBackendCommand(unittest.TestCase):
|
[backend] Add version and origin attributes
|
chaoss_grimoirelab-perceval
|
train
|
52f8ba0e5bd20579e4a5fc56365cd20a8bda9f88
|
diff --git a/core/src/main/java/hudson/PluginManager.java b/core/src/main/java/hudson/PluginManager.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/hudson/PluginManager.java
+++ b/core/src/main/java/hudson/PluginManager.java
@@ -24,6 +24,7 @@
package hudson;
import edu.umd.cs.findbugs.annotations.NonNull;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.security.ACLContext;
import jenkins.util.SystemProperties;
import hudson.PluginWrapper.Dependency;
@@ -571,6 +572,8 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas
return loadPluginsFromWar(fromPath, null);
}
+ //TODO: Consider refactoring in order to avoid DMI_COLLECTION_OF_URLS
+ @SuppressFBWarnings(value = "DMI_COLLECTION_OF_URLS", justification = "Plugin loading happens only once on Jenkins startup")
protected @Nonnull Set<String> loadPluginsFromWar(@Nonnull String fromPath, @CheckForNull FilenameFilter filter) {
Set<String> names = new HashSet();
@@ -627,6 +630,8 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas
return names;
}
+ //TODO: Consider refactoring in order to avoid DMI_COLLECTION_OF_URLS
+ @SuppressFBWarnings(value = "DMI_COLLECTION_OF_URLS", justification = "Plugin loading happens only once on Jenkins startup")
protected static void addDependencies(URL hpiResUrl, String fromPath, Set<URL> dependencySet) throws URISyntaxException, MalformedURLException {
if (dependencySet.contains(hpiResUrl)) {
return;
|
FindBugs: Suppress DMI_COLLECTION_OF_URLS in PluginManager since it's safe
|
jenkinsci_jenkins
|
train
|
ddca5d478aa8c4987e43c9801011c6aa88b79762
|
diff --git a/pytds/ntlm.py b/pytds/ntlm.py
index <HASH>..<HASH> 100644
--- a/pytds/ntlm.py
+++ b/pytds/ntlm.py
@@ -14,7 +14,10 @@
import struct
import base64
import string
-import pyDes
+try:
+ import pyDes
+except:
+ raise Exception('To use ntlm authentication you should install pyDes module: pip install pydes')
import hashlib
import hmac
import random
|
check for pyDes package presence
|
denisenkom_pytds
|
train
|
2a2eab2899a361fdca7980f5bc1058295fa3e39d
|
diff --git a/hcsvlab.py b/hcsvlab.py
index <HASH>..<HASH> 100644
--- a/hcsvlab.py
+++ b/hcsvlab.py
@@ -969,7 +969,21 @@ class Client(object):
raise APIError(resp['error'])
except KeyError:
raise APIError(resp)
-
+
+
+ def delete_item_list(self, item_list_url):
+
+ try:
+ resp = self.api_request(str(item_list_url), method="DELETE")
+ except APIError as e:
+ if e.http_status_code == 302:
+ print 'Successfully deleted item list'
+ else:
+ raise APIError
+
+
+
+
def sparql_query(self, collection_name, query):
""" Submit a sparql query to the server to search metadata
diff --git a/tests_hcsvlab.py b/tests_hcsvlab.py
index <HASH>..<HASH> 100644
--- a/tests_hcsvlab.py
+++ b/tests_hcsvlab.py
@@ -75,20 +75,25 @@ class Test(unittest.TestCase):
def test_item_lists(self):
client = hcsvlab.Client()
new_item_url_1 = ['https://ic2-hcsvlab-staging1-vm.intersect.org.au/catalog/ace/A01a']
- my_list = client.get_item_list_by_name('my new list')
+ my_list = client.get_item_list_by_name('my_list')
# Make sure to clear the item list from the web before running this
# ToDO : clear the item list from api
- self.assertEqual(my_list.name(), 'my new list')
+ self.assertEqual(my_list.name(), 'my_list')
#self.assertEqual(client.add_to_item_list_by_name(new_item_url_1, 'my new list'), '1 items added to existing item list my new list')
new_item_url_2 = ['https://ic2-hcsvlab-staging1-vm.intersect.org.au/catalog/ace/A01b']
- self.assertEqual(client.add_to_item_list(new_item_url_2, my_list.url()), '1 items added to existing item list my new list')
+ self.assertEqual(client.add_to_item_list(new_item_url_2, my_list.url()), '1 items added to existing item list ' + my_list.name())
- # ToDO : renaming item list.. client.rename_item_list is not working
+
my_list = my_list.refresh()
item = client.get_item(new_item_url_2[0])
self.assertTrue(my_list.__contains__(item))
+ # Test Rename List
+ client.rename_item_list(my_list, 'brand new list')
+ my_list = my_list.refresh()
+ self.assertEqual(my_list.name(), 'brand new list')
+
|
method for deleting item list added in Client
|
Alveo_pyalveo
|
train
|
df243da0cc611996ad7a3de89a34b2c850aec1d8
|
diff --git a/payu/experiment.py b/payu/experiment.py
index <HASH>..<HASH> 100644
--- a/payu/experiment.py
+++ b/payu/experiment.py
@@ -457,7 +457,7 @@ class Experiment(object):
for model in self.models:
# Skip models without executables (e.g. couplers)
- if not model.local_exec_path:
+ if not model.exec_path_local:
continue
mpi_config = self.config.get('mpi', {})
@@ -466,7 +466,7 @@ class Experiment(object):
# Update MPI library module (if not explicitly set)
# TODO: Check for MPI library mismatch across multiple binaries
if mpi_module is None:
- mpi_module = envmod.lib_update(model.local_exec_path, 'libmpi.so')
+ mpi_module = envmod.lib_update(model.exec_path_local, 'libmpi.so')
model_prog = []
diff --git a/payu/models/model.py b/payu/models/model.py
index <HASH>..<HASH> 100644
--- a/payu/models/model.py
+++ b/payu/models/model.py
@@ -43,6 +43,12 @@ class Model(object):
self.exec_path = None
self.exec_name = None
self.codebase_path = None
+ self.work_path_local = None
+ self.work_input_path_local = None
+ self.work_restart_path_local = None
+ self.work_init_path_local = None
+ self.exec_path_local = None
+
self.build_exec_path = None
self.build_path = None
@@ -77,11 +83,18 @@ class Model(object):
self.exec_prefix = self.config.get('exe_prefix', '')
self.exec_name = self.config.get('exe', self.default_exec)
if self.exec_name:
+ # By default os.path.join will not prepend the lab bin_path
+ # to an absolute path
self.exec_path = os.path.join(self.expt.lab.bin_path,
self.exec_name)
else:
self.exec_path = None
+ if self.exec_path:
+ # Make exec_name consistent for models with fully qualified path.
+ # In all cases it will just be the name of the executable without a path
+ self.exec_name = os.path.basename(self.exec_path)
+
def set_local_pathnames(self):
# This is the path relative to the control directory, required for manifests
@@ -95,11 +108,10 @@ class Model(object):
os.path.relpath(self.work_restart_path,self.expt.work_path)))
self.work_init_path_local = os.path.normpath(os.path.join('work',
os.path.relpath(self.work_init_path,self.expt.work_path)))
- if self.exec_name:
- # Local path in work directory (symlinked to full path and
- # added to manifest)
- self.local_exec_path = os.path.join(self.work_path_local,
- self.exec_name)
+ if self.exec_path:
+ # Local path in work directory
+ self.exec_path_local = os.path.join(self.work_path_local,
+ os.path.basename(self.exec_path))
def set_input_paths(self):
@@ -203,7 +215,7 @@ class Model(object):
# Make symlink to executable in work directory
if self.exec_path:
# Add to exe manifest
- self.expt.manifest.exe_manifest.add_filepath(self.local_exec_path,self.exec_path)
+ self.expt.manifest.exe_manifest.add_filepath(self.exec_path_local,self.exec_path)
timestep = self.config.get('timestep')
if timestep:
|
Initialised all local versions of paths. Required for multi model
experiments containing models without executables, but a good idea
nonetheless.
Strip the path from exec_name and exec_path_local to make it equivalent
if exe is a simple name or a full path.
Changed local_exec_path to exec_path_local for consistency.
|
payu-org_payu
|
train
|
5261a175a116b77b815e3c1cad12f8f2f35cda95
|
diff --git a/app/view/js/bolt.js b/app/view/js/bolt.js
index <HASH>..<HASH> 100644
--- a/app/view/js/bolt.js
+++ b/app/view/js/bolt.js
@@ -782,29 +782,6 @@ function updateGeoCoords(key) {
};
-
-function bindMarkdown(key) {
-// return pasted.replace(/\d+/,"XXX"); }
- $('#'+key).catchpaste( function( pasted, options ) {
-
- $.ajax({
- url: asyncpath + 'markdownify',
- type: 'POST',
- data: { html: pasted },
- success: function(data) {
- $('#'+key).val(data);
- },
- error: function() {
- console.log('failed to get an URI');
- $('#'+key).val(pasted);
- }
- });
- return "";
-
- });
-
-}
-
/**
* Backbone object for collapsable sidebar.
*/
|
Remove bindMarkdown() JS function as Markdownify library is now removed
|
bolt_bolt
|
train
|
10129fbf57ef851ad56158529081afa05ea1c030
|
diff --git a/activestorage/app/models/active_storage/variant.rb b/activestorage/app/models/active_storage/variant.rb
index <HASH>..<HASH> 100644
--- a/activestorage/app/models/active_storage/variant.rb
+++ b/activestorage/app/models/active_storage/variant.rb
@@ -1,5 +1,7 @@
# frozen_string_literal: true
+require "ostruct"
+
# Image blobs can have variants that are the result of a set of transformations applied to the original.
# These variants are used to create thumbnails, fixed-size avatars, or any other derivative image from the
# original.
@@ -51,7 +53,7 @@
# * {ImageProcessing::Vips}[https://github.com/janko-m/image_processing/blob/master/doc/vips.md#methods]
# * {ruby-vips reference}[http://www.rubydoc.info/gems/ruby-vips/Vips/Image]
class ActiveStorage::Variant
- WEB_IMAGE_CONTENT_TYPES = %w( image/png image/jpeg image/jpg image/gif )
+ WEB_IMAGE_CONTENT_TYPES = %w[ image/png image/jpeg image/jpg image/gif ]
attr_reader :blob, :variation
delegate :service, to: :blob
@@ -95,27 +97,11 @@ class ActiveStorage::Variant
def process
blob.open do |image|
- transform image do |output|
- upload output
- end
+ transform(image) { |output| upload(output) }
end
end
-
- def filename
- if WEB_IMAGE_CONTENT_TYPES.include?(blob.content_type)
- blob.filename
- else
- ActiveStorage::Filename.new("#{blob.filename.base}.png")
- end
- end
-
- def content_type
- blob.content_type.presence_in(WEB_IMAGE_CONTENT_TYPES) || "image/png"
- end
-
def transform(image)
- format = "png" unless WEB_IMAGE_CONTENT_TYPES.include?(blob.content_type)
result = variation.transform(image, format: format)
begin
@@ -128,4 +114,24 @@ class ActiveStorage::Variant
def upload(file)
service.upload(key, file)
end
+
+
+ def specification
+ @specification ||=
+ if WEB_IMAGE_CONTENT_TYPES.include?(blob.content_type)
+ Specification.new \
+ filename: blob.filename,
+ content_type: blob.content_type,
+ format: nil
+ else
+ Specification.new \
+ filename: ActiveStorage::Filename.new("#{blob.filename.base}.png"),
+ content_type: "image/png",
+ format: "png"
+ end
+ end
+
+ delegate :filename, :content_type, :format, to: :specification
+
+ class Specification < OpenStruct; end
end
|
DRY up web image checks in ActiveStorage::Variant
|
rails_rails
|
train
|
79c8ee495de3826f322d8c6144be14bebd275264
|
diff --git a/angr/state_plugins/history.py b/angr/state_plugins/history.py
index <HASH>..<HASH> 100644
--- a/angr/state_plugins/history.py
+++ b/angr/state_plugins/history.py
@@ -240,7 +240,7 @@ class SimStateHistory(SimStatePlugin):
return self.descriptions
@property
def addr_trace(self):
- print ".addr trace is deprecated: please use .bbl_addrs"
+ print ".addr_trace is deprecated: please use .bbl_addrs"
return self.bbl_addrs
@property
def stack_actions(self):
|
A typo fix in History.addr_trace.
|
angr_angr
|
train
|
0a30418ad3bb95ff1c88eea2ca91505f43d62bca
|
diff --git a/parsl/dataflow/futures.py b/parsl/dataflow/futures.py
index <HASH>..<HASH> 100644
--- a/parsl/dataflow/futures.py
+++ b/parsl/dataflow/futures.py
@@ -93,7 +93,7 @@ class AppFuture(Future):
Returns:
- None
- Updates the super() with the result() or exception()
+ Updates the future with the result() or exception()
"""
with self._update_lock:
@@ -113,7 +113,7 @@ class AppFuture(Future):
res = executor_fu.result()
if isinstance(res, RemoteExceptionWrapper):
res.reraise()
- super().set_result(executor_fu.result())
+ self.set_result(executor_fu.result())
except Exception as e:
if executor_fu.retries_left > 0:
@@ -122,7 +122,7 @@ class AppFuture(Future):
# will provide the answer
pass
else:
- super().set_exception(e)
+ self.set_exception(e)
@property
def stdout(self):
|
Replace super references with self references in AppFuture (#<I>)
The behaviour shouldn't change over this commit as the self methods should
be the same as the super methods at present, but super() calls
should be avoided unless something specific is being done with inheritence.
|
Parsl_parsl
|
train
|
c475815afbab645df74a8d7227ef52b956495c4d
|
diff --git a/web/concrete/core/models/file.php b/web/concrete/core/models/file.php
index <HASH>..<HASH> 100644
--- a/web/concrete/core/models/file.php
+++ b/web/concrete/core/models/file.php
@@ -419,6 +419,10 @@ class Concrete5_Model_File extends Object {
$db->Execute("delete from FileAttributeValues where fID = ?", array($this->fID));
$db->Execute("delete from FileSetFiles where fID = ?", array($this->fID));
$db->Execute("delete from FileVersionLog where fID = ?", array($this->fID));
+ $db->Execute("delete from FileSearchIndexAttributes where fID = ?", array($this->fID));
+ $db->Execute("delete from DownloadStatistics where fID = ?", array($this->fID));
+ $db->Execute("delete from FilePermissions where fID = ?", array($this->fID));
+ $db->Execute("delete from FilePermissionAssignments where fID = ?", array($this->fID));
}
|
file delete cleanup
remove related data records when removing a file
Former-commit-id: <I>c7bc<I>c<I>e<I>c0d<I>be<I>b<I>d<I>f4
|
concrete5_concrete5
|
train
|
c094f3d8cfe2c4d82c42f249a81a871d3bead9e6
|
diff --git a/examples/redditlivebot/app.js b/examples/redditlivebot/app.js
index <HASH>..<HASH> 100644
--- a/examples/redditlivebot/app.js
+++ b/examples/redditlivebot/app.js
@@ -2,7 +2,7 @@
const nodeogram = require('nodeogram'),
WebSocketClient = require('websocket').client,
config = require('./config.json'),
- bot = new nodeogram.Bot(config.token, {profiles_path: __dirname + '/profiles.json', enableHelp: true}),
+ bot = new nodeogram.Bot(config.token, {profiles_path: __dirname + '/profiles.json', enableHelp: true, useWebhooks: config.useWebhooks, webhookPort: config.webhookPort, webhookRoute: config.webhookRoute}),
request = require('superagent-promise')(require('superagent'), Promise);
var threads = {}, // thread_id: [user_id, ...]
diff --git a/examples/redditlivebot/config.dist.json b/examples/redditlivebot/config.dist.json
index <HASH>..<HASH> 100644
--- a/examples/redditlivebot/config.dist.json
+++ b/examples/redditlivebot/config.dist.json
@@ -1,3 +1,6 @@
{
- "token": "SOMETHING"
+ "token": "SOMETHING",
+ "useWebhooks": true,
+ "webhookPort": 8080,
+ "webhookRoute": "/"
}
\ No newline at end of file
diff --git a/lib/Bot.js b/lib/Bot.js
index <HASH>..<HASH> 100644
--- a/lib/Bot.js
+++ b/lib/Bot.js
@@ -27,7 +27,6 @@ function Bot(token, options) {
this.saveUsers = true;
this.saveChats = true;
this.enableHelp = true;
- this.debug = true;
this.forms = {}; // user_id: {form, answers}
this.webhookRoute = '/';
this.webhookPort = 8080;
@@ -87,9 +86,7 @@ function Bot(token, options) {
};
this.handleUpdates = (updates) => {
- if (this.debug){
- console.log(JSON.stringify(updates));
- }
+ console.log(JSON.stringify(updates));
if (updates.length > 0) {
this.lastUpdate = updates[updates.length - 1].update_id + 1;
var now = Date.now() / 1000;
|
Webhooks for RedditLiveBot
|
ALCC01_nodeogram
|
train
|
0bfab09f0774f547bdc413339b67716371712851
|
diff --git a/packages/postcss-reduce-idents/CHANGELOG.md b/packages/postcss-reduce-idents/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/packages/postcss-reduce-idents/CHANGELOG.md
+++ b/packages/postcss-reduce-idents/CHANGELOG.md
@@ -1,3 +1,8 @@
+# 1.0.2
+
+* Fixes an issue where multiple, comma separated animations with insufficient
+ whitespace were not being renamed.
+
# 1.0.1
* Documentation/metadata tweaks for plugin guidelines compatibility.
diff --git a/packages/postcss-reduce-idents/index.js b/packages/postcss-reduce-idents/index.js
index <HASH>..<HASH> 100644
--- a/packages/postcss-reduce-idents/index.js
+++ b/packages/postcss-reduce-idents/index.js
@@ -6,7 +6,9 @@ var encode = require('./lib/encode');
var list = postcss.list;
function eachValue (value, callback) {
- return list.space(value).map(callback).join(' ');
+ return list.space(value).map(function (val) {
+ return list.comma(val).map(callback).join(',');
+ }).join(' ');
}
function transformAtRule (css, atRuleRegex, propRegex) {
diff --git a/packages/postcss-reduce-idents/test.js b/packages/postcss-reduce-idents/test.js
index <HASH>..<HASH> 100644
--- a/packages/postcss-reduce-idents/test.js
+++ b/packages/postcss-reduce-idents/test.js
@@ -19,6 +19,10 @@ var tests = [{
fixture: '@-webkit-keyframes whiteToBlack{0%{color:#fff}to{color:#000}}@keyframes whiteToBlack{0%{color:#fff}to{color:#000}}div{-webkit-animation-name:whiteToBlack;animation-name:whiteToBlack}',
expected: '@-webkit-keyframes a{0%{color:#fff}to{color:#000}}@keyframes a{0%{color:#fff}to{color:#000}}div{-webkit-animation-name:a;animation-name:a}'
}, {
+ message: 'should support multiple animations',
+ fixture: '@keyframes one{0%{transform:rotate(0deg)}to{transform:rotate(360deg)}}@keyframes two{0%{border-width:0;opacity:0}}.loader{animation:one 1250ms infinite linear,two .3s ease-out both}',
+ expected: '@keyframes a{0%{transform:rotate(0deg)}to{transform:rotate(360deg)}}@keyframes b{0%{border-width:0;opacity:0}}.loader{animation:a 1250ms infinite linear,b .3s ease-out both}'
+}, {
message: 'should not touch animation names that are not defined in the file',
fixture: '.one{animation-name:fadeInUp}',
expected: '.one{animation-name:fadeInUp}'
|
Fixes an issue with renaming multiple animations.
|
cssnano_cssnano
|
train
|
ac7014ca573d9e50a8befc918d727e346dbf7a3f
|
diff --git a/pycanlib/ipython/AcceptanceFilter.py b/pycanlib/ipython/AcceptanceFilter.py
index <HASH>..<HASH> 100644
--- a/pycanlib/ipython/AcceptanceFilter.py
+++ b/pycanlib/ipython/AcceptanceFilter.py
@@ -5,7 +5,7 @@ from pycanlib import CAN
class AcceptanceFilter(ipipe.Pipe):
def __init__(self, std_acceptance_code=0, std_acceptance_mask=CAN.STD_ACCEPTANCE_MASK_ALL_BITS, ext_acceptance_code=0, ext_acceptance_mask=CAN.EXT_ACCEPTANCE_MASK_ALL_BITS):
ipipe.Pipe.__init__(self)
- self.__filter = CAN.SoftwareAcceptanceFilter(std_acceptance_code=std_acceptance_code, std_acceptance_mask=std_acceptance_mask, ext_acceptance_code=ext_acceptance_code, ext_acceptance_mask=ext_acceptance_mask)
+ self.__filter = CAN.AcceptanceFilter(std_acceptance_code=std_acceptance_code, std_acceptance_mask=std_acceptance_mask, ext_acceptance_code=ext_acceptance_code, ext_acceptance_mask=ext_acceptance_mask)
def __iter__(self):
for _i, _item in enumerate(self.input):
|
Fixed references to CAN.SoftwareAcceptanceFilter in ipython/AcceptanceFilter.py
|
hardbyte_python-can
|
train
|
20302cde4fe84d3c3b801ea230611ca00c067684
|
diff --git a/salt/pillar/reclass_adapter.py b/salt/pillar/reclass_adapter.py
index <HASH>..<HASH> 100644
--- a/salt/pillar/reclass_adapter.py
+++ b/salt/pillar/reclass_adapter.py
@@ -1,21 +1,60 @@
'''
-Adapter for reclass.
+ext_pillar adapter for reclass.
-This file cannot be called reclass.py, because then the module import would
-not work. Thanks to the __virtual__ function, however, the plugin still
-responds to the name 'reclass'.
+Please refer to the file `README.Salt` in the reclass source for more
+information on how to use these. In a nutshell, you'll just add the plugin to
+the ext_pillar hash in the master config and tell reclass by way of a few
+options how and where to find the inventory:
+
+ ---
+ ext_pillar:
+ - reclass:
+ storage_type: yaml_fs
+ base_inventory_uri: /srv/salt
+
+This would cause reclass to read the inventory from YAML files in
+`/srv/salt/nodes` and `/srv/salt/classes`.
More information about reclass: http://github.com/madduck/reclass
-It would be desirable to specify the location of reclass in the master config
-file. Unfortunately, __opts__ is only made available to the ext_pillar
-function, not to the module, so that the import cannot make use of these data,
-at least not at the module level, which is needed to set __virtual__
-accordingly.
+There is currently no way to avoid having to specify the same configuration
+for `ext_pillar` and `master_tops`.
+
+Unfortunately, there is currently no way to specify the location of the
+reclass source in the master config, because Salt provides no way to access
+the configuration file data at the module scope (`__opts__` is injected by the
+Salt loader), where we need to know about whether reclass is import-able to be
+able to define the `__virtual__` function. You will hence either have to
+install reclass to `PYTHONPATH`, or extend `PYTHONPATH` when running the
+master, e.g.:
+
+ PYTHONPATH=~/code/reclass:$PYTHONPATH salt-master …
'''
+# This file cannot be called reclass.py, because then the module import would
+# not work. Thanks to the __virtual__ function, however, the plugin still
+# responds to the name 'reclass'.
+
try:
- from reclass.adapters.saltstack import ext_pillar
+ from reclass.adapters.salt import ext_pillar as reclass_ext_pillar
+ from reclass.errors import ReclassException
__virtual__ = lambda: 'reclass'
except ImportError:
__virtual__ = lambda: False
+
+from salt.exceptions import SaltInvocationError
+
+def ext_pillar(pillar, **kwargs):
+ try:
+ return reclass_ext_pillar(__opts__, __salt__, __grains__, pillar, **kwargs)
+
+ except TypeError, e:
+ if e.message.find('unexpected keyword argument') > -1:
+ arg = e.message.split()[-1]
+ raise SaltInvocationError('pillar.reclass: unexpected option: ' + arg)
+
+ else:
+ raise
+
+ except ReclassException, e:
+ raise SaltInvocationError('pillar.reclass: ' + e.message)
diff --git a/salt/tops/reclass_adapter.py b/salt/tops/reclass_adapter.py
index <HASH>..<HASH> 100644
--- a/salt/tops/reclass_adapter.py
+++ b/salt/tops/reclass_adapter.py
@@ -1,20 +1,60 @@
'''
-Adapter for reclass.
+master_tops adapter for reclass.
-This file cannot be called reclass.py, because then the module import would
-not work. Thanks to the __virtual__ function, however, the plugin still
-responds to the name 'reclass'.
+Please refer to the file `README.Salt` in the reclass source for more
+information on how to use these. In a nutshell, you'll just add the plugin to
+the master_tops hash in the master config and tell reclass by way of a few
+options how and where to find the inventory:
+
+ ---
+ master_tops:
+ reclass:
+ storage_type: yaml_fs
+ base_inventory_uri: /srv/salt
+
+This would cause reclass to read the inventory from YAML files in
+`/srv/salt/nodes` and `/srv/salt/classes`.
More information about reclass: http://github.com/madduck/reclass
-It would be desirable to specify the location of reclass in the master config
-file. Unfortunately, __opts__ is only made available to the tops function, not
-to the module, so that the import cannot make use of these data, at least not
-at the module level, which is needed to set __virtual__ accordingly.
+There is currently no way to avoid having to specify the same configuration
+for `ext_pillar` and `master_tops`.
+
+Unfortunately, there is currently no way to specify the location of the
+reclass source in the master config, because Salt provides no way to access
+the configuration file data at the module scope (`__opts__` is injected by the
+Salt loader), where we need to know about whether reclass is import-able to be
+able to define the `__virtual__` function. You will hence either have to
+install reclass to `PYTHONPATH`, or extend `PYTHONPATH` when running the
+master, e.g.:
+
+ PYTHONPATH=~/code/reclass:$PYTHONPATH salt-master …
'''
+# This file cannot be called reclass.py, because then the module import would
+# not work. Thanks to the __virtual__ function, however, the plugin still
+# responds to the name 'reclass'.
+
try:
- from reclass.adapters.saltstack import tops
+ from reclass.adapters.salt import top as reclass_top
+ from reclass.errors import ReclassException
__virtual__ = lambda: 'reclass'
except ImportError:
__virtual__ = lambda: False
+
+from salt.exceptions import SaltInvocationError
+
+def top(**kwargs):
+ try:
+ return reclass_top(__opts__, __salt__, __grains__, **kwargs)
+
+ except TypeError, e:
+ if e.message.find('unexpected keyword argument') > -1:
+ arg = e.message.split()[-1]
+ raise SaltInvocationError('master_tops.reclass: unexpected option: ' + arg)
+
+ else:
+ raise
+
+ except ReclassException, e:
+ raise SaltInvocationError('master_tops.reclass: ' + e.message)
|
Provide wrapper functions for ext_pillar and tops
Unfortunately, the way Salt loads modules means that a simple import
adapter doesn't allow reclass to access the globals, like __opts__.
Therefore, we must provide a wrapper. Oh well.
|
saltstack_salt
|
train
|
fed65fe64740f44ac9000f62c74d10e028b13ad9
|
diff --git a/modules/custom/openy_campaign/src/Entity/Controller/MappingListBuilder.php b/modules/custom/openy_campaign/src/Entity/Controller/MappingListBuilder.php
index <HASH>..<HASH> 100644
--- a/modules/custom/openy_campaign/src/Entity/Controller/MappingListBuilder.php
+++ b/modules/custom/openy_campaign/src/Entity/Controller/MappingListBuilder.php
@@ -38,8 +38,11 @@ class MappingListBuilder extends EntityListBuilder {
$row['id'] = $entity->id();
$row['personify_branch'] = $entity->getPersonifyBranch();
$row['branch'] = $entity->branch->entity->getTitle();
- $regionTid = $entity->branch->entity->field_location_area->target_id;
- $row['region'] = Term::load($regionTid)->getName();
+ if (!empty($entity->branch->entity->field_location_area->target_id)) {
+ $regionTid = $entity->branch->entity->field_location_area->target_id;
+ $row['region'] = Term::load($regionTid)->getName();
+ }
+
return $row + parent::buildRow($entity);
}
|
Fix issue with absent area in the branch.
|
ymcatwincities_openy
|
train
|
7df49b068ae377854f9ee47aa94f958175cb85be
|
diff --git a/bigchaindb/web/views/info.py b/bigchaindb/web/views/info.py
index <HASH>..<HASH> 100644
--- a/bigchaindb/web/views/info.py
+++ b/bigchaindb/web/views/info.py
@@ -1,7 +1,7 @@
"""This module provides the blueprint for some basic API endpoints.
-For more information please refer to the documentation in Apiary:
- - http://docs.bigchaindb.apiary.io/
+For more information please refer to the documentation on ReadTheDocs:
+ - https://bigchaindb.readthedocs.io/en/latest/drivers-clients/http-client-server-api.html
"""
import flask
@@ -13,6 +13,7 @@ from bigchaindb import version
info_views = Blueprint('info_views', __name__)
+
@info_views.route('/')
def home():
return flask.jsonify({
diff --git a/bigchaindb/web/views/transactions.py b/bigchaindb/web/views/transactions.py
index <HASH>..<HASH> 100644
--- a/bigchaindb/web/views/transactions.py
+++ b/bigchaindb/web/views/transactions.py
@@ -1,7 +1,7 @@
"""This module provides the blueprint for some basic API endpoints.
-For more information please refer to the documentation in Apiary:
- - http://docs.bigchaindb.apiary.io/
+For more information please refer to the documentation on ReadTheDocs:
+ - https://bigchaindb.readthedocs.io/en/latest/drivers-clients/http-client-server-api.html
"""
import flask
|
remove apiary from docstring
|
bigchaindb_bigchaindb
|
train
|
22ba2f4c7d5420d138dbb3d8aa0c08cf0bcb29b2
|
diff --git a/test/test_stanforddependencies.py b/test/test_stanforddependencies.py
index <HASH>..<HASH> 100644
--- a/test/test_stanforddependencies.py
+++ b/test/test_stanforddependencies.py
@@ -87,27 +87,33 @@ class DefaultBackendTest(unittest.TestCase):
assert isinstance(sentences, Corpus)
assert isinstance(sentences[0], Sentence)
assert isinstance(sentences[0][0], Token)
- for tokens, expected in zip(sentences, expected_outputs):
- self.assertTokensMatch(tokens, expected)
+ for tree, tokens, expected in zip(trees, sentences, expected_outputs):
+ self.assertTokensMatch(tree, tokens, expected)
def test_reprs(self):
for representation, expected in self.trees.get_repr_test_tree2():
- self.assertConverts(self.trees.tree2, expected, representation=representation)
+ self.assertConverts(self.trees.tree2, expected,
+ representation=representation)
for representation, expected in self.trees.get_repr_test_tree4():
- self.assertConverts(self.trees.tree4, expected, representation=representation)
+ self.assertConverts(self.trees.tree4, expected,
+ representation=representation)
for representation, expected in self.trees.get_repr_test_tree5():
- self.assertConverts(self.trees.tree5, expected, representation=representation)
+ self.assertConverts(self.trees.tree5, expected,
+ representation=representation)
def test_punct_and_erased(self):
- self.assertConverts(self.trees.tree5, self.trees.tree5_out_collapsedTree_no_punct,
+ self.assertConverts(self.trees.tree5,
+ self.trees.tree5_out_collapsedTree_no_punct,
representation='collapsedTree',
include_punct=False, include_erased=False)
self.assertConverts(self.trees.tree5,
self.trees.tree5_out_collapsedTree_erased_no_punct,
representation='collapsedTree',
include_punct=False, include_erased=True)
- self.assertConverts(self.trees.tree5, self.trees.tree5_out_collapsedTree,
+ self.assertConverts(self.trees.tree5,
+ self.trees.tree5_out_collapsedTree,
representation='collapsedTree',
include_punct=True, include_erased=False)
- self.assertConverts(self.trees.tree5, self.trees.tree5_out_collapsedTree_erased,
+ self.assertConverts(self.trees.tree5,
+ self.trees.tree5_out_collapsedTree_erased,
representation='collapsedTree',
include_punct=True, include_erased=True)
def test_bogus_representation(self):
@@ -142,13 +148,13 @@ class DefaultBackendTest(unittest.TestCase):
def assertConverts(self, tree, expected, **conversion_options):
conversion_options.setdefault('universal', self.universal)
- print('tree:')
- print(tree)
print('conversion_options:')
print(conversion_options)
tokens = self.sd.convert_tree(tree, **conversion_options)
- self.assertTokensMatch(tokens, expected)
- def assertTokensMatch(self, tokens, expected_stringification):
+ self.assertTokensMatch(tree, tokens, expected)
+ def assertTokensMatch(self, tree, tokens, expected_stringification):
+ print('tree:')
+ print(tree)
stringified = stringify_sentence(tokens)
print('actual stringified:')
print(stringified)
@@ -194,7 +200,8 @@ class JPypeBackendTest(DefaultBackendTest):
backend = 'jpype'
def test_add_lemmas(self):
- self.assertConverts(self.trees.tree5, self.trees.tree5_out_basic_lemmas,
+ self.assertConverts(self.trees.tree5,
+ self.trees.tree5_out_basic_lemmas,
add_lemmas=True)
def test_report_version_error(self):
self.assertRaises(JavaRuntimeVersionError,
|
test_stanforddependencies.py: more debugging
assertTokensMatch() now takes the tree.
Reformatted for better PEP8 compliance.
|
dmcc_PyStanfordDependencies
|
train
|
cb5de7c6e57c42c72f3669a5b4aecf2661e026b4
|
diff --git a/src/utils/serve-functions.js b/src/utils/serve-functions.js
index <HASH>..<HASH> 100644
--- a/src/utils/serve-functions.js
+++ b/src/utils/serve-functions.js
@@ -117,11 +117,14 @@ function createHandler(dir) {
body = "";
}
+ let remoteAddress = (request.headers['x-forwarded-for'] || request.connection.remoteAddress || '')
+ remoteAddress = (remoteAddress.includes('.') ? remoteAddress.split(':') : remoteAddress.split(',')).pop().trim()
+
const lambdaRequest = {
path: request.path,
httpMethod: request.method,
queryStringParameters: queryString.parse(request.url.split(/\?(.+)/)[1]),
- headers: request.headers,
+ headers: Object.assign({}, request.headers, { 'client-ip': remoteAddress }),
body: body,
isBase64Encoded: isBase64Encoded
};
|
Functions: Add client-ip header to request
|
netlify_cli
|
train
|
da2e6325666b018510cebb67c6ea191c526d30f6
|
diff --git a/salt/modules/parted.py b/salt/modules/parted.py
index <HASH>..<HASH> 100644
--- a/salt/modules/parted.py
+++ b/salt/modules/parted.py
@@ -183,8 +183,8 @@ def list_(device, unit=None):
'start': cols[1],
'end': cols[2],
'size': cols[3],
- 'type': cols[4],
- 'file system': cols[5],
+ 'file system': cols[4],
+ 'name': cols[5],
'flags': cols[6]}
else:
raise CommandExecutionError(
diff --git a/tests/unit/modules/test_parted.py b/tests/unit/modules/test_parted.py
index <HASH>..<HASH> 100644
--- a/tests/unit/modules/test_parted.py
+++ b/tests/unit/modules/test_parted.py
@@ -207,17 +207,17 @@ class PartedTestCase(TestCase, LoaderModuleMockMixin):
'end': '150MB',
'number': '1',
'start': '17.4kB',
- 'file system': '',
+ 'file system': 'ext3',
'flags': 'boot',
- 'type': 'ext3',
+ 'name': '',
'size': '150MB'},
'2': {
'end': '4000GB',
'number': '2',
'start': '3921GB',
- 'file system': '',
+ 'file system': 'linux-swap(v1)',
'flags': '',
- 'type': 'linux-swap(v1)',
+ 'name': '',
'size': '79.3GB'
}
}
@@ -245,17 +245,17 @@ class PartedTestCase(TestCase, LoaderModuleMockMixin):
'end': '150MB',
'number': '1',
'start': '17.4kB',
- 'file system': '',
+ 'file system': 'ext3',
'flags': 'boot',
- 'type': 'ext3',
+ 'name': '',
'size': '150MB'},
'2': {
'end': '4000GB',
'number': '2',
'start': '3921GB',
- 'file system': '',
+ 'file system': 'linux-swap(v1)',
'flags': '',
- 'type': 'linux-swap(v1)',
+ 'name': '',
'size': '79.3GB'
}
}
@@ -282,17 +282,17 @@ class PartedTestCase(TestCase, LoaderModuleMockMixin):
'end': '150MB',
'number': '1',
'start': '17.4kB',
- 'file system': '',
+ 'file system': 'ext3',
'flags': 'boot',
- 'type': 'ext3',
+ 'name': '',
'size': '150MB'},
'2': {
'end': '4000GB',
'number': '2',
'start': '3921GB',
- 'file system': '',
+ 'file system': 'linux-swap(v1)',
'flags': '',
- 'type': 'linux-swap(v1)',
+ 'name': '',
'size': '79.3GB'
}
}
@@ -319,17 +319,17 @@ class PartedTestCase(TestCase, LoaderModuleMockMixin):
'end': '150MB',
'number': '1',
'start': '17.4kB',
- 'file system': '',
+ 'file system': 'ext3',
'flags': 'boot',
- 'type': 'ext3',
+ 'name': '',
'size': '150MB'},
'2': {
'end': '4000GB',
'number': '2',
'start': '3921GB',
- 'file system': '',
+ 'file system': 'linux-swap(v1)',
'flags': '',
- 'type': 'linux-swap(v1)',
+ 'name': '',
'size': '79.3GB'
}
}
|
parted: fix the ordering of list command
The command `parted -m -s {} print` do not print the "Type" column,
but after the "File System" column print the name of the partition.
This point that the type of the partition cannot be extracted using
parted with machine parseable output.
(cherry picked from commit f<I>d<I>e<I>b1a6ad<I>e<I>c<I>b<I>a<I>)
|
saltstack_salt
|
train
|
7db390a44c7bf1c9b40254f67fe70cfa916da4dc
|
diff --git a/Reinforcement-Learning/pyqlearning/qlearning/boltzmann_q_learning.py b/Reinforcement-Learning/pyqlearning/qlearning/boltzmann_q_learning.py
index <HASH>..<HASH> 100644
--- a/Reinforcement-Learning/pyqlearning/qlearning/boltzmann_q_learning.py
+++ b/Reinforcement-Learning/pyqlearning/qlearning/boltzmann_q_learning.py
@@ -2,7 +2,7 @@
# -*- coding: utf-8 -*-
import random
import math
-from rl.q_learning import QLearning
+from pyqlearning.q_learning import QLearning
class BoltzmannQLearning(QLearning):
@@ -44,12 +44,14 @@ class BoltzmannQLearning(QLearning):
def select_action(self, state_key, next_action_list):
'''
- 状態に紐付けて行動を選択する。
- 具象クラス
- ボルツマン分布で確率論的に行動を探索する。
+ Select action by Q(state, action).
+
+ Concreat method for boltzmann distribution.
Args:
- state_key: 状態
+ state_key: The key of state.
+ next_action_list: The possible action in `self.t+1`.
+ If the length of this list is 0, all action should be possible.
Retruns:
The key of action.
|
Update japanese comment.
|
chimera0_accel-brain-code
|
train
|
3eee458430e2a918594b41cdbf8be8142fb907db
|
diff --git a/src/Symfony/Component/OutputEscaper/Escaper.php b/src/Symfony/Component/OutputEscaper/Escaper.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/OutputEscaper/Escaper.php
+++ b/src/Symfony/Component/OutputEscaper/Escaper.php
@@ -294,34 +294,54 @@ class Escaper
'js' =>
/**
- * A function that c-escapes a string after applying (cf. entities). The
- * assumption is that the value will be used to generate dynamic HTML in some
- * way and the safest way to prevent mishap is to assume the value should have
- * HTML entities set properly.
- *
- * The (cf. js_no_entities) method should be used to escape a string
- * that is ultimately not going to end up as text in an HTML document.
+ * A function that escape all non-alphanumeric characters
+ * into their \xHH or \uHHHH representations
*
* @param string $value the value to escape
* @return string the escaped value
*/
function ($value)
{
- return str_replace(array("\\" , "\n" , "\r" , "\"" , "'" ), array("\\\\", "\\n" , "\\r", "\\\"", "\\'"), (is_string($value) ? htmlentities($value, ENT_QUOTES, Escaper::getCharset()) : $value));
- },
+ if ('UTF-8' != Escaper::getCharset()) {
+ $string = Escaper::convertEncoding($string, 'UTF-8', Escaper::getCharset());
+ }
- 'js_no_entities' =>
- /**
- * A function the c-escapes a string, making it suitable to be placed in a
- * JavaScript string.
- *
- * @param string $value the value to escape
- * @return string the escaped value
- */
- function ($value)
- {
- return str_replace(array("\\" , "\n" , "\r" , "\"" , "'" ), array("\\\\", "\\n" , "\\r", "\\\"", "\\'"), $value);
+ $callback = function ($matches)
+ {
+ $char = $matches[0];
+
+ // \xHH
+ if (!isset($char[1])) {
+ return '\\x'.substr('00'.bin2hex($char), -2);
+ }
+
+ // \uHHHH
+ $char = Escaper::convertEncoding($char, 'UTF-16BE', 'UTF-8');
+
+ return '\\u'.substr('0000'.bin2hex($char), -4);
+ };
+
+ if (null === $string = preg_replace_callback('#[^\p{L}\p{N} ]#u', $callback, $string)) {
+ throw new InvalidArgumentException('The string to escape is not a valid UTF-8 string.');
+ }
+
+ if ('UTF-8' != Escaper::getCharset()) {
+ $string = Escaper::convertEncoding($string, Escaper::getCharset(), 'UTF-8');
+ }
+
+ return $string;
},
);
}
+
+ static public function convertEncoding($string, $to, $from)
+ {
+ if (function_exists('iconv')) {
+ return iconv($from, $to, $string);
+ } elseif (function_exists('mb_convert_encoding')) {
+ return mb_convert_encoding($string, $to, $from);
+ } else {
+ throw new RuntimeException('No suitable convert encoding function (use UTF-8 as your encoding or install the iconv or mbstring extension).');
+ }
+ }
}
|
[OutputEscaper] replaced the JS escaper with the one from Twig
|
symfony_symfony
|
train
|
9169cd43d49236c69d5c9b7c556cb0ac0c9ce497
|
diff --git a/modules/caddyhttp/caddyhttp.go b/modules/caddyhttp/caddyhttp.go
index <HASH>..<HASH> 100644
--- a/modules/caddyhttp/caddyhttp.go
+++ b/modules/caddyhttp/caddyhttp.go
@@ -234,6 +234,8 @@ func (app *App) automaticHTTPS() error {
// skip if all listeners use the HTTP port
if !srv.listenersUseAnyPortOtherThan(app.HTTPPort) {
+ log.Printf("[INFO] Server %v is only listening on the HTTP port %d, so no automatic HTTPS will be applied to this server",
+ srv.Listen, app.HTTPPort)
continue
}
@@ -315,6 +317,12 @@ func (app *App) automaticHTTPS() error {
log.Printf("[INFO] Enabling automatic HTTP->HTTPS redirects for %v", domains)
+ // notify user if their config might override the HTTP->HTTPS redirects
+ if srv.listenersIncludePort(app.HTTPPort) {
+ log.Printf("[WARNING] Server %v is listening on HTTP port %d, so automatic HTTP->HTTPS redirects may be overridden by your own configuration",
+ srv.Listen, app.HTTPPort)
+ }
+
// create HTTP->HTTPS redirects
for _, addr := range srv.Listen {
netw, host, port, err := caddy.SplitListenAddr(addr)
diff --git a/modules/caddyhttp/server.go b/modules/caddyhttp/server.go
index <HASH>..<HASH> 100644
--- a/modules/caddyhttp/server.go
+++ b/modules/caddyhttp/server.go
@@ -181,6 +181,23 @@ func (s *Server) listenersUseAnyPortOtherThan(otherPort int) bool {
return false
}
+// listenersIncludePort returns true if there are any
+// listeners in s that use otherPort.
+func (s *Server) listenersIncludePort(otherPort int) bool {
+ for _, lnAddr := range s.Listen {
+ _, addrs, err := caddy.ParseListenAddr(lnAddr)
+ if err == nil {
+ for _, a := range addrs {
+ _, port, err := net.SplitHostPort(a)
+ if err == nil && port == strconv.Itoa(otherPort) {
+ return true
+ }
+ }
+ }
+ }
+ return false
+}
+
func (s *Server) hasTLSClientAuth() bool {
for _, cp := range s.TLSConnPolicies {
if cp.ClientAuthentication != nil && cp.ClientAuthentication.Active() {
|
Log when auto HTTPS or auto HTTP->HTTPS redirects are disabled
|
mholt_caddy
|
train
|
fdc8a3d81ca6ec91e86269972a88b9b5ac54c764
|
diff --git a/test/BootstrapMixinSpec.js b/test/BootstrapMixinSpec.js
index <HASH>..<HASH> 100644
--- a/test/BootstrapMixinSpec.js
+++ b/test/BootstrapMixinSpec.js
@@ -153,40 +153,22 @@ describe('BootstrapMixin', function () {
assert.deepEqual(instance.getBsClassSet(), {'btn': true, 'btn-inline': true});
});
- it('should return "btn btn-lg"', function () {
- let instance = ReactTestUtils.renderIntoDocument(
- <Component bsClass='button' bsSize='large'>
- content
- </Component>
- );
- assert.deepEqual(instance.getBsClassSet(), {'btn': true, 'btn-lg': true});
- });
-
- it('should return "btn btn-md"', function () {
- let instance = ReactTestUtils.renderIntoDocument(
- <Component bsClass='button' bsSize='medium'>
- content
- </Component>
- );
- assert.deepEqual(instance.getBsClassSet(), {'btn': true, 'btn-md': true});
- });
-
- it('should return "btn btn-sm"', function () {
- let instance = ReactTestUtils.renderIntoDocument(
- <Component bsClass='button' bsSize='small'>
- content
- </Component>
- );
- assert.deepEqual(instance.getBsClassSet(), {'btn': true, 'btn-sm': true});
- });
-
- it('should return "btn btn-xs"', function () {
- let instance = ReactTestUtils.renderIntoDocument(
- <Component bsClass='button' bsSize='xsmall'>
- content
- </Component>
- );
- assert.deepEqual(instance.getBsClassSet(), {'btn': true, 'btn-xs': true});
+ describe('Sizes', function () {
+ it('maps english words for sizes to bootstrap sizes constants', function () {
+ function instanceClassSet(size) {
+ let instance = ReactTestUtils.renderIntoDocument(
+ <Component bsClass='button' bsSize={size}>
+ content
+ </Component>
+ );
+ return instance.getBsClassSet();
+ }
+
+ assert.deepEqual(instanceClassSet('large'), {'btn': true, 'btn-lg': true});
+ assert.deepEqual(instanceClassSet('small'), {'btn': true, 'btn-sm': true});
+ assert.deepEqual(instanceClassSet('medium'), {'btn': true, 'btn-md': true});
+ assert.deepEqual(instanceClassSet('xsmall'), {'btn': true, 'btn-xs': true});
+ });
});
it('should return "btn-title"', function () {
|
Simplify 'bsSize' sizes mapping tests
|
react-bootstrap_react-bootstrap
|
train
|
73e438bf0f8c363b0941d4d880ff2122750ca7fe
|
diff --git a/src/Scheduler.php b/src/Scheduler.php
index <HASH>..<HASH> 100644
--- a/src/Scheduler.php
+++ b/src/Scheduler.php
@@ -75,8 +75,8 @@ class Scheduler extends ArrayObject
*/
public function at($datestring)
{
- $date = date('Y-m-d H:i:00', strtotime(date($datestring, $this->now)));
- if (!preg_match("@^$date$@", date('Y-m-d H:i:00', $this->now))) {
+ $date = date($datestring, $this->now);
+ if (!preg_match("@$date$@", date('Y-m-d H:i', $this->now))) {
throw new NotDueException;
}
}
|
better matching of the date; strtotime of course trips up on regexes
|
monolyth-php_croney
|
train
|
2b6ea64dbd408f9519f971b6cdbf874c6882070e
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -158,7 +158,7 @@ Example configuration:
"leading-zero": false,
"remove-empty-rulesets": true,
"rule-indent": " ",
- "stick-brace": true,
+ "stick-brace": "\n",
"strip-spaces": true,
"unitless-zero": true,
"vendor-prefix-align": true
@@ -617,10 +617,10 @@ p {
### stick-brace
-Available values:
- * `{Boolean}` `true` (means 1 space)
- * `{Number}` of spaces
- * `{String}` of whitespace characters (`/[ \t\n]+/`)
+Acceptable values:
+ * `{Number}` of spaces;
+ * `{String}` of whitespaces, tabs or newlines. If there is any other
+ character in the string, the value will not be set.
Example: `{ "stick-brace": "\n" }`
@@ -633,6 +633,17 @@ a
{ color:red }
```
+Example: `{ "stick-brace": 1 }`
+
+```css
+/* before */
+a{ color:red }
+
+/* after */
+a { color:red }
+```
+
+
### strip-spaces
Available value: `{Boolean}` `true`
diff --git a/lib/options/stick-brace.js b/lib/options/stick-brace.js
index <HASH>..<HASH> 100644
--- a/lib/options/stick-brace.js
+++ b/lib/options/stick-brace.js
@@ -3,15 +3,18 @@ module.exports = {
/**
* Sets handler value.
*
- * @param {String|Number|Boolean} value Option value
+ * @param {String|Number} value Option value
* @returns {Object|undefined}
*/
setValue: function(value) {
delete this._value;
- if (value === true) this._value = ' ';
- if (typeof value === 'number' && value === Math.abs(Math.round(value)))
+
+ if (typeof value === 'number' && value === Math.abs(Math.round(value))) {
this._value = new Array(value + 1).join(' ');
- if (typeof value === 'string' && value.match(/^[ \t\n]*$/)) this._value = value;
+ } else if (typeof value === 'string' && value.match(/^[ \t\n]*$/)) {
+ this._value = value;
+ }
+
if (typeof this._value === 'string') return this;
},
diff --git a/test/stick-brace.js b/test/stick-brace.js
index <HASH>..<HASH> 100644
--- a/test/stick-brace.js
+++ b/test/stick-brace.js
@@ -3,23 +3,29 @@ var assert = require('assert');
describe('options/stick-brace', function() {
var comb;
+
beforeEach(function() {
comb = new Comb();
});
+
+ it('Boolean value should not change space before brace', function() {
+ var input = 'a { color: red }';
+ comb.configure({ 'stick-brace': 'foobar' });
+ assert.equal(comb.processString(input), input);
+ });
+
it('Invalid String should not change space before brace', function() {
+ var input = 'a { color: red }';
comb.configure({ 'stick-brace': 'foobar' });
- assert.equal(
- comb.processString('a { color: red }'),
- 'a { color: red }'
- );
+ assert.equal(comb.processString(input), input);
});
- it('True Boolean value should set 1 space before brace', function() {
- comb.configure({ 'stick-brace': true });
- assert.equal(
- comb.processString('a{color:red }'),
- 'a {color:red }'
- );
+
+ it('Invalid Number should not change space before brace', function() {
+ var input = 'a { color: red }';
+ comb.configure({ 'stick-brace': 3.5 });
+ assert.equal(comb.processString(input), input);
});
+
it('Valid Number value should set equal space before brace', function() {
comb.configure({ 'stick-brace': 0 });
assert.equal(
@@ -27,6 +33,7 @@ describe('options/stick-brace', function() {
'a{color:red }'
);
});
+
it('Valid String value should set equal space before brace', function() {
comb.configure({ 'stick-brace': '\n' });
assert.equal(
|
Stick brace: Change acceptable values
`stick-brace` option now accepts only these kinds of values:
- `{Number}` of spaces;
- `{String}` of whitespaces and tabs. If there is any other character in the
string, the value will not be set.
|
csscomb_csscomb.js
|
train
|
f3ac8bd57c0c8bc5da6f9b10672f74f4f1171d10
|
diff --git a/go/vt/vttablet/tabletserver/tabletserver.go b/go/vt/vttablet/tabletserver/tabletserver.go
index <HASH>..<HASH> 100644
--- a/go/vt/vttablet/tabletserver/tabletserver.go
+++ b/go/vt/vttablet/tabletserver/tabletserver.go
@@ -238,8 +238,7 @@ func NewTabletServer(name string, config *tabletenv.TabletConfig, topoServer *to
tsv.txThrottler = txthrottler.NewTxThrottler(tsv.config, topoServer)
tsOnce.Do(func() { srvTopoServer = srvtopo.NewResilientServer(topoServer, "TabletSrvTopo") })
tsv.vstreamer = vstreamer.NewEngine(tsv, srvTopoServer, tsv.sh)
- schemaTracker := schema.NewTracker(tsv.se)
- tsv.watcher = NewReplicationWatcher(tsv, tsv.vstreamer, tsv.config, schemaTracker)
+ tsv.StartTracker()
tsv.messager = messager.NewEngine(tsv, tsv.se, tsv.vstreamer)
tsv.exporter.NewGaugeFunc("TabletState", "Tablet server state", func() int64 {
@@ -263,6 +262,18 @@ func NewTabletServer(name string, config *tabletenv.TabletConfig, topoServer *to
return tsv
}
+// StartTracker() starts a new replication watcher
+// Exporting it allows it to be called separately in endtoend tests
+func (tsv *TabletServer) StartTracker() {
+ schemaTracker := schema.NewTracker(tsv.se)
+ tsv.watcher = NewReplicationWatcher(tsv, tsv.vstreamer, tsv.config, schemaTracker)
+ tsv.watcher.Open()
+}
+
+func (tsv *TabletServer) StopTracker() {
+ tsv.watcher.Close()
+}
+
// Register prepares TabletServer for serving by calling
// all the registrations functions.
func (tsv *TabletServer) Register() {
@@ -1690,9 +1701,9 @@ func (tsv *TabletServer) BroadcastHealth(terTimestamp int64, stats *querypb.Real
target := tsv.target
tsv.mu.Unlock()
shr := &querypb.StreamHealthResponse{
- Target: &target,
- TabletAlias: &tsv.alias,
- Serving: tsv.IsServing(),
+ Target: &target,
+ TabletAlias: &tsv.alias,
+ Serving: tsv.IsServing(),
TabletExternallyReparentedTimestamp: terTimestamp,
RealtimeStats: stats,
}
|
Working version with e2e for 'current' stream
|
vitessio_vitess
|
train
|
56d0b608f3288c2eb40b972438127e687f9a01ce
|
diff --git a/packages/interaction/src/InteractionManager.js b/packages/interaction/src/InteractionManager.js
index <HASH>..<HASH> 100644
--- a/packages/interaction/src/InteractionManager.js
+++ b/packages/interaction/src/InteractionManager.js
@@ -1160,7 +1160,12 @@ export default class InteractionManager extends EventEmitter
if (this.autoPreventDefault && events[0].isNormalized)
{
- originalEvent.preventDefault();
+ const cancelable = originalEvent.cancelable || !('cancelable' in originalEvent);
+
+ if (cancelable)
+ {
+ originalEvent.preventDefault();
+ }
}
const eventLen = events.length;
diff --git a/packages/text-bitmap/src/BitmapText.js b/packages/text-bitmap/src/BitmapText.js
index <HASH>..<HASH> 100644
--- a/packages/text-bitmap/src/BitmapText.js
+++ b/packages/text-bitmap/src/BitmapText.js
@@ -27,8 +27,6 @@ import { removeItems, getResolutionOfUrl } from '@pixi/utils';
* let bitmapText = new PIXI.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"});
* ```
*
-
- *
* @class
* @extends PIXI.Container
* @memberof PIXI
|
Only call preventDefault on normalized events if the browser allows it. (#<I>)
|
pixijs_pixi.js
|
train
|
4642f96245f56b8104021acf354f64ec519939c4
|
diff --git a/dist/chef/cookbooks/sensu/recipes/default.rb b/dist/chef/cookbooks/sensu/recipes/default.rb
index <HASH>..<HASH> 100644
--- a/dist/chef/cookbooks/sensu/recipes/default.rb
+++ b/dist/chef/cookbooks/sensu/recipes/default.rb
@@ -20,16 +20,20 @@
node.sensu.rabbitmq.ssl.cert_chain_file = File.join(node.sensu.directory, "ssl", "cert.pem")
node.sensu.rabbitmq.ssl.private_key_file = File.join(node.sensu.directory, "ssl", "key.pem")
-include_recipe "apt"
-include_recipe "sensu::dependencies"
-
unless Sensu.is_windows(node)
- package "libssl-dev"
+ include_recipe "apt"
+ %w[
+ libssl-dev
+ build-essential
+ nagios-plugins
+ nagios-plugins-basic
+ nagios-plugins-standard
+ ].each do |pkg|
+ package pkg
+ end
end
-unless Sensu.is_windows(node)
- package "build-essential"
-end
+include_recipe "sensu::dependencies"
gem_package "sensu" do
version node.sensu.version
@@ -45,12 +49,6 @@ user node.sensu.user do
home node.sensu.directory
end
-directory node.sensu.log.directory do
- recursive true
- owner node.sensu.user
- mode 0755
-end
-
unless Sensu.is_windows(node)
template "/etc/sudoers.d/sensu" do
source "sudoers.erb"
@@ -58,6 +56,12 @@ unless Sensu.is_windows(node)
end
end
+directory node.sensu.log.directory do
+ recursive true
+ owner node.sensu.user
+ mode 0755
+end
+
remote_directory File.join(node.sensu.directory, "plugins") do
files_mode 0755
end
@@ -80,14 +84,3 @@ file File.join(node.sensu.directory, "config.json") do
content Sensu.generate_config(node, data_bag_item("sensu", "config"))
mode 0644
end
-
-unless Sensu.is_windows(node)
- %w[
- nagios-plugins
- nagios-plugins-basic
- nagios-plugins-standard
- ].each do |pkg|
- package pkg
- end
-end
-
|
[chef] reduce the number of is_windows calls
|
sensu_sensu
|
train
|
0dc5a8230e86495df7fb153913929425be500f38
|
diff --git a/horizon/karma.conf.js b/horizon/karma.conf.js
index <HASH>..<HASH> 100644
--- a/horizon/karma.conf.js
+++ b/horizon/karma.conf.js
@@ -22,14 +22,15 @@ var path = require('path');
module.exports = function (config) {
var xstaticPath = path.resolve('./.tox/npm');
- if (fs.existsSync(xstaticPath)) {
- xstaticPath += '/lib/python2.7/site-packages/xstatic/pkg/';
- }
-
if (!xstaticPath) {
console.error('xStatic libraries not found, please run `tox -e npm`');
process.exit(1);
}
+ xstaticPath += '/lib/';
+ xstaticPath += fs.readdirSync(xstaticPath).find(function(directory) {
+ return directory.indexOf('python') === 0;
+ });
+ xstaticPath += '/site-packages/xstatic/pkg/';
config.set({
preprocessors: {
diff --git a/openstack_dashboard/karma.conf.js b/openstack_dashboard/karma.conf.js
index <HASH>..<HASH> 100644
--- a/openstack_dashboard/karma.conf.js
+++ b/openstack_dashboard/karma.conf.js
@@ -22,14 +22,15 @@ var path = require('path');
module.exports = function (config) {
var xstaticPath = path.resolve('./.tox/npm');
- if (fs.existsSync(xstaticPath)) {
- xstaticPath += '/lib/python2.7/site-packages/xstatic/pkg/';
- }
-
if (!xstaticPath) {
console.error('xStatic libraries not found, please run `tox -e npm`');
process.exit(1);
}
+ xstaticPath += '/lib/';
+ xstaticPath += fs.readdirSync(xstaticPath).find(function(directory) {
+ return directory.indexOf('python') === 0;
+ });
+ xstaticPath += '/site-packages/xstatic/pkg/';
config.set({
preprocessors: {
|
Makes the xstatic files lookup dynamic in the tests
This change makes it so the tests will look for the actual
python folder where the xstatic files are located instead
of looking only for a python<I>/ folder.
Change-Id: Ib2a<I>b<I>b<I>ab<I>fb9a5
Closes-bug: #<I>
|
openstack_horizon
|
train
|
e0e54ca7c2d8ce0f2573e908abccc3a1da6e5c8c
|
diff --git a/tcex/sessions/external_session.py b/tcex/sessions/external_session.py
index <HASH>..<HASH> 100644
--- a/tcex/sessions/external_session.py
+++ b/tcex/sessions/external_session.py
@@ -34,7 +34,10 @@ def default_too_many_requests_handler(response: Response) -> float:
utils = Utils()
retry_after = response.headers.get('Retry-After', 0)
try:
- seconds = float(utils.datetime.format_datetime(retry_after, date_format='%s')) - time.time()
+ seconds = (
+ float(utils.datetime.format_datetime(float(retry_after), date_format='%s'))
+ - time.time()
+ )
except RuntimeError:
# retry_after must be in seconds
seconds = retry_after
|
tweak handling of rate-after header to always try to cast to a float before calling any_to_datetime
|
ThreatConnect-Inc_tcex
|
train
|
18d669b3fa0370ddb08a25ee50388c9b4d24658d
|
diff --git a/rulebook-core/src/test/java/com/deliveredtechnologies/rulebook/model/RuleBookAuditorTest.java b/rulebook-core/src/test/java/com/deliveredtechnologies/rulebook/model/RuleBookAuditorTest.java
index <HASH>..<HASH> 100644
--- a/rulebook-core/src/test/java/com/deliveredtechnologies/rulebook/model/RuleBookAuditorTest.java
+++ b/rulebook-core/src/test/java/com/deliveredtechnologies/rulebook/model/RuleBookAuditorTest.java
@@ -37,6 +37,9 @@ public class RuleBookAuditorTest {
Assert.assertEquals(auditor.getRuleStatus("Rule3"), RuleStatus.EXECUTED);
}
+ /**
+ * Test to ensure that rules invoked using null facts don't error just because that facts are null.
+ */
@Test
@SuppressWarnings("unchecked")
public void rulesAreStillExecutedWithNullFacts() {
|
added JavaDoc to further clarify new test
|
deliveredtechnologies_rulebook
|
train
|
783630be879685a8769ce97c784aec128f98166d
|
diff --git a/.gitignore b/.gitignore
index <HASH>..<HASH> 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,5 @@
.idea
.DS_STORE
*.log
-*.zip
\ No newline at end of file
+*.zip
+node_modules/
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -67,7 +67,7 @@ Speech.prototype.pause = function (duration) {
};
/**
- * Creates a break tag that will pause the audio based upon the strength provided.
+ * Creates a break tag that will pause the audio based upon the strength provided.
* For more information, please see https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/speech-synthesis-markup-language-ssml-reference#break
* @param strength such as none, x-weak, weak, medium, strong, x-strong
* @returns {Speech}
@@ -85,14 +85,25 @@ Speech.prototype.pauseByStrength = function (strength) {
/**
* Creates and inserts an audio tag.
* see https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/speech-synthesis-markup-language-ssml-reference#audio
- * @param url
+ * @param url a link to an audio file to play.
+ * @param callback - an optional callback which is called to build the nested SSML
+ * for the audio tag. The callback takes a single parameter of type
+ * Speech.
* @returns {Speech}
*/
-Speech.prototype.audio = function (url) {
- this._present(url, "The url provided to Speech#audio(..) was null or undefined.");
- this._elements.push("<audio src='" + url + "'/>");
- return this;
-};
+ Speech.prototype.audio = function (url, callback) {
+ this._present(url, "The url provided to Speech#audio(..) was null or undefined.");
+ if(callback){
+ this._isFunction(callback, "callback");
+ var audioBuilder = new Speech();
+ callback(audioBuilder);
+ this._elements.push("<audio src='" + url + "'>" + audioBuilder.ssml(true) + "</audio>");
+ }else{
+ this._elements.push("<audio src='" + url + "'/>");
+ }
+ return this;
+ };
+
/**
* Creates and inserts a say-as tag.
@@ -286,6 +297,18 @@ Speech.prototype._notEmpty = function (word, msg) {
};
/**
+ * Ensures 'fnc' is a function.
+ * @param fnc the variable to check if it's a function.
+ * @param name the name of the parameter used in the error message.
+ */
+Speech.prototype._isFunction = function (fnc, name) {
+ var fncType = typeof(fnc);
+ if(fncType !== "function"){
+ throw new Error(name + " was not a function. received: " + fncType);
+ }
+};
+
+/**
* Creates and inserts a emphasis tag.
* see https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/speech-synthesis-markup-language-ssml-reference#emphasis
* @param level includes strong, moderate and reduced
diff --git a/test/speech_test.js b/test/speech_test.js
index <HASH>..<HASH> 100644
--- a/test/speech_test.js
+++ b/test/speech_test.js
@@ -128,9 +128,26 @@ describe('Speech', function () {
describe('audio', function () {
- it('should build a audio tag', function () {
- speech.audio("http://www.audio.com/sound.mp3");
- assert.equal(speech.ssml(), "<speak><audio src='http://www.audio.com/sound.mp3'/></speak>");
+ describe('positive', function () {
+ it('should build a audio tag', function () {
+ speech.audio("http://www.audio.com/sound.mp3");
+ assert.equal(speech.ssml(), "<speak><audio src='http://www.audio.com/sound.mp3'/></speak>");
+ });
+
+ it('should build a audio tag with nested SSML', function () {
+ speech.audio("http://www.audio.com/sound.mp3", function(builder){
+ builder.say("wow");
+ });
+ assert.equal(speech.ssml(), "<speak><audio src='http://www.audio.com/sound.mp3'>wow</audio></speak>");
+ });
+ });
+
+ describe('negative', function () {
+ it('should throw an error for a string callback', function () {
+ assert.throws(function () {
+ speech.audio("http://www.audio.com/sound.mp3", "callback");
+ }, "callback was not a function. received: string");
+ });
});
});
@@ -294,7 +311,7 @@ describe('Speech', function () {
});
assert.equal(speech.ssml(), "<speak><say-as interpret-as='address' format='us-state'>CO</say-as></speak>");
});
-
+
it('should throw an exception because of invalid interpret', function () {
assert.throws(function () {
speech.sayAs({
|
Implemented the feature suggested by Mandy in issue 7. In addition, added node_modules to the .gitignore file.
|
mandnyc_ssml-builder
|
train
|
e5a97788ab25acb179a70d39d14642af2ec54d9b
|
diff --git a/bosh-director/lib/bosh/director/api/route_configuration.rb b/bosh-director/lib/bosh/director/api/route_configuration.rb
index <HASH>..<HASH> 100644
--- a/bosh-director/lib/bosh/director/api/route_configuration.rb
+++ b/bosh-director/lib/bosh/director/api/route_configuration.rb
@@ -40,6 +40,7 @@ module Bosh
@identity_provider ||= begin
# no fetching w defaults?
user_management = @config.hash['user_management']
+ user_management ||= { 'provider' => 'local' }
user_management_provider = user_management['provider']
unless USER_MANAGEMENT_PROVIDERS.include?(user_management_provider)
diff --git a/bosh-director/spec/unit/api/route_configuration_spec.rb b/bosh-director/spec/unit/api/route_configuration_spec.rb
index <HASH>..<HASH> 100644
--- a/bosh-director/spec/unit/api/route_configuration_spec.rb
+++ b/bosh-director/spec/unit/api/route_configuration_spec.rb
@@ -27,10 +27,21 @@ module Bosh::Director
describe 'authentication configuration' do
let(:test_config) { base_config.merge({'user_management' => {'provider' => provider}}) }
+ context 'when no user_management config is specified' do
+ let(:test_config) { base_config }
+
+ it 'uses LocalIdentityProvider' do
+ route_configuration.controllers.each do |route, controller|
+ identity_provider = controller.instance_variable_get(:"@instance").identity_provider
+ expect(identity_provider).to be_a(Api::LocalIdentityProvider)
+ end
+ end
+ end
+
context 'when local provider is supplied' do
let(:provider) { 'local' }
- it 'defaults to LocalIdentityProvider' do
+ it 'uses LocalIdentityProvider' do
route_configuration.controllers.each do |route, controller|
identity_provider = controller.instance_variable_get(:"@instance").identity_provider
expect(identity_provider).to be_a(Api::LocalIdentityProvider)
|
If user_management isn't configured, default to local.
|
cloudfoundry_bosh
|
train
|
2395164e47d4b684c937c9aec4c585d8837267bf
|
diff --git a/lib/src/main/java/com/auth0/android/lock/LockActivity.java b/lib/src/main/java/com/auth0/android/lock/LockActivity.java
index <HASH>..<HASH> 100644
--- a/lib/src/main/java/com/auth0/android/lock/LockActivity.java
+++ b/lib/src/main/java/com/auth0/android/lock/LockActivity.java
@@ -437,7 +437,7 @@ public class LockActivity extends AppCompatActivity implements ActivityCompat.On
request = apiClient.login(event.getUsernameOrEmail(), event.getPassword(), connection);
} else if (MFA_CHALLENGE_TYPE_OOB.equals(lastDatabaseLogin.getMultifactorChallengeType())) {
// oob multi-factor authentication
- request = apiClient.loginWithOOB(event.getMultifactorToken(), event.getMultifactorOOBCode(), null);
+ request = apiClient.loginWithOOB(event.getMultifactorToken(), event.getMultifactorOOBCode(), event.getMultifactorOTP());
} else {
// otp multi-factor authentication
request = apiClient.loginWithOTP(event.getMultifactorToken(), event.getMultifactorOTP());
|
add missing OTP value to request when verifying OOB
|
auth0_Lock.Android
|
train
|
4c602e93e92135ef3fd1bc36143e7dd3c905f6f4
|
diff --git a/presto-main/src/main/java/com/facebook/presto/connector/jmx/JmxConnectorFactory.java b/presto-main/src/main/java/com/facebook/presto/connector/jmx/JmxConnectorFactory.java
index <HASH>..<HASH> 100644
--- a/presto-main/src/main/java/com/facebook/presto/connector/jmx/JmxConnectorFactory.java
+++ b/presto-main/src/main/java/com/facebook/presto/connector/jmx/JmxConnectorFactory.java
@@ -23,7 +23,6 @@ import com.facebook.presto.spi.ConnectorRecordSetProvider;
import com.facebook.presto.spi.ConnectorRecordSinkProvider;
import com.facebook.presto.spi.ConnectorSplitManager;
import com.facebook.presto.spi.NodeManager;
-import io.airlift.node.NodeInfo;
import javax.inject.Inject;
import javax.management.MBeanServer;
@@ -37,14 +36,12 @@ public class JmxConnectorFactory
{
private final MBeanServer mbeanServer;
private final NodeManager nodeManager;
- private final NodeInfo nodeInfo;
@Inject
- public JmxConnectorFactory(MBeanServer mbeanServer, NodeManager nodeManager, NodeInfo nodeInfo)
+ public JmxConnectorFactory(MBeanServer mbeanServer, NodeManager nodeManager)
{
this.mbeanServer = checkNotNull(mbeanServer, "mbeanServer is null");
this.nodeManager = checkNotNull(nodeManager, "nodeManager is null");
- this.nodeInfo = checkNotNull(nodeInfo, "nodeInfo is null");
}
@Override
@@ -79,7 +76,7 @@ public class JmxConnectorFactory
@Override
public ConnectorRecordSetProvider getRecordSetProvider()
{
- return new JmxRecordSetProvider(mbeanServer, nodeInfo);
+ return new JmxRecordSetProvider(mbeanServer, nodeManager);
}
@Override
diff --git a/presto-main/src/main/java/com/facebook/presto/connector/jmx/JmxRecordSetProvider.java b/presto-main/src/main/java/com/facebook/presto/connector/jmx/JmxRecordSetProvider.java
index <HASH>..<HASH> 100644
--- a/presto-main/src/main/java/com/facebook/presto/connector/jmx/JmxRecordSetProvider.java
+++ b/presto-main/src/main/java/com/facebook/presto/connector/jmx/JmxRecordSetProvider.java
@@ -17,13 +17,13 @@ import com.facebook.presto.spi.ConnectorColumnHandle;
import com.facebook.presto.spi.ConnectorRecordSetProvider;
import com.facebook.presto.spi.ConnectorSplit;
import com.facebook.presto.spi.InMemoryRecordSet;
+import com.facebook.presto.spi.NodeManager;
import com.facebook.presto.spi.RecordSet;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.util.IterableTransformer;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
-import io.airlift.node.NodeInfo;
import io.airlift.slice.Slice;
import javax.inject.Inject;
@@ -49,10 +49,10 @@ public class JmxRecordSetProvider
private final String nodeId;
@Inject
- public JmxRecordSetProvider(MBeanServer mbeanServer, NodeInfo nodeInfo)
+ public JmxRecordSetProvider(MBeanServer mbeanServer, NodeManager nodeManager)
{
this.mbeanServer = checkNotNull(mbeanServer, "mbeanServer is null");
- this.nodeId = checkNotNull(nodeInfo, "nodeInfo is null").getNodeId();
+ this.nodeId = checkNotNull(nodeManager, "nodeManager is null").getCurrentNode().getNodeIdentifier();
}
@Override
|
Remove usage of NodeInfo from JMX connector
|
prestodb_presto
|
train
|
07f2282ba58bc588aada22d43df3e8d2ee5c0410
|
diff --git a/lib/create-http-client.js b/lib/create-http-client.js
index <HASH>..<HASH> 100644
--- a/lib/create-http-client.js
+++ b/lib/create-http-client.js
@@ -13,11 +13,12 @@ import rateLimit from './rate-limit'
* @prop {string=} host - Alternate host
* @prop {Object=} httpAgent - HTTP agent for node
* @prop {Object=} httpsAgent - HTTPS agent for node
+ * @prop {Object=} proxy - Axios proxy config
* @prop {Object=} headers - Additional headers
* @return {Object} Initialized axios instance
*/
export default function createHttpClient (axios, httpClientParams) {
- const {space, accessToken, insecure, host, defaultHostname, httpAgent, httpsAgent} = httpClientParams
+ const {space, accessToken, insecure, host, defaultHostname, httpAgent, httpsAgent, proxy} = httpClientParams
let {headers} = httpClientParams
let [hostname, port] = (host && host.split(':')) || []
hostname = hostname || defaultHostname
@@ -42,6 +43,7 @@ export default function createHttpClient (axios, httpClientParams) {
headers: headers,
httpAgent: httpAgent,
httpsAgent: httpsAgent,
+ proxy: proxy,
paramsSerializer: qs.stringify
})
instance.httpClientParams = httpClientParams
|
feat( create-http-client): Enable axios proxy
|
contentful_contentful-sdk-core
|
train
|
3134405066d5fba7f8ef07474fe109a16b186c00
|
diff --git a/lib/surrounded/context.rb b/lib/surrounded/context.rb
index <HASH>..<HASH> 100644
--- a/lib/surrounded/context.rb
+++ b/lib/surrounded/context.rb
@@ -25,8 +25,7 @@ module Surrounded
object = Context.modify(object, klass.const_get(role_module_name))
end
- roles[role.to_s] = object
- instance_variable_set("@#{role}", object)
+ set_role_attr(role, object)
}
}
end
@@ -78,6 +77,12 @@ module Surrounded
private
+ def set_role_attr(role, obj)
+ roles[role.to_s] = obj
+ instance_variable_set("@#{role}", obj)
+ self
+ end
+
def roles
@roles ||= {}
end
|
manage setting roles in a single method
|
saturnflyer_surrounded
|
train
|
3ddc2dcc123cbfbc80166cf5c1b958f3e9fd64dd
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -10,6 +10,7 @@ setup(name='splinter',
author='CobraTeam',
author_email='andrewsmedina@gmail.com',
packages=find_packages(),
+ include_package_data=True,
test_suite='nose.collector',
install_requires=['selenium', 'zope.testbrowser', 'lxml'],
tests_require=['nose', 'coverage', 'ludibrio', 'flask'],
|
add include_package_data to setup
|
cobrateam_splinter
|
train
|
24532e60e0c6d67b3d92c4f5a686f763d832a88b
|
diff --git a/lib/jpmobile/request_with_mobile.rb b/lib/jpmobile/request_with_mobile.rb
index <HASH>..<HASH> 100644
--- a/lib/jpmobile/request_with_mobile.rb
+++ b/lib/jpmobile/request_with_mobile.rb
@@ -36,6 +36,11 @@ module Jpmobile
mobile and mobile.smart_phone?
end
+ # タブレットからであれば +true+を、そうでなければ +false+ を返す
+ def tablet?
+ mobile and mobile.tablet?
+ end
+
# 携帯電話の機種に応じて Mobile::xxx を返す。
# 携帯電話でない場合はnilを返す。
def mobile
|
Add the function that devides tablets or others
|
jpmobile_jpmobile
|
train
|
bc4daf9ddd3499ecab750f70aa6513ad0fcb1ade
|
diff --git a/spec/lyber_core/destroyer_spec.rb b/spec/lyber_core/destroyer_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lyber_core/destroyer_spec.rb
+++ b/spec/lyber_core/destroyer_spec.rb
@@ -7,8 +7,7 @@ describe LyberCore::Destroyer do
before :all do
FakeWeb.allow_net_connect = false
fixture_metadata = open(File.expand_path(File.dirname(__FILE__) + "/../fixtures/objects.xml")) { |f| f.read }
- FakeWeb.allow_net_connect = false
- FakeWeb.register_uri(:get, %r|lyberservices|, :body => fixture_metadata)
+ FakeWeb.register_uri(:get, %r|lyberservices-dev\.stanford\.edu|, :body => fixture_metadata)
@dfo = LyberCore::Destroyer.new("dor","googleScannedBookWF", "register-object")
end
|
This spec is passing on my laptop but failing on the server. Just trying a few things to figure out why.
|
sul-dlss_lyber-core
|
train
|
4c2b9fb0495ed768286fcd2c4bc247fdb0dfe979
|
diff --git a/src/PoCProductProjector.php b/src/PoCProductProjector.php
index <HASH>..<HASH> 100644
--- a/src/PoCProductProjector.php
+++ b/src/PoCProductProjector.php
@@ -8,6 +8,7 @@ use Brera\PoC\Product\Product;
class PoCProductProjector
{
+ /* TODO: Replace array with RendererCollection */
/**
* @var ProductRenderer[]
*/
@@ -33,11 +34,27 @@ class PoCProductProjector
*/
public function project(Product $product)
{
+ /* TODO: Looping is done inside of RendererCollection. Projector just calls render() on RendererCollection. */
+
foreach ($this->renderers as $renderer) {
// The projector renderer could be used even on the frontend.
// The renderer is decoupled from the data storage and display.
+
+ /* TODO: Make renderer return list of snippet outputs */
+
$html = $renderer->render($product);
+
+ /* TODO: Loop through returned results and put each to data pool */
+
$this->dataPoolWriter->setPoCProductHtml($product->getId(), $html);
}
}
}
+
+/**
+ *
+ * - Key generation goes from DataPoll writer to Snippet
+ * - Then projector injects the list of snippets into DataPoolWriter
+ * - And DataPool writer gets key and content from each snippet and puts it into key/value storage
+ *
+ */
|
Issue #<I>: Add some TODOs and notes
|
lizards-and-pumpkins_catalog
|
train
|
3c2ddf2c93e155407043a9e9c68e08d38ff63cda
|
diff --git a/Configuration/TCA/Overrides/tt_content_element_image.php b/Configuration/TCA/Overrides/tt_content_element_image.php
index <HASH>..<HASH> 100644
--- a/Configuration/TCA/Overrides/tt_content_element_image.php
+++ b/Configuration/TCA/Overrides/tt_content_element_image.php
@@ -25,6 +25,7 @@ $GLOBALS['TCA']['tt_content']['types']['image'] = array_replace_recursive(
--palette--;LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:palette.general;general,
--palette--;LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:palette.header;header,
--div--;LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:tabs.images,
+ imagecols,
image,
imagecols,
--palette--;LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:palette.imagelinks;imagelinks,
diff --git a/Configuration/TCA/Overrides/tt_content_element_media.php b/Configuration/TCA/Overrides/tt_content_element_media.php
index <HASH>..<HASH> 100644
--- a/Configuration/TCA/Overrides/tt_content_element_media.php
+++ b/Configuration/TCA/Overrides/tt_content_element_media.php
@@ -25,6 +25,7 @@ $GLOBALS['TCA']['tt_content']['types']['media'] = array_replace_recursive(
--palette--;LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:palette.general;general,
--palette--;LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:palette.header;header,
--div--;LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:tabs.media,
+ imagecols,
assets,
imagecols,
--div--;LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:tabs.appearance,
diff --git a/Configuration/TCA/Overrides/tt_content_element_textmedia.php b/Configuration/TCA/Overrides/tt_content_element_textmedia.php
index <HASH>..<HASH> 100644
--- a/Configuration/TCA/Overrides/tt_content_element_textmedia.php
+++ b/Configuration/TCA/Overrides/tt_content_element_textmedia.php
@@ -26,8 +26,8 @@ $GLOBALS['TCA']['tt_content']['types']['textmedia'] = array_replace_recursive(
--palette--;LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:palette.header;header,
bodytext,
--div--;LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:tabs.media,
- assets,
--palette--;LLL:EXT:bootstrap_package/Resources/Private/Language/Backend.xlf:palette.alignment;mediablock,
+ assets,
--palette--;LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:palette.imagelinks;imagelinks,
--div--;LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:tabs.appearance,
--palette--;LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:palette.frames;frames,
diff --git a/Configuration/TCA/Overrides/tt_content_element_textpic.php b/Configuration/TCA/Overrides/tt_content_element_textpic.php
index <HASH>..<HASH> 100644
--- a/Configuration/TCA/Overrides/tt_content_element_textpic.php
+++ b/Configuration/TCA/Overrides/tt_content_element_textpic.php
@@ -26,8 +26,8 @@ $GLOBALS['TCA']['tt_content']['types']['textpic'] = array_replace_recursive(
--palette--;LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:palette.header;header,
bodytext,
--div--;LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:tabs.images,
- image,
--palette--;LLL:EXT:bootstrap_package/Resources/Private/Language/Backend.xlf:palette.alignment;imageblock,
+ image,
--palette--;LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:palette.imagelinks;imagelinks,
--div--;LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:tabs.appearance,
--palette--;LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:palette.frames;frames,
|
[FEATURE] rearrange settings for images and media assets (#<I>)
* [FEATURE] move imagecols on top of image
* [FEATURE] move imageblock on top of image
* [FEATURE] move imagecols over assets
* [FEATURE] move mediablock over assets
|
benjaminkott_bootstrap_package
|
train
|
7580b019c17cc96220174dfc79d507f00ffb2ac3
|
diff --git a/lib/requester/requester.js b/lib/requester/requester.js
index <HASH>..<HASH> 100644
--- a/lib/requester/requester.js
+++ b/lib/requester/requester.js
@@ -115,6 +115,7 @@ Requester.prototype.request = function (item, cb, scope) {
// get the reason phrase
codeReason = httpReasons.lookup(responseJSON.statusCode);
+ codeReason.overridden = !(res && res.statusMessage);
codeReason.name = (res && res.statusMessage) || codeReason.name;
// An object that is used in the app for certain things (such as response code details). Should be removed.
@@ -125,7 +126,8 @@ Requester.prototype.request = function (item, cb, scope) {
responseCode: {
code: responseJSON.statusCode,
name: codeReason.name || '',
- detail: codeReason.detail || ''
+ detail: codeReason.detail || '',
+ overridden: codeReason.overridden
},
responseCookies: cookies
};
|
added a flag that's set to true if http response reason is overridden
|
postmanlabs_postman-runtime
|
train
|
93712cdacfb150f3c02f8730e3ff9740a4be9a31
|
diff --git a/lib/tocer/runner.rb b/lib/tocer/runner.rb
index <HASH>..<HASH> 100644
--- a/lib/tocer/runner.rb
+++ b/lib/tocer/runner.rb
@@ -11,7 +11,7 @@ module Tocer
@writer = writer
end
- def call configuration
+ def call configuration = Configuration::Loader.call
Pathname(configuration.root_dir).files(%({#{configuration.includes.join ","}}))
.each do |path|
yield path if block_given?
|
Fixed runner to use default configuration
Necessary to fall back to the default configuration when none is given.
|
bkuhlmann_tocer
|
train
|
0a1ca685c9e391896be2dd7d565932d6cae10ebd
|
diff --git a/lib/datapackage/schema.rb b/lib/datapackage/schema.rb
index <HASH>..<HASH> 100644
--- a/lib/datapackage/schema.rb
+++ b/lib/datapackage/schema.rb
@@ -39,7 +39,7 @@ module DataPackage
ref_keys.each do |key|
path = key.split('/')[0..-2]
- replacement = resolve(schema.dig(*path, '$ref'), path_or_url)
+ replacement = resolve(schema.dig(*path, '$ref'), path_or_url, schema)
s = "schema['properties']#{path.map { |k| "['#{k}']" }.join}.merge! replacement"
eval s
@@ -51,7 +51,7 @@ module DataPackage
schema
end
- def resolve reference, path_or_url
+ def resolve reference, path_or_url, schema
base_path = base_path path_or_url
filename, reference = reference.split '#'
filename = path_or_url.split('/')[-1] if filename == ''
|
Pass schema to `resolve`
|
frictionlessdata_datapackage-rb
|
train
|
8812be8c800fca84c3dd952deda413a4c23be6bb
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -42,10 +42,21 @@ module.exports = function (robot) {
return;
}
- res.send(response);
+ try {
+ res.send(response);
+ } catch (e) {
+ console.error(e);
+
+ try {
+ res.send(String(response));
+ } catch (e) {
+ console.error(e);
+ res.send('Error', e);
+ }
+ }
})
.catch(function (err) {
robot.logger.error(err);
});
});
-};
\ No newline at end of file
+};
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -1,10 +1,10 @@
{
"name": "hubot-review",
"description": "Assigns and notifies reviewers for GitHub pull requests",
- "version": "0.9.0",
+ "version": "0.9.2",
"author": "Ivan Malopinsky",
"license": "MIT",
- "keywords": "hubot, hubot-scripts",
+ "keywords": ["hubot", "hubot-scripts"],
"repository": {
"type": "git",
"url": "git://github.com/imsky/hubot-review.git"
diff --git a/src/messages/slack.js b/src/messages/slack.js
index <HASH>..<HASH> 100644
--- a/src/messages/slack.js
+++ b/src/messages/slack.js
@@ -53,6 +53,7 @@ function templateFn (resources, reviewers) {
if (!reviewers || !reviewers.length) {
return {
+ 'text': '',
'attachments': attachments
};
}
@@ -73,4 +74,4 @@ function SlackMessage (options) {
});
}
-module.exports = SlackMessage;
\ No newline at end of file
+module.exports = SlackMessage;
|
try hard to send a response, <I>
|
imsky_pull-review
|
train
|
0594d72bee5b41fcc515864b6f3317d9548310b3
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -26,7 +26,7 @@ setup(
url='https://github.com/houtianze/bypy',
download_url='https://github.com/houtianze/bypy/tarball/' + bypy.__version__,
packages=find_packages(),
- scripts=['bypy', 'bypy.py', 'bypy.py', 'bypygui.pyw'],
+ scripts=['bypy', 'bypy.bat', 'bypy.py', 'bypygui.pyw'],
package_data = {
'' : ['*.md']
},
|
Trivial: Correct bypy.bat script in setup.py
|
houtianze_bypy
|
train
|
e83c4f39e83963116d392b34e951c8b8748cfa69
|
diff --git a/shell-core/src/main/java/org/apache/maven/shell/core/impl/Slf4jLoggerManager.java b/shell-core/src/main/java/org/apache/maven/shell/core/impl/Slf4jLoggerManager.java
index <HASH>..<HASH> 100644
--- a/shell-core/src/main/java/org/apache/maven/shell/core/impl/Slf4jLoggerManager.java
+++ b/shell-core/src/main/java/org/apache/maven/shell/core/impl/Slf4jLoggerManager.java
@@ -54,7 +54,7 @@ public class Slf4jLoggerManager
public LoggerImpl(final int threshold, final Logger logger) {
super(threshold, logger.getName());
-
+
this.log = logger;
}
diff --git a/shell-testsupport/src/main/java/org/apache/maven/shell/testsupport/TestLoggerManager.java b/shell-testsupport/src/main/java/org/apache/maven/shell/testsupport/TestLoggerManager.java
index <HASH>..<HASH> 100644
--- a/shell-testsupport/src/main/java/org/apache/maven/shell/testsupport/TestLoggerManager.java
+++ b/shell-testsupport/src/main/java/org/apache/maven/shell/testsupport/TestLoggerManager.java
@@ -25,7 +25,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * Adapts the Plexus logging system to SLF4J.
+ * Test {@link LoggerManager}.
*
* @version $Rev$ $Date$
*/
@@ -54,7 +54,6 @@ public class TestLoggerManager
public LoggerImpl(final int threshold, final Logger logger) {
super(threshold, logger.getName());
-
this.log = logger;
}
|
Bring loggerman back working or not
|
jdillon_gshell
|
train
|
aeacb7b1289ed175187146b947e2dd0e27c37d26
|
diff --git a/lib/simpletest/testfilterconfig.php b/lib/simpletest/testfilterconfig.php
index <HASH>..<HASH> 100644
--- a/lib/simpletest/testfilterconfig.php
+++ b/lib/simpletest/testfilterconfig.php
@@ -785,6 +785,7 @@ class filter_filter_set_applies_to_strings extends UnitTestCaseUsingDatabase {
}
public function tearDown() {
+ global $CFG;
$CFG->stringfilters = $this->origcfgstringfilters;
$CFG->filterall = $this->origcfgfilterall;
|
MDL-<I> fix missing global $CFG that was breaking unit test teardown
|
moodle_moodle
|
train
|
cb13ba6582357eee765293bda10909d3e0077b6f
|
diff --git a/framework/helpers/BaseHtml.php b/framework/helpers/BaseHtml.php
index <HASH>..<HASH> 100644
--- a/framework/helpers/BaseHtml.php
+++ b/framework/helpers/BaseHtml.php
@@ -1167,7 +1167,7 @@ class BaseHtml
$options['uncheck'] = '0';
}
- $checked = ($value !== $options['uncheck']);
+ $checked = ($value != $options['uncheck']);
if (!array_key_exists('id', $options)) {
$options['id'] = static::getInputId($model, $attribute);
|
A bit less stricter check as suggested by @qiang: <URL>
|
yiisoft_yii-core
|
train
|
a259475b3ba68e8990da0aea6eb0fe3e3ad982f0
|
diff --git a/src/Command/AbstractGSheetToXmlCommand.php b/src/Command/AbstractGSheetToXmlCommand.php
index <HASH>..<HASH> 100644
--- a/src/Command/AbstractGSheetToXmlCommand.php
+++ b/src/Command/AbstractGSheetToXmlCommand.php
@@ -11,7 +11,6 @@ namespace XmlSquad\GsheetXml\Command;
use Exception;
use Symfony\Component\Console\Command\Command;
-use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
@@ -145,11 +144,7 @@ abstract class AbstractGSheetToXmlCommand extends AbstractCommand
protected function doConfigureDataSourceOptions()
{
$this
- ->addArgument(
- 'drive-url',
- InputArgument::REQUIRED,
- 'The URL of the Google Drive entity (Google Sheet or Google Drive folder). is-recursive: if the Google Drive entity is a Google Drive folder, this option specifies whether or not to recurse through sub-directories to find sheets.'
- )
+ ->doConfigureDriveUrlArgument()
->addOption(
'recursive',
'r',
@@ -161,6 +156,8 @@ abstract class AbstractGSheetToXmlCommand extends AbstractCommand
}
+
+
/**
* Factory method for GoogleDriveProcessService object.
*
@@ -223,15 +220,7 @@ abstract class AbstractGSheetToXmlCommand extends AbstractCommand
return $input->getOption('recursive');
}
- /**
- * Get DataSourceOption [drive-url]
- *
- * @param InputInterface $input
- * @return mixed
- */
- protected function getDriveUrlOption(InputInterface $input){
- return $input->getArgument('drive-url');
- }
+
/**
* Finds the full path to the credentials file.
diff --git a/src/Command/GsheetToXmlCommand.php b/src/Command/GsheetToXmlCommand.php
index <HASH>..<HASH> 100644
--- a/src/Command/GsheetToXmlCommand.php
+++ b/src/Command/GsheetToXmlCommand.php
@@ -75,7 +75,7 @@ class GsheetToXmlCommand extends AbstractGSheetToXmlCommand
*/
protected function getDataSourceOptions(InputInterface $input){
return array(
- 'url' => $this->getDriveUrlOption($input),
+ 'url' => $this->getDriveUrlArgument($input),
'recursive' => $this->getIsRecursiveOption($input));
}
|
Renamed and wrap drive-url in config and get methods.
Renamed to make it clear it is an argument and not an option.
So, they can be defined in abstract and used by other commands to
add a little consistency to the suite of commands.
See: <URL>
|
xmlsquad_gsheet-to-xml
|
train
|
594f28d36c19a51ff73f91ca794fb575f781ccb9
|
diff --git a/topdown/eval.go b/topdown/eval.go
index <HASH>..<HASH> 100644
--- a/topdown/eval.go
+++ b/topdown/eval.go
@@ -332,7 +332,7 @@ func (e *eval) evalNot(iter evalIterator) error {
}
if !defined {
- return e.next(iter)
+ return iter(e)
}
e.traceFail(expr)
@@ -480,7 +480,7 @@ func (e *eval) evalNotPartial(iter evalIterator) error {
// If partial evaluation produced no results, the expression is always undefined
// so it does not have to be saved.
if len(savedQueries) == 0 {
- return e.next(iter)
+ return iter(e)
}
// Check if the partial evaluation result can be inlined in this query. If not,
@@ -502,7 +502,7 @@ func (e *eval) evalNotPartial(iter evalIterator) error {
// (!A && !C) || (!A && !D) || (!B && !C) || (!B && !D)
return complementedCartesianProduct(savedQueries, 0, nil, func(q ast.Body) error {
return e.saveInlinedNegatedExprs(q, func() error {
- return e.next(iter)
+ return iter(e)
})
})
}
@@ -1042,7 +1042,7 @@ func (e *eval) saveCall(declArgsLen int, terms []*ast.Term, iter unifyIterator)
func (e *eval) saveInlinedNegatedExprs(exprs []*ast.Expr, iter unifyIterator) error {
- // This function does not have include with statements on the exprs because
+ // This function does not include with statements on the exprs because
// they will have already been saved and therefore had their any relevant
// with statements set.
for _, expr := range exprs {
diff --git a/topdown/topdown_partial_test.go b/topdown/topdown_partial_test.go
index <HASH>..<HASH> 100644
--- a/topdown/topdown_partial_test.go
+++ b/topdown/topdown_partial_test.go
@@ -1728,6 +1728,17 @@ func TestTopDownPartialEval(t *testing.T) {
query: "x = [0]; y = {true | x[0]; input.y = 1}", // include an unknown in the comprehension to force saving
wantQueries: []string{`y = {true | x[0]; input.y = 1; x = [0]}; x = [0]`},
},
+ {
+ note: "negation: save inline negated with",
+ query: `not input with data.x as 2; data.x = 1`,
+ data: `{"x": 1}`,
+ wantQueries: []string{"not input"},
+ },
+ {
+ note: "negation: save inline negated with (undefined)",
+ query: `not input with data.x as 1; data.x = 1`,
+ wantQueries: []string{},
+ },
}
ctx := context.Background()
diff --git a/topdown/topdown_test.go b/topdown/topdown_test.go
index <HASH>..<HASH> 100644
--- a/topdown/topdown_test.go
+++ b/topdown/topdown_test.go
@@ -2105,6 +2105,15 @@ func TestTopDownWithKeyword(t *testing.T) {
`q = x { r = x with input.a.c as 2 }`,
`p = x { q = x with input.a.b as 1 }`,
},
+ }, {
+ note: "with not stack",
+ input: `{"a": {"d": 3}, "e": 4}`,
+ exp: `{"a": {"b": 1, "c": 2, "d": 3}, "e": 4}`,
+ rules: []string{
+ `r = input { true }`,
+ `q = x { not false with input as {}; r = x with input.a.c as 2 }`,
+ `p = x { q = x with input.a.b as 1 }`,
+ },
},
{
note: "with stack (data)",
@@ -2122,6 +2131,23 @@ func TestTopDownWithKeyword(t *testing.T) {
},
},
{
+ note: "with not stack (data)",
+ exp: `{"a": {"b": 1, "c": 2, "d": 3}, "e": 4}`,
+ modules: []string{
+ `package test.a
+ d = 3`,
+ `package test
+ e = 4`,
+ },
+ rules: []string{
+ `r = data.test { true }`,
+ `n1 { data.test.a.z == 7 }`,
+ `n { not n1 } `,
+ `q = x { not n with data.test.a.z as 7; r = x with data.test.a.c as 2 }`,
+ `p = x { q = x with data.test.a.b as 1 }`,
+ },
+ },
+ {
note: "with stack overwrites",
input: `{"a": {"b": 1, "c": 2}}`,
exp: `{"a": {"d": 3}}`,
|
topdown: Invoke iterator when evaluating negation
In `evalNot` when it succeeds we were calling `e.next(..)` to continue
evaluation, but if the previous expression was from `evalWith` the
original state was not being restored. This caused the patched data
to persist for subsequent expression evaluation(s) until `iter()` was
used.
Similar treatment was required in `evalNotPartial` for the partial
evaluation case.
Fixes: #<I>
|
open-policy-agent_opa
|
train
|
a87715f68851a2937749fdfbb25e639274ae8d2b
|
diff --git a/core/server/data/fixtures/index.js b/core/server/data/fixtures/index.js
index <HASH>..<HASH> 100644
--- a/core/server/data/fixtures/index.js
+++ b/core/server/data/fixtures/index.js
@@ -92,6 +92,10 @@ populate = function populate() {
});
_.each(fixtures.clients, function (client) {
+ // no random secrets during testing
+ if (process.env.NODE_ENV.indexOf('testing') !== 0) {
+ client.secret = crypto.randomBytes(6).toString('hex');
+ }
ops.push(Client.add(client, options));
});
diff --git a/core/server/data/migration/index.js b/core/server/data/migration/index.js
index <HASH>..<HASH> 100644
--- a/core/server/data/migration/index.js
+++ b/core/server/data/migration/index.js
@@ -1,5 +1,6 @@
var _ = require('lodash'),
Promise = require('bluebird'),
+ crypto = require('crypto'),
sequence = require('../../utils/sequence'),
path = require('path'),
fs = require('fs'),
@@ -19,6 +20,7 @@ var _ = require('lodash'),
logInfo,
populateDefaultSettings,
backupDatabase,
+ fixClientSecret,
// public
init,
@@ -52,6 +54,19 @@ backupDatabase = function backupDatabase() {
});
};
+// TODO: move to migration.to005() for next DB version
+fixClientSecret = function () {
+ return models.Clients.forge().query('where', 'secret', '=', 'not_available').fetch().then(function updateClients(results) {
+ return Promise.map(results.models, function mapper(client) {
+ if (process.env.NODE_ENV.indexOf('testing') !== 0) {
+ logInfo('Updating client secret');
+ client.secret = crypto.randomBytes(6).toString('hex');
+ }
+ return models.Client.edit(client, {context: {internal: true}, id: client.id});
+ });
+ });
+};
+
// Check for whether data is needed to be bootstrapped or not
init = function (tablesOnly) {
tablesOnly = tablesOnly || false;
@@ -78,7 +93,8 @@ init = function (tablesOnly) {
if (databaseVersion === defaultVersion) {
// 1. The database exists and is up-to-date
logInfo('Up to date at version ' + databaseVersion);
- return;
+ // TODO: temporary fix for missing client.secret
+ return fixClientSecret();
}
if (databaseVersion > defaultVersion) {
diff --git a/core/test/utils/fork.js b/core/test/utils/fork.js
index <HASH>..<HASH> 100644
--- a/core/test/utils/fork.js
+++ b/core/test/utils/fork.js
@@ -57,10 +57,10 @@ function forkGhost(newConfig, envName) {
newConfig.server.port = port;
newConfig.url = url.format(_.extend({}, url.parse(newConfig.url), {port: port, host: null}));
- var newConfigFile = path.join(config.paths.appRoot, 'config.test' + port + '.js');
+ var newConfigFile = path.join(config.paths.appRoot, 'config.test.' + envName + '.js');
return new Promise(function (resolve, reject) {
- fs.writeFile(newConfigFile, 'module.exports = {' + envName + ': ' + JSON.stringify(newConfig) + '}', function (err) {
+ fs.writeFile(newConfigFile, 'module.exports = {"' + process.env.NODE_ENV + '": ' + JSON.stringify(newConfig) + '}', function (err) {
if (err) {
return reject(err);
}
@@ -81,7 +81,6 @@ function forkGhost(newConfig, envName) {
};
env.GHOST_CONFIG = newConfigFile;
- env.NODE_ENV = envName;
child = cp.fork(path.join(config.paths.appRoot, 'index.js'), {env: env});
// return the port to make it easier to do requests
child.port = port;
|
Fix client.secret for new installs
closes #<I>
- added random secret for new databases
- added temporary fix for existing databases
- secret is still static (`not_available`) during tests
- fixed fork mechanism to keep active environment (never change
NODE_ENV!!!)
|
TryGhost_Ghost
|
train
|
df425f2a4a6598634b2acd62cb685700051ca508
|
diff --git a/trie/ctrie/ctrie_test.go b/trie/ctrie/ctrie_test.go
index <HASH>..<HASH> 100644
--- a/trie/ctrie/ctrie_test.go
+++ b/trie/ctrie/ctrie_test.go
@@ -293,7 +293,7 @@ func TestIterator(t *testing.T) {
close(cancel)
// Drain anything already put on the channel. Since select chooses a
// pseudo-random case, we must attempt to drain for every item.
- for i := 0; i < 10; i++ {
+ for _ = range expected {
<-iter
}
_, ok = <-iter
|
Range over expected in ctrie iterator test
|
Workiva_go-datastructures
|
train
|
7e05d0cd4bb027ae027f7a460d74972df1477d67
|
diff --git a/lib/io.js b/lib/io.js
index <HASH>..<HASH> 100644
--- a/lib/io.js
+++ b/lib/io.js
@@ -114,6 +114,10 @@ io.on('connection', function(socket) {
var db = req.mongo.db(req.params.database_name);
createSampleStream(db, req.params.collection_name, req.params.sample_options)
+ .on('error', function(dbErr) {
+ debug('database errror', dbErr);
+ return res.emit('error', dbErr);
+ })
.pipe(EJSON.createStringifyStream())
.pipe(res);
});
diff --git a/lib/routes/collection.js b/lib/routes/collection.js
index <HASH>..<HASH> 100644
--- a/lib/routes/collection.js
+++ b/lib/routes/collection.js
@@ -171,6 +171,10 @@ module.exports = {
],
sample: function(req, res) {
createSampleStream(req.db, req.ns.collection, req.params.sample_options)
+ .on('error', function(err) {
+ debug('database errror', err);
+ return res.emit('error', err);
+ })
.pipe(EJSON.createStringifyStream())
.pipe(setHeaders(req, res, {
'content-type': 'application/json'
|
minor: pass db operation errors to the client
|
mongodb-js_scope-server
|
train
|
2f60cb921e4d30f6915397d49562323c912a0716
|
diff --git a/src/services/leafletMarkersHelpers.js b/src/services/leafletMarkersHelpers.js
index <HASH>..<HASH> 100644
--- a/src/services/leafletMarkersHelpers.js
+++ b/src/services/leafletMarkersHelpers.js
@@ -132,10 +132,10 @@ angular.module("leaflet-directive")
return;
}
- var updatePopup = function(popup,adjustPan) {
+ var updatePopup = function(popup) {
popup._updateLayout();
popup._updatePosition();
- if (popup.options.autoPan && adjustPan) {
+ if (popup.options.autoPan) {
popup._adjustPan();
}
};
@@ -146,7 +146,7 @@ angular.module("leaflet-directive")
if (popup._contentNode.innerHTML.indexOf("ngInclude") > -1) {
var unregister = markerScope.$on('$includeContentLoaded', function () {
$timeout(function() {
- updatePopup(popup, true);
+ updatePopup(popup);
unregister();
});
});
|
Fix issue with autopan for ng-include after review
|
tombatossals_angular-leaflet-directive
|
train
|
ac41a2229d14140cf028a5f974907352862e30c3
|
diff --git a/test/test_api_state_things.py b/test/test_api_state_things.py
index <HASH>..<HASH> 100644
--- a/test/test_api_state_things.py
+++ b/test/test_api_state_things.py
@@ -407,6 +407,60 @@ class TestThing(testUtils.AbstractTest):
del self.appClient.state.active.thingTypes[TestThing.createdTT.id].things[createdThing.thingId]
assert TestStateUtils.doesThingIdExist(self.appClient, TestThing.thingTypeId, createdThing.thingId) == False
+ def testRegisterThingMetadata(self):
+ thingId = "thingId"
+ thingName = "TemperatureThingName"
+ thingDescription = "Temp thing description"
+ # Aggregated devices for thing
+ aggregated = {
+ "Temperature": {"type": "device", "typeId": TestThing.createdDT.id, "id": TestThing.createdDevice.deviceId}
+ }
+
+ # Create the thing
+ createdThing = self.createAndCheckThing(
+ TestThing.createdTT.id, thingId, thingName, thingDescription, aggregated, metadata={"test": "test"}
+ )
+
+ assert TestStateUtils.doesThingIdExist(self.appClient, TestThing.thingTypeId, createdThing.thingId)
+
+ for retrievedThing in TestThing.createdTT.things:
+ assert retrievedThing.thingTypeId == TestThing.createdTT.id
+ assert retrievedThing.thingId == thingId
+ assert retrievedThing.name == thingName
+ assert retrievedThing.metadata == {"test": "test"}
+ assert retrievedThing.description == thingDescription
+ assert retrievedThing.aggregatedObjects == aggregated
+
+ del self.appClient.state.active.thingTypes[TestThing.createdTT.id].things[createdThing.thingId]
+ assert TestStateUtils.doesThingIdExist(self.appClient, TestThing.thingTypeId, createdThing.thingId) == False
+
+ def testRegisterThingDescriptionNone(self):
+ thingId = "thingId"
+ thingName = "TemperatureThingName"
+ thingDescription = None
+ # Aggregated devices for thing
+ aggregated = {
+ "Temperature": {"type": "device", "typeId": TestThing.createdDT.id, "id": TestThing.createdDevice.deviceId}
+ }
+
+ # Create the thing
+ createdThing = self.createAndCheckThing(
+ TestThing.createdTT.id, thingId, thingName, thingDescription, aggregated, metadata={"test": "test"}
+ )
+
+ assert TestStateUtils.doesThingIdExist(self.appClient, TestThing.thingTypeId, createdThing.thingId)
+
+ for retrievedThing in TestThing.createdTT.things:
+ assert retrievedThing.thingTypeId == TestThing.createdTT.id
+ assert retrievedThing.thingId == thingId
+ assert retrievedThing.name == thingName
+ assert retrievedThing.metadata == {"test": "test"}
+ assert retrievedThing.description == None
+ assert retrievedThing.aggregatedObjects == aggregated
+
+ del self.appClient.state.active.thingTypes[TestThing.createdTT.id].things[createdThing.thingId]
+ assert TestStateUtils.doesThingIdExist(self.appClient, TestThing.thingTypeId, createdThing.thingId) == False
+
def testDeletePreReqs(self):
# delete any left over thing types
for tt in self.appClient.state.active.thingTypes:
|
Added 3 types to api_state_things.py
|
ibm-watson-iot_iot-python
|
train
|
3548abc1b03a56dca7b600ca5a5bf80216b81edc
|
diff --git a/tunnel.go b/tunnel.go
index <HASH>..<HASH> 100644
--- a/tunnel.go
+++ b/tunnel.go
@@ -320,7 +320,7 @@ func (api *API) UpdateTunnelConfiguration(ctx context.Context, rc *ResourceConta
}
uri := fmt.Sprintf("/accounts/%s/cfd_tunnel/%s/configurations", rc.Identifier, params.TunnelID)
- res, err := api.makeRequestContext(ctx, http.MethodPut, uri, params.Config)
+ res, err := api.makeRequestContext(ctx, http.MethodPut, uri, params)
if err != nil {
return TunnelConfigurationResult{}, err
}
|
Add `config` to body of UpdateTunnelConfiguration
|
cloudflare_cloudflare-go
|
train
|
1befa12550c9035ef468091ce72a4dc4504d1281
|
diff --git a/lib/smpp/receiver.rb b/lib/smpp/receiver.rb
index <HASH>..<HASH> 100644
--- a/lib/smpp/receiver.rb
+++ b/lib/smpp/receiver.rb
@@ -1,16 +1,14 @@
-# The SMPP Transceiver maintains a bidirectional connection to an SMSC.
+# The SMPP Receiver maintains a unidirectional connection to an SMSC.
# Provide a config hash with connection options to get started.
# See the sample_gateway.rb for examples of config values.
-# The transceiver accepts a delegate object that may implement
+# The receiver accepts a delegate object that may implement
# the following (all optional) methods:
#
-# mo_received(transceiver, pdu)
-# delivery_report_received(transceiver, pdu)
-# message_accepted(transceiver, mt_message_id, pdu)
-# message_rejected(transceiver, mt_message_id, pdu)
-# bound(transceiver)
-# unbound(transceiver)
+# mo_received(receiver, pdu)
+# delivery_report_received(receiver, pdu)
+# bound(receiver)
+# unbound(receiver)
class Smpp::Receiver < Smpp::Base
@@ -27,77 +25,10 @@ class Smpp::Receiver < Smpp::Base
ed = @config[:enquire_link_delay_secs] || 5
comm_inactivity_timeout = 2 * ed
rescue Exception => ex
- logger.error "Exception setting up transceiver: #{ex} at #{ex.backtrace.join("\n")}"
+ logger.error "Exception setting up receiver: #{ex} at #{ex.backtrace.join("\n")}"
raise
end
- # Send an MT SMS message. Delegate will receive message_accepted callback when SMSC
- # acknowledges, or the message_rejected callback upon error
- def send_mt(message_id, source_addr, destination_addr, short_message, options={})
- logger.debug "Sending MT: #{short_message}"
- if @state == :bound
- pdu = Pdu::SubmitSm.new(source_addr, destination_addr, short_message, options)
- write_pdu pdu
-
- # keep the message ID so we can associate the SMSC message ID with our message
- # when the response arrives.
- @ack_ids[pdu.sequence_number] = message_id
- else
- raise InvalidStateException, "Transceiver is unbound. Cannot send MT messages."
- end
- end
-
- # Send a concatenated message with a body of > 160 characters as multiple messages.
- def send_concat_mt(message_id, source_addr, destination_addr, message, options = {})
- logger.debug "Sending concatenated MT: #{message}"
- if @state == :bound
- # Split the message into parts of 153 characters. (160 - 7 characters for UDH)
- parts = []
- while message.size > 0 do
- parts << message.slice!(0..152)
- end
-
- 0.upto(parts.size-1) do |i|
- udh = sprintf("%c", 5) # UDH is 5 bytes.
- udh << sprintf("%c%c", 0, 3) # This is a concatenated message
- udh << sprintf("%c", message_id) # The ID for the entire concatenated message
- udh << sprintf("%c", parts.size) # How many parts this message consists of
- udh << sprintf("%c", i+1) # This is part i+1
-
- options = {
- :esm_class => 64, # This message contains a UDH header.
- :udh => udh
- }
-
- pdu = Pdu::SubmitSm.new(source_addr, destination_addr, parts[i], options)
- write_pdu pdu
-
- # This is definately a bit hacky - multiple PDUs are being associated with a single
- # message_id.
- @ack_ids[pdu.sequence_number] = message_id
- end
- else
- raise InvalidStateException, "Transceiver is unbound. Connot send MT messages."
- end
- end
-
- # Send MT SMS message for multiple dest_address
- # Author: Abhishek Parolkar (abhishek[at]parolkar.com)
- # USAGE: $tx.send_multi_mt(123, "9100000000", ["9199000000000","91990000000001","9199000000002"], "Message here")
- def send_multi_mt(message_id, source_addr, destination_addr_arr, short_message, options={})
- logger.debug "Sending Multiple MT: #{short_message}"
- if @state == :bound
- pdu = Pdu::SubmitMulti.new(source_addr, destination_addr_arr, short_message, options)
- write_pdu pdu
-
- # keep the message ID so we can associate the SMSC message ID with our message
- # when the response arrives.
- @ack_ids[pdu.sequence_number] = message_id
- else
- raise InvalidStateException, "Transceiver is unbound. Cannot send MT messages."
- end
- end
-
# a PDU is received. Parse it and invoke delegate methods.
def process_pdu(pdu)
case pdu
|
Remove methods for sending SMSes.
Also change messages, comments, etc to reflect Receiver class.
|
raykrueger_ruby-smpp
|
train
|
16fb85f840af3bfc1fb150abaffec558cc3cb418
|
diff --git a/pyes/queryset.py b/pyes/queryset.py
index <HASH>..<HASH> 100644
--- a/pyes/queryset.py
+++ b/pyes/queryset.py
@@ -332,7 +332,7 @@ class QuerySet(object):
and returning the created object.
"""
obj = self.model(**kwargs)
- meta = obj.get_meta()
+ meta = obj.get_meta()
meta.connection = get_es_connection(self.es_url, self.es_kwargs)
meta.index=self.index
meta.type=self.type
|
fixed inconsistent use to QuerySet
it would raise an Error under python<I>
the line <I>:
meta = obj.get_meta()
^
TabError: inconsistent use of tabs and spaces in indentation
|
aparo_pyes
|
train
|
7172ffe83d3a591798e4312ef151f5a6d31e2c59
|
diff --git a/lib/init.js b/lib/init.js
index <HASH>..<HASH> 100644
--- a/lib/init.js
+++ b/lib/init.js
@@ -75,7 +75,7 @@ module.exports = function(args){
},
// Load plugins
load_plugins: ['config', function(next, results){
- if (!results.config) return next();
+ if (safe || !results.config) return next();
var dir = baseDir + 'node_modules/';
@@ -101,7 +101,7 @@ module.exports = function(args){
}],
// Load scripts
load_scripts: ['config', function(next, results){
- if (!results.config) return next();
+ if (safe || !results.config) return next();
var dir = baseDir + 'scripts/';
|
Don't load plugins in safe mode
|
hexojs_hexo
|
train
|
1a175da7caee975f8010fe676e8da3f95a46f613
|
diff --git a/lib/Predis/ConnectionParameters.php b/lib/Predis/ConnectionParameters.php
index <HASH>..<HASH> 100644
--- a/lib/Predis/ConnectionParameters.php
+++ b/lib/Predis/ConnectionParameters.php
@@ -118,6 +118,10 @@ class ConnectionParameters implements IConnectionParameters {
}
public function __isset($parameter) {
+ return isset($this->_parameters[$parameter]);
+ }
+
+ public function setByUser($parameter) {
return in_array($parameter, $this->_userDefined);
}
|
Predis\ConnectionParameters::__isset() should check if a parameters has been set and its value is not null.
|
nrk_predis
|
train
|
baa78784afad67c2321be64af1d35b4ddf2c75ef
|
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PropertyDerivations.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PropertyDerivations.java
index <HASH>..<HASH> 100644
--- a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PropertyDerivations.java
+++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PropertyDerivations.java
@@ -187,7 +187,7 @@ class PropertyDerivations
@Override
public ActualProperties visitApply(ApplyNode node, List<ActualProperties> inputProperties)
{
- return inputProperties.get(0); // apply node input (outer query)
+ throw new IllegalArgumentException("Unexpected node: " + node.getClass().getName());
}
@Override
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/StreamPropertyDerivations.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/StreamPropertyDerivations.java
index <HASH>..<HASH> 100644
--- a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/StreamPropertyDerivations.java
+++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/StreamPropertyDerivations.java
@@ -494,7 +494,7 @@ final class StreamPropertyDerivations
@Override
public StreamProperties visitApply(ApplyNode node, List<StreamProperties> inputProperties)
{
- return inputProperties.get(0);
+ throw new IllegalStateException("Unexpected node: " + node.getClass());
}
@Override
diff --git a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java
index <HASH>..<HASH> 100644
--- a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java
+++ b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java
@@ -7161,7 +7161,7 @@ public abstract class AbstractTestQueries
@Test
public void testCorrelatedInPredicateSubqueries()
{
- String errorMsg = "Unsupported correlated subquery type";
+ String errorMsg = "Unexpected node: com.facebook.presto.sql.planner.plan.ApplyNode";
assertQuery("SELECT orderkey, clerk IN (SELECT clerk FROM orders s WHERE s.custkey = o.custkey AND s.orderkey < o.orderkey) FROM orders o");
assertQuery("SELECT orderkey FROM orders o WHERE clerk IN (SELECT clerk FROM orders s WHERE s.custkey = o.custkey AND s.orderkey < o.orderkey)");
@@ -7193,7 +7193,9 @@ public abstract class AbstractTestQueries
assertQueryFails("SELECT * FROM lineitem l1 JOIN lineitem l2 ON l1.orderkey IN (SELECT l2.orderkey)", errorMsg);
// subrelation
- assertQueryFails("SELECT * FROM lineitem l WHERE (SELECT * FROM (SELECT 1 IN (SELECT 2 * l.orderkey)))", errorMsg);
+ assertQueryFails(
+ "SELECT * FROM lineitem l WHERE (SELECT * FROM (SELECT 1 IN (SELECT 2 * l.orderkey)))",
+ "Unexpected node: com.facebook.presto.sql.planner.plan.LateralJoinNode");
// two level of nesting
assertQueryFails("SELECT * FROM lineitem l WHERE true IN (SELECT 1 IN (SELECT 2 * l.orderkey))", errorMsg);
|
Throw exception instead of returning wrong value
Returning only input properties for apply node is incorrect as it does
not consider subquery properties.
|
prestodb_presto
|
train
|
45d9dfcf7830532f13f2bb4f8243461ea2eca4fd
|
diff --git a/Module.php b/Module.php
index <HASH>..<HASH> 100755
--- a/Module.php
+++ b/Module.php
@@ -13,7 +13,32 @@ class Module
public function getConfig()
{
- return include "{$this->_moduleBaseDir}/config/module.config.php";
+ $config = include("{$this->_moduleBaseDir}/config/module.config.php");
+
+ //Load assets from module's public path
+ if(!isset($config['asset_manager']))
+ {
+ $config['asset_manager'] = array(
+ 'resolver_configs' => array(
+ 'paths' => array(
+ "{$this->_moduleBaseDir}/public",
+ ),
+ ),
+ );
+ }
+
+ //Load view from module's view path
+ if(!isset($config['view_manager']))
+ {
+ $config['view_manager'] = array(
+ 'template_path_stack' => array(
+ "{$this->_moduleBaseDir}/view",
+ )
+ );
+ }
+
+ //echo "<pre>";print_r($config);die();
+ return $config;
}
public function getAutoloaderConfig()
|
Automatically add asset manager and view manager config to module configs
|
DaemonAlchemist_atp
|
train
|
ea287f0ee956e4e9639fde32e494fc0b6c94b1e6
|
diff --git a/ext.py b/ext.py
index <HASH>..<HASH> 100644
--- a/ext.py
+++ b/ext.py
@@ -44,9 +44,11 @@ def create_logger(verbosity):
def build_extension(cmd, verbosity=3):
assert cmd in ["asan", "build", "coverage", "debug"]
+ arch = getattr(sys.implementation, "_multiarch", "unknown")
windows = (sys.platform == "win32")
macos = (sys.platform == "darwin")
linux = (sys.platform == "linux")
+ ppc64 = ("ppc64" in arch or "powerpc64" in arch)
if not (windows or macos or linux):
print("\x1b[93mWarning: unknown platform %s\x1b[m" % sys.platform)
linux = True
@@ -80,6 +82,8 @@ def build_extension(cmd, verbosity=3):
ext.compiler.add_linker_flag("-undefined", "dynamic_lookup")
if linux:
ext.compiler.add_linker_flag("-lstdc++")
+ if ppc64:
+ ext.compiler.add_linker_flag("-pthread")
if cmd == "asan":
ext.compiler.add_compiler_flag("-fsanitize=address")
|
Fix PPC build (#<I>)
|
h2oai_datatable
|
train
|
c2d77312b6a2851241d6fa618f65c4ae71e4acad
|
diff --git a/apps/actor-android/src/main/java/im/actor/messenger/app/fragment/dialogs/DialogsAdapter.java b/apps/actor-android/src/main/java/im/actor/messenger/app/fragment/dialogs/DialogsAdapter.java
index <HASH>..<HASH> 100644
--- a/apps/actor-android/src/main/java/im/actor/messenger/app/fragment/dialogs/DialogsAdapter.java
+++ b/apps/actor-android/src/main/java/im/actor/messenger/app/fragment/dialogs/DialogsAdapter.java
@@ -4,8 +4,8 @@ import android.content.Context;
import android.view.ViewGroup;
import android.widget.FrameLayout;
-import im.actor.messenger.app.view.OnItemClickedListener;
import im.actor.android.view.BindedListAdapter;
+import im.actor.messenger.app.view.OnItemClickedListener;
import im.actor.model.entity.Dialog;
import im.actor.model.mvvm.BindedDisplayList;
@@ -29,6 +29,7 @@ public class DialogsAdapter extends BindedListAdapter<Dialog, DialogHolder> {
@Override
public void onBindViewHolder(DialogHolder dialogHolder, int index, Dialog item) {
+ // Log.d("DialogsAdapter", "Perform bind @" + index);
dialogHolder.bind(item, index == getItemCount() - 1);
}
diff --git a/library/actor-common-base/src/main/java/im/actor/model/modules/DisplayLists.java b/library/actor-common-base/src/main/java/im/actor/model/modules/DisplayLists.java
index <HASH>..<HASH> 100644
--- a/library/actor-common-base/src/main/java/im/actor/model/modules/DisplayLists.java
+++ b/library/actor-common-base/src/main/java/im/actor/model/modules/DisplayLists.java
@@ -113,8 +113,8 @@ public class DisplayLists extends BaseModule {
}
};
}
- BindedDisplayList<Dialog> displayList = new BindedDisplayList<Dialog>(operationMode,
- (ListEngineDisplayExt<Dialog>) dialogsEngine, isGlobalList, LOAD_PAGE, LOAD_GAP, hook);
+ BindedDisplayList<Dialog> displayList = new BindedDisplayList<Dialog>((ListEngineDisplayExt<Dialog>) dialogsEngine,
+ isGlobalList, LOAD_PAGE, LOAD_GAP, hook);
displayList.initTop(false);
return displayList;
}
@@ -127,8 +127,8 @@ public class DisplayLists extends BaseModule {
throw new RuntimeException("Contacts ListEngine must implement ListEngineDisplayExt for using global list");
}
- BindedDisplayList<Contact> contactList = new BindedDisplayList<Contact>(operationMode,
- (ListEngineDisplayExt<Contact>) contactsEngine, isGlobalList, LOAD_PAGE, LOAD_GAP, null);
+ BindedDisplayList<Contact> contactList = new BindedDisplayList<Contact>((ListEngineDisplayExt<Contact>) contactsEngine,
+ isGlobalList, LOAD_PAGE, LOAD_GAP, null);
contactList.initTop(false);
return contactList;
}
@@ -159,8 +159,8 @@ public class DisplayLists extends BaseModule {
};
}
- BindedDisplayList<Message> chatList = new BindedDisplayList<Message>(operationMode,
- (ListEngineDisplayExt<Message>) messagesEngine, isGlobalList, LOAD_PAGE, LOAD_GAP, hook);
+ BindedDisplayList<Message> chatList = new BindedDisplayList<Message>((ListEngineDisplayExt<Message>) messagesEngine,
+ isGlobalList, LOAD_PAGE, LOAD_GAP, hook);
chatList.initTop(false);
return chatList;
}
@@ -173,8 +173,8 @@ public class DisplayLists extends BaseModule {
throw new RuntimeException("Media ListEngine must implement ListEngineDisplayExt for using global list");
}
- BindedDisplayList<Message> mediaList = new BindedDisplayList<Message>(operationMode,
- (ListEngineDisplayExt<Message>) mediaEngine, isGlobalList, LOAD_PAGE, LOAD_GAP, null);
+ BindedDisplayList<Message> mediaList = new BindedDisplayList<Message>((ListEngineDisplayExt<Message>) mediaEngine,
+ isGlobalList, LOAD_PAGE, LOAD_GAP, null);
mediaList.initTop(false);
return mediaList;
}
@@ -187,8 +187,8 @@ public class DisplayLists extends BaseModule {
throw new RuntimeException("Search ListEngine must implement ListEngineDisplayExt for using global list");
}
- BindedDisplayList<SearchEntity> contactList = new BindedDisplayList<SearchEntity>(operationMode,
- (ListEngineDisplayExt<SearchEntity>) contactsEngine, isGlobalList, LOAD_PAGE, LOAD_GAP, null);
+ BindedDisplayList<SearchEntity> contactList = new BindedDisplayList<SearchEntity>((ListEngineDisplayExt<SearchEntity>) contactsEngine,
+ isGlobalList, LOAD_PAGE, LOAD_GAP, null);
contactList.initEmpty();
return contactList;
}
|
feat(common-base): Fixed compilation error
|
actorapp_actor-platform
|
train
|
5bbd0b0547b18130225d4a87c046690685e02d02
|
diff --git a/lib/mk_time/consts.rb b/lib/mk_time/consts.rb
index <HASH>..<HASH> 100644
--- a/lib/mk_time/consts.rb
+++ b/lib/mk_time/consts.rb
@@ -181,7 +181,8 @@ module MkTime
["20170629", 0.3],
["20171130", 0.2],
["20180315", 0.1],
- ["20180615", 0.0] # (<= Provisional end-point)
+ ["20180921", 0.0],
+ ["20181221", 0.0] # (<= Provisional end-point)
].freeze # DUT1 adjustment
end
end
diff --git a/lib/mk_time/version.rb b/lib/mk_time/version.rb
index <HASH>..<HASH> 100644
--- a/lib/mk_time/version.rb
+++ b/lib/mk_time/version.rb
@@ -1,3 +1,3 @@
module MkTime
- VERSION = "0.3.5"
+ VERSION = "0.3.6"
end
|
UPD: Added a new DUT1 adjustment to constants.
|
komasaru_mk_time
|
train
|
f5ee606d20ed10360c1072ca9080c6b642110145
|
diff --git a/src/Schema/Directives/Fields/AuthDirective.php b/src/Schema/Directives/Fields/AuthDirective.php
index <HASH>..<HASH> 100644
--- a/src/Schema/Directives/Fields/AuthDirective.php
+++ b/src/Schema/Directives/Fields/AuthDirective.php
@@ -4,12 +4,29 @@ namespace Nuwave\Lighthouse\Schema\Directives\Fields;
use Illuminate\Contracts\Auth\Authenticatable;
use Nuwave\Lighthouse\Schema\Values\FieldValue;
+use Illuminate\Contracts\Auth\Factory as AuthFactory;
use Nuwave\Lighthouse\Schema\Directives\BaseDirective;
use Nuwave\Lighthouse\Support\Contracts\FieldResolver;
class AuthDirective extends BaseDirective implements FieldResolver
{
/**
+ * @var \Illuminate\Contracts\Auth\Factory
+ */
+ private $authFactory;
+
+ /**
+ * AuthDirective constructor.
+ *
+ * @param \Illuminate\Contracts\Auth\Factory $authFactory
+ * @return void
+ */
+ public function __construct(AuthFactory $authFactory)
+ {
+ $this->authFactory = $authFactory;
+ }
+
+ /**
* Name of the directive.
*
* @return string
@@ -28,11 +45,15 @@ class AuthDirective extends BaseDirective implements FieldResolver
*/
public function resolveField(FieldValue $fieldValue): FieldValue
{
+ /** @var string|null $guard */
$guard = $this->directiveArgValue('guard');
return $fieldValue->setResolver(
function () use ($guard): ?Authenticatable {
- return auth($guard)->user();
+ return $this
+ ->authFactory
+ ->guard($guard)
+ ->user();
}
);
}
diff --git a/src/Schema/Values/CacheValue.php b/src/Schema/Values/CacheValue.php
index <HASH>..<HASH> 100644
--- a/src/Schema/Values/CacheValue.php
+++ b/src/Schema/Values/CacheValue.php
@@ -74,7 +74,7 @@ class CacheValue
? 'auth'
: null,
$this->privateCache
- ? auth()->user()->getKey()
+ ? app('auth')->user()->getKey()
: null,
strtolower($this->resolveInfo->parentType->name),
$this->fieldKey,
diff --git a/src/Support/helpers.php b/src/Support/helpers.php
index <HASH>..<HASH> 100644
--- a/src/Support/helpers.php
+++ b/src/Support/helpers.php
@@ -15,18 +15,6 @@ if (! function_exists('graphql')) {
}
}
-if (! function_exists('auth')) {
- /**
- * Get instance of auth container.
- *
- * @return \Illuminate\Auth\AuthManager
- */
- function auth()
- {
- return app('auth');
- }
-}
-
if (! function_exists('config_path')) {
/**
* Get base configuration path.
|
Use DI in favour of redefining the auth helper method
|
nuwave_lighthouse
|
train
|
793f2cc6885577e1601b8d47b994b1dd5fca31f5
|
diff --git a/BAC0/scripts/Lite.py b/BAC0/scripts/Lite.py
index <HASH>..<HASH> 100755
--- a/BAC0/scripts/Lite.py
+++ b/BAC0/scripts/Lite.py
@@ -53,12 +53,19 @@ from ..core.io.IOExceptions import (
UnrecognizedService,
Timeout,
)
-from ..db.influxdb import InfluxDB
+
from ..tasks.RecurringTask import RecurringTask
from ..tasks.UpdateCOV import Update_local_COV
from ..infos import __version__ as version
+try:
+ from ..db.influxdb import InfluxDB
+
+ INFLUXDB = True
+except ImportError:
+ INFLUXDB = False
+
from bacpypes.pdu import Address
# ------------------------------------------------------------------------------
@@ -168,7 +175,7 @@ class Lite(
self._log.info("Update Local COV Task started")
# Activate InfluxDB if params are available
- if db_params:
+ if db_params and INFLUXDB:
self.database = (
InfluxDB(db_params) if db_params["name"].lower() == "influxdb" else None
)
|
Prevents app from failing if influxdb_client is not installed
|
ChristianTremblay_BAC0
|
train
|
95d5450a7f7e39f133a725614c9e4515bec61368
|
diff --git a/lxd/warnings/warnings.go b/lxd/warnings/warnings.go
index <HASH>..<HASH> 100644
--- a/lxd/warnings/warnings.go
+++ b/lxd/warnings/warnings.go
@@ -213,3 +213,54 @@ func DeleteWarningsByLocalNodeAndProjectAndEntity(cluster *db.Cluster, projectNa
return DeleteWarningsByNodeAndProjectAndEntity(cluster, localName, projectName, entityTypeCode, entityID)
}
+
+// DeleteWarningsByNodeAndProjectAndTypeAndEntity deletes warnings with the given node, project, type code, and entity.
+func DeleteWarningsByNodeAndProjectAndTypeAndEntity(cluster *db.Cluster, nodeName string, projectName string, typeCode db.WarningType, entityTypeCode int, entityID int) error {
+ err := cluster.Transaction(func(tx *db.ClusterTx) error {
+ warnings, err := tx.GetWarningsByType(typeCode)
+ if err != nil {
+ return err
+ }
+
+ for _, w := range warnings {
+ if w.Node != nodeName || w.Project != projectName || w.EntityTypeCode != entityTypeCode || entityID != entityID {
+ continue
+ }
+
+ err = tx.DeleteWarning(w.UUID)
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ return errors.Wrap(err, "Failed to delete warnings")
+ }
+
+ return nil
+}
+
+// DeleteWarningsByLocalNodeAndProjectAndTypeAndEntity resolves warnings with the given project, type code, and entity.
+func DeleteWarningsByLocalNodeAndProjectAndTypeAndEntity(cluster *db.Cluster, projectName string, typeCode db.WarningType, entityTypeCode int, entityID int) error {
+ var err error
+ var localName string
+
+ err = cluster.Transaction(func(tx *db.ClusterTx) error {
+ localName, err = tx.GetLocalNodeName()
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+ if err != nil {
+ return errors.Wrap(err, "Failed getting local member name")
+ }
+
+ if localName == "" {
+ return fmt.Errorf("Local member name not available")
+ }
+
+ return DeleteWarningsByNodeAndProjectAndTypeAndEntity(cluster, localName, projectName, typeCode, entityTypeCode, entityID)
+}
|
lxd/warnings: Add more delete functions
|
lxc_lxd
|
train
|
01fe005d0aa1774d173c5acfee35238f845fcd43
|
diff --git a/Request/ParamConverter/DoctrineParamConverter.php b/Request/ParamConverter/DoctrineParamConverter.php
index <HASH>..<HASH> 100644
--- a/Request/ParamConverter/DoctrineParamConverter.php
+++ b/Request/ParamConverter/DoctrineParamConverter.php
@@ -36,7 +36,7 @@ class DoctrineParamConverter implements ParamConverterInterface
/**
* @{inheritdoc}
- *
+ *
* @throws \LogicException When unable to guess how to get a Doctrine instance from the request information
* @throws NotFoundHttpException When object not found
*/
@@ -143,6 +143,10 @@ class DoctrineParamConverter implements ParamConverterInterface
}
}
+ if ($options['strip_null']) {
+ $criteria = array_filter($criteria, function ($value) { return !is_null($value); });
+ }
+
if (!$criteria) {
return false;
}
@@ -191,6 +195,7 @@ class DoctrineParamConverter implements ParamConverterInterface
'entity_manager' => null,
'exclude' => array(),
'mapping' => array(),
+ 'strip_null' => false,
), $configuration->getOptions());
}
diff --git a/Tests/Request/ParamConverter/DoctrineParamConverterTest.php b/Tests/Request/ParamConverter/DoctrineParamConverterTest.php
index <HASH>..<HASH> 100644
--- a/Tests/Request/ParamConverter/DoctrineParamConverterTest.php
+++ b/Tests/Request/ParamConverter/DoctrineParamConverterTest.php
@@ -82,6 +82,37 @@ class DoctrineParamConverterTest extends \PHPUnit_Framework_TestCase
$this->assertNull($request->attributes->get('arg'));
}
+ public function testApplyWithStripNulls()
+ {
+ $request = new Request();
+ $request->attributes->set('arg', null);
+ $config = $this->createConfiguration('stdClass', array('mapping' => array('arg' => 'arg'), 'strip_null' => true), 'arg', true);
+
+ $classMetadata = $this->getMock('Doctrine\Common\Persistence\Mapping\ClassMetadata');
+ $manager = $this->getMock('Doctrine\Common\Persistence\ObjectManager');
+ $manager->expects($this->once())
+ ->method('getClassMetadata')
+ ->with('stdClass')
+ ->will($this->returnValue($classMetadata));
+
+ $manager->expects($this->never())
+ ->method('getRepository');
+
+ $this->registry->expects($this->once())
+ ->method('getManagerForClass')
+ ->with('stdClass')
+ ->will($this->returnValue($manager));
+
+ $classMetadata->expects($this->once())
+ ->method('hasField')
+ ->with($this->equalTo('arg'))
+ ->will($this->returnValue(true));
+
+ $this->converter->apply($request, $config);
+
+ $this->assertNull($request->attributes->get('arg'));
+ }
+
/**
* @dataProvider idsProvider
*/
|
Added ability to ignore null request attributes
|
sensiolabs_SensioFrameworkExtraBundle
|
train
|
9d7c6b6954552a7011a76c846bcfc26628d0a78d
|
diff --git a/tests/ExampleField.php b/tests/ExampleField.php
index <HASH>..<HASH> 100644
--- a/tests/ExampleField.php
+++ b/tests/ExampleField.php
@@ -43,6 +43,8 @@ class ExampleField extends Example
$value = $property->proceed();
echo
"Calling Around Interceptor for field: ",
+ get_class($property->getThis()),
+ "->",
$property->getField()->getName(),
", access: $type",
", value: ",
diff --git a/tests/index.php b/tests/index.php
index <HASH>..<HASH> 100644
--- a/tests/index.php
+++ b/tests/index.php
@@ -12,6 +12,7 @@ use Go\Aop\Support\DefaultPointcutAdvisor;
use Go\Aop\Support\NameMatchMethodPointcut;
use Go\Aop\Framework\FieldBeforeInterceptor;
use Go\Aop\Framework\ClassFieldAccess;
+use Go\Aop\Framework\MethodAfterInterceptor;
use Go\Aop\Framework\MethodBeforeInterceptor;
use Go\Aop\Intercept\FieldAccess;
use Go\Aop\Intercept\MethodInvocation;
@@ -34,17 +35,36 @@ Autoload::init();
$pointcut = new NameMatchMethodPointcut();
$pointcut->setMappedName('*');
-$advice = new MethodBeforeInterceptor(function(MethodInvocation $invocation) {
+$before = new MethodBeforeInterceptor(function(MethodInvocation $invocation) {
+ $obj = $invocation->getThis();
echo 'Calling Before Interceptor for method: ',
+ is_object($obj) ? get_class($obj) : $obj,
+ $invocation->getMethod()->isStatic() ? '::' : '->',
$invocation->getMethod()->getName(),
+ '()',
+ ' with arguments: ',
+ json_encode($invocation->getArguments()),
+ "<br>\n";
+}, $pointcut);
+
+$after = new MethodAfterInterceptor(function(MethodInvocation $invocation) {
+ $obj = $invocation->getThis();
+ echo 'Calling After Interceptor for method: ',
+ is_object($obj) ? get_class($obj) : $obj,
+ $invocation->getMethod()->isStatic() ? '::' : '->',
+ $invocation->getMethod()->getName(),
+ '()',
' with arguments: ',
json_encode($invocation->getArguments()),
"<br>\n";
}, $pointcut);
-$advisor = new DefaultPointcutAdvisor($pointcut, $advice);
-AdvisorRegistry::register($advisor);
+$beforeAdvisor = new DefaultPointcutAdvisor($pointcut, $before);
+$afterAdvisor = new DefaultPointcutAdvisor($pointcut, $after);
+
+AdvisorRegistry::register($beforeAdvisor);
+AdvisorRegistry::register($afterAdvisor);
/*********************************************************************************
* CONFIGURATION FOR TRANSFORMERS BLOCK
@@ -56,8 +76,7 @@ $sourceTransformers = array(
new AopProxyTransformer(
new TokenReflection\Broker(
new TokenReflection\Broker\Backend\Memory()
- ),
- $advisor
+ )
),
);
@@ -70,8 +89,10 @@ foreach ($sourceTransformers as $sourceTransformer) {
* Remark: SourceTransformingLoader::load('app_autoload.php') should be here later
**********************************************************************************/
-//$class = new Example();
-//$class->hello('Welcome!');
+$class = new Example();
+$class->hello('Welcome!');
+
+echo "=========================================<br>\n";
$class = new ExampleField();
$class->hello('welcome');
|
More debug info, add one more interceptor to test chain
|
goaop_framework
|
train
|
c519bfdb31d090c2d0a74ca65e9c0efc49324d94
|
diff --git a/test/Test/Net/Bazzline/Component/Csv/AbstractTestCase.php b/test/Test/Net/Bazzline/Component/Csv/AbstractTestCase.php
index <HASH>..<HASH> 100644
--- a/test/Test/Net/Bazzline/Component/Csv/AbstractTestCase.php
+++ b/test/Test/Net/Bazzline/Component/Csv/AbstractTestCase.php
@@ -100,4 +100,12 @@ abstract class AbstractTestCase extends PHPUnit_Framework_TestCase
{
return $this->writerFactory->create();
}
+
+ /**
+ * @return boolean
+ */
+ protected function phpVersionLessThen5Dot4()
+ {
+ return (version_compare(phpversion(), '5.4', '<'));
+ }
}
\ No newline at end of file
diff --git a/test/Test/Net/Bazzline/Component/Csv/EasyCsvReaderAdapterTest.php b/test/Test/Net/Bazzline/Component/Csv/EasyCsvReaderAdapterTest.php
index <HASH>..<HASH> 100644
--- a/test/Test/Net/Bazzline/Component/Csv/EasyCsvReaderAdapterTest.php
+++ b/test/Test/Net/Bazzline/Component/Csv/EasyCsvReaderAdapterTest.php
@@ -50,12 +50,6 @@ class EasyCsvReaderAdapterTest extends AbstractTestCase
*/
public function getReaders()
{
- $file = $this->createFile('read.csv');
- //$fileWithSemicolonAsDelimiter = $this->createFile('read_sc.csv');
- $filesystem = $this->createFilesystem();
- //$path = $this->createRealFilePath('read.csv');
- $pathWithSemicolonAsDelimiter = $this->createRealFilePath('read_cs.csv');
-
$content =
'"column1", "column2", "column3"' . PHP_EOL .
'"1column2value", "1column3value", "1column4value"' . PHP_EOL .
@@ -71,18 +65,28 @@ class EasyCsvReaderAdapterTest extends AbstractTestCase
'"4column2value"; "4column3value"; "4column4value"' . PHP_EOL .
'5column2value"; "5column3value"; "5column4value"';
- //file_put_contents($path, $content);
- file_put_contents($pathWithSemicolonAsDelimiter, $contentWithSemicolonAsDelimiter);
+ if ($this->phpVersionLessThen5Dot4()) {
+ $path = $this->createRealFilePath('read.csv');
+ $pathWithSemicolonAsDelimiter = $this->createRealFilePath('read_cs.csv');
- $file->setContent($content);
- //$fileWithSemicolonAsDelimiter->setContent($contentWithSemicolonAsDelimiter);
- $filesystem->addChild($file);
- //$filesystem->addChild($fileWithSemicolonAsDelimiter);
+ file_put_contents($path, $content);
+ file_put_contents($pathWithSemicolonAsDelimiter, $contentWithSemicolonAsDelimiter);
- $reader = new EasyCsvReaderAdapter($file->url());
- //$reader = new EasyCsvReaderAdapter($path);
- //$readerWithSemicolonAsDelimiter = new EasyCsvReaderAdapter($fileWithSemicolonAsDelimiter->url());
- $readerWithSemicolonAsDelimiter = new EasyCsvReaderAdapter($pathWithSemicolonAsDelimiter);
+ $reader = new EasyCsvReaderAdapter($path);
+ $readerWithSemicolonAsDelimiter = new EasyCsvReaderAdapter($pathWithSemicolonAsDelimiter);
+ } else {
+ $file = $this->createFile('read.csv');
+ $filesystem = $this->createFilesystem();
+ $fileWithSemicolonAsDelimiter = $this->createFile('read_sc.csv');
+
+ $file->setContent($content);
+ $fileWithSemicolonAsDelimiter->setContent($contentWithSemicolonAsDelimiter);
+ $filesystem->addChild($file);
+ $filesystem->addChild($fileWithSemicolonAsDelimiter);
+
+ $reader = new EasyCsvReaderAdapter($file->url());
+ $readerWithSemicolonAsDelimiter = new EasyCsvReaderAdapter($fileWithSemicolonAsDelimiter->url());
+ }
$readerWithSemicolonAsDelimiter->setDelimiter(';');
|
implemented switch to php <I>
|
bazzline_php_component_csv
|
train
|
f14b5fe602bcb620a228a68060fa1fc551a950fc
|
diff --git a/cmsplugin_cascade/sphinx/cms_apps.py b/cmsplugin_cascade/sphinx/cms_apps.py
index <HASH>..<HASH> 100644
--- a/cmsplugin_cascade/sphinx/cms_apps.py
+++ b/cmsplugin_cascade/sphinx/cms_apps.py
@@ -50,5 +50,5 @@ class SphinxDocsApp(CMSApp):
def get_urls(self, page=None, language=None, **kwargs):
return [
- url(r'^(?P<slug>\S+)/?$', SphinxDocsView.as_view(), name='sphinx-documentation'),
+ url(r'^(?P<slug>\S+)/$', SphinxDocsView.as_view(), name='sphinx-documentation'),
]
|
always append slash to docs-URL
|
jrief_djangocms-cascade
|
train
|
c35662b667cde4ac74f114e317e787aea97e0f8c
|
diff --git a/test/e2e/upgrades/daemonsets.go b/test/e2e/upgrades/daemonsets.go
index <HASH>..<HASH> 100644
--- a/test/e2e/upgrades/daemonsets.go
+++ b/test/e2e/upgrades/daemonsets.go
@@ -36,7 +36,7 @@ type DaemonSetUpgradeTest struct {
daemonSet *extensions.DaemonSet
}
-func (DaemonSetUpgradeTest) Name() string { return "daemonset-upgrade" }
+func (DaemonSetUpgradeTest) Name() string { return "[sig-apps] daemonset-upgrade" }
// Setup creates a DaemonSet and verifies that it's running
func (t *DaemonSetUpgradeTest) Setup(f *framework.Framework) {
diff --git a/test/e2e/upgrades/deployments.go b/test/e2e/upgrades/deployments.go
index <HASH>..<HASH> 100644
--- a/test/e2e/upgrades/deployments.go
+++ b/test/e2e/upgrades/deployments.go
@@ -40,7 +40,7 @@ type DeploymentUpgradeTest struct {
newRS *extensions.ReplicaSet
}
-func (DeploymentUpgradeTest) Name() string { return "deployment-upgrade" }
+func (DeploymentUpgradeTest) Name() string { return "[sig-apps] deployment-upgrade" }
func (DeploymentUpgradeTest) Skip(upgCtx UpgradeContext) bool {
// The Deployment upgrade test currently relies on implementation details to probe the
diff --git a/test/e2e/upgrades/job.go b/test/e2e/upgrades/job.go
index <HASH>..<HASH> 100644
--- a/test/e2e/upgrades/job.go
+++ b/test/e2e/upgrades/job.go
@@ -31,7 +31,7 @@ type JobUpgradeTest struct {
namespace string
}
-func (JobUpgradeTest) Name() string { return "job-upgrade" }
+func (JobUpgradeTest) Name() string { return "[sig-apps] job-upgrade" }
// Setup starts a Job with a parallelism of 2 and 2 completions running.
func (t *JobUpgradeTest) Setup(f *framework.Framework) {
diff --git a/test/e2e/upgrades/statefulset.go b/test/e2e/upgrades/statefulset.go
index <HASH>..<HASH> 100644
--- a/test/e2e/upgrades/statefulset.go
+++ b/test/e2e/upgrades/statefulset.go
@@ -34,7 +34,7 @@ type StatefulSetUpgradeTest struct {
set *apps.StatefulSet
}
-func (StatefulSetUpgradeTest) Name() string { return "statefulset-upgrade" }
+func (StatefulSetUpgradeTest) Name() string { return "[sig-apps] statefulset-upgrade" }
func (StatefulSetUpgradeTest) Skip(upgCtx UpgradeContext) bool {
minVersion := version.MustParseSemantic("1.5.0")
|
add [sig-apps] identifier to relevant upgrade tests
|
kubernetes_kubernetes
|
train
|
9390141ae9620b4767bad6911df61fd12f0cc47c
|
diff --git a/lib/rails_admin/config/fields/base.rb b/lib/rails_admin/config/fields/base.rb
index <HASH>..<HASH> 100644
--- a/lib/rails_admin/config/fields/base.rb
+++ b/lib/rails_admin/config/fields/base.rb
@@ -178,7 +178,7 @@ module RailsAdmin
register_instance_option(:required?) do
@required ||= begin
validators = abstract_model.model.validators_on(@name)
- required_by_validator = validators.find{|v| (v.class == ActiveModel::Validations::PresenceValidator) || (v.class == ActiveModel::Validations::NumericalityValidator && v.options[:allow_nil]==false)} && true || false
+ required_by_validator = validators.find{|v| (v.class == ActiveModel::Validations::PresenceValidator) || (v.class == ActiveModel::Validations::NumericalityValidator && !v.options[:allow_nil])} && true || false
properties && !properties[:nullable?] || required_by_validator
end
end
diff --git a/lib/rails_admin/config/fields/types/belongs_to_association.rb b/lib/rails_admin/config/fields/types/belongs_to_association.rb
index <HASH>..<HASH> 100644
--- a/lib/rails_admin/config/fields/types/belongs_to_association.rb
+++ b/lib/rails_admin/config/fields/types/belongs_to_association.rb
@@ -20,8 +20,8 @@ module RailsAdmin
key_properties = abstract_model.properties.find{|p| p[:name] == method_name}
key_validators = abstract_model.model.validators_on(method_name)
validators = abstract_model.model.validators_on(name)
- key_required_by_validator = key_validators.find{|v| (v.class == ActiveModel::Validations::PresenceValidator) || (v.class == ActiveModel::Validations::NumericalityValidator && v.options[:allow_nil]==false)} && true || false
- required_by_validator = validators.find{|v| (v.class == ActiveModel::Validations::PresenceValidator) || (v.class == ActiveModel::Validations::NumericalityValidator && v.options[:allow_nil]==false)} && true || false
+ key_required_by_validator = key_validators.find{|v| (v.class == ActiveModel::Validations::PresenceValidator) || (v.class == ActiveModel::Validations::NumericalityValidator && !v.options[:allow_nil])} && true || false
+ required_by_validator = validators.find{|v| (v.class == ActiveModel::Validations::PresenceValidator) || (v.class == ActiveModel::Validations::NumericalityValidator && !v.options[:allow_nil])} && true || false
key_properties && !key_properties[:nullable?] || key_required_by_validator || required_by_validator
end
end
|
options[:allow_nil] is not always present in rails <I>
|
sferik_rails_admin
|
train
|
287f12807512577395a264365a6acabfeb1b71dd
|
diff --git a/src/components/input-checkbox/input-checkbox.component.js b/src/components/input-checkbox/input-checkbox.component.js
index <HASH>..<HASH> 100644
--- a/src/components/input-checkbox/input-checkbox.component.js
+++ b/src/components/input-checkbox/input-checkbox.component.js
@@ -1,6 +1,6 @@
import React from 'react';
import PropTypes from 'prop-types';
-import FieldCheckbox from '../decorators/field-checkbox.higher-order-component';
+import ControlledCheckbox from '../decorators/controlled-checkbox.decorator';
import style from './input-checkbox.component.scss';
@@ -59,4 +59,4 @@ InputCheckbox.defaultProps = {
required: false,
};
-export default FieldCheckbox(InputCheckbox);
+export default ControlledCheckbox(InputCheckbox);
diff --git a/src/components/input-number/input-number.component.js b/src/components/input-number/input-number.component.js
index <HASH>..<HASH> 100644
--- a/src/components/input-number/input-number.component.js
+++ b/src/components/input-number/input-number.component.js
@@ -1,6 +1,6 @@
import React from 'react';
import PropTypes from 'prop-types';
-import Field from '../decorators/field.higher-order-component';
+import ControlledNumber from '../decorators/controlled-number.decorator';
import style from './input-number.component.scss';
@@ -39,9 +39,9 @@ export function InputNumber({
InputNumber.propTypes = {
label: PropTypes.string,
name: PropTypes.string.isRequired,
- placeholder: PropTypes.string,
+ placeholder: PropTypes.number,
required: PropTypes.bool,
- value: PropTypes.string,
+ value: PropTypes.number,
handleChange: PropTypes.func.isRequired,
};
@@ -49,7 +49,7 @@ InputNumber.defaultProps = {
label: null,
placeholder: null,
required: false,
- value: '',
+ value: 0,
};
-export default Field(InputNumber);
+export default ControlledNumber(InputNumber);
diff --git a/src/components/input-text/input-text.component.js b/src/components/input-text/input-text.component.js
index <HASH>..<HASH> 100644
--- a/src/components/input-text/input-text.component.js
+++ b/src/components/input-text/input-text.component.js
@@ -1,6 +1,6 @@
import React from 'react';
import PropTypes from 'prop-types';
-import Field from '../decorators/field.higher-order-component';
+import ControlledText from '../decorators/controlled-text.decorator';
import style from './input-text.component.scss';
@@ -52,4 +52,4 @@ InputText.defaultProps = {
value: '',
};
-export default Field(InputText);
+export default ControlledText(InputText);
|
refactor components
update the components to use the refactored decorators
|
luetkemj_aglet-components
|
train
|
68efb250d2d617a342d6cdc95fca68957ae6e8d3
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -5,18 +5,20 @@ module.exports = {
included(appOrAddon) {
let app = appOrAddon.app || appOrAddon;
- if (!app.__emberBasicDropdownIncludedInvoked) {
- app.__emberBasicDropdownIncludedInvoked = true;
+ if (app.__emberBasicDropdownIncludedInvoked) {
this._super.included.apply(this, arguments);
+ return;
+ }
+ app.__emberBasicDropdownIncludedInvoked = true;
+ this._super.included.apply(this, arguments);
- let hasSass = !!app.registry.availablePlugins['ember-cli-sass'];
- let hasLess = !!app.registry.availablePlugins['ember-cli-less'];
+ let hasSass = !!app.registry.availablePlugins['ember-cli-sass'];
+ let hasLess = !!app.registry.availablePlugins['ember-cli-less'];
- // Don't include the precompiled css file if the user uses a supported CSS preprocessor
- if (!hasSass && !hasLess) {
- if (!app.__skipEmberBasicDropdownStyles) {
- app.import('vendor/ember-basic-dropdown.css');
- }
+ // Don't include the precompiled css file if the user uses a supported CSS preprocessor
+ if (!hasSass && !hasLess) {
+ if (!app.__skipEmberBasicDropdownStyles) {
+ app.import('vendor/ember-basic-dropdown.css');
}
}
},
|
Always call _super.included (#<I>)
|
cibernox_ember-basic-dropdown
|
train
|
60c32e2109206fcbb336498bc0d1e7f644a8b6da
|
diff --git a/gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/PropertiesAnimation.java b/gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/PropertiesAnimation.java
index <HASH>..<HASH> 100755
--- a/gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/PropertiesAnimation.java
+++ b/gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/PropertiesAnimation.java
@@ -15,8 +15,6 @@
*/
package com.google.gwt.query.client.plugins;
-import java.util.ArrayList;
-
import com.google.gwt.animation.client.Animation;
import com.google.gwt.dom.client.Element;
import com.google.gwt.query.client.Function;
@@ -26,6 +24,8 @@ import com.google.gwt.query.client.JSArray;
import com.google.gwt.query.client.Properties;
import com.google.gwt.query.client.Regexp;
+import java.util.ArrayList;
+
/**
* Animation effects on any numeric CSS property.
*/
@@ -69,45 +69,59 @@ public class PropertiesAnimation extends Animation {
}
private static final String[] attrsToSave = new String[] { "overflow",
- "visibility", "white-space" };
+ "visibility" };
private static Regexp nonPxRegExp = new Regexp(
"z-?index|font-?weight|opacity|zoom|line-?height", "i");
- public static Effect computeFxProp(Element e, String key, String val, boolean hidden) {
+
+ public static Effect computeFxProp(Element e, String key, String val,
+ boolean hidden) {
GQuery g = Effects.$(e);
+ String unit = "";
if ("toggle".equals(val)) {
val = hidden ? "show" : "hide";
}
+
+ if (("show".equals(val) && !hidden) || ("hide").equals(val) && hidden){
+ return null;
+ }
+
+ if (hidden){
+ g.show();
+ }
double start = GQUtils.cur(e, key, true), end = start;
+
if ("show".equals(val)) {
- if (!hidden) {
- return null;
- }
g.saveCssAttrs(key);
start = 0;
+ unit = nonPxRegExp.test(key) ? "" : "px";
} else if ("hide".equals(val)) {
if (hidden) {
return null;
}
g.saveCssAttrs(key);
end = 0;
- }
- JSArray parts = new Regexp("^([+-]=)?([0-9+-.]+)(.*)?$").match(val);
- String unit = "";
- if (parts != null) {
- unit = nonPxRegExp.test(key) ? "" : parts.getStr(3) == null ? "px" : parts.getStr(3);
- end = Double.parseDouble(parts.getStr(2));
- if (!"px".equals(unit)) {
- double to = end == 0 ? 1 : end;
- g.css(key, to + unit);
- start = to * start / GQUtils.cur(e, key, true);
- g.css(key, start + unit);
- }
- if (parts.getStr(1) != null) {
- end = (("-=".equals(parts.getStr(1)) ? -1 : 1) * end) + start;
+ unit = nonPxRegExp.test(key) ? "" : "px";
+ } else {
+ JSArray parts = new Regexp("^([+-]=)?([0-9+-.]+)(.*)?$").match(val);
+
+ if (parts != null) {
+ unit = nonPxRegExp.test(key) ? "" : parts.getStr(3) == null ? "px"
+ : parts.getStr(3);
+ end = Double.parseDouble(parts.getStr(2));
+ if (!"px".equals(unit)) {
+ double to = end == 0 ? 1 : end;
+ g.css(key, to + unit);
+ start = to * start / GQUtils.cur(e, key, true);
+ g.css(key, start + unit);
+ }
+ if (parts.getStr(1) != null) {
+ end = (("-=".equals(parts.getStr(1)) ? -1 : 1) * end) + start;
+ }
}
- }
+ }
+
Effect fx = new Effect(key, val, start, end, unit);
return fx;
}
@@ -144,7 +158,7 @@ public class PropertiesAnimation extends Animation {
} else if ("show".equals(l.value)) {
g.show();
g.restoreCssAttrs(l.attr);
- }
+ }
}
g.restoreCssAttrs(attrsToSave);
g.each(funcs);
@@ -157,7 +171,7 @@ public class PropertiesAnimation extends Animation {
boolean move = false;
boolean hidden = !g.visible();
Effect fx;
- g.show();
+ //g.show();
for (String key : prps.keys()) {
String val = prps.get(key);
if ((fx = computeFxProp(e, key, val, hidden)) != null) {
@@ -169,7 +183,6 @@ public class PropertiesAnimation extends Animation {
g.saveCssAttrs(attrsToSave);
if (resize) {
g.css("overflow", "hidden");
- g.css("white-space", "nowrap");
}
if (move && !g.css("position", true).matches("absolute|relative")) {
g.css("position", "relative");
|
fix for issue <I> and <I>
|
ArcBees_gwtquery
|
train
|
fe2f512bebfb3b01bfff3ae7db6885221baa6e70
|
diff --git a/app/sse.js b/app/sse.js
index <HASH>..<HASH> 100644
--- a/app/sse.js
+++ b/app/sse.js
@@ -13,12 +13,13 @@ exports.initStream = function(req, res, closeCb){
res.write('data: \n\n');
var handle = setInterval(function() {
- res.write('\n');
+ if(!res.finished)
+ res.write('\n');
}, 30 * 1000);
//clean up
- res.on('finish', function() {
- closeCb();
+ res.on('close', function() {
clearInterval(handle);
+ closeCb();
});
};
|
Added response.finished guard to server sent events
|
JacobeanRnD_expresscion
|
train
|
fb1d21c0dad9e4048ddc7fabe83c948012c55a61
|
diff --git a/src/kff.PageView.js b/src/kff.PageView.js
index <HASH>..<HASH> 100644
--- a/src/kff.PageView.js
+++ b/src/kff.PageView.js
@@ -2,7 +2,6 @@
kff.PageView = kff.createClass(
{
extend: kff.View,
- mixins: kff.EventsMixin,
statics:
{
precedingView: null,
@@ -46,57 +45,6 @@ kff.PageView = kff.createClass(
{
if(!$element) $element = this.$docElement;
kff.PageView._super.undelegateEvents.call(this, events, $element);
- },
-
- /**
- * Sets a new state of the view. Called by the front controller.
- *
- * @param {Object} state The state object (POJO)
- */
- setState: function(state)
- {
- this.trigger('setState', state);
- },
-
- /**
- * Initializes the view. Calls the render method. Should not be overloaded
- * by subclasses.
- *
- * @private
- * @param
- */
- init: function()
- {
- this.renderAll();
- this.runAll();
- },
-
- /**
- * Runs the view (i.e. binds events and models). It will be called automatically. Should not be called
- * directly.
- */
- runAll: function()
- {
- if(kff.View.prototype.runAll.call(this) !== false)
- {
- this.trigger('render');
- }
- },
-
- /**
- * Destroys the view (destroys all subviews and unbinds previously bound DOM events.
- * It will be called automatically. Should not be called directly.
- *
- * @param {Boolean} silent If true, the 'destroy' event won't be called
- */
- destroyAll: function()
- {
- var ret = kff.View.prototype.destroyAll.call(this);
-
- if(ret !== false)
- {
- this.trigger('destroy');
- }
}
});
|
refactor(kff.PageView): remove overloaded Page methods previously used for async rendering
|
karfcz_kff
|
train
|
2b0ca0237fba3cdb4dc6b5399cc9700b99e0c028
|
diff --git a/filer/fields/multistorage_file.py b/filer/fields/multistorage_file.py
index <HASH>..<HASH> 100644
--- a/filer/fields/multistorage_file.py
+++ b/filer/fields/multistorage_file.py
@@ -1,9 +1,9 @@
#-*- coding: utf-8 -*-
-import os
import base64
import hashlib
import warnings
from io import BytesIO
+from django.core.files.base import ContentFile
from django.utils import six
from easy_thumbnails import fields as easy_thumbnails_fields, \
files as easy_thumbnails_files
@@ -124,13 +124,14 @@ class MultiStorageFileField(easy_thumbnails_fields.ThumbnailerField):
def to_python(self, value):
if isinstance(value, list) and len(value) == 2 and isinstance(value[0], six.text_type):
+ filename, payload = value
try:
- payload = base64.b64decode(value[1])
- filename = os.path.join(self.storage.location, value[0])
- out_buf = self.storage.open(filename, 'wb')
- out_buf.write(payload)
- out_buf.close()
- return value[0]
+ payload = base64.b64decode(payload)
except TypeError:
pass
+ else:
+ if self.storage.exists(filename):
+ self.storage.delete(filename)
+ self.storage.save(filename, ContentFile(payload))
+ return filename
return value
|
Rebased PR#<I> from rollstudio to the latest develop branch, b<I>
|
divio_django-filer
|
train
|
c409ec838b8d43a0bf0c184dc3c07ac5f817b45f
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,7 +1,8 @@
### Change log for autoNumeric:
### "2.0.0-beta.18"
-+ Fix issue #330 The `negativePositiveSignPlacement` option can be ignored in some cases
++ Fix issue #330 The `negativePositiveSignPlacement` option can be ignored in some cases
++ Fix issue #339 `get` returns `'0'` when the input is empty even if `emptyInputBehavior` is not equal to `'zero'`
### "2.0.0-beta.17"
+ Fix issue #317 allow jumping over the decimal character when the caret is just left of the decimal character and the user enters the decimal character
diff --git a/src/autoNumeric.js b/src/autoNumeric.js
index <HASH>..<HASH> 100644
--- a/src/autoNumeric.js
+++ b/src/autoNumeric.js
@@ -2002,6 +2002,11 @@ if (typeof define === 'function' && define.amd) {
* @returns {string}
*/
function cleanLeadingTrailingZeros(value, settings) {
+ // Return the empty string is the value is already empty. This prevent converting that value to '0'.
+ if (value === '') {
+ return '';
+ }
+
// Return '0' if the value is zero
if (Number(value) === 0 && settings.leadingZero !== 'keep') {
return '0';
@@ -2971,6 +2976,7 @@ if (typeof define === 'function' && define.amd) {
if (settings.negativeBracketsTypeOnBlur !== null && settings.negativeSignCharacter !== '') {
$this.val(toggleNegativeBracket(e.target.value, settings));
}
+
// clean the value to compare to rawValue
let result = stripAllNonNumberCharacters(e.target.value, settings, true);
result = convertToNumericString(result, settings);
@@ -2978,6 +2984,7 @@ if (typeof define === 'function' && define.amd) {
if (settings.trailingNegative) {
result = '-' + result;
}
+
if (settings.decimalPlacesShownOnFocus) {
settings.decimalPlacesOverride = settings.decimalPlacesShownOnFocus;
$this.autoNumeric('set', settings.rawValue);
diff --git a/test/unit/autoNumeric.spec.js b/test/unit/autoNumeric.spec.js
index <HASH>..<HASH> 100644
--- a/test/unit/autoNumeric.spec.js
+++ b/test/unit/autoNumeric.spec.js
@@ -696,6 +696,22 @@ describe(`autoNumeric 'get', 'getLocalized' and 'getNumber' methods`, () => {
});
describe(`autoNumeric 'get' methods`, () => {
+ it(`should return an empty string as the default value`, () => {
+ const newInput = document.createElement('input');
+ document.body.appendChild(newInput);
+ const aNInput = $(newInput).autoNumeric('init'); // Initiate the autoNumeric input
+
+ expect(aNInput.autoNumeric('get')).toEqual('');
+ });
+
+ it(`should return '0' as the default value`, () => {
+ const newInput = document.createElement('input');
+ document.body.appendChild(newInput);
+ const aNInput = $(newInput).autoNumeric('init', { emptyInputBehavior : 'zero' }); // Initiate the autoNumeric input
+
+ expect(aNInput.autoNumeric('get')).toEqual('0');
+ });
+
it(`should not return a negative value when inputting a positive one and minimumValue is equal to '0' (cf. issue #284)`, () => {
const newInput = document.createElement('input');
document.body.appendChild(newInput);
@@ -703,7 +719,7 @@ describe(`autoNumeric 'get' methods`, () => {
const aNInput = $(newInput).autoNumeric('init', { minimumValue: '0', maximumValue: '9999', decimalPlacesOverride: '2' }); // Initiate the autoNumeric input
expect(console.warn).toHaveBeenCalled();
- expect(aNInput.autoNumeric('get')).toEqual('0');
+ expect(aNInput.autoNumeric('get')).toEqual('');
aNInput.autoNumeric('set', 1234);
expect(aNInput.autoNumeric('get')).toEqual('1234');
aNInput.autoNumeric('set', 0);
@@ -722,7 +738,7 @@ describe(`autoNumeric 'get' methods`, () => {
const aNInput = $(newInput).autoNumeric('init', { minimumValue: '1', maximumValue: '9999', decimalPlacesOverride: '2' }); // Initiate the autoNumeric input
expect(console.warn).toHaveBeenCalled();
- expect(aNInput.autoNumeric('get')).toEqual('0');
+ expect(aNInput.autoNumeric('get')).toEqual('');
aNInput.autoNumeric('set', 1234);
expect(aNInput.autoNumeric('get')).toEqual('1234');
|
Fix issue #<I> `get` returns `'0'` when the input is empty even if `emptyInputBehavior` is not equal to `'zero'`
|
autoNumeric_autoNumeric
|
train
|
60e408ae0b31abd5ce757da4d4bc87e5a8bd3a2e
|
diff --git a/spec/reel/websocket_spec.rb b/spec/reel/websocket_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/reel/websocket_spec.rb
+++ b/spec/reel/websocket_spec.rb
@@ -61,12 +61,11 @@ RSpec.describe Reel::WebSocket do
describe "WebSocket#next_message" do
it "triggers on the next sent message" do
- skip "update to new Celluloid internal APIs"
with_websocket_pair do |client, websocket|
f = Celluloid::Future.new
websocket.on_message do |message|
- f << Celluloid::SuccessResponse.new(:on_message, message)
+ f << Celluloid::Internals::Response::Success.new(:on_message, message)
end
message = WebSocket::Message.new(example_message)
@@ -82,7 +81,6 @@ RSpec.describe Reel::WebSocket do
describe "WebSocket#read_every" do
it "automatically executes read" do
- skip "update to new Celluloid internal APIs"
with_websocket_pair do |client, websocket|
class MyActor
@@ -95,7 +93,7 @@ RSpec.describe Reel::WebSocket do
f = Celluloid::Future.new
websocket.on_message do |message|
- f << Celluloid::SuccessResponse.new(:on_message, message)
+ f << Celluloid::Internals::Response::Success.new(:on_message, message)
end
message = WebSocket::Message.new(example_message)
|
Updated web socket specs to new Celluloid internal APIs
|
celluloid_reel
|
train
|
8df16383e0565713860fe39b61eb203cfd83d00a
|
diff --git a/lib/ronin/platform/overlay.rb b/lib/ronin/platform/overlay.rb
index <HASH>..<HASH> 100644
--- a/lib/ronin/platform/overlay.rb
+++ b/lib/ronin/platform/overlay.rb
@@ -246,13 +246,16 @@ module Ronin
raise(OverlayCached,"An overlay at the path #{path.dump} was already added",caller)
end
- # create and save the Overlay
+ # create the Overlay
overlay = Overlay.new(options.merge(:path => path))
if Overlay.count(:name => overlay.name, :host => overlay.host) > 0
raise(OverlayCached,"The overlay #{overlay} already exists in the database",caller)
end
+ # save the Overlay
+ overlay.save!
+
# update the object cache
ObjectCache.cache(overlay.cache_dir)
|
Oops, forgot to save the overlay.
|
ronin-ruby_ronin
|
train
|
8b3e56944cd21cf9a01094e96df8ff80780e2fa7
|
diff --git a/chatbot/__init__.py b/chatbot/__init__.py
index <HASH>..<HASH> 100644
--- a/chatbot/__init__.py
+++ b/chatbot/__init__.py
@@ -167,7 +167,7 @@ class Chat(object):
self._normalizer_regex = self._compile_reflections(normalizer)
self.__process_learn(default_pairs)
self.__process_learn(pairs)
- self._reflections = reflections if reflections else self.substitution.reflections
+ self._reflections = reflections or self.substitution.reflections
self._regex = self._compile_reflections(self._reflections)
self._memory = mapper.SessionHandler(dict, general={})
self._conversation = mapper.SessionHandler(mapper.Conversation, general=[])
@@ -265,10 +265,12 @@ class Chat(object):
content = text[max(0, pos[index-1][0]): pos[index][1]+5].strip()
raise NameError("Invalid Tag '%s': Error in `%s` " % (pos[index][2], content))
index += 1
- return index+1, (within_block["client"],
- within_block["prev"] if within_block["prev"] else None,
- within_block["response"],
- within_block["learn"])
+ return index + 1, (
+ within_block["client"],
+ within_block["prev"] or None,
+ within_block["response"],
+ within_block["learn"],
+ )
def __group_tags(self, text, pos, groups, condition, length, index=0, name=""):
pairs = []
@@ -451,12 +453,15 @@ class Chat(object):
return ordered_group
def _inherit(self, start_end_pair, action):
- group = {}
- for i, primary in enumerate(start_end_pair):
- group[i] = []
- for j, secondary in enumerate(start_end_pair):
- if primary[0] < secondary[0] and primary[1] > secondary[1]:
- group[i].append(j)
+ group = {
+ i: [
+ j
+ for j, secondary in enumerate(start_end_pair)
+ if primary[0] < secondary[0] and primary[1] > secondary[1]
+ ]
+ for i, primary in enumerate(start_end_pair)
+ }
+
group = self._restructure(group)
group = self._sub_action(group, start_end_pair, action)
return self._set_within(group)
@@ -468,7 +473,11 @@ class Chat(object):
e_n = end_tag[1]-end_tag[0]
start_char = response[begin_tag[0]]
end_char = response[end_tag[1]-1]
- if b_n != e_n or not ((start_char == "{" and end_char == "}") or (start_char == "[" and end_char == "]")):
+ if (
+ b_n != e_n
+ or (start_char != "{" or end_char != "}")
+ and (start_char != "[" or end_char != "]")
+ ):
raise SyntaxError("invalid syntax '%s'" % response)
if b_n == 2:
statement = self._re_tags.findall(response[begin_tag[1]: end_tag[0]])
diff --git a/chatbot/spellcheck/__init__.py b/chatbot/spellcheck/__init__.py
index <HASH>..<HASH> 100644
--- a/chatbot/spellcheck/__init__.py
+++ b/chatbot/spellcheck/__init__.py
@@ -56,7 +56,7 @@ class SpellChecker:
:param words: list of str
:return: unique set of words
"""
- return set(w for w in words if w in self.WORDS)
+ return {w for w in words if w in self.WORDS}
@staticmethod
def edits1(word):
|
'Refactored by Sourcery'
|
ahmadfaizalbh_Chatbot
|
train
|
c38a146497858043742299af3c45a69b2438cf6e
|
diff --git a/app/src/scripts/utils/google.js b/app/src/scripts/utils/google.js
index <HASH>..<HASH> 100644
--- a/app/src/scripts/utils/google.js
+++ b/app/src/scripts/utils/google.js
@@ -35,6 +35,9 @@ let google = {
.then(() => {
this.getCurrentUser(callback)
})
+ .catch(err => {
+ callback(err)
+ })
} else {
setTimeout(() => {
this.refresh(callback)
|
Prevent a hang when refresh tokens fail during login.
|
OpenNeuroOrg_openneuro
|
train
|
6475c246132158c60deae166f0e2ddeaf55707df
|
diff --git a/test/config/gemfiles/common.rb b/test/config/gemfiles/common.rb
index <HASH>..<HASH> 100644
--- a/test/config/gemfiles/common.rb
+++ b/test/config/gemfiles/common.rb
@@ -1,5 +1,5 @@
def declare_gems(activerecord_version)
- source :rubygems
+ source "https://rubygems.org"
gem 'activerecord', activerecord_version
gem 'adapter_extensions', :git => 'https://github.com/activewarehouse/adapter_extensions.git'
|
Use https for rubygems here, too
|
activewarehouse_activewarehouse-etl
|
train
|
08e9ca0ac4f29d891f78f6f585eb622c1ea06264
|
diff --git a/README.markdown b/README.markdown
index <HASH>..<HASH> 100644
--- a/README.markdown
+++ b/README.markdown
@@ -29,6 +29,10 @@ Buzz provides packages for connecting to third party APIs easily.
use Buzz\Service\RightScale;
$rightscale = new RightScale\API();
- $deployment = $rightscale->getDeployment('production');
- $servers = $deployment->getServersByTemplate('application'):
- $status = $servers->runRightScript('deploy');
+ $rightscale->setAccountId(123456);
+ $rightscale->setUsername('me@example.com');
+ $rightscale->setPassword('s3cr3t');
+
+ $deployment = $rightscale->findDeploymentByNickname('production');
+ $rightScript = $rightScript->findRightScriptByName('deploy');
+ $deployment->findServersByNickname('/^application-/')->runScript($rightScript);
diff --git a/lib/Buzz/Service/RightScale/API.php b/lib/Buzz/Service/RightScale/API.php
index <HASH>..<HASH> 100644
--- a/lib/Buzz/Service/RightScale/API.php
+++ b/lib/Buzz/Service/RightScale/API.php
@@ -24,9 +24,7 @@ class API extends Service\AbstractService
/**
* Returns all deployments on the current account.
*
- * @return array An array of deployment objects
- *
- * @link http://support.rightscale.com/15-References/RightScale_API_Reference_Guide/02-Management/01-Deployments
+ * @return DeploymentCollection A collection of deployments
*/
public function getDeployments()
{
@@ -88,19 +86,98 @@ class API extends Service\AbstractService
/**
* Finds a deployment with a certain nickname.
*
- * @param string $nickname A deployment nickname
+ * @param string $nickname A nickname or regular expression
*
* @return Deployment|null The deployment, if found
*/
public function findDeploymentByNickname($nickname)
{
- foreach ($this->getDeployments() as $deployment)
+ $deployments = $this->findDeploymentsByNickname($nickname, 1);
+
+ return count($deployments) ? $deployments->getDeployment(0) : null;
+ }
+
+ /**
+ * Returns all RightScripts on the current account.
+ *
+ * @return array An array of RightScript objects
+ */
+ public function getRightScripts()
+ {
+ $request = new Message\Request('GET', '/api/acct/'.$this->getAccountId().'/right_scripts.js', static::HOST);
+ $response = new Message\Response();
+
+ $this->send($request, $response);
+
+ $rightScripts = array();
+
+ foreach (json_decode($response->getContent(), true) as $array)
{
- if ($nickname == $deployment->getNickname())
+ $rightScript = new RightScript($this->getAPI());
+ $rightScript->fromArray($array);
+
+ $rightScripts[] = $rightScript;
+ }
+
+ return $rightScripts;
+ }
+
+ /**
+ * Finds RightScripts by name.
+ *
+ * @param string $name A name or regular expression
+ *
+ * @return array An array of matching RightScripts
+ */
+ public function findRightScriptsByName($name, $limit = null)
+ {
+ $rightScripts = array();
+
+ // choose a comparision function
+ if (preg_match('/^(!)?([^a-zA-Z0-9\\\\]).+?\\2[ims]?$/', $name, $match))
+ {
+ if ('!' == $match[1])
+ {
+ $compare = function ($name, $value) { return !preg_match(substr($name, 1), $value); };
+ }
+ else
+ {
+ $compare = function ($name, $value) { return preg_match($name, $value); };
+ }
+ }
+ else
+ {
+ $compare = function ($name, $value) { return $name == $value; };
+ }
+
+ foreach ($this->getRightScripts() as $rightScript)
+ {
+ if (null !== $limit && count($rightScripts) >= $limit)
{
- return $deployment;
+ break;
+ }
+
+ if ($compare($name, $rightScript->getName()))
+ {
+ $rightScripts[] = $rightScript;
}
}
+
+ return $rightScripts;
+ }
+
+ /**
+ * Finds a RightScript with a certain name.
+ *
+ * @param string $name A name or regular expression
+ *
+ * @return RightScript|null The RightScript, if found
+ */
+ public function findRightScriptByName($name)
+ {
+ $rightScripts = $this->findRightScriptsByName($name, 1);
+
+ return count($rightScripts) ? $rightScripts[0] : null;
}
/**
diff --git a/lib/Buzz/Service/RightScale/RightScript.php b/lib/Buzz/Service/RightScale/RightScript.php
index <HASH>..<HASH> 100644
--- a/lib/Buzz/Service/RightScale/RightScript.php
+++ b/lib/Buzz/Service/RightScale/RightScript.php
@@ -4,4 +4,49 @@ namespace Buzz\Service\RightScale;
class RightScript extends AbstractResource
{
+ protected $name;
+ protected $description;
+ protected $script;
+
+ /**
+ * @see AbstractResource
+ */
+ public function fromArray(array $array)
+ {
+ $this->setName($array['name']);
+ $this->setDescription($array['description']);
+ $this->setCreatedAt(new \DateTime($array['created_at']));
+ $this->setUpdatedAt(new \DateTime($array['updated_at']));
+ $this->setScript($array['script']);
+ }
+
+ public function setName($name)
+ {
+ $this->name = $name;
+ }
+
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ public function setDescription($description)
+ {
+ $this->description = $description;
+ }
+
+ public function getDescription()
+ {
+ return $this->description;
+ }
+
+ public function setScript($script)
+ {
+ $this->script = $script;
+ }
+
+ public function getScript()
+ {
+ return $this->script;
+ }
}
|
Updated README and added some RightScript goodness.
|
kriswallsmith_Buzz
|
train
|
03241b0fad89be13e83a89403628cb186408fdd9
|
diff --git a/lib/reel/connection.rb b/lib/reel/connection.rb
index <HASH>..<HASH> 100644
--- a/lib/reel/connection.rb
+++ b/lib/reel/connection.rb
@@ -9,7 +9,8 @@ module Reel
KEEP_ALIVE = 'Keep-Alive'.freeze
CLOSE = 'close'.freeze
- attr_reader :socket, :parser
+ attr_reader :socket, :parser, :current_request
+ attr_accessor :request_state, :response_state
# Attempt to read this much data
BUFFER_SIZE = 16384
@@ -21,7 +22,6 @@ module Reel
@keepalive = true
@buffer_size = buffer_size || BUFFER_SIZE
@parser = Request::Parser.new(self)
- @writer = Response::Writer.new(socket)
reset_request
@response_state = :header
@@ -44,10 +44,6 @@ module Reel
@parser.readpartial(size)
end
- def current_request
- @current_request
- end
-
# Read a request object from the connection
def request
raise StateError, "already processing a request" if current_request
@@ -103,7 +99,7 @@ module Reel
else raise TypeError, "invalid response: #{response.inspect}"
end
- @writer.handle_response(response)
+ current_request.handle_response(response)
# Enable streaming mode
if response.chunked? and response.body.nil?
@@ -121,20 +117,6 @@ module Reel
end
end
- # Write body chunks directly to the connection
- def write(chunk)
- raise StateError, "not in chunked body mode" unless @response_state == :chunked_body
- @writer.write(chunk)
- end
- alias_method :<<, :write
-
- # Finish the response and reset the response state to header
- def finish_response
- raise StateError, "not in body state" if @response_state != :chunked_body
- @writer.finish_response
- @response_state = :header
- end
-
# Close the connection
def close
raise StateError, "socket has been hijacked from this connection" unless @socket
diff --git a/lib/reel/request.rb b/lib/reel/request.rb
index <HASH>..<HASH> 100644
--- a/lib/reel/request.rb
+++ b/lib/reel/request.rb
@@ -5,7 +5,8 @@ module Reel
extend Forwardable
include RequestMixin
- def_delegators :@connection, :<<, :write, :remote_addr, :respond, :finish_response
+ def_delegators :@connection, :remote_addr, :respond
+ def_delegator :@response_writer, :handle_response
attr_reader :body
# request_info is a RequestInfo object including the headers and
@@ -13,13 +14,14 @@ module Reel
#
# Access it through the RequestMixin methods.
def initialize(request_info, connection = nil)
- @request_info = request_info
- @connection = connection
- @finished = false
- @buffer = ""
- @body = RequestBody.new(self)
- @finished_read = false
- @websocket = nil
+ @request_info = request_info
+ @connection = connection
+ @finished = false
+ @buffer = ""
+ @body = RequestBody.new(self)
+ @finished_read = false
+ @websocket = nil
+ @response_writer = Response::Writer.new(connection.socket)
end
# Returns true if request fully finished reading
@@ -79,6 +81,23 @@ module Reel
slice && slice.length == 0 ? nil : slice
end
+ # Write body chunks directly to the connection
+ def write(chunk)
+ unless @connection.response_state == :chunked_body
+ raise StateError, "not in chunked body mode"
+ end
+
+ @response_writer.write(chunk)
+ end
+ alias_method :<<, :write
+
+ # Finish the response and reset the response state to header
+ def finish_response
+ raise StateError, "not in body state" if @connection.response_state != :chunked_body
+ @response_writer.finish_response
+ @connection.response_state = :header
+ end
+
# Can the current request be upgraded to a WebSocket?
def websocket?; @request_info.websocket_request?; end
diff --git a/spec/reel/response_writer_spec.rb b/spec/reel/response_writer_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/reel/response_writer_spec.rb
+++ b/spec/reel/response_writer_spec.rb
@@ -12,7 +12,14 @@ describe Reel::Response::Writer do
writer.handle_response(response)
end
- peer.readpartial(4096).should eq expected_response
+ buf = ""
+ begin
+ buf << peer.readpartial(4096)
+ rescue IOError
+ # End of body!
+ end
+
+ expect(buf).to eq expected_response
end
end
end
|
Remove response writing thunks into Reel::Request
The Request object should keep track of its associated response, not the
connection. This should make pipelining cleaner.
We should still factor the connection state machine into its own class.
|
celluloid_reel
|
train
|
569d2b1787be36f79475a5ea937e050a8a7386d4
|
diff --git a/core/src/test/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdateTest.java b/core/src/test/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdateTest.java
index <HASH>..<HASH> 100644
--- a/core/src/test/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdateTest.java
+++ b/core/src/test/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdateTest.java
@@ -293,5 +293,56 @@ public class OCommandExecutorSQLUpdateTest {
db.close();
}
+
+ @Test
+ public void testSingleQuoteInNamedParameter() throws Exception {
+ final ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:OCommandExecutorSQLUpdateTestSingleQuoteInNamedParameter");
+ db.create();
+
+ db.command(new OCommandSQL("CREATE class test")).execute();
+
+ final ODocument test = new ODocument("test");
+ test.field("text", "initial value");
+
+ db.save(test);
+ ODocument queried = (ODocument) db.query(new OSQLSynchQuery<Object>("SELECT FROM test")).get(0);
+ assertEquals(queried.field("text"), "initial value");
+
+ OCommandSQL command = new OCommandSQL("UPDATE test SET text = :text");
+ Map<String, Object> params = new HashMap<String,Object>();
+ params.put("text", "single \"");
+
+ db.command(command).execute(params);
+ queried.reload();
+ assertEquals(queried.field("text"), "single \"");
+
+ db.close();
+ }
+
+ @Test
+ public void testQuotedStringInNamedParameter() throws Exception {
+ final ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:OCommandExecutorSQLUpdateTestQuotedStringInNamedParameter");
+ db.create();
+
+ db.command(new OCommandSQL("CREATE class test")).execute();
+
+ final ODocument test = new ODocument("test");
+ test.field("text", "initial value");
+
+ db.save(test);
+
+ ODocument queried = (ODocument) db.query(new OSQLSynchQuery<Object>("SELECT FROM test")).get(0);
+ assertEquals(queried.field("text"), "initial value");
+
+ OCommandSQL command = new OCommandSQL("UPDATE test SET text = :text");
+ Map<String, Object> params = new HashMap<String,Object>();
+ params.put("text", "quoted \"value\" string");
+
+ db.command(command).execute(params);
+ queried.reload();
+ assertEquals(queried.field("text"), "quoted \"value\" string");
+
+ db.close();
+ }
}
|
Adds unit tests for named parameters containing strings with quotes.
|
orientechnologies_orientdb
|
train
|
ed5ffc5290ec207fd88520dd78b60733c81d1d33
|
diff --git a/pgmpy/__init__.py b/pgmpy/__init__.py
index <HASH>..<HASH> 100644
--- a/pgmpy/__init__.py
+++ b/pgmpy/__init__.py
@@ -1,7 +1,9 @@
from . import BayesianModel
from . import Exceptions
from . import Factor
+from . import readwrite
__all__ = ['BayesianModel',
'Exceptions',
- 'Factor']
+ 'Factor',
+ 'readwrite']
|
__init__.py modified to include readwrite module
|
pgmpy_pgmpy
|
train
|
8332472a4c958281096b1388fe662c8b0a89d7c1
|
diff --git a/tests/test_mission_data.py b/tests/test_mission_data.py
index <HASH>..<HASH> 100644
--- a/tests/test_mission_data.py
+++ b/tests/test_mission_data.py
@@ -2,6 +2,7 @@ import os
from planetaryimage.pds3image import PDS3Image
import json
import pytest
+import pvl
DATA_DIR = os.path.join(os.path.dirname(__file__), 'mission_data/')
@@ -18,5 +19,6 @@ def test_mission_data():
image = PDS3Image.open(image_path)
assert data[file_name]['opens'] == "True"
assert data[file_name]['label'] == image.label.items()[0][1]
- except:
+ except (pvl.decoder.ParseError, KeyError, UnicodeDecodeError,
+ ValueError):
assert data[file_name]['opens'] == "False"
|
Fixed exception so only breaks on AssertionError
|
planetarypy_planetaryimage
|
train
|
ee608a36b6c125bd7352425cae0b730188f62ae3
|
diff --git a/lib/client.js b/lib/client.js
index <HASH>..<HASH> 100644
--- a/lib/client.js
+++ b/lib/client.js
@@ -97,8 +97,9 @@ Client.prototype._invoke = function(method, arguments, location, callback) {
encoding = '',
message = '',
xml = null,
+ soapAction = this.SOAPAction ? this.SOAPAction(ns, name) : (method.soapAction || (((ns.lastIndexOf("/") != ns.length - 1) ? ns + "/" : ns) + name)),
headers = {
- SOAPAction: '"' + method.soapAction + '"',
+ SOAPAction: '"' + soapAction + '"',
'Content-Type': "text/xml; charset=utf-8"
},
options = {},
|
fallback to old soapAction code if method.soapAction is undefined
|
vpulim_node-soap
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.