hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
d3d4f43f285902d969a2cfb2e8f4523c4937a299
diff --git a/__init__.py b/__init__.py index <HASH>..<HASH> 100644 --- a/__init__.py +++ b/__init__.py @@ -15,5 +15,5 @@ __revision__ = "$Id$" # Updated automatically by the Python release process. # #--start constants-- -__version__ = "3.2rc2" +__version__ = "3.2rc3" #--end constants--
Bump for <I>rc3.
pypa_setuptools
train
1ecebd540b05c8402d60fc724ddbab0198a2b2da
diff --git a/httprunner/loader.py b/httprunner/loader.py index <HASH>..<HASH> 100644 --- a/httprunner/loader.py +++ b/httprunner/loader.py @@ -416,7 +416,10 @@ def load_project_meta(test_path: Text, reload: bool = False) -> ProjectMeta: # environment variable maybe loaded in debugtalk.py # thus .env file should be loaded before loading debugtalk.py dot_env_path = os.path.join(project_working_directory, ".env") - project_meta.env = load_dot_env_file(dot_env_path) + dot_env = load_dot_env_file(dot_env_path) + if dot_env: + project_meta.env = dot_env + project_meta.dot_env_path = dot_env_path if debugtalk_path: # load debugtalk.py functions diff --git a/httprunner/make.py b/httprunner/make.py index <HASH>..<HASH> 100644 --- a/httprunner/make.py +++ b/httprunner/make.py @@ -1,6 +1,7 @@ import os import string import subprocess +from shutil import copyfile from typing import Text, List, Tuple, Dict, Set, NoReturn import jinja2 @@ -97,6 +98,28 @@ def __ensure_testcase_module(path: Text) -> NoReturn: f.write("# NOTICE: Generated By HttpRunner. DO NOT EDIT!\n") +def __ensure_project_meta_files(tests_path: Text) -> NoReturn: + """ ensure project meta files exist in generated pytest folder files + include debugtalk.py and .env + """ + project_meta = load_project_meta(tests_path) + + # handle cases when generated pytest directory are different from original yaml/json testcases + debugtalk_path = project_meta.debugtalk_path + if debugtalk_path: + debugtalk_new_path = ensure_file_path_valid(debugtalk_path) + if debugtalk_new_path != debugtalk_path: + logger.info(f"copy debugtalk.py to {debugtalk_new_path}") + copyfile(debugtalk_path, debugtalk_new_path) + + dot_csv_path = project_meta.dot_env_path + if dot_csv_path: + dot_csv_new_path = ensure_file_path_valid(dot_csv_path) + if dot_csv_new_path != dot_csv_path: + logger.info(f"copy .env to {dot_csv_new_path}") + copyfile(dot_csv_path, dot_csv_new_path) + + def ensure_file_path_valid(file_path: Text) -> Text: """ ensure file path valid for pytest @@ -108,12 +131,7 @@ def ensure_file_path_valid(file_path: Text) -> Text: """ raw_file_name, file_suffix = os.path.splitext(file_path) - file_suffix = file_suffix.lower() - if file_suffix not in [".json", ".yml", ".yaml", ".har"]: - raise exceptions.ParamsError( - "testcase/testsuite file should have .yaml/.yml/.json/.har suffix" - ) if os.path.isabs(file_path): raw_file_relative_name = raw_file_name[len(os.getcwd()) + 1 :] @@ -349,7 +367,8 @@ def make_testcase(testcase: Dict, dir_path: Text = None) -> Text: # ensure new file's directory exists dir_path = os.path.dirname(testcase_python_path) - os.makedirs(dir_path, exist_ok=True) + if not os.path.exists(dir_path): + os.makedirs(dir_path) with open(testcase_python_path, "w", encoding="utf-8") as f: f.write(content) @@ -479,6 +498,7 @@ def main_make(tests_paths: List[Text]) -> List[Text]: tests_path = os.path.join(os.getcwd(), tests_path) __make(tests_path) + __ensure_project_meta_files(tests_path) # format pytest files pytest_files_format_list = pytest_files_made_cache_mapping.keys() diff --git a/httprunner/models.py b/httprunner/models.py index <HASH>..<HASH> 100644 --- a/httprunner/models.py +++ b/httprunner/models.py @@ -82,6 +82,7 @@ class TestCase(BaseModel): class ProjectMeta(BaseModel): debugtalk_py: Text = "" # debugtalk.py file content debugtalk_path: Text = "" # debugtalk.py file path + dot_env_path: Text = "" # .env file path functions: FunctionsMapping = {} # functions defined in debugtalk.py env: Env = {} PWD: Text = os.getcwd() # project working directory, the path debugtalk.py located
fix: ensure project meta files exist in generated pytest folder files
HttpRunner_HttpRunner
train
ba6b8b58039a4591cd4781e2bb714799bdd19dfe
diff --git a/lib/puppet/provider/package/zypper.rb b/lib/puppet/provider/package/zypper.rb index <HASH>..<HASH> 100644 --- a/lib/puppet/provider/package/zypper.rb +++ b/lib/puppet/provider/package/zypper.rb @@ -10,7 +10,8 @@ Puppet::Type.type(:package).provide :zypper, :parent => :rpm do #on zypper versions <1.0, the version option returns 1 #some versions of zypper output on stderr def zypper_version - zypper "--version", { :failonfail => false, :combine => true} + cmd = [self.class.command(:zypper),"--version"] + execute(cmd, { :failonfail => false, :combine => true}) end # Install a package using 'zypper'.
(#<I>) Support zypper <I> with zypper package provider Replaced code that was erroneously assumed to be equivalent with a more verbose version that works on all Suse systems. Tested on: SLE <I>, <I>, <I> OpenSuSE <I>, <I>, <I>, <I>, <I>, <I>
puppetlabs_puppet
train
a181471f4eedad115211f2ada15b2ba55db3a801
diff --git a/theme/clean/classes/core_renderer.php b/theme/clean/classes/core_renderer.php index <HASH>..<HASH> 100644 --- a/theme/clean/classes/core_renderer.php +++ b/theme/clean/classes/core_renderer.php @@ -85,7 +85,7 @@ class theme_clean_core_renderer extends theme_bootstrapbase_core_renderer { array('class' => 'small-logo')); if ($returnlink) { - $logocontainer = html_writer::link($CFG->wwwroot, $image, + $logocontainer = html_writer::link(new moodle_url('/'), $image, array('class' => 'small-logo-container', 'title' => get_string('home'))); } else { $logocontainer = html_writer::tag('span', $image, array('class' => 'small-logo-container')); @@ -113,7 +113,7 @@ class theme_clean_core_renderer extends theme_bootstrapbase_core_renderer { $sitename = format_string($SITE->shortname, true, array('context' => context_course::instance(SITEID))); if ($returnlink) { - return html_writer::link($CFG->wwwroot, $sitename, array('class' => 'brand', 'title' => get_string('home'))); + return html_writer::link(new moodle_url('/'), $sitename, array('class' => 'brand', 'title' => get_string('home'))); } return html_writer::tag('span', $sitename, array('class' => 'brand'));
MDL-<I> theme_clean: Avoid redirects in home url
moodle_moodle
train
f4c8393113e2205eb8eeddeed10d42ad70d648ef
diff --git a/redis/client.py b/redis/client.py index <HASH>..<HASH> 100644 --- a/redis/client.py +++ b/redis/client.py @@ -896,6 +896,14 @@ class Redis(threading.local): "Increment the score of ``value`` in sorted set ``name`` by ``amount``" return self.execute_command('ZINCRBY', name, amount, value) + def zinter(self, dest, keys, aggregate=None): + """ + Intersect multiple sorted sets specified by ``keys`` into + a new sorted set, ``dest``. Scores in the destination will be + aggregated based on the ``aggregate``, or SUM if none is provided. + """ + return self._zaggregate('ZINTER', dest, keys, aggregate) + def zrange(self, name, start, end, desc=False, withscores=False): """ Return a range of values from sorted set ``name`` between @@ -980,6 +988,30 @@ class Redis(threading.local): "Return the score of element ``value`` in sorted set ``name``" return self.execute_command('ZSCORE', name, value) + def zunion(self, dest, keys, aggregate=None): + """ + Union multiple sorted sets specified by ``keys`` into + a new sorted set, ``dest``. Scores in the destination will be + aggregated based on the ``aggregate``, or SUM if none is provided. + """ + return self._zaggregate('ZUNION', dest, keys, aggregate) + + def _zaggregate(self, command, dest, keys, aggregate=None): + pieces = [command, dest, len(keys)] + if isinstance(keys, dict): + items = keys.items() + keys = [i[0] for i in items] + weights = [i[1] for i in items] + else: + weights = None + pieces.extend(keys) + if weights: + pieces.append('WEIGHTS') + pieces.extend(weights) + if aggregate: + pieces.append('AGGREGATE') + pieces.append(aggregate) + return self.execute_command(*pieces) #### HASH COMMANDS #### def hdel(self, name, key): diff --git a/tests/server_commands.py b/tests/server_commands.py index <HASH>..<HASH> 100644 --- a/tests/server_commands.py +++ b/tests/server_commands.py @@ -611,6 +611,33 @@ class ServerCommandsTestCase(unittest.TestCase): self.assertEquals(self.client.zscore('a', 'a2'), 3.0) self.assertEquals(self.client.zscore('a', 'a3'), 8.0) + def test_zinter(self): + self.make_zset('a', {'a1': 1, 'a2': 1, 'a3': 1}) + self.make_zset('b', {'a1': 2, 'a3': 2, 'a4': 2}) + self.make_zset('c', {'a1': 6, 'a3': 5, 'a4': 4}) + + # sum, no weight + self.assert_(self.client.zinter('z', ['a', 'b', 'c'])) + self.assertEquals( + self.client.zrange('z', 0, -1, withscores=True), + [('a3', 8), ('a1', 9)] + ) + + # max, no weight + self.assert_(self.client.zinter('z', ['a', 'b', 'c'], aggregate='MAX')) + self.assertEquals( + self.client.zrange('z', 0, -1, withscores=True), + [('a3', 5), ('a1', 6)] + ) + + # with weight + self.assert_(self.client.zinter('z', {'a': 1, 'b': 2, 'c': 3})) + self.assertEquals( + self.client.zrange('z', 0, -1, withscores=True), + [('a3', 20), ('a1', 23)] + ) + + def test_zrange(self): # key is not a zset self.client['a'] = 'a' @@ -724,6 +751,33 @@ class ServerCommandsTestCase(unittest.TestCase): # test a non-existant member self.assertEquals(self.client.zscore('a', 'a4'), None) + def test_zunion(self): + self.make_zset('a', {'a1': 1, 'a2': 1, 'a3': 1}) + self.make_zset('b', {'a1': 2, 'a3': 2, 'a4': 2}) + self.make_zset('c', {'a1': 6, 'a4': 5, 'a5': 4}) + + # sum, no weight + self.assert_(self.client.zunion('z', ['a', 'b', 'c'])) + self.assertEquals( + self.client.zrange('z', 0, -1, withscores=True), + [('a2', 1), ('a3', 3), ('a5', 4), ('a4', 7), ('a1', 9)] + ) + + # max, no weight + self.assert_(self.client.zunion('z', ['a', 'b', 'c'], aggregate='MAX')) + self.assertEquals( + self.client.zrange('z', 0, -1, withscores=True), + [('a2', 1), ('a3', 2), ('a5', 4), ('a4', 5), ('a1', 6)] + ) + + # with weight + self.assert_(self.client.zunion('z', {'a': 1, 'b': 2, 'c': 3})) + self.assertEquals( + self.client.zrange('z', 0, -1, withscores=True), + [('a2', 1), ('a3', 5), ('a5', 12), ('a4', 19), ('a1', 23)] + ) + + # HASHES def make_hash(self, key, d): for k,v in d.iteritems():
added support for zinter and zunion
andymccurdy_redis-py
train
4e4ff02db5f5c4e70e08b5cc7d5251cd2e342edd
diff --git a/troposphere/elasticsearch.py b/troposphere/elasticsearch.py index <HASH>..<HASH> 100644 --- a/troposphere/elasticsearch.py +++ b/troposphere/elasticsearch.py @@ -67,3 +67,7 @@ class Domain(AWSObject): 'SnapshotOptions': (SnapshotOptions, False), 'Tags': (list, False) } + + +# Backward compatibility +ElasticsearchDomain = Domain
Add backward compatibility for the deprecated ElasticsearchDomain
cloudtools_troposphere
train
6ada13643a1254624ac29ddf4a3320a354311bcf
diff --git a/test/test-50-fs-runtime-layer-2/test-x-index.js b/test/test-50-fs-runtime-layer-2/test-x-index.js index <HASH>..<HASH> 100644 --- a/test/test-50-fs-runtime-layer-2/test-x-index.js +++ b/test/test-50-fs-runtime-layer-2/test-x-index.js @@ -55,7 +55,17 @@ function test01 () { assert.equal(error6, null); const data3 = buffer3.toString('utf8', 0, buffer3.length); console.log('data3', data3); - test01e(fd); + const buffer4 = buffer3; + fs.writeFile(theFile, buffer4, function (error7, wtf2) { + if (process.pkg) { + assert.equal(typeof error7, 'object'); // TODO maybe code=EACCESS? + } else { + assert.equal(error7, null); + } + assert.equal(wtf2, undefined); + test01e(fd); + }); + console.log('after fs.writeFile'); }); console.log('after fs.readFile'); }); @@ -90,7 +100,17 @@ function test01e (badFd) { fs.readFile(theFile + '.notExists', function (error6, buffer3) { console.log('fs.readFile.error6.code', error6.code); console.log('typeof buffer3', typeof buffer3); - test02(); + const buffer4 = new Buffer(1024); + fs.writeFile(theFile + '/canNotWrite', buffer4, function (error7, wtf2) { + if (process.pkg) { + assert.equal(error7.code, 'ENOENT'); + } else { + assert.equal(error7.code, 'ENOTDIR'); + } + assert.equal(wtf2, undefined); + test02(); + }); + console.log('after fs.writeFile'); }); console.log('after fs.readFile'); });
test fs.writeFile in fs-layer-2
zeit_pkg
train
b20ba8145eb12ad1c0dcff4b5a3acb69ab55d1a3
diff --git a/addon/components/sl-select.js b/addon/components/sl-select.js index <HASH>..<HASH> 100755 --- a/addon/components/sl-select.js +++ b/addon/components/sl-select.js @@ -43,13 +43,6 @@ export default Ember.Component.extend( InputBased, TooltipEnabled, { disableSearch: false, /** - * Unique input id that will get generated and set on init of component - * - * @type {?String} - */ - inputId: null, - - /** * The internal input element, used for Select2's bindings * * @type {?Object} @@ -102,19 +95,6 @@ export default Ember.Component.extend( InputBased, TooltipEnabled, { // Observers /** - * Set unique inputId that will be set on label and input element - * - * @function - * @returns {undefined} - */ - setInputId: Ember.on( - 'init', - function() { - this.set( 'inputId', this.get( 'elementId' ) + '-input' ); - } - ), - - /** * Teardown the select2 to prevent memory leaks * * @function diff --git a/addon/components/sl-textarea.js b/addon/components/sl-textarea.js index <HASH>..<HASH> 100755 --- a/addon/components/sl-textarea.js +++ b/addon/components/sl-textarea.js @@ -110,13 +110,6 @@ export default Ember.Component.extend( InputBased, TooltipEnabled, { spellcheck: Spellcheck.Direction, /** - * Unique textarea id that will get generated and set on init of component - * - * @type {?String} - */ - textAreaId: null, - - /** * The bound value of the textarea * * @type {?String} @@ -135,19 +128,6 @@ export default Ember.Component.extend( InputBased, TooltipEnabled, { // ------------------------------------------------------------------------- // Observers - /** - * Set unique textAreaId that will be set on label and textarea element - * - * @function - * @returns {undefined} - */ - setTextAreaId: Ember.on( - 'init', - function() { - this.set( 'textAreaId', this.get( 'elementId' ) + '-textarea' ); - } - ) - // ------------------------------------------------------------------------- // Methods diff --git a/addon/mixins/sl-input-based.js b/addon/mixins/sl-input-based.js index <HASH>..<HASH> 100644 --- a/addon/mixins/sl-input-based.js +++ b/addon/mixins/sl-input-based.js @@ -39,6 +39,13 @@ export default Ember.Mixin.create({ disabled: false, /** + * Unique input id that will get generated and set on init of component + * + * @type {?String} + */ + inputId: null, + + /** * Whether the input-based component should be displayed as optional * * @type {Boolean} @@ -64,6 +71,19 @@ export default Ember.Mixin.create({ // ------------------------------------------------------------------------- // Observers + /** + * Set unique inputId that will be set on label and input element + * + * @function + * @returns {undefined} + */ + setInputId: Ember.on( + 'init', + function() { + this.set( 'inputId', this.get( 'elementId' ) + '-input' ); + } + ), + // ------------------------------------------------------------------------- // Methods diff --git a/addon/templates/components/sl-textarea.hbs b/addon/templates/components/sl-textarea.hbs index <HASH>..<HASH> 100644 --- a/addon/templates/components/sl-textarea.hbs +++ b/addon/templates/components/sl-textarea.hbs @@ -1,5 +1,5 @@ {{#if label}} - <label for={{textAreaId}} class="control-label"> + <label for={{inputId}} class="control-label"> {{label}} {{#if optional}} @@ -13,7 +13,7 @@ {{/if}} {{textarea - id=textAreaId + id=inputId autofocus=autofocus class="form-control" cols=cols
Moved inputId generation to input based mixin.
softlayer_sl-ember-components
train
5373981efb2a56e52139a46ed56008d084ac7871
diff --git a/dashboard_server/urls.py b/dashboard_server/urls.py index <HASH>..<HASH> 100644 --- a/dashboard_server/urls.py +++ b/dashboard_server/urls.py @@ -66,6 +66,7 @@ urlpatterns = patterns('', name='data-browser'), url(r'xml-rpc/', dashboard_xml_rpc_handler, name='xml-rpc'), + url(r'^dashboard/', include('dashboard_app.urls')), url(r'accounts/', include('django.contrib.auth.urls')), (r'^admin/', include(admin.site.urls)), )
Include all dashboard_app URLs from dashboard_server URLs under /dashboard
zyga_json-schema-validator
train
499cd75502b7598eebeda5864e19d70331bbc9c2
diff --git a/src/redisboard/admin.py b/src/redisboard/admin.py index <HASH>..<HASH> 100644 --- a/src/redisboard/admin.py +++ b/src/redisboard/admin.py @@ -17,6 +17,7 @@ class RedisServerAdmin(admin.ModelAdmin): list_display = ( '__unicode__', 'status', 'memory', 'clients', 'details', 'tools' ) + list_filter = 'label', 'hostname' ordering = ('hostname', 'port') def status(self, obj): return obj.stats['status']
Added list filters for label and hostname.
ionelmc_django-redisboard
train
f02531339279755e12347c5ce826544f3647f7ed
diff --git a/npm/test-lint.js b/npm/test-lint.js index <HASH>..<HASH> 100755 --- a/npm/test-lint.js +++ b/npm/test-lint.js @@ -10,9 +10,7 @@ var async = require('async'), './lib/authorizer', './lib/uvm/*.js', './lib/backpack', - './test/system', - './test/unit', - './test/integration', + './test', './npm/*.js', './index.js' ];
Add all test directories to eslint config
postmanlabs_postman-runtime
train
3608f3aa0cc26f41aad71402d6dd097b2fb40442
diff --git a/pygubu/__init__.py b/pygubu/__init__.py index <HASH>..<HASH> 100644 --- a/pygubu/__init__.py +++ b/pygubu/__init__.py @@ -7,21 +7,19 @@ __all__ = [ 'BuilderObject', 'register_widget', 'register_property', + 'register_custom_property', 'remove_binding', 'ApplicationLevelBindManager'] -import pygubu.builder.builderobject from pygubu.binding import ApplicationLevelBindManager, remove_binding from pygubu.builder import Builder -from pygubu.builder.builderobject import BuilderObject, register_widget +from pygubu.builder.builderobject import (BuilderObject, register_widget, + register_property, + register_custom_property) __version__ = '0.16' -def register_property(name, description): - return pygubu.builder.builderobject.register_property(name, description) - - class TkApplication: def __init__(self, master=None): self.master = master diff --git a/pygubu/builder/builderobject.py b/pygubu/builder/builderobject.py index <HASH>..<HASH> 100644 --- a/pygubu/builder/builderobject.py +++ b/pygubu/builder/builderobject.py @@ -14,7 +14,9 @@ except ImportError: __all__ = [ 'BuilderObject', 'EntryBaseBO', 'PanedWindowBO', 'PanedWindowPaneBO', 'WidgetDescription', 'CLASS_MAP', 'CB_TYPES', - 'CUSTOM_PROPERTIES', 'register_widget', 'register_property'] + 'CUSTOM_PROPERTIES', 'register_widget', 'register_property', + 'register_custom_property' +] logger = logging.getLogger(__name__) @@ -90,6 +92,29 @@ def register_property(name, description): logger.debug('Registered property %s', name) +def register_custom_property( + builder_uid, prop_name, + editor, default_value=None, help=None, + **editor_params): + '''Helper function to register a custom property. + All custom properties are created using internal dynamic editor. + ''' + description = { + 'editor': 'dynamic', + builder_uid: { + 'params': { + 'mode': editor, + } + } + } + description[builder_uid]['params'].update(editor_params) + if default_value is not None: + description[builder_uid]['default'] = default_value + if help is not None: + description[builder_uid]['help'] = help + register_property(prop_name, description) + + class CB_TYPES: '''Callback types''' SIMPLE = 'simple'
Add register_custom_property function. This is a helper function to easy register a new property.
alejandroautalan_pygubu
train
e7e2c23985e04cb4f084a4e6181532de1f44c60c
diff --git a/src/test/php/predicate/RegexTest.php b/src/test/php/predicate/RegexTest.php index <HASH>..<HASH> 100644 --- a/src/test/php/predicate/RegexTest.php +++ b/src/test/php/predicate/RegexTest.php @@ -94,14 +94,21 @@ class RegexTest extends TestCase */ public function invalidRegexThrowsRuntimeExceptionOnEvaluation() { - expect(function() { + $expect = expect(function() { $regex = new Regex('^([a-z]{3})$'); $regex('foo'); }) - ->throws(\RuntimeException::class) - ->withMessage( - 'Failure while matching "^([a-z]{3})$", reason: invalid regular expression.' - ); + ->throws(\RuntimeException::class); + if (version_compare(PHP_VERSION, '7.2.0', '<')) { + $expect->withMessage( + 'Failure while matching "^([a-z]{3})$", reason: invalid regular expression.' + ); + } else { + $expect->withMessage( + 'Failure while matching "^([a-z]{3})$", reason: internal PCRE error.' + ); + } + } /**
apparently the error changed... *sigh*
bovigo_assert
train
ac5b05702f9430076f70c275aae72695851e9214
diff --git a/app/models/tolk/locale.rb b/app/models/tolk/locale.rb index <HASH>..<HASH> 100644 --- a/app/models/tolk/locale.rb +++ b/app/models/tolk/locale.rb @@ -57,6 +57,7 @@ module Tolk accepts_nested_attributes_for :translations, :reject_if => proc { |attributes| attributes['text'].blank? } before_validation :remove_invalid_translations_from_target, :on => :update + attr_accessible :name cattr_accessor :locales_config_path self.locales_config_path = "#{Rails.root}/config/locales" diff --git a/app/models/tolk/phrase.rb b/app/models/tolk/phrase.rb index <HASH>..<HASH> 100644 --- a/app/models/tolk/phrase.rb +++ b/app/models/tolk/phrase.rb @@ -2,6 +2,8 @@ module Tolk class Phrase < ActiveRecord::Base self.table_name = "tolk_phrases" + attr_accessible :key + validates_uniqueness_of :key cattr_accessor :per_page diff --git a/app/models/tolk/translation.rb b/app/models/tolk/translation.rb index <HASH>..<HASH> 100644 --- a/app/models/tolk/translation.rb +++ b/app/models/tolk/translation.rb @@ -14,6 +14,7 @@ module Tolk belongs_to :locale, :class_name => 'Tolk::Locale' validates_presence_of :locale_id + attr_accessible :phrase_id, :locale_id, :text, :primary_updated, :previous_text, :locale, :phrase attr_accessor :force_set_primary_update before_save :set_primary_updated
Whitelisting attributes (rails <I> security enhancement)
tolk_tolk
train
761713142331194ffbde80e5ffc842a652d801c8
diff --git a/trimesh/exchange/gltf.py b/trimesh/exchange/gltf.py index <HASH>..<HASH> 100644 --- a/trimesh/exchange/gltf.py +++ b/trimesh/exchange/gltf.py @@ -236,7 +236,8 @@ def load_gltf(file_obj=None, # that can be used to instantiate a trimesh.Scene object kwargs = _read_buffers(header=tree, buffers=buffers, - mesh_kwargs=mesh_kwargs) + mesh_kwargs=mesh_kwargs, + resolver=resolver) return kwargs @@ -626,7 +627,7 @@ def _append_path(path, name, tree, buffer_items): vxlist[4][1].astype(float32).tobytes())) -def _parse_materials(header, views): +def _parse_materials(header, views, resolver=None): """ Convert materials and images stored in a GLTF header and buffer views to PBRMaterial objects. @@ -657,7 +658,14 @@ def _parse_materials(header, views): # loop through images for i, img in enumerate(header["images"]): # get the bytes representing an image - blob = views[img["bufferView"]] + if 'bufferView' in img: + blob = views[img["bufferView"]] + elif 'uri' in img: + blob = resolver.get(img['uri']) + else: + log.warning('unable to load image from: {}'.format( + img.keys())) + continue # i.e. 'image/jpeg' # mime = img['mimeType'] try: @@ -693,7 +701,7 @@ def _parse_materials(header, views): return materials -def _read_buffers(header, buffers, mesh_kwargs): +def _read_buffers(header, buffers, mesh_kwargs, resolver=None): """ Given a list of binary data and a layout, return the kwargs to create a scene object. @@ -750,7 +758,8 @@ def _read_buffers(header, buffers, mesh_kwargs): access.append(array) # load images and textures into material objects - materials = _parse_materials(header, views) + materials = _parse_materials( + header, views=views, resolver=resolver) mesh_prim = collections.defaultdict(list) # load data from accessors into Trimesh objects diff --git a/trimesh/version.py b/trimesh/version.py index <HASH>..<HASH> 100644 --- a/trimesh/version.py +++ b/trimesh/version.py @@ -1 +1 @@ -__version__ = '2.38.15' +__version__ = '2.38.17'
use resolver to load external GLTF images
mikedh_trimesh
train
c2a84a858442396e3702e80259f2dcedfbd941b9
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -46,7 +46,7 @@ setup(name='cwltool', 'rdflib >= 4.1.0', 'rdflib-jsonld >= 0.3.0', 'shellescape', - 'schema-salad >= 1.18', + 'schema-salad >= 1.18.20160930145650', 'typing >= 3.5.2', 'cwltest >= 1.0.20160907111242'], test_suite='tests',
Bump schema-salad version for validation performance fixes. (#<I>)
common-workflow-language_cwltool
train
a40315c4366240f9d21ae2e9e0415163c2b6abbc
diff --git a/test/assertions/to-contain.spec.js b/test/assertions/to-contain.spec.js index <HASH>..<HASH> 100644 --- a/test/assertions/to-contain.spec.js +++ b/test/assertions/to-contain.spec.js @@ -117,4 +117,26 @@ describe('to contain assertion', function () { '^^^ ^^^'); }); }); + + it('should not highlight overlapping partial matches', function () { + expect(function () { + expect('foobarquux', 'not to contain', 'foob', 'barq'); + }, 'to throw', + "expected 'foobarquux' not to contain 'foob', 'barq'\n" + + "\n" + + "foobarquux\n" + + "^^^^" + ); + }); + + it('should highlight all occurrences of the longest partial match', function () { + expect(function () { + expect('foobarquuxfoob', 'to contain', 'ooaaq', 'foobr'); + }, 'to throw', + "expected 'foobarquuxfoob' to contain 'ooaaq', 'foobr'\n" + + "\n" + + "foobarquuxfoob\n" + + "^^^^ ^^^^" + ); + }); });
Improve coverage of some unrelated code.
unexpectedjs_unexpected
train
abb4292bace20ca0829a479fc58414469a05411d
diff --git a/tests/integration/test_starlette_py36plus.py b/tests/integration/test_starlette_py36plus.py index <HASH>..<HASH> 100644 --- a/tests/integration/test_starlette_py36plus.py +++ b/tests/integration/test_starlette_py36plus.py @@ -261,8 +261,8 @@ async def test_amazon_queue_time(tracked_requests): async def test_server_error(tracked_requests): with app_with_scout() as app: communicator = ApplicationCommunicator(app, asgi_http_scope(path="/crash/")) + await communicator.send_input({"type": "http.request"}) with pytest.raises(ValueError) as excinfo: - await communicator.send_input({"type": "http.request"}) await communicator.receive_output() assert excinfo.value.args == ("BØØM!",)
Tidy Starlette test (#<I>) Noticed this `with pytest.raises()` wasn't around a single statement so ambiguous.
scoutapp_scout_apm_python
train
89eedffe04accd81fd2d5b1cbddc34186ffa9b42
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index <HASH>..<HASH> 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -17,6 +17,10 @@ Unreleased ---------- None +[3.46.5] +-------- +fix: degreed2 improperly tracking completion status + [3.46.4] -------- fix: Degreed2 estimated time to complete in hours diff --git a/enterprise/__init__.py b/enterprise/__init__.py index <HASH>..<HASH> 100644 --- a/enterprise/__init__.py +++ b/enterprise/__init__.py @@ -2,6 +2,6 @@ Your project description goes here. """ -__version__ = "3.46.4" +__version__ = "3.46.5" default_app_config = "enterprise.apps.EnterpriseConfig" diff --git a/integrated_channels/degreed2/exporters/learner_data.py b/integrated_channels/degreed2/exporters/learner_data.py index <HASH>..<HASH> 100644 --- a/integrated_channels/degreed2/exporters/learner_data.py +++ b/integrated_channels/degreed2/exporters/learner_data.py @@ -24,6 +24,7 @@ class Degreed2LearnerExporter(LearnerExporter): self, enterprise_enrollment, completed_date=None, + course_completed=False, **kwargs ): # pylint: disable=arguments-differ """ @@ -50,6 +51,7 @@ class Degreed2LearnerExporter(LearnerExporter): degreed_user_email=enterprise_enrollment.enterprise_customer_user.user_email, course_id=get_course_id_for_enrollment(enterprise_enrollment), completed_timestamp=completed_timestamp, + course_completed=course_completed, enterprise_customer_uuid=enterprise_enrollment.enterprise_customer_user.enterprise_customer.uuid, plugin_configuration_id=self.enterprise_configuration.id, ), @@ -58,6 +60,7 @@ class Degreed2LearnerExporter(LearnerExporter): degreed_user_email=enterprise_enrollment.enterprise_customer_user.user_email, course_id=enterprise_enrollment.course_id, completed_timestamp=completed_timestamp, + course_completed=course_completed, enterprise_customer_uuid=enterprise_enrollment.enterprise_customer_user.enterprise_customer.uuid, plugin_configuration_id=self.enterprise_configuration.id, )
fix: degreed2 improperly tracking completion status (#<I>) ENT-<I>
edx_edx-enterprise
train
d856414551912c378be663723eac3cc916717860
diff --git a/setup.php b/setup.php index <HASH>..<HASH> 100644 --- a/setup.php +++ b/setup.php @@ -93,7 +93,7 @@ Zend_Loader_Autoloader::getInstance(); require 'includes/functions/functions.php'; require 'includes/functions/functions_edit.php'; require 'includes/classes/class_i18n.php'; -define('WT_LOCALE', i18n::init()); +define('WT_LOCALE', i18n::init(safe_POST('lang', '[@a-zA-Z_]+'))); echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
Fix: setup.php reverts to english after page one
fisharebest_webtrees
train
3b51cd8ecfa4008d300be5922d4e9a3d789c1e61
diff --git a/synapse/models/material.py b/synapse/models/material.py index <HASH>..<HASH> 100644 --- a/synapse/models/material.py +++ b/synapse/models/material.py @@ -21,6 +21,10 @@ class MatModule(s_module.CoreModule): ('name', ('str', {'lower': True}), {'doc': 'The human readable name of the material item'}), + ('spec', ('mat:spec', {}), { + 'doc': 'The mat:spec of which this item is an instance.', + }), + ('latlong', ('geo:latlong', {}), {'doc': 'The last known lat/long location of the node'}), # TODO add baseline things like dimensions / mass / etc? diff --git a/synapse/models/telco.py b/synapse/models/telco.py index <HASH>..<HASH> 100644 --- a/synapse/models/telco.py +++ b/synapse/models/telco.py @@ -328,6 +328,10 @@ class TelcoModule(s_module.CoreModule): ('time', ('time', {}), {}), ('latlong', ('geo:latlong', {}), {}), + ('loc', ('loc', {}), { + 'doc': 'The geo-political location of the mobile telemetry sample.', + }), + ('accuracy', ('geo:dist', {}), { 'doc': 'The reported accuracy of the latlong telemetry reading.', }), diff --git a/synapse/tests/test_model_material.py b/synapse/tests/test_model_material.py index <HASH>..<HASH> 100644 --- a/synapse/tests/test_model_material.py +++ b/synapse/tests/test_model_material.py @@ -10,7 +10,7 @@ class MatTest(s_t_utils.SynTest): node0 = await snap.addNode('mat:spec', n0_guid, props={'name': 'F16 Fighter Jet'}) n1_guid = guid() node1 = await snap.addNode('mat:item', n1_guid, - props={'name': "Visi's F16 Fighter Jet", 'latlong': '0,0'}) + props={'name': "Visi's F16 Fighter Jet", 'latlong': '0,0', 'spec': n0_guid}) f0 = await snap.addNode('file:bytes', '*') f0_valu = f0.ndef[1] @@ -28,3 +28,5 @@ class MatTest(s_t_utils.SynTest): self.eq(node3.props.get('item'), n1_guid) self.eq(node3.props.get('file'), f0_valu) + + self.len(1, await core.nodes('mat:spec:name="f16 fighter jet" -> mat:item')) diff --git a/synapse/tests/test_model_telco.py b/synapse/tests/test_model_telco.py index <HASH>..<HASH> 100644 --- a/synapse/tests/test_model_telco.py +++ b/synapse/tests/test_model_telco.py @@ -82,6 +82,7 @@ class TelcoModelTest(s_t_utils.SynTest): softguid = s_common.guid() props = {'time': '2001', 'latlong': (-1, 1), + 'loc': 'us', 'accuracy': '100mm', 'cell': (('001', '02'), 3, 4), 'imsi': '310150123456789', @@ -105,6 +106,7 @@ class TelcoModelTest(s_t_utils.SynTest): self.eq(node.ndef[1], guid) self.eq(node.get('time'), 978307200000) self.eq(node.get('latlong'), (-1.0, 1.0)) + self.eq(node.get('loc'), 'us') self.eq(node.get('accuracy'), 100) self.eq(node.get('cell'), (('001', '02'), 3, 4)) self.eq(node.get('cell:carrier'), ('001', '02'))
tel:mob:telem:loc prop and mat:item:spec prop added (#<I>)
vertexproject_synapse
train
d6cd7d8f351588d3f4ffcf7fae6dd2ceb4e0fbc7
diff --git a/lib/hubs3d/model.rb b/lib/hubs3d/model.rb index <HASH>..<HASH> 100644 --- a/lib/hubs3d/model.rb +++ b/lib/hubs3d/model.rb @@ -26,16 +26,17 @@ module Hubs3D private - def base_64 + def base_64_file Base64.encode64 open(@path, 'r') { |f| f.read } end def post - post = API.post("/model", file: base_64, - fileName: name, - attachments: attachments) - fail "Expected Hash but was #{post.inspect}" unless post.kind_of?(Hash) - post + params = { + file: base_64_file, + fileName: name, + } + params[:attachments] = attachments if attachments + API.post("/model", params) end end end diff --git a/spec/model_spec.rb b/spec/model_spec.rb index <HASH>..<HASH> 100644 --- a/spec/model_spec.rb +++ b/spec/model_spec.rb @@ -2,20 +2,37 @@ require "spec_helper" require "hubs3d/model" describe Hubs3D::Model do - let(:model) { described_class.new(name: "Foo", path: "example.stl") } + let(:model) { + described_class.new(name: "foo.stl", path: "spec/fixtures/example.stl") + } describe "#name" do it "returns the name" do - expect(model.name).to eq("Foo") + expect(model.name).to eq("foo.stl") end end describe "#path" do it "returns the path" do - expect(model.path).to eq("example.stl") + expect(model.path).to eq("spec/fixtures/example.stl") end end - pending "#id" - pending "#attachments" + describe "#id" do + it "sends a request" do + stub_request(:post, "https://www.3dhubs.com/api/v1/model") + .with(body: {"file"=>"Rk9vTwo=\n", "fileName"=>"foo.stl"}, + headers: {'Accept' => 'application/json'}) + .to_return(status: 200, body: '{"modelId":"42"}') + + expect(model.id).to eq(42) + end + end + + describe "#attachments" do + it "returns the attachments" do + model = described_class.new(attachments: { foo: 42 }) + expect(model.attachments).to eq({ foo: 42 }) + end + end end
Add attachments params to the request only if needed
sunny_hubs3d
train
2a8998fc344886297e3932b0365f7effed5c2923
diff --git a/test/test_wordcloud.py b/test/test_wordcloud.py index <HASH>..<HASH> 100644 --- a/test/test_wordcloud.py +++ b/test/test_wordcloud.py @@ -69,10 +69,9 @@ def test_collocation_stopwords(): wc = WordCloud(collocations=True, stopwords={"you", "very"}, collocation_threshold=9) wc.generate(STOPWORDED_COLLOCATIONS) - assert "thank you" in wc.words_ - assert "very much" in wc.words_ - # "thank" will have been removed in favor of the bigrams including "thank" - assert "thank" not in wc.words_ + assert "thank you" not in wc.words_ + assert "very much" not in wc.words_ + assert "thank" in wc.words_ # a bigram of all stopwords will be removed assert "you very" not in wc.words_ diff --git a/wordcloud/tokenization.py b/wordcloud/tokenization.py index <HASH>..<HASH> 100644 --- a/wordcloud/tokenization.py +++ b/wordcloud/tokenization.py @@ -38,8 +38,9 @@ def pairwise(iterable): def unigrams_and_bigrams(words, stopwords, normalize_plurals=True, collocation_threshold=30): # We must create the bigrams before removing the stopword tokens from the words, or else we get bigrams like - # "thank much" from "thank you very much". But bigrams consisting entirely of stopwords are still invalid. - bigrams = list(p for p in pairwise(words) if not all(w in stopwords for w in p)) + # "thank much" from "thank you very much". + # We don't allow any of the words in the bigram to be stopwords + bigrams = list(p for p in pairwise(words) if not any(w in stopwords for w in p)) n_words = len(words) counts_unigrams, standard_form = process_tokens( words, normalize_plurals=normalize_plurals)
change tokenization behavior to never include stop words in bigrams
amueller_word_cloud
train
037e0d0775261017ab5396960e2b94d48eb40be7
diff --git a/bin/nodemcu-tool.js b/bin/nodemcu-tool.js index <HASH>..<HASH> 100755 --- a/bin/nodemcu-tool.js +++ b/bin/nodemcu-tool.js @@ -99,7 +99,7 @@ _cli .action(function(options){ // force silent mode! - SilentMode(options.json===true); + SilentMode(options.json===true || _cli.silent===true); _nodemcutool.fsinfo(_cli.port, _cli.baud, options.json); });
fixed silent mode for fsinfo command
AndiDittrich_NodeMCU-Tool
train
ea16803980ae93688f977e0a693a4a98df5d033d
diff --git a/desktop/app/menu-bar.js b/desktop/app/menu-bar.js index <HASH>..<HASH> 100644 --- a/desktop/app/menu-bar.js +++ b/desktop/app/menu-bar.js @@ -68,7 +68,7 @@ export default function () { }) if (process.platform === 'linux') { - mb.tray.setToolTip('View Folders') + mb.tray.setToolTip('Show Keybase') } mb.on('show', () => { diff --git a/desktop/app/menu-helper.js b/desktop/app/menu-helper.js index <HASH>..<HASH> 100644 --- a/desktop/app/menu-helper.js +++ b/desktop/app/menu-helper.js @@ -57,9 +57,7 @@ export default function makeMenu (window) { } else { const template = [{ label: '&File', - submenu: [ - {label: '&Close', accelerator: 'CmdOrCtrl+W', click () { this.remoteWindow.close() }} - ] + submenu: [{label: '&Close', accelerator: 'CmdOrCtrl+W', role: 'close'}] }, { label: 'Help', submenu: [{label: 'Learn More', click () { shell.openExternal('https://keybase.io') }}]
fix close. make context menu on unbuntu say show keybase vs view folders (#<I>)
keybase_client
train
11a7e49682227a3b6b8712b179e4dc6ea6433e6b
diff --git a/actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/modules/calls/CallMasterActor.java b/actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/modules/calls/CallMasterActor.java index <HASH>..<HASH> 100644 --- a/actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/modules/calls/CallMasterActor.java +++ b/actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/modules/calls/CallMasterActor.java @@ -176,8 +176,10 @@ public class CallMasterActor extends CallActor { // getPeer(uid, deviceId).send(new PeerConnectionActor.OnOfferNeeded()); for (MasterCallDevice device : state.getConnectedDevices()) { - sendSignalingMessage(device.getUid(), device.getDeviceId(), - new ApiNeedOffer(uid, deviceId, peerSettings, true)); + if (device.getUid() != uid && device.getDeviceId() != deviceId) { + sendSignalingMessage(device.getUid(), device.getDeviceId(), + new ApiNeedOffer(uid, deviceId, peerSettings, true)); + } } } } @@ -201,8 +203,10 @@ public class CallMasterActor extends CallActor { // Notify all devices about answer // for (MasterCallDevice device : state.getConnectedDevices()) { - sendSignalingMessage(device.getUid(), device.getDeviceId(), - new ApiOnAnswer(uid, deviceId)); + if (device.getUid() != uid && device.getDeviceId() != deviceId) { + sendSignalingMessage(device.getUid(), device.getDeviceId(), + new ApiOnAnswer(uid, deviceId)); + } } } else { @@ -212,8 +216,10 @@ public class CallMasterActor extends CallActor { ApiPeerSettings peerSettings = state.getPeerSettings(uid, deviceId); getPeer(uid, deviceId).send(new PeerConnectionActor.OnOfferNeeded()); for (MasterCallDevice device : state.getConnectedDevices()) { - sendSignalingMessage(device.getUid(), device.getDeviceId(), - new ApiNeedOffer(uid, deviceId, peerSettings, false)); + if (device.getUid() != uid && device.getDeviceId() != deviceId) { + sendSignalingMessage(device.getUid(), device.getDeviceId(), + new ApiNeedOffer(uid, deviceId, peerSettings, false)); + } } }
fix(core): Fixing incorrect signaling messages in master call actor
actorapp_actor-platform
train
f0cf49ca96832ce97feba2344252f03406c6d062
diff --git a/packages/jsdoc2spec/src/cli.js b/packages/jsdoc2spec/src/cli.js index <HASH>..<HASH> 100755 --- a/packages/jsdoc2spec/src/cli.js +++ b/packages/jsdoc2spec/src/cli.js @@ -13,13 +13,16 @@ const { generate, write } = require('./transformer.js'); const defaultConfig = require('../spec.config.js'); -const y = yargs // eslint-disable-line no-unused-expressions +const conf = yargs // eslint-disable-line no-unused-expressions .usage('jsdoc2spec') .help('help') .alias('h', 'help') - // .version() .alias('v', 'version') .options({ + glob: { + describe: 'Glob pattern for source files', + type: 'array', + }, c: { alias: 'config', describe: 'Path to config file', @@ -56,34 +59,24 @@ const y = yargs // eslint-disable-line no-unused-expressions .wrap(Math.min(120, yargs.terminalWidth())) .argv; -const config = ((configPath) => { - if (configPath == null) { - return defaultConfig; - } - const p = path.resolve(process.cwd(), configPath); +const configs = [defaultConfig]; + +if (typeof conf.c === 'string') { + const p = path.resolve(process.cwd(), conf.c); if (!fs.existsSync(p)) { throw new Error(`Config ${p} not found`); } - return extend(true, {}, defaultConfig, require(p)); -})(y.config); - -if (y.output && y.output.file != null) { - config.output.file = y.output.file; -} -if (y.jsdoc != null) { - config.jsdoc = y.jsdoc; -} -if (y.p != null) { - config.package = y.p; + configs.push(require(p)); } +configs.push(conf); +const config = extend(true, {}, ...configs); const run = (data) => { - // console.log(typeof data); const spec = generate({ data: data.docs || data, config, }); - if (y.x) { + if (config.x) { console.log(spec); // stream to stdout } else { write(spec, config.output.file); @@ -141,9 +134,9 @@ if (require.main === module) { const cwd = process.cwd(); const pkg = config.package ? path.resolve(cwd, config.package) : []; const files = (await globby(config.glob, { - gitignore: true, + gitignore: false, })).concat(pkg).map(f => path.resolve(cwd, f)); // need actual filenames since jsdoc does not support glob patterns - if (y.w) { + if (config.w) { chokidar.watch(files).on('change', (filename) => { console.log(filename); runWithJSDoc(files);
refactor: properly merge configs with cli options
miralemd_scriptappy
train
25b8b84f65116935b2873dce71616c6ca82c74bd
diff --git a/src/Symfony/Component/BrowserKit/CookieJar.php b/src/Symfony/Component/BrowserKit/CookieJar.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Component/BrowserKit/CookieJar.php +++ b/src/Symfony/Component/BrowserKit/CookieJar.php @@ -37,6 +37,11 @@ class CookieJar /** * Gets a cookie by name. * + * You should never use an empty domain, but if you do so, + * this method returns the first cookie for the given name/path + * (this behavior ensures a BC behavior with previous versions of + * Symfony). + * * @param string $name The cookie name * @param string $path The cookie path * @param string $domain The cookie domain @@ -49,12 +54,27 @@ class CookieJar { $this->flushExpiredCookies(); - return isset($this->cookieJar[$domain][$path][$name]) ? $this->cookieJar[$domain][$path][$name] : null; + if (!empty($domain)) { + return isset($this->cookieJar[$domain][$path][$name]) ? $this->cookieJar[$domain][$path][$name] : null; + } + + // avoid relying on this behavior that is mainly here for BC reasons + foreach ($this->cookieJar as $domain => $cookies) { + if (isset($cookies[$path][$name])) { + return $cookies[$path][$name]; + } + } + + return null; } /** * Removes a cookie by name. * + * You should never use an empty domain, but if you do so, + * all cookies for the given name/path expire (this behavior + * ensures a BC behavior with previous versions of Symfony). + * * @param string $name The cookie name * @param string $path The cookie path * @param string $domain The cookie domain @@ -67,13 +87,23 @@ class CookieJar $path = '/'; } - unset($this->cookieJar[$domain][$path][$name]); + if (empty($domain)) { + // an empty domain means any domain + // this should never happen but it allows for a better BC + $domains = array_keys($this->cookieJar); + } else { + $domains = array($domain); + } - if (empty($this->cookieJar[$domain][$path])) { - unset($this->cookieJar[$domain][$path]); + foreach ($domains as $domain) { + unset($this->cookieJar[$domain][$path][$name]); - if (empty($this->cookieJar[$domain])) { - unset($this->cookieJar[$domain]); + if (empty($this->cookieJar[$domain][$path])) { + unset($this->cookieJar[$domain][$path]); + + if (empty($this->cookieJar[$domain])) { + unset($this->cookieJar[$domain]); + } } } }
[BrowserKit] fixed BC break done recently
symfony_symfony
train
d23d20f20422f0746aedad0e31318417c2ac7041
diff --git a/config/styleguide.config.js b/config/styleguide.config.js index <HASH>..<HASH> 100644 --- a/config/styleguide.config.js +++ b/config/styleguide.config.js @@ -271,6 +271,17 @@ module.exports = { }, { name: 'Content', + sections: [ + { + name: 'Terms and Conditions', + components() { + return [ + path.resolve('packages/TermsAndConditions/TermsAndConditions.jsx'), + path.resolve('packages/TermsAndConditions/Sticky/Sticky.jsx'), + ] + }, + }, + ], components() { return [ path.resolve('packages/Card/Card.jsx'),
chore(docs): add terms and conditions to styleguidist
telus_tds-core
train
e4641f1d3d986d77142b1007406e57a4b108d36f
diff --git a/sbe-tool/src/main/java/uk/co/real_logic/sbe/xml/Field.java b/sbe-tool/src/main/java/uk/co/real_logic/sbe/xml/Field.java index <HASH>..<HASH> 100644 --- a/sbe-tool/src/main/java/uk/co/real_logic/sbe/xml/Field.java +++ b/sbe-tool/src/main/java/uk/co/real_logic/sbe/xml/Field.java @@ -96,11 +96,34 @@ public class Field checkForValidName(node, name); + if (presence == Presence.CONSTANT && null != valueRef) + { + final String typeName = type == null ? null : type.name(); + + if (!(type instanceof EnumType)) + { + handleError(node, "valueRef only valid for enum constants, type is " + typeName); + } + + final int periodIndex = valueRef.indexOf('.'); + if (periodIndex < 1 || periodIndex == (valueRef.length() - 1)) + { + handleError( + node, "valueRef format not valid for constant (enum-name.valid-value-name): " + valueRef); + } + + final String valueRefType = valueRef.substring(0, periodIndex); + if (!valueRefType.equals(typeName)) + { + handleError(node, "valueRef type " + valueRefType + " does not match " + typeName); + } + } + if (type instanceof EnumType && presence == Presence.CONSTANT) { if (null == valueRef) { - handleError(node, "valueRef not set for constant Enum"); + handleError(node, "valueRef not set for constant enum"); } else { @@ -114,7 +137,7 @@ public class Field final String valueRefType = valueRef.substring(0, periodIndex); if (!valueRefType.equals(type.name())) { - handleError(node, "valueRef for Enum name not found: " + valueRefType); + handleError(node, "valueRef for enum name not found: " + valueRefType); } final String validValueName = valueRef.substring(periodIndex + 1);
[Java] Validate the type is correct when using a valueRef for a enum constant. Issue #<I>.
real-logic_simple-binary-encoding
train
a24bac9e5e4d76112c199ec43f90a9d4d34dcd45
diff --git a/great_expectations/rule_based_profiler/data_assistant/data_assistant.py b/great_expectations/rule_based_profiler/data_assistant/data_assistant.py index <HASH>..<HASH> 100644 --- a/great_expectations/rule_based_profiler/data_assistant/data_assistant.py +++ b/great_expectations/rule_based_profiler/data_assistant/data_assistant.py @@ -109,6 +109,7 @@ class DataAssistant(metaclass=MetaDataAssistant): """ return self.build_numeric_metric_multi_batch_parameter_builder( metric_name="table.row_count", + metric_domain_kwargs=None, metric_value_kwargs=None, json_serialize=json_serialize, ) @@ -312,6 +313,9 @@ class DataAssistant(metaclass=MetaDataAssistant): @staticmethod def build_numeric_metric_multi_batch_parameter_builder( metric_name: str, + metric_domain_kwargs: Optional[ + Union[str, dict] + ] = DOMAIN_KWARGS_PARAMETER_FULLY_QUALIFIED_NAME, metric_value_kwargs: Optional[Union[str, dict]] = None, json_serialize: Union[str, bool] = True, ) -> MetricMultiBatchParameterBuilder: @@ -322,7 +326,7 @@ class DataAssistant(metaclass=MetaDataAssistant): return MetricMultiBatchParameterBuilder( name=name, metric_name=metric_name, - metric_domain_kwargs=DOMAIN_KWARGS_PARAMETER_FULLY_QUALIFIED_NAME, + metric_domain_kwargs=metric_domain_kwargs, metric_value_kwargs=metric_value_kwargs, enforce_numeric_metric=True, replace_nan_with_zero=True, diff --git a/tests/rule_based_profiler/data_assistant/test_volume_data_assistant.py b/tests/rule_based_profiler/data_assistant/test_volume_data_assistant.py index <HASH>..<HASH> 100644 --- a/tests/rule_based_profiler/data_assistant/test_volume_data_assistant.py +++ b/tests/rule_based_profiler/data_assistant/test_volume_data_assistant.py @@ -1562,7 +1562,6 @@ def quentin_expected_rule_based_profiler_configuration() -> Callable: }, "parameter_builders": [ { - "metric_domain_kwargs": "$domain.domain_kwargs", "replace_nan_with_zero": True, "name": "table_row_count", "module_name": "great_expectations.rule_based_profiler.parameter_builder.metric_multi_batch_parameter_builder",
[BUGFIX] Insure TABLE Domain Metrics Do Not Get Column Key From Column Type Rule Domain Builder (#<I>)
great-expectations_great_expectations
train
1755736fa740fc7646e581ffcb2d1f2a5f30f7a4
diff --git a/src/router.js b/src/router.js index <HASH>..<HASH> 100644 --- a/src/router.js +++ b/src/router.js @@ -624,7 +624,7 @@ function getEntryFromURL(url) { let config; const [pathname, search] = url.hash.split("?"); - if (pathname) { + if (pathname && pathname.match(/^#@.+-.+/)) { config = getConfigById(pathname.split("@")[1]); url = new URL(`?${search}`, window.location.origin); }
fix(router): use hash from url only when view id is detected
hybridsjs_hybrids
train
1bab1f156c5d37a2348d98452b67f7db8ef6db6b
diff --git a/src/consts/base.js b/src/consts/base.js index <HASH>..<HASH> 100644 --- a/src/consts/base.js +++ b/src/consts/base.js @@ -20,6 +20,6 @@ export const ON_ERROR = '__COLLECTION_TMP__onError'; export const - CACHE_VERSION = 23, + CACHE_VERSION = 24, CACHE_KEY = '__COLLECTION_CACHE__', CACHE_VERSION_KEY = '__COLLECTION_CACHE_VERSION__';
:arrow_up: CACHE_VERSION
kobezzza_Collection
train
bc6ce703af0d36e55ff614934660ce46a5bc5d98
diff --git a/core/peer/peer.go b/core/peer/peer.go index <HASH>..<HASH> 100644 --- a/core/peer/peer.go +++ b/core/peer/peer.go @@ -450,6 +450,17 @@ func GetLedger(cid string) ledger.PeerLedger { return nil } +// GetResourcesConfig returns the resources configuration of the chain with channel ID. Note that this +// call returns nil if chain cid has not been created. +func GetResourcesConfig(cid string) resourcesconfig.Resources { + chains.RLock() + defer chains.RUnlock() + if c, ok := chains.list[cid]; ok { + return c.cs.bundleSource.StableBundle() + } + return nil +} + // GetChannelConfig returns the channel configuration of the chain with channel ID. Note that this // call returns nil if chain cid has not been created. func GetChannelConfig(cid string) channelconfig.Resources { diff --git a/core/peer/support.go b/core/peer/support.go index <HASH>..<HASH> 100644 --- a/core/peer/support.go +++ b/core/peer/support.go @@ -43,8 +43,12 @@ func (s *supportImpl) GetApplicationConfig(cid string) (channelconfig.Applicatio } func (s *supportImpl) ChaincodeByName(chainname, ccname string) (resourcesconfig.ChaincodeDefinition, bool) { - // FIXME: implement me properly - return nil, false + rc := GetResourcesConfig(chainname) + if rc == nil { + return nil, false + } + + return rc.ChaincodeRegistry().ChaincodeByName(ccname) } type SupportFactoryImpl struct {
[FAB-<I>] add implementation of ChaincodeByName This change set introduces the proper implementation for the ChaincodeByName function exposed by the Support interface for the endorser. Change-Id: If<I>b5e<I>a4cffcbbd<I>f<I>fe5e4b0c
hyperledger_fabric
train
9daac350e9cbf7f1337e0a8956c0382b2def6391
diff --git a/mongo_orchestration/replica_sets.py b/mongo_orchestration/replica_sets.py index <HASH>..<HASH> 100644 --- a/mongo_orchestration/replica_sets.py +++ b/mongo_orchestration/replica_sets.py @@ -70,6 +70,9 @@ class ReplicaSet(BaseModel): self.member_create(member, index) for index, member in enumerate(members) ]} + if 'rsSettings' in rs_params: + config['settings'] = rs_params['rsSettings'] + logger.debug("replica config: {config}".format(**locals())) if not self.repl_init(config): self.cleanup() diff --git a/tests/test_replica_sets.py b/tests/test_replica_sets.py index <HASH>..<HASH> 100644 --- a/tests/test_replica_sets.py +++ b/tests/test_replica_sets.py @@ -611,6 +611,18 @@ class ReplicaSetTestCase(unittest.TestCase): # No ConnectionFailure/AutoReconnect. connected(pymongo.MongoClient(host)) + def test_rs_settings(self): + self.repl_cfg = { + 'rsSettings': {'chainingAllowed': True}, + 'members': [{}] + } + self.repl = ReplicaSet(self.repl_cfg) + if SERVER_VERSION >= (2, 8): + config = self.repl.connection().admin.command('replSetGetConfig') + else: + config = self.repl.connection().local.system.replset.find_one() + self.assertTrue(config['config']['settings'].get('chainingAllowed')) + class ReplicaSetSSLTestCase(SSLTestCase):
Configure replset settings with 'rsSettings'.
10gen_mongo-orchestration
train
e1075a482154d24e397b92e81c84ab901ebfd4d6
diff --git a/authapi/serializers.py b/authapi/serializers.py index <HASH>..<HASH> 100644 --- a/authapi/serializers.py +++ b/authapi/serializers.py @@ -4,30 +4,30 @@ from rest_framework import serializers from authapi.models import SeedOrganization, SeedTeam, SeedPermission -class OrganizationSummarySerializer(serializers.HyperlinkedModelSerializer): +class OrganizationSummarySerializer(serializers.ModelSerializer): class Meta: model = SeedOrganization fields = ('id', 'url') -class UserSummarySerializer(serializers.HyperlinkedModelSerializer): +class UserSummarySerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'url') -class TeamSummarySerializer(serializers.HyperlinkedModelSerializer): +class TeamSummarySerializer(serializers.ModelSerializer): class Meta: model = SeedTeam fields = ('id', 'url') -class PermissionSerializer(serializers.HyperlinkedModelSerializer): +class PermissionSerializer(serializers.ModelSerializer): class Meta: model = SeedPermission -class OrganizationSerializer(serializers.HyperlinkedModelSerializer): +class OrganizationSerializer(serializers.ModelSerializer): teams = TeamSummarySerializer( many=True, source='seedteam_set', read_only=True) users = UserSummarySerializer(many=True, read_only=True) @@ -37,7 +37,7 @@ class OrganizationSerializer(serializers.HyperlinkedModelSerializer): fields = ('id', 'url', 'teams', 'users') -class TeamSerializer(serializers.HyperlinkedModelSerializer): +class TeamSerializer(serializers.ModelSerializer): users = UserSummarySerializer(many=True, read_only=True) permissions = PermissionSerializer(many=True, read_only=True) @@ -46,7 +46,7 @@ class TeamSerializer(serializers.HyperlinkedModelSerializer): fields = ('id', 'permissions', 'users', 'url', 'organization') -class UserSerializer(serializers.HyperlinkedModelSerializer): +class UserSerializer(serializers.ModelSerializer): teams = TeamSummarySerializer( many=True, source='seedteam_set', read_only=True) organizations = OrganizationSummarySerializer(
Change to ModelSerializer, we don't actually want HyperlinkedModelSerializer
praekeltfoundation_seed-auth-api
train
52a69115ad2a871d890eca9999ac04f235f718de
diff --git a/tests/test_prediction_server.py b/tests/test_prediction_server.py index <HASH>..<HASH> 100644 --- a/tests/test_prediction_server.py +++ b/tests/test_prediction_server.py @@ -6,7 +6,7 @@ from sklearn.datasets import load_iris, load_boston from serveit.sklearn_server import PredictionServer -class PredictionServerTest(): +class PredictionServerTest(object): """Base class to test the prediction server. PredictionServerTest should be inherited by a class that has a `clf` classifier diff --git a/tests/test_sklearn_server.py b/tests/test_sklearn_server.py index <HASH>..<HASH> 100644 --- a/tests/test_sklearn_server.py +++ b/tests/test_sklearn_server.py @@ -7,7 +7,7 @@ from serveit.sklearn_server import SklearnServer from test_prediction_server import PredictionServerTest -class SklearnServerTest(PredictionServerTest): +class SklearnServerTest(PredictionServerTest, object): """Base class to test the Scikit-Learn server. SklearnServerTest should be inherited by a class that has a sklearn `clf`
Ensure base testing classes are new-style - inherit from object
rtlee9_serveit
train
ad1faa4cc0816d5a5733b7d48d6c5ba91157032c
diff --git a/tests/perf_unicorn.py b/tests/perf_unicorn.py index <HASH>..<HASH> 100644 --- a/tests/perf_unicorn.py +++ b/tests/perf_unicorn.py @@ -19,9 +19,6 @@ def perf_unicorn_0(): pg_unicorn.run() elapsed = time.time() - start - if len(pg_unicorn.errored) > 0: - pg_unicorn.errored[0].debug() - print "Elapsed %f sec" % elapsed print pg_unicorn.one_deadended @@ -36,9 +33,6 @@ def perf_unicorn_1(): pg_unicorn.run() elapsed = time.time() - start - if len(pg_unicorn.errored) > 0: - pg_unicorn.errored[0].debug() - print "Elapsed %f sec" % elapsed print pg_unicorn.one_deadended
remove debug statements from tests/perf_unicorn.py
angr_angr
train
9a4ffbbb5395cc3ec769f2a874638feefc7fc8c4
diff --git a/src/Sulu/Bundle/TagBundle/Tests/Functional/Controller/TagControllerTest.php b/src/Sulu/Bundle/TagBundle/Tests/Functional/Controller/TagControllerTest.php index <HASH>..<HASH> 100644 --- a/src/Sulu/Bundle/TagBundle/Tests/Functional/Controller/TagControllerTest.php +++ b/src/Sulu/Bundle/TagBundle/Tests/Functional/Controller/TagControllerTest.php @@ -100,8 +100,8 @@ class TagControllerTest extends DatabaseTestCase $response = json_decode($client->getResponse()->getContent()); $this->assertEquals(2, $response->total); - $this->assertEquals('tag1', $response->_embedded[0]->name); - $this->assertEquals('tag2', $response->_embedded[1]->name); + $this->assertEquals('tag1', $response->_embedded->tags[0]->name); + $this->assertEquals('tag2', $response->_embedded->tags[1]->name); } public function testGetByIdNotExisting() @@ -461,12 +461,12 @@ class TagControllerTest extends DatabaseTestCase $response = json_decode($client->getResponse()->getContent()); $this->assertEquals(6, $response->total); - $this->assertEquals('tag1', $response->_embedded[0]->name); - $this->assertEquals('tag2', $response->_embedded[1]->name); - $this->assertEquals('tag3', $response->_embedded[2]->name); - $this->assertEquals('tag4', $response->_embedded[3]->name); - $this->assertEquals('tag5', $response->_embedded[4]->name); - $this->assertEquals('tag6', $response->_embedded[5]->name); + $this->assertEquals('tag1', $response->_embedded->tags[0]->name); + $this->assertEquals('tag2', $response->_embedded->tags[1]->name); + $this->assertEquals('tag3', $response->_embedded->tags[2]->name); + $this->assertEquals('tag4', $response->_embedded->tags[3]->name); + $this->assertEquals('tag5', $response->_embedded->tags[4]->name); + $this->assertEquals('tag6', $response->_embedded->tags[5]->name); } @@ -543,10 +543,10 @@ class TagControllerTest extends DatabaseTestCase $response = json_decode($client->getResponse()->getContent()); $this->assertEquals(4, $response->total); - $this->assertEquals('tag1', $response->_embedded[0]->name); - $this->assertEquals('tag2', $response->_embedded[1]->name); - $this->assertEquals('tag11', $response->_embedded[2]->name); - $this->assertEquals('tag22', $response->_embedded[3]->name); + $this->assertEquals('tag1', $response->_embedded->tags[0]->name); + $this->assertEquals('tag2', $response->_embedded->tags[1]->name); + $this->assertEquals('tag11', $response->_embedded->tags[2]->name); + $this->assertEquals('tag22', $response->_embedded->tags[3]->name); } }
update tests for rest refractoring
sulu_sulu
train
84a4498eb565328d2fe92a1f145c33d6425fcc99
diff --git a/lib/more_core_extensions/core_ext/array/inclusions.rb b/lib/more_core_extensions/core_ext/array/inclusions.rb index <HASH>..<HASH> 100644 --- a/lib/more_core_extensions/core_ext/array/inclusions.rb +++ b/lib/more_core_extensions/core_ext/array/inclusions.rb @@ -7,6 +7,7 @@ module MoreCoreExtensions # [1, 2, 3].include_any?(1, 4) #=> true # [1, 2, 3].include_any?(4, 5) #=> false def include_any?(*items) + items = items.first if items.length == 1 && items.first.kind_of?(Array) !(self & items).empty? end @@ -17,6 +18,7 @@ module MoreCoreExtensions # [1, 2, 3].include_none?(1, 4) #=> false # [1, 2, 3].include_none?(4, 5) #=> true def include_none?(*items) + items = items.first if items.length == 1 && items.first.kind_of?(Array) (self & items).empty? end @@ -27,6 +29,7 @@ module MoreCoreExtensions # [1, 2, 3].include_all?(1, 4) #=> false # [1, 2, 3].include_all?(4, 5) #=> false def include_all?(*items) + items = items.first if items.length == 1 && items.first.kind_of?(Array) (items - self).empty? end diff --git a/spec/core_ext/array/inclusions_spec.rb b/spec/core_ext/array/inclusions_spec.rb index <HASH>..<HASH> 100644 --- a/spec/core_ext/array/inclusions_spec.rb +++ b/spec/core_ext/array/inclusions_spec.rb @@ -3,30 +3,42 @@ describe Array do expect([1, 2, 3].include_any?(1, 2)).to be_truthy expect([1, 2, 3].include_any?(1, 4)).to be_truthy expect([1, 2, 3].include_any?(4, 5)).to be_falsey + expect([1, 2, 3].include_any?([1, 4])).to be_truthy + expect([1, 2, 3].include_any?([4, 5])).to be_falsey expect(['1', '2', '3'].include_any?('1', '2')).to be_truthy expect(['1', '2', '3'].include_any?('1', '4')).to be_truthy expect(['1', '2', '3'].include_any?('4', '5')).to be_falsey + expect(['1', '2', '3'].include_any?(['1', '4'])).to be_truthy + expect(['1', '2', '3'].include_any?(['4', '5'])).to be_falsey end it '#include_none?' do expect([1, 2, 3].include_none?(1, 2)).to be_falsey expect([1, 2, 3].include_none?(1, 4)).to be_falsey expect([1, 2, 3].include_none?(4, 5)).to be_truthy + expect([1, 2, 3].include_none?([1, 4])).to be_falsey + expect([1, 2, 3].include_none?([4, 5])).to be_truthy expect(['1', '2', '3'].include_none?('1', '2')).to be_falsey expect(['1', '2', '3'].include_none?('1', '4')).to be_falsey expect(['1', '2', '3'].include_none?('4', '5')).to be_truthy + expect(['1', '2', '3'].include_none?(['1', '4'])).to be_falsey + expect(['1', '2', '3'].include_none?(['4', '5'])).to be_truthy end it '#include_all?' do expect([1, 2, 3].include_all?(1, 2)).to be_truthy expect([1, 2, 3].include_all?(1, 4)).to be_falsey expect([1, 2, 3].include_all?(4, 5)).to be_falsey + expect([1, 2, 3].include_all?([1, 2])).to be_truthy + expect([1, 2, 3].include_all?([1, 4])).to be_falsey expect(['1', '2', '3'].include_all?('1', '2')).to be_truthy expect(['1', '2', '3'].include_all?('1', '4')).to be_falsey expect(['1', '2', '3'].include_all?('4', '5')).to be_falsey + expect(['1', '2', '3'].include_all?(['1', '2'])).to be_truthy + expect(['1', '2', '3'].include_all?(['1', '4'])).to be_falsey end it "#includes_index?" do
Array#include_any? and friends now accept a single argument Array. Fixes: `[1, 2, 3].include_any?([1, 4])` returning false It should behave the same as `[1, 2, 3].include_any?(1, 4)` Single argument Arrays are splat so [1, 4] becomes [[1, 4]]. We have to grab the first item of the multidimensional array if it's a single subarray.
ManageIQ_more_core_extensions
train
a39add76c983034837b35f77649cfbb2a3cb51b6
diff --git a/src/Resource.js b/src/Resource.js index <HASH>..<HASH> 100644 --- a/src/Resource.js +++ b/src/Resource.js @@ -85,6 +85,46 @@ function Resource(name, url, options) { this.xhr = null; /** + * Describes if this resource was loaded as json. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isJson = false; + + /** + * Describes if this resource was loaded as xml. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isXml = false; + + /** + * Describes if this resource was loaded as an image tag. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isImage = false; + + /** + * Describes if this resource was loaded as an audio tag. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isAudio = false; + + /** + * Describes if this resource was loaded as a video tag. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isVideo = false; + + /** * The `dequeue` method that will be used a storage place for the async queue dequeue method * used privately by the loader. * @@ -245,6 +285,8 @@ Resource.prototype._loadImage = function () { this.data.src = this.url; + this.isImage = true; + this.data.addEventListener('error', this._boundOnError, false); this.data.addEventListener('load', this._boundComplete, false); this.data.addEventListener('progress', this._boundOnProgress, false); @@ -267,6 +309,8 @@ Resource.prototype._loadElement = function (type) { this.data.appendChild(this._createSource(type, this.url)); } + this['is' + type[0].toUpperCase() + type.substring(1)] = true; + this.data.addEventListener('error', this._boundOnError, false); this.data.addEventListener('load', this._boundComplete, false); this.data.addEventListener('progress', this._boundOnProgress, false); @@ -441,6 +485,7 @@ Resource.prototype._xhrOnLoad = function () { else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) { try { this.data = JSON.parse(xhr.responseText); + this.isJson = true; } catch(e) { this.error = new Error('Error trying to parse loaded json:', e); } @@ -457,6 +502,7 @@ Resource.prototype._xhrOnLoad = function () { div.innerHTML = xhr.responseText; this.data = div; } + this.isXml = true; } catch (e) { this.error = new Error('Error trying to parse loaded xml:', e); } diff --git a/src/middlewares/parsing/blob.js b/src/middlewares/parsing/blob.js index <HASH>..<HASH> 100644 --- a/src/middlewares/parsing/blob.js +++ b/src/middlewares/parsing/blob.js @@ -22,6 +22,8 @@ module.exports = function () { resource.data = new Image(); resource.data.src = 'data:' + type + ';base64,' + b64.encodeBinary(resource.xhr.responseText); + resource.isImage = true; + // wait until the image loads and then callback resource.data.onload = function () { resource.data.onload = null; @@ -38,6 +40,8 @@ module.exports = function () { resource.data = new Image(); resource.data.src = src; + resource.isImage = true; + // cleanup the no longer used blob after the image loads resource.data.onload = function () { URL.revokeObjectURL(src);
add support for checking data types with is*
englercj_resource-loader
train
80856acdfd623cd0838c9df507970b2077044159
diff --git a/src/angular-dragdrop.js b/src/angular-dragdrop.js index <HASH>..<HASH> 100644 --- a/src/angular-dragdrop.js +++ b/src/angular-dragdrop.js @@ -47,7 +47,7 @@ var jqyoui = angular.module('ngDragDrop', []).service('ngDragDropService', ['$ti // call either $scoped method i.e. $scope.dropCallback or constructor's method i.e. this.dropCallback. // Removing scope.$apply call that was performance intensive (especially onDrag) and does not require it // always. So call it within the callback if needed. - return (scope[callback] || scope[constructor][callback]).apply(scope, args); + return (scope[callback] || scope[constructor][callback]).apply(scope[callback] ? scope : scope[constructor], args); function extract(callbackName) { var atStartBracket = callbackName.indexOf('(') !== -1 ? callbackName.indexOf('(') : callbackName.length,
fix(*): Closes #<I> - pass right context in case of ctrlAs syntax
codef0rmer_angular-dragdrop
train
89aef82b68a9205ba08430c62c1651b73835dbf6
diff --git a/claripy/operations.py b/claripy/operations.py index <HASH>..<HASH> 100644 --- a/claripy/operations.py +++ b/claripy/operations.py @@ -362,6 +362,10 @@ def _flatten_simplifier(op_name, *args): if not any(isinstance(a, ast.Base) and a.op == op_name for a in args): return + # we cannot further flatten if any top-level argument has non-relocatable annotaitons + if any(not anno.relocatable for anno in itertools.chain.from_iterable(arg.annotations for arg in args)): + return + new_args = tuple(itertools.chain.from_iterable( (a.args if isinstance(a, ast.Base) and a.op == op_name else (a,)) for a in args )) diff --git a/tests/test_annotations.py b/tests/test_annotations.py index <HASH>..<HASH> 100644 --- a/tests/test_annotations.py +++ b/tests/test_annotations.py @@ -104,6 +104,15 @@ def test_annotations(): assert claripy.backends.z3.convert(x).eq(claripy.backends.z3.convert(x3)) + const = claripy.BVV(1, 32) + consta = const.annotate(AnnotationB('a', 0)) + const1 = consta + 1 + const1a = const1.annotate(AnnotationB('b', 1)) + const2 = const1a + 1 + # const2 should be (const1a + 1), instead of (1 + 1 + 1) + # the flatten simplifier for __add__ should not be applied as AnnotationB is not relocatable (and not eliminatable) + assert const2.depth == 3 + def test_eagerness(): x = claripy.BVV(10, 32).annotate(AnnotationD()) y = x + 1
Fix the issue where flatten simplifiers lose AST annotations.
angr_claripy
train
7c38e42d2e9046196483532adb6199cd4085a58a
diff --git a/js/commands/AccessTokenCommands.js b/js/commands/AccessTokenCommands.js index <HASH>..<HASH> 100644 --- a/js/commands/AccessTokenCommands.js +++ b/js/commands/AccessTokenCommands.js @@ -48,63 +48,63 @@ var AccessTokenCommands = function (cli, options) { util.inherits(AccessTokenCommands, BaseCommand); AccessTokenCommands.prototype = extend(BaseCommand.prototype, { options: null, - name: "token", + name: "token", description: "tools to help you manage access tokens on your account", init: function () { this.addOption("list", this.listAccessTokens.bind(this), "List all access tokens for your account"); - //this.addOption("revoke", this.revokeAccessToken.bind(this), "Revoke an access token"); - //this.addOption("new", this.createAccessToken.bind(this), "Create a new access token"); + //this.addOption("revoke", this.revokeAccessToken.bind(this), "Revoke an access token"); + //this.addOption("new", this.createAccessToken.bind(this), "Create a new access token"); }, - checkArguments: function (args) { - this.options = this.options || {}; - - if (!this.options.force) { - this.options.force = utilities.tryParseArgs(args, - "--force", - null - ); - } - }, - - getAccessTokens: function (args) { - console.error("Checking with the cloud..."); - var tmp = when.defer(); - - pipeline([ - prompts.getCredentials, - function (creds) { - var api = new ApiClient(settings.apiUrl); - tmp.resolve(api.listTokens(creds[0], creds[1])); - } - ]); - - return tmp.promise; - }, - - listAccessTokens: function (args) { - - when(this.getAccessTokens(args)).then(function (tokens) { - try { - var lines = []; - for (var i = 0; i < tokens.length; i++) { - // TODO: put a marker on settings.acccess_token - // TODO: sort by expiration date - token = tokens[i]; - lines.push('Token: ' + token.token); - lines.push(' Expires At: ' + token.expires_at); - lines.push(' Client: ' + token.client); - } - console.log(lines.join("\n")); - } - catch (ex) { - console.error("Error during list " + ex); - } - }, function(err) { - console.log("Please make sure you're online and logged in."); - }); - }, + checkArguments: function (args) { + this.options = this.options || {}; + + if (!this.options.force) { + this.options.force = utilities.tryParseArgs(args, + "--force", + null + ); + } + }, + + getAccessTokens: function (args) { + console.error("Checking with the cloud..."); + var tmp = when.defer(); + + pipeline([ + prompts.getCredentials, + function (creds) { + var api = new ApiClient(settings.apiUrl); + tmp.resolve(api.listTokens(creds[0], creds[1])); + } + ]); + + return tmp.promise; + }, + + listAccessTokens: function (args) { + + when(this.getAccessTokens(args)).then(function (tokens) { + try { + var lines = []; + for (var i = 0; i < tokens.length; i++) { + // TODO: put a marker on settings.acccess_token + // TODO: sort by expiration date + token = tokens[i]; + lines.push('Token: ' + token.token); + lines.push(' Expires At: ' + token.expires_at); + lines.push(' Client: ' + token.client); + } + console.log(lines.join("\n")); + } + catch (ex) { + console.error("Error during list " + ex); + } + }, function(err) { + console.log("Please make sure you're online and logged in."); + }); + }, _: null }); diff --git a/js/lib/ApiClient.js b/js/lib/ApiClient.js index <HASH>..<HASH> 100644 --- a/js/lib/ApiClient.js +++ b/js/lib/ApiClient.js @@ -163,7 +163,7 @@ ApiClient.prototype = { return dfd.promise; }, - //DELETE /v1/access_tokens/{ACCESS_TOKEN} + //DELETE /v1/access_tokens/{ACCESS_TOKEN} removeAccessToken: function (username, password, access_token) { console.log("removing access_token " + access_token); @@ -199,7 +199,7 @@ ApiClient.prototype = { return dfd.promise; }, - //GET /v1/access_tokens + //GET /v1/access_tokens listTokens: function (username, password) { var that = this; var dfd = when.defer();
retab: gah! Forgot to switch my tab hat for spaces Harumph. I need to figure out a vim autocmd for "do the right thing re: tabs".
particle-iot_particle-cli
train
61d658011f6a57001040e7e27e60dbab8ea467d5
diff --git a/rest_framework_extensions/cache/decorators.py b/rest_framework_extensions/cache/decorators.py index <HASH>..<HASH> 100644 --- a/rest_framework_extensions/cache/decorators.py +++ b/rest_framework_extensions/cache/decorators.py @@ -85,10 +85,15 @@ class CacheResponse: response.render() if not response.status_code >= 400 or self.cache_errors: + # django 3.0 has not .items() method, django 3.2 has not ._headers + if hasattr(response, '_headers'): + headers = response._headers.copy() + else: + headers = {k: (k, v) for k, v in response.items()} response_triple = ( response.rendered_content, response.status_code, - response._headers.copy() + headers ) self.cache.set(key, response_triple, timeout) else: @@ -97,7 +102,6 @@ class CacheResponse: response = HttpResponse(content=content, status=status) for k, v in headers.values(): response[k] = v - if not hasattr(response, '_closable_objects'): response._closable_objects = [] diff --git a/tests_app/tests/unit/cache/decorators/tests.py b/tests_app/tests/unit/cache/decorators/tests.py index <HASH>..<HASH> 100644 --- a/tests_app/tests/unit/cache/decorators/tests.py +++ b/tests_app/tests/unit/cache/decorators/tests.py @@ -184,10 +184,15 @@ class CacheResponseTest(TestCase): view_instance.finalize_response( request=self.request, response=cached_response) cached_response.render() + # django 3.0 has not .items() method, django 3.2 has not ._headers + if hasattr(cached_response, '_headers'): + headers = cached_response._headers + else: + headers = {k: (k, v) for k, v in cached_response.items()} response_dict = ( cached_response.rendered_content, cached_response.status_code, - cached_response._headers + headers ) self.cache.set('cache_response_key', response_dict) @@ -313,14 +318,23 @@ class CacheResponseTest(TestCase): view_instance.finalize_response( request=self.request, response=cached_response) cached_response.render() + # django 3.0 has not .items() method, django 3.2 has not ._headers + if hasattr(cached_response, '_headers'): + headers = {k: list(v) for k, v in cached_response._headers.items()} + else: + headers = {k: (k, v) for k, v in cached_response.items()} response_dict = ( cached_response.rendered_content, cached_response.status_code, - {k: list(v) for k, v in cached_response._headers.items()} + headers ) self.cache.set('cache_response_key', response_dict) response = view_instance.dispatch(request=self.request) - self.assertTrue(all(isinstance(v, tuple) + # django 3.0 has not .items() method, django 3.2 has not ._headers + if hasattr(response, '_headers'): + self.assertTrue(all(isinstance(v, tuple) for v in response._headers.values())) - self.assertEqual(response._headers['test'], ('Test', 'foo')) + self.assertEqual(response._headers['test'], ('Test', 'foo')) + else: + self.assertEqual(response['test'], 'foo') diff --git a/tox.ini b/tox.ini index <HASH>..<HASH> 100644 --- a/tox.ini +++ b/tox.ini @@ -2,6 +2,7 @@ envlist = py{36,37,38}-django{22}-drf{39,310,311,312} py{36,37,38}-django{30}-drf{310,311,312} py{36,37,38}-django{31}-drf{311,312} + py{36,37,38}-django{32}-drf{311,312} [testenv] @@ -19,6 +20,7 @@ deps= django22: Django>=2.2,<3.0 django30: Django>=3.0,<3.1 django31: Django>=3.1,<3.2 + django32: Django>=3.2 setenv = PYTHONPATH = {toxinidir}:{toxinidir}/tests_app commands =
django <I> compatibility: do not use _headers need to use .headers or .items() instead. However we must notice that internal structure has changed : instead of key.lower() => (key with initial casing, value) we now have key => value and override of __getitem__ and other same family methods. Therefore, for compatibility we emulate this behaviour
chibisov_drf-extensions
train
6d5c7c7cd4019cd09030f9ca55dc84ff5f91c8e2
diff --git a/pom.xml b/pom.xml index <HASH>..<HASH> 100644 --- a/pom.xml +++ b/pom.xml @@ -44,16 +44,12 @@ <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> - <version>2.12</version> + <version>3.0.0-M3</version> <configuration> <junitArtifactName>junit:junit</junitArtifactName> - <encoding>UTF-8</encoding> <inputEncoding>UTF-8</inputEncoding> <outputEncoding>UTF-8</outputEncoding> <argLine>-ea -Dfile.encoding=UTF-8</argLine> - <excludes> - <exclude>**/it/*</exclude> - </excludes> </configuration> </plugin> <plugin> @@ -171,7 +167,7 @@ <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> - <version>4.12</version> + <version>4.7</version> <scope>test</scope> </dependency> <dependency> diff --git a/src/main/java/js/container/ManagedMethod.java b/src/main/java/js/container/ManagedMethod.java index <HASH>..<HASH> 100644 --- a/src/main/java/js/container/ManagedMethod.java +++ b/src/main/java/js/container/ManagedMethod.java @@ -153,7 +153,7 @@ final class ManagedMethod implements ManagedMethodSPI { * @param requestPath request URI path for this method, possible null. */ void setRequestPath(String requestPath) { - this.requestPath = requestPath != null ? requestPath : Strings.toDashCase(method.getName()); + this.requestPath = requestPath != null ? requestPath : Strings.memberToDashCase(method.getName()); } /** diff --git a/src/test/java/js/mvc/test/FileResourceUnitTest.java b/src/test/java/js/mvc/test/FileResourceUnitTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/js/mvc/test/FileResourceUnitTest.java +++ b/src/test/java/js/mvc/test/FileResourceUnitTest.java @@ -9,6 +9,7 @@ import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; +import java.util.TimeZone; import javax.servlet.ServletOutputStream; import javax.servlet.WriteListener; @@ -70,7 +71,7 @@ public class FileResourceUnitTest { assertEquals("no-cache;no-store", httpResponse.headers.get("Cache-Control")); assertEquals("no-cache", httpResponse.headers.get("Pragma")); - assertEquals("Thu, 01 Jan 1970 02:00:00 GMT", httpResponse.headers.get("Expires")); + assertEquals("Thu, 01 Jan 1970 00:00:00", httpResponse.headers.get("Expires")); assertEquals("text/html;charset=UTF-8", httpResponse.headers.get("Content-Type")); assertEquals("497", httpResponse.headers.get("Content-Length")); assertEquals(497, httpResponse.stream.writeProbe); @@ -105,7 +106,8 @@ public class FileResourceUnitTest { @Override public void setDateHeader(String name, long value) { - DateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'"); + DateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss"); + dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); headers.put(name, dateFormat.format(new Date(value))); }
Fix test unit dependency on host time zone.
js-lib-com_tiny-container
train
fd43d3709e7fd84b201e0a80da0238b8b690191a
diff --git a/tests/py_test.py b/tests/py_test.py index <HASH>..<HASH> 100644 --- a/tests/py_test.py +++ b/tests/py_test.py @@ -162,9 +162,10 @@ class TestFuzz(unittest.TestCase): ''' Low level stress/fuzz test: serialize/deserialize a variety of different kinds of data in different combinations ''' - ofInt32Bytes = compat.binary_type([0x83, 0x33, 0x33, 0x33]) - ofInt64Bytes = compat.binary_type([0x84, 0x44, 0x44, 0x44, - 0x44, 0x44, 0x44, 0x44]) + binary_type = compat.binary_types[0] # this will always exist + ofInt32Bytes = binary_type([0x83, 0x33, 0x33, 0x33]) + ofInt64Bytes = binary_type([0x84, 0x44, 0x44, 0x44, + 0x44, 0x44, 0x44, 0x44]) overflowingInt32Val = flatbuffers.encode.Get(flatbuffers.packer.int32, ofInt32Bytes, 0) overflowingInt64Val = flatbuffers.encode.Get(flatbuffers.packer.int64,
Fix test using compat.binary_types (from March).
google_flatbuffers
train
a71e58c5d6dc89f224e457722647d2841c3554d6
diff --git a/chef/lib/chef/rest.rb b/chef/lib/chef/rest.rb index <HASH>..<HASH> 100644 --- a/chef/lib/chef/rest.rb +++ b/chef/lib/chef/rest.rb @@ -162,7 +162,7 @@ class Chef http_retries = 1 # TODO - Figure out how to test this block - I really have no idea how - # to do it wouthout actually calling http.request... + # to do it without actually calling http.request... begin res = http.request(req) do |response| if raw @@ -219,6 +219,7 @@ class Chef end run_request(:GET, create_url(res['location']), false, limit - 1, raw) else + Chef::Log.error("Failed REST request to: #{url}, #{res}") res.error! end end diff --git a/chefserverslice/lib/chefserverslice.rb b/chefserverslice/lib/chefserverslice.rb index <HASH>..<HASH> 100644 --- a/chefserverslice/lib/chefserverslice.rb +++ b/chefserverslice/lib/chefserverslice.rb @@ -113,8 +113,7 @@ if defined?(Merb::Plugins) # the slice is mounted at /chefserverslice - note that it comes before default_routes scope.match('/').to(:controller => 'nodes', :action =>'index').name(:top) # enable slice-level default routes by default - # [cb] disable default routing in favor of explicit (see scope.resources above) - #scope.default_routes + scope.default_routes end end
re-adding default routing to fix things up adding debugging to REST.rb
chef_chef
train
07a2c754b6534270553c6c75ffe5303c3fe0159a
diff --git a/tag/feature.py b/tag/feature.py index <HASH>..<HASH> 100644 --- a/tag/feature.py +++ b/tag/feature.py @@ -523,6 +523,17 @@ class Feature(object): return attributes @property + def ncbi_geneid(self): + values = self.get_attribute('Dbxref', as_list=True) + if values is None: + return None + for value in values: + if value.startswith('GeneID:'): + key, geneid = value.split(':') + return geneid + return None + + @property def cdslen(self): """ Translated length of this feature. diff --git a/tests/test_feature.py b/tests/test_feature.py index <HASH>..<HASH> 100644 --- a/tests/test_feature.py +++ b/tests/test_feature.py @@ -455,3 +455,35 @@ def test_pseudo_1(): assert parent.slug == 'cDNA_match@chr[1000, 6000]' assert repr(parent) == repr(feat_x) assert repr(parent) == repr(feat_z.pseudoify()) + + +def test_ncbi_geneid(): + gff3 = ('NW_007377440.1 Gnomon gene 63775 73670 . - . ' + 'ID=gene2;Name=LOC103504972;Dbxref=GeneID:103504972;gbkey=Gene;' + 'gene=LOC103504972;gene_biotype=protein_coding') + gene = Feature(gff3) + assert gene.ncbi_geneid == '103504972' + + gff3 = ('NW_007378253.1 Gnomon mRNA 103380 167368 . - . ' + 'ID=mRNA10000;Parent=gene9300;Name=XM_008477076.2;' + 'Dbxref=Genbank:XM_008477076.2,GeneID:103512317;gbkey=mRNA;' + 'gene=LOC103512317;model_evidence=Supporting evidence includes ' + 'similarity to: 5 Proteins%2C and 84%25 coverage of the annotated ' + 'genomic feature by RNAseq alignments;' + 'product=glutamine--fructose-6-phosphate aminotransferase ' + '[isomerizing] 2-like;transcript_id=XM_008477076.2') + mrna = Feature(gff3) + assert mrna.ncbi_geneid == '103512317' + + gff3 = ('NW_007377513.1 RefSeq cDNA_match 271974 274535 . + . ' + 'ID=cDNA_match42;Gap=M2086 D2 M474;Target=XM_008486908.2 1 2560 +;' + 'for_remapping=2;gap_count=1;num_ident=2840;num_mismatch=0;' + 'pct_coverage=100;pct_coverage_hiqual=100;' + 'pct_identity_gap=99.9296;pct_identity_ungap=100;rank=1') + match = Feature(gff3) + assert match.ncbi_geneid is None + + gff3 = ('chr atom region 1000 2000 . . . ' + 'Dbxref=MyDB:ID12345') + region = Feature(gff3) + assert region.ncbi_geneid is None
Step 1 of my evil plan to make it easier to parse various ID types
standage_tag
train
9e2a72245cfef3e10d5841c36f675b8e9b752083
diff --git a/glances/outputs/static/js/stats_controller.js b/glances/outputs/static/js/stats_controller.js index <HASH>..<HASH> 100644 --- a/glances/outputs/static/js/stats_controller.js +++ b/glances/outputs/static/js/stats_controller.js @@ -141,6 +141,10 @@ glancesApp.controller('statsController', function($scope, $http, $interval, $q, } } + _.remove(response['sensors'], function(sensor) { + return sensor.type == "battery" && _.isArray(sensor.value) && _.isEmpty(sensor.value); + }); + $scope.is_bsd = response['system'].os_name === 'FreeBSD'; $scope.is_linux = response['system'].os_name === 'Linux'; $scope.is_mac = response['system'].os_name === 'Darwin';
Remove empty battery in the web ui
nicolargo_glances
train
3c3a1ed1df2274f806af29259e2a32c544b84bb3
diff --git a/src/main/java/nl/topicus/jdbc/transaction/TransactionThread.java b/src/main/java/nl/topicus/jdbc/transaction/TransactionThread.java index <HASH>..<HASH> 100644 --- a/src/main/java/nl/topicus/jdbc/transaction/TransactionThread.java +++ b/src/main/java/nl/topicus/jdbc/transaction/TransactionThread.java @@ -17,12 +17,19 @@ import com.google.cloud.spanner.TransactionRunner.TransactionCallable; class TransactionThread extends Thread { + private static enum TransactionStatus + { + NOT_STARTED, RUNNING, SUCCESS, FAIL; + } + private DatabaseClient dbClient; private boolean stop; private boolean stopped; + private TransactionStatus status = TransactionStatus.NOT_STARTED; + private boolean commit; private List<Mutation> mutations = new ArrayList<>(40); @@ -40,37 +47,44 @@ class TransactionThread extends Thread @Override public void run() { + status = TransactionStatus.RUNNING; TransactionRunner runner = dbClient.readWriteTransaction(); - runner.run(new TransactionCallable<Void>() + synchronized (this) { - - @Override - public Void run(TransactionContext transaction) throws Exception + status = runner.run(new TransactionCallable<TransactionStatus>() { - while (!stop) + + @Override + public TransactionStatus run(TransactionContext transaction) throws Exception { - try + while (!stop) { - Statement statement = statements.take(); - if (!(statement.getSql().equals("commit") || statement.getSql().equals("rollback"))) + try + { + Statement statement = statements.take(); + if (!(statement.getSql().equals("commit") || statement.getSql().equals("rollback"))) + { + resultSets.put(transaction.executeQuery(statement)); + } + } + catch (InterruptedException e) { - resultSets.put(transaction.executeQuery(statement)); + System.err.println("Transaction interrupted while waiting for statement"); + stopped = true; + return TransactionStatus.FAIL; } } - catch (InterruptedException e) + + if (commit) { - System.err.println("Transaction interrupted while waiting for statement"); + transaction.buffer(mutations); } + stopped = true; + return TransactionStatus.SUCCESS; } - - if (commit) - { - transaction.buffer(mutations); - } - stopped = true; - return null; - } - }); + }); + this.notifyAll(); + } } ResultSet executeQuery(Statement statement) @@ -114,14 +128,17 @@ class TransactionThread extends Thread stop = true; // Add a null object in order to get the transaction thread to proceed statements.add(Statement.of(commit ? "commit" : "rollback")); - while (!stopped || this.isAlive()) + synchronized (this) { - try - { - Thread.sleep(0, 5); - } - catch (InterruptedException e) + while (!stopped || status == TransactionStatus.NOT_STARTED || status == TransactionStatus.RUNNING) { + try + { + this.wait(); + } + catch (InterruptedException e) + { + } } } }
changed waiting mechanism for transactions into standard Java wait/notify functionality
olavloite_spanner-jdbc
train
b5a2ec8a549d8fe16319667a87fd4ef3dbfc7e55
diff --git a/src/Aerys/Handlers/Websocket/Io/FrameWriter.php b/src/Aerys/Handlers/Websocket/Io/FrameWriter.php index <HASH>..<HASH> 100644 --- a/src/Aerys/Handlers/Websocket/Io/FrameWriter.php +++ b/src/Aerys/Handlers/Websocket/Io/FrameWriter.php @@ -15,12 +15,17 @@ class FrameWriter { private $currentFrame; private $buffer; private $bufferSize; + private $granularity = 65535; function __construct($destination) { $this->destination = $destination; $this->priorityFrameQueue = new FrameQueue; } + function setGranularity($bytes) { + $this->granularity = (int) $bytes; + } + function canWrite() { return ($this->currentFrame || $this->priorityFrameQueue->count()); } @@ -49,7 +54,11 @@ class FrameWriter { } writing: { - $bytesWritten = @fwrite($this->destination, $this->buffer); + $byteWriteLimit = ($this->bufferSize > $this->granularity) + ? $this->granularity + : $this->bufferSize; + + $bytesWritten = @fwrite($this->destination, $this->buffer, $byteWriteLimit); if ($bytesWritten === $this->bufferSize) { goto frame_complete;
Re-added IO granularity throttle on websocket frame writer
amphp_http-server
train
7e176b5115209b8a9d190eb13b4bfdee58b5458c
diff --git a/gcs/compose_objects.go b/gcs/compose_objects.go index <HASH>..<HASH> 100644 --- a/gcs/compose_objects.go +++ b/gcs/compose_objects.go @@ -36,6 +36,10 @@ func (b *bucket) makeComposeObjectsBody( r := storagev1.ComposeRequest{ Destination: &storagev1.Object{ Name: req.DstName, + + // We get an HTTP 400 if we don't set this. + // Cf. Google-internal bug 21588058. + ContentType: "application/octet-stream", }, }
Set a content type, to make GCS happy.
jacobsa_gcloud
train
05e651f038779e1c5b753b2b4a72a6f0348b88a0
diff --git a/salt/transport/tcp.py b/salt/transport/tcp.py index <HASH>..<HASH> 100644 --- a/salt/transport/tcp.py +++ b/salt/transport/tcp.py @@ -603,23 +603,22 @@ class TCPReqServerChannel(salt.transport.mixins.auth.AESReqServerMixin, salt.tra self.payload_handler = payload_handler self.io_loop = io_loop self.serial = salt.payload.Serial(self.opts) - if USE_LOAD_BALANCER: - self.req_server = LoadBalancerWorker(self.socket_queue, - self.handle_message, - io_loop=self.io_loop, - ssl_options=self.opts.get('ssl')) - else: - if salt.utils.platform.is_windows(): - self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - _set_tcp_keepalive(self._socket, self.opts) - self._socket.setblocking(0) - self._socket.bind((self.opts['interface'], int(self.opts['ret_port']))) - self.req_server = SaltMessageServer(self.handle_message, - io_loop=self.io_loop, - ssl_options=self.opts.get('ssl')) - self.req_server.add_socket(self._socket) - self._socket.listen(self.backlog) + with salt.utils.async.current_ioloop(self.io_loop): + if USE_LOAD_BALANCER: + self.req_server = LoadBalancerWorker(self.socket_queue, + self.handle_message, + ssl_options=self.opts.get('ssl')) + else: + if salt.utils.platform.is_windows(): + self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + _set_tcp_keepalive(self._socket, self.opts) + self._socket.setblocking(0) + self._socket.bind((self.opts['interface'], int(self.opts['ret_port']))) + self.req_server = SaltMessageServer(self.handle_message, + ssl_options=self.opts.get('ssl')) + self.req_server.add_socket(self._socket) + self._socket.listen(self.backlog) salt.transport.mixins.auth.AESReqServerMixin.post_fork(self, payload_handler, io_loop) @tornado.gen.coroutine @@ -704,6 +703,7 @@ class SaltMessageServer(tornado.tcpserver.TCPServer, object): ''' def __init__(self, message_handler, *args, **kwargs): super(SaltMessageServer, self).__init__(*args, **kwargs) + self.io_loop = tornado.ioloop.IOLoop.current() self.clients = [] self.message_handler = message_handler @@ -807,7 +807,9 @@ class TCPClientKeepAlive(tornado.tcpclient.TCPClient): stream = tornado.iostream.IOStream( sock, max_buffer_size=max_buffer_size) - return stream.connect(addr) + if tornado.version_info < (5,): + return stream.connect(addr) + return stream, stream.connect(addr) class SaltMessageClientPool(salt.transport.MessageClientPool): @@ -970,7 +972,8 @@ class SaltMessageClient(object): with salt.utils.async.current_ioloop(self.io_loop): self._stream = yield self._tcp_client.connect(self.host, self.port, - ssl_options=self.opts.get('ssl')) + ssl_options=self.opts.get('ssl'), + **kwargs) self._connecting_future.set_result(True) break except Exception as e:
fix _create_stream and tornado <I> This should be the last fix for tornado <I>
saltstack_salt
train
4e24ea8ef860433df6ca1f03b909cc6c2daf926e
diff --git a/spec/core/connect_spec.rb b/spec/core/connect_spec.rb index <HASH>..<HASH> 100644 --- a/spec/core/connect_spec.rb +++ b/spec/core/connect_spec.rb @@ -253,9 +253,10 @@ describe OSCRuby::Connect do end - context '#patch' + end + + context '#patch' - end end end \ No newline at end of file
made a mistake with the tests, fixing now
rajangdavis_osvc_ruby
train
f5f67cef4cc5b8fc62c251b05c943a4a0ffdb07d
diff --git a/src/util.py b/src/util.py index <HASH>..<HASH> 100644 --- a/src/util.py +++ b/src/util.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python -#-*- encoding: utf-8 -*- # # This file is part of python-gnupg, a Python wrapper around GnuPG. # Copyright © 2013 Isis Lovecruft, Andrej B.
Remove script headers from src/util.py.
isislovecruft_python-gnupg
train
00b61d88bf741bff98f1cd25bd85b4b108d2716c
diff --git a/java/src/com/google/template/soy/data/BaseSoyTemplateImpl.java b/java/src/com/google/template/soy/data/BaseSoyTemplateImpl.java index <HASH>..<HASH> 100644 --- a/java/src/com/google/template/soy/data/BaseSoyTemplateImpl.java +++ b/java/src/com/google/template/soy/data/BaseSoyTemplateImpl.java @@ -24,6 +24,7 @@ import static com.google.common.collect.Streams.stream; import com.google.common.base.Joiner; import com.google.common.base.Objects; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.html.types.SafeHtml; @@ -45,11 +46,9 @@ import com.google.template.soy.data.restricted.NullData; import com.google.template.soy.data.restricted.NumberData; import com.google.template.soy.data.restricted.StringData; import java.util.ArrayList; -import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.concurrent.Future; import java.util.function.Function; import javax.annotation.Nullable; @@ -114,12 +113,11 @@ public abstract class BaseSoyTemplateImpl implements SoyTemplate { // 3. They tend to be faster. // One downside is that they have less efficient entrySet() implementations, but we can // easily workaround that. - // fairly strong contract with our subclass so it is ok. We know that this method is just - // returning a static final field. - private final Map<SoyTemplateParam<?>, SoyValueProvider> data = - new IdentityHashMap<>(/* expectedMaxSize= */ allParams().size()); + private final IdentityHashMap<SoyTemplateParam<?>, SoyValueProvider> data; - protected AbstractBuilder() {} + protected AbstractBuilder(int numParams) { + this.data = new IdentityHashMap<>(/* expectedMaxSize= */ numParams); + } @Override public final T build() { @@ -156,6 +154,9 @@ public abstract class BaseSoyTemplateImpl implements SoyTemplate { @Override public final <V> B setParam(SoyTemplateParam<? super V> param, V value) { + // TODO(lukes): allParams uses .equals, perhaps we should use == so people don't use one + // templates param that happens to have the same name/type in a different template. + // Or maybe we should add some kind of 'cast' method to adapt one builder to another? if (!allParams().contains(param)) { throw new IllegalArgumentException( "No param in " + this.getClass().getName() + " like " + param); @@ -404,7 +405,7 @@ public abstract class BaseSoyTemplateImpl implements SoyTemplate { ImmutableMap<String, SoyValueProvider> finalData = finalDataBuilder.build(); if (checkRequired) { - Set<String> missingParams = getMissingParamNames(finalData); + List<String> missingParams = getMissingParamNames(finalData); if (!missingParams.isEmpty()) { throw new IllegalStateException( "Missing required params: " + Joiner.on(", ").join(missingParams)); @@ -413,12 +414,14 @@ public abstract class BaseSoyTemplateImpl implements SoyTemplate { return finalData; } - private Set<String> getMissingParamNames(Map<String, ?> data) { - Set<String> missing = ImmutableSet.of(); - for (SoyTemplateParam<?> param : allParams()) { + private List<String> getMissingParamNames(Map<String, ?> data) { + List<String> missing = ImmutableList.of(); + ImmutableList<SoyTemplateParam<?>> params = allParams().asList(); + for (int i = 0; i < params.size(); i++) { + SoyTemplateParam<?> param = params.get(i); if (param.isRequired() && !data.containsKey(param.getName())) { if (missing.isEmpty()) { - missing = new HashSet<>(); + missing = new ArrayList<>(); } missing.add(param.getName()); } @@ -441,7 +444,9 @@ public abstract class BaseSoyTemplateImpl implements SoyTemplate { private final Map<SoyTemplateParam<?>, List<SoyValueProvider>> accummulatorData = new IdentityHashMap<>(); - protected AbstractBuilderWithAccumulatorParameters() {} + protected AbstractBuilderWithAccumulatorParameters(int numParams) { + super(numParams); + } @Override void prepareDataForBuild() { diff --git a/java/src/com/google/template/soy/invocationbuilders/passes/GenInvocationBuildersVisitor.java b/java/src/com/google/template/soy/invocationbuilders/passes/GenInvocationBuildersVisitor.java index <HASH>..<HASH> 100644 --- a/java/src/com/google/template/soy/invocationbuilders/passes/GenInvocationBuildersVisitor.java +++ b/java/src/com/google/template/soy/invocationbuilders/passes/GenInvocationBuildersVisitor.java @@ -390,6 +390,7 @@ public final class GenInvocationBuildersVisitor // Constructor for Foo.Builder. ilb.appendLine("private Builder() {"); ilb.increaseIndent(); + ilb.appendLine("super(", nonInjectedParams.size(), ");"); appendRecordListInitializations(ilb, nonInjectedParams); ilb.decreaseIndent(); ilb.appendLine("}");
Tiny tweaks to invocation builders Instead of having BaseSoyTemplateImpl.Builder call allParams() from its constructor, just have the base class pass the number of params up. This avoids the weirdness of calling an abstract method from a constructor. GITHUB_BREAKING_CHANGES=none ------------- Created by MOE: <URL>
google_closure-templates
train
c4f488c9d67e1b525083ff8c2fe4c5477feb0039
diff --git a/pybar/ViTablesPlugin/pybar_plugin.py b/pybar/ViTablesPlugin/pybar_plugin.py index <HASH>..<HASH> 100644 --- a/pybar/ViTablesPlugin/pybar_plugin.py +++ b/pybar/ViTablesPlugin/pybar_plugin.py @@ -5,12 +5,7 @@ """Plugin that provides plotting of data from the Python Bonn Atlas Readout System (pyBAR). """ -__docformat__ = 'restructuredtext' -__version__ = '1.0' -plugin_class = 'pyBarPlugin' - import numpy as np - import os from PyQt4 import QtCore from PyQt4 import QtGui @@ -25,6 +20,10 @@ except: print 'ERROR: Cannot load additional libraries needed for the pyBAR ViTables plugin!' raise +__docformat__ = 'restructuredtext' +__version__ = '1.0' +plugin_class = 'pyBarPlugin' + translate = QtGui.QApplication.translate
MAINT: move imports to the top
SiLab-Bonn_pyBAR
train
b68e1228e97d23c0b7c7904f2b63b89284a3849d
diff --git a/salt/modules/rpm.py b/salt/modules/rpm.py index <HASH>..<HASH> 100644 --- a/salt/modules/rpm.py +++ b/salt/modules/rpm.py @@ -478,8 +478,6 @@ def info(*packages, **attr): if len(line) != 2: continue key, value = line - if key != 'name' and filter_attrs and key not in filter_attrs: - continue if key == 'description': descr_marker = True continue
Remove unnecessary check for the "name" key
saltstack_salt
train
9573a83b213e11e2fe4d5deda9e6f9ad8bf4006e
diff --git a/cluster_queryindexes.go b/cluster_queryindexes.go index <HASH>..<HASH> 100644 --- a/cluster_queryindexes.go +++ b/cluster_queryindexes.go @@ -45,6 +45,7 @@ type jsonQueryIndex struct { Keyspace string `json:"keyspace_id"` Namespace string `json:"namespace_id"` IndexKey []string `json:"index_key"` + Condition string `json:"condition"` } // QueryIndex represents a Couchbase GSI index. @@ -56,6 +57,7 @@ type QueryIndex struct { Keyspace string Namespace string IndexKey []string + Condition string } func (index *QueryIndex) fromData(data jsonQueryIndex) error { @@ -66,6 +68,7 @@ func (index *QueryIndex) fromData(data jsonQueryIndex) error { index.Keyspace = data.Keyspace index.Namespace = data.Namespace index.IndexKey = data.IndexKey + index.Condition = data.Condition return nil }
GOCBC-<I>: Add Condition to QueryIndex Motivation ---------- The SDK did not expose the condition field of a Query index. Changes ------- Added Condition field to QueryIndex. Change-Id: I<I>e<I>a0b1ba<I>da5d<I>ad<I>a3 Reviewed-on: <URL>
couchbase_gocb
train
857bd732723a6ca297195198b9796ba79226f83f
diff --git a/activerecord/lib/active_record/attribute_methods/read.rb b/activerecord/lib/active_record/attribute_methods/read.rb index <HASH>..<HASH> 100644 --- a/activerecord/lib/active_record/attribute_methods/read.rb +++ b/activerecord/lib/active_record/attribute_methods/read.rb @@ -120,22 +120,20 @@ module ActiveRecord # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)). def read_attribute(attr_name) # If it's cached, just return it - @attributes_cache.fetch(attr_name) { - - column = @columns_hash.fetch(attr_name) { - return self.class.type_cast_attribute(attr_name, @attributes, @attributes_cache) + @attributes_cache.fetch(attr_name) { |name| + column = @columns_hash.fetch(name) { + return self.class.type_cast_attribute(name, @attributes, @attributes_cache) } - value = @attributes.fetch(attr_name) { - return block_given? ? yield(attr_name) : nil + value = @attributes.fetch(name) { + return block_given? ? yield(name) : nil } - if self.class.cache_attribute?(attr_name) - @attributes_cache[attr_name] ||= column.type_cast(value) + if self.class.cache_attribute?(name) + @attributes_cache[name] = column.type_cast(value) else column.type_cast value end - } end
use the key name yielded to the fetch block
rails_rails
train
e68b680c91f57a68bf768fde8180fb36d3810636
diff --git a/app_listenAndServe.go b/app_listenAndServe.go index <HASH>..<HASH> 100644 --- a/app_listenAndServe.go +++ b/app_listenAndServe.go @@ -29,7 +29,7 @@ func (app *App) ListenAndServe(addr ...string) error { } } - if !flag.Parsed() { + if !flag.Parsed() && !flagsDisabled { flag.Parse() } diff --git a/regFlags.go b/regFlags.go index <HASH>..<HASH> 100644 --- a/regFlags.go +++ b/regFlags.go @@ -13,6 +13,8 @@ import ( "flag" ) +var flagsDisabled = false + var flagsToRegister = []Flag{ { Name: "bind", @@ -48,7 +50,7 @@ func (app *App) RegFlags() { // GetStringFlag return command line app flag value by name and false if not exists func (app *App) GetStringFlag(name string) (string, bool) { - if !flag.Parsed() { + if !flag.Parsed() && !flagsDisabled { flag.Parse() } if app.Flags.values != nil { @@ -59,3 +61,10 @@ func (app *App) GetStringFlag(name string) (string, bool) { return "", false } + +// DisableFlags globally disables default flags. +// Useful when using non-default flag libraries like pflag. +func DisableFlags() { + flagsDisabled = true + flagsToRegister = []Flag{} +}
:sparkles: introduced DisableFlags: this allows globally disable default gramework flags, which is useful when using non-default flag libraries like pflag.
gramework_gramework
train
1f774667198e72e29a124e8a39dc88b7a2e609d8
diff --git a/presto-main/src/main/java/com/facebook/presto/server/TaskResource.java b/presto-main/src/main/java/com/facebook/presto/server/TaskResource.java index <HASH>..<HASH> 100644 --- a/presto-main/src/main/java/com/facebook/presto/server/TaskResource.java +++ b/presto-main/src/main/java/com/facebook/presto/server/TaskResource.java @@ -114,12 +114,7 @@ public class TaskResource this.sessionPropertyManager = requireNonNull(sessionPropertyManager, "sessionPropertyManager is null"); this.responseExecutor = requireNonNull(responseExecutor, "responseExecutor is null"); this.timeoutExecutor = requireNonNull(timeoutExecutor, "timeoutExecutor is null"); - if (communicationConfig.isBinaryTransportEnabled()) { - this.planFragmentCodec = planFragmentSmileCodec; - } - else { - this.planFragmentCodec = wrapJsonCodec(planFragmentJsonCodec); - } + this.planFragmentCodec = wrapJsonCodec(planFragmentJsonCodec); } @GET diff --git a/presto-main/src/main/java/com/facebook/presto/server/remotetask/HttpRemoteTaskFactory.java b/presto-main/src/main/java/com/facebook/presto/server/remotetask/HttpRemoteTaskFactory.java index <HASH>..<HASH> 100644 --- a/presto-main/src/main/java/com/facebook/presto/server/remotetask/HttpRemoteTaskFactory.java +++ b/presto-main/src/main/java/com/facebook/presto/server/remotetask/HttpRemoteTaskFactory.java @@ -117,14 +117,13 @@ public class HttpRemoteTaskFactory this.taskStatusCodec = taskStatusSmileCodec; this.taskInfoCodec = taskInfoSmileCodec; this.taskUpdateRequestCodec = taskUpdateRequestSmileCodec; - this.planFragmentCodec = planFragmentSmileCodec; } else { this.taskStatusCodec = wrapJsonCodec(taskStatusJsonCodec); this.taskInfoCodec = wrapJsonCodec(taskInfoJsonCodec); this.taskUpdateRequestCodec = wrapJsonCodec(taskUpdateRequestJsonCodec); - this.planFragmentCodec = wrapJsonCodec(planFragmentJsonCodec); } + this.planFragmentCodec = wrapJsonCodec(planFragmentJsonCodec); this.updateScheduledExecutor = newSingleThreadScheduledExecutor(daemonThreadsNamed("task-info-update-scheduler-%s")); this.errorScheduledExecutor = newSingleThreadScheduledExecutor(daemonThreadsNamed("remote-task-error-delay-%s"));
Always use JSON for PlanFragment serialization SMILE support has flaky edge cases, and we cache the serialization now which already has reduced the cost.
prestodb_presto
train
0cf671115e9f944a974a398f5d800c0b99bb26a8
diff --git a/lib/rails-footnotes/notes/controller_note.rb b/lib/rails-footnotes/notes/controller_note.rb index <HASH>..<HASH> 100644 --- a/lib/rails-footnotes/notes/controller_note.rb +++ b/lib/rails-footnotes/notes/controller_note.rb @@ -25,7 +25,15 @@ module Footnotes def controller_filename controller_name=@controller.class.to_s.underscore controller_name='application' if controller_name=='application_controller' - File.join(File.expand_path(RAILS_ROOT), 'app', 'controllers', "#{controller_name}.rb").sub('/controllers/controllers/', '/controllers/') + if ActionController::Routing.respond_to? :controller_paths + ActionController::Routing.controller_paths.each do |controller_path| + full_controller_path = File.join(File.expand_path(controller_path), "#{controller_name}.rb") + return full_controller_path if File.exists?(full_controller_path) + end + raise "File not found" + else + File.join(File.expand_path(RAILS_ROOT), 'app', 'controllers', "#{controller_name}.rb").sub('/controllers/controllers/', '/controllers/') + end end def controller_text
controller_note now finds controllers in engines With rails engines controllers can be located in plugins. If ActionController::Routing responds to the message :controller_paths then this patch loops through all the paths to controllers and returns the first one where the file referenced by the full path exists. Otherwise the controller_filename method uses the previous method for generating the path for the controller.
josevalim_rails-footnotes
train
9de086df6032e04f51c32afc3816cad5b01e011a
diff --git a/zzk/service/service.go b/zzk/service/service.go index <HASH>..<HASH> 100644 --- a/zzk/service/service.go +++ b/zzk/service/service.go @@ -516,10 +516,11 @@ func WaitService(shutdown <-chan interface{}, conn client.Connection, serviceID // Get the service node and verify that the number of running instances meets or exceeds the number // of instances required by the service - var service ServiceNode - if err := conn.Get(servicepath(serviceID), &service); err != nil { + var node ServiceNode + node.Service = &service.Service{} + if err := conn.Get(servicepath(serviceID), &node); err != nil { return err - } else if count >= service.Instances { + } else if count >= node.Instances { return nil } case service.SVCPause:
Instantiate node.Service before calling client.Get.
control-center_serviced
train
2ecd01521fa95f2d79e9a483d6b84bc26145ddbc
diff --git a/src/Http/Response.php b/src/Http/Response.php index <HASH>..<HASH> 100644 --- a/src/Http/Response.php +++ b/src/Http/Response.php @@ -632,6 +632,7 @@ class Response implements ResponseInterface } $this->_reasonPhrase = $reasonPhrase; + // These status codes don't have bodies and can't have content-types. if (in_array($code, [304, 204], true)) { $this->_clearHeader('Content-Type'); }
Add comment for content-type removal.
cakephp_cakephp
train
afc063fb97e6d76d6306eb6118f994ae133ac4a1
diff --git a/server/config/index.js b/server/config/index.js index <HASH>..<HASH> 100644 --- a/server/config/index.js +++ b/server/config/index.js @@ -4,7 +4,7 @@ const config = { bcoin_http: 'localhost', bcoin: { network: 'main', - db: 'leveldb', + db: 'mem', prefix: '.', checkpoints: true, workers: false, diff --git a/server/lib/api/transaction.js b/server/lib/api/transaction.js index <HASH>..<HASH> 100644 --- a/server/lib/api/transaction.js +++ b/server/lib/api/transaction.js @@ -23,7 +23,7 @@ module.exports = function transactionAPI(router) { const txid = req.params.txid || ''; db.txs.getTxById(txid, (err, transaction) => { - if (err) { + if (err || !transaction) { logger.log('error', `/tx/:tid getTxById: ${err.err}`); return res.status(404).send(); diff --git a/server/lib/db/index.js b/server/lib/db/index.js index <HASH>..<HASH> 100644 --- a/server/lib/db/index.js +++ b/server/lib/db/index.js @@ -11,9 +11,13 @@ mongoose.connection.on('error', (err) => { process.on('SIGINT', gracefulExit).on('SIGTERM', gracefulExit); +// Catastrophic Fails can still result in data loss function gracefulExit() { + logger.log('debug', + 'Graceful Shutdown Starting...'); mongoose.connection.close(() => { - console.log('Mongoose connection with DB disconnected through app termination'); + logger.log('debug', + 'Mongoose connection with DB disconnected through app termination'); process.exit(0); }); } diff --git a/server/lib/db/transactions.js b/server/lib/db/transactions.js index <HASH>..<HASH> 100644 --- a/server/lib/db/transactions.js +++ b/server/lib/db/transactions.js @@ -45,7 +45,7 @@ function auditInputs() { getEmptyInputs( (err, txs) => { if (err) { - return logger.log('error', + return logger.log('warn', `No Empty Inputs found: ${err.err}`); } // For each tx with unmarked inputs @@ -56,7 +56,8 @@ function auditInputs() { return getTxById(txHash, (error, tx) => { if (error || !tx) { - return logger.log('error', + // Mongo save is async. Bcoin is kinda sync... Does not mean the tx will not be found + return logger.log('warn', `No Tx found: ${txHash} ${error}`); } return updateInput(inputTx._id, input._id, tx.outputs[outIdx].value, tx.outputs[outIdx].address); diff --git a/server/lib/node/index.js b/server/lib/node/index.js index <HASH>..<HASH> 100644 --- a/server/lib/node/index.js +++ b/server/lib/node/index.js @@ -6,9 +6,10 @@ const config = require('../../config'); const socket = require('../../lib/api/socket'); const db = require('../../lib/db'); -const node = new FullNode(config.bcoin); +const node = new FullNode(config.bcoin); let doneSyncing = false; + function start(bestBlockHeight) { node.open() .then(() => { @@ -20,13 +21,16 @@ function start(bestBlockHeight) { }); node.chain.on('connect', (entry, block) => { + // Saved block acts like a journal BlockParser.parse(entry, block); TxParser.parse(entry, block.txs); socket.processBlock(entry, block); db.blocks.bestHeight(entry.height); - if (entry.height % 20 === 0 || doneSyncing) { - db.txs.auditInputs(); - } + + node.chain.db.getBlockView(block) + .then((view) => { + console.log(view); + }); }); node.chain.on('full', () => {
sync & async saving. Bleh
bitpay_insight
train
61dffabf974109fc47146c56d6843e22b9c68adc
diff --git a/cmd/syncthing/main.go b/cmd/syncthing/main.go index <HASH>..<HASH> 100644 --- a/cmd/syncthing/main.go +++ b/cmd/syncthing/main.go @@ -68,9 +68,9 @@ The --logflags value is a sum of the following: 8 Long filename 16 Short filename -I.e. to prefix each log line with date and time, set --logflags=3 (1 + 2 from -above). The value 0 is used to disable all of the above. The default is to -show time only (2). +I.e. to prefix each log line with time and filename, set --logflags=18 (2 + 16 +from above). The value 0 is used to disable all of the above. The default is +to show date and time (3). Logging always happens to the command line (stdout) and optionally to the file at the path specified by --logfile=path. In addition to an path, the special @@ -187,7 +187,7 @@ type serveOptions struct { func defaultVars() kong.Vars { vars := kong.Vars{} - vars["logFlags"] = strconv.Itoa(log.Ltime) + vars["logFlags"] = strconv.Itoa(logger.DefaultFlags) vars["logMaxSize"] = strconv.Itoa(10 << 20) // 10 MiB vars["logMaxFiles"] = "3" // plus the current one diff --git a/lib/logger/logger.go b/lib/logger/logger.go index <HASH>..<HASH> 100644 --- a/lib/logger/logger.go +++ b/lib/logger/logger.go @@ -31,7 +31,7 @@ const ( ) const ( - DefaultFlags = log.Ltime + DefaultFlags = log.Ltime | log.Ldate DebugFlags = log.Ltime | log.Ldate | log.Lmicroseconds | log.Lshortfile )
cmd/syncthing, lib/logger: Add date to default log format (fixes #<I>) (#<I>) This changes the default log format to include the date.
syncthing_syncthing
train
1406181e2712832b35dc7e4ad812b6ddd9327665
diff --git a/classes/Gems/Agenda/Filter/XandAppointmentFilter.php b/classes/Gems/Agenda/Filter/XandAppointmentFilter.php index <HASH>..<HASH> 100644 --- a/classes/Gems/Agenda/Filter/XandAppointmentFilter.php +++ b/classes/Gems/Agenda/Filter/XandAppointmentFilter.php @@ -11,6 +11,8 @@ namespace Gems\Agenda\Filter; +use Gems\Agenda\EpisodeOfCare; + /** * * @package Gems diff --git a/classes/Gems/Agenda/Filter/XorAppointmentFilter.php b/classes/Gems/Agenda/Filter/XorAppointmentFilter.php index <HASH>..<HASH> 100644 --- a/classes/Gems/Agenda/Filter/XorAppointmentFilter.php +++ b/classes/Gems/Agenda/Filter/XorAppointmentFilter.php @@ -11,6 +11,8 @@ namespace Gems\Agenda\Filter; +use Gems\Agenda\EpisodeOfCare; + /** * * @package Gems
Fixed namespace issues in new appointment filters
GemsTracker_gemstracker-library
train
7fd927d505dc5edcdfe744665c5d05b3b3424a80
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -1,10 +1,9 @@ from setuptools import setup -import os setup(name='servicemanager', python_requires='>2.7.13', - version=os.environ.get("RELEASE_VERSION", "local-development-build"), + version='1.4.0', description='A python tool to manage developing and testing with lots of microservices', url='https://github.com/hmrc/service-manager', author='hmrc-web-operations',
Bump release version to <I>
hmrc_service-manager
train
0270e87b36db6e0c489bcb012cd0d16e8ae1ab57
diff --git a/common/src/main/java/tachyon/network/protocol/RPCBlockReadResponse.java b/common/src/main/java/tachyon/network/protocol/RPCBlockReadResponse.java index <HASH>..<HASH> 100644 --- a/common/src/main/java/tachyon/network/protocol/RPCBlockReadResponse.java +++ b/common/src/main/java/tachyon/network/protocol/RPCBlockReadResponse.java @@ -78,10 +78,7 @@ public class RPCBlockReadResponse extends RPCResponse { short status = in.readShort(); DataBuffer data = null; if (length > 0) { - // TODO: look into accessing Netty ByteBuf directly, to avoid copying the data. - ByteBuffer buffer = ByteBuffer.allocate((int) length); - in.readBytes(buffer); - data = new DataByteBuffer(buffer, (int) length); + data = new DataByteBuffer(in, (int) length); } return new RPCBlockReadResponse(blockId, offset, length, data, Status.fromShort(status)); } diff --git a/common/src/main/java/tachyon/network/protocol/databuffer/DataByteBuffer.java b/common/src/main/java/tachyon/network/protocol/databuffer/DataByteBuffer.java index <HASH>..<HASH> 100644 --- a/common/src/main/java/tachyon/network/protocol/databuffer/DataByteBuffer.java +++ b/common/src/main/java/tachyon/network/protocol/databuffer/DataByteBuffer.java @@ -17,6 +17,7 @@ package tachyon.network.protocol.databuffer; import java.nio.ByteBuffer; +import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; /** @@ -25,6 +26,7 @@ import io.netty.buffer.Unpooled; public class DataByteBuffer extends DataBuffer { private final ByteBuffer mBuffer; private final long mLength; + private ByteBuf mNettyBuf = null; /** * @@ -36,6 +38,29 @@ public class DataByteBuffer extends DataBuffer { mLength = length; } + /** + * Another constructor for creating a DataByteBuffer, by passing a Netty ByteBuf. + * This way we avoid one copy from ByteBuf to another ByteBuffer, + * and making sure the buffer would not be recycled. + * IMPORTANT: With this constructor, {@link #releaseBuffer()} must be called after + * reading is finished. Otherwise the memory space for the ByteBuf might never be reclaimed. + * + * @param bytebuf The ByteBuf having the data + * @param length The length of the underlying ByteBuffer data + */ + public DataByteBuffer(ByteBuf bytebuf, long length) { + // throws exception if there are multiple nioBuffers, or reference count is not 1 + // we probably want to fail instead of catching these exceptions for now + assert (bytebuf.nioBufferCount() == 1); + assert (bytebuf.refCnt() == 1); + + // increase the bytebuf reference count so it would not be recycled by Netty + bytebuf.retain(); + mNettyBuf = bytebuf; + mBuffer = bytebuf.nioBuffer(); + mLength = length; + } + @Override public Object getNettyOutput() { return Unpooled.wrappedBuffer(mBuffer); @@ -52,4 +77,18 @@ public class DataByteBuffer extends DataBuffer { buffer.position(0); return buffer; } + + /** + * Deallocate the Netty ByteBuf if we used ByteBuf to construct this DataByteBuffer. + * + * @return True if the netty ByteBuf is deallocated or not constructed using ByteBuf. + * As the Netty channel is responsible for performing another {@link ByteBuf#release()}, + * this method can return false in unit tests. + */ + public boolean releaseBuffer() { + if (mNettyBuf != null) { + return mNettyBuf.release(); + } + return true; + } }
Add another DataByteBuffer constructor to avoid copying from ByteBuf
Alluxio_alluxio
train
d1c126ccae46c22fe0ad4c312970aa7ffa6e30ce
diff --git a/growler/application.py b/growler/application.py index <HASH>..<HASH> 100644 --- a/growler/application.py +++ b/growler/application.py @@ -187,8 +187,6 @@ class Application(object): Called before running the server, ensures all required coroutines have finished running. """ - # print("[wait_for_all] Begin ", self._wait_for) - for x in self._wait_for: yield from x @@ -232,8 +230,14 @@ class Application(object): Use the middleware (a callable with parameters res, req, next) upon requests match the provided path. A None path matches every request. Returns 'self' so the middleware may be nicely chained. + + @param middleware callable: A function with signature '(req, res)' to + be called with every request which matches + 'path' + @param path: A string or regex wich will be used to match request paths. """ - print("[App::use] Adding middleware <{}>".format(middleware)) + debug = "[App::use] Adding middleware <{}> listening on path {}" + print(debug.format(middleware, path)) self.middleware.append(middleware) return self @@ -353,7 +357,7 @@ class Application(object): This function exists only to remove boilerplate code for starting up a growler app. - @param server_config: These keyword-argument parameters are passed + @param server_config: These keyword arguments parameters are passed directly to the BaseEventLoop.create_server function. Consult their documentation for details. @returns asyncio.coroutine which should be run inside a call to @@ -372,7 +376,7 @@ class Application(object): This function exists only to remove boilerplate code for starting up a growler app. - @param server_config: These keyword-argument parameters are passed + @param server_config: These keyword arguments parameters are passed directly to the BaseEventLoop.create_server function. Consult their documentation for details. """ diff --git a/growler/protocol.py b/growler/protocol.py index <HASH>..<HASH> 100644 --- a/growler/protocol.py +++ b/growler/protocol.py @@ -68,7 +68,9 @@ class GrowlerProtocol(asyncio.Protocol): """ asyncio.Protocol member - called upon when there is a new socket connection. This creates a new responder (as determined by the member - 'responder_type') and stores in a list for + 'responder_type') and stores in a list. Incoming data from this + connection will always call + on_data to the last element of this list. @param transport asyncio.Transport: The Transport handling the socket communication
Added/Improved docstrings
pyGrowler_Growler
train
efd329d593e84edfba2afd4adebe4970831a70ba
diff --git a/lib/ui.js b/lib/ui.js index <HASH>..<HASH> 100755 --- a/lib/ui.js +++ b/lib/ui.js @@ -58,17 +58,18 @@ var ui = { // There are commands running if // cancelCommands function is available. if (self.parent.session.cancelCommands) { - self.parent.session.emit('vorpal_command_cancel'); self.imprint(); self.submit(''); self._sigintCalled = false; self._sigintCount = 0; + self.parent.session.emit('vorpal_command_cancel'); } else if (String(text).trim() !== '') { self.imprint(); self.submit(''); self._sigintCalled = false; self._sigintCount = 0; } else { + self._sigintCalled = false; self.delimiter(' '); self.submit(''); self.log('(^C again to quit)'); @@ -80,7 +81,7 @@ var ui = { key = key || {}; if (key.ctrl === true && key.shift === false && key.meta === false && ['c', 'C'].indexOf(key.name) > -1) { self._sigintCount++; - if (self._sigint && !self._sigintCalled) { + if (self._sigint !== undefined && !self._sigintCalled) { self._sigintCalled = true; self._sigint.call(self.parent); } diff --git a/test/util/playground.js b/test/util/playground.js index <HASH>..<HASH> 100755 --- a/test/util/playground.js +++ b/test/util/playground.js @@ -81,6 +81,28 @@ vorpal.command('promptme') }); }); +vorpal.command('cancelme') + .action(function (args, cb) { + setTimeout(function () { + cb(); + }, 10000) + }) + .cancel(function (a, b) { + console.log('cancelled!', a, b); + }); + +vorpal.command('inputme') + .action(function (args, cb) { + this.prompt({ + type: 'input', + name: 'data', + message: 'say something im giving up on you: ' + }, function (result) { + console.log(result); + cb(); + }); + }); + vorpal .delimiter('calc:') .show()
fixed sigint bug on cancelled commands
dthree_vorpal
train
7009fadbabb56969a2d7a5b78616d1ad5725d540
diff --git a/apptentive/src/main/java/com/apptentive/android/sdk/debug/Assert.java b/apptentive/src/main/java/com/apptentive/android/sdk/debug/Assert.java index <HASH>..<HASH> 100644 --- a/apptentive/src/main/java/com/apptentive/android/sdk/debug/Assert.java +++ b/apptentive/src/main/java/com/apptentive/android/sdk/debug/Assert.java @@ -1,5 +1,6 @@ package com.apptentive.android.sdk.debug; +import com.apptentive.android.sdk.util.ObjectUtils; import com.apptentive.android.sdk.util.StringUtils; /** @@ -69,6 +70,12 @@ public class Assert { } } + public static void assertEquals(Object expected, Object actual) { + if (imp != null && !ObjectUtils.equal(expected, actual)) { + imp.assertFailed(StringUtils.format("Expected '%s' but was '%s'", expected, actual)); + } + } + public static void setImp(AssertImp imp) { Assert.imp = imp; } diff --git a/apptentive/src/main/java/com/apptentive/android/sdk/util/ObjectUtils.java b/apptentive/src/main/java/com/apptentive/android/sdk/util/ObjectUtils.java index <HASH>..<HASH> 100644 --- a/apptentive/src/main/java/com/apptentive/android/sdk/util/ObjectUtils.java +++ b/apptentive/src/main/java/com/apptentive/android/sdk/util/ObjectUtils.java @@ -49,4 +49,8 @@ public final class ObjectUtils { return map; } + + public static boolean equal(Object expected, Object actual) { + return expected != null && actual != null && expected.equals(actual); + } } diff --git a/apptentive/src/test/java/com/apptentive/android/sdk/debug/AssertTest.java b/apptentive/src/test/java/com/apptentive/android/sdk/debug/AssertTest.java index <HASH>..<HASH> 100644 --- a/apptentive/src/test/java/com/apptentive/android/sdk/debug/AssertTest.java +++ b/apptentive/src/test/java/com/apptentive/android/sdk/debug/AssertTest.java @@ -60,6 +60,13 @@ public class AssertTest extends TestCaseBase implements AssertImp { ); } + @Test + public void testAssertEquals() throws Exception { + AssertEx.assertEquals("foo", "foo"); + AssertEx.assertEquals("foo", "bar"); + assertResult("Expected 'foo' but was 'bar'"); + } + @Override public void assertFailed(String message) { addResult(message);
Added Assert.assertEquals method
apptentive_apptentive-android
train
d6f9703e37dd118dcda73e229a15ebe00ad94965
diff --git a/src/main/java/org/metacsp/meta/simplePlanner/ProactivePlanningDomain.java b/src/main/java/org/metacsp/meta/simplePlanner/ProactivePlanningDomain.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/metacsp/meta/simplePlanner/ProactivePlanningDomain.java +++ b/src/main/java/org/metacsp/meta/simplePlanner/ProactivePlanningDomain.java @@ -52,8 +52,11 @@ public class ProactivePlanningDomain extends SimpleDomain { ValueOrderingH valOH = new ValueOrderingH() { @Override public int compare(ConstraintNetwork arg0, ConstraintNetwork arg1) { - if (arg0.getAnnotation() != null && arg1.getAnnotation() != null) - return (Integer)arg1.getAnnotation()-(Integer)arg0.getAnnotation(); + if (arg0.getAnnotation() != null && arg1.getAnnotation() != null) { + if (arg0.getAnnotation() instanceof Integer && arg1.getAnnotation() instanceof Integer) { + return (Integer)arg1.getAnnotation()-(Integer)arg0.getAnnotation(); + } + } return arg1.getVariables().length - arg0.getVariables().length; } }; @@ -145,7 +148,7 @@ public class ProactivePlanningDomain extends SimpleDomain { String headComponent = head.substring(0,head.indexOf("::")); String headValue = head.substring(head.indexOf("::")+2); if (this.isContextVar(headComponent)) { - VariablePrototype toInfer = new VariablePrototype(groundSolver, headComponent, headValue); + VariablePrototype toInfer = new VariablePrototype(groundSolver, headComponent, headValue, "Inference"); toInfer.setMarking(markings.UNJUSTIFIED); vars.add(toInfer); } diff --git a/src/main/java/org/metacsp/meta/simplePlanner/SimpleDomain.java b/src/main/java/org/metacsp/meta/simplePlanner/SimpleDomain.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/metacsp/meta/simplePlanner/SimpleDomain.java +++ b/src/main/java/org/metacsp/meta/simplePlanner/SimpleDomain.java @@ -267,7 +267,6 @@ public class SimpleDomain extends MetaConstraint { for (ConstraintNetwork oneUnification : unifications) { retPossibleConstraintNetworks.add(oneUnification); oneUnification.setAnnotation(2); - System.out.println("ADDED UNIFICATION for " + problematicActivity + ": " + oneUnification); } } } diff --git a/src/main/java/org/metacsp/sensing/ConstraintNetworkAnimator.java b/src/main/java/org/metacsp/sensing/ConstraintNetworkAnimator.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/metacsp/sensing/ConstraintNetworkAnimator.java +++ b/src/main/java/org/metacsp/sensing/ConstraintNetworkAnimator.java @@ -117,17 +117,21 @@ public class ConstraintNetworkAnimator extends Thread { planner.backtrack(); Vector<Activity> oldInference = new Vector<Activity>(); for (ConstraintNetwork cn : planner.getAddedResolvers()) { - Variable[] vars = cn.getVariables(); - if (vars.length == 1) { - Variable var = vars[0]; - if (var instanceof VariablePrototype) { - VariablePrototype vp = (VariablePrototype)vars[0]; - Activity act = (Activity)cn.getSubstitution(vp); - if (domain.isContextVar(act.getComponent())) { - oldInference.add(act); + VariablePrototype var = null; + for (Variable v : cn.getVariables()) { + if (v instanceof VariablePrototype) { + if (((VariablePrototype)v).getParameters().length > 2) { + if (((VariablePrototype)v).getParameters()[2].equals("Inference")) { + var = (VariablePrototype)v; + } } } } + if (var != null) { +// System.out.println("DOING " + cn.getVariables()[0]); + Activity act = (Activity)cn.getSubstitution(var); + oldInference.add(act); + } } if (!oldInference.isEmpty()) { domain.setOldInference(oldInference.toArray(new Activity[oldInference.size()]));
Refining proactive planning example wih Cooking and Eating (still a bit shaky...). --F.
FedericoPecora_meta-csp-framework
train
10b042296f8e34954b1e873895c4650e62175bae
diff --git a/lib/raml/method.rb b/lib/raml/method.rb index <HASH>..<HASH> 100644 --- a/lib/raml/method.rb +++ b/lib/raml/method.rb @@ -1,6 +1,6 @@ module Raml class Method - NAMES = %w(options get head post put delete trace connect) + NAMES = %w(options get head post put delete trace connect patch) extend Common
Add PATCH to list of supported methods.
coub_raml_ruby
train
0a362917910356d2471a12cca057842923bbeb3b
diff --git a/spec/controllers/spree/adyen_redirect_controller_spec.rb b/spec/controllers/spree/adyen_redirect_controller_spec.rb index <HASH>..<HASH> 100644 --- a/spec/controllers/spree/adyen_redirect_controller_spec.rb +++ b/spec/controllers/spree/adyen_redirect_controller_spec.rb @@ -37,12 +37,6 @@ RSpec.describe Spree::AdyenRedirectController, type: :controller do end let(:merchantReturnData) { [order.guest_token, gateway.id].join("|") } - shared_examples "payments are pending" do - it "has pending payments" do - expect(order.payments).to all be_pending - end - end - shared_examples "payment is successful" do it "changes the order state to completed" do subject @@ -54,6 +48,10 @@ RSpec.describe Spree::AdyenRedirectController, type: :controller do ) end + it "has pending payments" do + expect(order.payments).to all be_pending + end + it "redirects to the order complete page" do is_expected.to have_http_status(:redirect). and redirect_to order_path(order) @@ -73,9 +71,20 @@ RSpec.describe Spree::AdyenRedirectController, type: :controller do end end + shared_examples "payment is not successful" do + it "does not change order state" do + expect{ subject }.to_not change{ order.state } + end + + it "redirects to the order payment page" do + is_expected.to have_http_status(:redirect). + and redirect_to checkout_state_path("payment") + end + end + context "when the payment is AUTHORISED" do include_examples "payment is successful" - include_examples "payments are pending" + let(:auth_result) { "AUTHORISED" } context "and the authorisation notification has already been received" do @@ -84,7 +93,7 @@ RSpec.describe Spree::AdyenRedirectController, type: :controller do let(:notification) do create( :notification, - notification_type, + :auth, processed: true, psp_reference: psp_reference, merchant_reference: order.number) @@ -96,43 +105,19 @@ RSpec.describe Spree::AdyenRedirectController, type: :controller do create(:hpp_source, psp_reference: psp_reference, order: order) create(:hpp_payment, source: source, order: order) - order.complete - end - - context "and payment method is sofort" do - let(:notification_type) { :sofort_auth } - include_examples "payment is successful" - end - context "and payment method is ideal" do - let(:notification_type) { :ideal_auth } - include_examples "payment is successful" + order.complete end - context "and payment method is credit" do - let(:notification_type) { :auth } - include_examples "payment is successful" - end + include_examples "payment is successful" end end context "when the payment is PENDING" do include_examples "payment is successful" - include_examples "payments are pending" let(:auth_result) { "PENDING" } end - shared_examples "payment is not successful" do - it "does not change order state" do - expect{ subject }.to_not change{ order.state } - end - - it "redirects to the order payment page" do - is_expected.to have_http_status(:redirect). - and redirect_to checkout_state_path("payment") - end - end - context "when the payment is CANCELLED" do include_examples "payment is not successful" let(:auth_result) { "CANCELLED" }
Cleaned up spec a bit Removed some unessecary parts that were specific about which payment method to use, this should really matter here as there is not specific logic based on that at this point.
StemboltHQ_solidus-adyen
train
ab25e7557e56bb54cbef916a6f4fc2646d7ac21b
diff --git a/go/vt/vtctl/reparentutil/reparent_functions.go b/go/vt/vtctl/reparentutil/reparent_functions.go index <HASH>..<HASH> 100644 --- a/go/vt/vtctl/reparentutil/reparent_functions.go +++ b/go/vt/vtctl/reparentutil/reparent_functions.go @@ -76,7 +76,6 @@ type ( tabletMap map[string]*topo.TabletInfo statusMap map[string]*replicationdatapb.StopReplicationStatus primaryStatusMap map[string]*replicationdatapb.PrimaryStatus - validCandidates map[string]mysql.Position } ) @@ -181,14 +180,12 @@ func (vtctlReparent *VtctlReparentFunctions) FindPrimaryCandidates(ctx context.C } } - vtctlReparent.validCandidates = validCandidates - // If we were requested to elect a particular primary, verify it's a valid // candidate (non-zero position, no errant GTIDs) and is at least as // advanced as the winning position. if vtctlReparent.NewPrimaryAlias != nil { winningPrimaryTabletAliasStr = topoproto.TabletAliasString(vtctlReparent.NewPrimaryAlias) - pos, ok := vtctlReparent.validCandidates[winningPrimaryTabletAliasStr] + pos, ok := validCandidates[winningPrimaryTabletAliasStr] switch { case !ok: return nil, nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "master elect %v has errant GTIDs", winningPrimaryTabletAliasStr)
remove validCandidates from the vtctlreparentFunctions struct
vitessio_vitess
train
0072a9391542cf45764559b47fb528bd9aa66676
diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java index <HASH>..<HASH> 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java @@ -912,6 +912,8 @@ public class ServerProperties valve.setPrefix(this.accesslog.getPrefix()); valve.setSuffix(this.accesslog.getSuffix()); valve.setRenameOnRotate(this.accesslog.isRenameOnRotate()); + valve.setRequestAttributesEnabled( + this.accesslog.isRequestAttributesEnabled()); factory.addEngineValves(valve); } @@ -961,6 +963,12 @@ public class ServerProperties */ private boolean renameOnRotate; + /** + * Set request attributes for IP address, Hostname, protocol and port used + * for the request. + */ + private boolean requestAttributesEnabled; + public boolean isEnabled() { return this.enabled; } @@ -1009,6 +1017,14 @@ public class ServerProperties this.renameOnRotate = renameOnRotate; } + public boolean isRequestAttributesEnabled() { + return this.requestAttributesEnabled; + } + + public void setRequestAttributesEnabled(boolean requestAttributesEnabled) { + this.requestAttributesEnabled = requestAttributesEnabled; + } + } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java index <HASH>..<HASH> 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java @@ -137,6 +137,7 @@ public class ServerPropertiesTests { map.put("server.tomcat.accesslog.pattern", "%h %t '%r' %s %b"); map.put("server.tomcat.accesslog.prefix", "foo"); map.put("server.tomcat.accesslog.rename-on-rotate", "true"); + map.put("server.tomcat.accesslog.request-attributes-enabled", "true"); map.put("server.tomcat.accesslog.suffix", "-bar.log"); map.put("server.tomcat.protocol_header", "X-Forwarded-Protocol"); map.put("server.tomcat.remote_ip_header", "Remote-Ip"); @@ -147,6 +148,7 @@ public class ServerPropertiesTests { assertThat(tomcat.getAccesslog().getPattern()).isEqualTo("%h %t '%r' %s %b"); assertThat(tomcat.getAccesslog().getPrefix()).isEqualTo("foo"); assertThat(tomcat.getAccesslog().isRenameOnRotate()).isTrue(); + assertThat(tomcat.getAccesslog().isRequestAttributesEnabled()).isTrue(); assertThat(tomcat.getAccesslog().getSuffix()).isEqualTo("-bar.log"); assertThat(tomcat.getRemoteIpHeader()).isEqualTo("Remote-Ip"); assertThat(tomcat.getProtocolHeader()).isEqualTo("X-Forwarded-Protocol"); diff --git a/spring-boot-docs/src/main/asciidoc/appendix-application-properties.adoc b/spring-boot-docs/src/main/asciidoc/appendix-application-properties.adoc index <HASH>..<HASH> 100644 --- a/spring-boot-docs/src/main/asciidoc/appendix-application-properties.adoc +++ b/spring-boot-docs/src/main/asciidoc/appendix-application-properties.adoc @@ -198,6 +198,7 @@ content into your application; rather pick only the properties that you need. server.tomcat.accesslog.pattern=common # Format pattern for access logs. server.tomcat.accesslog.prefix=access_log # Log file name prefix. server.tomcat.accesslog.rename-on-rotate=false # Defer inclusion of the date stamp in the file name until rotate time. + server.tomcat.accesslog.request-attributes-enabled=false # Set request attributes for IP address, Hostname, protocol and port used for the request. server.tomcat.accesslog.suffix=.log # Log file name suffix. server.tomcat.background-processor-delay=30 # Delay in seconds between the invocation of backgroundProcess methods. server.tomcat.basedir= # Tomcat base directory. If not specified a temporary directory will be used.
Expose Tomcat's accesslog requestAttributesEnabled This commit adds an extra property to the `server.tomcat.accesslog` to control the `reqestAttributesEnabled` flag. This flag sets request attributes for IP address, Hostname, protocol and port used for the request. Closes gh-<I>
spring-projects_spring-boot
train
bde8756110f094e8d6eafdac0797334414b446db
diff --git a/Library/Console/Application.php b/Library/Console/Application.php index <HASH>..<HASH> 100644 --- a/Library/Console/Application.php +++ b/Library/Console/Application.php @@ -12,6 +12,7 @@ namespace Zephir\Console; use Symfony\Component\Console\Application as BaseApplication; +use Symfony\Component\Console\Exception\CommandNotFoundException; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputDefinition; use Symfony\Component\Console\Input\InputInterface; @@ -90,7 +91,14 @@ final class Application extends BaseApplication return 0; } - return parent::doRun($input, $output); + try { + return parent::doRun($input, $output); + } catch (CommandNotFoundException $e) { + $this->setCatchExceptions(false); + fprintf(STDERR, $e->getMessage().PHP_EOL); + + return 1; + } } /**
Do not print exception backtrace when command not found
phalcon_zephir
train
e5e2978752a7d1418505a74410afb5e43537aa8d
diff --git a/indra/tools/reading/read_files.py b/indra/tools/reading/read_files.py index <HASH>..<HASH> 100644 --- a/indra/tools/reading/read_files.py +++ b/indra/tools/reading/read_files.py @@ -99,7 +99,7 @@ def main(): outputs = read_files(input_lines, readers, verboes=verbose) reading_out_path = args.name + '_readings.pkl' with open(reading_out_path, 'wb') as f: - pickle.dump([output.make_tuple() for output in outputs], f) + pickle.dump([output.make_tuple(None) for output in outputs], f) print("Reading outputs stored in %s." % reading_out_path) stmt_data_list = make_statements(outputs) diff --git a/indra/tools/reading/readers.py b/indra/tools/reading/readers.py index <HASH>..<HASH> 100644 --- a/indra/tools/reading/readers.py +++ b/indra/tools/reading/readers.py @@ -727,7 +727,7 @@ class ReadingData(object): def get_cols(): """Get the columns for the tuple returned by `make_tuple`.""" return ('text_content_id', 'reader', 'reader_version', 'format', - 'bytes') + 'bytes', 'batch_id') def get_statements(self, reprocess=False): """General method to create statements.""" @@ -775,10 +775,10 @@ class ReadingData(object): raise Exception('Do not know how to zip format %s.' % self.format) return ret - def make_tuple(self): + def make_tuple(self, batch_id): """Make the tuple expected by the database.""" return (self.tcid, self.reader, self.reader_version, self.format, - self.zip_content()) + self.zip_content(), batch_id) def matches(self, r_entry): """Determine if reading data matches the a reading entry from the db. diff --git a/indra/tools/reading/util/script_tools.py b/indra/tools/reading/util/script_tools.py index <HASH>..<HASH> 100644 --- a/indra/tools/reading/util/script_tools.py +++ b/indra/tools/reading/util/script_tools.py @@ -103,13 +103,13 @@ class StatementData(object): @classmethod def get_cols(self): """Get the columns for the tuple returned by `make_tuple`.""" - return 'reading_id', 'db_info_id', 'uuid', 'mk_hash', \ + return 'batch_id', 'reading_id', 'db_info_id', 'uuid', 'mk_hash', \ 'source_hash', 'type', 'json', 'indra_version' - def make_tuple(self): + def make_tuple(self, batch_id): """Make a tuple for copying into the database.""" - return (self.reading_id, self.db_info_id, self.statement.uuid, - self.statement.get_hash(shallow=False), + return (batch_id, self.reading_id, self.db_info_id, + self.statement.uuid, self.statement.get_hash(shallow=False), self.statement.evidence[0].get_source_hash(), self.statement.__class__.__name__, json.dumps(self.statement.to_json()), self.indra_version)
Apply batch-id methodology to readings and statements.
sorgerlab_indra
train
963cb1ffd31b6592cc881c56e25a37efe9178fe3
diff --git a/app/library/Module.php b/app/library/Module.php index <HASH>..<HASH> 100755 --- a/app/library/Module.php +++ b/app/library/Module.php @@ -78,32 +78,34 @@ abstract class Module implements Access public function name($name = null) { + $base = static::NAME; return isset($name) - ? static::NAME . '_' . $name - : static::NAME; + ? $base . '_' . $name + : $base; } public function path($path = null) { + $base = strtolower(\Coast\str_camel_split(static::NAME, '-')); return isset($path) - ? static::NAME . '/' . $path - : static::NAME; + ? $base . '/' . $path + : $base; } public function nspace($nspace = null) { - $class = get_class($this); - $class = substr($class, 0, strrpos($class, '\\')); + $base = substr($c = get_class($this), 0, strrpos($c, '\\')); return isset($nspace) - ? $class . '\\' . $nspace - : $class; + ? $base . '\\' . $nspace + : $base; } public function dir($path = null, $create = false) { + $base = $this->_baseDir; return isset($path) - ? $this->_baseDir->dir($path, $create) - : $this->_baseDir; + ? $base->dir($path, $create) + : $base; } public function file($path) @@ -247,7 +249,7 @@ abstract class Module implements Access public function backendRoute($name, $method = Router::METHOD_ALL, $path, $params) { $this->backend->router - ->route($name, $method, $path, $params); + ->route($name, $method, $path, ['group' => $this->path()] + $params); return $this; } diff --git a/modules/core/backend/controllers/All.php b/modules/core/backend/controllers/All.php index <HASH>..<HASH> 100755 --- a/modules/core/backend/controllers/All.php +++ b/modules/core/backend/controllers/All.php @@ -20,7 +20,7 @@ class All extends Action { $session = $this->session->data('__Chalk\Backend'); - $this->module = $this->chalk->module($req->dispatch['group']); + $this->module = $this->chalk->module(\Coast\str_camel_lower($req->dispatch['group'])); $this->domain = $this->em('core_domain')->id(1, [], [], false); $this->user = isset($session->user) ? $session->user : null; $this->model = $this->_model($req); @@ -65,7 +65,8 @@ class All extends Action public function postDispatch(Request $req, Response $res) { $controller = strtolower(str_replace('_', '/', $req->dispatch['controller'])); - $action = strtolower(str_replace('_', '-', $req->dispatch['action'])); + $action = $req->dispatch['action']; + $group = \Coast\str_camel_lower($req->dispatch['group']); $path = isset($req->view->path) ? $req->view->path : "{$controller}/{$action}"; @@ -85,7 +86,7 @@ class All extends Action ->html($this->view->render($path, [ 'req' => $req, 'res' => $res, - ] + (array) $req->view, $req->dispatch['group'])); + ] + (array) $req->view, $group)); } protected function _modelClass(Request $req)
Tweak group names in URLs
jacksleight_chalk
train
d604b6d47ae636e20fb4ca9d2327f7283222dc5a
diff --git a/lib/fog/openstack/storage.rb b/lib/fog/openstack/storage.rb index <HASH>..<HASH> 100644 --- a/lib/fog/openstack/storage.rb +++ b/lib/fog/openstack/storage.rb @@ -3,8 +3,7 @@ require 'fog/openstack/core' module Fog module Storage class OpenStack < Fog::Service - requires :openstack_auth_url, :openstack_username, - :openstack_api_key + requires :openstack_auth_url recognizes :openstack_auth_token, :openstack_management_url, :persistent, :openstack_service_type, :openstack_service_name, :openstack_tenant, :openstack_tenant_id,
[openstack] storage does not require api_key and username, token can also be used
fog_fog
train
28f737e4d4e3e0fc4186eef82c8ec239255ac840
diff --git a/core-bundle/src/Command/MigrateCommand.php b/core-bundle/src/Command/MigrateCommand.php index <HASH>..<HASH> 100644 --- a/core-bundle/src/Command/MigrateCommand.php +++ b/core-bundle/src/Command/MigrateCommand.php @@ -145,7 +145,7 @@ class MigrateCommand extends Command return 1; } - if (!$dryRun && !$this->executeMigrations($dryRun, $asJson, $specifiedHash)) { + if (!$dryRun && null === $specifiedHash && !$this->executeMigrations($dryRun, $asJson, null)) { return 1; } @@ -156,7 +156,7 @@ class MigrateCommand extends Command return 0; } - private function executeMigrations(bool $dryRun, bool $asJson, string $specifiedHash = null): bool + private function executeMigrations(bool &$dryRun, bool $asJson, string $specifiedHash = null): bool { while (true) { $first = true; @@ -261,8 +261,13 @@ class MigrateCommand extends Command $this->io->success('Executed '.$count.' migrations.'); } - // Do not run the update recursive if a hash was specified if (null !== $specifiedHash) { + // Do not run the schema update after migrations got executed + // if a hash was specified, because that hash could never match + // both, migrations and schema updates + $dryRun = true; + + // Do not run the update recursive if a hash was specified break; } }
Fix bug with hash comparison in migrate command (see #<I>) Description ----------- - Commits ------- f<I>af9f Fix bug with hash comparison in migrate command e8b<I>fa3 Do not require migrations-only or schema-only if a hash is specified
contao_contao
train
c9c9a683f70fd5d8c3f790790b5719971d6d5f91
diff --git a/_pydevd_bundle/pydevd_process_net_command_json.py b/_pydevd_bundle/pydevd_process_net_command_json.py index <HASH>..<HASH> 100644 --- a/_pydevd_bundle/pydevd_process_net_command_json.py +++ b/_pydevd_bundle/pydevd_process_net_command_json.py @@ -9,7 +9,7 @@ import types from _pydevd_bundle._debug_adapter import pydevd_base_schema from _pydevd_bundle._debug_adapter.pydevd_schema import (SourceBreakpoint, ScopesResponseBody, Scope, VariablesResponseBody, SetVariableResponseBody, ModulesResponseBody, SourceResponseBody, - GotoTargetsResponseBody, ExceptionOptions, SetExpressionResponseBody) + GotoTargetsResponseBody, ExceptionOptions, SetExpressionResponseBody, EvaluateResponseBody) from _pydevd_bundle._debug_adapter.pydevd_schema import CompletionsResponseBody from _pydevd_bundle.pydevd_api import PyDevdAPI from _pydevd_bundle.pydevd_comm_constants import ( @@ -627,8 +627,19 @@ class _PyDevJsonCommandProcessor(object): thread_id = py_db.suspended_frames_manager.get_thread_id_for_variable_reference( arguments.frameId) - self.api.request_exec_or_evaluate_json( - py_db, request, thread_id) + if thread_id is not None: + self.api.request_exec_or_evaluate_json( + py_db, request, thread_id) + else: + body = EvaluateResponseBody('', 0) + response = pydevd_base_schema.build_response( + request, + kwargs={ + 'body': body, + 'success': False, + 'message': 'Unable to find thread for evaluation.' + }) + return NetCommand(CMD_RETURN, 0, response, is_json=True) def on_setexpression_request(self, py_db, request): # : :type arguments: SetExpressionArguments @@ -644,7 +655,7 @@ class _PyDevJsonCommandProcessor(object): response = pydevd_base_schema.build_response( request, kwargs={ - 'body':body, + 'body': body, 'success': False, 'message': 'Unable to find thread to set expression.' }) @@ -676,7 +687,7 @@ class _PyDevJsonCommandProcessor(object): variables = [] body = VariablesResponseBody(variables) variables_response = pydevd_base_schema.build_response(request, kwargs={ - 'body':body, + 'body': body, 'success': False, 'message': 'Unable to find thread to evaluate variable reference.' }) @@ -695,7 +706,7 @@ class _PyDevJsonCommandProcessor(object): variables_response = pydevd_base_schema.build_response( request, kwargs={ - 'body':body, + 'body': body, 'success': False, 'message': 'Unable to find thread to evaluate variable reference.' }) diff --git a/tests_python/test_debugger_json.py b/tests_python/test_debugger_json.py index <HASH>..<HASH> 100644 --- a/tests_python/test_debugger_json.py +++ b/tests_python/test_debugger_json.py @@ -1473,6 +1473,43 @@ def test_evaluate(case_setup): writer.finished_ok = True +def test_evaluate_failures(case_setup): + with case_setup.test_file('_debugger_case_completions.py') as writer: + json_facade = JsonFacade(writer) + + json_facade.write_set_breakpoints(writer.get_line_index_with_content('Break here')) + json_facade.write_make_initial_run() + + json_hit = json_facade.wait_for_thread_stopped() + + # First, try with wrong id. + exec_request = json_facade.write_request( + pydevd_schema.EvaluateRequest(pydevd_schema.EvaluateArguments('a = 10', frameId=9999, context='repl'))) + exec_response = json_facade.wait_for_response(exec_request) + assert exec_response.success == False + assert exec_response.message == 'Wrong ID sent from the client: 9999' + + first_hit = None + for i in range(2): + json_hit = json_facade.get_stack_as_json_hit(json_hit.thread_id) + if i == 0: + first_hit = json_hit + + if i == 1: + # Now, check with a previously existing frameId. + exec_request = json_facade.write_request( + pydevd_schema.EvaluateRequest(pydevd_schema.EvaluateArguments('a = 10', frameId=first_hit.frame_id, context='repl'))) + exec_response = json_facade.wait_for_response(exec_request) + assert exec_response.success == False + assert exec_response.message == 'Unable to find thread for evaluation.' + + json_facade.write_continue(wait_for_response=i == 0) + if i == 0: + json_hit = json_facade.wait_for_thread_stopped() + + writer.finished_ok = True + + @pytest.mark.parametrize('max_frames', ['default', 'all', 10]) # -1 = default, 0 = all, 10 = 10 frames def test_exception_details(case_setup, max_frames): with case_setup.test_file('_debugger_case_large_exception_stack.py') as writer:
Check if returned thread id is valid in on_evaluate_request. ptvsd:<I>
fabioz_PyDev.Debugger
train
cda45918ced57322509d4ade9a0dcb5409148683
diff --git a/lib/runivedo/session.rb b/lib/runivedo/session.rb index <HASH>..<HASH> 100644 --- a/lib/runivedo/session.rb +++ b/lib/runivedo/session.rb @@ -23,6 +23,9 @@ module Runivedo def initialize(url, args = {}) @remote_objects = {} @ws = RfcWebSocket::WebSocket.new(url) + # Use TCP_NODELAY, since usually SQL queries are pretty small packets. + @ws.instance_variable_get(:@socket).setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1) + Thread.new { handle_ws } @urologin = RemoteObject.new(self, 0) @remote_objects[0] = @urologin diff --git a/lib/runivedo/version.rb b/lib/runivedo/version.rb index <HASH>..<HASH> 100644 --- a/lib/runivedo/version.rb +++ b/lib/runivedo/version.rb @@ -1,3 +1,3 @@ module Runivedo - VERSION = "0.2.2" + VERSION = "0.2.3" end
use TCP_NODELAY for sockets this results in a massive speedup on linux, since usually SQL queries are pretty small packets.
univedo_runivedo
train
5c3111af78de427e1e43f9f202427036dc1a731c
diff --git a/annis-gui/src/main/java/annis/gui/resultview/ResultViewPanel.java b/annis-gui/src/main/java/annis/gui/resultview/ResultViewPanel.java index <HASH>..<HASH> 100644 --- a/annis-gui/src/main/java/annis/gui/resultview/ResultViewPanel.java +++ b/annis-gui/src/main/java/annis/gui/resultview/ResultViewPanel.java @@ -344,7 +344,7 @@ public class ResultViewPanel extends VerticalLayout implements SingleResultPanel panel = new SingleResultPanel(corpusGraph. getSDocuments().get(0), i + offset, new ResolverProviderImpl(cacheResolver), ps, - tokenAnnotationLevelSet, segmentationName, + getVisibleTokenAnnos(), segmentationName, instanceConfig); i++; diff --git a/annis-visualizers/src/main/java/annis/visualizers/component/grid/GridComponent.java b/annis-visualizers/src/main/java/annis/visualizers/component/grid/GridComponent.java index <HASH>..<HASH> 100644 --- a/annis-visualizers/src/main/java/annis/visualizers/component/grid/GridComponent.java +++ b/annis-visualizers/src/main/java/annis/visualizers/component/grid/GridComponent.java @@ -88,6 +88,8 @@ public class GridComponent extends Panel if (input != null) { + this.manuallySelectedTokenAnnos = input.getVisibleTokenAnnos(); + EList<STextualDS> texts = input.getDocument().getSDocumentGraph().getSTextualDSs(); if (texts != null && texts.size() > 0)
don't forget information about selected token annotations
korpling_ANNIS
train
e05cacd08ff40fa7d7af192fee95c3bc60df9617
diff --git a/resource_aws_vpc_peering_connection.go b/resource_aws_vpc_peering_connection.go index <HASH>..<HASH> 100644 --- a/resource_aws_vpc_peering_connection.go +++ b/resource_aws_vpc_peering_connection.go @@ -147,7 +147,6 @@ func resourceAwsVPCPeeringUpdate(d *schema.ResourceData, meta interface{}) error } if _, ok := d.GetOk("auto_accept"); ok { - pcRaw, _, err := resourceAwsVPCPeeringConnectionStateRefreshFunc(conn, d.Id())() if err != nil { @@ -160,7 +159,6 @@ func resourceAwsVPCPeeringUpdate(d *schema.ResourceData, meta interface{}) error pc := pcRaw.(*ec2.VpcPeeringConnection) if pc.Status != nil && *pc.Status.Code == "pending-acceptance" { - status, err := resourceVPCPeeringConnectionAccept(conn, d.Id()) if err != nil { return err diff --git a/resource_aws_vpc_peering_connection_test.go b/resource_aws_vpc_peering_connection_test.go index <HASH>..<HASH> 100644 --- a/resource_aws_vpc_peering_connection_test.go +++ b/resource_aws_vpc_peering_connection_test.go @@ -22,6 +22,10 @@ func TestAccAWSVPCPeeringConnection_basic(t *testing.T) { t.Fatal("AWS_ACCOUNT_ID must be set") } }, + + IDRefreshName: "aws_vpc_peering_connection.foo", + IDRefreshIgnore: []string{"auto_accept"}, + Providers: testAccProviders, CheckDestroy: testAccCheckAWSVpcPeeringConnectionDestroy, Steps: []resource.TestStep{ @@ -59,6 +63,10 @@ func TestAccAWSVPCPeeringConnection_plan(t *testing.T) { t.Fatal("AWS_ACCOUNT_ID must be set") } }, + + IDRefreshName: "aws_vpc_peering_connection.foo", + IDRefreshIgnore: []string{"auto_accept"}, + Providers: testAccProviders, CheckDestroy: testAccCheckAWSVpcPeeringConnectionDestroy, Steps: []resource.TestStep{ @@ -82,7 +90,11 @@ func TestAccAWSVPCPeeringConnection_tags(t *testing.T) { } resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, + PreCheck: func() { testAccPreCheck(t) }, + + IDRefreshName: "aws_vpc_peering_connection.foo", + IDRefreshIgnore: []string{"auto_accept"}, + Providers: testAccProviders, CheckDestroy: testAccCheckVpcDestroy, Steps: []resource.TestStep{
providers/aws: peering connection id-only test settings
terraform-providers_terraform-provider-aws
train
9e2a5855e630b67a434ec3f56f04f8c4e71ce43d
diff --git a/lib/media/play_rate_controller.js b/lib/media/play_rate_controller.js index <HASH>..<HASH> 100644 --- a/lib/media/play_rate_controller.js +++ b/lib/media/play_rate_controller.js @@ -89,6 +89,15 @@ shaka.media.PlayRateController = class { } /** + * Get the default play rate of the playback. + * + * @return {number} + */ + getDefaultRate() { + return this.harness_.getDefaultRate(); + } + + /** * Reapply the effects of |this.rate_| and |this.active_| to the media * element. This will only update the rate via the harness if the desired rate * has changed. @@ -161,6 +170,7 @@ shaka.media.PlayRateController = class { /** * @typedef {{ * getRate: function():number, + * getDefaultRate: function():number, * setRate: function(number), * movePlayhead: function(number) * }} @@ -173,6 +183,9 @@ shaka.media.PlayRateController = class { * @property {function():number} getRate * Get the current playback rate being seen by the user. * + * @property {function():number} getDefaultRate + * Get the default playback rate that the user should see. + * * @property {function(number)} setRate * Set the playback rate that the user should see. * diff --git a/lib/player.js b/lib/player.js index <HASH>..<HASH> 100644 --- a/lib/player.js +++ b/lib/player.js @@ -1802,6 +1802,7 @@ shaka.Player = class extends shaka.util.FakeEventTarget { this.playRateController_ = new shaka.media.PlayRateController({ getRate: () => has.mediaElement.playbackRate, + getDefaultRate: () => has.mediaElement.defaultPlaybackRate, setRate: (rate) => { has.mediaElement.playbackRate = rate; }, movePlayhead: (delta) => { has.mediaElement.currentTime += delta; }, }); @@ -2084,6 +2085,7 @@ shaka.Player = class extends shaka.util.FakeEventTarget { this.playRateController_ = new shaka.media.PlayRateController({ getRate: () => has.mediaElement.playbackRate, + getDefaultRate: () => has.mediaElement.defaultPlaybackRate, setRate: (rate) => { has.mediaElement.playbackRate = rate; }, movePlayhead: (delta) => { has.mediaElement.currentTime += delta; }, }); @@ -3173,13 +3175,14 @@ shaka.Player = class extends shaka.util.FakeEventTarget { * @export */ cancelTrickPlay() { + const defaultPlaybackRate = this.playRateController_.getDefaultRate(); if (this.loadMode_ == shaka.Player.LoadMode.SRC_EQUALS) { - this.playRateController_.set(1); + this.playRateController_.set(defaultPlaybackRate); } if (this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE) { - this.playRateController_.set(1); - this.abrManager_.playbackRateChanged(1); + this.playRateController_.set(defaultPlaybackRate); + this.abrManager_.playbackRateChanged(defaultPlaybackRate); this.streamingEngine_.setTrickPlay(false); } } diff --git a/test/media/play_rate_controller_unit.js b/test/media/play_rate_controller_unit.js index <HASH>..<HASH> 100644 --- a/test/media/play_rate_controller_unit.js +++ b/test/media/play_rate_controller_unit.js @@ -12,6 +12,8 @@ describe('PlayRateController', () => { /** @type {!jasmine.Spy} */ let getPlayRateSpy; /** @type {!jasmine.Spy} */ + let getDefaultPlayRateSpy; + /** @type {!jasmine.Spy} */ let setPlayRateSpy; /** @type {!jasmine.Spy} */ let movePlayheadSpy; @@ -24,6 +26,7 @@ describe('PlayRateController', () => { beforeEach(() => { getPlayRateSpy = jasmine.createSpy('getPlaybackRate'); + getDefaultPlayRateSpy = jasmine.createSpy('getDefaultPlaybackRate'); setPlayRateSpy = jasmine.createSpy('setPlaybackRate'); movePlayheadSpy = jasmine.createSpy('movePlayhead'); @@ -36,6 +39,7 @@ describe('PlayRateController', () => { const harness = { getRate: shaka.test.Util.spyFunc(getPlayRateSpy), + getDefaultRate: shaka.test.Util.spyFunc(getDefaultPlayRateSpy), setRate: shaka.test.Util.spyFunc(setPlayRateSpy), movePlayhead: shaka.test.Util.spyFunc(movePlayheadSpy), }; diff --git a/ui/playback_rate_selection.js b/ui/playback_rate_selection.js index <HASH>..<HASH> 100644 --- a/ui/playback_rate_selection.js +++ b/ui/playback_rate_selection.js @@ -124,6 +124,7 @@ shaka.ui.PlaybackRateSelection = class extends shaka.ui.SettingsMenu { this.eventManager.listen(button, 'click', () => { this.video.playbackRate = this.playbackRates_.get(rateStr); + this.video.defaultPlaybackRate = this.playbackRates_.get(rateStr); }); this.menu.appendChild(button);
fix(ui): Play video with the previous speed after pause When we change the video play rate via UI, and pause and play the video, it resumes playing at 1. That's caused by 'cancelTrickPlay'. We can set the defaultPlaybackRate when changing the play rate, and use that value when we resume playing. Closes #<I> Change-Id: Ifc<I>ea<I>e<I>ae<I>bbb5c9c<I>f
google_shaka-player
train
3d0818d8ddee84aa53eba51ba8cf42775f09f040
diff --git a/tests/contrib_tests/ignite_tests/test_handler.py b/tests/contrib_tests/ignite_tests/test_handler.py index <HASH>..<HASH> 100644 --- a/tests/contrib_tests/ignite_tests/test_handler.py +++ b/tests/contrib_tests/ignite_tests/test_handler.py @@ -91,12 +91,10 @@ def test_post_metrics(client): @pytest.mark.skipif(not _ignite_installed, reason='Ignite is not installed') def test_post_metrics_with_interval(client): - step = 0 def stepper(engine, event_name): - nonlocal step - step += 1 - return step + engine.state.step += 1 + return engine.state.step handler = OutputHandler( 'test', metric_names='all', interval_step=2, @@ -104,6 +102,7 @@ def test_post_metrics_with_interval(client): metrics = {'loss': 0.1} engine = MagicMock() + engine.state.step = 0 engine.state.metrics = metrics logger = ChainerUILogger()
avoid to use nonlocal scope for python2
chainer_chainerui
train
332f96889f59005d51bdc3d46a90ef318352af5d
diff --git a/lib/assets/JavaScript.js b/lib/assets/JavaScript.js index <HASH>..<HASH> 100644 --- a/lib/assets/JavaScript.js +++ b/lib/assets/JavaScript.js @@ -405,7 +405,7 @@ class JavaScript extends Text { node, href: node.source.value }); - } else if (node.type === 'ExportNamedDeclaration') { + } else if (node.type === 'ExportNamedDeclaration' || node.type === 'ExportAllDeclaration') { outgoingRelations.push({ type: 'JavaScriptExport', node, diff --git a/test/relations/JavaScriptExport.js b/test/relations/JavaScriptExport.js index <HASH>..<HASH> 100644 --- a/test/relations/JavaScriptExport.js +++ b/test/relations/JavaScriptExport.js @@ -2,7 +2,7 @@ const expect = require('../unexpected-with-plugins'); const AssetGraph = require('../../lib/AssetGraph'); describe('JavaScriptExport', function () { - it('should detect a relation', function () { + it('should detect an ExportNamedDeclaration node', function () { const javaScript = new AssetGraph().addAsset({ type: 'JavaScript', url: 'https://example.com/', @@ -16,6 +16,20 @@ describe('JavaScriptExport', function () { ]); }); + it('should detect an ExportAllDeclaration node', function () { + const javaScript = new AssetGraph().addAsset({ + type: 'JavaScript', + url: 'https://example.com/', + text: ` + export * from 'bar/quux.js'; + ` + }); + + expect(javaScript.outgoingRelations, 'to satisfy', [ + { type: 'JavaScriptExport', href: 'bar/quux.js', to: { url: 'https://example.com/bar/quux.js' } } + ]); + }); + it('should update the href of a relation', function () { const javaScript = new AssetGraph().addAsset({ type: 'JavaScript',
JavaScriptExport: Add support for ExportAllDeclaration (export * from ...)
assetgraph_assetgraph
train
0fde9fe3e81c5726fb42ed4ffb19210d5f53024a
diff --git a/src/claviska/SimpleImage.php b/src/claviska/SimpleImage.php index <HASH>..<HASH> 100644 --- a/src/claviska/SimpleImage.php +++ b/src/claviska/SimpleImage.php @@ -1378,7 +1378,7 @@ class SimpleImage { imagefilledarc($tempImage->image, $x, $y, $width+$thickness, $height+$thickness, $start, $end, $tempColor, IMG_ARC_PIE); // Draw a smaller ellipse filled with red|blue (-$thickness pixels) - $tempColor = ($color == 'red') ? 'blue' : 'red'; + $tempColor = (self::normalizeColor($color)['red'] == 255) ? 'blue' : 'red'; $tempColor = $tempImage->allocateColor($tempColor); imagefilledarc($tempImage->image, $x, $y, $width-$thickness, $height-$thickness, $start, $end, $tempColor, IMG_ARC_PIE); @@ -1460,7 +1460,7 @@ class SimpleImage { imagefilledellipse($tempImage->image, $x, $y, $width+$thickness, $height+$thickness, $tempColor); // Draw a smaller ellipse filled with red|blue (-$thickness pixels) - $tempColor = ($color == 'red') ? 'blue' : 'red'; + $tempColor = (self::normalizeColor($color)['red'] == 255) ? 'blue' : 'red'; $tempColor = $tempImage->allocateColor($tempColor); imagefilledellipse($tempImage->image, $x, $y, $width-$thickness, $height-$thickness, $tempColor); @@ -1620,7 +1620,7 @@ class SimpleImage { $tempImage->roundedRectangle($x1, $y1, $x2, $y2, $radius, $color,'filled'); // Draw a smaller rectangle filled with red|blue (-$thickness pixels on each side) - $tempColor = ($color == 'red') ? 'blue' : 'red'; + $tempColor = (self::normalizeColor($color)['red'] == 255) ? 'blue' : 'red'; $radius = $radius - $thickness; $radius = self::keepWithin($radius, 0, $radius); $tempImage->roundedRectangle(
Fixes problem with red border in ellipse, arc and roundedRectangle (#<I>)
claviska_SimpleImage
train
970726b8748422dcc5e275313c735e28e84427b9
diff --git a/src/feat/test/integration/test_agencies_net_agency.py b/src/feat/test/integration/test_agencies_net_agency.py index <HASH>..<HASH> 100644 --- a/src/feat/test/integration/test_agencies_net_agency.py +++ b/src/feat/test/integration/test_agencies_net_agency.py @@ -403,7 +403,6 @@ class IntegrationTestCase(FullIntegrationTest, ModelTestMixin): @defer.inlineCallbacks def tearDown(self): - yield self.wait_for(self.agency.is_idle, 20) if self.shutdown: yield self.agency.full_shutdown() yield FullIntegrationTest.tearDown(self) diff --git a/src/feat/test/integration/test_agencies_standalone_agency.py b/src/feat/test/integration/test_agencies_standalone_agency.py index <HASH>..<HASH> 100644 --- a/src/feat/test/integration/test_agencies_standalone_agency.py +++ b/src/feat/test/integration/test_agencies_standalone_agency.py @@ -85,7 +85,6 @@ class FullIntegrationTestCase(FullIntegrationTest): @defer.inlineCallbacks def tearDown(self): - yield self.wait_for(self.agency.is_idle, 20) yield self.agency.shutdown(stop_process=False) yield FullIntegrationTest.tearDown(self) pid = run.get_pid(os.path.curdir) @@ -105,6 +104,7 @@ class FullIntegrationTestCase(FullIntegrationTest): yield self.wait_for_master_back() # we should have a pid now yield self.wait_for_pid(self.pid_path) + yield self.wait_for(self.agency.is_idle, 20) @defer.inlineCallbacks def testLockAlreadyTaken(self):
Fix issues with integration tests timing out in tearDown.
f3at_feat
train
07c48004954626e670ff5e3c446a4e5dfeaabc74
diff --git a/greycat/src/main/java/greycat/internal/custom/NDTree.java b/greycat/src/main/java/greycat/internal/custom/NDTree.java index <HASH>..<HASH> 100644 --- a/greycat/src/main/java/greycat/internal/custom/NDTree.java +++ b/greycat/src/main/java/greycat/internal/custom/NDTree.java @@ -360,7 +360,11 @@ public class NDTree extends BaseCustomType implements NDIndexer { EStruct root = _backend.root(); double[][] space = getRootSpace(root); check(keys, space[MIN], space[MAX]); - double[] resolution = ((DoubleArray) root.getAt(RESOLUTION)).extract(); + double[] resolution = null; + DoubleArray storedResolution = (DoubleArray) root.getAt(RESOLUTION); + if(storedResolution != null) { + resolution = storedResolution.extract(); + } int buffersize = root.getAtWithDefault(BUFFER_SIZE, BUFFER_SIZE_DEF);
Null pointer protection on NDTree
datathings_greycat
train
ad78345ad3d9fbbcba9a179e1d8ee257f03ff6aa
diff --git a/spyderlib/baseconfig.py b/spyderlib/baseconfig.py index <HASH>..<HASH> 100644 --- a/spyderlib/baseconfig.py +++ b/spyderlib/baseconfig.py @@ -20,7 +20,6 @@ import os import sys # Local imports -from spyderlib import __version__ from spyderlib.utils import encoding from spyderlib.py3compat import (is_unicode, TEXT_TYPES, INT_TYPES, PY3, to_text_string, is_text_string) @@ -61,7 +60,7 @@ def debug_print(*message): #============================================================================== # Spyder settings dir if TEST is None: - SUBFOLDER = '.spyder%s' % __version__.split('.')[0] + SUBFOLDER = '.spyder' else: SUBFOLDER = 'spyder_test' diff --git a/spyderlib/userconfig.py b/spyderlib/userconfig.py index <HASH>..<HASH> 100644 --- a/spyderlib/userconfig.py +++ b/spyderlib/userconfig.py @@ -42,6 +42,7 @@ import os.path as osp import shutil import time +from spyderlib import __version__ from spyderlib.baseconfig import (DEV, TEST, get_module_source_path, get_home_dir) from spyderlib.utils.programs import check_version @@ -154,7 +155,21 @@ class DefaultsConfig(cp.ConfigParser): if 'defaults' in self.name: folder = osp.join(folder, 'defaults') try: - os.makedirs(folder) + # Copying old config dir for Spyder 3.0. The new config + # dir for 3.0+ is going to be simply ~/.spyder{-py3} + if __version__.split('.')[0] == '3': + if PY2: + old_confdir = '.spyder2' + else: + old_confdir = '.spyder2-py3' + old_confdir = osp.join(get_home_dir(), old_confdir) + new_confdir = osp.join(get_home_dir(), self.subfolder) + if osp.isdir(old_confdir) and not osp.isdir(new_confdir): + shutil.copytree(old_confdir, new_confdir) + else: + os.makedirs(folder) + else: + os.makedirs(folder) except os.error: # Folder (or one of its parents) already exists pass
Rename configuration dir from ~/.spyder2{-py3} to ~/.spyder{-py3} This will make our life easier when doing major updates in version
spyder-ide_spyder
train
92f892a4673a9746ca4eba2122cce7b8c9da11dc
diff --git a/src/index.js b/src/index.js index <HASH>..<HASH> 100644 --- a/src/index.js +++ b/src/index.js @@ -138,7 +138,7 @@ export default class Bot extends EventEmitter { * @return {unknown} returns the result of calling message's send method */ send(message) { - return message.send(this).catch(console.error); + return message.send(this); } /**
Do not try to eat up request errors with catch as this will break rejection chain
mdibaiee_node-telegram-api
train
bdd1422ec442c20be7c901d14fcf6399b443a3d9
diff --git a/domain-management/src/main/java/org/jboss/as/domain/management/controller/FindNonProgressingOperationHandler.java b/domain-management/src/main/java/org/jboss/as/domain/management/controller/FindNonProgressingOperationHandler.java index <HASH>..<HASH> 100644 --- a/domain-management/src/main/java/org/jboss/as/domain/management/controller/FindNonProgressingOperationHandler.java +++ b/domain-management/src/main/java/org/jboss/as/domain/management/controller/FindNonProgressingOperationHandler.java @@ -75,6 +75,8 @@ public class FindNonProgressingOperationHandler implements OperationStepHandler DomainManagementResolver.getResolver(CORE, MANAGEMENT_OPERATIONS)) .setReplyType(ModelType.STRING) .withFlag(OperationEntry.Flag.HOST_CONTROLLER_ONLY) + .setReadOnly() + .setRuntimeOnly() .build(); static final OperationStepHandler INSTANCE = new FindNonProgressingOperationHandler();
[WFCORE-<I>] find-non-progressing-operation should be read-only and runtime-only
wildfly_wildfly-core
train
d4a4df005f3dfd80fada14dd35cb82dbe97e60b0
diff --git a/pyscreeze/__init__.py b/pyscreeze/__init__.py index <HASH>..<HASH> 100644 --- a/pyscreeze/__init__.py +++ b/pyscreeze/__init__.py @@ -24,14 +24,15 @@ from PIL import ImageOps try: import cv2, numpy useOpenCV = True + RUNNING_CV_2 = cv2.__version__[0] < '3' except ImportError: useOpenCV = False -RUNNING_CV_2 = cv2.__version__[0] < '3' RUNNING_PYTHON_2 = sys.version_info[0] == 2 +if useOpenCV: + LOAD_COLOR = cv2.CV_LOAD_IMAGE_COLOR if RUNNING_CV_2 else cv2.IMREAD_COLOR + LOAD_GRAYSCALE = cv2.CV_LOAD_IMAGE_GRAYSCALE if RUNNING_CV_2 else cv2.IMREAD_GRAYSCALE -LOAD_COLOR = cv2.CV_LOAD_IMAGE_COLOR if RUNNING_CV_2 else cv2.IMREAD_COLOR -LOAD_GRAYSCALE = cv2.CV_LOAD_IMAGE_GRAYSCALE if RUNNING_CV_2 else cv2.IMREAD_GRAYSCALE RAISE_IF_NOT_FOUND = False GRAYSCALE_DEFAULT = False
Updated the code to put all checks in the try/except, and reference the useOpenCV variable.
asweigart_pyscreeze
train
bd57a55cad3067061cc7f412244b745f8fcb7fca
diff --git a/spyder/plugins/ipythonconsole/widgets/client.py b/spyder/plugins/ipythonconsole/widgets/client.py index <HASH>..<HASH> 100644 --- a/spyder/plugins/ipythonconsole/widgets/client.py +++ b/spyder/plugins/ipythonconsole/widgets/client.py @@ -594,8 +594,10 @@ class ClientWidget(QWidget, SaveHistoryMixin): self.set_color_scheme(sw.syntax_style, reset=reset) sw._append_html(_("<br>Restarting kernel...\n<hr><br>"), before_prompt=True) - if reset: - self._hide_loading_page() + + self._hide_loading_page() + self.stop_button.setDisabled(True) + sw.refresh_namespacebrowser() self.restart_thread = None @Slot(str)
IPython Console: Correctly handle multiple restarts due to crashes when running code
spyder-ide_spyder
train
22e45daefd3a3cd13a5d2e5e1c4e3533582b82dc
diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/FaultRecoveringOutputStream.java b/okhttp/src/main/java/com/squareup/okhttp/internal/FaultRecoveringOutputStream.java index <HASH>..<HASH> 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/internal/FaultRecoveringOutputStream.java +++ b/okhttp/src/main/java/com/squareup/okhttp/internal/FaultRecoveringOutputStream.java @@ -84,15 +84,29 @@ public abstract class FaultRecoveringOutputStream extends OutputStream { if (closed) { return; // don't throw; this stream might have been closed on the caller's behalf } - out.flush(); + while (true) { + try { + out.flush(); + return; + } catch (IOException e) { + if (!recover(e)) throw e; + } + } } @Override public final void close() throws IOException { if (closed) { return; } - out.close(); - closed = true; + while (true) { + try { + out.close(); + closed = true; + return; + } catch (IOException e) { + if (!recover(e)) throw e; + } + } } /** diff --git a/okhttp/src/test/java/com/squareup/okhttp/internal/FaultRecoveringOutputStreamTest.java b/okhttp/src/test/java/com/squareup/okhttp/internal/FaultRecoveringOutputStreamTest.java index <HASH>..<HASH> 100644 --- a/okhttp/src/test/java/com/squareup/okhttp/internal/FaultRecoveringOutputStreamTest.java +++ b/okhttp/src/test/java/com/squareup/okhttp/internal/FaultRecoveringOutputStreamTest.java @@ -47,7 +47,7 @@ public final class FaultRecoveringOutputStreamTest { } } - @Test public void successfulRecovery() throws Exception { + @Test public void successfulRecoveryOnWriteFault() throws Exception { FaultingOutputStream faulting1 = new FaultingOutputStream(); FaultingOutputStream faulting2 = new FaultingOutputStream(); TestFaultRecoveringOutputStream recovering = new TestFaultRecoveringOutputStream(10, faulting1); @@ -70,6 +70,45 @@ public final class FaultRecoveringOutputStreamTest { assertEquals("abc", faulting2.receivedUtf8); } + @Test public void successfulRecoveryOnFlushFault() throws Exception { + FaultingOutputStream faulting1 = new FaultingOutputStream(); + FaultingOutputStream faulting2 = new FaultingOutputStream(); + TestFaultRecoveringOutputStream recovering = new TestFaultRecoveringOutputStream(10, faulting1); + recovering.replacements.addLast(faulting2); + + recovering.write('a'); + faulting1.nextFault = "bad weather"; + recovering.flush(); + assertEquals(Arrays.asList("bad weather"), recovering.exceptionMessages); + assertEquals("a", faulting1.receivedUtf8); + assertEquals("a", faulting2.receivedUtf8); + assertTrue(faulting1.closed); + assertFalse(faulting2.closed); + assertEquals("a", faulting2.flushedUtf8); + + // Confirm that new data goes to the new stream. + recovering.write('b'); + assertEquals("a", faulting1.receivedUtf8); + assertEquals("ab", faulting2.receivedUtf8); + assertEquals("a", faulting2.flushedUtf8); + } + + @Test public void successfulRecoveryOnCloseFault() throws Exception { + FaultingOutputStream faulting1 = new FaultingOutputStream(); + FaultingOutputStream faulting2 = new FaultingOutputStream(); + TestFaultRecoveringOutputStream recovering = new TestFaultRecoveringOutputStream(10, faulting1); + recovering.replacements.addLast(faulting2); + + recovering.write('a'); + faulting1.nextFault = "termites"; + recovering.close(); + assertEquals(Arrays.asList("termites"), recovering.exceptionMessages); + assertEquals("a", faulting1.receivedUtf8); + assertEquals("a", faulting2.receivedUtf8); + assertTrue(faulting1.closed); + assertTrue(faulting2.closed); + } + @Test public void replacementStreamFaultsImmediately() throws Exception { FaultingOutputStream faulting1 = new FaultingOutputStream(); FaultingOutputStream faulting2 = new FaultingOutputStream(); @@ -145,6 +184,7 @@ public final class FaultRecoveringOutputStreamTest { static class FaultingOutputStream extends OutputStream { String receivedUtf8 = ""; + String flushedUtf8 = null; String nextFault; boolean closed; @@ -157,8 +197,14 @@ public final class FaultRecoveringOutputStreamTest { if (nextFault != null) throw new IOException(nextFault); } + @Override public void flush() throws IOException { + flushedUtf8 = receivedUtf8; + if (nextFault != null) throw new IOException(nextFault); + } + @Override public void close() throws IOException { closed = true; + if (nextFault != null) throw new IOException(nextFault); } }
Recover from failed flushes and closes too.
square_okhttp
train