_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q24000
Handshake.ClauseMethods.Block
train
def Block(contract_hash) pc = Handshake::ProcContract.new pc.signature = contract_hash pc end
ruby
{ "resource": "" }
q24001
Openapi2ruby.Openapi::Schema.properties
train
def properties return [] if @definition['properties'].nil? @definition['properties'].each_with_object([]) do |(key, value), results| content = { name: key, definition: value } results << Openapi2ruby::Openapi::Schema::Property.new(content) end end
ruby
{ "resource": "" }
q24002
TeslaAPI.Connection.vehicles
train
def vehicles @vehicles ||= begin _, json = get_json("/vehicles") json.map { |data| Vehicle.new(self, data) } end end
ruby
{ "resource": "" }
q24003
Omniship.Carrier.valid_credentials?
train
def valid_credentials? location = self.class.default_location find_rates(location,location,Package.new(100, [5,15,30]), :test => test_mode) rescue Omniship::ResponseError false else true end
ruby
{ "resource": "" }
q24004
RDF.Statement.to_mongo
train
def to_mongo self.to_hash.inject({}) do |hash, (place_in_statement, entity)| hash.merge(RDF::Mongo::Conversion.to_mongo(entity, place_in_statement)) end end
ruby
{ "resource": "" }
q24005
RLP.DecodeLazy.decode_lazy
train
def decode_lazy(rlp, sedes: nil, sedes_options: {}) item, next_start = consume_item_lazy(rlp, 0) raise DecodingError.new("RLP length prefix announced wrong length", rlp) if next_start != rlp.size if item.instance_of?(LazyList) item.sedes = sedes item.sedes_options = sedes_options item elsif sedes # FIXME: lazy man's kwargs sedes_options.empty? ? sedes.deserialize(item) : sedes.deserialize(item, **sedes_options) else item end end
ruby
{ "resource": "" }
q24006
RLP.DecodeLazy.consume_item_lazy
train
def consume_item_lazy(rlp, start) t, l, s = consume_length_prefix(rlp, start) if t == :str consume_payload(rlp, s, :str, l) elsif t == :list [LazyList.new(rlp, s, s+l), s+l] else raise "Invalid item type: #{t}" end end
ruby
{ "resource": "" }
q24007
RLP.DecodeLazy.peek
train
def peek(rlp, index, sedes: nil) ll = decode_lazy(rlp) index = Array(index) index.each do |i| raise IndexError, "Too many indices given" if primitive?(ll) ll = ll.fetch(i) end sedes ? sedes.deserialize(ll) : ll end
ruby
{ "resource": "" }
q24008
Handshake.ClassMethods.contract_reader
train
def contract_reader(meth_to_clause) attr_reader(*(meth_to_clause.keys)) meth_to_clause.each do |meth, cls| contract meth, nil => cls end end
ruby
{ "resource": "" }
q24009
Handshake.ClassMethods.contract_writer
train
def contract_writer(meth_to_clause) attr_writer(*(meth_to_clause.keys)) meth_to_clause.each do |meth, cls| contract "#{meth}=".to_sym, cls => anything end end
ruby
{ "resource": "" }
q24010
Handshake.ClassMethods.method_added
train
def method_added(meth_name) @deferred ||= {} unless @deferred.empty? @deferred.each do |k, v| case k when :before, :after, :around define_condition meth_name, k, v when :contract define_contract meth_name, v end end @deferred.clear end end
ruby
{ "resource": "" }
q24011
Handshake.MethodContract.accepts=
train
def accepts=(args) if args.last == Block # Transform into a ProcContract args.pop @block_contract = ProcContract.new @block_contract.accepts = ClauseMethods::ANYTHING @block_contract.returns = ClauseMethods::ANYTHING elsif args.last.is_a?(ProcContract) @block_contract = args.pop end if args.find_all {|o| o.is_a? Array}.length > 1 raise ContractError, "Cannot define more than one expected variable argument" end super(args) end
ruby
{ "resource": "" }
q24012
RackStatsD.RequestStatus.call
train
def call(env) if env[REQUEST_METHOD] == GET if env[PATH_INFO] == @status_path if @callback.respond_to?(:call) return @callback.call else return [200, HEADERS, [@callback.to_s]] end end end @app.call env end
ruby
{ "resource": "" }
q24013
RackStatsD.RequestHostname.call
train
def call(env) status, headers, body = @app.call(env) headers['X-Node'] = @host if @host headers['X-Revision'] = @sha [status, headers, body] end
ruby
{ "resource": "" }
q24014
RackStatsD.ProcessUtilization.procline
train
def procline "unicorn %s[%s] worker[%02d]: %5d reqs, %4.1f req/s, %4dms avg, %5.1f%% util" % [ domain, revision, worker_number.to_i, total_requests.to_i, requests_per_second.to_f, average_response_time.to_i, percentage_active.to_f ] end
ruby
{ "resource": "" }
q24015
RackStatsD.ProcessUtilization.record_request
train
def record_request(status, env) now = Time.now diff = (now - @start) @active_time += diff @requests += 1 $0 = procline if @stats @stats.timing("#{@stats_prefix}.response_time", diff * 1000) if VALID_METHODS.include?(env[REQUEST_METHOD]) stat = "#{@stats_prefix}.response_time.#{env[REQUEST_METHOD].downcase}" @stats.timing(stat, diff * 1000) end if suffix = status_suffix(status) @stats.increment "#{@stats_prefix}.status_code.#{status_suffix(status)}" end if @track_gc && GC.time > 0 @stats.timing "#{@stats_prefix}.gc.time", GC.time / 1000 @stats.count "#{@stats_prefix}.gc.collections", GC.collections end end reset_horizon if now - horizon > @window rescue => boom warn "ProcessUtilization#record_request failed: #{boom}" end
ruby
{ "resource": "" }
q24016
RackStatsD.ProcessUtilization.call
train
def call(env) @start = Time.now GC.clear_stats if @track_gc @total_requests += 1 first_request if @total_requests == 1 env['process.request_start'] = @start.to_f env['process.total_requests'] = total_requests # newrelic X-Request-Start env.delete('HTTP_X_REQUEST_START') status, headers, body = @app.call(env) body = Body.new(body) { record_request(status, env) } [status, headers, body] end
ruby
{ "resource": "" }
q24017
HammerCLIForemanTasks.Helper.task_progress
train
def task_progress(task_or_id) task_id = task_or_id.is_a?(Hash) ? task_or_id['id'] : task_or_id if !task_id.empty? options = { verbosity: @context[:verbosity] || HammerCLI::V_VERBOSE } task_progress = TaskProgress.new(task_id, options) { |id| load_task(id) } task_progress.render task_progress.success? else signal_usage_error(_('Please mention appropriate attribute value')) end end
ruby
{ "resource": "" }
q24018
RLP.Decode.decode
train
def decode(rlp, **options) rlp = str_to_bytes(rlp) sedes = options.delete(:sedes) strict = options.has_key?(:strict) ? options.delete(:strict) : true begin item, next_start = consume_item(rlp, 0) rescue Exception => e raise DecodingError.new("Cannot decode rlp string: #{e}", rlp) end raise DecodingError.new("RLP string ends with #{rlp.size - next_start} superfluous bytes", rlp) if next_start != rlp.size && strict if sedes obj = sedes.instance_of?(Class) && sedes.include?(Sedes::Serializable) ? sedes.deserialize(item, **options) : sedes.deserialize(item) if obj.respond_to?(:_cached_rlp) obj._cached_rlp = rlp raise "RLP::Sedes::Serializable object must be immutable after decode" if obj.is_a?(Sedes::Serializable) && obj.mutable? end obj else item end end
ruby
{ "resource": "" }
q24019
RLP.Decode.consume_item
train
def consume_item(rlp, start) t, l, s = consume_length_prefix(rlp, start) consume_payload(rlp, s, t, l) end
ruby
{ "resource": "" }
q24020
RLP.Decode.consume_payload
train
def consume_payload(rlp, start, type, length) case type when :str [rlp[start...(start+length)], start+length] when :list items = [] next_item_start = start payload_end = next_item_start + length while next_item_start < payload_end item, next_item_start = consume_item rlp, next_item_start items.push item end raise DecodingError.new('List length prefix announced a too small length', rlp) if next_item_start > payload_end [items, next_item_start] else raise TypeError, 'Type must be either :str or :list' end end
ruby
{ "resource": "" }
q24021
Pipes.Context.add
train
def add(values) values.each do |key, val| k_sym = key.to_sym fail Override, "Property :#{key} already present" if respond_to?(k_sym) define_singleton_method(k_sym) { val } end end
ruby
{ "resource": "" }
q24022
RubyFS.Stream.run
train
def run logger.debug "Starting up..." @socket = TCPSocket.from_ruby_socket ::TCPSocket.new(@host, @port) post_init loop { receive_data @socket.readpartial(4096) } rescue EOFError, IOError, Errno::ECONNREFUSED => e logger.info "Client socket closed due to (#{e.class}) #{e.message}!" async.terminate end
ruby
{ "resource": "" }
q24023
RubyFS.Stream.command
train
def command(command, options = {}, &callback) uuid = SecureRandom.uuid @command_callbacks << (callback || lambda { |reply| signal uuid, reply }) string = "#{command}\n" body_value = options.delete :command_body_value options.each_pair do |key, value| string << "#{key.to_s.gsub '_', '-'}: #{value}\n" if value end string << "\n" << body_value << "\n" if body_value string << "\n" send_data string wait uuid unless callback end
ruby
{ "resource": "" }
q24024
RubyFS.Stream.application
train
def application(call, appname, options = nil) opts = {call_command: 'execute', execute_app_name: appname} if options opts[:content_type] = 'text/plain' opts[:content_length] = options.bytesize opts[:command_body_value] = options end sendmsg call, opts end
ruby
{ "resource": "" }
q24025
GdprExporter.ClassMethods.gdpr_collect
train
def gdpr_collect(*args) # Params handling if args.class == Hash # when user provides the hash_params only simple_fields, hash_params = [[], args] else simple_fields, hash_params = [args[0..-2], args.last] end unless hash_params.class == Hash raise ArgumentError.new("Gdpr fields collection error: last argument must be a hash!") end unless hash_params.key?(:user_id) raise ArgumentError.new("Gdpr fields collection error: the field aliasing user_id is not declared for '#{self}'!") end # Adds the eigen class to the set of classes eligible for gdpr data collection. GdprExporter.add_klass(self) # Adds instance fields to the eigenclass. They store # all the fields and info we are interested in. @gdpr_simple_fields = simple_fields @gdpr_hash_params = hash_params # Add readers for the instance vars declared above (for testing reasons) self.class.send :attr_reader, :gdpr_simple_fields self.class.send :attr_reader, :gdpr_hash_params # Build the csv header and prepare the fields used for querying # user_id_field = hash_params[:user_id] # csv_headers = [:user_id].concat @gdpr_simple_fields # Uncomment if user_id needed # query_fields = [user_id_field].concat @gdpr_simple_fields # Uncomment if user_id needed csv_headers = [].concat @gdpr_simple_fields query_fields = [].concat @gdpr_simple_fields if hash_params[:renamed_fields] csv_headers.concat hash_params[:renamed_fields].values query_fields.concat hash_params[:renamed_fields].keys end # Adds the class method 'gdpr_query' to the eigenclass. # It will execute the query. self.define_singleton_method(:gdpr_query) do |_user_id| result = self.where(user_id_field => _user_id) # When there are multiple joins defined, just keep calling 'joins' # for each association. if hash_params[:joins] result = hash_params[:joins].inject(result) do | query, assoc | query.send(:joins, assoc) end end result end # Adds a method to export to csv to the eigenclass. self.define_singleton_method(:gdpr_export) do |rows, csv| return unless !rows.empty? csv << (hash_params[:table_name] ? [hash_params[:table_name]] : [self.to_s]) if hash_params[:desc] csv << ['Description:', hash_params[:desc]] end csv << csv_headers rows.each do |r| csv << query_fields.map do |f| f_splitted = f.to_s.split(' ') if (f_splitted.size == 2) # field f is coming from an assoc, i.e. field has been defined # as "<tablename> <field>" in gdpr_collect then to get its value # do r.<tablename>.<field> f_splitted.inject(r) { |result, method| result.send(method) } elsif (f_splitted.size > 2) raise ArgumentError.new("Field #{f} is made of more than 2 words!?") else # No association involved, simply retrieve the field value. r.send(f) end end end csv << [] end end
ruby
{ "resource": "" }
q24026
SpinningCursor.ConsoleHelpers.reset_line
train
def reset_line(text = "") # Initialise ANSI escape string escape = "" # Get terminal window width cols = console_columns # The number of lines the previous message spanned lines = @@prev / cols # If cols == 80 and @@prev == 80, @@prev / cols == 1 but we don't want to # go up an extra line since it fits exactly lines -= 1 if @@prev % cols == 0 # Clear and go up a line lines.times { escape += "#{ESC_R_AND_CLR}#{ESC_UP_A_LINE}" } # Clear the line that is to be printed on escape += "#{ESC_R_AND_CLR}" # Console is clear, we can print! $console.print "#{escape}#{text}" # Store the current message so we know how many lines it spans @@prev = text.to_s.length end
ruby
{ "resource": "" }
q24027
Bump.BumpInfo.valid?
train
def valid? create_update_rules.each do |rule| return false if !rule.file_exists || !rule.pattern_exists end true end
ruby
{ "resource": "" }
q24028
Hermitage.RailsRenderCore.render
train
def render # Initialize the resulting tag tag_parts = [] # Slice objects into separate lists lists = slice_objects # Render each list into `tag` variable lists.each do |list| items = list.collect { |item| render_link_for(item) } tag_parts << render_content_tag_for(items) end tag_parts.join.html_safe end
ruby
{ "resource": "" }
q24029
Hermitage.RailsRenderCore.value_for
train
def value_for(item, option) attribute = @options[option] if attribute.is_a? Proc attribute.call(item) else eval("item.#{attribute}") end end
ruby
{ "resource": "" }
q24030
Hermitage.RailsRenderCore.render_link_for
train
def render_link_for(item) original_path = value_for(item, :original) thumbnail_path = value_for(item, :thumbnail) title = @options[:title] ? value_for(item, :title) : nil image = @template.image_tag(thumbnail_path, class: @options[:image_class]) @template.link_to(image, original_path, rel: 'hermitage', class: @options[:link_class], title: title) end
ruby
{ "resource": "" }
q24031
RLP.Encode.encode
train
def encode(obj, sedes: nil, infer_serializer: true, cache: false) return obj._cached_rlp if obj.is_a?(Sedes::Serializable) && obj._cached_rlp && sedes.nil? really_cache = obj.is_a?(Sedes::Serializable) && sedes.nil? && cache if sedes item = sedes.serialize(obj) elsif infer_serializer item = Sedes.infer(obj).serialize(obj) else item = obj end result = encode_raw(item) if really_cache obj._cached_rlp = result obj.make_immutable! end result end
ruby
{ "resource": "" }
q24032
Bump.Application.create_bump_info
train
def create_bump_info repo = BumpInfoRepository.new @file begin bump_info = repo.from_file rescue Errno::ENOENT log_red "Error: the file `#{@file}` not found." return nil end bump_info end
ruby
{ "resource": "" }
q24033
Bump.Application.print_version_patterns
train
def print_version_patterns(bump_info) log 'Current Version:', false log_green " #{bump_info.before_version}" log 'Version patterns:' bump_info.update_rules.each do |rule| print_rule rule end end
ruby
{ "resource": "" }
q24034
Bump.Application.print_rule
train
def print_rule(rule) unless rule.file_exists log_red " #{rule.file}:", false log_red " '#{rule.before_pattern}' (file not found)" return end log " #{rule.file}:", false unless rule.pattern_exists log_red " '#{rule.before_pattern}' (pattern not found)" return end log_green " '#{rule.before_pattern}'" end
ruby
{ "resource": "" }
q24035
Bump.Application.report
train
def report(bump_info) bump_info.update_rules.each do |rule| log rule.file.to_s log ' Performed pattern replacement:' log_green " '#{rule.before_pattern}' => '#{rule.after_pattern}'" log end end
ruby
{ "resource": "" }
q24036
Bump.Application.action_bump
train
def action_bump bump_info = create_bump_info return false if bump_info.nil? print_bump_plan bump_info unless bump_info.valid? print_invalid_bump_info bump_info return false end bump_info.perform_update report bump_info save_bump_info bump_info commit_and_tag bump_info if @options[:commit] true end
ruby
{ "resource": "" }
q24037
Bump.Application.print_bump_plan
train
def print_bump_plan(bump_info) level = bump_level print_bump_plan_level level, bump_info unless level.nil? preid = @options[:preid] print_bump_plan_preid preid, bump_info unless preid.nil? print_bump_plan_release bump_info if @options[:release] log end
ruby
{ "resource": "" }
q24038
Bump.Application.print_bump_plan_preid
train
def print_bump_plan_preid(preid, bump_info) bump_info.preid = preid log 'Set pre-release version id: ', false log_green preid print_version_transition bump_info end
ruby
{ "resource": "" }
q24039
Omniship.UPS.create_shipment
train
def create_shipment(origin, destination, packages, options={}) @options = @options.merge(options) origin, destination = upsified_location(origin), upsified_location(destination) options = @options.merge(options) options[:test] = options[:test].nil? ? true : options[:test] packages = Array(packages) access_request = build_access_request ship_confirm_request = build_ship_confirm(origin, destination, packages, options) response = commit(:shipconfirm, save_request(access_request.gsub("\n", "") + ship_confirm_request.gsub("\n", "")), options[:test]) parse_ship_confirm_response(origin, destination, packages, response, options) end
ruby
{ "resource": "" }
q24040
Ansible.Vault.write
train
def write file = FileWriter.new(@path) encryptor = Encryptor.new(password: @password, file: file) encryptor.encrypt(@plaintext) file.write end
ruby
{ "resource": "" }
q24041
Ansible.Vault.read
train
def read file = FileReader.new(@path) return File.read(@path) unless file.encrypted? decryptor = Decryptor.new(password: @password, file: file) decryptor.plaintext end
ruby
{ "resource": "" }
q24042
JSchema.ValidationHelpers.non_empty_array?
train
def non_empty_array?(value, uniqueness_check = true) result = value.is_a?(Array) && !value.empty? if uniqueness_check result && value.size == value.uniq.size else result end end
ruby
{ "resource": "" }
q24043
JSchema.ValidationHelpers.schema_array?
train
def schema_array?(value, id, uniqueness_check = true) non_empty_array?(value, uniqueness_check) && value.to_enum.with_index.all? do |schema, index| full_id = [id, index].join('/') valid_schema? schema, full_id end end
ruby
{ "resource": "" }
q24044
JSchema.ValidationHelpers.valid_schema?
train
def valid_schema?(schema, id) schema.is_a?(Hash) && Schema.build(schema, parent, id) rescue InvalidSchema false end
ruby
{ "resource": "" }
q24045
Redmine.AcceptJson.get
train
def get(path, headers = {}) response = super(path, { 'Accept' => ACCEPT }.merge(headers.to_h)) case response.content_type when CONTENT_TYPE then [parse_response(response), response] else raise "Unknown content type #{response.content_type.inspect}" end end
ruby
{ "resource": "" }
q24046
Kondate.HashExt.deep_merge!
train
def deep_merge!(other_hash, &block) other_hash.each_pair do |current_key, other_value| this_value = self[current_key] self[current_key] = if this_value.is_a?(Hash) && other_value.is_a?(Hash) _this_value = HashExt.new.replace(this_value) _this_value.deep_merge(other_value, &block).to_h else if block_given? && key?(current_key) block.call(current_key, this_value, other_value) else other_value end end end self end
ruby
{ "resource": "" }
q24047
RestfulResource.Request.format_headers
train
def format_headers @headers.stringify_keys.each_with_object({}) do |key_with_value, headers| headers[format_key(key_with_value.first)] = key_with_value.last end end
ruby
{ "resource": "" }
q24048
CFoundry.Zip.unpack
train
def unpack(file, dest) ::Zip::ZipFile.foreach(file) do |zentry| epath = "#{dest}/#{zentry}" dirname = File.dirname(epath) FileUtils.mkdir_p(dirname) unless File.exists?(dirname) zentry.extract(epath) unless File.exists?(epath) end end
ruby
{ "resource": "" }
q24049
CFoundry.Zip.files_to_pack
train
def files_to_pack(dir) Dir.glob("#{dir}/**/*", File::FNM_DOTMATCH).select do |f| File.exists?(f) && PACK_EXCLUSION_GLOBS.none? do |e| File.fnmatch(e, File.basename(f)) end end end
ruby
{ "resource": "" }
q24050
CFoundry.Zip.pack
train
def pack(dir, zipfile) files = files_to_pack(dir) return false if files.empty? ::Zip::ZipFile.open(zipfile, true) do |zf| files.each do |f| zf.add(f.sub("#{dir}/",''), f) end end true end
ruby
{ "resource": "" }
q24051
Effective.FormBuilder.remote_link_to
train
def remote_link_to(name, url, options = {}, &block) options[:href] ||= url Effective::FormInputs::RemoteLinkTo.new(name, options, builder: self).to_html(&block) end
ruby
{ "resource": "" }
q24052
Slackbotsy.Api.get_objects
train
def get_objects(method, key) self.class.get("/#{method}", query: { token: @token }).tap do |response| raise "error retrieving #{key} from #{method}: #{response.fetch('error', 'unknown error')}" unless response['ok'] end.fetch(key) end
ruby
{ "resource": "" }
q24053
Slackbotsy.Api.join
train
def join(channel) self.class.post('/channels.join', body: {name: channel, token: @token}).tap do |response| raise "error posting message: #{response.fetch('error', 'unknown error')}" unless response['ok'] end end
ruby
{ "resource": "" }
q24054
Slackbotsy.Api.post_message
train
def post_message(params) self.class.post('/chat.postMessage', body: params.merge({token: @token})).tap do |response| raise "error posting message: #{response.fetch('error', 'unknown error')}" unless response['ok'] end end
ruby
{ "resource": "" }
q24055
CFoundry.UploadHelpers.prune_empty_directories
train
def prune_empty_directories(path) all_files = all_files(path) directories = all_files.select { |x| File.directory?(x) } directories.sort! { |a, b| b.size <=> a.size } directories.each do |directory| entries = all_files(directory) FileUtils.rmdir(directory) if entries.empty? end end
ruby
{ "resource": "" }
q24056
Slackbotsy.Bot.setup_incoming_webhook
train
def setup_incoming_webhook ## incoming_webhook will be used if provided, otherwise fallback to old-style url with team and token url = @options.fetch('incoming_webhook', false) || "https://#{@options['team']}.slack.com/services/hooks/incoming-webhook?token=#{@options['incoming_token']}" @uri = URI.parse(url) @http = Net::HTTP.new(@uri.host, @uri.port) @http.use_ssl = true @http.verify_mode = OpenSSL::SSL::VERIFY_PEER end
ruby
{ "resource": "" }
q24057
Slackbotsy.Bot.post
train
def post(options) payload = { username: @options['name'], channel: @options['channel'] }.merge(options) payload[:channel] = payload[:channel].gsub(/^#?/, '#') #slack api needs leading # on channel request = Net::HTTP::Post.new(@uri.request_uri) request.set_form_data(payload: payload.to_json) @http.request(request) return nil # so as not to trigger text in outgoing webhook reply end
ruby
{ "resource": "" }
q24058
Slackbotsy.Bot.hear
train
def hear(regex, &block) @listeners << OpenStruct.new(regex: regex, desc: @last_desc, proc: block) @last_desc = nil end
ruby
{ "resource": "" }
q24059
Slackbotsy.Bot.eval_scripts
train
def eval_scripts(*files) files.flatten.each do |file| self.instance_eval(File.open(file).read) end end
ruby
{ "resource": "" }
q24060
Slackbotsy.Bot.handle_outgoing_webhook
train
def handle_outgoing_webhook(msg) return nil unless @options['outgoing_token'].include?(msg[:token]) # ensure messages are for us from slack return nil if msg[:user_name] == 'slackbot' # do not reply to self return nil unless msg[:text].is_a?(String) # skip empty messages responses = get_responses(msg, msg[:text].strip) if responses { text: responses.compact.join("\n") }.to_json # webhook responses are json end end
ruby
{ "resource": "" }
q24061
Slackbotsy.Bot.get_responses
train
def get_responses(msg, text) message = Slackbotsy::Message.new(self, msg) @listeners.map do |listener| text.match(listener.regex) do |mdata| begin message.instance_exec(mdata, *mdata[1..-1], &listener.proc) rescue => err # keep running even with a broken script, but report the error err end end end end
ruby
{ "resource": "" }
q24062
CFoundry::V2.Client.current_user
train
def current_user return unless token token_data = @base.token.token_data if guid = token_data[:user_id] user = user(guid) user.emails = [{ :value => token_data[:email] }] user end end
ruby
{ "resource": "" }
q24063
Twittbot.Bot.auth
train
def auth require 'oauth' say "This will reset your current access tokens.", :red if already_authed? # get the request token URL callback = OAuth::OUT_OF_BAND consumer = OAuth::Consumer.new $bot[:config][:consumer_key], $bot[:config][:consumer_secret], site: Twitter::REST::Client::BASE_URL, scheme: :header request_token = consumer.get_request_token(oauth_callback: callback) url = request_token.authorize_url(oauth_callback: callback) puts "Open this URL in a browser: #{url}" pin = '' until pin =~ /^\d+$/ print "Enter PIN =>" pin = $stdin.gets.strip end access_token = request_token.get_access_token(oauth_verifier: pin) $bot[:config][:access_token] = access_token.token $bot[:config][:access_token_secret] = access_token.secret # get the bot's user name (screen_name) and print it to the console $bot[:config][:screen_name] = get_screen_name access_token puts "Hello, #{$bot[:config][:screen_name]}!" end
ruby
{ "resource": "" }
q24064
Twittbot.Bot.start
train
def start check_config init_clients if $bot[:stream] puts "connecting to streaming APIs" @userstream_thread ||= Thread.new do loop do begin puts "connected to user stream" @streamer.user do |obj| handle_stream_object obj, :user end rescue => e puts "lost user stream connection: " + e.message end puts "reconnecting in #{Twittbot::RECONNECT_WAIT_TIME} seconds..." sleep Twittbot::RECONNECT_WAIT_TIME end end @tweetstream_thread ||= Thread.new do loop do begin puts "connected to tweet stream" @streamer.filter track: $bot[:config][:track].join(",") do |obj| handle_stream_object obj, :filter end rescue puts "lost tweet stream connection: " + e.message end puts "reconnecting in #{Twittbot::RECONNECT_WAIT_TIME} seconds..." sleep Twittbot::RECONNECT_WAIT_TIME end end end @periodic_thread ||= Thread.new do loop do begin Thread.new { do_periodic } rescue => _ end sleep 60 end end do_callbacks :load, nil if $bot[:stream] @userstream_thread.join @tweetstream_thread.join end @periodic_thread.join end
ruby
{ "resource": "" }
q24065
Twittbot.Bot.load_bot_code
train
def load_bot_code load_special_tasks files = Dir["#{File.expand_path('./lib', @options[:current_dir])}/**/*"] files.each do |file| require_relative file.sub(/\.rb$/, '') if file.end_with? '.rb' end end
ruby
{ "resource": "" }
q24066
Twittbot.Bot.do_callbacks
train
def do_callbacks(callback_type, object, options = {}) return if $bot[:callbacks][callback_type].nil? $bot[:callbacks][callback_type].each do |c| c[:block].call object, options end end
ruby
{ "resource": "" }
q24067
Twittbot.Bot.do_direct_message
train
def do_direct_message(dm, opts = {}) return if dm.sender.screen_name == $bot[:config][:screen_name] return do_callbacks(:direct_message, dm, opts) unless dm.text.start_with? $bot[:config][:dm_command_prefix] dm_text = dm.text.sub($bot[:config][:dm_command_prefix], '').strip return if dm_text.empty? return unless /(?<command>[A-Za-z0-9]+)(?:\s*)(?<args>.*)/m =~ dm_text command = Regexp.last_match(:command).to_sym args = Regexp.last_match :args cmd = $bot[:commands][command] return say_status :dm, "#{dm.sender.screen_name} tried to issue non-existent command :#{command}, ignoring", :cyan if cmd.nil? return say_status :dm, "#{dm.sender.screen_name} tried to issue admin command :#{command}, ignoring", :cyan if cmd[:admin] and !dm.sender.admin? say_status :dm, "#{dm.sender.screen_name} issued command :#{command}", :cyan cmd[:block].call(args, dm.sender) end
ruby
{ "resource": "" }
q24068
Twittbot.Bot.list_tasks
train
def list_tasks tasks = $bot[:tasks].map do |name, value| [name, value[:desc]] end.to_h longest_name = tasks.keys.map(&:to_s).max { |a, b| a.length <=> b.length }.length tasks = tasks.map do |name, desc| "twittbot cron %-*s # %s" % [longest_name + 2, name, desc] end.sort puts tasks end
ruby
{ "resource": "" }
q24069
Phys.Quantity.want
train
def want(unit=nil) case unit when Unit expr = unit.expr when Quantity expr = unit.expr unit = unit.unit when String,Symbol expr = unit unit = Unit.parse(expr) when Numeric unit = Unit.cast(unit) when NilClass unit = Unit.cast(1) else raise TypeError, "invalid argument: #{unit.inspect}" end val = unit.convert(self) self.class.new( val, expr, unit ) end
ruby
{ "resource": "" }
q24070
Phys.Quantity.close_to
train
def close_to(other,epsilon=Float::EPSILON) other_value = @unit.convert(other) abs_sum = @value.abs+other_value.abs (@value-other_value).abs <= abs_sum*epsilon end
ruby
{ "resource": "" }
q24071
Phys.Quantity.to_base_unit
train
def to_base_unit unit = @unit.base_unit val = unit.convert(self) expr = unit.unit_string self.class.new( val, expr, unit ) end
ruby
{ "resource": "" }
q24072
Phys.Quantity.inspect
train
def inspect expr = @expr || @unit.expr expr = (expr) ? ","+expr.inspect : "" sufx = (@@verbose_inspect) ? " "+@unit.inspect : "" self.class.to_s+"["+Unit::Utils.num_inspect(@value)+expr+"]"+sufx end
ruby
{ "resource": "" }
q24073
LIS::Message.Base.to_message
train
def to_message @fields ||= {} arr = Array.new(self.class.default_fields) type_id + @fields.inject(arr) { |a,(k,v)| a[k-1] = v; a }.join("|") end
ruby
{ "resource": "" }
q24074
Slaw.ActGenerator.guess_section_number_after_title
train
def guess_section_number_after_title(text) before = text.scan(/^\w{4,}[^\n]+\n\d+\. /).length after = text.scan(/^\s*\n\d+\. \w{4,}/).length before > after * 1.25 end
ruby
{ "resource": "" }
q24075
Slaw.ActGenerator.text_from_act
train
def text_from_act(doc) # look on the load path for an XSL file for this grammar filename = "/slaw/grammars/#{@grammar}/act_text.xsl" if dir = $LOAD_PATH.find { |p| File.exist?(p + filename) } xslt = Nokogiri::XSLT(File.read(dir + filename)) xslt.transform(doc).child.to_xml else raise "Unable to find text XSL for grammar #{@grammar}: #{fragment}" end end
ruby
{ "resource": "" }
q24076
ThreeScale.Client.authorize
train
def authorize(options) extensions = options.delete :extensions creds = creds_params(options) path = "/transactions/authorize.xml" + options_to_params(options, ALL_PARAMS) + '&' + creds headers = extensions_to_header extensions if extensions http_response = @http.get(path, headers: headers) case http_response when Net::HTTPSuccess,Net::HTTPConflict build_authorize_response(http_response.body) when Net::HTTPClientError build_error_response(http_response.body, AuthorizeResponse) else raise ServerError.new(http_response) end end
ruby
{ "resource": "" }
q24077
ThreeScale.Client.usage_report
train
def usage_report(node) period_start = node.at('period_start') period_end = node.at('period_end') { :metric => node['metric'].to_s.strip, :period => node['period'].to_s.strip.to_sym, :period_start => period_start ? period_start.content : '', :period_end => period_end ? period_end.content : '', :current_value => node.at('current_value').content.to_i, :max_value => node.at('max_value').content.to_i } end
ruby
{ "resource": "" }
q24078
ThreeScale.Client.generate_creds_params
train
def generate_creds_params define_singleton_method :creds_params, if @service_tokens lambda do |options| token = options.delete(:service_token) service_id = options[:service_id] raise ArgumentError, "need to specify a service_token and a service_id" unless token && service_id 'service_token='.freeze + CGI.escape(token) end elsif @provider_key warn DEPRECATION_MSG_PROVIDER_KEY if @warn_deprecated lambda do |_| "provider_key=#{CGI.escape @provider_key}".freeze end else raise ArgumentError, 'missing credentials - either use "service_tokens: true" or specify a provider_key value' end end
ruby
{ "resource": "" }
q24079
Twitter.Tweet.reply
train
def reply(tweet_text, options = {}) return if $bot.nil? or $bot[:client].nil? opts = { reply_all: false }.merge(options) mentions = self.mentioned_users(opts[:reply_all]) result = "@#{mentions.join(" @")} #{tweet_text}"[(0...140)] $bot[:client].update result, in_reply_to_status_id: self.id rescue Twitter::Error => e puts "caught Twitter error while replying: #{e.message}" end
ruby
{ "resource": "" }
q24080
Twitter.Tweet.mentioned_users
train
def mentioned_users(reply_all = true, screen_name = $bot[:config][:screen_name]) userlist = [ self.user.screen_name ] if reply_all self.text.scan /@([A-Za-z0-9_]{1,16})/ do |user_name| user_name = user_name[0] userlist << user_name unless userlist.include?(user_name) or screen_name == user_name end end userlist end
ruby
{ "resource": "" }
q24081
Twitter.DirectMessage.reply
train
def reply(direct_message_text) return if $bot.nil? or $bot[:client].nil? $bot[:client].create_direct_message self.sender.id, direct_message_text rescue Twitter::Error => e puts "caught Twitter error while replying via DM: #{e.message}" end
ruby
{ "resource": "" }
q24082
Sinew.Request.perform
train
def perform validate! party_options = options.dup # merge proxy if proxy = self.proxy addr, port = proxy.split(':') party_options[:http_proxyaddr] = addr party_options[:http_proxyport] = port || 80 end # now merge runtime_options party_options = party_options.merge(sinew.runtime_options.httparty_options) # merge headers headers = sinew.runtime_options.headers headers = headers.merge(party_options[:headers]) if party_options[:headers] party_options[:headers] = headers party_response = HTTParty.send(method, uri, party_options) Response.from_network(self, party_response) end
ruby
{ "resource": "" }
q24083
Sinew.Request.parse_url
train
def parse_url(url) s = url # remove entities s = HTML_ENTITIES.decode(s) # fix a couple of common encoding bugs s = s.gsub(' ', '%20') s = s.gsub("'", '%27') # append query manually (instead of letting HTTParty handle it) so we can # include it in cache_key query = options.delete(:query) if query.present? q = HTTParty::HashConversions.to_params(query) separator = s.include?('?') ? '&' : '?' s = "#{s}#{separator}#{q}" end URI.parse(s) end
ruby
{ "resource": "" }
q24084
Twittbot.BotPart.cmd
train
def cmd(name, options = {}, &block) raise "Command already exists: #{name}" if $bot[:commands].include? name raise "Command name does not contain only alphanumerical characters" unless name.to_s.match /\A[A-Za-z0-9]+\z/ opts = { admin: true }.merge(options) $bot[:commands][name] ||= { admin: opts[:admin], block: block } end
ruby
{ "resource": "" }
q24085
Twittbot.BotPart.task
train
def task(name, options = {}, &block) name = name.to_s.downcase.to_sym task_re = /\A[a-z0-9.:-_]+\z/ raise "Task already exists: #{name}" if $bot[:tasks].include?(name) raise "Task name does not match regexp #{task_re.to_s}" unless name.to_s.match(task_re) opts = { desc: '' }.merge(options) $bot[:tasks][name] ||= { block: block, desc: opts[:desc] } end
ruby
{ "resource": "" }
q24086
Twittbot.BotPart.save_config
train
def save_config botpart_config = Hash[@config.to_a - $bot[:config].to_a] unless botpart_config.empty? File.open @botpart_config_path, 'w' do |f| f.write botpart_config.to_yaml end end end
ruby
{ "resource": "" }
q24087
CFoundry::V2.App.health
train
def health if state == "STARTED" healthy_count = running_instances expected = total_instances if expected > 0 ratio = healthy_count / expected.to_f if ratio == 1.0 "RUNNING" else "#{(ratio * 100).to_i}%" end else "N/A" end else state end rescue CFoundry::StagingError, CFoundry::NotStaged "STAGING FAILED" end
ruby
{ "resource": "" }
q24088
CFoundry::V2.App.bind
train
def bind(*instances) instances.each do |i| binding = @client.service_binding binding.app = self binding.service_instance = i binding.create! end self end
ruby
{ "resource": "" }
q24089
CFoundry::V2.App.unbind
train
def unbind(*instances) service_bindings.each do |b| if instances.include? b.service_instance b.delete! end end self end
ruby
{ "resource": "" }
q24090
Metar.Station.parser
train
def parser raw = Metar::Raw::Noaa.new(@cccc) Metar::Parser.new(raw) end
ruby
{ "resource": "" }
q24091
Openfoodfacts.Product.weburl
train
def weburl(locale: nil, domain: DEFAULT_DOMAIN) locale ||= self.lc || DEFAULT_LOCALE if self.code && prefix = LOCALE_WEBURL_PREFIXES[locale] path = "#{prefix}/#{self.code}" "https://#{locale}.#{domain}/#{path}" end end
ruby
{ "resource": "" }
q24092
Metar.Parser.seek_visibility
train
def seek_visibility if observer.value == :auto # WMO 15.4 if @chunks[0] == '////' @chunks.shift # Simply dispose of it return end end if @chunks[0] == '1' or @chunks[0] == '2' @visibility = Metar::Data::Visibility.parse(@chunks[0] + ' ' + @chunks[1]) if @visibility @chunks.shift @chunks.shift end else @visibility = Metar::Data::Visibility.parse(@chunks[0]) if @visibility @chunks.shift end end @visibility end
ruby
{ "resource": "" }
q24093
Phys.Unit.inspect
train
def inspect use_dimension a = [Utils.num_inspect(@factor), @dim.inspect] a << "@name="+@name.inspect if @name a << "@expr="+@expr.inspect if @expr a << "@offset="+@offset.inspect if @offset a << "@dimensionless=true" if @dimensionless if @dimension_value && @dimension_value!=1 a << "@dimension_value="+@dimension_value.inspect end s = a.join(",") "#<#{self.class} #{s}>" end
ruby
{ "resource": "" }
q24094
Phys.Unit.unit_string
train
def unit_string use_dimension a = [] a << Utils.num_inspect(@factor) if @factor!=1 a += @dim.map do |k,d| if d==1 k else "#{k}^#{d}" end end a.join(" ") end
ruby
{ "resource": "" }
q24095
Phys.Unit.conversion_factor
train
def conversion_factor use_dimension f = @factor @dim.each do |k,d| if d != 0 u = LIST[k] if u.dimensionless? f *= u.dimension_value**d end end end f end
ruby
{ "resource": "" }
q24096
Phys.Unit.convert
train
def convert(quantity) if Quantity===quantity assert_same_dimension(quantity.unit) v = quantity.unit.convert_value_to_base_unit(quantity.value) convert_value_from_base_unit(v) else quantity / to_numeric end end
ruby
{ "resource": "" }
q24097
Phys.Unit.convert_scale
train
def convert_scale(quantity) if Quantity===quantity assert_same_dimension(quantity.unit) v = quantity.value * quantity.unit.conversion_factor v = v / self.conversion_factor else quantity / to_numeric end end
ruby
{ "resource": "" }
q24098
Phys.Unit.+
train
def +(x) x = Unit.cast(x) check_operable2(x) assert_same_dimension(x) Unit.new(@factor+x.factor,@dim.dup) end
ruby
{ "resource": "" }
q24099
Phys.Unit.*
train
def *(x) x = Unit.cast(x) if scalar? return x elsif x.scalar? return self.dup end check_operable2(x) dims = dimension_binop(x){|a,b| a+b} factor = self.factor * x.factor Unit.new(factor,dims) end
ruby
{ "resource": "" }