_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q22600
OneviewSDK.Cli.env
train
def env data = {} OneviewSDK::ENV_VARS.each { |k| data[k] = ENV[k] } if @options['format'] == 'human' data.each do |key, value| value = "'#{value}'" if value && !%w[true false].include?(value) printf "%-#{data.keys.max_by(&:length).length}s = %s\n", key, value || 'nil' end else output(parse_hash(data, true)) end end
ruby
{ "resource": "" }
q22601
OneviewSDK.Cli.show
train
def show(type, name) resource_class = parse_type(type) client_setup matches = resource_class.find_by(@client, name: name) fail_nice 'Not Found' if matches.empty? data = matches.first.data if options['attribute'] data = select_attributes(options['attribute'], data) end output data end
ruby
{ "resource": "" }
q22602
OneviewSDK.Cli.rest
train
def rest(method, uri) log_level = @options['log_level'] == :warn ? :error : @options['log_level'].to_sym # Default to :error client_setup('log_level' => log_level) uri_copy = uri.dup uri_copy.prepend('/') unless uri_copy.start_with?('/') if @options['data'] begin data = { body: JSON.parse(@options['data']) } rescue JSON::ParserError => e fail_nice("Failed to parse data as JSON\n#{e.message}") end end data ||= {} response = @client.rest_api(method, uri_copy, data) if response.code.to_i.between?(200, 299) case @options['format'] when 'yaml' puts JSON.parse(response.body).to_yaml when 'json' puts JSON.pretty_generate(JSON.parse(response.body)) else # raw puts response.body end else body = JSON.pretty_generate(JSON.parse(response.body)) rescue response.body fail_nice("Request failed: #{response.inspect}\nHeaders: #{response.to_hash}\nBody: #{body}") end rescue OneviewSDK::InvalidRequest => e fail_nice(e.message) end
ruby
{ "resource": "" }
q22603
OneviewSDK.Cli.update
train
def update(type, name) resource_class = parse_type(type) client_setup fail_nice 'Must set the hash or json option' unless @options['hash'] || @options['json'] fail_nice 'Must set the hash OR json option. Not both' if @options['hash'] && @options['json'] begin data = @options['hash'] || JSON.parse(@options['json']) rescue JSON::ParserError => e fail_nice("Failed to parse json\n#{e.message}") end matches = resource_class.find_by(@client, name: name) fail_nice 'Not Found' if matches.empty? resource = matches.first begin resource.update(data) puts 'Updated Successfully!' rescue StandardError => e fail_nice "Failed to update #{resource.class.name.split('::').last} '#{name}': #{e}" end end
ruby
{ "resource": "" }
q22604
OneviewSDK.Cli.delete
train
def delete(type, name) resource_class = parse_type(type) client_setup matches = resource_class.find_by(@client, name: name) fail_nice('Not Found', 2) if matches.empty? resource = matches.first return unless options['force'] || agree("Delete '#{name}'? [Y/N] ") begin resource.delete puts 'Deleted Successfully!' rescue StandardError => e fail_nice "Failed to delete #{resource.class.name.split('::').last} '#{name}': #{e}" end end
ruby
{ "resource": "" }
q22605
OneviewSDK.Cli.delete_from_file
train
def delete_from_file(file_path) client_setup resource = OneviewSDK::Resource.from_file(@client, file_path) fail_nice("#{resource.class.name.split('::').last} '#{resource[:name] || resource[:uri]}' Not Found", 2) unless resource.retrieve! return unless options['force'] || agree("Delete '#{resource[:name]}'? [Y/N] ") begin resource.delete puts 'Deleted Successfully!' rescue StandardError => e fail_nice "Failed to delete #{resource.class.name.split('::').last} '#{resource[:name]}': #{e}" end rescue IncompleteResource => e fail_nice "Failed to delete #{resource.class.name.split('::').last} '#{resource[:name]}': #{e}" rescue SystemCallError => e # File open errors fail_nice e end
ruby
{ "resource": "" }
q22606
OneviewSDK.Cli.to_file
train
def to_file(type, name) file = File.expand_path(options['path']) resource_class = parse_type(type) client_setup resource = resource_class.find_by(@client, name: name).first fail_nice "#{resource_class.name.split('::').last} '#{name}' not found" unless resource resource.to_file(file, options['format']) puts "Output to #{file}" rescue SystemCallError => e fail_nice "Failed to create file! (You may need to create the necessary directories). Message: #{e}" end
ruby
{ "resource": "" }
q22607
OneviewSDK.Cli.cert
train
def cert(type, url = ENV['ONEVIEWSDK_URL']) case type.downcase when 'check' fail_nice 'Must specify a url' unless url puts "Checking certificate for '#{url}' ..." if OneviewSDK::SSLHelper.check_cert(url) puts 'Certificate is valid!' else fail_nice 'Certificate Validation Failed!' end when 'import' fail_nice 'Must specify a url' unless url puts "Importing certificate for '#{url}' into '#{OneviewSDK::SSLHelper::CERT_STORE}'..." OneviewSDK::SSLHelper.install_cert(url) when 'list' if File.file?(OneviewSDK::SSLHelper::CERT_STORE) puts File.read(OneviewSDK::SSLHelper::CERT_STORE) else puts 'No certs imported!' end else fail_nice "Invalid action '#{type}'. Valid actions are [check, import, list]" end rescue StandardError => e fail_nice e.message end
ruby
{ "resource": "" }
q22608
OneviewSDK.Cli.scmb
train
def scmb client_setup connection = OneviewSDK::SCMB.new_connection(@client) q = OneviewSDK::SCMB.new_queue(connection, @options['route']) puts 'Subscribing to OneView messages. To exit, press Ctrl + c' q.subscribe(block: true) do |_delivery_info, _properties, payload| data = JSON.parse(payload) rescue payload puts "\n#{'=' * 50}\n\nReceived message with payload:" @options['format'] == 'raw' ? puts(payload) : output(data) end end
ruby
{ "resource": "" }
q22609
OneviewSDK.Cli.parse_type
train
def parse_type(type) api_ver = (@options['api_version'] || ENV['ONEVIEWSDK_API_VERSION'] || OneviewSDK.api_version).to_i unless OneviewSDK::SUPPORTED_API_VERSIONS.include?(api_ver) # Find and use the best available match for the desired API version (round down to nearest) valid_api_ver = OneviewSDK::SUPPORTED_API_VERSIONS.select { |x| x <= api_ver }.max || OneviewSDK::SUPPORTED_API_VERSIONS.min puts "WARNING: Module API version #{api_ver} is not supported. Using #{valid_api_ver}" api_ver = valid_api_ver end variant = @options['variant'] || ENV['ONEVIEWSDK_VARIANT'] variant ||= OneviewSDK::API300.variant if api_ver == 300 if variant && !SUPPORTED_VARIANTS.include?(variant) fail_nice "Variant '#{variant}' is not supported. Try one of #{SUPPORTED_VARIANTS}" end r = OneviewSDK.resource_named(type, api_ver, variant) # Try default API version as last resort r ||= OneviewSDK.resource_named(type, OneviewSDK.api_version, variant) unless api_ver == OneviewSDK.api_version return r if r && r.respond_to?(:find_by) valid_classes = [] api_module = OneviewSDK.const_get("API#{api_ver}") api_module = api_module.const_get(variant.to_s) unless api_ver.to_i == 200 api_module.constants.each do |c| klass = api_module.const_get(c) next unless klass.is_a?(Class) && klass.respond_to?(:find_by) valid_classes.push(klass.name.split('::').last) end vc = valid_classes.sort_by!(&:downcase).join("\n ") var = variant ? " (variant #{variant})" : '' fail_nice("Invalid resource type: '#{type}'. Valid options for API version #{api_ver}#{var} are:\n #{vc}") end
ruby
{ "resource": "" }
q22610
OneviewSDK.Cli.select_attributes
train
def select_attributes(attributes, data = {}) attributes = attributes.split(',').map(&:strip).reject(&:empty?).map { |a| a.split('.') } if attributes.is_a?(String) r_data = data.is_a?(Hash) ? data : data.data temp = {} attributes.each do |attr| temp_level = temp attr = [attr] if attr.is_a?(String) attr.each_with_index do |a, index| # Safely retrieving and setting nested keys is not as easy, so loop to build a nested Hash structure for the result if index == attr.size - 1 # Use r_data.dig(*attr) if we ever drop support for Ruby < 2.3 temp_level[a] = [*attr].reduce(r_data) { |m, k| m && m[k] } rescue nil else temp_level[a] ||= {} temp_level = temp_level[a] end end end temp end
ruby
{ "resource": "" }
q22611
OneviewSDK.Cli.select_attributes_from_multiple
train
def select_attributes_from_multiple(attributes, data = []) attributes = attributes.split(',').map(&:strip).reject(&:empty?).map { |a| a.split('.') } if attributes.is_a?(String) result = [] data.each do |r| result.push(r['name'] => select_attributes(attributes, r)) end result end
ruby
{ "resource": "" }
q22612
OneviewSDK.Client.get_all
train
def get_all(type, api_ver = @api_version, variant = nil) klass = OneviewSDK.resource_named(type, api_ver, variant) raise TypeError, "Invalid resource type '#{type}'. OneviewSDK::API#{api_ver} does not contain a class like it." unless klass klass.get_all(self) end
ruby
{ "resource": "" }
q22613
OneviewSDK.Client.wait_for
train
def wait_for(task_uri) raise ArgumentError, 'Must specify a task_uri!' if task_uri.nil? || task_uri.empty? loop do task_uri.gsub!(%r{https:(.*)\/rest}, '/rest') task = rest_get(task_uri) body = JSON.parse(task.body) case body['taskState'].downcase when 'completed' return body when 'warning' @logger.warn "Task ended with warning status. Details: #{JSON.pretty_generate(body['taskErrors']) rescue body}" return body when 'error', 'killed', 'terminated' msg = "Task ended with bad state: '#{body['taskState']}'.\nResponse: " msg += body['taskErrors'] ? JSON.pretty_generate(body['taskErrors']) : JSON.pretty_generate(body) raise TaskError, msg else print '.' if @print_wait_dots sleep 10 end end end
ruby
{ "resource": "" }
q22614
OneviewSDK.Client.appliance_api_version
train
def appliance_api_version options = { 'Content-Type' => :none, 'X-API-Version' => :none, 'auth' => :none } response = rest_api(:get, '/rest/version', options) version = response_handler(response)['currentVersion'] raise ConnectionError, "Couldn't get API version" unless version version = version.to_i if version.class != Integer version rescue ConnectionError @logger.warn "Failed to get OneView max api version. Using default (#{OneviewSDK::DEFAULT_API_VERSION})" OneviewSDK::DEFAULT_API_VERSION end
ruby
{ "resource": "" }
q22615
OneviewSDK.Client.login
train
def login(retries = 2) options = { 'body' => { 'userName' => @user, 'password' => @password, 'authLoginDomain' => @domain } } response = rest_post('/rest/login-sessions', options) body = response_handler(response) return body['sessionID'] if body['sessionID'] raise ConnectionError, "\nERROR! Couldn't log into OneView server at #{@url}. Response: #{response}\n#{response.body}" rescue StandardError => e raise e unless retries > 0 @logger.debug 'Failed to log in to OneView. Retrying...' return login(retries - 1) end
ruby
{ "resource": "" }
q22616
OneviewSDK.Rest.rest_api
train
def rest_api(type, path, options = {}, api_ver = @api_version, redirect_limit = 3) @logger.debug "Making :#{type} rest call to #{@url}#{path}" raise InvalidRequest, 'Must specify path' unless path uri = URI.parse(Addressable::URI.escape(@url + path)) http = build_http_object(uri) request = build_request(type, uri, options.dup, api_ver) response = http.request(request) @logger.debug " Response: Code=#{response.code}. Headers=#{response.to_hash}\n Body=#{response.body}" if response.class <= Net::HTTPRedirection && redirect_limit > 0 && response['location'] @logger.debug "Redirecting to #{response['location']}" return rest_api(type, response['location'], options, api_ver, redirect_limit - 1) end response rescue OpenSSL::SSL::SSLError => e msg = 'SSL verification failed for request. Please either:' msg += "\n 1. Install the certificate into your system's cert store" msg += ". Using cert store: #{ENV['SSL_CERT_FILE']}" if ENV['SSL_CERT_FILE'] msg += "\n 2. Run oneview-sdk-ruby cert import #{@url}" msg += "\n 3. Set the :ssl_enabled option to false for your client (NOT RECOMMENDED)" @logger.error msg raise e end
ruby
{ "resource": "" }
q22617
OneviewSDK.Rest.upload_file
train
def upload_file(file_path, path, options = {}, timeout = READ_TIMEOUT) raise NotFound, "ERROR: File '#{file_path}' not found!" unless File.file?(file_path) options = Hash[options.map { |k, v| [k.to_s, v] }] body_params = options['body'] || {} headers_params = options['header'] || {} headers = { 'Content-Type' => 'multipart/form-data', 'X-Api-Version' => @api_version.to_s, 'auth' => @token } headers.merge!(headers_params) File.open(file_path) do |file| name_to_show = options['file_name'] || File.basename(file_path) body_params['file'] = UploadIO.new(file, 'application/octet-stream', name_to_show) uri = URI.parse(Addressable::URI.escape(@url + path)) http_request = build_http_object(uri) http_request.read_timeout = timeout req = Net::HTTP::Post::Multipart.new( uri.path, body_params, headers ) http_request.start do |http| begin response = http.request(req) return response_handler(response) rescue Net::ReadTimeout raise "The connection was closed because the timeout of #{timeout} seconds has expired."\ 'You can specify the timeout in seconds by passing the timeout on the method call.'\ 'Interrupted file uploads may result in corrupted file remaining in the appliance.'\ 'HPE recommends checking the appliance for corrupted file and removing it.' end end end end
ruby
{ "resource": "" }
q22618
OneviewSDK.Rest.download_file
train
def download_file(path, local_drive_path) uri = URI.parse(Addressable::URI.escape(@url + path)) http_request = build_http_object(uri) req = build_request(:get, uri, {}, @api_version.to_s) http_request.start do |http| http.request(req) do |res| response_handler(res) unless res.code.to_i.between?(200, 204) File.open(local_drive_path, 'wb') do |file| res.read_body do |segment| file.write(segment) end end end end true end
ruby
{ "resource": "" }
q22619
OneviewSDK.Rest.response_handler
train
def response_handler(response, wait_on_task = true) case response.code.to_i when RESPONSE_CODE_OK # Synchronous read/query begin return JSON.parse(response.body) rescue JSON::ParserError => e @logger.warn "Failed to parse JSON response. #{e}" return response.body end when RESPONSE_CODE_CREATED # Synchronous add JSON.parse(response.body) when RESPONSE_CODE_ACCEPTED # Asynchronous add, update or delete return JSON.parse(response.body) unless wait_on_task @logger.debug "Waiting for task: response.header['location']" uri = response.header['location'] || JSON.parse(response.body)['uri'] # If task uri is not returned in header task = wait_for(uri) return true unless task['associatedResource'] && task['associatedResource']['resourceUri'] resource_data = rest_get(task['associatedResource']['resourceUri']) JSON.parse(resource_data.body) when RESPONSE_CODE_NO_CONTENT # Synchronous delete {} when RESPONSE_CODE_BAD_REQUEST BadRequest.raise! "400 BAD REQUEST #{response.body}", response when RESPONSE_CODE_UNAUTHORIZED Unauthorized.raise! "401 UNAUTHORIZED #{response.body}", response when RESPONSE_CODE_NOT_FOUND NotFound.raise! "404 NOT FOUND #{response.body}", response else RequestError.raise! "#{response.code} #{response.body}", response end end
ruby
{ "resource": "" }
q22620
OneviewSDK.Rest.build_http_object
train
def build_http_object(uri) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true if uri.scheme == 'https' if @ssl_enabled http.cert_store = @cert_store if @cert_store else http.verify_mode = OpenSSL::SSL::VERIFY_NONE end http.read_timeout = @timeout if @timeout # Timeout for a request http.open_timeout = @timeout if @timeout # Timeout for a connection http end
ruby
{ "resource": "" }
q22621
OneviewSDK.Rest.build_request
train
def build_request(type, uri, options, api_ver) case type.downcase.to_sym when :get request = Net::HTTP::Get.new(uri.request_uri) when :post request = Net::HTTP::Post.new(uri.request_uri) when :put request = Net::HTTP::Put.new(uri.request_uri) when :patch request = Net::HTTP::Patch.new(uri.request_uri) when :delete request = Net::HTTP::Delete.new(uri.request_uri) else raise InvalidRequest, "Invalid rest method: #{type}. Valid methods are: get, post, put, patch, delete" end options['X-API-Version'] ||= api_ver options['auth'] ||= @token options['Content-Type'] ||= 'application/json' options.delete('Content-Type') if [:none, 'none', nil].include?(options['Content-Type']) options.delete('X-API-Version') if [:none, 'none', nil].include?(options['X-API-Version']) options.delete('auth') if [:none, 'none', nil].include?(options['auth']) options.each do |key, val| if key.to_s.downcase == 'body' request.body = val.to_json rescue val else request[key] = val end end @logger.debug " Options: #{options}" # Warning: This may include passwords and tokens request end
ruby
{ "resource": "" }
q22622
WineBouncer.OAuth2.doorkeeper_authorize!
train
def doorkeeper_authorize!(*scopes) scopes = Doorkeeper.configuration.default_scopes if scopes.empty? unless valid_doorkeeper_token?(*scopes) if !doorkeeper_token || !doorkeeper_token.accessible? error = Doorkeeper::OAuth::InvalidTokenResponse.from_access_token(doorkeeper_token) raise WineBouncer::Errors::OAuthUnauthorizedError, error else error = Doorkeeper::OAuth::ForbiddenTokenResponse.from_scopes(scopes) raise WineBouncer::Errors::OAuthForbiddenError, error end end end
ruby
{ "resource": "" }
q22623
OneviewSDK.Resource.exists?
train
def exists?(header = self.class::DEFAULT_REQUEST_HEADER) retrieval_keys = self.class::UNIQUE_IDENTIFIERS.reject { |k| @data[k].nil? } raise IncompleteResource, "Must set resource #{self.class::UNIQUE_IDENTIFIERS.join(' or ')} before trying to retrieve!" if retrieval_keys.empty? retrieval_keys.each do |k| results = self.class.find_by(@client, { k => @data[k] }, self.class::BASE_URI, header) return true if results.size == 1 end false end
ruby
{ "resource": "" }
q22624
OneviewSDK.Resource.deep_merge!
train
def deep_merge!(other_data, target_data = @data) raise 'Both arguments should be a object Hash' unless other_data.is_a?(Hash) && target_data.is_a?(Hash) other_data.each do |key, value| value_target = target_data[key.to_s] if value_target.is_a?(Hash) && value.is_a?(Hash) deep_merge!(value, value_target) else target_data[key.to_s] = value end end end
ruby
{ "resource": "" }
q22625
OneviewSDK.Resource.set_all
train
def set_all(params = self.class::DEFAULT_REQUEST_HEADER) params = params.data if params.class <= Resource params = Hash[params.map { |(k, v)| [k.to_s, v] }] params.each { |key, value| set(key.to_s, value) } self end
ruby
{ "resource": "" }
q22626
OneviewSDK.Resource.set
train
def set(key, value) method_name = "validate_#{key}" send(method_name.to_sym, value) if respond_to?(method_name.to_sym) @data[key.to_s] = value end
ruby
{ "resource": "" }
q22627
OneviewSDK.Resource.create
train
def create(header = self.class::DEFAULT_REQUEST_HEADER) ensure_client options = {}.merge(header).merge('body' => @data) response = @client.rest_post(self.class::BASE_URI, options, @api_version) body = @client.response_handler(response) set_all(body) self end
ruby
{ "resource": "" }
q22628
OneviewSDK.Resource.create!
train
def create!(header = self.class::DEFAULT_REQUEST_HEADER) temp = self.class.new(@client, @data) temp.delete(header) if temp.retrieve!(header) create(header) end
ruby
{ "resource": "" }
q22629
OneviewSDK.Resource.refresh
train
def refresh(header = self.class::DEFAULT_REQUEST_HEADER) ensure_client && ensure_uri response = @client.rest_get(@data['uri'], header, @api_version) body = @client.response_handler(response) set_all(body) self end
ruby
{ "resource": "" }
q22630
OneviewSDK.Resource.update
train
def update(attributes = {}, header = self.class::DEFAULT_REQUEST_HEADER) set_all(attributes) ensure_client && ensure_uri options = {}.merge(header).merge('body' => @data) response = @client.rest_put(@data['uri'], options, @api_version) @client.response_handler(response) self end
ruby
{ "resource": "" }
q22631
OneviewSDK.Resource.delete
train
def delete(header = self.class::DEFAULT_REQUEST_HEADER) ensure_client && ensure_uri response = @client.rest_delete(@data['uri'], header, @api_version) @client.response_handler(response) true end
ruby
{ "resource": "" }
q22632
OneviewSDK.Resource.to_file
train
def to_file(file_path, format = :json) format = :yml if %w[.yml .yaml].include? File.extname(file_path) temp_data = { type: self.class.name, api_version: @api_version, data: @data } case format.to_sym when :json File.open(file_path, 'w') { |f| f.write(JSON.pretty_generate(temp_data)) } when :yml, :yaml File.open(file_path, 'w') { |f| f.write(temp_data.to_yaml) } else raise InvalidFormat, "Invalid format: #{format}" end true end
ruby
{ "resource": "" }
q22633
OneviewSDK.Resource.recursive_like?
train
def recursive_like?(other, data = @data) raise "Can't compare with object type: #{other.class}! Must respond_to :each" unless other.respond_to?(:each) other.each do |key, val| return false unless data && data.respond_to?(:[]) if val.is_a?(Hash) return false unless data.class == Hash && recursive_like?(val, data[key.to_s]) elsif val.is_a?(Array) && val.first.is_a?(Hash) data_array = data[key.to_s] || data[key.to_sym] return false unless data_array.is_a?(Array) val.each do |other_item| return false unless data_array.find { |data_item| recursive_like?(other_item, data_item) } end elsif val.to_s != data[key.to_s].to_s && val.to_s != data[key.to_sym].to_s return false end end true end
ruby
{ "resource": "" }
q22634
PayuIndia.Notification.amount_ok?
train
def amount_ok?( order_amount, order_discount = BigDecimal.new( '0.0' ) ) BigDecimal.new( gross ) == order_amount && BigDecimal.new( discount.to_s ) == order_discount end
ruby
{ "resource": "" }
q22635
PayuIndia.ActionViewHelper.payment_form_for_payu
train
def payment_form_for_payu(key, salt, options = {}) if !options.is_a?(Hash) || !key.is_a?(String) || !salt.is_a?(String) concat("Something Wrong! params order -> key (String), salt (String), options (Hash) ") nil else form_options = options.delete(:html) || {} service = PayuIndia::Helper.new(key, salt, options) result = [] result << form_tag(PayuIndia.service_url, form_options.merge(:method => :post)) result << hidden_field_tag('key', key) service.form_fields.each do |field, value| result << hidden_field_tag(field, value) end result << '<input type=submit value=" Pay with PayU ">' result << '</form>' result= result.join("\n") concat(result.respond_to?(:html_safe) ? result.html_safe : result) nil end end
ruby
{ "resource": "" }
q22636
Sprinkle::Package.Rendering.template
train
def template(src, context=binding) eruby = Erubis::Eruby.new(src) eruby.result(context) rescue Object => e raise Sprinkle::Errors::TemplateError.new(e, src, context) end
ruby
{ "resource": "" }
q22637
Sprinkle::Package.Rendering.render
train
def render(filename, context=binding) contents=File.read(expand_filename(filename)) template(contents, context) end
ruby
{ "resource": "" }
q22638
GamedayApi.Pitcher.load_from_id
train
def load_from_id(gid, pid) @gid = gid @pid = pid @position = 'P' @xml_data = GamedayFetcher.fetch_pitcher(gid, pid) @xml_doc = REXML::Document.new(@xml_data) @team_abbrev = @xml_doc.root.attributes["team"] @first_name = @xml_doc.root.attributes["first_name"] @last_name = @xml_doc.root.attributes["last_name"] @jersey_number = @xml_doc.root.attributes["jersey_number"] @height = @xml_doc.root.attributes["height"] @weight = @xml_doc.root.attributes["weight"] @bats = @xml_doc.root.attributes["bats"] @throws = @xml_doc.root.attributes["throws"] @dob = @xml_doc.root.attributes['dob'] set_opponent_stats end
ruby
{ "resource": "" }
q22639
GamedayApi.Pitcher.get_all_starts
train
def get_all_starts(year) results = [] app = get_all_appearances(year) if app.start == true results << app end end
ruby
{ "resource": "" }
q22640
GamedayApi.Pitcher.get_vs_ab
train
def get_vs_ab results = [] abs = get_game.get_atbats abs.each do |ab| if ab.pitcher_id == @pid results << ab end end results end
ruby
{ "resource": "" }
q22641
GamedayApi.Pitcher.get_pitches
train
def get_pitches results = [] ab = get_vs_ab ab.each do |ab| results << ab.pitches end results.flatten end
ruby
{ "resource": "" }
q22642
GamedayApi.BoxScore.load_from_id
train
def load_from_id(gid) @gid = gid @xml_data = GamedayFetcher.fetch_boxscore(gid) @xml_doc = REXML::Document.new(@xml_data) if @xml_doc.root @game = Game.new(@gid) @game.boxscore = self set_basic_info @linescore = LineScore.new @linescore.init(@xml_doc.root.elements["linescore"]) @home_runs = @linescore.home_team_runs @away_runs = @linescore.away_team_runs @game_info = @xml_doc.root.elements["game_info"].text set_batting_text set_cities set_pitchers set_batters set_weather end end
ruby
{ "resource": "" }
q22643
GamedayApi.BoxScore.to_html
train
def to_html(template_filename) gameday_info = GamedayUtil.parse_gameday_id('gid_' + gid) template = ERB.new File.new(File.expand_path(File.dirname(__FILE__) + "/" + template_filename)).read, nil, "%" return template.result(binding) end
ruby
{ "resource": "" }
q22644
GamedayApi.BoxScore.set_basic_info
train
def set_basic_info @game_id = @xml_doc.root.attributes["game_id"] @game_pk = @xml_doc.root.attributes["game_pk"] @home_sport_code = @xml_doc.root.attributes["home_sport_code"] @away_team_code = @xml_doc.root.attributes["away_team_code"] @home_team_code = @xml_doc.root.attributes["home_team_code"] @away_id = @xml_doc.root.attributes["away_id"] @home_id = @xml_doc.root.attributes["home_id"] @away_fname = @xml_doc.root.attributes["away_fname"] @home_fname = @xml_doc.root.attributes["home_fname"] @away_sname = @xml_doc.root.attributes["away_sname"] @home_sname = @xml_doc.root.attributes["home_sname"] @date = @xml_doc.root.attributes["date"] @away_wins = @xml_doc.root.attributes["away_wins"] @away_loss = @xml_doc.root.attributes["away_loss"] @home_wins = @xml_doc.root.attributes["home_wins"] @home_loss = @xml_doc.root.attributes["home_loss"] @status_ind = @xml_doc.root.attributes["status_ind"] end
ruby
{ "resource": "" }
q22645
GamedayApi.BoxScore.set_pitchers
train
def set_pitchers @pitchers, away_pitchers, home_pitchers = [], [], [] count = 1 @xml_doc.elements.each("boxscore/pitching[@team_flag='away']/pitcher") { |element| pitcher = PitchingAppearance.new pitcher.init(@gid, element, count) count += 1 away_pitchers.push pitcher } count = 1 @xml_doc.elements.each("boxscore/pitching[@team_flag='home']/pitcher") { |element| pitcher = PitchingAppearance.new pitcher.init(@gid, element, count) count += 1 home_pitchers.push pitcher } @pitchers << away_pitchers @pitchers << home_pitchers end
ruby
{ "resource": "" }
q22646
GamedayApi.BoxScore.set_batters
train
def set_batters @batters, away_batters, home_batters = [], [], [] @xml_doc.elements.each("boxscore/batting[@team_flag='away']/batter") { |element| batter = BattingAppearance.new batter.init(element) away_batters.push batter } @xml_doc.elements.each("boxscore/batting[@team_flag='home']/batter") { |element| batter = BattingAppearance.new batter.init(element) home_batters.push batter } @batters << away_batters @batters << home_batters end
ruby
{ "resource": "" }
q22647
GamedayApi.Team.all_games
train
def all_games(year) if !@games puts 'Finding all games for team...' results = [] (START_MONTH..END_MONTH).each do |month| puts "Month: " + month.to_s month_s = GamedayUtil.convert_digit_to_string(month) (1..31).each do |date| if !GamedayUtil.is_date_valid(month, date) next end date_s = GamedayUtil.convert_digit_to_string(date) games = games_for_date(year, month_s, date_s) if games # make sure game was not postponed good_games = games.select { |g| g.get_boxscore.status_ind != 'P' } good_games.each do |game| results << game end end end end @games = results end @games end
ruby
{ "resource": "" }
q22648
GamedayApi.Team.all_home_games
train
def all_home_games(year) games = all_games(year) results = games.select {|g| g.home_team_abbrev == @abrev } end
ruby
{ "resource": "" }
q22649
GamedayApi.Team.all_away_games
train
def all_away_games(year) games = all_games(year) results = games.select {|g| g.visit_team_abbrev == @abrev } end
ruby
{ "resource": "" }
q22650
GamedayApi.Team.games_for_date
train
def games_for_date(year, month, day) games_page = GamedayFetcher.fetch_games_page(year, month, day) gids = find_gid_for_date(year, month, day, games_page) if gids results = gids.collect {|gid| Game.new(gid) } else results = nil end results end
ruby
{ "resource": "" }
q22651
GamedayApi.Team.get_leadoff_hitters_by_year
train
def get_leadoff_hitters_by_year(year) results = [] games = all_games(year) games.each do |game| boxscore = game.get_boxscore leadoffs = boxscore.get_leadoff_hitters if game.home_team_abbrev == @abrev results << leadoffs[1] else results << leadoffs[0] end end results end
ruby
{ "resource": "" }
q22652
GamedayApi.Team.get_leadoff_hitters_unique
train
def get_leadoff_hitters_unique(year) hitters = get_leadoff_hitters_by_year(year) h = {} hitters.each {|hitter| h[hitter.batter_name]=hitter} h.values end
ruby
{ "resource": "" }
q22653
GamedayApi.Team.get_cleanup_hitters_by_year
train
def get_cleanup_hitters_by_year(year) results = [] games = all_games(year) games.each do |game| boxscore = game.get_boxscore hitters = boxscore.get_cleanup_hitters if game.home_team_abbrev == @abrev results << hitters[1] else results << hitters[0] end end results end
ruby
{ "resource": "" }
q22654
GamedayApi.Team.get_starters_unique
train
def get_starters_unique(year) pitchers = get_start_pitcher_appearances_by_year(year) h = {} pitchers.each {|pitcher| h[pitcher.pitcher_name]=pitcher} h.values end
ruby
{ "resource": "" }
q22655
GamedayApi.Team.get_closers_unique
train
def get_closers_unique(year) pitchers = get_close_pitcher_appearances_by_year(year) h = {} pitchers.each {|pitcher| h[pitcher.pitcher_name]=pitcher} h.values end
ruby
{ "resource": "" }
q22656
GamedayApi.Team.quality_starts_count
train
def quality_starts_count(year) count = 0 games = all_games(year) games.each do |game| starters = game.get_starting_pitchers if game.home_team_abbrev == @abrev if starters[1].quality_start? count = count + 1 end else if starters[0].quality_start? count = count + 1 end end end count end
ruby
{ "resource": "" }
q22657
GamedayApi.Team.get_opening_day_game
train
def get_opening_day_game(year) schedule = Schedule.new(year) oday = schedule.get_opening_day oday_array = GamedayUtil.parse_date_string(oday) games = games_for_date(oday_array[0], oday_array[1], oday_array[2]) if games[0] == nil games = games_for_date(oday_array[0], oday_array[1], GamedayUtil.convert_digit_to_string(oday_array[2].to_i + 1)) end return games[0] end
ruby
{ "resource": "" }
q22658
GamedayApi.Team.opening_day_roster
train
def opening_day_roster(year) game = get_opening_day_game(year) rosters = game.get_rosters rosters[0].team_name == city + ' ' + name ? rosters[0] : rosters[1] end
ruby
{ "resource": "" }
q22659
GamedayApi.Gameday.get_all_gids_for_date
train
def get_all_gids_for_date(year, month, day) begin gids = [] url = GamedayUtil.build_day_url(year, month, date) connection = GamedayUtil.get_connection(url) if connection @hp = Hpricot(connection) a = @hp.at('ul') (a/"a").each do |link| if link.inner_html.include?('gid') str = link.inner_html gids.push str[5..str.length-2] end end end connection.close return gids rescue puts "No games data found for #{year}, #{month}, #{day}." end end
ruby
{ "resource": "" }
q22660
GamedayApi.Player.load_from_id
train
def load_from_id(gid, pid) @gid = gid @pid = pid # fetch players.xml file @xml_data = GamedayFetcher.fetch_players(gid) @xml_doc = REXML::Document.new(@xml_data) # find specific player in the file pelement = @xml_doc.root.elements["team/player[@id=#{pid}]"] init(pelement, gid) end
ruby
{ "resource": "" }
q22661
GamedayApi.Player.init_pitcher_from_scoreboard
train
def init_pitcher_from_scoreboard(element) @first = element.attributes['first'] @last = element.attributes['last'] @wins = element.attributes['wins'] @losses = element.attributes['losses'] @era = element.attributes['era'] end
ruby
{ "resource": "" }
q22662
GamedayApi.Player.at_bats_count
train
def at_bats_count gameday_info = GamedayUtil.parse_gameday_id(@gid) appearances = get_all_appearances(gameday_info["year"]) count = appearances.inject(0) {|sum, a| sum + a.ab.to_i } end
ruby
{ "resource": "" }
q22663
GamedayApi.Player.init
train
def init(element, gid) @gid = gid @pid = element.attributes['id'] @first = element.attributes['first'] @last = element.attributes['last'] @num= element.attributes['num'] @boxname = element.attributes['boxname'] @rl, = element.attributes['rl'] @position = element.attributes['position'] @status = element.attributes['status'] @bat_order = element.attributes['bat_order'] @game_position = element.attributes['game_position'] @avg = element.attributes['avg'] @hr = element.attributes['hr'] @rbi = element.attributes['rbi'] @wins = element.attributes['wins'] @losses = element.attributes['losses'] @era = element.attributes['era'] set_extra_info end
ruby
{ "resource": "" }
q22664
GamedayApi.DataDownloader.download_all_for_game
train
def download_all_for_game(gid) download_xml_for_game(gid) download_batters_for_game(gid) download_inning_for_game(gid) download_media_for_game(gid) download_notification_for_game(gid) download_onbase_for_game(gid) download_pitchers_for_game(gid) end
ruby
{ "resource": "" }
q22665
GamedayApi.DataDownloader.write_file
train
def write_file(file_path, gd_data) if gd_data && !File.exists?(file_path) FileUtils.mkdir_p(File.dirname(file_path)) File.open(file_path, "wb") do |data| data << gd_data end end end
ruby
{ "resource": "" }
q22666
GamedayApi.Game.load_from_scoreboard
train
def load_from_scoreboard(element) @away_innings = [] @home_innings = [] @scoreboard_game_id = element.attributes['id'] @ampm = element.attributes['ampm'] @venue = element.attributes['venue'] @game_pk = element.attributes['game_pk'] @time = element.attributes['time'] @time_zone = element.attributes['time_zone'] @game_type = element.attributes['game_type'] @away_name_abbrev = element.attributes['away_name_abbrev'] @home_name_abbrev = element.attributes['home_name_abbrev'] @away_code = element.attributes['away_code'] @away_file_code = element.attributes['away_file_code'] @away_team_id = element.attributes['away_team_id'] @away_team_city = element.attributes['away_team_city'] @away_team_name = element.attributes['away_team_name'] @away_division = element.attributes['away_division'] @home_code = element.attributes['home_code'] @home_file_code = element.attributes['home_file_code'] @home_team_id = element.attributes['home_team_id'] @home_team_city = element.attributes['home_team_city'] @home_team_name = element.attributes['home_team_name'] @home_division = element.attributes['home_division'] @day = element.attributes['day'] @gameday_sw = element.attributes['gameday_sw'] @away_games_back = element.attributes['away_games_back'] @home_games_back = element.attributes['home_games_back'] @away_games_back_wildcard = element.attributes['away_games_back_wildcard'] @home_games_back_wildcard = element.attributes['home_games_back_wildcard'] @venue_w_chan_loc = element.attributes['venue_w_chan_loc'] @gameday = element.attributes['gameday'] @away_win = element.attributes['away_win'] @away_loss = element.attributes['away_loss'] @home_win = element.attributes['home_win'] @home_loss = element.attributes['home_loss'] @league = element.attributes['league'] set_status(element) set_innings(element) set_totals(element) set_pitchers(element) set_homeruns(element) end
ruby
{ "resource": "" }
q22667
GamedayApi.Game.set_status
train
def set_status(element) element.elements.each("status") { |status| @status = GameStatus.new @status.status = status.attributes['status'] @status.ind = status.attributes['ind'] @status.reason = status.attributes['reason'] @status.inning = status.attributes['inning'] @status.top_inning = status.attributes['top_inning'] @status.b = status.attributes['b'] @status.s = status.attributes['s'] @status.o = status.attributes['o'] } end
ruby
{ "resource": "" }
q22668
GamedayApi.Game.set_innings
train
def set_innings(element) element.elements.each("linescore/inning") { |element| @away_innings << element.attributes['away'] @home_innings << element.attributes['home'] } end
ruby
{ "resource": "" }
q22669
GamedayApi.Game.set_homeruns
train
def set_homeruns(element) @homeruns = [] element.elements.each("home_runs/player") do |hr| player = Player.new player.last = hr.attributes['last'] player.first = hr.attributes['first'] player.hr = hr.attributes['hr'] player.std_hr = hr.attributes['std_hr'] player.team_code = hr.attributes['team_code'] @homeruns << player end end
ruby
{ "resource": "" }
q22670
GamedayApi.Game.get_pitchers
train
def get_pitchers(home_or_away) if self.gid bs = get_boxscore if home_or_away == 'away' bs.pitchers[0] else bs.pitchers[1] end else puts "No data for input specified" end end
ruby
{ "resource": "" }
q22671
GamedayApi.Game.get_pitches
train
def get_pitches(pid) results = [] atbats = get_atbats atbats.each do |ab| if ab.pitcher_id == pid results << ab.pitches end end results.flatten end
ruby
{ "resource": "" }
q22672
GamedayApi.Game.get_batters
train
def get_batters(home_or_away) if self.gid bs = get_boxscore if home_or_away == 'away' bs.batters[0] else bs.batters[1] end else puts "No data for input specified" end end
ruby
{ "resource": "" }
q22673
GamedayApi.Game.get_winner
train
def get_winner ls = get_boxscore.linescore if ls.home_team_runs > ls.away_team_runs return home_team_abbrev else return visit_team_abbrev end end
ruby
{ "resource": "" }
q22674
GamedayApi.Game.get_innings
train
def get_innings if @innings.length == 0 inn_count = get_num_innings (1..get_num_innings).each do |inn| inning = Inning.new inning.load_from_id(@gid, inn) @innings << inning end end @innings end
ruby
{ "resource": "" }
q22675
GamedayApi.Game.get_atbats
train
def get_atbats atbats = [] innings = get_innings innings.each do |inning| inning.top_atbats.each do |atbat| atbats << atbat end inning.bottom_atbats.each do |atbat| atbats << atbat end end atbats end
ruby
{ "resource": "" }
q22676
GamedayApi.LineScore.init
train
def init(element) @xml_doc = element self.away_team_runs = element.attributes["away_team_runs"] self.away_team_hits = element.attributes["away_team_hits"] self.away_team_errors = element.attributes["away_team_errors"] self.home_team_runs = element.attributes["home_team_runs"] self.home_team_hits = element.attributes["home_team_hits"] self.home_team_errors = element.attributes["home_team_errors"] # Set score by innings set_innings end
ruby
{ "resource": "" }
q22677
GamedayApi.BattingAppearance.get_player
train
def get_player if !self.player # retrieve player object player = Player.new player.init() self.player = player end self.player end
ruby
{ "resource": "" }
q22678
GamedayApi.Inning.load_from_id
train
def load_from_id(gid, inning) @top_atbats = [] @bottom_atbats = [] @gid = gid begin @xml_data = GamedayFetcher.fetch_inningx(gid, inning) @xml_doc = REXML::Document.new(@xml_data) if @xml_doc.root @num = @xml_doc.root.attributes["num"] @away_team = @xml_doc.root.attributes["away_team"] @home_team = @xml_doc.root.attributes["home_team"] set_top_ab set_bottom_ab end rescue puts "Could not load inning file for #{gid}, inning #{inning.to_s}" end end
ruby
{ "resource": "" }
q22679
GamedayApi.Roster.init
train
def init(element, gid) self.gid = gid self.team_name = element.attributes['name'] self.id = element.attributes['id'] self.type = element.attributes['type'] self.players = [] self.coaches = [] self.set_players(element) self.set_coaches(element) end
ruby
{ "resource": "" }
q22680
GrapeDeviseTokenAuth.DeviseInterface.set_user_in_warden
train
def set_user_in_warden(scope, resource) scope = Devise::Mapping.find_scope!(scope) warden.set_user(resource, scope: scope, store: false) end
ruby
{ "resource": "" }
q22681
GamedayApi.DbImporter.import_team_for_month
train
def import_team_for_month(team_abbrev, year, month) start_date = Date.new(year.to_i, month.to_i) # first day of month end_date = (start_date >> 1)-1 # last day of month ((start_date)..(end_date)).each do |dt| puts year.to_s + '/' + month.to_s + '/' + dt.day team = Team.new('det') games = team.games_for_date(year, month, dt.day.to_s) games.each do |game| import_for_game(game.gid) end end end
ruby
{ "resource": "" }
q22682
Beaker.Docker.install_ssh_components
train
def install_ssh_components(container, host) case host['platform'] when /ubuntu/, /debian/ container.exec(%w(apt-get update)) container.exec(%w(apt-get install -y openssh-server openssh-client)) when /cumulus/ container.exec(%w(apt-get update)) container.exec(%w(apt-get install -y openssh-server openssh-client)) when /fedora-(2[2-9])/ container.exec(%w(dnf clean all)) container.exec(%w(dnf install -y sudo openssh-server openssh-clients)) container.exec(%w(ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key)) container.exec(%w(ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key)) when /^el-/, /centos/, /fedora/, /redhat/, /eos/ container.exec(%w(yum clean all)) container.exec(%w(yum install -y sudo openssh-server openssh-clients)) container.exec(%w(ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key)) container.exec(%w(ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key)) when /opensuse/, /sles/ container.exec(%w(zypper -n in openssh)) container.exec(%w(ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key)) container.exec(%w(ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key)) container.exec(%w(sed -ri 's/^#?UsePAM .*/UsePAM no/' /etc/ssh/sshd_config)) when /archlinux/ container.exec(%w(pacman --noconfirm -Sy archlinux-keyring)) container.exec(%w(pacman --noconfirm -Syu)) container.exec(%w(pacman -S --noconfirm openssh)) container.exec(%w(ssh-keygen -A)) container.exec(%w(sed -ri 's/^#?UsePAM .*/UsePAM no/' /etc/ssh/sshd_config)) container.exec(%w(systemctl enable sshd)) when /alpine/ container.exec(%w(apk add --update openssh)) container.exec(%w(ssh-keygen -A)) else # TODO add more platform steps here raise "platform #{host['platform']} not yet supported on docker" end # Make sshd directory, set root password container.exec(%w(mkdir -p /var/run/sshd)) container.exec(['/bin/sh', '-c', "echo root:#{root_password} | chpasswd"]) end
ruby
{ "resource": "" }
q22683
Beaker.Docker.fix_ssh
train
def fix_ssh(container, host=nil) @logger.debug("Fixing ssh on container #{container.id}") container.exec(['sed','-ri', 's/^#?PermitRootLogin .*/PermitRootLogin yes/', '/etc/ssh/sshd_config']) container.exec(['sed','-ri', 's/^#?PasswordAuthentication .*/PasswordAuthentication yes/', '/etc/ssh/sshd_config']) container.exec(['sed','-ri', 's/^#?UseDNS .*/UseDNS no/', '/etc/ssh/sshd_config']) # Make sure users with a bunch of SSH keys loaded in their keyring can # still run tests container.exec(['sed','-ri', 's/^#?MaxAuthTries.*/MaxAuthTries 1000/', '/etc/ssh/sshd_config']) if host if host['platform'] =~ /alpine/ container.exec(%w(/usr/sbin/sshd)) else container.exec(%w(service ssh restart)) end end end
ruby
{ "resource": "" }
q22684
Beaker.Docker.find_container
train
def find_container(host) id = host['docker_container_id'] name = host['docker_container_name'] return unless id || name containers = ::Docker::Container.all if id @logger.debug("Looking for an existing container with ID #{id}") container = containers.select { |c| c.id == id }.first end if name && container.nil? @logger.debug("Looking for an existing container with name #{name}") container = containers.select do |c| c.info['Names'].include? "/#{name}" end.first end return container unless container.nil? @logger.debug("Existing container not found") end
ruby
{ "resource": "" }
q22685
GamedayApi.Players.load_from_id
train
def load_from_id(gid) @gid = gid @rosters = [] @umpires = {} @xml_data = GamedayFetcher.fetch_players(gid) @xml_doc = REXML::Document.new(@xml_data) if @xml_doc.root self.set_rosters self.set_umpires end end
ruby
{ "resource": "" }
q22686
GamedayApi.PitchfxDbManager.update_rosters
train
def update_rosters(game, away_id, home_id) game_id = find_or_create_game(game, nil, nil) gameday_info = GamedayUtil.parse_gameday_id('gid_' + game.gid) active_date = "#{gameday_info['year']}/#{gameday_info['month']}/#{gameday_info['day']}" away_res = @db.query("select id from rosters where team_id = '#{away_id}' and active_date = '#{active_date}'") away_roster_id=0 found = false away_res.each do |row| found = true away_roster_id = row['id'] end @db.query("UPDATE rosters SET game_id = '#{game_id}', home_or_away = 'a' WHERE id = '#{away_roster_id}'") home_res = @db.query("select id from rosters where team_id = '#{home_id}' and active_date = '#{active_date}'") home_roster_id=0 found = false home_res.each do |row| found = true home_roster_id = row['id'] end @db.query("UPDATE rosters SET game_id = '#{game_id}', home_or_away = 'h' WHERE id = '#{home_roster_id}'") end
ruby
{ "resource": "" }
q22687
GamedayApi.PitchfxDbManager.update_umpire_ids_for_games
train
def update_umpire_ids_for_games ump_id_hp = nil ump_id_1b = nil ump_id_2b = nil ump_id_3b = nil res = @db.query("select id, umpire_hp_id, umpire_1b_id, umpire_2b_id, umpire_3b_id from games") res.each do |row| # each game game_id = row[0] umpire_hp_id = row['umpire_hp_id'] umpire_1b_id = row['umpire_1b_id'] umpire_2b_id = row['umpire_2b_id'] umpire_3b_id = row['umpire_3b_id'] # look up umpire record for hp ump ump_id_hp = get_first_occurance_of_umpire(umpire_hp_id) ump_id_1b = get_first_occurance_of_umpire(umpire_1b_id) ump_id_2b = get_first_occurance_of_umpire(umpire_2b_id) ump_id_3b = get_first_occurance_of_umpire(umpire_3b_id) # update game with correct ump ids @db.query("UPDATE games SET umpire_hp_id='#{ump_id_hp}',umpire_1b_id='#{ump_id_1b}', umpire_2b_id='#{ump_id_2b}', umpire_3b_id='#{ump_id_3b}' WHERE id=#{game_id}") end end
ruby
{ "resource": "" }
q22688
GamedayApi.EventLog.load_from_id
train
def load_from_id(gid) @gid = gid @xml_data = GamedayFetcher.fetch_eventlog(gid) @xml_doc = REXML::Document.new(@xml_data) if @xml_doc.root set_teams set_events end end
ruby
{ "resource": "" }
q22689
GamedayApi.EventLog.set_teams
train
def set_teams @xml_doc.elements.each("game/team[@home_team='false']") do |element| @away_team = element.attributes["name"] end @xml_doc.elements.each("game/team[@home_team='true']") do |element| @home_team = element.attributes["name"] end end
ruby
{ "resource": "" }
q22690
Jimson.Server.call
train
def call(env) req = Rack::Request.new(env) resp = Rack::Response.new return resp.finish if !req.post? resp.write process(req.body.read) resp.finish end
ruby
{ "resource": "" }
q22691
Logdna.Client.buffer
train
def buffer(msg, opts) buffer_size = write_to_buffer(msg, opts) unless buffer_size.nil? process_buffer(buffer_size) end end
ruby
{ "resource": "" }
q22692
Logdna.Client.flush
train
def flush() if defined? @@request and !@@request.nil? request_messages = [] @lock.synchronize do request_messages = @messages @buffer.truncate(0) @messages = [] end return if request_messages.empty? real = { e: 'ls', ls: request_messages, }.to_json @@request.body = real @response = Net::HTTP.start(@uri.hostname, @uri.port, use_ssl: @uri.scheme == 'https') do |http| http.request(@@request) end # don't kill @task if this was executed from self.buffer # don't kill @task if there are queued messages unless @buffer_over_limit || @messages.any? || @task.nil? @task.shutdown @task.kill end end end
ruby
{ "resource": "" }
q22693
Riddle.Client.run
train
def run response = Response.new request(:search, @queue) results = @queue.collect do result = { :matches => [], :fields => [], :attributes => {}, :attribute_names => [], :words => {} } result[:status] = response.next_int case result[:status] when Statuses[:warning] result[:warning] = response.next when Statuses[:error] result[:error] = response.next next result end result[:fields] = response.next_array attributes = response.next_int attributes.times do attribute_name = response.next type = response.next_int result[:attributes][attribute_name] = type result[:attribute_names] << attribute_name end result_attribute_names_and_types = result[:attribute_names]. inject([]) { |array, attr| array.push([ attr, result[:attributes][attr] ]) } matches = response.next_int is_64_bit = response.next_int result[:matches] = (0...matches).map do |i| doc = is_64_bit > 0 ? response.next_64bit_int : response.next_int weight = response.next_int current_match_attributes = {} result_attribute_names_and_types.each do |attr, type| current_match_attributes[attr] = attribute_from_type(type, response) end {:doc => doc, :weight => weight, :index => i, :attributes => current_match_attributes} end result[:total] = response.next_int.to_i || 0 result[:total_found] = response.next_int.to_i || 0 result[:time] = ('%.3f' % (response.next_int / 1000.0)).to_f || 0.0 words = response.next_int words.times do word = response.next docs = response.next_int hits = response.next_int result[:words][word] = {:docs => docs, :hits => hits} end result end @queue.clear results rescue Riddle::OutOfBoundsError => error raise error rescue => original error = ResponseError.new original.message error.original = original raise error end
ruby
{ "resource": "" }
q22694
Riddle.Client.query
train
def query(search, index = '*', comments = '') @queue.clear @queue << query_message(search, index, comments) self.run.first end
ruby
{ "resource": "" }
q22695
Riddle.Client.update
train
def update(index, attributes, values_by_doc) response = Response.new request( :update, update_message(index, attributes, values_by_doc) ) response.next_int end
ruby
{ "resource": "" }
q22696
Riddle.Client.query_message
train
def query_message(search, index, comments = '') message = Message.new # Mode, Limits message.append_ints @offset, @limit, MatchModes[@match_mode] # Ranking message.append_int RankModes[@rank_mode] message.append_string @rank_expr if @rank_mode == :expr # Sort Mode message.append_int SortModes[@sort_mode] message.append_string @sort_by # Query message.append_string search # Weights message.append_int @weights.length message.append_ints *@weights # Index message.append_string index # ID Range message.append_int 1 message.append_64bit_ints @id_range.first, @id_range.last # Filters message.append_int @filters.length @filters.each { |filter| message.append filter.query_message } # Grouping message.append_int GroupFunctions[@group_function] message.append_string @group_by message.append_int @max_matches message.append_string @group_clause message.append_ints @cut_off, @retry_count, @retry_delay message.append_string @group_distinct # Anchor Point if @anchor.empty? message.append_int 0 else message.append_int 1 message.append_string @anchor[:latitude_attribute] message.append_string @anchor[:longitude_attribute] message.append_floats @anchor[:latitude], @anchor[:longitude] end # Per Index Weights message.append_int @index_weights.length @index_weights.each do |key,val| message.append_string key.to_s message.append_int val end # Max Query Time message.append_int @max_query_time # Per Field Weights message.append_int @field_weights.length @field_weights.each do |key,val| message.append_string key.to_s message.append_int val end message.append_string comments return message.to_s if Versions[:search] < 0x116 # Overrides message.append_int @overrides.length @overrides.each do |key,val| message.append_string key.to_s message.append_int AttributeTypes[val[:type]] message.append_int val[:values].length val[:values].each do |id,map| message.append_64bit_int id method = case val[:type] when :float :append_float when :bigint :append_64bit_int else :append_int end message.send method, map end end message.append_string @select message.to_s end
ruby
{ "resource": "" }
q22697
Riddle.Client.excerpts_message
train
def excerpts_message(options) message = Message.new message.append [0, excerpt_flags(options)].pack('N2') # 0 = mode message.append_string options[:index] message.append_string options[:words] # options message.append_string options[:before_match] message.append_string options[:after_match] message.append_string options[:chunk_separator] message.append_ints options[:limit], options[:around] message.append_array options[:docs] message.to_s end
ruby
{ "resource": "" }
q22698
Riddle.Client.update_message
train
def update_message(index, attributes, values_by_doc) message = Message.new message.append_string index message.append_array attributes message.append_int values_by_doc.length values_by_doc.each do |key,values| message.append_64bit_int key # document ID message.append_ints *values # array of new values (integers) end message.to_s end
ruby
{ "resource": "" }
q22699
Riddle.Client.keywords_message
train
def keywords_message(query, index, return_hits) message = Message.new message.append_string query message.append_string index message.append_int return_hits ? 1 : 0 message.to_s end
ruby
{ "resource": "" }