hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
0c7bc6124a189e5307f2bd1f960dd06495932d10
diff --git a/app/controllers/rails_admin/main_controller.rb b/app/controllers/rails_admin/main_controller.rb index <HASH>..<HASH> 100644 --- a/app/controllers/rails_admin/main_controller.rb +++ b/app/controllers/rails_admin/main_controller.rb @@ -66,16 +66,14 @@ module RailsAdmin def get_sort_hash(model_config) abstract_model = model_config.abstract_model - params[:sort] = params[:sort_reverse] = nil unless model_config.list.fields.collect { |f| f.name.to_s }.include? params[:sort] - params[:sort] ||= model_config.list.sort_by.to_s - params[:sort_reverse] ||= 'false' - field = model_config.list.fields.detect { |f| f.name.to_s == params[:sort] } + column = - if field.nil? || field.sortable == true # use params[:sort] on the base table - "#{abstract_model.table_name}.#{params[:sort]}" - elsif field.sortable == false # use default sort, asked field is not sortable + if field.nil? || field.sortable == false # use default sort, asked field does not exist or is not sortable + field = model_config.list.possible_fields.detect { |f| f.name == model_config.list.sort_by.to_sym } "#{abstract_model.table_name}.#{model_config.list.sort_by}" + elsif field.sortable == true # use the given field + "#{abstract_model.table_name}.#{field.name}" elsif (field.sortable.is_a?(String) || field.sortable.is_a?(Symbol)) && field.sortable.to_s.include?('.') # just provide sortable, don't do anything smart field.sortable elsif field.sortable.is_a?(Hash) # just join sortable hash, don't do anything smart @@ -86,8 +84,8 @@ module RailsAdmin "#{abstract_model.table_name}.#{field.sortable}" end - reversed_sort = (field ? field.sort_reverse? : model_config.list.sort_reverse?) - {sort: column, sort_reverse: (params[:sort_reverse] == reversed_sort.to_s)} + params[:sort_reverse] ||= 'false' + {sort: column, sort_reverse: (params[:sort_reverse] == (field&.sort_reverse&.to_s || 'true'))} end def redirect_to_on_success diff --git a/lib/rails_admin/config/has_fields.rb b/lib/rails_admin/config/has_fields.rb index <HASH>..<HASH> 100644 --- a/lib/rails_admin/config/has_fields.rb +++ b/lib/rails_admin/config/has_fields.rb @@ -116,6 +116,10 @@ module RailsAdmin all_fields.collect { |f| f.with(bindings) }.select(&:visible?).sort_by { |f| [f.order, i += 1] } # stable sort, damn end + def possible_fields + _fields(true) + end + protected # Raw fields. diff --git a/lib/rails_admin/config/sections/list.rb b/lib/rails_admin/config/sections/list.rb index <HASH>..<HASH> 100644 --- a/lib/rails_admin/config/sections/list.rb +++ b/lib/rails_admin/config/sections/list.rb @@ -32,10 +32,6 @@ module RailsAdmin parent.abstract_model.primary_key end - register_instance_option :sort_reverse? do - true # By default show latest first - end - register_instance_option :scopes do [] end @@ -51,6 +47,10 @@ module RailsAdmin def fields_for_table visible_fields.partition(&:sticky?).flatten end + + register_deprecated_instance_option :sort_reverse do + ActiveSupport::Deprecation.warn('The sort_reverse configuration option is deprecated and has no effect.') + end end end end diff --git a/spec/integration/actions/index_spec.rb b/spec/integration/actions/index_spec.rb index <HASH>..<HASH> 100644 --- a/spec/integration/actions/index_spec.rb +++ b/spec/integration/actions/index_spec.rb @@ -795,20 +795,6 @@ RSpec.describe 'Index action', type: :request do before { @players = players.collect { |h| Player.create(h) } } - it 'is configurable per model' do - RailsAdmin.config Player do - list do - sort_by :created_at - sort_reverse true - field :name - end - end - visit index_path(model_name: 'player') - player_names_by_date.reverse.each_with_index do |name, i| - expect(find("tbody tr:nth-child(#{i + 1})")).to have_content(name) - end - end - it 'has reverse direction by default' do RailsAdmin.config Player do list do @@ -822,11 +808,13 @@ RSpec.describe 'Index action', type: :request do end end - it 'allows change default direction' do + it 'allows change direction by using field configuration' do RailsAdmin.config Player do list do sort_by :created_at - sort_reverse false + configure :created_at do + sort_reverse false + end field :name end end
Remove Sections::List#sort_reverse because of having very limited use case Closes #<I>
sferik_rails_admin
train
c60bb401719626d394d32ed18cab37cf0f0a2127
diff --git a/src/Agent/AgentInterface.php b/src/Agent/AgentInterface.php index <HASH>..<HASH> 100644 --- a/src/Agent/AgentInterface.php +++ b/src/Agent/AgentInterface.php @@ -180,9 +180,9 @@ interface AgentInterface * Where. * @param string $where * @param array $params - * @return string + * @return string|null */ - public function where(string $where, array $params = null): string; + public function where(string $where = null, array $params = null); /** * Limit. diff --git a/src/Agent/Mysqli.php b/src/Agent/Mysqli.php index <HASH>..<HASH> 100644 --- a/src/Agent/Mysqli.php +++ b/src/Agent/Mysqli.php @@ -517,9 +517,9 @@ final class Mysqli extends Agent * Prepare "WHERE" statement. * @param string $where * @param array $params - * @return string + * @return string|null */ - final public function where(string $where, array $params = null): string + final public function where(string $where = null, array $params = null) { if (!empty($params)) { $where = 'WHERE '. $this->prepare($where, $params);
Fix param/return types.
k-gun_oppa
train
aba230554f18d53efedf2f90f42afc19145d02a3
diff --git a/lib/avatars_for_rails/avatarable.rb b/lib/avatars_for_rails/avatarable.rb index <HASH>..<HASH> 100644 --- a/lib/avatars_for_rails/avatarable.rb +++ b/lib/avatars_for_rails/avatarable.rb @@ -27,6 +27,8 @@ module AvatarsForRails def check_avatar_aspect_ratio + return if logo.queued_for_write[:original].blank? + FileUtils.cp logo.queued_for_write[:original].path, AvatarsForRails.tmp_path @avatar_tmp_basename = File.basename(logo.queued_for_write[:original].path)
Fix callback when there is not logo
ging_avatars_for_rails
train
a16534afa45293b0467a3489f207eb15de4497b2
diff --git a/graylog2-shared/src/main/java/org/graylog2/shared/metrics/HdrHistogram.java b/graylog2-shared/src/main/java/org/graylog2/shared/metrics/HdrHistogram.java index <HASH>..<HASH> 100644 --- a/graylog2-shared/src/main/java/org/graylog2/shared/metrics/HdrHistogram.java +++ b/graylog2-shared/src/main/java/org/graylog2/shared/metrics/HdrHistogram.java @@ -95,11 +95,15 @@ public class HdrHistogram extends com.codahale.metrics.Histogram { @Override public void update(int value) { - hdrHistogram.recordValue(value); + update((long)value); } @Override public void update(long value) { - hdrHistogram.recordValue(value); + try { + hdrHistogram.recordValue(value); + } catch (ArrayIndexOutOfBoundsException e) { + log.debug("Ignoring value {} for HdrHistogram, it exceeds the highest trackable value {}", value, hdrHistogram.getHighestTrackableValue()); + } } }
guard against exception when hdr histogram is asked to track values outside its range
Graylog2_graylog2-server
train
62f8dae024ac4d5b56ff4ced47134126a8aca186
diff --git a/src/attributes.js b/src/attributes.js index <HASH>..<HASH> 100644 --- a/src/attributes.js +++ b/src/attributes.js @@ -51,7 +51,7 @@ const applyAttr = function(el, name, value) { if (value == null) { el.removeAttribute(name); } else { - let attrNS = attributeNSMap[name]; + const attrNS = attributeNSMap[name]; if (attrNS) { el.setAttributeNS(attrNS, name, value); } else {
Changing `let` to `const`
google_incremental-dom
train
0e63ebc69655eab962cf3415ac9e3980fede1255
diff --git a/billy/web/public/urls.py b/billy/web/public/urls.py index <HASH>..<HASH> 100644 --- a/billy/web/public/urls.py +++ b/billy/web/public/urls.py @@ -3,7 +3,7 @@ from django.conf.urls.defaults import patterns, url from billy.web.public.views import (VotesList, NewsList, BillsBySubject, SponsoredBillsList, BillsIntroducedUpper, BillsIntroducedLower, BillsPassedUpper, BillsPassedLower, - StateBills, FilterBills, EventsList,) + StateBills, EventsList,) from billy.web.public.feeds import (SponsoredBillsFeed, BillsPassedLowerFeed, BillsPassedUpperFeed, BillsIntroducedLowerFeed, @@ -93,7 +93,6 @@ urlpatterns = patterns('billy.web.public.views', url(r'^(?P<abbr>[a-z]{2})/bills/$', StateBills.as_view(), name='bills'), - url(r'^(?P<abbr>[a-z]{2})/bills/filter$', FilterBills.as_view(), name='filter_bills'), #------------------------------------------------------------------------ url(r'^(?P<abbr>[a-z]{2})/votes/(?P<bill_id>\w+)/(?P<vote_index>\w+)/', 'vote', name='vote'), diff --git a/billy/web/public/views.py b/billy/web/public/views.py index <HASH>..<HASH> 100644 --- a/billy/web/public/views.py +++ b/billy/web/public/views.py @@ -336,23 +336,23 @@ class RelatedBillsList(RelatedObjectsList): statenav_active = 'bills' -class StateBills(RelatedBillsList): - template_name = templatename('state_bills_list') - collection_name = 'metadata' - query_attr = 'bills' - description_template = templatename( - 'list_descriptions/bills') - - def get_context_data(self, *args, **kwargs): - context = super(RelatedObjectsList, self).get_context_data( - *args, **kwargs) - metadata = context['metadata'] - FilterBillsForm = get_filter_bills_form(metadata) - context.update(form=FilterBillsForm()) - return context +# class StateBills(RelatedBillsList): +# template_name = templatename('state_bills_list') +# collection_name = 'metadata' +# query_attr = 'bills' +# description_template = templatename( +# 'list_descriptions/bills') + +# def get_context_data(self, *args, **kwargs): +# context = super(RelatedObjectsList, self).get_context_data( +# *args, **kwargs) +# metadata = context['metadata'] +# FilterBillsForm = get_filter_bills_form(metadata) +# context.update(form=FilterBillsForm()) +# return context -class FilterBills(RelatedBillsList): +class StateBills(RelatedBillsList): template_name = templatename('state_bills_list') collection_name = 'metadata' query_attr = 'bills' @@ -365,20 +365,41 @@ class FilterBills(RelatedBillsList): *args, **kwargs) metadata = context['metadata'] FilterBillsForm = get_filter_bills_form(metadata) - form = FilterBillsForm(self.request.GET) - search_text = form.data.get('search_text') - context.update(search_text=search_text) - context.update(form=FilterBillsForm(self.request.GET)) - full_url = self.request.path + '?' - full_url += urllib.urlencode(self.request.GET) - context.update(full_url=full_url) + if self.request.GET: + form = FilterBillsForm(self.request.GET) + search_text = form.data.get('search_text') + context.update(search_text=search_text) + context.update(form=FilterBillsForm(self.request.GET)) + + full_url = self.request.path + '?' + full_url += urllib.urlencode(self.request.GET) + context.update(full_url=full_url) + else: + context.update(form=FilterBillsForm()) + return context def get_queryset(self): metadata = Metadata.get_object(self.kwargs['abbr']) FilterBillsForm = get_filter_bills_form(metadata) + + # Setup the paginator. + get = self.request.GET.get + show_per_page = getattr(self, 'show_per_page', 10) + show_per_page = int(get('show_per_page', show_per_page)) + page = int(get('page', 1)) + if 100 < show_per_page: + show_per_page = 100 + + if not self.request.GET: + spec = {} + cursor = db.bills.find(spec) + cursor.sort([('updated_at', pymongo.DESCENDING)]) + return self.paginator(cursor, page=page, + show_per_page=show_per_page) + form = FilterBillsForm(self.request.GET) params = [ 'chamber', @@ -426,16 +447,8 @@ class FilterBills(RelatedBillsList): cursor = db.bills.find(spec) cursor.sort([('updated_at', pymongo.DESCENDING)]) - # Setup the paginator. - get = self.request.GET.get - show_per_page = getattr(self, 'show_per_page', 10) - show_per_page = int(get('show_per_page', show_per_page)) - page = int(get('page', 1)) - if 100 < show_per_page: - show_per_page = 100 - return self.paginator(cursor, page=page, - show_per_page=self.show_per_page) + show_per_page=show_per_page) class SponsoredBillsList(RelatedBillsList):
make bills and bill filter functionality use the same url & view function
openstates_billy
train
6c054539eacc4e127153ed484145a14a6f5688db
diff --git a/raiden/network/transport/matrix/transport.py b/raiden/network/transport/matrix/transport.py index <HASH>..<HASH> 100644 --- a/raiden/network/transport/matrix/transport.py +++ b/raiden/network/transport/matrix/transport.py @@ -414,9 +414,10 @@ class MatrixTransport(Runnable): self._raiden_service: Optional["RaidenService"] = None if config.server == MATRIX_AUTO_SELECT_SERVER: - our_homeserver_candidates = config.available_servers + homeserver_candidates = config.available_servers elif urlparse(config.server).scheme in {"http", "https"}: - our_homeserver_candidates = [config.server] + # When an explicit server is given we don't need to do the RTT check on all others + homeserver_candidates = [config.server] else: raise TransportError( f"Invalid matrix server specified (valid values: " @@ -434,7 +435,7 @@ class MatrixTransport(Runnable): self._client: GMatrixClient = make_client( self._handle_sync_messages, self._handle_member_join, - our_homeserver_candidates, + homeserver_candidates, http_pool_maxsize=4, http_retry_timeout=40, http_retry_delay=_http_retry_delay, diff --git a/raiden/ui/app.py b/raiden/ui/app.py index <HASH>..<HASH> 100644 --- a/raiden/ui/app.py +++ b/raiden/ui/app.py @@ -16,7 +16,6 @@ from raiden.constants import ( CHAIN_TO_MIN_REVEAL_TIMEOUT, DOC_URL, GENESIS_BLOCK_NUMBER, - MATRIX_AUTO_SELECT_SERVER, RAIDEN_DB_VERSION, Environment, EthereumForks, @@ -369,10 +368,9 @@ def run_raiden_service( else: deployed_addresses = load_deployment_addresses_from_contracts(contracts=contracts) - # Load the available matrix servers when no matrix server is given - # The list is used in a PFS check - if config.transport.server == MATRIX_AUTO_SELECT_SERVER: - fetch_available_matrix_servers(config.transport, config.environment_type) + # Always fetch all available matrix servers. It's necessary to know the complete list in order + # to be able to construct user-ids on other homeservers + fetch_available_matrix_servers(config.transport, config.environment_type) raiden_bundle = raiden_bundle_from_contracts_deployment( proxy_manager=proxy_manager,
Always fetch list of available Matrix servers This is necessary since we're currently use this list to construct user-ids on other homeservers in the to-device fallback communication method.
raiden-network_raiden
train
f331713fad84bcbcf0b1f22a3fa27b3f6d7690ed
diff --git a/fastlane/lib/fastlane/helper/sh_helper.rb b/fastlane/lib/fastlane/helper/sh_helper.rb index <HASH>..<HASH> 100644 --- a/fastlane/lib/fastlane/helper/sh_helper.rb +++ b/fastlane/lib/fastlane/helper/sh_helper.rb @@ -52,7 +52,7 @@ module Fastlane message += "\n#{result}" if print_command_output error_callback.call(result) if error_callback - UI.user_error!(message) + UI.shell_error!(message) end end diff --git a/fastlane_core/lib/fastlane_core/ui/interface.rb b/fastlane_core/lib/fastlane_core/ui/interface.rb index <HASH>..<HASH> 100644 --- a/fastlane_core/lib/fastlane_core/ui/interface.rb +++ b/fastlane_core/lib/fastlane_core/ui/interface.rb @@ -182,6 +182,25 @@ module FastlaneCore end end + class FastlaneShellError < FastlaneException + def prefix + '[SHELL_ERROR]' + end + + def trimmed_backtrace + backtrace = trim_backtrace(method_name: 'shell_error!') + + # we also want to trim off the shell invocation itself, which means + # removing any lines from the backtrace that contain functions + # in `sh_helper.rb` + backtrace.drop_while { |frame| frame.include?('sh_helper.rb') } + end + + def could_contain_pii? + caused_by_calling_ui_method?(method_name: 'shell_error!') + end + end + # raised from build_failure! class FastlaneBuildFailure < FastlaneError end @@ -210,6 +229,18 @@ module FastlaneCore raise FastlaneError.new(options), error_message.to_s end + # Use this method to exit the program because of a shell command + # failure -- the command returned a non-zero response. This does + # not specify the nature of the error. The error might be from a + # programming error, a user error, or an expected error because + # the user of the Fastfile doesn't have their environment set up + # properly. Because of this, when these errors occur, it means + # that the caller of the shell command did not adequate error + # handling and the caller error handling should be improved. + def shell_error!(error_message, options = {}) + raise FastlaneShellError.new(options), error_message.to_s + end + # Use this method to exit the program because of a build failure # that's caused by the source code of the user. Example for this # is that gym will fail when the code doesn't compile or because diff --git a/fastlane_core/spec/fastlane_exception_spec.rb b/fastlane_core/spec/fastlane_exception_spec.rb index <HASH>..<HASH> 100644 --- a/fastlane_core/spec/fastlane_exception_spec.rb +++ b/fastlane_core/spec/fastlane_exception_spec.rb @@ -64,4 +64,25 @@ describe FastlaneCore::Interface::FastlaneException do end end end + + context 'shell error stack trimming' do + # testing the shell error stack trimming behavior is complicated, because + # the code explicitly only removes frames in sh_helper.rb, but we cannot + # actually have those frames in a backtrace in a unit test + # so, we will stub the backtrace on the object under test to return a + # hard code backtrace, and be sure that is trimmed properly + it 'trims backtrace containing sh_helper.rb' do + mock_backtrace = ["path/to/sh_helper.rb:55", "path/to/sh_helper.rb:10", "path/to/another/file.rb:1337"] + exception = FastlaneCore::Interface::FastlaneShellError.new "SHELL ERROR!!" + expect(exception).to receive(:backtrace).at_least(:once).and_return(mock_backtrace) + expect(exception.trimmed_backtrace).to eq(mock_backtrace.drop(2)) + end + + it 'does not trim backtrace not containing sh_helper.rb' do + mock_backtrace = ["path/to/file.rb:1337", "path/to/file.rb:2001"] + exception = FastlaneCore::Interface::FastlaneShellError.new "SHELL ERROR!!" + expect(exception).to receive(:backtrace).at_least(:once).and_return(mock_backtrace) + expect(exception.trimmed_backtrace).to eq(mock_backtrace) + end + end end
Add shell_error! to help clean up places where we do poor error handling (#<I>)
fastlane_fastlane
train
70a081f5b4e95577dceb33cc4c81d12f056dcf7f
diff --git a/lib/cucumber/cli/configuration.rb b/lib/cucumber/cli/configuration.rb index <HASH>..<HASH> 100644 --- a/lib/cucumber/cli/configuration.rb +++ b/lib/cucumber/cli/configuration.rb @@ -136,8 +136,9 @@ module Cucumber def arrange_formats @options[:formats] << ['pretty', @out_stream] if @options[:formats].empty? @options[:formats] = @options[:formats].sort_by{|f| f[1] == @out_stream ? -1 : 1} - if @options[:formats].length > 1 && @options[:formats][1][1] == @out_stream - raise "All but one formatter must use --out, only one can print to STDOUT" + streams = @options[:formats].map { |(_, stream)| stream } + if streams != streams.uniq + raise "All but one formatter must use --out, only one can print to each stream (or STDOUT)" end end
Fix an issue where it thought I was piping multiple formats to STDOUT. Changed it to just check for actual duplication of output streams.
cucumber_cucumber-ruby
train
7293e18deaac9634e248725072ecadfc9b61bf5c
diff --git a/lib/objects/node/base.rb b/lib/objects/node/base.rb index <HASH>..<HASH> 100644 --- a/lib/objects/node/base.rb +++ b/lib/objects/node/base.rb @@ -116,7 +116,9 @@ module Bcome::Node @identifier = "NO-ID_#{Time.now.to_i}" unless @identifier #raise ::Bcome::Exception::MissingIdentifierOnView.new(@views.inspect) unless @identifier - @identifier.gsub!(/\s/, "_") if @identifier =~ /\s/ + @identifier.gsub!(/\s/, "_") # Remove whitespace + @identifier.gsub!("-", "_") # change hyphens to undescores, hyphens don't play well in var names in irb + #raise ::Bcome::Exception::InvalidIdentifier.new("'#{@identifier}' contains whitespace") if @identifier =~ /\s/ end
Hyphens now underscores in instance names
webzakimbo_bcome-kontrol
train
7d7a99f68894281029a3933ddd9770f2fbbc1bb4
diff --git a/modules/backend/lang/fr/lang.php b/modules/backend/lang/fr/lang.php index <HASH>..<HASH> 100644 --- a/modules/backend/lang/fr/lang.php +++ b/modules/backend/lang/fr/lang.php @@ -89,7 +89,7 @@ return [ 'updates_link' => 'Mettre à jour', 'warnings_pending' => 'Certaines anomalies méritent votre attention', 'warnings_nil' => 'Aucun avertissement à afficher', - 'warnings_link' => 'Vue', + 'warnings_link' => 'Voir', 'core_build' => 'Version du système', 'event_log' => 'Journal des évènements', 'request_log' => 'Journal des requêtes',
Update lang.php (#<I>) Corrected dashboard warnings_link from 'Vue' to 'Voir'
octobercms_october
train
e8099ae6302140498ff39453f6b2808207779f9f
diff --git a/api/api.go b/api/api.go index <HASH>..<HASH> 100644 --- a/api/api.go +++ b/api/api.go @@ -3,7 +3,6 @@ package api import ( "encoding/json" "io/ioutil" - "log" "net/http" "github.com/gorilla/mux" @@ -20,7 +19,7 @@ func auth(handler http.Handler) http.Handler { }) } -func New(serviceBroker ServiceBroker, httpLogger *log.Logger, brokerLogger lager.Logger) http.Handler { +func New(serviceBroker ServiceBroker, brokerLogger lager.Logger) http.Handler { router := mux.NewRouter() // Catalog diff --git a/api/api_suite_test.go b/api/api_suite_test.go index <HASH>..<HASH> 100644 --- a/api/api_suite_test.go +++ b/api/api_suite_test.go @@ -3,8 +3,6 @@ package api_test import ( "fmt" "io/ioutil" - "log" - "os" "path" "testing" @@ -29,14 +27,6 @@ func fixture(name string) string { return string(contents) } -func nullLogger() *log.Logger { - devNull, err := os.Open(os.DevNull) - if err != nil { - panic("Could not make a null logger") - } - return log.New(devNull, "", 0) -} - func uniqueID() string { return uuid.NewRandom().String() } diff --git a/api/api_test.go b/api/api_test.go index <HASH>..<HASH> 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -52,7 +52,7 @@ var _ = Describe("Service Broker API", func() { InstanceLimit: 3, } brokerLogger = lagertest.NewTestLogger("broker-api") - brokerAPI = api.New(fakeServiceBroker, nullLogger(), brokerLogger) + brokerAPI = api.New(fakeServiceBroker, brokerLogger) }) Describe("authentication", func() {
remove old httplogger from martini
pivotal-cf_brokerapi
train
5d6487016da8afa58947b2c51ddf91d54308cdda
diff --git a/ui/dev/src/pages/form/form.vue b/ui/dev/src/pages/form/form.vue index <HASH>..<HASH> 100644 --- a/ui/dev/src/pages/form/form.vue +++ b/ui/dev/src/pages/form/form.vue @@ -9,11 +9,10 @@ <q-toggle v-model="autofocus" label="Autofocus" /> <q-toggle v-model="dark" label="Dark" :false-value="null" /> <q-toggle v-model="greedy" label="Greedy" /> + <q-toggle v-model="loading" label="Loading" /> <q-toggle v-model="customInput" label="Custom Input" /> <q-option-group class="q-mb-lg" inline v-model="autofocusEl" dense="dense" :options="autofocusEls" /> - <q-btn loading label="loading" @click.native="onClick" /> - <q-btn label="loading" @click.native="onClick" /> <q-form v-if="show" :autofocus="autofocus" @@ -82,8 +81,8 @@ <q-toggle :dark="dark" v-model="accept" label="I accept the license and terms" :autofocus="autofocusEl === 3" /> <div> - <q-btn label="Submit" type="submit" color="primary" loading /> - <q-btn label="Reset" type="reset" color="primary" flat class="q-ml-sm" loading /> + <q-btn label="Submit" type="submit" color="primary" :loading="loading" /> + <q-btn label="Reset" type="reset" color="primary" flat class="q-ml-sm" :loading="loading" /> </div> </div> </q-form> @@ -142,6 +141,7 @@ export default { }, data () { return { + loading: false, native: null, name: null, age: null, diff --git a/ui/src/components/btn/QBtn.js b/ui/src/components/btn/QBtn.js index <HASH>..<HASH> 100644 --- a/ui/src/components/btn/QBtn.js +++ b/ui/src/components/btn/QBtn.js @@ -201,6 +201,11 @@ export default Vue.extend({ } this.$el !== void 0 && this.$el.classList.remove('q-btn--active') + }, + + __onLoadingEvt (evt) { + stopAndPrevent(evt) + evt.qSkipRipple = true } }, @@ -266,17 +271,25 @@ export default Vue.extend({ }) ] - this.loading === true && this.percentage !== void 0 && child.push( - h('div', { - staticClass: 'q-btn__progress absolute-full overflow-hidden' - }, [ + if (this.loading === true) { + // stop propagation and ripple + data.on = { + click: this.__onLoadingEvt, + keyup: this.__onLoadingEvt + } + + this.percentage !== void 0 && child.push( h('div', { - staticClass: 'q-btn__progress-indicator fit', - class: this.darkPercentage === true ? 'q-btn__progress--dark' : '', - style: this.percentageStyle - }) - ]) - ) + staticClass: 'q-btn__progress absolute-full overflow-hidden' + }, [ + h('div', { + staticClass: 'q-btn__progress-indicator fit', + class: this.darkPercentage === true ? 'q-btn__progress--dark' : '', + style: this.percentageStyle + }) + ]) + ) + } child.push( h('div', { diff --git a/ui/src/directives/Ripple.js b/ui/src/directives/Ripple.js index <HASH>..<HASH> 100644 --- a/ui/src/directives/Ripple.js +++ b/ui/src/directives/Ripple.js @@ -88,13 +88,21 @@ export default { click (evt) { // on ENTER in form IE emits a PointerEvent with negative client cordinates - if (ctx.enabled === true && (client.is.ie !== true || evt.clientX >= 0)) { + if ( + ctx.enabled === true && + evt.qSkipRipple !== true && + (client.is.ie !== true || evt.clientX >= 0) + ) { showRipple(evt, el, ctx, evt.qKeyEvent === true) } }, keyup (evt) { - if (ctx.enabled === true && isKeyCode(evt, ctx.modifiers.keyCodes) === true) { + if ( + ctx.enabled === true && + evt.qSkipRipple !== true && + isKeyCode(evt, ctx.modifiers.keyCodes) === true + ) { showRipple(evt, el, ctx, true) } }
fix(QBtn): QBtn in loading state in a form should not submit form; loading state improvements #<I>
quasarframework_quasar
train
773e9a9f7983fa3dd982a153bc54eaea542305ca
diff --git a/moto/s3/responses.py b/moto/s3/responses.py index <HASH>..<HASH> 100644 --- a/moto/s3/responses.py +++ b/moto/s3/responses.py @@ -964,7 +964,7 @@ class ResponseObject(_TemplateEnvironmentMixin, ActionAuthenticatorMixin): def _bucket_response_delete_keys(self, request, body, bucket_name): template = self.response_template(S3_DELETE_KEYS_RESPONSE) - body_dict = xmltodict.parse(body) + body_dict = xmltodict.parse(body, strip_whitespace=False) objects = body_dict["Delete"].get("Object", []) if not isinstance(objects, list): diff --git a/tests/test_s3/test_s3.py b/tests/test_s3/test_s3.py index <HASH>..<HASH> 100644 --- a/tests/test_s3/test_s3.py +++ b/tests/test_s3/test_s3.py @@ -6587,3 +6587,22 @@ def test_create_bucket_duplicate(): "Your previous request to create the named bucket succeeded and you already own it." ) err["BucketName"].should.equal(bucket_name) + + +@mock_s3 +def test_delete_objects_with_empty_keyname(): + client = boto3.client("s3", region_name=DEFAULT_REGION_NAME) + resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME) + bucket_name = "testbucket-4077" + bucket = resource.create_bucket(Bucket=bucket_name) + key_name = " " + bucket.put_object(Key=key_name, Body=b"") + client.list_objects(Bucket=bucket_name).should.have.key("Contents").length_of(1) + + bucket.delete_objects(Delete={"Objects": [{"Key": key_name}]}) + client.list_objects(Bucket=bucket_name).shouldnt.have.key("Contents") + + bucket.put_object(Key=key_name, Body=b"") + + client.delete_object(Bucket=bucket_name, Key=key_name) + client.list_objects(Bucket=bucket_name).shouldnt.have.key("Contents")
S3 - Allow for keyname that is just an empty space (#<I>)
spulec_moto
train
cbd84388dd7dba4311506c6f5fcd6017f9b401e4
diff --git a/src/lib/Menu/ContentRightSidebarBuilder.php b/src/lib/Menu/ContentRightSidebarBuilder.php index <HASH>..<HASH> 100644 --- a/src/lib/Menu/ContentRightSidebarBuilder.php +++ b/src/lib/Menu/ContentRightSidebarBuilder.php @@ -107,7 +107,7 @@ class ContentRightSidebarBuilder extends AbstractBuilder implements TranslationC ); $canTrashLocation = $this->permissionResolver->canUser( 'content', - 'manage_locations', + 'remove', $location->getContentInfo(), [$location] );
EZP-<I>: Changed policy which allows to trash a Location
ezsystems_ezplatform-admin-ui
train
14758f761f221b4ec4c1f3607fc0aec8d64f0d4e
diff --git a/packages/eslint-settings/.eslintrc.js b/packages/eslint-settings/.eslintrc.js index <HASH>..<HASH> 100644 --- a/packages/eslint-settings/.eslintrc.js +++ b/packages/eslint-settings/.eslintrc.js @@ -22,6 +22,13 @@ module.exports = { ignoreRegExpLiterals: true, }, ], + "object-shorthand": [ + 2, + "always", + { + "avoidExplicitReturnArrows": true + } + ], "function-paren-newline": 0, "class-methods-use-this": 0, "comma-dangle": 0,
[infra] Add linting rule to disallow arrow functions in object expressions (#<I>)
ringcentral_ringcentral-js-widgets
train
23617cd57254c96d493baf0c57fa9b5412308799
diff --git a/apptentive-android-sdk/src/com/apptentive/android/sdk/util/Constants.java b/apptentive-android-sdk/src/com/apptentive/android/sdk/util/Constants.java index <HASH>..<HASH> 100644 --- a/apptentive-android-sdk/src/com/apptentive/android/sdk/util/Constants.java +++ b/apptentive-android-sdk/src/com/apptentive/android/sdk/util/Constants.java @@ -61,11 +61,6 @@ public class Constants { public static final int CONFIG_DEFAULT_INTERACTION_CACHE_EXPIRATION_DURATION_SECONDS = 28800; // 8 hours public static final int CONFIG_DEFAULT_APP_CONFIG_EXPIRATION_MILLIS = 0; public static final int CONFIG_DEFAULT_APP_CONFIG_EXPIRATION_DURATION_SECONDS = 86400; // 24 hours - public static final int CONFIG_DEFAULT_DAYS_BEFORE_PROMPT = 30; - public static final int CONFIG_DEFAULT_USES_BEFORE_PROMPT = 5; - public static final int CONFIG_DEFAULT_SIGNIFICANT_EVENTS_BEFORE_PROMPT = 10; - public static final int CONFIG_DEFAULT_DAYS_BEFORE_REPROMPTING = 5; - public static final String CONFIG_DEFAULT_RATING_PROMPT_LOGIC = "{\"and\": [\"uses\",\"days\",\"events\"]}"; public static final int CONFIG_DEFAULT_MESSAGE_CENTER_FG_POLL_SECONDS = 15; public static final int CONFIG_DEFAULT_MESSAGE_CENTER_BG_POLL_SECONDS = 60; public static final boolean CONFIG_DEFAULT_MESSAGE_CENTER_ENABLED = true; @@ -78,7 +73,7 @@ public class Constants { public static final String MANIFEST_KEY_SDK_DISTRIBUTION_VERSION = "apptentive_sdk_distribution_version"; public static final String MANIFEST_KEY_MESSAGE_CENTER_ENABLED = "apptentive_message_center_enabled"; public static final String MANIFEST_KEY_EMAIL_REQUIRED = "apptentive_email_required"; - public static final String MANIFEST_KEY_HIDE_BRANDING = "apptentive_hide_branding"; + public static final String MANIFEST_KEY_INITIALLY_HIDE_BRANDING = "apptentive_initially_hide_branding"; // View layout shortcuts public static final ViewGroup.LayoutParams ROW_LAYOUT = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
Remove constants we no longer need.
apptentive_apptentive-android
train
ab7e5c92aed1fc22a16751b3c77ed6ec3c2cbd55
diff --git a/master/docs/bbdocs/highlighterrors.py b/master/docs/bbdocs/highlighterrors.py index <HASH>..<HASH> 100644 --- a/master/docs/bbdocs/highlighterrors.py +++ b/master/docs/bbdocs/highlighterrors.py @@ -93,3 +93,4 @@ def setup(app): of Sphinx is %s. Check disabled. """) % (sphinx.__version__, required_sphinx_version) sys.stderr.write(msg) + return {'parallel_read_safe': True, 'parallel_write_safe': True}
docs: Enable multiprocess support for bbdocs.highlighterrors extension
buildbot_buildbot
train
de36116e3bec9610932fd3034fc4bc7fc8271f74
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -57,4 +57,4 @@ for tf_pkg_name in ['tensorflow', 'tensorflow-gpu']: pass assert tf_pkg is not None, 'TensorFlow needed, of version above 1.4' from distutils.version import StrictVersion -assert StrictVersion(re.sub(r'-rc\d+$', '', tf_pkg.version)) >= StrictVersion('1.4.0') +assert StrictVersion(re.sub(r'-?rc\d+$', '', tf_pkg.version)) >= StrictVersion('1.4.0')
update tensorflow version check regex to parse version like <I>rc4 (previously only <I>-rc4)
openai_baselines
train
4cefaeaf4a620d89f5342223ce634a7fad383fb2
diff --git a/addon/components/new-version-notifier.js b/addon/components/new-version-notifier.js index <HASH>..<HASH> 100644 --- a/addon/components/new-version-notifier.js +++ b/addon/components/new-version-notifier.js @@ -1,6 +1,7 @@ import Component from '@glimmer/component'; import { tracked } from '@glimmer/tracking'; import { inject as service } from '@ember/service'; +import { action } from '@ember/object'; export default class NewVersionNotifier extends Component { /** @type {import("ember-cli-new-version/services/new-version").default} */ @@ -25,10 +26,14 @@ export default class NewVersionNotifier extends Component { return undefined; } + @action close() { this.newVersion.ignoreVersion(this.newVersion.latestVersion); + + return false; } + @action reload() { if (typeof window !== 'undefined' && window.location) { window.location.reload(true); diff --git a/addon/services/new-version.js b/addon/services/new-version.js index <HASH>..<HASH> 100644 --- a/addon/services/new-version.js +++ b/addon/services/new-version.js @@ -1,5 +1,4 @@ import { getOwner } from '@ember/application'; -import { A } from '@ember/array'; import { later } from '@ember/runloop'; import Service from '@ember/service'; import { waitFor } from '@ember/test-waiters'; @@ -50,7 +49,7 @@ export default class NewVersionService extends Service { */ @tracked latestVersion = undefined; - ignoredVersions = A(); + ignoredVersions = []; /** * Templates can use this attribute to show or hide a proposition to reload the page. @@ -128,7 +127,8 @@ export default class NewVersionService extends Service { if (this.isNewVersionAvailable) { this.onNewVersion( this.latestVersion, - this.ignoredVersions.lastObject || this.currentVersion + this.ignoredVersions[this.ignoredVersions.length - 1] || + this.currentVersion ); } }); @@ -163,7 +163,7 @@ export default class NewVersionService extends Service { * @param {string} version */ ignoreVersion(version) { - this.ignoredVersions.push(version); + this.ignoredVersions = [...this.ignoredVersions, version]; } // eslint-disable-next-line no-unused-vars
fix: action decorators not used in places (#<I>) * fix: #<I> adds action decorator to action methods * fix: #<I>, recalculation of the message not triggered (close not closing) * fix: cs
sethwebster_ember-cli-new-version
train
6666ef4d06be6386f6a7c423f1f8d6cd0cb11f14
diff --git a/plugin.php b/plugin.php index <HASH>..<HASH> 100644 --- a/plugin.php +++ b/plugin.php @@ -4,7 +4,7 @@ * Description: JSON-based REST API for WordPress, developed as part of GSoC 2013. * Author: WP REST API Team * Author URI: http://wp-api.org - * Version: 2.0-beta4 + * Version: 2.0-beta5 * Plugin URI: https://github.com/WP-API/WP-API * License: GPL2+ */
Bump `develop` to beta5
WP-API_WP-API
train
409c9c2589af18be15bfba7ed5c6e92ec471fb30
diff --git a/Entity/BaseProduct.php b/Entity/BaseProduct.php index <HASH>..<HASH> 100644 --- a/Entity/BaseProduct.php +++ b/Entity/BaseProduct.php @@ -157,4 +157,19 @@ class BaseProduct implements EntityInterface, ProductInterface } $this->productType = $type; } + + public function isPhysical() + { + return $this->productType === self::TYPE_PHYSICAL; + } + + public function isHybrid() + { + return $this->productType === self::TYPE_HYBRID; + } + + public function isDigital() + { + return $this->productType === self::TYPE_DIGITAL; + } }
Add methods to check if the product type
modpreneur_trinity-core-entities
train
9d98905e2e547a161d4d59ae1d9fe7444b7a1015
diff --git a/src/Datasource/EntityInterface.php b/src/Datasource/EntityInterface.php index <HASH>..<HASH> 100644 --- a/src/Datasource/EntityInterface.php +++ b/src/Datasource/EntityInterface.php @@ -69,7 +69,7 @@ interface EntityInterface extends ArrayAccess, JsonSerializable * will be returned. Otherwise the hidden properties will be set. * * @param null|array $properties Either an array of properties to hide or null to get properties - * @return array|\Cake\DataSource\EntityInterface + * @return array|\Cake\Datasource\EntityInterface */ public function hiddenProperties($properties = null); @@ -80,7 +80,7 @@ interface EntityInterface extends ArrayAccess, JsonSerializable * will be returned. Otherwise the virtual properties will be set. * * @param null|array $properties Either an array of properties to treat as virtual or null to get properties - * @return array|\Cake\DataSource\EntityInterface + * @return array|\Cake\Datasource\EntityInterface */ public function virtualProperties($properties = null); diff --git a/src/ORM/Table.php b/src/ORM/Table.php index <HASH>..<HASH> 100644 --- a/src/ORM/Table.php +++ b/src/ORM/Table.php @@ -1656,7 +1656,7 @@ class Table implements RepositoryInterface, EventListenerInterface, EventDispatc * Will delete the entity provided. Will remove rows from any * dependent associations, and clear out join tables for BelongsToMany associations. * - * @param \Cake\DataSource\EntityInterface $entity The entity to delete. + * @param \Cake\Datasource\EntityInterface $entity The entity to delete. * @param \ArrayObject $options The options for the delete. * @throws \InvalidArgumentException if there are no primary key values of the * passed entity diff --git a/src/View/Form/EntityContext.php b/src/View/Form/EntityContext.php index <HASH>..<HASH> 100644 --- a/src/View/Form/EntityContext.php +++ b/src/View/Form/EntityContext.php @@ -256,7 +256,7 @@ class EntityContext implements ContextInterface * * @param array|null $path Each one of the parts in a path for a field name * or null to get the entity passed in contructor context. - * @return \Cake\DataSource\EntityInterface|\Traversable|array|bool + * @return \Cake\Datasource\EntityInterface|\Traversable|array|bool * @throws \RuntimeException When properties cannot be read. */ public function entity($path = null)
correct the case for `Cake\Datasource\EntityInterface` as it can be misunderstood by some IDE and static analysis tools.
cakephp_cakephp
train
bd606c87b73e85df2cb4e759c1c3a6cf005799fb
diff --git a/app/Http/Middleware/SecurityHeaders.php b/app/Http/Middleware/SecurityHeaders.php index <HASH>..<HASH> 100644 --- a/app/Http/Middleware/SecurityHeaders.php +++ b/app/Http/Middleware/SecurityHeaders.php @@ -30,6 +30,7 @@ use Psr\Http\Server\RequestHandlerInterface; class SecurityHeaders implements MiddlewareInterface { private const SECURITY_HEADERS = [ + 'Permissions-Policy' => 'interest-cohort=()', 'Referrer-Policy' => 'same-origin', 'X-Content-Type-Options' => 'nosniff', 'X-Frame-Options' => 'SAMEORIGIN',
Opt out of google's FLoC tracking system
fisharebest_webtrees
train
ae4573b27c839c74a5e00d570a846c773e07a8af
diff --git a/lib/unitwise/atom.rb b/lib/unitwise/atom.rb index <HASH>..<HASH> 100644 --- a/lib/unitwise/atom.rb +++ b/lib/unitwise/atom.rb @@ -61,7 +61,15 @@ module Unitwise end def root_terms - measurement.root_terms unless terminal? + base? ? [Term.new(atom_code: primary_code)] : measurement.root_terms + end + + def to_s + "#{codes.join('|')}:#{names.join('|')}" + end + + def inspect + "<#{self.class} #{to_s}>" end end diff --git a/lib/unitwise/composable.rb b/lib/unitwise/composable.rb index <HASH>..<HASH> 100644 --- a/lib/unitwise/composable.rb +++ b/lib/unitwise/composable.rb @@ -1,5 +1,10 @@ module Unitwise module Composable + + def self.included(base) + base.send :include, Comparable + end + def composition root_terms.reduce(SignedMultiset.new) do |s, t| s.increment(t.atom.key, t.exponent); s @@ -10,5 +15,11 @@ module Unitwise self.composition == other.composition end + def <=>(other) + if other.respond_to?(:composition) && similar_to?(other) + scale <=> other.scale + end + end + end end \ No newline at end of file diff --git a/lib/unitwise/expression.rb b/lib/unitwise/expression.rb index <HASH>..<HASH> 100644 --- a/lib/unitwise/expression.rb +++ b/lib/unitwise/expression.rb @@ -155,5 +155,9 @@ module Unitwise end end + def to_s + string + end + end end \ No newline at end of file diff --git a/lib/unitwise/measurement.rb b/lib/unitwise/measurement.rb index <HASH>..<HASH> 100644 --- a/lib/unitwise/measurement.rb +++ b/lib/unitwise/measurement.rb @@ -44,5 +44,13 @@ module Unitwise end end + def to_s + "#{value} #{unit.to_s}" + end + + def inspect + "<#{self.class} #{to_s}>" + end + end end \ No newline at end of file diff --git a/lib/unitwise/term.rb b/lib/unitwise/term.rb index <HASH>..<HASH> 100644 --- a/lib/unitwise/term.rb +++ b/lib/unitwise/term.rb @@ -54,5 +54,13 @@ module Unitwise end end + def to_s + [factor, prefix_code, atom_code, exponent].join(' ') + end + + def inspect + "<#{self.class} #{to_s}>" + end + end end \ No newline at end of file diff --git a/lib/unitwise/unit.rb b/lib/unitwise/unit.rb index <HASH>..<HASH> 100644 --- a/lib/unitwise/unit.rb +++ b/lib/unitwise/unit.rb @@ -36,5 +36,13 @@ module Unitwise end end + def to_s + @expression.to_s + end + + def inspect + "<#{self.class} #{to_s}>" + end + end end \ No newline at end of file
Implement comparable, add to_s/inspect methods
joshwlewis_unitwise
train
f2de4f20193f014e8bcab3031edfe15b13ff8998
diff --git a/command/agent/agent.go b/command/agent/agent.go index <HASH>..<HASH> 100644 --- a/command/agent/agent.go +++ b/command/agent/agent.go @@ -158,6 +158,9 @@ func (a *Agent) serverConfig() (*nomad.Config, error) { conf.SerfConfig.MemberlistConfig.BindPort = port } a.serverHTTPAddr = fmt.Sprintf("%v:%v", a.config.Addresses.HTTP, a.config.Ports.HTTP) + if a.config.AdvertiseAddrs.HTTP != "" { + a.serverHTTPAddr = a.config.AdvertiseAddrs.HTTP + } if gcThreshold := a.config.Server.NodeGCThreshold; gcThreshold != "" { dur, err := time.ParseDuration(gcThreshold)
Using advertise addr for the http address
hashicorp_nomad
train
5936415b09aeeafc2c1a1d04c923289f1af376b8
diff --git a/src/Psalm/Internal/Fork/Pool.php b/src/Psalm/Internal/Fork/Pool.php index <HASH>..<HASH> 100644 --- a/src/Psalm/Internal/Fork/Pool.php +++ b/src/Psalm/Internal/Fork/Pool.php @@ -51,10 +51,12 @@ class Pool 'The pool size must be >= 2 to use the fork pool.' ); - \assert( - extension_loaded('pcntl'), - 'The pcntl extension must be loaded in order for Psalm to be able to fork.' - ); + if (!extension_loaded('pcntl')) { + die( + 'The pcntl extension must be loaded in order for Psalm to be able to use multiple processes.' + . PHP_EOL + ); + } // We'll keep track of if this is the parent process // so that we can tell who will be doing the waiting
Exit if trying to use --threads without pcntl extension
vimeo_psalm
train
dc3b1fa71512ee54567472017ec4aede0b2cde33
diff --git a/assets/javascripts/kitten/components/cards/project-card.test.js b/assets/javascripts/kitten/components/cards/project-card.test.js index <HASH>..<HASH> 100644 --- a/assets/javascripts/kitten/components/cards/project-card.test.js +++ b/assets/javascripts/kitten/components/cards/project-card.test.js @@ -103,7 +103,7 @@ describe('<ProjectCard />', () => { ] const projectCard = mount( - <ProjectCard tags={ tags } /> + <ProjectCard tagLists={ tags } /> ) const projectCardWithTwoLists = mount( diff --git a/assets/javascripts/kitten/components/images/image-with-caption.test.js b/assets/javascripts/kitten/components/images/image-with-caption.test.js index <HASH>..<HASH> 100644 --- a/assets/javascripts/kitten/components/images/image-with-caption.test.js +++ b/assets/javascripts/kitten/components/images/image-with-caption.test.js @@ -42,9 +42,9 @@ describe ('<ImageWithCaption />', () => { const component = mount( <ImageWithCaption imageSrc="test" - imageAlt - imageWidth - imageHeight + imageAlt="FooBar" + imageWidth="42" + imageHeight="42" /> ) const image = component.find('.k-ImageWithCaption__img') @@ -52,9 +52,9 @@ describe ('<ImageWithCaption />', () => { it('renders an image with good attributes', () => { expect(image).toHaveLength(1) expect(image.props().src).toBe('test') - expect(image.props().alt).toBeTruthy() - expect(image.props().width).toBeTruthy() - expect(image.props().height).toBeTruthy() + expect(image.props().alt).toBe('FooBar') + expect(image.props().width).toBe('42') + expect(image.props().height).toBe('42') }) }) diff --git a/assets/javascripts/kitten/components/navigation/horizontal-nav.test.js b/assets/javascripts/kitten/components/navigation/horizontal-nav.test.js index <HASH>..<HASH> 100644 --- a/assets/javascripts/kitten/components/navigation/horizontal-nav.test.js +++ b/assets/javascripts/kitten/components/navigation/horizontal-nav.test.js @@ -5,10 +5,10 @@ describe('<HorizontalNav />', () => { const component = shallow( <HorizontalNav items={ [ - { text: 'Nav link 1', href: '#foobar' }, - { text: 'Nav link 2', href: '#foobar' }, - { text: 'Nav link 3', href: '#foobar' }, - { text: 'Nav link 4', href: '#foobar' }, + { key: 'item-1', text: 'Nav link 1', href: '#foobar' }, + { key: 'item-2', text: 'Nav link 2', href: '#foobar' }, + { key: 'item-3', text: 'Nav link 3', href: '#foobar' }, + { key: 'item-4', text: 'Nav link 4', href: '#foobar' }, ] } /> ) @@ -44,7 +44,7 @@ describe('<HorizontalNav />', () => { const component = mount( <HorizontalNav items={ [ - { text: 'Nav link 1' }, + { key: 'item-1', text: 'Nav link 1' }, ] } height="auto" /> @@ -64,10 +64,10 @@ describe('<HorizontalNav />', () => { className="custom-class" elementClassName="element-custom-class" items={ [ - { text: 'Nav link 1', className: 'item-custom-class' }, - { text: 'Nav link 2', className: 'item-custom-class' }, - { text: 'Nav link 3', className: 'item-custom-class' }, - { text: 'Nav link 4', className: 'item-custom-class' }, + { key: 'item-1', text: 'Nav link 1', className: 'item-custom-class' }, + { key: 'item-2', text: 'Nav link 2', className: 'item-custom-class' }, + { key: 'item-3', text: 'Nav link 3', className: 'item-custom-class' }, + { key: 'item-4', text: 'Nav link 4', className: 'item-custom-class' }, ] } /> ) @@ -89,7 +89,7 @@ describe('<HorizontalNav />', () => { const component = shallow( <HorizontalNav items={ [ - { text: 'Nav\n1', className: 'item-1' }, + { key: 'item-1', text: 'Nav\n1', className: 'item-1' }, ] } /> ) diff --git a/bin/test b/bin/test index <HASH>..<HASH> 100755 --- a/bin/test +++ b/bin/test @@ -1,6 +1,6 @@ #!/usr/bin/env bash set -e -FILES=${1:-assets/javascripts/kitten/**/*.test.js} +FILES=${1:-\\.test\\.js$} npm test -- "$FILES"
Fix some test warnings (#<I>)
KissKissBankBank_kitten
train
bdbda32da1d4849e85c112067a0706745cacc594
diff --git a/lib/pling.rb b/lib/pling.rb index <HASH>..<HASH> 100644 --- a/lib/pling.rb +++ b/lib/pling.rb @@ -2,11 +2,16 @@ require "pling/version" module Pling - autoload :Device, 'pling/device' - autoload :Message, 'pling/message' - autoload :Gateway, 'pling/gateway' + autoload :Device, 'pling/device' + autoload :Message, 'pling/message' + autoload :Gateway, 'pling/gateway' + autoload :Middleware, 'pling/middleware' + autoload :Adapter, 'pling/adapter' + autoload :Configurable, 'pling/configurable' @gateways = [] + @middlewares = [] + @adapter = Pling::Adapter::Base.new class Error < StandardError; end class AuthenticationFailed < Error; end @@ -20,6 +25,17 @@ module Pling # @return [Array] list of available gateways attr_accessor :gateways + ## + # Stores the list of avaiable middleware instances + # + # @return [Array] list of available middleware + attr_accessor :middlewares + + ## + # Stores the adapter + # + # @return [Pling::Adapter] + attr_accessor :adapter ## # Allows configuration of Pling by passing a config object to the given block @@ -31,6 +47,17 @@ module Pling yield self end + ## + # Delivers the given message to the given device using the given stack. + # + # @param message [#to_pling_message] + # @param device [#to_pling_device] + # @param stack [Array] The stack to use (Default: middlewares + [adapter]) + def deliver(message, device, stack = middlewares + [adapter]) + stack.shift.deliver(message, device) do |m, d| + deliver(m, d, stack) + end + end ## # [INTERNAL METHOD] Converts the given object to the given pling type diff --git a/spec/pling_spec.rb b/spec/pling_spec.rb index <HASH>..<HASH> 100644 --- a/spec/pling_spec.rb +++ b/spec/pling_spec.rb @@ -31,6 +31,53 @@ describe Pling do end end + it { should respond_to(:middlewares) } + it { should respond_to(:middlewares=) } + + describe '.middlewares' do + it 'should default to an empty array' do + subject.middlewares.should eq([]) + end + end + + it { should respond_to(:adapter) } + it { should respond_to(:adapter=) } + + describe '.adapter' do + it 'should default to Pling::Adapter::Base' do + subject.adapter.class.should eq(Pling::Adapter::Base) + end + end + + describe '.deliver' do + + let(:message) { Pling::Message.new } + let(:device) { Pling::Device.new } + let(:adapter) { mock(:deliver => true) } + + before do + Pling.stub(:adapter).and_return(adapter) + end + + it 'should call the adapter' do + adapter.should_receive(:deliver).with(message, device) + Pling.deliver(message, device) + end + + it 'should call each middleware in the given order' do + first_middleware = double(Pling::Middleware::Base) + first_middleware.should_receive(:deliver). + with(message, device).and_yield(message, device) + + second_middleware = double(Pling::Middleware::Base) + second_middleware.should_receive(:deliver). + with(message, device) + + Pling.stub(:middlewares).and_return([first_middleware, second_middleware]) + + Pling.deliver(message, device) + end + end end describe Pling::AuthenticationFailed do
Adds Pling.deliver and extends Pling to use both middle wares and adapters
flinc_pling
train
f58fbebba6ddceebc321cb8d717a161b44186aab
diff --git a/django_extensions/management/commands/sqldiff.py b/django_extensions/management/commands/sqldiff.py index <HASH>..<HASH> 100644 --- a/django_extensions/management/commands/sqldiff.py +++ b/django_extensions/management/commands/sqldiff.py @@ -492,8 +492,9 @@ class SQLDiff(object): continue if constraint['unique'] and field.unique: continue - if constraint['index'] and constraint['type'] == 'idx' and constraint['orders'] and field.unique: + if constraint['index'] and constraint['type'] == 'idx' and constraint.get('orders') and field.unique: # django automatically creates a _like varchar_pattern_ops/text_pattern_ops index see https://code.djangoproject.com/ticket/12234 + # note: mysql does not have and/or introspect and fill the 'orders' attribute of constraint information continue if constraint['index'] and field.db_index: continue
mysql does not have and/or introspect and fill the `orders` attribute of constraint information
django-extensions_django-extensions
train
de66180167e7efda297ad81ece0f2d2953f81fb3
diff --git a/src/components/scrollHeader/scrollHeader.js b/src/components/scrollHeader/scrollHeader.js index <HASH>..<HASH> 100644 --- a/src/components/scrollHeader/scrollHeader.js +++ b/src/components/scrollHeader/scrollHeader.js @@ -6,6 +6,7 @@ * Scrollable content */ angular.module('material.components.scrollHeader', [ + 'material.components.content', 'material.services.registry' ]) diff --git a/src/components/scrollHeader/scrollHeader.spec.js b/src/components/scrollHeader/scrollHeader.spec.js index <HASH>..<HASH> 100644 --- a/src/components/scrollHeader/scrollHeader.spec.js +++ b/src/components/scrollHeader/scrollHeader.spec.js @@ -0,0 +1,23 @@ + +describe('materialScrollHeader', function() { + beforeEach(module('material.components.scrollHeader')); + + function setup(attrs) { + var el; + inject(function($compile, $document, $rootScope) { + el = $compile('<div><material-toolbar class="material-theme-light-blue material-medium-tall" scroll-header condensed-height="60"><material-content></material-content></div>')($rootScope.$new()); + $rootScope.$apply(); + $document[0].body.appendChild(el[0]); + }); + return el; + } + + describe('directive', function() { + iit('Should have attribute', function() { + var el = setup(''); + var toolbar = el[0].querySelector('material-toolbar'); + expect(el[0].hasAttribute('scroll-header')).toBe(true); + }); + }); + +});
chore(scrollHeader): Unit test and cleanup
angular_material
train
0d10d7b6b4ebdeb43347819730a46bf117899462
diff --git a/salt/grains/core.py b/salt/grains/core.py index <HASH>..<HASH> 100644 --- a/salt/grains/core.py +++ b/salt/grains/core.py @@ -471,6 +471,8 @@ def _virtual(osdata): zone = __salt__['cmd.run']('{0}'.format(zonename)) if zone != "global": grains['virtual'] = 'zone' + if osdata['os'] == 'SmartOS': + grains.update(_smartos_zone_data(grains)) # Check if it's a branded zone (i.e. Solaris 8/9 zone) if isdir('/.SUNWnative'): grains['virtual'] = 'zone' @@ -990,6 +992,35 @@ def _hw_data(osdata): grains[key] = value return grains +def _smartos_zone_data(osdata): + ''' + Return useful information from a SmartOS zone + ''' + # Provides: + # pkgsrcversion + # imageversion + grains = {} + + pkgsrcversion = re.compile('^release:\\s(.+)') + imageversion = re.compile('Image:\\s(.+)') + if os.path.isfile('/etc/pkgsrc_version'): + with salt.utils.fopen('/etc/pkgsrc_version', 'r') as fp_: + for line in fp_: + match = pkgsrcversion.match(line) + if match: + grains['pkgsrcversion'] = match.group(1) + if os.path.isfile('/etc/product'): + with salt.utils.fopen('/etc/product', 'r') as fp_: + for line in fp_: + match = imageversion.match(line) + if match: + grains['imageversion'] = match.group(1) + if 'pkgsrcversion' not in grains: + grains['pkgsrcversion'] = 'Unknown' + if 'imageversion' not in grains: + grains['imageversion'] = 'Unknown' + + return grains def get_server_id(): '''
grains/core : add useful information from SmartOS zone This patch is intended for SmartOS users who are using OS virtualization. You can now have access to : - pkgsrcversion - imageversion
saltstack_salt
train
8700ed1379e0089fd7c8df1743403dd09ec4baf4
diff --git a/chef/lib/chef/cookbook_version.rb b/chef/lib/chef/cookbook_version.rb index <HASH>..<HASH> 100644 --- a/chef/lib/chef/cookbook_version.rb +++ b/chef/lib/chef/cookbook_version.rb @@ -549,11 +549,16 @@ class Chef end private :preferences_for_path - def to_json(*a) + def to_hash result = manifest.dup - result['json_class'] = self.class.name result['chef_type'] = 'cookbook_version' result["_rev"] = couchdb_rev if couchdb_rev + result.to_hash + end + + def to_json(*a) + result = self.to_hash + result['json_class'] = self.class.name result.to_json(*a) end diff --git a/features/api/cookbooks/showlist_cookbooks.feature b/features/api/cookbooks/showlist_cookbooks.feature index <HASH>..<HASH> 100644 --- a/features/api/cookbooks/showlist_cookbooks.feature +++ b/features/api/cookbooks/showlist_cookbooks.feature @@ -9,15 +9,17 @@ Feature: Show a cookbook via the REST API Given I am an administrator When I fully upload a sandboxed cookbook named 'testcookbook_valid' versioned '0.1.0' with 'testcookbook_valid' Then I 'GET' the path '/cookbooks/testcookbook_valid/0.1.0' - Then I call to_hash on the inflated response - Then the inflated responses key 'name' should match 'testcookbook_valid' - Then the inflated responses key 'files' should match '^\[.+\]$' as json - Then the inflated responses key 'recipes' should match '^\[.+\]$' as json - Then the inflated responses key 'metadata' should match '^\{.+\}$' as json - Then the inflated responses key 'attributes' should match '^\[.+\]$' as json - Then the inflated responses key 'libraries' should match '^\[.+\]$' as json - Then the inflated responses key 'definitions' should match '^\[.+\]$' as json - Then the inflated responses key 'templates' should match '^\[.+\]$' as json + Then the inflated response should respond to 'cookbook_name' and match 'testcookbook_valid' + Then the inflated response should respond to 'name' and match 'testcookbook_valid-0.1.0' + Then the inflated response should respond to 'files' and match '^\[\]$' as json + Then the inflated response should respond to 'root_files' and match '^\[.+\]$' as json + Then the inflated response should respond to 'recipes' and match '^\[.+\]$' as json + Then the inflated response should respond to 'metadata' and match '^\{.+\}$' as json + Then the inflated response should respond to 'attributes' and match '^\[.+\]$' as json + Then the inflated response should respond to 'libraries' and match '^\[\]$' as json + Then the inflated response should respond to 'definitions' and match '^\[\]$' as json + Then the inflated response should respond to 'templates' and match '^\[\]$' as json + Then the inflated response should respond to 'resources' and match '^\[\]$' as json @show_cookbook_negative Scenario: Show a cookbook with a wrong private key diff --git a/features/steps/response_steps.rb b/features/steps/response_steps.rb index <HASH>..<HASH> 100644 --- a/features/steps/response_steps.rb +++ b/features/steps/response_steps.rb @@ -141,6 +141,9 @@ Then /^the inflated response should respond to '(.+)' and match '(.+)'$/ do |met self.inflated_response.to_hash[method].should == to_match end +Then /^the inflated response should respond to '(.+)' and match '(.+)' as json$/ do |method, regex| + self.inflated_response.to_hash[method].to_json.should =~ /#{regex}/m +end Then /^the fields in the inflated response should match the '(.+)'$/ do |stash_name| self.inflated_response.each do |k,v|
add to_json to cookbook version
chef_chef
train
22f5e45811acd18b2940666524d6959bb06e155a
diff --git a/core/src/main/java/com/google/bitcoin/script/Script.java b/core/src/main/java/com/google/bitcoin/script/Script.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/google/bitcoin/script/Script.java +++ b/core/src/main/java/com/google/bitcoin/script/Script.java @@ -660,10 +660,7 @@ public class Script { continue; switch(opcode) { - case OP_0: - // This is also OP_FALSE (they are both zero). - stack.add(new byte[]{0}); - break; + // OP_0 is no opcode case OP_1NEGATE: stack.add(Utils.reverseBytes(Utils.encodeMPI(BigInteger.ONE.negate(), false))); break;
Remove incorrect execution of OP_0. That code was never reached, because OP_0 is not an opcode in terms of chunk.isOpCode()). However, it lead to believe that OP_0 pushes the vector [0], rather than correctly the empty vector to the stack. Because the code was never executed, this bug could never trigger a test. Afaict, script.cpp does not have the corresponding case in its switch block.
bitcoinj_bitcoinj
train
4b14aa1b0a9ff145ce263e3d95e6067c5f19c9d4
diff --git a/tests/questions/test_questions_base.py b/tests/questions/test_questions_base.py index <HASH>..<HASH> 100644 --- a/tests/questions/test_questions_base.py +++ b/tests/questions/test_questions_base.py @@ -105,11 +105,11 @@ class QuestionsBaseTestCase(unittest2.TestCase): {'text': 'Derelik', 'value': 10000001L}, ], 'images': { - 32: 'https://image.eveonline.com/Render/10000001_32.png', - 64: 'https://image.eveonline.com/Render/10000001_64.png', - 128: 'https://image.eveonline.com/Render/10000001_128.png', - 256: 'https://image.eveonline.com/Render/10000001_256.png', - 512: 'https://image.eveonline.com/Render/10000001_512.png', + 32: 'https://imageserver.eveonline.com/Render/10000001_32.png', + 64: 'https://imageserver.eveonline.com/Render/10000001_64.png', + 128: 'https://imageserver.eveonline.com/Render/10000001_128.png', + 256: 'https://imageserver.eveonline.com/Render/10000001_256.png', + 512: 'https://imageserver.eveonline.com/Render/10000001_512.png', }, })
Fixing tests based because of the eveimageserver library switch
evetrivia_thanatos
train
ebc7a139a1328300408c2561bbc8e9e9781cf74a
diff --git a/tests/spec/Digbang/Security/Auth/EmailerSpec.php b/tests/spec/Digbang/Security/Auth/EmailerSpec.php index <HASH>..<HASH> 100644 --- a/tests/spec/Digbang/Security/Auth/EmailerSpec.php +++ b/tests/spec/Digbang/Security/Auth/EmailerSpec.php @@ -31,6 +31,9 @@ class EmailerSpec extends ObjectBehavior $this->beConstructedWith($mailer, $config); + $user->name = 'Some Username'; + $user->email = 'some@email.com'; + $this->sendActivation($user, 'http://an/activation/url'); } @@ -44,6 +47,9 @@ class EmailerSpec extends ObjectBehavior $this->beConstructedWith($mailer, $config); + $user->name = 'Some Username'; + $user->email = 'some@email.com'; + $this->sendPasswordReset($user, 'http://the/password/reset/link'); } }
UserInterface doesn't have name and email properties because they are magical __get calls.
digbang_security
train
3eac183d8cb1d00d59dc4a7ebf6c472f8db23e86
diff --git a/src/mousetracker.js b/src/mousetracker.js index <HASH>..<HASH> 100644 --- a/src/mousetracker.js +++ b/src/mousetracker.js @@ -943,7 +943,7 @@ if( event.touches.length === 1 && event.targetTouches.length === 1 && event.changedTouches.length === 1 && - THIS[ tracker.hash ].lastTouch === event.touches[ 0 ]){ + THIS[ tracker.hash ].lastTouch.identifier === event.touches[ 0 ].identifier){ onMouseMove( tracker, event.touches[ 0 ] );
Fix handling of touchmove events on Android Dragging the canvas did not work on Android devices as the === check for lastTouch and the current event was always evaluating to false. Presumably Safari on iOS re-uses the same Touch object for touchmove events with the same finger, whereas Chrome/Firefox on Android creates new Touch objects for each event (so the === evaluates false). The code now compares Touch.identifier to ensure the new touch event is from the same finger as the initiating touchstart.
openseadragon_openseadragon
train
1477af8c63543238813a916221dee9fe90bea1e5
diff --git a/.babelrc b/.babelrc index <HASH>..<HASH> 100644 --- a/.babelrc +++ b/.babelrc @@ -1,4 +1,7 @@ { "presets": [ "es2015", "react" ], - "plugins": [ "transform-object-rest-spread", "add-module-exports" ] + "plugins": [ + "transform-object-rest-spread", + "add-module-exports" + ] } diff --git a/src/utils/gulp/gulp-tasks-dist.js b/src/utils/gulp/gulp-tasks-dist.js index <HASH>..<HASH> 100644 --- a/src/utils/gulp/gulp-tasks-dist.js +++ b/src/utils/gulp/gulp-tasks-dist.js @@ -41,6 +41,7 @@ module.exports = function(gulp, options, webpackConfig, dist) { if (!argv.skipMinify) { plugins.push(new webpack.optimize.UglifyJsPlugin({ + mangle: false, compress: { warnings: false } diff --git a/src/utils/gulp/gulp-tasks-test.js b/src/utils/gulp/gulp-tasks-test.js index <HASH>..<HASH> 100644 --- a/src/utils/gulp/gulp-tasks-test.js +++ b/src/utils/gulp/gulp-tasks-test.js @@ -36,7 +36,10 @@ module.exports = function(gulp, options) { read: false }).pipe(babel({ "presets": [ "es2015", "react" ], - "plugins": [ "transform-object-rest-spread", "add-module-exports" ] + "plugins": [ + "transform-object-rest-spread", + "add-module-exports" + ] })).pipe(mocha({ reporter: 'spec'})).once('end', function() { if (argv.w) { diff --git a/src/utils/gulp/gulp-tasks.js b/src/utils/gulp/gulp-tasks.js index <HASH>..<HASH> 100644 --- a/src/utils/gulp/gulp-tasks.js +++ b/src/utils/gulp/gulp-tasks.js @@ -99,7 +99,10 @@ module.exports = function(gulp, opts) { dot: true }).pipe(gulpif(copyAsset.babel, babel({ "presets": [ "es2015", "react" ], - "plugins": [ "transform-object-rest-spread", "add-module-exports" ] + "plugins": [ + "transform-object-rest-spread", + "add-module-exports" + ] }))) .pipe(gulp.dest(copyAsset.dist ? copyAsset.dist : dist)); }
Added mangle false to js minify in webpack.
grommet_grommet
train
7cdbc7ea896833b2fd8b564826ca3010c29c13bd
diff --git a/salesforce/tests/test_integration.py b/salesforce/tests/test_integration.py index <HASH>..<HASH> 100644 --- a/salesforce/tests/test_integration.py +++ b/salesforce/tests/test_integration.py @@ -508,8 +508,9 @@ class BasicSOQLTest(TestCase): self.assertLessEqual(len(leads_list), 2000) print("Not enough Leads accumulated (currently %d including deleted) " "in the last two weeks that are necessary for splitting the " - "query into more requests. Number 1001 or 2001 is sure." % + "query into more requests. Number 1001 or 2001 is enough." % len(leads_list)) + self.skipTest("Not enough Leads found for big query test") def test_errors(self): """
Fixed statistics of big query test as skipped if not enough data.
django-salesforce_django-salesforce
train
09242b166268231402c2efec1836b20f1b5a60ed
diff --git a/lib/bench/summarize.rb b/lib/bench/summarize.rb index <HASH>..<HASH> 100644 --- a/lib/bench/summarize.rb +++ b/lib/bench/summarize.rb @@ -53,23 +53,27 @@ module Bench end # class LeafNode def initialize - @by = [] + @nodes = [] @aggregators = {} yield self end def build_sub_node(index) - if key = @by[index + 1] - ByNode.new(key, lambda{ build_sub_node(index + 1) }) - else - LeafNode.new(@aggregators) + kind, key = @nodes[index + 1] + case kind + when :by + ByNode.new(key, lambda{ build_sub_node(index + 1) }) + when NilClass + LeafNode.new(@aggregators) + else + raise "Unexpected node kind #{kind}" end end # Factory methods (public DSL) def by(*names) - @by += names + @nodes += names.collect{|n| [:by, n]} end def count(arg)
Opened the ability to add other kind of nodes in Summarize
blambeau_viiite
train
53649f4b95da713630033c60186cff5a2bf7778f
diff --git a/src/org/jgroups/protocols/pbcast/CoordGmsImpl.java b/src/org/jgroups/protocols/pbcast/CoordGmsImpl.java index <HASH>..<HASH> 100644 --- a/src/org/jgroups/protocols/pbcast/CoordGmsImpl.java +++ b/src/org/jgroups/protocols/pbcast/CoordGmsImpl.java @@ -17,7 +17,7 @@ import java.util.concurrent.locks.ReentrantLock; * Coordinator role of the Group MemberShip (GMS) protocol. Accepts JOIN and LEAVE requests and emits view changes * accordingly. * @author Bela Ban - * @version $Id: CoordGmsImpl.java,v 1.106 2009/05/19 15:35:30 belaban Exp $ + * @version $Id: CoordGmsImpl.java,v 1.107 2009/05/20 11:30:56 belaban Exp $ */ public class CoordGmsImpl extends GmsImpl { private final MergeTask merge_task=new MergeTask(); @@ -205,7 +205,7 @@ public class CoordGmsImpl extends GmsImpl { * If a merge is already in progress, send back a MergeData with the merge_rejected field set to true. */ public void handleMergeRequest(Address sender, MergeId merge_id) { - boolean success=setMergeId(null, merge_id); + boolean success=matchMergeId(merge_id) || setMergeId(null, merge_id); if(!success) { if(log.isErrorEnabled()) log.error(gms.local_addr + ": merge is already in progress"); sendMergeRejectedResponse(sender, merge_id); @@ -237,7 +237,7 @@ public class CoordGmsImpl extends GmsImpl { public void handleMergeResponse(MergeData data, MergeId merge_id) { if(!matchMergeId(merge_id)) { if(log.isErrorEnabled()) - log.error("this.merge_id (" + this.merge_id + ") is different from merge_id (" + merge_id + ')'); + log.error(gms.local_addr + ": this.merge_id (" + this.merge_id + ") is different from merge_id (" + merge_id + ')'); return; } merge_rsps.add(data.getSender(), data); @@ -767,9 +767,15 @@ public class CoordGmsImpl extends GmsImpl { MergeId new_merge_id=MergeId.create(gms.local_addr); Vector<Address> coordsCopy=new Vector<Address>(coords); - try { + try { + boolean success=setMergeId(null, new_merge_id); + if(!success) { + log.warn("failed to set my own merge_id (" + merge_id + ") to " + new_merge_id); + return; + } + /* 2. Fetch the current Views/Digests from all subgroup coordinators */ - boolean success=getMergeDataFromSubgroupCoordinators(coords, new_merge_id, gms.merge_timeout); + success=getMergeDataFromSubgroupCoordinators(coords, new_merge_id, gms.merge_timeout); if(!success) throw new Exception("merge aborted, merge leader did not get data from all subgroup coordinators " + coords);
leader sets merge_id right away, otherwise it cannot correlate responses from other which are faster than the leader itself
belaban_JGroups
train
997546d2ff79aa21db240b9607c39ae73935b96c
diff --git a/lib/undies/source.rb b/lib/undies/source.rb index <HASH>..<HASH> 100644 --- a/lib/undies/source.rb +++ b/lib/undies/source.rb @@ -12,5 +12,13 @@ module Undies @block = block end + def markup + self.block || self.file + end + + def layout + self.file if self.block + end + end end diff --git a/test/source_test.rb b/test/source_test.rb index <HASH>..<HASH> 100644 --- a/test/source_test.rb +++ b/test/source_test.rb @@ -9,6 +9,7 @@ class Undies::Source context 'a source' subject { Undies::Source.new(&Proc.new {}) } should have_readers :file, :block + should have_instance_methods :markup, :layout should "complain if no file or block given" do assert_raises ArgumentError do @@ -33,6 +34,12 @@ class Undies::Source assert_nil subject.file end + should "use the block source as markup w/ no layout" do + assert subject.markup + assert_equal subject.block, subject.markup + assert_nil subject.layout + end + end class FileTest < BasicTest @@ -47,6 +54,12 @@ class Undies::Source assert subject.file end + should "use the file source as markup w/ no layout" do + assert subject.markup + assert_equal subject.file, subject.markup + assert_nil subject.layout + end + end class BothTest < BasicTest @@ -61,6 +74,15 @@ class Undies::Source assert subject.file end + should "use the block source as markup and the file source as layout" do + assert subject.markup + assert_equal subject.block, subject.markup + assert subject.layout + assert_equal subject.file, subject.layout + end + + + end end
making the source aware of marku vs layout
redding_undies
train
4bad04172b6073dfed02b5f867b71863724617cd
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -15,7 +15,7 @@ setup(name='satyr', packages=['satyr'], long_description=(open('README.rst').read() if exists('README.rst') else ''), - install_requires=[], + install_requires=['cloudpickle'], extras_require={'mesos': ['mesos.native']}, setup_requires=['pytest-runner'], tests_require=['pytest'],
Added cloudpickle to dependencies
daskos_mentor
train
301523fe76201c1450f97ef6098b6f17d8b054fd
diff --git a/colorama/winterm.py b/colorama/winterm.py index <HASH>..<HASH> 100644 --- a/colorama/winterm.py +++ b/colorama/winterm.py @@ -27,9 +27,10 @@ class WinTerm(object): self._default_fore = self._fore self._default_back = self._back self._default_style = self._style + self._light = 0 def get_attrs(self): - return self._fore + self._back * 16 + self._style + return self._fore + self._back * 16 + (self._style | self._light) def set_attrs(self, value): self._fore = value & 7 @@ -45,9 +46,9 @@ class WinTerm(object): fore = self._default_fore self._fore = fore if light: - self._style |= WinStyle.BRIGHT + self._light |= WinStyle.BRIGHT else: - self._style &= ~WinStyle.BRIGHT + self._light &= ~WinStyle.BRIGHT self.set_console(on_stderr=on_stderr) def back(self, back=None, light=False, on_stderr=False): @@ -55,9 +56,9 @@ class WinTerm(object): back = self._default_back self._back = back if light: - self._style |= WinStyle.BRIGHT_BACKGROUND + self._light |= WinStyle.BRIGHT_BACKGROUND else: - self._style &= ~WinStyle.BRIGHT + self._light &= ~WinStyle.BRIGHT_BACKGROUND self.set_console(on_stderr=on_stderr) def style(self, style=None, on_stderr=False):
Added separate _light attribute for Windows
tartley_colorama
train
6ff6f3095aeedb55859ce1bad2fb39f0b8a93673
diff --git a/segments/username.py b/segments/username.py index <HASH>..<HASH> 100644 --- a/segments/username.py +++ b/segments/username.py @@ -8,6 +8,11 @@ def add_username_segment(): import os user_prompt = ' %s ' % os.getenv('USER') - powerline.append(user_prompt, Color.USERNAME_FG, Color.USERNAME_BG) + if os.getenv('USER') == 'root': + bgcolor = Color.USERNAME_ROOT_BG + else: + bgcolor = Color.USERNAME_BG + + powerline.append(user_prompt, Color.USERNAME_FG, bgcolor) add_username_segment() diff --git a/themes/basic.py b/themes/basic.py index <HASH>..<HASH> 100644 --- a/themes/basic.py +++ b/themes/basic.py @@ -3,6 +3,7 @@ class Color(DefaultColor): USERNAME_FG = 8 USERNAME_BG = 15 + USERNAME_ROOT_BG = 1 HOSTNAME_FG = 8 HOSTNAME_BG = 7 diff --git a/themes/default.py b/themes/default.py index <HASH>..<HASH> 100644 --- a/themes/default.py +++ b/themes/default.py @@ -5,6 +5,7 @@ class DefaultColor: """ USERNAME_FG = 250 USERNAME_BG = 240 + USERNAME_ROOT_BG = 124 HOSTNAME_FG = 250 HOSTNAME_BG = 238 diff --git a/themes/solarized-dark.py b/themes/solarized-dark.py index <HASH>..<HASH> 100644 --- a/themes/solarized-dark.py +++ b/themes/solarized-dark.py @@ -1,6 +1,7 @@ class Color(DefaultColor): USERNAME_FG = 15 USERNAME_BG = 4 + USERNAME_ROOT_BG = 1 HOSTNAME_FG = 15 HOSTNAME_BG = 10 diff --git a/themes/washed.py b/themes/washed.py index <HASH>..<HASH> 100644 --- a/themes/washed.py +++ b/themes/washed.py @@ -1,6 +1,7 @@ class Color(DefaultColor): USERNAME_FG = 8 USERNAME_BG = 251 + USERNAME_ROOT_BG = 209 HOSTNAME_FG = 8 HOSTNAME_BG = 7
Show username segment in red if the current user is root
b-ryan_powerline-shell
train
51b08f7244dc0e4f3d0b40e0b88517fd541d9444
diff --git a/src/openbandparams/iii_v/binary.py b/src/openbandparams/iii_v/binary.py index <HASH>..<HASH> 100644 --- a/src/openbandparams/iii_v/binary.py +++ b/src/openbandparams/iii_v/binary.py @@ -193,9 +193,8 @@ class Binary(Base): Returns the bandgap, Eg, in electron Volts at a given temperature, T, in Kelvin (default: 300 K). ''' - T = cls._get_T(kwargs) - return float(min(cls.Eg_Gamma(T=T), cls.Eg_X(T=T), - cls.Eg_L(T=T))) + return float(min(cls.Eg_Gamma(**kwargs), cls.Eg_X(**kwargs), + cls.Eg_L(**kwargs))) @classmethod def Delta_SO(cls, **kwargs): diff --git a/src/openbandparams/iii_v/quaternary.py b/src/openbandparams/iii_v/quaternary.py index <HASH>..<HASH> 100644 --- a/src/openbandparams/iii_v/quaternary.py +++ b/src/openbandparams/iii_v/quaternary.py @@ -58,14 +58,11 @@ class Quaternary(AlloyBase): temperature, T, in Kelvin (default: 300 K). ''' if self is not None: - T = self._get_T(kwargs) - return min(self.Eg_Gamma(T=T), self.Eg_X(T=T), self.Eg_L(T=T)) + return min(self.Eg_Gamma(**kwargs), self.Eg_X(**kwargs), + self.Eg_L(**kwargs)) else: - x = cls._get_x(kwargs) - y = cls._get_y(kwargs) - T = cls._get_T(kwargs) - return min(cls.Eg_Gamma(x=x, y=y, T=T), cls.Eg_X(x=x, y=y, T=T), - cls.Eg_L(x=x, y=y, T=T)) + return min(cls.Eg_Gamma(**kwargs), cls.Eg_X(**kwargs), + cls.Eg_L(**kwargs)) def __eq__(self, other): return (type(self) == type(other) and diff --git a/src/openbandparams/iii_v/ternary.py b/src/openbandparams/iii_v/ternary.py index <HASH>..<HASH> 100644 --- a/src/openbandparams/iii_v/ternary.py +++ b/src/openbandparams/iii_v/ternary.py @@ -110,13 +110,11 @@ class Ternary(AlloyBase): temperature, T, in Kelvin (default: 300 K). ''' if self is not None: - T = self._get_T(kwargs) - return min(self.Eg_Gamma(T=T), self.Eg_X(T=T), self.Eg_L(T=T)) + return min(self.Eg_Gamma(**kwargs), self.Eg_X(**kwargs), + self.Eg_L(**kwargs)) else: - x = cls._get_x(kwargs) - T = cls._get_T(kwargs) - return min(cls.Eg_Gamma(x=x, T=T), cls.Eg_X(x=x, T=T), - cls.Eg_L(x=x, T=T)) + return min(cls.Eg_Gamma(**kwargs), cls.Eg_X(**kwargs), + cls.Eg_L(**kwargs)) class Ternary1(Ternary): diff --git a/src/openbandparams/tests/test_iii_v_zinc_blende_quaternary.py b/src/openbandparams/tests/test_iii_v_zinc_blende_quaternary.py index <HASH>..<HASH> 100644 --- a/src/openbandparams/tests/test_iii_v_zinc_blende_quaternary.py +++ b/src/openbandparams/tests/test_iii_v_zinc_blende_quaternary.py @@ -18,9 +18,7 @@ # ############################################################################# -from openbandparams.iii_v.zinc_blende.binary import GaAs, AlAs -from openbandparams.iii_v.zinc_blende.quaternary import (quaternaries, - AlGaInAs, AlPAsSb, AlGaAsSb, GaPAsSb, AlGaInSb, AlGaPAs) +from openbandparams.iii_v.zinc_blende.binary import * from openbandparams.iii_v.zinc_blende.quaternary import * import unittest @@ -132,5 +130,11 @@ class TestIIIVZincBlendeQuaternary(unittest.TestCase): self.assertEqual(AlGaPAs.Eg(x=1, y=0), AlAs.Eg()) self.assertEqual(AlGaPAs(x=1, y=0).Eg(), AlAs.Eg()) + def test_non_instanced_lattice_matching(self): + mat = AlInAsSb(Al=0, a=GaSb.a(), T=300) + Eg1 = mat.Eg() + Eg2 = AlInAsSb.Eg(Al=0, a=GaSb.a(), T=300) + self.assertEqual(Eg1, Eg2) + if __name__ == '__main__': unittest.main()
fixed issue #<I> and added a test case for it
scott-maddox_openbandparams
train
0aba3b31df82c6979d57ff201d759b93d25209d0
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -20,7 +20,6 @@ var CSGOClient = function CSGOClient(steamClient, debug) { var self = this; this._client.on("fromGC", function fromGC(app, type, message, callback) { - /* Routes messages from Game Coordinator to their handlers. */ callback = callback || null; var kMsg = type & ~protoMask; @@ -42,7 +41,7 @@ var CSGOClient = function CSGOClient(steamClient, debug) { this._sendClientHello = function() { if (self.debug) util.log("Sending ClientHello"); if (!self._client) { - util.log("Where the fuck is _client?"); + util.log("Client went missing..."); } else { self._client.toGC(self._appid, (CSGO.EGCBaseClientMsg.k_EMsgGCClientHello | protoMask), gcsdk_gcmessages.CMsgClientHello.serialize({})); @@ -53,13 +52,12 @@ util.inherits(CSGOClient, EventEmitter); require("./generated/messages"); -// Expose enums CSGOClient.prototype.ServerRegion = CSGO.ServerRegion; CSGOClient.prototype.GameMode = CSGO.GameMode; // Methods CSGOClient.prototype.launch = function() { - /* Reports to Steam that we are running Dota 2. Initiates communication with GC with EMsgGCClientHello */ + /* Reports to Steam that we are running Counter-Strike: Global Offensive. Initiates communication with GC with EMsgGCClientHello */ if (this.debug) util.log("Launching CS:GO"); this._client.gamesPlayed([this._appid]); @@ -134,4 +132,4 @@ handlers[CSGO.EGCBaseClientMsg.k_EMsgGCClientConnectionStatus] = function gcClie CSGO.CSGOClient = CSGOClient; -require("./handlers/match"); \ No newline at end of file +require("./handlers/match");
Removed some dota 2 stuff
joshuaferrara_node-csgo
train
7e86a4db8a703fbf1e6f4d1a5cdd29f170b1cffa
diff --git a/lib/counter_culture/extensions.rb b/lib/counter_culture/extensions.rb index <HASH>..<HASH> 100644 --- a/lib/counter_culture/extensions.rb +++ b/lib/counter_culture/extensions.rb @@ -36,7 +36,13 @@ module CounterCulture if: -> (model) { !model.paranoia_destroyed? } end - after_update :_update_counts_after_update + after_update :_update_counts_after_update, if: -> (model) do + if defined?(Discard::Model) && model.class.include?(Discard::Model) + !model.discarded? + else + true + end + end if respond_to?(:before_restore) before_restore :_update_counts_after_create, diff --git a/spec/counter_culture_spec.rb b/spec/counter_culture_spec.rb index <HASH>..<HASH> 100644 --- a/spec/counter_culture_spec.rb +++ b/spec/counter_culture_spec.rb @@ -1813,6 +1813,39 @@ describe "CounterCulture" do expect(company.reload.soft_delete_discards_count).to eq(0) end end + + describe "dynamic column names with totaling instead of counting" do + describe 'when updating discarded records' do + it 'does not update sum' do + skip("Unsupported in this version of Rails") if Rails.version < "4.2.0" + + company = Company.create! + sd = SoftDeleteDiscard.create!(company_id: company.id, value: 5) + + expect(company.reload.soft_delete_discard_values_sum).to eq(5) + + sd.discard + expect(company.reload.soft_delete_discard_values_sum).to eq(0) + + sd.update value: 10 + expect(company.reload.soft_delete_discard_values_sum).to eq(0) + end + end + + describe 'when updating undiscarded records' do + it 'updates sum' do + skip("Unsupported in this version of Rails") if Rails.version < "4.2.0" + + company = Company.create! + sd = SoftDeleteDiscard.create!(company_id: company.id, value: 5) + + expect(company.reload.soft_delete_discard_values_sum).to eq(5) + + sd.update value: 10 + expect(company.reload.soft_delete_discard_values_sum).to eq(10) + end + end + end end describe "when using paranoia for soft deletes" do diff --git a/spec/models/soft_delete_discard.rb b/spec/models/soft_delete_discard.rb index <HASH>..<HASH> 100644 --- a/spec/models/soft_delete_discard.rb +++ b/spec/models/soft_delete_discard.rb @@ -3,4 +3,5 @@ class SoftDeleteDiscard < ActiveRecord::Base belongs_to :company counter_culture :company + counter_culture :company, column_name: 'soft_delete_discard_values_sum', delta_column: 'value' end diff --git a/spec/schema.rb b/spec/schema.rb index <HASH>..<HASH> 100644 --- a/spec/schema.rb +++ b/spec/schema.rb @@ -26,6 +26,7 @@ ActiveRecord::Schema.define(:version => 20120522160158) do t.integer "children_count", :default => 0, :null => false t.integer "soft_delete_paranoia_count", :default => 0, :null => false t.integer "soft_delete_discards_count", :default => 0, :null => false + t.integer "soft_delete_discard_values_sum", :default => 0, :null => false t.datetime "created_at" t.datetime "updated_at" end @@ -184,6 +185,7 @@ ActiveRecord::Schema.define(:version => 20120522160158) do create_table "soft_delete_discards", :force => true do |t| t.integer "company_id", :null => false + t.integer "value", :default => 0 t.timestamp "discarded_at" end
Dont update running total on discarded records
magnusvk_counter_culture
train
9dcc9facf025eb8043503987431af4b3bfe46a0f
diff --git a/src/Symfony/Component/Console/Output/Output.php b/src/Symfony/Component/Console/Output/Output.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Component/Console/Output/Output.php +++ b/src/Symfony/Component/Console/Output/Output.php @@ -36,16 +36,16 @@ abstract class Output implements OutputInterface * Constructor. * * @param integer $verbosity The verbosity level (self::VERBOSITY_QUIET, self::VERBOSITY_NORMAL, self::VERBOSITY_VERBOSE) - * @param Boolean $decorated Whether to decorate messages or not (null for auto-guessing) + * @param Boolean $decorated Whether to decorate messages or not * @param OutputFormatterInterface $formatter Output formatter instance * * @api */ - public function __construct($verbosity = self::VERBOSITY_NORMAL, $decorated = null, OutputFormatterInterface $formatter = null) + public function __construct($verbosity = self::VERBOSITY_NORMAL, $decorated = false, OutputFormatterInterface $formatter = null) { $this->verbosity = null === $verbosity ? self::VERBOSITY_NORMAL : $verbosity; $this->formatter = null === $formatter ? new OutputFormatter() : $formatter; - $this->formatter->setDecorated((Boolean) $decorated); + $this->formatter->setDecorated($decorated); } /** @@ -81,7 +81,7 @@ abstract class Output implements OutputInterface */ public function setDecorated($decorated) { - $this->formatter->setDecorated((Boolean) $decorated); + $this->formatter->setDecorated($decorated); } /**
[Console] fix abstract Output class that fasly claims to support guessing of decorated variable. Also we don't need to typecast to boolean as its already done by the formatter and its his responsibility
symfony_symfony
train
e9cf7d9e17d3d52e25707b24bc7b0e6e45788aca
diff --git a/network/firewall.go b/network/firewall.go index <HASH>..<HASH> 100644 --- a/network/firewall.go +++ b/network/firewall.go @@ -227,7 +227,7 @@ type ListMachineRulesInput struct { } func (c *FirewallClient) ListMachineRules(ctx context.Context, input *ListMachineRulesInput) ([]*FirewallRule, error) { - path := fmt.Sprintf("/%s/machines/%s/firewallrules", c.client.AccountName, input.MachineID) + path := fmt.Sprintf("/%s/machines/%s/fwrules", c.client.AccountName, input.MachineID) reqInputs := client.RequestInput{ Method: http.MethodGet, Path: path, @@ -243,7 +243,7 @@ func (c *FirewallClient) ListMachineRules(ctx context.Context, input *ListMachin var result []*FirewallRule decoder := json.NewDecoder(respReader) if err = decoder.Decode(&result); err != nil { - return nil, errwrap.Wrapf("Error decoding ListRules response: {{err}}", err) + return nil, errwrap.Wrapf("Error decoding ListMachineRules response: {{err}}", err) } return result, nil
Fix endpoint for compute.ListMachineRules This wasn't as per the documentation <URL>
joyent_triton-go
train
3ada984ba1960c9eb4358bf3fc5586e2a944ed73
diff --git a/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/picker/MenuPanel.java b/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/picker/MenuPanel.java index <HASH>..<HASH> 100755 --- a/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/picker/MenuPanel.java +++ b/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/picker/MenuPanel.java @@ -274,16 +274,11 @@ final class MenuPanel extends WPanel { * Updates the entries in the "Recent" sub-menu. */ private void updateRecentMenu() { - WComponent itemContainerComponent = recentMenu.getChildAt(recentMenu.getChildCount() - 1); - if(itemContainerComponent instanceof WContainer) { - WContainer itemContainer = (WContainer) itemContainerComponent; - for (int i = itemContainer.getChildCount() - 1; i >= 0; i--) { - WComponent child = itemContainer.getChildAt(i); - - if (child instanceof WMenuItem) { - recentMenu.removeMenuItem((WMenuItem) child); - } - } + + Object[] menuItems = recentMenu.getMenuItems().toArray(); + + for (int i = menuItems.length - 1; i >= 0; i--) { + recentMenu.removeMenuItem((WMenuItem) menuItems[i]); } int index = 1;
Improve recently accessed list Improve the method for removing menuItems in the recently accessed list.
BorderTech_wcomponents
train
c9328b72b28cf91cc8dfcd8fa35cbacfa5882585
diff --git a/spock/plugins/helpers/physics.py b/spock/plugins/helpers/physics.py index <HASH>..<HASH> 100644 --- a/spock/plugins/helpers/physics.py +++ b/spock/plugins/helpers/physics.py @@ -52,7 +52,11 @@ class PhysicsCore(object): def move_target(self, vector): vector.y = self.pos.y - self.direction = vector - self.pos + if vector - self.pos < self.vec: + self.pos.init(vector) + self.vec.zero() + else: + self.direction = vector - self.pos def move_vector(self, vector): vector.y = 0 @@ -69,7 +73,7 @@ class PhysicsPlugin(PluginBase): events = { 'physics_tick': 'tick', 'client_position_update': 'stop_physics', - 'position_reset': 'start_physics', + 'movement_position_reset': 'start_physics', } def __init__(self, ploader, settings): @@ -93,13 +97,12 @@ class PhysicsPlugin(PluginBase): def tick(self, _, __): if self.pause_physics: return self.pause_physics - self.vec *= const.PHY_BASE_DRG self.apply_accel() mtv = self.get_mtv() self.apply_vector(mtv) self.pos.on_ground = mtv.y > 0 self.vec -= Vector3(0, const.PHY_GAV_ACC, 0) - self.apply_friction() + self.apply_drag() self.pc.direction = Vector3() def get_block_slip(self): @@ -117,7 +120,7 @@ class PhysicsPlugin(PluginBase): if self.pos.on_ground: block_slip = self.get_block_slip() accel_mod = const.BASE_GND_SLIP**3 / block_slip**3 - accel = self.pc.move_accel * accel_mod + accel = self.pc.move_accel * accel_mod * const.PHY_BASE_DRG else: accel = const.PHY_JMP_ACC self.vec += self.pc.direction.norm() * accel @@ -128,10 +131,11 @@ class PhysicsPlugin(PluginBase): self.vec.y = 0 if mtv.y else self.vec.y self.vec.z = 0 if mtv.z else self.vec.z - def apply_friction(self): - friction = self.get_block_slip() * const.PHY_DRG_MUL - self.vec.x *= friction - self.vec.z *= friction + def apply_drag(self): + drag = self.get_block_slip() * const.PHY_DRG_MUL + self.vec.x *= drag + self.vec.z *= drag + self.vec.y *= const.PHY_BASE_DRG # Breadth-first search for a minimum translation vector def get_mtv(self):
Physics update I meant to push ages ago
SpockBotMC_SpockBot
train
ae0ef7e33d55bb3d99d21c517ef9abf5c2b551a9
diff --git a/src/library_visual_scenes/parse-visual-scenes.js b/src/library_visual_scenes/parse-visual-scenes.js index <HASH>..<HASH> 100644 --- a/src/library_visual_scenes/parse-visual-scenes.js +++ b/src/library_visual_scenes/parse-visual-scenes.js @@ -11,7 +11,8 @@ function ParseVisualScenes (library_visual_scenes) { // This is the location of all top level parent nodes if (node.node) { // node.node is the location of all top level nodes - armatureScale = node.scale[0]._.split(' ').map(Number) + armatureScale = node.scale && node.scale[0] + ? node.scale[0]._.split(' ').map(Number) : null parsedJoints = parseJoints(node.node) } /*
fix for when armature scale isn't present
chinedufn_collada-dae-parser
train
7b6b0ecb445da55478e29d738c693ed13e08d231
diff --git a/scriptblock.js b/scriptblock.js index <HASH>..<HASH> 100644 --- a/scriptblock.js +++ b/scriptblock.js @@ -46,7 +46,11 @@ ScriptblockPlugin.prototype.interact = function(target) { // interact (right-click) with top to set script, other sides to run // TODO: run script when block takes damage instead (left-click) if (target.side === 'top') { - bd.script = prompt("Script for block at ("+[x,y,z].join(",")+"): ", bd.script); + var newScript = prompt("Script for block at ("+[x,y,z].join(",")+"): ", bd.script); + + if (newScript !== null) { + bd.script = newScript; + } this.blockdata.set(x, y, z, bd); } else {
Allow canceling script prompt() to not change it
voxel_voxel-scriptblock
train
3cb65af35208cd51ce25f714cfc99effa2c60282
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -100,6 +100,26 @@ hash for *SELECT* queries. Binding hash values are instances of `Redlander::Node For query options and available query languages refer to `Model#query` documentation. +### Notes on Nodes + +For detailed information about creating and working with individual nodes +refer to `Redlander::Node` documentation. We just highlight a few gotchas +and tips here. + +To create a blank node, just do `Node.new` (or `Node.new(nil)`). This produces +a blank node with a random unique identifier, as documented in `librdf` API. +To produce a blank node with a user-defined id, add `:blank_id` option: +`Node.new(:blank_id => "my-blank-node-1")`. + +It is sometimes not convenient to create resource nodes from the instances +of URI -- you can be given just a simple list of URIs in text format. +Converting them all into Ruby URI objects, then feeding them to `Node.new` +doesn't make much sense if you are not going to reuse those Ruby URI objects. +In such cases you can use `:resource` option to create resource nodes directly +from strings (that would otherwise be interpreted as string literals): +`Node.new("http://example.org/thing/1", :resource => true)`. + + ### Localized string literals Localized string literals are instantiated as LocalizedString objects. diff --git a/lib/redlander/node.rb b/lib/redlander/node.rb index <HASH>..<HASH> 100644 --- a/lib/redlander/node.rb +++ b/lib/redlander/node.rb @@ -21,10 +21,14 @@ module Redlander when URI Redland.librdf_new_node_from_uri_string(Redlander.rdf_world, @arg.to_s) else - value = @arg.respond_to?(:xmlschema) ? @arg.xmlschema : @arg.to_s - lang = @arg.respond_to?(:lang) ? @arg.lang.to_s : nil - dt = lang ? nil : Uri.new(XmlSchema.datatype_of(@arg)).rdf_uri - Redland.librdf_new_node_from_typed_literal(Redlander.rdf_world, value, lang, dt) + if @options[:resource] + Redland.librdf_new_node_from_uri_string(Redlander.rdf_world, @arg.to_s) + else + value = @arg.respond_to?(:xmlschema) ? @arg.xmlschema : @arg.to_s + lang = @arg.respond_to?(:lang) ? @arg.lang.to_s : nil + dt = lang ? nil : Uri.new(XmlSchema.datatype_of(@arg)).rdf_uri + Redland.librdf_new_node_from_typed_literal(Redlander.rdf_world, value, lang, dt) + end end raise RedlandError, "Failed to create a new node" if @rdf_node.null? ObjectSpace.define_finalizer(self, self.class.send(:finalize_node, @rdf_node)) @@ -49,13 +53,13 @@ module Redlander # Create a RDF node. # # @param [Any] arg - # - an instance of URI - to create a RDF "resource", - # Note that you cannot create a resource node from an URI string, - # it must be an instance of URI. Otherwise it is treated as a string literal. + # - an instance of URI - to create an RDF "resource", + # see also :resource option below. # - nil (or absent) - to create a blank node, # - any other Ruby object, which can be coerced into a literal. # @param [Hash] options # @option options [String] :blank_id optional ID to use for a blank node. + # @option options [Boolean] :resource interpret arg as URI string and create an RDF "resource". # @raise [RedlandError] if it fails to create a node from the given args. def initialize(arg = nil, options = {}) # If FFI::Pointer is passed, wrap it instantly, diff --git a/spec/lib/redlander/node_spec.rb b/spec/lib/redlander/node_spec.rb index <HASH>..<HASH> 100644 --- a/spec/lib/redlander/node_spec.rb +++ b/spec/lib/redlander/node_spec.rb @@ -36,8 +36,13 @@ describe Node do Node.new(resource_uri).should be_resource end + it "should create a resource node with :resource => true option" do + n1 = Node.new("http://example.com/nodes#node_1", :resource => true) + expect(n1).to be_resource + end + it "should have an instance of URI for a resource node" do - resource_uri = URI('http://example.com/nodes#node_1') + resource_uri = URI.parse('http://example.com/nodes#node_1') Node.new(resource_uri).value.should be_an_instance_of(URI::HTTP) end end
added an option to create resource nodes directly from strings
cordawyn_redlander
train
a6e636b06adf1b6608b01aab295ca66384e02313
diff --git a/byte-buddy-dep/src/main/java/net/bytebuddy/agent/builder/AgentBuilder.java b/byte-buddy-dep/src/main/java/net/bytebuddy/agent/builder/AgentBuilder.java index <HASH>..<HASH> 100644 --- a/byte-buddy-dep/src/main/java/net/bytebuddy/agent/builder/AgentBuilder.java +++ b/byte-buddy-dep/src/main/java/net/bytebuddy/agent/builder/AgentBuilder.java @@ -1466,6 +1466,13 @@ public interface AgentBuilder { */ protected static final ClassLoader INSTANCE = AccessController.doPrivileged(new CreationAction()); + /** + * Creates a new class loader that represents the bootstrap class loader. + */ + private BootstrapClassLoaderMarker() { + super(ClassLoadingStrategy.BOOTSTRAP_LOADER); + } + @Override protected Class<?> loadClass(String name, boolean resolve) { throw new UnsupportedOperationException("This loader is only a non-null marker and is not supposed to be used");
Defined private constructor for marker class loader.
raphw_byte-buddy
train
7c279a2e28b28d76f63083ad26d60569030b5f32
diff --git a/tinylog-impl/src/main/java/org/tinylog/core/WritingThread.java b/tinylog-impl/src/main/java/org/tinylog/core/WritingThread.java index <HASH>..<HASH> 100644 --- a/tinylog-impl/src/main/java/org/tinylog/core/WritingThread.java +++ b/tinylog-impl/src/main/java/org/tinylog/core/WritingThread.java @@ -25,7 +25,7 @@ import org.tinylog.writers.Writer; /** * Thread for writing log entries asynchronously. */ -final class WritingThread extends Thread { +public final class WritingThread extends Thread { private static final String THREAD_NAME = "tinylog-WritingThread"; private static final long MILLISECONDS_TO_SLEEP = 10L;
Less strict code of the TinylogLoggingProvider #<I>. WritingThread needs to be public to allow its use outside TinyLog packages.
pmwmedia_tinylog
train
eddb5401cf631be408bfed1414e71137781e498f
diff --git a/src/Synapse/Mapper/AbstractMapper.php b/src/Synapse/Mapper/AbstractMapper.php index <HASH>..<HASH> 100644 --- a/src/Synapse/Mapper/AbstractMapper.php +++ b/src/Synapse/Mapper/AbstractMapper.php @@ -67,6 +67,8 @@ abstract class AbstractMapper implements LoggerAwareInterface { $this->dbAdapter = $dbAdapter; $this->prototype = $prototype; + + $this->initialize(); } /** @@ -118,6 +120,8 @@ abstract class AbstractMapper implements LoggerAwareInterface if (!$this->hydrator instanceof HydratorInterface) { $this->hydrator = new ArraySerializable; } + + $this->initialized = true; } /** @@ -128,8 +132,6 @@ abstract class AbstractMapper implements LoggerAwareInterface */ protected function execute(PreparableSqlInterface $query) { - $this->initialize(); - $statement = $this->sql()->prepareStatementForSqlObject($query); $resultSet = new HydratingResultSet($this->hydrator, $this->prototype);
Refs #<I> - Call AbstractMapper::initialize() from the constructor instead of the execute method. Also set the $initialized property, which previously was never set.
synapsestudios_synapse-base
train
7850606d2f4bff63360e08a34e1e573c6ed7e199
diff --git a/salt/version.py b/salt/version.py index <HASH>..<HASH> 100644 --- a/salt/version.py +++ b/salt/version.py @@ -19,11 +19,7 @@ try: warnings.simplefilter("ignore") return _deprecated_linux_distribution(**kwargs) except ImportError: - try: - from distro import linux_distribution - except ImportError: - # For Windows - pass + from distro import linux_distribution # pylint: disable=invalid-name,redefined-builtin # Import 3rd-party libs @@ -779,43 +775,5 @@ def versions_report(include_salt_cloud=False): yield line -def msi_conformant_version(): - ''' - For upgrades, an msi installer relies on the "internal version". - The "internal version" MAJOR.MINOR.BUILD is constrained to 255.255.65535. - This contraint can be satisfied for released versions but not so for nightly builds. - The nightly builds, therefore, must first be uninstalled. - - The "display version" is free format. - - Examples: - Git-tag msi display version msi internal version - v3000 3000 30.00.0.0 - v3001 3001 30.01.0.0 - v3001.1 3001.1 30.01.1.0 - v3500 3500 35.00.0.0 - v3800 3800 38.00.0.0 - 2018.3.2 2018.3.2 18.3.2 - v2016.11.2 2016.11.2 16.11.2 - ''' - - if __saltstack_version__.major >= 3000: - # First and second half of major - major1 = six.text_type(__saltstack_version__.major)[:2] - major2 = six.text_type(__saltstack_version__.major)[2:] - # Mask minor == None as 0 - minor = __saltstack_version__.minor or 0 - return '{}.{}.{}'.format(major1, major2, minor) - else: - year = int(six.text_type(__saltstack_version__.major)[2:]) - month = __saltstack_version__.minor - bugfix = __saltstack_version__.bugfix or 0 - return '{}.{}.{}'.format(year, month, bugfix) - - if __name__ == '__main__': - if len(sys.argv) == 2 and sys.argv[1] == 'msi': - # Building the msi requires an msi-conformant version - print(msi_conformant_version()) - else: - print(__version__) + print(__version__)
Removed msi installer related code
saltstack_salt
train
327390704409467b72688b2dc1301f4bce960ff5
diff --git a/core/src/test/java/de/javakaffee/web/msm/MemcachedBackupSessionTest.java b/core/src/test/java/de/javakaffee/web/msm/MemcachedBackupSessionTest.java index <HASH>..<HASH> 100644 --- a/core/src/test/java/de/javakaffee/web/msm/MemcachedBackupSessionTest.java +++ b/core/src/test/java/de/javakaffee/web/msm/MemcachedBackupSessionTest.java @@ -34,16 +34,19 @@ public class MemcachedBackupSessionTest { private MemcachedBackupSession cut; private ExecutorService executor; + private ExecutorService alternateExecutor; @BeforeMethod public void beforeMethod() { cut = new MemcachedBackupSession(); executor = Executors.newCachedThreadPool(); + alternateExecutor = Executors.newCachedThreadPool(); } @AfterMethod public void afterMethod() { executor.shutdown(); + alternateExecutor.shutdown(); } @Test @@ -61,7 +64,7 @@ public class MemcachedBackupSessionTest { }; executor.submit(registerReference).get(); assertEquals(cut.getRefCount(), 1); - executor.submit(registerReference).get(); + alternateExecutor.submit(registerReference).get(); assertEquals(cut.getRefCount(), 2); // we (no ref registered) must not be able to decrement the ref count
Merge PR #<I>: Make MemcachedBackupSessionTest.testRefCount more robust PR text: This test can fail at line <I> because sometimes the same thread will be used in the pool and so the reference is not incremented. I don't know exactly what this means for the semantics involved.
magro_memcached-session-manager
train
fb3c35243f769e1b79f717340f9ae50f2ffed0bd
diff --git a/packages/vaex-core/vaex/expresso.py b/packages/vaex-core/vaex/expresso.py index <HASH>..<HASH> 100644 --- a/packages/vaex-core/vaex/expresso.py +++ b/packages/vaex-core/vaex/expresso.py @@ -310,6 +310,9 @@ class SimplifyExpression(ast.NodeTransformer): return num(0) elif isinstance(left, ast.Num) and left.n == 1: return right + if isinstance(node.op, ast.Div): + if isinstance(left, ast.Num) and left.n == 0: + return num(0) if isinstance(node.op, ast.Add): if isinstance(right, ast.Num) and right.n == 0: return left
expresso: optimization for 0/...
vaexio_vaex
train
25a0512dd97769fc5153afc6e26af298506c542f
diff --git a/lib/solargraph/source/updater.rb b/lib/solargraph/source/updater.rb index <HASH>..<HASH> 100644 --- a/lib/solargraph/source/updater.rb +++ b/lib/solargraph/source/updater.rb @@ -45,43 +45,6 @@ module Solargraph end text end - - # This is an insane hack to fix a discrepancy in version numbers and - # content changes. It's far from perfect. - # - # @return [Integer] - def effective_changes - # changes.length - @effective_changes ||= begin - result = 0 - last_change = nil - changes.each do |change| - if last_change.nil? - result += 1 - last_change = change - else - if change.range.nil? - result += 1 - last_change = nil - else - if last_change.range.start == last_change.range.ending and last_change.range.ending == change.range.ending and change.new_text.empty? - # Some kind of modification to the previous change - elsif change.range.start == change.range.ending and last_change.range.start == change.range.start and last_change.new_text.empty? - # Same idea reversed - elsif change.range.start.line == change.range.ending.line and last_change.range.start.line == change.range.start.line - 1 and last_change.range.ending.line == change.range.ending.line - 1 and last_change.range.start.column == 0 and change.range.start.column == 0 and last_change.new_text == change.new_text - # A block of identical changes - elsif change.range.start.line == change.range.ending.line and last_change.range.start.line == change.range.start.line + 1 and last_change.range.ending.line == change.range.ending.line + 1 and last_change.range.start.column == 0 and change.range.start.column == 0 and last_change.new_text == change.new_text - # Same idea reversed - else - result += 1 - end - last_change = change - end - end - end - result - end - end end end end
Updater no longer relies on effective_changes.
castwide_solargraph
train
6f903479c9cbec38a0db39a7098f00b24e6b83ef
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -124,8 +124,10 @@ function applyVirtualsToChildren(doc, schema, res, virtuals, parent) { } } - attachVirtuals.call(doc, _schema, _doc, virtualsForChild, res); - attachedVirtuals = true; + if (virtualsForChild.length > 0) { + attachVirtuals.call(doc, _schema, _doc, virtualsForChild, res); + attachedVirtuals = true; + } } if (virtuals && virtuals.length && !attachedVirtuals) { diff --git a/test/examples.test.js b/test/examples.test.js index <HASH>..<HASH> 100644 --- a/test/examples.test.js +++ b/test/examples.test.js @@ -186,7 +186,7 @@ describe('examples', function() { schema.plugin(mongooseLeanVirtuals); - const Model = mongoose.model('gh43c', schema); + const Model = mongoose.model('gh43a', schema); return Model.create({ nested: { test: { a: 'Val' } } }). then(() => Model.findOne().lean({ virtuals: ['nested.test2'] })). @@ -195,4 +195,38 @@ describe('examples', function() { assert.equal(result.nested.test2.a, 'Val'); }); }); + + it('nested virtuals that are objects return the value that also have child schemas (gh-43)', function() { + const subschema = new mongoose.Schema({ + other: String, + }, { id: false }); + + subschema.virtual('uppercaseOther').get(function() { + return this.other.toUpperCase(); + }); + + const schema = new mongoose.Schema({ + childs: [subschema], + nested: { + test: { + a: String + } + } + }, { id: false }); + + schema.virtual('nested.test2').get(function() { + return this.nested.test; + }); + + schema.plugin(mongooseLeanVirtuals); + + const Model = mongoose.model('gh43b', schema); + + return Model.create({ childs: [{ other: 'Val' }], nested: { test: { a: 'Val' } } }). + then(() => Model.findOne().lean({ virtuals: ['nested.test2'] })). + then(result => { + assert.equal(result.nested.test.a, 'Val'); + assert.equal(result.nested.test2.a, 'Val'); + }); + }); });
Fix and add test when using nested objects with children
vkarpov15_mongoose-lean-virtuals
train
571c14adf9eea724fe27c8206a8dbb8fcdbc8db1
diff --git a/src/Composer/DependencyResolver/DefaultPolicy.php b/src/Composer/DependencyResolver/DefaultPolicy.php index <HASH>..<HASH> 100644 --- a/src/Composer/DependencyResolver/DefaultPolicy.php +++ b/src/Composer/DependencyResolver/DefaultPolicy.php @@ -75,7 +75,7 @@ class DefaultPolicy implements PolicyInterface foreach ($packages as &$literals) { $policy = $this; usort($literals, function ($a, $b) use ($policy, $pool, $installed) { - return $policy->compareByPriorityPreferInstalled($pool, $installed, $a->getPackage(), $b->getPackage()); + return $policy->compareByPriorityPreferInstalled($pool, $installed, $a->getPackage(), $b->getPackage(), true); }); } @@ -87,6 +87,11 @@ class DefaultPolicy implements PolicyInterface $selected = call_user_func_array('array_merge', $packages); + // now sort the result across all packages to respect replaces across packages + usort($selected, function ($a, $b) use ($policy, $pool, $installed) { + return $policy->compareByPriorityPreferInstalled($pool, $installed, $a->getPackage(), $b->getPackage()); + }); + return $selected; } @@ -110,10 +115,26 @@ class DefaultPolicy implements PolicyInterface return $packages; } - public function compareByPriorityPreferInstalled(Pool $pool, RepositoryInterface $installed, PackageInterface $a, PackageInterface $b) + public function compareByPriorityPreferInstalled(Pool $pool, RepositoryInterface $installed, PackageInterface $a, PackageInterface $b, $ignoreReplace = false) { if ($a->getRepository() === $b->getRepository()) { - return 0; + + if (!$ignoreReplace) { + // return original, not replaced + if ($this->replaces($a, $b)) { + return 1; // use b + } + if ($this->replaces($b, $a)) { + return -1; // use a + } + } + + // priority equal, sort by package id to make reproducible + if ($a->getId() === $b->getId()) { + return 0; + } + + return ($a->getId() < $b->getId()) ? -1 : 1; } if ($a->getRepository() === $installed) { @@ -127,6 +148,19 @@ class DefaultPolicy implements PolicyInterface return ($this->getPriority($pool, $a) > $this->getPriority($pool, $b)) ? -1 : 1; } + protected function replaces(PackageInterface $source, PackageInterface $target) + { + foreach ($source->getReplaces() as $link) { + if ($link->getTarget() === $target->getName() && + (null === $link->getConstraint() || + $link->getConstraint()->matches(new VersionConstraint('==', $target->getVersion())))) { + return true; + } + } + + return false; + } + protected function pruneToBestVersion($literals) { $bestLiterals = array($literals[0]); diff --git a/tests/Composer/Test/DependencyResolver/DefaultPolicyTest.php b/tests/Composer/Test/DependencyResolver/DefaultPolicyTest.php index <HASH>..<HASH> 100644 --- a/tests/Composer/Test/DependencyResolver/DefaultPolicyTest.php +++ b/tests/Composer/Test/DependencyResolver/DefaultPolicyTest.php @@ -135,9 +135,8 @@ class DefaultPolicyTest extends \PHPUnit_Framework_TestCase $this->assertEquals($expected, $selected); } - public function testSelectNonReplacingFromSameRepo() + public function testPreferNonReplacingFromSameRepo() { - $this->markTestIncomplete(); $this->repo->addPackage($packageA = new MemoryPackage('A', '1.0')); $this->repo->addPackage($packageB = new MemoryPackage('B', '2.0')); @@ -147,7 +146,7 @@ class DefaultPolicyTest extends \PHPUnit_Framework_TestCase $this->pool->addRepository($this->repo); $literals = array(new Literal($packageA, true), new Literal($packageB, true)); - $expected = array(new Literal($packageA, true)); + $expected = array(new Literal($packageA, true), new Literal($packageB, true)); $selected = $this->policy->selectPreferedPackages($this->pool, $this->repoInstalled, $literals); diff --git a/tests/Composer/Test/DependencyResolver/SolverTest.php b/tests/Composer/Test/DependencyResolver/SolverTest.php index <HASH>..<HASH> 100644 --- a/tests/Composer/Test/DependencyResolver/SolverTest.php +++ b/tests/Composer/Test/DependencyResolver/SolverTest.php @@ -209,7 +209,7 @@ class SolverTest extends \PHPUnit_Framework_TestCase $this->request->install('A'); $this->checkSolverResult(array( - array('job' => 'install', 'package' => $packageB), + array('job' => 'install', 'package' => $packageA), )); }
Prefer original packages over replaced packages of same repository priority
mothership-ec_composer
train
69d7b6f47a30e24ebc3537473f7508b9f8d48fc3
diff --git a/src/Support/RulesInFields.php b/src/Support/RulesInFields.php index <HASH>..<HASH> 100644 --- a/src/Support/RulesInFields.php +++ b/src/Support/RulesInFields.php @@ -27,7 +27,7 @@ class RulesInFields } /** - * @return array<array> + * @return array<string,mixed> */ public function get(): array {
Adjust returned value to match what is returned from getRules
rebing_graphql-laravel
train
af0893c72ead794f5becd1d64824a45fc87bfddc
diff --git a/doc/source/conf.py b/doc/source/conf.py index <HASH>..<HASH> 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -34,7 +34,7 @@ print pyemma.__version__ extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', - 'sphinxcontrib.napoleon', + 'sphinx.ext.napoleon', 'sphinx.ext.mathjax', ] diff --git a/pyemma/coordinates/transform/tica.py b/pyemma/coordinates/transform/tica.py index <HASH>..<HASH> 100644 --- a/pyemma/coordinates/transform/tica.py +++ b/pyemma/coordinates/transform/tica.py @@ -271,7 +271,6 @@ class TICA(Transformer): if last_chunk: self._logger.info("finished calculation of Cov and Cov_tau.") - return True # finished! return False # not finished yet. @@ -316,11 +315,12 @@ class TICA(Transformer): Y = np.dot(X_meanfree, self.eigenvectors[:, 0:self._output_dimension]) return Y - #@property + #def sigma(self): # """ standard deviation (sigma) of the input features """ # return np.sqrt(np.diag(self.cov)) + @property def feature_correlation(self): r"""Instantaneous correlation matrix between input features and TICs @@ -340,4 +340,5 @@ class TICA(Transformer): feature_sigma = np.sqrt(np.diag(self.cov)) feat_corr = np.dot(self.cov,self.eigenvectors[:,:self._output_dimension])/feature_sigma[:, np.newaxis] - return feat_corr \ No newline at end of file + return feat_corr + \ No newline at end of file
changed the conf.py to include the sphinx.ext.napoleon and other minor changes
markovmodel_PyEMMA
train
a8fbe1c2a0ab6c46e0105a5329ae26fadec9f886
diff --git a/app/assets/javascripts/filterrific/filterrific-jquery.js b/app/assets/javascripts/filterrific/filterrific-jquery.js index <HASH>..<HASH> 100644 --- a/app/assets/javascripts/filterrific/filterrific-jquery.js +++ b/app/assets/javascripts/filterrific/filterrific-jquery.js @@ -21,6 +21,8 @@ if (typeof Filterrific === 'undefined') { Filterrific.submitFilterForm = function(){ var form = $(this).parents("form"), url = form.attr("action"); + // send before event + $(form).trigger('loadingFilterrificResults'); // turn on spinner $('.filterrific_spinner').show(); // Submit ajax request @@ -30,6 +32,8 @@ Filterrific.submitFilterForm = function(){ type: 'GET', dataType: 'script' }).done(function( msg ) { + // send after event + $(form).trigger('loadedFilterrificResults'); $('.filterrific_spinner').hide(); }); };
Trigger events before and after ajax call Events loadingFilterrificResults and loadedFilterrificResults will be triggered by the filterrific form.
jhund_filterrific
train
0e65971f16ee1684b6bfe397cc751cd341eb36ac
diff --git a/lib/jekyll-admin/server.rb b/lib/jekyll-admin/server.rb index <HASH>..<HASH> 100644 --- a/lib/jekyll-admin/server.rb +++ b/lib/jekyll-admin/server.rb @@ -74,6 +74,8 @@ module JekyllAdmin end body << "\n---\n\n" body << request_payload["raw_content"].to_s + body << "\n" unless body.end_with?("\n") + body end alias_method :page_body, :document_body
Ensure a blank line at end of document (#<I>) Currently, editing a page / document via the MarkdownEditor interface removes the blank line at the end of the file. This change ensures that a blank line is injected if it has been removed or doesn't exist otherwise.
jekyll_jekyll-admin
train
e2da4e084f50b4fe38f2b4caae816bf461c903ef
diff --git a/packages/react-dock/src/Dock.js b/packages/react-dock/src/Dock.js index <HASH>..<HASH> 100644 --- a/packages/react-dock/src/Dock.js +++ b/packages/react-dock/src/Dock.js @@ -244,7 +244,9 @@ export default class Dock extends Component { }; componentDidMount() { + window.addEventListener('touchend', this.handleMouseUp); window.addEventListener('mouseup', this.handleMouseUp); + window.addEventListener('touchmove', this.handleMouseMove); window.addEventListener('mousemove', this.handleMouseMove); window.addEventListener('resize', this.handleResize); @@ -254,7 +256,9 @@ export default class Dock extends Component { } componentWillUnmount() { + window.removeEventListener('touchend', this.handleMouseUp); window.removeEventListener('mouseup', this.handleMouseUp); + window.removeEventListener('touchmove', this.handleMouseMove); window.removeEventListener('mousemove', this.handleMouseMove); window.removeEventListener('resize', this.handleResize); } @@ -329,7 +333,11 @@ export default class Dock extends Component { <div style={dimStyles} onClick={this.handleDimClick} /> )} <div style={dockStyles}> - <div style={resizerStyles} onMouseDown={this.handleMouseDown} /> + <div + style={resizerStyles} + onMouseDown={this.handleMouseDown} + onTouchStart={this.handleMouseDown} + /> <div style={styles.dockContent}> {typeof children === 'function' ? children({ @@ -401,11 +409,18 @@ export default class Dock extends Component { handleMouseMove = (e) => { if (!this.state.isResizing || this.state.isWindowResizing) return; - e.preventDefault(); + + if (!e.touches) e.preventDefault(); const { position, fluid } = this.props; const { fullWidth, fullHeight, isControlled } = this.state; - const { clientX: x, clientY: y } = e; + let { clientX: x, clientY: y } = e; + + if (e.touches) { + x = e.touches[0].clientX; + y = e.touches[0].clientY; + } + let size; switch (position) {
feature(react-dock): add touch events (#<I>) * Touch events Enable to resize the dock on touch devices by handling touch events in addition to mouse events * Prettifying `yarn run prettify` command prettifying.
reduxjs_redux-devtools
train
b5e067e0862925ecbe2f68ff894ded3ed697363c
diff --git a/api/ParserService.js b/api/ParserService.js index <HASH>..<HASH> 100644 --- a/api/ParserService.js +++ b/api/ParserService.js @@ -36,10 +36,10 @@ var app = express.createServer(); app.use(express.bodyParser()); app.get('/', function(req, res){ - res.write('<body><strong>Welcome to the alpha test web service for the ' + - '<a href="http://www.mediawiki.org/wiki/Parsoid">Parsoid project<a>.</strong>'); + res.write('<body><h3>Welcome to the alpha test web service for the ' + + '<a href="http://www.mediawiki.org/wiki/Parsoid">Parsoid project<a>.</h3>'); res.write( '<p>Usage: <ul><li>GET /title for the DOM. ' + - 'Example: <a href="/Main_Page">Main Page</a>'); + 'Example: <strong><a href="/Main_Page">Main Page</a></strong>'); res.write('<li>POST a DOM as parameter "content" to /title for the wikitext</ul>'); res.write('<p>There are also some tools for experiments:' + '<ul><li><strong><a href="/_wikitext/">WikiText -&gt; HTML DOM form</a></strong></li>' + @@ -130,6 +130,7 @@ app.post(/\/_wikitext\/(.*)/, function(req, res){ */ app.get(/\/_roundtrip\/(.*)/, function(req, res){ env.pageName = req.params[0]; + env.wgScriptPath = '/_roundtrip'; if ( env.pageName === 'favicon.ico' ) { res.end( 'no favicon yet..' ); @@ -144,13 +145,13 @@ app.get(/\/_roundtrip\/(.*)/, function(req, res){ var parser = parserPipelineFactory.makePipeline( 'text/x-mediawiki/full' ); parser.on('document', function ( document ) { res.write('<html><head><style>del { background: #ff9191; text-decoration: none; } ins { background: #99ff7e; text-decoration: none }; </style></head><body>'); - var out = new WikitextSerializer({env: env}).serializeDOM( document.body ); - var patch = jsDiff.convertChangesToXML( jsDiff.diffWords( out, src ) ); res.write( '<h2>Wikitext parsed to HTML DOM</h2><hr>' ); res.write(document.body.innerHTML + '<hr>'); res.write( '<h2>HTML DOM converted back to Wikitext</h2><hr>' ); + var out = new WikitextSerializer({env: env}).serializeDOM( document.body ); res.write('<pre>' + htmlSpecialChars( out ) + '</pre><hr>'); res.write( '<h2>Diff between original Wikitext (green) and round-tripped wikitext (red)</h2><hr>' ); + var patch = jsDiff.convertChangesToXML( jsDiff.diffWords( out, src ) ); res.end( '<pre>' + patch); }); try { @@ -170,6 +171,7 @@ app.get(/\/_roundtrip\/(.*)/, function(req, res){ */ app.get(/\/(.*)/, function(req, res){ env.pageName = req.params[0]; + env.wgScriptPath = ''; if ( env.pageName === 'favicon.ico' ) { res.end( 'no favicon yet..'); return; @@ -197,6 +199,7 @@ app.get(/\/(.*)/, function(req, res){ */ app.post(/\/(.*)/, function(req, res){ env.pageName = req.params[0]; + env.wgScriptPath = ''; res.setHeader('Content-Type', 'text/x-mediawiki; charset=UTF-8'); var p = new html5.Parser(); p.parse( req.body.content );
Some more web service tweaks * Stay in round-trip mode in HTML DOM output * Return DOM, wikitext and diff as soon as they are available Change-Id: I7f8f<I>cfe8eed<I>a<I>d<I>d<I>c<I>cb6b1b
wikimedia_parsoid
train
75b403ed472ff8e94514d278583dde394ea3dfa5
diff --git a/remote.go b/remote.go index <HASH>..<HASH> 100644 --- a/remote.go +++ b/remote.go @@ -42,14 +42,6 @@ var remoteErrors = map[int]string{ 32: "invalid selector", } -const ( - // DefaultURLPrefix is the default HTTP endpoint that offers the WebDriver - // API. - DefaultURLPrefix = "http://127.0.0.1:4444/wd/hub" - // jsonContentType is JSON content type. - jsonContentType = "application/json" -) - type remoteWD struct { id, urlPrefix string capabilities Capabilities @@ -63,6 +55,9 @@ type remoteWD struct { // server. var HTTPClient = http.DefaultClient +// jsonContentType is JSON content type. +const jsonContentType = "application/json" + func newRequest(method string, url string, data []byte) (*http.Request, error) { request, err := http.NewRequest(method, url, bytes.NewBuffer(data)) if err != nil { @@ -184,6 +179,9 @@ func (wd *remoteWD) execute(method, url string, data []byte) (json.RawMessage, e return buf, nil } +// DefaultURLPrefix is the default HTTP endpoint that offers the WebDriver API. +const DefaultURLPrefix = "http://127.0.0.1:4444/wd/hub" + // NewRemote creates new remote client, this will also start a new session. // capabilities provides the desired capabilities. urlPrefix is the URL to the // Selenium server, must be prefixed with protocol (http, https, ...).
Rearrange where some package-level constants and variables are in remote.go
tebeka_selenium
train
e50eedea56e68f6525f9f011d09ebaea7c4c5d7e
diff --git a/foolbox/adversarial.py b/foolbox/adversarial.py index <HASH>..<HASH> 100644 --- a/foolbox/adversarial.py +++ b/foolbox/adversarial.py @@ -188,7 +188,7 @@ class Adversarial(object): """Returns True if a threshold is given and the currently best adversarial distance is smaller than the threshold.""" return self.__threshold is not None \ - and self.__best_distance <= self.__threshold + and self.__best_distance <= self.__threshold def __new_adversarial(self, x, predictions, in_bounds): x = x.copy() # to prevent accidental inplace changes @@ -228,7 +228,7 @@ class Adversarial(object): is_adversarial = self.__criterion.is_adversarial( predictions, self.__original_class) assert isinstance(is_adversarial, bool) or \ - isinstance(is_adversarial, np.bool_) + isinstance(is_adversarial, np.bool_) if is_adversarial: is_best, distance = self.__new_adversarial( x, predictions, in_bounds) @@ -404,7 +404,8 @@ class Adversarial(object): assert gradient.shape == x.shape return gradient - def forward_and_gradient_one(self, x=None, label=None, strict=True, return_details=False): + def forward_and_gradient_one(self, x=None, label=None, strict=True, + return_details=False): """Interface to model.forward_and_gradient_one for attacks. Parameters @@ -433,7 +434,9 @@ class Adversarial(object): self._total_prediction_calls += 1 self._total_gradient_calls += 1 predictions, gradient = self.__model.forward_and_gradient_one(x, label) - is_adversarial, is_best, distance = self.__is_adversarial(x, predictions, in_bounds) + is_adversarial, is_best, distance = self.__is_adversarial(x, + predictions, + in_bounds) assert predictions.ndim == 1 assert gradient.shape == x.shape @@ -442,6 +445,55 @@ class Adversarial(object): else: return predictions, gradient, is_adversarial + def forward_and_gradient(self, x, label=None, strict=True, + return_details=False): + """Interface to model.forward_and_gradient_one for attacks. + + Parameters + ---------- + x : `numpy.ndarray` + Multiple input with shape as expected by the model + (with the batch dimension). + label : `numpy.ndarray` + Labels used to calculate the loss that is differentiated. + Defaults to the original label. + strict : bool + Controls if the bounds for the pixel values should be checked. + + """ + assert self.has_gradient() + + if label is None: + label = np.ones(len(x), dtype=np.int) * self.__original_class + + in_bounds = self.in_bounds(x) + assert not strict or in_bounds + + self._total_prediction_calls += len(x) + self._total_gradient_calls += len(x) + predictions, gradients = self.__model.forward_and_gradient(x, label) + + assert predictions.ndim == 2 + assert gradients.shape == x.shape + + is_adversarials, is_bests, distances = [], [], [] + for single_x, prediction in zip(x, predictions): + is_adversarial, is_best, distance = self.__is_adversarial(single_x, + prediction, + in_bounds) + is_adversarials.append(is_adversarial) + is_bests.append(is_best) + distances.append(distance) + + is_adversarials = np.array(is_adversarials) + is_bests = np.array(is_bests) + distances = np.array(distances) + + if return_details: + return predictions, gradients, is_adversarials, is_bests, distances + else: + return predictions, gradients, is_adversarials + def backward_one(self, gradient, x=None, strict=True): """Interface to model.backward_one for attacks.
Add forward_and_gradient support to Adversarial
bethgelab_foolbox
train
40772cbbe5cd30b5f46bdbeb24a7844c7f952250
diff --git a/set.go b/set.go index <HASH>..<HASH> 100644 --- a/set.go +++ b/set.go @@ -270,10 +270,6 @@ type CompressedSetIter struct { // Next moves the iterator forward, returning true if there a KSUID was found, // or false if the iterator as reached the end of the set it was created from. func (it *CompressedSetIter) Next() bool { - if it.offset == len(it.content) { - return false - } - if it.seqlength != 0 { value := incr128(it.lastValue) it.KSUID = value.ksuid(it.timestamp) @@ -282,6 +278,10 @@ func (it *CompressedSetIter) Next() bool { return true } + if it.offset == len(it.content) { + return false + } + b := it.content[it.offset] it.offset++ diff --git a/set_test.go b/set_test.go index <HASH>..<HASH> 100644 --- a/set_test.go +++ b/set_test.go @@ -46,6 +46,10 @@ func TestCompressedSet(t *testing.T) { scenario: "building a compressed set with a single id repeated multiple times produces the id only once", function: testCompressedSetSingle, }, + { + scenario: "iterating over a compressed sequence returns the full sequence", + function: testCompressedSetSequence, + }, } for _, test := range tests { @@ -233,6 +237,30 @@ func testCompressedSetSingle(t *testing.T) { } } +func testCompressedSetSequence(t *testing.T) { + seq := Sequence{Seed: New()} + + ids := make([]KSUID, 5) + + for i := 0; i < 5; i++ { + ids[i], _ = seq.Next() + } + + iter := Compress(ids...).Iter() + + index := 0 + for iter.Next() { + if iter.KSUID != ids[index] { + t.Errorf("mismatched id at index %d: %s != %s", index, iter.KSUID, ids[index]) + } + index++ + } + + if index != 5 { + t.Errorf("Expected 5 ids, got %d", index) + } +} + func testCompressedSetNil(t *testing.T) { set := CompressedSet(nil)
Fix CompressedSetIter when set ends in a sequence (#<I>)
segmentio_ksuid
train
2d38ac96fb0fb2c48651f97d5e74176b847d942c
diff --git a/misc/log4j/src/main/java/org/openscience/cdk/tools/LoggingTool.java b/misc/log4j/src/main/java/org/openscience/cdk/tools/LoggingTool.java index <HASH>..<HASH> 100644 --- a/misc/log4j/src/main/java/org/openscience/cdk/tools/LoggingTool.java +++ b/misc/log4j/src/main/java/org/openscience/cdk/tools/LoggingTool.java @@ -177,7 +177,7 @@ public class LoggingTool implements ILoggingTool { if (System.getProperty("cdk.debug.stdout", "false").equals("true")) { toSTDOUT = true; } - } catch (Exception e) { + } catch (SecurityException e) { System.err.println("Could not read the System property used to determine " + "if logging should be turned on. So continuing without logging."); }
Catching the more specific SecurityException instead of the general Exception to avoid just swallowing all exceptions that might occur
cdk_cdk
train
71d5e4dd8d4f21dc526a4f6e59fde11ae8dcc57f
diff --git a/lib/acmesmith/command.rb b/lib/acmesmith/command.rb index <HASH>..<HASH> 100644 --- a/lib/acmesmith/command.rb +++ b/lib/acmesmith/command.rb @@ -68,10 +68,11 @@ module Acmesmith execute_post_issue_hooks(common_name) end - desc "post_issue_hooks COMMON_NAME", "Run all post-issueing hooks for common name. (for testing purposed)" + desc "post-issue-hooks COMMON_NAME", "Run all post-issueing hooks for common name. (for testing purpose)" def post_issue_hooks(common_name) execute_post_issue_hooks(common_name) end + map 'post-issue-hooks' => :post_issue_hooks desc "list [COMMON_NAME]", "list certificates or its versions" def list(common_name = nil) @@ -224,10 +225,8 @@ module Acmesmith def execute_post_issue_hooks(common_name) post_issues_hooks_for_common_name = config.post_issueing_hooks(common_name) - post_issues_hooks_for_common_name.each do | hook | - begin - hook.execute - end + post_issues_hooks_for_common_name.each do |hook| + hook.execute end end
pointless begin/end, rename command
sorah_acmesmith
train
1be995fe56e52bb1bdd5abf2578d28ac8a4db868
diff --git a/go/client/chat_cli_rendering.go b/go/client/chat_cli_rendering.go index <HASH>..<HASH> 100644 --- a/go/client/chat_cli_rendering.go +++ b/go/client/chat_cli_rendering.go @@ -109,7 +109,8 @@ func (v conversationListView) show(g *libkb.GlobalContext, myUsername string, sh unread = "" } if m.Message.ServerHeader.MessageType == chat1.MessageType_TEXT { - msg = &m + mCopy := m + msg = &mCopy } } }
quick fix for kbc list (#<I>)
keybase_client
train
8195a364b53bd2e61960a21aebb41b1cb8eb71f5
diff --git a/test/features/router/misc.js b/test/features/router/misc.js index <HASH>..<HASH> 100644 --- a/test/features/router/misc.js +++ b/test/features/router/misc.js @@ -61,4 +61,27 @@ describe('router - misc', function() { }); }); + it('should log the request ID for a 404', function() { + var reqId = '9c54ff673d634b31bb28d60aae1cb43c'; + var slice = server.config.logStream.slice(); + return preq.get({ + uri: server.config.bucketURL + '/foo-bucket/Foobar', + headers: { + 'X-Request-Id': reqId + } + }).then(function(res) { + slice.halt(); + throw new Error('Expected a 404, got ' + res.status); + }, function(err) { + slice.halt(); + assert.deepEqual(err.headers['x-request-id'], reqId, 'Returned request ID does not match the sent one'); + slice.get().forEach(function(line) { + var a = JSON.parse(line); + if(a.req || a.request_id) { + assert.deepEqual(a.request_id, reqId, 'Request ID mismatch'); + } + }); + }); + }); + });
Add a test controlling request IDs are output even for errors
wikimedia_restbase
train
66959f9e7ab5f1c89273eb7c458dda76dee9668b
diff --git a/spyderlib/widgets/dataframeeditor.py b/spyderlib/widgets/dataframeeditor.py index <HASH>..<HASH> 100644 --- a/spyderlib/widgets/dataframeeditor.py +++ b/spyderlib/widgets/dataframeeditor.py @@ -473,7 +473,7 @@ class DataFrameEditor(QDialog): self.setLayout(self.layout) self.setWindowIcon(ima.icon('arredit')) if title: - title = to_text_string(title) # in case title is not a string + title = to_text_string(title) + " - %s" % data.__class__.__name__ else: title = _("%s editor") % data.__class__.__name__ if isinstance(data, TimeSeries): diff --git a/spyderlib/widgets/dicteditor.py b/spyderlib/widgets/dicteditor.py index <HASH>..<HASH> 100644 --- a/spyderlib/widgets/dicteditor.py +++ b/spyderlib/widgets/dicteditor.py @@ -503,8 +503,8 @@ class DictDelegate(QItemDelegate): elif isinstance(value, (DataFrame, TimeSeries))\ and DataFrame is not FakeObject: editor = DataFrameEditor() - if not editor.setup_and_check(value): - return + if not editor.setup_and_check(value, title=key): + return self.create_dialog(editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None
Variable Explorer: Add object name to Series and DataFrame editors Fixes #<I>
spyder-ide_spyder
train
2ab19a75836271696abae600bdac12b1e4282b23
diff --git a/lib/riemann/client.rb b/lib/riemann/client.rb index <HASH>..<HASH> 100644 --- a/lib/riemann/client.rb +++ b/lib/riemann/client.rb @@ -70,6 +70,11 @@ class Riemann::Client (response.states || []) end + def connect + # NOTE: connections are made automatically on send + puts "Riemann client#connect is deprecated" + end + # Close both UDP and TCP sockets. def close @udp.close diff --git a/lib/riemann/client/tcp.rb b/lib/riemann/client/tcp.rb index <HASH>..<HASH> 100644 --- a/lib/riemann/client/tcp.rb +++ b/lib/riemann/client/tcp.rb @@ -46,7 +46,7 @@ module Riemann def connected? @locket.synchronize do - (@socket.nil? || @socket.closed?) ? false : true + !@socket.nil? && !@socket.closed? end end diff --git a/lib/riemann/client/udp.rb b/lib/riemann/client/udp.rb index <HASH>..<HASH> 100644 --- a/lib/riemann/client/udp.rb +++ b/lib/riemann/client/udp.rb @@ -9,7 +9,6 @@ module Riemann @host = opts[:host] || HOST @port = opts[:port] || PORT @max_size = opts[:max_size] || MAX_SIZE - @locket = Mutex.new end def connect @@ -17,16 +16,12 @@ module Riemann end def close - # there is no socket.close for UDP - # @locket.synchronize do - # @socket.close - # end + @socket.close if connected? + @socket = nil end def connected? - @locket.synchronize do - @socket.nil? ? false : true - end + @socket.nil? ? false : true end # Read a message from a stream @@ -53,19 +48,13 @@ module Riemann # Yields a connection in the block. def with_connection tries = 0 - - @locket.synchronize do - begin - tries += 1 - yield(@socket || connect) - rescue IOError, Errno::EPIPE, Errno::ECONNREFUSED, Errno::ECONNRESET, InvalidResponse - if tries > 3 - @socket = nil - raise - else - connect and retry - end - end + begin + tries += 1 + yield(@socket || connect) + rescue IOError, Errno::EPIPE, Errno::ECONNREFUSED, Errno::ECONNRESET, InvalidResponse, SocketError + close # force a reconnect + raise if tries > 3 + retry end end end diff --git a/spec/client.rb b/spec/client.rb index <HASH>..<HASH> 100755 --- a/spec/client.rb +++ b/spec/client.rb @@ -9,6 +9,7 @@ Bacon.summary_on_exit include Riemann +INACTIVITY_TIME = 5 def roundtrip_metric(m) @client_with_transport << { @@ -161,28 +162,28 @@ describe "Riemann::Client (TCP transport)" do should 'survive inactivity' do @client_with_transport.<<({ :state => 'warning', - :service => 'test', + :service => 'survive inactivity', }) - sleep 5 + sleep INACTIVITY_TIME @client_with_transport.<<({ :state => 'warning', - :service => 'test', + :service => 'survive inactivity', }).ok.should.be.true end should 'survive local close' do @client_with_transport.<<({ :state => 'warning', - :service => 'test', + :service => 'survive local close', }).ok.should.be.true @client.close @client_with_transport.<<({ :state => 'warning', - :service => 'test', + :service => 'survive local close', }).ok.should.be.true end end @@ -210,33 +211,33 @@ describe "Riemann::Client (UDP transport)" do should 'survive inactivity' do @client_with_transport.<<({ :state => 'warning', - :service => 'test', + :service => 'survive UDP inactivity', }) - @client['service = "test"'].first.state.should.equal 'warning' + @client['service = "survive UDP inactivity"'].first.state.should.equal 'warning' - sleep 5 + sleep INACTIVITY_TIME @client_with_transport.<<({ :state => 'ok', - :service => 'test', + :service => 'survive UDP inactivity', }) - @client['service = "test"'].first.state.should.equal 'ok' + @client['service = "survive UDP inactivity"'].first.state.should.equal 'ok' end should 'survive local close' do @client_with_transport.<<({ :state => 'warning', - :service => 'test', + :service => 'survive UDP local close', }) - @client['service = "test"'].first.state.should.equal 'warning' + @client['service = "survive UDP local close"'].first.state.should.equal 'warning' @client.close @client_with_transport.<<({ :state => 'ok', - :service => 'test', + :service => 'survive UDP local close', }) - @client['service = "test"'].first.state.should.equal 'ok' + @client['service = "survive UDP local close"'].first.state.should.equal 'ok' end should "raise Riemann::Client::Unsupported exception on query" do
Fixes and cleanup as suggested by @eric See <URL>
riemann_riemann-ruby-client
train
ab3da939096a677b9bbabc17fdc974a74e60f73e
diff --git a/lib/www_applet.rb b/lib/www_applet.rb index <HASH>..<HASH> 100644 --- a/lib/www_applet.rb +++ b/lib/www_applet.rb @@ -33,6 +33,8 @@ class WWW_Applet < BasicObject INVALID_CSS_CLASS_CHARS = /[^a-z0-9\#\:\_\-\.\ ]/i INVALID_CSS_PROP_NAME_CHARS = /[^a-z0-9-]/i + HASH = '#' + DOT = '.' BANG = '!' NEW_LINE = "\n" SPACE = ' ' @@ -420,34 +422,41 @@ class WWW_Applet < BasicObject classes = [] while i > -1 - curr = @tag_arr[i] - id = dom_id(curr) - css_class = if start == i && str_class - str_class - else - curr[:attrs][:class].first - end + e = @tag_arr[i] + id = dom_id e + first_class = e[:attrs][:class].first + + if id + id_given = true + if str_class + classes.unshift( + str_class.is_a?(::Symbol) ? + "##{id}.#{str_class}" : + "##{id}#{str_class}" + ) + else + classes.unshift "##{id}" + end - temp_id = case - when id && css_class - "##{id}.#{css_class}" - when id - "##{id}" - when css_class - "#{curr[:tag]}.#{css_class}" - else - curr[:tag] - end + else # no id given + if str_class + classes.unshift( + str_class.is_a?(::Symbol) ? + "#{e[:tag]}.#{str_class}" : + "#{e[:tag]}#{str_class}" + ) + elsif first_class + classes.unshift "#{e[:tag]}.#{first_class}" + else + if e[:tag] != :body + classes.unshift "#{e[:tag]}" + end + end # if first_class - if temp_id == :body && !classes.empty? - # do nothing because - # we do not want 'body tag.class tag.class' - else - classes.unshift temp_id - end + end # if id break if id_given - i = @tag_arr[i][:parent_index] + i = e[:parent_index] break if !i || i == @body[:tag_index] end diff --git a/specs/as_ruby/0012-html_with_inner_style.rb b/specs/as_ruby/0012-html_with_inner_style.rb index <HASH>..<HASH> 100644 --- a/specs/as_ruby/0012-html_with_inner_style.rb +++ b/specs/as_ruby/0012-html_with_inner_style.rb @@ -43,6 +43,22 @@ describe "HTML with inner style" do end end + it "does not include parents when element has id" do + target :style, <<-EOF + #my_box div.box { + border: 15px; + } + EOF + + actual do + div.^(:top) { + div.*(:my_box) { + div.^(:box) { border '15px' } + } + } + end + end + end # === describe
Fixed: css psuedo classes with :on
da99_www_app
train
0db509d0b5413d80658a088f87da82da8c46389c
diff --git a/bin/now-deploy.js b/bin/now-deploy.js index <HASH>..<HASH> 100755 --- a/bin/now-deploy.js +++ b/bin/now-deploy.js @@ -320,19 +320,19 @@ async function sync(token) { } } else if (hasPackage) { if (debug) { - console.log('[debug] `package.json` found, assuming `deploymentType` = `npm`') + console.log('> [debug] `package.json` found, assuming `deploymentType` = `npm`') } deploymentType = 'npm' } else if (hasDockerfile) { if (debug) { - console.log('[debug] `Dockerfile` found, assuming `deploymentType` = `docker`') + console.log('> [debug] `Dockerfile` found, assuming `deploymentType` = `docker`') } deploymentType = 'docker' } else { if (debug) { - console.log('[debug] No manifest files found, assuming static deployment') + console.log('> [debug] No manifest files found, assuming static deployment') } isStatic = true
Missing greather-than-sign added
zeit_now-cli
train
f5bc9b1dee0f6b6312b1217b66ed33aa94ceff84
diff --git a/closure/goog/proto2/fielddescriptor.js b/closure/goog/proto2/fielddescriptor.js index <HASH>..<HASH> 100644 --- a/closure/goog/proto2/fielddescriptor.js +++ b/closure/goog/proto2/fielddescriptor.js @@ -96,8 +96,8 @@ goog.proto2.FieldDescriptor = function(messageType, tag, metadata) { /** * Is it permissible on deserialization to convert between numbers and - * well-formed strings? Is true for 64-bit integral field types, false for - * all other field types. + * well-formed strings? Is true for 64-bit integral field types and float and + * double types, false for all other field types. * @private {boolean} */ this.deserializationConversionPermitted_ = false; @@ -108,6 +108,8 @@ goog.proto2.FieldDescriptor = function(messageType, tag, metadata) { case goog.proto2.FieldDescriptor.FieldType.FIXED64: case goog.proto2.FieldDescriptor.FieldType.SFIXED64: case goog.proto2.FieldDescriptor.FieldType.SINT64: + case goog.proto2.FieldDescriptor.FieldType.FLOAT: + case goog.proto2.FieldDescriptor.FieldType.DOUBLE: this.deserializationConversionPermitted_ = true; break; } diff --git a/closure/goog/proto2/objectserializer_test.js b/closure/goog/proto2/objectserializer_test.js index <HASH>..<HASH> 100644 --- a/closure/goog/proto2/objectserializer_test.js +++ b/closure/goog/proto2/objectserializer_test.js @@ -446,6 +446,56 @@ function testDeserializationNumbersOrStrings() { assertArrayEquals(['5300', '5301'], message.repeatedInt64StringArray()); } +function testSerializationSpecialFloatDoubleValues() { + // NaN, Infinity and -Infinity should get serialized as strings. + var message = new proto2.TestAllTypes(); + message.setOptionalFloat(Infinity); + message.setOptionalDouble(-Infinity); + message.addRepeatedFloat(Infinity); + message.addRepeatedFloat(-Infinity); + message.addRepeatedFloat(NaN); + message.addRepeatedDouble(Infinity); + message.addRepeatedDouble(-Infinity); + message.addRepeatedDouble(NaN); + var simplified = new goog.proto2.ObjectSerializer().serialize(message); + + // Assert that everything serialized properly. + assertEquals('Infinity', simplified[11]); + assertEquals('-Infinity', simplified[12]); + assertEquals('Infinity', simplified[41][0]); + assertEquals('-Infinity', simplified[41][1]); + assertEquals('NaN', simplified[41][2]); + assertEquals('Infinity', simplified[42][0]); + assertEquals('-Infinity', simplified[42][1]); + assertEquals('NaN', simplified[42][2]); +} + +function testDeserializationSpecialFloatDoubleValues() { + // NaN, Infinity and -Infinity values should be de-serialized from their + // string representation. + var simplified = { + 41: ['Infinity', '-Infinity', 'NaN'], + 42: ['Infinity', '-Infinity', 'NaN'] + }; + + var serializer = new goog.proto2.ObjectSerializer(); + + var message = serializer.deserialize( + proto2.TestAllTypes.getDescriptor(), simplified); + + assertNotNull(message); + + var floatArray = message.repeatedFloatArray(); + assertEquals(Infinity, floatArray[0]); + assertEquals(-Infinity, floatArray[1]); + assertTrue(isNaN(floatArray[2])); + + var doubleArray = message.repeatedDoubleArray(); + assertEquals(Infinity, doubleArray[0]); + assertEquals(-Infinity, doubleArray[1]); + assertTrue(isNaN(doubleArray[2])); +} + function testDeserializationConversionProhibited() { // 64-bit types may have been serialized as numbers or strings. // But 32-bit types must be serialized as numbers. diff --git a/closure/goog/proto2/serializer.js b/closure/goog/proto2/serializer.js index <HASH>..<HASH> 100644 --- a/closure/goog/proto2/serializer.js +++ b/closure/goog/proto2/serializer.js @@ -52,9 +52,10 @@ goog.proto2.Serializer.prototype.serialize = goog.abstractMethod; /** - * Returns the serialized form of the given value for the given field - * if the field is a Message or Group and returns the value unchanged - * otherwise. + * Returns the serialized form of the given value for the given field if the + * field is a Message or Group and returns the value unchanged otherwise, except + * for Infinity, -Infinity and NaN numerical values which are converted to + * string representation. * * @param {goog.proto2.FieldDescriptor} field The field from which this * value came. @@ -67,6 +68,8 @@ goog.proto2.Serializer.prototype.serialize = goog.abstractMethod; goog.proto2.Serializer.prototype.getSerializedValue = function(field, value) { if (field.isCompositeType()) { return this.serialize(/** @type {goog.proto2.Message} */ (value)); + } else if (goog.isNumber(value) && !isFinite(value)) { + return value.toString(); } else { return value; } @@ -158,8 +161,14 @@ goog.proto2.Serializer.prototype.getDeserializedValue = function(field, value) { return String(value); } } else if (nativeType === Number) { - // JSON strings are sometimes used for large integer numeric values. + // JSON strings are sometimes used for large integer numeric values, as well + // as Infinity, -Infinity and NaN. if (goog.isString(value)) { + // Handle +/- Infinity and NaN values. + if (value === 'Infinity' || value === '-Infinity' || value === 'NaN') { + return Number(value); + } + // Validate the string. If the string is not an integral number, we would // rather have an assertion or error in the caller than a mysterious NaN // value.
Deserializing 'Infinity', '-Infinity' and 'NaN' strings as valid numerical values. ------------- Created by MOE: <URL>
google_closure-library
train
0b4155f37ce223f0c5098dd49cec87044699d663
diff --git a/qa_tests/risk/event_based/case_3/test.py b/qa_tests/risk/event_based/case_3/test.py index <HASH>..<HASH> 100644 --- a/qa_tests/risk/event_based/case_3/test.py +++ b/qa_tests/risk/event_based/case_3/test.py @@ -23,7 +23,8 @@ from qa_tests import risk from openquake.engine.db import models -# FIXME(lp). This is no more than a smoke test +# TODO(lp). This is a regression test that checks for the presence of +# the results class EventBasedRiskCase3TestCase(risk.End2EndRiskQATestCase): hazard_cfg = os.path.join(os.path.dirname(__file__), 'job_haz.ini') risk_cfg = os.path.join(os.path.dirname(__file__), 'job_risk.ini') @@ -44,11 +45,7 @@ class EventBasedRiskCase3TestCase(risk.End2EndRiskQATestCase): fractions = [fractions for fractions in loss_fraction.iteritems()] - return [[len(loss_fraction.total_fractions())], - [node[0] for node in fractions], - [len(node[1]) for node in fractions]] + return [node[0] for node in fractions] def expected_data(self): - return [2, - [[80.838823, 29.386172], [80.988823, 29.611172]], - [1, 1]] + return [80.838823, 29.386172], [80.988823, 29.611172]
removed unreproducible data from qa tests
gem_oq-engine
train
fd1da49d9819d5099c5b9def5398a8c7ce0dd8f8
diff --git a/reader.go b/reader.go index <HASH>..<HASH> 100644 --- a/reader.go +++ b/reader.go @@ -157,11 +157,11 @@ func (q *Reader) SetLogger(logger *log.Logger, lvl LogLevel) { q.logLvl = lvl } -// ConnectionMaxInFlight calculates the per-connection max-in-flight count. +// perConnMaxInFlight calculates the per-connection max-in-flight count. // // This may change dynamically based on the number of connections to nsqd the Reader // is responsible for. -func (q *Reader) ConnectionMaxInFlight() int64 { +func (q *Reader) perConnMaxInFlight() int64 { b := float64(q.maxInFlight()) s := b / float64(len(q.conns())) return int64(math.Min(math.Max(1, s), b)) @@ -550,7 +550,7 @@ func (q *Reader) rdyLoop() { // send ready immediately remain := c.RDY() lastRdyCount := c.LastRDY() - count := q.ConnectionMaxInFlight() + count := q.perConnMaxInFlight() // refill when at 1, or at 25%, or if connections have changed and we have too many RDY if remain <= 1 || remain < (lastRdyCount/4) || (count > 0 && count < remain) { q.log(LogLevelDebug, "(%s) sending RDY %d (%d remain from last RDY %d)", @@ -590,7 +590,7 @@ func (q *Reader) rdyLoop() { // exit backoff if backoffCounter == 0 && backoffUpdated { - count := q.ConnectionMaxInFlight() + count := q.perConnMaxInFlight() q.log(LogLevelWarning, "exiting backoff, returning all to RDY %d", count) for _, c := range q.conns() { q.updateRDY(c, count)
reader: drop SetMaxInFlight; un-export ConnectionMaxInFlight
nsqio_go-nsq
train
96578f42a2592415d132caaf59e784a8e5d1f9ce
diff --git a/src/main/java/graphql/schema/idl/SchemaGenerator.java b/src/main/java/graphql/schema/idl/SchemaGenerator.java index <HASH>..<HASH> 100644 --- a/src/main/java/graphql/schema/idl/SchemaGenerator.java +++ b/src/main/java/graphql/schema/idl/SchemaGenerator.java @@ -22,6 +22,7 @@ import graphql.language.StringValue; import graphql.language.Type; import graphql.language.TypeDefinition; import graphql.language.TypeExtensionDefinition; +import graphql.language.TypeName; import graphql.language.UnionTypeDefinition; import graphql.language.Value; import graphql.schema.DataFetcher; @@ -134,9 +135,7 @@ public class SchemaGenerator { * * @param typeRegistry this can be obtained via {@link SchemaCompiler#compile(String)} * @param wiring this can be built using {@link RuntimeWiring#newRuntimeWiring()} - * * @return an executable schema - * * @throws SchemaProblem if there are problems in assembling a schema such as missing type resolvers or no operations defined */ public GraphQLSchema makeExecutableSchema(TypeDefinitionRegistry typeRegistry, RuntimeWiring wiring) throws SchemaProblem { @@ -185,7 +184,6 @@ public class SchemaGenerator { * * @param buildCtx the context we need to work out what we are doing * @param rawType the type to be built - * * @return an output type */ @SuppressWarnings("unchecked") @@ -333,9 +331,7 @@ public class SchemaGenerator { builder.typeResolver(getTypeResolver(buildCtx, typeDefinition.getName())); typeDefinition.getMemberTypes().forEach(mt -> { - TypeDefinition memberTypeDef = buildCtx.getTypeDefinition(mt); - GraphQLObjectType objectType = buildObjectType(buildCtx, (ObjectTypeDefinition) memberTypeDef); - builder.possibleType(objectType); + builder.possibleType(new GraphQLTypeReference(((TypeName) mt).getName())); }); return builder.build(); }
fix union type generation (test missing)
graphql-java_graphql-java
train
a89e7741b7db3310f0cf4590aa28cd5425e7e622
diff --git a/requirements.txt b/requirements.txt index <HASH>..<HASH> 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,3 +3,4 @@ jinja2>=2.2 requests>=2.10.0 six xmltodict +lxml diff --git a/rtcclient/client.py b/rtcclient/client.py index <HASH>..<HASH> 100644 --- a/rtcclient/client.py +++ b/rtcclient/client.py @@ -1070,7 +1070,7 @@ class RTCClient(RTCBase): wi_url_post = "/".join([self.url, "oslc/contexts", projectarea_id, - "workitems/%s" % itemtype.identifier]) + "workitems/%s" % itemtype.identifier.lower()]) return self._createWorkitem(wi_url_post, wi_raw) def copyWorkitem(self, copied_from, title=None, description=None, @@ -1099,13 +1099,13 @@ class RTCClient(RTCBase): if prefix is not None: description = prefix + description - self.log.info("Start to create a new <Workitem>, copied from ", + self.log.info("Start to create a new <Workitem>, copied from " "<Workitem %s>", copied_from) wi_url_post = "/".join([self.url, "oslc/contexts/%s" % copied_wi.contextId, "workitems", - "%s" % copied_wi.type.split("/")[-1]]) + "%s" % copied_wi.type.lower()]) wi_raw = self.templater.renderFromWorkitem(copied_from, keep=True, encoding="UTF-8", diff --git a/rtcclient/template.py b/rtcclient/template.py index <HASH>..<HASH> 100644 --- a/rtcclient/template.py +++ b/rtcclient/template.py @@ -7,6 +7,7 @@ import jinja2.meta from rtcclient import exception from rtcclient import _search_path import six +from rtcclient.utils import remove_empty_elements class Templater(RTCBase): @@ -129,7 +130,9 @@ class Templater(RTCBase): template_folder=None, keep=keep, encoding=encoding)) - return temp.render(**kwargs) + + rendered_data = temp.render(**kwargs) + return remove_empty_elements(rendered_data) def listFields(self, template): """List all the attributes to be rendered from the template file @@ -328,9 +331,10 @@ class Templater(RTCBase): ("rtc_cm:filedAgainst", "{{ filedAgainst }}")] for field in replace_fields: try: - wk_raw_data[field[0]]["@rdf:resource"] = field[1] - self.log.debug("Successfully replace field [%s] with [%s]", - field[0], field[1]) + if field[0] in wk_raw_data: + wk_raw_data[field[0]]["@rdf:resource"] = field[1] + self.log.debug("Successfully replace field [%s] with [%s]", + field[0], field[1]) except: self.log.warning("Cannot replace field [%s]", field[0]) continue @@ -340,8 +344,7 @@ class Templater(RTCBase): template_file_path) return xmltodict.unparse(raw_data, output=output, - encoding=encoding, - pretty=True) + encoding=encoding) def _remove_long_fields(self, wk_raw_data): """Remove long fields: These fields are can only customized after diff --git a/rtcclient/utils.py b/rtcclient/utils.py index <HASH>..<HASH> 100644 --- a/rtcclient/utils.py +++ b/rtcclient/utils.py @@ -4,6 +4,7 @@ from xml.parsers.expat import ExpatError import xmltodict from rtcclient.exception import RTCException, BadValue import six +from lxml import etree def setup_basic_logging(): @@ -62,3 +63,12 @@ def capitalize(keyword): return keyword.capitalize() else: raise BadValue("Input value %s is not string type" % keyword) + + +def remove_empty_elements(docs): + root = etree.fromstring(str(docs)) + for element in root.xpath("//*[not(node())]"): + if "rdf:resource" not in etree.tostring(element): + element.getparent().remove(element) + + return etree.tostring(root)
fix issue #<I>: workitem creation bug
dixudx_rtcclient
train
f00e72825c54b15217fbe179d9bb8fed48e2de7e
diff --git a/WrightTools/data/_data.py b/WrightTools/data/_data.py index <HASH>..<HASH> 100644 --- a/WrightTools/data/_data.py +++ b/WrightTools/data/_data.py @@ -457,30 +457,29 @@ class Data(Group): new_shape = list(self[channel].shape) new_shape[axis_index] = 1 + rtype = self[channel].dtype + if method in ["ave", "average", "mean", "int", "integrate"]: + rtype = np.result_type(self[channel].dtype, float) new = self.create_channel( "{}_{}_{}".format(channel, axis, method), - shape=new_shape, + values=np.empty(new_shape, dtype=rtype), units=self[channel].units, ) channel = self[channel] if method == "sum": - res = np.nansum(channel[:], axis=axis_index) - res.shape = new_shape + res = np.nansum(channel[:], axis=axis_index, keepdims=True) new[:] = res elif method in ["max", "maximum"]: - res = np.nanmax(channel[:], axis=axis_index) - res.shape = new_shape + res = np.nanmax(channel[:], axis=axis_index, keepdims=True) new[:] = res elif method in ["min", "minimum"]: - res = np.nanmin(channel[:], axis=axis_index) - res.shape = new_shape + res = np.nanmin(channel[:], axis=axis_index, keepdims=True) new[:] = res elif method in ["ave", "average", "mean"]: - res = np.nanmean(channel[:], axis=axis_index) - res.shape = new_shape + res = np.nanmean(channel[:], axis=axis_index, keepdims=True) new[:] = res elif method in ["int", "integrate"]: res = np.trapz(y=channel[:], x=self._axes[axis_index][:], axis=axis_index)
Ensure proper dtype support in collapse (#<I>) * Ensure proper dtype support in collapse Also ensures that actions which would result in single numbers keep their dimensionality * Trapz doesn't accept keepdims * Ensure average/integrate is at least float, but preserve if float<I> or complex
wright-group_WrightTools
train
eb2b81c766a6f9bf3c27ae0a494ae82956fb8555
diff --git a/railties/lib/commands/dbconsole.rb b/railties/lib/commands/dbconsole.rb index <HASH>..<HASH> 100644 --- a/railties/lib/commands/dbconsole.rb +++ b/railties/lib/commands/dbconsole.rb @@ -47,7 +47,7 @@ when "mysql" args << config['database'] - exec(find_cmd('mysql5', 'mysql'), *args) + exec(find_cmd('mysql', 'mysql5'), *args) when "postgresql" ENV['PGUSER'] = config["username"] if config["username"]
Reverse the priority of the mysql commands in dbconsole
rails_rails
train
be8738af08bee64ab72d1b61f3723bf6a390d6b9
diff --git a/src/com/google/javascript/refactoring/examples/refasterjs/set_element_href.js b/src/com/google/javascript/refactoring/examples/refasterjs/set_element_href.js index <HASH>..<HASH> 100644 --- a/src/com/google/javascript/refactoring/examples/refasterjs/set_element_href.js +++ b/src/com/google/javascript/refactoring/examples/refasterjs/set_element_href.js @@ -126,7 +126,7 @@ function after_setElementDefiniteHrefOptional(anchor, url) { * +require {goog.dom.asserts} * +require {goog.dom.safe} * @param {!Element|null|undefined} anchor - * @param {!string|null|undefined} url + * @param {?} url */ function before_setElementHrefBothOptional(anchor, url) { anchor.href = url; @@ -135,7 +135,7 @@ function before_setElementHrefBothOptional(anchor, url) { /** * @param {!Element|null|undefined} anchor - * @param {!string|null|undefined} url + * @param {?} url */ function after_setElementHrefBothOptional(anchor, url) { goog.dom.safe.setAnchorHref( diff --git a/src/com/google/javascript/refactoring/examples/refasterjs/set_location_href.js b/src/com/google/javascript/refactoring/examples/refasterjs/set_location_href.js index <HASH>..<HASH> 100644 --- a/src/com/google/javascript/refactoring/examples/refasterjs/set_location_href.js +++ b/src/com/google/javascript/refactoring/examples/refasterjs/set_location_href.js @@ -27,6 +27,7 @@ * otherwise be present if the URL is derived from untrusted input. */ +goog.require('goog.asserts'); goog.require('goog.dom.safe'); /** @@ -56,3 +57,25 @@ function before_setLocationHref(loc, url) { function after_setLocationHref(loc, url) { goog.dom.safe.setLocationHref(loc, url); } +/** + * Replaces writes to Location.property.href with a call to the corresponding + * goog.dom.safe.setLocationHref wrapper. + * +require {goog.asserts} + * +require {goog.dom.safe} + * @param {!Location} loc The location object. + * @param {?} url The url. + */ +function before_setLocationUntypedHref(loc, url) { + loc.href = url; +} + +/** + * @param {!Location} loc The location object. + * @param {?} url The url. + */ +function after_setLocationUntypedHref(loc, url) { + // TODO(bangert): add test once we have go/api-prohibition-design + // (which will re-do the test infrastructure for this). + // TODO(bangert): add tests for nullable locations + goog.dom.safe.setLocationHref(loc, goog.asserts.assertString(url)); +} diff --git a/src/com/google/javascript/refactoring/examples/refasterjs/set_window_location.js b/src/com/google/javascript/refactoring/examples/refasterjs/set_window_location.js index <HASH>..<HASH> 100644 --- a/src/com/google/javascript/refactoring/examples/refasterjs/set_window_location.js +++ b/src/com/google/javascript/refactoring/examples/refasterjs/set_window_location.js @@ -27,6 +27,7 @@ * otherwise be present if the URL is derived from untrusted input. */ +goog.require('goog.asserts'); goog.require('goog.dom.safe'); /** @@ -42,7 +43,7 @@ function do_not_change_setLocationStringLiteral(thing1, string_literal_thing2) { * Replaces writes to Window.property.location with a call to the corresponding * goog.dom.safe.setLocationHref wrapper. * +require {goog.dom.safe} - * @param {!Window} win The window object. + * @param {?Window} win The window object. * @param {string} url The url. */ function before_setWindowLocation(win, url) { @@ -50,9 +51,28 @@ function before_setWindowLocation(win, url) { } /** - * @param {!Window} win The window object. + * @param {?Window} win The window object. * @param {string} url The url. */ function after_setWindowLocation(win, url) { goog.dom.safe.setLocationHref(win.location, url); } + +/** + * Replaces writes to Window.property.location with a call to the corresponding + * goog.dom.safe.setLocationHref wrapper. + * +require {goog.dom.safe} + * @param {?Window} win The window object. + * @param {?} url The url. + */ +function before_setWindowLocationUntyped(win, url) { + win.location = url; +} + +/** + * @param {?Window} win The window object. + * @param {?} url The url. + */ +function after_setWindowLocationUntyped(win, url) { + goog.dom.safe.setLocationHref(win.location, goog.asserts.assertString(url)); +}
Extend refactoring examples for DOM XSS sinks to also catch implicit string coercions. ------------- Created by MOE: <URL>
google_closure-compiler
train
eb484812b21fd7e6fb2f210e368b6edad3c6cf73
diff --git a/internal/goofys_test.go b/internal/goofys_test.go index <HASH>..<HASH> 100644 --- a/internal/goofys_test.go +++ b/internal/goofys_test.go @@ -634,7 +634,10 @@ func (s *GoofysTest) TestCreateFiles(t *C) { resp, err = s.cloud.GetBlob(&GetBlobInput{Key: fileName}) t.Assert(err, IsNil) - t.Assert(resp.HeadBlobOutput.Size, Equals, uint64(1)) + // ADLv1 doesn't return size when we do a GET + if _, adlv1 := s.cloud.(*ADLv1); !adlv1 { + t.Assert(resp.HeadBlobOutput.Size, Equals, uint64(1)) + } defer resp.Body.Close() }
don't test that GET returns payload size for ADLv1 it doesn't support it despite what the documentation says
kahing_goofys
train
f96ec5c22ed54ec2ca62023a254aa756a17c37e5
diff --git a/views/js/qtiCreator/plugins/panel/outcomeEditor.js b/views/js/qtiCreator/plugins/panel/outcomeEditor.js index <HASH>..<HASH> 100644 --- a/views/js/qtiCreator/plugins/panel/outcomeEditor.js +++ b/views/js/qtiCreator/plugins/panel/outcomeEditor.js @@ -68,7 +68,10 @@ define([ */ function getRpUsedVariables(item) { const rpXml = xmlRenderer.render(item.responseProcessing); - const variables = [ 'SCORE', 'MAXSCORE' ]; //score and max score are always used, even in template based response processing + const variables = [ ]; //score and max score are always used, even in template based response processing + if (rpXml !== '') { + variables.push('SCORE', 'MAXSCORE'); + } const $rp = $(rpXml); $rp.find('variable,setOutcomeValue').each(function () {
fix: make SCORE and MAXSCORE editable when no response processing chosen
oat-sa_extension-tao-itemqti
train
5aa3762c0998c6a2c4da6fff10b549fc69ae8318
diff --git a/tests/Composer/Test/Script/EventDispatcherTest.php b/tests/Composer/Test/Script/EventDispatcherTest.php index <HASH>..<HASH> 100644 --- a/tests/Composer/Test/Script/EventDispatcherTest.php +++ b/tests/Composer/Test/Script/EventDispatcherTest.php @@ -35,10 +35,12 @@ class EventDispatcherTest extends TestCase $dispatcher->dispatchCommandEvent("post-install-cmd"); } - public function testDispatcherCanExecuteCommandLineScripts() + /** + * @dataProvider getValidCommands + * @param string $command + */ + public function testDispatcherCanExecuteSingleCommandLineScript($command) { - $eventCliCommand = 'phpunit'; - $process = $this->getMock('Composer\Util\ProcessExecutor'); $dispatcher = $this->getMockBuilder('Composer\Script\EventDispatcher') ->setConstructorArgs(array( @@ -49,14 +51,14 @@ class EventDispatcherTest extends TestCase ->setMethods(array('getListeners')) ->getMock(); - $listeners = array($eventCliCommand); + $listener = array($command); $dispatcher->expects($this->atLeastOnce()) ->method('getListeners') - ->will($this->returnValue($listeners)); + ->will($this->returnValue($listener)); $process->expects($this->once()) ->method('execute') - ->with($eventCliCommand); + ->with($command); $dispatcher->dispatchCommandEvent("post-install-cmd"); } @@ -78,6 +80,15 @@ class EventDispatcherTest extends TestCase return $dispatcher; } + public function getValidCommands() + { + return array( + array('phpunit'), + array('echo foo'), + array('echo -n foo'), + ); + } + public static function call() { throw new \RuntimeException();
Expand tests for valid CLI command from script
mothership-ec_composer
train
807786b59e7ff34152e3c4a503153d44cc39f971
diff --git a/corelib.js b/corelib.js index <HASH>..<HASH> 100644 --- a/corelib.js +++ b/corelib.js @@ -187,6 +187,24 @@ passing in the element as the first argument, the index of the element as the second argument, and `this` array as the third argument. +<code><pre> + + word = "" + indices = [] + ["r", "a", "d"].each (letter, index) -> + word += letter + indices.push(index) + +=> ["r", "a", "d"] + + word +=> "rad" + + indices +=> [0, 1, 2] + +</pre></code> + @name each @methodOf Array# @param {Function} iterator Function to be called once for
Modified in browser at pixie.strd6.com
PixieEngine_Cornerstone
train
e7ba58970f4ff5a7fa62bb680ac49c27c1918837
diff --git a/code/submissions/SubmittedFormReportField.php b/code/submissions/SubmittedFormReportField.php index <HASH>..<HASH> 100755 --- a/code/submissions/SubmittedFormReportField.php +++ b/code/submissions/SubmittedFormReportField.php @@ -143,7 +143,8 @@ class SubmittedFormReportField extends FormField { return $csvData; } else { - SS_HTTPRequest::send_file($csvData, $fileName)->output(); + SS_HTTPRequest::send_file($csvData, $fileName, 'text/csv')->output(); + exit; } } else { user_error("'$SQL_ID' is a valid type, but we can't find a UserDefinedForm in the database that matches the ID.", E_USER_ERROR);
BUGFIX: provide default file format, as Windows is unable to detect the mime type, and exit after the file is served so the headers will not get overwritten.
silverstripe_silverstripe-userforms
train
27c111b1e3248b5606b3aec65623a1fb9788a052
diff --git a/dispatch/migrations/0008_article_featured_video.py b/dispatch/migrations/0008_article_featured_video.py index <HASH>..<HASH> 100644 --- a/dispatch/migrations/0008_article_featured_video.py +++ b/dispatch/migrations/0008_article_featured_video.py @@ -22,7 +22,7 @@ class Migration(migrations.Migration): ('order', models.PositiveIntegerField(null=True)), ('article', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='video_article', to='dispatch.Article')), ('page', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='video_page', to='dispatch.Page')), - ('video', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='video', to='dispatch.Image')), + ('video', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='video', to='dispatch.Video')), ], ), migrations.AlterField( diff --git a/dispatch/static/manager/src/js/components/Editor/tabs/FeaturedVideoTab.js b/dispatch/static/manager/src/js/components/Editor/tabs/FeaturedVideoTab.js index <HASH>..<HASH> 100644 --- a/dispatch/static/manager/src/js/components/Editor/tabs/FeaturedVideoTab.js +++ b/dispatch/static/manager/src/js/components/Editor/tabs/FeaturedVideoTab.js @@ -14,14 +14,27 @@ export default function FeaturedVideoTab(props) { ) } - return ( - <div> - <FormInput - label='Video'> - <VideoSelectInput - selected={props.video} - update={updateVideo} /> - </FormInput> - </div> - ) + if (props.featured_video) { + return ( + <div> + <FormInput + label='Video'> + <VideoSelectInput + selected={props.featured_video.video} + update={updateVideo} /> + </FormInput> + </div> + ) + } else { + return ( + <div> + <FormInput + label='Video'> + <VideoSelectInput + update={updateVideo} /> + </FormInput> + </div> + ) + } + }
Show the title of the current featured video for an article
ubyssey_dispatch
train
65696139a126d5cd523f56f6ef8852f15b107512
diff --git a/closure/goog/testing/asserts.js b/closure/goog/testing/asserts.js index <HASH>..<HASH> 100644 --- a/closure/goog/testing/asserts.js +++ b/closure/goog/testing/asserts.js @@ -945,7 +945,7 @@ var assertEvaluatesToFalse = function(a, opt_b) { * comparisons erroneously fail: * <pre> * assertHTMLEquals('<a href="x" target="y">', '<a target="y" href="x">'); - * assertHTMLEquals('<div classname="a b">', '<div classname="b a">'); + * assertHTMLEquals('<div class="a b">', '<div class="b a">'); * assertHTMLEquals('<input disabled>', '<input disabled="disabled">'); * </pre> *
Fix a typo in a comment. ------------- Created by MOE: <URL>
google_closure-library
train
47a96690985b749c5598fb542a35a29a7ed76528
diff --git a/tests/ValidateTest.php b/tests/ValidateTest.php index <HASH>..<HASH> 100644 --- a/tests/ValidateTest.php +++ b/tests/ValidateTest.php @@ -129,5 +129,51 @@ class ValidateTest extends \PHPUnit_Framework_TestCase $signature = $this->validate->generateSignature($data); $this->assertEquals($hash, $signature); } + + /** + * Test that an exception is thrown when the API is invalid (null or empty) + * @covers \Yubikey\Validate::generateSignature + * @expectedException \InvalidArgumentException + */ + public function testSignatureGenerateNoApiKey() + { + $key = null; + $data = array('foo' => 'bar'); + $validate = new \Yubikey\Validate($key, $this->clientId); + $hash = preg_replace( + '/\+/', '%2B', + base64_encode(hash_hmac('sha1', http_build_query($data), $key, true)) + ); + + $signature = $validate->generateSignature($data); + } + + /** + * Add a new Host to the list + * @covers \Yubikey\Validate::addHost + */ + public function testAddNewHost() + { + $this->validate->addHost('test.com'); + $this->assertTrue( + in_array('test.com', $this->validate->getHosts()) + ); + } + + /** + * Set the new Hosts list (override) + * @covers \Yubikey\Validate::setHosts + * @covers \Yubikey\Validate::getHosts + */ + public function testSetHosts() + { + $hosts = array('foo.com'); + $this->validate->setHosts($hosts); + + $this->assertEquals( + $this->validate->getHosts(), + $hosts + ); + } }
adding tests for setting hosts, generating signature without key
enygma_yubikey
train
ebac0fa3211dcacd947219c3ba09e89327ee5828
diff --git a/charmhelpers/contrib/amulet/utils.py b/charmhelpers/contrib/amulet/utils.py index <HASH>..<HASH> 100644 --- a/charmhelpers/contrib/amulet/utils.py +++ b/charmhelpers/contrib/amulet/utils.py @@ -139,11 +139,11 @@ class AmuletUtils(object): return self._get_dir_mtime(sentry_unit, proc_dir) def service_restarted(self, sentry_unit, service, filename, - pgrep_full=False): + pgrep_full=False, sleep_time=20): """Compare a service's start time vs a file's last modification time (such as a config file for that service) to determine if the service has been restarted.""" - sleep(10) + sleep(sleep_time) if self._get_proc_start_time(sentry_unit, service, pgrep_full) >= \ self._get_file_mtime(sentry_unit, filename): return True
Make sleep time an optional parameter for service_restarted(). This allows the caller to optionally decide how long to wait before verifying that the service has restarted.
juju_charm-helpers
train
7cf3d5ccf04f33c5ee2deeb59fc7e46dfb6dedd8
diff --git a/src/meshio/stl/_stl.py b/src/meshio/stl/_stl.py index <HASH>..<HASH> 100644 --- a/src/meshio/stl/_stl.py +++ b/src/meshio/stl/_stl.py @@ -27,7 +27,7 @@ def read(filename): # num_triangles and see if it matches the file size # (https://stackoverflow.com/a/7394842/353337). f.read(80) - num_triangles = np.fromfile(f, count=1, dtype=np.uint32)[0] + num_triangles = np.fromfile(f, count=1, dtype="<u4")[0] # for each triangle, one has 3 float32 (facet normal), 9 float32 (facet), and 1 # int16 (attribute count), 50 bytes in total is_binary = 84 + num_triangles * 50 == os.path.getsize(filename) @@ -145,7 +145,7 @@ def _read_binary(f, num_triangles): f, count=num_triangles, dtype=np.dtype( - [("normal", "f4", (3,)), ("facet", "f4", (3, 3)), ("attr count", "i2")] + [("normal", "<f4", (3,)), ("facet", "<f4", (3, 3)), ("attr count", "<i2")] ), ) # discard normals, attribute count
Read binary STL file as little-endian Closes: #<I>
nschloe_meshio
train
f4c145636adddf49375930815bd6295aa30a7bec
diff --git a/dev/migrate_testing_phylesystem.py b/dev/migrate_testing_phylesystem.py index <HASH>..<HASH> 100644 --- a/dev/migrate_testing_phylesystem.py +++ b/dev/migrate_testing_phylesystem.py @@ -1,16 +1,16 @@ #!/usr/bin/env python from peyotl.nexson_validation.phylografter_workaround import workaround_phylografter_export_diffs +from peyotl import get_logger from subprocess import call import codecs import json import sys import os import re +_LOG = get_logger(__name__) def debug(m): - sys.stderr.write(m) - sys.stderr.write('\n') - sys.stderr.flush() + _LOG.debug(m) old_phylesystem = sys.argv[1] old_phylesystem_study = os.path.abspath(os.path.join(old_phylesystem, 'study')) @@ -34,7 +34,7 @@ pg_study_pat = re.compile(r'^\d+') if len(sys.argv) > 4: sl = sys.argv[4:] else: - sl = sl + sl = os.listdir(old_phylesystem_study) for f in sl: if pg_study_pat.match(f): source_study = f @@ -51,25 +51,35 @@ for f in sl: dest_full = os.path.join(new_phylesystem_study, dest_frag) dest_dir = os.path.split(dest_full)[0] assert(os.path.exists(full_source)) - + if os.path.exists(dest_full): + debug('Skipping {} because output exists'.format(f)) + continue # read input and do the phylografter_workaround to valid 0.0.0 syntax # store in scratch. valid_bf = os.path.join(scratch_dir, 'v0.0.0-' + source_study + '.json') debug('Raw phylografter from "{}" to valid 0.0.0 NexSON at "{}" ...'.format(full_source, valid_bf)) inp = codecs.open(full_source, mode='rU', encoding='utf-8') obj = json.load(inp) - workaround_phylografter_export_diffs(obj, valid_bf) + try: + workaround_phylografter_export_diffs(obj, valid_bf) + except: + _LOG.exception('Exception in workaround_phylografter_export_diffs for study ' + f) + failed.append(f) + continue # Convert to 1.2.1 unchecked_hbf = os.path.join(scratch_dir, 'v1.2.1-' + source_study + '.json') debug('Converting cleaned 0.0.0 NexSON from "{}" to unchecked 1.2.1 NexSON at "{}" ...'.format(valid_bf, unchecked_hbf)) - rc = call([sys.executable, conversion_script, - '-s', - '-e', - '1.2.1', - '-o', - unchecked_hbf, - valid_bf]) + invoc = [sys.executable, + conversion_script, + '-s', + '-e', + '1.2.1', + '-o', + unchecked_hbf, + valid_bf] + debug('invoc: "{}"'.format('" "'.join(invoc))) + rc = call(invoc) if rc != 0: failed.append(f) @@ -92,7 +102,7 @@ for f in sl: if rc != 0: if os.path.exists(dest_full): os.unlink(dest_full) - failed(f) + failed.append(f) else: if not os.path.isdir(dest_dir): os.makedirs(dest_dir) @@ -100,4 +110,4 @@ for f in sl: if failed: m = '\n '.join(failed) - sys.exit('Conversion of the following studies failed:\n {}\n'.format(m)) \ No newline at end of file + sys.exit('Conversion of the following studies failed:\n {}'.format(m)) \ No newline at end of file diff --git a/peyotl/nexson_syntax/direct2optimal_nexson.py b/peyotl/nexson_syntax/direct2optimal_nexson.py index <HASH>..<HASH> 100644 --- a/peyotl/nexson_syntax/direct2optimal_nexson.py +++ b/peyotl/nexson_syntax/direct2optimal_nexson.py @@ -59,6 +59,7 @@ class Direct2OptimalNexson(NexsonConverter): for node in node_list: nodeById[node['@id']] = node r = node.get('@root') + _LOG.debug(' node {} @root={}'.format(node['@id'], r)) if r in [True, 'true']: #@TEMP accepting true or "true" assert(root_node is None) root_node = node
migrate script working for all but studies <I> and <I>
OpenTreeOfLife_peyotl
train