_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q1500
RightApi.Client.do_get
train
def do_get(path, params={}) login if need_login? # Resource id is a special param as it needs to be added to the path path = add_id_and_params_to_path(path, params) req, res, resource_type, body = nil begin retry_request(true) do # Return content type so the resulting resource object knows what kind of resource it is. resource_type, body = @rest_client[path].get(headers) do |response, request, result, &block| req, res = request, response update_cookies(response) update_last_request(request, response) case response.code when 200 # Get the resource_type from the content_type, the resource_type # will be used later to add relevant methods to relevant resources type = if result.content_type.index('rightscale') get_resource_type(result.content_type) elsif result.content_type.index('text/plain') 'text' else '' end # work around getting ASCII-8BIT from some resources like audit entry detail charset = get_charset(response.headers) if charset && response.body.encoding != charset response.body.force_encoding(charset) end # raise an error if the API is misbehaving and returning an empty response when it shouldn't if type != 'text' && response.body.empty? raise EmptyBodyError.new(request, response) end [type, response.body] when 301, 302 update_api_url(response) response.follow_redirection(request, result, &block) when 404 raise UnknownRouteError.new(request, response) else raise ApiError.new(request, response) end end end rescue => e raise wrap(e, :get, path, params, req, res) end data = if resource_type == 'text' { 'text' => body } else JSON.parse(body, :allow_nan => true) end [resource_type, path, data] end
ruby
{ "resource": "" }
q1501
RightApi.Client.re_login?
train
def re_login?(e) auth_error = (e.response_code == 403 && e.message =~ %r(.*cookie is expired or invalid)) || e.response_code == 401 renewable_creds = (@instance_token || (@email && (@password || @password_base64)) || @refresh_token) auth_error && renewable_creds end
ruby
{ "resource": "" }
q1502
Ra10ke::Solve.RakeTask.get_version_req
train
def get_version_req(dep) req = get_key_or_sym(dep, :version_requirement) req = get_key_or_sym(dep, :version_range) unless req req end
ruby
{ "resource": "" }
q1503
Jekyll.Convertible.do_layout
train
def do_layout(payload, layouts) info = { :filters => [Jekyll::Filters], :registers => { :site => site } } payload['pygments_prefix'] = converter.pygments_prefix payload['pygments_suffix'] = converter.pygments_suffix # render and transform content (this becomes the final content of the object) self.content = engine.render(payload, content, info, data) transform # output keeps track of what will finally be written self.output = content # recursively render layouts layout = self while layout = layouts[layout.data['layout']] payload = payload.deep_merge('content' => output, 'page' => layout.data) self.output = engine.render(payload, output, info, data, layout.content) end end
ruby
{ "resource": "" }
q1504
LightIO::Watchers.IO.monitor
train
def monitor(interests=:rw) @monitor ||= begin raise @error if @error monitor = @ioloop.add_io_wait(@io, interests) {callback_on_waiting} ObjectSpace.define_finalizer(self, self.class.finalizer(monitor)) monitor end end
ruby
{ "resource": "" }
q1505
LightIO::Watchers.IO.wait_in_ioloop
train
def wait_in_ioloop raise LightIO::Error, "Watchers::IO can't cross threads" if @ioloop != LightIO::Core::IOloop.current raise EOFError, "can't wait closed IO watcher" if @monitor.closed? @ioloop.wait(self) end
ruby
{ "resource": "" }
q1506
Effective.Order.assign_confirmed_if_valid!
train
def assign_confirmed_if_valid! return unless pending? self.state = EffectiveOrders::CONFIRMED return true if valid? self.errors.clear self.state = EffectiveOrders::PENDING false end
ruby
{ "resource": "" }
q1507
Effective.Subscripter.create_stripe_token!
train
def create_stripe_token! return if stripe_token.blank? Rails.logger.info "[STRIPE] update source: #{stripe_token}" customer.stripe_customer.source = stripe_token customer.stripe_customer.save return if customer.stripe_customer.default_source.blank? card = customer.stripe_customer.sources.retrieve(customer.stripe_customer.default_source) customer.active_card = "**** **** **** #{card.last4} #{card.brand} #{card.exp_month}/#{card.exp_year}" customer.save! end
ruby
{ "resource": "" }
q1508
Effective.Subscripter.metadata
train
def metadata { :user_id => user.id.to_s, :user => user.to_s.truncate(500), (subscription.subscribable_type.downcase + '_id').to_sym => subscription.subscribable.id.to_s, subscription.subscribable_type.downcase.to_sym => subscription.subscribable.to_s } end
ruby
{ "resource": "" }
q1509
Plissken.Methods.to_snake_keys
train
def to_snake_keys(value = self) case value when Array value.map { |v| to_snake_keys(v) } when Hash snake_hash(value) else value end end
ruby
{ "resource": "" }
q1510
Effective.OrdersController.new
train
def new @order ||= Effective::Order.new(view_context.current_cart) EffectiveOrders.authorize!(self, :new, @order) unless @order.valid? flash[:danger] = "Unable to proceed: #{flash_errors(@order)}. Please try again." redirect_to(effective_orders.cart_path) return end end
ruby
{ "resource": "" }
q1511
Effective.OrdersController.create
train
def create @order ||= Effective::Order.new(view_context.current_cart) EffectiveOrders.authorize!(self, :create, @order) @order.assign_attributes(checkout_params) if (@order.confirm! rescue false) redirect_to(effective_orders.order_path(@order)) else flash.now[:danger] = "Unable to proceed: #{flash_errors(@order)}. Please try again." render :new end end
ruby
{ "resource": "" }
q1512
Effective.OrdersController.update
train
def update @order ||= Effective::Order.find(params[:id]) EffectiveOrders.authorize!(self, :update, @order) @order.assign_attributes(checkout_params) if (@order.confirm! rescue false) redirect_to(effective_orders.order_path(@order)) else flash.now[:danger] = "Unable to proceed: #{flash_errors(@order)}. Please try again." render :edit end end
ruby
{ "resource": "" }
q1513
Effective.OrdersController.index
train
def index @orders = Effective::Order.deep.purchased.where(user: current_user) @pending_orders = Effective::Order.deep.pending.where(user: current_user) EffectiveOrders.authorize!(self, :index, Effective::Order.new(user: current_user)) end
ruby
{ "resource": "" }
q1514
Effective.OrdersController.purchased
train
def purchased # Thank You! @order = if params[:id].present? Effective::Order.find(params[:id]) elsif current_user.present? Effective::Order.sorted.purchased_by(current_user).last end if @order.blank? redirect_to(effective_orders.orders_path) and return end EffectiveOrders.authorize!(self, :show, @order) redirect_to(effective_orders.order_path(@order)) unless @order.purchased? end
ruby
{ "resource": "" }
q1515
Effective.Cart.add
train
def add(item, quantity: 1, unique: true) raise 'expecting an acts_as_purchasable object' unless item.kind_of?(ActsAsPurchasable) existing = ( if unique.kind_of?(Proc) cart_items.find { |cart_item| instance_exec(item, cart_item.purchasable, &unique) } elsif unique.kind_of?(Symbol) || (unique.kind_of?(String) && unique != 'true') raise "expected item to respond to unique #{unique}" unless item.respond_to?(unique) cart_items.find { |cart_item| cart_item.purchasable.respond_to?(unique) && item.send(unique) == cart_item.purchasable.send(unique) } elsif unique.present? find(item) end ) if existing if unique || (existing.unique.present?) existing.assign_attributes(purchasable: item, quantity: quantity, unique: existing.unique) else existing.quantity = existing.quantity + quantity end end if item.quantity_enabled? && (existing ? existing.quantity : quantity) > item.quantity_remaining raise EffectiveOrders::SoldOutException, "#{item.purchasable_name} is sold out" end existing ||= cart_items.build(purchasable: item, quantity: quantity, unique: (unique.to_s unless unique.kind_of?(Proc))) save! end
ruby
{ "resource": "" }
q1516
Effective.OrdersMailer.pending_order_invoice_to_buyer
train
def pending_order_invoice_to_buyer(order_param) return true unless EffectiveOrders.mailer[:send_pending_order_invoice_to_buyer] @order = (order_param.kind_of?(Effective::Order) ? order_param : Effective::Order.find(order_param)) @user = @order.user @subject = subject_for(@order, :pending_order_invoice_to_buyer, "Pending Order: ##{@order.to_param}") mail(to: @order.user.email, subject: @subject) end
ruby
{ "resource": "" }
q1517
Effective.OrdersMailer.subscription_payment_succeeded
train
def subscription_payment_succeeded(customer_param) return true unless EffectiveOrders.mailer[:send_subscription_payment_succeeded] @customer = (customer_param.kind_of?(Effective::Customer) ? customer_param : Effective::Customer.find(customer_param)) @subscriptions = @customer.subscriptions @user = @customer.user @subject = subject_for(@customer, :subscription_payment_succeeded, 'Thank you for your payment') mail(to: @customer.user.email, subject: @subject) end
ruby
{ "resource": "" }
q1518
Infoboxer.MediaWiki.get
train
def get(*titles, interwiki: nil, &processor) return interwikis(interwiki).get(*titles, &processor) if interwiki pages = get_h(*titles, &processor).values.compact titles.count == 1 ? pages.first : Tree::Nodes[*pages] end
ruby
{ "resource": "" }
q1519
Infoboxer.MediaWiki.category
train
def category(title, limit: 'max', &processor) title = normalize_category_title(title) list(@api.query.generator(:categorymembers).title(title), limit, &processor) end
ruby
{ "resource": "" }
q1520
LightIO::Core.Beam.join
train
def join(limit=nil) # try directly get result if !alive? || limit.nil? || limit <= 0 # call value to raise error value return self end # return to current beam if beam done within time limit origin_parent = parent self.parent = Beam.current # set a transfer back timer timer = LightIO::Watchers::Timer.new(limit) timer.set_callback do if alive? caller_beam = parent # resume to origin parent self.parent = origin_parent caller_beam.transfer end end ioloop.add_timer(timer) ioloop.transfer if alive? nil else check_and_raise_error self end end
ruby
{ "resource": "" }
q1521
LightIO::Core.Beam.raise
train
def raise(error, message=nil, backtrace=nil) unless error.is_a?(BeamError) message ||= error.respond_to?(:message) ? error.message : nil backtrace ||= error.respond_to?(:backtrace) ? error.backtrace : nil super(error, message, backtrace) end self.parent = error.parent if error.parent if Beam.current == self raise(error.error, message, backtrace) else @error ||= error end end
ruby
{ "resource": "" }
q1522
LightIO::Wrap.IOWrapper.wait_nonblock
train
def wait_nonblock(method, *args) loop do result = __send__(method, *args, exception: false) case result when :wait_readable io_watcher.wait_readable when :wait_writable io_watcher.wait_writable else return result end end end
ruby
{ "resource": "" }
q1523
AppConfig.Processor.process_array
train
def process_array(value) value.split("\n").map { |s| s.to_s.strip }.compact.select { |s| !s.empty? } end
ruby
{ "resource": "" }
q1524
AppConfig.Processor.process
train
def process(data, type) raise InvalidType, 'Type is invalid!' unless FORMATS.include?(type) send("process_#{type}".to_sym, data.to_s) end
ruby
{ "resource": "" }
q1525
SolidusAdyen.AccountLocator.by_reference
train
def by_reference(psp_reference) code = Spree::Store. joins(orders: :payments). find_by(spree_payments: { response_code: psp_reference }). try!(:code) by_store_code(code) end
ruby
{ "resource": "" }
q1526
Autogui.Window.close
train
def close(options={}) PostMessage(handle, WM_SYSCOMMAND, SC_CLOSE, 0) wait_for_close(options) if (options[:wait_for_close] == true) end
ruby
{ "resource": "" }
q1527
Autogui.Window.wait_for_close
train
def wait_for_close(options={}) seconds = options[:timeout] || 5 timeout(seconds) do begin yield if block_given? sleep 0.05 end until 0 == IsWindow(handle) end end
ruby
{ "resource": "" }
q1528
Autogui.Window.set_focus
train
def set_focus if is_window? # if current process was the last to receive input, we can be sure that # SetForegroundWindow will be allowed. Send the shift key to whatever has # the focus now. This allows IRB to set_focus. keystroke(VK_SHIFT) ret = SetForegroundWindow(handle) logger.warn("SetForegroundWindow failed") if ret == 0 end end
ruby
{ "resource": "" }
q1529
Autogui.Window.combined_text
train
def combined_text return unless is_window? t = [] t << text unless text == '' children.each do |w| t << w.combined_text unless w.combined_text == '' end t.join("\n") end
ruby
{ "resource": "" }
q1530
Spree.AdyenRedirectController.authorise3d
train
def authorise3d payment = Spree::Adyen::RedirectResponse.find_by(md: params[:MD]).payment payment.request_env = request.env payment_method = payment.payment_method @order = payment.order payment_method.authorize_3d_secure_payment(payment, adyen_3d_params) payment.capture! if payment_method.auto_capture if complete redirect_to_order else redirect_to checkout_state_path(@order.state) end rescue Spree::Core::GatewayError handle_failed_redirect end
ruby
{ "resource": "" }
q1531
Spree.AdyenRedirectController.confirm_order_already_completed
train
def confirm_order_already_completed if psp_reference payment = @order.payments.find_by!(response_code: psp_reference) else # If no psp_reference is present but the order is complete then the # notification must have completed the order and created the payment. # Therefore select the last Adyen payment. payment = @order.payments.where(source_type: "Spree::Adyen::HppSource").last end payment.source.update(source_params) redirect_to_order end
ruby
{ "resource": "" }
q1532
Spree.AdyenRedirectController.restore_session
train
def restore_session guest_token, payment_method_id = params.fetch(:merchantReturnData).split("|") cookies.permanent.signed[:guest_token] = guest_token @payment_method = Spree::PaymentMethod.find(payment_method_id) @order = Spree::Order.find_by!(number: order_number) end
ruby
{ "resource": "" }
q1533
ChromedriverScreenshot.Tile.get_offset
train
def get_offset platform = ChromedriverScreenshot::Platforms.platform offset_x = @x - platform.window_x offset_y = @y - platform.window_y [offset_x, offset_y] end
ruby
{ "resource": "" }
q1534
HangoutsChat.Sender.card
train
def card(header, sections) payload = { cards: [header: header, sections: sections] } send_request(payload) end
ruby
{ "resource": "" }
q1535
HangoutsChat.Sender.send_request
train
def send_request(payload) response = @http.post payload raise APIError, response unless response.is_a?(Net::HTTPSuccess) response end
ruby
{ "resource": "" }
q1536
Ignorable.ClassMethods.ignore_columns
train
def ignore_columns(*columns) self.ignored_columns ||= [] self.ignored_columns += columns.map(&:to_s) reset_column_information descendants.each(&:reset_column_information) self.ignored_columns.tap(&:uniq!) end
ruby
{ "resource": "" }
q1537
Autogui.Input.keystroke
train
def keystroke(*keys) return if keys.empty? keybd_event keys.first, 0, KEYBD_EVENT_KEYDOWN, 0 sleep KEYBD_KEYDELAY keystroke *keys[1..-1] sleep KEYBD_KEYDELAY keybd_event keys.first, 0, KEYBD_EVENT_KEYUP, 0 end
ruby
{ "resource": "" }
q1538
Autogui.Input.char_to_virtual_keycode
train
def char_to_virtual_keycode(char) unless char.size == 1 raise "virtual keycode conversion is for single characters only" end code = char.unpack('U')[0] case char when '0'..'9' [code - ?0.ord + 0x30] when 'A'..'Z' [VK_SHIFT, code] when 'a'..'z' [code - ?a.ord + ?A.ord] when ' ' [code] when '+' [VK_ADD] when '=' [VK_OEM_PLUS] when ',' [VK_OEM_COMMA] when '.' [VK_OEM_PERIOD] when '-' [VK_OEM_MINUS] when '_' [VK_SHIFT, VK_OEM_MINUS] when ';' [VK_OEM_1] when ':' [VK_SHIFT, VK_OEM_1] when '/' [VK_OEM_2] when '?' [VK_SHIFT, VK_OEM_2] when '`' [VK_OEM_3] when '~' [VK_SHIFT, VK_OEM_3] when '[' [VK_OEM_4] when '{' [VK_SHIFT, VK_OEM_4] when '\\' [VK_OEM_5] when '|' [VK_SHIFT, VK_OEM_5] when ']' [VK_OEM_6] when '}' [VK_SHIFT, VK_OEM_6] when "'" [VK_OEM_7] when '"' [VK_SHIFT, VK_OEM_7] when '!' [VK_SHIFT, VK_1] when '@' [VK_SHIFT, VK_2] when '#' [VK_SHIFT, VK_3] when '$' [VK_SHIFT, VK_4] when '%' [VK_SHIFT, VK_5] when '^' [VK_SHIFT, VK_6] when '&' [VK_SHIFT, VK_7] when '*' [VK_SHIFT, VK_8] when '(' [VK_SHIFT, VK_9] when ')' [VK_SHIFT, VK_0] when "\n" [VK_RETURN] else raise "No conversion exists for character #{char}" end end
ruby
{ "resource": "" }
q1539
Credy.Rules.all
train
def all rules = [] raw.each do |type, details| # Add general rules Array(details['prefix']).each do |prefix| rules.push({ prefix: prefix.to_s, length: details['length'], type: type }) end # Process each country Array(details['countries']).each do |country, prefixes| # Add a rule for each prefix Array(prefixes).each do |prefix| rules.push({ prefix: prefix.to_s, length: details['length'], type: type, country: country, }) end end end # Sort by prefix length rules.sort { |x, y| y[:prefix].length <=> x[:prefix].length } end
ruby
{ "resource": "" }
q1540
Credy.Rules.filter
train
def filter(filters = {}) all.select do |rule| [:country, :type].each do |condition| break false if filters[condition] && filters[condition] != rule[condition] true end end end
ruby
{ "resource": "" }
q1541
Credy.CreditCard.generate
train
def generate(options = {}) rule = find_rule(options) || return number = generate_from_rule(rule) { number: number, type: rule[:type], country: rule[:country] } end
ruby
{ "resource": "" }
q1542
Credy.CreditCard.infos
train
def infos(number) rules = Rules.all.select do |rule| valid = true # Check number of digits lengths = rule[:length].is_a?(Array) ? rule[:length] : [rule[:length]] valid = false unless lengths.include? number.length # Check prefix valid = false unless !(number =~ Regexp.new("^#{rule[:prefix]}")).nil? valid end if rules rules[0] else nil end end
ruby
{ "resource": "" }
q1543
Credy.CreditCard.validate
train
def validate(number) criterii = {} criterii[:luhn] = Check.luhn number criterii[:type] = !!infos(number) valid = criterii.all? { |_, v| v == true } { valid: valid, details: criterii } end
ruby
{ "resource": "" }
q1544
Autogui.Clipboard.text=
train
def text=(str) data = str.nil? ? "" : str.dup Win32::Clipboard.set_data(data) end
ruby
{ "resource": "" }
q1545
Akismet.Client.spam
train
def spam(user_ip, user_agent, params = {}) response = invoke_comment_method('submit-spam', user_ip, user_agent, params) unless response.body == 'Thanks for making the web a better place.' raise_with_response response end end
ruby
{ "resource": "" }
q1546
Boxes.Builder.run
train
def run # rubocop:disable Metrics/AbcSize, Metrics/MethodLength original_directory = FileUtils.pwd box_name = '' # render the template rendered_template = template.render(name: name, provider: provider, scripts: scripts) # write the template to a file File.open(Boxes.config.working_dir + "#{build_name}.json", 'w') do |f| f.puts rendered_template end # set the environment vars Boxes.config.environment_vars.each do |e| e.each do |k, v| ENV[k] = v.to_s end end # execute the packer command FileUtils.chdir(Boxes.config.working_dir) cmd = "packer build #{build_name}.json" status = Subprocess.run(cmd) do |stdout, stderr, _thread| puts stdout unless stdout.nil? puts stderr unless stderr.nil? # catch the name of the artifact if stdout =~ /\.box/ box_name = stdout.gsub(/[a-zA-Z0-9:\-_]*?\.box/).first end end if status.exitstatus == 0 FileUtils.mv(Boxes.config.working_dir + box_name, "#{original_directory}/#{name}.box") else fail BuildRunError, 'The build didn\'t complete successfully. Check the logs.' end end
ruby
{ "resource": "" }
q1547
EmojiData.EmojiChar.render
train
def render(opts = {}) options = {variant_encoding: true}.merge(opts) #decide whether to use the normal unified ID or the variant for encoding to str target = (self.variant? && options[:variant_encoding]) ? self.variant : @unified EmojiChar::unified_to_char(target) end
ruby
{ "resource": "" }
q1548
EmojiData.EmojiChar.chars
train
def chars results = [self.render({variant_encoding: false})] @variations.each do |variation| results << EmojiChar::unified_to_char(variation) end @chars ||= results end
ruby
{ "resource": "" }
q1549
Boxes.Template.render
train
def render(args) ERB.new(template, nil, '-').result(ERBContext.new(args).get_binding) end
ruby
{ "resource": "" }
q1550
Parsi.Date.-
train
def - x case x when Numeric return self.class.new!(ajd - x, offset) when Date return ajd - x.ajd end raise TypeError, 'expected numeric or date' end
ruby
{ "resource": "" }
q1551
Parsi.Date.>>
train
def >> n y, m = (year * 12 + (mon - 1) + n).divmod(12) m, = (m + 1) .divmod(1) d = mday until jd2 = _valid_civil?(y, m, d) d -= 1 raise ArgumentError, 'invalid date' unless d > 0 end self + (jd2 - jd) end
ruby
{ "resource": "" }
q1552
CZTop::Config::Traversing.ChildrenAccessor.new
train
def new(name = nil, value = nil) config = CZTop::Config.new(name, value, parent: @config) yield config if block_given? config end
ruby
{ "resource": "" }
q1553
CZTop.Socket.CURVE_client!
train
def CURVE_client!(client_cert, server_cert) if server_cert.secret_key raise SecurityError, "server's secret key not secret" end client_cert.apply(self) # NOTE: desired: raises if no secret key in cert options.CURVE_serverkey = server_cert.public_key end
ruby
{ "resource": "" }
q1554
CZTop.Socket.connect
train
def connect(endpoint) rc = ffi_delegate.connect("%s", :string, endpoint) raise ArgumentError, "incorrect endpoint: %p" % endpoint if rc == -1 end
ruby
{ "resource": "" }
q1555
CZTop.Socket.disconnect
train
def disconnect(endpoint) rc = ffi_delegate.disconnect("%s", :string, endpoint) raise ArgumentError, "incorrect endpoint: %p" % endpoint if rc == -1 end
ruby
{ "resource": "" }
q1556
CZTop.Socket.bind
train
def bind(endpoint) rc = ffi_delegate.bind("%s", :string, endpoint) raise_zmq_err("unable to bind to %p" % endpoint) if rc == -1 @last_tcp_port = rc if rc > 0 end
ruby
{ "resource": "" }
q1557
CZTop.Socket.unbind
train
def unbind(endpoint) rc = ffi_delegate.unbind("%s", :string, endpoint) raise ArgumentError, "incorrect endpoint: %p" % endpoint if rc == -1 end
ruby
{ "resource": "" }
q1558
Hawkular::Inventory.Client.resource
train
def resource(id) hash = http_get(url('/resources/%s', id)) Resource.new(hash) rescue ::Hawkular::Exception => e return if e.cause.is_a?(::RestClient::NotFound) raise end
ruby
{ "resource": "" }
q1559
Hawkular::Inventory.Client.children_resources
train
def children_resources(parent_id) http_get(url('/resources/%s/children', parent_id))['results'].map { |r| Resource.new(r) } end
ruby
{ "resource": "" }
q1560
Hawkular::Inventory.Client.parent
train
def parent(id) hash = http_get(url('/resources/%s/parent', id)) Resource.new(hash) if hash end
ruby
{ "resource": "" }
q1561
CZTop.Beacon.configure
train
def configure(port) @actor.send_picture("si", :string, "CONFIGURE", :int, port) ptr = Zstr.recv(@actor) # NULL if context terminated or interrupted HasFFIDelegate.raise_zmq_err if ptr.null? hostname = ptr.read_string return hostname unless hostname.empty? raise NotImplementedError, "system doesn't support UDP broadcasts" end
ruby
{ "resource": "" }
q1562
CZTop.Beacon.publish
train
def publish(data, interval) raise ArgumentError, "data too long" if data.bytesize > MAX_BEACON_DATA @actor.send_picture("sbi", :string, "PUBLISH", :string, data, :int, data.bytesize, :int, interval) end
ruby
{ "resource": "" }
q1563
Hawkular::Token.Client.get_tokens
train
def get_tokens(credentials = {}) creds = credentials.empty? ? @credentials : credentials auth_header = { Authorization: base_64_credentials(creds) } http_get('/secret-store/v1/tokens', auth_header) end
ruby
{ "resource": "" }
q1564
CZTop.Z85.encode
train
def encode(input) raise ArgumentError, "wrong input length" if input.bytesize % 4 > 0 input = input.dup.force_encoding(Encoding::BINARY) ptr = ffi_delegate.encode(input, input.bytesize) raise_zmq_err if ptr.null? z85 = ptr.read_string z85.encode!(Encoding::ASCII) return z85 end
ruby
{ "resource": "" }
q1565
CZTop.Z85.decode
train
def decode(input) raise ArgumentError, "wrong input length" if input.bytesize % 5 > 0 zchunk = ffi_delegate.decode(input) raise_zmq_err if zchunk.null? decoded_string = zchunk.data.read_string(zchunk.size - 1) return decoded_string end
ruby
{ "resource": "" }
q1566
Protocol.Message.to_ruby
train
def to_ruby(result = '') if arity result << " def #{name}(" args = if arity >= 0 (1..arity).map { |i| "x#{i}" } else (1..~arity).map { |i| "x#{i}" } << '*rest' end if block_expected? args << '&block' end result << args * ', ' result << ") end\n" else result << " understand :#{name}\n" end end
ruby
{ "resource": "" }
q1567
Protocol.Message.check_class
train
def check_class(klass) unless klass.method_defined?(name) raise NotImplementedErrorCheckError.new(self, "method '#{name}' not implemented in #{klass}") end check_method = klass.instance_method(name) if arity and (check_arity = check_method.arity) != arity raise ArgumentErrorCheckError.new(self, "wrong number of arguments for protocol"\ " in method '#{name}' (#{check_arity} for #{arity}) of #{klass}") end if block_expected? modul = Utilities.find_method_module(name, klass.ancestors) parser = MethodParser.new(modul, name) parser.block_arg? or raise BlockCheckError.new(self, "expected a block argument for #{klass}") end arity and wrap_method(klass) true end
ruby
{ "resource": "" }
q1568
Protocol.Message.check_object
train
def check_object(object) if !object.respond_to?(name) raise NotImplementedErrorCheckError.new(self, "method '#{name}' not responding in #{object}") end check_method = object.method(name) if arity and (check_arity = check_method.arity) != arity raise ArgumentErrorCheckError.new(self, "wrong number of arguments for protocol"\ " in method '#{name}' (#{check_arity} for #{arity}) of #{object}") end if block_expected? if object.singleton_methods(false).map { |m| m.to_s } .include?(name) parser = MethodParser.new(object, name, true) else ancestors = object.class.ancestors modul = Utilities.find_method_module(name, ancestors) parser = MethodParser.new(modul, name) end parser.block_arg? or raise BlockCheckError.new(self, "expected a block argument for #{object}:#{object.class}") end if arity and not protocol === object object.extend protocol wrap_method(class << object ; self ; end) end true end
ruby
{ "resource": "" }
q1569
MdSpell.CLI.files
train
def files cli_arguments.each_with_index do |filename, index| if Dir.exist?(filename) cli_arguments[index] = Dir["#{filename}/**/*.md"] end end cli_arguments.flatten! cli_arguments end
ruby
{ "resource": "" }
q1570
Jshint.Lint.lint
train
def lint config.javascript_files.each do |file| file_content = get_file_content_as_json(file) code = %( JSHINT(#{file_content}, #{jshint_options}, #{jshint_globals}); return JSHINT.errors; ) errors[file] = context.exec(code) end end
ruby
{ "resource": "" }
q1571
Hawkular.BaseClient.generate_query_params
train
def generate_query_params(params = {}) params = params.reject { |_k, v| v.nil? || ((v.instance_of? Array) && v.empty?) } return '' if params.empty? params.inject('?') do |ret, (k, v)| ret += '&' unless ret == '?' part = v.instance_of?(Array) ? "#{k}=#{v.join(',')}" : "#{k}=#{v}" ret + hawk_escape(part) end end
ruby
{ "resource": "" }
q1572
CZTop.Message.<<
train
def <<(frame) case frame when String # NOTE: can't use addstr because the data might be binary mem = FFI::MemoryPointer.from_string(frame) rc = ffi_delegate.addmem(mem, mem.size - 1) # without NULL byte when Frame rc = ffi_delegate.append(frame.ffi_delegate) else raise ArgumentError, "invalid frame: %p" % frame end raise_zmq_err unless rc == 0 self end
ruby
{ "resource": "" }
q1573
CZTop.Message.prepend
train
def prepend(frame) case frame when String # NOTE: can't use pushstr because the data might be binary mem = FFI::MemoryPointer.from_string(frame) rc = ffi_delegate.pushmem(mem, mem.size - 1) # without NULL byte when Frame rc = ffi_delegate.prepend(frame.ffi_delegate) else raise ArgumentError, "invalid frame: %p" % frame end raise_zmq_err unless rc == 0 end
ruby
{ "resource": "" }
q1574
CZTop.Message.pop
train
def pop # NOTE: can't use popstr because the data might be binary ptr = ffi_delegate.pop return nil if ptr.null? Frame.from_ffi_delegate(ptr).to_s end
ruby
{ "resource": "" }
q1575
CZTop.Message.to_a
train
def to_a ffi_delegate = ffi_delegate() frame = ffi_delegate.first return [] if frame.null? arr = [ frame.data.read_bytes(frame.size) ] while frame = ffi_delegate.next and not frame.null? arr << frame.data.read_bytes(frame.size) end return arr end
ruby
{ "resource": "" }
q1576
CZTop.Message.routing_id=
train
def routing_id=(new_routing_id) raise ArgumentError unless new_routing_id.is_a? Integer # need to raise manually, as FFI lacks this feature. # @see https://github.com/ffi/ffi/issues/473 raise RangeError if new_routing_id < 0 ffi_delegate.set_routing_id(new_routing_id) end
ruby
{ "resource": "" }
q1577
Cbc.ConflictSolver.first_failing
train
def first_failing(conflict_set_size, crs, continuous: false, max_iterations: nil) min_idx = conflict_set_size max_idx = crs.nb_constraints - 1 loop do unless max_iterations.nil? return min_idx..max_idx if max_iterations <= 0 max_iterations -= 1 end half_constraint_idx = (max_idx + min_idx) / 2 # puts "Refining: [#{min_idx}:#{max_idx}] -> #{half_constraint_idx}" crs2 = crs.restrict_to_n_constraints(half_constraint_idx + 1) problem = Problem.from_compressed_row_storage(crs2, continuous: continuous) if infeasible?(problem) max_idx = half_constraint_idx # puts " INFEAS" else min_idx = half_constraint_idx + 1 # puts " FEAS" end next if max_idx != min_idx return nil if max_idx > crs.nb_constraints return min_idx..max_idx end # Shouldn't come here if the whole problem is infeasible nil end
ruby
{ "resource": "" }
q1578
Genealogy.AlterMethods.add_siblings
train
def add_siblings(*args) options = args.extract_options! case options[:half] when :father check_incompatible_relationship(:paternal_half_sibling, *args) when :mother check_incompatible_relationship(:maternal_half_sibling, *args) when nil check_incompatible_relationship(:sibling, *args) end transaction do args.inject(true) do |res,sib| res &= case options[:half] when :father raise LineageGapException, "Can't add paternal halfsiblings without a father" unless father sib.add_mother(options[:spouse]) if options[:spouse] sib.add_father(father) when :mother raise LineageGapException, "Can't add maternal halfsiblings without a mother" unless mother sib.add_father(options[:spouse]) if options[:spouse] sib.add_mother(mother) when nil raise LineageGapException, "Can't add siblings without parents" unless father and mother sib.add_father(father) sib.add_mother(mother) else raise ArgumentError, "Admitted values for :half options are: :father, :mother or nil" end end end end
ruby
{ "resource": "" }
q1579
Genealogy.AlterMethods.remove_siblings
train
def remove_siblings(*args) options = args.extract_options! raise ArgumentError.new("Unknown option value: half: #{options[:half]}.") if (options[:half] and ![:father,:mother].include?(options[:half])) resulting_indivs = if args.blank? siblings(options) else args & siblings(options) end transaction do resulting_indivs.each do |sib| case options[:half] when :father sib.remove_father sib.remove_mother if options[:remove_other_parent] == true when :mother sib.remove_father if options[:remove_other_parent] == true sib.remove_mother when nil sib.remove_parents end end end !resulting_indivs.empty? #returned value must be true if self has at least a siblings to affect end
ruby
{ "resource": "" }
q1580
Genealogy.AlterMethods.add_children
train
def add_children(*args) options = args.extract_options! raise_if_sex_undefined check_incompatible_relationship(:children, *args) transaction do args.inject(true) do |res,child| res &= case sex_before_type_cast when gclass.sex_male_value child.add_mother(options[:spouse]) if options[:spouse] child.add_father(self) when gclass.sex_female_value child.add_father(options[:spouse]) if options[:spouse] child.add_mother(self) else raise SexError, "Sex value not valid for #{self}" end end end end
ruby
{ "resource": "" }
q1581
Genealogy.AlterMethods.remove_children
train
def remove_children(*args) options = args.extract_options! raise_if_sex_undefined resulting_indivs = if args.blank? children(options) else args & children(options) end transaction do resulting_indivs.each do |child| if options[:remove_other_parent] == true child.remove_parents else case sex_before_type_cast when gclass.sex_male_value child.remove_father when gclass.sex_female_value child.remove_mother else raise SexError, "Sex value not valid for #{self}" end end end end !resulting_indivs.empty? #returned value must be true if self has at least a siblings to affect end
ruby
{ "resource": "" }
q1582
Genealogy.CurrentSpouseMethods.add_current_spouse
train
def add_current_spouse(spouse) raise_unless_current_spouse_enabled check_incompatible_relationship(:current_spouse,spouse) if gclass.perform_validation_enabled self.current_spouse = spouse spouse.current_spouse = self transaction do spouse.save! save! end else transaction do self.update_attribute(:current_spouse,spouse) spouse.update_attribute(:current_spouse,self) end end end
ruby
{ "resource": "" }
q1583
Genealogy.CurrentSpouseMethods.remove_current_spouse
train
def remove_current_spouse raise_unless_current_spouse_enabled if gclass.perform_validation_enabled ex_current_spouse = current_spouse current_spouse.current_spouse = nil self.current_spouse = nil transaction do ex_current_spouse.save! save! end else transaction do current_spouse.update_attribute(:current_spouse,nil) self.update_attribute(:current_spouse,nil) end end end
ruby
{ "resource": "" }
q1584
CZTop.Poller::ZPoller.add
train
def add(reader) rc = ffi_delegate.add(reader) raise_zmq_err("unable to add socket %p" % reader) if rc == -1 remember_socket(reader) end
ruby
{ "resource": "" }
q1585
CZTop.Poller::ZPoller.remove
train
def remove(reader) rc = ffi_delegate.remove(reader) raise_zmq_err("unable to remove socket %p" % reader) if rc == -1 forget_socket(reader) end
ruby
{ "resource": "" }
q1586
CZTop.Poller::ZPoller.wait
train
def wait(timeout = -1) ptr = ffi_delegate.wait(timeout) if ptr.null? raise Interrupt if ffi_delegate.terminated return nil end return socket_by_ptr(ptr) end
ruby
{ "resource": "" }
q1587
MdSpell.SpellChecker.typos
train
def typos results = [] FFI::Aspell::Speller.open(Configuration[:language]) do |speller| TextLine.scan(document).each do |line| line.words.each do |word| next if ignored? word unless speller.correct? word results << Typo.new(line, word, speller.suggestions(word)) end end end end results end
ruby
{ "resource": "" }
q1588
Hawkular::Metrics.Client.data_by_tags
train
def data_by_tags(tags, buckets: nil, bucketDuration: nil, # rubocop:disable Naming/VariableName start: nil, ends: nil) data = { tags: tags_param(tags), buckets: buckets, bucketDuration: bucketDuration, start: start, end: ends } http_post('metrics/stats/query', data) end
ruby
{ "resource": "" }
q1589
Hawkular::Metrics.Client.push_data
train
def push_data(gauges: [], counters: [], availabilities: [], strings: []) gauges.each { |g| default_timestamp g[:data] } counters.each { |g| default_timestamp g[:data] } availabilities.each { |g| default_timestamp g[:data] } strings.each { |g| default_timestamp g[:data] } data = { gauges: gauges, counters: counters, availabilities: availabilities, strings: strings } path = '/metrics/' path << (@legacy_api ? 'data' : 'raw') http_post(path, data) end
ruby
{ "resource": "" }
q1590
Hawkular::Metrics.Client.query_stats
train
def query_stats(gauge_ids: [], counter_ids: [], avail_ids: [], rates: false, starts: nil, ends: nil, bucket_duration: '3600s') path = '/metrics/stats/query' metrics = { gauge: gauge_ids, counter: counter_ids, availability: avail_ids } data = { metrics: metrics, start: starts, end: ends, bucketDuration: bucket_duration } data['types'] = %w[gauge gauge_rate counter counter_rate availability] if rates http_post(path, data) end
ruby
{ "resource": "" }
q1591
Hawkular::Metrics.Client.tags
train
def tags tags = [] http_get('/metrics/').map do |g| next if g['tags'].nil? g['tags'].map do |k, v| tags << { k => v } end end tags.uniq! end
ruby
{ "resource": "" }
q1592
Geometry.Polygon.outset_bisectors
train
def outset_bisectors(length) vertices.zip(spokes).map {|v,b| b ? Edge.new(v, v+(b * length)) : nil} end
ruby
{ "resource": "" }
q1593
Declarative.Defaults.call
train
def call(name, given_options) # TODO: allow to receive rest of options/block in dynamic block. or, rather, test it as it was already implemented. evaluated_options = @dynamic_options.(name, given_options) options = Variables.merge( @static_options, handle_array_and_deprecate(evaluated_options) ) options = Variables.merge( options, handle_array_and_deprecate(given_options) ) # FIXME: given_options is not tested! end
ruby
{ "resource": "" }
q1594
CZTop.Certificate.[]=
train
def []=(key, value) if value ffi_delegate.set_meta(key, "%s", :string, value) else ffi_delegate.unset_meta(key) end end
ruby
{ "resource": "" }
q1595
CZTop.Certificate.meta_keys
train
def meta_keys zlist = ffi_delegate.meta_keys first_key = zlist.first return [] if first_key.null? keys = [first_key.read_string] while key = zlist.next break if key.null? keys << key.read_string end keys end
ruby
{ "resource": "" }
q1596
Sorted.Set.direction_intersect
train
def direction_intersect(other_set) self.class.new.tap do |memo| unless other_set.keys.empty? a(memo, other_set) b(memo, other_set) end c(memo) d(memo, other_set) end end
ruby
{ "resource": "" }
q1597
Sorted.Set.-
train
def -(other_set) self.class.new.tap do |memo| each do |a| b = other_set.assoc(a.first) next if b memo << a end end end
ruby
{ "resource": "" }
q1598
Sorted.Set.a
train
def a(memo, other) if keys == other.keys.take(keys.size) keys.each do |order| if other.keys.include?(order) memo << [order, flip_direction(other.assoc(order).last)] end end else keys.each do |order| if other.keys.include?(order) memo << other.assoc(order) end end end end
ruby
{ "resource": "" }
q1599
Sorted.Set.b
train
def b(memo, other) other.keys.each do |sort| if keys.include?(sort) && !memo.keys.include?(sort) memo << other.assoc(sort) end end end
ruby
{ "resource": "" }