repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
hayesdavis/mockingbird | lib/mockingbird/script.rb | Mockingbird.Script.on_connection | def on_connection(selector=nil,&block)
if selector.nil? || selector == '*'
instance_eval(&block)
else
@current_connection = ConnectionScript.new
instance_eval(&block)
@connections << [selector,@current_connection]
@current_connection = nil
end
end | ruby | def on_connection(selector=nil,&block)
if selector.nil? || selector == '*'
instance_eval(&block)
else
@current_connection = ConnectionScript.new
instance_eval(&block)
@connections << [selector,@current_connection]
@current_connection = nil
end
end | [
"def",
"on_connection",
"(",
"selector",
"=",
"nil",
",",
"&",
"block",
")",
"if",
"selector",
".",
"nil?",
"||",
"selector",
"==",
"'*'",
"instance_eval",
"(",
"&",
"block",
")",
"else",
"@current_connection",
"=",
"ConnectionScript",
".",
"new",
"instance_eval",
"(",
"&",
"block",
")",
"@connections",
"<<",
"[",
"selector",
",",
"@current_connection",
"]",
"@current_connection",
"=",
"nil",
"end",
"end"
] | Configuration API
Specifies behavior to run for specific connections based on the id number
assigned to that connection. Connection ids are 1-based.
The selector can be any of the following:
Number - Run the code on that connection id
Range - Run the code for a connection id in that range
Proc - Call the proc with the id and run if it matches
'*' - Run this code for any connection that doesn't match others | [
"Configuration",
"API",
"Specifies",
"behavior",
"to",
"run",
"for",
"specific",
"connections",
"based",
"on",
"the",
"id",
"number",
"assigned",
"to",
"that",
"connection",
".",
"Connection",
"ids",
"are",
"1",
"-",
"based",
"."
] | 128e3f10d5774b319d9a4fa8f70841ad5bbc5d3b | https://github.com/hayesdavis/mockingbird/blob/128e3f10d5774b319d9a4fa8f70841ad5bbc5d3b/lib/mockingbird/script.rb#L31-L40 | train |
hayesdavis/mockingbird | lib/mockingbird/script.rb | Mockingbird.Script.add_command | def add_command(command=nil,&block)
command = Commands::Command.new(&block) if block_given?
current_connection.add_command(command)
end | ruby | def add_command(command=nil,&block)
command = Commands::Command.new(&block) if block_given?
current_connection.add_command(command)
end | [
"def",
"add_command",
"(",
"command",
"=",
"nil",
",",
"&",
"block",
")",
"command",
"=",
"Commands",
"::",
"Command",
".",
"new",
"(",
"&",
"block",
")",
"if",
"block_given?",
"current_connection",
".",
"add_command",
"(",
"command",
")",
"end"
] | Not really part of the public API but users could use this to
implement their own fancy command | [
"Not",
"really",
"part",
"of",
"the",
"public",
"API",
"but",
"users",
"could",
"use",
"this",
"to",
"implement",
"their",
"own",
"fancy",
"command"
] | 128e3f10d5774b319d9a4fa8f70841ad5bbc5d3b | https://github.com/hayesdavis/mockingbird/blob/128e3f10d5774b319d9a4fa8f70841ad5bbc5d3b/lib/mockingbird/script.rb#L89-L92 | train |
kevgo/active_cucumber | lib/active_cucumber/active_record_builder.rb | ActiveCucumber.ActiveRecordBuilder.create_record | def create_record attributes
creator = @creator_class.new attributes, @context
FactoryGirl.create @clazz.name.underscore.to_sym, creator.factorygirl_attributes
end | ruby | def create_record attributes
creator = @creator_class.new attributes, @context
FactoryGirl.create @clazz.name.underscore.to_sym, creator.factorygirl_attributes
end | [
"def",
"create_record",
"attributes",
"creator",
"=",
"@creator_class",
".",
"new",
"attributes",
",",
"@context",
"FactoryGirl",
".",
"create",
"@clazz",
".",
"name",
".",
"underscore",
".",
"to_sym",
",",
"creator",
".",
"factorygirl_attributes",
"end"
] | Creates a new record with the given attributes in the database | [
"Creates",
"a",
"new",
"record",
"with",
"the",
"given",
"attributes",
"in",
"the",
"database"
] | 9f3609abbfe2c4c3534c2c64d2f638a6bb6347cf | https://github.com/kevgo/active_cucumber/blob/9f3609abbfe2c4c3534c2c64d2f638a6bb6347cf/lib/active_cucumber/active_record_builder.rb#L27-L30 | train |
holtrop/rscons | lib/rscons/job_set.rb | Rscons.JobSet.get_next_job_to_run | def get_next_job_to_run(targets_still_building)
targets_not_built_yet = targets_still_building + @jobs.keys
side_effects = targets_not_built_yet.map do |target|
@side_effects[target] || []
end.flatten
targets_not_built_yet += side_effects
@jobs.keys.each do |target|
skip = false
(@jobs[target][0][:sources] + (@build_dependencies[target] || []).to_a).each do |src|
if targets_not_built_yet.include?(src)
skip = true
break
end
end
next if skip
job = @jobs[target][0]
if @jobs[target].size > 1
@jobs[target].slice!(0)
else
@jobs.delete(target)
end
return job
end
# If there is a job to run, and nothing is still building, but we did
# not find a job to run above, then there might be a circular dependency
# introduced by the user.
if (@jobs.size > 0) and targets_still_building.empty?
raise "Could not find a runnable job. Possible circular dependency for #{@jobs.keys.first}"
end
end | ruby | def get_next_job_to_run(targets_still_building)
targets_not_built_yet = targets_still_building + @jobs.keys
side_effects = targets_not_built_yet.map do |target|
@side_effects[target] || []
end.flatten
targets_not_built_yet += side_effects
@jobs.keys.each do |target|
skip = false
(@jobs[target][0][:sources] + (@build_dependencies[target] || []).to_a).each do |src|
if targets_not_built_yet.include?(src)
skip = true
break
end
end
next if skip
job = @jobs[target][0]
if @jobs[target].size > 1
@jobs[target].slice!(0)
else
@jobs.delete(target)
end
return job
end
# If there is a job to run, and nothing is still building, but we did
# not find a job to run above, then there might be a circular dependency
# introduced by the user.
if (@jobs.size > 0) and targets_still_building.empty?
raise "Could not find a runnable job. Possible circular dependency for #{@jobs.keys.first}"
end
end | [
"def",
"get_next_job_to_run",
"(",
"targets_still_building",
")",
"targets_not_built_yet",
"=",
"targets_still_building",
"+",
"@jobs",
".",
"keys",
"side_effects",
"=",
"targets_not_built_yet",
".",
"map",
"do",
"|",
"target",
"|",
"@side_effects",
"[",
"target",
"]",
"||",
"[",
"]",
"end",
".",
"flatten",
"targets_not_built_yet",
"+=",
"side_effects",
"@jobs",
".",
"keys",
".",
"each",
"do",
"|",
"target",
"|",
"skip",
"=",
"false",
"(",
"@jobs",
"[",
"target",
"]",
"[",
"0",
"]",
"[",
":sources",
"]",
"+",
"(",
"@build_dependencies",
"[",
"target",
"]",
"||",
"[",
"]",
")",
".",
"to_a",
")",
".",
"each",
"do",
"|",
"src",
"|",
"if",
"targets_not_built_yet",
".",
"include?",
"(",
"src",
")",
"skip",
"=",
"true",
"break",
"end",
"end",
"next",
"if",
"skip",
"job",
"=",
"@jobs",
"[",
"target",
"]",
"[",
"0",
"]",
"if",
"@jobs",
"[",
"target",
"]",
".",
"size",
">",
"1",
"@jobs",
"[",
"target",
"]",
".",
"slice!",
"(",
"0",
")",
"else",
"@jobs",
".",
"delete",
"(",
"target",
")",
"end",
"return",
"job",
"end",
"if",
"(",
"@jobs",
".",
"size",
">",
"0",
")",
"and",
"targets_still_building",
".",
"empty?",
"raise",
"\"Could not find a runnable job. Possible circular dependency for #{@jobs.keys.first}\"",
"end",
"end"
] | Get the next job that is ready to run from the JobSet.
This method will remove the job from the JobSet.
@param targets_still_building [Array<String>]
Targets that are not finished building. This is used to avoid returning
a job as available to run if it depends on one of the targets that are
still building as a source.
@return [nil, Hash]
The next job to run. | [
"Get",
"the",
"next",
"job",
"that",
"is",
"ready",
"to",
"run",
"from",
"the",
"JobSet",
"."
] | 4967f89a769a7b5c6ca91377526e3f53ceabd6a3 | https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/job_set.rb#L54-L85 | train |
platanus/negroku | lib/negroku/modes/stage.rb | Negroku::Modes.Stage.ask_stage | def ask_stage
question = I18n.t :ask_stage_name, scope: :negroku
stage_name = Ask.input question
raise "Stage name required" if stage_name.empty?
stage_name
end | ruby | def ask_stage
question = I18n.t :ask_stage_name, scope: :negroku
stage_name = Ask.input question
raise "Stage name required" if stage_name.empty?
stage_name
end | [
"def",
"ask_stage",
"question",
"=",
"I18n",
".",
"t",
":ask_stage_name",
",",
"scope",
":",
":negroku",
"stage_name",
"=",
"Ask",
".",
"input",
"question",
"raise",
"\"Stage name required\"",
"if",
"stage_name",
".",
"empty?",
"stage_name",
"end"
] | Ask the stage name | [
"Ask",
"the",
"stage",
"name"
] | 7124973132de65026b30b66477678387a07dfa4d | https://github.com/platanus/negroku/blob/7124973132de65026b30b66477678387a07dfa4d/lib/negroku/modes/stage.rb#L60-L65 | train |
chef-workflow/chef-workflow | lib/chef-workflow/support/debug.rb | ChefWorkflow.DebugSupport.if_debug | def if_debug(minimum=1, else_block=nil)
$CHEF_WORKFLOW_DEBUG ||=
ENV.has_key?("CHEF_WORKFLOW_DEBUG") ?
ENV["CHEF_WORKFLOW_DEBUG"].to_i :
CHEF_WORKFLOW_DEBUG_DEFAULT
if $CHEF_WORKFLOW_DEBUG >= minimum
yield if block_given?
elsif else_block
else_block.call
end
end | ruby | def if_debug(minimum=1, else_block=nil)
$CHEF_WORKFLOW_DEBUG ||=
ENV.has_key?("CHEF_WORKFLOW_DEBUG") ?
ENV["CHEF_WORKFLOW_DEBUG"].to_i :
CHEF_WORKFLOW_DEBUG_DEFAULT
if $CHEF_WORKFLOW_DEBUG >= minimum
yield if block_given?
elsif else_block
else_block.call
end
end | [
"def",
"if_debug",
"(",
"minimum",
"=",
"1",
",",
"else_block",
"=",
"nil",
")",
"$CHEF_WORKFLOW_DEBUG",
"||=",
"ENV",
".",
"has_key?",
"(",
"\"CHEF_WORKFLOW_DEBUG\"",
")",
"?",
"ENV",
"[",
"\"CHEF_WORKFLOW_DEBUG\"",
"]",
".",
"to_i",
":",
"CHEF_WORKFLOW_DEBUG_DEFAULT",
"if",
"$CHEF_WORKFLOW_DEBUG",
">=",
"minimum",
"yield",
"if",
"block_given?",
"elsif",
"else_block",
"else_block",
".",
"call",
"end",
"end"
] | Conditionally executes based on the level of debugging requested.
`CHEF_WORKFLOW_DEBUG` in the environment is converted to an integer. This
integer is compared to the first argument. If it is higher than the first
argument, the block supplied will execute.
Optionally, if there is a `else_block`, this block will be executed if the
condition is *not* met. This allows a slightly more elegant (if less ugly)
variant of dealing with the situation where if debugging is on, do one
thing, and if not, do something else.
Examples:
if_debug(1) do
$stderr.puts "Here's a debug message"
end
This will print "here's a debug message" to standard error if debugging is
set to 1 or greater.
do_thing = lambda { run_thing }
if_debug(2, &do_thing) do
$stderr.puts "Doing this thing"
do_thing.call
end
If debugging is set to 2 or higher, "Doing this thing" will be printed to
standard error and then `run_thing` will be executed. If lower than 2 or
off, will just execute `run_thing`. | [
"Conditionally",
"executes",
"based",
"on",
"the",
"level",
"of",
"debugging",
"requested",
"."
] | 956c8f6cd694dacc25dfa405d70b05b12b7c1691 | https://github.com/chef-workflow/chef-workflow/blob/956c8f6cd694dacc25dfa405d70b05b12b7c1691/lib/chef-workflow/support/debug.rb#L40-L51 | train |
liquidm/zmachine | lib/zmachine/tcp_msg_channel.rb | ZMachine.TcpMsgChannel.read_inbound_data | def read_inbound_data
ZMachine.logger.debug("zmachine:tcp_msg_channel:#{__method__}", channel: self) if ZMachine.debug
raise IOException.new("EOF") if @socket.read(@buffer) == -1
pos = @buffer.position
@buffer.flip
# validate magic
if @buffer.remaining >= 4
bytes = java.util.Arrays.copyOfRange(@buffer.array, @buffer.position, @buffer.position+4)
@buffer.position(@buffer.position+4)
if String.from_java_bytes(bytes) != MAGIC # read broken message - client should reconnect
ZMachine.logger.error("read broken message", worker: self)
close!
return
end
else
@buffer.position(pos).limit(@buffer.capacity)
return
end
# extract number of msg parts
if @buffer.remaining >= 4
bytes = java.util.Arrays.copyOfRange(@buffer.array, @buffer.position, @buffer.position+4)
@buffer.position(@buffer.position+4)
array_length = String.from_java_bytes(bytes).unpack('V')[0]
else
@buffer.position(pos).limit(@buffer.capacity)
return
end
# extract data
data = Array.new(array_length)
array_length.times do |i|
if @buffer.remaining >= 4
bytes = java.util.Arrays.copyOfRange(@buffer.array, @buffer.position, @buffer.position+4)
@buffer.position(@buffer.position+4)
data_length = String.from_java_bytes(bytes).unpack('V')[0]
else
@buffer.position(pos).limit(@buffer.capacity)
return
end
if @buffer.remaining >= data_length
data[i] = java.util.Arrays.copyOfRange(@buffer.array, @buffer.position, @buffer.position+data_length)
@buffer.position(@buffer.position+data_length)
else
@buffer.position(pos).limit(@buffer.capacity)
return
end
end
@buffer.compact
data
end | ruby | def read_inbound_data
ZMachine.logger.debug("zmachine:tcp_msg_channel:#{__method__}", channel: self) if ZMachine.debug
raise IOException.new("EOF") if @socket.read(@buffer) == -1
pos = @buffer.position
@buffer.flip
# validate magic
if @buffer.remaining >= 4
bytes = java.util.Arrays.copyOfRange(@buffer.array, @buffer.position, @buffer.position+4)
@buffer.position(@buffer.position+4)
if String.from_java_bytes(bytes) != MAGIC # read broken message - client should reconnect
ZMachine.logger.error("read broken message", worker: self)
close!
return
end
else
@buffer.position(pos).limit(@buffer.capacity)
return
end
# extract number of msg parts
if @buffer.remaining >= 4
bytes = java.util.Arrays.copyOfRange(@buffer.array, @buffer.position, @buffer.position+4)
@buffer.position(@buffer.position+4)
array_length = String.from_java_bytes(bytes).unpack('V')[0]
else
@buffer.position(pos).limit(@buffer.capacity)
return
end
# extract data
data = Array.new(array_length)
array_length.times do |i|
if @buffer.remaining >= 4
bytes = java.util.Arrays.copyOfRange(@buffer.array, @buffer.position, @buffer.position+4)
@buffer.position(@buffer.position+4)
data_length = String.from_java_bytes(bytes).unpack('V')[0]
else
@buffer.position(pos).limit(@buffer.capacity)
return
end
if @buffer.remaining >= data_length
data[i] = java.util.Arrays.copyOfRange(@buffer.array, @buffer.position, @buffer.position+data_length)
@buffer.position(@buffer.position+data_length)
else
@buffer.position(pos).limit(@buffer.capacity)
return
end
end
@buffer.compact
data
end | [
"def",
"read_inbound_data",
"ZMachine",
".",
"logger",
".",
"debug",
"(",
"\"zmachine:tcp_msg_channel:#{__method__}\"",
",",
"channel",
":",
"self",
")",
"if",
"ZMachine",
".",
"debug",
"raise",
"IOException",
".",
"new",
"(",
"\"EOF\"",
")",
"if",
"@socket",
".",
"read",
"(",
"@buffer",
")",
"==",
"-",
"1",
"pos",
"=",
"@buffer",
".",
"position",
"@buffer",
".",
"flip",
"if",
"@buffer",
".",
"remaining",
">=",
"4",
"bytes",
"=",
"java",
".",
"util",
".",
"Arrays",
".",
"copyOfRange",
"(",
"@buffer",
".",
"array",
",",
"@buffer",
".",
"position",
",",
"@buffer",
".",
"position",
"+",
"4",
")",
"@buffer",
".",
"position",
"(",
"@buffer",
".",
"position",
"+",
"4",
")",
"if",
"String",
".",
"from_java_bytes",
"(",
"bytes",
")",
"!=",
"MAGIC",
"ZMachine",
".",
"logger",
".",
"error",
"(",
"\"read broken message\"",
",",
"worker",
":",
"self",
")",
"close!",
"return",
"end",
"else",
"@buffer",
".",
"position",
"(",
"pos",
")",
".",
"limit",
"(",
"@buffer",
".",
"capacity",
")",
"return",
"end",
"if",
"@buffer",
".",
"remaining",
">=",
"4",
"bytes",
"=",
"java",
".",
"util",
".",
"Arrays",
".",
"copyOfRange",
"(",
"@buffer",
".",
"array",
",",
"@buffer",
".",
"position",
",",
"@buffer",
".",
"position",
"+",
"4",
")",
"@buffer",
".",
"position",
"(",
"@buffer",
".",
"position",
"+",
"4",
")",
"array_length",
"=",
"String",
".",
"from_java_bytes",
"(",
"bytes",
")",
".",
"unpack",
"(",
"'V'",
")",
"[",
"0",
"]",
"else",
"@buffer",
".",
"position",
"(",
"pos",
")",
".",
"limit",
"(",
"@buffer",
".",
"capacity",
")",
"return",
"end",
"data",
"=",
"Array",
".",
"new",
"(",
"array_length",
")",
"array_length",
".",
"times",
"do",
"|",
"i",
"|",
"if",
"@buffer",
".",
"remaining",
">=",
"4",
"bytes",
"=",
"java",
".",
"util",
".",
"Arrays",
".",
"copyOfRange",
"(",
"@buffer",
".",
"array",
",",
"@buffer",
".",
"position",
",",
"@buffer",
".",
"position",
"+",
"4",
")",
"@buffer",
".",
"position",
"(",
"@buffer",
".",
"position",
"+",
"4",
")",
"data_length",
"=",
"String",
".",
"from_java_bytes",
"(",
"bytes",
")",
".",
"unpack",
"(",
"'V'",
")",
"[",
"0",
"]",
"else",
"@buffer",
".",
"position",
"(",
"pos",
")",
".",
"limit",
"(",
"@buffer",
".",
"capacity",
")",
"return",
"end",
"if",
"@buffer",
".",
"remaining",
">=",
"data_length",
"data",
"[",
"i",
"]",
"=",
"java",
".",
"util",
".",
"Arrays",
".",
"copyOfRange",
"(",
"@buffer",
".",
"array",
",",
"@buffer",
".",
"position",
",",
"@buffer",
".",
"position",
"+",
"data_length",
")",
"@buffer",
".",
"position",
"(",
"@buffer",
".",
"position",
"+",
"data_length",
")",
"else",
"@buffer",
".",
"position",
"(",
"pos",
")",
".",
"limit",
"(",
"@buffer",
".",
"capacity",
")",
"return",
"end",
"end",
"@buffer",
".",
"compact",
"data",
"end"
] | return nil if no addional data is available | [
"return",
"nil",
"if",
"no",
"addional",
"data",
"is",
"available"
] | ded5c4e83a2378f97568e2902fb7799c2723f5f4 | https://github.com/liquidm/zmachine/blob/ded5c4e83a2378f97568e2902fb7799c2723f5f4/lib/zmachine/tcp_msg_channel.rb#L34-L90 | train |
fredemmott/rxhp | lib/rxhp/attribute_validator.rb | Rxhp.AttributeValidator.validate_attributes! | def validate_attributes!
# Check for required attributes
self.class.required_attributes.each do |matcher|
matched = self.attributes.any? do |key, value|
key = key.to_s
Rxhp::AttributeValidator.match? matcher, key, value
end
if !matched
raise MissingRequiredAttributeError.new(self, matcher)
end
end
# Check other attributes are acceptable
return true if self.attributes.empty?
self.attributes.each do |key, value|
key = key.to_s
matched = self.class.acceptable_attributes.any? do |matcher|
Rxhp::AttributeValidator.match? matcher, key, value
end
if !matched
raise UnacceptableAttributeError.new(self, key, value)
end
end
true
end | ruby | def validate_attributes!
# Check for required attributes
self.class.required_attributes.each do |matcher|
matched = self.attributes.any? do |key, value|
key = key.to_s
Rxhp::AttributeValidator.match? matcher, key, value
end
if !matched
raise MissingRequiredAttributeError.new(self, matcher)
end
end
# Check other attributes are acceptable
return true if self.attributes.empty?
self.attributes.each do |key, value|
key = key.to_s
matched = self.class.acceptable_attributes.any? do |matcher|
Rxhp::AttributeValidator.match? matcher, key, value
end
if !matched
raise UnacceptableAttributeError.new(self, key, value)
end
end
true
end | [
"def",
"validate_attributes!",
"self",
".",
"class",
".",
"required_attributes",
".",
"each",
"do",
"|",
"matcher",
"|",
"matched",
"=",
"self",
".",
"attributes",
".",
"any?",
"do",
"|",
"key",
",",
"value",
"|",
"key",
"=",
"key",
".",
"to_s",
"Rxhp",
"::",
"AttributeValidator",
".",
"match?",
"matcher",
",",
"key",
",",
"value",
"end",
"if",
"!",
"matched",
"raise",
"MissingRequiredAttributeError",
".",
"new",
"(",
"self",
",",
"matcher",
")",
"end",
"end",
"return",
"true",
"if",
"self",
".",
"attributes",
".",
"empty?",
"self",
".",
"attributes",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"key",
"=",
"key",
".",
"to_s",
"matched",
"=",
"self",
".",
"class",
".",
"acceptable_attributes",
".",
"any?",
"do",
"|",
"matcher",
"|",
"Rxhp",
"::",
"AttributeValidator",
".",
"match?",
"matcher",
",",
"key",
",",
"value",
"end",
"if",
"!",
"matched",
"raise",
"UnacceptableAttributeError",
".",
"new",
"(",
"self",
",",
"key",
",",
"value",
")",
"end",
"end",
"true",
"end"
] | Check if attributes are valid, and raise an exception if they're not.
@raise {MissingRequiredAttributeError} if an attribute that is
required was not provided.
@raise {UnacceptableAttributeError} if a non-whitelisted attribute
was provided.
@return [true] if the attribute are all valid, and all required
attributes are provided. | [
"Check",
"if",
"attributes",
"are",
"valid",
"and",
"raise",
"an",
"exception",
"if",
"they",
"re",
"not",
"."
] | 45b39680c64e3a47741c4ba2ab6a92c1a4c1b975 | https://github.com/fredemmott/rxhp/blob/45b39680c64e3a47741c4ba2ab6a92c1a4c1b975/lib/rxhp/attribute_validator.rb#L64-L89 | train |
fredemmott/rxhp | lib/rxhp/html_element.rb | Rxhp.HtmlElement.render | def render options = {}
validate!
options = fill_options(options)
open = render_open_tag(options)
inner = render_children(options)
close = render_close_tag(options)
if options[:pretty]
indent = ' ' * (options[:indent] * options[:depth])
out = indent.dup
out << open << "\n"
out << inner if inner
out << indent << close << "\n" if close && !close.empty?
out
else
out = open
out << inner if inner
out << close if close
out
end
end | ruby | def render options = {}
validate!
options = fill_options(options)
open = render_open_tag(options)
inner = render_children(options)
close = render_close_tag(options)
if options[:pretty]
indent = ' ' * (options[:indent] * options[:depth])
out = indent.dup
out << open << "\n"
out << inner if inner
out << indent << close << "\n" if close && !close.empty?
out
else
out = open
out << inner if inner
out << close if close
out
end
end | [
"def",
"render",
"options",
"=",
"{",
"}",
"validate!",
"options",
"=",
"fill_options",
"(",
"options",
")",
"open",
"=",
"render_open_tag",
"(",
"options",
")",
"inner",
"=",
"render_children",
"(",
"options",
")",
"close",
"=",
"render_close_tag",
"(",
"options",
")",
"if",
"options",
"[",
":pretty",
"]",
"indent",
"=",
"' '",
"*",
"(",
"options",
"[",
":indent",
"]",
"*",
"options",
"[",
":depth",
"]",
")",
"out",
"=",
"indent",
".",
"dup",
"out",
"<<",
"open",
"<<",
"\"\\n\"",
"out",
"<<",
"inner",
"if",
"inner",
"out",
"<<",
"indent",
"<<",
"close",
"<<",
"\"\\n\"",
"if",
"close",
"&&",
"!",
"close",
".",
"empty?",
"out",
"else",
"out",
"=",
"open",
"out",
"<<",
"inner",
"if",
"inner",
"out",
"<<",
"close",
"if",
"close",
"out",
"end",
"end"
] | Render the element.
Pays attention to the formatter type, doctype, pretty print options,
etc. See {Element#render} for options. | [
"Render",
"the",
"element",
"."
] | 45b39680c64e3a47741c4ba2ab6a92c1a4c1b975 | https://github.com/fredemmott/rxhp/blob/45b39680c64e3a47741c4ba2ab6a92c1a4c1b975/lib/rxhp/html_element.rb#L54-L75 | train |
fredemmott/rxhp | lib/rxhp/html_element.rb | Rxhp.HtmlElement.render_string | def render_string string, options
escaped = html_escape(string)
if options[:pretty]
indent = ' ' * (options[:indent] * options[:depth])
indent + escaped + "\n"
else
escaped
end
end | ruby | def render_string string, options
escaped = html_escape(string)
if options[:pretty]
indent = ' ' * (options[:indent] * options[:depth])
indent + escaped + "\n"
else
escaped
end
end | [
"def",
"render_string",
"string",
",",
"options",
"escaped",
"=",
"html_escape",
"(",
"string",
")",
"if",
"options",
"[",
":pretty",
"]",
"indent",
"=",
"' '",
"*",
"(",
"options",
"[",
":indent",
"]",
"*",
"options",
"[",
":depth",
"]",
")",
"indent",
"+",
"escaped",
"+",
"\"\\n\"",
"else",
"escaped",
"end",
"end"
] | html-escape a string, paying attention to indentation too. | [
"html",
"-",
"escape",
"a",
"string",
"paying",
"attention",
"to",
"indentation",
"too",
"."
] | 45b39680c64e3a47741c4ba2ab6a92c1a4c1b975 | https://github.com/fredemmott/rxhp/blob/45b39680c64e3a47741c4ba2ab6a92c1a4c1b975/lib/rxhp/html_element.rb#L89-L97 | train |
fredemmott/rxhp | lib/rxhp/html_element.rb | Rxhp.HtmlElement.render_open_tag | def render_open_tag options
out = '<' + tag_name
unless attributes.empty?
attributes.each do |name,value|
name = name.to_s.gsub('_', '-') if name.is_a? Symbol
value = value.to_s.gsub('_', '-') if value.is_a? Symbol
case value
when false
next
when true
if options[:format] == Rxhp::XHTML_FORMAT
out += ' ' + name + '="' + name + '"'
else
out += ' ' + name
end
else
out += ' ' + name.to_s + '="' + html_escape(value.to_s) + '"'
end
end
end
if options[:format] == Rxhp::XHTML_FORMAT && !children?
out + ' />'
else
out + '>'
end
end | ruby | def render_open_tag options
out = '<' + tag_name
unless attributes.empty?
attributes.each do |name,value|
name = name.to_s.gsub('_', '-') if name.is_a? Symbol
value = value.to_s.gsub('_', '-') if value.is_a? Symbol
case value
when false
next
when true
if options[:format] == Rxhp::XHTML_FORMAT
out += ' ' + name + '="' + name + '"'
else
out += ' ' + name
end
else
out += ' ' + name.to_s + '="' + html_escape(value.to_s) + '"'
end
end
end
if options[:format] == Rxhp::XHTML_FORMAT && !children?
out + ' />'
else
out + '>'
end
end | [
"def",
"render_open_tag",
"options",
"out",
"=",
"'<'",
"+",
"tag_name",
"unless",
"attributes",
".",
"empty?",
"attributes",
".",
"each",
"do",
"|",
"name",
",",
"value",
"|",
"name",
"=",
"name",
".",
"to_s",
".",
"gsub",
"(",
"'_'",
",",
"'-'",
")",
"if",
"name",
".",
"is_a?",
"Symbol",
"value",
"=",
"value",
".",
"to_s",
".",
"gsub",
"(",
"'_'",
",",
"'-'",
")",
"if",
"value",
".",
"is_a?",
"Symbol",
"case",
"value",
"when",
"false",
"next",
"when",
"true",
"if",
"options",
"[",
":format",
"]",
"==",
"Rxhp",
"::",
"XHTML_FORMAT",
"out",
"+=",
"' '",
"+",
"name",
"+",
"'=\"'",
"+",
"name",
"+",
"'\"'",
"else",
"out",
"+=",
"' '",
"+",
"name",
"end",
"else",
"out",
"+=",
"' '",
"+",
"name",
".",
"to_s",
"+",
"'=\"'",
"+",
"html_escape",
"(",
"value",
".",
"to_s",
")",
"+",
"'\"'",
"end",
"end",
"end",
"if",
"options",
"[",
":format",
"]",
"==",
"Rxhp",
"::",
"XHTML_FORMAT",
"&&",
"!",
"children?",
"out",
"+",
"' />'",
"else",
"out",
"+",
"'>'",
"end",
"end"
] | Render the opening tag.
Considers:
- attributes
- XHTML or HTML?
- are there any children?
#render_close_tag assumes that this will not leave a tag open in XHTML
unless there are children. | [
"Render",
"the",
"opening",
"tag",
"."
] | 45b39680c64e3a47741c4ba2ab6a92c1a4c1b975 | https://github.com/fredemmott/rxhp/blob/45b39680c64e3a47741c4ba2ab6a92c1a4c1b975/lib/rxhp/html_element.rb#L108-L135 | train |
fredemmott/rxhp | lib/rxhp/element.rb | Rxhp.Element.render_children | def render_children options = {}
return if children.empty?
flattened_children.map{ |child| render_child(child, options) }.join
end | ruby | def render_children options = {}
return if children.empty?
flattened_children.map{ |child| render_child(child, options) }.join
end | [
"def",
"render_children",
"options",
"=",
"{",
"}",
"return",
"if",
"children",
".",
"empty?",
"flattened_children",
".",
"map",
"{",
"|",
"child",
"|",
"render_child",
"(",
"child",
",",
"options",
")",
"}",
".",
"join",
"end"
] | Iterate over all the children, calling render. | [
"Iterate",
"over",
"all",
"the",
"children",
"calling",
"render",
"."
] | 45b39680c64e3a47741c4ba2ab6a92c1a4c1b975 | https://github.com/fredemmott/rxhp/blob/45b39680c64e3a47741c4ba2ab6a92c1a4c1b975/lib/rxhp/element.rb#L79-L83 | train |
fredemmott/rxhp | lib/rxhp/element.rb | Rxhp.Element.fill_options | def fill_options options
{
:pretty => true,
:format => Rxhp::HTML_FORMAT,
:skip_doctype => false,
:doctype => Rxhp::HTML_5,
:depth => 0,
:indent => 2,
}.merge(options)
end | ruby | def fill_options options
{
:pretty => true,
:format => Rxhp::HTML_FORMAT,
:skip_doctype => false,
:doctype => Rxhp::HTML_5,
:depth => 0,
:indent => 2,
}.merge(options)
end | [
"def",
"fill_options",
"options",
"{",
":pretty",
"=>",
"true",
",",
":format",
"=>",
"Rxhp",
"::",
"HTML_FORMAT",
",",
":skip_doctype",
"=>",
"false",
",",
":doctype",
"=>",
"Rxhp",
"::",
"HTML_5",
",",
":depth",
"=>",
"0",
",",
":indent",
"=>",
"2",
",",
"}",
".",
"merge",
"(",
"options",
")",
"end"
] | Fill default render options.
These are as defined for {#render}, with the addition of a
+:depth+ value of 0. Other values aren't guaranteed to stay fixed,
check source for current values. | [
"Fill",
"default",
"render",
"options",
"."
] | 45b39680c64e3a47741c4ba2ab6a92c1a4c1b975 | https://github.com/fredemmott/rxhp/blob/45b39680c64e3a47741c4ba2ab6a92c1a4c1b975/lib/rxhp/element.rb#L90-L99 | train |
fredemmott/rxhp | lib/rxhp/element.rb | Rxhp.Element.flattened_children | def flattened_children
no_frags = []
children.each do |node|
if node.is_a? Rxhp::Fragment
no_frags += node.children
else
no_frags.push node
end
end
previous = nil
no_consecutive_strings = []
no_frags.each do |node|
if node.is_a?(String) && previous.is_a?(String)
previous << node
else
no_consecutive_strings.push node
previous = node
end
end
no_consecutive_strings
end | ruby | def flattened_children
no_frags = []
children.each do |node|
if node.is_a? Rxhp::Fragment
no_frags += node.children
else
no_frags.push node
end
end
previous = nil
no_consecutive_strings = []
no_frags.each do |node|
if node.is_a?(String) && previous.is_a?(String)
previous << node
else
no_consecutive_strings.push node
previous = node
end
end
no_consecutive_strings
end | [
"def",
"flattened_children",
"no_frags",
"=",
"[",
"]",
"children",
".",
"each",
"do",
"|",
"node",
"|",
"if",
"node",
".",
"is_a?",
"Rxhp",
"::",
"Fragment",
"no_frags",
"+=",
"node",
".",
"children",
"else",
"no_frags",
".",
"push",
"node",
"end",
"end",
"previous",
"=",
"nil",
"no_consecutive_strings",
"=",
"[",
"]",
"no_frags",
".",
"each",
"do",
"|",
"node",
"|",
"if",
"node",
".",
"is_a?",
"(",
"String",
")",
"&&",
"previous",
".",
"is_a?",
"(",
"String",
")",
"previous",
"<<",
"node",
"else",
"no_consecutive_strings",
".",
"push",
"node",
"previous",
"=",
"node",
"end",
"end",
"no_consecutive_strings",
"end"
] | Normalize the children.
For example, turn +['foo', 'bar']+ into +['foobar']+.
This is needed to stop things like pretty printing adding extra
whitespace between the two strings. | [
"Normalize",
"the",
"children",
"."
] | 45b39680c64e3a47741c4ba2ab6a92c1a4c1b975 | https://github.com/fredemmott/rxhp/blob/45b39680c64e3a47741c4ba2ab6a92c1a4c1b975/lib/rxhp/element.rb#L122-L144 | train |
fredemmott/rxhp | lib/rxhp/composable_element.rb | Rxhp.ComposableElement.render | def render options = {}
validate!
self.compose do
# Allow 'yield' to embed all children
self.children.each do |child|
fragment child
end
end.render(options)
end | ruby | def render options = {}
validate!
self.compose do
# Allow 'yield' to embed all children
self.children.each do |child|
fragment child
end
end.render(options)
end | [
"def",
"render",
"options",
"=",
"{",
"}",
"validate!",
"self",
".",
"compose",
"do",
"self",
".",
"children",
".",
"each",
"do",
"|",
"child",
"|",
"fragment",
"child",
"end",
"end",
".",
"render",
"(",
"options",
")",
"end"
] | You don't want to implement this function in your subclasses -
just reimplement compose instead.
This calls compose, provides the 'yield' magic, and callls render on
the output. | [
"You",
"don",
"t",
"want",
"to",
"implement",
"this",
"function",
"in",
"your",
"subclasses",
"-",
"just",
"reimplement",
"compose",
"instead",
"."
] | 45b39680c64e3a47741c4ba2ab6a92c1a4c1b975 | https://github.com/fredemmott/rxhp/blob/45b39680c64e3a47741c4ba2ab6a92c1a4c1b975/lib/rxhp/composable_element.rb#L17-L25 | train |
liquidm/zmachine | lib/zmachine/connection.rb | ZMachine.Connection.bind | def bind(address, port_or_type, &block)
ZMachine.logger.debug("zmachine:connection:#{__method__}", connection: self) if ZMachine.debug
klass = channel_class(address)
@channel = klass.new
@channel.bind(sanitize_adress(address, klass), port_or_type)
@block = block
@block.call(self) if @block && @channel.is_a?(ZMQChannel)
self
end | ruby | def bind(address, port_or_type, &block)
ZMachine.logger.debug("zmachine:connection:#{__method__}", connection: self) if ZMachine.debug
klass = channel_class(address)
@channel = klass.new
@channel.bind(sanitize_adress(address, klass), port_or_type)
@block = block
@block.call(self) if @block && @channel.is_a?(ZMQChannel)
self
end | [
"def",
"bind",
"(",
"address",
",",
"port_or_type",
",",
"&",
"block",
")",
"ZMachine",
".",
"logger",
".",
"debug",
"(",
"\"zmachine:connection:#{__method__}\"",
",",
"connection",
":",
"self",
")",
"if",
"ZMachine",
".",
"debug",
"klass",
"=",
"channel_class",
"(",
"address",
")",
"@channel",
"=",
"klass",
".",
"new",
"@channel",
".",
"bind",
"(",
"sanitize_adress",
"(",
"address",
",",
"klass",
")",
",",
"port_or_type",
")",
"@block",
"=",
"block",
"@block",
".",
"call",
"(",
"self",
")",
"if",
"@block",
"&&",
"@channel",
".",
"is_a?",
"(",
"ZMQChannel",
")",
"self",
"end"
] | channel type dispatch | [
"channel",
"type",
"dispatch"
] | ded5c4e83a2378f97568e2902fb7799c2723f5f4 | https://github.com/liquidm/zmachine/blob/ded5c4e83a2378f97568e2902fb7799c2723f5f4/lib/zmachine/connection.rb#L26-L34 | train |
datasift/datasift-ruby | lib/account.rb | DataSift.Account.usage | def usage(start_time, end_time, period = '')
params = { start: start_time, end: end_time }
params.merge!(period: period) unless period.empty?
DataSift.request(:GET, 'account/usage', @config, params)
end | ruby | def usage(start_time, end_time, period = '')
params = { start: start_time, end: end_time }
params.merge!(period: period) unless period.empty?
DataSift.request(:GET, 'account/usage', @config, params)
end | [
"def",
"usage",
"(",
"start_time",
",",
"end_time",
",",
"period",
"=",
"''",
")",
"params",
"=",
"{",
"start",
":",
"start_time",
",",
"end",
":",
"end_time",
"}",
"params",
".",
"merge!",
"(",
"period",
":",
"period",
")",
"unless",
"period",
".",
"empty?",
"DataSift",
".",
"request",
"(",
":GET",
",",
"'account/usage'",
",",
"@config",
",",
"params",
")",
"end"
] | Check your account usage for a given period and timeframe
@param period [String] (Optional) Period is one of either hourly, daily or monthly
@param start_time [Integer] (Optional) Unix timestamp of the start of the period
you are querying
@param end_time [Integer] (Optional) Unix timestamp of the end of the period
you are querying
@return [Object] API reponse object | [
"Check",
"your",
"account",
"usage",
"for",
"a",
"given",
"period",
"and",
"timeframe"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/account.rb#L13-L18 | train |
zhimin/rwebspec | lib/rwebspec-webdriver/web_browser.rb | RWebSpec.WebBrowser.locate_input_element | def locate_input_element(how, what, types, value=nil)
@browser.locate_input_element(how, what, types, value)
end | ruby | def locate_input_element(how, what, types, value=nil)
@browser.locate_input_element(how, what, types, value)
end | [
"def",
"locate_input_element",
"(",
"how",
",",
"what",
",",
"types",
",",
"value",
"=",
"nil",
")",
"@browser",
".",
"locate_input_element",
"(",
"how",
",",
"what",
",",
"types",
",",
"value",
")",
"end"
] | Returns the specified ole object for input elements on a web page.
This method is used internally by Watir and should not be used externally. It cannot be marked as private because of the way mixins and inheritance work in watir
* how - symbol - the way we look for the object. Supported values are
- :name
- :id
- :index
- :value etc
* what - string that we are looking for, ex. the name, or id tag attribute or index of the object we are looking for.
* types - what object types we will look at.
* value - used for objects that have one name, but many values. ex. radio lists and checkboxes | [
"Returns",
"the",
"specified",
"ole",
"object",
"for",
"input",
"elements",
"on",
"a",
"web",
"page",
"."
] | aafccee2ba66d17d591d04210067035feaf2f892 | https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-webdriver/web_browser.rb#L217-L219 | train |
zhimin/rwebspec | lib/rwebspec-webdriver/web_browser.rb | RWebSpec.WebBrowser.click_button_with_caption | def click_button_with_caption(caption, opts={})
all_buttons = button_elements
matching_buttons = all_buttons.select{|x| x.attribute('value') == caption}
if matching_buttons.size > 0
if opts && opts[:index]
the_index = opts[:index].to_i() - 1
puts "Call matching buttons: #{matching_buttons.inspect} => #{the_index}"
first_match = matching_buttons[the_index]
first_match.click
else
the_button = matching_buttons[0]
the_button.click
end
else
raise "No button with value: #{caption} found"
end
end | ruby | def click_button_with_caption(caption, opts={})
all_buttons = button_elements
matching_buttons = all_buttons.select{|x| x.attribute('value') == caption}
if matching_buttons.size > 0
if opts && opts[:index]
the_index = opts[:index].to_i() - 1
puts "Call matching buttons: #{matching_buttons.inspect} => #{the_index}"
first_match = matching_buttons[the_index]
first_match.click
else
the_button = matching_buttons[0]
the_button.click
end
else
raise "No button with value: #{caption} found"
end
end | [
"def",
"click_button_with_caption",
"(",
"caption",
",",
"opts",
"=",
"{",
"}",
")",
"all_buttons",
"=",
"button_elements",
"matching_buttons",
"=",
"all_buttons",
".",
"select",
"{",
"|",
"x",
"|",
"x",
".",
"attribute",
"(",
"'value'",
")",
"==",
"caption",
"}",
"if",
"matching_buttons",
".",
"size",
">",
"0",
"if",
"opts",
"&&",
"opts",
"[",
":index",
"]",
"the_index",
"=",
"opts",
"[",
":index",
"]",
".",
"to_i",
"(",
")",
"-",
"1",
"puts",
"\"Call matching buttons: #{matching_buttons.inspect} => #{the_index}\"",
"first_match",
"=",
"matching_buttons",
"[",
"the_index",
"]",
"first_match",
".",
"click",
"else",
"the_button",
"=",
"matching_buttons",
"[",
"0",
"]",
"the_button",
".",
"click",
"end",
"else",
"raise",
"\"No button with value: #{caption} found\"",
"end",
"end"
] | Click a button with caption
TODO: Caption is same as value
Usage:
click_button_with_caption("Confirm payment") | [
"Click",
"a",
"button",
"with",
"caption"
] | aafccee2ba66d17d591d04210067035feaf2f892 | https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-webdriver/web_browser.rb#L525-L543 | train |
zhimin/rwebspec | lib/rwebspec-webdriver/web_browser.rb | RWebSpec.WebBrowser.submit | def submit(buttonName = nil)
if (buttonName.nil?) then
buttons.each { |button|
next if button.type != 'submit'
button.click
return
}
else
click_button_with_name(buttonName)
end
end | ruby | def submit(buttonName = nil)
if (buttonName.nil?) then
buttons.each { |button|
next if button.type != 'submit'
button.click
return
}
else
click_button_with_name(buttonName)
end
end | [
"def",
"submit",
"(",
"buttonName",
"=",
"nil",
")",
"if",
"(",
"buttonName",
".",
"nil?",
")",
"then",
"buttons",
".",
"each",
"{",
"|",
"button",
"|",
"next",
"if",
"button",
".",
"type",
"!=",
"'submit'",
"button",
".",
"click",
"return",
"}",
"else",
"click_button_with_name",
"(",
"buttonName",
")",
"end",
"end"
] | submit first submit button | [
"submit",
"first",
"submit",
"button"
] | aafccee2ba66d17d591d04210067035feaf2f892 | https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-webdriver/web_browser.rb#L590-L600 | train |
FTB-Gamepedia/MediaWiki-Butt-Ruby | lib/mediawiki/watch.rb | MediaWiki.Watch.watch_request | def watch_request(titles, unwatch = false)
titles = titles.is_a?(Array) ? titles : [titles]
params = {
action: 'watch',
titles: titles.shift(get_limited(titles.length, 50, 500)).join('|'),
token: get_token('watch')
}
success_key = 'watched'
if unwatch
params[:unwatch] = 1
success_key = 'unwatched'
end
post(params)['watch'].inject({}) do |result, entry|
title = entry['title']
if entry.key?(success_key)
result[title] = entry.key?('missing') ? nil : true
else
result[title] = false
end
result
end
end | ruby | def watch_request(titles, unwatch = false)
titles = titles.is_a?(Array) ? titles : [titles]
params = {
action: 'watch',
titles: titles.shift(get_limited(titles.length, 50, 500)).join('|'),
token: get_token('watch')
}
success_key = 'watched'
if unwatch
params[:unwatch] = 1
success_key = 'unwatched'
end
post(params)['watch'].inject({}) do |result, entry|
title = entry['title']
if entry.key?(success_key)
result[title] = entry.key?('missing') ? nil : true
else
result[title] = false
end
result
end
end | [
"def",
"watch_request",
"(",
"titles",
",",
"unwatch",
"=",
"false",
")",
"titles",
"=",
"titles",
".",
"is_a?",
"(",
"Array",
")",
"?",
"titles",
":",
"[",
"titles",
"]",
"params",
"=",
"{",
"action",
":",
"'watch'",
",",
"titles",
":",
"titles",
".",
"shift",
"(",
"get_limited",
"(",
"titles",
".",
"length",
",",
"50",
",",
"500",
")",
")",
".",
"join",
"(",
"'|'",
")",
",",
"token",
":",
"get_token",
"(",
"'watch'",
")",
"}",
"success_key",
"=",
"'watched'",
"if",
"unwatch",
"params",
"[",
":unwatch",
"]",
"=",
"1",
"success_key",
"=",
"'unwatched'",
"end",
"post",
"(",
"params",
")",
"[",
"'watch'",
"]",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"result",
",",
"entry",
"|",
"title",
"=",
"entry",
"[",
"'title'",
"]",
"if",
"entry",
".",
"key?",
"(",
"success_key",
")",
"result",
"[",
"title",
"]",
"=",
"entry",
".",
"key?",
"(",
"'missing'",
")",
"?",
"nil",
":",
"true",
"else",
"result",
"[",
"title",
"]",
"=",
"false",
"end",
"result",
"end",
"end"
] | Submits a watch action request.
@param (see #watch)
@param unwatch [Boolean] Whether the request should unwatch the pages or not.
@return (see #watch) | [
"Submits",
"a",
"watch",
"action",
"request",
"."
] | d71c5dfdf9d349d025e1c3534286ce116777eaa4 | https://github.com/FTB-Gamepedia/MediaWiki-Butt-Ruby/blob/d71c5dfdf9d349d025e1c3534286ce116777eaa4/lib/mediawiki/watch.rb#L26-L49 | train |
zhimin/rwebspec | lib/rwebspec-common/core.rb | RWebSpec.Core.failsafe | def failsafe(& block)
begin
yield
rescue RWebSpec::Assertion => e1
rescue ArgumentError => ae
rescue RSpec::Expectations::ExpectationNotMetError => ree
rescue =>e
end
end | ruby | def failsafe(& block)
begin
yield
rescue RWebSpec::Assertion => e1
rescue ArgumentError => ae
rescue RSpec::Expectations::ExpectationNotMetError => ree
rescue =>e
end
end | [
"def",
"failsafe",
"(",
"&",
"block",
")",
"begin",
"yield",
"rescue",
"RWebSpec",
"::",
"Assertion",
"=>",
"e1",
"rescue",
"ArgumentError",
"=>",
"ae",
"rescue",
"RSpec",
"::",
"Expectations",
"::",
"ExpectationNotMetError",
"=>",
"ree",
"rescue",
"=>",
"e",
"end",
"end"
] | try operation, ignore if errors occur
Example:
failsafe { click_link("Logout") } # try logout, but it still OK if not being able to (already logout)) | [
"try",
"operation",
"ignore",
"if",
"errors",
"occur"
] | aafccee2ba66d17d591d04210067035feaf2f892 | https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-common/core.rb#L254-L262 | train |
zhimin/rwebspec | lib/rwebspec-common/core.rb | RWebSpec.Core.random_string_in | def random_string_in(arr)
return nil if arr.empty?
index = random_number(0, arr.length-1)
arr[index]
end | ruby | def random_string_in(arr)
return nil if arr.empty?
index = random_number(0, arr.length-1)
arr[index]
end | [
"def",
"random_string_in",
"(",
"arr",
")",
"return",
"nil",
"if",
"arr",
".",
"empty?",
"index",
"=",
"random_number",
"(",
"0",
",",
"arr",
".",
"length",
"-",
"1",
")",
"arr",
"[",
"index",
"]",
"end"
] | Return a random string in a rangeof pre-defined strings | [
"Return",
"a",
"random",
"string",
"in",
"a",
"rangeof",
"pre",
"-",
"defined",
"strings"
] | aafccee2ba66d17d591d04210067035feaf2f892 | https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-common/core.rb#L355-L359 | train |
zhimin/rwebspec | lib/rwebspec-common/core.rb | RWebSpec.Core.interpret_value | def interpret_value(value)
case value
when Array then value.rand
when Range then value_in_range(value)
else value
end
end | ruby | def interpret_value(value)
case value
when Array then value.rand
when Range then value_in_range(value)
else value
end
end | [
"def",
"interpret_value",
"(",
"value",
")",
"case",
"value",
"when",
"Array",
"then",
"value",
".",
"rand",
"when",
"Range",
"then",
"value_in_range",
"(",
"value",
")",
"else",
"value",
"end",
"end"
] | If an array or range is passed, a random value will be selected to match.
All other values are simply returned. | [
"If",
"an",
"array",
"or",
"range",
"is",
"passed",
"a",
"random",
"value",
"will",
"be",
"selected",
"to",
"match",
".",
"All",
"other",
"values",
"are",
"simply",
"returned",
"."
] | aafccee2ba66d17d591d04210067035feaf2f892 | https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-common/core.rb#L403-L409 | train |
zhimin/rwebspec | lib/rwebspec-common/core.rb | RWebSpec.Core.process_each_row_in_csv_file | def process_each_row_in_csv_file(csv_file, &block)
require 'faster_csv'
connect_to_testwise("CSV_START", csv_file) if $testwise_support
has_error = false
idx = 0
FasterCSV.foreach(csv_file, :headers => :first_row, :encoding => 'u') do |row|
connect_to_testwise("CSV_ON_ROW", idx.to_s) if $testwise_support
begin
yield row
connect_to_testwise("CSV_ROW_PASS", idx.to_s) if $testwise_support
rescue => e
connect_to_testwise("CSV_ROW_FAIL", idx.to_s) if $testwise_support
has_error = true
ensure
idx += 1
end
end
connect_to_testwise("CSV_END", "") if $testwise_support
raise "Test failed on data" if has_error
end | ruby | def process_each_row_in_csv_file(csv_file, &block)
require 'faster_csv'
connect_to_testwise("CSV_START", csv_file) if $testwise_support
has_error = false
idx = 0
FasterCSV.foreach(csv_file, :headers => :first_row, :encoding => 'u') do |row|
connect_to_testwise("CSV_ON_ROW", idx.to_s) if $testwise_support
begin
yield row
connect_to_testwise("CSV_ROW_PASS", idx.to_s) if $testwise_support
rescue => e
connect_to_testwise("CSV_ROW_FAIL", idx.to_s) if $testwise_support
has_error = true
ensure
idx += 1
end
end
connect_to_testwise("CSV_END", "") if $testwise_support
raise "Test failed on data" if has_error
end | [
"def",
"process_each_row_in_csv_file",
"(",
"csv_file",
",",
"&",
"block",
")",
"require",
"'faster_csv'",
"connect_to_testwise",
"(",
"\"CSV_START\"",
",",
"csv_file",
")",
"if",
"$testwise_support",
"has_error",
"=",
"false",
"idx",
"=",
"0",
"FasterCSV",
".",
"foreach",
"(",
"csv_file",
",",
":headers",
"=>",
":first_row",
",",
":encoding",
"=>",
"'u'",
")",
"do",
"|",
"row",
"|",
"connect_to_testwise",
"(",
"\"CSV_ON_ROW\"",
",",
"idx",
".",
"to_s",
")",
"if",
"$testwise_support",
"begin",
"yield",
"row",
"connect_to_testwise",
"(",
"\"CSV_ROW_PASS\"",
",",
"idx",
".",
"to_s",
")",
"if",
"$testwise_support",
"rescue",
"=>",
"e",
"connect_to_testwise",
"(",
"\"CSV_ROW_FAIL\"",
",",
"idx",
".",
"to_s",
")",
"if",
"$testwise_support",
"has_error",
"=",
"true",
"ensure",
"idx",
"+=",
"1",
"end",
"end",
"connect_to_testwise",
"(",
"\"CSV_END\"",
",",
"\"\"",
")",
"if",
"$testwise_support",
"raise",
"\"Test failed on data\"",
"if",
"has_error",
"end"
] | Data Driven Tests
Processing each row in a CSV file, must have heading rows
Usage:
process_each_row_in_csv_file(@csv_file) { |row|
goto_page("/")
enter_text("username", row[1])
enter_text("password", row[2])
click_button("Sign in")
page_text.should contain(row[3])
failsafe{ click_link("Sign off") }
} | [
"Data",
"Driven",
"Tests"
] | aafccee2ba66d17d591d04210067035feaf2f892 | https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-common/core.rb#L488-L508 | train |
xing/crep | lib/crep/crash_controller.rb | Crep.CrashController.top_crashes | def top_crashes(version, build)
@version = version
@build = build
@crashes = @crash_source.crashes(@top, version, build, @show_only_unresolved)
@total_crashes = @crash_source.crash_count(version: @version, build: @build)
report
end | ruby | def top_crashes(version, build)
@version = version
@build = build
@crashes = @crash_source.crashes(@top, version, build, @show_only_unresolved)
@total_crashes = @crash_source.crash_count(version: @version, build: @build)
report
end | [
"def",
"top_crashes",
"(",
"version",
",",
"build",
")",
"@version",
"=",
"version",
"@build",
"=",
"build",
"@crashes",
"=",
"@crash_source",
".",
"crashes",
"(",
"@top",
",",
"version",
",",
"build",
",",
"@show_only_unresolved",
")",
"@total_crashes",
"=",
"@crash_source",
".",
"crash_count",
"(",
"version",
":",
"@version",
",",
"build",
":",
"@build",
")",
"report",
"end"
] | returns list of top crashes for the given build | [
"returns",
"list",
"of",
"top",
"crashes",
"for",
"the",
"given",
"build"
] | bee045b59cf3bfd40e2a7f1d3dd3d749bd3d4614 | https://github.com/xing/crep/blob/bee045b59cf3bfd40e2a7f1d3dd3d749bd3d4614/lib/crep/crash_controller.rb#L32-L38 | train |
zhimin/rwebspec | lib/rwebspec-watir/driver.rb | RWebSpec.Driver.attach_browser | def attach_browser(how, what, options = {})
options.merge!(:browser => is_firefox? ? "Firefox" : "IE") unless options[:browser]
begin
options.merge!(:base_url => browser.context.base_url)
rescue => e
puts "failed to set base_url, ignore : #{e}"
end
WebBrowser.attach_browser(how, what, options)
end | ruby | def attach_browser(how, what, options = {})
options.merge!(:browser => is_firefox? ? "Firefox" : "IE") unless options[:browser]
begin
options.merge!(:base_url => browser.context.base_url)
rescue => e
puts "failed to set base_url, ignore : #{e}"
end
WebBrowser.attach_browser(how, what, options)
end | [
"def",
"attach_browser",
"(",
"how",
",",
"what",
",",
"options",
"=",
"{",
"}",
")",
"options",
".",
"merge!",
"(",
":browser",
"=>",
"is_firefox?",
"?",
"\"Firefox\"",
":",
"\"IE\"",
")",
"unless",
"options",
"[",
":browser",
"]",
"begin",
"options",
".",
"merge!",
"(",
":base_url",
"=>",
"browser",
".",
"context",
".",
"base_url",
")",
"rescue",
"=>",
"e",
"puts",
"\"failed to set base_url, ignore : #{e}\"",
"end",
"WebBrowser",
".",
"attach_browser",
"(",
"how",
",",
"what",
",",
"options",
")",
"end"
] | Attach to existing browser window
attach_browser(:title, "Page" )
attach_browser(:url, "http://wwww..." ) | [
"Attach",
"to",
"existing",
"browser",
"window"
] | aafccee2ba66d17d591d04210067035feaf2f892 | https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-watir/driver.rb#L204-L212 | train |
zhimin/rwebspec | lib/rwebspec-watir/driver.rb | RWebSpec.Driver.enter_text_with_id | def enter_text_with_id(textfield_id, value, opts = {})
# For IE10, it seems unable to identify HTML5 elements
#
# However for IE10, the '.' is omitted.
if opts.nil? || opts.empty?
# for Watir, default is clear
opts[:appending] = false
end
perform_operation {
begin
text_field(:id, textfield_id).set(value)
rescue => e
# However, this approach is not reliable with Watir (IE)
# for example, for entering email, the dot cannot be entered, try ["a@b", :decimal, "com"]
the_elem = element(:xpath, "//input[@id='#{textfield_id}']")
the_elem.send_keys(:clear) unless opts[:appending]
the_elem.send_keys(value)
end
}
end | ruby | def enter_text_with_id(textfield_id, value, opts = {})
# For IE10, it seems unable to identify HTML5 elements
#
# However for IE10, the '.' is omitted.
if opts.nil? || opts.empty?
# for Watir, default is clear
opts[:appending] = false
end
perform_operation {
begin
text_field(:id, textfield_id).set(value)
rescue => e
# However, this approach is not reliable with Watir (IE)
# for example, for entering email, the dot cannot be entered, try ["a@b", :decimal, "com"]
the_elem = element(:xpath, "//input[@id='#{textfield_id}']")
the_elem.send_keys(:clear) unless opts[:appending]
the_elem.send_keys(value)
end
}
end | [
"def",
"enter_text_with_id",
"(",
"textfield_id",
",",
"value",
",",
"opts",
"=",
"{",
"}",
")",
"if",
"opts",
".",
"nil?",
"||",
"opts",
".",
"empty?",
"opts",
"[",
":appending",
"]",
"=",
"false",
"end",
"perform_operation",
"{",
"begin",
"text_field",
"(",
":id",
",",
"textfield_id",
")",
".",
"set",
"(",
"value",
")",
"rescue",
"=>",
"e",
"the_elem",
"=",
"element",
"(",
":xpath",
",",
"\"//input[@id='#{textfield_id}']\"",
")",
"the_elem",
".",
"send_keys",
"(",
":clear",
")",
"unless",
"opts",
"[",
":appending",
"]",
"the_elem",
".",
"send_keys",
"(",
"value",
")",
"end",
"}",
"end"
] | for text field can be easier to be identified by attribute "id" instead of "name", not recommended though
params opts takes :appending => true or false, if true, won't clear the text field. | [
"for",
"text",
"field",
"can",
"be",
"easier",
"to",
"be",
"identified",
"by",
"attribute",
"id",
"instead",
"of",
"name",
"not",
"recommended",
"though"
] | aafccee2ba66d17d591d04210067035feaf2f892 | https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-watir/driver.rb#L319-L340 | train |
zhimin/rwebspec | lib/rwebspec-watir/driver.rb | RWebSpec.Driver.absolutize_page | def absolutize_page(content, base_url, current_url_parent)
modified_content = ""
content.each_line do |line|
if line =~ /<script\s+.*src=["'']?(.*)["'].*/i then
script_src = $1
substitute_relative_path_in_src_line(line, script_src, base_url, current_url_parent)
elsif line =~ /<link\s+.*href=["'']?(.*)["'].*/i then
link_href = $1
substitute_relative_path_in_src_line(line, link_href, base_url, current_url_parent)
elsif line =~ /<img\s+.*src=["'']?(.*)["'].*/i then
img_src = $1
substitute_relative_path_in_src_line(line, img_src, base_url, current_url_parent)
end
modified_content += line
end
return modified_content
end | ruby | def absolutize_page(content, base_url, current_url_parent)
modified_content = ""
content.each_line do |line|
if line =~ /<script\s+.*src=["'']?(.*)["'].*/i then
script_src = $1
substitute_relative_path_in_src_line(line, script_src, base_url, current_url_parent)
elsif line =~ /<link\s+.*href=["'']?(.*)["'].*/i then
link_href = $1
substitute_relative_path_in_src_line(line, link_href, base_url, current_url_parent)
elsif line =~ /<img\s+.*src=["'']?(.*)["'].*/i then
img_src = $1
substitute_relative_path_in_src_line(line, img_src, base_url, current_url_parent)
end
modified_content += line
end
return modified_content
end | [
"def",
"absolutize_page",
"(",
"content",
",",
"base_url",
",",
"current_url_parent",
")",
"modified_content",
"=",
"\"\"",
"content",
".",
"each_line",
"do",
"|",
"line",
"|",
"if",
"line",
"=~",
"/",
"\\s",
"/i",
"then",
"script_src",
"=",
"$1",
"substitute_relative_path_in_src_line",
"(",
"line",
",",
"script_src",
",",
"base_url",
",",
"current_url_parent",
")",
"elsif",
"line",
"=~",
"/",
"\\s",
"/i",
"then",
"link_href",
"=",
"$1",
"substitute_relative_path_in_src_line",
"(",
"line",
",",
"link_href",
",",
"base_url",
",",
"current_url_parent",
")",
"elsif",
"line",
"=~",
"/",
"\\s",
"/i",
"then",
"img_src",
"=",
"$1",
"substitute_relative_path_in_src_line",
"(",
"line",
",",
"img_src",
",",
"base_url",
",",
"current_url_parent",
")",
"end",
"modified_content",
"+=",
"line",
"end",
"return",
"modified_content",
"end"
] | Return page HTML with absolute references of images, stylesheets and javascripts | [
"Return",
"page",
"HTML",
"with",
"absolute",
"references",
"of",
"images",
"stylesheets",
"and",
"javascripts"
] | aafccee2ba66d17d591d04210067035feaf2f892 | https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-watir/driver.rb#L457-L474 | train |
zhimin/rwebspec | lib/rwebspec-watir/driver.rb | RWebSpec.Driver.absolutize_page_hpricot | def absolutize_page_hpricot(content, base_url, parent_url)
return absolutize_page(content, base_url, parent_url) if RUBY_PLATFORM == 'java'
begin
require 'hpricot'
doc = Hpricot(content)
base_url.slice!(-1) if ends_with?(base_url, "/")
(doc/'link').each { |e| e['href'] = absolutify_url(e['href'], base_url, parent_url) || "" }
(doc/'img').each { |e| e['src'] = absolutify_url(e['src'], base_url, parent_url) || "" }
(doc/'script').each { |e| e['src'] = absolutify_url(e['src'], base_url, parent_url) || "" }
return doc.to_html
rescue => e
absolutize_page(content, base_url, parent_url)
end
end | ruby | def absolutize_page_hpricot(content, base_url, parent_url)
return absolutize_page(content, base_url, parent_url) if RUBY_PLATFORM == 'java'
begin
require 'hpricot'
doc = Hpricot(content)
base_url.slice!(-1) if ends_with?(base_url, "/")
(doc/'link').each { |e| e['href'] = absolutify_url(e['href'], base_url, parent_url) || "" }
(doc/'img').each { |e| e['src'] = absolutify_url(e['src'], base_url, parent_url) || "" }
(doc/'script').each { |e| e['src'] = absolutify_url(e['src'], base_url, parent_url) || "" }
return doc.to_html
rescue => e
absolutize_page(content, base_url, parent_url)
end
end | [
"def",
"absolutize_page_hpricot",
"(",
"content",
",",
"base_url",
",",
"parent_url",
")",
"return",
"absolutize_page",
"(",
"content",
",",
"base_url",
",",
"parent_url",
")",
"if",
"RUBY_PLATFORM",
"==",
"'java'",
"begin",
"require",
"'hpricot'",
"doc",
"=",
"Hpricot",
"(",
"content",
")",
"base_url",
".",
"slice!",
"(",
"-",
"1",
")",
"if",
"ends_with?",
"(",
"base_url",
",",
"\"/\"",
")",
"(",
"doc",
"/",
"'link'",
")",
".",
"each",
"{",
"|",
"e",
"|",
"e",
"[",
"'href'",
"]",
"=",
"absolutify_url",
"(",
"e",
"[",
"'href'",
"]",
",",
"base_url",
",",
"parent_url",
")",
"||",
"\"\"",
"}",
"(",
"doc",
"/",
"'img'",
")",
".",
"each",
"{",
"|",
"e",
"|",
"e",
"[",
"'src'",
"]",
"=",
"absolutify_url",
"(",
"e",
"[",
"'src'",
"]",
",",
"base_url",
",",
"parent_url",
")",
"||",
"\"\"",
"}",
"(",
"doc",
"/",
"'script'",
")",
".",
"each",
"{",
"|",
"e",
"|",
"e",
"[",
"'src'",
"]",
"=",
"absolutify_url",
"(",
"e",
"[",
"'src'",
"]",
",",
"base_url",
",",
"parent_url",
")",
"||",
"\"\"",
"}",
"return",
"doc",
".",
"to_html",
"rescue",
"=>",
"e",
"absolutize_page",
"(",
"content",
",",
"base_url",
",",
"parent_url",
")",
"end",
"end"
] | absolutize_page using hpricot | [
"absolutize_page",
"using",
"hpricot"
] | aafccee2ba66d17d591d04210067035feaf2f892 | https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-watir/driver.rb#L478-L491 | train |
zhimin/rwebspec | lib/rwebspec-watir/driver.rb | RWebSpec.Driver.wait_for_element | def wait_for_element(element_id, timeout = $testwise_polling_timeout, interval = $testwise_polling_interval)
start_time = Time.now
#TODO might not work with Firefox
until @web_browser.element_by_id(element_id) do
sleep(interval)
if (Time.now - start_time) > timeout
raise RuntimeError, "failed to find element: #{element_id} for max #{timeout}"
end
end
end | ruby | def wait_for_element(element_id, timeout = $testwise_polling_timeout, interval = $testwise_polling_interval)
start_time = Time.now
#TODO might not work with Firefox
until @web_browser.element_by_id(element_id) do
sleep(interval)
if (Time.now - start_time) > timeout
raise RuntimeError, "failed to find element: #{element_id} for max #{timeout}"
end
end
end | [
"def",
"wait_for_element",
"(",
"element_id",
",",
"timeout",
"=",
"$testwise_polling_timeout",
",",
"interval",
"=",
"$testwise_polling_interval",
")",
"start_time",
"=",
"Time",
".",
"now",
"until",
"@web_browser",
".",
"element_by_id",
"(",
"element_id",
")",
"do",
"sleep",
"(",
"interval",
")",
"if",
"(",
"Time",
".",
"now",
"-",
"start_time",
")",
">",
"timeout",
"raise",
"RuntimeError",
",",
"\"failed to find element: #{element_id} for max #{timeout}\"",
"end",
"end",
"end"
] | Wait the element with given id to be present in web page
Warning: this not working in Firefox, try use wait_util or try instead | [
"Wait",
"the",
"element",
"with",
"given",
"id",
"to",
"be",
"present",
"in",
"web",
"page"
] | aafccee2ba66d17d591d04210067035feaf2f892 | https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-watir/driver.rb#L672-L681 | train |
zhimin/rwebspec | lib/rwebspec-watir/driver.rb | RWebSpec.Driver.clear_popup | def clear_popup(popup_win_title, seconds = 10, yes = true)
# commonly "Security Alert", "Security Information"
if is_windows?
sleep 1
autoit = WIN32OLE.new('AutoItX3.Control')
# Look for window with given title. Give up after 1 second.
ret = autoit.WinWait(popup_win_title, '', seconds)
#
# If window found, send appropriate keystroke (e.g. {enter}, {Y}, {N}).
if ret == 1 then
puts "about to send click Yes" if debugging?
button_id = yes ? "Button1" : "Button2" # Yes or No
autoit.ControlClick(popup_win_title, '', button_id)
end
sleep(0.5)
else
raise "Currently supported only on Windows"
end
end | ruby | def clear_popup(popup_win_title, seconds = 10, yes = true)
# commonly "Security Alert", "Security Information"
if is_windows?
sleep 1
autoit = WIN32OLE.new('AutoItX3.Control')
# Look for window with given title. Give up after 1 second.
ret = autoit.WinWait(popup_win_title, '', seconds)
#
# If window found, send appropriate keystroke (e.g. {enter}, {Y}, {N}).
if ret == 1 then
puts "about to send click Yes" if debugging?
button_id = yes ? "Button1" : "Button2" # Yes or No
autoit.ControlClick(popup_win_title, '', button_id)
end
sleep(0.5)
else
raise "Currently supported only on Windows"
end
end | [
"def",
"clear_popup",
"(",
"popup_win_title",
",",
"seconds",
"=",
"10",
",",
"yes",
"=",
"true",
")",
"if",
"is_windows?",
"sleep",
"1",
"autoit",
"=",
"WIN32OLE",
".",
"new",
"(",
"'AutoItX3.Control'",
")",
"ret",
"=",
"autoit",
".",
"WinWait",
"(",
"popup_win_title",
",",
"''",
",",
"seconds",
")",
"if",
"ret",
"==",
"1",
"then",
"puts",
"\"about to send click Yes\"",
"if",
"debugging?",
"button_id",
"=",
"yes",
"?",
"\"Button1\"",
":",
"\"Button2\"",
"autoit",
".",
"ControlClick",
"(",
"popup_win_title",
",",
"''",
",",
"button_id",
")",
"end",
"sleep",
"(",
"0.5",
")",
"else",
"raise",
"\"Currently supported only on Windows\"",
"end",
"end"
] | Clear popup windows such as 'Security Alert' or 'Security Information' popup window,
Screenshot see http://kb2.adobe.com/cps/165/tn_16588.html
You can also by pass security alerts by change IE setting, http://kb.iu.edu/data/amuj.html
Example
clear_popup("Security Information", 5, true) # check for Security Information for 5 seconds, click Yes | [
"Clear",
"popup",
"windows",
"such",
"as",
"Security",
"Alert",
"or",
"Security",
"Information",
"popup",
"window"
] | aafccee2ba66d17d591d04210067035feaf2f892 | https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-watir/driver.rb#L691-L709 | train |
zhimin/rwebspec | lib/rwebspec-watir/driver.rb | RWebSpec.Driver.basic_authentication_ie | def basic_authentication_ie(title, username, password, options = {})
default_options = {:textctrl_username => "Edit2",
:textctrl_password => "Edit3",
:button_ok => 'Button1'
}
options = default_options.merge(options)
title ||= ""
if title =~ /^Connect\sto/
full_title = title
else
full_title = "Connect to #{title}"
end
require 'rformspec'
login_win = RFormSpec::Window.new(full_title)
login_win.send_control_text(options[:textctrl_username], username)
login_win.send_control_text(options[:textctrl_password], password)
login_win.click_button("OK")
end | ruby | def basic_authentication_ie(title, username, password, options = {})
default_options = {:textctrl_username => "Edit2",
:textctrl_password => "Edit3",
:button_ok => 'Button1'
}
options = default_options.merge(options)
title ||= ""
if title =~ /^Connect\sto/
full_title = title
else
full_title = "Connect to #{title}"
end
require 'rformspec'
login_win = RFormSpec::Window.new(full_title)
login_win.send_control_text(options[:textctrl_username], username)
login_win.send_control_text(options[:textctrl_password], password)
login_win.click_button("OK")
end | [
"def",
"basic_authentication_ie",
"(",
"title",
",",
"username",
",",
"password",
",",
"options",
"=",
"{",
"}",
")",
"default_options",
"=",
"{",
":textctrl_username",
"=>",
"\"Edit2\"",
",",
":textctrl_password",
"=>",
"\"Edit3\"",
",",
":button_ok",
"=>",
"'Button1'",
"}",
"options",
"=",
"default_options",
".",
"merge",
"(",
"options",
")",
"title",
"||=",
"\"\"",
"if",
"title",
"=~",
"/",
"\\s",
"/",
"full_title",
"=",
"title",
"else",
"full_title",
"=",
"\"Connect to #{title}\"",
"end",
"require",
"'rformspec'",
"login_win",
"=",
"RFormSpec",
"::",
"Window",
".",
"new",
"(",
"full_title",
")",
"login_win",
".",
"send_control_text",
"(",
"options",
"[",
":textctrl_username",
"]",
",",
"username",
")",
"login_win",
".",
"send_control_text",
"(",
"options",
"[",
":textctrl_password",
"]",
",",
"password",
")",
"login_win",
".",
"click_button",
"(",
"\"OK\"",
")",
"end"
] | Use AutoIT3 to send password
title starts with "Connect to ..." | [
"Use",
"AutoIT3",
"to",
"send",
"password",
"title",
"starts",
"with",
"Connect",
"to",
"..."
] | aafccee2ba66d17d591d04210067035feaf2f892 | https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-watir/driver.rb#L748-L767 | train |
szTheory/meta_presenter | lib/meta_presenter/helpers.rb | MetaPresenter.Helpers.presenter | def presenter
@presenter ||= begin
controller = self
klass = MetaPresenter::Builder.new(controller, action_name).presenter_class
klass.new(controller)
end
end | ruby | def presenter
@presenter ||= begin
controller = self
klass = MetaPresenter::Builder.new(controller, action_name).presenter_class
klass.new(controller)
end
end | [
"def",
"presenter",
"@presenter",
"||=",
"begin",
"controller",
"=",
"self",
"klass",
"=",
"MetaPresenter",
"::",
"Builder",
".",
"new",
"(",
"controller",
",",
"action_name",
")",
".",
"presenter_class",
"klass",
".",
"new",
"(",
"controller",
")",
"end",
"end"
] | Initialize presenter with the current controller | [
"Initialize",
"presenter",
"with",
"the",
"current",
"controller"
] | 478787ebff72beaef4c4ce6776f050342ea6d221 | https://github.com/szTheory/meta_presenter/blob/478787ebff72beaef4c4ce6776f050342ea6d221/lib/meta_presenter/helpers.rb#L28-L34 | train |
datasift/datasift-ruby | lib/account_identity_token.rb | DataSift.AccountIdentityToken.create | def create(identity_id = '', service = '', token = '')
fail BadParametersError, 'identity_id is required' if identity_id.empty?
fail BadParametersError, 'service is required' if service.empty?
fail BadParametersError, 'token is required' if token.empty?
params = {
service: service,
token: token
}
DataSift.request(:POST, "account/identity/#{identity_id}/token", @config, params)
end | ruby | def create(identity_id = '', service = '', token = '')
fail BadParametersError, 'identity_id is required' if identity_id.empty?
fail BadParametersError, 'service is required' if service.empty?
fail BadParametersError, 'token is required' if token.empty?
params = {
service: service,
token: token
}
DataSift.request(:POST, "account/identity/#{identity_id}/token", @config, params)
end | [
"def",
"create",
"(",
"identity_id",
"=",
"''",
",",
"service",
"=",
"''",
",",
"token",
"=",
"''",
")",
"fail",
"BadParametersError",
",",
"'identity_id is required'",
"if",
"identity_id",
".",
"empty?",
"fail",
"BadParametersError",
",",
"'service is required'",
"if",
"service",
".",
"empty?",
"fail",
"BadParametersError",
",",
"'token is required'",
"if",
"token",
".",
"empty?",
"params",
"=",
"{",
"service",
":",
"service",
",",
"token",
":",
"token",
"}",
"DataSift",
".",
"request",
"(",
":POST",
",",
"\"account/identity/#{identity_id}/token\"",
",",
"@config",
",",
"params",
")",
"end"
] | Creates a new Identity Token
@param identity_id [String] ID of the Identity for which you are creating
a token
@param service [String] The service this token will be used to access. For
example; 'facebook'
@param token [String] The token provided by the PYLON data provider
@return [Object] API reponse object | [
"Creates",
"a",
"new",
"Identity",
"Token"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/account_identity_token.rb#L13-L23 | train |
datasift/datasift-ruby | lib/account_identity_token.rb | DataSift.AccountIdentityToken.list | def list(identity_id = '', per_page = '', page = '')
params = { identity_id: identity_id }
requires params
params.merge!(per_page: per_page) unless per_page.empty?
params.merge!(page: page) unless page.empty?
DataSift.request(:GET, "account/identity/#{identity_id}/token", @config, params)
end | ruby | def list(identity_id = '', per_page = '', page = '')
params = { identity_id: identity_id }
requires params
params.merge!(per_page: per_page) unless per_page.empty?
params.merge!(page: page) unless page.empty?
DataSift.request(:GET, "account/identity/#{identity_id}/token", @config, params)
end | [
"def",
"list",
"(",
"identity_id",
"=",
"''",
",",
"per_page",
"=",
"''",
",",
"page",
"=",
"''",
")",
"params",
"=",
"{",
"identity_id",
":",
"identity_id",
"}",
"requires",
"params",
"params",
".",
"merge!",
"(",
"per_page",
":",
"per_page",
")",
"unless",
"per_page",
".",
"empty?",
"params",
".",
"merge!",
"(",
"page",
":",
"page",
")",
"unless",
"page",
".",
"empty?",
"DataSift",
".",
"request",
"(",
":GET",
",",
"\"account/identity/#{identity_id}/token\"",
",",
"@config",
",",
"params",
")",
"end"
] | Returns a list of Tokens for a given Identity
@param identity_id [String] ID of the Identity we are fetching Tokens for
@param per_page [Integer] (Optional) How many Tokens should be returned
per page of results
@param page [Integer] (Optional) Which page of results to return
@return [Object] API reponse object | [
"Returns",
"a",
"list",
"of",
"Tokens",
"for",
"a",
"given",
"Identity"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/account_identity_token.rb#L45-L52 | train |
ngiger/buildrizpack | lib/buildrizpack/package.rb | BuildrIzPack.Pack.emitIzPackXML | def emitIzPackXML(xm)
# raise "xm must be an Builder::XmlMarkup object, but is #{xm.class}" if xm.class != Builder::XmlMarkup
xm.pack(@attributes) {
xm.description(@description)
@files.each{ |src, dest| xm.singlefile('src'=> src, 'target' =>dest) }
}
end | ruby | def emitIzPackXML(xm)
# raise "xm must be an Builder::XmlMarkup object, but is #{xm.class}" if xm.class != Builder::XmlMarkup
xm.pack(@attributes) {
xm.description(@description)
@files.each{ |src, dest| xm.singlefile('src'=> src, 'target' =>dest) }
}
end | [
"def",
"emitIzPackXML",
"(",
"xm",
")",
"xm",
".",
"pack",
"(",
"@attributes",
")",
"{",
"xm",
".",
"description",
"(",
"@description",
")",
"@files",
".",
"each",
"{",
"|",
"src",
",",
"dest",
"|",
"xm",
".",
"singlefile",
"(",
"'src'",
"=>",
"src",
",",
"'target'",
"=>",
"dest",
")",
"}",
"}",
"end"
] | collect the XML representation for the pack using an XMLMarkup object | [
"collect",
"the",
"XML",
"representation",
"for",
"the",
"pack",
"using",
"an",
"XMLMarkup",
"object"
] | 01a107af5edbbb1c838ccf840cb40f5d40a4da10 | https://github.com/ngiger/buildrizpack/blob/01a107af5edbbb1c838ccf840cb40f5d40a4da10/lib/buildrizpack/package.rb#L53-L59 | train |
ngiger/buildrizpack | lib/buildrizpack/package.rb | BuildrIzPack.IzPackTask.create_from | def create_from(file_map)
@izpackVersion ||= '4.3.5'
@appName ||= project.id
@izpackBaseDir = File.dirname(@output) if !@izpackBaseDir
@installerType ||= 'standard'
@inheritAll ||= 'true'
@compression ||= 'deflate'
@compressionLevel ||= '9'
@locales ||= ['eng']
@panels ||= ['TargetPanel', 'InstallPanel']
@packs ||=
raise "You must include at least one file to create an izPack installer" if file_map.size == 0 and !File.exists?(@input)
izPackArtifact = Buildr.artifact( "org.codehaus.izpack:izpack-standalone-compiler:jar:#{@izpackVersion}")
doc = nil
if !File.exists?(@input)
genInstaller(Builder::XmlMarkup.new(:target=>File.open(@input, 'w+'), :indent => 2), file_map)
# genInstaller(Builder::XmlMarkup.new(:target=>$stdout, :indent => 2), file_map)
# genInstaller(Builder::XmlMarkup.new(:target=>File.open('/home/niklaus/tmp2.xml', 'w+'), :indent => 2), file_map)
end
Buildr.ant('izpack-ant') do |x|
izPackArtifact.invoke
msg = "Generating izpack aus #{File.expand_path(@input)}"
trace msg
if properties
properties.each{ |name, value|
puts "Need added property #{name} with value #{value}"
x.property(:name => name, :value => value)
}
end
x.echo(:message =>msg)
x.taskdef :name=>'izpack',
:classname=>'com.izforge.izpack.ant.IzPackTask',
:classpath=>izPackArtifact.to_s
x.izpack :input=> @input,
:output => @output,
:basedir => @izpackBaseDir,
:installerType=> @installerType,
:inheritAll=> @inheritAll,
:compression => @compression,
:compressionLevel => @compressionLevel do
end
end
end | ruby | def create_from(file_map)
@izpackVersion ||= '4.3.5'
@appName ||= project.id
@izpackBaseDir = File.dirname(@output) if !@izpackBaseDir
@installerType ||= 'standard'
@inheritAll ||= 'true'
@compression ||= 'deflate'
@compressionLevel ||= '9'
@locales ||= ['eng']
@panels ||= ['TargetPanel', 'InstallPanel']
@packs ||=
raise "You must include at least one file to create an izPack installer" if file_map.size == 0 and !File.exists?(@input)
izPackArtifact = Buildr.artifact( "org.codehaus.izpack:izpack-standalone-compiler:jar:#{@izpackVersion}")
doc = nil
if !File.exists?(@input)
genInstaller(Builder::XmlMarkup.new(:target=>File.open(@input, 'w+'), :indent => 2), file_map)
# genInstaller(Builder::XmlMarkup.new(:target=>$stdout, :indent => 2), file_map)
# genInstaller(Builder::XmlMarkup.new(:target=>File.open('/home/niklaus/tmp2.xml', 'w+'), :indent => 2), file_map)
end
Buildr.ant('izpack-ant') do |x|
izPackArtifact.invoke
msg = "Generating izpack aus #{File.expand_path(@input)}"
trace msg
if properties
properties.each{ |name, value|
puts "Need added property #{name} with value #{value}"
x.property(:name => name, :value => value)
}
end
x.echo(:message =>msg)
x.taskdef :name=>'izpack',
:classname=>'com.izforge.izpack.ant.IzPackTask',
:classpath=>izPackArtifact.to_s
x.izpack :input=> @input,
:output => @output,
:basedir => @izpackBaseDir,
:installerType=> @installerType,
:inheritAll=> @inheritAll,
:compression => @compression,
:compressionLevel => @compressionLevel do
end
end
end | [
"def",
"create_from",
"(",
"file_map",
")",
"@izpackVersion",
"||=",
"'4.3.5'",
"@appName",
"||=",
"project",
".",
"id",
"@izpackBaseDir",
"=",
"File",
".",
"dirname",
"(",
"@output",
")",
"if",
"!",
"@izpackBaseDir",
"@installerType",
"||=",
"'standard'",
"@inheritAll",
"||=",
"'true'",
"@compression",
"||=",
"'deflate'",
"@compressionLevel",
"||=",
"'9'",
"@locales",
"||=",
"[",
"'eng'",
"]",
"@panels",
"||=",
"[",
"'TargetPanel'",
",",
"'InstallPanel'",
"]",
"@packs",
"||=",
"raise",
"\"You must include at least one file to create an izPack installer\"",
"if",
"file_map",
".",
"size",
"==",
"0",
"and",
"!",
"File",
".",
"exists?",
"(",
"@input",
")",
"izPackArtifact",
"=",
"Buildr",
".",
"artifact",
"(",
"\"org.codehaus.izpack:izpack-standalone-compiler:jar:#{@izpackVersion}\"",
")",
"doc",
"=",
"nil",
"if",
"!",
"File",
".",
"exists?",
"(",
"@input",
")",
"genInstaller",
"(",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"(",
":target",
"=>",
"File",
".",
"open",
"(",
"@input",
",",
"'w+'",
")",
",",
":indent",
"=>",
"2",
")",
",",
"file_map",
")",
"end",
"Buildr",
".",
"ant",
"(",
"'izpack-ant'",
")",
"do",
"|",
"x",
"|",
"izPackArtifact",
".",
"invoke",
"msg",
"=",
"\"Generating izpack aus #{File.expand_path(@input)}\"",
"trace",
"msg",
"if",
"properties",
"properties",
".",
"each",
"{",
"|",
"name",
",",
"value",
"|",
"puts",
"\"Need added property #{name} with value #{value}\"",
"x",
".",
"property",
"(",
":name",
"=>",
"name",
",",
":value",
"=>",
"value",
")",
"}",
"end",
"x",
".",
"echo",
"(",
":message",
"=>",
"msg",
")",
"x",
".",
"taskdef",
":name",
"=>",
"'izpack'",
",",
":classname",
"=>",
"'com.izforge.izpack.ant.IzPackTask'",
",",
":classpath",
"=>",
"izPackArtifact",
".",
"to_s",
"x",
".",
"izpack",
":input",
"=>",
"@input",
",",
":output",
"=>",
"@output",
",",
":basedir",
"=>",
"@izpackBaseDir",
",",
":installerType",
"=>",
"@installerType",
",",
":inheritAll",
"=>",
"@inheritAll",
",",
":compression",
"=>",
"@compression",
",",
":compressionLevel",
"=>",
"@compressionLevel",
"do",
"end",
"end",
"end"
] | The ArchiveTask class delegates this method
so we can create the archive.
the file_map is the result of the computations of the include and exclude filters. | [
"The",
"ArchiveTask",
"class",
"delegates",
"this",
"method",
"so",
"we",
"can",
"create",
"the",
"archive",
".",
"the",
"file_map",
"is",
"the",
"result",
"of",
"the",
"computations",
"of",
"the",
"include",
"and",
"exclude",
"filters",
"."
] | 01a107af5edbbb1c838ccf840cb40f5d40a4da10 | https://github.com/ngiger/buildrizpack/blob/01a107af5edbbb1c838ccf840cb40f5d40a4da10/lib/buildrizpack/package.rb#L107-L149 | train |
factore/tenon | app/helpers/tenon/application_helper.rb | Tenon.ApplicationHelper.first_image | def first_image(obj, options = {})
opts = {
collection: :images,
method: :image,
style: :thumbnail,
default: image_path('noimage.jpg')
}.merge(options.symbolize_keys!)
image = obj.send(opts[:collection]).first
image ? image.send(opts[:method]).url(opts[:style]) : opts[:default]
end | ruby | def first_image(obj, options = {})
opts = {
collection: :images,
method: :image,
style: :thumbnail,
default: image_path('noimage.jpg')
}.merge(options.symbolize_keys!)
image = obj.send(opts[:collection]).first
image ? image.send(opts[:method]).url(opts[:style]) : opts[:default]
end | [
"def",
"first_image",
"(",
"obj",
",",
"options",
"=",
"{",
"}",
")",
"opts",
"=",
"{",
"collection",
":",
":images",
",",
"method",
":",
":image",
",",
"style",
":",
":thumbnail",
",",
"default",
":",
"image_path",
"(",
"'noimage.jpg'",
")",
"}",
".",
"merge",
"(",
"options",
".",
"symbolize_keys!",
")",
"image",
"=",
"obj",
".",
"send",
"(",
"opts",
"[",
":collection",
"]",
")",
".",
"first",
"image",
"?",
"image",
".",
"send",
"(",
"opts",
"[",
":method",
"]",
")",
".",
"url",
"(",
"opts",
"[",
":style",
"]",
")",
":",
"opts",
"[",
":default",
"]",
"end"
] | eg. first_image(@product) | [
"eg",
".",
"first_image",
"("
] | 49907830c00524853d087566f60951b8b6a9aedf | https://github.com/factore/tenon/blob/49907830c00524853d087566f60951b8b6a9aedf/app/helpers/tenon/application_helper.rb#L41-L51 | train |
factore/tenon | app/helpers/tenon/application_helper.rb | Tenon.ApplicationHelper.human | def human(object)
if object.is_a?(Date)
object.strftime('%B %d, %Y')
elsif object.is_a?(Time)
object.strftime('%B %d, %Y at %I:%M %p')
elsif object.is_a?(String)
object.humanize
else
object
end
end | ruby | def human(object)
if object.is_a?(Date)
object.strftime('%B %d, %Y')
elsif object.is_a?(Time)
object.strftime('%B %d, %Y at %I:%M %p')
elsif object.is_a?(String)
object.humanize
else
object
end
end | [
"def",
"human",
"(",
"object",
")",
"if",
"object",
".",
"is_a?",
"(",
"Date",
")",
"object",
".",
"strftime",
"(",
"'%B %d, %Y'",
")",
"elsif",
"object",
".",
"is_a?",
"(",
"Time",
")",
"object",
".",
"strftime",
"(",
"'%B %d, %Y at %I:%M %p'",
")",
"elsif",
"object",
".",
"is_a?",
"(",
"String",
")",
"object",
".",
"humanize",
"else",
"object",
"end",
"end"
] | humanizing various things | [
"humanizing",
"various",
"things"
] | 49907830c00524853d087566f60951b8b6a9aedf | https://github.com/factore/tenon/blob/49907830c00524853d087566f60951b8b6a9aedf/app/helpers/tenon/application_helper.rb#L124-L134 | train |
knaveofdiamonds/tealeaves | lib/tealeaves/exponential_smoothing_forecast.rb | TeaLeaves.ExponentialSmoothingForecast.mean_squared_error | def mean_squared_error
return @mean_squared_error if @mean_squared_error
numerator = errors.drop(@seasonality_strategy.start_index).map {|i| i ** 2 }.inject(&:+)
@mean_squared_error = numerator / (errors.size - @seasonality_strategy.start_index).to_f
end | ruby | def mean_squared_error
return @mean_squared_error if @mean_squared_error
numerator = errors.drop(@seasonality_strategy.start_index).map {|i| i ** 2 }.inject(&:+)
@mean_squared_error = numerator / (errors.size - @seasonality_strategy.start_index).to_f
end | [
"def",
"mean_squared_error",
"return",
"@mean_squared_error",
"if",
"@mean_squared_error",
"numerator",
"=",
"errors",
".",
"drop",
"(",
"@seasonality_strategy",
".",
"start_index",
")",
".",
"map",
"{",
"|",
"i",
"|",
"i",
"**",
"2",
"}",
".",
"inject",
"(",
"&",
":+",
")",
"@mean_squared_error",
"=",
"numerator",
"/",
"(",
"errors",
".",
"size",
"-",
"@seasonality_strategy",
".",
"start_index",
")",
".",
"to_f",
"end"
] | Returns the mean squared error of the forecast. | [
"Returns",
"the",
"mean",
"squared",
"error",
"of",
"the",
"forecast",
"."
] | 226d61cbb5cfc61a16ae84679e261eebf9895358 | https://github.com/knaveofdiamonds/tealeaves/blob/226d61cbb5cfc61a16ae84679e261eebf9895358/lib/tealeaves/exponential_smoothing_forecast.rb#L131-L136 | train |
datasift/datasift-ruby | lib/managed_source_resource.rb | DataSift.ManagedSourceResource.add | def add(id, resources, validate = 'true')
params = {
id: id,
resources: resources,
validate: validate
}
requires params
DataSift.request(:PUT, 'source/resource/add', @config, params)
end | ruby | def add(id, resources, validate = 'true')
params = {
id: id,
resources: resources,
validate: validate
}
requires params
DataSift.request(:PUT, 'source/resource/add', @config, params)
end | [
"def",
"add",
"(",
"id",
",",
"resources",
",",
"validate",
"=",
"'true'",
")",
"params",
"=",
"{",
"id",
":",
"id",
",",
"resources",
":",
"resources",
",",
"validate",
":",
"validate",
"}",
"requires",
"params",
"DataSift",
".",
"request",
"(",
":PUT",
",",
"'source/resource/add'",
",",
"@config",
",",
"params",
")",
"end"
] | Add resources to a Managed Source
@param id [String] ID of the Managed Source you are adding resources to
@param resources [Array] Array of resources you are adding to your source
@param validate [Boolean] Whether you want to validate your new resources
against the third party API (i.e. the Facebook or Instagram API) | [
"Add",
"resources",
"to",
"a",
"Managed",
"Source"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/managed_source_resource.rb#L10-L18 | train |
datasift/datasift-ruby | lib/managed_source_resource.rb | DataSift.ManagedSourceResource.remove | def remove(id, resource_ids)
params = {
id: id,
resource_ids: resource_ids
}
requires params
DataSift.request(:PUT, 'source/resource/remove', @config, params)
end | ruby | def remove(id, resource_ids)
params = {
id: id,
resource_ids: resource_ids
}
requires params
DataSift.request(:PUT, 'source/resource/remove', @config, params)
end | [
"def",
"remove",
"(",
"id",
",",
"resource_ids",
")",
"params",
"=",
"{",
"id",
":",
"id",
",",
"resource_ids",
":",
"resource_ids",
"}",
"requires",
"params",
"DataSift",
".",
"request",
"(",
":PUT",
",",
"'source/resource/remove'",
",",
"@config",
",",
"params",
")",
"end"
] | Remove resources from a Managed Source
@param id [String] ID of the Managed Source you are removing resources
from
@param resource_ids [Array] Array of resource_id strings you need to
remove from your source | [
"Remove",
"resources",
"from",
"a",
"Managed",
"Source"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/managed_source_resource.rb#L26-L33 | train |
datasift/datasift-ruby | lib/managed_source_auth.rb | DataSift.ManagedSourceAuth.add | def add(id, auth, validate = 'true')
params = {
id: id,
auth: auth,
validate: validate
}
requires params
DataSift.request(:PUT, 'source/auth/add', @config, params)
end | ruby | def add(id, auth, validate = 'true')
params = {
id: id,
auth: auth,
validate: validate
}
requires params
DataSift.request(:PUT, 'source/auth/add', @config, params)
end | [
"def",
"add",
"(",
"id",
",",
"auth",
",",
"validate",
"=",
"'true'",
")",
"params",
"=",
"{",
"id",
":",
"id",
",",
"auth",
":",
"auth",
",",
"validate",
":",
"validate",
"}",
"requires",
"params",
"DataSift",
".",
"request",
"(",
":PUT",
",",
"'source/auth/add'",
",",
"@config",
",",
"params",
")",
"end"
] | Add auth tokens to a Managed Source
@param id [String] ID of the Managed Source you are adding Auth tokens to
@param auth [Array] Array of auth tokens you are adding to your source
@param validate [Boolean] Whether you want to validate your new tokens
against the third party API (i.e. the Facebook or Instagram API) | [
"Add",
"auth",
"tokens",
"to",
"a",
"Managed",
"Source"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/managed_source_auth.rb#L10-L18 | train |
datasift/datasift-ruby | lib/managed_source_auth.rb | DataSift.ManagedSourceAuth.remove | def remove(id, auth_ids)
params = {
id: id,
auth_ids: auth_ids
}
requires params
DataSift.request(:PUT, 'source/auth/remove', @config, params)
end | ruby | def remove(id, auth_ids)
params = {
id: id,
auth_ids: auth_ids
}
requires params
DataSift.request(:PUT, 'source/auth/remove', @config, params)
end | [
"def",
"remove",
"(",
"id",
",",
"auth_ids",
")",
"params",
"=",
"{",
"id",
":",
"id",
",",
"auth_ids",
":",
"auth_ids",
"}",
"requires",
"params",
"DataSift",
".",
"request",
"(",
":PUT",
",",
"'source/auth/remove'",
",",
"@config",
",",
"params",
")",
"end"
] | Remove auth tokens from a Managed Source
@param id [String] ID of the Managed Source you are removing auth tokens
from
@param auth_ids [Array] Array of auth_id strings you need to remove from
your source | [
"Remove",
"auth",
"tokens",
"from",
"a",
"Managed",
"Source"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/managed_source_auth.rb#L26-L33 | train |
FTB-Gamepedia/MediaWiki-Butt-Ruby | lib/mediawiki/auth.rb | MediaWiki.Auth.login | def login(username, password)
# Save the assertion value while trying to log in, because otherwise the assertion will prevent us from logging in
assertion_value = @assertion.clone
@assertion = nil
params = {
action: 'login',
lgname: username,
lgpassword: password,
lgtoken: get_token('login')
}
response = post(params)
@assertion = assertion_value
result = response['login']['result']
if result == 'Success'
@name = response['login']['lgusername']
@logged_in = true
return true
end
raise MediaWiki::Butt::AuthenticationError.new(result)
end | ruby | def login(username, password)
# Save the assertion value while trying to log in, because otherwise the assertion will prevent us from logging in
assertion_value = @assertion.clone
@assertion = nil
params = {
action: 'login',
lgname: username,
lgpassword: password,
lgtoken: get_token('login')
}
response = post(params)
@assertion = assertion_value
result = response['login']['result']
if result == 'Success'
@name = response['login']['lgusername']
@logged_in = true
return true
end
raise MediaWiki::Butt::AuthenticationError.new(result)
end | [
"def",
"login",
"(",
"username",
",",
"password",
")",
"assertion_value",
"=",
"@assertion",
".",
"clone",
"@assertion",
"=",
"nil",
"params",
"=",
"{",
"action",
":",
"'login'",
",",
"lgname",
":",
"username",
",",
"lgpassword",
":",
"password",
",",
"lgtoken",
":",
"get_token",
"(",
"'login'",
")",
"}",
"response",
"=",
"post",
"(",
"params",
")",
"@assertion",
"=",
"assertion_value",
"result",
"=",
"response",
"[",
"'login'",
"]",
"[",
"'result'",
"]",
"if",
"result",
"==",
"'Success'",
"@name",
"=",
"response",
"[",
"'login'",
"]",
"[",
"'lgusername'",
"]",
"@logged_in",
"=",
"true",
"return",
"true",
"end",
"raise",
"MediaWiki",
"::",
"Butt",
"::",
"AuthenticationError",
".",
"new",
"(",
"result",
")",
"end"
] | Logs the user into the wiki. This is generally required for editing and getting restricted data.
@param username [String] The username
@param password [String] The password
@see https://www.mediawiki.org/wiki/API:Login MediaWiki Login API Docs
@since 0.1.0
@raise [AuthenticationError]
@return [Boolean] True if the login was successful. | [
"Logs",
"the",
"user",
"into",
"the",
"wiki",
".",
"This",
"is",
"generally",
"required",
"for",
"editing",
"and",
"getting",
"restricted",
"data",
"."
] | d71c5dfdf9d349d025e1c3534286ce116777eaa4 | https://github.com/FTB-Gamepedia/MediaWiki-Butt-Ruby/blob/d71c5dfdf9d349d025e1c3534286ce116777eaa4/lib/mediawiki/auth.rb#L12-L37 | train |
FTB-Gamepedia/MediaWiki-Butt-Ruby | lib/mediawiki/auth.rb | MediaWiki.Auth.create_account | def create_account(username, password, language = 'en', reason = nil)
params = {
name: username,
password: password,
language: language,
token: get_token('createaccount')
}
params[:reason] = reason unless reason.nil?
result = post(params)
unless result['error'].nil?
raise MediaWiki::Butt::AuthenticationError.new(result['error']['code'])
end
result['createaccount']['result'] == 'Success'
end | ruby | def create_account(username, password, language = 'en', reason = nil)
params = {
name: username,
password: password,
language: language,
token: get_token('createaccount')
}
params[:reason] = reason unless reason.nil?
result = post(params)
unless result['error'].nil?
raise MediaWiki::Butt::AuthenticationError.new(result['error']['code'])
end
result['createaccount']['result'] == 'Success'
end | [
"def",
"create_account",
"(",
"username",
",",
"password",
",",
"language",
"=",
"'en'",
",",
"reason",
"=",
"nil",
")",
"params",
"=",
"{",
"name",
":",
"username",
",",
"password",
":",
"password",
",",
"language",
":",
"language",
",",
"token",
":",
"get_token",
"(",
"'createaccount'",
")",
"}",
"params",
"[",
":reason",
"]",
"=",
"reason",
"unless",
"reason",
".",
"nil?",
"result",
"=",
"post",
"(",
"params",
")",
"unless",
"result",
"[",
"'error'",
"]",
".",
"nil?",
"raise",
"MediaWiki",
"::",
"Butt",
"::",
"AuthenticationError",
".",
"new",
"(",
"result",
"[",
"'error'",
"]",
"[",
"'code'",
"]",
")",
"end",
"result",
"[",
"'createaccount'",
"]",
"[",
"'result'",
"]",
"==",
"'Success'",
"end"
] | Creates an account using the standard procedure.
@param username [String] The desired username.
@param password [String] The desired password.
@param language [String] The language code to be set as default for the account. Defaults to 'en', or English.
Use the language code, not the name.
@param reason [String] The reason for creating the account, as shown in the account creation log. Optional.
@see #check_create
@see https://www.mediawiki.org/wiki/API:Account_creation MediaWiki Account Creation Docs
@since 0.1.0
@return [Boolean] True if successful, false if not. | [
"Creates",
"an",
"account",
"using",
"the",
"standard",
"procedure",
"."
] | d71c5dfdf9d349d025e1c3534286ce116777eaa4 | https://github.com/FTB-Gamepedia/MediaWiki-Butt-Ruby/blob/d71c5dfdf9d349d025e1c3534286ce116777eaa4/lib/mediawiki/auth.rb#L68-L83 | train |
FTB-Gamepedia/MediaWiki-Butt-Ruby | lib/mediawiki/auth.rb | MediaWiki.Auth.create_account_email | def create_account_email(username, email, language = 'en', reason = nil)
params = {
name: username,
email: email,
mailpassword: 'value',
language: language,
token: get_token('createaccount')
}
params[:reason] = reason unless reason.nil?
result = post(params)
unless result['error'].nil?
raise MediaWiki::Butt::AuthenticationError.new(result['error']['code'])
end
result['createaccount']['result'] == 'Success'
end | ruby | def create_account_email(username, email, language = 'en', reason = nil)
params = {
name: username,
email: email,
mailpassword: 'value',
language: language,
token: get_token('createaccount')
}
params[:reason] = reason unless reason.nil?
result = post(params)
unless result['error'].nil?
raise MediaWiki::Butt::AuthenticationError.new(result['error']['code'])
end
result['createaccount']['result'] == 'Success'
end | [
"def",
"create_account_email",
"(",
"username",
",",
"email",
",",
"language",
"=",
"'en'",
",",
"reason",
"=",
"nil",
")",
"params",
"=",
"{",
"name",
":",
"username",
",",
"email",
":",
"email",
",",
"mailpassword",
":",
"'value'",
",",
"language",
":",
"language",
",",
"token",
":",
"get_token",
"(",
"'createaccount'",
")",
"}",
"params",
"[",
":reason",
"]",
"=",
"reason",
"unless",
"reason",
".",
"nil?",
"result",
"=",
"post",
"(",
"params",
")",
"unless",
"result",
"[",
"'error'",
"]",
".",
"nil?",
"raise",
"MediaWiki",
"::",
"Butt",
"::",
"AuthenticationError",
".",
"new",
"(",
"result",
"[",
"'error'",
"]",
"[",
"'code'",
"]",
")",
"end",
"result",
"[",
"'createaccount'",
"]",
"[",
"'result'",
"]",
"==",
"'Success'",
"end"
] | Creates an account using the random password sent by email procedure.
@param email [String] The desired email address
@param (see #create_account)
@see #check_create
@see https://www.mediawiki.org/wiki/API:Account_creation MediaWiki Account Creation Docs
@since 0.1.0
@return [Boolean] True if successful, false if not. | [
"Creates",
"an",
"account",
"using",
"the",
"random",
"password",
"sent",
"by",
"email",
"procedure",
"."
] | d71c5dfdf9d349d025e1c3534286ce116777eaa4 | https://github.com/FTB-Gamepedia/MediaWiki-Butt-Ruby/blob/d71c5dfdf9d349d025e1c3534286ce116777eaa4/lib/mediawiki/auth.rb#L92-L108 | train |
zhimin/rwebspec | lib/rwebspec-webdriver/driver.rb | RWebSpec.Driver.save_current_page | def save_current_page(options = {})
default_options = {:replacement => true}
options = default_options.merge(options)
to_dir = options[:dir] || default_dump_dir
if options[:filename]
file_name = options[:filename]
else
file_name = Time.now.strftime("%m%d%H%M%S") + ".html"
end
Dir.mkdir(to_dir) unless File.exists?(to_dir)
file = File.join(to_dir, file_name)
content = page_source
base_url = @web_browser.context.base_url
current_url = @web_browser.url
current_url =~ /(.*\/).*$/
current_url_parent = $1
if options[:replacement] && base_url =~ /^http:/
File.new(file, "w").puts absolutize_page_hpricot(content, base_url, current_url_parent)
else
File.new(file, "w").puts content
end
end | ruby | def save_current_page(options = {})
default_options = {:replacement => true}
options = default_options.merge(options)
to_dir = options[:dir] || default_dump_dir
if options[:filename]
file_name = options[:filename]
else
file_name = Time.now.strftime("%m%d%H%M%S") + ".html"
end
Dir.mkdir(to_dir) unless File.exists?(to_dir)
file = File.join(to_dir, file_name)
content = page_source
base_url = @web_browser.context.base_url
current_url = @web_browser.url
current_url =~ /(.*\/).*$/
current_url_parent = $1
if options[:replacement] && base_url =~ /^http:/
File.new(file, "w").puts absolutize_page_hpricot(content, base_url, current_url_parent)
else
File.new(file, "w").puts content
end
end | [
"def",
"save_current_page",
"(",
"options",
"=",
"{",
"}",
")",
"default_options",
"=",
"{",
":replacement",
"=>",
"true",
"}",
"options",
"=",
"default_options",
".",
"merge",
"(",
"options",
")",
"to_dir",
"=",
"options",
"[",
":dir",
"]",
"||",
"default_dump_dir",
"if",
"options",
"[",
":filename",
"]",
"file_name",
"=",
"options",
"[",
":filename",
"]",
"else",
"file_name",
"=",
"Time",
".",
"now",
".",
"strftime",
"(",
"\"%m%d%H%M%S\"",
")",
"+",
"\".html\"",
"end",
"Dir",
".",
"mkdir",
"(",
"to_dir",
")",
"unless",
"File",
".",
"exists?",
"(",
"to_dir",
")",
"file",
"=",
"File",
".",
"join",
"(",
"to_dir",
",",
"file_name",
")",
"content",
"=",
"page_source",
"base_url",
"=",
"@web_browser",
".",
"context",
".",
"base_url",
"current_url",
"=",
"@web_browser",
".",
"url",
"current_url",
"=~",
"/",
"\\/",
"/",
"current_url_parent",
"=",
"$1",
"if",
"options",
"[",
":replacement",
"]",
"&&",
"base_url",
"=~",
"/",
"/",
"File",
".",
"new",
"(",
"file",
",",
"\"w\"",
")",
".",
"puts",
"absolutize_page_hpricot",
"(",
"content",
",",
"base_url",
",",
"current_url_parent",
")",
"else",
"File",
".",
"new",
"(",
"file",
",",
"\"w\"",
")",
".",
"puts",
"content",
"end",
"end"
] | For current page souce to a file in specified folder for inspection
save_current_page(:dir => "C:\\mysite", filename => "abc", :replacement => true) | [
"For",
"current",
"page",
"souce",
"to",
"a",
"file",
"in",
"specified",
"folder",
"for",
"inspection"
] | aafccee2ba66d17d591d04210067035feaf2f892 | https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-webdriver/driver.rb#L427-L452 | train |
zhimin/rwebspec | lib/rwebspec-webdriver/driver.rb | RWebSpec.Driver.wait_until | def wait_until(timeout = $testwise_polling_timeout || 30, polling_interval = $testwise_polling_interval || 1, & block)
end_time = ::Time.now + timeout
until ::Time.now > end_time
result = nil
begin
result = yield(self)
return result if result
rescue => e
end
sleep polling_interval
end
raise TimeoutError, "timed out after #{timeout} seconds"
end | ruby | def wait_until(timeout = $testwise_polling_timeout || 30, polling_interval = $testwise_polling_interval || 1, & block)
end_time = ::Time.now + timeout
until ::Time.now > end_time
result = nil
begin
result = yield(self)
return result if result
rescue => e
end
sleep polling_interval
end
raise TimeoutError, "timed out after #{timeout} seconds"
end | [
"def",
"wait_until",
"(",
"timeout",
"=",
"$testwise_polling_timeout",
"||",
"30",
",",
"polling_interval",
"=",
"$testwise_polling_interval",
"||",
"1",
",",
"&",
"block",
")",
"end_time",
"=",
"::",
"Time",
".",
"now",
"+",
"timeout",
"until",
"::",
"Time",
".",
"now",
">",
"end_time",
"result",
"=",
"nil",
"begin",
"result",
"=",
"yield",
"(",
"self",
")",
"return",
"result",
"if",
"result",
"rescue",
"=>",
"e",
"end",
"sleep",
"polling_interval",
"end",
"raise",
"TimeoutError",
",",
"\"timed out after #{timeout} seconds\"",
"end"
] | = Convenient functions
Execute the provided block until either (1) it returns true, or
(2) the timeout (in seconds) has been reached. If the timeout is reached,
a TimeOutException will be raised. The block will always
execute at least once.
This does not handle error, if the given block raise error, the statement finish with error
Examples:
wait_until {puts 'hello'}
wait_until { div(:id, :receipt_date).exists? } | [
"=",
"Convenient",
"functions"
] | aafccee2ba66d17d591d04210067035feaf2f892 | https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-webdriver/driver.rb#L622-L636 | train |
FTB-Gamepedia/MediaWiki-Butt-Ruby | lib/mediawiki/administration.rb | MediaWiki.Administration.block | def block(user, expiry = '2 weeks', reason = nil, nocreate = true)
params = {
action: 'block',
user: user,
expiry: expiry
}
token = get_token
params[:reason] = reason if reason
params[:nocreate] = '1' if nocreate
params[:token] = token
response = post(params)
if response.key?('error')
raise MediaWiki::Butt::BlockError.new(response.dig('error', 'code') || 'Unknown error code')
end
response['id'].to_i
end | ruby | def block(user, expiry = '2 weeks', reason = nil, nocreate = true)
params = {
action: 'block',
user: user,
expiry: expiry
}
token = get_token
params[:reason] = reason if reason
params[:nocreate] = '1' if nocreate
params[:token] = token
response = post(params)
if response.key?('error')
raise MediaWiki::Butt::BlockError.new(response.dig('error', 'code') || 'Unknown error code')
end
response['id'].to_i
end | [
"def",
"block",
"(",
"user",
",",
"expiry",
"=",
"'2 weeks'",
",",
"reason",
"=",
"nil",
",",
"nocreate",
"=",
"true",
")",
"params",
"=",
"{",
"action",
":",
"'block'",
",",
"user",
":",
"user",
",",
"expiry",
":",
"expiry",
"}",
"token",
"=",
"get_token",
"params",
"[",
":reason",
"]",
"=",
"reason",
"if",
"reason",
"params",
"[",
":nocreate",
"]",
"=",
"'1'",
"if",
"nocreate",
"params",
"[",
":token",
"]",
"=",
"token",
"response",
"=",
"post",
"(",
"params",
")",
"if",
"response",
".",
"key?",
"(",
"'error'",
")",
"raise",
"MediaWiki",
"::",
"Butt",
"::",
"BlockError",
".",
"new",
"(",
"response",
".",
"dig",
"(",
"'error'",
",",
"'code'",
")",
"||",
"'Unknown error code'",
")",
"end",
"response",
"[",
"'id'",
"]",
".",
"to_i",
"end"
] | Blocks the user.
@param (see #unblock)
@param expiry [String] The expiry timestamp using a relative expiry time.
@param nocreate [Boolean] Whether to allow them to create an account.
@see https://www.mediawiki.org/wiki/API:Block MediaWiki Block API Docs
@since 0.5.0
@raise [BlockError]
@return (see #unblock) | [
"Blocks",
"the",
"user",
"."
] | d71c5dfdf9d349d025e1c3534286ce116777eaa4 | https://github.com/FTB-Gamepedia/MediaWiki-Butt-Ruby/blob/d71c5dfdf9d349d025e1c3534286ce116777eaa4/lib/mediawiki/administration.rb#L13-L32 | train |
FTB-Gamepedia/MediaWiki-Butt-Ruby | lib/mediawiki/administration.rb | MediaWiki.Administration.unblock | def unblock(user, reason = nil)
params = {
action: 'unblock',
user: user
}
token = get_token
params[:reason] = reason if reason
params[:token] = token
response = post(params)
if response.key?('error')
raise MediaWiki::Butt::BlockError.new(response.dig('error', 'code') || 'Unknown error code')
end
response['id'].to_i
end | ruby | def unblock(user, reason = nil)
params = {
action: 'unblock',
user: user
}
token = get_token
params[:reason] = reason if reason
params[:token] = token
response = post(params)
if response.key?('error')
raise MediaWiki::Butt::BlockError.new(response.dig('error', 'code') || 'Unknown error code')
end
response['id'].to_i
end | [
"def",
"unblock",
"(",
"user",
",",
"reason",
"=",
"nil",
")",
"params",
"=",
"{",
"action",
":",
"'unblock'",
",",
"user",
":",
"user",
"}",
"token",
"=",
"get_token",
"params",
"[",
":reason",
"]",
"=",
"reason",
"if",
"reason",
"params",
"[",
":token",
"]",
"=",
"token",
"response",
"=",
"post",
"(",
"params",
")",
"if",
"response",
".",
"key?",
"(",
"'error'",
")",
"raise",
"MediaWiki",
"::",
"Butt",
"::",
"BlockError",
".",
"new",
"(",
"response",
".",
"dig",
"(",
"'error'",
",",
"'code'",
")",
"||",
"'Unknown error code'",
")",
"end",
"response",
"[",
"'id'",
"]",
".",
"to_i",
"end"
] | Unblocks the user.
@param user [String] The user affected.
@param reason [String] The reason to show in the block log.
@see https://www.mediawiki.org/wiki/API:Block MediaWiki Block API Docs
@since 0.5.0
@raise [BlockError]
@return [Fixnum] The block ID. | [
"Unblocks",
"the",
"user",
"."
] | d71c5dfdf9d349d025e1c3534286ce116777eaa4 | https://github.com/FTB-Gamepedia/MediaWiki-Butt-Ruby/blob/d71c5dfdf9d349d025e1c3534286ce116777eaa4/lib/mediawiki/administration.rb#L41-L57 | train |
npolar/argos-ruby | lib/argos/ds.rb | Argos.Ds.parse_message | def parse_message(contact)
header = contact[0]
body = contact[1,contact.count]
items = process_item_body(body)
combine_header_with_transmission(items, header)
end | ruby | def parse_message(contact)
header = contact[0]
body = contact[1,contact.count]
items = process_item_body(body)
combine_header_with_transmission(items, header)
end | [
"def",
"parse_message",
"(",
"contact",
")",
"header",
"=",
"contact",
"[",
"0",
"]",
"body",
"=",
"contact",
"[",
"1",
",",
"contact",
".",
"count",
"]",
"items",
"=",
"process_item_body",
"(",
"body",
")",
"combine_header_with_transmission",
"(",
"items",
",",
"header",
")",
"end"
] | Pare one DS segment | [
"Pare",
"one",
"DS",
"segment"
] | d352087dba54764a43c8ad3dbae0a91102ecbfa3 | https://github.com/npolar/argos-ruby/blob/d352087dba54764a43c8ad3dbae0a91102ecbfa3/lib/argos/ds.rb#L160-L165 | train |
npolar/argos-ruby | lib/argos/ds.rb | Argos.Ds.merge | def merge(ds, measurement, cardinality)
m = ds.select {|k,v| k != :measurements and k != :errors and k != :warn }
m = m.merge(measurement)
m = m.merge ({ technology: "argos",
type: type,
cardinality: cardinality
#file: "file://"+filename,
#source: sha1
})
# if not ds[:errors].nil? and ds[:errors].any?
# m[:errors] = ds[:errors].clone
# end
#
# if not ds[:warn].nil? and ds[:warn].any?
# m[:warn] = ds[:warn].clone
# end
#
# if not m[:sensor_data].nil? and m[:sensor_data].size != ds[:sensors]
# if m[:warn].nil?
# m[:warn] = []
# end
# m[:warn] << "sensors-count-mismatch"
# end
# Create id as SHA1 hash of measurement minus stuff that may vary (like filename)
#
# Possible improvement for is to base id on a static list of keys
# :program,
# :platform,
# :lines,
# :sensors,
# :satellite,
# :lc,
# :positioned,
# :latitude,
# :longitude,
# :altitude,
# :headers,
# :measured,
# :identical,
# :sensor_data,
# :technology,
# :type,
# :source
idbase = m.clone
idbase.delete :errors
idbase.delete :file
idbase.delete :warn
id = Digest::SHA1.hexdigest(idbase.to_json)
#m[:parser] = Argos.library_version
m[:id] = id
#m[:bundle] = bundle
m
end | ruby | def merge(ds, measurement, cardinality)
m = ds.select {|k,v| k != :measurements and k != :errors and k != :warn }
m = m.merge(measurement)
m = m.merge ({ technology: "argos",
type: type,
cardinality: cardinality
#file: "file://"+filename,
#source: sha1
})
# if not ds[:errors].nil? and ds[:errors].any?
# m[:errors] = ds[:errors].clone
# end
#
# if not ds[:warn].nil? and ds[:warn].any?
# m[:warn] = ds[:warn].clone
# end
#
# if not m[:sensor_data].nil? and m[:sensor_data].size != ds[:sensors]
# if m[:warn].nil?
# m[:warn] = []
# end
# m[:warn] << "sensors-count-mismatch"
# end
# Create id as SHA1 hash of measurement minus stuff that may vary (like filename)
#
# Possible improvement for is to base id on a static list of keys
# :program,
# :platform,
# :lines,
# :sensors,
# :satellite,
# :lc,
# :positioned,
# :latitude,
# :longitude,
# :altitude,
# :headers,
# :measured,
# :identical,
# :sensor_data,
# :technology,
# :type,
# :source
idbase = m.clone
idbase.delete :errors
idbase.delete :file
idbase.delete :warn
id = Digest::SHA1.hexdigest(idbase.to_json)
#m[:parser] = Argos.library_version
m[:id] = id
#m[:bundle] = bundle
m
end | [
"def",
"merge",
"(",
"ds",
",",
"measurement",
",",
"cardinality",
")",
"m",
"=",
"ds",
".",
"select",
"{",
"|",
"k",
",",
"v",
"|",
"k",
"!=",
":measurements",
"and",
"k",
"!=",
":errors",
"and",
"k",
"!=",
":warn",
"}",
"m",
"=",
"m",
".",
"merge",
"(",
"measurement",
")",
"m",
"=",
"m",
".",
"merge",
"(",
"{",
"technology",
":",
"\"argos\"",
",",
"type",
":",
"type",
",",
"cardinality",
":",
"cardinality",
"}",
")",
"idbase",
"=",
"m",
".",
"clone",
"idbase",
".",
"delete",
":errors",
"idbase",
".",
"delete",
":file",
"idbase",
".",
"delete",
":warn",
"id",
"=",
"Digest",
"::",
"SHA1",
".",
"hexdigest",
"(",
"idbase",
".",
"to_json",
")",
"m",
"[",
":id",
"]",
"=",
"id",
"m",
"end"
] | Merges a DS header hash into each measurement
@return [Array] Measurements with header and static metadata merged in | [
"Merges",
"a",
"DS",
"header",
"hash",
"into",
"each",
"measurement"
] | d352087dba54764a43c8ad3dbae0a91102ecbfa3 | https://github.com/npolar/argos-ruby/blob/d352087dba54764a43c8ad3dbae0a91102ecbfa3/lib/argos/ds.rb#L308-L367 | train |
datasift/datasift-ruby | lib/account_identity_limit.rb | DataSift.AccountIdentityLimit.create | def create(identity_id = '', service = '', total_allowance = nil, analyze_queries = nil)
fail BadParametersError, 'identity_id is required' if identity_id.empty?
fail BadParametersError, 'service is required' if service.empty?
fail BadParametersError, 'Must set total_allowance or analyze_queries' if
total_allowance.nil? && analyze_queries.nil?
params = { service: service }
params[:total_allowance] = total_allowance unless total_allowance.nil?
params[:analyze_queries] = analyze_queries unless analyze_queries.nil?
DataSift.request(:POST, "account/identity/#{identity_id}/limit", @config, params)
end | ruby | def create(identity_id = '', service = '', total_allowance = nil, analyze_queries = nil)
fail BadParametersError, 'identity_id is required' if identity_id.empty?
fail BadParametersError, 'service is required' if service.empty?
fail BadParametersError, 'Must set total_allowance or analyze_queries' if
total_allowance.nil? && analyze_queries.nil?
params = { service: service }
params[:total_allowance] = total_allowance unless total_allowance.nil?
params[:analyze_queries] = analyze_queries unless analyze_queries.nil?
DataSift.request(:POST, "account/identity/#{identity_id}/limit", @config, params)
end | [
"def",
"create",
"(",
"identity_id",
"=",
"''",
",",
"service",
"=",
"''",
",",
"total_allowance",
"=",
"nil",
",",
"analyze_queries",
"=",
"nil",
")",
"fail",
"BadParametersError",
",",
"'identity_id is required'",
"if",
"identity_id",
".",
"empty?",
"fail",
"BadParametersError",
",",
"'service is required'",
"if",
"service",
".",
"empty?",
"fail",
"BadParametersError",
",",
"'Must set total_allowance or analyze_queries'",
"if",
"total_allowance",
".",
"nil?",
"&&",
"analyze_queries",
".",
"nil?",
"params",
"=",
"{",
"service",
":",
"service",
"}",
"params",
"[",
":total_allowance",
"]",
"=",
"total_allowance",
"unless",
"total_allowance",
".",
"nil?",
"params",
"[",
":analyze_queries",
"]",
"=",
"analyze_queries",
"unless",
"analyze_queries",
".",
"nil?",
"DataSift",
".",
"request",
"(",
":POST",
",",
"\"account/identity/#{identity_id}/limit\"",
",",
"@config",
",",
"params",
")",
"end"
] | Creates a Limit for an Identity
@param identity_id [String] ID of the Identity for which you are creating
a limit
@param service [String] The service this limit will apply to. For example;
'facebook'
@param total_allowance [Integer] (Optional) The daily interaction limit for this Identity
@param analyze_queries [Integer] (Optional) The hourly analysis query limit for this Identity
@return [Object] API reponse object | [
"Creates",
"a",
"Limit",
"for",
"an",
"Identity"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/account_identity_limit.rb#L14-L24 | train |
datasift/datasift-ruby | lib/account_identity_limit.rb | DataSift.AccountIdentityLimit.get | def get(identity_id = '', service = '')
fail BadParametersError, 'identity_id is required' if identity_id.empty?
fail BadParametersError, 'service is required' if service.empty?
DataSift.request(:GET, "account/identity/#{identity_id}/limit/#{service}", @config)
end | ruby | def get(identity_id = '', service = '')
fail BadParametersError, 'identity_id is required' if identity_id.empty?
fail BadParametersError, 'service is required' if service.empty?
DataSift.request(:GET, "account/identity/#{identity_id}/limit/#{service}", @config)
end | [
"def",
"get",
"(",
"identity_id",
"=",
"''",
",",
"service",
"=",
"''",
")",
"fail",
"BadParametersError",
",",
"'identity_id is required'",
"if",
"identity_id",
".",
"empty?",
"fail",
"BadParametersError",
",",
"'service is required'",
"if",
"service",
".",
"empty?",
"DataSift",
".",
"request",
"(",
":GET",
",",
"\"account/identity/#{identity_id}/limit/#{service}\"",
",",
"@config",
")",
"end"
] | Get the Limit for a given Identity and Service
@param identity_id [String] ID of the Identity you wish to return limits
for
@param service [String] Name of the service you are retreiving limits for
@return [Object] API reponse object | [
"Get",
"the",
"Limit",
"for",
"a",
"given",
"Identity",
"and",
"Service"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/account_identity_limit.rb#L32-L37 | train |
datasift/datasift-ruby | lib/account_identity_limit.rb | DataSift.AccountIdentityLimit.list | def list(service = '', per_page = '', page = '')
fail BadParametersError, 'service is required' if service.empty?
params = {}
params[:per_page] = per_page unless per_page.empty?
params[:page] = page unless page.empty?
DataSift.request(:GET, "account/identity/limit/#{service}", @config, params)
end | ruby | def list(service = '', per_page = '', page = '')
fail BadParametersError, 'service is required' if service.empty?
params = {}
params[:per_page] = per_page unless per_page.empty?
params[:page] = page unless page.empty?
DataSift.request(:GET, "account/identity/limit/#{service}", @config, params)
end | [
"def",
"list",
"(",
"service",
"=",
"''",
",",
"per_page",
"=",
"''",
",",
"page",
"=",
"''",
")",
"fail",
"BadParametersError",
",",
"'service is required'",
"if",
"service",
".",
"empty?",
"params",
"=",
"{",
"}",
"params",
"[",
":per_page",
"]",
"=",
"per_page",
"unless",
"per_page",
".",
"empty?",
"params",
"[",
":page",
"]",
"=",
"page",
"unless",
"page",
".",
"empty?",
"DataSift",
".",
"request",
"(",
":GET",
",",
"\"account/identity/limit/#{service}\"",
",",
"@config",
",",
"params",
")",
"end"
] | Returns a list Identities and their Limits for a given Service
@param service [String] ID of the Identity we are fetching Limits for
@param per_page [Integer] (Optional) How many Identities and Limits should
be returned per page of results
@param page [Integer] (Optional) Which page of results to return
@return [Object] API reponse object | [
"Returns",
"a",
"list",
"Identities",
"and",
"their",
"Limits",
"for",
"a",
"given",
"Service"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/account_identity_limit.rb#L46-L54 | train |
datasift/datasift-ruby | lib/account_identity_limit.rb | DataSift.AccountIdentityLimit.delete | def delete(identity_id = '', service = '')
fail BadParametersError, 'identity_id is required' if identity_id.empty?
fail BadParametersError, 'service is required' if service.empty?
DataSift.request(:DELETE, "account/identity/#{identity_id}/limit/#{service}", @config)
end | ruby | def delete(identity_id = '', service = '')
fail BadParametersError, 'identity_id is required' if identity_id.empty?
fail BadParametersError, 'service is required' if service.empty?
DataSift.request(:DELETE, "account/identity/#{identity_id}/limit/#{service}", @config)
end | [
"def",
"delete",
"(",
"identity_id",
"=",
"''",
",",
"service",
"=",
"''",
")",
"fail",
"BadParametersError",
",",
"'identity_id is required'",
"if",
"identity_id",
".",
"empty?",
"fail",
"BadParametersError",
",",
"'service is required'",
"if",
"service",
".",
"empty?",
"DataSift",
".",
"request",
"(",
":DELETE",
",",
"\"account/identity/#{identity_id}/limit/#{service}\"",
",",
"@config",
")",
"end"
] | Removes a Service Limit for an Identity
@param identity_id [String] ID of the Identity for which you wish to
remove the Limit
@param service [String] Service from which you wish to remove the Limit
@return [Object] API response object | [
"Removes",
"a",
"Service",
"Limit",
"for",
"an",
"Identity"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/account_identity_limit.rb#L83-L88 | train |
faradayio/ecs_compose | lib/ecs_compose/json_generator.rb | EcsCompose.JsonGenerator.generate | def generate
if @yaml.has_key?("version")
@yaml = @yaml.fetch("services")
end
# Generate JSON for our containers.
containers = @yaml.map do |name, fields|
# Skip this service if we've been given a list to emit, and
# this service isn't on the list.
begin
mount_points = (fields["volumes"] || []).map do |v|
host, container, ro = v.split(':')
{
"sourceVolume" => path_to_vol_name(host),
"containerPath" => container,
"readOnly" => (ro == "ro")
}
end
json = {
"name" => name,
"image" => fields.fetch("image"),
# Default to a tiny guaranteed CPU share. Currently, 2 is the
# smallest meaningful value, and various ECS tools will round
# smaller numbers up.
"cpu" => fields["cpu_shares"] || 2,
"memory" => mem_limit_to_mb(fields.fetch("mem_limit")),
"links" => fields["links"] || [],
"portMappings" =>
(fields["ports"] || []).map {|pm| port_mapping(pm) },
"essential" => true,
"environment" => environment(fields["environment"] || {}),
"mountPoints" => mount_points,
"volumesFrom" => [],
"dockerLabels" => fields.fetch("labels", {}),
}
if fields.has_key?("entrypoint")
json["entryPoint"] = command_line(fields.fetch("entrypoint"))
end
if fields.has_key?("command")
json["command"] = command_line(fields.fetch("command"))
end
if fields.has_key?("privileged")
json["privileged"] = fields.fetch("privileged")
end
if fields.has_key?("ulimits")
json["ulimits"] = fields.fetch("ulimits").map do |name, limits|
case limits
when Hash
softLimit = limits.fetch("soft")
hardLimit = limits.fetch("hard")
else
softLimit = limits
hardLimit = limits
end
{ "name" => name,
"softLimit" => softLimit,
"hardLimit" => hardLimit }
end
end
json
rescue KeyError => e
# This makes it a lot easier to localize errors a bit.
raise ContainerKeyError.new("#{e.message} processing container \"#{name}\"")
end
end
# Generate our top-level volume declarations.
volumes = @yaml.map do |name, fields|
(fields["volumes"] || []).map {|v| v.split(':')[0] }
end.flatten.sort.uniq.map do |host_path|
{
"name" => path_to_vol_name(host_path),
"host" => { "sourcePath" => host_path }
}
end
# Return our final JSON.
{
"family" => @family,
"containerDefinitions" => containers,
"volumes" => volumes
}
end | ruby | def generate
if @yaml.has_key?("version")
@yaml = @yaml.fetch("services")
end
# Generate JSON for our containers.
containers = @yaml.map do |name, fields|
# Skip this service if we've been given a list to emit, and
# this service isn't on the list.
begin
mount_points = (fields["volumes"] || []).map do |v|
host, container, ro = v.split(':')
{
"sourceVolume" => path_to_vol_name(host),
"containerPath" => container,
"readOnly" => (ro == "ro")
}
end
json = {
"name" => name,
"image" => fields.fetch("image"),
# Default to a tiny guaranteed CPU share. Currently, 2 is the
# smallest meaningful value, and various ECS tools will round
# smaller numbers up.
"cpu" => fields["cpu_shares"] || 2,
"memory" => mem_limit_to_mb(fields.fetch("mem_limit")),
"links" => fields["links"] || [],
"portMappings" =>
(fields["ports"] || []).map {|pm| port_mapping(pm) },
"essential" => true,
"environment" => environment(fields["environment"] || {}),
"mountPoints" => mount_points,
"volumesFrom" => [],
"dockerLabels" => fields.fetch("labels", {}),
}
if fields.has_key?("entrypoint")
json["entryPoint"] = command_line(fields.fetch("entrypoint"))
end
if fields.has_key?("command")
json["command"] = command_line(fields.fetch("command"))
end
if fields.has_key?("privileged")
json["privileged"] = fields.fetch("privileged")
end
if fields.has_key?("ulimits")
json["ulimits"] = fields.fetch("ulimits").map do |name, limits|
case limits
when Hash
softLimit = limits.fetch("soft")
hardLimit = limits.fetch("hard")
else
softLimit = limits
hardLimit = limits
end
{ "name" => name,
"softLimit" => softLimit,
"hardLimit" => hardLimit }
end
end
json
rescue KeyError => e
# This makes it a lot easier to localize errors a bit.
raise ContainerKeyError.new("#{e.message} processing container \"#{name}\"")
end
end
# Generate our top-level volume declarations.
volumes = @yaml.map do |name, fields|
(fields["volumes"] || []).map {|v| v.split(':')[0] }
end.flatten.sort.uniq.map do |host_path|
{
"name" => path_to_vol_name(host_path),
"host" => { "sourcePath" => host_path }
}
end
# Return our final JSON.
{
"family" => @family,
"containerDefinitions" => containers,
"volumes" => volumes
}
end | [
"def",
"generate",
"if",
"@yaml",
".",
"has_key?",
"(",
"\"version\"",
")",
"@yaml",
"=",
"@yaml",
".",
"fetch",
"(",
"\"services\"",
")",
"end",
"containers",
"=",
"@yaml",
".",
"map",
"do",
"|",
"name",
",",
"fields",
"|",
"begin",
"mount_points",
"=",
"(",
"fields",
"[",
"\"volumes\"",
"]",
"||",
"[",
"]",
")",
".",
"map",
"do",
"|",
"v",
"|",
"host",
",",
"container",
",",
"ro",
"=",
"v",
".",
"split",
"(",
"':'",
")",
"{",
"\"sourceVolume\"",
"=>",
"path_to_vol_name",
"(",
"host",
")",
",",
"\"containerPath\"",
"=>",
"container",
",",
"\"readOnly\"",
"=>",
"(",
"ro",
"==",
"\"ro\"",
")",
"}",
"end",
"json",
"=",
"{",
"\"name\"",
"=>",
"name",
",",
"\"image\"",
"=>",
"fields",
".",
"fetch",
"(",
"\"image\"",
")",
",",
"\"cpu\"",
"=>",
"fields",
"[",
"\"cpu_shares\"",
"]",
"||",
"2",
",",
"\"memory\"",
"=>",
"mem_limit_to_mb",
"(",
"fields",
".",
"fetch",
"(",
"\"mem_limit\"",
")",
")",
",",
"\"links\"",
"=>",
"fields",
"[",
"\"links\"",
"]",
"||",
"[",
"]",
",",
"\"portMappings\"",
"=>",
"(",
"fields",
"[",
"\"ports\"",
"]",
"||",
"[",
"]",
")",
".",
"map",
"{",
"|",
"pm",
"|",
"port_mapping",
"(",
"pm",
")",
"}",
",",
"\"essential\"",
"=>",
"true",
",",
"\"environment\"",
"=>",
"environment",
"(",
"fields",
"[",
"\"environment\"",
"]",
"||",
"{",
"}",
")",
",",
"\"mountPoints\"",
"=>",
"mount_points",
",",
"\"volumesFrom\"",
"=>",
"[",
"]",
",",
"\"dockerLabels\"",
"=>",
"fields",
".",
"fetch",
"(",
"\"labels\"",
",",
"{",
"}",
")",
",",
"}",
"if",
"fields",
".",
"has_key?",
"(",
"\"entrypoint\"",
")",
"json",
"[",
"\"entryPoint\"",
"]",
"=",
"command_line",
"(",
"fields",
".",
"fetch",
"(",
"\"entrypoint\"",
")",
")",
"end",
"if",
"fields",
".",
"has_key?",
"(",
"\"command\"",
")",
"json",
"[",
"\"command\"",
"]",
"=",
"command_line",
"(",
"fields",
".",
"fetch",
"(",
"\"command\"",
")",
")",
"end",
"if",
"fields",
".",
"has_key?",
"(",
"\"privileged\"",
")",
"json",
"[",
"\"privileged\"",
"]",
"=",
"fields",
".",
"fetch",
"(",
"\"privileged\"",
")",
"end",
"if",
"fields",
".",
"has_key?",
"(",
"\"ulimits\"",
")",
"json",
"[",
"\"ulimits\"",
"]",
"=",
"fields",
".",
"fetch",
"(",
"\"ulimits\"",
")",
".",
"map",
"do",
"|",
"name",
",",
"limits",
"|",
"case",
"limits",
"when",
"Hash",
"softLimit",
"=",
"limits",
".",
"fetch",
"(",
"\"soft\"",
")",
"hardLimit",
"=",
"limits",
".",
"fetch",
"(",
"\"hard\"",
")",
"else",
"softLimit",
"=",
"limits",
"hardLimit",
"=",
"limits",
"end",
"{",
"\"name\"",
"=>",
"name",
",",
"\"softLimit\"",
"=>",
"softLimit",
",",
"\"hardLimit\"",
"=>",
"hardLimit",
"}",
"end",
"end",
"json",
"rescue",
"KeyError",
"=>",
"e",
"raise",
"ContainerKeyError",
".",
"new",
"(",
"\"#{e.message} processing container \\\"#{name}\\\"\"",
")",
"end",
"end",
"volumes",
"=",
"@yaml",
".",
"map",
"do",
"|",
"name",
",",
"fields",
"|",
"(",
"fields",
"[",
"\"volumes\"",
"]",
"||",
"[",
"]",
")",
".",
"map",
"{",
"|",
"v",
"|",
"v",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
"}",
"end",
".",
"flatten",
".",
"sort",
".",
"uniq",
".",
"map",
"do",
"|",
"host_path",
"|",
"{",
"\"name\"",
"=>",
"path_to_vol_name",
"(",
"host_path",
")",
",",
"\"host\"",
"=>",
"{",
"\"sourcePath\"",
"=>",
"host_path",
"}",
"}",
"end",
"{",
"\"family\"",
"=>",
"@family",
",",
"\"containerDefinitions\"",
"=>",
"containers",
",",
"\"volumes\"",
"=>",
"volumes",
"}",
"end"
] | Create a new generator, specifying the family name to use, and the
raw YAML input.
Generate an ECS task definition as a raw Ruby hash. | [
"Create",
"a",
"new",
"generator",
"specifying",
"the",
"family",
"name",
"to",
"use",
"and",
"the",
"raw",
"YAML",
"input",
".",
"Generate",
"an",
"ECS",
"task",
"definition",
"as",
"a",
"raw",
"Ruby",
"hash",
"."
] | 5a897c85f3476e1d3d1ed01db0a301706a3e376d | https://github.com/faradayio/ecs_compose/blob/5a897c85f3476e1d3d1ed01db0a301706a3e376d/lib/ecs_compose/json_generator.rb#L21-L105 | train |
faradayio/ecs_compose | lib/ecs_compose/json_generator.rb | EcsCompose.JsonGenerator.mem_limit_to_mb | def mem_limit_to_mb(mem_limit)
unless mem_limit.downcase =~ /\A(\d+)([bkmg])\z/
raise "Cannot parse docker memory limit: #{mem_limit}"
end
val = $1.to_i
case $2
when "b" then (val / (1024.0 * 1024.0)).ceil
when "k" then (val / 1024.0).ceil
when "m" then (val * 1.0).ceil
when "g" then (val * 1024.0).ceil
else raise "Can't convert #{mem_limit} to megabytes"
end
end | ruby | def mem_limit_to_mb(mem_limit)
unless mem_limit.downcase =~ /\A(\d+)([bkmg])\z/
raise "Cannot parse docker memory limit: #{mem_limit}"
end
val = $1.to_i
case $2
when "b" then (val / (1024.0 * 1024.0)).ceil
when "k" then (val / 1024.0).ceil
when "m" then (val * 1.0).ceil
when "g" then (val * 1024.0).ceil
else raise "Can't convert #{mem_limit} to megabytes"
end
end | [
"def",
"mem_limit_to_mb",
"(",
"mem_limit",
")",
"unless",
"mem_limit",
".",
"downcase",
"=~",
"/",
"\\A",
"\\d",
"\\z",
"/",
"raise",
"\"Cannot parse docker memory limit: #{mem_limit}\"",
"end",
"val",
"=",
"$1",
".",
"to_i",
"case",
"$2",
"when",
"\"b\"",
"then",
"(",
"val",
"/",
"(",
"1024.0",
"*",
"1024.0",
")",
")",
".",
"ceil",
"when",
"\"k\"",
"then",
"(",
"val",
"/",
"1024.0",
")",
".",
"ceil",
"when",
"\"m\"",
"then",
"(",
"val",
"*",
"1.0",
")",
".",
"ceil",
"when",
"\"g\"",
"then",
"(",
"val",
"*",
"1024.0",
")",
".",
"ceil",
"else",
"raise",
"\"Can't convert #{mem_limit} to megabytes\"",
"end",
"end"
] | Parse a Docker-style `mem_limit` and convert to megabytes. | [
"Parse",
"a",
"Docker",
"-",
"style",
"mem_limit",
"and",
"convert",
"to",
"megabytes",
"."
] | 5a897c85f3476e1d3d1ed01db0a301706a3e376d | https://github.com/faradayio/ecs_compose/blob/5a897c85f3476e1d3d1ed01db0a301706a3e376d/lib/ecs_compose/json_generator.rb#L153-L165 | train |
faradayio/ecs_compose | lib/ecs_compose/json_generator.rb | EcsCompose.JsonGenerator.port_mapping | def port_mapping(port)
case port.to_s
when /\A(\d+)(?:\/([a-z]+))?\z/
port = $1.to_i
{
"hostPort" => port,
"containerPort" => port,
"protocol" => $2 || "tcp"
}
when /\A(\d+):(\d+)(?:\/([a-z]+))?\z/
{
"hostPort" => $1.to_i,
"containerPort" => $2.to_i,
"protocol" => $3 || "tcp"
}
else
raise "Cannot parse port specification: #{port}"
end
end | ruby | def port_mapping(port)
case port.to_s
when /\A(\d+)(?:\/([a-z]+))?\z/
port = $1.to_i
{
"hostPort" => port,
"containerPort" => port,
"protocol" => $2 || "tcp"
}
when /\A(\d+):(\d+)(?:\/([a-z]+))?\z/
{
"hostPort" => $1.to_i,
"containerPort" => $2.to_i,
"protocol" => $3 || "tcp"
}
else
raise "Cannot parse port specification: #{port}"
end
end | [
"def",
"port_mapping",
"(",
"port",
")",
"case",
"port",
".",
"to_s",
"when",
"/",
"\\A",
"\\d",
"\\/",
"\\z",
"/",
"port",
"=",
"$1",
".",
"to_i",
"{",
"\"hostPort\"",
"=>",
"port",
",",
"\"containerPort\"",
"=>",
"port",
",",
"\"protocol\"",
"=>",
"$2",
"||",
"\"tcp\"",
"}",
"when",
"/",
"\\A",
"\\d",
"\\d",
"\\/",
"\\z",
"/",
"{",
"\"hostPort\"",
"=>",
"$1",
".",
"to_i",
",",
"\"containerPort\"",
"=>",
"$2",
".",
"to_i",
",",
"\"protocol\"",
"=>",
"$3",
"||",
"\"tcp\"",
"}",
"else",
"raise",
"\"Cannot parse port specification: #{port}\"",
"end",
"end"
] | Parse a Docker-style port mapping and convert to ECS format. | [
"Parse",
"a",
"Docker",
"-",
"style",
"port",
"mapping",
"and",
"convert",
"to",
"ECS",
"format",
"."
] | 5a897c85f3476e1d3d1ed01db0a301706a3e376d | https://github.com/faradayio/ecs_compose/blob/5a897c85f3476e1d3d1ed01db0a301706a3e376d/lib/ecs_compose/json_generator.rb#L168-L186 | train |
pivotal-cf-experimental/semi_semantic | lib/semi_semantic/version_segment.rb | SemiSemantic.VersionSegment.increment | def increment(index=-1)
value = @components[index]
raise TypeError.new "'#{value}' is not an integer" unless value.is_a? Integer
copy = Array.new @components
copy[index] = value + 1
while index < copy.size && index != -1
index += 1
value = copy[index]
if value.is_a? Integer
copy[index] = 0
end
end
self.class.new copy
end | ruby | def increment(index=-1)
value = @components[index]
raise TypeError.new "'#{value}' is not an integer" unless value.is_a? Integer
copy = Array.new @components
copy[index] = value + 1
while index < copy.size && index != -1
index += 1
value = copy[index]
if value.is_a? Integer
copy[index] = 0
end
end
self.class.new copy
end | [
"def",
"increment",
"(",
"index",
"=",
"-",
"1",
")",
"value",
"=",
"@components",
"[",
"index",
"]",
"raise",
"TypeError",
".",
"new",
"\"'#{value}' is not an integer\"",
"unless",
"value",
".",
"is_a?",
"Integer",
"copy",
"=",
"Array",
".",
"new",
"@components",
"copy",
"[",
"index",
"]",
"=",
"value",
"+",
"1",
"while",
"index",
"<",
"copy",
".",
"size",
"&&",
"index",
"!=",
"-",
"1",
"index",
"+=",
"1",
"value",
"=",
"copy",
"[",
"index",
"]",
"if",
"value",
".",
"is_a?",
"Integer",
"copy",
"[",
"index",
"]",
"=",
"0",
"end",
"end",
"self",
".",
"class",
".",
"new",
"copy",
"end"
] | Construction can throw ArgumentError, but does no parsing or type-conversion
Returns a copy of the VersionCluster with the integer at the provided index incremented by one.
Raises a TypeError if the value at that index is not an integer. | [
"Construction",
"can",
"throw",
"ArgumentError",
"but",
"does",
"no",
"parsing",
"or",
"type",
"-",
"conversion",
"Returns",
"a",
"copy",
"of",
"the",
"VersionCluster",
"with",
"the",
"integer",
"at",
"the",
"provided",
"index",
"incremented",
"by",
"one",
".",
"Raises",
"a",
"TypeError",
"if",
"the",
"value",
"at",
"that",
"index",
"is",
"not",
"an",
"integer",
"."
] | 27cffb1ebeb44ef69d743577ecc3890456a109e9 | https://github.com/pivotal-cf-experimental/semi_semantic/blob/27cffb1ebeb44ef69d743577ecc3890456a109e9/lib/semi_semantic/version_segment.rb#L62-L78 | train |
pivotal-cf-experimental/semi_semantic | lib/semi_semantic/version_segment.rb | SemiSemantic.VersionSegment.decrement | def decrement(index=-1)
value = @components[index]
raise TypeError.new "'#{value}' is not an integer" unless value.is_a? Integer
raise RangeError.new "'#{value}' is zero or less" unless value > 0
copy = Array.new @components
copy[index] = value - 1
self.class.new copy
end | ruby | def decrement(index=-1)
value = @components[index]
raise TypeError.new "'#{value}' is not an integer" unless value.is_a? Integer
raise RangeError.new "'#{value}' is zero or less" unless value > 0
copy = Array.new @components
copy[index] = value - 1
self.class.new copy
end | [
"def",
"decrement",
"(",
"index",
"=",
"-",
"1",
")",
"value",
"=",
"@components",
"[",
"index",
"]",
"raise",
"TypeError",
".",
"new",
"\"'#{value}' is not an integer\"",
"unless",
"value",
".",
"is_a?",
"Integer",
"raise",
"RangeError",
".",
"new",
"\"'#{value}' is zero or less\"",
"unless",
"value",
">",
"0",
"copy",
"=",
"Array",
".",
"new",
"@components",
"copy",
"[",
"index",
"]",
"=",
"value",
"-",
"1",
"self",
".",
"class",
".",
"new",
"copy",
"end"
] | Returns a copy of the VersionCluster with the integer at the provided index decremented by one.
Raises a TypeError if the value at that index is not an integer.
Raises a RangeError if the value is zero or less | [
"Returns",
"a",
"copy",
"of",
"the",
"VersionCluster",
"with",
"the",
"integer",
"at",
"the",
"provided",
"index",
"decremented",
"by",
"one",
".",
"Raises",
"a",
"TypeError",
"if",
"the",
"value",
"at",
"that",
"index",
"is",
"not",
"an",
"integer",
".",
"Raises",
"a",
"RangeError",
"if",
"the",
"value",
"is",
"zero",
"or",
"less"
] | 27cffb1ebeb44ef69d743577ecc3890456a109e9 | https://github.com/pivotal-cf-experimental/semi_semantic/blob/27cffb1ebeb44ef69d743577ecc3890456a109e9/lib/semi_semantic/version_segment.rb#L83-L91 | train |
pivotal-cf-experimental/semi_semantic | lib/semi_semantic/version_segment.rb | SemiSemantic.VersionSegment.compare_arrays | def compare_arrays(a, b)
a.each_with_index do |v1, i|
v2 = b[i]
if v1.is_a?(String) && v2.is_a?(Integer)
return 1
elsif v1.is_a?(Integer) && v2.is_a?(String)
return -1
end
comparison = v1 <=> v2
unless comparison == 0
return comparison
end
end
0
end | ruby | def compare_arrays(a, b)
a.each_with_index do |v1, i|
v2 = b[i]
if v1.is_a?(String) && v2.is_a?(Integer)
return 1
elsif v1.is_a?(Integer) && v2.is_a?(String)
return -1
end
comparison = v1 <=> v2
unless comparison == 0
return comparison
end
end
0
end | [
"def",
"compare_arrays",
"(",
"a",
",",
"b",
")",
"a",
".",
"each_with_index",
"do",
"|",
"v1",
",",
"i",
"|",
"v2",
"=",
"b",
"[",
"i",
"]",
"if",
"v1",
".",
"is_a?",
"(",
"String",
")",
"&&",
"v2",
".",
"is_a?",
"(",
"Integer",
")",
"return",
"1",
"elsif",
"v1",
".",
"is_a?",
"(",
"Integer",
")",
"&&",
"v2",
".",
"is_a?",
"(",
"String",
")",
"return",
"-",
"1",
"end",
"comparison",
"=",
"v1",
"<=>",
"v2",
"unless",
"comparison",
"==",
"0",
"return",
"comparison",
"end",
"end",
"0",
"end"
] | a & b must have the same length | [
"a",
"&",
"b",
"must",
"have",
"the",
"same",
"length"
] | 27cffb1ebeb44ef69d743577ecc3890456a109e9 | https://github.com/pivotal-cf-experimental/semi_semantic/blob/27cffb1ebeb44ef69d743577ecc3890456a109e9/lib/semi_semantic/version_segment.rb#L99-L113 | train |
datasift/datasift-ruby | lib/managed_source.rb | DataSift.ManagedSource.create | def create(source_type, name, parameters = {}, resources = [], auth = [], options = {})
fail BadParametersError, 'source_type and name are required' if source_type.nil? || name.nil?
params = {
:source_type => source_type,
:name => name
}
params.merge!(options) unless options.empty?
params.merge!(
{ :auth => auth.is_a?(String) ? auth : MultiJson.dump(auth) }
) unless auth.empty?
params.merge!(
{ :parameters => parameters.is_a?(String) ? parameters : MultiJson.dump(parameters) }
) unless parameters.empty?
params.merge!(
{ :resources => resources.is_a?(String) ? resources : MultiJson.dump(resources) }
) if resources.length > 0
DataSift.request(:POST, 'source/create', @config, params)
end | ruby | def create(source_type, name, parameters = {}, resources = [], auth = [], options = {})
fail BadParametersError, 'source_type and name are required' if source_type.nil? || name.nil?
params = {
:source_type => source_type,
:name => name
}
params.merge!(options) unless options.empty?
params.merge!(
{ :auth => auth.is_a?(String) ? auth : MultiJson.dump(auth) }
) unless auth.empty?
params.merge!(
{ :parameters => parameters.is_a?(String) ? parameters : MultiJson.dump(parameters) }
) unless parameters.empty?
params.merge!(
{ :resources => resources.is_a?(String) ? resources : MultiJson.dump(resources) }
) if resources.length > 0
DataSift.request(:POST, 'source/create', @config, params)
end | [
"def",
"create",
"(",
"source_type",
",",
"name",
",",
"parameters",
"=",
"{",
"}",
",",
"resources",
"=",
"[",
"]",
",",
"auth",
"=",
"[",
"]",
",",
"options",
"=",
"{",
"}",
")",
"fail",
"BadParametersError",
",",
"'source_type and name are required'",
"if",
"source_type",
".",
"nil?",
"||",
"name",
".",
"nil?",
"params",
"=",
"{",
":source_type",
"=>",
"source_type",
",",
":name",
"=>",
"name",
"}",
"params",
".",
"merge!",
"(",
"options",
")",
"unless",
"options",
".",
"empty?",
"params",
".",
"merge!",
"(",
"{",
":auth",
"=>",
"auth",
".",
"is_a?",
"(",
"String",
")",
"?",
"auth",
":",
"MultiJson",
".",
"dump",
"(",
"auth",
")",
"}",
")",
"unless",
"auth",
".",
"empty?",
"params",
".",
"merge!",
"(",
"{",
":parameters",
"=>",
"parameters",
".",
"is_a?",
"(",
"String",
")",
"?",
"parameters",
":",
"MultiJson",
".",
"dump",
"(",
"parameters",
")",
"}",
")",
"unless",
"parameters",
".",
"empty?",
"params",
".",
"merge!",
"(",
"{",
":resources",
"=>",
"resources",
".",
"is_a?",
"(",
"String",
")",
"?",
"resources",
":",
"MultiJson",
".",
"dump",
"(",
"resources",
")",
"}",
")",
"if",
"resources",
".",
"length",
">",
"0",
"DataSift",
".",
"request",
"(",
":POST",
",",
"'source/create'",
",",
"@config",
",",
"params",
")",
"end"
] | Creates a new managed source
@param source_type [String] Type of Managed Source you are creating. e.g.
facebook_page, instagram, etc
@param name [String] Name of this Managed Source
@param parameters [Hash] Source-specific configuration parameters
@param resources [Array] Array of source-specific resources
@param auth [Array] Array of source-specific auth credentials | [
"Creates",
"a",
"new",
"managed",
"source"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/managed_source.rb#L13-L30 | train |
datasift/datasift-ruby | lib/managed_source.rb | DataSift.ManagedSource.update | def update(id, source_type, name, parameters = {}, resources = [], auth = [], options = {})
fail BadParametersError, 'ID, source_type and name are required' if id.nil? || source_type.nil? || name.nil?
params = {
:id => id,
:source_type => source_type,
:name => name
}
params.merge!(options) unless options.empty?
params.merge!({:auth => MultiJson.dump(auth)}) if !auth.empty?
params.merge!({:parameters => MultiJson.dump(parameters)}) if !parameters.empty?
params.merge!({:resources => MultiJson.dump(resources)}) if resources.length > 0
DataSift.request(:POST, 'source/update', @config, params)
end | ruby | def update(id, source_type, name, parameters = {}, resources = [], auth = [], options = {})
fail BadParametersError, 'ID, source_type and name are required' if id.nil? || source_type.nil? || name.nil?
params = {
:id => id,
:source_type => source_type,
:name => name
}
params.merge!(options) unless options.empty?
params.merge!({:auth => MultiJson.dump(auth)}) if !auth.empty?
params.merge!({:parameters => MultiJson.dump(parameters)}) if !parameters.empty?
params.merge!({:resources => MultiJson.dump(resources)}) if resources.length > 0
DataSift.request(:POST, 'source/update', @config, params)
end | [
"def",
"update",
"(",
"id",
",",
"source_type",
",",
"name",
",",
"parameters",
"=",
"{",
"}",
",",
"resources",
"=",
"[",
"]",
",",
"auth",
"=",
"[",
"]",
",",
"options",
"=",
"{",
"}",
")",
"fail",
"BadParametersError",
",",
"'ID, source_type and name are required'",
"if",
"id",
".",
"nil?",
"||",
"source_type",
".",
"nil?",
"||",
"name",
".",
"nil?",
"params",
"=",
"{",
":id",
"=>",
"id",
",",
":source_type",
"=>",
"source_type",
",",
":name",
"=>",
"name",
"}",
"params",
".",
"merge!",
"(",
"options",
")",
"unless",
"options",
".",
"empty?",
"params",
".",
"merge!",
"(",
"{",
":auth",
"=>",
"MultiJson",
".",
"dump",
"(",
"auth",
")",
"}",
")",
"if",
"!",
"auth",
".",
"empty?",
"params",
".",
"merge!",
"(",
"{",
":parameters",
"=>",
"MultiJson",
".",
"dump",
"(",
"parameters",
")",
"}",
")",
"if",
"!",
"parameters",
".",
"empty?",
"params",
".",
"merge!",
"(",
"{",
":resources",
"=>",
"MultiJson",
".",
"dump",
"(",
"resources",
")",
"}",
")",
"if",
"resources",
".",
"length",
">",
"0",
"DataSift",
".",
"request",
"(",
":POST",
",",
"'source/update'",
",",
"@config",
",",
"params",
")",
"end"
] | Update a Managed Source
@param id [String] ID of the Managed Source you are updating
@param source_type [String] Type of Managed Source you are updating
@param name [String] Name (or new name) of the Managed Source
@param parameters [Hash] Source-specific configuration parameters
@param resources [Array] Array of source-specific resources
@param auth [Array] Array of source-specific auth credentials | [
"Update",
"a",
"Managed",
"Source"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/managed_source.rb#L40-L53 | train |
datasift/datasift-ruby | lib/managed_source.rb | DataSift.ManagedSource.get | def get(id = nil, source_type = nil, page = 1, per_page = 20)
params = { :page => page, :per_page => per_page }
params.merge!({ :id => id }) if !id.nil?
params.merge!({ :source_type => source_type }) if !source_type.nil?
DataSift.request(:GET, 'source/get', @config, params)
end | ruby | def get(id = nil, source_type = nil, page = 1, per_page = 20)
params = { :page => page, :per_page => per_page }
params.merge!({ :id => id }) if !id.nil?
params.merge!({ :source_type => source_type }) if !source_type.nil?
DataSift.request(:GET, 'source/get', @config, params)
end | [
"def",
"get",
"(",
"id",
"=",
"nil",
",",
"source_type",
"=",
"nil",
",",
"page",
"=",
"1",
",",
"per_page",
"=",
"20",
")",
"params",
"=",
"{",
":page",
"=>",
"page",
",",
":per_page",
"=>",
"per_page",
"}",
"params",
".",
"merge!",
"(",
"{",
":id",
"=>",
"id",
"}",
")",
"if",
"!",
"id",
".",
"nil?",
"params",
".",
"merge!",
"(",
"{",
":source_type",
"=>",
"source_type",
"}",
")",
"if",
"!",
"source_type",
".",
"nil?",
"DataSift",
".",
"request",
"(",
":GET",
",",
"'source/get'",
",",
"@config",
",",
"params",
")",
"end"
] | Retrieve details of a Managed Source
@param id [String] ID of the Managed Source you are getting. Omitting the
ID will return a list of Managed Sources
@param source_type [String] Limits the list of Managed Sources returned to
only sources of a specific source type if specified
@param page [Integer] Number of Managed Sources to return on one page of
results
@param per_page [Integer] Number of Managed Sources to return per page | [
"Retrieve",
"details",
"of",
"a",
"Managed",
"Source"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/managed_source.rb#L88-L94 | train |
datasift/datasift-ruby | lib/managed_source.rb | DataSift.ManagedSource.log | def log(id, page = 1, per_page = 20)
fail BadParametersError, 'ID is required' if id.nil?
DataSift.request(:POST, 'source/log', @config, { :id => id, :page => page, :per_page => per_page })
end | ruby | def log(id, page = 1, per_page = 20)
fail BadParametersError, 'ID is required' if id.nil?
DataSift.request(:POST, 'source/log', @config, { :id => id, :page => page, :per_page => per_page })
end | [
"def",
"log",
"(",
"id",
",",
"page",
"=",
"1",
",",
"per_page",
"=",
"20",
")",
"fail",
"BadParametersError",
",",
"'ID is required'",
"if",
"id",
".",
"nil?",
"DataSift",
".",
"request",
"(",
":POST",
",",
"'source/log'",
",",
"@config",
",",
"{",
":id",
"=>",
"id",
",",
":page",
"=>",
"page",
",",
":per_page",
"=>",
"per_page",
"}",
")",
"end"
] | Retrieve log details of Managed Sources
@param id [String] ID of the Managed Source for which you are collecting
logs
@param page [Integer] Number of Managed Source logs to return on one page
of results
@param per_page [Integer] Number of Managed Source logs to return per page | [
"Retrieve",
"log",
"details",
"of",
"Managed",
"Sources"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/managed_source.rb#L103-L106 | train |
guard/guard-less | lib/guard/less.rb | Guard.Less.compile | def compile(lessfile, cssfile)
import_paths = options[:import_paths].unshift(File.dirname(lessfile))
parser = ::Less::Parser.new paths: import_paths, filename: lessfile
File.open(lessfile, 'r') do |infile|
File.open(cssfile, 'w') do |outfile|
tree = parser.parse(infile.read)
outfile << tree.to_css(compress: options[:compress], yuicompress: options[:yuicompress])
end
end
true
rescue StandardError => e
Compat::UI.info "Guard::Less: Compiling #{lessfile} failed with message: #{e.message}"
false
end | ruby | def compile(lessfile, cssfile)
import_paths = options[:import_paths].unshift(File.dirname(lessfile))
parser = ::Less::Parser.new paths: import_paths, filename: lessfile
File.open(lessfile, 'r') do |infile|
File.open(cssfile, 'w') do |outfile|
tree = parser.parse(infile.read)
outfile << tree.to_css(compress: options[:compress], yuicompress: options[:yuicompress])
end
end
true
rescue StandardError => e
Compat::UI.info "Guard::Less: Compiling #{lessfile} failed with message: #{e.message}"
false
end | [
"def",
"compile",
"(",
"lessfile",
",",
"cssfile",
")",
"import_paths",
"=",
"options",
"[",
":import_paths",
"]",
".",
"unshift",
"(",
"File",
".",
"dirname",
"(",
"lessfile",
")",
")",
"parser",
"=",
"::",
"Less",
"::",
"Parser",
".",
"new",
"paths",
":",
"import_paths",
",",
"filename",
":",
"lessfile",
"File",
".",
"open",
"(",
"lessfile",
",",
"'r'",
")",
"do",
"|",
"infile",
"|",
"File",
".",
"open",
"(",
"cssfile",
",",
"'w'",
")",
"do",
"|",
"outfile",
"|",
"tree",
"=",
"parser",
".",
"parse",
"(",
"infile",
".",
"read",
")",
"outfile",
"<<",
"tree",
".",
"to_css",
"(",
"compress",
":",
"options",
"[",
":compress",
"]",
",",
"yuicompress",
":",
"options",
"[",
":yuicompress",
"]",
")",
"end",
"end",
"true",
"rescue",
"StandardError",
"=>",
"e",
"Compat",
"::",
"UI",
".",
"info",
"\"Guard::Less: Compiling #{lessfile} failed with message: #{e.message}\"",
"false",
"end"
] | Parse the source lessfile and write to target cssfile | [
"Parse",
"the",
"source",
"lessfile",
"and",
"write",
"to",
"target",
"cssfile"
] | 95e5af13f6d7cb554810ed585f2b13efe79353b2 | https://github.com/guard/guard-less/blob/95e5af13f6d7cb554810ed585f2b13efe79353b2/lib/guard/less.rb#L68-L81 | train |
datasift/datasift-ruby | lib/pylon.rb | DataSift.Pylon.tags | def tags(hash = '', id = '', service = 'facebook')
fail BadParametersError, 'hash or id is required' if hash.empty? && id.empty?
fail BadParametersError, 'service is required' if service.empty?
params = {}
params.merge!(hash: hash) unless hash.empty?
params.merge!(id: id) unless id.empty?
DataSift.request(:GET, build_path(service, 'pylon/tags', @config), @config, params)
end | ruby | def tags(hash = '', id = '', service = 'facebook')
fail BadParametersError, 'hash or id is required' if hash.empty? && id.empty?
fail BadParametersError, 'service is required' if service.empty?
params = {}
params.merge!(hash: hash) unless hash.empty?
params.merge!(id: id) unless id.empty?
DataSift.request(:GET, build_path(service, 'pylon/tags', @config), @config, params)
end | [
"def",
"tags",
"(",
"hash",
"=",
"''",
",",
"id",
"=",
"''",
",",
"service",
"=",
"'facebook'",
")",
"fail",
"BadParametersError",
",",
"'hash or id is required'",
"if",
"hash",
".",
"empty?",
"&&",
"id",
".",
"empty?",
"fail",
"BadParametersError",
",",
"'service is required'",
"if",
"service",
".",
"empty?",
"params",
"=",
"{",
"}",
"params",
".",
"merge!",
"(",
"hash",
":",
"hash",
")",
"unless",
"hash",
".",
"empty?",
"params",
".",
"merge!",
"(",
"id",
":",
"id",
")",
"unless",
"id",
".",
"empty?",
"DataSift",
".",
"request",
"(",
":GET",
",",
"build_path",
"(",
"service",
",",
"'pylon/tags'",
",",
"@config",
")",
",",
"@config",
",",
"params",
")",
"end"
] | Query the tag hierarchy on interactions populated by a particular
recording
@param hash [String] Hash of the recording you wish to query
@param id [String] ID of the recording you wish to query
@param service [String] The PYLON service to make this API call against
@return [Object] API reponse object | [
"Query",
"the",
"tag",
"hierarchy",
"on",
"interactions",
"populated",
"by",
"a",
"particular",
"recording"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/pylon.rb#L181-L190 | train |
datasift/datasift-ruby | lib/pylon.rb | DataSift.Pylon.sample | def sample(hash = '', count = nil, start_time = nil, end_time = nil, filter = '', id = '', service = 'facebook')
fail BadParametersError, 'hash or id is required' if hash.empty? && id.empty?
fail BadParametersError, 'service is required' if service.empty?
params = {}
params.merge!(hash: hash) unless hash.empty?
params.merge!(id: id) unless id.empty?
params.merge!(count: count) unless count.nil?
params.merge!(start_time: start_time) unless start_time.nil?
params.merge!(end_time: end_time) unless end_time.nil?
if filter.empty?
DataSift.request(:GET, build_path(service, 'pylon/sample', @config), @config, params)
else
params.merge!(filter: filter)
DataSift.request(:POST, build_path(service, 'pylon/sample', @config), @config, params)
end
end | ruby | def sample(hash = '', count = nil, start_time = nil, end_time = nil, filter = '', id = '', service = 'facebook')
fail BadParametersError, 'hash or id is required' if hash.empty? && id.empty?
fail BadParametersError, 'service is required' if service.empty?
params = {}
params.merge!(hash: hash) unless hash.empty?
params.merge!(id: id) unless id.empty?
params.merge!(count: count) unless count.nil?
params.merge!(start_time: start_time) unless start_time.nil?
params.merge!(end_time: end_time) unless end_time.nil?
if filter.empty?
DataSift.request(:GET, build_path(service, 'pylon/sample', @config), @config, params)
else
params.merge!(filter: filter)
DataSift.request(:POST, build_path(service, 'pylon/sample', @config), @config, params)
end
end | [
"def",
"sample",
"(",
"hash",
"=",
"''",
",",
"count",
"=",
"nil",
",",
"start_time",
"=",
"nil",
",",
"end_time",
"=",
"nil",
",",
"filter",
"=",
"''",
",",
"id",
"=",
"''",
",",
"service",
"=",
"'facebook'",
")",
"fail",
"BadParametersError",
",",
"'hash or id is required'",
"if",
"hash",
".",
"empty?",
"&&",
"id",
".",
"empty?",
"fail",
"BadParametersError",
",",
"'service is required'",
"if",
"service",
".",
"empty?",
"params",
"=",
"{",
"}",
"params",
".",
"merge!",
"(",
"hash",
":",
"hash",
")",
"unless",
"hash",
".",
"empty?",
"params",
".",
"merge!",
"(",
"id",
":",
"id",
")",
"unless",
"id",
".",
"empty?",
"params",
".",
"merge!",
"(",
"count",
":",
"count",
")",
"unless",
"count",
".",
"nil?",
"params",
".",
"merge!",
"(",
"start_time",
":",
"start_time",
")",
"unless",
"start_time",
".",
"nil?",
"params",
".",
"merge!",
"(",
"end_time",
":",
"end_time",
")",
"unless",
"end_time",
".",
"nil?",
"if",
"filter",
".",
"empty?",
"DataSift",
".",
"request",
"(",
":GET",
",",
"build_path",
"(",
"service",
",",
"'pylon/sample'",
",",
"@config",
")",
",",
"@config",
",",
"params",
")",
"else",
"params",
".",
"merge!",
"(",
"filter",
":",
"filter",
")",
"DataSift",
".",
"request",
"(",
":POST",
",",
"build_path",
"(",
"service",
",",
"'pylon/sample'",
",",
"@config",
")",
",",
"@config",
",",
"params",
")",
"end",
"end"
] | Hit the PYLON Sample endpoint to pull public sample data from a PYLON recording
@param hash [String] The CSDL hash that identifies the recording you want to sample
@param count [Integer] Optional number of public interactions you wish to receive
@param start_time [Integer] Optional start timestamp for filtering by date
@param end_time [Integer] Optional end timestamp for filtering by date
@param filter [String] Optional PYLON CSDL for a query filter
@param id [String] ID of the recording you wish to sample
@param service [String] The PYLON service to make this API call against
@return [Object] API reponse object | [
"Hit",
"the",
"PYLON",
"Sample",
"endpoint",
"to",
"pull",
"public",
"sample",
"data",
"from",
"a",
"PYLON",
"recording"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/pylon.rb#L202-L219 | train |
datasift/datasift-ruby | lib/pylon.rb | DataSift.Pylon.reference | def reference(service:, slug: '', **opts)
params = {}
params[:per_page] = opts[:per_page] if opts.key?(:per_page)
params[:page] = opts[:page] if opts.key?(:page)
DataSift.request(:GET, "pylon/#{service}/reference/#{slug}", @config, params)
end | ruby | def reference(service:, slug: '', **opts)
params = {}
params[:per_page] = opts[:per_page] if opts.key?(:per_page)
params[:page] = opts[:page] if opts.key?(:page)
DataSift.request(:GET, "pylon/#{service}/reference/#{slug}", @config, params)
end | [
"def",
"reference",
"(",
"service",
":",
",",
"slug",
":",
"''",
",",
"**",
"opts",
")",
"params",
"=",
"{",
"}",
"params",
"[",
":per_page",
"]",
"=",
"opts",
"[",
":per_page",
"]",
"if",
"opts",
".",
"key?",
"(",
":per_page",
")",
"params",
"[",
":page",
"]",
"=",
"opts",
"[",
":page",
"]",
"if",
"opts",
".",
"key?",
"(",
":page",
")",
"DataSift",
".",
"request",
"(",
":GET",
",",
"\"pylon/#{service}/reference/#{slug}\"",
",",
"@config",
",",
"params",
")",
"end"
] | Hit the PYLON Reference endpoint to expose reference data sets
@param service [String] The PYLON service to make this API call against
@param slug [String] Optional slug of the reference data set you would like to explore
**opts
@param per_page [Integer] (Optional) How many data sets should be returned per page of results
@param page [Integer] (Optional) Which page of results to return | [
"Hit",
"the",
"PYLON",
"Reference",
"endpoint",
"to",
"expose",
"reference",
"data",
"sets"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/pylon.rb#L228-L234 | train |
knaveofdiamonds/tealeaves | lib/tealeaves/forecast.rb | TeaLeaves.Forecast.errors | def errors
@errors ||= @time_series.zip(one_step_ahead_forecasts).map do |(observation, forecast)|
forecast - observation if forecast && observation
end
end | ruby | def errors
@errors ||= @time_series.zip(one_step_ahead_forecasts).map do |(observation, forecast)|
forecast - observation if forecast && observation
end
end | [
"def",
"errors",
"@errors",
"||=",
"@time_series",
".",
"zip",
"(",
"one_step_ahead_forecasts",
")",
".",
"map",
"do",
"|",
"(",
"observation",
",",
"forecast",
")",
"|",
"forecast",
"-",
"observation",
"if",
"forecast",
"&&",
"observation",
"end",
"end"
] | Returns the errors between the observed values and the one step
ahead forecasts. | [
"Returns",
"the",
"errors",
"between",
"the",
"observed",
"values",
"and",
"the",
"one",
"step",
"ahead",
"forecasts",
"."
] | 226d61cbb5cfc61a16ae84679e261eebf9895358 | https://github.com/knaveofdiamonds/tealeaves/blob/226d61cbb5cfc61a16ae84679e261eebf9895358/lib/tealeaves/forecast.rb#L10-L14 | train |
factore/tenon | app/helpers/tenon/tenon_helper.rb | Tenon.TenonHelper.action_link | def action_link(title, link, icon, options = {})
icon_tag = content_tag(:i, '', class: "fa fa-#{icon} fa-fw")
default_options = { title: title, data: { tooltip: title } }
link_to icon_tag, link, default_options.deep_merge(options)
end | ruby | def action_link(title, link, icon, options = {})
icon_tag = content_tag(:i, '', class: "fa fa-#{icon} fa-fw")
default_options = { title: title, data: { tooltip: title } }
link_to icon_tag, link, default_options.deep_merge(options)
end | [
"def",
"action_link",
"(",
"title",
",",
"link",
",",
"icon",
",",
"options",
"=",
"{",
"}",
")",
"icon_tag",
"=",
"content_tag",
"(",
":i",
",",
"''",
",",
"class",
":",
"\"fa fa-#{icon} fa-fw\"",
")",
"default_options",
"=",
"{",
"title",
":",
"title",
",",
"data",
":",
"{",
"tooltip",
":",
"title",
"}",
"}",
"link_to",
"icon_tag",
",",
"link",
",",
"default_options",
".",
"deep_merge",
"(",
"options",
")",
"end"
] | default tenon action link | [
"default",
"tenon",
"action",
"link"
] | 49907830c00524853d087566f60951b8b6a9aedf | https://github.com/factore/tenon/blob/49907830c00524853d087566f60951b8b6a9aedf/app/helpers/tenon/tenon_helper.rb#L15-L19 | train |
factore/tenon | app/helpers/tenon/tenon_helper.rb | Tenon.TenonHelper.toggle_link | def toggle_link(object, field, link, true_values, false_values)
state = object.send(field)
icon = state ? true_values[0] : false_values[0]
tooltip = state ? true_values[1] : false_values[1]
data = {
trueicon: true_values[0],
falseicon: false_values[0],
truetooltip: true_values[1],
falsetooltip: false_values[1]
}
action_link tooltip, link, icon, class: "toggle #{field} #{state}", data: data
end | ruby | def toggle_link(object, field, link, true_values, false_values)
state = object.send(field)
icon = state ? true_values[0] : false_values[0]
tooltip = state ? true_values[1] : false_values[1]
data = {
trueicon: true_values[0],
falseicon: false_values[0],
truetooltip: true_values[1],
falsetooltip: false_values[1]
}
action_link tooltip, link, icon, class: "toggle #{field} #{state}", data: data
end | [
"def",
"toggle_link",
"(",
"object",
",",
"field",
",",
"link",
",",
"true_values",
",",
"false_values",
")",
"state",
"=",
"object",
".",
"send",
"(",
"field",
")",
"icon",
"=",
"state",
"?",
"true_values",
"[",
"0",
"]",
":",
"false_values",
"[",
"0",
"]",
"tooltip",
"=",
"state",
"?",
"true_values",
"[",
"1",
"]",
":",
"false_values",
"[",
"1",
"]",
"data",
"=",
"{",
"trueicon",
":",
"true_values",
"[",
"0",
"]",
",",
"falseicon",
":",
"false_values",
"[",
"0",
"]",
",",
"truetooltip",
":",
"true_values",
"[",
"1",
"]",
",",
"falsetooltip",
":",
"false_values",
"[",
"1",
"]",
"}",
"action_link",
"tooltip",
",",
"link",
",",
"icon",
",",
"class",
":",
"\"toggle #{field} #{state}\"",
",",
"data",
":",
"data",
"end"
] | extention of action_link for boolean toggles | [
"extention",
"of",
"action_link",
"for",
"boolean",
"toggles"
] | 49907830c00524853d087566f60951b8b6a9aedf | https://github.com/factore/tenon/blob/49907830c00524853d087566f60951b8b6a9aedf/app/helpers/tenon/tenon_helper.rb#L22-L33 | train |
factore/tenon | app/helpers/tenon/tenon_helper.rb | Tenon.TenonHelper.edit_link | def edit_link(obj, options = {})
if policy(obj).edit?
url = polymorphic_url([:edit] + Array(obj))
action_link('Edit', url, 'pencil', options)
end
end | ruby | def edit_link(obj, options = {})
if policy(obj).edit?
url = polymorphic_url([:edit] + Array(obj))
action_link('Edit', url, 'pencil', options)
end
end | [
"def",
"edit_link",
"(",
"obj",
",",
"options",
"=",
"{",
"}",
")",
"if",
"policy",
"(",
"obj",
")",
".",
"edit?",
"url",
"=",
"polymorphic_url",
"(",
"[",
":edit",
"]",
"+",
"Array",
"(",
"obj",
")",
")",
"action_link",
"(",
"'Edit'",
",",
"url",
",",
"'pencil'",
",",
"options",
")",
"end",
"end"
] | default tenon edit link | [
"default",
"tenon",
"edit",
"link"
] | 49907830c00524853d087566f60951b8b6a9aedf | https://github.com/factore/tenon/blob/49907830c00524853d087566f60951b8b6a9aedf/app/helpers/tenon/tenon_helper.rb#L36-L41 | train |
factore/tenon | app/helpers/tenon/tenon_helper.rb | Tenon.TenonHelper.delete_link | def delete_link(obj, options = {})
if policy(obj).destroy?
default_options = { data: {
confirm: 'Are you sure? There is no undo for this!',
tooltip: 'Delete',
method: 'Delete',
remote: 'true'
} }
url = polymorphic_url(obj)
action_link('Delete', url, 'trash-o', default_options.deep_merge(options))
end
end | ruby | def delete_link(obj, options = {})
if policy(obj).destroy?
default_options = { data: {
confirm: 'Are you sure? There is no undo for this!',
tooltip: 'Delete',
method: 'Delete',
remote: 'true'
} }
url = polymorphic_url(obj)
action_link('Delete', url, 'trash-o', default_options.deep_merge(options))
end
end | [
"def",
"delete_link",
"(",
"obj",
",",
"options",
"=",
"{",
"}",
")",
"if",
"policy",
"(",
"obj",
")",
".",
"destroy?",
"default_options",
"=",
"{",
"data",
":",
"{",
"confirm",
":",
"'Are you sure? There is no undo for this!'",
",",
"tooltip",
":",
"'Delete'",
",",
"method",
":",
"'Delete'",
",",
"remote",
":",
"'true'",
"}",
"}",
"url",
"=",
"polymorphic_url",
"(",
"obj",
")",
"action_link",
"(",
"'Delete'",
",",
"url",
",",
"'trash-o'",
",",
"default_options",
".",
"deep_merge",
"(",
"options",
")",
")",
"end",
"end"
] | default tenon delete link | [
"default",
"tenon",
"delete",
"link"
] | 49907830c00524853d087566f60951b8b6a9aedf | https://github.com/factore/tenon/blob/49907830c00524853d087566f60951b8b6a9aedf/app/helpers/tenon/tenon_helper.rb#L44-L55 | train |
npolar/argos-ruby | lib/argos/soap.rb | Argos.Soap._call_xml_operation | def _call_xml_operation(op_sym, body, extract=nil)
@operation = _operation(op_sym)
@operation.body = body
@response = operation.call
# Check for http errors?
# Handle faults (before extracting data)
_envelope.xpath("soap:Body/soap:Fault", namespaces).each do | fault |
raise Exception, fault.to_s
end
# Extract data
if extract.respond_to?(:call)
@xml = extract.call(response)
else
@xml = response.raw
end
# Handle errors
ng = Nokogiri.XML(xml)
ng.xpath("/data/errors/error").each do | error |
if error.key?("code")
case error["code"].to_i
when 4
raise NodataException
end
#<error code="2">max response reached</error>
#<error code="3">authentification error</error>
#<error code="9">start date upper than end date</error>
else
raise Exception, error
end
end
# Validation - only :getXml
if [:getXml].include? op_sym
# Validation against getXSD schema does not work: ["Element 'data': No matching global declaration available for the validation root."]
# See https://github.com/npolar/argos-ruby/commit/219e4b3761e5265f8f9e8b924bcfc23607902428 for the fix
schema = Nokogiri::XML::Schema(File.read("#{__dir__}/_xsd/argos-data.xsd"))
v = schema.validate(ng)
if v.any?
log.debug "#{v.size} errors: #{v.map{|v|v.to_s}.uniq.to_json}"
end
end
# Convert XML to Hash
nori = Nori.new
nori.parse(xml)
end | ruby | def _call_xml_operation(op_sym, body, extract=nil)
@operation = _operation(op_sym)
@operation.body = body
@response = operation.call
# Check for http errors?
# Handle faults (before extracting data)
_envelope.xpath("soap:Body/soap:Fault", namespaces).each do | fault |
raise Exception, fault.to_s
end
# Extract data
if extract.respond_to?(:call)
@xml = extract.call(response)
else
@xml = response.raw
end
# Handle errors
ng = Nokogiri.XML(xml)
ng.xpath("/data/errors/error").each do | error |
if error.key?("code")
case error["code"].to_i
when 4
raise NodataException
end
#<error code="2">max response reached</error>
#<error code="3">authentification error</error>
#<error code="9">start date upper than end date</error>
else
raise Exception, error
end
end
# Validation - only :getXml
if [:getXml].include? op_sym
# Validation against getXSD schema does not work: ["Element 'data': No matching global declaration available for the validation root."]
# See https://github.com/npolar/argos-ruby/commit/219e4b3761e5265f8f9e8b924bcfc23607902428 for the fix
schema = Nokogiri::XML::Schema(File.read("#{__dir__}/_xsd/argos-data.xsd"))
v = schema.validate(ng)
if v.any?
log.debug "#{v.size} errors: #{v.map{|v|v.to_s}.uniq.to_json}"
end
end
# Convert XML to Hash
nori = Nori.new
nori.parse(xml)
end | [
"def",
"_call_xml_operation",
"(",
"op_sym",
",",
"body",
",",
"extract",
"=",
"nil",
")",
"@operation",
"=",
"_operation",
"(",
"op_sym",
")",
"@operation",
".",
"body",
"=",
"body",
"@response",
"=",
"operation",
".",
"call",
"_envelope",
".",
"xpath",
"(",
"\"soap:Body/soap:Fault\"",
",",
"namespaces",
")",
".",
"each",
"do",
"|",
"fault",
"|",
"raise",
"Exception",
",",
"fault",
".",
"to_s",
"end",
"if",
"extract",
".",
"respond_to?",
"(",
":call",
")",
"@xml",
"=",
"extract",
".",
"call",
"(",
"response",
")",
"else",
"@xml",
"=",
"response",
".",
"raw",
"end",
"ng",
"=",
"Nokogiri",
".",
"XML",
"(",
"xml",
")",
"ng",
".",
"xpath",
"(",
"\"/data/errors/error\"",
")",
".",
"each",
"do",
"|",
"error",
"|",
"if",
"error",
".",
"key?",
"(",
"\"code\"",
")",
"case",
"error",
"[",
"\"code\"",
"]",
".",
"to_i",
"when",
"4",
"raise",
"NodataException",
"end",
"else",
"raise",
"Exception",
",",
"error",
"end",
"end",
"if",
"[",
":getXml",
"]",
".",
"include?",
"op_sym",
"schema",
"=",
"Nokogiri",
"::",
"XML",
"::",
"Schema",
"(",
"File",
".",
"read",
"(",
"\"#{__dir__}/_xsd/argos-data.xsd\"",
")",
")",
"v",
"=",
"schema",
".",
"validate",
"(",
"ng",
")",
"if",
"v",
".",
"any?",
"log",
".",
"debug",
"\"#{v.size} errors: #{v.map{|v|v.to_s}.uniq.to_json}\"",
"end",
"end",
"nori",
"=",
"Nori",
".",
"new",
"nori",
".",
"parse",
"(",
"xml",
")",
"end"
] | Build and call @operation, set @response, @request, and @xml
@raise on faults
@return [Hash] | [
"Build",
"and",
"call"
] | d352087dba54764a43c8ad3dbae0a91102ecbfa3 | https://github.com/npolar/argos-ruby/blob/d352087dba54764a43c8ad3dbae0a91102ecbfa3/lib/argos/soap.rb#L331-L382 | train |
npolar/argos-ruby | lib/argos/soap.rb | Argos.Soap._extract_motm | def _extract_motm
lambda {|response|
# Scan for MOTM signature --uuid:*
if response.raw =~ (/^(--[\w:-]+)--$/)
# Get the last message, which is -2 because of the trailing --
xml = response.raw.split($1)[-2].strip
# Get rid of HTTP headers
if xml =~ /\r\n\r\n[<]/
xml = xml.split(/\r\n\r\n/)[-1]
end
else
raise "Cannot parse MOTM"
end
}
end | ruby | def _extract_motm
lambda {|response|
# Scan for MOTM signature --uuid:*
if response.raw =~ (/^(--[\w:-]+)--$/)
# Get the last message, which is -2 because of the trailing --
xml = response.raw.split($1)[-2].strip
# Get rid of HTTP headers
if xml =~ /\r\n\r\n[<]/
xml = xml.split(/\r\n\r\n/)[-1]
end
else
raise "Cannot parse MOTM"
end
}
end | [
"def",
"_extract_motm",
"lambda",
"{",
"|",
"response",
"|",
"if",
"response",
".",
"raw",
"=~",
"(",
"/",
"\\w",
"/",
")",
"xml",
"=",
"response",
".",
"raw",
".",
"split",
"(",
"$1",
")",
"[",
"-",
"2",
"]",
".",
"strip",
"if",
"xml",
"=~",
"/",
"\\r",
"\\n",
"\\r",
"\\n",
"/",
"xml",
"=",
"xml",
".",
"split",
"(",
"/",
"\\r",
"\\n",
"\\r",
"\\n",
"/",
")",
"[",
"-",
"1",
"]",
"end",
"else",
"raise",
"\"Cannot parse MOTM\"",
"end",
"}",
"end"
] | This is proof-of-concept quality code.
@todo Need to extract boundary and start markers from Content-Type header:
Content-Type: multipart/related; type="application/xop+xml"; boundary="uuid:14b8db9f-a393-4786-be3f-f0f7b12e14a2"; start="<[email protected]>"; start-info="application/soap+xml"
@return [String] | [
"This",
"is",
"proof",
"-",
"of",
"-",
"concept",
"quality",
"code",
"."
] | d352087dba54764a43c8ad3dbae0a91102ecbfa3 | https://github.com/npolar/argos-ruby/blob/d352087dba54764a43c8ad3dbae0a91102ecbfa3/lib/argos/soap.rb#L396-L412 | train |
leoniv/ass_launcher | lib/ass_launcher/api.rb | AssLauncher.Api.ole | def ole(type, requiremet = '>= 0')
AssLauncher::Enterprise::Ole.ole_client(type).new(requiremet)
end | ruby | def ole(type, requiremet = '>= 0')
AssLauncher::Enterprise::Ole.ole_client(type).new(requiremet)
end | [
"def",
"ole",
"(",
"type",
",",
"requiremet",
"=",
"'>= 0'",
")",
"AssLauncher",
"::",
"Enterprise",
"::",
"Ole",
".",
"ole_client",
"(",
"type",
")",
".",
"new",
"(",
"requiremet",
")",
"end"
] | Return 1C ole client suitable class instance
@param type [Symbol] type of 1C ole client.
See {Enterprise::Ole::OLE_CLIENT_TYPES}
@param requiremet [String, Gem::Version::Requirement] require version spec
@raise [ArgumentError] if invalid +type+ given | [
"Return",
"1C",
"ole",
"client",
"suitable",
"class",
"instance"
] | f2354541560e214856039e7ab95ebd0d4314a51b | https://github.com/leoniv/ass_launcher/blob/f2354541560e214856039e7ab95ebd0d4314a51b/lib/ass_launcher/api.rb#L118-L120 | train |
zhimin/rwebspec | lib/rwebspec-common/popup.rb | RWebSpec.Popup.check_for_security_alerts | def check_for_security_alerts
autoit = WIN32OLE.new('AutoItX3.Control')
loop do
["Security Alert", "Security Information"].each do |win_title|
ret = autoit.WinWait(win_title, '', 1)
if (ret==1) then
autoit.Send('{Y}')
end
end
sleep(3)
end
end | ruby | def check_for_security_alerts
autoit = WIN32OLE.new('AutoItX3.Control')
loop do
["Security Alert", "Security Information"].each do |win_title|
ret = autoit.WinWait(win_title, '', 1)
if (ret==1) then
autoit.Send('{Y}')
end
end
sleep(3)
end
end | [
"def",
"check_for_security_alerts",
"autoit",
"=",
"WIN32OLE",
".",
"new",
"(",
"'AutoItX3.Control'",
")",
"loop",
"do",
"[",
"\"Security Alert\"",
",",
"\"Security Information\"",
"]",
".",
"each",
"do",
"|",
"win_title",
"|",
"ret",
"=",
"autoit",
".",
"WinWait",
"(",
"win_title",
",",
"''",
",",
"1",
")",
"if",
"(",
"ret",
"==",
"1",
")",
"then",
"autoit",
".",
"Send",
"(",
"'{Y}'",
")",
"end",
"end",
"sleep",
"(",
"3",
")",
"end",
"end"
] | Check for "Security Information" and "Security Alert" alert popup, click 'Yes'
Usage: For individual test suite
before(:all) do
$popup = Thread.new { check_for_alerts }
open_in_browser
...
end
after(:all) do
close_browser
Thread.kill($popup)
end
or for all tests,
$popup = Thread.new { check_for_alerts }
at_exit{ Thread.kill($popup) } | [
"Check",
"for",
"Security",
"Information",
"and",
"Security",
"Alert",
"alert",
"popup",
"click",
"Yes"
] | aafccee2ba66d17d591d04210067035feaf2f892 | https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-common/popup.rb#L50-L61 | train |
zhimin/rwebspec | lib/rwebspec-common/popup.rb | RWebSpec.Popup.start_checking_js_dialog | def start_checking_js_dialog(button = "OK", wait_time = 3)
w = WinClicker.new
longName = File.expand_path(File.dirname(__FILE__)).gsub("/", "\\" )
shortName = w.getShortFileName(longName)
c = "start ruby #{shortName}\\clickJSDialog.rb #{button} #{wait_time} "
w.winsystem(c)
w = nil
end | ruby | def start_checking_js_dialog(button = "OK", wait_time = 3)
w = WinClicker.new
longName = File.expand_path(File.dirname(__FILE__)).gsub("/", "\\" )
shortName = w.getShortFileName(longName)
c = "start ruby #{shortName}\\clickJSDialog.rb #{button} #{wait_time} "
w.winsystem(c)
w = nil
end | [
"def",
"start_checking_js_dialog",
"(",
"button",
"=",
"\"OK\"",
",",
"wait_time",
"=",
"3",
")",
"w",
"=",
"WinClicker",
".",
"new",
"longName",
"=",
"File",
".",
"expand_path",
"(",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
")",
".",
"gsub",
"(",
"\"/\"",
",",
"\"\\\\\"",
")",
"shortName",
"=",
"w",
".",
"getShortFileName",
"(",
"longName",
")",
"c",
"=",
"\"start ruby #{shortName}\\\\clickJSDialog.rb #{button} #{wait_time} \"",
"w",
".",
"winsystem",
"(",
"c",
")",
"w",
"=",
"nil",
"end"
] | Start a background process to click the button on a javascript popup window | [
"Start",
"a",
"background",
"process",
"to",
"click",
"the",
"button",
"on",
"a",
"javascript",
"popup",
"window"
] | aafccee2ba66d17d591d04210067035feaf2f892 | https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-common/popup.rb#L123-L130 | train |
FTB-Gamepedia/MediaWiki-Butt-Ruby | lib/mediawiki/butt.rb | MediaWiki.Butt.query | def query(params, base_return = [])
params[:action] = 'query'
params[:continue] = ''
loop do
result = post(params)
yield(base_return, result['query']) if result.key?('query')
break unless @use_continuation
break unless result.key?('continue')
continue = result['continue']
continue.each do |key, val|
params[key.to_sym] = val
end
end
base_return
end | ruby | def query(params, base_return = [])
params[:action] = 'query'
params[:continue] = ''
loop do
result = post(params)
yield(base_return, result['query']) if result.key?('query')
break unless @use_continuation
break unless result.key?('continue')
continue = result['continue']
continue.each do |key, val|
params[key.to_sym] = val
end
end
base_return
end | [
"def",
"query",
"(",
"params",
",",
"base_return",
"=",
"[",
"]",
")",
"params",
"[",
":action",
"]",
"=",
"'query'",
"params",
"[",
":continue",
"]",
"=",
"''",
"loop",
"do",
"result",
"=",
"post",
"(",
"params",
")",
"yield",
"(",
"base_return",
",",
"result",
"[",
"'query'",
"]",
")",
"if",
"result",
".",
"key?",
"(",
"'query'",
")",
"break",
"unless",
"@use_continuation",
"break",
"unless",
"result",
".",
"key?",
"(",
"'continue'",
")",
"continue",
"=",
"result",
"[",
"'continue'",
"]",
"continue",
".",
"each",
"do",
"|",
"key",
",",
"val",
"|",
"params",
"[",
"key",
".",
"to_sym",
"]",
"=",
"val",
"end",
"end",
"base_return",
"end"
] | Performs a Mediawiki API query and provides the response, dealing with continuation as necessary.
@param params [Hash] A hash containing MediaWiki API parameters.
@param base_return [Any] The return value to start with. Defaults to an empty array.
@yield [base_return, query] Provides the value provided to the base_return parameter, and the value in the
'query' key in the API response. See the API documentation for more information on this. If the base_return
value is modified in the block, its modifications will persist across each continuation loop.
@return [Any] The base_return value as modified by the yielded block. | [
"Performs",
"a",
"Mediawiki",
"API",
"query",
"and",
"provides",
"the",
"response",
"dealing",
"with",
"continuation",
"as",
"necessary",
"."
] | d71c5dfdf9d349d025e1c3534286ce116777eaa4 | https://github.com/FTB-Gamepedia/MediaWiki-Butt-Ruby/blob/d71c5dfdf9d349d025e1c3534286ce116777eaa4/lib/mediawiki/butt.rb#L93-L109 | train |
FTB-Gamepedia/MediaWiki-Butt-Ruby | lib/mediawiki/butt.rb | MediaWiki.Butt.query_ary_irrelevant_keys | def query_ary_irrelevant_keys(params, base_response_key, property_key)
query(params) do |return_val, query|
return_val.concat(query[base_response_key].values.collect { |obj| obj[property_key] })
end
end | ruby | def query_ary_irrelevant_keys(params, base_response_key, property_key)
query(params) do |return_val, query|
return_val.concat(query[base_response_key].values.collect { |obj| obj[property_key] })
end
end | [
"def",
"query_ary_irrelevant_keys",
"(",
"params",
",",
"base_response_key",
",",
"property_key",
")",
"query",
"(",
"params",
")",
"do",
"|",
"return_val",
",",
"query",
"|",
"return_val",
".",
"concat",
"(",
"query",
"[",
"base_response_key",
"]",
".",
"values",
".",
"collect",
"{",
"|",
"obj",
"|",
"obj",
"[",
"property_key",
"]",
"}",
")",
"end",
"end"
] | Helper method for query methods that return a two-dimensional hashes in which the keys are not relevant to the
returning value. In most cases this key is a redundant page or revision ID that is also available in the object.
@param (see #query_ary) | [
"Helper",
"method",
"for",
"query",
"methods",
"that",
"return",
"a",
"two",
"-",
"dimensional",
"hashes",
"in",
"which",
"the",
"keys",
"are",
"not",
"relevant",
"to",
"the",
"returning",
"value",
".",
"In",
"most",
"cases",
"this",
"key",
"is",
"a",
"redundant",
"page",
"or",
"revision",
"ID",
"that",
"is",
"also",
"available",
"in",
"the",
"object",
"."
] | d71c5dfdf9d349d025e1c3534286ce116777eaa4 | https://github.com/FTB-Gamepedia/MediaWiki-Butt-Ruby/blob/d71c5dfdf9d349d025e1c3534286ce116777eaa4/lib/mediawiki/butt.rb#L114-L118 | train |
FTB-Gamepedia/MediaWiki-Butt-Ruby | lib/mediawiki/butt.rb | MediaWiki.Butt.query_ary | def query_ary(params, base_response_key, property_key)
query(params) do |return_val, query|
return_val.concat(query[base_response_key].collect { |obj| obj[property_key] })
end
end | ruby | def query_ary(params, base_response_key, property_key)
query(params) do |return_val, query|
return_val.concat(query[base_response_key].collect { |obj| obj[property_key] })
end
end | [
"def",
"query_ary",
"(",
"params",
",",
"base_response_key",
",",
"property_key",
")",
"query",
"(",
"params",
")",
"do",
"|",
"return_val",
",",
"query",
"|",
"return_val",
".",
"concat",
"(",
"query",
"[",
"base_response_key",
"]",
".",
"collect",
"{",
"|",
"obj",
"|",
"obj",
"[",
"property_key",
"]",
"}",
")",
"end",
"end"
] | Helper method for query methods that return an array built from the query objects.
@param params [Hash] A hash containing MediaWiki API parameters.
@param base_response_key [String] The key inside the "query" object to collect.
@param property_key [String] The key inside the object (under the base_response_key) to collect. | [
"Helper",
"method",
"for",
"query",
"methods",
"that",
"return",
"an",
"array",
"built",
"from",
"the",
"query",
"objects",
"."
] | d71c5dfdf9d349d025e1c3534286ce116777eaa4 | https://github.com/FTB-Gamepedia/MediaWiki-Butt-Ruby/blob/d71c5dfdf9d349d025e1c3534286ce116777eaa4/lib/mediawiki/butt.rb#L124-L128 | train |
FTB-Gamepedia/MediaWiki-Butt-Ruby | lib/mediawiki/butt.rb | MediaWiki.Butt.get_limited | def get_limited(integer, max_user = 500, max_bot = 5000)
if integer.is_a?(String)
return integer if integer == 'max'
return 500
end
return integer if integer <= max_user
if user_bot?
integer > max_bot ? max_bot : integer
else
max_user
end
end | ruby | def get_limited(integer, max_user = 500, max_bot = 5000)
if integer.is_a?(String)
return integer if integer == 'max'
return 500
end
return integer if integer <= max_user
if user_bot?
integer > max_bot ? max_bot : integer
else
max_user
end
end | [
"def",
"get_limited",
"(",
"integer",
",",
"max_user",
"=",
"500",
",",
"max_bot",
"=",
"5000",
")",
"if",
"integer",
".",
"is_a?",
"(",
"String",
")",
"return",
"integer",
"if",
"integer",
"==",
"'max'",
"return",
"500",
"end",
"return",
"integer",
"if",
"integer",
"<=",
"max_user",
"if",
"user_bot?",
"integer",
">",
"max_bot",
"?",
"max_bot",
":",
"integer",
"else",
"max_user",
"end",
"end"
] | Gets the limited version of the integer, to ensure nobody provides an int that is too large.
@param integer [Fixnum] The number to limit.
@param max_user [Fixnum] The maximum limit for normal users.
@param max_bot [Fixnum] The maximum limit for bot users.
@since 0.8.0
@return [Fixnum] The capped number. | [
"Gets",
"the",
"limited",
"version",
"of",
"the",
"integer",
"to",
"ensure",
"nobody",
"provides",
"an",
"int",
"that",
"is",
"too",
"large",
"."
] | d71c5dfdf9d349d025e1c3534286ce116777eaa4 | https://github.com/FTB-Gamepedia/MediaWiki-Butt-Ruby/blob/d71c5dfdf9d349d025e1c3534286ce116777eaa4/lib/mediawiki/butt.rb#L160-L172 | train |
szTheory/meta_presenter | lib/meta_presenter/builder.rb | MetaPresenter.Builder.ancestors_until | def ancestors_until(until_class)
# trim down the list
ancestors_list = all_ancestors[0..all_ancestors.index(until_class)]
# map to the fully qualified class name
ancestors_list.map { |klass| yield(klass) }
end | ruby | def ancestors_until(until_class)
# trim down the list
ancestors_list = all_ancestors[0..all_ancestors.index(until_class)]
# map to the fully qualified class name
ancestors_list.map { |klass| yield(klass) }
end | [
"def",
"ancestors_until",
"(",
"until_class",
")",
"ancestors_list",
"=",
"all_ancestors",
"[",
"0",
"..",
"all_ancestors",
".",
"index",
"(",
"until_class",
")",
"]",
"ancestors_list",
".",
"map",
"{",
"|",
"klass",
"|",
"yield",
"(",
"klass",
")",
"}",
"end"
] | The list of ancestors is very long.
Trim it down to just the length of the class we are looking for.
Takes an optional block method to transform the result
with a map operation | [
"The",
"list",
"of",
"ancestors",
"is",
"very",
"long",
".",
"Trim",
"it",
"down",
"to",
"just",
"the",
"length",
"of",
"the",
"class",
"we",
"are",
"looking",
"for",
"."
] | 478787ebff72beaef4c4ce6776f050342ea6d221 | https://github.com/szTheory/meta_presenter/blob/478787ebff72beaef4c4ce6776f050342ea6d221/lib/meta_presenter/builder.rb#L121-L127 | train |
rkotov93/rails_rate_limiter | lib/rails_rate_limiter.rb | RailsRateLimiter.ClassMethods.rate_limit | def rate_limit(options = {}, &block)
raise Error, 'Handling block was not provided' unless block_given?
# Separate out options related only to rate limiting
strategy = (options.delete(:strategy) || 'sliding_window_log').to_s
limit = options.delete(:limit) || 100
per = options.delete(:per) || 3600
pattern = options.delete(:pattern)
client = options.delete(:client)
before_action(options) do
check_rate_limits(strategy, limit, per, pattern, client, block)
end
end | ruby | def rate_limit(options = {}, &block)
raise Error, 'Handling block was not provided' unless block_given?
# Separate out options related only to rate limiting
strategy = (options.delete(:strategy) || 'sliding_window_log').to_s
limit = options.delete(:limit) || 100
per = options.delete(:per) || 3600
pattern = options.delete(:pattern)
client = options.delete(:client)
before_action(options) do
check_rate_limits(strategy, limit, per, pattern, client, block)
end
end | [
"def",
"rate_limit",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"raise",
"Error",
",",
"'Handling block was not provided'",
"unless",
"block_given?",
"strategy",
"=",
"(",
"options",
".",
"delete",
"(",
":strategy",
")",
"||",
"'sliding_window_log'",
")",
".",
"to_s",
"limit",
"=",
"options",
".",
"delete",
"(",
":limit",
")",
"||",
"100",
"per",
"=",
"options",
".",
"delete",
"(",
":per",
")",
"||",
"3600",
"pattern",
"=",
"options",
".",
"delete",
"(",
":pattern",
")",
"client",
"=",
"options",
".",
"delete",
"(",
":client",
")",
"before_action",
"(",
"options",
")",
"do",
"check_rate_limits",
"(",
"strategy",
",",
"limit",
",",
"per",
",",
"pattern",
",",
"client",
",",
"block",
")",
"end",
"end"
] | Sets callback that handles rate limit exceeding. Additionally to
described options supports all the `before_action` options.
@example Renders text with time left in case of rate limit exceeding.
rate_limit limit: 100, per: 1.hour, only: :index do |info|
render plain: "Next request can be done in #{info.time_left} seconds",
status: :too_many_requests
end
@param [Hash] options
@option options [Symbol] :strategy Rate limiting strategy.
Default value is :sliding_window_log
@option options [Fixnum, Lambda, Proc] :limit The number of allowed
requests per time period. Default value is 100
@option options [Fixnum, Lambda, Proc] :per Time period in seconds.
Default value is 1.hour
@option options [Lambda, Proc] :pattern Can be used if you want to use
something instead of IP as cache key identifier. For example
`-> { current_user.id }`. Default value is `request.remote_ip`
@option options [Object] :cient Redis client.
Uses `Redis.new` if not specified
@yield [info] Executed if rate limit exceded. This argument is mandatory.
@yieldparam [RailsRateLimiter::Result] Represent information about
rate limiting | [
"Sets",
"callback",
"that",
"handles",
"rate",
"limit",
"exceeding",
".",
"Additionally",
"to",
"described",
"options",
"supports",
"all",
"the",
"before_action",
"options",
"."
] | dbb98c372d7a3eb09c5ad98640993442568e2e70 | https://github.com/rkotov93/rails_rate_limiter/blob/dbb98c372d7a3eb09c5ad98640993442568e2e70/lib/rails_rate_limiter.rb#L40-L53 | train |
datasift/datasift-ruby | lib/historics.rb | DataSift.Historics.prepare | def prepare(hash, start, end_time, name, sources = '', sample = 100)
params = {
:hash => hash,
:start => start,
:end => end_time,
:name => name,
:sources => sources,
:sample => sample
}
requires params
DataSift.request(:POST, 'historics/prepare', @config, params)
end | ruby | def prepare(hash, start, end_time, name, sources = '', sample = 100)
params = {
:hash => hash,
:start => start,
:end => end_time,
:name => name,
:sources => sources,
:sample => sample
}
requires params
DataSift.request(:POST, 'historics/prepare', @config, params)
end | [
"def",
"prepare",
"(",
"hash",
",",
"start",
",",
"end_time",
",",
"name",
",",
"sources",
"=",
"''",
",",
"sample",
"=",
"100",
")",
"params",
"=",
"{",
":hash",
"=>",
"hash",
",",
":start",
"=>",
"start",
",",
":end",
"=>",
"end_time",
",",
":name",
"=>",
"name",
",",
":sources",
"=>",
"sources",
",",
":sample",
"=>",
"sample",
"}",
"requires",
"params",
"DataSift",
".",
"request",
"(",
":POST",
",",
"'historics/prepare'",
",",
"@config",
",",
"params",
")",
"end"
] | Prepare a new Historics query
@param hash [String] Hash of compiled CSDL filter
@param start [Integer] Start timestamp for your Historics Query. Should be
provided as a Unix timestamp
@param end_time [Integer] End timestamp for your Historics Query. Should
be provided as a Unix timestamp
@param name [String] The name of your Historics query
@param sources [String] Comma separated list of data sources you wish to
query
@param sample [Integer] Sample size of your Historics query
@return [Object] API reponse object | [
"Prepare",
"a",
"new",
"Historics",
"query"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/historics.rb#L16-L27 | train |
datasift/datasift-ruby | lib/historics.rb | DataSift.Historics.pause | def pause(id, reason = '')
params = { :id => id }
requires params
params[:reason] = reason
DataSift.request(:PUT, 'historics/pause', @config, params)
end | ruby | def pause(id, reason = '')
params = { :id => id }
requires params
params[:reason] = reason
DataSift.request(:PUT, 'historics/pause', @config, params)
end | [
"def",
"pause",
"(",
"id",
",",
"reason",
"=",
"''",
")",
"params",
"=",
"{",
":id",
"=>",
"id",
"}",
"requires",
"params",
"params",
"[",
":reason",
"]",
"=",
"reason",
"DataSift",
".",
"request",
"(",
":PUT",
",",
"'historics/pause'",
",",
"@config",
",",
"params",
")",
"end"
] | Pause Historics query
@param id [String] ID of the Historics query you need to pause
@param reason [String] You can give a reason for pausing the query | [
"Pause",
"Historics",
"query"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/historics.rb#L33-L38 | train |
datasift/datasift-ruby | lib/historics.rb | DataSift.Historics.stop | def stop(id, reason = '')
params = { :id => id }
requires params
params[:reason] = reason
DataSift.request(:POST, 'historics/stop', @config, params)
end | ruby | def stop(id, reason = '')
params = { :id => id }
requires params
params[:reason] = reason
DataSift.request(:POST, 'historics/stop', @config, params)
end | [
"def",
"stop",
"(",
"id",
",",
"reason",
"=",
"''",
")",
"params",
"=",
"{",
":id",
"=>",
"id",
"}",
"requires",
"params",
"params",
"[",
":reason",
"]",
"=",
"reason",
"DataSift",
".",
"request",
"(",
":POST",
",",
"'historics/stop'",
",",
"@config",
",",
"params",
")",
"end"
] | Stop Historics query
@param id [String] ID of the Historics query you need to stop
@param reason [String] You can give a reason for stopping the query | [
"Stop",
"Historics",
"query"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/historics.rb#L62-L67 | train |
datasift/datasift-ruby | lib/historics.rb | DataSift.Historics.status | def status(start, end_time, sources = '')
params = { :start => start, :end => end_time, :sources => sources }
requires params
DataSift.request(:GET, 'historics/status', @config, params)
end | ruby | def status(start, end_time, sources = '')
params = { :start => start, :end => end_time, :sources => sources }
requires params
DataSift.request(:GET, 'historics/status', @config, params)
end | [
"def",
"status",
"(",
"start",
",",
"end_time",
",",
"sources",
"=",
"''",
")",
"params",
"=",
"{",
":start",
"=>",
"start",
",",
":end",
"=>",
"end_time",
",",
":sources",
"=>",
"sources",
"}",
"requires",
"params",
"DataSift",
".",
"request",
"(",
":GET",
",",
"'historics/status'",
",",
"@config",
",",
"params",
")",
"end"
] | Check the data coverage in the archive for a specified interval
@param start [Integer] Start timestamp for the period you wish to query.
Should be provided as a Unix timestamp
@param end_time [Integer] End timestamp for the period you wish to query.
Should be provided as a Unix timestamp
@param sources [String] Comma separated list of data sources you wish to
query | [
"Check",
"the",
"data",
"coverage",
"in",
"the",
"archive",
"for",
"a",
"specified",
"interval"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/historics.rb#L77-L81 | train |
datasift/datasift-ruby | lib/historics.rb | DataSift.Historics.update | def update(id, name)
params = { :id => id, :name => name }
requires params
DataSift.request(:POST, 'historics/update', @config, params)
end | ruby | def update(id, name)
params = { :id => id, :name => name }
requires params
DataSift.request(:POST, 'historics/update', @config, params)
end | [
"def",
"update",
"(",
"id",
",",
"name",
")",
"params",
"=",
"{",
":id",
"=>",
"id",
",",
":name",
"=>",
"name",
"}",
"requires",
"params",
"DataSift",
".",
"request",
"(",
":POST",
",",
"'historics/update'",
",",
"@config",
",",
"params",
")",
"end"
] | Update the name of an Historics query
@param id [String] ID of the Historics query you need to update
@param name [String] New name for the Historics query | [
"Update",
"the",
"name",
"of",
"an",
"Historics",
"query"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/historics.rb#L87-L91 | train |
datasift/datasift-ruby | lib/historics.rb | DataSift.Historics.get_by_id | def get_by_id(id, with_estimate = 1)
params = { :id => id, :with_estimate => with_estimate }
requires params
DataSift.request(:GET, 'historics/get', @config, params)
end | ruby | def get_by_id(id, with_estimate = 1)
params = { :id => id, :with_estimate => with_estimate }
requires params
DataSift.request(:GET, 'historics/get', @config, params)
end | [
"def",
"get_by_id",
"(",
"id",
",",
"with_estimate",
"=",
"1",
")",
"params",
"=",
"{",
":id",
"=>",
"id",
",",
":with_estimate",
"=>",
"with_estimate",
"}",
"requires",
"params",
"DataSift",
".",
"request",
"(",
":GET",
",",
"'historics/get'",
",",
"@config",
",",
"params",
")",
"end"
] | Get details for a given Historics query
@param id [String] ID of the Historics query you need to get
@param with_estimate [Boolean] 1 or 0 indicating whether you want to see
the estimated completion time of the Historics query | [
"Get",
"details",
"for",
"a",
"given",
"Historics",
"query"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/historics.rb#L107-L111 | train |
datasift/datasift-ruby | lib/historics.rb | DataSift.Historics.get | def get(max = 20, page = 1, with_estimate = 1)
params = { :max => max, :page => page, :with_estimate => with_estimate }
requires params
DataSift.request(:GET, 'historics/get', @config, params)
end | ruby | def get(max = 20, page = 1, with_estimate = 1)
params = { :max => max, :page => page, :with_estimate => with_estimate }
requires params
DataSift.request(:GET, 'historics/get', @config, params)
end | [
"def",
"get",
"(",
"max",
"=",
"20",
",",
"page",
"=",
"1",
",",
"with_estimate",
"=",
"1",
")",
"params",
"=",
"{",
":max",
"=>",
"max",
",",
":page",
"=>",
"page",
",",
":with_estimate",
"=>",
"with_estimate",
"}",
"requires",
"params",
"DataSift",
".",
"request",
"(",
":GET",
",",
"'historics/get'",
",",
"@config",
",",
"params",
")",
"end"
] | Get details for a list of Historics within the given page constraints
@param max [Integer] Max number of Historics you wish to return per page
@param page [Integer] Which page of results you need returned
@param with_estimate [Boolean] 1 or 0 indicating whether you want to see
the estimated completion time of the Historics query | [
"Get",
"details",
"for",
"a",
"list",
"of",
"Historics",
"within",
"the",
"given",
"page",
"constraints"
] | d724e4ff15d178f196001ea5a517a981dc56c18c | https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/historics.rb#L119-L123 | train |
azuchi/bech32rb | lib/bech32/segwit_addr.rb | Bech32.SegwitAddr.to_script_pubkey | def to_script_pubkey
v = ver == 0 ? ver : ver + 0x50
([v, prog.length].pack("CC") + prog.map{|p|[p].pack("C")}.join).unpack('H*').first
end | ruby | def to_script_pubkey
v = ver == 0 ? ver : ver + 0x50
([v, prog.length].pack("CC") + prog.map{|p|[p].pack("C")}.join).unpack('H*').first
end | [
"def",
"to_script_pubkey",
"v",
"=",
"ver",
"==",
"0",
"?",
"ver",
":",
"ver",
"+",
"0x50",
"(",
"[",
"v",
",",
"prog",
".",
"length",
"]",
".",
"pack",
"(",
"\"CC\"",
")",
"+",
"prog",
".",
"map",
"{",
"|",
"p",
"|",
"[",
"p",
"]",
".",
"pack",
"(",
"\"C\"",
")",
"}",
".",
"join",
")",
".",
"unpack",
"(",
"'H*'",
")",
".",
"first",
"end"
] | witness program
Returns segwit script pubkey which generated from witness version and witness program. | [
"witness",
"program",
"Returns",
"segwit",
"script",
"pubkey",
"which",
"generated",
"from",
"witness",
"version",
"and",
"witness",
"program",
"."
] | b4cd48193af54609afb48abc8ca45e8899710818 | https://github.com/azuchi/bech32rb/blob/b4cd48193af54609afb48abc8ca45e8899710818/lib/bech32/segwit_addr.rb#L19-L22 | train |
azuchi/bech32rb | lib/bech32/segwit_addr.rb | Bech32.SegwitAddr.script_pubkey= | def script_pubkey=(script_pubkey)
values = [script_pubkey].pack('H*').unpack("C*")
@ver = values[0] == 0 ? values[0] : values[0] - 0x50
@prog = values[2..-1]
end | ruby | def script_pubkey=(script_pubkey)
values = [script_pubkey].pack('H*').unpack("C*")
@ver = values[0] == 0 ? values[0] : values[0] - 0x50
@prog = values[2..-1]
end | [
"def",
"script_pubkey",
"=",
"(",
"script_pubkey",
")",
"values",
"=",
"[",
"script_pubkey",
"]",
".",
"pack",
"(",
"'H*'",
")",
".",
"unpack",
"(",
"\"C*\"",
")",
"@ver",
"=",
"values",
"[",
"0",
"]",
"==",
"0",
"?",
"values",
"[",
"0",
"]",
":",
"values",
"[",
"0",
"]",
"-",
"0x50",
"@prog",
"=",
"values",
"[",
"2",
"..",
"-",
"1",
"]",
"end"
] | parse script pubkey into witness version and witness program | [
"parse",
"script",
"pubkey",
"into",
"witness",
"version",
"and",
"witness",
"program"
] | b4cd48193af54609afb48abc8ca45e8899710818 | https://github.com/azuchi/bech32rb/blob/b4cd48193af54609afb48abc8ca45e8899710818/lib/bech32/segwit_addr.rb#L25-L29 | train |
johnfaucett/youtrack | lib/youtrack/resources/issue.rb | Youtrack.Issue.add_work_item_to | def add_work_item_to(issue_id, attributes={})
attributes = attributes.to_hash
attributes.symbolize_keys!
attributes[:date] ||= Date.current.iso8601
epoc_date = Date.parse(attributes[:date]).to_time.to_i * 1000
attributes[:user] ||= self.service.login
work_items = REXML::Element.new('workItems')
work_item = work_items.add_element('workItem')
work_item.add_element('author').add_attribute('login', attributes[:user])
work_item.add_element('date').add_text(epoc_date.to_s)
work_item.add_element('duration').add_text(attributes[:duration].to_s)
work_item.add_element('description').add_text(attributes[:description])
put("import/issue/#{issue_id}/workitems", body: work_items.to_s, :headers => {'Content-type' => 'text/xml'} )
response
end | ruby | def add_work_item_to(issue_id, attributes={})
attributes = attributes.to_hash
attributes.symbolize_keys!
attributes[:date] ||= Date.current.iso8601
epoc_date = Date.parse(attributes[:date]).to_time.to_i * 1000
attributes[:user] ||= self.service.login
work_items = REXML::Element.new('workItems')
work_item = work_items.add_element('workItem')
work_item.add_element('author').add_attribute('login', attributes[:user])
work_item.add_element('date').add_text(epoc_date.to_s)
work_item.add_element('duration').add_text(attributes[:duration].to_s)
work_item.add_element('description').add_text(attributes[:description])
put("import/issue/#{issue_id}/workitems", body: work_items.to_s, :headers => {'Content-type' => 'text/xml'} )
response
end | [
"def",
"add_work_item_to",
"(",
"issue_id",
",",
"attributes",
"=",
"{",
"}",
")",
"attributes",
"=",
"attributes",
".",
"to_hash",
"attributes",
".",
"symbolize_keys!",
"attributes",
"[",
":date",
"]",
"||=",
"Date",
".",
"current",
".",
"iso8601",
"epoc_date",
"=",
"Date",
".",
"parse",
"(",
"attributes",
"[",
":date",
"]",
")",
".",
"to_time",
".",
"to_i",
"*",
"1000",
"attributes",
"[",
":user",
"]",
"||=",
"self",
".",
"service",
".",
"login",
"work_items",
"=",
"REXML",
"::",
"Element",
".",
"new",
"(",
"'workItems'",
")",
"work_item",
"=",
"work_items",
".",
"add_element",
"(",
"'workItem'",
")",
"work_item",
".",
"add_element",
"(",
"'author'",
")",
".",
"add_attribute",
"(",
"'login'",
",",
"attributes",
"[",
":user",
"]",
")",
"work_item",
".",
"add_element",
"(",
"'date'",
")",
".",
"add_text",
"(",
"epoc_date",
".",
"to_s",
")",
"work_item",
".",
"add_element",
"(",
"'duration'",
")",
".",
"add_text",
"(",
"attributes",
"[",
":duration",
"]",
".",
"to_s",
")",
"work_item",
".",
"add_element",
"(",
"'description'",
")",
".",
"add_text",
"(",
"attributes",
"[",
":description",
"]",
")",
"put",
"(",
"\"import/issue/#{issue_id}/workitems\"",
",",
"body",
":",
"work_items",
".",
"to_s",
",",
":headers",
"=>",
"{",
"'Content-type'",
"=>",
"'text/xml'",
"}",
")",
"response",
"end"
] | Add new work item to issue
issue_id string youtrack ticket id
attributes hash
user string login name of the user who will be set as the author of the work item. (defaults to logged in user)
date string date and time of the new work item in ISO8601 time format (defaults to current date)
duration string Duration of the work item in minutes
description string Activity description | [
"Add",
"new",
"work",
"item",
"to",
"issue"
] | d4288a803c74a59984d616e12f147c10a4a24bf2 | https://github.com/johnfaucett/youtrack/blob/d4288a803c74a59984d616e12f147c10a4a24bf2/lib/youtrack/resources/issue.rb#L138-L152 | train |
jrmehle/songkickr | lib/songkickr/setlist.rb | Songkickr.Setlist.parse_setlist_items | def parse_setlist_items(setlist_item_array = nil)
return [] unless setlist_item_array
setlist_item_array.inject([]) do |setlist_items, item|
setlist_items << Songkickr::SetlistItem.new(item)
end
end | ruby | def parse_setlist_items(setlist_item_array = nil)
return [] unless setlist_item_array
setlist_item_array.inject([]) do |setlist_items, item|
setlist_items << Songkickr::SetlistItem.new(item)
end
end | [
"def",
"parse_setlist_items",
"(",
"setlist_item_array",
"=",
"nil",
")",
"return",
"[",
"]",
"unless",
"setlist_item_array",
"setlist_item_array",
".",
"inject",
"(",
"[",
"]",
")",
"do",
"|",
"setlist_items",
",",
"item",
"|",
"setlist_items",
"<<",
"Songkickr",
"::",
"SetlistItem",
".",
"new",
"(",
"item",
")",
"end",
"end"
] | Takes the array of setlist items and create SetLists | [
"Takes",
"the",
"array",
"of",
"setlist",
"items",
"and",
"create",
"SetLists"
] | c32263da9fe32e25c65b797a5c9bcef0dd7182bd | https://github.com/jrmehle/songkickr/blob/c32263da9fe32e25c65b797a5c9bcef0dd7182bd/lib/songkickr/setlist.rb#L35-L40 | train |
ultraspeed/epp | lib/epp/server.rb | Epp.Server.get_frame | def get_frame
raise SocketError.new("Connection closed by remote server") if !@socket or @socket.eof?
header = @socket.read(4)
raise SocketError.new("Error reading frame from remote server") if header.nil?
length = header_size(header)
raise SocketError.new("Got bad frame header length of #{length} bytes from the server") if length < 5
return @socket.read(length - 4)
end | ruby | def get_frame
raise SocketError.new("Connection closed by remote server") if !@socket or @socket.eof?
header = @socket.read(4)
raise SocketError.new("Error reading frame from remote server") if header.nil?
length = header_size(header)
raise SocketError.new("Got bad frame header length of #{length} bytes from the server") if length < 5
return @socket.read(length - 4)
end | [
"def",
"get_frame",
"raise",
"SocketError",
".",
"new",
"(",
"\"Connection closed by remote server\"",
")",
"if",
"!",
"@socket",
"or",
"@socket",
".",
"eof?",
"header",
"=",
"@socket",
".",
"read",
"(",
"4",
")",
"raise",
"SocketError",
".",
"new",
"(",
"\"Error reading frame from remote server\"",
")",
"if",
"header",
".",
"nil?",
"length",
"=",
"header_size",
"(",
"header",
")",
"raise",
"SocketError",
".",
"new",
"(",
"\"Got bad frame header length of #{length} bytes from the server\"",
")",
"if",
"length",
"<",
"5",
"return",
"@socket",
".",
"read",
"(",
"length",
"-",
"4",
")",
"end"
] | Receive an EPP frame from the server. Since the connection is blocking,
this method will wait until the connection becomes available for use. If
the connection is broken, a SocketError will be raised. Otherwise,
it will return a string containing the XML from the server. | [
"Receive",
"an",
"EPP",
"frame",
"from",
"the",
"server",
".",
"Since",
"the",
"connection",
"is",
"blocking",
"this",
"method",
"will",
"wait",
"until",
"the",
"connection",
"becomes",
"available",
"for",
"use",
".",
"If",
"the",
"connection",
"is",
"broken",
"a",
"SocketError",
"will",
"be",
"raised",
".",
"Otherwise",
"it",
"will",
"return",
"a",
"string",
"containing",
"the",
"XML",
"from",
"the",
"server",
"."
] | e23cec53148d0de0418eb91221b4560c0325bb3f | https://github.com/ultraspeed/epp/blob/e23cec53148d0de0418eb91221b4560c0325bb3f/lib/epp/server.rb#L102-L114 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.