hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
422ce6ebd92a1019b6e7ed26171640263fd7bf02
|
diff --git a/misc/plugin/amazon.rb b/misc/plugin/amazon.rb
index <HASH>..<HASH> 100644
--- a/misc/plugin/amazon.rb
+++ b/misc/plugin/amazon.rb
@@ -92,7 +92,7 @@ def amazon_fetch( url, limit = 10 )
case res
when Net::HTTPSuccess
res.body
- when Net::HTTPRedirection
+ when Net::HTTPRedirection, Net::HTTPFound
amazon_fetch( res['location'], limit - 1 )
when Net::HTTPForbidden, Net::HTTPServiceUnavailable
raise AmazonRedirectError.new( limit.to_s )
@@ -281,6 +281,9 @@ def amazon_get( asin, with_image = true, label = nil, pos = 'amazon' )
Dir::mkdir( cache ) unless File::directory?( cache )
begin
xml = File::read( "#{cache}/#{country}#{asin}.xml" )
+ if xml.chomp == 'true'
+ raise Errno::ENOENT
+ end
rescue Errno::ENOENT
xml = amazon_call_ecs( asin, id_type, country )
File::open( "#{cache}/#{country}#{asin}.xml", 'wb' ) {|f| f.write( xml )}
|
amazon plugin: support HTTP Found response and discard wrong stored cache
|
tdiary_tdiary-core
|
train
|
ae2c897a03109b1c33e1287faf052ccdc4a3ab87
|
diff --git a/salt/modules/tomcat.py b/salt/modules/tomcat.py
index <HASH>..<HASH> 100644
--- a/salt/modules/tomcat.py
+++ b/salt/modules/tomcat.py
@@ -429,11 +429,10 @@ def deploy_war(war, context, force='no', url='http://localhost:8080/manager', en
tfile = war
if war[0] != '/':
tfile = os.path.join( tempfile.gettempdir(), 'salt.'+os.path.basename(war) )
- try:
- cached = __salt__['cp.get_file'](war, tfile, env)
- __salt__['file.set_mode'](cached, '0644')
- except Exception:
+ cached = __salt__['cp.get_file'](war, tfile, env)
+ if not cached:
return 'FAIL - could not cache the WAR file'
+ __salt__['file.set_mode'](cached, '0644')
# Prepare options
opts = {
@@ -446,10 +445,7 @@ def deploy_war(war, context, force='no', url='http://localhost:8080/manager', en
# Deploy
deployed = _wget('deploy', opts, url, timeout=timeout)
- if deployed['res'] == False:
- res = deployed['msg']
- else:
- res = '\n'.join(deployed['msg'])
+ res = '\n'.join(deployed['msg'])
# Cleanup
if war[0] != '/':
|
error handling when executing war_deployed when the war file is missing
|
saltstack_salt
|
train
|
d70660673fc4f56b2a31d761e50fa6ed0cb38942
|
diff --git a/suds/__init__.py b/suds/__init__.py
index <HASH>..<HASH> 100644
--- a/suds/__init__.py
+++ b/suds/__init__.py
@@ -31,7 +31,7 @@ import socket
__version__ = '0.3.7'
-properties = dict(version=__version__, build="(beta) R564-20090901")
+properties = dict(version=__version__, build="(beta) R567-20091009")
#
# Exceptions
diff --git a/suds/wsdl.py b/suds/wsdl.py
index <HASH>..<HASH> 100644
--- a/suds/wsdl.py
+++ b/suds/wsdl.py
@@ -664,7 +664,9 @@ class Binding(NamedObject):
def resolve(self, definitions):
"""
- Resolve named references to other WSDL objects.
+ Resolve named references to other WSDL objects. This includes
+ cross-linking information (from) the portType (to) the I{soap}
+ protocol information on the binding for each operation.
@param definitions: A definitions object.
@type definitions: L{Definitions}
"""
|
update epydocs and bump beta release information.
|
suds-community_suds
|
train
|
a9d1c72d2a4d133f0b2976f3057c3e5b5eacdf47
|
diff --git a/library/src/main/java/com/alexvasilkov/gestures/GestureControllerForPager.java b/library/src/main/java/com/alexvasilkov/gestures/GestureControllerForPager.java
index <HASH>..<HASH> 100644
--- a/library/src/main/java/com/alexvasilkov/gestures/GestureControllerForPager.java
+++ b/library/src/main/java/com/alexvasilkov/gestures/GestureControllerForPager.java
@@ -125,6 +125,10 @@ public class GestureControllerForPager extends GestureController {
@Override
protected boolean onDown(@NonNull MotionEvent e) {
+ if (mViewPager == null) {
+ return super.onDown(e);
+ }
+
mViewPager.requestDisallowInterceptTouchEvent(true);
mIsSkipViewPager = false;
|
Fixed issue when view pager is not specified
|
alexvasilkov_GestureViews
|
train
|
dbfdce005a6e468c7d3a1ca4d03b4a7b142b8cab
|
diff --git a/classes/search/class.tx_solr_search_sortingcomponent.php b/classes/search/class.tx_solr_search_sortingcomponent.php
index <HASH>..<HASH> 100644
--- a/classes/search/class.tx_solr_search_sortingcomponent.php
+++ b/classes/search/class.tx_solr_search_sortingcomponent.php
@@ -52,6 +52,18 @@ class tx_solr_search_SortingComponent extends tx_solr_search_AbstractComponent i
if (!empty($this->searchConfiguration['query.']['sortBy'])) {
$this->query->addQueryParameter('sort', $this->searchConfiguration['query.']['sortBy']);
}
+
+ $solrGetParameters = t3lib_div::_GET('tx_solr');
+
+ if (!empty($this->searchConfiguration['sorting'])
+ && !empty($solrGetParameters['sort'])
+ && preg_match('/^[a-z0-9_]+ (asc|desc)$/i', $solrGetParameters['sort'])
+ ) {
+ $sortHelper = t3lib_div::makeInstance('tx_solr_Sorting', $this->searchConfiguration['sorting.']['options.']);
+ $sortField = $sortHelper->getSortFieldFromUrlParameter($solrGetParameters['sort']);
+
+ $this->query->setSorting($sortField);
+ }
}
/**
diff --git a/pi_results/class.tx_solr_pi_results.php b/pi_results/class.tx_solr_pi_results.php
index <HASH>..<HASH> 100644
--- a/pi_results/class.tx_solr_pi_results.php
+++ b/pi_results/class.tx_solr_pi_results.php
@@ -242,17 +242,6 @@ class tx_solr_pi_results extends tx_solr_pluginbase_CommandPluginBase {
$query->addFilter($additionalFilter);
}
- // sorting
- if ($this->conf['search.']['sorting'] != 0
- && !empty($this->piVars['sort'])
- && preg_match('/^[a-z0-9_]+ (asc|desc)$/i', $this->piVars['sort'])
- ) {
- $sortHelper = t3lib_div::makeInstance('tx_solr_Sorting', $this->conf['search.']['sorting.']['options.']);
- $sortField = $sortHelper->getSortFieldFromUrlParameter($this->piVars['sort']);
-
- $query->setSorting($sortField);
- }
-
$this->query = $query;
}
}
|
[TASK] Move sorting to a search component
Change-Id: I<I>d<I>c8c5e6b<I>fc3dfee<I>ba<I>dc8f6eaeeb7
|
TYPO3-Solr_ext-solr
|
train
|
17dd731e32d9d10ad2c486bd3354c368aebb3f48
|
diff --git a/openid/fetchers.py b/openid/fetchers.py
index <HASH>..<HASH> 100644
--- a/openid/fetchers.py
+++ b/openid/fetchers.py
@@ -198,9 +198,6 @@ class Urllib2Fetcher(HTTPFetcher):
headers.setdefault(
'User-Agent',
"%s Python-urllib/%s" % (USER_AGENT, urllib2.__version__,))
- headers.setdefault(
- 'Range',
- '0-%s' % (1024*MAX_RESPONSE_KB,))
req = urllib2.Request(url, data=body, headers=headers)
try:
@@ -324,7 +321,6 @@ class CurlHTTPFetcher(HTTPFetcher):
c.setopt(pycurl.HEADERFUNCTION, response_header_data.write)
c.setopt(pycurl.TIMEOUT, off)
c.setopt(pycurl.URL, openid.urinorm.urinorm(url))
- c.setopt(pycurl.RANGE, '0-%s'%(MAX_RESPONSE_KB*1024))
c.perform()
@@ -394,9 +390,6 @@ class HTTPLib2Fetcher(HTTPFetcher):
if headers is None:
headers = {}
- headers.setdefault(
- 'Range',
- '0-%s' % (1024*MAX_RESPONSE_KB,))
# httplib2 doesn't check to make sure that the URL's scheme is
# 'http' so we do it here.
|
[project @ Remove range headers from requests]
|
necaris_python3-openid
|
train
|
bae6a9175f8e04f223836a71083e0cb0b641faac
|
diff --git a/test/pngmin_test.js b/test/pngmin_test.js
index <HASH>..<HASH> 100644
--- a/test/pngmin_test.js
+++ b/test/pngmin_test.js
@@ -125,7 +125,7 @@ exports.pngmin = {
quality_test: function(test) {
test.expect(2);
- var actual = grunt.file.read('tmp/quality_test/pngquant-logo-qual1.png');
+ var actual = grunt.file.read('tmp/quality_test/pngquant-logo-qual2.png');
var already_optimized = grunt.file.read('tmp/pngquant-logo-fs8.png');
test.ok(actual.length < already_optimized.length, 'lower quality should result in even smaller images!');
|
Changed test to pass also on linux
|
zauni_pngmin
|
train
|
4575e0002bcaa49267ff3104c5fec332602bfb88
|
diff --git a/src/components/body/ScrollerDirective.js b/src/components/body/ScrollerDirective.js
index <HASH>..<HASH> 100644
--- a/src/components/body/ScrollerDirective.js
+++ b/src/components/body/ScrollerDirective.js
@@ -23,9 +23,14 @@ export function ScrollerDirective($timeout){
};
function update(){
+ if(lastScrollX !== ctrl.options.internal.offsetX){
+ $scope.$apply(() => {
+ ctrl.options.internal.offsetX = lastScrollX;
+ });
+ }
+
$scope.$applyAsync(() => {
ctrl.options.internal.offsetY = lastScrollY;
- ctrl.options.internal.offsetX = lastScrollX;
ctrl.updatePage();
if(ctrl.options.scrollbarV){
@@ -43,12 +48,16 @@ export function ScrollerDirective($timeout){
}
};
- $elm.parent().on('scroll', function(ev) {
+ parent.on('scroll', function(ev) {
lastScrollY = this.scrollTop;
lastScrollX = this.scrollLeft;
requestTick();
});
+ $scope.$on('$destroy', () => {
+ parent.off('scroll');
+ });
+
$scope.scrollerStyles = function(){
if(ctrl.options.scrollbarV){
return {
|
(perf): fix memory leak on scroll tear down, remove duplicate elm find, apply offsetX faster and only when needed
|
swimlane_angular-data-table
|
train
|
043a1633bb6b9b1268990a8f603865f543a98e16
|
diff --git a/go/vt/tabletserver/cache_pool.go b/go/vt/tabletserver/cache_pool.go
index <HASH>..<HASH> 100644
--- a/go/vt/tabletserver/cache_pool.go
+++ b/go/vt/tabletserver/cache_pool.go
@@ -142,10 +142,10 @@ func (cache *Cache) Recycle() {
func CacheCreator(dbconfig dbconfigs.DBConfig) CreateCacheFunc {
if dbconfig.Memcache == "" {
- relog.Info("Row cache not enabled")
+ relog.Info("rowcache not enabled")
return nil
}
- relog.Info("Row cache is enabled")
+ relog.Info("rowcache is enabled")
return func() (*memcache.Connection, error) {
return memcache.Connect(dbconfig.Memcache)
}
diff --git a/go/vt/tabletserver/schema_info.go b/go/vt/tabletserver/schema_info.go
index <HASH>..<HASH> 100644
--- a/go/vt/tabletserver/schema_info.go
+++ b/go/vt/tabletserver/schema_info.go
@@ -171,7 +171,7 @@ func (si *SchemaInfo) override(schemaOverrides []SchemaOverride) {
continue
}
}
- if si.cachePool == nil || override.Cache == nil {
+ if si.cachePool.IsClosed() || override.Cache == nil {
continue
}
switch override.Cache.Type {
|
bug fix: Use cachePool.IsClosed to check if rowcache is enabled
|
vitessio_vitess
|
train
|
205d711d40eec55ebab1f09eb921e72ff2f458a9
|
diff --git a/Siel/Acumulus/Helpers/Translator.php b/Siel/Acumulus/Helpers/Translator.php
index <HASH>..<HASH> 100644
--- a/Siel/Acumulus/Helpers/Translator.php
+++ b/Siel/Acumulus/Helpers/Translator.php
@@ -32,9 +32,7 @@ class Translator implements TranslatorInterface {
}
/**
- * Returns the current (2 character) language (code).
- *
- * @return string
+ * @inheritdoc
*/
public function getLanguage() {
return $this->language;
diff --git a/Siel/Acumulus/Helpers/TranslatorInterface.php b/Siel/Acumulus/Helpers/TranslatorInterface.php
index <HASH>..<HASH> 100644
--- a/Siel/Acumulus/Helpers/TranslatorInterface.php
+++ b/Siel/Acumulus/Helpers/TranslatorInterface.php
@@ -12,6 +12,13 @@ namespace Siel\Acumulus\Helpers;
interface TranslatorInterface {
/**
+ * Returns the current (2 character) language (code).
+ *
+ * @return string
+ */
+ public function getLanguage();
+
+ /**
* Returns the string in the current language for the given key.
*
* @param string $key
|
getLanguage now also part of the translator interface
|
SIELOnline_libAcumulus
|
train
|
f2a053a3cf018750a87e0aa2e9abeba572cdc3d4
|
diff --git a/tests/test_parser.py b/tests/test_parser.py
index <HASH>..<HASH> 100644
--- a/tests/test_parser.py
+++ b/tests/test_parser.py
@@ -13,7 +13,7 @@ from conllu.parser import (
)
-class TestParse(unittest.TestCase):
+class TestParseTokenAndMetadata(unittest.TestCase):
def test_empty(self):
with self.assertRaises(ParseException):
parse_token_and_metadata(None)
|
Clarify test name, it doesn't test parse().
|
EmilStenstrom_conllu
|
train
|
c0666e4dc8708ead5e179d8ed086473134b4166d
|
diff --git a/safe/gui/tools/test/test_osm_downloader_dialog.py b/safe/gui/tools/test/test_osm_downloader_dialog.py
index <HASH>..<HASH> 100644
--- a/safe/gui/tools/test/test_osm_downloader_dialog.py
+++ b/safe/gui/tools/test/test_osm_downloader_dialog.py
@@ -39,6 +39,7 @@ LOGGER = logging.getLogger('InaSAFE')
class OsmDownloaderDialogTest(unittest.TestCase):
"""Test Osm Downloader Dialog widget
+ .. versionchanged:: 3.2
"""
# noinspection PyPep8Naming
def setUp(self):
diff --git a/safe/utilities/gis.py b/safe/utilities/gis.py
index <HASH>..<HASH> 100644
--- a/safe/utilities/gis.py
+++ b/safe/utilities/gis.py
@@ -145,6 +145,8 @@ def viewport_geo_array(map_canvas):
def validate_geo_array(extent):
"""Validate a geographic extent.
+ .. versionadded:: 3.2
+
:param extent: A list in the form [xmin, ymin, xmax, ymax] where all
coordinates provided are in Geographic / EPSG:4326.
:type extent: list
diff --git a/safe/utilities/osm_downloader.py b/safe/utilities/osm_downloader.py
index <HASH>..<HASH> 100644
--- a/safe/utilities/osm_downloader.py
+++ b/safe/utilities/osm_downloader.py
@@ -41,6 +41,8 @@ LOGGER = logging.getLogger('InaSAFE')
def download(feature_type, output_base_path, extent, progress_dialog=None):
"""Download shapefiles from Kartoza server.
+ .. versionadded:: 3.2
+
:param feature_type: What kind of features should be downloaded.
Currently 'buildings', 'building-points' or 'roads' are supported.
:type feature_type: str
@@ -96,6 +98,8 @@ def download(feature_type, output_base_path, extent, progress_dialog=None):
def fetch_zip(url, output_path, feature_type, progress_dialog=None):
"""Download zip containing shp file and write to output_path.
+ .. versionadded:: 3.2
+
:param url: URL of the zip bundle.
:type url: str
@@ -165,6 +169,8 @@ def extract_zip(zip_path, destination_base_path):
If two files in the zip with the same extension, only one will be
copied.
+ .. versionadded:: 3.2
+
:param zip_path: The path of the .zip file
:type zip_path: str
diff --git a/safe/utilities/test/test_gis.py b/safe/utilities/test/test_gis.py
index <HASH>..<HASH> 100644
--- a/safe/utilities/test/test_gis.py
+++ b/safe/utilities/test/test_gis.py
@@ -95,7 +95,10 @@ class TestQGIS(unittest.TestCase):
self.assertFalse(is_polygon_layer(layer), message)
def test_validate_geo_array(self):
- """Test validate geographic extent method."""
+ """Test validate geographic extent method.
+
+ .. versionadded:: 3.2
+ """
# Normal case
min_longitude = 20.389938354492188
min_latitude = -34.10782492987083
diff --git a/safe/utilities/test/test_osm_downloader.py b/safe/utilities/test/test_osm_downloader.py
index <HASH>..<HASH> 100644
--- a/safe/utilities/test/test_osm_downloader.py
+++ b/safe/utilities/test/test_osm_downloader.py
@@ -39,6 +39,8 @@ LOGGER = logging.getLogger('InaSAFE')
class MockQNetworkReply(QObject):
"""A mock network reply for testing.
+ .. versionadded:: 3.2
+
:param parent:
:type parent:
"""
@@ -104,7 +106,10 @@ class MockQNetworkReply(QObject):
# noinspection PyClassHasNoInit
class FakeQNetworkAccessManager:
- """Mock network manager for testing."""
+ """Mock network manager for testing.
+
+ .. versionadded:: 3.2
+ """
# noinspection PyDocstring,PyPep8Naming,PyMethodMayBeStatic
# pylint: disable=W0613
def post(self, request_url, data=None):
@@ -173,7 +178,10 @@ def read_all(path):
class OsmDownloaderTest(unittest.TestCase):
- """Test the OSM Downloader."""
+ """Test the OSM Downloader.
+
+ .. versionadded:: 3.2
+ """
# noinspection PyPep8Naming
def setUp(self):
"""Runs before each test."""
@@ -181,7 +189,10 @@ class OsmDownloaderTest(unittest.TestCase):
self.network_manager = FakeQNetworkAccessManager()
def test_fetch_zip(self):
- """Test fetch zip method."""
+ """Test fetch zip method.
+
+ .. versionadded:: 3.2
+ """
feature = 'buildings'
url = (
'http://osm.linfiniti.com/buildings-shp?'
@@ -197,9 +208,11 @@ class OsmDownloaderTest(unittest.TestCase):
os.remove(path)
def test_extract_zip(self):
- """Test extract_zip method which will only take care of one file for
- each extensions. If many files has the same extension, only the last
- one will be copied.
+ """Test extract_zip method.
+ This function will only take care of one file for each extensions.
+ If many files has the same extension, only the last one will be copied.
+
+ .. versionadded:: 3.2
"""
base_path = tempfile.mkdtemp()
base_file_path = os.path.join(base_path, 'test')
@@ -218,7 +231,10 @@ class OsmDownloaderTest(unittest.TestCase):
shutil.rmtree(base_path)
def test_load_shapefile(self):
- """Test loading shape file to QGIS Main Window """
+ """Test loading shape file to QGIS Main Window.
+
+ .. versionadded:: 3.2
+ """
zip_file_path = test_data_path(
'control', 'files', 'test-importdlg-extractzip.zip')
output_path = tempfile.mkdtemp()
|
change docstring in the osm downloader
|
inasafe_inasafe
|
train
|
faccaf9473a2c7f544c4ca350ebab8124d194d8a
|
diff --git a/app/templates/src/main/webapp/_app.js b/app/templates/src/main/webapp/_app.js
index <HASH>..<HASH> 100644
--- a/app/templates/src/main/webapp/_app.js
+++ b/app/templates/src/main/webapp/_app.js
@@ -5,15 +5,17 @@ angular.module('<%=angularAppName%>', ['LocalStorageModule', 'tmh.dynamicLocale'
.run(function ($rootScope, $location, $http, $state, Auth, Principal) {
$rootScope.$on('$stateChangeStart', function (event, toState, toStateParams) {
+ $rootScope.toState = toState;
+ $rootScope.toStateParams = toStateParams;
+
$http.get('protected/authentication_check.gif', { ignoreErrors: true })
.error(function() {
- Auth.logout();
- $state.go('login')
+ if ($rootScope.toState.data.roles.length > 0) {
+ Auth.logout();
+ $state.go('login')
+ }
});
- $rootScope.toState = toState;
- $rootScope.toStateParams = toStateParams;
-
if (Principal.isIdentityResolved()) {
Auth.authorize();
}
diff --git a/app/templates/src/main/webapp/app/account/login/_login.controller.js b/app/templates/src/main/webapp/app/account/login/_login.controller.js
index <HASH>..<HASH> 100644
--- a/app/templates/src/main/webapp/app/account/login/_login.controller.js
+++ b/app/templates/src/main/webapp/app/account/login/_login.controller.js
@@ -17,7 +17,7 @@ angular.module('<%=angularAppName%>')
}
});
})
- .controller('LoginController', function ($scope, $location, Auth) {
+ .controller('LoginController', function ($rootScope, $scope, $state, Auth) {
$scope.user = {};
$scope.errors = {};
@@ -29,9 +29,7 @@ angular.module('<%=angularAppName%>')
rememberMe: $scope.rememberMe
}).then(function () {
$scope.authenticationError = false;
- // Logged in, redirect to home
- $location.path('/');
-
+ $rootScope.back();
}).catch(function (err) {
$scope.authenticationError = true;
});
diff --git a/app/templates/src/main/webapp/app/main/main.html b/app/templates/src/main/webapp/app/main/main.html
index <HASH>..<HASH> 100644
--- a/app/templates/src/main/webapp/app/main/main.html
+++ b/app/templates/src/main/webapp/app/main/main.html
@@ -7,7 +7,7 @@
<h1 translate="main.title">Welcome, Java Hipster!</h1>
<p class="lead" translate="main.subtitle">This is your homepage</p>
- <div ng-switch="isLoggedIn()">
+ <div ng-switch="isAuthenticated()">
<div class="alert alert-success" ng-switch-when="true"
translate="main.logged.message" translate-values="{username: '{{account.login}}'}">
You are logged in as user "Admin".
|
fix small bugs
- login is displayed even if the page is not protected.
|
jhipster_generator-jhipster
|
train
|
67ab1aecfb6e1babee249f3c41c98532c740f047
|
diff --git a/admin/index.php b/admin/index.php
index <HASH>..<HASH> 100644
--- a/admin/index.php
+++ b/admin/index.php
@@ -512,6 +512,7 @@
/// Set up the admin user
if (empty($CFG->rolesactive)) {
+ build_context_path();
create_admin_user();
}
|
admin/index: Populate the context path JIT for the new admin user
With this call to build_context_path() the admin rights of the new
user are loaded just before they are first needed.
|
moodle_moodle
|
train
|
27defc432bb2c44ee77c78e27476ed87eaa9dad3
|
diff --git a/src/main/java/org/junit/Assume.java b/src/main/java/org/junit/Assume.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/junit/Assume.java
+++ b/src/main/java/org/junit/Assume.java
@@ -16,7 +16,7 @@ import org.hamcrest.Matcher;
* For example:
* <pre>
* // only provides information if database is reachable.
- * \@Test public void calculateTotalSalary() {
+ * @Test public void calculateTotalSalary() {
* DBConnection dbc = Database.connect();
* assumeNotNull(dbc);
* // ...
|
@ displayed incorrectly in javadocs
This is how it's displayed when rendered: <URL>
|
junit-team_junit4
|
train
|
84254a0585207ae6653e4e03a50f93e517b9da8f
|
diff --git a/src/Htmlizer.js b/src/Htmlizer.js
index <HASH>..<HASH> 100755
--- a/src/Htmlizer.js
+++ b/src/Htmlizer.js
@@ -39,15 +39,7 @@
}
//HTML 4 and 5 void tags
- var voidTags = unwrap('area,base,basefont,br,col,command,embed,frame,hr,img,input,keygen,link,meta,param,source,track,wbr'),
- regexString = {
- JSVar: "[$_A-Za-z][$_A-Za-z0-9]*"
- };
- regexString.DotNotation = '(' + regexString.JSVar + '(?:\\.' + regexString.JSVar + ')*)';
-
- var regexMap = {
- DotNotation: new RegExp(regexString.DotNotation)
- };
+ var voidTags = unwrap('area,base,basefont,br,col,command,embed,frame,hr,img,input,keygen,link,meta,param,source,track,wbr');
//Valid statements.
var syntaxRegex = {
@@ -214,30 +206,34 @@
}
}
- if (binding === 'text' && regexMap.DotNotation.test(value)) {
+ if (binding === 'text') {
val = saferEval(value, context, data, node);
- if (val !== undefined) {
- node.innerHTML = ''; //KO nukes the inner content.
- node.appendChild(document.createTextNode(val));
+ node.innerHTML = ''; //KO nukes the inner content.
+ if (val === null || val === undefined) {
+ val = '';
}
+ node.appendChild(document.createTextNode(val));
}
if (binding === 'html') {
$(node).empty();
val = saferEval(value, context, data, node);
- if (val) {
- tempFrag = this.moveToNewFragment(this.parseHTML(val));
- node.appendChild(tempFrag);
+ if (val !== undefined && val !== null && val !== '') {
+ var nodes = this.parseHTML(val + '');
+ if (nodes) {
+ tempFrag = this.moveToNewFragment(nodes);
+ node.appendChild(tempFrag);
+ }
}
}
if (binding === 'attr') {
this.forEachObjectLiteral(value.slice(1, -1), function (attr, value) {
- if (regexMap.DotNotation.test(value)) {
- val = saferEval(value, context, data, node);
- if (typeof val === 'string' || typeof val === 'number') {
- node.setAttribute(attr, val);
- }
+ val = saferEval(value, context, data, node);
+ if (val || typeof val === 'string' || typeof val === 'number') {
+ node.setAttribute(attr, val);
+ } else { //undefined, null, false
+ node.removeAttribute(attr);
}
});
}
@@ -247,6 +243,8 @@
val = saferEval(expr, context, data, node);
if (val) {
$(node).addClass(className);
+ } else {
+ $(node).removeClass(className);
}
});
}
@@ -254,14 +252,19 @@
if (binding === 'style') {
this.forEachObjectLiteral(value.slice(1, -1), function (prop, value) {
val = saferEval(value, context, data, node) || null;
- node.style.setProperty(prop.replace(/[A-Z]/g, replaceJsCssPropWithCssProp), val);
+ if (val || typeof val === 'string' || typeof val === 'number') {
+ node.style.setProperty(prop.replace(/[A-Z]/g, replaceJsCssPropWithCssProp), val);
+ } else { //undefined, null, false
+ node.style.removeProperty(prop.replace(/[A-Z]/g, replaceJsCssPropWithCssProp));
+ }
});
}
//Some of the following aren't treated as attributes by Knockout, but this is here to keep compatibility with Knockout.
if (binding === 'disable' || binding === 'enable') {
- var disable = (binding === 'disable' ? value : !value);
+ val = saferEval(value, context, data, node);
+ var disable = (binding === 'disable' ? val : !val);
if (disable) {
node.setAttribute('disabled', 'disabled');
} else {
@@ -270,7 +273,8 @@
}
if (binding === 'checked') {
- if (value) {
+ val = saferEval(value, context, data, node);
+ if (val) {
node.setAttribute('checked', 'checked');
} else {
node.removeAttribute('checked');
@@ -278,12 +282,20 @@
}
if (binding === 'value') {
- node.setAttribute('value', value);
+ val = saferEval(value, context, data, node);
+ if (val === null || val === undefined) {
+ node.removeAttribute('value');
+ } else {
+ node.setAttribute('value', val);
+ }
}
if (binding === 'visible') {
- if (value) {
- node.style.removeProperty('display');
+ val = saferEval(value, context, data, node);
+ if (val) {
+ if (node.style.display === 'none') {
+ node.style.removeProperty('display');
+ }
} else {
node.style.setProperty('display', 'none');
}
|
Made several bindings behave as close as possible to KO <I>.
Also fixed some bindings like attr,css,style to remove properties when value is "falsy".
|
Munawwar_htmlizer
|
train
|
3daac74ae37db7aa3a32ad06f926b6a3a8ac7b60
|
diff --git a/spyder/plugins/editor/widgets/codeeditor.py b/spyder/plugins/editor/widgets/codeeditor.py
index <HASH>..<HASH> 100644
--- a/spyder/plugins/editor/widgets/codeeditor.py
+++ b/spyder/plugins/editor/widgets/codeeditor.py
@@ -590,8 +590,8 @@ class CodeEditor(TextEditBaseWidget):
self.show_hint_for_completion)
# re-use parent of completion_widget (usually the main window)
- compl_parent = self.completion_widget.parent()
- self.kite_call_to_action = KiteCallToAction(self, compl_parent)
+ completion_parent = self.completion_widget.parent()
+ self.kite_call_to_action = KiteCallToAction(self, completion_parent)
# --- Helper private methods
# ------------------------------------------------------------------------
|
Kite: Tiny refactoring for clarity
|
spyder-ide_spyder
|
train
|
0a945dc741613f966a67fcf4a3558f0cb1c31e29
|
diff --git a/setup_libuv.py b/setup_libuv.py
index <HASH>..<HASH> 100644
--- a/setup_libuv.py
+++ b/setup_libuv.py
@@ -93,8 +93,8 @@ def prepare_windows_env(env):
class libuv_build_ext(build_ext):
libuv_dir = os.path.join('deps', 'libuv')
libuv_repo = 'https://github.com/joyent/libuv.git'
- libuv_branch = 'master'
- libuv_revision = '06f9e14'
+ libuv_branch = 'v1.x'
+ libuv_revision = 'f70b3fa'
libuv_patches = []
user_options = build_ext.user_options
|
core: raised libuv revision and switched to v1.x branch
|
saghul_pyuv
|
train
|
70fc1040ee40faf129604557107cc59fd51c4fe2
|
diff --git a/torchtext/__init__.py b/torchtext/__init__.py
index <HASH>..<HASH> 100644
--- a/torchtext/__init__.py
+++ b/torchtext/__init__.py
@@ -4,7 +4,7 @@ import os
from torchtext import _extension # noqa: F401
_TEXT_BUCKET = "https://download.pytorch.org/models/text/"
-_CACHE_DIR = os.path.expanduser("~/.torchtext/cache")
+_CACHE_DIR = os.path.expanduser("~/.cache/torch/text")
from . import data, datasets, experimental, functional, models, nn, transforms, utils, vocab
diff --git a/torchtext/data/datasets_utils.py b/torchtext/data/datasets_utils.py
index <HASH>..<HASH> 100644
--- a/torchtext/data/datasets_utils.py
+++ b/torchtext/data/datasets_utils.py
@@ -187,7 +187,7 @@ def _create_dataset_directory(dataset_name):
@functools.wraps(fn)
def wrapper(root=_CACHE_DIR, *args, **kwargs):
- new_root = os.path.join(root, dataset_name)
+ new_root = os.path.join(root, "datasets", dataset_name)
if not os.path.exists(new_root):
os.makedirs(new_root, exist_ok=True)
return fn(root=new_root, *args, **kwargs)
|
Change root directory for datasets (#<I>)
|
pytorch_text
|
train
|
ac0fec1ad1fb05365eb695ccb08a6d76fab330b7
|
diff --git a/lib/rnes/cpu.rb b/lib/rnes/cpu.rb
index <HASH>..<HASH> 100644
--- a/lib/rnes/cpu.rb
+++ b/lib/rnes/cpu.rb
@@ -1003,9 +1003,14 @@ module Rnes
end
# @return [Integer]
+ # @raise [Rnes::Errors::StackPointerOverflowError]
def pop
- @registers.stack_pointer += 1
- read(@registers.stack_pointer & 0xFF | 0x100)
+ if @registers.stack_pointer < 0x1FF
+ @registers.stack_pointer += 1
+ read(@registers.stack_pointer)
+ else
+ raise ::Rnes::Errors::StackPointerOverflowError
+ end
end
# @return [Integer]
@@ -1014,9 +1019,14 @@ module Rnes
end
# @param [Integer] value
+ # @raise [Rnes::Errors::StackPointerOverflowError]
def push(value)
- write(@registers.stack_pointer | 0x100, value)
- @registers.stack_pointer -= 1
+ if @registers.stack_pointer > 0x100
+ write(@registers.stack_pointer, value)
+ @registers.stack_pointer -= 1
+ else
+ raise ::Rnes::Errors::StackPointerOverflowError
+ end
end
# @param [Integer] value
diff --git a/lib/rnes/errors.rb b/lib/rnes/errors.rb
index <HASH>..<HASH> 100644
--- a/lib/rnes/errors.rb
+++ b/lib/rnes/errors.rb
@@ -39,5 +39,8 @@ module Rnes
class ProgramRomNotConnectedError < BaseError
end
+
+ class StackPointerOverflowError < BaseError
+ end
end
end
|
Raise error on stack pointer overflow
|
r7kamura_rnes
|
train
|
2cccc6f73e1817d82ec06a89d9e525187c34af4e
|
diff --git a/erizo_controller/erizoClient/src/Stream.js b/erizo_controller/erizoClient/src/Stream.js
index <HASH>..<HASH> 100644
--- a/erizo_controller/erizoClient/src/Stream.js
+++ b/erizo_controller/erizoClient/src/Stream.js
@@ -84,6 +84,14 @@ const Stream = (altConnectionHelpers, specInput) => {
const translated = (maxVideoBW * 1000 * 0.90) - (50 * 40 * 8);
log.info(`message: Setting maxVideoBW, streamId: ${that.getID()}, maxVideoBW: ${maxVideoBW}, translated: ${translated}`);
that.maxVideoBW = translated;
+ // Make sure all the current parameters respect the new limit
+ if (videoSenderLicodeParameters) {
+ Object.keys(videoSenderLicodeParameters).forEach((key) => {
+ const senderParam = videoSenderLicodeParameters[key];
+ senderParam.maxBitrate = senderParam.maxBitrate > that.maxVideoBW ?
+ that.maxVideoBW : senderParam.maxBitrate;
+ });
+ }
} else {
that.maxVideoBW = maxVideoBW;
}
@@ -617,7 +625,7 @@ const Stream = (altConnectionHelpers, specInput) => {
that.updateSimulcastLayersBitrate = (bitrates) => {
if (that.pc && that.local) {
// limit with maxVideoBW
- const limitedBitrates = bitrates;
+ const limitedBitrates = Object.assign({}, bitrates);
Object.keys(limitedBitrates).forEach((key) => {
// explicitly passing undefined means assigning the max for that layer
if (limitedBitrates[key] > that.maxVideoBW || limitedBitrates[key] === undefined) {
@@ -625,8 +633,6 @@ const Stream = (altConnectionHelpers, specInput) => {
`, layer :${key}, requested: ${limitedBitrates[key]}, max: ${that.maxVideoBW}`);
limitedBitrates[key] = that.maxVideoBW;
}
- limitedBitrates[key] =
- limitedBitrates[key] > that.maxVideoBW ? that.maxVideoBW : limitedBitrates[key];
});
setEncodingConfig('maxBitrate', limitedBitrates);
that.applySenderEncoderParameters();
|
Fix issues with setMaxVideoBW and updateSimulcastLayersBitrate (#<I>)
|
lynckia_licode
|
train
|
9fb136bb042e318f73191c466923fc22402f99b6
|
diff --git a/src/main/java/smartrics/ant/git/GitTasksContainer.java b/src/main/java/smartrics/ant/git/GitTasksContainer.java
index <HASH>..<HASH> 100644
--- a/src/main/java/smartrics/ant/git/GitTasksContainer.java
+++ b/src/main/java/smartrics/ant/git/GitTasksContainer.java
@@ -1,9 +1,10 @@
package smartrics.ant.git;
import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
+import java.util.LinkedList;
+
+import java.util.Queue;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
@@ -12,7 +13,7 @@ public class GitTasksContainer extends Task {
private boolean verbose = false;
private File localDirectory;
- private List<GitTask> tasks = new ArrayList<GitTask>();
+ private Queue<GitTask> tasks = new LinkedList<GitTask>();
public void setVerbose(boolean v) {
this.verbose = v;
@@ -24,37 +25,37 @@ public class GitTasksContainer extends Task {
public CloneTask createClone() {
CloneTask c = new CloneTask();
- tasks.add(c);
+ tasks.offer(c);
return c;
}
public CommitTask createCommit() {
CommitTask c = new CommitTask();
- tasks.add(c);
+ tasks.offer(c);
return c;
}
public UpToDateTask createUpToDate() {
UpToDateTask c = new UpToDateTask();
- tasks.add(c);
+ tasks.offer(c);
return c;
}
public PushTask createPush() {
PushTask c = new PushTask();
- tasks.add(c);
+ tasks.offer(c);
return c;
}
public TagTask createTag() {
TagTask c = new TagTask();
- tasks.add(c);
+ tasks.offer(c);
return c;
}
public PullTask createPull() {
PullTask p = new PullTask();
- tasks.add(p);
+ tasks.offer(p);
return p;
}
@@ -63,14 +64,16 @@ public class GitTasksContainer extends Task {
if (localDirectory == null) {
throw new BuildException("Please specify local repository directory");
}
- int size = tasks.size();
- while(size>0) {
- GitTask t = tasks.remove(0);
- size = tasks.size();
+
+ while(!tasks.isEmpty()) {
+ GitTask t = tasks.poll();
+
if (verbose) {
t.setProgressMonitor(new SimpleProgressMonitor(t));
}
+
t.setDirectory(localDirectory);
+
try {
t.execute();
} catch (Exception e) {
|
Using a queue instead of an array list for the task container
|
rimerosolutions_ant-git-tasks
|
train
|
4af160ecbf6f17458d7feee49792a44fe985cbcc
|
diff --git a/src/internal/fragments/utils/Evaluator.js b/src/internal/fragments/utils/Evaluator.js
index <HASH>..<HASH> 100644
--- a/src/internal/fragments/utils/Evaluator.js
+++ b/src/internal/fragments/utils/Evaluator.js
@@ -133,8 +133,8 @@
update: function () {
var value = this.root.get( this.keypath );
- if ( typeof value === 'function' ) {
- value = value._wrapped || wrapFunction( value, this.root );
+ if ( typeof value === 'function' && !value._nowrap ) {
+ value = value[ '_' + this.root._guid ] || wrapFunction( value, this.root );
}
if ( !isEqual( value, this.value ) ) {
@@ -179,11 +179,14 @@
// if the function doesn't refer to `this`, we don't need
// to set the context
if ( !thisPattern.test( fn.toString() ) ) {
- return fn._wrapped = fn;
+ defineProperty( fn, '_nowrap', { // no point doing this every time
+ value: true
+ });
+ return fn;
}
// otherwise, we do
- defineProperty( fn, '_wrapped', {
+ defineProperty( fn, '_' + ractive._guid, {
value: function () {
return fn.apply( ractive, arguments );
},
@@ -192,11 +195,11 @@
for ( prop in fn ) {
if ( hasOwn.call( fn, prop ) ) {
- fn._wrapped[ prop ] = fn[ prop ];
+ fn[ '_' + ractive._guid ][ prop ] = fn[ prop ];
}
}
- return fn._wrapped;
+ return fn[ '_' + ractive._guid ];
};
}({}));
\ No newline at end of file
|
allow expression functions to be used in multiple instances of the same subclass with the correct context
|
ractivejs_ractive
|
train
|
c71d1ad066f494fdcb17755fd95171dde26632c9
|
diff --git a/mpop/instruments/seviri.py b/mpop/instruments/seviri.py
index <HASH>..<HASH> 100644
--- a/mpop/instruments/seviri.py
+++ b/mpop/instruments/seviri.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
-# Copyright (c) 2010, 2011.
+# Copyright (c) 2010, 2011, 2013.
# Author(s):
@@ -104,6 +104,35 @@ class SeviriCompositer(VisirCompositer):
co2corr_chan.prerequisites = set([3.75, 10.8, 13.4])
+
+ def convection_co2(self):
+ """Make a Severe Convection RGB image composite on SEVIRI compensating
+ for the CO2 absorption in the 3.9 micron channel.
+ """
+ self.co2corr_chan()
+ self.check_channels("_IR39Corr", 0.635, 1.63, 6.7, 7.3, 10.8)
+
+ ch1 = self[6.7].data - self[7.3].data
+ ch2 = self["_IR39Corr"].data - self[10.8].data
+ ch3 = self[1.63].check_range() - self[0.635].check_range()
+
+ img = geo_image.GeoImage((ch1, ch2, ch3),
+ self.area,
+ self.time_slot,
+ fill_value=(0, 0, 0),
+ mode="RGB",
+ crange=((-30, 0),
+ (0, 55),
+ (-70, 20)))
+
+ img.enhance(gamma = (1.0, 0.5, 1.0))
+
+ return img
+
+ convection_co2.prerequisites = (co2corr_chan.prerequisites |
+ set([0.635, 1.63, 6.7, 7.3, 10.8]))
+
+
def cloudtop(self):
"""Make a Cloudtop RGB image composite from Seviri channels.
"""
diff --git a/mpop/satin/mipp_xrit.py b/mpop/satin/mipp_xrit.py
index <HASH>..<HASH> 100644
--- a/mpop/satin/mipp_xrit.py
+++ b/mpop/satin/mipp_xrit.py
@@ -89,7 +89,7 @@ def load_generic(satscene, options, calibrate=True, area_extent=None):
LOG.debug("Channels to load from %s: %s"%(satscene.instrument_name,
satscene.channels_to_load))
- # Compulsory global attribudes
+ # Compulsory global attributes
satscene.info["title"] = (satscene.satname.capitalize() + satscene.number +
" satellite, " +
satscene.instrument_name.capitalize() +
|
Adding a new convection RGB with co2 correction for SEVIRI
|
pytroll_satpy
|
train
|
bbc33383d4011f8e8ab5498547bfebe57649103d
|
diff --git a/cycy/compiler.py b/cycy/compiler.py
index <HASH>..<HASH> 100644
--- a/cycy/compiler.py
+++ b/cycy/compiler.py
@@ -74,8 +74,10 @@ class __extend__(ast.Block):
class __extend__(ast.BinaryOperation):
def compile(self, context):
- self.left.compile(context=context)
+ # compile RHS then LHS so that their results end up on the stack
+ # in reverse order; then we can pop in order in the interpreter
self.right.compile(context=context)
+ self.left.compile(context=context)
context.emit(bytecode.BINARY_OPERATION_BYTECODE[self.operator])
class __extend__(ast.Int32):
diff --git a/cycy/tests/test_interpreter.py b/cycy/tests/test_interpreter.py
index <HASH>..<HASH> 100644
--- a/cycy/tests/test_interpreter.py
+++ b/cycy/tests/test_interpreter.py
@@ -4,11 +4,13 @@ import os
from mock import patch
from cycy import interpreter
-from cycy.objects import W_Bool, W_Char, W_Function, W_Int32, W_String
from cycy.bytecode import *
+from cycy.compiler import compile
+from cycy.objects import W_Bool, W_Char, W_Function, W_Int32, W_String
+from cycy.parser import parse
-class TestInterpreter(TestCase):
+class TestInterpreterWithBytecode(TestCase):
def test_it_handles_opcodes_with_args(self):
byte_code = Bytecode(
instructions=[
@@ -306,3 +308,27 @@ class TestInterpreter(TestCase):
rv = interpreter.CyCy().run(byte_code)
self.assertEqual(rv, W_Int32(1))
+
+class TestInterperterWithC(TestCase):
+
+ def get_bytecode(self, source, func_name="main"):
+ program = parse(source)
+ return compile(next(f for f in program.functions() if f.name == func_name))
+
+ def test_binary_leq(self):
+ byte_code_lt = self.get_bytecode("int main(void) { return 1 <= 2; }")
+ rv = interpreter.CyCy().run(byte_code_lt)
+ self.assertEqual(rv, W_Bool(True))
+
+ byte_code_leq = self.get_bytecode("int main(void) { return 1 <= 1; }")
+ rv = interpreter.CyCy().run(byte_code_leq)
+ self.assertEqual(rv, W_Bool(True))
+
+ byte_code_gt = self.get_bytecode("int main(void) { return 2 <= 1; }")
+ rv = interpreter.CyCy().run(byte_code_gt)
+ self.assertEqual(rv, W_Bool(False))
+
+ def test_binary_sub(self):
+ byte_code_lt = self.get_bytecode("int main(void) { return 7 - 3; }")
+ rv = interpreter.CyCy().run(byte_code_lt)
+ self.assertEqual(rv, W_Int32(4))
|
fix subtraction
(seriously @tompko???)
|
Magnetic_cycy
|
train
|
4f274c847b67f3eb0ce134ac2c7bc5b6bdc59a8e
|
diff --git a/notif.go b/notif.go
index <HASH>..<HASH> 100644
--- a/notif.go
+++ b/notif.go
@@ -1,6 +1,8 @@
package dht
import (
+ ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
+
inet "github.com/jbenet/go-ipfs/p2p/net"
)
@@ -31,3 +33,5 @@ func (nn *netNotifiee) Disconnected(n inet.Network, v inet.Conn) {
func (nn *netNotifiee) OpenedStream(n inet.Network, v inet.Stream) {}
func (nn *netNotifiee) ClosedStream(n inet.Network, v inet.Stream) {}
+func (nn *netNotifiee) Listen(n inet.Network, a ma.Multiaddr) {}
+func (nn *netNotifiee) ListenClose(n inet.Network, a ma.Multiaddr) {}
|
p2p/net: notify on listens
Network now signals when it successfully listens on some address
or when an address shuts down. This will be used to establish and
close nat port mappings. It could also be used to notify peers
of address changes.
|
libp2p_go-libp2p-kad-dht
|
train
|
80cf31dd48d872200e22199d04862fd95a5c6ca1
|
diff --git a/openprocurement_client/tests/tests.py b/openprocurement_client/tests/tests.py
index <HASH>..<HASH> 100644
--- a/openprocurement_client/tests/tests.py
+++ b/openprocurement_client/tests/tests.py
@@ -379,6 +379,7 @@ class UserTestCase(unittest.TestCase):
setup_routing(self.app, routs=['tender_patch_credentials'])
tender = self.client.patch_credentials(self.tender.data.id, self.tender.access['token'])
self.assertTrue(tender['access']['token'])
+ self.assertTrue(tender['data'])
###########################################################################
# DOCUMENTS FILE TEST
|
check 'data' key in response
|
openprocurement_openprocurement.client.python
|
train
|
2accdb215de61966abb5e9b154eacbc0d35908d5
|
diff --git a/lib/plangrade/resources/notice.rb b/lib/plangrade/resources/notice.rb
index <HASH>..<HASH> 100644
--- a/lib/plangrade/resources/notice.rb
+++ b/lib/plangrade/resources/notice.rb
@@ -2,7 +2,7 @@ module Plangrade
module Resources
class Notice < Plangrade::Resources::Base
- attr_accessor_deffered :name
+ attr_accessor_deffered :name, :plan_name, :link, :create_at
def self.all(company_id)
result = api_handler.all_notices(company_id)
|
forgot to include other calls in attr_accessor_deferred
|
plangrade_plangrade-ruby
|
train
|
a8894e5cb818246ed78ed15f862406c750977f16
|
diff --git a/websockets/src/main/java/io/undertow/websockets/protocol/AbstractFrameSinkChannel.java b/websockets/src/main/java/io/undertow/websockets/protocol/AbstractFrameSinkChannel.java
index <HASH>..<HASH> 100644
--- a/websockets/src/main/java/io/undertow/websockets/protocol/AbstractFrameSinkChannel.java
+++ b/websockets/src/main/java/io/undertow/websockets/protocol/AbstractFrameSinkChannel.java
@@ -153,12 +153,16 @@ public abstract class AbstractFrameSinkChannel extends StreamSinkFrameChannel {
protected boolean flush0() throws IOException {
if (writeFrameStart()) {
if (getState() == ChannelState.SHUTDOWN) {
+
//we know end has not been written yet, or the state would be CLOSED
if (end == null) {
end = createFrameEnd();
+ end.flip();
}
+
while (end.hasRemaining()) {
int b = channel.write(end);
+
if (b == -1) {
throw WebSocketMessages.MESSAGES.channelClosed();
} else if (b == 0) {
|
Need to flip the end buffer before try to write it
|
undertow-io_undertow
|
train
|
f9fe70b39dc207606c5388ace7a1eef4af0a8eb6
|
diff --git a/src/registry/node-catalog.js b/src/registry/node-catalog.js
index <HASH>..<HASH> 100644
--- a/src/registry/node-catalog.js
+++ b/src/registry/node-catalog.js
@@ -194,7 +194,10 @@ class NodeCatalog {
this.registry.updateMetrics();
- this.logger.warn(`Node '${node.id}' disconnected${isUnexpected ? " unexpectedly" : ""}.`);
+ if (isUnexpected)
+ this.logger.warn(`Node '${node.id}' disconnected unexpectedly.`);
+ else
+ this.logger.info(`Node '${node.id}' disconnected.`);
if (this.broker.transit)
this.broker.transit.removePendingRequestByNodeID(nodeID);
diff --git a/test/unit/registry/node-catalog.spec.js b/test/unit/registry/node-catalog.spec.js
index <HASH>..<HASH> 100644
--- a/test/unit/registry/node-catalog.spec.js
+++ b/test/unit/registry/node-catalog.spec.js
@@ -191,6 +191,10 @@ describe("Test NodeCatalog.processNodeInfo", () => {
describe("Test NodeCatalog.disconnected", () => {
const broker = new ServiceBroker({ logger: false, transporter: "Fake" });
const catalog = new NodeCatalog(broker.registry, broker);
+ catalog.logger = {
+ info: jest.fn(),
+ warn: jest.fn(),
+ };
broker.registry.unregisterServicesByNode = jest.fn();
broker.broadcastLocal = jest.fn();
broker.transit.removePendingRequestByNodeID = jest.fn();
@@ -206,6 +210,11 @@ describe("Test NodeCatalog.disconnected", () => {
const node = catalog.get("node-11");
node.disconnected = jest.fn();
+ beforeEach(() => {
+ catalog.logger.info.mockClear();
+ catalog.logger.warn.mockClear();
+ });
+
it("should call disconnected & unregister services", () => {
broker.broadcastLocal.mockClear();
broker.registry.unregisterServicesByNode.mockClear();
@@ -229,6 +238,10 @@ describe("Test NodeCatalog.disconnected", () => {
expect(broker.registry.unregisterServicesByNode).toHaveBeenCalledTimes(1);
expect(broker.registry.unregisterServicesByNode).toHaveBeenCalledWith(node.id);
+
+ expect(catalog.logger.info).toHaveBeenCalledTimes(1);
+ expect(catalog.logger.info).toHaveBeenCalledWith("Node 'node-11' disconnected.");
+ expect(catalog.logger.warn).toHaveBeenCalledTimes(0);
});
it("should call disconnected & unregister services (unexpected)", () => {
@@ -253,6 +266,10 @@ describe("Test NodeCatalog.disconnected", () => {
expect(broker.registry.unregisterServicesByNode).toHaveBeenCalledTimes(1);
expect(broker.registry.unregisterServicesByNode).toHaveBeenCalledWith(node.id);
+
+ expect(catalog.logger.info).toHaveBeenCalledTimes(0);
+ expect(catalog.logger.warn).toHaveBeenCalledTimes(1);
+ expect(catalog.logger.warn).toHaveBeenCalledWith("Node 'node-11' disconnected unexpectedly.");
});
});
|
Raising an info log event instead of warning on node expected disconnection
|
moleculerjs_moleculer
|
train
|
0102b9e178dfbd914edcc3fc8505400982747af7
|
diff --git a/bin/starscope.rb b/bin/starscope.rb
index <HASH>..<HASH> 100755
--- a/bin/starscope.rb
+++ b/bin/starscope.rb
@@ -53,6 +53,12 @@ END
end.parse!
+def print_summary(db)
+ db.summary.each do |name, count|
+ printf("%-8s %5d keys\n", name, count)
+ end
+end
+
# Load the database
db = StarScope::DB.new
new = true
@@ -88,7 +94,7 @@ if options[:query]
end
if options[:summary]
- db.print_summary
+ print_summary(db)
end
if options[:dump]
@@ -115,7 +121,7 @@ END
input = gets.chomp
case input
when "!summary"
- db.print_summary
+ print_summary(db)
when "!update"
db.update
if options[:auto] || options[:write]
diff --git a/lib/starscope/db.rb b/lib/starscope/db.rb
index <HASH>..<HASH> 100644
--- a/lib/starscope/db.rb
+++ b/lib/starscope/db.rb
@@ -69,10 +69,14 @@ class StarScope::DB
@tables.keys.each {|tbl| dump_table(tbl)}
end
- def print_summary
- @tables.each do |name, tbl|
- puts "#{name} - #{tbl.keys.count} entries"
+ def summary
+ ret = {}
+
+ @tables.each_key do |key|
+ ret[key] = @tables[key].keys.count
end
+
+ ret
end
def query(table, value)
|
More eliminating puts from the DB api
|
eapache_starscope
|
train
|
af856cfd43c12f077cede081c7252bb112870b61
|
diff --git a/lib/phantomjs/core.js b/lib/phantomjs/core.js
index <HASH>..<HASH> 100644
--- a/lib/phantomjs/core.js
+++ b/lib/phantomjs/core.js
@@ -125,27 +125,40 @@ function phantomExit (code) {
}
function extractFullCssFromPage (doneStatus, originalCss) {
- originalCss = decodeURIComponent(originalCss)
- var css = Array.prototype.map.call(document.styleSheets, function (stylesheet) {
- return Array.prototype.map.call(stylesheet.cssRules || [], function (rule) {
- if (!rule.selectorText) {
- // TODO: if this is a media query, we would still need to fix lower case selectors, as below..
+ var getOriginalSelectorCase = function (selector) {
+ var sanitizedSelector = selector.replace(/[#-.]|[[-^]|[?|{}]/g, '\\$&')
+ var pattern = new RegExp('(' + sanitizedSelector + ')[ ,{]?', 'i') // }
+ var match = originalCss.match(pattern)
+ if (match && match[1]) {
+ return match[1]
+ }
+ return selector
+ }
+ // can't just return rule.cssText here, because these selectors are forced lowercase (in Chrome),
+ // but querySelectorAll is case sensitive (for selectors containing certain reserved words, such as float)
+ // therefor need to go back to original styles and grab original (case) name for each selector..
+ var handleRuleSelectorCase = function (cssStyleRule) {
+ var selectors = cssStyleRule.selectorText.split(',').map(getOriginalSelectorCase).join(',')
+ return selectors + '{' + cssStyleRule.style.cssText + '}'
+ }
+
+ var handleCssRule = function (rule) {
+ if (!rule.selectorText) {
+ if (!rule.media) {
return rule.cssText
}
- // can't just return rule.cssText here, because these selectors are forced lowercase (in Chrome),
- // but querySelectorAll is case sensitive (for selectors containing certain reserved words, such as float)
- // therefor need to go back to original styles and grab original (case) name for each selector..
- var selectors = rule.selectorText.split(',').map(function (selector) {
- var sanitizedSelector = selector.replace(/[#-.]|[[-^]|[?|{}]/g, '\\$&')
- var pattern = new RegExp('(' + sanitizedSelector + ')[ ,{]?', 'i')
- var match = originalCss.match(pattern)
- if (match && match[1]) {
- return match[1]
- }
- return selector
- }).join(',')
- return selectors + '{' + rule.style.cssText + '}'
- }).join(' ')
+ var mediaContent = handleCssRules(rule.cssRules)
+ return '@media ' + rule.media.mediaText + '{' + mediaContent + '}'
+ }
+ return handleRuleSelectorCase(rule)
+ }
+ var handleCssRules = function (cssRulesList) {
+ return Array.prototype.map.call(cssRulesList || [], handleCssRule).join(' ')
+ }
+
+ originalCss = decodeURIComponent(originalCss)
+ var css = Array.prototype.map.call(document.styleSheets, function (stylesheet) {
+ return handleCssRules(stylesheet.cssRules)
}).join(' ')
// these (case 0) @-rules are not part of document.styleSheets, so need to be preserved manually
|
handle case for media rules when normalising css
|
pocketjoso_penthouse
|
train
|
b1b0aac6430020e80a809de7d62197dc0e22053f
|
diff --git a/kvdb/etcd/db.go b/kvdb/etcd/db.go
index <HASH>..<HASH> 100644
--- a/kvdb/etcd/db.go
+++ b/kvdb/etcd/db.go
@@ -132,7 +132,7 @@ type db struct {
var _ walletdb.DB = (*db)(nil)
// newEtcdBackend returns a db object initialized with the passed backend
-// config. If etcd connection cannot be estabished, then returns error.
+// config. If etcd connection cannot be established, then returns error.
func newEtcdBackend(ctx context.Context, cfg Config) (*db, error) {
clientCfg := clientv3.Config{
Context: ctx,
@@ -182,7 +182,7 @@ func newEtcdBackend(ctx context.Context, cfg Config) (*db, error) {
return backend, nil
}
-// getSTMOptions creats all STM options based on the backend config.
+// getSTMOptions creates all STM options based on the backend config.
func (db *db) getSTMOptions() []STMOptionFunc {
opts := []STMOptionFunc{
WithAbortContext(db.ctx),
diff --git a/lncfg/db.go b/lncfg/db.go
index <HASH>..<HASH> 100644
--- a/lncfg/db.go
+++ b/lncfg/db.go
@@ -27,7 +27,7 @@ type DB struct {
Bolt *kvdb.BoltConfig `group:"bolt" namespace:"bolt" description:"Bolt settings."`
}
-// NewDB creates and returns a new default DB config.
+// DefaultDB creates and returns a new default DB config.
func DefaultDB() *DB {
return &DB{
Backend: BoltBackend,
|
kvdb+lncfg: fix some typos in comments
|
lightningnetwork_lnd
|
train
|
6fad4d6b46f4066076a18446d8ccd16b9bc3b48d
|
diff --git a/vote.js b/vote.js
index <HASH>..<HASH> 100644
--- a/vote.js
+++ b/vote.js
@@ -14,6 +14,19 @@ exports.create = function (api) {
return { message: {
action: function (msg, context) {
var expression = 'yup'
+ function setState () {
+ var c = 0
+ pull(
+ api.sbot.links({dest: msg.key, rel: 'vote'}),
+ pull.drain(function (e) {
+ api.sbot.names.getSignifier(e.source, function (err, name) {
+ if(name) y.title += name + '\n'
+ })
+ c ++
+ y.textContent = c+' '+expression
+ })
+ )
+ }
var y = h('a', expression, { href:"#", onclick: function (ev) {
api.confirm.show({
type: 'vote', vote: {
@@ -21,19 +34,9 @@ exports.create = function (api) {
},
channel: msg.value.content.channel,
recps: msg.value.content.recps
- }, null, function () {})
+ }, null, setState)
}})
- var c = 0
- pull(
- api.sbot.links({dest: msg.key, rel: 'vote'}),
- pull.drain(function (e) {
- api.sbot.names.getSignifier(e.source, function (err, name) {
- if(name) y.title += name + '\n'
- })
- c ++
- y.textContent = c+' '+expression
- })
- )
+ setState()
return y
},
render: function (msg) {
@@ -45,5 +48,3 @@ exports.create = function (api) {
}}
}
-
-
|
use query, render, requery pattern
|
patchless_patchapp-vote
|
train
|
28ffc68606b3795aaf128354b77d3cb70e5c6566
|
diff --git a/news-bundle/src/Resources/contao/config/config.php b/news-bundle/src/Resources/contao/config/config.php
index <HASH>..<HASH> 100644
--- a/news-bundle/src/Resources/contao/config/config.php
+++ b/news-bundle/src/Resources/contao/config/config.php
@@ -18,7 +18,9 @@ array_insert($GLOBALS['BE_MOD']['content'], 1, array
(
'news' => array
(
- 'tables' => array('tl_news_archive', 'tl_news', 'tl_news_feed', 'tl_content')
+ 'tables' => array('tl_news_archive', 'tl_news', 'tl_news_feed', 'tl_content'),
+ 'table' => array('TableWizard', 'importTable'),
+ 'list' => array('ListWizard', 'importList')
)
));
|
[News] Register the CSV import in the news and calendar modules (see #<I>)
|
contao_contao
|
train
|
504dbcba2d12db8c6451364e0b28473ce1e39281
|
diff --git a/lib/heroku/jsplugin.rb b/lib/heroku/jsplugin.rb
index <HASH>..<HASH> 100644
--- a/lib/heroku/jsplugin.rb
+++ b/lib/heroku/jsplugin.rb
@@ -145,7 +145,7 @@ class Heroku::JSPlugin
File.delete bin
raise 'SHA mismatch for heroku-cli'
end
- $stderr.puts " done\nFor more information on Toolbelt v4: https://github.com/heroku/heroku-cli"
+ $stderr.puts " done"
version
end
|
take out install message about v4
it has been out long enough to serve its purpose
Fixes <URL>
|
heroku_legacy-cli
|
train
|
40cb4e344884578cabdfa237d56beb93ff0cc40f
|
diff --git a/src/Building/Builder.php b/src/Building/Builder.php
index <HASH>..<HASH> 100644
--- a/src/Building/Builder.php
+++ b/src/Building/Builder.php
@@ -62,6 +62,7 @@ class Builder
public function build($name, array $args = array())
{
$process = $this->processes[$name];
+ $this->context()->name = $name;
array_unshift($args, $this->context());
if ($context = call_user_func_array(array($process, 'build'), $args)) {
diff --git a/tests/Building/BuilderTest.php b/tests/Building/BuilderTest.php
index <HASH>..<HASH> 100644
--- a/tests/Building/BuilderTest.php
+++ b/tests/Building/BuilderTest.php
@@ -92,6 +92,7 @@ class BuilderTest extends \PHPUnit_Framework_TestCase
$b->build('foo', array('hey', 'man'));
$this->assertAttributeSame(array($startContext), 'stack', $b);
+ $this->assertEquals('foo', $startContext->name);
$b->build('bar');
$this->assertAttributeSame(array($startContext, $secondCContext), 'stack', $b);
|
Set context name in Builder::build
|
nicmart_Building
|
train
|
cc2af38a9b93ac7cde99840050912dd60e2a8873
|
diff --git a/framework/Parsers/PathParser.php b/framework/Parsers/PathParser.php
index <HASH>..<HASH> 100644
--- a/framework/Parsers/PathParser.php
+++ b/framework/Parsers/PathParser.php
@@ -163,8 +163,12 @@ REGEX;
$replacement = '(\w+)';
break;
default :
+ $regex = ($params[2][$key] ?: $params[1][$key]);
+ // Undo replacements made in parse foreach loop (see line 67)
+ $regex = str_replace([')*?', ')?'], ['*]', ']'], $regex);
+
// Check if a regex was set for this match, otherwise use a wildcard all
- $replacement = '(' . ($params[2][$key] ?: $params[1][$key]) . ')';
+ $replacement = '(' . $regex . ')';
break;
}
|
Updating path parser to allow for brackets within regex part of segments.
|
valkyrjaio_valkyrja
|
train
|
fcb8e39ec7a12e7b8af3b69247df88f3b6054f67
|
diff --git a/test/simple.rb b/test/simple.rb
index <HASH>..<HASH> 100644
--- a/test/simple.rb
+++ b/test/simple.rb
@@ -46,14 +46,22 @@ module MigrationSetup
end
def self.teardown!
- CreateCustomPkName.down
- CreateThings.down
- CreateValidatesUniquenessOf.down
- CreateAutoIds.down
- CreateUsers.down
- CreateEntries.down
- CreateStringIds.down
- DbTypeMigration.down
+ silent_down CreateCustomPkName
+ silent_down CreateThings
+ silent_down CreateValidatesUniquenessOf
+ silent_down CreateAutoIds
+ silent_down CreateUsers
+ silent_down CreateEntries
+ silent_down CreateStringIds
+ silent_down DbTypeMigration
+ end
+
+ def self.silent_down(migration)
+ begin
+ migration.down
+ rescue ActiveRecord::ActiveRecordError => e
+ warn "#{migration}.down failed: #{e.inspect}"
+ end
end
end
|
attempt to tear-down all migrations - even when error occurs on some
... helps test setup/teardown on DBs where database is not re-created
|
jruby_activerecord-jdbc-adapter
|
train
|
b8e992027b58fda1bccda4d4c0ba1e0818306022
|
diff --git a/gossip/stats.py b/gossip/stats.py
index <HASH>..<HASH> 100644
--- a/gossip/stats.py
+++ b/gossip/stats.py
@@ -66,6 +66,23 @@ class Stats(object):
raise AttributeError("no metric of type %r", attr)
+ def get_stats(self, metrics=[]):
+ """
+ Return a dictionary with current value of the statistics
+
+ Args:
+ metrics (list of Metric): A list of metrics to dump.
+ """
+ if len(metrics) == 0:
+ metrics = self.Metrics.keys()
+
+ result = dict()
+ for metric in metrics:
+ if metric in self.Metrics:
+ result[metric] = self.Metrics[metric].get_metric()
+
+ return result
+
def dump_stats(self, batchid, metrics=[]):
"""Dumps associated metrics information to the log.
@@ -130,6 +147,13 @@ class Metric(object):
entry.
"""
logger.info("metric, %s", ", ".join([str(x) for x in args]))
+ return args
+
+ def get_metric(self):
+ """
+ Return the current value of the metric. Subclasses will override.
+ """
+ return None
def dump_metric(self, identifier):
"""Writes a logger entry containing the provided identifier and
@@ -138,7 +162,7 @@ class Metric(object):
Args:
identifier (str): The identifier to log.
"""
- self.dump(identifier, self.Name)
+ return self.dump(identifier, self.Name)
def reset(self):
"""Base class reset of associated measure.
@@ -167,6 +191,12 @@ class Value(Metric):
super(Value, self).__init__(name)
self.Value = value
+ def get_metric(self):
+ """
+ Return the current value of the metric.
+ """
+ return self.Value
+
def dump_metric(self, identifier):
"""Writes a logger entry containing the provided identifier,
the metric name, and the metric value.
@@ -174,7 +204,7 @@ class Value(Metric):
Args:
identifier (str): The identifier to log.
"""
- self.dump(identifier, self.Name, self.Value)
+ return self.dump(identifier, self.Name, self.Value)
class Counter(Metric):
@@ -202,6 +232,12 @@ class Counter(Metric):
"""
self.Value += int(value)
+ def get_metric(self):
+ """
+ Return the current value of the metric.
+ """
+ return self.Value
+
def dump_metric(self, identifier):
"""Writes a logger entry containing the provided identifier,
the metric name, and the metric value.
@@ -209,7 +245,7 @@ class Counter(Metric):
Args:
identifier (str): The identifier to log.
"""
- self.dump(identifier, self.Name, self.Value)
+ return self.dump(identifier, self.Name, self.Value)
def reset(self):
"""Resets the value of the metric to zero.
@@ -246,6 +282,12 @@ class MapCounter(Metric):
self.Values[key] = 0
self.Values[key] += int(value)
+ def get_metric(self):
+ """
+ Return the current value of the metric.
+ """
+ return self.Values
+
def dump_metric(self, identifier):
"""Writes a logger entry for each key in the map containing the
provided identifier, the key and the metric value.
@@ -256,6 +298,8 @@ class MapCounter(Metric):
for key, val in self.Values.iteritems():
self.dump(identifier, key, val)
+ return
+
def reset(self):
"""Resets the contents of the Values dict.
"""
@@ -289,6 +333,12 @@ class Average(Metric):
self.Total += value
self.Count += 1
+ def get_metric(self):
+ """
+ Return the current value of the metric.
+ """
+ return [self.Total, self.Count]
+
def dump_metric(self, identifier):
"""Writes a logger entry containing the provided identifier,
the name of the metric, the total value, and the counter.
@@ -326,6 +376,12 @@ class Sample(Metric):
super(Sample, self).__init__(name)
self.Closure = closure
+ def get_metric(self):
+ """
+ Return the current value of the metric.
+ """
+ return self.Closure()
+
def dump_metric(self, identifier):
"""Writes a logger entry containing the provided identifier, the
name of the metric, and the return value of Closure()
|
Provide ability to retrieve current metrics from stats module
This was derived directly from Mic Bowen's implementation.
|
hyperledger_sawtooth-core
|
train
|
ac88148559d14c7492163c25c1eb20927347d5c9
|
diff --git a/lib/index.js b/lib/index.js
index <HASH>..<HASH> 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -77,10 +77,14 @@ function monitor(interval, timeoutCb, pingTimeout) {
var _this2 = this;
pingTimeout = pingTimeout || interval;
- var currentTimeout = undefined;
- var currentInterval = undefined;
+ var currentTimeout = void 0;
+ var currentInterval = void 0;
+ var closed = false;
var onTimeoutExpired = function onTimeoutExpired() {
+ if (closed) return;
+ closed = true;
+
clearTimeout(currentTimeout);
clearInterval(currentInterval);
timeoutCb();
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -65,8 +65,12 @@ function monitor(interval, timeoutCb, pingTimeout) {
pingTimeout = pingTimeout || interval;
let currentTimeout;
let currentInterval;
+ let closed = false;
const onTimeoutExpired = () => {
+ if (closed) return;
+ closed = true;
+
clearTimeout(currentTimeout);
clearInterval(currentInterval);
timeoutCb();
|
fix multiple calls to onTimeoutExpired when monitoring (#2)
|
itajaja_websocket-monkeypatch
|
train
|
b71f5068ec8d85dc0edf854d6b1d199bbc7300b2
|
diff --git a/src/network/connection.js b/src/network/connection.js
index <HASH>..<HASH> 100644
--- a/src/network/connection.js
+++ b/src/network/connection.js
@@ -50,6 +50,7 @@ module.exports = class Connection {
this.correlationId = 0
this.pendingQueue = {}
this.authHandlers = null
+ this.authExpectResponse = false
const log = level => (message, extra = {}) => {
const logFn = this.logger[level]
@@ -173,11 +174,14 @@ module.exports = class Connection {
* @public
* @returns {Promise}
*/
- authenticate({ request, response }) {
+ authenticate({ authExpectResponse = false, request, response }) {
+ this.authExpectResponse = authExpectResponse
return new Promise(async (resolve, reject) => {
this.authHandlers = {
onSuccess: rawData => {
this.authHandlers = null
+ this.authExpectResponse = false
+
response
.decode(rawData)
.then(data => response.parse(data))
@@ -185,6 +189,8 @@ module.exports = class Connection {
},
onError: () => {
this.authHandlers = null
+ this.authExpectResponse = false
+
reject(
new KafkaJSConnectionError('Connection closed by the server', {
broker: `${this.host}:${this.port}`,
@@ -292,7 +298,7 @@ module.exports = class Connection {
* @private
*/
processData(rawData) {
- if (this.authHandlers) {
+ if (this.authHandlers && !this.authExpectResponse) {
return this.authHandlers.onSuccess(rawData)
}
@@ -303,6 +309,10 @@ module.exports = class Connection {
return
}
+ if (this.authHandlers && this.authExpectResponse) {
+ return this.authHandlers.onSuccess(this.buffer)
+ }
+
const data = Buffer.from(this.buffer)
const decoder = new Decoder(data)
const expectedResponseSize = decoder.readInt32()
|
Allow connection to buffer data for auth requests expecting a response
|
tulios_kafkajs
|
train
|
dfcf414111a5959df0b9438ab284d6087ac6f3f5
|
diff --git a/telethon/client/uploads.py b/telethon/client/uploads.py
index <HASH>..<HASH> 100644
--- a/telethon/client/uploads.py
+++ b/telethon/client/uploads.py
@@ -414,32 +414,30 @@ class UploadMethods(MessageParseMethods, UserMethods):
os.path.basename(file))
}
if utils.is_audio(file) and hachoir:
- m = hachoir.metadata.extractMetadata(
- hachoir.parser.createParser(file)
- )
- attr_dict[types.DocumentAttributeAudio] = \
- types.DocumentAttributeAudio(
- voice=voice_note,
- title=m.get('title') if m.has(
- 'title') else None,
- performer=m.get('author') if m.has(
- 'author') else None,
- duration=int(m.get('duration').seconds
- if m.has('duration') else 0)
- )
+ with hachoir.parser.createParser(file) as parser:
+ m = hachoir.metadata.extractMetadata(parser)
+ attr_dict[types.DocumentAttributeAudio] = \
+ types.DocumentAttributeAudio(
+ voice=voice_note,
+ title=m.get('title') if m.has(
+ 'title') else None,
+ performer=m.get('author') if m.has(
+ 'author') else None,
+ duration=int(m.get('duration').seconds
+ if m.has('duration') else 0)
+ )
if not force_document and utils.is_video(file):
if hachoir:
- m = hachoir.metadata.extractMetadata(
- hachoir.parser.createParser(file)
- )
- doc = types.DocumentAttributeVideo(
- round_message=video_note,
- w=m.get('width') if m.has('width') else 0,
- h=m.get('height') if m.has('height') else 0,
- duration=int(m.get('duration').seconds
- if m.has('duration') else 0)
- )
+ with hachoir.parser.createParser(file) as parser:
+ m = hachoir.metadata.extractMetadata(parser)
+ doc = types.DocumentAttributeVideo(
+ round_message=video_note,
+ w=m.get('width') if m.has('width') else 0,
+ h=m.get('height') if m.has('height') else 0,
+ duration=int(m.get('duration').seconds
+ if m.has('duration') else 0)
+ )
else:
doc = types.DocumentAttributeVideo(
0, 1, 1, round_message=video_note)
|
Fix hachoir don't close files by itself (#<I>)
|
LonamiWebs_Telethon
|
train
|
42154f07775887ce0b48aec03c73f15cd0836d0f
|
diff --git a/lib/engineyard.rb b/lib/engineyard.rb
index <HASH>..<HASH> 100644
--- a/lib/engineyard.rb
+++ b/lib/engineyard.rb
@@ -6,6 +6,9 @@ module EY
class Error < StandardError; end
+ class EnvironmentError < Error; end
+ class BranchMismatch < Error; end
+
autoload :Account, 'engineyard/account'
autoload :API, 'engineyard/api'
autoload :Config, 'engineyard/config'
diff --git a/lib/engineyard/cli.rb b/lib/engineyard/cli.rb
index <HASH>..<HASH> 100644
--- a/lib/engineyard/cli.rb
+++ b/lib/engineyard/cli.rb
@@ -8,24 +8,26 @@ module EY
method_option :force, :type => :boolean, :aliases => %w(-f), :desc => "Force a deploy of the specified branch"
method_option :migrate, :type => :boolean, :default => true, :aliases => %w(-m), :desc => "Run migrations after deploy"
def deploy(environment = nil, branch = nil)
- environment ||= config.default_environment
- default_branch = config.default_branch(environment)
+ env_name ||= config.default_environment
+ default_branch = config.default_branch(env_name)
branch ||= (default_branch || repo.current_branch)
if default_branch && (branch != default_branch) && !options[:force]
- ui.say_status "Branch mismatch",
- %{Your deploy branch is set to "#{default_branch}".\n} +
- %{If you want to deploy branch "#{branch}", use --force.},
- :red
- raise Exit
+ raise BranchMismatch, %{Your deploy branch is set to "#{default_branch}".\n} +
+ %{If you want to deploy branch "#{branch}", use --force.}
end
- require 'pp'
- pp environment
- pp branch
- pp default_branch
+ env = account.environments.find{|e| e["name"] == env_name }
+ raise EnvironmentError, "No environment named '#{env_name}' running this app" unless env
+
+ # OMG EY cloud quotes nulls when it returns JSON :(
+ app_master = env["app_master"] != "null" && env["app_master"]
+ raise EnvironmentError, "Your environment isn't running" unless app_master
+
+ puts "ssh #{env["app_master"]} eysd deploy #{branch}"
end
+
desc "targets", "List environments that are deploy targets for the app in the current directory"
def targets
envs = account.environments_for_url(repo.url)
@@ -37,6 +39,7 @@ module EY
end
end
+
desc "environments", "All cloud environments"
def environments
envs = account.environments
@@ -68,13 +71,16 @@ module EY
def print_envs(envs)
# this should be a method of EY::Account::Environments or something eventually
- envs.each do |e|
+ printable_envs = envs.map do |e|
icount = e["instances_count"]
iname = (icount == 1) ? "instance" : "instances"
- env = " #{e["name"]}, #{icount} #{iname}"
- env << " (default)" if e["name"] == config.default_environment
- ui.say env
+
+ e["name"] << " (default)" if e["name"] == config.default_environment
+ env = [e["name"]]
+ env << "#{icount} #{iname}"
+ env << e["apps"].map{|a| a["name"] }.join(", ")
end
+ ui.print_table(printable_envs, :ident => 2)
end
end # CLI
end # EY
|
Deploy errors now inherit from EY::Error, and have better messages
Change-Id: I4c<I>b<I>e<I>a9d<I>bd<I>feff<I>d<I>c9c
Reviewed-on: <URL>
|
engineyard_engineyard
|
train
|
aac1a786f4e5acaed282a731ca9ec7cfda258e15
|
diff --git a/lib/formtastic-bootstrap/helpers.rb b/lib/formtastic-bootstrap/helpers.rb
index <HASH>..<HASH> 100644
--- a/lib/formtastic-bootstrap/helpers.rb
+++ b/lib/formtastic-bootstrap/helpers.rb
@@ -1,13 +1,14 @@
-require "formtastic-bootstrap/helpers/fieldset_wrapper"
+# require "formtastic-bootstrap/helpers/fieldset_wrapper"
require "formtastic-bootstrap/helpers/input_helper"
require "formtastic-bootstrap/helpers/inputs_helper"
module FormtasticBootstrap
module Helpers
- autoload :ActionHelper, 'formtastic-bootstrap/helpers/action_helper'
+ autoload :ActionHelper, 'formtastic-bootstrap/helpers/action_helper'
+ autoload :ActionsHelper, 'formtastic-bootstrap/helpers/actions_helper'
# autoload :ErrorsHelper, 'formtastic/helpers/errors_helper'
- # autoload :FieldsetWrapper, 'formtastic/helpers/fieldset_wrapper'
+ autoload :FieldsetWrapper, 'formtastic-bootstrap/helpers/fieldset_wrapper'
# autoload :FileColumnDetection, 'formtastic/helpers/file_column_detection'
# autoload :FormHelper, 'formtastic/helpers/form_helper'
# autoload :InputHelper, 'formtastic/helpers/input_helper'
diff --git a/lib/formtastic-bootstrap/helpers/actions_helper.rb b/lib/formtastic-bootstrap/helpers/actions_helper.rb
index <HASH>..<HASH> 100644
--- a/lib/formtastic-bootstrap/helpers/actions_helper.rb
+++ b/lib/formtastic-bootstrap/helpers/actions_helper.rb
@@ -3,6 +3,7 @@ module FormtasticBootstrap
module ActionsHelper
include Formtastic::Helpers::ActionsHelper
+ include FormtasticBootstrap::Helpers::FieldsetWrapper
def actions(*args, &block)
@@ -18,12 +19,6 @@ module FormtasticBootstrap
end
end
- # protected
- #
- # def default_actions
- # [:submit]
- # end
-
end
end
end
\ No newline at end of file
diff --git a/lib/formtastic-bootstrap/helpers/fieldset_wrapper.rb b/lib/formtastic-bootstrap/helpers/fieldset_wrapper.rb
index <HASH>..<HASH> 100644
--- a/lib/formtastic-bootstrap/helpers/fieldset_wrapper.rb
+++ b/lib/formtastic-bootstrap/helpers/fieldset_wrapper.rb
@@ -10,10 +10,6 @@ module FormtasticBootstrap
contents = args.last.is_a?(::Hash) ? '' : args.pop.flatten
html_options = args.extract_options!
- legend = (html_options[:name] || '').to_s
- legend %= parent_child_index(html_options[:parent]) if html_options[:parent]
- legend = template.content_tag(:legend, Formtastic::Util.html_safe(legend)) unless legend.blank?
-
if block_given?
contents = if template.respond_to?(:is_haml?) && template.is_haml?
template.capture_haml(&block)
@@ -24,10 +20,11 @@ module FormtasticBootstrap
# Ruby 1.9: String#to_s behavior changed, need to make an explicit join.
contents = contents.join if contents.respond_to?(:join)
+
+ legend = field_set_legend(html_options)
fieldset = template.content_tag(:fieldset,
Formtastic::Util.html_safe(legend) << Formtastic::Util.html_safe(contents),
- html_options.except(:builder, :parent, :name)
- )
+ html_options.except(:builder, :parent, :name))
fieldset
end
|
Additional work on ActionsHelper.
|
mjbellantoni_formtastic-bootstrap
|
train
|
90c270560e1485d8e0656103ee8655f87b8e485a
|
diff --git a/bin/server-cloud-elections b/bin/server-cloud-elections
index <HASH>..<HASH> 100755
--- a/bin/server-cloud-elections
+++ b/bin/server-cloud-elections
@@ -15,8 +15,7 @@ remote_base_name = schema.options.remote_base.split('::')[-1].camelcase
remoter_base = PoolParty::Remote.module_eval(remote_base_name)
o.loaded_clouds.each do |cld|
- keypairs = schema.options.delete(:keypairs).map {|a| PoolParty::Key.new(a.full_filepath) }
- cld.options.merge!(schema.options.merge(:keypairs => keypairs))
+ cld.update_from_schema(schema)
case vote_for
when "expand"
diff --git a/bin/server-ensure-provisioning b/bin/server-ensure-provisioning
index <HASH>..<HASH> 100755
--- a/bin/server-ensure-provisioning
+++ b/bin/server-ensure-provisioning
@@ -11,10 +11,8 @@ end
schema = ::PoolParty.load_cloud_from_json
o.loaded_clouds.each do |cld|
- keypairs = schema.options.delete(:keypairs).map {|a| PoolParty::Key.new(a.full_filepath) }
- cld.options.merge!(schema.options.merge(:keypairs => keypairs))
- cld.dependency_provider schema.options.dependency_resolver.split("::")[-1].gsub(/Resolver/, '')
-
+ cld.update_from_schema(schema)
+
# If an IP or DNS name is given, bootstrap that node, otherwise, bootstrap all running nodes.
nodes = !o.unflagged_args.empty? ? o.unflagged_args : cld.remote_instances_list.collect {|inst| inst.ip if inst.running? }.compact
if nodes.empty?
diff --git a/lib/poolparty/modules/cloud_resourcer.rb b/lib/poolparty/modules/cloud_resourcer.rb
index <HASH>..<HASH> 100644
--- a/lib/poolparty/modules/cloud_resourcer.rb
+++ b/lib/poolparty/modules/cloud_resourcer.rb
@@ -87,7 +87,7 @@ module PoolParty
if args && !args.empty?
args.each {|arg| _keypairs.unshift Key.new(arg) unless arg.nil? || arg.empty? }
else
- _keypairs.select {|key| key.exists? }.first
+ @keypair ||= _keypairs.select {|key| key.exists? }.first
end
end
@@ -101,6 +101,15 @@ module PoolParty
@full_keypair_path ||= keypair.full_filepath
end
+ def update_from_schema(schema)
+ keypairs = schema.options.delete(:keypairs).map {|a| PoolParty::Key.new(a.basename) }
+ cld.options.merge! schema.options
+ cld.dsl_options[:keypairs] = keypairs
+
+ cld.dsl_options[:dependency_resolver] = schema.options.dependency_resolver.split("::")[-1].gsub(/Resolver/, '').preserved_class_constant("Resolver") rescue PoolParty::Chef
+
+ end
+
# TODO: deprecate
def number_of_resources
arr = resources.map do |n, r|
diff --git a/lib/poolparty/poolparty/key.rb b/lib/poolparty/poolparty/key.rb
index <HASH>..<HASH> 100644
--- a/lib/poolparty/poolparty/key.rb
+++ b/lib/poolparty/poolparty/key.rb
@@ -52,7 +52,8 @@ module PoolParty
# Default locations to search for the key
def self.keypair_paths
- [ "#{ENV["HOME"]}/.ssh",
+ [
+ "#{ENV["HOME"]}/.ssh",
"#{Default.poolparty_home_path}/keys",
PoolParty::Default.base_keypair_path,
PoolParty::Default.base_config_directory,
diff --git a/lib/poolparty/provision/dr_configure.rb b/lib/poolparty/provision/dr_configure.rb
index <HASH>..<HASH> 100644
--- a/lib/poolparty/provision/dr_configure.rb
+++ b/lib/poolparty/provision/dr_configure.rb
@@ -30,13 +30,14 @@ module PoolParty
end
end
- attr_reader :cloud
- attr_accessor :full_keypair_path
+ attr_reader :cloud, :keypair
+
def initialize(host, opts={}, &block)
self.class.defaults.merge(opts).to_instance_variables(self)
@target_host = host
@configurator = "::PoolParty::Provision::#{dependency_resolver.capitalize}".constantize
@cloud = opts[:cloud]
+ @keypair = @cloud.keypair
@cloud.call_before_configure_callbacks if @cloud
prescribe_configuration
|
Added update_from_schema to cloud for server tasks
Explicitly set key in the dr_configure when on server
|
auser_poolparty
|
train
|
8233ca1963fd072bfae5a4e267b9046b50a5786e
|
diff --git a/libdokan/fs.go b/libdokan/fs.go
index <HASH>..<HASH> 100644
--- a/libdokan/fs.go
+++ b/libdokan/fs.go
@@ -251,6 +251,11 @@ func (f *FS) open(ctx context.Context, oc *openContext, ps []string) (dokan.File
// Unfortunately sometimes we end up in this case while using
// reparse points.
case PublicName == ps[0], "PUBLIC" == ps[0]:
+ // Refuse private directories while we are in a a generic error state.
+ if f.remoteStatus.ExtraFileName() == libfs.HumanErrorFileName {
+ f.log.CWarningf(ctx, "Refusing access to public directory while errors are present!")
+ return nil, false, dokan.ErrAccessDenied
+ }
return f.root.public.open(ctx, oc, ps[1:])
case PrivateName == ps[0], "PRIVATE" == ps[0]:
// Refuse private directories while we are in a error state.
@@ -538,23 +543,29 @@ func (r *Root) GetFileInformation(*dokan.FileInfo) (*dokan.Stat, error) {
// FindFiles for dokan readdir.
func (r *Root) FindFiles(fi *dokan.FileInfo, callback func(*dokan.NamedStat) error) error {
var ns dokan.NamedStat
+ var err error
ns.NumberOfLinks = 1
ns.FileAttributes = fileAttributeDirectory
- ns.Name = PublicName
- err := callback(&ns)
- if err != nil {
- return err
- }
- if name, size := r.private.fs.remoteStatus.ExtraFileNameAndSize(); name != "" {
- ns.Name = name
- ns.FileAttributes = fileAttributeNormal
- ns.FileSize = size
+ ename, esize := r.private.fs.remoteStatus.ExtraFileNameAndSize()
+ switch ename {
+ case "":
+ ns.Name = PrivateName
err = callback(&ns)
if err != nil {
return err
}
- } else {
- ns.Name = PrivateName
+ fallthrough
+ case libfs.HumanNoLoginFileName:
+ ns.Name = PublicName
+ err = callback(&ns)
+ if err != nil {
+ return err
+ }
+ }
+ if ename != "" {
+ ns.Name = ename
+ ns.FileAttributes = fileAttributeNormal
+ ns.FileSize = esize
err = callback(&ns)
if err != nil {
return err
|
libdokan: Also deny public directories when there are generic errors
|
keybase_client
|
train
|
b957bf952ee71a732022b152d896b5a322d0b951
|
diff --git a/cmd.go b/cmd.go
index <HASH>..<HASH> 100644
--- a/cmd.go
+++ b/cmd.go
@@ -26,9 +26,9 @@ type PassiveCmd struct {
// PeriodicConfig holds a cron specification for periodically notifying the configured channels
type PeriodicConfig struct {
- CronSpec string // CronSpec that schedules some function
- Channels []string // A list of channels to notify
- CmdFunc func(channel string) (string, error) // func to be executed at the period specified on CronSpec
+ CronSpec string // CronSpec that schedules some function
+ Channels []string // A list of channels to notify
+ CmdFunc func(channel string) (string, error) // func to be executed at the period specified on CronSpec
}
// User holds user id (nick) and real name
diff --git a/cmd_test.go b/cmd_test.go
index <HASH>..<HASH> 100644
--- a/cmd_test.go
+++ b/cmd_test.go
@@ -27,60 +27,62 @@ func resetResponses() {
}
func TestPeriodicCommands(t *testing.T) {
- Convey("Periodic Commands", t, func() {
- Reset(resetResponses)
- RegisterPeriodicCommand("morning",
- PeriodicConfig{
- CronSpec: "0 0 08 * * mon-fri",
- Channels: []string{"#channel"},
- CmdFunc: func(channel string) (string, error) { return "ok " + channel, nil },
- })
-
- b := New(&Handlers{Response: responseHandler})
-
- entries := b.cron.Entries()
- So(entries, ShouldHaveLength, 1)
- So(entries[0].Next.Hour(), ShouldEqual, 8)
-
- entries[0].Job.Run()
+ resetResponses()
+ RegisterPeriodicCommand("morning",
+ PeriodicConfig{
+ CronSpec: "0 0 08 * * mon-fri",
+ Channels: []string{"#channel"},
+ CmdFunc: func(channel string) (string, error) { return "ok " + channel, nil },
+ })
+ b := New(&Handlers{Response: responseHandler})
+
+ entries := b.cron.Entries()
+ if len(entries) != 1 {
+ t.Fatal("Should have one cron job entry")
+ }
+ if entries[0].Next.Hour() != 8 {
+ t.Fatal("Cron job should be scheduled to 8am")
+ }
+
+ entries[0].Job.Run()
+
+ if len(replies) != 1 {
+ t.Fatal("Should have one reply in the channel")
+ }
+ if replies[0] != "ok #channel" {
+ t.Fatal("Invalid reply")
+ }
+}
- So(replies, ShouldHaveLength, 1)
- So(replies[0], ShouldEqual, "ok #channel")
+func TestDisabledCommands(t *testing.T) {
+ resetResponses()
+ commands = make(map[string]*customCommand)
+ b := New(&Handlers{
+ Response: responseHandler,
})
-}
-func TestDisableCommands(t *testing.T) {
- Convey("Allow disabling commands", t, func() {
- Reset(resetResponses)
- commands = make(map[string]*customCommand)
- b := New(&Handlers{
- Response: responseHandler,
+ RegisterCommand("cmd", "", "",
+ func(c *Cmd) (string, error) {
+ return "active", nil
})
- RegisterCommand("cmd", "", "",
- func(c *Cmd) (string, error) {
- return "active", nil
- })
-
- RegisterPassiveCommand("passive",
- func(cmd *PassiveCmd) (string, error) {
- return "passive", nil
- })
-
- Convey("When the disabled command is active", func() {
- b.Disable([]string{"cmd"})
- b.MessageReceived("#go-bot", "!cmd", &User{Nick: "user"})
-
- So(replies, ShouldBeEmpty)
+ RegisterPassiveCommand("passive",
+ func(cmd *PassiveCmd) (string, error) {
+ return "passive", nil
})
- Convey("When the disabled command is passive", func() {
- b.Disable([]string{"passive"})
- b.MessageReceived("#go-bot", "regular message", &User{Nick: "user"})
+ b.Disable([]string{"cmd"})
+ b.MessageReceived("#go-bot", "!cmd", &User{Nick: "user"})
+ if len(replies) != 0 {
+ t.Fatal("Should not execute disabled active commands")
+ }
- So(replies, ShouldBeEmpty)
- })
- })
+ b.Disable([]string{"passive"})
+ b.MessageReceived("#go-bot", "regular message", &User{Nick: "user"})
+
+ if len(replies) != 0 {
+ t.Fatal("Should not execute disabled passive commands")
+ }
}
func TestMessageReceived(t *testing.T) {
|
Removes Goconvey from Periodic and Disabled commands tests (#<I>)
|
go-chat-bot_bot
|
train
|
957411a3205626fecc3122e43dca21adb09eddf0
|
diff --git a/lib/statsd.js b/lib/statsd.js
index <HASH>..<HASH> 100644
--- a/lib/statsd.js
+++ b/lib/statsd.js
@@ -178,7 +178,10 @@ Client.prototype.sendAll = function(stat, value, type, sampleRate, tags, callbac
return;
}
- sentBytes += bytes;
+ if (bytes) {
+ sentBytes += bytes;
+ }
+
if(completed === stat.length && typeof callback === 'function'){
callback(null, sentBytes);
}
|
Do not add bytes to sentBytes when it is undefined
|
brightcove_hot-shots
|
train
|
e07b14bcfe9b374df5e1d129b83ee3b49292379d
|
diff --git a/src/grid/PurseGridView.php b/src/grid/PurseGridView.php
index <HASH>..<HASH> 100644
--- a/src/grid/PurseGridView.php
+++ b/src/grid/PurseGridView.php
@@ -11,8 +11,10 @@
namespace hipanel\modules\finance\grid;
+use hipanel\modules\client\widgets\combo\ContactCombo;
use hipanel\helpers\FontIcon;
use hipanel\widgets\ArraySpoiler;
+use hiqdev\xeditable\widgets\ComboXEditable;
use Yii;
use yii\helpers\Html;
@@ -57,8 +59,23 @@ class PurseGridView extends \hipanel\grid\BoxedGridView
'requisite' => [
'format' => 'raw',
'value' => function ($model) {
- $org = $model->requisite->organization;
- return $org . ($org ? ' / ' : '') . $model->requisite->name;
+ if (!Yii::$app->user->can('manage')) {
+ $org = $model->requisite->organization;
+ return $org . ($org ? ' / ' : '') . $model->requisite->name;
+ }
+ return ComboXEditable::widget([
+ 'model' => $model,
+ 'attribute' => 'requisite_id',
+ 'combo' => [
+ 'class' => ContactCombo::class,
+ 'client_id' => $model->seller_id,
+ 'pluginOptions' => [
+ 'select2Options' => [
+ 'width' => '40rem',
+ ],
+ ],
+ ],
+ ]);
},
],
];
|
+ ComboXEditable for purse requisite
|
hiqdev_hipanel-module-finance
|
train
|
ad002dda71f14ee0e6c9f45d6c97e42972212859
|
diff --git a/spec/support/pedant/pedant_config.rb b/spec/support/pedant/pedant_config.rb
index <HASH>..<HASH> 100644
--- a/spec/support/pedant/pedant_config.rb
+++ b/spec/support/pedant/pedant_config.rb
@@ -21,7 +21,8 @@
################################################################################
# You MUST specify the address of the server the API requests will be
# sent to. Only specify protocol, hostname, and port.
-chef_server 'http://127.0.0.1:8889'
+# NOTE this is assigned in run_pedant.rb, because it's possible 8889 will not be the port chosen.
+#chef_server 'http://127.0.0.1:8889'
# If you are doing development testing, you can specify the address of
# the Solr server. The presence of this parameter will enable tests
diff --git a/spec/support/pedant/run_pedant.rb b/spec/support/pedant/run_pedant.rb
index <HASH>..<HASH> 100644
--- a/spec/support/pedant/run_pedant.rb
+++ b/spec/support/pedant/run_pedant.rb
@@ -26,7 +26,7 @@ def start_server(chef_repo_path)
chef_fs = Chef::ChefFS::Config.new.local_fs
data_store = Chef::ChefFS::ChefFSDataStore.new(chef_fs)
data_store = ChefZero::DataStore::V1ToV2Adapter.new(data_store, 'chef', :org_defaults => ChefZero::DataStore::V1ToV2Adapter::ORG_DEFAULTS)
- server = ChefZero::Server.new(:port => 8889, :data_store => data_store)#, :log_level => :debug)
+ server = ChefZero::Server.new(:port => 8889.upto(9999), :data_store => data_store)#, :log_level => :debug)
server.start_background
server
end
@@ -46,6 +46,7 @@ begin
Pedant.config.suite = 'api'
Pedant.config[:config_file] = 'spec/support/pedant/pedant_config.rb'
+ Pedant.config.chef_server = server.url
Pedant.setup([
'--skip-knife',
'--skip-validation',
|
Allow Pedant to run if port <I> is blocked
|
chef_chef
|
train
|
d331df24f5fcfbd3bc0972ca356f2f40858db569
|
diff --git a/js/gateio.js b/js/gateio.js
index <HASH>..<HASH> 100644
--- a/js/gateio.js
+++ b/js/gateio.js
@@ -856,10 +856,20 @@ module.exports = class gateio extends Exchange {
const market = this.market (symbol);
const request = {
'currency_pair': market['id'],
+ // 'limit': limit,
+ // 'page': 0,
+ // 'order_id': 'Order ID',
+ // 'account': 'spot', // default to spot and margin account if not specified, set to cross_margin to operate against margin account
+ // 'from': since, // default to 7 days before current time
+ // 'to': this.milliseconds (), // default to current time
};
if (limit !== undefined) {
request['limit'] = limit; // default 100, max 1000
}
+ if (since !== undefined) {
+ request['from'] = since;
+ request['to'] = since + 30 * 24 * 60 * 60 * 1000;
+ }
const response = await this.privateSpotGetMyTrades (this.extend (request, params));
return this.parseTrades (response, market, since, limit);
}
|
gateio fetchMyTrades since
|
ccxt_ccxt
|
train
|
0a88ca7b8ff84ee4463c91aa3c1d4fce797c2ffb
|
diff --git a/plugins/org.eclipse.xtext/src/org/eclipse/xtext/xtext/XtextLinker.java b/plugins/org.eclipse.xtext/src/org/eclipse/xtext/xtext/XtextLinker.java
index <HASH>..<HASH> 100644
--- a/plugins/org.eclipse.xtext/src/org/eclipse/xtext/xtext/XtextLinker.java
+++ b/plugins/org.eclipse.xtext/src/org/eclipse/xtext/xtext/XtextLinker.java
@@ -196,8 +196,8 @@ public class XtextLinker extends Linker {
// unload generated metamodels as they will be recreated during linking
for (AbstractMetamodelDeclaration metamodelDeclaration : ((Grammar) root).getMetamodelDeclarations()) {
if (metamodelDeclaration instanceof GeneratedMetamodel) {
- EPackage ePackage = ((GeneratedMetamodel) metamodelDeclaration).getEPackage();
- if (ePackage != null) {
+ EPackage ePackage = (EPackage) metamodelDeclaration.eGet(XtextPackage.Literals.ABSTRACT_METAMODEL_DECLARATION__EPACKAGE, false);
+ if (ePackage != null && !ePackage.eIsProxy()) {
Resource resource = ePackage.eResource();
if (resource != null && resource.getResourceSet() != null) {
if (unloader != null) {
diff --git a/plugins/org.eclipse.xtext/src/org/eclipse/xtext/xtext/XtextLinkingService.java b/plugins/org.eclipse.xtext/src/org/eclipse/xtext/xtext/XtextLinkingService.java
index <HASH>..<HASH> 100644
--- a/plugins/org.eclipse.xtext/src/org/eclipse/xtext/xtext/XtextLinkingService.java
+++ b/plugins/org.eclipse.xtext/src/org/eclipse/xtext/xtext/XtextLinkingService.java
@@ -278,9 +278,10 @@ public class XtextLinkingService extends DefaultLinkingService {
generatedEPackage.setNsPrefix(generatedMetamodel.getName());
generatedEPackage.setNsURI(nsURI);
final Resource generatedPackageResource = new EcoreResourceFactoryImpl().createResource(uri);
- try {
+ XtextResourceSet resourceSet = (XtextResourceSet) generatedMetamodel.eResource().getResourceSet();
+ if (!resourceSet.getURIResourceMap().containsKey(generatedPackageResource.getURI())) {
generatedMetamodel.eResource().getResourceSet().getResources().add(generatedPackageResource);
- } catch (IllegalStateException exception) {
+ } else {
generatedPackageResource.setURI(URI.createURI(nsURI+"_"+generatedMetamodel.hashCode()));
generatedMetamodel.eResource().getResourceSet().getResources().add(generatedPackageResource);
}
diff --git a/plugins/org.eclipse.xtext/src/org/eclipse/xtext/xtext/ecoreInference/Xtext2EcoreTransformer.java b/plugins/org.eclipse.xtext/src/org/eclipse/xtext/xtext/ecoreInference/Xtext2EcoreTransformer.java
index <HASH>..<HASH> 100755
--- a/plugins/org.eclipse.xtext/src/org/eclipse/xtext/xtext/ecoreInference/Xtext2EcoreTransformer.java
+++ b/plugins/org.eclipse.xtext/src/org/eclipse/xtext/xtext/ecoreInference/Xtext2EcoreTransformer.java
@@ -121,7 +121,11 @@ public class Xtext2EcoreTransformer {
Iterables.filter(grammar.getMetamodelDeclarations(), GeneratedMetamodel.class),
new Function<AbstractMetamodelDeclaration, EPackage>() {
public EPackage apply(AbstractMetamodelDeclaration param) {
- return param.getEPackage();
+ EPackage pack = (EPackage) param.eGet(XtextPackage.Literals.ABSTRACT_METAMODEL_DECLARATION__EPACKAGE, false);
+ if (pack != null && !pack.eIsProxy()) {
+ return pack;
+ }
+ return null;
}
}), Predicates.notNull()));
return getPackagesSortedByName(result);
|
[xtext] don't accidentely resolve AbstractMetamodelDeclaration#getEPackage, since it will leave an empty XMIResource behind. (see <URL>)
Change-Id: I<I>a2df4fcd<I>d<I>eba1a0b7bfd<I>dd<I>ca
|
eclipse_xtext-core
|
train
|
492b666266c9b67a695476ead616a06e1f92c0d0
|
diff --git a/src/werkzeug/middleware/shared_data.py b/src/werkzeug/middleware/shared_data.py
index <HASH>..<HASH> 100644
--- a/src/werkzeug/middleware/shared_data.py
+++ b/src/werkzeug/middleware/shared_data.py
@@ -35,7 +35,7 @@ class SharedDataMiddleware(object):
environments or simple server setups. Usage is quite simple::
import os
- from werkzeug.wsgi import SharedDataMiddleware
+ from werkzeug.middleware.shared_data import SharedDataMiddleware
app = SharedDataMiddleware(app, {
'/static': os.path.join(os.path.dirname(__file__), 'static')
|
Update documentation of SharedDataMiddleware
Let the doc of SharedDataMiddleware reflect its move to middleware.shared_data
|
pallets_werkzeug
|
train
|
c1e4feaa8eabfdd30672ca680665deba2fbbec74
|
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -5,7 +5,7 @@
},
"name": "hdb",
"description": "SAP HANA Database Client for Node",
- "version": "0.2.0",
+ "version": "0.3.0",
"repository": {
"type": "git",
"url": "git://github.com/SAP/node-hdb.git"
@@ -29,14 +29,14 @@
},
"dependencies": {},
"devDependencies": {
- "should": "~2.1.0",
- "mocha": "~1.14.0",
- "async": "~0.2.9",
- "debuglog": "~0.0.2",
- "readable-stream": "~1.1.9",
+ "should": "~3.1.3",
+ "mocha": "~1.17.1",
+ "async": "~0.2.10",
+ "debuglog": "~1.0.0",
+ "readable-stream": "~1.1.11",
"generic-pool": "~2.0.4",
- "fstream": "~0.1.24",
- "concat-stream": "~1.2.0"
+ "fstream": "~0.1.25",
+ "concat-stream": "~1.4.1"
},
"optionalDependencies": {}
}
\ No newline at end of file
diff --git a/test/acceptance/db.Lob.js b/test/acceptance/db.Lob.js
index <HASH>..<HASH> 100644
--- a/test/acceptance/db.Lob.js
+++ b/test/acceptance/db.Lob.js
@@ -38,9 +38,8 @@ describe('db', function () {
if (err) {
return done(err);
}
- rows.should
- .have.length(db.images.length)
- .and.eql(db.images);
+ rows.should.have.length(db.images.length);
+ rows.should.eql(db.images);
done();
});
});
diff --git a/test/acceptance/db.Prepare.js b/test/acceptance/db.Prepare.js
index <HASH>..<HASH> 100644
--- a/test/acceptance/db.Prepare.js
+++ b/test/acceptance/db.Prepare.js
@@ -104,8 +104,8 @@ describe('db', function () {
}
Object.keys(parameters).should.have.length(0);
arguments.should.have.length(3);
- rows.should.have.length(3)
- .and.eql(db.numbers.slice(3, 6));
+ rows.should.have.length(3);
+ rows.should.eql(db.numbers.slice(3, 6));
callback();
});
},
diff --git a/test/acceptance/db.Query.js b/test/acceptance/db.Query.js
index <HASH>..<HASH> 100644
--- a/test/acceptance/db.Query.js
+++ b/test/acceptance/db.Query.js
@@ -38,9 +38,8 @@ describe('db', function () {
if (err) {
return done(err);
}
- rows.should
- .have.length(db.numbers.length)
- .and.eql(db.numbers);
+ rows.should.have.length(db.numbers.length);
+ rows.should.eql(db.numbers);
done();
});
});
@@ -53,9 +52,8 @@ describe('db', function () {
}
rs.should.be.an.instanceof(ResultSet);
rs.fetch(function onfetch(err, rows) {
- rows.should
- .have.length(db.numbers.length)
- .and.eql(db.numbers);
+ rows.should.have.length(db.numbers.length);
+ rows.should.eql(db.numbers);
rs.closed.should.be.true;
done();
});
@@ -80,9 +78,8 @@ describe('db', function () {
rows = rows.concat(chunk);
}
}).once('end', function onend() {
- rows.should
- .have.length(db.numbers.length)
- .and.eql(db.numbers);
+ rows.should.have.length(db.numbers.length);
+ rows.should.eql(db.numbers);
done();
});
});
@@ -106,9 +103,8 @@ describe('db', function () {
callback();
};
writable.once('finish', function onfinish() {
- rows.should
- .have.length(db.numbers.length)
- .and.eql(db.numbers);
+ rows.should.have.length(db.numbers.length);
+ rows.should.eql(db.numbers);
done();
});
readable.once('error', function onreadable() {
@@ -132,9 +128,8 @@ describe('db', function () {
if (err) {
return done(err);
}
- rows.should
- .have.length(3)
- .and.eql(db.numbers.slice(3, 6));
+ rows.should.have.length(3);
+ rows.should.eql(db.numbers.slice(3, 6));
done();
});
});
|
bumped to version <I>
|
SAP_node-hdb
|
train
|
d76e83074195b6ea1ab6d49a8c8c104a32284cb3
|
diff --git a/word2vec-client/main.go b/word2vec-client/main.go
index <HASH>..<HASH> 100644
--- a/word2vec-client/main.go
+++ b/word2vec-client/main.go
@@ -16,6 +16,8 @@ import (
var addr string
var addListA, subListA string
var addListB, subListB string
+var sim bool
+var n int
func init() {
flag.StringVar(&addr, "addr", "localhost:1234", "server address")
@@ -23,6 +25,8 @@ func init() {
flag.StringVar(&subListA, "subA", "", "comma separated list of model words to subtract from the target vector A")
flag.StringVar(&addListB, "addB", "", "comma separated list of model words to add to the target vector B")
flag.StringVar(&subListB, "subB", "", "comma separated list of model words to subtract from the target vector B")
+ flag.BoolVar(&sim, "sim", false, "similarity query")
+ flag.IntVar(&n, "n", 10, "return `N` similar items in similarity query")
}
func makeExpr(addList, subList string) (word2vec.Expr, error) {
@@ -58,6 +62,19 @@ func main() {
os.Exit(1)
}
+ if sim {
+ c := word2vec.Client{Addr: addr}
+ r, err := c.CosineN(exprA, n)
+ if err != nil {
+ fmt.Printf("error looking up similar items: %v\n", err)
+ os.Exit(1)
+ }
+ for _, x := range r {
+ fmt.Printf("%9f %#v\n", x.Score, x.Word)
+ }
+ return
+ }
+
exprB, err := makeExpr(addListB, subListB)
if err != nil {
fmt.Printf("error creating target vector for 'B': %v\n", err)
|
And similarity query to client tool.
|
sajari_word2vec
|
train
|
befed23924c10253ca98a532f3c44f1e4f83fa02
|
diff --git a/src/Command/Route/RouteListCommand.php b/src/Command/Route/RouteListCommand.php
index <HASH>..<HASH> 100644
--- a/src/Command/Route/RouteListCommand.php
+++ b/src/Command/Route/RouteListCommand.php
@@ -8,6 +8,7 @@ use Platformsh\Cli\Model\Route;
use Platformsh\Cli\Service\Table;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
+use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class RouteListCommand extends CommandBase
@@ -21,7 +22,8 @@ class RouteListCommand extends CommandBase
->setName('route:list')
->setAliases(['routes'])
->setDescription('List all routes for an environment')
- ->addArgument('environment', InputArgument::OPTIONAL, 'The environment ID');
+ ->addArgument('environment', InputArgument::OPTIONAL, 'The environment ID')
+ ->addOption('refresh', null, InputOption::VALUE_NONE, 'Bypass the cache of routes');;
$this->setHiddenAliases(['environment:routes']);
Table::configureInput($this->getDefinition());
$this->addProjectOption()
@@ -41,10 +43,11 @@ class RouteListCommand extends CommandBase
$routes = Route::fromVariables($decoded);
$fromEnv = true;
} else {
- $this->debug('Reading routes from the API');
+ $this->debug('Reading routes from the deployments API');
$this->validateInput($input);
$environment = $this->getSelectedEnvironment();
- $routes = Route::fromEnvironmentApi($environment->getRoutes());
+ $deployment = $this->api()->getCurrentDeployment($environment, $input->getOption('refresh'));
+ $routes = Route::fromDeploymentApi($deployment->routes);
$fromEnv = false;
}
if (empty($routes)) {
|
Read routes from the deployments API in route:list command (#<I>)
|
platformsh_platformsh-cli
|
train
|
16b1ae21a31cdb47e1c42170899b549afa83193f
|
diff --git a/src/jobTreeSlave.py b/src/jobTreeSlave.py
index <HASH>..<HASH> 100644
--- a/src/jobTreeSlave.py
+++ b/src/jobTreeSlave.py
@@ -273,7 +273,8 @@ def main():
environment = cPickle.load(fileHandle)
fileHandle.close()
for i in environment:
- os.environ[i] = environment[i]
+ if i not in {"TMPDIR", "TMP", "HOSTNAME", "HOSTTYPE" }:
+ os.environ[i] = environment[i]
# sys.path is used by __import__ to find modules
if "PYTHONPATH" in environment:
for e in environment["PYTHONPATH"].split(':'):
|
Fix to jobTree to prevent it overriding TMPDIR
|
DataBiosphere_toil
|
train
|
947c1a248bca1c34e826338d661aec93b4034f4d
|
diff --git a/.bumpversion.cfg b/.bumpversion.cfg
index <HASH>..<HASH> 100644
--- a/.bumpversion.cfg
+++ b/.bumpversion.cfg
@@ -1,5 +1,5 @@
[bumpversion]
-current_version = 0.14.3
+current_version = 0.14.4
parse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)((?P<release>[a-z]+\d+))?
serialize =
{major}.{minor}.{patch}{release}
diff --git a/CHANGES.txt b/CHANGES.txt
index <HASH>..<HASH> 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,6 +1,11 @@
CHANGES
=======
+0.14.4 (01-29-2015)
+-------------------
+
+- Fix issue with error during constructing of url with regex parts #264
+
0.14.3 (01-28-2015)
-------------------
diff --git a/aiohttp/__init__.py b/aiohttp/__init__.py
index <HASH>..<HASH> 100644
--- a/aiohttp/__init__.py
+++ b/aiohttp/__init__.py
@@ -1,6 +1,6 @@
# This relies on each of the submodules having an __all__ variable.
-__version__ = '0.14.3'
+__version__ = '0.14.4'
from . import hdrs # noqa
diff --git a/aiohttp/web.py b/aiohttp/web.py
index <HASH>..<HASH> 100644
--- a/aiohttp/web.py
+++ b/aiohttp/web.py
@@ -1401,6 +1401,7 @@ class UrlDispatcher(AbstractRouter, collections.abc.Mapping):
assert method in self.METHODS, method
parts = []
factory = PlainRoute
+ format_parts = []
for part in path.split('/'):
if not part:
continue
@@ -1409,6 +1410,7 @@ class UrlDispatcher(AbstractRouter, collections.abc.Mapping):
parts.append('(?P<' + match.group('var') + '>' +
self.GOOD + ')')
factory = DynamicRoute
+ format_parts.append('{'+match.group('var')+'}')
continue
match = self.DYN_WITH_RE.match(part)
@@ -1416,9 +1418,11 @@ class UrlDispatcher(AbstractRouter, collections.abc.Mapping):
parts.append('(?P<' + match.group('var') + '>' +
match.group('re') + ')')
factory = DynamicRoute
+ format_parts.append('{'+match.group('var')+'}')
continue
if self.PLAIN.match(part):
parts.append(re.escape(part))
+ format_parts.append(part)
continue
raise ValueError("Invalid path '{}'['{}']".format(path, part))
if factory is PlainRoute:
@@ -1432,7 +1436,8 @@ class UrlDispatcher(AbstractRouter, collections.abc.Mapping):
except re.error as exc:
raise ValueError(
"Bad pattern '{}': {}".format(pattern, exc)) from None
- route = DynamicRoute(method, handler, name, compiled, path)
+ formatter = '/' + '/'.join(format_parts)
+ route = DynamicRoute(method, handler, name, compiled, formatter)
self._register_endpoint(route)
return route
diff --git a/tests/test_urldispatch.py b/tests/test_urldispatch.py
index <HASH>..<HASH> 100644
--- a/tests/test_urldispatch.py
+++ b/tests/test_urldispatch.py
@@ -326,3 +326,11 @@ class TestUrlDispatcher(unittest.TestCase):
"Bad pattern '/handler/(?P<to>+++)': nothing to repeat",
str(ctx.exception))
self.assertIsNone(ctx.exception.__cause__)
+
+ def test_route_dynamic_with_regex_spec(self):
+ handler = self.make_handler()
+ route = self.router.add_route('GET', '/get/{num:^\d+}', handler,
+ name='name')
+
+ url = route.url(parts={'num': '123'})
+ self.assertEqual('/get/123', url)
|
Fix issue #<I> with error during constructing of url with regex parts
|
aio-libs_aiohttp
|
train
|
d0bffdeabd3f94ff3b5b0dc8a18d9fcf8a00403c
|
diff --git a/index.html b/index.html
index <HASH>..<HASH> 100755
--- a/index.html
+++ b/index.html
@@ -175,6 +175,9 @@
<div class="clear-both"></div>
<div class="content square-panel-wrapper"><!-- dynamic content --></div>
</div>
+
+ <div class="clear-both"></div>
+ <br />
</div>
<!-- PAGE DIVIDER -->
diff --git a/js/navigation.js b/js/navigation.js
index <HASH>..<HASH> 100755
--- a/js/navigation.js
+++ b/js/navigation.js
@@ -702,14 +702,15 @@ function renderDiscoverPage(){
$(document).find('.page#discover .sub-page.category').hide();
$(document).find('.page#discover .sub-page.index').show();
+ var container = $(document).find('.page#discover .sub-page.index .content');
+ container.html('');
+ var html = '';
+
updateLoader('start');
// get the categories
getCategories().success( function(response){
- var container = $(document).find('.page#discover .sub-page.index .content');
- var html = '';
-
// loop all the categories
$(response.categories.items).each( function(key, category){
@@ -749,14 +750,16 @@ function renderDiscoverCategory( categoryID ){
$(document).find('.page#discover .sub-page.index').hide();
$(document).find('.page#discover .sub-page.category').show();
+ var container = $(document).find('.page#discover .sub-page.category .content');
+ var html = '';
+ container.html('');
+
updateLoader('start');
// get the single category
getCategory( categoryID ).success( function(response){
$(document).find('.page#discover .sub-page.category .title').html( response.name );
- var container = $(document).find('.page#discover .sub-page.category .content');
- var html = '';
// now get his playlists
getCategoryPlaylists( categoryID ).success( function(response){
diff --git a/js/playlists.js b/js/playlists.js
index <HASH>..<HASH> 100755
--- a/js/playlists.js
+++ b/js/playlists.js
@@ -16,7 +16,7 @@ $(document).ready( function(evt){
// listen for scroll to bottom, then we can load the additional tracks
$('#pages').scroll(function( evt ){
if( readyToLoad && ( $('#pages').scrollTop() + 40 >= ( $('#pages > .liner').innerHeight() - $('#pages').innerHeight() ) ) ){
-
+
// first, check the token
$.when( checkToken() ).done( function(){
diff --git a/js/spotify.js b/js/spotify.js
index <HASH>..<HASH> 100755
--- a/js/spotify.js
+++ b/js/spotify.js
@@ -5,9 +5,15 @@
* Integration and authentication with Spotify API
*/
-
function checkToken(){
-
+
+ var hash = window.location.hash;
+ hash = hash.replace('#','');
+
+ // if we have a force refresh hash, just do it, no questions asked
+ if( hash == 'force-token' )
+ getNewToken();
+
// if we don't have an authorization_code, go get one
if( localStorage.authorization_code == null ){
return getAuthorizationCode();
@@ -267,7 +273,7 @@ function getCategory( categoryID ){
function getCategoryPlaylists( categoryID ){
return $.ajax({
- url: 'https://api.spotify.com/v1/browse/categories/'+categoryID+'/playlists',
+ url: 'https://api.spotify.com/v1/browse/categories/'+categoryID+'/playlists?limit=50',
type: "GET",
headers: {
'Authorization': 'Bearer ' + localStorage.access_token
|
Show <I> playlists by default; allow force-token to kill tokens
|
jaedb_spotmop
|
train
|
78439416c0dccaf3edaed00a970b6278bf762baa
|
diff --git a/htlcswitch/circuit_test.go b/htlcswitch/circuit_test.go
index <HASH>..<HASH> 100644
--- a/htlcswitch/circuit_test.go
+++ b/htlcswitch/circuit_test.go
@@ -483,8 +483,9 @@ func TestCircuitMapPersistence(t *testing.T) {
// Removing already-removed circuit should return an error.
err = circuitMap.DeleteCircuits(circuit1.Incoming)
- if err == nil {
- t.Fatal("Remove did not return expected not found error")
+ if err != nil {
+ t.Fatal("Unexpected failure when deleting already "+
+ "deleted circuit: %v", err)
}
// Verify that nothing related to hash1 has changed
@@ -518,10 +519,17 @@ func TestCircuitMapPersistence(t *testing.T) {
assertNumCircuitsWithHash(t, circuitMap, hash2, 0)
assertNumCircuitsWithHash(t, circuitMap, hash3, 1)
- // Remove last remaining circuit with payment hash hash3.
- err = circuitMap.DeleteCircuits(circuit3.Incoming)
+ // In removing the final circuit, we will try and remove all other known
+ // circuits as well. Any circuits that are unknown to the circuit map
+ // will be ignored, and only circuit 3 should be cause any change in the
+ // state.
+ err = circuitMap.DeleteCircuits(
+ circuit1.Incoming, circuit2.Incoming,
+ circuit3.Incoming, circuit4.Incoming,
+ )
if err != nil {
- t.Fatalf("Remove returned unexpected error: %v", err)
+ t.Fatalf("Unexpected failure when removing circuit while also "+
+ "deleting already deleted circuits: %v", err)
}
// Check that the circuit map is empty, even after restarting.
|
htlcswitch/circuit_test: test for relaxed DeleteCircuits
Modify unit tests to expect success when removing
already-deleted circuits, as well as test that extra
circuit deletions are ignored.
|
lightningnetwork_lnd
|
train
|
b5d2b806550583dd342eb4c641b1edcc511e0475
|
diff --git a/spec/stoplight/light_spec.rb b/spec/stoplight/light_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/stoplight/light_spec.rb
+++ b/spec/stoplight/light_spec.rb
@@ -6,7 +6,7 @@ require 'spec_helper'
describe Stoplight::Light do
before do
@notifiers = Stoplight.notifiers
- Stoplight.notifiers = []
+ Stoplight.notifiers = [Stoplight::Notifier::IO.new(StringIO.new)]
end
after { Stoplight.notifiers = @notifiers }
|
Configure IO notifier in tests
This would prevent stuff like 9a0b<I>e1a6d<I>c4d<I>eb1ff<I>f<I>b<I>f.
|
orgsync_stoplight
|
train
|
83e6cf2f822cac2bd64cdfd52c42828d396331ee
|
diff --git a/blocks/admin_tree/block_admin_tree.php b/blocks/admin_tree/block_admin_tree.php
index <HASH>..<HASH> 100644
--- a/blocks/admin_tree/block_admin_tree.php
+++ b/blocks/admin_tree/block_admin_tree.php
@@ -37,7 +37,7 @@ class block_admin_tree extends block_base {
global $CFG;
$strfolderopened = s(get_string('folderopened'));
- $this->tempcontent .= '<div class="depth'.$this->currentdepth.'"><a href="#" onclick="toggle(\''.$this->divcounter.'\');return false">';
+ $this->tempcontent .= '<div class="depth'.$this->currentdepth.'"><a href="#" onclick="menu_toggle(\''.$this->divcounter.'\');return false">';
$this->tempcontent .= '<span id="vh_div'.$this->divcounter.'indicator"><img src="'.$CFG->pixpath.'/i/open.gif" alt="'.$strfolderopened.'" /></span> ';
$this->tempcontent .= $visiblename.'</a></div><div id="vh_div'.$this->divcounter.'">'."\n";
$this->currentdepth++;
@@ -145,7 +145,7 @@ for (var i=1; i<=vh_numdivs; i++) {
parkplatz[i] = null;
}
-function toggle(i) {
+function menu_toggle(i) {
i = parseInt(i);
if (parkplatz[i] === null) {
collapse(i);
|
"MDL-<I>, change js function name toggle() to menu_toggle(), to be friendly with prototype.js, merged from MOODLE_<I>_STABLE"
|
moodle_moodle
|
train
|
03f5efc4dc6ce01861f84be96ca48bc33e075174
|
diff --git a/openquake/baselib/hdf5.py b/openquake/baselib/hdf5.py
index <HASH>..<HASH> 100644
--- a/openquake/baselib/hdf5.py
+++ b/openquake/baselib/hdf5.py
@@ -173,13 +173,17 @@ class PickleableSequence(collections.Sequence):
return repr(self._objects)
def __toh5__(self):
- dic = {
- '%06d' % i: numpy.array(pickle.dumps(obj, pickle.HIGHEST_PROTOCOL))
- for i, obj in enumerate(self._objects)}
- return dic, {}
+ dic = {}
+ nbytes = 0
+ for i, obj in enumerate(self._objects):
+ pik = pickle.dumps(obj, pickle.HIGHEST_PROTOCOL)
+ dic['%06d' % i] = numpy.array(pik)
+ nbytes += len(pik)
+ return dic, dict(nbytes=nbytes)
def __fromh5__(self, dic, attrs):
self._objects = tuple(pickle.loads(dic[k].value) for k in sorted(dic))
+ vars(self).update(attrs)
class File(h5py.File):
|
Stored the number of bytes used
|
gem_oq-engine
|
train
|
bbe5bad5759e438877ffb111949a5e62063cff51
|
diff --git a/mod/scorm/report/interactions/report.php b/mod/scorm/report/interactions/report.php
index <HASH>..<HASH> 100644
--- a/mod/scorm/report/interactions/report.php
+++ b/mod/scorm/report/interactions/report.php
@@ -153,7 +153,7 @@ class scorm_interactions_report extends scorm_default_report {
}
$params = array();
- list($usql, $params) = $DB->get_in_or_equal($allowedlist);
+ list($usql, $params) = $DB->get_in_or_equal($allowedlist, SQL_PARAMS_NAMED);
// Construct the SQL
$select = 'SELECT DISTINCT '.$DB->sql_concat('u.id', '\'#\'', 'COALESCE(st.attempt, 0)').' AS uniqueid, ';
$select .= 'st.scormid AS scormid, st.attempt AS attempt, ' .
|
MDL-<I> SCORM Fixing Sql errors in interraction reporting
|
moodle_moodle
|
train
|
340e58be31567f7c93b27cba22ca1c7cb49f5dce
|
diff --git a/structr-db-driver-api/src/main/java/org/structr/api/config/Settings.java b/structr-db-driver-api/src/main/java/org/structr/api/config/Settings.java
index <HASH>..<HASH> 100644
--- a/structr-db-driver-api/src/main/java/org/structr/api/config/Settings.java
+++ b/structr-db-driver-api/src/main/java/org/structr/api/config/Settings.java
@@ -99,7 +99,7 @@ public class Settings {
public static final Setting<Integer> SshPort = new IntegerSetting(serverGroup, "Interfaces", "application.ssh.port", 8022, "SSH port the Structr server will listen on (if SSHService is enabled)");
public static final Setting<Integer> FtpPort = new IntegerSetting(serverGroup, "Interfaces", "application.ftp.port", 8021, "FTP port the Structr server will listen on (if FtpService is enabled)");
public static final Setting<Boolean> HttpsEnabled = new BooleanSetting(serverGroup, "Interfaces", "application.https.enabled", false, "Whether SSL is enabled");
- public static final Setting<String> KeystorePath = new StringSetting(serverGroup, "Interfaces", "application.keystore.path", "", "The path to the JKS keystore containing the SSL certificate");
+ public static final Setting<String> KeystorePath = new StringSetting(serverGroup, "Interfaces", "application.keystore.path", "domain.key.keystore", "The path to the JKS keystore containing the SSL certificate. Default value is 'domain.key.keystore' which fits with the default value for letsencrypt.domain.key.filename which is 'domain.key'.");
public static final Setting<String> KeystorePassword = new StringSetting(serverGroup, "Interfaces", "application.keystore.password", "", "The password for the JKS keystore");
public static final Setting<String> RestPath = new StringSetting(serverGroup, "hidden", "application.rest.path", "/structr/rest", "Defines the URL path of the Structr REST server. Should not be changed because it is hard-coded in many parts of the application.");
public static final Setting<String> BaseUrlOverride = new StringSetting(serverGroup, "Interfaces", "application.baseurl.override", "", "Overrides the baseUrl that can be used to prefix links to local web resources. By default, the value is assembled from the protocol, hostname and port of the server instance Structr is running on");
|
Enhancement: Sets default value for 'application.keystore.path' to 'domain.key.keystore' so it fits the default value of letsencrypt.domain.key.filename which is 'domain.key'.
|
structr_structr
|
train
|
eb4c6b3e88883c1625c1b0df4b058c117c8634f3
|
diff --git a/lib/trouble.rb b/lib/trouble.rb
index <HASH>..<HASH> 100644
--- a/lib/trouble.rb
+++ b/lib/trouble.rb
@@ -19,7 +19,26 @@ module Trouble
#
def self.notify(exception, metadata = nil)
exception.set_backtrace(caller) unless exception.backtrace
- notify! exception, metadata
+ notify_error_service(exception, metadata)
+ log_in_logger(exception, metadata)
+ increment_metric
+ end
+
+ # Public: Log the error in the logger and track as metric.
+ #
+ # exception - An instance of an Exception
+ # metadata - An Hash with arbitrary additional information (optional)
+ #
+ # Examples
+ #
+ # Trouble.log RuntimeError.new
+ # Trouble.log RuntimeError.new, some_idea_why_it_happened: "I don't know, but try this and that."
+ #
+ # Returns nothing.
+ #
+ def self.log(exception, metadata = nil)
+ exception.set_backtrace(caller) unless exception.backtrace
+ log_in_logger(exception, metadata)
increment_metric
end
@@ -27,11 +46,8 @@ module Trouble
# Internal: Dispatch the Exception to the backend(s).
#
- def self.notify!(exception, metadata)
- log(exception, metadata) if config.logger
- if metadata.fetch(:notify_error_service, true)
- Bugsnag.notify(exception, metadata) if defined?(Bugsnag)
- end
+ def self.notify_error_service(exception, metadata)
+ Bugsnag.notify(exception, metadata) if defined?(Bugsnag)
end
# Internal: track exceptions metric
@@ -42,8 +58,8 @@ module Trouble
# Internal: Log to the current Logger.
#
- def self.log(exception, metadata)
- config.logger.error "TROUBLE NOTIFICATION #{exception.inspect} at #{exception.backtrace.first} with metadata #{metadata.inspect}"
+ def self.log_in_logger(exception, metadata)
+ config.logger.error("TROUBLE NOTIFICATION #{exception.inspect} at #{exception.backtrace.first} with metadata #{metadata.inspect}") if config.logger
end
end
diff --git a/spec/lib/trouble_spec.rb b/spec/lib/trouble_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lib/trouble_spec.rb
+++ b/spec/lib/trouble_spec.rb
@@ -42,25 +42,25 @@ describe Trouble do
Bugsnag.should_receive(:notify).with(exception, metadata)
trouble.notify exception, metadata
end
+ end
+ end
- context 'with { notify_error_service: false } in the metadata' do
+ describe '.log' do
- it 'does not notify the error service' do
- Bugsnag.should_not_receive(:notify)
- trouble.notify exception, metadata.merge(notify_error_service: false)
- end
+ it 'does not notify the error service' do
+ Bugsnag.should_not_receive(:notify)
+ trouble.log exception, metadata.merge(notify_error_service: false)
+ end
- it 'increments the metric' do
- trouble.should_receive(:increment_metric)
- trouble.notify exception, metadata.merge(notify_error_service: false)
- end
+ it 'increments the metric' do
+ trouble.should_receive(:increment_metric)
+ trouble.log exception, metadata.merge(notify_error_service: false)
+ end
- it 'logs with the configured logger' do
- trouble.config.logger = logger
- trouble.config.logger.should_receive(:error)
- trouble.notify exception, metadata.merge(notify_error_service: false)
- end
- end
+ it 'logs with the configured logger' do
+ trouble.config.logger = logger
+ trouble.config.logger.should_receive(:error)
+ trouble.log exception, metadata.merge(notify_error_service: false)
end
end
|
Separate log method for just logging and metric #2
|
bukowskis_trouble
|
train
|
d464f090d2b1f7cee06c4d451778a11c10e8bbfe
|
diff --git a/util/files.js b/util/files.js
index <HASH>..<HASH> 100644
--- a/util/files.js
+++ b/util/files.js
@@ -15,7 +15,7 @@ module.exports = function (files) {
var toProcess = '';
if (files instanceof Array) {
files.forEach(function (f) {
- toProcess += '"' + f + '" ';
+ toProcess += '"' + f.replace(/\^/g, '^^').replace(/\&/g, '^&').replace(/\\/g, '^\\').replace(/\</g, '^<').replace(/\>/g, '^>').replace(/\|/g, '^|')/.replace(/\%/g, '%%') + '" ';
});
toProcess = toProcess.trim();
} else {
|
Escaping special characters in file/folder paths
|
quentinrossetti_node-7z
|
train
|
fa094cd3ec3491dfa1bedfadcdaa2f29853e875a
|
diff --git a/modules/@apostrophecms/area/index.js b/modules/@apostrophecms/area/index.js
index <HASH>..<HASH> 100644
--- a/modules/@apostrophecms/area/index.js
+++ b/modules/@apostrophecms/area/index.js
@@ -211,6 +211,7 @@ module.exports = {
});
deep(doc, `${path}._rendered`, areaRendered);
+ deep(doc, `${path}._fieldId`, undefined);
deep(doc, `${path}.items`, undefined);
}
},
diff --git a/modules/@apostrophecms/piece-type/index.js b/modules/@apostrophecms/piece-type/index.js
index <HASH>..<HASH> 100644
--- a/modules/@apostrophecms/piece-type/index.js
+++ b/modules/@apostrophecms/piece-type/index.js
@@ -172,7 +172,7 @@ module.exports = {
result.currentPage = query.get('page') || 1;
result.results = await query.toArray();
if (self.apos.launder.boolean(req.query.renderareas) === true) {
- self.apos.area.renderDocsAreas(req, result.results);
+ await self.apos.area.renderDocsAreas(req, result.results);
}
self.apos.attachment.all(result.results, { annotate: true });
if (query.get('choicesResults')) {
|
Awaits method and removes unecessary property
|
apostrophecms_apostrophe
|
train
|
d2a824e4b66f15141dba117d0921789341b6a828
|
diff --git a/tfatool/_version.py b/tfatool/_version.py
index <HASH>..<HASH> 100644
--- a/tfatool/_version.py
+++ b/tfatool/_version.py
@@ -1,2 +1,2 @@
-__version__ = "v2.2.2"
+__version__ = "v2.2.3"
|
merging in bugfix branch. This fixes issue #7.
|
TadLeonard_tfatool
|
train
|
2687b69a16bd7fa8b4d311df532a7738f2b7bf40
|
diff --git a/lib/origen/pins/pin_collection.rb b/lib/origen/pins/pin_collection.rb
index <HASH>..<HASH> 100755
--- a/lib/origen/pins/pin_collection.rb
+++ b/lib/origen/pins/pin_collection.rb
@@ -8,6 +8,7 @@ module Origen
attr_accessor :endian
attr_accessor :description
+ attr_accessor :group
def initialize(owner, *pins)
options = pins.last.is_a?(Hash) ? pins.pop : {}
@@ -195,9 +196,7 @@ module Origen
else
pin = owner.pins(pin)
end
- if @store.include?(pin)
- fail "Pin collection #{id} already contains pin #{pin.id}!"
- else
+ unless @store.include?(pin)
pin.invalidate_group_cache
@store.push(pin)
end
|
Added group reference so that the pin collection can match bus reference and took out unneeded fail statement.
|
Origen-SDK_origen
|
train
|
fa10849c4063391f2be4c61c32bd9cc82f3ddb57
|
diff --git a/format.go b/format.go
index <HASH>..<HASH> 100644
--- a/format.go
+++ b/format.go
@@ -237,8 +237,8 @@ func NewStringFormatter(format string) (Formatter, error) {
Id: 12345,
Time: t,
Module: "logger",
+ Args: []interface{}{"go"},
fmt: "hello %s",
- args: []interface{}{"go"},
}
if err := fmter.Format(0, r, &bytes.Buffer{}); err != nil {
return nil, err
diff --git a/logger.go b/logger.go
index <HASH>..<HASH> 100644
--- a/logger.go
+++ b/logger.go
@@ -45,11 +45,11 @@ type Record struct {
Time time.Time
Module string
Level Level
+ Args []interface{}
// message is kept as a pointer to have shallow copies update this once
// needed.
message *string
- args []interface{}
fmt string
formatter Formatter
formatted string
@@ -69,12 +69,12 @@ func (r *Record) Formatted(calldepth int) string {
func (r *Record) Message() string {
if r.message == nil {
// Redact the arguments that implements the Redactor interface
- for i, arg := range r.args {
+ for i, arg := range r.Args {
if redactor, ok := arg.(Redactor); ok == true {
- r.args[i] = redactor.Redacted()
+ r.Args[i] = redactor.Redacted()
}
}
- msg := fmt.Sprintf(r.fmt, r.args...)
+ msg := fmt.Sprintf(r.fmt, r.Args...)
r.message = &msg
}
return *r.message
@@ -144,7 +144,7 @@ func (l *Logger) log(lvl Level, format string, args ...interface{}) {
Module: l.Module,
Level: lvl,
fmt: format,
- args: args,
+ Args: args,
}
// TODO use channels to fan out the records to all backends?
|
Make Record.Args public so can be accessed by backends
|
ckeyer_go-log
|
train
|
0237f372bbce904801510bdb977788f3b5216ee0
|
diff --git a/ui/admin/media_button.php b/ui/admin/media_button.php
index <HASH>..<HASH> 100644
--- a/ui/admin/media_button.php
+++ b/ui/admin/media_button.php
@@ -6,11 +6,15 @@
/**
* Add a button to the media buttons context
*/
+
+$current_page = basename($_SERVER['PHP_SELF']);
+
function pods_media_button($context) {
$button = '<a href="#TB_inline?inlineId=pods_shortcode_form&width=640" class="thickbox" id="add_pod_button"><img src="' . PODS_URL . 'ui/images/icon16.png" alt="Add Pod" /></a>';
$context .= $button;
return $context;
}
+
add_filter('media_buttons_context', 'pods_media_button');
/**
@@ -112,6 +116,7 @@ function add_pods_mce_popup() {
<?php
require_once PODS_DIR . 'ui/admin/pods_shortcode_form.php';
}
-add_action('admin_footer', 'add_pods_mce_popup');
+if (in_array($current_page, array('post.php', 'page.php', 'page-new.php', 'post-new.php')))
+ add_action('admin_footer', 'add_pods_mce_popup');
?>
|
Restricted shortcode form to only show up on post/page pages
|
pods-framework_pods
|
train
|
926071e07e0c5da441d9b9615a1a140fab268827
|
diff --git a/lib/appsignal/version.rb b/lib/appsignal/version.rb
index <HASH>..<HASH> 100644
--- a/lib/appsignal/version.rb
+++ b/lib/appsignal/version.rb
@@ -1,5 +1,5 @@
require 'yaml'
module Appsignal
- VERSION = '1.2.0.alpha.4'
+ VERSION = '1.2.0.alpha.5'
end
|
Bump to <I>.alpha<I> [ci skip]
|
appsignal_appsignal-ruby
|
train
|
7de291d0a99fb687d5a61ab689c53aa5af91c623
|
diff --git a/js/bootstrap-select.js b/js/bootstrap-select.js
index <HASH>..<HASH> 100644
--- a/js/bootstrap-select.js
+++ b/js/bootstrap-select.js
@@ -1815,6 +1815,7 @@
text.className = 'text';
a.className = 'dropdown-item ' + (firstOption ? firstOption.className : '');
newElement.className = this.$menu[0].parentNode.className + ' ' + classNames.SHOW;
+ newElement.style.width = 0; // ensure button width doesn't affect natural width of menu when calculating
if (this.options.width === 'auto') menu.style.minWidth = 0;
menu.className = classNames.MENU + ' ' + classNames.SHOW;
menuInner.className = 'inner ' + classNames.SHOW;
|
set width of newElement when calculating menu size (fixes issue introduced in <I> when select has form-control class)
|
snapappointments_bootstrap-select
|
train
|
bf4ed5ec6d6a209a08fbd40c7a1aa5e4aff09ad6
|
diff --git a/src/VersionParser.php b/src/VersionParser.php
index <HASH>..<HASH> 100644
--- a/src/VersionParser.php
+++ b/src/VersionParser.php
@@ -178,7 +178,7 @@ class VersionParser
*/
public function parseNumericAliasPrefix($branch)
{
- if (preg_match('/^(?<version>(\d+\\.)*\d+)(?:\.x)?-dev$/i', $branch, $matches)) {
+ if (preg_match('/^(?P<version>(\d+\\.)*\d+)(?:\.x)?-dev$/i', $branch, $matches)) {
return $matches['version'].".";
}
|
Add the P character to the regex pattern
According to <URL>: Compilation failed: unrecognized character after (?< at offset 4
Exception trace:
() at phar:///var/www/git/smmqa/app/admin/composer.phar/src/Composer/Package/Version/VersionParser.php:<I>
|
composer_semver
|
train
|
ca447f22fb6ac563365d3effce33e57e71aedf08
|
diff --git a/lib/json_translate/translates/instance_methods.rb b/lib/json_translate/translates/instance_methods.rb
index <HASH>..<HASH> 100644
--- a/lib/json_translate/translates/instance_methods.rb
+++ b/lib/json_translate/translates/instance_methods.rb
@@ -14,25 +14,18 @@ module JSONTranslate
attr_reader :enabled_fallback
def json_translate_fallback_locales(locale)
- return if enabled_fallback == false || !I18n.respond_to?(:fallbacks)
+ return locale if enabled_fallback == false || !I18n.respond_to?(:fallbacks)
I18n.fallbacks[locale]
end
def read_json_translation(attr_name, locale = I18n.locale)
translations = public_send("#{attr_name}#{SUFFIX}") || {}
- translation = translations[locale.to_s]
-
- if fallback_locales = json_translate_fallback_locales(locale)
- fallback_locales.each do |fallback_locale|
- t = translations[fallback_locale.to_s]
- if t.present?
- translation = t
- break
- end
- end
+
+ available = Array(json_translate_fallback_locales(locale)).detect do |available_locale|
+ translations[available_locale.to_s].present?
end
- translation
+ translations[available.to_s]
end
def write_json_translation(attr_name, value, locale = I18n.locale)
|
Refactor read_json_translation
|
cfabianski_json_translate
|
train
|
cb0d14d597da4e8831601a34fee61b34391b63c4
|
diff --git a/app/controllers/admin/categories_controller.rb b/app/controllers/admin/categories_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/admin/categories_controller.rb
+++ b/app/controllers/admin/categories_controller.rb
@@ -18,7 +18,7 @@ class Admin::CategoriesController < Admin::BaseController
if request.post? and @category.save
flash[:notice] = 'Category was successfully created.'
- redirect_to :action => 'show', :id => @category.id
+ redirect_to :action => 'list'
end
end
@@ -27,7 +27,7 @@ class Admin::CategoriesController < Admin::BaseController
@category.attributes = params[:category]
if request.post? and @category.save
flash[:notice] = 'Category was successfully updated.'
- redirect_to :action => 'show', :id => @category.id
+ redirect_to :action => 'list'
end
end
|
after creating a category you are taken back to the category listing instead of the detail view (robbyonrails)
git-svn-id: <URL>
|
publify_publify
|
train
|
ba9e1a65e0f7975f055d50a2c0201c50d941c24c
|
diff --git a/panicwrap.go b/panicwrap.go
index <HASH>..<HASH> 100644
--- a/panicwrap.go
+++ b/panicwrap.go
@@ -68,6 +68,13 @@ type WrapConfig struct {
// Catch and igore these signals in the parent process, let the child
// handle them gracefully.
IgnoreSignals []os.Signal
+
+ // Catch these signals in the parent process and manually forward
+ // them to the child process. Some signals such as SIGINT are usually
+ // sent to the entire process group so setting it isn't necessary. Other
+ // signals like SIGTERM are only sent to the parent process and need
+ // to be forwarded. This defaults to empty.
+ ForwardSignals []os.Signal
}
// BasicWrap calls Wrap with the given handler function, using defaults
@@ -166,16 +173,23 @@ func Wrap(c *WrapConfig) (int, error) {
// Listen to signals and capture them forever. We allow the child
// process to handle them in some way.
sigCh := make(chan os.Signal)
+ fwdSigCh := make(chan os.Signal)
if len(c.IgnoreSignals) == 0 {
c.IgnoreSignals = []os.Signal{os.Interrupt}
}
signal.Notify(sigCh, c.IgnoreSignals...)
+ signal.Notify(sigCh, c.ForwardSignals...)
go func() {
defer signal.Stop(sigCh)
+ defer signal.Stop(fwdSigCh)
for {
select {
case <-doneCh:
return
+ case s := <-fwdSigCh:
+ if cmd.Process != nil {
+ cmd.Process.Signal(s)
+ }
case <-sigCh:
}
}
|
allow specifying signals to forward to the child process
|
mitchellh_panicwrap
|
train
|
7eb1df15d722929f118e210af05cb34b849f8046
|
diff --git a/safe/report/processors/default.py b/safe/report/processors/default.py
index <HASH>..<HASH> 100644
--- a/safe/report/processors/default.py
+++ b/safe/report/processors/default.py
@@ -27,7 +27,8 @@ from qgis.core import (
QgsLegendRenderer,
QgsComposerLegendStyle,
QgsComposerMap,
- QgsComposerLegend
+ QgsComposerLegend,
+ QgsCoordinateTransform
)
from safe.common.exceptions import TemplateLoadingError
@@ -394,6 +395,10 @@ def qgis_composer_renderer(impact_report, component):
qurl = QUrl.fromLocalFile(url)
html_element.setUrl(qurl)
+ original_crs = impact_report.impact_function.impact.crs()
+ destination_crs = qgis_composition_context.map_settings.destinationCrs()
+ coord_transform = QgsCoordinateTransform(original_crs, destination_crs)
+
# resize map extent
for map_el in context.map_elements:
item_id = map_el.get('id')
@@ -409,7 +414,7 @@ def qgis_composer_renderer(impact_report, component):
if map_extent_option and isinstance(
map_extent_option, QgsRectangle):
# use provided map extent
- extent = map_extent_option
+ extent = coord_transform.transform(map_extent_option)
else:
# if map extent not provided, try to calculate extent
# from list of given layers. Combine it so all layers were
@@ -418,7 +423,8 @@ def qgis_composer_renderer(impact_report, component):
extent.setMinimal()
for l in layers:
# combine extent if different layer is provided.
- extent.combineExtentWith(l.extent())
+ layer_extent = coord_transform.transform(l.extent())
+ extent.combineExtentWith(layer_extent)
width = extent.width()
height = extent.height()
|
transform extent's crs to mapcomposer crs (#<I>)
|
inasafe_inasafe
|
train
|
470f415fb4a17c200f109c464f709e236147a339
|
diff --git a/airflow/configuration.py b/airflow/configuration.py
index <HASH>..<HASH> 100644
--- a/airflow/configuration.py
+++ b/airflow/configuration.py
@@ -139,6 +139,7 @@ class AirflowConfigParser(ConfigParser):
'celery': {
# Remove these keys in Airflow 1.11
'worker_concurrency': 'celeryd_concurrency',
+ 'result_backend': 'celery_result_backend',
'broker_url': 'celery_broker_url',
'ssl_active': 'celery_ssl_active',
'ssl_cert': 'celery_ssl_cert',
|
[AIRFLOW-<I>] Make celery_result_backend conf Backwards compatible (#<I>)
(#<I>) Renamed `celery_result_backend` to `result_backend` and broke backwards compatibility.
|
apache_airflow
|
train
|
997c650c1c43139847b4e82871925ed31db514ef
|
diff --git a/src/Symfony/Component/DomCrawler/Crawler.php b/src/Symfony/Component/DomCrawler/Crawler.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/DomCrawler/Crawler.php
+++ b/src/Symfony/Component/DomCrawler/Crawler.php
@@ -66,7 +66,7 @@ class Crawler extends \SplObjectStorage
*/
public function clear()
{
- $this->removeAll($this);
+ parent::removeAll($this);
}
/**
@@ -319,9 +319,9 @@ class Crawler extends \SplObjectStorage
public function addNode(\DOMNode $node)
{
if ($node instanceof \DOMDocument) {
- $this->attach($node->documentElement);
+ parent::attach($node->documentElement);
} else {
- $this->attach($node);
+ parent::attach($node);
}
}
@@ -877,6 +877,136 @@ class Crawler extends \SplObjectStorage
}
/**
+ * @deprecated Using the SplObjectStorage API on the Crawler is deprecated as of 2.8 and will be removed in 3.0.
+ */
+ public function attach($object, $data = null)
+ {
+ @trigger_error('The '.__METHOD__.' method is deprecated as of 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
+
+ parent::attach($object, $data);
+ }
+
+ /**
+ * @deprecated Using the SplObjectStorage API on the Crawler is deprecated as of 2.8 and will be removed in 3.0.
+ */
+ public function detach($object)
+ {
+ @trigger_error('The '.__METHOD__.' method is deprecated as of 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
+
+ parent::detach($object);
+ }
+
+ /**
+ * @deprecated Using the SplObjectStorage API on the Crawler is deprecated as of 2.8 and will be removed in 3.0.
+ */
+ public function contains($object)
+ {
+ @trigger_error('The '.__METHOD__.' method is deprecated as of 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
+
+ return parent::contains($object);
+ }
+
+ /**
+ * @deprecated Using the SplObjectStorage API on the Crawler is deprecated as of 2.8 and will be removed in 3.0.
+ */
+ public function addAll($storage)
+ {
+ @trigger_error('The '.__METHOD__.' method is deprecated as of 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
+
+ parent::addAll($storage);
+ }
+
+ /**
+ * @deprecated Using the SplObjectStorage API on the Crawler is deprecated as of 2.8 and will be removed in 3.0.
+ */
+ public function removeAll($storage)
+ {
+ @trigger_error('The '.__METHOD__.' method is deprecated as of 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
+
+ parent::removeAll($storage);
+ }
+
+ /**
+ * @deprecated Using the SplObjectStorage API on the Crawler is deprecated as of 2.8 and will be removed in 3.0.
+ */
+ public function removeAllExcept($storage)
+ {
+ @trigger_error('The '.__METHOD__.' method is deprecated as of 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
+
+ parent::removeAllExcept($storage);
+ }
+
+ /**
+ * @deprecated Using the SplObjectStorage API on the Crawler is deprecated as of 2.8 and will be removed in 3.0.
+ */
+ public function getInfo()
+ {
+ @trigger_error('The '.__METHOD__.' method is deprecated as of 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
+
+ return parent::getInfo();
+ }
+
+ /**
+ * @deprecated Using the SplObjectStorage API on the Crawler is deprecated as of 2.8 and will be removed in 3.0.
+ */
+ public function setInfo($data)
+ {
+ @trigger_error('The '.__METHOD__.' method is deprecated as of 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
+
+ parent::setInfo($data);
+ }
+
+ /**
+ * @deprecated Using the SplObjectStorage API on the Crawler is deprecated as of 2.8 and will be removed in 3.0.
+ */
+ public function offsetExists($object)
+ {
+ @trigger_error('The '.__METHOD__.' method is deprecated as of 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
+
+ return parent::offsetExists($object);
+ }
+
+ /**
+ * @deprecated Using the SplObjectStorage API on the Crawler is deprecated as of 2.8 and will be removed in 3.0.
+ */
+ public function offsetSet($object, $data = null)
+ {
+ @trigger_error('The '.__METHOD__.' method is deprecated as of 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
+
+ parent::offsetSet($object, $data);
+ }
+
+ /**
+ * @deprecated Using the SplObjectStorage API on the Crawler is deprecated as of 2.8 and will be removed in 3.0.
+ */
+ public function offsetUnset($object)
+ {
+ @trigger_error('The '.__METHOD__.' method is deprecated as of 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
+
+ parent::offsetUnset($object);
+ }
+
+ /**
+ * @deprecated Using the SplObjectStorage API on the Crawler is deprecated as of 2.8 and will be removed in 3.0.
+ */
+ public function offsetGet($object)
+ {
+ @trigger_error('The '.__METHOD__.' method is deprecated as of 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
+
+ return parent::offsetGet($object);
+ }
+
+ /**
+ * @deprecated Using the SplObjectStorage API on the Crawler is deprecated as of 2.8 and will be removed in 3.0.
+ */
+ public function getHash($object)
+ {
+ // Cannot trigger a deprecation warning here because SplObjectStorage calls this method when attaching an object.
+
+ return parent::getHash($object);
+ }
+
+ /**
* Filters the list of nodes with an XPath expression.
*
* The XPath expression should already be processed to apply it in the context of each node.
|
Deprecate methods inherited from SplObjectStorage
|
symfony_symfony
|
train
|
5330328efec816491368256fa345769e6d426b25
|
diff --git a/tests/Asana/OAuthDispatcherTest.php b/tests/Asana/OAuthDispatcherTest.php
index <HASH>..<HASH> 100644
--- a/tests/Asana/OAuthDispatcherTest.php
+++ b/tests/Asana/OAuthDispatcherTest.php
@@ -18,7 +18,8 @@ class OAuthDispatcherTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
- $this->dispatcher = new FakeOAuthDispatcher(array());
+ $this->dispatcher = new FakeOAuthDispatcher(array(
+ 'client_id' => 'fake_client_id'));
}
/**
|
Fix more broken-ness travis catches but local build does not
|
Asana_php-asana
|
train
|
bfabb9ef0b22862966766d1bff8e30e15681b373
|
diff --git a/pysat/instruments/cosmic2013_gps.py b/pysat/instruments/cosmic2013_gps.py
index <HASH>..<HASH> 100644
--- a/pysat/instruments/cosmic2013_gps.py
+++ b/pysat/instruments/cosmic2013_gps.py
@@ -113,14 +113,14 @@ def load(cosmicFiles, tag=None, sat_id=None, altitude_bin=None):
for key in keys:
meta[key] = {'units':data.variables[key].units,
'long_name':data.variables[key].long_name}
- #ncattrsList = data.ncattrs()
+ # ncattrsList = data.ncattrs()
ncattrsList = data._attributes.keys()
for d in ncattrsList:
meta[d] = {'units':'', 'long_name':d}
repeat = False
except RuntimeError:
# file was empty, try the next one by incrementing ind
- ind+=1
+ ind += 1
return output, meta
else:
@@ -143,19 +143,23 @@ def load_files(files, tag=None, sat_id=None, altitude_bin=None):
for (i,file) in enumerate(files):
try:
#data = netCDF4.Dataset(file)
- data = netcdf_file(file, mode='r', mmap=False)
+ data = netcdf_file(file, mode='r', mmap=True)
# build up dictionary will all ncattrs
new = {}
# get list of file attributes
#ncattrsList = data.ncattrs()
ncattrsList = data._attributes.keys()
for d in ncattrsList:
- new[d] = data._attributes[d] #data.getncattr(d)
+ new[d] = data._attributes[d] #data.getncattr(d)
# load all of the variables in the netCDF
loadedVars={}
keys = data.variables.keys()
for key in keys:
- loadedVars[key] = data.variables[key][:]
+ if data.variables[key][:].dtype.byteorder != '=':
+ loadedVars[key] = data.variables[key][:].byteswap().newbyteorder().copy()
+ else:
+ loadedVars[key] = data.variables[key][:].copy()
+
new['profiles'] = pysat.DataFrame(loadedVars)
output[i] = new
|
fixed scipy netCDF routine endianness issue in cosmic loading routine
|
rstoneback_pysat
|
train
|
fe8f96e9981376e26984bfa4812916d14856dc05
|
diff --git a/osmnx/distance.py b/osmnx/distance.py
index <HASH>..<HASH> 100644
--- a/osmnx/distance.py
+++ b/osmnx/distance.py
@@ -169,6 +169,8 @@ def get_nearest_edge(G, point, return_geom=False, return_dist=False):
"""
Find the nearest edge to a point by minimum Euclidean distance.
+ For best results, both G and point should be projected.
+
Parameters
----------
G : networkx.MultiDiGraph
@@ -190,18 +192,16 @@ def get_nearest_edge(G, point, return_geom=False, return_dist=False):
Or a tuple of (u, v, key, dist) if return_dist is True.
Or a tuple of (u, v, key, geom, dist) if return_geom and return_dist are True.
"""
- # get u, v, key, geom from all the graph edges
- gdf_edges = utils_graph.graph_to_gdfs(G, nodes=False, fill_edge_geometry=True)
- edges = gdf_edges[["u", "v", "key", "geometry"]].values
-
# convert lat,lng (y,x) point to x,y for shapely distance operation
xy_point = Point(reversed(point))
# calculate euclidean distance from each edge's geometry to this point
- edge_distances = [(edge, xy_point.distance(edge[3])) for edge in edges]
+ gs_edges = utils_graph.graph_to_gdfs(G, nodes=False)["geometry"]
+ uvk_geoms = zip(gs_edges.index, gs_edges.values)
+ distances = ((uvk, geom, xy_point.distance(geom)) for uvk, geom in uvk_geoms)
# the nearest edge minimizes the distance to the point
- (u, v, key, geom), dist = min(edge_distances, key=lambda x: x[1])
+ (u, v, key), geom, dist = min(distances, key=lambda x: x[2])
utils.log(f"Found nearest edge ({u, v, key}) to point {point}")
# return results requested by caller
@@ -365,7 +365,7 @@ def get_nearest_edges(G, X, Y, method=None, dist=0.0001):
raise ImportError("The scipy package must be installed to use this optional feature.")
# transform graph into DataFrame
- edges = utils_graph.graph_to_gdfs(G, nodes=False, fill_edge_geometry=True)
+ edges = utils_graph.graph_to_gdfs(G, nodes=False).reset_index()
# transform edges into evenly spaced points
edges["points"] = edges.apply(
@@ -409,7 +409,7 @@ def get_nearest_edges(G, X, Y, method=None, dist=0.0001):
)
# transform graph into DataFrame
- edges = utils_graph.graph_to_gdfs(G, nodes=False, fill_edge_geometry=True)
+ edges = utils_graph.graph_to_gdfs(G, nodes=False).reset_index()
# transform edges into evenly spaced points
edges["points"] = edges.apply(
|
update get nearest edge function to accommodate new edges index structure
|
gboeing_osmnx
|
train
|
f4414bba32ea42c325c0ec0a1d23076e9d89fee7
|
diff --git a/src/org/datasift/PushDefinition.java b/src/org/datasift/PushDefinition.java
index <HASH>..<HASH> 100644
--- a/src/org/datasift/PushDefinition.java
+++ b/src/org/datasift/PushDefinition.java
@@ -54,7 +54,7 @@ public class PushDefinition implements Serializable {
*
* @param User user The user creating this object.
*/
- protected PushDefinition(User user) {
+ public PushDefinition(User user) {
_user = user;
}
|
PushDefinition constructor needs to be public.
|
datasift_datasift-java
|
train
|
477273a72bb19862588a4707ab0641acf4f0da71
|
diff --git a/lib/corser.js b/lib/corser.js
index <HASH>..<HASH> 100644
--- a/lib/corser.js
+++ b/lib/corser.js
@@ -133,7 +133,7 @@ exports.create = function (options) {
// Origin is not one of the simple request headers. Therefore, the header is
// accepted even if it is not in the list of request headers because CORS would
// not work without it.
- if (requestHeader.match(/origin/i)) {
+ if (requestHeader === "origin") {
return true;
} else {
if (options.requestHeaders.indexOf(requestHeader) !== -1) {
|
Remove redundant case-sensitive matching, requestHeader is already lowercase.
|
agrueneberg_Corser
|
train
|
855ba0abbfee4a4a01d80065adb4bef51e5fe856
|
diff --git a/state/watcher.go b/state/watcher.go
index <HASH>..<HASH> 100644
--- a/state/watcher.go
+++ b/state/watcher.go
@@ -700,6 +700,9 @@ func (w *MachineUnitsWatcher) mergeChange(changes *MachineUnitsChange, ch watche
doc := &unitDoc{}
if _, ok := w.knownUnits[name]; !ok {
err = w.st.units.FindId(name).One(doc)
+ if err == mgo.ErrNotFound {
+ return nil
+ }
if err != nil {
return err
}
@@ -725,7 +728,7 @@ func (changes *MachineUnitsChange) isEmpty() bool {
func (w *MachineUnitsWatcher) getInitialEvent() (initial *MachineUnitsChange, err error) {
changes := &MachineUnitsChange{}
docs := []unitDoc{}
- err = w.st.units.Find(D{{"machineid", w.machine.Id()}}).All(&docs)
+ err = w.st.units.Find(D{{"_id", D{{"$in", w.machine.doc.Principals}}}}).All(&docs)
if err != nil {
return nil, err
}
|
state: find units by known ids in the machine units watcher
|
juju_juju
|
train
|
dc19198e25d53a7b9d22160adcf5a048314f411e
|
diff --git a/steam/core/cm.py b/steam/core/cm.py
index <HASH>..<HASH> 100644
--- a/steam/core/cm.py
+++ b/steam/core/cm.py
@@ -85,10 +85,12 @@ class CMClient(EventEmitter):
self._recv_loop.kill()
self._init_attributes()
- self.emit('disconnected')
if reconnect:
+ self.emit('reconnect')
gevent.spawn(self.connect)
+ else:
+ self.emit('disconnected')
def _init_attributes(self):
self.current_server_addr = None
|
CMCLient: emit reconnect when about to reconnect
|
ValvePython_steam
|
train
|
327b861dd68b38cb6be31918541a25dac03a150b
|
diff --git a/src/lib/Supra/Remote/Server/RemoteCommandController.php b/src/lib/Supra/Remote/Server/RemoteCommandController.php
index <HASH>..<HASH> 100644
--- a/src/lib/Supra/Remote/Server/RemoteCommandController.php
+++ b/src/lib/Supra/Remote/Server/RemoteCommandController.php
@@ -133,6 +133,9 @@ class RemoteCommandController extends ControllerAbstraction
$remoteCommandResponse = new RemoteCommandResponse();
+ \Log::debug('Arguments: ' . $input->getArguments());
+ \Log::debug('Options : ' . $input->getOptions());
+
try {
$application = \Supra\Console\Application::getInstance();
@@ -145,7 +148,7 @@ class RemoteCommandController extends ControllerAbstraction
$remoteCommandResponse->setProxyOutput($output);
$remoteCommandResponse->setSuccess(true);
} catch (\Exception $e) {
-
+
$remoteCommandResponse->setError($e);
$remoteCommandResponse->setSuccess(false);
}
|
Issue red #<I>;
* Add more debug to remote command controller;
|
sitesupra_sitesupra
|
train
|
a72e4fda0bf7178272b2a30c1ec977a69577b072
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/paginated/wal/cas/OCASDiskWriteAheadLog.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/paginated/wal/cas/OCASDiskWriteAheadLog.java
index <HASH>..<HASH> 100755
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/paginated/wal/cas/OCASDiskWriteAheadLog.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/paginated/wal/cas/OCASDiskWriteAheadLog.java
@@ -912,7 +912,9 @@ public final class OCASDiskWriteAheadLog implements OWriteAheadLog {
} else {
result = readFromDisk(lsn, limit + 1);
}
-
+ if (result.isEmpty()) {
+ return result;
+ }
return result.subList(1, result.size());
} finally {
removeCutTillLimit(lsn);
|
fixed LSN lookup from the WAL for the case when there is no LSN
|
orientechnologies_orientdb
|
train
|
d0a0849a25015681a2f3f5b78d217aace5e0e46b
|
diff --git a/climlab/constants.py b/climlab/constants.py
index <HASH>..<HASH> 100644
--- a/climlab/constants.py
+++ b/climlab/constants.py
@@ -45,3 +45,5 @@ seconds_per_year = seconds_per_day * days_per_year
area_earth = 4 * np.math.pi * a**2
+# present-day orbital parameters, in the same format generated by orbital.py
+orb = {'ecc':0.017236, 'long_peri':281.37, 'obliquity':23.446}
\ No newline at end of file
|
Added present-day orbital parameters to constants.py
|
brian-rose_climlab
|
train
|
69cc48cb0f34576903a4f0cb095113d54d48314d
|
diff --git a/test/com/opera/core/systems/OperaFilePreferencesTest.java b/test/com/opera/core/systems/OperaFilePreferencesTest.java
index <HASH>..<HASH> 100644
--- a/test/com/opera/core/systems/OperaFilePreferencesTest.java
+++ b/test/com/opera/core/systems/OperaFilePreferencesTest.java
@@ -89,9 +89,10 @@ public class OperaFilePreferencesTest extends OperaDriverTestCase {
}
if (newDriver != null && newDriver.isRunning()) {
- if (newDriver.utils().getProduct().contains("core")) {
+ if (!newDriver.utils().getProduct().contains("desktop")) {
newDriver.preferences().resetAll();
}
+
newDriver.quit();
}
}
|
Actually, all products _apart_ from desktop does not support -pd
|
operasoftware_operaprestodriver
|
train
|
dfc59866e896122cbf80cbad858093a8f12d38f6
|
diff --git a/agent.go b/agent.go
index <HASH>..<HASH> 100644
--- a/agent.go
+++ b/agent.go
@@ -34,6 +34,9 @@ type Agent struct {
// Interval at which to flush data
FlushInterval Duration
+ // FlushRetries is the number of times to retry each data flush
+ FlushRetries int
+
// TODO(cam): Remove UTC and Precision parameters, they are no longer
// valid for the agent config. Leaving them here for now for backwards-
// compatability
@@ -61,6 +64,7 @@ func NewAgent(config *Config) (*Agent, error) {
Config: config,
Interval: Duration{10 * time.Second},
FlushInterval: Duration{10 * time.Second},
+ FlushRetries: 2,
UTC: true,
Precision: "s",
}
@@ -293,28 +297,56 @@ func (a *Agent) Test() error {
return nil
}
-func (a *Agent) flush(points []*client.Point) {
- var wg sync.WaitGroup
-
+// writeOutput writes a list of points to a single output, with retries
+func (a *Agent) writeOutput(
+ points []*client.Point,
+ ro *runningOutput,
+ shutdown chan struct{},
+) {
+ retry := 0
+ retries := a.FlushRetries
start := time.Now()
- counter := 0
- for _, o := range a.outputs {
- wg.Add(1)
- counter++
- go func(ro *runningOutput) {
- defer wg.Done()
- // Log all output errors:
- if err := ro.output.Write(points); err != nil {
- log.Printf("Error in output [%s]: %s", ro.name, err.Error())
+ for {
+ err := ro.output.Write(points)
+
+ select {
+ case <-shutdown:
+ return
+ default:
+ if err == nil {
+ // Write successful
+ elapsed := time.Since(start)
+ log.Printf("Flushed %d metrics to output %s in %s\n",
+ len(points), ro.name, elapsed)
+ return
+ } else if retry >= retries {
+ // No more retries
+ msg := "FATAL: Write to output [%s] failed %d times, dropping" +
+ " %d metrics\n"
+ log.Printf(msg, ro.name, retries+1, len(points))
+ return
+ } else if err != nil {
+ // Sleep for a retry
+ log.Printf("Error in output [%s]: %s, retrying in %s",
+ ro.name, err.Error(), a.FlushInterval.Duration)
+ time.Sleep(a.FlushInterval.Duration)
}
- }(o)
+ }
+
+ retry++
}
+}
- wg.Wait()
- elapsed := time.Since(start)
- log.Printf("Flushed %d metrics to %d output sinks in %s\n",
- len(points), counter, elapsed)
+// flush writes a list of points to all configured outputs
+func (a *Agent) flush(points []*client.Point, shutdown chan struct{}) {
+ if len(points) == 0 {
+ return
+ }
+
+ for _, o := range a.outputs {
+ go a.writeOutput(points, o, shutdown)
+ }
}
// flusher monitors the points input channel and flushes on the minimum interval
@@ -327,9 +359,11 @@ func (a *Agent) flusher(shutdown chan struct{}, pointChan chan *client.Point) er
for {
select {
case <-shutdown:
+ log.Println("Hang on, flushing any cached points before shutdown")
+ a.flush(points, shutdown)
return nil
case <-ticker.C:
- a.flush(points)
+ a.flush(points, shutdown)
points = make([]*client.Point, 0)
case pt := <-pointChan:
points = append(points, pt)
diff --git a/config.go b/config.go
index <HASH>..<HASH> 100644
--- a/config.go
+++ b/config.go
@@ -357,6 +357,8 @@ var header = `# Telegraf configuration
interval = "10s"
# Default data flushing interval for all outputs
flush_interval = "10s"
+ # Number of times to retry each data flush
+ flush_retries = 2
# run telegraf in debug mode
debug = false
# Override default hostname, if empty use os.Hostname()
diff --git a/etc/config.sample.toml b/etc/config.sample.toml
index <HASH>..<HASH> 100644
--- a/etc/config.sample.toml
+++ b/etc/config.sample.toml
@@ -27,17 +27,12 @@
[agent]
# Default data collection interval for all plugins
interval = "10s"
-
- # If utc = false, uses local time (utc is highly recommended)
- utc = true
-
- # Precision of writes, valid values are n, u, ms, s, m, and h
- # note: using second precision greatly helps InfluxDB compression
- precision = "s"
-
+ # Default data flushing interval for all outputs
+ flush_interval = "10s"
+ # Number of times to retry each data flush
+ flush_retries = 2
# run telegraf in debug mode
debug = false
-
# Override default hostname, if empty use os.Hostname()
hostname = ""
@@ -54,15 +49,16 @@
# Multiple urls can be specified for InfluxDB cluster support. Server to
# write to will be randomly chosen each interval.
urls = ["http://localhost:8086"] # required.
-
# The target database for metrics. This database must already exist
database = "telegraf" # required.
+ # Precision of writes, valid values are n, u, ms, s, m, and h
+ # note: using second precision greatly helps InfluxDB compression
+ precision = "s"
# Connection timeout (for the connection with InfluxDB), formatted as a string.
# Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
# If not provided, will default to 0 (no timeout)
# timeout = "5s"
-
# username = "telegraf"
# password = "metricsmetricsmetricsmetrics"
|
Add support for retrying output writes, using independent threads
Fixes #<I>
|
influxdata_telegraf
|
train
|
dd9eb9cc4641138faf3e50cd1e9425ef467a1b92
|
diff --git a/tests/vcr_config.py b/tests/vcr_config.py
index <HASH>..<HASH> 100644
--- a/tests/vcr_config.py
+++ b/tests/vcr_config.py
@@ -37,6 +37,9 @@ uber_vcr = vcr.VCR(
serializer='yaml',
cassette_library_dir='tests/fixtures',
+ # disable gzip
+ decode_compressed_response=True,
+
# you can record_mode='all' to force re-record all cassettes
record_mode='once',
|
Forced disabled gzip responses in fixtures
|
uber_rides-python-sdk
|
train
|
0bf48006870c6fa70076ad02c6b7b904a7b1f82a
|
diff --git a/TemplateMailer.js b/TemplateMailer.js
index <HASH>..<HASH> 100644
--- a/TemplateMailer.js
+++ b/TemplateMailer.js
@@ -7,7 +7,11 @@ let _template = require('lodash/template')
let _forEach = require('lodash/forEach')
let nodemailer = require('nodemailer')
let showdown = require('showdown')
-let converter = new showdown.Converter()
+let converter = new showdown.Converter({
+ simplifiedAutoLink: true,
+ strikethrough: true,
+ tables: true
+})
let formatContent = (data) => {
if (!(typeof data === 'object')) {
|
feat(Markdown): enable support for strike-through, auto-links and tables
|
ResourcefulHumans_template-mailer-aws-lambda
|
train
|
79067b600a67e4eae45c935b1f279d69878c99e2
|
diff --git a/src/v2/commands/setup.js b/src/v2/commands/setup.js
index <HASH>..<HASH> 100644
--- a/src/v2/commands/setup.js
+++ b/src/v2/commands/setup.js
@@ -47,13 +47,17 @@ const validators = {
}
};
+function getUserHome() {
+ return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
+}
+
function installModule(moduleName) {
if (_.endsWith(moduleName, '.yml')) {
return Promise.resolve();
}
- const usherExePath = path.parse(__filename);
- return exec(`npm install ${moduleName} --prefix ${usherExePath.dir}`);
+ const sharedTaskDir = `${getUserHome()}/.usher-cli/src/v2/commands`
+ return exec(`npm install ${moduleName} --prefix ${sharedTaskDir}`);
}
function requireTask(taskList, requireName) {
|
Using home directory for storing shared tasks
|
findmypast_usher
|
train
|
1cfef1cefbc3406c56cd4cf8a0fcc245ab04ea46
|
diff --git a/client-hc/src/test/java/com/graphhopper/api/GraphHopperWebIT.java b/client-hc/src/test/java/com/graphhopper/api/GraphHopperWebIT.java
index <HASH>..<HASH> 100644
--- a/client-hc/src/test/java/com/graphhopper/api/GraphHopperWebIT.java
+++ b/client-hc/src/test/java/com/graphhopper/api/GraphHopperWebIT.java
@@ -67,10 +67,10 @@ public class GraphHopperWebIT {
@Test
public void testAlternativeRoute() {
- // https://graphhopper.com/maps/?point=52.044124%2C10.378346&point=52.043847%2C10.381994&algorithm=alternative_route&ch.disable=true
+ // https://graphhopper.com/maps/?point=52.042989%2C10.373926&point=52.042289%2C10.384043&algorithm=alternative_route&ch.disable=true
GHRequest req = new GHRequest().
- addPoint(new GHPoint(52.044124,10.378346)).
- addPoint(new GHPoint(52.043847,10.381994));
+ addPoint(new GHPoint(52.042989, 10.373926)).
+ addPoint(new GHPoint(52.042289, 10.384043));
req.setAlgorithm("alternative_route");
req.getHints().put("instructions", true);
req.getHints().put("calc_points", true);
@@ -82,13 +82,13 @@ public class GraphHopperWebIT {
PathWrapper path = paths.get(0);
isBetween(5, 20, path.getPoints().size());
- isBetween(400, 500, path.getDistance());
+ isBetween(1000, 1100, path.getDistance());
assertEquals("Wiesenstraße", path.getDescription().get(0));
path = paths.get(1);
- isBetween(3, 15, path.getPoints().size());
- isBetween(350, 450, path.getDistance());
- assertEquals("Schlopweg", path.getDescription().get(0));
+ isBetween(20, 30, path.getPoints().size());
+ isBetween(800, 900, path.getDistance());
+ assertEquals("Jacobistraße", path.getDescription().get(0));
}
@Test
|
improve stability of client integration test regarding alternative route
|
graphhopper_graphhopper
|
train
|
44d01cff48578e5ea9083d10851649ebc700e461
|
diff --git a/snackbar/src/main/java/com/github/mrengineer13/snackbar/SnackBar.java b/snackbar/src/main/java/com/github/mrengineer13/snackbar/SnackBar.java
index <HASH>..<HASH> 100644
--- a/snackbar/src/main/java/com/github/mrengineer13/snackbar/SnackBar.java
+++ b/snackbar/src/main/java/com/github/mrengineer13/snackbar/SnackBar.java
@@ -87,6 +87,7 @@ public class SnackBar {
public interface OnVisibilityChangeListener {
void onShow(int stackSize);
+
void onHide(int stackSize);
}
@@ -164,11 +165,11 @@ public class SnackBar {
mHandler = new Handler();
}
- public static SnackBar create(Activity activity){
+ public static SnackBar create(Activity activity) {
return new SnackBar(activity);
}
- public static SnackBar create(Context context, View view){
+ public static SnackBar create(Context context, View view) {
return new SnackBar(context, view);
}
@@ -316,11 +317,6 @@ public class SnackBar {
return this;
}
- public SnackBar show(int message, short duration) {
- show(message, duration);
- return this;
- }
-
public SnackBar show(int message, int actionMessage, short duration) {
show(message, actionMessage, Style.DEFAULT, duration);
return this;
@@ -356,18 +352,23 @@ public class SnackBar {
int color = mContext.getResources().getColor(textColor);
String message = mContext.getString(messageResId);
String actionMessage = null;
- if(actionMessageResId > 0) {
+ if (actionMessageResId > 0) {
actionMessage = mContext.getString(actionMessageResId);
}
Snack m = new Snack(message, (actionMessage != null ? actionMessage.toUpperCase() : null),
actionIcon, token, duration, color);
+ if (isShowing()) {
+ mSnacks.push(m);
+ } else {
+ show(m);
+ }
return this;
}
public SnackBar show(int messageResId, int actionMessageResId, Style style, int actionIcon, Parcelable token, short duration) {
String message = mContext.getString(messageResId);
String actionMessage = null;
- if(actionMessageResId > 0) {
+ if (actionMessageResId > 0) {
actionMessage = mContext.getString(actionMessageResId);
}
Snack m = new Snack(message, (actionMessage != null ? actionMessage.toUpperCase() : null), actionIcon, token, duration, style);
@@ -390,7 +391,7 @@ public class SnackBar {
}
private ColorStateList getActionTextColor(Style style) {
- switch (style){
+ switch (style) {
case ALERT:
return mContext.getResources().getColorStateList(R.color.sb__button_text_color_red);
case INFO:
@@ -419,14 +420,13 @@ public class SnackBar {
mSnackMsg.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
mSnackBtn.setVisibility(View.VISIBLE);
mSnackBtn.setText(message.mActionMessage);
- //mSnackBtn.setTextColor(message.mBtnTextColor);
mSnackBtn.setCompoundDrawablesWithIntrinsicBounds(message.mActionIcon, 0, 0, 0);
} else {
mSnackMsg.setGravity(Gravity.CENTER);
mSnackBtn.setVisibility(View.GONE);
}
- if (message.mBtnTextColor > 0){
+ if (message.mBtnTextColor != 0) {
mSnackBtn.setTextColor(message.mBtnTextColor);
} else {
mSnackBtn.setTextColor(getActionTextColor(message.mStyle));
|
Fix Snack not showing when use of custom color.
|
MrEngineer13_SnackBar
|
train
|
f6f9d38482c24a6088542a02e7d30ed592741858
|
diff --git a/lib/IXF/ApiRequestor.php b/lib/IXF/ApiRequestor.php
index <HASH>..<HASH> 100644
--- a/lib/IXF/ApiRequestor.php
+++ b/lib/IXF/ApiRequestor.php
@@ -171,6 +171,9 @@ class ApiRequestor
$absUrl = self::utf8($absUrl);
$opts[CURLOPT_URL] = $absUrl;
+ if( IXF::getDebug() )
+ echo "\n{$absUrl}";
+
$opts[CURLOPT_RETURNTRANSFER] = true;
$opts[CURLOPT_CONNECTTIMEOUT] = 30;
$opts[CURLOPT_TIMEOUT] = 80;
diff --git a/lib/IXF/IXF.php b/lib/IXF/IXF.php
index <HASH>..<HASH> 100644
--- a/lib/IXF/IXF.php
+++ b/lib/IXF/IXF.php
@@ -35,6 +35,9 @@ abstract class IXF
*/
public static $verifySslCerts = true;
+
+ public static $debug = false;
+
const VERSION = '1.0.0';
/**
@@ -121,4 +124,14 @@ abstract class IXF
{
self::$apiBase = $apiBase;
}
+
+ public static getDebug()
+ {
+ return self::$debug;
+ }
+
+ public static setDebug( $d )
+ {
+ self::$debug = $d;
+ }
}
diff --git a/lib/IXF/Object.php b/lib/IXF/Object.php
index <HASH>..<HASH> 100644
--- a/lib/IXF/Object.php
+++ b/lib/IXF/Object.php
@@ -42,15 +42,6 @@ class Object implements \ArrayAccess
// Standard accessor magic methods
public function __set($k, $v)
{
- // IXF-FIXME
- if ($v === "") {
- throw new \InvalidArgumentException(
- 'You cannot set \''.$k.'\'to an empty string. '
- .'We interpret empty strings as NULL in requests. '
- .'You may set obj->'.$k.' = NULL to delete the property'
- );
- }
-
$this->_values[$k] = $v;
if (!self::$permanentAttributes->includes($k))
@@ -71,9 +62,12 @@ class Object implements \ArrayAccess
public function __get($k)
{
- if (array_key_exists($k, $this->_values)) {
+ if( array_key_exists( $k, $this->_values ) )
+ {
return $this->_values[$k];
- } elseif ($this->_transientValues->includes($k)) {
+ }
+ elseif( $this->_transientValues->includes($k) )
+ {
$class = get_class($this);
$attrs = join(', ', array_keys($this->_values));
// IXF-FIXME
@@ -200,28 +194,12 @@ class Object implements \ArrayAccess
return $params;
}
- // Pretend to have late static bindings, even in PHP 5.2
- protected function _lsb($method)
- {
- $class = get_class($this);
- $args = array_slice(func_get_args(), 1);
-
- return call_user_func_array(array($class, $method), $args);
- }
-
- protected static function _scopedLsb($class, $method)
- {
- $args = array_slice(func_get_args(), 2);
-
- return call_user_func_array(array($class, $method), $args);
- }
-
public function __toJSON()
{
if (defined('JSON_PRETTY_PRINT'))
- return json_encode($this->__toArray(true), JSON_PRETTY_PRINT);
+ return json_encode($this->__toArray(true), JSON_PRETTY_PRINT);
else
- return json_encode($this->__toArray(true));
+ return json_encode($this->__toArray(true));
}
public function __toString()
@@ -232,9 +210,9 @@ class Object implements \ArrayAccess
public function __toArray($recursive=false)
{
if ($recursive)
- return Util::convertIxfObjectToArray($this->_values);
+ return Util::convertIxfObjectToArray($this->_values);
else
- return $this->_values;
+ return $this->_values;
}
}
|
More sync fixes, cruft removal
|
euro-ix_ixf-client-php
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.