hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
06a6c8df049288288a686de1bc0c8f36b705f9fd
diff --git a/lib/commands/marshalString.js b/lib/commands/marshalString.js index <HASH>..<HASH> 100644 --- a/lib/commands/marshalString.js +++ b/lib/commands/marshalString.js @@ -3,7 +3,7 @@ var _ = require('lodash'); module.exports = function(item) { - if (!_.isString(item)) { + if (!_.isString(item) || _.isEmpty(item)) { return undefined; } return {S: item}; diff --git a/test/commands/marshalString.js b/test/commands/marshalString.js index <HASH>..<HASH> 100644 --- a/test/commands/marshalString.js +++ b/test/commands/marshalString.js @@ -1,12 +1,19 @@ 'use strict'; var marshalString = require('../../lib/commands/marshalString'), + withData = require('leche').withData, should = require('should'); describe('marshalString', function() { - it('should return undefined if item is not a string', function() { - var result = marshalString({}); - (result === undefined).should.equal(true); + + withData({ + 'empty string': [''], + 'non string value': [{}] + }, function(item) { + it('should return undefined', function() { + var result = marshalString(item); + (result === undefined).should.equal(true); + }); }); it('should marshal item to dynamoDb "S" format', function() {
Added an empty check to the marshalString command.
CascadeEnergy_dynamoDb-marshaler
train
b5358b5774f6312491c69240de9873879328fcf3
diff --git a/lizzy_client/cli.py b/lizzy_client/cli.py index <HASH>..<HASH> 100644 --- a/lizzy_client/cli.py +++ b/lizzy_client/cli.py @@ -104,14 +104,10 @@ def agent_error(e: requests.HTTPError, fatal=True): data = e.response.json() details = data['detail'] # type: str except JSONDecodeError: - data = e.response.text - details = data + details = e.response.text - if details: - lines = ('[AGENT] {}'.format(line) for line in details.splitlines()) - msg = '\n' + '\n'.join(lines) - else: - msg = "[AGENT] {status} {title}".format_map(data) + lines = ('[AGENT] {}'.format(line) for line in details.splitlines()) + msg = '\n' + '\n'.join(lines) if fatal: fatal_error(msg)
Always try to use error message as text
zalando-stups_lizzy-client
train
f6da8b258a9d149360e4867355434fe6655f0ee9
diff --git a/numina/user.py b/numina/user.py index <HASH>..<HASH> 100644 --- a/numina/user.py +++ b/numina/user.py @@ -100,13 +100,38 @@ def super_load(path): def mode_show(serializer, args): '''Run the show mode of Numina''' _logger.debug('show mode') + if args.what == 'om': + show_observingmodes(args) + elif args.what == 'rcp': + show_recipes(args) + else: + show_instruments(args) + +def show_recipes(args): if args.id is None: for Cls in list_recipes(): print_recipe(Cls) else: Cls = super_load(args.id) - print_recipe(Cls) + print_recipe(Cls) + +def show_observingmodes(args): + + if args.id: + must_print = lambda x: x.uuid == args.id + else: + must_print = lambda x: True + + ins = get_instruments() + for theins in ins.values(): + for mode in theins.modes: + if must_print(mode): + print_obsmode(mode) +def show_instruments(args): + ins = get_instruments() + for theins in ins.values(): + print_instrument(theins, modes=False) def print_recipe(recipe): print 'Recipe:', recipe.__name__ @@ -117,28 +142,22 @@ def print_recipe(recipe): rp.print_requirements() print -def print_instrument(instrument): +def print_instrument(instrument, modes=True): print 'Name:', instrument.name - if instrument.modes: + if modes and instrument.modes: print 'Observing modes' print '---------------' for mode in instrument.modes: print_obsmode(mode) - print '---' + print '---' def print_obsmode(obsmode): print obsmode.name, ':', obsmode.summary print 'Recipe:', obsmode.recipe + print 'UUID:', obsmode.uuid print '--' -def mode_list_instrument(serializer, args): - '''Run the list_instrument mode of Numina''' - _logger.debug('list_instrument mode') - ins = get_instruments() - for theins in ins.values(): - print_instrument(theins) - def main_internal(cls, obsres, instrument, parameters, @@ -467,18 +486,22 @@ def main(args=None): description='These are valid commands you can ask numina to do.') parser_show = subparsers.add_parser('show', help='show help') - parser_show.set_defaults(command=mode_show) - parser_show.add_argument('id', nargs='?', default=None) + parser_show.add_argument('-o', '--observing-modes', action='store_const', dest='what', const='om', + help='Show observing modes') + parser_show.add_argument('-r', action='store_const', dest='what', const='rcp', + help='Show recipes') + parser_show.add_argument('-i', action='store_const', dest='what', const='ins', + help='Show instruments') + + parser_show.set_defaults(command=mode_show, what='om') + parser_show.add_argument('id', nargs='?', default=None, + help='Identificator') parser_list = subparsers.add_parser('list', help='list help') parser_list.set_defaults(command=mode_list) parser_list.add_argument('recipe', nargs='?', default=None) - parser_list_instrument = subparsers.add_parser('list_instrument', help='list_instrument help') - - parser_list_instrument.set_defaults(command=mode_list_instrument) - parser_run = subparsers.add_parser('run', help='run help') parser_run.set_defaults(command=mode_run)
Added show options (instrument, obsmodes and recipes)
guaix-ucm_numina
train
0cba00aacadb485f13f846112d1c3f5affbef4f4
diff --git a/src/Connections/Ldap.php b/src/Connections/Ldap.php index <HASH>..<HASH> 100644 --- a/src/Connections/Ldap.php +++ b/src/Connections/Ldap.php @@ -821,7 +821,7 @@ class Ldap implements ConnectionInterface return chr(hexdec($matches[1])); }; - return preg_replace_callback("/\\\([0-9A-Fa-f]{2})/", $callback, $value); + return preg_replace_callback('/\\\([0-9A-Fa-f]{2})/', $callback, $value); } /** diff --git a/tests/ConnectionTest.php b/tests/ConnectionTest.php index <HASH>..<HASH> 100644 --- a/tests/ConnectionTest.php +++ b/tests/ConnectionTest.php @@ -96,15 +96,4 @@ class ConnectionTest extends FunctionalTestCase $this->assertEquals($expected, $result); } - - public function testUnescape() - { - $ldap = $this->mock('Adldap\Connections\Ldap')->makePartial(); - - $toEscape = 'test!@#$%^&*()'; - - $escaped = $ldap->escape($toEscape); - - $this->assertEquals($toEscape, $ldap->unescape($escaped)); - } } \ No newline at end of file
Removing unescape test for now
Adldap2_Adldap2
train
7746ca17008518e04bced57f7c3b1b11eca4b408
diff --git a/client/src/views/serverselect.js b/client/src/views/serverselect.js index <HASH>..<HASH> 100644 --- a/client/src/views/serverselect.js +++ b/client/src/views/serverselect.js @@ -46,6 +46,7 @@ _kiwi.view.ServerSelect = Backbone.View.extend({ this.gateway = _kiwi.global.components.Network(); this.gateway.on('connect', this.networkConnected, this); this.gateway.on('connecting', this.networkConnecting, this); + this.gateway.on('disconnect', this.networkDisconnected, this); this.gateway.on('irc_error', this.onIrcError, this); }, @@ -258,6 +259,11 @@ _kiwi.view.ServerSelect = Backbone.View.extend({ this.model.current_connecting_network = null; }, + networkDisconnected: function () { + this.model.current_connecting_network = null; + this.state = 'all'; + }, + networkConnecting: function (event) { this.model.trigger('connecting'); this.setStatus(_kiwi.global.i18n.translate('client_views_serverselect_connection_trying').fetch(), 'ok'); diff --git a/server/irc/connection.js b/server/irc/connection.js index <HASH>..<HASH> 100644 --- a/server/irc/connection.js +++ b/server/irc/connection.js @@ -37,6 +37,9 @@ var IrcConnection = function (hostname, port, ssl, nick, user, options, state, c // Socket state this.connected = false; + // If the connection closes and this is false, we reconnect + this.requested_disconnect = false; + // IRCd write buffers (flood controll) this.write_buffer = []; @@ -175,6 +178,8 @@ IrcConnection.prototype.connect = function () { // Make sure we don't already have an open connection this.disposeSocket(); + this.requested_disconnect = false; + // Get the IP family for the dest_addr (either socks or IRCd destination) getConnectionFamily(dest_addr, function getConnectionFamilyCb(err, family, host) { var outgoing; @@ -290,17 +295,37 @@ IrcConnection.prototype.connect = function () { }); that.socket.on('close', function socketCloseCb(had_error) { + // If that.connected is false, we never actually managed to connect + var was_connected = that.connected, + had_registered = that.server.registered, + should_reconnect = false; + that.connected = false; + that.server.reset(); // Remove this socket form the identd lookup if (that.identd_port_pair) { delete global.clients.port_pairs[that.identd_port_pair]; } - that.emit('close', had_error); + should_reconnect = (!that.requested_disconnect && was_connected && had_registered); + + if (should_reconnect) { + that.emit('reconnecting'); + } else { + that.emit('close', had_error); + } // Close the whole socket down that.disposeSocket(); + + // If this socket closing was not expected and we did actually connect and + // we did previously completely register on the network, then reconnect + if (should_reconnect) { + setTimeout(function() { + that.connect(); + }, 3000); + } }); }); }; @@ -392,6 +417,8 @@ IrcConnection.prototype.end = function (data) { return; } + this.requested_disconnect = true; + if (data) { this.write(data, true); } diff --git a/server/irc/server.js b/server/irc/server.js index <HASH>..<HASH> 100755 --- a/server/irc/server.js +++ b/server/irc/server.js @@ -8,6 +8,8 @@ var IrcServer = function (irc_connection) { this.list_buffer = []; this.motd_buffer = ''; + this.registered = false; + this.irc_events = { connect: onConnect, options: onOptions, @@ -49,8 +51,17 @@ IrcServer.prototype.dispose = function (){ }; +IrcServer.prototype.reset = function() { + this.registered = false; + this.list_buffer = []; + this.motd_buffer = ''; +}; + + function onConnect(event) { + this.registered = true; + this.irc_connection.clientEvent('connect', { nick: event.nick }); diff --git a/server/irc/state.js b/server/irc/state.js index <HASH>..<HASH> 100755 --- a/server/irc/state.js +++ b/server/irc/state.js @@ -70,6 +70,10 @@ State.prototype.connect = function (hostname, port, ssl, nick, user, options, ca return callback(err.message); }); + con.on('reconnecting', function IrcConnectionReconnecting() { + that.sendIrcCommand('disconnect', {connection_id: con.con_num, reason: 'IRC server reconnecting'}); + }); + con.on('close', function IrcConnectionClose() { // TODO: Can we get a better reason for the disconnection? Was it planned? that.sendIrcCommand('disconnect', {connection_id: con.con_num, reason: 'disconnected'});
Reconnecting when IRCd drops the connection
prawnsalad_KiwiIRC
train
5756e6e448b2a30b259c592ef517d25b5a7fa920
diff --git a/src/main/java/com/ibm/watson/developer_cloud/dialog/v1/DialogService.java b/src/main/java/com/ibm/watson/developer_cloud/dialog/v1/DialogService.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/ibm/watson/developer_cloud/dialog/v1/DialogService.java +++ b/src/main/java/com/ibm/watson/developer_cloud/dialog/v1/DialogService.java @@ -23,8 +23,6 @@ import java.util.List; import java.util.Map; import java.util.logging.Logger; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import com.ibm.watson.developer_cloud.dialog.v1.model.Conversation; @@ -300,15 +298,10 @@ public class DialogService extends WatsonService { final Response response = execute(request); final JsonObject jsonObject = ResponseUtil.getJsonObject(response); final List<ConversationData> conversationDataList = - getGson().fromJson(jsonObject.get(CONVERSATIONS), listConversationDataType); + GsonSingleton.getGsonWithoutPrettyPrinting().fromJson(jsonObject.get(CONVERSATIONS), listConversationDataType); return conversationDataList; } - private Gson getGson() { - return new GsonBuilder().setDateFormat(CONVERSATION_DATE_FORMAT).create(); - } - - /** * Retrieves the list of Dialogs for the user. * diff --git a/src/test/java/com/ibm/watson/developer_cloud/dialog/v1/DialogServiceIT.java b/src/test/java/com/ibm/watson/developer_cloud/dialog/v1/DialogServiceIT.java index <HASH>..<HASH> 100644 --- a/src/test/java/com/ibm/watson/developer_cloud/dialog/v1/DialogServiceIT.java +++ b/src/test/java/com/ibm/watson/developer_cloud/dialog/v1/DialogServiceIT.java @@ -13,6 +13,7 @@ */ package com.ibm.watson.developer_cloud.dialog.v1; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -101,12 +102,16 @@ public class DialogServiceIT extends WatsonServiceTest { assertFalse(dialogContent.isEmpty()); assertNotNull(dialogContent.get(0)); - final Map<String, String> profile = service.getProfile(dialogId, c.getClientId()); + Map<String, String> profile = service.getProfile(dialogId, c.getClientId()); + // update profile - profile.put(profile.keySet().iterator().next(), "foo"); - + String variable = profile.keySet().iterator().next(); + profile.put(variable, "foo"); service.updateProfile(dialogId, c.getClientId(), profile); + assertEquals(service.getProfile(dialogId, c.getClientId()).get(variable), "foo"); + assertEquals(service.getProfile(dialogId, c.getClientId(), variable).get(variable), "foo"); + final Map<String, Object> params = new HashMap<String,Object>(); params.put(DialogService.DATE_FROM, DateUtils.addDays(new Date(), -10)); params.put(DialogService.DATE_TO, new Date());
[dialog] Added integration test to check that the updateProfile method works. #<I>
watson-developer-cloud_java-sdk
train
e997b8ba14803516fd5f4f01b2e041245ee52a9c
diff --git a/src/Illuminate/Foundation/Testing/TestResponse.php b/src/Illuminate/Foundation/Testing/TestResponse.php index <HASH>..<HASH> 100644 --- a/src/Illuminate/Foundation/Testing/TestResponse.php +++ b/src/Illuminate/Foundation/Testing/TestResponse.php @@ -64,6 +64,36 @@ class TestResponse } /** + * Assert that the response has a not found status code. + * + * @return $this + */ + public function assertNotFound() + { + PHPUnit::assertTrue( + $this->isNotFound(), + 'Response status code ['.$this->getStatusCode().'] is not a not found status code.' + ); + + return $this; + } + + /** + * Assert that the response has a forbidden status code. + * + * @return $this + */ + public function assertForbidden() + { + PHPUnit::assertTrue( + $this->isForbidden(), + 'Response status code ['.$this->getStatusCode().'] is not a forbidden status code.' + ); + + return $this; + } + + /** * Assert that the response has the given status code. * * @param int $status
Add additional methods for response status testing (#<I>)
laravel_framework
train
9c2982b03bbbd8f09903921fd9affabbabcad6cb
diff --git a/pipenv/environments.py b/pipenv/environments.py index <HASH>..<HASH> 100644 --- a/pipenv/environments.py +++ b/pipenv/environments.py @@ -36,5 +36,7 @@ if PIPENV_VENV_IN_PROJECT: if os.name == 'nt': PIPENV_NOSPIN = True +_pipenv_timout_raw = os.environ.get('PIPENV_TIMEOUT') + # Tells pipenv how long to wait for virtualenvs to be created in seconds -PIPENV_TIMEOUT = int(os.environ.get('PIPENV_TIMEOUT')) or 120 +PIPENV_TIMEOUT = int(_pipenv_timout_raw) if _pipenv_timout_raw is not None else 120
put in more proper logic for int conversion when reading from the PIPENV_TIMEOUT variable
pypa_pipenv
train
baef16c209e967a42d8f515ce110d903d2304e72
diff --git a/app/lib/navigation/organization_menu.rb b/app/lib/navigation/organization_menu.rb index <HASH>..<HASH> 100644 --- a/app/lib/navigation/organization_menu.rb +++ b/app/lib/navigation/organization_menu.rb @@ -48,7 +48,7 @@ module Navigation }, { :key => :organization_default_info, :name => _("System Default Info"), - :url => organization_default_info_path(@organization.label, "system"), + :url => lambda{organization_default_info_path(@organization.label, "system")}, :if => lambda{@organization && @organization.editable?}, :options => {:class=>"panel_link"} },
oh glorious tests, i offer you this sacrifice. please work.
Katello_katello
train
e387c744e998d639b1117d52ee10e933d1cbc801
diff --git a/lib/createLiveStyleApp.js b/lib/createLiveStyleApp.js index <HASH>..<HASH> 100644 --- a/lib/createLiveStyleApp.js +++ b/lib/createLiveStyleApp.js @@ -45,6 +45,14 @@ module.exports = function createLiveStyleApp(options) { } if (options.root) { + if (options.autoprefixer) { + var autoprefixerOptions = {}; + if (typeof options.autoprefixer === 'string') { + autoprefixerOptions.options = options.autoprefixer; + } + app.use(autoprefixer(autoprefixerOptions)); + } + if (options.compiless) { app.use(compiless({root: options.root})); } @@ -61,15 +69,6 @@ module.exports = function createLiveStyleApp(options) { next(); } }); - - if (options.autoprefixer) { - var autoprefixerOptions = {}; - if (typeof options.autoprefixer === 'string') { - autoprefixerOptions.options = options.autoprefixer; - } - app.use(autoprefixer(autoprefixerOptions)); - } - } if (proxyUrl) {
fix ordering of middleware to ensure autoprefixer is ran after compiless.
One-com_livestyle
train
5bd2e60191f18a583874f3ad92bcba1f4c310345
diff --git a/lib/baza_models/query.rb b/lib/baza_models/query.rb index <HASH>..<HASH> 100644 --- a/lib/baza_models/query.rb +++ b/lib/baza_models/query.rb @@ -57,7 +57,22 @@ class BazaModels::Query end def length - count + if @_previous_model && !any_wheres_other_than_relation? && @_previous_model.autoloads[@_relation.fetch(:relation_name)] + @_previous_model.autoloads[@_relation.fetch(:relation_name)].length + else + count + end + end + + def new(attributes) + raise "No previous model" unless @_previous_model + raise "No relation" unless @_relation + + new_sub_model = @model.new(@_relation.fetch(:foreign_key) => @_previous_model.id) + new_sub_model.assign_attributes(attributes) + autoloaded_cache_or_create << new_sub_model + + new_sub_model end def find(id) diff --git a/spec/baza_models/query_spec.rb b/spec/baza_models/query_spec.rb index <HASH>..<HASH> 100644 --- a/spec/baza_models/query_spec.rb +++ b/spec/baza_models/query_spec.rb @@ -31,7 +31,7 @@ describe BazaModels::Query do end end - context '#joins' do + context "#joins" do before do user.save! role_admin.save! @@ -152,4 +152,21 @@ describe BazaModels::Query do expect(sql).to end_with " DESC" end end + + it "#new" do + user.save! + expect(user.roles.length).to eq 0 + expect(user.roles.count).to eq 0 + + role = user.roles.new(role: "admin") + expect(role.new_record?).to eq true + expect(user.roles.length).to eq 1 + expect(user.roles.count).to eq 0 + + role.save! + + expect(user.roles.length).to eq 1 + expect(user.roles.count).to eq 1 + expect(user.roles.to_a).to eq [role] + end end
Added support for Query#new
kaspernj_baza_models
train
5f7b24a9beb35ec186afc887a077311179d6f74e
diff --git a/test/extended/builds/webhook.go b/test/extended/builds/webhook.go index <HASH>..<HASH> 100644 --- a/test/extended/builds/webhook.go +++ b/test/extended/builds/webhook.go @@ -3,6 +3,7 @@ package builds import ( "bytes" "encoding/json" + "fmt" "io/ioutil" "net/http" "time" @@ -12,6 +13,7 @@ import ( "k8s.io/client-go/rest" g "github.com/onsi/ginkgo" + o "github.com/onsi/gomega" buildv1 "github.com/openshift/api/build/v1" imagev1 "github.com/openshift/api/image/v1" exutil "github.com/openshift/origin/test/extended/util" @@ -93,30 +95,27 @@ func TestWebhook(t g.GinkgoTInterface, oc *exutil.CLI) { } for _, test := range tests { + g.By(fmt.Sprintf("testing %s webhooks", test.Name)) for _, s := range test.URLs { // trigger build event sending push notification clusterAdminClientConfig := oc.AdminConfig() + g.By("executing the webhook to get the build object") body := postFile(clusterAdminBuildClient.RESTClient(), test.HeaderFunc, test.Payload, clusterAdminClientConfig.Host+s, http.StatusOK, t, oc) - if len(body) == 0 { - t.Fatalf("%s: Webhook did not return expected Build object.", test.Name) - } + o.Expect(body).NotTo(o.BeEmpty()) + g.By("Unmarshalling the build object") returnedBuild := &buildv1.Build{} err := json.Unmarshal(body, returnedBuild) - if err != nil { - t.Fatalf("%s: Unable to unmarshal returned body into a Build object: %v", test.Name, err) - } + o.Expect(err).NotTo(o.HaveOccurred()) + g.By("checking that the build exists") actual, err := clusterAdminBuildClient.Builds(oc.Namespace()).Get(returnedBuild.Name, metav1.GetOptions{}) - if err != nil { - t.Errorf("Created build not found in cluster: %v", err) - } + o.Expect(err).NotTo(o.HaveOccurred()) + g.By("checking that we found the correct build") // There should only be one trigger on these builds. - if actual.Spec.TriggeredBy[0].Message != returnedBuild.Spec.TriggeredBy[0].Message { - t.Fatalf("%s: Webhook returned incorrect build.", test.Name) - } + o.Expect(actual.Spec.TriggeredBy[0].Message).To(o.Equal(returnedBuild.Spec.TriggeredBy[0].Message)) } } }
Adding By statements for Webhook Test
openshift_origin
train
7e03645a5534fc582847df6ece72aec516487b47
diff --git a/src/event/event.js b/src/event/event.js index <HASH>..<HASH> 100644 --- a/src/event/event.js +++ b/src/event/event.js @@ -13,6 +13,10 @@ jQuery.event = { if ( jQuery.browser.msie && element.setInterval != undefined ) element = window; + // Make sure that the function being executed has a unique ID + if ( !handler.guid ) + handler.guid = this.guid++; + // if data is passed, bind to handler if( data != undefined ) { // Create temporary function pointer to original handler @@ -31,13 +35,6 @@ jQuery.event = { handler.guid = fn.guid; } - // Make sure that the function being executed has a unique ID - if ( !handler.guid ) { - handler.guid = this.guid++; - // Don't forget to set guid for the original handler function - if (fn) fn.guid = handler.guid; - } - // Init the element's event structure if (!element.$events) element.$events = {};
Clean up in jQuery.event.add for assigning a handler.guid
jquery_jquery
train
7cf1d37c93a54627e17b150ebd361520a2e7b8f7
diff --git a/code/dataobjects/Link.php b/code/dataobjects/Link.php index <HASH>..<HASH> 100644 --- a/code/dataobjects/Link.php +++ b/code/dataobjects/Link.php @@ -157,8 +157,8 @@ class Link extends DataObject ), TextField::create( 'Anchor', - _t('Linkable.ANCHOR', 'Anchor') - )->setRightTitle(_t('Linkable.ANCHORINFO', 'Include # at the start of your anchor name')) + _t('Linkable.ANCHOR', 'Anchor/Querystring') + )->setRightTitle(_t('Linkable.ANCHORINFO', 'Include # at the start of your anchor name or, ? at the start of your querystring')) )->displayIf("Type")->isEqualTo("SiteTree")->end() ), 'OpenInNewWindow'
Update anchor field label to include querystring tip
sheadawson_silverstripe-linkable
train
f54233b1b236c7457828075843c35d04182c55c5
diff --git a/Mapper/DoctrineORMMapper.php b/Mapper/DoctrineORMMapper.php index <HASH>..<HASH> 100644 --- a/Mapper/DoctrineORMMapper.php +++ b/Mapper/DoctrineORMMapper.php @@ -227,7 +227,6 @@ class DoctrineORMMapper implements EventSubscriber try { foreach ($this->associations[$metadata->name] as $type => $mappings) { foreach ($mappings as $mapping) { - // the association is already set, skip the native one if ($metadata->hasAssociation($mapping['fieldName'])) { continue;
Apply fixes from StyleCI (#<I>)
sonata-project_SonataEasyExtendsBundle
train
96e4ed2d497d70d58ab3b8a30f29d96781ad544f
diff --git a/redisson/src/main/java/org/redisson/remote/BaseRemoteProxy.java b/redisson/src/main/java/org/redisson/remote/BaseRemoteProxy.java index <HASH>..<HASH> 100644 --- a/redisson/src/main/java/org/redisson/remote/BaseRemoteProxy.java +++ b/redisson/src/main/java/org/redisson/remote/BaseRemoteProxy.java @@ -67,12 +67,7 @@ public abstract class BaseRemoteProxy { private final Map<Class<?>, String> requestQueueNameCache = new ConcurrentHashMap<>(); public String getRequestQueueName(Class<?> remoteInterface) { - String str = requestQueueNameCache.get(remoteInterface); - if (str == null) { - str = "{" + name + ":" + remoteInterface.getName() + "}"; - requestQueueNameCache.put(remoteInterface, str); - } - return str; + return requestQueueNameCache.computeIfAbsent(remoteInterface, k -> "{" + name + ":" + k.getName() + "}"); } protected RFuture<RemoteServiceAck> tryPollAckAgainAsync(RemoteInvocationOptions optionsCopy, diff --git a/redisson/src/main/java/org/redisson/remote/BaseRemoteService.java b/redisson/src/main/java/org/redisson/remote/BaseRemoteService.java index <HASH>..<HASH> 100644 --- a/redisson/src/main/java/org/redisson/remote/BaseRemoteService.java +++ b/redisson/src/main/java/org/redisson/remote/BaseRemoteService.java @@ -92,12 +92,7 @@ public abstract class BaseRemoteService { public String getRequestQueueName(Class<?> remoteInterface) { - String str = requestQueueNameCache.get(remoteInterface); - if (str == null) { - str = "{" + name + ":" + remoteInterface.getName() + "}"; - requestQueueNameCache.put(remoteInterface, str); - } - return str; + return requestQueueNameCache.computeIfAbsent(remoteInterface, k -> "{" + name + ":" + k.getName() + "}"); } protected ByteBuf encode(Object obj) {
Simplify code using Map::computeIfAbsent
redisson_redisson
train
d983bb9e5a717c2bece47cda5d21b21d3d037cfd
diff --git a/types/src/main/java/com/google/common/html/types/SafeHtmlBuilder.java b/types/src/main/java/com/google/common/html/types/SafeHtmlBuilder.java index <HASH>..<HASH> 100644 --- a/types/src/main/java/com/google/common/html/types/SafeHtmlBuilder.java +++ b/types/src/main/java/com/google/common/html/types/SafeHtmlBuilder.java @@ -296,6 +296,33 @@ public final class SafeHtmlBuilder { return setAttribute("id", value); } + /** These elements are whitelisted to use media with a String value. */ + private static final Set<String> MEDIA_STRING_ELEMENT_WHITELIST = + createUnmodifiableSet("link", "source"); + + /** + * Sets the {@code media} attribute for this element. + * + * <p>The attribute {@code media} with a {@code String} value is allowed on these elements: + * + * <ul> + * <li>{@code link} + * <li>{@code source} + * </ul> + * + * @throws IllegalArgumentException if the {@code media} attribute with a {@code String} value is + * not allowed on this element + */ + public SafeHtmlBuilder setMedia(String value) { + if (!MEDIA_STRING_ELEMENT_WHITELIST.contains(elementName)) { + throw new IllegalArgumentException( + "Attribute \"media\" with a String value can only be used " + + "by one of the following elements: " + + MEDIA_STRING_ELEMENT_WHITELIST); + } + return setAttribute("media", value); + } + /** Sets the {@code name} attribute for this element. */ public SafeHtmlBuilder setName(@CompileTimeConstant final String value) { return setAttribute("name", value);
Add support for "media" attribute. Restricted the attribute to specific elements as it seems like a name which could be used for something dangerous in a future HTML element. Needed in [] ------------- Created by MOE: <URL>
google_safe-html-types
train
1883e41079685a6931addc5e304b6682cc2cd2a3
diff --git a/cubicle.gemspec b/cubicle.gemspec index <HASH>..<HASH> 100644 --- a/cubicle.gemspec +++ b/cubicle.gemspec @@ -5,7 +5,7 @@ Gem::Specification.new do |s| s.name = %q{cubicle} - s.version = "0.1.5" + s.version = "0.1.6" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Nathan Stults"] diff --git a/lib/cubicle/member.rb b/lib/cubicle/member.rb index <HASH>..<HASH> 100644 --- a/lib/cubicle/member.rb +++ b/lib/cubicle/member.rb @@ -22,6 +22,7 @@ module Cubicle @expression_type = :javascript else @expression = @name + @field_name = @name @expression_type = :field_name end diff --git a/test/cubicle/cubicle_query_test.rb b/test/cubicle/cubicle_query_test.rb index <HASH>..<HASH> 100644 --- a/test/cubicle/cubicle_query_test.rb +++ b/test/cubicle/cubicle_query_test.rb @@ -106,6 +106,7 @@ class CubicleQueryTest < ActiveSupport::TestCase assert_equal "Sad Day Moonshine", @results[0]["product"] assert_equal 3, @results[0]["total_defects"] assert_equal 2, @results[0]["preventable_defects"] + assert_equal 2, @results[0]["conditioned_preventable"] assert_equal 15.91, @results[0]["total_cost"] assert_equal 15.91/3, @results[0]["avg_cost"] assert_equal 2/3.0, @results[0]["preventable_pct"] @@ -145,6 +146,7 @@ class CubicleQueryTest < ActiveSupport::TestCase assert_equal "Sad Day Moonshine", @results[0]["product"] assert_equal 3, @results[0]["total_defects"] assert_equal 2, @results[0]["preventable_defects"] + assert_equal 2, @results[0]["conditioned_preventable"] assert_in_delta 15.91, @results[0]["total_cost"],0.0001 assert_in_delta 15.91/3, @results[0]["avg_cost"],0.0001 assert_in_delta 2/3.0, @results[0]["preventable_pct"],0.0001 @@ -181,6 +183,7 @@ class CubicleQueryTest < ActiveSupport::TestCase assert_equal "Sad Day Moonshine", @results[0]["product"] assert_equal 3, @results[0]["total_defects"] assert_equal 2, @results[0]["preventable_defects"] + assert_equal 2, @results[0]["conditioned_preventable"] assert_in_delta 15.91, @results[0]["total_cost"],0.0001 assert_in_delta 15.91/3, @results[0]["avg_cost"],0.0001 assert_equal 2/3.0, @results[0]["preventable_pct"] @@ -200,6 +203,7 @@ class CubicleQueryTest < ActiveSupport::TestCase assert_equal "Sad Day Moonshine", @results[0]["product"] assert_equal 3, @results[0]["total_defects"] assert_equal 2, @results[0]["preventable_defects"] + assert_equal 2, @results[0]["conditioned_preventable"] assert_equal 15.91, @results[0]["total_cost"] assert_equal 15.91/3, @results[0]["avg_cost"] assert_equal 2/3.0, @results[0]["preventable_pct"] @@ -372,6 +376,7 @@ class CubicleQueryTest < ActiveSupport::TestCase assert_equal "Sad Day Moonshine", results[0]["product"] assert_equal 3, results[0]["total_defects"] assert_equal 2, results[0]["preventable_defects"] + assert_equal 2, results[0]["conditioned_preventable"] assert_in_delta 15.91, results[0]["total_cost"],0.0001 assert_in_delta 15.91/3, results[0]["avg_cost"],0.0001 assert_in_delta 2/3.0, results[0]["preventable_pct"],0.0001 diff --git a/test/cubicle/duration_test.rb b/test/cubicle/duration_test.rb index <HASH>..<HASH> 100644 --- a/test/cubicle/duration_test.rb +++ b/test/cubicle/duration_test.rb @@ -47,7 +47,6 @@ class DurationTest < ActiveSupport::TestCase results = DefectCubicle.query do select :all_measures, :product end - puts results.inspect results = results[0] assert_equal((6+5)/2.0, results["ms3_to_now_average"]) @@ -58,7 +57,6 @@ class DurationTest < ActiveSupport::TestCase results = DefectCubicle.query do select :all_measures, :product end - puts results.inspect results = results[0] assert_equal((6+5)/2.0, results["avg_time_since_ms3"])
Added :condition modifier to cubicle DSL, allowing the formal specification of boolean conditions which control whether a value is emitted for each document during an aggregation, or if a null is emitted instead.
PlasticLizard_Cubicle
train
f4bab4d763c0313631384a44ab720320b4738147
diff --git a/pacman/fields.py b/pacman/fields.py index <HASH>..<HASH> 100644 --- a/pacman/fields.py +++ b/pacman/fields.py @@ -87,34 +87,34 @@ class BaseByteSequence(BaseField): self._value = struct.unpack(self.format, data) -class BUByteSequence(BaseByteSequence): +class UBByteSequence(BaseByteSequence): FORMAT_MODIFIER = lambda self, l: ">" + "B" * l -class LUByteSequence(BaseByteSequence): +class ULByteSequence(BaseByteSequence): FORMAT_MODIFIER = lambda self, l: "<" + "B" * l #=============================================================================== # Unsigned Big Endian #=============================================================================== -class BUInt8(BaseStructField): +class UBInt8(BaseStructField): FORMAT = ">B" -class BUInt16(BaseStructField): +class UBInt16(BaseStructField): FORMAT = ">H" -class BUInt24(BaseStructField): +class UBInt24(BaseStructField): FORMAT = ">BBB" -class BUInt32(BaseStructField): +class UBInt32(BaseStructField): FORMAT = ">I" -class BUInt64(BaseStructField): +class UBInt64(BaseStructField): FORMAT = ">Q" @@ -140,19 +140,19 @@ class BInt64(BaseStructField): #=============================================================================== # Unsigned Little Endian #=============================================================================== -class LUInt8(BaseStructField): +class ULInt8(BaseStructField): FORMAT = "<B" -class LUInt16(BaseStructField): +class ULInt16(BaseStructField): FORMAT = "<H" -class LUInt32(BaseStructField): +class ULInt32(BaseStructField): FORMAT = "<I" -class LUInt64(BaseStructField): +class ULInt64(BaseStructField): FORMAT = "<Q"
Refactor: Change from BUInt8 to UBInt8 form This matches the convention in the construct library and seems to be a bit nicer to look at in general. Much easier to make the change now then later.
digidotcom_python-suitcase
train
163c3c614bd9bf26afb384d851d99215389f9c5b
diff --git a/lib/chai/core/assertions.js b/lib/chai/core/assertions.js index <HASH>..<HASH> 100644 --- a/lib/chai/core/assertions.js +++ b/lib/chai/core/assertions.js @@ -1037,27 +1037,40 @@ module.exports = function (chai, _) { if (desiredError) { this.assert( err === desiredError - , 'expected #{this} to throw ' + _.inspect(desiredError) + ' but ' + _.inspect(err) + ' was thrown' - , 'expected #{this} to not throw ' + _.inspect(desiredError) + , 'expected #{this} to throw #{exp} but #{act} was thrown' + , 'expected #{this} to not throw #{exp}' + , desiredError + , err ); + return this; } // next, check constructor if (constructor) { this.assert( err instanceof constructor - , 'expected #{this} to throw ' + name + ' but ' + _.inspect(err) + ' was thrown' - , 'expected #{this} to not throw ' + name + ' but ' + _.inspect(err) + ' was thrown'); + , 'expected #{this} to throw #{exp} but #{act} was thrown' + , 'expected #{this} to not throw #{exp} but #{act} was thrown' + , name + , err + ); + if (!errMsg) return this; } // next, check message - var message = typeof(err) === 'object' && "message" in err ? err.message : '' + err; + var message = 'object' === _.type(err) && "message" in err + ? err.message + : '' + err; + if ((message != null) && errMsg && errMsg instanceof RegExp) { this.assert( errMsg.exec(message) - , 'expected #{this} to throw error matching ' + errMsg + ' but got ' + _.inspect(message) - , 'expected #{this} to throw error not matching ' + errMsg + , 'expected #{this} to throw error matching #{exp} but got #{act}' + , 'expected #{this} to throw error not matching #{exp}' + , errMsg + , message ); + return this; } else if ((message != null) && errMsg && 'string' === typeof errMsg) { this.assert( @@ -1067,6 +1080,7 @@ module.exports = function (chai, _) { , errMsg , message ); + return this; } else { thrown = true; @@ -1075,20 +1089,22 @@ module.exports = function (chai, _) { } var actuallyGot = '' - , expectedThrown = name + , expectedThrown = name !== null ? name : desiredError - ? _.inspect(desiredError) + ? '#{exp}' //_.inspect(desiredError) : 'an error'; if (thrown) { - actuallyGot = ' but ' + _.inspect(thrownError) + ' was thrown' + actuallyGot = ' but #{act} was thrown' } this.assert( thrown === true , 'expected #{this} to throw ' + expectedThrown + actuallyGot , 'expected #{this} to not throw ' + expectedThrown + actuallyGot + , desiredError + , thrownError ); }; @@ -1121,7 +1137,7 @@ module.exports = function (chai, _) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object') , itself = flag(this, 'itself') - , context = ('function' === typeof obj && !itself) + , context = ('function' === _.type(obj) && !itself) ? obj.prototype[method] : obj[method]; @@ -1170,8 +1186,8 @@ module.exports = function (chai, _) { var obj = flag(this, 'object'); this.assert( matcher(obj) - , 'expected #{this} to satisfy ' + _.inspect(matcher) - , 'expected #{this} to not satisfy' + _.inspect(matcher) + , 'expected #{this} to satisfy ' + _.objDisplay(matcher) + , 'expected #{this} to not satisfy' + _.objDisplay(matcher) , this.negate ? false : true , matcher(obj) );
assertions: refactor some assertions to use objDisplay instead of inspect
chaijs_chai
train
a029748f1812501f11a7171bb2332f95acfe88f9
diff --git a/test/unit/gateways/quickbooks_test.rb b/test/unit/gateways/quickbooks_test.rb index <HASH>..<HASH> 100644 --- a/test/unit/gateways/quickbooks_test.rb +++ b/test/unit/gateways/quickbooks_test.rb @@ -1,15 +1,15 @@ require 'test_helper' class QuickBooksTest < Test::Unit::TestCase + include CommStub + def setup @gateway = QuickbooksGateway.new( - options = { consumer_key: 'consumer_key', consumer_secret: 'consumer_secret', access_token: 'access_token', token_secret: 'token_secret', realm: 'realm_ID', - } ) @credit_card = credit_card @@ -38,7 +38,7 @@ class QuickBooksTest < Test::Unit::TestCase response = @gateway.purchase(@amount, @credit_card, @options) assert_failure response - assert_equal Gateway::STANDARD_ERROR_CODE[:card_declined], response.error_code + assert_equal Gateway::STANDARD_ERROR_CODE[:processing_error], response.error_code end def test_successful_authorize @@ -51,7 +51,7 @@ class QuickBooksTest < Test::Unit::TestCase end def test_failed_authorize - @gateway.expects(:ssl_post).returns(failed_purchase_response) + @gateway.expects(:ssl_post).returns(failed_authorize_response) response = @gateway.authorize(@amount, @credit_card, @options) assert_failure response @@ -66,27 +66,65 @@ class QuickBooksTest < Test::Unit::TestCase end def test_failed_capture + @gateway.expects(:ssl_post).returns(failed_capture_response) + + response = @gateway.capture(@amount, @authorization) + assert_failure response end def test_successful_refund + @gateway.expects(:ssl_post).returns(successful_refund_response) + + response = @gateway.refund(@amount, @authorization) + assert_success response end def test_failed_refund + @gateway.expects(:ssl_post).returns(failed_refund_response) + + response = @gateway.refund(@amount, @authorization) + assert_failure response end def test_successful_void + @gateway.expects(:ssl_request).returns(successful_authorize_response) + @gateway.expects(:ssl_post).returns(successful_void_response) + + response = @gateway.void(@authorization) + assert_success response end def test_failed_void + response = stub_comms do + @gateway.void(@authorization) + end.respond_with(failed_void_response) + + assert_failure response end def test_successful_verify + response = stub_comms do + @gateway.verify(@credit_card) + end.respond_with(successful_authorize_response, successful_void_response) + + assert_success response end def test_successful_verify_with_failed_void + response = stub_comms do + @gateway.verify(@credit_card, @options) + end.respond_with(successful_authorize_response, failed_void_response) + + assert_success response end def test_failed_verify + response = stub_comms do + @gateway.verify(@credit_card, @options) + end.respond_with(failed_authorize_response, successful_void_response) + + assert_failure response + assert_not_nil response.message end def test_scrub @@ -220,6 +258,28 @@ class QuickBooksTest < Test::Unit::TestCase end def successful_refund_response + <<-RESPONSE + { + "created": "2014-09-23T01:49:12Z", + "status": "ISSUED", + "amount": "5.00", + "description": "first refund", + "id": "EMU891209421", + "context": { + "tax": "0.00", + "recurring": false, + "deviceInfo": { + "id": "", + "type": "", + "longitude": "", + "latitude": "", + "phoneNumber": "", + "macAddress": "", + "ipAddress": "" + } + } + } + RESPONSE end def failed_refund_response @@ -237,7 +297,28 @@ class QuickBooksTest < Test::Unit::TestCase end def successful_void_response - + <<-RESPONSE + { + "created": "2014-09-23T01:49:12Z", + "status": "ISSUED", + "amount": "5.00", + "description": "first refund", + "id": "EMU891209421", + "context": { + "tax": "0.00", + "recurring": false, + "deviceInfo": { + "id": "", + "type": "", + "longitude": "", + "latitude": "", + "phoneNumber": "", + "macAddress": "", + "ipAddress": "" + } + } + } + RESPONSE end def failed_void_response
use CommStub for MultiResponse-based tests, add API response stubs, add unit tests for transactional methods
activemerchant_active_merchant
train
c15ff7cc667ca069d138c0f15c08df3953c53d55
diff --git a/endless_pagination/tests/integration/__init__.py b/endless_pagination/tests/integration/__init__.py index <HASH>..<HASH> 100644 --- a/endless_pagination/tests/integration/__init__.py +++ b/endless_pagination/tests/integration/__init__.py @@ -17,6 +17,8 @@ from endless_pagination.utils import PYTHON3 SKIP_SELENIUM = os.getenv('SKIP_SELENIUM', False) +# FIXME: do not exclude integration tests on Python3 once Selenium is updated +# (bug #17). tests_are_run = not (PYTHON3 or SKIP_SELENIUM) @@ -40,6 +42,8 @@ def teardown_package(): SeleniumTestCase.selenium.quit() +# FIXME: do not exclude integration tests on Python3 once Selenium is updated +# (bug #17). @unittest.skipIf( PYTHON3, 'excluding integration tests: Python 3 tests are still not supported.') @@ -98,10 +102,10 @@ class SeleniumTestCase(LiveServerTestCase): def get_current_elements(self, class_name, driver=None): """Return the range of current elements as a list of numbers.""" elements = [] - path = '//div[contains(@class, "{0}")]/h4'.format(class_name) + selector = 'div.{0} > h4'.format(class_name) if driver is None: driver = self.selenium - for element in driver.find_elements_by_xpath(path): + for element in driver.find_elements_by_css_selector(selector): elements.append(int(element.text.split()[1])) return elements diff --git a/tests/develop.py b/tests/develop.py index <HASH>..<HASH> 100644 --- a/tests/develop.py +++ b/tests/develop.py @@ -8,11 +8,11 @@ import sys if sys.version_info[0] >= 3: # FIXME: a different requirements file will no longer be required once - # Django 1.5 is released. + # Django 1.5 is released (bug #15). REQUIREMENTS_FILE = 'test-requires3.pip' VENV_NAME = '.venv3' # FIXME: running 2to3 on django-nose will no longer be required once - # the project supports Python 3. + # the project supports Python 3 (bug #16). PATCH_DJANGO_NOSE = True else: REQUIREMENTS_FILE = 'test-requires.pip' @@ -39,7 +39,7 @@ def pip_install(*args): def patch_django_nose(): """Run 2to3 on django-nose and remove ``import new`` from its runner.""" - # FIXME: delete once django-nose supports Python 3. + # FIXME: delete once django-nose supports Python 3 (bug #16). python = 'python' + '.'.join(map(str, sys.version_info[:2])) django_nose = os.path.join( VENV, 'lib', python, 'site-packages', 'django_nose') @@ -54,6 +54,6 @@ def patch_django_nose(): if __name__ == '__main__': call('virtualenv', '--distribute', '-p', sys.executable, VENV) pip_install('-r', REQUIREMENTS) - # FIXME: delete from now on once django-nose supports Python 3. + # FIXME: delete from now on once django-nose supports Python 3 (bug #16). if PATCH_DJANGO_NOSE: patch_django_nose() diff --git a/tests/test-requires3.pip b/tests/test-requires3.pip index <HASH>..<HASH> 100644 --- a/tests/test-requires3.pip +++ b/tests/test-requires3.pip @@ -1,6 +1,6 @@ # Django Endless Pagination test requirements for Python 3. # Dependencies are installed by the ``make`` command. -# FIXME: this file can be deleted once Django 1.5 is released. +# FIXME: this file can be deleted once Django 1.5 is released (bug #15). coverage https://www.djangoproject.com/download/1.5c1/tarball/
Selenium tests: replaced xpaths with css selectors.
frankban_django-endless-pagination
train
55351ce27345edb862cecce2b645f8d918994525
diff --git a/lib/mongo/collection.rb b/lib/mongo/collection.rb index <HASH>..<HASH> 100644 --- a/lib/mongo/collection.rb +++ b/lib/mongo/collection.rb @@ -1027,7 +1027,7 @@ module Mongo if RUBY_VERSION < '1.9' && !spec.is_a?(BSON::OrderedHash) raise MongoArgumentError, "Must used OrderedHash in Ruby < 1.9.0" else - field_spec = BSON::OrderedHash.try_convert(spec) + field_spec = spec.is_a?(BSON::OrderedHash) ? spec : BSON::OrderedHash.try_convert(spec) end elsif spec.is_a?(Array) && spec.all? {|field| field.is_a?(Array) } spec.each do |f| diff --git a/test/unit/collection_test.rb b/test/unit/collection_test.rb index <HASH>..<HASH> 100644 --- a/test/unit/collection_test.rb +++ b/test/unit/collection_test.rb @@ -149,9 +149,17 @@ class CollectionTest < Test::Unit::TestCase a == {"x"=>-1, "y"=>-1} end - @coll.ensure_index({"x" => Mongo::DESCENDING, "y" => Mongo::DESCENDING}) + if RUBY_VERSION > '1.9' + @coll.ensure_index({"x" => Mongo::DESCENDING, "y" => Mongo::DESCENDING}) + else + ordered_hash = BSON::OrderedHash.new + ordered_hash['x'] = Mongo::DESCENDING + ordered_hash['y'] = Mongo::DESCENDING + @coll.ensure_index(ordered_hash) + end end + should "use the connection's logger" do @client = MongoClient.new('localhost', 27017, :logger => @logger, :connect => false) @db = @client['testing']
RUBY-<I> now with <I> support
mongodb_mongo-ruby-driver
train
94270b85e6976e9f9edeff5346bc1d1099beaab1
diff --git a/bql/planner/planner_test.go b/bql/planner/planner_test.go index <HASH>..<HASH> 100644 --- a/bql/planner/planner_test.go +++ b/bql/planner/planner_test.go @@ -760,19 +760,21 @@ func TestPlannerQuery(t *testing.T) { s, ctx := memory.NewStore(), context.Background() populateStoreWithTriples(ctx, s, "?test", testTriples, t) for _, entry := range testTable { + // Test setup: p, err := grammar.NewParser(grammar.SemanticBQL()) if err != nil { t.Fatalf("grammar.NewParser should have produced a valid BQL parser but got error: %v", err) } - st := &semantic.Statement{} if err := p.Parse(grammar.NewLLk(entry.q, 1), st); err != nil { - t.Errorf("parser.Parse(%s)\n= %v; want nil error", entry.q, err) + t.Fatalf("parser.Parse failed for query \"%s\"\nwith error: %v", entry.q, err) } plnr, err := New(ctx, s, st, 0, 10, nil) if err != nil { - t.Errorf("planner.New() = _, %v; want nil error", err) + t.Fatalf("planner.New failed to create a valid query plan with error: %v", err) } + + // Actual test: tbl, err := plnr.Execute(ctx) if !entry.wantErr && err != nil { t.Errorf("planner.Execute(%s)\n= _, %v; want nil error", entry.q, err)
Separate better the setup from the actual test inside "planner_test.go"
google_badwolf
train
0cea26e862dcfe0524e06de6f6acbd655d8e2d7a
diff --git a/system/Debug/Toolbar/Views/toolbar.js b/system/Debug/Toolbar/Views/toolbar.js index <HASH>..<HASH> 100644 --- a/system/Debug/Toolbar/Views/toolbar.js +++ b/system/Debug/Toolbar/Views/toolbar.js @@ -507,29 +507,48 @@ var ciDebugBar = { setToolbarTheme: function () { var btnTheme = document.getElementById('toolbar-theme'); + var isDarkMode = window.matchMedia("(prefers-color-scheme: dark)").matches; + var isLightMode = window.matchMedia("(prefers-color-scheme: light)").matches; + // If a cookie is set with a value, we force the color scheme if (ciDebugBar.readCookie('debug-bar-theme') === 'dark') { - ciDebugBar.addClass(ciDebugBar.icon, 'dark'); + ciDebugBar.removeClass(ciDebugBar.toolbar, 'light'); ciDebugBar.addClass(ciDebugBar.toolbar, 'dark'); } + else if (ciDebugBar.readCookie('debug-bar-theme') === 'light') + { + ciDebugBar.removeClass(ciDebugBar.toolbar, 'dark'); + ciDebugBar.addClass(ciDebugBar.toolbar, 'light'); + } btnTheme.addEventListener('click', function () { var theme = ciDebugBar.readCookie('debug-bar-theme'); - ciDebugBar.createCookie('debug-bar-theme', '', -1); - - if (!theme || theme === 'light') + if (!theme && window.matchMedia("(prefers-color-scheme: dark)").matches) { - ciDebugBar.createCookie('debug-bar-theme', 'dark', 365); - ciDebugBar.addClass(ciDebugBar.icon, 'dark'); - ciDebugBar.addClass(ciDebugBar.toolbar, 'dark'); + // If there is no cookie, and "prefers-color-scheme" is set to "dark" + // It means that the user wants to switch to light mode + ciDebugBar.createCookie('debug-bar-theme', 'light', 365); + ciDebugBar.removeClass(ciDebugBar.toolbar, 'dark'); + ciDebugBar.addClass(ciDebugBar.toolbar, 'light'); } else { - ciDebugBar.createCookie('debug-bar-theme', 'light', 365); - ciDebugBar.removeClass(ciDebugBar.icon, 'dark'); - ciDebugBar.removeClass(ciDebugBar.toolbar, 'dark'); + if (theme === 'dark') + { + ciDebugBar.createCookie('debug-bar-theme', 'light', 365); + ciDebugBar.removeClass(ciDebugBar.toolbar, 'dark'); + ciDebugBar.addClass(ciDebugBar.toolbar, 'light'); + } + else + { + // In any other cases: if there is no cookie, or the cookie is set to + // "light", or the "prefers-color-scheme" is "light"... + ciDebugBar.createCookie('debug-bar-theme', 'dark', 365); + ciDebugBar.removeClass(ciDebugBar.toolbar, 'light'); + ciDebugBar.addClass(ciDebugBar.toolbar, 'dark'); + } } }, true); },
Improved JS to manage special cases with dark/light mode
codeigniter4_CodeIgniter4
train
561aa11bd1203deb506cfaa14f5cab43293f0163
diff --git a/lib/rsvp/version.rb b/lib/rsvp/version.rb index <HASH>..<HASH> 100644 --- a/lib/rsvp/version.rb +++ b/lib/rsvp/version.rb @@ -1,3 +1,3 @@ module Rsvp - VERSION = "0.2.3" + VERSION = "0.2.4" end
Version bump. Removed rogue migration in build <I>.
ryanricard_rsvp
train
7896520bce05beaa9abaa47445ef089b74cb1ba5
diff --git a/zipline/utils/sentinel.py b/zipline/utils/sentinel.py index <HASH>..<HASH> 100644 --- a/zipline/utils/sentinel.py +++ b/zipline/utils/sentinel.py @@ -4,6 +4,7 @@ Construction of sentinel objects. Sentinel objects are used when you only care to check for object identity. """ import sys +from textwrap import dedent def sentinel(name, doc=None): @@ -15,10 +16,15 @@ def sentinel(name, doc=None): if doc == value.__doc__: return value - raise ValueError( - 'attempted to create sentinel with a used name and a different' - ' docstring: %r\noriginal docstring:\n%s' % (name, value.__doc__), - ) + raise ValueError(dedent( + """\ + New sentinel value %r conflicts with an existing sentinel of the + same name. + Old sentinel docstring: %r + New sentinel docstring: %r + Resolve this conflict by changing the name of one of the sentinels. + """, + ) % (name, value.__doc__, doc)) @object.__new__ # bind a single instance to the name 'Sentinel' class Sentinel(object): @@ -45,7 +51,7 @@ def sentinel(name, doc=None): try: # traverse up one frame to find the module where this is defined cls.__module__ = sys._getframe(1).f_globals['__name__'] - except (AttributeError, ValueError, KeyError): + except (ValueError, KeyError): # Couldn't get the name from the calling scope, just use None. cls.__module__ = None
ENH: better error and don't catch attrerror
quantopian_zipline
train
03741aca3894af6f24b2c88fee0aa42b86b7ea54
diff --git a/src/Models/CatalogGroup.js b/src/Models/CatalogGroup.js index <HASH>..<HASH> 100644 --- a/src/Models/CatalogGroup.js +++ b/src/Models/CatalogGroup.js @@ -57,6 +57,11 @@ var CatalogGroup = function(application) { */ this.items = []; + /** + * Gets or sets flag to prevent items in group being sorted. Subgroups will still sort unless their own preserveOrder flag is set. + */ + this.preserveOrder = false; + knockout.track(this, ['isOpen', 'isLoading', 'items']); var that = this; @@ -112,7 +117,7 @@ defineProperties(CatalogGroup.prototype, { */ sortItemsOnLoad : { get : function() { - return true; + return true; // Even if preserveOrder is set, the process of sorting should take place. } }, @@ -371,9 +376,12 @@ CatalogGroup.prototype.findFirstItemByName = function(name) { */ CatalogGroup.prototype.sortItems = function(sortRecursively) { naturalSort.insensitive = true; - this.items.sort(function(a, b) { - return naturalSort(a.name, b.name); - }); + // Allow a group to be non-sorted, while still containing sorted groups. + if (!this.preserveOrder) { + this.items.sort(function(a, b) { + return naturalSort(a.name, b.name); + }); + } if (defaultValue(sortRecursively, false)) { for (var i = 0; i < this.items.length; ++i) {
Add "preserveOrder" flag to CatalogGroup.
TerriaJS_terriajs
train
383a41698e80f7d9d61069454ce6928f7e18be81
diff --git a/tests/Integration/Suites/FrontendRenderingTest.php b/tests/Integration/Suites/FrontendRenderingTest.php index <HASH>..<HASH> 100644 --- a/tests/Integration/Suites/FrontendRenderingTest.php +++ b/tests/Integration/Suites/FrontendRenderingTest.php @@ -5,7 +5,7 @@ namespace Brera; use Brera\Environment\VersionedEnvironment; use Brera\Http\HttpUrl; use Brera\DataPool\DataPoolReader; -use Brera\KeyValue\InMemory\InMemoryKeyValueStore; +use Brera\DataPool\KeyValue\InMemory\InMemoryKeyValueStore; use Brera\DataPool\SearchEngine\InMemorySearchEngine; use Brera\DataPool\KeyValue\KeyValueStore;
Issue #<I>: Change data pool namespace (sorry)
lizards-and-pumpkins_catalog
train
3db05a1e66c1e061c3e6db3176a635ff2c00a236
diff --git a/xchange-btcturk/src/main/java/org/knowm/xchange/btcturk/BTCTurkExchange.java b/xchange-btcturk/src/main/java/org/knowm/xchange/btcturk/BTCTurkExchange.java index <HASH>..<HASH> 100644 --- a/xchange-btcturk/src/main/java/org/knowm/xchange/btcturk/BTCTurkExchange.java +++ b/xchange-btcturk/src/main/java/org/knowm/xchange/btcturk/BTCTurkExchange.java @@ -21,12 +21,9 @@ public class BTCTurkExchange extends BaseExchange implements Exchange { @Override protected void initServices() { - this.marketDataService = new BTCTurkMarketDataService(this); - if (exchangeSpecification.getApiKey() != null) { - this.accountService = new BTCTurkAccountService(this); - this.tradeService = new BTCTurkTradeService(this); - } + this.accountService = new BTCTurkAccountService(this); + this.tradeService = new BTCTurkTradeService(this); } @Override
Fixed NULL Error for Authenticated Services If the api key is defined after running "ExchangeFactory.INSTANCE.createExchange" command, authenticated services were null.
knowm_XChange
train
cb7756a6f5b62a772b48d0cf39354dd0dedee2c2
diff --git a/pghoard/pghoard.py b/pghoard/pghoard.py index <HASH>..<HASH> 100644 --- a/pghoard/pghoard.py +++ b/pghoard/pghoard.py @@ -355,17 +355,20 @@ class PGHoard: last_backup_time = None site_config = self.config["backup_sites"][site] - basebackups_to_delete = self.determine_backups_to_delete(basebackups=basebackups, site_config=site_config) - - for basebackup_to_be_deleted in basebackups_to_delete: - pg_version = basebackup_to_be_deleted["metadata"].get("pg-version") - last_wal_segment_still_needed = 0 - if basebackups: - last_wal_segment_still_needed = basebackups[0]["metadata"]["start-wal-segment"] - - if last_wal_segment_still_needed: - self.delete_remote_wal_before(last_wal_segment_still_needed, site, pg_version) - self.delete_remote_basebackup(site, basebackup_to_be_deleted["name"], basebackup_to_be_deleted["metadata"]) + # Never delete backups from a recovery site. This check is already elsewhere as well + # but still check explicitly here to ensure we certainly won't delete anything unexpectedly + if site_config["active"]: + basebackups_to_delete = self.determine_backups_to_delete(basebackups=basebackups, site_config=site_config) + + for basebackup_to_be_deleted in basebackups_to_delete: + pg_version = basebackup_to_be_deleted["metadata"].get("pg-version") + last_wal_segment_still_needed = 0 + if basebackups: + last_wal_segment_still_needed = basebackups[0]["metadata"]["start-wal-segment"] + + if last_wal_segment_still_needed: + self.delete_remote_wal_before(last_wal_segment_still_needed, site, pg_version) + self.delete_remote_basebackup(site, basebackup_to_be_deleted["name"], basebackup_to_be_deleted["metadata"]) self.state["backup_sites"][site]["basebackups"] = basebackups return last_backup_time
Add explicit site active check before deleting anything This is already checked in `handle_site` but to make the code more resilient for future bugs explicitly check the state before proceeding with any deletes.
aiven_pghoard
train
d6d343865bc7c915ec7f6222b436a28eeedf23e2
diff --git a/core/server/config/index.js b/core/server/config/index.js index <HASH>..<HASH> 100644 --- a/core/server/config/index.js +++ b/core/server/config/index.js @@ -43,6 +43,7 @@ _private.loadNconf = function loadNconf(options) { nconf.isPrivacyDisabled = localUtils.isPrivacyDisabled.bind(nconf); nconf.getContentPath = localUtils.getContentPath.bind(nconf); nconf.sanitizeDatabaseProperties = localUtils.sanitizeDatabaseProperties.bind(nconf); + nconf.doesContentPathExist = localUtils.doesContentPathExist.bind(nconf); nconf.sanitizeDatabaseProperties(); nconf.makePathsAbsolute(nconf.get('paths'), 'paths'); @@ -55,6 +56,11 @@ _private.loadNconf = function loadNconf(options) { nconf.checkUrlProtocol(); /** + * Ensure that the content path exists + */ + nconf.doesContentPathExist(); + + /** * values we have to set manual */ nconf.set('env', env); diff --git a/core/server/config/utils.js b/core/server/config/utils.js index <HASH>..<HASH> 100644 --- a/core/server/config/utils.js +++ b/core/server/config/utils.js @@ -1,4 +1,5 @@ var path = require('path'), + fs = require('fs-extra'), _ = require('lodash'); exports.isPrivacyDisabled = function isPrivacyDisabled(privacyFlag) { @@ -69,6 +70,16 @@ exports.getContentPath = function getContentPath(type) { }; /** + * @TODO: + * - content/logs folder is required right now, otherwise Ghost want start + */ +exports.doesContentPathExist = function doesContentPathExist() { + if (!fs.pathExistsSync(this.get('paths:contentPath'))) { + throw new Error('Your content path does not exist! Please double check `paths.contentPath` in your custom config file e.g. config.production.json.'); + } +}; + +/** * Check if the URL in config has a protocol and sanitise it if not including a warning that it should be changed */ exports.checkUrlProtocol = function checkUrlProtocol() { diff --git a/core/test/unit/config/index_spec.js b/core/test/unit/config/index_spec.js index <HASH>..<HASH> 100644 --- a/core/test/unit/config/index_spec.js +++ b/core/test/unit/config/index_spec.js @@ -22,6 +22,10 @@ describe('Config', function () { originalEnv = _.clone(process.env); originalArgv = _.clone(process.argv); config = rewire('../../../server/config'); + + // we manually call `loadConf` in the tests and we need to ensure that the minimum + // required config properties are available + process.env['paths__contentPath'] = 'content/'; }); afterEach(function () {
🎨 show clearer error for wrong content path (#<I>) no issue
TryGhost_Ghost
train
4ef5d37433bb86ee0218ca54828dab08a19eeecf
diff --git a/system-test/storage.js b/system-test/storage.js index <HASH>..<HASH> 100644 --- a/system-test/storage.js +++ b/system-test/storage.js @@ -1671,7 +1671,7 @@ describe('storage', function() { upload({interrupt: false}, function(err) { assert.ifError(err); - assert.strictEqual(file.metadata.size, fileSize); + assert.strictEqual(Number(file.metadata.size), fileSize); file.delete(done); }); }); @@ -1727,7 +1727,7 @@ describe('storage', function() { assert.ifError(err); fs.readFile(tmpFilePath, function(err, data) { - assert.strictEqual(data, fileContent); + assert.strictEqual(data.toString(), fileContent); done(); }); }); @@ -2301,7 +2301,10 @@ describe('storage', function() { destinationFile.download(function(err, contents) { assert.ifError(err); - assert.strictEqual(contents, files.map(prop('contents')).join('')); + assert.strictEqual( + contents.toString(), + files.map(prop('contents')).join('') + ); async.each(sourceFiles.concat([destinationFile]), deleteFile, done); }); @@ -2471,7 +2474,7 @@ describe('storage', function() { firstGenFile.download(function(err, contents) { assert.ifError(err); - assert.strictEqual(contents, 'a'); + assert.strictEqual(contents.toString(), 'a'); done(); }); }); @@ -2532,7 +2535,7 @@ describe('storage', function() { assert.ifError(err); request.get(signedReadUrl, function(err, resp, body) { assert.ifError(err); - assert.strictEqual(body, localFile); + assert.strictEqual(body, localFile.toString()); file.delete(done); }); }
Fix system tests for string comparisons (#<I>) * test: fix buffer-string comparisons * npm run prettier
googleapis_nodejs-storage
train
5c6aad6d5c78d80283c8d5b0238c180576ae1416
diff --git a/operator/crd_test.go b/operator/crd_test.go index <HASH>..<HASH> 100644 --- a/operator/crd_test.go +++ b/operator/crd_test.go @@ -112,13 +112,6 @@ func (s *crdTestSuite) TestGetCRD(c *C) { err = waitForCRD(context.TODO(), client, "bar") c.Assert(err, ErrorMatches, ".*timeout waiting for CRD bar.*") - err = client.ApiextensionsV1().CustomResourceDefinitions().Delete( - context.TODO(), - v1CRD.GetName(), - metav1.DeleteOptions{}, - ) - c.Assert(err, IsNil) - // v1beta1 CRDs _, err = client.ApiextensionsV1beta1().CustomResourceDefinitions().Create( @@ -139,11 +132,4 @@ func (s *crdTestSuite) TestGetCRD(c *C) { err = waitForCRD(context.TODO(), client, "bar") c.Assert(err, ErrorMatches, ".*timeout waiting for CRD bar.*") - - err = client.ApiextensionsV1beta1().CustomResourceDefinitions().Delete( - context.TODO(), - v1beta1CRD.GetName(), - metav1.DeleteOptions{}, - ) - c.Assert(err, IsNil) } diff --git a/pkg/k8s/apis/cilium.io/v2/client/register.go b/pkg/k8s/apis/cilium.io/v2/client/register.go index <HASH>..<HASH> 100644 --- a/pkg/k8s/apis/cilium.io/v2/client/register.go +++ b/pkg/k8s/apis/cilium.io/v2/client/register.go @@ -441,17 +441,6 @@ func waitForV1CRD( return false, err }) if err != nil { - if deleteErr := client.CustomResourceDefinitions().Delete( - context.TODO(), - crd.ObjectMeta.Name, - metav1.DeleteOptions{}, - ); deleteErr != nil { - scopedLog.WithError(err).WithFields(logrus.Fields{ - "deleteErr": deleteErr, - }).Error("Failed to delete CRD") - return fmt.Errorf("unable to delete CRD: %w", deleteErr) - } - return fmt.Errorf("error occurred waiting for CRD: %w", err) } diff --git a/pkg/k8s/apis/cilium.io/v2/client/v1beta1.go b/pkg/k8s/apis/cilium.io/v2/client/v1beta1.go index <HASH>..<HASH> 100644 --- a/pkg/k8s/apis/cilium.io/v2/client/v1beta1.go +++ b/pkg/k8s/apis/cilium.io/v2/client/v1beta1.go @@ -234,17 +234,6 @@ func waitForV1beta1CRD( return false, err }) if err != nil { - if deleteErr := client.CustomResourceDefinitions().Delete( - context.TODO(), - crd.ObjectMeta.Name, - metav1.DeleteOptions{}, - ); deleteErr != nil { - scopedLog.WithError(err).WithFields(logrus.Fields{ - "deleteErr": deleteErr, - }).Error("Failed to delete CRD") - return fmt.Errorf("unable to delete CRD: %w", deleteErr) - } - return fmt.Errorf("error occurred waiting for CRD: %w", err) }
k8s: Remove CRD deleting functionality This commit removes the ability to delete CRDs from Cilium because that would delete all the CRs in the cluster. Follow-up from: <URL>
cilium_cilium
train
db094f9b92cf8c844e61ece19caf294bd58cf37c
diff --git a/tools/validator.py b/tools/validator.py index <HASH>..<HASH> 100755 --- a/tools/validator.py +++ b/tools/validator.py @@ -23,37 +23,30 @@ class ArtifactDefinitionsValidator(object): _MACOS_PRIVATE_SUB_PATHS = ('etc', 'tftpboot', 'tmp', 'var') + _SUPPORTED_ENVIRONMENT_VARIABLES = [ + '%%environ_allusersappdata%%', + '%%environ_allusersprofile%%', + '%%environ_programfiles%%', + '%%environ_programfilesx86%%', + '%%environ_systemdrive%%', + '%%environ_systemroot%%', + '%%environ_windir%%'] + + _SUPPORTED_USER_VARIABLES = [ + '%%users.appdata%%', + '%%users.homedir%%', + '%%users.localappdata%%', + '%%users.sid%%', + '%%users.temp%%', + '%%users.username%%', + '%%users.userprofile%%'] + def __init__(self): """Initializes an artifact definitions validator.""" super(ArtifactDefinitionsValidator, self).__init__() self._artifact_registry = registry.ArtifactDefinitionsRegistry() self._artifact_registry_key_paths = set() - def _CheckRegistryKeyPath(self, filename, artifact_definition, key_path): - """Checks a Windows Registry key path. - - Args: - filename (str): name of the artifacts definition file. - artifact_definition (ArtifactDefinition): artifact definition. - key_path (str): key path. - - Returns: - bool: True if the Registry key path is valid. - """ - result = True - key_path = key_path.upper() - - if key_path.startswith('%%CURRENT_CONTROL_SET%%'): - result = False - logging.warning(( - 'Artifact definition: {0:s} in file: {1:s} contains Windows ' - 'Registry key path that starts with ' - '%%CURRENT_CONTROL_SET%%. Replace %%CURRENT_CONTROL_SET%% with ' - 'HKEY_LOCAL_MACHINE\\System\\CurrentControlSet').format( - artifact_definition.name, filename)) - - return result - def _CheckMacOSPaths(self, filename, artifact_definition, source, paths): """Checks if the paths are valid MacOS paths. @@ -204,6 +197,57 @@ class ArtifactDefinitionsValidator(object): return result + def _CheckWindowsRegistryKeyPath( + self, filename, artifact_definition, key_path): + """Checks if a path is a valid Windows Registry key path. + + Args: + filename (str): name of the artifacts definition file. + artifact_definition (ArtifactDefinition): artifact definition. + key_path (str): Windows Registry key path to validate. + + Returns: + bool: True if the Windows Registry key path is valid. + """ + result = True + key_path_segments = key_path.lower().split('\\') + + if key_path_segments[0] == '%%current_control_set%%': + result = False + logging.warning(( + 'Artifact definition: {0:s} in file: {1:s} contains Windows ' + 'Registry key path that starts with ' + '%%CURRENT_CONTROL_SET%%. Replace %%CURRENT_CONTROL_SET%% with ' + 'HKEY_LOCAL_MACHINE\\System\\CurrentControlSet').format( + artifact_definition.name, filename)) + + for segment_index, key_path_segment in enumerate(key_path_segments): + if key_path_segment.startswith('%%') and key_path_segment.endswith('%%'): + if (segment_index == 1 and key_path_segment == '%%users.sid%%' and + key_path_segments[0] == 'hkey_users'): + continue + + if key_path_segment in self._SUPPORTED_ENVIRONMENT_VARIABLES: + result = False + logging.warning(( + 'Artifact definition: {0:s} in file: {1:s} contains Windows ' + 'Registry key path that contains an environment variable: ' + '"{2:s}". Usage of environment variables in key paths is not ' + 'encouraged at this time.').format( + artifact_definition.name, filename, key_path_segment)) + + if key_path_segment in self._SUPPORTED_USER_VARIABLES: + result = False + logging.warning(( + 'Artifact definition: {0:s} in file: {1:s} contains Windows ' + 'Registry key path that contains a users variable: "{2:s}". ' + 'Usage of users variables in key paths, except for ' + '"HKEY_USERS\\%%users.sid%%", is not encouraged at this ' + 'time.').format( + artifact_definition.name, filename, key_path_segment)) + + return result + def _HasDuplicateRegistryKeyPaths( self, filename, artifact_definition, source): """Checks if Registry key paths are not already defined by other artifacts. @@ -292,7 +336,7 @@ class ArtifactDefinitionsValidator(object): result = False for key_path in source.keys: - if not self._CheckRegistryKeyPath( + if not self._CheckWindowsRegistryKeyPath( filename, artifact_definition, key_path): result = False @@ -300,7 +344,7 @@ class ArtifactDefinitionsValidator(object): definitions.TYPE_INDICATOR_WINDOWS_REGISTRY_VALUE): for key_value_pair in source.key_value_pairs: - if not self._CheckRegistryKeyPath( + if not self._CheckWindowsRegistryKeyPath( filename, artifact_definition, key_value_pair['key']): result = False
Validate environment and users variables in Registry key paths (#<I>)
ForensicArtifacts_artifacts
train
5243b7c6e77de8fbaf499f1ae007abd48d466580
diff --git a/flap/__init__.py b/flap/__init__.py index <HASH>..<HASH> 100644 --- a/flap/__init__.py +++ b/flap/__init__.py @@ -18,7 +18,7 @@ from logging import getLogger, FileHandler, Formatter, DEBUG __tool_name__ = "FLaP" -__version__ = "0.4.2" +__version__ = "0.5.0" def _configure_logger():
Releasing version <I>
fchauvel_flap
train
0293f958c989d9abb7e436c8933961e59154ee66
diff --git a/lib/client.js b/lib/client.js index <HASH>..<HASH> 100644 --- a/lib/client.js +++ b/lib/client.js @@ -53,7 +53,7 @@ var StoreSchema = require('./commands/yokozuna/storeschema'); * * @class Client * @constructor - * @param {Object} cluster - the cluster to use. + * @param {Object} cluster - the cluster to use. See {{#crossLink "RiakCluster"}}{{/crossLink}}. */ function Client(cluster) { this.cluster = cluster; @@ -65,6 +65,7 @@ function Client(cluster) { */ /** + * See {{#crossLink "RiakCluster/execute:method"}}RiakCluster#execute{{/crossLink}} * @method execute */ Client.prototype.execute = function(command) { @@ -72,6 +73,7 @@ Client.prototype.execute = function(command) { }; /** + * See {{#crossLink "Ping"}}{{/crossLink}} * @method ping */ Client.prototype.ping = function(callback) { @@ -80,6 +82,7 @@ Client.prototype.ping = function(callback) { }; /** + * See {{#crossLink "DeleteValue"}}{{/crossLink}} * @method DeleteValue */ Client.prototype.DeleteValue = function(options) { @@ -88,6 +91,7 @@ Client.prototype.DeleteValue = function(options) { }; /** + * See {{#crossLink "FetchBucketProps"}}{{/crossLink}} * @method FetchBucketProps */ Client.prototype.FetchBucketProps = function(options) { @@ -96,6 +100,7 @@ Client.prototype.FetchBucketProps = function(options) { }; /** + * See {{#crossLink "FetchValue"}}{{/crossLink}} * @method FetchValue */ Client.prototype.FetchValue = function(options) { @@ -104,6 +109,7 @@ Client.prototype.FetchValue = function(options) { }; /** + * See {{#crossLink "ListBuckets"}}{{/crossLink}} * @method ListBuckets */ Client.prototype.ListBuckets = function(options) { @@ -112,6 +118,7 @@ Client.prototype.ListBuckets = function(options) { }; /** + * See {{#crossLink "ListKeys"}}{{/crossLink}} * @method ListKeys */ Client.prototype.ListKeys = function(options) { @@ -120,6 +127,7 @@ Client.prototype.ListKeys = function(options) { }; /** + * See {{#crossLink "SecondaryIndexQuery"}}{{/crossLink}} * @method SecondaryIndexQuery */ Client.prototype.SecondaryIndexQuery = function(options) { @@ -128,6 +136,7 @@ Client.prototype.SecondaryIndexQuery = function(options) { }; /** + * See {{#crossLink "StoreBucketProps"}}{{/crossLink}} * @method StoreBucketProps */ Client.prototype.StoreBucketProps = function(options) { @@ -136,6 +145,7 @@ Client.prototype.StoreBucketProps = function(options) { }; /** + * See {{#crossLink "StoreValue"}}{{/crossLink}} * @method StoreValue */ Client.prototype.StoreValue = function(options) { @@ -148,6 +158,7 @@ Client.prototype.StoreValue = function(options) { */ /** + * See {{#crossLink "FetchSet"}}{{/crossLink}} * @method FetchSet */ Client.prototype.FetchSet = function(options) { @@ -158,7 +169,9 @@ Client.prototype.FetchSet = function(options) { /* * YZ methods */ + /** + * See {{#crossLink "DeleteIndex"}}{{/crossLink}} * @method DeleteIndex */ Client.prototype.DeleteIndex = function(options) { @@ -167,6 +180,7 @@ Client.prototype.DeleteIndex = function(options) { }; /** + * See {{#crossLink "FetchIndex"}}{{/crossLink}} * @method FetchIndex */ Client.prototype.FetchIndex = function(options) { @@ -175,6 +189,7 @@ Client.prototype.FetchIndex = function(options) { }; /** + * See {{#crossLink "FetchSchema"}}{{/crossLink}} * @method FetchSchema */ Client.prototype.FetchSchema = function(options) { @@ -183,6 +198,7 @@ Client.prototype.FetchSchema = function(options) { }; /** + * See {{#crossLink "Search"}}{{/crossLink}} * @method Search */ Client.prototype.Search = function(options) { @@ -191,6 +207,7 @@ Client.prototype.Search = function(options) { }; /** + * See {{#crossLink "StoreIndex"}}{{/crossLink}} * @method StoreIndex */ Client.prototype.StoreIndex = function(options) { @@ -199,6 +216,7 @@ Client.prototype.StoreIndex = function(options) { }; /** + * See {{#crossLink "StoreSchema"}}{{/crossLink}} * @method StoreSchema */ Client.prototype.StoreSchema = function(options) { @@ -206,9 +224,7 @@ Client.prototype.StoreSchema = function(options) { this.cluster.execute(cmd); }; -/* - * Poor man's namespaces - */ +// Namespaces function Riak() { } function Commands() { } function KV() { } diff --git a/lib/commands/kv/deletevalue.js b/lib/commands/kv/deletevalue.js index <HASH>..<HASH> 100644 --- a/lib/commands/kv/deletevalue.js +++ b/lib/commands/kv/deletevalue.js @@ -13,11 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + var CommandBase = require('../commandbase'); var inherits = require('util').inherits; var Joi = require('joi'); /** + * Provides the DeleteValue class and its builder + * @module DeleteValue + */ + + +/** * Command used to delete a value from Riak. * * As a convenience, a builder class is provided: @@ -309,4 +316,4 @@ Builder.prototype = { }; module.exports = DeleteValue; -module.exports.Builder = Builder; \ No newline at end of file +module.exports.Builder = Builder;
Documentation tags to refer to command classes and other items done.
basho_riak-nodejs-client
train
00d32d183c5e93ef46292021ea1c70b165cd1c12
diff --git a/src/com/google/javascript/jscomp/J2clPass.java b/src/com/google/javascript/jscomp/J2clPass.java index <HASH>..<HASH> 100644 --- a/src/com/google/javascript/jscomp/J2clPass.java +++ b/src/com/google/javascript/jscomp/J2clPass.java @@ -239,7 +239,7 @@ public class J2clPass implements CompilerPass { /* * Inlines Arrays.$create(), Arrays.$init(), Arrays.$instanceIsOfType(), Arrays.$castTo() and - * Casts.to() so that all references to Object.$isInstance() functions will be fully qualified + * Casts.$to() so that all references to Object.$isInstance() functions will be fully qualified * and easy to strip. */ inlineFunctionsInFile( @@ -247,8 +247,9 @@ public class J2clPass implements CompilerPass { "vmbootstrap/Arrays.impl.java.js", ImmutableSet.of("$create", "$init", "$instanceIsOfType", "$castTo", "$stampType"), InliningMode.DIRECT); + // TODO(b/37722603): remove "to" once the change is done in J2CL. inlineFunctionsInFile( - root, "vmbootstrap/Casts.impl.java.js", ImmutableSet.of("to"), InliningMode.DIRECT); + root, "vmbootstrap/Casts.impl.java.js", ImmutableSet.of("$to", "to"), InliningMode.DIRECT); /* * Inlines all Interface.$markImplementor(FooClass) metaclass calls so that FooClass and others diff --git a/test/com/google/javascript/jscomp/J2clPassTest.java b/test/com/google/javascript/jscomp/J2clPassTest.java index <HASH>..<HASH> 100644 --- a/test/com/google/javascript/jscomp/J2clPassTest.java +++ b/test/com/google/javascript/jscomp/J2clPassTest.java @@ -105,8 +105,11 @@ public class J2clPassTest extends CompilerTestCase { LINE_JOINER.join( // Function definitions and calls are qualified globals. "var Casts = function() {};", - "Casts.to = function() { return 1; }", + "Casts.$to = function() { return 1; }", + // TODO(b/37722603): remove "to" once the change is done in J2CL. + "Casts.to = function() { return 2; }", "", + "alert(Casts.$to());", "alert(Casts.to());"))), Lists.newArrayList( SourceFile.fromCode( @@ -114,9 +117,11 @@ public class J2clPassTest extends CompilerTestCase { LINE_JOINER.join( // Function definitions and calls are qualified globals. "var Casts = function() {};", - "Casts.to = function() { return 1; }", + "Casts.$to = function() { return 1; }", + "Casts.to = function() { return 2; }", "", - "alert(1);")))); + "alert(1);", + "alert(2);")))); // Interface $markImplementor() functions. test( @@ -191,19 +196,28 @@ public class J2clPassTest extends CompilerTestCase { "j2cl/transpiler/vmbootstrap/Casts.impl.java.js", LINE_JOINER.join( // Function definitions and calls are qualified globals. - "var Casts = function() {};", - "Casts.to = function() { return 1; }", + "var $jscomp = {};", + "$jscomp.scope = {};", + "$jscomp.scope.Casts = function() {};", + "$jscomp.scope.Casts.$to = function() { return 1; }", + // TODO(b/37722603): remove "to" once the change is done in J2CL. + "$jscomp.scope.Casts.to = function() { return 2; }", "", - "alert(Casts.to());"))), + "alert($jscomp.scope.Casts.$to());", + "alert($jscomp.scope.Casts.to());"))), Lists.newArrayList( SourceFile.fromCode( "j2cl/transpiler/vmbootstrap/Casts.impl.java.js", LINE_JOINER.join( // Function definitions and calls are qualified globals. - "var Casts = function() {};", - "Casts.to = function() { return 1; }", + "var $jscomp = {};", + "$jscomp.scope = {};", + "$jscomp.scope.Casts = function() {};", + "$jscomp.scope.Casts.$to = function() { return 1; }", + "$jscomp.scope.Casts.to = function() { return 2; }", "", - "alert(1);")))); + "alert(1);", + "alert(2);")))); // Interface $markImplementor() functions. test(
Make J2CL pass inline Casts.to and Casts.$to. This pass is in preparation to rename Casts.to to Casts.$to. J2CL runtime supporting classes should have methods whose names are clearly internal and unlikely to name clash with method names written by users. ------------- Created by MOE: <URL>
google_closure-compiler
train
e2fccafa3c5903bff28b177d7aac8eee7ac4b05f
diff --git a/modules/cms/classes/Controller.php b/modules/cms/classes/Controller.php index <HASH>..<HASH> 100644 --- a/modules/cms/classes/Controller.php +++ b/modules/cms/classes/Controller.php @@ -640,7 +640,7 @@ class Controller list($componentName, $handlerName) = explode('::', $handler); $componentObj = $this->findComponentByName($componentName); - if ($componentObj && method_exists($componentObj, $handlerName)) { + if ($componentObj && $componentObj->methodExists($handlerName)) { $this->componentContext = $componentObj; $result = $componentObj->runAjaxHandler($handlerName); return ($result) ?: true;
allow calling of components extension ajax handlers
octobercms_october
train
e66d513281d5e9f47c5627463a019a9a8906824b
diff --git a/src/components/VInput/VInput.js b/src/components/VInput/VInput.js index <HASH>..<HASH> 100755 --- a/src/components/VInput/VInput.js +++ b/src/components/VInput/VInput.js @@ -172,11 +172,14 @@ export default { } }) }, - genSlot (ref, location, slot) { + genSlot (type, location, slot) { if (!slot.length) return null + const ref = `${type}-${location}` + return this.$createElement('div', { - staticClass: `v-input__${ref}-${location}` + staticClass: `v-input__${ref}`, + ref }, slot) }, genPrependSlot () { diff --git a/src/components/VSelect/VSelect.js b/src/components/VSelect/VSelect.js index <HASH>..<HASH> 100644 --- a/src/components/VSelect/VSelect.js +++ b/src/components/VSelect/VSelect.js @@ -511,7 +511,20 @@ export default { } }, onMouseUp (e) { - if (this.isSolo || this.hasOutline) { + const appendInner = this.$refs['append-inner'] + + // If append inner is present + // and the target is itself + // or inside, toggle menu + if (this.isMenuActive && + appendInner && + (appendInner === e.target || + appendInner.contains(e.target)) + ) { + this.$nextTick(() => (this.isMenuActive = !this.isMenuActive)) + // If user is clicking in the container + // and field is enclosed, activate it + } else if (this.isEnclosed) { this.isMenuActive = true } diff --git a/test/unit/components/VSelect/VSelect.spec.js b/test/unit/components/VSelect/VSelect.spec.js index <HASH>..<HASH> 100644 --- a/test/unit/components/VSelect/VSelect.spec.js +++ b/test/unit/components/VSelect/VSelect.spec.js @@ -6,6 +6,7 @@ import { VListTileTitle, VListTileContent } from '@/components/VList' +import VAutocomplete from '@/components/VAutocomplete' test('VSelect', ({ mount, compileToFunctions }) => { const app = document.createElement('div') @@ -420,4 +421,31 @@ test('VSelect', ({ mount, compileToFunctions }) => { expect(wrapper.html()).toMatchSnapshot() }) + + it('should toggle menu on icon click', async () => { + const wrapper = mount(VSelect, { + propsData: { offsetY: true } + }) + + const icon = wrapper.first('.v-icon') + const slot = wrapper.first('.v-input__slot') + + expect(wrapper.vm.isMenuActive).toBe(false) + + slot.trigger('click') + expect(wrapper.vm.isMenuActive).toBe(true) + + slot.trigger('click') + expect(wrapper.vm.isMenuActive).toBe(true) + + // Mock mouseup event with a target of + // the inner icon element + const event = new Event('mouseup') + Object.defineProperty(event, 'target', { writable: false, value: icon.element }) + + wrapper.element.dispatchEvent(event) + + await wrapper.vm.$nextTick() + expect(wrapper.vm.isMenuActive).toBe(false) + }) })
fix(VSelect): toggle menu when dropdown arrow is clicked (#<I>) * fix(v-autocomplete): toggle menu on icon click * fix(v-autocomplete): fix icon/menu toggle fixes #<I> * refactor(v-select): move onMouseUp logic for `v-select` with **offset-y** * refactor(v-select): change comparison should evaluate isEnclosed * test: move spec to VSelect
vuetifyjs_vuetify
train
0beb81ad4c915ebfe4327bd193b726865ab2fbef
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -107,6 +107,7 @@ * [#2569](https://github.com/bbatsov/rubocop/issues/2569): `Style/MethodCallParentheses` doesn't register warnings for `object.()` syntax, since it is handled by `Style/LambdaCall`. ([@alexdowad][]) * [#2570](https://github.com/bbatsov/rubocop/issues/2570): `Performance/RedundantMerge` doesn't break code with a modifier `if` when autocorrecting. ([@alexdowad][]) * `Performance/RedundantMerge` doesn't break code with a modifier `while` or `until` when autocorrecting. ([@alexdowad][]) +* [#2574](https://github.com/bbatsov/rubocop/issues/2574): `variable` style for `Lint/EndAlignment` is working again. ([@alexdowad][]) ### Changes diff --git a/lib/rubocop/cop/lint/end_alignment.rb b/lib/rubocop/cop/lint/end_alignment.rb index <HASH>..<HASH> 100644 --- a/lib/rubocop/cop/lint/end_alignment.rb +++ b/lib/rubocop/cop/lint/end_alignment.rb @@ -97,6 +97,7 @@ module RuboCop def check_other_alignment(node) align_with = { keyword: node.loc.keyword, + variable: node.loc.keyword, start_of_line: start_line_range(node) } check_end_kw_alignment(node, align_with) @@ -111,7 +112,9 @@ module RuboCop node elsif style == :variable return node.parent if argument_case?(node) - node.each_ancestor(:lvasgn).first + # Fall back to 'keyword' style if this node is not on the RHS + # of an assignment + node.each_ancestor(:lvasgn).first || node else start_line_range(node) end diff --git a/spec/rubocop/cop/lint/end_alignment_spec.rb b/spec/rubocop/cop/lint/end_alignment_spec.rb index <HASH>..<HASH> 100644 --- a/spec/rubocop/cop/lint/end_alignment_spec.rb +++ b/spec/rubocop/cop/lint/end_alignment_spec.rb @@ -80,6 +80,46 @@ describe RuboCop::Cop::Lint::EndAlignment, :config do include_examples 'misaligned', '', 'puts 1; case a when b', '', ' end' end + context 'when AlignWith is variable' do + # same as 'AlignWith' => 'keyword', as long as assignments or `case` + # are not involved + let(:cop_config) do + { 'AlignWith' => 'variable', 'AutoCorrect' => true } + end + + include_examples 'misaligned', '', 'class', 'Test', ' end' + include_examples 'misaligned', '', 'module', 'Test', ' end' + include_examples 'misaligned', '', 'if', 'test', ' end' + include_examples 'misaligned', '', 'unless', 'test', ' end' + include_examples 'misaligned', '', 'while', 'test', ' end' + include_examples 'misaligned', '', 'until', 'test', ' end' + include_examples 'misaligned', '', 'case', 'a when b', ' end' + + include_examples 'aligned', 'class', 'Test', 'end' + include_examples 'aligned', 'module', 'Test', 'end' + include_examples 'aligned', 'if', 'test', 'end' + include_examples 'aligned', 'unless', 'test', 'end' + include_examples 'aligned', 'while', 'test', 'end' + include_examples 'aligned', 'until', 'test', 'end' + include_examples 'aligned', 'case', 'a when b', 'end' + + include_examples 'misaligned', 'puts 1; ', 'class', 'Test', 'end' + include_examples 'misaligned', 'puts 1; ', 'module', 'Test', 'end' + include_examples 'misaligned', 'puts 1; ', 'if', 'test', 'end' + include_examples 'misaligned', 'puts 1; ', 'unless', 'test', 'end' + include_examples 'misaligned', 'puts 1; ', 'while', 'test', 'end' + include_examples 'misaligned', 'puts 1; ', 'until', 'test', 'end' + include_examples 'misaligned', 'puts 1; ', 'case', 'a when b', 'end' + + include_examples 'aligned', 'puts 1; class', 'Test', ' end' + include_examples 'aligned', 'puts 1; module', 'Test', ' end' + include_examples 'aligned', 'puts 1; if', 'Test', ' end' + include_examples 'aligned', 'puts 1; unless', 'Test', ' end' + include_examples 'aligned', 'puts 1; while', 'Test', ' end' + include_examples 'aligned', 'puts 1; until', 'Test', ' end' + include_examples 'aligned', 'puts 1; case', 'a when b', ' end' + end + context 'correct + opposite' do let(:source) do ['x = if a',
[Fix #<I>] Fix 'variable' style for Lint/EndAlignment We had no tests checking whether `Lint/EndAlignment`'s `variable` style worked or not when a node with `end` is not on the RHS of an assignment. So it was never noticed when <I>d0b<I> completely broke the `variable` style. Fix it up, and add tests so this doesn't happen again.
rubocop-hq_rubocop
train
9c665374989856dc0190d93e324ea55f8ae7c543
diff --git a/lib/Sabre/DAV/Version.php b/lib/Sabre/DAV/Version.php index <HASH>..<HASH> 100644 --- a/lib/Sabre/DAV/Version.php +++ b/lib/Sabre/DAV/Version.php @@ -15,7 +15,7 @@ class Sabre_DAV_Version { /** * Full version number */ - const VERSION = '1.0.1'; + const VERSION = '1.0.2'; /** * Stability : alpha, beta, stable
Bumped version to <I>
sabre-io_dav
train
3373995e012b1c43b0acf2ca94dda8a30097f98e
diff --git a/core-http/pom.xml b/core-http/pom.xml index <HASH>..<HASH> 100644 --- a/core-http/pom.xml +++ b/core-http/pom.xml @@ -30,12 +30,6 @@ </dependency> <dependency> <groupId>io.datakernel</groupId> - <artifactId>datakernel-codec</artifactId> - <version>${project.version}</version> - <optional>true</optional> - </dependency> - <dependency> - <groupId>io.datakernel</groupId> <artifactId>datakernel-jmxapi</artifactId> <version>${project.version}</version> <optional>true</optional> diff --git a/core-http/src/main/java/io/datakernel/http/HttpResponse.java b/core-http/src/main/java/io/datakernel/http/HttpResponse.java index <HASH>..<HASH> 100644 --- a/core-http/src/main/java/io/datakernel/http/HttpResponse.java +++ b/core-http/src/main/java/io/datakernel/http/HttpResponse.java @@ -16,8 +16,6 @@ package io.datakernel.http; import io.datakernel.bytebuf.ByteBuf; -import io.datakernel.codec.StructuredEncoder; -import io.datakernel.codec.json.JsonUtils; import io.datakernel.common.Initializable; import io.datakernel.csp.ChannelSupplier; import io.datakernel.http.HttpHeaderValue.HttpHeaderValueOfSetCookies; @@ -261,9 +259,9 @@ public final class HttpResponse extends HttpMessage implements Async<HttpRespons } @NotNull - public <T> HttpResponse withJson(StructuredEncoder<T> encoder, T object) { + public HttpResponse withJson(@NotNull String text) { return withHeader(CONTENT_TYPE, ofContentType(JSON_UTF_8)) - .withBody(JsonUtils.toJson(encoder, object).getBytes(UTF_8)); + .withBody(text.getBytes(UTF_8)); } @Override diff --git a/examples/tutorials/advanced-react-integration/src/main/java/ApplicationLauncher.java b/examples/tutorials/advanced-react-integration/src/main/java/ApplicationLauncher.java index <HASH>..<HASH> 100644 --- a/examples/tutorials/advanced-react-integration/src/main/java/ApplicationLauncher.java +++ b/examples/tutorials/advanced-react-integration/src/main/java/ApplicationLauncher.java @@ -64,7 +64,7 @@ public final class ApplicationLauncher extends HttpServerLauncher { .map(GET, "/get/all", request -> { Map<Integer, Record> records = recordDAO.findAll(); return HttpResponse.ok200() - .withJson(ofMap(INT_CODEC, RECORD_CODEC), records); + .withJson(JsonUtils.toJson(ofMap(INT_CODEC, RECORD_CODEC), records)); }) //[START REGION_4] .map(GET, "/delete/:recordId", request -> {
Remove datakernel-codec dependency from datakernel-http
softindex_datakernel
train
7d611c6eac1893da94ede6a4541e082918db73da
diff --git a/src/index.js b/src/index.js index <HASH>..<HASH> 100644 --- a/src/index.js +++ b/src/index.js @@ -1,8 +1,6 @@ import * as hooks from './hooks'; import service from './service'; -import mongoose from 'mongoose'; export { hooks }; -export { mongoose }; export { service }; export default service; \ No newline at end of file
no longer exposing mongoose
feathersjs-ecosystem_feathers-mongoose
train
7090f8b1e2120e9ab7cac05840a9c2057d7e8541
diff --git a/tools/src/main/java/org/wildfly/swarm/tools/exec/SwarmExecutor.java b/tools/src/main/java/org/wildfly/swarm/tools/exec/SwarmExecutor.java index <HASH>..<HASH> 100644 --- a/tools/src/main/java/org/wildfly/swarm/tools/exec/SwarmExecutor.java +++ b/tools/src/main/java/org/wildfly/swarm/tools/exec/SwarmExecutor.java @@ -228,7 +228,17 @@ public class SwarmExecutor { if (!this.classpath.isEmpty()) { cli.add("-classpath"); cli.add(String.join(File.pathSeparator, - this.classpath.stream().map(e -> e.toString()).collect(Collectors.toList()))); + this.classpath.stream() + .sorted((o1, o2) -> { + if (o1.toString().contains("weld-se-shaded")) { + return -1; + } else if (o2.toString().contains("weld-se-shaded")) { + return 1; + } + return o1.compareTo(o2); + }) + .map(e -> e.toString()) + .collect(Collectors.toList()))); } cli.addAll(this.executable.toArguments());
Ensure that the `weld-se-shaded` artifact containing Weld 3 is the first on the classpath for non uber jar scenarios
thorntail_thorntail
train
e2b09a8aecc8330697cf27aaa01b3b9e36577cda
diff --git a/src/DoctrineORMModule/Options/DBALConnection.php b/src/DoctrineORMModule/Options/DBALConnection.php index <HASH>..<HASH> 100644 --- a/src/DoctrineORMModule/Options/DBALConnection.php +++ b/src/DoctrineORMModule/Options/DBALConnection.php @@ -160,9 +160,9 @@ class DBALConnection extends AbstractOptions /** * @param array $doctrineCommentedTypes */ - public function setDoctrineCommentedTypes($doctrineCommentedTypes) + public function setDoctrineCommentedTypes(array $doctrineCommentedTypes) { - $this->doctrineCommentedTypes = (array) $doctrineCommentedTypes; + $this->doctrineCommentedTypes = $doctrineCommentedTypes; } /** diff --git a/tests/DoctrineORMModuleTest/Options/DBALConnectionTest.php b/tests/DoctrineORMModuleTest/Options/DBALConnectionTest.php index <HASH>..<HASH> 100644 --- a/tests/DoctrineORMModuleTest/Options/DBALConnectionTest.php +++ b/tests/DoctrineORMModuleTest/Options/DBALConnectionTest.php @@ -28,7 +28,7 @@ class DBALConnectionTest extends PHPUnit_Framework_TestCase public function testSetNullCommentedTypes() { $options = new DBALConnection(); - $options->setDoctrineCommentedTypes(null); + $options->setDoctrineCommentedTypes([]); $this->assertSame(array(), $options->getDoctrineCommentedTypes()); }
Fixed signature setDoctrineCommentedTypes
doctrine_DoctrineORMModule
train
ad57aa05ad05b08348acee229bad163c995146a5
diff --git a/src/sap.ui.mdc/src/sap/ui/mdc/ValueHelp.js b/src/sap.ui.mdc/src/sap/ui/mdc/ValueHelp.js index <HASH>..<HASH> 100644 --- a/src/sap.ui.mdc/src/sap/ui/mdc/ValueHelp.js +++ b/src/sap.ui.mdc/src/sap/ui/mdc/ValueHelp.js @@ -356,9 +356,10 @@ sap.ui.define([ var oTypeahead = this.getTypeahead(); var oDialog = this.getDialog(); - if (oTypeahead && oTypeahead.isOpen()) { + // check for opening too as focus move sometimes to valuehelp before handleOpened finished + if (oTypeahead && (oTypeahead.isOpen() || oTypeahead.isOpening())) { return oTypeahead.getDomRef(); - } else if (oDialog && oDialog.isOpen()) { + } else if (oDialog && (oDialog.isOpen() || oDialog.isOpening())) { return oDialog.getDomRef(); } diff --git a/src/sap.ui.mdc/test/sap/ui/mdc/qunit/valuehelp/ValueHelp.qunit.js b/src/sap.ui.mdc/test/sap/ui/mdc/qunit/valuehelp/ValueHelp.qunit.js index <HASH>..<HASH> 100644 --- a/src/sap.ui.mdc/test/sap/ui/mdc/qunit/valuehelp/ValueHelp.qunit.js +++ b/src/sap.ui.mdc/test/sap/ui/mdc/qunit/valuehelp/ValueHelp.qunit.js @@ -519,10 +519,17 @@ sap.ui.define([ assert.notOk(oContainer.getDomRef.called, "Container getDomRef not called if closed"); assert.notOk(oDomRef, "no DomRef returned if closed"); + sinon.stub(oContainer, "isOpening").returns(true); + oDomRef = oValueHelp.getDomRef(); + assert.ok(oContainer.getDomRef.called, "Container getDomRef called"); + assert.equal(oDomRef, oField.getDomRef(), "DomRef returned if opening"); + oContainer.isOpening.reset(); + sinon.stub(oContainer, "isOpen").returns(true); oDomRef = oValueHelp.getDomRef(); assert.ok(oContainer.getDomRef.called, "Container getDomRef called"); - assert.equal(oDomRef, oField.getDomRef(), "no DomRef returned if closed"); + assert.equal(oDomRef, oField.getDomRef(), "DomRef returned if open"); + oContainer.isOpen.reset(); oContainer.getDomRef.reset(); @@ -955,10 +962,17 @@ sap.ui.define([ assert.notOk(oContainer.getDomRef.called, "Container getDomRef not called if closed"); assert.notOk(oDomRef, "no DomRef returned if closed"); + sinon.stub(oContainer, "isOpening").returns(true); + oDomRef = oValueHelp.getDomRef(); + assert.ok(oContainer.getDomRef.called, "Container getDomRef called"); + assert.equal(oDomRef, oField.getDomRef(), "DomRef returned if opening"); + oContainer.isOpening.reset(); + sinon.stub(oContainer, "isOpen").returns(true); oDomRef = oValueHelp.getDomRef(); assert.ok(oContainer.getDomRef.called, "Container getDomRef called"); - assert.equal(oDomRef, oField.getDomRef(), "no DomRef returned if closed"); + assert.equal(oDomRef, oField.getDomRef(), "DomRef returned if open"); + oContainer.isOpen.reset(); oContainer.getDomRef.reset();
[INTERNAL] ValueHelp: cannot be closed Change-Id: Ia6dec7d<I>e<I>b<I>a<I>f1c<I>a<I>
SAP_openui5
train
0f381a162b7358e923d1b6ed03650ed36cd3d518
diff --git a/lib/rest_adapter/connection.rb b/lib/rest_adapter/connection.rb index <HASH>..<HASH> 100644 --- a/lib/rest_adapter/connection.rb +++ b/lib/rest_adapter/connection.rb @@ -15,7 +15,7 @@ module DataMapperRest # this is used to run the http verbs like http_post, http_put, http_delete etc. # TODO: handle nested resources, see prefix in ActiveResource def method_missing(method, *args) - @uri.path += "/#{args[0]}.#{@format.extension}" # Should be the form of /resources + @uri.path = "/#{args[0]}.#{@format.extension}" # Should be the form of /resources if verb = method.to_s.match(/^http_(get|post|put|delete|head)$/) run_verb(verb.to_s.split("_").last, args[1]) end
[dm-rest-adapter] Can't append path, otherwise every request is appended...
datamapper_dm-rest-adapter
train
8a7e832e264f5f763629df10d27ae9e9716dee9a
diff --git a/library/Phpass.php b/library/Phpass.php index <HASH>..<HASH> 100644 --- a/library/Phpass.php +++ b/library/Phpass.php @@ -81,18 +81,18 @@ class Phpass public function __construct($iterationCountLog2 = 8, $portableHashes = false) { $this->_itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; - + $this->_randomState = microtime(); if (function_exists('getmypid')) { $this->_randomState .= getmypid(); } - + if (is_array($iterationCountLog2)) { $options = array_merge( array ( - 'iterationCountLog2' => 8, + 'iterationCountLog2' => 8, 'portableHashes' => false - ), + ), $iterationCountLog2 ); } else { @@ -101,20 +101,20 @@ class Phpass 'portableHashes' => $portableHashes ); } - + $this->setOptions($options); } /** * Configure the instance. - * + * * @param array $options Array containing key => value pairs. * @return Phpass */ public function setOptions(Array $options) { $options = array_change_key_case($options, CASE_LOWER); - + if (isset ($options['iterationcountlog2'])) { $iterationCountLog2 = $options['iterationcountlog2']; if ($iterationCountLog2 < 4 || $iterationCountLog2 > 31) { @@ -124,14 +124,14 @@ class Phpass } $this->_iterationCountLog2 = $iterationCountLog2; } - + if (isset ($options['portablehashes'])) { $this->_portableHashes = (bool) $options['portablehashes']; } - + return $this; } - + /** * Fetch a random pool of data. *
Cleaned up extra whitespace in source file.
rchouinard_phpass
train
13b65fd5119bd17eb0402e6a025ed3bf5d23ee65
diff --git a/lib/sir-trevor/helpers/view_helper.rb b/lib/sir-trevor/helpers/view_helper.rb index <HASH>..<HASH> 100644 --- a/lib/sir-trevor/helpers/view_helper.rb +++ b/lib/sir-trevor/helpers/view_helper.rb @@ -8,14 +8,14 @@ module SirTrevor def render_sir_trevor(json, image_type = 'large') if hash = parse_sir_trevor(json) hash.map { |object| - render_block(object, image_type) + render_sir_trevor_block(object, image_type) }.compact.join.html_safe else '' end end - def render_block(object, image_type = 'large') + def render_sir_trevor_block(object, image_type = 'large') view_name = "sir-trevor/blocks/#{object['type'].to_s.downcase}_block" render(view_name,
Rename render_block to make it consistent with other method names.
madebymany_sir-trevor-rails
train
539f0fa396b6144d21cec2d8e3cd352964839a9e
diff --git a/lib/plugins/jingle.js b/lib/plugins/jingle.js index <HASH>..<HASH> 100644 --- a/lib/plugins/jingle.js +++ b/lib/plugins/jingle.js @@ -7,6 +7,12 @@ var window = window || global; module.exports = function (client) { var jingle = client.jingle = new Jingle(); + client.supportedICEServiceTypes = { + stun: true, + stuns: true, + turn: true, + turns: true + }; client.disco.addFeature('urn:xmpp:jingle:1'); if (window.RTCPeerConnection) { @@ -83,6 +89,11 @@ module.exports = function (client) { for (var i = 0; i < services.length; i++) { var service = services[i]; var ice = {}; + + if (!client.supportedICEServiceTypes[service.type]) { + continue; + } + if (service.type === 'stun' || service.type === 'stuns') { ice.urls = service.type + ':' + service.host; if (service.port) {
Allow restricting the types of ICE servers used by Jingle
legastero_stanza.io
train
f15567f175620eea9902d7a39deff800a57ccc74
diff --git a/src/painter.js b/src/painter.js index <HASH>..<HASH> 100644 --- a/src/painter.js +++ b/src/painter.js @@ -283,6 +283,7 @@ function outputAttribute(pen, name, value, diff, inspect, diffFn) { if (diff) { + pen.sp(); switch(diff.type) { case 'changed': outputRawAttribute(pen, name, value, inspect); @@ -348,7 +349,8 @@ function outputAttribute(pen, name, value, diff, inspect, diffFn) { } }).forceLineBreak(); } - } else { + } else if (value !== undefined) { + pen.sp(); outputRawAttribute(pen, name, value, inspect); } } @@ -404,7 +406,6 @@ function outputAttributes(pen, attributes, inspect, diffFn) { attributes.forEach(attrib => { attribOutput.add(pen => { - pen.sp(); outputAttribute(pen, attrib.name, attrib.value, attrib.diff, inspect, diffFn); }); }); diff --git a/src/tests/painter.spec.js b/src/tests/painter.spec.js index <HASH>..<HASH> 100644 --- a/src/tests/painter.spec.js +++ b/src/tests/painter.spec.js @@ -60,6 +60,36 @@ describe('Painter', () => { expect(pen.toString(), 'to equal', '<div id="abc" className="foo" />'); }); + + it('skips outputting attributes that are undefined', () => { + + Painter(pen, { + type: 'ELEMENT', + name: 'div', + attributes: [ + { name: 'id', value: undefined }, + { name: 'className', value: 'foo' } + ] + }, expect.inspect); + + expect(pen.toString(), 'to equal', + '<div className="foo" />'); + }); + + it('skips outputting attributes that are undefined', () => { + + Painter(pen, { + type: 'ELEMENT', + name: 'div', + attributes: [ + { name: 'id', value: undefined }, + { name: 'className', value: 'foo' } + ] + }, expect.inspect); + + expect(pen.toString(), 'to equal', + '<div className="foo" />'); + }); it('outputs a single empty element with object attributes', () => {
Skips outputting attributes that are undefined Closes #1
bruderstein_unexpected-htmllike
train
1071e9357ef9e31bb1aea1064586fbc507b0f4b3
diff --git a/benchexec/tools/ultimate.py b/benchexec/tools/ultimate.py index <HASH>..<HASH> 100644 --- a/benchexec/tools/ultimate.py +++ b/benchexec/tools/ultimate.py @@ -57,6 +57,7 @@ class UltimateTool(benchexec.tools.template.BaseTool): "LICENSE.GPL", "LICENSE.GPL.LESSER", "mathsat", + "mathsat-LICENSE", "p2", "plugins", "README",
add mathsat-LICENSE as required file
sosy-lab_benchexec
train
8339a019a1764ad09a41defc02dafa3ad6b97321
diff --git a/lang/en/admin.php b/lang/en/admin.php index <HASH>..<HASH> 100755 --- a/lang/en/admin.php +++ b/lang/en/admin.php @@ -236,7 +236,7 @@ $string['configintrosite'] = 'This page allows you to configure the front page a $string['configintrotimezones'] = 'This page will search for new information about world timezones (including daylight savings time rules) and update your local database with this information. These locations will be checked, in order: {$a} This procedure is generally very safe and can not break normal installations. Do you wish to update your timezones now?'; $string['configiplookup'] = 'When you click on an IP address (such as 34.12.222.93), such as in the logs, you are shown a map with a best guess of where that IP is located. There are different plugins for this that you can choose from, each has benefits and disadvantages.'; $string['configkeeptagnamecase'] = 'Check this if you want tag names to keep the original casing as entered by users who created them'; -$string['configlang'] = 'Choose a default language for the whole site. Users can override this setting later. You can also set $CFG->lang="yourlangcode_utf8"; in config.php if you want localised error messages for database connection problems.'; +$string['configlang'] = 'Choose a default language for the whole site. Users can override this setting using the language menu or the setting in their personal profile.'; $string['configlangcache'] = 'Cache the language menu. Saves a lot of memory and processing power. If you enable this, the menu takes a few minutes to update after you have added or removed languages.'; $string['configlangstringcache'] = 'Caches all the language strings into compiled files in the data directory. If you are translating Moodle or changing strings in the Moodle source code then you may want to switch this off. Otherwise leave it on to see performance benefits.'; $string['configlangdir'] = 'Most languages are printed left-to-right, but some, like Arabic and Hebrew, are printed right-to-left.';
MDL-<I> string rewording thanks to Koen Roggemans
moodle_moodle
train
77f4c1f2e881fe1c858e251ec659f7077e56b734
diff --git a/elasticsearch_dsl/filter.py b/elasticsearch_dsl/filter.py index <HASH>..<HASH> 100644 --- a/elasticsearch_dsl/filter.py +++ b/elasticsearch_dsl/filter.py @@ -70,6 +70,41 @@ class Bool(BoolMixin, Filter): 'should': {'type': 'filter', 'multi': True}, 'must_not': {'type': 'filter', 'multi': True}, } + + def __and__(self, other): + f = self._clone() + if isinstance(other, self.__class__): + f.must += other.must + f.must_not += other.must_not + f.should = [] + if self.should and other.should: + selfshould, othershould = self.should[:], other.should[:] + # required subfilter, move to must + if len(selfshould) == 1: + f.must.append(selfshould.pop()) + + # required subfilter, move to must + if len(othershould) == 1: + f.must.append(othershould.pop()) + + # we have leftover lists, nothing to do but add to must as bool(should) + if selfshould and othershould: + f.must.extend(( + Bool(should=selfshould), + Bool(should=othershould), + )) + # at most one should list is left, keep as should + else: + f.should = selfshould + othershould + + # at most one should list is left, keep as should + else: + f.should = self.should + other.should + else: + f.must.append(other) + return f + __rand__ = __and__ + # register this as Bool for Filter Filter._bool = Bool diff --git a/elasticsearch_dsl/query.py b/elasticsearch_dsl/query.py index <HASH>..<HASH> 100644 --- a/elasticsearch_dsl/query.py +++ b/elasticsearch_dsl/query.py @@ -60,6 +60,29 @@ class Bool(BoolMixin, Query): 'should': {'type': 'query', 'multi': True}, 'must_not': {'type': 'query', 'multi': True}, } + + def __and__(self, other): + q = self._clone() + if isinstance(other, self.__class__): + q.must += other.must + q.must_not += other.must_not + q.should = [] + for qx in (self, other): + min_should_match = getattr(qx, 'minimum_should_match', 0 if any((qx.must, qx.must_not)) else 1) + # all subqueries are required + if len(qx.should) <= min_should_match: + q.must.extend(qx.should) + # not all of them are required, use it and remember min_should_match + elif not q.should: + q.minimum_should_match = min_should_match + q.should = qx.should + # not all are required, add a should list to the must with proper min_should_match + else: + q.must.append(Bool(should=qx.should, minimum_should_match=min_should_match)) + else: + q.must.append(other) + return q + __rand__ = __and__ # register this as Bool for Query Query._bool = Bool diff --git a/elasticsearch_dsl/utils.py b/elasticsearch_dsl/utils.py index <HASH>..<HASH> 100644 --- a/elasticsearch_dsl/utils.py +++ b/elasticsearch_dsl/utils.py @@ -338,27 +338,9 @@ class DslBase(object): class BoolMixin(object): """ Mixin containing all the operator overrides for Bool queries and filters. - """ - def __and__(self, other): - q = self._clone() - if isinstance(other, self.__class__): - q.must += other.must - q.must_not += other.must_not - if q.should and other.should: - should = [] - for orig_should in (q.should, other.should): - if len(orig_should) == 1: - should.append(orig_should[0]) - else: - should.append(self.__class__(should=orig_should)) - q.should = should - else: - q.should += other.should - else: - q.must.append(other) - return q - __rand__ = __and__ + Except for and where should behavior differs + """ def __add__(self, other): q = self._clone() if isinstance(other, self.__class__): diff --git a/test_elasticsearch_dsl/test_query.py b/test_elasticsearch_dsl/test_query.py index <HASH>..<HASH> 100644 --- a/test_elasticsearch_dsl/test_query.py +++ b/test_elasticsearch_dsl/test_query.py @@ -101,11 +101,11 @@ def test_bool_and_bool(): q1 = query.Bool(must=[qt1], should=[qt2]) q2 = query.Bool(must_not=[qt3]) - assert q1 & q2 == query.Bool(must=[qt1], must_not=[qt3], should=[qt2]) + assert q1 & q2 == query.Bool(must=[qt1], must_not=[qt3], should=[qt2], minimum_should_match=0) q1 = query.Bool(must=[qt1], should=[qt1, qt2]) q2 = query.Bool(should=[qt3]) - assert q1 & q2 == query.Bool(must=[qt1], should=[query.Bool(should=[qt1, qt2]), qt3]) + assert q1 & q2 == query.Bool(must=[qt1, qt3], should=[qt1, qt2], minimum_should_match=0) def test_inverted_query_becomes_bool_with_must_not(): q = query.Match(f=42)
Proper logix with & for bool filters/queries Respecting minimum_should_match logic
elastic_elasticsearch-dsl-py
train
419330ea53c60889160b3b32c240478c22df65a0
diff --git a/languagetool-language-modules/en/src/main/java/org/languagetool/rules/en/AbstractEnglishSpellerRule.java b/languagetool-language-modules/en/src/main/java/org/languagetool/rules/en/AbstractEnglishSpellerRule.java index <HASH>..<HASH> 100644 --- a/languagetool-language-modules/en/src/main/java/org/languagetool/rules/en/AbstractEnglishSpellerRule.java +++ b/languagetool-language-modules/en/src/main/java/org/languagetool/rules/en/AbstractEnglishSpellerRule.java @@ -25,10 +25,7 @@ import org.languagetool.rules.*; import org.languagetool.rules.en.translation.BeoLingusTranslator; import org.languagetool.rules.spelling.morfologik.MorfologikSpellerRule; import org.languagetool.rules.translation.Translator; -import org.languagetool.synthesis.en.EnglishSynthesizer; import org.languagetool.tools.StringTools; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; @@ -37,8 +34,8 @@ import java.util.stream.Collectors; @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") public abstract class AbstractEnglishSpellerRule extends MorfologikSpellerRule { - private static Logger logger = LoggerFactory.getLogger(AbstractEnglishSpellerRule.class); - private static final EnglishSynthesizer synthesizer = (EnglishSynthesizer) Languages.getLanguageForShortCode("en").getSynthesizer(); + //private static Logger logger = LoggerFactory.getLogger(AbstractEnglishSpellerRule.class); + //private static final EnglishSynthesizer synthesizer = (EnglishSynthesizer) Languages.getLanguageForShortCode("en").getSynthesizer(); private final BeoLingusTranslator translator;
[en] comment out unused member vars
languagetool-org_languagetool
train
5d4cb475a919cdd4a02d39cad35a54127f65c785
diff --git a/identify/extensions.py b/identify/extensions.py index <HASH>..<HASH> 100644 --- a/identify/extensions.py +++ b/identify/extensions.py @@ -116,7 +116,7 @@ EXTENSIONS = { 'rs': {'text', 'rust'}, 'rst': {'text', 'rst'}, 's': {'text', 'asm'}, - 'sbt': {'text', 'scala'}, + 'sbt': {'text', 'sbt', 'scala'}, 'sc': {'text', 'scala'}, 'scala': {'text', 'scala'}, 'scss': {'text', 'scss'},
Allow sbt to be differentiated
chriskuehl_identify
train
4470e4e5ed66cd67f8e1ad8004a19d6714b6d846
diff --git a/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/TestSipListener.java b/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/TestSipListener.java index <HASH>..<HASH> 100644 --- a/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/TestSipListener.java +++ b/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/TestSipListener.java @@ -722,13 +722,15 @@ public class TestSipListener implements SipListener { if(dialog != null) { logger.info("Dialog State = " + dialog.getState()); } - Response response = protocolObjects.messageFactory.createResponse( - 200, request); - serverTransactionId.sendResponse(response); - this.transactionCount++; - logger.info("shootist: Sending OK."); - if(dialog != null) { - logger.info("Dialog State = " + dialog.getState()); + if(!waitForCancel) { + Response response = protocolObjects.messageFactory.createResponse( + 200, request); + serverTransactionId.sendResponse(response); + this.transactionCount++; + logger.info("shootist: Sending OK."); + if(dialog != null) { + logger.info("Dialog State = " + dialog.getState()); + } } this.optionsRequest = request; } catch (Exception ex) { diff --git a/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/simple/ShootistSipServletTest.java b/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/simple/ShootistSipServletTest.java index <HASH>..<HASH> 100644 --- a/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/simple/ShootistSipServletTest.java +++ b/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/simple/ShootistSipServletTest.java @@ -1053,6 +1053,32 @@ public class ShootistSipServletTest extends SipServletTestCase { assertTrue("sipAppSessionReadyToInvalidate", allMessagesContent.contains("sipAppSessionReadyToInvalidate")); } + // Tests Issue 1693 http://code.google.com/p/mobicents/issues/detail?id=1693 + public void testShootistOptionsTimeout() throws Exception { + receiverProtocolObjects =new ProtocolObjects( + "sender", "gov.nist", TRANSPORT, AUTODIALOG, null, null, null); + + receiver = new TestSipListener(5080, 5070, receiverProtocolObjects, false); + receiver.setProvisionalResponsesToSend(new ArrayList<Integer>()); + receiver.setWaitForCancel(true); + SipProvider senderProvider = receiver.createProvider(); + + senderProvider.addSipListener(receiver); + + receiverProtocolObjects.start(); + tomcat.startTomcat(); + Map<String, String> params = new HashMap<String, String>(); + params.put("testErrorResponse", "true"); + params.put("method", "OPTIONS"); + deployApplication(params); + Thread.sleep(DIALOG_TIMEOUT + TIMEOUT); + List<String> allMessagesContent = receiver.getAllMessagesContent(); + assertEquals(1,allMessagesContent.size()); +// assertTrue("sipSessionReadyToInvalidate", allMessagesContent.contains("sipSessionReadyToInvalidate")); +// assertTrue("sipAppSessionReadyToInvalidate", allMessagesContent.contains("sipAppSessionReadyToInvalidate")); + assertTrue("408 received", allMessagesContent.contains("408 received")); + } + // Tests Issue 143 http://code.google.com/p/mobicents/issues/detail?id=143 public void testShootist422Response() throws Exception { receiverProtocolObjects =new ProtocolObjects(
Non regression test for github Issue #<I> (cherry picked from commit <I>d<I>a<I>ccbad1cb<I>dcb<I>dcec3de<I>f<I>e)
RestComm_sip-servlets
train
302f52311cef67b0e3d654544eb84dbf01c6ed2f
diff --git a/lib/rfc/rif.rb b/lib/rfc/rif.rb index <HASH>..<HASH> 100644 --- a/lib/rfc/rif.rb +++ b/lib/rfc/rif.rb @@ -102,9 +102,9 @@ class Rif < RSpec::Core::Formatters::BaseTextFormatter return "Unexpected unit: #{unit} for #{line}" end value = value * 1024 - measure.sub!(/:$/, '') - stats[measure] = value end + measure.sub!(/:$/, '') + stats[measure] = value end mem_used = stats['MemTotal'] - stats['MemFree'] - stats['Buffers'] - stats['Cached']
Fix memory stats when there is no swap
p-mongo_rfc
train
7d4294b2799654dbe3a837091dc6f2963eaaf46d
diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -37,16 +37,16 @@ }, "homepage": "https://github.com/libp2p/js-libp2p-identify#readme", "devDependencies": { - "aegir": "^11.0.0", + "aegir": "^11.0.1", "chai": "^3.5.0", "dirty-chai": "^1.2.2", "pre-commit": "^1.2.2", "pull-pair": "^1.1.0" }, "dependencies": { - "multiaddr": "^2.2.2", - "peer-id": "~0.8.4", - "peer-info": "~0.8.4", + "multiaddr": "^2.3.0", + "peer-id": "~0.8.6", + "peer-info": "~0.9.0", "protocol-buffers": "^3.2.1", "pull-length-prefixed": "^1.2.0", "pull-stream": "^3.5.0" diff --git a/src/dialer.js b/src/dialer.js index <HASH>..<HASH> 100644 --- a/src/dialer.js +++ b/src/dialer.js @@ -24,12 +24,12 @@ module.exports = (conn, callback) => { return callback(err) } - const info = new PeerInfo(id) + const peerInfo = new PeerInfo(id) input.listenAddrs .map(multiaddr) - .forEach((ma) => info.multiaddr.add(ma)) + .forEach((ma) => peerInfo.multiaddrs.add(ma)) - callback(null, info, getObservedAddrs(input)) + callback(null, peerInfo, getObservedAddrs(input)) }) }) ) diff --git a/src/listener.js b/src/listener.js index <HASH>..<HASH> 100644 --- a/src/listener.js +++ b/src/listener.js @@ -20,7 +20,7 @@ module.exports = (conn, pInfoSelf) => { protocolVersion: 'ipfs/0.1.0', agentVersion: 'na', publicKey: publicKey, - listenAddrs: pInfoSelf.multiaddrs.map((ma) => ma.buffer), + listenAddrs: pInfoSelf.multiaddrs.toArray().map((ma) => ma.buffer), observedAddr: observedAddrs ? observedAddrs.buffer : new Buffer('') }) diff --git a/test/dialer.spec.js b/test/dialer.spec.js index <HASH>..<HASH> 100644 --- a/test/dialer.spec.js +++ b/test/dialer.spec.js @@ -29,7 +29,7 @@ describe('identify.dialer', () => { it('works', (done) => { const p = pair() - original.multiaddr.add(multiaddr('/ip4/127.0.0.1/tcp/5002')) + original.multiaddrs.add(multiaddr('/ip4/127.0.0.1/tcp/5002')) const input = msg.encode({ protocolVersion: 'ipfs/0.1.0', agentVersion: 'na', @@ -49,17 +49,11 @@ describe('identify.dialer', () => { expect(info.id.pubKey.bytes) .to.eql(original.id.pubKey.bytes) - expect( - info.multiaddrs - ).to.be.eql( - original.multiaddrs - ) + expect(info.multiaddrs.toArray()) + .to.eql(original.multiaddrs.toArray()) - expect( - observedAddrs - ).to.be.eql( - [multiaddr('/ip4/127.0.0.1/tcp/5001')] - ) + expect(observedAddrs) + .to.eql([multiaddr('/ip4/127.0.0.1/tcp/5001')]) done() }) diff --git a/test/listener.spec.js b/test/listener.spec.js index <HASH>..<HASH> 100644 --- a/test/listener.spec.js +++ b/test/listener.spec.js @@ -16,6 +16,7 @@ const identify = require('../src') describe('identify.listener', () => { let info + beforeEach((done) => { PeerInfo.create((err, _info) => { if (err) { @@ -29,7 +30,7 @@ describe('identify.listener', () => { it('works', (done) => { const p = pair() - info.multiaddr.add(multiaddr('/ip4/127.0.0.1/tcp/5002')) + info.multiaddrs.add(multiaddr('/ip4/127.0.0.1/tcp/5002')) pull( p[1], lp.decode(),
Feat/new peer info (#<I>) * chore: update deps * feat: peer-info rave
libp2p_js-libp2p-identify
train
97cbea005e6e1e5c238a8e1d6a753a54404811a6
diff --git a/src/Symfony/Component/Lock/Tests/Store/BlockingStoreTestTrait.php b/src/Symfony/Component/Lock/Tests/Store/BlockingStoreTestTrait.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Component/Lock/Tests/Store/BlockingStoreTestTrait.php +++ b/src/Symfony/Component/Lock/Tests/Store/BlockingStoreTestTrait.php @@ -31,6 +31,7 @@ trait BlockingStoreTestTrait * This test is time sensible: the $clockDelay could be adjust. * * @requires extension pcntl + * @requires extension posix * @requires function pcntl_sigwaitinfo */ public function testBlockingLocks()
[Lock] Skip test if posix extension is not installed This isn't installed by default on Fedora
symfony_symfony
train
dec00f3b9825df374638ffbe450b6f46d4802784
diff --git a/lib/Pagon/App.php b/lib/Pagon/App.php index <HASH>..<HASH> 100644 --- a/lib/Pagon/App.php +++ b/lib/Pagon/App.php @@ -111,8 +111,6 @@ class App extends EventEmitter */ public function __construct($config = array()) { - $app = & $this; - // Is cli $this->_cli = PHP_SAPI == 'cli'; @@ -124,11 +122,11 @@ class App extends EventEmitter // Set io depends on SAPI if (!$this->_cli) { - $this->input = new Http\Input($app); - $this->output = new Http\Output($app); + $this->input = new Http\Input($this); + $this->output = new Http\Output($this); } else { - $this->input = new Cli\Input($app); - $this->output = new Cli\Output($app); + $this->input = new Cli\Input($this); + $this->output = new Cli\Output($this); } // Init Route @@ -139,23 +137,23 @@ class App extends EventEmitter iconv_set_encoding("internal_encoding", "UTF-8"); mb_internal_encoding('UTF-8'); + // Config + $this->config = !is_array($config) ? Config::load((string)$config)->defaults($this->config) : new Config($config + $this->config); + // configure timezone - if ($app->config['timezone']) date_default_timezone_set($app->config['timezone']); + if ($this->config['timezone']) date_default_timezone_set($this->config['timezone']); // configure debug - if ($app->config['debug']) $app->add(new Middleware\PrettyException()); + if ($this->config['debug']) $this->add(new Middleware\PrettyException()); // Share the cryptor for the app - $app->share('cryptor', function ($app) { + $this->share('cryptor', function ($app) { if (empty($app->config['crypt'])) { throw new \RuntimeException('Encrypt cookie need configure config["crypt"]'); } return new \Pagon\Utility\Cryptor($app->config['crypt']); }); - // Config - $this->config = !is_array($config) ? Config::load((string)$config)->defaults($this->config) : new Config($config + $this->config); - // Set default locals $this->locals['config'] = & $this->config;
Some fix for app->config when construct
hfcorriez_pagon
train
3d76571621d9f34d7c0470b7d621aea916ceb0f6
diff --git a/jsonresults.go b/jsonresults.go index <HASH>..<HASH> 100644 --- a/jsonresults.go +++ b/jsonresults.go @@ -131,7 +131,7 @@ type GetNetworkInfoResult struct { ProtocolVersion int32 `json:"protocolversion"` TimeOffset int64 `json:"timeoffset"` Connections int32 `json:"connections"` - Proxy string `json:"proxy,omitempty"` + Networks []NetworksResult `json:"networks"` RelayFee float64 `json:"relayfee"` LocalAddresses []LocalAddressesResult `json:"localaddresses"` } @@ -382,6 +382,14 @@ type ListUnspentResult struct { Confirmations int64 `json:"confirmations"` } +// NetworksResult models the networks data from the getnetworkinfo command. +type NetworksResult struct { + Name string `json:"name"` + Limited bool `json:"limited"` + Reachable bool `json:"reachable"` + Proxy string `json:"proxy"` +} + // SignRawTransactionResult models the data from the signrawtransaction // command. type SignRawTransactionResult struct {
Update getnetworkinfo structure. This matches the changes in Bitcoin Core. Tested with btcctl. OK @jcvernaleo
btcsuite_btcd
train
893ca2a56846d498f30b75b6fcad771138ac4574
diff --git a/test/integration/features/step_definitions/common-steps.js b/test/integration/features/step_definitions/common-steps.js index <HASH>..<HASH> 100644 --- a/test/integration/features/step_definitions/common-steps.js +++ b/test/integration/features/step_definitions/common-steps.js @@ -5,18 +5,22 @@ import {info} from '@travi/cli-messages'; import {Before, After, Given, When, setWorldConstructor} from 'cucumber'; import any from '@travi/any'; import {World} from '../support/world'; -import {scaffold, questionNames} from '../../../../src'; setWorldConstructor(World); +let scaffold, questionNames; +const projectPath = [__dirname, '..', '..', '..', '..']; +const projectTemplatePath = [...projectPath, 'templates']; +const stubbedNodeModules = stubbedFs.load(resolve(...projectPath, 'node_modules')); + Before(async () => { - const projectTemplatePath = '../../../../templates'; + ({scaffold, questionNames} = require('../../../../src')); stubbedFs({ - node_modules: stubbedFs.load(resolve(__dirname, '..', '..', '..', '..', 'node_modules')), + node_modules: stubbedNodeModules, templates: { - 'README.mustache': await promises.readFile(resolve(__dirname, projectTemplatePath, './README.mustache')), - 'editorconfig.txt': await promises.readFile(resolve(__dirname, projectTemplatePath, './editorconfig.txt')) + 'README.mustache': await promises.readFile(resolve(...projectTemplatePath, './README.mustache')), + 'editorconfig.txt': await promises.readFile(resolve(...projectTemplatePath, './editorconfig.txt')) } }); });
test: prepared for use of package-preview
travi_project-scaffolder
train
3a929ec7667f79a7663e89bdcd06d0f91afa3db8
diff --git a/core/src/main/java/at/stefangeyer/challonge/model/enumeration/TournamentState.java b/core/src/main/java/at/stefangeyer/challonge/model/enumeration/TournamentState.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/at/stefangeyer/challonge/model/enumeration/TournamentState.java +++ b/core/src/main/java/at/stefangeyer/challonge/model/enumeration/TournamentState.java @@ -3,6 +3,7 @@ package at.stefangeyer.challonge.model.enumeration; public enum TournamentState { CHECKING_IN("checking_in"), CHECKED_IN("checked_in"), + ACCEPTING_PREDICTIONS("accepting_predictions"), PENDING("pending"), UNDERWAY("underway"), GROUP_STAGES_UNDERWAY("group_stages_underway"),
Adds tournament state for accepting_predictions
stefangeyer_challonge-java
train
8d2330a8975f704dfc564c417e45b8973f3298fb
diff --git a/test/Event/ReadModel/JSONLD/CdbXMLImporterTest.php b/test/Event/ReadModel/JSONLD/CdbXMLImporterTest.php index <HASH>..<HASH> 100644 --- a/test/Event/ReadModel/JSONLD/CdbXMLImporterTest.php +++ b/test/Event/ReadModel/JSONLD/CdbXMLImporterTest.php @@ -486,6 +486,10 @@ class CdbXMLImporterTest extends \PHPUnit_Framework_TestCase * @test * @group issue-III-165 * @dataProvider descriptionsProvider + * + * @param $cdbxmlFile + * @param $expectedDescriptionFile + * @param string $schemaVersion */ public function it_combines_long_and_short_description_to_one_description( $cdbxmlFile,
III-<I> Updated header docs.
cultuurnet_udb3-php
train
3978d6ac3bdbc18485e8094fc6a776a8f126d2a2
diff --git a/synapse/tests/test_cortex.py b/synapse/tests/test_cortex.py index <HASH>..<HASH> 100644 --- a/synapse/tests/test_cortex.py +++ b/synapse/tests/test_cortex.py @@ -1325,3 +1325,20 @@ class CortexTest(s_test.SynTest): self.len(0, core.eval('testint<10')) self.len(0, core.eval('testint<20')) self.len(1, core.eval('testint<30')) + + # time indx is derived from the same lift helpers + list(core.eval('[teststr=foo :tick=201808021201]')) + + self.len(0, core.eval('teststr:tick>=201808021202')) + self.len(1, core.eval('teststr:tick>=201808021201')) + self.len(1, core.eval('teststr:tick>=201808021200')) + + self.len(0, core.eval('teststr:tick>201808021202')) + self.len(1, core.eval('teststr:tick>201808021200')) + + self.len(1, core.eval('teststr:tick<=201808021202')) + self.len(1, core.eval('teststr:tick<=201808021201')) + self.len(0, core.eval('teststr:tick<=201808021200')) + + self.len(1, core.eval('teststr:tick<201808021202')) + self.len(0, core.eval('teststr:tick<201808021200'))
ensure time based gt/ge/lt/le lifts work like regular int lifts.
vertexproject_synapse
train
f7a9e088f9ec8bf4593bf017baa38722e5a047e1
diff --git a/lib/stupidedi/builder/navigation.rb b/lib/stupidedi/builder/navigation.rb index <HASH>..<HASH> 100644 --- a/lib/stupidedi/builder/navigation.rb +++ b/lib/stupidedi/builder/navigation.rb @@ -430,6 +430,22 @@ module Stupidedi end end + # Sequence multiple traversals together, by iteratively calling + # `find`. Each argument must be either a single segment ID or a + # list whose first element is a segment ID and remaining elements + # are segment constraints. + # + # @example + # machine.sequence(:GS, :ST, :HL) + # machine.sequence(:GS, [:ST, "837"], [:HL, nil, "20"]) + # + # @return [Either<StateMachine>] + def sequence(pattern, *patterns) + patterns.inject(find(*pattern)) do |m, p| + m = m.flatmap{|n| n.find(*p) } + end + end + private # @return [Either<StateMachine>]
Create method Navigation#sequence to make several traversals in one call
irobayna_stupidedi
train
4e8c56f30b7020982fd09691f74999c447d64517
diff --git a/azurerm/helpers/validate/compute.go b/azurerm/helpers/validate/compute.go index <HASH>..<HASH> 100644 --- a/azurerm/helpers/validate/compute.go +++ b/azurerm/helpers/validate/compute.go @@ -41,7 +41,7 @@ func SharedImageName(v interface{}, k string) (ws []string, es []error) { func SharedImageVersionName(v interface{}, k string) (ws []string, es []error) { value := v.(string) - r, _ := regexp.Compile(`^([0-9]\.[0-9]\.[0-9])$`) + r, _ := regexp.Compile(`^([0-9]{1,10}\.[0-9]{1,10}\.[0-9]{1,10})$`) if !r.MatchString(value) { es = append(es, fmt.Errorf("Expected %s to be in the format `1.2.3` but got %q.", k, value)) } diff --git a/azurerm/resource_arm_shared_image_version_test.go b/azurerm/resource_arm_shared_image_version_test.go index <HASH>..<HASH> 100644 --- a/azurerm/resource_arm_shared_image_version_test.go +++ b/azurerm/resource_arm_shared_image_version_test.go @@ -51,6 +51,7 @@ func TestAccAzureRMSharedImageVersion_basic(t *testing.T) { testCheckAzureRMSharedImageVersionExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "managed_image_id"), resource.TestCheckResourceAttr(resourceName, "target_region.#", "2"), + resource.TestCheckResourceAttr(resourceName, "name", "1234567890.1234567890.1234567890"), ), }, { @@ -181,7 +182,7 @@ func testAccAzureRMSharedImageVersion_imageVersionUpdated(rInt int, location, al %s resource "azurerm_shared_image_version" "test" { - name = "0.0.1" + name = "1234567890.1234567890.1234567890" gallery_name = "${azurerm_shared_image_gallery.test.name}" image_name = "${azurerm_shared_image.test.name}" resource_group_name = "${azurerm_resource_group.test.name}"
Allowed larger numbers for azurerm_shared_image_version name (#<I>)
terraform-providers_terraform-provider-azurerm
train
dd6612ccee1867440e382423204ed386df3e8357
diff --git a/tests/test_menu_launcher.py b/tests/test_menu_launcher.py index <HASH>..<HASH> 100644 --- a/tests/test_menu_launcher.py +++ b/tests/test_menu_launcher.py @@ -163,7 +163,7 @@ def test_running_menu(): cmd = "python2.7 menu_launcher.py "+path_dirs.base_dir+" "+path_dirs.info_dir+" "+path_dirs.data_dir invalid_url = "https://thisisinvalid-.git" child = pexpect.spawn(cmd) -# child.timeout = 1200 + child.timeout = 1200 # expect main menu child.expect('Exit') ### Mode Menu ### @@ -174,9 +174,7 @@ def test_running_menu(): child.sendline('1') child.expect('Return to Mode menu') # return to mode - child.send("[A") - child.sendline('') -# child.sendline('2') + child.sendline('2') child.expect('Return to Vent menu') # go to stop child.sendline('2') @@ -353,7 +351,7 @@ def test_running_add_plugin(): cmd = "python2.7 menu_launcher.py "+path_dirs.base_dir+" "+path_dirs.info_dir+" "+path_dirs.data_dir child1 = pexpect.spawn(cmd) - child1.timeout = 1200 + child1.timeout = 600 ### Plugins Menu ### # go to plugins menu child1.sendline('2')
Undoing some test_running_menu experiments.
CyberReboot_vent
train
cb0c6dd251eef3f7753516c9f50ad329d9cb845a
diff --git a/secedgar/filings/_base.py b/secedgar/filings/_base.py index <HASH>..<HASH> 100644 --- a/secedgar/filings/_base.py +++ b/secedgar/filings/_base.py @@ -13,18 +13,6 @@ class AbstractFiling(ABC): """``secedgar.client._base``: Client to use to make requests.""" pass # pragma: no cover - @abstractmethod - def get_urls(self, **kwargs): - """Get all URLs for filings. - - Args: - kwargs: Anything to be passed to requests when making GET request. - - Returns: - urls (list): List of urls for txt files to download. - """ - pass # pragma: no cover - @property @abstractmethod def params(self): @@ -38,6 +26,18 @@ class AbstractFiling(ABC): pass # pragma: no cover @abstractmethod + def get_urls(self, **kwargs): + """Get all URLs for filings. + + Args: + kwargs: Anything to be passed to requests when making GET request. + + Returns: + urls (list): List of urls for txt files to download. + """ + pass # pragma: no cover + + @abstractmethod def save(self, directory): """Save filings in directory.
CLN: Rearrange to have all properties at start
coyo8_sec-edgar
train
2b3289ceade0530a8b9ab178c844aeadb1aea956
diff --git a/lib/giantbomb.rb b/lib/giantbomb.rb index <HASH>..<HASH> 100644 --- a/lib/giantbomb.rb +++ b/lib/giantbomb.rb @@ -6,5 +6,5 @@ require 'httparty' end module GiantBomb - VERSION = "0.0.1" + VERSION = "0.0.2" end \ No newline at end of file
bumped version to <I>
games-directory_api-giantbomb
train
93eff19f5fad5e0e8e8556eb235edbe657b999bd
diff --git a/main/src/main/java/tachyon/UnderFileSystem.java b/main/src/main/java/tachyon/UnderFileSystem.java index <HASH>..<HASH> 100644 --- a/main/src/main/java/tachyon/UnderFileSystem.java +++ b/main/src/main/java/tachyon/UnderFileSystem.java @@ -46,8 +46,7 @@ public abstract class UnderFileSystem { public static UnderFileSystem get(String path) { if (path.startsWith("hdfs://") || path.startsWith("s3://") || path.startsWith("s3n://")) { return UnderFileSystemHdfs.getClient(path); - } else if (path.startsWith(Constants.PATH_SEPARATOR) || path.startsWith("file://") - || path.isEmpty()) { //path is empty in UnderfsUtil.loadUnderFs/5 for local FS + } else if (path.startsWith(Constants.PATH_SEPARATOR) || path.startsWith("file://")) { return UnderFileSystemSingleLocal.getClient(); } CommonUtils.illegalArgumentException("Unknown under file system scheme " + path); @@ -55,16 +54,16 @@ public abstract class UnderFileSystem { } /** - * Transform an input string like hdfs://host:port/dir, hdfs://host:port, /dir + * Transform an input string like hdfs://host:port/dir, hdfs://host:port, file:///dir, /dir * into a pair of address and path. The returned pairs are ("hdfs://host:port", "/dir"), - * ("hdfs://host:port", "/"), and ("", "/dir"), respectively. + * ("hdfs://host:port", "/"), and ("/", "/dir"), respectively. * * @param s * the input path string * @return null if s does not start with tachon://, tachyon-ft://, hdfs://, s3://, s3n://, * file://, /. Or a pair of strings denoting the under FS address and the relative path * relative to that address. For local FS (with prefixes file:// or /), the under FS - * address is "" and the path starts with "/". + * address is "/" and the path starts with "/". */ public static Pair<String, String> parse(String s) { if (s == null) { @@ -82,7 +81,7 @@ public abstract class UnderFileSystem { } else if (s.startsWith("file://") || s.startsWith(Constants.PATH_SEPARATOR)) { String prefix = "file://"; String suffix = s.startsWith(prefix) ? s.substring(prefix.length()) : s; - new Pair<String, String>("", suffix); + return new Pair<String, String>(Constants.PATH_SEPARATOR, suffix); } return null; diff --git a/main/src/main/java/tachyon/util/UnderfsUtil.java b/main/src/main/java/tachyon/util/UnderfsUtil.java index <HASH>..<HASH> 100644 --- a/main/src/main/java/tachyon/util/UnderfsUtil.java +++ b/main/src/main/java/tachyon/util/UnderfsUtil.java @@ -46,7 +46,7 @@ public class UnderfsUtil { * @param tfs * the TFS handler created out of address like "tachyon://host:port" * @param underfsAddress - * the address of underFS server, like "hdfs://h:p", or "" for local FS. + * the address of underFS server, like "hdfs://h:p", or "/" for local FS. * @param rootPath * the source path in underFS, like "/dir". * @param excludePathPrefix @@ -76,7 +76,7 @@ public class UnderfsUtil { */ public static void getInfo(TachyonFS tfs, String tfsRoot, String underfsAddress, String rootPath, PrefixList excludePathPrefix) throws IOException { - String underfsRootPath = underfsAddress + rootPath; + String underfsRootPath = (underfsAddress + rootPath).replace("//", "/"); LOG.info(tfs + tfsRoot + " " + underfsRootPath + " " + excludePathPrefix); if (!tfs.exist(tfsRoot)) { @@ -118,8 +118,8 @@ public class UnderfsUtil { for (String filePath : files) { LOG.info("Get: " + filePath); String aPath = (path + "/" + filePath).replace("//", "/"); - if (isFirstLevel && excludePathPrefix.outList(filePath)) { - pathQueue.add(aPath); + if (isFirstLevel && excludePathPrefix.inList(filePath)) { + LOG.info("excluded: "+filePath); } else { pathQueue.add(aPath); }
change local FS underfsAddress to /; fix a bug in excluding prefix-matching paths
Alluxio_alluxio
train
9f3d26d90ec316c5ecd6f6f311c009cd72198ca8
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -85,7 +85,7 @@ function SerialPortListener(){ this.Dimmer=function (offset){ this.parent=parent; this.head="55000a0701eb"; - this.adr=(parseInt(base,16)+offset).toString(16) + this.adr=(parseInt(base,16)+parseInt(offset)).toString(16) this.speed="01" this.setValue=function(val){ var value=pad(parseInt(val).toString(16),2) @@ -110,7 +110,7 @@ function SerialPortListener(){ this.Button=function (offset){ this.parent=parent; this.head="55000707017a"; - this.adr=(parseInt(base,16)+offset).toString(16) + this.adr=(parseInt(base,16)+parseInt(offset)).toString(16) this.B0={ click:function(){ this.B0.down()
make sure offset is allways a number
enocean-js_node-enocean
train
0a1ed5f9bc9d94ab959af6a63cfc4a67cae69730
diff --git a/parsl/executors/status_handling.py b/parsl/executors/status_handling.py index <HASH>..<HASH> 100644 --- a/parsl/executors/status_handling.py +++ b/parsl/executors/status_handling.py @@ -177,7 +177,7 @@ class BlockProviderExecutor(ParslExecutor): launch_cmd = self._get_launch_command(block_id) job_id = self.provider.submit(launch_cmd, 1) if job_id: - logger.debug("Launched block {}->{}".format(block_id, job_id)) + logger.debug(f"Launched block {block_id} on executor {self.label} with job ID {job_id}") else: raise ScalingFailed(self, "Attempt to provision nodes did not return a job ID")
Disambiguate which executor blocks are launched on (#<I>) Elaborate on x->y notation to be clear what the x and y values are in the log message
Parsl_parsl
train
1fd8fba0459e44eb05a4eff73b03856d12b79006
diff --git a/tests/commands/envelope_test.py b/tests/commands/envelope_test.py index <HASH>..<HASH> 100644 --- a/tests/commands/envelope_test.py +++ b/tests/commands/envelope_test.py @@ -26,6 +26,7 @@ import unittest import mock from alot.commands import envelope +from alot.db.envelope import Envelope # When using an assert from a mock a TestCase method might not use self. That's # okay. @@ -110,3 +111,49 @@ class TestAttachCommand(unittest.TestCase): cmd = envelope.AttachCommand(path=os.path.join(d, 'doesnt-exist')) cmd.apply(ui) ui.notify.assert_called() + + +class TestTagCommands(unittest.TestCase): + + def _test(self, tagstring, action, expected): + """Common steps for envelope.TagCommand tests + + :param tagstring: the string to pass to the TagCommand + :type tagstring: str + :param action: the action to pass to the TagCommand + :type action: str + :param expected: the expected output to assert in the test + :type expected: list(str) + """ + env = Envelope(tags=['one', 'two', 'three']) + ui = mock.Mock() + ui.current_buffer = mock.Mock() + ui.current_buffer.envelope = env + cmd = envelope.TagCommand(tags=tagstring, action=action) + cmd.apply(ui) + actual = env.tags + self.assertListEqual(sorted(actual), sorted(expected)) + + def test_add_new_tags(self): + self._test(u'four', 'add', ['one', 'two', 'three', 'four']) + + def test_adding_existing_tags_has_no_effect(self): + self._test(u'one', 'add', ['one', 'two', 'three']) + + def test_remove_existing_tags(self): + self._test(u'one', 'remove', ['two', 'three']) + + def test_remove_non_existing_tags_has_no_effect(self): + self._test(u'four', 'remove', ['one', 'two', 'three']) + + def test_set_tags(self): + self._test(u'a,b,c', 'set', ['a', 'b', 'c']) + + def test_toggle_will_remove_existing_tags(self): + self._test(u'one', 'toggle', ['two', 'three']) + + def test_toggle_will_add_new_tags(self): + self._test(u'four', 'toggle', ['one', 'two', 'three', 'four']) + + def test_toggle_can_remove_and_add_in_one_run(self): + self._test(u'one,four', 'toggle', ['two', 'three', 'four'])
Add tests for new commands The test file is also renamed.
pazz_alot
train
5b3e6b965f486961b54bec72470f4459350f4d4b
diff --git a/src/Analyser/NodeScopeResolver.php b/src/Analyser/NodeScopeResolver.php index <HASH>..<HASH> 100644 --- a/src/Analyser/NodeScopeResolver.php +++ b/src/Analyser/NodeScopeResolver.php @@ -501,10 +501,6 @@ class NodeScopeResolver } return; - } elseif ($node instanceof Do_) { - foreach ($node->stmts as $statement) { - $scope = $this->lookForAssigns($scope, $statement, TrinaryLogic::createYes()); - } } elseif ($node instanceof FuncCall) { $scope = $scope->enterFunctionCall($node); } elseif ($node instanceof Expr\StaticCall) { @@ -624,6 +620,10 @@ class NodeScopeResolver } } + if ($node instanceof Do_ && $subNodeName === 'stmts') { + $scope = $this->lookForAssigns($scope, $node->cond, TrinaryLogic::createMaybe()); + } + $this->processNodes($subNode, $scope, $nodeCallback, $argClosureBindScope); } elseif ($subNode instanceof \PhpParser\Node) { if ($node instanceof Coalesce && $subNodeName === 'left') { @@ -679,6 +679,12 @@ class NodeScopeResolver $scope = $this->lookForAssigns($scope, $node->cond, TrinaryLogic::createYes()); } + if ($node instanceof Do_ && $subNodeName === 'cond') { + foreach ($node->stmts as $statement) { + $scope = $this->lookForAssigns($scope, $statement, TrinaryLogic::createYes()); + } + } + $nodeScope = $scope->exitFirstLevelStatements(); if ($scope->isInFirstLevelStatement()) { if ($node instanceof Ternary && $subNodeName !== 'cond') { diff --git a/tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php b/tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php index <HASH>..<HASH> 100644 --- a/tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php +++ b/tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php @@ -151,6 +151,10 @@ class DefinedVariableRuleTest extends \PHPStan\Rules\AbstractRuleTest 'Undefined variable: $variableInBitwiseAndAssign', 278, ], + [ + 'Variable $mightBeUndefinedInDoWhile might not be defined.', + 282, + ], ]); } diff --git a/tests/PHPStan/Rules/Variables/VariableCertaintyInIssetRuleTest.php b/tests/PHPStan/Rules/Variables/VariableCertaintyInIssetRuleTest.php index <HASH>..<HASH> 100644 --- a/tests/PHPStan/Rules/Variables/VariableCertaintyInIssetRuleTest.php +++ b/tests/PHPStan/Rules/Variables/VariableCertaintyInIssetRuleTest.php @@ -33,6 +33,10 @@ class VariableCertaintyInIssetRuleTest extends \PHPStan\Rules\AbstractRuleTest 'Variable $yetYetAnotherNeverDefinedVariableInIsset in isset() is never defined.', 53, ], + [ + 'Variable $anotherVariableInDoWhile in isset() always exists and is not nullable.', + 101, + ], ]); } diff --git a/tests/PHPStan/Rules/Variables/data/defined-variables.php b/tests/PHPStan/Rules/Variables/data/defined-variables.php index <HASH>..<HASH> 100644 --- a/tests/PHPStan/Rules/Variables/data/defined-variables.php +++ b/tests/PHPStan/Rules/Variables/data/defined-variables.php @@ -277,3 +277,10 @@ echo $variableInListWithMissingItem; $variableInBitwiseAndAssign &= $anotherVariableBitwiseAndAssign = doFoo(); echo $variableInBitwiseAndAssign; echo $anotherVariableBitwiseAndAssign; + +do { + echo $mightBeUndefinedInDoWhile; + $definedInDoWhile = 1; +} while ($mightBeUndefinedInDoWhile = 1); + +echo $definedInDoWhile; diff --git a/tests/PHPStan/Rules/Variables/data/variable-certainty-isset.php b/tests/PHPStan/Rules/Variables/data/variable-certainty-isset.php index <HASH>..<HASH> 100644 --- a/tests/PHPStan/Rules/Variables/data/variable-certainty-isset.php +++ b/tests/PHPStan/Rules/Variables/data/variable-certainty-isset.php @@ -88,3 +88,16 @@ if (something()) { while (isset($variableInWhile)) { unset($variableInWhile); } + +if (something()) { + $variableInDoWhile = 1; +} + +do { + $anotherVariableInDoWhile = 1; + echo isset($yetAnotherVariableInDoWhile); // fine +} while ( + isset($variableInDoWhile) // fine + && isset($anotherVariableInDoWhile) // always defined + && ($yetAnotherVariableInDoWhile = 1) +);
VariableCertaintyInIssetRule - fixed isset() in do-while loop
phpstan_phpstan
train
dfd43330e7b42f66d0351fd7045c903dc5ee898c
diff --git a/packages/ember-engines/tests/acceptance/teardown-test.js b/packages/ember-engines/tests/acceptance/teardown-test.js index <HASH>..<HASH> 100644 --- a/packages/ember-engines/tests/acceptance/teardown-test.js +++ b/packages/ember-engines/tests/acceptance/teardown-test.js @@ -1,4 +1,4 @@ -import { module, test, skip } from 'qunit'; +import { module, test } from 'qunit'; import startApp from '../helpers/start-app'; import destroyApp from '../helpers/destroy-app'; @@ -20,8 +20,7 @@ test('routeable engines clean up their container state', async function(assert) assert.ok(service.isDestroyed, 'service got destroyed'); }); -// TODO: Unskip test after investigating issue with destroyables in ember 3.20 -skip('routeless engines clean up their container state', async function(assert) { +test('routeless engines clean up their container state', async function(assert) { let service; assert.expect(2); this.application = startApp();
Re-enable routeless engine container cleanup test. This test was disabled due to a failure on Ember <I>, which has subsequently been fixed in Ember <I>.
ember-engines_ember-engines
train
94083023172a755b716cb4ebeb2e577d62de7220
diff --git a/openquake/engine/calculators/hazard/event_based/core.py b/openquake/engine/calculators/hazard/event_based/core.py index <HASH>..<HASH> 100644 --- a/openquake/engine/calculators/hazard/event_based/core.py +++ b/openquake/engine/calculators/hazard/event_based/core.py @@ -297,7 +297,6 @@ class GmfCalculator(object): for rupid, gmfa in zip(rupids, computer.compute(seeds)): for gname in gmfa.dtype.fields: gmf_by_imt = gmfa[gname] - print gmf_by_imt for imt in self.sorted_imts: for site_id, gmv in zip(r_sites.sids, gmf_by_imt[imt]): self.gmvs_per_site[
Removed a debugging print
gem_oq-engine
train
5a386f5f1ad3f9a4d41f7b2ca0afea33e148bbed
diff --git a/docs-site/src/pages/pattern-lab/_patterns/40-components/text/15-text-tag-variations.twig b/docs-site/src/pages/pattern-lab/_patterns/40-components/text/15-text-tag-variations.twig index <HASH>..<HASH> 100644 --- a/docs-site/src/pages/pattern-lab/_patterns/40-components/text/15-text-tag-variations.twig +++ b/docs-site/src/pages/pattern-lab/_patterns/40-components/text/15-text-tag-variations.twig @@ -18,14 +18,4 @@ {% include text_code.code_example(text_demo, true) %} {% endfor %} - - -{% set anchor_demo %} -<bolt-text tag="a" url="https://www.google.com"> - This text has its tag prop defined as: a -</bolt-text> -{% endset %} -{% include text_code.code_example(anchor_demo, true) %} - - {% endblock %} diff --git a/packages/components/bolt-text/src/text.js b/packages/components/bolt-text/src/text.js index <HASH>..<HASH> 100644 --- a/packages/components/bolt-text/src/text.js +++ b/packages/components/bolt-text/src/text.js @@ -37,7 +37,10 @@ class BoltText extends BoltElement { this.fontSize = this.setDefaultValue('font-size', 'xlarge'); this.fontWeight = this.setDefaultValue('font-weight', 'bold'); - if (this.textContent.trim().length >= 60 && fontSize === 'xxxlarge') { + if ( + this.textContent.trim().length >= 60 && + this.fontSize === 'xxxlarge' + ) { longText = true; } } @@ -139,10 +142,6 @@ class BoltText extends BoltElement { return html` <span class="${classes}">${innerHTML}</span> `; - case 'cite': - return html` - <cite class="${classes}">${innerHTML}</cite> - `; default: return html` <p class="${classes}">${innerHTML}</p> diff --git a/packages/components/bolt-text/text.schema.js b/packages/components/bolt-text/text.schema.js index <HASH>..<HASH> 100644 --- a/packages/components/bolt-text/text.schema.js +++ b/packages/components/bolt-text/text.schema.js @@ -17,19 +17,7 @@ module.exports = { type: 'string', description: 'HTML semantic tags.', default: 'p', - enum: [ - 'h1', - 'h2', - 'h3', - 'h4', - 'h5', - 'h6', - 'p', - 'div', - 'span', - 'cite', - 'a', - ], + enum: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'div', 'span'], }, display: { type: 'string',
DS-<I>: remove anchor demo, fix fontSize bug, remove cite case since we're deprecating it.
bolt-design-system_bolt
train
6ca3b3faa7e3ec29d01016fdc7bd656ff0e8a64e
diff --git a/src/filters.php b/src/filters.php index <HASH>..<HASH> 100644 --- a/src/filters.php +++ b/src/filters.php @@ -40,7 +40,7 @@ array_map(function ($type) { }); }, [ 'index', '404', 'archive', 'author', 'category', 'tag', 'taxonomy', 'date', 'home', - 'front_page', 'page', 'paged', 'search', 'single', 'singular', 'attachment' + 'frontpage', 'page', 'paged', 'search', 'single', 'singular', 'attachment' ]); /**
front_page => frontpage Correct the value based on what WordPress passes as filter values <URL>
roots_sage
train
5914704eb2a19bcc5f19b1f1778fe7a330d78077
diff --git a/lib/sneakers/queue.rb b/lib/sneakers/queue.rb index <HASH>..<HASH> 100644 --- a/lib/sneakers/queue.rb +++ b/lib/sneakers/queue.rb @@ -46,7 +46,7 @@ class Sneakers::Queue handler_klass = worker.opts[:handler] || Sneakers::CONFIG[:handler] handler = handler_klass.new(@channel, queue, worker.opts) - @consumer = queue.subscribe(:block => false, :ack => @opts[:ack]) do | delivery_info, metadata, msg | + @consumer = queue.subscribe(:block => false, :manual_ack => @opts[:ack]) do | delivery_info, metadata, msg | worker.do_work(delivery_info, metadata, msg, handler) end nil diff --git a/spec/sneakers/queue_spec.rb b/spec/sneakers/queue_spec.rb index <HASH>..<HASH> 100644 --- a/spec/sneakers/queue_spec.rb +++ b/spec/sneakers/queue_spec.rb @@ -44,7 +44,7 @@ describe Sneakers::Queue do q = Sneakers::Queue.new("downloads", queue_vars) mock(@mkqueue).bind(@mkex, :routing_key => "downloads") - mock(@mkqueue).subscribe(:block => false, :ack => true) + mock(@mkqueue).subscribe(:block => false, :manual_ack => true) q.subscribe(@mkworker) end @@ -56,7 +56,7 @@ describe Sneakers::Queue do mock(@mkqueue).bind(@mkex, :routing_key => "alpha") mock(@mkqueue).bind(@mkex, :routing_key => "beta") - mock(@mkqueue).subscribe(:block => false, :ack => true) + mock(@mkqueue).subscribe(:block => false, :manual_ack => true) q.subscribe(@mkworker) end @@ -80,7 +80,7 @@ describe Sneakers::Queue do q = Sneakers::Queue.new("test_nondurable", queue_vars) mock(@mkqueue_nondurable).bind(@mkex, :routing_key => "test_nondurable") - mock(@mkqueue_nondurable).subscribe(:block => false, :ack => true) + mock(@mkqueue_nondurable).subscribe(:block => false, :manual_ack => true) q.subscribe(@mkworker) myqueue = q.instance_variable_get(:@queue)
Switch to :manual_ack to remove deprecation warning.
jondot_sneakers
train
08b82193ed5dc26b6bdb5d3cac3311675447b768
diff --git a/lib/AbstractObject.php b/lib/AbstractObject.php index <HASH>..<HASH> 100644 --- a/lib/AbstractObject.php +++ b/lib/AbstractObject.php @@ -489,19 +489,21 @@ abstract class AbstractObject */ function exception($message, $type = null, $code = null) { - if (!$type) { + if (! $type) { $type=$this->default_exception; } elseif ($type[0]=='_') { $type=$this->default_exception.'_'.substr($type, 1); - } elseif($type=='Exception' || $type=='BaseException') { - $type='BaseException'; - } elseif(strpos($type,'Exception_')!==0) { + } elseif ($type!='BaseException' && strpos($type,'Exception_')!==0) { $type='Exception_'.$type; } - + // Localization support $message=$this->api->_($message); + if ($type=='Exception') { + $type='BaseException'; + } + $e=new $type($message,$code); $e->owner=$this; $e->api=$this->api;
AbstractObject: bugfix for my fix :) Partly reverting <URL>
atk4_atk4
train
cd6cf6b6e4ac7df8ab0540429228bc54ca2f267c
diff --git a/pluginfile.php b/pluginfile.php index <HASH>..<HASH> 100644 --- a/pluginfile.php +++ b/pluginfile.php @@ -524,7 +524,7 @@ if ($component === 'blog') { send_file_not_found(); } - require_login($course); + require_course_login($course, true); $groupid = (int)array_shift($args); @@ -534,6 +534,9 @@ if ($component === 'blog') { } if ($filearea === 'description') { + + require_login($course); + $filename = array_pop($args); $filepath = $args ? '/'.implode('/', $args).'/' : '/'; if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
pluginfile MDLSITE-<I> Relaxed login check on pluginfile surrounding group icons
moodle_moodle
train
66597585c12f87e35dfb8dc643d94434679be515
diff --git a/boolean/boolean.py b/boolean/boolean.py index <HASH>..<HASH> 100644 --- a/boolean/boolean.py +++ b/boolean/boolean.py @@ -470,21 +470,25 @@ class Expression(object): """ return set(s.obj for s in self.symbols) + def get_literals(self): + """ + Return a list of all the literals contained in this expression. + Include recursively subexpressions symbols. + This includes duplicates. + """ + if self.isliteral: + return [self] + if not self.args: + return [] + return list(itertools.chain.from_iterable(arg.literals for arg in self.args)) + @property def literals(self): """ Return a set of all literals contained in this expression. Include recursively subexpressions literals. """ - if self.isliteral: - return set((self,)) - if not self.args: - return set() - - s = set() - for arg in self.args: - s |= arg.literals - return s + return set(self.get_literals()) def literalize(self): """ @@ -499,21 +503,22 @@ class Expression(object): return self.__class__(*args) - @property - def symbols(self): + def get_symbols(self): """ - Return a set of all symbols contained in this expression. + Return a list of all the symbols contained in this expression. Include recursively subexpressions symbols. + This includes duplicates. """ - if isinstance(self, Symbol): - return set([self]) - if not self.args: - return set() + return [s for s in self.literals if isinstance(s, Symbol)] - s = set() - for arg in self.args: - s |= arg.symbols - return s + @property + def symbols(self, ): + """ + Return a list of all the symbols contained in this expression. + Include recursively subexpressions symbols. + This includes duplicates. + """ + return set(self.get_symbols()) def subs(self, substitutions, simplify=True): """
#<I> Add new get_literals and get_symbols Expression methods * the methods allow to remove some code duplication and offer a way to get all symbols and literals instances too.
bastikr_boolean.py
train
fe14638b520d56a7d2a07b6bebdaaef3f8528864
diff --git a/lib/transforms/reviewContentSecurityPolicy.js b/lib/transforms/reviewContentSecurityPolicy.js index <HASH>..<HASH> 100644 --- a/lib/transforms/reviewContentSecurityPolicy.js +++ b/lib/transforms/reviewContentSecurityPolicy.js @@ -327,6 +327,18 @@ module.exports = (queryObj, options) => { } let origins = [...originsToAdd]; if (options.update) { + if (originsToAdd.includes("'unsafe-inline'")) { + assetGraph.warn( + new Error( + `${htmlAsset.urlOrDescription} contains one or more inline ${ + directive === 'styleSrc' + ? 'style attributes' + : 'event handlers' + }, which cannot be whitelisted with CSP level 2 except via 'unsafe-inline', which almost defeats the purpose of having a CSP\n` + + "The 'unsafe-hashed-attributes' CSP3 keyword will allow it, but at the time of writing the spec is not finalized and no browser implements it." + ) + ); + } origins = _.uniq([...origins, ...existingOrigins]); let noncesWereRemoved = false; const seenNonces = seenNoncesByDirective[directive] || []; @@ -444,19 +456,6 @@ module.exports = (queryObj, options) => { .join('\n ') ) ); - } else { - assetGraph.warn( - new Error( - `${ - htmlAsset.urlOrDescription - } contains one or more inline ${ - directive === 'styleSrc' - ? 'style attributes' - : 'event handlers' - }, which cannot be whitelisted with CSP level 2.\n` + - "The 'unsafe-hashed-attributes' CSP3 keyword will allow it, but at the time of writing the spec is not finalized and no browser implements it." - ) - ); } } else { assetGraph.warn( diff --git a/test/transforms/reviewContentSecurityPolicy.js b/test/transforms/reviewContentSecurityPolicy.js index <HASH>..<HASH> 100644 --- a/test/transforms/reviewContentSecurityPolicy.js +++ b/test/transforms/reviewContentSecurityPolicy.js @@ -1101,13 +1101,15 @@ describe('transforms/reviewContentSecurityPolicy', function() { describe('with an inline event handler', function() { describe('in update:true mode', function() { describe('with level=2', function() { - it("should add 'unsafe-inline' instead of 'unsafe-hashed-attributes'", async function() { + it("should add 'unsafe-inline' instead of 'unsafe-hashed-attributes' and emit a warning", async function() { const assetGraph = new AssetGraph({ root: pathModule.resolve( __dirname, '../../testdata/transforms/reviewContentSecurityPolicy/existingContentSecurityPolicy/inlineEventHandler/' ) }); + const warnSpy = sinon.spy().named('warn'); + assetGraph.on('warn', warnSpy); await assetGraph.loadAssets('index.html'); await assetGraph.reviewContentSecurityPolicy(undefined, { level: 2, @@ -1122,6 +1124,13 @@ describe('transforms/reviewContentSecurityPolicy', function() { scriptSrc: ["'unsafe-inline'"] } ); + + expect(warnSpy, 'to have calls satisfying', () => { + warnSpy( + `testdata/transforms/reviewContentSecurityPolicy/existingContentSecurityPolicy/inlineEventHandler/index.html contains one or more inline event handlers, which cannot be whitelisted with CSP level 2 except via 'unsafe-inline', which almost defeats the purpose of having a CSP\n` + + `The 'unsafe-hashed-attributes' CSP3 keyword will allow it, but at the time of writing the spec is not finalized and no browser implements it.` + ); + }); }); describe("when the existing CSP allows 'unsafe-inline'", function() {
reviewCSP: Tweak the wording of the 'unsafe-inline' warning, and make sure it is emitted
assetgraph_assetgraph
train
2e553f8d343316ac201c0bc95a0abda570822f3e
diff --git a/src/Codeception/Util/Connector/Kohana.php b/src/Codeception/Util/Connector/Kohana.php index <HASH>..<HASH> 100644 --- a/src/Codeception/Util/Connector/Kohana.php +++ b/src/Codeception/Util/Connector/Kohana.php @@ -37,7 +37,7 @@ class Kohana extends \Symfony\Component\BrowserKit\Client { $kohanaRequest->cookie($_COOKIE); - $kohanaRequest::initial = $kohanaRequest; + $kohanaRequest::$initial = $kohanaRequest; $content = $kohanaRequest->execute()->render(); $headers = (array)$kohanaRequest->response()->headers();
Syntax error in Kohana connector
Codeception_Codeception
train
95c58269b998a1544697b1464fca749e5d318296
diff --git a/builtin/providers/aws/resource_aws_cloudwatch_log_subscription_filter_test.go b/builtin/providers/aws/resource_aws_cloudwatch_log_subscription_filter_test.go index <HASH>..<HASH> 100644 --- a/builtin/providers/aws/resource_aws_cloudwatch_log_subscription_filter_test.go +++ b/builtin/providers/aws/resource_aws_cloudwatch_log_subscription_filter_test.go @@ -103,7 +103,7 @@ func testAccAWSCloudwatchLogSubscriptionFilterConfig(rstring string) string { return fmt.Sprintf(` resource "aws_cloudwatch_log_subscription_filter" "test_lambdafunction_logfilter" { name = "test_lambdafunction_logfilter_%s" - log_group_name = "example_lambda_name" + log_group_name = "${aws_cloudwatch_log_group.logs.name}" filter_pattern = "logtype test" destination_arn = "${aws_lambda_function.test_lambdafunction.arn}" }
provider/aws: fix TestAccAWSCloudwatchLogSubscriptionFilter_basic by linking the name
hashicorp_terraform
train
1ffd2bd7e5023cd81464f0a6ac1ac8e6c0816183
diff --git a/test/host/bdd.js b/test/host/bdd.js index <HASH>..<HASH> 100644 --- a/test/host/bdd.js +++ b/test/host/bdd.js @@ -4,17 +4,18 @@ /*global console, setTimeout, clearTimeout*/ - var context = (function () { - /*global global*/ // NodeJS global - if ("object" === typeof global) { - return global; - } - /*global window*/ // Browser global - if ("undefined" !== typeof window) { - return window; - } - return this; //eslint-disable-line no-invalid-this - }()); + var safeFunction = Function, + context = (function () { + /*global global*/ // NodeJS global + if ("object" === typeof global) { + return global; + } + /*global window*/ // Browser global + if ("undefined" !== typeof window) { + return window; + } + return safeFunction("return this;")(); + }()); /* * Simple BDD implementation
Support Nashorn: access to global (#<I>)
ArnaudBuchholz_gpf-js
train
aa7e2c049be18653508161293cc7e73dccba880b
diff --git a/app/helpers/linkify.js b/app/helpers/linkify.js index <HASH>..<HASH> 100644 --- a/app/helpers/linkify.js +++ b/app/helpers/linkify.js @@ -1 +1,2 @@ -export { default, linkify } from 'ember-linkify/helpers/linkify'; +import Linkify from 'ember-linkify/helpers/linkify'; +export default Linkify; diff --git a/tests/unit/helpers/linkify-test.js b/tests/unit/helpers/linkify-test.js index <HASH>..<HASH> 100644 --- a/tests/unit/helpers/linkify-test.js +++ b/tests/unit/helpers/linkify-test.js @@ -1,6 +1,6 @@ import { linkify -} from '../../../helpers/linkify'; +} from 'ember-linkify/helpers/linkify'; import { module, test } from 'qunit'; module('Unit | Helper | linkify');
Continue attempting to get the tests to pass
johno_ember-linkify
train
03ac407276c3347306db774050c8568815a86d67
diff --git a/lxd/lifecycle/storage_volume_backup.go b/lxd/lifecycle/storage_volume_backup.go index <HASH>..<HASH> 100644 --- a/lxd/lifecycle/storage_volume_backup.go +++ b/lxd/lifecycle/storage_volume_backup.go @@ -1,12 +1,9 @@ package lifecycle import ( - "fmt" - "net/url" - - "github.com/lxc/lxd/lxd/project" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" + "github.com/lxc/lxd/shared/version" ) // StorageVolumeBackupAction represents a lifecycle event action for storage volume backups. @@ -21,21 +18,14 @@ const ( ) // Event creates the lifecycle event for an action on a storage volume backup. -func (a StorageVolumeBackupAction) Event(poolName string, volumeType string, volumeName string, projectName string, requestor *api.EventLifecycleRequestor, ctx map[string]any) api.EventLifecycle { - parentName, backupName, _ := shared.InstanceGetParentAndSnapshotName(volumeName) - - u := fmt.Sprintf("/1.0/storage-pools/%s/volumes/%s/%s/backups", url.PathEscape(poolName), url.PathEscape(volumeType), url.PathEscape(parentName)) - if backupName != "" { - u = fmt.Sprintf("%s/%s", u, backupName) - } +func (a StorageVolumeBackupAction) Event(poolName string, volumeType string, fullBackupName string, projectName string, requestor *api.EventLifecycleRequestor, ctx map[string]any) api.EventLifecycle { + volumeName, backupName, _ := shared.InstanceGetParentAndSnapshotName(fullBackupName) - if projectName != project.Default { - u = fmt.Sprintf("%s?project=%s", u, url.QueryEscape(projectName)) - } + u := api.NewURL().Path(version.APIVersion, "storage-pools", poolName, "volumes", volumeType, volumeName, "backups", backupName).Project(projectName) return api.EventLifecycle{ Action: string(a), - Source: u, + Source: u.String(), Context: ctx, Requestor: requestor, }
lxd/lifecycle/storage/volume/backup: Updates StorageVolumeBackupAction.Event to clarify the type of backup name required And updates to use api.NewURL().
lxc_lxd
train
0655db6843d1120caf4b515c9f2be65a01d44fee
diff --git a/lib/Thelia/Command/ModuleRefreshCommand.php b/lib/Thelia/Command/ModuleRefreshCommand.php index <HASH>..<HASH> 100644 --- a/lib/Thelia/Command/ModuleRefreshCommand.php +++ b/lib/Thelia/Command/ModuleRefreshCommand.php @@ -36,7 +36,7 @@ class ModuleRefreshCommand extends ContainerAwareCommand { try { $moduleManagement = new ModuleManagement; - $moduleManagement->updateModules(); + $moduleManagement->updateModules($this->getContainer()); } catch (\Exception $e) { throw new \RuntimeException(sprintf('Refresh modules list fail with Exception : [%d] %s', $e->getCode(), $e->getMessage())); }
Container is now required by ModuleManagement::updateModules()
thelia_core
train
bc203747192852a0e0ed88ec6c7ab83baaddc415
diff --git a/shared/chat/conversations-list/index.native.js b/shared/chat/conversations-list/index.native.js index <HASH>..<HASH> 100644 --- a/shared/chat/conversations-list/index.native.js +++ b/shared/chat/conversations-list/index.native.js @@ -97,9 +97,7 @@ const BottomLine = ({participantNeedToRekey, youNeedToRekey, isMuted, showBold, return ( <Box style={{...globalStyles.flexBoxRow, alignItems: 'center', maxHeight: 17, minHeight: 17, position: 'relative', backgroundColor}}> - <Box style={{...globalStyles.flexBoxColumn, bottom: 0, justifyContent: 'flex-start', left: 0, position: 'absolute', right: 0, top: 0, backgroundColor}}> - {content} - </Box> + {content} </Box> ) }
Fix cut off emoji on Android conversation list
keybase_client
train
3f6b55a32064d370cfc648393c22254ac48d2c4c
diff --git a/src/services/line-stat-getter.js b/src/services/line-stat-getter.js index <HASH>..<HASH> 100644 --- a/src/services/line-stat-getter.js +++ b/src/services/line-stat-getter.js @@ -1,10 +1,7 @@ /* eslint-disable no-underscore-dangle */ import _ from 'lodash'; import P from 'bluebird'; -import moment from 'moment'; -// NOTICE: moment-timezone extends moment itself, -// Importing it will automatically add functions to moment. -import 'moment-timezone'; +import moment from 'moment-timezone'; import Interface from 'forest-express'; import QueryBuilder from './query-builder'; import utils from '../utils/schema';
fix: switched moment to moment-tz for line-stat-getter (#<I>)
ForestAdmin_forest-express-mongoose
train
f125873c500b8ee2c5739551c2b7848c4ab47f01
diff --git a/src/utils/subscription-registry.js b/src/utils/subscription-registry.js index <HASH>..<HASH> 100644 --- a/src/utils/subscription-registry.js +++ b/src/utils/subscription-registry.js @@ -187,12 +187,12 @@ class SubscriptionRegistry { * * @param {String} name the name/topic the subscriber was previously registered for * @param {String} msgString the message as string - * @param {[SocketWrapper]} sender an optional socketWrapper that shouldn't receive the message + * @param {[SocketWrapper]} socket an optional socketWrapper that shouldn't receive the message * * @public * @returns {void} */ - sendToSubscribers(name, msgString, sender) { + sendToSubscribers(name, msgString, socket) { if (!this._subscriptions.has(name)) { return } @@ -220,15 +220,15 @@ class SubscriptionRegistry { // uniqueSendersMap maps from uuid to offset in uniqueSendersVector // each uniqueSender has a vector of "gaps" in relation to sharedMessage - // senders should not receive what they sent themselves, so a gap is inserted - // for every send from this sender - if (sender && sender.uuid !== undefined) { + // sockets should not receive what they sent themselves, so a gap is inserted + // for every send from this socket + if (socket && socket.uuid !== undefined) { let uniqueSenders = delayedBroadcasts.uniqueSenders - let gaps = uniqueSenders.get(sender) + let gaps = uniqueSenders.get(socket) if (!gaps) { gaps = [] - uniqueSenders.set(sender, gaps) + uniqueSenders.set(socket, gaps) } gaps.push(start, stop)
style(subscription-registry): Rename sender to socket.
deepstreamIO_deepstream.io
train
9938f524565bea089339bba3e051febe972a71de
diff --git a/src/bin/kittik-list.js b/src/bin/kittik-list.js index <HASH>..<HASH> 100644 --- a/src/bin/kittik-list.js +++ b/src/bin/kittik-list.js @@ -1,10 +1,7 @@ #!/usr/bin/env node -var program = require('commander'); +import program from 'commander'; program .option('--only-themes', 'Print out installed themes') - .option('--only-presentations', 'Print out available presentations') .parse(process.argv); - -console.log(program.onlyThemes); diff --git a/src/bin/kittik-start.js b/src/bin/kittik-start.js index <HASH>..<HASH> 100644 --- a/src/bin/kittik-start.js +++ b/src/bin/kittik-start.js @@ -1,9 +1,7 @@ #!/usr/bin/env node -var program = require('commander'); -var pkg = require('../../package.json'); +import program from 'commander'; program - .version(pkg.version) .usage('<file> [options]') .parse(process.argv); diff --git a/src/bin/kittik.js b/src/bin/kittik.js index <HASH>..<HASH> 100644 --- a/src/bin/kittik.js +++ b/src/bin/kittik.js @@ -1,8 +1,7 @@ #!/usr/bin/env node -var program = require('commander'); -var pkg = require('../../package.json'); -var Cursor = require('../../lib/Cursor'); +import program from 'commander'; +import pkg from '../../package.json'; program .version(pkg.version)
refactor(cli): Split to sub-commands
ghaiklor_kittik
train
11e363325f80f7120ad071947c0f7bb60423bf01
diff --git a/CHANGES b/CHANGES index <HASH>..<HASH> 100644 --- a/CHANGES +++ b/CHANGES @@ -1,3 +1,9 @@ +Release 2.0 (April 2, 2014) +--------------------------- + +* Stable release. + + Release 2.0rc2 (March, 2014) ---------------------------- @@ -53,6 +59,7 @@ This is a beta release. implies, it returns the database vendor instead of the engine used. Treebeard will get the value from Django, but you can subclass the method if needed. + Release 1.61 (Jul 24, 2010) --------------------------- diff --git a/docs/conf.py b/docs/conf.py index <HASH>..<HASH> 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -36,9 +36,9 @@ templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = 'django-treebeard' -copyright = '2008-2013, Gustavo Picon' -version = '2.0rc1' -release = '2.0rc1' +copyright = '2008-2014, Gustavo Picon' +version = '2.0' +release = '2.0' exclude_trees = ['_build'] pygments_style = 'sphinx' html_theme = 'default' diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -25,7 +25,7 @@ class pytest_test(test): setup_args = dict( name='django-treebeard', - version='2.0rc1', + version='2.0', url='https://tabo.pe/projects/django-treebeard/', author='Gustavo Picon', author_email='tabo@tabo.pe', diff --git a/treebeard/__init__.py b/treebeard/__init__.py index <HASH>..<HASH> 100644 --- a/treebeard/__init__.py +++ b/treebeard/__init__.py @@ -1 +1 @@ -__version__ = '2.0rc1' +__version__ = '2.0'
Preparing for <I> release
django-treebeard_django-treebeard
train
a3ddce858c73789f6c51adcb4d5bb42e36fe34a6
diff --git a/lib/adhearsion/commands.rb b/lib/adhearsion/commands.rb index <HASH>..<HASH> 100644 --- a/lib/adhearsion/commands.rb +++ b/lib/adhearsion/commands.rb @@ -1,4 +1,5 @@ require 'fileutils' +require 'adhearsion/script_ahn_loader' module Adhearsion module CLI @@ -17,6 +18,14 @@ USAGE class << self def execute! + if ARGV.first == 'start' && !(ScriptAhnLoader.in_ahn_application? || ScriptAhnLoader.in_ahn_application_subdirectory?) + args = parse_arguments + Dir.chdir args[1] do + args = args.compact.map(&:to_s) + args[1], args[2] = args[2], '.' + ScriptAhnLoader.exec_script_ahn! args + end + end CommandHandler.send(*parse_arguments) rescue CommandHandler::CLIException => error fail_and_print_usage error @@ -48,7 +57,7 @@ USAGE if args.size == 2 path = args.last - if args.first =~ /daemon|console/ + if args.first =~ /foreground|daemon|console/ mode = args.first.to_sym else raise CommandHandler::CLIException, "Invalid start mode requested: #{args.first}" diff --git a/lib/adhearsion/script_ahn_loader.rb b/lib/adhearsion/script_ahn_loader.rb index <HASH>..<HASH> 100644 --- a/lib/adhearsion/script_ahn_loader.rb +++ b/lib/adhearsion/script_ahn_loader.rb @@ -6,10 +6,10 @@ module Adhearsion RUBY = File.join(*RbConfig::CONFIG.values_at("bindir", "ruby_install_name")) + RbConfig::CONFIG["EXEEXT"] SCRIPT_AHN = File.join('script', 'ahn') - def self.exec_script_ahn! + def self.exec_script_ahn!(args = ARGV) cwd = Dir.pwd return unless in_ahn_application? || in_ahn_application_subdirectory? - exec RUBY, SCRIPT_AHN, *ARGV if in_ahn_application? + exec RUBY, SCRIPT_AHN, *args if in_ahn_application? Dir.chdir("..") do # Recurse in a chdir block: if the search fails we want to be sure # the application is generated in the original working directory.
When starting an app, fork inside the app's directory so bundler works right
adhearsion_adhearsion
train
866713f110c59640951aa2b5de3e7bf5188d66c0
diff --git a/dataset/freeze/format/fjson.py b/dataset/freeze/format/fjson.py index <HASH>..<HASH> 100644 --- a/dataset/freeze/format/fjson.py +++ b/dataset/freeze/format/fjson.py @@ -1,6 +1,6 @@ import json from datetime import datetime, date -from collections import defaultdict +from collections import defaultdict, OrderedDict from decimal import Decimal from six import PY3 @@ -29,10 +29,10 @@ class JSONSerializer(Serializer): if self.mode == 'item': result = result[0] if self.export.get_bool('wrap', True): - result = { - 'count': len(result), - 'results': result - } + result = OrderedDict([ + ('count', len(result)), + ('results', result), + ]) meta = self.export.get('meta', {}) if meta is not None: result['meta'] = meta
Order JSON freeze fields deterministically To avoid commits like [this one](<URL>) on Python 3
pudo_dataset
train
f756b2a9aa89e228cf34c0e343773225240205ed
diff --git a/lib/ruby-lint/definition/ruby_object.rb b/lib/ruby-lint/definition/ruby_object.rb index <HASH>..<HASH> 100644 --- a/lib/ruby-lint/definition/ruby_object.rb +++ b/lib/ruby-lint/definition/ruby_object.rb @@ -78,6 +78,13 @@ module RubyLint :method ] + ## + # String used to separate segments in a constant path. + # + # @return [String] + # + PATH_SEPARATOR = '::' + attr_reader :column, :definitions, :file, @@ -237,6 +244,33 @@ module RubyLint end ## + # Returns the definition for the given constant path. If one of the + # segments does not exist an error is raised instead. + # + # @param [String|Array] path + # @return [RubyLint::Definition::RubyObject] + # @raise ArgumentError Raised when an invalid constant path is specified. + # + def lookup_constant_path(path) + constant = self + path = path.split(PATH_SEPARATOR) if path.is_a?(String) + + path.each do |segment| + found = constant.lookup(:constant, segment) + + if found + constant = found + else + name = path.join(PATH_SEPARATOR) + + raise ArgumentError, "Invalid constant path: #{name}" + end + end + + return constant + end + + ## # Mimics a method call based on the given method name and the instance # type of the current definition. # @@ -450,7 +484,15 @@ module RubyLint # @return [RubyLint::Definition::RubyObject] # def define_constant(name, &block) - return add_child_definition(name, :constant, &block) + if name.include?(PATH_SEPARATOR) + path = name.split(PATH_SEPARATOR) + target = lookup_constant_path(path[0..-2]) + definition = target.define_constant(path[-1], &block) + else + definition = add_child_definition(name, :constant, &block) + end + + return definition end ## diff --git a/spec/ruby-lint/definition/dsl.rb b/spec/ruby-lint/definition/dsl.rb index <HASH>..<HASH> 100644 --- a/spec/ruby-lint/definition/dsl.rb +++ b/spec/ruby-lint/definition/dsl.rb @@ -49,6 +49,16 @@ describe RubyLint::Definition::RubyObject do .is_a?(@ruby_object) \ .should == true end + + should 'define a constant using a constant path' do + @first.define_constant('A') + @first.define_constant('A::B') + + @first.lookup(:constant, 'A') \ + .lookup(:constant, 'B') \ + .is_a?(@ruby_object) \ + .should == true + end end describe 'defining methods using a DSL' do
Defining constants using constant paths.
YorickPeterse_ruby-lint
train