hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
9f8aa96343f28c81dde8d4e4cad2ef5b86b3acc9
diff --git a/nbdiff/server/remote_server.py b/nbdiff/server/remote_server.py index <HASH>..<HASH> 100644 --- a/nbdiff/server/remote_server.py +++ b/nbdiff/server/remote_server.py @@ -53,7 +53,7 @@ def merge(): mergedNotebook = notebook_merge(nb_local, nb_base, nb_remote) temp = tempfile.NamedTemporaryFile(delete=False) - json.dump(mergedNotebook, temp) + temp.write(json.dumps(mergedNotebook, indent=2)) temp.close() nb_id = ntpath.basename(temp.name) @@ -84,7 +84,7 @@ def mergeURL(): mergedNotebook = notebook_merge(nb_local, nb_base, nb_remote) temp = tempfile.NamedTemporaryFile(delete=False) - json.dump(mergedNotebook, temp) + temp.write(json.dumps(mergedNotebook, indent=2)) temp.close() nb_id = ntpath.basename(temp.name) @@ -98,10 +98,14 @@ def notebookRequest(path): request.environ.get('werkzeug.server.shutdown')() return "" else: - parsed = open(os.path.join(tempfile.gettempdir(), path)) - return json.dumps(parsed.read()) + filepath = os.path.join(tempfile.gettempdir(), path) + file = open(filepath) + notebook = file.read() + file.close() + #remove the tempfile in order to relieve server resource. + os.remove(filepath) + return notebook - if __name__ == "__main__": app.debug = False app.run()
Fixed loading issues with notebook & cleaned temp
tarmstrong_nbdiff
train
3ac9484d144f83d3e67d9bf99c0d868462ae06ac
diff --git a/lib/opal/parser/lexer.rb b/lib/opal/parser/lexer.rb index <HASH>..<HASH> 100644 --- a/lib/opal/parser/lexer.rb +++ b/lib/opal/parser/lexer.rb @@ -674,6 +674,8 @@ module Opal @lex_state = :expr_end end + self.yylval = matched + return matched =~ /#{REGEXP_START}[A-Z]/ ? :tCONSTANT : :tIDENTIFIER end diff --git a/spec/lib/parser/call_spec.rb b/spec/lib/parser/call_spec.rb index <HASH>..<HASH> 100644 --- a/spec/lib/parser/call_spec.rb +++ b/spec/lib/parser/call_spec.rb @@ -23,6 +23,10 @@ describe "Method calls" do parsed("foo\n.bar").should == [:call, [:call, nil, :foo, [:arglist]], :bar, [:arglist]] lambda { parsed("foo\n..bar") }.should raise_error(Exception) end + + it "parses method starting on the next line after \\" do + parsed("\\\nfoo").should == [:call, nil, :foo, [:arglist]] + end end describe "Operator calls" do
Fix parsing of method call starting after "\" on the next line.
opal_opal
train
dd8c230abedd9462f506c5866e907ee0c29ea46e
diff --git a/main/src/org/objenesis/ObjenesisBase.java b/main/src/org/objenesis/ObjenesisBase.java index <HASH>..<HASH> 100644 --- a/main/src/org/objenesis/ObjenesisBase.java +++ b/main/src/org/objenesis/ObjenesisBase.java @@ -88,8 +88,11 @@ public class ObjenesisBase implements Objenesis { } ObjectInstantiator<?> instantiator = cache.get(clazz.getName()); if(instantiator == null) { - instantiator = strategy.newInstantiatorOf(clazz); - cache.putIfAbsent(clazz.getName(), instantiator); + ObjectInstantiator<?> newInstantiator = strategy.newInstantiatorOf(clazz); + instantiator = cache.putIfAbsent(clazz.getName(), newInstantiator); + if(instantiator == null) { + instantiator = newInstantiator; + } } return (ObjectInstantiator<T>) instantiator; }
Should return the value from putIfAbsent
easymock_objenesis
train
c0a01dbc91ace606e3cc5ab6fa0e16c6dd41b9aa
diff --git a/src/Model/Comment.php b/src/Model/Comment.php index <HASH>..<HASH> 100755 --- a/src/Model/Comment.php +++ b/src/Model/Comment.php @@ -766,6 +766,20 @@ class Comment extends DataObject } /** + * Proxy for checking whether the has permission to comment on the comment parent. + * + * @param Member $member Member to check + * + * @return boolean + */ + public function canPostComment($member = null) + { + return $this->Parent() + && $this->Parent()->exists() + && $this->Parent()->canPostComment($member); + } + + /** * Returns the list of all replies * * @return SS_List
BUGFIX created way of knowing whether user has permission to post
silverstripe_silverstripe-comments
train
c4cc2c9969ffc357b49283ecadf1d0fa4dac41ad
diff --git a/karma.conf.js b/karma.conf.js index <HASH>..<HASH> 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -3,21 +3,18 @@ module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) - basePath: '/home/eric/repos/react-d3-charts', + basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['mocha', 'browserify', 'chai', 'chai-as-promised'], // list of files / patterns to load in the browser + // 'utils/phantomjs-shims.js', files: [ - 'utils/phantomjs-shims.js', 'tests/index.js' ], - // list of files to exclude - exclude: [], - // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { @@ -48,11 +45,13 @@ module.exports = function(config) { autoWatch: false, plugins: [ - 'karma-*', // 'karma-chrome-launcher', - // 'karma-jasmine', - // 'karma-phantomjs', - // 'karma-browserify' + 'karma-phantomjs-launcher', + 'karma-jasmine', + 'karma-mocha', + 'karma-chai', + 'karma-chai-plugins', + 'karma-bro' ], // start these browsers
Refinements to karma config
esbullington_react-d3
train
4da00517de77c16df0ca1146566eccc24bf3773a
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -517,14 +517,18 @@ Ycb.prototype = { var value = context[name]; if (isA(value, Array)) { var lookup = []; - value.forEach(function (val) { - if (options.useAllDimensions || (this.dimsUsed[name] && this.dimsUsed[name][val])) { - lookup = lookup.concat(this._dimensionHierarchies[name][val] || DEFAULT_LOOKUP); - } else { - lookup = lookup.concat(DEFAULT_LOOKUP); - } - }, this); - chains[name] = arrayReverseUnique(lookup); + if (value.length > 0) { + value.forEach(function (val) { + if (options.useAllDimensions || (this.dimsUsed[name] && this.dimsUsed[name][val])) { + lookup = lookup.concat(this._dimensionHierarchies[name][val] || DEFAULT_LOOKUP); + } else { + lookup = lookup.concat(DEFAULT_LOOKUP); + } + }, this); + chains[name] = arrayReverseUnique(lookup); + } else { + chains[name] = DEFAULT_LOOKUP; + } } else { if (options.useAllDimensions || (this.dimsUsed[name] && this.dimsUsed[name][value])) { chains[name] = this._dimensionHierarchies[name][value] || DEFAULT_LOOKUP; diff --git a/tests/unit/index.js b/tests/unit/index.js index <HASH>..<HASH> 100644 --- a/tests/unit/index.js +++ b/tests/unit/index.js @@ -119,6 +119,18 @@ describe('ycb unit tests', function () { '*' ], list.bucket); }); + it('should generate default lookup when multi-value dimensions is an empty array', function () { + var dims = readFixtureFile('dimensions.json'), + ycb = new libycb.Ycb(dims), + context, list; + context = { + 'bucket': [] + }; + list = ycb._makeOrderedLookupList(context, {useAllDimensions: true}); + assert.deepEqual([ + '*' + ], list.bucket); + }); }); describe('_createSettingsLookups', function () { @@ -244,6 +256,20 @@ describe('ycb unit tests', function () { ]; assert.deepEqual(expected, paths); }); + it('should handle multi-value dimensions with an empty array', function () { + var dims = readFixtureFile('dimensions.json'), + ycb = new libycb.Ycb(dims), + context, paths, expected; + context = { + 'bucket': [] + }; + paths = ycb._getLookupPaths(context, {useAllDimensions: true}); + + expected = [ + '*/*/*/*/*/*/*/*/*/*/*' + ]; + assert.deepEqual(expected, paths); + }); }); describe('_processRawBundle', function () {
fix the case when multi-value dimension is an empty array
yahoo_ycb
train
8c7f6884f2c5861f875fb5219978f6ad75152b12
diff --git a/test/e2e/lib/components/shopping-cart-widget-component.js b/test/e2e/lib/components/shopping-cart-widget-component.js index <HASH>..<HASH> 100644 --- a/test/e2e/lib/components/shopping-cart-widget-component.js +++ b/test/e2e/lib/components/shopping-cart-widget-component.js @@ -14,13 +14,13 @@ import AsyncBaseContainer from '../async-base-container'; export default class ShoppingCartWidgetComponent extends AsyncBaseContainer { constructor( driver ) { - super( driver, by.css( '.cart-toggle-button' ) ); + super( driver, by.css( '.popover-cart .header-button' ) ); } async open() { return await driverHelper.clickWhenClickable( this.driver, - by.css( '.cart-toggle-button' ), + by.css( '.popover-cart .header-button' ), this.explicitWaitMS ); }
Fix broken selector in e2e tests (#<I>)
Automattic_wp-calypso
train
9465b5299fb405efa274b358f6f85c3f9a179d98
diff --git a/addons/cb.files.editor/views/file.js b/addons/cb.files.editor/views/file.js index <HASH>..<HASH> 100644 --- a/addons/cb.files.editor/views/file.js +++ b/addons/cb.files.editor/views/file.js @@ -332,6 +332,9 @@ define([ this.sync.on("mode", function(mode) { this.tab.setTabState("sync", mode == this.sync.modes.SYNC); }, this); + this.sync.on("close", function(mode) { + this.tab.closeTab(); + }, this); this.sync.on("sync:modified", function(state) { this.tab.setTabState("modified", state); diff --git a/client/utils/filesync.js b/client/utils/filesync.js index <HASH>..<HASH> 100644 --- a/client/utils/filesync.js +++ b/client/utils/filesync.js @@ -323,13 +323,13 @@ define([ logging.log("update env with", this.envId, options, hr.Offline.isConnected()); - if (this.file.isNewfile()) options.sync = false; + if (this.file.isNewfile() || !hr.Offline.isConnected()) options.sync = false; // Signal update this.trigger("update:env", options); // Start sync - if (!hr.Offline.isConnected() || !options.sync) { + if (!options.sync) { /// Offline sync self.setMode(self.modes.READONLY); @@ -341,6 +341,7 @@ define([ self.setMode(self.modes.ASYNC); }, function(err) { logging.error("Error for offline sync: ", err); + self.trigger("close"); }); } else { /// Online sync
Close file when during init of sync
CodeboxIDE_codebox
train
57a1f5e5000a14b37dc1048ebaa2b28b72ade51a
diff --git a/cmd/influxd/server_integration_test.go b/cmd/influxd/server_integration_test.go index <HASH>..<HASH> 100644 --- a/cmd/influxd/server_integration_test.go +++ b/cmd/influxd/server_integration_test.go @@ -255,7 +255,6 @@ var mergeMany = func(t *testing.T, node *Node, database, retention string) { for j := 1; j < 5+i%3; j++ { data := fmt.Sprintf(`{"database": "%s", "retentionPolicy": "%s", "points": [{"name": "cpu", "timestamp": "%s", "tags": {"host": "server_%d"}, "fields": {"value": 22}}]}`, database, retention, time.Unix(int64(j), int64(0)).Format(time.RFC3339), i) - fmt.Println(data) write(t, node, data) }
Remove debug fmt.Println from tests
influxdata_influxdb
train
1b330a8c55f0ec114970855c6682627434216ab5
diff --git a/superset/views/core.py b/superset/views/core.py index <HASH>..<HASH> 100755 --- a/superset/views/core.py +++ b/superset/views/core.py @@ -1794,6 +1794,7 @@ class Superset(BaseSupersetView): is_dim = config.get('is_dim', False) SqlaTable = ConnectorRegistry.sources['table'] TableColumn = SqlaTable.column_cls + SqlMetric = SqlaTable.metric_cls col = TableColumn( column_name=column_name, filterable=is_dim, @@ -1806,18 +1807,18 @@ class Superset(BaseSupersetView): agg = config.get('agg') if agg: if agg == 'count_distinct': - metrics.append(models.SqlMetric( + metrics.append(SqlMetric( metric_name="{agg}__{column_name}".format(**locals()), expression="COUNT(DISTINCT {column_name})" .format(**locals()), )) else: - metrics.append(models.SqlMetric( + metrics.append(SqlMetric( metric_name="{agg}__{column_name}".format(**locals()), expression="{agg}({column_name})".format(**locals()), )) if not metrics: - metrics.append(models.SqlMetric( + metrics.append(SqlMetric( metric_name="count".format(**locals()), expression="count(*)".format(**locals()), ))
Use connector registry for metrics (#<I>)
apache_incubator-superset
train
897444d761398226b5340819e2b2a780dbfabbe6
diff --git a/lang/en/admin.php b/lang/en/admin.php index <HASH>..<HASH> 100644 --- a/lang/en/admin.php +++ b/lang/en/admin.php @@ -1073,7 +1073,7 @@ $string['unbookmarkthispage'] = 'Unbookmark this page'; $string['unicoderequired'] = 'It is required that you store all your data in Unicode format (UTF-8). New installations must be performed into databases that have their default character set as Unicode. If you are upgrading, you should perform the UTF-8 migration process (see the Admin page).'; $string['uninstallplugin'] = 'Uninstall'; $string['unlockaccount'] = 'Unlock account'; -$string['unoconvwarning'] = 'The installed version of your unoconv is not supported, the required version to support assignment grading features is 0.7.'; +$string['unoconvwarning'] = 'The version of unoconv you have installed is not supported. Moodle\'s assignment grading feature requires version 0.7 or higher.'; $string['unsettheme'] = 'Unset theme'; $string['unsupported'] = 'Unsupported'; $string['unsupporteddbstorageengine'] = 'The database storage engine being used is no longer supported.'; diff --git a/mod/assign/feedback/editpdf/lang/en/assignfeedback_editpdf.php b/mod/assign/feedback/editpdf/lang/en/assignfeedback_editpdf.php index <HASH>..<HASH> 100644 --- a/mod/assign/feedback/editpdf/lang/en/assignfeedback_editpdf.php +++ b/mod/assign/feedback/editpdf/lang/en/assignfeedback_editpdf.php @@ -88,12 +88,12 @@ $string['test_doesnotexist'] = 'The ghostscript path points to a non-existent fi $string['test_empty'] = 'The ghostscript path is empty - please enter the correct path'; $string['test_unoconv'] = 'Test unoconv path'; $string['test_unoconvdoesnotexist'] = 'The unoconv path does not point to the unoconv program. Please review your path settings.'; -$string['test_unoconvdownload'] = 'Download converted pdf test file.'; +$string['test_unoconvdownload'] = 'Download the converted pdf test file.'; $string['test_unoconvisdir'] = 'The unoconv path points to a folder, please include the unoconv program in the path you specify'; -$string['test_unoconvnotestfile'] = 'The test DOC is missing'; -$string['test_unoconvnotexecutable'] = 'The unoconv points to a file that is not executable'; -$string['test_unoconvok'] = 'The unoconv path appears to properly configured.'; -$string['test_unoconvversionnotsupported'] = 'The minimum supported version for unoconv is 0.7'; +$string['test_unoconvnotestfile'] = 'The test document to be coverted into a PDF is missing'; +$string['test_unoconvnotexecutable'] = 'The unoconv path points to a file that is not executable'; +$string['test_unoconvok'] = 'The unoconv path appears to be properly configured.'; +$string['test_unoconvversionnotsupported'] = 'The version of unoconv you have installed is not supported. Moodle\'s assignment grading feature requires version 0.7 or higher.'; $string['toolbarbutton'] = '{$a->tool} {$a->shortcut}'; $string['tool'] = 'Tool'; $string['viewfeedbackonline'] = 'View annotated PDF...'; diff --git a/mod/assign/feedback/editpdf/testunoconv.php b/mod/assign/feedback/editpdf/testunoconv.php index <HASH>..<HASH> 100644 --- a/mod/assign/feedback/editpdf/testunoconv.php +++ b/mod/assign/feedback/editpdf/testunoconv.php @@ -51,19 +51,18 @@ if ($sendpdf) { $result = file_storage::test_unoconv_path(); switch ($result->status) { case file_storage::UNOCONVPATH_OK: - $msg = get_string('test_unoconvok', 'assignfeedback_editpdf'); - $msg .= html_writer::empty_tag('br'); + $msg = $OUTPUT->notification(get_string('test_unoconvok', 'assignfeedback_editpdf'), 'success'); $pdflink = new moodle_url($PAGE->url, array('sendpdf' => 1, 'sesskey' => sesskey())); $msg .= html_writer::link($pdflink, get_string('test_unoconvdownload', 'assignfeedback_editpdf')); $msg .= html_writer::empty_tag('br'); break; case file_storage::UNOCONVPATH_ERROR: - $msg = $result->message; + $msg = $OUTPUT->notification($result->message, 'warning'); break; default: - $msg = get_string("test_unoconv{$result->status}", 'assignfeedback_editpdf'); + $msg = $OUTPUT->notification(get_string("test_unoconv{$result->status}", 'assignfeedback_editpdf'), 'warning'); break; } $returl = new moodle_url('/admin/settings.php', array('section' => 'assignfeedback_editpdf'));
MDL-<I> mod_assign: Put messages into notifications. The unoconv test page was before just outputting text to page. Now it is wrapped in a nice notification. One of the warnings has been improved as well.
moodle_moodle
train
af69d29ee931c50b6398a3f536e54bc9341646da
diff --git a/pachyderm/fit/__init__.py b/pachyderm/fit/__init__.py index <HASH>..<HASH> 100644 --- a/pachyderm/fit/__init__.py +++ b/pachyderm/fit/__init__.py @@ -17,4 +17,4 @@ from .base import ( # noqa: F401 from .cost_function import ( # noqa: F401 BinnedChiSquared, BinnedLogLikelihood, ChiSquared, CostFunctionBase, LogLikelihood, SimultaneousFit ) -from .function import AddPDF, gaussian # noqa: F401 +from .function import AddPDF, extended_gaussian, gaussian # noqa: F401 diff --git a/pachyderm/fit/function.py b/pachyderm/fit/function.py index <HASH>..<HASH> 100644 --- a/pachyderm/fit/function.py +++ b/pachyderm/fit/function.py @@ -73,3 +73,20 @@ def gaussian(x: Union[np.ndarray, float], mean: float, sigma: float) -> Union[np Calculated gaussian value(s). """ return 1.0 / np.sqrt(2 * np.pi * np.square(sigma)) * np.exp(-1.0 / 2.0 * np.square((x - mean) / sigma)) + +def extended_gaussian(x: Union[np.ndarray, float], mean: float, sigma: float, amplitude: float) -> Union[np.ndarray, float]: + r""" Extended gaussian. + + .. math:: + + f = A / \sqrt{2 * \pi * \sigma^{2}} * \exp{-\frac{(x - \mu)^{2}}{(2 * \sigma^{2}}} + + Args: + x: Value(s) where the gaussian should be evaluated. + mean: Mean of the gaussian distribution. + sigma: Width of the gaussian distribution. + amplitude: Amplitude of the gaussian. + Returns: + Calculated gaussian value(s). + """ + return amplitude / np.sqrt(2 * np.pi * np.square(sigma)) * np.exp(-1.0 / 2.0 * np.square((x - mean) / sigma))
Add extended gaussian Just for convenience
raymondEhlers_pachyderm
train
c87ef02d487513e95be46af05dfc54a33d90dc37
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ Unreleased Changes ------------------ +* Issue - PageableResponse - Resolved an issue where Enumerable was not + correctly getting mixed into pageable responses. + + See [related GitHub issue #842](https://github.com/aws/aws-sdk-ruby/issues/842) + * Issue - Shared Credentials - Resolved an issue where the shared credentials provider would fail to parse profiles which contained an inline comment. diff --git a/aws-sdk-core/lib/aws-sdk-core/pageable_response.rb b/aws-sdk-core/lib/aws-sdk-core/pageable_response.rb index <HASH>..<HASH> 100644 --- a/aws-sdk-core/lib/aws-sdk-core/pageable_response.rb +++ b/aws-sdk-core/lib/aws-sdk-core/pageable_response.rb @@ -30,11 +30,9 @@ module Aws # module PageableResponse - def self.included(base) - base.send(:include, Enumerable) - end - def self.extended(base) + base.send(:extend, Enumerable) + base.send(:extend, SafeCount) base.instance_variable_set("@last_page", nil) base.instance_variable_set("@more_results", nil) end @@ -82,24 +80,6 @@ module Aws end alias each_page each - # @api private - def count - if respond_to?(:count) - data.count - else - raise NotImplementedError - end - end - - # @api private - def respond_to?(method_name, *args) - if method_name == :count - data.respond_to?(:count) - else - super - end - end - private # @param [Hash] params A hash of additional request params to @@ -136,5 +116,27 @@ module Aws end + module SafeCount + + # Enumerable#count is a dangerous method to expose on a pageable + # response as it will trigger potentially many API calls. This causes + # a response to respond to #count if-and-only-if the data defines count. + def count + if data.respond_to?(:count) + data.count + else + raise NoMethodError, "undefined method `count'" + end + end + + def respond_to?(method_name, *args) + if method_name == :count + data.respond_to?(:count) + else + false + end + end + + end end end diff --git a/aws-sdk-core/spec/aws/pageable_response_spec.rb b/aws-sdk-core/spec/aws/pageable_response_spec.rb index <HASH>..<HASH> 100644 --- a/aws-sdk-core/spec/aws/pageable_response_spec.rb +++ b/aws-sdk-core/spec/aws/pageable_response_spec.rb @@ -20,6 +20,10 @@ module Aws 'output_token' => 'NextToken', }} + it 'is Enumerable' do + expect(resp).to be_kind_of(Enumerable) + end + it 'returns false from last page if the paging token value is present' do resp.data = { 'next_token' => 'OFFSET' } expect(resp.last_page?).to be(false) @@ -177,7 +181,7 @@ module Aws page = pageable(resp, pager) expect { page.count - }.to raise_error(NotImplementedError) + }.to raise_error(NoMethodError) end it 'passes count from the raises not implemented error by default' do
Fixed a regression on PageableResponse. Enumerable was not correctly getting mixed into the pageable response objects. Fixes #<I>
aws_aws-sdk-ruby
train
4fae39c4ba546652d3e06f69e64b75861517245f
diff --git a/skyfield/earthlib.py b/skyfield/earthlib.py index <HASH>..<HASH> 100644 --- a/skyfield/earthlib.py +++ b/skyfield/earthlib.py @@ -27,7 +27,12 @@ def geocentric_position_and_velocity(topos, jd): x1, x2, eqeq, x3, x4 = earth_tilt(jd) gast = gmst + eqeq / 3600.0 - pos, vel = terra(topos, gast) + pos, vel = terra( + topos.latitude.radians, + topos.longitude.radians, + topos.elevation.m, + gast, + ) pos = einsum('ij...,j...->i...', jd.MT, pos) vel = einsum('ij...,j...->i...', jd.MT, vel) @@ -35,10 +40,12 @@ def geocentric_position_and_velocity(topos, jd): return pos, vel -def terra(topos, st): +def terra(latitude, longitude, elevation, st): """Compute the position and velocity of a terrestrial observer. - `topos` - `Topos` object describing a geographic position. + `latitude` - Latitude in radians. + `longitude` - Longitude in radians. + `elevation` - Elevation in meters. `st` - Array of sidereal times in floating-point hours. The return value is a tuple of two 3-vectors `(pos, vel)` in the @@ -47,19 +54,18 @@ def terra(topos, st): """ zero = zeros_like(st) - phi = topos.latitude.radians - sinphi = sin(phi) - cosphi = cos(phi) + sinphi = sin(latitude) + cosphi = cos(latitude) c = 1.0 / sqrt(cosphi * cosphi + sinphi * sinphi * one_minus_flattening_squared) s = one_minus_flattening_squared * c - ht = topos.elevation.m + ht = elevation ach = ERAD * c + ht ash = ERAD * s + ht # Compute local sidereal time factors at the observer's longitude. - stlocl = st * 15.0 * DEG2RAD + topos.longitude.radians + stlocl = st * 15.0 * DEG2RAD + longitude sinst = sin(stlocl) cosst = cos(stlocl)
Make terra() innocent of knowledge of Topos class
skyfielders_python-skyfield
train
638dec5027b06ef39be779763e0c352ff3c1a3ed
diff --git a/tests/unit/states/file_test.py b/tests/unit/states/file_test.py index <HASH>..<HASH> 100644 --- a/tests/unit/states/file_test.py +++ b/tests/unit/states/file_test.py @@ -317,7 +317,8 @@ class FileTestCase(TestCase): self.assertDictEqual(filestate.absent(name), ret) with patch.dict(filestate.__opts__, {'test': False}): - with patch.object(shutil, 'rmtree', mock_tree): + with patch.object(filestate.__salt__, + {'file.remove': mock_tree}): comt = ('Removed directory {0}'.format(name)) ret.update({'comment': comt, 'result': True, 'changes': {'removed': name}}) @@ -619,7 +620,8 @@ class FileTestCase(TestCase): True, True, True, False])): with patch.object(os.path, 'lexists', mock_t): - with patch.object(os.path, 'islink', mock_f): + with patch.object(filestate.__salt__, + {'file.is_link', mock_f}): with patch.object(os.path, 'isdir', mock_f): comt = ('File exists where the backup target' ' A should go') @@ -1280,15 +1282,12 @@ class FileTestCase(TestCase): with patch.object(os.path, 'lexists', mock_t): with patch.dict(filestate.__opts__, {'test': False}): - with patch.object(os.path, 'isfile', mock_f): - with patch.object(os.path, 'islink', - mock_io): - ret.update({'comment': comt1, - 'result': False}) - self.assertDictEqual(filestate.copy - (name, source, - preserve=True, - force=True), ret) + ret.update({'comment': comt1, + 'result': False}) + self.assertDictEqual(filestate.copy + (name, source, + preserve=True, + force=True), ret) with patch.object(os.path, 'isfile', mock_t): ret.update({'comment': comt2, @@ -1376,9 +1375,12 @@ class FileTestCase(TestCase): with patch.dict(filestate.__opts__, {'test': False}): comt = ('Failed to delete "{0}" in preparation for ' 'forced move'.format(name)) - ret.update({'comment': comt, 'result': False}) - self.assertDictEqual(filestate.rename(name, source, - force=True), ret) + with patch.object(filestate.__salt__, + {'file.remove', mock_f}, + MagicMock(side_effect=[IOError, True])): + ret.update({'comment': comt, 'result': False}) + self.assertDictEqual(filestate.rename(name, source, + force=True), ret) with patch.dict(filestate.__opts__, {'test': True}): comt = ('File "{0}" is set to be moved to "{1}"'
Fixed some tests... let's see if they're really are
saltstack_salt
train
a305ba813b460c3ef5fee7e8effcb9ded52baf04
diff --git a/lib/active_record/connection_adapters/oracle_enhanced_adapter.rb b/lib/active_record/connection_adapters/oracle_enhanced_adapter.rb index <HASH>..<HASH> 100644 --- a/lib/active_record/connection_adapters/oracle_enhanced_adapter.rb +++ b/lib/active_record/connection_adapters/oracle_enhanced_adapter.rb @@ -194,11 +194,11 @@ module ActiveRecord ## # :singleton-method: - # Specify default sequence start with value (by default 10000 if not explicitly set), e.g.: + # Specify default sequence start with value (by default 1 if not explicitly set), e.g.: # - # ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.default_sequence_start_value = 1 + # ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.default_sequence_start_value = 10000 cattr_accessor :default_sequence_start_value - self.default_sequence_start_value = 10000 + self.default_sequence_start_value = 1 class StatementPool < ConnectionAdapters::StatementPool private diff --git a/spec/active_record/connection_adapters/oracle_enhanced/schema_statements_spec.rb b/spec/active_record/connection_adapters/oracle_enhanced/schema_statements_spec.rb index <HASH>..<HASH> 100644 --- a/spec/active_record/connection_adapters/oracle_enhanced/schema_statements_spec.rb +++ b/spec/active_record/connection_adapters/oracle_enhanced/schema_statements_spec.rb @@ -113,24 +113,24 @@ describe "OracleEnhancedAdapter schema definition" do ActiveRecord::Base.clear_cache! end - it "should use default sequence start value 10000" do - expect(ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.default_sequence_start_value).to eq(10000) + it "should use default sequence start value 1" do + expect(ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.default_sequence_start_value).to eq(1) create_test_employees_table class ::TestEmployee < ActiveRecord::Base; end employee = TestEmployee.create! - expect(employee.id).to eq(10000) + expect(employee.id).to eq(1) end it "should use specified default sequence start value" do - ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.default_sequence_start_value = 1 + ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.default_sequence_start_value = 10000 create_test_employees_table class ::TestEmployee < ActiveRecord::Base; end employee = TestEmployee.create! - expect(employee.id).to eq(1) + expect(employee.id).to eq(10000) end it "should use sequence start value from table definition" do
Change `default_sequence_start_value` from <I> to 1 Refer #<I> for the background of this change
rsim_oracle-enhanced
train
d75fdbcca0e54e01ee49ea8b9b1b078fc0c69f4a
diff --git a/lib/Model.js b/lib/Model.js index <HASH>..<HASH> 100644 --- a/lib/Model.js +++ b/lib/Model.js @@ -69,7 +69,8 @@ function Model(options) { this._scheduler = options.scheduler || options._scheduler || new ImmediateScheduler(); this._source = options.source || options._source; this._request = options.request || options._request || new RequestQueue(this, this._scheduler); - this._router = options.router || options._router; + this._maxSize = options.maxSize || options._maxSize || Model.prototype._maxSize; + this._collectRatio = options.collectRatio || options._collectRatio || Model.prototype._collectRatio; if(options.boxed || options.hasOwnProperty("_boxed")) { this._boxed = options.boxed || options._boxed; @@ -385,7 +386,7 @@ Model.prototype.materialize = function materialize() { return this.clone({ _materialized: true }); }; -Model.prototype.dematerialize = function materialize() { +Model.prototype.dematerialize = function dematerialize() { return this.clone({ _materialized: "delete" }); }; diff --git a/lib/get/util/isMaterialzed.js b/lib/get/util/isMaterialzed.js index <HASH>..<HASH> 100644 --- a/lib/get/util/isMaterialzed.js +++ b/lib/get/util/isMaterialzed.js @@ -1,3 +1,3 @@ module.exports = function isMaterialized(model) { - return model._materialized && !(model._router || model._source); + return model._materialized && !model._source; };
Adds back in maxSize and collectRatio to Model constructor. Removes legacy router references.
Netflix_falcor
train
24e9365fe0cc126974db88da25c5b532460d55bd
diff --git a/django_object_view_tracking/models.py b/django_object_view_tracking/models.py index <HASH>..<HASH> 100644 --- a/django_object_view_tracking/models.py +++ b/django_object_view_tracking/models.py @@ -38,9 +38,8 @@ class ObjectTracker(object): # The last date that we say "everything before this has been seen" last_date = self.session[self.key_name].get('_date') ct = ContentType.objects.get_for_model(model_class).id - if ct not in session: - if not last_date or not date_value: - return False + if ct not in session or not last_date or not date_value: + return False else: last_date = session[ct].get(pk, last_date) return last_date > date_value
reworked viewed logic again
dcramer_objtrack
train
da2a124f519121d2da1b3be066395eae116b9e10
diff --git a/src/phpDocumentor/Application.php b/src/phpDocumentor/Application.php index <HASH>..<HASH> 100644 --- a/src/phpDocumentor/Application.php +++ b/src/phpDocumentor/Application.php @@ -27,6 +27,8 @@ use RuntimeException; * Application class for phpDocumentor. * * Can be used as bootstrap when the run method is not invoked. + * + * @codeCoverageIgnore too many side-effects and system calls to properly test */ class Application extends Cilex { @@ -78,8 +80,6 @@ class Application extends Cilex $this->setTimezone(); ini_set('memory_limit', '-1'); - // this code cannot be tested because we cannot control the system settings in unit tests - // @codeCoverageIgnoreStart if (extension_loaded('Zend OPcache') && ini_get('opcache.enable') && ini_get('opcache.enable_cli')) { if (ini_get('opcache.save_comments')) { ini_set('opcache.load_comments', '1'); @@ -91,8 +91,6 @@ class Application extends Cilex if (extension_loaded('Zend Optimizer+') && ini_get('zend_optimizerplus.save_comments') === 0) { throw new RuntimeException('Please enable zend_optimizerplus.save_comments in php.ini.'); } - - // @codeCoverageIgnoreEnd } /** @@ -103,8 +101,6 @@ class Application extends Cilex * * @link http://php.net/manual/en/function.date-default-timezone-get.php for more information how PHP determines the * default timezone. - * - * @codeCoverageIgnore this method is very hard, if not impossible, to unit test and not critical. */ protected function setTimezone(): void { diff --git a/src/phpDocumentor/AutoloaderLocator.php b/src/phpDocumentor/AutoloaderLocator.php index <HASH>..<HASH> 100644 --- a/src/phpDocumentor/AutoloaderLocator.php +++ b/src/phpDocumentor/AutoloaderLocator.php @@ -17,6 +17,9 @@ namespace phpDocumentor; final class AutoloaderLocator { + /** + * @codeCoverageIgnore cannot test without side-effects + */ public static function autoload() { return require static::findVendorPath(). '/autoload.php'; diff --git a/src/phpDocumentor/Kernel.php b/src/phpDocumentor/Kernel.php index <HASH>..<HASH> 100644 --- a/src/phpDocumentor/Kernel.php +++ b/src/phpDocumentor/Kernel.php @@ -22,6 +22,9 @@ use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Kernel as BaseKernel; use Symfony\Component\Routing\RouteCollectionBuilder; +/** + * @codeCoverageIgnore Kernels do not need to be covered; mostly configuration anyway + */ class Kernel extends BaseKernel { use MicroKernelTrait;
Code coverage ignore a couple of files because they are impossible to test
phpDocumentor_phpDocumentor2
train
ac1f715200bf21532a142b0f9fac6b0458cf59c1
diff --git a/lib/util.js b/lib/util.js index <HASH>..<HASH> 100644 --- a/lib/util.js +++ b/lib/util.js @@ -742,20 +742,6 @@ var Util = function (settings) { this.authenticate = this.Authenticate; /* - RetrieveMultiple public and private methods - */ - this.RetrieveMultiple = function (options, cb) { - this.executePost(options, "RetrieveMultiple", apiRetrieveMultipleMessage, serializer.toXmlRetrieveMultiple(options), cb); - }; - - /* - Retrieve public and private methods - */ - this.Retrieve = function (options, cb) { - this.executePost(options, "Retrieve", apiRetrieveMessage, serializer.toXmlRetrieve(options), cb); - }; - - /* Create public and private methods */ this.Create = function (options, cb) {
Removing obsolete implementations of Retrieve and RetrieveMultiple
Innofactor_xrm-api
train
7c7d9c144b10573acb06be17483ef0a9837d2f76
diff --git a/web/concrete/blocks/dashboard_site_activity/controller.php b/web/concrete/blocks/dashboard_site_activity/controller.php index <HASH>..<HASH> 100644 --- a/web/concrete/blocks/dashboard_site_activity/controller.php +++ b/web/concrete/blocks/dashboard_site_activity/controller.php @@ -42,7 +42,8 @@ class Controller extends BlockController } } $this->set('totalFormSubmissions', FormBlockStatistics::getTotalSubmissions()); - $this->set('totalFormSubmissionsToday', FormBlockStatistics::getTotalSubmissions(date('Y-m-d'))); + $now = new \DateTime('now', $dh->getTimezone('user')); + $this->set('totalFormSubmissionsToday', FormBlockStatistics::getTotalSubmissions($now->format('Y-m-d'))); } } diff --git a/web/concrete/blocks/form/statistics.php b/web/concrete/blocks/form/statistics.php index <HASH>..<HASH> 100644 --- a/web/concrete/blocks/form/statistics.php +++ b/web/concrete/blocks/form/statistics.php @@ -2,17 +2,57 @@ namespace Concrete\Block\Form; use Loader; +use Core; class Statistics { - public static function getTotalSubmissions($date = null) + /** + * Gets the total number of submissions + * @param string $date Set to a specific day (eg '2014-09-14') to retrieve the submissions in that day. + * @param string $dateTimezone The timezone of the $date parameter (acceptable values: 'user', 'system', 'app' or any valid PHP timezone identifier) + * @return int + */ + public static function getTotalSubmissions($date = null, $dateTimezone = 'user') { - $db = Loader::db(); - if ($date != null) { - return $db->GetOne("select count(asID) from btFormAnswerSet where DATE_FORMAT(created, '%Y-%m-%d') = ?", array($date)); + if ($date) { + return static::getTotalSubmissionsBetween("$date 00:00:00", "$date 23:59:59", $dateTimezone); } else { - return $db->GetOne("select count(asID) from btFormAnswerSet"); + return static::getTotalSubmissionsBetween(); + } + } + /** + * Gets the total number of submissions in specific date/time ranges + * @param string|int|\DateTime $fromDate The start of the period (if empty: from ever). Inclusive. Example: '2014-09-14 08:00:00'. + * @param string|int|\DateTime $toDate The end of the period (if empty: for ever). Inclusive. Example: '2014-09-14 08:00:00'. + * @param string $dateTimezone The timezone of the $dateFrom and $dateTo parameter (acceptable values: 'user', 'system', 'app' or any valid PHP timezone identifier) + * @return number + */ + public static function getTotalSubmissionsBetween($fromDate = null, $toDate = null, $datesTimezone = 'user') + { + $dh = Core::make('helper/date'); + /* @var $dh \Concrete\Core\Localization\Service\Date */ + if ($fromDate) { + $fromDate = $dh->toDB($fromDate, $datesTimezone); } + if ($toDate) { + $toDate = $dh->toDB($toDate, $datesTimezone); + } + $where = ''; + $q = array(); + if ($fromDate && $toDate) { + $where = ' where created between ? and ?'; + $q[] = $fromDate; + $q[] = $toDate; + } elseif ($fromDate) { + $where = ' where created >= ?'; + $q[] = $fromDate; + } elseif ($toDate) { + $where = ' where created <= ?'; + $q[] = $toDate; + } + $count = Loader::db()->GetOne('select count(asID) from btFormAnswerSet' . $where, $q); + + return empty($count) ? 0 : intval($count); } public static function loadSurveys($MiniSurvey)
Today form submissions for the users' timezone Former-commit-id: ea<I>dbcc8e<I>ff3ed0efb<I>c<I>
concrete5_concrete5
train
16fc7c3a157d22df0829da48dc1c2d85f1923699
diff --git a/src/abcTransaction.js b/src/abcTransaction.js index <HASH>..<HASH> 100644 --- a/src/abcTransaction.js +++ b/src/abcTransaction.js @@ -1,7 +1,6 @@ export class ABCTransaction { - constructor ({ rawTx, wallet, currencyCode, metadata, txid, date, blockHeight, nativeAmount, providerFee, networkFee, runningBalance, signedTx, ourReceiveAddresses, otherParams }) { + constructor ({ wallet, currencyCode, metadata, txid, date, blockHeight, nativeAmount, providerFee, networkFee, runningBalance, signedTx, ourReceiveAddresses, otherParams }) { this.wallet = wallet - this.rawTx = rawTx this.currencyCode = currencyCode this.metadata = metadata this.txid = txid
moved rawTX into other params
EdgeApp_edge-currency-bitcoin
train
6aefc9c5cc151dc6d496046f9c5b1bab1e9e2258
diff --git a/cassandra/cqlengine/query.py b/cassandra/cqlengine/query.py index <HASH>..<HASH> 100644 --- a/cassandra/cqlengine/query.py +++ b/cassandra/cqlengine/query.py @@ -664,12 +664,20 @@ class AbstractQuerySet(object): return self.filter(*args, **kwargs).get() self._execute_query() - if self.count() == 0: + + # Check that the resultset only contains one element, avoiding sending a COUNT query + try: + self[1] + raise self.model.MultipleObjectsReturned('Multiple objects found') + except IndexError: + pass + + try: + obj = self[0] + except IndexError: raise self.model.DoesNotExist - elif self.count() > 1: - raise self.model.MultipleObjectsReturned('{0} objects found'.format(self.count())) - else: - return self[0] + + return obj def _get_ordering_condition(self, colname): order_type = 'DESC' if colname.startswith('-') else 'ASC'
PYTHON-<I>: Avoid sending a COUNT query with QuerySet.get()
datastax_python-driver
train
eb2fc8a28bcdb1b441a74b4bdc44020089643c84
diff --git a/jest.config.js b/jest.config.js index <HASH>..<HASH> 100644 --- a/jest.config.js +++ b/jest.config.js @@ -4,7 +4,7 @@ module.exports = { transform: { '\\.ts$': '<rootDir>/dist/index.js', }, - testMatch: ['<rootDir>/src/**/?(*.)+(spec|test).ts?(x)'], + testMatch: ['<rootDir>/src/**/*.spec.ts'], collectCoverageFrom: [ '<rootDir>/src/**/*.ts', '!<rootDir>/src/**/*.d.ts',
fix: test path for windows (attempt 2)
kulshekhar_ts-jest
train
9b90d2c22888665f1c27bd14c1a0b1d537006dfc
diff --git a/src/Views/discussion.blade.php b/src/Views/discussion.blade.php index <HASH>..<HASH> 100644 --- a/src/Views/discussion.blade.php +++ b/src/Views/discussion.blade.php @@ -72,10 +72,10 @@ <?php $db_field = Config::get('chatter.user.avatar_image_database_field'); ?> <!-- If the user db field contains http:// or https:// we don't need to use the relative path to the image assets --> - @if( (substr($discussion->user->{$db_field}, 0, 7) == 'http://') || (substr($discussion->user->{$db_field}, 0, 8) == 'https://') ) - <img src="{{ $discussion->user->{$db_field} }}"> + @if( (substr($post->user->{$db_field}, 0, 7) == 'http://') || (substr($post->user->{$db_field}, 0, 8) == 'https://') ) + <img src="{{ $post->user->{$db_field} }}"> @else - <img src="{{ Config::get('chatter.user.relative_url_to_image_assets') . $discussion->user->{$db_field} }}"> + <img src="{{ Config::get('chatter.user.relative_url_to_image_assets') . $post->user->{$db_field} }}"> @endif @else @@ -105,14 +105,14 @@ <div class="chatter_avatar"> @if(Config::get('chatter.user.avatar_image_database_field')) - + <?php $db_field = Config::get('chatter.user.avatar_image_database_field'); ?> <!-- If the user db field contains http:// or https:// we don't need to use the relative path to the image assets --> - @if( (substr($discussion->user->{$db_field}, 0, 7) == 'http://') || (substr($discussion->user->{$db_field}, 0, 8) == 'https://') ) - <img src="{{ $discussion->user->{$db_field} }}"> + @if( (substr(Auth::user()->{$db_field}, 0, 7) == 'http://') || (substr(Auth::user()->{$db_field}, 0, 8) == 'https://') ) + <img src="{{ Auth::user()->{$db_field} }}"> @else - <img src="{{ Config::get('chatter.user.relative_url_to_image_assets') . $discussion->user->{$db_field} }}"> + <img src="{{ Config::get('chatter.user.relative_url_to_image_assets') . Auth::user()->{$db_field} }}"> @endif @else
Adding correct avatars for discussion page
thedevdojo_chatter
train
a0beb0a2815e866070f7521b3b15dc9f00141371
diff --git a/src/template/lombok/ast/template/TemplateProcessor.java b/src/template/lombok/ast/template/TemplateProcessor.java index <HASH>..<HASH> 100644 --- a/src/template/lombok/ast/template/TemplateProcessor.java +++ b/src/template/lombok/ast/template/TemplateProcessor.java @@ -382,9 +382,9 @@ public class TemplateProcessor extends AbstractProcessor { } else if (field.isList()) { out.write("\t\tfor (Node n : this."); out.write(field.getName()); - out.write(") {\n\t\t\tresult."); - out.write(field.getName()); - out.write("Accessor.addToEndRaw(n == null ? null : n.copy());\n\t\t}\n"); + out.write(") {\n\t\t\tresult.raw"); + out.write(field.titleCasedName()); + out.write("().addToEnd(n == null ? null : n.copy());\n\t\t}\n"); } else { out.write("\t\tif (this."); out.write(field.getName());
Updated Template Processor to the new list accessor model.
rzwitserloot_lombok.ast
train
3f4b945026fa2452afa067899fc72714966aeabd
diff --git a/fileformat/src/main/java/org/zuinnote/hadoop/office/format/mapred/AbstractSpreadSheetDocumentFileOutputFormat.java b/fileformat/src/main/java/org/zuinnote/hadoop/office/format/mapred/AbstractSpreadSheetDocumentFileOutputFormat.java index <HASH>..<HASH> 100644 --- a/fileformat/src/main/java/org/zuinnote/hadoop/office/format/mapred/AbstractSpreadSheetDocumentFileOutputFormat.java +++ b/fileformat/src/main/java/org/zuinnote/hadoop/office/format/mapred/AbstractSpreadSheetDocumentFileOutputFormat.java @@ -18,21 +18,16 @@ package org.zuinnote.hadoop.office.format.mapred; import java.io.IOException; -import java.io.DataOutputStream; - -import org.apache.hadoop.fs.FileSystem; -import org.apache.hadoop.fs.Path; -import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.io.NullWritable; -import org.apache.hadoop.io.compress.CompressionCodec; -import org.apache.hadoop.io.compress.GzipCodec; import org.apache.hadoop.mapred.FileOutputFormat; import org.apache.hadoop.mapred.JobConf; +import org.apache.hadoop.util.Progressable; + +import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.mapred.RecordWriter; -import org.apache.hadoop.util.ReflectionUtils; -import org.apache.hadoop.util.Progressable; + import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; @@ -49,36 +44,5 @@ private static final Log LOG = LogFactory.getLog(AbstractSpreadSheetDocumentFile public abstract RecordWriter<NullWritable,SpreadSheetCellDAO> getRecordWriter(FileSystem ignored, JobConf conf, String name, Progressable progress) throws IOException; -/* -* Creates for the file to be written and outputstream and takes - depending on the configuration - take of compression. Set for compression the following options: -* mapreduce.output.fileoutputformat.compress true/false -* mapreduce.output.fileoutputformat.compress.codec java class of compression codec -* -* Note that some formats may use already internal compression so that additional compression does not lead to many benefits -* -* @param conf Configuration of Job -* @param file file to be written -* -* @return outputstream of the file -* -*/ - -public DataOutputStream getDataOutputStream(JobConf conf, Path file, Progressable progress) throws IOException { -if (getCompressOutput(conf)==false) { // uncompressed - FileSystem fs = file.getFileSystem(conf); - FSDataOutputStream fileOut = fs.create(file, progress); - return fileOut; -} else { // compressed (note partially adapted from TextOutputFormat) - Class<? extends CompressionCodec> codecClass = getOutputCompressorClass(conf, GzipCodec.class); // Gzip is default if no other has been selected - // create the named codec - CompressionCodec codec = ReflectionUtils.newInstance(codecClass, conf); - // provide proper file extension - Path compressedFile = file.suffix(codec.getDefaultExtension()); - // build the filename including the extension - FileSystem fs = compressedFile.getFileSystem(conf); - FSDataOutputStream realFileOut = fs.create(compressedFile, progress); - return new DataOutputStream(codec.createOutputStream(realFileOut)); -} -} }
Refactored to prepare for new mapreduce.* api
ZuInnoTe_hadoopoffice
train
76f8a1d0241e8a4e42091a7bfba3791afd468c5e
diff --git a/rqalpha/mod/rqalpha_mod_sys_accounts/position_model.py b/rqalpha/mod/rqalpha_mod_sys_accounts/position_model.py index <HASH>..<HASH> 100644 --- a/rqalpha/mod/rqalpha_mod_sys_accounts/position_model.py +++ b/rqalpha/mod/rqalpha_mod_sys_accounts/position_model.py @@ -36,9 +36,9 @@ def _int_to_date(d): class StockPosition(BasePosition): - __repr_properties__ = [ - "order_book_id", "direction", "market_value" - ] + __repr_properties__ = ( + "order_book_id", "direction", "quantity", "market_value", "trading_pnl", "position_pnl" + ) dividend_reinvestment = False cash_return_by_stock_delisted = True @@ -223,6 +223,10 @@ class StockPosition(BasePosition): class FuturePosition(BasePosition): + __repr_properties__ = ( + "order_book_id", "direction", "old_quantity", "quantity", "margin", "market_value", "trading_pnl", "position_pnl" + ) + enable_position_validator = True old_quantity = property(lambda self: self._old_quantity)
update repr of StockPosition and FuturePosition
ricequant_rqalpha
train
693f71f8bec38394f848bed7114cb6ff8aff0bad
diff --git a/package/domino/hand.py b/package/domino/hand.py index <HASH>..<HASH> 100644 --- a/package/domino/hand.py +++ b/package/domino/hand.py @@ -1,6 +1,7 @@ +import collections import domino -class Hand: +class Hand(collections.abc.Sequence): ''' Python class for objects that represent a hand of dominoes. @@ -40,11 +41,8 @@ class Hand: raise domino.NoSuchDominoException('Cannot make move -' ' {} is not in hand!'.format(d)) - def __contains__(self, d): - return d in self._dominoes - - def __iter__(self): - return iter(self._dominoes) + def __getitem__(self, i): + return self._dominoes[i] def __len__(self): return len(self._dominoes) diff --git a/package/tests/test_hand.py b/package/tests/test_hand.py index <HASH>..<HASH> 100644 --- a/package/tests/test_hand.py +++ b/package/tests/test_hand.py @@ -22,6 +22,15 @@ class TestHand(unittest.TestCase): self.assertTrue(d1 in h) self.assertFalse(d2 in h) + def test_getitem(self): + d1 = domino.Domino(1, 2) + d2 = domino.Domino(1, 3) + + h = domino.Hand([d1, d2]) + + self.assertEqual(h[0], d1) + self.assertEqual(h[1], d2) + def test_iter(self): h = domino.Hand([])
implementing Hand as a subclass of Sequence
abw333_dominoes
train
a12c08d15ec10df699fd7003ac9bf002a3dd15f3
diff --git a/src/resolver/value.js b/src/resolver/value.js index <HASH>..<HASH> 100644 --- a/src/resolver/value.js +++ b/src/resolver/value.js @@ -53,6 +53,7 @@ export default class Value extends Node { for(const v of valueEncounter._matches) { const matchCopy = match.copy(); matchCopy.data.values[this.id] = v.value; + matchCopy.scoreData.score += 0.9 * v.score; results.push(matchCopy); } }); @@ -66,7 +67,7 @@ export default class Value extends Node { ) return Promise.resolve(); valueEncounter._adjust(currentIndex, idx); - return encounter.branchWithOnMatch(onMatch, () => encounter.next(len * 0.9, len)) + return encounter.branchWithOnMatch(onMatch, () => encounter.next(0, len)) .then(() => { // If request to only match to keep if(this.options.onlySingle && results.length > 0) return; @@ -113,7 +114,7 @@ class ValueEncounter { return this.tokens.raw(); } - match(value, score=undefined) { + match(value, score=1) { if(! this._encounter.partial && this._matches.length >= 1) { throw new Error('Multiple matches are only supported when in partial mode'); }
feat(values): Custom values can now indicate their custom score
aholstenson_ecolect-js
train
de5d7ba7d0125ceef7b0774496079603acc20db4
diff --git a/zarr/storage.py b/zarr/storage.py index <HASH>..<HASH> 100644 --- a/zarr/storage.py +++ b/zarr/storage.py @@ -743,7 +743,7 @@ class DirectoryStore(MutableMapping): Parameters ---------- - fn: str + fn : str Filepath to open and read from. Notes @@ -759,10 +759,9 @@ class DirectoryStore(MutableMapping): Parameters ---------- - a: array-like + a : array-like Data to write into the file. - - fn: str + fn : str Filepath to open and write to. Notes
Numpydoc consistency. (#<I>) Numpydoc expect space on each side of the colon, on it may mis-parse what this actually means.
zarr-developers_zarr
train
de7d310ee79618582a81cdea2a208248284c6223
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -2,14 +2,16 @@ from __future__ import absolute_import from setuptools import setup, Extension from setuptools.command.build_ext import build_ext as _build_ext from distutils.errors import CompileError +from Cython.Compiler.Errors import CompileError as CythonCompileError from warnings import warn +import os try: from Cython.Distutils import build_ext as _build_ext except ImportError: use_cython = False else: - use_cython = True + use_cython = os.getenv('USE_CYTHON', False) class build_ext(_build_ext): # see http://stackoverflow.com/q/19919905 for explanation @@ -24,17 +26,20 @@ class build_ext(_build_ext): try: _build_ext.run(self) except CompileError: - warn('Failed to build optional extension modules') + warn('Failed to compile optional extension modules') + +extensions = [ + Extension( + 'autograd.numpy.linalg_extra', ['autograd/numpy/linalg_extra.c'], + extra_compile_args=['-w','-Ofast']), +] if use_cython: from Cython.Build import cythonize - extensions = cythonize('**/*.pyx') -else: - extensions = [ - Extension( - 'autograd.numpy.linalg_extra', ['autograd/numpy/linalg_extra.c'], - extra_compile_args=['-w','-Ofast']), - ] + try: + extensions = cythonize('**/*.pyx') + except CythonCompileError: + warn('Failed to generate extension module code from Cython file') setup( name='autograd',
try/except around cythonize, only use cython if USE_CYTHON env var is set
HIPS_autograd
train
fe3380a7cec08b9b7365121b5bcd9b59e2fe838e
diff --git a/aliyun/log/logclient.py b/aliyun/log/logclient.py index <HASH>..<HASH> 100755 --- a/aliyun/log/logclient.py +++ b/aliyun/log/logclient.py @@ -1135,7 +1135,8 @@ class LogClient(object): preserve_storage=False, encrypt_conf=None, telemetry_type='', - hot_ttl=-1 + hot_ttl=-1, + mode = None ): """ create log store Unsuccessful operation will cause an LogException. @@ -1182,6 +1183,9 @@ class LogClient(object): :type telemetry_type: string :param telemetry_type: the Telemetry type + :type mode: string + :param mode: type of logstore, can be choose between lite and standard, default value standard + :return: CreateLogStoreResponse :raise: LogException @@ -1205,6 +1209,8 @@ class LogClient(object): body['hot_ttl'] = hot_ttl if encrypt_conf != None: body["encrypt_conf"] = encrypt_conf + if mode != None: + body["mode"] = mode body_str = six.b(json.dumps(body)) @@ -1271,7 +1277,8 @@ class LogClient(object): max_split_shard=None, preserve_storage=None, encrypt_conf=None, - hot_ttl=-1 + hot_ttl=-1, + mode = None ): """ update the logstore meta info @@ -1320,6 +1327,9 @@ class LogClient(object): + } + } + :type mode: string + :param mode: type of logstore, can be choose between lite and standard, default value standard + :return: UpdateLogStoreResponse :raise: LogException @@ -1360,6 +1370,8 @@ class LogClient(object): body['hot_ttl'] = hot_ttl if encrypt_conf != None: body["encrypt_conf"] = encrypt_conf + if mode != None: + body['mode'] = mode body_str = six.b(json.dumps(body)) try: (resp, header) = self._send("PUT", project_name, body_str, resource, params, headers) diff --git a/aliyun/log/logstore_config_response.py b/aliyun/log/logstore_config_response.py index <HASH>..<HASH> 100755 --- a/aliyun/log/logstore_config_response.py +++ b/aliyun/log/logstore_config_response.py @@ -62,11 +62,14 @@ class GetLogStoreResponse(LogResponse): self.max_split_shard = int(resp["maxSplitShard"]) self.preserve_storage = self.ttl >= 3650 self.encrypt_conf = None + self.mode = None self.hot_ttl=-1; if 'hot_ttl' in resp: self.hot_ttl= int(resp['hot_ttl']) if 'encrypt_conf' in resp: self.encrypt_conf = resp["encrypt_conf"] + if 'mode' in resp: + self.mode = resp["mode"] def get_shard_count(self): """ @@ -112,6 +115,8 @@ class GetLogStoreResponse(LogResponse): print('ttl:', str(self.ttl)) if self.encrypt_conf != None: print('encrypt_conf:', str(self.encrypt_conf)) + if hasattr(self, 'mode') and self.mode != None: + print('mode:', str(self.mode)) class UpdateLogStoreResponse(LogResponse):
support logstore lite (#<I>)
aliyun_aliyun-log-python-sdk
train
842b30e2ca943222eba36026c85c6f7b3906eae1
diff --git a/core/src/main/java/com/google/bitcoin/core/Transaction.java b/core/src/main/java/com/google/bitcoin/core/Transaction.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/google/bitcoin/core/Transaction.java +++ b/core/src/main/java/com/google/bitcoin/core/Transaction.java @@ -760,6 +760,19 @@ public class Transaction extends ChildMessage implements Serializable { ECKey[] signingKeys = new ECKey[inputs.size()]; for (int i = 0; i < inputs.size(); i++) { TransactionInput input = inputs.get(i); + // We don't have the connected output, we assume it was signed already and move on + if (input.getOutpoint().getConnectedOutput() == null) { + log.warn("Missing connected output, assuming input {} is already signed.", i); + continue; + } + try { + // We assume if its already signed, its hopefully got a SIGHASH type that will not invalidate when + // we sign missing pieces (to check this would require either assuming any signatures are signing + // standard output types or a way to get processed signatures out of script execution) + input.getScriptSig().correctlySpends(this, i, input.getOutpoint().getConnectedOutput().getScriptPubKey(), true); + log.warn("Input {} already correctly spends output, assuming SIGHASH type used will be safe and skipping signing.", i); + continue; + } catch (ScriptException e) {} if (input.getScriptBytes().length != 0) log.warn("Re-signing an already signed transaction! Be sure this is what you want."); // Find the signing key we'll need to use. @@ -786,6 +799,8 @@ public class Transaction extends ChildMessage implements Serializable { // to the address and then checks the signature. // 2) For pay-to-key outputs: just a signature. for (int i = 0; i < inputs.size(); i++) { + if (signatures[i] == null) + continue; TransactionInput input = inputs.get(i); Script scriptPubKey = input.getOutpoint().getConnectedOutput().getScriptPubKey(); if (scriptPubKey.isSentToAddress()) {
Add basic support for existing inputs in Transaction.signInputs
bitcoinj_bitcoinj
train
5acd4ce099caabefa6e7e6d705b1bab44f16db71
diff --git a/BaseCommands.py b/BaseCommands.py index <HASH>..<HASH> 100644 --- a/BaseCommands.py +++ b/BaseCommands.py @@ -16,6 +16,7 @@ class BaseCommands(object): self.SleepTime = .1 self.SEEK = 0 self.Last = "" + self.ResultsLast = "" self.TimeOut = 3600 @@ -36,7 +37,8 @@ class BaseCommands(object): while Condition: if len(self.lens) > 1000: self.results = set() - self.lens = [] + self.lens = self.lens[-1:] + self.results.add(self.ResultsLast) if time() > deadline: process.terminate() yield {'Last':'exec command timeout.'} @@ -67,6 +69,7 @@ class BaseCommands(object): newres = newres[-2] yield {'execoutput':newres} self.Last = newres + self.ResultsLast = res self.results.add(res) self.lens.append(len(res.split("\n")))
Update BaseCommands.py
zhuangchaoxi_subcommands
train
520d17c85eef2d5e4de666cd4c39a85dbb3fb6c5
diff --git a/lib/ansible_tower_client/base_model.rb b/lib/ansible_tower_client/base_model.rb index <HASH>..<HASH> 100644 --- a/lib/ansible_tower_client/base_model.rb +++ b/lib/ansible_tower_client/base_model.rb @@ -37,11 +37,17 @@ module AnsibleTowerClient super(raw_hash) end - def self.create(api, attributes) + def self.create!(api, attributes) response = api.post("#{endpoint}/", attributes).body new(api, JSON.parse(response)) end + def self.create(*args) + create!(*args) + rescue AnsibleTowerClient::Error # Any Errors from the API should already be logged + false + end + def hashify(attribute) YAML.safe_load(send(attribute)) end
Change create to create! to be more like ActiveRecord::Base
ansible_ansible_tower_client_ruby
train
d46dbace591ff60eb5bf38b210490a10967ea70d
diff --git a/extensions/mongodb/Collection.php b/extensions/mongodb/Collection.php index <HASH>..<HASH> 100644 --- a/extensions/mongodb/Collection.php +++ b/extensions/mongodb/Collection.php @@ -772,6 +772,7 @@ class Collection extends Object protected function normalizeConditionKeyword($key) { static $map = [ + 'AND' => '$and', 'OR' => '$or', 'IN' => '$in', 'NOT IN' => '$nin', @@ -898,13 +899,13 @@ class Collection extends Object */ public function buildAndCondition($operator, $operands) { - $result = []; + $operator = $this->normalizeConditionKeyword($operator); + $parts = []; foreach ($operands as $operand) { - $condition = $this->buildCondition($operand); - $result = array_merge_recursive($result, $condition); + $parts[] = $this->buildCondition($operand); } - return $result; + return [$operator => $parts]; } /**
Changes mongodb build and condition, fixes #<I>
yiisoft_yii-core
train
98fda672a69ff9eb45b8764ec5cf5c316e10135c
diff --git a/activemodel/lib/active_model/secure_password.rb b/activemodel/lib/active_model/secure_password.rb index <HASH>..<HASH> 100644 --- a/activemodel/lib/active_model/secure_password.rb +++ b/activemodel/lib/active_model/secure_password.rb @@ -117,7 +117,7 @@ module ActiveModel # user.authenticate_password('notright') # => false # user.authenticate_password('mUc3m00RsqyRe') # => user define_method("authenticate_#{attribute}") do |unencrypted_password| - attribute_digest = send("#{attribute}_digest") + attribute_digest = public_send("#{attribute}_digest") BCrypt::Password.new(attribute_digest).is_password?(unencrypted_password) && self end
*_digest is defined as a public method
rails_rails
train
cf1cc735548d399199623e13fa003ca91be67946
diff --git a/HISTORY.rst b/HISTORY.rst index <HASH>..<HASH> 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -3,6 +3,17 @@ Release History --------------- +1.7.1 (2018-08-06) ++++++++++++++++++++ + +**Improvements** + +- + +**Bug Fixes** + +- async renamed to _async in betting endpoint for py3.7 + 1.7.0 (2018-07-23) +++++++++++++++++++ diff --git a/betfairlightweight/__init__.py b/betfairlightweight/__init__.py index <HASH>..<HASH> 100644 --- a/betfairlightweight/__init__.py +++ b/betfairlightweight/__init__.py @@ -6,7 +6,7 @@ from .streaming import StreamListener from . import filters __title__ = 'betfairlightweight' -__version__ = '1.7.0' +__version__ = '1.7.1b' __author__ = 'Liam Pauling' # Set default logging handler to avoid "No handler found" warnings. diff --git a/betfairlightweight/endpoints/betting.py b/betfairlightweight/endpoints/betting.py index <HASH>..<HASH> 100644 --- a/betfairlightweight/endpoints/betting.py +++ b/betfairlightweight/endpoints/betting.py @@ -274,7 +274,7 @@ class Betting(BaseEndpoint): return self.process_response(response, resources.MarketProfitLoss, elapsed_time, lightweight) def place_orders(self, market_id, instructions, customer_ref=None, market_version=None, - customer_strategy_ref=None, async=None, session=None, lightweight=None): + customer_strategy_ref=None, _async=None, session=None, lightweight=None): """ Place new orders into market. @@ -286,7 +286,7 @@ class Betting(BaseEndpoint): version of the market the orders should be placed on, e.g. "{'version': 123456}" :param str customer_strategy_ref: An optional reference customers can use to specify which strategy has sent the order - :param bool async: An optional flag (not setting equates to false) which specifies if + :param bool _async: An optional flag (not setting equates to false) which specifies if the orders should be placed asynchronously :param requests.session session: Requests session object :param bool lightweight: If True will return dict not a resource @@ -336,7 +336,7 @@ class Betting(BaseEndpoint): return self.process_response(response, resources.UpdateOrders, elapsed_time, lightweight) def replace_orders(self, market_id, instructions, customer_ref=None, market_version=None, - async=None, session=None, lightweight=None): + _async=None, session=None, lightweight=None): """ This operation is logically a bulk cancel followed by a bulk place. The cancel is completed first then the new orders are placed. @@ -348,7 +348,7 @@ class Betting(BaseEndpoint): string (up to 32 chars) that is used to de-dupe mistaken re-submissions :param dict market_version: Optional parameter allowing the client to specify which version of the market the orders should be placed on, e.g. "{'version': 123456}" - :param str async: An optional flag (not setting equates to false) which specifies + :param bool _async: An optional flag (not setting equates to false) which specifies if the orders should be replaced asynchronously :param requests.session session: Requests session object :param bool lightweight: If True will return dict not a resource
async renamed to _async in betting endpoint
liampauling_betfair
train
ac1003769a5c435ec3ba6084e22bb73aa517a752
diff --git a/lib/runtime.js b/lib/runtime.js index <HASH>..<HASH> 100644 --- a/lib/runtime.js +++ b/lib/runtime.js @@ -100,8 +100,8 @@ Runtime.prototype.observe = function(queries, cb) { var filters = []; queries.forEach(function(query) { var queryObservable = observable.flatMap(function(device) { - Rx.Observable.create(function(observer) { - self.registry.session.match(query, device, function(err, match) { + return Rx.Observable.create(function(observer) { + self.registry.match(query, device, function(err, match) { if (match) { observer.onNext(device); } diff --git a/test/test_runtime.js b/test/test_runtime.js index <HASH>..<HASH> 100644 --- a/test/test_runtime.js +++ b/test/test_runtime.js @@ -1,7 +1,6 @@ var Runtime = require('../lib/runtime'); var assert = require('assert'); -var Mocks = require('./fixture/scout_test_mocks'); -var Registry = Mocks.MockRegistry; +var Registry = require('./fixture/mem_registry'); var EventEmitter = require('events').EventEmitter; describe('Runtime', function(){
test runtime using mem registry, fixed bugs in new runtime registry code
zettajs_zetta
train
9aa6dc75db3b274590efe01d040d3d36411733d6
diff --git a/packages/substyle/src/defaultStyle.js b/packages/substyle/src/defaultStyle.js index <HASH>..<HASH> 100644 --- a/packages/substyle/src/defaultStyle.js +++ b/packages/substyle/src/defaultStyle.js @@ -1,7 +1,7 @@ // @flow import { createElement, Component } from 'react' import hoistStatics from 'hoist-non-react-statics' -import { identity, isFunction } from 'lodash' +import { omit, identity, isFunction } from 'lodash' import createSubstyle from './createSubstyle' import { @@ -24,32 +24,42 @@ const createDefaultStyle = ( constructor(props, context) { super(props, context) - this.lastDefaultStyle = null - this.setWrappedInstance = this.setWrappedInstance.bind(this) - } - - render() { - const { style, className, classNames, ...rest } = this.props - - const substyle = createSubstyle( + const { style, className, classNames, ...rest } = props + this.substyle = createSubstyle( { style, className, classNames }, this.context[PROPS_DECORATOR_CONTEXT_NAME] ) - const modifiers = getModifiers && getModifiers(rest) + this.setWrappedInstance = this.setWrappedInstance.bind(this) + if (isFunction(defaultStyle)) { + this.defaultStyle = defaultStyle(rest) + } + } + + componentWillReceiveProps({ style, className, classNames, ...rest }) { + if ( + style !== this.props.style || + className !== this.props.className || + classNames !== this.props.classNames + ) { + this.substyle = createSubstyle( + { style, className, classNames }, + this.context[PROPS_DECORATOR_CONTEXT_NAME] + ) + } - let finalDefaultStyle if (isFunction(defaultStyle)) { if (shouldUpdate(rest)) { - this.lastDefaultStyle = defaultStyle(rest) + this.defaultStyle = defaultStyle(rest) } - finalDefaultStyle = this.lastDefaultStyle - } else { - finalDefaultStyle = defaultStyle } + } + render() { + const rest = omit(this.props, ['style', 'className', 'classNames']) const EnhancedWrappedComponent = this.getWrappedComponent() + const modifiers = getModifiers && getModifiers(rest) return createElement(EnhancedWrappedComponent, { - style: substyle(modifiers, finalDefaultStyle), + style: this.substyle(modifiers, this.defaultStyle || defaultStyle), ref: isStatelessFunction(EnhancedWrappedComponent) ? undefined : this.setWrappedInstance, diff --git a/packages/substyle/test/defaultStyle.spec.js b/packages/substyle/test/defaultStyle.spec.js index <HASH>..<HASH> 100644 --- a/packages/substyle/test/defaultStyle.spec.js +++ b/packages/substyle/test/defaultStyle.spec.js @@ -210,4 +210,16 @@ describe('`defaultStyle` higher-order component factory', () => { expect(containerProps).to.not.have.property('className') expect(containerProps).to.have.property('data-mapped', 'foobar') }) + + it('should preserve previous default styles if shouldUpdate function returns false', () => { + const MyStyledComponent = defaultStyle(() => ({}), () => [], () => false)( + MyComponent + ) + const wrapper = mount(createElement(MyStyledComponent)) + const { style } = wrapper.find('MyComponent').props() + wrapper.setProps({ update: 'yes' }) + + const { style: nextStyle } = wrapper.find('MyComponent').props() + expect(nextStyle).to.equal(style) + }) })
preserve identity of substyle instances in defaultStyle HOC
jfschwarz_substyle
train
9260e51379463cc4d73d18624f10a19bbca9b009
diff --git a/tests/unit/Del/Common/Command/MigrationTest.php b/tests/unit/Del/Common/Command/MigrationTest.php index <HASH>..<HASH> 100644 --- a/tests/unit/Del/Common/Command/MigrationTest.php +++ b/tests/unit/Del/Common/Command/MigrationTest.php @@ -28,10 +28,11 @@ class MigrationTest extends \Codeception\TestCase\Test protected function _before() { $credentials = new DbCredentials(); - $credentials->setDriver('pdo_mysql') - ->setDatabase('delboy1978uk') - ->setUser('dbuser') - ->setPassword('[123456]'); + $credentials = new DbCredentials(); + $credentials->setDriver('pdo_mysql'); + $credentials->setDatabase('delboy1978uk'); + $credentials->setUser('dbuser'); + $credentials->setPassword('[123456]'); $container = ContainerService::getInstance() ->setDbCredentials($credentials) ->addEntityPath('src/Entity') diff --git a/tests/unit/Del/Common/Config/DBCredentialsTest.php b/tests/unit/Del/Common/Config/DBCredentialsTest.php index <HASH>..<HASH> 100644 --- a/tests/unit/Del/Common/Config/DBCredentialsTest.php +++ b/tests/unit/Del/Common/Config/DBCredentialsTest.php @@ -19,10 +19,10 @@ class DBCredentialsTest extends \Codeception\TestCase\Test protected function _before() { $this->creds = new DbCredentials(); - $this->creds->setDriver('pdo_mysql') - ->setDatabase('delboy1978uk') - ->setUser('dbuser') - ->setPassword('[123456]'); + $this->creds->setDriver('pdo_mysql'); + $this->creds->setDatabase('delboy1978uk'); + $this->creds->setUser('dbuser'); + $this->creds->setPassword('[123456]'); } protected function _after()
more fluent setter removal in tests
delboy1978uk_common
train
d52d6395ca8ae63eeb9c801c8fe5fa7e7638f396
diff --git a/resource_aws_api_gateway_authorizer_test.go b/resource_aws_api_gateway_authorizer_test.go index <HASH>..<HASH> 100644 --- a/resource_aws_api_gateway_authorizer_test.go +++ b/resource_aws_api_gateway_authorizer_test.go @@ -295,6 +295,7 @@ resource "aws_lambda_function" "authorizer" { function_name = "tf_acc_api_gateway_authorizer" role = "${aws_iam_role.iam_for_lambda.arn}" handler = "exports.example" + runtime = "nodejs4.3" } ` diff --git a/resource_aws_api_gateway_method_test.go b/resource_aws_api_gateway_method_test.go index <HASH>..<HASH> 100644 --- a/resource_aws_api_gateway_method_test.go +++ b/resource_aws_api_gateway_method_test.go @@ -261,6 +261,7 @@ resource "aws_lambda_function" "authorizer" { function_name = "tf_acc_api_gateway_authorizer" role = "${aws_iam_role.iam_for_lambda.arn}" handler = "exports.example" + runtime = "nodejs4.3" } resource "aws_api_gateway_authorizer" "test" {
provider/aws: Update lambda_function with runtime for tests
terraform-providers_terraform-provider-aws
train
f7e5879d06e2989ed96be5bda6baf6fd72fb50ec
diff --git a/gulp/tasks/compare.js b/gulp/tasks/compare.js index <HASH>..<HASH> 100644 --- a/gulp/tasks/compare.js +++ b/gulp/tasks/compare.js @@ -24,6 +24,13 @@ gulp.task('compare', function (done) { console.log ('\x1b[32m', (results.pass || 0) + ' Passed', '\x1b[0m'); console.log ('\x1b[31m', (results.fail || 0) + ' Failed\n', '\x1b[0m'); + // if the test report is enabled in the config + if (testSuite) { + junitWriter.save(path.join(paths.ci_report, 'xunit.xml'), function() { + console.log('\x1b[32m', 'Regression test report file (xunit.xml) is successfully created.', '\x1b[0m'); + }); + } + if (results.fail) { console.log ('\x1b[31m', '*** Mismatch errors found ***', '\x1b[0m'); console.log ("For a detailed report run `npm run openReport`\n"); @@ -35,7 +42,7 @@ gulp.task('compare', function (done) { } - _.each(compareConfig.testPairs, function (pair, key) { + _.each(compareConfig.testPairs, function (pair) { pair.testStatus = "running"; if (!testPairsLength) { @@ -69,12 +76,6 @@ gulp.task('compare', function (done) { } } - if (testSuite && testPairsLength === key + 1) { - junitWriter.save(path.join(paths.ci_report, 'xunit.xml'), function() { - console.log('\x1b[32m', 'Regression test report file (xunit.xml) is successfully created.', '\x1b[0m'); - }); - } - updateProgress(); }); });
test report file generation [Fixes #<I>]
garris_BackstopJS
train
ac497045f5c487ffb691bc5430e0d6f89b862d0f
diff --git a/txtorcon/test/test_torstate.py b/txtorcon/test/test_torstate.py index <HASH>..<HASH> 100644 --- a/txtorcon/test/test_torstate.py +++ b/txtorcon/test/test_torstate.py @@ -728,6 +728,53 @@ p reject 1-65535 self.assertTrue(self.state.routers.has_key('Unnamed')) self.assertTrue(self.state.routers.has_key('$00126582E505CF596F412D23ABC9E14DD4625C49')) + def test_NEWCONSENSUS_ends_with_OK(self): + """ + The arrival of a second NEWCONSENSUS event causes parsing + errors. + """ + + ## bootstrap the TorState so we can send it a "real" 650 + ## update + + self.protocol._set_valid_events(' '.join(self.state.event_map.keys())) + self.state._bootstrap() + + self.send("250+ns/all=") + self.send(".") + self.send("250 OK") + + self.send("250+circuit-status=") + self.send(".") + self.send("250 OK") + + self.send("250-stream-status=") + self.send("250 OK") + + self.send("250-address-mappings/all=") + self.send('250 OK') + + for ignored in self.state.event_map.items(): + self.send("250 OK") + + self.send("250-entry-guards=") + self.send("250 OK") + + self.send("250 OK") + + ## state is now bootstrapped, we can send our NEWCONSENSUS update + + self.protocol.dataReceived('\r\n'.join('''650+NEWCONSENSUS +r Unnamed ABJlguUFz1lvQS0jq8nhTdRiXEk /zIVUg1tKMUeyUBoyimzorbQN9E 2012-05-23 01:10:22 219.94.255.254 9001 0 +s Fast Guard Running Stable Valid +w Bandwidth=166 +. +650 OK +'''.split('\n'))) + + self.assertTrue(self.state.routers.has_key('Unnamed')) + self.assertTrue(self.state.routers.has_key('$00126582E505CF596F412D23ABC9E14DD4625C49')) + def test_newdesc_parse(self): """ should this mostly go in test_router instead? all we need to
add utest for failing if routerdescriptors end with OK
meejah_txtorcon
train
beb664568910b5333cd67cdcabc9420c288a68fa
diff --git a/src/View/Cell/DblistCell.php b/src/View/Cell/DblistCell.php index <HASH>..<HASH> 100644 --- a/src/View/Cell/DblistCell.php +++ b/src/View/Cell/DblistCell.php @@ -34,17 +34,17 @@ class DblistCell extends Cell * Checks the given list if it has the given value in its list items. * * @throws RunTimeException If the value is not found - * @param string $listItemValue List item value - * @param string $list Name of the list + * @param string $value List item value + * @param string $list Name of the list * @return void */ - public function renderValue($listItemValue, $list = null) + public function renderValue($value, $list = null) { $this->loadModel('CsvMigrations.Dblists'); $this->_createList($list); $query = $this->Dblists->findByName($list); - $query = $query->matching('DblistItems', function ($q) use ($listItemValue) { - return $q->where(['DblistItems.value' => $listItemValue]); + $query = $query->matching('DblistItems', function ($q) use ($value) { + return $q->where(['DblistItems.value' => $value]); }); if (! $query->isEmpty()) { @@ -53,13 +53,13 @@ class DblistCell extends Cell return; } - if ($query->isEmpty() && '' === trim($listItemValue)) { + if ($query->isEmpty() && '' === trim($value)) { $this->set('data', ''); return; } - $this->set('data', sprintf(ListRenderer::VALUE_NOT_FOUND_HTML, $listItemValue)); + $this->set('data', sprintf(ListRenderer::VALUE_NOT_FOUND_HTML, $value)); } /**
Shortened variable name (task #<I>)
QoboLtd_cakephp-csv-migrations
train
da9b3e5cbe7258f6c8f7cbb0987a0ca837881030
diff --git a/changelog.md b/changelog.md index <HASH>..<HASH> 100644 --- a/changelog.md +++ b/changelog.md @@ -1,3 +1,7 @@ +#### 0.3.12 update 2018.09.27 + +* Added: a new return code named `TOO_FREQUENT` + #### 0.3.11 update 2018.06.03 diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -19,7 +19,7 @@ def long_desc(): setup( name='slim', - version='0.3.11', + version='0.3.12', description=description(), long_description=long_desc(), diff --git a/slim/base/view.py b/slim/base/view.py index <HASH>..<HASH> 100644 --- a/slim/base/view.py +++ b/slim/base/view.py @@ -199,7 +199,7 @@ class BaseView(metaclass=MetaClassForInit): return default @property - def headers(self): + def headers(self) -> Dict: return self._request.headers @property diff --git a/slim/retcode.py b/slim/retcode.py index <HASH>..<HASH> 100644 --- a/slim/retcode.py +++ b/slim/retcode.py @@ -6,6 +6,7 @@ class RETCODE(StateObject): FAILED = -255 # 失败 TIMEOUT = -254 # 超时 UNKNOWN = -253 # 未知错误 + TOO_FREQUENT = -252 # 请求过于频繁 NOT_FOUND = -249 # 未找到 ALREADY_EXISTS = -248 # 已存在 @@ -27,6 +28,7 @@ class RETCODE(StateObject): FAILED: '失败', TIMEOUT: '超时', UNKNOWN: '未知错误', + TOO_FREQUENT: '请求过于频繁', NOT_FOUND: '未找到', ALREADY_EXISTS: '已存在', @@ -49,6 +51,7 @@ class RETCODE(StateObject): FAILED: 'failed', TIMEOUT: 'timeout', UNKNOWN: 'unknown', + TOO_FREQUENT: 'request too frequent', NOT_FOUND: 'not found', ALREADY_EXISTS: 'already exists',
added a new return code: TOO_FREQUENT
fy0_slim
train
1d1959e0bc3c220dd154da728b92085d760c5182
diff --git a/niworkflows/interfaces/utils.py b/niworkflows/interfaces/utils.py index <HASH>..<HASH> 100644 --- a/niworkflows/interfaces/utils.py +++ b/niworkflows/interfaces/utils.py @@ -261,6 +261,7 @@ def _gen_reference(fixed_image, moving_image, fov_mask=None, out_file=None, class SanitizeImageInputSpec(BaseInterfaceInputSpec): in_file = File(exists=True, mandatory=True, desc='input image') + n_volumes_to_discard = traits.Int(desc='discard n first volumes') class SanitizeImageOutputSpec(TraitedSpec): @@ -327,20 +328,17 @@ class SanitizeImage(SimpleInterface): # Matching affines matching_affines = valid_qform and np.allclose(img.get_qform(), img.get_sform()) + save_file = False + # Both match, qform valid (implicit with match), codes okay -> do nothing, empty report if matching_affines and qform_code > 0 and sform_code > 0: self._results['out_file'] = self.inputs.in_file open(out_report, 'w').close() - self._results['out_report'] = out_report - return runtime - - # A new file will be written - out_fname = fname_presuffix(self.inputs.in_file, suffix='_valid', newpath=runtime.cwd) - self._results['out_file'] = out_fname # Row 2: - if valid_qform and qform_code > 0: + elif valid_qform and qform_code > 0: img.set_sform(img.get_qform(), qform_code) + save_file = True warning_txt = 'Note on orientation: sform matrix set' description = """\ <p class="elem-desc">The sform has been copied from qform.</p> @@ -349,6 +347,7 @@ class SanitizeImage(SimpleInterface): # Note: if qform is not valid, matching_affines is False elif sform_code > 0 and (not matching_affines or qform_code == 0): img.set_qform(img.get_sform(), sform_code) + save_file = True warning_txt = 'Note on orientation: qform matrix overwritten' description = """\ <p class="elem-desc">The qform has been copied from sform.</p> @@ -368,6 +367,7 @@ class SanitizeImage(SimpleInterface): affine = img.affine img.set_sform(affine, nb.nifti1.xform_codes['scanner']) img.set_qform(affine, nb.nifti1.xform_codes['scanner']) + save_file = True warning_txt = 'WARNING - Missing orientation information' description = """\ <p class="elem-desc"> @@ -376,9 +376,24 @@ class SanitizeImage(SimpleInterface): Analyses of this dataset MAY BE INVALID. </p> """ + snippet = '<h3 class="elem-title">%s</h3>\n%s\n' % (warning_txt, description) + + if traits.isdefined(self.inputs.n_volumes_to_discard) and \ + self.inputs.n_volumes_to_discard: + img = nb.Nifti1Image(img.get_data[:, :, :, self.inputs.n_volumes_to_discard:], + img.affine, + img.header) + save_file = True + # Store new file and report - img.to_filename(out_fname) + if save_file: + # A new file will be written + out_fname = fname_presuffix(self.inputs.in_file, suffix='_valid', + newpath=runtime.cwd) + self._results['out_file'] = out_fname + img.to_filename(out_fname) + with open(out_report, 'w') as fobj: fobj.write(indent(snippet, '\t' * 3))
add option to discard n first volumes
poldracklab_niworkflows
train
70625f9f3a39e12943bed3c62594273217eb7f2d
diff --git a/src/Contracts/Bot.php b/src/Contracts/Bot.php index <HASH>..<HASH> 100644 --- a/src/Contracts/Bot.php +++ b/src/Contracts/Bot.php @@ -42,29 +42,4 @@ class Bot extends FbBotApp { return new HandleMessageResponse($this->call('me/thread_settings', $message, $type)); } - - /** - * @param $text - * - * @return array - */ - public function setGreeting($text) - { - return $this->call('me/thread_settings', [ - 'setting_type' => 'greeting', - 'greeting' => [ - 'text' => $text, - ], - ]); - } - - /** - * @return array - */ - public function deleteGreeting() - { - return $this->call([ - 'setting_type' => 'greeting', - ], self::TYPE_DELETE); - } }
refactor: Remove unused code
CasperLaiTW_laravel-fb-messenger
train
47fa9bea3070d2824f81512d8cf20c3f35c90b6f
diff --git a/lib/fabricator.js b/lib/fabricator.js index <HASH>..<HASH> 100644 --- a/lib/fabricator.js +++ b/lib/fabricator.js @@ -42,6 +42,11 @@ const script = ` const children = {}; export function fabricate (bakes, fabricator, snap, body, cb) { + bakes = bakes.filter(function (bake) { + // list of bakes that don't influence the bytecode + return ![ '--prof', '--v8-options' ].includes(bake); + }); + const cmd = fabricator.binaryPath; const key = JSON.stringify([ cmd, bakes ]); let child = children[key];
filter out bakes that don't influence the bytecode. fixes #<I>
zeit_pkg
train
6feb52ef27c715e4817e5fc8deb019ee67f17cce
diff --git a/app/helpers/effective_datatables_helper.rb b/app/helpers/effective_datatables_helper.rb index <HASH>..<HASH> 100644 --- a/app/helpers/effective_datatables_helper.rb +++ b/app/helpers/effective_datatables_helper.rb @@ -47,21 +47,21 @@ module EffectiveDatatablesHelper input_html: { name: nil, value: value, autocomplete: 'off', data: {'column-name' => opts[:name], 'column-index' => opts[:index]} } when :date form.input name, label: false, required: false, value: value, - as: (defined?(EffectiveFormInputs) ? :effective_date_picker : :string), + as: (ActionView::Helpers::FormBuilder.instance_methods.include?(:effective_date_picker) ? :effective_date_picker : :string), placeholder: (opts[:label] || name), input_group: false, input_html: { name: nil, autocomplete: 'off', data: {'column-name' => opts[:name], 'column-index' => opts[:index]} }, input_js: { useStrict: true, keepInvalid: true } when :datetime form.input name, label: false, required: false, value: value, - as: (defined?(EffectiveFormInputs) ? :effective_date_time_picker : :string), + as: (ActionView::Helpers::FormBuilder.instance_methods.include?(:effective_date_time_picker) ? :effective_date_time_picker : :string), placeholder: (opts[:label] || name), input_group: false, input_html: { name: nil, value: value, autocomplete: 'off', data: {'column-name' => opts[:name], 'column-index' => opts[:index]} }, input_js: { useStrict: true, keepInvalid: true } # Keep invalid format like "2015-11" so we can still filter by year, month or day when :select, :boolean form.input name, label: false, required: false, value: value, - as: (defined?(EffectiveFormInputs) ? :effective_select : :select), + as: (ActionView::Helpers::FormBuilder.instance_methods.include?(:effective_select) ? :effective_select : :select), collection: opts[:filter][:values], selected: opts[:filter][:selected], multiple: opts[:filter][:multiple] == true, @@ -70,7 +70,7 @@ module EffectiveDatatablesHelper input_js: { placeholder: (opts[:label] || name.titleize) } when :grouped_select form.input name, label: false, required: false, value: value, - as: (defined?(EffectiveFormInputs) ? :effective_select : :grouped_select), + as: (ActionView::Helpers::FormBuilder.instance_methods.include?(:effective_select) ? :effective_select : :grouped_select), collection: opts[:filter][:values], selected: opts[:filter][:selected], multiple: opts[:filter][:multiple] == true,
test for defined helpers rather than presence of gem
code-and-effect_effective_datatables
train
f9e388750605908eee97516b7a112ed0ba037500
diff --git a/lib/resque/worker.rb b/lib/resque/worker.rb index <HASH>..<HASH> 100644 --- a/lib/resque/worker.rb +++ b/lib/resque/worker.rb @@ -557,7 +557,7 @@ module Resque # The string representation is the same as the id for this worker # instance. Can be used with `Worker.find`. def to_s - @to_s ||= "#{hostname}:#{Process.pid}:#{@queues.join(',')}" + @to_s ||= "#{hostname}:#{pid}:#{@queues.join(',')}" end alias_method :id, :to_s @@ -568,7 +568,7 @@ module Resque # Returns Integer PID of running worker def pid - Process.pid + @pid ||= Process.pid end # Returns an Array of string pids of all the other workers on this
Cache pid. This way, the pid is correct from other places. <URL>
resque_resque
train
f5396a0f38a8a7c3645d25949061efc6fa75b9fd
diff --git a/.eslintrc.js b/.eslintrc.js index <HASH>..<HASH> 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -41,7 +41,7 @@ module.exports = { 'max-depth': 'off', 'max-lines': 'off', 'max-nested-callbacks': 'error', - 'max-params': 'error', + 'max-params': 'off', 'new-cap': 'error', 'newline-after-var': 'off', 'newline-before-return': 'off',
ESLint: Disable `max-params` rule We have quite a few functions with more than three parameters
glimmerjs_glimmer-vm
train
cf81f44060079d342e83091e55ff8abb453fdf37
diff --git a/src/org/jbehave/scenario/finegrained/junit/monitoring/JUnitDescriptionGenerator.java b/src/org/jbehave/scenario/finegrained/junit/monitoring/JUnitDescriptionGenerator.java index <HASH>..<HASH> 100644 --- a/src/org/jbehave/scenario/finegrained/junit/monitoring/JUnitDescriptionGenerator.java +++ b/src/org/jbehave/scenario/finegrained/junit/monitoring/JUnitDescriptionGenerator.java @@ -11,8 +11,8 @@ public class JUnitDescriptionGenerator { public Description createDescriptionFrom(ScenarioDefinition scenario, Steps... candidateSteps) { - Description scenarioDescription = Description.createTestDescription( - candidateSteps[0].getClass(), scenario.getTitle()); + Description scenarioDescription = Description + .createSuiteDescription("Scenario: " + scenario.getTitle()); DescriptionTextUniquefier uniquefier = new DescriptionTextUniquefier(); for (String stringStep : scenario.getSteps()) { for (Steps candidates : candidateSteps) { diff --git a/test/org/jbehave/scenario/finegrained/junit/monitoring/JUnitDescriptionGeneratorTest.java b/test/org/jbehave/scenario/finegrained/junit/monitoring/JUnitDescriptionGeneratorTest.java index <HASH>..<HASH> 100644 --- a/test/org/jbehave/scenario/finegrained/junit/monitoring/JUnitDescriptionGeneratorTest.java +++ b/test/org/jbehave/scenario/finegrained/junit/monitoring/JUnitDescriptionGeneratorTest.java @@ -47,8 +47,7 @@ public class JUnitDescriptionGeneratorTest { ScenarioDefinition scenario = new ScenarioDefinition("MyTitle"); Description description = generator.createDescriptionFrom(scenario, steps); - ensureThat(description, equalTo(Description.createTestDescription(steps - .getClass(), "MyTitle"))); + ensureThat(description, equalTo(Description.createSuiteDescription("Scenario: MyTitle"))); } @Test @@ -80,7 +79,7 @@ public class JUnitDescriptionGeneratorTest { JUnitScenario.class); ensureThat(description.getChildren().size(), equalTo(1)); ensureThat(description.getChildren().get(0), equalTo(Description - .createTestDescription(steps.getClass(), "MyTitle"))); + .createSuiteDescription("Scenario: MyTitle"))); } @Test diff --git a/test/org/jbehave/scenario/finegrained/junit/monitoring/JUnitReportingRunnerTest.java b/test/org/jbehave/scenario/finegrained/junit/monitoring/JUnitReportingRunnerTest.java index <HASH>..<HASH> 100644 --- a/test/org/jbehave/scenario/finegrained/junit/monitoring/JUnitReportingRunnerTest.java +++ b/test/org/jbehave/scenario/finegrained/junit/monitoring/JUnitReportingRunnerTest.java @@ -1,7 +1,11 @@ package org.jbehave.scenario.finegrained.junit.monitoring; -import static org.mockito.Mockito.verify; +import static org.hamcrest.CoreMatchers.*; +import static org.jbehave.util.JUnit4Ensure.*; +import static org.mockito.Mockito.*; +import org.hamcrest.BaseMatcher; +import org.hamcrest.Matcher; import org.junit.Before; import org.junit.Test; import org.junit.runner.Description; @@ -13,17 +17,19 @@ public class JUnitReportingRunnerTest { @Mock private RunNotifier notifier; + private JUnitReportingRunner runner; + private Description description; @Before public void setUp() { MockitoAnnotations.initMocks(this); + runner = new JUnitReportingRunner( + ExampleScenario.class); + description = runner.getDescription(); } @Test public void runUpExampleScenarioAndCheckNotifications() { - JUnitReportingRunner runner = new JUnitReportingRunner( - ExampleScenario.class); - Description description = runner.getDescription(); runner.run(notifier); verifyAllChildDescriptionsFired(description); } @@ -35,5 +41,35 @@ public class JUnitReportingRunnerTest { verifyAllChildDescriptionsFired(child); } } + + @Test + public void topLevelDescriptionForExample() { + ensureThat(description.getDisplayName(), equalTo("org.jbehave.scenario.finegrained.junit.monitoring.ExampleScenario")); + } + + @Test + public void scenarioDescriptionsForExample() { + ensureThat(description.getChildren().get(0).getDisplayName(), equalTo("Scenario: 2 squared")); + } + + @Test + public void stepDescriptionsForExample() { + ensureThat(description.getChildren().get(0).getChildren().get(0).getDisplayName(), startsWith("Given a variable x with value 2")); + } + + private Matcher<String> startsWith(final String prefix) { + return new BaseMatcher<String>() { + + public boolean matches(Object item) { + return item.toString().indexOf(prefix) == 0; + } + + public void describeTo(org.hamcrest.Description description) { + description.appendText("A String starting with \"" + prefix + "\""); + } + + }; + + } }
Create junit descriptions that show the scenario name rather than the name of the Steps class
valfirst_jbehave-junit-runner
train
703e24dc2a04a56dfc6847b63a695a8c423c1698
diff --git a/src/Core/HttpKernel.php b/src/Core/HttpKernel.php index <HASH>..<HASH> 100644 --- a/src/Core/HttpKernel.php +++ b/src/Core/HttpKernel.php @@ -176,9 +176,11 @@ class HttpKernel } if (InstalledVersions::isInstalled('shopware/platform')) { - $shopwareVersion = InstalledVersions::getVersion('shopware/platform'); + $shopwareVersion = InstalledVersions::getVersion('shopware/platform') + . '@' . InstalledVersions::getReference('shopware/platform'); } else { - $shopwareVersion = InstalledVersions::getVersion('shopware/core'); + $shopwareVersion = InstalledVersions::getVersion('shopware/core') + . '@' . InstalledVersions::getReference('shopware/core'); } $connection = self::getConnection();
NEXT-<I> - Include reference in version
shopware_platform
train
faf86df2020cbf4791ff1e504fd733cdf42038b2
diff --git a/xmantissa/webapp.py b/xmantissa/webapp.py index <HASH>..<HASH> 100644 --- a/xmantissa/webapp.py +++ b/xmantissa/webapp.py @@ -20,7 +20,7 @@ from nevow.rend import Page from nevow import livepage, athena from nevow.inevow import IResource, IQ from nevow import tags as t -from nevow.url import URL +from nevow import url from xmantissa.publicweb import CustomizedPublicPage from xmantissa.website import PrefixURLMixin, StaticRedirect @@ -68,7 +68,7 @@ class NavMixin(object): def render_navigation(self, ctx, data): # this won't work with child tabs who have children - url = URL.fromContext(ctx) + thisurl = url.URL.fromContext(ctx) patterns = PatternDictionary(self.getDocFactory('navigation')) @@ -82,7 +82,7 @@ class NavMixin(object): for tab in tabs: if tab.linkURL is None: tab.linkURL = self.webapp.linkTo(tab.storeID) - if tab.linkURL[1:] == url.path: + if tab.linkURL[1:] == thisurl.path: tab.selected = True else: tab.selected = False @@ -231,8 +231,14 @@ class GenericNavigationLivePage(FragmentWrapperMixin, livepage.LivePage, NavMixi class GenericNavigationAthenaPage(athena.LivePage, FragmentWrapperMixin, NavMixin): def __init__(self, webapp, fragment, pageComponents): - root = URL.fromString('/').child('private').child('jsmodule') - athena.LivePage.__init__(self, getattr(fragment, 'iface', None), fragment, jsModuleRoot=root, docFactory=webapp.getDocFactory('shell')) + root = url.URL.fromString('/').child('private').child('jsmodule') + athena.LivePage.__init__( + self, + getattr(fragment, 'iface', None), + fragment, + jsModuleRoot=root, + transportRoot=url.root.child('live'), + docFactory=webapp.getDocFactory('shell')) NavMixin.__init__(self, webapp, pageComponents) FragmentWrapperMixin.__init__(self, fragment) @@ -262,7 +268,7 @@ class PrivateRootPage(Page, NavMixin): return self # /private/XXXX -> click = self.webapp.linkTo(navigation[0].storeID) - return URL.fromContext(ctx).click(click) + return url.URL.fromContext(ctx).click(click) def render_content(self, ctx, data): return """ @@ -293,9 +299,11 @@ class PrivateRootPage(Page, NavMixin): if fragment.docFactory is None: raise RuntimeError("%r (fragment name %r) has no docFactory" % (fragment, fragment.fragmentName)) - pageClass = {False: GenericNavigationPage, - True: GenericNavigationLivePage, - 'athena': GenericNavigationAthenaPage}.get(fragment.live) + if isinstance(fragment, athena.LiveFragment): + pageClass = GenericNavigationAthenaPage + else: + pageClass = {False: GenericNavigationPage, + True: GenericNavigationLivePage}.get(fragment.live) return pageClass(self.webapp, fragment, self.pageComponents) diff --git a/xmantissa/website.py b/xmantissa/website.py index <HASH>..<HASH> 100644 --- a/xmantissa/website.py +++ b/xmantissa/website.py @@ -30,6 +30,7 @@ from nevow import inevow from nevow.appserver import NevowSite, NevowRequest from nevow.static import File from nevow.url import URL +from nevow import athena from vertex import sslverify @@ -65,6 +66,9 @@ class SiteRootMixin(object): "This _must_ be installed at the root of a server.") def locateChild(self, ctx, segments): + if segments[0] == 'live': + return athena.LivePage(None, None), segments[1:] + self.hitCount += 1 shortcut = getattr(self, 'child_'+segments[0], None) if shortcut:
Merge isometric-<I> Author: exarkun Reviewer: moe (Mantissa bits) Fixes #<I> This adds the beginning of an Athena-based Radical implementation. It also adds /live/ to Mantissa to short-circuit all the unnecessary database work when serving a LivePage's transports, and makes it even more convenient to use LiveFragment by removing the need to set `live' on it when it is used as an INavigableFragment.
twisted_mantissa
train
0c3fc148754dff21dcc7efee6e9dd8d5feb51ea0
diff --git a/client/lib/abtest/active-tests.js b/client/lib/abtest/active-tests.js index <HASH>..<HASH> 100644 --- a/client/lib/abtest/active-tests.js +++ b/client/lib/abtest/active-tests.js @@ -16,15 +16,6 @@ module.exports = { }, defaultVariation: 'singlePurchaseFlow' }, - verticalSurvey: { - datestamp: '20151210', - variations: { - noSurvey: 12, - oneStep: 44, - twoStep: 44 - }, - defaultVariation: 'noSurvey' - }, translatorInvitation: { datestamp: '20150910', variations: { diff --git a/client/signup/config/flows.js b/client/signup/config/flows.js index <HASH>..<HASH> 100644 --- a/client/signup/config/flows.js +++ b/client/signup/config/flows.js @@ -167,11 +167,6 @@ function removeUserStepFromFlow( flow ) { } function getCurrentFlowNameFromTest( currentURL ) { - // Assign the user to the verticals survey test if appropriate. - if ( '/start/vert-blog' === currentURL || '/start/vert-site' === currentURL ) { - return ( 'noSurvey' === abtest( 'verticalSurvey' ) ) ? 'main' : 'verticals'; - } - // Consider remaining homepage users for the Triforce AB test. if ( '/start/en?ref=homepage' === currentURL && 'triforce' === abtest( 'triforce' ) ) { return 'layout';
Signup: Disable verticals test i2 The test was enabled in #<I>
Automattic_wp-calypso
train
0f6ae0aeee472d3de55567034f9e59834698cddf
diff --git a/src/Projection/InMemoryProjectionManager.php b/src/Projection/InMemoryProjectionManager.php index <HASH>..<HASH> 100644 --- a/src/Projection/InMemoryProjectionManager.php +++ b/src/Projection/InMemoryProjectionManager.php @@ -19,14 +19,6 @@ use Prooph\EventStore\InMemoryEventStore; final class InMemoryProjectionManager implements ProjectionManager { - public const OPTION_CACHE_SIZE = 'cache_size'; - public const OPTION_SLEEP = 'sleep'; - public const OPTION_PERSIST_BLOCK_SIZE = 'persist_block_size'; - - private const DEFAULT_CACHE_SIZE = 1000; - private const DEFAULT_SLEEP = 100000; - private const DEFAULT_PERSIST_BLOCK_SIZE = 1000; - /** * @var EventStore */ diff --git a/src/Projection/ProjectionManager.php b/src/Projection/ProjectionManager.php index <HASH>..<HASH> 100644 --- a/src/Projection/ProjectionManager.php +++ b/src/Projection/ProjectionManager.php @@ -14,6 +14,14 @@ namespace Prooph\EventStore\Projection; interface ProjectionManager { + public const OPTION_CACHE_SIZE = 'cache_size'; + public const OPTION_SLEEP = 'sleep'; + public const OPTION_PERSIST_BLOCK_SIZE = 'persist_block_size'; + + public const DEFAULT_CACHE_SIZE = 1000; + public const DEFAULT_SLEEP = 100000; + public const DEFAULT_PERSIST_BLOCK_SIZE = 1000; + public function createQuery(): Query; public function createProjection( diff --git a/tests/Projection/AbstractEventStoreProjectionTest.php b/tests/Projection/AbstractEventStoreProjectionTest.php index <HASH>..<HASH> 100644 --- a/tests/Projection/AbstractEventStoreProjectionTest.php +++ b/tests/Projection/AbstractEventStoreProjectionTest.php @@ -463,6 +463,7 @@ abstract class AbstractEventStoreProjectionTest extends TestCase $this->assertEquals(0, $projection->getState()['count']); $this->assertEquals(49, $calledTimes); + $this->assertEquals([], $projectionManager->fetchProjectionNames('test_projection')); } /** @@ -918,7 +919,9 @@ abstract class AbstractEventStoreProjectionTest extends TestCase { $this->prepareEventStream('user-123'); - $projection = $this->projectionManager->createProjection('test_projection'); + $projection = $this->projectionManager->createProjection('test_projection', [ + $this->projectionManager::OPTION_PERSIST_BLOCK_SIZE => 10, + ]); $projection ->init(function (): array { @@ -942,7 +945,9 @@ abstract class AbstractEventStoreProjectionTest extends TestCase { $this->prepareEventStream('user-123'); - $projection = $this->projectionManager->createProjection('test_projection'); + $projection = $this->projectionManager->createProjection('test_projection', [ + $this->projectionManager::OPTION_PERSIST_BLOCK_SIZE => 10, + ]); $projection ->init(function (): array { diff --git a/tests/Projection/AbstractEventStoreReadModelProjectionTest.php b/tests/Projection/AbstractEventStoreReadModelProjectionTest.php index <HASH>..<HASH> 100644 --- a/tests/Projection/AbstractEventStoreReadModelProjectionTest.php +++ b/tests/Projection/AbstractEventStoreReadModelProjectionTest.php @@ -763,10 +763,9 @@ abstract class AbstractEventStoreReadModelProjectionTest extends TestCase ]) ->run(false); - $projection->run(false); - $this->assertEquals(0, $projection->getState()['count']); $this->assertEquals(49, $calledTimes); + $this->assertEquals([], $projectionManager->fetchProjectionNames('test_projection')); } /**
move projection manager constants to interface, update some tests
prooph_event-store
train
f72feae9bafbadfd4da4e383bb302afc33c7d3e0
diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb index <HASH>..<HASH> 100644 --- a/actionpack/test/controller/caching_test.rb +++ b/actionpack/test/controller/caching_test.rb @@ -253,7 +253,7 @@ CACHED def test_fragment_caching_with_variant @request.variant = :phone - get :formatted_fragment_cached_with_variant, :format => "html", :variant => :phone + get :formatted_fragment_cached_with_variant, :format => "html" assert_response :success expected_body = "<body>\n<p>PHONE</p>\n</body>\n"
Don't pass variant in params, it's ignored We're setting variant above, in request object directly
rails_rails
train
d44176c888d6b76fab7c7017632c505799a84b99
diff --git a/docs/change-log.md b/docs/change-log.md index <HASH>..<HASH> 100644 --- a/docs/change-log.md +++ b/docs/change-log.md @@ -5,12 +5,16 @@ ### News: - config contexts can now have an `onunload` property for clean up tasks after elements are detached from the document +- route changes now re-render from scratch, rather than attempting a virtual dom diff +- virtual elements that are children of an array can now accept a `key` attribute which maintains the identity of the underlying DOM elements when the array gets shuffled [#98](https://github.com/lhorie/mithril.js/issues/98) ### Bug Fixes: - fixed a subtree directive bug that happened in inputs inside loops - fixed select.value so that the correct option is displayed on first render - in m.request, non-idempotent methods now automatically send appropriate Content-Type header if `serialize` is `JSON.stringify` [#139](https://github.com/lhorie/mithril.js/issues/139) +- `m` selectors now correctly handle empty attribute values like `[href='']` +- pre-existing nodes in a root element now get cleared if there's no cell cache associated with the element [#60](https://github.com/lhorie/mithril.js/issues/60) --- diff --git a/mithril.js b/mithril.js index <HASH>..<HASH> 100644 --- a/mithril.js +++ b/mithril.js @@ -297,12 +297,16 @@ Mithril = m = new function app(window) { m.render = function(root, cell) { var configs = [] if (!root) throw new Error("Please ensure the DOM element exists before rendering a template into it.") - var index = nodeCache.indexOf(root) - var id = index < 0 ? nodeCache.push(root) - 1 : index + var id = getCellCacheId(root) var node = root == window.document || root == window.document.documentElement ? documentNode : root + if (cellCache[id] === undefined) clear(node.childNodes) cellCache[id] = build(node, null, undefined, undefined, cell, cellCache[id], false, 0, null, undefined, configs) for (var i = 0; i < configs.length; i++) configs[i]() } + function getCellCacheId(element) { + var index = nodeCache.indexOf(element) + return index < 0 ? nodeCache.push(element) - 1 : index + } m.trust = function(value) { value = new String(value) @@ -428,17 +432,23 @@ Mithril = m = new function app(window) { } for (var route in router) { - if (route == path) return !void m.module(root, router[route]) + if (route == path) { + clear(root.childNodes, cellCache[getCellCacheId(root)]) + m.module(root, router[route]) + return true + } var matcher = new RegExp("^" + route.replace(/:[^\/]+?\.{3}/g, "(.*?)").replace(/:[^\/]+/g, "([^\\/]+)") + "\/?$") if (matcher.test(path)) { - return !void path.replace(matcher, function() { + clear(root.childNodes, cellCache[getCellCacheId(root)]) + path.replace(matcher, function() { var keys = route.match(/:[^\/]+/g) || [] var values = [].slice.call(arguments, 1, -2) for (var i = 0; i < keys.length; i++) routeParams[keys[i].replace(/:|\./g, "")] = decodeSpace(values[i]) m.module(root, router[route]) }) + return true } } } diff --git a/tests/mithril-tests.js b/tests/mithril-tests.js index <HASH>..<HASH> 100644 --- a/tests/mithril-tests.js +++ b/tests/mithril-tests.js @@ -577,6 +577,32 @@ function testMithril(mock) { m.render(root, m("textarea", ["test1"])) return root.childNodes[0].value === "test1" }) + test(function() { + var root = mock.document.createElement("div") + var unloaded = 0 + m.render(root, [ + m("div", { + key: 1, + config: function(el, init, ctx) { + ctx.onunload = function() { + unloaded++ + } + } + }) + ]) + m.render(root, [ + m("div", {key: 2}), + m("div", { + key: 1, + config: function(el, init, ctx) { + ctx.onunload = function() { + unloaded++ + } + } + }) + ]) + return unloaded == 0 + }) //end m.render //m.redraw @@ -1047,50 +1073,6 @@ function testMithril(mock) { ] } }, - "/test19": { - controller: function() {}, - view: function() { - return [ - m("div", { - key: 1, - config: function(el, init, ctx) { - ctx.onunload = function() { - unloaded++ - } - } - }) - ] - } - } - }) - mock.performance.$elapse(50) - m.route("/test19") - mock.performance.$elapse(50) //teardown - return unloaded == 0 - }) - test(function() { - mock.performance.$elapse(50) //setup - mock.location.search = "?" - - var root = mock.document.createElement("div") - var unloaded = 0 - m.route.mode = "search" - m.route(root, "/", { - "/": { - controller: function() {}, - view: function() { - return [ - m("div", { - key: 1, - config: function(el, init, ctx) { - ctx.onunload = function() { - unloaded++ - } - } - }) - ] - } - }, "/test20": { controller: function() {}, view: function() {
re-render from scratch on route changes
MithrilJS_mithril.js
train
a4e24e857435532be0cca1fdac7db962e7d1a229
diff --git a/src/Swarrot/Processor/RPC/RpcServerProcessor.php b/src/Swarrot/Processor/RPC/RpcServerProcessor.php index <HASH>..<HASH> 100644 --- a/src/Swarrot/Processor/RPC/RpcServerProcessor.php +++ b/src/Swarrot/Processor/RPC/RpcServerProcessor.php @@ -41,7 +41,7 @@ class RpcServerProcessor implements ProcessorInterface $properties = $message->getProperties(); - if (!isset($properties['reply_to'], $properties['correlation_id'])) { + if (!isset($properties['reply_to'], $properties['correlation_id']) || empty($properties['reply_to']) || empty($properties['correlation_id'])) { return $result; } diff --git a/tests/Swarrot/Processor/RPC/RpcServerProcessorTest.php b/tests/Swarrot/Processor/RPC/RpcServerProcessorTest.php index <HASH>..<HASH> 100644 --- a/tests/Swarrot/Processor/RPC/RpcServerProcessorTest.php +++ b/tests/Swarrot/Processor/RPC/RpcServerProcessorTest.php @@ -44,12 +44,15 @@ class RpcServerProcessorTest extends ProphecyTestCase { return [[[]], [['reply_to' => 'foo']], - [['correlation_id' => 0]]]; + [['correlation_id' => 0]], + [['reply_to' => '', 'correlation_id' => 0]], + [['reply_to' => '', 'correlation_id' => 42]], + [['reply_to' => 'foo', 'correlation_id' => 0]]]; } public function test_it_should_publish_a_new_message_when_done() { - $message = new Message('', ['reply_to' => 'foo', 'correlation_id' => 0]); + $message = new Message('', ['reply_to' => 'foo', 'correlation_id' => 42]); $processor = $this->prophesize('Swarrot\\Processor\\ProcessorInterface'); $processor->process($message, [])->willReturn('bar');
[RPC] The properties reply_to and correlation_id are always be set But they can be empty...
swarrot_swarrot
train
74d1a91aa61034efa4b2ab24baffff9ef713ea42
diff --git a/rb/lib/selenium/webdriver/common/socket_poller.rb b/rb/lib/selenium/webdriver/common/socket_poller.rb index <HASH>..<HASH> 100644 --- a/rb/lib/selenium/webdriver/common/socket_poller.rb +++ b/rb/lib/selenium/webdriver/common/socket_poller.rb @@ -66,8 +66,8 @@ module Selenium }.freeze if Platform.jruby? - # we use a plain TCPSocket here since JRuby has issues select()ing on a connecting socket - # see http://jira.codehaus.org/browse/JRUBY-5165 + # we use a plain TCPSocket here since JRuby has issues closing socket + # see https://github.com/jruby/jruby/issues/5709 def listening? TCPSocket.new(@host, @port).close true diff --git a/rb/spec/unit/selenium/webdriver/socket_poller_spec.rb b/rb/spec/unit/selenium/webdriver/socket_poller_spec.rb index <HASH>..<HASH> 100644 --- a/rb/spec/unit/selenium/webdriver/socket_poller_spec.rb +++ b/rb/spec/unit/selenium/webdriver/socket_poller_spec.rb @@ -22,62 +22,49 @@ require_relative 'spec_helper' module Selenium module WebDriver describe SocketPoller do - let(:poller) { Selenium::WebDriver::SocketPoller.new('localhost', 1234, 5, 0.05) } - let(:socket) { instance_double Socket, close: true } - - def setup_connect(*states) - # TODO(jari): find a cleaner way to solve the platform-specific collaborators - if Platform.jruby? - states.each do |state| - if state - expect(TCPSocket).to receive(:new).and_return socket - else - expect(TCPSocket).to receive(:new).and_raise Errno::ECONNREFUSED - end - end - else - allow(Socket).to receive(:new).and_return socket - states.each do |state| - expect(socket).to receive(:connect_nonblock) - .and_raise(state ? Errno::EISCONN.new('connection in progress') : Errno::ECONNREFUSED.new('connection refused')) - end + around do |example| + server_thread = Thread.new do + server = TCPServer.open(9250) + Thread.current.thread_variable_set(:server, server) + loop { server.accept.close } end + server_thread.report_on_exception = false + example.call + ensure + server_thread.thread_variable_get(:server).close + end + + def poller(port) + described_class.new('localhost', port, 5, 0.05) end describe '#connected?' do it 'returns true when the socket is listening' do - setup_connect false, true - expect(poller).to be_connected + expect(poller(9250)).to be_connected end it 'returns false if the socket is not listening after the given timeout' do - setup_connect false - start = Time.parse('2010-01-01 00:00:00') wait = Time.parse('2010-01-01 00:00:04') stop = Time.parse('2010-01-01 00:00:06') expect(Process).to receive(:clock_gettime).and_return(start, wait, stop) - expect(poller).not_to be_connected + expect(poller(9251)).not_to be_connected end end describe '#closed?' do it 'returns true when the socket is closed' do - setup_connect true, true, false - - expect(poller).to be_closed + expect(poller(9251)).to be_closed end it 'returns false if the socket is still listening after the given timeout' do - setup_connect true - start = Time.parse('2010-01-01 00:00:00').to_f wait = Time.parse('2010-01-01 00:00:04').to_f stop = Time.parse('2010-01-01 00:00:06').to_f expect(Process).to receive(:clock_gettime).and_return(start, wait, stop) - expect(poller).not_to be_closed + expect(poller(9250)).not_to be_closed end end end
Improve SocketPoller unit tests to actually use real sockets
SeleniumHQ_selenium
train
cc5d73149b95723cc3df3d0e3c003964d9e7db1a
diff --git a/golang/choriautil/choriautil.go b/golang/choriautil/choriautil.go index <HASH>..<HASH> 100644 --- a/golang/choriautil/choriautil.go +++ b/golang/choriautil/choriautil.go @@ -93,7 +93,7 @@ func infoAction(ctx context.Context, req *mcorpc.Request, reply *mcorpc.Reply, a reply.Data = &info{ Security: "choria", Connector: "choria", - ClientVersion: fmt.Sprintf("choria %s", nats.Version), + ClientVersion: nats.Version, ClientFlavour: fmt.Sprintf("go-nats %s", runtime.Version()), ConnectedServer: conn.ConnectedServer(), FacterCommand: agent.Choria.FacterCmd(),
(#<I>) clarify versions in choria_util info
choria-io_go-choria
train
0811d2bdc6fe4b1adfeb5bcef015d2244261cb62
diff --git a/cmd/modelcmd/base.go b/cmd/modelcmd/base.go index <HASH>..<HASH> 100644 --- a/cmd/modelcmd/base.go +++ b/cmd/modelcmd/base.go @@ -27,7 +27,7 @@ var errNoNameSpecified = errors.New("no name specified") type CommandBase interface { cmd.Command - // closeContext closes the commands API context. + // closeContext closes the command's API context. closeContext() } diff --git a/cmd/modelcmd/modelcommand.go b/cmd/modelcmd/modelcommand.go index <HASH>..<HASH> 100644 --- a/cmd/modelcmd/modelcommand.go +++ b/cmd/modelcmd/modelcommand.go @@ -22,7 +22,7 @@ import ( "github.com/juju/juju/jujuclient" ) -var logger = loggo.GetLogger("juju.cmd.envcmd") +var logger = loggo.GetLogger("juju.cmd.modelcmd") // ErrNoModelSpecified is returned by commands that operate on // an environment if there is no current model, no model
cmd/modelcmd: Drive by spelling
juju_juju
train
6fc2928c75d5f11b25efca826770d6dc3fc24d99
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -91,6 +91,13 @@ An upload also creates conversions(size) for the file: The original version will be returned if you don't specify the size. These conversions can be defined in the assetlibrary config file. +If you want to conversion names prefixed with the file name you can set the converionprefix in the config file to true. + +``` +'conversionPrefix' => true, +``` + + To aid you in sending the right data to the controller there are helper functions to inject an input into your form like so: ```php diff --git a/config/assetlibrary.php b/config/assetlibrary.php index <HASH>..<HASH> 100644 --- a/config/assetlibrary.php +++ b/config/assetlibrary.php @@ -4,6 +4,7 @@ return [ 'locale' => Thinktomorrow\Locale\Locale::class, ], + 'conversionPrefix' => false, 'conversions' => [ 'thumb' => [ 'width' => 150, diff --git a/tests/AssetTest.php b/tests/AssetTest.php index <HASH>..<HASH> 100644 --- a/tests/AssetTest.php +++ b/tests/AssetTest.php @@ -337,6 +337,17 @@ class AssetTest extends TestCase $this->assertEquals('<input type="hidden" value="bar" name="trans[fr][files][]">', Asset::typeField('bar', 'fr')); } + /** + * @test + */ + public function it_can_prefix_the_conversions_with_the_filename(){ + $asset = Asset::upload(UploadedFile::fake()->image('image.png')); + + config(['assetlibrary.conversionPrefix' => true]); + + $this->assertEquals('/media/1/conversions/image_thumb.png', $asset->getFileUrl('image_thumb')); + } + // // /** // * @test
Added option to add file name as conversion prefix
thinktomorrow_assetlibrary
train
17df8abf503c16348d53e0843ae9d541cf8fc85f
diff --git a/installation-bundle/src/HttpKernel/InstallationKernel.php b/installation-bundle/src/HttpKernel/InstallationKernel.php index <HASH>..<HASH> 100644 --- a/installation-bundle/src/HttpKernel/InstallationKernel.php +++ b/installation-bundle/src/HttpKernel/InstallationKernel.php @@ -118,10 +118,7 @@ class InstallationKernel extends \AppKernel $context = new RequestContext(); $context->fromRequest(Request::createFromGlobals()); - $context->setBaseUrl(''); - $generator = new UrlGenerator($routes, $context); - - return $generator->generate('contao_install'); + return str_replace('/install.php/', '/', (new UrlGenerator($routes, $context))->generate('contao_install')); } }
[Installation] Support calling the install tool with the /web fragment (see #<I>).
contao_contao
train
7b4146e464a2a346205d8dd09b7e9de732e34c6b
diff --git a/docs/List.md b/docs/List.md index <HASH>..<HASH> 100644 --- a/docs/List.md +++ b/docs/List.md @@ -22,7 +22,7 @@ Here are all the props accepted by the `<List>` component: * [`defaultSort`](#default-sort-field) * [`Actions`](#actions) * [`Filter`](#filters) -* [`Pagination`](#pagination) +* [`pagination`](#pagination) Here is the minimal code necessary to display a list of posts: @@ -170,7 +170,7 @@ It does so by inspecting its `context` prop. ### Pagination -You can replace the default pagination component by your own, using the `Pagination` prop. The pagination component receives the current page, the number of records per page, the total number of records, as well as a `setPage()` function that changes the page. +You can replace the default pagination element by your own, using the `pagination` prop. The pagination element receives the current page, the number of records per page, the total number of records, as well as a `setPage()` function that changes the page. So if you want to replace the default pagination by a "<previous - next>" pagination, create a pagination component like the following: @@ -198,7 +198,7 @@ const PostPagination = ({ page, perPage, total, setPage }) => { } export const PostList = (props) => ( - <List {...props} Pagination={PostPagination}> + <List {...props} pagination={<PostPagination />}> ... </List> ); diff --git a/example/comments.js b/example/comments.js index <HASH>..<HASH> 100644 --- a/example/comments.js +++ b/example/comments.js @@ -74,7 +74,7 @@ CommentGrid.defaultProps = { }; export const CommentList = (props) => ( - <List title="All comments" {...props} perPage={6} Filter={CommentFilter} Pagination={CommentPagination}> + <List title="All comments" {...props} perPage={6} Filter={CommentFilter} pagination={<CommentPagination />}> <CommentGrid /> </List> ); diff --git a/src/mui/list/List.js b/src/mui/list/List.js index <HASH>..<HASH> 100644 --- a/src/mui/list/List.js +++ b/src/mui/list/List.js @@ -30,7 +30,7 @@ const filterFormName = 'filterForm'; * - defaultSort * - Actions * - Filter - * - Pagination + * - pagination * * @example * const PostFilter = (props) => ( @@ -149,7 +149,7 @@ export class List extends Component { } render() { - const { Filter, Pagination = DefaultPagination, Actions = DefaultActions, resource, hasCreate, title, data, ids, total, children, isLoading } = this.props; + const { Filter, pagination = <DefaultPagination />, Actions = DefaultActions, resource, hasCreate, title, data, ids, total, children, isLoading } = this.props; const query = this.getQuery(); const filterValues = query.filter; const basePath = this.getBasePath(); @@ -172,7 +172,13 @@ export class List extends Component { basePath, setSort: this.setSort, })} - <Pagination resource={resource} page={parseInt(query.page, 10)} perPage={parseInt(query.perPage, 10)} total={total} setPage={this.setPage} /> + {React.cloneElement(pagination, { + resource, + total, + page: parseInt(query.page, 10), + perPage: parseInt(query.perPage, 10), + setPage: this.setPage, + })} </Card> ); } @@ -185,10 +191,7 @@ List.propTypes = { PropTypes.func, PropTypes.string, ]), - Pagination: PropTypes.oneOfType([ - PropTypes.func, - PropTypes.string, - ]), + pagination: PropTypes.element, Actions: PropTypes.oneOfType([ PropTypes.func, PropTypes.string,
Replace Pagination prop component by pagination prop element in List
marmelab_react-admin
train
bb1757b19588c141049aa4f1d4f04f68ccf5c852
diff --git a/zap/src/main/dist/db/hsqldb.properties b/zap/src/main/dist/db/hsqldb.properties index <HASH>..<HASH> 100644 --- a/zap/src/main/dist/db/hsqldb.properties +++ b/zap/src/main/dist/db/hsqldb.properties @@ -180,6 +180,7 @@ alerttag.field.alertid = ALERT_ID alerttag.field.key = KEY alerttag.field.value = VALUE alerttag.ps.createtable = CREATE CACHED TABLE alert_tag (tag_id bigint generated by default as identity (start with 1) primary key, alert_id bigint not null, key varchar(1024) default '' not null, value nvarchar(4000) default '' not null) +alerttag.ps.indexalertid = CREATE INDEX alert_id_index ON alert_tag (alert_id) alerttag.ps.readbytagid = SELECT * FROM alert_tag WHERE tag_id = ? alerttag.ps.readbyalertidtagkey = SELECT * FROM alert_tag WHERE alert_id = ? AND key = ? alerttag.ps.insertorupdate = MERGE INTO alert_tag AS tag USING (VALUES(?, ?, ?)) AS v(aid, key, val) ON tag.alert_id = v.aid AND tag.key = v.key WHEN MATCHED AND tag.value <> v.val THEN UPDATE SET tag.value = v.val WHEN NOT MATCHED THEN INSERT (alert_id, key, value) VALUES (v.aid, v.key, v.val) diff --git a/zap/src/main/java/org/zaproxy/zap/db/paros/ParosTableAlertTag.java b/zap/src/main/java/org/zaproxy/zap/db/paros/ParosTableAlertTag.java index <HASH>..<HASH> 100644 --- a/zap/src/main/java/org/zaproxy/zap/db/paros/ParosTableAlertTag.java +++ b/zap/src/main/java/org/zaproxy/zap/db/paros/ParosTableAlertTag.java @@ -62,6 +62,10 @@ public class ParosTableAlertTag extends ParosAbstractTable implements TableAlert + ")"); } + if (!DbUtils.hasIndex(conn, "ALERT_TAG", "ALERT_ID_INDEX")) { + DbUtils.execute(conn, "CREATE INDEX alert_id_index ON alert_tag (alert_id)"); + } + psReadByTagId = conn.prepareStatement("SELECT * FROM alert_tag WHERE tag_id = ?"); psReadByAlertIdTagKey = conn.prepareStatement("SELECT * FROM alert_tag WHERE alert_id = ? AND key = ?"); diff --git a/zap/src/main/java/org/zaproxy/zap/db/sql/SqlTableAlertTag.java b/zap/src/main/java/org/zaproxy/zap/db/sql/SqlTableAlertTag.java index <HASH>..<HASH> 100644 --- a/zap/src/main/java/org/zaproxy/zap/db/sql/SqlTableAlertTag.java +++ b/zap/src/main/java/org/zaproxy/zap/db/sql/SqlTableAlertTag.java @@ -46,6 +46,9 @@ public class SqlTableAlertTag extends SqlAbstractTable implements TableAlertTag if (!DbUtils.hasTable(conn, TABLE_NAME)) { DbUtils.execute(conn, DbSQL.getSQL("alerttag.ps.createtable")); } + if (!DbUtils.hasIndex(conn, "ALERT_TAG", "ALERT_ID_INDEX")) { + DbUtils.execute(conn, DbSQL.getSQL("alerttag.ps.indexalertid")); + } } catch (SQLException e) { throw new DatabaseException(e); }
Index Alert ID in the Alert Tags Table
zaproxy_zaproxy
train
73c0625969e55239e53014e2a7ae1fc70400d45c
diff --git a/src/Standards/BestIt/CodeSniffer/File.php b/src/Standards/BestIt/CodeSniffer/File.php index <HASH>..<HASH> 100644 --- a/src/Standards/BestIt/CodeSniffer/File.php +++ b/src/Standards/BestIt/CodeSniffer/File.php @@ -21,32 +21,6 @@ use function func_get_args; class File extends AbstractFileDecorator { /** - * File constructor. - * - * @param BaseFile $baseFile CodeSniffer file - */ - public function __construct(BaseFile $baseFile) - { - parent::__construct($baseFile); - - $this->tokens = $baseFile->getTokens(); - - $this->addPointerToTokens(); - } - - /** - * Adds the pointer to all token data arrays. - * - * @return void - */ - private function addPointerToTokens(): void - { - foreach ($this->tokens as $tokenPtr => &$token) { - $token['pointer'] = $tokenPtr; - } - } - - /** * Returns the position of the next specified token(s). * * If a value is specified, the next token of the specified type(s) diff --git a/src/Standards/BestIt/CodeSniffer/Helper/DocTagHelper.php b/src/Standards/BestIt/CodeSniffer/Helper/DocTagHelper.php index <HASH>..<HASH> 100644 --- a/src/Standards/BestIt/CodeSniffer/Helper/DocTagHelper.php +++ b/src/Standards/BestIt/CodeSniffer/Helper/DocTagHelper.php @@ -53,11 +53,12 @@ class DocTagHelper * @param array $commentStartToken The start token of the comment. * @param File $file The php cs file * @param int $stackPtr Pointer to the token which is to be listened + * @param array $tokens Another token array if we want to overwrite them, */ - public function __construct(array $commentStartToken, File $file, int $stackPtr) + public function __construct(array $commentStartToken, File $file, int $stackPtr, array $tokens = []) { $this->file = $file; - $this->tokens = $file->getTokens(); + $this->tokens = $tokens ?: $file->getTokens(); $this->stackPtr = $stackPtr; $this->commentStartToken = $commentStartToken; } diff --git a/src/Standards/BestIt/Sniffs/AbstractSniff.php b/src/Standards/BestIt/Sniffs/AbstractSniff.php index <HASH>..<HASH> 100644 --- a/src/Standards/BestIt/Sniffs/AbstractSniff.php +++ b/src/Standards/BestIt/Sniffs/AbstractSniff.php @@ -50,6 +50,18 @@ abstract class AbstractSniff implements Sniff protected $tokens; /** + * Adds the pointer to all token data arrays. + * + * @return void + */ + protected function addPointerToTokens(): void + { + foreach ($this->tokens as $tokenPtr => &$token) { + $token['pointer'] = $tokenPtr; + } + } + + /** * Returns true if the requirements for this sniff are met. * * @return bool Are the requirements met and the sniff should proceed? diff --git a/src/Standards/BestIt/Sniffs/DocTags/ParamTagSniff.php b/src/Standards/BestIt/Sniffs/DocTags/ParamTagSniff.php index <HASH>..<HASH> 100644 --- a/src/Standards/BestIt/Sniffs/DocTags/ParamTagSniff.php +++ b/src/Standards/BestIt/Sniffs/DocTags/ParamTagSniff.php @@ -322,6 +322,8 @@ class ParamTagSniff extends AbstractTagSniff { parent::setUp(); + $this->addPointerToTokens(); + $this->argumentToken = null; } } diff --git a/src/Standards/BestIt/Sniffs/DocTags/TagSortingSniff.php b/src/Standards/BestIt/Sniffs/DocTags/TagSortingSniff.php index <HASH>..<HASH> 100644 --- a/src/Standards/BestIt/Sniffs/DocTags/TagSortingSniff.php +++ b/src/Standards/BestIt/Sniffs/DocTags/TagSortingSniff.php @@ -306,7 +306,9 @@ class TagSortingSniff extends AbstractSniff */ protected function setUp(): void { - $this->docTagHelper = new DocTagHelper($this->token, $this->file, $this->stackPos); + $this->addPointerToTokens(); + + $this->docTagHelper = new DocTagHelper($this->token, $this->file, $this->stackPos, $this->tokens); } /**
PHPCS-<I> Moved the token-pointer-marker only in the sniffs, in which they are needed
bestit_PHP_CodeSniffer
train
3318d863e27480dface8c19414f6309b73336caa
diff --git a/cdpybio/cghub.py b/cdpybio/cghub.py index <HASH>..<HASH> 100644 --- a/cdpybio/cghub.py +++ b/cdpybio/cghub.py @@ -331,7 +331,7 @@ class ReadsFromIntervalsEngine: self.in_queue.put('STOP') while (sum([p.is_alive() for p in self.processes]) > 0 and - not self.stop_event.is_set()): + not self._stop_event.is_set()): while True: try: bam = self.out_queue.get(timeout=self.sleeptime) @@ -344,6 +344,9 @@ class ReadsFromIntervalsEngine: inspect.ismethod(self.engine_fnc)): self.engine_fnc() + if (type(self.engine_fnc) == types.FunctionType or + inspect.ismethod(self.engine_fnc)): + self.engine_fnc() self.stop() def _reads_from_intervals_worker(self, in_queue, out_queue): @@ -476,7 +479,7 @@ class FLCVariantCallingEngine(ReadsFromIntervalsEngine): # TumorNormalVariantCalls that we have begun calling variants for. self.variant_calling_started = [] # Directory that holds information about this variant calling run. - self.infodir = os.path.join(bam_outdir, + self.infodir = os.path.join(variant_outdir, '{}_variant_calling_info'.format(self.name)) # HTML file that provides the status of the variant calling run in # realtime. @@ -509,29 +512,30 @@ class FLCVariantCallingEngine(ReadsFromIntervalsEngine): for these intervals, make a directory to hold some information about this variant calling run and populate it. """ - if os.path.exists(self.html_status): - sys.exit(1) # Not tested or fully implemented yet - self._exist_setup() - else: - self._not_exist_setup() - - def _exist_setup(self): - """Set up the engine given that an engine has already worked on these - samples and intervals in the past""" - # Update analysis ids based on which samples have already been - # completed. - import pandas as pd - df = pd.read_html(self.html_status)[0] - for vc in self.tumor_normal_variant_calls: - t = vc.tumor_id - n = vc.normal_id - ind = vc.name - if df.ix[ind, 'tumor reads'] == 'finished': - self.analysis_ids.remove(t) - if df.ix[ind, 'normal reads'] == 'finished': - self.analysis_ids.remove(n) - if df.ix[ind, 'variant calling'] == 'finished': - self.variant_calling_started.append(vc) + # TODO: update ability to restart engine. + # if os.path.exists(self.html_status): + # self._exist_setup() + # else: + # self._not_exist_setup() + self._not_exist_setup() + + # def _exist_setup(self): + # """Set up the engine given that an engine has already worked on these + # samples and intervals in the past""" + # # Update analysis ids based on which samples have already been + # # completed. + # import pandas as pd + # df = pd.read_html(self.html_status)[0] + # for vc in self.tumor_normal_variant_calls: + # t = vc.tumor_id + # n = vc.normal_id + # ind = vc.name + # if df.ix[ind, 'tumor reads'] == 'finished': + # self.analysis_ids.remove(t) + # if df.ix[ind, 'normal reads'] == 'finished': + # self.analysis_ids.remove(n) + # if df.ix[ind, 'variant calling'] == 'finished': + # self.variant_calling_started.append(vc) def _not_exist_setup(self): import pandas as pd @@ -552,9 +556,11 @@ class FLCVariantCallingEngine(ReadsFromIntervalsEngine): columns = ['tumor reads', 'normal reads', 'variant calling'] df = pd.DataFrame(index=index, columns=columns) df.to_html(self.html_status, na_rep='') - self._update_html_status() + # self.update_html_status() - def _update_html_status(self): + def update_html_status(self): + # TODO: I'll likely need updates here for restarting a job later and + # picking up where the last engine left off. import pandas as pd df = pd.read_html(self.html_status, index_col=0, header=0)[0] @@ -614,14 +620,15 @@ class FLCVariantCallingEngine(ReadsFromIntervalsEngine): if (type(self.variant_engine_fnc) == types.FunctionType or inspect.ismethod(self.variant_engine_fnc)): self.variant_engine_fnc() - self._update_html_status() + self.update_html_status() # If the engine is done, wait until all variant calls are done. - if len(self.processes) == 0 and self._stop_event.is_set(): + if (self._stop_event.is_set() or + sum([p.is_alive() for p in self.processes]) == 0): df = pd.read_html(self.html_status, index_col=0, header=0)[0] while set(df['variant calling']) != set(['finished']): - time.sleep(self.sleeptime) - self._update_html_status() + time.sleep(self.sleeptime) + self.update_html_status() df = pd.read_html(self.html_status, index_col=0, header=0)[0]
Updates, bug fixes Variant calling worked for small number of samples/intervals, now trying for larger number of intervals.
cdeboever3_cdpybio
train
15bdf92c0e03eb223a67c988cf998ea2a92a5f18
diff --git a/docker/docker_client.go b/docker/docker_client.go index <HASH>..<HASH> 100644 --- a/docker/docker_client.go +++ b/docker/docker_client.go @@ -85,6 +85,7 @@ type dockerClient struct { registry string client *http.Client insecureSkipTLSVerify bool + // The following members are not set by newDockerClient and must be set by callers if needed. username string password string @@ -96,12 +97,12 @@ type dockerClient struct { scheme string // Empty value also used to indicate detectProperties() has not yet succeeded. challenges []challenge supportsSignatures bool - // Private state for setupRequestAuth - tokenCache map[string]bearerToken + + // Private state for setupRequestAuth (key: string, value: bearerToken) + tokenCache sync.Map // detectPropertiesError caches the initial error. detectPropertiesError error - // detectPropertiesOnce is used to execuute detectProperties() at most once in - // in makeRequest(). + // detectPropertiesOnce is used to execuute detectProperties() at most once in in makeRequest(). detectPropertiesOnce sync.Once } @@ -268,7 +269,6 @@ func newDockerClient(sys *types.SystemContext, registry, reference string) (*doc registry: registry, client: &http.Client{Transport: tr}, insecureSkipTLSVerify: skipVerify, - tokenCache: map[string]bearerToken{}, }, nil } @@ -479,14 +479,18 @@ func (c *dockerClient) setupRequestAuth(req *http.Request) error { cacheKey = fmt.Sprintf("%s:%s", c.extraScope.remoteName, c.extraScope.actions) scopes = append(scopes, *c.extraScope) } - token, ok := c.tokenCache[cacheKey] - if !ok || time.Now().After(token.expirationTime) { + var token bearerToken + t, inCache := c.tokenCache.Load(cacheKey) + if inCache { + token = t.(bearerToken) + } + if !inCache || time.Now().After(token.expirationTime) { t, err := c.getBearerToken(req.Context(), challenge, scopes) if err != nil { return err } token = *t - c.tokenCache[cacheKey] = token + c.tokenCache.Store(cacheKey, token) } req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token.Token)) return nil
dockerClient: make tokenCache thread safe Make tokenCache thread safe by turning it into a `sync.Map` suitable for concurrent reads and writes.
containers_image
train
c4175be7a30d38bdf63c7c637fc63c0ba984b91d
diff --git a/tests/framework/db/CommandTest.php b/tests/framework/db/CommandTest.php index <HASH>..<HASH> 100644 --- a/tests/framework/db/CommandTest.php +++ b/tests/framework/db/CommandTest.php @@ -436,12 +436,10 @@ SQL; * @expectedException \yii\base\InvalidParamException * @expectedExceptionMessage Expected select query object with enumerated (named) parameters */ - public function testInsertSelectFailed($invalidSelectCulumns) + public function testInsertSelectFailed($invalidSelectColumns) { - $this->setExpectedException('\yii\base\InvalidParamException'); - $query = new \yii\db\Query(); - $query->select(['*'])->from('{{customer}}'); + $query->select($invalidSelectColumns)->from('{{customer}}'); $db = $this->getConnection(); $command = $db->createCommand();
Adjusted command test for incorrect inserts to use data provider
yiisoft_yii2
train
455c83d01a210dff9a4ed288f2c390d2b74e37c5
diff --git a/src/SxBootstrap/View/Helper/Bootstrap/Button.php b/src/SxBootstrap/View/Helper/Bootstrap/Button.php index <HASH>..<HASH> 100644 --- a/src/SxBootstrap/View/Helper/Bootstrap/Button.php +++ b/src/SxBootstrap/View/Helper/Bootstrap/Button.php @@ -41,6 +41,17 @@ class Button extends AbstractElementHelper protected function initFormElement(ButtonElement $element) { $this->getElement()->addAttributes($element->getAttributes()); + + $value = $element->getValue(); + $label = $element->getLabel(); + + if (!empty($label)) { + $this->setLabel($label); + } + + if (!empty($value)) { + $this->addAttribute('value', $value); + } } /** diff --git a/src/SxBootstrap/View/Helper/Bootstrap/Form/Button.php b/src/SxBootstrap/View/Helper/Bootstrap/Form/Button.php index <HASH>..<HASH> 100644 --- a/src/SxBootstrap/View/Helper/Bootstrap/Form/Button.php +++ b/src/SxBootstrap/View/Helper/Bootstrap/Form/Button.php @@ -2,6 +2,8 @@ namespace SxBootstrap\View\Helper\Bootstrap\Form; +use Zend\Form\ElementInterface; + class Button extends Input { /** @@ -15,4 +17,18 @@ class Button extends Input { return parent::__invoke($elementType)->type('button'); } + + /** + * {@InheritDoc} + */ + protected function initFormElement(ElementInterface $element) + { + $value = $element->getValue(); + + if (!empty($value)) { + $this->addAttribute('value', $this->translate($value)); + } + + return parent::initFormElement($element); + } } diff --git a/src/SxBootstrap/View/Helper/Bootstrap/Form/Submit.php b/src/SxBootstrap/View/Helper/Bootstrap/Form/Submit.php index <HASH>..<HASH> 100644 --- a/src/SxBootstrap/View/Helper/Bootstrap/Form/Submit.php +++ b/src/SxBootstrap/View/Helper/Bootstrap/Form/Submit.php @@ -2,6 +2,8 @@ namespace SxBootstrap\View\Helper\Bootstrap\Form; +use Zend\Form\ElementInterface; + class Submit extends Input { @@ -20,6 +22,20 @@ class Submit extends Input /** * {@InheritDoc} */ + protected function initFormElement(ElementInterface $element) + { + $value = $element->getValue(); + + if (!empty($value)) { + $this->value($value); + } + + return parent::initFormElement($element); + } + + /** + * {@InheritDoc} + */ public function value($value) { return parent::value($this->translate($value));
Added support for values on form controls.
SpoonX_SxBootstrap
train
b40379eaf229e7ffc7580def57ee1fad46080261
diff --git a/stanza/utils/conll.py b/stanza/utils/conll.py index <HASH>..<HASH> 100644 --- a/stanza/utils/conll.py +++ b/stanza/utils/conll.py @@ -105,7 +105,7 @@ class CoNLL: if input_str: infile = io.StringIO(input_str) else: - infile = open(input_file) + infile = open(input_file, encoding='utf-8') doc_conll, doc_comments = CoNLL.load_conll(infile, ignore_gapping) doc_dict = CoNLL.convert_conll(doc_conll) return doc_dict, doc_comments @@ -207,5 +207,5 @@ class CoNLL: def write_doc2conll(doc, filename): """ Writes the doc as a conll file to the given filename """ - with open(filename, 'w') as outfile: + with open(filename, 'w', encoding='utf-8') as outfile: outfile.write(CoNLL.doc2conll_text(doc))
Add encoding=utf-8 to a couple more relevant places
stanfordnlp_stanza
train
4ebfc1af92e3cd9324e5747e7ae70a5a46c3e069
diff --git a/bin/cli.js b/bin/cli.js index <HASH>..<HASH> 100644 --- a/bin/cli.js +++ b/bin/cli.js @@ -15,22 +15,22 @@ const argv = require("yargs") .option("filename", { describe: "Output file name", string: true, - default: "./stats.html" + default: "./stats.html", }) .option("title", { describe: "Output file title", string: true, - default: "RollUp Visualizer" + default: "RollUp Visualizer", }) .option("template", { describe: "Template type", string: true, choices: TEMPLATE, - default: "treemap" + default: "treemap", }) .option("sourcemap", { describe: "Provided files is sourcemaps", - boolean: true + boolean: true, }) .help().argv; @@ -42,7 +42,7 @@ const runForPluginJson = async ({ title, template, filename }, files) => { } const fileContents = await Promise.all( - files.map(async file => { + files.map(async (file) => { const textContent = await fs.readFile(file, { encoding: "utf-8" }); const jsonContent = JSON.parse(textContent); return [file, jsonContent]; @@ -51,7 +51,7 @@ const runForPluginJson = async ({ title, template, filename }, files) => { const tree = { name: "root", - children: [] + children: [], }; const nodes = Object.create(null); let links = []; @@ -75,20 +75,27 @@ const runForPluginJson = async ({ title, template, filename }, files) => { links = links.concat(fileContent.links); } - const data = { version: JSON_VERSION, tree, links, nodes }; + const data = { + version: JSON_VERSION, + tree, + links, + nodes, + env: fileContents[0].env, + options: fileContents[0].options, + }; const fileContent = await buildStats({ title, data, template, - chartParameters: {} + chartParameters: {}, }); await fs.mkdir(path.dirname(filename), { recursive: true }); await fs.writeFile(filename, fileContent); }; -runForPluginJson(argv, listOfFiles).catch(err => { +runForPluginJson(argv, listOfFiles).catch((err) => { warn(err.message); process.exit(1); });
Copy env and options from files
btd_rollup-plugin-visualizer
train
d3603a85e57ee34eb52c6abd5a2dd37a721c66a7
diff --git a/rb/spec/integration/selenium/webdriver/options_spec.rb b/rb/spec/integration/selenium/webdriver/options_spec.rb index <HASH>..<HASH> 100644 --- a/rb/spec/integration/selenium/webdriver/options_spec.rb +++ b/rb/spec/integration/selenium/webdriver/options_spec.rb @@ -39,7 +39,8 @@ module Selenium expect(driver.manage.logs.available_types).to include(:browser, :har) end - it 'can get the browser log', only: {browser: %i[firefox ff_esr]} do + # TODO (Alex): Investigate why this spec passes on macOS but fails on Linux. + it 'can get the browser log', only: {browser: %i[firefox ff_esr]}, except: {browser: :chrome, platform: :linux} do driver.navigate.to url_for('simpleTest.html') entries = driver.manage.logs.get(:browser) diff --git a/rb/spec/integration/selenium/webdriver/target_locator_spec.rb b/rb/spec/integration/selenium/webdriver/target_locator_spec.rb index <HASH>..<HASH> 100644 --- a/rb/spec/integration/selenium/webdriver/target_locator_spec.rb +++ b/rb/spec/integration/selenium/webdriver/target_locator_spec.rb @@ -239,7 +239,7 @@ module Selenium expect(driver.title).to eq('Testing Alerts') end - it 'allows the user to dismiss an alert', except: {browser: :chrome, platform: :macosx} do + it 'allows the user to dismiss an alert' do driver.navigate.to url_for('alerts.html') driver.find_element(id: 'alert').click @@ -307,7 +307,7 @@ module Selenium expect { driver.title }.to raise_error(Selenium::WebDriver::Error::UnhandledAlertError) end - it 'raises an UnhandledAlertError if an alert has not been dealt with', only: {browser: :ff_esr} do + it 'raises an UnhandledAlertError if an alert has not been dealt with', only: {browser: %i[chrome ff_esr]} do driver.navigate.to url_for('alerts.html') driver.find_element(id: 'alert').click wait_for_alert
Clean up guards for specs passing against Chrome
SeleniumHQ_selenium
train
0221fadc6644e1b1a7d963c10eaaa54cc70b70d0
diff --git a/src/test/java/integration/ActionDoIT.java b/src/test/java/integration/ActionDoIT.java index <HASH>..<HASH> 100644 --- a/src/test/java/integration/ActionDoIT.java +++ b/src/test/java/integration/ActionDoIT.java @@ -743,11 +743,12 @@ public class ActionDoIT extends WebBase { // use this object to manipulate the app App app = this.apps.get(); // perform some actions - app.newElement(Locator.ID, "input_box").type("Text"); - app.newElement(Locator.ID, "input_box").assertEquals().value("Text"); - app.newElement(Locator.ID, "input_box").clear(); - app.acceptAlert(); - app.newElement(Locator.ID, "input_box").assertEquals().value(""); + app.newElement(Locator.ID, "delayed_enable_button").click(); + app.wait(5.0); + app.newElement(Locator.ID, "delayed_input").type("Text"); + app.newElement(Locator.ID, "delayed_input").assertEquals().value("Text"); + app.newElement(Locator.ID, "delayed_input").clear(); + app.newElement(Locator.ID, "delayed_input").assertEquals().value(""); // verify no issues finish(); }
Fixing test so it runs in HTML and browser
Coveros_selenified
train
d34279accec818ffed2cb7ae8820fbb6b516f7ad
diff --git a/lib/overcommit/hook_signer.rb b/lib/overcommit/hook_signer.rb index <HASH>..<HASH> 100644 --- a/lib/overcommit/hook_signer.rb +++ b/lib/overcommit/hook_signer.rb @@ -49,7 +49,8 @@ module Overcommit end def signable_file?(file) - file.start_with?(".#{File::SEPARATOR}") && + sep = Overcommit::OS.windows? ? '\\' : File::SEPARATOR + file.start_with?(".#{sep}") && Overcommit::GitRepo.tracked?(file) end
Check that script starts with '.\' on Windows
sds_overcommit
train
3b8982c6d6121d51c900a4a0317469814f839ec5
diff --git a/src/block.js b/src/block.js index <HASH>..<HASH> 100644 --- a/src/block.js +++ b/src/block.js @@ -1,25 +1,24 @@ -/* eslint-disable camelcase */ +/* eslint-disable camelcase, key-spacing */ const ffi = require('ffi'); -const struct = require('ref-struct'); +const structs = require('./structs'); +const {pointer, int32, ulonglong} = require('./types'); const runtime = require('./runtime'); const {coerceType} = require('./type-encodings'); -const __block_literal = struct({ - isa: 'pointer', - flags: 'int32', - reserved: 'int32', - invoke: 'pointer', - descriptor: 'pointer' -}); +const _NSConcreteGlobalBlock = runtime.getSymbol('_NSConcreteGlobalBlock'); -const __block_descriptor = struct({ - reserved: 'ulonglong', - Block_size: 'ulonglong' +const block_t = structs.defineStruct(null, { + isa: pointer, + flags: int32, + reserved: int32, + invoke: pointer, + descriptor: pointer }); -const descriptor = new __block_descriptor(); -descriptor.reserved = 0; -descriptor.Block_size = __block_literal.size; +const descriptor = structs.defineStruct(null, { + reserved: ulonglong, + block_size: ulonglong +}).new(0, block_t.size); class Block { constructor(fn, returnType, argumentTypes, skipBlockArgument = true) { @@ -40,15 +39,13 @@ class Block { } makeBlock() { - const block = new __block_literal(); - - block.isa = runtime.getSymbol('_NSConcreteGlobalBlock'); - block.flags = 1 << 29; - block.reserved = 0; - block.invoke = this.getFunctionPointer(); - block.descriptor = descriptor.ref(); - - return block.ref(); + return block_t.new(structs.CompoundInit, { + isa: _NSConcreteGlobalBlock, + flags: 1 << 29, + reserved: 0, + invoke: this.getFunctionPointer(), + descriptor: descriptor.ref() + }).ref(); } getFunctionPointer() { diff --git a/src/structs.js b/src/structs.js index <HASH>..<HASH> 100644 --- a/src/structs.js +++ b/src/structs.js @@ -1,5 +1,6 @@ const struct = require('ref-struct'); +const CompoundInit = Symbol('structs.CompoundInit'); const structs = {}; const createStructInitializer = (name, StructType) => { @@ -12,27 +13,38 @@ const createStructInitializer = (name, StructType) => { return new StructType(); } - if (fields.length !== args.length) { - throw new TypeError(`Invalid number of fields passed to '${name}' constructor. Expected ${fields.length}, got ${args.length}`); + const retval = new StructType(); + + if (args.length === 2 && args[0] === CompoundInit) { + for (const [key, value] of Object.entries(args[1])) { + retval[key] = value; + } + } else { // Array-like init + if (fields.length !== args.length) { + throw new TypeError(`Invalid number of fields passed to '${name}' constructor. Expected ${fields.length}, got ${args.length}`); + } + args.forEach((arg, index) => { + retval[fields[index]] = arg; + }); } - const value = new StructType(); - args.forEach((arg, index) => { - value[fields[index]] = arg; - }); - return value; + return retval; }; return StructType; }; module.exports = { + CompoundInit, + defineStruct: (name, fields) => { if (name in structs) { throw new Error(`Struct '${name}' is already defined`); } const type = struct(fields); - structs[name] = type; + if (name !== null) { + structs[name] = type; + } return createStructInitializer(name, type); }, diff --git a/src/type-encodings.js b/src/type-encodings.js index <HASH>..<HASH> 100644 --- a/src/type-encodings.js +++ b/src/type-encodings.js @@ -250,6 +250,9 @@ module.exports = { coerceType: type => { if (typeof type === 'string') { + if (type === 'pointer') { + return ref.refType(ref.types.void); + } return parser.parse(type).toRefType(); } else if (typeof type === 'object') { return type; diff --git a/src/types.js b/src/types.js index <HASH>..<HASH> 100644 --- a/src/types.js +++ b/src/types.js @@ -1,12 +1,13 @@ const ref = require('ref'); const structs = require('./structs'); -const id = ref.coerceType('pointer'); +const pointer = ref.refType(ref.types.void); +const id = pointer; const NSInteger = ref.coerceType('int64'); const NSUInteger = ref.coerceType('uint64'); module.exports = Object.assign({}, ref.types, { - id, NSInteger, NSUInteger, + pointer, id, NSInteger, NSUInteger, NSRange: structs.defineStruct('_NSRange', { location: NSUInteger,
added a struct compound init option
lukaskollmer_objc
train
19d557a7b71273fe78b0a2d9e2f00ea7af7d9002
diff --git a/scripts/docs.js b/scripts/docs.js index <HASH>..<HASH> 100644 --- a/scripts/docs.js +++ b/scripts/docs.js @@ -20,7 +20,7 @@ const main = async () => { const packages = await globPromise('packages/*') await fs.mkdirp(path.resolve(docsFolder, 'api')) for (let pkg of packages) { - if (pkg === 'cozy-client') { + if (pkg === 'packages/cozy-client') { continue // documentation for cozy-client is made via typedoc } const files = await globPromise(`${pkg}/src/**/*.js*`, {
fix: Typo, don't generate docs from cozy-client with jsdocs
cozy_cozy-client
train
78b01ae172b8118bbd8076b66de0207dab4950b2
diff --git a/test/auto-block.js b/test/auto-block.js index <HASH>..<HASH> 100644 --- a/test/auto-block.js +++ b/test/auto-block.js @@ -20,7 +20,7 @@ fixture.listen(10000); test('fixture can verify the torrent', function(t) { t.plan(2); fixture.on('ready', function() { - t.ok(true, 'should be ready'); + t.ok(true, 'seed should be ready'); t.deepEqual(fixture.bitfield.buffer.toString('hex'), 'c0', 'should verify all the pieces'); }); }); @@ -29,7 +29,7 @@ test('peer should be blocked on bad piece', function(t) { t.plan(5); fixture.store.write(0, new Buffer(1 << 14), function() { - t.ok(true, 'should be written'); + t.ok(true, 'bad piece should be written'); var engine = torrents(torrent, { dht: false, @@ -40,19 +40,20 @@ test('peer should be blocked on bad piece', function(t) { engine.on('blocked-peer', function(addr, reason) { t.equal(addr, '127.0.0.1:10000'); t.equal(reason, 'Blocked'); - engine.destroy(t.ok.bind(t, true, 'should be destroyed')); + engine.destroy(t.ok.bind(t, true, 'peer should be destroyed')); }); engine.connect('127.0.0.1:10000'); engine.on('ready', function() { - t.ok(true, 'should be ready'); + t.ok(true, 'peer should be ready'); engine.files[0].select(); + fixture.swarm.wires[0].unchoke(); }); }); }); test('cleanup', function(t) { t.plan(1); - fixture.destroy(t.ok.bind(t, true, 'should be destroyed')); + fixture.destroy(t.ok.bind(t, true, 'seed should be destroyed')); }); \ No newline at end of file
unchoke the peer to speed up tests
mafintosh_torrent-stream
train
39ffef6eecac0c1878af113f4add3d18a866e414
diff --git a/core/src/playn/core/TextLayout.java b/core/src/playn/core/TextLayout.java index <HASH>..<HASH> 100644 --- a/core/src/playn/core/TextLayout.java +++ b/core/src/playn/core/TextLayout.java @@ -35,13 +35,13 @@ public interface TextLayout { /** The bounds of the text on the given line. */ Rectangle lineBounds(int line); - /** The space from the top of a line of text to the baseline. */ + /** The number of pixels from the top of a line of text to the baseline. */ float ascent (); - /** The space from the baseline to the bottom of a line of text. */ + /** The number of pixels from the baseline to the bottom of a line of text. */ float descent (); - /** The space between the bottom of one line of text and the top of the next line of text. */ + /** The number of pixels between the bottom of one line of text and the top of the next. */ float leading (); /** The {@link TextFormat} used to lay out this text. */
Clarify the metrics docs.
threerings_playn
train
73b6e6f36d4a154fdfb9da816b8d8e83dcfa9048
diff --git a/src/InfoViz/Native/MutualInformationDiagram/index.js b/src/InfoViz/Native/MutualInformationDiagram/index.js index <HASH>..<HASH> 100644 --- a/src/InfoViz/Native/MutualInformationDiagram/index.js +++ b/src/InfoViz/Native/MutualInformationDiagram/index.js @@ -659,7 +659,6 @@ function informationDiagram(publicAPI, model) { .classed('group', true) .classed(style.group, true); - // Add the group arc. groupEnter .append('path') @@ -669,7 +668,6 @@ function informationDiagram(publicAPI, model) { .append('path') .classed(style.mouseArcHidden, true); - // Add a text label. const groupText = groupEnter .append('text') @@ -677,18 +675,10 @@ function informationDiagram(publicAPI, model) { .attr('dy', 15); if (!model.textLengthMap) model.textLengthMap = {}; - // pull a stunt to measure text length - use a straight path, then switch to the real curved one. - const textPath = groupText + groupText .append('textPath') - .attr('xlink:href', '#straight-text-path') .attr('startOffset', '25%') - .text((d, i) => model.mutualInformationData.vmap[i].name) - .each(function textLen(d, i) { - model.textLengthMap[model.mutualInformationData.vmap[i].name] = this.getComputedTextLength(); - }); - - textPath - .attr('xlink:href', (d, i) => `#${model.instanceID}-group${i}`); + .text((d, i) => model.mutualInformationData.vmap[i].name); // enter + update items. const groupPath = group.select('path') @@ -696,18 +686,30 @@ function informationDiagram(publicAPI, model) { group.select(`.${style.jsMouseArc}`) .attr('d', insideArc); - // Remove the labels that don't fit, or shorten label, using ... - group - .select('text').select('textPath') + const textPath = group + .select('text').select('textPath'); + + // pull a stunt to measure text length - use a straight path, then switch to the real curved one. + textPath.filter(d => (!model.textLengthMap[model.mutualInformationData.vmap[d.index].name])) + .text(d => model.mutualInformationData.vmap[d.index].name) + .attr('xlink:href', '#straight-text-path') + .each(function textLen(d) { + model.textLengthMap[model.mutualInformationData.vmap[d.index].name] = this.getComputedTextLength(); + }); + + textPath + .attr('xlink:href', (d, i) => `#${model.instanceID}-group${d.index}`) + // Remove the labels that don't fit, or shorten label, using ... .each(function truncate(d, i) { d.textShown = true; const availLength = ((groupPath[0][d.index].getTotalLength() / 2) - deltaRadius - model.glyphSize); // shorten text based on string length vs initial total length. - const fullText = model.mutualInformationData.vmap[d.index].name; + const fullText = model.mutualInformationData.vmap[i].name; const textLength = model.textLengthMap[fullText]; const strLength = fullText.length; // we fit! done. if (textLength <= availLength) { + d3.select(this).text(fullText); d.textLength = textLength; return; }
fix(MutualInformationDiagram): Field labels weren't updating After introducing group reuse, when removing/adding selected fields, the labels weren't updating content and size correctly. Calculate text length only for fields that need it.
Kitware_paraviewweb
train
a57fee37185a7c4bdc222b643311fec694569913
diff --git a/.gitignore b/.gitignore index <HASH>..<HASH> 100644 --- a/.gitignore +++ b/.gitignore @@ -1,14 +1,18 @@ -examples/cellar/cellar -examples/cellar/client/cellar-cli/cellar-cli +# Golang tools artifacts **/*.coverprofile -goagen/goagen -**/autogen **/*.test vendor + +# Executables and test outputs +goagen/goagen _integration_tests/*/**/*.* -public/ + +# Editor / IDEs cruft .idea/ +*.iml .vscode/ *~ *.orig -.DS_Store \ No newline at end of file + +# OSes cruft +.DS_Store diff --git a/goagen/gen_client/generator.go b/goagen/gen_client/generator.go index <HASH>..<HASH> 100644 --- a/goagen/gen_client/generator.go +++ b/goagen/gen_client/generator.go @@ -375,22 +375,6 @@ func (g *Generator) generateResourceClient(pkgDir string, res *design.ResourceDe } g.generatedTypes[action.Payload.TypeName] = true } - if action.Params != nil { - params := make(design.Object, len(action.QueryParams.Type.ToObject())) - for n, param := range action.QueryParams.Type.ToObject() { - name := codegen.Goify(n, false) - params[name] = param - } - action.QueryParams.Type = params - } - if action.Headers != nil { - headers := make(design.Object, len(action.Headers.Type.ToObject())) - for n, header := range action.Headers.Type.ToObject() { - name := codegen.Goify(n, false) - headers[name] = header - } - action.Headers.Type = headers - } for i, r := range action.Routes { data := struct { Route *design.RouteDefinition diff --git a/goagen/gen_client/generator_test.go b/goagen/gen_client/generator_test.go index <HASH>..<HASH> 100644 --- a/goagen/gen_client/generator_test.go +++ b/goagen/gen_client/generator_test.go @@ -37,6 +37,47 @@ var _ = Describe("Generate", func() { delete(codegen.Reserved, "client") }) + Context("with jsonapi like querystring params", func() { + BeforeEach(func() { + o := design.Object{ + "fields[foo]": &design.AttributeDefinition{Type: design.String}, + } + design.Design = &design.APIDefinition{ + Name: "testapi", + Resources: map[string]*design.ResourceDefinition{ + "foo": { + Name: "foo", + Actions: map[string]*design.ActionDefinition{ + "show": { + Name: "show", + Routes: []*design.RouteDefinition{ + { + Verb: "GET", + Path: "", + }, + }, + QueryParams: &design.AttributeDefinition{Type: o}, + }, + }, + }, + }, + } + fooRes := design.Design.Resources["foo"] + showAct := fooRes.Actions["show"] + showAct.Parent = fooRes + showAct.Routes[0].Parent = showAct + }) + + It("generates param initialization code that uses the param name given in the design", func() { + Ω(genErr).Should(BeNil()) + Ω(files).Should(HaveLen(9)) + content, err := ioutil.ReadFile(filepath.Join(outDir, "client", "foo.go")) + Ω(err).ShouldNot(HaveOccurred()) + Ω(content).Should(ContainSubstring("func ShowFooPath(")) + Ω(content).Should(ContainSubstring(`values.Set("fields[foo]", *fieldsFoo)`)) + }) + }) + Context("with an action with multiple routes", func() { BeforeEach(func() { design.Design = &design.APIDefinition{
Fix bug in gen_client in generation of NewXXXRequest functions (#<I>) That causes query string and header values to be set incorrectly if their 'goified' name differs from their given name
goadesign_goa
train
fc1a89bdfe47d3c6924f0e5157558acfc14508d8
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # ClassyEnum Changelog +## 3.1.2 + +* Allow enum property to be assigned using enum class. Previously it + could only be assigned with an instance, string or symbol. + + @alarm.priority = Priority::Medium + @alarm.priority.medium? # => true + ## 3.1.1 * Fixes a regression with Formtastic support. ClassyEnumm::Base.build now diff --git a/LICENSE b/LICENSE index <HASH>..<HASH> 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2010 Peter Brown +Copyright (c) 2010-2013 Peter Brown Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/lib/classy_enum/active_record.rb b/lib/classy_enum/active_record.rb index <HASH>..<HASH> 100644 --- a/lib/classy_enum/active_record.rb +++ b/lib/classy_enum/active_record.rb @@ -42,9 +42,14 @@ module ClassyEnum ) end - # Define setter method that accepts either string or symbol for member + # Define setter method that accepts string, symbol, instance or class for member define_method "#{attribute}=" do |value| - value = value.to_s unless value.nil? + if value.class == Class && value < ClassyEnum::Base + value = value.new + elsif value.present? + value = value.to_s + end + super(value) end end diff --git a/lib/classy_enum/version.rb b/lib/classy_enum/version.rb index <HASH>..<HASH> 100644 --- a/lib/classy_enum/version.rb +++ b/lib/classy_enum/version.rb @@ -1,3 +1,3 @@ module ClassyEnum - VERSION = "3.1.1" + VERSION = "3.1.2" end diff --git a/spec/classy_enum/active_record_spec.rb b/spec/classy_enum/active_record_spec.rb index <HASH>..<HASH> 100644 --- a/spec/classy_enum/active_record_spec.rb +++ b/spec/classy_enum/active_record_spec.rb @@ -43,7 +43,7 @@ describe Dog do specify { Dog.new(:breed => '').should_not be_valid } context "with valid breed options" do - [:golden_retriever, 'golden_retriever', Breed::GoldenRetriever.new].each do |option| + [:golden_retriever, 'golden_retriever', Breed::GoldenRetriever.new, Breed::GoldenRetriever].each do |option| subject { Dog.new(:breed => option) } it { should be_valid } its(:breed) { should be_a(Breed::GoldenRetriever) }
Allow enums to be assigned using class
beerlington_classy_enum
train
c6fc8ac565ff793aea3c5c86d394a427e6c5e92e
diff --git a/packages/heroku-apps/commands/apps/errors.js b/packages/heroku-apps/commands/apps/errors.js index <HASH>..<HASH> 100644 --- a/packages/heroku-apps/commands/apps/errors.js +++ b/packages/heroku-apps/commands/apps/errors.js @@ -51,6 +51,12 @@ function * run (context, heroku) { host: 'api.metrics.herokai.com', path: `/apps/${context.app}/formation/${type}/metrics/errors?${DATE}`, headers: {Range: ''} + }).catch((err) => { + const match = new RegExp('^invalid process_type provided', 'i') + if (err.statusCode === 400 && err.body && err.body.message && match.test(err.body.message)) { + return {data: {}} + } + throw err }).then((rsp) => { Object.keys(rsp.data).forEach((key) => { rsp.data[key] = sum(rsp.data[key]) }) return rsp.data diff --git a/packages/heroku-apps/test/commands/apps/errors.js b/packages/heroku-apps/test/commands/apps/errors.js index <HASH>..<HASH> 100644 --- a/packages/heroku-apps/test/commands/apps/errors.js +++ b/packages/heroku-apps/test/commands/apps/errors.js @@ -54,6 +54,41 @@ describe('apps:errors', () => { .then(() => heroku.done()) }) + it('traps bad request', () => { + let heroku = nock('https://api.heroku.com:443') + .get('/apps/myapp/formation') + .reply(200, formation) + let metrics = nock('https://api.metrics.herokai.com:443') + .get(`/apps/myapp/router-metrics/errors?start_time=${yesterday.toISOString()}&end_time=${now.toISOString()}&step=1h&process_type=web`) + .reply(200, {data: {}}) + .get(`/apps/myapp/formation/node/metrics/errors?start_time=${yesterday.toISOString()}&end_time=${now.toISOString()}&step=1h`) + .reply(200, {data: {}}) + .get(`/apps/myapp/formation/web/metrics/errors?start_time=${yesterday.toISOString()}&end_time=${now.toISOString()}&step=1h`) + .reply(400, {'id': 'bad_request', 'message': 'invalid process_type provided (valid examples: web, worker, etc); '}) + + return cmd.run({app: 'myapp', flags: {json: false}}) + .then(() => expect(cli.stdout, 'to be', `No errors on myapp in the last 24 hours +`)) + .then(() => expect(cli.stderr, 'to be empty')) + .then(() => metrics.done()) + .then(() => heroku.done()) + }) + + it('propagates other bad request', () => { + nock('https://api.heroku.com:443') + .get('/apps/myapp/formation') + .reply(200, formation) + nock('https://api.metrics.herokai.com:443') + .get(`/apps/myapp/router-metrics/errors?start_time=${yesterday.toISOString()}&end_time=${now.toISOString()}&step=1h&process_type=web`) + .reply(200, {data: {}}) + .get(`/apps/myapp/formation/node/metrics/errors?start_time=${yesterday.toISOString()}&end_time=${now.toISOString()}&step=1h`) + .reply(200, {data: {}}) + .get(`/apps/myapp/formation/web/metrics/errors?start_time=${yesterday.toISOString()}&end_time=${now.toISOString()}&step=1h`) + .reply(400, {'id': 'bad_request', 'message': 'ack!'}) + + return expect(cmd.run({app: 'myapp', flags: {json: false}}), 'to be rejected') + }) + it('shows errors', () => { let heroku = nock('https://api.heroku.com:443') .get('/apps/myapp/formation')
Trap bad request response when web missing (#<I>) * Trap bad request response when web missing * Fixing error for real & PR feedback
heroku_cli
train
76e8b82c917f435fc834123547ad4252b8ffbbd0
diff --git a/pypump/models/feed.py b/pypump/models/feed.py index <HASH>..<HASH> 100644 --- a/pypump/models/feed.py +++ b/pypump/models/feed.py @@ -238,7 +238,6 @@ class Feed(PumpObject): def __init__(self, url=None, *args, **kwargs): super(Feed, self).__init__(*args, **kwargs) - self.unserialize({}) #do empty unserialize to set all attributes self.url = url or None def items(self, offset=None, limit=20, since=None, before=None, *args, **kwargs):
no need to unserialize on Feed init We do this in PumpObject
xray7224_PyPump
train
8f6134f757db19a8aeaa641658dae5c9b1200fb3
diff --git a/electronics/gateways/buspirate.py b/electronics/gateways/buspirate.py index <HASH>..<HASH> 100644 --- a/electronics/gateways/buspirate.py +++ b/electronics/gateways/buspirate.py @@ -29,6 +29,7 @@ class BusPirate(object): >>> # Enable the power supply and the pull-ups in the next mode switch >>> gw.power = True # doctest: +SKIP >>> gw.pullup = True # doctest: +SKIP + >>> gw.i2c_speed = '50kHz' # doctest: +SKIP >>> # Add a device so the config will apply >>> sensor = LM75(gw) # doctest: +SKIP >>> # The power and pullup is now enabled. @@ -55,6 +56,7 @@ class BusPirate(object): self.power = False self.aux = False self.chip_select = False + self.i2c_speed = None # default for i in range(0, 20): self.device.timeout = 0.1 @@ -91,6 +93,8 @@ class BusPirate(object): raise Exception('Could not switch mode') self.mode = new_mode self.set_peripheral() + if self.i2c_speed: + self._set_i2c_speed(self.i2c_speed) def set_peripheral(self, power=None, pullup=None, aux=None, chip_select=None): """ Set the peripheral config at runtime. @@ -195,3 +199,20 @@ class BusPirate(object): def _write_cs(self, value): self.set_peripheral(chip_select=value) + + def _set_i2c_speed(self, i2c_speed): + """ Set I2C speed to one of '400kHz', '100kHz', 50kHz', '5kHz' + """ + lower_bits_mapping = { + '400kHz': 3, + '100kHz': 2, + '50kHz': 1, + '5kHz': 0, + } + if i2c_speed not in lower_bits_mapping: + raise ValueError('Invalid i2c_speed') + speed_byte = 0b01100000 | lower_bits_mapping[i2c_speed] + self.device.write(bytearray([speed_byte])) + response = self.device.read(1) + if response != b"\x01": + raise Exception("Changing I2C speed failed. Received: {}".format(repr(response)))
buspirate: add i2c_speed variable. This adds support for changing the I2C speed from the default <I>kHz. Example usage: bp = buspirate.BusPirate('/dev/tty.usbserial-XYZ') bp.i2c_speed = '5kHz' i2c = device.I2CDevice(bp, 0xa0) i2c.i2c_read(5)
MartijnBraam_pyElectronics
train
0911aacaf35b1f2b2725d2715bb47a43e4e1da2c
diff --git a/invenio_records/tasks/api.py b/invenio_records/tasks/api.py index <HASH>..<HASH> 100644 --- a/invenio_records/tasks/api.py +++ b/invenio_records/tasks/api.py @@ -23,6 +23,7 @@ from __future__ import absolute_import from celery import shared_task from celery.utils.log import get_task_logger +from flask import current_app from sqlalchemy import exc from ..api import Record @@ -39,7 +40,7 @@ def create_record(data=None, force=False): except exc.IntegrityError: if force: current_app.logger.warning( - "Trying to force insert: {0}".format(json)) - return Record(json).commit().get('recid') + "Trying to force insert: {0}".format(data)) + return Record(data).commit().get('recid') finally: db.session.commit()
tasks: wrong imports fix * Fixes wrong imports in celery tasks.
inveniosoftware_invenio-records
train
a44da9333100a0a576bf74b064d340f40ca60e37
diff --git a/spec/public/core_ext/class_spec.rb b/spec/public/core_ext/class_spec.rb index <HASH>..<HASH> 100644 --- a/spec/public/core_ext/class_spec.rb +++ b/spec/public/core_ext/class_spec.rb @@ -10,7 +10,9 @@ class Child < Parent end class Grandparent - class_inheritable_accessor :last_name + class_inheritable_accessor :last_name, :_attribute + + self._attribute = "1900" end describe Class, "#inheritable_accessor" do @@ -20,6 +22,15 @@ describe Class, "#inheritable_accessor" do Parent.send(:remove_instance_variable, "@last_name") rescue nil Child.send(:remove_instance_variable, "@last_name") rescue nil end + + it 'inherits from parent unless overriden' do + Parent._attribute.should == "1900" + Child._attribute.should == "1900" + end + + it 'inherits from grandparent unless overriden' do + Child._attribute.should == "1900" + end it "inherits even if the accessor is made after the inheritance" do Grandparent.last_name = "Merb" @@ -88,4 +99,4 @@ describe Class, "#inheritable_accessor" do Child.last_name.should == "Core" end -end \ No newline at end of file +end
Two more specs for class_inheritable_accessor.
wycats_merb
train
d1bf4772ba755cc992ec124a1632327f97cbd04e
diff --git a/lib/sprockets/directive_processor.rb b/lib/sprockets/directive_processor.rb index <HASH>..<HASH> 100644 --- a/lib/sprockets/directive_processor.rb +++ b/lib/sprockets/directive_processor.rb @@ -72,33 +72,31 @@ module Sprockets end def call(input) - @environment = input[:environment] - @filename = input[:filename] - @base_path = File.dirname(@filename) + @environment = input[:environment] + @filename = input[:filename] + @base_path = File.dirname(@filename) @content_type = input[:content_type] - data = input[:data] - @header = data[HEADER_PATTERN, 0] || "" - @body = $' || data + data = input[:data] + header = data[HEADER_PATTERN, 0] || "" + body = $' || data # Ensure body ends in a new line - @body += "\n" if @body != "" && @body !~ /\n\Z/m - - @result = "" - @result.force_encoding(@body.encoding) - - @has_written_body = false + body += "\n" if body != "" && body !~ /\n\Z/m @required_paths = [] @stubbed_paths = Set.new @dependency_paths = Set.new - @processed_header, directives = extract_directives(@header) - + header, directives = extract_directives(header) process_directives(directives) - process_source + + result = "" + result.force_encoding(body.encoding) + result << header << "\n" unless header.empty? + result << body { - data: @result, + data: result, required_paths: @required_paths, stubbed_paths: @stubbed_paths, dependency_paths: @dependency_paths @@ -164,16 +162,6 @@ module Sprockets end end - def process_source - unless @has_written_body || @processed_header.empty? - @result << @processed_header << "\n" - end - - unless @has_written_body - @result << @body - end - end - # The `require` directive functions similar to Ruby's own `require`. # It provides a way to declare a dependency on a file in your path # and ensures its only loaded once before the source file. @@ -208,13 +196,10 @@ module Sprockets # */ # def process_require_self_directive - if @has_written_body + if @required_paths.include?(@filename) raise ArgumentError, "require_self can only be called once per source file" end - @required_paths << @filename - process_source - @has_written_body = true end # `require_directory` requires all the files inside a single
Remove has written body hacks No longer needed for require self since include is removed
rails_sprockets
train
953f87e29ef3410e94e224533289f582f0fbadfb
diff --git a/testng/src/test/java/com/automation/remarks/testng/test/BaseTest.java b/testng/src/test/java/com/automation/remarks/testng/test/BaseTest.java index <HASH>..<HASH> 100644 --- a/testng/src/test/java/com/automation/remarks/testng/test/BaseTest.java +++ b/testng/src/test/java/com/automation/remarks/testng/test/BaseTest.java @@ -1,5 +1,6 @@ package com.automation.remarks.testng.test; +import com.automation.remarks.video.enums.RecorderType; import com.automation.remarks.video.enums.RecordingMode; import com.automation.remarks.video.recorder.monte.MonteRecorder; import org.apache.commons.io.FileUtils; @@ -27,7 +28,9 @@ public class BaseTest { public void beforeMethod(Method method) throws IOException { this.testMethod = method; deleteVideoDir(); - MonteRecorder.conf().withRecordMode(RecordingMode.ANNOTATED); + MonteRecorder.conf() + .withRecordMode(RecordingMode.ANNOTATED) + .withRecorderType(RecorderType.MONTE); } @AfterClass
* BaseTest fix. Added setup with recorder type MONTE. Without it tests might be flacky
SergeyPirogov_video-recorder-java
train
3a6adf528f0d65f876f1b6e8704d8af41573e3ee
diff --git a/lib/version.php b/lib/version.php index <HASH>..<HASH> 100644 --- a/lib/version.php +++ b/lib/version.php @@ -19,8 +19,8 @@ class eZPublishSDK const VERSION_RELEASE = 0; const VERSION_STATE = 'alpha1'; const VERSION_DEVELOPMENT = true; - const VERSION_ALIAS = '5.90'; - const EDITION = 'eZ Publish Community Project'; + const VERSION_ALIAS = '2017.08'; + const EDITION = 'eZ Publish legacy'; /*! \return the SDK version as a string
[version] Update version info for master
ezsystems_ezpublish-legacy
train
2e153a3455fa2fe54f7ddefff66b06f8f4ec1870
diff --git a/test/transit.js b/test/transit.js index <HASH>..<HASH> 100644 --- a/test/transit.js +++ b/test/transit.js @@ -4,10 +4,10 @@ var should = require('chai').should(); var MysqlTransit = require('../index'); var connectionParams = { - 'host': 'localhost', - 'port': 13306, - 'user': 'root', - 'password': 'root' + 'host': (process.env.MYSQL_TEST_HOST) ? process.env.MYSQL_TEST_PORT : 'localhost', + 'port': (process.env.MYSQL_TEST_PORT) ? process.env.MYSQL_TEST_PORT : 3306, + 'user': (process.env.MYSQL_TEST_USER) ? process.env.MYSQL_TEST_PORT : 'root', + 'password': (process.env.MYSQL_TEST_PASSWORD) ? process.env.MYSQL_TEST_PORT : 'root' }; var connection, createOriginalDatabase,
add mysql params as env variables
AGCPartners_mysql-transit
train
d1af9ac532f895f44940ddbf4fa8f2006f879e29
diff --git a/src/GetOptionKit/OptionParser.php b/src/GetOptionKit/OptionParser.php index <HASH>..<HASH> 100644 --- a/src/GetOptionKit/OptionParser.php +++ b/src/GetOptionKit/OptionParser.php @@ -23,18 +23,12 @@ class OptionParser public $longOptions; public $shortOptions; - function __construct($specs) + public function __construct(OptionCollection $specs) { - if( $specs ) { - if( ! is_a($specs,'\GetOptionKit\OptionCollection') ) - throw new Exception('not option spec collection class.'); - $this->specs = $specs; - } else { - $this->specs = new \GetOptionKit\OptionCollection; - } + $this->specs = $specs; } - function setSpecs(OptionCollection $specs) + public function setSpecs(OptionCollection $specs) { $this->specs = $specs; }
Simplify OptionParser::__construct
c9s_GetOptionKit
train
378c810f81f2d8118126b0b0e71f0502e21a0470
diff --git a/src/Symfony/Bundle/DoctrineBundle/Mapping/Driver/XmlDriver.php b/src/Symfony/Bundle/DoctrineBundle/Mapping/Driver/XmlDriver.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Bundle/DoctrineBundle/Mapping/Driver/XmlDriver.php +++ b/src/Symfony/Bundle/DoctrineBundle/Mapping/Driver/XmlDriver.php @@ -60,7 +60,7 @@ class XmlDriver extends BaseXmlDriver } } - return array_merge(parent::getAllClassNames(), array_keys($this->_classCache)); + return array_merge($classes, array_keys($this->_classCache)); } public function getElement($className)
[DoctrineBundle] fixed regression
symfony_symfony
train
ebf5287ab40a2b5fd980b67371ff49b882a93753
diff --git a/neurondm/neurondm/core.py b/neurondm/neurondm/core.py index <HASH>..<HASH> 100644 --- a/neurondm/neurondm/core.py +++ b/neurondm/neurondm/core.py @@ -1736,15 +1736,18 @@ class NeuronBase(AnnotationMixin, GraphOpsMixin, graphBase): if not cls._loading: NeuronBase._loading = True # block all other neuron loading try: + log.debug(str([i for i in iris if '4164' in i or '100212' in i])) for iri in iris: - #if iri.endswith('4164') or iri.endswith('100212'): # rod/cone issue #breakpoint() try: - cls(id_=iri, override=True)#, out_graph=cls.config.load_graph) # I think we can get away without this + n = cls(id_=iri, override=True)#, out_graph=cls.config.load_graph) # I think we can get away without this + if iri.endswith('4164') or iri.endswith('100212'): + log.debug(f'{iri} -> {n}') + # because we just call Config again an everything resets except cls.owlClassMismatch as e: - log.error(str(e)) + log.exception(e) continue except AttributeError as e: log.critical(str(e)) @@ -2050,7 +2053,9 @@ class NeuronBase(AnnotationMixin, GraphOpsMixin, graphBase): sn = self._shortname if sn: sn = ' ' + sn - id_ = ',\n' + t + f"id_={str(self.id_)!r}" if self.id_ != self.temp_id else '' + id_ = (',\n' + t + f"id_={str(self.id_)!r}" + if not hasattr(self, 'temp_id') or + self.id_ != self.temp_id else '') asdf += id_ lab = ',\n' + t + f"label={str(self.origLabel) + sn!r}" if self._origLabel else '' asdf += lab diff --git a/neurondm/neurondm/models/cuts.py b/neurondm/neurondm/models/cuts.py index <HASH>..<HASH> 100755 --- a/neurondm/neurondm/models/cuts.py +++ b/neurondm/neurondm/models/cuts.py @@ -304,7 +304,7 @@ def main(): n._origLabel = l ns.append(n) - sns = set(n._origLabel for n in ns) + sns = set(n.origLabel for n in ns) labels_set1 = labels_set0 - sns
neurondm rod/cone issue report so, it turns out that the phenotypes for rods and cones were set to be identical (DUH), so fixing that downstream instead of upstream, also a clear indication that we need a warning if origLabels do not match and the pes match
tgbugs_pyontutils
train
9e71daa8faa91e38a4f54aa7a4352a05f09d9073
diff --git a/Market/MarketSession.php b/Market/MarketSession.php index <HASH>..<HASH> 100644 --- a/Market/MarketSession.php +++ b/Market/MarketSession.php @@ -5,7 +5,7 @@ * */ class MarketSession { - private $context = NULL; + public $context = NULL; private $authSubToken = ""; /** @@ -18,6 +18,9 @@ class MarketSession { $this->context->setAndroidId("0000000000000000"); $this->context->setDeviceAndSdkVersion("sapphire:7"); + $this->context->setUserLanguage("en"); + $this->context->setUserCountry("US"); + $this->setOperatorTmobile(); } @@ -41,9 +44,21 @@ class MarketSession { $this->setOperator("sunrise", "22802"); } - public function setOperator($alpha, $simAlpha, $numeric = false, $simNumeric = false) { - $this->context->setOperatorAlpha($alpha); - $this->context->setSimOperatorAlpha($simAlpha); + public function setOperator($alpha, $simAlpha, $numeric = "", $simNumeric = "") { + if (!$numeric && !$simNumeric) { + $this->context->setOperatorAlpha($alpha); + $this->context->setSimOperatorAlpha($alpha); + + $this->context->setOperatorNumeric($simAlpha); + $this->context->setSimOperatorNumeric($simAlpha); + + } else { + $this->context->setOperatorAlpha($alpha); + $this->context->setSimOperatorAlpha($simAlpha); + + $this->context->setOperatorNumeric($numeric); + $this->context->setSimOperatorNumeric($simNumeric); + } } /** @@ -164,7 +179,6 @@ class MarketSession { curl_close($ch); $ret = $this->gzdecode($ret); - return $ret; }
Set user locale by default and fixed setOperator
koconder_android-market-api-php
train
347a94da43a5eca6abb3ddd0fad478325ee31e64
diff --git a/hamster/hamster-applet.py b/hamster/hamster-applet.py index <HASH>..<HASH> 100755 --- a/hamster/hamster-applet.py +++ b/hamster/hamster-applet.py @@ -69,7 +69,8 @@ def on_destroy(event): if last_activity and last_activity['end_time'] == None: storage.touch_fact(last_activity) - gtk.main_quit() + if gtk.main_level(): + gtk.main_quit() def usage(): print _(u"""Time tracker: Usage
fixed the crash message that kept popping up after hamster shutting down : main_quit is not required if applet is removed from panel svn path=/trunk/; revision=<I>
projecthamster_hamster
train
2a201ac7b360fe30e066404218f8ab9a72b05206
diff --git a/nodeconductor/billing/tasks.py b/nodeconductor/billing/tasks.py index <HASH>..<HASH> 100644 --- a/nodeconductor/billing/tasks.py +++ b/nodeconductor/billing/tasks.py @@ -102,6 +102,11 @@ def update_today_usage_of_resource(resource_str): backend = CostTrackingRegister.get_resource_backend(resource) used_items = backend.get_used_items(resource) + if not resource.billing_backend_id: + logger.warning( + "Can't update usage for resource %s which is not subscribed to backend", resource_str) + return + numerical = ['storage', 'users'] # XXX: use consistent method for usage calculation content_type = ContentType.objects.get_for_model(resource)
Post usage to killbill for already subscribed resources only - NC-<I>
opennode_waldur-core
train