hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
66113959473829d4044df97b381e40fd633eca5b
diff --git a/js2py/evaljs.py b/js2py/evaljs.py index <HASH>..<HASH> 100644 --- a/js2py/evaljs.py +++ b/js2py/evaljs.py @@ -11,6 +11,7 @@ class EvalJs: def execute(self, js): """executes javascript js in current context""" + js = js.replace('\t', '\n') # have to remove tabs in parser if not self.__started: code = translate_js(js) self.__started = True @@ -24,40 +25,5 @@ class EvalJs: def __getitem__(self, var): return self.get_variable(var) - -e = EvalJs() -x = '''function lcs(string1, string2){ - var longestCommonSubstring = 0; - var table = [], - len1 = string1.length, - len2 = string2.length, - row, col; - for(row = 0; row <= len1; row++){ - table[row] = []; - for(col = 0; col <= len2; col++){ - table[row][col] = 0; - } - } - var i, j; - for(i = 0; i < len1; i++){ - for(j = 0; j < len2; j++){ - if(string1[i]==string2[j]){ - if(table[i][j] == 0){ - table[i+1][j+1] = 1; - } else { - table[i+1][j+1] = table[i][j] + 1; - } - if(table[i+1][j+1] > longestCommonSubstring){ - longestCommonSubstring = table[i+1][j+1]; - } - } else { - table[i+1][j+1] = 0; - } - } - } - return longestCommonSubstring; -}'''.replace('\t', '\n') - -e.execute(x) -print e['lcs']('absdsa','cccccccccccccbsjdcccc') + diff --git a/js2py/translators/translator.py b/js2py/translators/translator.py index <HASH>..<HASH> 100644 --- a/js2py/translators/translator.py +++ b/js2py/translators/translator.py @@ -41,7 +41,7 @@ def translate_js(js, top=TOP_GLOBAL): for nested_name, nested_info in hoisted.iteritems(): nested_block, nested_args = nested_info new_code = translate_func('PyJsLvalTempHoisted', nested_block, nested_args) - new_code += indent('PyJsLvalTempHoisted.func_name = %s\n' %repr(nested_name)) + new_code += 'PyJsLvalTempHoisted.func_name = %s\n' %repr(nested_name) defs += new_code +'\nvar.put(%s, PyJsLvalTempHoisted)\n' % repr(nested_name) #defs += '# Everting ready!\n' # inline functions recovery
Added evaluator finally usable. more bug fixes.
PiotrDabkowski_Js2Py
train
cc0557a82911f7bf5234cbb79060ced0a2ee736a
diff --git a/lib/bibliothecary.rb b/lib/bibliothecary.rb index <HASH>..<HASH> 100644 --- a/lib/bibliothecary.rb +++ b/lib/bibliothecary.rb @@ -13,7 +13,7 @@ module Bibliothecary file_list = [] Find.find(path) do |subpath| Find.prune if FileTest.directory?(subpath) && ignored_dirs.include?(File.basename(subpath)) - file_list.append(subpath) + file_list.push(subpath) end package_managers.map{|pm| pm.analyse(path, file_list) }.flatten.compact end diff --git a/spec/bibliothecary_spec.rb b/spec/bibliothecary_spec.rb index <HASH>..<HASH> 100644 --- a/spec/bibliothecary_spec.rb +++ b/spec/bibliothecary_spec.rb @@ -59,7 +59,7 @@ describe Bibliothecary do it 'searches a folder for manifests and parses them' do Bibliothecary.configure do |config| - config.ignored_dirs.append("fixtures") + config.ignored_dirs.push("fixtures") end analysis = described_class.analyse('./') # empty out any dependencies to make the test more reliable.
Switch to push as I guess append was not available in ruby <I>
librariesio_bibliothecary
train
498df77a2a6bf2decf0ac3a670e9e6d630b77637
diff --git a/collatex/src/main/java/eu/interedition/collatex2/experimental/DeTestDirkVincent.java b/collatex/src/main/java/eu/interedition/collatex2/experimental/DeTestDirkVincent.java index <HASH>..<HASH> 100644 --- a/collatex/src/main/java/eu/interedition/collatex2/experimental/DeTestDirkVincent.java +++ b/collatex/src/main/java/eu/interedition/collatex2/experimental/DeTestDirkVincent.java @@ -4,6 +4,7 @@ import static org.junit.Assert.assertEquals; import java.util.Iterator; import java.util.List; +import java.util.Map; import org.junit.Test; @@ -74,17 +75,16 @@ public class DeTestDirkVincent { } - //TODO: make return type map + //TODO: maybe call it linker instead of alignment? @Test public void testDirkVincent4() { CollateXEngine factory = new CollateXEngine(); IWitness a = factory.createWitness("01b", "Its soft light neither daylight nor moonlight nor starlight nor any light he could remember from the days & nights when day followed night & vice versa."); IWitness b = factory.createWitness("10a", "Its soft changeless light unlike any light he could remember from the days and nights when day followed hard on night and vice versa."); MyNewAligner aligner = new MyNewAligner(); - List<IAlignedToken> tokens = aligner.align(a, b); - IAlignedToken its = tokens.get(0); + Map<INormalizedToken, INormalizedToken> tokens = aligner.align(a, b); + INormalizedToken itsA = a.getTokens().get(0); INormalizedToken itsB = b.getTokens().get(0); - //TODO: het zou ook met een map kunnen (zonder multimap dan natuurlijk) - assertEquals(itsB, its.getAlignedToken()); + assertEquals(itsB, tokens.get(itsA)); } } diff --git a/collatex/src/main/java/eu/interedition/collatex2/experimental/MyNewAligner.java b/collatex/src/main/java/eu/interedition/collatex2/experimental/MyNewAligner.java index <HASH>..<HASH> 100644 --- a/collatex/src/main/java/eu/interedition/collatex2/experimental/MyNewAligner.java +++ b/collatex/src/main/java/eu/interedition/collatex2/experimental/MyNewAligner.java @@ -1,23 +1,22 @@ package eu.interedition.collatex2.experimental; -import java.util.List; +import java.util.Map; import com.google.common.collect.ListMultimap; -import com.google.common.collect.Lists; +import com.google.common.collect.Maps; import eu.interedition.collatex2.interfaces.INormalizedToken; import eu.interedition.collatex2.interfaces.IWitness; public class MyNewAligner { - public List<IAlignedToken> align(IWitness a, IWitness b) { - List<IAlignedToken> alignedTokens = Lists.newArrayList(); + public Map<INormalizedToken, INormalizedToken> align(IWitness a, IWitness b) { + Map<INormalizedToken, INormalizedToken> alignedTokens = Maps.newLinkedHashMap(); MyNewMatcher matcher = new MyNewMatcher(); ListMultimap<INormalizedToken, INormalizedToken> matches = matcher.match(a, b); for (INormalizedToken token: a.getTokens()) { if (matches.keys().count(token)==1) { - IAlignedToken alignedToken = new AlignedToken(token, matches.get(token).get(0)); - alignedTokens.add(alignedToken); + alignedTokens.put(token, matches.get(token).get(0)); } } return alignedTokens;
[RHD] Refactored test to use Map instead of List
interedition_collatex
train
3c12e24e8446229029e6f94f0768e9e83c9f21cf
diff --git a/devices/aurora_lighting.js b/devices/aurora_lighting.js index <HASH>..<HASH> 100644 --- a/devices/aurora_lighting.js +++ b/devices/aurora_lighting.js @@ -5,6 +5,31 @@ const reporting = require('../lib/reporting'); const extend = require('../lib/extend'); const e = exposes.presets; +const batteryRotaryDimmer = (...endpointsIds) => ({ + fromZigbee: [fz.battery, fz.command_on, fz.command_off, fz.command_step, fz.command_step_color_temperature], + toZigbee: [], + exposes: [e.battery(), e.action([ + 'on', 'off', 'brightness_step_up', 'brightness_step_down', 'color_temperature_step_up', 'color_temperature_step_down'])], + configure: async (device, coordinatorEndpoint, logger) => { + const endpoints = endpointsIds.map((endpoint) => device.getEndpoint(endpoint)); + + // Battery level is only reported on first endpoint + await reporting.batteryVoltage(endpoints[0]); + + for await (const endpoint of endpoints) { + logger.debug(`processing endpoint ${endpoint.ID}`); + await reporting.bind(endpoint, coordinatorEndpoint, + ['genIdentify', 'genOnOff', 'genLevelCtrl', 'lightingColorCtrl']); + + // The default is for the device to also report the on/off and + // brightness at the same time as sending on/off and step commands. + // Disable the reporting by setting the max interval to 0xFFFF. + await reporting.brightness(endpoint, {max: 0xFFFF}); + await reporting.onOff(endpoint, {max: 0xFFFF}); + } + }, +}); + module.exports = [ { zigbeeModel: ['TWGU10Bulb50AU'], @@ -167,38 +192,20 @@ module.exports = [ model: 'AU-A1ZBR1GW', vendor: 'Aurora Lighting', description: 'AOne one gang wireless battery rotary dimmer', - fromZigbee: [fz.battery, fz.command_on, fz.command_off, fz.command_step, fz.command_step_color_temperature], - toZigbee: [], - exposes: [e.battery(), e.action([ - 'on', 'off', 'brightness_step_up', 'brightness_step_down', 'color_temperature_step_up', 'color_temperature_step_down'])], meta: {battery: {voltageToPercentage: '3V_2100'}}, - configure: async (device, coordinatorEndpoint, logger) => { - const endpoint1 = device.getEndpoint(1); - await reporting.bind(endpoint1, coordinatorEndpoint, - ['genIdentify', 'genOnOff', 'genLevelCtrl', 'lightingColorCtrl', 'genPowerCfg']); - await reporting.batteryVoltage(endpoint1); - }, + // One gang battery rotary dimmer with endpoint ID 1 + ...batteryRotaryDimmer(1), }, { zigbeeModel: ['2GBatteryDimmer50AU'], model: 'AU-A1ZBR2GW', vendor: 'Aurora Lighting', description: 'AOne two gang wireless battery rotary dimmer', - fromZigbee: [fz.battery, fz.command_on, fz.command_off, fz.command_step, fz.command_step_color_temperature], - toZigbee: [], - exposes: [e.battery(), e.action([ - 'on', 'off', 'brightness_step_up', 'brightness_step_down', 'color_temperature_step_up', 'color_temperature_step_down'])], meta: {multiEndpoint: true, battery: {voltageToPercentage: '3V_2100'}}, endpoint: (device) => { return {'right': 1, 'left': 2}; }, - configure: async (device, coordinatorEndpoint, logger) => { - const endpoint1 = device.getEndpoint(1); - await reporting.bind(endpoint1, coordinatorEndpoint, - ['genIdentify', 'genOnOff', 'genLevelCtrl', 'lightingColorCtrl', 'genPowerCfg']); - await reporting.batteryVoltage(endpoint1); - const endpoint2 = device.getEndpoint(2); - await reporting.bind(endpoint2, coordinatorEndpoint, ['genIdentify', 'genOnOff', 'genLevelCtrl', 'lightingColorCtrl']); - }, + // Two gang battery rotary dimmer with endpoint IDs 1 and 2 + ...batteryRotaryDimmer(1, 2), }, ];
Improve Aurora Lighting AU-A1ZBR1GW and AU-A1ZBR2GW stability (#<I>)
Koenkk_zigbee-shepherd-converters
train
1dcc45468ac062ee1138a8370592539cbdbb9970
diff --git a/messaging/src/main/java/org/cloudiator/messaging/kafka/BaseKafkaConsumerFactory.java b/messaging/src/main/java/org/cloudiator/messaging/kafka/BaseKafkaConsumerFactory.java index <HASH>..<HASH> 100644 --- a/messaging/src/main/java/org/cloudiator/messaging/kafka/BaseKafkaConsumerFactory.java +++ b/messaging/src/main/java/org/cloudiator/messaging/kafka/BaseKafkaConsumerFactory.java @@ -49,8 +49,10 @@ class BaseKafkaConsumerFactory implements KafkaConsumerFactory { Properties properties = new Properties(); properties.put("bootstrap.servers", bootstrapServers); properties.put("group.id", groupId); - properties.put("enable.auto.commit", "true"); - properties.put("auto.commit.interval.ms", "1000"); + properties.put("enable.auto.commit", true); + properties.put("auto.commit.interval.ms", 1000); + properties.put("fetch.wait.max.ms", 1000); + properties.put("fetch.error.backoff.ms", 1000); return new KafkaConsumer<>(properties, new StringDeserializer(), new ProtobufDeserializer<>(parser)); } diff --git a/messaging/src/main/java/org/cloudiator/messaging/kafka/SingletonKafkaProducerFactory.java b/messaging/src/main/java/org/cloudiator/messaging/kafka/SingletonKafkaProducerFactory.java index <HASH>..<HASH> 100644 --- a/messaging/src/main/java/org/cloudiator/messaging/kafka/SingletonKafkaProducerFactory.java +++ b/messaging/src/main/java/org/cloudiator/messaging/kafka/SingletonKafkaProducerFactory.java @@ -63,6 +63,7 @@ class SingletonKafkaProducerFactory implements KafkaProducerFactory { public Producer<String, Message> createKafkaProducer() { final Properties properties = new Properties(); properties.put("bootstrap.servers", bootstrapServers); + properties.put("queue.buffering.max.ms", 500); return ProducerSingleton.getInstance(properties); }
Adapted kafka configuration
cloudiator_common
train
5ce2772e1d3c8b63965e28180dd346e2276c1dae
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -14,7 +14,7 @@ dependencies = [ setup( name='templar', - version='1.1', + version='1.2.dev1', description='A static templating engine written in Python', # long_description=long_description, url='https://github.com/albert12132/templar', diff --git a/templar/compile.py b/templar/compile.py index <HASH>..<HASH> 100644 --- a/templar/compile.py +++ b/templar/compile.py @@ -237,6 +237,7 @@ class Frame: try: return eval(variable) except: + log.warn('"{}" not found'.format(variable)) return '' def __contains__(self, variable): @@ -254,7 +255,9 @@ def evaluate(expression, attrs): else: try: return eval(expression, {}, attrs) - except: + except Exception as e: + log.warn('"{}" caused {}: {}'.format(expression, + e.__class__.__name__, e)) return ''
Add warnings when compiler can't evaluate an expression
albert12132_templar
train
16fbb8997090cc69af9490b411e3a7dee1037627
diff --git a/ips_vagrant/commands/delete/__init__.py b/ips_vagrant/commands/delete/__init__.py index <HASH>..<HASH> 100644 --- a/ips_vagrant/commands/delete/__init__.py +++ b/ips_vagrant/commands/delete/__init__.py @@ -10,10 +10,10 @@ from ips_vagrant.models.sites import Domain, Site, Session @click.command('list', short_help='Delete a single site or ALL sites under a domain.') @click.argument('dname', metavar='<domain>') @click.argument('site', default=False, metavar='<site>') -@click.option('--delete-code/--preserve-code', 'delete_code', help='Deletes HTTP files (project code) with the site ' +@click.option('--remove-code/--preserve-code', 'delete_code', help='Deletes project code (HTTP files) with the site ' 'entry. (Default: Preserve)') @click.option('--no-safety-prompt', 'no_prompt', is_flag=True, help='Skip the safety confirmation prompt(s). ' - 'USE WITH CAUTION!') + 'USE WITH CAUTION!') @pass_context def cli(ctx, dname, site, delete_code, no_prompt): """ @@ -85,6 +85,7 @@ def delete_single(site, domain, delete_code=False, no_prompt=False): Session.delete(domain) Session.commit() + click.secho('{sn} removed'.format(sn=site.name), fg='yellow', bold=True) # Restart Nginx FNULL = open(os.devnull, 'w')
--delete-code renamed to --remove-code
FujiMakoto_IPS-Vagrant
train
f8375e415ef0d7ec4cbcc55f8cc70de453e3ae88
diff --git a/languagetool-core/src/main/java/org/languagetool/rules/CommaWhitespaceRule.java b/languagetool-core/src/main/java/org/languagetool/rules/CommaWhitespaceRule.java index <HASH>..<HASH> 100644 --- a/languagetool-core/src/main/java/org/languagetool/rules/CommaWhitespaceRule.java +++ b/languagetool-core/src/main/java/org/languagetool/rules/CommaWhitespaceRule.java @@ -151,6 +151,10 @@ public class CommaWhitespaceRule extends Rule { fromPos = tokens[i - 2].getStartPos(); } int toPos = tokens[i].getEndPos(); + String marked = sentence.getText().substring(fromPos, toPos); + if (marked.equals(suggestionText) && !twoSuggestions) { + continue; + } RuleMatch ruleMatch = new RuleMatch(this, sentence, fromPos, toPos, msg); if (twoSuggestions) { ruleMatch.addSuggestedReplacement(suggestionText + " "); diff --git a/languagetool-core/src/test/java/org/languagetool/rules/CommaWhitespaceRuleTest.java b/languagetool-core/src/test/java/org/languagetool/rules/CommaWhitespaceRuleTest.java index <HASH>..<HASH> 100644 --- a/languagetool-core/src/test/java/org/languagetool/rules/CommaWhitespaceRuleTest.java +++ b/languagetool-core/src/test/java/org/languagetool/rules/CommaWhitespaceRuleTest.java @@ -60,6 +60,7 @@ public class CommaWhitespaceRuleTest { assertMatches("I'd recommend resaving the .DOC as a PDF file.", 0); assertMatches("I'd recommend resaving the .mp3 as a WAV file.", 0); assertMatches("I'd suggest buying the .org domain.", 0); + assertMatches(". This isn't good.", 0); // strange, but complaining without having a suggestions also doesn't help much... assertMatches("I live in .Los Angeles", 1); // errors:
avoid a match for strange cases where we don't (and can't) offer a suggestion
languagetool-org_languagetool
train
41051401bfcdf90253e800e5c541608df1618682
diff --git a/quilt_server/views.py b/quilt_server/views.py index <HASH>..<HASH> 100644 --- a/quilt_server/views.py +++ b/quilt_server/views.py @@ -413,7 +413,7 @@ def user_packages(auth_user, owner): ) @app.route('/api/log/<owner>/<package_name>/', methods=['GET']) -@api() +@api(require_login=False) @as_json def logs_list(auth_user, owner, package_name): package = _get_package(auth_user, owner, package_name) diff --git a/tests/log_test.py b/tests/log_test.py index <HASH>..<HASH> 100644 --- a/tests/log_test.py +++ b/tests/log_test.py @@ -5,6 +5,7 @@ Log tests import json import requests +from quilt_server.const import PUBLIC from quilt_server.core import hash_contents, GroupNode from .utils import QuiltTestCase @@ -58,7 +59,7 @@ class LogTestCase(QuiltTestCase): def testAccess(self): sharewith = "share_with" - # Can't view + # Can't view as a user with no access. resp = self.app.get( '/api/log/{usr}/{pkg}/'.format( usr=self.user, @@ -70,6 +71,15 @@ class LogTestCase(QuiltTestCase): ) assert resp.status_code == requests.codes.not_found + # Can't view when not logged in. + resp = self.app.get( + '/api/log/{usr}/{pkg}/'.format( + usr=self.user, + pkg=self.pkg + ), + ) + assert resp.status_code == requests.codes.not_found + # Share the package. resp = self._share_package(self.user, self.pkg, sharewith) assert resp.status_code == requests.codes.ok @@ -85,3 +95,25 @@ class LogTestCase(QuiltTestCase): } ) assert resp.status_code == requests.codes.ok + + # Still can't view when not logged in. + resp = self.app.get( + '/api/log/{usr}/{pkg}/'.format( + usr=self.user, + pkg=self.pkg + ), + ) + assert resp.status_code == requests.codes.not_found + + # Share the package publicly. + resp = self._share_package(self.user, self.pkg, PUBLIC) + assert resp.status_code == requests.codes.ok + + # Can now view when not logged in. + resp = self.app.get( + '/api/log/{usr}/{pkg}/'.format( + usr=self.user, + pkg=self.pkg + ), + ) + assert resp.status_code == requests.codes.ok
Make log work for public packages when not logged in
quiltdata_quilt
train
f208892d877eec9bc062c9d8d2af9983b35bd41c
diff --git a/ghost/admin/app/components/gh-navitem-url-input.js b/ghost/admin/app/components/gh-navitem-url-input.js index <HASH>..<HASH> 100644 --- a/ghost/admin/app/components/gh-navitem-url-input.js +++ b/ghost/admin/app/components/gh-navitem-url-input.js @@ -20,16 +20,11 @@ let isRelative = function (url) { export default TextField.extend({ classNames: 'gh-input', - classNameBindings: ['fakePlaceholder'], isBaseUrl: computed('baseUrl', 'value', function () { return this.get('baseUrl') === this.get('value'); }), - fakePlaceholder: computed('isBaseUrl', 'hasFocus', 'isNew', function () { - return this.get('isBaseUrl') && this.get('isNew') && !this.get('hasFocus'); - }), - didReceiveAttrs() { this._super(...arguments); diff --git a/ghost/admin/app/controllers/settings/navigation.js b/ghost/admin/app/controllers/settings/navigation.js index <HASH>..<HASH> 100644 --- a/ghost/admin/app/controllers/settings/navigation.js +++ b/ghost/admin/app/controllers/settings/navigation.js @@ -122,6 +122,11 @@ export default Controller.extend(SettingsSaveMixin, { addItem() { let newNavItem = this.get('newNavItem'); + // If the url sent through is blank (user never edited the url) + if (newNavItem.get('url') === '') { + newNavItem.set('url', '/'); + } + return newNavItem.validate().then(() => { this.addNewNavItem(); }); diff --git a/ghost/admin/app/styles/layouts/settings.css b/ghost/admin/app/styles/layouts/settings.css index <HASH>..<HASH> 100644 --- a/ghost/admin/app/styles/layouts/settings.css +++ b/ghost/admin/app/styles/layouts/settings.css @@ -34,10 +34,6 @@ cursor: move; } -.gh-blognav-url .fake-placeholder { - color: #c1c1c1; -} - .gh-blognav-line { display: flex; width: 100%; diff --git a/ghost/admin/tests/acceptance/settings/navigation-test.js b/ghost/admin/tests/acceptance/settings/navigation-test.js index <HASH>..<HASH> 100644 --- a/ghost/admin/tests/acceptance/settings/navigation-test.js +++ b/ghost/admin/tests/acceptance/settings/navigation-test.js @@ -150,11 +150,6 @@ describe('Acceptance: Settings - Navigation', function () { find('.gh-blognav-label:last .response').is(':visible'), 'blank label has validation error' ).to.be.true; - - expect( - find('.gh-blognav-url:last .response').is(':visible'), - 'blank url has validation error' - ).to.be.true; }); fillIn('.gh-blognav-label:last input', 'New'); @@ -165,11 +160,6 @@ describe('Acceptance: Settings - Navigation', function () { find('.gh-blognav-label:last .response').is(':visible'), 'label validation is visible after typing' ).to.be.false; - - expect( - find('.gh-blognav-url:last .response').is(':visible'), - 'blank url still has validation error' - ).to.be.true; }); fillIn('.gh-blognav-url:last input', '/new'); diff --git a/ghost/admin/tests/integration/components/gh-navitem-url-input-test.js b/ghost/admin/tests/integration/components/gh-navitem-url-input-test.js index <HASH>..<HASH> 100644 --- a/ghost/admin/tests/integration/components/gh-navitem-url-input-test.js +++ b/ghost/admin/tests/integration/components/gh-navitem-url-input-test.js @@ -189,21 +189,6 @@ describeComponent( expect($input.val()).to.equal(`${currentUrl} /test`); }); - it('toggles .fake-placeholder on focus', function () { - this.set('isNew', true); - this.render(hbs ` - {{gh-navitem-url-input baseUrl=baseUrl url=url isNew=isNew change="updateUrl" clearErrors=(action "clearErrors")}} - `); - let $input = this.$('input'); - - expect($input.hasClass('fake-placeholder')).to.be.true; - - run(() => { - $input.trigger('focus'); - }); - expect($input.hasClass('fake-placeholder')).to.be.false; - }); - it('triggers "change" action on blur', function () { let changeActionCallCount = 0; this.on('updateUrl', () => {
Remove Nav Item Placeholder and Set as Base Url Value Closes #<I> * Removed the `.fake-placeholder`class from the input, test, and css * On adding a nav item, if the url value has not been set by the user, then set it to the base url as shown in the input * If url has been set by the user, just do what it has always done
TryGhost_Ghost
train
6522f3e0c207db5a1b342185ea1671b4c0dcf616
diff --git a/hitch_test.go b/hitch_test.go index <HASH>..<HASH> 100644 --- a/hitch_test.go +++ b/hitch_test.go @@ -7,8 +7,6 @@ import ( "net/http/httptest" "runtime" "testing" - - "github.com/nbio/st" ) func TestHome(t *testing.T) { @@ -24,7 +22,10 @@ func TestEcho(t *testing.T) { defer res.Body.Close() expectHeaders(t, res) body, _ := ioutil.ReadAll(res.Body) - st.Assert(t, string(body), "hip-hop") + + if g, e := string(body), "hip-hop"; g != e { + t.Fatalf("should be == \n \thave: %s\n\twant: %s", g, e) + } } func TestRouteMiddleware(t *testing.T) { @@ -33,16 +34,22 @@ func TestRouteMiddleware(t *testing.T) { defer res.Body.Close() expectHeaders(t, res) body, _ := ioutil.ReadAll(res.Body) - st.Assert(t, string(body), "middleware1 -> middleware2 -> Hello, world! -> middleware2 -> middleware1") + + if g, e := string(body), "middleware1 -> middleware2 -> Hello, world! -> middleware2 -> middleware1"; g != e { + t.Fatalf("should be == \n \thave: %s\n\twant: %s", g, e) + } } func expectHeaders(t *testing.T, res *http.Response) { - st.Expect(t, res.Header.Get("Content-Type"), "text/plain") - st.Expect(t, res.Header.Get("X-Awesome"), "awesome") + if g, e := res.Header.Get("Content-Type"), "text/plain"; g != e { + t.Errorf("should be == \n \thave: %s\n\twant: %s", g, e) + } + if g, e := res.Header.Get("X-Awesome"), "awesome"; g != e { + t.Errorf("should be == \n \thave: %s\n\twant: %s", g, e) + } } // testServer - type testServer struct { *httptest.Server t *testing.T
drop github.com/nbio/st dependency in testing
nbio_hitch
train
a83bb46ffc84e25043d68ae4786bc5d6a532b215
diff --git a/src/main/java/com/tulskiy/keymaster/AWTTest.java b/src/main/java/com/tulskiy/keymaster/AWTTest.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/tulskiy/keymaster/AWTTest.java +++ b/src/main/java/com/tulskiy/keymaster/AWTTest.java @@ -22,17 +22,8 @@ public class AWTTest { public static void main(String[] args) { final JFrame frame = new JFrame(); - final Provider provider; - if (Platform.isX11()) { - provider = new X11Provider(); - } else if (Platform.isWindows()) { - provider = new WindowsProvider(); - } else if (Platform.isMac()) { - provider = new CarbonProvider(); - } else { - System.out.println("No suitable provider!"); - return; - } + final Provider provider = Provider.getCurrentProvider(); + provider.init(); final JTextField textField = new JTextField(); textField.setEditable(false); @@ -42,7 +33,7 @@ public class AWTTest { if (MODIFIERS.contains(e.getKeyCode())) textField.setText(""); else - textField.setText(KeyStroke.getKeyStrokeForEvent(e).toString()); + textField.setText(KeyStroke.getKeyStrokeForEvent(e).toString().replaceAll("pressed ", "")); } }); frame.add(textField, BorderLayout.CENTER); diff --git a/src/main/java/com/tulskiy/keymaster/ProviderTest.java b/src/main/java/com/tulskiy/keymaster/ProviderTest.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/tulskiy/keymaster/ProviderTest.java +++ b/src/main/java/com/tulskiy/keymaster/ProviderTest.java @@ -15,16 +15,8 @@ import java.awt.event.ActionListener; */ public class ProviderTest { public static void main(String[] args) { - final Provider provider; + final Provider provider = Provider.getCurrentProvider(); - if (Platform.isX11()) { - provider = new X11Provider(); - } else if (Platform.isWindows()) { - provider = new WindowsProvider(); - } else { - System.out.println("No suitable provider!"); - return; - } provider.init(); provider.register(KeyStroke.getKeyStroke("control alt D"), new ActionListener() { diff --git a/src/main/java/com/tulskiy/keymaster/common/Provider.java b/src/main/java/com/tulskiy/keymaster/common/Provider.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/tulskiy/keymaster/common/Provider.java +++ b/src/main/java/com/tulskiy/keymaster/common/Provider.java @@ -1,5 +1,10 @@ package com.tulskiy.keymaster.common; +import com.sun.jna.Platform; +import com.tulskiy.keymaster.osx.CarbonProvider; +import com.tulskiy.keymaster.windows.WindowsProvider; +import com.tulskiy.keymaster.x11.X11Provider; + import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -14,6 +19,19 @@ import java.util.logging.Logger; public abstract class Provider { public static final Logger logger = Logger.getLogger(Provider.class.getName()); + public static Provider getCurrentProvider() { + if (Platform.isX11()) { + return new X11Provider(); + } else if (Platform.isWindows()) { + return new WindowsProvider(); + } else if (Platform.isMac()) { + return new CarbonProvider(); + } else { + logger.warning("No suitable provider for " + System.getProperty("os.name")); + return null; + } + } + private ExecutorService eventQueue = Executors.newSingleThreadExecutor(); public abstract void init();
[common] added static method to get current provider
tulskiy_jkeymaster
train
36d4af6a9283c59fb96881404935b77e686b46fc
diff --git a/master/buildbot/db/buildslaves.py b/master/buildbot/db/buildslaves.py index <HASH>..<HASH> 100644 --- a/master/buildbot/db/buildslaves.py +++ b/master/buildbot/db/buildslaves.py @@ -157,11 +157,11 @@ class BuildslavesConnectorComponent(base.DBConnectorComponent): 'masterid': row.masterid}) # now go back and get the connection info for the same set of - # buildslaves + # workers j = conn_tbl if _name is not None: # note this is not an outer join; if there are unconnected - # buildslaves, they were captured in rv above + # workers, they were captured in rv above j = j.join(bslave_tbl) q = sa.select( [conn_tbl.c.buildslaveid, conn_tbl.c.masterid], diff --git a/master/buildbot/interfaces.py b/master/buildbot/interfaces.py index <HASH>..<HASH> 100644 --- a/master/buildbot/interfaces.py +++ b/master/buildbot/interfaces.py @@ -532,7 +532,7 @@ class IBuilderStatus(Interface): (possibly empty) representing the currently active builds.""" def getSlaves(): - """Return a list of ISlaveStatus objects for the buildslaves that are + """Return a list of ISlaveStatus objects for the workers that are used by this builder.""" def getPendingBuildRequestStatuses(): diff --git a/master/buildbot/process/builder.py b/master/buildbot/process/builder.py index <HASH>..<HASH> 100644 --- a/master/buildbot/process/builder.py +++ b/master/buildbot/process/builder.py @@ -65,11 +65,11 @@ class Builder(util_service.ReconfigurableServiceMixin, # old_building holds active builds that were stolen from a predecessor self.old_building = weakref.WeakKeyDictionary() - # buildslaves which have connected but which are not yet available. + # workers which have connected but which are not yet available. # These are always in the ATTACHING state. self.attaching_slaves = [] - # buildslaves at our disposal. Each SlaveBuilder instance has a + # workers at our disposal. Each SlaveBuilder instance has a # .state that is IDLE, PINGING, or BUILDING. "PINGING" is used when a # Build is about to start, to make sure that they're still alive. self.slaves = [] diff --git a/master/buildbot/steps/python_twisted.py b/master/buildbot/steps/python_twisted.py index <HASH>..<HASH> 100644 --- a/master/buildbot/steps/python_twisted.py +++ b/master/buildbot/steps/python_twisted.py @@ -175,7 +175,7 @@ class Trial(ShellCommand): name = "trial" progressMetrics = ('output', 'tests', 'test.log') - # note: the slash only works on unix buildslaves, of course, but we have + # note: the slash only works on unix workers, of course, but we have # no way to know what the buildslave uses as a separator. # TODO: figure out something clever. logfiles = {"test.log": "_trial_temp/test.log"} diff --git a/master/buildbot/test/fake/fakedata.py b/master/buildbot/test/fake/fakedata.py index <HASH>..<HASH> 100644 --- a/master/buildbot/test/fake/fakedata.py +++ b/master/buildbot/test/fake/fakedata.py @@ -44,7 +44,7 @@ class FakeUpdates(service.AsyncService): self.builderIds = {} # { name : id }; users can add schedulers here self.schedulerMasters = {} # { schedulerid : masterid } self.changesourceMasters = {} # { changesourceid : masterid } - self.buildslaveIds = {} # { name : id }; users can add buildslaves here + self.buildslaveIds = {} # { name : id }; users can add workers here # { logid : {'finished': .., 'name': .., 'type': .., 'content': [ .. ]} } self.logs = {} self.claimedBuildRequests = set([])
rename "buildslave" to "worker" in comments
buildbot_buildbot
train
d185af544dc12c917e905f0df81cb22d058bb591
diff --git a/src/Aerys/Server.php b/src/Aerys/Server.php index <HASH>..<HASH> 100644 --- a/src/Aerys/Server.php +++ b/src/Aerys/Server.php @@ -457,6 +457,8 @@ class Server extends TcpServer { $this->invokeOnHeadersMods($host, $requestId); if (!isset($client->responses[$requestId])) { + // Mods may have modified the request environment, so reload it. + $asgiEnv = $client->requests[$requestId]; $this->invokeRequestHandler($requestId, $asgiEnv, $host->getHandler()); } } @@ -831,6 +833,18 @@ class Server extends TcpServer { } } + function setRequest($requestId, array $asgiEnv) { + if (isset($this->requestIdClientMap[$requestId])) { + $client = $this->requestIdClientMap[$requestId]; + } else { + throw new \DomainException( + 'Request ID does not exist: ' . $requestId + ); + } + + $client->requests[$requestId] = $asgiEnv; + } + function getRequest($requestId) { if (isset($this->requestIdClientMap[$requestId])) { $client = $this->requestIdClientMap[$requestId];
Apps and mods can now modify the ASGI environment via Server::setRequest
amphp_http-server
train
ccdc653f6c1d5154adb6f5d6af9c13053726f581
diff --git a/openxc/sources/base.py b/openxc/sources/base.py index <HASH>..<HASH> 100644 --- a/openxc/sources/base.py +++ b/openxc/sources/base.py @@ -78,7 +78,7 @@ class SourceLogger(threading.Thread): self.file = open(filename, 'wa') def record(self, message): - if len(message) > 0: + if self.mode != "off" and len(message) > 0: log_file = None if self.mode == "stderr": log_file = sys.stderr @@ -109,6 +109,7 @@ class SourceLogger(threading.Thread): self.record(record) message_buffer = remainder + class BytestreamDataSource(DataSource): """A source that receives data is a series of bytes, with discrete messages separated by a newline character.
Don't show logs when in "off" mode. Fixed #<I>.
openxc_openxc-python
train
ea0359b76ff7d8fcb82759cd20f61cefb793e1b0
diff --git a/src/BulkUploader/BulkUploader.php b/src/BulkUploader/BulkUploader.php index <HASH>..<HASH> 100644 --- a/src/BulkUploader/BulkUploader.php +++ b/src/BulkUploader/BulkUploader.php @@ -330,7 +330,8 @@ class BulkUploader implements GridField_HTMLProvider, GridField_URLHandler public function bulkUploadField($gridField) { $fileRelationName = $this->getFileRelationName($gridField); - $uploadField = BulkUploadField::create($gridField, $fileRelationName, '') + $fieldName = $fileRelationName . '_' . $this->getRecordClassName($gridField) . '_BU'; + $uploadField = BulkUploadField::create($gridField, $fieldName, '') ->setForm($gridField->getForm()) /*->setConfig('previewMaxWidth', 20)
FIX UploadField name should be unique Avoid having multiple UploadFields with the same name, whcih in turn would all change at the same time
colymba_GridFieldBulkEditingTools
train
404e795f470099789d144f593cd0be2cf3ecfd0a
diff --git a/test/authentication/test_session.rb b/test/authentication/test_session.rb index <HASH>..<HASH> 100644 --- a/test/authentication/test_session.rb +++ b/test/authentication/test_session.rb @@ -8,7 +8,7 @@ module Authentication include Net::SSH::Authentication::Constants def test_constructor_should_set_defaults - assert_equal %w(none publickey hostbased password keyboard-interactive), session.auth_methods + assert_equal %w(none publickey password keyboard-interactive), session.auth_methods assert_equal session.auth_methods, session.allowed_auth_methods end @@ -44,7 +44,6 @@ module Authentication end Net::SSH::Authentication::Methods::Publickey.any_instance.expects(:authenticate).with("next service", "username", "password").returns(false) - Net::SSH::Authentication::Methods::Hostbased.any_instance.expects(:authenticate).with("next service", "username", "password").returns(false) Net::SSH::Authentication::Methods::Password.any_instance.expects(:authenticate).with("next service", "username", "password").returns(false) Net::SSH::Authentication::Methods::KeyboardInteractive.any_instance.expects(:authenticate).with("next service", "username", "password").returns(false) Net::SSH::Authentication::Methods::None.any_instance.expects(:authenticate).with("next service", "username", "password").returns(false)
updated tests to match the default of not allowing hostbased auth
net-ssh_net-ssh
train
6e3b1c835d9db31a52e4bf6d82037d31f773be8e
diff --git a/lib/Predis.php b/lib/Predis.php index <HASH>..<HASH> 100644 --- a/lib/Predis.php +++ b/lib/Predis.php @@ -1461,7 +1461,15 @@ class Sort extends \Predis\InlineCommand { $query[] = 'BY ' . $sortParams['by']; } if (isset($sortParams['get'])) { - $query[] = 'GET ' . $sortParams['get']; + $getargs = $sortParams['get']; + if (is_array($getargs)) { + foreach ($getargs as $getarg) { + $query[] = 'GET ' . $getarg; + } + } + else { + $query[] = 'GET ' . $getargs; + } } if (isset($sortParams['limit']) && is_array($sortParams['limit'])) { $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
Enhancement: support multiple GET parameters for the SORT command (see also my comment in ISSUE #1)
nrk_predis
train
e697854bb97319ef14dd61ed9f125bef3f8bb4eb
diff --git a/evaluation.py b/evaluation.py index <HASH>..<HASH> 100644 --- a/evaluation.py +++ b/evaluation.py @@ -103,39 +103,69 @@ class ClassEvaluation(object): def precision(self, cls=None): if not self.computed: self.compute() if cls: - return self.tp[cls] / float(self.tp[cls] + self.fp[cls]) + if self.tp[cls] + self.fp[cls] > 0: + return self.tp[cls] / float(self.tp[cls] + self.fp[cls]) + else: + return float('nan') else: - return sum( ( self.precision(x) for x in self.observations ) ) / float(len(self.observations)) + if len(self.observations) > 0: + return sum( ( self.precision(x) for x in self.observations ) ) / float(len(self.observations)) + else: + return float('nan') def recall(self, cls=None): if not self.computed: self.compute() if cls: - return self.tp[cls] / float(self.tp[cls] + self.fn[cls]) + if self.tp[cls] + self.fn[cls] > 0: + return self.tp[cls] / float(self.tp[cls] + self.fn[cls]) + else: + return float('nan') else: - return sum( ( self.recall(x) for x in self.observations ) ) / float(len(self.observations)) + if len(self.observations) > 0: + return sum( ( self.recall(x) for x in self.observations ) ) / float(len(self.observations)) + else: + return float('nan') def specificity(self, cls=None): if not self.computed: self.compute() if cls: - return self.tn[cls] / float(self.tn[cls] + self.fp[cls]) + if self.tn[cls] + self.fp[cls] > 0: + return self.tn[cls] / float(self.tn[cls] + self.fp[cls]) + else: + return float('nan') else: - return sum( ( self.specificity(x) for x in self.observations ) ) / float(len(self.observations)) + if len(self.observations) > 0: + return sum( ( self.specificity(x) for x in self.observations ) ) / float(len(self.observations)) + else: + return float('nan') def accuracy(self, cls=None): if not self.computed: self.compute() if cls: - return (self.tp[cls]+self.tn[cls]) / float(self.tp[cls] + self.tn[cls] + self.fp[cls] + self.fn[cls]) + if self.tp[cls] + self.tn[cls] + self.fp[cls] + self.fn[cls] > 0: + return (self.tp[cls]+self.tn[cls]) / float(self.tp[cls] + self.tn[cls] + self.fp[cls] + self.fn[cls]) + else: + return float('nan') else: - return sum( ( self.tp[x] for x in self.tp ) ) / float(len(self.observations)) + if len(self.observations) > 0: + return sum( ( self.tp[x] for x in self.tp ) ) / float(len(self.observations)) + else: + return float('nan') def fscore(self, cls=None, beta=1): if not self.computed: self.compute() if cls: prec = self.precision(cls) rec = self.recall(cls) - return (1 + beta*beta) * ((prec * rec) / (beta*beta * prec + rec)) + if prec * rec > 0: + return (1 + beta*beta) * ((prec * rec) / (beta*beta * prec + rec)) + else: + return float('nan') else: - return sum( ( self.fscore(x) for x in self.observations ) ) / float(len(self.observations)) + if len(self.observations) > 0: + return sum( ( self.fscore(x) for x in self.observations ) ) / float(len(self.observations)) + else: + return float('nan') def __iter__(self):
protection against division by zero git-svn-id: <URL>
proycon_pynlpl
train
a6e82130a0f2af135d88ffa9d3b7474719c43cb6
diff --git a/wafer/pages/models.py b/wafer/pages/models.py index <HASH>..<HASH> 100644 --- a/wafer/pages/models.py +++ b/wafer/pages/models.py @@ -22,7 +22,11 @@ class File(models.Model): item = models.FileField(upload_to='pages_files') def __str__(self): - return u'%s' % (self.name,) + if self.pages.exists(): + pages = ' & '.join([x.name for x in self.pages.all()]) + return u'<%s>: %s (%s)' % (pages, self.name, self.item.url) + else: + return u'<No Page>: %s (%s)' % (self.name, self.item.url) @python_2_unicode_compatible diff --git a/wafer/sponsors/models.py b/wafer/sponsors/models.py index <HASH>..<HASH> 100644 --- a/wafer/sponsors/models.py +++ b/wafer/sponsors/models.py @@ -15,7 +15,11 @@ class File(models.Model): item = models.FileField(upload_to='sponsors_files') def __str__(self): - return u'%s' % (self.name,) + if self.sponsors.exists(): + sponsors = ' & '.join([x.name for x in self.sponsors.all()]) + return u'<%s>: %s (%s)' % (sponsors, self.name, self.item.url) + else: + return u'<No Sponsor>: %s (%s)' % (self.name, self.item.url) @python_2_unicode_compatible
Tweak file repr to make associations between files and relevant pages / sponsors clearer
CTPUG_wafer
train
0186ccf12ae16032b5b94e32a8e78e2ca9000a68
diff --git a/websockhop.js b/websockhop.js index <HASH>..<HASH> 100644 --- a/websockhop.js +++ b/websockhop.js @@ -573,7 +573,10 @@ var handler = isObject(obj) ? this.formatter.getHandlerForResponse(obj) : null; if (handler != null) { handler.callback(obj); - if (this._lastSentPingRequest != null && this._lastSentPingRequest.id == this._lastReceivedPongId) { + if (this._lastSentPingRequest != null && + this._lastSentPingRequest.obj != null && + this._lastSentPingRequest.obj.id == this._lastReceivedPongId + ) { this._lastSentPingRequest = null; this._lastReceivedPongId = 0; isPong = true;
Additional fix to pong response for "stopped sending private info with request() call"
fanout_websockhop
train
7eaf9c2476b99e05b8af2bfe395144ff8c10de09
diff --git a/examples/nas/oneshot/pfld/train.py b/examples/nas/oneshot/pfld/train.py index <HASH>..<HASH> 100644 --- a/examples/nas/oneshot/pfld/train.py +++ b/examples/nas/oneshot/pfld/train.py @@ -63,6 +63,7 @@ def main(args): alpha=args.alpha, beta=args.beta, search_space=search_space, + start_epoch=args.start_epoch, ) # look-up table with information of search space, flops per block, etc. lookup_table = LookUpTable(config=nas_config, primitives=PRIMITIVES) @@ -162,6 +163,7 @@ def parse_args(): ) parser.add_argument("--alpha", default=0.25, type=float) parser.add_argument("--beta", default=0.6, type=float) + parser.add_argument("--start_epoch", default=50, type=int) parser.add_argument("--end_epoch", default=300, type=int) parser.add_argument( "--snapshot", default="models", type=str, metavar="PATH"
Add start_epoch configuration in PFLD example (#<I>)
Microsoft_nni
train
6f8dd4b254b92f74ce0dadbc9a674b8d81e03df5
diff --git a/lib/verbs/conjugator.rb b/lib/verbs/conjugator.rb index <HASH>..<HASH> 100644 --- a/lib/verbs/conjugator.rb +++ b/lib/verbs/conjugator.rb @@ -1,10 +1,10 @@ # The program conjugates most common english verbs with the following option: -# * :tense => :past or :present or :future -# * :person => :first or :second or :third -# * :plurality => :singular or :plural -# * :aspect => :habitual or :perfect or :perfective or :progressive or :prospective -# * :mood => :indicative or :imperative or :subjunctive -# Respective defaults are :present, :third, :singular, :habitual (:perfective for past tense), and :indicative +# * :tense => :past or :present or :future (default: :present) +# * :person => :first or :second or :third (default: :third) +# * :plurality => :singular or :plural (default: :singular) +# * :aspect => :habitual or :perfect or :perfective or :progressive or :prospective (default: :habitual, or :perfective for past tense) +# * :mood => :indicative or :imperative or :subjunctive (default: :indicative) +# * :diathesis => :active or :passive (default: :active) # # Author:: Andy Rossmeissl # Copyright:: Copyright (c) 2009 Andy Rossmeissl
add missing comment for diathesis option
rossmeissl_verbs
train
5d2946966ad5297e0c7d38c75ce704103088b3b6
diff --git a/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/suites/DomainTestSuite.java b/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/suites/DomainTestSuite.java index <HASH>..<HASH> 100644 --- a/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/suites/DomainTestSuite.java +++ b/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/suites/DomainTestSuite.java @@ -22,6 +22,7 @@ package org.jboss.as.test.integration.domain.suites; +import org.jboss.as.test.integration.domain.AdminOnlyModeTestCase; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.integration.domain.management.util.JBossAsManagedConfigurationParameters; import org.junit.AfterClass; @@ -38,17 +39,23 @@ import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses ({ CoreResourceManagementTestCase.class, - ManagementReadsTestCase.class, + DatasourceTestCase.class, DeploymentManagementTestCase.class, DeploymentOverlayTestCase.class, - ServerManagementTestCase.class, - ServerRestartRequiredTestCase.class, + DirectoryGroupingByTypeTestCase.class, + ExtensionManagementTestCase.class, + IgnoredResourcesTestCase.class, ManagementAccessTestCase.class, ManagementClientContentTestCase.class, - ValidateOperationOperationTestCase.class, + ManagementReadsTestCase.class, + ManagementVersionTestCase.class, + ModelPersistenceTestCase.class, + OperationTransformationTestCase.class, ReadEnvironmentVariablesTestCase.class, - ExtensionManagementTestCase.class, - OperationTransformationTestCase.class + ServerManagementTestCase.class, + ServerRestartRequiredTestCase.class, + ValidateAddressOperationTestCase.class, + ValidateOperationOperationTestCase.class }) public class DomainTestSuite {
Add tests to DomainTestSuite so they always run
wildfly_wildfly
train
a1807fd5ed115ae1708b631d9639bf3cb11b8f90
diff --git a/src/auth.js b/src/auth.js index <HASH>..<HASH> 100644 --- a/src/auth.js +++ b/src/auth.js @@ -5,7 +5,7 @@ var request = require('request').defaults({ headers: { "x-tesla-user-agent": "TeslaApp/3.10.8-421/adff2e065/android/8.1.0", - "user-agent": "Mozilla/5.0 (Linux; Android 8.1.0; Pixel XL Build/OPM4.171019.021.D1; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/68.0.3440.91 Mobile Safari/537.36", + "user-agent": "TeslaApp", "x-requested-with": "com.teslamotors.tesla" }, gzip: true,
Fixed header per timdorr suggestion (#<I>) as found in the authentication documentation <URL>
mseminatore_TeslaJS
train
709af06ce2f8342bd83c4d484abc97341991388e
diff --git a/masonite/drivers/UploadDiskDriver.py b/masonite/drivers/UploadDiskDriver.py index <HASH>..<HASH> 100644 --- a/masonite/drivers/UploadDiskDriver.py +++ b/masonite/drivers/UploadDiskDriver.py @@ -12,6 +12,8 @@ class UploadDiskDriver(object): if not location: location = self.config.DRIVERS['disk']['location'] + location += '/' + open(location + filename, 'wb').write(fileitem.file.read()) return location + filename
closes #<I> - Uploading images does not direct to the correct location
MasoniteFramework_masonite
train
6e5dccbbe5ed5411ca5b59846161adf448c77b3d
diff --git a/lib/config.js b/lib/config.js index <HASH>..<HASH> 100644 --- a/lib/config.js +++ b/lib/config.js @@ -61,6 +61,8 @@ defaultConfig.searchResultCnt = 10; defaultConfig.playedQueueSize = 100; defaultConfig.songDelayMs = 1000; // add delay between songs to prevent skips +defaultConfig.songPrepareTimeout = 10000; // cancel preparation if no progress + // hostname of the server, may be used as a default value by other plugins defaultConfig.hostname = os.hostname(); diff --git a/lib/player.js b/lib/player.js index <HASH>..<HASH> 100644 --- a/lib/player.js +++ b/lib/player.js @@ -118,6 +118,24 @@ Player.prototype.pausePlayback = function() { this.callHooks('onSongPause', [this.nowPlaying]); }; +// TODO: proper song object with constructor? +Player.prototype.setPrepareTimeout = function(song) { + if (song.prepareTimeout) { + clearTimeout(song.prepareTimeout); + } + + song.prepareTimeout = setTimeout(_.bind(function() { + this.logger.info('prepare timeout for song: ' + song.songID + ', removing'); + song.cancelPrepare('prepare timeout'); + song.prepareTimeout = null; + }, this), this.config.songPrepareTimeout); + + Object.defineProperty(song, 'prepareTimeout', { + enumerable: false, + writable: true + }); +}; + Player.prototype.prepareError = function(song, err) { // remove all instances of this song for (var i = this.queue.length - 1; i >= 0; i--) { @@ -154,7 +172,14 @@ Player.prototype.prepareProgCallback = function(song, dataSize, done, asyncCallb delete(song.cancelPrepare); delete(this.songsPreparing[song.backendName][song.songID]); + // clear prepare timeout + clearTimeout(song.prepareTimeout); + song.prepareTimeout = null; + asyncCallback(); + } else { + // reset prepare timeout + this.setPrepareTimeout(song); } // tell plugins that new data is available for this song, and @@ -168,6 +193,10 @@ Player.prototype.prepareErrCallback = function(song, err, asyncCallback) { // don't let anything run cancelPrepare anymore delete(song.cancelPrepare); + // clear prepare timeout + clearTimeout(song.prepareTimeout); + song.prepareTimeout = null; + // abort preparing more songs; current song will be deleted -> // onQueueModified is called -> song preparation is triggered again asyncCallback(true); @@ -214,6 +243,8 @@ Player.prototype.prepareSong = function(song, asyncCallback) { _.partial(this.prepareProgCallback, _, _, _, asyncCallback), _.partial(this.prepareErrCallback, _, _, asyncCallback) ); + + this.setPrepareTimeout(song); } };
prepare timeouts if no progress callback called for x ms
FruitieX_nodeplayer
train
9de47d3a39ae67722284d86905af58d241eff96b
diff --git a/components/prism-css-extras.js b/components/prism-css-extras.js index <HASH>..<HASH> 100644 --- a/components/prism-css-extras.js +++ b/components/prism-css-extras.js @@ -9,11 +9,14 @@ Prism.languages.css.selector = { } }; -Prism.languages.insertBefore('css', 'function', { +Prism.languages.insertBefore('css', 'property', { 'variable': { - pattern: /(var\()[^)]+(?=\))/, + pattern: /(^|[^-\w\xA0-\uFFFF])--[-_a-z\xA0-\uFFFF][-\w\xA0-\uFFFF]*/i, lookbehind: true - }, + } +}); + +Prism.languages.insertBefore('css', 'function', { 'operator': { pattern: /(\s)[+\-*\/](?=\s)/, lookbehind: true diff --git a/components/prism-css-extras.min.js b/components/prism-css-extras.min.js index <HASH>..<HASH> 100644 --- a/components/prism-css-extras.min.js +++ b/components/prism-css-extras.min.js @@ -1 +1 @@ -Prism.languages.css.selector={pattern:Prism.languages.css.selector,inside:{"pseudo-element":/:(?:after|before|first-letter|first-line|selection)|::[-\w]+/,"pseudo-class":/:[-\w]+(?:\(.*\))?/,"class":/\.[-:.\w]+/,id:/#[-:.\w]+/,attribute:/\[[^\]]+\]/}},Prism.languages.insertBefore("css","function",{variable:{pattern:/(var\()[^)]+(?=\))/,lookbehind:!0},operator:{pattern:/(\s)[+\-*\/](?=\s)/,lookbehind:!0},hexcode:/#[\da-f]{3,8}/i,entity:/\\[\da-f]{1,8}/i,unit:{pattern:/(\d)(?:%|[a-z]+)/,lookbehind:!0},number:/-?[\d.]+/}); \ No newline at end of file +Prism.languages.css.selector={pattern:Prism.languages.css.selector,inside:{"pseudo-element":/:(?:after|before|first-letter|first-line|selection)|::[-\w]+/,"pseudo-class":/:[-\w]+(?:\(.*\))?/,"class":/\.[-:.\w]+/,id:/#[-:.\w]+/,attribute:/\[[^\]]+\]/}},Prism.languages.insertBefore("css","property",{variable:{pattern:/(^|[^-\w\xA0-\uFFFF])--[-_a-z\xA0-\uFFFF][-\w\xA0-\uFFFF]*/i,lookbehind:!0}}),Prism.languages.insertBefore("css","function",{operator:{pattern:/(\s)[+\-*\/](?=\s)/,lookbehind:!0},hexcode:/#[\da-f]{3,8}/i,entity:/\\[\da-f]{1,8}/i,unit:{pattern:/(\d)(?:%|[a-z]+)/,lookbehind:!0},number:/-?[\d.]+/}); \ No newline at end of file diff --git a/tests/languages/css!+css-extras/variable_feature.test b/tests/languages/css!+css-extras/variable_feature.test index <HASH>..<HASH> 100644 --- a/tests/languages/css!+css-extras/variable_feature.test +++ b/tests/languages/css!+css-extras/variable_feature.test @@ -1,10 +1,23 @@ +element { + --foo: green; +} + var(--color-primary) var(--level-3) +var(--foo, red) calc(100% - var(--margin-size) * 2) ---------------------------------------------------- [ + ["selector", ["element"]], + ["punctuation", "{"], + ["variable", "--foo"], + ["punctuation", ":"], + " green", + ["punctuation", ";"], + ["punctuation", "}"], + ["function", "var"], ["punctuation", "("], ["variable", "--color-primary"], @@ -15,6 +28,13 @@ calc(100% - var(--margin-size) * 2) ["variable", "--level-3"], ["punctuation", ")"], + ["function", "var"], + ["punctuation", "("], + ["variable", "--foo"], + ["punctuation", ","], + " red", + ["punctuation", ")"], + ["function", "calc"], ["punctuation", "("], ["number", "100"],
Fixed CSS extra variable (#<I>) Details are described [here](<URL>
PrismJS_prism
train
18caaeab0eb00d4186eea15b393b1b0b810cbd8e
diff --git a/Core/Executor/ContentManager.php b/Core/Executor/ContentManager.php index <HASH>..<HASH> 100644 --- a/Core/Executor/ContentManager.php +++ b/Core/Executor/ContentManager.php @@ -597,13 +597,7 @@ class ContentManager extends RepositoryExecutor implements MigrationGeneratorInt { $fields = $this->normalizeFieldDefs($fields, $step); - if ($this->hasLanguageCodesAsKeys($fields)) { - $fieldsList = $this->parseMultiLangFields($fields); - } else { - $fieldsList = $this->parseSingleLangFields($fields, $this->getLanguageCode($step)); - } - - foreach ($fieldsList as $fieldIdentifier => $fieldLanguages) { + foreach ($fields as $fieldIdentifier => $fieldLanguages) { foreach ($fieldLanguages as $language => $fieldValue) { if (!isset($contentType->fieldDefinitionsByIdentifier[$fieldIdentifier])) { throw new \Exception("Field '$fieldIdentifier' is not present in content type '{$contentType->identifier}'");
fixup for commit d0c8b1a9f<I>
kaliop-uk_ezmigrationbundle
train
d84b82a7520d164f791a7abf9b0d348bb2f592a6
diff --git a/lib/sorcery/controller/submodules/session_timeout.rb b/lib/sorcery/controller/submodules/session_timeout.rb index <HASH>..<HASH> 100644 --- a/lib/sorcery/controller/submodules/session_timeout.rb +++ b/lib/sorcery/controller/submodules/session_timeout.rb @@ -38,6 +38,7 @@ module Sorcery def validate_session session_to_use = Config.session_timeout_from_last_action ? session[:last_action_time] : session[:login_time] if session_to_use && (Time.now.in_time_zone - session_to_use > Config.session_timeout) + if session_to_use && (Time.now.in_time_zone - session_to_use.to_time > Config.session_timeout) reset_sorcery_session @current_user = nil else diff --git a/spec/active_record/controller_session_timeout_spec.rb b/spec/active_record/controller_session_timeout_spec.rb index <HASH>..<HASH> 100644 --- a/spec/active_record/controller_session_timeout_spec.rb +++ b/spec/active_record/controller_session_timeout_spec.rb @@ -29,6 +29,13 @@ describe SorceryController do response.should be_a_redirect end + it "should work if the session is stored as a string or a Time" do + session[:login_time] = Time.now.to_s + get :test_login, :email => 'bla@bla.com', :password => 'secret' + session[:user_id].should_not be_nil + response.should be_a_success + end + context "with 'session_timeout_from_last_action'" do it "should not logout if there was activity" do sorcery_controller_property_set(:session_timeout_from_last_action, true)
Fix session timeout to work with Rails cookie store Rails cookie-based default session store represents times as Strings, which must be converted to times before comparison.
Sorcery_sorcery
train
a7e092f510dc7aba48092886897515fc1b843cfe
diff --git a/cmd/info.js b/cmd/info.js index <HASH>..<HASH> 100644 --- a/cmd/info.js +++ b/cmd/info.js @@ -9,10 +9,13 @@ exports.describe = 'Get info from npms.io of a given package.'; exports.builder = (yargs) => yargs .strict() + .demand(1, 1) + .usage('Usage: $0 info <package> [options]\n\nGet info from npms.io of a given package.') + .example('$0 info gulp', 'Get "gulp" package info') .options({ output: { alias: 'o', - describe: 'Format the results in a human readable format or as JSON.', + describe: 'Format the results in a human readable format or as JSON', default: 'human', }, }); diff --git a/cmd/open.js b/cmd/open.js index <HASH>..<HASH> 100644 --- a/cmd/open.js +++ b/cmd/open.js @@ -8,7 +8,10 @@ exports.command = 'open <package>'; exports.describe = 'Opens the package in your browser.'; exports.builder = (yargs) => yargs - .strict(); + .strict() + .usage('Usage: $0 open <package> [options]\n\nOpens the package in your browser..') + .example('$0 open gulp', 'Opens "gulp" package') + .demand(1, 1); exports.handler = (argv) => { got(`https://api.npms.io/module/${encodeURIComponent(argv.package)}`, { json: true }) diff --git a/cmd/search.js b/cmd/search.js index <HASH>..<HASH> 100644 --- a/cmd/search.js +++ b/cmd/search.js @@ -7,43 +7,47 @@ const moment = require('moment'); const truncate = require('truncate'); const handleError = require('./util/handleError'); -exports.command = 'search <packages...>'; +exports.command = 'search <term...>'; exports.describe = 'Search npms.io for packages matching the search terms.'; exports.builder = (yargs) => yargs .strict() + .usage('Usage: $0 search <term...> [options]\n\nSearch npms.io for packages matching the search terms.') + .example('$0 search cross spawn', 'Search for "cross spawn"') + .example('$0 search cross spawn --output json', 'Search for "cross spawn" and print results as JSON') + .demand(1) .options({ from: { alias: 'f', - describe: 'The offset in which to start searching from.', + describe: 'The offset in which to start searching from', default: 0, type: 'number', }, size: { alias: 's', - describe: 'The total number of results to return.', + describe: 'The total number of results to return', default: 10, type: 'number', }, output: { alias: 'o', - describe: 'Format the results in a table or as JSON.', + describe: 'Format the results in a table or as JSON', default: 'table', }, 'score-effect': { - describe: 'The effect that the module scores have for the final search score.', + describe: 'The effect that the module scores have for the final search score', type: 'number', }, 'quality-weight': { - describe: 'The weight that the quality has for the each module score.', + describe: 'The weight that the quality has for the each module score', type: 'number', }, 'popularity-weight': { - describe: 'The weight that the popularity has for each module score.', + describe: 'The weight that the popularity has for each module score', type: 'number', }, 'maintenance-weight': { - describe: 'The weight that the maintenance has for each module score.', + describe: 'The weight that the maintenance has for each module score', type: 'number', }, }); @@ -52,7 +56,7 @@ exports.handler = (argv) => { got('https://api.npms.io/search', { json: true, query: JSON.parse(JSON.stringify({ - term: argv.packages.join('+'), + term: argv.term.join('+'), from: argv.from, size: argv.size, scoreEffect: argv['score-effect'], @@ -68,7 +72,7 @@ exports.handler = (argv) => { } if (!res.body.results.length) { - console.log(chalk.red(`No matches found for: ${chalk.white.bold(argv.packages.join('+'))}`)); + console.log(chalk.red(`No matches found for: ${chalk.white.bold(argv.term.join(' '))}`)); return; }
Add usage and examples to the CLI. Standardize some options.
npms-io_npms-cli
train
723730f8acf9a159cf23c2836ba040b0db678b74
diff --git a/assets/codemirror/codemirror.js b/assets/codemirror/codemirror.js index <HASH>..<HASH> 100644 --- a/assets/codemirror/codemirror.js +++ b/assets/codemirror/codemirror.js @@ -1,4 +1,4 @@ -// CodeMirror version 2.31 +// CodeMirror version 2.32 // // All functions that need access to the editor's state live inside // the CodeMirror function. Below that, at the bottom of the file, @@ -1143,7 +1143,7 @@ var CodeMirror = (function() { var shouldHaveScrollbar = scrollHeight ? "block" : "none"; if (scrollbar.style.display != shouldHaveScrollbar) { scrollbar.style.display = shouldHaveScrollbar; - scrollbarInner.style.height = scrollHeight + "px"; + if (scrollHeight) scrollbarInner.style.height = scrollHeight + "px"; checkHeights(); } } @@ -2667,7 +2667,12 @@ var CodeMirror = (function() { outPos += l; span_(text, style); // Output empty wrapper when at end of line - if (outPos == wrapAt && outPos == len) html.push(open + (gecko ? "&#x200b;" : " ") + "</span>"); + // (Gecko and IE8+ do strange wrapping when adding a space + // to the end of the line. Other browsers don't react well + // to zero-width spaces. So we do hideous browser sniffing + // to determine which to use.) + if (outPos == wrapAt && outPos == len) + html.push(open + (gecko || (ie && !ie_lt8) ? "&#x200b;" : " ") + "</span>"); // Stop outputting HTML when gone sufficiently far beyond measure else if (outPos > wrapAt + 10 && /\s/.test(text)) span = function(){}; }
Update CodeMirror to version <I>. According to CodeMirror web site: <I>-<I>-<I>: Version <I>: Emergency fix for a bug where an editor with line wrapping on IE will break when there is no scrollbar. <URL>
jscs-dev_esprima-harmony
train
95f9f2bf69429968b34000571ba7c895e23e68b1
diff --git a/lib/plugins/httpHeaders.js b/lib/plugins/httpHeaders.js index <HASH>..<HASH> 100644 --- a/lib/plugins/httpHeaders.js +++ b/lib/plugins/httpHeaders.js @@ -3,18 +3,18 @@ module.exports = { if(req.prerender.documentHTML) { var statusMatch = /<meta name=['"]prerender-status-code['"] content=['"]([0-9]{3})['"] ?\/?>/i, headerMatch = /<meta name=['"]prerender-header['"] content=['"](.*?): ?(.*?)['"] ?\/?>/gi, - head = req.prerender.documentHTML.split('</head>', 1).pop(), + head = req.prerender.documentHTML.toString().split('</head>', 1).pop(), statusCode = 200, match; if (match = statusMatch.exec(head)) { statusCode = match[1]; - req.prerender.documentHTML = req.prerender.documentHTML.replace(match[0], ''); + req.prerender.documentHTML = req.prerender.documentHTML.toString().replace(match[0], ''); } while (match = headerMatch.exec(head)) { res.setHeader(match[1], match[2]); - req.prerender.documentHTML = req.prerender.documentHTML.replace(match[0], ''); + req.prerender.documentHTML = req.prerender.documentHTML.toString().replace(match[0], ''); } if (statusCode != 200) {
making sure httpHeaders handles buffers
prerender_prerender
train
2d0105f245a9f9dde780c76c78d52978a18537c2
diff --git a/languagetool-language-modules/de/src/test/java/org/languagetool/rules/de/AgreementRuleTest.java b/languagetool-language-modules/de/src/test/java/org/languagetool/rules/de/AgreementRuleTest.java index <HASH>..<HASH> 100644 --- a/languagetool-language-modules/de/src/test/java/org/languagetool/rules/de/AgreementRuleTest.java +++ b/languagetool-language-modules/de/src/test/java/org/languagetool/rules/de/AgreementRuleTest.java @@ -226,6 +226,7 @@ public class AgreementRuleTest { assertGood("Er wollte doch nur jemandem Gutes tun."); assertGood("und das erst Jahrhunderte spätere Auftauchen der Legende"); assertGood("Texas und New Mexico, beides spanische Kolonien, sind..."); + assertGood("Unser Hund vergräbt seine Knochen im Garten."); // incorrect sentences: assertBad("Ein Buch mit einem ganz ähnlichem Titel.");
[de] add test for "unser"
languagetool-org_languagetool
train
07f786b28bc08deff87692f4a1d1d67c72e9def2
diff --git a/aeron-archive/src/main/java/io/aeron/archive/RecordingWriter.java b/aeron-archive/src/main/java/io/aeron/archive/RecordingWriter.java index <HASH>..<HASH> 100644 --- a/aeron-archive/src/main/java/io/aeron/archive/RecordingWriter.java +++ b/aeron-archive/src/main/java/io/aeron/archive/RecordingWriter.java @@ -139,13 +139,11 @@ class RecordingWriter implements BlockHandler void close() { - if (isClosed) + if (!isClosed) { - return; + CloseHelper.close(recordingFileChannel); + isClosed = true; } - - isClosed = true; - CloseHelper.close(recordingFileChannel); } void init(final int segmentOffset) throws IOException
[Java] Mark closed after a successful close.
real-logic_aeron
train
295cd986fbc191de926e19e91de279cd9a8b1ff5
diff --git a/src-gwt/org/opencms/acacia/client/widgets/CmsSelectConfigurationParser.java b/src-gwt/org/opencms/acacia/client/widgets/CmsSelectConfigurationParser.java index <HASH>..<HASH> 100644 --- a/src-gwt/org/opencms/acacia/client/widgets/CmsSelectConfigurationParser.java +++ b/src-gwt/org/opencms/acacia/client/widgets/CmsSelectConfigurationParser.java @@ -27,6 +27,7 @@ package org.opencms.acacia.client.widgets; +import org.opencms.gwt.client.util.CmsDebugLog; import org.opencms.util.CmsStringUtil; import java.util.ArrayList; @@ -47,6 +48,7 @@ public class CmsSelectConfigurationParser { /** Delimiter between option sets. */ private static final char INPUT_DELIMITER = '|'; + /** Delimiter at the end of a value. */ private static final char VALUE_DELIMITER = '\''; @@ -111,9 +113,32 @@ public class CmsSelectConfigurationParser { public static String[] splitOptions(String input) { //Note that we use a regex matching all "|" characters not prefixed by "\" + //Since we define a regex for matching, the input delimiter "|" needs to be escaped, as well as "\", //which is even double-escaped - one escaping is due to the String, one due to the regex. - return input.split("(?<!\\\\)\\" + INPUT_DELIMITER); + + // emulate missing lookbehinds in JS regexes by first reversing the input, + // then using a split with lookaheads, and finally reversing the parts resulting + // from the split + String reverse = reverse(input); + String[] parts = reverse.split("\\|(?!\\\\)"); + + for (int i = 0; i < parts.length; i++) { + parts[i] = reverse(parts[i]); + } + return parts; + + } + + /** + * Reverses a string.<p> + * + * @param input the input string + * @return the reversed string + */ + private static String reverse(String input) { + + return new StringBuilder(input).reverse().toString(); } /**
Fixed error in select widget option parsing.
alkacon_opencms-core
train
1aa2cb732485d037a4386eefaded22e87c75acc0
diff --git a/public/js/core.forms.js b/public/js/core.forms.js index <HASH>..<HASH> 100644 --- a/public/js/core.forms.js +++ b/public/js/core.forms.js @@ -21,7 +21,7 @@ { $.each(errors, function(idx, error) { var $errorsDiv = $form.find('#' + prefix + idx + '-errors'); - console.debug('inserting error messages', '#' + prefix + idx + '-errors', $errorsDiv, error); +// console.debug('inserting error messages', '#' + prefix + idx + '-errors', $errorsDiv, error); if ($errorsDiv.length) { var html = '<ul class="error">' $.each(error, function(i, err) { @@ -42,7 +42,7 @@ onSubmit: function(e, extraData) { var $form = $(e.currentTarget); var data = $form.serializeArray(); - console.debug('data', e, $form, data); +// console.debug('data', e, $form, data); if (extraData) { $.each(extraData, function(idx, value) { data.push({ @@ -70,7 +70,7 @@ if (!data.valid) { methods.displayErrors($form, data.errors); } - console.debug('bubble done event for form',$form,data); +// console.debug('bubble done event for form',$form,data); $form.trigger('yk.forms.done', {data: data, status:textStatus, jqXHR:jqXHR}); // DEPRECATED EVENT USE NEXT $form.trigger('done.yk.core.forms', {data: data, status:textStatus, jqXHR: jqXHR}); $form.trigger('ajax.ready', {'data': data}); @@ -90,7 +90,7 @@ if (validate) { data.validationGroup = validate; } - console.debug('triggering a submit on change', data); +// console.debug('triggering a submit on change', data); $element.parents('form').trigger('submit', data); return false; } @@ -117,7 +117,7 @@ options[idx] = val; }); - console.debug($select, options); +// console.debug($select, options); $select.select2(options); } }; @@ -144,13 +144,13 @@ return methods[method].apply(this, args); } - console.debug('ajax submit initialized for', $form); +// console.debug('ajax submit initialized for', $form); // overwrite the originally (HTML)-Submit for the form $form.submit(handlers.onSubmit); // triggers an ajax call for elements with this specific attribute 'data-trigger' // originally it is designed to immidiatly fire an submit event for input elements, after they have changed var elementsThatTriggerASubmit = $form.find('[data-trigger="submit"]'); - console.debug('elements that trigger a submit',elementsThatTriggerASubmit); +// console.debug('elements that trigger a submit',elementsThatTriggerASubmit); elementsThatTriggerASubmit.change(handlers.onChange); }); }; diff --git a/public/js/forms.descriptions.js b/public/js/forms.descriptions.js index <HASH>..<HASH> 100644 --- a/public/js/forms.descriptions.js +++ b/public/js/forms.descriptions.js @@ -22,7 +22,7 @@ $form.find(':input:not([id^="s2id_"]):not(select), .select2-container, .cam-description-toggle, .cam-description-toggle *') .on('mouseover mouseout', $.proxy(this.eventToggle, this)) .focus($.proxy(function(event) { - console.debug('focus'); +// console.debug('focus'); if (this.blurTimeout) { var $desc = this._getDescription($(event.target).attr('id')); if ($desc) { @@ -64,7 +64,7 @@ toggle: function(id, focus) { - console.debug('toggle description', id); + //console.debug('toggle description', id); if (!id) { id = this.focus || '__initial__'; } @@ -115,7 +115,7 @@ select2Toggle: function(event) { - console.debug(event); +// console.debug(event); var $select = $(event.target); var id = $select.attr('id');
[Core] Removes debug messages from javascript files.
yawik_core
train
8de2995f8740b202f85ff483c130d6c15686cf7f
diff --git a/flash_test.go b/flash_test.go index <HASH>..<HASH> 100644 --- a/flash_test.go +++ b/flash_test.go @@ -1,8 +1,12 @@ package buffalo import ( + "io/ioutil" + "os" "testing" + "github.com/gobuffalo/buffalo/render" + "github.com/markbates/willie" "github.com/stretchr/testify/require" ) @@ -71,3 +75,81 @@ func Test_FlashAdd(t *testing.T) { "error": []string{"something", "other"}, }) } + +func Test_FlashRender(t *testing.T) { + tempFolder := os.TempDir() + ioutil.WriteFile(tempFolder+"application.html", []byte("{{yield}}"), 0755) + ioutil.WriteFile(tempFolder+"show.html", []byte(errorsTPL), 0755) + + r := require.New(t) + a := Automatic(Options{}) + rr := render.New(render.Options{ + HTMLLayout: tempFolder + "application.html", + }) + + a.GET("/", func(c Context) error { + c.Flash().Add("errors", "Error AJ set") + c.Flash().Add("errors", "Error DAL set") + + return c.Render(201, rr.HTML(tempFolder+"show.html")) + }) + + w := willie.New(a) + res := w.Request("/").Get() + + r.Contains(res.Body.String(), "Error AJ set") + r.Contains(res.Body.String(), "Error DAL set") +} + +func Test_FlashRenderElse(t *testing.T) { + tempFolder := os.TempDir() + ioutil.WriteFile(tempFolder+"application.html", []byte("{{yield}}"), 0755) + ioutil.WriteFile(tempFolder+"show.html", []byte(errorsTPL), 0755) + + r := require.New(t) + a := Automatic(Options{}) + rr := render.New(render.Options{ + HTMLLayout: tempFolder + "application.html", + }) + + a.GET("/", func(c Context) error { + return c.Render(201, rr.HTML(tempFolder+"show.html")) + }) + + w := willie.New(a) + + res := w.Request("/").Get() + r.NotContains(res.Body.String(), "Flash:") +} + +const errorsTPL = `{{#each flash.Errors as |k flash|}} + Flash: + {{k}}:{{flash}} +{{/each}}` + +func Test_FlashRenderAll(t *testing.T) { + tempFolder := os.TempDir() + ioutil.WriteFile(tempFolder+"application.html", []byte("{{yield}}"), 0755) + ioutil.WriteFile(tempFolder+"show.html", []byte(keyTPL), 0755) + + r := require.New(t) + a := Automatic(Options{}) + rr := render.New(render.Options{ + HTMLLayout: tempFolder + "application.html", + }) + + a.GET("/", func(c Context) error { + c.Flash().Set("something", "something to say!") + return c.Render(201, rr.HTML(tempFolder+"show.html")) + }) + + w := willie.New(a) + res := w.Request("/").Get() + + r.Contains(res.Body.String(), "something to say!") +} + +const keyTPL = `{{#each flash.All as |k flash|}} + Flash: + {{k}}:{{flash}} +{{/each}}`
adding some tests for the rendering of the Errors and All
gobuffalo_buffalo
train
5a3e5d91c1bf1aff548deca292be2c95a304cb11
diff --git a/xlsxworker.flow.js b/xlsxworker.flow.js index <HASH>..<HASH> 100644 --- a/xlsxworker.flow.js +++ b/xlsxworker.flow.js @@ -1,7 +1,7 @@ /* xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */ /*:: declare var XLSX: XLSXModule; */ /*:: declare var self: DedicatedWorkerGlobalScope; */ -importScripts('shim.js'); +importScripts('dist/shim.js'); /* uncomment the next line for encoding support */ importScripts('dist/cpexcel.js'); importScripts('jszip.js'); diff --git a/xlsxworker.js b/xlsxworker.js index <HASH>..<HASH> 100644 --- a/xlsxworker.js +++ b/xlsxworker.js @@ -1,5 +1,5 @@ /* xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */ -importScripts('shim.js'); +importScripts('dist/shim.js'); /* uncomment the next line for encoding support */ importScripts('dist/cpexcel.js'); importScripts('jszip.js');
xlsxworker use dist shim [ci skip]
SheetJS_js-xlsx
train
f6948a4647a59ce3adf26dba11f8bc25ab6a63fb
diff --git a/great_expectations/dataset/pandas_dataset.py b/great_expectations/dataset/pandas_dataset.py index <HASH>..<HASH> 100644 --- a/great_expectations/dataset/pandas_dataset.py +++ b/great_expectations/dataset/pandas_dataset.py @@ -490,23 +490,24 @@ class PandasDataSet(MetaPandasDataSet, pd.DataFrame): @MetaPandasDataSet.column_map_expectation def expect_column_values_to_be_between(self, series, min_value=None, max_value=None): - if min_value != None and max_value != None: - return series.map( - lambda x: (min_value <= x) and (x <= max_value) - ) + def is_between(val): + # TODO Might be worth explicitly defining comparisons between types (for example, between strings and ints). + if type(val) == str: + raise TypeError("cannot compare type 'str'") - elif min_value == None and max_value != None: - return series.map( - lambda x: (x <= max_value) - ) + if min_value != None and max_value != None: + return (min_value <= val) and (val <= max_value) - elif min_value != None and max_value == None: - return series.map( - lambda x: (min_value <= x) - ) + elif min_value == None and max_value != None: + return (val <= max_value) - else: - raise ValueError("min_value and max_value cannot both be None") + elif min_value != None and max_value == None: + return (min_value <= val) + + else: + raise ValueError("min_value and max_value cannot both be None") + + return series.map(is_between) # @DataSet.old_column_expectation # def expect_column_values_to_be_between(self, column, min_value, max_value, mostly=None, suppress_exceptions=False): @@ -917,10 +918,10 @@ class PandasDataSet(MetaPandasDataSet, pd.DataFrame): ), unique_value_count elif min_value == None and max_value != None: - return (x <= max_value), unique_value_count + return (unique_value_count <= max_value), unique_value_count elif min_value != None and max_value == None: - return (min_value <= x), unique_value_count + return (min_value <= unique_value_count), unique_value_count else: raise ValueError("min_value and max_value cannot both be None") diff --git a/great_expectations/dataset/util.py b/great_expectations/dataset/util.py index <HASH>..<HASH> 100644 --- a/great_expectations/dataset/util.py +++ b/great_expectations/dataset/util.py @@ -34,7 +34,14 @@ def ensure_json_serializable(test_dict): test_dict[key] = ensure_json_serializable(test_dict[key]) else: - raise TypeError(key + ' is type ' + type(test_dict[key]).__name__ + ' which cannot be serialized.') + try: + # In Python 2, unicode and long should still be valid. + # This will break in Python 3 and throw the exception instead. + if isinstance(test_dict[key], (long, unicode)): + # No problem to encode json + continue + except: + raise TypeError(key + ' is type ' + type(test_dict[key]).__name__ + ' which cannot be serialized.') return test_dict diff --git a/tests/test_expectation_decorators.py b/tests/test_expectation_decorators.py index <HASH>..<HASH> 100644 --- a/tests/test_expectation_decorators.py +++ b/tests/test_expectation_decorators.py @@ -275,7 +275,7 @@ class TestExpectationDecorators(unittest.TestCase): self.assertEqual( result_obj["exception_traceback"].split('\n')[-2], - "ZeroDivisionError: integer division or modulo by zero", + "ZeroDivisionError: division by zero", ) self.assertEqual( diff --git a/tests/test_pandas_dataset.py b/tests/test_pandas_dataset.py index <HASH>..<HASH> 100644 --- a/tests/test_pandas_dataset.py +++ b/tests/test_pandas_dataset.py @@ -776,7 +776,7 @@ class TestPandasDataset(unittest.TestCase): ] for t in T: - print t + print(t) out = D2.expect_column_values_to_match_regex(**t['in'])#, **t['kwargs']) self.assertEqual(out, t['out']) @@ -1117,8 +1117,14 @@ class TestPandasDataset(unittest.TestCase): for t in T: # print t['in'], t['out'] - out = D.expect_column_unique_value_count_to_be_between(**t['in']) - self.assertEqual(out, t['out']) + if t['in']['min_value'] == None and t['in']['max_value'] == None: + with self.assertRaises(Exception) as e: + D.expect_column_unique_value_count_to_be_between(**t['in']) + self.assertTrue('min_value and max_value cannot both be None', str(e.exception)) + + else: + out = D.expect_column_unique_value_count_to_be_between(**t['in']) + self.assertEqual(out, t['out']) def test_expect_column_unique_proportion_to_be_between(self):
Fixed some errors and failures but many are still present. Trying to develop workarounds between python 2 and 3
great-expectations_great_expectations
train
0ae6144448fef63b8a875ef19800b610e62c84d4
diff --git a/go/protocol/keybase1/extras.go b/go/protocol/keybase1/extras.go index <HASH>..<HASH> 100644 --- a/go/protocol/keybase1/extras.go +++ b/go/protocol/keybase1/extras.go @@ -1905,6 +1905,20 @@ func (s SigChainLocation) LessThanOrEqualTo(s2 SigChainLocation) bool { return s.SeqType == s2.SeqType && s.Seqno <= s2.Seqno } +func (s SigChainLocation) Comparable(s2 SigChainLocation) error { + if s.SeqType != s2.SeqType { + return fmt.Errorf("mismatched seqtypes: %v != %v", s.SeqType, s2.SeqType) + } + return nil +} + +func (s SigChainLocation) Sub1() SigChainLocation { + return SigChainLocation{ + Seqno: s.Seqno - 1, + SeqType: s.SeqType, + } +} + func (r TeamRole) IsAdminOrAbove() bool { return r.IsOrAbove(TeamRole_ADMIN) } diff --git a/go/teams/chain.go b/go/teams/chain.go index <HASH>..<HASH> 100644 --- a/go/teams/chain.go +++ b/go/teams/chain.go @@ -186,7 +186,7 @@ func findRoleDowngrade(points []keybase1.UserLogPoint, role keybase1.TeamRole) * } // AssertWasRoleOrAboveAt asserts that user `uv` had `role` or above on the -// team at the given SigChainLocation `scl`. +// team just after the given SigChainLocation `scl`. // We start at the point given, go backwards until we find a promotion, // then go forwards to make sure there wasn't a demotion before the specified time. // If there was, return a PermissionError. If no adminship was found at all, return a PermissionError. @@ -199,9 +199,15 @@ func (t TeamSigChainState) AssertWasRoleOrAboveAt(uv keybase1.UserVersion, } return NewPermissionError(t.GetID(), uv, msg) } + if scl.Seqno < keybase1.Seqno(0) { + return mkErr("negative seqno: %v", scl.Seqno) + } points := t.inner.UserLog[uv] for i := len(points) - 1; i >= 0; i-- { point := points[i] + if err := point.SigMeta.SigChainLocation.Comparable(scl); err != nil { + return mkErr(err.Error()) + } if point.SigMeta.SigChainLocation.LessThanOrEqualTo(scl) && point.Role.IsOrAbove(role) { // OK great, we found a point with the role in the log that's less than or equal to the given one. // But now we reverse and go forward, and check that it wasn't revoked or downgraded. diff --git a/go/teams/loader2.go b/go/teams/loader2.go index <HASH>..<HASH> 100644 --- a/go/teams/loader2.go +++ b/go/teams/loader2.go @@ -239,9 +239,10 @@ func (l *TeamLoader) verifyLink(ctx context.Context, } } +// Verify that the user had the explicit on-chain role just before this `link`. func (l *TeamLoader) verifyExplicitPermission(ctx context.Context, state *keybase1.TeamData, link *chainLinkUnpacked, uv keybase1.UserVersion, atOrAbove keybase1.TeamRole) error { - return (TeamSigChainState{state.Chain}).AssertWasRoleOrAboveAt(uv, atOrAbove, link.SigChainLocation()) + return (TeamSigChainState{state.Chain}).AssertWasRoleOrAboveAt(uv, atOrAbove, link.SigChainLocation().Sub1()) } // Does not return a full TeamData because it might get a subteam-reader version. @@ -305,7 +306,7 @@ func (l *TeamLoader) verifyAdminPermissions(ctx context.Context, // In the simple case, we don't ask for explicit adminship, so we have to be admins of // the current chain at or before the signature in question. if explicitAdmin == nil { - err := teamChain.AssertWasAdminAt(uv, link.SigChainLocation()) + err := teamChain.AssertWasAdminAt(uv, link.SigChainLocation().Sub1()) return signer, err }
fix role ordering check (#<I>)
keybase_client
train
c178597abf01709628b4e2a7109ec8cd1eb757cf
diff --git a/app/models/no_cms/menus/menu.rb b/app/models/no_cms/menus/menu.rb index <HASH>..<HASH> 100644 --- a/app/models/no_cms/menus/menu.rb +++ b/app/models/no_cms/menus/menu.rb @@ -2,7 +2,7 @@ module NoCms::Menus class Menu < ActiveRecord::Base translates :name - has_many :menu_items, dependent: :destroy + has_many :menu_items, dependent: :destroy, inverse_of: :menu accepts_nested_attributes_for :menu_items, allow_destroy: true validates :name, :uid, presence: true diff --git a/app/models/no_cms/menus/menu_item.rb b/app/models/no_cms/menus/menu_item.rb index <HASH>..<HASH> 100644 --- a/app/models/no_cms/menus/menu_item.rb +++ b/app/models/no_cms/menus/menu_item.rb @@ -6,7 +6,7 @@ module NoCms::Menus acts_as_nested_set - belongs_to :menu + belongs_to :menu, inverse_of: :menu_items belongs_to :menuable, polymorphic: true accepts_nested_attributes_for :children, allow_destroy: true
Created inverse relationships between menu and menu_item
simplelogica_nocms-menus
train
99a8911f3b6c6d96a943453466929db4f94f7564
diff --git a/lib/cborb/decoding/state.rb b/lib/cborb/decoding/state.rb index <HASH>..<HASH> 100644 --- a/lib/cborb/decoding/state.rb +++ b/lib/cborb/decoding/state.rb @@ -71,6 +71,7 @@ module Cborb::Decoding else @stack.pop if @stack.empty? + raise Cborb::InvalidByteSequenceError unless @buffer.eof? @result = ret break else
Raise error if remained unknown data
murakmii_cborb
train
6537ad64d5e4450802cd4c90ba4f03fbeaf15037
diff --git a/spec/shared/optimize_method_behavior.rb b/spec/shared/optimize_method_behavior.rb index <HASH>..<HASH> 100644 --- a/spec/shared/optimize_method_behavior.rb +++ b/spec/shared/optimize_method_behavior.rb @@ -2,8 +2,8 @@ shared_examples_for 'an optimize method' do it_should_behave_like 'an idempotent method' it 'does not optimize further' do - object = subject - object.optimize.should equal(object) + optimized = subject + optimized.optimize.should equal(optimized) end it 'returns an optimized object' do
Minor improvement to variable naming in shared spec
dkubb_axiom
train
e3252b625a972af9982882dff5f2aafcc0c2dd1a
diff --git a/activiti-engine/src/main/java/org/activiti/engine/impl/persistence/entity/VariableScopeImpl.java b/activiti-engine/src/main/java/org/activiti/engine/impl/persistence/entity/VariableScopeImpl.java index <HASH>..<HASH> 100644 --- a/activiti-engine/src/main/java/org/activiti/engine/impl/persistence/entity/VariableScopeImpl.java +++ b/activiti-engine/src/main/java/org/activiti/engine/impl/persistence/entity/VariableScopeImpl.java @@ -74,16 +74,12 @@ public abstract class VariableScopeImpl implements Serializable, VariableScope { return variables; } - private void collectParentVariables(HashMap<String, Object> variables) { + protected Map<String, Object> collectVariables(HashMap<String, Object> variables) { + ensureVariableInstancesInitialized(); VariableScopeImpl parentScope = getParentVariableScope(); if (parentScope!=null) { variables.putAll(parentScope.collectVariables(variables)); } - } - - protected Map<String, Object> collectVariables(HashMap<String, Object> variables) { - ensureVariableInstancesInitialized(); - collectParentVariables(variables); for (VariableInstanceEntity variableInstance: variableInstances.values()) { variables.put(variableInstance.getName(), variableInstance.getValue()); } @@ -145,9 +141,20 @@ public abstract class VariableScopeImpl implements Serializable, VariableScope { return variableInstances.containsKey(variableName); } - public Set<String> getVariableNames() { + protected Set<String> collectVariableNames(Set<String> variableNames) { ensureVariableInstancesInitialized(); - return collectVariables(new HashMap<String, Object>()).keySet(); + VariableScopeImpl parentScope = getParentVariableScope(); + if (parentScope!=null) { + variableNames.addAll(parentScope.collectVariableNames(variableNames)); + } + for (VariableInstanceEntity variableInstance: variableInstances.values()) { + variableNames.add(variableInstance.getName()); + } + return variableNames; + } + + public Set<String> getVariableNames() { + return collectVariableNames(new HashSet<String>()); } public Set<String> getVariableNamesLocal() {
ACT-<I>: Removed duplicated calling of "ensureVariableInstancesInitialized()" and changed the implementation of "getVariableNames()" that in this case the values of the variables will not be loaded
camunda_camunda-bpm-platform
train
e856aba9ab69094787dfd0f6e911f20782069e92
diff --git a/airflow/kubernetes/pod_generator_deprecated.py b/airflow/kubernetes/pod_generator_deprecated.py index <HASH>..<HASH> 100644 --- a/airflow/kubernetes/pod_generator_deprecated.py +++ b/airflow/kubernetes/pod_generator_deprecated.py @@ -178,7 +178,8 @@ class PodGenerator: self.container.command = cmds or [] self.container.args = args or [] - self.container.image_pull_policy = image_pull_policy + if image_pull_policy: + self.container.image_pull_policy = image_pull_policy self.container.ports = ports or [] self.container.resources = resources self.container.volume_mounts = volume_mounts or [] @@ -187,7 +188,8 @@ class PodGenerator: self.spec = k8s.V1PodSpec(containers=[]) self.spec.security_context = security_context self.spec.tolerations = tolerations - self.spec.dns_policy = dnspolicy + if dnspolicy: + self.spec.dns_policy = dnspolicy self.spec.scheduler_name = schedulername self.spec.host_network = hostnetwork self.spec.affinity = affinity @@ -195,7 +197,8 @@ class PodGenerator: self.spec.init_containers = init_containers self.spec.volumes = volumes or [] self.spec.node_selector = node_selectors - self.spec.restart_policy = restart_policy + if restart_policy: + self.spec.restart_policy = restart_policy self.spec.priority_class_name = priority_class_name self.spec.image_pull_secrets = []
Fix handling some None parameters in kubernetes <I> libs. (#<I>) Kubernetes <I>.* is more picky when it comes to values passed to Pod Generator - it requires: * imagePullPolicy * dnsPolicy * restartPolicy to be not None. We are fixing it in the way, that we simply skip setting those if they are None.
apache_airflow
train
eee16fb5d7fef77843c1ed133ef41b291c2f2aea
diff --git a/src/lib/shortcuts.js b/src/lib/shortcuts.js index <HASH>..<HASH> 100644 --- a/src/lib/shortcuts.js +++ b/src/lib/shortcuts.js @@ -1,8 +1,13 @@ /* globals AFRAME */ var Events = require('./Events'); -var shouldCaptureKeyEvent = AFRAME.utils.shouldCaptureKeyEvent; import {removeSelectedEntity, cloneSelectedEntity} from '../actions/entity'; +function shouldCaptureKeyEvent (event) { + if (event.metaKey) { return false; } + return event.target.tagName !== 'INPUT' && + event.target.tagName !== 'TEXTAREA'; +} + module.exports = { onKeyUp: function (event) { if (!shouldCaptureKeyEvent(event)) { return; }
Do not fire hotkey shortcuts dependent on activeElement, but instead allow events if not originating on an input element
aframevr_aframe-inspector
train
701cd768167acdd735b42f39c8efa97466e3d57e
diff --git a/twstock/codes.py b/twstock/codes.py index <HASH>..<HASH> 100644 --- a/twstock/codes.py +++ b/twstock/codes.py @@ -24,7 +24,7 @@ twse = {} def read_csv(path, types): global codes, twse, tpex - with open(path, newline='') as csvfile: + with open(path, newline='', encoding='utf_8') as csvfile: reader = csv.reader(csvfile) csvfile.readline() for row in reader:
Explicitly define 'utf-8' encoding while reading CSV. (#2) * Explicitly define 'utf-8' encoding while reading CSV.
mlouielu_twstock
train
f68196b74abc730caeecdd930d45d681642e06fa
diff --git a/spec/dummy/app/assets/javascripts/application.js b/spec/dummy/app/assets/javascripts/application.js index <HASH>..<HASH> 100644 --- a/spec/dummy/app/assets/javascripts/application.js +++ b/spec/dummy/app/assets/javascripts/application.js @@ -13,8 +13,8 @@ //= require_tree . Renalware.Configuration.init({ - disable_inputs_controlled_by_tissue_typing_feed: true, - disable_inputs_controlled_by_demographics_feed: true + disable_inputs_controlled_by_tissue_typing_feed: false, + disable_inputs_controlled_by_demographics_feed: false }); // Running integration tests, we turn off animations to reduce the risk of timing errors.
Enabled feed inputs in dev
airslie_renalware-core
train
233112fc0603ba6719717cef39f32e79af19a656
diff --git a/openquake/server/db/actions.py b/openquake/server/db/actions.py index <HASH>..<HASH> 100644 --- a/openquake/server/db/actions.py +++ b/openquake/server/db/actions.py @@ -28,13 +28,11 @@ from openquake.server.db.schema.upgrades import upgrader from openquake.server.db import upgrade_manager from openquake.server.dbapi import NotFound -JOB_TYPE = '''CASE -WHEN calculation_mode LIKE '%risk' -OR calculation_mode LIKE '%bcr' -OR calculation_mode LIKE '%damage' -THEN 'risk' -ELSE 'hazard' -END AS job_type +CALCULATION_MODE = '''CASE +WHEN calculation_mode LIKE '' +THEN 'undefined' +ELSE calculation_mode +END AS calculation_mode ''' @@ -160,7 +158,7 @@ def get_calc_id(db, datadir, job_id=None): return max(calc_id, job_id) -def list_calculations(db, job_type, user_name): +def list_calculations(db, calculation_mode, user_name): """ Yield a summary of past calculations. @@ -169,8 +167,8 @@ def list_calculations(db, job_type, user_name): :param user_name: an user name """ jobs = db('SELECT *, %s FROM job WHERE user_name=?x ' - 'AND job_type=?x ORDER BY start_time' % JOB_TYPE, - user_name, job_type) + 'ORDER BY start_time', + user_name, calculation_mode) if len(jobs) == 0: yield 'None' @@ -458,8 +456,8 @@ def get_calcs(db, request_get_dict, user_name, user_acl_on=False, id=None): if id is not None: filterdict['id'] = id - if 'job_type' in request_get_dict: - filterdict['job_type'] = request_get_dict.get('job_type') + if 'calculation_mode' in request_get_dict: + filterdict['calculation_mode'] = request_get_dict.get('calculation_mode') if 'is_running' in request_get_dict: is_running = request_get_dict.get('is_running') @@ -481,11 +479,13 @@ def get_calcs(db, request_get_dict, user_name, user_acl_on=False, id=None): time_filter = 1 jobs = db('SELECT *, %s FROM job WHERE ?A AND %s ORDER BY id DESC LIMIT %d' - % (JOB_TYPE, time_filter, limit), filterdict) - return [(job.id, job.user_name, job.status, job.job_type, + % (CALCULATION_MODE, time_filter, limit), filterdict) + return [(job.id, job.user_name, job.status, job.calculation_mode, job.is_running, job.description) for job in jobs] + + def set_relevant(db, job_id, flag): """ Set the `relevant` field of the given calculation record.
Changed variable job_type to calculation_mode in some function, changed case, changed query in def list_calculations, added calculation_mode in response_data, changed position calculation_mode and status {skip CI]
gem_oq-engine
train
66f0259f538e79aeeb4bd97ff650f99114bd42dc
diff --git a/yass/__about__.py b/yass/__about__.py index <HASH>..<HASH> 100644 --- a/yass/__about__.py +++ b/yass/__about__.py @@ -16,7 +16,7 @@ __all__ = [ ] __title__ = "Yass" -__version__ = "1.0.3" +__version__ = "1.0.4" __summary__ = "Yet Another Static Site (generator) for the common folks! " __uri__ = "https://github.com/mardix/yass" __author__ = "Mardix" diff --git a/yass/yass.py b/yass/yass.py index <HASH>..<HASH> 100644 --- a/yass/yass.py +++ b/yass/yass.py @@ -70,10 +70,12 @@ class Yass(object): "title": "", # The title of the page "markup": None, # The markup to use. ie: md | jade | html (default) "slug": None, # The pretty url new name of the file. A file with the same name will be created - "url": "", # This will be added when processed + "url": "", # This will be added when processed "description": "", # Page description "pretty_url": True, # By default, all url will be pretty (search engine friendly) Set to False to keep the .html - "meta": {} + "meta": {}, + "layout": None, # The layout for the page + "template": None # The page template. } tpl_env = None _templates = {} @@ -300,6 +302,7 @@ class Yass(object): context={"page": meta}, content=content, markup=meta.get("markup"), + template=meta.get("template"), layout=meta.get("layout") or self.default_layout )
Added template option in page, to allow dynamic update from template
mardix_Yass
train
73563fd13d1c5b17ec4de790c45c98222602d9c9
diff --git a/lib/firestore.js b/lib/firestore.js index <HASH>..<HASH> 100644 --- a/lib/firestore.js +++ b/lib/firestore.js @@ -38,10 +38,14 @@ class Firestore { this.buildQuery(filter, query1, query => { query.get().then(snapshot => { if (snapshot.exists) { - response.push(snapshot.data()); + let completeItem = snapshot.data(); + completeItem.id = snapshot.id; + response.push(completeItem); } else { snapshot.forEach(item => { - response.push(item.data()); + let completeItem = item.data(); + completeItem.id = item.id; + response.push(completeItem); }); } }).then(() => callback(null, response)).catch(err => callback(err)); diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "loopback-connector-firestore", - "version": "1.0.5", + "version": "1.1.1", "description": "Firebase Firestore connector for the LoopBack framework.", "main": "index.js", "scripts": { diff --git a/test/model.test.js b/test/model.test.js index <HASH>..<HASH> 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -16,7 +16,7 @@ describe('Firestore collection', function() { age: Number, }); - var customerObj; + var customer1, customer2; it('Should create a document', function(done) { Customer.create({ @@ -26,7 +26,7 @@ describe('Firestore collection', function() { ], age: 26, }, function(err, customer) { - customerObj = customer; + customer1 = customer; customer.should.have.property('name', 'Dyaa Eldin'); customer.should.have.property('emails').with.lengthOf(2); done(err, customer); @@ -41,6 +41,7 @@ describe('Firestore collection', function() { ], age: 27, }, function(err, customer) { + customer2 = customer; customer.should.have.property('name', 'Cristian Bullokles'); customer.should.have.property('emails').with.lengthOf(1); done(err, customer); @@ -48,16 +49,19 @@ describe('Firestore collection', function() { }); it('Should find a document by id', function(done) { - Customer.find({where: {id: customerObj.id}}, function(err, customer) { + Customer.find({where: {id: customer1.id}}, function(err, customer) { customer.should.be.array; // eslint-disable-line no-unused-expressions + customer.should.containDeep([{id: customer1.id}]); done(err, customer); }); }); it('Should get object properties', function(done) { - Customer.find({where: {id: customerObj.id}}, function(err, customer) { + Customer.find({where: {id: customer1.id}}, function(err, customer) { customer.should.have.length(1); - customer.should.containDeep([{name: 'Dyaa Eldin'}]); + customer.should.containDeep([{name: customer1.name}]); + customer.should.containDeep([{id: customer1.id}]); + done(err, customer); }); }); @@ -65,7 +69,8 @@ describe('Firestore collection', function() { it('Should get all documents', function(done) { Customer.all(function(err, customer) { customer.should.have.length(2); - customer.should.containDeep([{name: 'Cristian Bullokles'}]); + customer.should.containDeep([{id: customer1.id}]); + customer.should.containDeep([{id: customer2.id}]); done(err, customer); }); }); @@ -74,27 +79,29 @@ describe('Firestore collection', function() { Customer.find({where: {age: {'lt': 28}}}, function(err, customer) { customer.should.have.length(2); customer.should.containDeep([{age: 26}]); + customer.should.containDeep([{id: customer1.id}]); done(err, customer); }); }); it('Should find a document by age equals to 26', function(done) { - Customer.find({where: {age: 27}}, function(err, customer) { + Customer.find({where: {age: customer1.age}}, function(err, customer) { customer.should.have.length(1); - customer.should.containDeep([{age: 27}]); + customer.should.containDeep([{age: customer1.age}]); + customer.should.containDeep([{id: customer1.id}]); done(err, customer); }); }); it('Should Replace attributes for a model instance', function(done) { - Customer.replaceById(customerObj.id, {emails: ['bar@example.com']}, {validate: true}, function(err, customer) { + Customer.replaceById(customer1.id, {emails: ['bar@example.com']}, {validate: true}, function(err, customer) { customer.should.have.property('emails').with.lengthOf(1); done(err, customer); }); }); it('Should delete a document', function(done) { - Customer.destroyAll({id: customerObj.id}, function(err, customer) { + Customer.destroyAll({id: customer1.id}, function(err, customer) { done(err, customer); }); });
Added Object.id as part of response
dyaa_loopback-connector-firestore
train
e4612f9045708bd41fa2f81f9c602baf3d79b5e7
diff --git a/lib/clearbit/logo.rb b/lib/clearbit/logo.rb index <HASH>..<HASH> 100644 --- a/lib/clearbit/logo.rb +++ b/lib/clearbit/logo.rb @@ -20,7 +20,7 @@ module Clearbit encoded_params = URI.encode_www_form(params) if domain = values.delete(:domain) - raise ArgumentError, 'Invalid domain' unless domain =~ /^[a-z0-9\-]+([\.]{1}[a-z0-9\-]+)*\.[a-z]{2,5}$/ + raise ArgumentError, 'Invalid domain' unless domain =~ /^[a-z0-9-]+(\.[a-z0-9-]+)*\.[a-z]{2,}$/ if encoded_params.empty? "#{ENDPOINT}/#{domain}" else diff --git a/spec/lib/clearbit/logo_spec.rb b/spec/lib/clearbit/logo_spec.rb index <HASH>..<HASH> 100644 --- a/spec/lib/clearbit/logo_spec.rb +++ b/spec/lib/clearbit/logo_spec.rb @@ -3,38 +3,41 @@ require 'spec_helper' describe Clearbit::Logo do context 'domain validation' do - def check_valid_domain(domain) - expect { - Clearbit::Logo.url({ - domain: domain - }) - }.not_to raise_error - end - def check_invalid_domain(domain) - expect { - Clearbit::Logo.url({ - domain: domain - }) - }.to raise_error(ArgumentError) end it 'passes for simple domains' do - check_valid_domain('clearbit.com') + expect { + Clearbit::Logo.url(domain: 'clearbit.com') + }.to_not raise_error end it 'passes for dashed domains' do - check_valid_domain('clear-bit.com') - check_valid_domain('clear--bit.com.uk') + expect { + Clearbit::Logo.url(domain: 'clear-bit.com') + }.to_not raise_error end it 'passes for multi-dot TLDs' do - check_valid_domain('bbc.co.uk') - check_valid_domain('clear-bit.co.uk') + expect { + Clearbit::Logo.url(domain: 'bbc.co.uk') + }.to_not raise_error + + expect { + Clearbit::Logo.url(domain: 'clear-bit.co.uk') + }.to_not raise_error + end + + it 'passes for new-style tlds' do + expect { + Clearbit::Logo.url(domain: 'clearbit.museum') + }.to_not raise_error end it 'fails for invalid urls' do - check_invalid_domain('clearbit.verylongtld') + expect { + Clearbit::Logo.url(domain: 'clearbit') + }.to raise_error(ArgumentError) end end end
Amend regex to be simpler and support new style tlds.
clearbit_clearbit-ruby
train
f36de8a9bb178d406b89e6d68107f24967c95d02
diff --git a/src/Database/Query.php b/src/Database/Query.php index <HASH>..<HASH> 100644 --- a/src/Database/Query.php +++ b/src/Database/Query.php @@ -1605,7 +1605,7 @@ class Query implements ExpressionInterface, IteratorAggregate */ public function func() { - if (empty($this->_functionsBuilder)) { + if ($this->_functionsBuilder === null) { $this->_functionsBuilder = new FunctionsBuilder(); } @@ -1622,7 +1622,7 @@ class Query implements ExpressionInterface, IteratorAggregate */ public function getIterator() { - if (empty($this->_iterator) || $this->_dirty) { + if ($this->_iterator === null || $this->_dirty) { $this->_iterator = $this->execute(); } diff --git a/src/Event/EventDispatcherTrait.php b/src/Event/EventDispatcherTrait.php index <HASH>..<HASH> 100644 --- a/src/Event/EventDispatcherTrait.php +++ b/src/Event/EventDispatcherTrait.php @@ -48,7 +48,7 @@ trait EventDispatcherTrait { if ($eventManager !== null) { $this->_eventManager = $eventManager; - } elseif (empty($this->_eventManager)) { + } elseif ($this->_eventManager === null) { $this->_eventManager = new EventManager(); } diff --git a/src/Routing/Route/Route.php b/src/Routing/Route/Route.php index <HASH>..<HASH> 100644 --- a/src/Routing/Route/Route.php +++ b/src/Routing/Route/Route.php @@ -52,7 +52,7 @@ class Route /** * The routes template string. * - * @var string + * @var string|null */ public $template = null; @@ -60,21 +60,21 @@ class Route * Is this route a greedy route? Greedy routes have a `/*` in their * template * - * @var string + * @var bool */ protected $_greedy = false; /** * The compiled route regular expression * - * @var string + * @var string|null */ protected $_compiledRoute = null; /** * The name for a route. Fetch with Route::getName(); * - * @var string + * @var string|null */ protected $_name = null; diff --git a/src/TestSuite/IntegrationTestCase.php b/src/TestSuite/IntegrationTestCase.php index <HASH>..<HASH> 100644 --- a/src/TestSuite/IntegrationTestCase.php +++ b/src/TestSuite/IntegrationTestCase.php @@ -945,7 +945,7 @@ abstract class IntegrationTestCase extends TestCase */ public function assertCookie($expected, $name, $message = '') { - if (empty($this->_response)) { + if (!$this->_response) { $this->fail('Not response set, cannot assert cookies.'); } $result = $this->_response->cookie($name); @@ -990,7 +990,7 @@ abstract class IntegrationTestCase extends TestCase */ public function assertCookieEncrypted($expected, $name, $encrypt = 'aes', $key = null, $message = '') { - if (empty($this->_response)) { + if (!$this->_response) { $this->fail('No response set, cannot assert cookies.'); } $result = $this->_response->cookie($name); diff --git a/src/TestSuite/TestCase.php b/src/TestSuite/TestCase.php index <HASH>..<HASH> 100644 --- a/src/TestSuite/TestCase.php +++ b/src/TestSuite/TestCase.php @@ -35,7 +35,7 @@ abstract class TestCase extends PHPUnit_Framework_TestCase /** * The class responsible for managing the creation, loading and removing of fixtures * - * @var \Cake\TestSuite\Fixture\FixtureManager + * @var \Cake\TestSuite\Fixture\FixtureManager|null */ public $fixtureManager = null; @@ -134,7 +134,7 @@ abstract class TestCase extends PHPUnit_Framework_TestCase */ public function loadFixtures() { - if (empty($this->fixtureManager)) { + if ($this->fixtureManager === null) { throw new Exception('No fixture manager to load the test fixture'); } $args = func_get_args(); diff --git a/src/View/View.php b/src/View/View.php index <HASH>..<HASH> 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -334,7 +334,7 @@ class View implements EventDispatcherInterface $this->eventManager($eventManager); $this->request = $request ?: Router::getRequest(true); $this->response = $response ?: new Response(); - if (empty($this->request)) { + if ($this->request === null) { $this->request = new ServerRequest([ 'base' => '', 'url' => '',
Remove some cloaking for stricter null checks and fix a doc block.
cakephp_cakephp
train
109861e8f17e51eb3025ddd88645445dc916ba16
diff --git a/holoviews/core/element.py b/holoviews/core/element.py index <HASH>..<HASH> 100644 --- a/holoviews/core/element.py +++ b/holoviews/core/element.py @@ -495,11 +495,13 @@ class HoloMap(UniformNdMapping): data_type = (ViewableElement, NdMapping, Layout) - def overlay(self, dimensions, **kwargs): + def overlay(self, dimensions=None, **kwargs): """ Splits the UniformNdMapping along a specified number of dimensions and overlays items in the split out Maps. """ + if dimensions is None: + dimensions = self.kdims dimensions = self._valid_dimensions(dimensions) if len(dimensions) == self.ndims: with item_check(False): @@ -510,11 +512,13 @@ class HoloMap(UniformNdMapping): return self.groupby(dims, group_type=NdOverlay, **kwargs) - def grid(self, dimensions, **kwargs): + def grid(self, dimensions=None, **kwargs): """ GridSpace takes a list of one or two dimensions, and lays out the containing Views along these axes in a GridSpace. """ + if dimensions is None: + dimensions = self.kdims dimensions = self._valid_dimensions(dimensions) if len(dimensions) == self.ndims: with item_check(False): @@ -522,11 +526,13 @@ class HoloMap(UniformNdMapping): return self.groupby(dimensions, container_type=GridSpace, **kwargs) - def layout(self, dimensions, **kwargs): + def layout(self, dimensions=None, **kwargs): """ GridSpace takes a list of one or two dimensions, and lays out the containing Views along these axes in a GridSpace. """ + if dimensions is None: + dimensions = self.kdims dimensions = self._valid_dimensions(dimensions) if len(dimensions) == self.ndims: with item_check(False):
Layout, overlay and grid of a HoloMap now reduces all key dimensions by default.
pyviz_holoviews
train
ba20b43ae2fb78a478ea2f3ea0ea01d0f837e17f
diff --git a/vendor/k8s.io/kubernetes/cmd/kubelet/app/server.go b/vendor/k8s.io/kubernetes/cmd/kubelet/app/server.go index <HASH>..<HASH> 100644 --- a/vendor/k8s.io/kubernetes/cmd/kubelet/app/server.go +++ b/vendor/k8s.io/kubernetes/cmd/kubelet/app/server.go @@ -1125,9 +1125,7 @@ func RunKubelet(kubeServer *options.KubeletServer, kubeDeps *kubelet.Dependencie func startKubelet(k kubelet.Bootstrap, podCfg *config.PodConfig, kubeCfg *kubeletconfiginternal.KubeletConfiguration, kubeDeps *kubelet.Dependencies, enableCAdvisorJSONEndpoints, enableServer bool) { // start the kubelet - go wait.Until(func() { - k.Run(podCfg.Updates()) - }, 0, wait.NeverStop) + go k.Run(podCfg.Updates()) // start the kubelet server if enableServer {
UPSTREAM: <I>: Remove wait.Until for running Kubelet Bootstrap
openshift_origin
train
bde2bfe4e23de447c6fa7b2de760e2282accdd2f
diff --git a/build_package.py b/build_package.py index <HASH>..<HASH> 100755 --- a/build_package.py +++ b/build_package.py @@ -26,7 +26,8 @@ SUPPORTED_RELEASES = """\ 14.04 trusty LTS 14.10 utopic HISTORIC 15.04 vivid SUPPORTED -15.10 wily DEVEL +15.10 wily SUPPORTED +16.04 xenial DEVEL """ diff --git a/tests/test_build_package.py b/tests/test_build_package.py index <HASH>..<HASH> 100644 --- a/tests/test_build_package.py +++ b/tests/test_build_package.py @@ -52,7 +52,7 @@ class JujuSeriesTestCase(unittest.TestCase): def test_get_living_names(self): juju_series = _JujuSeries() self.assertEqual( - ['precise', 'trusty', 'vivid', 'wily'], + ['precise', 'trusty', 'vivid', 'wily', 'xenial'], juju_series.get_living_names()) def test_get_version(self):
Enable xenial package building.
juju_juju
train
67af9519e323932d46ce7bd7e97ff93c41cd8395
diff --git a/src/main/java/water/api/Tutorials.java b/src/main/java/water/api/Tutorials.java index <HASH>..<HASH> 100644 --- a/src/main/java/water/api/Tutorials.java +++ b/src/main/java/water/api/Tutorials.java @@ -39,7 +39,7 @@ public class Tutorials extends HTMLOnlyRequest { + "<div class='span2 col'>" + "<h2>K-Means</h2>" - + "<p>Perform cluster analysis with H<sub>2</sub>O. K-means is a scalable clustering algorithm for unsupervised learning on big data.</p>" + + "<p>Perform clustering analysis with H<sub>2</sub>O. K-means is a highly scalable clustering algorithm for unsupervised learning on big data.</p>" + "<a href='/TutorialKMeans.html' class='btn btn-primary'>Try it!</a>" + "</div>"
Cosmetics for Tutorials page (to align).
h2oai_h2o-2
train
3b89449dc34e2e6bee10ce34c95728a2eb297bf4
diff --git a/src/oidcmsg/time_util.py b/src/oidcmsg/time_util.py index <HASH>..<HASH> 100644 --- a/src/oidcmsg/time_util.py +++ b/src/oidcmsg/time_util.py @@ -26,6 +26,7 @@ import sys import time from datetime import datetime from datetime import timedelta +from datetime import timezone TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ" TIME_FORMAT_WITH_FRAGMENT = re.compile("^(\d{4,4}-\d{2,2}-\d{2,2}T\d{2,2}:\d{2,2}:\d{2,2})\.\d*Z$") @@ -351,7 +352,7 @@ def later_than(after, before): def utc_time_sans_frac(): - now_timestampt = int(datetime.utcnow().timestamp()) + now_timestampt = int(datetime.now(timezone.utc).timestamp()) return now_timestampt
fix: utcnow timestamp
openid_JWTConnect-Python-OidcMsg
train
85207f0765b8303d50be37b3517acd375148e697
diff --git a/umap/settings/base.py b/umap/settings/base.py index <HASH>..<HASH> 100644 --- a/umap/settings/base.py +++ b/umap/settings/base.py @@ -30,7 +30,6 @@ SECRET_KEY = 'j6fly6aomgo6!3_$v#9kvhw-%wgs1@1l6x+4nr73tmn40=&amp;_@&amp;' INSTALLED_APPS = ( 'leaflet_storage', - 'endless_pagination', 'umap', 'sesql', 'compressor',
Remove endless_pagination from INSTALLED_APPS
umap-project_umap
train
c089b542268f78c7451567fa76fa5223972eae21
diff --git a/ChangeLog b/ChangeLog index <HASH>..<HASH> 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +2020 Apr 07 Sergey Satskiy <sergey.satskiy@gmail.com> + +* Release 3.2.1 +* Fix: incorrect python version spec in setup.py + 2020 Apr 06 Sergey Satskiy <sergey.satskiy@gmail.com> * Release 3.2.0 diff --git a/cdmpyparserversion.py b/cdmpyparserversion.py index <HASH>..<HASH> 100644 --- a/cdmpyparserversion.py +++ b/cdmpyparserversion.py @@ -1 +1 @@ -version = '3.2.0' +version = '3.2.1' diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -61,7 +61,7 @@ except Exception as exc: # dependencies setup(name='cdmpyparser', description=description, - python_requires='>=3.5, <=3.8', + python_requires='>=3.5, <3.9', long_description=long_description, version=version, author='Sergey Satskiy',
Release <I>: fixed python version requirements
SergeySatskiy_cdm-pythonparser
train
a593ee5fb4a2320163a9a0cfefd22538e2a9e6b6
diff --git a/lib/rollbar/encoding.rb b/lib/rollbar/encoding.rb index <HASH>..<HASH> 100644 --- a/lib/rollbar/encoding.rb +++ b/lib/rollbar/encoding.rb @@ -7,7 +7,6 @@ module Rollbar def self.encode(object) can_be_encoded = object.is_a?(Symbol) || object.is_a?(String) - return if object.frozen? return object unless can_be_encoded encoding_class.new(object).encode diff --git a/lib/rollbar/encoding/encoder.rb b/lib/rollbar/encoding/encoder.rb index <HASH>..<HASH> 100644 --- a/lib/rollbar/encoding/encoder.rb +++ b/lib/rollbar/encoding/encoder.rb @@ -30,6 +30,8 @@ module Rollbar private def force_encoding(value) + return value if value.frozen? + value.force_encoding(detect_encoding(value)) if value.encoding == ::Encoding::UTF_8 value
Fix returning of frozen strings. This should happen when we are trying to force encoding. So, if it's frozen, we don't force anything and just encode it.
rollbar_rollbar-gem
train
f15c62e602f9f6588792b082ee6e2e226386b600
diff --git a/lib/mincer/engines/stylus_engine.js b/lib/mincer/engines/stylus_engine.js index <HASH>..<HASH> 100644 --- a/lib/mincer/engines/stylus_engine.js +++ b/lib/mincer/engines/stylus_engine.js @@ -115,9 +115,10 @@ StylusEngine.prototype.evaluate = function (context, locals, callback) { o[k] = (this[i] || {}).val; }, arguments); - if (this && (!'context' in this)) { + if (!('context' in this)) { this.context = context; } + return func.call(this, o.a, o.b, o.c, o.d, o.e, o.f, o.g, o.h); }); });
Small codestyle improvement `this` is always "true"ish, so no need to test it.
nodeca_mincer
train
7fb201359f28a7ea9daec54d61589e890ec163cc
diff --git a/jodd-json/src/main/java/jodd/json/JsonParser.java b/jodd-json/src/main/java/jodd/json/JsonParser.java index <HASH>..<HASH> 100644 --- a/jodd-json/src/main/java/jodd/json/JsonParser.java +++ b/jodd-json/src/main/java/jodd/json/JsonParser.java @@ -885,10 +885,13 @@ public class JsonParser extends JsonParserBase { // *** add to map if (isTargetRealTypeMap) { path.push(VALUES, key); + + valueType = replaceWithMappedTypeForPath(valueType); } else { path.push(key); } + value = parseValue(valueType, null, null); path.pop(); diff --git a/jodd-json/src/test/java/jodd/json/AnnotationTest.java b/jodd-json/src/test/java/jodd/json/AnnotationTest.java index <HASH>..<HASH> 100644 --- a/jodd-json/src/test/java/jodd/json/AnnotationTest.java +++ b/jodd-json/src/test/java/jodd/json/AnnotationTest.java @@ -125,6 +125,37 @@ public class AnnotationTest { } @Test + public void testCustomMap() { + String json = "{\"userId\" : 123, \"name\": 456}"; + + Map<String, Integer> map = JsonParser.create().parse(json); + assertEquals(2, map.size()); + assertEquals(Integer.valueOf(123), map.get("userId")); + assertEquals(Integer.valueOf(456), map.get("name")); + + Map<String, Long> map2 = JsonParser + .create() + .map(JsonParser.VALUES, Long.class) + .parse(json); + + assertEquals(2, map2.size()); + assertEquals(Long.valueOf(123), map2.get("userId")); + assertEquals(Long.valueOf(456), map2.get("name")); + + + json = "{\"123\" : \"hey\", \"456\": \"man\"}"; + + Map<Long, String> map3 = JsonParser + .create() + .map(JsonParser.KEYS, Long.class) + .parse(json); + + assertEquals(2, map3.size()); + assertEquals("hey", map3.get(Long.valueOf(123))); + assertEquals("man", map3.get(Long.valueOf(456))); + } + + @Test public void testClassInArrayOrMapParse() { String json = "{\"userId\" : 123, \"name\":\"Joe\"}"; diff --git a/jodd-json/src/test/java/jodd/json/JSONDeserializerTest.java b/jodd-json/src/test/java/jodd/json/JSONDeserializerTest.java index <HASH>..<HASH> 100644 --- a/jodd-json/src/test/java/jodd/json/JSONDeserializerTest.java +++ b/jodd-json/src/test/java/jodd/json/JSONDeserializerTest.java @@ -218,6 +218,7 @@ public class JSONDeserializerTest { .map("secretIdentity", SecretIdentity.class) .parse(json, Hero.class); + assertEquals("Fortress of Solitude", jsonSuperMan.getLair().getName()); assertHeroHasSuperPowers(jsonSuperMan); }
Fixes JSON issue - special keys when map is serialized and mapping is set.
oblac_jodd
train
6142275d78c1716586f0b778c54baf132a99f24e
diff --git a/tests/Saxulum/Tests/DoctrineMongoDbOdm/Provider/DoctrineMongoDbOdmProviderTest.php b/tests/Saxulum/Tests/DoctrineMongoDbOdm/Provider/DoctrineMongoDbOdmProviderTest.php index <HASH>..<HASH> 100644 --- a/tests/Saxulum/Tests/DoctrineMongoDbOdm/Provider/DoctrineMongoDbOdmProviderTest.php +++ b/tests/Saxulum/Tests/DoctrineMongoDbOdm/Provider/DoctrineMongoDbOdmProviderTest.php @@ -114,7 +114,7 @@ class DoctrineMongoDbOdmProviderTest extends \PHPUnit_Framework_TestCase /** * Test hydrator configuration (defaults) */ - public function testProxyConfigurationDefaults() + public function testHydratorConfigurationDefaults() { $container = $this->createMockDefaultApp(); @@ -129,16 +129,16 @@ class DoctrineMongoDbOdmProviderTest extends \PHPUnit_Framework_TestCase /** * Test hydrator configuration (defined) */ - public function testProxyConfigurationDefined() + public function testHydratorConfigurationDefined() { $container = $this->createMockDefaultApp(); $doctrineOrmServiceProvider = new DoctrineMongoDbOdmProvider; $doctrineOrmServiceProvider->register($container); - $container['mongodbodm.proxies_dir'] = '/path/to/hydrators'; - $container['mongodbodm.proxies_namespace'] = 'TestDoctrineMongoDbOdmHydratorsNamespace'; - $container['mongodbodm.auto_generate_proxies'] = false; + $container['mongodbodm.hydrator_dir'] = '/path/to/hydrators'; + $container['mongodbodm.hydrator_namespace'] = 'TestDoctrineMongoDbOdmHydratorsNamespace'; + $container['mongodbodm.auto_generate_hydrator'] = false; $this->assertEquals('/path/to/hydrators', $container['mongodbodm.dm.config']->getHydratorDir()); $this->assertEquals('TestDoctrineMongoDbOdmHydratorsNamespace', $container['mongodbodm.dm.config']->getHydratorNamespace());
Fixes for the config unit tests
saxulum_saxulum-doctrine-mongodb-odm-provider
train
a2f5e0c596179f971e7cd3221d6b73cd615a8c7f
diff --git a/qjobs.js b/qjobs.js index <HASH>..<HASH> 100644 --- a/qjobs.js +++ b/qjobs.js @@ -112,4 +112,4 @@ module.exports = new EventEmitter(); module.exports.run = run; module.exports.add = add; module.exports.pause = pause; - +module.exports.setConcurrency = setConcurrency;
oups .. forgot to add setConcurrency in module export
franck34_qjobs
train
71c004396cb891b79be3af88a5036efbcf8beac8
diff --git a/lib/jacoco/gem_version.rb b/lib/jacoco/gem_version.rb index <HASH>..<HASH> 100644 --- a/lib/jacoco/gem_version.rb +++ b/lib/jacoco/gem_version.rb @@ -1,3 +1,3 @@ module Jacoco - VERSION = '0.1.0'.freeze + VERSION = '0.1.1'.freeze end diff --git a/lib/jacoco/plugin.rb b/lib/jacoco/plugin.rb index <HASH>..<HASH> 100644 --- a/lib/jacoco/plugin.rb +++ b/lib/jacoco/plugin.rb @@ -53,14 +53,10 @@ module Danger report_markdown = "### JaCoCO Code Coverage #{total_covered[:covered]}% #{total_covered[:status]}\n" report_markdown << "| Class | Covered | Meta | Status |\n" report_markdown << "|:---:|:---:|:---:|:---:|\n" - markdown_class(parser, report_markdown) + class_coverage_above_minimum = markdown_class(parser, report_markdown) markdown(report_markdown) - return if total_covered[:covered] >= minimum_project_coverage_percentage - - # fail danger if total coveraged is smaller than minimum_project_coverage_percentage - covered = total_covered[:covered] - raise("Total coverage of #{covered}%. Improve this to as least #{minimum_project_coverage_percentage} %") + report_fails(class_coverage_above_minimum, total_covered) end # Select modified and added files in this PR @@ -113,12 +109,30 @@ module Danger private + # rubocop:disable Style/SignalException + def report_fails(class_coverage_above_minimum, total_covered) + if total_covered[:covered] < minimum_project_coverage_percentage + # fail danger if total coverage is smaller than minimum_project_coverage_percentage + covered = total_covered[:covered] + fail("Total coverage of #{covered}%. Improve this to at least #{minimum_project_coverage_percentage}%") + end + + return if class_coverage_above_minimum + + fail("Class coverage is below minimum. Improve to at least #{minimum_class_coverage_percentage}%") + end + def markdown_class(parser, report_markdown) + class_coverage_above_minimum = true parser.classes.each do |jacoco_class| # Check metrics for each classes rp = report_class(jacoco_class) ln = "| `#{jacoco_class.name}` | #{rp[:covered]}% | #{minimum_class_coverage_percentage}% | #{rp[:status]} |\n" report_markdown << ln + + class_coverage_above_minimum &&= rp[:covered] >= minimum_class_coverage_percentage end + + class_coverage_above_minimum end end end
Fix fail not reported when class coverage is below minimum
Malinskiy_danger-jacoco
train
ecf3277ba9abf177dda25a547d943ab0342fb3be
diff --git a/werobot/testing.py b/werobot/testing.py index <HASH>..<HASH> 100644 --- a/werobot/testing.py +++ b/werobot/testing.py @@ -13,13 +13,9 @@ _kwargs = { class WeTest(object): def __init__(self, app): - if not isinstance(app, WeRoBot): - raise TypeError self._app = app def send(self, message): - if not isinstance(message, WeChatMessage): - raise TypeError return self._app.get_reply(message) def send_xml(self, xml):
drop instance check in werobot.testing
offu_WeRoBot
train
cd86bc2c33c57bec47a6f7f4e8e362dc4d7499a6
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ else: data_files = None setup(name = 'Rtree', - version = '0.5.0', + version = '0.6.0', description = 'R-Tree spatial index for Python GIS', license = 'LGPL', keywords = 'gis spatial index',
bump the version number so it doesn't clash with what's on PyPI
Toblerity_rtree
train
d7f913ca8394b1cd23cda8adc05d023dcae2c764
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -271,8 +271,8 @@ def get_version_info(): # If this is a release or another kind of source distribution of PyCBC except: - version = '1.7.9' - release = 'True' + version = '1.8.0dev' + release = 'False' date = hash = branch = tag = author = committer = status = builder = build_date = ''
Set back to development (#<I>)
gwastro_pycbc
train
b7d1f44364d6d35b158df660825d2741ee9c60bb
diff --git a/liquibase-core/src/main/java/liquibase/datatype/core/TimestampType.java b/liquibase-core/src/main/java/liquibase/datatype/core/TimestampType.java index <HASH>..<HASH> 100644 --- a/liquibase-core/src/main/java/liquibase/datatype/core/TimestampType.java +++ b/liquibase-core/src/main/java/liquibase/datatype/core/TimestampType.java @@ -1,5 +1,7 @@ package liquibase.datatype.core; +import liquibase.configuration.GlobalConfiguration; +import liquibase.configuration.LiquibaseConfiguration; import liquibase.database.Database; import liquibase.database.core.MSSQLDatabase; import liquibase.database.core.MySQLDatabase; @@ -21,7 +23,11 @@ public class TimestampType extends DateTimeType { return super.toDatabaseDataType(database); } if (database instanceof MSSQLDatabase) { - return new DatabaseDataType(database.escapeDataTypeName("datetime")); + if (!LiquibaseConfiguration.getInstance().getProperty(GlobalConfiguration.class, GlobalConfiguration.CONVERT_DATA_TYPES).getValue(Boolean.class) && originalDefinition.toLowerCase().startsWith("timestamp")) { + return new DatabaseDataType(database.escapeDataTypeName("TIMESTAMP")); + } + + return new DatabaseDataType(database.escapeDataTypeName("DATETIME")); } return super.toDatabaseDataType(database); }
CORE-<I> MSSQL handling timestamp according to sql standard, not sqlserver usage
liquibase_liquibase
train
d373becbf05dee63e6555d9853c37f5753f376f4
diff --git a/faker/providers/address/pt_PT/__init__.py b/faker/providers/address/pt_PT/__init__.py index <HASH>..<HASH> 100644 --- a/faker/providers/address/pt_PT/__init__.py +++ b/faker/providers/address/pt_PT/__init__.py @@ -1,4 +1,7 @@ # coding=utf-8 +# Source from wikipedia.pt +# https://pt.wikipedia.org/wiki/Distritos_de_Portugal +# https://pt.wikipedia.org/wiki/Lista_de_freguesias_de_Portugal from __future__ import unicode_literals from .. import Provider as AddressProvider
Added pt_PT address source
joke2k_faker
train
f7cae06ecfc759578b561cb76baa80f897c65e8e
diff --git a/scripts/linkCommodo.js b/scripts/linkCommodo.js index <HASH>..<HASH> 100644 --- a/scripts/linkCommodo.js +++ b/scripts/linkCommodo.js @@ -36,6 +36,12 @@ async function symlink(src, dest) { } (async () => { + const commodoRepo = path.resolve("..", "commodo", "packages"); + + if (!fs.existsSync(commodoRepo)) { + return; + } + console.log(`Linking @commodo packages...`); const directories = source => fs @@ -46,7 +52,6 @@ async function symlink(src, dest) { .map(c => c.name); const commodoRoot = path.resolve("node_modules", "@commodo"); - const commodoRepo = path.resolve("..", "commodo", "packages"); const commodoPackages = directories(commodoRepo); await new Promise(resolve => rimraf(path.join(commodoRoot, "*"), resolve));
chore: add commodo linking tool for development purposes
Webiny_webiny-js
train
e8e6dc55f58884cf6c0cd3938450300b147451a5
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index <HASH>..<HASH> 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -10,6 +10,9 @@ This change log uses principles from `keep a changelog <http://keepachangelog.co Added ^^^^^ +- ``dtool config readme-template`` CLI command for configuring the path to a + custom readme template + Changed ^^^^^^^ diff --git a/dtool_config/cli.py b/dtool_config/cli.py index <HASH>..<HASH> 100644 --- a/dtool_config/cli.py +++ b/dtool_config/cli.py @@ -44,6 +44,25 @@ def email(email_address): )) +@config.command() +@click.argument( + "readme_template_file", + required=False, + type=click.Path(exists=True, dir_okay=False) +) +def readme_template(readme_template_file): + """Display / set / update the readme template file.""" + if not readme_template_file: + click.secho(dtool_config.utils.get_readme_template_fpath( + CONFIG_PATH, + )) + else: + click.secho(dtool_config.utils.set_readme_template_fpath( + CONFIG_PATH, + readme_template_file + )) + + @config.group() def ecs(): """Configure ECS S3 object storage.""" diff --git a/dtool_config/utils.py b/dtool_config/utils.py index <HASH>..<HASH> 100644 --- a/dtool_config/utils.py +++ b/dtool_config/utils.py @@ -11,6 +11,10 @@ from dtoolcore.utils import ( USERNAME_KEY = "DTOOL_USER_FULL_NAME" USER_EMAIL_KEY = "DTOOL_USER_EMAIL" +README_TEMPLATE_KEY = "DTOOL_README_TEMPLATE_FPATH" + +CACHE_DIRECTORY_KEY = "DTOOL_CACHE_DIRECTORY" + ECS_ENDPOINT_KEY = "DTOOL_ECS_ENDPOINT" ECS_ACCESS_KEY_ID_KEY = "DTOOL_ECS_ACCESS_KEY_ID" ECS_SECRET_ACCESS_KEY_KEY = "DTOOL_ECS_SECRET_ACCESS_KEY" @@ -54,6 +58,28 @@ def set_user_email(config_fpath, email): return write_config_value_to_file(USER_EMAIL_KEY, email, config_fpath) +def get_readme_template_fpath(config_fpath): + """Return the readme template path. + + :param config_fpath: path to the dtool config file + :returns: path to the readme template file + """ + return get_config_value_from_file(README_TEMPLATE_KEY, config_fpath, "") + + +def set_readme_template_fpath(config_fpath, readme_template_fpath): + """Write the user email to the dtool config file. + + :param config_fpath: path to the dtool config file + :param readme_template_fpath: path to the readme template file + """ + return write_config_value_to_file( + README_TEMPLATE_KEY, + readme_template_fpath, + config_fpath + ) + + def get_ecs_endpoint(config_fpath): """Return the ECS endpoint URL. @@ -132,7 +158,7 @@ def get_cache(config_fpath): """ return get_config_value_from_file( - "DTOOL_CACHE_DIRECTORY", + CACHE_DIRECTORY_KEY, config_fpath, "" ) @@ -146,7 +172,7 @@ def set_cache(config_fpath, cache_dir): """ cache_dir = os.path.abspath(cache_dir) return write_config_value_to_file( - "DTOOL_CACHE_DIRECTORY", + CACHE_DIRECTORY_KEY, cache_dir, config_fpath ) diff --git a/tests/test_utils.py b/tests/test_utils.py index <HASH>..<HASH> 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -54,6 +54,28 @@ def test_set_get_email(tmp_dir_fixture): # NOQA assert dtool_config.utils.get_user_email(config_fpath) == email +def test_set_get_readme_template_fpath(tmp_dir_fixture): # NOQA + import dtool_config.utils + + config_fpath = os.path.join(tmp_dir_fixture, "dtool.json") + + assert dtool_config.utils.get_readme_template_fpath(config_fpath) == "" + + template_fpath = os.path.join(tmp_dir_fixture, "readme.yml") + with open(template_fpath, "w") as fh: + fh.write("---/ndescription: something\n") + + dtool_config.utils.set_readme_template_fpath(config_fpath, template_fpath) + assert dtool_config.utils.get_readme_template_fpath(config_fpath) == template_fpath # NOQA + + template_fpath_alt = os.path.join(tmp_dir_fixture, "readme_alt.yml") + with open(template_fpath_alt, "w") as fh: + fh.write("---/ndescription: something else\n") + + dtool_config.utils.set_readme_template_fpath(config_fpath, template_fpath_alt) # NOQA + assert dtool_config.utils.get_readme_template_fpath(config_fpath) == template_fpath_alt # NOQA + + def test_set_get_ecs_endpoint(tmp_dir_fixture): # NOQA import dtool_config.utils
Add command to configure the path to a custom readme file
jic-dtool_dtool-config
train
888ac59f32e65ffc598ba7cb9b4c6532b08f1cdd
diff --git a/cmd/juju-bridge/main.go b/cmd/juju-bridge/main.go index <HASH>..<HASH> 100644 --- a/cmd/juju-bridge/main.go +++ b/cmd/juju-bridge/main.go @@ -17,7 +17,7 @@ import ( const usage = ` Bridge existing devices -usage: [ -p ] [ -b <bridge-prefix ] <filename> <device-name>~<bridge-name>... +usage: [ -p ] [ -b <bridge-prefix ] <filename> <device-name>=<bridge-name>... Options: @@ -25,7 +25,7 @@ Options: Example: - $ juju-bridge /etc/network/interfaces ens3~br-ens3 bond0.150~br-bond0.150 + $ juju-bridge /etc/network/interfaces ens3=br-ens3 bond0.150=br-bond0.150 ` func printParseError(err error) { @@ -61,7 +61,7 @@ func main() { devices := make(map[string]string) for _, v := range args[1:] { - arg := strings.Split(v, "~") + arg := strings.Split(v, "=") if len(arg) != 2 { fmt.Fprintln(os.Stderr, usage) os.Exit(1) diff --git a/network/containerizer/bridgepolicy_test.go b/network/containerizer/bridgepolicy_test.go index <HASH>..<HASH> 100644 --- a/network/containerizer/bridgepolicy_test.go +++ b/network/containerizer/bridgepolicy_test.go @@ -1097,6 +1097,7 @@ var bridgeNames = map[string]string{ "fourteenchars1": "b-5590a4-chars1", "fifteenchars.12": "b-7e0acf-ars.12", "zeros0526193032": "b-000000-193032", + "enx00e07cc81e1d": "b-x00e07cc81e1d", } func (s *bridgePolicyStateSuite) TestBridgeNameForDevice(c *gc.C) {
Use '=' for separator in juju-bridge command. Another test for bridge name generator
juju_juju
train
58949b7c84044b02339926fa5dcbddaae30a1f7d
diff --git a/app/models/edition.rb b/app/models/edition.rb index <HASH>..<HASH> 100644 --- a/app/models/edition.rb +++ b/app/models/edition.rb @@ -87,6 +87,10 @@ class Edition series.where(state: "published").order(version_number: "desc").second end + def in_progress_sibling + subsequent_siblings.in_progress.order(version_number: "desc").first + end + def can_create_new_edition? subsequent_siblings.in_progress.empty? end
Add method to access an Edition's in-progress sibling
alphagov_govuk_content_models
train
7d88eed64b8ef4d846adeeecf9d86882219625d4
diff --git a/src/Sylius/Bundle/CartBundle/Twig/SyliusCartExtension.php b/src/Sylius/Bundle/CartBundle/Twig/SyliusCartExtension.php index <HASH>..<HASH> 100644 --- a/src/Sylius/Bundle/CartBundle/Twig/SyliusCartExtension.php +++ b/src/Sylius/Bundle/CartBundle/Twig/SyliusCartExtension.php @@ -29,21 +29,21 @@ class SyliusCartExtension extends Twig_Extension * * @var CartProviderInterface */ - private $cartProvider; + protected $cartProvider; /** * Cart item manager. * * @var ObjectRepository */ - private $cartItemRepository; + protected $cartItemRepository; /** * Form factory. * * @var FormFactory */ - private $formFactory; + protected $formFactory; /** * Constructor.
Unable properties access to extending classes
Sylius_Sylius
train
0b2002f679abe279be40da0be4de31132140c9f4
diff --git a/tests/test_llcp_sec.py b/tests/test_llcp_sec.py index <HASH>..<HASH> 100644 --- a/tests/test_llcp_sec.py +++ b/tests/test_llcp_sec.py @@ -2,6 +2,7 @@ from __future__ import absolute_import, division +import time import pytest import nfc.llcp.sec @@ -88,6 +89,7 @@ def test_bi_cs1_initialize_by_name(): def test_bv_cs1_calculate_session_key(): cs_1 = nfc.llcp.sec.CipherSuite1() + time.sleep(0.1) cs_2 = nfc.llcp.sec.CipherSuite1() ecpk = cs_2.public_key_x + cs_2.public_key_y rn_i = cs_2.random_nonce @@ -133,6 +135,7 @@ def test_bi_cs1_public_key_not_on_curve(): ]) def test_bv_cs1_encrypt_decrypt(a, p): cs_i = nfc.llcp.sec.CipherSuite1() + time.sleep(0.1) cs_t = nfc.llcp.sec.CipherSuite1() pk_i = cs_i.public_key_x + cs_i.public_key_y pk_t = cs_t.public_key_x + cs_t.public_key_y @@ -148,6 +151,7 @@ def test_bv_cs1_encrypt_decrypt(a, p): def test_bv_cs1_last_packet_send_counter(): cs_a = nfc.llcp.sec.CipherSuite1() + time.sleep(0.1) cs_b = nfc.llcp.sec.CipherSuite1() pk_b = cs_b.public_key_x + cs_b.public_key_y cs_a.calculate_session_key(pk_b, cs_b.random_nonce) @@ -159,6 +163,7 @@ def test_bv_cs1_last_packet_send_counter(): def test_bv_cs1_packet_send_counter_overflow(): with pytest.raises(nfc.llcp.sec.EncryptionError): cs_a = nfc.llcp.sec.CipherSuite1() + time.sleep(0.1) cs_b = nfc.llcp.sec.CipherSuite1() pk_b = cs_b.public_key_x + cs_b.public_key_y cs_a.calculate_session_key(pk_b, cs_b.random_nonce) @@ -170,6 +175,7 @@ def test_bv_cs1_packet_send_counter_overflow(): def test_bv_cs1_last_packet_recv_counter(): cs_a = nfc.llcp.sec.CipherSuite1() + time.sleep(0.1) cs_b = nfc.llcp.sec.CipherSuite1() pk_b = cs_b.public_key_x + cs_b.public_key_y cs_a.calculate_session_key(pk_b, cs_b.random_nonce) @@ -183,6 +189,7 @@ def test_bv_cs1_last_packet_recv_counter(): def test_bv_cs1_packet_recv_counter_overflow(): with pytest.raises(nfc.llcp.sec.DecryptionError): cs_a = nfc.llcp.sec.CipherSuite1() + time.sleep(0.1) cs_b = nfc.llcp.sec.CipherSuite1() pk_b = cs_b.public_key_x + cs_b.public_key_y cs_a.calculate_session_key(pk_b, cs_b.random_nonce) @@ -197,6 +204,7 @@ def test_bv_cs1_packet_recv_counter_overflow(): def test_bi_cs1_packet_recv_counter_mismatch(): with pytest.raises(nfc.llcp.sec.DecryptionError): cs_a = nfc.llcp.sec.CipherSuite1() + time.sleep(0.1) cs_b = nfc.llcp.sec.CipherSuite1() pk_b = cs_b.public_key_x + cs_b.public_key_y cs_a.calculate_session_key(pk_b, cs_b.random_nonce) @@ -210,6 +218,7 @@ def test_bi_cs1_packet_recv_counter_mismatch(): def test_bi_cs1_set_invalid_tag_size(): with pytest.raises(nfc.llcp.sec.EncryptionError): cs_a = nfc.llcp.sec.CipherSuite1() + time.sleep(0.1) cs_b = nfc.llcp.sec.CipherSuite1() pk_b = cs_b.public_key_x + cs_b.public_key_y cs_a.calculate_session_key(pk_b, cs_b.random_nonce)
Sleep between generating two CipherSuite1 instances. Without some delay between creating tow CipherSuite1 instances loacally, there is frequently the case that the second ECPK does not lie on the curve.
nfcpy_nfcpy
train
bfdb66ab710a02b5077d3ceaa008f915d880efd5
diff --git a/lib/faraday/adapter/httpclient.rb b/lib/faraday/adapter/httpclient.rb index <HASH>..<HASH> 100644 --- a/lib/faraday/adapter/httpclient.rb +++ b/lib/faraday/adapter/httpclient.rb @@ -6,51 +6,54 @@ module Faraday class HTTPClient < Faraday::Adapter dependency 'httpclient' - # @return [HTTPClient] - def client - @client ||= ::HTTPClient.new - end - - def call(env) - super - - # enable compression - client.transparent_gzip_decompression = true + def build_connection(env) + @client ||= ::HTTPClient.new.tap do |cli| + # enable compression + cli.transparent_gzip_decompression = true + end if (req = env[:request]) if (proxy = req[:proxy]) - configure_proxy proxy + configure_proxy @client, proxy end if (bind = req[:bind]) - configure_socket bind + configure_socket @client, bind end - configure_timeouts req + configure_timeouts @client, req end if env[:url].scheme == 'https' && (ssl = env[:ssl]) - configure_ssl ssl + configure_ssl @client, ssl end - configure_client + configure_client @client + + @client + end + + def call(env) + super # TODO: Don't stream yet. # https://github.com/nahi/httpclient/pull/90 env[:body] = env[:body].read if env[:body].respond_to? :read - resp = client.request env[:method], env[:url], + connection(env) do |http| + resp = http.request env[:method], env[:url], body: env[:body], header: env[:request_headers] - if (req = env[:request]).stream_response? - warn "Streaming downloads for #{self.class.name} " \ - 'are not yet implemented.' - req.on_data.call(resp.body, resp.body.bytesize) - end - save_response env, resp.status, resp.body, resp.headers, resp.reason + if (req = env[:request]).stream_response? + warn "Streaming downloads for #{self.class.name} " \ + 'are not yet implemented.' + req.on_data.call(resp.body, resp.body.bytesize) + end + save_response env, resp.status, resp.body, resp.headers, resp.reason - @app.call env + @app.call env + end rescue ::HTTPClient::TimeoutError, Errno::ETIMEDOUT raise Faraday::TimeoutError, $ERROR_INFO rescue ::HTTPClient::BadResponseError => e @@ -71,7 +74,7 @@ module Faraday end # @param bind [Hash] - def configure_socket(bind) + def configure_socket(client, bind) client.socket_local.host = bind[:host] client.socket_local.port = bind[:port] end @@ -79,7 +82,7 @@ module Faraday # Configure proxy URI and any user credentials. # # @param proxy [Hash] - def configure_proxy(proxy) + def configure_proxy(client, proxy) client.proxy = proxy[:uri] return unless proxy[:user] && proxy[:password] @@ -87,7 +90,7 @@ module Faraday end # @param ssl [Hash] - def configure_ssl(ssl) + def configure_ssl(client, ssl) ssl_config = client.ssl_config ssl_config.verify_mode = ssl_verify_mode(ssl) ssl_config.cert_store = ssl_cert_store(ssl) @@ -100,23 +103,23 @@ module Faraday end # @param req [Hash] - def configure_timeouts(req) - configure_timeout(req) if req[:timeout] - configure_open_timeout(req) if req[:open_timeout] + def configure_timeouts(client, req) + configure_timeout(client, req) if req[:timeout] + configure_open_timeout(client, req) if req[:open_timeout] end - def configure_timeout(req) + def configure_timeout(client, req) client.connect_timeout = req[:timeout] client.receive_timeout = req[:timeout] client.send_timeout = req[:timeout] end - def configure_open_timeout(req) + def configure_open_timeout(client, req) client.connect_timeout = req[:open_timeout] client.send_timeout = req[:open_timeout] end - def configure_client + def configure_client(client) @config_block&.call(client) end diff --git a/spec/faraday/adapter/httpclient_spec.rb b/spec/faraday/adapter/httpclient_spec.rb index <HASH>..<HASH> 100644 --- a/spec/faraday/adapter/httpclient_spec.rb +++ b/spec/faraday/adapter/httpclient_spec.rb @@ -12,9 +12,7 @@ RSpec.describe Faraday::Adapter::HTTPClient do client.ssl_config.timeout = 25 end - client = adapter.client - adapter.configure_client - + client = adapter.build_connection(url: URI.parse('https://example.com')) expect(client.keep_alive_timeout).to eq(20) expect(client.ssl_config.timeout).to eq(25) end
Refactor httpclient adapter to use #connection
lostisland_faraday
train
ba037cb41e57a02b0275992adf1010080a62ac14
diff --git a/lib/baby_tooth.rb b/lib/baby_tooth.rb index <HASH>..<HASH> 100644 --- a/lib/baby_tooth.rb +++ b/lib/baby_tooth.rb @@ -73,6 +73,10 @@ module BabyTooth super access_token, '/user' end + def street_team + @street_team ||= TeamFeed.new(access_token).members + end + def profile @profile ||= Profile.new(access_token, self['profile']) end @@ -90,6 +94,16 @@ module BabyTooth "profile" end + class TeamFeed < Client + def initialize(access_token) + super access_token, '/team' + end + + def members + body['items'] + end + end + private class Configuration
return street team members as an array. Example: user.street_team # => [{"name"=>"Buster Bluth", "url"=>"/team/<I>", "profile"=>"<URL>
terriblelabs_BabyTooth
train
3f2612df4768a1ee55b6fdfbcda04467f68539d3
diff --git a/src/failable.js b/src/failable.js index <HASH>..<HASH> 100644 --- a/src/failable.js +++ b/src/failable.js @@ -1,4 +1,5 @@ const equal = require('assert').deepEqual +const { fail } = require('assert') const stringify = require('json-stringify-safe') const SUCCESS = 0 @@ -35,8 +36,8 @@ const anyFailed = l => l.filter(isFailure).length > 0 const firstFailure = l => l.filter(isFailure)[0] const assertSuccessWhich = (t, f) => { - equal(isSuccess(f), true, stringify(hydrate(f))) - equal(t(payload(f)), true, stringify(hydrate(f))) + if (!isSuccess(f)) fail(stringify(hydrate(f))) + if (!t(payload(f))) fail(stringify(hydrate(f))) } const same = (a, b) => { @@ -54,11 +55,13 @@ const assertSuccess = (f, p) => const assertSuccessTyped = (t, f) => assertSuccessWhich(p => typeof p === t, f) const assertFailure = (f, p) => { - equal(isFailure(f), true, stringify(hydrate(f))) + if (!isFailure(f)) fail(stringify(hydrate(f))) if (p !== undefined) equal(payload(f), p) } -const assertEmpty = f => equal(isEmpty(f), true, stringify(hydrate(f))) +const assertEmpty = f => { + if (!isEmpty(f)) fail(stringify(hydrate(f))) +} const extractPayloads = results => results.map(payload)
only evaluates error string in failure condition
pheasantplucker_failables
train
15cff55655c66820c7307c703a1dfda5c8eb2f6f
diff --git a/pyexchange/exchange2010/soap_request.py b/pyexchange/exchange2010/soap_request.py index <HASH>..<HASH> 100644 --- a/pyexchange/exchange2010/soap_request.py +++ b/pyexchange/exchange2010/soap_request.py @@ -116,8 +116,8 @@ def get_item(exchange_id, format=u"Default"): return root def get_calendar_items(format=u"Default", start=None, end=None, max_entries=999999): - start = start.strftime(EXCHANGE_DATE_FORMAT) - end = end.strftime(EXCHANGE_DATE_FORMAT) + start = start.strftime(EXCHANGE_DATETIME_FORMAT) + end = end.strftime(EXCHANGE_DATETIME_FORMAT) root = M.FindItem( {u'Traversal': u'Shallow'}, diff --git a/tests/exchange2010/fixtures.py b/tests/exchange2010/fixtures.py index <HASH>..<HASH> 100644 --- a/tests/exchange2010/fixtures.py +++ b/tests/exchange2010/fixtures.py @@ -9,7 +9,7 @@ from datetime import datetime, timedelta, date from pytz import utc from collections import namedtuple from pyexchange.base.calendar import ExchangeEventOrganizer, ExchangeEventResponse, RESPONSE_ACCEPTED, RESPONSE_DECLINED, RESPONSE_TENTATIVE, RESPONSE_UNKNOWN -from pyexchange.exchange2010.soap_request import EXCHANGE_DATE_FORMAT # noqa +from pyexchange.exchange2010.soap_request import EXCHANGE_DATE_FORMAT, EXCHANGE_DATETIME_FORMAT # noqa # don't remove this - a few tests import stuff this way from ..fixtures import * # noqa diff --git a/tests/exchange2010/test_list_events.py b/tests/exchange2010/test_list_events.py index <HASH>..<HASH> 100644 --- a/tests/exchange2010/test_list_events.py +++ b/tests/exchange2010/test_list_events.py @@ -38,6 +38,10 @@ class Test_ParseEventListResponseData(unittest.TestCase): def test_canary(self): assert self.event_list is not None + def test_dates_are_in_datetime_format(self): + assert 'StartDate="%s"' % TEST_EVENT_LIST_START.strftime(EXCHANGE_DATETIME_FORMAT) in HTTPretty.last_request.body.decode('utf-8') + assert 'EndDate="%s"' % TEST_EVENT_LIST_END.strftime(EXCHANGE_DATETIME_FORMAT) in HTTPretty.last_request.body.decode('utf-8') + def test_event_count(self): assert self.event_list.count == 3
Fix getting a calendar event list with Exchange <I> The SOAP query was returing the following error: The request failed schema validation: The 'EndDate' attribute is invalid - The value '<I>-<I>-<I>' is invalid according to its datatype '<URL>
linkedin_pyexchange
train
812d63b1719237779a87f47b9aa24fb59f3abec3
diff --git a/tests/Monolog/Handler/DynamoDbHandlerTest.php b/tests/Monolog/Handler/DynamoDbHandlerTest.php index <HASH>..<HASH> 100644 --- a/tests/Monolog/Handler/DynamoDbHandlerTest.php +++ b/tests/Monolog/Handler/DynamoDbHandlerTest.php @@ -35,11 +35,14 @@ class DynamoDbHandlerTest extends TestCase $absentMethods[] = 'formatAttributes'; } - $this->client = $this->getMockBuilder('Aws\DynamoDb\DynamoDbClient') + $clientMockBuilder = $this->getMockBuilder('Aws\DynamoDb\DynamoDbClient') ->onlyMethods($implementedMethods) - ->addMethods($absentMethods) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor(); + if ($absentMethods) { + $clientMockBuilder->addMethods($absentMethods); + } + + $this->client = $clientMockBuilder->getMock(); } public function testConstruct()
Fix of incorrect DynamoDB mock creation addMethods([]) breaks the methods configured at onlyMethods() call
Seldaek_monolog
train
905e3d530b5a0e2d3a9e7d184d8858ef21dab7c7
diff --git a/test/configCases/plugins/banner-plugin-hashing/index.js b/test/configCases/plugins/banner-plugin-hashing/index.js index <HASH>..<HASH> 100644 --- a/test/configCases/plugins/banner-plugin-hashing/index.js +++ b/test/configCases/plugins/banner-plugin-hashing/index.js @@ -15,21 +15,22 @@ var source = require("fs") .slice(0,1)[0]; const banner = parseBanner(source) +const REGEXP_HASH = /^[A-Za-z0-9]{20}$/ it("should interpolate file hash in bundle0 chunk", () => { - banner["hash"].should.not.equal("[hash]"); + REGEXP_HASH.test(banner["hash"]).should.be.true; }); it("should interpolate chunkHash in bundle0 chunk", () => { - banner["chunkhash"].should.not.equal("[chunkhash]"); + REGEXP_HASH.test(banner["chunkhash"]).should.be.true; }); it("should interpolate name in bundle0 chunk", () => { - banner["name"].should.not.equal("[name]"); + banner["name"].should.equal("banner"); }); it("should interpolate extension in bundle0 chunk", () => { - banner["ext"].should.not.equal("[filebase]"); + banner["basename"].should.equal("banner.js"); }); it("should interpolate extension in bundle0 chunk", () => { diff --git a/test/configCases/plugins/banner-plugin-hashing/webpack.config.js b/test/configCases/plugins/banner-plugin-hashing/webpack.config.js index <HASH>..<HASH> 100644 --- a/test/configCases/plugins/banner-plugin-hashing/webpack.config.js +++ b/test/configCases/plugins/banner-plugin-hashing/webpack.config.js @@ -14,7 +14,7 @@ module.exports = { }, plugins: [ new webpack.BannerPlugin({ - banner: "hash:[hash], chunkhash:[chunkhash], name:[name], ext:[filebase], query:[query]" + banner: "hash:[hash], chunkhash:[chunkhash], name:[name], basename:[filebase], query:[query]" }) ] };
stricter testing of hash and chunkhash interpolation
webpack_webpack
train
0d28f4005fdba8accd4862c2aa05b34ec5bf6d3a
diff --git a/legacy/migrate_09_to_010.rb b/legacy/migrate_09_to_010.rb index <HASH>..<HASH> 100644 --- a/legacy/migrate_09_to_010.rb +++ b/legacy/migrate_09_to_010.rb @@ -20,12 +20,29 @@ Kernel.system "rake db:migrate:up VERSION=20100725000003 RAILS_ENV=#{Rails.env}" # Build up credentials. reload! User.all.each do |user| - Credentials::Email.create! :user => user, :email => user.attributes['email'] + unless /\@graph\.facebook\.com$/ =~ user.email + eml = Credentials::Email.new :email => user.attributes['email'] + eml.user = user + eml.save! + end - pwd = Credentials::Password.new :user => user - pwd.password = pwd.password_confirmation = '_' - pwd.key = user.password_salt + '|' + user.password_hash - pwd.save! + if user.password_hash + pwd = Credentials::Password.new + pwd.user = user + pwd.password = pwd.password_confirmation = '_' + pwd.key = user.password_salt + '|' + user.password_hash + pwd.save! + end +end +class FacebookToken < ActiveRecord::Base + belongs_to :user +end +FacebookToken.all.each do |token| + cred = Credentials::Facebook.new + cred.user = token.user + cred.facebook_uid = token.external_uid + cred.key = token.access_token + cred.save! end # Update the columns in the User model. @@ -57,5 +74,9 @@ class FinishUpgradingUserModel < ActiveRecord::Migration end end FinishUpgradingUserModel.migrate :up +class DropFacebookTokens < ActiveRecord::Migration + def change + drop_table :facebook_tokens + end +end reload! -
Ammended <I> migration script to handle Facebook tokens.
pwnall_authpwn_rails
train
ba123a6082d62fd525acd01cd2ee3d70d43caa7e
diff --git a/lib/core/connection/connect.js b/lib/core/connection/connect.js index <HASH>..<HASH> 100644 --- a/lib/core/connection/connect.js +++ b/lib/core/connection/connect.js @@ -15,6 +15,7 @@ const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION let AUTH_PROVIDERS; function connect(options, callback) { + const ConnectionType = options && options.connectionType ? options.connectionType : Connection; if (AUTH_PROVIDERS == null) { AUTH_PROVIDERS = defaultAuthProviders(options.bson); } @@ -26,7 +27,7 @@ function connect(options, callback) { return; } - performInitialHandshake(new Connection(socket, options), options, callback); + performInitialHandshake(new ConnectionType(socket, options), options, callback); }); return; @@ -40,13 +41,13 @@ function connect(options, callback) { return; } - performInitialHandshake(new Connection(ipv4Socket, options), options, callback); + performInitialHandshake(new ConnectionType(ipv4Socket, options), options, callback); }); return; } - performInitialHandshake(new Connection(ipv6Socket, options), options, callback); + performInitialHandshake(new ConnectionType(ipv6Socket, options), options, callback); }); }
refactor: support a factory type in `connect` This allows for easier testing, as well as potentially supporting multiple `Connection` types during our CMAP work
mongodb_node-mongodb-native
train
62961231e86562b30499a35b477840490702aca0
diff --git a/modules/webservices/debugger/action.php b/modules/webservices/debugger/action.php index <HASH>..<HASH> 100644 --- a/modules/webservices/debugger/action.php +++ b/modules/webservices/debugger/action.php @@ -394,7 +394,7 @@ if ( $action ) { $max = count( $v ); echo "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n"; - echo "<thead>\n<tr><th>Method</th><th>Description</th></tr>\n</thead>\n<tbody>\n"; + echo "<thead>\n<tr><th>Method ($max found)</th><th>Description</th></tr>\n</thead>\n<tbody>\n"; for($i=0; $i < $max; $i++) { $rec = $v[$i]; @@ -425,7 +425,7 @@ if ( $action ) "<input type=\"hidden\" name=\"wsdl\" value=\"$wsdl\" />". "<input type=\"hidden\" name=\"soapversion\" value=\"$soapversion\" />". "<input type=\"hidden\" name=\"action\" value=\"describe\" />". - "<input type=\"hidden\" name=\"run\" value=\"now\" />". + //"<input type=\"hidden\" name=\"run\" value=\"now\" />". "<input type=\"submit\" value=\"Describe\" /></form>"; echo "</td>"; @@ -614,8 +614,9 @@ else <h3>Examples:</h3> <p> -Server Address: phpxmlrpc.sourceforge.net, Path: /server.php (for xmlrpc)<br/> -Server Address: soap.amazon.com, Path: /schemas3/AmazonWebServices.wsdl (for soap with wsdl) +Server Address: phpxmlrpc.sourceforge.net, Path: <a target="frmcontroller" href="./controller/?action=&host=phpxmlrpc.sourceforge.net&path=/server.php&wstype=0">/server.php</a> (for xmlrpc)<br/> +Server Address: soap.amazon.com, Path: <a target="frmcontroller" href="./controller/?action=&host=soap.amazon.com&path=/schemas3/AmazonWebServices.wsdl&wstype=3">/schemas3/AmazonWebServices.wsdl</a> (for soap with wsdl)<br/> +Server Address: api.twitter.com, Path: /1, Method: <a target="frmcontroller" href="./controller/?action=execute&host=api.twitter.com&path=/1&method=statuses/public_timeline.json&wstype=4">statuses/public_timeline.json</a> (for rest) </p> <h3>Notes:</h3>
- show nr. of methods found in listmethods results; - avoid broken page refresh when going from method list to method description - add a rest sample url - make sample urls clickable
gggeek_ggwebservices
train
2f781863f5cf19358606989cb198d9223f7e763a
diff --git a/core/src/main/java/hudson/Util.java b/core/src/main/java/hudson/Util.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/hudson/Util.java +++ b/core/src/main/java/hudson/Util.java @@ -1095,6 +1095,21 @@ public class Util { } /** + * Resolves a symlink to the {@link File} that points to. + * + * @return null + * if the specified file is not a symlink. + */ + public static File resolveSymlinkToFile(File link) throws InterruptedException, IOException { + String target = resolveSymlink(link); + if (target==null) return null; + + File f = new File(target); + if (f.isAbsolute()) return f; // absolute symlink + return new File(link.getParentFile(),target); // relative symlink + } + + /** * Resolves symlink, if the given file is a symlink. Otherwise return null. * <p> * If the resolution fails, report an error. diff --git a/core/src/main/java/hudson/model/Run.java b/core/src/main/java/hudson/model/Run.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/hudson/model/Run.java +++ b/core/src/main/java/hudson/model/Run.java @@ -342,10 +342,9 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run try { if(Util.isSymlink(buildDir)) { // "Util.resolveSymlink(file)" resolves NTFS symlinks. - String resolvedSymlink = Util.resolveSymlink(buildDir); - if(resolvedSymlink != null) { - buildDir = new File(resolvedSymlink); - } + File target = Util.resolveSymlinkToFile(buildDir); + if(target != null) + buildDir = target; } // canonicalization to ensure we are looking at the ID in the directory name // as opposed to build numbers which are used in symlinks diff --git a/core/src/test/java/hudson/model/RunTest.java b/core/src/test/java/hudson/model/RunTest.java index <HASH>..<HASH> 100644 --- a/core/src/test/java/hudson/model/RunTest.java +++ b/core/src/test/java/hudson/model/RunTest.java @@ -30,6 +30,7 @@ import hudson.util.StreamTaskListener; import java.io.ByteArrayOutputStream; import java.io.File; import java.nio.charset.Charset; +import java.util.Date; import java.util.TimeZone; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; @@ -92,13 +93,11 @@ public class RunTest { public void testParseTimestampFromBuildDir() throws Exception { //Assume.assumeTrue(!Functions.isWindows() || (NTFS && JAVA7) || ...); - String buildDateTime = "2012-12-21_14-02-28"; - long buildTimestamp = 1356091348000L; + String buildDateTime = "2012-12-21_04-02-28"; int buildNumber = 155; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - StreamTaskListener l = new StreamTaskListener(baos, Charset.defaultCharset()); - + StreamTaskListener l = StreamTaskListener.fromStdout(); + File tempDir = Util.createTempDir(); File buildDir = new File(tempDir, buildDateTime); assertEquals(true, buildDir.mkdir()); @@ -108,7 +107,8 @@ public class RunTest { buildDir.mkdir(); Util.createSymlink(tempDir, buildDir.getAbsolutePath(), buildDirSymLink.getName(), l); - assertEquals(buildTimestamp, Run.parseTimestampFromBuildDir(buildDirSymLink)); + long time = Run.parseTimestampFromBuildDir(buildDirSymLink); + assertEquals(buildDateTime, Run.ID_FORMATTER.get().format(new Date(time))); } finally { Util.deleteRecursive(tempDir); }
Massaging the fix. - ID_FORMATTER is time zone sensitive, so comparing against # of milliseconds since the epoch won't be portable. - resolveSymlink can return a relative path.
jenkinsci_jenkins
train
803d226b7990806f82623ea8c1661ea2f3253ce1
diff --git a/src/satosa/micro_services/attribute_authorization.py b/src/satosa/micro_services/attribute_authorization.py index <HASH>..<HASH> 100644 --- a/src/satosa/micro_services/attribute_authorization.py +++ b/src/satosa/micro_services/attribute_authorization.py @@ -16,18 +16,14 @@ class AttributeAuthorization(ResponseMicroService): self.attribute_deny = config.get("attribute_deny", {}) def _check_authz(self, context, attributes, requester, provider): - for attribute_name, attribute_filter in _filters(self.attribute_allow, requester, provider): - regex = re.compile(attribute_filter) + for attribute_name, attribute_filters in _filters(self.attribute_allow, requester, provider): if attribute_name in attributes: - print(repr(regex)) - print(list(filter(regex.search, attributes[attribute_name]))) - if not list(filter(regex.search, attributes[attribute_name])): + if not any([any(filter(re.compile(af).search, attributes[attribute_name])) for af in attribute_filters]): raise SATOSAAuthenticationError(context.state, "Permission denied") - for attribute_name, attribute_filter in _filters(self.attribute_deny, requester, provider): - regex = re.compile(attribute_filter) + for attribute_name, attribute_filters in _filters(self.attribute_deny, requester, provider): if attribute_name in attributes: - if len(list(filter(regex.search, attributes[attribute_name]))) != len(attributes[attribute_name]): + if any([any(filter(re.compile(af).search, attributes[attribute_name])) for af in attribute_filters]): raise SATOSAAuthenticationError(context.state, "Permission denied") def process(self, context, data): diff --git a/tests/satosa/micro_services/test_attribute_authorization.py b/tests/satosa/micro_services/test_attribute_authorization.py index <HASH>..<HASH> 100644 --- a/tests/satosa/micro_services/test_attribute_authorization.py +++ b/tests/satosa/micro_services/test_attribute_authorization.py @@ -10,9 +10,9 @@ class TestAttributeAuthorization: authz_service.next = lambda ctx, data: data return authz_service - def test_authz_allow(self): + def test_authz_allow_success(self): attribute_allow = { - "": { "default": {"a0": '.+@.+'} } + "": { "default": {"a0": ['.+@.+']} } } attribute_deny = {} authz_service = self.create_authz_service(attribute_allow, attribute_deny) @@ -27,9 +27,9 @@ class TestAttributeAuthorization: except SATOSAAuthenticationError as ex: assert False - def test_authz_not_allow(self): + def test_authz_allow_fail(self): attribute_allow = { - "": { "default": {"a0": 'foo'} } + "": { "default": {"a0": ['foo1','foo2']} } } attribute_deny = {} authz_service = self.create_authz_service(attribute_allow, attribute_deny) @@ -41,5 +41,58 @@ class TestAttributeAuthorization: ctx = Context() ctx.state = dict() authz_service.process(ctx, resp) + assert False + except SATOSAAuthenticationError as ex: + assert True + + def test_authz_allow_second(self): + attribute_allow = { + "": { "default": {"a0": ['foo1','foo2']} } + } + attribute_deny = {} + authz_service = self.create_authz_service(attribute_allow, attribute_deny) + resp = InternalResponse(AuthenticationInformation(None, None, None)) + resp.attributes = { + "a0": ["foo2","kaka"], + } + try: + ctx = Context() + ctx.state = dict() + authz_service.process(ctx, resp) + except SATOSAAuthenticationError as ex: + assert False + + def test_authz_deny_success(self): + attribute_deny = { + "": { "default": {"a0": ['foo1','foo2']} } + } + attribute_allow = {} + authz_service = self.create_authz_service(attribute_allow, attribute_deny) + resp = InternalResponse(AuthenticationInformation(None, None, None)) + resp.attributes = { + "a0": ["foo2"], + } + try: + ctx = Context() + ctx.state = dict() + authz_service.process(ctx, resp) + assert False except SATOSAAuthenticationError as ex: assert True + + def test_authz_deny_fail(self): + attribute_deny = { + "": { "default": {"a0": ['foo1','foo2']} } + } + attribute_allow = {} + authz_service = self.create_authz_service(attribute_allow, attribute_deny) + resp = InternalResponse(AuthenticationInformation(None, None, None)) + resp.attributes = { + "a0": ["foo3"], + } + try: + ctx = Context() + ctx.state = dict() + authz_service.process(ctx, resp) + except SATOSAAuthenticationError as ex: + assert False
use any/all to clarify, allow lists of regexps and add more test
IdentityPython_SATOSA
train
37f21114fc6603d659d11ce82a28de7b55f9471a
diff --git a/tests/test_git_changelog.py b/tests/test_git_changelog.py index <HASH>..<HASH> 100644 --- a/tests/test_git_changelog.py +++ b/tests/test_git_changelog.py @@ -72,10 +72,10 @@ class TestWithRepository(TempDirTestCase): self.repo.index.commit('commit #{0}'.format(n)) nodes = self.changelog.run() assert_equal(1, len(nodes)) - list_node = nodes[0] - assert_equal(10, len(list_node)) - list_markup = str(list_node) - assert_in('<bullet_list>', list_markup) - for n in range(5, 15): - assert_in('commit #{0}'.format(n), list_markup) - assert_not_in('commit #4', list_markup) + list_markup = BeautifulStoneSoup(str(nodes[0])) + assert_equal(1, len(list_markup.findAll('bullet_list'))) + l = list_markup.bullet_list + assert_equal(10, len(l.findAll('list_item'))) + for n, child in zip(range(15, 5), l.childGenerator()): + assert_in('commit #{0}'.format(n), child.text) + assert_not_in('commit #4', l.text)
Convert multi-commit test to use BeautifulSoup.
OddBloke_sphinx-git
train
406dca11ddb37ad7a0652a8120fec060346cd667
diff --git a/voluptuous/tests/tests.py b/voluptuous/tests/tests.py index <HASH>..<HASH> 100644 --- a/voluptuous/tests/tests.py +++ b/voluptuous/tests/tests.py @@ -5,11 +5,22 @@ from voluptuous import ( Schema, Required, Extra, Invalid, In, Remove, Literal, Url, MultipleInvalid, LiteralInvalid, NotIn, Match, Email, Replace, Range, Coerce, All, Any, Length, FqdnUrl, ALLOW_EXTRA, PREVENT_EXTRA, - validate_schema, + validate_schema, ExactSequence ) from voluptuous.humanize import humanize_error +def test_exact_sequence(): + schema = Schema(ExactSequence([int, int])) + try: + schema([1, 2, 3]) + except Invalid: + assert True + else: + assert False, "Did not raise Invalid" + assert_equal(schema([1, 2]), [1, 2]) + + def test_required(): """Verify that Required works.""" schema = Schema({Required('q'): 1}) diff --git a/voluptuous/validators.py b/voluptuous/validators.py index <HASH>..<HASH> 100644 --- a/voluptuous/validators.py +++ b/voluptuous/validators.py @@ -634,7 +634,7 @@ class ExactSequence(object): self._schemas = [Schema(val, **kwargs) for val in validators] def __call__(self, v): - if not isinstance(v, (list, tuple)): + if not isinstance(v, (list, tuple)) or len(v) != len(self._schemas): raise ExactSequenceInvalid(self.msg) try: v = type(v)(schema(x) for x, schema in zip(v, self._schemas))
Fix Exact Sequence to Match Lengths
alecthomas_voluptuous
train
7c2e37266d3771326cae3b6fc659be2970877268
diff --git a/distributed-v2/src/main/java/com/orientechnologies/orient/distributed/impl/ODiscoveryListener.java b/distributed-v2/src/main/java/com/orientechnologies/orient/distributed/impl/ODiscoveryListener.java index <HASH>..<HASH> 100644 --- a/distributed-v2/src/main/java/com/orientechnologies/orient/distributed/impl/ODiscoveryListener.java +++ b/distributed-v2/src/main/java/com/orientechnologies/orient/distributed/impl/ODiscoveryListener.java @@ -8,13 +8,15 @@ public interface ODiscoveryListener { boolean master; int term; long lastPingTimestamp; + String connectionUsername; + String connectionPassword; } void nodeJoined(NodeData data); void nodeLeft(NodeData data); - default void leaderElected(NodeData data){ + default void leaderElected(NodeData data) { //TODO } diff --git a/distributed-v2/src/main/java/com/orientechnologies/orient/distributed/impl/ONodeManager.java b/distributed-v2/src/main/java/com/orientechnologies/orient/distributed/impl/ONodeManager.java index <HASH>..<HASH> 100644 --- a/distributed-v2/src/main/java/com/orientechnologies/orient/distributed/impl/ONodeManager.java +++ b/distributed-v2/src/main/java/com/orientechnologies/orient/distributed/impl/ONodeManager.java @@ -32,6 +32,8 @@ public abstract class ONodeManager { String group; int term; int role; + String connectionUsername; + String connectionPassword; //for ping int tcpPort; @@ -47,6 +49,8 @@ public abstract class ONodeManager { int masterTerm; String masterAddress; int masterTcpPort; + String masterConnectionUsername; + String masterConnectionPassword; long masterPing; } @@ -223,6 +227,9 @@ public abstract class ONodeManager { message.role = leaderStatus.status == OLeaderElectionStateMachine.Status.LEADER ? Message.ROLE_COORDINATOR : Message.ROLE_REPLICA; + message.connectionUsername = config.getConnectionUsername(); + message.connectionPassword = config.getConnectionPassword(); + message.tcpPort = config.getTcpPort(); //masterData ODiscoveryListener.NodeData master = this.knownServers.values().stream().filter(x -> x.master).findFirst().orElse(null); if (master != null) { @@ -230,6 +237,8 @@ public abstract class ONodeManager { message.masterTerm = master.term; message.masterAddress = master.address; message.masterTcpPort = master.port; + message.masterConnectionUsername = master.connectionUsername; + message.masterConnectionPassword = master.connectionPassword; message.masterPing = master.lastPingTimestamp; } @@ -248,6 +257,8 @@ public abstract class ONodeManager { data.term = message.term; data.name = message.nodeName; data.address = fromAddr; + data.connectionUsername = message.connectionUsername; + data.connectionPassword = message.connectionPassword; data.port = message.tcpPort; knownServers.put(message.nodeName, data); discoveryListener.nodeJoined(data); @@ -288,6 +299,8 @@ public abstract class ONodeManager { data.name = message.masterName; data.term = message.masterTerm; data.address = message.masterAddress; + data.connectionUsername = message.masterConnectionUsername; + data.connectionPassword = message.masterConnectionPassword; data.port = message.masterTcpPort; data.lastPingTimestamp = message.masterPing; data.master = true; @@ -431,6 +444,8 @@ public abstract class ONodeManager { data.master = true; data.term = message.term; data.address = fromAddr; + data.connectionUsername = message.connectionUsername; + data.connectionPassword = message.connectionPassword; data.port = message.tcpPort; data.lastPingTimestamp = System.currentTimeMillis(); @@ -524,15 +539,19 @@ public abstract class ONodeManager { writeString(message.nodeName, buffer); writeInt(message.term, buffer); writeInt(message.role, buffer); + writeInt(message.tcpPort, buffer); + writeString(message.connectionUsername, buffer); + writeString(message.connectionPassword, buffer); switch (message.type) { case Message.TYPE_PING: - writeInt(message.tcpPort, buffer); writeString(message.masterName, buffer); writeInt(message.masterTerm, buffer); writeString(message.masterAddress, buffer); writeInt(message.masterTcpPort, buffer); writeLong(message.masterPing, buffer); + writeString(message.masterConnectionUsername, buffer); + writeString(message.masterConnectionPassword, buffer); break; case Message.TYPE_VOTE_LEADER_ELECTION: writeString(message.voteForNode, buffer); @@ -553,15 +572,19 @@ public abstract class ONodeManager { message.nodeName = readString(stream); message.term = readInt(stream); message.role = readInt(stream); + message.tcpPort = readInt(stream); + message.connectionUsername = readString(stream); + message.connectionPassword = readString(stream); switch (message.type) { case Message.TYPE_PING: - message.tcpPort = readInt(stream); message.masterName = readString(stream); message.masterTerm = readInt(stream); message.masterAddress = readString(stream); message.masterTcpPort = readInt(stream); message.masterPing = readLong(stream); + message.masterConnectionUsername = readString(stream); + message.masterConnectionPassword = readString(stream); case Message.TYPE_VOTE_LEADER_ELECTION: message.voteForNode = readString(stream);
Pass distributed connection user/pwd in discovery ping
orientechnologies_orientdb
train
e47d96bf646f549ac050c85731cb52b54eac72e4
diff --git a/src/main/java/net/kuujo/copycat/impl/DefaultStateMachineExecutor.java b/src/main/java/net/kuujo/copycat/impl/DefaultStateMachineExecutor.java index <HASH>..<HASH> 100644 --- a/src/main/java/net/kuujo/copycat/impl/DefaultStateMachineExecutor.java +++ b/src/main/java/net/kuujo/copycat/impl/DefaultStateMachineExecutor.java @@ -32,6 +32,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import org.vertx.java.core.json.JsonArray; import org.vertx.java.core.json.JsonElement; import org.vertx.java.core.json.JsonObject; @@ -473,49 +474,6 @@ public class DefaultStateMachineExecutor implements StateMachineExecutor { protected final Annotation[] args; protected final Method method; protected final Class<?>[] parameters; - protected final boolean[] serializable; - - @SuppressWarnings("serial") - private static final Set<Class<?>> primitiveTypes = new HashSet<Class<?>>() {{ - add(Class.class); - add(String.class); - add(String[].class); - add(Boolean.class); - add(Boolean[].class); - add(boolean.class); - add(boolean[].class); - add(Character.class); - add(Character[].class); - add(char.class); - add(char[].class); - add(Byte.class); - add(Byte[].class); - add(byte.class); - add(byte[].class); - add(Short.class); - add(Short[].class); - add(short.class); - add(short[].class); - add(Integer.class); - add(Integer[].class); - add(int.class); - add(int[].class); - add(Long.class); - add(Long[].class); - add(long.class); - add(long[].class); - add(Float.class); - add(Float[].class); - add(float.class); - add(float[].class); - add(Double.class); - add(Double[].class); - add(double.class); - add(double[].class); - add(Void.class); - add(Void[].class); - add(void.class); - }}; private CommandWrapper(String name, Command info, Annotation[] args, Method method) { this.name = name; @@ -523,16 +481,6 @@ public class DefaultStateMachineExecutor implements StateMachineExecutor { this.args = args; this.method = method; parameters = method.getParameterTypes(); - serializable = new boolean[parameters.length]; - for (int i = 0; i < parameters.length; i++) { - serializable[i] = true; - for (Class<?> primitive : primitiveTypes) { - if (primitive.isAssignableFrom(parameters[i])) { - serializable[i] = false; - break; - } - } - } } @Override @@ -562,8 +510,21 @@ public class DefaultStateMachineExecutor implements StateMachineExecutor { } } else { - if (serializable[i]) { - args[i] = serializer.readObject(new JsonObject((Map) value), parameters[i]); + if (value instanceof Map) { + if (Map.class.isAssignableFrom(parameters[i])) { + args[i] = value; + } + else { + args[i] = serializer.readObject(new JsonObject((Map) value), parameters[i]); + } + } + else if (value instanceof List) { + if (List.class.isAssignableFrom(parameters[i])) { + args[i] = value; + } + else { + args[i] = serializer.readObject(new JsonArray((List) value), parameters[i]); + } } else { args[i] = value;
Automatically deserialize List and Map types to command arguments.
atomix_atomix
train
f0568eea72da8bff024050e5910552fb9148a0a8
diff --git a/internal/exec/stages/disks/disks.go b/internal/exec/stages/disks/disks.go index <HASH>..<HASH> 100644 --- a/internal/exec/stages/disks/disks.go +++ b/internal/exec/stages/disks/disks.go @@ -253,6 +253,34 @@ func (s stage) createFilesystems(config types.Config) error { } } + // udevd registers an IN_CLOSE_WRITE inotify watch on block device + // nodes, and synthesizes udev "change" events when the watch fires. + // mkfs.btrfs triggers multiple such events, the first of which + // occurs while there is no recognizable filesystem on the + // partition. Thus, if an existing partition is reformatted as + // btrfs while keeping the same filesystem label, there will be a + // synthesized uevent that deletes the /dev/disk/by-label symlink + // and a second one that restores it. If we didn't account for this, + // a systemd unit that depended on the by-label symlink (e.g. + // systemd-fsck-root.service) could have the symlink deleted out + // from under it. + // + // There's no way to fix this completely. We can't wait for the + // restoring uevent to propagate, since we can't determine which + // specific uevents were triggered by the mkfs. We can wait for + // udev to settle, though it's conceivable that the deleting uevent + // has already been processed and the restoring uevent is still + // sitting in the inotify queue. In practice the uevent queue will + // be the slow one, so this should be good enough. + // + // Test case: boot failure in coreos.ignition.*.btrfsroot kola test. + if err := s.Logger.LogCmd( + exec.Command("/bin/udevadm", "settle"), + "waiting for udev to settle", + ); err != nil { + return fmt.Errorf("udevadm settle failed: %v", err) + } + return nil }
stages/disks: Wait for uevents triggered by mkfs to settle The disks stage could complete with udev events still in flight. When running mkfs.btrfs to overwrite an existing filesystem, this could cause by-label symlinks to be temporarily deleted while other systemd units were expecting them to exist.
coreos_ignition
train
e52cb59e8b199fa14865312155939e1fdf4579fd
diff --git a/views/structure/header/blank.php b/views/structure/header/blank.php index <HASH>..<HASH> 100644 --- a/views/structure/header/blank.php +++ b/views/structure/header/blank.php @@ -11,6 +11,19 @@ if (!empty($page->seo->title)) { $aPageTitle[] = APP_NAME; +if (!empty($page->html_lang)) { + $sHtmlLang = $page->html_lang; +} else { + $sHtmlLang = 'en'; +} + +if (!empty($page->html_class) && is_array($page->html_class)) { + $aHtmlClass = $page->html_class; +} elseif (!empty($page->html_class)) { + $aHtmlClass = [$page->html_class]; +} else { + $aHtmlClass = []; +} if (!empty($page->body_class) && is_array($page->body_class)) { $aBodyClass = $page->body_class; @@ -22,8 +35,10 @@ if (!empty($page->body_class) && is_array($page->body_class)) { ?> <!DOCTYPE html> -<!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]--> -<!--[if (gte IE 9)|!(IE)]><!--><html lang="en"> <!--<![endif]--> +<!--[if IE 8 ]> +<html class="ie ie8 <?=implode(' ', $aHtmlClass)?>" lang="<?=$sHtmlLang?>>"> <![endif]--> +<!--[if (gte IE 9)|!(IE)]><!--> +<html class="<?=implode(' ', $aHtmlClass)?>" lang="<?=$sHtmlLang?>"> <!--<![endif]--> <head> <?php @@ -49,8 +64,8 @@ if (!empty($page->body_class) && is_array($page->body_class)) { <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> - <script src="<?=NAILS_ASSETS_URL . 'bower_components/html5shiv/dist/html5shiv.js'?>"></script> - <script src="<?=NAILS_ASSETS_URL . 'bower_components/respond/dest/respond.min.js'?>"></script> + <script src="<?=NAILS_ASSETS_URL . 'bower_components/html5shiv/dist/html5shiv.js'?>"></script> + <script src="<?=NAILS_ASSETS_URL . 'bower_components/respond/dest/respond.min.js'?>"></script> <![endif]--> </head> - <body<?=$aBodyClass ? ' class="' . implode(' ', $aBodyClass) . '"' : ''?>> + <body class="<?=implode(' ', $aBodyClass)?>">
Added ability to specify page language and add classes to the <html> tag
nails_common
train
ac020bc7ae265ac6f7268c8ae3a054aaf1d84626
diff --git a/core/src/main/java/org/testcontainers/containers/GenericContainer.java b/core/src/main/java/org/testcontainers/containers/GenericContainer.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/org/testcontainers/containers/GenericContainer.java +++ b/core/src/main/java/org/testcontainers/containers/GenericContainer.java @@ -421,12 +421,10 @@ public class GenericContainer<SELF extends GenericContainer<SELF>> if (!reused) { containerIsCreated(containerId); - logger().info("Starting container with ID: {}", containerId); + logger().info("Container {} is starting: {}", dockerImageName, containerId); dockerClient.startContainerCmd(containerId).exec(); } - logger().info("Container {} is starting: {}", dockerImageName, containerId); - // For all registered output consumers, start following as close to container startup as possible this.logConsumers.forEach(this::followOutput);
Stop logging about starting when reusing (#<I>)
testcontainers_testcontainers-java
train
04d44be1f19fd149883f2ba1b15c134c19452e29
diff --git a/lib/wool.rb b/lib/wool.rb index <HASH>..<HASH> 100644 --- a/lib/wool.rb +++ b/lib/wool.rb @@ -41,4 +41,7 @@ require 'wool/runner' require 'wool/rake/task' # Program logic require 'wool/warning' -require 'wool/scanner' \ No newline at end of file +require 'wool/scanner' + +Wool::SexpAnalysis.analyze_inputs([[File.join(File.dirname(__FILE__), 'wool', 'standard_library', 'class_definitions.rb'), + File.read(File.join(File.dirname(__FILE__), 'wool', 'standard_library', 'class_definitions.rb'))]]) \ No newline at end of file diff --git a/lib/wool/analysis/annotations/scope_annotation.rb b/lib/wool/analysis/annotations/scope_annotation.rb index <HASH>..<HASH> 100644 --- a/lib/wool/analysis/annotations/scope_annotation.rb +++ b/lib/wool/analysis/annotations/scope_annotation.rb @@ -177,14 +177,14 @@ module Wool case node when :var_field begin - binding = scope.lookup(name[1][1]) + binding = @current_scope.lookup(name[1][1]) rescue Scope::ScopeResolutionError object = WoolObject.new(ClassRegistry['Object'], @current_scope) - scope.add_binding!(LocalVariableBinding.new(name[1][1], object)) + @current_scope.add_binding!(LocalVariableBinding.new(name[1][1], object)) end end - visit_with_scope(name, @current_scope) - visit_with_scope(val, @current_scope) + visit name + visit val end # add :for do |sym, vars, iterable, body| diff --git a/lib/wool/analysis/bootstrap.rb b/lib/wool/analysis/bootstrap.rb index <HASH>..<HASH> 100644 --- a/lib/wool/analysis/bootstrap.rb +++ b/lib/wool/analysis/bootstrap.rb @@ -30,8 +30,6 @@ module Wool class_class.instance_variable_set("@scope", class_scope) # move these to a real ruby file that gets run through the scanner at # boot time - WoolClass.new('Array') { |klass| klass.superclass = object_class } - WoolClass.new('Proc') { |klass| klass.superclass = object_class } rescue StandardError => err new_exception = BootstrappingError.new("Bootstrapping failed: #{err.message}") new_exception.set_backtrace(err.backtrace) diff --git a/lib/wool/runner.rb b/lib/wool/runner.rb index <HASH>..<HASH> 100644 --- a/lib/wool/runner.rb +++ b/lib/wool/runner.rb @@ -85,7 +85,12 @@ module Wool end def print_modules - SexpAnalysis::WoolModule.all_modules.sort_by(&:name).each { |mod| puts mod.name } + SexpAnalysis::WoolModule.all_modules.map do |mod| + if SexpAnalysis::WoolClass === mod && mod.superclass + then "#{mod.name} < #{mod.superclass.name}" + else mod.name + end + end.sort.each { |name| puts name } end def read_file(file) diff --git a/spec/runner_spec.rb b/spec/runner_spec.rb index <HASH>..<HASH> 100644 --- a/spec/runner_spec.rb +++ b/spec/runner_spec.rb @@ -75,7 +75,9 @@ describe Runner do modules = output.split("\n") modules.should_not be_empty modules.should == modules.sort - %w(Array Module Proc Class Object).each {|mod| modules.should include(mod)} + ["Array < Object", "Module < Object", "Proc < Object", "Class < Module", "Object"].each do |mod| + modules.should include(mod) + end end end
Got the standard library to load and not conflict with any other features!
michaeledgar_laser
train
3a044a99d86fdf5b8aab9265834a878cead6d84c
diff --git a/grimoire_elk/enriched/gitlab.py b/grimoire_elk/enriched/gitlab.py index <HASH>..<HASH> 100644 --- a/grimoire_elk/enriched/gitlab.py +++ b/grimoire_elk/enriched/gitlab.py @@ -264,6 +264,9 @@ class GitLabEnrich(Enrich): # The real data merge_request = item['data'] + # merge requests can end up in two states, merged and closed. The former concerns merge requests + # that were finally merged to the code base, while the latter represents rejected merge requests. + # `time_to_close_days` and `time_to_merge_days` are aligned to the aforementioned states. time_to_close_days = get_time_diff_days(merge_request['created_at'], merge_request['closed_at']) time_to_merge_days = get_time_diff_days(merge_request['created_at'], merge_request['merged_at'])
[enrich-gitlab] Add doc for `time_to_close_days` and `time_to_merge_days` This code adds information about why/how the variables `time_to_close_days` and `time_to_merge_days` are calculated.
chaoss_grimoirelab-elk
train
518feadc3e62a9c9cc5788ea5eb0224cf338508a
diff --git a/ReactNativeClient/lib/MdToHtml.js b/ReactNativeClient/lib/MdToHtml.js index <HASH>..<HASH> 100644 --- a/ReactNativeClient/lib/MdToHtml.js +++ b/ReactNativeClient/lib/MdToHtml.js @@ -326,7 +326,7 @@ class MdToHtml { -webkit-mask: url("data:image/svg+xml;utf8,<svg viewBox='0 0 1792 1792' xmlns='http://www.w3.org/2000/svg'><path d='M1312 256h-832q-66 0-113 47t-47 113v832q0 66 47 113t113 47h832q66 0 113-47t47-113v-832q0-66-47-113t-113-47zm288 160v832q0 119-84.5 203.5t-203.5 84.5h-832q-119 0-203.5-84.5t-84.5-203.5v-832q0-119 84.5-203.5t203.5-84.5h832q119 0 203.5 84.5t84.5 203.5z'/></svg>"); } a.checkbox.tick { - left: .05em; /* square-o and check-square-o aren't exactly aligned so add this extra gap to align them */ + left: .124em; /* square-o and check-square-o aren't exactly aligned so add this extra gap to align them */ /* Awesome Font check-square-o */ -webkit-mask: url("data:image/svg+xml;utf8,<svg viewBox='0 0 1792 1792' xmlns='http://www.w3.org/2000/svg'><path d='M1472 930v318q0 119-84.5 203.5t-203.5 84.5h-832q-119 0-203.5-84.5t-84.5-203.5v-832q0-119 84.5-203.5t203.5-84.5h832q63 0 117 25 15 7 18 23 3 17-9 29l-49 49q-10 10-23 10-3 0-9-2-23-6-45-6h-832q-66 0-113 47t-47 113v832q0 66 47 113t113 47h832q66 0 113-47t47-113v-254q0-13 9-22l64-64q10-10 23-10 6 0 12 3 20 8 20 29zm231-489l-814 814q-24 24-57 24t-57-24l-430-430q-24-24-24-57t24-57l110-110q24-24 57-24t57 24l263 263 647-647q24-24 57-24t57 24l110 110q24 24 24 57t-24 57z'/></svg>"); } diff --git a/ReactNativeClient/lib/components/screens/folder.js b/ReactNativeClient/lib/components/screens/folder.js index <HASH>..<HASH> 100644 --- a/ReactNativeClient/lib/components/screens/folder.js +++ b/ReactNativeClient/lib/components/screens/folder.js @@ -36,6 +36,7 @@ class FolderScreenComponent extends BaseScreenComponent { let styles = { textInput: { color: theme.color, + paddingLeft: 10, }, };
All: Better checkbox alignment and added padding on notebook title
laurent22_joplin
train
1993ce72282ec188de8ffd9021e6e96b22679cde
diff --git a/integrationtests/gquic/drop_test.go b/integrationtests/gquic/drop_test.go index <HASH>..<HASH> 100644 --- a/integrationtests/gquic/drop_test.go +++ b/integrationtests/gquic/drop_test.go @@ -3,6 +3,7 @@ package gquic_test import ( "bytes" "fmt" + mrand "math/rand" "os/exec" "strconv" @@ -56,6 +57,13 @@ var _ = Describe("Drop tests", func() { return (p % interval) < dropInARow } + stochasticDropper := func(p protocol.PacketNumber, freq int) bool { + if p <= 10 { // don't interfere with the crypto handshake + return false + } + return mrand.Int63n(int64(freq)) == 0 + } + for _, v := range protocol.SupportedVersions { version := v @@ -69,6 +77,12 @@ var _ = Describe("Drop tests", func() { }, version) }) + It(fmt.Sprintf("downloads a file when 1/5th of all packet are dropped randomly in %s direction", d), func() { + runDropTest(func(d quicproxy.Direction, p protocol.PacketNumber) bool { + return d.Is(direction) && stochasticDropper(p, 5) + }, version) + }) + It(fmt.Sprintf("downloads a file when 10 packets every 100 packet are dropped in %s direction", d), func() { runDropTest(func(d quicproxy.Direction, p uint64) bool { return d.Is(direction) && deterministicDropper(p, 100, 10)
add drop tests with stochastically dropped packets
lucas-clemente_quic-go
train