hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
995f2151233406cfe46e05ec9fcd5aed5ab4aef0
diff --git a/src/radical/entk/task.py b/src/radical/entk/task.py index <HASH>..<HASH> 100644 --- a/src/radical/entk/task.py +++ b/src/radical/entk/task.py @@ -27,6 +27,7 @@ class Task(object): `uid` offset the uid count file in radical.utils and can potentially affect the profiling if not taken care. ''' + _uids = list() # FIXME: this should be converted into an RU/RS Attribute object, almost all # of the code is redundant with the attribute class... @@ -1073,6 +1074,11 @@ class Task(object): executable has been specified for the task. ''' + if self._uid in Task._uids: + raise ree.EnTKError(msg='Task ID %s already exists' % self._uid) + else: + Task._uids.append(self._uid) + if self._state is not res.INITIAL: raise ree.ValueError(obj=self._uid, attribute='state', expected_value=res.INITIAL,
Tasks should have unique ids for tags to work properly
radical-cybertools_radical.entk
train
2bbca0809f97a7fc464200884cf946ebd1bda8fd
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -8,5 +8,8 @@ setup( author_email='dev@praekelt.com', url='https://github.com/praekelt/django-content', packages = find_packages(), + install_requires = [ + 'django-photologue==2.3', + ], include_package_data=True, )
requires django-photologue
praekelt_panya
train
84132752a5459f593f43b70cb5e5ef40f3aa0dac
diff --git a/Gemfile.lock b/Gemfile.lock index <HASH>..<HASH> 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: . specs: - exchange_wrapper (0.1.6) + exchange_wrapper (0.1.7) coinbase (~> 4.2) coinbase-exchange (~> 0.2) faraday (~> 0.14) diff --git a/lib/exchange_wrapper/binance/utils.rb b/lib/exchange_wrapper/binance/utils.rb index <HASH>..<HASH> 100644 --- a/lib/exchange_wrapper/binance/utils.rb +++ b/lib/exchange_wrapper/binance/utils.rb @@ -22,7 +22,7 @@ module ExchangeWrapper def symbols symbols = [] - ::ExchangeWrapper::Binance::PublicApi.exchange_info['symbols'].each do |symbol| + fetch_symbols.each do |symbol| next if symbol['symbol'] == '123456' # skip dummy symbol data symbols << symbol['baseAsset'] @@ -37,7 +37,7 @@ module ExchangeWrapper def trading_pairs trading_pairs = [] - ::ExchangeWrapper::Binance::PublicApi.exchange_info['symbols'].each do |symbol| + fetch_symbols.each do |symbol| next if symbol['symbol'] == '123456' # skip dummy symbol data trading_pairs << [ @@ -56,12 +56,44 @@ module ExchangeWrapper prices = ::ExchangeWrapper::Binance::PublicApi.prices.sort do |tp_0, tp_1| tp_0['symbol'] <=> tp_1['symbol'] end - # remove dummy trading pair - prices.delete_at(prices.index {|tp| tp['symbol'] == '123456'} || prices.length) + # remap the symbols with a '/' + # e.g. ETHBTC -> ETH/BTC + map = trading_pairs_map + prices.map! do |tp| + if tp['symbol'] == '123456' # skip dummy symbol data + nil + else + tp.merge!('symbol' => map[tp['symbol']]) + tp + end + end.compact! prices end + private + + def trading_pairs_map + trading_pairs_map = {} + + fetch_symbols.each do |symbol| + next if symbol['symbol'] == '123456' # skip dummy symbol data + + trading_pairs_map[symbol['symbol']] = "#{symbol['baseAsset']}/#{symbol['quoteAsset']}" + end + + trading_pairs_map + end + + def fetch_symbols + if defined?(::Rails) + ::Rails.cache.fetch('binance-public-api-exchange-info', expires_in: 58.seconds) do + ::ExchangeWrapper::Binance::PublicApi.exchange_info + end + else + ::ExchangeWrapper::Binance::PublicApi.exchange_info + end['symbols'] + end end end end diff --git a/lib/exchange_wrapper/version.rb b/lib/exchange_wrapper/version.rb index <HASH>..<HASH> 100644 --- a/lib/exchange_wrapper/version.rb +++ b/lib/exchange_wrapper/version.rb @@ -1,3 +1,3 @@ module ExchangeWrapper - VERSION = "0.1.6" + VERSION = "0.1.7" end
add conditional rails caching to avoid taxing binance api; add "/" to prices symbols
ericmwalsh_exchange_wrapper_gem
train
73f0e1a8423d53370f272841ce29747434de4d9a
diff --git a/actionpack/test/abstract/translation_test.rb b/actionpack/test/abstract/translation_test.rb index <HASH>..<HASH> 100644 --- a/actionpack/test/abstract/translation_test.rb +++ b/actionpack/test/abstract/translation_test.rb @@ -9,18 +9,18 @@ class TranslationControllerTest < Test::Unit::TestCase end def test_action_controller_base_responds_to_translate - assert @controller.respond_to?(:translate) + assert_respond_to @controller, :translate end def test_action_controller_base_responds_to_t - assert @controller.respond_to?(:t) + assert_respond_to @controller, :t end def test_action_controller_base_responds_to_localize - assert @controller.respond_to?(:localize) + assert_respond_to @controller, :localize end def test_action_controller_base_responds_to_l - assert @controller.respond_to?(:l) + assert_respond_to @controller, :l end end \ No newline at end of file diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb index <HASH>..<HASH> 100644 --- a/actionpack/test/controller/integration_test.rb +++ b/actionpack/test/controller/integration_test.rb @@ -176,8 +176,8 @@ class IntegrationTestTest < Test::Unit::TestCase session1 = @test.open_session { |sess| } session2 = @test.open_session # implicit session - assert session1.respond_to?(:assert_template), "open_session makes assert_template available" - assert session2.respond_to?(:assert_template), "open_session makes assert_template available" + assert_respond_to session1, :assert_template, "open_session makes assert_template available" + assert_respond_to session2, :assert_template, "open_session makes assert_template available" assert !session1.equal?(session2) end diff --git a/actionpack/test/controller/send_file_test.rb b/actionpack/test/controller/send_file_test.rb index <HASH>..<HASH> 100644 --- a/actionpack/test/controller/send_file_test.rb +++ b/actionpack/test/controller/send_file_test.rb @@ -55,8 +55,8 @@ class SendFileTest < ActionController::TestCase response = nil assert_nothing_raised { response = process('file') } assert_not_nil response - assert response.body_parts.respond_to?(:each) - assert response.body_parts.respond_to?(:to_path) + assert_respond_to response.body_parts, :each + assert_respond_to response.body_parts, :to_path require 'stringio' output = StringIO.new
Use assert_respond_to because it has better error messaging [#<I> state:resolved]
rails_rails
train
62e8bc7d098b9a489de0fa2cb447f36542b60d04
diff --git a/ratcave/wavefront.py b/ratcave/wavefront.py index <HASH>..<HASH> 100644 --- a/ratcave/wavefront.py +++ b/ratcave/wavefront.py @@ -133,6 +133,12 @@ class WavefrontReader(object): return prefix, value + # parsing in 3 steps: + # - read all data in [lines] list + # - split each mesh section in {mtls} dict + # - parse each mesh section and create material from it + + # STEP1: read all data in [lines] list try: with open(filename, 'r') as material_file: lines = [line for line in material_file] @@ -147,17 +153,25 @@ class WavefrontReader(object): mtl_name_buff = '' mtl_line_buff = [] - for i, line in enumerate(lines): - if line.startswith('newmtl') or i == len(lines) - 1: - if mtl_name_buff: - mtls[mtl_name_buff] = mtl_line_buff + # STEP 2: split each mesh section in {mtls} dict + # empty lines as newmtl section separators + separators = [0] + [i for i, x in enumerate(lines) if x == "\n"] + [len(lines)] + + for i in range(len(separators) - 1): + for line in lines[separators[i]:separators[i + 1]]: + if line.startswith('newmtl'): + mtl_name_buff = line.strip('\n').split(' ')[1] + + elif len(line.strip('\n')) > 0: + mtl_line_buff.append(line.strip('\n')) - mtl_name_buff = line.strip('\n').split(' ')[1] - mtl_line_buff = [] + if mtl_name_buff: + mtls[mtl_name_buff] = mtl_line_buff - elif len(line.strip('\n')) > 0: - mtl_line_buff.append(line.strip('\n')) + mtl_name_buff = '' + mtl_line_buff = [] + # STEP 3: parse each newmtl section into Material prefixes = ['#', 'newmtl', 'Ns', 'Ka', 'Kd', 'Ks', 'Ni', 'd', 'illum', 'map_Kd'] for name, lines in mtls.items():
fixed a bug in wavefront object parsing
ratcave_ratcave
train
e2527cd8426b94c10ac7ae46750aef2dc1b6a7fa
diff --git a/resources/views/panel/roles-assignment/index.blade.php b/resources/views/panel/roles-assignment/index.blade.php index <HASH>..<HASH> 100644 --- a/resources/views/panel/roles-assignment/index.blade.php +++ b/resources/views/panel/roles-assignment/index.blade.php @@ -6,7 +6,7 @@ <div class="flex flex-col"> <div class="-my-2 py-2 overflow-x-auto sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8"> <div - x-data="{ model: new URLSearchParams(location.search).get('model') || 'initial' }" + x-data="{ model: @if($modelKey) '{{$modelKey}}' @else 'initial' @endif }" x-init="$watch('model', value => value != 'initial' ? window.location = `?model=${value}` : '')" class="mt-4 align-middle inline-block min-w-full shadow overflow-hidden sm:rounded-lg border-b border-gray-200 p-4" > @@ -59,7 +59,7 @@ </table> </div> @if ($modelKey) - {{ $users->withQueryString()->links('laratrust::panel.pagination') }} + {{ $users->appends(['model' => $modelKey])->links('laratrust::panel.pagination') }} @endif </div> diff --git a/src/Http/Controllers/RolesAssignmentController.php b/src/Http/Controllers/RolesAssignmentController.php index <HASH>..<HASH> 100644 --- a/src/Http/Controllers/RolesAssignmentController.php +++ b/src/Http/Controllers/RolesAssignmentController.php @@ -23,18 +23,20 @@ class RolesAssignmentController public function index(Request $request) { - $modelKey = $request->get('model'); + $modelsKeys = array_keys(Config::get('laratrust.user_models')); + $modelKey = $request->get('model') ?? $modelsKeys[0] ?? null; $userModel = Config::get('laratrust.user_models')[$modelKey] ?? null; - $users = $userModel - ? $userModel::query() - ->withCount(['roles', 'permissions']) - ->simplePaginate(10) - : []; + + if (!$userModel) { + abort(404); + } return View::make('laratrust::panel.roles-assignment.index', [ - 'models' => array_keys(Config::get('laratrust.user_models')), + 'models' => $modelsKeys, 'modelKey' => $modelKey, - 'users' => $users, + 'users' => $userModel::query() + ->withCount(['roles', 'permissions']) + ->simplePaginate(10), ]); } diff --git a/tests/LaratrustTestCase.php b/tests/LaratrustTestCase.php index <HASH>..<HASH> 100644 --- a/tests/LaratrustTestCase.php +++ b/tests/LaratrustTestCase.php @@ -26,6 +26,7 @@ class LaratrustTestCase extends TestCase 'prefix' => '', ]); $app['config']->set('laratrust.user_models.users', 'Laratrust\Tests\Models\User'); + $app['config']->set('laratrust.panel.register', true); $app['config']->set('laratrust.models', [ 'role' => 'Laratrust\Tests\Models\Role', 'permission' => 'Laratrust\Tests\Models\Permission',
Use a default model when entering the roles assignment view
santigarcor_laratrust
train
b2a14915793376e055bd3a69bb87c535ef0c2f8b
diff --git a/web/app.js b/web/app.js index <HASH>..<HASH> 100644 --- a/web/app.js +++ b/web/app.js @@ -7,7 +7,7 @@ const pod = require('../lib/api'), ghURL = require('parse-github-url'), app = express(), - favicon = require('serve-favicon'), + // favicon = require('serve-favicon'), statics = require('serve-static'), basicAuth = require('basic-auth'); @@ -34,7 +34,7 @@ var auth = function(username, password) { app.set('views', __dirname + '/views') app.set('view engine', 'ejs') -app.use(favicon()) +//app.use(favicon()) app.use(reloadConf) app.use(app.router) app.use(bodyParser.json())
Remove favicon as we don't have one
yyx990803_pod
train
589ecb1c52832d304c1fb5c4c421708c1bb308e8
diff --git a/jsonrpcserver/dispatcher.py b/jsonrpcserver/dispatcher.py index <HASH>..<HASH> 100644 --- a/jsonrpcserver/dispatcher.py +++ b/jsonrpcserver/dispatcher.py @@ -123,10 +123,6 @@ def dispatch(methods, request): response = Request(request).process(methods) except JsonRpcServerError as e: response = ExceptionResponse(e, None) - except Exception as e: # pylint: disable=broad-except - # Log the uncaught exception - logger.exception(e) - response = ExceptionResponse(e, None) http_status = 200 if isinstance(request, list) else response.http_status response_log.info(str(response), extra={ 'http_code': http_status,
Don't return library exceptions to client
bcb_jsonrpcserver
train
71f7b4df85ef4027051b39336fa04e0668f8f742
diff --git a/eventsourcingtests/test_stored_events.py b/eventsourcingtests/test_stored_events.py index <HASH>..<HASH> 100644 --- a/eventsourcingtests/test_stored_events.py +++ b/eventsourcingtests/test_stored_events.py @@ -8,14 +8,14 @@ from eventsourcingtests.test_domain_events import Example class TestStoredEvent(unittest.TestCase): - def test_stored_event_from_domain_event(self): + def test_serialize_domain_event(self): event1 = Example.Event(a=1, b=2, entity_id='entity1', timestamp=3) stored_event = serialize_domain_event(event1) self.assertEqual('entity1', stored_event.entity_id) self.assertEqual('eventsourcingtests.test_domain_events#Example.Event', stored_event.event_topic) self.assertEqual('{"a":1,"b":2,"entity_id":"entity1","timestamp":3}', stored_event.event_attrs) - def test_domain_event_from_stored_event(self): + def test_recreate_domain_event(self): stored_event = StoredEvent(event_id='1', entity_id='entity1', event_topic='eventsourcingtests.test_domain_events#Example.Event',
Changed test method names, to match methods under test.
johnbywater_eventsourcing
train
c1e2a7619485494f4f52d370cc6fb9b73bb3a929
diff --git a/openquake/risklib/riskinput.py b/openquake/risklib/riskinput.py index <HASH>..<HASH> 100644 --- a/openquake/risklib/riskinput.py +++ b/openquake/risklib/riskinput.py @@ -275,6 +275,16 @@ class CompositeRiskModel(collections.Mapping): iml[rf.imt].append(rf.imls[0]) return {imt: min(iml[imt]) for imt in iml} + def get_imts(self): + """ + Returns a sorted list of IMTs defined in the underlying models + """ + imts = set() + for loss_type in self.loss_types: + for taxonomy in self.taxonomies: + imts.add(self[taxonomy].risk_functions[loss_type].imt) + return sorted(imts) + def build_loss_dtypes(self, conditional_loss_poes, insured_losses=False): """ :param conditional_loss_poes: @@ -452,9 +462,10 @@ class CompositeRiskModel(collections.Mapping): :param monitor: a monitor object used to measure the performance :param assetcol: not None only for event based risk """ + mon_context = monitor('building context') mon_hazard = monitor('building hazard') mon_risk = monitor('computing risk', measuremem=False) - with mon_hazard: + with mon_context: assets_by_site = (riskinput.assets_by_site if assetcol is None else assetcol.assets_by_site()) hazard_getter = riskinput.hazard_getter( @@ -469,19 +480,19 @@ class CompositeRiskModel(collections.Mapping): epsgetter = riskinput.epsilon_getter( [asset.ordinal for asset in group[taxonomy]]) dic[taxonomy].append((i, group[taxonomy], epsgetter)) - - with mon_risk: + imts = self.get_imts() + for rlz in rlzs_assoc.realizations: + with mon_hazard: + hazard = {imt: hazard_getter.get(imt, rlz) for imt in imts} for loss_type in self.loss_types: - for rlz in rlzs_assoc.realizations: - for taxonomy in self.taxonomies: - riskmodel = self[taxonomy] - imt = riskmodel.risk_functions[loss_type].imt - hazard = hazard_getter.get(imt, rlz) + for taxonomy in self.taxonomies: + riskmodel = self[taxonomy] + haz = hazard[riskmodel.risk_functions[loss_type].imt] + with mon_risk: for i, assets, epsgetter in dic[taxonomy]: - haz = hazard[i] - if len(haz): + if len(haz[i]): out = riskmodel( - loss_type, assets, haz, epsgetter) + loss_type, assets, haz[i], epsgetter) if out: # can be None in scenario_risk out.lr = self.lti[loss_type], rlz.ordinal yield out @@ -534,8 +545,12 @@ class GmfGetter(object): def __init__(self, trti, gsims, ebruptures, sitecol, imts, min_iml, truncation_level, correlation_model, samples): self.trti = trti + self.gsims = gsims + self.imts = imts self.min_iml = { from_string(imt): min for imt, min in zip(imts, min_iml)} + self.truncation_level = truncation_level + self.correlation_model = correlation_model self.samples = samples self.sids = sitecol.sids self.computers = []
Computing the hazard only once per realization Former-commit-id: 1c3e<I>ab<I>c<I>c<I>fdff5ca<I>b1
gem_oq-engine
train
c07160dd70054ae40db14aa18e8476b25ca3d20b
diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/Tuple.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/Tuple.java index <HASH>..<HASH> 100644 --- a/vertx-sql-client/src/main/java/io/vertx/sqlclient/Tuple.java +++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/Tuple.java @@ -1388,20 +1388,10 @@ public interface Tuple { throw new IllegalArgumentException("Accessor type can not be null"); } Object value = getValue(pos); - if (value.getClass() == type) { + if (value != null && type.isAssignableFrom(value.getClass())) { return type.cast(value); - } else { - try { - if (value instanceof Buffer) { - return type.cast(value); - } else if (value instanceof Temporal) { - return type.cast(value); - } - } catch (ClassCastException e) { - throw new IllegalArgumentException("mismatched type [" + type.getName() + "] for the value of type [" + value.getClass().getName() + "]"); - } - throw new IllegalArgumentException("mismatched type [" + type.getName() + "] for the value of type [" + value.getClass().getName() + "]"); } + return null; } @GenIgnore @@ -1410,11 +1400,10 @@ public interface Tuple { throw new IllegalArgumentException("Accessor type can not be null"); } Object value = getValue(pos); - if (value.getClass().isArray() && value.getClass().getComponentType() == type) { + if (value != null && value.getClass().isArray() && type.isAssignableFrom(value.getClass().getComponentType())) { return (T[]) value; - } else { - throw new IllegalArgumentException("mismatched array element type [" + type.getName() + "] for the value of type [" + value.getClass().getName() + "]"); } + return null; } @GenIgnore @@ -1428,7 +1417,7 @@ public interface Tuple { int size(); void clear(); - + /** * @return A String containing the {@link Object#toString} value of each element, * separated by a comma (,) character
Improve type casting in Tuple#get and Tuple#getValues
reactiverse_reactive-pg-client
train
92627d1a46c7f6c6cb1fb92f92217d35de55cb78
diff --git a/src/Database/Schema/Table.php b/src/Database/Schema/Table.php index <HASH>..<HASH> 100644 --- a/src/Database/Schema/Table.php +++ b/src/Database/Schema/Table.php @@ -335,6 +335,21 @@ class Table { } /** + * Get a hash of columns and their default values. + * + * @return array + */ + public function defaultValues() { + $defaults = []; + foreach ($this->_columns as $name => $data) { + if (isset($data['default'])) { + $defaults[$name] = $data['default']; + } + } + return $defaults; + } + +/** * Add an index. * * Used to add indexes, and full text indexes in platforms that support diff --git a/tests/TestCase/Database/Schema/TableTest.php b/tests/TestCase/Database/Schema/TableTest.php index <HASH>..<HASH> 100644 --- a/tests/TestCase/Database/Schema/TableTest.php +++ b/tests/TestCase/Database/Schema/TableTest.php @@ -150,10 +150,34 @@ class TableTest extends TestCase { } /** - * Test adding an constraint. + * Test reading default values. * * @return void */ + public function testDefaultValues() { + $table = new Table('articles'); + $table->addColumn('id', [ + 'type' => 'integer', + 'default' => 0 + ])->addColumn('title', [ + 'type' => 'string', + 'default' => 'A title' + ])->addColumn('body', [ + 'type' => 'text', + ]); + $result = $table->defaultValues(); + $expected = [ + 'id' => 0, + 'title' => 'A title' + ]; + $this->assertEquals($expected, $result); + } + +/** + * Test adding an constraint. + *> + * @return void + */ public function testAddConstraint() { $table = new Table('articles'); $table->addColumn('id', [
Add Table::defaultValues() This makes it easy to get the default values from a schema table. Having this is really useful when you want to make an entity with the default values from the database. Refs #<I>
cakephp_cakephp
train
4fd34e88c4f5a9dfdad5a17708f0998c9d858e6f
diff --git a/source/rafcon/core/state_elements/state_element.py b/source/rafcon/core/state_elements/state_element.py index <HASH>..<HASH> 100644 --- a/source/rafcon/core/state_elements/state_element.py +++ b/source/rafcon/core/state_elements/state_element.py @@ -111,7 +111,7 @@ class StateElement(Observable, YAMLObject, JSONObject, Hashable): # In case of just the data type is wrong raise an Exception but keep the data flow if "not have matching data types" in message: do_delete_item = False - self._parent = parent + self._parent = ref(parent) raise RecoveryModeException("{0} invalid within state \"{1}\" (id {2}): {3}".format( class_name, parent.name, parent.state_id, message), do_delete_item=do_delete_item) else:
fix(state element): for invalid element _parent always weakref or None
DLR-RM_RAFCON
train
da8dedab3413eaf98e08f0077d10b850e1b38f8b
diff --git a/fonte.rb b/fonte.rb index <HASH>..<HASH> 100644 --- a/fonte.rb +++ b/fonte.rb @@ -21,7 +21,7 @@ class Fonte include Constants def initialize file - @file = File.open file + @file = File.open file, "rb:ASCII-8BIT" end def offset_table @@ -31,12 +31,35 @@ class Fonte end def tables - accumulator = [] + entries = [] @file.seek table_records_begin offset_table.tables_count.times do chunk = @file.read table_record_size - accumulator << TableRecord.new(*(chunk.unpack 'a4N3')) + entries << TableRecord.new(*(chunk.unpack 'a4N3')) end - accumulator - end + entries + end + + def feature_list + seek_to_table 'GSUB' + gsub_header = @file.read(10).unpack 'n5' + feature_list_offset = gsub_header[3] + + @file.seek(feature_list_offset + find_table('GSUB').offset) + + feature_count = @file.read(2).unpack 'n' + acc = [] + feature_count[0].times do + acc << @file.read(6).unpack('a4n')[0] + end + acc.uniq + end + + def seek_to_table tag + @file.seek find_table(tag).offset + end + + def find_table tag + tables.select { |t| t.tag == tag }.first + end end diff --git a/spec/fonte_spec.rb b/spec/fonte_spec.rb index <HASH>..<HASH> 100644 --- a/spec/fonte_spec.rb +++ b/spec/fonte_spec.rb @@ -7,9 +7,22 @@ describe Fonte do fonte.offset_table.version.should eq "OTTO" end - it "reads the table tables" do + it "reads the table record entries" do fonte = Fonte.new 'spec/hobo.otf' fonte.tables.first.tag.should eq "BASE" end end + + context "reads simple font information" do + it "reads the feature list" do + fonte = Fonte.new 'spec/hobo.otf' + fonte.feature_list.should eq ['aalt', 'frac', 'liga', 'ordn', 'sups'] + end + + it "reads the font name" + + it "reads the font style" + + it "reads the font family name" + end end
We can now derive a simple feature list from the font file
hugobast_tipo
train
4dddcbdf2296e0f7c79c2a9b43082d9219c419db
diff --git a/geopy/geocoders/google.py b/geopy/geocoders/google.py index <HASH>..<HASH> 100644 --- a/geopy/geocoders/google.py +++ b/geopy/geocoders/google.py @@ -36,9 +36,9 @@ class Google(Geocoder): geocode should be interpolated before querying the geocoder. For example: '%s, Mountain View, CA'. The default is just '%s'. - ``output_format`` (DEPRECATED) can be 'json', 'xml', 'kml', or 'csv' and will - control the output format of Google's response. The default is 'kml' - since it is supported by both the 'maps' and 'maps/geo' resources. + ``output_format`` (DEPRECATED) can be 'json', 'xml', or 'kml' and will + control the output format of Google's response. The default is 'json'. 'kml' is + an alias for 'xml'. """ if resource != None: from warnings import warn @@ -54,12 +54,15 @@ class Google(Geocoder): self.format_string = format_string if output_format: - if output_format not in ('json','xml','kml','csv'): - raise ValueError('if defined, `output_format` must be one of: "json","xml","kml","csv"') + if output_format not in ('json','xml','kml'): + raise ValueError('if defined, `output_format` must be one of: "json","xml","kml"') else: - self.output_format = output_format + if output_format == "kml": + self.output_format = "xml" + else: + self.output_format = output_format else: - self.output_format = "kml" + self.output_format = "xml" @property def url(self): @@ -124,12 +127,6 @@ class Google(Geocoder): else: return [parse_place(place) for place in places] - def parse_csv(self, page, exactly_one=True): - raise NotImplementedError - - def parse_kml(self, page, exactly_one=True): - return self.parse_xml(page, exactly_one) - def parse_json(self, page, exactly_one=True): if not isinstance(page, basestring): page = util.decode_page(page) @@ -157,42 +154,6 @@ class Google(Geocoder): else: return [parse_place(place) for place in places] - def parse_js(self, page, exactly_one=True): - """This parses JavaScript returned by queries the actual Google Maps - interface and could thus break easily. However, this is desirable if - the HTTP geocoder doesn't work for addresses in your country (the - UK, for example). - """ - if not isinstance(page, basestring): - page = util.decode_page(page) - - LATITUDE = r"[\s,]lat:\s*(?P<latitude>-?\d+\.\d+)" - LONGITUDE = r"[\s,]lng:\s*(?P<longitude>-?\d+\.\d+)" - LOCATION = r"[\s,]laddr:\s*'(?P<location>.*?)(?<!\\)'," - ADDRESS = r"(?P<address>.*?)(?:(?: \(.*?@)|$)" - MARKER = '.*?'.join([LATITUDE, LONGITUDE, LOCATION]) - MARKERS = r"{markers: (?P<markers>\[.*?\]),\s*polylines:" - - def parse_marker(marker): - latitude, longitude, location = marker - location = re.match(ADDRESS, location).group('address') - latitude, longitude = float(latitude), float(longitude) - return (location, (latitude, longitude)) - - match = re.search(MARKERS, page) - markers = match and match.group('markers') or '' - markers = re.findall(MARKER, markers) - - if exactly_one: - if len(markers) != 1: - raise ValueError("Didn't find exactly one marker! " \ - "(Found %d.)" % len(markers)) - - marker = markers[0] - return parse_marker(marker) - else: - return [parse_marker(marker) for marker in markers] - def check_status_code(self,status_code): if status_code == 400: raise GeocoderResultError("Bad request (Server returned status 400)")
Fully remove the 'js' output format in Google backend. Goes along with r<I> which actually disabled it. git-svn-id: <URL>
geopy_geopy
train
cf562afbe72eee89cbebbf96972b2ada8f462ba7
diff --git a/src/org/joml/sampling/Math.java b/src/org/joml/sampling/Math.java index <HASH>..<HASH> 100644 --- a/src/org/joml/sampling/Math.java +++ b/src/org/joml/sampling/Math.java @@ -68,4 +68,12 @@ class Math { return a < b ? a : b; } + static int min(int a, int b) { + return a < b ? a : b; + } + + static int max(int a, int b) { + return a > b ? a : b; + } + } diff --git a/src/org/joml/sampling/PoissonSampling.java b/src/org/joml/sampling/PoissonSampling.java index <HASH>..<HASH> 100644 --- a/src/org/joml/sampling/PoissonSampling.java +++ b/src/org/joml/sampling/PoissonSampling.java @@ -127,13 +127,13 @@ public class PoissonSampling { int col = (int) ((p.x + diskRadius) / cellSize); if (grid[row * numCells + col] != null) return true; - for (int y = -1; y <= +1; y++) { - if (y + row < 0 || y + row > numCells - 1) - continue; - for (int x = -1; x <= +1; x++) { - if (x + col < 0 || x + col > numCells - 1) - continue; - Vector2f v = grid[(row + y) * numCells + (col + x)]; + int minX = Math.max(0, col - 1); + int minY = Math.max(0, row - 1); + int maxX = Math.min(col + 1, numCells - 1); + int maxY = Math.min(row + 1, numCells - 1); + for (int y = minY; y <= maxY; y++) { + for (int x = minX; x <= maxX; x++) { + Vector2f v = grid[y * numCells + x]; if (v != null && v.distanceSquared(p) < minDistSquared) { return true; }
Improve performance of PoissonSampling
JOML-CI_JOML
train
a43dbc8bcd4840f3be0fbf0c87fe791b5665ce1f
diff --git a/fastlane_core/lib/fastlane_core/version.rb b/fastlane_core/lib/fastlane_core/version.rb index <HASH>..<HASH> 100644 --- a/fastlane_core/lib/fastlane_core/version.rb +++ b/fastlane_core/lib/fastlane_core/version.rb @@ -1,3 +1,3 @@ module FastlaneCore - VERSION = "0.38.0".freeze + VERSION = "0.39.0".freeze end
[fastlane_core] version bump
fastlane_fastlane
train
ba4655eeb823fb7eaf6269dea5b96cad0df6b675
diff --git a/src/global/fun.php b/src/global/fun.php index <HASH>..<HASH> 100644 --- a/src/global/fun.php +++ b/src/global/fun.php @@ -128,8 +128,8 @@ function _isset($var): bool { return isset($var); } function _empty($var): bool { return empty($var); } // safe trim for strict mode -function _trim($input): string { - return trim((string) $input); +function _trim($input, $chrs = " \t\n\r\0\x0B"): string { + return trim((string) $input, $chrs); } // boolval
Add $chrs arg.
froq_froq
train
debf8bb5cc3e3b80a7eabe9f91c76829ecb672f5
diff --git a/src/pps/jobserver/api_server.go b/src/pps/jobserver/api_server.go index <HASH>..<HASH> 100644 --- a/src/pps/jobserver/api_server.go +++ b/src/pps/jobserver/api_server.go @@ -104,6 +104,22 @@ func (a *apiServer) ListJob(ctx context.Context, request *pps.ListJobRequest) (r }, nil } +func (a *apiServer) GetJobLogs(request *pps.GetJobLogsRequest, responseServer pps.JobAPI_GetJobLogsServer) (err error) { + // TODO(pedge): filter by output stream + persistJobLogs, err := a.persistAPIClient.GetJobLogs(context.Background(), request.Job) + if err != nil { + return err + } + for _, persistJobLog := range persistJobLogs.JobLog { + if persistJobLog.OutputStream == request.OutputStream { + if err := responseServer.Send(&google_protobuf.BytesValue{Value: persistJobLog.Value}); err != nil { + return err + } + } + } + return nil +} + // TODO(pedge): bulk get func (a *apiServer) persistJobInfoToJobInfo(ctx context.Context, persistJobInfo *persist.JobInfo) (*pps.JobInfo, error) { job := &pps.Job{Id: persistJobInfo.JobId} @@ -144,19 +160,3 @@ func (a *apiServer) persistJobInfoToJobInfo(ctx context.Context, persistJobInfo } return jobInfo, nil } - -func (a *apiServer) GetJobLogs(request *pps.GetJobLogsRequest, responseServer pps.JobAPI_GetJobLogsServer) (err error) { - // TODO(pedge): filter by output stream - persistJobLogs, err := a.persistAPIClient.GetJobLogs(context.Background(), request.Job) - if err != nil { - return err - } - for _, persistJobLog := range persistJobLogs.JobLog { - if persistJobLog.OutputStream == request.OutputStream { - if err := responseServer.Send(&google_protobuf.BytesValue{Value: persistJobLog.Value}); err != nil { - return err - } - } - } - return nil -}
move pps api job serve function persistJobInfoToJobInfo to bottom of file
pachyderm_pachyderm
train
5cb80a38efb6914a8b5382d7daca38de1db0cc9c
diff --git a/src/Carbon/Lang/cs.php b/src/Carbon/Lang/cs.php index <HASH>..<HASH> 100644 --- a/src/Carbon/Lang/cs.php +++ b/src/Carbon/Lang/cs.php @@ -30,4 +30,9 @@ return [ 'before' => ':time předtím', 'first_day_of_week' => 1, 'day_of_first_week_of_year' => 4, + 'months' => ['Leden', 'Únor', 'Březen', 'Duben', 'Květen', 'Červen', 'Červenec', 'Srpen', 'Září', 'Říjen', 'Listopad', 'Prosinec'], + 'months_short' => ['Led', 'Úno', 'Bře', 'Dub', 'Kvě', 'Čer', 'Čer', 'Srp', 'Zář', 'Říj', 'Lis', 'Pro'], + 'weekdays' => ['Neděle', 'Pondělí', 'Úterý', 'Středa', 'Čtvrtek', 'Pátek', 'Sobota'], + 'weekdays_short' => ['Ned', 'Pon', 'Úte', 'Stř', 'Čtv', 'Pát', 'Sob'], + 'weekdays_min' => ['Ne', 'Po', 'Út', 'St', 'Čt', 'Pá', 'So'], ];
Extends czech localization (#<I>)
briannesbitt_Carbon
train
d8e84973cc3b79bfdebd2e65d5af8b9c279d16e6
diff --git a/EntityService/DateRepeatService.php b/EntityService/DateRepeatService.php index <HASH>..<HASH> 100755 --- a/EntityService/DateRepeatService.php +++ b/EntityService/DateRepeatService.php @@ -82,24 +82,6 @@ class DateRepeatService implements HookServiceTriggerInterface return $entity; } - /** - * This method is being called by the scheduler to check whether - * an entity's trigger hook allows the scheduler to execute - * the entity's Job. - * - * @param $entity - * @return bool - */ - public function isExecutable($entity){ - $now = new \DateTime('now', new \DateTimeZone('UTC')); - - if($entity->getIntervalStartDate() <= $now){ - return true; - } - - return false; - } - public function arrayToObject($hookData){ if(is_array($hookData) && count($hookData)){ $datetimeUtil = $this->container->get('campaignchain.core.util.datetime');
CE-<I> Repeating campaign
CampaignChain_hook-data-repeat
train
f9a4df16f3ec7d2f052f1525580680510132fe3d
diff --git a/src/Tsufeki/BlancheJsonRpc/Mapper/MapperFactory.php b/src/Tsufeki/BlancheJsonRpc/Mapper/MapperFactory.php index <HASH>..<HASH> 100644 --- a/src/Tsufeki/BlancheJsonRpc/Mapper/MapperFactory.php +++ b/src/Tsufeki/BlancheJsonRpc/Mapper/MapperFactory.php @@ -15,7 +15,7 @@ class MapperFactory ->addDumper(new ExceptionDumper()) ->addLoader(new ExceptionLoader()) ->throwOnUnknownProperty(true) - ->throwOnMissingProperty(false) + ->throwOnMissingProperty(true) ->getMapper(); } } diff --git a/src/Tsufeki/BlancheJsonRpc/Message/ResultResponse.php b/src/Tsufeki/BlancheJsonRpc/Message/ResultResponse.php index <HASH>..<HASH> 100644 --- a/src/Tsufeki/BlancheJsonRpc/Message/ResultResponse.php +++ b/src/Tsufeki/BlancheJsonRpc/Message/ResultResponse.php @@ -5,7 +5,7 @@ namespace Tsufeki\BlancheJsonRpc\Message; class ResultResponse extends Response { /** - * @var mixed + * @var mixed|null */ public $result;
Properly error on missing properties.
tsufeki_blanche-json-rpc
train
4e1d6b9e6c1c1b13d8245f5a0a9267e840d2e436
diff --git a/flux_led/models_db.py b/flux_led/models_db.py index <HASH>..<HASH> 100755 --- a/flux_led/models_db.py +++ b/flux_led/models_db.py @@ -975,6 +975,7 @@ MODELS = [ ), LEDENETModel( model_num=0x35, + # 'AK001-ZJ200' is v5.17 # 'AK001-ZJ2101' is v7.63 # 'AK001-ZJ2104' is v7.07 # 'AK001-ZJ2145' is v8.47, v8.56 - seen on 7w bulbs @@ -982,6 +983,7 @@ MODELS = [ # 'AK001-ZJ2147' is v9.7 (with RF remote control support) # 'AK001-ZJ21410' is v9.91 seen on the Bunpeon smart floor light ASIN:B09MN65324 models=[ + "AK001-ZJ200", "AK001-ZJ2101", "AK001-ZJ2104", "AK001-ZJ2145",
Add older models to 0x<I> (#<I>)
Danielhiversen_flux_led
train
f76aace34c77a179a587a091b5809c4565b41492
diff --git a/app/models/viewable.rb b/app/models/viewable.rb index <HASH>..<HASH> 100644 --- a/app/models/viewable.rb +++ b/app/models/viewable.rb @@ -1,6 +1,8 @@ module Viewable extend ActiveSupport::Concern + # TODO fallback for translations + included do self.table_name_prefix = 'viewable_'
todo added for translation fallback
o2web_rails_admin_cms
train
d2205228fb1676d4f6a176c936a888758a4f2380
diff --git a/internal/model/rwfolder.go b/internal/model/rwfolder.go index <HASH>..<HASH> 100644 --- a/internal/model/rwfolder.go +++ b/internal/model/rwfolder.go @@ -109,6 +109,13 @@ func newRWFolder(m *Model, shortID uint64, cfg config.FolderConfiguration) *rwFo } } +// Helper function to check whether either the ignorePerm flag has been +// set on the local host or the FlagNoPermBits has been set on the file/dir +// which is being pulled. +func (p *rwFolder) ignorePermissions(file protocol.FileInfo) bool { + return p.ignorePerms || file.Flags&protocol.FlagNoPermBits != 0 +} + // Serve will run scans and pulls. It will return when Stop()ed or on a // critical error. func (p *rwFolder) Serve() { @@ -540,7 +547,7 @@ func (p *rwFolder) handleDir(file protocol.FileInfo) { realName := filepath.Join(p.dir, file.Name) mode := os.FileMode(file.Flags & 0777) - if p.ignorePerms { + if p.ignorePermissions(file) { mode = 0777 } @@ -569,7 +576,7 @@ func (p *rwFolder) handleDir(file protocol.FileInfo) { // not MkdirAll because the parent should already exist. mkdir := func(path string) error { err = os.Mkdir(path, mode) - if err != nil || p.ignorePerms { + if err != nil || p.ignorePermissions(file) { return err } return os.Chmod(path, mode) @@ -592,7 +599,7 @@ func (p *rwFolder) handleDir(file protocol.FileInfo) { // don't handle modification times on directories, because that sucks...) // It's OK to change mode bits on stuff within non-writable directories. - if p.ignorePerms { + if p.ignorePermissions(file) { p.dbUpdates <- file } else if err := os.Chmod(realName, mode); err == nil { p.dbUpdates <- file @@ -858,7 +865,7 @@ func (p *rwFolder) handleFile(file protocol.FileInfo, copyChan chan<- copyBlocks copyTotal: len(blocks), copyNeeded: len(blocks), reused: reused, - ignorePerms: p.ignorePerms, + ignorePerms: p.ignorePermissions(file), version: curFile.Version, mut: sync.NewMutex(), } @@ -878,7 +885,7 @@ func (p *rwFolder) handleFile(file protocol.FileInfo, copyChan chan<- copyBlocks // thing that has changed. func (p *rwFolder) shortcutFile(file protocol.FileInfo) error { realName := filepath.Join(p.dir, file.Name) - if !p.ignorePerms { + if !p.ignorePermissions(file) { if err := os.Chmod(realName, os.FileMode(file.Flags&0777)); err != nil { l.Infof("Puller (folder %q, file %q): shortcut: chmod: %v", p.folder, file.Name, err) return err @@ -1076,7 +1083,7 @@ func (p *rwFolder) performFinish(state *sharedPullerState) { }() // Set the correct permission bits on the new file - if !p.ignorePerms { + if !p.ignorePermissions(state.file) { err = os.Chmod(state.tempName, os.FileMode(state.file.Flags&0777)) if err != nil { l.Warnln("Puller: final:", err)
Make syncthing honor both the ignorePerms and FlagNoPermBits settings (fixes #<I>)
syncthing_syncthing
train
9c7d9c1c6310e916340f8b102dc02dd421f499d3
diff --git a/vent/api/plugin_helpers.py b/vent/api/plugin_helpers.py index <HASH>..<HASH> 100644 --- a/vent/api/plugin_helpers.py +++ b/vent/api/plugin_helpers.py @@ -3,11 +3,11 @@ import fnmatch import json import requests import shlex +import socket from ast import literal_eval from os import chdir, getcwd, walk from os.path import expanduser, join -from subprocess import check_output, Popen, PIPE, STDOUT from vent.api.templates import Template from vent.helpers.logs import Logger @@ -653,11 +653,12 @@ class PluginHelper: if result[0]: host = result[1] else: - route = Popen(('/sbin/ip', 'route'), stdout=PIPE) - h = check_output(('awk', '/default/ {print $3}'), - stdin=route.stdout) - route.wait() - host = h.strip() + s = socket.socket(socket.AF_INET, + socket.SOCK_DGRAM) + s.connect(("8.8.8.8", 80)) + host = s.getsockname()[0] + s.shutdown() + s.close() nd_url = 'http://' + host + ':' + port + '/v1.0/docker/cli' params = {'vol': 'nvidia_driver'} diff --git a/vent/core/rq_worker/watch.py b/vent/core/rq_worker/watch.py index <HASH>..<HASH> 100644 --- a/vent/core/rq_worker/watch.py +++ b/vent/core/rq_worker/watch.py @@ -124,11 +124,11 @@ def file_queue(path, template_path="/vent/"): import json import requests import os + import socket import sys from redis import Redis from rq import Queue - from subprocess import check_output, Popen, PIPE from string import punctuation status = (True, None) @@ -289,11 +289,12 @@ def file_queue(path, template_path="/vent/"): vent_config.has_option('nvidia-docker-plugin', 'host')): host = vent_config.get('nvidia-docker-plugin', 'host') else: - route = Popen(('/sbin/ip', 'route'), stdout=PIPE) - h = check_output(('awk', '/default/ {print $3}'), - stdin=route.stdout) - route.wait() - host = h.strip() + s = socket.socket(socket.AF_INET, + socket.SOCK_DGRAM) + s.connect(("8.8.8.8", 80)) + host = s.getsockname()[0] + s.shutdown() + s.close() nd_url = 'http://' + host + ':' + port + '/v1.0/docker/cli' params = {'vol': 'nvidia_driver'} try:
create socket object to connect to google DNS and return it's own IP address
CyberReboot_vent
train
4fed07347f156e2a39fea104b6ac0f4eace1b405
diff --git a/includes/lib/utilities.php b/includes/lib/utilities.php index <HASH>..<HASH> 100644 --- a/includes/lib/utilities.php +++ b/includes/lib/utilities.php @@ -227,8 +227,8 @@ function papi_get_only_arrays( array $arr ) { * @return array */ -function papi_get_only_objects( array $arr ) { - return array_filter( $arr, function ( $item ) { +function papi_get_only_objects( $arr ) { + return array_filter( papi_to_array( $arr ), function ( $item ) { return is_object( $item ); } ); } diff --git a/includes/properties/class-papi-property-image.php b/includes/properties/class-papi-property-image.php index <HASH>..<HASH> 100644 --- a/includes/properties/class-papi-property-image.php +++ b/includes/properties/class-papi-property-image.php @@ -48,9 +48,8 @@ class Papi_Property_Image extends Papi_Property { $settings = $this->get_settings(); $value = papi_to_array( $this->get_value() ); - $value = array_filter( $value, function ( $image ) { - return is_object( $image ); - } ); + // Keep only objects. + $value = papi_get_only_objects( $value ); $slug = $options->slug; $show_button = empty( $value ); diff --git a/includes/properties/class-papi-property-post.php b/includes/properties/class-papi-property-post.php index <HASH>..<HASH> 100644 --- a/includes/properties/class-papi-property-post.php +++ b/includes/properties/class-papi-property-post.php @@ -76,7 +76,7 @@ class Papi_Property_Post extends Papi_Property { } // Keep only objects. - $posts = papi_get_only_objects( papi_to_array( $posts ) ); + $posts = papi_get_only_objects( $posts ); ?> diff --git a/includes/properties/class-papi-property-relationship.php b/includes/properties/class-papi-property-relationship.php index <HASH>..<HASH> 100644 --- a/includes/properties/class-papi-property-relationship.php +++ b/includes/properties/class-papi-property-relationship.php @@ -136,7 +136,7 @@ class Papi_Property_Relationship extends Papi_Property { ) ) ); // Keep only objects. - $posts = papi_get_only_objects( papi_to_array( $posts ) ); + $posts = papi_get_only_objects( $posts ); ?> <div class="papi-property-relationship">
Changed to papi_get_only_objects calls papi_to_array
wp-papi_papi
train
ae379e3b57b1534868da2dbc383b3eeae379ac54
diff --git a/tests/test_git_ext.py b/tests/test_git_ext.py index <HASH>..<HASH> 100644 --- a/tests/test_git_ext.py +++ b/tests/test_git_ext.py @@ -33,3 +33,15 @@ class JtimeGitTestCase(unittest.TestCase): side_effect=git.errors.InvalidGitRepositoryError ) self.repo.branch + + def test_get_last_commit_message(self): + type(self.repo).active_branch = mock.PropertyMock( + return_value='master' + ) + self.assertIsInstance(self.repo.get_last_commit_message(), basestring) + + def test_get_last_commit_message_raises_InvalidGitRepositoryError(self): + type(self.repo).active_branch = mock.PropertyMock( + side_effect=git.errors.InvalidGitRepositoryError + ) + self.assertEquals(self.repo.get_last_commit_message(), None)
Adding some more tests around the git_ext module.
mapmyfitness_jtime
train
183648f44f4a4e7a01f8838144ec788cb4cc32c2
diff --git a/server/statistics_handler_test.go b/server/statistics_handler_test.go index <HASH>..<HASH> 100644 --- a/server/statistics_handler_test.go +++ b/server/statistics_handler_test.go @@ -106,6 +106,7 @@ func (ds *testDumpStatsSuite) TestDumpStatsAPI(c *C) { c.Assert(err, IsNil) fp.Write(js) ds.checkData(c, path) + ds.checkCorrelation(c) // sleep for 1 seconds to ensure the existence of tidb.test time.Sleep(time.Second) @@ -179,6 +180,34 @@ func (ds *testDumpStatsSuite) prepare4DumpHistoryStats(c *C) { dbt.mustExec("create table tidb.test (a int, b varchar(20))") } +func (ds *testDumpStatsSuite) checkCorrelation(c *C) { + db, err := sql.Open("mysql", getDSN(nil)) + c.Assert(err, IsNil, Commentf("Error connecting")) + dbt := &DBTest{c, db} + defer db.Close() + + dbt.mustExec("use tidb") + rows := dbt.mustQuery("SELECT tidb_table_id FROM information_schema.tables WHERE table_name = 'test' AND table_schema = 'tidb'") + var tableID int64 + if rows.Next() { + rows.Scan(&tableID) + dbt.Check(rows.Next(), IsFalse, Commentf("unexpected data")) + } else { + dbt.Error("no data") + } + rows.Close() + rows = dbt.mustQuery("select correlation from mysql.stats_histograms where table_id = ? and hist_id = 1 and is_index = 0", tableID) + if rows.Next() { + var corr float64 + rows.Scan(&corr) + dbt.Check(corr, Equals, float64(1)) + dbt.Check(rows.Next(), IsFalse, Commentf("unexpected data")) + } else { + dbt.Error("no data") + } + rows.Close() +} + func (ds *testDumpStatsSuite) checkData(c *C, path string) { db, err := sql.Open("mysql", getDSN(func(config *mysql.Config) { config.AllowAllFiles = true diff --git a/statistics/handle/dump.go b/statistics/handle/dump.go index <HASH>..<HASH> 100644 --- a/statistics/handle/dump.go +++ b/statistics/handle/dump.go @@ -44,6 +44,7 @@ type jsonColumn struct { NullCount int64 `json:"null_count"` TotColSize int64 `json:"tot_col_size"` LastUpdateVersion uint64 `json:"last_update_version"` + Correlation float64 `json:"correlation"` } func dumpJSONCol(hist *statistics.Histogram, CMSketch *statistics.CMSketch) *jsonColumn { @@ -52,6 +53,7 @@ func dumpJSONCol(hist *statistics.Histogram, CMSketch *statistics.CMSketch) *jso NullCount: hist.NullCount, TotColSize: hist.TotColSize, LastUpdateVersion: hist.LastUpdateVersion, + Correlation: hist.Correlation, } if CMSketch != nil { jsonCol.CMSketch = statistics.CMSketchToProto(CMSketch) @@ -191,7 +193,7 @@ func TableStatsFromJSON(tableInfo *model.TableInfo, physicalID int64, jsonTbl *J continue } hist := statistics.HistogramFromProto(jsonIdx.Histogram) - hist.ID, hist.NullCount, hist.LastUpdateVersion = idxInfo.ID, jsonIdx.NullCount, jsonIdx.LastUpdateVersion + hist.ID, hist.NullCount, hist.LastUpdateVersion, hist.Correlation = idxInfo.ID, jsonIdx.NullCount, jsonIdx.LastUpdateVersion, jsonIdx.Correlation idx := &statistics.Index{ Histogram: *hist, CMSketch: statistics.CMSketchFromProto(jsonIdx.CMSketch), @@ -213,7 +215,7 @@ func TableStatsFromJSON(tableInfo *model.TableInfo, physicalID int64, jsonTbl *J if err != nil { return nil, errors.Trace(err) } - hist.ID, hist.NullCount, hist.LastUpdateVersion, hist.TotColSize = colInfo.ID, jsonCol.NullCount, jsonCol.LastUpdateVersion, jsonCol.TotColSize + hist.ID, hist.NullCount, hist.LastUpdateVersion, hist.TotColSize, hist.Correlation = colInfo.ID, jsonCol.NullCount, jsonCol.LastUpdateVersion, jsonCol.TotColSize, jsonCol.Correlation col := &statistics.Column{ PhysicalID: physicalID, Histogram: *hist, diff --git a/statistics/histogram.go b/statistics/histogram.go index <HASH>..<HASH> 100644 --- a/statistics/histogram.go +++ b/statistics/histogram.go @@ -162,6 +162,7 @@ func (hg *Histogram) DecodeTo(tp *types.FieldType, timeZone *time.Location) erro // ConvertTo converts the histogram bucket values into `Tp`. func (hg *Histogram) ConvertTo(sc *stmtctx.StatementContext, tp *types.FieldType) (*Histogram, error) { hist := NewHistogram(hg.ID, hg.NDV, hg.NullCount, hg.LastUpdateVersion, tp, hg.Len(), hg.TotColSize) + hist.Correlation = hg.Correlation iter := chunk.NewIterator4Chunk(hg.Bounds) for row := iter.Begin(); row != iter.End(); row = iter.Next() { d := row.GetDatum(0, hg.Tp)
statistics: support dump/load correlation of histogram (#<I>)
pingcap_tidb
train
410f4268e1b51460cf84ec9eabdaca71149a6034
diff --git a/querydsl-sql/src/test/java/com/mysema/query/sql/SQLSerializerTest.java b/querydsl-sql/src/test/java/com/mysema/query/sql/SQLSerializerTest.java index <HASH>..<HASH> 100644 --- a/querydsl-sql/src/test/java/com/mysema/query/sql/SQLSerializerTest.java +++ b/querydsl-sql/src/test/java/com/mysema/query/sql/SQLSerializerTest.java @@ -87,9 +87,10 @@ public class SQLSerializerTest { SQLSerializer serializer = new SQLSerializer(Configuration.DEFAULT); serializer.handle(sq); - assertEquals("(select user.id, user.username\n" + - "from user\n" + - "where user.id = ?)", serializer.toString()); + //USER is a reserved word in ANSI SQL 2008 + assertEquals("(select \"user\".id, \"user\".username\n" + + "from \"user\"\n" + + "where \"user\".id = ?)", serializer.toString()); } @Test @@ -103,9 +104,10 @@ public class SQLSerializerTest { SQLSerializer serializer = new SQLSerializer(Configuration.DEFAULT); serializer.handle(sq); - assertEquals("(select user.id, user.username\n" + - "from user\n" + - "where user.id = ?)", serializer.toString()); + //USER is a reserved word in ANSI SQL 2008 + assertEquals("(select \"user\".id, \"user\".username\n" + + "from \"user\"\n" + + "where \"user\".id = ?)", serializer.toString()); } @Test
Update SQLSerializerTest to expect quoting of reserved words
querydsl_querydsl
train
100e7327bcfd60925a74258512e63aaf39021297
diff --git a/src/main/java/io/github/biezhi/wechat/api/WeChatApiImpl.java b/src/main/java/io/github/biezhi/wechat/api/WeChatApiImpl.java index <HASH>..<HASH> 100644 --- a/src/main/java/io/github/biezhi/wechat/api/WeChatApiImpl.java +++ b/src/main/java/io/github/biezhi/wechat/api/WeChatApiImpl.java @@ -680,6 +680,7 @@ public class WeChatApiImpl implements WeChatApi { WeChatMessage.WeChatMessageBuilder weChatMessageBuilder = WeChatMessage.builder() .raw(message) + .id(message.getId()) .fromUserName(message.getFromUserName()) .toUserName(message.getToUserName()) .msgType(message.msgType()) diff --git a/src/main/java/io/github/biezhi/wechat/api/client/BotClient.java b/src/main/java/io/github/biezhi/wechat/api/client/BotClient.java index <HASH>..<HASH> 100644 --- a/src/main/java/io/github/biezhi/wechat/api/client/BotClient.java +++ b/src/main/java/io/github/biezhi/wechat/api/client/BotClient.java @@ -101,6 +101,12 @@ public class BotClient { if (!"webpush.web.wechat.com".equals(okHttpRequest.url().host())) { cookieStore.put("webpush.web.wechat.com", cookies); } + if (!"webpush.wx2.qq.com".equals(okHttpRequest.url().host())) { + cookieStore.put("webpush.wx2.qq.com", cookies); + } + if (!"wx2.qq.com".equals(okHttpRequest.url().host())) { + cookieStore.put("wx2.qq.com", cookies); + } if (!"file.web.wechat.com".equals(okHttpRequest.url().host())) { cookieStore.put("file.web.wechat.com", cookies); } diff --git a/src/main/java/io/github/biezhi/wechat/api/model/Invoke.java b/src/main/java/io/github/biezhi/wechat/api/model/Invoke.java index <HASH>..<HASH> 100644 --- a/src/main/java/io/github/biezhi/wechat/api/model/Invoke.java +++ b/src/main/java/io/github/biezhi/wechat/api/model/Invoke.java @@ -9,7 +9,11 @@ import lombok.Data; import lombok.extern.slf4j.Slf4j; import java.lang.reflect.Method; +import java.util.HashSet; import java.util.List; +import java.util.Set; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; /** * 消息执行器 @@ -22,6 +26,8 @@ import java.util.List; @AllArgsConstructor public class Invoke { + private static final Set<String> INVOKED_MSG = new HashSet<>(); + private Method method; private List<AccountType> accountTypes; private MsgType msgType; @@ -35,16 +41,22 @@ public class Invoke { */ public <T extends WeChatBot> void call(T bot, WeChatMessage message) { try { + if (INVOKED_MSG.contains(message.getId())) { + return; + } Account account = bot.api().getAccountById(message.getFromUserName()); if (null == account) { + INVOKED_MSG.add(message.getId()); method.invoke(bot, message); return; } if (msgType == MsgType.ALL || msgType == message.getMsgType()) { if (message.getMsgType() == MsgType.ADD_FRIEND) { + INVOKED_MSG.add(message.getId()); method.invoke(bot, message); } else { if (accountTypes.contains(account.getAccountType())) { + INVOKED_MSG.add(message.getId()); method.invoke(bot, message); } } diff --git a/src/main/java/io/github/biezhi/wechat/api/model/Member.java b/src/main/java/io/github/biezhi/wechat/api/model/Member.java index <HASH>..<HASH> 100644 --- a/src/main/java/io/github/biezhi/wechat/api/model/Member.java +++ b/src/main/java/io/github/biezhi/wechat/api/model/Member.java @@ -28,7 +28,7 @@ public class Member { private String remarkName; @SerializedName("AttrStatus") - private Integer attrStatus; + private Long attrStatus; @SerializedName("MemberStatus") private Integer memberStatus; diff --git a/src/main/java/io/github/biezhi/wechat/api/model/WeChatMessage.java b/src/main/java/io/github/biezhi/wechat/api/model/WeChatMessage.java index <HASH>..<HASH> 100644 --- a/src/main/java/io/github/biezhi/wechat/api/model/WeChatMessage.java +++ b/src/main/java/io/github/biezhi/wechat/api/model/WeChatMessage.java @@ -25,6 +25,11 @@ public class WeChatMessage { private Message raw; /** + * mssage_id + */ + private String id; + + /** * 文本内容 */ private String text;
:ambulance: to ensure that the message is processed only once
biezhi_wechat-api
train
6bd082c3a23b1b96f0a9563d8c224a16e495c5a4
diff --git a/tests/test_representation.py b/tests/test_representation.py index <HASH>..<HASH> 100644 --- a/tests/test_representation.py +++ b/tests/test_representation.py @@ -31,7 +31,7 @@ Tests to verify that string representations are accurate from . import TestCase import bitmath -class TestBasicMath(TestCase): +class TestRepresentation(TestCase): def setUp(self): self.kib = bitmath.KiB(1) self.kib_repr = 'KiB(1.0)' diff --git a/tests/test_sorting.py b/tests/test_sorting.py index <HASH>..<HASH> 100644 --- a/tests/test_sorting.py +++ b/tests/test_sorting.py @@ -32,7 +32,7 @@ import unittest from . import TestCase import bitmath -class TestRichComparison(TestCase): +class TestSorting(TestCase): def test_sort_homogeneous_list(self): """Same types in a list can be sorted properly""" first = bitmath.kB(0) diff --git a/tests/test_to_Type_conversion.py b/tests/test_to_Type_conversion.py index <HASH>..<HASH> 100644 --- a/tests/test_to_Type_conversion.py +++ b/tests/test_to_Type_conversion.py @@ -32,7 +32,7 @@ from . import TestCase import bitmath from bitmath import NIST_STEPS, NIST_PREFIXES -class TestBasicMath(TestCase): +class TestToTypeConversion(TestCase): def setUp(self): self.bit = bitmath.Bit(1) self.byte = bitmath.Byte(1) diff --git a/tests/test_to_built_in_conversion.py b/tests/test_to_built_in_conversion.py index <HASH>..<HASH> 100644 --- a/tests/test_to_built_in_conversion.py +++ b/tests/test_to_built_in_conversion.py @@ -36,7 +36,7 @@ import sys if sys.version > '3': long = int -class TestBasicMath(TestCase): +class TestToBuiltInConversion(TestCase): def test_to_int(self): """int(bitmath) returns an int"""
Fix some duplicated test class names.
tbielawa_bitmath
train
bb24f8f8d6fd9d8ef057518806a8324eca6c4c24
diff --git a/base.php b/base.php index <HASH>..<HASH> 100644 --- a/base.php +++ b/base.php @@ -2623,6 +2623,9 @@ class Cache extends Prefab { //! View handler class View extends Prefab { + private + //! Temporary stored HIVE. + $sandboxedHive; protected //! Template file @@ -2701,8 +2704,10 @@ class View extends Prefab { if (isset($hive['ALIASES'])) $hive['ALIASES']=$fw->build($hive['ALIASES']); } - extract($hive); + $this->sandboxedHive=$hive; unset($fw,$hive,$implicit,$mime); + extract($this->sandboxedHive); + $this->sandboxedHive=NULL; $this->level++; ob_start(); require($this->template);
View: Don't delete sandboxed variables (#<I>) * View: Don't delete sandboxed variables (except `$hive` for this commit) References: * <URL>
bcosca_fatfree-core
train
b9f615fa4f9773cfbff4178d240a538cd956e176
diff --git a/benchexec/runexecutor.py b/benchexec/runexecutor.py index <HASH>..<HASH> 100644 --- a/benchexec/runexecutor.py +++ b/benchexec/runexecutor.py @@ -68,35 +68,45 @@ def main(argv=None): """Execute a command with resource limits and measurements. Command-line parameters can additionally be read from a file if file name prefixed with '@' is given as argument. Part of BenchExec: https://github.com/sosy-lab/benchexec/""") - parser.add_argument("--input", metavar="FILE", - help="name of file used as stdin for command (default: /dev/null; use - for stdin passthrough)") - parser.add_argument("--output", default="output.log", metavar="FILE", - help="name of file where command output is written") - parser.add_argument("--maxOutputSize", type=util.parse_memory_value, metavar="BYTES", - help="shrink output file to approximately this size if necessary (by removing lines from the middle of the output)") - parser.add_argument("--memlimit", type=util.parse_memory_value, metavar="BYTES", - help="memory limit in bytes") - parser.add_argument("--timelimit", type=util.parse_timespan_value, metavar="SECONDS", - help="CPU time limit in seconds") - parser.add_argument("--softtimelimit", type=util.parse_timespan_value, metavar="SECONDS", - help='"soft" CPU time limit in seconds (command will be send the TERM signal at this time)') - parser.add_argument("--walltimelimit", type=util.parse_timespan_value, metavar="SECONDS", - help='wall time limit in seconds (default is CPU time limit plus a few seconds)') - parser.add_argument("--cores", type=util.parse_int_list, metavar="N,M-K", - help="list of CPU cores to use") - parser.add_argument("--memoryNodes", type=util.parse_int_list, metavar="N,M-K", - help="list of memory nodes to use") - parser.add_argument("--require-cgroup-subsystem", action="append", default=[], metavar="SUBSYSTEM", - help="additional cgroup system that should be enabled for runs (may be specified multiple times)") - parser.add_argument("--set-cgroup-value", action="append", dest="cgroup_values", default=[], - metavar="SUBSYSTEM.OPTION=VALUE", - help="additional cgroup values that should be set for runs (e.g., 'cpu.shares=1000')") - parser.add_argument("--dir", metavar="DIR", - help="working directory for executing the command (default is current directory)") - parser.add_argument("--user", metavar="USER", - help="execute tool under given user account (needs password-less sudo setup)") - parser.add_argument("--skip-cleanup", action="store_false", dest="cleanup", - help="do not delete files created by the tool in temp directory") + + resource_args = parser.add_argument_group("optional arguments for resource limits") + resource_args.add_argument("--memlimit", type=util.parse_memory_value, metavar="BYTES", + help="memory limit in bytes") + resource_args.add_argument("--timelimit", type=util.parse_timespan_value, metavar="SECONDS", + help="CPU time limit in seconds") + resource_args.add_argument("--softtimelimit", type=util.parse_timespan_value, metavar="SECONDS", + help='"soft" CPU time limit in seconds (command will be send the TERM signal at this time)') + resource_args.add_argument("--walltimelimit", type=util.parse_timespan_value, metavar="SECONDS", + help='wall time limit in seconds (default is CPU time limit plus a few seconds)') + resource_args.add_argument("--cores", type=util.parse_int_list, metavar="N,M-K", + help="list of CPU cores to use") + resource_args.add_argument("--memoryNodes", type=util.parse_int_list, metavar="N,M-K", + help="list of memory nodes to use") + + io_args = parser.add_argument_group("optional arguments for run I/O") + io_args.add_argument("--input", metavar="FILE", + help="name of file used as stdin for command " + "(default: /dev/null; use - for stdin passthrough)") + io_args.add_argument("--output", default="output.log", metavar="FILE", + help="name of file where command output is written") + io_args.add_argument("--maxOutputSize", type=util.parse_memory_value, metavar="BYTES", + help="shrink output file to approximately this size if necessary " + "(by removing lines from the middle of the output)") + io_args.add_argument("--skip-cleanup", action="store_false", dest="cleanup", + help="do not delete files created by the tool in temp directory") + + environment_args = parser.add_argument_group("optional arguments for run environment") + environment_args.add_argument("--require-cgroup-subsystem", action="append", default=[], metavar="SUBSYSTEM", + help="additional cgroup system that should be enabled for runs " + "(may be specified multiple times)") + environment_args.add_argument("--set-cgroup-value", action="append", dest="cgroup_values", default=[], + metavar="SUBSYSTEM.OPTION=VALUE", + help="additional cgroup values that should be set for runs (e.g., 'cpu.shares=1000')") + environment_args.add_argument("--dir", metavar="DIR", + help="working directory for executing the command (default is current directory)") + environment_args.add_argument("--user", metavar="USER", + help="execute tool under given user account (needs password-less sudo setup)") + baseexecutor.add_basic_executor_options(parser) options = parser.parse_args(argv[1:])
Reorder command-line arguments for runexec and group them.
sosy-lab_benchexec
train
671f738c8e00a945102d671e1f80679a30cccbf9
diff --git a/dingo/grid/mv_grid/mv_routing.py b/dingo/grid/mv_grid/mv_routing.py index <HASH>..<HASH> 100644 --- a/dingo/grid/mv_grid/mv_routing.py +++ b/dingo/grid/mv_grid/mv_routing.py @@ -6,7 +6,7 @@ from dingo.grid.mv_grid.solvers import savings, local_search from dingo.tools.geo import calc_geo_dist_vincenty, calc_geo_dist_matrix_vincenty from dingo.core.network.stations import * from dingo.core.structure.regions import LVLoadAreaCentreDingo -from dingo.core.network import BranchDingo +from dingo.core.network import BranchDingo, CircuitBreakerDingo def dingo_graph_to_routing_specs(graph): @@ -89,6 +89,11 @@ def routing_solution_to_dingo_graph(graph, solution): mv_branches = [BranchDingo() for _ in edges] edges_with_branches = list(zip(edges, mv_branches)) + # recalculate circuit breaker positions for final solution and create + circ_breaker_pos = r.calc_circuit_breaker_position() + circ_breaker = CircuitBreakerDingo(grid=depot_node.grid, branch=mv_branches[circ_breaker_pos-1]) + depot_node.grid.add_circuit_breaker(circ_breaker) + # translate solution's node names to graph node objects using dict created before # note: branch object is assigned to edge using an attribute ('branch' is used here), it can be accessed # using the method `graph_edges()` of class `GridDingo`
add creation of circuit breakers after routing
openego_ding0
train
e51c8d4763f4cbecff570ebe9432d1b3f4bea918
diff --git a/bokeh/widgetobjects.py b/bokeh/widgetobjects.py index <HASH>..<HASH> 100644 --- a/bokeh/widgetobjects.py +++ b/bokeh/widgetobjects.py @@ -73,7 +73,7 @@ class BokehApplet(PlotObject): def update(self, **kwargs): super(BokehApplet, self).update(**kwargs) - self. setup_events() + self.setup_events() def setup_events(self): if self.modelform: @@ -90,7 +90,11 @@ class BokehApplet(PlotObject): def create(self): pass - + def add_all(self, session): + objs = self.references() + for obj in objs: + session.add(obj) + @classmethod def add_route(cls, route, bokeh_url): from bokeh.server.app import bokeh_app diff --git a/examples/app/applet/example.py b/examples/app/applet/example.py index <HASH>..<HASH> 100644 --- a/examples/app/applet/example.py +++ b/examples/app/applet/example.py @@ -47,7 +47,6 @@ class MyApp(BokehApplet): creating all objects (plots, datasources, etc) """ self.modelform = MyModel() - session.add(self.modelform) self.modelform.create_inputs(session) self.source = ColumnDataSource(data={'x':[], 'y':[]}) self.update_data() @@ -57,6 +56,7 @@ class MyApp(BokehApplet): ) self.children.append(self.modelform) self.children.append(self.plot) + self.add_all(session) def input_change(self, obj, attrname, old, new): """ @@ -153,17 +153,15 @@ class StockApp(BokehApplet): creating all objects (plots, datasources, etc) """ self.modelform = StockInputModel() - session.add(self.modelform) self.modelform.create_inputs(session) ticker1 = self.modelform.ticker1 ticker2 = self.modelform.ticker2 self.pretext = PreText(text="") - session.add(self.pretext) self.make_source(ticker1, ticker2) self.make_plots(ticker1, ticker2) self.make_stats() self.set_children() - + self.add_all(session) def make_source(self, ticker1, ticker2): df = self.get_data(ticker1, ticker2)
convenience function to add all descendant objects of an applet
bokeh_bokeh
train
c1b9f74f98d2c3b65b026e8de06da7b1c4f41c7e
diff --git a/plugin/dnssec/dnssec.go b/plugin/dnssec/dnssec.go index <HASH>..<HASH> 100644 --- a/plugin/dnssec/dnssec.go +++ b/plugin/dnssec/dnssec.go @@ -49,7 +49,7 @@ func (d Dnssec) Sign(state request.Request, zone string, now time.Time) *dns.Msg incep, expir := incepExpir(now) - if mt == response.NameError { + if mt == response.NameError || mt == response.NoData { if req.Ns[0].Header().Rrtype != dns.TypeSOA || len(req.Ns) > 1 { return req } diff --git a/plugin/dnssec/dnssec_test.go b/plugin/dnssec/dnssec_test.go index <HASH>..<HASH> 100644 --- a/plugin/dnssec/dnssec_test.go +++ b/plugin/dnssec/dnssec_test.go @@ -127,6 +127,20 @@ func TestSigningDname(t *testing.T) { } } +func TestSigningEmpty(t *testing.T) { + d, rm1, rm2 := newDnssec(t, []string{"miek.nl."}) + defer rm1() + defer rm2() + + m := testEmptyMsg() + m.SetQuestion("a.miek.nl.", dns.TypeA) + state := request.Request{Req: m} + m = d.Sign(state, "miek.nl.", time.Now().UTC()) + if !section(m.Ns, 2) { + t.Errorf("authority section should have 2 sig") + } +} + func section(rss []dns.RR, nrSigs int) bool { i := 0 for _, r := range rss { @@ -181,6 +195,13 @@ func testMsgDname() *dns.Msg { } } +func testEmptyMsg() *dns.Msg { + // don't care about the message header + return &dns.Msg{ + Ns: []dns.RR{test.SOA("miek.nl. 1800 IN SOA ns.miek.nl. dnsmaster.miek.nl. 2017100301 200 100 604800 3600")}, + } +} + func newDnssec(t *testing.T, zones []string) (Dnssec, func(), func()) { k, rm1, rm2 := newKey(t) c := cache.New(defaultCap)
plugin/dnssec: fix NSEC-records (#<I>) * add NSEC-records if entry exists but the requested type is missing * added test for dnssec fix
coredns_coredns
train
7dda34c241b1bae1e4dff96e3dba2aea9cffa5af
diff --git a/pabot/pabot.py b/pabot/pabot.py index <HASH>..<HASH> 100755 --- a/pabot/pabot.py +++ b/pabot/pabot.py @@ -487,7 +487,7 @@ def hash_directory(digest, path): get_hash_of_file(file_path, digest) def _digest(text): - text = text.decode('utf-8') if PY2 else text + text = text.decode('utf-8') if PY2 and not is_unicode(text) else text return hashlib.sha1(text.encode('utf-8')).digest() def get_hash_of_file(filename, digest):
digest: decode utf-8 only when not unicode
mkorpela_pabot
train
80761007310e20c944f8890c7e65cc03a9a77cbe
diff --git a/lib/xcake/generator/build_phase_registry.rb b/lib/xcake/generator/build_phase_registry.rb index <HASH>..<HASH> 100644 --- a/lib/xcake/generator/build_phase_registry.rb +++ b/lib/xcake/generator/build_phase_registry.rb @@ -1,8 +1,18 @@ module Xcake module Generator class BuildPhase + + # This namespace contains methods + # for working with Build Phase generators. + # module Registry + # This returns all the build phase generators + # the order of these is important so that files + # are added correctly. + # + # @return [Array<BuildPhase>] the build phase generators + # def self.build_phase_generators [ CompileSourceBuildPhase, @@ -12,6 +22,13 @@ module Xcake ] end + # This returns a build phase generator + # designed to handle the node + # + # @param [Node] node for the build phase generator + # + # @return [BuildPhase] the build phase generator + # def self.generator_for_node(node) generator_class = self.build_phase_generators.find do |g| g.can_install_node(node)
BuildPhaseRegistry Methods.
igor-makarov_xcake
train
6a430d495e3e616304000e21e72deba27eb5303f
diff --git a/client-src/utils/log.js b/client-src/utils/log.js index <HASH>..<HASH> 100644 --- a/client-src/utils/log.js +++ b/client-src/utils/log.js @@ -19,7 +19,7 @@ setLogLevel(defaultLevel); const log = logger.getLogger(name); const logEnabledFeatures = (features) => { - const enabledFeatures = Object.entries(features); + const enabledFeatures = Object.keys(features); if (!features || enabledFeatures.length === 0) { return; } @@ -27,8 +27,9 @@ const logEnabledFeatures = (features) => { let logString = "Server started:"; // Server started: Hot Module Replacement enabled, Live Reloading enabled, Overlay disabled. - for (const [key, value] of Object.entries(features)) { - logString += ` ${key} ${value ? "enabled" : "disabled"},`; + for (let i = 0; i < enabledFeatures.length; i++) { + const key = enabledFeatures[i]; + logString += ` ${key} ${features[key] ? "enabled" : "disabled"},`; } // replace last comma with a period logString = logString.slice(0, -1).concat(".");
fix: compatibility with old browsers (#<I>)
webpack_webpack-dev-server
train
3e0c6a0777036d2d8238f17f4d6c7d92cddd7fbb
diff --git a/presto-hive/src/main/java/com/facebook/presto/hive/HiveTableLayoutHandle.java b/presto-hive/src/main/java/com/facebook/presto/hive/HiveTableLayoutHandle.java index <HASH>..<HASH> 100644 --- a/presto-hive/src/main/java/com/facebook/presto/hive/HiveTableLayoutHandle.java +++ b/presto-hive/src/main/java/com/facebook/presto/hive/HiveTableLayoutHandle.java @@ -248,7 +248,7 @@ public final class HiveTableLayoutHandle TupleDomain<Subfield> domainPredicate = this.domainPredicate; // If split is provided, we would update the identifier based on split runtime information. - if (split.isPresent() && domainPredicate.getColumnDomains().isPresent()) { + if (split.isPresent() && (split.get() instanceof HiveSplit) && domainPredicate.getColumnDomains().isPresent()) { HiveSplit hiveSplit = (HiveSplit) split.get(); Set<Subfield> subfields = hiveSplit.getRedundantColumnDomains().stream() .map(column -> new Subfield(((HiveColumnHandle) column).getName()))
Handle casting to HiveSplit If the split is not of type HiveSplit then treat it as no split.
prestodb_presto
train
bd0c390ed73d1ba77f21d21e453e10ba60cf537d
diff --git a/filter/tex/defaultsettings.php b/filter/tex/defaultsettings.php index <HASH>..<HASH> 100644 --- a/filter/tex/defaultsettings.php +++ b/filter/tex/defaultsettings.php @@ -8,7 +8,7 @@ global $CFG; if (!isset($CFG->filter_tex_latexpreamble)) { - set_config( 'filter_tex_latexpreamble', " \\usepackage[latin1]{inputenc}\n \\usepackage{amsmath}\n \\usepackage{amsfonts}\n"); + set_config( 'filter_tex_latexpreamble', " \\usepackage[latin1]{inputenc}\n \\usepackage{amsmath}\n \\usepackage{amsfonts}\n \\RequirePackage{amsmath,amssymb,latexsym}\n"); } if (!isset($CFG->filter_tex_latexbackground)) {
Added preamble for LaTeX AMS notation to default. See bug #<I>
moodle_moodle
train
87ec3b11f14e7f0dbd30a2a09d562b7bb4fcb4b4
diff --git a/src/js/image.js b/src/js/image.js index <HASH>..<HASH> 100644 --- a/src/js/image.js +++ b/src/js/image.js @@ -20,11 +20,15 @@ $.magnificPopup.registerModule('image', { options: { markup: '<div class="mfp-figure">'+ '<div class="mfp-close"></div>'+ - '<div class="mfp-img"></div>'+ - '<div class="mfp-bottom-bar">'+ - '<div class="mfp-title"></div>'+ - '<div class="mfp-counter"></div>'+ - '</div>'+ + '<figure>'+ + '<div class="mfp-img"></div>'+ + '<figcaption>'+ + '<div class="mfp-bottom-bar">'+ + '<div class="mfp-title"></div>'+ + '<div class="mfp-counter"></div>'+ + '</div>'+ + '</figcaption>'+ + '</figure>'+ '</div>', cursor: 'mfp-zoom-out-cur', titleSrc: 'title',
Implemented HTML5 figure and figcaption elements for images
dimsemenov_Magnific-Popup
train
0a154ae7ce2097dbc6ce77bde06ed40bcbb67719
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -15,7 +15,7 @@ else: setup( name='PySoundCard', - version='0.4.1', + version='0.4.2', description='An audio library based on PortAudio, CFFI and NumPy', author='Bastian Bechtold', author_email='basti@bastibe.de',
incremented version number - now using frombuffer instead of fromstring (faster) - can play mono signal on multichannel device
bastibe_PySoundCard
train
0b3bc953ef8a6549bb0f99cf834fd24a9b783288
diff --git a/deliver/lib/deliver/options.rb b/deliver/lib/deliver/options.rb index <HASH>..<HASH> 100644 --- a/deliver/lib/deliver/options.rb +++ b/deliver/lib/deliver/options.rb @@ -190,7 +190,7 @@ module Deliver short_option: "-l", verify_block: proc do |value| UI.user_error!("Could not find png file at path '#{File.expand_path(value)}'") unless File.exist?(value) - UI.user_error!("'#{value}' doesn't seem to be a png file") unless value.end_with?(".png") + UI.user_error!("'#{value}' doesn't seem to be one of the supported files. supported: #{Deliver::UploadAssets::SUPPORTED_ICON_EXTENSIONS.join(',')}") unless Deliver::UploadAssets::SUPPORTED_ICON_EXTENSIONS.include?(File.extname(value).downcase) end), FastlaneCore::ConfigItem.new(key: :apple_watch_app_icon, description: "Metadata: The path to the Apple Watch app icon", @@ -198,7 +198,7 @@ module Deliver short_option: "-q", verify_block: proc do |value| UI.user_error!("Could not find png file at path '#{File.expand_path(value)}'") unless File.exist?(value) - UI.user_error!("'#{value}' doesn't seem to be a png file") unless value.end_with?(".png") + UI.user_error!("'#{value}' doesn't seem to be one of the supported files. supported: #{Deliver::UploadAssets::SUPPORTED_ICON_EXTENSIONS.join(',')}") unless Deliver::UploadAssets::SUPPORTED_ICON_EXTENSIONS.include?(File.extname(value).downcase) end), FastlaneCore::ConfigItem.new(key: :copyright, description: "Metadata: The copyright notice", diff --git a/deliver/lib/deliver/upload_assets.rb b/deliver/lib/deliver/upload_assets.rb index <HASH>..<HASH> 100644 --- a/deliver/lib/deliver/upload_assets.rb +++ b/deliver/lib/deliver/upload_assets.rb @@ -1,5 +1,6 @@ module Deliver class UploadAssets + SUPPORTED_ICON_EXTENSIONS = [".png", ".jpg", ".jpeg"] def upload(options) return if options[:edit_live] app = options[:app]
[deliver] support JPG icons for metadata (#<I>)
fastlane_fastlane
train
f5f7c0526e7840b8778560e614eb65661a6c54b1
diff --git a/lib/i18n/backend/cache.rb b/lib/i18n/backend/cache.rb index <HASH>..<HASH> 100644 --- a/lib/i18n/backend/cache.rb +++ b/lib/i18n/backend/cache.rb @@ -17,9 +17,9 @@ # # The cache_key implementation by default assumes you pass values that return # a valid key from #hash (see -# http://www.ruby-doc.org/core/classes/Object.html#M000337). However, you can +# https://www.ruby-doc.org/core/classes/Object.html#M000337). However, you can # configure your own digest method via which responds to #hexdigest (see -# http://ruby-doc.org/stdlib/libdoc/digest/rdoc/index.html): +# https://ruby-doc.org/stdlib/libdoc/openssl/rdoc/OpenSSL/Digest.html): # # I18n.cache_key_digest = OpenSSL::Digest::SHA256.new #
Update documentation reference to point to OpenSSL
ruby-i18n_i18n
train
fff8bfc1540e81a17e9c0d231c4c102413c9cf11
diff --git a/pipenv/installers.py b/pipenv/installers.py index <HASH>..<HASH> 100644 --- a/pipenv/installers.py +++ b/pipenv/installers.py @@ -191,11 +191,11 @@ class Pyenv(Installer): A ValueError is raised if the given version does not have a match in pyenv. A InstallerError is raised if the pyenv command fails. """ - c = self._run( - 'install', '-s', str(version), - timeout=self.project.s.PIPENV_INSTALL_TIMEOUT, - ) - return c + args = ['install', '-s', str(version)] + if Pyenv.WIN: + # pyenv-win skips installed versions by default and does not support -s + del args[1] + return self._run(*args, timeout=self.project.s.PIPENV_INSTALL_TIMEOUT) class Asdf(Installer):
Do not pass -s to pyenv install under Windows
pypa_pipenv
train
a504033a47d9c77f2698757eebba4b773f6cc913
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -28,14 +28,18 @@ function gulpJsonWrapper(params) { var stream = through.obj( function(file, enc, cb) { var self = this; - fs.readFile(params.src, "utf8", function (err, jsonFile) { + fs.readFile(params.src, "utf8", function(err, jsonFile) { if (err) throw new PluginError(PLUGIN_NAME, 'Json file not found!'); var obj = JSON.parse(jsonFile); - if (params.angular){ + if (params.angular) { var moduleName = params.module || 'json'; - jsonFile = 'angular.module(\''+moduleName+'\', []).constant(\''+params.namespace+'\', '+JSON.stringify(obj)+');'; + jsonFile = "(function(){ var module; try { "; + jsonFile += 'module = angular.module(\'' + moduleName + '\');'; + jsonFile += '} catch(e) { module = angular.module(\'' + moduleName + '\', []); }'; + jsonFile += 'module.constant(\'' + params.namespace + '\', ' + JSON.stringify(obj) + ');'; + jsonFile += '}());'; } else { jsonFile = 'var ' + params.namespace + '=' + JSON.stringify(obj) + ';'; } @@ -64,4 +68,4 @@ function gulpJsonWrapper(params) { return stream; }; -module.exports = gulpJsonWrapper; +module.exports = gulpJsonWrapper; \ No newline at end of file
Support for multiple ng modules of the same name
krowten_gulp-json-wrapper
train
e13825489b9eda9d1649a3fc6060e92c3b792c8d
diff --git a/ravel.py b/ravel.py index <HASH>..<HASH> 100644 --- a/ravel.py +++ b/ravel.py @@ -731,7 +731,7 @@ class Connection : if reply != None : result = reply.expect_return_objects(call_info["out_signature"]) else : - result = None + raise dbus.DBusError(DBUS.ERROR_TIMEOUT, "server took too long to return reply") #end if return \ result @@ -778,7 +778,7 @@ class Connection : if reply != None : result = reply.expect_return_objects(call_info["out_signature"]) else : - result = None + raise dbus.DBusError(DBUS.ERROR_TIMEOUT, "server took too long to return reply") #end if return \ result
raise timeout exception rather than return None method response
ldo_dbussy
train
d93b4e5a4438fcf034ec370d4803c44acafb85ab
diff --git a/lib/amee/profile_item.rb b/lib/amee/profile_item.rb index <HASH>..<HASH> 100644 --- a/lib/amee/profile_item.rb +++ b/lib/amee/profile_item.rb @@ -74,22 +74,6 @@ module AMEE raise AMEE::BadData.new("Couldn't load ProfileItem from XML data. Check that your URL is correct.") end - def self.get_history(connection, path, num_months, end_date = Date.today) - month = end_date.month - year = end_date.year - history = [] - num_months.times do - date = Date.new(year, month) - history << self.get(connection, path, date) - month -= 1 - if (month == 0) - year -= 1 - month = 12 - end - end - return history.reverse - end - def self.get(connection, path, for_date = Date.today) # Load data from path response = connection.get(path, :profileDate => for_date.strftime("%Y%m"))
ProfileItem#get_history doesn't actually do anything
OpenAMEE_amee-ruby
train
717dac36c65573f1288ddda2c7b9294f9a1d5057
diff --git a/js/coinmarketcap.js b/js/coinmarketcap.js index <HASH>..<HASH> 100644 --- a/js/coinmarketcap.js +++ b/js/coinmarketcap.js @@ -106,6 +106,7 @@ module.exports = class coinmarketcap extends Exchange { 'ENTCash': 'ENTCash', 'FairGame': 'FairGame', 'GET Protocol': 'GET Protocol', + 'Global Tour Coin': 'Global Tour Coin', 'GuccioneCoin': 'GuccioneCoin', 'Hi Mutual Society': 'Hi Mutual Society', 'iCoin': 'iCoin',
coinmarketcap GTC → Global Tour Coin fix #<I>
ccxt_ccxt
train
584bd6169c3546c62e96ba8ed0514b8bf621b40f
diff --git a/lib/ruboto/commands/base.rb b/lib/ruboto/commands/base.rb index <HASH>..<HASH> 100644 --- a/lib/ruboto/commands/base.rb +++ b/lib/ruboto/commands/base.rb @@ -92,6 +92,7 @@ module Ruboto update_jruby true log_action("\nAdding activities (RubotoActivity and RubotoDialog) and SDK versions to the manifest") do + verify_manifest.elements['application'].attributes['android:hardwareAccelerated'] = 'true' verify_manifest.elements['application'].add_element 'activity', {"android:name" => "org.ruboto.RubotoActivity"} verify_manifest.elements['application'].add_element 'activity', {"android:name" => "org.ruboto.RubotoDialog", "android:theme" => "@android:style/Theme.Dialog"}
* Enabled hardware accelleration for new apps
ruboto_ruboto
train
15b20ebb2f0f76b406555a748ddb276cb710c0e3
diff --git a/src/org/pitaya/util/Throwables.java b/src/org/pitaya/util/Throwables.java index <HASH>..<HASH> 100644 --- a/src/org/pitaya/util/Throwables.java +++ b/src/org/pitaya/util/Throwables.java @@ -113,6 +113,32 @@ public final class Throwables return Collections.unmodifiableList(frames); } + /** + * Re-throws the given {@code Throwable} if it is already an instance of + * {@code RuntimeException} or {@link Error}, and, if not, wraps it in a + * {@code RuntimeException} before throwing it. + * + * @param t the {@code Throwable} to propagate. + * + * @return nothing (this method always throws a {@code Throwable}). + * + * @throws NullPointerException if {@code t} is {@code null}. + * @throws RuntimeException if {@code t} is already an instance of + * {@code RuntimeException} or if {@code t} is neither an instance + * of {@code RuntimeException} nor an instance of {@code Error}. + * @throws Error if {@code t} is an instance of {@code Error}. + */ + public static RuntimeException propagate(Throwable t) + { + Parameters.checkNotNull(t); + if (t instanceof RuntimeException) { + throw (RuntimeException) t; + } else if (t instanceof Error) { + throw (Error) t; + } + throw new RuntimeException(t); + } + private Throwables() { /* ... */ diff --git a/test/org/pitaya/util/ThrowablesTest.java b/test/org/pitaya/util/ThrowablesTest.java index <HASH>..<HASH> 100644 --- a/test/org/pitaya/util/ThrowablesTest.java +++ b/test/org/pitaya/util/ThrowablesTest.java @@ -18,6 +18,8 @@ package org.pitaya.util; import static org.junit.Assert.*; +import java.io.IOError; +import java.io.IOException; import java.util.Arrays; import java.util.List; @@ -70,4 +72,22 @@ public final class ThrowablesTest assertEquals(elements[i].toString(), frames.get(i)); } } + + @Test(expected = IOError.class) + public void testPropagateError() + { + Throwables.propagate(new IOError(new Throwable())); + } + + @Test(expected = NullPointerException.class) + public void testPropagateRuntimeException() + { + Throwables.propagate(new NullPointerException()); + } + + @Test(expected = RuntimeException.class) + public void testPropagateCheckedException() + { + Throwables.propagate(new IOException()); + } }
Added Throwables.propagate
kocakosm_pitaya
train
acb3d58b828c0efc7b6ebc74c2a9c37c078910f9
diff --git a/command/agent/agent.go b/command/agent/agent.go index <HASH>..<HASH> 100644 --- a/command/agent/agent.go +++ b/command/agent/agent.go @@ -607,17 +607,31 @@ func (a *Agent) syncAgentServicesWithConsul() error { a.consulSyncer.SetAddrFinder(func(portLabel string) (string, int) { host, port, err := net.SplitHostPort(portLabel) if err != nil { - return "", 0 + p, err := strconv.Atoi(port) + if err != nil { + return "", 0 + } + return "", p } - // if the addr for the service is ":port", then we default to - // registering the service with ip as the loopback addr + // If the addr for the service is ":port", then we fall back + // to Nomad's default address resolution protocol. + // + // TODO(sean@): This should poll Consul to figure out what + // its advertise address is and use that in order to handle + // the case where there is something funky like NAT on this + // host. For now we just use the BindAddr if set, otherwise + // we fall back to a loopback addr. if host == "" { - host = "127.0.0.1" + if a.config.BindAddr != "" { + host = a.configBindAddr + } else { + host = "127.0.0.1" + } } p, err := strconv.Atoi(port) if err != nil { - return "", 0 + return host, 0 } return host, p })
Refine Nomad's Consul `port` handling. Previously this would immediately default to '<I>' if the config was set to `:some-port-number`. Now it uses the BindAddr if available. Also, if the `port` option is set to just a port` number (e.g. '<I>'), attempt to parse the port number by itself to allow statically configured ports to work, even when no host is specified.
hashicorp_nomad
train
666dc6390408a0ffcd3f85a862002ff4d8c86131
diff --git a/module/__init__.py b/module/__init__.py index <HASH>..<HASH> 100644 --- a/module/__init__.py +++ b/module/__init__.py @@ -25,7 +25,7 @@ try: except ImportError: from xcffib.ffi_build import ffi -lib = ffi.dlopen('libxcb.so') +lib = ffi.dlopen('libxcb.so.1') __xcb_proto_version__ = 'placeholder'
use an soname that is provided by the non-dev package
tych0_xcffib
train
3ecd1935c55946eb2f8160942fa7c31c0832cdd6
diff --git a/app/assets/javascripts/foreign_office.js b/app/assets/javascripts/foreign_office.js index <HASH>..<HASH> 100644 --- a/app/assets/javascripts/foreign_office.js +++ b/app/assets/javascripts/foreign_office.js @@ -71,6 +71,7 @@ var ForeignOfficeListener = Class.extend({ init: function($listener){ this.$listener = $listener; this.endpoint = $listener.data('endpoint'); + this.reveal_hide = $listener.data('reveal-hide'); this.object_key = $listener.data('key'); this.delete_key = $listener.data('delete-key'); this.channel = $listener.data('channel'); @@ -89,6 +90,14 @@ var ForeignOfficeListener = Class.extend({ if (m.object[this.delete_key] == true) { $listener.remove; } + }else if(this.reveal_hide){ + var current_value = m.object[this.object_key]; + if(!current_value || current_value == 'false' || current_value == 'hide'){ + this.$listener.hide(); + } else if(current_value == true || current_value == 'true' || current_value == 'show'){ + this.$listener.removeClass('hidden'); + this.$listener.show(); + } }else{ var new_value = m.object[this.object_key]; switch(this.$listener.get(0).nodeName.toLowerCase()){ @@ -148,18 +157,6 @@ var ForeignOfficeNewListItems = ForeignOfficeListener.extend({ } }); -var ForeignOfficeRevealer = ForeignOfficeListener.extend({ - handleMessage: function(m){ - var current_value = m.object[this.object_key]; - if(!current_value || current_value == 'false' || current_value == 'hide'){ - this.$listener.hide(); - } else if(current_value == true || current_value == 'true' || current_value == 'show'){ - this.$listener.removeClass('hidden'); - this.$listener.show(); - } - } -}); - var ForeignOfficeColor = ForeignOfficeListener.extend({ handleMessage: function(m){ var new_value = m.object[this.object_key]; diff --git a/lib/foreign_office/foreign_office_helper.rb b/lib/foreign_office/foreign_office_helper.rb index <HASH>..<HASH> 100644 --- a/lib/foreign_office/foreign_office_helper.rb +++ b/lib/foreign_office/foreign_office_helper.rb @@ -12,4 +12,11 @@ module ForeignOffice data_attrs end end + + def listener_hash(resource, key, reveal_hide: false) + hash = {listener: true, channel: resource.class.name + resource.id.to_s, key: key} + hash[:reveal_hide] = true if reveal_hide + hash + end + end \ No newline at end of file diff --git a/lib/foreign_office/version.rb b/lib/foreign_office/version.rb index <HASH>..<HASH> 100644 --- a/lib/foreign_office/version.rb +++ b/lib/foreign_office/version.rb @@ -1,3 +1,3 @@ module ForeignOffice - VERSION = "0.4.0" + VERSION = "0.5.0" end
added reveal/hide option added listener_hash helper
edraut_foreign-office
train
a27376f286e1fa25447ccafbea84c23544b09e2b
diff --git a/wtforms_dynamic_fields/wtforms_dynamic_fields.py b/wtforms_dynamic_fields/wtforms_dynamic_fields.py index <HASH>..<HASH> 100644 --- a/wtforms_dynamic_fields/wtforms_dynamic_fields.py +++ b/wtforms_dynamic_fields/wtforms_dynamic_fields.py @@ -170,7 +170,6 @@ class WTFormsDynamicFields(): try: arg = re_field_name.sub(r'\1'+'_'+current_set_number, arg) - print arg except: # The argument does not seem to be regex-able # Probably not a string, thus we can skip it.
Removed debug print statement, sorry about that...
Timusan_wtforms-dynamic-fields
train
f25238c9bf0abac645035a44ecd30454bfcec49c
diff --git a/lib/rbbt/util/misc/omics.rb b/lib/rbbt/util/misc/omics.rb index <HASH>..<HASH> 100644 --- a/lib/rbbt/util/misc/omics.rb +++ b/lib/rbbt/util/misc/omics.rb @@ -266,9 +266,9 @@ module Misc end - def self.sort_mutations(mutations) + def self.sort_mutations_strict(mutations) mutations.collect do |mutation| - chr,pos,mut = mutation.split ":" + chr, pos, mut = mutation.split ":" chr.sub!(/^chr/i,'') chr = 22 if chr == "Y" chr = 23 if chr == "X" @@ -293,6 +293,10 @@ module Misc end.collect{|p| p.last } end + class << self + alias sort_mutations sort_mutations_strict + end + def self.ensembl_server(organism) date = organism.split("/")[1] if date.nil? @@ -302,8 +306,12 @@ module Misc end end + def self.sort_genomic_locations_strict(stream, sep = ":") + sort_stream(stream, '#', "-k1,1V -k2,2n -t#{sep}") + end + def self.sort_genomic_locations(stream) - sort_stream(stream, '#', '-k1,1 -k2,2n -t:') + sort_stream(stream, '#', "-k1,1 -k2,2n -t#{sep}") end def self.intersect_streams_read(io, sep=":") @@ -319,18 +327,46 @@ module Misc [line,chr, start, eend, rest] end - def self.intersect_streams_cmp_chr(chr1, chr2) - if chr1 =~ /^\d+$/ and chr2 =~ /^\d+$/ - chr1 <=> chr2 - elsif chr1 =~ /^\d+$/ + def self.chr_cmp_strict(chr1, chr2) + if (m1 = chr1.match(/(\d+)$/)) && (m2 = chr2.match(/(\d+)$/)) + m1[1].to_i <=> m2[1].to_i + elsif chr1 =~ /\d+$/ -1 - elsif chr2 =~ /^\d+$/ + elsif chr2 =~ /\d+$/ 1 else chr1 <=> chr2 end end + def self.genomic_location_cmp(gpos1, gpos2, sep = ":") + chr1, _sep, pos1 = gpos1.partition(sep) + chr2, _sep, pos2 = gpos2.partition(sep) + cmp = chr1 <=> chr2 + case cmp + when 0 + pos1.to_i <=> pos2.to_i + else + cmp + end + end + + def self.genomic_location_cmp_strict(gpos1, gpos2, sep = ":") + chr1, _sep, pos1 = gpos1.partition(sep) + chr2, _sep, pos2 = gpos2.partition(sep) + cmp = chr_cmp_strict(chr1, chr2) + case cmp + when 0 + pos1.to_i <=> pos2.to_i + else + cmp + end + end + + def self.intersect_streams_cmp_chr(chr1, chr2) + chr1 <=> chr2 + end + def self.intersect_streams(f1, f2, out, sep=":") finish = false return if f1.eof? or f2.eof? @@ -404,7 +440,7 @@ module Misc max_size = 0 nio = Misc.open_pipe do |sin| while line = io.gets - chr, start, eend, id, *rest = line.split("\t") + chr, start, eend, id, *rest = line.chomp.split("\t") l = id.length max_size = l if max_size < l chr = chr.sub('chr','') @@ -422,6 +458,7 @@ module Misc end TSV.traverse tmpfile, :type => :array, :bar => "Creating BED index for #{Misc.fingerprint source}" do |line| + next if line.empty? chr, start, eend, id, *rest = line.split("\t") key = [chr, start, eend] * ":" sharder[key] = id diff --git a/lib/rbbt/util/misc/pipes.rb b/lib/rbbt/util/misc/pipes.rb index <HASH>..<HASH> 100644 --- a/lib/rbbt/util/misc/pipes.rb +++ b/lib/rbbt/util/misc/pipes.rb @@ -677,11 +677,14 @@ module Misc end end + def self.sort_mutation_stream_strict(stream, sep=":") + CMD.cmd("grep '#{sep}' | sort -u | sed 's/^M:/MT:/' | env LC_ALL=C sort -V -k1,1 -k2,2n -k3,3n -t'#{sep}'", :in => stream, :pipe => true, :no_fail => true) + end + def self.sort_mutation_stream(stream, sep=":") CMD.cmd("grep '#{sep}' | sort -u | sed 's/^M:/MT:/' | env LC_ALL=C sort -k1,1 -k2,2n -k3,3n -t'#{sep}'", :in => stream, :pipe => true, :no_fail => true) end - def self.swap_quoted_character(stream, charout="\n", charin=" ", quote='"') io = Misc.open_pipe do |sin| begin diff --git a/test/rbbt/util/misc/test_omics.rb b/test/rbbt/util/misc/test_omics.rb index <HASH>..<HASH> 100644 --- a/test/rbbt/util/misc/test_omics.rb +++ b/test/rbbt/util/misc/test_omics.rb @@ -78,7 +78,6 @@ class TestMiscOmics < Test::Unit::TestCase end end - io = Misc.open_pipe do |sin| sin.write text end
Sorting chromosomes by strict order
mikisvaz_rbbt-util
train
a90ff7726427745d84c6d09e48b9d1e79eb431f2
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -5,16 +5,18 @@ # See the files INSTALL and README for details or visit # https://github.com/Becksteinlab/GromacsWrapper from __future__ import with_statement - from setuptools import setup, find_packages +import imp, os + with open("README.rst") as readme: long_description = readme.read() # Dynamically calculate the version based on gromacs.VERSION. # (but requires that we can actually import the package BEFORE it is # properly installed!) -version = __import__('gromacs.version').get_version() +version_file = os.path.join(os.path.dirname(__file__), 'gromacs', 'version.py') +version = imp.load_source('gromacs.version', version_file).get_version() setup(name="GromacsWrapper", version=version,
not import the whole package while setuping
Becksteinlab_GromacsWrapper
train
9650850299bce532e5a2c591fcb1a35e35600e9e
diff --git a/lib/conjure/instance.rb b/lib/conjure/instance.rb index <HASH>..<HASH> 100644 --- a/lib/conjure/instance.rb +++ b/lib/conjure/instance.rb @@ -16,6 +16,11 @@ module Conjure new(@server.ip_address, options).tap(&:update) end + def self.update(options) + ip_address = options.delete(:ip_address) + new(ip_address, options).tap(&:update) + end + def update components.each(&:install) end
Update API to handle Instance creating and updating similarly
brianauton_conjure
train
0566b4e23a2448c6b71c4f956f2b0006c11ed618
diff --git a/isort/exceptions.py b/isort/exceptions.py index <HASH>..<HASH> 100644 --- a/isort/exceptions.py +++ b/isort/exceptions.py @@ -163,9 +163,18 @@ class UnsupportedSettings(ISortError): class UnsupportedEncoding(ISortError): """Raised when isort encounters an encoding error while trying to read a file""" - def __init__( - self, - filename: Union[str, Path], - ): + def __init__(self, filename: Union[str, Path]): super().__init__(f"Unknown or unsupported encoding in {filename}") self.filename = filename + + +class MissingSection(ISortError): + """Raised when isort encounters an import that matches a section that is not defined""" + + def __init__(self, import_module: str, section: str): + super().__init__( + f"Found {import_module} import while parsing, but {section} was not included " + "in the `sections` setting of your config. Please add it before continuing\n" + "See https://pycqa.github.io/isort/#custom-sections-and-ordering " + "for more info." + ) diff --git a/isort/main.py b/isort/main.py index <HASH>..<HASH> 100644 --- a/isort/main.py +++ b/isort/main.py @@ -11,11 +11,11 @@ from typing import Any, Dict, Iterable, Iterator, List, Optional, Sequence, Set from warnings import warn from . import __version__, api, sections -from .exceptions import FileSkipped, UnsupportedEncoding +from .exceptions import FileSkipped, ISortError, UnsupportedEncoding from .format import create_terminal_printer from .logo import ASCII_ART from .profiles import profiles -from .settings import DEFAULT_CONFIG, VALID_PY_TARGETS, Config, WrapModes +from .settings import VALID_PY_TARGETS, Config, WrapModes try: from .setuptools_commands import ISortCommand # noqa: F401 @@ -110,17 +110,8 @@ def sort_imports( if config.verbose: warn(f"Encoding not supported for {file_name}") return SortAttempt(incorrectly_sorted, skipped, False) - except KeyError as error: - if error.args[0] not in DEFAULT_CONFIG.sections: - _print_hard_fail(config, offending_file=file_name) - raise - msg = ( - f"Found {error} imports while parsing, but {error} was not included " - "in the `sections` setting of your config. Please add it before continuing\n" - "See https://pycqa.github.io/isort/#custom-sections-and-ordering " - "for more info." - ) - _print_hard_fail(config, message=msg) + except ISortError as error: + _print_hard_fail(config, message=str(error)) sys.exit(os.EX_CONFIG) except Exception: _print_hard_fail(config, offending_file=file_name) diff --git a/isort/parse.py b/isort/parse.py index <HASH>..<HASH> 100644 --- a/isort/parse.py +++ b/isort/parse.py @@ -8,6 +8,7 @@ from warnings import warn from . import place from .comments import parse as parse_comments from .deprecated.finders import FindersManager +from .exceptions import MissingSection from .settings import DEFAULT_CONFIG, Config if TYPE_CHECKING: @@ -524,6 +525,10 @@ def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedConte " Do you need to define a default section?" ) imports.setdefault("", {"straight": OrderedDict(), "from": OrderedDict()}) + + if placed_module and placed_module not in imports: + raise MissingSection(import_module=module, section=placed_module) + straight_import |= imports[placed_module][type_of_import].get( # type: ignore module, False )
Improve reporting of known errors in isort, reachieve <I>% test coverage
timothycrosley_isort
train
4b8feb38cbd5c00532d91a13191fca05ecea6156
diff --git a/test/Psy/Test/Input/CodeArgumentTest.php b/test/Psy/Test/Input/CodeArgumentTest.php index <HASH>..<HASH> 100644 --- a/test/Psy/Test/Input/CodeArgumentTest.php +++ b/test/Psy/Test/Input/CodeArgumentTest.php @@ -11,11 +11,10 @@ namespace Psy\Tests\Input; -use PHPUnit\Framework\TestCase; use Psy\Input\CodeArgument; use Symfony\Component\Console\Input\InputArgument; -class CodeArgumentTest extends TestCase +class CodeArgumentTest extends \PHPUnit_Framework_TestCase { /** * @dataProvider getInvalidModes diff --git a/test/Psy/Test/Input/ShellInputTest.php b/test/Psy/Test/Input/ShellInputTest.php index <HASH>..<HASH> 100644 --- a/test/Psy/Test/Input/ShellInputTest.php +++ b/test/Psy/Test/Input/ShellInputTest.php @@ -11,14 +11,13 @@ namespace Psy\Tests\Input; -use PHPUnit\Framework\TestCase; use Psy\Input\CodeArgument; use Psy\Input\ShellInput; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputDefinition; use Symfony\Component\Console\Input\InputOption; -class ShellInputTest extends TestCase +class ShellInputTest extends \PHPUnit_Framework_TestCase { /** * @dataProvider getTokenizeData
Fix TestCase class name for older phpunits.
bobthecow_psysh
train
3b7dc8bb438034e582900f1d91925c2ec767d406
diff --git a/pvlib/irradiance.py b/pvlib/irradiance.py index <HASH>..<HASH> 100644 --- a/pvlib/irradiance.py +++ b/pvlib/irradiance.py @@ -10,6 +10,8 @@ from __future__ import division import logging pvl_logger = logging.getLogger('pvlib') +import datetime + import numpy as np import pandas as pd @@ -167,7 +169,7 @@ def _doy_to_timestamp(doy, epoch='2013-12-31'): ------- pd.Timestamp """ - return pd.Timestamp('2013-12-31') + pd.Timedelta(days=float(doy)) + return pd.Timestamp('2013-12-31') + datetime.timedelta(days=float(doy)) def aoi_projection(surf_tilt, surf_az, sun_zen, sun_az): diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -32,7 +32,7 @@ if not sys.version_info[:2] in ((2,7), (3,3), (3,4)): setuptools_kwargs = { 'zip_safe': False, 'install_requires': ['numpy >= 1.7.0', - 'pandas >= 0.15', + 'pandas >= 0.13.1', 'pytz', 'six', 'pyephem',
make compatible with pandas <I>
pvlib_pvlib-python
train
87718756c7adee844db30d34a65e7f151d10cf17
diff --git a/src/helpers.php b/src/helpers.php index <HASH>..<HASH> 100644 --- a/src/helpers.php +++ b/src/helpers.php @@ -29,7 +29,7 @@ if (!function_exists('asset')) { } } -if (!function_exists('template_path')) { +if (!function_exists('base_path')) { /** * Get the path to the base of the install. *
Check is base_path exists Closes #<I>
wordplate_framework
train
e4df4ee141e071580135d010b8afefd926c0acaa
diff --git a/components/TimelineBlip.js b/components/TimelineBlip.js index <HASH>..<HASH> 100644 --- a/components/TimelineBlip.js +++ b/components/TimelineBlip.js @@ -1,21 +1,20 @@ -import React, { Component } from 'react' +import React, {Component} from 'react' import PropTypes from 'prop-types' import s from './styles' class TimelineBlip extends Component { - mergeNotificationStyle(iconColor) { - return iconColor ? { ...s.eventType, ...{ color: iconColor, borderColor: iconColor } } : s.eventType + return iconColor ? {...s.eventType, ...{color: iconColor, borderColor: iconColor}} : s.eventType } iconStyle(iconStyle) { - return { ...s.materialIcons, iconStyle } + return {...s.materialIcons, ...iconStyle} } render() { - const { title, iconStyle, icon, iconColor, ...otherProps } = this.props + const {title, iconStyle, icon, iconColor, style, ...otherProps} = this.props return ( - <div style={{...s.event, marginBottom: 50}}> + <div style={{...s.event, marginBottom: 50, ...style}}> <div style={this.mergeNotificationStyle(iconColor)}> <span style={this.iconStyle(iconStyle)}>{icon}</span> </div> diff --git a/stories/App.story.js b/stories/App.story.js index <HASH>..<HASH> 100644 --- a/stories/App.story.js +++ b/stories/App.story.js @@ -52,8 +52,12 @@ storiesOf('Timeline', module) <Timeline> <TimelineBlip title='Remove PropTypes warning' + iconStyle={{marginLeft: 1, marginTop: 0}} icon={<i className='material-icons md-18'>assignment_late</i>} - iconColor='#6fba1c' + iconColor='#03a9f4' + style={{ + color: '#9c27b0' + }} /> <TimelineBlip title='John starred this thread'
fix: Make iconStyle and style props work in TimelineBlip
rcdexta_react-event-timeline
train
46e1268726db3d1542d89b511132cd5b0fc3c360
diff --git a/lib/aims/geometry.rb b/lib/aims/geometry.rb index <HASH>..<HASH> 100644 --- a/lib/aims/geometry.rb +++ b/lib/aims/geometry.rb @@ -519,6 +519,10 @@ module Aims # Make a coyp of the unit cell new_unit_cell = self.copy + # atoms on the border will be repeated with + # periodicity of lattice vectors for better rendering + border_atoms = {} + # Move each atom behind all the planes new_unit_cell.atoms(false).each do |atom| planes_vecs.each_pair do |p, v| @@ -527,15 +531,39 @@ module Aims # move atoms not on the plane (inequality) while p.distance_to_point(atom.x, atom.y, atom.z) > 0 atom.displace!(v[0], v[1], v[2]) - end + end else # Move atoms that lie on the plane if the plane doesn't intersect the origin while p.distance_to_point(atom.x, atom.y, atom.z) >= 0 atom.displace!(v[0], v[1], v[2]) end end + + # This part repeats atoms on the unit cell boundaries + # useful for drawing pictures, but these atoms are really repeats + if p.distance_to_point(atom.x, atom.y, atom.z) == 0 + if border_atoms[atom] + border_atoms[atom] << v + else + border_atoms[atom] = [v] + end + end end end + + # Add more border atoms for each combination of lattice planes + border_atoms.each_pair{|atom, planes| + planes.size.times{|i| + combos = Volume.choose(planes, i+1) + combos.each{|combo| + x = combo.inject(0){|sum, v| sum = sum + v[0]} + y = combo.inject(0){|sum, v| sum = sum + v[1]} + z = combo.inject(0){|sum, v| sum = sum + v[2]} + puts [x,y,z] + new_unit_cell.atoms(:allAtoms) << atom.displace(x, y, z) + } + } + } new_unit_cell.atoms.uniq! new_unit_cell.make_bonds return new_unit_cell
Added code to geometry.correct to repeat atoms on border of unit cell. This is seems to work but fails lots of rspecs
jns_Aims
train
bbe7fd261337f00cc4ebc4f1739c6b8f06241645
diff --git a/builtin/providers/aws/resource_aws_elastic_beanstalk_environment_test.go b/builtin/providers/aws/resource_aws_elastic_beanstalk_environment_test.go index <HASH>..<HASH> 100644 --- a/builtin/providers/aws/resource_aws_elastic_beanstalk_environment_test.go +++ b/builtin/providers/aws/resource_aws_elastic_beanstalk_environment_test.go @@ -323,6 +323,23 @@ resource "aws_elastic_beanstalk_environment" "tfenvtest" { ` const testAccBeanstalkWorkerEnvConfig = ` +resource "aws_iam_instance_profile" "tftest" { + name = "tftest_profile" + roles = ["${aws_iam_role.tftest.name}"] +} + +resource "aws_iam_role" "tftest" { + name = "tftest_role" + path = "/" + assume_role_policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Effect\":\"Allow\",\"Sid\":\"\"}]}" +} + +resource "aws_iam_role_policy" "tftest" { + name = "tftest_policy" + role = "${aws_iam_role.tftest.id}" + policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"QueueAccess\",\"Action\":[\"sqs:ChangeMessageVisibility\",\"sqs:DeleteMessage\",\"sqs:ReceiveMessage\"],\"Effect\":\"Allow\",\"Resource\":\"*\"}]}" +} + resource "aws_elastic_beanstalk_application" "tftest" { name = "tf-test-name" description = "tf-test-desc" @@ -333,6 +350,12 @@ resource "aws_elastic_beanstalk_environment" "tfenvtest" { application = "${aws_elastic_beanstalk_application.tftest.name}" tier = "Worker" solution_stack_name = "64bit Amazon Linux running Python" + + setting { + namespace = "aws:autoscaling:launchconfiguration" + name = "IamInstanceProfile" + value = "${aws_iam_instance_profile.tftest.name}" + } } `
provider/aws: Fix Elastic Beanstalk test (#<I>) This fixes the `TestAccAWSBeanstalkEnv_tier` test. The instance profile needs access to send and receive messages from its sqs queue. Without these permissions Beanstalk returns an error event, causing the test to fail.
hashicorp_terraform
train
a35833640c558d932bf0a9056cb79d33b9f76900
diff --git a/integration-tests/apps/rack/background/something.rb b/integration-tests/apps/rack/background/something.rb index <HASH>..<HASH> 100644 --- a/integration-tests/apps/rack/background/something.rb +++ b/integration-tests/apps/rack/background/something.rb @@ -11,8 +11,8 @@ class Something end def foo - puts "JC: in foo" - puts "JC: ", @background.receive(:timeout => 25000) - @foreground.publish "success" + if "release" == @background.receive(:timeout => 25000) + @foreground.publish "success" + end end end
Make sure we get what we expect.
torquebox_torquebox
train
ef2a67db29a62d62212747098403acc1e3c6c3cd
diff --git a/lib/que/poller.spec.rb b/lib/que/poller.spec.rb index <HASH>..<HASH> 100644 --- a/lib/que/poller.spec.rb +++ b/lib/que/poller.spec.rb @@ -255,7 +255,7 @@ describe Que::Poller do assert poller.should_poll? end - it "should be true if the jobs returned from the last poll satisfied all given priorities" do + it "should be true if the jobs returned from the last poll satisfied all priority requests" do job_ids_p10 = 3.times.map { Que::Job.enqueue(job_options: { priority: 10 }).que_attrs[:id] } job_ids_p20 = 2.times.map { Que::Job.enqueue(job_options: { priority: 20 }).que_attrs[:id] } @@ -265,7 +265,7 @@ describe Que::Poller do assert_equal true, poller.should_poll? end - it "should be true if the jobs returned from the last poll satisfied any given priority" do + it "should be true if the jobs returned from the last poll satisfied any priority request" do job_ids_p10 = 2.times.map { Que::Job.enqueue(job_options: { priority: 10 }).que_attrs[:id] } job_ids_p20 = 2.times.map { Que::Job.enqueue(job_options: { priority: 20 }).que_attrs[:id] } @@ -275,7 +275,7 @@ describe Que::Poller do assert_equal true, poller.should_poll? end - it "should be true if the jobs returned from the last poll satisfied any given priority and were slightly higher priority than each priority requested" do + it "should be true if the jobs returned from the last poll satisfied any priority request and were slightly higher priority than each priority requested" do job_ids_p10 = 2.times.map { Que::Job.enqueue(job_options: { priority: 10 }).que_attrs[:id] } job_ids_p20 = 2.times.map { Que::Job.enqueue(job_options: { priority: 20 }).que_attrs[:id] } @@ -285,7 +285,7 @@ describe Que::Poller do assert_equal true, poller.should_poll? end - it "should be true if the jobs returned from the last poll satisfied any given priority and a lower priority request was upgraded to high priority" do + it "should be true if the jobs returned from the last poll satisfied any priority request and a lower priority request was upgraded to high priority" do job_ids_p10 = 5.times.map { Que::Job.enqueue(job_options: { priority: 10 }).que_attrs[:id] } job_ids_p20 = 2.times.map { Que::Job.enqueue(job_options: { priority: 20 }).que_attrs[:id] } @@ -295,7 +295,7 @@ describe Que::Poller do assert_equal true, poller.should_poll? end - it "should be false if the jobs returned from the last poll didn't return a full complement of jobs matching any given priority" do + it "should be false if the jobs returned from the last poll didn't satisfy any priority request" do job_ids_p10 = 5.times.map { Que::Job.enqueue(job_options: { priority: 10 }).que_attrs[:id] } job_ids_p20 = 2.times.map { Que::Job.enqueue(job_options: { priority: 20 }).que_attrs[:id] } @@ -305,7 +305,7 @@ describe Que::Poller do assert_equal false, poller.should_poll? end - it "should be true if the jobs returned from the last poll didn't return a full complement of jobs, but the poll_interval has elapsed" do + it "should be true if the jobs returned from the last poll didn't satisfy any priority request, but the poll_interval has elapsed" do job_ids = 5.times.map { Que::Job.enqueue.que_attrs[:id] } result = poller.poll(priorities: { 500 => 7 }, held_locks: Set.new)
Slightly reword spec descriptions for Poller#should_poll?
chanks_que
train
85f3dadc7dcae6432a013f901a8b36868d22afb4
diff --git a/src/toil/job.py b/src/toil/job.py index <HASH>..<HASH> 100644 --- a/src/toil/job.py +++ b/src/toil/job.py @@ -305,6 +305,7 @@ class Job(JobLikeObject): self._rvs = collections.defaultdict(list) self._promiseJobStore = None self._fileStore = None + self._tempDir = None def run(self, fileStore): """ @@ -457,6 +458,24 @@ class Job(JobLikeObject): else: return self.addFollowOn(JobFunctionWrappingJob(fn, *args, **kwargs)) + @property + def tempDir(self): + """ + Shortcut to calling `job.fileStore.getLocalTempDir`. Temp dir is created on first call + and will be returned for first and future calls + :return: Path to tempDir. See `job.fileStore.getLocalTempDir` + :rtype: str + """ + if self._tempDir is None: + self._tempDir = self._fileStore.getLocalTempDir() + return self._tempDir + + def log(self, text, level=logging.INFO): + """ + clone of `fileStore.logToMaster` for convenience + """ + self._fileStore.logToMaster(text, level) + @staticmethod def wrapFn(fn, *args, **kwargs): """
Add log and tempDir property to Job class
DataBiosphere_toil
train
c27da5daf830e7ae499dc653ad3e68eb96fc9b85
diff --git a/AdminModule/presenters/BasePresenter.php b/AdminModule/presenters/BasePresenter.php index <HASH>..<HASH> 100755 --- a/AdminModule/presenters/BasePresenter.php +++ b/AdminModule/presenters/BasePresenter.php @@ -45,6 +45,8 @@ abstract class BasePresenter extends Nette\Application\UI\Presenter { $this->setLayout("layout"); + $this->setBasePathModule(); + if ($this->isAjax()) { $this->invalidateControl('flashMessages'); } @@ -632,4 +634,9 @@ abstract class BasePresenter extends Nette\Application\UI\Presenter parent::flashMessage($this->translation[$text], $type); } + public function setBasePathModule() + { + $this->template->basePathModule = __DIR__ . '/../../'; + } + } diff --git a/tests/PresenterTest.php b/tests/PresenterTest.php index <HASH>..<HASH> 100755 --- a/tests/PresenterTest.php +++ b/tests/PresenterTest.php @@ -90,4 +90,43 @@ abstract class PresenterTestCase extends EntityTestCase return $this->presenter->run($request); } + + protected function createPage($module) + { + $this->pageMain = new \WebCMS\Entity\Page; + $this->pageMain->setParent(null); + $this->pageMain->setLanguage($this->language); + $this->pageMain->setModule(null); + $this->pageMain->setModuleName(''); + $this->pageMain->setMetaTitle('meta title'); + $this->pageMain->setMetaDescription('meta description'); + $this->pageMain->setMetaKeywords('meta keywords'); + $this->pageMain->setTitle('Main'); + $this->pageMain->setPresenter('Presenter'); + $this->pageMain->setVisible(true); + $this->pageMain->setRedirect(false); + $this->pageMain->setPath('path/to/page'); + $this->pageMain->setDefault(true); + $this->pageMain->setClass(''); + + $this->em->persist($this->pageMain); + + $this->page = new \WebCMS\Entity\Page; + $this->page->setParent($this->pageMain); + $this->page->setLanguage($this->language); + $this->page->setModule(null); + $this->page->setModuleName($module); + $this->page->setMetaTitle('meta title'); + $this->page->setMetaDescription('meta description'); + $this->page->setMetaKeywords('meta keywords'); + $this->page->setTitle('Home'); + $this->page->setPresenter('Presenter'); + $this->page->setVisible(true); + $this->page->setRedirect(false); + $this->page->setPath('path/to/home'); + $this->page->setDefault(true); + $this->page->setClass('class'); + + $this->em->persist($this->page); + } }
Added basepath for module. Extended presenter test for modules.
voslartomas_WebCMS2
train
0f3eecc8e714252b53a97086f7f4476fe7614572
diff --git a/bcbio/distributed/ipythontasks.py b/bcbio/distributed/ipythontasks.py index <HASH>..<HASH> 100644 --- a/bcbio/distributed/ipythontasks.py +++ b/bcbio/distributed/ipythontasks.py @@ -128,7 +128,7 @@ pipeline_summary.metadata = {"resources": ["gatk"]} def generate_transcript_counts(*args): with _setup_logging(args): return apply(rnaseq.generate_transcript_counts, *args) -generate_transcript_counts.metadata = {"resources": ["samtools"]} +generate_transcript_counts.metadata = {"resources": ["samtools","gatk"]} @require(rnaseq) def run_cufflinks(*args):
generate_transcript_counts uses gatk . . . . . . which should be reflected in it's metadata. This was causing me memory problems during JVM startup.
bcbio_bcbio-nextgen
train
072f806f95b13587652797baa505788c23fe2c09
diff --git a/lib/mongoloid.rb b/lib/mongoloid.rb index <HASH>..<HASH> 100644 --- a/lib/mongoloid.rb +++ b/lib/mongoloid.rb @@ -1,6 +1,6 @@ require "rubygems" -gem "mongodb-mongo", "0.13" +gem "mongodb-mongo", "0.14" require "mongo" require "mongoloid/paginator"
Staying on the edge, baby - using <I> mongo driver
mongodb_mongoid
train
ef3dca91bab147225d2d3fbde94ccb3e605bee7d
diff --git a/vault/seal_autoseal_test.go b/vault/seal_autoseal_test.go index <HASH>..<HASH> 100644 --- a/vault/seal_autoseal_test.go +++ b/vault/seal_autoseal_test.go @@ -177,47 +177,43 @@ func TestAutoSeal_HealthCheck(t *testing.T) { metrics.NewGlobal(metricsConf, inmemSink) - core, _, _ := TestCoreUnsealed(t) - testSeal, setErr := seal.NewToggleableTestSeal(nil) - - var encKeys []string - changeKey := func(key string) { - encKeys = append(encKeys, key) - testSeal.Wrapper.(*seal.ToggleableWrapper).Wrapper.(*wrapping.TestWrapper).SetKeyID(key) - } - - // Set initial encryption key. - changeKey("kaz") - - autoSeal := NewAutoSeal(testSeal) - autoSeal.SetCore(core) pBackend := newTestBackend(t) - core.physical = pBackend - core.metricSink = metricsutil.NewClusterMetricSink("", inmemSink) - + testSealAccess, setErr := seal.NewToggleableTestSeal(nil) + core, _, _ := TestCoreUnsealedWithConfig(t, &CoreConfig{ + MetricSink: metricsutil.NewClusterMetricSink("", inmemSink), + Physical: pBackend, + }) sealHealthTestIntervalNominal = 10 * time.Millisecond sealHealthTestIntervalUnhealthy = 10 * time.Millisecond - setErr(errors.New("disconnected")) + autoSeal := NewAutoSeal(testSealAccess) + autoSeal.SetCore(core) + core.seal = autoSeal autoSeal.StartHealthCheck() defer autoSeal.StopHealthCheck() + setErr(errors.New("disconnected")) - time.Sleep(50 * time.Millisecond) - - asu := strings.Join(autoSealUnavailableDuration, ".") + ";cluster=" - intervals := inmemSink.Data() - if len(intervals) == 1 { - interval := inmemSink.Data()[0] + asu := strings.Join(autoSealUnavailableDuration, ".") + ";cluster=" + core.clusterName + tries := 10 + for tries = 10; tries > 0; tries-- { + intervals := inmemSink.Data() + if len(intervals) == 1 { + interval := inmemSink.Data()[0] - if _, ok := interval.Gauges[asu]; !ok { - t.Fatalf("Expected metrics to include a value for gauge %s", asu) - } - if interval.Gauges[asu].Value == 0 { - t.Fatalf("Expected value metric %s to be non-zero", asu) + if _, ok := interval.Gauges[asu]; ok { + if interval.Gauges[asu].Value > 0 { + break + } + } } + time.Sleep(100 * time.Millisecond) } + if tries == 0 { + t.Fatalf("Expected value metric %s to be non-zero", asu) + } + setErr(nil) time.Sleep(50 * time.Millisecond) - intervals = inmemSink.Data() + intervals := inmemSink.Data() if len(intervals) == 1 { interval := inmemSink.Data()[0] @@ -225,7 +221,7 @@ func TestAutoSeal_HealthCheck(t *testing.T) { t.Fatalf("Expected metrics to include a value for gauge %s", asu) } if interval.Gauges[asu].Value != 0 { - t.Fatalf("Expected value metric %s to be non-zero", asu) + t.Fatalf("Expected value metric %s to be zero", asu) } } }
Fix autoseal health check race by passing metrics sink in CoreConfig (#<I>)
hashicorp_vault
train
ddaed13c102e8492414cdc37e658ec2f6b9ecf86
diff --git a/src/Ractive/initialise.js b/src/Ractive/initialise.js index <HASH>..<HASH> 100644 --- a/src/Ractive/initialise.js +++ b/src/Ractive/initialise.js @@ -7,7 +7,7 @@ import arrayAdaptor from 'Ractive/static/adaptors/array/index'; import magicAdaptor from 'Ractive/static/adaptors/magic'; import magicArrayAdaptor from 'Ractive/static/adaptors/magicArray'; import { getElement } from 'utils/dom'; -import { create, extend } from 'utils/object'; +import { create, defineProperty, extend } from 'utils/object'; import runloop from 'global/runloop'; import config from 'Ractive/config/config'; import dataConfigurator from 'Ractive/config/custom/data'; @@ -46,7 +46,7 @@ function initialiseRactiveInstance ( ractive, userOptions = {}, options = {} ) { initialiseProperties( ractive, options ); // TODO remove this, eventually - Object.defineProperty( ractive, 'data', { get: deprecateRactiveData }); + defineProperty( ractive, 'data', { get: deprecateRactiveData }); // TODO don't allow `onconstruct` with `new Ractive()`, there's no need for it constructHook.fire( ractive, userOptions );
use internal defineProperty sham (fails gracefully in IE8)
ractivejs_ractive
train
55d7aa34fd40e316b929422aec09f6e7d6668854
diff --git a/asammdf/blocks/mdf_v4.py b/asammdf/blocks/mdf_v4.py index <HASH>..<HASH> 100755 --- a/asammdf/blocks/mdf_v4.py +++ b/asammdf/blocks/mdf_v4.py @@ -5966,7 +5966,10 @@ class MDF4(MDF_Common): self._file.close() if Path(self.name).parent == Path(gettempdir()): - Path(self.name).unlink(missing_ok=True) + try: + Path(self.name).unlink() + except: + pass if self.original_name is not None: if self.original_name.suffix.lower() in ('.bz2', '.gzip', '.mf4z', '.zip'):
keep Python <I> compatibility
danielhrisca_asammdf
train
b7871b33d5c19067f7c3139b21b0d4e0d1155dd2
diff --git a/system/Debug/Exceptions.php b/system/Debug/Exceptions.php index <HASH>..<HASH> 100644 --- a/system/Debug/Exceptions.php +++ b/system/Debug/Exceptions.php @@ -410,7 +410,7 @@ class Exceptions } } - $out .= str_repeat('</span>', $spans); + $out .= str_repeat('</span>', (int)$spans); return '<pre><code>'.$out.'</code></pre>'; }
Attempting to solve #<I>
codeigniter4_CodeIgniter4
train
5a6e9a5283d7e0b17d424c2aa4db61c7a3c84fb8
diff --git a/lib/client.js b/lib/client.js index <HASH>..<HASH> 100644 --- a/lib/client.js +++ b/lib/client.js @@ -30,7 +30,7 @@ AWS.Client = inherit({ initialize: function initialize(config) { this.config = new AWS.Config(AWS.config); - if (config) this.config.update(config); + if (config) this.config.update(config, true); this.setEndpoint(this.config.endpoint); }, diff --git a/lib/config.js b/lib/config.js index <HASH>..<HASH> 100644 --- a/lib/config.js +++ b/lib/config.js @@ -123,17 +123,21 @@ AWS.Config = inherit({ }, /** - * Updates the current configuration object with new options. + * @overload update(options, allowUnknownKeys = false) + * Updates the current configuration object with new options. * - * @example Update maxRetries property of a configuration object - * config.update({maxRetries: 10}); - * @param [Object] options a map of option keys and values. - * @see constructor + * @example Update maxRetries property of a configuration object + * config.update({maxRetries: 10}); + * @param [Object] options a map of option keys and values. + * @param [Boolean] allowUnknownKeys whether unknown keys can be set on + * the configuration object. Defaults to `false`. + * @see constructor */ - update: function update(options) { + update: function update(options, allowUnknownKeys) { + allowUnknownKeys = allowUnknownKeys || false; options = this.extractCredentials(options); AWS.util.each.call(this, options, function (key, value) { - if (this.keys.hasOwnProperty(key)) this[key] = value; + if (allowUnknownKeys || this.keys.hasOwnProperty(key)) this[key] = value; }); }, diff --git a/test/config.spec.coffee b/test/config.spec.coffee index <HASH>..<HASH> 100644 --- a/test/config.spec.coffee +++ b/test/config.spec.coffee @@ -132,6 +132,11 @@ describe 'AWS.Config', -> config.update(foo: 10) expect(config.foo).toEqual(undefined) + it 'allows unknown keys if allowUnknownKeys is set', -> + config = new AWS.Config() + config.update(foo: 10, true) + expect(config.foo).toEqual(10) + it 'should be able to update literal credentials', -> config = new AWS.Config() config.update(
Allow unknown keys when initializing clients so custom config sticks around
aws_aws-sdk-js
train
e733c7f6cde31e13be5b008fd88d4409c08d9fc6
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -153,6 +153,8 @@ exports.array = function (len) { return b } function decode (buffer, offset) { + if(buffer.length < offset + len) + throw new Error('buffer to short to contain length:' + len) return buffer.slice(offset, offset + len) } encode.bytesWritten = decode.bytesRead = len @@ -180,6 +182,8 @@ exports.varbuf = function (lenType) { var length = lenType.decode(buffer, offset) var bytes = lenType.decode.bytesRead decode.bytesRead = bytes + length + if(bytes + offset + length > buffer.length) + throw new Error('read out of buffer range') return buffer.slice(offset + bytes, offset + bytes + length) }, encodingLength: function (value) {
buffer should throw if the buffer is too short
varstruct_varstruct
train
553e0932b28221905a0939cdbd3f8b43dc0698aa
diff --git a/core/server/models/base/actions.js b/core/server/models/base/actions.js index <HASH>..<HASH> 100644 --- a/core/server/models/base/actions.js +++ b/core/server/models/base/actions.js @@ -2,6 +2,9 @@ const _ = require('lodash'); const errors = require('@tryghost/errors'); const logging = require('@tryghost/logging'); +/** + * @param {import('bookshelf')} Bookshelf + */ module.exports = function (Bookshelf) { Bookshelf.Model = Bookshelf.Model.extend({ /** diff --git a/core/server/models/base/raw-knex.js b/core/server/models/base/raw-knex.js index <HASH>..<HASH> 100644 --- a/core/server/models/base/raw-knex.js +++ b/core/server/models/base/raw-knex.js @@ -5,6 +5,9 @@ const Promise = require('bluebird'); const schema = require('../../data/schema'); +/** + * @param {import('bookshelf')} Bookshelf + */ module.exports = function (Bookshelf) { Bookshelf.Model = Bookshelf.Model.extend({}, { /**
Added missing Bookshelf JSDoc import no issue - this helps us with types across the model code
TryGhost_Ghost
train
da06afafc87b03f7588b6bd319e1b7592b091339
diff --git a/transformers/configuration_distilbert.py b/transformers/configuration_distilbert.py index <HASH>..<HASH> 100644 --- a/transformers/configuration_distilbert.py +++ b/transformers/configuration_distilbert.py @@ -28,7 +28,7 @@ logger = logging.getLogger(__name__) DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP = { 'distilbert-base-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/distilbert-base-uncased-config.json", 'distilbert-base-uncased-distilled-squad': "https://s3.amazonaws.com/models.huggingface.co/bert/distilbert-base-uncased-distilled-squad-config.json", - 'distilbert-base-german-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/distilbert-base-german-cased-config.json" + 'distilbert-base-german-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/distilbert-base-german-cased-config.json", } diff --git a/transformers/modeling_distilbert.py b/transformers/modeling_distilbert.py index <HASH>..<HASH> 100644 --- a/transformers/modeling_distilbert.py +++ b/transformers/modeling_distilbert.py @@ -43,7 +43,7 @@ logger = logging.getLogger(__name__) DISTILBERT_PRETRAINED_MODEL_ARCHIVE_MAP = { 'distilbert-base-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/distilbert-base-uncased-pytorch_model.bin", 'distilbert-base-uncased-distilled-squad': "https://s3.amazonaws.com/models.huggingface.co/bert/distilbert-base-uncased-distilled-squad-pytorch_model.bin", - 'distilbert-base-german-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/distilbert-base-german-cased-pytorch_model.bin" + 'distilbert-base-german-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/distilbert-base-german-cased-pytorch_model.bin", } diff --git a/transformers/tokenization_distilbert.py b/transformers/tokenization_distilbert.py index <HASH>..<HASH> 100644 --- a/transformers/tokenization_distilbert.py +++ b/transformers/tokenization_distilbert.py @@ -33,7 +33,7 @@ PRETRAINED_VOCAB_FILES_MAP = { { 'distilbert-base-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt", 'distilbert-base-uncased-distilled-squad': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt", - 'distilbert-base-german-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/distilbert-base-german-cased-vocab.txt" + 'distilbert-base-german-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/distilbert-base-german-cased-vocab.txt", } }
tree-wide: add trailing comma in configuration maps
huggingface_pytorch-pretrained-BERT
train
3087121fb35e1a8db833117ef2cfcaa29bd8ced8
diff --git a/src/com/opencms/file/CmsExport.java b/src/com/opencms/file/CmsExport.java index <HASH>..<HASH> 100644 --- a/src/com/opencms/file/CmsExport.java +++ b/src/com/opencms/file/CmsExport.java @@ -2,8 +2,8 @@ package com.opencms.file; /* * File : $Source: /alkacon/cvs/opencms/src/com/opencms/file/Attic/CmsExport.java,v $ - * Date : $Date: 2001/02/21 10:06:56 $ - * Version: $Revision: 1.16 $ + * Date : $Date: 2001/02/28 16:42:57 $ + * Version: $Revision: 1.17 $ * * Copyright (C) 2000 The OpenCms Group * @@ -42,7 +42,7 @@ import com.opencms.util.*; * to the filesystem. * * @author Andreas Schouten - * @version $Revision: 1.16 $ $Date: 2001/02/21 10:06:56 $ + * @version $Revision: 1.17 $ $Date: 2001/02/28 16:42:57 $ */ public class CmsExport implements I_CmsConstants, Serializable { @@ -159,7 +159,7 @@ public CmsExport(String exportFile, String[] exportPaths, CmsObject cms, boolean */ public CmsExport(String exportFile, String[] exportPaths, CmsObject cms, boolean excludeSystem, boolean excludeUnchanged, Node moduleNode) throws CmsException { - this(exportFile, exportPaths, cms, excludeSystem, excludeUnchanged, null, false); + this(exportFile, exportPaths, cms, excludeSystem, excludeUnchanged, moduleNode, false); } /** * This constructs a new CmsImport-object which imports the resources. diff --git a/src/com/opencms/file/CmsRegistry.java b/src/com/opencms/file/CmsRegistry.java index <HASH>..<HASH> 100644 --- a/src/com/opencms/file/CmsRegistry.java +++ b/src/com/opencms/file/CmsRegistry.java @@ -2,8 +2,8 @@ package com.opencms.file; /* * File : $Source: /alkacon/cvs/opencms/src/com/opencms/file/Attic/CmsRegistry.java,v $ - * Date : $Date: 2001/02/21 12:35:28 $ - * Version: $Revision: 1.28 $ + * Date : $Date: 2001/02/28 16:42:57 $ + * Version: $Revision: 1.29 $ * * Copyright (C) 2000 The OpenCms Group * @@ -42,7 +42,7 @@ import com.opencms.core.*; * This class implements the registry for OpenCms. * * @author Andreas Schouten - * @version $Revision: 1.28 $ $Date: 2001/02/21 12:35:28 $ + * @version $Revision: 1.29 $ $Date: 2001/02/28 16:42:57 $ * */ public class CmsRegistry extends A_CmsXmlContent implements I_CmsRegistry { @@ -1410,7 +1410,6 @@ private void init() throws Exception { NodeList modules = m_xmlReg.getElementsByTagName("module"); // create the hashtable for the shortcuts m_modules.clear(); - // walk throug all modules for (int i = 0; i < modules.getLength(); i++) { Element module = (Element) modules.item(i);
bugfix: moduleExport reanimated
alkacon_opencms-core
train
aa8afbaa1ad7b4d3c24605e6a1456184ff90e89e
diff --git a/src/sos/sos_executor.py b/src/sos/sos_executor.py index <HASH>..<HASH> 100755 --- a/src/sos/sos_executor.py +++ b/src/sos/sos_executor.py @@ -427,7 +427,7 @@ class Base_Executor: added_node = 0 dangling_targets, existing_targets = dag.dangling(targets) if dangling_targets: - env.logger.info(f'Resolving {dangling_targets} objects from {dag.number_of_nodes()} nodes') + env.logger.debug(f'Resolving {dangling_targets} objects from {dag.number_of_nodes()} nodes') # find matching steps # check auxiliary steps and see if any steps provides it for target in dangling_targets:
Reduce a message from info to debug
vatlab_SoS
train
fa5678d64a0c8946c1cf65921446e30440dd5c2b
diff --git a/ceph_deploy/cli.py b/ceph_deploy/cli.py index <HASH>..<HASH> 100644 --- a/ceph_deploy/cli.py +++ b/ceph_deploy/cli.py @@ -81,13 +81,27 @@ def parse_args(args=None, namespace=None): def main(args=None, namespace=None): args = parse_args(args=args, namespace=namespace) - loglevel = logging.INFO + console_loglevel = logging.INFO if args.verbose: - loglevel = logging.DEBUG + console_loglevel = logging.DEBUG + sh = logging.StreamHandler() + sh.setLevel(console_loglevel) - logging.basicConfig( - level=loglevel, - ) + fh = logging.FileHandler('{cluster}.log'.format(cluster=args.cluster)) + fh.setLevel(logging.DEBUG) + formatter = logging.Formatter( + '%(asctime)s %(name)s %(levelname)s %(message)s') + fh.setFormatter(formatter) + + # because we're in a module already, __name__ is not the ancestor of + # the rest of the package; use the root as the logger for everyone + root_logger = logging.getLogger() + + # allow all levels at root_logger, handlers control individual levels + root_logger.setLevel(logging.DEBUG) + + root_logger.addHandler(sh) + root_logger.addHandler(fh) sudo_pushy.patch()
Send log msgs to file '{cluster}.log' as well as console. Default log level is INFO to console, DEBUG to logfile --verbose changes console log level to DEBUG as well logfile gets timestamp modulename level msg, console gets just msg Fixes: #<I>
ceph_ceph-deploy
train
dc093b14d5494beb401fe3f1c43aa5ec3489580d
diff --git a/enabler/src/com/openxc/enabler/DiagnosticRequestFragment.java b/enabler/src/com/openxc/enabler/DiagnosticRequestFragment.java index <HASH>..<HASH> 100644 --- a/enabler/src/com/openxc/enabler/DiagnosticRequestFragment.java +++ b/enabler/src/com/openxc/enabler/DiagnosticRequestFragment.java @@ -137,6 +137,8 @@ public class DiagnosticRequestFragment extends ListFragment { private void updateLastRequestView(final DiagnosticRequest request) { getActivity().runOnUiThread(new Runnable() { public void run() { + // TODO This is duplicated in DiagnosticResponseAdapter - figure + // out the best way to share this rendering info TextView timestampView = (TextView) mLastRequestView.findViewById(R.id.timestamp); timestampView.setText(new SimpleDateFormat("HH:mm:ss").format( diff --git a/enabler/src/com/openxc/enabler/DiagnosticResponseAdapter.java b/enabler/src/com/openxc/enabler/DiagnosticResponseAdapter.java index <HASH>..<HASH> 100644 --- a/enabler/src/com/openxc/enabler/DiagnosticResponseAdapter.java +++ b/enabler/src/com/openxc/enabler/DiagnosticResponseAdapter.java @@ -1,5 +1,7 @@ package com.openxc.enabler; +import java.text.SimpleDateFormat; + import android.content.Context; import android.view.LayoutInflater; import android.view.View; @@ -26,11 +28,15 @@ public class DiagnosticResponseAdapter extends KeyedMessageAdapter { public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null) { convertView = LayoutInflater.from(mContext) - .inflate(R.layout.can_message_list_item, parent, false); + .inflate(R.layout.diagnostic_request_list_item, parent, false); } DiagnosticResponse message = getItem(position); + TextView timestampView = (TextView) convertView.findViewById(R.id.timestamp); + timestampView.setText(new SimpleDateFormat("HH:mm:ss").format( + message.getDate())); + TextView busView = (TextView) convertView.findViewById(R.id.bus); busView.setText("" + message.getBusId());
Fix display of received diag responses in Enabler. It's currently using an adapter based on the key, so you only see the latest response for each key. This might be OK, or we might need to have more of a running timeline of all responses received.
openxc_openxc-android
train
5616bf287befc3493a0d1ba456d9c5b6e6bf30d5
diff --git a/src/Mailjet/Api/Client.php b/src/Mailjet/Api/Client.php index <HASH>..<HASH> 100644 --- a/src/Mailjet/Api/Client.php +++ b/src/Mailjet/Api/Client.php @@ -2,8 +2,9 @@ namespace Mailjet\Api; -use Guzzle\Http\Message\Request; use Guzzle\Http\Message\Response; +use Guzzle\Http\Message\RequestInterface; + use Guzzle\Http\Client as HttpClient; use Guzzle\Http\ClientInterface; @@ -168,7 +169,7 @@ class Client * @param Request $request * @param array $options */ - private function prepareRequest(Request $request, $options = array()) + private function prepareRequest(RequestInterface $request, $options = array()) { $request->setAuth($this->apiKey, $this->secretKey); diff --git a/tests/Mailjet/Api/ClientTest.php b/tests/Mailjet/Api/ClientTest.php index <HASH>..<HASH> 100644 --- a/tests/Mailjet/Api/ClientTest.php +++ b/tests/Mailjet/Api/ClientTest.php @@ -3,6 +3,7 @@ namespace Mailjet\Tests\Api; use Mailjet\Api\Client; +use Mailjet\Api\RequestApi; class ClientTest extends \PHPUnit_Framework_TestCase { @@ -44,6 +45,23 @@ class ClientTest extends \PHPUnit_Framework_TestCase $this->client->setConnectionMode('bogusmode'); } + public function testGetQuery() + { + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); + + $requestMock = $this->getMock('Guzzle\Http\Message\RequestInterface'); + $apiMock = $this->getMock('Guzzle\Http\ClientInterface'); + $apiMock->expects($this->any()) + ->method('get') + ->will($this->returnValue($requestMock)) + ; + $this->client->setApi($apiMock); + + $response = $this->client->get(RequestApi::USER_INFOS); + } + /** * @expectedException \InvalidArgumentException */
[WIP] add test coverage for Client::get
KnpLabs_mailjet-api-php
train
039bf95a92a2baeb90eddf2692eb818053bdbf43
diff --git a/core/resource/ResourceCollection.php b/core/resource/ResourceCollection.php index <HASH>..<HASH> 100644 --- a/core/resource/ResourceCollection.php +++ b/core/resource/ResourceCollection.php @@ -21,7 +21,6 @@ namespace oat\generis\model\resource; use common_persistence_SqlPersistence; use core_kernel_classes_Class; -use core_kernel_classes_Resource; use Countable; use Iterator; use common_persistence_sql_Filter as Filter; @@ -90,11 +89,14 @@ class ResourceCollection implements Iterator, Countable /** * ResourceCollection constructor. * - * @param null $class + * @param null|string|core_kernel_classes_Class $class * @param int $cacheSize */ public function __construct($class = null, $cacheSize = self::CACHE_SIZE) { + if ($class !== null) { + $class = $this->getClass($class); + } $this->class = $class; $this->filter = new Filter(); $this->cacheSize = $cacheSize; @@ -257,7 +259,7 @@ class ResourceCollection implements Iterator, Countable */ private function isLimitReached() { - return $this->limit !== null && (!$this->count()) < $this->limit; + return $this->limit !== null && $this->count() >= $this->limit; } /** @@ -274,10 +276,6 @@ class ResourceCollection implements Iterator, Countable */ private function addClassFilter() { - if (is_string($this->class)) { - $this->getClass($this->class); - } - $this->addTypeFilter($this->class->getUri()); $this->classFilterSet = true; } diff --git a/scripts/tools/FileSerializerMigration/Migrate.php b/scripts/tools/FileSerializerMigration/Migrate.php index <HASH>..<HASH> 100644 --- a/scripts/tools/FileSerializerMigration/Migrate.php +++ b/scripts/tools/FileSerializerMigration/Migrate.php @@ -14,7 +14,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * - * Copyright (c) 2017 (original work) Open Assessment Technologies SA; + * Copyright (c) 2019 (original work) Open Assessment Technologies SA; * * @author Martijn Swinkels <m.swinkels@taotesting.com> */ @@ -205,12 +205,11 @@ class Migrate extends ScriptAction * Check if the file serializer service needs to be updated * * @return bool - * @throws InvalidServiceManagerException */ private function fileSerializerNeedsUpdate() { $needsUpdate = true; - $currentFileReferenceSerializer = $this->getServiceManager()->get(FileReferenceSerializer::SERVICE_ID); + $currentFileReferenceSerializer = $this->getServiceLocator()->get(FileReferenceSerializer::SERVICE_ID); if ($currentFileReferenceSerializer instanceof UrlFileSerializer) { $needsUpdate = false; } diff --git a/scripts/tools/FileSerializerMigration/MigrationHelper.php b/scripts/tools/FileSerializerMigration/MigrationHelper.php index <HASH>..<HASH> 100644 --- a/scripts/tools/FileSerializerMigration/MigrationHelper.php +++ b/scripts/tools/FileSerializerMigration/MigrationHelper.php @@ -14,7 +14,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * - * Copyright (c) 2018 (original work) Open Assessment Technologies SA (under the project TAO-PRODUCT); + * Copyright (c) 2019 (original work) Open Assessment Technologies SA (under the project TAO-PRODUCT); */ namespace oat\generis\scripts\tools\FileSerializerMigration; @@ -29,8 +29,7 @@ use oat\generis\model\GenerisRdf; use oat\generis\model\OntologyAwareTrait; use oat\oatbox\filesystem\Directory; use oat\oatbox\filesystem\File; -use oat\oatbox\service\ServiceManager; -use Zend\ServiceManager\ServiceLocatorInterface; +use Zend\ServiceManager\ServiceLocatorAwareTrait; /** * Helper class for the File serializer migration script @@ -38,6 +37,7 @@ use Zend\ServiceManager\ServiceLocatorInterface; class MigrationHelper { use OntologyAwareTrait; + use ServiceLocatorAwareTrait; /** * Amount of resources processed in one batch @@ -74,16 +74,6 @@ class MigrationHelper public $failedResources = []; /** - * @var ServiceManager - */ - private $serviceLocator; - - /** - * @var ServiceManager - */ - private $serviceManager; - - /** * @var bool */ public $endReached = false; @@ -181,26 +171,6 @@ class MigrationHelper } /** - * Set the Service Locator for this class - * - * @param ServiceLocatorInterface $serviceLocator - */ - public function setServiceLocator(ServiceLocatorInterface $serviceLocator) - { - $this->serviceLocator = $serviceLocator; - } - - /** - * Get the Service Locator - * - * @return ServiceLocatorInterface - */ - private function getServiceLocator() - { - return $this->serviceLocator; - } - - /** * @return array */ private function getFileResourceData()
Updated code based on PR review
oat-sa_generis
train
c809486d27f84cc05941eac63f9a065d51ebefcd
diff --git a/petact/__init__.py b/petact/__init__.py index <HASH>..<HASH> 100644 --- a/petact/__init__.py +++ b/petact/__init__.py @@ -1,3 +1,3 @@ from .petact import calc_md5, download, download_extract_tar, install_package -__version__ = '0.1.0' +__version__ = '0.1.1'
Increment version to <I>
MatthewScholefield_petact
train
10cd77555d9a7494359faed1242b7c52e896bb9f
diff --git a/pyes/__init__.py b/pyes/__init__.py index <HASH>..<HASH> 100644 --- a/pyes/__init__.py +++ b/pyes/__init__.py @@ -4,7 +4,7 @@ import logging logger = logging.getLogger(__name__) -VERSION = (0, 19, 2, "dev") +VERSION = (0, 20, 0) __version__ = ".".join(map(str, VERSION[0:3])) + "".join(VERSION[3:]) __author__ = "Alberto Paro" diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -60,7 +60,7 @@ class QuickRunTests(TestCommand): TestCommand.run(self, *args, **kwargs) -install_requires = ["urllib3"] +install_requires = ["urllib3==1.6"] #if not sys.platform.startswith("java"): # install_requires += [ "thrift", ]
Preparing to release <I>
aparo_pyes
train
7d3addd6c56614ed012001ba289059cd12714f45
diff --git a/app/controllers/devise_invitable/registrations_controller.rb b/app/controllers/devise_invitable/registrations_controller.rb index <HASH>..<HASH> 100644 --- a/app/controllers/devise_invitable/registrations_controller.rb +++ b/app/controllers/devise_invitable/registrations_controller.rb @@ -1,8 +1,8 @@ class DeviseInvitable::RegistrationsController < Devise::RegistrationsController protected - def build_resource(*args) - hash = args.first || resource_params || {} + def build_resource(hash = nil) + hash ||= resource_params || {} if hash[:email] self.resource = resource_class.where(:email => hash[:email], :encrypted_password => '').first if self.resource
popping last element modifies params array therefore super receives empty object, returns nil, and causes tests to fail
scambra_devise_invitable
train
c9cf56f4426e2797a30b6c3d7fcfcee3107356a0
diff --git a/spec/dumper_spec.rb b/spec/dumper_spec.rb index <HASH>..<HASH> 100644 --- a/spec/dumper_spec.rb +++ b/spec/dumper_spec.rb @@ -244,6 +244,12 @@ describe Hexdump::Dumper do expect(words).to be == binary_words end end + + context "when no block is given" do + it "must return an Enumerator" do + expect(subject.each(data)).to be_kind_of(Enumerator) + end + end end describe "#dump" do
Added a spec for the return value of #each.
postmodern_hexdump
train
47fd2b978ea3ce34798ef494203a1422fd3b3347
diff --git a/simpycity/model.py b/simpycity/model.py index <HASH>..<HASH> 100644 --- a/simpycity/model.py +++ b/simpycity/model.py @@ -274,14 +274,16 @@ class SimpleModel(Construct): """Sets the provided name to the provided value, in the dirty dictionary. This only occurs if the specified name is in the table specification.""" - - if name in self.table: - if not hasattr(self, "__dict__"): - self.__dict__ = {} - if '__dirty' not in self.__dict__: - self.__dict__['__dirty'] = {} - - self.__dict__['__dirty'][name] = value + if hasattr(self, "table"): + if name in self.table: + if not hasattr(self, "__dict__"): + self.__dict__ = {} + if '__dirty' not in self.__dict__: + self.__dict__['__dirty'] = {} + + self.__dict__['__dirty'][name] = value + else: + super(SimpleModel, self).__setattr__(name, value) else: # setattr(self, name, value) @@ -296,14 +298,17 @@ class SimpleModel(Construct): """ cols = object.__getattribute__(self, "__dict__") - table = object.__getattribute__(self, "table") - if name in table: - if name in cols: - return cols[name] - elif name in cols['__dirty']: - return cols['__dirty'][name] + if hasattr(self, "table"): + table = object.__getattribute__(self, "table") + + if name in table: + if name in cols: + return cols[name] + elif name in cols['__dirty']: + return cols['__dirty'][name] else: + attr = object.__getattribute__(self, name) return attr
Repairing some bugs in the Model, assuming that a table attribute would be present in all models (it is not required)
commandprompt_Simpycity
train
60e567b559411e88f50166e8962ab4b89f53a3b5
diff --git a/test/unit/composite-adapter-test.js b/test/unit/composite-adapter-test.js index <HASH>..<HASH> 100644 --- a/test/unit/composite-adapter-test.js +++ b/test/unit/composite-adapter-test.js @@ -116,6 +116,52 @@ suite('composite-adapter', function() { }); }); }); + suite('updateTask()', function() { + var dbconn; + setup(function() { + initSandbox(); + composite.initialize( + config, + function(e,dbconn_local) { dbconn = dbconn_local }, + config_helper); + }); + + teardown(function() { + sandbox.restore(); + }); + + test('calls updateTask() of correct adapter', function() { + var callback = sandbox.spy(); + var task = {id:{db_id:2}}; + dbconn.updateTask(task, callback); + expect(dbconn._databases[2].updateTask).to.have.been.calledOnce; + expect(dbconn._databases[2].updateTask).to.have.been + .calledWith(task, callback); + }); + }); + suite('completeTask()', function() { + var dbconn; + setup(function() { + initSandbox(); + composite.initialize( + config, + function(e,dbconn_local) { dbconn = dbconn_local }, + config_helper); + }); + + teardown(function() { + sandbox.restore(); + }); + + test('calls completeTask() of correct adapter', function() { + var callback = sandbox.spy(); + var task = {id:{db_id:2}}; + dbconn.completeTask(task, callback); + expect(dbconn._databases[2].completeTask).to.have.been.calledOnce; + expect(dbconn._databases[2].completeTask).to.have.been + .calledWith(task, callback); + }); + }); suite('_findDbById()', function() { var dbconn; setup(function() { @@ -140,6 +186,8 @@ suite('composite-adapter', function() { var adapter = {db_id: i}; adapter.saveTask = sandbox.spy(); adapter.listenTask = sandbox.spy(); + adapter.updateTask = sandbox.spy(); + adapter.completeTask = sandbox.spy(); adapters[i] = adapter; var aug_conf = {dbconn: adapter} config_helper.initializeDb.onCall(i).callsArgWith(1, null, aug_conf);
added tests for updateTask and completeTask
meetings_gearsloth
train
6bc29cc2b4e2f295a809974cad62d770c974d4fa
diff --git a/invenio_github/api.py b/invenio_github/api.py index <HASH>..<HASH> 100644 --- a/invenio_github/api.py +++ b/invenio_github/api.py @@ -354,12 +354,10 @@ class GitHubRelease(object): @cached_property def title(self): """Extract title from a release.""" - if self.event: - if self.release['name']: - return u'{0}: {1}'.format( - self.repository['full_name'], self.release['name'] - ) - return u'{0} {1}'.format(self.repo_model.name, self.model.tag) + repo_name = self.repository.get('full_name', self.repo_model.name) + release_name = self.release.get( + 'name', self.release.get('tag_name', self.model.tag)) + return u'{0}: {1}'.format(repo_name, release_name) @cached_property def description(self):
fix: use GitHub payload for title * uses repository name from GitHub payload instead of the first repo name we've got from GitHub. The problem was that, if the release has no name, we were using the first name we collected for the repo. If the repo's name changed over time, the title would be incorrect.
inveniosoftware_invenio-github
train
c4ccd93842e109fbea6c7bf6f875aaf1c0cdf9ab
diff --git a/src/Illuminate/Routing/Router.php b/src/Illuminate/Routing/Router.php index <HASH>..<HASH> 100644 --- a/src/Illuminate/Routing/Router.php +++ b/src/Illuminate/Routing/Router.php @@ -328,8 +328,14 @@ class Router implements RegistrarContract, BindingRegistrar */ public function apiResource($name, $controller, array $options = []) { + $only = ['index', 'show', 'store', 'update', 'destroy']; + + if (isset($options['except'])) { + $only = array_diff($only, (array) $options['except']); + } + return $this->resource($name, $controller, array_merge([ - 'only' => ['index', 'show', 'store', 'update', 'destroy'], + 'only' => $only, ], $options)); } diff --git a/tests/Routing/RouteRegistrarTest.php b/tests/Routing/RouteRegistrarTest.php index <HASH>..<HASH> 100644 --- a/tests/Routing/RouteRegistrarTest.php +++ b/tests/Routing/RouteRegistrarTest.php @@ -269,6 +269,31 @@ class RouteRegistrarTest extends TestCase $this->assertFalse($this->router->getRoutes()->hasNamedRoute('users.edit')); } + public function testUserCanRegisterApiResourceWithExceptOption() + { + $this->router->apiResource('users', \Illuminate\Tests\Routing\RouteRegistrarControllerStub::class, [ + 'except' => ['destroy'], + ]); + + $this->assertCount(4, $this->router->getRoutes()); + + $this->assertFalse($this->router->getRoutes()->hasNamedRoute('users.create')); + $this->assertFalse($this->router->getRoutes()->hasNamedRoute('users.edit')); + $this->assertFalse($this->router->getRoutes()->hasNamedRoute('users.destroy')); + } + + public function testUserCanRegisterApiResourceWithOnlyOption() + { + $this->router->apiResource('users', \Illuminate\Tests\Routing\RouteRegistrarControllerStub::class, [ + 'only' => ['index', 'show'], + ]); + + $this->assertCount(2, $this->router->getRoutes()); + + $this->assertTrue($this->router->getRoutes()->hasNamedRoute('users.index')); + $this->assertTrue($this->router->getRoutes()->hasNamedRoute('users.show')); + } + public function testCanNameRoutesOnRegisteredResource() { $this->router->resource('comments', 'Illuminate\Tests\Routing\RouteRegistrarControllerStub')
Let apiResource support except option. (#<I>)
laravel_framework
train
c5602f1fa6b4d06765b058830f41770ce0d8de74
diff --git a/opticalmaterialspy/_material_base.py b/opticalmaterialspy/_material_base.py index <HASH>..<HASH> 100644 --- a/opticalmaterialspy/_material_base.py +++ b/opticalmaterialspy/_material_base.py @@ -292,3 +292,14 @@ class _MaterialAni(metaclass=abc.ABCMeta): @property def zy(self): return None + + def n3(self, wl): + return [self.xx.n(wl), self.yy.n(wl), self.zz.n(wl)] + + def n_xyz(self, wl): + return self.n3(wl) + + def n5(self, wl): + return [self.xx.n(wl), self.xy.n(wl), self.yx.n(wl), + self.yy.n(wl), self.zz.n(wl)] +
Added helper functions to anisotropic materials.
jtambasco_opticalmaterialspy
train
c931cf6ca8d01933a1bdd5b5b12ee0bf52fd7b51
diff --git a/models/classes/search/class.ItemContentTokenizer.php b/models/classes/search/class.ItemContentTokenizer.php index <HASH>..<HASH> 100644 --- a/models/classes/search/class.ItemContentTokenizer.php +++ b/models/classes/search/class.ItemContentTokenizer.php @@ -37,19 +37,23 @@ class taoItems_models_classes_search_ItemContentTokenizer implements Tokenizer foreach ($values as $valueUri) { $file = new core_kernel_file_File($valueUri); - $content = file_get_contents($file->getAbsolutePath()); - if ($content === false) { - common_Logger::w('File '.$file->getAbsolutePath().' not found for item'); - } else { - // Try to make it a DOM Document... - $dom = new DOMDocument('1.0', 'UTF-8'); - - if (@$dom->loadXML($content) === true) { - $contentStrings = array_merge($contentStrings, $xmlTokenizer->getStrings($dom)); - unset($dom); + try { + $content = file_get_contents($file->getAbsolutePath()); + if ($content === false) { + common_Logger::w('File '.$file->getAbsolutePath().' not found for item'); } else { - common_Logger::d('Skipped non XML content for '.$file->getUri()); + // Try to make it a DOM Document... + $dom = new DOMDocument('1.0', 'UTF-8'); + + if (@$dom->loadXML($content) === true) { + $contentStrings = array_merge($contentStrings, $xmlTokenizer->getStrings($dom)); + unset($dom); + } else { + common_Logger::d('Skipped non XML content for '.$file->getUri()); + } } + } catch (common_Exception $exc) { + common_Logger::w('Invalid file '.$valueUri.' for ItemContentTokenizer: '.$exc->getMessage()); } }
Don't throw exception on invalid file indexation
oat-sa_extension-tao-item
train
b67cad46e43c2a88e6f9cc986a9f0c3b6b300971
diff --git a/lib/go/thrift/http_transport.go b/lib/go/thrift/http_transport.go index <HASH>..<HASH> 100644 --- a/lib/go/thrift/http_transport.go +++ b/lib/go/thrift/http_transport.go @@ -19,16 +19,45 @@ package thrift -import "net/http" +import ( + "compress/gzip" + "io" + "net/http" + "strings" +) // NewThriftHandlerFunc is a function that create a ready to use Apache Thrift Handler function func NewThriftHandlerFunc(processor TProcessor, inPfactory, outPfactory TProtocolFactory) func(w http.ResponseWriter, r *http.Request) { - return func(w http.ResponseWriter, r *http.Request) { + return gz(func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Content-Type", "application/x-thrift") transport := NewStreamTransport(r.Body, w) processor.Process(inPfactory.GetProtocol(transport), outPfactory.GetProtocol(transport)) + }) +} + +// gz transparently compresses the HTTP response if the client supports it. +func gz(handler http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { + handler(w, r) + return + } + w.Header().Set("Content-Encoding", "gzip") + gz := gzip.NewWriter(w) + defer gz.Close() + gzw := gzipResponseWriter{Writer: gz, ResponseWriter: w} + handler(gzw, r) } } + +type gzipResponseWriter struct { + io.Writer + http.ResponseWriter +} + +func (w gzipResponseWriter) Write(b []byte) (int, error) { + return w.Writer.Write(b) +}
THRIFT-<I> Implement transparent gzip compression for HTTP transport Client: Go
limingxinleo_thrift
train
7cc3eddb02c0f58eca636552f54d420e60a03168
diff --git a/lib/para/routes.rb b/lib/para/routes.rb index <HASH>..<HASH> 100644 --- a/lib/para/routes.rb +++ b/lib/para/routes.rb @@ -18,9 +18,9 @@ module Para end # Components are namespaced into :admin in their respective methods - crud_component - form_component - component :settings + crud_component scoped_in_para: true + form_component scoped_in_para: true + component :settings, scoped_in_para: true end block.call if block diff --git a/lib/rails/routing_mapper.rb b/lib/rails/routing_mapper.rb index <HASH>..<HASH> 100644 --- a/lib/rails/routing_mapper.rb +++ b/lib/rails/routing_mapper.rb @@ -52,8 +52,6 @@ module ActionDispatch # namespacing issues in plugins and other module namespaced scenarios # controller = options.fetch(:controller, '/para/admin/crud_resources') - imports_controller = options.fetch(:imports_controller, '/para/admin/imports') - exports_controller = options.fetch(:exports_controller, '/para/admin/exports') constraints Para::Routing::ComponentNameConstraint.new(component) do constraints Para::Routing::ComponentControllerConstraint.new(controller) do @@ -94,8 +92,6 @@ module ActionDispatch ) controller = options.fetch(:controller, '/para/admin/form_resources') - imports_controller = options.fetch(:imports_controller, '/para/admin/imports') - exports_controller = options.fetch(:exports_controller, '/para/admin/exports') constraints Para::Routing::ComponentNameConstraint.new(component) do constraints Para::Routing::ComponentControllerConstraint.new(controller) do @@ -141,10 +137,11 @@ module ActionDispatch end def common_component_routes(options) + nested_forms_controller = options.fetch(:nested_forms_controller, '/para/admin/nested_forms') imports_controller = options.fetch(:imports_controller, '/para/admin/imports') exports_controller = options.fetch(:exports_controller, '/para/admin/exports') - get 'nested-form' => 'nested_forms#show' + resource 'nested_form', controller: nested_forms_controller, only: [:show] scope ':importer' do resources :imports, controller: imports_controller
fix app-defined components namespacing issue with remote nested forms controller
para-cms_para
train
0f7c499122084e74c97205fb5f193ea1c2af2a60
diff --git a/lib/dragonfly/job.rb b/lib/dragonfly/job.rb index <HASH>..<HASH> 100644 --- a/lib/dragonfly/job.rb +++ b/lib/dragonfly/job.rb @@ -190,7 +190,7 @@ module Dragonfly def format apply - format_from_meta || analyse(:format) + meta[:format] || (ext.to_sym if ext && app.trust_file_extensions) || analyse(:format) end def mime_type @@ -415,10 +415,6 @@ module Dragonfly attr_reader :previous_temp_objects - def format_from_meta - meta[:format] || (ext.to_sym if ext && app.trust_file_extensions) - end - def last_step_of_type(type) steps.select{|s| s.is_a?(type) }.last end
Job#format_from_meta was unclear and not necessary
markevans_dragonfly
train