repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
knaveofdiamonds/sequel_migration_builder | lib/sequel/migration_builder.rb | Sequel.MigrationBuilder.alter_tables | def alter_tables(current_table_names, tables)
each_table(current_table_names, tables) do |table_name, table, last_table|
hsh = table.dup
hsh[:columns] = hsh[:columns].map {|c| Schema::DbColumn.build_from_hash(c) }
operations = Schema::AlterTableOperations.
build(@db_tables[table_name], hsh, :immutable_columns => @immutable_columns)
unless operations.empty?
all_operations = if @separate_alter_table_statements
operations.map {|o| [o] }
else
[operations]
end
all_operations.each_with_index do |o, i|
alter_table_statement table_name, o
add_blank_line unless last_table && i + 1 == all_operations.size
end
end
end
end | ruby | def alter_tables(current_table_names, tables)
each_table(current_table_names, tables) do |table_name, table, last_table|
hsh = table.dup
hsh[:columns] = hsh[:columns].map {|c| Schema::DbColumn.build_from_hash(c) }
operations = Schema::AlterTableOperations.
build(@db_tables[table_name], hsh, :immutable_columns => @immutable_columns)
unless operations.empty?
all_operations = if @separate_alter_table_statements
operations.map {|o| [o] }
else
[operations]
end
all_operations.each_with_index do |o, i|
alter_table_statement table_name, o
add_blank_line unless last_table && i + 1 == all_operations.size
end
end
end
end | [
"def",
"alter_tables",
"(",
"current_table_names",
",",
"tables",
")",
"each_table",
"(",
"current_table_names",
",",
"tables",
")",
"do",
"|",
"table_name",
",",
"table",
",",
"last_table",
"|",
"hsh",
"=",
"table",
".",
"dup",
"hsh",
"[",
":columns",
"]",
... | Generates any alter table statements for current tables. | [
"Generates",
"any",
"alter",
"table",
"statements",
"for",
"current",
"tables",
"."
] | 8e640d1af39ccd83418ae408f62d68519363fa7b | https://github.com/knaveofdiamonds/sequel_migration_builder/blob/8e640d1af39ccd83418ae408f62d68519363fa7b/lib/sequel/migration_builder.rb#L77-L96 | valid |
knaveofdiamonds/sequel_migration_builder | lib/sequel/migration_builder.rb | Sequel.MigrationBuilder.alter_table_statement | def alter_table_statement(table_name, operations)
add_line "alter_table #{table_name.inspect} do"
indent do
operations.compact.each {|op| add_line op }
end
add_line "end"
end | ruby | def alter_table_statement(table_name, operations)
add_line "alter_table #{table_name.inspect} do"
indent do
operations.compact.each {|op| add_line op }
end
add_line "end"
end | [
"def",
"alter_table_statement",
"(",
"table_name",
",",
"operations",
")",
"add_line",
"\"alter_table #{table_name.inspect} do\"",
"indent",
"do",
"operations",
".",
"compact",
".",
"each",
"{",
"|",
"op",
"|",
"add_line",
"op",
"}",
"end",
"add_line",
"\"end\"",
... | Generates an individual alter table statement. | [
"Generates",
"an",
"individual",
"alter",
"table",
"statement",
"."
] | 8e640d1af39ccd83418ae408f62d68519363fa7b | https://github.com/knaveofdiamonds/sequel_migration_builder/blob/8e640d1af39ccd83418ae408f62d68519363fa7b/lib/sequel/migration_builder.rb#L100-L106 | valid |
knaveofdiamonds/sequel_migration_builder | lib/sequel/migration_builder.rb | Sequel.MigrationBuilder.create_table_statement | def create_table_statement(table_name, table)
normalize_primary_key(table)
add_line "create_table #{table_name.inspect}#{pretty_hash(table[:table_options])} do"
indent do
output_columns(table[:columns], table[:primary_key])
output_indexes(table[:indexes])
output_primary_key(table)
end
add_line "end"
end | ruby | def create_table_statement(table_name, table)
normalize_primary_key(table)
add_line "create_table #{table_name.inspect}#{pretty_hash(table[:table_options])} do"
indent do
output_columns(table[:columns], table[:primary_key])
output_indexes(table[:indexes])
output_primary_key(table)
end
add_line "end"
end | [
"def",
"create_table_statement",
"(",
"table_name",
",",
"table",
")",
"normalize_primary_key",
"(",
"table",
")",
"add_line",
"\"create_table #{table_name.inspect}#{pretty_hash(table[:table_options])} do\"",
"indent",
"do",
"output_columns",
"(",
"table",
"[",
":columns",
"]... | Generates an individual create_table statement. | [
"Generates",
"an",
"individual",
"create_table",
"statement",
"."
] | 8e640d1af39ccd83418ae408f62d68519363fa7b | https://github.com/knaveofdiamonds/sequel_migration_builder/blob/8e640d1af39ccd83418ae408f62d68519363fa7b/lib/sequel/migration_builder.rb#L110-L119 | valid |
machzqcq/saucelabs | lib/saucelabs/sauce_browser_factory.rb | SauceLabs.SauceBrowserFactory.watir_browser | def watir_browser(browser,browser_options)
target,options = browser_caps(browser,browser_options)
create_watir_browser(target,options)
end | ruby | def watir_browser(browser,browser_options)
target,options = browser_caps(browser,browser_options)
create_watir_browser(target,options)
end | [
"def",
"watir_browser",
"(",
"browser",
",",
"browser_options",
")",
"target",
",",
"options",
"=",
"browser_caps",
"(",
"browser",
",",
"browser_options",
")",
"create_watir_browser",
"(",
"target",
",",
"options",
")",
"end"
] | Creates a watir browser session and returns the browser object
@example
SauceLabs.watir_browser(browser = :chrome, browser_options = {})
@param [String] the browser string passed into the method
@param [Hash] the optional hash to specify browser options
@return [Object] browser session | [
"Creates",
"a",
"watir",
"browser",
"session",
"and",
"returns",
"the",
"browser",
"object"
] | fcdf933c83c6b8bd32773b571a1919c697d8ce53 | https://github.com/machzqcq/saucelabs/blob/fcdf933c83c6b8bd32773b571a1919c697d8ce53/lib/saucelabs/sauce_browser_factory.rb#L25-L28 | valid |
machzqcq/saucelabs | lib/saucelabs/sauce_browser_factory.rb | SauceLabs.SauceBrowserFactory.selenium_driver | def selenium_driver(browser,browser_options)
target,options = browser_caps(browser,browser_options)
create_selenium_driver(target,options)
end | ruby | def selenium_driver(browser,browser_options)
target,options = browser_caps(browser,browser_options)
create_selenium_driver(target,options)
end | [
"def",
"selenium_driver",
"(",
"browser",
",",
"browser_options",
")",
"target",
",",
"options",
"=",
"browser_caps",
"(",
"browser",
",",
"browser_options",
")",
"create_selenium_driver",
"(",
"target",
",",
"options",
")",
"end"
] | Creates a Selenium driver session and returns the driver object
@example
SauceLabs.selenium_driver(browser = :chrome, browser_options = {})
@param [String] the browser string passed into the method
@param [Hash] the optional hash to specify browser options
@return [Object] browser session | [
"Creates",
"a",
"Selenium",
"driver",
"session",
"and",
"returns",
"the",
"driver",
"object"
] | fcdf933c83c6b8bd32773b571a1919c697d8ce53 | https://github.com/machzqcq/saucelabs/blob/fcdf933c83c6b8bd32773b571a1919c697d8ce53/lib/saucelabs/sauce_browser_factory.rb#L40-L43 | valid |
machzqcq/saucelabs | lib/saucelabs/sauce_browser_factory.rb | SauceLabs.SauceBrowserFactory.browser_caps | def browser_caps(browser,browser_options)
target = (browser.to_sym if ENV['BROWSER'].nil? or ENV['browser'].empty?) || (ENV['BROWSER'].to_sym)
browser,version,platform,device = extract_values_from(target)
options = {}
options.merge! browser_options
caps = capabilities(browser,version,platform,device)
options[:url] = url if url
if options.include? :url
browser = :remote
options[:desired_capabilities] = caps
end
options[:http_client] = http_client if persistent_http or options.delete(:persistent_http)
return browser,options
end | ruby | def browser_caps(browser,browser_options)
target = (browser.to_sym if ENV['BROWSER'].nil? or ENV['browser'].empty?) || (ENV['BROWSER'].to_sym)
browser,version,platform,device = extract_values_from(target)
options = {}
options.merge! browser_options
caps = capabilities(browser,version,platform,device)
options[:url] = url if url
if options.include? :url
browser = :remote
options[:desired_capabilities] = caps
end
options[:http_client] = http_client if persistent_http or options.delete(:persistent_http)
return browser,options
end | [
"def",
"browser_caps",
"(",
"browser",
",",
"browser_options",
")",
"target",
"=",
"(",
"browser",
".",
"to_sym",
"if",
"ENV",
"[",
"'BROWSER'",
"]",
".",
"nil?",
"or",
"ENV",
"[",
"'browser'",
"]",
".",
"empty?",
")",
"||",
"(",
"ENV",
"[",
"'BROWSER'... | Returns the target and options including the capabilities
@param [String] the browser string passed into the method
@param [Hash] the optional hash to specify browser options
@return [Symbol,Hash] browser as symbol and options as Hash | [
"Returns",
"the",
"target",
"and",
"options",
"including",
"the",
"capabilities"
] | fcdf933c83c6b8bd32773b571a1919c697d8ce53 | https://github.com/machzqcq/saucelabs/blob/fcdf933c83c6b8bd32773b571a1919c697d8ce53/lib/saucelabs/sauce_browser_factory.rb#L81-L94 | valid |
machzqcq/saucelabs | lib/saucelabs/parsed_values.rb | SauceLabs.ParsedValues.extract_values_from | def extract_values_from(browser_string)
browser = extract_browser(browser_string).to_sym
version = extract_version(browser_string)
platform = extract_platform(browser_string)
device = extract_device(browser_string)
return browser,version,platform,device
end | ruby | def extract_values_from(browser_string)
browser = extract_browser(browser_string).to_sym
version = extract_version(browser_string)
platform = extract_platform(browser_string)
device = extract_device(browser_string)
return browser,version,platform,device
end | [
"def",
"extract_values_from",
"(",
"browser_string",
")",
"browser",
"=",
"extract_browser",
"(",
"browser_string",
")",
".",
"to_sym",
"version",
"=",
"extract_version",
"(",
"browser_string",
")",
"platform",
"=",
"extract_platform",
"(",
"browser_string",
")",
"d... | Extracts browser, version, platform, device from the browser string
@example
extract_values_from(:'safari5|linux|iphone') will extract
browser = safari
version=5
platform=Linux
device=iPhone
@param [String] the browser string passed into the method
@return [String,String,String,String] browser, version, platform and device | [
"Extracts",
"browser",
"version",
"platform",
"device",
"from",
"the",
"browser",
"string"
] | fcdf933c83c6b8bd32773b571a1919c697d8ce53 | https://github.com/machzqcq/saucelabs/blob/fcdf933c83c6b8bd32773b571a1919c697d8ce53/lib/saucelabs/parsed_values.rb#L17-L23 | valid |
machzqcq/saucelabs | lib/saucelabs/parsed_values.rb | SauceLabs.ParsedValues.extract_browser | def extract_browser(value)
browser = value.to_s.split(/\d+/)[0]
browser = browser.to_s.split('|')[0] if browser.to_s.include? '|'
browser
end | ruby | def extract_browser(value)
browser = value.to_s.split(/\d+/)[0]
browser = browser.to_s.split('|')[0] if browser.to_s.include? '|'
browser
end | [
"def",
"extract_browser",
"(",
"value",
")",
"browser",
"=",
"value",
".",
"to_s",
".",
"split",
"(",
"/",
"\\d",
"/",
")",
"[",
"0",
"]",
"browser",
"=",
"browser",
".",
"to_s",
".",
"split",
"(",
"'|'",
")",
"[",
"0",
"]",
"if",
"browser",
".",... | Extracts browser from browser string
@example
extract_browser(:'safari5|linux|iphone') will extract
browser = safari
@param [String] the browser string passed into the method
@return [String] the browser value | [
"Extracts",
"browser",
"from",
"browser",
"string"
] | fcdf933c83c6b8bd32773b571a1919c697d8ce53 | https://github.com/machzqcq/saucelabs/blob/fcdf933c83c6b8bd32773b571a1919c697d8ce53/lib/saucelabs/parsed_values.rb#L37-L41 | valid |
machzqcq/saucelabs | lib/saucelabs/parsed_values.rb | SauceLabs.ParsedValues.extract_version | def extract_version(value)
value = value.to_s.split('|')[0] if value.to_s.include? '|'
regexp_to_match = /\d{1,}/
if (not regexp_to_match.match(value).nil?)
version = regexp_to_match.match(value)[0]
else
version = ''
end
version
end | ruby | def extract_version(value)
value = value.to_s.split('|')[0] if value.to_s.include? '|'
regexp_to_match = /\d{1,}/
if (not regexp_to_match.match(value).nil?)
version = regexp_to_match.match(value)[0]
else
version = ''
end
version
end | [
"def",
"extract_version",
"(",
"value",
")",
"value",
"=",
"value",
".",
"to_s",
".",
"split",
"(",
"'|'",
")",
"[",
"0",
"]",
"if",
"value",
".",
"to_s",
".",
"include?",
"'|'",
"regexp_to_match",
"=",
"/",
"\\d",
"/",
"if",
"(",
"not",
"regexp_to_m... | Extracts version from browser string
@example
extract_version(:'safari5|linux|iphone') will extract
browser = safari
@param [String] the browser string passed into the method
@return [String] the version value | [
"Extracts",
"version",
"from",
"browser",
"string"
] | fcdf933c83c6b8bd32773b571a1919c697d8ce53 | https://github.com/machzqcq/saucelabs/blob/fcdf933c83c6b8bd32773b571a1919c697d8ce53/lib/saucelabs/parsed_values.rb#L53-L62 | valid |
machzqcq/saucelabs | lib/saucelabs/parsed_values.rb | SauceLabs.ParsedValues.extract_platform | def extract_platform(value)
platform = value.to_s.split('|')[1] if value.to_s.include? '|'
sauce_platforms
@sauce_platforms[platform] if not platform.nil?
end | ruby | def extract_platform(value)
platform = value.to_s.split('|')[1] if value.to_s.include? '|'
sauce_platforms
@sauce_platforms[platform] if not platform.nil?
end | [
"def",
"extract_platform",
"(",
"value",
")",
"platform",
"=",
"value",
".",
"to_s",
".",
"split",
"(",
"'|'",
")",
"[",
"1",
"]",
"if",
"value",
".",
"to_s",
".",
"include?",
"'|'",
"sauce_platforms",
"@sauce_platforms",
"[",
"platform",
"]",
"if",
"not... | Extracts platform from browser string
@example
extract_platform(:'safari5|linux|iphone') will extract
browser = safari
@param [String] the browser string passed into the method
@return [String] the platform value | [
"Extracts",
"platform",
"from",
"browser",
"string"
] | fcdf933c83c6b8bd32773b571a1919c697d8ce53 | https://github.com/machzqcq/saucelabs/blob/fcdf933c83c6b8bd32773b571a1919c697d8ce53/lib/saucelabs/parsed_values.rb#L74-L78 | valid |
machzqcq/saucelabs | lib/saucelabs/parsed_values.rb | SauceLabs.ParsedValues.extract_device | def extract_device(value)
device = value.to_s.split('|')[2] if value.to_s.include? '|'
sauce_devices
@sauce_devices[device] if not device.nil?
end | ruby | def extract_device(value)
device = value.to_s.split('|')[2] if value.to_s.include? '|'
sauce_devices
@sauce_devices[device] if not device.nil?
end | [
"def",
"extract_device",
"(",
"value",
")",
"device",
"=",
"value",
".",
"to_s",
".",
"split",
"(",
"'|'",
")",
"[",
"2",
"]",
"if",
"value",
".",
"to_s",
".",
"include?",
"'|'",
"sauce_devices",
"@sauce_devices",
"[",
"device",
"]",
"if",
"not",
"devi... | Extracts device from browser string
@example
extract_device(:'safari5|linux|iphone') will extract
browser = safari
@param [String] the browser string passed into the method
@return [String] the device value | [
"Extracts",
"device",
"from",
"browser",
"string"
] | fcdf933c83c6b8bd32773b571a1919c697d8ce53 | https://github.com/machzqcq/saucelabs/blob/fcdf933c83c6b8bd32773b571a1919c697d8ce53/lib/saucelabs/parsed_values.rb#L91-L95 | valid |
billdueber/library_stdnums | lib/library_stdnums.rb | StdNum.Helpers.extractNumber | def extractNumber str
match = STDNUMPAT.match str
return nil unless match
return (match[1].gsub(/\-/, '')).upcase
end | ruby | def extractNumber str
match = STDNUMPAT.match str
return nil unless match
return (match[1].gsub(/\-/, '')).upcase
end | [
"def",
"extractNumber",
"str",
"match",
"=",
"STDNUMPAT",
".",
"match",
"str",
"return",
"nil",
"unless",
"match",
"return",
"(",
"match",
"[",
"1",
"]",
".",
"gsub",
"(",
"/",
"\\-",
"/",
",",
"''",
")",
")",
".",
"upcase",
"end"
] | Extract the most likely looking number from the string. This will be the first
string of digits-and-hyphens-and-maybe-a-trailing-X, with the hypens removed
@param [String] str The string from which to extract an ISBN/ISSN
@return [String] The extracted identifier | [
"Extract",
"the",
"most",
"likely",
"looking",
"number",
"from",
"the",
"string",
".",
"This",
"will",
"be",
"the",
"first",
"string",
"of",
"digits",
"-",
"and",
"-",
"hyphens",
"-",
"and",
"-",
"maybe",
"-",
"a",
"-",
"trailing",
"-",
"X",
"with",
... | 388cca76f90c241dbcc556a4fe506ab0fc05996f | https://github.com/billdueber/library_stdnums/blob/388cca76f90c241dbcc556a4fe506ab0fc05996f/lib/library_stdnums.rb#L18-L22 | valid |
billdueber/library_stdnums | lib/library_stdnums.rb | StdNum.Helpers.extract_multiple_numbers | def extract_multiple_numbers(str)
return [] if str == '' || str.nil?
str.scan(STDNUMPAT_MULTIPLE).flatten.map{ |i| i.gsub(/\-/, '').upcase }
end | ruby | def extract_multiple_numbers(str)
return [] if str == '' || str.nil?
str.scan(STDNUMPAT_MULTIPLE).flatten.map{ |i| i.gsub(/\-/, '').upcase }
end | [
"def",
"extract_multiple_numbers",
"(",
"str",
")",
"return",
"[",
"]",
"if",
"str",
"==",
"''",
"||",
"str",
".",
"nil?",
"str",
".",
"scan",
"(",
"STDNUMPAT_MULTIPLE",
")",
".",
"flatten",
".",
"map",
"{",
"|",
"i",
"|",
"i",
".",
"gsub",
"(",
"/... | Extract the most likely looking numbers from the string. This will be each
string with digits-and-hyphens-and-maybe-a-trailing-X, with the hypens removed
@param [String] str The string from which to extract the ISBN/ISSNs
@return [Array] An array of extracted identifiers | [
"Extract",
"the",
"most",
"likely",
"looking",
"numbers",
"from",
"the",
"string",
".",
"This",
"will",
"be",
"each",
"string",
"with",
"digits",
"-",
"and",
"-",
"hyphens",
"-",
"and",
"-",
"maybe",
"-",
"a",
"-",
"trailing",
"-",
"X",
"with",
"the",
... | 388cca76f90c241dbcc556a4fe506ab0fc05996f | https://github.com/billdueber/library_stdnums/blob/388cca76f90c241dbcc556a4fe506ab0fc05996f/lib/library_stdnums.rb#L31-L34 | valid |
thinkwell/mongoid_nested_set | lib/mongoid_nested_set/update.rb | Mongoid::Acts::NestedSet.Update.set_default_left_and_right | def set_default_left_and_right
maxright = nested_set_scope.remove_order_by.max(right_field_name) || 0
self[left_field_name] = maxright + 1
self[right_field_name] = maxright + 2
self[:depth] = 0
end | ruby | def set_default_left_and_right
maxright = nested_set_scope.remove_order_by.max(right_field_name) || 0
self[left_field_name] = maxright + 1
self[right_field_name] = maxright + 2
self[:depth] = 0
end | [
"def",
"set_default_left_and_right",
"maxright",
"=",
"nested_set_scope",
".",
"remove_order_by",
".",
"max",
"(",
"right_field_name",
")",
"||",
"0",
"self",
"[",
"left_field_name",
"]",
"=",
"maxright",
"+",
"1",
"self",
"[",
"right_field_name",
"]",
"=",
"max... | on creation, set automatically lft and rgt to the end of the tree | [
"on",
"creation",
"set",
"automatically",
"lft",
"and",
"rgt",
"to",
"the",
"end",
"of",
"the",
"tree"
] | d482b2642889d5853079cb13ced049513caa1af3 | https://github.com/thinkwell/mongoid_nested_set/blob/d482b2642889d5853079cb13ced049513caa1af3/lib/mongoid_nested_set/update.rb#L67-L72 | valid |
thinkwell/mongoid_nested_set | lib/mongoid_nested_set/update.rb | Mongoid::Acts::NestedSet.Update.update_self_and_descendants_depth | def update_self_and_descendants_depth
if depth?
scope_class.each_with_level(self_and_descendants) do |node, level|
node.with(:safe => true).set(:depth, level) unless node.depth == level
end
self.reload
end
self
end | ruby | def update_self_and_descendants_depth
if depth?
scope_class.each_with_level(self_and_descendants) do |node, level|
node.with(:safe => true).set(:depth, level) unless node.depth == level
end
self.reload
end
self
end | [
"def",
"update_self_and_descendants_depth",
"if",
"depth?",
"scope_class",
".",
"each_with_level",
"(",
"self_and_descendants",
")",
"do",
"|",
"node",
",",
"level",
"|",
"node",
".",
"with",
"(",
":safe",
"=>",
"true",
")",
".",
"set",
"(",
":depth",
",",
"... | Update cached level attribute for self and descendants | [
"Update",
"cached",
"level",
"attribute",
"for",
"self",
"and",
"descendants"
] | d482b2642889d5853079cb13ced049513caa1af3 | https://github.com/thinkwell/mongoid_nested_set/blob/d482b2642889d5853079cb13ced049513caa1af3/lib/mongoid_nested_set/update.rb#L188-L196 | valid |
thinkwell/mongoid_nested_set | lib/mongoid_nested_set/update.rb | Mongoid::Acts::NestedSet.Update.destroy_descendants | def destroy_descendants
return if right.nil? || left.nil? || skip_before_destroy
if acts_as_nested_set_options[:dependent] == :destroy
descendants.each do |model|
model.skip_before_destroy = true
model.destroy
end
else
c = nested_set_scope.where(left_field_name.to_sym.gt => left, right_field_name.to_sym.lt => right)
scope_class.where(c.selector).delete_all
end
# update lefts and rights for remaining nodes
diff = right - left + 1
scope_class.with(:safe => true).where(
nested_set_scope.where(left_field_name.to_sym.gt => right).selector
).inc(left_field_name, -diff)
scope_class.with(:safe => true).where(
nested_set_scope.where(right_field_name.to_sym.gt => right).selector
).inc(right_field_name, -diff)
# Don't allow multiple calls to destroy to corrupt the set
self.skip_before_destroy = true
end | ruby | def destroy_descendants
return if right.nil? || left.nil? || skip_before_destroy
if acts_as_nested_set_options[:dependent] == :destroy
descendants.each do |model|
model.skip_before_destroy = true
model.destroy
end
else
c = nested_set_scope.where(left_field_name.to_sym.gt => left, right_field_name.to_sym.lt => right)
scope_class.where(c.selector).delete_all
end
# update lefts and rights for remaining nodes
diff = right - left + 1
scope_class.with(:safe => true).where(
nested_set_scope.where(left_field_name.to_sym.gt => right).selector
).inc(left_field_name, -diff)
scope_class.with(:safe => true).where(
nested_set_scope.where(right_field_name.to_sym.gt => right).selector
).inc(right_field_name, -diff)
# Don't allow multiple calls to destroy to corrupt the set
self.skip_before_destroy = true
end | [
"def",
"destroy_descendants",
"return",
"if",
"right",
".",
"nil?",
"||",
"left",
".",
"nil?",
"||",
"skip_before_destroy",
"if",
"acts_as_nested_set_options",
"[",
":dependent",
"]",
"==",
":destroy",
"descendants",
".",
"each",
"do",
"|",
"model",
"|",
"model"... | Prunes a branch off of the tree, shifting all of the elements on the right
back to the left so the counts still work | [
"Prunes",
"a",
"branch",
"off",
"of",
"the",
"tree",
"shifting",
"all",
"of",
"the",
"elements",
"on",
"the",
"right",
"back",
"to",
"the",
"left",
"so",
"the",
"counts",
"still",
"work"
] | d482b2642889d5853079cb13ced049513caa1af3 | https://github.com/thinkwell/mongoid_nested_set/blob/d482b2642889d5853079cb13ced049513caa1af3/lib/mongoid_nested_set/update.rb#L201-L227 | valid |
knife/nlp | lib/text_statistics.rb | NLP.TextStatistics.add | def add(word,categories)
categories.each do |category|
@cwords[category] = [] if @cwords[category].nil?
@cwords[category].push word
@scores[category] += 1
end
@words.push word
@word_count += 1
end | ruby | def add(word,categories)
categories.each do |category|
@cwords[category] = [] if @cwords[category].nil?
@cwords[category].push word
@scores[category] += 1
end
@words.push word
@word_count += 1
end | [
"def",
"add",
"(",
"word",
",",
"categories",
")",
"categories",
".",
"each",
"do",
"|",
"category",
"|",
"@cwords",
"[",
"category",
"]",
"=",
"[",
"]",
"if",
"@cwords",
"[",
"category",
"]",
".",
"nil?",
"@cwords",
"[",
"category",
"]",
".",
"push"... | Adds word and its category to stats. | [
"Adds",
"word",
"and",
"its",
"category",
"to",
"stats",
"."
] | 3729a516a177b5b92780dabe913a5e74c3364f6b | https://github.com/knife/nlp/blob/3729a516a177b5b92780dabe913a5e74c3364f6b/lib/text_statistics.rb#L17-L25 | valid |
ksylvest/formula | lib/formula.rb | Formula.FormulaFormBuilder.button | def button(value = nil, options = {})
options[:button] ||= {}
options[:container] ||= {}
options[:container][:class] = arrayorize(options[:container][:class]) << ::Formula.block_class
@template.content_tag(::Formula.block_tag, options[:container]) do
submit value, options[:button]
end
end | ruby | def button(value = nil, options = {})
options[:button] ||= {}
options[:container] ||= {}
options[:container][:class] = arrayorize(options[:container][:class]) << ::Formula.block_class
@template.content_tag(::Formula.block_tag, options[:container]) do
submit value, options[:button]
end
end | [
"def",
"button",
"(",
"value",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":button",
"]",
"||=",
"{",
"}",
"options",
"[",
":container",
"]",
"||=",
"{",
"}",
"options",
"[",
":container",
"]",
"[",
":class",
"]",
"=",
"arrayor... | Generate a form button.
Options:
* :container - add custom options to the container
* :button - add custom options to the button
Usage:
f.button(:name)
Equivalent:
<div class="block">
<%= f.submit("Save")
</div> | [
"Generate",
"a",
"form",
"button",
"."
] | 3a06528f674a5f9e19472561a61c0cc8edcb6bfd | https://github.com/ksylvest/formula/blob/3a06528f674a5f9e19472561a61c0cc8edcb6bfd/lib/formula.rb#L98-L108 | valid |
ksylvest/formula | lib/formula.rb | Formula.FormulaFormBuilder.block | def block(method = nil, options = {}, &block)
options[:error] ||= error(method) if method
components = "".html_safe
if method
components << self.label(method, options[:label]) if options[:label] or options[:label].nil? and method
end
components << @template.capture(&block)
options[:container] ||= {}
options[:container][:class] = arrayorize(options[:container][:class]) << ::Formula.block_class << method
options[:container][:class] << ::Formula.block_error_class if ::Formula.block_error_class.present? and error?(method)
components << @template.content_tag(::Formula.hint_tag , options[:hint ], :class => ::Formula.hint_class ) if options[:hint ]
components << @template.content_tag(::Formula.error_tag, options[:error], :class => ::Formula.error_class) if options[:error]
@template.content_tag(::Formula.block_tag, options[:container]) do
components
end
end | ruby | def block(method = nil, options = {}, &block)
options[:error] ||= error(method) if method
components = "".html_safe
if method
components << self.label(method, options[:label]) if options[:label] or options[:label].nil? and method
end
components << @template.capture(&block)
options[:container] ||= {}
options[:container][:class] = arrayorize(options[:container][:class]) << ::Formula.block_class << method
options[:container][:class] << ::Formula.block_error_class if ::Formula.block_error_class.present? and error?(method)
components << @template.content_tag(::Formula.hint_tag , options[:hint ], :class => ::Formula.hint_class ) if options[:hint ]
components << @template.content_tag(::Formula.error_tag, options[:error], :class => ::Formula.error_class) if options[:error]
@template.content_tag(::Formula.block_tag, options[:container]) do
components
end
end | [
"def",
"block",
"(",
"method",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"options",
"[",
":error",
"]",
"||=",
"error",
"(",
"method",
")",
"if",
"method",
"components",
"=",
"\"\"",
".",
"html_safe",
"if",
"method",
"compone... | Basic container generator for use with blocks.
Options:
* :hint - specify a hint to be displayed ('We promise not to spam you.', etc.)
* :label - override the default label used ('Name:', 'URL:', etc.)
* :error - override the default error used ('invalid', 'incorrect', etc.)
Usage:
f.block(:name, :label => "Name:", :hint => "Please use your full name.", :container => { :class => 'fill' }) do
...
end
Equivalent:
<div class='block fill'>
<%= f.label(:name, "Name:") %>
...
<div class="hint">Please use your full name.</div>
<div class="error">...</div>
</div> | [
"Basic",
"container",
"generator",
"for",
"use",
"with",
"blocks",
"."
] | 3a06528f674a5f9e19472561a61c0cc8edcb6bfd | https://github.com/ksylvest/formula/blob/3a06528f674a5f9e19472561a61c0cc8edcb6bfd/lib/formula.rb#L134-L155 | valid |
ksylvest/formula | lib/formula.rb | Formula.FormulaFormBuilder.input | def input(method, options = {})
options[:as] ||= as(method)
options[:input] ||= {}
return hidden_field method, options[:input] if options[:as] == :hidden
klass = [::Formula.input_class, options[:as]]
klass << ::Formula.input_error_class if ::Formula.input_error_class.present? and error?(method)
self.block(method, options) do
@template.content_tag(::Formula.input_tag, :class => klass) do
case options[:as]
when :text then text_area method, ::Formula.area_options.merge(options[:input] || {})
when :file then file_field method, ::Formula.file_options.merge(options[:input] || {})
when :string then text_field method, ::Formula.field_options.merge(options[:input] || {})
when :password then password_field method, ::Formula.field_options.merge(options[:input] || {})
when :url then url_field method, ::Formula.field_options.merge(options[:input] || {})
when :email then email_field method, ::Formula.field_options.merge(options[:input] || {})
when :phone then phone_field method, ::Formula.field_options.merge(options[:input] || {})
when :number then number_field method, ::Formula.field_options.merge(options[:input] || {})
when :boolean then check_box method, ::Formula.box_options.merge(options[:input] || {})
when :country then country_select method, ::Formula.select_options.merge(options[:input] || {})
when :date then date_select method, ::Formula.select_options.merge(options[:input] || {}), options[:input].delete(:html) || {}
when :time then time_select method, ::Formula.select_options.merge(options[:input] || {}), options[:input].delete(:html) || {}
when :datetime then datetime_select method, ::Formula.select_options.merge(options[:input] || {}), options[:input].delete(:html) || {}
when :select then select method, options[:choices], ::Formula.select_options.merge(options[:input] || {}), options[:input].delete(:html) || {}
end
end
end
end | ruby | def input(method, options = {})
options[:as] ||= as(method)
options[:input] ||= {}
return hidden_field method, options[:input] if options[:as] == :hidden
klass = [::Formula.input_class, options[:as]]
klass << ::Formula.input_error_class if ::Formula.input_error_class.present? and error?(method)
self.block(method, options) do
@template.content_tag(::Formula.input_tag, :class => klass) do
case options[:as]
when :text then text_area method, ::Formula.area_options.merge(options[:input] || {})
when :file then file_field method, ::Formula.file_options.merge(options[:input] || {})
when :string then text_field method, ::Formula.field_options.merge(options[:input] || {})
when :password then password_field method, ::Formula.field_options.merge(options[:input] || {})
when :url then url_field method, ::Formula.field_options.merge(options[:input] || {})
when :email then email_field method, ::Formula.field_options.merge(options[:input] || {})
when :phone then phone_field method, ::Formula.field_options.merge(options[:input] || {})
when :number then number_field method, ::Formula.field_options.merge(options[:input] || {})
when :boolean then check_box method, ::Formula.box_options.merge(options[:input] || {})
when :country then country_select method, ::Formula.select_options.merge(options[:input] || {})
when :date then date_select method, ::Formula.select_options.merge(options[:input] || {}), options[:input].delete(:html) || {}
when :time then time_select method, ::Formula.select_options.merge(options[:input] || {}), options[:input].delete(:html) || {}
when :datetime then datetime_select method, ::Formula.select_options.merge(options[:input] || {}), options[:input].delete(:html) || {}
when :select then select method, options[:choices], ::Formula.select_options.merge(options[:input] || {}), options[:input].delete(:html) || {}
end
end
end
end | [
"def",
"input",
"(",
"method",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":as",
"]",
"||=",
"as",
"(",
"method",
")",
"options",
"[",
":input",
"]",
"||=",
"{",
"}",
"return",
"hidden_field",
"method",
",",
"options",
"[",
":input",
"]",
... | Generate a suitable form input for a given method by performing introspection on the type.
Options:
* :as - override the default type used (:url, :email, :phone, :password, :number, :text)
* :label - override the default label used ('Name:', 'URL:', etc.)
* :error - override the default error used ('invalid', 'incorrect', etc.)
* :input - add custom options to the input ({ :class => 'goregous' }, etc.)
* :container - add custom options to the container ({ :class => 'gorgeous' }, etc.)
Usage:
f.input(:name)
f.input(:email)
f.input(:password_a, :label => "Password", :hint => "It's a secret!", :container => { :class => "half" })
f.input(:password_b, :label => "Password", :hint => "It's a secret!", :container => { :class => "half" })
Equivalent:
<div class="block name">
<%= f.label(:name)
<div class="input string"><%= f.text_field(:name)</div>
<div class="error">...</div>
</div>
<div class="block email">
<%= f.label(:email)
<div class="input string"><%= f.email_field(:email)</div>
<div class="error">...</div>
</div>
<div class="block half password_a">
<div class="input">
<%= f.label(:password_a, "Password")
<%= f.password_field(:password_a)
<div class="hint">It's a secret!</div>
<div class="error">...</div>
</div>
</div>
<div class="block half password_b">
<div class="input">
<%= f.label(:password_b, "Password")
<%= f.password_field(:password_b)
<div class="hint">It's a secret!</div>
<div class="error">...</div>
</div>
</div> | [
"Generate",
"a",
"suitable",
"form",
"input",
"for",
"a",
"given",
"method",
"by",
"performing",
"introspection",
"on",
"the",
"type",
"."
] | 3a06528f674a5f9e19472561a61c0cc8edcb6bfd | https://github.com/ksylvest/formula/blob/3a06528f674a5f9e19472561a61c0cc8edcb6bfd/lib/formula.rb#L204-L233 | valid |
ksylvest/formula | lib/formula.rb | Formula.FormulaFormBuilder.file? | def file?(method)
@files ||= {}
@files[method] ||= begin
file = @object.send(method) if @object && @object.respond_to?(method)
file && ::Formula.file.any? { |method| file.respond_to?(method) }
end
end | ruby | def file?(method)
@files ||= {}
@files[method] ||= begin
file = @object.send(method) if @object && @object.respond_to?(method)
file && ::Formula.file.any? { |method| file.respond_to?(method) }
end
end | [
"def",
"file?",
"(",
"method",
")",
"@files",
"||=",
"{",
"}",
"@files",
"[",
"method",
"]",
"||=",
"begin",
"file",
"=",
"@object",
".",
"send",
"(",
"method",
")",
"if",
"@object",
"&&",
"@object",
".",
"respond_to?",
"(",
"method",
")",
"file",
"&... | Introspection on an association to determine if a method is a file. This
is determined by the methods ability to respond to file methods. | [
"Introspection",
"on",
"an",
"association",
"to",
"determine",
"if",
"a",
"method",
"is",
"a",
"file",
".",
"This",
"is",
"determined",
"by",
"the",
"methods",
"ability",
"to",
"respond",
"to",
"file",
"methods",
"."
] | 3a06528f674a5f9e19472561a61c0cc8edcb6bfd | https://github.com/ksylvest/formula/blob/3a06528f674a5f9e19472561a61c0cc8edcb6bfd/lib/formula.rb#L330-L336 | valid |
ksylvest/formula | lib/formula.rb | Formula.FormulaFormBuilder.arrayorize | def arrayorize(value)
case value
when nil then return []
when String then value.to_s.split
when Symbol then value.to_s.split
else value
end
end | ruby | def arrayorize(value)
case value
when nil then return []
when String then value.to_s.split
when Symbol then value.to_s.split
else value
end
end | [
"def",
"arrayorize",
"(",
"value",
")",
"case",
"value",
"when",
"nil",
"then",
"return",
"[",
"]",
"when",
"String",
"then",
"value",
".",
"to_s",
".",
"split",
"when",
"Symbol",
"then",
"value",
".",
"to_s",
".",
"split",
"else",
"value",
"end",
"end... | Create an array from a string, a symbol, or an undefined value. The default is to return
the value and assume it has already is valid. | [
"Create",
"an",
"array",
"from",
"a",
"string",
"a",
"symbol",
"or",
"an",
"undefined",
"value",
".",
"The",
"default",
"is",
"to",
"return",
"the",
"value",
"and",
"assume",
"it",
"has",
"already",
"is",
"valid",
"."
] | 3a06528f674a5f9e19472561a61c0cc8edcb6bfd | https://github.com/ksylvest/formula/blob/3a06528f674a5f9e19472561a61c0cc8edcb6bfd/lib/formula.rb#L403-L410 | valid |
pd/yard_types | lib/yard_types/types.rb | YardTypes.KindType.check | def check(obj)
if name == 'Boolean'
obj == true || obj == false
else
obj.kind_of? constant
end
end | ruby | def check(obj)
if name == 'Boolean'
obj == true || obj == false
else
obj.kind_of? constant
end
end | [
"def",
"check",
"(",
"obj",
")",
"if",
"name",
"==",
"'Boolean'",
"obj",
"==",
"true",
"||",
"obj",
"==",
"false",
"else",
"obj",
".",
"kind_of?",
"constant",
"end",
"end"
] | Type checks a given object. Special consideration is given to
the pseudo-class `Boolean`, which does not actually exist in Ruby,
but is commonly used to mean `TrueClass, FalseClass`.
@param (see Type#check)
@return [Boolean] `true` if `obj.kind_of?(constant)`. | [
"Type",
"checks",
"a",
"given",
"object",
".",
"Special",
"consideration",
"is",
"given",
"to",
"the",
"pseudo",
"-",
"class",
"Boolean",
"which",
"does",
"not",
"actually",
"exist",
"in",
"Ruby",
"but",
"is",
"commonly",
"used",
"to",
"mean",
"TrueClass",
... | a909254cff3b7e63d483e17169519ee11b7ab15d | https://github.com/pd/yard_types/blob/a909254cff3b7e63d483e17169519ee11b7ab15d/lib/yard_types/types.rb#L135-L141 | valid |
tablexi/synaccess | lib/synaccess_connect/net_booter/http/http_connection.rb | NetBooter.HttpConnection.toggle | def toggle(outlet, status)
current_status = status(outlet)
toggle_relay(outlet) if current_status != status
status
end | ruby | def toggle(outlet, status)
current_status = status(outlet)
toggle_relay(outlet) if current_status != status
status
end | [
"def",
"toggle",
"(",
"outlet",
",",
"status",
")",
"current_status",
"=",
"status",
"(",
"outlet",
")",
"toggle_relay",
"(",
"outlet",
")",
"if",
"current_status",
"!=",
"status",
"status",
"end"
] | Toggle the status of an outlet
Example:
>> netbooter.toggle(1, false)
=> false
Arguments:
+outlet+ The outlet you want to toggle
+status+ Boolean. true to turn on, false to turn off
Returns:
boolean - The new status of the outlet | [
"Toggle",
"the",
"status",
"of",
"an",
"outlet"
] | 68df823b226975d22e3b1ce00daf36b31639003b | https://github.com/tablexi/synaccess/blob/68df823b226975d22e3b1ce00daf36b31639003b/lib/synaccess_connect/net_booter/http/http_connection.rb#L72-L76 | valid |
tablexi/synaccess | lib/synaccess_connect/net_booter/http/http_connection.rb | NetBooter.HttpConnection.get_request | def get_request(path)
resp = nil
begin
Timeout::timeout(5) do
resp = do_http_request(path)
end
rescue => e
raise NetBooter::Error.new("Error connecting to relay: #{e.message}")
end
resp
end | ruby | def get_request(path)
resp = nil
begin
Timeout::timeout(5) do
resp = do_http_request(path)
end
rescue => e
raise NetBooter::Error.new("Error connecting to relay: #{e.message}")
end
resp
end | [
"def",
"get_request",
"(",
"path",
")",
"resp",
"=",
"nil",
"begin",
"Timeout",
"::",
"timeout",
"(",
"5",
")",
"do",
"resp",
"=",
"do_http_request",
"(",
"path",
")",
"end",
"rescue",
"=>",
"e",
"raise",
"NetBooter",
"::",
"Error",
".",
"new",
"(",
... | Make an http request and return the result. | [
"Make",
"an",
"http",
"request",
"and",
"return",
"the",
"result",
"."
] | 68df823b226975d22e3b1ce00daf36b31639003b | https://github.com/tablexi/synaccess/blob/68df823b226975d22e3b1ce00daf36b31639003b/lib/synaccess_connect/net_booter/http/http_connection.rb#L102-L112 | valid |
sxross/MotionModel | motion/adapters/array_model_persistence.rb | MotionModel.ArrayModelAdapter.encodeWithCoder | def encodeWithCoder(coder)
columns.each do |attr|
# Serialize attributes except the proxy has_many and belongs_to ones.
unless [:belongs_to, :has_many, :has_one].include? column(attr).type
value = self.send(attr)
unless value.nil?
coder.encodeObject(value, forKey: attr.to_s)
end
end
end
end | ruby | def encodeWithCoder(coder)
columns.each do |attr|
# Serialize attributes except the proxy has_many and belongs_to ones.
unless [:belongs_to, :has_many, :has_one].include? column(attr).type
value = self.send(attr)
unless value.nil?
coder.encodeObject(value, forKey: attr.to_s)
end
end
end
end | [
"def",
"encodeWithCoder",
"(",
"coder",
")",
"columns",
".",
"each",
"do",
"|",
"attr",
"|",
"unless",
"[",
":belongs_to",
",",
":has_many",
",",
":has_one",
"]",
".",
"include?",
"column",
"(",
"attr",
")",
".",
"type",
"value",
"=",
"self",
".",
"sen... | Follow Apple's recommendation not to encode missing
values. | [
"Follow",
"Apple",
"s",
"recommendation",
"not",
"to",
"encode",
"missing",
"values",
"."
] | 37bf447b6c9bdc2158f320cef40714f41132c542 | https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/adapters/array_model_persistence.rb#L146-L156 | valid |
sxross/MotionModel | motion/adapters/array_finder_query.rb | MotionModel.ArrayFinderQuery.order | def order(field = nil, &block)
if block_given?
@collection = @collection.sort{|o1, o2| yield(o1, o2)}
else
raise ArgumentError.new('you must supply a field name to sort unless you supply a block.') if field.nil?
@collection = @collection.sort{|o1, o2| o1.send(field) <=> o2.send(field)}
end
self
end | ruby | def order(field = nil, &block)
if block_given?
@collection = @collection.sort{|o1, o2| yield(o1, o2)}
else
raise ArgumentError.new('you must supply a field name to sort unless you supply a block.') if field.nil?
@collection = @collection.sort{|o1, o2| o1.send(field) <=> o2.send(field)}
end
self
end | [
"def",
"order",
"(",
"field",
"=",
"nil",
",",
"&",
"block",
")",
"if",
"block_given?",
"@collection",
"=",
"@collection",
".",
"sort",
"{",
"|",
"o1",
",",
"o2",
"|",
"yield",
"(",
"o1",
",",
"o2",
")",
"}",
"else",
"raise",
"ArgumentError",
".",
... | Specifies how to sort. only ascending sort is supported in the short
form. For descending, implement the block form.
Task.where(:name).eq('bob').order(:pay_grade).all => array of bobs ascending by pay grade
Task.where(:name).eq('bob').order(:pay_grade){|o1, o2| o2 <=> o1} => array of bobs descending by pay grade | [
"Specifies",
"how",
"to",
"sort",
".",
"only",
"ascending",
"sort",
"is",
"supported",
"in",
"the",
"short",
"form",
".",
"For",
"descending",
"implement",
"the",
"block",
"form",
"."
] | 37bf447b6c9bdc2158f320cef40714f41132c542 | https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/adapters/array_finder_query.rb#L31-L39 | valid |
sxross/MotionModel | motion/adapters/array_finder_query.rb | MotionModel.ArrayFinderQuery.contain | def contain(query_string, options = {:case_sensitive => false})
do_comparison(query_string) do |comparator, item|
if options[:case_sensitive]
item =~ Regexp.new(comparator, Regexp::MULTILINE)
else
item =~ Regexp.new(comparator, Regexp::IGNORECASE | Regexp::MULTILINE)
end
end
end | ruby | def contain(query_string, options = {:case_sensitive => false})
do_comparison(query_string) do |comparator, item|
if options[:case_sensitive]
item =~ Regexp.new(comparator, Regexp::MULTILINE)
else
item =~ Regexp.new(comparator, Regexp::IGNORECASE | Regexp::MULTILINE)
end
end
end | [
"def",
"contain",
"(",
"query_string",
",",
"options",
"=",
"{",
":case_sensitive",
"=>",
"false",
"}",
")",
"do_comparison",
"(",
"query_string",
")",
"do",
"|",
"comparator",
",",
"item",
"|",
"if",
"options",
"[",
":case_sensitive",
"]",
"item",
"=~",
"... | performs a "like" query.
Task.find(:work_group).contain('dev') => ['UI dev', 'Core dev', ...] | [
"performs",
"a",
"like",
"query",
"."
] | 37bf447b6c9bdc2158f320cef40714f41132c542 | https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/adapters/array_finder_query.rb#L59-L67 | valid |
sxross/MotionModel | motion/adapters/array_finder_query.rb | MotionModel.ArrayFinderQuery.in | def in(set)
@collection = @collection.collect do |item|
item if set.include?(item.send(@field_name.to_sym))
end.compact
end | ruby | def in(set)
@collection = @collection.collect do |item|
item if set.include?(item.send(@field_name.to_sym))
end.compact
end | [
"def",
"in",
"(",
"set",
")",
"@collection",
"=",
"@collection",
".",
"collect",
"do",
"|",
"item",
"|",
"item",
"if",
"set",
".",
"include?",
"(",
"item",
".",
"send",
"(",
"@field_name",
".",
"to_sym",
")",
")",
"end",
".",
"compact",
"end"
] | performs a set-inclusion test.
Task.find(:id).in([3, 5, 9]) | [
"performs",
"a",
"set",
"-",
"inclusion",
"test",
"."
] | 37bf447b6c9bdc2158f320cef40714f41132c542 | https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/adapters/array_finder_query.rb#L74-L78 | valid |
sxross/MotionModel | motion/adapters/array_finder_query.rb | MotionModel.ArrayFinderQuery.eq | def eq(query_string, options = {:case_sensitive => false})
do_comparison(query_string, options) do |comparator, item|
comparator == item
end
end | ruby | def eq(query_string, options = {:case_sensitive => false})
do_comparison(query_string, options) do |comparator, item|
comparator == item
end
end | [
"def",
"eq",
"(",
"query_string",
",",
"options",
"=",
"{",
":case_sensitive",
"=>",
"false",
"}",
")",
"do_comparison",
"(",
"query_string",
",",
"options",
")",
"do",
"|",
"comparator",
",",
"item",
"|",
"comparator",
"==",
"item",
"end",
"end"
] | performs strict equality comparison.
If arguments are strings, they are, by default,
compared case-insensitive, if case-sensitivity
is required, use:
eq('something', :case_sensitive => true) | [
"performs",
"strict",
"equality",
"comparison",
"."
] | 37bf447b6c9bdc2158f320cef40714f41132c542 | https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/adapters/array_finder_query.rb#L87-L91 | valid |
sxross/MotionModel | motion/adapters/array_finder_query.rb | MotionModel.ArrayFinderQuery.gt | def gt(query_string, options = {:case_sensitive => false})
do_comparison(query_string, options) do |comparator, item|
comparator < item
end
end | ruby | def gt(query_string, options = {:case_sensitive => false})
do_comparison(query_string, options) do |comparator, item|
comparator < item
end
end | [
"def",
"gt",
"(",
"query_string",
",",
"options",
"=",
"{",
":case_sensitive",
"=>",
"false",
"}",
")",
"do_comparison",
"(",
"query_string",
",",
"options",
")",
"do",
"|",
"comparator",
",",
"item",
"|",
"comparator",
"<",
"item",
"end",
"end"
] | performs greater-than comparison.
see `eq` for notes on case sensitivity. | [
"performs",
"greater",
"-",
"than",
"comparison",
"."
] | 37bf447b6c9bdc2158f320cef40714f41132c542 | https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/adapters/array_finder_query.rb#L98-L102 | valid |
sxross/MotionModel | motion/adapters/array_finder_query.rb | MotionModel.ArrayFinderQuery.lt | def lt(query_string, options = {:case_sensitive => false})
do_comparison(query_string, options) do |comparator, item|
comparator > item
end
end | ruby | def lt(query_string, options = {:case_sensitive => false})
do_comparison(query_string, options) do |comparator, item|
comparator > item
end
end | [
"def",
"lt",
"(",
"query_string",
",",
"options",
"=",
"{",
":case_sensitive",
"=>",
"false",
"}",
")",
"do_comparison",
"(",
"query_string",
",",
"options",
")",
"do",
"|",
"comparator",
",",
"item",
"|",
"comparator",
">",
"item",
"end",
"end"
] | performs less-than comparison.
see `eq` for notes on case sensitivity. | [
"performs",
"less",
"-",
"than",
"comparison",
"."
] | 37bf447b6c9bdc2158f320cef40714f41132c542 | https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/adapters/array_finder_query.rb#L109-L113 | valid |
sxross/MotionModel | motion/adapters/array_finder_query.rb | MotionModel.ArrayFinderQuery.gte | def gte(query_string, options = {:case_sensitive => false})
do_comparison(query_string, options) do |comparator, item|
comparator <= item
end
end | ruby | def gte(query_string, options = {:case_sensitive => false})
do_comparison(query_string, options) do |comparator, item|
comparator <= item
end
end | [
"def",
"gte",
"(",
"query_string",
",",
"options",
"=",
"{",
":case_sensitive",
"=>",
"false",
"}",
")",
"do_comparison",
"(",
"query_string",
",",
"options",
")",
"do",
"|",
"comparator",
",",
"item",
"|",
"comparator",
"<=",
"item",
"end",
"end"
] | performs greater-than-or-equal comparison.
see `eq` for notes on case sensitivity. | [
"performs",
"greater",
"-",
"than",
"-",
"or",
"-",
"equal",
"comparison",
"."
] | 37bf447b6c9bdc2158f320cef40714f41132c542 | https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/adapters/array_finder_query.rb#L120-L124 | valid |
sxross/MotionModel | motion/adapters/array_finder_query.rb | MotionModel.ArrayFinderQuery.lte | def lte(query_string, options = {:case_sensitive => false})
do_comparison(query_string, options) do |comparator, item|
comparator >= item
end
end | ruby | def lte(query_string, options = {:case_sensitive => false})
do_comparison(query_string, options) do |comparator, item|
comparator >= item
end
end | [
"def",
"lte",
"(",
"query_string",
",",
"options",
"=",
"{",
":case_sensitive",
"=>",
"false",
"}",
")",
"do_comparison",
"(",
"query_string",
",",
"options",
")",
"do",
"|",
"comparator",
",",
"item",
"|",
"comparator",
">=",
"item",
"end",
"end"
] | performs less-than-or-equal comparison.
see `eq` for notes on case sensitivity. | [
"performs",
"less",
"-",
"than",
"-",
"or",
"-",
"equal",
"comparison",
"."
] | 37bf447b6c9bdc2158f320cef40714f41132c542 | https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/adapters/array_finder_query.rb#L131-L135 | valid |
sxross/MotionModel | motion/adapters/array_finder_query.rb | MotionModel.ArrayFinderQuery.ne | def ne(query_string, options = {:case_sensitive => false})
do_comparison(query_string, options) do |comparator, item|
comparator != item
end
end | ruby | def ne(query_string, options = {:case_sensitive => false})
do_comparison(query_string, options) do |comparator, item|
comparator != item
end
end | [
"def",
"ne",
"(",
"query_string",
",",
"options",
"=",
"{",
":case_sensitive",
"=>",
"false",
"}",
")",
"do_comparison",
"(",
"query_string",
",",
"options",
")",
"do",
"|",
"comparator",
",",
"item",
"|",
"comparator",
"!=",
"item",
"end",
"end"
] | performs inequality comparison.
see `eq` for notes on case sensitivity. | [
"performs",
"inequality",
"comparison",
"."
] | 37bf447b6c9bdc2158f320cef40714f41132c542 | https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/adapters/array_finder_query.rb#L142-L146 | valid |
cheerfulstoic/music | lib/music/chord.rb | Music.Chord.inversion | def inversion(amount)
fail ArgumentError, 'Inversion amount must be greater than or equal to 1' if amount < 1
fail ArgumentError, 'Not enough notes in chord for inversion' if amount >= @notes.size
note_array = @notes.to_a.sort
notes = (0...amount).collect { note_array.shift.adjust_by_semitones(12) }
Chord.new(notes + note_array)
end | ruby | def inversion(amount)
fail ArgumentError, 'Inversion amount must be greater than or equal to 1' if amount < 1
fail ArgumentError, 'Not enough notes in chord for inversion' if amount >= @notes.size
note_array = @notes.to_a.sort
notes = (0...amount).collect { note_array.shift.adjust_by_semitones(12) }
Chord.new(notes + note_array)
end | [
"def",
"inversion",
"(",
"amount",
")",
"fail",
"ArgumentError",
",",
"'Inversion amount must be greater than or equal to 1'",
"if",
"amount",
"<",
"1",
"fail",
"ArgumentError",
",",
"'Not enough notes in chord for inversion'",
"if",
"amount",
">=",
"@notes",
".",
"size",... | Give the Nth inversion of the chord which simply adjusts the lowest N notes up by one octive
@returns [Chord] The specified inversion of chord | [
"Give",
"the",
"Nth",
"inversion",
"of",
"the",
"chord",
"which",
"simply",
"adjusts",
"the",
"lowest",
"N",
"notes",
"up",
"by",
"one",
"octive"
] | fef5354e5d965dad54c92eac851bff9192aa183b | https://github.com/cheerfulstoic/music/blob/fef5354e5d965dad54c92eac851bff9192aa183b/lib/music/chord.rb#L74-L81 | valid |
pwnall/stellar | lib/stellar/courses.rb | Stellar.Courses.mine | def mine
page = @client.get_nokogiri '/atstellar'
class_links = page.css('a[href*="/S/course/"]').
map { |link| Stellar::Course.from_link link, @client }.reject(&:nil?)
end | ruby | def mine
page = @client.get_nokogiri '/atstellar'
class_links = page.css('a[href*="/S/course/"]').
map { |link| Stellar::Course.from_link link, @client }.reject(&:nil?)
end | [
"def",
"mine",
"page",
"=",
"@client",
".",
"get_nokogiri",
"'/atstellar'",
"class_links",
"=",
"page",
".",
"css",
"(",
"'a[href*=\"/S/course/\"]'",
")",
".",
"map",
"{",
"|",
"link",
"|",
"Stellar",
"::",
"Course",
".",
"from_link",
"link",
",",
"@client",... | My classes.
@return [Array] array with one Hash per class; Hashes have :number and
:url keys | [
"My",
"classes",
"."
] | cd2bfd55a6afe9118a06c0d45d6a168e520ec19f | https://github.com/pwnall/stellar/blob/cd2bfd55a6afe9118a06c0d45d6a168e520ec19f/lib/stellar/courses.rb#L13-L17 | valid |
sxross/MotionModel | motion/validatable.rb | MotionModel.Validatable.error_messages_for | def error_messages_for(field)
key = field.to_sym
error_messages.select{|message| message.has_key?(key)}.map{|message| message[key]}
end | ruby | def error_messages_for(field)
key = field.to_sym
error_messages.select{|message| message.has_key?(key)}.map{|message| message[key]}
end | [
"def",
"error_messages_for",
"(",
"field",
")",
"key",
"=",
"field",
".",
"to_sym",
"error_messages",
".",
"select",
"{",
"|",
"message",
"|",
"message",
".",
"has_key?",
"(",
"key",
")",
"}",
".",
"map",
"{",
"|",
"message",
"|",
"message",
"[",
"key"... | Array of messages for a given field. Results are always an array
because a field can fail multiple validations. | [
"Array",
"of",
"messages",
"for",
"a",
"given",
"field",
".",
"Results",
"are",
"always",
"an",
"array",
"because",
"a",
"field",
"can",
"fail",
"multiple",
"validations",
"."
] | 37bf447b6c9bdc2158f320cef40714f41132c542 | https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/validatable.rb#L89-L92 | valid |
sxross/MotionModel | motion/validatable.rb | MotionModel.Validatable.validate_presence | def validate_presence(field, value, setting)
if(value.is_a?(Numeric))
return true
elsif value.is_a?(String) || value.nil?
result = value.nil? || ((value.length == 0) == setting)
additional_message = setting ? "non-empty" : "non-empty"
add_message(field, "incorrect value supplied for #{field.to_s} -- should be #{additional_message}.") if result
return !result
end
return false
end | ruby | def validate_presence(field, value, setting)
if(value.is_a?(Numeric))
return true
elsif value.is_a?(String) || value.nil?
result = value.nil? || ((value.length == 0) == setting)
additional_message = setting ? "non-empty" : "non-empty"
add_message(field, "incorrect value supplied for #{field.to_s} -- should be #{additional_message}.") if result
return !result
end
return false
end | [
"def",
"validate_presence",
"(",
"field",
",",
"value",
",",
"setting",
")",
"if",
"(",
"value",
".",
"is_a?",
"(",
"Numeric",
")",
")",
"return",
"true",
"elsif",
"value",
".",
"is_a?",
"(",
"String",
")",
"||",
"value",
".",
"nil?",
"result",
"=",
... | Validates that something has been endntered in a field.
Should catch Fixnums, Bignums and Floats. Nils and Strings should
be handled as well, Arrays, Hashes and other datatypes will not. | [
"Validates",
"that",
"something",
"has",
"been",
"endntered",
"in",
"a",
"field",
".",
"Should",
"catch",
"Fixnums",
"Bignums",
"and",
"Floats",
".",
"Nils",
"and",
"Strings",
"should",
"be",
"handled",
"as",
"well",
"Arrays",
"Hashes",
"and",
"other",
"data... | 37bf447b6c9bdc2158f320cef40714f41132c542 | https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/validatable.rb#L149-L159 | valid |
sxross/MotionModel | motion/validatable.rb | MotionModel.Validatable.validate_length | def validate_length(field, value, setting)
if value.is_a?(String) || value.nil?
result = value.nil? || (value.length < setting.first || value.length > setting.last)
add_message(field, "incorrect value supplied for #{field.to_s} -- should be between #{setting.first} and #{setting.last} characters long.") if result
return !result
end
return false
end | ruby | def validate_length(field, value, setting)
if value.is_a?(String) || value.nil?
result = value.nil? || (value.length < setting.first || value.length > setting.last)
add_message(field, "incorrect value supplied for #{field.to_s} -- should be between #{setting.first} and #{setting.last} characters long.") if result
return !result
end
return false
end | [
"def",
"validate_length",
"(",
"field",
",",
"value",
",",
"setting",
")",
"if",
"value",
".",
"is_a?",
"(",
"String",
")",
"||",
"value",
".",
"nil?",
"result",
"=",
"value",
".",
"nil?",
"||",
"(",
"value",
".",
"length",
"<",
"setting",
".",
"firs... | Validates that the length is in a given range of characters. E.g.,
validate :name, :length => 5..8 | [
"Validates",
"that",
"the",
"length",
"is",
"in",
"a",
"given",
"range",
"of",
"characters",
".",
"E",
".",
"g",
"."
] | 37bf447b6c9bdc2158f320cef40714f41132c542 | https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/validatable.rb#L164-L171 | valid |
sxross/MotionModel | motion/validatable.rb | MotionModel.Validatable.validate_format | def validate_format(field, value, setting)
result = value.nil? || setting.match(value).nil?
add_message(field, "#{field.to_s} does not appear to be in the proper format.") if result
return !result
end | ruby | def validate_format(field, value, setting)
result = value.nil? || setting.match(value).nil?
add_message(field, "#{field.to_s} does not appear to be in the proper format.") if result
return !result
end | [
"def",
"validate_format",
"(",
"field",
",",
"value",
",",
"setting",
")",
"result",
"=",
"value",
".",
"nil?",
"||",
"setting",
".",
"match",
"(",
"value",
")",
".",
"nil?",
"add_message",
"(",
"field",
",",
"\"#{field.to_s} does not appear to be in the proper ... | Validates contents of field against a given Regexp. This can be tricky because you need
to anchor both sides in most cases using \A and \Z to get a reliable match. | [
"Validates",
"contents",
"of",
"field",
"against",
"a",
"given",
"Regexp",
".",
"This",
"can",
"be",
"tricky",
"because",
"you",
"need",
"to",
"anchor",
"both",
"sides",
"in",
"most",
"cases",
"using",
"\\",
"A",
"and",
"\\",
"Z",
"to",
"get",
"a",
"re... | 37bf447b6c9bdc2158f320cef40714f41132c542 | https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/validatable.rb#L183-L187 | valid |
sxross/MotionModel | motion/model/model.rb | MotionModel.Model.set_auto_date_field | def set_auto_date_field(field_name)
unless self.class.protect_remote_timestamps?
method = "#{field_name}="
self.send(method, Time.now) if self.respond_to?(method)
end
end | ruby | def set_auto_date_field(field_name)
unless self.class.protect_remote_timestamps?
method = "#{field_name}="
self.send(method, Time.now) if self.respond_to?(method)
end
end | [
"def",
"set_auto_date_field",
"(",
"field_name",
")",
"unless",
"self",
".",
"class",
".",
"protect_remote_timestamps?",
"method",
"=",
"\"#{field_name}=\"",
"self",
".",
"send",
"(",
"method",
",",
"Time",
".",
"now",
")",
"if",
"self",
".",
"respond_to?",
"(... | Set created_at and updated_at fields | [
"Set",
"created_at",
"and",
"updated_at",
"fields"
] | 37bf447b6c9bdc2158f320cef40714f41132c542 | https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/model/model.rb#L551-L556 | valid |
sxross/MotionModel | motion/model/model.rb | MotionModel.Model.set_belongs_to_attr | def set_belongs_to_attr(col, owner, options = {})
_col = column(col)
unless belongs_to_synced?(_col, owner)
_set_attr(_col.name, owner)
rebuild_relation(_col, owner, set_inverse: options[:set_inverse])
if _col.polymorphic
set_polymorphic_attr(_col.name, owner)
else
_set_attr(_col.foreign_key, owner ? owner.id : nil)
end
end
owner
end | ruby | def set_belongs_to_attr(col, owner, options = {})
_col = column(col)
unless belongs_to_synced?(_col, owner)
_set_attr(_col.name, owner)
rebuild_relation(_col, owner, set_inverse: options[:set_inverse])
if _col.polymorphic
set_polymorphic_attr(_col.name, owner)
else
_set_attr(_col.foreign_key, owner ? owner.id : nil)
end
end
owner
end | [
"def",
"set_belongs_to_attr",
"(",
"col",
",",
"owner",
",",
"options",
"=",
"{",
"}",
")",
"_col",
"=",
"column",
"(",
"col",
")",
"unless",
"belongs_to_synced?",
"(",
"_col",
",",
"owner",
")",
"_set_attr",
"(",
"_col",
".",
"name",
",",
"owner",
")"... | Associate the owner but without rebuilding the inverse assignment | [
"Associate",
"the",
"owner",
"but",
"without",
"rebuilding",
"the",
"inverse",
"assignment"
] | 37bf447b6c9bdc2158f320cef40714f41132c542 | https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/model/model.rb#L707-L720 | valid |
pwnall/stellar | lib/stellar/homework.rb | Stellar.Homework.submissions | def submissions
page = @client.get_nokogiri @url
@submissions ||= page.css('.gradeTable tbody tr').map { |tr|
begin
Stellar::Homework::Submission.new tr, self
rescue ArgumentError
nil
end
}.reject(&:nil?)
end | ruby | def submissions
page = @client.get_nokogiri @url
@submissions ||= page.css('.gradeTable tbody tr').map { |tr|
begin
Stellar::Homework::Submission.new tr, self
rescue ArgumentError
nil
end
}.reject(&:nil?)
end | [
"def",
"submissions",
"page",
"=",
"@client",
".",
"get_nokogiri",
"@url",
"@submissions",
"||=",
"page",
".",
"css",
"(",
"'.gradeTable tbody tr'",
")",
".",
"map",
"{",
"|",
"tr",
"|",
"begin",
"Stellar",
"::",
"Homework",
"::",
"Submission",
".",
"new",
... | Creates a Stellar client scoped to an assignment.
@param [URI, String] page_url URL to the assignment's main Stellar page
@param [String] assignment name, e.g. "name"
@param [Course] the course that issued the assignment
List of submissions associated with this problem set. | [
"Creates",
"a",
"Stellar",
"client",
"scoped",
"to",
"an",
"assignment",
"."
] | cd2bfd55a6afe9118a06c0d45d6a168e520ec19f | https://github.com/pwnall/stellar/blob/cd2bfd55a6afe9118a06c0d45d6a168e520ec19f/lib/stellar/homework.rb#L70-L79 | valid |
pwnall/stellar | lib/stellar/client.rb | Stellar.Client.mech | def mech(&block)
m = Mechanize.new do |m|
m.cert_store = OpenSSL::X509::Store.new
m.cert_store.add_file mitca_path
m.user_agent_alias = 'Linux Firefox'
yield m if block
m
end
m
end | ruby | def mech(&block)
m = Mechanize.new do |m|
m.cert_store = OpenSSL::X509::Store.new
m.cert_store.add_file mitca_path
m.user_agent_alias = 'Linux Firefox'
yield m if block
m
end
m
end | [
"def",
"mech",
"(",
"&",
"block",
")",
"m",
"=",
"Mechanize",
".",
"new",
"do",
"|",
"m",
"|",
"m",
".",
"cert_store",
"=",
"OpenSSL",
"::",
"X509",
"::",
"Store",
".",
"new",
"m",
".",
"cert_store",
".",
"add_file",
"mitca_path",
"m",
".",
"user_a... | Client for accessing public information.
Call auth to authenticate as a user and access restricted functionality.
New Mechanize instance. | [
"Client",
"for",
"accessing",
"public",
"information",
"."
] | cd2bfd55a6afe9118a06c0d45d6a168e520ec19f | https://github.com/pwnall/stellar/blob/cd2bfd55a6afe9118a06c0d45d6a168e520ec19f/lib/stellar/client.rb#L18-L27 | valid |
pwnall/stellar | lib/stellar/client.rb | Stellar.Client.get_nokogiri | def get_nokogiri(path)
uri = URI.join('https://stellar.mit.edu', path)
raw_html = @mech.get_file uri
Nokogiri.HTML raw_html, uri.to_s
end | ruby | def get_nokogiri(path)
uri = URI.join('https://stellar.mit.edu', path)
raw_html = @mech.get_file uri
Nokogiri.HTML raw_html, uri.to_s
end | [
"def",
"get_nokogiri",
"(",
"path",
")",
"uri",
"=",
"URI",
".",
"join",
"(",
"'https://stellar.mit.edu'",
",",
"path",
")",
"raw_html",
"=",
"@mech",
".",
"get_file",
"uri",
"Nokogiri",
".",
"HTML",
"raw_html",
",",
"uri",
".",
"to_s",
"end"
] | Fetches a page from the Stellar site.
@param [String] path relative URL of the page to be fetched
@return [Nokogiri::HTML::Document] the desired page, parsed with Nokogiri | [
"Fetches",
"a",
"page",
"from",
"the",
"Stellar",
"site",
"."
] | cd2bfd55a6afe9118a06c0d45d6a168e520ec19f | https://github.com/pwnall/stellar/blob/cd2bfd55a6afe9118a06c0d45d6a168e520ec19f/lib/stellar/client.rb#L42-L46 | valid |
sxross/MotionModel | motion/input_helpers.rb | MotionModel.InputHelpers.field_at | def field_at(index)
data = self.class.instance_variable_get('@binding_data'.to_sym)
data[index].tag = index + 1
data[index]
end | ruby | def field_at(index)
data = self.class.instance_variable_get('@binding_data'.to_sym)
data[index].tag = index + 1
data[index]
end | [
"def",
"field_at",
"(",
"index",
")",
"data",
"=",
"self",
".",
"class",
".",
"instance_variable_get",
"(",
"'@binding_data'",
".",
"to_sym",
")",
"data",
"[",
"index",
"]",
".",
"tag",
"=",
"index",
"+",
"1",
"data",
"[",
"index",
"]",
"end"
] | +field_at+ retrieves the field at a given index.
Usage:
field = field_at(indexPath.row)
label_view = subview(UILabel, :label_frame, text: field.label) | [
"+",
"field_at",
"+",
"retrieves",
"the",
"field",
"at",
"a",
"given",
"index",
"."
] | 37bf447b6c9bdc2158f320cef40714f41132c542 | https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/input_helpers.rb#L73-L77 | valid |
sxross/MotionModel | motion/input_helpers.rb | MotionModel.InputHelpers.bind | def bind
raise ModelNotSetError.new("You must set the model before binding it.") unless @model
fields do |field|
view_obj = self.view.viewWithTag(field.tag)
@model.send("#{field.name}=".to_sym, view_obj.text) if view_obj.respond_to?(:text)
end
end | ruby | def bind
raise ModelNotSetError.new("You must set the model before binding it.") unless @model
fields do |field|
view_obj = self.view.viewWithTag(field.tag)
@model.send("#{field.name}=".to_sym, view_obj.text) if view_obj.respond_to?(:text)
end
end | [
"def",
"bind",
"raise",
"ModelNotSetError",
".",
"new",
"(",
"\"You must set the model before binding it.\"",
")",
"unless",
"@model",
"fields",
"do",
"|",
"field",
"|",
"view_obj",
"=",
"self",
".",
"view",
".",
"viewWithTag",
"(",
"field",
".",
"tag",
")",
"... | +bind+ fetches all mapped fields from
any subview of the current +UIView+
and transfers the contents to the
corresponding fields of the model
specified by the +model+ method. | [
"+",
"bind",
"+",
"fetches",
"all",
"mapped",
"fields",
"from",
"any",
"subview",
"of",
"the",
"current",
"+",
"UIView",
"+",
"and",
"transfers",
"the",
"contents",
"to",
"the",
"corresponding",
"fields",
"of",
"the",
"model",
"specified",
"by",
"the",
"+"... | 37bf447b6c9bdc2158f320cef40714f41132c542 | https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/input_helpers.rb#L108-L115 | valid |
sxross/MotionModel | motion/input_helpers.rb | MotionModel.InputHelpers.handle_keyboard_will_hide | def handle_keyboard_will_hide(notification)
return unless @table
if UIEdgeInsetsEqualToEdgeInsets(@table.contentInset, UIEdgeInsetsZero)
return
end
animationCurve = notification.userInfo.valueForKey(UIKeyboardAnimationCurveUserInfoKey)
animationDuration = notification.userInfo.valueForKey(UIKeyboardAnimationDurationUserInfoKey)
UIView.beginAnimations("changeTableViewContentInset", context:nil)
UIView.setAnimationDuration(animationDuration)
UIView.setAnimationCurve(animationCurve)
@table.contentInset = UIEdgeInsetsZero;
UIView.commitAnimations
end | ruby | def handle_keyboard_will_hide(notification)
return unless @table
if UIEdgeInsetsEqualToEdgeInsets(@table.contentInset, UIEdgeInsetsZero)
return
end
animationCurve = notification.userInfo.valueForKey(UIKeyboardAnimationCurveUserInfoKey)
animationDuration = notification.userInfo.valueForKey(UIKeyboardAnimationDurationUserInfoKey)
UIView.beginAnimations("changeTableViewContentInset", context:nil)
UIView.setAnimationDuration(animationDuration)
UIView.setAnimationCurve(animationCurve)
@table.contentInset = UIEdgeInsetsZero;
UIView.commitAnimations
end | [
"def",
"handle_keyboard_will_hide",
"(",
"notification",
")",
"return",
"unless",
"@table",
"if",
"UIEdgeInsetsEqualToEdgeInsets",
"(",
"@table",
".",
"contentInset",
",",
"UIEdgeInsetsZero",
")",
"return",
"end",
"animationCurve",
"=",
"notification",
".",
"userInfo",
... | Undo all the rejiggering when the keyboard slides
down.
You *must* handle the +UIKeyboardWillHideNotification+ and
when you receive it, call this method to handle the keyboard
hiding. | [
"Undo",
"all",
"the",
"rejiggering",
"when",
"the",
"keyboard",
"slides",
"down",
"."
] | 37bf447b6c9bdc2158f320cef40714f41132c542 | https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/input_helpers.rb#L191-L208 | valid |
mkristian/cuba-api | lib/cuba_api/utils.rb | CubaApi.Utils.no_body | def no_body( status )
res.status = ::Rack::Utils.status_code( status )
res.write ::Rack::Utils::HTTP_STATUS_CODES[ res.status ]
res['Content-Type' ] = 'text/plain'
end | ruby | def no_body( status )
res.status = ::Rack::Utils.status_code( status )
res.write ::Rack::Utils::HTTP_STATUS_CODES[ res.status ]
res['Content-Type' ] = 'text/plain'
end | [
"def",
"no_body",
"(",
"status",
")",
"res",
".",
"status",
"=",
"::",
"Rack",
"::",
"Utils",
".",
"status_code",
"(",
"status",
")",
"res",
".",
"write",
"::",
"Rack",
"::",
"Utils",
"::",
"HTTP_STATUS_CODES",
"[",
"res",
".",
"status",
"]",
"res",
... | convenient method for status only responses | [
"convenient",
"method",
"for",
"status",
"only",
"responses"
] | e3413d7c32bee83280efd001e3d166b0b93c7417 | https://github.com/mkristian/cuba-api/blob/e3413d7c32bee83280efd001e3d166b0b93c7417/lib/cuba_api/utils.rb#L19-L23 | valid |
smileart/rack-fraction | lib/rack/fraction.rb | Rack.Fraction.call | def call(env)
if rand(1..100) <= @percent
if @modify == :response
# status, headers, body
response = @handler.call(*@app.call(env))
else # :env
modified_env = @handler.call(env) || env
response = @app.call(modified_env)
end
else
response = @app.call(env)
end
response
end | ruby | def call(env)
if rand(1..100) <= @percent
if @modify == :response
# status, headers, body
response = @handler.call(*@app.call(env))
else # :env
modified_env = @handler.call(env) || env
response = @app.call(modified_env)
end
else
response = @app.call(env)
end
response
end | [
"def",
"call",
"(",
"env",
")",
"if",
"rand",
"(",
"1",
"..",
"100",
")",
"<=",
"@percent",
"if",
"@modify",
"==",
":response",
"response",
"=",
"@handler",
".",
"call",
"(",
"*",
"@app",
".",
"call",
"(",
"env",
")",
")",
"else",
"modified_env",
"... | Initialisation of the middleware
@param [Rack::App] app rack app to stack middleware into (passed automatically)
@param [Symbol] modify a flag which tells what to modify with this middleware (:response or :env)
anything other than :response would mean :env (default: nil)
@param [Integer] percent fraction of the requests that should be affected by this middleware (default: 0)
@param [Proc] block the block of code with business logic which modifies response/env
Implementation of the middleware automatically called by Rack
@param [Hash] env rack app env automatically passed to the middleware
@return [Rack::Response] response after either calling original app and modifying response
or calling the app with modified environment and returning its response | [
"Initialisation",
"of",
"the",
"middleware"
] | d030b63a6b0181ceca2768faf5452ca823c15fcf | https://github.com/smileart/rack-fraction/blob/d030b63a6b0181ceca2768faf5452ca823c15fcf/lib/rack/fraction.rb#L30-L44 | valid |
claco/muster | lib/muster/results.rb | Muster.Results.filtered | def filtered
return self if filters.empty?
filtered_results = filters.each_with_object({}) do |(key, options), results|
results[key] = filter(key, *options)
end
self.class.new(filtered_results)
end | ruby | def filtered
return self if filters.empty?
filtered_results = filters.each_with_object({}) do |(key, options), results|
results[key] = filter(key, *options)
end
self.class.new(filtered_results)
end | [
"def",
"filtered",
"return",
"self",
"if",
"filters",
".",
"empty?",
"filtered_results",
"=",
"filters",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"(",
"key",
",",
"options",
")",
",",
"results",
"|",
"results",
"[",
"key",
"]",
"=",
"fil... | Returns the raw data with all of the filters applied
If no filters were added, this method simply returns self.
@return [Muster::Results]
@example
results.add_filter(:select, :only => [:id, :name])
results.add_dilter(:page, 1)
results.filtered #=> { 'select' => [:id, :name], 'page' => 1 } | [
"Returns",
"the",
"raw",
"data",
"with",
"all",
"of",
"the",
"filters",
"applied"
] | 71e99053ced9da3e98820eb8be653d9b76325a39 | https://github.com/claco/muster/blob/71e99053ced9da3e98820eb8be653d9b76325a39/lib/muster/results.rb#L99-L107 | valid |
claco/muster | lib/muster/results.rb | Muster.Results.filter | def filter(key, *options)
if options.present? && options.first.instance_of?(Hash)
options = options.first.with_indifferent_access
if options.key?(:only)
return filter_only_values(key, options[:only])
elsif options.key?(:except)
return filter_excluded_values(key, options[:except])
end
else
return fetch(key, *options)
end
end | ruby | def filter(key, *options)
if options.present? && options.first.instance_of?(Hash)
options = options.first.with_indifferent_access
if options.key?(:only)
return filter_only_values(key, options[:only])
elsif options.key?(:except)
return filter_excluded_values(key, options[:except])
end
else
return fetch(key, *options)
end
end | [
"def",
"filter",
"(",
"key",
",",
"*",
"options",
")",
"if",
"options",
".",
"present?",
"&&",
"options",
".",
"first",
".",
"instance_of?",
"(",
"Hash",
")",
"options",
"=",
"options",
".",
"first",
".",
"with_indifferent_access",
"if",
"options",
".",
... | Filters and returns the raw data values for the specifid key and options
@param key [String,Symbol] the key of the values in {#data} to filter
@param [optional, Hash] options the options available for this filter
@option options [optional] :only when specified, only return the matching values
If you specify a single value, a single value will be returned
If you specify an Array of values, an Array will be returned, even if only one value matches
@option options [optional] :except return all values except the ones given here
If the raw data value is a single value, a single value will be returned
If the raw data value is an Array, and array will be returned, even if all values are excluded
If nothing was excluded, the raw value is returned as-is
If you pass a scalar value instead of a Hash into options, it will be treated as the default, just like
Hash#fetch does.
If you pass nothing into the options argument, it will return all values if the key exists or raise
a KeyError like Hash#fetch.
@return [void]
@example
data = { :select => [:id, :name, :created_at] }
results = Muster::Results.new(data)
results.filter(:select) #=> [:id, :name, :created_at]
results.filter(:select, :only => :name) #=> :name
results.filter(:select, :only => [:other, :name]) #=> [:name]
results.filter(:other, :default) #=> :default
results.filter(:other) #=> KeyError | [
"Filters",
"and",
"returns",
"the",
"raw",
"data",
"values",
"for",
"the",
"specifid",
"key",
"and",
"options"
] | 71e99053ced9da3e98820eb8be653d9b76325a39 | https://github.com/claco/muster/blob/71e99053ced9da3e98820eb8be653d9b76325a39/lib/muster/results.rb#L138-L150 | valid |
mnpopcenter/stats_package_syntax_file_generator | lib/syntax_file/controller.rb | SyntaxFile.Controller.modify_metadata | def modify_metadata
# Force all variables to be strings.
if @all_vars_as_string
@variables.each do |var|
var.is_string_var = true
var.is_double_var = false
var.implied_decimals = 0
end
end
# If the user wants to rectangularize hierarchical data, the
# select_vars_by_record_type option is required.
@select_vars_by_record_type = true if @rectangularize
# Remove any variables not belonging to the declared record types.
if @select_vars_by_record_type
rt_lookup = rec_type_lookup_hash()
@variables = @variables.find_all { |var| var.is_common_var or rt_lookup[var.record_type] }
end
end | ruby | def modify_metadata
# Force all variables to be strings.
if @all_vars_as_string
@variables.each do |var|
var.is_string_var = true
var.is_double_var = false
var.implied_decimals = 0
end
end
# If the user wants to rectangularize hierarchical data, the
# select_vars_by_record_type option is required.
@select_vars_by_record_type = true if @rectangularize
# Remove any variables not belonging to the declared record types.
if @select_vars_by_record_type
rt_lookup = rec_type_lookup_hash()
@variables = @variables.find_all { |var| var.is_common_var or rt_lookup[var.record_type] }
end
end | [
"def",
"modify_metadata",
"if",
"@all_vars_as_string",
"@variables",
".",
"each",
"do",
"|",
"var",
"|",
"var",
".",
"is_string_var",
"=",
"true",
"var",
".",
"is_double_var",
"=",
"false",
"var",
".",
"implied_decimals",
"=",
"0",
"end",
"end",
"@select_vars_... | Before generating syntax, we need to handle some controller-level
options that require global modification of the metadata. | [
"Before",
"generating",
"syntax",
"we",
"need",
"to",
"handle",
"some",
"controller",
"-",
"level",
"options",
"that",
"require",
"global",
"modification",
"of",
"the",
"metadata",
"."
] | 014e23a69f9a647f20eaffcf9e95016f98d5c17e | https://github.com/mnpopcenter/stats_package_syntax_file_generator/blob/014e23a69f9a647f20eaffcf9e95016f98d5c17e/lib/syntax_file/controller.rb#L252-L271 | valid |
mnpopcenter/stats_package_syntax_file_generator | lib/syntax_file/controller.rb | SyntaxFile.Controller.validate_metadata | def validate_metadata (check = {})
bad_metadata('no variables') if @variables.empty?
if @rectangularize
msg = 'the rectangularize option requires data_structure=hier'
bad_metadata(msg) unless @data_structure == 'hier'
end
if @data_structure == 'hier' or @select_vars_by_record_type
bad_metadata('no record types') if @record_types.empty?
msg = 'record types must be unique'
bad_metadata(msg) unless rec_type_lookup_hash.keys.size == @record_types.size
msg = 'all variables must have a record type'
bad_metadata(msg) unless @variables.find { |var| var.record_type.length == 0 }.nil?
msg = 'with no common variables, every record type needs at least one variable ('
if @variables.find { |var| var.is_common_var }.nil?
@record_types.each do |rt|
next if get_vars_by_record_type(rt).size > 0
bad_metadata(msg + rt + ')')
end
end
end
if @data_structure == 'hier'
bad_metadata('no record type variable') if record_type_var.nil?
end
return if check[:minimal]
@variables.each do |v|
v.start_column = v.start_column.to_i
v.width = v.width.to_i
v.implied_decimals = v.implied_decimals.to_i
bad_metadata("#{v.name}, start_column" ) unless v.start_column > 0
bad_metadata("#{v.name}, width" ) unless v.width > 0
bad_metadata("#{v.name}, implied_decimals") unless v.implied_decimals >= 0
end
end | ruby | def validate_metadata (check = {})
bad_metadata('no variables') if @variables.empty?
if @rectangularize
msg = 'the rectangularize option requires data_structure=hier'
bad_metadata(msg) unless @data_structure == 'hier'
end
if @data_structure == 'hier' or @select_vars_by_record_type
bad_metadata('no record types') if @record_types.empty?
msg = 'record types must be unique'
bad_metadata(msg) unless rec_type_lookup_hash.keys.size == @record_types.size
msg = 'all variables must have a record type'
bad_metadata(msg) unless @variables.find { |var| var.record_type.length == 0 }.nil?
msg = 'with no common variables, every record type needs at least one variable ('
if @variables.find { |var| var.is_common_var }.nil?
@record_types.each do |rt|
next if get_vars_by_record_type(rt).size > 0
bad_metadata(msg + rt + ')')
end
end
end
if @data_structure == 'hier'
bad_metadata('no record type variable') if record_type_var.nil?
end
return if check[:minimal]
@variables.each do |v|
v.start_column = v.start_column.to_i
v.width = v.width.to_i
v.implied_decimals = v.implied_decimals.to_i
bad_metadata("#{v.name}, start_column" ) unless v.start_column > 0
bad_metadata("#{v.name}, width" ) unless v.width > 0
bad_metadata("#{v.name}, implied_decimals") unless v.implied_decimals >= 0
end
end | [
"def",
"validate_metadata",
"(",
"check",
"=",
"{",
"}",
")",
"bad_metadata",
"(",
"'no variables'",
")",
"if",
"@variables",
".",
"empty?",
"if",
"@rectangularize",
"msg",
"=",
"'the rectangularize option requires data_structure=hier'",
"bad_metadata",
"(",
"msg",
")... | Before generating syntax, run a sanity check on the metadata. | [
"Before",
"generating",
"syntax",
"run",
"a",
"sanity",
"check",
"on",
"the",
"metadata",
"."
] | 014e23a69f9a647f20eaffcf9e95016f98d5c17e | https://github.com/mnpopcenter/stats_package_syntax_file_generator/blob/014e23a69f9a647f20eaffcf9e95016f98d5c17e/lib/syntax_file/controller.rb#L276-L316 | valid |
mrcsparker/activerecord-jdbcteradata-adapter | lib/arjdbc/teradata/adapter.rb | ::ArJdbc.Teradata._execute | def _execute(sql, name = nil)
if self.class.select?(sql)
result = @connection.execute_query(sql)
result.map! do |r|
new_hash = {}
r.each_pair do |k, v|
new_hash.merge!({ k.downcase => v })
end
new_hash
end if self.class.lowercase_schema_reflection
result
elsif self.class.insert?(sql)
(@connection.execute_insert(sql) || last_insert_id(_table_name_from_insert(sql))).to_i
else
@connection.execute_update(sql)
end
end | ruby | def _execute(sql, name = nil)
if self.class.select?(sql)
result = @connection.execute_query(sql)
result.map! do |r|
new_hash = {}
r.each_pair do |k, v|
new_hash.merge!({ k.downcase => v })
end
new_hash
end if self.class.lowercase_schema_reflection
result
elsif self.class.insert?(sql)
(@connection.execute_insert(sql) || last_insert_id(_table_name_from_insert(sql))).to_i
else
@connection.execute_update(sql)
end
end | [
"def",
"_execute",
"(",
"sql",
",",
"name",
"=",
"nil",
")",
"if",
"self",
".",
"class",
".",
"select?",
"(",
"sql",
")",
"result",
"=",
"@connection",
".",
"execute_query",
"(",
"sql",
")",
"result",
".",
"map!",
"do",
"|",
"r",
"|",
"new_hash",
"... | - native_sql_to_type
- active?
- reconnect!
- disconnect!
- exec_query
- exec_insert
- exec_delete
- exec_update
+ do_exec
- execute | [
"-",
"native_sql_to_type",
"-",
"active?",
"-",
"reconnect!",
"-",
"disconnect!",
"-",
"exec_query",
"-",
"exec_insert",
"-",
"exec_delete",
"-",
"exec_update",
"+",
"do_exec",
"-",
"execute"
] | 4cad231a69ae13b82a5fecdecb10f243230690f6 | https://github.com/mrcsparker/activerecord-jdbcteradata-adapter/blob/4cad231a69ae13b82a5fecdecb10f243230690f6/lib/arjdbc/teradata/adapter.rb#L127-L143 | valid |
mrcsparker/activerecord-jdbcteradata-adapter | lib/arjdbc/teradata/adapter.rb | ::ArJdbc.Teradata.primary_keys | def primary_keys(table)
if self.class.lowercase_schema_reflection
@connection.primary_keys(table).map do |key|
key.downcase
end
else
@connection.primary_keys(table)
end
end | ruby | def primary_keys(table)
if self.class.lowercase_schema_reflection
@connection.primary_keys(table).map do |key|
key.downcase
end
else
@connection.primary_keys(table)
end
end | [
"def",
"primary_keys",
"(",
"table",
")",
"if",
"self",
".",
"class",
".",
"lowercase_schema_reflection",
"@connection",
".",
"primary_keys",
"(",
"table",
")",
".",
"map",
"do",
"|",
"key",
"|",
"key",
".",
"downcase",
"end",
"else",
"@connection",
".",
"... | - begin_db_transaction
- commit_db_transaction
- rollback_db_transaction
- begin_isolated_db_transaction
- supports_transaction_isolation?
- write_large_object
- pk_and_sequence_for
- primary_key
- primary_keys | [
"-",
"begin_db_transaction",
"-",
"commit_db_transaction",
"-",
"rollback_db_transaction",
"-",
"begin_isolated_db_transaction",
"-",
"supports_transaction_isolation?",
"-",
"write_large_object",
"-",
"pk_and_sequence_for",
"-",
"primary_key",
"-",
"primary_keys"
] | 4cad231a69ae13b82a5fecdecb10f243230690f6 | https://github.com/mrcsparker/activerecord-jdbcteradata-adapter/blob/4cad231a69ae13b82a5fecdecb10f243230690f6/lib/arjdbc/teradata/adapter.rb#L249-L257 | valid |
mrcsparker/activerecord-jdbcteradata-adapter | lib/arjdbc/teradata/adapter.rb | ::ArJdbc.Teradata.change_column | def change_column(table_name, column_name, type, options = {}) #:nodoc:
change_column_sql = "ALTER TABLE #{quote_table_name(table_name)} " <<
"ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit])}"
add_column_options!(change_column_sql, options)
execute(change_column_sql)
end | ruby | def change_column(table_name, column_name, type, options = {}) #:nodoc:
change_column_sql = "ALTER TABLE #{quote_table_name(table_name)} " <<
"ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit])}"
add_column_options!(change_column_sql, options)
execute(change_column_sql)
end | [
"def",
"change_column",
"(",
"table_name",
",",
"column_name",
",",
"type",
",",
"options",
"=",
"{",
"}",
")",
"change_column_sql",
"=",
"\"ALTER TABLE #{quote_table_name(table_name)} \"",
"<<",
"\"ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit])}\"",
... | + change_column
This only works in a VERY limited fashion. For example, VARCHAR columns
cannot be shortened, one column type cannot be converted to another. | [
"+",
"change_column",
"This",
"only",
"works",
"in",
"a",
"VERY",
"limited",
"fashion",
".",
"For",
"example",
"VARCHAR",
"columns",
"cannot",
"be",
"shortened",
"one",
"column",
"type",
"cannot",
"be",
"converted",
"to",
"another",
"."
] | 4cad231a69ae13b82a5fecdecb10f243230690f6 | https://github.com/mrcsparker/activerecord-jdbcteradata-adapter/blob/4cad231a69ae13b82a5fecdecb10f243230690f6/lib/arjdbc/teradata/adapter.rb#L298-L303 | valid |
mnpopcenter/stats_package_syntax_file_generator | lib/syntax_file/maker.rb | SyntaxFile.Maker.labelable_values | def labelable_values (var)
# For non-string variables, only values that look
# like integers can be labeled.
return var.values if var.is_string_var
var.values.find_all { |val| val.value.to_s =~ /^\-?\d+$/ }
end | ruby | def labelable_values (var)
# For non-string variables, only values that look
# like integers can be labeled.
return var.values if var.is_string_var
var.values.find_all { |val| val.value.to_s =~ /^\-?\d+$/ }
end | [
"def",
"labelable_values",
"(",
"var",
")",
"return",
"var",
".",
"values",
"if",
"var",
".",
"is_string_var",
"var",
".",
"values",
".",
"find_all",
"{",
"|",
"val",
"|",
"val",
".",
"value",
".",
"to_s",
"=~",
"/",
"\\-",
"\\d",
"/",
"}",
"end"
] | Helper methods for values and their labels. | [
"Helper",
"methods",
"for",
"values",
"and",
"their",
"labels",
"."
] | 014e23a69f9a647f20eaffcf9e95016f98d5c17e | https://github.com/mnpopcenter/stats_package_syntax_file_generator/blob/014e23a69f9a647f20eaffcf9e95016f98d5c17e/lib/syntax_file/maker.rb#L86-L91 | valid |
joseairosa/ohm-expire | lib/ohm/expire.rb | Ohm.Model.update_ttl | def update_ttl new_ttl=nil
# Load default if no new ttl is specified
new_ttl = self._default_expire if new_ttl.nil?
# Make sure we have a valid value
new_ttl = -1 if !new_ttl.to_i.is_a?(Fixnum) || new_ttl.to_i < 0
# Update indices
Ohm.redis.expire(self.key, new_ttl)
Ohm.redis.expire("#{self.key}:_indices", new_ttl)
end | ruby | def update_ttl new_ttl=nil
# Load default if no new ttl is specified
new_ttl = self._default_expire if new_ttl.nil?
# Make sure we have a valid value
new_ttl = -1 if !new_ttl.to_i.is_a?(Fixnum) || new_ttl.to_i < 0
# Update indices
Ohm.redis.expire(self.key, new_ttl)
Ohm.redis.expire("#{self.key}:_indices", new_ttl)
end | [
"def",
"update_ttl",
"new_ttl",
"=",
"nil",
"new_ttl",
"=",
"self",
".",
"_default_expire",
"if",
"new_ttl",
".",
"nil?",
"new_ttl",
"=",
"-",
"1",
"if",
"!",
"new_ttl",
".",
"to_i",
".",
"is_a?",
"(",
"Fixnum",
")",
"||",
"new_ttl",
".",
"to_i",
"<",
... | Update the ttl
==== Attributes
* +new_ttl <i>Fixnum</i>+ - The new expire amount. If nil, value will fallback to default expire
==== Returns
* nil
==== Examples
d = Model.create(:hash => "123")
d.update_ttl(30) | [
"Update",
"the",
"ttl"
] | 979cc9252baefcf77aa56a5cbf85fba5cf98cf76 | https://github.com/joseairosa/ohm-expire/blob/979cc9252baefcf77aa56a5cbf85fba5cf98cf76/lib/ohm/expire.rb#L107-L115 | valid |
gregory/sipwizard | lib/sipwizard/relation.rb | Sipwizard.Relation.hash_to_query | def hash_to_query(h)
h = Hash[h.map{|k,v| [k, "\"#{v}\""]}]
Rack::Utils.unescape Rack::Utils.build_query(h)
end | ruby | def hash_to_query(h)
h = Hash[h.map{|k,v| [k, "\"#{v}\""]}]
Rack::Utils.unescape Rack::Utils.build_query(h)
end | [
"def",
"hash_to_query",
"(",
"h",
")",
"h",
"=",
"Hash",
"[",
"h",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"[",
"k",
",",
"\"\\\"#{v}\\\"\"",
"]",
"}",
"]",
"Rack",
"::",
"Utils",
".",
"unescape",
"Rack",
"::",
"Utils",
".",
"build_query",
"(",... | Hack to comply with the api spec ... which sucks | [
"Hack",
"to",
"comply",
"with",
"the",
"api",
"spec",
"...",
"which",
"sucks"
] | 93751f507ced2ba5aafa28dd25c8c6a3a20ea955 | https://github.com/gregory/sipwizard/blob/93751f507ced2ba5aafa28dd25c8c6a3a20ea955/lib/sipwizard/relation.rb#L22-L25 | valid |
gouravtiwari/akamai-cloudlet-manager | lib/akamai_cloudlet_manager/policy_version.rb | AkamaiCloudletManager.PolicyVersion.existing_rules | def existing_rules
request = Net::HTTP::Get.new URI.join(@base_uri.to_s, "cloudlets/api/v2/policies/#{@policy_id}/versions/#{@version_id}?omitRules=false&matchRuleFormat=1.0").to_s
response = @http_host.request(request)
response.body
end | ruby | def existing_rules
request = Net::HTTP::Get.new URI.join(@base_uri.to_s, "cloudlets/api/v2/policies/#{@policy_id}/versions/#{@version_id}?omitRules=false&matchRuleFormat=1.0").to_s
response = @http_host.request(request)
response.body
end | [
"def",
"existing_rules",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"URI",
".",
"join",
"(",
"@base_uri",
".",
"to_s",
",",
"\"cloudlets/api/v2/policies/#{@policy_id}/versions/#{@version_id}?omitRules=false&matchRuleFormat=1.0\"",
")",
".",
"to_s",
"r... | Get Policy version's rules | [
"Get",
"Policy",
"version",
"s",
"rules"
] | 03ef8a19065bdd1998550071be07b872b643715a | https://github.com/gouravtiwari/akamai-cloudlet-manager/blob/03ef8a19065bdd1998550071be07b872b643715a/lib/akamai_cloudlet_manager/policy_version.rb#L10-L14 | valid |
gouravtiwari/akamai-cloudlet-manager | lib/akamai_cloudlet_manager/policy_version.rb | AkamaiCloudletManager.PolicyVersion.create | def create(clone_from_version_id)
request = Net::HTTP::Post.new(
URI.join(
@base_uri.to_s,
"cloudlets/api/v2/policies/#{@policy_id}/versions?includeRules=false&matchRuleFormat=1.0&cloneVersion=#{clone_from_version_id}"
).to_s,
{ 'Content-Type' => 'application/json'}
)
response = @http_host.request(request)
response.body
end | ruby | def create(clone_from_version_id)
request = Net::HTTP::Post.new(
URI.join(
@base_uri.to_s,
"cloudlets/api/v2/policies/#{@policy_id}/versions?includeRules=false&matchRuleFormat=1.0&cloneVersion=#{clone_from_version_id}"
).to_s,
{ 'Content-Type' => 'application/json'}
)
response = @http_host.request(request)
response.body
end | [
"def",
"create",
"(",
"clone_from_version_id",
")",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"URI",
".",
"join",
"(",
"@base_uri",
".",
"to_s",
",",
"\"cloudlets/api/v2/policies/#{@policy_id}/versions?includeRules=false&matchRuleFormat=1.0&clo... | Create a policy version | [
"Create",
"a",
"policy",
"version"
] | 03ef8a19065bdd1998550071be07b872b643715a | https://github.com/gouravtiwari/akamai-cloudlet-manager/blob/03ef8a19065bdd1998550071be07b872b643715a/lib/akamai_cloudlet_manager/policy_version.rb#L28-L38 | valid |
gouravtiwari/akamai-cloudlet-manager | lib/akamai_cloudlet_manager/policy_version.rb | AkamaiCloudletManager.PolicyVersion.activate | def activate(network)
request = Net::HTTP::Post.new(
URI.join(
@base_uri.to_s,
"/cloudlets/api/v2/policies/#{@policy_id}/versions/#{@version_id}/activations"
).to_s,
{ 'Content-Type' => 'application/json'}
)
request.body = {
"network": network
}.to_json
response = @http_host.request(request)
response.body
end | ruby | def activate(network)
request = Net::HTTP::Post.new(
URI.join(
@base_uri.to_s,
"/cloudlets/api/v2/policies/#{@policy_id}/versions/#{@version_id}/activations"
).to_s,
{ 'Content-Type' => 'application/json'}
)
request.body = {
"network": network
}.to_json
response = @http_host.request(request)
response.body
end | [
"def",
"activate",
"(",
"network",
")",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"URI",
".",
"join",
"(",
"@base_uri",
".",
"to_s",
",",
"\"/cloudlets/api/v2/policies/#{@policy_id}/versions/#{@version_id}/activations\"",
")",
".",
"to_s"... | Activate a policy version | [
"Activate",
"a",
"policy",
"version"
] | 03ef8a19065bdd1998550071be07b872b643715a | https://github.com/gouravtiwari/akamai-cloudlet-manager/blob/03ef8a19065bdd1998550071be07b872b643715a/lib/akamai_cloudlet_manager/policy_version.rb#L41-L54 | valid |
gouravtiwari/akamai-cloudlet-manager | lib/akamai_cloudlet_manager/policy_version.rb | AkamaiCloudletManager.PolicyVersion.update | def update(options = {}, existing_rules = [])
request = Net::HTTP::Put.new(
URI.join(@base_uri.to_s, "cloudlets/api/v2/policies/#{@policy_id}/versions/#{@version_id}?omitRules=false&matchRuleFormat=1.0").to_s,
{ 'Content-Type' => 'application/json'}
)
rules = generate_path_rules(options) + generate_cookie_rules(options) + existing_rules
if rules.empty?
puts "No rules to apply, please check syntax"
return
end
request.body = {
matchRules: rules
}.to_json
response = @http_host.request(request)
response.body
end | ruby | def update(options = {}, existing_rules = [])
request = Net::HTTP::Put.new(
URI.join(@base_uri.to_s, "cloudlets/api/v2/policies/#{@policy_id}/versions/#{@version_id}?omitRules=false&matchRuleFormat=1.0").to_s,
{ 'Content-Type' => 'application/json'}
)
rules = generate_path_rules(options) + generate_cookie_rules(options) + existing_rules
if rules.empty?
puts "No rules to apply, please check syntax"
return
end
request.body = {
matchRules: rules
}.to_json
response = @http_host.request(request)
response.body
end | [
"def",
"update",
"(",
"options",
"=",
"{",
"}",
",",
"existing_rules",
"=",
"[",
"]",
")",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Put",
".",
"new",
"(",
"URI",
".",
"join",
"(",
"@base_uri",
".",
"to_s",
",",
"\"cloudlets/api/v2/policies/#{@policy_i... | Update policy version, all rules | [
"Update",
"policy",
"version",
"all",
"rules"
] | 03ef8a19065bdd1998550071be07b872b643715a | https://github.com/gouravtiwari/akamai-cloudlet-manager/blob/03ef8a19065bdd1998550071be07b872b643715a/lib/akamai_cloudlet_manager/policy_version.rb#L66-L84 | valid |
gouravtiwari/akamai-cloudlet-manager | lib/akamai_cloudlet_manager/origin.rb | AkamaiCloudletManager.Origin.list | def list(type)
request = Net::HTTP::Get.new URI.join(@base_uri.to_s, "cloudlets/api/v2/origins?type=#{type}").to_s
response = @http_host.request(request)
response.body
end | ruby | def list(type)
request = Net::HTTP::Get.new URI.join(@base_uri.to_s, "cloudlets/api/v2/origins?type=#{type}").to_s
response = @http_host.request(request)
response.body
end | [
"def",
"list",
"(",
"type",
")",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"URI",
".",
"join",
"(",
"@base_uri",
".",
"to_s",
",",
"\"cloudlets/api/v2/origins?type=#{type}\"",
")",
".",
"to_s",
"response",
"=",
"@http_host",
".",
"reque... | List cloudlet Origins
@type this is origin type, e.g. APPLICATION_LOAD_BALANCER | [
"List",
"cloudlet",
"Origins"
] | 03ef8a19065bdd1998550071be07b872b643715a | https://github.com/gouravtiwari/akamai-cloudlet-manager/blob/03ef8a19065bdd1998550071be07b872b643715a/lib/akamai_cloudlet_manager/origin.rb#L5-L9 | valid |
LucasAndrad/InoxConverter | lib/inox_converter/converter.rb | InoxConverter.Converter.convert | def convert(valueToConvert, firstUnit, secondUnit)
# First Step
finalValue = valueToConvert.round(10)
# Second Step
firstUnitResultant = getInDictionary(firstUnit)
if firstUnitResultant.nil?
raise NotImplementedError.new("#{firstUnit} isn't recognized by InoxConverter")
end
finalValue *= firstUnitResultant.round(10)
# Third step
secondUnitResultant = getInDictionary(secondUnit)
if secondUnitResultant.nil?
raise NotImplementedError.new("#{secondUnit} isn't recognized by InoxConverter")
end
finalValue /= secondUnitResultant.round(10)
# Fourth step
return finalValue.round(10)
end | ruby | def convert(valueToConvert, firstUnit, secondUnit)
# First Step
finalValue = valueToConvert.round(10)
# Second Step
firstUnitResultant = getInDictionary(firstUnit)
if firstUnitResultant.nil?
raise NotImplementedError.new("#{firstUnit} isn't recognized by InoxConverter")
end
finalValue *= firstUnitResultant.round(10)
# Third step
secondUnitResultant = getInDictionary(secondUnit)
if secondUnitResultant.nil?
raise NotImplementedError.new("#{secondUnit} isn't recognized by InoxConverter")
end
finalValue /= secondUnitResultant.round(10)
# Fourth step
return finalValue.round(10)
end | [
"def",
"convert",
"(",
"valueToConvert",
",",
"firstUnit",
",",
"secondUnit",
")",
"finalValue",
"=",
"valueToConvert",
".",
"round",
"(",
"10",
")",
"firstUnitResultant",
"=",
"getInDictionary",
"(",
"firstUnit",
")",
"if",
"firstUnitResultant",
".",
"nil?",
"r... | Template to convert | [
"Template",
"to",
"convert"
] | c7dd8ac2c6ee8f9447b6302ec7ba8b3a55d4e6a3 | https://github.com/LucasAndrad/InoxConverter/blob/c7dd8ac2c6ee8f9447b6302ec7ba8b3a55d4e6a3/lib/inox_converter/converter.rb#L13-L33 | valid |
mmb/meme_captain | lib/meme_captain/caption.rb | MemeCaptain.Caption.wrap | def wrap(num_lines)
cleaned = gsub(/\s+/, ' ').strip
chars_per_line = cleaned.size / num_lines.to_f
lines = []
cleaned.split.each do |word|
if lines.empty?
lines << word
else
if (lines[-1].size + 1 + word.size) <= chars_per_line ||
lines.size >= num_lines
lines[-1] << ' ' unless lines[-1].empty?
lines[-1] << word
else
lines << word
end
end
end
Caption.new(lines.join("\n"))
end | ruby | def wrap(num_lines)
cleaned = gsub(/\s+/, ' ').strip
chars_per_line = cleaned.size / num_lines.to_f
lines = []
cleaned.split.each do |word|
if lines.empty?
lines << word
else
if (lines[-1].size + 1 + word.size) <= chars_per_line ||
lines.size >= num_lines
lines[-1] << ' ' unless lines[-1].empty?
lines[-1] << word
else
lines << word
end
end
end
Caption.new(lines.join("\n"))
end | [
"def",
"wrap",
"(",
"num_lines",
")",
"cleaned",
"=",
"gsub",
"(",
"/",
"\\s",
"/",
",",
"' '",
")",
".",
"strip",
"chars_per_line",
"=",
"cleaned",
".",
"size",
"/",
"num_lines",
".",
"to_f",
"lines",
"=",
"[",
"]",
"cleaned",
".",
"split",
".",
"... | Wrap the string of into num_lines lines. | [
"Wrap",
"the",
"string",
"of",
"into",
"num_lines",
"lines",
"."
] | daa7ac8244916562378d37820dad21ee01b89d71 | https://github.com/mmb/meme_captain/blob/daa7ac8244916562378d37820dad21ee01b89d71/lib/meme_captain/caption.rb#L25-L46 | valid |
LucasAndrad/InoxConverter | lib/inox_converter/api/api.rb | Api.Api.consume_api | def consume_api
@dados = RestClient::Request.execute(method: :get, url: 'https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote')
hash_local = Hash.new
@hash_local = Hash.from_xml(@dados)
end | ruby | def consume_api
@dados = RestClient::Request.execute(method: :get, url: 'https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote')
hash_local = Hash.new
@hash_local = Hash.from_xml(@dados)
end | [
"def",
"consume_api",
"@dados",
"=",
"RestClient",
"::",
"Request",
".",
"execute",
"(",
"method",
":",
":get",
",",
"url",
":",
"'https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote'",
")",
"hash_local",
"=",
"Hash",
".",
"new",
"@hash_local",
"=",
... | Consuming yahoo finances api and transform in hash for ruby | [
"Consuming",
"yahoo",
"finances",
"api",
"and",
"transform",
"in",
"hash",
"for",
"ruby"
] | c7dd8ac2c6ee8f9447b6302ec7ba8b3a55d4e6a3 | https://github.com/LucasAndrad/InoxConverter/blob/c7dd8ac2c6ee8f9447b6302ec7ba8b3a55d4e6a3/lib/inox_converter/api/api.rb#L10-L14 | valid |
LucasAndrad/InoxConverter | lib/inox_converter/api/api.rb | Api.Api.treat_data | def treat_data
@hash_inter = Hash.new
@hash = Hash.new
if validate_api_return
@hash_inter = @hash_local['list']['resources']['resource']
@hash_inter.each do |cout|
simbol_string = cout['field'][0].to_s
simbol = simbol_string.split("/")
@hash[simbol[1]] = cout['field'][1].to_f
end
else
@data = false
end
end | ruby | def treat_data
@hash_inter = Hash.new
@hash = Hash.new
if validate_api_return
@hash_inter = @hash_local['list']['resources']['resource']
@hash_inter.each do |cout|
simbol_string = cout['field'][0].to_s
simbol = simbol_string.split("/")
@hash[simbol[1]] = cout['field'][1].to_f
end
else
@data = false
end
end | [
"def",
"treat_data",
"@hash_inter",
"=",
"Hash",
".",
"new",
"@hash",
"=",
"Hash",
".",
"new",
"if",
"validate_api_return",
"@hash_inter",
"=",
"@hash_local",
"[",
"'list'",
"]",
"[",
"'resources'",
"]",
"[",
"'resource'",
"]",
"@hash_inter",
".",
"each",
"d... | Treating data in hash | [
"Treating",
"data",
"in",
"hash"
] | c7dd8ac2c6ee8f9447b6302ec7ba8b3a55d4e6a3 | https://github.com/LucasAndrad/InoxConverter/blob/c7dd8ac2c6ee8f9447b6302ec7ba8b3a55d4e6a3/lib/inox_converter/api/api.rb#L17-L30 | valid |
LucasAndrad/InoxConverter | lib/inox_converter/api/api.rb | Api.Api.convert_currency | def convert_currency(valueToConvert, firstUnit, secondUnit)
dictionary_api
if validate_usd_unit(firstUnit) && validate_usd_unit(secondUnit)
return valueToConvert
elsif validate_usd_unit(firstUnit) && validate_usd_unit(secondUnit) == false
if validate_currency_unit(secondUnit)
finalValue = valueToConvert * @hash[secondUnit]
return finalValue
else
return 0
end
elsif validate_usd_unit(firstUnit) == false && validate_usd_unit(secondUnit)
if validate_currency_unit(firstUnit)
finalValue = valueToConvert / @hash[firstUnit]
return finalValue
else
return 0
end
else
if data_validate_api(firstUnit, secondUnit)
finalValue = (valueToConvert / @hash[firstUnit]) * @hash[secondUnit]
return finalValue
else
return 0
end
end
end | ruby | def convert_currency(valueToConvert, firstUnit, secondUnit)
dictionary_api
if validate_usd_unit(firstUnit) && validate_usd_unit(secondUnit)
return valueToConvert
elsif validate_usd_unit(firstUnit) && validate_usd_unit(secondUnit) == false
if validate_currency_unit(secondUnit)
finalValue = valueToConvert * @hash[secondUnit]
return finalValue
else
return 0
end
elsif validate_usd_unit(firstUnit) == false && validate_usd_unit(secondUnit)
if validate_currency_unit(firstUnit)
finalValue = valueToConvert / @hash[firstUnit]
return finalValue
else
return 0
end
else
if data_validate_api(firstUnit, secondUnit)
finalValue = (valueToConvert / @hash[firstUnit]) * @hash[secondUnit]
return finalValue
else
return 0
end
end
end | [
"def",
"convert_currency",
"(",
"valueToConvert",
",",
"firstUnit",
",",
"secondUnit",
")",
"dictionary_api",
"if",
"validate_usd_unit",
"(",
"firstUnit",
")",
"&&",
"validate_usd_unit",
"(",
"secondUnit",
")",
"return",
"valueToConvert",
"elsif",
"validate_usd_unit",
... | new metodo for convert currency | [
"new",
"metodo",
"for",
"convert",
"currency"
] | c7dd8ac2c6ee8f9447b6302ec7ba8b3a55d4e6a3 | https://github.com/LucasAndrad/InoxConverter/blob/c7dd8ac2c6ee8f9447b6302ec7ba8b3a55d4e6a3/lib/inox_converter/api/api.rb#L82-L108 | valid |
mynyml/holygrail | lib/holygrail.rb | HolyGrail.XhrProxy.request | def request(info, data="")
context.instance_eval do
xhr(info["method"].downcase, info["url"], data)
@response.body.to_s
end
end | ruby | def request(info, data="")
context.instance_eval do
xhr(info["method"].downcase, info["url"], data)
@response.body.to_s
end
end | [
"def",
"request",
"(",
"info",
",",
"data",
"=",
"\"\"",
")",
"context",
".",
"instance_eval",
"do",
"xhr",
"(",
"info",
"[",
"\"method\"",
"]",
".",
"downcase",
",",
"info",
"[",
"\"url\"",
"]",
",",
"data",
")",
"@response",
".",
"body",
".",
"to_s... | Surrogate ajax request | [
"Surrogate",
"ajax",
"request"
] | 0c6ef60f18c3e032c9bee74867b0e5a26028e05d | https://github.com/mynyml/holygrail/blob/0c6ef60f18c3e032c9bee74867b0e5a26028e05d/lib/holygrail.rb#L15-L20 | valid |
mynyml/holygrail | lib/holygrail.rb | HolyGrail.Extensions.js | def js(code)
XhrProxy.context = self
@__page ||= Harmony::Page.new(XHR_MOCK_SCRIPT + rewrite_script_paths(@response.body.to_s))
Harmony::Page::Window::BASE_RUNTIME.wait
@__page.execute_js(code)
end | ruby | def js(code)
XhrProxy.context = self
@__page ||= Harmony::Page.new(XHR_MOCK_SCRIPT + rewrite_script_paths(@response.body.to_s))
Harmony::Page::Window::BASE_RUNTIME.wait
@__page.execute_js(code)
end | [
"def",
"js",
"(",
"code",
")",
"XhrProxy",
".",
"context",
"=",
"self",
"@__page",
"||=",
"Harmony",
"::",
"Page",
".",
"new",
"(",
"XHR_MOCK_SCRIPT",
"+",
"rewrite_script_paths",
"(",
"@response",
".",
"body",
".",
"to_s",
")",
")",
"Harmony",
"::",
"Pa... | Execute javascript within the context of a view.
@example
class PeopleControllerTest < ActionController::TestCase
get :index
assert_equal 'People: index', js('document.title')
end
@param [String]
code javascript code to evaluate
@return [Object]
value of last javascript statement, cast to an equivalent ruby object
@raise [Johnson::Error]
javascript code exception | [
"Execute",
"javascript",
"within",
"the",
"context",
"of",
"a",
"view",
"."
] | 0c6ef60f18c3e032c9bee74867b0e5a26028e05d | https://github.com/mynyml/holygrail/blob/0c6ef60f18c3e032c9bee74867b0e5a26028e05d/lib/holygrail.rb#L77-L82 | valid |
mmb/meme_captain | lib/meme_captain/draw.rb | MemeCaptain.Draw.calc_pointsize | def calc_pointsize(width, height, text, min_pointsize)
current_pointsize = min_pointsize
metrics = nil
loop {
self.pointsize = current_pointsize
last_metrics = metrics
metrics = get_multiline_type_metrics(text)
if metrics.width + stroke_padding > width or
metrics.height + stroke_padding > height
if current_pointsize > min_pointsize
current_pointsize -= 1
metrics = last_metrics
end
break
else
current_pointsize += 1
end
}
[current_pointsize, metrics]
end | ruby | def calc_pointsize(width, height, text, min_pointsize)
current_pointsize = min_pointsize
metrics = nil
loop {
self.pointsize = current_pointsize
last_metrics = metrics
metrics = get_multiline_type_metrics(text)
if metrics.width + stroke_padding > width or
metrics.height + stroke_padding > height
if current_pointsize > min_pointsize
current_pointsize -= 1
metrics = last_metrics
end
break
else
current_pointsize += 1
end
}
[current_pointsize, metrics]
end | [
"def",
"calc_pointsize",
"(",
"width",
",",
"height",
",",
"text",
",",
"min_pointsize",
")",
"current_pointsize",
"=",
"min_pointsize",
"metrics",
"=",
"nil",
"loop",
"{",
"self",
".",
"pointsize",
"=",
"current_pointsize",
"last_metrics",
"=",
"metrics",
"metr... | Calculate the largest pointsize for text that will be in a width x
height box.
Return [pointsize, metrics] where pointsize is the largest pointsize and
metrics is the RMagick multiline type metrics of the best fit. | [
"Calculate",
"the",
"largest",
"pointsize",
"for",
"text",
"that",
"will",
"be",
"in",
"a",
"width",
"x",
"height",
"box",
"."
] | daa7ac8244916562378d37820dad21ee01b89d71 | https://github.com/mmb/meme_captain/blob/daa7ac8244916562378d37820dad21ee01b89d71/lib/meme_captain/draw.rb#L11-L34 | valid |
LucasAndrad/InoxConverter | lib/inox_converter/currency_adapter.rb | InoxConverter.CurrencyAdapter.convert | def convert(valueToConvert, firstUnit, secondUnit)
@api = Api::Api.new
@api.convert_currency(valueToConvert, firstUnit, secondUnit)
end | ruby | def convert(valueToConvert, firstUnit, secondUnit)
@api = Api::Api.new
@api.convert_currency(valueToConvert, firstUnit, secondUnit)
end | [
"def",
"convert",
"(",
"valueToConvert",
",",
"firstUnit",
",",
"secondUnit",
")",
"@api",
"=",
"Api",
"::",
"Api",
".",
"new",
"@api",
".",
"convert_currency",
"(",
"valueToConvert",
",",
"firstUnit",
",",
"secondUnit",
")",
"end"
] | subscrible of metod convert in adapter | [
"subscrible",
"of",
"metod",
"convert",
"in",
"adapter"
] | c7dd8ac2c6ee8f9447b6302ec7ba8b3a55d4e6a3 | https://github.com/LucasAndrad/InoxConverter/blob/c7dd8ac2c6ee8f9447b6302ec7ba8b3a55d4e6a3/lib/inox_converter/currency_adapter.rb#L9-L12 | valid |
ordinaryzelig/entrez | lib/entrez/query_limit.rb | Entrez.QueryLimit.respect_query_limit | def respect_query_limit
now = Time.now.to_f
three_requests_ago = request_times[-3]
request_times << now
return unless three_requests_ago
time_for_last_3_requeests = now - three_requests_ago
enough_time_has_passed = time_for_last_3_requeests >= 1.0
unless enough_time_has_passed
sleep_time = 1 - time_for_last_3_requeests
STDERR.puts "sleeping #{sleep_time}"
sleep(sleep_time)
end
end | ruby | def respect_query_limit
now = Time.now.to_f
three_requests_ago = request_times[-3]
request_times << now
return unless three_requests_ago
time_for_last_3_requeests = now - three_requests_ago
enough_time_has_passed = time_for_last_3_requeests >= 1.0
unless enough_time_has_passed
sleep_time = 1 - time_for_last_3_requeests
STDERR.puts "sleeping #{sleep_time}"
sleep(sleep_time)
end
end | [
"def",
"respect_query_limit",
"now",
"=",
"Time",
".",
"now",
".",
"to_f",
"three_requests_ago",
"=",
"request_times",
"[",
"-",
"3",
"]",
"request_times",
"<<",
"now",
"return",
"unless",
"three_requests_ago",
"time_for_last_3_requeests",
"=",
"now",
"-",
"three_... | NCBI does not allow more than 3 requests per second.
If the last 3 requests happened within the last 1 second,
sleep for enough time to let a full 1 second pass before the next request.
Add current time to queue. | [
"NCBI",
"does",
"not",
"allow",
"more",
"than",
"3",
"requests",
"per",
"second",
".",
"If",
"the",
"last",
"3",
"requests",
"happened",
"within",
"the",
"last",
"1",
"second",
"sleep",
"for",
"enough",
"time",
"to",
"let",
"a",
"full",
"1",
"second",
... | cbed68ae3f432f476f5335910d6f04279acfdb1a | https://github.com/ordinaryzelig/entrez/blob/cbed68ae3f432f476f5335910d6f04279acfdb1a/lib/entrez/query_limit.rb#L10-L22 | valid |
govdelivery/jekyll-ramler | lib/utils.rb | Jekyll.RamlSchemaGenerator.insert_schemas | def insert_schemas(obj)
if obj.is_a?(Array)
obj.map!{|method| insert_schemas(method)}
elsif obj.is_a?(Hash)
@current_method = obj['method'] if obj.include?('method')
obj.each { |k, v| obj[k] = insert_schemas(v)}
if obj.include?('body')
if obj['body'].fetch('application/x-www-form-urlencoded', {}).include?('formParameters')
if insert_json_schema?(obj)
insert_json_schema(obj, generate_json_schema(obj))
end
end
end
end
obj
end | ruby | def insert_schemas(obj)
if obj.is_a?(Array)
obj.map!{|method| insert_schemas(method)}
elsif obj.is_a?(Hash)
@current_method = obj['method'] if obj.include?('method')
obj.each { |k, v| obj[k] = insert_schemas(v)}
if obj.include?('body')
if obj['body'].fetch('application/x-www-form-urlencoded', {}).include?('formParameters')
if insert_json_schema?(obj)
insert_json_schema(obj, generate_json_schema(obj))
end
end
end
end
obj
end | [
"def",
"insert_schemas",
"(",
"obj",
")",
"if",
"obj",
".",
"is_a?",
"(",
"Array",
")",
"obj",
".",
"map!",
"{",
"|",
"method",
"|",
"insert_schemas",
"(",
"method",
")",
"}",
"elsif",
"obj",
".",
"is_a?",
"(",
"Hash",
")",
"@current_method",
"=",
"o... | Creates a schema attribute sibling of any formParameter attribute found,
based on the found formParameters attribute.
Existing schema siblings of formParameter attributes are not modified.
Modifys obj, and returns the modified obj | [
"Creates",
"a",
"schema",
"attribute",
"sibling",
"of",
"any",
"formParameter",
"attribute",
"found",
"based",
"on",
"the",
"found",
"formParameters",
"attribute",
"."
] | 8415d0d3a5a742fb88c47799326f0f470bc3d6fe | https://github.com/govdelivery/jekyll-ramler/blob/8415d0d3a5a742fb88c47799326f0f470bc3d6fe/lib/utils.rb#L39-L57 | valid |
brendanhay/amqp-subscribe-many | lib/messaging/client.rb | Messaging.Client.declare_exchange | def declare_exchange(channel, name, type, options = {})
exchange =
# Check if default options need to be supplied to a non-default delcaration
if default_exchange?(name)
channel.default_exchange
else
channel.send(type, name, options)
end
log.debug("Exchange #{exchange.name.inspect} declared")
exchange
end | ruby | def declare_exchange(channel, name, type, options = {})
exchange =
# Check if default options need to be supplied to a non-default delcaration
if default_exchange?(name)
channel.default_exchange
else
channel.send(type, name, options)
end
log.debug("Exchange #{exchange.name.inspect} declared")
exchange
end | [
"def",
"declare_exchange",
"(",
"channel",
",",
"name",
",",
"type",
",",
"options",
"=",
"{",
"}",
")",
"exchange",
"=",
"if",
"default_exchange?",
"(",
"name",
")",
"channel",
".",
"default_exchange",
"else",
"channel",
".",
"send",
"(",
"type",
",",
"... | Declare an exchange on the specified channel.
@param channel [AMQP::Channel]
@param name [String]
@param type [String]
@param options [Hash]
@return [AMQP::Exchange]
@api public | [
"Declare",
"an",
"exchange",
"on",
"the",
"specified",
"channel",
"."
] | 6832204579ae46c2bd8703977682750f21bdf74e | https://github.com/brendanhay/amqp-subscribe-many/blob/6832204579ae46c2bd8703977682750f21bdf74e/lib/messaging/client.rb#L91-L103 | valid |
brendanhay/amqp-subscribe-many | lib/messaging/client.rb | Messaging.Client.declare_queue | def declare_queue(channel, exchange, name, key, options = {})
channel.queue(name, options) do |queue|
# Check if additional bindings are needed
unless default_exchange?(exchange.name)
queue.bind(exchange, { :routing_key => key })
end
log.debug("Queue #{queue.name.inspect} bound to #{exchange.name.inspect}")
end
end | ruby | def declare_queue(channel, exchange, name, key, options = {})
channel.queue(name, options) do |queue|
# Check if additional bindings are needed
unless default_exchange?(exchange.name)
queue.bind(exchange, { :routing_key => key })
end
log.debug("Queue #{queue.name.inspect} bound to #{exchange.name.inspect}")
end
end | [
"def",
"declare_queue",
"(",
"channel",
",",
"exchange",
",",
"name",
",",
"key",
",",
"options",
"=",
"{",
"}",
")",
"channel",
".",
"queue",
"(",
"name",
",",
"options",
")",
"do",
"|",
"queue",
"|",
"unless",
"default_exchange?",
"(",
"exchange",
".... | Declare and bind a queue to the specified exchange via the
supplied routing key.
@param channel [AMQP::Channel]
@param exchange [AMQP::Exchange]
@param name [String]
@param key [String]
@param options [Hash]
@return [AMQP::Queue]
@api public | [
"Declare",
"and",
"bind",
"a",
"queue",
"to",
"the",
"specified",
"exchange",
"via",
"the",
"supplied",
"routing",
"key",
"."
] | 6832204579ae46c2bd8703977682750f21bdf74e | https://github.com/brendanhay/amqp-subscribe-many/blob/6832204579ae46c2bd8703977682750f21bdf74e/lib/messaging/client.rb#L115-L124 | valid |
brendanhay/amqp-subscribe-many | lib/messaging/client.rb | Messaging.Client.disconnect | def disconnect
channels.each do |chan|
chan.close
end
connections.each do |conn|
conn.disconnect
end
end | ruby | def disconnect
channels.each do |chan|
chan.close
end
connections.each do |conn|
conn.disconnect
end
end | [
"def",
"disconnect",
"channels",
".",
"each",
"do",
"|",
"chan",
"|",
"chan",
".",
"close",
"end",
"connections",
".",
"each",
"do",
"|",
"conn",
"|",
"conn",
".",
"disconnect",
"end",
"end"
] | Close all channels and then disconnect all the connections.
@return []
@api public | [
"Close",
"all",
"channels",
"and",
"then",
"disconnect",
"all",
"the",
"connections",
"."
] | 6832204579ae46c2bd8703977682750f21bdf74e | https://github.com/brendanhay/amqp-subscribe-many/blob/6832204579ae46c2bd8703977682750f21bdf74e/lib/messaging/client.rb#L130-L138 | valid |
postmodern/env | lib/env/variables.rb | Env.Variables.home | def home
# logic adapted from Gem.find_home.
path = if (env['HOME'] || env['USERPROFILE'])
env['HOME'] || env['USERPROFILE']
elsif (env['HOMEDRIVE'] && env['HOMEPATH'])
"#{env['HOMEDRIVE']}#{env['HOMEPATH']}"
else
begin
File.expand_path('~')
rescue
if File::ALT_SEPARATOR
'C:/'
else
'/'
end
end
end
return Pathname.new(path)
end | ruby | def home
# logic adapted from Gem.find_home.
path = if (env['HOME'] || env['USERPROFILE'])
env['HOME'] || env['USERPROFILE']
elsif (env['HOMEDRIVE'] && env['HOMEPATH'])
"#{env['HOMEDRIVE']}#{env['HOMEPATH']}"
else
begin
File.expand_path('~')
rescue
if File::ALT_SEPARATOR
'C:/'
else
'/'
end
end
end
return Pathname.new(path)
end | [
"def",
"home",
"path",
"=",
"if",
"(",
"env",
"[",
"'HOME'",
"]",
"||",
"env",
"[",
"'USERPROFILE'",
"]",
")",
"env",
"[",
"'HOME'",
"]",
"||",
"env",
"[",
"'USERPROFILE'",
"]",
"elsif",
"(",
"env",
"[",
"'HOMEDRIVE'",
"]",
"&&",
"env",
"[",
"'HOME... | The home directory.
@return [Pathname]
The path of the home directory. | [
"The",
"home",
"directory",
"."
] | f3c76e432320f6134c0e34d3906502290e0aa145 | https://github.com/postmodern/env/blob/f3c76e432320f6134c0e34d3906502290e0aa145/lib/env/variables.rb#L69-L88 | valid |
postmodern/env | lib/env/variables.rb | Env.Variables.parse_paths | def parse_paths(paths)
if paths
paths.split(File::PATH_SEPARATOR).map do |path|
Pathname.new(path)
end
else
[]
end
end | ruby | def parse_paths(paths)
if paths
paths.split(File::PATH_SEPARATOR).map do |path|
Pathname.new(path)
end
else
[]
end
end | [
"def",
"parse_paths",
"(",
"paths",
")",
"if",
"paths",
"paths",
".",
"split",
"(",
"File",
"::",
"PATH_SEPARATOR",
")",
".",
"map",
"do",
"|",
"path",
"|",
"Pathname",
".",
"new",
"(",
"path",
")",
"end",
"else",
"[",
"]",
"end",
"end"
] | Parses a String containing multiple paths.
@return [Array<Pathname>]
The multiple paths. | [
"Parses",
"a",
"String",
"containing",
"multiple",
"paths",
"."
] | f3c76e432320f6134c0e34d3906502290e0aa145 | https://github.com/postmodern/env/blob/f3c76e432320f6134c0e34d3906502290e0aa145/lib/env/variables.rb#L206-L214 | valid |
sealink/timely | lib/timely/week_days.rb | Timely.WeekDays.weekdays_int | def weekdays_int
int = 0
WEEKDAY_KEYS.each.with_index do |day, index|
int += 2 ** index if @weekdays[day]
end
int
end | ruby | def weekdays_int
int = 0
WEEKDAY_KEYS.each.with_index do |day, index|
int += 2 ** index if @weekdays[day]
end
int
end | [
"def",
"weekdays_int",
"int",
"=",
"0",
"WEEKDAY_KEYS",
".",
"each",
".",
"with_index",
"do",
"|",
"day",
",",
"index",
"|",
"int",
"+=",
"2",
"**",
"index",
"if",
"@weekdays",
"[",
"day",
"]",
"end",
"int",
"end"
] | 7 bits encoded in decimal number
0th bit = Sunday, 6th bit = Saturday
Value of 127 => all days are on | [
"7",
"bits",
"encoded",
"in",
"decimal",
"number",
"0th",
"bit",
"=",
"Sunday",
"6th",
"bit",
"=",
"Saturday",
"Value",
"of",
"127",
"=",
">",
"all",
"days",
"are",
"on"
] | 39ad5164242d679a936ea4792c41562ba9f3e670 | https://github.com/sealink/timely/blob/39ad5164242d679a936ea4792c41562ba9f3e670/lib/timely/week_days.rb#L116-L122 | valid |
sealink/timely | lib/timely/trackable_date_set.rb | Timely.TrackableDateSet.do_once | def do_once(action_name, opts={})
return if action_applied?(action_name)
result = yield
job_done = opts[:job_done_when].blank? || opts[:job_done_when].call(result)
apply_action(action_name) if job_done
end | ruby | def do_once(action_name, opts={})
return if action_applied?(action_name)
result = yield
job_done = opts[:job_done_when].blank? || opts[:job_done_when].call(result)
apply_action(action_name) if job_done
end | [
"def",
"do_once",
"(",
"action_name",
",",
"opts",
"=",
"{",
"}",
")",
"return",
"if",
"action_applied?",
"(",
"action_name",
")",
"result",
"=",
"yield",
"job_done",
"=",
"opts",
"[",
":job_done_when",
"]",
".",
"blank?",
"||",
"opts",
"[",
":job_done_whe... | Do something once within this tracked period
Will only consider job done when opts[:job_done] is true
action_name => Name to track
{:job_done_when} => Block to call, passed result of yield | [
"Do",
"something",
"once",
"within",
"this",
"tracked",
"period"
] | 39ad5164242d679a936ea4792c41562ba9f3e670 | https://github.com/sealink/timely/blob/39ad5164242d679a936ea4792c41562ba9f3e670/lib/timely/trackable_date_set.rb#L115-L121 | valid |
govdelivery/jekyll-ramler | lib/raml-generate.rb | Jekyll.ResourcePage.add_schema_hashes | def add_schema_hashes(obj, key=nil)
if obj.is_a?(Array)
obj.map! { |method| add_schema_hashes(method) }
elsif obj.is_a?(Hash)
obj.each { |k, v| obj[k] = add_schema_hashes(v, k)}
if obj.include?("schema")
case key
when 'application/json'
obj['schema_hash'] = JSON.parse(obj['schema'])
refactor_object = lambda do |lam_obj|
lam_obj['properties'].each do |name, param|
param['displayName'] = name
param['required'] = true if lam_obj.fetch('required', []).include?(name)
if param.include?('example') and ['object', 'array'].include?(param['type'])
param['example'] = JSON.pretty_generate(JSON.parse(param['example']))
elsif param.include?('properties')
param['properties'] = JSON.pretty_generate(param['properties'])
elsif param.include?('items')
param['items'] = JSON.pretty_generate(param['items'])
end
lam_obj['properties'][name] = param
end
lam_obj
end
if obj['schema_hash'].include?('properties')
obj['schema_hash'] = refactor_object.call(obj['schema_hash'])
end
if obj['schema_hash'].include?('items') and obj['schema_hash']['items'].include?('properties')
obj['schema_hash']['items'] = refactor_object.call(obj['schema_hash']['items'])
end
end
end
end
obj
end | ruby | def add_schema_hashes(obj, key=nil)
if obj.is_a?(Array)
obj.map! { |method| add_schema_hashes(method) }
elsif obj.is_a?(Hash)
obj.each { |k, v| obj[k] = add_schema_hashes(v, k)}
if obj.include?("schema")
case key
when 'application/json'
obj['schema_hash'] = JSON.parse(obj['schema'])
refactor_object = lambda do |lam_obj|
lam_obj['properties'].each do |name, param|
param['displayName'] = name
param['required'] = true if lam_obj.fetch('required', []).include?(name)
if param.include?('example') and ['object', 'array'].include?(param['type'])
param['example'] = JSON.pretty_generate(JSON.parse(param['example']))
elsif param.include?('properties')
param['properties'] = JSON.pretty_generate(param['properties'])
elsif param.include?('items')
param['items'] = JSON.pretty_generate(param['items'])
end
lam_obj['properties'][name] = param
end
lam_obj
end
if obj['schema_hash'].include?('properties')
obj['schema_hash'] = refactor_object.call(obj['schema_hash'])
end
if obj['schema_hash'].include?('items') and obj['schema_hash']['items'].include?('properties')
obj['schema_hash']['items'] = refactor_object.call(obj['schema_hash']['items'])
end
end
end
end
obj
end | [
"def",
"add_schema_hashes",
"(",
"obj",
",",
"key",
"=",
"nil",
")",
"if",
"obj",
".",
"is_a?",
"(",
"Array",
")",
"obj",
".",
"map!",
"{",
"|",
"method",
"|",
"add_schema_hashes",
"(",
"method",
")",
"}",
"elsif",
"obj",
".",
"is_a?",
"(",
"Hash",
... | Adds a 'schema_hash' attribute to bodies with 'schema', which allows for the generation of schema table views | [
"Adds",
"a",
"schema_hash",
"attribute",
"to",
"bodies",
"with",
"schema",
"which",
"allows",
"for",
"the",
"generation",
"of",
"schema",
"table",
"views"
] | 8415d0d3a5a742fb88c47799326f0f470bc3d6fe | https://github.com/govdelivery/jekyll-ramler/blob/8415d0d3a5a742fb88c47799326f0f470bc3d6fe/lib/raml-generate.rb#L154-L196 | valid |
sealink/timely | lib/timely/rails/extensions.rb | Timely.Extensions.weekdays_field | def weekdays_field(attribute, options={})
db_field = options[:db_field] || attribute.to_s + '_bit_array'
self.composed_of(attribute,
:class_name => "::Timely::WeekDays",
:mapping => [[db_field, 'weekdays_int']],
:converter => Proc.new {|field| ::Timely::WeekDays.new(field)}
)
end | ruby | def weekdays_field(attribute, options={})
db_field = options[:db_field] || attribute.to_s + '_bit_array'
self.composed_of(attribute,
:class_name => "::Timely::WeekDays",
:mapping => [[db_field, 'weekdays_int']],
:converter => Proc.new {|field| ::Timely::WeekDays.new(field)}
)
end | [
"def",
"weekdays_field",
"(",
"attribute",
",",
"options",
"=",
"{",
"}",
")",
"db_field",
"=",
"options",
"[",
":db_field",
"]",
"||",
"attribute",
".",
"to_s",
"+",
"'_bit_array'",
"self",
".",
"composed_of",
"(",
"attribute",
",",
":class_name",
"=>",
"... | Add a WeekDays attribute
By default it will use attribute_bit_array as db field, but this can
be overridden by specifying :db_field => 'somthing_else' | [
"Add",
"a",
"WeekDays",
"attribute"
] | 39ad5164242d679a936ea4792c41562ba9f3e670 | https://github.com/sealink/timely/blob/39ad5164242d679a936ea4792c41562ba9f3e670/lib/timely/rails/extensions.rb#L7-L14 | valid |
MatthewChang/PaperTrailAudit | lib/paper_trail-audit.rb | PaperTrailAudit.Model.calculate_audit_for | def calculate_audit_for(param)
#Gets all flattened attribute lists
#objects are a hash of
#{attributes: object attributes, whodunnit: paper_trail whodunnit which caused the object to be in this state}
objects = [{attributes: self.attributes, whodunnit: self.paper_trail.originator},
self.versions.map {|e| {attributes: YAML.load(e.object), whodunnit: e.paper_trail_originator} if e.object}.compact].flatten
#rejecting objects with no update time, orders by the updated at times in ascending order
objects = objects.select {|e| e[:attributes]["updated_at"]}.sort_by {|e| e[:attributes]["updated_at"]}
result = []
#Add the initial state if the first element has a value
if(objects.count > 0 && !objects.first[:attributes][param.to_s].nil?)
result << PaperTrailAudit::Change.new({old_value: nil,
new_value: objects.first[:attributes][param.to_s],
time: objects.first[:attributes]["updated_at"],
whodunnit: objects.first[:whodunnit]
})
end
objects.each_cons(2) do |a,b|
if a[:attributes][param.to_s] != b[:attributes][param.to_s]
result << PaperTrailAudit::Change.new({old_value: a[:attributes][param.to_s],
new_value: b[:attributes][param.to_s],
time: b[:attributes]["updated_at"],
whodunnit: b[:whodunnit]
})
end
end
result
end | ruby | def calculate_audit_for(param)
#Gets all flattened attribute lists
#objects are a hash of
#{attributes: object attributes, whodunnit: paper_trail whodunnit which caused the object to be in this state}
objects = [{attributes: self.attributes, whodunnit: self.paper_trail.originator},
self.versions.map {|e| {attributes: YAML.load(e.object), whodunnit: e.paper_trail_originator} if e.object}.compact].flatten
#rejecting objects with no update time, orders by the updated at times in ascending order
objects = objects.select {|e| e[:attributes]["updated_at"]}.sort_by {|e| e[:attributes]["updated_at"]}
result = []
#Add the initial state if the first element has a value
if(objects.count > 0 && !objects.first[:attributes][param.to_s].nil?)
result << PaperTrailAudit::Change.new({old_value: nil,
new_value: objects.first[:attributes][param.to_s],
time: objects.first[:attributes]["updated_at"],
whodunnit: objects.first[:whodunnit]
})
end
objects.each_cons(2) do |a,b|
if a[:attributes][param.to_s] != b[:attributes][param.to_s]
result << PaperTrailAudit::Change.new({old_value: a[:attributes][param.to_s],
new_value: b[:attributes][param.to_s],
time: b[:attributes]["updated_at"],
whodunnit: b[:whodunnit]
})
end
end
result
end | [
"def",
"calculate_audit_for",
"(",
"param",
")",
"objects",
"=",
"[",
"{",
"attributes",
":",
"self",
".",
"attributes",
",",
"whodunnit",
":",
"self",
".",
"paper_trail",
".",
"originator",
"}",
",",
"self",
".",
"versions",
".",
"map",
"{",
"|",
"e",
... | Returns the audit list for the specified column
@param [symbol] param: symbol to query
@return [array of Change objects] | [
"Returns",
"the",
"audit",
"list",
"for",
"the",
"specified",
"column"
] | e8c7de44f2a7f227f8d3880ae657e91df4357c7e | https://github.com/MatthewChang/PaperTrailAudit/blob/e8c7de44f2a7f227f8d3880ae657e91df4357c7e/lib/paper_trail-audit.rb#L14-L41 | valid |
sugaryourcoffee/syc-svpro | lib/sycsvpro/analyzer.rb | Sycsvpro.Analyzer.result | def result
rows = File.readlines(file)
result = Result.new
unless rows.empty?
row_number = 0
row_number += 1 while rows[row_number].chomp.empty?
result.cols = rows[row_number].chomp.split(';')
result.col_count = result.cols.size
row_number += 1
row_number += 1 while rows[row_number].chomp.empty?
result.row_count = rows.size - 1
result.sample_row = rows[row_number].chomp
end
result
end | ruby | def result
rows = File.readlines(file)
result = Result.new
unless rows.empty?
row_number = 0
row_number += 1 while rows[row_number].chomp.empty?
result.cols = rows[row_number].chomp.split(';')
result.col_count = result.cols.size
row_number += 1
row_number += 1 while rows[row_number].chomp.empty?
result.row_count = rows.size - 1
result.sample_row = rows[row_number].chomp
end
result
end | [
"def",
"result",
"rows",
"=",
"File",
".",
"readlines",
"(",
"file",
")",
"result",
"=",
"Result",
".",
"new",
"unless",
"rows",
".",
"empty?",
"row_number",
"=",
"0",
"row_number",
"+=",
"1",
"while",
"rows",
"[",
"row_number",
"]",
".",
"chomp",
".",... | Creates a new analyzer
Analyzes the file and returns the result | [
"Creates",
"a",
"new",
"analyzer",
"Analyzes",
"the",
"file",
"and",
"returns",
"the",
"result"
] | a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3 | https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/analyzer.rb#L33-L52 | valid |
caruby/tissue | examples/galena/lib/galena/seed.rb | Galena.Seed.populate | def populate
galena = CaTissue::Institution.new(:name => 'Galena University')
addr = CaTissue::Address.new(
:city => 'Galena', :state => 'Illinois', :country => 'United States', :zipCode => '37544',
:street => '411 Basin St', :phoneNumber => '311-555-5555')
dept = CaTissue::Department.new(:name => 'Pathology')
crg = CaTissue::CancerResearchGroup.new(:name => 'Don Thomas Cancer Center')
coord = CaTissue::User.new(
:email_address => 'corey.nator@galena.edu',
:last_name => 'Nator', :first_name => 'Corey', :address => addr.copy,
:institution => galena, :department => dept, :cancer_research_group => crg)
@hospital = CaTissue::Site.new(
:site_type => CaTissue::Site::SiteType::COLLECTION, :name => 'Galena Hospital',
:address => addr.copy, :coordinator => coord)
@tissue_bank = CaTissue::Site.new(
:site_type => CaTissue::Site::SiteType::REPOSITORY, :name => 'Galena Tissue Bank',
:address => addr.copy, :coordinator => coord)
pi = CaTissue::User.new(
:email_address => 'vesta.gator@galena.edu',
:last_name => 'Gator', :first_name => 'Vesta', :address => addr.copy,
:institution => galena, :department => dept, :cancer_research_group => crg)
@surgeon = CaTissue::User.new(
:email_address => 'serge.on@galena.edu',
:first_name => 'Serge', :last_name => 'On', :address => addr.copy,
:institution => galena, :department => dept, :cancer_research_group => crg)
@protocol = CaTissue::CollectionProtocol.new(:title => 'Galena Migration',
:principal_investigator => pi, :sites => [@tissue_bank])
# CPE has default 1.0 event point and label
cpe = CaTissue::CollectionProtocolEvent.new(
:collection_protocol => @protocol,
:event_point => 1.0
)
# The sole specimen requirement. Setting the requirement collection_event attribute to a CPE automatically
# sets the CPE requirement inverse attribute in caRuby.
CaTissue::TissueSpecimenRequirement.new(:collection_event => cpe, :specimen_type => 'Fixed Tissue')
# the storage container type hierarchy
@freezer_type = CaTissue::StorageType.new(
:name => 'Galena Freezer',
:columns => 10, :rows => 1,
:column_label => 'Rack'
)
rack_type = CaTissue::StorageType.new(:name => 'Galena Rack', :columns => 10, :rows => 10)
@box_type = CaTissue::StorageType.new(:name => 'Galena Box', :columns => 10, :rows => 10)
@freezer_type << rack_type
rack_type << @box_type
@box_type << 'Tissue'
# the example tissue box
@box = @box_type.new_container(:name => 'Galena Box 1')
end | ruby | def populate
galena = CaTissue::Institution.new(:name => 'Galena University')
addr = CaTissue::Address.new(
:city => 'Galena', :state => 'Illinois', :country => 'United States', :zipCode => '37544',
:street => '411 Basin St', :phoneNumber => '311-555-5555')
dept = CaTissue::Department.new(:name => 'Pathology')
crg = CaTissue::CancerResearchGroup.new(:name => 'Don Thomas Cancer Center')
coord = CaTissue::User.new(
:email_address => 'corey.nator@galena.edu',
:last_name => 'Nator', :first_name => 'Corey', :address => addr.copy,
:institution => galena, :department => dept, :cancer_research_group => crg)
@hospital = CaTissue::Site.new(
:site_type => CaTissue::Site::SiteType::COLLECTION, :name => 'Galena Hospital',
:address => addr.copy, :coordinator => coord)
@tissue_bank = CaTissue::Site.new(
:site_type => CaTissue::Site::SiteType::REPOSITORY, :name => 'Galena Tissue Bank',
:address => addr.copy, :coordinator => coord)
pi = CaTissue::User.new(
:email_address => 'vesta.gator@galena.edu',
:last_name => 'Gator', :first_name => 'Vesta', :address => addr.copy,
:institution => galena, :department => dept, :cancer_research_group => crg)
@surgeon = CaTissue::User.new(
:email_address => 'serge.on@galena.edu',
:first_name => 'Serge', :last_name => 'On', :address => addr.copy,
:institution => galena, :department => dept, :cancer_research_group => crg)
@protocol = CaTissue::CollectionProtocol.new(:title => 'Galena Migration',
:principal_investigator => pi, :sites => [@tissue_bank])
# CPE has default 1.0 event point and label
cpe = CaTissue::CollectionProtocolEvent.new(
:collection_protocol => @protocol,
:event_point => 1.0
)
# The sole specimen requirement. Setting the requirement collection_event attribute to a CPE automatically
# sets the CPE requirement inverse attribute in caRuby.
CaTissue::TissueSpecimenRequirement.new(:collection_event => cpe, :specimen_type => 'Fixed Tissue')
# the storage container type hierarchy
@freezer_type = CaTissue::StorageType.new(
:name => 'Galena Freezer',
:columns => 10, :rows => 1,
:column_label => 'Rack'
)
rack_type = CaTissue::StorageType.new(:name => 'Galena Rack', :columns => 10, :rows => 10)
@box_type = CaTissue::StorageType.new(:name => 'Galena Box', :columns => 10, :rows => 10)
@freezer_type << rack_type
rack_type << @box_type
@box_type << 'Tissue'
# the example tissue box
@box = @box_type.new_container(:name => 'Galena Box 1')
end | [
"def",
"populate",
"galena",
"=",
"CaTissue",
"::",
"Institution",
".",
"new",
"(",
":name",
"=>",
"'Galena University'",
")",
"addr",
"=",
"CaTissue",
"::",
"Address",
".",
"new",
"(",
":city",
"=>",
"'Galena'",
",",
":state",
"=>",
"'Illinois'",
",",
":c... | Sets the Galena example Defaults attributes to new objects. | [
"Sets",
"the",
"Galena",
"example",
"Defaults",
"attributes",
"to",
"new",
"objects",
"."
] | 08d99aabf4801c89842ce6dee138ccb1e4f5f56b | https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/examples/galena/lib/galena/seed.rb#L60-L121 | valid |
sugaryourcoffee/syc-svpro | lib/sycsvpro/script_list.rb | Sycsvpro.ScriptList.execute | def execute
scripts = Dir.glob(File.join(@script_dir, @script_file))
scripts.each do |script|
list[script] = []
if show_methods
list[script] = retrieve_methods(script)
end
end
list
end | ruby | def execute
scripts = Dir.glob(File.join(@script_dir, @script_file))
scripts.each do |script|
list[script] = []
if show_methods
list[script] = retrieve_methods(script)
end
end
list
end | [
"def",
"execute",
"scripts",
"=",
"Dir",
".",
"glob",
"(",
"File",
".",
"join",
"(",
"@script_dir",
",",
"@script_file",
")",
")",
"scripts",
".",
"each",
"do",
"|",
"script",
"|",
"list",
"[",
"script",
"]",
"=",
"[",
"]",
"if",
"show_methods",
"lis... | Creates a new ScriptList. Takes params script_dir, script_file and show_methods
Retrieves the information about scripts and methods from the script directory | [
"Creates",
"a",
"new",
"ScriptList",
".",
"Takes",
"params",
"script_dir",
"script_file",
"and",
"show_methods",
"Retrieves",
"the",
"information",
"about",
"scripts",
"and",
"methods",
"from",
"the",
"script",
"directory"
] | a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3 | https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/script_list.rb#L31-L40 | valid |
sugaryourcoffee/syc-svpro | lib/sycsvpro/script_list.rb | Sycsvpro.ScriptList.retrieve_methods | def retrieve_methods(script)
code = File.read(script)
methods = code.scan(/((#.*\s)*def.*\s|def.*\s)/)
result = []
methods.each do |method|
result << method[0]
end
result
end | ruby | def retrieve_methods(script)
code = File.read(script)
methods = code.scan(/((#.*\s)*def.*\s|def.*\s)/)
result = []
methods.each do |method|
result << method[0]
end
result
end | [
"def",
"retrieve_methods",
"(",
"script",
")",
"code",
"=",
"File",
".",
"read",
"(",
"script",
")",
"methods",
"=",
"code",
".",
"scan",
"(",
"/",
"\\s",
"\\s",
"\\s",
"/",
")",
"result",
"=",
"[",
"]",
"methods",
".",
"each",
"do",
"|",
"method",... | Retrieve the methods including comments if available | [
"Retrieve",
"the",
"methods",
"including",
"comments",
"if",
"available"
] | a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3 | https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/script_list.rb#L45-L53 | valid |
obrie/turntabler | lib/turntabler/client.rb | Turntabler.Client.close | def close(allow_reconnect = false)
if @connection
# Disable reconnects if specified
reconnect = @reconnect
@reconnect = reconnect && allow_reconnect
# Clean up timers / connections
@keepalive_timer.cancel if @keepalive_timer
@keepalive_timer = nil
@connection.close
# Revert change to reconnect config once the final signal is received
wait do |&resume|
on(:session_ended, :once => true) { resume.call }
end
@reconnect = reconnect
end
true
end | ruby | def close(allow_reconnect = false)
if @connection
# Disable reconnects if specified
reconnect = @reconnect
@reconnect = reconnect && allow_reconnect
# Clean up timers / connections
@keepalive_timer.cancel if @keepalive_timer
@keepalive_timer = nil
@connection.close
# Revert change to reconnect config once the final signal is received
wait do |&resume|
on(:session_ended, :once => true) { resume.call }
end
@reconnect = reconnect
end
true
end | [
"def",
"close",
"(",
"allow_reconnect",
"=",
"false",
")",
"if",
"@connection",
"reconnect",
"=",
"@reconnect",
"@reconnect",
"=",
"reconnect",
"&&",
"allow_reconnect",
"@keepalive_timer",
".",
"cancel",
"if",
"@keepalive_timer",
"@keepalive_timer",
"=",
"nil",
"@co... | Closes the current connection to Turntable if one was previously opened.
@return [true] | [
"Closes",
"the",
"current",
"connection",
"to",
"Turntable",
"if",
"one",
"was",
"previously",
"opened",
"."
] | e2240f1a5d210a33c05c5b2261d291089cdcf1c6 | https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/client.rb#L125-L144 | valid |
obrie/turntabler | lib/turntabler/client.rb | Turntabler.Client.api | def api(command, params = {})
raise(ConnectionError, 'Connection is not open') unless @connection && @connection.connected?
message_id = @connection.publish(params.merge(:api => command))
# Wait until we get a response for the given message
data = wait do |&resume|
on(:response_received, :once => true, :if => {'msgid' => message_id}) {|data| resume.call(data)}
end
if data['success']
data
else
error = data['error'] || data['err']
raise APIError, "Command \"#{command}\" failed with message: \"#{error}\""
end
end | ruby | def api(command, params = {})
raise(ConnectionError, 'Connection is not open') unless @connection && @connection.connected?
message_id = @connection.publish(params.merge(:api => command))
# Wait until we get a response for the given message
data = wait do |&resume|
on(:response_received, :once => true, :if => {'msgid' => message_id}) {|data| resume.call(data)}
end
if data['success']
data
else
error = data['error'] || data['err']
raise APIError, "Command \"#{command}\" failed with message: \"#{error}\""
end
end | [
"def",
"api",
"(",
"command",
",",
"params",
"=",
"{",
"}",
")",
"raise",
"(",
"ConnectionError",
",",
"'Connection is not open'",
")",
"unless",
"@connection",
"&&",
"@connection",
".",
"connected?",
"message_id",
"=",
"@connection",
".",
"publish",
"(",
"par... | Runs the given API command.
@api private
@param [String] command The name of the command to execute
@param [Hash] params The parameters to pass into the command
@return [Hash] The data returned from the Turntable service
@raise [Turntabler::Error] if the connection is not open or the command fails to execute | [
"Runs",
"the",
"given",
"API",
"command",
"."
] | e2240f1a5d210a33c05c5b2261d291089cdcf1c6 | https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/client.rb#L161-L177 | valid |
obrie/turntabler | lib/turntabler/client.rb | Turntabler.Client.on | def on(event, options = {}, &block)
event = event.to_sym
@event_handlers[event] ||= []
@event_handlers[event] << Handler.new(event, options, &block)
true
end | ruby | def on(event, options = {}, &block)
event = event.to_sym
@event_handlers[event] ||= []
@event_handlers[event] << Handler.new(event, options, &block)
true
end | [
"def",
"on",
"(",
"event",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"event",
"=",
"event",
".",
"to_sym",
"@event_handlers",
"[",
"event",
"]",
"||=",
"[",
"]",
"@event_handlers",
"[",
"event",
"]",
"<<",
"Handler",
".",
"new",
"(",
"... | Registers a handler to invoke when an event occurs in Turntable.
@param [Symbol] event The event to register a handler for
@param [Hash] options The configuration options for the handler
@option options [Hash] :if Specifies a set of key-value pairs that must be matched in the event data in order to run the handler
@option options [Boolean] :once (false) Whether to only run the handler once
@return [true]
== Client Events
* +:reconnected+ - The client reconnected (and re-entered any room that the user was previously in)
@example
client.on :reconnected do
client.room.dj
# ...
end
== Room Events
* +:room_updated+ - Information about the room was updated
* +:room_description_updated+ - The room's description was updated
@example
client.on :room_updated do |room| # Room
puts room.description
# ...
end
client.on :room_description_updated do |room| # Room
puts room.description
# ...
end
== User Events
* +:user_entered+ - A user entered the room
* +:user_left+ - A user left the room
* +:user_booted+ - A user has been booted from the room
* +:user_updated+ - A user's profile was updated
* +:user_name_updated+ - A user's name was updated
* +:user_avatar_updated+ - A user's avatar was updated
* +:user_spoke+ - A user spoke in the chat room
@example
client.on :user_entered do |user| # User
puts user.id
# ...
end
client.on :user_left do |user| # User
puts user.id
# ...
end
client.on :user_booted do |boot| # Boot
puts boot.user.id
puts boot.reason
# ...
end
client.on :user_updated do |user| # User
puts user.name
# ...
end
client.on :user_name_updated do |user| # User
puts user.name
# ...
end
client.on :user_avatar_updated do |user| # User
puts user.avatar.id
# ...
end
client.on :user_stickers_updated do |user| # User
puts user.stickers.map {|sticker| sticker.id}
# ...
end
client.on :user_spoke do |message| # Message
puts message.content
# ...
end
== DJ Events
* +:fan_added+ - A new fan was added by a user in the room
* +:fan_removed+ - A fan was removed from a user in the room
@example
client.on :fan_added do |user, fan_of| # User, User
puts user.id
# ...
end
client.on :fan_removed do |user, count| # User, Fixnum
puts user.id
# ...
end
== DJ Events
* +:dj_added+ - A new DJ was added to the stage
* +:dj_removed+ - A DJ was removed from the stage
* +:dj_escorted_off+ - A DJ was escorted off the stage by a moderator
* +:dj_booed_off+ - A DJ was booed off the stage
@example
client.on :dj_added do |user| # User
puts user.id
# ...
end
client.on :dj_removed do |user| # User
puts user.id
# ...
end
client.on :dj_escorted_off do |user, moderator| # User, User
puts user.id
# ...
end
client.on :dj_booed_off do |user| # User
puts user.id
# ...
end
== Moderator Events
* +:moderator_added+ - A new moderator was added to the room
* +:moderator_removed+ - A moderator was removed from the room
@example
client.on :moderator_added do |user| # User
puts user.id
# ...
end
client.on :moderator_removed do |user| # User
puts user.id
# ...
end
== Song Events
* +:song_unavailable+ - Indicates that there are no more songs to play in the room
* +:song_started+ - A new song has started playing
* +:song_ended+ - The current song has ended. This is typically followed by a +:song_started+ or +:song_unavailable+ event.
* +:song_voted+ - One or more votes were cast for the song
* +:song_snagged+ - A user in the room has queued the current song onto their playlist
* +:song_skipped+ - A song was skipped due to either the dj skipping it or too many downvotes
* +:song_moderated+ - A song was forcefully skipped by a moderator
* +:song_blocked+ - A song was prevented from playing due to a copyright claim
@example
client.on :song_unavailable do
# ...
end
client.on :song_started do |song| # Song
puts song.title
# ...
end
client.on :song_ended do |song| # Song
puts song.title
# ...
end
client.on :song_voted do |song| # Song
puts song.up_votes_count
puts song.down_votes_count
puts song.votes
# ...
end
client.on :song_snagged do |snag| # Snag
puts snag.user.id
puts snag.song.id
# ...
end
client.on :song_skipped do |song| # Song
puts song.title
# ...
end
client.on :song_moderated do |song, moderator| # Song, User
puts song.title
puts moderator.id
# ...
end
client.on :song_blocked do |song| # Song
puts song.id
# ...
end
client.on :song_limited do |song| # Song
puts song.id
# ...
end
== Messaging Events
* +:message_received+ - A private message was received from another user in the room
@example
client.on :message_received do |message| # Message
puts message.content
# ...
end | [
"Registers",
"a",
"handler",
"to",
"invoke",
"when",
"an",
"event",
"occurs",
"in",
"Turntable",
"."
] | e2240f1a5d210a33c05c5b2261d291089cdcf1c6 | https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/client.rb#L394-L399 | valid |
obrie/turntabler | lib/turntabler/client.rb | Turntabler.Client.user_by_name | def user_by_name(name)
data = api('user.get_id', :name => name)
user = self.user(data['userid'])
user.attributes = {'name' => name}
user
end | ruby | def user_by_name(name)
data = api('user.get_id', :name => name)
user = self.user(data['userid'])
user.attributes = {'name' => name}
user
end | [
"def",
"user_by_name",
"(",
"name",
")",
"data",
"=",
"api",
"(",
"'user.get_id'",
",",
":name",
"=>",
"name",
")",
"user",
"=",
"self",
".",
"user",
"(",
"data",
"[",
"'userid'",
"]",
")",
"user",
".",
"attributes",
"=",
"{",
"'name'",
"=>",
"name",... | Gets the user with the given DJ name. This should only be used if the id
of the user is unknown.
@param [String] name The user's DJ name
@return [Turntabler::User]
@raise [Turntabler::Error] if the command fails
@example
client.user_by_name('DJSpinster') # => #<Turntabler::User id="a34bd..." ...> | [
"Gets",
"the",
"user",
"with",
"the",
"given",
"DJ",
"name",
".",
"This",
"should",
"only",
"be",
"used",
"if",
"the",
"id",
"of",
"the",
"user",
"is",
"unknown",
"."
] | e2240f1a5d210a33c05c5b2261d291089cdcf1c6 | https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/client.rb#L433-L438 | valid |
obrie/turntabler | lib/turntabler/client.rb | Turntabler.Client.avatars | def avatars
data = api('user.available_avatars')
avatars = []
data['avatars'].each do |avatar_group|
avatar_group['avatarids'].each do |avatar_id|
avatars << Avatar.new(self, :_id => avatar_id, :min => avatar_group['min'], :acl => avatar_group['acl'])
end
end
avatars
end | ruby | def avatars
data = api('user.available_avatars')
avatars = []
data['avatars'].each do |avatar_group|
avatar_group['avatarids'].each do |avatar_id|
avatars << Avatar.new(self, :_id => avatar_id, :min => avatar_group['min'], :acl => avatar_group['acl'])
end
end
avatars
end | [
"def",
"avatars",
"data",
"=",
"api",
"(",
"'user.available_avatars'",
")",
"avatars",
"=",
"[",
"]",
"data",
"[",
"'avatars'",
"]",
".",
"each",
"do",
"|",
"avatar_group",
"|",
"avatar_group",
"[",
"'avatarids'",
"]",
".",
"each",
"do",
"|",
"avatar_id",
... | Get all avatars availble on Turntable.
@return [Array<Turntabler::Avatar>]
@raise [Turntabler::Error] if the command fails
@example
client.avatars # => [#<Turntabler::Avatar ...>, ...] | [
"Get",
"all",
"avatars",
"availble",
"on",
"Turntable",
"."
] | e2240f1a5d210a33c05c5b2261d291089cdcf1c6 | https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/client.rb#L446-L455 | valid |
obrie/turntabler | lib/turntabler/client.rb | Turntabler.Client.search_song | def search_song(query, options = {})
assert_valid_keys(options, :artist, :duration, :page)
options = {:page => 1}.merge(options)
raise(APIError, 'User must be in a room to search for songs') unless room
if artist = options[:artist]
query = "title: #{query}"
query << " artist: #{artist}"
end
query << " duration: #{options[:duration]}" if options[:duration]
api('file.search', :query => query, :page => options[:page])
conditions = {'query' => query}
# Time out if the response takes too long
EventMachine.add_timer(@timeout) do
trigger(:search_failed, conditions)
end if @timeout
# Wait for the async callback
songs = wait do |&resume|
on(:search_completed, :once => true, :if => conditions) {|songs| resume.call(songs)}
on(:search_failed, :once => true, :if => conditions) { resume.call }
end
# Clean up any leftover handlers
@event_handlers[:search_completed].delete_if {|handler| handler.conditions == conditions}
@event_handlers[:search_failed].delete_if {|handler| handler.conditions == conditions}
songs || raise(APIError, 'Search failed to complete')
end | ruby | def search_song(query, options = {})
assert_valid_keys(options, :artist, :duration, :page)
options = {:page => 1}.merge(options)
raise(APIError, 'User must be in a room to search for songs') unless room
if artist = options[:artist]
query = "title: #{query}"
query << " artist: #{artist}"
end
query << " duration: #{options[:duration]}" if options[:duration]
api('file.search', :query => query, :page => options[:page])
conditions = {'query' => query}
# Time out if the response takes too long
EventMachine.add_timer(@timeout) do
trigger(:search_failed, conditions)
end if @timeout
# Wait for the async callback
songs = wait do |&resume|
on(:search_completed, :once => true, :if => conditions) {|songs| resume.call(songs)}
on(:search_failed, :once => true, :if => conditions) { resume.call }
end
# Clean up any leftover handlers
@event_handlers[:search_completed].delete_if {|handler| handler.conditions == conditions}
@event_handlers[:search_failed].delete_if {|handler| handler.conditions == conditions}
songs || raise(APIError, 'Search failed to complete')
end | [
"def",
"search_song",
"(",
"query",
",",
"options",
"=",
"{",
"}",
")",
"assert_valid_keys",
"(",
"options",
",",
":artist",
",",
":duration",
",",
":page",
")",
"options",
"=",
"{",
":page",
"=>",
"1",
"}",
".",
"merge",
"(",
"options",
")",
"raise",
... | Finds songs that match the given query.
@note The user must be entered in a room to search for songs
@param [String] query The query string to search for. This should just be the title of the song if :artist is specified.
@param [Hash] options The configuration options for the search
@option options [String] :artist The name of the artist for the song
@option options [Fixnum] :duration The length, in minutes, of the song
@option options [Fixnum] :page The page number to get from the results
@return [Array<Turntabler::Song>]
@raise [ArgumentError] if an invalid option is specified
@raise [Turntabler::Error] if the user is not in a room or the command fails
@example
# Less accurate, general query search
client.search_song('Like a Rolling Stone by Bob Dylan') # => [#<Turntabler::Song ...>, ...]
# More accurate, explicit title / artist search
client.search_song('Like a Rolling Stone', :artist => 'Bob Dylan') # => [#<Turntabler::Song ...>, ...] | [
"Finds",
"songs",
"that",
"match",
"the",
"given",
"query",
"."
] | e2240f1a5d210a33c05c5b2261d291089cdcf1c6 | https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/client.rb#L495-L527 | valid |
obrie/turntabler | lib/turntabler/client.rb | Turntabler.Client.trigger | def trigger(command, *args)
command = command.to_sym if command
if Event.command?(command)
event = Event.new(self, command, args)
handlers = @event_handlers[event.name] || []
handlers.each do |handler|
success = handler.run(event)
handlers.delete(handler) if success && handler.once
end
end
true
end | ruby | def trigger(command, *args)
command = command.to_sym if command
if Event.command?(command)
event = Event.new(self, command, args)
handlers = @event_handlers[event.name] || []
handlers.each do |handler|
success = handler.run(event)
handlers.delete(handler) if success && handler.once
end
end
true
end | [
"def",
"trigger",
"(",
"command",
",",
"*",
"args",
")",
"command",
"=",
"command",
".",
"to_sym",
"if",
"command",
"if",
"Event",
".",
"command?",
"(",
"command",
")",
"event",
"=",
"Event",
".",
"new",
"(",
"self",
",",
"command",
",",
"args",
")",... | Triggers callback handlers for the given Turntable command. This should
either be invoked when responses are received for Turntable or when
triggering custom events.
@note If the command is unknown, it will simply get skipped and not raise an exception
@param [Symbol] command The name of the command triggered. This is typically the same name as the event.
@param [Array] args The arguments to be processed by the event
@return [true]
== Triggering custom events
After defining custom events, `trigger` can be used to invoke any handler
that's been registered for that event. The argument list passed into
`trigger` will be passed, exactly as specified, to the registered
handlers.
@example
# Define names of events
Turntabler.events(:no_args, :one_arg, :multiple_args)
# ...
# Register handlers
client.on(:no_args) { }
client.on(:one_arg) {|arg| }
client.on(:multiple_args) {|arg1, arg2| }
# Trigger handlers registered for events
client.trigger(:no_args) # => true
client.trigger(:one_arg, 1) # => true
client.trigger(:multiple_args, 1, 2) # => true | [
"Triggers",
"callback",
"handlers",
"for",
"the",
"given",
"Turntable",
"command",
".",
"This",
"should",
"either",
"be",
"invoked",
"when",
"responses",
"are",
"received",
"for",
"Turntable",
"or",
"when",
"triggering",
"custom",
"events",
"."
] | e2240f1a5d210a33c05c5b2261d291089cdcf1c6 | https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/client.rb#L560-L573 | valid |
obrie/turntabler | lib/turntabler/client.rb | Turntabler.Client.reset_keepalive | def reset_keepalive(interval = 10)
if !@keepalive_timer || @keepalive_interval != interval
@keepalive_interval = interval
# Periodically update the user's status to remain available
@keepalive_timer.cancel if @keepalive_timer
@keepalive_timer = EM::Synchrony.add_periodic_timer(interval) do
Turntabler.run { user.update(:status => user.status) }
end
end
end | ruby | def reset_keepalive(interval = 10)
if !@keepalive_timer || @keepalive_interval != interval
@keepalive_interval = interval
# Periodically update the user's status to remain available
@keepalive_timer.cancel if @keepalive_timer
@keepalive_timer = EM::Synchrony.add_periodic_timer(interval) do
Turntabler.run { user.update(:status => user.status) }
end
end
end | [
"def",
"reset_keepalive",
"(",
"interval",
"=",
"10",
")",
"if",
"!",
"@keepalive_timer",
"||",
"@keepalive_interval",
"!=",
"interval",
"@keepalive_interval",
"=",
"interval",
"@keepalive_timer",
".",
"cancel",
"if",
"@keepalive_timer",
"@keepalive_timer",
"=",
"EM",... | Resets the keepalive timer to run at the given interval.
@param [Fixnum] interval The frequency with which keepalives get sent (in seconds)
@api private | [
"Resets",
"the",
"keepalive",
"timer",
"to",
"run",
"at",
"the",
"given",
"interval",
"."
] | e2240f1a5d210a33c05c5b2261d291089cdcf1c6 | https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/client.rb#L579-L589 | valid |
obrie/turntabler | lib/turntabler/client.rb | Turntabler.Client.on_session_missing | def on_session_missing
user.authenticate
user.fan_of
user.update(:status => user.status)
reset_keepalive
end | ruby | def on_session_missing
user.authenticate
user.fan_of
user.update(:status => user.status)
reset_keepalive
end | [
"def",
"on_session_missing",
"user",
".",
"authenticate",
"user",
".",
"fan_of",
"user",
".",
"update",
"(",
":status",
"=>",
"user",
".",
"status",
")",
"reset_keepalive",
"end"
] | Callback when session authentication is missing from the connection. This
will automatically authenticate with configured user as well as set up a
heartbeat. | [
"Callback",
"when",
"session",
"authentication",
"is",
"missing",
"from",
"the",
"connection",
".",
"This",
"will",
"automatically",
"authenticate",
"with",
"configured",
"user",
"as",
"well",
"as",
"set",
"up",
"a",
"heartbeat",
"."
] | e2240f1a5d210a33c05c5b2261d291089cdcf1c6 | https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/client.rb#L601-L606 | valid |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.