_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q27400
Koi.Entity.method_missing
test
def method_missing meth, *args, &blk if meth.to_s.end_with?('?') && Status.include?(s = meth.to_s.chop.to_sym) self[:status] == s else super end end
ruby
{ "resource": "" }
q27401
AMEE.Connection.v3_get
test
def v3_get(path, options = {}) # Create request parameters get_params = { :method => "get" } get_params[:params] = options unless options.empty? # Send request (with caching) v3_do_request(get_params, path, :cache => true) end
ruby
{ "resource": "" }
q27402
AMEE.Connection.v3_put
test
def v3_put(path, options = {}) # Expire cached objects from parent on down expire_matching "#{parent_path(path)}.*" # Create request parameters put_params = { :method => "put", :body => options[:body] ? options[:body] : form_encode(options) } if options[:content_type] put_params[:headers] = { :'Content-Type' => content_type(options[:content_type]) } end # Request v3_do_request(put_params, path) end
ruby
{ "resource": "" }
q27403
AMEE.Connection.v3_do_request
test
def v3_do_request(params, path, options = {}) req = Typhoeus::Request.new("https://#{v3_hostname}#{path}", v3_defaults.merge(params)) response = do_request(req, :xml, options) options[:return_obj]==true ? response : response.body end
ruby
{ "resource": "" }
q27404
FastTCPN.TimedPlace.add
test
def add(token, timestamp = nil) @net.call_callbacks(:place, :add, Event.new(@name, [token], @net)) unless @net.nil? if timestamp.nil? @marking.add token else @marking.add token, timestamp end end
ruby
{ "resource": "" }
q27405
DevTrainingBot.GoogleDriveService.authorize
test
def authorize client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH) token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH) authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store) user_id = 'default' credentials = authorizer.get_credentials(user_id) if credentials.nil? url = authorizer.get_authorization_url(base_url: OOB_URI) puts 'Open the following URL in the browser and enter the ' \ "resulting code after authorization:\n" + url code = STDIN.gets credentials = authorizer.get_and_store_credentials_from_code( user_id: user_id, code: code, base_url: OOB_URI ) end credentials end
ruby
{ "resource": "" }
q27406
AMEE.Connection.get
test
def get(path, data = {}) # Allow format override format = data.delete(:format) || @format # Add parameters to URL query string get_params = { :method => "get", :verbose => DEBUG } get_params[:params] = data unless data.empty? # Create GET request get = Typhoeus::Request.new("#{protocol}#{@server}#{path}", get_params) # Send request do_request(get, format, :cache => true) end
ruby
{ "resource": "" }
q27407
AMEE.Connection.post
test
def post(path, data = {}) # Allow format override format = data.delete(:format) || @format # Clear cache expire_matching "#{raw_path(path)}.*" # Extract return unit params query_params = {} query_params[:returnUnit] = data.delete(:returnUnit) if data[:returnUnit] query_params[:returnPerUnit] = data.delete(:returnPerUnit) if data[:returnPerUnit] # Create POST request post_params = { :verbose => DEBUG, :method => "post", :body => form_encode(data) } post_params[:params] = query_params unless query_params.empty? post = Typhoeus::Request.new("#{protocol}#{@server}#{path}", post_params) # Send request do_request(post, format) end
ruby
{ "resource": "" }
q27408
AMEE.Connection.raw_post
test
def raw_post(path, body, options = {}) # Allow format override format = options.delete(:format) || @format # Clear cache expire_matching "#{raw_path(path)}.*" # Create POST request post = Typhoeus::Request.new("#{protocol}#{@server}#{path}", :verbose => DEBUG, :method => "post", :body => body, :headers => { :'Content-type' => options[:content_type] || content_type(format) } ) # Send request do_request(post, format) end
ruby
{ "resource": "" }
q27409
AMEE.Connection.put
test
def put(path, data = {}) # Allow format override format = data.delete(:format) || @format # Clear cache expire_matching "#{parent_path(path)}.*" # Extract return unit params query_params = {} query_params[:returnUnit] = data.delete(:returnUnit) if data[:returnUnit] query_params[:returnPerUnit] = data.delete(:returnPerUnit) if data[:returnPerUnit] # Create PUT request put_params = { :verbose => DEBUG, :method => "put", :body => form_encode(data) } put_params[:params] = query_params unless query_params.empty? put = Typhoeus::Request.new("#{protocol}#{@server}#{path}", put_params) # Send request do_request(put, format) end
ruby
{ "resource": "" }
q27410
AMEE.Connection.raw_put
test
def raw_put(path, body, options = {}) # Allow format override format = options.delete(:format) || @format # Clear cache expire_matching "#{parent_path(path)}.*" # Create PUT request put = Typhoeus::Request.new("#{protocol}#{@server}#{path}", :verbose => DEBUG, :method => "put", :body => body, :headers => { :'Content-type' => options[:content_type] || content_type(format) } ) # Send request do_request(put, format) end
ruby
{ "resource": "" }
q27411
AMEE.Connection.authenticate
test
def authenticate # :x_amee_source = "X-AMEE-Source".to_sym request = Typhoeus::Request.new("#{protocol}#{@server}/auth/signIn", :method => "post", :verbose => DEBUG, :headers => { :Accept => content_type(:xml), }, :body => form_encode(:username=>@username, :password=>@password) ) hydra.queue(request) hydra.run response = request.response @auth_token = response.headers_hash['AuthToken'] d {request.url} d {response.code} d {@auth_token} connection_failed if response.code == 0 unless authenticated? raise AMEE::AuthFailed.new("Authentication failed. Please check your username and password. (tried #{@username},#{@password})") end # Detect API version if response.body.is_json? @version = JSON.parse(response.body)["user"]["apiVersion"].to_f elsif response.body.is_xml? @version = REXML::Document.new(response.body).elements['Resources'].elements['SignInResource'].elements['User'].elements['ApiVersion'].text.to_f else @version = 1.0 end end
ruby
{ "resource": "" }
q27412
AMEE.Connection.response_ok?
test
def response_ok?(response, request) # first allow for debugging d {request.object_id} d {request} d {response.object_id} d {response.code} d {response.headers_hash} d {response.body} case response.code.to_i when 502, 503, 504 raise AMEE::ConnectionFailed.new("A connection error occurred while talking to AMEE: HTTP response code #{response.code}.\nRequest: #{request.method.upcase} #{request.url.gsub(request.host, '')}") when 408 raise AMEE::TimeOut.new("Request timed out.") when 404 raise AMEE::NotFound.new("The URL was not found on the server.\nRequest: #{request.method.upcase} #{request.url.gsub(request.host, '')}") when 403 raise AMEE::PermissionDenied.new("You do not have permission to perform the requested operation.\nRequest: #{request.method.upcase} #{request.url.gsub(request.host, '')}\n#{request.body}\Response: #{response.body}") when 401 authenticate return false when 400 if response.body.include? "would have resulted in a duplicate resource being created" raise AMEE::DuplicateResource.new("The specified resource already exists. This is most often caused by creating an item that overlaps another in time.\nRequest: #{request.method.upcase} #{request.url.gsub(request.host, '')}\n#{request.body}\Response: #{response.body}") else raise AMEE::BadRequest.new("Bad request. This is probably due to malformed input data.\nRequest: #{request.method.upcase} #{request.url.gsub(request.host, '')}\n#{request.body}\Response: #{response.body}") end when 200, 201, 204 return response when 0 connection_failed end # If we get here, something unhandled has happened, so raise an unknown error. raise AMEE::UnknownError.new("An error occurred while talking to AMEE: HTTP response code #{response.code}.\nRequest: #{request.method.upcase} #{request.url}\n#{request.body}\Response: #{response.body}") end
ruby
{ "resource": "" }
q27413
AMEE.Connection.do_request
test
def do_request(request, format = @format, options = {}) # Is this a v3 request? v3_request = request.url.include?("/#{v3_hostname}/") # make sure we have our auth token before we start # any v1 or v2 requests if !@auth_token && !v3_request d "Authenticating first before we hit #{request.url}" authenticate end request.headers['Accept'] = content_type(format) # Set AMEE source header if set request.headers['X-AMEE-Source'] = @amee_source if @amee_source # path+query string only (split with an int limits the number of splits) path_and_query = '/' + request.url.split('/', 4)[3] if options[:cache] # Get response with caching response = cache(path_and_query) { run_request(request, :xml) } else response = run_request(request, :xml) end response end
ruby
{ "resource": "" }
q27414
AMEE.Connection.run_request
test
def run_request(request, format) # Is this a v3 request? v3_request = request.url.include?("/#{v3_hostname}/") # Execute with retries retries = [1] * @retries begin begin d "Queuing the request for #{request.url}" add_authentication_to(request) if @auth_token && !v3_request hydra.queue request hydra.run # Return response if OK end while !response_ok?(request.response, request) # Store updated authToken @auth_token = request.response.headers_hash['AuthToken'] return request.response rescue AMEE::ConnectionFailed, AMEE::TimeOut => e if delay = retries.shift sleep delay retry else raise end end end
ruby
{ "resource": "" }
q27415
FastTCPN.TCPN.timed_place
test
def timed_place(name, keys = {}) place = create_or_find_place(name, keys, TimedPlace) @timed_places[place] = true place end
ruby
{ "resource": "" }
q27416
FastTCPN.TCPN.transition
test
def transition(name) t = find_transition name if t.nil? t = Transition.new name, self @transitions << t end t end
ruby
{ "resource": "" }
q27417
FastTCPN.TCPN.sim
test
def sim @stopped = catch :stop_simulation do begin fired = fire_transitions advanced = move_clock_to find_next_time end while fired || advanced end @stopped = false if @stopped == nil rescue StandardError => e raise SimulationError.new(e) end
ruby
{ "resource": "" }
q27418
FastTCPN.Transition.output
test
def output(place, &block) raise "This is not a Place object!" unless place.kind_of? Place raise "Tried to define output arc without expression! Block is required!" unless block_given? @outputs << OutputArc.new(place, block) end
ruby
{ "resource": "" }
q27419
FastTCPN.Transition.fire
test
def fire(clock = 0) # Marking is shuffled each time before it is # used so here we can take first found binding mapping = Enumerator.new do |y| get_sentry.call(input_markings, clock, y) end.first return false if mapping.nil? tcpn_binding = TCPNBinding.new mapping, input_markings call_callbacks :before, Event.new(@name, tcpn_binding, clock, @net) tokens_for_outputs = @outputs.map do |o| o.block.call(tcpn_binding, clock) end mapping.each do |place_name, token| unless token.kind_of? Token t = if token.instance_of? Array token else [ token ] end t.each do |t| unless t.kind_of? Token raise InvalidToken.new("#{t.inspect} put by sentry for transition `#{name}` in binding for `#{place_name}`") end end end deleted = find_input(place_name).delete(token) if deleted.nil? raise InvalidToken.new("#{token.inspect} put by sentry for transition `#{name}` does not exists in `#{place_name}`") end end @outputs.each do |o| token = tokens_for_outputs.shift o.place.add token unless token.nil? end call_callbacks :after, Event.new(@name, mapping, clock, @net) true rescue InvalidToken raise rescue RuntimeError => e raise FiringError.new(self, e) end
ruby
{ "resource": "" }
q27420
ArtTypograf.Client.send_request
test
def send_request(text) begin request = Net::HTTP::Post.new(@url.path, { 'Content-Type' => 'text/xml', 'SOAPAction' => '"http://typograf.artlebedev.ru/webservices/ProcessText"' }) request.body = form_xml(text, @options) response = Net::HTTP.new(@url.host, @url.port).start do |http| http.request(request) end rescue StandardError => exception raise NetworkError.new(exception.message, exception.backtrace) end if !response.is_a?(Net::HTTPOK) raise NetworkError, "#{response.code}: #{response.message}" end if RESULT =~ response.body body = $1.gsub(/&gt;/, '>').gsub(/&lt;/, '<').gsub(/&amp;/, '&') body.force_encoding("UTF-8").chomp else raise NetworkError, "Can't match result #{response.body}" end end
ruby
{ "resource": "" }
q27421
Beaker.Librarian.install_librarian
test
def install_librarian(opts = {}) # Check for 'librarian_version' option librarian_version = opts[:librarian_version] ||= nil hosts.each do |host| install_package host, 'rubygems' install_package host, 'git' if librarian_version on host, "gem install --no-ri --no-rdoc librarian-puppet -v '#{librarian_version}'" else on host, 'gem install --no-ri --no-rdoc librarian-puppet' end end end
ruby
{ "resource": "" }
q27422
Beaker.Librarian.librarian_install_modules
test
def librarian_install_modules(directory, module_name) hosts.each do |host| sut_dir = File.join('/tmp', module_name) scp_to host, directory, sut_dir on host, "cd #{sut_dir} && librarian-puppet install --clean --verbose --path #{host['distmoduledir']}" puppet_module_install(:source => directory, :module_name => module_name) end end
ruby
{ "resource": "" }
q27423
Sigimera.Client.get_crisis
test
def get_crisis(identifier, params = nil) return nil if identifier.nil? or identifier.empty? endpoint = "/v1/crises/#{identifier}.json?auth_token=#{@auth_token}" endpoint += "&#{URI.encode_www_form params}" if params response = self.get(endpoint) Sigimera::Crisis.new JSON.parse response.body if response and response.body end
ruby
{ "resource": "" }
q27424
Sigimera.Client.get_crises_stat
test
def get_crises_stat response = self.get("/v1/stats/crises.json?auth_token=#{@auth_token}") JSON.parse response.body if response and response.body end
ruby
{ "resource": "" }
q27425
Sigimera.Client.get_user_stat
test
def get_user_stat response = self.get("/v1/stats/users.json?auth_token=#{@auth_token}") JSON.parse response.body if response and response.body end
ruby
{ "resource": "" }
q27426
Pose.ActiveRecordBaseAdditions.posify
test
def posify *source_methods, &block include ModelClassAdditions self.pose_content = proc do text_chunks = source_methods.map { |source| send(source) } text_chunks << instance_eval(&block) if block text_chunks.reject(&:blank?).join(' ') end end
ruby
{ "resource": "" }
q27427
FastTCPN.HashMarking.add
test
def add(objects) unless objects.kind_of? Array objects = [ objects ] end objects.each do |object| value = object if object.instance_of? Hash value = object[:val] end add_token prepare_token(value) end end
ruby
{ "resource": "" }
q27428
FastTCPN.HashMarking.delete
test
def delete(tokens) unless tokens.instance_of? Array tokens = [ tokens ] end removed = tokens.map do |token| validate_token!(token) delete_token(token) end if removed.size == 1 removed.first else removed end end
ruby
{ "resource": "" }
q27429
Pose.Search.add_joins
test
def add_joins arel @query.joins.inject(arel) do |memo, join_data| add_join memo, join_data end end
ruby
{ "resource": "" }
q27430
Pose.Search.add_wheres
test
def add_wheres arel @query.where.inject(arel) { |memo, where| memo.where where } end
ruby
{ "resource": "" }
q27431
Pose.Search.load_classes
test
def load_classes result return if @query.ids_requested? result.each do |clazz, ids| if ids.size > 0 result[clazz] = clazz.where(id: ids) if @query.has_select result[clazz] = result[clazz].select(@query.options[:select]) end end end end
ruby
{ "resource": "" }
q27432
Pose.Search.search_word
test
def search_word word empty_result.tap do |result| data = Assignment.joins(:word) \ .select('pose_assignments.posable_id, pose_assignments.posable_type') \ .where('pose_words.text LIKE ?', "#{word}%") \ .where('pose_assignments.posable_type IN (?)', @query.class_names) data = add_joins data data = add_wheres data Assignment.connection.select_all(data.to_sql).each do |pose_assignment| result[pose_assignment['posable_type']] << pose_assignment['posable_id'].to_i end end end
ruby
{ "resource": "" }
q27433
Pose.Search.search_words
test
def search_words {}.tap do |result| @query.query_words.each do |query_word| search_word(query_word).each do |class_name, ids| merge_search_result_word_matches result, class_name, ids end end end end
ruby
{ "resource": "" }
q27434
GoogleSpreadsheets.Connection.client_login_authorization_header
test
def client_login_authorization_header(http_method, uri) if @user && @password && !@auth_token email = CGI.escape(@user) password = CGI.escape(@password) http = Net::HTTP.new('www.google.com', 443) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE resp, data = http.post('/accounts/ClientLogin', "accountType=HOSTED_OR_GOOGLE&Email=#{email}&Passwd=#{password}&service=wise", { 'Content-Type' => 'application/x-www-form-urlencoded' }) handle_response(resp) @auth_token = (data || resp.body)[/Auth=(.*)/n, 1] end @auth_token ? { 'Authorization' => "GoogleLogin auth=#{@auth_token}" } : {} end
ruby
{ "resource": "" }
q27435
Dev.Project.app_folder
test
def app_folder(app_name = self.current_app) if self.type == :multi if app_name.in? self.main_apps "#{self.folder}/main_apps/#{app_name}" elsif app_name.in? self.engines "#{self.folder}/engines/#{app_name}" end elsif self.type == :single self.folder end end
ruby
{ "resource": "" }
q27436
Dev.Project.app_version_file
test
def app_version_file(app_name = self.current_app) Dir.glob("#{app_folder(app_name)}/lib/**/version.rb").min_by do |filename| filename.chars.count end end
ruby
{ "resource": "" }
q27437
Dev.Project.app_version
test
def app_version(app_name = self.current_app) if File.exists? app_version_file(app_name).to_s File.read(app_version_file(app_name)) .match(/VERSION = '([0-9\.]+)'\n/) .try(:captures).try(:first) else `git tag`.split("\n").first end end
ruby
{ "resource": "" }
q27438
Dev.Project.bump_app_version_to
test
def bump_app_version_to(version) if File.exists? self.app_version_file version_file = self.app_version_file version_content = File.read("#{version_file}") File.open(version_file, 'w+') do |f| f.puts version_content.gsub(/VERSION = '[0-9\.]+'\n/, "VERSION = '#{version}'\n") end end end
ruby
{ "resource": "" }
q27439
Dev.Executable.load_project
test
def load_project config_file = Dir.glob("#{Dir.pwd}/**/dev.yml").first raise ExecutionError.new "No valid configuration files found. Searched for a file named 'dev.yml' "\ "in folder #{Dir.pwd} and all its subdirectories." if config_file.nil? @project = Dev::Project.new(config_file) end
ruby
{ "resource": "" }
q27440
Dev.Executable.help
test
def help puts print "Dev".green print " - available commands:\n" puts print "\tversion\t\t".limegreen print "Prints current version.\n" puts print "\tfeature\t\t".limegreen print "Opens or closes a feature for the current app.\n" print "\t\t\tWarning: the app is determined from the current working directory!\n" print "\t\t\tExample: " print "dev feature open my-new-feature".springgreen print " (opens a new feature for the current app)" print ".\n" print "\t\t\tExample: " print "dev feature close my-new-feature".springgreen print " (closes a developed new feature for the current app)" print ".\n" puts print "\thotfix\t\t".limegreen print "Opens or closes a hotfix for the current app.\n" print "\t\t\tWarning: the app is determined from the current working directory!\n" print "\t\t\tExample: " print "dev hotfix open 0.2.1".springgreen print " (opens a new hotfix for the current app)" print ".\n" print "\t\t\tExample: " print "dev hotfix close 0.2.1".springgreen print " (closes a developed new hotfix for the current app)" print ".\n" puts print "\trelease\t\t".limegreen print "Opens or closes a release for the current app.\n" print "\t\t\tWarning: the app is determined from the current working directory!\n" print "\t\t\tExample: " print "dev release open 0.2.0".springgreen print " (opens a new release for the current app)" print ".\n" print "\t\t\tExample: " print "dev release close 0.2.0".springgreen print " (closes a developed new release for the current app)" print ".\n" puts print "\tpull\t\t".limegreen print "Pulls specified app's git repository, or pulls all apps if none are specified.\n" print "\t\t\tWarning: the pulled branch is the one the app is currently on!\n" print "\t\t\tExample: " print "dev pull [myapp]".springgreen print ".\n" puts print "\tpush\t\t".limegreen print "Commits and pushes the specified app.\n" print "\t\t\tWarning: the pushed branch is the one the app is currently on!\n" print "\t\t\tExample: " print "dev push myapp \"commit message\"".springgreen print ".\n" puts print "\ttest\t\t".limegreen print "Runs the app's test suite. Tests must be written with rspec.\n" print "\t\t\tIt is possibile to specify which app's test suite to run.\n" print "\t\t\tIf nothing is specified, all main app's test suites are run.\n" print "\t\t\tExample: " print "dev test mymainapp myengine".springgreen print " (runs tests for 'mymainapp' and 'myengine')" print ".\n" print "\t\t\tExample: " print "dev test".springgreen print " (runs tests for all main apps and engines within this project)" print ".\n" puts end
ruby
{ "resource": "" }
q27441
FastTCPN.TimedHashMarking.add
test
def add(objects, timestamp = @time) unless objects.kind_of? Array objects = [ objects ] end objects.each do |object| if object.instance_of? Hash timestamp = object[:ts] || 0 object = object[:val] end token = prepare_token(object, timestamp) timestamp = token.timestamp if timestamp > @time add_to_waiting token else add_token token end end end
ruby
{ "resource": "" }
q27442
FastTCPN.TimedHashMarking.time=
test
def time=(time) if time < @time raise InvalidTime.new("You are trying to put back clock from #{@time} back to #{time}") end @time = time @waiting.keys.sort.each do |timestamp| if timestamp > @time @next_time = timestamp break end @waiting[timestamp].each { |token| add_token token } @waiting.delete timestamp end @next_time = 0 if @waiting.empty? @time end
ruby
{ "resource": "" }
q27443
EventMachine.WebSocketClient.send_message
test
def send_message data, binary=false if established? unless @closing @socket.send_data(@encoder.encode(data.to_s, binary ? BINARY_FRAME : TEXT_FRAME)) end else raise WebSocketError.new "can't send on a closed channel" end end
ruby
{ "resource": "" }
q27444
RubyMeetup.AuthenticatedClient.post
test
def post(options) uri = new_uri params = merge_params(options) response = Net::HTTP.post_form(uri, params) unless response.is_a?(Net::HTTPSuccess) raise "#{response.code} #{response.message}\n#{response.body}" end response.body end
ruby
{ "resource": "" }
q27445
RubyMeetup.AuthenticatedClient.delete
test
def delete(options={}) uri = new_uri params = merge_params(options) uri.query = URI.encode_www_form(params) http = Net::HTTP.new(uri.host, uri.port) request = Net::HTTP::Delete.new(uri) # uri or uri.request_uri? response = http.request(request) unless response.is_a?(Net::HTTPSuccess) raise "#{response.code} #{response.message}\n#{response.body}" end true end
ruby
{ "resource": "" }
q27446
Vagrantomatic.Vagrantomatic.instance_metadata
test
def instance_metadata(name) instance = instance(name) config = {} # annotate the raw config hash with data for puppet (and humans...) if instance.configured? config = instance.configfile_hash config["ensure"] = :present else # VM missing or damaged config["ensure"] = :absent end config["name"] = name config end
ruby
{ "resource": "" }
q27447
Vagrantomatic.Vagrantomatic.instances_metadata
test
def instances_metadata() instance_wildcard = File.join(@vagrant_vm_dir, "*", ::Vagrantomatic::Instance::VAGRANTFILE) instances = {} Dir.glob(instance_wildcard).each { |f| elements = f.split(File::SEPARATOR) # /var/lib/vagrantomatic/mycoolvm/Vagrantfile # -----------------------^^^^^^^^------------ name = elements[elements.size - 2] instances[name] = instance_metadata(name) } instances end
ruby
{ "resource": "" }
q27448
Scripto.CsvCommands.csv_read
test
def csv_read(path) lines = begin if path =~ /\.gz$/ Zlib::GzipReader.open(path) do |f| CSV.new(f).read end else CSV.read(path) end end keys = lines.shift.map(&:to_sym) klass = Struct.new(*keys) lines.map { |i| klass.new(*i) } end
ruby
{ "resource": "" }
q27449
Scripto.CsvCommands.csv_write
test
def csv_write(path, rows, cols: nil) atomic_write(path) do |tmp| CSV.open(tmp.path, "wb") { |f| csv_write0(f, rows, cols: cols) } end end
ruby
{ "resource": "" }
q27450
Scripto.CsvCommands.csv_to_s
test
def csv_to_s(rows, cols: nil) string = "" f = CSV.new(StringIO.new(string)) csv_write0(f, rows, cols: cols) string end
ruby
{ "resource": "" }
q27451
RustyJson.RustStruct.add_value
test
def add_value(name, type, subtype = nil) if type.class == RustyJson::RustStruct || subtype.class == RustyJson::RustStruct if type.class == RustyJson::RustStruct t = type type = type.name struct = t elsif subtype.class == RustyJson::RustStruct s = subtype subtype = subtype.name struct = s end @structs << struct RustStruct.add_type(struct.name, struct.name) end @values[name] = [type, subtype] true end
ruby
{ "resource": "" }
q27452
RodeoClown.ELB.rotate
test
def rotate(hsh) current_ec2, new_ec2 = hsh.first cur_instances = EC2.by_tags("Name" => current_ec2.to_s) new_instances = EC2.by_tags("Name" => new_ec2.to_s) register_and_wait new_instances deregister cur_instances end
ruby
{ "resource": "" }
q27453
RodeoClown.ELB.wait_for_state
test
def wait_for_state(instances, exp_state) time = 0 all_good = false loop do all_good = instances.all? do |i| state = i.elb_health[:state] puts "#{i.id}: #{state}" exp_state == state end break if all_good || time > timeout sleep 1 time += 1 end # If timeout before all inservice, deregister and raise error unless all_good raise "Instances are out of service" end end
ruby
{ "resource": "" }
q27454
OWNet.RawConnection.read
test
def read(path) owconnect do |socket| owwrite(socket,:path => path, :function => READ) return to_number(owread(socket).data) end end
ruby
{ "resource": "" }
q27455
OWNet.RawConnection.write
test
def write(path, value) owconnect do |socket| owwrite(socket, :path => path, :value => value.to_s, :function => WRITE) return owread(socket).return_value end end
ruby
{ "resource": "" }
q27456
OWNet.RawConnection.dir
test
def dir(path) owconnect do |socket| owwrite(socket,:path => path, :function => DIR) fields = [] while true response = owread(socket) if response.data fields << response.data else break end end return fields end end
ruby
{ "resource": "" }
q27457
Praxis::Mapper.QueryStatistics.sum_totals_by_model
test
def sum_totals_by_model @sum_totals_by_model ||= begin totals = Hash.new { |hash, key| hash[key] = Hash.new(0) } @queries_by_model.each do |model, queries| totals[model][:query_count] = queries.length queries.each do |query| query.statistics.each do |stat, value| totals[model][stat] += value end end totals[model][:datastore_interaction_time] = totals[model][:datastore_interaction_time] end totals end end
ruby
{ "resource": "" }
q27458
Praxis::Mapper.QueryStatistics.sum_totals
test
def sum_totals @sum_totals ||= begin totals = Hash.new(0) sum_totals_by_model.each do |_, model_totals| model_totals.each do |stat, value| totals[stat] += value end end totals end end
ruby
{ "resource": "" }
q27459
Tai64.Time.to_label
test
def to_label s = '%016x%08x' sec = tai_second ts = if sec >= 0 sec + EPOCH else EPOCH - sec end Label.new s % [ ts, tai_nanosecond ] end
ruby
{ "resource": "" }
q27460
Conject.ObjectContext.put
test
def put(name, object) raise "This ObjectContext already has an instance or configuration for '#{name.to_s}'" if directly_has?(name) Conject.install_object_context(object, self) object.instance_variable_set(:@_conject_contextual_name, name.to_s) @cache[name.to_sym] = object end
ruby
{ "resource": "" }
q27461
Conject.ObjectContext.configure_objects
test
def configure_objects(confs={}) confs.each do |key,opts| key = key.to_sym @object_configs[key] ={} unless has_config?(key) @object_configs[key].merge!(opts) end end
ruby
{ "resource": "" }
q27462
HanselCore.Httperf.httperf
test
def httperf warm_up = false httperf_cmd = build_httperf_cmd if warm_up # Do a warm up run to setup any resources status "\n#{httperf_cmd} (warm up run)" IO.popen("#{httperf_cmd} 2>&1") else IO.popen("#{httperf_cmd} 2>&1") do |pipe| status "\n#{httperf_cmd}" @results << (httperf_result = HttperfResult.new({ :rate => @current_rate, :server => @current_job.server, :port => @current_job.port, :uri => @current_job.uri, :num_conns => @current_job.num_conns, :description => @current_job.description })) HttperfResultParser.new(pipe).parse(httperf_result) end end end
ruby
{ "resource": "" }
q27463
SFKB.REST.url
test
def url(path, params = {}) params = params.inject({}, &@@stringify) path = path.gsub(@@placeholder) { params.delete($1, &@@required) } params = params.inject('', &@@parameterize) [path, params].reject(&:nil?).reject(&:empty?).join('?') end
ruby
{ "resource": "" }
q27464
SFKB.REST.url?
test
def url?(string) return false unless string.to_s =~ url_pattern return false if string.to_s =~ @@placeholder true end
ruby
{ "resource": "" }
q27465
Assit.Assertions.assit_equal
test
def assit_equal(expected, actual, message = "Object expected to be equal") if(expected != actual) message << " expected #{expected} but was #{actual}" assit(false, message) end end
ruby
{ "resource": "" }
q27466
Assit.Assertions.assit_kind_of
test
def assit_kind_of(klass, object, message = "Object of wrong type") if(!object.kind_of?(klass)) message << " (Expected #{klass} but was #{object.class})" assit(false, message) end end
ruby
{ "resource": "" }
q27467
Assit.Assertions.assit_real_string
test
def assit_real_string(object, message = "Not a non-empty string.") unless(object && object.kind_of?(String) && object.strip != "") assit(false, message) end end
ruby
{ "resource": "" }
q27468
Assit.Assertions.assit_block
test
def assit_block(&block) errors = [] assit((block.call(errors) && errors.size == 0), errors.join(', ')) end
ruby
{ "resource": "" }
q27469
QbtClient.WebUI.poll
test
def poll interval: 10, &block raise '#poll requires a block' unless block_given? response_id = 0 loop do res = self.sync response_id if res response_id = res['rid'] yield res end sleep interval end end
ruby
{ "resource": "" }
q27470
QbtClient.WebUI.sync
test
def sync response_id = 0 req = self.class.get '/sync/maindata', format: :json, query: { rid: response_id } res = req.parsed_response if req.success? return res end end
ruby
{ "resource": "" }
q27471
QbtClient.WebUI.add_trackers
test
def add_trackers torrent_hash, urls urls = Array(urls) # Ampersands in urls must be escaped. urls = urls.map { |url| url.gsub('&', '%26') } urls = urls.join('%0A') options = { body: "hash=#{torrent_hash}&urls=#{urls}" } self.class.post('/command/addTrackers', options) end
ruby
{ "resource": "" }
q27472
QbtClient.WebUI.download
test
def download urls urls = Array(urls) urls = urls.join('%0A') options = { body: "urls=#{urls}" } self.class.post('/command/download', options) end
ruby
{ "resource": "" }
q27473
QbtClient.WebUI.delete_torrent_and_data
test
def delete_torrent_and_data torrent_hashes torrent_hashes = Array(torrent_hashes) torrent_hashes = torrent_hashes.join('|') options = { body: "hashes=#{torrent_hashes}" } self.class.post('/command/deletePerm', options) end
ruby
{ "resource": "" }
q27474
QbtClient.WebUI.set_location
test
def set_location(torrent_hashes, path) torrent_hashes = Array(torrent_hashes) torrent_hashes = torrent_hashes.join('|') options = { body: { "hashes" => torrent_hashes, "location" => path }, } self.class.post('/command/setLocation', options) end
ruby
{ "resource": "" }
q27475
QbtClient.WebUI.increase_priority
test
def increase_priority torrent_hashes torrent_hashes = Array(torrent_hashes) torrent_hashes = torrent_hashes.join('|') options = { body: "hashes=#{torrent_hashes}" } self.class.post('/command/increasePrio', options) end
ruby
{ "resource": "" }
q27476
QbtClient.WebUI.decrease_priority
test
def decrease_priority torrent_hashes torrent_hashes = Array(torrent_hashes) torrent_hashes = torrent_hashes.join('|') options = { body: "hashes=#{torrent_hashes}" } self.class.post('/command/decreasePrio', options) end
ruby
{ "resource": "" }
q27477
QbtClient.WebUI.maximize_priority
test
def maximize_priority torrent_hashes torrent_hashes = Array(torrent_hashes) torrent_hashes = torrent_hashes.join('|') options = { body: "hashes=#{torrent_hashes}" } self.class.post('/command/topPrio', options) end
ruby
{ "resource": "" }
q27478
QbtClient.WebUI.minimize_priority
test
def minimize_priority torrent_hashes torrent_hashes = Array(torrent_hashes) torrent_hashes = torrent_hashes.join('|') options = { body: "hashes=#{torrent_hashes}" } self.class.post('/command/bottomPrio', options) end
ruby
{ "resource": "" }
q27479
QbtClient.WebUI.set_file_priority
test
def set_file_priority torrent_hash, file_id, priority query = ["hash=#{torrent_hash}", "id=#{file_id}", "priority=#{priority}"] options = { body: query.join('&') } self.class.post('/command/setFilePrio', options) end
ruby
{ "resource": "" }
q27480
QbtClient.WebUI.set_download_limit
test
def set_download_limit torrent_hash, limit query = ["hashes=#{torrent_hash}", "limit=#{limit}"] options = { body: query.join('&') } self.class.post('/command/setTorrentsDlLimit', options) end
ruby
{ "resource": "" }
q27481
QbtClient.WebUI.set_upload_limit
test
def set_upload_limit torrent_hash, limit query = ["hashes=#{torrent_hash}", "limit=#{limit}"] options = { body: query.join('&') } self.class.post('/command/setTorrentsUpLimit', options) end
ruby
{ "resource": "" }
q27482
Scripto.MiscCommands.md5_file
test
def md5_file(path) File.open(path) do |f| digest, buf = Digest::MD5.new, "" while f.read(4096, buf) digest.update(buf) end digest.hexdigest end end
ruby
{ "resource": "" }
q27483
Risky::ListKeys.ClassMethods.keys
test
def keys(*a) if block_given? bucket.keys(*a) do |keys| # This API is currently inconsistent from protobuffs to http if keys.kind_of? Array keys.each do |key| yield key end else yield keys end end else bucket.keys(*a) end end
ruby
{ "resource": "" }
q27484
Risky::ListKeys.ClassMethods.each
test
def each bucket.keys do |keys| keys.each do |key| if x = self[key] yield x end end end end
ruby
{ "resource": "" }
q27485
Scripto.RunCommands.run
test
def run(command, args = nil) cmd = CommandLine.new(command, args) vputs(cmd) cmd.run end
ruby
{ "resource": "" }
q27486
RSqoot.Click.clicks
test
def clicks(options = {}) options = update_by_expire_time options if clicks_not_latest?(options) @rsqoot_clicks = get('clicks', options, SqootClick) @rsqoot_clicks = @rsqoot_clicks.clicks if @rsqoot_clicks @rsqoot_clicks = @rsqoot_clicks.clicks.map(&:click) if @rsqoot_clicks.clicks end logger(uri: sqoot_query_uri, records: @rsqoot_clicks, type: 'clicks', opts: options) @rsqoot_clicks end
ruby
{ "resource": "" }
q27487
RodeoClown.InstanceBuilder.build_instances
test
def build_instances(template = nil) build_args = if template == :template [build_options.first.merge(count: 1)] else build_options end build_args.map do |args| instances = create_instance args apply_tags(instances) instances end.flatten end
ruby
{ "resource": "" }
q27488
ScopedEnum.ScopeCreator.scope
test
def scope(scope_name, scope_enum_keys) target_enum = @record_class.defined_enums[@enum_name.to_s] sub_enum_values = target_enum.values_at(*scope_enum_keys) if @record_class.defined_enum_scopes.has_key?(scope_name) fail ArgumentError, "Conflicting scope names. A scope named #{scope_name} has already been defined" elsif sub_enum_values.include?(nil) unknown_key = scope_enum_keys[sub_enum_values.index(nil)] fail ArgumentError, "Unknown key - #{unknown_key} for enum #{@enum_name}" elsif @record_class.respond_to?(scope_name.to_s.pluralize) fail ArgumentError, "Scope name - #{scope_name} conflicts with a class method of the same name" elsif @record_class.instance_methods.include?("#{scope_name}?".to_sym) fail ArgumentError, "Scope name - #{scope_name} conflicts with the instance method - #{scope_name}?" end sub_enum_entries = target_enum.slice(*scope_enum_keys) @record_class.defined_enum_scopes[scope_name] = sub_enum_entries # 1. Instance method <scope_name>? @record_class.send(:define_method, "#{scope_name}?") { sub_enum_entries.include? self.role } # 2. The class scope with the scope name @record_class.scope scope_name.to_s.pluralize, -> { @record_class.where("#{@enum_name}" => sub_enum_entries.values) } @scope_names << scope_name end
ruby
{ "resource": "" }
q27489
Revenc.Settings.configure
test
def configure # config file default options configuration = { :options => { :verbose => false, :coloring => 'AUTO' }, :mount => { :source => { :name => nil }, :mountpoint => { :name => nil }, :passphrasefile => { :name => 'passphrase' }, :keyfile => { :name => 'encfs6.xml' }, :cmd => nil, :executable => nil }, :unmount => { :mountpoint => { :name => nil }, :cmd => nil, :executable => nil }, :copy => { :source => { :name => nil }, :destination => { :name => nil }, :cmd => nil, :executable => nil } } # set default config if not given on command line config = @options[:config] unless config config = [ File.join(@working_dir, "revenc.conf"), File.join(@working_dir, ".revenc.conf"), File.join(@working_dir, "config", "revenc.conf"), File.expand_path(File.join("~", ".revenc.conf")) ].detect { |filename| File.exists?(filename) } end if config && File.exists?(config) # rewrite options full path for config for later use @options[:config] = config # load options from the config file, overwriting hard-coded defaults config_contents = YAML::load(File.open(config)) configuration.merge!(config_contents.symbolize_keys!) if config_contents && config_contents.is_a?(Hash) else # user specified a config file?, no error if user did not specify config file raise "config file not found" if @options[:config] end # the command line options override options read from the config file @options = configuration[:options].merge!(@options) @options.symbolize_keys! # mount, unmount and copy configuration hashes @options[:mount] = configuration[:mount].recursively_symbolize_keys! if configuration[:mount] @options[:unmount] = configuration[:unmount].recursively_symbolize_keys! if configuration[:unmount] @options[:copy] = configuration[:copy].recursively_symbolize_keys! if configuration[:copy] end
ruby
{ "resource": "" }
q27490
Feedtosis.Client.mark_new_entries
test
def mark_new_entries(response) digests = summary_digests # For each entry in the responses object, mark @_seen as false if the # digest of this entry doesn't exist in the cached object. response.entries.each do |e| seen = digests.include?(digest_for(e)) e.instance_variable_set(:@_seen, seen) end response end
ruby
{ "resource": "" }
q27491
Feedtosis.Client.set_header_options
test
def set_header_options(curl) summary = summary_for_feed unless summary.nil? curl.headers['If-None-Match'] = summary[:etag] unless summary[:etag].nil? curl.headers['If-Modified-Since'] = summary[:last_modified] unless summary[:last_modified].nil? end curl end
ruby
{ "resource": "" }
q27492
Feedtosis.Client.store_summary_to_backend
test
def store_summary_to_backend(feed, curl) headers = HttpHeaders.new(curl.header_str) # Store info about HTTP retrieval summary = { } summary.merge!(:etag => headers.etag) unless headers.etag.nil? summary.merge!(:last_modified => headers.last_modified) unless headers.last_modified.nil? # Store digest for each feed entry so we can detect new feeds on the next # retrieval new_digest_set = feed.entries.map do |e| digest_for(e) end new_digest_set = summary_for_feed[:digests].unshift(new_digest_set) new_digest_set = new_digest_set[0..@options[:retained_digest_size]] summary.merge!( :digests => new_digest_set ) set_summary(summary) end
ruby
{ "resource": "" }
q27493
Ropenstack.Rest.error_manager
test
def error_manager(uri, response) case response when Net::HTTPSuccess then # This covers cases where the response may not validate as JSON. begin data = JSON.parse(response.body) rescue data = {} end ## Get the Headers out of the response object data['headers'] = response.to_hash() return data when Net::HTTPBadRequest raise Ropenstack::MalformedRequestError, response.body when Net::HTTPNotFound raise Ropenstack::NotFoundError, "URI: #{uri} \n" + response.body when Net::HTTPUnauthorized raise Ropenstack::UnauthorisedError, response.body else raise Ropenstack::RopenstackError, response.body end end
ruby
{ "resource": "" }
q27494
Ropenstack.Rest.do_request
test
def do_request(uri, request, manage_errors = true, timeout = 10) begin http = build_http(uri, timeout) if(manage_errors) return error_manager(uri, http.request(request)) else http.request(request) return { "Success" => true } end rescue Timeout::Error raise Ropenstack::TimeoutError, "It took longer than #{timeout} to connect to #{uri.to_s}" rescue Errno::ECONNREFUSED raise Ropenstack::TimeoutError, "It took longer than #{timeout} to connect to #{uri.to_s}" end end
ruby
{ "resource": "" }
q27495
Ropenstack.Rest.get_request
test
def get_request(uri, token = nil, manage_errors = true) request = Net::HTTP::Get.new(uri.request_uri, initheader = build_headers(token)) return do_request(uri, request, manage_errors) end
ruby
{ "resource": "" }
q27496
Ropenstack.Rest.delete_request
test
def delete_request(uri, token = nil, manage_errors = true) request = Net::HTTP::Delete.new(uri.request_uri, initheader = build_headers(token)) return do_request(uri, request, manage_errors) end
ruby
{ "resource": "" }
q27497
Ropenstack.Rest.put_request
test
def put_request(uri, body, token = nil, manage_errors = true) request = Net::HTTP::Put.new(uri.request_uri, initheader = build_headers(token)) request.body = body.to_json return do_request(uri, request, manage_errors) end
ruby
{ "resource": "" }
q27498
Ropenstack.Rest.post_request
test
def post_request(uri, body, token = nil, manage_errors = true) request = Net::HTTP::Post.new(uri.request_uri, initheader = build_headers(token)) request.body = body.to_json return do_request(uri, request, manage_errors) end
ruby
{ "resource": "" }
q27499
SFKB.Knowledge.article
test
def article(id) url = index.knowledgeManagement.articles.article url = url(url, ArticleID: id) decorate(get(url).body) { |o| autodefine(o) } end
ruby
{ "resource": "" }