repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
Beagle123/visualruby | lib/treeview/columns/CellRendererCombo.rb | VR::Col::Ren.CellRendererCombo.set_model | def set_model(vr_combo) # :nodoc:
self.model = Gtk::ListStore.new(String)
vr_combo.selections.each { |s| r = self.model.append ; r[0] = s }
self.text_column = 0
end | ruby | def set_model(vr_combo) # :nodoc:
self.model = Gtk::ListStore.new(String)
vr_combo.selections.each { |s| r = self.model.append ; r[0] = s }
self.text_column = 0
end | [
"def",
"set_model",
"(",
"vr_combo",
")",
"self",
".",
"model",
"=",
"Gtk",
"::",
"ListStore",
".",
"new",
"(",
"String",
")",
"vr_combo",
".",
"selections",
".",
"each",
"{",
"|",
"s",
"|",
"r",
"=",
"self",
".",
"model",
".",
"append",
";",
"r",
"[",
"0",
"]",
"=",
"s",
"}",
"self",
".",
"text_column",
"=",
"0",
"end"
]
| This sets the renderer's "editable" property to true, and makes it save
the edited value to the model. When a user edits a row in the ListView
the value isn't automatically saved by Gtk. This method groups both actions
together, so setting edit_save=true, allows both editing and saving of
the field.
Also, you can use VR::ListView and VR::TreeView's convenience methods to
envoke call this method:
NAME = 0
ADDR = 1
@view.set_attr([NAME, ADDR], :edit_save => true) #sets model_col = 0, 1
@view.set_edit_save( 0 => true, 1 => false)
is_editable = boolean | [
"This",
"sets",
"the",
"renderer",
"s",
"editable",
"property",
"to",
"true",
"and",
"makes",
"it",
"save",
"the",
"edited",
"value",
"to",
"the",
"model",
".",
"When",
"a",
"user",
"edits",
"a",
"row",
"in",
"the",
"ListView",
"the",
"value",
"isn",
"t",
"automatically",
"saved",
"by",
"Gtk",
".",
"This",
"method",
"groups",
"both",
"actions",
"together",
"so",
"setting",
"edit_save",
"=",
"true",
"allows",
"both",
"editing",
"and",
"saving",
"of",
"the",
"field",
"."
]
| 245e22864c9d7c7c4e6f92562447caa5d6a705a9 | https://github.com/Beagle123/visualruby/blob/245e22864c9d7c7c4e6f92562447caa5d6a705a9/lib/treeview/columns/CellRendererCombo.rb#L58-L62 | train |
Beagle123/visualruby | lib/treeview/FileTreeView.rb | VR.FileTreeView.refresh | def refresh(flags={})
@root = flags[:root] if flags[:root]
open_folders = flags[:open_folders] ? flags[:open_folders] : get_open_folders()
model.clear
@root_iter = add_file(@root, nil)
open_folders([@root_iter[:path]])
open_folders(open_folders)
end | ruby | def refresh(flags={})
@root = flags[:root] if flags[:root]
open_folders = flags[:open_folders] ? flags[:open_folders] : get_open_folders()
model.clear
@root_iter = add_file(@root, nil)
open_folders([@root_iter[:path]])
open_folders(open_folders)
end | [
"def",
"refresh",
"(",
"flags",
"=",
"{",
"}",
")",
"@root",
"=",
"flags",
"[",
":root",
"]",
"if",
"flags",
"[",
":root",
"]",
"open_folders",
"=",
"flags",
"[",
":open_folders",
"]",
"?",
"flags",
"[",
":open_folders",
"]",
":",
"get_open_folders",
"(",
")",
"model",
".",
"clear",
"@root_iter",
"=",
"add_file",
"(",
"@root",
",",
"nil",
")",
"open_folders",
"(",
"[",
"@root_iter",
"[",
":path",
"]",
"]",
")",
"open_folders",
"(",
"open_folders",
")",
"end"
]
| FileTreeView creates a TreeView of files with folders and icons.
Often you should subclass this class for a particular use.
@param [String] root Root folder of the tree
@param [String] icon_path Path to a folder where icons are stored. See VR::IconHash
@param [String] glob Glob designating the files to be included. Google: "ruby glob" for more.
@param [Proc] validate_block Block that limits files and folders to include. When block returns true file is includud. (false = excluded)
Refresh the file tree, optionally with a new root folder, and optionally opening an array of folders.
@param [Hash] flags You can change the root and/or open an array of folders.
@option flags [String] :root Path to root folder to open
@option flags [Array] :open_folders A list of folders to open, possibly from #get_open_folders.
Default: the currently open folders, so the tree doesn't collapse when refreshed. | [
"FileTreeView",
"creates",
"a",
"TreeView",
"of",
"files",
"with",
"folders",
"and",
"icons",
".",
"Often",
"you",
"should",
"subclass",
"this",
"class",
"for",
"a",
"particular",
"use",
"."
]
| 245e22864c9d7c7c4e6f92562447caa5d6a705a9 | https://github.com/Beagle123/visualruby/blob/245e22864c9d7c7c4e6f92562447caa5d6a705a9/lib/treeview/FileTreeView.rb#L45-L52 | train |
Beagle123/visualruby | lib/treeview/FileTreeView.rb | VR.FileTreeView.open_folders | def open_folders(folder_paths)
model.each do |model, path, iter|
if folder_paths.include?(iter[id(:path)])
fill_folder(iter)
# expand_row(path, false)
# self__row_expanded(self, iter, path)
end
end
end | ruby | def open_folders(folder_paths)
model.each do |model, path, iter|
if folder_paths.include?(iter[id(:path)])
fill_folder(iter)
# expand_row(path, false)
# self__row_expanded(self, iter, path)
end
end
end | [
"def",
"open_folders",
"(",
"folder_paths",
")",
"model",
".",
"each",
"do",
"|",
"model",
",",
"path",
",",
"iter",
"|",
"if",
"folder_paths",
".",
"include?",
"(",
"iter",
"[",
"id",
"(",
":path",
")",
"]",
")",
"fill_folder",
"(",
"iter",
")",
"end",
"end",
"end"
]
| Opens a list of folders.
@param [Array] folder_paths Array of Strings of folder names to expand, possibly from the #get_open_folders method. | [
"Opens",
"a",
"list",
"of",
"folders",
"."
]
| 245e22864c9d7c7c4e6f92562447caa5d6a705a9 | https://github.com/Beagle123/visualruby/blob/245e22864c9d7c7c4e6f92562447caa5d6a705a9/lib/treeview/FileTreeView.rb#L94-L102 | train |
Beagle123/visualruby | lib/treeview/FileTreeView.rb | VR.FileTreeView.add_file | def add_file(filename, parent = @root_iter)
my_path = File.dirname(filename)
model.each do |model, path, iter|
return if iter[id(:path)] == filename # duplicate
parent = iter if iter[id(:path)] == my_path
end
fn = filename.gsub("\\", "/")
parent[id(:empty)] = false unless parent.nil?
child = add_row(parent)
child[:pix] = @icons.get_icon(File.directory?(fn) ? "x.folder" : fn) if @icons
child[:file_name] = File.basename(fn)
child[:path] = fn
if File.directory?(fn)
child[:sort_on] = "0" + child[:file_name]
child[:empty] = true
add_row(child) # dummy record so expander appears
else
child[id(:sort_on)] = "1" + child[id(:file_name)]
end
return child
end | ruby | def add_file(filename, parent = @root_iter)
my_path = File.dirname(filename)
model.each do |model, path, iter|
return if iter[id(:path)] == filename # duplicate
parent = iter if iter[id(:path)] == my_path
end
fn = filename.gsub("\\", "/")
parent[id(:empty)] = false unless parent.nil?
child = add_row(parent)
child[:pix] = @icons.get_icon(File.directory?(fn) ? "x.folder" : fn) if @icons
child[:file_name] = File.basename(fn)
child[:path] = fn
if File.directory?(fn)
child[:sort_on] = "0" + child[:file_name]
child[:empty] = true
add_row(child) # dummy record so expander appears
else
child[id(:sort_on)] = "1" + child[id(:file_name)]
end
return child
end | [
"def",
"add_file",
"(",
"filename",
",",
"parent",
"=",
"@root_iter",
")",
"my_path",
"=",
"File",
".",
"dirname",
"(",
"filename",
")",
"model",
".",
"each",
"do",
"|",
"model",
",",
"path",
",",
"iter",
"|",
"return",
"if",
"iter",
"[",
"id",
"(",
":path",
")",
"]",
"==",
"filename",
"parent",
"=",
"iter",
"if",
"iter",
"[",
"id",
"(",
":path",
")",
"]",
"==",
"my_path",
"end",
"fn",
"=",
"filename",
".",
"gsub",
"(",
"\"\\\\\"",
",",
"\"/\"",
")",
"parent",
"[",
"id",
"(",
":empty",
")",
"]",
"=",
"false",
"unless",
"parent",
".",
"nil?",
"child",
"=",
"add_row",
"(",
"parent",
")",
"child",
"[",
":pix",
"]",
"=",
"@icons",
".",
"get_icon",
"(",
"File",
".",
"directory?",
"(",
"fn",
")",
"?",
"\"x.folder\"",
":",
"fn",
")",
"if",
"@icons",
"child",
"[",
":file_name",
"]",
"=",
"File",
".",
"basename",
"(",
"fn",
")",
"child",
"[",
":path",
"]",
"=",
"fn",
"if",
"File",
".",
"directory?",
"(",
"fn",
")",
"child",
"[",
":sort_on",
"]",
"=",
"\"0\"",
"+",
"child",
"[",
":file_name",
"]",
"child",
"[",
":empty",
"]",
"=",
"true",
"add_row",
"(",
"child",
")",
"else",
"child",
"[",
"id",
"(",
":sort_on",
")",
"]",
"=",
"\"1\"",
"+",
"child",
"[",
"id",
"(",
":file_name",
")",
"]",
"end",
"return",
"child",
"end"
]
| Adds a file to the tree under a given parent iter.
@param [String] filename Full path to file to add. | [
"Adds",
"a",
"file",
"to",
"the",
"tree",
"under",
"a",
"given",
"parent",
"iter",
"."
]
| 245e22864c9d7c7c4e6f92562447caa5d6a705a9 | https://github.com/Beagle123/visualruby/blob/245e22864c9d7c7c4e6f92562447caa5d6a705a9/lib/treeview/FileTreeView.rb#L106-L126 | train |
muffinista/namey | lib/namey/generator.rb | Namey.Generator.generate | def generate(params = {})
params = {
:type => random_gender,
:frequency => :common,
:with_surname => true
}.merge(params)
if ! ( params[:min_freq] || params[:max_freq] )
params[:min_freq], params[:max_freq] = frequency_values(params[:frequency])
else
#
# do some basic data validation in case someone is being a knucklehead
#
params[:min_freq] = params[:min_freq].to_i
params[:max_freq] = params[:max_freq].to_i
params[:max_freq] = params[:min_freq] + 1 if params[:max_freq] <= params[:min_freq]
# max_freq needs to be at least 4 to get any results back,
# because the most common male name only rates 3.3
# JAMES 3.318 3.318 1
params[:max_freq] = 4 if params[:max_freq] < 4
end
name = get_name(params[:type], params[:min_freq], params[:max_freq])
# add surname if needed
if params[:type] != :surname && params[:with_surname] == true
name = "#{name} #{get_name(:surname, params[:min_freq], params[:max_freq])}"
end
name
end | ruby | def generate(params = {})
params = {
:type => random_gender,
:frequency => :common,
:with_surname => true
}.merge(params)
if ! ( params[:min_freq] || params[:max_freq] )
params[:min_freq], params[:max_freq] = frequency_values(params[:frequency])
else
#
# do some basic data validation in case someone is being a knucklehead
#
params[:min_freq] = params[:min_freq].to_i
params[:max_freq] = params[:max_freq].to_i
params[:max_freq] = params[:min_freq] + 1 if params[:max_freq] <= params[:min_freq]
# max_freq needs to be at least 4 to get any results back,
# because the most common male name only rates 3.3
# JAMES 3.318 3.318 1
params[:max_freq] = 4 if params[:max_freq] < 4
end
name = get_name(params[:type], params[:min_freq], params[:max_freq])
# add surname if needed
if params[:type] != :surname && params[:with_surname] == true
name = "#{name} #{get_name(:surname, params[:min_freq], params[:max_freq])}"
end
name
end | [
"def",
"generate",
"(",
"params",
"=",
"{",
"}",
")",
"params",
"=",
"{",
":type",
"=>",
"random_gender",
",",
":frequency",
"=>",
":common",
",",
":with_surname",
"=>",
"true",
"}",
".",
"merge",
"(",
"params",
")",
"if",
"!",
"(",
"params",
"[",
":min_freq",
"]",
"||",
"params",
"[",
":max_freq",
"]",
")",
"params",
"[",
":min_freq",
"]",
",",
"params",
"[",
":max_freq",
"]",
"=",
"frequency_values",
"(",
"params",
"[",
":frequency",
"]",
")",
"else",
"params",
"[",
":min_freq",
"]",
"=",
"params",
"[",
":min_freq",
"]",
".",
"to_i",
"params",
"[",
":max_freq",
"]",
"=",
"params",
"[",
":max_freq",
"]",
".",
"to_i",
"params",
"[",
":max_freq",
"]",
"=",
"params",
"[",
":min_freq",
"]",
"+",
"1",
"if",
"params",
"[",
":max_freq",
"]",
"<=",
"params",
"[",
":min_freq",
"]",
"params",
"[",
":max_freq",
"]",
"=",
"4",
"if",
"params",
"[",
":max_freq",
"]",
"<",
"4",
"end",
"name",
"=",
"get_name",
"(",
"params",
"[",
":type",
"]",
",",
"params",
"[",
":min_freq",
"]",
",",
"params",
"[",
":max_freq",
"]",
")",
"if",
"params",
"[",
":type",
"]",
"!=",
":surname",
"&&",
"params",
"[",
":with_surname",
"]",
"==",
"true",
"name",
"=",
"\"#{name} #{get_name(:surname, params[:min_freq], params[:max_freq])}\"",
"end",
"name",
"end"
]
| generate a name using the supplied parameter hash
* +params+ - A hash of parameters
==== Params
* +:type+ - :male, :female, :surname
* +:frequency+ - :common, :rare, :all
* +:min_freq+ - raw frequency values to specify a precise range
* +:max_freq+ - raw frequency values to specify a precise range | [
"generate",
"a",
"name",
"using",
"the",
"supplied",
"parameter",
"hash"
]
| 10e62cba0bab2603f95ad454f752c1dc93685461 | https://github.com/muffinista/namey/blob/10e62cba0bab2603f95ad454f752c1dc93685461/lib/namey/generator.rb#L67-L101 | train |
muffinista/namey | lib/namey/generator.rb | Namey.Generator.random_sort | def random_sort(set)
set.order do
# this is a bit of a hack obviously, but it checks the sort of
# data engine being used to figure out how to randomly sort
if set.class.name !~ /mysql/i
random.function
else
rand.function
end
end
end | ruby | def random_sort(set)
set.order do
# this is a bit of a hack obviously, but it checks the sort of
# data engine being used to figure out how to randomly sort
if set.class.name !~ /mysql/i
random.function
else
rand.function
end
end
end | [
"def",
"random_sort",
"(",
"set",
")",
"set",
".",
"order",
"do",
"if",
"set",
".",
"class",
".",
"name",
"!~",
"/",
"/i",
"random",
".",
"function",
"else",
"rand",
".",
"function",
"end",
"end",
"end"
]
| randomly sort a result set according to the data adapter class | [
"randomly",
"sort",
"a",
"result",
"set",
"according",
"to",
"the",
"data",
"adapter",
"class"
]
| 10e62cba0bab2603f95ad454f752c1dc93685461 | https://github.com/muffinista/namey/blob/10e62cba0bab2603f95ad454f752c1dc93685461/lib/namey/generator.rb#L141-L151 | train |
muffinista/namey | lib/namey/generator.rb | Namey.Generator.get_name | def get_name(src, min_freq = 0, max_freq = 100)
tmp = random_sort(@db[src.to_sym].filter{(freq >= min_freq) & (freq <= max_freq)})
tmp.count > 0 ? tmp.first[:name] : nil
end | ruby | def get_name(src, min_freq = 0, max_freq = 100)
tmp = random_sort(@db[src.to_sym].filter{(freq >= min_freq) & (freq <= max_freq)})
tmp.count > 0 ? tmp.first[:name] : nil
end | [
"def",
"get_name",
"(",
"src",
",",
"min_freq",
"=",
"0",
",",
"max_freq",
"=",
"100",
")",
"tmp",
"=",
"random_sort",
"(",
"@db",
"[",
"src",
".",
"to_sym",
"]",
".",
"filter",
"{",
"(",
"freq",
">=",
"min_freq",
")",
"&",
"(",
"freq",
"<=",
"max_freq",
")",
"}",
")",
"tmp",
".",
"count",
">",
"0",
"?",
"tmp",
".",
"first",
"[",
":name",
"]",
":",
"nil",
"end"
]
| query the db for a name | [
"query",
"the",
"db",
"for",
"a",
"name"
]
| 10e62cba0bab2603f95ad454f752c1dc93685461 | https://github.com/muffinista/namey/blob/10e62cba0bab2603f95ad454f752c1dc93685461/lib/namey/generator.rb#L156-L159 | train |
schmich/kappa | lib/kappa/video.rb | Twitch::V2.Videos.top | def top(options = {}, &block)
params = {}
if options[:game]
params[:game] = options[:game]
end
period = options[:period] || :week
if ![:week, :month, :all].include?(period)
raise ArgumentError, 'period'
end
params[:period] = period.to_s
return @query.connection.accumulate(
:path => 'videos/top',
:params => params,
:json => 'videos',
:create => -> hash { Video.new(hash, @query) },
:limit => options[:limit],
:offset => options[:offset],
&block
)
end | ruby | def top(options = {}, &block)
params = {}
if options[:game]
params[:game] = options[:game]
end
period = options[:period] || :week
if ![:week, :month, :all].include?(period)
raise ArgumentError, 'period'
end
params[:period] = period.to_s
return @query.connection.accumulate(
:path => 'videos/top',
:params => params,
:json => 'videos',
:create => -> hash { Video.new(hash, @query) },
:limit => options[:limit],
:offset => options[:offset],
&block
)
end | [
"def",
"top",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"params",
"=",
"{",
"}",
"if",
"options",
"[",
":game",
"]",
"params",
"[",
":game",
"]",
"=",
"options",
"[",
":game",
"]",
"end",
"period",
"=",
"options",
"[",
":period",
"]",
"||",
":week",
"if",
"!",
"[",
":week",
",",
":month",
",",
":all",
"]",
".",
"include?",
"(",
"period",
")",
"raise",
"ArgumentError",
",",
"'period'",
"end",
"params",
"[",
":period",
"]",
"=",
"period",
".",
"to_s",
"return",
"@query",
".",
"connection",
".",
"accumulate",
"(",
":path",
"=>",
"'videos/top'",
",",
":params",
"=>",
"params",
",",
":json",
"=>",
"'videos'",
",",
":create",
"=>",
"->",
"hash",
"{",
"Video",
".",
"new",
"(",
"hash",
",",
"@query",
")",
"}",
",",
":limit",
"=>",
"options",
"[",
":limit",
"]",
",",
":offset",
"=>",
"options",
"[",
":offset",
"]",
",",
"&",
"block",
")",
"end"
]
| Get the list of most popular videos based on view count.
@note The number of videos returned is potentially very large, so it's recommended that you specify a `:limit`.
@example
Twitch.videos.top
@example
Twitch.videos.top(:period => :month, :game => 'Super Meat Boy')
@example
Twitch.videos.top(:period => :all, :limit => 10)
@example
Twitch.videos.top(:period => :all) do |video|
next if video.view_count < 10000
puts video.url
end
@param options [Hash] Filter criteria.
@option options [Symbol] :period (:week) Return videos only in this time period. Valid values are `:week`, `:month`, `:all`.
@option options [String] :game (nil) Return videos only for this game.
@option options [Fixnum] :limit (nil) Limit on the number of results returned.
@option options [Fixnum] :offset (0) Offset into the result set to begin enumeration.
@yield Optional. If a block is given, each top video is yielded.
@yieldparam [Video] video Current video.
@see https://github.com/justintv/Twitch-API/blob/master/v2_resources/videos.md#get-videostop GET /videos/top
@raise [ArgumentError] If `:period` is not one of `:week`, `:month`, or `:all`.
@return [Array<Video>] Top videos, if no block is given.
@return [nil] If a block is given. | [
"Get",
"the",
"list",
"of",
"most",
"popular",
"videos",
"based",
"on",
"view",
"count",
"."
]
| 09b2a8374257d7088292060bda8131f4b96b7867 | https://github.com/schmich/kappa/blob/09b2a8374257d7088292060bda8131f4b96b7867/lib/kappa/video.rb#L154-L177 | train |
schmich/kappa | lib/kappa/video.rb | Twitch::V2.Videos.for_channel | def for_channel(channel, options = {})
if channel.respond_to?(:name)
channel_name = channel.name
else
channel_name = channel.to_s
end
params = {}
type = options[:type] || :highlights
if !type.nil?
if ![:broadcasts, :highlights].include?(type)
raise ArgumentError, 'type'
end
params[:broadcasts] = (type == :broadcasts)
end
name = CGI.escape(channel_name)
return @query.connection.accumulate(
:path => "channels/#{name}/videos",
:params => params,
:json => 'videos',
:create => -> hash { Video.new(hash, @query) },
:limit => options[:limit],
:offset => options[:offset]
)
end | ruby | def for_channel(channel, options = {})
if channel.respond_to?(:name)
channel_name = channel.name
else
channel_name = channel.to_s
end
params = {}
type = options[:type] || :highlights
if !type.nil?
if ![:broadcasts, :highlights].include?(type)
raise ArgumentError, 'type'
end
params[:broadcasts] = (type == :broadcasts)
end
name = CGI.escape(channel_name)
return @query.connection.accumulate(
:path => "channels/#{name}/videos",
:params => params,
:json => 'videos',
:create => -> hash { Video.new(hash, @query) },
:limit => options[:limit],
:offset => options[:offset]
)
end | [
"def",
"for_channel",
"(",
"channel",
",",
"options",
"=",
"{",
"}",
")",
"if",
"channel",
".",
"respond_to?",
"(",
":name",
")",
"channel_name",
"=",
"channel",
".",
"name",
"else",
"channel_name",
"=",
"channel",
".",
"to_s",
"end",
"params",
"=",
"{",
"}",
"type",
"=",
"options",
"[",
":type",
"]",
"||",
":highlights",
"if",
"!",
"type",
".",
"nil?",
"if",
"!",
"[",
":broadcasts",
",",
":highlights",
"]",
".",
"include?",
"(",
"type",
")",
"raise",
"ArgumentError",
",",
"'type'",
"end",
"params",
"[",
":broadcasts",
"]",
"=",
"(",
"type",
"==",
":broadcasts",
")",
"end",
"name",
"=",
"CGI",
".",
"escape",
"(",
"channel_name",
")",
"return",
"@query",
".",
"connection",
".",
"accumulate",
"(",
":path",
"=>",
"\"channels/#{name}/videos\"",
",",
":params",
"=>",
"params",
",",
":json",
"=>",
"'videos'",
",",
":create",
"=>",
"->",
"hash",
"{",
"Video",
".",
"new",
"(",
"hash",
",",
"@query",
")",
"}",
",",
":limit",
"=>",
"options",
"[",
":limit",
"]",
",",
":offset",
"=>",
"options",
"[",
":offset",
"]",
")",
"end"
]
| Get the videos for a channel, most recently created first.
@example
v = Twitch.videos.for_channel('dreamhacktv')
@example
v = Twitch.videos.for_channel('dreamhacktv', :type => :highlights, :limit => 10)
@example
Twitch.videos.for_channel('dreamhacktv') do |video|
next if video.view_count < 10000
puts video.url
end
@param options [Hash] Filter criteria.
@option options [Symbol] :type (:highlights) The type of videos to return. Valid values are `:broadcasts`, `:highlights`.
@option options [Fixnum] :limit (nil) Limit on the number of results returned.
@option options [Fixnum] :offset (0) Offset into the result set to begin enumeration.
@yield Optional. If a block is given, each video is yielded.
@yieldparam [Video] video Current video.
@see Channel#videos Channel#videos
@see https://github.com/justintv/Twitch-API/blob/master/v2_resources/videos.md#get-channelschannelvideos GET /channels/:channel/videos
@raise [ArgumentError] If `:type` is not one of `:broadcasts` or `:highlights`.
@return [Array<Video>] Videos for the channel, if no block is given.
@return [nil] If a block is given. | [
"Get",
"the",
"videos",
"for",
"a",
"channel",
"most",
"recently",
"created",
"first",
"."
]
| 09b2a8374257d7088292060bda8131f4b96b7867 | https://github.com/schmich/kappa/blob/09b2a8374257d7088292060bda8131f4b96b7867/lib/kappa/video.rb#L200-L227 | train |
schmich/kappa | lib/kappa/user.rb | Twitch::V2.User.following | def following(options = {}, &block)
name = CGI.escape(@name)
return @query.connection.accumulate(
:path => "users/#{name}/follows/channels",
:json => 'follows',
:sub_json => 'channel',
:create => -> hash { Channel.new(hash, @query) },
:limit => options[:limit],
:offset => options[:offset],
&block
)
end | ruby | def following(options = {}, &block)
name = CGI.escape(@name)
return @query.connection.accumulate(
:path => "users/#{name}/follows/channels",
:json => 'follows',
:sub_json => 'channel',
:create => -> hash { Channel.new(hash, @query) },
:limit => options[:limit],
:offset => options[:offset],
&block
)
end | [
"def",
"following",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"name",
"=",
"CGI",
".",
"escape",
"(",
"@name",
")",
"return",
"@query",
".",
"connection",
".",
"accumulate",
"(",
":path",
"=>",
"\"users/#{name}/follows/channels\"",
",",
":json",
"=>",
"'follows'",
",",
":sub_json",
"=>",
"'channel'",
",",
":create",
"=>",
"->",
"hash",
"{",
"Channel",
".",
"new",
"(",
"hash",
",",
"@query",
")",
"}",
",",
":limit",
"=>",
"options",
"[",
":limit",
"]",
",",
":offset",
"=>",
"options",
"[",
":offset",
"]",
",",
"&",
"block",
")",
"end"
]
| Get the channels the user is currently following.
@example
user.following(:limit => 10)
@example
user.following do |channel|
next if channel.game_name !~ /starcraft/i
puts channel.display_name
end
@param options [Hash] Filter criteria.
@option options [Fixnum] :limit (nil) Limit on the number of results returned.
@option options [Fixnum] :offset (0) Offset into the result set to begin enumeration.
@yield Optional. If a block is given, each followed channel is yielded.
@yieldparam [Channel] channel Current channel.
@see #following?
@see https://github.com/justintv/Twitch-API/blob/master/v2_resources/follows.md#get-usersuserfollowschannels GET /users/:user/follows/channels
@return [Array<Channel>] Channels the user is currently following, if no block is given.
@return [nil] If a block is given. | [
"Get",
"the",
"channels",
"the",
"user",
"is",
"currently",
"following",
"."
]
| 09b2a8374257d7088292060bda8131f4b96b7867 | https://github.com/schmich/kappa/blob/09b2a8374257d7088292060bda8131f4b96b7867/lib/kappa/user.rb#L73-L84 | train |
domcleal/rspec-puppet-augeas | lib/rspec-puppet-augeas/fixtures.rb | RSpec::Puppet::Augeas.Fixtures.load_fixtures | def load_fixtures(resource, file)
if block_given?
Dir.mktmpdir("rspec-puppet-augeas") do |dir|
prepare_fixtures(dir, resource, file)
yield dir
end
else
dir = Dir.mktmpdir("rspec-puppet-augeas")
prepare_fixtures(dir, resource, file)
dir
end
end | ruby | def load_fixtures(resource, file)
if block_given?
Dir.mktmpdir("rspec-puppet-augeas") do |dir|
prepare_fixtures(dir, resource, file)
yield dir
end
else
dir = Dir.mktmpdir("rspec-puppet-augeas")
prepare_fixtures(dir, resource, file)
dir
end
end | [
"def",
"load_fixtures",
"(",
"resource",
",",
"file",
")",
"if",
"block_given?",
"Dir",
".",
"mktmpdir",
"(",
"\"rspec-puppet-augeas\"",
")",
"do",
"|",
"dir",
"|",
"prepare_fixtures",
"(",
"dir",
",",
"resource",
",",
"file",
")",
"yield",
"dir",
"end",
"else",
"dir",
"=",
"Dir",
".",
"mktmpdir",
"(",
"\"rspec-puppet-augeas\"",
")",
"prepare_fixtures",
"(",
"dir",
",",
"resource",
",",
"file",
")",
"dir",
"end",
"end"
]
| Copies test fixtures to a temporary directory
If file is nil, copies the entire augeas_fixtures directory
If file is a hash, it copies the "value" from augeas_fixtures
to each "key" path | [
"Copies",
"test",
"fixtures",
"to",
"a",
"temporary",
"directory",
"If",
"file",
"is",
"nil",
"copies",
"the",
"entire",
"augeas_fixtures",
"directory",
"If",
"file",
"is",
"a",
"hash",
"it",
"copies",
"the",
"value",
"from",
"augeas_fixtures",
"to",
"each",
"key",
"path"
]
| 7110a831a23e1b7716c525eef256454083cc9f72 | https://github.com/domcleal/rspec-puppet-augeas/blob/7110a831a23e1b7716c525eef256454083cc9f72/lib/rspec-puppet-augeas/fixtures.rb#L11-L22 | train |
domcleal/rspec-puppet-augeas | lib/rspec-puppet-augeas/fixtures.rb | RSpec::Puppet::Augeas.Fixtures.apply | def apply(resource, logs)
logs.clear
Puppet::Util::Log.newdestination(Puppet::Test::LogCollector.new(logs))
Puppet::Util::Log.level = 'debug'
confdir = Dir.mktmpdir
oldconfdir = Puppet[:confdir]
Puppet[:confdir] = confdir
[:require, :before, :notify, :subscribe].each { |p| resource.delete p }
catalog = Puppet::Resource::Catalog.new
catalog.add_resource resource
catalog = catalog.to_ral if resource.is_a? Puppet::Resource
txn = catalog.apply
Puppet::Util::Log.close_all
txn
ensure
if confdir
Puppet[:confdir] = oldconfdir
FileUtils.rm_rf(confdir)
end
end | ruby | def apply(resource, logs)
logs.clear
Puppet::Util::Log.newdestination(Puppet::Test::LogCollector.new(logs))
Puppet::Util::Log.level = 'debug'
confdir = Dir.mktmpdir
oldconfdir = Puppet[:confdir]
Puppet[:confdir] = confdir
[:require, :before, :notify, :subscribe].each { |p| resource.delete p }
catalog = Puppet::Resource::Catalog.new
catalog.add_resource resource
catalog = catalog.to_ral if resource.is_a? Puppet::Resource
txn = catalog.apply
Puppet::Util::Log.close_all
txn
ensure
if confdir
Puppet[:confdir] = oldconfdir
FileUtils.rm_rf(confdir)
end
end | [
"def",
"apply",
"(",
"resource",
",",
"logs",
")",
"logs",
".",
"clear",
"Puppet",
"::",
"Util",
"::",
"Log",
".",
"newdestination",
"(",
"Puppet",
"::",
"Test",
"::",
"LogCollector",
".",
"new",
"(",
"logs",
")",
")",
"Puppet",
"::",
"Util",
"::",
"Log",
".",
"level",
"=",
"'debug'",
"confdir",
"=",
"Dir",
".",
"mktmpdir",
"oldconfdir",
"=",
"Puppet",
"[",
":confdir",
"]",
"Puppet",
"[",
":confdir",
"]",
"=",
"confdir",
"[",
":require",
",",
":before",
",",
":notify",
",",
":subscribe",
"]",
".",
"each",
"{",
"|",
"p",
"|",
"resource",
".",
"delete",
"p",
"}",
"catalog",
"=",
"Puppet",
"::",
"Resource",
"::",
"Catalog",
".",
"new",
"catalog",
".",
"add_resource",
"resource",
"catalog",
"=",
"catalog",
".",
"to_ral",
"if",
"resource",
".",
"is_a?",
"Puppet",
"::",
"Resource",
"txn",
"=",
"catalog",
".",
"apply",
"Puppet",
"::",
"Util",
"::",
"Log",
".",
"close_all",
"txn",
"ensure",
"if",
"confdir",
"Puppet",
"[",
":confdir",
"]",
"=",
"oldconfdir",
"FileUtils",
".",
"rm_rf",
"(",
"confdir",
")",
"end",
"end"
]
| Runs a particular resource via a catalog and stores logs in the caller's
supplied array | [
"Runs",
"a",
"particular",
"resource",
"via",
"a",
"catalog",
"and",
"stores",
"logs",
"in",
"the",
"caller",
"s",
"supplied",
"array"
]
| 7110a831a23e1b7716c525eef256454083cc9f72 | https://github.com/domcleal/rspec-puppet-augeas/blob/7110a831a23e1b7716c525eef256454083cc9f72/lib/rspec-puppet-augeas/fixtures.rb#L38-L60 | train |
schmich/kappa | lib/kappa/channel.rb | Twitch::V2.Channel.followers | def followers(options = {}, &block)
name = CGI.escape(@name)
return @query.connection.accumulate(
:path => "channels/#{name}/follows",
:json => 'follows',
:sub_json => 'user',
:create => -> hash { User.new(hash, @query) },
:limit => options[:limit],
:offset => options[:offset],
&block
)
end | ruby | def followers(options = {}, &block)
name = CGI.escape(@name)
return @query.connection.accumulate(
:path => "channels/#{name}/follows",
:json => 'follows',
:sub_json => 'user',
:create => -> hash { User.new(hash, @query) },
:limit => options[:limit],
:offset => options[:offset],
&block
)
end | [
"def",
"followers",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"name",
"=",
"CGI",
".",
"escape",
"(",
"@name",
")",
"return",
"@query",
".",
"connection",
".",
"accumulate",
"(",
":path",
"=>",
"\"channels/#{name}/follows\"",
",",
":json",
"=>",
"'follows'",
",",
":sub_json",
"=>",
"'user'",
",",
":create",
"=>",
"->",
"hash",
"{",
"User",
".",
"new",
"(",
"hash",
",",
"@query",
")",
"}",
",",
":limit",
"=>",
"options",
"[",
":limit",
"]",
",",
":offset",
"=>",
"options",
"[",
":offset",
"]",
",",
"&",
"block",
")",
"end"
]
| Get the users following this channel.
@note The number of followers is potentially very large, so it's recommended that you specify a `:limit`.
@example
channel.followers(:limit => 20)
@example
channel.followers do |follower|
puts follower.display_name
end
@param options [Hash] Filter criteria.
@option options [Fixnum] :limit (nil) Limit on the number of results returned.
@option options [Fixnum] :offset (0) Offset into the result set to begin enumeration.
@yield Optional. If a block is given, each follower is yielded.
@yieldparam [User] follower Current follower.
@see User
@see https://github.com/justintv/Twitch-API/blob/master/v2_resources/channels.md#get-channelschannelfollows GET /channels/:channel/follows
@return [Array<User>] Users following this channel, if no block is given.
@return [nil] If a block is given. | [
"Get",
"the",
"users",
"following",
"this",
"channel",
"."
]
| 09b2a8374257d7088292060bda8131f4b96b7867 | https://github.com/schmich/kappa/blob/09b2a8374257d7088292060bda8131f4b96b7867/lib/kappa/channel.rb#L85-L96 | train |
schmich/kappa | lib/kappa/game.rb | Twitch::V2.Games.find | def find(options)
raise ArgumentError, 'options' if options.nil?
raise ArgumentError, 'name' if options[:name].nil?
params = {
:query => options[:name],
:type => 'suggest'
}
if options[:live]
params.merge!(:live => true)
end
return @query.connection.accumulate(
:path => 'search/games',
:params => params,
:json => 'games',
:create => GameSuggestion,
:limit => options[:limit]
)
end | ruby | def find(options)
raise ArgumentError, 'options' if options.nil?
raise ArgumentError, 'name' if options[:name].nil?
params = {
:query => options[:name],
:type => 'suggest'
}
if options[:live]
params.merge!(:live => true)
end
return @query.connection.accumulate(
:path => 'search/games',
:params => params,
:json => 'games',
:create => GameSuggestion,
:limit => options[:limit]
)
end | [
"def",
"find",
"(",
"options",
")",
"raise",
"ArgumentError",
",",
"'options'",
"if",
"options",
".",
"nil?",
"raise",
"ArgumentError",
",",
"'name'",
"if",
"options",
"[",
":name",
"]",
".",
"nil?",
"params",
"=",
"{",
":query",
"=>",
"options",
"[",
":name",
"]",
",",
":type",
"=>",
"'suggest'",
"}",
"if",
"options",
"[",
":live",
"]",
"params",
".",
"merge!",
"(",
":live",
"=>",
"true",
")",
"end",
"return",
"@query",
".",
"connection",
".",
"accumulate",
"(",
":path",
"=>",
"'search/games'",
",",
":params",
"=>",
"params",
",",
":json",
"=>",
"'games'",
",",
":create",
"=>",
"GameSuggestion",
",",
":limit",
"=>",
"options",
"[",
":limit",
"]",
")",
"end"
]
| Get a list of games with names similar to the specified name.
@example
Twitch.games.find(:name => 'diablo')
@example
Twitch.games.find(:name => 'starcraft', :live => true)
@example
Twitch.games.find(:name => 'starcraft') do |suggestion|
next if suggestion.name =~ /heart of the swarm/i
puts suggestion.name
end
@param options [Hash] Search criteria.
@option options [String] :name Game name search term. This can be a partial name, e.g. `"league"`.
@option options [Boolean] :live (false) If `true`, only returns games that are currently live on at least one channel.
@option options [Fixnum] :limit (nil) Limit on the number of results returned.
@yield Optional. If a block is given, each game suggestion is yielded.
@yieldparam [GameSuggestion] suggestion Current game suggestion.
@see GameSuggestion GameSuggestion
@see https://github.com/justintv/Twitch-API/blob/master/v2_resources/search.md#get-searchgames GET /search/games
@raise [ArgumentError] If `:name` is not specified.
@return [Array<GameSuggestion>] Games matching the criteria, if no block is given.
@return [nil] If a block is given. | [
"Get",
"a",
"list",
"of",
"games",
"with",
"names",
"similar",
"to",
"the",
"specified",
"name",
"."
]
| 09b2a8374257d7088292060bda8131f4b96b7867 | https://github.com/schmich/kappa/blob/09b2a8374257d7088292060bda8131f4b96b7867/lib/kappa/game.rb#L194-L214 | train |
domcleal/rspec-puppet-augeas | lib/rspec-puppet-augeas/resource.rb | RSpec::Puppet::Augeas.Resource.idempotent | def idempotent
@logs_idempotent = []
root = load_fixtures(resource, {"." => "#{@root}/."})
oldroot = resource[:root]
resource[:root] = root
@txn_idempotent = apply(resource, @logs_idempotent)
FileUtils.rm_r root
resource[:root] = oldroot
@txn_idempotent
end | ruby | def idempotent
@logs_idempotent = []
root = load_fixtures(resource, {"." => "#{@root}/."})
oldroot = resource[:root]
resource[:root] = root
@txn_idempotent = apply(resource, @logs_idempotent)
FileUtils.rm_r root
resource[:root] = oldroot
@txn_idempotent
end | [
"def",
"idempotent",
"@logs_idempotent",
"=",
"[",
"]",
"root",
"=",
"load_fixtures",
"(",
"resource",
",",
"{",
"\".\"",
"=>",
"\"#{@root}/.\"",
"}",
")",
"oldroot",
"=",
"resource",
"[",
":root",
"]",
"resource",
"[",
":root",
"]",
"=",
"root",
"@txn_idempotent",
"=",
"apply",
"(",
"resource",
",",
"@logs_idempotent",
")",
"FileUtils",
".",
"rm_r",
"root",
"resource",
"[",
":root",
"]",
"=",
"oldroot",
"@txn_idempotent",
"end"
]
| Run the resource a second time, against the output dir from the first
@return [Puppet::Transaction] repeated transaction | [
"Run",
"the",
"resource",
"a",
"second",
"time",
"against",
"the",
"output",
"dir",
"from",
"the",
"first"
]
| 7110a831a23e1b7716c525eef256454083cc9f72 | https://github.com/domcleal/rspec-puppet-augeas/blob/7110a831a23e1b7716c525eef256454083cc9f72/lib/rspec-puppet-augeas/resource.rb#L27-L38 | train |
schmich/kappa | lib/kappa/stream.rb | Twitch::V2.Streams.all | def all(options = {}, &block)
return @query.connection.accumulate(
:path => 'streams',
:json => 'streams',
:create => -> hash { Stream.new(hash, @query) },
:limit => options[:limit],
:offset => options[:offset],
&block
)
end | ruby | def all(options = {}, &block)
return @query.connection.accumulate(
:path => 'streams',
:json => 'streams',
:create => -> hash { Stream.new(hash, @query) },
:limit => options[:limit],
:offset => options[:offset],
&block
)
end | [
"def",
"all",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"return",
"@query",
".",
"connection",
".",
"accumulate",
"(",
":path",
"=>",
"'streams'",
",",
":json",
"=>",
"'streams'",
",",
":create",
"=>",
"->",
"hash",
"{",
"Stream",
".",
"new",
"(",
"hash",
",",
"@query",
")",
"}",
",",
":limit",
"=>",
"options",
"[",
":limit",
"]",
",",
":offset",
"=>",
"options",
"[",
":offset",
"]",
",",
"&",
"block",
")",
"end"
]
| Get all currently live streams sorted by descending viewer count.
@example
Twitch.streams.all
@example
Twitch.streams.all(:offset => 100, :limit => 10)
@example
Twitch.streams.all do |stream|
next if stream.viewer_count < 1000
puts stream.url
end
@param options [Hash] Limit criteria.
@option options [Fixnum] :limit (nil) Limit on the number of results returned.
@option options [Fixnum] :offset (0) Offset into the result set to begin enumeration.
@yield Optional. If a block is given, each stream is yielded.
@yieldparam [Stream] stream Current stream.
@see #get
@see https://github.com/justintv/Twitch-API/blob/master/v2_resources/streams.md#get-streams GET /streams
@return [Array<Stream>] Currently live streams, sorted by descending viewer count, if no block is given.
@return [nil] If a block is given. | [
"Get",
"all",
"currently",
"live",
"streams",
"sorted",
"by",
"descending",
"viewer",
"count",
"."
]
| 09b2a8374257d7088292060bda8131f4b96b7867 | https://github.com/schmich/kappa/blob/09b2a8374257d7088292060bda8131f4b96b7867/lib/kappa/stream.rb#L146-L155 | train |
schmich/kappa | lib/kappa/stream.rb | Twitch::V2.Streams.find | def find(options, &block)
check = options.dup
check.delete(:limit)
check.delete(:offset)
raise ArgumentError, 'options' if check.empty?
params = {}
channels = options[:channel]
if channels
if !channels.respond_to?(:map)
raise ArgumentError, ':channel'
end
params[:channel] = channels.map { |channel|
if channel.respond_to?(:name)
channel.name
else
channel.to_s
end
}.join(',')
end
game = options[:game]
if game
if game.respond_to?(:name)
params[:game] = game.name
else
params[:game] = game.to_s
end
end
if options[:hls]
params[:hls] = true
end
if options[:embeddable]
params[:embeddable] = true
end
return @query.connection.accumulate(
:path => 'streams',
:params => params,
:json => 'streams',
:create => -> hash { Stream.new(hash, @query) },
:limit => options[:limit],
:offset => options[:offset],
&block
)
end | ruby | def find(options, &block)
check = options.dup
check.delete(:limit)
check.delete(:offset)
raise ArgumentError, 'options' if check.empty?
params = {}
channels = options[:channel]
if channels
if !channels.respond_to?(:map)
raise ArgumentError, ':channel'
end
params[:channel] = channels.map { |channel|
if channel.respond_to?(:name)
channel.name
else
channel.to_s
end
}.join(',')
end
game = options[:game]
if game
if game.respond_to?(:name)
params[:game] = game.name
else
params[:game] = game.to_s
end
end
if options[:hls]
params[:hls] = true
end
if options[:embeddable]
params[:embeddable] = true
end
return @query.connection.accumulate(
:path => 'streams',
:params => params,
:json => 'streams',
:create => -> hash { Stream.new(hash, @query) },
:limit => options[:limit],
:offset => options[:offset],
&block
)
end | [
"def",
"find",
"(",
"options",
",",
"&",
"block",
")",
"check",
"=",
"options",
".",
"dup",
"check",
".",
"delete",
"(",
":limit",
")",
"check",
".",
"delete",
"(",
":offset",
")",
"raise",
"ArgumentError",
",",
"'options'",
"if",
"check",
".",
"empty?",
"params",
"=",
"{",
"}",
"channels",
"=",
"options",
"[",
":channel",
"]",
"if",
"channels",
"if",
"!",
"channels",
".",
"respond_to?",
"(",
":map",
")",
"raise",
"ArgumentError",
",",
"':channel'",
"end",
"params",
"[",
":channel",
"]",
"=",
"channels",
".",
"map",
"{",
"|",
"channel",
"|",
"if",
"channel",
".",
"respond_to?",
"(",
":name",
")",
"channel",
".",
"name",
"else",
"channel",
".",
"to_s",
"end",
"}",
".",
"join",
"(",
"','",
")",
"end",
"game",
"=",
"options",
"[",
":game",
"]",
"if",
"game",
"if",
"game",
".",
"respond_to?",
"(",
":name",
")",
"params",
"[",
":game",
"]",
"=",
"game",
".",
"name",
"else",
"params",
"[",
":game",
"]",
"=",
"game",
".",
"to_s",
"end",
"end",
"if",
"options",
"[",
":hls",
"]",
"params",
"[",
":hls",
"]",
"=",
"true",
"end",
"if",
"options",
"[",
":embeddable",
"]",
"params",
"[",
":embeddable",
"]",
"=",
"true",
"end",
"return",
"@query",
".",
"connection",
".",
"accumulate",
"(",
":path",
"=>",
"'streams'",
",",
":params",
"=>",
"params",
",",
":json",
"=>",
"'streams'",
",",
":create",
"=>",
"->",
"hash",
"{",
"Stream",
".",
"new",
"(",
"hash",
",",
"@query",
")",
"}",
",",
":limit",
"=>",
"options",
"[",
":limit",
"]",
",",
":offset",
"=>",
"options",
"[",
":offset",
"]",
",",
"&",
"block",
")",
"end"
]
| Get streams for a specific game, for a set of channels, or by other criteria, sorted by descending viewer count.
@example
Twitch.streams.find(:game => 'League of Legends', :limit => 50)
@example
Twitch.streams.find(:channel => ['fgtvlive', 'incontroltv', 'destiny'])
@example
Twitch.streams.find(:game => 'Diablo III', :channel => ['nl_kripp', 'protech'])
@example
Twitch.streams.find(:game => 'League of Legends') do |stream|
next if stream.viewer_count < 1000
puts stream.url
end
@param options [Hash] Search criteria.
@option options [String, Game, #name] :game Only return streams currently streaming the specified game.
@option options [Array<String, Channel, #name>] :channel Only return streams for these channels.
If a channel is not currently streaming, it is omitted. You must specify an array of channels
or channel names. If you want to find the stream for a single channel, see {Streams#get}.
@option options [Boolean] :embeddable (nil) If `true`, limit the streams to those that can be embedded. If `false` or `nil`, do not limit.
@option options [Boolean] :hls (nil) If `true`, limit the streams to those using HLS (HTTP Live Streaming). If `false` or `nil`, do not limit.
@option options [Fixnum] :limit (nil) Limit on the number of results returned.
@option options [Fixnum] :offset (0) Offset into the result set to begin enumeration.
@yield Optional. If a block is given, each stream found is yielded.
@yieldparam [Stream] stream Current stream.
@see #get
@see https://github.com/justintv/Twitch-API/blob/master/v2_resources/streams.md#get-streams GET /streams
@raise [ArgumentError] If `options` does not specify a search criteria (`:game`, `:channel`, `:embeddable`, or `:hls`).
@raise [ArgumentError] If `:channel` is not an array.
@return [Array<Stream>] Streams matching the specified criteria, sorted by
descending viewer count, if no block is given.
@return [nil] If a block is given. | [
"Get",
"streams",
"for",
"a",
"specific",
"game",
"for",
"a",
"set",
"of",
"channels",
"or",
"by",
"other",
"criteria",
"sorted",
"by",
"descending",
"viewer",
"count",
"."
]
| 09b2a8374257d7088292060bda8131f4b96b7867 | https://github.com/schmich/kappa/blob/09b2a8374257d7088292060bda8131f4b96b7867/lib/kappa/stream.rb#L187-L236 | train |
voydz/souyuz | lib/souyuz/runner.rb | Souyuz.Runner.apk_file | def apk_file
build_path = Souyuz.project.options[:output_path]
assembly_name = Souyuz.project.options[:assembly_name]
Souyuz.cache[:build_apk_path] = "#{build_path}/#{assembly_name}.apk"
"#{build_path}/#{assembly_name}.apk"
end | ruby | def apk_file
build_path = Souyuz.project.options[:output_path]
assembly_name = Souyuz.project.options[:assembly_name]
Souyuz.cache[:build_apk_path] = "#{build_path}/#{assembly_name}.apk"
"#{build_path}/#{assembly_name}.apk"
end | [
"def",
"apk_file",
"build_path",
"=",
"Souyuz",
".",
"project",
".",
"options",
"[",
":output_path",
"]",
"assembly_name",
"=",
"Souyuz",
".",
"project",
".",
"options",
"[",
":assembly_name",
"]",
"Souyuz",
".",
"cache",
"[",
":build_apk_path",
"]",
"=",
"\"#{build_path}/#{assembly_name}.apk\"",
"\"#{build_path}/#{assembly_name}.apk\"",
"end"
]
| android build stuff to follow.. | [
"android",
"build",
"stuff",
"to",
"follow",
".."
]
| ee6e13d21197bea5d58bb272988e06027dd358cb | https://github.com/voydz/souyuz/blob/ee6e13d21197bea5d58bb272988e06027dd358cb/lib/souyuz/runner.rb#L38-L45 | train |
voydz/souyuz | lib/souyuz/runner.rb | Souyuz.Runner.package_path | def package_path
build_path = Souyuz.project.options[:output_path]
assembly_name = Souyuz.project.options[:assembly_name]
# in the upcomming switch we determin the output path of iOS ipa files
# those change in the Xamarin.iOS Cycle 9 release
# see https://developer.xamarin.com/releases/ios/xamarin.ios_10/xamarin.ios_10.4/
if File.exist? "#{build_path}/#{assembly_name}.ipa"
# after Xamarin.iOS Cycle 9
package_path = build_path
else
# before Xamarin.iOS Cycle 9
package_path = Dir.glob("#{build_path}/#{assembly_name} *").sort.last
end
package_path
end | ruby | def package_path
build_path = Souyuz.project.options[:output_path]
assembly_name = Souyuz.project.options[:assembly_name]
# in the upcomming switch we determin the output path of iOS ipa files
# those change in the Xamarin.iOS Cycle 9 release
# see https://developer.xamarin.com/releases/ios/xamarin.ios_10/xamarin.ios_10.4/
if File.exist? "#{build_path}/#{assembly_name}.ipa"
# after Xamarin.iOS Cycle 9
package_path = build_path
else
# before Xamarin.iOS Cycle 9
package_path = Dir.glob("#{build_path}/#{assembly_name} *").sort.last
end
package_path
end | [
"def",
"package_path",
"build_path",
"=",
"Souyuz",
".",
"project",
".",
"options",
"[",
":output_path",
"]",
"assembly_name",
"=",
"Souyuz",
".",
"project",
".",
"options",
"[",
":assembly_name",
"]",
"if",
"File",
".",
"exist?",
"\"#{build_path}/#{assembly_name}.ipa\"",
"package_path",
"=",
"build_path",
"else",
"package_path",
"=",
"Dir",
".",
"glob",
"(",
"\"#{build_path}/#{assembly_name} *\"",
")",
".",
"sort",
".",
"last",
"end",
"package_path",
"end"
]
| ios build stuff to follow.. | [
"ios",
"build",
"stuff",
"to",
"follow",
".."
]
| ee6e13d21197bea5d58bb272988e06027dd358cb | https://github.com/voydz/souyuz/blob/ee6e13d21197bea5d58bb272988e06027dd358cb/lib/souyuz/runner.rb#L65-L81 | train |
iande/onstomp | lib/onstomp/interfaces/uri_configurable.rb | OnStomp::Interfaces::UriConfigurable.ClassMethods.attr_configurable_single | def attr_configurable_single *args, &block
trans = attr_configurable_wrap lambda { |v| v.is_a?(Array) ? v.first : v }, block
attr_configurable(*args, &trans)
end | ruby | def attr_configurable_single *args, &block
trans = attr_configurable_wrap lambda { |v| v.is_a?(Array) ? v.first : v }, block
attr_configurable(*args, &trans)
end | [
"def",
"attr_configurable_single",
"*",
"args",
",",
"&",
"block",
"trans",
"=",
"attr_configurable_wrap",
"lambda",
"{",
"|",
"v",
"|",
"v",
".",
"is_a?",
"(",
"Array",
")",
"?",
"v",
".",
"first",
":",
"v",
"}",
",",
"block",
"attr_configurable",
"(",
"*",
"args",
",",
"&",
"trans",
")",
"end"
]
| Creates a group readable and writeable attributes that can be set
by a URI query parameter sharing the same name, a property of a URI or
a default value. The value of this attribute will be transformed by
invoking the given block, if one has been provided. If the attributes
created by this method are assigned an `Array`, only the first element
will be used as their value. | [
"Creates",
"a",
"group",
"readable",
"and",
"writeable",
"attributes",
"that",
"can",
"be",
"set",
"by",
"a",
"URI",
"query",
"parameter",
"sharing",
"the",
"same",
"name",
"a",
"property",
"of",
"a",
"URI",
"or",
"a",
"default",
"value",
".",
"The",
"value",
"of",
"this",
"attribute",
"will",
"be",
"transformed",
"by",
"invoking",
"the",
"given",
"block",
"if",
"one",
"has",
"been",
"provided",
".",
"If",
"the",
"attributes",
"created",
"by",
"this",
"method",
"are",
"assigned",
"an",
"Array",
"only",
"the",
"first",
"element",
"will",
"be",
"used",
"as",
"their",
"value",
"."
]
| 0a3e00871167b37dc424a682003d3182ba3e5c42 | https://github.com/iande/onstomp/blob/0a3e00871167b37dc424a682003d3182ba3e5c42/lib/onstomp/interfaces/uri_configurable.rb#L46-L49 | train |
iande/onstomp | lib/onstomp/interfaces/uri_configurable.rb | OnStomp::Interfaces::UriConfigurable.ClassMethods.attr_configurable_arr | def attr_configurable_arr *args, &block
trans = attr_configurable_wrap lambda { |v| Array(v) }, block
attr_configurable(*args, &trans)
end | ruby | def attr_configurable_arr *args, &block
trans = attr_configurable_wrap lambda { |v| Array(v) }, block
attr_configurable(*args, &trans)
end | [
"def",
"attr_configurable_arr",
"*",
"args",
",",
"&",
"block",
"trans",
"=",
"attr_configurable_wrap",
"lambda",
"{",
"|",
"v",
"|",
"Array",
"(",
"v",
")",
"}",
",",
"block",
"attr_configurable",
"(",
"*",
"args",
",",
"&",
"trans",
")",
"end"
]
| Creates a group readable and writeable attributes that can be set
by a URI query parameter sharing the same name, a property of a URI or
a default value. The value of this attribute will be transformed by
invoking the given block, if one has been provided. If the attributes
created by this method are assigned a value that is not an `Array`, the
value will be wrapped in an array. | [
"Creates",
"a",
"group",
"readable",
"and",
"writeable",
"attributes",
"that",
"can",
"be",
"set",
"by",
"a",
"URI",
"query",
"parameter",
"sharing",
"the",
"same",
"name",
"a",
"property",
"of",
"a",
"URI",
"or",
"a",
"default",
"value",
".",
"The",
"value",
"of",
"this",
"attribute",
"will",
"be",
"transformed",
"by",
"invoking",
"the",
"given",
"block",
"if",
"one",
"has",
"been",
"provided",
".",
"If",
"the",
"attributes",
"created",
"by",
"this",
"method",
"are",
"assigned",
"a",
"value",
"that",
"is",
"not",
"an",
"Array",
"the",
"value",
"will",
"be",
"wrapped",
"in",
"an",
"array",
"."
]
| 0a3e00871167b37dc424a682003d3182ba3e5c42 | https://github.com/iande/onstomp/blob/0a3e00871167b37dc424a682003d3182ba3e5c42/lib/onstomp/interfaces/uri_configurable.rb#L68-L71 | train |
iande/onstomp | lib/onstomp/interfaces/uri_configurable.rb | OnStomp::Interfaces::UriConfigurable.ClassMethods.attr_configurable_int | def attr_configurable_int *args, &block
trans = attr_configurable_wrap lambda { |v| v.to_i }, block
attr_configurable_single(*args, &trans)
end | ruby | def attr_configurable_int *args, &block
trans = attr_configurable_wrap lambda { |v| v.to_i }, block
attr_configurable_single(*args, &trans)
end | [
"def",
"attr_configurable_int",
"*",
"args",
",",
"&",
"block",
"trans",
"=",
"attr_configurable_wrap",
"lambda",
"{",
"|",
"v",
"|",
"v",
".",
"to_i",
"}",
",",
"block",
"attr_configurable_single",
"(",
"*",
"args",
",",
"&",
"trans",
")",
"end"
]
| Creates readable and writeable attributes that are automatically
converted into integers. | [
"Creates",
"readable",
"and",
"writeable",
"attributes",
"that",
"are",
"automatically",
"converted",
"into",
"integers",
"."
]
| 0a3e00871167b37dc424a682003d3182ba3e5c42 | https://github.com/iande/onstomp/blob/0a3e00871167b37dc424a682003d3182ba3e5c42/lib/onstomp/interfaces/uri_configurable.rb#L75-L78 | train |
TinderBox/soapforce | lib/soapforce/sobject.rb | Soapforce.SObject.method_missing | def method_missing(method, *args, &block)
# Check string keys first, original and downcase
string_method = method.to_s
if raw_hash.key?(string_method)
return self[string_method]
elsif raw_hash.key?(string_method.downcase)
return self[string_method.downcase]
end
if string_method =~ /[A-Z+]/
string_method = string_method.snakecase
end
index = string_method.downcase.to_sym
# Check symbol key and return local hash entry.
return self[index] if raw_hash.has_key?(index)
# Then delegate to hash object.
if raw_hash.respond_to?(method)
return raw_hash.send(method, *args)
end
# Finally return nil.
nil
end | ruby | def method_missing(method, *args, &block)
# Check string keys first, original and downcase
string_method = method.to_s
if raw_hash.key?(string_method)
return self[string_method]
elsif raw_hash.key?(string_method.downcase)
return self[string_method.downcase]
end
if string_method =~ /[A-Z+]/
string_method = string_method.snakecase
end
index = string_method.downcase.to_sym
# Check symbol key and return local hash entry.
return self[index] if raw_hash.has_key?(index)
# Then delegate to hash object.
if raw_hash.respond_to?(method)
return raw_hash.send(method, *args)
end
# Finally return nil.
nil
end | [
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
",",
"&",
"block",
")",
"string_method",
"=",
"method",
".",
"to_s",
"if",
"raw_hash",
".",
"key?",
"(",
"string_method",
")",
"return",
"self",
"[",
"string_method",
"]",
"elsif",
"raw_hash",
".",
"key?",
"(",
"string_method",
".",
"downcase",
")",
"return",
"self",
"[",
"string_method",
".",
"downcase",
"]",
"end",
"if",
"string_method",
"=~",
"/",
"/",
"string_method",
"=",
"string_method",
".",
"snakecase",
"end",
"index",
"=",
"string_method",
".",
"downcase",
".",
"to_sym",
"return",
"self",
"[",
"index",
"]",
"if",
"raw_hash",
".",
"has_key?",
"(",
"index",
")",
"if",
"raw_hash",
".",
"respond_to?",
"(",
"method",
")",
"return",
"raw_hash",
".",
"send",
"(",
"method",
",",
"*",
"args",
")",
"end",
"nil",
"end"
]
| Allows method-like access to the hash using camelcase field names. | [
"Allows",
"method",
"-",
"like",
"access",
"to",
"the",
"hash",
"using",
"camelcase",
"field",
"names",
"."
]
| 4b07b9fe3f74ce024c9b0298adcc8f4147802e4e | https://github.com/TinderBox/soapforce/blob/4b07b9fe3f74ce024c9b0298adcc8f4147802e4e/lib/soapforce/sobject.rb#L44-L67 | train |
benedikt/layer-ruby | lib/layer/user.rb | Layer.User.blocks | def blocks
RelationProxy.new(self, Block, [Operations::Create, Operations::List, Operations::Delete]) do
def from_response(response, client)
response['url'] ||= "#{base.url}#{resource_type.url}/#{response['user_id']}"
super
end
def create(attributes, client = self.client)
response = client.post(url, attributes)
from_response({ 'user_id' => attributes['user_id'] }, client)
end
end
end | ruby | def blocks
RelationProxy.new(self, Block, [Operations::Create, Operations::List, Operations::Delete]) do
def from_response(response, client)
response['url'] ||= "#{base.url}#{resource_type.url}/#{response['user_id']}"
super
end
def create(attributes, client = self.client)
response = client.post(url, attributes)
from_response({ 'user_id' => attributes['user_id'] }, client)
end
end
end | [
"def",
"blocks",
"RelationProxy",
".",
"new",
"(",
"self",
",",
"Block",
",",
"[",
"Operations",
"::",
"Create",
",",
"Operations",
"::",
"List",
",",
"Operations",
"::",
"Delete",
"]",
")",
"do",
"def",
"from_response",
"(",
"response",
",",
"client",
")",
"response",
"[",
"'url'",
"]",
"||=",
"\"#{base.url}#{resource_type.url}/#{response['user_id']}\"",
"super",
"end",
"def",
"create",
"(",
"attributes",
",",
"client",
"=",
"self",
".",
"client",
")",
"response",
"=",
"client",
".",
"post",
"(",
"url",
",",
"attributes",
")",
"from_response",
"(",
"{",
"'user_id'",
"=>",
"attributes",
"[",
"'user_id'",
"]",
"}",
",",
"client",
")",
"end",
"end",
"end"
]
| Returns the users blocked by this user
@return [Layer::RelationProxy] the users the user blocks
@!macro platform-api | [
"Returns",
"the",
"users",
"blocked",
"by",
"this",
"user"
]
| 3eafc708f71961b98de86d01080ee5970e8482ef | https://github.com/benedikt/layer-ruby/blob/3eafc708f71961b98de86d01080ee5970e8482ef/lib/layer/user.rb#L12-L24 | train |
benedikt/layer-ruby | lib/layer/user.rb | Layer.User.identity | def identity
SingletonRelationProxy.new(self, Layer::Identity) do
def from_response(response, client)
response['url'] ||= "#{base.url}#{resource_type.url}"
super
end
def create(attributes, client = self.client)
client.post(url, attributes)
fetch
end
def delete(client = self.client)
client.delete(url)
end
end
end | ruby | def identity
SingletonRelationProxy.new(self, Layer::Identity) do
def from_response(response, client)
response['url'] ||= "#{base.url}#{resource_type.url}"
super
end
def create(attributes, client = self.client)
client.post(url, attributes)
fetch
end
def delete(client = self.client)
client.delete(url)
end
end
end | [
"def",
"identity",
"SingletonRelationProxy",
".",
"new",
"(",
"self",
",",
"Layer",
"::",
"Identity",
")",
"do",
"def",
"from_response",
"(",
"response",
",",
"client",
")",
"response",
"[",
"'url'",
"]",
"||=",
"\"#{base.url}#{resource_type.url}\"",
"super",
"end",
"def",
"create",
"(",
"attributes",
",",
"client",
"=",
"self",
".",
"client",
")",
"client",
".",
"post",
"(",
"url",
",",
"attributes",
")",
"fetch",
"end",
"def",
"delete",
"(",
"client",
"=",
"self",
".",
"client",
")",
"client",
".",
"delete",
"(",
"url",
")",
"end",
"end",
"end"
]
| Returns the identity object for this user
@return [Layer::RelationProxy] identity object
@!macro platform-api | [
"Returns",
"the",
"identity",
"object",
"for",
"this",
"user"
]
| 3eafc708f71961b98de86d01080ee5970e8482ef | https://github.com/benedikt/layer-ruby/blob/3eafc708f71961b98de86d01080ee5970e8482ef/lib/layer/user.rb#L30-L46 | train |
benedikt/layer-ruby | lib/layer/conversation.rb | Layer.Conversation.messages | def messages
RelationProxy.new(self, Message, [Operations::Create, Operations::Paginate, Operations::Find, Operations::Delete, Operations::Destroy])
end | ruby | def messages
RelationProxy.new(self, Message, [Operations::Create, Operations::Paginate, Operations::Find, Operations::Delete, Operations::Destroy])
end | [
"def",
"messages",
"RelationProxy",
".",
"new",
"(",
"self",
",",
"Message",
",",
"[",
"Operations",
"::",
"Create",
",",
"Operations",
"::",
"Paginate",
",",
"Operations",
"::",
"Find",
",",
"Operations",
"::",
"Delete",
",",
"Operations",
"::",
"Destroy",
"]",
")",
"end"
]
| Returns the conversations messages
@return [Layer::RelationProxy] the conversation's messages
@!macro various-apis | [
"Returns",
"the",
"conversations",
"messages"
]
| 3eafc708f71961b98de86d01080ee5970e8482ef | https://github.com/benedikt/layer-ruby/blob/3eafc708f71961b98de86d01080ee5970e8482ef/lib/layer/conversation.rb#L58-L60 | train |
benedikt/layer-ruby | lib/layer/conversation.rb | Layer.Conversation.contents | def contents
RelationProxy.new(self, Content, [Operations::Create, Operations::Find]) do
def create(mime_type, file, client = self.client)
response = client.post(url, {}, {
'Upload-Content-Type' => mime_type,
'Upload-Content-Length' => file.size
})
attributes = response.merge('size' => file.size, 'mime_type' => mime_type)
Content.from_response(attributes, client).tap do |content|
content.upload(file)
end
end
end
end | ruby | def contents
RelationProxy.new(self, Content, [Operations::Create, Operations::Find]) do
def create(mime_type, file, client = self.client)
response = client.post(url, {}, {
'Upload-Content-Type' => mime_type,
'Upload-Content-Length' => file.size
})
attributes = response.merge('size' => file.size, 'mime_type' => mime_type)
Content.from_response(attributes, client).tap do |content|
content.upload(file)
end
end
end
end | [
"def",
"contents",
"RelationProxy",
".",
"new",
"(",
"self",
",",
"Content",
",",
"[",
"Operations",
"::",
"Create",
",",
"Operations",
"::",
"Find",
"]",
")",
"do",
"def",
"create",
"(",
"mime_type",
",",
"file",
",",
"client",
"=",
"self",
".",
"client",
")",
"response",
"=",
"client",
".",
"post",
"(",
"url",
",",
"{",
"}",
",",
"{",
"'Upload-Content-Type'",
"=>",
"mime_type",
",",
"'Upload-Content-Length'",
"=>",
"file",
".",
"size",
"}",
")",
"attributes",
"=",
"response",
".",
"merge",
"(",
"'size'",
"=>",
"file",
".",
"size",
",",
"'mime_type'",
"=>",
"mime_type",
")",
"Content",
".",
"from_response",
"(",
"attributes",
",",
"client",
")",
".",
"tap",
"do",
"|",
"content",
"|",
"content",
".",
"upload",
"(",
"file",
")",
"end",
"end",
"end",
"end"
]
| Allows creating and finding of the conversation's rich content
@return [Layer::RelationProxy] the conversation's rich content
@!macro platform-api | [
"Allows",
"creating",
"and",
"finding",
"of",
"the",
"conversation",
"s",
"rich",
"content"
]
| 3eafc708f71961b98de86d01080ee5970e8482ef | https://github.com/benedikt/layer-ruby/blob/3eafc708f71961b98de86d01080ee5970e8482ef/lib/layer/conversation.rb#L66-L81 | train |
benedikt/layer-ruby | lib/layer/conversation.rb | Layer.Conversation.delete | def delete(options = {})
options = { mode: :my_devices }.merge(options)
client.delete(url, {}, { params: options })
end | ruby | def delete(options = {})
options = { mode: :my_devices }.merge(options)
client.delete(url, {}, { params: options })
end | [
"def",
"delete",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"mode",
":",
":my_devices",
"}",
".",
"merge",
"(",
"options",
")",
"client",
".",
"delete",
"(",
"url",
",",
"{",
"}",
",",
"{",
"params",
":",
"options",
"}",
")",
"end"
]
| Deletes the conversation, removing it from the user's devices by default
@param options [Hash] the options for the delete request (REST API only: `leave: true/false`, `mode: all_participants/my_devices`)
@raise [Layer::Exceptions::Exception] a subclass of Layer::Exceptions::Exception describing the error | [
"Deletes",
"the",
"conversation",
"removing",
"it",
"from",
"the",
"user",
"s",
"devices",
"by",
"default"
]
| 3eafc708f71961b98de86d01080ee5970e8482ef | https://github.com/benedikt/layer-ruby/blob/3eafc708f71961b98de86d01080ee5970e8482ef/lib/layer/conversation.rb#L124-L127 | train |
nesquena/dante | lib/dante/runner.rb | Dante.Runner.execute | def execute(opts={}, &block)
parse_options
self.options.merge!(opts)
@verify_options_hook.call(self.options) if @verify_options_hook
if options.include?(:kill)
self.stop
else # create process
self.stop if options.include?(:restart)
# If a username, uid, groupname, or gid is passed,
# drop privileges accordingly.
if options[:group]
gid = options[:group].is_a?(Integer) ? options[:group] : Etc.getgrnam(options[:group]).gid
Process::GID.change_privilege(gid)
end
if options[:user]
uid = options[:user].is_a?(Integer) ? options[:user] : Etc.getpwnam(options[:user]).uid
Process::UID.change_privilege(uid)
end
@startup_command = block if block_given?
options[:daemonize] ? daemonize : start
end
end | ruby | def execute(opts={}, &block)
parse_options
self.options.merge!(opts)
@verify_options_hook.call(self.options) if @verify_options_hook
if options.include?(:kill)
self.stop
else # create process
self.stop if options.include?(:restart)
# If a username, uid, groupname, or gid is passed,
# drop privileges accordingly.
if options[:group]
gid = options[:group].is_a?(Integer) ? options[:group] : Etc.getgrnam(options[:group]).gid
Process::GID.change_privilege(gid)
end
if options[:user]
uid = options[:user].is_a?(Integer) ? options[:user] : Etc.getpwnam(options[:user]).uid
Process::UID.change_privilege(uid)
end
@startup_command = block if block_given?
options[:daemonize] ? daemonize : start
end
end | [
"def",
"execute",
"(",
"opts",
"=",
"{",
"}",
",",
"&",
"block",
")",
"parse_options",
"self",
".",
"options",
".",
"merge!",
"(",
"opts",
")",
"@verify_options_hook",
".",
"call",
"(",
"self",
".",
"options",
")",
"if",
"@verify_options_hook",
"if",
"options",
".",
"include?",
"(",
":kill",
")",
"self",
".",
"stop",
"else",
"self",
".",
"stop",
"if",
"options",
".",
"include?",
"(",
":restart",
")",
"if",
"options",
"[",
":group",
"]",
"gid",
"=",
"options",
"[",
":group",
"]",
".",
"is_a?",
"(",
"Integer",
")",
"?",
"options",
"[",
":group",
"]",
":",
"Etc",
".",
"getgrnam",
"(",
"options",
"[",
":group",
"]",
")",
".",
"gid",
"Process",
"::",
"GID",
".",
"change_privilege",
"(",
"gid",
")",
"end",
"if",
"options",
"[",
":user",
"]",
"uid",
"=",
"options",
"[",
":user",
"]",
".",
"is_a?",
"(",
"Integer",
")",
"?",
"options",
"[",
":user",
"]",
":",
"Etc",
".",
"getpwnam",
"(",
"options",
"[",
":user",
"]",
")",
".",
"uid",
"Process",
"::",
"UID",
".",
"change_privilege",
"(",
"uid",
")",
"end",
"@startup_command",
"=",
"block",
"if",
"block_given?",
"options",
"[",
":daemonize",
"]",
"?",
"daemonize",
":",
"start",
"end",
"end"
]
| Executes the runner based on options
@runner.execute
@runner.execute { ... } | [
"Executes",
"the",
"runner",
"based",
"on",
"options"
]
| 2a5be903fded5bbd44e57b5192763d9107e9d740 | https://github.com/nesquena/dante/blob/2a5be903fded5bbd44e57b5192763d9107e9d740/lib/dante/runner.rb#L49-L76 | train |
nesquena/dante | lib/dante/runner.rb | Dante.Runner.stop | def stop(kill_arg=nil)
if self.daemon_running?
kill_pid(kill_arg || options[:kill])
if until_true(MAX_START_TRIES) { self.daemon_stopped? }
FileUtils.rm options[:pid_path] # Only kill if we stopped the daemon
log "Daemonized process killed after term."
else
log "Failed to kill daemonized process"
if options[:force]
kill_pid(kill_arg || options[:kill], 'KILL')
if until_true(MAX_START_TRIES) { self.daemon_stopped? }
FileUtils.rm options[:pid_path] # Only kill if we stopped the daemon
log "Daemonized process killed after kill."
end
end
end
else # not running
log "No #{@name} processes are running"
false
end
end | ruby | def stop(kill_arg=nil)
if self.daemon_running?
kill_pid(kill_arg || options[:kill])
if until_true(MAX_START_TRIES) { self.daemon_stopped? }
FileUtils.rm options[:pid_path] # Only kill if we stopped the daemon
log "Daemonized process killed after term."
else
log "Failed to kill daemonized process"
if options[:force]
kill_pid(kill_arg || options[:kill], 'KILL')
if until_true(MAX_START_TRIES) { self.daemon_stopped? }
FileUtils.rm options[:pid_path] # Only kill if we stopped the daemon
log "Daemonized process killed after kill."
end
end
end
else # not running
log "No #{@name} processes are running"
false
end
end | [
"def",
"stop",
"(",
"kill_arg",
"=",
"nil",
")",
"if",
"self",
".",
"daemon_running?",
"kill_pid",
"(",
"kill_arg",
"||",
"options",
"[",
":kill",
"]",
")",
"if",
"until_true",
"(",
"MAX_START_TRIES",
")",
"{",
"self",
".",
"daemon_stopped?",
"}",
"FileUtils",
".",
"rm",
"options",
"[",
":pid_path",
"]",
"log",
"\"Daemonized process killed after term.\"",
"else",
"log",
"\"Failed to kill daemonized process\"",
"if",
"options",
"[",
":force",
"]",
"kill_pid",
"(",
"kill_arg",
"||",
"options",
"[",
":kill",
"]",
",",
"'KILL'",
")",
"if",
"until_true",
"(",
"MAX_START_TRIES",
")",
"{",
"self",
".",
"daemon_stopped?",
"}",
"FileUtils",
".",
"rm",
"options",
"[",
":pid_path",
"]",
"log",
"\"Daemonized process killed after kill.\"",
"end",
"end",
"end",
"else",
"log",
"\"No #{@name} processes are running\"",
"false",
"end",
"end"
]
| Stops a daemonized process | [
"Stops",
"a",
"daemonized",
"process"
]
| 2a5be903fded5bbd44e57b5192763d9107e9d740 | https://github.com/nesquena/dante/blob/2a5be903fded5bbd44e57b5192763d9107e9d740/lib/dante/runner.rb#L127-L149 | train |
nesquena/dante | lib/dante/runner.rb | Dante.Runner.daemon_running? | def daemon_running?
return false unless File.exist?(options[:pid_path])
Process.kill 0, File.read(options[:pid_path]).to_i
true
rescue Errno::ESRCH
false
end | ruby | def daemon_running?
return false unless File.exist?(options[:pid_path])
Process.kill 0, File.read(options[:pid_path]).to_i
true
rescue Errno::ESRCH
false
end | [
"def",
"daemon_running?",
"return",
"false",
"unless",
"File",
".",
"exist?",
"(",
"options",
"[",
":pid_path",
"]",
")",
"Process",
".",
"kill",
"0",
",",
"File",
".",
"read",
"(",
"options",
"[",
":pid_path",
"]",
")",
".",
"to_i",
"true",
"rescue",
"Errno",
"::",
"ESRCH",
"false",
"end"
]
| Returns running for the daemonized process
self.daemon_running? | [
"Returns",
"running",
"for",
"the",
"daemonized",
"process",
"self",
".",
"daemon_running?"
]
| 2a5be903fded5bbd44e57b5192763d9107e9d740 | https://github.com/nesquena/dante/blob/2a5be903fded5bbd44e57b5192763d9107e9d740/lib/dante/runner.rb#L172-L178 | train |
grackorg/grack | lib/grack/git_adapter.rb | Grack.GitAdapter.handle_pack | def handle_pack(pack_type, io_in, io_out, opts = {})
args = %w{--stateless-rpc}
if opts.fetch(:advertise_refs, false)
io_out.write(advertisement_prefix(pack_type))
args << '--advertise-refs'
end
args << repository_path.to_s
command(pack_type.sub(/^git-/, ''), args, io_in, io_out)
end | ruby | def handle_pack(pack_type, io_in, io_out, opts = {})
args = %w{--stateless-rpc}
if opts.fetch(:advertise_refs, false)
io_out.write(advertisement_prefix(pack_type))
args << '--advertise-refs'
end
args << repository_path.to_s
command(pack_type.sub(/^git-/, ''), args, io_in, io_out)
end | [
"def",
"handle_pack",
"(",
"pack_type",
",",
"io_in",
",",
"io_out",
",",
"opts",
"=",
"{",
"}",
")",
"args",
"=",
"%w{",
"--stateless-rpc",
"}",
"if",
"opts",
".",
"fetch",
"(",
":advertise_refs",
",",
"false",
")",
"io_out",
".",
"write",
"(",
"advertisement_prefix",
"(",
"pack_type",
")",
")",
"args",
"<<",
"'--advertise-refs'",
"end",
"args",
"<<",
"repository_path",
".",
"to_s",
"command",
"(",
"pack_type",
".",
"sub",
"(",
"/",
"/",
",",
"''",
")",
",",
"args",
",",
"io_in",
",",
"io_out",
")",
"end"
]
| Process the pack file exchange protocol.
@param [String] pack_type the type of pack exchange to perform.
@param [#read] io_in a readable, IO-like object providing client input
data.
@param [#write] io_out a writable, IO-like object sending output data to
the client.
@param [Hash] opts options to pass to the Git adapter's #handle_pack
method.
@option opts [Boolean] :advertise_refs (false) | [
"Process",
"the",
"pack",
"file",
"exchange",
"protocol",
"."
]
| 603bc28193923d3cc9c2fd3c47a7176680e58728 | https://github.com/grackorg/grack/blob/603bc28193923d3cc9c2fd3c47a7176680e58728/lib/grack/git_adapter.rb#L50-L58 | train |
grackorg/grack | lib/grack/git_adapter.rb | Grack.GitAdapter.command | def command(cmd, args, io_in, io_out, dir = nil)
cmd = [git_path, cmd] + args
opts = {:err => :close}
opts[:chdir] = dir unless dir.nil?
cmd << opts
IO.popen(cmd, 'r+b') do |pipe|
while ! io_in.nil? && chunk = io_in.read(READ_SIZE) do
pipe.write(chunk)
end
pipe.close_write
while chunk = pipe.read(READ_SIZE) do
io_out.write(chunk) unless io_out.nil?
end
end
end | ruby | def command(cmd, args, io_in, io_out, dir = nil)
cmd = [git_path, cmd] + args
opts = {:err => :close}
opts[:chdir] = dir unless dir.nil?
cmd << opts
IO.popen(cmd, 'r+b') do |pipe|
while ! io_in.nil? && chunk = io_in.read(READ_SIZE) do
pipe.write(chunk)
end
pipe.close_write
while chunk = pipe.read(READ_SIZE) do
io_out.write(chunk) unless io_out.nil?
end
end
end | [
"def",
"command",
"(",
"cmd",
",",
"args",
",",
"io_in",
",",
"io_out",
",",
"dir",
"=",
"nil",
")",
"cmd",
"=",
"[",
"git_path",
",",
"cmd",
"]",
"+",
"args",
"opts",
"=",
"{",
":err",
"=>",
":close",
"}",
"opts",
"[",
":chdir",
"]",
"=",
"dir",
"unless",
"dir",
".",
"nil?",
"cmd",
"<<",
"opts",
"IO",
".",
"popen",
"(",
"cmd",
",",
"'r+b'",
")",
"do",
"|",
"pipe",
"|",
"while",
"!",
"io_in",
".",
"nil?",
"&&",
"chunk",
"=",
"io_in",
".",
"read",
"(",
"READ_SIZE",
")",
"do",
"pipe",
".",
"write",
"(",
"chunk",
")",
"end",
"pipe",
".",
"close_write",
"while",
"chunk",
"=",
"pipe",
".",
"read",
"(",
"READ_SIZE",
")",
"do",
"io_out",
".",
"write",
"(",
"chunk",
")",
"unless",
"io_out",
".",
"nil?",
"end",
"end",
"end"
]
| Runs the Git utilty with the given subcommand.
@param [String] cmd the Git subcommand to invoke.
@param [Array<String>] args additional arguments for the command.
@param [#read, nil] io_in a readable, IO-like source of data to write to
the Git command.
@param [#write, nil] io_out a writable, IO-like sink for output produced
by the Git command.
@param [String, nil] dir a directory to switch to before invoking the Git
command. | [
"Runs",
"the",
"Git",
"utilty",
"with",
"the",
"given",
"subcommand",
"."
]
| 603bc28193923d3cc9c2fd3c47a7176680e58728 | https://github.com/grackorg/grack/blob/603bc28193923d3cc9c2fd3c47a7176680e58728/lib/grack/git_adapter.rb#L130-L144 | train |
grackorg/grack | lib/grack/app.rb | Grack.App.route | def route
# Sanitize the URI:
# * Unescape escaped characters
# * Replace runs of / with a single /
path_info = Rack::Utils.unescape(request.path_info).gsub(%r{/+}, '/')
ROUTES.each do |path_matcher, verb, handler|
path_info.match(path_matcher) do |match|
@repository_uri = match[1]
@request_verb = verb
return method_not_allowed unless verb == request.request_method
return bad_request if bad_uri?(@repository_uri)
git.repository_path = root + @repository_uri
return not_found unless git.exist?
return send(handler, *match[2..-1])
end
end
not_found
end | ruby | def route
# Sanitize the URI:
# * Unescape escaped characters
# * Replace runs of / with a single /
path_info = Rack::Utils.unescape(request.path_info).gsub(%r{/+}, '/')
ROUTES.each do |path_matcher, verb, handler|
path_info.match(path_matcher) do |match|
@repository_uri = match[1]
@request_verb = verb
return method_not_allowed unless verb == request.request_method
return bad_request if bad_uri?(@repository_uri)
git.repository_path = root + @repository_uri
return not_found unless git.exist?
return send(handler, *match[2..-1])
end
end
not_found
end | [
"def",
"route",
"path_info",
"=",
"Rack",
"::",
"Utils",
".",
"unescape",
"(",
"request",
".",
"path_info",
")",
".",
"gsub",
"(",
"%r{",
"}",
",",
"'/'",
")",
"ROUTES",
".",
"each",
"do",
"|",
"path_matcher",
",",
"verb",
",",
"handler",
"|",
"path_info",
".",
"match",
"(",
"path_matcher",
")",
"do",
"|",
"match",
"|",
"@repository_uri",
"=",
"match",
"[",
"1",
"]",
"@request_verb",
"=",
"verb",
"return",
"method_not_allowed",
"unless",
"verb",
"==",
"request",
".",
"request_method",
"return",
"bad_request",
"if",
"bad_uri?",
"(",
"@repository_uri",
")",
"git",
".",
"repository_path",
"=",
"root",
"+",
"@repository_uri",
"return",
"not_found",
"unless",
"git",
".",
"exist?",
"return",
"send",
"(",
"handler",
",",
"*",
"match",
"[",
"2",
"..",
"-",
"1",
"]",
")",
"end",
"end",
"not_found",
"end"
]
| Routes requests to appropriate handlers. Performs request path cleanup
and several sanity checks prior to attempting to handle the request.
@return a Rack response object. | [
"Routes",
"requests",
"to",
"appropriate",
"handlers",
".",
"Performs",
"request",
"path",
"cleanup",
"and",
"several",
"sanity",
"checks",
"prior",
"to",
"attempting",
"to",
"handle",
"the",
"request",
"."
]
| 603bc28193923d3cc9c2fd3c47a7176680e58728 | https://github.com/grackorg/grack/blob/603bc28193923d3cc9c2fd3c47a7176680e58728/lib/grack/app.rb#L153-L174 | train |
grackorg/grack | lib/grack/app.rb | Grack.App.handle_pack | def handle_pack(pack_type)
@pack_type = pack_type
unless request.content_type == "application/x-#{@pack_type}-request" &&
valid_pack_type? && authorized?
return no_access
end
headers = {'Content-Type' => "application/x-#{@pack_type}-result"}
exchange_pack(headers, request_io_in)
end | ruby | def handle_pack(pack_type)
@pack_type = pack_type
unless request.content_type == "application/x-#{@pack_type}-request" &&
valid_pack_type? && authorized?
return no_access
end
headers = {'Content-Type' => "application/x-#{@pack_type}-result"}
exchange_pack(headers, request_io_in)
end | [
"def",
"handle_pack",
"(",
"pack_type",
")",
"@pack_type",
"=",
"pack_type",
"unless",
"request",
".",
"content_type",
"==",
"\"application/x-#{@pack_type}-request\"",
"&&",
"valid_pack_type?",
"&&",
"authorized?",
"return",
"no_access",
"end",
"headers",
"=",
"{",
"'Content-Type'",
"=>",
"\"application/x-#{@pack_type}-result\"",
"}",
"exchange_pack",
"(",
"headers",
",",
"request_io_in",
")",
"end"
]
| Processes pack file exchange requests for both push and pull. Ensures
that the request is allowed and properly formatted.
@param [String] pack_type the type of pack exchange to perform per the
request.
@return a Rack response object. | [
"Processes",
"pack",
"file",
"exchange",
"requests",
"for",
"both",
"push",
"and",
"pull",
".",
"Ensures",
"that",
"the",
"request",
"is",
"allowed",
"and",
"properly",
"formatted",
"."
]
| 603bc28193923d3cc9c2fd3c47a7176680e58728 | https://github.com/grackorg/grack/blob/603bc28193923d3cc9c2fd3c47a7176680e58728/lib/grack/app.rb#L184-L193 | train |
grackorg/grack | lib/grack/app.rb | Grack.App.info_refs | def info_refs
@pack_type = request.params['service']
return no_access unless authorized?
if @pack_type.nil?
git.update_server_info
send_file(
git.file('info/refs'), 'text/plain; charset=utf-8', hdr_nocache
)
elsif valid_pack_type?
headers = hdr_nocache
headers['Content-Type'] = "application/x-#{@pack_type}-advertisement"
exchange_pack(headers, nil, {:advertise_refs => true})
else
not_found
end
end | ruby | def info_refs
@pack_type = request.params['service']
return no_access unless authorized?
if @pack_type.nil?
git.update_server_info
send_file(
git.file('info/refs'), 'text/plain; charset=utf-8', hdr_nocache
)
elsif valid_pack_type?
headers = hdr_nocache
headers['Content-Type'] = "application/x-#{@pack_type}-advertisement"
exchange_pack(headers, nil, {:advertise_refs => true})
else
not_found
end
end | [
"def",
"info_refs",
"@pack_type",
"=",
"request",
".",
"params",
"[",
"'service'",
"]",
"return",
"no_access",
"unless",
"authorized?",
"if",
"@pack_type",
".",
"nil?",
"git",
".",
"update_server_info",
"send_file",
"(",
"git",
".",
"file",
"(",
"'info/refs'",
")",
",",
"'text/plain; charset=utf-8'",
",",
"hdr_nocache",
")",
"elsif",
"valid_pack_type?",
"headers",
"=",
"hdr_nocache",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"\"application/x-#{@pack_type}-advertisement\"",
"exchange_pack",
"(",
"headers",
",",
"nil",
",",
"{",
":advertise_refs",
"=>",
"true",
"}",
")",
"else",
"not_found",
"end",
"end"
]
| Processes requests for the list of refs for the requested repository.
This works for both Smart HTTP clients and basic ones. For basic clients,
the Git adapter is used to update the +info/refs+ file which is then
served to the clients. For Smart HTTP clients, the more efficient pack
file exchange mechanism is used.
@return a Rack response object. | [
"Processes",
"requests",
"for",
"the",
"list",
"of",
"refs",
"for",
"the",
"requested",
"repository",
"."
]
| 603bc28193923d3cc9c2fd3c47a7176680e58728 | https://github.com/grackorg/grack/blob/603bc28193923d3cc9c2fd3c47a7176680e58728/lib/grack/app.rb#L204-L220 | train |
grackorg/grack | lib/grack/app.rb | Grack.App.send_file | def send_file(streamer, content_type, headers = {})
return not_found if streamer.nil?
headers['Content-Type'] = content_type
headers['Last-Modified'] = streamer.mtime.httpdate
[200, headers, streamer]
end | ruby | def send_file(streamer, content_type, headers = {})
return not_found if streamer.nil?
headers['Content-Type'] = content_type
headers['Last-Modified'] = streamer.mtime.httpdate
[200, headers, streamer]
end | [
"def",
"send_file",
"(",
"streamer",
",",
"content_type",
",",
"headers",
"=",
"{",
"}",
")",
"return",
"not_found",
"if",
"streamer",
".",
"nil?",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"content_type",
"headers",
"[",
"'Last-Modified'",
"]",
"=",
"streamer",
".",
"mtime",
".",
"httpdate",
"[",
"200",
",",
"headers",
",",
"streamer",
"]",
"end"
]
| Produces a Rack response that wraps the output from the Git adapter.
A 404 response is produced if _streamer_ is +nil+. Otherwise a 200
response is produced with _streamer_ as the response body.
@param [FileStreamer,IOStreamer] streamer a provider of content for the
response body.
@param [String] content_type the MIME type of the content.
@param [Hash] headers additional headers to include in the response.
@return a Rack response object. | [
"Produces",
"a",
"Rack",
"response",
"that",
"wraps",
"the",
"output",
"from",
"the",
"Git",
"adapter",
"."
]
| 603bc28193923d3cc9c2fd3c47a7176680e58728 | https://github.com/grackorg/grack/blob/603bc28193923d3cc9c2fd3c47a7176680e58728/lib/grack/app.rb#L311-L318 | train |
grackorg/grack | lib/grack/app.rb | Grack.App.exchange_pack | def exchange_pack(headers, io_in, opts = {})
Rack::Response.new([], 200, headers).finish do |response|
git.handle_pack(pack_type, io_in, response, opts)
end
end | ruby | def exchange_pack(headers, io_in, opts = {})
Rack::Response.new([], 200, headers).finish do |response|
git.handle_pack(pack_type, io_in, response, opts)
end
end | [
"def",
"exchange_pack",
"(",
"headers",
",",
"io_in",
",",
"opts",
"=",
"{",
"}",
")",
"Rack",
"::",
"Response",
".",
"new",
"(",
"[",
"]",
",",
"200",
",",
"headers",
")",
".",
"finish",
"do",
"|",
"response",
"|",
"git",
".",
"handle_pack",
"(",
"pack_type",
",",
"io_in",
",",
"response",
",",
"opts",
")",
"end",
"end"
]
| Opens a tunnel for the pack file exchange protocol between the client and
the Git adapter.
@param [Hash] headers headers to provide in the Rack response.
@param [#read] io_in a readable, IO-like object providing client input
data.
@param [Hash] opts options to pass to the Git adapter's #handle_pack
method.
@return a Rack response object. | [
"Opens",
"a",
"tunnel",
"for",
"the",
"pack",
"file",
"exchange",
"protocol",
"between",
"the",
"client",
"and",
"the",
"Git",
"adapter",
"."
]
| 603bc28193923d3cc9c2fd3c47a7176680e58728 | https://github.com/grackorg/grack/blob/603bc28193923d3cc9c2fd3c47a7176680e58728/lib/grack/app.rb#L331-L335 | train |
grackorg/grack | lib/grack/app.rb | Grack.App.bad_uri? | def bad_uri?(path)
invalid_segments = %w{. ..}
path.split('/').any? { |segment| invalid_segments.include?(segment) }
end | ruby | def bad_uri?(path)
invalid_segments = %w{. ..}
path.split('/').any? { |segment| invalid_segments.include?(segment) }
end | [
"def",
"bad_uri?",
"(",
"path",
")",
"invalid_segments",
"=",
"%w{",
".",
"..",
"}",
"path",
".",
"split",
"(",
"'/'",
")",
".",
"any?",
"{",
"|",
"segment",
"|",
"invalid_segments",
".",
"include?",
"(",
"segment",
")",
"}",
"end"
]
| Determines whether or not _path_ is an acceptable URI.
@param [String] path the path part of the request URI.
@return [Boolean] +true+ if the requested path is considered invalid;
otherwise, +false+. | [
"Determines",
"whether",
"or",
"not",
"_path_",
"is",
"an",
"acceptable",
"URI",
"."
]
| 603bc28193923d3cc9c2fd3c47a7176680e58728 | https://github.com/grackorg/grack/blob/603bc28193923d3cc9c2fd3c47a7176680e58728/lib/grack/app.rb#L362-L365 | train |
swcraig/oxford-dictionary | lib/oxford_dictionary/request.rb | OxfordDictionary.Request.search_endpoint_url | def search_endpoint_url(params)
params[:prefix] || params[:prefix] = false
append = ''
if params[:translations]
append = "/translations=#{params[:translations]}"
params.delete(:translations)
end
"#{append}?#{create_query_string(params, '&')}"
end | ruby | def search_endpoint_url(params)
params[:prefix] || params[:prefix] = false
append = ''
if params[:translations]
append = "/translations=#{params[:translations]}"
params.delete(:translations)
end
"#{append}?#{create_query_string(params, '&')}"
end | [
"def",
"search_endpoint_url",
"(",
"params",
")",
"params",
"[",
":prefix",
"]",
"||",
"params",
"[",
":prefix",
"]",
"=",
"false",
"append",
"=",
"''",
"if",
"params",
"[",
":translations",
"]",
"append",
"=",
"\"/translations=#{params[:translations]}\"",
"params",
".",
"delete",
"(",
":translations",
")",
"end",
"\"#{append}?#{create_query_string(params, '&')}\"",
"end"
]
| The search endpoint has a slightly different url structure | [
"The",
"search",
"endpoint",
"has",
"a",
"slightly",
"different",
"url",
"structure"
]
| bcd1d9f8a81781726e846e33e2f36ac71ffa8c18 | https://github.com/swcraig/oxford-dictionary/blob/bcd1d9f8a81781726e846e33e2f36ac71ffa8c18/lib/oxford_dictionary/request.rb#L69-L77 | train |
noboru-i/danger-checkstyle_format | lib/checkstyle_format/plugin.rb | Danger.DangerCheckstyleFormat.report | def report(file, inline_mode = true)
raise "Please specify file name." if file.empty?
raise "No checkstyle file was found at #{file}" unless File.exist? file
errors = parse(File.read(file))
send_comment(errors, inline_mode)
end | ruby | def report(file, inline_mode = true)
raise "Please specify file name." if file.empty?
raise "No checkstyle file was found at #{file}" unless File.exist? file
errors = parse(File.read(file))
send_comment(errors, inline_mode)
end | [
"def",
"report",
"(",
"file",
",",
"inline_mode",
"=",
"true",
")",
"raise",
"\"Please specify file name.\"",
"if",
"file",
".",
"empty?",
"raise",
"\"No checkstyle file was found at #{file}\"",
"unless",
"File",
".",
"exist?",
"file",
"errors",
"=",
"parse",
"(",
"File",
".",
"read",
"(",
"file",
")",
")",
"send_comment",
"(",
"errors",
",",
"inline_mode",
")",
"end"
]
| Report checkstyle warnings
@return [void] | [
"Report",
"checkstyle",
"warnings"
]
| 3b8656c834d7ff9522f5d912fbe223b008914d64 | https://github.com/noboru-i/danger-checkstyle_format/blob/3b8656c834d7ff9522f5d912fbe223b008914d64/lib/checkstyle_format/plugin.rb#L28-L34 | train |
noboru-i/danger-checkstyle_format | lib/checkstyle_format/plugin.rb | Danger.DangerCheckstyleFormat.report_by_text | def report_by_text(text, inline_mode = true)
raise "Please specify xml text." if text.empty?
errors = parse(text)
send_comment(errors, inline_mode)
end | ruby | def report_by_text(text, inline_mode = true)
raise "Please specify xml text." if text.empty?
errors = parse(text)
send_comment(errors, inline_mode)
end | [
"def",
"report_by_text",
"(",
"text",
",",
"inline_mode",
"=",
"true",
")",
"raise",
"\"Please specify xml text.\"",
"if",
"text",
".",
"empty?",
"errors",
"=",
"parse",
"(",
"text",
")",
"send_comment",
"(",
"errors",
",",
"inline_mode",
")",
"end"
]
| Report checkstyle warnings by XML text
@return [void] | [
"Report",
"checkstyle",
"warnings",
"by",
"XML",
"text"
]
| 3b8656c834d7ff9522f5d912fbe223b008914d64 | https://github.com/noboru-i/danger-checkstyle_format/blob/3b8656c834d7ff9522f5d912fbe223b008914d64/lib/checkstyle_format/plugin.rb#L39-L44 | train |
jistr/mobvious | lib/mobvious/manager.rb | Mobvious.Manager.call | def call(env)
request = Rack::Request.new(env)
assign_device_type(request)
status, headers, body = @app.call(env)
response = Rack::Response.new(body, status, headers)
response_callback(request, response)
[status, headers, body]
end | ruby | def call(env)
request = Rack::Request.new(env)
assign_device_type(request)
status, headers, body = @app.call(env)
response = Rack::Response.new(body, status, headers)
response_callback(request, response)
[status, headers, body]
end | [
"def",
"call",
"(",
"env",
")",
"request",
"=",
"Rack",
"::",
"Request",
".",
"new",
"(",
"env",
")",
"assign_device_type",
"(",
"request",
")",
"status",
",",
"headers",
",",
"body",
"=",
"@app",
".",
"call",
"(",
"env",
")",
"response",
"=",
"Rack",
"::",
"Response",
".",
"new",
"(",
"body",
",",
"status",
",",
"headers",
")",
"response_callback",
"(",
"request",
",",
"response",
")",
"[",
"status",
",",
"headers",
",",
"body",
"]",
"end"
]
| Create a new instance of this rack middleware.
@param app Rack application that can be called.
Perform the device type detection and call the inner Rack application.
@param env Rack environment.
@return rack response `[status, headers, body]` | [
"Create",
"a",
"new",
"instance",
"of",
"this",
"rack",
"middleware",
"."
]
| 085190877fe184bc380497915a74207d575f5e77 | https://github.com/jistr/mobvious/blob/085190877fe184bc380497915a74207d575f5e77/lib/mobvious/manager.rb#L21-L31 | train |
aviator/aviator | lib/aviator/core/session.rb | Aviator.Session.authenticate | def authenticate(opts={}, &block)
block ||= lambda do |params|
config[:auth_credentials].each do |key, value|
begin
params[key] = value
rescue NameError => e
raise NameError.new("Unknown param name '#{key}'")
end
end
end
response = auth_service.request(config[:auth_service][:request].to_sym, opts, &block)
if [200, 201].include? response.status
@auth_response = Hashish.new({
:headers => response.headers,
:body => response.body
})
update_services_session_data
else
raise AuthenticationError.new(response.body)
end
self
end | ruby | def authenticate(opts={}, &block)
block ||= lambda do |params|
config[:auth_credentials].each do |key, value|
begin
params[key] = value
rescue NameError => e
raise NameError.new("Unknown param name '#{key}'")
end
end
end
response = auth_service.request(config[:auth_service][:request].to_sym, opts, &block)
if [200, 201].include? response.status
@auth_response = Hashish.new({
:headers => response.headers,
:body => response.body
})
update_services_session_data
else
raise AuthenticationError.new(response.body)
end
self
end | [
"def",
"authenticate",
"(",
"opts",
"=",
"{",
"}",
",",
"&",
"block",
")",
"block",
"||=",
"lambda",
"do",
"|",
"params",
"|",
"config",
"[",
":auth_credentials",
"]",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"begin",
"params",
"[",
"key",
"]",
"=",
"value",
"rescue",
"NameError",
"=>",
"e",
"raise",
"NameError",
".",
"new",
"(",
"\"Unknown param name '#{key}'\"",
")",
"end",
"end",
"end",
"response",
"=",
"auth_service",
".",
"request",
"(",
"config",
"[",
":auth_service",
"]",
"[",
":request",
"]",
".",
"to_sym",
",",
"opts",
",",
"&",
"block",
")",
"if",
"[",
"200",
",",
"201",
"]",
".",
"include?",
"response",
".",
"status",
"@auth_response",
"=",
"Hashish",
".",
"new",
"(",
"{",
":headers",
"=>",
"response",
".",
"headers",
",",
":body",
"=>",
"response",
".",
"body",
"}",
")",
"update_services_session_data",
"else",
"raise",
"AuthenticationError",
".",
"new",
"(",
"response",
".",
"body",
")",
"end",
"self",
"end"
]
| Create a new Session instance.
<b>Initialize with a config file</b>
Aviator::Session.new(:config_file => 'path/to/aviator.yml', :environment => :production)
In the above example, the config file must have the following form:
production:
provider: openstack
auth_service:
name: identity
host_uri: 'http://my.openstackenv.org:5000'
request: create_token
validator: list_tenants
api_version: v2
auth_credentials:
username: myusername
password: mypassword
tenant_name: myproject
<b>SIDENOTE:</b> For more information about the <tt>validator</tt> member, see Session#validate.
Once the session has been instantiated, you may authenticate against the
provider as follows:
session.authenticate
The members you put under <tt>auth_credentials</tt> will depend on the request
class you declare under <tt>auth_service:request</tt> and what parameters it
accepts. To know more about a request class and its parameters, you can use
the CLI tool <tt>aviator describe</tt> or view the request definition file directly.
If writing the <tt>auth_credentials</tt> in the config file is not acceptable,
you may omit it and just supply the credentials at runtime. For example:
session.authenticate do |params|
params.username = ARGV[0]
params.password = ARGV[1]
params.tenant_name = ARGV[2]
end
See Session#authenticate for more info.
Note that while the example config file above only has one environment (production),
you can declare an arbitrary number of environments in your config file. Shifting
between environments is as simple as changing the <tt>:environment</tt> to refer to that.
<b>Initialize with an in-memory hash</b>
You can create an in-memory hash with a structure similar to the config file but without
the environment name. For example:
configuration = {
:provider => 'openstack',
:auth_service => {
:name => 'identity',
:host_uri => 'http://devstack:5000/v2.0',
:request => 'create_token',
:validator => 'list_tenants'
}
}
Supply this to the initializer using the <tt>:config</tt> option. For example:
Aviator::Session.new(:config => configuration)
<b>Initialize with a session dump</b>
You can create a new Session instance using a dump from another instance. For example:
session_dump = session1.dump
session2 = Aviator::Session.new(:session_dump => session_dump)
However, Session.load is cleaner and recommended over this method.
<b>Optionally supply a log file</b>
In all forms above, you may optionally add a <tt>:log_file</tt> option to make
Aviator write all HTTP calls to the given path. For example:
Aviator::Session.new(:config_file => 'path/to/aviator.yml', :environment => :production, :log_file => 'path/to/log')
Authenticates against the backend provider using the auth_service request class
declared in the session's configuration. Please see Session.new for more information
on declaring the request class to use for authentication.
<b>Request params block</b>
If the auth_service request class accepts parameters, you may supply that
as a block and it will be directly passed to the request. For example:
session = Aviator::Session.new(:config => config)
session.authenticate do |params|
params.username = username
params.password = password
params.tenant_name = project
end
If your configuration happens to have an <tt>auth_credentials</tt> in it, those
will be overridden by this block.
<b>Treat parameters as a hash</b>
You can also treat the params struct like a hash with the attribute
names as the keys. For example, we can rewrite the above as:
session = Aviator::Session.new(:config => config)
session.authenticate do |params|
params[:username] = username
params[:password] = password
params[:tenant_name] = project
end
Keys can be symbols or strings.
<b>Use a hash argument instead of a block</b>
You may also provide request params as an argument instead of a block. This is
especially useful if you want to mock Aviator as it's easier to specify ordinary
argument expectations over blocks. Further rewriting the example above,
we end up with:
session = Aviator::Session.new(:config => config)
session.authenticate :params => {
:username => username,
:password => password,
:tenant_name => project
}
If both <tt>:params</tt> and a block are provided, the <tt>:params</tt>
values will be used and the block ignored.
<b>Success requirements</b>
Expects an HTTP status 200 or 201 response from the backend. Any other
status is treated as a failure. | [
"Create",
"a",
"new",
"Session",
"instance",
"."
]
| 96fd83c1a131bc0532fc89696935173506c891fa | https://github.com/aviator/aviator/blob/96fd83c1a131bc0532fc89696935173506c891fa/lib/aviator/core/session.rb#L212-L235 | train |
mhgbrown/cached_resource | lib/cached_resource/configuration.rb | CachedResource.Configuration.sample_range | def sample_range(range, seed=nil)
srand seed if seed
rand * (range.end - range.begin) + range.begin
end | ruby | def sample_range(range, seed=nil)
srand seed if seed
rand * (range.end - range.begin) + range.begin
end | [
"def",
"sample_range",
"(",
"range",
",",
"seed",
"=",
"nil",
")",
"srand",
"seed",
"if",
"seed",
"rand",
"*",
"(",
"range",
".",
"end",
"-",
"range",
".",
"begin",
")",
"+",
"range",
".",
"begin",
"end"
]
| Choose a random value from within the given range, optionally
seeded by seed. | [
"Choose",
"a",
"random",
"value",
"from",
"within",
"the",
"given",
"range",
"optionally",
"seeded",
"by",
"seed",
"."
]
| 0a69e2abf6d9432655b2795f081065ac4b6735b6 | https://github.com/mhgbrown/cached_resource/blob/0a69e2abf6d9432655b2795f081065ac4b6735b6/lib/cached_resource/configuration.rb#L67-L70 | train |
voloko/twitter-stream | lib/twitter/json_stream.rb | Twitter.JSONStream.receive_stream_data | def receive_stream_data(data)
begin
@buffer.extract(data).each do |line|
parse_stream_line(line)
end
@stream = ''
rescue => e
receive_error("#{e.class}: " + [e.message, e.backtrace].flatten.join("\n\t"))
close_connection
return
end
end | ruby | def receive_stream_data(data)
begin
@buffer.extract(data).each do |line|
parse_stream_line(line)
end
@stream = ''
rescue => e
receive_error("#{e.class}: " + [e.message, e.backtrace].flatten.join("\n\t"))
close_connection
return
end
end | [
"def",
"receive_stream_data",
"(",
"data",
")",
"begin",
"@buffer",
".",
"extract",
"(",
"data",
")",
".",
"each",
"do",
"|",
"line",
"|",
"parse_stream_line",
"(",
"line",
")",
"end",
"@stream",
"=",
"''",
"rescue",
"=>",
"e",
"receive_error",
"(",
"\"#{e.class}: \"",
"+",
"[",
"e",
".",
"message",
",",
"e",
".",
"backtrace",
"]",
".",
"flatten",
".",
"join",
"(",
"\"\\n\\t\"",
")",
")",
"close_connection",
"return",
"end",
"end"
]
| Called every time a chunk of data is read from the connection once it has
been opened and after the headers have been processed. | [
"Called",
"every",
"time",
"a",
"chunk",
"of",
"data",
"is",
"read",
"from",
"the",
"connection",
"once",
"it",
"has",
"been",
"opened",
"and",
"after",
"the",
"headers",
"have",
"been",
"processed",
"."
]
| 45ce963d56e6e383f0e001522a817e7538438f71 | https://github.com/voloko/twitter-stream/blob/45ce963d56e6e383f0e001522a817e7538438f71/lib/twitter/json_stream.rb#L226-L237 | train |
voloko/twitter-stream | lib/twitter/json_stream.rb | Twitter.JSONStream.oauth_header | def oauth_header
uri = uri_base + @options[:path].to_s
# The hash SimpleOAuth accepts is slightly different from that of
# ROAuth. To preserve backward compatability, fix the cache here
# so that the arguments passed in don't need to change.
oauth = {
:consumer_key => @options[:oauth][:consumer_key],
:consumer_secret => @options[:oauth][:consumer_secret],
:token => @options[:oauth][:access_key],
:token_secret => @options[:oauth][:access_secret]
}
data = ['POST', 'PUT'].include?(@options[:method]) ? params : {}
SimpleOAuth::Header.new(@options[:method], uri, data, oauth)
end | ruby | def oauth_header
uri = uri_base + @options[:path].to_s
# The hash SimpleOAuth accepts is slightly different from that of
# ROAuth. To preserve backward compatability, fix the cache here
# so that the arguments passed in don't need to change.
oauth = {
:consumer_key => @options[:oauth][:consumer_key],
:consumer_secret => @options[:oauth][:consumer_secret],
:token => @options[:oauth][:access_key],
:token_secret => @options[:oauth][:access_secret]
}
data = ['POST', 'PUT'].include?(@options[:method]) ? params : {}
SimpleOAuth::Header.new(@options[:method], uri, data, oauth)
end | [
"def",
"oauth_header",
"uri",
"=",
"uri_base",
"+",
"@options",
"[",
":path",
"]",
".",
"to_s",
"oauth",
"=",
"{",
":consumer_key",
"=>",
"@options",
"[",
":oauth",
"]",
"[",
":consumer_key",
"]",
",",
":consumer_secret",
"=>",
"@options",
"[",
":oauth",
"]",
"[",
":consumer_secret",
"]",
",",
":token",
"=>",
"@options",
"[",
":oauth",
"]",
"[",
":access_key",
"]",
",",
":token_secret",
"=>",
"@options",
"[",
":oauth",
"]",
"[",
":access_secret",
"]",
"}",
"data",
"=",
"[",
"'POST'",
",",
"'PUT'",
"]",
".",
"include?",
"(",
"@options",
"[",
":method",
"]",
")",
"?",
"params",
":",
"{",
"}",
"SimpleOAuth",
"::",
"Header",
".",
"new",
"(",
"@options",
"[",
":method",
"]",
",",
"uri",
",",
"data",
",",
"oauth",
")",
"end"
]
| URL and request components
:filters => %w(miama lebron jesus)
:oauth => {
:consumer_key => [key],
:consumer_secret => [token],
:access_key => [access key],
:access_secret => [access secret]
} | [
"URL",
"and",
"request",
"components"
]
| 45ce963d56e6e383f0e001522a817e7538438f71 | https://github.com/voloko/twitter-stream/blob/45ce963d56e6e383f0e001522a817e7538438f71/lib/twitter/json_stream.rb#L322-L338 | train |
voloko/twitter-stream | lib/twitter/json_stream.rb | Twitter.JSONStream.params | def params
flat = {}
@options[:params].merge( :track => @options[:filters] ).each do |param, val|
next if val.to_s.empty? || (val.respond_to?(:empty?) && val.empty?)
val = val.join(",") if val.respond_to?(:join)
flat[param.to_s] = val.to_s
end
flat
end | ruby | def params
flat = {}
@options[:params].merge( :track => @options[:filters] ).each do |param, val|
next if val.to_s.empty? || (val.respond_to?(:empty?) && val.empty?)
val = val.join(",") if val.respond_to?(:join)
flat[param.to_s] = val.to_s
end
flat
end | [
"def",
"params",
"flat",
"=",
"{",
"}",
"@options",
"[",
":params",
"]",
".",
"merge",
"(",
":track",
"=>",
"@options",
"[",
":filters",
"]",
")",
".",
"each",
"do",
"|",
"param",
",",
"val",
"|",
"next",
"if",
"val",
".",
"to_s",
".",
"empty?",
"||",
"(",
"val",
".",
"respond_to?",
"(",
":empty?",
")",
"&&",
"val",
".",
"empty?",
")",
"val",
"=",
"val",
".",
"join",
"(",
"\",\"",
")",
"if",
"val",
".",
"respond_to?",
"(",
":join",
")",
"flat",
"[",
"param",
".",
"to_s",
"]",
"=",
"val",
".",
"to_s",
"end",
"flat",
"end"
]
| Normalized query hash of escaped string keys and escaped string values
nil values are skipped | [
"Normalized",
"query",
"hash",
"of",
"escaped",
"string",
"keys",
"and",
"escaped",
"string",
"values",
"nil",
"values",
"are",
"skipped"
]
| 45ce963d56e6e383f0e001522a817e7538438f71 | https://github.com/voloko/twitter-stream/blob/45ce963d56e6e383f0e001522a817e7538438f71/lib/twitter/json_stream.rb#L347-L355 | train |
crowdin/crowdin-api | lib/crowdin-api/methods.rb | Crowdin.API.add_file | def add_file(files, params = {})
params[:files] = Hash[files.map { |f| [
f[:dest] || raise(ArgumentError, "'`:dest`' is required"),
::File.open(f[:source] || raise(ArgumentError, "'`:source` is required'"))
] }]
params[:titles] = Hash[files.map { |f| [f[:dest], f[:title]] }]
params[:titles].delete_if { |_, v| v.nil? }
params[:export_patterns] = Hash[files.map { |f| [f[:dest], f[:export_pattern]] }]
params[:export_patterns].delete_if { |_, v| v.nil? }
params.delete_if { |_, v| v.respond_to?(:empty?) ? !!v.empty? : !v }
request(
:method => :post,
:path => "/api/project/#{@project_id}/add-file",
:query => params,
)
end | ruby | def add_file(files, params = {})
params[:files] = Hash[files.map { |f| [
f[:dest] || raise(ArgumentError, "'`:dest`' is required"),
::File.open(f[:source] || raise(ArgumentError, "'`:source` is required'"))
] }]
params[:titles] = Hash[files.map { |f| [f[:dest], f[:title]] }]
params[:titles].delete_if { |_, v| v.nil? }
params[:export_patterns] = Hash[files.map { |f| [f[:dest], f[:export_pattern]] }]
params[:export_patterns].delete_if { |_, v| v.nil? }
params.delete_if { |_, v| v.respond_to?(:empty?) ? !!v.empty? : !v }
request(
:method => :post,
:path => "/api/project/#{@project_id}/add-file",
:query => params,
)
end | [
"def",
"add_file",
"(",
"files",
",",
"params",
"=",
"{",
"}",
")",
"params",
"[",
":files",
"]",
"=",
"Hash",
"[",
"files",
".",
"map",
"{",
"|",
"f",
"|",
"[",
"f",
"[",
":dest",
"]",
"||",
"raise",
"(",
"ArgumentError",
",",
"\"'`:dest`' is required\"",
")",
",",
"::",
"File",
".",
"open",
"(",
"f",
"[",
":source",
"]",
"||",
"raise",
"(",
"ArgumentError",
",",
"\"'`:source` is required'\"",
")",
")",
"]",
"}",
"]",
"params",
"[",
":titles",
"]",
"=",
"Hash",
"[",
"files",
".",
"map",
"{",
"|",
"f",
"|",
"[",
"f",
"[",
":dest",
"]",
",",
"f",
"[",
":title",
"]",
"]",
"}",
"]",
"params",
"[",
":titles",
"]",
".",
"delete_if",
"{",
"|",
"_",
",",
"v",
"|",
"v",
".",
"nil?",
"}",
"params",
"[",
":export_patterns",
"]",
"=",
"Hash",
"[",
"files",
".",
"map",
"{",
"|",
"f",
"|",
"[",
"f",
"[",
":dest",
"]",
",",
"f",
"[",
":export_pattern",
"]",
"]",
"}",
"]",
"params",
"[",
":export_patterns",
"]",
".",
"delete_if",
"{",
"|",
"_",
",",
"v",
"|",
"v",
".",
"nil?",
"}",
"params",
".",
"delete_if",
"{",
"|",
"_",
",",
"v",
"|",
"v",
".",
"respond_to?",
"(",
":empty?",
")",
"?",
"!",
"!",
"v",
".",
"empty?",
":",
"!",
"v",
"}",
"request",
"(",
":method",
"=>",
":post",
",",
":path",
"=>",
"\"/api/project/#{@project_id}/add-file\"",
",",
":query",
"=>",
"params",
",",
")",
"end"
]
| Add new file to Crowdin project.
== Parameters
files - Array of files that should be added to Crowdin project.
file is a Hash { :dest, :source, :title, :export_pattern }
* :dest - file name with path in Crowdin project (required)
* :source - path for uploaded file (required)
* :title - title in Crowdin UI (optional)
* :export_pattern - Resulted file name (optional)
Optional:
* :branch - a branch name.
If the branch is not exists Crowdin will be return an error:
"error":{
"code":8,
"message":"File was not found"
}
== Request
POST https://api.crowdin.com/api/project/{project-identifier}/add-file?key={project-key} | [
"Add",
"new",
"file",
"to",
"Crowdin",
"project",
"."
]
| e36e09dd5474244e69b664c8ec33c627cd20c299 | https://github.com/crowdin/crowdin-api/blob/e36e09dd5474244e69b664c8ec33c627cd20c299/lib/crowdin-api/methods.rb#L33-L52 | train |
crowdin/crowdin-api | lib/crowdin-api/methods.rb | Crowdin.API.update_file | def update_file(files, params = {})
params[:files] = Hash[files.map { |f|
dest = f[:dest] || raise(ArgumentError, "'`:dest` is required'")
source = ::File.open(f[:source] || raise(ArgumentError, "'`:source` is required'"))
source.define_singleton_method(:original_filename) do
dest
end
[dest, source]
}]
params[:titles] = Hash[files.map { |f| [f[:dest], f[:title]] }]
params[:titles].delete_if { |_, v| v.nil? }
params[:export_patterns] = Hash[files.map { |f| [f[:dest], f[:export_pattern]] }]
params[:export_patterns].delete_if { |_, v| v.nil? }
params.delete_if { |_, v| v.respond_to?(:empty?) ? !!v.empty? : !v }
request(
:method => :post,
:path => "/api/project/#{@project_id}/update-file",
:query => params,
)
end | ruby | def update_file(files, params = {})
params[:files] = Hash[files.map { |f|
dest = f[:dest] || raise(ArgumentError, "'`:dest` is required'")
source = ::File.open(f[:source] || raise(ArgumentError, "'`:source` is required'"))
source.define_singleton_method(:original_filename) do
dest
end
[dest, source]
}]
params[:titles] = Hash[files.map { |f| [f[:dest], f[:title]] }]
params[:titles].delete_if { |_, v| v.nil? }
params[:export_patterns] = Hash[files.map { |f| [f[:dest], f[:export_pattern]] }]
params[:export_patterns].delete_if { |_, v| v.nil? }
params.delete_if { |_, v| v.respond_to?(:empty?) ? !!v.empty? : !v }
request(
:method => :post,
:path => "/api/project/#{@project_id}/update-file",
:query => params,
)
end | [
"def",
"update_file",
"(",
"files",
",",
"params",
"=",
"{",
"}",
")",
"params",
"[",
":files",
"]",
"=",
"Hash",
"[",
"files",
".",
"map",
"{",
"|",
"f",
"|",
"dest",
"=",
"f",
"[",
":dest",
"]",
"||",
"raise",
"(",
"ArgumentError",
",",
"\"'`:dest` is required'\"",
")",
"source",
"=",
"::",
"File",
".",
"open",
"(",
"f",
"[",
":source",
"]",
"||",
"raise",
"(",
"ArgumentError",
",",
"\"'`:source` is required'\"",
")",
")",
"source",
".",
"define_singleton_method",
"(",
":original_filename",
")",
"do",
"dest",
"end",
"[",
"dest",
",",
"source",
"]",
"}",
"]",
"params",
"[",
":titles",
"]",
"=",
"Hash",
"[",
"files",
".",
"map",
"{",
"|",
"f",
"|",
"[",
"f",
"[",
":dest",
"]",
",",
"f",
"[",
":title",
"]",
"]",
"}",
"]",
"params",
"[",
":titles",
"]",
".",
"delete_if",
"{",
"|",
"_",
",",
"v",
"|",
"v",
".",
"nil?",
"}",
"params",
"[",
":export_patterns",
"]",
"=",
"Hash",
"[",
"files",
".",
"map",
"{",
"|",
"f",
"|",
"[",
"f",
"[",
":dest",
"]",
",",
"f",
"[",
":export_pattern",
"]",
"]",
"}",
"]",
"params",
"[",
":export_patterns",
"]",
".",
"delete_if",
"{",
"|",
"_",
",",
"v",
"|",
"v",
".",
"nil?",
"}",
"params",
".",
"delete_if",
"{",
"|",
"_",
",",
"v",
"|",
"v",
".",
"respond_to?",
"(",
":empty?",
")",
"?",
"!",
"!",
"v",
".",
"empty?",
":",
"!",
"v",
"}",
"request",
"(",
":method",
"=>",
":post",
",",
":path",
"=>",
"\"/api/project/#{@project_id}/update-file\"",
",",
":query",
"=>",
"params",
",",
")",
"end"
]
| Upload fresh version of your localization file to Crowdin.
== Parameters
files - Array of files that should be updated in Crowdin project.
file is a Hash { :dest, :source }
* :dest - file name with path in Crowdin project (required)
* :source - path for uploaded file (required)
* :title - title in Crowdin UI (optional)
* :export_pattern - Resulted file name (optional)
Optional:
* :branch - a branch name
== Request
POST https://api.crowdin.com/api/project/{project-identifier}/update-file?key={project-key} | [
"Upload",
"fresh",
"version",
"of",
"your",
"localization",
"file",
"to",
"Crowdin",
"."
]
| e36e09dd5474244e69b664c8ec33c627cd20c299 | https://github.com/crowdin/crowdin-api/blob/e36e09dd5474244e69b664c8ec33c627cd20c299/lib/crowdin-api/methods.rb#L72-L95 | train |
crowdin/crowdin-api | lib/crowdin-api/methods.rb | Crowdin.API.upload_translation | def upload_translation(files, language, params = {})
params[:files] = Hash[files.map { |f| [
f[:dest] || raise(ArgumentError, "`:dest` is required"),
::File.open(f[:source] || raise(ArgumentError, "`:source` is required"))
] }]
params[:language] = language
request(
:method => :post,
:path => "/api/project/#{@project_id}/upload-translation",
:query => params,
)
end | ruby | def upload_translation(files, language, params = {})
params[:files] = Hash[files.map { |f| [
f[:dest] || raise(ArgumentError, "`:dest` is required"),
::File.open(f[:source] || raise(ArgumentError, "`:source` is required"))
] }]
params[:language] = language
request(
:method => :post,
:path => "/api/project/#{@project_id}/upload-translation",
:query => params,
)
end | [
"def",
"upload_translation",
"(",
"files",
",",
"language",
",",
"params",
"=",
"{",
"}",
")",
"params",
"[",
":files",
"]",
"=",
"Hash",
"[",
"files",
".",
"map",
"{",
"|",
"f",
"|",
"[",
"f",
"[",
":dest",
"]",
"||",
"raise",
"(",
"ArgumentError",
",",
"\"`:dest` is required\"",
")",
",",
"::",
"File",
".",
"open",
"(",
"f",
"[",
":source",
"]",
"||",
"raise",
"(",
"ArgumentError",
",",
"\"`:source` is required\"",
")",
")",
"]",
"}",
"]",
"params",
"[",
":language",
"]",
"=",
"language",
"request",
"(",
":method",
"=>",
":post",
",",
":path",
"=>",
"\"/api/project/#{@project_id}/upload-translation\"",
",",
":query",
"=>",
"params",
",",
")",
"end"
]
| Upload existing translations to your Crowdin project.
== Parameters
files - Array of files that should be added to Crowdin project.
file is a Hash { :dest, :source }
* :dest - file name with path in Crowdin project (required)
* :source - path for uploaded file (required)
language - Target language. With a single call it's possible to upload translations for several
files but only into one of the languages. (required)
Optional:
* :import_duplicates (default: false)
* :import_eq_suggestions (default: false)
* :auto_approve_imported (default: false)
* :branch - a branch name
== Request
POST https://api.crowdin.com/api/project/{project-identifier}/upload-translation?key={project-key} | [
"Upload",
"existing",
"translations",
"to",
"your",
"Crowdin",
"project",
"."
]
| e36e09dd5474244e69b664c8ec33c627cd20c299 | https://github.com/crowdin/crowdin-api/blob/e36e09dd5474244e69b664c8ec33c627cd20c299/lib/crowdin-api/methods.rb#L118-L131 | train |
crowdin/crowdin-api | lib/crowdin-api.rb | Crowdin.API.request | def request(params, &block)
# Returns a query hash with non nil values.
params[:query].reject! { |_, value| value.nil? } if params[:query]
case params[:method]
when :post
query = @connection.options.merge(params[:query] || {})
@connection[params[:path]].post(query) { |response, _, _|
@response = response
}
when :get
query = @connection.options[:params].merge(params[:query] || {})
@connection[params[:path]].get(:params => query) { |response, _, _|
@response = response
}
end
log.debug("args: #{@response.request.args}") if log
if @response.headers[:content_disposition]
filename = params[:output] || @response.headers[:content_disposition][/attachment; filename="(.+?)"/, 1]
body = @response.body
file = open(filename, 'wb')
file.write(body)
file.close
return true
else
doc = JSON.load(@response.body)
log.debug("body: #{doc}") if log
if doc.kind_of?(Hash) && doc['success'] == false
code = doc['error']['code']
message = doc['error']['message']
error = Crowdin::API::Errors::Error.new(code, message)
raise(error)
else
return doc
end
end
end | ruby | def request(params, &block)
# Returns a query hash with non nil values.
params[:query].reject! { |_, value| value.nil? } if params[:query]
case params[:method]
when :post
query = @connection.options.merge(params[:query] || {})
@connection[params[:path]].post(query) { |response, _, _|
@response = response
}
when :get
query = @connection.options[:params].merge(params[:query] || {})
@connection[params[:path]].get(:params => query) { |response, _, _|
@response = response
}
end
log.debug("args: #{@response.request.args}") if log
if @response.headers[:content_disposition]
filename = params[:output] || @response.headers[:content_disposition][/attachment; filename="(.+?)"/, 1]
body = @response.body
file = open(filename, 'wb')
file.write(body)
file.close
return true
else
doc = JSON.load(@response.body)
log.debug("body: #{doc}") if log
if doc.kind_of?(Hash) && doc['success'] == false
code = doc['error']['code']
message = doc['error']['message']
error = Crowdin::API::Errors::Error.new(code, message)
raise(error)
else
return doc
end
end
end | [
"def",
"request",
"(",
"params",
",",
"&",
"block",
")",
"params",
"[",
":query",
"]",
".",
"reject!",
"{",
"|",
"_",
",",
"value",
"|",
"value",
".",
"nil?",
"}",
"if",
"params",
"[",
":query",
"]",
"case",
"params",
"[",
":method",
"]",
"when",
":post",
"query",
"=",
"@connection",
".",
"options",
".",
"merge",
"(",
"params",
"[",
":query",
"]",
"||",
"{",
"}",
")",
"@connection",
"[",
"params",
"[",
":path",
"]",
"]",
".",
"post",
"(",
"query",
")",
"{",
"|",
"response",
",",
"_",
",",
"_",
"|",
"@response",
"=",
"response",
"}",
"when",
":get",
"query",
"=",
"@connection",
".",
"options",
"[",
":params",
"]",
".",
"merge",
"(",
"params",
"[",
":query",
"]",
"||",
"{",
"}",
")",
"@connection",
"[",
"params",
"[",
":path",
"]",
"]",
".",
"get",
"(",
":params",
"=>",
"query",
")",
"{",
"|",
"response",
",",
"_",
",",
"_",
"|",
"@response",
"=",
"response",
"}",
"end",
"log",
".",
"debug",
"(",
"\"args: #{@response.request.args}\"",
")",
"if",
"log",
"if",
"@response",
".",
"headers",
"[",
":content_disposition",
"]",
"filename",
"=",
"params",
"[",
":output",
"]",
"||",
"@response",
".",
"headers",
"[",
":content_disposition",
"]",
"[",
"/",
"/",
",",
"1",
"]",
"body",
"=",
"@response",
".",
"body",
"file",
"=",
"open",
"(",
"filename",
",",
"'wb'",
")",
"file",
".",
"write",
"(",
"body",
")",
"file",
".",
"close",
"return",
"true",
"else",
"doc",
"=",
"JSON",
".",
"load",
"(",
"@response",
".",
"body",
")",
"log",
".",
"debug",
"(",
"\"body: #{doc}\"",
")",
"if",
"log",
"if",
"doc",
".",
"kind_of?",
"(",
"Hash",
")",
"&&",
"doc",
"[",
"'success'",
"]",
"==",
"false",
"code",
"=",
"doc",
"[",
"'error'",
"]",
"[",
"'code'",
"]",
"message",
"=",
"doc",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
"error",
"=",
"Crowdin",
"::",
"API",
"::",
"Errors",
"::",
"Error",
".",
"new",
"(",
"code",
",",
"message",
")",
"raise",
"(",
"error",
")",
"else",
"return",
"doc",
"end",
"end",
"end"
]
| Create a new API object using the given parameters.
@param [String] api_key the authentication API key can be found on the project settings page
@param [String] project_id the project identifier.
@param [String] account_key the account API Key
@param [String] base_url the url of the Crowdin API | [
"Create",
"a",
"new",
"API",
"object",
"using",
"the",
"given",
"parameters",
"."
]
| e36e09dd5474244e69b664c8ec33c627cd20c299 | https://github.com/crowdin/crowdin-api/blob/e36e09dd5474244e69b664c8ec33c627cd20c299/lib/crowdin-api.rb#L72-L112 | train |
locaweb/heartcheck | lib/heartcheck/app.rb | Heartcheck.App.call | def call(env)
req = Rack::Request.new(env)
[200, { 'Content-Type' => 'application/json' }, [dispatch_action(req)]]
rescue Heartcheck::Errors::RoutingError
[404, { 'Content-Type' => 'application/json' }, ['Not found']]
end | ruby | def call(env)
req = Rack::Request.new(env)
[200, { 'Content-Type' => 'application/json' }, [dispatch_action(req)]]
rescue Heartcheck::Errors::RoutingError
[404, { 'Content-Type' => 'application/json' }, ['Not found']]
end | [
"def",
"call",
"(",
"env",
")",
"req",
"=",
"Rack",
"::",
"Request",
".",
"new",
"(",
"env",
")",
"[",
"200",
",",
"{",
"'Content-Type'",
"=>",
"'application/json'",
"}",
",",
"[",
"dispatch_action",
"(",
"req",
")",
"]",
"]",
"rescue",
"Heartcheck",
"::",
"Errors",
"::",
"RoutingError",
"[",
"404",
",",
"{",
"'Content-Type'",
"=>",
"'application/json'",
"}",
",",
"[",
"'Not found'",
"]",
"]",
"end"
]
| Sets up the rack application.
@param app [RackApp] is a rack app where
heartcheck is included.
@return [void]
Sets up the rack application.
@param env [Hash] is an instance of Hash
that includes CGI-like headers.
@return [Array] must be an array that contains
- The HTTP response code
- A Hash of headers
- The response body, which must respond to each | [
"Sets",
"up",
"the",
"rack",
"application",
"."
]
| b1ee73c8a1498f1de28f494c4272cb4698e71e26 | https://github.com/locaweb/heartcheck/blob/b1ee73c8a1498f1de28f494c4272cb4698e71e26/lib/heartcheck/app.rb#L43-L49 | train |
locaweb/heartcheck | lib/heartcheck/app.rb | Heartcheck.App.dispatch_action | def dispatch_action(req)
controller = ROUTE_TO_CONTROLLER[req.path_info]
fail Heartcheck::Errors::RoutingError if controller.nil?
Logger.info "Start [#{controller}] from #{req.ip} at #{Time.now}"
controller.new.index.tap do |_|
Logger.info "End [#{controller}]\n"
end
end | ruby | def dispatch_action(req)
controller = ROUTE_TO_CONTROLLER[req.path_info]
fail Heartcheck::Errors::RoutingError if controller.nil?
Logger.info "Start [#{controller}] from #{req.ip} at #{Time.now}"
controller.new.index.tap do |_|
Logger.info "End [#{controller}]\n"
end
end | [
"def",
"dispatch_action",
"(",
"req",
")",
"controller",
"=",
"ROUTE_TO_CONTROLLER",
"[",
"req",
".",
"path_info",
"]",
"fail",
"Heartcheck",
"::",
"Errors",
"::",
"RoutingError",
"if",
"controller",
".",
"nil?",
"Logger",
".",
"info",
"\"Start [#{controller}] from #{req.ip} at #{Time.now}\"",
"controller",
".",
"new",
".",
"index",
".",
"tap",
"do",
"|",
"_",
"|",
"Logger",
".",
"info",
"\"End [#{controller}]\\n\"",
"end",
"end"
]
| Find a controller to espefic path
and call the index method
@param req [Rack::Request] an instance of request
@return [String] a response body | [
"Find",
"a",
"controller",
"to",
"espefic",
"path",
"and",
"call",
"the",
"index",
"method"
]
| b1ee73c8a1498f1de28f494c4272cb4698e71e26 | https://github.com/locaweb/heartcheck/blob/b1ee73c8a1498f1de28f494c4272cb4698e71e26/lib/heartcheck/app.rb#L59-L68 | train |
czarneckid/redis_pagination | lib/redis_pagination/paginator.rb | RedisPagination.Paginator.paginate | def paginate(key, options = {})
type = RedisPagination.redis.type(key)
case type
when 'list'
RedisPagination::Paginator::ListPaginator.new(key, options)
when 'zset'
RedisPagination::Paginator::SortedSetPaginator.new(key, options)
when 'none'
RedisPagination::Paginator::NonePaginator.new(key, options)
else
raise "Pagination is not supported for #{type}"
end
end | ruby | def paginate(key, options = {})
type = RedisPagination.redis.type(key)
case type
when 'list'
RedisPagination::Paginator::ListPaginator.new(key, options)
when 'zset'
RedisPagination::Paginator::SortedSetPaginator.new(key, options)
when 'none'
RedisPagination::Paginator::NonePaginator.new(key, options)
else
raise "Pagination is not supported for #{type}"
end
end | [
"def",
"paginate",
"(",
"key",
",",
"options",
"=",
"{",
"}",
")",
"type",
"=",
"RedisPagination",
".",
"redis",
".",
"type",
"(",
"key",
")",
"case",
"type",
"when",
"'list'",
"RedisPagination",
"::",
"Paginator",
"::",
"ListPaginator",
".",
"new",
"(",
"key",
",",
"options",
")",
"when",
"'zset'",
"RedisPagination",
"::",
"Paginator",
"::",
"SortedSetPaginator",
".",
"new",
"(",
"key",
",",
"options",
")",
"when",
"'none'",
"RedisPagination",
"::",
"Paginator",
"::",
"NonePaginator",
".",
"new",
"(",
"key",
",",
"options",
")",
"else",
"raise",
"\"Pagination is not supported for #{type}\"",
"end",
"end"
]
| Retrieve a paginator class appropriate for the +key+ in Redis.
+key+ must be one of +list+ or +zset+, otherwise an exception
will be raised.
@params key [String] Redis key
@params options [Hash] Options to be passed to the individual paginator class.
@return Returns either a +RedisPagination::Paginator::ListPaginator+ or
a +RedisPagination::Paginator::SortedSetPaginator+ depending on the
type of +key+. | [
"Retrieve",
"a",
"paginator",
"class",
"appropriate",
"for",
"the",
"+",
"key",
"+",
"in",
"Redis",
".",
"+",
"key",
"+",
"must",
"be",
"one",
"of",
"+",
"list",
"+",
"or",
"+",
"zset",
"+",
"otherwise",
"an",
"exception",
"will",
"be",
"raised",
"."
]
| fecc1d9ee579ceb3ca7df5c45031422d43aaceef | https://github.com/czarneckid/redis_pagination/blob/fecc1d9ee579ceb3ca7df5c45031422d43aaceef/lib/redis_pagination/paginator.rb#L17-L30 | train |
locaweb/heartcheck | lib/heartcheck/caching_app.rb | Heartcheck.CachingApp.call | def call(env)
req = Rack::Request.new(env)
controller = Heartcheck::App::ROUTE_TO_CONTROLLER[req.path_info]
if controller && (result = cache.result(controller))
[200, { 'Content-type' => 'application/json' }, [result]]
else
@app.call(env)
end
end | ruby | def call(env)
req = Rack::Request.new(env)
controller = Heartcheck::App::ROUTE_TO_CONTROLLER[req.path_info]
if controller && (result = cache.result(controller))
[200, { 'Content-type' => 'application/json' }, [result]]
else
@app.call(env)
end
end | [
"def",
"call",
"(",
"env",
")",
"req",
"=",
"Rack",
"::",
"Request",
".",
"new",
"(",
"env",
")",
"controller",
"=",
"Heartcheck",
"::",
"App",
"::",
"ROUTE_TO_CONTROLLER",
"[",
"req",
".",
"path_info",
"]",
"if",
"controller",
"&&",
"(",
"result",
"=",
"cache",
".",
"result",
"(",
"controller",
")",
")",
"[",
"200",
",",
"{",
"'Content-type'",
"=>",
"'application/json'",
"}",
",",
"[",
"result",
"]",
"]",
"else",
"@app",
".",
"call",
"(",
"env",
")",
"end",
"end"
]
| Creates an instance of the middleware
@param app [Heartcheck:App] the Rack app to wrap around
@param ttl [Integer] the time to cache the results in seconds
@param cache [Heartcheck::CachingApp::Cache] the cache instance to use
The cache will be created on first use if not supplied
@return [#call] rack compatible middleware
Invokes the middleware
@param env [Hash] the rack request/environment
@return [Array] a rack compatible response | [
"Creates",
"an",
"instance",
"of",
"the",
"middleware"
]
| b1ee73c8a1498f1de28f494c4272cb4698e71e26 | https://github.com/locaweb/heartcheck/blob/b1ee73c8a1498f1de28f494c4272cb4698e71e26/lib/heartcheck/caching_app.rb#L26-L35 | train |
giuseb/mork | lib/mork/grid_omr.rb | Mork.GridOMR.rx | def rx(corner)
case corner
when :tl; reg_off
when :tr; page_width - reg_crop - reg_off
when :br; page_width - reg_crop - reg_off
when :bl; reg_off
end
end | ruby | def rx(corner)
case corner
when :tl; reg_off
when :tr; page_width - reg_crop - reg_off
when :br; page_width - reg_crop - reg_off
when :bl; reg_off
end
end | [
"def",
"rx",
"(",
"corner",
")",
"case",
"corner",
"when",
":tl",
";",
"reg_off",
"when",
":tr",
";",
"page_width",
"-",
"reg_crop",
"-",
"reg_off",
"when",
":br",
";",
"page_width",
"-",
"reg_crop",
"-",
"reg_off",
"when",
":bl",
";",
"reg_off",
"end",
"end"
]
| iterationless x registration | [
"iterationless",
"x",
"registration"
]
| 63acbe762b09e4cda92f5d8dad41ac5735279724 | https://github.com/giuseb/mork/blob/63acbe762b09e4cda92f5d8dad41ac5735279724/lib/mork/grid_omr.rb#L72-L79 | train |
giuseb/mork | lib/mork/grid_pdf.rb | Mork.GridPDF.qnum_xy | def qnum_xy(q)
[
item_x(q).mm - qnum_width - qnum_margin,
item_y(q).mm
]
end | ruby | def qnum_xy(q)
[
item_x(q).mm - qnum_width - qnum_margin,
item_y(q).mm
]
end | [
"def",
"qnum_xy",
"(",
"q",
")",
"[",
"item_x",
"(",
"q",
")",
".",
"mm",
"-",
"qnum_width",
"-",
"qnum_margin",
",",
"item_y",
"(",
"q",
")",
".",
"mm",
"]",
"end"
]
| Coordinates at which to place item numbers | [
"Coordinates",
"at",
"which",
"to",
"place",
"item",
"numbers"
]
| 63acbe762b09e4cda92f5d8dad41ac5735279724 | https://github.com/giuseb/mork/blob/63acbe762b09e4cda92f5d8dad41ac5735279724/lib/mork/grid_pdf.rb#L46-L51 | train |
giuseb/mork | lib/mork/sheet_omr.rb | Mork.SheetOMR.marked_letters | def marked_letters
return if not_registered
marked_choices.map do |q|
q.map { |cho| (65+cho).chr }
end
end | ruby | def marked_letters
return if not_registered
marked_choices.map do |q|
q.map { |cho| (65+cho).chr }
end
end | [
"def",
"marked_letters",
"return",
"if",
"not_registered",
"marked_choices",
".",
"map",
"do",
"|",
"q",
"|",
"q",
".",
"map",
"{",
"|",
"cho",
"|",
"(",
"65",
"+",
"cho",
")",
".",
"chr",
"}",
"end",
"end"
]
| The set of letters marked on the response sheet. At this time, only the
latin sequence 'A, B, C...' is supported.
@return [Array] an array of arrays of 1-character strings; each element
contains the list of letters marked for the corresponding question. | [
"The",
"set",
"of",
"letters",
"marked",
"on",
"the",
"response",
"sheet",
".",
"At",
"this",
"time",
"only",
"the",
"latin",
"sequence",
"A",
"B",
"C",
"...",
"is",
"supported",
"."
]
| 63acbe762b09e4cda92f5d8dad41ac5735279724 | https://github.com/giuseb/mork/blob/63acbe762b09e4cda92f5d8dad41ac5735279724/lib/mork/sheet_omr.rb#L129-L134 | train |
sikachu/sprockets-redirect | lib/sprockets/redirect.rb | Sprockets.Redirect.redirect_to_digest_version | def redirect_to_digest_version(env)
url = URI(computed_asset_host || @request.url)
url.path = "#{@prefix}/#{digest_path}"
headers = { 'Location' => url.to_s,
'Content-Type' => Rack::Mime.mime_type(::File.extname(digest_path)),
'Pragma' => 'no-cache',
'Cache-Control' => 'no-cache; max-age=0' }
[self.class.redirect_status, headers, [redirect_message(url.to_s)]]
end | ruby | def redirect_to_digest_version(env)
url = URI(computed_asset_host || @request.url)
url.path = "#{@prefix}/#{digest_path}"
headers = { 'Location' => url.to_s,
'Content-Type' => Rack::Mime.mime_type(::File.extname(digest_path)),
'Pragma' => 'no-cache',
'Cache-Control' => 'no-cache; max-age=0' }
[self.class.redirect_status, headers, [redirect_message(url.to_s)]]
end | [
"def",
"redirect_to_digest_version",
"(",
"env",
")",
"url",
"=",
"URI",
"(",
"computed_asset_host",
"||",
"@request",
".",
"url",
")",
"url",
".",
"path",
"=",
"\"#{@prefix}/#{digest_path}\"",
"headers",
"=",
"{",
"'Location'",
"=>",
"url",
".",
"to_s",
",",
"'Content-Type'",
"=>",
"Rack",
"::",
"Mime",
".",
"mime_type",
"(",
"::",
"File",
".",
"extname",
"(",
"digest_path",
")",
")",
",",
"'Pragma'",
"=>",
"'no-cache'",
",",
"'Cache-Control'",
"=>",
"'no-cache; max-age=0'",
"}",
"[",
"self",
".",
"class",
".",
"redirect_status",
",",
"headers",
",",
"[",
"redirect_message",
"(",
"url",
".",
"to_s",
")",
"]",
"]",
"end"
]
| Sends a redirect header back to browser | [
"Sends",
"a",
"redirect",
"header",
"back",
"to",
"browser"
]
| e6d1f175d73ed0e63ac8350fc84017b70e05bfaa | https://github.com/sikachu/sprockets-redirect/blob/e6d1f175d73ed0e63ac8350fc84017b70e05bfaa/lib/sprockets/redirect.rb#L80-L90 | train |
giuseb/mork | lib/mork/mimage.rb | Mork.Mimage.register | def register
each_corner { |c| @rm[c] = rm_centroid_on c }
@rm.all? { |k,v| v[:status] == :ok }
end | ruby | def register
each_corner { |c| @rm[c] = rm_centroid_on c }
@rm.all? { |k,v| v[:status] == :ok }
end | [
"def",
"register",
"each_corner",
"{",
"|",
"c",
"|",
"@rm",
"[",
"c",
"]",
"=",
"rm_centroid_on",
"c",
"}",
"@rm",
".",
"all?",
"{",
"|",
"k",
",",
"v",
"|",
"v",
"[",
":status",
"]",
"==",
":ok",
"}",
"end"
]
| find the XY coordinates of the 4 registration marks,
plus the stdev of the search area as quality control | [
"find",
"the",
"XY",
"coordinates",
"of",
"the",
"4",
"registration",
"marks",
"plus",
"the",
"stdev",
"of",
"the",
"search",
"area",
"as",
"quality",
"control"
]
| 63acbe762b09e4cda92f5d8dad41ac5735279724 | https://github.com/giuseb/mork/blob/63acbe762b09e4cda92f5d8dad41ac5735279724/lib/mork/mimage.rb#L160-L163 | train |
giuseb/mork | lib/mork/mimage.rb | Mork.Mimage.rm_centroid_on | def rm_centroid_on(corner)
c = @grom.rm_crop_area(corner)
p = @mack.rm_patch(c, @grom.rm_blur, @grom.rm_dilate)
# byebug
n = NPatch.new(p, c.w, c.h)
cx, cy, sd = n.centroid
st = (cx < 2) or (cy < 2) or (cy > c.h-2) or (cx > c.w-2)
status = st ? :edgy : :ok
return {x: cx+c.x, y: cy+c.y, sd: sd, status: status}
end | ruby | def rm_centroid_on(corner)
c = @grom.rm_crop_area(corner)
p = @mack.rm_patch(c, @grom.rm_blur, @grom.rm_dilate)
# byebug
n = NPatch.new(p, c.w, c.h)
cx, cy, sd = n.centroid
st = (cx < 2) or (cy < 2) or (cy > c.h-2) or (cx > c.w-2)
status = st ? :edgy : :ok
return {x: cx+c.x, y: cy+c.y, sd: sd, status: status}
end | [
"def",
"rm_centroid_on",
"(",
"corner",
")",
"c",
"=",
"@grom",
".",
"rm_crop_area",
"(",
"corner",
")",
"p",
"=",
"@mack",
".",
"rm_patch",
"(",
"c",
",",
"@grom",
".",
"rm_blur",
",",
"@grom",
".",
"rm_dilate",
")",
"n",
"=",
"NPatch",
".",
"new",
"(",
"p",
",",
"c",
".",
"w",
",",
"c",
".",
"h",
")",
"cx",
",",
"cy",
",",
"sd",
"=",
"n",
".",
"centroid",
"st",
"=",
"(",
"cx",
"<",
"2",
")",
"or",
"(",
"cy",
"<",
"2",
")",
"or",
"(",
"cy",
">",
"c",
".",
"h",
"-",
"2",
")",
"or",
"(",
"cx",
">",
"c",
".",
"w",
"-",
"2",
")",
"status",
"=",
"st",
"?",
":edgy",
":",
":ok",
"return",
"{",
"x",
":",
"cx",
"+",
"c",
".",
"x",
",",
"y",
":",
"cy",
"+",
"c",
".",
"y",
",",
"sd",
":",
"sd",
",",
"status",
":",
"status",
"}",
"end"
]
| returns the centroid of the dark region within the given area
in the XY coordinates of the entire image | [
"returns",
"the",
"centroid",
"of",
"the",
"dark",
"region",
"within",
"the",
"given",
"area",
"in",
"the",
"XY",
"coordinates",
"of",
"the",
"entire",
"image"
]
| 63acbe762b09e4cda92f5d8dad41ac5735279724 | https://github.com/giuseb/mork/blob/63acbe762b09e4cda92f5d8dad41ac5735279724/lib/mork/mimage.rb#L167-L176 | train |
rails-engine/exception-track | lib/exception_notifier/exception_track_notifier.rb | ExceptionNotifier.ExceptionTrackNotifier.headers_for_env | def headers_for_env(env)
return "" if env.blank?
parameters = filter_parameters(env)
headers = []
headers << "Method: #{env['REQUEST_METHOD']}"
headers << "URL: #{env['REQUEST_URI']}"
if env['REQUEST_METHOD'].downcase != "get"
headers << "Parameters:\n#{pretty_hash(parameters.except(:controller, :action), 13)}"
end
headers << "Controller: #{parameters['controller']}##{parameters['action']}"
headers << "RequestId: #{env['action_dispatch.request_id']}"
headers << "User-Agent: #{env['HTTP_USER_AGENT']}"
headers << "Remote IP: #{env['REMOTE_ADDR']}"
headers << "Language: #{env['HTTP_ACCEPT_LANGUAGE']}"
headers << "Server: #{Socket.gethostname}"
headers << "Process: #{$PROCESS_ID}"
headers.join("\n")
end | ruby | def headers_for_env(env)
return "" if env.blank?
parameters = filter_parameters(env)
headers = []
headers << "Method: #{env['REQUEST_METHOD']}"
headers << "URL: #{env['REQUEST_URI']}"
if env['REQUEST_METHOD'].downcase != "get"
headers << "Parameters:\n#{pretty_hash(parameters.except(:controller, :action), 13)}"
end
headers << "Controller: #{parameters['controller']}##{parameters['action']}"
headers << "RequestId: #{env['action_dispatch.request_id']}"
headers << "User-Agent: #{env['HTTP_USER_AGENT']}"
headers << "Remote IP: #{env['REMOTE_ADDR']}"
headers << "Language: #{env['HTTP_ACCEPT_LANGUAGE']}"
headers << "Server: #{Socket.gethostname}"
headers << "Process: #{$PROCESS_ID}"
headers.join("\n")
end | [
"def",
"headers_for_env",
"(",
"env",
")",
"return",
"\"\"",
"if",
"env",
".",
"blank?",
"parameters",
"=",
"filter_parameters",
"(",
"env",
")",
"headers",
"=",
"[",
"]",
"headers",
"<<",
"\"Method: #{env['REQUEST_METHOD']}\"",
"headers",
"<<",
"\"URL: #{env['REQUEST_URI']}\"",
"if",
"env",
"[",
"'REQUEST_METHOD'",
"]",
".",
"downcase",
"!=",
"\"get\"",
"headers",
"<<",
"\"Parameters:\\n#{pretty_hash(parameters.except(:controller, :action), 13)}\"",
"end",
"headers",
"<<",
"\"Controller: #{parameters['controller']}##{parameters['action']}\"",
"headers",
"<<",
"\"RequestId: #{env['action_dispatch.request_id']}\"",
"headers",
"<<",
"\"User-Agent: #{env['HTTP_USER_AGENT']}\"",
"headers",
"<<",
"\"Remote IP: #{env['REMOTE_ADDR']}\"",
"headers",
"<<",
"\"Language: #{env['HTTP_ACCEPT_LANGUAGE']}\"",
"headers",
"<<",
"\"Server: #{Socket.gethostname}\"",
"headers",
"<<",
"\"Process: #{$PROCESS_ID}\"",
"headers",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
]
| Log Request headers from Rack env | [
"Log",
"Request",
"headers",
"from",
"Rack",
"env"
]
| 7b9a506b95f745e895e623d923d6d23817bc26f1 | https://github.com/rails-engine/exception-track/blob/7b9a506b95f745e895e623d923d6d23817bc26f1/lib/exception_notifier/exception_track_notifier.rb#L38-L58 | train |
dkubb/yardstick | lib/yardstick/rule_config.rb | Yardstick.RuleConfig.exclude? | def exclude?(path)
exclude.include?(path) ||
exclude.include?(path.split(METHOD_SEPARATOR).first)
end | ruby | def exclude?(path)
exclude.include?(path) ||
exclude.include?(path.split(METHOD_SEPARATOR).first)
end | [
"def",
"exclude?",
"(",
"path",
")",
"exclude",
".",
"include?",
"(",
"path",
")",
"||",
"exclude",
".",
"include?",
"(",
"path",
".",
"split",
"(",
"METHOD_SEPARATOR",
")",
".",
"first",
")",
"end"
]
| Checks if given path is in exclude list
If exact match fails then checks if the method class is in the exclude
list.
@param [String] path
document path
@return [Boolean]
true if path is in the exclude list
@api private | [
"Checks",
"if",
"given",
"path",
"is",
"in",
"exclude",
"list"
]
| 6dcc0139eca3b6bfbdfd6722c77937142e6ed1b9 | https://github.com/dkubb/yardstick/blob/6dcc0139eca3b6bfbdfd6722c77937142e6ed1b9/lib/yardstick/rule_config.rb#L52-L55 | train |
dkubb/yardstick | lib/yardstick/document_set.rb | Yardstick.DocumentSet.measure | def measure(config)
reduce(MeasurementSet.new) do |set, document|
set.merge(Document.measure(document, config))
end
end | ruby | def measure(config)
reduce(MeasurementSet.new) do |set, document|
set.merge(Document.measure(document, config))
end
end | [
"def",
"measure",
"(",
"config",
")",
"reduce",
"(",
"MeasurementSet",
".",
"new",
")",
"do",
"|",
"set",
",",
"document",
"|",
"set",
".",
"merge",
"(",
"Document",
".",
"measure",
"(",
"document",
",",
"config",
")",
")",
"end",
"end"
]
| Measure documents using given config
@return [Yardstick::MeasurementSet]
a collection of measurements
@api private | [
"Measure",
"documents",
"using",
"given",
"config"
]
| 6dcc0139eca3b6bfbdfd6722c77937142e6ed1b9 | https://github.com/dkubb/yardstick/blob/6dcc0139eca3b6bfbdfd6722c77937142e6ed1b9/lib/yardstick/document_set.rb#L12-L16 | train |
dkubb/yardstick | lib/yardstick/config.rb | Yardstick.Config.for_rule | def for_rule(rule_class)
key = rule_class.to_s[NAMESPACE_PREFIX.length..-1]
if key
RuleConfig.new(@rules.fetch(key.to_sym, {}))
else
fail InvalidRule, "every rule must begin with #{NAMESPACE_PREFIX}"
end
end | ruby | def for_rule(rule_class)
key = rule_class.to_s[NAMESPACE_PREFIX.length..-1]
if key
RuleConfig.new(@rules.fetch(key.to_sym, {}))
else
fail InvalidRule, "every rule must begin with #{NAMESPACE_PREFIX}"
end
end | [
"def",
"for_rule",
"(",
"rule_class",
")",
"key",
"=",
"rule_class",
".",
"to_s",
"[",
"NAMESPACE_PREFIX",
".",
"length",
"..",
"-",
"1",
"]",
"if",
"key",
"RuleConfig",
".",
"new",
"(",
"@rules",
".",
"fetch",
"(",
"key",
".",
"to_sym",
",",
"{",
"}",
")",
")",
"else",
"fail",
"InvalidRule",
",",
"\"every rule must begin with #{NAMESPACE_PREFIX}\"",
"end",
"end"
]
| Initializes new config
@param [Hash] options
optional configuration
@yieldparam [Yardstick::Config] config
the config object
@return [Yardstick::Config]
@api private
Return config for given rule
@param [Class] rule_class
@return [RuleConfig]
@api private | [
"Initializes",
"new",
"config"
]
| 6dcc0139eca3b6bfbdfd6722c77937142e6ed1b9 | https://github.com/dkubb/yardstick/blob/6dcc0139eca3b6bfbdfd6722c77937142e6ed1b9/lib/yardstick/config.rb#L119-L127 | train |
dkubb/yardstick | lib/yardstick/config.rb | Yardstick.Config.defaults= | def defaults=(options)
@threshold = options.fetch(:threshold, 100)
@verbose = options.fetch(:verbose, true)
@path = options.fetch(:path, 'lib/**/*.rb')
@require_exact_threshold = options.fetch(:require_exact_threshold, true)
@rules = options.fetch(:rules, {})
self.output = 'measurements/report.txt'
end | ruby | def defaults=(options)
@threshold = options.fetch(:threshold, 100)
@verbose = options.fetch(:verbose, true)
@path = options.fetch(:path, 'lib/**/*.rb')
@require_exact_threshold = options.fetch(:require_exact_threshold, true)
@rules = options.fetch(:rules, {})
self.output = 'measurements/report.txt'
end | [
"def",
"defaults",
"=",
"(",
"options",
")",
"@threshold",
"=",
"options",
".",
"fetch",
"(",
":threshold",
",",
"100",
")",
"@verbose",
"=",
"options",
".",
"fetch",
"(",
":verbose",
",",
"true",
")",
"@path",
"=",
"options",
".",
"fetch",
"(",
":path",
",",
"'lib/**/*.rb'",
")",
"@require_exact_threshold",
"=",
"options",
".",
"fetch",
"(",
":require_exact_threshold",
",",
"true",
")",
"@rules",
"=",
"options",
".",
"fetch",
"(",
":rules",
",",
"{",
"}",
")",
"self",
".",
"output",
"=",
"'measurements/report.txt'",
"end"
]
| Sets default options
@param [Hash] options
optional configuration
@return [undefined]
@api private | [
"Sets",
"default",
"options"
]
| 6dcc0139eca3b6bfbdfd6722c77937142e6ed1b9 | https://github.com/dkubb/yardstick/blob/6dcc0139eca3b6bfbdfd6722c77937142e6ed1b9/lib/yardstick/config.rb#L169-L176 | train |
clarete/s3sync | lib/s3sync/sync.rb | S3Sync.Node.compare_small_comparators | def compare_small_comparators(other)
return true if @size > SMALL_FILE || other.size > SMALL_FILE
return true if small_comparator.nil? || other.small_comparator.nil?
small_comparator.call == other.small_comparator.call
end | ruby | def compare_small_comparators(other)
return true if @size > SMALL_FILE || other.size > SMALL_FILE
return true if small_comparator.nil? || other.small_comparator.nil?
small_comparator.call == other.small_comparator.call
end | [
"def",
"compare_small_comparators",
"(",
"other",
")",
"return",
"true",
"if",
"@size",
">",
"SMALL_FILE",
"||",
"other",
".",
"size",
">",
"SMALL_FILE",
"return",
"true",
"if",
"small_comparator",
".",
"nil?",
"||",
"other",
".",
"small_comparator",
".",
"nil?",
"small_comparator",
".",
"call",
"==",
"other",
".",
"small_comparator",
".",
"call",
"end"
]
| If files are small and both nodes have a comparator, we can call an extra
provided block to verify equality. This allows | [
"If",
"files",
"are",
"small",
"and",
"both",
"nodes",
"have",
"a",
"comparator",
"we",
"can",
"call",
"an",
"extra",
"provided",
"block",
"to",
"verify",
"equality",
".",
"This",
"allows"
]
| b690957f6bb4299bca3224258855f1694406aab3 | https://github.com/clarete/s3sync/blob/b690957f6bb4299bca3224258855f1694406aab3/lib/s3sync/sync.rb#L102-L107 | train |
acatighera/statistics | lib/statistics.rb | Statistics.HasStats.define_calculated_statistic | def define_calculated_statistic(name, &block)
method_name = name.to_s.gsub(" ", "").underscore + "_stat"
@statistics ||= {}
@statistics[name] = method_name
(class<<self; self; end).instance_eval do
define_method(method_name) do |filters|
@filters = filters
yield
end
end
end | ruby | def define_calculated_statistic(name, &block)
method_name = name.to_s.gsub(" ", "").underscore + "_stat"
@statistics ||= {}
@statistics[name] = method_name
(class<<self; self; end).instance_eval do
define_method(method_name) do |filters|
@filters = filters
yield
end
end
end | [
"def",
"define_calculated_statistic",
"(",
"name",
",",
"&",
"block",
")",
"method_name",
"=",
"name",
".",
"to_s",
".",
"gsub",
"(",
"\" \"",
",",
"\"\"",
")",
".",
"underscore",
"+",
"\"_stat\"",
"@statistics",
"||=",
"{",
"}",
"@statistics",
"[",
"name",
"]",
"=",
"method_name",
"(",
"class",
"<<",
"self",
";",
"self",
";",
"end",
")",
".",
"instance_eval",
"do",
"define_method",
"(",
"method_name",
")",
"do",
"|",
"filters",
"|",
"@filters",
"=",
"filters",
"yield",
"end",
"end",
"end"
]
| Defines a statistic using a block that has access to all other defined statistics
EXAMPLE:
class MockModel < ActiveRecord::Base
define_statistic "Basic Count", :count => :all
define_statistic "Basic Sum", :sum => :all, :column_name => 'amount'
define_calculated_statistic "Total Profit"
defined_stats('Basic Sum') * defined_stats('Basic Count')
end | [
"Defines",
"a",
"statistic",
"using",
"a",
"block",
"that",
"has",
"access",
"to",
"all",
"other",
"defined",
"statistics"
]
| 33699ccb3aaccd78506b910e56145911323419a5 | https://github.com/acatighera/statistics/blob/33699ccb3aaccd78506b910e56145911323419a5/lib/statistics.rb#L105-L117 | train |
acatighera/statistics | lib/statistics.rb | Statistics.HasStats.statistics | def statistics(filters = {}, except = nil)
(@statistics || {}).inject({}) do |stats_hash, stat|
stats_hash[stat.first] = send(stat.last, filters) if stat.last != except
stats_hash
end
end | ruby | def statistics(filters = {}, except = nil)
(@statistics || {}).inject({}) do |stats_hash, stat|
stats_hash[stat.first] = send(stat.last, filters) if stat.last != except
stats_hash
end
end | [
"def",
"statistics",
"(",
"filters",
"=",
"{",
"}",
",",
"except",
"=",
"nil",
")",
"(",
"@statistics",
"||",
"{",
"}",
")",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"stats_hash",
",",
"stat",
"|",
"stats_hash",
"[",
"stat",
".",
"first",
"]",
"=",
"send",
"(",
"stat",
".",
"last",
",",
"filters",
")",
"if",
"stat",
".",
"last",
"!=",
"except",
"stats_hash",
"end",
"end"
]
| Calculates all the statistics defined for this AR class and returns a hash with the values.
There is an optional parameter that is a hash of all values you want to filter by.
EXAMPLE:
MockModel.statistics
MockModel.statistics(:user_type => 'registered', :user_status => 'active') | [
"Calculates",
"all",
"the",
"statistics",
"defined",
"for",
"this",
"AR",
"class",
"and",
"returns",
"a",
"hash",
"with",
"the",
"values",
".",
"There",
"is",
"an",
"optional",
"parameter",
"that",
"is",
"a",
"hash",
"of",
"all",
"values",
"you",
"want",
"to",
"filter",
"by",
"."
]
| 33699ccb3aaccd78506b910e56145911323419a5 | https://github.com/acatighera/statistics/blob/33699ccb3aaccd78506b910e56145911323419a5/lib/statistics.rb#L130-L135 | train |
fcheung/keychain | lib/keychain/keychain.rb | Keychain.Keychain.add_to_search_list | def add_to_search_list
list = FFI::MemoryPointer.new(:pointer)
status = Sec.SecKeychainCopySearchList(list)
Sec.check_osstatus(status)
ruby_list = CF::Base.typecast(list.read_pointer).release_on_gc.to_ruby
ruby_list << self unless ruby_list.include?(self)
status = Sec.SecKeychainSetSearchList(CF::Array.immutable(ruby_list))
Sec.check_osstatus(status)
self
end | ruby | def add_to_search_list
list = FFI::MemoryPointer.new(:pointer)
status = Sec.SecKeychainCopySearchList(list)
Sec.check_osstatus(status)
ruby_list = CF::Base.typecast(list.read_pointer).release_on_gc.to_ruby
ruby_list << self unless ruby_list.include?(self)
status = Sec.SecKeychainSetSearchList(CF::Array.immutable(ruby_list))
Sec.check_osstatus(status)
self
end | [
"def",
"add_to_search_list",
"list",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":pointer",
")",
"status",
"=",
"Sec",
".",
"SecKeychainCopySearchList",
"(",
"list",
")",
"Sec",
".",
"check_osstatus",
"(",
"status",
")",
"ruby_list",
"=",
"CF",
"::",
"Base",
".",
"typecast",
"(",
"list",
".",
"read_pointer",
")",
".",
"release_on_gc",
".",
"to_ruby",
"ruby_list",
"<<",
"self",
"unless",
"ruby_list",
".",
"include?",
"(",
"self",
")",
"status",
"=",
"Sec",
".",
"SecKeychainSetSearchList",
"(",
"CF",
"::",
"Array",
".",
"immutable",
"(",
"ruby_list",
")",
")",
"Sec",
".",
"check_osstatus",
"(",
"status",
")",
"self",
"end"
]
| Add the keychain to the default searchlist | [
"Add",
"the",
"keychain",
"to",
"the",
"default",
"searchlist"
]
| f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b | https://github.com/fcheung/keychain/blob/f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b/lib/keychain/keychain.rb#L60-L69 | train |
fcheung/keychain | lib/keychain/keychain.rb | Keychain.Keychain.import | def import(input, app_list=[])
input = input.read if input.is_a? IO
# Create array of TrustedApplication objects
trusted_apps = get_trusted_apps(app_list)
# Create an Access object
access_buffer = FFI::MemoryPointer.new(:pointer)
status = Sec.SecAccessCreate(path.to_cf, trusted_apps, access_buffer)
Sec.check_osstatus status
access = CF::Base.typecast(access_buffer.read_pointer)
key_params = Sec::SecItemImportExportKeyParameters.new
key_params[:accessRef] = access
# Import item to the keychain
cf_data = CF::Data.from_string(input).release_on_gc
cf_array = FFI::MemoryPointer.new(:pointer)
status = Sec.SecItemImport(cf_data, nil, :kSecFormatUnknown, :kSecItemTypeUnknown, :kSecItemPemArmour, key_params, self, cf_array)
access.release
Sec.check_osstatus status
item_array = CF::Base.typecast(cf_array.read_pointer).release_on_gc
item_array.to_ruby
end | ruby | def import(input, app_list=[])
input = input.read if input.is_a? IO
# Create array of TrustedApplication objects
trusted_apps = get_trusted_apps(app_list)
# Create an Access object
access_buffer = FFI::MemoryPointer.new(:pointer)
status = Sec.SecAccessCreate(path.to_cf, trusted_apps, access_buffer)
Sec.check_osstatus status
access = CF::Base.typecast(access_buffer.read_pointer)
key_params = Sec::SecItemImportExportKeyParameters.new
key_params[:accessRef] = access
# Import item to the keychain
cf_data = CF::Data.from_string(input).release_on_gc
cf_array = FFI::MemoryPointer.new(:pointer)
status = Sec.SecItemImport(cf_data, nil, :kSecFormatUnknown, :kSecItemTypeUnknown, :kSecItemPemArmour, key_params, self, cf_array)
access.release
Sec.check_osstatus status
item_array = CF::Base.typecast(cf_array.read_pointer).release_on_gc
item_array.to_ruby
end | [
"def",
"import",
"(",
"input",
",",
"app_list",
"=",
"[",
"]",
")",
"input",
"=",
"input",
".",
"read",
"if",
"input",
".",
"is_a?",
"IO",
"trusted_apps",
"=",
"get_trusted_apps",
"(",
"app_list",
")",
"access_buffer",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":pointer",
")",
"status",
"=",
"Sec",
".",
"SecAccessCreate",
"(",
"path",
".",
"to_cf",
",",
"trusted_apps",
",",
"access_buffer",
")",
"Sec",
".",
"check_osstatus",
"status",
"access",
"=",
"CF",
"::",
"Base",
".",
"typecast",
"(",
"access_buffer",
".",
"read_pointer",
")",
"key_params",
"=",
"Sec",
"::",
"SecItemImportExportKeyParameters",
".",
"new",
"key_params",
"[",
":accessRef",
"]",
"=",
"access",
"cf_data",
"=",
"CF",
"::",
"Data",
".",
"from_string",
"(",
"input",
")",
".",
"release_on_gc",
"cf_array",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":pointer",
")",
"status",
"=",
"Sec",
".",
"SecItemImport",
"(",
"cf_data",
",",
"nil",
",",
":kSecFormatUnknown",
",",
":kSecItemTypeUnknown",
",",
":kSecItemPemArmour",
",",
"key_params",
",",
"self",
",",
"cf_array",
")",
"access",
".",
"release",
"Sec",
".",
"check_osstatus",
"status",
"item_array",
"=",
"CF",
"::",
"Base",
".",
"typecast",
"(",
"cf_array",
".",
"read_pointer",
")",
".",
"release_on_gc",
"item_array",
".",
"to_ruby",
"end"
]
| Imports item from string or file to this keychain
@param [IO, String] input IO object or String with raw data to import
@param [Array <String>] app_list List of applications which will be
permitted to access imported items
@return [Array <SecKeychainItem>] List of imported keychain objects,
each of which may be a SecCertificate, SecKey, or SecIdentity instance | [
"Imports",
"item",
"from",
"string",
"or",
"file",
"to",
"this",
"keychain"
]
| f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b | https://github.com/fcheung/keychain/blob/f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b/lib/keychain/keychain.rb#L123-L147 | train |
fcheung/keychain | lib/keychain/keychain.rb | Keychain.Keychain.path | def path
out_buffer = FFI::MemoryPointer.new(:uchar, 2048)
io_size = FFI::MemoryPointer.new(:uint32)
io_size.put_uint32(0, out_buffer.size)
status = Sec.SecKeychainGetPath(self,io_size, out_buffer)
Sec.check_osstatus(status)
out_buffer.read_string(io_size.get_uint32(0)).force_encoding(Encoding::UTF_8)
end | ruby | def path
out_buffer = FFI::MemoryPointer.new(:uchar, 2048)
io_size = FFI::MemoryPointer.new(:uint32)
io_size.put_uint32(0, out_buffer.size)
status = Sec.SecKeychainGetPath(self,io_size, out_buffer)
Sec.check_osstatus(status)
out_buffer.read_string(io_size.get_uint32(0)).force_encoding(Encoding::UTF_8)
end | [
"def",
"path",
"out_buffer",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":uchar",
",",
"2048",
")",
"io_size",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":uint32",
")",
"io_size",
".",
"put_uint32",
"(",
"0",
",",
"out_buffer",
".",
"size",
")",
"status",
"=",
"Sec",
".",
"SecKeychainGetPath",
"(",
"self",
",",
"io_size",
",",
"out_buffer",
")",
"Sec",
".",
"check_osstatus",
"(",
"status",
")",
"out_buffer",
".",
"read_string",
"(",
"io_size",
".",
"get_uint32",
"(",
"0",
")",
")",
".",
"force_encoding",
"(",
"Encoding",
"::",
"UTF_8",
")",
"end"
]
| Returns the path at which the keychain is stored
See https://developer.apple.com/library/mac/documentation/security/Reference/keychainservices/Reference/reference.html#//apple_ref/c/func/SecKeychainGetPath
@return [String] path to the keychain file | [
"Returns",
"the",
"path",
"at",
"which",
"the",
"keychain",
"is",
"stored"
]
| f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b | https://github.com/fcheung/keychain/blob/f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b/lib/keychain/keychain.rb#L170-L179 | train |
fcheung/keychain | lib/keychain/keychain.rb | Keychain.Keychain.unlock! | def unlock! password=nil
if password
password = password.encode(Encoding::UTF_8)
status = Sec.SecKeychainUnlock self, password.bytesize, password, 1
else
status = Sec.SecKeychainUnlock self, 0, nil, 0
end
Sec.check_osstatus status
end | ruby | def unlock! password=nil
if password
password = password.encode(Encoding::UTF_8)
status = Sec.SecKeychainUnlock self, password.bytesize, password, 1
else
status = Sec.SecKeychainUnlock self, 0, nil, 0
end
Sec.check_osstatus status
end | [
"def",
"unlock!",
"password",
"=",
"nil",
"if",
"password",
"password",
"=",
"password",
".",
"encode",
"(",
"Encoding",
"::",
"UTF_8",
")",
"status",
"=",
"Sec",
".",
"SecKeychainUnlock",
"self",
",",
"password",
".",
"bytesize",
",",
"password",
",",
"1",
"else",
"status",
"=",
"Sec",
".",
"SecKeychainUnlock",
"self",
",",
"0",
",",
"nil",
",",
"0",
"end",
"Sec",
".",
"check_osstatus",
"status",
"end"
]
| Unlocks the keychain
@param [optional, String] password the password to unlock the keychain with. If no password is supplied the keychain will prompt the user for a password | [
"Unlocks",
"the",
"keychain"
]
| f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b | https://github.com/fcheung/keychain/blob/f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b/lib/keychain/keychain.rb#L191-L199 | train |
fcheung/keychain | lib/keychain/item.rb | Keychain.Item.password | def password
return @unsaved_password if @unsaved_password
out_buffer = FFI::MemoryPointer.new(:pointer)
status = Sec.SecItemCopyMatching({Sec::Query::ITEM_LIST => CF::Array.immutable([self]),
Sec::Query::SEARCH_LIST => [self.keychain],
Sec::Query::CLASS => self.klass,
Sec::Query::RETURN_DATA => true}.to_cf, out_buffer)
Sec.check_osstatus(status)
CF::Base.typecast(out_buffer.read_pointer).release_on_gc.to_s
end | ruby | def password
return @unsaved_password if @unsaved_password
out_buffer = FFI::MemoryPointer.new(:pointer)
status = Sec.SecItemCopyMatching({Sec::Query::ITEM_LIST => CF::Array.immutable([self]),
Sec::Query::SEARCH_LIST => [self.keychain],
Sec::Query::CLASS => self.klass,
Sec::Query::RETURN_DATA => true}.to_cf, out_buffer)
Sec.check_osstatus(status)
CF::Base.typecast(out_buffer.read_pointer).release_on_gc.to_s
end | [
"def",
"password",
"return",
"@unsaved_password",
"if",
"@unsaved_password",
"out_buffer",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":pointer",
")",
"status",
"=",
"Sec",
".",
"SecItemCopyMatching",
"(",
"{",
"Sec",
"::",
"Query",
"::",
"ITEM_LIST",
"=>",
"CF",
"::",
"Array",
".",
"immutable",
"(",
"[",
"self",
"]",
")",
",",
"Sec",
"::",
"Query",
"::",
"SEARCH_LIST",
"=>",
"[",
"self",
".",
"keychain",
"]",
",",
"Sec",
"::",
"Query",
"::",
"CLASS",
"=>",
"self",
".",
"klass",
",",
"Sec",
"::",
"Query",
"::",
"RETURN_DATA",
"=>",
"true",
"}",
".",
"to_cf",
",",
"out_buffer",
")",
"Sec",
".",
"check_osstatus",
"(",
"status",
")",
"CF",
"::",
"Base",
".",
"typecast",
"(",
"out_buffer",
".",
"read_pointer",
")",
".",
"release_on_gc",
".",
"to_s",
"end"
]
| Fetches the password data associated with the item. This may cause the user to be asked for access
@return [String] The password data, an ASCII_8BIT encoded string | [
"Fetches",
"the",
"password",
"data",
"associated",
"with",
"the",
"item",
".",
"This",
"may",
"cause",
"the",
"user",
"to",
"be",
"asked",
"for",
"access"
]
| f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b | https://github.com/fcheung/keychain/blob/f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b/lib/keychain/item.rb#L80-L89 | train |
fcheung/keychain | lib/keychain/item.rb | Keychain.Item.save! | def save!(options={})
if persisted?
cf_dict = update
else
cf_dict = create(options)
self.ptr = cf_dict[Sec::Value::REF].to_ptr
self.retain.release_on_gc
end
@unsaved_password = nil
update_self_from_dictionary(cf_dict)
cf_dict.release
self
end | ruby | def save!(options={})
if persisted?
cf_dict = update
else
cf_dict = create(options)
self.ptr = cf_dict[Sec::Value::REF].to_ptr
self.retain.release_on_gc
end
@unsaved_password = nil
update_self_from_dictionary(cf_dict)
cf_dict.release
self
end | [
"def",
"save!",
"(",
"options",
"=",
"{",
"}",
")",
"if",
"persisted?",
"cf_dict",
"=",
"update",
"else",
"cf_dict",
"=",
"create",
"(",
"options",
")",
"self",
".",
"ptr",
"=",
"cf_dict",
"[",
"Sec",
"::",
"Value",
"::",
"REF",
"]",
".",
"to_ptr",
"self",
".",
"retain",
".",
"release_on_gc",
"end",
"@unsaved_password",
"=",
"nil",
"update_self_from_dictionary",
"(",
"cf_dict",
")",
"cf_dict",
".",
"release",
"self",
"end"
]
| Attempts to update the keychain with any changes made to the item
or saves a previously unpersisted item
@param [optional, Hash] options extra options when saving the item
@option options [Keychain::Keychain] :keychain when saving an unsaved item, they keychain to save it in
@return [Keychain::Item] returns the item | [
"Attempts",
"to",
"update",
"the",
"keychain",
"with",
"any",
"changes",
"made",
"to",
"the",
"item",
"or",
"saves",
"a",
"previously",
"unpersisted",
"item"
]
| f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b | https://github.com/fcheung/keychain/blob/f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b/lib/keychain/item.rb#L96-L108 | train |
devrandom/net_dav | lib/net/dav.rb | Net.DAV.propfind | def propfind(path,*options)
headers = {'Depth' => '1'}
if(options[0] == :acl)
body = '<?xml version="1.0" encoding="utf-8" ?><D:propfind xmlns:D="DAV:"><D:prop><D:owner/>' +
'<D:supported-privilege-set/><D:current-user-privilege-set/><D:acl/></D:prop></D:propfind>'
else
body = options[0]
end
if(!body)
body = '<?xml version="1.0" encoding="utf-8"?><DAV:propfind xmlns:DAV="DAV:"><DAV:allprop/></DAV:propfind>'
end
res = @handler.request(:propfind, path, body, headers.merge(@headers))
Nokogiri::XML.parse(res.body)
end | ruby | def propfind(path,*options)
headers = {'Depth' => '1'}
if(options[0] == :acl)
body = '<?xml version="1.0" encoding="utf-8" ?><D:propfind xmlns:D="DAV:"><D:prop><D:owner/>' +
'<D:supported-privilege-set/><D:current-user-privilege-set/><D:acl/></D:prop></D:propfind>'
else
body = options[0]
end
if(!body)
body = '<?xml version="1.0" encoding="utf-8"?><DAV:propfind xmlns:DAV="DAV:"><DAV:allprop/></DAV:propfind>'
end
res = @handler.request(:propfind, path, body, headers.merge(@headers))
Nokogiri::XML.parse(res.body)
end | [
"def",
"propfind",
"(",
"path",
",",
"*",
"options",
")",
"headers",
"=",
"{",
"'Depth'",
"=>",
"'1'",
"}",
"if",
"(",
"options",
"[",
"0",
"]",
"==",
":acl",
")",
"body",
"=",
"'<?xml version=\"1.0\" encoding=\"utf-8\" ?><D:propfind xmlns:D=\"DAV:\"><D:prop><D:owner/>'",
"+",
"'<D:supported-privilege-set/><D:current-user-privilege-set/><D:acl/></D:prop></D:propfind>'",
"else",
"body",
"=",
"options",
"[",
"0",
"]",
"end",
"if",
"(",
"!",
"body",
")",
"body",
"=",
"'<?xml version=\"1.0\" encoding=\"utf-8\"?><DAV:propfind xmlns:DAV=\"DAV:\"><DAV:allprop/></DAV:propfind>'",
"end",
"res",
"=",
"@handler",
".",
"request",
"(",
":propfind",
",",
"path",
",",
"body",
",",
"headers",
".",
"merge",
"(",
"@headers",
")",
")",
"Nokogiri",
"::",
"XML",
".",
"parse",
"(",
"res",
".",
"body",
")",
"end"
]
| Perform a PROPFIND request
Example:
Basic propfind:
properties = propfind('/path/')
Get ACL for resource:
properties = propfind('/path/', :acl)
Custom propfind:
properties = propfind('/path/', '<?xml version="1.0" encoding="utf-8"?>...')
See http://webdav.org/specs/rfc3744.html#rfc.section.5.9 for more on
how to retrieve access control properties. | [
"Perform",
"a",
"PROPFIND",
"request"
]
| dd41e51dee05d81f7eb4256dce3f263f8d12e44e | https://github.com/devrandom/net_dav/blob/dd41e51dee05d81f7eb4256dce3f263f8d12e44e/lib/net/dav.rb#L487-L500 | train |
devrandom/net_dav | lib/net/dav.rb | Net.DAV.cd | def cd(url)
new_uri = @uri.merge(url)
if new_uri.host != @uri.host || new_uri.port != @uri.port || new_uri.scheme != @uri.scheme
raise Exception , "uri must have same scheme, host and port"
end
@uri = new_uri
end | ruby | def cd(url)
new_uri = @uri.merge(url)
if new_uri.host != @uri.host || new_uri.port != @uri.port || new_uri.scheme != @uri.scheme
raise Exception , "uri must have same scheme, host and port"
end
@uri = new_uri
end | [
"def",
"cd",
"(",
"url",
")",
"new_uri",
"=",
"@uri",
".",
"merge",
"(",
"url",
")",
"if",
"new_uri",
".",
"host",
"!=",
"@uri",
".",
"host",
"||",
"new_uri",
".",
"port",
"!=",
"@uri",
".",
"port",
"||",
"new_uri",
".",
"scheme",
"!=",
"@uri",
".",
"scheme",
"raise",
"Exception",
",",
"\"uri must have same scheme, host and port\"",
"end",
"@uri",
"=",
"new_uri",
"end"
]
| Change the base URL for use in handling relative paths | [
"Change",
"the",
"base",
"URL",
"for",
"use",
"in",
"handling",
"relative",
"paths"
]
| dd41e51dee05d81f7eb4256dce3f263f8d12e44e | https://github.com/devrandom/net_dav/blob/dd41e51dee05d81f7eb4256dce3f263f8d12e44e/lib/net/dav.rb#L583-L589 | train |
devrandom/net_dav | lib/net/dav.rb | Net.DAV.get | def get(path, &block)
path = @uri.merge(path).path
body = @handler.request_returning_body(:get, path, @headers, &block)
body
end | ruby | def get(path, &block)
path = @uri.merge(path).path
body = @handler.request_returning_body(:get, path, @headers, &block)
body
end | [
"def",
"get",
"(",
"path",
",",
"&",
"block",
")",
"path",
"=",
"@uri",
".",
"merge",
"(",
"path",
")",
".",
"path",
"body",
"=",
"@handler",
".",
"request_returning_body",
"(",
":get",
",",
"path",
",",
"@headers",
",",
"&",
"block",
")",
"body",
"end"
]
| Get the content of a resource as a string
If called with a block, yields each fragment of the
entity body in turn as a string as it is read from
the socket. Note that in this case, the returned response
object will *not* contain a (meaningful) body. | [
"Get",
"the",
"content",
"of",
"a",
"resource",
"as",
"a",
"string"
]
| dd41e51dee05d81f7eb4256dce3f263f8d12e44e | https://github.com/devrandom/net_dav/blob/dd41e51dee05d81f7eb4256dce3f263f8d12e44e/lib/net/dav.rb#L598-L602 | train |
devrandom/net_dav | lib/net/dav.rb | Net.DAV.put | def put(path, stream, length)
path = @uri.merge(path).path
res = @handler.request_sending_stream(:put, path, stream, length, @headers)
res.body
end | ruby | def put(path, stream, length)
path = @uri.merge(path).path
res = @handler.request_sending_stream(:put, path, stream, length, @headers)
res.body
end | [
"def",
"put",
"(",
"path",
",",
"stream",
",",
"length",
")",
"path",
"=",
"@uri",
".",
"merge",
"(",
"path",
")",
".",
"path",
"res",
"=",
"@handler",
".",
"request_sending_stream",
"(",
":put",
",",
"path",
",",
"stream",
",",
"length",
",",
"@headers",
")",
"res",
".",
"body",
"end"
]
| Stores the content of a stream to a URL
Example:
File.open(file, "r") do |stream|
dav.put(url.path, stream, File.size(file))
end | [
"Stores",
"the",
"content",
"of",
"a",
"stream",
"to",
"a",
"URL"
]
| dd41e51dee05d81f7eb4256dce3f263f8d12e44e | https://github.com/devrandom/net_dav/blob/dd41e51dee05d81f7eb4256dce3f263f8d12e44e/lib/net/dav.rb#L610-L614 | train |
devrandom/net_dav | lib/net/dav.rb | Net.DAV.put_string | def put_string(path, str)
path = @uri.merge(path).path
res = @handler.request_sending_body(:put, path, str, @headers)
res.body
end | ruby | def put_string(path, str)
path = @uri.merge(path).path
res = @handler.request_sending_body(:put, path, str, @headers)
res.body
end | [
"def",
"put_string",
"(",
"path",
",",
"str",
")",
"path",
"=",
"@uri",
".",
"merge",
"(",
"path",
")",
".",
"path",
"res",
"=",
"@handler",
".",
"request_sending_body",
"(",
":put",
",",
"path",
",",
"str",
",",
"@headers",
")",
"res",
".",
"body",
"end"
]
| Stores the content of a string to a URL
Example:
dav.put(url.path, "hello world") | [
"Stores",
"the",
"content",
"of",
"a",
"string",
"to",
"a",
"URL"
]
| dd41e51dee05d81f7eb4256dce3f263f8d12e44e | https://github.com/devrandom/net_dav/blob/dd41e51dee05d81f7eb4256dce3f263f8d12e44e/lib/net/dav.rb#L621-L625 | train |
devrandom/net_dav | lib/net/dav.rb | Net.DAV.move | def move(path,destination)
path = @uri.merge(path).path
destination = @uri.merge(destination).to_s
headers = {'Destination' => destination}
res = @handler.request(:move, path, nil, headers.merge(@headers))
res.body
end | ruby | def move(path,destination)
path = @uri.merge(path).path
destination = @uri.merge(destination).to_s
headers = {'Destination' => destination}
res = @handler.request(:move, path, nil, headers.merge(@headers))
res.body
end | [
"def",
"move",
"(",
"path",
",",
"destination",
")",
"path",
"=",
"@uri",
".",
"merge",
"(",
"path",
")",
".",
"path",
"destination",
"=",
"@uri",
".",
"merge",
"(",
"destination",
")",
".",
"to_s",
"headers",
"=",
"{",
"'Destination'",
"=>",
"destination",
"}",
"res",
"=",
"@handler",
".",
"request",
"(",
":move",
",",
"path",
",",
"nil",
",",
"headers",
".",
"merge",
"(",
"@headers",
")",
")",
"res",
".",
"body",
"end"
]
| Send a move request to the server.
Example:
dav.move(original_path, new_path) | [
"Send",
"a",
"move",
"request",
"to",
"the",
"server",
"."
]
| dd41e51dee05d81f7eb4256dce3f263f8d12e44e | https://github.com/devrandom/net_dav/blob/dd41e51dee05d81f7eb4256dce3f263f8d12e44e/lib/net/dav.rb#L641-L647 | train |
devrandom/net_dav | lib/net/dav.rb | Net.DAV.proppatch | def proppatch(path, xml_snippet)
path = @uri.merge(path).path
headers = {'Depth' => '1'}
body = '<?xml version="1.0"?>' +
'<d:propertyupdate xmlns:d="DAV:">' +
xml_snippet +
'</d:propertyupdate>'
res = @handler.request(:proppatch, path, body, headers.merge(@headers))
Nokogiri::XML.parse(res.body)
end | ruby | def proppatch(path, xml_snippet)
path = @uri.merge(path).path
headers = {'Depth' => '1'}
body = '<?xml version="1.0"?>' +
'<d:propertyupdate xmlns:d="DAV:">' +
xml_snippet +
'</d:propertyupdate>'
res = @handler.request(:proppatch, path, body, headers.merge(@headers))
Nokogiri::XML.parse(res.body)
end | [
"def",
"proppatch",
"(",
"path",
",",
"xml_snippet",
")",
"path",
"=",
"@uri",
".",
"merge",
"(",
"path",
")",
".",
"path",
"headers",
"=",
"{",
"'Depth'",
"=>",
"'1'",
"}",
"body",
"=",
"'<?xml version=\"1.0\"?>'",
"+",
"'<d:propertyupdate xmlns:d=\"DAV:\">'",
"+",
"xml_snippet",
"+",
"'</d:propertyupdate>'",
"res",
"=",
"@handler",
".",
"request",
"(",
":proppatch",
",",
"path",
",",
"body",
",",
"headers",
".",
"merge",
"(",
"@headers",
")",
")",
"Nokogiri",
"::",
"XML",
".",
"parse",
"(",
"res",
".",
"body",
")",
"end"
]
| Do a proppatch request to the server to
update properties on resources or collections.
Example:
dav.proppatch(uri.path,
"<d:set><d:prop>" +
"<d:creationdate>#{new_date}</d:creationdate>" +
"</d:set></d:prop>" +
) | [
"Do",
"a",
"proppatch",
"request",
"to",
"the",
"server",
"to",
"update",
"properties",
"on",
"resources",
"or",
"collections",
"."
]
| dd41e51dee05d81f7eb4256dce3f263f8d12e44e | https://github.com/devrandom/net_dav/blob/dd41e51dee05d81f7eb4256dce3f263f8d12e44e/lib/net/dav.rb#L670-L679 | train |
devrandom/net_dav | lib/net/dav.rb | Net.DAV.unlock | def unlock(path, locktoken)
headers = {'Lock-Token' => '<'+locktoken+'>'}
path = @uri.merge(path).path
res = @handler.request(:unlock, path, nil, headers.merge(@headers))
end | ruby | def unlock(path, locktoken)
headers = {'Lock-Token' => '<'+locktoken+'>'}
path = @uri.merge(path).path
res = @handler.request(:unlock, path, nil, headers.merge(@headers))
end | [
"def",
"unlock",
"(",
"path",
",",
"locktoken",
")",
"headers",
"=",
"{",
"'Lock-Token'",
"=>",
"'<'",
"+",
"locktoken",
"+",
"'>'",
"}",
"path",
"=",
"@uri",
".",
"merge",
"(",
"path",
")",
".",
"path",
"res",
"=",
"@handler",
".",
"request",
"(",
":unlock",
",",
"path",
",",
"nil",
",",
"headers",
".",
"merge",
"(",
"@headers",
")",
")",
"end"
]
| Send an unlock request to the server
Example:
dav.unlock(uri.path, "opaquelocktoken:eee47ade-09ac-626b-02f7-e354175d984e") | [
"Send",
"an",
"unlock",
"request",
"to",
"the",
"server"
]
| dd41e51dee05d81f7eb4256dce3f263f8d12e44e | https://github.com/devrandom/net_dav/blob/dd41e51dee05d81f7eb4256dce3f263f8d12e44e/lib/net/dav.rb#L702-L706 | train |
devrandom/net_dav | lib/net/dav.rb | Net.DAV.exists? | def exists?(path)
path = @uri.merge(path).path
headers = {'Depth' => '1'}
body = '<?xml version="1.0" encoding="utf-8"?><DAV:propfind xmlns:DAV="DAV:"><DAV:allprop/></DAV:propfind>'
begin
res = @handler.request(:propfind, path, body, headers.merge(@headers))
rescue
return false
end
return (res.is_a? Net::HTTPSuccess)
end | ruby | def exists?(path)
path = @uri.merge(path).path
headers = {'Depth' => '1'}
body = '<?xml version="1.0" encoding="utf-8"?><DAV:propfind xmlns:DAV="DAV:"><DAV:allprop/></DAV:propfind>'
begin
res = @handler.request(:propfind, path, body, headers.merge(@headers))
rescue
return false
end
return (res.is_a? Net::HTTPSuccess)
end | [
"def",
"exists?",
"(",
"path",
")",
"path",
"=",
"@uri",
".",
"merge",
"(",
"path",
")",
".",
"path",
"headers",
"=",
"{",
"'Depth'",
"=>",
"'1'",
"}",
"body",
"=",
"'<?xml version=\"1.0\" encoding=\"utf-8\"?><DAV:propfind xmlns:DAV=\"DAV:\"><DAV:allprop/></DAV:propfind>'",
"begin",
"res",
"=",
"@handler",
".",
"request",
"(",
":propfind",
",",
"path",
",",
"body",
",",
"headers",
".",
"merge",
"(",
"@headers",
")",
")",
"rescue",
"return",
"false",
"end",
"return",
"(",
"res",
".",
"is_a?",
"Net",
"::",
"HTTPSuccess",
")",
"end"
]
| Returns true if resource exists on server.
Example:
dav.exists?('https://www.example.com/collection/') => true
dav.exists?('/collection/') => true | [
"Returns",
"true",
"if",
"resource",
"exists",
"on",
"server",
"."
]
| dd41e51dee05d81f7eb4256dce3f263f8d12e44e | https://github.com/devrandom/net_dav/blob/dd41e51dee05d81f7eb4256dce3f263f8d12e44e/lib/net/dav.rb#L713-L723 | train |
fcheung/keychain | lib/keychain/sec.rb | Sec.Base.keychain | def keychain
out = FFI::MemoryPointer.new :pointer
status = Sec.SecKeychainItemCopyKeychain(self,out)
Sec.check_osstatus(status)
CF::Base.new(out.read_pointer).release_on_gc
end | ruby | def keychain
out = FFI::MemoryPointer.new :pointer
status = Sec.SecKeychainItemCopyKeychain(self,out)
Sec.check_osstatus(status)
CF::Base.new(out.read_pointer).release_on_gc
end | [
"def",
"keychain",
"out",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
":pointer",
"status",
"=",
"Sec",
".",
"SecKeychainItemCopyKeychain",
"(",
"self",
",",
"out",
")",
"Sec",
".",
"check_osstatus",
"(",
"status",
")",
"CF",
"::",
"Base",
".",
"new",
"(",
"out",
".",
"read_pointer",
")",
".",
"release_on_gc",
"end"
]
| Returns the keychain the item is in
@return [Keychain::Keychain] | [
"Returns",
"the",
"keychain",
"the",
"item",
"is",
"in"
]
| f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b | https://github.com/fcheung/keychain/blob/f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b/lib/keychain/sec.rb#L150-L155 | train |
pmahoney/process_shared | lib/process_shared/mutex.rb | ProcessShared.Mutex.sleep | def sleep(timeout = nil)
unlock
begin
timeout ? Kernel.sleep(timeout) : Kernel.sleep
ensure
lock
end
end | ruby | def sleep(timeout = nil)
unlock
begin
timeout ? Kernel.sleep(timeout) : Kernel.sleep
ensure
lock
end
end | [
"def",
"sleep",
"(",
"timeout",
"=",
"nil",
")",
"unlock",
"begin",
"timeout",
"?",
"Kernel",
".",
"sleep",
"(",
"timeout",
")",
":",
"Kernel",
".",
"sleep",
"ensure",
"lock",
"end",
"end"
]
| Releases the lock and sleeps timeout seconds if it is given and
non-nil or forever.
@return [Numeric] | [
"Releases",
"the",
"lock",
"and",
"sleeps",
"timeout",
"seconds",
"if",
"it",
"is",
"given",
"and",
"non",
"-",
"nil",
"or",
"forever",
"."
]
| 9ef0acb09335c44ac5133bfac566786b038fcd90 | https://github.com/pmahoney/process_shared/blob/9ef0acb09335c44ac5133bfac566786b038fcd90/lib/process_shared/mutex.rb#L52-L59 | train |
pmahoney/process_shared | lib/mach/port.rb | Mach.Port.insert_right | def insert_right(right, opts = {})
ipc_space = opts[:ipc_space] || @ipc_space
port_name = opts[:port_name] || @port
mach_port_insert_right(ipc_space.to_i, port_name.to_i, @port, right)
end | ruby | def insert_right(right, opts = {})
ipc_space = opts[:ipc_space] || @ipc_space
port_name = opts[:port_name] || @port
mach_port_insert_right(ipc_space.to_i, port_name.to_i, @port, right)
end | [
"def",
"insert_right",
"(",
"right",
",",
"opts",
"=",
"{",
"}",
")",
"ipc_space",
"=",
"opts",
"[",
":ipc_space",
"]",
"||",
"@ipc_space",
"port_name",
"=",
"opts",
"[",
":port_name",
"]",
"||",
"@port",
"mach_port_insert_right",
"(",
"ipc_space",
".",
"to_i",
",",
"port_name",
".",
"to_i",
",",
"@port",
",",
"right",
")",
"end"
]
| Insert +right+ into another ipc space. The current task must
have sufficient rights to insert the requested right.
@param [MsgType] right
@param [Hash] opts
@option opts [Port,Integer] :ipc_space the space (task port) into which
+right+ will be inserted; defaults to this port's ipc_space
@option opts [Port,Integer] :port the name the port right should
have in :ipc_space; defaults to the same name as this port | [
"Insert",
"+",
"right",
"+",
"into",
"another",
"ipc",
"space",
".",
"The",
"current",
"task",
"must",
"have",
"sufficient",
"rights",
"to",
"insert",
"the",
"requested",
"right",
"."
]
| 9ef0acb09335c44ac5133bfac566786b038fcd90 | https://github.com/pmahoney/process_shared/blob/9ef0acb09335c44ac5133bfac566786b038fcd90/lib/mach/port.rb#L88-L93 | train |
pmahoney/process_shared | lib/mach/port.rb | Mach.Port.send_right | def send_right(right, remote_port)
msg = SendRightMsg.new
msg[:header].tap do |h|
h[:remote_port] = remote_port.to_i
h[:local_port] = PORT_NULL
h[:bits] =
(MsgType[right] | (0 << 8)) | 0x80000000 # MACH_MSGH_BITS_COMPLEX
h[:size] = 40 # msg.size
end
msg[:body][:descriptor_count] = 1
msg[:port].tap do |p|
p[:name] = port
p[:disposition] = MsgType[right]
p[:type] = 0 # MSG_PORT_DESCRIPTOR;
end
mach_msg_send msg
end | ruby | def send_right(right, remote_port)
msg = SendRightMsg.new
msg[:header].tap do |h|
h[:remote_port] = remote_port.to_i
h[:local_port] = PORT_NULL
h[:bits] =
(MsgType[right] | (0 << 8)) | 0x80000000 # MACH_MSGH_BITS_COMPLEX
h[:size] = 40 # msg.size
end
msg[:body][:descriptor_count] = 1
msg[:port].tap do |p|
p[:name] = port
p[:disposition] = MsgType[right]
p[:type] = 0 # MSG_PORT_DESCRIPTOR;
end
mach_msg_send msg
end | [
"def",
"send_right",
"(",
"right",
",",
"remote_port",
")",
"msg",
"=",
"SendRightMsg",
".",
"new",
"msg",
"[",
":header",
"]",
".",
"tap",
"do",
"|",
"h",
"|",
"h",
"[",
":remote_port",
"]",
"=",
"remote_port",
".",
"to_i",
"h",
"[",
":local_port",
"]",
"=",
"PORT_NULL",
"h",
"[",
":bits",
"]",
"=",
"(",
"MsgType",
"[",
"right",
"]",
"|",
"(",
"0",
"<<",
"8",
")",
")",
"|",
"0x80000000",
"h",
"[",
":size",
"]",
"=",
"40",
"end",
"msg",
"[",
":body",
"]",
"[",
":descriptor_count",
"]",
"=",
"1",
"msg",
"[",
":port",
"]",
".",
"tap",
"do",
"|",
"p",
"|",
"p",
"[",
":name",
"]",
"=",
"port",
"p",
"[",
":disposition",
"]",
"=",
"MsgType",
"[",
"right",
"]",
"p",
"[",
":type",
"]",
"=",
"0",
"end",
"mach_msg_send",
"msg",
"end"
]
| Send +right+ on this Port to +remote_port+. The current task
must already have the requisite rights allowing it to send
+right+. | [
"Send",
"+",
"right",
"+",
"on",
"this",
"Port",
"to",
"+",
"remote_port",
"+",
".",
"The",
"current",
"task",
"must",
"already",
"have",
"the",
"requisite",
"rights",
"allowing",
"it",
"to",
"send",
"+",
"right",
"+",
"."
]
| 9ef0acb09335c44ac5133bfac566786b038fcd90 | https://github.com/pmahoney/process_shared/blob/9ef0acb09335c44ac5133bfac566786b038fcd90/lib/mach/port.rb#L98-L118 | train |
pmahoney/process_shared | lib/mach/port.rb | Mach.Port.receive_right | def receive_right
msg = ReceiveRightMsg.new
mach_msg(msg,
2, # RCV_MSG,
0,
msg.size,
port,
MSG_TIMEOUT_NONE,
PORT_NULL)
self.class.new :port => msg[:port][:name]
end | ruby | def receive_right
msg = ReceiveRightMsg.new
mach_msg(msg,
2, # RCV_MSG,
0,
msg.size,
port,
MSG_TIMEOUT_NONE,
PORT_NULL)
self.class.new :port => msg[:port][:name]
end | [
"def",
"receive_right",
"msg",
"=",
"ReceiveRightMsg",
".",
"new",
"mach_msg",
"(",
"msg",
",",
"2",
",",
"0",
",",
"msg",
".",
"size",
",",
"port",
",",
"MSG_TIMEOUT_NONE",
",",
"PORT_NULL",
")",
"self",
".",
"class",
".",
"new",
":port",
"=>",
"msg",
"[",
":port",
"]",
"[",
":name",
"]",
"end"
]
| Create a new Port by receiving a port right message on this
port. | [
"Create",
"a",
"new",
"Port",
"by",
"receiving",
"a",
"port",
"right",
"message",
"on",
"this",
"port",
"."
]
| 9ef0acb09335c44ac5133bfac566786b038fcd90 | https://github.com/pmahoney/process_shared/blob/9ef0acb09335c44ac5133bfac566786b038fcd90/lib/mach/port.rb#L129-L141 | train |
pmahoney/process_shared | lib/mach/semaphore.rb | Mach.Semaphore.destroy | def destroy(opts = {})
task = opts[:task] || ipc_space || mach_task_self
semaphore_destroy(task.to_i, port)
end | ruby | def destroy(opts = {})
task = opts[:task] || ipc_space || mach_task_self
semaphore_destroy(task.to_i, port)
end | [
"def",
"destroy",
"(",
"opts",
"=",
"{",
"}",
")",
"task",
"=",
"opts",
"[",
":task",
"]",
"||",
"ipc_space",
"||",
"mach_task_self",
"semaphore_destroy",
"(",
"task",
".",
"to_i",
",",
"port",
")",
"end"
]
| Create a new Semaphore.
@param [Hash] opts
@option opts [Integer] :value the initial value of the
semaphore; defaults to 1
@option opts [Integer] :task the Mach task that owns the
semaphore (defaults to Mach.task_self)
@options opts [Integer] :sync_policy the sync policy for this
semaphore (defaults to SyncPolicy::FIFO)
@options opts [Integer] :port existing port to wrap with a
Semaphore object; otherwise a new semaphore is created
@return [Integer] a semaphore port name
Destroy a Semaphore.
@param [Hash] opts
@option opts [Integer] :task the Mach task that owns the
semaphore (defaults to the owning task) | [
"Create",
"a",
"new",
"Semaphore",
"."
]
| 9ef0acb09335c44ac5133bfac566786b038fcd90 | https://github.com/pmahoney/process_shared/blob/9ef0acb09335c44ac5133bfac566786b038fcd90/lib/mach/semaphore.rb#L49-L52 | train |
jdan/rubycards | lib/rubycards/card.rb | RubyCards.Card.suit | def suit(glyph = false)
case @suit
when 1
glyph ? CLUB.black.bold : 'Clubs'
when 2
glyph ? DIAMOND.red : 'Diamonds'
when 3
glyph ? HEART.red : 'Hearts'
when 4
glyph ? SPADE.black.bold : 'Spades'
end
end | ruby | def suit(glyph = false)
case @suit
when 1
glyph ? CLUB.black.bold : 'Clubs'
when 2
glyph ? DIAMOND.red : 'Diamonds'
when 3
glyph ? HEART.red : 'Hearts'
when 4
glyph ? SPADE.black.bold : 'Spades'
end
end | [
"def",
"suit",
"(",
"glyph",
"=",
"false",
")",
"case",
"@suit",
"when",
"1",
"glyph",
"?",
"CLUB",
".",
"black",
".",
"bold",
":",
"'Clubs'",
"when",
"2",
"glyph",
"?",
"DIAMOND",
".",
"red",
":",
"'Diamonds'",
"when",
"3",
"glyph",
"?",
"HEART",
".",
"red",
":",
"'Hearts'",
"when",
"4",
"glyph",
"?",
"SPADE",
".",
"black",
".",
"bold",
":",
"'Spades'",
"end",
"end"
]
| Returns the suit of the card.
@param glyph [Boolean] Optional setting to draw a unicode glyph in place
of a word
@return [String] The string (of glyph) representation of the card's suit | [
"Returns",
"the",
"suit",
"of",
"the",
"card",
"."
]
| e6e7fda255451844681d43b5a9da2ab2393da052 | https://github.com/jdan/rubycards/blob/e6e7fda255451844681d43b5a9da2ab2393da052/lib/rubycards/card.rb#L45-L56 | train |
enkessler/cql | lib/cql/filters.rb | CQL.TagFilter.has_tags? | def has_tags?(object, target_tags)
target_tags.all? { |target_tag|
tags = object.tags
tags = tags.collect { |tag| tag.name } unless Gem.loaded_specs['cuke_modeler'].version.version[/^0/]
tags.include?(target_tag)
}
end | ruby | def has_tags?(object, target_tags)
target_tags.all? { |target_tag|
tags = object.tags
tags = tags.collect { |tag| tag.name } unless Gem.loaded_specs['cuke_modeler'].version.version[/^0/]
tags.include?(target_tag)
}
end | [
"def",
"has_tags?",
"(",
"object",
",",
"target_tags",
")",
"target_tags",
".",
"all?",
"{",
"|",
"target_tag",
"|",
"tags",
"=",
"object",
".",
"tags",
"tags",
"=",
"tags",
".",
"collect",
"{",
"|",
"tag",
"|",
"tag",
".",
"name",
"}",
"unless",
"Gem",
".",
"loaded_specs",
"[",
"'cuke_modeler'",
"]",
".",
"version",
".",
"version",
"[",
"/",
"/",
"]",
"tags",
".",
"include?",
"(",
"target_tag",
")",
"}",
"end"
]
| Creates a new filter
Returns whether or not the object has the target tags | [
"Creates",
"a",
"new",
"filter",
"Returns",
"whether",
"or",
"not",
"the",
"object",
"has",
"the",
"target",
"tags"
]
| 4c0b264db64dc02e436e490b9a6286d52d7ab515 | https://github.com/enkessler/cql/blob/4c0b264db64dc02e436e490b9a6286d52d7ab515/lib/cql/filters.rb#L15-L21 | train |
enkessler/cql | lib/cql/filters.rb | CQL.ContentMatchFilter.content_match? | def content_match?(content)
if pattern.is_a?(String)
content.any? { |thing| thing == pattern }
else
content.any? { |thing| thing =~ pattern }
end
end | ruby | def content_match?(content)
if pattern.is_a?(String)
content.any? { |thing| thing == pattern }
else
content.any? { |thing| thing =~ pattern }
end
end | [
"def",
"content_match?",
"(",
"content",
")",
"if",
"pattern",
".",
"is_a?",
"(",
"String",
")",
"content",
".",
"any?",
"{",
"|",
"thing",
"|",
"thing",
"==",
"pattern",
"}",
"else",
"content",
".",
"any?",
"{",
"|",
"thing",
"|",
"thing",
"=~",
"pattern",
"}",
"end",
"end"
]
| Creates a new filter
Returns whether or not the content matches the pattern | [
"Creates",
"a",
"new",
"filter",
"Returns",
"whether",
"or",
"not",
"the",
"content",
"matches",
"the",
"pattern"
]
| 4c0b264db64dc02e436e490b9a6286d52d7ab515 | https://github.com/enkessler/cql/blob/4c0b264db64dc02e436e490b9a6286d52d7ab515/lib/cql/filters.rb#L46-L52 | train |
enkessler/cql | lib/cql/filters.rb | CQL.TypeCountFilter.execute | def execute(input, negate)
method = negate ? :reject : :select
input.send(method) do |object|
type_count(object).send(comparison.operator, comparison.amount)
end
end | ruby | def execute(input, negate)
method = negate ? :reject : :select
input.send(method) do |object|
type_count(object).send(comparison.operator, comparison.amount)
end
end | [
"def",
"execute",
"(",
"input",
",",
"negate",
")",
"method",
"=",
"negate",
"?",
":reject",
":",
":select",
"input",
".",
"send",
"(",
"method",
")",
"do",
"|",
"object",
"|",
"type_count",
"(",
"object",
")",
".",
"send",
"(",
"comparison",
".",
"operator",
",",
"comparison",
".",
"amount",
")",
"end",
"end"
]
| Creates a new filter
Not a part of the public API. Subject to change at any time.
Filters the input models so that only the desired ones are returned | [
"Creates",
"a",
"new",
"filter",
"Not",
"a",
"part",
"of",
"the",
"public",
"API",
".",
"Subject",
"to",
"change",
"at",
"any",
"time",
".",
"Filters",
"the",
"input",
"models",
"so",
"that",
"only",
"the",
"desired",
"ones",
"are",
"returned"
]
| 4c0b264db64dc02e436e490b9a6286d52d7ab515 | https://github.com/enkessler/cql/blob/4c0b264db64dc02e436e490b9a6286d52d7ab515/lib/cql/filters.rb#L72-L78 | train |
datacite/bolognese | lib/bolognese/doi_utils.rb | Bolognese.DoiUtils.get_doi_ra | def get_doi_ra(doi)
prefix = validate_prefix(doi)
return nil if prefix.blank?
url = "https://doi.org/ra/#{prefix}"
result = Maremma.get(url)
result.body.dig("data", 0, "RA")
end | ruby | def get_doi_ra(doi)
prefix = validate_prefix(doi)
return nil if prefix.blank?
url = "https://doi.org/ra/#{prefix}"
result = Maremma.get(url)
result.body.dig("data", 0, "RA")
end | [
"def",
"get_doi_ra",
"(",
"doi",
")",
"prefix",
"=",
"validate_prefix",
"(",
"doi",
")",
"return",
"nil",
"if",
"prefix",
".",
"blank?",
"url",
"=",
"\"https://doi.org/ra/#{prefix}\"",
"result",
"=",
"Maremma",
".",
"get",
"(",
"url",
")",
"result",
".",
"body",
".",
"dig",
"(",
"\"data\"",
",",
"0",
",",
"\"RA\"",
")",
"end"
]
| get DOI registration agency | [
"get",
"DOI",
"registration",
"agency"
]
| 10b8666a6724c0a9508df4547a9f9213bf80b59c | https://github.com/datacite/bolognese/blob/10b8666a6724c0a9508df4547a9f9213bf80b59c/lib/bolognese/doi_utils.rb#L45-L53 | train |
davidesantangelo/emailhunter | lib/email_hunter/api.rb | EmailHunter.Api.search | def search(domain, params = {})
EmailHunter::Search.new(domain, self.key, params).hunt
end | ruby | def search(domain, params = {})
EmailHunter::Search.new(domain, self.key, params).hunt
end | [
"def",
"search",
"(",
"domain",
",",
"params",
"=",
"{",
"}",
")",
"EmailHunter",
"::",
"Search",
".",
"new",
"(",
"domain",
",",
"self",
".",
"key",
",",
"params",
")",
".",
"hunt",
"end"
]
| Domain search API | [
"Domain",
"search",
"API"
]
| cbb092e4acb57b8cb209119d103128c8833aac63 | https://github.com/davidesantangelo/emailhunter/blob/cbb092e4acb57b8cb209119d103128c8833aac63/lib/email_hunter/api.rb#L18-L20 | train |
davidesantangelo/emailhunter | lib/email_hunter/api.rb | EmailHunter.Api.finder | def finder(domain, first_name, last_name)
EmailHunter::Finder.new(domain, first_name, last_name, self.key).hunt
end | ruby | def finder(domain, first_name, last_name)
EmailHunter::Finder.new(domain, first_name, last_name, self.key).hunt
end | [
"def",
"finder",
"(",
"domain",
",",
"first_name",
",",
"last_name",
")",
"EmailHunter",
"::",
"Finder",
".",
"new",
"(",
"domain",
",",
"first_name",
",",
"last_name",
",",
"self",
".",
"key",
")",
".",
"hunt",
"end"
]
| Email Finder API | [
"Email",
"Finder",
"API"
]
| cbb092e4acb57b8cb209119d103128c8833aac63 | https://github.com/davidesantangelo/emailhunter/blob/cbb092e4acb57b8cb209119d103128c8833aac63/lib/email_hunter/api.rb#L33-L35 | train |
datacite/bolognese | lib/bolognese/metadata_utils.rb | Bolognese.MetadataUtils.raw | def raw
r = string.present? ? string.strip : nil
return r unless (from == "datacite" && r.present?)
doc = Nokogiri::XML(string, nil, 'UTF-8', &:noblanks)
node = doc.at_css("identifier")
node.content = doi.to_s.upcase if node.present? && doi.present?
doc.to_xml.strip
end | ruby | def raw
r = string.present? ? string.strip : nil
return r unless (from == "datacite" && r.present?)
doc = Nokogiri::XML(string, nil, 'UTF-8', &:noblanks)
node = doc.at_css("identifier")
node.content = doi.to_s.upcase if node.present? && doi.present?
doc.to_xml.strip
end | [
"def",
"raw",
"r",
"=",
"string",
".",
"present?",
"?",
"string",
".",
"strip",
":",
"nil",
"return",
"r",
"unless",
"(",
"from",
"==",
"\"datacite\"",
"&&",
"r",
".",
"present?",
")",
"doc",
"=",
"Nokogiri",
"::",
"XML",
"(",
"string",
",",
"nil",
",",
"'UTF-8'",
",",
"&",
":noblanks",
")",
"node",
"=",
"doc",
".",
"at_css",
"(",
"\"identifier\"",
")",
"node",
".",
"content",
"=",
"doi",
".",
"to_s",
".",
"upcase",
"if",
"node",
".",
"present?",
"&&",
"doi",
".",
"present?",
"doc",
".",
"to_xml",
".",
"strip",
"end"
]
| replace DOI in XML if provided in options | [
"replace",
"DOI",
"in",
"XML",
"if",
"provided",
"in",
"options"
]
| 10b8666a6724c0a9508df4547a9f9213bf80b59c | https://github.com/datacite/bolognese/blob/10b8666a6724c0a9508df4547a9f9213bf80b59c/lib/bolognese/metadata_utils.rb#L69-L77 | train |
datacite/bolognese | lib/bolognese/author_utils.rb | Bolognese.AuthorUtils.get_authors | def get_authors(authors)
Array.wrap(authors).map { |author| get_one_author(author) }.compact
end | ruby | def get_authors(authors)
Array.wrap(authors).map { |author| get_one_author(author) }.compact
end | [
"def",
"get_authors",
"(",
"authors",
")",
"Array",
".",
"wrap",
"(",
"authors",
")",
".",
"map",
"{",
"|",
"author",
"|",
"get_one_author",
"(",
"author",
")",
"}",
".",
"compact",
"end"
]
| parse array of author strings into CSL format | [
"parse",
"array",
"of",
"author",
"strings",
"into",
"CSL",
"format"
]
| 10b8666a6724c0a9508df4547a9f9213bf80b59c | https://github.com/datacite/bolognese/blob/10b8666a6724c0a9508df4547a9f9213bf80b59c/lib/bolognese/author_utils.rb#L116-L118 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.