hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
71d0862a28e5711a665e713e971849bc06d9335b
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -4,33 +4,37 @@ """Setup script for humanize.""" from setuptools import setup, find_packages -import sys, os import io version = '0.5.1' -# some trove classifiers: - - setup( name='humanize', version=version, description="python humanize utilities", long_description=io.open('README.rst', 'r', encoding="UTF-8").read(), - # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers + # Get strings from https://pypi.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', - 'Programming Language :: Python :: 3', 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', ], keywords='humanize time size', author='Jason Moiron', author_email='jmoiron@jmoiron.net', - url='http://github.com/jmoiron/humanize', + url='https://github.com/jmoiron/humanize', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True,
Update Trove classifiers to match tested versions
jmoiron_humanize
train
85e044a91bf71019d3518c16d1190e705b8dbbab
diff --git a/cumulusci/core/keychain/BaseProjectKeychain.py b/cumulusci/core/keychain/BaseProjectKeychain.py index <HASH>..<HASH> 100644 --- a/cumulusci/core/keychain/BaseProjectKeychain.py +++ b/cumulusci/core/keychain/BaseProjectKeychain.py @@ -32,6 +32,7 @@ class BaseProjectKeychain(BaseConfig): if not connected_app: # not configured return + print('Using old-style Connected App info. Set the connected_app service using the same info.') ca_config = ServiceConfig({ 'callback_url': connected_app.callback_url, 'client_id': connected_app.client_id,
print message about setting connected_app service
SFDO-Tooling_CumulusCI
train
5951edcbbd008ad1ab9daeb61b873411dbf6724f
diff --git a/supertable/variables/SuperTableVariable.php b/supertable/variables/SuperTableVariable.php index <HASH>..<HASH> 100644 --- a/supertable/variables/SuperTableVariable.php +++ b/supertable/variables/SuperTableVariable.php @@ -4,6 +4,105 @@ namespace Craft; class SuperTableVariable { + /** + * Expands the defualt relationship behaviour to include Super Table + * fields so that the user can filter by those too. + * + * For example: + * + * ```twig + * {% set reverseRelatedElements = craft.supertable.getRelatedElements({ + * relatedTo : { + * targetElement: entry, + * field: 'superTableFieldHandle.columnHandle' + * }, + * elementType : 'SomePlugin_Element', + * criteria : { + * id : 'not 123', + * section : 'someSection' + * } + * }) + * ``` + * + * @method getRelatedElements + * @param array $params Should contain 'relatedTo' but can also optionally + * include 'elementType' and 'criteria' + * @return ElementCriteriaModel + */ + public function getRelatedElements($params = null) + { + + // Parse out the field handles + $superTableFieldHandle = explode('.', $params['relatedTo']['field'])[0]; + $superTableBlockFieldHandle = explode('.', $params['relatedTo']['field'])[1]; + + // For saftey fail early if that didn't work + if (!$superTableFieldHandle || !$superTableFieldHandle) + { + return false; + } + + // Get the Super Table field and associated block type + $superTableField = craft()->fields->getFieldByHandle($superTableFieldHandle); + $superTableBlockType = craft()->superTable->getBlockTypesByFieldId($superTableField->id)[0]; + + // Loop the fields on the block type and save the first one that matches our handle + $fieldId = false; + foreach ($superTableBlockType->getFields() as $field) + { + if ($field->handle === $superTableBlockFieldHandle ) + { + $fieldId = $field->id; + break; + } + } + + // Check we got something and update the relatedTo criteria for our next elements call + if ($fieldId) + { + $params['relatedTo']['field'] = $fieldId; + } + else + { + return false; + } + + // Get the Super Table Blocks that are related to that field + $superTableBlocks = craft()->elements->getCriteria('SuperTable_Block', array( + 'relatedTo' => $params['relatedTo'] + )); + + // Loop over the returned Super Table Blocks and save their owner ids + $elementIds = array(); + foreach ($superTableBlocks as $superTableBlock) + { + $elementIds[] = $superTableBlock->ownerId; + } + + // Defualt to getting Entry elements but let the user override + $elementType = ElementType::Entry; + if (isset($params['elementType'])) + { + $elementType = $params['elementType']; + } + + // Start our final criteria with the element ids we just got + $finalCriteria = array( + 'id' => $elementIds + ); + + // Check if the user gave us another criteria model and merge that in + if (isset($params['criteria'])) + { + $finalCriteria = array_merge($finalCriteria, $params['criteria']); + } + + // Return our final element criteria + return craft()->elements->getCriteria($elementType, $finalCriteria); + + } + + // // Having a Matrix-SuperTable-Matrix layout will cause issues becase it will try to apply the namespace for the top-level // Matrix field, which means inner-Matrix fields will not work properly. Very hacky, but we need to replicate the Matrix @@ -114,4 +213,4 @@ class SuperTableVariable return $blockTypes; } -} \ No newline at end of file +}
Added a Variable to allow finding elements related through a Super Table field.
verbb_super-table
train
834b5dadf8cc81087ac1edc17cf876943197391e
diff --git a/nion/swift/DisplayPanel.py b/nion/swift/DisplayPanel.py index <HASH>..<HASH> 100644 --- a/nion/swift/DisplayPanel.py +++ b/nion/swift/DisplayPanel.py @@ -365,10 +365,18 @@ class RelatedIconsCanvasItem(CanvasItem.CanvasItemComposition): self.set_display(None) super().close() + @property + def _source_thumbnails(self): + return self.__source_thumbnails + + @property + def _dependent_thumbnails(self): + return self.__dependent_thumbnails + def __related_items_changed(self, display, source_displays, dependent_displays): - self.__source_thumbnails.remove_all_canvas_items() - self.__dependent_thumbnails.remove_all_canvas_items() if display == self.__display: + self.__source_thumbnails.remove_all_canvas_items() + self.__dependent_thumbnails.remove_all_canvas_items() for source_display in source_displays: thumbnail_source = DataItemThumbnailWidget.DataItemThumbnailSource(self.ui, display=source_display) thumbnail_canvas_item = DataItemThumbnailWidget.ThumbnailCanvasItem(self.ui, thumbnail_source, self.__thumbnail_size) @@ -943,6 +951,10 @@ class DisplayPanel(CanvasItem.CanvasItemComposition): return self.__filtered_display_items_model.display_items @property + def _related_icons_canvas_item(self): + return self.__related_icons_canvas_item + + @property def header_canvas_item(self): return self.__header_canvas_item diff --git a/nion/swift/test/DisplayPanel_test.py b/nion/swift/test/DisplayPanel_test.py index <HASH>..<HASH> 100644 --- a/nion/swift/test/DisplayPanel_test.py +++ b/nion/swift/test/DisplayPanel_test.py @@ -1510,6 +1510,23 @@ class TestDisplayPanelClass(unittest.TestCase): document_model.remove_data_item(composite_item) self.assertEqual(len(document_model.data_items), 0) + def test_dependency_icons_updated_properly_when_one_of_two_dependents_are_removed(self): + app = Application.Application(TestUI.UserInterface(), set_global=False) + document_model = DocumentModel.DocumentModel() + document_controller = DocumentController.DocumentController(app.ui, document_model, workspace_id="library") + with contextlib.closing(document_controller): + data_item = DataItem.DataItem(numpy.zeros((100, ))) + document_model.append_data_item(data_item) + display_panel = document_controller.selected_display_panel + document_model.get_crop_new(data_item) + document_model.get_line_profile_new(data_item) + self.assertEqual(3, len(document_model.data_items)) + self.assertEqual(2, len(data_item.displays[0].graphics)) + self.assertEqual(2, len(document_model.get_dependent_items(data_item))) + display_panel.set_display_panel_data_item(data_item) + self.assertEqual(2, len(display_panel._related_icons_canvas_item._dependent_thumbnails.canvas_items)) + data_item.displays[0].remove_graphic(data_item.displays[0].graphics[1]) + self.assertEqual(1, len(display_panel._related_icons_canvas_item._dependent_thumbnails.canvas_items)) if __name__ == '__main__': logging.getLogger().setLevel(logging.DEBUG)
Fix issue with related icons being removed when unrelated dependent changes.
nion-software_nionswift
train
1a170083fd4e0268555b3f02676976654ba71b9c
diff --git a/public/js/chrome/app.js b/public/js/chrome/app.js index <HASH>..<HASH> 100644 --- a/public/js/chrome/app.js +++ b/public/js/chrome/app.js @@ -1,10 +1,8 @@ // if a gist has been requested, lazy load the gist library and plug it in -if (/gist(\/.*)?\/\d+/.test(window.location.pathname) && (!sessionStorage.getItem('javascript') && !sessionStorage.getItem('html'))) { +if (/gist\/.*/.test(window.location.pathname)) { window.editors = editors; // needs to be global when the callback triggers to set the content loadGist = function () { - $.getScript(jsbin.static + '/js/chrome/gist.js', function () { - window.gist = new Gist(window.location.pathname.replace(/.*?(\d+).*/, "$1")); - }); + window.gist = new Gist(window.location.pathname.replace(/.*\/([^/]+)$/, "$1")); }; if (editors.ready) { @@ -43,4 +41,4 @@ document.getElementsByTagName('head')[0].appendChild(link); if (jsbin.embed) { analytics.embed(); -} +} \ No newline at end of file diff --git a/public/js/chrome/gist.js b/public/js/chrome/gist.js index <HASH>..<HASH> 100644 --- a/public/js/chrome/gist.js +++ b/public/js/chrome/gist.js @@ -21,7 +21,6 @@ var Gist = (function () { // jshint ignore:line $.get('https://api.github.com/gists/' + id + token, function (data) { if (!data) {return;} $.each(data.files, function (fileName, fileData) { - console.log.apply(console, [].slice.call(arguments)); var ext = fileName.split('.').slice(-1).join(''); gist.code[ext] = fileData.content; }); @@ -38,7 +37,9 @@ var Gist = (function () { // jshint ignore:line panel = jsbin.panels.panels[target]; if (!panel) {return;} processors.set(target, processorInit.id); + jsbin.saveDisabled = true; panel.setCode(data); + jsbin.saveDisabled = false; }); }; diff --git a/public/js/editors/panel.js b/public/js/editors/panel.js index <HASH>..<HASH> 100644 --- a/public/js/editors/panel.js +++ b/public/js/editors/panel.js @@ -118,7 +118,11 @@ var Panel = function (name, settings) { // Bind events using CM3 syntax panel.editor.on('change', function codeChange(cm, changeObj) { - $document.trigger('codeChange', [{ panelId: panel.id, revert: true, origin: changeObj.origin }]); + if (jsbin.saveDisabled) { + $document.trigger('codeChange.live', [{ panelId: panel.id, revert: true, origin: changeObj.origin }]); + } else { + $document.trigger('codeChange', [{ panelId: panel.id, revert: true, origin: changeObj.origin }]); + } return true; });
Fix for new gist id and removed automatical saving
jsbin_jsbin
train
a300ab2752c0858e6fc511c9c06a1f690e26a442
diff --git a/mathparse/mathwords.py b/mathparse/mathwords.py index <HASH>..<HASH> 100644 --- a/mathparse/mathwords.py +++ b/mathparse/mathwords.py @@ -313,6 +313,58 @@ MATH_WORDS = { 'миллиард': 1000000000, 'триллион': 1000000000000 } + }, + 'POR': { + 'unary_operators': { + 'ao quadrado': '^ 2', + 'ao cubo': '^ 3', + 'raiz quadrada de': 'sqrt' + }, + 'binary_operators': { + 'mais': '+', + 'dividido por': '/', + 'menos': '-', + 'vezes': '*', + 'elevado à potência de': '^' + }, + 'numbers': { + 'zero': 0, + 'um': 1, + 'dois': 2, + 'três': 3, + 'quatro': 4, + 'cinco': 5, + 'seis': 6, + 'sete': 7, + 'oito': 8, + 'nove': 9, + 'dez': 10, + 'onze': 11, + 'doze': 12, + 'treze': 13, + 'quatorze': 14, + 'catorze': 14, + 'quinze': 15, + 'dezesseis': 16, + 'dezessete': 17, + 'dezoito': 18, + 'dezenove': 19, + 'vinte': 20, + 'trinta': 30, + 'quarenta': 40, + 'cinquenta': 50, + 'sessenta': 60, + 'setenta': 70, + 'oitenta': 80, + 'noventa': 90 + }, + 'scales': { + 'cem': 100, + 'mil': 1000, + 'milhão': 1000000, + 'bilhão': 1000000000, + 'trilhão': 1000000000000 + } } }
Add support for Portuguese (POR)
gunthercox_mathparse
train
2737c88b189f165e7fe3dd3463b90ab7e87e18a4
diff --git a/src/pyrocore/scripts/lstor.py b/src/pyrocore/scripts/lstor.py index <HASH>..<HASH> 100644 --- a/src/pyrocore/scripts/lstor.py +++ b/src/pyrocore/scripts/lstor.py @@ -67,28 +67,18 @@ class MetafileLister(ScriptBase): if idx and not self.options.output: print print "~" * 79 + try: # Read and check metafile try: - with closing(open(filename, "rb")) as handle: - raw_data = handle.read() - data = bencode.bdecode(raw_data) + data = metafile.checked_open(filename, log=self.LOG if self.options.skip_validation else None, + quiet=(self.options.quiet and (self.options.output or self.options.raw))) except EnvironmentError, exc: self.fatal("Can't read '%s' (%s)" % ( filename, str(exc).replace(": '%s'" % filename, ""), )) raise - try: - metafile.check_meta(data) - if raw_data != bencode.bencode(data): - raise ValueError("Bad bencoded data - dict keys out of order?") - except ValueError, exc: - if self.options.skip_validation: - # Warn about it, unless it's a quiet value query - if not (self.options.quiet and (self.options.output or self.options.raw)): - self.LOG.warn("%s: %s" % (filename, exc)) - else: - raise + listing = None if self.options.raw: diff --git a/src/pyrocore/util/metafile.py b/src/pyrocore/util/metafile.py index <HASH>..<HASH> 100644 --- a/src/pyrocore/util/metafile.py +++ b/src/pyrocore/util/metafile.py @@ -342,6 +342,31 @@ def data_size(metadata): return total_size +def checked_open(filename, log=None, quiet=False): + """ Open and validate the given metafile. + Optionally provide diagnostics on the passed logger, for + invalid metafiles, which then just cause a warning but no exception. + "quiet" can supress that warning. + """ + with closing(open(filename, "rb")) as handle: + raw_data = handle.read() + data = bencode.bdecode(raw_data) + + try: + check_meta(data) + if raw_data != bencode.bencode(data): + raise ValueError("Bad bencoded data - dict keys out of order?") + except ValueError, exc: + if log: + # Warn about it, unless it's a quiet value query + if not quiet: + log.warn("%s: %s" % (filename, exc)) + else: + raise + + return data + + class Metafile(object): """ A torrent metafile. """
refactored metafile loading to checked_open()
pyroscope_pyrocore
train
f1b8d36ec641cb7aebd734706807689214fa3e08
diff --git a/decidim-dev/lib/decidim/test/i18n_spec.rb b/decidim-dev/lib/decidim/test/i18n_spec.rb index <HASH>..<HASH> 100644 --- a/decidim-dev/lib/decidim/test/i18n_spec.rb +++ b/decidim-dev/lib/decidim/test/i18n_spec.rb @@ -15,4 +15,20 @@ RSpec.describe "I18n" do expect(unused_keys).to be_empty, "#{unused_keys.leaves.count} unused i18n keys, run `i18n-tasks unused` to show them" end + + it "is normalized" do + previous_locale_hashes = locale_hashes + i18n.normalize_store! + new_locale_hashes = locale_hashes + + expect(previous_locale_hashes).to eq(new_locale_hashes), + "Please normalize your locale files with `i18n-tasks normalize`" + end + + def locale_hashes + Dir.glob("config/locales/**/*.yml").inject({}) do |results, file| + md5 = Digest::MD5.file(file).hexdigest + results.merge(file => md5) + end + end end
Enforce normalizing locales (#<I>)
decidim_decidim
train
32c9858b85a102e2054e388822bce7008d9f164c
diff --git a/lib/omniship/carriers/ups.rb b/lib/omniship/carriers/ups.rb index <HASH>..<HASH> 100644 --- a/lib/omniship/carriers/ups.rb +++ b/lib/omniship/carriers/ups.rb @@ -475,6 +475,7 @@ module Omniship @response_text[:error_code] = xml.xpath('/*/Response/Error/ErrorCode').text @response_text[:error_description] = xml.xpath('/*/Response/Error/ErrorDescription').text end + return @response_text end def parse_ship_accept_response(response, options={})
Debugging UPS Error Codes
Digi-Cazter_omniship
train
5155d097653b062f1439f680c7070081491a6bab
diff --git a/system/src/Grav/Common/Utils.php b/system/src/Grav/Common/Utils.php index <HASH>..<HASH> 100644 --- a/system/src/Grav/Common/Utils.php +++ b/system/src/Grav/Common/Utils.php @@ -240,6 +240,9 @@ abstract class Utils ignore_user_abort(false); + // fix corrupted files + ob_clean(); + if ($force_download) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream');
Fix for corrupted downloads in inherited themes - <URL>
getgrav_grav
train
bcba9dece90070d9855ce55d57c8546905039c7a
diff --git a/Services/AzineNotifierService.php b/Services/AzineNotifierService.php index <HASH>..<HASH> 100644 --- a/Services/AzineNotifierService.php +++ b/Services/AzineNotifierService.php @@ -336,14 +336,17 @@ class AzineNotifierService implements NotifierServiceInterface { } $recipientParams[self::CONTENT_ITEMS] = array_merge($recipientContentItems, $generalContentItems); $recipientParams['_locale'] = $recipient->getPreferredLocale(); - + + if(sizeof($recipientParams[self::CONTENT_ITEMS]) == 0){ + $this->logger->warning("The newsletter for ".$recipient->getDisplayName()." <".$recipient->getEmail()."> has not been sent. It would have been empty.", $params); + return $recipient->getEmail(); + } // render and send the email with the right wrapper-template $sent = $this->mailer->sendSingleEmail($recipient->getEmail(), $recipient->getDisplayName(), $recipientParams, $wrapperTemplate.".txt.twig", $recipient->getPreferredLocale()); if($sent){ // save that this recipient has recieved the newsletter - //$this->setNotificationsAsSent($notifications); return null; } else {
don't send empty newsletters, but add a warning to the log.
azine_email-bundle
train
9567f4a1a3ebf41cea417c376e7adedfc3122a17
diff --git a/hazelcast/src/main/java/com/hazelcast/internal/diagnostics/DiagnosticsLogFile.java b/hazelcast/src/main/java/com/hazelcast/internal/diagnostics/DiagnosticsLogFile.java index <HASH>..<HASH> 100644 --- a/hazelcast/src/main/java/com/hazelcast/internal/diagnostics/DiagnosticsLogFile.java +++ b/hazelcast/src/main/java/com/hazelcast/internal/diagnostics/DiagnosticsLogFile.java @@ -74,7 +74,7 @@ final class DiagnosticsLogFile { public void write(DiagnosticsPlugin plugin) { try { if (file == null) { - file = new File(diagnostics.directory, format(fileName, index)); + file = newFile(index); printWriter = newWriter(); renderStaticPlugins(); } @@ -95,6 +95,10 @@ final class DiagnosticsLogFile { } } + private File newFile(int index) { + return new File(diagnostics.directory, format(fileName, index)); + } + private void renderStaticPlugins() throws IOException { for (DiagnosticsPlugin plugin : diagnostics.staticTasks.get()) { renderPlugin(plugin); @@ -119,7 +123,7 @@ final class DiagnosticsLogFile { file = null; index++; - File file = new File(format(fileName, index - maxRollingFileCount)); + File file = newFile(index - maxRollingFileCount); deleteQuietly(file); } }
DiagnosticLogFiles not deleted when custom directory used
hazelcast_hazelcast
train
cb3c1dd486ba0a891c81886c1546553fc17f01b8
diff --git a/lib/serializer.rb b/lib/serializer.rb index <HASH>..<HASH> 100644 --- a/lib/serializer.rb +++ b/lib/serializer.rb @@ -26,6 +26,8 @@ module OpenTox OT.Algorithm => { RDF["type"] => [{ "type" => "uri", "value" => OWL['Class'] }] } , OT.Parameter => { RDF["type"] => [{ "type" => "uri", "value" => OWL['Class'] }] } , OT.Task => { RDF["type"] => [{ "type" => "uri", "value" => OWL['Class'] }] } , + OTA.PatternMiningSupervised => { RDF["type"] => [{ "type" => "uri", "value" => OWL['Class'] }] } , + #classes for validation OT.Validation => { RDF["type"] => [{ "type" => "uri", "value" => OWL['Class'] }] } , OT.ClassificationStatistics => { RDF["type"] => [{ "type" => "uri", "value" => OWL['Class'] }] } , @@ -40,10 +42,10 @@ module OpenTox OT.compound => { RDF["type"] => [{ "type" => "uri", "value" => OWL.ObjectProperty }] } , OT.feature => { RDF["type"] => [{ "type" => "uri", "value" => OWL.ObjectProperty }] } , OT.dataEntry => { RDF["type"] => [{ "type" => "uri", "value" => OWL.ObjectProperty }] } , - OT.acceptValue => { RDF["type"] => [{ "type" => "uri", "value" => OWL.ObjectProperty }] } , OT.values => { RDF["type"] => [{ "type" => "uri", "value" => OWL.ObjectProperty }] } , OT.algorithm => { RDF["type"] => [{ "type" => "uri", "value" => OWL.ObjectProperty }] } , OT.parameters => { RDF["type"] => [{ "type" => "uri", "value" => OWL.ObjectProperty }] } , + #object props for validation# OT.model => { RDF["type"] => [{ "type" => "uri", "value" => OWL.ObjectProperty }] } , OT.trainingDataset => { RDF["type"] => [{ "type" => "uri", "value" => OWL.ObjectProperty }] } , @@ -73,6 +75,8 @@ module OpenTox OT.hasStatus => { RDF["type"] => [{ "type" => "uri", "value" => OWL.AnnotationProperty }] } , OT.resultURI => { RDF["type"] => [{ "type" => "uri", "value" => OWL.AnnotationProperty }] } , OT.percentageCompleted => { RDF["type"] => [{ "type" => "uri", "value" => OWL.AnnotationProperty }] } , + OT.acceptValue => { RDF["type"] => [{ "type" => "uri", "value" => OWL.AnnotationProperty }] } , + # annotation props for validation OT.numUnpredicted => { RDF["type"] => [{ "type" => "uri", "value" => OWL.AnnotationProperty }] } , OT.crossvalidationFold => { RDF["type"] => [{ "type" => "uri", "value" => OWL.AnnotationProperty }] } , @@ -256,7 +260,8 @@ module OpenTox def add_metadata(uri,metadata) id = 0 metadata.each do |u,v| - if v.is_a? Array and u == OT.parameters + #if v.is_a? Array and (u == OT.parameters or u == RDF.type) + if v.is_a? Array and u == OT.parameters#or u == RDF.type) @object[uri][u] = [] unless @object[uri][u] v.each do |value| id+=1 @@ -267,7 +272,13 @@ module OpenTox @object[genid][name] = [{"type" => type(entry), "value" => entry }] end end - else # v.is_a? String + elsif v.is_a? Array and u == RDF.type + @object[uri] = {} unless @object[uri] + v.each do |value| + @object[uri][u] = [] unless @object[uri][u] + @object[uri][u] << {"type" => type(value), "value" => value } + end + elsif v.is_a? String @object[uri] = {} unless @object[uri] @object[uri][u] = [{"type" => type(v), "value" => v }] end @@ -309,6 +320,7 @@ module OpenTox OT.value => v } @object[feature][RDF["type"]] << { "type" => "uri", "value" => featuretype(value) } + #@object[feature][RDF["type"]] = { "type" => "uri", "value" => featuretype(value) } end # Serializers
RDF serialization of metadata fixed for multiple RDF.types
opentox_lazar
train
84b18a8f77f0904d8fb1a5cbcd8adb6f554ef3f3
diff --git a/spec/cucumber/parser/table_spec.rb b/spec/cucumber/parser/table_spec.rb index <HASH>..<HASH> 100644 --- a/spec/cucumber/parser/table_spec.rb +++ b/spec/cucumber/parser/table_spec.rb @@ -20,6 +20,7 @@ module Cucumber it "should parse a row with two cells" do parse("hello|my|friend").build.should == %w{hello my friend} end + end end end \ No newline at end of file
Testing that git push works on branch
cucumber_cucumber-ruby
train
c506c5a2bdaeddb424bdf081e968befe91d990d1
diff --git a/gem-proxy/src/main/java/de/saumya/mojo/proxy/Controller.java b/gem-proxy/src/main/java/de/saumya/mojo/proxy/Controller.java index <HASH>..<HASH> 100644 --- a/gem-proxy/src/main/java/de/saumya/mojo/proxy/Controller.java +++ b/gem-proxy/src/main/java/de/saumya/mojo/proxy/Controller.java @@ -31,7 +31,7 @@ public class Controller { private static final String SHA1 = ".sha1"; - private static final String RUBYGEMS_URL = "http://rubygems.org/gems"; + private static final String RUBYGEMS_URL = "https://rubygems.org/gems"; static final Map<String, Set<String>> BROKEN_GEMS = new HashMap<String, Set<String>>(); diff --git a/gem-proxy/src/main/java/de/saumya/mojo/proxy/MavenMetadataBuilder.java b/gem-proxy/src/main/java/de/saumya/mojo/proxy/MavenMetadataBuilder.java index <HASH>..<HASH> 100644 --- a/gem-proxy/src/main/java/de/saumya/mojo/proxy/MavenMetadataBuilder.java +++ b/gem-proxy/src/main/java/de/saumya/mojo/proxy/MavenMetadataBuilder.java @@ -11,11 +11,12 @@ public class MavenMetadataBuilder extends RubygemsHtmlVisitor { public static void main(String... args) throws Exception{ String first = null; - for(int i = 1; i < 10; i ++){ + for(int i = 1; i < 5; i ++){ long start = System.currentTimeMillis(); MavenMetadataBuilder visitor = new MavenMetadataBuilder("rails", true, Controller.BROKEN_GEMS.get("rails")); visitor.build(); System.err.println(System.currentTimeMillis() - start); + System.out.println(visitor.toXML()); if(first == null){ first = visitor.toXML().replaceFirst(".*<last.*\n", ""); } @@ -42,7 +43,7 @@ public class MavenMetadataBuilder extends RubygemsHtmlVisitor { xml.append(" <artifactId>").append(this.gemname).append("</artifactId>\n"); xml.append(" <versioning>\n"); xml.append(" <versions>\n"); - accept(new URL("http://rubygems.org/gems/" + this.gemname + "/versions")); + accept(new URL("https://rubygems.org/gems/" + this.gemname + "/versions")); xml.append(" </versions>\n"); xml.append(" </versioning>\n"); xml.append(" <lastUpdated>") diff --git a/gem-proxy/src/main/java/de/saumya/mojo/proxy/RubygemsHtmlVisitor.java b/gem-proxy/src/main/java/de/saumya/mojo/proxy/RubygemsHtmlVisitor.java index <HASH>..<HASH> 100644 --- a/gem-proxy/src/main/java/de/saumya/mojo/proxy/RubygemsHtmlVisitor.java +++ b/gem-proxy/src/main/java/de/saumya/mojo/proxy/RubygemsHtmlVisitor.java @@ -67,7 +67,7 @@ public abstract class RubygemsHtmlVisitor { } } - private void checkLine(String versionLine) { + private void checkLine(String versionLine) { if(!versionLine.contains("yanked") && !versionLine.contains("x86-m")){ String version = versionLine.replaceFirst("</a>.*$", "") .replaceFirst("^.*>", "").trim(); diff --git a/gem-proxy/src/main/ruby/create_pom.rb b/gem-proxy/src/main/ruby/create_pom.rb index <HASH>..<HASH> 100644 --- a/gem-proxy/src/main/ruby/create_pom.rb +++ b/gem-proxy/src/main/ruby/create_pom.rb @@ -2,18 +2,24 @@ require 'java' java_import 'de.saumya.mojo.ruby.ScriptUtils' -require ScriptUtils.getScriptFromResource('maven/tools/pom_generator.rb').to_s +require ScriptUtils.getScriptFromResource('maven/tools/gem_project.rb').to_s +require ScriptUtils.getScriptFromResource('maven/tools/minimal_project.rb').to_s require 'rubygems' require 'rubygems/format' class CreatePom def create(gemfile) - maven = Maven::Tools::GemProject.new - maven.load_gemspec Gem::Format.from_file_by_path(gemfile).spec - maven.add_defaults(:jruby_version => nil) + #maven = Maven::Tools::GemProject.new + #maven.load_gemspec spec(gemfile) + #maven.add_defaults(:jruby_version => nil) + maven = Maven::Tools::MinimalProject.new( spec( gemfile ) ) maven.to_xml end + + def spec(gemfile) + Gem::Format.from_file_by_path(gemfile).spec + end end CreatePom.new
use https instead of http for rubygems.org
torquebox_jruby-maven-plugins
train
679215de9759ee5cb175257fb142ab722032eaa7
diff --git a/tsdb/series_iterators.go b/tsdb/series_iterators.go index <HASH>..<HASH> 100644 --- a/tsdb/series_iterators.go +++ b/tsdb/series_iterators.go @@ -30,7 +30,7 @@ type seriesIDSetIterator struct { } func NewSeriesIDSetIterator(ss *SeriesIDSet) SeriesIDSetIterator { - if ss == nil || ss.IsEmpty() { + if ss == nil || ss.bitmap == nil { return nil } return &seriesIDSetIterator{ss: ss, itr: ss.Iterator()} diff --git a/tsdb/series_iterators_test.go b/tsdb/series_iterators_test.go index <HASH>..<HASH> 100644 --- a/tsdb/series_iterators_test.go +++ b/tsdb/series_iterators_test.go @@ -18,7 +18,6 @@ import ( "github.com/influxdata/influxdb/tsdb/seriesfile" "github.com/influxdata/influxdb/tsdb/tsi1" "github.com/influxdata/influxql" - "github.com/stretchr/testify/assert" ) func toSeriesIDs(ids []uint64) []tsdb.SeriesID { @@ -356,25 +355,3 @@ func BenchmarkIndex_ConcurrentWriteQuery(b *testing.B) { }) } } - -func TestSeriesIDSet_isEmpty(t *testing.T) { - sis := tsdb.NewSeriesIDSet(tsdb.NewSeriesID(1)) - assert.False(t, sis.IsEmpty()) - - sis = tsdb.NewSeriesIDSet() - assert.True(t, sis.IsEmpty()) - - sis = &tsdb.SeriesIDSet{} // sis.bitmap == nil - assert.True(t, sis.IsEmpty()) -} - -func TestNewSeriesIDSetIterator(t *testing.T) { - sisi := tsdb.NewSeriesIDSetIterator(tsdb.NewSeriesIDSet(tsdb.NewSeriesID(1))) - assert.NotNil(t, sisi) - - sisi = tsdb.NewSeriesIDSetIterator(tsdb.NewSeriesIDSet()) - assert.Nil(t, sisi) - - sisi = tsdb.NewSeriesIDSetIterator(nil) - assert.Nil(t, sisi) -} diff --git a/tsdb/series_set.go b/tsdb/series_set.go index <HASH>..<HASH> 100644 --- a/tsdb/series_set.go +++ b/tsdb/series_set.go @@ -48,10 +48,6 @@ func (s *SeriesIDSet) Bytes() int { return b } -func (s *SeriesIDSet) IsEmpty() bool { - return s == nil || s.bitmap == nil || s.bitmap.IsEmpty() -} - // Add adds the series id to the set. func (s *SeriesIDSet) Add(id SeriesID) { s.Lock()
chore: Revert "refactor(tsdb): remove read from unexported field (#<I>)" (#<I>) This reverts commit 0ec2b<I>b<I>c3f<I>ce5c<I>b<I>a8ac<I>a<I>. Fixes panic.
influxdata_influxdb
train
404702375c6feb9c9ec46a1257ef047842f7564e
diff --git a/includes/modules/export/mpdf/class-pb-pdf.php b/includes/modules/export/mpdf/class-pb-pdf.php index <HASH>..<HASH> 100644 --- a/includes/modules/export/mpdf/class-pb-pdf.php +++ b/includes/modules/export/mpdf/class-pb-pdf.php @@ -45,6 +45,7 @@ class Pdf extends Export { * @param array $args */ function __construct( array $args ) { + set_time_limit( 600 ); if ( ! defined( 'MPDF_WRITEHTML_MODE_DOC' ) ) { // Define some constants for mPDF::WriteHTML() // @see http://mpdf1.com/manual/index.php?tid=121
Adding extended time limit to allow pdf builds to complete.
pressbooks_pressbooks
train
c3014f535e97923b553c9c1d0e74b8a88681ab73
diff --git a/script/surveyor/specs/answer_spec.rb b/script/surveyor/specs/answer_spec.rb index <HASH>..<HASH> 100644 --- a/script/surveyor/specs/answer_spec.rb +++ b/script/surveyor/specs/answer_spec.rb @@ -2,22 +2,19 @@ require File.dirname(__FILE__) + '/../answer' describe Answer, " when first created" do - TEST_ID = 1 - TEST_CONTEXT_ID = "b3a_1" - TEST_QUESTION_ID = "2" - TEST_TEXT = "No / Rarely" - TEST_OPTIONS = {:help_text => "Never or rarely ever"} - - before do - @ans = Answer.new(TEST_ID, TEST_QUESTION_ID, TEST_CONTEXT_ID, TEST_TEXT, TEST_OPTIONS) + before do + question = mock("Question", :id => 2, :parser => mock("Parser", :new_answer_id => 1)) + args = {:text => "No / Rarely", :help_text => "Never or rarely ever", :reference_identifier => "b3a_1"} + options = {} + @ans = Answer.new(question, args, options) end it "should set inititalized variables to those passed in" do - @ans.id.should == TEST_ID - @ans.question_id.should == TEST_QUESTION_ID - @ans.context_id.should == TEST_CONTEXT_ID - @ans.text.should == TEST_TEXT - @ans.help_text.should == TEST_OPTIONS[:help_text] + @ans.id.should == 1 + @ans.question_id.should == 2 + @ans.reference_identifier.should == "b3a_1" + @ans.text.should == "No / Rarely" + @ans.help_text.should == "Never or rarely ever" end it "should output current state to yml" do @@ -25,42 +22,34 @@ describe Answer, " when first created" do end it "should create a normalized code from the answer text" do - # The answer object should take the title of the text and convert - # it to a code that is more appropirate for a database entry + # The answer object should take the title of the text and convert it to a code that is more appropirate for a database entry # Taking a few answers from the survey for testing - str = [] - str[0] = "This? is a in - t3rrible-@nswer of! (question) on" - str[1] = "Private insurance/ HMO/ PPO" - str[2] = "VA" - str[3] = "PMS (Premenstrual syndrome)/ PMDD (Premenstrual Dysphoric Disorder)" - str[4] = "Have never been employed outside the home" - str[5] = "Professional" - str[6] = "Not working because of temporary disability, but expect to return to a job" + strings = [ "This? is a in - t3rrible-@nswer of! (question) on", + "Private insurance/ HMO/ PPO", + "VA", + "PMS (Premenstrual syndrome)/ PMDD (Premenstrual Dysphoric Disorder)", + "Have never been employed outside the home", + "Professional", + "Not working because of temporary disability, but expect to return to a job" ] # What the results should look like - r_str = [] - r_str[0] = "this_t3rrible_nswer" - r_str[1] = "private_insurance_hmo_ppo" - r_str[2] = "va" - r_str[3] = "pms_pmdd" - r_str[4] = "never_been_employed_outside_home" - r_str[5] = "professional" - r_str[6] = "temporary_disability_expect_return_job" + codes = [ "this_t3rrible_nswer", + "private_insurance_hmo_ppo", + "va", + "pms_pmdd", + "never_been_employed_outside_home", + "professional", + "temporary_disability_expect_return_job" ] - count = 0 - str.each do |s| - - code = Answer.to_normalized_code(s) - code.should eql(r_str[count]) - count += 1 - + require File.dirname(__FILE__) + '/../../../lib/tiny_code' + strings.each_with_index do |s, i| + Columnizer.to_normalized_column(s).should == codes[i] end - end it "should create a normalized code automatically when initalized" do - @ans.code.should eql("no_rarely") + @ans.data_export_identifier.should eql("no_rarely") end end \ No newline at end of file
fixing surveyor parser answer spec
NUBIC_surveyor
train
ecd4ed1bdddf64b1a62d4fac9b989698025f14d9
diff --git a/helper/constraints/semver/constraints_test.go b/helper/constraints/semver/constraints_test.go index <HASH>..<HASH> 100644 --- a/helper/constraints/semver/constraints_test.go +++ b/helper/constraints/semver/constraints_test.go @@ -58,6 +58,9 @@ func TestConstraintCheck(t *testing.T) { {"= 1.0", "1.0.0", true}, {"1.0", "1.0.0", true}, + // Assert numbers are *not* compared lexically as in #4729 + {"> 10", "8", false}, + // Pre-releases are ordered according to Semver v2 {"> 2.0", "2.1.0-beta", true}, {"> 2.1.0-a", "2.1.0-beta", true},
test: assert semvers are *not* compared lexically
hashicorp_nomad
train
7bb09bca2a92bbd889855124e8bcfa278b8fe530
diff --git a/addict/__init__.py b/addict/__init__.py index <HASH>..<HASH> 100644 --- a/addict/__init__.py +++ b/addict/__init__.py @@ -2,7 +2,7 @@ from .addict import Dict __title__ = 'addict' -__version__ = '0.0.2' +__version__ = '0.0.3' __author__ = 'Mats Julian Olsen' __license__ = 'MIT' __copyright__ = 'Copyright 2014 Mats Julian Olsen' diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -23,5 +23,6 @@ setup( 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'Development Status :: 3' - ) + ), + description='A Python Dict whos keys can be set both using attribute and item syntax' )
Version bump and setup.py has a desc.
mewwts_addict
train
afd10949f0f2a2a6729ac9b6c7eb9e4d1c0ce839
diff --git a/django_pandas/io.py b/django_pandas/io.py index <HASH>..<HASH> 100644 --- a/django_pandas/io.py +++ b/django_pandas/io.py @@ -122,4 +122,5 @@ def read_frame(qs, fieldnames=(), index_col=None, coerce_float=False, if index_col is not None: df.set_index(index_col, inplace=True) + df.index = pd.to_datetime(df.index, errors="ignore") return df diff --git a/django_pandas/tests/models.py b/django_pandas/tests/models.py index <HASH>..<HASH> 100644 --- a/django_pandas/tests/models.py +++ b/django_pandas/tests/models.py @@ -86,6 +86,25 @@ class WideTimeSeries(models.Model): self.col4 ) +@python_2_unicode_compatible +class WideTimeSeriesDateField(models.Model): + date_ix = models.DateField() + col1 = models.FloatField() + col2 = models.FloatField() + col3 = models.FloatField() + col4 = models.FloatField() + + objects = DataFrameManager() + + def __str__(self): + return "{} {} {} {}".format( + self.date_ix, + self.col1, + self.col2, + self.col3, + self.col4 + ) + @python_2_unicode_compatible class PivotData(models.Model): diff --git a/django_pandas/tests/test_manager.py b/django_pandas/tests/test_manager.py index <HASH>..<HASH> 100644 --- a/django_pandas/tests/test_manager.py +++ b/django_pandas/tests/test_manager.py @@ -4,7 +4,7 @@ import numpy as np import pickle import django from .models import ( - DataFrame, WideTimeSeries, + DataFrame, WideTimeSeries, WideTimeSeriesDateField, LongTimeSeries, PivotData, MyModelChoice, Dude, Car, Spot ) import pandas.util.testing as tm @@ -71,9 +71,15 @@ class TimeSeriesTest(TestCase): col2=cols['col2'], col3=cols['col3'], col4=cols['col4'])) - WideTimeSeries.objects.bulk_create(create_list) + for ix, cols in self.ts.iterrows(): + create_list.append(WideTimeSeriesDateField(date_ix=ix, col1=cols['col1'], + col2=cols['col2'], + col3=cols['col3'], + col4=cols['col4'])) + WideTimeSeriesDateField.objects.bulk_create(create_list) + create_list = [LongTimeSeries(date_ix=r[0], series_name=r[1][0], value=r[1][1]) for r in self.ts2.iterrows()] @@ -90,6 +96,14 @@ class TimeSeriesTest(TestCase): self.assertIsInstance(df.index, pd.DatetimeIndex) self.assertIsNone(df.index.freq) + def test_widestorage_datefield(self): + + qs = WideTimeSeriesDateField.objects.all() + + df = qs.to_timeseries(index='date_ix', storage='wide') + + self.assertIsInstance(df.index, pd.DatetimeIndex) + def test_longstorage(self): qs = LongTimeSeries.objects.all() df = qs.to_timeseries(index='date_ix', pivot_columns='series_name', @@ -156,7 +170,7 @@ class TimeSeriesTest(TestCase): ##df = qs.to_timeseries(index='date_ix', pivot_columns='series_name', ##values='value', ##storage='long') - + def test_coerce_float(self): qs = LongTimeSeries.objects.all() ts = qs.to_timeseries(index='date_ix', coerce_float=True).resample('D').sum() @@ -207,7 +221,7 @@ class PivotTableTest(TestCase): if django.VERSION < (1, 9): - + class PassThroughManagerTests(TestCase): def setUp(self):
Make it work on DateField as well as DateTimeField
chrisdev_django-pandas
train
ff402e042c36dc95dc05e1fb63226661483af3fb
diff --git a/pools.go b/pools.go index <HASH>..<HASH> 100644 --- a/pools.go +++ b/pools.go @@ -326,9 +326,11 @@ const HTTP_MAX_RETRY = 5 // Someday golang network packages will implement standard // error codes. Until then #sigh func isHttpConnError(err error) bool { + estr := err.Error() return strings.Contains(estr, "broken pipe") || - strings.Contains(estr, "broken connection") + strings.Contains(estr, "broken connection") || + strings.Contains(estr, "connection reset") } func doHTTPRequest(req *http.Request) (*http.Response, error) {
MB-<I> : Retry http request when connection reset error is hit Note: Tried to implement this with net.OpError but it seems that OpError is not set for requests made with httpClient Change-Id: Icf2e<I>f<I>ca1c<I>d9bbe<I>d<I>e2a<I> Reviewed-on: <URL>
couchbase_go-couchbase
train
ac25819caecd702a96ba61e9c63f9c712470ce07
diff --git a/metrics2/dogstatsd/dogstatsd.go b/metrics2/dogstatsd/dogstatsd.go index <HASH>..<HASH> 100644 --- a/metrics2/dogstatsd/dogstatsd.go +++ b/metrics2/dogstatsd/dogstatsd.go @@ -108,7 +108,7 @@ func (d *Dogstatsd) WriteTo(w io.Writer) (int64, error) { adds, sets, obvs := d.buffer.Get() var count int64 for _, add := range adds { - n, err := fmt.Fprintf(w, "%s:%f|c%s\n", add.Name, add.Delta, tagValues(add.LVs)) + n, err := fmt.Fprintf(w, "%s:%f|c%s%s\n", add.Name, add.Delta, sampling(add.SampleRate), tagValues(add.LVs)) if err != nil { return count, err }
metrics/dogstatsd: add sample rate to Counter metrics
go-kit_kit
train
33a0050f587bb7414babe9d079477e7a3f31d49f
diff --git a/Tests/OrientDBCommandIndexLookupTest.php b/Tests/OrientDBCommandIndexLookupTest.php index <HASH>..<HASH> 100644 --- a/Tests/OrientDBCommandIndexLookupTest.php +++ b/Tests/OrientDBCommandIndexLookupTest.php @@ -40,10 +40,12 @@ class OrientDBIndexLookupTest extends OrientDBBaseTesting $key = 'testkey'; $this->db->DBOpen('demo', 'admin', 'admin'); $this->db->indexPut($key, '13:1'); - $this->db->DBOpen('demo', 'writer', 'writer'); - $record = $this->db->indexLookup($key); - $this->assertInstanceOf('OrientDBRecord', $record); + $db = new OrientDB('localhost', 2424); + $db->DBOpen('demo', 'writer', 'writer'); + $record = $db->indexLookup($key); $result = $this->db->indexRemove($key); + $this->assertInstanceOf('OrientDBRecord', $record); + } public function testIndexLookupWithWrongOptionCount()
Test testIndexLookupOnOpenDB() now cleanup its data
AntonTerekhov_OrientDB-PHP
train
966b08a1d5a2bc4056355a9915eaa6080bb0897b
diff --git a/bosh-dev/lib/bosh/dev/release_change_promoter.rb b/bosh-dev/lib/bosh/dev/release_change_promoter.rb index <HASH>..<HASH> 100644 --- a/bosh-dev/lib/bosh/dev/release_change_promoter.rb +++ b/bosh-dev/lib/bosh/dev/release_change_promoter.rb @@ -18,6 +18,10 @@ module Bosh::Dev shell.run("git checkout #{@candidate_sha}") + # Remove any artifacts from Jenkins setup + shell.run('git checkout .') + shell.run('git clean --force') + shell.run("git apply #{patch_file.path}") shell.run('git add -A :/') shell.run("git commit -m 'Adding final release for build #{@build_number}'") diff --git a/bosh-dev/spec/bosh/dev/release_change_promoter_spec.rb b/bosh-dev/spec/bosh/dev/release_change_promoter_spec.rb index <HASH>..<HASH> 100644 --- a/bosh-dev/spec/bosh/dev/release_change_promoter_spec.rb +++ b/bosh-dev/spec/bosh/dev/release_change_promoter_spec.rb @@ -34,6 +34,8 @@ module Bosh::Dev download_adapter.stub(:download).and_return(patch_file.path) expect(shell).to receive(:run).with("git checkout #{candidate_sha}").ordered + expect(shell).to receive(:run).with('git checkout .').ordered + expect(shell).to receive(:run).with('git clean --force').ordered expect(shell).to receive(:run).with("git apply #{patch_file.path}").ordered expect(shell).to receive(:run).with('git add -A :/').ordered expect(shell).to receive(:run).with("git commit -m 'Adding final release for build #{build_number}'").ordered
Clean directory after checking out candidate sha
cloudfoundry_bosh
train
86fd28b20bebdcbb87e989d264e8effacdbf00fa
diff --git a/ramda.js b/ramda.js index <HASH>..<HASH> 100644 --- a/ramda.js +++ b/ramda.js @@ -755,6 +755,8 @@ return result; }; + R.filter = curry2(filter); + /** * filterIdx * @@ -791,11 +793,6 @@ return filter(not(fn), list); }; - // Returns a new list containing only those items that match a given predicate function. - // n.b.: `ramda.filter` differs from `Array.prototype.filter` in that it does not distinguish "sparse - // arrays". - R.filter = curry2(filter); - // Like `filter`, but passes additional parameters to the predicate function. Parameters are // `list item`, `index of item in list`, `entire list`. //
Move filter export near declaration, replace docstring
ramda_ramda
train
1af05c6b0ed98a6977cc1a07dc598e22e7e64796
diff --git a/lib/util/data-server.js b/lib/util/data-server.js index <HASH>..<HASH> 100644 --- a/lib/util/data-server.js +++ b/lib/util/data-server.js @@ -15,7 +15,9 @@ if (!(config.frameCacheSize > 0) || config.frameCacheSize < 720) { var CLEAR_INTERVAL = 6000; var CACHE_TIME = 1000 * 60 * 2; +var BODY_CACHE_TIME = 1000 * 60 * 3; var MAX_CACHE_TIME = 1000 * 60 * 6; +var CACHE_BODY_SIZE = 1024 * 128; var MAX_LENGTH = config.reqCacheSize; var OVERFLOW_LENGTH = MAX_LENGTH * 3; var MAX_CACHE_SIZE = MAX_LENGTH * 2; @@ -91,6 +93,19 @@ var clearFrames = function(frame, now) { reduceFrameSize(frame, MAX_BUF_LEN4, MIN4, now); }; +function clearFiled(data, filed) { + var value = data[filed]; + if (value && value.length > CACHE_BODY_SIZE) { + data[filed] = ''; + } +} + +function clearBody(data) { + clearFiled(data, 'base64'); + clearFiled(data, 'bin'); + clearFiled(data, 'body'); +} + function clearCache() { var overflow = framesCache.length - MAX_FRAMES_LENGTH; var now = Date.now(); @@ -124,22 +139,27 @@ function clearCache() { overflow = len - MAX_CACHE_SIZE; preserveLen = len - PRESERVE_LEN; } - var isTimeout = function(curData, i) { + var isTimeout = function(cacheTime, i) { if (i < overflow) { return true; } - return curData.endTime && now - curData.endTime > (i >= preserveLen ? MAX_CACHE_TIME : CACHE_TIME); + return cacheTime && cacheTime > (i >= preserveLen ? MAX_CACHE_TIME : CACHE_TIME); }; for (var i = 0; i < len; i++) { var id = ids[i]; var curData = reqData[id]; - if (isTimeout(curData, i)) { + var cacheTime = curData.endTime && now - curData.endTime; + if (isTimeout(cacheTime, i)) { curData.abort && curData.abort(true); delete reqData[id]; } else { if (curData.abort && now - curData.startTime > MAX_CACHE_TIME) { curData.abort(true); } + if (cacheTime && cacheTime > BODY_CACHE_TIME) { + clearBody(curData.req); + clearBody(curData.res); + } _ids.push(id); } }
refactor: refine request data cache
avwo_whistle
train
8ba6d4b0ea661fd6c701fed56212ecc9c4acabb2
diff --git a/src/installer/lombok/installer/IdeLocation.java b/src/installer/lombok/installer/IdeLocation.java index <HASH>..<HASH> 100644 --- a/src/installer/lombok/installer/IdeLocation.java +++ b/src/installer/lombok/installer/IdeLocation.java @@ -66,7 +66,7 @@ public abstract class IdeLocation { } private static final String LEGAL_PATH_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_/"; - private static final String LEGAL_PATH_CHARS_WINDOWS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_/:\\ "; + private static final String LEGAL_PATH_CHARS_WINDOWS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,/;'[]{}!@#$^&()-_+= :\\"; public static String escapePath(String path) { StringBuilder out = new StringBuilder(); String legalChars = OsUtils.getOS() == OsUtils.OS.UNIX ? LEGAL_PATH_CHARS : LEGAL_PATH_CHARS_WINDOWS;
Add more characters not to escape on Windows. Fixes #<I>
rzwitserloot_lombok
train
18a65016142f63d04dc2da9789ec7bda3a6b3eb8
diff --git a/src/Config.php b/src/Config.php index <HASH>..<HASH> 100644 --- a/src/Config.php +++ b/src/Config.php @@ -14,21 +14,23 @@ class Config implements \ArrayAccess protected $config = []; /** - * Class constructor, runs on object creation. + * Create a Config object. * * @param mixed $context Raw array of configuration options or path to a - * configuration file or directory + * configuration file or directory containing one or + * more configuration files + * @param string $prefix A key under which the loaded config will be nested */ - public function __construct($context = null) + public function __construct($context = null, $prefix = null) { switch (gettype($context)) { case 'NULL': break; case 'array': - $this->config = $context; + $this->config = $prefix ? [$prefix => $context] : $context; break; case 'string': - $this->load($context); + $this->load($context, $prefix); break; default: throw new InvalidContextException('Failed to initialize config'); @@ -125,12 +127,13 @@ class Config implements \ArrayAccess * Load configuration options from a file or directory. * * @param string $path Path to configuration file or directory + * @param string $prefix A key under which the loaded config will be nested * @param bool $override Whether or not to override existing options with * values from the loaded file * * @return object This Config object */ - public function load($path, $override = true) + public function load($path, $prefix = null, $override = true) { $file = new SplFileInfo($path); @@ -139,10 +142,12 @@ class Config implements \ArrayAccess $loader = new $classPath($file->getRealPath()); + $newConfig = $prefix ? [$prefix => $loader->getArray()] : $loader->getArray(); + if ($override) { - $this->config = array_replace_recursive($this->config, $loader->getArray()); + $this->config = array_replace_recursive($this->config, $newConfig); } else { - $this->config = array_replace_recursive($loader->getArray(), $this->config); + $this->config = array_replace_recursive($newConfig, $this->config); } return $this; diff --git a/tests/ConfigTest.php b/tests/ConfigTest.php index <HASH>..<HASH> 100644 --- a/tests/ConfigTest.php +++ b/tests/ConfigTest.php @@ -72,11 +72,20 @@ class ConfigTest extends PHPUnit_Framework_TestCase $this->assertEquals('mysql', $config->get('driver')); } + public function test_it_can_load_additonal_files_with_a_prefix() + { + $config = new Config\Config(); + + $config->load(__DIR__ . '/files/php/config.php', 'database'); + + $this->assertEquals('mysql', $config->get('database.driver')); + } + public function test_it_can_load_additional_files_without_overriding_existing_options() { $config = new Config\Config(['driver' => 'sqlite']); - $config->load(__DIR__ . '/files/php/config.php', false); + $config->load(__DIR__ . '/files/php/config.php', null, false); $this->assertEquals('sqlite', $config->get('driver')); }
Creating and loading a config can now be prefixed
PHLAK_Config
train
04f62f23b235daf7618a240042e25cf2c4e89b5b
diff --git a/rqalpha/__init__.py b/rqalpha/__init__.py index <HASH>..<HASH> 100644 --- a/rqalpha/__init__.py +++ b/rqalpha/__init__.py @@ -63,6 +63,7 @@ def run_ipython_cell(line, cell=None): args = line.split() args.extend(["--source-code", cell if cell is not None else ""]) try: + # It raise exception every time run.main(args, standalone_mode=True) except SystemExit as e: pass diff --git a/rqalpha/__main__.py b/rqalpha/__main__.py index <HASH>..<HASH> 100644 --- a/rqalpha/__main__.py +++ b/rqalpha/__main__.py @@ -120,9 +120,10 @@ def run(**kwargs): from .utils import is_run_from_ipython if is_run_from_ipython(): import IPython + from .utils import RqAttrDict ipy = IPython.get_ipython() - report = results.get("sys_analyser", None) - ipy.user_global_ns["report"] = report + report = results.get("sys_analyser", {}) + ipy.user_global_ns["report"] = RqAttrDict(report) @cli.command() diff --git a/rqalpha/utils/__init__.py b/rqalpha/utils/__init__.py index <HASH>..<HASH> 100644 --- a/rqalpha/utils/__init__.py +++ b/rqalpha/utils/__init__.py @@ -68,6 +68,9 @@ class RqAttrDict(object): iteritems = items + def keys(self): + return self.__dict__.keys() + @staticmethod def _update_dict_recursive(target, other): if isinstance(other, RqAttrDict):
wrapper report as attrdict
ricequant_rqalpha
train
6446d747336a8f78c2ee9bf1a2e469c1255395be
diff --git a/lib/capybara/spec/test_app.rb b/lib/capybara/spec/test_app.rb index <HASH>..<HASH> 100644 --- a/lib/capybara/spec/test_app.rb +++ b/lib/capybara/spec/test_app.rb @@ -6,6 +6,8 @@ class TestApp < Sinatra::Base set :root, File.dirname(__FILE__) set :static, true + # Also check lib/capybara/spec/views/*.erb for pages not listed here + get '/' do 'Hello world! <a href="with_html">Relative</a>' end
Add conspicuous pointer at top of spec/test_app.rb to help contributors
teamcapybara_capybara
train
d7e54c93c0a11739d45182b975d9a8f2975c5cf6
diff --git a/lib/rbnacl/signatures/ed25519/signing_key.rb b/lib/rbnacl/signatures/ed25519/signing_key.rb index <HASH>..<HASH> 100644 --- a/lib/rbnacl/signatures/ed25519/signing_key.rb +++ b/lib/rbnacl/signatures/ed25519/signing_key.rb @@ -81,6 +81,20 @@ module RbNaCl buffer[0, signature_bytes] end + # Sign a message using this key + # + # @param message [String] Message to be signed by this key + # + # @return [String] Signature and the message as bytes + def sign_full(message) + buffer = Util.prepend_zeros(signature_bytes, message) + buffer_len = Util.zeros(FFI::Type::LONG_LONG.size) + + self.class.sign_ed25519(buffer, buffer_len, message, message.bytesize, @signing_key) + + buffer + end + # Return the raw seed value of this key # # @return [String] seed used to create this key diff --git a/lib/rbnacl/signatures/ed25519/verify_key.rb b/lib/rbnacl/signatures/ed25519/verify_key.rb index <HASH>..<HASH> 100644 --- a/lib/rbnacl/signatures/ed25519/verify_key.rb +++ b/lib/rbnacl/signatures/ed25519/verify_key.rb @@ -58,6 +58,29 @@ module RbNaCl true end + # Verify a signature for a given signed message + # + # Raises if the signature is invalid. + # + # @param signed_message [String] Message combined with signature to be authenticated + # + # @raise [BadSignatureError] if the signature check fails + # + # @return [Boolean] was the signature authentic? + def verify_full(signed_message) + raise LengthError, "Signed message can not be nil" if signed_message.nil? + + raise LengthError, "Signed message can not be shorter than a signature" if signed_message.bytesize <= signature_bytes + + buffer = Util.zeros(signed_message.bytesize) + buffer_len = Util.zeros(FFI::Type::LONG_LONG.size) + + success = self.class.sign_ed25519_open(buffer, buffer_len, signed_message, signed_message.bytesize, @key) + raise(BadSignatureError, "signature was forged/corrupt") unless success + + true + end + # Return the raw key in byte format # # @return [String] raw key as bytes diff --git a/spec/rbnacl/signatures/ed25519/signing_key_spec.rb b/spec/rbnacl/signatures/ed25519/signing_key_spec.rb index <HASH>..<HASH> 100644 --- a/spec/rbnacl/signatures/ed25519/signing_key_spec.rb +++ b/spec/rbnacl/signatures/ed25519/signing_key_spec.rb @@ -17,6 +17,11 @@ RSpec.describe RbNaCl::SigningKey do expect(subject.sign(message)).to eq signature end + it "signs messages, full version" do + expect(subject.sign_full(message)[0, RbNaCl::SigningKey.signature_bytes]).to eq signature + expect(subject.sign_full(message)[RbNaCl::SigningKey.signature_bytes, message.length]).to eq message + end + it "serializes to bytes" do expect(subject.to_bytes).to eq signing_key end diff --git a/spec/rbnacl/signatures/ed25519/verify_key_spec.rb b/spec/rbnacl/signatures/ed25519/verify_key_spec.rb index <HASH>..<HASH> 100644 --- a/spec/rbnacl/signatures/ed25519/verify_key_spec.rb +++ b/spec/rbnacl/signatures/ed25519/verify_key_spec.rb @@ -20,14 +20,30 @@ RSpec.describe RbNaCl::VerifyKey do expect(subject.verify(signature, message)).to eq true end + it "verifies correct signatures, full version" do + expect(subject.verify_full(signature + message)).to eq true + end + it "raises when asked to verify a bad signature" do expect { subject.verify(bad_signature, message) }.to raise_exception RbNaCl::BadSignatureError end + it "raises when asked to verify a bad signature, full version" do + expect { subject.verify_full(bad_signature + message) }.to raise_exception RbNaCl::BadSignatureError + end + it "raises when asked to verify a short signature" do expect { subject.verify(bad_signature[0, 63], message) }.to raise_exception RbNaCl::LengthError end + it "raises when asked to verify a nil signed message" do + expect { subject.verify_full(nil) }.to raise_exception RbNaCl::LengthError + end + + it "raises when asked to verify too short signed message" do + expect { subject.verify_full(signature) }.to raise_exception RbNaCl::LengthError + end + it "serializes to bytes" do expect(subject.to_bytes).to eq verify_key end
Added functions to the SigninKey and to the VeryKey classes for signed messages Added functions sign_full and verify_full to work with messages combined with their signatures, in comparison to the sign and verify.
crypto-rb_rbnacl
train
b7fffc2ee313a0f09bb3d10083694c212726e0f4
diff --git a/is_core/__init__.py b/is_core/__init__.py index <HASH>..<HASH> 100644 --- a/is_core/__init__.py +++ b/is_core/__init__.py @@ -11,7 +11,7 @@ def autodiscover(): except ImportError as ex: pass -VERSION = (0, 3, 0) +VERSION = (0, 3, 1) def get_version(): return '.'.join(map(str, VERSION)) diff --git a/is_core/rest/emitters.py b/is_core/rest/emitters.py index <HASH>..<HASH> 100644 --- a/is_core/rest/emitters.py +++ b/is_core/rest/emitters.py @@ -26,10 +26,11 @@ from django.db.models.query import QuerySet from django.db.models import Model, permalink from django.utils.xmlutils import SimplerXMLGenerator from django.utils.encoding import smart_unicode -from django.core.urlresolvers import reverse, NoReverseMatch +from django.core.urlresolvers import NoReverseMatch from django.core.serializers.json import DateTimeAwareJSONEncoder from django.http import HttpResponse from django.core import serializers +from django.utils.translation import ugettext as _ from piston.utils import HttpStatusCode, Mimer from piston.validate_jsonp import is_valid_jsonp_callback_value @@ -91,6 +92,13 @@ class Emitter(object): return ret + def smart_unicode(self, thing): + + if isinstance(thing, bool): + thing = thing and _('Yes') or _('No') + + return smart_unicode(thing, strings_only=True) + def construct(self): """ Recursively serialize a lot of types, and @@ -127,7 +135,7 @@ class Emitter(object): elif repr(thing).startswith("<django.db.models.fields.related.RelatedManager"): ret = _any(thing.all()) else: - ret = smart_unicode(thing, strings_only=True) + ret = self.smart_unicode(thing) return ret @@ -159,7 +167,15 @@ class Emitter(object): get_absolute_uri = False if handler or fields: - v = lambda f: getattr(data, f.attname) + + def v(f): + """ + If field has choices this return display value + """ + if f.choices: + return getattr(data, 'get_%s_display' % f.attname)() + + return getattr(data, f.attname) if not fields and handler: fields = getattr(handler, 'fields') diff --git a/is_core/rest/resource.py b/is_core/rest/resource.py index <HASH>..<HASH> 100644 --- a/is_core/rest/resource.py +++ b/is_core/rest/resource.py @@ -11,6 +11,7 @@ from piston.utils import MimerDataException, translate_mime, UnsupportedMediaTyp from emitters import Emitter from handler import HeadersResult +from is_core.utils.models import get_model_field_names class RestResource(Resource): @@ -207,6 +208,7 @@ class RestModelResource(DynamicRestHandlerResource): obj_fields.append(field.name) obj_fields += list_fields fields = list(list_fields) + for default_field in ['id', '_rest_links', '_obj_name']: fields.append(default_field) obj_fields.append(default_field)
REST return boolean as yes/no and field with choices as get_foo_display
matllubos_django-is-core
train
f78d77886377269013e6b6a2303d0c855d8b2711
diff --git a/lantern/fitness/chisquared.py b/lantern/fitness/chisquared.py index <HASH>..<HASH> 100644 --- a/lantern/fitness/chisquared.py +++ b/lantern/fitness/chisquared.py @@ -1,18 +1,20 @@ """Chi Squared Scoring function""" -import string - from lantern.analysis.frequency import ( frequency_analyze, chi_squared ) -from lantern.util import remove class ChiSquared: - """Score a text by comparing its frequency distribution against another.""" - def __init__(self, target_frequency_map, ngram=1): + """ + Score a text by comparing its frequency distribution against another. + + Parameters: + target_frequency_map (dict): symbol to frequency mapping of the distribution you want to compare to + """ + + def __init__(self, target_frequency_map): self.target_frequency = target_frequency_map - self.ngram = 1 def __call__(self, text): - return -chi_squared(frequency_analyze(text, self.ngram), self.target_frequency) + return -chi_squared(frequency_analyze(text), self.target_frequency) diff --git a/tests/fitness/test_chisquared.py b/tests/fitness/test_chisquared.py index <HASH>..<HASH> 100644 --- a/tests/fitness/test_chisquared.py +++ b/tests/fitness/test_chisquared.py @@ -1,12 +1,14 @@ """Test the chi-squared scoring function""" -# from lantern.analysis.frequency import ( -# english, frequency_to_probability, -# chi_squared, frequency_analyze -# ) -# from lantern.fitness import ChiSquared +from lantern.fitness import ChiSquared +def test_chisquared(): + scorer = ChiSquared({'a': 1, 'b': 2}) + text = 'aabbb' + assert scorer(text) == -0.1 + +# TODO: solve the floating point inaccuracy problem # def test_chisquared_english_unigrams(): # unigram_freq = frequency_to_probability(english.unigrams) # scorer = ChiSquared(english.unigrams)
Docs and cleanup for the ChiSquared fitness function
CameronLonsdale_lantern
train
8cf0b80a7843633018b66a35d9a55f30814a56b6
diff --git a/integration/buildfile_test.go b/integration/buildfile_test.go index <HASH>..<HASH> 100644 --- a/integration/buildfile_test.go +++ b/integration/buildfile_test.go @@ -2,11 +2,11 @@ package docker import ( "fmt" - "github.com/dotcloud/docker" "github.com/dotcloud/docker/archive" "github.com/dotcloud/docker/engine" "github.com/dotcloud/docker/image" "github.com/dotcloud/docker/nat" + "github.com/dotcloud/docker/server" "github.com/dotcloud/docker/utils" "io/ioutil" "net" @@ -384,7 +384,7 @@ func buildImage(context testContextTemplate, t *testing.T, eng *engine.Engine, u } dockerfile := constructDockerfile(context.dockerfile, ip, port) - buildfile := docker.NewBuildFile(srv, ioutil.Discard, ioutil.Discard, false, useCache, false, ioutil.Discard, utils.NewStreamFormatter(false), nil, nil) + buildfile := server.NewBuildFile(srv, ioutil.Discard, ioutil.Discard, false, useCache, false, ioutil.Discard, utils.NewStreamFormatter(false), nil, nil) id, err := buildfile.Build(context.Archive(dockerfile, t)) if err != nil { return nil, err @@ -799,7 +799,7 @@ func TestForbiddenContextPath(t *testing.T) { } dockerfile := constructDockerfile(context.dockerfile, ip, port) - buildfile := docker.NewBuildFile(srv, ioutil.Discard, ioutil.Discard, false, true, false, ioutil.Discard, utils.NewStreamFormatter(false), nil, nil) + buildfile := server.NewBuildFile(srv, ioutil.Discard, ioutil.Discard, false, true, false, ioutil.Discard, utils.NewStreamFormatter(false), nil, nil) _, err = buildfile.Build(context.Archive(dockerfile, t)) if err == nil { @@ -845,7 +845,7 @@ func TestBuildADDFileNotFound(t *testing.T) { } dockerfile := constructDockerfile(context.dockerfile, ip, port) - buildfile := docker.NewBuildFile(mkServerFromEngine(eng, t), ioutil.Discard, ioutil.Discard, false, true, false, ioutil.Discard, utils.NewStreamFormatter(false), nil, nil) + buildfile := server.NewBuildFile(mkServerFromEngine(eng, t), ioutil.Discard, ioutil.Discard, false, true, false, ioutil.Discard, utils.NewStreamFormatter(false), nil, nil) _, err = buildfile.Build(context.Archive(dockerfile, t)) if err == nil { @@ -917,8 +917,8 @@ func TestBuildFails(t *testing.T) { func TestBuildFailsDockerfileEmpty(t *testing.T) { _, err := buildImage(testContextTemplate{``, nil, nil}, t, nil, true) - if err != docker.ErrDockerfileEmpty { - t.Fatal("Expected: %v, got: %v", docker.ErrDockerfileEmpty, err) + if err != server.ErrDockerfileEmpty { + t.Fatal("Expected: %v, got: %v", server.ErrDockerfileEmpty, err) } } diff --git a/integration/server_test.go b/integration/server_test.go index <HASH>..<HASH> 100644 --- a/integration/server_test.go +++ b/integration/server_test.go @@ -1,9 +1,9 @@ package docker import ( - "github.com/dotcloud/docker" "github.com/dotcloud/docker/engine" "github.com/dotcloud/docker/runconfig" + "github.com/dotcloud/docker/server" "strings" "testing" "time" @@ -739,7 +739,7 @@ func TestListContainers(t *testing.T) { } } -func assertContainerList(srv *docker.Server, all bool, limit int, since, before string, expected []string) bool { +func assertContainerList(srv *server.Server, all bool, limit int, since, before string, expected []string) bool { job := srv.Eng.Job("containers") job.SetenvBool("all", all) job.SetenvInt("limit", limit) diff --git a/integration/utils_test.go b/integration/utils_test.go index <HASH>..<HASH> 100644 --- a/integration/utils_test.go +++ b/integration/utils_test.go @@ -14,11 +14,11 @@ import ( "testing" "time" - "github.com/dotcloud/docker" "github.com/dotcloud/docker/builtins" "github.com/dotcloud/docker/engine" "github.com/dotcloud/docker/runconfig" "github.com/dotcloud/docker/runtime" + "github.com/dotcloud/docker/server" "github.com/dotcloud/docker/utils" ) @@ -149,14 +149,14 @@ func getContainer(eng *engine.Engine, id string, t utils.Fataler) *runtime.Conta return c } -func mkServerFromEngine(eng *engine.Engine, t utils.Fataler) *docker.Server { +func mkServerFromEngine(eng *engine.Engine, t utils.Fataler) *server.Server { iSrv := eng.Hack_GetGlobalVar("httpapi.server") if iSrv == nil { panic("Legacy server field not set in engine") } - srv, ok := iSrv.(*docker.Server) + srv, ok := iSrv.(*server.Server) if !ok { - panic("Legacy server field in engine does not cast to *docker.Server") + panic("Legacy server field in engine does not cast to *server.Server") } return srv }
Update integration tests for server pkg Docker-DCO-<I>-
containers_storage
train
d2df380d4711734b184a3b62d9bbe0a93b966f65
diff --git a/source/library/com/restfb/types/send/MediaAttachment.java b/source/library/com/restfb/types/send/MediaAttachment.java index <HASH>..<HASH> 100644 --- a/source/library/com/restfb/types/send/MediaAttachment.java +++ b/source/library/com/restfb/types/send/MediaAttachment.java @@ -26,22 +26,57 @@ import com.restfb.Facebook; public class MediaAttachment extends MessageAttachment { @Facebook - private UrlPayload payload; + private MediaAttachmentPayload payload; public MediaAttachment(Type type, String imageUrl) { setType(type.toString().toLowerCase()); - payload = new UrlPayload(imageUrl); + if (imageUrl.matches("^\\d+$")) { + payload = new ReuseIdPayload(imageUrl); + } else { + payload = new UrlPayload(imageUrl); + } + } + + public void setIsReusable(boolean isReusable) { + payload.setIsReusable(isReusable); } - private static class UrlPayload { + private static class UrlPayload implements MediaAttachmentPayload { @Facebook private String url; + @Facebook("is_reusable") + private Boolean isReusable; + public UrlPayload(String urlString) { url = urlString; } + @Override + public void setIsReusable(boolean isReusable) { + this.isReusable = isReusable; + } + + } + + private static class ReuseIdPayload implements MediaAttachmentPayload { + + @Facebook("attachment_id") + private String attachmentId; + + public ReuseIdPayload(String urlString) { + attachmentId = urlString; + } + + @Override + public void setIsReusable(boolean isReusable) { + // ignore this here + } + } + + private interface MediaAttachmentPayload { + void setIsReusable(boolean isReusable); } public enum Type { diff --git a/source/library/com/restfb/types/send/SendResponse.java b/source/library/com/restfb/types/send/SendResponse.java index <HASH>..<HASH> 100644 --- a/source/library/com/restfb/types/send/SendResponse.java +++ b/source/library/com/restfb/types/send/SendResponse.java @@ -29,8 +29,8 @@ import lombok.Setter; /** * Represents the - * <a href="https://developers.facebook.com/docs/messenger-platform/send-api-reference#response">Messenger - * API Send Response</a>. + * <a href="https://developers.facebook.com/docs/messenger-platform/send-api-reference#response">Messenger API Send + * Response</a>. */ public class SendResponse extends AbstractFacebookType { @@ -43,4 +43,13 @@ public class SendResponse extends AbstractFacebookType { @Setter @Facebook("message_id") private String messageId; + + @Getter + @Setter + @Facebook("attachment_id") + private String attachmentId; + + public boolean hasReusableAttachment() { + return attachmentId != null; + } } diff --git a/source/test/java/com/restfb/types/SendApiTest.java b/source/test/java/com/restfb/types/SendApiTest.java index <HASH>..<HASH> 100644 --- a/source/test/java/com/restfb/types/SendApiTest.java +++ b/source/test/java/com/restfb/types/SendApiTest.java @@ -102,6 +102,32 @@ public class SendApiTest extends AbstractJsonMapperTests { } @Test + public void messageAudioAttachmentWithReuse() { + MediaAttachment attachment = new MediaAttachment(MediaAttachment.Type.AUDIO, "AUDIO_URL"); + attachment.setIsReusable(true); + Message recipient = new Message(attachment); + + DefaultJsonMapper mapper = new DefaultJsonMapper(); + String recipientJsonString = mapper.toJson(recipient, true); + + AssertJson.assertEquals("{\"attachment\":{\"payload\":{\"url\":\"AUDIO_URL\",\"is_reusable\":true},\"type\":\"audio\"}}", + recipientJsonString); + } + + @Test + public void messageAudioAttachmentReuseId() { + MediaAttachment attachment = new MediaAttachment(MediaAttachment.Type.AUDIO, "123456789"); + Message recipient = new Message(attachment); + + DefaultJsonMapper mapper = new DefaultJsonMapper(); + String recipientJsonString = mapper.toJson(recipient, true); + + AssertJson.assertEquals("{\"attachment\":{\"payload\":{\"attachment_id\":\"123456789\"},\"type\":\"audio\"}}", + recipientJsonString); + } + + + @Test public void messageLocationAttachment() { LocationAttachment attachment = new LocationAttachment(20, 30); Message recipient = new Message(attachment);
Issue #<I> - attachment_id and is_reusable added
restfb_restfb
train
2fe585428b4b97387e8820d16e27b9354b1c6edf
diff --git a/Console/AuthMakeCommand.php b/Console/AuthMakeCommand.php index <HASH>..<HASH> 100644 --- a/Console/AuthMakeCommand.php +++ b/Console/AuthMakeCommand.php @@ -126,7 +126,7 @@ class AuthMakeCommand extends Command protected function getViewPath($path) { return implode(DIRECTORY_SEPARATOR, [ - config('view.paths')[0] ?? resource_path('views'), $path + config('view.paths')[0] ?? resource_path('views'), $path, ]); } }
Apply fixes from StyleCI (#<I>)
illuminate_auth
train
17773ad492dd334822a00e1dcd41afe77bdc699f
diff --git a/app/models/no_cms/pages/page.rb b/app/models/no_cms/pages/page.rb index <HASH>..<HASH> 100644 --- a/app/models/no_cms/pages/page.rb +++ b/app/models/no_cms/pages/page.rb @@ -26,8 +26,9 @@ module NoCms::Pages after_move :rebuild_path def set_slug_and_path - self.slug = title.parameterize if slug.nil? && !title.nil? - self.slug = title.parameterize if slug.blank? && parent.nil? && Page.home && (Page.home != self) + self.slug = title.parameterize if slug.nil? && !title.nil? # If there's no slug then we create it + self.slug = title.parameterize if slug.blank? && !parent.nil? # If slug is blank and this page has a parent then we recreate it + self.slug = title.parameterize if slug.blank? && Page.home && (Page.home != self) # If slug is blank and there's already a home (and it's another page) then we recreate it self.rebuild_path if path.nil? || attribute_changed?('slug') end diff --git a/spec/models/nocms/pages/page_spec.rb b/spec/models/nocms/pages/page_spec.rb index <HASH>..<HASH> 100644 --- a/spec/models/nocms/pages/page_spec.rb +++ b/spec/models/nocms/pages/page_spec.rb @@ -95,7 +95,7 @@ describe NoCms::Pages::Page do context "when setting an empty slug and a parent" do - let(:page) { create :nocms_page, parent: create(:nocms_page)} + let(:page) { create :nocms_page, slug: '', parent: create(:nocms_page, slug: 'asdasdasd')} subject { page }
Bad testing caused a false positive :( Now we really test that a page with an empty slug and a parent doesn't get the empty slug
simplelogica_nocms-pages
train
33c2f401cd3e104bae125912a5e757a19fbcdc69
diff --git a/spec/shared/spec/dusen/active_record/base_ext_spec.rb b/spec/shared/spec/dusen/active_record/base_ext_spec.rb index <HASH>..<HASH> 100644 --- a/spec/shared/spec/dusen/active_record/base_ext_spec.rb +++ b/spec/shared/spec/dusen/active_record/base_ext_spec.rb @@ -181,6 +181,24 @@ shared_examples_for 'model with search syntax' do end end + + describe '.where_like' do + + it 'finds a word in any of the given columns' do + match1 = subject.create!(:name => 'word', :city => 'XXXX') + match2 = subject.create!(:name => 'XXXX', :city => 'word') + no_match = subject.create!(:name => 'XXXX', :city => 'XXXX') + subject.where_like([:name, :city] => 'word').to_a.should =~ [match1, match2] + end + + it 'requires all the given words' do + match1 = subject.create!(:city => 'word1 word2') + match2 = subject.create!(:city => 'word2 word1') + no_match = subject.create!(:city => 'word1') + subject.where_like(:city => ['word1', 'word2']).to_a.should =~ [match1, match2] + end + + end end
Add specs for .where_like
makandra_dusen
train
9faf29821fc4cb959b0459da7adb10be93ab4209
diff --git a/client.go b/client.go index <HASH>..<HASH> 100644 --- a/client.go +++ b/client.go @@ -457,10 +457,6 @@ func (c *Client) importBits(indexName string, frameName string, slice uint64, bi host: node.Host, port: node.Port, } - err = c.importNode(uri, bitsToImportRequest(indexName, frameName, slice, bits)) - if err != nil { - return errors.Wrap(err, "setting scheme on uri") - } eg.Go(func() error { return c.importNode(uri, bitsToImportRequest(indexName, frameName, slice, bits)) })
remove repeated call to importNode I think we were actually double importing - this appears to be a bug introduced by a merge - especially since the error message is wrong.
pilosa_go-pilosa
train
af390bbb546947f3f4cb122c304087f97654d2a1
diff --git a/openpnm/models/physics/electrical_conductance.py b/openpnm/models/physics/electrical_conductance.py index <HASH>..<HASH> 100644 --- a/openpnm/models/physics/electrical_conductance.py +++ b/openpnm/models/physics/electrical_conductance.py @@ -3,7 +3,79 @@ Pore-scale models for calculating the electrical conductance of conduits. """ import numpy as _np -__all__ = ["series_resistors"] +__all__ = ["series_resistors", "series_resistors_generic"] + + +def series_resistors_generic(target, + pore_conductivity='pore.electrical_conductivity', + throat_conductivity='throat.electrical_conductivity', + size_factors='throat.diffusive_size_factors'): + r""" + Calculate the electrical conductance of conduits in network, where a + conduit is ( 1/2 pore - full throat - 1/2 pore ). See the notes section. + + Parameters + ---------- + target : OpenPNM Object + The object which this model is associated with. This controls the + length of the calculated array, and also provides access to other + necessary properties. + + pore_conductivity : string + Dictionary key of the pore thermal conductivity values + + throat_conductivity : string + Dictionary key of the throat thermal conductivity values + + size_factors: str + Dictionary key of the conduit diffusive shape factors' values. + + Returns + ------- + g : ndarray + Array containing electrical conductance values for conduits in the + geometry attached to the given physics object. + + Notes + ----- + (1) This function requires that all the necessary phase properties already + be calculated. + + (2) This function calculates the specified property for the *entire* + network then extracts the values for the appropriate throats at the end. + + (3) This function assumes cylindrical throats with constant cross-section + area. Corrections for different shapes and variable cross-section area can + be imposed by passing the proper conduit_shape_factors argument. + + (4) shape_factor depends on the physics of the problem, i.e. diffusion-like + processes and fluid flow need different shape factors. + + """ + network = target.project.network + throats = network.map_throats(throats=target.Ts, origin=target) + phase = target.project.find_phase(target) + cn = network['throat.conns'][throats] + F = network[size_factors] + # Interpolate pore phase property values to throats + try: + Dt = phase[throat_conductivity][throats] + except KeyError: + Dt = phase.interpolate_data(propname=pore_conductivity)[throats] + try: + D1 = phase[pore_conductivity][cn[:, 0]] + D2 = phase[pore_conductivity][cn[:, 1]] + except KeyError: + D1 = phase.interpolate_data(propname=throat_conductivity)[cn[:, 0]] + D2 = phase.interpolate_data(propname=throat_conductivity)[cn[:, 1]] + if isinstance(F, dict): + g1 = D1 * F[f"{size_factors}.pore1"][throats] + gt = Dt * F[f"{size_factors}.throat"][throats] + g2 = D2 * F[f"{size_factors}.pore2"][throats] + gelec = 1 / (1 / g1 + 1 / gt + 1 / g2) + else: + gelec = Dt * F + return gelec def series_resistors(target,
added electrical conductance model consistent with the new size factor [ci skip]
PMEAL_OpenPNM
train
db33d75559dcd97633d28eb078a721d3765d6feb
diff --git a/src/index.js b/src/index.js index <HASH>..<HASH> 100644 --- a/src/index.js +++ b/src/index.js @@ -57,6 +57,7 @@ module.exports = (config = {}) => { // defaults client.apiVersion = config.apiVersion || 'v1'; client.endpoint = config.endpoint || process.env.VAULT_ADDR || 'http://127.0.0.1:8200'; + client.pathPrefix = config.pathPrefix || process.env.VAULT_PREFIX || ''; client.token = config.token || process.env.VAULT_TOKEN; const requestSchema = { @@ -76,7 +77,7 @@ module.exports = (config = {}) => { client.request = (options = {}) => { const valid = tv4.validate(options, requestSchema); if (!valid) return Promise.reject(tv4.error); - let uri = `${client.endpoint}/${client.apiVersion}${options.path}`; + let uri = `${client.endpoint}/${client.apiVersion}${client.pathPrefix}${options.path}`; // Replace variables in uri. uri = mustache.render(uri, options.json); // Replace unicode encodings. @@ -87,8 +88,8 @@ module.exports = (config = {}) => { } options.uri = uri; debug(options.method, uri); - // debug(options.json); - return rp(options).then(handleVaultResponse); + if (options.json) debug(options.json); + return rp(options).then(client.handleVaultResponse); }; client.help = (path, requestOptions) => {
Fixes for path prefixing on Vault. Use client.handleVaultResponse than handleVaultResponse
kr1sp1n_node-vault
train
da0d14f7c39bed77cf5665088936c10b528ceef1
diff --git a/classes/PodsForm.php b/classes/PodsForm.php index <HASH>..<HASH> 100644 --- a/classes/PodsForm.php +++ b/classes/PodsForm.php @@ -428,7 +428,7 @@ class PodsForm { if ( 0 < strlen( pods_v( 'label', $options, '' ) ) ) $_attributes[ 'data-label' ] = strip_tags( pods_v( 'label', $options ) ); - $_attributes[ 'id' ] = 'pods-form-ui-' . $name_clean; + $_attributes['id'] = 'pods-form-ui-' . $name_clean . ( self::$form_counter > 1 ? '-' . self::$form_counter : '' ); $_attributes[ 'class' ] = 'pods-form-ui-field-type-' . $type . ' pods-form-ui-field-name-' . $name_more_clean; if ( isset( $options[ 'dependency' ] ) && false !== $options[ 'dependency' ] )
*#<I> Use form_counter in ID attribute to be unique and prevent conflicts
pods-framework_pods
train
770a1f954dfbd1b956ffceaf67c38f10a4de4401
diff --git a/okhttp/pom.xml b/okhttp/pom.xml index <HASH>..<HASH> 100644 --- a/okhttp/pom.xml +++ b/okhttp/pom.xml @@ -26,6 +26,9 @@ <artifactId>maven-javadoc-plugin</artifactId> <configuration> <excludePackageNames>com.squareup.okhttp.internal:com.squareup.okhttp.internal.*</excludePackageNames> + <links> + <link>http://square.github.io/okio/</link> + </links> </configuration> </plugin> </plugins> diff --git a/okhttp/src/main/java/com/squareup/okhttp/Call.java b/okhttp/src/main/java/com/squareup/okhttp/Call.java index <HASH>..<HASH> 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/Call.java +++ b/okhttp/src/main/java/com/squareup/okhttp/Call.java @@ -236,9 +236,6 @@ public final class Call { throw new ProtocolException("Too many redirects: " + redirectionCount); } - // TODO: drop from POST to GET when redirected? HttpURLConnection does. - // TODO: confirm that Cookies are not retained across hosts. - if (!engine.sameConnection(followUp)) { engine.releaseConnection(); } diff --git a/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java b/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java index <HASH>..<HASH> 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java +++ b/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java @@ -78,12 +78,13 @@ public final class OkHttpClient implements URLStreamHandlerFactory, Cloneable { * * @see URLConnection#setConnectTimeout(int) */ - public void setConnectTimeout(long timeout, TimeUnit unit) { + public OkHttpClient setConnectTimeout(long timeout, TimeUnit unit) { if (timeout < 0) throw new IllegalArgumentException("timeout < 0"); if (unit == null) throw new IllegalArgumentException("unit == null"); long millis = unit.toMillis(timeout); if (millis > Integer.MAX_VALUE) throw new IllegalArgumentException("Timeout too large."); connectTimeout = (int) millis; + return this; } /** Default connect timeout (in milliseconds). */ @@ -96,12 +97,13 @@ public final class OkHttpClient implements URLStreamHandlerFactory, Cloneable { * * @see URLConnection#setReadTimeout(int) */ - public void setReadTimeout(long timeout, TimeUnit unit) { + public OkHttpClient setReadTimeout(long timeout, TimeUnit unit) { if (timeout < 0) throw new IllegalArgumentException("timeout < 0"); if (unit == null) throw new IllegalArgumentException("unit == null"); long millis = unit.toMillis(timeout); if (millis > Integer.MAX_VALUE) throw new IllegalArgumentException("Timeout too large."); readTimeout = (int) millis; + return this; } /** Default read timeout (in milliseconds). */ @@ -112,12 +114,13 @@ public final class OkHttpClient implements URLStreamHandlerFactory, Cloneable { /** * Sets the default write timeout for new connections. A value of 0 means no timeout. */ - public void setWriteTimeout(long timeout, TimeUnit unit) { + public OkHttpClient setWriteTimeout(long timeout, TimeUnit unit) { if (timeout < 0) throw new IllegalArgumentException("timeout < 0"); if (unit == null) throw new IllegalArgumentException("unit == null"); long millis = unit.toMillis(timeout); if (millis > Integer.MAX_VALUE) throw new IllegalArgumentException("Timeout too large."); writeTimeout = (int) millis; + return this; } /** Default write timeout (in milliseconds). */ @@ -365,8 +368,9 @@ public final class OkHttpClient implements URLStreamHandlerFactory, Cloneable { * Cancels all scheduled tasks tagged with {@code tag}. Requests that are already * complete cannot be canceled. */ - public void cancel(Object tag) { + public OkHttpClient cancel(Object tag) { dispatcher.cancel(tag); + return this; } public HttpURLConnection open(URL url) {
Small cleanups. Return the OkHttpClient on setters. Remove some completed TODOs in Call. Link to Okio in Javadoc.
square_okhttp
train
23ccdb1faf8fe2e504a1b7d3ac101311c03cd433
diff --git a/simulator/src/main/java/com/hazelcast/simulator/worker/performance/WorkerPerformanceMonitor.java b/simulator/src/main/java/com/hazelcast/simulator/worker/performance/WorkerPerformanceMonitor.java index <HASH>..<HASH> 100644 --- a/simulator/src/main/java/com/hazelcast/simulator/worker/performance/WorkerPerformanceMonitor.java +++ b/simulator/src/main/java/com/hazelcast/simulator/worker/performance/WorkerPerformanceMonitor.java @@ -133,9 +133,12 @@ public class WorkerPerformanceMonitor { private void updatePerformanceStates(long currentTimestamp) { for (TestContainer testContainer : testContainers) { + String testId = testContainer.getTestContext().getTestId(); if (!testContainer.isRunning()) { + trackerMap.remove(testId); continue; } + Map<String, Probe> probeMap = testContainer.getProbeMap(); Map<String, Histogram> intervalHistograms = new HashMap<String, Histogram>(probeMap.size()); @@ -166,9 +169,7 @@ public class WorkerPerformanceMonitor { } } - String testId = testContainer.getTestContext().getTestId(); PerformanceTracker tracker = getOrCreatePerformanceTracker(testId, testContainer); - tracker.update(intervalHistograms, intervalPercentileLatency, intervalAvgLatency, intervalMaxLatency, intervalOperationalCount, currentTimestamp); }
Removed PerformanceTrackers from finished TestContainers to prevent stale data to be sent over the wire and written to files until all tests have finished.
hazelcast_hazelcast-simulator
train
acf1266ac8f81952b5cf2aef2e95e863a5da3b14
diff --git a/test/unit/test_http.rb b/test/unit/test_http.rb index <HASH>..<HASH> 100644 --- a/test/unit/test_http.rb +++ b/test/unit/test_http.rb @@ -26,15 +26,62 @@ class SSRFProxyHTTPTest < Minitest::Test end # - # @note test creating SSRFProxy::HTTP objects with valid params + # @note test creating SSRFProxy::HTTP objects with GET method # - def test_ssrf_good + def test_ssrf_method_get ssrf = SSRFProxy::HTTP.new('http://127.0.0.1/xxURLxx', @opts) validate(ssrf) - assert_equal(SSRFProxy::HTTP, ssrf.class) - ssrf = SSRFProxy::HTTP.new(URI::parse('http://127.0.0.1/file.ext?query1=a&query2=b&query3=xxURLxx'), @opts) + @opts['post_data'] = 'xxURLxx' + SSRFProxy::HTTP.new('http://127.0.0.1/', @opts) + validate(ssrf) + end + + # + # @note test creating SSRFProxy::HTTP objects with HEAD method + # + def test_ssrf_method_head + @opts['method'] = 'HEAD' + ssrf = SSRFProxy::HTTP.new('http://127.0.0.1/xxURLxx', @opts) + validate(ssrf) + @opts['post_data'] = 'xxURLxx' + SSRFProxy::HTTP.new('http://127.0.0.1/', @opts) + validate(ssrf) + end + + # + # @note test creating SSRFProxy::HTTP objects with DELETE method + # + def test_ssrf_method_delete + @opts['method'] = 'DELETE' + ssrf = SSRFProxy::HTTP.new('http://127.0.0.1/xxURLxx', @opts) + validate(ssrf) + @opts['post_data'] = 'xxURLxx' + SSRFProxy::HTTP.new('http://127.0.0.1/', @opts) + validate(ssrf) + end + + # + # @note test creating SSRFProxy::HTTP objects with POST method + # + def test_ssrf_method_post + @opts['method'] = 'POST' + ssrf = SSRFProxy::HTTP.new('http://127.0.0.1/xxURLxx', @opts) + validate(ssrf) + @opts['post_data'] = 'xxURLxx' + SSRFProxy::HTTP.new('http://127.0.0.1/', @opts) + validate(ssrf) + end + + # + # @note test creating SSRFProxy::HTTP objects with HEAD method + # + def test_ssrf_method_put + @opts['method'] = 'PUT' + ssrf = SSRFProxy::HTTP.new('http://127.0.0.1/xxURLxx', @opts) + validate(ssrf) + @opts['post_data'] = 'xxURLxx' + SSRFProxy::HTTP.new('http://127.0.0.1/', @opts) validate(ssrf) - assert_equal(SSRFProxy::HTTP, ssrf.class) end #
Add tests for SSRF request methods
bcoles_ssrf_proxy
train
b1106b5e0057cdef84e8a610e1dfddae6628f67b
diff --git a/charts/Bar.js b/charts/Bar.js index <HASH>..<HASH> 100644 --- a/charts/Bar.js +++ b/charts/Bar.js @@ -61,6 +61,7 @@ export default class Bar extends Component{ this.padding = { top: + // releated to font size of title and subtitle. (this.props.title ? 50 : 0) + ( this.props.subtitle ? 50 : 0) + 20, right:20, @@ -70,6 +71,7 @@ export default class Bar extends Component{ } componentDidMount(){ + // need to be refactor with timing function. let animationHub = []; this.props.series.forEach(({data},index) => { @@ -120,6 +122,8 @@ export default class Bar extends Component{ } = this.props; return series.map((data,index) => { + + // theme info required. return ( <Shape key = { index } diff --git a/mockup/chart.js b/mockup/chart.js index <HASH>..<HASH> 100644 --- a/mockup/chart.js +++ b/mockup/chart.js @@ -81,17 +81,43 @@ export default class Main extends Component{ getSeries() { return [ { - data:200, - normalFill:"", - activeFill:"", - normalStroke:"", - activeStroke:"" - },{ - data:130, - normalFill:"", - activeFill:"", - normalStroke:"", - activeStroke:"" + theme:new Theme({ + stroke:{ + active:"", + normal:"" + }, + fill:{ + active:"", + normal:"" + } + }), + data:[200,300,400,600] + }, + { + theme:new Theme({ + stroke:{ + active:"", + normal:"" + }, + fill:{ + active:"", + normal:"" + } + }), + data:[200,300,400,600] + }, + { + theme:new Theme({ + stroke:{ + active:"", + normal:"" + }, + fill:{ + active:"", + normal:"" + } + }), + data:[200,300,400,600] } ] }
update mockup,added comments.
react-native-china_react-native-animate-chart
train
6e5e6ef28ef46cb474a632a353bdb4f3e4d11582
diff --git a/rosetta/views.py b/rosetta/views.py index <HASH>..<HASH> 100644 --- a/rosetta/views.py +++ b/rosetta/views.py @@ -371,7 +371,7 @@ def lang_sel(request, langid, idx): third_party_apps = rosetta_i18n_catalog_filter in ('all', 'third-party') django_apps = rosetta_i18n_catalog_filter in ('all', 'django') project_apps = rosetta_i18n_catalog_filter in ('all', 'project') - file_ = find_pos(langid, project_apps=project_apps, django_apps=django_apps, third_party_apps=third_party_apps)[int(idx)] + file_ = sorted(find_pos(langid, project_apps=project_apps, django_apps=django_apps, third_party_apps=third_party_apps), key=get_app_name)[int(idx)] storage.set('rosetta_i18n_lang_code', langid) storage.set('rosetta_i18n_lang_name', six.text_type([l[1] for l in settings.LANGUAGES if l[0] == langid][0]))
fixed lang_sel view picking the wrong file.
mbi_django-rosetta
train
d42736bff9316eb7aaa222554ab3e70559a6467c
diff --git a/sock_modules/emoji.js b/sock_modules/emoji.js index <HASH>..<HASH> 100644 --- a/sock_modules/emoji.js +++ b/sock_modules/emoji.js @@ -2,7 +2,7 @@ var async = require('async'); var discourse, configuration, - emojiSig = "<!-- Emoji'd by"; + emojiSig = '<!-- Emoji\'d by'; exports.description = 'Automatically replace emoji with Discourse emoji codes'; @@ -39,8 +39,8 @@ exports.onMessage = function onMessage(message, post, callback) { } //Sign the post so we don't process it again - raw += "\n\n" + emojiSig + " " + exports.name + " " + exports.version + "-->"; - discourse.editPost(post.id, raw, exports.name + " " + exports.version, function () { + raw += '\n\n' + emojiSig + ' ' + exports.name + ' ' + exports.version + '-->'; + discourse.editPost(post.id, raw, exports.name + ' ' + exports.version, function () { flow(null, true); }); @@ -49,11 +49,11 @@ exports.onMessage = function onMessage(message, post, callback) { // discourse.log(item); // callback(); //}, function () { - // discourse.log("Emoji in post " + post.id + " replaced"); + // discourse.log('Emoji in post ' + post.id + ' replaced'); // //Sign the post so we don't process it again - // raw += "\n\n" + emojiSig + " " + exports.name + " " + exports.version + "-->"; - // discourse.editPost(post.id, raw, exports.name + " " + exports.version, function () { + // raw += '\n\n' + emojiSig + ' ' + exports.name + ' ' + exports.version + '-->'; + // discourse.editPost(post.id, raw, exports.name + ' ' + exports.version, function () { // flow(null, true); // }); //}); @@ -70,6 +70,6 @@ exports.onMessage = function onMessage(message, post, callback) { }; var emojiLookup = { - "☺": ":smile:", - "☹": ":frowning:" + '☺': ':smile:', + '☹': ':frowning:' }; \ No newline at end of file diff --git a/sock_modules/spellar.js b/sock_modules/spellar.js index <HASH>..<HASH> 100644 --- a/sock_modules/spellar.js +++ b/sock_modules/spellar.js @@ -9,7 +9,7 @@ var discourse, dictionary, username, spellcheckerActive = false, - spellardSig = "<!-- Spellar'd by"; + spellardSig = '<!-- Spellar\'d by'; exports.description = 'Automaticly trak adn corect speling misteaks'; @@ -56,8 +56,8 @@ function initialiseDictionary() { } dictionary = dict; spellcheckerActive = true; - discourse.log("Laoded dictonary " + configuration.baseDictName); - discourse.log("Spellar iz aktiv"); + discourse.log('Laoded dictonary ' + configuration.baseDictName); + discourse.log('Spellar iz aktiv'); loadAddtitionalDictionaries(); }); }); @@ -73,12 +73,12 @@ function loadAddtitionalDictionaries() { discourse.error(err); } else { dictionary.addDictionary(data); - discourse.log("Laoded dictonary " + dict); + discourse.log('Laoded dictonary ' + dict); } flow(err); }); }, function () { - discourse.log("Al dictonaries laoded"); + discourse.log('Al dictonaries laoded'); }); } } @@ -109,7 +109,7 @@ exports.onMessage = function onMessage(message, post, callback) { }; function spellCheckPost(post, callback) { - discourse.log("Spellaring psot " + post.id); + discourse.log('Spellaring psot ' + post.id); var raw = post.raw; spellcheck(dictionary, raw, function (err, typos) { if (err) { @@ -126,10 +126,10 @@ function spellCheckPost(post, callback) { // - `to`: The end offset for the typo within the text (integer) // - `length`: Word length (integer) }); - discourse.log("Psot " + post.id + " spellard"); + discourse.log('Psot ' + post.id + ' spellard'); //Sign the post so we don't spellar it again - raw += "\n\n" + spellardSig + " " + exports.name + " " + exports.version + "-->"; - discourse.editPost(post.id, raw, exports.name + " " + exports.version, callback(null, true)); + raw += '\n\n' + spellardSig + ' ' + exports.name + ' ' + exports.version + '-->'; + discourse.editPost(post.id, raw, exports.name + ' ' + exports.version, callback(null, true)); }); }; \ No newline at end of file
Code style tweaks So @accalia doesn't shout at me when my code triggers a million eslint errors ☺
SockDrawer_SockBot
train
77e6a5a61ffa3e187b784f999123d384e4e5bc8f
diff --git a/src/ducks/triggers/index.js b/src/ducks/triggers/index.js index <HASH>..<HASH> 100644 --- a/src/ducks/triggers/index.js +++ b/src/ducks/triggers/index.js @@ -49,14 +49,14 @@ export const buildTriggerFrequencyOptions = (konnector, options) => { frequency: parseFrequency(konnector.frequency) } - if (frequencyOptions.frequency === 'daily') { + if (frequencyOptions.frequency === DAILY_FREQUENCY) { return { ...frequencyOptions, hours } } - if (frequencyOptions.frequency === 'weekly') { + if (frequencyOptions.frequency === WEEKLY_FREQUENCY) { return { ...frequencyOptions, hours, diff --git a/src/ducks/triggers/test/triggers.spec.js b/src/ducks/triggers/test/triggers.spec.js index <HASH>..<HASH> 100644 --- a/src/ducks/triggers/test/triggers.spec.js +++ b/src/ducks/triggers/test/triggers.spec.js @@ -6,7 +6,6 @@ describe('Trigger Duck', () => { const konnector = { slug: 'test' } const options = { - frequency: 'weekly', day: 1, hours: 14, minutes: 15
☔️ test: better trigger frequency test
cozy_cozy-home
train
137d950a997f8af56eac513b393842733015f0d2
diff --git a/gwpy/segments/flag.py b/gwpy/segments/flag.py index <HASH>..<HASH> 100644 --- a/gwpy/segments/flag.py +++ b/gwpy/segments/flag.py @@ -345,9 +345,9 @@ class DataQualityFlag(object): @padding.setter def padding(self, pad): if pad is None: - self._padding = (float(0), float(0)) + self._padding = (0., 0.) else: - self._padding = (float(pad[0]), float(pad[1])) + self._padding = tuple([0. if p == None else float(p) for p in pad]) @padding.deleter def padding(self):
Added check for None entry in pad tuple
gwpy_gwpy
train
c35cc2763b21a366d7c4323778f7191c26aed3f8
diff --git a/packages/heroku-redis-jsplugin/lib/commands/redis/shared.js b/packages/heroku-redis-jsplugin/lib/commands/redis/shared.js index <HASH>..<HASH> 100644 --- a/packages/heroku-redis-jsplugin/lib/commands/redis/shared.js +++ b/packages/heroku-redis-jsplugin/lib/commands/redis/shared.js @@ -1,5 +1,6 @@ 'use strict'; -var Heroku = require('heroku-client'); +let Heroku = require('heroku-client'); +let cli = require('heroku-cli-util'); const HOST = process.env.HEROKU_REDIS_HOST || 'redis-api.heroku.com' ; const PATH = '/redis/v0/databases'; @@ -11,9 +12,9 @@ function request(context, path, method, body) { path: `${PATH}/${path}`, host: HOST, auth: `${context.auth.username}:${context.auth.password}`, - headers: { + headers: cli.extend({ 'Accept': 'application/json' - }, + }, JSON.parse(process.env.HEROKU_HEADERS)), body: body }); }
Pass headers down to Redis API
heroku_cli
train
f7aaf8a0a5a5df97f2a3d21dca893931a7e5b629
diff --git a/src/Processes/Schema.php b/src/Processes/Schema.php index <HASH>..<HASH> 100644 --- a/src/Processes/Schema.php +++ b/src/Processes/Schema.php @@ -17,6 +17,8 @@ class Migrations { public static function exec($rt = null) { + Schema::ini(); + // $root = is_null($rt) ? Process::root : $rt ; // $r=glob($root."database/schema/*.php"); @@ -85,7 +87,7 @@ class Migrations { Schema::create(Config::get('database.migration'),function($tab) { - $tab->inc("pk_schema"); + $tab->id("pk_schema"); $tab->string("name_schema"); $tab->timestamp("date_schema"); $tab->string("status_schema"); @@ -118,6 +120,8 @@ class Migrations public static function rollback($rt = null) { + Schema::ini(); + // $Root = is_null($rt) ? Process::root : $rt ; // $r=glob($Root."database/schema/*.php");
init schema and replace inc function by id function because it deprecated
vinala_kernel
train
529070b6e113f382d5c7c7163c1fe0fb96feb48d
diff --git a/pycbc/__init__.py b/pycbc/__init__.py index <HASH>..<HASH> 100644 --- a/pycbc/__init__.py +++ b/pycbc/__init__.py @@ -12,6 +12,3 @@ Provides """ __author__ = 'Karsten Wiesner <karsten.wiesner@ligo.org>' -__all__ = ["datavecstim_opencl, datavecterm_cpu, datavector, fft, \ - highpassfilter, injector, matchedfilter, overwhiteningfilter, \ - resampler, singledetectorevent, straindata, templatebank"]
temporarily removed the __all__ list from the top-level __init__.py
gwastro_pycbc
train
a6eb2d4bd1148aeb2ac3272bb22c1731b35ed22e
diff --git a/test/RetrieveRecord.test.php b/test/RetrieveRecord.test.php index <HASH>..<HASH> 100644 --- a/test/RetrieveRecord.test.php +++ b/test/RetrieveRecord.test.php @@ -170,7 +170,7 @@ public function testGetRowNumberFromOtherColumns($filePath) { $originalRows = TestHelper::createCsv($filePath); $csv = new Csv($filePath); - $randomRowNumber = array_rand($originalRows); + $randomRowNumber = array_rand($originalRows) - 1; $headers = $originalRows[0]; $row = []; foreach($originalRows[$randomRowNumber + 1] as $headerI => $value) {
Fix off-by-one error in test
g105b_phpcsv
train
522f608d02cb8ab82a2ee8cc3ac9d5717f6ae90c
diff --git a/course/mod.php b/course/mod.php index <HASH>..<HASH> 100644 --- a/course/mod.php +++ b/course/mod.php @@ -5,6 +5,7 @@ require("../config.php"); require("lib.php"); + require_login(); if (isset($cancel)) { if (!empty($SESSION->returnpage)) { @@ -26,8 +27,6 @@ $mod = (object)$_POST; } - require_login($mod->course); - if (!isteacher($mod->course)) { error("You can't modify this course!"); } @@ -111,6 +110,10 @@ if (! $cm = get_record("course_modules", "id", $id)) { error("This course module doesn't exist"); } + + if (!isteacher($cm->course)) { + error("You can't modify this course!"); + } move_module($cm, $move); @@ -129,6 +132,10 @@ if (! $cm = get_record("course_modules", "id", $hide)) { error("This course module doesn't exist"); } + + if (!isteacher($cm->course)) { + error("You can't modify this course!"); + } hide_course_module($cm->id); @@ -148,6 +155,10 @@ error("This course module doesn't exist"); } + if (!isteacher($cm->course)) { + error("You can't modify this course!"); + } + if (! $section = get_record("course_sections", "id", $cm->section)) { error("This module doesn't exist"); } @@ -180,8 +191,6 @@ error("This course doesn't exist"); } - require_login($course->id); - if (!isteacher($course->id)) { error("You can't modify this course!"); } @@ -227,6 +236,10 @@ error("This course doesn't exist"); } + if (!isteacher($course->id)) { + error("You can't modify this course!"); + } + if (! $module = get_record("modules", "id", $cm->module)) { error("This module doesn't exist"); } @@ -304,8 +317,6 @@ error("No action was specfied"); } - require_login($course->id); - if (!isteacher($course->id)) { error("You can't modify this course!"); }
Important bug fixed! Non-teachers could modify course!
moodle_moodle
train
8fba0f4a51a91e5735e5d1fc08cec39cc6ea34f1
diff --git a/clevertap-android-sdk/src/main/java/com/clevertap/android/sdk/CleverTapAPI.java b/clevertap-android-sdk/src/main/java/com/clevertap/android/sdk/CleverTapAPI.java index <HASH>..<HASH> 100644 --- a/clevertap-android-sdk/src/main/java/com/clevertap/android/sdk/CleverTapAPI.java +++ b/clevertap-android-sdk/src/main/java/com/clevertap/android/sdk/CleverTapAPI.java @@ -8286,7 +8286,7 @@ public class CleverTapAPI implements CTInAppNotification.CTInAppNotificationList } if (ctProductConfigController == null) { - ctProductConfigController = new CTProductConfigController(context, getCleverTapID(), config, this, this); + ctProductConfigController = new CTProductConfigController(context, getCleverTapID(), config, this); getConfigLogger().verbose(config.getAccountId(), "Product Config initialized"); } if (fromPlayServices && ctProductConfigController != null && !ctProductConfigController.isInitialized()) { diff --git a/clevertap-android-sdk/src/main/java/com/clevertap/android/sdk/product_config/CTProductConfigController.java b/clevertap-android-sdk/src/main/java/com/clevertap/android/sdk/product_config/CTProductConfigController.java index <HASH>..<HASH> 100644 --- a/clevertap-android-sdk/src/main/java/com/clevertap/android/sdk/product_config/CTProductConfigController.java +++ b/clevertap-android-sdk/src/main/java/com/clevertap/android/sdk/product_config/CTProductConfigController.java @@ -50,12 +50,12 @@ public class CTProductConfigController { private int[] arpValues = new int[]{DEFAULT_NO_OF_CALLS, DEFAULT_WINDOW_LENGTH_MINS};//0 is for rc_n, 1 is for rc_w - public CTProductConfigController(Context context, String guid, CleverTapInstanceConfig config, Listener listener, CTProductConfigListener ctProductConfigListener) { + public CTProductConfigController(Context context, String guid, CleverTapInstanceConfig config, Listener listener) { this.context = context; this.guid = guid; this.config = config; cleverTapApiListener = listener; - listenerList.add(ctProductConfigListener); + listenerList.add(listener); initAsync(); } @@ -481,7 +481,7 @@ public class CTProductConfigController { FETCH_FAILED, ACTIVATE_SUCCESS, ACTIVATE_FAILED } - public interface Listener { + public interface Listener extends CTProductConfigListener { void fetchProductConfig(); } } \ No newline at end of file
feat(Product Config): 1. Added checks to avoid subsequent fetch & activate requests if already requested <URL>
CleverTap_clevertap-android-sdk
train
99ea9259265858f7a04e243df438cea38038dfdd
diff --git a/src/Db/Redis.php b/src/Db/Redis.php index <HASH>..<HASH> 100644 --- a/src/Db/Redis.php +++ b/src/Db/Redis.php @@ -4,8 +4,20 @@ namespace Siler\Redis; use Siler\Container; +/** + * Default Redis instance name on Siler\Container. + */ const DEFAULT_INSTANCE = 'redis_default_instance'; +/** + * Creates an instance and connects to a Redis server. + * + * @param string $host + * @param int $port + * @param string $redisInstance + * + * @return \Redis + */ function connect(string $host = '127.0.0.1', int $port = 6379, string $redisInstance = DEFAULT_INSTANCE): \Redis { $redis = new \Redis(); @@ -16,21 +28,44 @@ function connect(string $host = '127.0.0.1', int $port = 6379, string $redisInst return $redis; } - +/** + * Gets the value from the given $key. + * + * @param string $key + * @param string $redisInstance + * + * @return mixed + */ function get(string $key, string $redisInstance = DEFAULT_INSTANCE) { - $redis = Container\get(DEFAULT_INSTANCE); + $redis = Container\get($redisInstance); return $redis->get($key); } +/** + * Sets a value on the given $key. + * + * @param string $key + * @param string $val + * @param string $redisInstance + * + * @return mixed + */ function set(string $key, string $val, string $redisInstance = DEFAULT_INSTANCE) { - $redis = Container\get(DEFAULT_INSTANCE); + $redis = Container\get($redisInstance); return $redis->set($key, $val); } -function has(string $key): bool +/** + * Checks if the key exists. + * + * @param string $key + * + * @return bool + */ +function has(string $key, string $redisInstance = DEFAULT_INSTANCE): bool { - $redis = Container\get(DEFAULT_INSTANCE); + $redis = Container\get($redisInstance); return $redis->exists($key) > 0; }
redis: fix instance usage and add docblocks
leocavalcante_siler
train
e5c4d1e9ab5e33f99cd175dd1d3702dd7b0cf4a8
diff --git a/Notifications/ResetPassword.php b/Notifications/ResetPassword.php index <HASH>..<HASH> 100644 --- a/Notifications/ResetPassword.php +++ b/Notifications/ResetPassword.php @@ -60,7 +60,7 @@ class ResetPassword extends Notification ->subject(Lang::getFromJson('Reset Password Notification')) ->line(Lang::getFromJson('You are receiving this email because we received a password reset request for your account.')) ->action(Lang::getFromJson('Reset Password'), url(config('app.url').route('password.reset', $this->token, false))) - ->line(Lang::getFromJson('This password reset link will expire in :count minutes.', config('auth.passwords.users.expire'))) + ->line(Lang::getFromJson('This password reset link will expire in :count minutes.', [config('auth.passwords.users.expire')])) ->line(Lang::getFromJson('If you did not request a password reset, no further action is required.')); }
Pass second argument to Lang::getFromJson as an array.
illuminate_auth
train
34946ee827f1c9c3baaac8ed17eeac4f913d4089
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -15,7 +15,7 @@ setup( python_requires='~=3.3', description='This is a library used to manipulate and verify ipv4 address\'s. ucast and mcast', keywords='ipv4 ip multicast unicast network engineer', - url='https://github.com/btr1975/ipaddresstools', + url='https://ipaddresstools.readthedocs.io', author='Benjamin P. Trachtenberg', author_email='e_ben_75-python@yahoo.com', license='MIT', @@ -29,4 +29,4 @@ setup( 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', ], -) \ No newline at end of file +)
Updated setup.py to point to readthedocs
btr1975_ipaddresstools
train
07a4ce43c9d1a0e13570e9b4b4b17e0574f4f52c
diff --git a/lib/mongoid/validations/referenced.rb b/lib/mongoid/validations/referenced.rb index <HASH>..<HASH> 100644 --- a/lib/mongoid/validations/referenced.rb +++ b/lib/mongoid/validations/referenced.rb @@ -38,7 +38,7 @@ module Mongoid #:nodoc: def validate_each(document, attribute, value) document.validated = true valid = - if !value || !value.loaded + if !value || !value.target true else Array.wrap(value).collect do |doc|
want to check if target is there or not directly, to catch not yet persisted things
mongodb_mongoid
train
31f85c8faa5c2fcff761950cee99db5c1358b576
diff --git a/python_modules/dagit/dagit/pipeline_execution_manager.py b/python_modules/dagit/dagit/pipeline_execution_manager.py index <HASH>..<HASH> 100644 --- a/python_modules/dagit/dagit/pipeline_execution_manager.py +++ b/python_modules/dagit/dagit/pipeline_execution_manager.py @@ -1,4 +1,5 @@ from __future__ import absolute_import +import copy from collections import namedtuple import multiprocessing import time @@ -118,7 +119,7 @@ class MultiprocessingExecutionManager(PipelineExecutionManager): def _poll(self): with self._processes_lock: - processes = self._processes + processes = copy.copy(self._processes) self._processes = [] for process in processes: @@ -163,7 +164,9 @@ class MultiprocessingExecutionManager(PipelineExecutionManager): def join(self): '''Joins on all processes synchronously.''' - for process in self._processes: + with self._processes_lock: + processes = copy.copy(self._processes) + for process in processes: while process.process.is_alive(): process.process.join(0.1) gevent.sleep(0.1)
Fix potential flakiness (#<I>) By making the process collection more thread-safe.
dagster-io_dagster
train
ec2fb9fee40bb90e650a552843d7220006df85fa
diff --git a/source/Core/Database/Doctrine.php b/source/Core/Database/Doctrine.php index <HASH>..<HASH> 100644 --- a/source/Core/Database/Doctrine.php +++ b/source/Core/Database/Doctrine.php @@ -64,9 +64,7 @@ class Doctrine extends oxLegacyDb */ protected function createConnection() { - $connection = DriverManager::getConnection($this->getConnectionParameters()); - - return $connection; + return DriverManager::getConnection($this->getConnectionParameters()); } /**
ESDEV-<I> Remove unnecessary local variable. (cherry picked from commit <I>bbcf7)
OXID-eSales_oxideshop_ce
train
b183dd5c77a5acc0f90fea750eef7d3d8757b3c6
diff --git a/pyscada/hmi/static/pyscada/js/admin/display_inline_protocols_variable.js b/pyscada/hmi/static/pyscada/js/admin/display_inline_protocols_variable.js index <HASH>..<HASH> 100644 --- a/pyscada/hmi/static/pyscada/js/admin/display_inline_protocols_variable.js +++ b/pyscada/hmi/static/pyscada/js/admin/display_inline_protocols_variable.js @@ -5,7 +5,7 @@ django.jQuery( $("[id^='" + v + "'].js-inline-admin-formset.inline-group").show(); $("#id_device").on('change', function() { value = $("#id_device :selected").text().split("-")[0] - $("[id^='" + value + "variable'].js-inline-admin-formset.inline-group").show(); + $("[id^='" + value + "'].js-inline-admin-formset.inline-group").show(); $(".js-inline-admin-formset.inline-group").not("[id^='" + value + "']").hide(); }) }
Fix for variable model name Fix for variable model name not like model + variable but model + ...
trombastic_PyScada
train
2f9d70ded4e434102138265a15a04bfffe6015e1
diff --git a/appinst/platforms/win32.py b/appinst/platforms/win32.py index <HASH>..<HASH> 100644 --- a/appinst/platforms/win32.py +++ b/appinst/platforms/win32.py @@ -35,6 +35,8 @@ class Win32(object): Install application menus. """ + self._unistall = unistall + # Defaults when no enicab custom_tools is present self.props = {'ADDTODESKTOP':'1', 'ADDTOLAUNCHER':'1'} if HAS_CUSTOM: @@ -47,8 +49,8 @@ class Win32(object): if uninstall: self._uninstall_application_menus(menus, shortcuts, start_menu) - else: - self._install_application_menus(menus, shortcuts, start_menu) + + self._install_application_menus(menus, shortcuts, start_menu) def uninstall_application_menus(self, menus, shortcuts, mode): @@ -152,24 +154,27 @@ class Win32(object): else: shortcut_args = [] - wininst.create_shortcut( # Menu link - cmd, comment, - join(self.category_map[mapped_category], link), - cmd_args, *shortcut_args) + dst_dirs = [self.category_map[mapped_category]] # Menu link if shortcut.get('desktop', None) and \ - self.props['ADDTODESKTOP'] == '1': # Desktop link - wininst.create_shortcut( - cmd, comment, - join(self.desktop_dir, link), - cmd_args, *shortcut_args) + self.props['ADDTODESKTOP'] == '1': # Desktop link + dst_dirs.append(self.desktop_dir) if shortcut.get('quicklaunch', None) and \ - self.props['ADDTOLAUNCHER'] == '1': # Quicklaunch link - wininst.create_shortcut( - cmd, comment, - join(self.quicklaunch_dir, link), - cmd_args, *shortcut_args) + self.props['ADDTOLAUNCHER'] == '1': # Quicklaunch link + dst_dirs.append(self.quicklaunch_dir) + + for dst_dir in dst_dirs: + dst = join(dst_dir, link) + if self.uninstall: + try: + os.unlink(dst) + print "Removed: %r" % dst + except: + print "Could not remove: %r" % dst + else: + wininst.create_shortcut( + cmd, comment, dst, cmd_args, *shortcut_args) def _uninstall_application_menus(self, menus, shortcuts, start_menu):
adding removing of desktop and quicklaunch items
ContinuumIO_menuinst
train
f632f3a5b354c03a1f9fe4b805c349f871ba47cd
diff --git a/dbt/config.py b/dbt/config.py index <HASH>..<HASH> 100644 --- a/dbt/config.py +++ b/dbt/config.py @@ -1,21 +1,33 @@ import os.path import yaml +import yaml.scanner -import dbt.project as project +import dbt.exceptions +from dbt.logger import GLOBAL_LOGGER as logger -def read_config(profiles_dir): + +def read_profile(profiles_dir): # TODO: validate profiles_dir path = os.path.join(profiles_dir, 'profiles.yml') if os.path.isfile(path): - with open(path, 'r') as f: - profile = yaml.safe_load(f) - return profile.get('config', {}) + try: + with open(path, 'r') as f: + return yaml.safe_load(f) + except (yaml.scanner.ScannerError, + yaml.YAMLError) as e: + raise dbt.exceptions.ValidationException( + ' Could not read {}\n\n{}'.format(path, str(e))) return {} +def read_config(profiles_dir): + profile = read_profile(profiles_dir) + return profile.get('config') + + def send_anonymous_usage_stats(profiles_dir): config = read_config(profiles_dir) diff --git a/dbt/main.py b/dbt/main.py index <HASH>..<HASH> 100644 --- a/dbt/main.py +++ b/dbt/main.py @@ -141,6 +141,7 @@ def invoke_dbt(parsed): logger.info("Valid profiles:") all_profiles = project.read_profiles(parsed.profiles_dir).keys() + for profile in all_profiles: logger.info(" - {}".format(profile)) @@ -172,7 +173,8 @@ def invoke_dbt(parsed): logger.info(" ERROR Specified target {} is not a valid option " "for profile {}" .format(parsed.target, proj.profile_to_load)) - logger.info("Valid targets are: {}".format(targets)) + logger.info("Valid targets are: {}".format( + ', '.join(targets))) dbt.tracking.track_invalid_invocation( project=proj, args=parsed, diff --git a/dbt/project.py b/dbt/project.py index <HASH>..<HASH> 100644 --- a/dbt/project.py +++ b/dbt/project.py @@ -174,19 +174,10 @@ def read_profiles(profiles_dir=None): if profiles_dir is None: profiles_dir = default_profiles_dir - profiles = {} - paths = [ - os.path.join(profiles_dir, 'profiles.yml') - ] - for path in paths: - if os.path.isfile(path): - with open(path, 'r') as f: - m = yaml.safe_load(f) - valid_profiles = {k: v for (k, v) in m.items() - if k != 'config'} - profiles.update(valid_profiles) - - return profiles + raw_profiles = dbt.config.read_profile(profiles_dir) + + return {k: v for (k, v) in raw_profiles.items() + if k != 'config'} def read_project(filename, profiles_dir=None, validate=True,
handle yaml errors (#<I>)
fishtown-analytics_dbt
train
2461e9048b71d3be5764bb795f8c18067f6703ac
diff --git a/library/CM/Model/Stream/Publish.php b/library/CM/Model/Stream/Publish.php index <HASH>..<HASH> 100644 --- a/library/CM/Model/Stream/Publish.php +++ b/library/CM/Model/Stream/Publish.php @@ -23,14 +23,14 @@ class CM_Model_Stream_Publish extends CM_Model_Stream_Abstract { return CM_Db_Db::select('cm_stream_publish', '*', array('id' => $this->getId()))->fetch(); } - protected function _onDeleteBefore() { - $this->getStreamChannel()->onUnpublish($this); - } - protected function _onDelete() { CM_Db_Db::delete('cm_stream_publish', array('id' => $this->getId())); } + protected function _onDeleteAfter() { + $this->getStreamChannel()->onUnpublish($this); + } + /** * @param string $key * @param CM_Model_StreamChannel_Abstract $channel diff --git a/tests/library/CM/Model/Stream/PublishTest.php b/tests/library/CM/Model/Stream/PublishTest.php index <HASH>..<HASH> 100644 --- a/tests/library/CM/Model/Stream/PublishTest.php +++ b/tests/library/CM/Model/Stream/PublishTest.php @@ -158,10 +158,8 @@ class CM_Model_Stream_PublishTest extends CMTest_TestCase { /** @var CM_Model_StreamChannel_Media $streamChannel */ /** @var CM_Model_Stream_Publish $streamPublish */ - $onDeleteBefore = CMTest_TH::getProtectedMethod('CM_Model_Stream_Publish', '_onDeleteBefore'); + $onDeleteBefore = CMTest_TH::getProtectedMethod('CM_Model_Stream_Publish', '_onDeleteAfter'); $onDeleteBefore->invoke($streamPublish); - $onDelete = CMTest_TH::getProtectedMethod('CM_Model_Stream_Publish', '_onDelete'); - $onDelete->invoke($streamPublish); } public function testDeleteOnUnpublishInvalid() {
move onUnpublish() call to onDeleteAfter()
cargomedia_cm
train
75d9cf5b2c05786c5409c6761bf42e6e9e425179
diff --git a/src/sap.m/src/sap/m/Dialog.js b/src/sap.m/src/sap/m/Dialog.js index <HASH>..<HASH> 100644 --- a/src/sap.m/src/sap/m/Dialog.js +++ b/src/sap.m/src/sap/m/Dialog.js @@ -519,10 +519,6 @@ function( //restore the focus after rendering when dialog is already open this._setInitialFocus(); } - - if (this.getType() === DialogType.Message) { - this.$("footer").removeClass("sapContrast sapContrastPlus"); - } }; Dialog.prototype.exit = function () { @@ -1443,6 +1439,13 @@ function( Dialog.prototype._getToolbar = function () { if (!this._oToolbar) { this._oToolbar = new AssociativeOverflowToolbar(this.getId() + "-footer").addStyleClass("sapMTBNoBorders"); + this._oToolbar.addDelegate({ + onAfterRendering: function () { + if (this.getType() === DialogType.Message) { + this.$("footer").removeClass("sapContrast sapContrastPlus"); + } + } + }, false, this); this.setAggregation("_toolbar", this._oToolbar); } diff --git a/src/sap.m/test/sap/m/qunit/Dialog.qunit.js b/src/sap.m/test/sap/m/qunit/Dialog.qunit.js index <HASH>..<HASH> 100755 --- a/src/sap.m/test/sap/m/qunit/Dialog.qunit.js +++ b/src/sap.m/test/sap/m/qunit/Dialog.qunit.js @@ -419,6 +419,31 @@ sap.ui.define([ oDialog.destroy(); }); + QUnit.module("Message dialog"); + + QUnit.test("Footer rendering", function (assert) { + + var oDialog = new Dialog({ + type: DialogType.Message, + buttons: [ + new Button({ text: "Cancel"}) + ] + }); + + oDialog.open(); + this.clock.tick(500); + + oDialog._oToolbar.rerender(); + this.clock.tick(500); + + var $toolbar = oDialog._oToolbar.$(); + var bContrastApplied = $toolbar.hasClass("sapContrast") || $toolbar.hasClass("sapContrastPlus"); + + assert.notOk(bContrastApplied, "Should NOT have contrast classes applied on footer for message dialog."); + + oDialog.destroy(); + }); + QUnit.module("set properties"); QUnit.test("Set vertical/horizontal scrolling to false", function (assert) {
[INTERNAL][FIX] sap.m.Dialog: Footer rendering fixed Issue: When the footer toolbar is rerendered without triggering dialog rendering and the dialog is of type "Message" the sapContrast and sapContrastPlus classes were not getting removed. BCP: <I> Change-Id: I3e<I>e<I>f8c5de<I>b<I>ba<I>a6a5f6fa<I>d
SAP_openui5
train
e4cced12a78d183789e2cc83faeaf356a170f8a0
diff --git a/holoviews/plotting/bokeh/util.py b/holoviews/plotting/bokeh/util.py index <HASH>..<HASH> 100644 --- a/holoviews/plotting/bokeh/util.py +++ b/holoviews/plotting/bokeh/util.py @@ -53,7 +53,8 @@ def convert_timestamp(timestamp): """ Converts bokehJS timestamp to datetime64. """ - return np.datetime64(dt.datetime.fromtimestamp(timestamp/1000.)) + datetime = dt.datetime.fromtimestamp(timestamp, dt.timezone.utc) + return np.datetime64(datetime.replace(tzinfo=None)) def rgba_tuple(rgba):
Apply utc offset to bokeh callback datetimes (#<I>)
pyviz_holoviews
train
94510db26584f43d829045042cae978d3df9d732
diff --git a/Command/FixturesLoadCommand.php b/Command/FixturesLoadCommand.php index <HASH>..<HASH> 100644 --- a/Command/FixturesLoadCommand.php +++ b/Command/FixturesLoadCommand.php @@ -14,12 +14,16 @@ class FixturesLoadCommand extends ContainerAwareCommand { ->setName('khepin:yamlfixtures:load') ->setDescription('Loads all fixtures in a given context') ->addArgument('context', InputArgument::OPTIONAL, 'Specify a context from which to load additional fixtures') + ->addOption('nopurge', null, InputOption::VALUE_NONE, 'If set, will purge the database before importing new fixtures') ; } protected function execute(InputInterface $input, OutputInterface $output) { $context = $input->getArgument('context'); + if (!$input->getOption('nopurge')) { + $this->getContainer()->get('khepin.yaml_loader')->purgeDatabase(); + } $this->getContainer()->get('khepin.yaml_loader')->loadFixtures($context); diff --git a/Loader/YamlLoader.php b/Loader/YamlLoader.php index <HASH>..<HASH> 100644 --- a/Loader/YamlLoader.php +++ b/Loader/YamlLoader.php @@ -4,6 +4,8 @@ namespace Khepin\YamlFixturesBundle\Loader; use Symfony\Component\Yaml\Yaml; use Doctrine\Common\Util\Inflector; +use Doctrine\Common\DataFixtures\Purger\ORMPurger; +use Doctrine\Common\DataFixtures\Executor\ORMExecutor; class YamlLoader { @@ -100,5 +102,11 @@ class YamlLoader { // Flush the complete object graph to the database $this->object_manager->flush(); } + + public function purgeDatabase(){ + $purger = new ORMPurger($this->object_manager); + $executor = new ORMExecutor($this->object_manager, $purger); + $executor->purge(); + } } \ No newline at end of file
add possibility to purge the database. Add option --nopurge on command line to avoid purging data
khepin_KhepinYamlFixturesBundle
train
d7d1a4175362205675b27d3d6265e94a066e874b
diff --git a/raiden/constants.py b/raiden/constants.py index <HASH>..<HASH> 100644 --- a/raiden/constants.py +++ b/raiden/constants.py @@ -213,7 +213,7 @@ ETH_GET_LOGS_THRESHOLD_FAST = ETH_GET_LOGS_TIMEOUT // 4 ETH_GET_LOGS_THRESHOLD_SLOW = ETH_GET_LOGS_TIMEOUT // 2 # Keep in sync with .circleci/config.yaml -HIGHEST_SUPPORTED_GETH_VERSION = "1.9.21" +HIGHEST_SUPPORTED_GETH_VERSION = "1.10.3" LOWEST_SUPPORTED_GETH_VERSION = "1.9.7" # this is the last stable version as of this comment HIGHEST_SUPPORTED_PARITY_VERSION = "3.1.0"
Update highest supported geth version to <I>
raiden-network_raiden
train
8706908bed44e627303bfcca87a48a2e011335e6
diff --git a/lib/chef/knife/node_run_list_set.rb b/lib/chef/knife/node_run_list_set.rb index <HASH>..<HASH> 100644 --- a/lib/chef/knife/node_run_list_set.rb +++ b/lib/chef/knife/node_run_list_set.rb @@ -31,7 +31,11 @@ class Chef def run node = Chef::Node.load(@name_args[0]) - if @name_args.size > 2 + if @name_args.size < 2 + ui.fatal "You must supply both a node name and a run list." + show_usage + exit 1 + elsif @name_args.size > 2 # Check for nested lists and create a single plain one entries = @name_args[1..-1].map do |entry| entry.split(',').map { |e| e.strip } diff --git a/spec/unit/knife/node_run_list_set_spec.rb b/spec/unit/knife/node_run_list_set_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/knife/node_run_list_set_spec.rb +++ b/spec/unit/knife/node_run_list_set_spec.rb @@ -111,5 +111,30 @@ describe Chef::Knife::NodeRunListSet do end end + describe "with no role or recipe" do + # Set up outputs for inspection later + before(:each) do + @stdout = StringIO.new + @stderr = StringIO.new + + @knife.ui.stub!(:stdout).and_return(@stdout) + @knife.ui.stub!(:stderr).and_return(@stderr) + end + + it "should exit" do + @knife.name_args = [ "adam" ] + lambda { @knife.run }.should raise_error SystemExit + end + + it "should show the user" do + @knife.name_args = [ "adam" ] + + begin ; @knife.run ; rescue SystemExit ; end + + @stdout.string.should eq "USAGE: knife node run_list set NODE ENTRIES (options)\n" + @stderr.string.should eq "FATAL: You must supply both a node name and a run list.\n" + end + end + end end
Adds another test for correct amount of arguments @fnichol and I paired on this and come to this method. We split the tests into two cases for test readability.
chef_chef
train
f3474c00cd6d9e5fd61b6ef1562003e9986ad67d
diff --git a/src/event.js b/src/event.js index <HASH>..<HASH> 100644 --- a/src/event.js +++ b/src/event.js @@ -776,11 +776,10 @@ jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," + }); // Prevent memory leaks in IE -// And prevent errors on refresh with events like mouseover in other browsers // Window isn't included so as not to unbind existing unload events // More info: // - http://isaacschlueter.com/2006/10/msie-memory-leaks/ -// - https://bugzilla.mozilla.org/show_bug.cgi?id=252542 +/*@cc_on jQuery( window ).bind( 'unload', function() { for ( var id in jQuery.cache ) { // Skip the window @@ -789,3 +788,4 @@ jQuery( window ).bind( 'unload', function() { } } }); +@*/
fix for #<I>, event memory leak limited to IE only via conditional compilation
jquery_jquery
train
5d84eaae0e00c8a7d15f908d071499273f9232f8
diff --git a/bitex/interfaces/rocktrading.py b/bitex/interfaces/rocktrading.py index <HASH>..<HASH> 100644 --- a/bitex/interfaces/rocktrading.py +++ b/bitex/interfaces/rocktrading.py @@ -49,7 +49,8 @@ class RockTradingLtd(RockTradingREST): def _place_order(self, side, pair, price, size, **kwargs): q = {'fund_id': pair, 'side': side, 'amount': size, 'price': price} q.update(kwargs) - return self.private_query('funds/%s/orders' % pair, method='POST', params=q) + return self.private_query('funds/%s/orders' % pair, method='POST', + params=q) @return_json(None) def bid(self, pair, price, size, **kwargs): @@ -66,15 +67,23 @@ class RockTradingLtd(RockTradingREST): @return_json(None) def order(self, order_id, **kwargs): - raise NotImplementedError() + try: + fund_id = kwargs.pop('fund_id') + except KeyError: + raise + + return self.private_query('funds/%s/orders/%s' % (fund_id, order_id), + params=kwargs) @return_json(None) def balance(self, **kwargs): return self.private_query('balances', params=kwargs) @return_json(None) - def withdraw(self, _type, source_wallet, amount, tar_addr, **kwargs): - raise NotImplementedError() + def withdraw(self, amount, tar_addr, **kwargs): + q = {'destination_address': tar_addr, 'amount': amount} + q.update(kwargs) + return self.private_query('atms/withdraw', params=q) @return_json(None) def deposit_address(self, **kwargs):
added further support for bitex standardized methods for rocktrading interface
Crypto-toolbox_bitex
train
4b4fd7678c2518c945a9fcce9cd857cfdd4ccfad
diff --git a/EventListener/CartSubscriber.php b/EventListener/CartSubscriber.php index <HASH>..<HASH> 100755 --- a/EventListener/CartSubscriber.php +++ b/EventListener/CartSubscriber.php @@ -15,7 +15,7 @@ use Symfony\Component\HttpKernel\Event\FilterControllerEvent; use Symfony\Component\HttpKernel\KernelEvents; use WellCommerce\Bundle\CartBundle\Manager\Front\CartManagerInterface; use WellCommerce\Bundle\CartBundle\Visitor\CartVisitorTraverserInterface; -use WellCommerce\Bundle\CoreBundle\Event\ResourceEvent; +use WellCommerce\Bundle\DoctrineBundle\Event\ResourceEvent; use WellCommerce\Bundle\CoreBundle\EventListener\AbstractEventSubscriber; /**
DistributionBundle (cherry picked from commit <I>a<I>c<I>bb<I>cbc<I>c3e5c<I>a<I>c<I>)
WellCommerce_CouponBundle
train
ff3473c05dac06366a7064e7f3d2586fabfb0851
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index <HASH>..<HASH> 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -894,7 +894,7 @@ Bug Fixes - Bug in clearing the cache on ``DataFrame.pop`` and a subsequent inplace op (:issue:`10912`) - Bug in indexing with a mixed-integer ``Index`` causing an ``ImportError`` (:issue:`10610`) - Bug in ``Series.count`` when index has nulls (:issue:`10946`) - +- Bug in pickling of a non-regular freq ``DatetimeIndex`` (:issue:`11002`) - Bug causing ``DataFrame.where`` to not respect the ``axis`` parameter when the frame has a symmetric shape. (:issue:`9736`) - Bug in ``Table.select_column`` where name is not preserved (:issue:`10392`) diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index <HASH>..<HASH> 100644 --- a/pandas/tseries/index.py +++ b/pandas/tseries/index.py @@ -120,7 +120,8 @@ def _new_DatetimeIndex(cls, d): # data are already in UTC # so need to localize tz = d.pop('tz',None) - result = cls.__new__(cls, **d) + + result = cls.__new__(cls, verify_integrity=False, **d) if tz is not None: result = result.tz_localize('UTC').tz_convert(tz) return result diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index <HASH>..<HASH> 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -2142,8 +2142,8 @@ class TestTimeSeries(tm.TestCase): def test_pickle(self): - #GH4606 + # GH4606 p = self.round_trip_pickle(NaT) self.assertTrue(p is NaT) @@ -2153,6 +2153,11 @@ class TestTimeSeries(tm.TestCase): self.assertTrue(idx_p[1] is NaT) self.assertTrue(idx_p[2] == idx[2]) + # GH11002 + # don't infer freq + idx = date_range('1750-1-1', '2050-1-1', freq='7D') + idx_p = self.round_trip_pickle(idx) + tm.assert_index_equal(idx, idx_p) def _simple_ts(start, end, freq='D'): rng = date_range(start, end, freq=freq)
BUG: Bug in pickling of a non-regular freq DatetimeIndex #<I>
pandas-dev_pandas
train
c6402aa615f0f1070c7a1bbe85d0e721ed8ae9c0
diff --git a/whither/bridge.py b/whither/bridge.py index <HASH>..<HASH> 100644 --- a/whither/bridge.py +++ b/whither/bridge.py @@ -29,4 +29,7 @@ """ Python <=> JavaScript Bridge Object """ # This Library -from .toolkits.bootstrap import BridgeObject, prop +from .toolkits.bootstrap import ( + BridgeObject, + bridge, +) diff --git a/whither/toolkits/bootstrap.py b/whither/toolkits/bootstrap.py index <HASH>..<HASH> 100644 --- a/whither/toolkits/bootstrap.py +++ b/whither/toolkits/bootstrap.py @@ -33,7 +33,7 @@ try: from .qt.application import QtApplication as Application from .qt.web_container import QtWebContainer as WebContainer from .qt.bridge import BridgeObject - from .qt.bridge import pyqtProperty as prop + from .qt.bridge import Bridge as bridge except ImportError: from .gtk.window import GtkWindow as Window from .gtk.application import GtkApplication as Application diff --git a/whither/toolkits/qt/bridge.py b/whither/toolkits/qt/bridge.py index <HASH>..<HASH> 100644 --- a/whither/toolkits/qt/bridge.py +++ b/whither/toolkits/qt/bridge.py @@ -46,6 +46,20 @@ BuiltIns = Union[str, int, tuple, list, set, dict] SignalDefinition = Tuple[str, Tuple[Type[BuiltIns]]] +class Bridge: + @staticmethod + def method(*args, **kwargs): + return pyqtSlot(*args, **kwargs) + + @staticmethod + def prop(*args, **kwargs): + return pyqtProperty(*args, **kwargs) + + @staticmethod + def signal(*args, **kwargs): + return pyqtSignal(*args, **kwargs) + + class QtSignalHelper(pyqtWrapperType): """ This is a metaclass that makes it possible to define Qt signals dynamically """
add a new class to abstract qt signal/slot functions/decorators
Antergos_whither
train
eb8c7e2176f1baa68bf22a267838fe30849fea86
diff --git a/luaparser/LuaAstBuilder.py b/luaparser/LuaAstBuilder.py index <HASH>..<HASH> 100644 --- a/luaparser/LuaAstBuilder.py +++ b/luaparser/LuaAstBuilder.py @@ -145,10 +145,10 @@ class ParseTreeVisitor(LuaVisitor): return self.visit(ctx.children[1]).body def visitLabel(self, ctx): - return LabelStat(self.visitChildren(ctx)) + return LabelStat(id=self.visit(ctx.children[1]).id) def visitGoto(self, ctx): - return GotoStat(self.visitChildren(ctx)) + return GotoStat(label=self.visit(ctx.children[1]).id) def visitBreakStat(self, ctx): return BreakStat(self.visitChildren(ctx)) diff --git a/luaparser/astNodes.py b/luaparser/astNodes.py index <HASH>..<HASH> 100644 --- a/luaparser/astNodes.py +++ b/luaparser/astNodes.py @@ -135,13 +135,22 @@ class IfStat(Statement): class LabelStat(Statement): """Define the '::label::' lua statement""" - def __init__(self, childs): - super(LabelStat, self).__init__('Label', childs) + def __init__(self, id): + super(LabelStat, self).__init__('Label', []) + self.id = id + def __eq__(self, other): + return isinstance(self, other.__class__) and \ + (self.id == other.id) class GotoStat(Statement): """Define the 'goto' lua statement""" - def __init__(self, childs): - super(GotoStat, self).__init__('Goto', childs) + def __init__(self, label): + super(GotoStat, self).__init__('Goto', []) + self.label = label + def __eq__(self, other): + if isinstance(self, other.__class__): + return self.label == other.label + return False class BreakStat(Statement): """Define the 'break' lua statement""" diff --git a/luaparser/tests/test_control_structures.py b/luaparser/tests/test_control_structures.py index <HASH>..<HASH> 100644 --- a/luaparser/tests/test_control_structures.py +++ b/luaparser/tests/test_control_structures.py @@ -155,19 +155,7 @@ class ControlStructureTestCase(tests.TestCase): ::foo:: """)) exp = Chunk(body=Block(body=[ - IfStat( - test=TrueExpr(), - body=[], - orelse=IfStat( - test=FalseExpr(), - body=[], - orelse=IfStat( - test=NumberExpr(42), - body=[], - orelse=[] - ) - ) - ) + GotoStat(label='foo'), + LabelStat(id='foo') ])) - Printer.pprint(ast, Printer.Style.PYTHON, True) self.assertEqual(exp, ast)
ast: refactor label, goto statements.
boolangery_py-lua-parser
train
9380b13497ca4ac1f87c8c4e65c9ae1e838c702a
diff --git a/packages/ember-states/lib/state_manager.js b/packages/ember-states/lib/state_manager.js index <HASH>..<HASH> 100644 --- a/packages/ember-states/lib/state_manager.js +++ b/packages/ember-states/lib/state_manager.js @@ -280,7 +280,7 @@ var sendEvent = function(eventName, sendRecursiveArguments, isUnhandledPass) { ## The Initial State - When created a StateManager instance will immediately enter into the state + When created, a StateManager instance will immediately enter into the state defined as its `start` property or the state referenced by name in its `initialState` property:
Update docs/StateManager, improve grammar
emberjs_ember.js
train
e64ae780c60e4c97fe57d72e576362c1d1c26b65
diff --git a/urlrewrite/rewriterapp.py b/urlrewrite/rewriterapp.py index <HASH>..<HASH> 100644 --- a/urlrewrite/rewriterapp.py +++ b/urlrewrite/rewriterapp.py @@ -1,6 +1,6 @@ import requests -from pywb.rewrite.rewrite_content import RewriteContent +from pywb.rewrite.rewrite_content import RewriteContentAMF from pywb.rewrite.wburl import WbUrl from pywb.rewrite.url_rewriter import UrlRewriter @@ -42,7 +42,7 @@ class RewriterApp(object): frame_type = 'inverse' if framed_replay else False - self.content_rewriter = RewriteContent(is_framed_replay=frame_type) + self.content_rewriter = RewriteContentAMF(is_framed_replay=frame_type) if not jinja_env: jinja_env = JinjaEnv(globals={'static_path': 'static/__pywb'}) @@ -101,6 +101,8 @@ class RewriterApp(object): inputreq = RewriteInputRequest(environ, urlkey, url, self.content_rewriter) + inputreq.include_post_query(url) + mod_url = None use_206 = False rangeres = None @@ -203,7 +205,8 @@ class RewriterApp(object): head_insert_func, urlkey, cdx, - cookie_rewriter) + cookie_rewriter, + environ) status_headers, gen, is_rw = result diff --git a/webagg/inputrequest.py b/webagg/inputrequest.py index <HASH>..<HASH> 100644 --- a/webagg/inputrequest.py +++ b/webagg/inputrequest.py @@ -68,14 +68,15 @@ class DirectWSGIInputRequest(object): return url mime = self._get_content_type() - mime = mime.split(';')[0] if mime else '' + #mime = mime.split(';')[0] if mime else '' length = self._get_content_length() stream = self.env['wsgi.input'] buffered_stream = BytesIO() post_query = extract_post_query('POST', mime, length, stream, - buffered_stream=buffered_stream) + buffered_stream=buffered_stream, + environ=self.env) if post_query: self.env['wsgi.input'] = buffered_stream
urlrewrite: improve POST request support for ikreymer/pywb#<I>
webrecorder_pywb
train
d510bc97c2af8838dd0cc8ffa6f8dec64071aaf6
diff --git a/lib/produce/developer_center.rb b/lib/produce/developer_center.rb index <HASH>..<HASH> 100644 --- a/lib/produce/developer_center.rb +++ b/lib/produce/developer_center.rb @@ -4,6 +4,7 @@ require 'openssl' require 'capybara' require 'capybara/poltergeist' +require 'phantomjs/poltergeist' module Produce class DeveloperCenter diff --git a/lib/produce/itunes_connect.rb b/lib/produce/itunes_connect.rb index <HASH>..<HASH> 100644 --- a/lib/produce/itunes_connect.rb +++ b/lib/produce/itunes_connect.rb @@ -1,6 +1,7 @@ require 'capybara' require 'capybara/poltergeist' require 'credentials_manager/password_manager' +require 'phantomjs/poltergeist' module Produce # Every method you call here, might take a time
Fixed problem with produce when used in fastlane
fastlane_fastlane
train
b2dbc5e67405dcc6454a1ec112b697b589b10c4a
diff --git a/src/main/java/com/aol/cyclops2/types/Transformable.java b/src/main/java/com/aol/cyclops2/types/Transformable.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/aol/cyclops2/types/Transformable.java +++ b/src/main/java/com/aol/cyclops2/types/Transformable.java @@ -7,9 +7,9 @@ import java.util.function.Function; import com.aol.cyclops2.util.ExceptionSoftener; import cyclops.control.Trampoline; -/** +/** * An interface that represents a type that can transform a value from one type to another - * + * * @author johnmcclean * * @param <T> Data type of element(s) stored in this Transformable @@ -20,10 +20,10 @@ public interface Transformable<T> { /** * Cast all elements in a reactiveStream to a given type, possibly throwing a * {@link ClassCastException}. - * - * + * + * * // ClassCastException ReactiveSeq.of(1, "a", 2, "b", 3).cast(Integer.class) - * + * */ default <U> Transformable<U> cast(final Class<? extends U> type) { return map(type::cast); @@ -31,36 +31,36 @@ public interface Transformable<T> { /** * Transform this functor using the supplied transformation function - * + * * <pre> - * {@code - * - * + * {@code + * + * * of(1,2,3).map(i->i*2) - * + * * //[2,4,6] - * + * * } * </pre> - * + * * @param fn Transformation function * @return Transformed Transformable */ <R> Transformable<R> map(Function<? super T, ? extends R> fn); - + /** * Peek at the current value of this Transformable, without transforming it - * + * * <pre> - * {@code - * - * + * {@code + * + * * of(1,2,3).map(System.out::println) - * + * * 1 * 2 * 3 - * + * * } * </pre> * @param c Consumer that recieves each element from this Transformable @@ -79,30 +79,30 @@ public interface Transformable<T> { * {@code * ReactiveSeq.of(10,20,30,40) .trampoline(i-> fibonacci(i)) - .forEach(System.out::println); - + .forEach(System.out::println); + Trampoline<Long> fibonacci(int i){ return fibonacci(i,1,0); } Trampoline<Long> fibonacci(int n, long a, long b) { return n == 0 ? Trampoline.done(b) : Trampoline.more( ()->fibonacci(n-1, a+b, a)); - } - + } + * 55 6765 832040 102334155 - * - * + * + * * ReactiveSeq.of(10_000,200_000,3_000_000,40_000_000) .trampoline(i-> fibonacci(i)) .forEach(System.out::println); - - + + * completes successfully * } * </pre> - * + * * @param mapper TCO Transformation function * @return Transformable transformed by the supplied transformation function */ @@ -172,19 +172,17 @@ public interface Transformable<T> { */ default <R> Transformable<R> retry(final Function<? super T, ? extends R> fn, final int retries, final long delay, final TimeUnit timeUnit) { final Function<T, R> retry = t -> { - int count = retries; final long[] sleep = { timeUnit.toMillis(delay) }; Throwable exception = null; - while (count-- > 0) { - ExceptionSoftener.softenRunnable(() -> Thread.sleep(sleep[0])) - .run(); + for (int count = retries; count >=0; count--) { try { return fn.apply(t); } catch (final Throwable e) { exception = e; + ExceptionSoftener.softenRunnable(() -> Thread.sleep(sleep[0])) + .run(); + sleep[0] = sleep[0] * 2; } - - sleep[0] = sleep[0] * 2; } ExceptionSoftener.throwSoftenedException(exception); return null; diff --git a/src/main/java/cyclops/stream/ReactiveSeq.java b/src/main/java/cyclops/stream/ReactiveSeq.java index <HASH>..<HASH> 100644 --- a/src/main/java/cyclops/stream/ReactiveSeq.java +++ b/src/main/java/cyclops/stream/ReactiveSeq.java @@ -3874,23 +3874,7 @@ public interface ReactiveSeq<T> extends To<ReactiveSeq<T>>, * TimeUnit to use for delay */ default <R> ReactiveSeq<R> retry(final Function<? super T, ? extends R> fn, final int retries, final long delay, final TimeUnit timeUnit) { - final Function<T, R> retry = t -> { - final long[] sleep = { timeUnit.toMillis(delay) }; - Throwable exception = null; - for (int count = retries; count >=0; count--) { - try { - return fn.apply(t); - } catch (final Throwable e) { - exception = e; - ExceptionSoftener.softenRunnable(() -> Thread.sleep(sleep[0])) - .run(); - sleep[0] = sleep[0] * 2; - } - } - ExceptionSoftener.throwSoftenedException(exception); - return null; - }; - return map(retry); + return (ReactiveSeq) FoldableTraversable.super.retry(fn, retries, delay, timeUnit); } /**
refactored ReactiveSeq to use the retry implementation from Transformable
aol_cyclops
train
2cc0c7cc3b81161b38363e90fd84e980ba2c4761
diff --git a/src/Kernel/Messages/Music.php b/src/Kernel/Messages/Music.php index <HASH>..<HASH> 100644 --- a/src/Kernel/Messages/Music.php +++ b/src/Kernel/Messages/Music.php @@ -46,14 +46,18 @@ class Music extends Message public function toXmlArray() { - return [ + $music = [ 'Music' => [ 'Title' => $this->get('title'), 'Description' => $this->get('description'), 'MusicUrl' => $this->get('url'), 'HQMusicUrl' => $this->get('hq_url'), - 'ThumbMediaId' => $this->get('thumb_media_id'), ], ]; + if ($thumbMediaId = $this->get('thumb_media_id')) { + $music['ThumbMediaId'] = $thumbMediaId; + } + + return $music; } }
fix Music Message reply with ThumbMediaId option (#<I>) * fix Music Message reply with ThumbMediaId option * blank line before return * format check faied
overtrue_wechat
train
e7d301632613e58c85ab2e7281e83656a028b3ba
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -158,7 +158,5 @@ $app['silex_user.options'] = [ - Custom routes - Change password - Groups -- Roles -- Tests - Configuration - Security diff --git a/src/Entity/User.php b/src/Entity/User.php index <HASH>..<HASH> 100644 --- a/src/Entity/User.php +++ b/src/Entity/User.php @@ -286,7 +286,7 @@ abstract class User implements UserInterface { $roles = $this->roles; - $roles[] = 'ROLE_USER'; + $roles[] = self::ROLE_DEFAULT; return array_unique($roles); } diff --git a/src/Entity/UserInterface.php b/src/Entity/UserInterface.php index <HASH>..<HASH> 100644 --- a/src/Entity/UserInterface.php +++ b/src/Entity/UserInterface.php @@ -6,6 +6,8 @@ use Symfony\Component\Security\Core\User\AdvancedUserInterface; interface UserInterface extends AdvancedUserInterface { + const ROLE_DEFAULT = 'ROLE_USER'; + /** * Returns the user unique id. *
Added class constant ROLE_DEFAULT in UserInterface
awurth_SilexUserBundle
train
249937a0dba2749054127f4a37ade7641ecf5687
diff --git a/geomdl/exchange.py b/geomdl/exchange.py index <HASH>..<HASH> 100644 --- a/geomdl/exchange.py +++ b/geomdl/exchange.py @@ -486,10 +486,12 @@ def export_obj(surf_in, file_name, **kwargs): """ vertex_spacing = kwargs.get('vertex_spacing', 2) - if isinstance(surf_in, Multi.MultiSurface): + if isinstance(surf_in, Abstract.Surface): + _export_obj_single(surf_in, file_name=file_name, vertex_spacing=vertex_spacing) + elif isinstance(surf_in, Multi.MultiSurface): _export_obj_multi(surf_in, file_name=file_name, vertex_spacing=vertex_spacing) else: - _export_obj_single(surf_in, file_name=file_name, vertex_spacing=vertex_spacing) + raise NotImplementedError("Cannot export input surface - unknown type") def export_stl(surf_in, file_name, **kwargs): @@ -508,16 +510,18 @@ def export_stl(surf_in, file_name, **kwargs): binary = kwargs.get('binary', True) vertex_spacing = kwargs.get('vertex_spacing', 2) - if isinstance(surf_in, Multi.MultiSurface): + if isinstance(surf_in, Abstract.Surface): + if binary: + _export_stl_binary_single(surf_in, file_name=file_name, vertex_spacing=vertex_spacing) + else: + _export_stl_ascii_single(surf_in, file_name=file_name, vertex_spacing=vertex_spacing) + elif isinstance(surf_in, Multi.MultiSurface): if binary: _export_stl_binary_multi(surf_in, file_name=file_name, vertex_spacing=vertex_spacing) else: _export_stl_ascii_multi(surf_in, file_name=file_name, vertex_spacing=vertex_spacing) else: - if binary: - _export_stl_binary_single(surf_in, file_name=file_name, vertex_spacing=vertex_spacing) - else: - _export_stl_ascii_single(surf_in, file_name=file_name, vertex_spacing=vertex_spacing) + raise NotImplementedError("Cannot export input surface - unknown type") def export_off(surf_in, file_name, **kwargs): @@ -534,10 +538,12 @@ def export_off(surf_in, file_name, **kwargs): """ vertex_spacing = kwargs.get('vertex_spacing', 2) - if isinstance(surf_in, Multi.MultiSurface): + if isinstance(surf_in, Abstract.Surface): + _export_off_single(surf_in, file_name=file_name, vertex_spacing=vertex_spacing) + elif isinstance(surf_in, Multi.MultiSurface): _export_off_multi(surf_in, file_name=file_name, vertex_spacing=vertex_spacing) else: - _export_off_single(surf_in, file_name=file_name, vertex_spacing=vertex_spacing) + raise NotImplementedError("Cannot export input surface - unknown type") def import_smesh(file):
Improve type detection in surface export file types
orbingol_NURBS-Python
train
d8413fc2abf3eaffc25255e3f4abe9f8cbbab40f
diff --git a/lib/pack.js b/lib/pack.js index <HASH>..<HASH> 100644 --- a/lib/pack.js +++ b/lib/pack.js @@ -249,17 +249,6 @@ function transBabel(data) { function extractTsDefinition(data, modName, dependencies) { const comments = extractBlockCmts(data); - let imports = ''; - - if (dependencies) { - const len = dependencies.length; - each(dependencies, (val, i) => { - imports += 'import ' + val + " = require('./" + val + "');"; - - if (i !== len - 1) imports += '\n'; - }); - } - let tsDefinition = ''; each(comments, comment => { @@ -272,6 +261,19 @@ function extractTsDefinition(data, modName, dependencies) { } }); + let imports = ''; + + if (dependencies) { + const len = dependencies.length; + each(dependencies, (val, i) => { + if (!contain(tsDefinition, val)) return; + + imports += 'import ' + val + " = require('./" + val + "');"; + + if (i !== len - 1) imports += '\n'; + }); + } + if (imports) { tsDefinition = imports + '\n\n' + tsDefinition; }
chore: reduce ts definition size
liriliri_licia
train
e442d138187d2ebed1c1656f78f0b32d492f0090
diff --git a/fastlane/lib/fastlane/actions/update_app_identifier.rb b/fastlane/lib/fastlane/actions/update_app_identifier.rb index <HASH>..<HASH> 100644 --- a/fastlane/lib/fastlane/actions/update_app_identifier.rb +++ b/fastlane/lib/fastlane/actions/update_app_identifier.rb @@ -14,17 +14,18 @@ module Fastlane plist = Plist.parse_xml(info_plist_path) # Check if current app identifier product bundle identifier - if plist['CFBundleIdentifier'] == "$(#{identifier_key})" + app_id_equals_bundle_id = %W($(#{identifier_key}) ${#{identifier_key}}).include?(plist['CFBundleIdentifier']) + if app_id_equals_bundle_id # Load .xcodeproj project_path = params[:xcodeproj] project = Xcodeproj::Project.open(project_path) # Fetch the build configuration objects configs = project.objects.select { |obj| obj.isa == 'XCBuildConfiguration' && !obj.build_settings[identifier_key].nil? } - UI.user_error!("Info plist uses $(#{identifier_key}), but xcodeproj does not") unless configs.count > 0 + UI.user_error!("Info plist uses #{identifier_key}, but xcodeproj does not") if configs.empty? configs = configs.select { |obj| resolve_path(obj.build_settings[info_plist_key], params[:xcodeproj]) == info_plist_path } - UI.user_error!("Xcodeproj doesn't have configuration with info plist #{params[:plist_path]}.") unless configs.count > 0 + UI.user_error!("Xcodeproj doesn't have configuration with info plist #{params[:plist_path]}.") if configs.empty? # For each of the build configurations, set app identifier configs.each do |c| diff --git a/fastlane/spec/actions_specs/update_app_identifier_spec.rb b/fastlane/spec/actions_specs/update_app_identifier_spec.rb index <HASH>..<HASH> 100644 --- a/fastlane/spec/actions_specs/update_app_identifier_spec.rb +++ b/fastlane/spec/actions_specs/update_app_identifier_spec.rb @@ -78,6 +78,36 @@ describe Fastlane do expect(stub_settings_2['PRODUCT_BUNDLE_IDENTIFIER']).to_not(eq('com.test.plist')) end + it "updates the xcode project when product bundle identifier in use and it uses curly brackets notation" do + stub_project = 'stub project' + stub_configuration_1 = 'stub config 1' + stub_configuration_2 = 'stub config 2' + stub_object = ['object'] + stub_settings_1 = Hash['PRODUCT_BUNDLE_IDENTIFIER', 'com.something.else'] + stub_settings_1['INFOPLIST_FILE'] = plist_path + stub_settings_2 = Hash['PRODUCT_BUNDLE_IDENTIFIER', 'com.something.entirely.else'] + stub_settings_2['INFOPLIST_FILE'] = "Other-Info.plist" + + expect(Xcodeproj::Project).to receive(:open).with('/tmp/fastlane/tests/fastlane/bundle.xcodeproj').and_return(stub_project) + expect(stub_project).to receive(:objects).and_return(stub_object) + expect(stub_object).to receive(:select).and_return([stub_configuration_1, stub_configuration_2]) + expect(stub_configuration_1).to receive(:build_settings).twice.and_return(stub_settings_1) + expect(stub_configuration_2).to receive(:build_settings).and_return(stub_settings_2) + expect(stub_project).to receive(:save) + + create_plist_with_identifier("${#{identifier_key}}") + Fastlane::FastFile.new.parse("lane :test do + update_app_identifier({ + xcodeproj: '#{xcodeproj}', + plist_path: '#{plist_path}', + app_identifier: '#{app_identifier}' + }) + end").runner.execute(:test) + + expect(stub_settings_1['PRODUCT_BUNDLE_IDENTIFIER']).to eq('com.test.plist') + expect(stub_settings_2['PRODUCT_BUNDLE_IDENTIFIER']).to_not(eq('com.test.plist')) + end + it "updates the xcode project when info plist path contains $(SRCROOT)" do stub_project = 'stub project' stub_configuration_1 = 'stub config 1' @@ -179,7 +209,7 @@ describe Fastlane do app_identifier: '#{app_identifier}' }) end").runner.execute(:test) - end.to raise_error("Info plist uses $(#{identifier_key}), but xcodeproj does not") + end.to raise_error("Info plist uses #{identifier_key}, but xcodeproj does not") end end
[action] update_app_identifier fails to search for curly brace variables in Info.plist (#<I>) * [action] update_app_identifier fails to search for curly brace variables in Info.plist * Code review changes
fastlane_fastlane
train
02fb344bd2058c3f8e2e5ebb33b91e2166452bdb
diff --git a/clients/web/test/spec/collectionSpec.js b/clients/web/test/spec/collectionSpec.js index <HASH>..<HASH> 100644 --- a/clients/web/test/spec/collectionSpec.js +++ b/clients/web/test/spec/collectionSpec.js @@ -27,6 +27,34 @@ describe('Test collection actions', function () { it('create a collection', girderTest.createCollection('collName0', 'coll Desc 0', 'Private')); + it('make sure nFolder is fetch', function () { + runs(function () { + $('.g-collection-info-button').click(); + }); + + waitsFor(function () { + return $('#g-dialog-container:visible').length > 0; + }, 'collection info dialog to appear'); + + runs(function () { + for (var i = 0; i < 4; i++) { + if ($('.g-collection-info-line').eq(i).attr('property') === 'id') { + var id = $('.g-bold-part').eq(i).text() + var n = $('.g-bold-part').eq(i - 1).text() + console.log('ID ', id, ' - nFolder ', n); + } + } + }); + + runs(function () { + $('.btn-default').click(); + }); + + waitsFor(function () { + return $('#g-dialog-container:visible').length === 0; + }, 'collection info dialog to be closed'); + }); + it('go back to collections page', function () { runs(function () { $('a.g-nav-link[g-target="collections"]').click(); @@ -288,6 +316,35 @@ describe('Test collection actions', function () { return $('.g-loading-block').length === 0; }, 'for all blocks to load'); +// ------------------ DEBUG -------------------- + runs(function () { + $('.g-collection-info-button').click(); + }); + + waitsFor(function () { + return $('#g-dialog-container:visible').length > 0; + }, 'collection info dialog to appear'); + + runs(function () { + for (var i = 0; i < 4; i++) { + if ($('.g-collection-info-line').eq(i).attr('property') === 'id') { + var id = $('.g-bold-part').eq(i).text() + var n = $('.g-bold-part').eq(i - 1).text() + var size = $('.g-bold-part').eq(i - 2).text() + console.log('ID ', id, ' - nFolder ', n, ' - Size', size); + } + } + }); + + runs(function () { + $('.btn-default').click(); + }); + + waitsFor(function () { + return $('#g-dialog-container:visible').length === 0; + }, 'collection info dialog to be closed'); +// --------------------------------------------------------------- +// Issue : nFolders = 1, but the confirmation dialog doesn't show up... runs(function () { $('.g-collection-actions-button').click(); }); @@ -304,6 +361,37 @@ describe('Test collection actions', function () { return $('#g-confirm-button:visible').length > 0; }, 'delete confirmation to appear'); + waitsFor(function () { + $('#g-confirm-text').val('DELETE wrongName'); + return $('#g-confirm-text').val() === 'DELETE wrongName'; + }, 'enter the wrong message of delete confirmation'); + + runs(function () { + $('#g-confirm-button').click(); + }); + + waitsFor(function () { + return $('.g-msg-error').is(':visible'); + }, 'error message to be displayed'); + + waitsFor(function () { + $('#g-confirm-text').val(''); + return $('#g-confirm-text').val() === ''; + }, 'forget to enter the message of delete confirmation'); + + runs(function () { + $('#g-confirm-button').click(); + }); + + waitsFor(function () { + return $('.g-msg-error').is(':visible'); + }, 'error message to be displayed'); + + waitsFor(function () { + $('#g-confirm-text').val('DELETE collName0'); + return $('#g-confirm-text').val() === 'DELETE collName0'; + }, 'enter the right message of delete confirmation'); + runs(function () { $('#g-confirm-button').click(); });
Test: Adapt collection tests This commit ask to enter the confirmation text before submit. This confirmation text has to be: "DELETE nameOfCollection"
girder_girder
train
c66586c07c615de0596c4e3f535d31080aa09050
diff --git a/protos/client.proto b/protos/client.proto index <HASH>..<HASH> 100644 --- a/protos/client.proto +++ b/protos/client.proto @@ -48,8 +48,13 @@ message ClientBatchSubmitResponse { } // A request for the status of one or more batches, specified by id. +// If `wait_for_commit` is set to true, the validator will wait to respond +// until all batches are committed, or until the specified `timeout +// in seconds has elapsed. Defaults to 300. message ClientBatchStatusRequest { repeated string batch_ids = 1; + bool wait_for_commit = 2; + int32 timeout = 3; } // This is a response to a request for the status of specific batches. The diff --git a/validator/sawtooth_validator/journal/block_store.py b/validator/sawtooth_validator/journal/block_store.py index <HASH>..<HASH> 100644 --- a/validator/sawtooth_validator/journal/block_store.py +++ b/validator/sawtooth_validator/journal/block_store.py @@ -13,7 +13,8 @@ # limitations under the License. # ------------------------------------------------------------------------------ - +from time import time +from threading import Condition # pylint: disable=no-name-in-module from collections.abc import MutableMapping from sawtooth_validator.journal.block_wrapper import BlockStatus @@ -30,6 +31,7 @@ class BlockStore(MutableMapping): """ def __init__(self, block_db): self._block_store = block_db + self._commit_condition = Condition() def __setitem__(self, key, value): if key != value.identifier: @@ -111,8 +113,24 @@ class BlockStore(MutableMapping): """ return self._block_store - @staticmethod - def _build_add_block_ops(blkw): + def wait_for_batch_commits(self, batch_ids=None, timeout=None): + """Waits for a set of batch ids to be committed to the block chain, + and returns True when they have. If timeout is exceeded, returns False. + If no batch_ids are passed in, it will return True on the next commit. + """ + batch_ids = batch_ids or [] + timeout = timeout or 300 + start_time = time() + + with self._commit_condition: + while True: + if all(self.has_batch(b) for b in batch_ids): + return True + if time() - start_time > timeout: + return False + self._commit_condition.wait(timeout - (time() - start_time)) + + def _build_add_block_ops(self, blkw): """Build the batch operations to add a block to the BlockStore. :param blkw (BlockWrapper): Block to add BlockStore. @@ -121,11 +139,13 @@ class BlockStore(MutableMapping): """ out = [] blk_id = blkw.identifier - out.append((blk_id, blkw.block.SerializeToString())) - for batch in blkw.batches: - out.append((batch.header_signature, blk_id)) - for txn in batch.transactions: - out.append((txn.header_signature, blk_id)) + with self._commit_condition: + out.append((blk_id, blkw.block.SerializeToString())) + for batch in blkw.batches: + out.append((batch.header_signature, blk_id)) + for txn in batch.transactions: + out.append((txn.header_signature, blk_id)) + self._commit_condition.notify_all() return out @staticmethod diff --git a/validator/sawtooth_validator/state/client_handlers.py b/validator/sawtooth_validator/state/client_handlers.py index <HASH>..<HASH> 100644 --- a/validator/sawtooth_validator/state/client_handlers.py +++ b/validator/sawtooth_validator/state/client_handlers.py @@ -45,6 +45,11 @@ class BatchStatusRequest(Handler): if helper.has_response(): return helper.result + if helper.request.wait_for_commit: + self._block_store.wait_for_batch_commits( + batch_ids=helper.request.batch_ids, + timeout=helper.request.timeout) + statuses = {} for batch_id in helper.request.batch_ids:
Add wait_for_commit to Client Batch Status Requests Add the boolean `wait_for_commit` and integer `timeout` to `ClientBatchStatusRequests`s. If set to true, the handler will not respond until every specified batch has been committed to the block chain, or the timeout has elapsed. `timeout` will default to <I>.
hyperledger_sawtooth-core
train
d7a5229b3f47b49e83ae61a7ff4e34257c74ccd7
diff --git a/src/App/Console/MigrateCommand.php b/src/App/Console/MigrateCommand.php index <HASH>..<HASH> 100644 --- a/src/App/Console/MigrateCommand.php +++ b/src/App/Console/MigrateCommand.php @@ -31,12 +31,18 @@ class MigrateCommand extends Command 'module', InputArgument::OPTIONAL, 'Specific module to run migrations for' + ) + ->addArgument( + 'args', + InputArgument::IS_ARRAY | InputArgument::OPTIONAL, + 'Optional arguments to pass to phinx' ); } protected function execute( InputInterface $input, OutputInterface $output ) { - $result = $this->migrate( $input->getArgument( 'module' ), $output ); + $migrateArgs = implode( ' ', $input->getArgument( 'args' ) ); + $result = $this->migrate( $input->getArgument( 'module' ), $migrateArgs, $output ); return $result ? 0 : 1; } @@ -46,18 +52,23 @@ class MigrateCommand extends Command * Also, will setup database sessions if enabled * * @param string $module optional module + * @param string $migrateArgs optional arguments to pass to phinx * @param OutputInterface $output * * @return boolean success */ - private function migrate( $module = '', OutputInterface $output ) + private function migrate( $module = '', $migrateArgs, OutputInterface $output ) { $success = true; - $output->writeln( '-- Running migrations' ); + if( empty( $migrateArgs ) ) + $migrateArgs = 'migrate'; + + if( $migrateArgs == 'migrate' ) + $output->writeln( '-- Running migrations' ); // database sessions - if( $this->app[ 'config' ]->get( 'sessions.adapter' ) == 'database' ) + if( empty( $module ) && $this->app[ 'config' ]->get( 'sessions.adapter' ) == 'database' ) { $output->writeln( 'Migrating Database Sessions' ); @@ -76,13 +87,14 @@ class MigrateCommand extends Command foreach( (array)$modules as $mod ) { - $output->writeln( "-- Migrating $mod" ); + if( $migrateArgs == 'migrate' ) + $output->writeln( "-- Migrating $mod" ); $result = 1; putenv( "PHINX_APP_MODULE=$mod" ); ob_start(); - system( 'php vendor/robmorgan/phinx/bin/phinx migrate', $result ); + system( 'php vendor/robmorgan/phinx/bin/phinx ' . $migrateArgs, $result ); $phinxOutput = ob_get_contents(); ob_end_clean(); @@ -98,10 +110,13 @@ class MigrateCommand extends Command } } - if( $success ) - $output->writeln( '-- Success!' ); - else - $output->writeln( '-- Error running migrations' ); + if( $migrateArgs == 'migrate' ) + { + if( $success ) + $output->writeln( '-- Success!' ); + else + $output->writeln( '-- Error running migrations' ); + } return $success; }
added ability to pass optional arguments to phinx in console migration command
infusephp_infuse
train
bae9125fc163d62804eb7115b3dec855e273e4d0
diff --git a/agent/consul/leader_connect_test.go b/agent/consul/leader_connect_test.go index <HASH>..<HASH> 100644 --- a/agent/consul/leader_connect_test.go +++ b/agent/consul/leader_connect_test.go @@ -12,16 +12,17 @@ import ( "testing" "time" + uuid "github.com/hashicorp/go-uuid" + msgpackrpc "github.com/hashicorp/net-rpc-msgpackrpc" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/hashicorp/consul/agent/connect" "github.com/hashicorp/consul/agent/connect/ca" "github.com/hashicorp/consul/agent/structs" "github.com/hashicorp/consul/agent/token" "github.com/hashicorp/consul/sdk/testutil/retry" "github.com/hashicorp/consul/testrpc" - uuid "github.com/hashicorp/go-uuid" - msgpackrpc "github.com/hashicorp/net-rpc-msgpackrpc" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func TestLeader_SecondaryCA_Initialize(t *testing.T) { @@ -923,8 +924,7 @@ func TestLeader_CARootPruning(t *testing.T) { t.Skip("too slow for testing.Short") } - t.Parallel() - + // Can not use t.Parallel(), because this modifies a global. caRootPruneInterval = 200 * time.Millisecond require := require.New(t)
Fix one race caused by t.Parallel
hashicorp_consul
train
6ee99cbc44933ee61c9433bc5621c3295a71558a
diff --git a/src/engine/Clause.js b/src/engine/Clause.js index <HASH>..<HASH> 100644 --- a/src/engine/Clause.js +++ b/src/engine/Clause.js @@ -1,5 +1,6 @@ const Unifier = require('./Unifier'); const BooleanBinaryOperator = require('./BooleanBinaryOperator'); +const BooleanUnaryOperator = require('./BooleanUnaryOperator'); function Clause(head, body) { // array of expressions @@ -87,7 +88,8 @@ function Clause(head, body) { // perform head check for (let i = 0; i < unresolvedHeadLiterals.length; i += 1) { let literal = unresolvedHeadLiterals[i]; - if (literal instanceof BooleanBinaryOperator + if ((literal instanceof BooleanBinaryOperator + || literal instanceof BooleanUnaryOperator) && literal.isGround() && !literal.evaluate()) { // nope this doesn't work out return null;
add clause support for boolean binary operator
lps-js_lps.js
train
8783196dda2706e6019867585de8c89ff4691594
diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index <HASH>..<HASH> 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -30,7 +30,7 @@ ext { // Misc commons_lang3 : 'org.apache.commons:commons-lang3:3.4', commons_io : 'commons-io:commons-io:2.5', - jackson_databind : 'com.fasterxml.jackson.core:jackson-databind:2.6.3', + jackson_databind : 'com.fasterxml.jackson.core:jackson-databind:2.8.1', guava : 'com.google.guava:guava:19.0', dbinit : 'net.sf.dbinit:dbinit:1.4.0', h2 : 'com.h2database:h2:1.4.192', diff --git a/ontrack-json/src/test/java/net/nemerosa/ontrack/json/ConstructorPropertiesAnnotationIntrospectorTest.java b/ontrack-json/src/test/java/net/nemerosa/ontrack/json/ConstructorPropertiesAnnotationIntrospectorTest.java index <HASH>..<HASH> 100644 --- a/ontrack-json/src/test/java/net/nemerosa/ontrack/json/ConstructorPropertiesAnnotationIntrospectorTest.java +++ b/ontrack-json/src/test/java/net/nemerosa/ontrack/json/ConstructorPropertiesAnnotationIntrospectorTest.java @@ -1,6 +1,5 @@ package net.nemerosa.ontrack.json; -import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.Data; import org.junit.Test; @@ -20,13 +19,6 @@ public class ConstructorPropertiesAnnotationIntrospectorTest { private final ImmutablePojo instance = new ImmutablePojo("foobar", 42); - @Test(expected = JsonMappingException.class) - public void testJacksonUnableToDeserialize() throws IOException { - ObjectMapper mapper = new ObjectMapper(); - String json = mapper.writeValueAsString(instance); - mapper.readValue(json, ImmutablePojo.class); - } - @Test public void testJacksonAbleToDeserialize() throws IOException { ObjectMapper mapper = ObjectMapperFactory.create(); diff --git a/ontrack-ui-support/src/main/java/net/nemerosa/ontrack/ui/resource/ResourceDecoratorSerializer.java b/ontrack-ui-support/src/main/java/net/nemerosa/ontrack/ui/resource/ResourceDecoratorSerializer.java index <HASH>..<HASH> 100644 --- a/ontrack-ui-support/src/main/java/net/nemerosa/ontrack/ui/resource/ResourceDecoratorSerializer.java +++ b/ontrack-ui-support/src/main/java/net/nemerosa/ontrack/ui/resource/ResourceDecoratorSerializer.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.ser.std.BeanSerializerBase; import org.apache.commons.lang3.Validate; import java.io.IOException; +import java.util.Set; import static java.lang.String.format; @@ -27,7 +28,7 @@ public class ResourceDecoratorSerializer<T> extends BeanSerializerBase { this.resourceDecorator = resourceDecorator; } - protected ResourceDecoratorSerializer(BeanSerializerBase src, String[] toIgnore, ResourceContext resourceContext, ResourceDecorator<T> resourceDecorator) { + public ResourceDecoratorSerializer(BeanSerializerBase src, Set<String> toIgnore, ResourceContext resourceContext, ResourceDecorator<T> resourceDecorator) { super(src, toIgnore); this.resourceContext = resourceContext; this.resourceDecorator = resourceDecorator; @@ -35,7 +36,7 @@ public class ResourceDecoratorSerializer<T> extends BeanSerializerBase { @Override public BeanSerializerBase withObjectIdWriter(ObjectIdWriter objectIdWriter) { - return new ResourceDecoratorSerializer<T>( + return new ResourceDecoratorSerializer<>( this, objectIdWriter, resourceContext, @@ -44,8 +45,8 @@ public class ResourceDecoratorSerializer<T> extends BeanSerializerBase { } @Override - protected BeanSerializerBase withIgnorals(String[] toIgnore) { - return new ResourceDecoratorSerializer<T>( + protected BeanSerializerBase withIgnorals(Set<String> toIgnore) { + return new ResourceDecoratorSerializer<>( this, toIgnore, resourceContext,
<I> Upgrade of dependencies - Jackson
nemerosa_ontrack
train
77a653b24cebb4998b723c218be01c16f9dac257
diff --git a/components/amorphic/client.js b/components/amorphic/client.js index <HASH>..<HASH> 100644 --- a/components/amorphic/client.js +++ b/components/amorphic/client.js @@ -225,7 +225,7 @@ amorphic = // Needs to be global to make mocha tests work if (this.controller && typeof(this.controller.displayError) === 'function') { this.controller.displayError(output); } - } + } }.bind(this); this.setContextProps = RemoteObjectTemplate.logger.setContextProps; @@ -293,9 +293,12 @@ amorphic = // Needs to be global to make mocha tests work } else { var hasChanges = RemoteObjectTemplate.processMessage(message); - Bluebird.delay(50).then(function () { - self.refresh(hasChanges); - }); // Let the promises settle out + new Promise((resolve) => { + setTimeout(() => { + self.refresh(hasChanges); + resolve(); + }, 50); + }); } if (message.sync === false) { @@ -491,7 +494,7 @@ amorphic = // Needs to be global to make mocha tests work function isRetriableErrorStatus(status) { const errorStatuses = new Set([500, 502, 503, 504, 0]); - + return errorStatuses.has(status); }
Replace Bluebird.delay with Promise/setTimeout calls to remove BB dependency from frontend code
haven-life_amorphic
train
9ac250e16d88b2b9a9e7051e59c8248cc1762413
diff --git a/aeron-cluster/src/main/java/io/aeron/cluster/ClusterMember.java b/aeron-cluster/src/main/java/io/aeron/cluster/ClusterMember.java index <HASH>..<HASH> 100644 --- a/aeron-cluster/src/main/java/io/aeron/cluster/ClusterMember.java +++ b/aeron-cluster/src/main/java/io/aeron/cluster/ClusterMember.java @@ -410,17 +410,17 @@ public final class ClusterMember } /** - * Has the members of the cluster all reached the provided position in their log. + * Has the members of the cluster the voted reached the provided position in their log. * * @param clusterMembers to check. * @param position to compare the {@link #logPosition()} against. * @return true if all members have reached this position otherwise false. */ - public static boolean hasReachedPosition(final ClusterMember[] clusterMembers, final long position) + public static boolean haveVotersReachedPosition(final ClusterMember[] clusterMembers, final long position) { for (final ClusterMember member : clusterMembers) { - if (member.logPosition() < position) + if (member.votedForId() != NULL_MEMBER_ID && member.logPosition() < position) { return false; } diff --git a/aeron-cluster/src/main/java/io/aeron/cluster/Election.java b/aeron-cluster/src/main/java/io/aeron/cluster/Election.java index <HASH>..<HASH> 100644 --- a/aeron-cluster/src/main/java/io/aeron/cluster/Election.java +++ b/aeron-cluster/src/main/java/io/aeron/cluster/Election.java @@ -577,7 +577,7 @@ class Election implements MemberStatusListener, AutoCloseable { int workCount = 0; - if (ClusterMember.hasReachedPosition(clusterMembers, logPosition)) + if (ClusterMember.haveVotersReachedPosition(clusterMembers, logPosition)) { sequencerAgent.electionComplete(Cluster.Role.LEADER); close();
[Java] Check that voting members have indicated they have joined the log rather than all members.
real-logic_aeron
train
b87792bebc949376a767575fec0976a758d87d24
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -1,5 +1,8 @@ from setuptools import setup +with open('README.rst') as file: + long_description = file.read() + setup( name='zxcvbn-python', version='4.4.20', @@ -9,8 +12,8 @@ setup( license='MIT', author='Daniel Wolf', author_email='danielrwolf5@gmail.com', - description='Python implementation of Dropbox\'s realistic password ' - 'strength estimator, zxcvbn', + description=long_description, + long_description=long_description, keywords=['zxcvbn', 'password', 'security'], classifiers=[ 'Intended Audience :: Developers',
adding better long description for pypi
dwolfhub_zxcvbn-python
train
a6bfe43741ed3d3747e7cdbcda3babd40cb260d2
diff --git a/allel/test/model/test_chunked.py b/allel/test/model/test_chunked.py index <HASH>..<HASH> 100644 --- a/allel/test/model/test_chunked.py +++ b/allel/test/model/test_chunked.py @@ -619,6 +619,13 @@ class VariantChunkedTableTestsZarrStorage(VariantChunkedTableTests): vt = self.setup_instance(a) assert isinstance(vt.values, ZarrTable) + def test_zarr_group(self): + z = zarr.group() + z.create_dataset('chrom', data=['1', '2', '3']) + z.create_dataset('pos', data=[2, 4, 6]) + vt = VariantChunkedTable(z) + assert isinstance(vt.values, zarr.Group) + class FeatureChunkedTableTests(FeatureTableInterface, unittest.TestCase):
add test to resolve #<I>
cggh_scikit-allel
train
8e45ab6dcdca9cbb0ae2bdc5b16a0e8622287718
diff --git a/src/scripts/admin/admin.store.js b/src/scripts/admin/admin.store.js index <HASH>..<HASH> 100644 --- a/src/scripts/admin/admin.store.js +++ b/src/scripts/admin/admin.store.js @@ -277,7 +277,7 @@ let UserStore = Reflux.createStore({ if (formData.parameters) { for (let param of formData.parameters) { - parameters[param.label] = param.defaultValue; + parameters[param.label] = JSON.stringify(param); } } jobDefinition.parameters = parameters; @@ -318,7 +318,12 @@ let UserStore = Reflux.createStore({ let params = []; if(Object.keys(jobDefinition.parameters).length) { Object.keys(jobDefinition.parameters).forEach((key) => { - params.push({label: key, defaultValue: jobDefinition.parameters[key], Type: 'String'}); + // params.push({label: key, defaultValue: jobDefinition.parameters[key], Type: 'String'}); + try { + params.push(JSON.parse(jobDefinition.parameters[key])); + } catch(e) { + //error handling for this or just skip improperly formatted JSON params? + } }); }
JSON stringify paremeters for storage as part of job def
OpenNeuroOrg_openneuro
train
a1cc15b7fd00f804351b7432634f91dcfa63607d
diff --git a/aiohttp/web.py b/aiohttp/web.py index <HASH>..<HASH> 100644 --- a/aiohttp/web.py +++ b/aiohttp/web.py @@ -308,7 +308,7 @@ def run_app(app, *, host='0.0.0.0', port=None, try: loop.run_forever() - except KeyboardInterrupt: # pragma: no branch + except KeyboardInterrupt: # pragma: no cover pass finally: srv.close()
Use proper pragma for coverage warning suppressing
aio-libs_aiohttp
train
3f6d0b44b86d153121e4b96cdb181b937e77887e
diff --git a/unleash/unleash.py b/unleash/unleash.py index <HASH>..<HASH> 100644 --- a/unleash/unleash.py +++ b/unleash/unleash.py @@ -1,7 +1,5 @@ from contextlib import contextmanager from pprint import pformat -import os -import subprocess import time import click @@ -13,6 +11,7 @@ from tempdir import TempDir from .exc import InvocationError, PluginError from .git import export_tree, MalleableCommit, ResolvedRef, get_local_timezone from .issues import IssueCollector +from .util import run_user_shell log = Logger('unleash') @@ -126,7 +125,7 @@ class Unleash(object): 'the shell to abort the release process.\n\n' 'Use "exit 2" to continue the release.') - status = self.run_user_shell(cwd=inspect_dir) + status = run_user_shell(cwd=inspect_dir) if status != 2: raise InvocationError( @@ -274,9 +273,6 @@ class Unleash(object): log.debug('Exiting due to PluginError') return - def run_user_shell(self, **kwargs): - return subprocess.call(os.environ['SHELL'], env=os.environ, **kwargs) - def set_global_opts(self, root, opts=None): self.opts = opts or {} self.root = root diff --git a/unleash/util.py b/unleash/util.py index <HASH>..<HASH> 100644 --- a/unleash/util.py +++ b/unleash/util.py @@ -68,3 +68,7 @@ def checked_output(cmd, *args, **kwargs): except subprocess.CalledProcessError as e: log.error('Error calling external process.\n%s' % e.output) raise + + +def run_user_shell(self, **kwargs): + return subprocess.call(os.environ['SHELL'], env=os.environ, **kwargs)
Moved run_user_shell out of unleash class.
mbr_unleash
train