_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q10000
LatoBlog.Back::PostsController.destroy
train
def destroy @post = LatoBlog::Post.find_by(id: params[:id]) return unless check_post_presence unless @post.destroy flash[:danger] = @post.post_parent.errors.full_messages.to_sentence redirect_to lato_blog.edit_post_path(@post.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:post_destroy_success] redirect_to lato_blog.posts_path(status: 'deleted') end
ruby
{ "resource": "" }
q10001
LatoBlog.Back::PostsController.destroy_all_deleted
train
def destroy_all_deleted @posts = LatoBlog::Post.deleted if !@posts || @posts.empty? flash[:warning] = LANGUAGES[:lato_blog][:flashes][:deleted_posts_not_found] redirect_to lato_blog.posts_path(status: 'deleted') return end @posts.each do |post| unless post.destroy flash[:danger] = post.errors.full_messages.to_sentence redirect_to lato_blog.edit_post_path(post.id) return end end flash[:success] = LANGUAGES[:lato_blog][:flashes][:deleted_posts_destroy_success] redirect_to lato_blog.posts_path(status: 'deleted') end
ruby
{ "resource": "" }
q10002
LatoBlog.Back::PostsController.update_field
train
def update_field(field, value) case field.typology when 'text' update_field_text(field, value) when 'textarea' update_field_textarea(field, value) when 'datetime' update_field_datetime(field, value) when 'editor' update_field_editor(field, value) when 'geolocalization' update_field_geolocalization(field, value) when 'image' update_field_image(field, value) when 'gallery' update_field_gallery(field, value) when 'youtube' update_field_youtube(field, value) when 'composed' update_field_composed(field, value) when 'relay' update_field_relay(field, value) end end
ruby
{ "resource": "" }
q10003
BlipTV.Video.get_attributes
train
def get_attributes url = URI.parse('http://www.blip.tv/') res = Net::HTTP.start(url.host, url.port) {|http| http.get("http://www.blip.tv/file/#{@id.to_s}?skin=api") } hash = Hash.from_xml(res.body) if hash["response"]["status"] != "OK" raise VideoResponseError.new(hash["response"]["notice"]) end if hash["response"]["payload"]["asset"].is_a?(Array) return hash["response"]["payload"]["asset"][0] # there may be several assets. In that case, read the first one else return hash["response"]["payload"]["asset"] end end
ruby
{ "resource": "" }
q10004
BlipTV.Video.delete!
train
def delete!(creds = {}, section = "file", reason = "because") BlipTV::ApiSpec.check_attributes('videos.delete', creds) reason = reason.gsub(" ", "%20") # TODO write a method to handle this and other illegalities of URL if creds[:username] && !creds[:userlogin] creds[:userlogin] = creds[:username] end url, path = "www.blip.tv", "/?userlogin=#{creds[:userlogin]}&password=#{creds[:password]}&cmd=delete&s=file&id=#{@id}&reason=#{reason}&skin=api" request = Net::HTTP.get(url, path) hash = Hash.from_xml(request) make_sure_video_was_deleted(hash) end
ruby
{ "resource": "" }
q10005
Rester.Service._response
train
def _response(status, body=nil, headers={}) body = [body].compact headers = headers.merge("Content-Type" => "application/json") Rack::Response.new(body, status, headers).finish end
ruby
{ "resource": "" }
q10006
Ablerc.DSL.option
train
def option(name, behaviors = {}, &block) Ablerc.options << Ablerc::Option.new(name, behaviors, &block) end
ruby
{ "resource": "" }
q10007
MIPPeR.Variable.value
train
def value # Model must be solved to have a value return nil unless @model && @model.status == :optimized value = @model.variable_value self case @type when :integer value.round when :binary [false, true][value.round] else value end end
ruby
{ "resource": "" }
q10008
VRTK::Applets.VersionApplet.run_parse
train
def run_parse obj = { 'name' => VRTK::NAME, 'version' => VRTK::VERSION, 'codename' => VRTK::CODENAME, 'ffmpeg' => ffmpeg_version, 'magick' => magick_version, 'license' => VRTK::LICENSE } puts JSON.pretty_unparse obj end
ruby
{ "resource": "" }
q10009
TF2R.Scraper.scrape_main_page
train
def scrape_main_page page = fetch('http://tf2r.com/raffles.html') # All raffle links begin with 'tf2r.com/k' raffle_links = page.links_with(href: /tf2r\.com\/k/) raffle_links.map! { |x| x.uri.to_s } raffle_links.reverse! end
ruby
{ "resource": "" }
q10010
TF2R.Scraper.scrape_raffle_for_creator
train
def scrape_raffle_for_creator(page) # Reag classed some things "raffle_infomation". That's spelled right. infos = page.parser.css('.raffle_infomation') # The main 'a' element, containing the creator's username. user_anchor = infos[2].css('a')[0] steam_id = extract_steam_id(user_anchor.attribute('href').to_s) username = user_anchor.text avatar_link = infos[1].css('img')[0].attribute('src').to_s posrep = /(\d+)/.match(infos.css('.upvb').text)[1].to_i negrep = /(\d+)/.match(infos.css('.downvb').text)[1].to_i # The creator's username color. Corresponds to rank. color = extract_color(user_anchor.attribute('style').to_s) {steam_id: steam_id, username: username, avatar_link: avatar_link, posrep: posrep, negrep: negrep, color: color} end
ruby
{ "resource": "" }
q10011
TF2R.Scraper.scrape_raffle_for_raffle
train
def scrape_raffle_for_raffle(page) # Reag classed some things "raffle_infomation". That's spelled right. infos = page.parser.css('.raffle_infomation') # Elements of the main raffle info table. raffle_tds = infos[3].css('td') # 'kabc123' for http://tf2r.com/kabc123.html' link_snippet = extract_link_snippet(page.uri.path) title = extract_title(infos[0].text) description = raffle_tds[1].text # This doesn't work right now, because Miz just displays "10%" in the # page HTML and updates it with JS after a call to the API. # win_chance = /(.+)%/.match(infos.css('#winc').text)[1].to_f / 100 start_time = extract_start_time(raffle_tds[9]) end_time = extract_end_time(raffle_tds[11]) {link_snippet: link_snippet, title: title, description: description, start_time: start_time, end_time: end_time} end
ruby
{ "resource": "" }
q10012
TF2R.Scraper.scrape_raffle_for_participants
train
def scrape_raffle_for_participants(page) participants = [] participant_divs = page.parser.css('.pentry') participant_divs.each do |participant| user_anchor = participant.children[1] steam_id = extract_steam_id(user_anchor.to_s) username = participant.text color = extract_color(user_anchor.children[0].attribute('style')) participants << {steam_id: steam_id, username: username, color: color} end participants.reverse! end
ruby
{ "resource": "" }
q10013
TF2R.Scraper.scrape_user
train
def scrape_user(user_page) if user_page.parser.css('.profile_info').empty? raise InvalidUserPage, 'The given page does not correspond to any user.' else infos = user_page.parser.css('.raffle_infomation') #sic user_anchor = infos[1].css('a')[0] steam_id = extract_steam_id(user_page.uri.to_s) username = /TF2R Item Raffles - (.+)/.match(user_page.title)[1] avatar_link = infos[0].css('img')[0].attribute('src').to_s posrep = infos.css('.upvb').text.to_i negrep = infos.css('.downvb').text.to_i color = extract_color(user_anchor.attribute('style').to_s) end {steam_id: steam_id, username: username, avatar_link: avatar_link, posrep: posrep, negrep: negrep, color: color} end
ruby
{ "resource": "" }
q10014
TF2R.Scraper.scrape_ranks
train
def scrape_ranks(info_page) rank_divs = info_page.parser.css('#ranks').children ranks = rank_divs.select { |div| div.children.size == 3 } ranks.map { |div| extract_rank(div) } end
ruby
{ "resource": "" }
q10015
SlackBotManager.Connection.start
train
def start # Clear RTM connections storage.delete_all(teams_key) # Start a new connection for each team storage.get_all(tokens_key).each do |id, token| create(id, token) end end
ruby
{ "resource": "" }
q10016
SlackBotManager.Connection.stop
train
def stop # Thread wrapped to ensure no lock issues on shutdown thr = Thread.new do conns = storage.get_all(teams_key) storage.pipeline do conns.each { |k, _| storage.set(teams_key, k, 'destroy') } end info('Stopped.') end thr.join end
ruby
{ "resource": "" }
q10017
SlackBotManager.Connection.restart
train
def restart conns = storage.get_all(teams_key) storage.pipeline do conns.each { |k, _| storage.set(teams_key, k, 'restart') } end end
ruby
{ "resource": "" }
q10018
SlackBotManager.Connection.find_connection
train
def find_connection(id) connections.each do |_, conn| return (conn.connected? ? conn : false) if conn && conn.id == id end false end
ruby
{ "resource": "" }
q10019
SlackBotManager.Connection.create
train
def create(id, token) fail SlackBotManager::TokenAlreadyConnected if find_connection(id) # Create connection conn = SlackBotManager::Client.new(token) conn.connect # Add to connections using a uniq token if conn cid = [id, Time.now.to_i].join(':') connections[cid] = conn info("Connected: #{id} (Connection: #{cid})") storage.set(teams_key, id, 'active') end rescue => err on_error(err) end
ruby
{ "resource": "" }
q10020
SlackBotManager.Connection.destroy
train
def destroy(*args) options = args.extract_options! # Get connection or search for connection with cid if options[:cid] conn = connections[options[:cid]] cid = options[:cid] elsif options[:id] conn, cid = find_connection(options[:id]) end return false unless conn && cid # Kill connection, remove from keys, and delete from list begin thr = Thread.new do storage.delete(teams_key, conn.id) rescue nil storage.delete(tokens_key, conn.id) rescue nil if options[:remove_token] end thr.join connections.delete(cid) rescue nil end rescue => err on_error(err) end
ruby
{ "resource": "" }
q10021
Controll::Flow::Action.PathAction.method_missing
train
def method_missing(method_name, *args, &block) if controller.respond_to? method_name controller.send method_name, *args, &block else super end end
ruby
{ "resource": "" }
q10022
SmartQue.Publisher.publish
train
def publish(queue, payload = {}) # Check queue name includes in the configured list # Return if queue doesn't exist if queue_list.include? queue # Publish sms to queue begin x_direct.publish( payload.to_json, mandatory: true, routing_key: get_queue(queue).name ) log_message("Publish status: success, Queue : #{queue}, Content : #{payload}") :success rescue => ex log_message("Publish error:#{ex.message}") :error end else log_message("Publish status: failed, Queue(#{queue}) doesn't exist.") log_message("Content : #{payload}") raise QueueNotFoundError end end
ruby
{ "resource": "" }
q10023
SmartQue.Publisher.unicast
train
def unicast(q_name, payload = {}) begin x_default.publish( payload.to_json, routing_key: dot_formatted(q_name) ) log_message("unicast status: success, Queue : #{q_name}, Content : #{payload}") :success rescue => ex log_message("Unicast error:#{ex.message}") :error end end
ruby
{ "resource": "" }
q10024
SmartQue.Publisher.multicast
train
def multicast(topic, payload = {}) begin x_topic.publish( payload.to_json, routing_key: dot_formatted(topic) ) log_message("multicast status: success, Topic : #{topic}, Content : #{payload}") :success rescue => ex log_message("Multicast error:#{ex.message}") :error end end
ruby
{ "resource": "" }
q10025
XS.PollItems.clean
train
def clean if @dirty @store = FFI::MemoryPointer.new @element_size, @items.size, true # copy over offset = 0 @items.each do |item| LibC.memcpy(@store + offset, item.pointer, @element_size) offset += @element_size end @dirty = false end end
ruby
{ "resource": "" }
q10026
XES.Attribute.format_value
train
def format_value case @type when "string" @value when "date" @value.kind_of?(Time) ? @value.iso8601(3) : @value when "int" @value.kind_of?(Integer) ? @value : @value.to_i when "float" @value.kind_of?(Float) ? @value : @value.to_f when "boolean" @value when "id" @value end.to_s end
ruby
{ "resource": "" }
q10027
ActiveParams.Parser.combine_hashes
train
def combine_hashes(array_of_hashes) array_of_hashes.select {|v| v.kind_of?(Hash) }. inject({}) {|sum, hash| hash.inject(sum) {|sum,(k,v)| sum.merge(k => v) } } end
ruby
{ "resource": "" }
q10028
Citero.Base.from
train
def from format #Formats are enums in java, so they are all uppercase @citero = @citero::from(Formats::valueOf(format.upcase)) self #rescue any exceptions, if the error is not caught in JAR, most likely a #problem with the data rescue Exception => e raise TypeError, "Mismatched data for #{format}" end
ruby
{ "resource": "" }
q10029
Citero.Base.to
train
def to format #Formats are enums in java, so they are all uppercase if to_formats.include? format @citero::to(Formats::valueOf(format.upcase)) else @citero::to(CitationStyles::valueOf(format.upcase)) end #rescue any exceptions, if the error is not caught in JAR, most likely a #problem with the source format rescue Exception => e raise ArgumentError, "Missing a source format. Use from_[format] first." end
ruby
{ "resource": "" }
q10030
DataPaths.Finders.each_data_path
train
def each_data_path(path) return enum_for(:each_data_path,path) unless block_given? DataPaths.paths.each do |dir| full_path = File.join(dir,path) yield(full_path) if File.exists?(full_path) end end
ruby
{ "resource": "" }
q10031
DataPaths.Finders.each_data_file
train
def each_data_file(path) return enum_for(:each_data_file,path) unless block_given? each_data_path(path) do |full_path| yield(full_path) if File.file?(full_path) end end
ruby
{ "resource": "" }
q10032
DataPaths.Finders.each_data_dir
train
def each_data_dir(path) return enum_for(:each_data_dir,path) unless block_given? each_data_path(path) do |full_path| yield(full_path) if File.directory?(full_path) end end
ruby
{ "resource": "" }
q10033
DataPaths.Finders.glob_data_paths
train
def glob_data_paths(pattern,&block) return enum_for(:glob_data_paths,pattern).to_a unless block_given? DataPaths.paths.each do |path| Dir.glob(File.join(path,pattern),&block) end end
ruby
{ "resource": "" }
q10034
Loco.Resizable.initWithFrame
train
def initWithFrame(properties={}) if properties.is_a? Hash # Set the initial property values from the given hash super(CGRect.new) initialize_bindings set_properties(properties) else super(properties) end view_setup self end
ruby
{ "resource": "" }
q10035
MultiSync.Client.add_target
train
def add_target(clazz, options = {}) # TODO: friendly pool names? pool_name = Celluloid.uuid supervisor.pool(clazz, as: pool_name, args: [options], size: MultiSync.target_pool_size) pool_name end
ruby
{ "resource": "" }
q10036
Cyclical.YearlyRule.potential_next
train
def potential_next(current, base) candidate = super(current, base) return candidate if (base.year - candidate.year).to_i % @interval == 0 years = ((base.year - candidate.year).to_i % @interval) (candidate + years.years).beginning_of_year end
ruby
{ "resource": "" }
q10037
ICU.Tournament.fed=
train
def fed=(fed) obj = ICU::Federation.find(fed) @fed = obj ? obj.code : nil raise "invalid tournament federation (#{fed})" if @fed.nil? && fed.to_s.strip.length > 0 end
ruby
{ "resource": "" }
q10038
ICU.Tournament.add_round_date
train
def add_round_date(round_date) round_date = round_date.to_s.strip parsed_date = Util::Date.parse(round_date) raise "invalid round date (#{round_date})" unless parsed_date @round_dates << parsed_date end
ruby
{ "resource": "" }
q10039
ICU.Tournament.tie_breaks=
train
def tie_breaks=(tie_breaks) raise "argument error - always set tie breaks to an array" unless tie_breaks.class == Array @tie_breaks = tie_breaks.map do |str| tb = ICU::TieBreak.identify(str) raise "invalid tie break method '#{str}'" unless tb tb.id end end
ruby
{ "resource": "" }
q10040
ICU.Tournament.add_player
train
def add_player(player) raise "invalid player" unless player.class == ICU::Player raise "player number (#{player.num}) should be unique" if @player[player.num] @player[player.num] = player end
ruby
{ "resource": "" }
q10041
ICU.Tournament.rerank
train
def rerank tie_break_methods, tie_break_order, tie_break_hash = tie_break_data @player.values.sort do |a,b| cmp = 0 tie_break_methods.each do |m| cmp = (tie_break_hash[m][a.num] <=> tie_break_hash[m][b.num]) * tie_break_order[m] if cmp == 0 end cmp end.each_with_index do |p,i| p.rank = i + 1 end self end
ruby
{ "resource": "" }
q10042
ICU.Tournament.renumber
train
def renumber(criterion = :rank) if (criterion.class == Hash) # Undocumentted feature - supply your own hash. map = criterion else # Official way of reordering. map = Hash.new # Renumber by rank only if possible. criterion = criterion.to_s.downcase if criterion == 'rank' begin check_ranks rescue criterion = 'name' end end # Decide how to renumber. if criterion == 'rank' # Renumber by rank. @player.values.each{ |p| map[p.num] = p.rank } elsif criterion == 'order' # Just keep the existing numbers in order. @player.values.sort_by{ |p| p.num }.each_with_index{ |p, i| map[p.num] = i + 1 } else # Renumber by name alphabetically. @player.values.sort_by{ |p| p.name }.each_with_index{ |p, i| map[p.num] = i + 1 } end end # Apply renumbering. @teams.each{ |t| t.renumber(map) } @player = @player.values.inject({}) do |hash, player| player.renumber(map) hash[player.num] = player hash end # Return self for chaining. self end
ruby
{ "resource": "" }
q10043
ICU.Tournament.validate!
train
def validate!(options={}) begin check_ranks rescue rerank end if options[:rerank] check_players check_rounds check_dates check_teams check_ranks(:allow_none => true) check_type(options[:type]) if options[:type] true end
ruby
{ "resource": "" }
q10044
ICU.Tournament.serialize
train
def serialize(format, arg={}) serializer = case format.to_s.downcase when 'krause' then ICU::Tournament::Krause.new when 'foreigncsv' then ICU::Tournament::ForeignCSV.new when 'spexport' then ICU::Tournament::SPExport.new when '' then raise "no format supplied" else raise "unsupported serialisation format: '#{format}'" end serializer.serialize(self, arg) end
ruby
{ "resource": "" }
q10045
ICU.Tournament.check_players
train
def check_players raise "the number of players (#{@player.size}) must be at least 2" if @player.size < 2 ids = Hash.new fide_ids = Hash.new @player.each do |num, p| if p.id raise "duplicate ICU IDs, players #{p.num} and #{ids[p.id]}" if ids[p.id] ids[p.id] = num end if p.fide_id raise "duplicate FIDE IDs, players #{p.num} and #{fide_ids[p.fide_id]}" if fide_ids[p.fide_id] fide_ids[p.fide_id] = num end return if p.results.size == 0 p.results.each do |r| next unless r.opponent opponent = @player[r.opponent] raise "opponent #{r.opponent} of player #{num} is not in the tournament" unless opponent o = opponent.find_result(r.round) raise "opponent #{r.opponent} of player #{num} has no result in round #{r.round}" unless o score = r.rateable || o.rateable ? [] : [:score] raise "opponent's result (#{o.inspect}) is not reverse of player's (#{r.inspect})" unless o.reverse.eql?(r, :except => score) end end end
ruby
{ "resource": "" }
q10046
ICU.Tournament.check_rounds
train
def check_rounds round = Hash.new round_last = last_round @player.values.each do |p| p.results.each do |r| round[r.round] = true end end (1..round_last).each { |r| raise "there are no results for round #{r}" unless round[r] } if rounds raise "declared number of rounds is #{rounds} but there are results in later rounds, such as #{round_last}" if rounds < round_last raise "declared number of rounds is #{rounds} but there are no results with rounds greater than #{round_last}" if rounds > round_last else self.rounds = round_last end end
ruby
{ "resource": "" }
q10047
ICU.Tournament.check_dates
train
def check_dates raise "start date (#{start}) is after end date (#{finish})" if @start && @finish && @start > @finish if @round_dates.size > 0 raise "the number of round dates (#{@round_dates.size}) does not match the number of rounds (#{@rounds})" unless @round_dates.size == @rounds raise "the date of the first round (#{@round_dates[0]}) does not match the start (#{@start}) of the tournament" if @start && @start != @round_dates[0] raise "the date of the last round (#{@round_dates[-1]}) does not match the end (#{@finish}) of the tournament" if @finish && @finish != @round_dates[-1] (2..@round_dates.size).to_a.each do |r| #puts "#{@round_dates[r-2]} => #{@round_dates[r-1]}" raise "the date of round #{r-1} (#{@round_dates[r-2]}) is after the date of round #{r} (#{@round_dates[r-1]}) of the tournament" if @round_dates[r-2] > @round_dates[r-1] end @finish = @round_dates[-1] unless @finish end end
ruby
{ "resource": "" }
q10048
ICU.Tournament.check_type
train
def check_type(type) if type.respond_to?(:validate!) type.validate!(self) elsif klass = self.class.factory(type.to_s) klass.new.validate!(self) else raise "invalid type supplied for validation check" end end
ruby
{ "resource": "" }
q10049
ICU.Tournament.tie_break_score
train
def tie_break_score(hash, method, player, rounds) case method when :score then player.points when :wins then player.results.inject(0) { |t,r| t + (r.opponent && r.score == 'W' ? 1 : 0) } when :blacks then player.results.inject(0) { |t,r| t + (r.opponent && r.colour == 'B' ? 1 : 0) } when :buchholz then player.results.inject(0.0) { |t,r| t + (r.opponent ? hash[:opp_score][r.opponent] : 0.0) } when :neustadtl then player.results.inject(0.0) { |t,r| t + (r.opponent ? hash[:opp_score][r.opponent] * r.points : 0.0) } when :opp_score then player.results.inject(0.0) { |t,r| t + (r.opponent ? r.points : 0.5) } + (rounds - player.results.size) * 0.5 when :progressive then (1..rounds).inject(0.0) { |t,n| r = player.find_result(n); s = r ? r.points : 0.0; t + s * (rounds + 1 - n) } when :ratings then player.results.inject(0) { |t,r| t + (r.opponent && (@player[r.opponent].fide_rating || @player[r.opponent].rating) ? (@player[r.opponent].fide_rating || @player[r.opponent].rating) : 0) } when :harkness, :modified_median scores = player.results.map{ |r| r.opponent ? hash[:opp_score][r.opponent] : 0.0 }.sort 1.upto(rounds - player.results.size) { scores << 0.0 } half = rounds / 2.0 times = rounds >= 9 ? 2 : 1 if method == :harkness || player.points == half 1.upto(times) { scores.shift; scores.pop } else 1.upto(times) { scores.send(player.points > half ? :shift : :pop) } end scores.inject(0.0) { |t,s| t + s } else player.name end end
ruby
{ "resource": "" }
q10050
Capnotify.Plugin.deployed_by
train
def deployed_by username = nil scm = fetch(:scm, nil) if scm if scm.to_sym == :git username = `git config user.name`.chomp username = nil if $? != 0 || username.strip == '' end end username || `whoami`.chomp end
ruby
{ "resource": "" }
q10051
Capnotify.Plugin.unload_plugin
train
def unload_plugin(name) p = get_plugin(name) p.unload if p.respond_to?(:unload) Capistrano.remove_plugin(name) end
ruby
{ "resource": "" }
q10052
Capnotify.Plugin.get_plugin
train
def get_plugin(name) raise "Unknown plugin: #{ name }" unless Capistrano::EXTENSIONS.keys.include?(name) self.send(name) end
ruby
{ "resource": "" }
q10053
Capnotify.Plugin.build_template
train
def build_template(template_path) # FIXME: this is called every time build_template is called. # although this is idepodent, it's got room for optimization self.build_components! ERB.new( File.open( template_path ).read, nil, '<>' ).result(self.binding) end
ruby
{ "resource": "" }
q10054
Capnotify.Plugin.component
train
def component(name) components.each { |c| return c if c.name == name.to_sym } return nil end
ruby
{ "resource": "" }
q10055
Capnotify.Plugin.insert_component_before
train
def insert_component_before(name, component) # iterate over all components, find the component with the given name # once found, insert the given component at that location and return components.each_with_index do |c, i| if c.name == name components.insert(i, component) return end end components << component end
ruby
{ "resource": "" }
q10056
Capnotify.Plugin.insert_component_after
train
def insert_component_after(name, component) # iterate over all components, find the component with the given name # once found, insert the given component at the following location and return components.each_with_index do |c, i| if c.name == name components.insert(i + 1, component) return end end components << component end
ruby
{ "resource": "" }
q10057
Networkr.MultiGraph.new_edge_key
train
def new_edge_key(u, v) if @adj[u] && @adj[u][v] keys = @adj[u][v] key = keys.length while keys.include?(key) key += 1 end return key else return 0 end end
ruby
{ "resource": "" }
q10058
GhContributors.Calculator.calculated_data
train
def calculated_data @data ||= @raw_data.group_by { |contributor| contributor['login'] }.map {|login, data| log "user: #{login}" [login, user_data(login, data)] }.sort_by{|login, data| [1000000/data['contributions'], login] } end
ruby
{ "resource": "" }
q10059
Scat.Cache.start
train
def start(redis) logger.debug { "Scat is starting the Redis cache server..." } unless system(REDIS_SERVER, REDIS_CONF) then raise ScatError.new("Scat cannot start the Redis cache server.") end # Ping the server until loaded. 3.times do |n| begin redis.ping logger.debug { "Scat started the Redis cache server." } return redis rescue n < 2 ? sleep(0.5) : raise end end end
ruby
{ "resource": "" }
q10060
Redlander.Model.query
train
def query(q, options = {}, &block) query = Query::Results.new(q, options) query.process(self, &block) end
ruby
{ "resource": "" }
q10061
Octo.Funnel.populate_with_fake_data
train
def populate_with_fake_data(interval_days = 7) if self.enterprise.fakedata? today = Time.now.beginning_of_day (today - interval_days.days).to(today, 24.hour).each do |ts| Octo::FunnelData.new( enterprise_id: self.enterprise_id, funnel_slug: self.name_slug, ts: ts, value: fake_data(self.funnel.count) ).save! end end end
ruby
{ "resource": "" }
q10062
Octo.Funnel.data
train
def data(ts = Time.now.floor) args = { enterprise_id: self.enterprise.id, funnel_slug: self.name_slug, ts: ts } res = Octo::FunnelData.where(args) if res.count > 0 res.first elsif self.enterprise.fakedata? args.merge!({ value: fake_data(self.funnel.count) }) Octo::FunnelData.new(args).save! end end
ruby
{ "resource": "" }
q10063
Octo.Funnel.fake_data
train
def fake_data(n) fun = Array.new(n) max_dropoff = 100/n n.times do |i| if i == 0 fun[i] = 100.0 else fun[i] = fun[i-1] - rand(1..max_dropoff) if fun[i] < 0 fun[i] = rand(0...fun[i].abs) end end end fun end
ruby
{ "resource": "" }
q10064
SlackBotManager.Client.handle_error
train
def handle_error(err, data = nil) case determine_error_type(err) when :token_revoked on_revoke(data) when :rate_limited on_rate_limit(data) when :closed on_close(data) else on_error(err, data) end end
ruby
{ "resource": "" }
q10065
Activr.Storage.find_activity
train
def find_activity(activity_id) activity_hash = self.driver.find_activity(activity_id) if activity_hash # run hook self.run_hook(:did_find_activity, activity_hash) # unserialize Activr::Activity.from_hash(activity_hash) else nil end end
ruby
{ "resource": "" }
q10066
Activr.Storage.find_activities
train
def find_activities(limit, options = { }) # default options options = { :skip => 0, :before => nil, :after => nil, :entities => { }, :only => [ ], :except => [ ], }.merge(options) options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Array)) # find result = self.driver.find_activities(limit, options).map do |activity_hash| # run hook self.run_hook(:did_find_activity, activity_hash) # unserialize Activr::Activity.from_hash(activity_hash) end result end
ruby
{ "resource": "" }
q10067
Activr.Storage.count_activities
train
def count_activities(options = { }) # default options options = { :before => nil, :after => nil, :entities => { }, :only => [ ], :except => [ ], }.merge(options) options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Array)) # count self.driver.count_activities(options) end
ruby
{ "resource": "" }
q10068
Activr.Storage.count_duplicate_activities
train
def count_duplicate_activities(activity, after) entities = { } activity.entities.each do |entity_name, entity| entities[entity_name.to_sym] = entity.model_id end self.count_activities({ :only => activity.class, :entities => entities, :after => after, }) end
ruby
{ "resource": "" }
q10069
Activr.Storage.delete_activities_for_entity_model
train
def delete_activities_for_entity_model(model) Activr.registry.activity_entities_for_model(model.class).each do |entity_name| self.driver.delete_activities(:entities => { entity_name => model.id }) end end
ruby
{ "resource": "" }
q10070
Activr.Storage.find_timeline_entry
train
def find_timeline_entry(timeline, tl_entry_id) timeline_entry_hash = self.driver.find_timeline_entry(timeline.kind, tl_entry_id) if timeline_entry_hash # run hook self.run_hook(:did_find_timeline_entry, timeline_entry_hash, timeline.class) # unserialize Activr::Timeline::Entry.from_hash(timeline_entry_hash, timeline) else nil end end
ruby
{ "resource": "" }
q10071
Activr.Storage.find_timeline
train
def find_timeline(timeline, limit, options = { }) options = { :skip => 0, :only => [ ], }.merge(options) options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Array)) result = self.driver.find_timeline_entries(timeline.kind, timeline.recipient_id, limit, options).map do |timeline_entry_hash| # run hook self.run_hook(:did_find_timeline_entry, timeline_entry_hash, timeline.class) # unserialize Activr::Timeline::Entry.from_hash(timeline_entry_hash, timeline) end result end
ruby
{ "resource": "" }
q10072
Activr.Storage.count_timeline
train
def count_timeline(timeline, options = { }) options = { :only => [ ], }.merge(options) options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Array)) self.driver.count_timeline_entries(timeline.kind, timeline.recipient_id, options) end
ruby
{ "resource": "" }
q10073
Activr.Storage.delete_timeline
train
def delete_timeline(timeline, options = { }) # default options options = { :before => nil, :entities => { }, }.merge(options) self.driver.delete_timeline_entries(timeline.kind, timeline.recipient_id, options) end
ruby
{ "resource": "" }
q10074
Activr.Storage.delete_timeline_entries_for_entity_model
train
def delete_timeline_entries_for_entity_model(model) Activr.registry.timeline_entities_for_model(model.class).each do |timeline_class, entities| entities.each do |entity_name| self.driver.delete_timeline_entries(timeline_class.kind, nil, :entities => { entity_name => model.id }) end end end
ruby
{ "resource": "" }
q10075
Activr.Storage.run_hook
train
def run_hook(name, *args) return if @hooks[name].blank? @hooks[name].each do |hook| args.any? ? hook.call(*args) : hook.call end end
ruby
{ "resource": "" }
q10076
Formant.FormObject.reformatted!
train
def reformatted! self.class.format_fields.each do |field_name, format_method, options| formatted_value = send(format_method, get_field(field_name), options) set_field(field_name, formatted_value) end self end
ruby
{ "resource": "" }
q10077
Formant.FormObject.to_params
train
def to_params attrs = Hash.new instance_variables.each do |ivar| name = ivar[1..-1] attrs[name.to_sym] = instance_variable_get(ivar) if respond_to? "#{name}=" end attrs end
ruby
{ "resource": "" }
q10078
ParamProtected.Protector.merge_protections
train
def merge_protections(protections, protected_params) protected_params.each do |k,v| if protections[k].is_a?(Hash) merge_protections(protections[k], v) if v else protections[k] = v end end protections end
ruby
{ "resource": "" }
q10079
SoundDrop.Drop.media_url
train
def media_url begin r = HTTParty.get("https://api.soundcloud.com/i1/tracks/#{id}/streams?client_id=#{@CLIENT.client_id}") r['http_mp3_128_url'] rescue Exception => ex raise SoundDrop::Exception::FailedRequest.new(ex) end end
ruby
{ "resource": "" }
q10080
ActiveAdminSimpleLife.SimpleMenu.for
train
def for(klass, options = {}, &blk) ActiveAdmin.register klass do options = {index: {}, form: {}, filter: {}}.merge options permitted_params = options.delete :permitted_params permit_params(*(klass.main_fields + (permitted_params || []))) # menu_options = options.slice(:priority, :parent, :if) menu options if options.any? actions :all, except: [:show] controller.class_variable_set(:@@permitted_params, permitted_params) controller.class_variable_set(:@@klass, klass) controller do def scoped_collection permitted_params = self.class.class_variable_get :@@permitted_params self.class.class_variable_get(:@@klass).includes(*permitted_params.map{|symbol| ExtensionedSymbol.new(symbol).cut_id}) end end if permitted_params %i[index filter form].each do |action| send "#{action}_for_main_fields", klass, options[action] unless options[action][:skip] == true end instance_exec &blk if block_given? end end
ruby
{ "resource": "" }
q10081
MissingText.Diff.generate_diff_for_language
train
def generate_diff_for_language(current_language, target_language) current_langmap = langmap[current_language] target_langmap = langmap[target_language] diffmap_key = [current_language, target_language] diffmap[diffmap_key] = current_langmap - target_langmap end
ruby
{ "resource": "" }
q10082
MissingText.Diff.make_keymap
train
def make_keymap(langmap_entry, language) language.each do |key, value| if value.is_a? Hash make_keymap_for(langmap_entry, value, [key.to_sym]) else langmap_entry << [key.to_sym] end end end
ruby
{ "resource": "" }
q10083
MissingText.Diff.make_keymap_for
train
def make_keymap_for(langmap_entry, language, key_path) language.each do |key, value| # need a new value of this for every value we are looking at because we want all route traces to have single threading for when they are called again new_path = Array.new key_path if value.is_a? Hash make_keymap_for(langmap_entry, value, new_path.push(key.to_s.to_sym)) else langmap_entry << new_path.push(key.to_s.to_sym) end end end
ruby
{ "resource": "" }
q10084
Scalaroid.TransactionSingleOp.write
train
def write(key, value, binary = false) value = @conn.class.encode_value(value, binary) result = @conn.call(:write, [key, value]) @conn.class.check_fail_abort(result) @conn.class.process_result_commit(result) end
ruby
{ "resource": "" }
q10085
Scalaroid.TransactionSingleOp.add_del_on_list
train
def add_del_on_list(key, to_add, to_remove) result = @conn.call(:add_del_on_list, [key, to_add, to_remove]) @conn.class.check_fail_abort(result) @conn.class.process_result_add_del_on_list(result) end
ruby
{ "resource": "" }
q10086
Scalaroid.TransactionSingleOp.add_on_nr
train
def add_on_nr(key, to_add) result = @conn.call(:add_on_nr, [key, to_add]) @conn.class.check_fail_abort(result) @conn.class.process_result_add_on_nr(result) end
ruby
{ "resource": "" }
q10087
Psc.Connection.has_superclass?
train
def has_superclass?(child, ancestor) if child.superclass == ancestor true elsif child.superclass.nil? false else has_superclass?(child.superclass, ancestor) end end
ruby
{ "resource": "" }
q10088
EndiFeed.News.process_news
train
def process_news(total = 25) items.map.with_index do |item, num| @headlines << format_headline(item, num) if total_met?(total) end.compact || nil end
ruby
{ "resource": "" }
q10089
Cul.LDAP.find_by_uni
train
def find_by_uni(uni) entries = search(base: "ou=People,o=Columbia University, c=US", filter: Net::LDAP::Filter.eq("uid", uni)) (entries.count == 1) ? entries.first : nil end
ruby
{ "resource": "" }
q10090
Cul.LDAP.find_by_name
train
def find_by_name(name) if name.include?(',') name = name.split(',').map(&:strip).reverse.join(" ") end entries = search(base: "ou=People,o=Columbia University, c=US", filter: Net::LDAP::Filter.eq("cn", name)) (entries.count == 1) ? entries.first : nil end
ruby
{ "resource": "" }
q10091
Glass.Client.rest_action
train
def rest_action(options, action="insert") body_object = json_content(options, action) inserting_content = { api_method: mirror_api.timeline.send(action), body_object: body_object} end
ruby
{ "resource": "" }
q10092
Glass.Client.list
train
def list(opts={as_hash: true}) page_token = nil parameters = {} self.timeline_list = [] begin parameters = {} parameters['pageToken'] = page_token if page_token.present? api_result = google_client.execute(api_method: mirror_api.timeline.list, parameters: parameters) if api_result.success? timeline_items = api_result.data page_token = nil if timeline_items.items.empty? if timeline_items.items.any? @timeline_list.concat(timeline_items.items) page_token = timeline_items.next_page_token end else puts "An error occurred: #{api_result.data['error']['message']}" page_token = nil end end while page_token.to_s != '' timeline_list(opts) end
ruby
{ "resource": "" }
q10093
Handlebarer.Serialize.to_hbs
train
def to_hbs h = {:model => self.class.name.downcase} self.hbs_attributes.each do |attr| h[attr] = self.send(attr) ans = h[attr].class.ancestors if h[attr].class.respond_to?(:hbs_serializable) || ans.include?(Enumerable) || ans.include?(ActiveModel::Validations) h[attr] = h[attr].to_hbs else end end h end
ruby
{ "resource": "" }
q10094
Handlebarer.Serialize.hbs_attributes
train
def hbs_attributes s = self.class.class_variable_get(:@@serialize) if s[:merge] attrs = s[:attrs] + self.attributes.keys else attrs = s[:attrs] end attrs.collect{|attr| attr.to_sym}.uniq end
ruby
{ "resource": "" }
q10095
HashThatTree.CompareMD5.validate
train
def validate if(folder1==nil) || (folder1=="") || !Dir.exists?(folder1) puts "a valid folder path is required as argument 1" exit end if(folder2==nil) || (folder2=="") || !Dir.exists?(folder2) puts "a valid folder path is required as argument 2" exit end end
ruby
{ "resource": "" }
q10096
HashThatTree.CompareMD5.display_results_html
train
def display_results_html output ="<!DOCTYPE html><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title></title></head><body>" output.concat("<table><thead><tr><td>FileName</td></tr><tr><td>#{@folder1}</td></tr><tr><td>#{@folder2}</td></tr><tr><td>Equal</td></tr></thead>") @filehash.each{ |key, value| output.concat("<tbody><tr><td>#{value.file_name}</td></tr><tr><td>#{value.file_hash1}</td></tr><tr><td>#{value.file_hash2}</td></tr><tr><td>#{value.file_hash1==value.file_hash2}</td></tr>")} output.concat("</tbody></table></body></html>") puts output end
ruby
{ "resource": "" }
q10097
Analects.Encoding.ratings
train
def ratings(str) all_valid_cjk(str).map do |enc| [ enc, recode(enc, str).codepoints.map do |point| Analects::Models::Zi.codepoint_ranges.map.with_index do |range, idx| next 6 - idx if range.include?(point) 0 end.inject(:+) end.inject(:+) ] end.sort_by(&:last).reverse end
ruby
{ "resource": "" }
q10098
ProjectEulerCli.Scraper.lookup_totals
train
def lookup_totals begin Timeout.timeout(4) do html = open("https://projecteuler.net/recent") fragment = Nokogiri::HTML(html) id_col = fragment.css('#problems_table td.id_column') # The newest problem is the first one listed on the recent page. The ID # of this problem will always equal the total number of problems. id_col.first.text.to_i.times { Problem.new } # There are ten problems on the recent page, so the last archive problem # can be found by subtracting 10 from the total number of problems. Page.total = Problem.page(Problem.total - 10) end rescue Timeout::Error puts "Project Euler is not responding." exit(true) end end
ruby
{ "resource": "" }
q10099
ProjectEulerCli.Scraper.load_recent
train
def load_recent return if Page.visited.include?(0) html = open("https://projecteuler.net/recent") fragment = Nokogiri::HTML(html) problem_links = fragment.css('#problems_table td a') i = Problem.total problem_links.each do |link| Problem[i].title = link.text i -= 1 end Page.visited << 0 end
ruby
{ "resource": "" }